From 1436aea4d5707e672672a11bda72be2c63c936c3 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Sun, 5 Dec 2021 14:54:02 -0800 Subject: [PATCH] MdeModulePkg: Apply uncrustify changes REF: https://bugzilla.tianocore.org/show_bug.cgi?id=3737 Apply uncrustify changes to .c/.h files in the MdeModulePkg package Cc: Andrew Fish Cc: Leif Lindholm Cc: Michael D Kinney Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao --- .../BootManagerMenuApp/BootManagerMenu.c | 416 +- .../BootManagerMenuApp/BootManagerMenu.h | 22 +- .../Application/CapsuleApp/AppSupport.c | 76 +- .../Application/CapsuleApp/CapsuleApp.c | 516 +-- .../Application/CapsuleApp/CapsuleApp.h | 50 +- .../Application/CapsuleApp/CapsuleDump.c | 843 ++-- .../Application/CapsuleApp/CapsuleOnDisk.c | 333 +- .../Application/DumpDynPcd/DumpDynPcd.c | 223 +- .../Application/HelloWorld/HelloWorld.c | 8 +- .../MemoryProfileInfo/MemoryProfileInfo.c | 614 +-- .../SmiHandlerProfileInfo.c | 373 +- MdeModulePkg/Application/UiApp/FrontPage.c | 328 +- MdeModulePkg/Application/UiApp/FrontPage.h | 61 +- .../Application/UiApp/FrontPageCustomizedUi.c | 36 +- .../Application/UiApp/FrontPageCustomizedUi.h | 18 +- .../UiApp/FrontPageCustomizedUiSupport.c | 301 +- .../UiApp/FrontPageCustomizedUiSupport.h | 40 +- MdeModulePkg/Application/UiApp/String.c | 36 +- MdeModulePkg/Application/UiApp/String.h | 4 +- MdeModulePkg/Application/UiApp/Ui.h | 11 +- .../Application/VariableInfo/VariableInfo.c | 132 +- MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c | 803 ++-- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c | 97 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h | 336 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c | 94 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.h | 2 +- .../Bus/Ata/AhciPei/AhciPeiPassThru.c | 111 +- .../Bus/Ata/AhciPei/AhciPeiPassThru.h | 24 +- MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c | 39 +- .../Bus/Ata/AhciPei/AhciPeiStorageSecurity.c | 58 +- .../Bus/Ata/AhciPei/AhciPeiStorageSecurity.h | 28 +- MdeModulePkg/Bus/Ata/AhciPei/DevicePath.c | 66 +- MdeModulePkg/Bus/Ata/AhciPei/DmaMem.c | 118 +- .../Bus/Ata/AtaAtapiPassThru/AhciMode.c | 1039 ++--- .../Bus/Ata/AtaAtapiPassThru/AhciMode.h | 414 +- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.c | 591 +-- .../Ata/AtaAtapiPassThru/AtaAtapiPassThru.h | 346 +- .../Bus/Ata/AtaAtapiPassThru/ComponentName.c | 31 +- .../Bus/Ata/AtaAtapiPassThru/IdeMode.c | 590 +-- .../Bus/Ata/AtaAtapiPassThru/IdeMode.h | 68 +- MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c | 498 ++- MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h | 279 +- .../Bus/Ata/AtaBusDxe/AtaPassThruExecute.c | 325 +- .../Bus/Ata/AtaBusDxe/ComponentName.c | 35 +- MdeModulePkg/Bus/I2c/I2cDxe/I2cBus.c | 437 +- MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.c | 27 +- MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.h | 174 +- MdeModulePkg/Bus/I2c/I2cDxe/I2cHost.c | 215 +- .../Bus/Isa/IsaBusDxe/ComponentName.c | 21 +- .../Bus/Isa/IsaBusDxe/ComponentName.h | 15 +- MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.c | 130 +- MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.h | 12 +- .../Bus/Isa/Ps2KeyboardDxe/ComponentName.c | 42 +- .../Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c | 559 +-- .../Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c | 159 +- .../Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.c | 160 +- .../Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h | 247 +- MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.c | 255 +- MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.h | 88 +- .../Bus/Isa/Ps2MouseDxe/ComponentName.c | 29 +- MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.c | 185 +- MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.h | 77 +- MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.c | 34 +- MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.h | 13 +- MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c | 923 ++--- MdeModulePkg/Bus/Pci/EhciDxe/Ehci.h | 114 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.c | 50 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.h | 18 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.c | 169 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.h | 157 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c | 381 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.h | 72 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.c | 321 +- MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.h | 301 +- MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.c | 172 +- MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.h | 49 +- MdeModulePkg/Bus/Pci/EhciPei/DmaMem.c | 89 +- MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.c | 592 +-- MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.h | 116 +- MdeModulePkg/Bus/Pci/EhciPei/EhciReg.h | 127 +- MdeModulePkg/Bus/Pci/EhciPei/EhciSched.c | 142 +- MdeModulePkg/Bus/Pci/EhciPei/EhciSched.h | 18 +- MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c | 297 +- MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.h | 300 +- MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.c | 247 +- MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.h | 31 +- MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.c | 912 ++--- MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.h | 210 +- .../IncompatiblePciDeviceSupport.c | 260 +- .../ComponentName.c | 30 +- .../NonDiscoverablePciDeviceDxe.c | 143 +- .../NonDiscoverablePciDeviceIo.c | 929 +++-- .../NonDiscoverablePciDeviceIo.h | 42 +- .../Bus/Pci/NvmExpressDxe/ComponentName.c | 47 +- .../Bus/Pci/NvmExpressDxe/NvmExpress.c | 345 +- .../Bus/Pci/NvmExpressDxe/NvmExpress.h | 187 +- .../Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c | 629 +-- .../Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h | 82 +- .../Pci/NvmExpressDxe/NvmExpressDiskInfo.c | 39 +- .../Pci/NvmExpressDxe/NvmExpressDiskInfo.h | 30 +- .../Bus/Pci/NvmExpressDxe/NvmExpressHci.c | 386 +- .../Bus/Pci/NvmExpressDxe/NvmExpressHci.h | 17 +- .../Pci/NvmExpressDxe/NvmExpressPassthru.c | 320 +- .../Bus/Pci/NvmExpressPei/DevicePath.c | 66 +- MdeModulePkg/Bus/Pci/NvmExpressPei/DmaMem.c | 118 +- .../Bus/Pci/NvmExpressPei/NvmExpressPei.c | 148 +- .../Bus/Pci/NvmExpressPei/NvmExpressPei.h | 137 +- .../Pci/NvmExpressPei/NvmExpressPeiBlockIo.c | 134 +- .../Pci/NvmExpressPei/NvmExpressPeiBlockIo.h | 4 +- .../Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c | 204 +- .../Bus/Pci/NvmExpressPei/NvmExpressPeiHci.h | 39 +- .../Pci/NvmExpressPei/NvmExpressPeiPassThru.c | 191 +- .../Pci/NvmExpressPei/NvmExpressPeiPassThru.h | 24 +- .../Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c | 27 +- .../NvmExpressPeiStorageSecurity.c | 60 +- .../NvmExpressPeiStorageSecurity.h | 4 +- .../Bus/Pci/PciBusDxe/ComponentName.c | 23 +- .../Bus/Pci/PciBusDxe/ComponentName.h | 14 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c | 145 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h | 257 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c | 67 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h | 42 +- .../Bus/Pci/PciBusDxe/PciDeviceSupport.c | 214 +- .../Bus/Pci/PciBusDxe/PciDeviceSupport.h | 54 +- .../Bus/Pci/PciBusDxe/PciDriverOverride.c | 49 +- .../Bus/Pci/PciBusDxe/PciDriverOverride.h | 25 +- .../Bus/Pci/PciBusDxe/PciEnumerator.c | 730 ++-- .../Bus/Pci/PciBusDxe/PciEnumerator.h | 100 +- .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 1268 +++--- .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.h | 138 +- .../Bus/Pci/PciBusDxe/PciHotPlugSupport.c | 121 +- .../Bus/Pci/PciBusDxe/PciHotPlugSupport.h | 42 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c | 680 ++-- MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h | 77 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c | 629 +-- MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h | 46 +- .../Bus/Pci/PciBusDxe/PciOptionRomSupport.c | 246 +- .../Bus/Pci/PciBusDxe/PciOptionRomSupport.h | 33 +- .../Bus/Pci/PciBusDxe/PciPowerManagement.c | 14 +- .../Bus/Pci/PciBusDxe/PciPowerManagement.h | 2 +- .../Bus/Pci/PciBusDxe/PciResourceSupport.c | 1519 ++++--- .../Bus/Pci/PciBusDxe/PciResourceSupport.h | 180 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c | 55 +- MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h | 2 +- .../Bus/Pci/PciHostBridgeDxe/PciHostBridge.c | 1328 +++--- .../Bus/Pci/PciHostBridgeDxe/PciHostBridge.h | 81 +- .../Pci/PciHostBridgeDxe/PciHostResource.h | 15 +- .../Bus/Pci/PciHostBridgeDxe/PciRootBridge.h | 82 +- .../Pci/PciHostBridgeDxe/PciRootBridgeIo.c | 594 +-- .../Bus/Pci/PciSioSerialDxe/ComponentName.c | 51 +- MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c | 669 +-- MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.h | 398 +- .../Bus/Pci/PciSioSerialDxe/SerialIo.c | 472 ++- .../Bus/Pci/SataControllerDxe/ComponentName.c | 41 +- .../Pci/SataControllerDxe/SataController.c | 203 +- .../Pci/SataControllerDxe/SataController.h | 134 +- .../Bus/Pci/SdMmcPciHcDxe/ComponentName.c | 36 +- .../Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c | 435 +- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c | 395 +- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c | 365 +- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h | 271 +- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 845 ++-- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h | 284 +- .../Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.c | 66 +- .../Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.h | 36 +- .../Bus/Pci/UfsPciHcDxe/ComponentName.c | 33 +- .../Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.c | 145 +- .../Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h | 70 +- .../Bus/Pci/UfsPciHcPei/UfsPciHcPei.c | 25 +- .../Bus/Pci/UfsPciHcPei/UfsPciHcPei.h | 20 +- MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.c | 32 +- MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.h | 11 +- MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c | 858 ++-- MdeModulePkg/Bus/Pci/UhciDxe/Uhci.h | 86 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.c | 43 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.h | 6 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.c | 320 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.h | 132 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.c | 93 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.h | 140 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c | 293 +- MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.h | 89 +- MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c | 170 +- MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.h | 51 +- MdeModulePkg/Bus/Pci/UhciPei/DmaMem.c | 83 +- MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c | 1210 +++--- MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.h | 541 ++- MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.c | 19 +- MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.h | 2 - MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c | 243 +- MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h | 63 +- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c | 866 ++-- MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h | 193 +- MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c | 197 +- MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h | 356 +- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c | 1270 +++--- MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h | 1148 +++--- MdeModulePkg/Bus/Pci/XhciPei/DmaMem.c | 127 +- MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c | 204 +- MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h | 58 +- MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.c | 558 +-- MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.h | 135 +- MdeModulePkg/Bus/Pci/XhciPei/XhciReg.h | 324 +- MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c | 1038 ++--- MdeModulePkg/Bus/Pci/XhciPei/XhciSched.h | 1082 +++-- .../Bus/Scsi/ScsiBusDxe/ComponentName.c | 24 +- MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c | 413 +- MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h | 79 +- .../Bus/Scsi/ScsiDiskDxe/ComponentName.c | 34 +- MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c | 2359 +++++------ MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h | 541 ++- MdeModulePkg/Bus/Sd/EmmcBlockIoPei/DmaMem.c | 85 +- .../Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.c | 222 +- .../Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.h | 126 +- .../Bus/Sd/EmmcBlockIoPei/EmmcHcMem.c | 142 +- .../Bus/Sd/EmmcBlockIoPei/EmmcHcMem.h | 23 +- MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.c | 846 ++-- MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.h | 161 +- MdeModulePkg/Bus/Sd/EmmcDxe/ComponentName.c | 33 +- MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c | 615 +-- MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h | 101 +- MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDiskInfo.c | 6 +- MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.c | 483 ++- MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.h | 163 +- MdeModulePkg/Bus/Sd/SdBlockIoPei/DmaMem.c | 85 +- .../Bus/Sd/SdBlockIoPei/SdBlockIoPei.c | 167 +- .../Bus/Sd/SdBlockIoPei/SdBlockIoPei.h | 118 +- MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.c | 142 +- MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.h | 23 +- MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.c | 862 ++-- MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.h | 173 +- MdeModulePkg/Bus/Sd/SdDxe/ComponentName.c | 31 +- MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.c | 336 +- MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.h | 53 +- MdeModulePkg/Bus/Sd/SdDxe/SdDiskInfo.c | 4 +- MdeModulePkg/Bus/Sd/SdDxe/SdDxe.c | 304 +- MdeModulePkg/Bus/Sd/SdDxe/SdDxe.h | 135 +- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c | 85 +- .../Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c | 285 +- .../Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h | 152 +- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c | 138 +- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.h | 21 +- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c | 512 ++- MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.h | 1137 +++--- .../Bus/Ufs/UfsPassThruDxe/ComponentName.c | 25 +- .../Ufs/UfsPassThruDxe/UfsDevConfigProtocol.c | 55 +- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.c | 326 +- .../Bus/Ufs/UfsPassThruDxe/UfsPassThru.h | 259 +- .../Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.c | 630 +-- .../Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.h | 1137 +++--- MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.c | 216 +- MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.h | 37 +- MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c | 351 +- MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c | 68 +- MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.h | 85 +- MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.c | 366 +- MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.h | 112 +- MdeModulePkg/Bus/Usb/UsbBotPei/UsbPeim.h | 1 - .../Bus/Usb/UsbBusDxe/ComponentName.c | 36 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c | 541 +-- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.h | 239 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c | 366 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.h | 76 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c | 332 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.h | 58 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c | 393 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.h | 116 +- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.c | 496 ++- MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.h | 36 +- MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.c | 196 +- MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.h | 117 +- MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.c | 57 +- MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.h | 106 +- MdeModulePkg/Bus/Usb/UsbBusPei/UsbIoPeim.c | 215 +- MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.c | 533 +-- MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.h | 123 +- MdeModulePkg/Bus/Usb/UsbKbDxe/ComponentName.c | 37 +- MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c | 294 +- MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h | 231 +- MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.c | 861 ++-- MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.h | 91 +- .../Bus/Usb/UsbMassStorageDxe/ComponentName.c | 23 +- .../Bus/Usb/UsbMassStorageDxe/UsbMass.h | 65 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassBoot.c | 431 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassBoot.h | 217 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassBot.c | 136 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassBot.h | 74 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassCbi.c | 197 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassCbi.h | 36 +- .../Usb/UsbMassStorageDxe/UsbMassDiskInfo.c | 41 +- .../Usb/UsbMassStorageDxe/UsbMassDiskInfo.h | 30 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassImpl.c | 242 +- .../Bus/Usb/UsbMassStorageDxe/UsbMassImpl.h | 46 +- .../ComponentName.c | 38 +- .../Usb/UsbMouseAbsolutePointerDxe/MouseHid.c | 192 +- .../UsbMouseAbsolutePointer.c | 226 +- .../UsbMouseAbsolutePointer.h | 139 +- .../Bus/Usb/UsbMouseDxe/ComponentName.c | 38 +- MdeModulePkg/Bus/Usb/UsbMouseDxe/MouseHid.c | 194 +- MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c | 226 +- MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.h | 143 +- MdeModulePkg/Core/Dxe/Dispatcher/Dependency.c | 335 +- MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c | 514 ++- MdeModulePkg/Core/Dxe/DxeMain.h | 705 ++-- MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c | 418 +- .../Core/Dxe/DxeMain/DxeProtocolNotify.c | 74 +- MdeModulePkg/Core/Dxe/Event/Event.c | 165 +- MdeModulePkg/Core/Dxe/Event/Event.h | 45 +- MdeModulePkg/Core/Dxe/Event/Timer.c | 52 +- MdeModulePkg/Core/Dxe/Event/Tpl.c | 31 +- MdeModulePkg/Core/Dxe/FwVol/Ffs.c | 103 +- MdeModulePkg/Core/Dxe/FwVol/FwVol.c | 221 +- MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c | 39 +- MdeModulePkg/Core/Dxe/FwVol/FwVolDriver.h | 105 +- MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c | 172 +- MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c | 3 - MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c | 204 +- MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.h | 45 +- MdeModulePkg/Core/Dxe/Gcd/Gcd.c | 998 ++--- MdeModulePkg/Core/Dxe/Gcd/Gcd.h | 18 +- MdeModulePkg/Core/Dxe/Hand/DriverSupport.c | 209 +- MdeModulePkg/Core/Dxe/Hand/Handle.c | 556 ++- MdeModulePkg/Core/Dxe/Hand/Handle.h | 111 +- MdeModulePkg/Core/Dxe/Hand/Locate.c | 293 +- MdeModulePkg/Core/Dxe/Hand/Notify.c | 68 +- MdeModulePkg/Core/Dxe/Image/Image.c | 851 ++-- MdeModulePkg/Core/Dxe/Image/Image.h | 11 +- MdeModulePkg/Core/Dxe/Library/Library.c | 10 +- MdeModulePkg/Core/Dxe/Mem/HeapGuard.c | 621 +-- MdeModulePkg/Core/Dxe/Mem/HeapGuard.h | 76 +- MdeModulePkg/Core/Dxe/Mem/Imem.h | 66 +- MdeModulePkg/Core/Dxe/Mem/MemData.c | 5 +- .../Core/Dxe/Mem/MemoryProfileRecord.c | 611 +-- MdeModulePkg/Core/Dxe/Mem/Page.c | 687 ++-- MdeModulePkg/Core/Dxe/Mem/Pool.c | 368 +- MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c | 52 +- .../Core/Dxe/Misc/InstallConfigurationTable.c | 20 +- .../Core/Dxe/Misc/MemoryAttributesTable.c | 534 +-- MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c | 503 +-- MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c | 10 +- MdeModulePkg/Core/Dxe/Misc/Stall.c | 6 +- .../SectionExtraction/CoreSectionExtraction.c | 466 +-- .../Core/DxeIplPeim/Arm/DxeLoadFunc.c | 14 +- MdeModulePkg/Core/DxeIplPeim/DxeIpl.h | 41 +- MdeModulePkg/Core/DxeIplPeim/DxeLoad.c | 359 +- .../Core/DxeIplPeim/Ebc/DxeLoadFunc.c | 16 +- .../Core/DxeIplPeim/Ia32/DxeLoadFunc.c | 198 +- .../Core/DxeIplPeim/RiscV64/DxeLoadFunc.c | 25 +- .../Core/DxeIplPeim/X64/DxeLoadFunc.c | 45 +- .../Core/DxeIplPeim/X64/VirtualMemory.c | 382 +- .../Core/DxeIplPeim/X64/VirtualMemory.h | 215 +- MdeModulePkg/Core/Pei/BootMode/BootMode.c | 23 +- MdeModulePkg/Core/Pei/CpuIo/CpuIo.c | 162 +- MdeModulePkg/Core/Pei/Dependency/Dependency.c | 31 +- MdeModulePkg/Core/Pei/Dependency/Dependency.h | 5 +- MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c | 896 +++-- MdeModulePkg/Core/Pei/FwVol/FwVol.c | 923 +++-- MdeModulePkg/Core/Pei/FwVol/FwVol.h | 96 +- MdeModulePkg/Core/Pei/Hob/Hob.c | 121 +- MdeModulePkg/Core/Pei/Image/Image.c | 635 +-- MdeModulePkg/Core/Pei/Memory/MemoryServices.c | 309 +- MdeModulePkg/Core/Pei/PciCfg2/PciCfg2.c | 34 +- MdeModulePkg/Core/Pei/PeiMain.h | 626 +-- MdeModulePkg/Core/Pei/PeiMain/PeiMain.c | 163 +- MdeModulePkg/Core/Pei/Ppi/Ppi.c | 353 +- MdeModulePkg/Core/Pei/Reset/Reset.c | 2 +- MdeModulePkg/Core/Pei/Security/Security.c | 33 +- MdeModulePkg/Core/Pei/StatusCode/StatusCode.c | 39 +- MdeModulePkg/Core/PiSmmCore/Dependency.c | 288 +- MdeModulePkg/Core/PiSmmCore/Dispatcher.c | 637 +-- MdeModulePkg/Core/PiSmmCore/Handle.c | 58 +- MdeModulePkg/Core/PiSmmCore/HeapGuard.c | 602 +-- MdeModulePkg/Core/PiSmmCore/HeapGuard.h | 66 +- .../PiSmmCore/InstallConfigurationTable.c | 5 +- MdeModulePkg/Core/PiSmmCore/Locate.c | 166 +- .../Core/PiSmmCore/MemoryAttributesTable.c | 521 +-- MdeModulePkg/Core/PiSmmCore/Notify.c | 42 +- MdeModulePkg/Core/PiSmmCore/Page.c | 236 +- MdeModulePkg/Core/PiSmmCore/PiSmmCore.c | 286 +- MdeModulePkg/Core/PiSmmCore/PiSmmCore.h | 398 +- .../Core/PiSmmCore/PiSmmCorePrivateData.h | 28 +- MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c | 465 ++- MdeModulePkg/Core/PiSmmCore/Pool.c | 135 +- MdeModulePkg/Core/PiSmmCore/Smi.c | 150 +- .../Core/PiSmmCore/SmiHandlerProfile.c | 605 +-- .../Core/PiSmmCore/SmramProfileRecord.c | 1141 +++--- MdeModulePkg/Core/RuntimeDxe/Crc32.c | 3 +- MdeModulePkg/Core/RuntimeDxe/Runtime.c | 105 +- MdeModulePkg/Core/RuntimeDxe/Runtime.h | 6 +- MdeModulePkg/Include/Guid/AcpiS3Context.h | 59 +- .../Include/Guid/BootDiscoveryPolicy.h | 10 +- .../Include/Guid/BootScriptExecutorVariable.h | 6 +- MdeModulePkg/Include/Guid/CapsuleVendor.h | 16 +- MdeModulePkg/Include/Guid/ConnectConInEvent.h | 2 +- MdeModulePkg/Include/Guid/ConsoleInDevice.h | 2 +- MdeModulePkg/Include/Guid/ConsoleOutDevice.h | 2 +- .../Guid/Crc32GuidedSectionExtraction.h | 2 +- MdeModulePkg/Include/Guid/DebugMask.h | 18 +- MdeModulePkg/Include/Guid/DriverSampleHii.h | 6 +- MdeModulePkg/Include/Guid/EndOfS3Resume.h | 2 +- .../Include/Guid/EventExitBootServiceFailed.h | 2 +- .../Guid/ExtendedFirmwarePerformance.h | 120 +- .../Include/Guid/FaultTolerantWrite.h | 8 +- .../Include/Guid/FirmwarePerformance.h | 46 +- .../Include/Guid/HiiBootMaintenanceFormset.h | 4 +- .../Include/Guid/HiiResourceSampleHii.h | 2 +- MdeModulePkg/Include/Guid/IdleLoopEvent.h | 2 +- .../Include/Guid/LoadModuleAtFixedAddress.h | 3 +- MdeModulePkg/Include/Guid/LzmaDecompress.h | 4 +- MdeModulePkg/Include/Guid/MdeModuleHii.h | 123 +- .../Include/Guid/MdeModulePkgTokenSpace.h | 2 +- MdeModulePkg/Include/Guid/MemoryProfile.h | 228 +- .../Include/Guid/MemoryStatusCodeRecord.h | 20 +- .../Include/Guid/MemoryTypeInformation.h | 8 +- MdeModulePkg/Include/Guid/MigratedFvInfo.h | 11 +- MdeModulePkg/Include/Guid/MtcVendor.h | 4 +- .../Include/Guid/NonDiscoverableDevice.h | 19 +- .../Include/Guid/PcdDataBaseHobGuid.h | 2 +- .../Include/Guid/PcdDataBaseSignatureGuid.h | 150 +- MdeModulePkg/Include/Guid/Performance.h | 129 +- .../Include/Guid/PerformanceMeasurement.h | 6 +- .../Guid/PiSmmCommunicationRegionTable.h | 14 +- .../Include/Guid/PiSmmMemoryAttributesTable.h | 14 +- .../Include/Guid/PlatDriOverrideHii.h | 2 +- MdeModulePkg/Include/Guid/PlatformHasAcpi.h | 3 +- MdeModulePkg/Include/Guid/RamDiskHii.h | 2 +- MdeModulePkg/Include/Guid/RecoveryDevice.h | 10 +- MdeModulePkg/Include/Guid/S3SmmInitDone.h | 2 +- .../Include/Guid/S3StorageDeviceInitList.h | 2 +- .../Include/Guid/SerialPortLibVendor.h | 4 +- MdeModulePkg/Include/Guid/SmiHandlerProfile.h | 94 +- MdeModulePkg/Include/Guid/SmmLockBox.h | 52 +- MdeModulePkg/Include/Guid/SmmVariableCommon.h | 68 +- .../Include/Guid/StandardErrorDevice.h | 2 +- .../Include/Guid/StatusCodeCallbackGuid.h | 2 +- .../Include/Guid/StatusCodeDataTypeDebug.h | 6 +- .../Include/Guid/StatusCodeDataTypeVariable.h | 12 +- MdeModulePkg/Include/Guid/SystemNvDataGuid.h | 56 +- MdeModulePkg/Include/Guid/TtyTerm.h | 10 +- MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h | 28 +- MdeModulePkg/Include/Guid/VarErrorFlag.h | 13 +- MdeModulePkg/Include/Guid/VariableFormat.h | 80 +- .../Include/Guid/VariableIndexTable.h | 20 +- MdeModulePkg/Include/Guid/ZeroGuid.h | 2 +- .../Include/Library/AuthVariableLib.h | 58 +- MdeModulePkg/Include/Library/BootLogoLib.h | 13 +- MdeModulePkg/Include/Library/CapsuleLib.h | 16 +- .../Include/Library/CpuExceptionHandlerLib.h | 46 +- .../Include/Library/CustomizedDisplayLib.h | 49 +- MdeModulePkg/Include/Library/DebugAgentLib.h | 33 +- .../Include/Library/FmpAuthenticationLib.h | 2 - MdeModulePkg/Include/Library/HiiLib.h | 12 +- MdeModulePkg/Include/Library/IpmiLib.h | 13 +- MdeModulePkg/Include/Library/LockBoxLib.h | 28 +- .../Include/Library/MemoryProfileLib.h | 12 +- .../Include/Library/OemHookStatusCodeLib.h | 10 +- .../Include/Library/PciHostBridgeLib.h | 69 +- .../Include/Library/PlatformBootManagerLib.h | 3 +- .../Include/Library/PlatformHookLib.h | 1 - .../Include/Library/PlatformVarCleanupLib.h | 5 +- MdeModulePkg/Include/Library/ResetSystemLib.h | 12 +- .../Include/Library/ResetUtilityLib.h | 19 +- .../Include/Library/SecurityManagementLib.h | 34 +- .../Include/Library/SmmCorePlatformHookLib.h | 1 - MdeModulePkg/Include/Library/SortLib.h | 22 +- .../Include/Library/TpmMeasurementLib.h | 12 +- .../Include/Library/UefiBootManagerLib.h | 157 +- MdeModulePkg/Include/Library/VarCheckLib.h | 36 +- .../Include/Library/VariablePolicyHelperLib.h | 39 +- .../Include/Library/VariablePolicyLib.h | 28 +- MdeModulePkg/Include/Ppi/AtaAhciController.h | 8 +- MdeModulePkg/Include/Ppi/AtaController.h | 22 +- MdeModulePkg/Include/Ppi/AtaPassThru.h | 15 +- MdeModulePkg/Include/Ppi/CapsuleOnDisk.h | 6 +- MdeModulePkg/Include/Ppi/Debug.h | 7 +- MdeModulePkg/Include/Ppi/IoMmu.h | 19 +- MdeModulePkg/Include/Ppi/IpmiPpi.h | 8 +- .../Include/Ppi/NvmExpressHostController.h | 8 +- MdeModulePkg/Include/Ppi/NvmExpressPassThru.h | 19 +- .../Include/Ppi/PlatformSpecificResetFilter.h | 4 +- .../Ppi/PlatformSpecificResetHandler.h | 4 +- .../Ppi/PlatformSpecificResetNotification.h | 4 +- .../Include/Ppi/PostBootScriptTable.h | 2 +- .../Include/Ppi/SdMmcHostController.h | 8 +- MdeModulePkg/Include/Ppi/SecPerformance.h | 8 +- MdeModulePkg/Include/Ppi/SerialPortPei.h | 2 +- MdeModulePkg/Include/Ppi/SmmAccess.h | 16 +- MdeModulePkg/Include/Ppi/SmmCommunication.h | 7 +- MdeModulePkg/Include/Ppi/SmmControl.h | 17 +- .../Include/Ppi/StorageSecurityCommand.h | 13 +- MdeModulePkg/Include/Ppi/UfsHostController.h | 8 +- MdeModulePkg/Include/Ppi/Usb2HostController.h | 15 +- MdeModulePkg/Include/Ppi/UsbController.h | 12 +- MdeModulePkg/Include/Ppi/UsbHostController.h | 15 +- MdeModulePkg/Include/Ppi/UsbIo.h | 14 +- .../Include/Protocol/AtaAtapiPolicy.h | 17 +- MdeModulePkg/Include/Protocol/BootLogo.h | 6 +- MdeModulePkg/Include/Protocol/BootLogo2.h | 4 +- .../Include/Protocol/DebuggerConfiguration.h | 6 +- .../Include/Protocol/DeviceSecurity.h | 23 +- .../Include/Protocol/DisplayProtocol.h | 162 +- .../Include/Protocol/EbcSimpleDebugger.h | 18 +- MdeModulePkg/Include/Protocol/EbcVmTest.h | 76 +- .../Include/Protocol/EsrtManagement.h | 23 +- .../Include/Protocol/FaultTolerantWrite.h | 32 +- MdeModulePkg/Include/Protocol/FileExplorer.h | 8 +- .../Protocol/FirmwareManagementProgress.h | 8 +- MdeModulePkg/Include/Protocol/FormBrowserEx.h | 45 +- .../Include/Protocol/FormBrowserEx2.h | 61 +- .../Include/Protocol/GenericMemoryTest.h | 16 +- MdeModulePkg/Include/Protocol/IoMmu.h | 29 +- MdeModulePkg/Include/Protocol/IpmiProtocol.h | 13 +- MdeModulePkg/Include/Protocol/LoadPe32Image.h | 9 +- MdeModulePkg/Include/Protocol/LockBox.h | 2 +- .../Include/Protocol/NonDiscoverableDevice.h | 12 +- .../Include/Protocol/PeCoffImageEmulator.h | 10 +- .../Include/Protocol/PlatformBootManager.h | 10 +- MdeModulePkg/Include/Protocol/PlatformLogo.h | 14 +- .../Protocol/PlatformSpecificResetFilter.h | 4 +- .../Protocol/PlatformSpecificResetHandler.h | 4 +- MdeModulePkg/Include/Protocol/Print2.h | 49 +- MdeModulePkg/Include/Protocol/Ps2Policy.h | 15 +- MdeModulePkg/Include/Protocol/SdMmcOverride.h | 28 +- .../Include/Protocol/SmmExitBootServices.h | 2 +- .../Include/Protocol/SmmFaultTolerantWrite.h | 2 +- .../Include/Protocol/SmmFirmwareVolumeBlock.h | 2 +- MdeModulePkg/Include/Protocol/SmmLegacyBoot.h | 2 +- .../Include/Protocol/SmmMemoryAttribute.h | 10 +- .../Include/Protocol/SmmReadyToBoot.h | 2 +- .../Include/Protocol/SmmSwapAddressRange.h | 2 +- MdeModulePkg/Include/Protocol/SmmVarCheck.h | 9 +- MdeModulePkg/Include/Protocol/SmmVariable.h | 12 +- .../Include/Protocol/SwapAddressRange.h | 20 +- .../Include/Protocol/UfsHostController.h | 32 +- .../Protocol/UfsHostControllerPlatform.h | 41 +- MdeModulePkg/Include/Protocol/VarCheck.h | 39 +- MdeModulePkg/Include/Protocol/VariableLock.h | 9 +- .../Include/Protocol/VariablePolicy.h | 52 +- .../Include/UniversalPayload/AcpiTable.h | 8 +- .../Include/UniversalPayload/ExtraData.h | 17 +- .../Include/UniversalPayload/PciRootBridges.h | 72 +- .../Include/UniversalPayload/SerialPortInfo.h | 14 +- .../Include/UniversalPayload/SmbiosTable.h | 10 +- .../UniversalPayload/UniversalPayload.h | 36 +- .../AuthVariableLibNull/AuthVariableLibNull.c | 10 +- .../Library/BaseBmpSupportLib/BmpSupportLib.c | 244 +- .../Library/BaseHobLibNull/BaseHobLibNull.c | 78 +- .../Library/BaseIpmiLibNull/BaseIpmiLibNull.c | 13 +- .../BaseMemoryAllocationLibNull.c | 4 +- .../BasePlatformHookLibNull.c | 3 +- .../BaseResetSystemLibNull.c | 13 +- .../BaseSerialPortLib16550.c | 211 +- .../Library/BaseSortLib/BaseSortLib.c | 39 +- .../BootDiscoveryPolicyUiLib.c | 23 +- .../Library/BootLogoLib/BootLogoLib.c | 307 +- .../BootMaintenanceManagerUiLib/BmLib.c | 12 +- .../BootMaintenance.c | 730 ++-- .../BootMaintenanceManager.h | 467 +-- .../BootMaintenanceManagerCustomizedUi.c | 20 +- .../BootMaintenanceManagerCustomizedUi.h | 13 +- ...ootMaintenanceManagerCustomizedUiSupport.c | 178 +- ...ootMaintenanceManagerCustomizedUiSupport.h | 40 +- .../BootMaintenanceManagerUiLib/BootOption.c | 480 +-- .../ConsoleOption.c | 357 +- .../BootMaintenanceManagerUiLib/Data.c | 134 +- .../BootMaintenanceManagerUiLib/FormGuid.h | 166 +- .../BootMaintenanceManagerUiLib/UpdatePage.c | 449 ++- .../BootMaintenanceManagerUiLib/Variable.c | 220 +- .../Library/BootManagerUiLib/BootManager.c | 267 +- .../Library/BootManagerUiLib/BootManager.h | 48 +- .../BrotliDecUefiSupport.c | 4 +- .../BrotliDecUefiSupport.h | 34 +- .../BrotliDecompress.c | 185 +- .../BrotliDecompressLibInternal.h | 11 +- .../GuidedSectionExtraction.c | 56 +- .../CpuExceptionHandlerLibNull.c | 17 +- .../Library/CustomizedDisplayLib/Colors.h | 40 +- .../CustomizedDisplayLib.c | 500 +-- .../CustomizedDisplayLibInternal.c | 463 +-- .../CustomizedDisplayLibInternal.h | 110 +- .../DebugAgentLibNull/DebugAgentLibNull.c | 2 +- .../DeviceManagerUiLib/DeviceManager.c | 388 +- .../DeviceManagerUiLib/DeviceManager.h | 74 +- .../DisplayUpdateProgressLibGraphics.c | 20 +- .../DisplayUpdateProgressLibText.c | 8 +- .../Library/DxeCapsuleLibFmp/CapsuleOnDisk.c | 1005 ++--- .../Library/DxeCapsuleLibFmp/CapsuleOnDisk.h | 20 +- .../Library/DxeCapsuleLibFmp/DxeCapsuleLib.c | 736 ++-- .../DxeCapsuleLibFmp/DxeCapsuleProcessLib.c | 240 +- .../DxeCapsuleLibFmp/DxeCapsuleReportLib.c | 219 +- .../DxeCapsuleReportLibNull.c | 4 +- .../DxeCapsuleLibFmp/DxeCapsuleRuntime.c | 42 +- .../DxeCapsuleLibNull/DxeCapsuleLibNull.c | 15 +- .../DxeCoreMemoryAllocationServices.h | 16 +- .../DxeCoreMemoryProfileLib.c | 14 +- .../DxeCoreMemoryProfileLibNull.c | 14 +- .../MemoryAllocationLib.c | 97 +- .../DxeCorePerformanceLib.c | 919 +++-- .../DxeCorePerformanceLibInternal.h | 3 +- .../DxeCrc32GuidedSectionExtractLib.c | 76 +- .../DxeDebugPrintErrorLevelLib.c | 57 +- .../DxeFileExplorerProtocol.c | 10 +- .../DxeIpmiLibIpmiProtocol.c | 23 +- .../DxePerformanceLib/DxePerformanceLib.c | 59 +- .../DxePrintLibPrint2Protocol/PrintLib.c | 1118 ++--- .../ReportStatusCodeLib.c | 59 +- .../DxeResetSystemLib/DxeResetSystemLib.c | 12 +- .../UnitTest/DxeResetSystemLibUnitTest.c | 22 +- .../DxeSecurityManagementLib.c | 138 +- .../Library/FileExplorerLib/FileExplorer.c | 569 +-- .../Library/FileExplorerLib/FileExplorer.h | 114 +- .../Library/FileExplorerLib/FormGuid.h | 5 +- .../FmpAuthenticationLibNull.c | 2 +- .../FrameBufferBltLib/FrameBufferBltLib.c | 500 +-- .../Library/LockBoxNullLib/LockBoxNullLib.c | 24 +- .../F86GuidedSectionExtraction.c | 83 +- .../GuidedSectionExtraction.c | 55 +- .../LzmaCustomDecompressLib/LzmaDecompress.c | 89 +- .../LzmaDecompressLibInternal.h | 1 - .../LzmaCustomDecompressLib/Sdk/C/7zTypes.h | 425 +- .../LzmaCustomDecompressLib/Sdk/C/7zVersion.h | 30 +- .../LzmaCustomDecompressLib/Sdk/C/Bra.h | 56 +- .../LzmaCustomDecompressLib/Sdk/C/Bra86.c | 81 +- .../LzmaCustomDecompressLib/Sdk/C/Compiler.h | 6 +- .../LzmaCustomDecompressLib/Sdk/C/CpuArch.h | 358 +- .../LzmaCustomDecompressLib/Sdk/C/LzFind.c | 1110 ++--- .../LzmaCustomDecompressLib/Sdk/C/LzFind.h | 260 +- .../LzmaCustomDecompressLib/Sdk/C/LzHash.h | 27 +- .../LzmaCustomDecompressLib/Sdk/C/LzmaDec.c | 1344 ++++--- .../LzmaCustomDecompressLib/Sdk/C/LzmaDec.h | 153 +- .../LzmaCustomDecompressLib/UefiLzma.h | 9 +- .../NonDiscoverableDeviceRegistrationLib.c | 114 +- .../OemHookStatusCodeLibNull.c | 11 +- .../PciHostBridgeLibNull.c | 63 +- .../PeiCrc32GuidedSectionExtractLib.c | 76 +- .../Library/PeiDebugLibDebugPpi/DebugLib.c | 91 +- .../PeiDebugPrintHobLib/PeiDebugPrintHobLib.c | 17 +- .../PeiDxeDebugLibReportStatusCode/DebugLib.c | 96 +- .../PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.c | 46 +- .../PeiPerformanceLib/PeiPerformanceLib.c | 384 +- .../ReportStatusCodeLib.c | 76 +- .../PeiResetSystemLib/PeiResetSystemLib.c | 12 +- .../PiDxeS3BootScriptLib/BootScriptExecute.c | 1196 +++--- .../BootScriptInternalFormat.h | 187 +- .../PiDxeS3BootScriptLib/BootScriptSave.c | 1244 +++--- .../InternalBootScriptLib.h | 50 +- .../MemoryAllocationLib.c | 108 +- .../PiSmmCoreMemoryAllocationServices.h | 48 +- .../PiSmmCoreMemoryProfileLib.c | 20 +- .../PiSmmCoreMemoryProfileLibNull.c | 13 +- .../PlatformBootManager.c | 4 +- .../PlatformVarCleanupLib/PlatVarCleanup.h | 62 +- .../PlatformVarCleanupLib/PlatVarCleanupHii.h | 26 +- .../PlatformVarCleanupLib/PlatVarCleanupLib.c | 388 +- .../Library/ResetUtilityLib/ResetUtility.c | 37 +- .../ReportStatusCodeLib.c | 79 +- .../RuntimeResetSystemLib.c | 30 +- .../SmmCorePerformanceLib.c | 612 +-- .../SmmCorePerformanceLibInternal.h | 4 +- .../SmmCorePlatformHookLibNull.c | 1 - .../SmmIpmiLibSmmIpmiProtocol.c | 23 +- .../Library/SmmLockBoxLib/SmmLockBoxDxeLib.c | 276 +- .../SmmLockBoxLib/SmmLockBoxLibPrivate.h | 25 +- .../Library/SmmLockBoxLib/SmmLockBoxMmLib.c | 158 +- .../Library/SmmLockBoxLib/SmmLockBoxPeiLib.c | 247 +- .../SmmLockBoxLib/SmmLockBoxStandaloneMmLib.c | 4 +- .../SmmLockBoxTraditionalMmLib.c | 4 +- .../MemoryAllocationLib.c | 104 +- .../SmmMemoryProfileLib.c | 23 +- .../SmmPerformanceLib/SmmPerformanceLib.c | 56 +- .../ReportStatusCodeLib.c | 66 +- .../MmSmiHandlerProfileLib.c | 22 +- .../SmmSmiHandlerProfileLib.c | 4 +- .../StandaloneMmSmiHandlerProfileLib.c | 1 - .../TpmMeasurementLibNull.c | 12 +- .../Library/UefiBootManagerLib/BmBoot.c | 837 ++-- .../UefiBootManagerLib/BmBootDescription.c | 468 ++- .../Library/UefiBootManagerLib/BmConnect.c | 44 +- .../Library/UefiBootManagerLib/BmConsole.c | 235 +- .../UefiBootManagerLib/BmDriverHealth.c | 238 +- .../Library/UefiBootManagerLib/BmHotkey.c | 480 ++- .../Library/UefiBootManagerLib/BmLoadOption.c | 534 +-- .../Library/UefiBootManagerLib/BmMisc.c | 137 +- .../Library/UefiBootManagerLib/InternalBm.h | 123 +- MdeModulePkg/Library/UefiHiiLib/HiiLanguage.c | 6 +- MdeModulePkg/Library/UefiHiiLib/HiiLib.c | 1798 +++++---- MdeModulePkg/Library/UefiHiiLib/HiiString.c | 43 +- .../UefiHiiServicesLib/UefiHiiServicesLib.c | 12 +- .../DxeMemoryProfileLib.c | 22 +- .../MemoryAllocationLib.c | 99 +- .../Library/UefiSortLib/UefiSortLib.c | 109 +- .../UnitTest/UefiSortLibUnitTest.c | 34 +- .../InternalVarCheckStructure.h | 78 +- .../Library/VarCheckHiiLib/VarCheckHii.h | 16 +- .../Library/VarCheckHiiLib/VarCheckHiiGen.c | 706 ++-- .../Library/VarCheckHiiLib/VarCheckHiiGen.h | 18 +- .../VarCheckHiiLib/VarCheckHiiGenFromFv.c | 263 +- .../VarCheckHiiLib/VarCheckHiiGenFromHii.c | 24 +- .../VarCheckHiiLib/VarCheckHiiLibNullClass.c | 245 +- .../Library/VarCheckLib/VarCheckLib.c | 235 +- .../VarCheckPcdLib/VarCheckPcdLibNullClass.c | 184 +- .../VarCheckPcdLib/VarCheckPcdStructure.h | 48 +- .../VarCheckPolicyLib/VarCheckPolicyLib.c | 208 +- .../VarCheckPolicyLibStandaloneMm.c | 4 +- .../VarCheckPolicyLibTraditional.c | 4 +- .../VarCheckUefiLibNullClass.c | 132 +- .../VariablePolicyHelperLib.c | 251 +- .../VariablePolicyExtraInitNull.c | 2 - .../VariablePolicyExtraInitRuntimeDxe.c | 31 +- .../VariablePolicyLib/VariablePolicyLib.c | 393 +- MdeModulePkg/Logo/Logo.c | 58 +- .../Acpi/AcpiPlatformDxe/AcpiPlatform.c | 75 +- .../Universal/Acpi/AcpiTableDxe/AcpiSdt.c | 249 +- .../Universal/Acpi/AcpiTableDxe/AcpiSdt.h | 194 +- .../Universal/Acpi/AcpiTableDxe/AcpiTable.c | 30 +- .../Universal/Acpi/AcpiTableDxe/AcpiTable.h | 100 +- .../Acpi/AcpiTableDxe/AcpiTableProtocol.c | 1294 +++--- .../Universal/Acpi/AcpiTableDxe/Aml.c | 366 +- .../Universal/Acpi/AcpiTableDxe/AmlChild.c | 54 +- .../Acpi/AcpiTableDxe/AmlNamespace.c | 154 +- .../Universal/Acpi/AcpiTableDxe/AmlOption.c | 208 +- .../Universal/Acpi/AcpiTableDxe/AmlString.c | 189 +- .../BootGraphicsResourceTableDxe.c | 69 +- .../BootScriptExecutorDxe/IA32/SetIdtEntry.c | 37 +- .../BootScriptExecutorDxe/ScriptExecute.c | 242 +- .../BootScriptExecutorDxe/ScriptExecute.h | 22 +- .../BootScriptExecutorDxe/X64/SetIdtEntry.c | 137 +- .../FirmwarePerformanceDxe.c | 190 +- .../FirmwarePerformancePei.c | 55 +- .../FirmwarePerformanceCommon.c | 26 +- .../FirmwarePerformanceStandaloneMm.c | 4 +- .../FirmwarePerformanceTraditional.c | 4 +- .../Acpi/S3SaveStateDxe/AcpiS3ContextSave.c | 110 +- .../Acpi/S3SaveStateDxe/InternalS3SaveState.h | 34 +- .../Acpi/S3SaveStateDxe/S3SaveState.c | 799 ++-- .../SmmS3SaveState/InternalSmmSaveState.h | 35 +- .../Acpi/SmmS3SaveState/SmmS3SaveState.c | 807 ++-- MdeModulePkg/Universal/BdsDxe/Bds.h | 30 +- MdeModulePkg/Universal/BdsDxe/BdsEntry.c | 314 +- .../Universal/BdsDxe/HwErrRecSupport.c | 6 +- MdeModulePkg/Universal/BdsDxe/Language.c | 58 +- MdeModulePkg/Universal/BdsDxe/Language.h | 2 +- .../BootManagerPolicyDxe.c | 64 +- .../CapsuleOnDiskLoadPei.c | 144 +- MdeModulePkg/Universal/CapsulePei/Capsule.h | 92 +- .../CapsulePei/Common/CapsuleCoalesce.c | 485 ++- .../CapsulePei/Common/CommonHeader.h | 62 +- .../Universal/CapsulePei/UefiCapsule.c | 577 +-- .../Universal/CapsulePei/X64/X64Entry.c | 147 +- .../CapsuleRuntimeDxe/Arm/CapsuleReset.c | 1 - .../CapsuleRuntimeDxe/CapsuleCache.c | 5 +- .../CapsuleRuntimeDxe/CapsuleCacheNull.c | 3 +- .../CapsuleRuntimeDxe/CapsuleReset.c | 1 - .../CapsuleRuntimeDxe/CapsuleService.c | 130 +- .../CapsuleRuntimeDxe/CapsuleService.h | 2 +- .../X64/SaveLongModeContext.c | 88 +- .../Console/ConPlatformDxe/ComponentName.c | 19 +- .../Console/ConPlatformDxe/ConPlatform.c | 267 +- .../Console/ConPlatformDxe/ConPlatform.h | 47 +- .../Console/ConSplitterDxe/ComponentName.c | 130 +- .../Console/ConSplitterDxe/ConSplitter.c | 1707 ++++---- .../Console/ConSplitterDxe/ConSplitter.h | 537 ++- .../ConSplitterDxe/ConSplitterGraphics.c | 244 +- .../GraphicsConsoleDxe/ComponentName.c | 19 +- .../GraphicsConsoleDxe/GraphicsConsole.c | 934 ++--- .../GraphicsConsoleDxe/GraphicsConsole.h | 84 +- .../Console/GraphicsConsoleDxe/LaffStd.c | 731 ++-- .../Console/GraphicsOutputDxe/ComponentName.c | 24 +- .../GraphicsOutputDxe/GraphicsOutput.c | 249 +- .../GraphicsOutputDxe/GraphicsOutput.h | 23 +- .../Universal/Console/TerminalDxe/Ansi.c | 23 +- .../Console/TerminalDxe/ComponentName.c | 23 +- .../Universal/Console/TerminalDxe/Terminal.c | 381 +- .../Universal/Console/TerminalDxe/Terminal.h | 302 +- .../Console/TerminalDxe/TerminalConIn.c | 1543 +++---- .../Console/TerminalDxe/TerminalConOut.c | 604 ++- .../Universal/Console/TerminalDxe/Vtutf8.c | 262 +- .../Universal/DebugPortDxe/ComponentName.c | 21 +- .../Universal/DebugPortDxe/DebugPort.c | 292 +- .../Universal/DebugPortDxe/DebugPort.h | 86 +- .../Universal/DebugServicePei/DebugService.h | 17 +- .../DebugServicePei/DebugServicePei.c | 29 +- .../Universal/DebugSupportDxe/DebugSupport.c | 10 +- .../DebugSupportDxe/Ia32/DebugSupport.h | 70 +- .../DebugSupportDxe/Ia32/PlDebugSupport.c | 79 +- .../DebugSupportDxe/Ia32/PlDebugSupport.h | 2 +- .../DebugSupportDxe/Ia32/PlDebugSupportIa32.c | 26 +- .../DebugSupportDxe/X64/PlDebugSupport.h | 2 +- .../DebugSupportDxe/X64/PlDebugSupportX64.c | 26 +- .../Universal/DevicePathDxe/DevicePath.c | 35 +- .../Disk/CdExpressPei/PeiCdExpress.c | 298 +- .../Disk/CdExpressPei/PeiCdExpress.h | 113 +- .../Universal/Disk/DiskIoDxe/ComponentName.c | 22 +- .../Universal/Disk/DiskIoDxe/DiskIo.c | 330 +- .../Universal/Disk/DiskIoDxe/DiskIo.h | 120 +- .../Disk/PartitionDxe/ComponentName.c | 21 +- .../Universal/Disk/PartitionDxe/ElTorito.c | 119 +- .../Universal/Disk/PartitionDxe/Gpt.c | 177 +- .../Universal/Disk/PartitionDxe/Mbr.c | 111 +- .../Universal/Disk/PartitionDxe/Partition.c | 365 +- .../Universal/Disk/PartitionDxe/Partition.h | 84 +- .../Universal/Disk/PartitionDxe/Udf.c | 399 +- .../Disk/RamDiskDxe/RamDiskBlockIo.c | 127 +- .../Universal/Disk/RamDiskDxe/RamDiskDriver.c | 33 +- .../Disk/RamDiskDxe/RamDiskFileExplorer.c | 27 +- .../Universal/Disk/RamDiskDxe/RamDiskImpl.c | 371 +- .../Universal/Disk/RamDiskDxe/RamDiskImpl.h | 180 +- .../Universal/Disk/RamDiskDxe/RamDiskNVData.h | 22 +- .../Disk/RamDiskDxe/RamDiskProtocol.c | 218 +- .../Universal/Disk/UdfDxe/ComponentName.c | 20 +- MdeModulePkg/Universal/Disk/UdfDxe/File.c | 275 +- MdeModulePkg/Universal/Disk/UdfDxe/FileName.c | 126 +- .../Disk/UdfDxe/FileSystemOperations.c | 1478 +++---- MdeModulePkg/Universal/Disk/UdfDxe/Udf.c | 185 +- MdeModulePkg/Universal/Disk/UdfDxe/Udf.h | 347 +- .../EnglishDxe/UnicodeCollationEng.c | 247 +- .../EnglishDxe/UnicodeCollationEng.h | 48 +- .../Universal/DisplayEngineDxe/FormDisplay.c | 3306 +++++++-------- .../Universal/DisplayEngineDxe/FormDisplay.h | 329 +- .../Universal/DisplayEngineDxe/InputHandler.c | 1736 ++++---- .../Universal/DisplayEngineDxe/Popup.c | 490 +-- .../DisplayEngineDxe/ProcessOptions.c | 1321 +++--- .../DriverHealthManagerDxe.c | 415 +- .../DriverHealthManagerDxe.h | 31 +- .../DriverHealthManagerVfr.h | 16 +- .../Universal/DriverSampleDxe/DriverSample.c | 1556 +++---- .../Universal/DriverSampleDxe/DriverSample.h | 44 +- .../Universal/DriverSampleDxe/NVDataStruc.h | 128 +- .../Universal/EbcDxe/AArch64/EbcSupport.c | 182 +- .../EbcDxe/EbcDebugger/EbcDebuggerConfig.c | 48 +- .../Universal/EbcDxe/EbcDebugger/Edb.c | 164 +- .../Universal/EbcDxe/EbcDebugger/Edb.h | 14 +- .../EbcDxe/EbcDebugger/EdbCmdBranch.c | 66 +- .../EbcDxe/EbcDebugger/EdbCmdBreak.c | 49 +- .../EbcDxe/EbcDebugger/EdbCmdBreakpoint.c | 139 +- .../EbcDxe/EbcDebugger/EdbCmdExtIo.c | 51 +- .../EbcDxe/EbcDebugger/EdbCmdExtPci.c | 41 +- .../Universal/EbcDxe/EbcDebugger/EdbCmdGo.c | 19 +- .../Universal/EbcDxe/EbcDebugger/EdbCmdHelp.c | 11 +- .../EbcDxe/EbcDebugger/EdbCmdMemory.c | 254 +- .../Universal/EbcDxe/EbcDebugger/EdbCmdQuit.c | 8 +- .../EbcDxe/EbcDebugger/EdbCmdRegister.c | 9 +- .../EbcDxe/EbcDebugger/EdbCmdScope.c | 25 +- .../Universal/EbcDxe/EbcDebugger/EdbCmdStep.c | 36 +- .../EbcDxe/EbcDebugger/EdbCmdSymbol.c | 251 +- .../Universal/EbcDxe/EbcDebugger/EdbCommand.c | 302 +- .../Universal/EbcDxe/EbcDebugger/EdbCommand.h | 6 +- .../Universal/EbcDxe/EbcDebugger/EdbCommon.h | 204 +- .../Universal/EbcDxe/EbcDebugger/EdbDisasm.c | 1073 ++--- .../Universal/EbcDxe/EbcDebugger/EdbDisasm.h | 8 +- .../EbcDxe/EbcDebugger/EdbDisasmSupport.c | 341 +- .../EbcDxe/EbcDebugger/EdbDisasmSupport.h | 86 +- .../Universal/EbcDxe/EbcDebugger/EdbHook.c | 253 +- .../Universal/EbcDxe/EbcDebugger/EdbSupport.h | 84 +- .../EbcDxe/EbcDebugger/EdbSupportFile.c | 118 +- .../EbcDxe/EbcDebugger/EdbSupportString.c | 278 +- .../EbcDxe/EbcDebugger/EdbSupportUI.c | 508 +-- .../Universal/EbcDxe/EbcDebugger/EdbSymbol.c | 893 ++-- .../Universal/EbcDxe/EbcDebugger/EdbSymbol.h | 72 +- .../Universal/EbcDxe/EbcDebuggerHook.c | 30 +- .../Universal/EbcDxe/EbcDebuggerHook.h | 39 +- MdeModulePkg/Universal/EbcDxe/EbcExecute.c | 1960 ++++----- MdeModulePkg/Universal/EbcDxe/EbcExecute.h | 25 +- MdeModulePkg/Universal/EbcDxe/EbcInt.c | 527 +-- MdeModulePkg/Universal/EbcDxe/EbcInt.h | 72 +- .../Universal/EbcDxe/Ia32/EbcSupport.c | 285 +- .../Universal/EbcDxe/X64/EbcSupport.c | 286 +- MdeModulePkg/Universal/EsrtDxe/EsrtDxe.c | 296 +- MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c | 165 +- MdeModulePkg/Universal/EsrtDxe/EsrtImpl.h | 70 +- MdeModulePkg/Universal/EsrtFmpDxe/EsrtFmp.c | 68 +- .../Universal/EsrtFmpDxe/EsrtFmpDebugPrint.c | 40 +- .../FaultTolerantWrite.c | 339 +- .../FaultTolerantWrite.h | 193 +- .../FaultTolerantWriteDxe.c | 55 +- .../FaultTolerantWriteSmm.c | 177 +- .../FaultTolerantWriteSmmCommon.h | 58 +- .../FaultTolerantWriteSmmDxe.c | 189 +- .../FaultTolerantWriteSmmDxe.h | 53 +- .../FaultTolerantWriteStandaloneMm.c | 8 +- .../FaultTolerantWriteTraditionalMm.c | 28 +- .../Universal/FaultTolerantWriteDxe/FtwMisc.c | 326 +- .../UpdateWorkingBlock.c | 193 +- .../FaultTolerantWritePei.c | 111 +- .../FileExplorerDxe/FileExplorerDxe.c | 9 +- .../FvSimpleFileSystemDxe/ComponentName.c | 18 +- .../FvSimpleFileSystem.c | 309 +- .../FvSimpleFileSystemEntryPoint.c | 187 +- .../FvSimpleFileSystemInternal.h | 135 +- .../HiiDatabaseDxe/ConfigKeywordHandler.c | 1825 +++++---- .../Universal/HiiDatabaseDxe/ConfigRouting.c | 3584 +++++++++-------- .../Universal/HiiDatabaseDxe/Database.c | 2443 +++++------ MdeModulePkg/Universal/HiiDatabaseDxe/Font.c | 1610 ++++---- .../Universal/HiiDatabaseDxe/HiiDatabase.h | 779 ++-- .../HiiDatabaseDxe/HiiDatabaseEntry.c | 55 +- MdeModulePkg/Universal/HiiDatabaseDxe/Image.c | 870 ++-- .../Universal/HiiDatabaseDxe/ImageEx.c | 258 +- .../Universal/HiiDatabaseDxe/String.c | 1239 +++--- .../HiiResourcesSample.c | 41 +- .../LegacyRegion2Dxe/LegacyRegion2.c | 21 +- .../LegacyRegion2Dxe/LegacyRegion2.h | 16 +- .../Universal/LoadFileOnFv2/LoadFileOnFv2.c | 185 +- .../Universal/LockBox/SmmLockBox/SmmLockBox.c | 155 +- .../GenericMemoryTestDxe/LightMemoryTest.c | 295 +- .../GenericMemoryTestDxe/LightMemoryTest.h | 66 +- .../NullMemoryTestDxe/NullMemoryTest.c | 90 +- .../NullMemoryTestDxe/NullMemoryTest.h | 26 +- MdeModulePkg/Universal/Metronome/Metronome.c | 6 +- .../MonotonicCounter.c | 52 +- MdeModulePkg/Universal/PCD/Dxe/Pcd.c | 357 +- MdeModulePkg/Universal/PCD/Dxe/Service.c | 935 ++--- MdeModulePkg/Universal/PCD/Dxe/Service.h | 293 +- MdeModulePkg/Universal/PCD/Pei/Pcd.c | 519 +-- MdeModulePkg/Universal/PCD/Pei/Service.c | 420 +- MdeModulePkg/Universal/PCD/Pei/Service.h | 207 +- .../PcatSingleSegmentPciCfg2Pei/PciCfg2.c | 123 +- .../InternalPlatDriOverrideDxe.h | 38 +- .../PlatDriOverrideDxe.c | 753 ++-- .../PlatDriOverrideLib.c | 804 ++-- .../PlatformDriOverrideDxe/PlatOverMngr.h | 36 +- MdeModulePkg/Universal/PrintDxe/Print.c | 25 +- .../RegularExpressionDxe/OnigurumaUefiPort.c | 84 +- .../RegularExpressionDxe/OnigurumaUefiPort.h | 150 +- .../RegularExpressionDxe.c | 73 +- .../RegularExpressionDxe.h | 20 +- .../Pei/ReportStatusCodeRouterPei.c | 90 +- .../Pei/ReportStatusCodeRouterPei.h | 19 +- .../ReportStatusCodeRouterRuntimeDxe.c | 118 +- .../ReportStatusCodeRouterRuntimeDxe.h | 47 +- .../Smm/ReportStatusCodeRouterCommon.c | 44 +- .../Smm/ReportStatusCodeRouterCommon.h | 20 +- .../Smm/ReportStatusCodeRouterStandaloneMm.c | 4 +- .../Smm/ReportStatusCodeRouterTraditional.c | 4 +- .../Universal/ResetSystemPei/ResetSystem.c | 112 +- .../Universal/ResetSystemPei/ResetSystem.h | 35 +- .../ResetSystemRuntimeDxe/ResetSystem.c | 120 +- .../ResetSystemRuntimeDxe/ResetSystem.h | 29 +- .../SectionExtractionDxe.c | 44 +- .../SectionExtractionPei.c | 43 +- .../SecurityStubDxe/Defer3rdPartyImageLoad.c | 116 +- .../SecurityStubDxe/Defer3rdPartyImageLoad.h | 12 +- .../Universal/SecurityStubDxe/SecurityStub.c | 57 +- MdeModulePkg/Universal/SerialDxe/SerialIo.c | 227 +- .../Universal/SetupBrowserDxe/Expression.c | 2629 ++++++------ .../Universal/SetupBrowserDxe/Expression.h | 29 +- .../Universal/SetupBrowserDxe/IfrParse.c | 2602 ++++++------ .../Universal/SetupBrowserDxe/Presentation.c | 1075 ++--- .../Universal/SetupBrowserDxe/Setup.c | 2321 +++++------ .../Universal/SetupBrowserDxe/Setup.h | 839 ++-- MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c | 641 +-- MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.h | 71 +- .../SmbiosMeasurementDxe.c | 308 +- .../SmmCommunicationBufferDxe.c | 18 +- .../Pei/MemoryStausCodeWorker.c | 31 +- .../Pei/SerialStatusCodeWorker.c | 50 +- .../Pei/StatusCodeHandlerPei.c | 10 +- .../Pei/StatusCodeHandlerPei.h | 30 +- .../RuntimeDxe/MemoryStatusCodeWorker.c | 20 +- .../RuntimeDxe/SerialStatusCodeWorker.c | 53 +- .../RuntimeDxe/StatusCodeHandlerRuntimeDxe.c | 40 +- .../RuntimeDxe/StatusCodeHandlerRuntimeDxe.h | 23 +- .../Smm/MemoryStatusCodeWorker.c | 32 +- .../Smm/SerialStatusCodeWorker.c | 46 +- .../Smm/StatusCodeHandlerMm.c | 11 +- .../Smm/StatusCodeHandlerMm.h | 23 +- .../Smm/StatusCodeHandlerTraditional.c | 4 +- .../Universal/TimestampDxe/TimestampDxe.c | 20 +- .../Universal/Variable/Pei/Variable.c | 443 +- .../Universal/Variable/Pei/Variable.h | 25 +- .../Variable/RuntimeDxe/Measurement.c | 182 +- .../RuntimeDxe/PrivilegePolymorphic.h | 15 +- .../Universal/Variable/RuntimeDxe/Reclaim.c | 32 +- .../VariableLockRequestToLockUnitTest.c | 274 +- .../Variable/RuntimeDxe/TcgMorLockDxe.c | 65 +- .../Variable/RuntimeDxe/TcgMorLockSmm.c | 173 +- .../Universal/Variable/RuntimeDxe/VarCheck.c | 21 +- .../Universal/Variable/RuntimeDxe/Variable.c | 1369 ++++--- .../Universal/Variable/RuntimeDxe/Variable.h | 223 +- .../Variable/RuntimeDxe/VariableDxe.c | 196 +- .../Variable/RuntimeDxe/VariableExLib.c | 104 +- .../RuntimeDxe/VariableLockRequestToLock.c | 28 +- .../Variable/RuntimeDxe/VariableNonVolatile.c | 99 +- .../Variable/RuntimeDxe/VariableNonVolatile.h | 2 +- .../Variable/RuntimeDxe/VariableParsing.c | 300 +- .../Variable/RuntimeDxe/VariableParsing.h | 66 +- .../RuntimeDxe/VariablePolicySmmDxe.c | 272 +- .../RuntimeDxe/VariableRuntimeCache.c | 101 +- .../RuntimeDxe/VariableRuntimeCache.h | 6 +- .../Variable/RuntimeDxe/VariableSmm.c | 405 +- .../RuntimeDxe/VariableSmmRuntimeDxe.c | 606 +-- .../RuntimeDxe/VariableStandaloneMm.c | 4 +- .../RuntimeDxe/VariableTraditionalMm.c | 16 +- .../WatchdogTimerDxe/WatchdogTimer.c | 11 +- .../WatchdogTimerDxe/WatchdogTimer.h | 3 - 994 files changed, 107445 insertions(+), 101148 deletions(-) diff --git a/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.c b/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.c index d4bdeba073..ef19319614 100644 --- a/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.c +++ b/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.c @@ -8,24 +8,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "BootManagerMenu.h" -EFI_HII_HANDLE gStringPackHandle; +EFI_HII_HANDLE gStringPackHandle; -BOOLEAN mModeInitialized = FALSE; +BOOLEAN mModeInitialized = FALSE; // // Boot video resolution and text mode. // -UINT32 mBootHorizontalResolution = 0; -UINT32 mBootVerticalResolution = 0; -UINT32 mBootTextModeColumn = 0; -UINT32 mBootTextModeRow = 0; +UINT32 mBootHorizontalResolution = 0; +UINT32 mBootVerticalResolution = 0; +UINT32 mBootTextModeColumn = 0; +UINT32 mBootTextModeRow = 0; // // BIOS setup video resolution and text mode. // -UINT32 mSetupTextModeColumn = 0; -UINT32 mSetupTextModeRow = 0; -UINT32 mSetupHorizontalResolution = 0; -UINT32 mSetupVerticalResolution = 0; +UINT32 mSetupTextModeColumn = 0; +UINT32 mSetupTextModeRow = 0; +UINT32 mSetupHorizontalResolution = 0; +UINT32 mSetupVerticalResolution = 0; /** Prints a unicode string to the default console, at @@ -40,16 +40,16 @@ UINT32 mSetupVerticalResolution = 0; **/ UINTN PrintStringAt ( - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *String + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *String ) { - UINTN ScreenWidth; - UINTN ScreenRows; - CHAR16 *TurncateString; - EFI_STATUS Status; - UINTN ShowingLength; + UINTN ScreenWidth; + UINTN ScreenRows; + CHAR16 *TurncateString; + EFI_STATUS Status; + UINTN ShowingLength; gST->ConOut->SetCursorPosition (gST->ConOut, Column, Row); @@ -60,7 +60,7 @@ PrintStringAt ( &ScreenRows ); - if (Column > (ScreenWidth - 1) || Row > (ScreenRows - 1)) { + if ((Column > (ScreenWidth - 1)) || (Row > (ScreenRows - 1))) { return 0; } @@ -71,7 +71,7 @@ PrintStringAt ( // TurncateString length should leave one character for draw box and // require one character for string end. // - ShowingLength = ScreenWidth - Column - 1; + ShowingLength = ScreenWidth - Column - 1; TurncateString = AllocatePool ((ShowingLength + 1) * sizeof (CHAR16)); if (TurncateString == NULL) { @@ -89,7 +89,7 @@ PrintStringAt ( *(TurncateString + ShowingLength - 2) = L'.'; *(TurncateString + ShowingLength - 1) = L'.'; *(TurncateString + ShowingLength) = L'\0'; - ShowingLength = Print (L"%s", TurncateString); + ShowingLength = Print (L"%s", TurncateString); FreePool (TurncateString); return ShowingLength; } else { @@ -110,13 +110,13 @@ PrintStringAt ( **/ UINTN PrintCharAt ( - IN UINTN Column, - IN UINTN Row, - CHAR16 Character + IN UINTN Column, + IN UINTN Row, + CHAR16 Character ) { - UINTN ScreenWidth; - UINTN ScreenRows; + UINTN ScreenWidth; + UINTN ScreenRows; gST->ConOut->SetCursorPosition (gST->ConOut, Column, Row); @@ -127,7 +127,7 @@ PrintCharAt ( &ScreenRows ); - if (Column > (ScreenWidth - 1) || Row > (ScreenRows - 1)) { + if ((Column > (ScreenWidth - 1)) || (Row > (ScreenRows - 1))) { return 0; } @@ -145,30 +145,31 @@ PrintCharAt ( **/ UINTN GetLineWidth ( - IN EFI_STRING_ID StringId + IN EFI_STRING_ID StringId ) { - UINTN Index; - UINTN IncrementValue; - EFI_STRING String; - UINTN LineWidth; + UINTN Index; + UINTN IncrementValue; + EFI_STRING String; + UINTN LineWidth; LineWidth = 0; - String = HiiGetString (gStringPackHandle, StringId, NULL); + String = HiiGetString (gStringPackHandle, StringId, NULL); if (String != NULL) { - Index = 0; - IncrementValue = 1; + Index = 0; + IncrementValue = 1; do { // // Advance to the null-terminator or to the first width directive // - for (; - (String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); - Index++, LineWidth = LineWidth + IncrementValue - ) - ; + for ( ; + (String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); + Index++, LineWidth = LineWidth + IncrementValue + ) + { + } // // We hit the null-terminator, we now have a count @@ -176,6 +177,7 @@ GetLineWidth ( if (String[Index] == 0) { break; } + // // We encountered a narrow directive - strip it from the size calculation since it doesn't get printed // and also set the flag that determines what we increment by.(if narrow, increment by 1, if wide increment by 2) @@ -194,6 +196,7 @@ GetLineWidth ( IncrementValue = 2; } } while (String[Index] != 0); + FreePool (String); } @@ -214,35 +217,37 @@ InitializeBootMenuScreen ( IN OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { - UINTN MaxStrWidth; - UINTN StrWidth; - UINTN Index; - UINTN Column; - UINTN Row; - UINTN MaxPrintRows; - UINTN UnSelectableItmes; + UINTN MaxStrWidth; + UINTN StrWidth; + UINTN Index; + UINTN Column; + UINTN Row; + UINTN MaxPrintRows; + UINTN UnSelectableItmes; if (BootMenuData == NULL) { return EFI_INVALID_PARAMETER; } + // // Get maximum string width // MaxStrWidth = 0; for (Index = 0; Index < TITLE_TOKEN_COUNT; Index++) { - StrWidth = GetLineWidth (BootMenuData->TitleToken[Index]); + StrWidth = GetLineWidth (BootMenuData->TitleToken[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } for (Index = 0; Index < BootMenuData->ItemCount; Index++) { - StrWidth = GetLineWidth (BootMenuData->PtrTokens[Index]); + StrWidth = GetLineWidth (BootMenuData->PtrTokens[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } for (Index = 0; Index < HELP_TOKEN_COUNT; Index++) { - StrWidth = GetLineWidth (BootMenuData->HelpToken[Index]); + StrWidth = GetLineWidth (BootMenuData->HelpToken[Index]); MaxStrWidth = MaxStrWidth > StrWidth ? MaxStrWidth : StrWidth; } + // // query current row and column to calculate boot menu location // @@ -253,31 +258,34 @@ InitializeBootMenuScreen ( &Row ); - MaxPrintRows = Row - 6; + MaxPrintRows = Row - 6; UnSelectableItmes = TITLE_TOKEN_COUNT + 2 + HELP_TOKEN_COUNT + 2; if (MaxStrWidth + 8 > Column) { BootMenuData->MenuScreen.Width = Column; } else { BootMenuData->MenuScreen.Width = MaxStrWidth + 8; } + if (BootMenuData->ItemCount + UnSelectableItmes > MaxPrintRows) { - BootMenuData->MenuScreen.Height = MaxPrintRows; - BootMenuData->ScrollBarControl.HasScrollBar = TRUE; + BootMenuData->MenuScreen.Height = MaxPrintRows; + BootMenuData->ScrollBarControl.HasScrollBar = TRUE; BootMenuData->ScrollBarControl.ItemCountPerScreen = MaxPrintRows - UnSelectableItmes; - BootMenuData->ScrollBarControl.FirstItem = 0; - BootMenuData->ScrollBarControl.LastItem = MaxPrintRows - UnSelectableItmes - 1; + BootMenuData->ScrollBarControl.FirstItem = 0; + BootMenuData->ScrollBarControl.LastItem = MaxPrintRows - UnSelectableItmes - 1; } else { - BootMenuData->MenuScreen.Height = BootMenuData->ItemCount + UnSelectableItmes; - BootMenuData->ScrollBarControl.HasScrollBar = FALSE; + BootMenuData->MenuScreen.Height = BootMenuData->ItemCount + UnSelectableItmes; + BootMenuData->ScrollBarControl.HasScrollBar = FALSE; BootMenuData->ScrollBarControl.ItemCountPerScreen = BootMenuData->ItemCount; - BootMenuData->ScrollBarControl.FirstItem = 0; - BootMenuData->ScrollBarControl.LastItem = BootMenuData->ItemCount - 1; + BootMenuData->ScrollBarControl.FirstItem = 0; + BootMenuData->ScrollBarControl.LastItem = BootMenuData->ItemCount - 1; } + BootMenuData->MenuScreen.StartCol = (Column - BootMenuData->MenuScreen.Width) / 2; BootMenuData->MenuScreen.StartRow = (Row - BootMenuData->MenuScreen.Height) / 2; return EFI_SUCCESS; } + /** This function uses check boot option is wheher setup application or no @@ -289,18 +297,18 @@ InitializeBootMenuScreen ( **/ BOOLEAN IsBootManagerMenu ( - IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu; Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu); if (!EFI_ERROR (Status)) { EfiBootManagerFreeLoadOption (&BootManagerMenu); } - return (BOOLEAN) (!EFI_ERROR (Status) && (BootOption->OptionNumber == BootManagerMenu.OptionNumber)); + return (BOOLEAN)(!EFI_ERROR (Status) && (BootOption->OptionNumber == BootManagerMenu.OptionNumber)); } /** @@ -316,13 +324,13 @@ IgnoreBootOption ( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath; // // Ignore myself. // - Status = gBS->HandleProtocol (gImageHandle, &gEfiLoadedImageDevicePathProtocolGuid, (VOID **) &ImageDevicePath); + Status = gBS->HandleProtocol (gImageHandle, &gEfiLoadedImageDevicePathProtocolGuid, (VOID **)&ImageDevicePath); ASSERT_EFI_ERROR (Status); if (CompareMem (BootOption->FilePath, ImageDevicePath, GetDevicePathSize (ImageDevicePath)) == 0) { return TRUE; @@ -363,10 +371,10 @@ InitializeBootMenuData ( OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { - UINTN Index; - UINTN StrIndex; + UINTN Index; + UINTN StrIndex; - if (BootOption == NULL || BootMenuData == NULL) { + if ((BootOption == NULL) || (BootMenuData == NULL)) { return EFI_INVALID_PARAMETER; } @@ -391,7 +399,7 @@ InitializeBootMenuData ( ); } - BootMenuData->ItemCount = StrIndex; + BootMenuData->ItemCount = StrIndex; BootMenuData->HelpToken[0] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP1_STRING); BootMenuData->HelpToken[1] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP2_STRING); BootMenuData->HelpToken[2] = STRING_TOKEN (STR_BOOT_POPUP_MENU_HELP3_STRING); @@ -417,93 +425,101 @@ BootMenuSelectItem ( IN OUT BOOT_MENU_POPUP_DATA *BootMenuData ) { - INT32 SavedAttribute; - EFI_STRING String; - UINTN StartCol; - UINTN StartRow; - UINTN PrintCol; - UINTN PrintRow; - UINTN TopShadeNum; - UINTN LowShadeNum; - UINTN FirstItem; - UINTN LastItem; - UINTN ItemCountPerScreen; - UINTN Index; - BOOLEAN RePaintItems; - - if (BootMenuData == NULL || WantSelectItem >= BootMenuData->ItemCount) { + INT32 SavedAttribute; + EFI_STRING String; + UINTN StartCol; + UINTN StartRow; + UINTN PrintCol; + UINTN PrintRow; + UINTN TopShadeNum; + UINTN LowShadeNum; + UINTN FirstItem; + UINTN LastItem; + UINTN ItemCountPerScreen; + UINTN Index; + BOOLEAN RePaintItems; + + if ((BootMenuData == NULL) || (WantSelectItem >= BootMenuData->ItemCount)) { return EFI_INVALID_PARAMETER; } + ASSERT (BootMenuData->ItemCount != 0); SavedAttribute = gST->ConOut->Mode->Attribute; - RePaintItems = FALSE; - StartCol = BootMenuData->MenuScreen.StartCol; - StartRow = BootMenuData->MenuScreen.StartRow; + RePaintItems = FALSE; + StartCol = BootMenuData->MenuScreen.StartCol; + StartRow = BootMenuData->MenuScreen.StartRow; // // print selectable items again and adjust scroll bar if need // if (BootMenuData->ScrollBarControl.HasScrollBar && - (WantSelectItem < BootMenuData->ScrollBarControl.FirstItem || - WantSelectItem > BootMenuData->ScrollBarControl.LastItem || - WantSelectItem == BootMenuData->SelectItem)) { - ItemCountPerScreen = BootMenuData->ScrollBarControl.ItemCountPerScreen; + ((WantSelectItem < BootMenuData->ScrollBarControl.FirstItem) || + (WantSelectItem > BootMenuData->ScrollBarControl.LastItem) || + (WantSelectItem == BootMenuData->SelectItem))) + { + ItemCountPerScreen = BootMenuData->ScrollBarControl.ItemCountPerScreen; // // Set first item and last item // if (WantSelectItem < BootMenuData->ScrollBarControl.FirstItem) { BootMenuData->ScrollBarControl.FirstItem = WantSelectItem; - BootMenuData->ScrollBarControl.LastItem = WantSelectItem + ItemCountPerScreen - 1; + BootMenuData->ScrollBarControl.LastItem = WantSelectItem + ItemCountPerScreen - 1; } else if (WantSelectItem > BootMenuData->ScrollBarControl.LastItem) { BootMenuData->ScrollBarControl.FirstItem = WantSelectItem - ItemCountPerScreen + 1; - BootMenuData->ScrollBarControl.LastItem = WantSelectItem; + BootMenuData->ScrollBarControl.LastItem = WantSelectItem; } + gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); - FirstItem = BootMenuData->ScrollBarControl.FirstItem; - LastItem = BootMenuData->ScrollBarControl.LastItem; + FirstItem = BootMenuData->ScrollBarControl.FirstItem; + LastItem = BootMenuData->ScrollBarControl.LastItem; TopShadeNum = 0; if (FirstItem != 0) { TopShadeNum = (FirstItem * ItemCountPerScreen) / BootMenuData->ItemCount; if ((FirstItem * ItemCountPerScreen) % BootMenuData->ItemCount != 0) { TopShadeNum++; } + PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2; for (Index = 0; Index < TopShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_LIGHT_SHADE); } } + LowShadeNum = 0; if (LastItem != BootMenuData->ItemCount - 1) { LowShadeNum = ((BootMenuData->ItemCount - 1 - LastItem) * ItemCountPerScreen) / BootMenuData->ItemCount; if (((BootMenuData->ItemCount - 1 - LastItem) * ItemCountPerScreen) % BootMenuData->ItemCount != 0) { LowShadeNum++; } + PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + ItemCountPerScreen - LowShadeNum; for (Index = 0; Index < LowShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_LIGHT_SHADE); } } + PrintCol = StartCol + BootMenuData->MenuScreen.Width - 2; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + TopShadeNum; for (Index = TopShadeNum; Index < ItemCountPerScreen - LowShadeNum; Index++, PrintRow++) { PrintCharAt (PrintCol, PrintRow, BLOCKELEMENT_FULL_BLOCK); } - // // Clear selectable items first // PrintCol = StartCol + 1; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2; - String = AllocateZeroPool ((BootMenuData->MenuScreen.Width - 2) * sizeof (CHAR16)); + String = AllocateZeroPool ((BootMenuData->MenuScreen.Width - 2) * sizeof (CHAR16)); ASSERT (String != NULL); for (Index = 0; Index < BootMenuData->MenuScreen.Width - 3; Index++) { String[Index] = 0x20; } + for (Index = 0; Index < ItemCountPerScreen; Index++) { PrintStringAt (PrintCol, PrintRow + Index, String); } + FreePool (String); // // print selectable items @@ -513,6 +529,7 @@ BootMenuSelectItem ( PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } + RePaintItems = TRUE; } @@ -521,9 +538,9 @@ BootMenuSelectItem ( // items, clear select item // FirstItem = BootMenuData->ScrollBarControl.FirstItem; - if (WantSelectItem != BootMenuData->SelectItem && !RePaintItems) { + if ((WantSelectItem != BootMenuData->SelectItem) && !RePaintItems) { gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); - String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[BootMenuData->SelectItem], NULL); + String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[BootMenuData->SelectItem], NULL); PrintCol = StartCol + 1; PrintRow = StartRow + 3 + BootMenuData->SelectItem - FirstItem; PrintStringAt (PrintCol, PrintRow, String); @@ -534,7 +551,7 @@ BootMenuSelectItem ( // Print want to select item // gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLACK); - String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[WantSelectItem], NULL); + String = HiiGetString (gStringPackHandle, BootMenuData->PtrTokens[WantSelectItem], NULL); PrintCol = StartCol + 1; PrintRow = StartRow + TITLE_TOKEN_COUNT + 2 + WantSelectItem - FirstItem; PrintStringAt (PrintCol, PrintRow, String); @@ -558,26 +575,26 @@ DrawBootPopupMenu ( IN BOOT_MENU_POPUP_DATA *BootMenuData ) { - EFI_STRING String; - UINTN Index; - UINTN Width; - UINTN StartCol; - UINTN StartRow; - UINTN PrintRow; - UINTN PrintCol; - UINTN LineWidth; - INT32 SavedAttribute; - UINTN ItemCountPerScreen; + EFI_STRING String; + UINTN Index; + UINTN Width; + UINTN StartCol; + UINTN StartRow; + UINTN PrintRow; + UINTN PrintCol; + UINTN LineWidth; + INT32 SavedAttribute; + UINTN ItemCountPerScreen; gST->ConOut->ClearScreen (gST->ConOut); SavedAttribute = gST->ConOut->Mode->Attribute; gST->ConOut->SetAttribute (gST->ConOut, EFI_WHITE | EFI_BACKGROUND_BLUE); - Width = BootMenuData->MenuScreen.Width; - StartCol = BootMenuData->MenuScreen.StartCol; - StartRow = BootMenuData->MenuScreen.StartRow; + Width = BootMenuData->MenuScreen.Width; + StartCol = BootMenuData->MenuScreen.StartCol; + StartRow = BootMenuData->MenuScreen.StartRow; ItemCountPerScreen = BootMenuData->ScrollBarControl.ItemCountPerScreen; - PrintRow = StartRow; + PrintRow = StartRow; gST->ConOut->EnableCursor (gST->ConOut, FALSE); // @@ -587,6 +604,7 @@ DrawBootPopupMenu ( for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } + PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_DOWN_LEFT); // @@ -610,6 +628,7 @@ DrawBootPopupMenu ( for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } + PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL_LEFT); // @@ -627,6 +646,7 @@ DrawBootPopupMenu ( for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } + PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL_LEFT); // @@ -638,6 +658,7 @@ DrawBootPopupMenu ( PrintStringAt (StartCol + 1, PrintRow, String); PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_VERTICAL); } + FreePool (String); PrintRow++; @@ -645,17 +666,17 @@ DrawBootPopupMenu ( for (Index = 1; Index < Width - 1; Index++) { PrintCharAt (StartCol + Index, PrintRow, BOXDRAW_HORIZONTAL); } - PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_UP_LEFT); + PrintCharAt (StartCol + Width - 1, PrintRow, BOXDRAW_UP_LEFT); // // print title strings // PrintRow = StartRow + 1; for (Index = 0; Index < TITLE_TOKEN_COUNT; Index++, PrintRow++) { - String = HiiGetString (gStringPackHandle, BootMenuData->TitleToken[Index], NULL); + String = HiiGetString (gStringPackHandle, BootMenuData->TitleToken[Index], NULL); LineWidth = GetLineWidth (BootMenuData->TitleToken[Index]); - PrintCol = StartCol + (Width - LineWidth) / 2; + PrintCol = StartCol + (Width - LineWidth) / 2; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } @@ -676,9 +697,9 @@ DrawBootPopupMenu ( // PrintRow++; for (Index = 0; Index < HELP_TOKEN_COUNT; Index++, PrintRow++) { - String = HiiGetString (gStringPackHandle, BootMenuData->HelpToken[Index], NULL); + String = HiiGetString (gStringPackHandle, BootMenuData->HelpToken[Index], NULL); LineWidth = GetLineWidth (BootMenuData->HelpToken[Index]); - PrintCol = StartCol + (Width - LineWidth) / 2; + PrintCol = StartCol + (Width - LineWidth) / 2; PrintStringAt (PrintCol, PrintRow, String); FreePool (String); } @@ -718,8 +739,8 @@ BootFromSelectOption ( IN UINTN SelectItem ) { - UINTN ItemNum; - UINTN Index; + UINTN ItemNum; + UINTN Index; ASSERT (BootOptions != NULL); @@ -778,7 +799,7 @@ BdsSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -787,7 +808,7 @@ BdsSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -816,7 +837,7 @@ BdsSetConsoleMode ( } if (GraphicsOutput != NULL) { - MaxGopMode = GraphicsOutput->Mode->MaxMode; + MaxGopMode = GraphicsOutput->Mode->MaxMode; } if (SimpleTextOut != NULL) { @@ -832,22 +853,24 @@ BdsSetConsoleMode ( // for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( - GraphicsOutput, - ModeNumber, - &SizeOfInfo, - &Info - ); + GraphicsOutput, + ModeNumber, + &SizeOfInfo, + &Info + ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == NewHorizontalResolution) && - (Info->VerticalResolution == NewVerticalResolution)) { + (Info->VerticalResolution == NewVerticalResolution)) + { if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) && - (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) { + (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) + { // // Current resolution is same with required resolution, check if text mode need be set // Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow); ASSERT_EFI_ERROR (Status); - if (CurrentColumn == NewColumns && CurrentRow == NewRows) { + if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // If current text mode is same with required text mode. Do nothing // @@ -859,7 +882,7 @@ BdsSetConsoleMode ( // for (Index = 0; Index < MaxTextMode; Index++) { Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // Required text mode is supported, set it. @@ -878,6 +901,7 @@ BdsSetConsoleMode ( } } } + if (Index == MaxTextMode) { // // If required text mode is not supported, return error. @@ -898,6 +922,7 @@ BdsSetConsoleMode ( } } } + FreePool (Info); } } @@ -928,19 +953,21 @@ BdsSetConsoleMode ( // Locate all the handles with GOP protocol and reconnect it. // Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextOutProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextOutProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); } + for (Index = 0; Index < HandleCount; Index++) { gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } + if (HandleBuffer != NULL) { FreePool (HandleBuffer); } @@ -962,29 +989,29 @@ BdsSetConsoleMode ( EFI_STATUS EFIAPI BootManagerMenuEntry ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_BOOT_MANAGER_LOAD_OPTION *BootOption; - UINTN BootOptionCount; - EFI_STATUS Status; - BOOT_MENU_POPUP_DATA BootMenuData; - UINTN Index; - EFI_INPUT_KEY Key; - BOOLEAN ExitApplication; - UINTN SelectItem; - EFI_BOOT_LOGO_PROTOCOL *BootLogo; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; - EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; - UINTN BootTextColumn; - UINTN BootTextRow; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOption; + UINTN BootOptionCount; + EFI_STATUS Status; + BOOT_MENU_POPUP_DATA BootMenuData; + UINTN Index; + EFI_INPUT_KEY Key; + BOOLEAN ExitApplication; + UINTN SelectItem; + EFI_BOOT_LOGO_PROTOCOL *BootLogo; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; + UINTN BootTextColumn; + UINTN BootTextRow; // // Set Logo status invalid when boot manager menu is launched // BootLogo = NULL; - Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); + Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **)&BootLogo); if (!EFI_ERROR (Status) && (BootLogo != NULL)) { Status = BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0); ASSERT_EFI_ERROR (Status); @@ -993,11 +1020,11 @@ BootManagerMenuEntry ( gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL); gStringPackHandle = HiiAddPackages ( - &gEfiCallerIdGuid, - gImageHandle, - BootManagerMenuAppStrings, - NULL - ); + &gEfiCallerIdGuid, + gImageHandle, + BootManagerMenuAppStrings, + NULL + ); ASSERT (gStringPackHandle != NULL); // @@ -1016,7 +1043,7 @@ BootManagerMenuEntry ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -1025,7 +1052,7 @@ BootManagerMenuEntry ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -1083,58 +1110,57 @@ BootManagerMenuEntry ( Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); if (!EFI_ERROR (Status)) { switch (Key.UnicodeChar) { + case CHAR_NULL: + switch (Key.ScanCode) { + case SCAN_UP: + SelectItem = BootMenuData.SelectItem == 0 ? BootMenuData.ItemCount - 1 : BootMenuData.SelectItem - 1; + BootMenuSelectItem (SelectItem, &BootMenuData); + break; + + case SCAN_DOWN: + SelectItem = BootMenuData.SelectItem == BootMenuData.ItemCount - 1 ? 0 : BootMenuData.SelectItem + 1; + BootMenuSelectItem (SelectItem, &BootMenuData); + break; + + case SCAN_ESC: + gST->ConOut->ClearScreen (gST->ConOut); + ExitApplication = TRUE; + // + // Set boot resolution for normal boot + // + BdsSetConsoleMode (FALSE); + break; - case CHAR_NULL: - switch (Key.ScanCode) { - - case SCAN_UP: - SelectItem = BootMenuData.SelectItem == 0 ? BootMenuData.ItemCount - 1 : BootMenuData.SelectItem - 1; - BootMenuSelectItem (SelectItem, &BootMenuData); - break; + default: + break; + } - case SCAN_DOWN: - SelectItem = BootMenuData.SelectItem == BootMenuData.ItemCount - 1 ? 0 : BootMenuData.SelectItem + 1; - BootMenuSelectItem (SelectItem, &BootMenuData); break; - case SCAN_ESC: + case CHAR_CARRIAGE_RETURN: gST->ConOut->ClearScreen (gST->ConOut); - ExitApplication = TRUE; // // Set boot resolution for normal boot // BdsSetConsoleMode (FALSE); + BootFromSelectOption (BootOption, BootOptionCount, BootMenuData.SelectItem); + // + // Back to boot manager menu again, set back to setup resolution + // + BdsSetConsoleMode (TRUE); + DrawBootPopupMenu (&BootMenuData); break; default: break; - } - break; - - case CHAR_CARRIAGE_RETURN: - gST->ConOut->ClearScreen (gST->ConOut); - // - // Set boot resolution for normal boot - // - BdsSetConsoleMode (FALSE); - BootFromSelectOption (BootOption, BootOptionCount, BootMenuData.SelectItem); - // - // Back to boot manager menu again, set back to setup resolution - // - BdsSetConsoleMode (TRUE); - DrawBootPopupMenu (&BootMenuData); - break; - - default: - break; } } } + EfiBootManagerFreeLoadOptions (BootOption, BootOptionCount); FreePool (BootMenuData.PtrTokens); HiiRemovePackages (gStringPackHandle); return Status; - } diff --git a/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.h b/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.h index e38e87824d..876237df18 100644 --- a/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.h +++ b/MdeModulePkg/Application/BootManagerMenuApp/BootManagerMenu.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _BOOT_MANAGER_MENU_H_ #define _BOOT_MANAGER_MENU_H_ @@ -23,21 +22,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define TITLE_TOKEN_COUNT 1 -#define HELP_TOKEN_COUNT 3 +#define TITLE_TOKEN_COUNT 1 +#define HELP_TOKEN_COUNT 3 typedef struct _BOOT_MENU_SCREEN { - UINTN StartCol; - UINTN StartRow; - UINTN Width; - UINTN Height; + UINTN StartCol; + UINTN StartRow; + UINTN Width; + UINTN Height; } BOOT_MENU_SCREEN; typedef struct _BOOT_MENU_SCROLL_BAR_CONTROL { - BOOLEAN HasScrollBar; - UINTN ItemCountPerScreen; - UINTN FirstItem; - UINTN LastItem; + BOOLEAN HasScrollBar; + UINTN ItemCountPerScreen; + UINTN FirstItem; + UINTN LastItem; } BOOT_MENU_SCROLL_BAR_CONTROL; typedef struct _BOOT_MENU_POPUP_DATA { @@ -51,4 +50,3 @@ typedef struct _BOOT_MENU_POPUP_DATA { } BOOT_MENU_POPUP_DATA; #endif - diff --git a/MdeModulePkg/Application/CapsuleApp/AppSupport.c b/MdeModulePkg/Application/CapsuleApp/AppSupport.c index 8fe70dc3b6..3b98ad07bf 100644 --- a/MdeModulePkg/Application/CapsuleApp/AppSupport.c +++ b/MdeModulePkg/Application/CapsuleApp/AppSupport.c @@ -8,9 +8,9 @@ #include "CapsuleApp.h" -UINTN Argc; -CHAR16 **Argv; -EFI_SHELL_PROTOCOL *mShellProtocol = NULL; +UINTN Argc; +CHAR16 **Argv; +EFI_SHELL_PROTOCOL *mShellProtocol = NULL; /** @@ -23,15 +23,15 @@ GetArg ( VOID ) { - EFI_STATUS Status; - EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters; + EFI_STATUS Status; + EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters; Status = gBS->HandleProtocol ( gImageHandle, &gEfiShellParametersProtocolGuid, - (VOID**)&ShellParameters + (VOID **)&ShellParameters ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -50,13 +50,13 @@ GetShellProtocol ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; if (mShellProtocol == NULL) { Status = gBS->LocateProtocol ( &gEfiShellProtocolGuid, NULL, - (VOID **) &mShellProtocol + (VOID **)&mShellProtocol ); if (EFI_ERROR (Status)) { mShellProtocol = NULL; @@ -79,19 +79,19 @@ GetShellProtocol ( **/ EFI_STATUS ReadFileToBuffer ( - IN CHAR16 *FileName, - OUT UINTN *BufferSize, - OUT VOID **Buffer + IN CHAR16 *FileName, + OUT UINTN *BufferSize, + OUT VOID **Buffer ) { - EFI_STATUS Status; - EFI_SHELL_PROTOCOL *ShellProtocol; - SHELL_FILE_HANDLE Handle; - UINT64 FileSize; - UINTN TempBufferSize; - VOID *TempBuffer; - - ShellProtocol = GetShellProtocol(); + EFI_STATUS Status; + EFI_SHELL_PROTOCOL *ShellProtocol; + SHELL_FILE_HANDLE Handle; + UINT64 FileSize; + UINTN TempBufferSize; + VOID *TempBuffer; + + ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { return EFI_NOT_FOUND; } @@ -117,8 +117,8 @@ ReadFileToBuffer ( return Status; } - TempBufferSize = (UINTN) FileSize; - TempBuffer = AllocateZeroPool (TempBufferSize); + TempBufferSize = (UINTN)FileSize; + TempBuffer = AllocateZeroPool (TempBufferSize); if (TempBuffer == NULL) { ShellProtocol->CloseFile (Handle); return EFI_OUT_OF_RESOURCES; @@ -157,18 +157,18 @@ ReadFileToBuffer ( **/ EFI_STATUS WriteFileFromBuffer ( - IN CHAR16 *FileName, - IN UINTN BufferSize, - IN VOID *Buffer + IN CHAR16 *FileName, + IN UINTN BufferSize, + IN VOID *Buffer ) { - EFI_STATUS Status; - EFI_SHELL_PROTOCOL *ShellProtocol; - SHELL_FILE_HANDLE Handle; - EFI_FILE_INFO *FileInfo; - UINTN TempBufferSize; + EFI_STATUS Status; + EFI_SHELL_PROTOCOL *ShellProtocol; + SHELL_FILE_HANDLE Handle; + EFI_FILE_INFO *FileInfo; + UINTN TempBufferSize; - ShellProtocol = GetShellProtocol(); + ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { return EFI_NOT_FOUND; } @@ -202,24 +202,25 @@ WriteFileFromBuffer ( // Set the file size to 0. // FileInfo->FileSize = 0; - Status = ShellProtocol->SetFileInfo (Handle, FileInfo); + Status = ShellProtocol->SetFileInfo (Handle, FileInfo); if (EFI_ERROR (Status)) { FreePool (FileInfo); ShellProtocol->CloseFile (Handle); return Status; } } + FreePool (FileInfo); // // Write the file data from the buffer // TempBufferSize = BufferSize; - Status = ShellProtocol->WriteFile ( - Handle, - &TempBufferSize, - Buffer - ); + Status = ShellProtocol->WriteFile ( + Handle, + &TempBufferSize, + Buffer + ); if (EFI_ERROR (Status)) { ShellProtocol->CloseFile (Handle); return Status; @@ -229,4 +230,3 @@ WriteFileFromBuffer ( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Application/CapsuleApp/CapsuleApp.c b/MdeModulePkg/Application/CapsuleApp/CapsuleApp.c index 4034714773..d6fb9283d3 100644 --- a/MdeModulePkg/Application/CapsuleApp/CapsuleApp.c +++ b/MdeModulePkg/Application/CapsuleApp/CapsuleApp.c @@ -27,52 +27,54 @@ CreateBmpFmp ( VOID ) { - CHAR16 *OutputCapsuleName; - VOID *BmpBuffer; - UINTN FileSize; - CHAR16 *BmpName; - UINT8 *FullCapsuleBuffer; - UINTN FullCapsuleBufferSize; - EFI_DISPLAY_CAPSULE *DisplayCapsule; - EFI_STATUS Status; - EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop; - EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *GopBlt; - UINTN GopBltSize; - UINTN Height; - UINTN Width; - - Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: NO GOP is found.\n"); + CHAR16 *OutputCapsuleName; + VOID *BmpBuffer; + UINTN FileSize; + CHAR16 *BmpName; + UINT8 *FullCapsuleBuffer; + UINTN FullCapsuleBufferSize; + EFI_DISPLAY_CAPSULE *DisplayCapsule; + EFI_STATUS Status; + EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop; + EFI_GRAPHICS_OUTPUT_MODE_INFORMATION *Info; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *GopBlt; + UINTN GopBltSize; + UINTN Height; + UINTN Width; + + Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&Gop); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: NO GOP is found.\n"); return EFI_UNSUPPORTED; } + Info = Gop->Mode->Info; - Print(L"Current GOP: Mode - %d, ", Gop->Mode->Mode); - Print(L"HorizontalResolution - %d, ", Info->HorizontalResolution); - Print(L"VerticalResolution - %d\n", Info->VerticalResolution); + Print (L"Current GOP: Mode - %d, ", Gop->Mode->Mode); + Print (L"HorizontalResolution - %d, ", Info->HorizontalResolution); + Print (L"VerticalResolution - %d\n", Info->VerticalResolution); // HorizontalResolution >= BMP_IMAGE_HEADER.PixelWidth // VerticalResolution >= BMP_IMAGE_HEADER.PixelHeight if (Argc != 5) { - Print(L"CapsuleApp: Incorrect parameter count.\n"); + Print (L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } - if (StrCmp(Argv[3], L"-O") != 0) { - Print(L"CapsuleApp: NO output capsule name.\n"); + if (StrCmp (Argv[3], L"-O") != 0) { + Print (L"CapsuleApp: NO output capsule name.\n"); return EFI_UNSUPPORTED; } + OutputCapsuleName = Argv[4]; - BmpBuffer = NULL; - FileSize = 0; + BmpBuffer = NULL; + FileSize = 0; FullCapsuleBuffer = NULL; BmpName = Argv[2]; - Status = ReadFileToBuffer(BmpName, &FileSize, &BmpBuffer); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: BMP image (%s) is not found.\n", BmpName); + Status = ReadFileToBuffer (BmpName, &FileSize, &BmpBuffer); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: BMP image (%s) is not found.\n", BmpName); goto Done; } @@ -85,45 +87,48 @@ CreateBmpFmp ( &Height, &Width ); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: BMP image (%s) is not valid.\n", BmpName); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: BMP image (%s) is not valid.\n", BmpName); goto Done; } + if (GopBlt != NULL) { FreePool (GopBlt); } - Print(L"BMP image (%s), Width - %d, Height - %d\n", BmpName, Width, Height); + + Print (L"BMP image (%s), Width - %d, Height - %d\n", BmpName, Width, Height); if (Height > Info->VerticalResolution) { Status = EFI_INVALID_PARAMETER; - Print(L"CapsuleApp: BMP image (%s) height is larger than current resolution.\n", BmpName); + Print (L"CapsuleApp: BMP image (%s) height is larger than current resolution.\n", BmpName); goto Done; } + if (Width > Info->HorizontalResolution) { Status = EFI_INVALID_PARAMETER; - Print(L"CapsuleApp: BMP image (%s) width is larger than current resolution.\n", BmpName); + Print (L"CapsuleApp: BMP image (%s) width is larger than current resolution.\n", BmpName); goto Done; } - FullCapsuleBufferSize = sizeof(EFI_DISPLAY_CAPSULE) + FileSize; - FullCapsuleBuffer = AllocatePool(FullCapsuleBufferSize); + FullCapsuleBufferSize = sizeof (EFI_DISPLAY_CAPSULE) + FileSize; + FullCapsuleBuffer = AllocatePool (FullCapsuleBufferSize); if (FullCapsuleBuffer == NULL) { - Print(L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); + Print (L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); Status = EFI_OUT_OF_RESOURCES; goto Done; } DisplayCapsule = (EFI_DISPLAY_CAPSULE *)FullCapsuleBuffer; - CopyGuid(&DisplayCapsule->CapsuleHeader.CapsuleGuid, &gWindowsUxCapsuleGuid); - DisplayCapsule->CapsuleHeader.HeaderSize = sizeof(DisplayCapsule->CapsuleHeader); - DisplayCapsule->CapsuleHeader.Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; + CopyGuid (&DisplayCapsule->CapsuleHeader.CapsuleGuid, &gWindowsUxCapsuleGuid); + DisplayCapsule->CapsuleHeader.HeaderSize = sizeof (DisplayCapsule->CapsuleHeader); + DisplayCapsule->CapsuleHeader.Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; DisplayCapsule->CapsuleHeader.CapsuleImageSize = (UINT32)FullCapsuleBufferSize; - DisplayCapsule->ImagePayload.Version = 1; - DisplayCapsule->ImagePayload.Checksum = 0; + DisplayCapsule->ImagePayload.Version = 1; + DisplayCapsule->ImagePayload.Checksum = 0; DisplayCapsule->ImagePayload.ImageType = 0; // BMP - DisplayCapsule->ImagePayload.Reserved = 0; - DisplayCapsule->ImagePayload.Mode = Gop->Mode->Mode; + DisplayCapsule->ImagePayload.Reserved = 0; + DisplayCapsule->ImagePayload.Mode = Gop->Mode->Mode; // // Center the bitmap horizontally @@ -140,26 +145,27 @@ CreateBmpFmp ( (UINT32)(((3 * Info->VerticalResolution) - (2 * Height)) / 4) ); - Print(L"BMP image (%s), OffsetX - %d, OffsetY - %d\n", + Print ( + L"BMP image (%s), OffsetX - %d, OffsetY - %d\n", BmpName, DisplayCapsule->ImagePayload.OffsetX, DisplayCapsule->ImagePayload.OffsetY ); - CopyMem((DisplayCapsule + 1), BmpBuffer, FileSize); + CopyMem ((DisplayCapsule + 1), BmpBuffer, FileSize); - DisplayCapsule->ImagePayload.Checksum = CalculateCheckSum8(FullCapsuleBuffer, FullCapsuleBufferSize); + DisplayCapsule->ImagePayload.Checksum = CalculateCheckSum8 (FullCapsuleBuffer, FullCapsuleBufferSize); - Status = WriteFileFromBuffer(OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); - Print(L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); + Status = WriteFileFromBuffer (OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); + Print (L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); Done: if (BmpBuffer != NULL) { - FreePool(BmpBuffer); + FreePool (BmpBuffer); } if (FullCapsuleBuffer != NULL) { - FreePool(FullCapsuleBuffer); + FreePool (FullCapsuleBuffer); } return Status; @@ -174,18 +180,19 @@ Done: **/ EFI_GUID * GetCapsuleImageTypeId ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { - EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *FmpCapsuleHeader; - UINT64 *ItemOffsetList; - EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader; + EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *FmpCapsuleHeader; + UINT64 *ItemOffsetList; + EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader; FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); - ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); + ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); if (FmpCapsuleHeader->PayloadItemCount == 0) { return NULL; } + ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[FmpCapsuleHeader->EmbeddedDriverCount]); return &ImageHeader->UpdateImageTypeId; } @@ -199,7 +206,7 @@ GetCapsuleImageTypeId ( **/ UINT32 GetEsrtFwType ( - IN EFI_GUID *ImageTypeId + IN EFI_GUID *ImageTypeId ) { EFI_STATUS Status; @@ -210,12 +217,12 @@ GetEsrtFwType ( // // Check ESRT // - Status = EfiGetSystemConfigurationTable(&gEfiSystemResourceTableGuid, (VOID **)&Esrt); - if (!EFI_ERROR(Status)) { - ASSERT(Esrt != NULL); + Status = EfiGetSystemConfigurationTable (&gEfiSystemResourceTableGuid, (VOID **)&Esrt); + if (!EFI_ERROR (Status)) { + ASSERT (Esrt != NULL); EsrtEntry = (VOID *)(Esrt + 1); for (Index = 0; Index < Esrt->FwResourceCount; Index++, EsrtEntry++) { - if (CompareGuid(&EsrtEntry->FwClass, ImageTypeId)) { + if (CompareGuid (&EsrtEntry->FwClass, ImageTypeId)) { return EsrtEntry->FwType; } } @@ -238,19 +245,22 @@ GetEsrtFwType ( **/ BOOLEAN IsValidCapsuleHeader ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - IN UINT64 CapsuleSize + IN EFI_CAPSULE_HEADER *CapsuleHeader, + IN UINT64 CapsuleSize ) { if (CapsuleSize < sizeof (EFI_CAPSULE_HEADER)) { return FALSE; } + if (CapsuleHeader->CapsuleImageSize != CapsuleSize) { return FALSE; } + if (CapsuleHeader->HeaderSize > CapsuleHeader->CapsuleImageSize) { return FALSE; } + if (CapsuleHeader->HeaderSize < sizeof (EFI_CAPSULE_HEADER)) { return FALSE; } @@ -271,7 +281,7 @@ IsFmpCapsuleGuid ( IN EFI_GUID *CapsuleGuid ) { - if (CompareGuid(&gEfiFmpCapsuleGuid, CapsuleGuid)) { + if (CompareGuid (&gEfiFmpCapsuleGuid, CapsuleGuid)) { return TRUE; } @@ -291,96 +301,98 @@ CreateNestedFmp ( VOID ) { - CHAR16 *OutputCapsuleName; - VOID *CapsuleBuffer; - UINTN FileSize; - CHAR16 *CapsuleName; - UINT8 *FullCapsuleBuffer; - UINTN FullCapsuleBufferSize; - EFI_CAPSULE_HEADER *NestedCapsuleHeader; - EFI_GUID *ImageTypeId; - UINT32 FwType; - EFI_STATUS Status; + CHAR16 *OutputCapsuleName; + VOID *CapsuleBuffer; + UINTN FileSize; + CHAR16 *CapsuleName; + UINT8 *FullCapsuleBuffer; + UINTN FullCapsuleBufferSize; + EFI_CAPSULE_HEADER *NestedCapsuleHeader; + EFI_GUID *ImageTypeId; + UINT32 FwType; + EFI_STATUS Status; if (Argc != 5) { - Print(L"CapsuleApp: Incorrect parameter count.\n"); + Print (L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } - if (StrCmp(Argv[3], L"-O") != 0) { - Print(L"CapsuleApp: NO output capsule name.\n"); + if (StrCmp (Argv[3], L"-O") != 0) { + Print (L"CapsuleApp: NO output capsule name.\n"); return EFI_UNSUPPORTED; } + OutputCapsuleName = Argv[4]; - CapsuleBuffer = NULL; - FileSize = 0; + CapsuleBuffer = NULL; + FileSize = 0; FullCapsuleBuffer = NULL; CapsuleName = Argv[2]; - Status = ReadFileToBuffer(CapsuleName, &FileSize, &CapsuleBuffer); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: Capsule image (%s) is not found.\n", CapsuleName); + Status = ReadFileToBuffer (CapsuleName, &FileSize, &CapsuleBuffer); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: Capsule image (%s) is not found.\n", CapsuleName); goto Done; } + if (!IsValidCapsuleHeader (CapsuleBuffer, FileSize)) { - Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); + Print (L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); Status = EFI_INVALID_PARAMETER; goto Done; } - if (!IsFmpCapsuleGuid (&((EFI_CAPSULE_HEADER *) CapsuleBuffer)->CapsuleGuid)) { - Print(L"CapsuleApp: Capsule image (%s) is not a FMP capsule.\n", CapsuleName); + if (!IsFmpCapsuleGuid (&((EFI_CAPSULE_HEADER *)CapsuleBuffer)->CapsuleGuid)) { + Print (L"CapsuleApp: Capsule image (%s) is not a FMP capsule.\n", CapsuleName); Status = EFI_INVALID_PARAMETER; goto Done; } - ImageTypeId = GetCapsuleImageTypeId(CapsuleBuffer); + ImageTypeId = GetCapsuleImageTypeId (CapsuleBuffer); if (ImageTypeId == NULL) { - Print(L"CapsuleApp: Capsule ImageTypeId is not found.\n"); + Print (L"CapsuleApp: Capsule ImageTypeId is not found.\n"); Status = EFI_INVALID_PARAMETER; goto Done; } - FwType = GetEsrtFwType(ImageTypeId); + + FwType = GetEsrtFwType (ImageTypeId); if ((FwType != ESRT_FW_TYPE_SYSTEMFIRMWARE) && (FwType != ESRT_FW_TYPE_DEVICEFIRMWARE)) { - Print(L"CapsuleApp: Capsule FwType is invalid.\n"); + Print (L"CapsuleApp: Capsule FwType is invalid.\n"); Status = EFI_INVALID_PARAMETER; goto Done; } FullCapsuleBufferSize = NESTED_CAPSULE_HEADER_SIZE + FileSize; - FullCapsuleBuffer = AllocatePool(FullCapsuleBufferSize); + FullCapsuleBuffer = AllocatePool (FullCapsuleBufferSize); if (FullCapsuleBuffer == NULL) { - Print(L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); + Print (L"CapsuleApp: Capsule Buffer size (0x%x) too big.\n", FullCapsuleBufferSize); Status = EFI_OUT_OF_RESOURCES; goto Done; } NestedCapsuleHeader = (EFI_CAPSULE_HEADER *)FullCapsuleBuffer; - ZeroMem(NestedCapsuleHeader, NESTED_CAPSULE_HEADER_SIZE); - CopyGuid(&NestedCapsuleHeader->CapsuleGuid, ImageTypeId); - NestedCapsuleHeader->HeaderSize = NESTED_CAPSULE_HEADER_SIZE; - NestedCapsuleHeader->Flags = (FwType == ESRT_FW_TYPE_SYSTEMFIRMWARE) ? SYSTEM_FIRMWARE_FLAG : DEVICE_FIRMWARE_FLAG; + ZeroMem (NestedCapsuleHeader, NESTED_CAPSULE_HEADER_SIZE); + CopyGuid (&NestedCapsuleHeader->CapsuleGuid, ImageTypeId); + NestedCapsuleHeader->HeaderSize = NESTED_CAPSULE_HEADER_SIZE; + NestedCapsuleHeader->Flags = (FwType == ESRT_FW_TYPE_SYSTEMFIRMWARE) ? SYSTEM_FIRMWARE_FLAG : DEVICE_FIRMWARE_FLAG; NestedCapsuleHeader->CapsuleImageSize = (UINT32)FullCapsuleBufferSize; - CopyMem((UINT8 *)NestedCapsuleHeader + NestedCapsuleHeader->HeaderSize, CapsuleBuffer, FileSize); + CopyMem ((UINT8 *)NestedCapsuleHeader + NestedCapsuleHeader->HeaderSize, CapsuleBuffer, FileSize); - Status = WriteFileFromBuffer(OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); - Print(L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); + Status = WriteFileFromBuffer (OutputCapsuleName, FullCapsuleBufferSize, FullCapsuleBuffer); + Print (L"CapsuleApp: Write %s %r\n", OutputCapsuleName, Status); Done: if (CapsuleBuffer != NULL) { - FreePool(CapsuleBuffer); + FreePool (CapsuleBuffer); } if (FullCapsuleBuffer != NULL) { - FreePool(FullCapsuleBuffer); + FreePool (FullCapsuleBuffer); } return Status; } - /** Clear capsule status variable. @@ -391,19 +403,19 @@ ClearCapsuleStatusVariable ( VOID ) { - EFI_STATUS Status; - UINT32 Index; - CHAR16 CapsuleVarName[20]; - CHAR16 *TempVarName; - BOOLEAN Found; + EFI_STATUS Status; + UINT32 Index; + CHAR16 CapsuleVarName[20]; + CHAR16 *TempVarName; + BOOLEAN Found; - StrCpyS (CapsuleVarName, sizeof(CapsuleVarName)/sizeof(CapsuleVarName[0]), L"Capsule"); + StrCpyS (CapsuleVarName, sizeof (CapsuleVarName)/sizeof (CapsuleVarName[0]), L"Capsule"); TempVarName = CapsuleVarName + StrLen (CapsuleVarName); - Index = 0; + Index = 0; Found = FALSE; while (TRUE) { - UnicodeSPrint (TempVarName, 5 * sizeof(CHAR16), L"%04x", Index); + UnicodeSPrint (TempVarName, 5 * sizeof (CHAR16), L"%04x", Index); Status = gRT->SetVariable ( CapsuleVarName, @@ -418,6 +430,7 @@ ClearCapsuleStatusVariable ( // break; } + Found = TRUE; Print (L"Clear %s %r\n", CapsuleVarName, Status); @@ -447,10 +460,10 @@ ClearCapsuleStatusVariable ( **/ EFI_STATUS BuildGatherList ( - IN VOID **CapsuleBuffer, - IN UINTN *FileSize, - IN UINTN CapsuleNum, - OUT EFI_CAPSULE_BLOCK_DESCRIPTOR **BlockDescriptors + IN VOID **CapsuleBuffer, + IN UINTN *FileSize, + IN UINTN CapsuleNum, + OUT EFI_CAPSULE_BLOCK_DESCRIPTOR **BlockDescriptors ) { EFI_STATUS Status; @@ -482,15 +495,15 @@ BuildGatherList ( Count = (INT32)(NumberOfDescriptors + 2) / 2; } - Size = Count * sizeof (EFI_CAPSULE_BLOCK_DESCRIPTOR); - BlockDescriptors1 = AllocateRuntimeZeroPool (Size); + Size = Count * sizeof (EFI_CAPSULE_BLOCK_DESCRIPTOR); + BlockDescriptors1 = AllocateRuntimeZeroPool (Size); if (BlockDescriptors1 == NULL) { Print (L"CapsuleApp: failed to allocate memory for descriptors\n"); Status = EFI_OUT_OF_RESOURCES; goto ERREXIT; } else { - Print (L"CapsuleApp: creating capsule descriptors at 0x%X\n", (UINTN) BlockDescriptors1); - Print (L"CapsuleApp: capsule data starts at 0x%X with size 0x%X\n", (UINTN) CapsuleBuffer[Index], FileSize[Index]); + Print (L"CapsuleApp: creating capsule descriptors at 0x%X\n", (UINTN)BlockDescriptors1); + Print (L"CapsuleApp: capsule data starts at 0x%X with size 0x%X\n", (UINTN)CapsuleBuffer[Index], FileSize[Index]); } // @@ -501,16 +514,16 @@ BuildGatherList ( } if (BlockDescriptorPre != NULL) { - BlockDescriptorPre->Union.ContinuationPointer = (UINTN) BlockDescriptors1; - BlockDescriptorPre->Length = 0; + BlockDescriptorPre->Union.ContinuationPointer = (UINTN)BlockDescriptors1; + BlockDescriptorPre->Length = 0; } // // Fill them in // - TempBlockPtr = BlockDescriptors1; - TempDataPtr = CapsuleBuffer[Index]; - SizeLeft = FileSize[Index]; + TempBlockPtr = BlockDescriptors1; + TempDataPtr = CapsuleBuffer[Index]; + SizeLeft = FileSize[Index]; for (Number = 0; (Number < Count - 1) && (SizeLeft != 0); Number++) { // // Divide remaining data in half @@ -524,10 +537,11 @@ BuildGatherList ( } else { Size = SizeLeft; } - TempBlockPtr->Union.DataBlock = (UINTN)TempDataPtr; - TempBlockPtr->Length = Size; - Print (L"CapsuleApp: capsule block/size 0x%X/0x%X\n", (UINTN) TempDataPtr, Size); - SizeLeft -= Size; + + TempBlockPtr->Union.DataBlock = (UINTN)TempDataPtr; + TempBlockPtr->Length = Size; + Print (L"CapsuleApp: capsule block/size 0x%X/0x%X\n", (UINTN)TempDataPtr, Size); + SizeLeft -= Size; TempDataPtr += Size; TempBlockPtr++; } @@ -555,10 +569,10 @@ BuildGatherList ( // // Point the first list's last element to point to this second list. // - TempBlockPtr->Union.ContinuationPointer = (UINTN) BlockDescriptors2; + TempBlockPtr->Union.ContinuationPointer = (UINTN)BlockDescriptors2; - TempBlockPtr->Length = 0; - TempBlockPtr = BlockDescriptors2; + TempBlockPtr->Length = 0; + TempBlockPtr = BlockDescriptors2; for (Number = 0; Number < Count - 1; Number++) { // // If second-to-last one, then dump rest to this element @@ -576,10 +590,10 @@ BuildGatherList ( } } - TempBlockPtr->Union.DataBlock = (UINTN)TempDataPtr; - TempBlockPtr->Length = Size; - Print (L"CapsuleApp: capsule block/size 0x%X/0x%X\n", (UINTN) TempDataPtr, Size); - SizeLeft -= Size; + TempBlockPtr->Union.DataBlock = (UINTN)TempDataPtr; + TempBlockPtr->Length = Size; + Print (L"CapsuleApp: capsule block/size 0x%X/0x%X\n", (UINTN)TempDataPtr, Size); + SizeLeft -= Size; TempDataPtr += Size; TempBlockPtr++; if (SizeLeft == 0) { @@ -596,20 +610,20 @@ BuildGatherList ( // Null-terminate. // if (TempBlockPtr != NULL) { - TempBlockPtr->Union.ContinuationPointer = (UINTN)NULL; - TempBlockPtr->Length = 0; - *BlockDescriptors = BlockDescriptorsHeader; + TempBlockPtr->Union.ContinuationPointer = (UINTN)NULL; + TempBlockPtr->Length = 0; + *BlockDescriptors = BlockDescriptorsHeader; } return EFI_SUCCESS; ERREXIT: if (BlockDescriptors1 != NULL) { - FreePool(BlockDescriptors1); + FreePool (BlockDescriptors1); } if (BlockDescriptors2 != NULL) { - FreePool(BlockDescriptors2); + FreePool (BlockDescriptors2); } return Status; @@ -623,18 +637,18 @@ ERREXIT: **/ VOID CleanGatherList ( - IN EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors, - IN UINTN CapsuleNum + IN EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors, + IN UINTN CapsuleNum ) { - EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr; - EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr1; - EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr2; - UINTN Index; + EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr; + EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr1; + EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr2; + UINTN Index; if (BlockDescriptors != NULL) { TempBlockPtr1 = BlockDescriptors; - while (1){ + while (1) { TempBlockPtr = TempBlockPtr1; for (Index = 0; Index < CapsuleNum; Index++) { if (TempBlockPtr[Index].Length == 0) { @@ -646,8 +660,8 @@ CleanGatherList ( break; } - TempBlockPtr2 = (VOID *) ((UINTN) TempBlockPtr[Index].Union.ContinuationPointer); - FreePool(TempBlockPtr1); + TempBlockPtr2 = (VOID *)((UINTN)TempBlockPtr[Index].Union.ContinuationPointer); + FreePool (TempBlockPtr1); TempBlockPtr1 = TempBlockPtr2; } } @@ -661,42 +675,42 @@ PrintUsage ( VOID ) { - Print(L"CapsuleApp: usage\n"); - Print(L" CapsuleApp [-NR] [-OD [FSx]]\n"); - Print(L" CapsuleApp -S\n"); - Print(L" CapsuleApp -C\n"); - Print(L" CapsuleApp -P\n"); - Print(L" CapsuleApp -E\n"); - Print(L" CapsuleApp -L\n"); - Print(L" CapsuleApp -L INFO\n"); - Print(L" CapsuleApp -F\n"); - Print(L" CapsuleApp -G -O \n"); - Print(L" CapsuleApp -N -O \n"); - Print(L" CapsuleApp -D \n"); - Print(L" CapsuleApp -P GET -O \n"); - Print(L"Parameter:\n"); - Print(L" -NR: No reset will be triggered for the capsule\n"); - Print(L" with CAPSULE_FLAGS_PERSIST_ACROSS_RESET and without CAPSULE_FLAGS_INITIATE_RESET.\n"); - Print(L" -OD: Delivery of Capsules via file on Mass Storage device.\n"); - Print(L" -S: Dump capsule report variable (EFI_CAPSULE_REPORT_GUID),\n"); - Print(L" which is defined in UEFI specification.\n"); - Print(L" -C: Clear capsule report variable (EFI_CAPSULE_REPORT_GUID),\n"); - Print(L" which is defined in UEFI specification.\n"); - Print(L" -P: Dump UEFI FMP protocol info, or get image with specified\n"); - Print(L" ImageTypeId and Index (decimal format) to a file if 'GET'\n"); - Print(L" option is used.\n"); - Print(L" -E: Dump UEFI ESRT table info.\n"); - Print(L" -L: Dump provisioned capsule image information.\n"); - Print(L" -F: Dump all EFI System Partition.\n"); - Print(L" -G: Convert a BMP file to be an UX capsule,\n"); - Print(L" according to Windows Firmware Update document\n"); - Print(L" -N: Append a Capsule Header to an existing FMP capsule image\n"); - Print(L" with its ImageTypeId supported by the system,\n"); - Print(L" according to Windows Firmware Update document\n"); - Print(L" -O: Output new Capsule file name\n"); - Print(L" -D: Dump Capsule image header information, image payload\n"); - Print(L" information if it is an UX capsule and FMP header\n"); - Print(L" information if it is a FMP capsule.\n"); + Print (L"CapsuleApp: usage\n"); + Print (L" CapsuleApp [-NR] [-OD [FSx]]\n"); + Print (L" CapsuleApp -S\n"); + Print (L" CapsuleApp -C\n"); + Print (L" CapsuleApp -P\n"); + Print (L" CapsuleApp -E\n"); + Print (L" CapsuleApp -L\n"); + Print (L" CapsuleApp -L INFO\n"); + Print (L" CapsuleApp -F\n"); + Print (L" CapsuleApp -G -O \n"); + Print (L" CapsuleApp -N -O \n"); + Print (L" CapsuleApp -D \n"); + Print (L" CapsuleApp -P GET -O \n"); + Print (L"Parameter:\n"); + Print (L" -NR: No reset will be triggered for the capsule\n"); + Print (L" with CAPSULE_FLAGS_PERSIST_ACROSS_RESET and without CAPSULE_FLAGS_INITIATE_RESET.\n"); + Print (L" -OD: Delivery of Capsules via file on Mass Storage device.\n"); + Print (L" -S: Dump capsule report variable (EFI_CAPSULE_REPORT_GUID),\n"); + Print (L" which is defined in UEFI specification.\n"); + Print (L" -C: Clear capsule report variable (EFI_CAPSULE_REPORT_GUID),\n"); + Print (L" which is defined in UEFI specification.\n"); + Print (L" -P: Dump UEFI FMP protocol info, or get image with specified\n"); + Print (L" ImageTypeId and Index (decimal format) to a file if 'GET'\n"); + Print (L" option is used.\n"); + Print (L" -E: Dump UEFI ESRT table info.\n"); + Print (L" -L: Dump provisioned capsule image information.\n"); + Print (L" -F: Dump all EFI System Partition.\n"); + Print (L" -G: Convert a BMP file to be an UX capsule,\n"); + Print (L" according to Windows Firmware Update document\n"); + Print (L" -N: Append a Capsule Header to an existing FMP capsule image\n"); + Print (L" with its ImageTypeId supported by the system,\n"); + Print (L" according to Windows Firmware Update document\n"); + Print (L" -O: Output new Capsule file name\n"); + Print (L" -D: Dump Capsule image header information, image payload\n"); + Print (L" information if it is an UX capsule and FMP header\n"); + Print (L" information if it is a FMP capsule.\n"); } /** @@ -738,54 +752,63 @@ UefiMain ( EFI_GUID ImageTypeId; UINTN ImageIndex; - BlockDescriptors = NULL; - MapFsStr = NULL; - CapsuleNum = 0; + BlockDescriptors = NULL; + MapFsStr = NULL; + CapsuleNum = 0; - Status = GetArg(); - if (EFI_ERROR(Status)) { - Print(L"Please use UEFI SHELL to run this application!\n", Status); + Status = GetArg (); + if (EFI_ERROR (Status)) { + Print (L"Please use UEFI SHELL to run this application!\n", Status); return Status; } + if (Argc < 2) { - PrintUsage(); + PrintUsage (); return EFI_UNSUPPORTED; } - if (StrCmp(Argv[1], L"-D") == 0) { + + if (StrCmp (Argv[1], L"-D") == 0) { if (Argc != 3) { - Print(L"CapsuleApp: Incorrect parameter count.\n"); + Print (L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } - Status = DumpCapsule(Argv[2]); + + Status = DumpCapsule (Argv[2]); return Status; } - if (StrCmp(Argv[1], L"-G") == 0) { - Status = CreateBmpFmp(); + + if (StrCmp (Argv[1], L"-G") == 0) { + Status = CreateBmpFmp (); return Status; } - if (StrCmp(Argv[1], L"-N") == 0) { - Status = CreateNestedFmp(); + + if (StrCmp (Argv[1], L"-N") == 0) { + Status = CreateNestedFmp (); return Status; } - if (StrCmp(Argv[1], L"-S") == 0) { - Status = DumpCapsuleStatusVariable(); + + if (StrCmp (Argv[1], L"-S") == 0) { + Status = DumpCapsuleStatusVariable (); return EFI_SUCCESS; } - if (StrCmp(Argv[1], L"-C") == 0) { - Status = ClearCapsuleStatusVariable(); + + if (StrCmp (Argv[1], L"-C") == 0) { + Status = ClearCapsuleStatusVariable (); return Status; } - if (StrCmp(Argv[1], L"-P") == 0) { + + if (StrCmp (Argv[1], L"-P") == 0) { if (Argc == 2) { - DumpFmpData(); + DumpFmpData (); } + if (Argc >= 3) { - if (StrCmp(Argv[2], L"GET") != 0) { - Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[2]); + if (StrCmp (Argv[2], L"GET") != 0) { + Print (L"CapsuleApp: Unrecognized option(%s).\n", Argv[2]); return EFI_UNSUPPORTED; } else { if (Argc != 7) { - Print(L"CapsuleApp: Incorrect parameter count.\n"); + Print (L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } @@ -797,54 +820,58 @@ UefiMain ( Print (L"Invalid ImageTypeId - %s\n", Argv[3]); return EFI_INVALID_PARAMETER; } - ImageIndex = StrDecimalToUintn(Argv[4]); - if (StrCmp(Argv[5], L"-O") != 0) { - Print(L"CapsuleApp: NO output file name.\n"); + + ImageIndex = StrDecimalToUintn (Argv[4]); + if (StrCmp (Argv[5], L"-O") != 0) { + Print (L"CapsuleApp: NO output file name.\n"); return EFI_UNSUPPORTED; } - DumpFmpImage(&ImageTypeId, ImageIndex, Argv[6]); + + DumpFmpImage (&ImageTypeId, ImageIndex, Argv[6]); } } + return EFI_SUCCESS; } - if (StrCmp(Argv[1], L"-E") == 0) { - DumpEsrtData(); + if (StrCmp (Argv[1], L"-E") == 0) { + DumpEsrtData (); return EFI_SUCCESS; } - if (StrCmp(Argv[1], L"-L") == 0) { - if (Argc >= 3 && StrCmp(Argv[2], L"INFO") == 0) { - DumpProvisionedCapsule(TRUE); + if (StrCmp (Argv[1], L"-L") == 0) { + if ((Argc >= 3) && (StrCmp (Argv[2], L"INFO") == 0)) { + DumpProvisionedCapsule (TRUE); } else { - DumpProvisionedCapsule(FALSE); + DumpProvisionedCapsule (FALSE); } + return EFI_SUCCESS; } - if (StrCmp(Argv[1], L"-F") == 0) { - DumpAllEfiSysPartition(); + if (StrCmp (Argv[1], L"-F") == 0) { + DumpAllEfiSysPartition (); return EFI_SUCCESS; } if (Argv[1][0] == L'-') { - Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[1]); + Print (L"CapsuleApp: Unrecognized option(%s).\n", Argv[1]); return EFI_UNSUPPORTED; } CapsuleFirstIndex = 1; - NoReset = FALSE; - CapsuleOnDisk = FALSE; - ParaOdIndex = 0; - ParaNrIndex = 0; + NoReset = FALSE; + CapsuleOnDisk = FALSE; + ParaOdIndex = 0; + ParaNrIndex = 0; for (Index = 1; Index < Argc; Index++) { - if (StrCmp(Argv[Index], L"-OD") == 0) { - ParaOdIndex = Index; + if (StrCmp (Argv[Index], L"-OD") == 0) { + ParaOdIndex = Index; CapsuleOnDisk = TRUE; - } else if (StrCmp(Argv[Index], L"-NR") == 0) { + } else if (StrCmp (Argv[Index], L"-NR") == 0) { ParaNrIndex = Index; - NoReset = TRUE; + NoReset = TRUE; } } @@ -886,37 +913,40 @@ UefiMain ( CapsuleNum = CapsuleLastIndex - CapsuleFirstIndex + 1; if (CapsuleFirstIndex > CapsuleLastIndex) { - Print(L"CapsuleApp: NO capsule image.\n"); + Print (L"CapsuleApp: NO capsule image.\n"); return EFI_UNSUPPORTED; } + if (CapsuleNum > MAX_CAPSULE_NUM) { - Print(L"CapsuleApp: Too many capsule images.\n"); + Print (L"CapsuleApp: Too many capsule images.\n"); return EFI_UNSUPPORTED; } - ZeroMem(&CapsuleBuffer, sizeof(CapsuleBuffer)); - ZeroMem(&CapsuleBufferSize, sizeof(CapsuleBufferSize)); + ZeroMem (&CapsuleBuffer, sizeof (CapsuleBuffer)); + ZeroMem (&CapsuleBufferSize, sizeof (CapsuleBufferSize)); BlockDescriptors = NULL; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleName = Argv[CapsuleFirstIndex + Index]; - Status = ReadFileToBuffer(CapsuleName, &CapsuleBufferSize[Index], &CapsuleBuffer[Index]); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: capsule image (%s) is not found.\n", CapsuleName); + Status = ReadFileToBuffer (CapsuleName, &CapsuleBufferSize[Index], &CapsuleBuffer[Index]); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: capsule image (%s) is not found.\n", CapsuleName); goto Done; } + if (!IsValidCapsuleHeader (CapsuleBuffer[Index], CapsuleBufferSize[Index])) { - Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); + Print (L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); return EFI_INVALID_PARAMETER; } + CapsuleNames[Index] = CapsuleName; } // // Every capsule use 2 descriptor 1 for data 1 for end // - Status = BuildGatherList(CapsuleBuffer, CapsuleBufferSize, CapsuleNum, &BlockDescriptors); - if (EFI_ERROR(Status)) { + Status = BuildGatherList (CapsuleBuffer, CapsuleBufferSize, CapsuleNum, &BlockDescriptors); + if (EFI_ERROR (Status)) { goto Done; } @@ -925,18 +955,19 @@ UefiMain ( // NeedReset = FALSE; for (Index = 0; Index < CapsuleNum; Index++) { - CapsuleHeaderArray[Index] = (EFI_CAPSULE_HEADER *) CapsuleBuffer[Index]; + CapsuleHeaderArray[Index] = (EFI_CAPSULE_HEADER *)CapsuleBuffer[Index]; if ((CapsuleHeaderArray[Index]->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { NeedReset = TRUE; } } + CapsuleHeaderArray[CapsuleNum] = NULL; // // Inquire platform capability of UpdateCapsule. // Status = gRT->QueryCapsuleCapabilities (CapsuleHeaderArray, CapsuleNum, &MaxCapsuleSize, &ResetType); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { Print (L"CapsuleApp: failed to query capsule capability - %r\n", Status); goto Done; } @@ -970,11 +1001,12 @@ UefiMain ( // Check whether the input capsule image has the flag of persist across system reset. // if (NeedReset) { - Status = gRT->UpdateCapsule(CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); + Status = gRT->UpdateCapsule (CapsuleHeaderArray, CapsuleNum, (UINTN)BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); goto Done; } + // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET + CAPSULE_FLAGS_INITIATE_RESET, // a system reset should have been triggered by gRT->UpdateCapsule() calling above. @@ -994,7 +1026,7 @@ UefiMain ( // For capsule who has no reset flag, only call UpdateCapsule Service without a // system reset. The service will process the capsule immediately. // - Status = gRT->UpdateCapsule (CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); + Status = gRT->UpdateCapsule (CapsuleHeaderArray, CapsuleNum, (UINTN)BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); } @@ -1009,7 +1041,7 @@ Done: } } - CleanGatherList(BlockDescriptors, CapsuleNum); + CleanGatherList (BlockDescriptors, CapsuleNum); return Status; } diff --git a/MdeModulePkg/Application/CapsuleApp/CapsuleApp.h b/MdeModulePkg/Application/CapsuleApp/CapsuleApp.h index 270d2359a3..255a2e0e1e 100644 --- a/MdeModulePkg/Application/CapsuleApp/CapsuleApp.h +++ b/MdeModulePkg/Application/CapsuleApp/CapsuleApp.h @@ -6,7 +6,6 @@ **/ - #ifndef _CAPSULE_APP_H_ #define _CAPSULE_APP_H_ @@ -42,22 +41,22 @@ #define CAPSULE_HEADER_SIZE 0x20 #define NESTED_CAPSULE_HEADER_SIZE SIZE_4KB -#define SYSTEM_FIRMWARE_FLAG 0x50000 -#define DEVICE_FIRMWARE_FLAG 0x78010 +#define SYSTEM_FIRMWARE_FLAG 0x50000 +#define DEVICE_FIRMWARE_FLAG 0x78010 -#define MAJOR_VERSION 1 -#define MINOR_VERSION 0 +#define MAJOR_VERSION 1 +#define MINOR_VERSION 0 -#define MAX_CAPSULE_NUM 10 +#define MAX_CAPSULE_NUM 10 // // (20 * (6+5+2))+1) unicode characters from EFI FAT spec (doubled for bytes) // -#define MAX_FILE_NAME_SIZE 522 -#define MAX_FILE_NAME_LEN (MAX_FILE_NAME_SIZE / sizeof(CHAR16)) +#define MAX_FILE_NAME_SIZE 522 +#define MAX_FILE_NAME_LEN (MAX_FILE_NAME_SIZE / sizeof(CHAR16)) -extern UINTN Argc; -extern CHAR16 **Argv; +extern UINTN Argc; +extern CHAR16 **Argv; /** @@ -81,7 +80,6 @@ GetShellProtocol ( VOID ); - /** Read a file. @@ -95,9 +93,9 @@ GetShellProtocol ( **/ EFI_STATUS ReadFileToBuffer ( - IN CHAR16 *FileName, - OUT UINTN *BufferSize, - OUT VOID **Buffer + IN CHAR16 *FileName, + OUT UINTN *BufferSize, + OUT VOID **Buffer ); /** @@ -113,12 +111,11 @@ ReadFileToBuffer ( **/ EFI_STATUS WriteFileFromBuffer ( - IN CHAR16 *FileName, - IN UINTN BufferSize, - IN VOID *Buffer + IN CHAR16 *FileName, + IN UINTN BufferSize, + IN VOID *Buffer ); - /** Dump capsule information @@ -129,7 +126,7 @@ WriteFileFromBuffer ( **/ EFI_STATUS DumpCapsule ( - IN CHAR16 *CapsuleName + IN CHAR16 *CapsuleName ); /** @@ -182,7 +179,7 @@ DumpEsrtData ( **/ VOID DumpProvisionedCapsule ( - IN BOOLEAN DumpCapsuleInfo + IN BOOLEAN DumpCapsuleInfo ); /** @@ -193,7 +190,6 @@ DumpAllEfiSysPartition ( VOID ); - /** Get SimpleFileSystem from boot option file path. @@ -213,7 +209,6 @@ GetEfiSysPartitionFromBootOptionFilePath ( OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs ); - /** Process Capsule On Disk. @@ -229,12 +224,11 @@ GetEfiSysPartitionFromBootOptionFilePath ( **/ EFI_STATUS ProcessCapsuleOnDisk ( - IN VOID **CapsuleBuffer, - IN UINTN *CapsuleBufferSize, - IN CHAR16 **FilePath, - IN CHAR16 *Map, - IN UINTN CapsuleNum + IN VOID **CapsuleBuffer, + IN UINTN *CapsuleBufferSize, + IN CHAR16 **FilePath, + IN CHAR16 *Map, + IN UINTN CapsuleNum ); #endif - diff --git a/MdeModulePkg/Application/CapsuleApp/CapsuleDump.c b/MdeModulePkg/Application/CapsuleApp/CapsuleDump.c index 5725e2f6dd..26ad60ce59 100644 --- a/MdeModulePkg/Application/CapsuleApp/CapsuleDump.c +++ b/MdeModulePkg/Application/CapsuleApp/CapsuleDump.c @@ -22,8 +22,8 @@ **/ BOOLEAN IsValidCapsuleHeader ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - IN UINT64 CapsuleSize + IN EFI_CAPSULE_HEADER *CapsuleHeader, + IN UINT64 CapsuleSize ); /** @@ -36,24 +36,24 @@ DumpUxCapsule ( IN EFI_CAPSULE_HEADER *CapsuleHeader ) { - EFI_DISPLAY_CAPSULE *DisplayCapsule; + EFI_DISPLAY_CAPSULE *DisplayCapsule; + DisplayCapsule = (EFI_DISPLAY_CAPSULE *)CapsuleHeader; - Print(L"[UxCapsule]\n"); - Print(L"CapsuleHeader:\n"); - Print(L" CapsuleGuid - %g\n", &DisplayCapsule->CapsuleHeader.CapsuleGuid); - Print(L" HeaderSize - 0x%x\n", DisplayCapsule->CapsuleHeader.HeaderSize); - Print(L" Flags - 0x%x\n", DisplayCapsule->CapsuleHeader.Flags); - Print(L" CapsuleImageSize - 0x%x\n", DisplayCapsule->CapsuleHeader.CapsuleImageSize); - Print(L"ImagePayload:\n"); - Print(L" Version - 0x%x\n", DisplayCapsule->ImagePayload.Version); - Print(L" Checksum - 0x%x\n", DisplayCapsule->ImagePayload.Checksum); - Print(L" ImageType - 0x%x\n", DisplayCapsule->ImagePayload.ImageType); - Print(L" Mode - 0x%x\n", DisplayCapsule->ImagePayload.Mode); - Print(L" OffsetX - 0x%x\n", DisplayCapsule->ImagePayload.OffsetX); - Print(L" OffsetY - 0x%x\n", DisplayCapsule->ImagePayload.OffsetY); + Print (L"[UxCapsule]\n"); + Print (L"CapsuleHeader:\n"); + Print (L" CapsuleGuid - %g\n", &DisplayCapsule->CapsuleHeader.CapsuleGuid); + Print (L" HeaderSize - 0x%x\n", DisplayCapsule->CapsuleHeader.HeaderSize); + Print (L" Flags - 0x%x\n", DisplayCapsule->CapsuleHeader.Flags); + Print (L" CapsuleImageSize - 0x%x\n", DisplayCapsule->CapsuleHeader.CapsuleImageSize); + Print (L"ImagePayload:\n"); + Print (L" Version - 0x%x\n", DisplayCapsule->ImagePayload.Version); + Print (L" Checksum - 0x%x\n", DisplayCapsule->ImagePayload.Checksum); + Print (L" ImageType - 0x%x\n", DisplayCapsule->ImagePayload.ImageType); + Print (L" Mode - 0x%x\n", DisplayCapsule->ImagePayload.Mode); + Print (L" OffsetX - 0x%x\n", DisplayCapsule->ImagePayload.OffsetX); + Print (L" OffsetY - 0x%x\n", DisplayCapsule->ImagePayload.OffsetY); } - /** Dump a non-nested FMP capsule. @@ -70,36 +70,36 @@ DumpFmpCapsule ( UINTN Count; EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *FmpImageHeader; - Print(L"[FmpCapsule]\n"); - Print(L"CapsuleHeader:\n"); - Print(L" CapsuleGuid - %g\n", &CapsuleHeader->CapsuleGuid); - Print(L" HeaderSize - 0x%x\n", CapsuleHeader->HeaderSize); - Print(L" Flags - 0x%x\n", CapsuleHeader->Flags); - Print(L" CapsuleImageSize - 0x%x\n", CapsuleHeader->CapsuleImageSize); + Print (L"[FmpCapsule]\n"); + Print (L"CapsuleHeader:\n"); + Print (L" CapsuleGuid - %g\n", &CapsuleHeader->CapsuleGuid); + Print (L" HeaderSize - 0x%x\n", CapsuleHeader->HeaderSize); + Print (L" Flags - 0x%x\n", CapsuleHeader->Flags); + Print (L" CapsuleImageSize - 0x%x\n", CapsuleHeader->CapsuleImageSize); FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); - ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); - Print(L"FmpHeader:\n"); - Print(L" Version - 0x%x\n", FmpCapsuleHeader->Version); - Print(L" EmbeddedDriverCount - 0x%x\n", FmpCapsuleHeader->EmbeddedDriverCount); - Print(L" PayloadItemCount - 0x%x\n", FmpCapsuleHeader->PayloadItemCount); + ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); + Print (L"FmpHeader:\n"); + Print (L" Version - 0x%x\n", FmpCapsuleHeader->Version); + Print (L" EmbeddedDriverCount - 0x%x\n", FmpCapsuleHeader->EmbeddedDriverCount); + Print (L" PayloadItemCount - 0x%x\n", FmpCapsuleHeader->PayloadItemCount); Count = FmpCapsuleHeader->EmbeddedDriverCount + FmpCapsuleHeader->PayloadItemCount; for (Index = 0; Index < Count; Index++) { - Print(L" Offset[%d] - 0x%x\n", Index, ItemOffsetList[Index]); + Print (L" Offset[%d] - 0x%x\n", Index, ItemOffsetList[Index]); } for (Index = FmpCapsuleHeader->EmbeddedDriverCount; Index < Count; Index++) { - Print(L"FmpPayload[%d] ImageHeader:\n", Index); + Print (L"FmpPayload[%d] ImageHeader:\n", Index); FmpImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); - Print(L" Version - 0x%x\n", FmpImageHeader->Version); - Print(L" UpdateImageTypeId - %g\n", &FmpImageHeader->UpdateImageTypeId); - Print(L" UpdateImageIndex - 0x%x\n", FmpImageHeader->UpdateImageIndex); - Print(L" UpdateImageSize - 0x%x\n", FmpImageHeader->UpdateImageSize); - Print(L" UpdateVendorCodeSize - 0x%x\n", FmpImageHeader->UpdateVendorCodeSize); + Print (L" Version - 0x%x\n", FmpImageHeader->Version); + Print (L" UpdateImageTypeId - %g\n", &FmpImageHeader->UpdateImageTypeId); + Print (L" UpdateImageIndex - 0x%x\n", FmpImageHeader->UpdateImageIndex); + Print (L" UpdateImageSize - 0x%x\n", FmpImageHeader->UpdateImageSize); + Print (L" UpdateVendorCodeSize - 0x%x\n", FmpImageHeader->UpdateVendorCodeSize); if (FmpImageHeader->Version >= 2) { - Print(L" UpdateHardwareInstance - 0x%lx\n", FmpImageHeader->UpdateHardwareInstance); + Print (L" UpdateHardwareInstance - 0x%lx\n", FmpImageHeader->UpdateHardwareInstance); if (FmpImageHeader->Version >= EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER_INIT_VERSION) { - Print(L" ImageCapsuleSupport - 0x%lx\n", FmpImageHeader->ImageCapsuleSupport); + Print (L" ImageCapsuleSupport - 0x%lx\n", FmpImageHeader->ImageCapsuleSupport); } } } @@ -115,7 +115,7 @@ DumpFmpCapsule ( **/ BOOLEAN IsNestedFmpCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { EFI_STATUS Status; @@ -130,12 +130,12 @@ IsNestedFmpCapsule ( // Check ESRT // EsrtGuidFound = FALSE; - Status = EfiGetSystemConfigurationTable(&gEfiSystemResourceTableGuid, (VOID **)&Esrt); - if (!EFI_ERROR(Status)) { + Status = EfiGetSystemConfigurationTable (&gEfiSystemResourceTableGuid, (VOID **)&Esrt); + if (!EFI_ERROR (Status)) { ASSERT (Esrt != NULL); EsrtEntry = (VOID *)(Esrt + 1); for (Index = 0; Index < Esrt->FwResourceCount; Index++, EsrtEntry++) { - if (CompareGuid(&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) { + if (CompareGuid (&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) { EsrtGuidFound = TRUE; break; } @@ -151,13 +151,15 @@ IsNestedFmpCapsule ( // FMP GUID after ESRT one // NestedCapsuleHeader = (EFI_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); - NestedCapsuleSize = (UINTN)CapsuleHeader + CapsuleHeader->CapsuleImageSize- (UINTN)NestedCapsuleHeader; - if (NestedCapsuleSize < sizeof(EFI_CAPSULE_HEADER)) { + NestedCapsuleSize = (UINTN)CapsuleHeader + CapsuleHeader->CapsuleImageSize- (UINTN)NestedCapsuleHeader; + if (NestedCapsuleSize < sizeof (EFI_CAPSULE_HEADER)) { return FALSE; } - if (!CompareGuid(&NestedCapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { + + if (!CompareGuid (&NestedCapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { return FALSE; } + return TRUE; } @@ -171,50 +173,53 @@ IsNestedFmpCapsule ( **/ EFI_STATUS DumpCapsule ( - IN CHAR16 *CapsuleName + IN CHAR16 *CapsuleName ) { - VOID *Buffer; - UINTN FileSize; - EFI_CAPSULE_HEADER *CapsuleHeader; - EFI_STATUS Status; + VOID *Buffer; + UINTN FileSize; + EFI_CAPSULE_HEADER *CapsuleHeader; + EFI_STATUS Status; Buffer = NULL; - Status = ReadFileToBuffer(CapsuleName, &FileSize, &Buffer); - if (EFI_ERROR(Status)) { - Print(L"CapsuleApp: Capsule (%s) is not found.\n", CapsuleName); + Status = ReadFileToBuffer (CapsuleName, &FileSize, &Buffer); + if (EFI_ERROR (Status)) { + Print (L"CapsuleApp: Capsule (%s) is not found.\n", CapsuleName); goto Done; } + if (!IsValidCapsuleHeader (Buffer, FileSize)) { - Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); + Print (L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); Status = EFI_INVALID_PARAMETER; goto Done; } CapsuleHeader = Buffer; - if (CompareGuid(&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { - DumpUxCapsule(CapsuleHeader); + if (CompareGuid (&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { + DumpUxCapsule (CapsuleHeader); Status = EFI_SUCCESS; goto Done; } - if (CompareGuid(&CapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { - DumpFmpCapsule(CapsuleHeader); + if (CompareGuid (&CapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { + DumpFmpCapsule (CapsuleHeader); } - if (IsNestedFmpCapsule(CapsuleHeader)) { - Print(L"[NestedCapsule]\n"); - Print(L"CapsuleHeader:\n"); - Print(L" CapsuleGuid - %g\n", &CapsuleHeader->CapsuleGuid); - Print(L" HeaderSize - 0x%x\n", CapsuleHeader->HeaderSize); - Print(L" Flags - 0x%x\n", CapsuleHeader->Flags); - Print(L" CapsuleImageSize - 0x%x\n", CapsuleHeader->CapsuleImageSize); - DumpFmpCapsule((EFI_CAPSULE_HEADER *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize)); + + if (IsNestedFmpCapsule (CapsuleHeader)) { + Print (L"[NestedCapsule]\n"); + Print (L"CapsuleHeader:\n"); + Print (L" CapsuleGuid - %g\n", &CapsuleHeader->CapsuleGuid); + Print (L" HeaderSize - 0x%x\n", CapsuleHeader->HeaderSize); + Print (L" Flags - 0x%x\n", CapsuleHeader->Flags); + Print (L" CapsuleImageSize - 0x%x\n", CapsuleHeader->CapsuleImageSize); + DumpFmpCapsule ((EFI_CAPSULE_HEADER *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize)); } Done: if (Buffer != NULL) { - FreePool(Buffer); + FreePool (Buffer); } + return Status; } @@ -241,80 +246,81 @@ DumpCapsuleStatusVariable ( CHAR16 *CapsuleFileName; CHAR16 *CapsuleTarget; - Status = GetVariable2( + Status = GetVariable2 ( L"CapsuleMax", &gEfiCapsuleReportGuid, (VOID **)&CapsuleIndex, NULL ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { ASSERT (CapsuleIndex != NULL); - CopyMem(CapsuleIndexData, CapsuleIndex, 11 * sizeof(CHAR16)); + CopyMem (CapsuleIndexData, CapsuleIndex, 11 * sizeof (CHAR16)); CapsuleIndexData[11] = 0; - Print(L"CapsuleMax - %s\n", CapsuleIndexData); - FreePool(CapsuleIndex); + Print (L"CapsuleMax - %s\n", CapsuleIndexData); + FreePool (CapsuleIndex); } - Status = GetVariable2( + + Status = GetVariable2 ( L"CapsuleLast", &gEfiCapsuleReportGuid, (VOID **)&CapsuleIndex, NULL ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { ASSERT (CapsuleIndex != NULL); - CopyMem(CapsuleIndexData, CapsuleIndex, 11 * sizeof(CHAR16)); + CopyMem (CapsuleIndexData, CapsuleIndex, 11 * sizeof (CHAR16)); CapsuleIndexData[11] = 0; - Print(L"CapsuleLast - %s\n", CapsuleIndexData); - FreePool(CapsuleIndex); + Print (L"CapsuleLast - %s\n", CapsuleIndexData); + FreePool (CapsuleIndex); } - - StrCpyS (CapsuleVarName, sizeof(CapsuleVarName)/sizeof(CapsuleVarName[0]), L"Capsule"); + StrCpyS (CapsuleVarName, sizeof (CapsuleVarName)/sizeof (CapsuleVarName[0]), L"Capsule"); TempVarName = CapsuleVarName + StrLen (CapsuleVarName); - Index = 0; + Index = 0; while (TRUE) { - UnicodeSPrint (TempVarName, 5 * sizeof(CHAR16), L"%04x", Index); + UnicodeSPrint (TempVarName, 5 * sizeof (CHAR16), L"%04x", Index); Status = GetVariable2 ( CapsuleVarName, &gEfiCapsuleReportGuid, - (VOID **) &CapsuleResult, + (VOID **)&CapsuleResult, NULL ); if (Status == EFI_NOT_FOUND) { break; - } else if (EFI_ERROR(Status)) { + } else if (EFI_ERROR (Status)) { continue; } + ASSERT (CapsuleResult != NULL); // // display capsule process status // - if (CapsuleResult->VariableTotalSize >= sizeof(EFI_CAPSULE_RESULT_VARIABLE_HEADER)) { + if (CapsuleResult->VariableTotalSize >= sizeof (EFI_CAPSULE_RESULT_VARIABLE_HEADER)) { Print (L"CapsuleName: %s\n", CapsuleVarName); Print (L" Capsule Guid: %g\n", &CapsuleResult->CapsuleGuid); Print (L" Capsule ProcessedTime: %t\n", &CapsuleResult->CapsuleProcessed); Print (L" Capsule Status: %r\n", CapsuleResult->CapsuleStatus); } - if (CompareGuid(&CapsuleResult->CapsuleGuid, &gEfiFmpCapsuleGuid)) { - if (CapsuleResult->VariableTotalSize >= sizeof(EFI_CAPSULE_RESULT_VARIABLE_HEADER) + sizeof(EFI_CAPSULE_RESULT_VARIABLE_FMP) + sizeof(CHAR16) * 2) { + if (CompareGuid (&CapsuleResult->CapsuleGuid, &gEfiFmpCapsuleGuid)) { + if (CapsuleResult->VariableTotalSize >= sizeof (EFI_CAPSULE_RESULT_VARIABLE_HEADER) + sizeof (EFI_CAPSULE_RESULT_VARIABLE_FMP) + sizeof (CHAR16) * 2) { CapsuleResultFmp = (EFI_CAPSULE_RESULT_VARIABLE_FMP *)(CapsuleResult + 1); - Print(L" Capsule FMP Version: 0x%x\n", CapsuleResultFmp->Version); - Print(L" Capsule FMP PayloadIndex: 0x%x\n", CapsuleResultFmp->PayloadIndex); - Print(L" Capsule FMP UpdateImageIndex: 0x%x\n", CapsuleResultFmp->UpdateImageIndex); - Print(L" Capsule FMP UpdateImageTypeId: %g\n", &CapsuleResultFmp->UpdateImageTypeId); + Print (L" Capsule FMP Version: 0x%x\n", CapsuleResultFmp->Version); + Print (L" Capsule FMP PayloadIndex: 0x%x\n", CapsuleResultFmp->PayloadIndex); + Print (L" Capsule FMP UpdateImageIndex: 0x%x\n", CapsuleResultFmp->UpdateImageIndex); + Print (L" Capsule FMP UpdateImageTypeId: %g\n", &CapsuleResultFmp->UpdateImageTypeId); CapsuleFileName = (CHAR16 *)(CapsuleResultFmp + 1); - Print(L" Capsule FMP CapsuleFileName: \"%s\"\n", CapsuleFileName); - CapsuleFileNameSize = StrSize(CapsuleFileName); - CapsuleTarget = (CHAR16 *)((UINTN)CapsuleFileName + CapsuleFileNameSize); - Print(L" Capsule FMP CapsuleTarget: \"%s\"\n", CapsuleTarget); + Print (L" Capsule FMP CapsuleFileName: \"%s\"\n", CapsuleFileName); + CapsuleFileNameSize = StrSize (CapsuleFileName); + CapsuleTarget = (CHAR16 *)((UINTN)CapsuleFileName + CapsuleFileNameSize); + Print (L" Capsule FMP CapsuleTarget: \"%s\"\n", CapsuleTarget); } } - FreePool(CapsuleResult); + FreePool (CapsuleResult); Index++; if (Index > 0xFFFF) { @@ -325,14 +331,14 @@ DumpCapsuleStatusVariable ( return EFI_SUCCESS; } -CHAR8 *mFwTypeString[] = { +CHAR8 *mFwTypeString[] = { "Unknown", "SystemFirmware", "DeviceFirmware", "UefiDriver", }; -CHAR8 *mLastAttemptStatusString[] = { +CHAR8 *mLastAttemptStatusString[] = { "Success", "Error: Unsuccessful", "Error: Insufficient Resources", @@ -356,7 +362,7 @@ FwTypeToString ( IN UINT32 FwType ) { - if (FwType < sizeof(mFwTypeString) / sizeof(mFwTypeString[0])) { + if (FwType < sizeof (mFwTypeString) / sizeof (mFwTypeString[0])) { return mFwTypeString[FwType]; } else { return "Invalid"; @@ -375,7 +381,7 @@ LastAttemptStatusToString ( IN UINT32 LastAttemptStatus ) { - if (LastAttemptStatus < sizeof(mLastAttemptStatusString) / sizeof(mLastAttemptStatusString[0])) { + if (LastAttemptStatus < sizeof (mLastAttemptStatusString) / sizeof (mLastAttemptStatusString[0])) { return mLastAttemptStatusString[LastAttemptStatus]; } else { return "Error: Unknown"; @@ -392,13 +398,13 @@ DumpEsrtEntry ( IN EFI_SYSTEM_RESOURCE_ENTRY *EsrtEntry ) { - Print(L" FwClass - %g\n", &EsrtEntry->FwClass); - Print(L" FwType - 0x%x (%a)\n", EsrtEntry->FwType, FwTypeToString(EsrtEntry->FwType)); - Print(L" FwVersion - 0x%x\n", EsrtEntry->FwVersion); - Print(L" LowestSupportedFwVersion - 0x%x\n", EsrtEntry->LowestSupportedFwVersion); - Print(L" CapsuleFlags - 0x%x\n", EsrtEntry->CapsuleFlags); - Print(L" LastAttemptVersion - 0x%x\n", EsrtEntry->LastAttemptVersion); - Print(L" LastAttemptStatus - 0x%x (%a)\n", EsrtEntry->LastAttemptStatus, LastAttemptStatusToString(EsrtEntry->LastAttemptStatus)); + Print (L" FwClass - %g\n", &EsrtEntry->FwClass); + Print (L" FwType - 0x%x (%a)\n", EsrtEntry->FwType, FwTypeToString (EsrtEntry->FwType)); + Print (L" FwVersion - 0x%x\n", EsrtEntry->FwVersion); + Print (L" LowestSupportedFwVersion - 0x%x\n", EsrtEntry->LowestSupportedFwVersion); + Print (L" CapsuleFlags - 0x%x\n", EsrtEntry->CapsuleFlags); + Print (L" LastAttemptVersion - 0x%x\n", EsrtEntry->LastAttemptVersion); + Print (L" LastAttemptStatus - 0x%x (%a)\n", EsrtEntry->LastAttemptStatus, LastAttemptStatusToString (EsrtEntry->LastAttemptStatus)); } /** @@ -415,18 +421,18 @@ DumpEsrt ( EFI_SYSTEM_RESOURCE_ENTRY *EsrtEntry; if (Esrt == NULL) { - return ; + return; } - Print(L"EFI_SYSTEM_RESOURCE_TABLE:\n"); - Print(L"FwResourceCount - 0x%x\n", Esrt->FwResourceCount); - Print(L"FwResourceCountMax - 0x%x\n", Esrt->FwResourceCountMax); - Print(L"FwResourceVersion - 0x%lx\n", Esrt->FwResourceVersion); + Print (L"EFI_SYSTEM_RESOURCE_TABLE:\n"); + Print (L"FwResourceCount - 0x%x\n", Esrt->FwResourceCount); + Print (L"FwResourceCountMax - 0x%x\n", Esrt->FwResourceCountMax); + Print (L"FwResourceVersion - 0x%lx\n", Esrt->FwResourceVersion); EsrtEntry = (VOID *)(Esrt + 1); for (Index = 0; Index < Esrt->FwResourceCount; Index++) { - Print(L"EFI_SYSTEM_RESOURCE_ENTRY (%d):\n", Index); - DumpEsrtEntry(EsrtEntry); + Print (L"EFI_SYSTEM_RESOURCE_ENTRY (%d):\n", Index); + DumpEsrtEntry (EsrtEntry); EsrtEntry++; } } @@ -442,19 +448,19 @@ DumpEsrtData ( EFI_STATUS Status; EFI_SYSTEM_RESOURCE_TABLE *Esrt; - Print(L"##############\n"); - Print(L"# ESRT TABLE #\n"); - Print(L"##############\n"); + Print (L"##############\n"); + Print (L"# ESRT TABLE #\n"); + Print (L"##############\n"); Status = EfiGetSystemConfigurationTable (&gEfiSystemResourceTableGuid, (VOID **)&Esrt); - if (EFI_ERROR(Status)) { - Print(L"ESRT - %r\n", Status); + if (EFI_ERROR (Status)) { + Print (L"ESRT - %r\n", Status); return; } - DumpEsrt(Esrt); - Print(L"\n"); -} + DumpEsrt (Esrt); + Print (L"\n"); +} /** Dump capsule information from CapsuleHeader @@ -466,7 +472,7 @@ DumpEsrtData ( **/ EFI_STATUS DumpCapsuleFromBuffer ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { if (CompareGuid (&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { @@ -477,6 +483,7 @@ DumpCapsuleFromBuffer ( if (CompareGuid (&CapsuleHeader->CapsuleGuid, &gEfiFmpCapsuleGuid)) { DumpFmpCapsule (CapsuleHeader); } + if (IsNestedFmpCapsule (CapsuleHeader)) { Print (L"[NestedCapusule]\n"); Print (L"CapsuleHeader:\n"); @@ -501,13 +508,13 @@ DumpCapsuleFromBuffer ( STATIC CHAR16 * UpperCaseString ( - IN CHAR16 *Str + IN CHAR16 *Str ) { CHAR16 *Cptr; for (Cptr = Str; *Cptr != L'\0'; Cptr++) { - if (L'a' <= *Cptr && *Cptr <= L'z') { + if ((L'a' <= *Cptr) && (*Cptr <= L'z')) { *Cptr = *Cptr - L'a' + L'A'; } } @@ -527,18 +534,19 @@ UpperCaseString ( STATIC VOID GetSubStringBeforePeriod ( - IN CHAR16 *Str, - OUT CHAR16 *SubStr, - OUT UINTN *SubStrLen + IN CHAR16 *Str, + OUT CHAR16 *SubStr, + OUT UINTN *SubStrLen ) { - UINTN Index; + UINTN Index; + for (Index = 0; Str[Index] != L'.' && Str[Index] != L'\0'; Index++) { SubStr[Index] = Str[Index]; } SubStr[Index] = L'\0'; - *SubStrLen = Index; + *SubStrLen = Index; } /** @@ -552,16 +560,17 @@ GetSubStringBeforePeriod ( STATIC VOID PadStrInTail ( - IN CHAR16 *StrBuf, - IN UINTN PadLen, - IN CHAR16 Character + IN CHAR16 *StrBuf, + IN UINTN PadLen, + IN CHAR16 Character ) { - UINTN Index; + UINTN Index; - for (Index = 0; StrBuf[Index] != L'\0'; Index++); + for (Index = 0; StrBuf[Index] != L'\0'; Index++) { + } - while(PadLen != 0) { + while (PadLen != 0) { StrBuf[Index] = Character; Index++; PadLen--; @@ -587,18 +596,19 @@ SplitFileNameExtension ( OUT CHAR16 *FileNameExtension ) { - UINTN Index; - UINTN StringLen; + UINTN Index; + UINTN StringLen; - StringLen = StrLen(FileName); - for (Index = StringLen; Index > 0 && FileName[Index] != L'.'; Index--); + StringLen = StrLen (FileName); + for (Index = StringLen; Index > 0 && FileName[Index] != L'.'; Index--) { + } // // No period exists. No FileName Extension // - if (Index == 0 && FileName[Index] != L'.') { + if ((Index == 0) && (FileName[Index] != L'.')) { FileNameExtension[0] = L'\0'; - Index = StringLen; + Index = StringLen; } else { StrCpyS (FileNameExtension, MAX_FILE_NAME_LEN, &FileName[Index+1]); } @@ -623,8 +633,8 @@ SplitFileNameExtension ( **/ INTN CompareFileNameInAlphabet ( - IN VOID *Left, - IN VOID *Right + IN VOID *Left, + IN VOID *Right ) { EFI_FILE_INFO *FileInfo1; @@ -639,8 +649,8 @@ CompareFileNameInAlphabet ( UINTN SubStrLen2; INTN SubStrCmpResult; - FileInfo1 = (EFI_FILE_INFO *) (*(UINTN *)Left); - FileInfo2 = (EFI_FILE_INFO *) (*(UINTN *)Right); + FileInfo1 = (EFI_FILE_INFO *)(*(UINTN *)Left); + FileInfo2 = (EFI_FILE_INFO *)(*(UINTN *)Right); SplitFileNameExtension (FileInfo1->FileName, FileName1, FileExtension1); SplitFileNameExtension (FileInfo2->FileName, FileName2, FileExtension2); @@ -656,7 +666,7 @@ CompareFileNameInAlphabet ( // Substr in NewFileName is longer. Pad tail with SPACE // PadStrInTail (TempSubStr2, SubStrLen1 - SubStrLen2, L' '); - } else if (SubStrLen1 < SubStrLen2){ + } else if (SubStrLen1 < SubStrLen2) { // // Substr in ListedFileName is longer. Pad tail with SPACE // @@ -685,29 +695,29 @@ CompareFileNameInAlphabet ( **/ EFI_STATUS DumpCapsuleFromDisk ( - IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs, - IN BOOLEAN DumpCapsuleInfo + IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs, + IN BOOLEAN DumpCapsuleInfo ) { - EFI_STATUS Status; - EFI_FILE *Root; - EFI_FILE *DirHandle; - EFI_FILE *FileHandle; - UINTN Index; - UINTN FileSize; - VOID *FileBuffer; - EFI_FILE_INFO **FileInfoBuffer; - EFI_FILE_INFO *FileInfo; - UINTN FileCount; - BOOLEAN NoFile; - - DirHandle = NULL; - FileHandle = NULL; - Index = 0; - FileInfoBuffer = NULL; - FileInfo = NULL; - FileCount = 0; - NoFile = FALSE; + EFI_STATUS Status; + EFI_FILE *Root; + EFI_FILE *DirHandle; + EFI_FILE *FileHandle; + UINTN Index; + UINTN FileSize; + VOID *FileBuffer; + EFI_FILE_INFO **FileInfoBuffer; + EFI_FILE_INFO *FileInfo; + UINTN FileCount; + BOOLEAN NoFile; + + DirHandle = NULL; + FileHandle = NULL; + Index = 0; + FileInfoBuffer = NULL; + FileInfo = NULL; + FileCount = 0; + NoFile = FALSE; Status = Fs->OpenVolume (Fs, &Root); if (EFI_ERROR (Status)) { @@ -715,7 +725,7 @@ DumpCapsuleFromDisk ( goto Done; } - Status = Root->Open (Root, &DirHandle, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE , 0); + Status = Root->Open (Root, &DirHandle, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0); if (EFI_ERROR (Status)) { Print (L"Cannot open %s. Status = %r\n", EFI_CAPSULE_FILE_DIRECTORY, Status); goto Done; @@ -726,7 +736,7 @@ DumpCapsuleFromDisk ( // Status = FileHandleFindFirstFile (DirHandle, &FileInfo); do { - if (EFI_ERROR (Status) || FileInfo == NULL) { + if (EFI_ERROR (Status) || (FileInfo == NULL)) { Print (L"Get File Info Fail. Status = %r\n", Status); goto Done; } @@ -753,6 +763,7 @@ DumpCapsuleFromDisk ( Status = EFI_OUT_OF_RESOURCES; goto Done; } + NoFile = FALSE; // @@ -760,7 +771,7 @@ DumpCapsuleFromDisk ( // Status = FileHandleFindFirstFile (DirHandle, &FileInfo); do { - if (EFI_ERROR (Status) || FileInfo == NULL) { + if (EFI_ERROR (Status) || (FileInfo == NULL)) { Print (L"Get File Info Fail. Status = %r\n", Status); goto Done; } @@ -783,7 +794,7 @@ DumpCapsuleFromDisk ( FileInfoBuffer, FileCount, sizeof (FileInfo), - (SORT_COMPARE) CompareFileNameInAlphabet + (SORT_COMPARE)CompareFileNameInAlphabet ); Print (L"The capsules will be performed by following order:\n"); @@ -797,16 +808,16 @@ DumpCapsuleFromDisk ( goto Done; } - Print(L"The infomation of the capsules:\n"); + Print (L"The infomation of the capsules:\n"); for (Index = 0; Index < FileCount; Index++) { FileHandle = NULL; - Status = DirHandle->Open (DirHandle, &FileHandle, FileInfoBuffer[Index]->FileName, EFI_FILE_MODE_READ, 0); + Status = DirHandle->Open (DirHandle, &FileHandle, FileInfoBuffer[Index]->FileName, EFI_FILE_MODE_READ, 0); if (EFI_ERROR (Status)) { goto Done; } - Status = FileHandleGetSize (FileHandle, (UINT64 *) &FileSize); + Status = FileHandleGetSize (FileHandle, (UINT64 *)&FileSize); if (EFI_ERROR (Status)) { Print (L"Cannot read file %s. Status = %r\n", FileInfoBuffer[Index]->FileName, Status); FileHandleClose (FileHandle); @@ -830,7 +841,7 @@ DumpCapsuleFromDisk ( Print (L"**************************\n"); Print (L" %d.%s:\n", Index + 1, FileInfoBuffer[Index]->FileName); Print (L"**************************\n"); - DumpCapsuleFromBuffer ((EFI_CAPSULE_HEADER *) FileBuffer); + DumpCapsuleFromBuffer ((EFI_CAPSULE_HEADER *)FileBuffer); FileHandleClose (FileHandle); FreePool (FileBuffer); } @@ -842,6 +853,7 @@ Done: FreePool (FileInfoBuffer[Index]); } } + FreePool (FileInfoBuffer); } @@ -857,30 +869,32 @@ Done: **/ VOID DumpBlockDescriptors ( - IN EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors, - IN BOOLEAN DumpCapsuleInfo + IN EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors, + IN BOOLEAN DumpCapsuleInfo ) { - EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr; + EFI_CAPSULE_BLOCK_DESCRIPTOR *TempBlockPtr; TempBlockPtr = BlockDescriptors; while (TRUE) { if (TempBlockPtr->Length != 0) { if (DumpCapsuleInfo) { - Print(L"******************************************************\n"); + Print (L"******************************************************\n"); } - Print(L"Capsule data starts at 0x%08x with size 0x%08x\n", TempBlockPtr->Union.DataBlock, TempBlockPtr->Length); + + Print (L"Capsule data starts at 0x%08x with size 0x%08x\n", TempBlockPtr->Union.DataBlock, TempBlockPtr->Length); if (DumpCapsuleInfo) { - Print(L"******************************************************\n"); - DumpCapsuleFromBuffer ((EFI_CAPSULE_HEADER *) (UINTN) TempBlockPtr->Union.DataBlock); + Print (L"******************************************************\n"); + DumpCapsuleFromBuffer ((EFI_CAPSULE_HEADER *)(UINTN)TempBlockPtr->Union.DataBlock); } + TempBlockPtr += 1; } else { if (TempBlockPtr->Union.ContinuationPointer == (UINTN)NULL) { break; } else { - TempBlockPtr = (EFI_CAPSULE_BLOCK_DESCRIPTOR *) (UINTN) TempBlockPtr->Union.ContinuationPointer; + TempBlockPtr = (EFI_CAPSULE_BLOCK_DESCRIPTOR *)(UINTN)TempBlockPtr->Union.ContinuationPointer; } } } @@ -894,29 +908,29 @@ DumpBlockDescriptors ( **/ VOID DumpProvisionedCapsule ( - IN BOOLEAN DumpCapsuleInfo + IN BOOLEAN DumpCapsuleInfo ) { - EFI_STATUS Status; - CHAR16 CapsuleVarName[30]; - CHAR16 *TempVarName; - UINTN Index; - EFI_PHYSICAL_ADDRESS *CapsuleDataPtr64; - UINT16 *BootNext; - CHAR16 BootOptionName[20]; - EFI_BOOT_MANAGER_LOAD_OPTION BootNextOptionEntry; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; - EFI_SHELL_PROTOCOL *ShellProtocol; - - Index = 0; - CapsuleDataPtr64 = NULL; - BootNext = NULL; + EFI_STATUS Status; + CHAR16 CapsuleVarName[30]; + CHAR16 *TempVarName; + UINTN Index; + EFI_PHYSICAL_ADDRESS *CapsuleDataPtr64; + UINT16 *BootNext; + CHAR16 BootOptionName[20]; + EFI_BOOT_MANAGER_LOAD_OPTION BootNextOptionEntry; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + EFI_SHELL_PROTOCOL *ShellProtocol; + + Index = 0; + CapsuleDataPtr64 = NULL; + BootNext = NULL; ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { Print (L"Get Shell Protocol Fail\n"); - return ; + return; } // @@ -925,7 +939,7 @@ DumpProvisionedCapsule ( Print (L"#########################\n"); Print (L"### Capsule on Memory ###\n"); Print (L"#########################\n"); - StrCpyS (CapsuleVarName, sizeof(CapsuleVarName)/sizeof(CHAR16), EFI_CAPSULE_VARIABLE_NAME); + StrCpyS (CapsuleVarName, sizeof (CapsuleVarName)/sizeof (CHAR16), EFI_CAPSULE_VARIABLE_NAME); TempVarName = CapsuleVarName + StrLen (CapsuleVarName); while (TRUE) { if (Index > 0) { @@ -939,21 +953,22 @@ DumpProvisionedCapsule ( } Status = GetVariable2 ( - CapsuleVarName, - &gEfiCapsuleVendorGuid, - (VOID **) &CapsuleDataPtr64, - NULL - ); - if (EFI_ERROR (Status) || CapsuleDataPtr64 == NULL) { + CapsuleVarName, + &gEfiCapsuleVendorGuid, + (VOID **)&CapsuleDataPtr64, + NULL + ); + if (EFI_ERROR (Status) || (CapsuleDataPtr64 == NULL)) { if (Index == 0) { Print (L"No data.\n"); } + break; } Index++; Print (L"Capsule Description at 0x%08x\n", *CapsuleDataPtr64); - DumpBlockDescriptors ((EFI_CAPSULE_BLOCK_DESCRIPTOR*) (UINTN) *CapsuleDataPtr64, DumpCapsuleInfo); + DumpBlockDescriptors ((EFI_CAPSULE_BLOCK_DESCRIPTOR *)(UINTN)*CapsuleDataPtr64, DumpCapsuleInfo); } // @@ -965,10 +980,10 @@ DumpProvisionedCapsule ( Status = GetVariable2 ( L"BootNext", &gEfiGlobalVariableGuid, - (VOID **) &BootNext, + (VOID **)&BootNext, NULL - ); - if (EFI_ERROR (Status) || BootNext == NULL) { + ); + if (EFI_ERROR (Status) || (BootNext == NULL)) { Print (L"Get BootNext Variable Fail. Status = %r\n", Status); } else { UnicodeSPrint (BootOptionName, sizeof (BootOptionName), L"Boot%04x", *BootNext); @@ -978,9 +993,9 @@ DumpProvisionedCapsule ( // Display description and device path // GetEfiSysPartitionFromBootOptionFilePath (BootNextOptionEntry.FilePath, &DevicePath, &Fs); - if(!EFI_ERROR (Status)) { + if (!EFI_ERROR (Status)) { Print (L"Capsules are provisioned on BootOption: %s\n", BootNextOptionEntry.Description); - Print (L" %s %s\n", ShellProtocol->GetMapFromDevicePath (&DevicePath), ConvertDevicePathToText(DevicePath, TRUE, TRUE)); + Print (L" %s %s\n", ShellProtocol->GetMapFromDevicePath (&DevicePath), ConvertDevicePathToText (DevicePath, TRUE, TRUE)); DumpCapsuleFromDisk (Fs, DumpCapsuleInfo); } } @@ -1000,68 +1015,70 @@ DumpProvisionedCapsule ( **/ VOID DumpFmpImageInfo ( - IN UINTN ImageInfoSize, - IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, - IN UINT32 DescriptorVersion, - IN UINT8 DescriptorCount, - IN UINTN DescriptorSize, - IN UINT32 PackageVersion, - IN CHAR16 *PackageVersionName + IN UINTN ImageInfoSize, + IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, + IN UINT32 DescriptorVersion, + IN UINT8 DescriptorCount, + IN UINTN DescriptorSize, + IN UINT32 PackageVersion, + IN CHAR16 *PackageVersionName ) { - EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; - UINTN Index; - UINTN Index2; - - Print(L" DescriptorVersion - 0x%x\n", DescriptorVersion); - Print(L" DescriptorCount - 0x%x\n", DescriptorCount); - Print(L" DescriptorSize - 0x%x\n", DescriptorSize); - Print(L" PackageVersion - 0x%x\n", PackageVersion); - Print(L" PackageVersionName - \"%s\"\n", PackageVersionName); + EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; + UINTN Index; + UINTN Index2; + + Print (L" DescriptorVersion - 0x%x\n", DescriptorVersion); + Print (L" DescriptorCount - 0x%x\n", DescriptorCount); + Print (L" DescriptorSize - 0x%x\n", DescriptorSize); + Print (L" PackageVersion - 0x%x\n", PackageVersion); + Print (L" PackageVersionName - \"%s\"\n", PackageVersionName); CurrentImageInfo = ImageInfo; for (Index = 0; Index < DescriptorCount; Index++) { - Print(L" ImageDescriptor (%d)\n", Index); - Print(L" ImageIndex - 0x%x\n", CurrentImageInfo->ImageIndex); - Print(L" ImageTypeId - %g\n", &CurrentImageInfo->ImageTypeId); - Print(L" ImageId - 0x%lx\n", CurrentImageInfo->ImageId); - Print(L" ImageIdName - \"%s\"\n", CurrentImageInfo->ImageIdName); - Print(L" Version - 0x%x\n", CurrentImageInfo->Version); - Print(L" VersionName - \"%s\"\n", CurrentImageInfo->VersionName); - Print(L" Size - 0x%x\n", CurrentImageInfo->Size); - Print(L" AttributesSupported - 0x%lx\n", CurrentImageInfo->AttributesSupported); - Print(L" IMAGE_UPDATABLE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); - Print(L" RESET_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_RESET_REQUIRED); - Print(L" AUTHENTICATION_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); - Print(L" IN_USE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_IN_USE); - Print(L" UEFI_IMAGE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_UEFI_IMAGE); - Print(L" AttributesSetting - 0x%lx\n", CurrentImageInfo->AttributesSetting); - Print(L" IMAGE_UPDATABLE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); - Print(L" RESET_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_RESET_REQUIRED); - Print(L" AUTHENTICATION_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); - Print(L" IN_USE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_IN_USE); - Print(L" UEFI_IMAGE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_UEFI_IMAGE); - Print(L" Compatibilities - 0x%lx\n", CurrentImageInfo->Compatibilities); - Print(L" COMPATIB_CHECK_SUPPORTED - 0x%lx\n", CurrentImageInfo->Compatibilities & IMAGE_COMPATIBILITY_CHECK_SUPPORTED); + Print (L" ImageDescriptor (%d)\n", Index); + Print (L" ImageIndex - 0x%x\n", CurrentImageInfo->ImageIndex); + Print (L" ImageTypeId - %g\n", &CurrentImageInfo->ImageTypeId); + Print (L" ImageId - 0x%lx\n", CurrentImageInfo->ImageId); + Print (L" ImageIdName - \"%s\"\n", CurrentImageInfo->ImageIdName); + Print (L" Version - 0x%x\n", CurrentImageInfo->Version); + Print (L" VersionName - \"%s\"\n", CurrentImageInfo->VersionName); + Print (L" Size - 0x%x\n", CurrentImageInfo->Size); + Print (L" AttributesSupported - 0x%lx\n", CurrentImageInfo->AttributesSupported); + Print (L" IMAGE_UPDATABLE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); + Print (L" RESET_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_RESET_REQUIRED); + Print (L" AUTHENTICATION_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); + Print (L" IN_USE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_IN_USE); + Print (L" UEFI_IMAGE - 0x%lx\n", CurrentImageInfo->AttributesSupported & IMAGE_ATTRIBUTE_UEFI_IMAGE); + Print (L" AttributesSetting - 0x%lx\n", CurrentImageInfo->AttributesSetting); + Print (L" IMAGE_UPDATABLE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); + Print (L" RESET_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_RESET_REQUIRED); + Print (L" AUTHENTICATION_REQUIRED - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); + Print (L" IN_USE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_IN_USE); + Print (L" UEFI_IMAGE - 0x%lx\n", CurrentImageInfo->AttributesSetting & IMAGE_ATTRIBUTE_UEFI_IMAGE); + Print (L" Compatibilities - 0x%lx\n", CurrentImageInfo->Compatibilities); + Print (L" COMPATIB_CHECK_SUPPORTED - 0x%lx\n", CurrentImageInfo->Compatibilities & IMAGE_COMPATIBILITY_CHECK_SUPPORTED); if (DescriptorVersion > 1) { - Print(L" LowestSupportedImageVersion - 0x%x\n", CurrentImageInfo->LowestSupportedImageVersion); + Print (L" LowestSupportedImageVersion - 0x%x\n", CurrentImageInfo->LowestSupportedImageVersion); if (DescriptorVersion > 2) { - Print(L" LastAttemptVersion - 0x%x\n", CurrentImageInfo->LastAttemptVersion); - Print(L" LastAttemptStatus - 0x%x (%a)\n", CurrentImageInfo->LastAttemptStatus, LastAttemptStatusToString(CurrentImageInfo->LastAttemptStatus)); - Print(L" HardwareInstance - 0x%lx\n", CurrentImageInfo->HardwareInstance); + Print (L" LastAttemptVersion - 0x%x\n", CurrentImageInfo->LastAttemptVersion); + Print (L" LastAttemptStatus - 0x%x (%a)\n", CurrentImageInfo->LastAttemptStatus, LastAttemptStatusToString (CurrentImageInfo->LastAttemptStatus)); + Print (L" HardwareInstance - 0x%lx\n", CurrentImageInfo->HardwareInstance); if (DescriptorVersion > 3) { - Print(L" Dependencies - "); + Print (L" Dependencies - "); if (CurrentImageInfo->Dependencies == NULL) { - Print(L"NULL\n"); + Print (L"NULL\n"); } else { Index2 = 0; do { - Print(L"%02x ", CurrentImageInfo->Dependencies->Dependencies[Index2]); - } while (CurrentImageInfo->Dependencies->Dependencies[Index2 ++] != EFI_FMP_DEP_END); - Print(L"\n"); + Print (L"%02x ", CurrentImageInfo->Dependencies->Dependencies[Index2]); + } while (CurrentImageInfo->Dependencies->Dependencies[Index2++] != EFI_FMP_DEP_END); + + Print (L"\n"); } } } } + // // Use DescriptorSize to move ImageInfo Pointer to stay compatible with different ImageInfo version // @@ -1080,24 +1097,24 @@ DumpFmpImageInfo ( **/ VOID DumpFmpPackageInfo ( - IN UINT32 PackageVersion, - IN CHAR16 *PackageVersionName, - IN UINT32 PackageVersionNameMaxLen, - IN UINT64 AttributesSupported, - IN UINT64 AttributesSetting + IN UINT32 PackageVersion, + IN CHAR16 *PackageVersionName, + IN UINT32 PackageVersionNameMaxLen, + IN UINT64 AttributesSupported, + IN UINT64 AttributesSetting ) { - Print(L" PackageVersion - 0x%x\n", PackageVersion); - Print(L" PackageVersionName - \"%s\"\n", PackageVersionName); - Print(L" PackageVersionNameMaxLen - 0x%x\n", PackageVersionNameMaxLen); - Print(L" AttributesSupported - 0x%lx\n", AttributesSupported); - Print(L" IMAGE_UPDATABLE - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); - Print(L" RESET_REQUIRED - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_RESET_REQUIRED); - Print(L" AUTHENTICATION_REQUIRED - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); - Print(L" AttributesSetting - 0x%lx\n", AttributesSetting); - Print(L" IMAGE_UPDATABLE - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); - Print(L" RESET_REQUIRED - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_RESET_REQUIRED); - Print(L" AUTHENTICATION_REQUIRED - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); + Print (L" PackageVersion - 0x%x\n", PackageVersion); + Print (L" PackageVersionName - \"%s\"\n", PackageVersionName); + Print (L" PackageVersionNameMaxLen - 0x%x\n", PackageVersionNameMaxLen); + Print (L" AttributesSupported - 0x%lx\n", AttributesSupported); + Print (L" IMAGE_UPDATABLE - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); + Print (L" RESET_REQUIRED - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_RESET_REQUIRED); + Print (L" AUTHENTICATION_REQUIRED - 0x%lx\n", AttributesSupported & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); + Print (L" AttributesSetting - 0x%lx\n", AttributesSetting); + Print (L" IMAGE_UPDATABLE - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_IMAGE_UPDATABLE); + Print (L" RESET_REQUIRED - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_RESET_REQUIRED); + Print (L" AUTHENTICATION_REQUIRED - 0x%lx\n", AttributesSetting & IMAGE_ATTRIBUTE_AUTHENTICATION_REQUIRED); } /** @@ -1108,25 +1125,25 @@ DumpFmpData ( VOID ) { - EFI_STATUS Status; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - UINTN Index; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; - UINTN ImageInfoSize; - UINT32 FmpImageInfoDescriptorVer; - UINT8 FmpImageInfoCount; - UINTN DescriptorSize; - UINT32 PackageVersion; - CHAR16 *PackageVersionName; - UINT32 PackageVersionNameMaxLen; - UINT64 AttributesSupported; - UINT64 AttributesSetting; - - Print(L"############\n"); - Print(L"# FMP DATA #\n"); - Print(L"############\n"); + EFI_STATUS Status; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + UINTN Index; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; + UINTN ImageInfoSize; + UINT32 FmpImageInfoDescriptorVer; + UINT8 FmpImageInfoCount; + UINTN DescriptorSize; + UINT32 PackageVersion; + CHAR16 *PackageVersionName; + UINT32 PackageVersionNameMaxLen; + UINT64 AttributesSupported; + UINT64 AttributesSetting; + + Print (L"############\n"); + Print (L"# FMP DATA #\n"); + Print (L"############\n"); Status = gBS->LocateHandleBuffer ( ByProtocol, &gEfiFirmwareManagementProtocolGuid, @@ -1134,32 +1151,32 @@ DumpFmpData ( &NumberOfHandles, &HandleBuffer ); - if (EFI_ERROR(Status)) { - Print(L"FMP protocol - %r\n", EFI_NOT_FOUND); + if (EFI_ERROR (Status)) { + Print (L"FMP protocol - %r\n", EFI_NOT_FOUND); return; } for (Index = 0; Index < NumberOfHandles; Index++) { - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } ImageInfoSize = 0; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + ); if (Status != EFI_BUFFER_TOO_SMALL) { continue; } @@ -1172,28 +1189,28 @@ DumpFmpData ( } PackageVersionName = NULL; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, // ImageInfoSize - FmpImageInfoBuf, // ImageInfo - &FmpImageInfoDescriptorVer, // DescriptorVersion - &FmpImageInfoCount, // DescriptorCount - &DescriptorSize, // DescriptorSize - &PackageVersion, // PackageVersion - &PackageVersionName // PackageVersionName - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, // ImageInfoSize + FmpImageInfoBuf, // ImageInfo + &FmpImageInfoDescriptorVer, // DescriptorVersion + &FmpImageInfoCount, // DescriptorCount + &DescriptorSize, // DescriptorSize + &PackageVersion, // PackageVersion + &PackageVersionName // PackageVersionName + ); // // If FMP GetInformation interface failed, skip this resource // - if (EFI_ERROR(Status)) { - Print(L"FMP (%d) ImageInfo - %r\n", Index, Status); - FreePool(FmpImageInfoBuf); + if (EFI_ERROR (Status)) { + Print (L"FMP (%d) ImageInfo - %r\n", Index, Status); + FreePool (FmpImageInfoBuf); continue; } - Print(L"FMP (%d) ImageInfo:\n", Index); - DumpFmpImageInfo( + Print (L"FMP (%d) ImageInfo:\n", Index); + DumpFmpImageInfo ( ImageInfoSize, // ImageInfoSize FmpImageInfoBuf, // ImageInfo FmpImageInfoDescriptorVer, // DescriptorVersion @@ -1204,27 +1221,28 @@ DumpFmpData ( ); if (PackageVersionName != NULL) { - FreePool(PackageVersionName); + FreePool (PackageVersionName); } - FreePool(FmpImageInfoBuf); + + FreePool (FmpImageInfoBuf); // // Get package info // PackageVersionName = NULL; - Status = Fmp->GetPackageInfo ( - Fmp, - &PackageVersion, // PackageVersion - &PackageVersionName, // PackageVersionName - &PackageVersionNameMaxLen, // PackageVersionNameMaxLen - &AttributesSupported, // AttributesSupported - &AttributesSetting // AttributesSetting - ); - if (EFI_ERROR(Status)) { - Print(L"FMP (%d) PackageInfo - %r\n", Index, Status); + Status = Fmp->GetPackageInfo ( + Fmp, + &PackageVersion, // PackageVersion + &PackageVersionName, // PackageVersionName + &PackageVersionNameMaxLen, // PackageVersionNameMaxLen + &AttributesSupported, // AttributesSupported + &AttributesSetting // AttributesSetting + ); + if (EFI_ERROR (Status)) { + Print (L"FMP (%d) PackageInfo - %r\n", Index, Status); } else { - Print(L"FMP (%d) ImageInfo:\n", Index); - DumpFmpPackageInfo( + Print (L"FMP (%d) ImageInfo:\n", Index); + DumpFmpPackageInfo ( PackageVersion, // PackageVersion PackageVersionName, // PackageVersionName PackageVersionNameMaxLen, // PackageVersionNameMaxLen @@ -1233,14 +1251,15 @@ DumpFmpData ( ); if (PackageVersionName != NULL) { - FreePool(PackageVersionName); + FreePool (PackageVersionName); } } } - Print(L"\n"); + + Print (L"\n"); EXIT: - FreePool(HandleBuffer); + FreePool (HandleBuffer); } /** @@ -1256,22 +1275,24 @@ EXIT: **/ BOOLEAN IsThisFmpImageInfo ( - IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, - IN UINT8 DescriptorCount, - IN UINTN DescriptorSize, - IN EFI_GUID *ImageTypeId + IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, + IN UINT8 DescriptorCount, + IN UINTN DescriptorSize, + IN EFI_GUID *ImageTypeId ) { - EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; - UINTN Index; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; + UINTN Index; CurrentImageInfo = ImageInfo; for (Index = 0; Index < DescriptorCount; Index++) { if (CompareGuid (&CurrentImageInfo->ImageTypeId, ImageTypeId)) { return TRUE; } + CurrentImageInfo = (EFI_FIRMWARE_IMAGE_DESCRIPTOR *)((UINT8 *)CurrentImageInfo + DescriptorSize); } + return FALSE; } @@ -1287,19 +1308,19 @@ FindFmpFromImageTypeId ( IN EFI_GUID *ImageTypeId ) { - EFI_STATUS Status; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *TargetFmp; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - UINTN Index; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; - UINTN ImageInfoSize; - UINT32 FmpImageInfoDescriptorVer; - UINT8 FmpImageInfoCount; - UINTN DescriptorSize; - UINT32 PackageVersion; - CHAR16 *PackageVersionName; + EFI_STATUS Status; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *TargetFmp; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + UINTN Index; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; + UINTN ImageInfoSize; + UINT32 FmpImageInfoDescriptorVer; + UINT8 FmpImageInfoCount; + UINTN DescriptorSize; + UINT32 PackageVersion; + CHAR16 *PackageVersionName; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -1308,33 +1329,33 @@ FindFmpFromImageTypeId ( &NumberOfHandles, &HandleBuffer ); - if (EFI_ERROR(Status)) { - Print(L"FMP protocol - %r\n", EFI_NOT_FOUND); + if (EFI_ERROR (Status)) { + Print (L"FMP protocol - %r\n", EFI_NOT_FOUND); return NULL; } TargetFmp = NULL; for (Index = 0; Index < NumberOfHandles; Index++) { - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } ImageInfoSize = 0; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + ); if (Status != EFI_BUFFER_TOO_SMALL) { continue; } @@ -1342,44 +1363,46 @@ FindFmpFromImageTypeId ( FmpImageInfoBuf = NULL; FmpImageInfoBuf = AllocateZeroPool (ImageInfoSize); if (FmpImageInfoBuf == NULL) { - FreePool(HandleBuffer); - Print(L"Out of resource\n"); + FreePool (HandleBuffer); + Print (L"Out of resource\n"); return NULL; } PackageVersionName = NULL; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, // ImageInfoSize - FmpImageInfoBuf, // ImageInfo - &FmpImageInfoDescriptorVer, // DescriptorVersion - &FmpImageInfoCount, // DescriptorCount - &DescriptorSize, // DescriptorSize - &PackageVersion, // PackageVersion - &PackageVersionName // PackageVersionName - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, // ImageInfoSize + FmpImageInfoBuf, // ImageInfo + &FmpImageInfoDescriptorVer, // DescriptorVersion + &FmpImageInfoCount, // DescriptorCount + &DescriptorSize, // DescriptorSize + &PackageVersion, // PackageVersion + &PackageVersionName // PackageVersionName + ); // // If FMP GetInformation interface failed, skip this resource // - if (EFI_ERROR(Status)) { - FreePool(FmpImageInfoBuf); + if (EFI_ERROR (Status)) { + FreePool (FmpImageInfoBuf); continue; } if (PackageVersionName != NULL) { - FreePool(PackageVersionName); + FreePool (PackageVersionName); } if (IsThisFmpImageInfo (FmpImageInfoBuf, FmpImageInfoCount, DescriptorSize, ImageTypeId)) { TargetFmp = Fmp; } - FreePool(FmpImageInfoBuf); + + FreePool (FmpImageInfoBuf); if (TargetFmp != NULL) { break; } } - FreePool(HandleBuffer); + + FreePool (HandleBuffer); return TargetFmp; } @@ -1399,46 +1422,46 @@ DumpFmpImage ( IN CHAR16 *ImageName ) { - EFI_STATUS Status; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - VOID *Image; - UINTN ImageSize; + EFI_STATUS Status; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + VOID *Image; + UINTN ImageSize; Fmp = FindFmpFromImageTypeId (ImageTypeId); if (Fmp == NULL) { - Print(L"No FMP include ImageTypeId %g\n", ImageTypeId); - return ; + Print (L"No FMP include ImageTypeId %g\n", ImageTypeId); + return; } if (ImageIndex > 0xFF) { - Print(L"ImageIndex 0x%x too big\n", ImageIndex); - return ; + Print (L"ImageIndex 0x%x too big\n", ImageIndex); + return; } - Image = Fmp; + Image = Fmp; ImageSize = 0; - Status = Fmp->GetImage (Fmp, (UINT8)ImageIndex, Image, &ImageSize); + Status = Fmp->GetImage (Fmp, (UINT8)ImageIndex, Image, &ImageSize); if (Status != EFI_BUFFER_TOO_SMALL) { - Print(L"Fmp->GetImage - %r\n", Status); - return ; + Print (L"Fmp->GetImage - %r\n", Status); + return; } Image = AllocatePool (ImageSize); if (Image == NULL) { - Print(L"Allocate FmpImage 0x%x - %r\n", ImageSize, EFI_OUT_OF_RESOURCES); - return ; + Print (L"Allocate FmpImage 0x%x - %r\n", ImageSize, EFI_OUT_OF_RESOURCES); + return; } Status = Fmp->GetImage (Fmp, (UINT8)ImageIndex, Image, &ImageSize); - if (EFI_ERROR(Status)) { - Print(L"Fmp->GetImage - %r\n", Status); - return ; + if (EFI_ERROR (Status)) { + Print (L"Fmp->GetImage - %r\n", Status); + return; } - Status = WriteFileFromBuffer(ImageName, ImageSize, Image); - Print(L"CapsuleApp: Dump %g ImageIndex (0x%x) to %s %r\n", ImageTypeId, ImageIndex, ImageName, Status); + Status = WriteFileFromBuffer (ImageName, ImageSize, Image); + Print (L"CapsuleApp: Dump %g ImageIndex (0x%x) to %s %r\n", ImageTypeId, ImageIndex, ImageName, Status); FreePool (Image); - return ; + return; } diff --git a/MdeModulePkg/Application/CapsuleApp/CapsuleOnDisk.c b/MdeModulePkg/Application/CapsuleApp/CapsuleOnDisk.c index 77f9a1571f..5ce5a50f7b 100644 --- a/MdeModulePkg/Application/CapsuleApp/CapsuleOnDisk.c +++ b/MdeModulePkg/Application/CapsuleApp/CapsuleOnDisk.c @@ -8,7 +8,9 @@ #include "CapsuleApp.h" -EFI_GUID mCapsuleOnDiskBootOptionGuid = { 0x4CC29BB7, 0x2413, 0x40A2, { 0xB0, 0x6D, 0x25, 0x3E, 0x37, 0x10, 0xF5, 0x32 } }; +EFI_GUID mCapsuleOnDiskBootOptionGuid = { + 0x4CC29BB7, 0x2413, 0x40A2, { 0xB0, 0x6D, 0x25, 0x3E, 0x37, 0x10, 0xF5, 0x32 } +}; /** Get file name from file path. @@ -20,13 +22,13 @@ EFI_GUID mCapsuleOnDiskBootOptionGuid = { 0x4CC29BB7, 0x2413, 0x40A2, { 0xB0, 0x **/ CHAR16 * GetFileNameFromPath ( - CHAR16 *FilePath + CHAR16 *FilePath ) { - EFI_STATUS Status; - EFI_SHELL_PROTOCOL *ShellProtocol; - SHELL_FILE_HANDLE Handle; - EFI_FILE_INFO *FileInfo; + EFI_STATUS Status; + EFI_SHELL_PROTOCOL *ShellProtocol; + SHELL_FILE_HANDLE Handle; + EFI_FILE_INFO *FileInfo; ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { @@ -68,13 +70,13 @@ GetFileNameFromPath ( **/ BOOLEAN IsEfiSysPartitionDevicePath ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath + EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - HARDDRIVE_DEVICE_PATH *Hd; - EFI_HANDLE Handle; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + HARDDRIVE_DEVICE_PATH *Hd; + EFI_HANDLE Handle; // // Check if the device path contains GPT node @@ -83,12 +85,14 @@ IsEfiSysPartitionDevicePath ( while (!IsDevicePathEnd (TempDevicePath)) { if ((DevicePathType (TempDevicePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) { + (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) + { Hd = (HARDDRIVE_DEVICE_PATH *)TempDevicePath; if (Hd->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER) { break; } } + TempDevicePath = NextDevicePathNode (TempDevicePath); } @@ -112,19 +116,19 @@ DumpAllEfiSysPartition ( VOID ) { - EFI_HANDLE *SimpleFileSystemHandles; - UINTN NumberSimpleFileSystemHandles; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINTN NumberEfiSystemPartitions; - EFI_SHELL_PROTOCOL *ShellProtocol; + EFI_HANDLE *SimpleFileSystemHandles; + UINTN NumberSimpleFileSystemHandles; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINTN NumberEfiSystemPartitions; + EFI_SHELL_PROTOCOL *ShellProtocol; NumberEfiSystemPartitions = 0; ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { - Print (L"Get Shell Protocol Fail\n");; - return ; + Print (L"Get Shell Protocol Fail\n"); + return; } Print (L"EFI System Partition list:\n"); @@ -141,12 +145,12 @@ DumpAllEfiSysPartition ( DevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]); if (IsEfiSysPartitionDevicePath (DevicePath)) { NumberEfiSystemPartitions++; - Print(L" %s\n %s\n", ShellProtocol->GetMapFromDevicePath (&DevicePath), ConvertDevicePathToText (DevicePath, TRUE, TRUE)); + Print (L" %s\n %s\n", ShellProtocol->GetMapFromDevicePath (&DevicePath), ConvertDevicePathToText (DevicePath, TRUE, TRUE)); } } if (NumberEfiSystemPartitions == 0) { - Print(L" No ESP found.\n"); + Print (L" No ESP found.\n"); } } @@ -162,21 +166,22 @@ IsCapsuleProvisioned ( VOID ) { - EFI_STATUS Status; - UINT64 OsIndication; - UINTN DataSize; + EFI_STATUS Status; + UINT64 OsIndication; + UINTN DataSize; OsIndication = 0; - DataSize = sizeof(UINT64); - Status = gRT->GetVariable ( - L"OsIndications", - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - &OsIndication - ); + DataSize = sizeof (UINT64); + Status = gRT->GetVariable ( + L"OsIndications", + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + &OsIndication + ); if (!EFI_ERROR (Status) && - (OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) != 0) { + ((OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) != 0)) + { return TRUE; } @@ -199,11 +204,11 @@ GetEfiSysPartition ( OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs ) { - EFI_HANDLE *SimpleFileSystemHandles; - UINTN NumberSimpleFileSystemHandles; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_STATUS Status; + EFI_HANDLE *SimpleFileSystemHandles; + UINTN NumberSimpleFileSystemHandles; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_STATUS Status; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -245,15 +250,15 @@ GetEfiSysPartition ( **/ EFI_STATUS GetEfiSysPartitionFromDevPath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT EFI_DEVICE_PATH_PROTOCOL **FsDevicePath, - OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT EFI_DEVICE_PATH_PROTOCOL **FsDevicePath, + OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - HARDDRIVE_DEVICE_PATH *Hd; - EFI_HANDLE Handle; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + HARDDRIVE_DEVICE_PATH *Hd; + EFI_HANDLE Handle; // // Check if the device path contains GPT node @@ -261,12 +266,14 @@ GetEfiSysPartitionFromDevPath ( TempDevicePath = DevicePath; while (!IsDevicePathEnd (TempDevicePath)) { if ((DevicePathType (TempDevicePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) { + (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) + { Hd = (HARDDRIVE_DEVICE_PATH *)TempDevicePath; if (Hd->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER) { break; } } + TempDevicePath = NextDevicePathNode (TempDevicePath); } @@ -310,13 +317,13 @@ GetEfiSysPartitionFromBootOptionFilePath ( OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *CurFullPath; - EFI_DEVICE_PATH_PROTOCOL *PreFullPath; - EFI_DEVICE_PATH_PROTOCOL *FsFullPath; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *CurFullPath; + EFI_DEVICE_PATH_PROTOCOL *PreFullPath; + EFI_DEVICE_PATH_PROTOCOL *FsFullPath; CurFullPath = NULL; - FsFullPath = NULL; + FsFullPath = NULL; // // Try every full device Path generated from bootoption // @@ -337,13 +344,14 @@ GetEfiSysPartitionFromBootOptionFilePath ( } DEBUG_CODE_BEGIN (); - CHAR16 *DevicePathStr; + CHAR16 *DevicePathStr; + + DevicePathStr = ConvertDevicePathToText (CurFullPath, TRUE, TRUE); + if (DevicePathStr != NULL) { + DEBUG ((DEBUG_INFO, "Full device path %s\n", DevicePathStr)); + FreePool (DevicePathStr); + } - DevicePathStr = ConvertDevicePathToText (CurFullPath, TRUE, TRUE); - if (DevicePathStr != NULL){ - DEBUG ((DEBUG_INFO, "Full device path %s\n", DevicePathStr)); - FreePool (DevicePathStr); - } DEBUG_CODE_END (); Status = GetEfiSysPartitionFromDevPath (CurFullPath, &FsFullPath, Fs); @@ -376,7 +384,7 @@ GetUpdateFileSystem ( OUT UINT16 *BootNext, OUT EFI_SIMPLE_FILE_SYSTEM_PROTOCOL **Fs, OUT BOOLEAN *UpdateBootNext -) + ) { EFI_STATUS Status; CHAR16 BootOptionName[20]; @@ -396,7 +404,7 @@ GetUpdateFileSystem ( ShellProtocol = GetShellProtocol (); if (ShellProtocol == NULL) { - Print (L"Get Shell Protocol Fail\n");; + Print (L"Get Shell Protocol Fail\n"); return EFI_NOT_FOUND; } @@ -404,14 +412,14 @@ GetUpdateFileSystem ( // 1. If Fs is not assigned and there are capsule provisioned before, // Get EFI system partition from BootNext. // - if (IsCapsuleProvisioned () && Map == NULL) { + if (IsCapsuleProvisioned () && (Map == NULL)) { Status = GetVariable2 ( L"BootNext", &gEfiGlobalVariableGuid, (VOID **)&BootNextData, NULL ); - if (EFI_ERROR (Status) || BootNextData == NULL) { + if (EFI_ERROR (Status) || (BootNextData == NULL)) { Print (L"Get Boot Next Data Fail. Status = %r\n", Status); return EFI_NOT_FOUND; } else { @@ -419,11 +427,11 @@ GetUpdateFileSystem ( Status = EfiBootManagerVariableToLoadOption (BootOptionName, &BootNextOption); if (!EFI_ERROR (Status)) { DevicePath = BootNextOption.FilePath; - Status = GetEfiSysPartitionFromBootOptionFilePath (DevicePath, &FullPath, Fs); + Status = GetEfiSysPartitionFromBootOptionFilePath (DevicePath, &FullPath, Fs); if (!EFI_ERROR (Status)) { *UpdateBootNext = FALSE; - Print(L"Get EFI system partition from BootNext : %s\n", BootNextOption.Description); - Print(L"%s %s\n", ShellProtocol->GetMapFromDevicePath (&FullPath), ConvertDevicePathToText (FullPath, TRUE, TRUE)); + Print (L"Get EFI system partition from BootNext : %s\n", BootNextOption.Description); + Print (L"%s %s\n", ShellProtocol->GetMapFromDevicePath (&FullPath), ConvertDevicePathToText (FullPath, TRUE, TRUE)); return EFI_SUCCESS; } } @@ -436,10 +444,10 @@ GetUpdateFileSystem ( if (Map != NULL) { MappedDevicePath = ShellProtocol->GetDevicePathFromMap (Map); if (MappedDevicePath == NULL) { - Print(L"'%s' is not a valid mapping.\n", Map); + Print (L"'%s' is not a valid mapping.\n", Map); return EFI_INVALID_PARAMETER; } else if (!IsEfiSysPartitionDevicePath (DuplicateDevicePath (MappedDevicePath))) { - Print(L"'%s' is not a EFI System Partition.\n", Map); + Print (L"'%s' is not a EFI System Partition.\n", Map); return EFI_INVALID_PARAMETER; } } @@ -448,9 +456,10 @@ GetUpdateFileSystem ( // 2. Get EFI system partition form boot options. // BootOptionBuffer = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot); - if ( (BootOptionBuffer == NULL) || - (BootOptionCount == 0 && Map == NULL) - ) { + if ((BootOptionBuffer == NULL) || + ((BootOptionCount == 0) && (Map == NULL)) + ) + { return EFI_NOT_FOUND; } @@ -458,32 +467,34 @@ GetUpdateFileSystem ( // // Get the boot option from the link list // - DevicePath = BootOptionBuffer[Index].FilePath; + DevicePath = BootOptionBuffer[Index].FilePath; // // Skip inactive or legacy boot options // - if ((BootOptionBuffer[Index].Attributes & LOAD_OPTION_ACTIVE) == 0 || - DevicePathType (DevicePath) == BBS_DEVICE_PATH) { + if (((BootOptionBuffer[Index].Attributes & LOAD_OPTION_ACTIVE) == 0) || + (DevicePathType (DevicePath) == BBS_DEVICE_PATH)) + { continue; } DEBUG_CODE_BEGIN (); - CHAR16 *DevicePathStr; - - DevicePathStr = ConvertDevicePathToText (DevicePath, TRUE, TRUE); - if (DevicePathStr != NULL){ - DEBUG ((DEBUG_INFO, "Try BootOption %s\n", DevicePathStr)); - FreePool (DevicePathStr); - } else { - DEBUG ((DEBUG_INFO, "DevicePathToStr failed\n")); - } + CHAR16 *DevicePathStr; + + DevicePathStr = ConvertDevicePathToText (DevicePath, TRUE, TRUE); + if (DevicePathStr != NULL) { + DEBUG ((DEBUG_INFO, "Try BootOption %s\n", DevicePathStr)); + FreePool (DevicePathStr); + } else { + DEBUG ((DEBUG_INFO, "DevicePathToStr failed\n")); + } + DEBUG_CODE_END (); Status = GetEfiSysPartitionFromBootOptionFilePath (DevicePath, &FullPath, Fs); if (!EFI_ERROR (Status)) { if (Map == NULL) { - *BootNext = (UINT16) BootOptionBuffer[Index].OptionNumber; + *BootNext = (UINT16)BootOptionBuffer[Index].OptionNumber; *UpdateBootNext = TRUE; Print (L"Found EFI system partition on Boot%04x: %s\n", *BootNext, BootOptionBuffer[Index].Description); Print (L"%s %s\n", ShellProtocol->GetMapFromDevicePath (&FullPath), ConvertDevicePathToText (FullPath, TRUE, TRUE)); @@ -491,7 +502,7 @@ GetUpdateFileSystem ( } if (StrnCmp (Map, ShellProtocol->GetMapFromDevicePath (&FullPath), StrLen (Map)) == 0) { - *BootNext = (UINT16) BootOptionBuffer[Index].OptionNumber; + *BootNext = (UINT16)BootOptionBuffer[Index].OptionNumber; *UpdateBootNext = TRUE; Print (L"Found Boot Option on %s : %s\n", Map, BootOptionBuffer[Index].Description); return EFI_SUCCESS; @@ -507,11 +518,12 @@ GetUpdateFileSystem ( // If map is assigned, try to get ESP from mapped Fs. // DevicePath = DuplicateDevicePath (MappedDevicePath); - Status = GetEfiSysPartitionFromDevPath (DevicePath, &FullPath, Fs); + Status = GetEfiSysPartitionFromDevPath (DevicePath, &FullPath, Fs); if (EFI_ERROR (Status)) { Print (L"Error: Cannot get EFI system partition from '%s' - %r\n", Map, Status); return EFI_NOT_FOUND; } + Print (L"Warning: Cannot find Boot Option on '%s'!\n", Map); } else { Status = GetEfiSysPartition (&DevicePath, Fs); @@ -529,15 +541,16 @@ GetUpdateFileSystem ( LOAD_OPTION_ACTIVE, L"UEFI Capsule On Disk", DevicePath, - (UINT8 *) &mCapsuleOnDiskBootOptionGuid, - sizeof(EFI_GUID) + (UINT8 *)&mCapsuleOnDiskBootOptionGuid, + sizeof (EFI_GUID) ); if (!EFI_ERROR (Status)) { - Status = EfiBootManagerAddLoadOptionVariable (&NewOption, (UINTN) -1); { + Status = EfiBootManagerAddLoadOptionVariable (&NewOption, (UINTN)-1); + { if (!EFI_ERROR (Status)) { *UpdateBootNext = TRUE; - *BootNext = (UINT16) NewOption.OptionNumber; - Print (L" Boot%04x: %s\n", *BootNext, ConvertDevicePathToText(DevicePath, TRUE, TRUE)); + *BootNext = (UINT16)NewOption.OptionNumber; + Print (L" Boot%04x: %s\n", *BootNext, ConvertDevicePathToText (DevicePath, TRUE, TRUE)); return EFI_SUCCESS; } } @@ -564,25 +577,25 @@ GetUpdateFileSystem ( **/ EFI_STATUS WriteUpdateFile ( - IN VOID **Buffer, - IN UINTN *BufferSize, - IN CHAR16 **FileName, - IN UINTN BufferNum, - IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs -) + IN VOID **Buffer, + IN UINTN *BufferSize, + IN CHAR16 **FileName, + IN UINTN BufferNum, + IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs + ) { - EFI_STATUS Status; - EFI_FILE *Root; - EFI_FILE *FileHandle; - EFI_FILE_PROTOCOL *DirHandle; - UINT64 FileInfo; - VOID *Filebuffer; - UINTN FileSize; - UINTN Index; + EFI_STATUS Status; + EFI_FILE *Root; + EFI_FILE *FileHandle; + EFI_FILE_PROTOCOL *DirHandle; + UINT64 FileInfo; + VOID *Filebuffer; + UINTN FileSize; + UINTN Index; - DirHandle = NULL; - FileHandle = NULL; - Index = 0; + DirHandle = NULL; + FileHandle = NULL; + Index = 0; // // Open Root from SFS @@ -600,15 +613,16 @@ WriteUpdateFile ( if (EFI_ERROR (Status)) { Status = Root->Open (Root, &DirHandle, L"\\EFI", EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, EFI_FILE_DIRECTORY); if (EFI_ERROR (Status)) { - Print(L"Unable to create %s directory\n", L"\\EFI"); + Print (L"Unable to create %s directory\n", L"\\EFI"); return EFI_NOT_FOUND; } } - Status = Root->Open (Root, &DirHandle, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE , 0); + + Status = Root->Open (Root, &DirHandle, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0); if (EFI_ERROR (Status)) { Status = Root->Open (Root, &DirHandle, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, EFI_FILE_DIRECTORY); if (EFI_ERROR (Status)) { - Print(L"Unable to create %s directory\n", EFI_CAPSULE_FILE_DIRECTORY); + Print (L"Unable to create %s directory\n", EFI_CAPSULE_FILE_DIRECTORY); return EFI_NOT_FOUND; } } @@ -643,7 +657,7 @@ WriteUpdateFile ( // Set the file size to 0. // FileInfo = 0; - Status = FileHandleSetSize (FileHandle, FileInfo); + Status = FileHandleSetSize (FileHandle, FileInfo); if (EFI_ERROR (Status)) { Print (L"Error Deleting %s\n", FileName[Index]); FileHandleClose (FileHandle); @@ -655,8 +669,8 @@ WriteUpdateFile ( // Write Filebuffer to file // Filebuffer = Buffer[Index]; - FileSize = BufferSize[Index]; - Status = FileHandleWrite (FileHandle, &FileSize, Filebuffer); + FileSize = BufferSize[Index]; + Status = FileHandleWrite (FileHandle, &FileSize, Filebuffer); if (EFI_ERROR (Status)) { Print (L"Unable to write Capsule Update to %s, Status = %r\n", FileName[Index], Status); return EFI_NOT_FOUND; @@ -680,36 +694,37 @@ WriteUpdateFile ( **/ EFI_STATUS SetCapsuleStatusVariable ( - BOOLEAN SetCap + BOOLEAN SetCap ) { - EFI_STATUS Status; - UINT64 OsIndication; - UINTN DataSize; + EFI_STATUS Status; + UINT64 OsIndication; + UINTN DataSize; OsIndication = 0; - DataSize = sizeof(UINT64); - Status = gRT->GetVariable ( - L"OsIndications", - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - &OsIndication - ); + DataSize = sizeof (UINT64); + Status = gRT->GetVariable ( + L"OsIndications", + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + &OsIndication + ); if (EFI_ERROR (Status)) { OsIndication = 0; } + if (SetCap) { OsIndication |= ((UINT64)EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED); - } - else { + } else { OsIndication &= ~((UINT64)EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED); } + Status = gRT->SetVariable ( L"OsIndications", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, - sizeof(UINT64), + sizeof (UINT64), &OsIndication ); @@ -728,18 +743,18 @@ IsCapsuleOnDiskSupported ( VOID ) { - EFI_STATUS Status; - UINT64 OsIndicationsSupported; - UINTN DataSize; - - DataSize = sizeof(UINT64); - Status = gRT->GetVariable ( - L"OsIndicationsSupported", - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - &OsIndicationsSupported - ); + EFI_STATUS Status; + UINT64 OsIndicationsSupported; + UINTN DataSize; + + DataSize = sizeof (UINT64); + Status = gRT->GetVariable ( + L"OsIndicationsSupported", + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + &OsIndicationsSupported + ); if (EFI_ERROR (Status)) { return FALSE; } @@ -766,19 +781,19 @@ IsCapsuleOnDiskSupported ( **/ EFI_STATUS ProcessCapsuleOnDisk ( - IN VOID **CapsuleBuffer, - IN UINTN *CapsuleBufferSize, - IN CHAR16 **FilePath, - IN CHAR16 *Map, - IN UINTN CapsuleNum + IN VOID **CapsuleBuffer, + IN UINTN *CapsuleBufferSize, + IN CHAR16 **FilePath, + IN CHAR16 *Map, + IN UINTN CapsuleNum ) { - EFI_STATUS Status; - UINT16 BootNext; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; - BOOLEAN UpdateBootNext; - CHAR16 *FileName[MAX_CAPSULE_NUM]; - UINTN Index; + EFI_STATUS Status; + UINT16 BootNext; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + BOOLEAN UpdateBootNext; + CHAR16 *FileName[MAX_CAPSULE_NUM]; + UINTN Index; // // Check if Capsule On Disk is supported @@ -802,7 +817,7 @@ ProcessCapsuleOnDisk ( // // Get file name from file path // - for (Index = 0; Index < CapsuleNum; Index ++) { + for (Index = 0; Index < CapsuleNum; Index++) { FileName[Index] = GetFileNameFromPath (FilePath[Index]); } @@ -826,13 +841,13 @@ ProcessCapsuleOnDisk ( if (UpdateBootNext) { Status = gRT->SetVariable ( - L"BootNext", - &gEfiGlobalVariableGuid, - EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, - sizeof(UINT16), - &BootNext - ); - if (EFI_ERROR (Status)){ + L"BootNext", + &gEfiGlobalVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, + sizeof (UINT16), + &BootNext + ); + if (EFI_ERROR (Status)) { Print (L"CapsuleApp: unable to set BootNext variable.\n"); return Status; } diff --git a/MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.c b/MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.c index 96b35d3da0..b8571c4556 100644 --- a/MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.c +++ b/MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.c @@ -14,7 +14,6 @@ #include #include - #include #include #include @@ -23,7 +22,6 @@ #include #include - // // String token ID of help message text. // Shell supports to find help message in the resource section of an application image if @@ -32,24 +30,23 @@ // the resource section. Thus the application can use '-?' option to show help message in // Shell. // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_STRING_ID mStrDumpDynPcdHelpTokenId = STRING_TOKEN (STR_DUMP_DYN_PCD_HELP_INFORMATION); - -#define MAJOR_VERSION 1 -#define MINOR_VERSION 0 +GLOBAL_REMOVE_IF_UNREFERENCED EFI_STRING_ID mStrDumpDynPcdHelpTokenId = STRING_TOKEN (STR_DUMP_DYN_PCD_HELP_INFORMATION); -static EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL; -static EFI_PCD_PROTOCOL *mPiPcd = NULL; -static PCD_PROTOCOL *mPcd = NULL; -static EFI_GET_PCD_INFO_PROTOCOL *mPiPcdInfo = NULL; -static GET_PCD_INFO_PROTOCOL *mPcdInfo = NULL; -static CHAR16 *mTempPcdNameBuffer = NULL; -static UINTN mTempPcdNameBufferSize = 0; +#define MAJOR_VERSION 1 +#define MINOR_VERSION 0 -static CONST CHAR8 mHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; +static EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL; +static EFI_PCD_PROTOCOL *mPiPcd = NULL; +static PCD_PROTOCOL *mPcd = NULL; +static EFI_GET_PCD_INFO_PROTOCOL *mPiPcdInfo = NULL; +static GET_PCD_INFO_PROTOCOL *mPcdInfo = NULL; +static CHAR16 *mTempPcdNameBuffer = NULL; +static UINTN mTempPcdNameBufferSize = 0; -static UINTN Argc; -static CHAR16 **Argv; +static CONST CHAR8 mHex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; +static UINTN Argc; +static CHAR16 **Argv; /** @@ -63,15 +60,15 @@ GetArg ( VOID ) { - EFI_STATUS Status; - EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters; + EFI_STATUS Status; + EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters; Status = gBS->HandleProtocol ( gImageHandle, &gEfiShellParametersProtocolGuid, - (VOID**)&ShellParameters + (VOID **)&ShellParameters ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -121,21 +118,21 @@ ShowHelp ( static VOID DumpHex ( - IN UINTN Indent, - IN UINTN Offset, - IN UINTN DataSize, - IN VOID *UserData + IN UINTN Indent, + IN UINTN Offset, + IN UINTN DataSize, + IN VOID *UserData ) { - UINT8 *Data; + UINT8 *Data; - CHAR8 Val[50]; + CHAR8 Val[50]; - CHAR8 Str[20]; + CHAR8 Str[20]; - UINT8 TempByte; - UINTN Size; - UINTN Index; + UINT8 TempByte; + UINTN Size; + UINTN Index; Data = UserData; while (DataSize != 0) { @@ -145,24 +142,23 @@ DumpHex ( } for (Index = 0; Index < Size; Index += 1) { - TempByte = Data[Index]; - Val[Index * 3 + 0] = mHex[TempByte >> 4]; - Val[Index * 3 + 1] = mHex[TempByte & 0xF]; - Val[Index * 3 + 2] = (CHAR8) ((Index == 7) ? '-' : ' '); - Str[Index] = (CHAR8) ((TempByte < ' ' || TempByte > 'z') ? '.' : TempByte); + TempByte = Data[Index]; + Val[Index * 3 + 0] = mHex[TempByte >> 4]; + Val[Index * 3 + 1] = mHex[TempByte & 0xF]; + Val[Index * 3 + 2] = (CHAR8)((Index == 7) ? '-' : ' '); + Str[Index] = (CHAR8)((TempByte < ' ' || TempByte > 'z') ? '.' : TempByte); } - Val[Index * 3] = 0; - Str[Index] = 0; + Val[Index * 3] = 0; + Str[Index] = 0; Print (L"%*a%08X: %-48a *%a*\r\n", Indent, "", Offset, Val, Str); - Data += Size; - Offset += Size; + Data += Size; + Offset += Size; DataSize -= Size; } } - /** Safely append with automatic string resizing given length of Destination and desired length of copy from Source. @@ -194,23 +190,23 @@ DumpHex ( @return Destination return the resultant string. **/ static -CHAR16* +CHAR16 * InternalStrnCatGrow ( - IN OUT CHAR16 **Destination, - IN OUT UINTN *CurrentSize, - IN CONST CHAR16 *Source + IN OUT CHAR16 **Destination, + IN OUT UINTN *CurrentSize, + IN CONST CHAR16 *Source ) { - UINTN DestinationStartSize; - UINTN NewSize; - UINTN SourceLen; + UINTN DestinationStartSize; + UINTN NewSize; + UINTN SourceLen; - SourceLen = StrLen(Source); + SourceLen = StrLen (Source); // // ASSERTs // - ASSERT(Destination != NULL); + ASSERT (Destination != NULL); // // If there's nothing to do then just return Destination @@ -222,7 +218,7 @@ InternalStrnCatGrow ( // // allow for un-initialized pointers, based on size being 0 // - if (CurrentSize != NULL && *CurrentSize == 0) { + if ((CurrentSize != NULL) && (*CurrentSize == 0)) { *Destination = NULL; } @@ -230,9 +226,9 @@ InternalStrnCatGrow ( // allow for NULL pointers address as Destination // if (*Destination != NULL) { - ASSERT(CurrentSize != 0); - DestinationStartSize = StrSize(*Destination); - ASSERT(DestinationStartSize <= *CurrentSize); + ASSERT (CurrentSize != 0); + DestinationStartSize = StrSize (*Destination); + ASSERT (DestinationStartSize <= *CurrentSize); } else { DestinationStartSize = 0; } @@ -242,16 +238,17 @@ InternalStrnCatGrow ( // if (CurrentSize != NULL) { NewSize = *CurrentSize; - if (NewSize < DestinationStartSize + (SourceLen * sizeof(CHAR16))) { - while (NewSize < (DestinationStartSize + (SourceLen*sizeof(CHAR16)))) { - NewSize += 2 * SourceLen * sizeof(CHAR16); + if (NewSize < DestinationStartSize + (SourceLen * sizeof (CHAR16))) { + while (NewSize < (DestinationStartSize + (SourceLen*sizeof (CHAR16)))) { + NewSize += 2 * SourceLen * sizeof (CHAR16); } - *Destination = ReallocatePool(*CurrentSize, NewSize, *Destination); + + *Destination = ReallocatePool (*CurrentSize, NewSize, *Destination); *CurrentSize = NewSize; } } else { - NewSize = (SourceLen + 1)*sizeof(CHAR16); - *Destination = AllocateZeroPool(NewSize); + NewSize = (SourceLen + 1)*sizeof (CHAR16); + *Destination = AllocateZeroPool (NewSize); } // @@ -261,7 +258,7 @@ InternalStrnCatGrow ( return (NULL); } - StrnCatS(*Destination, NewSize/sizeof(CHAR16), Source, SourceLen); + StrnCatS (*Destination, NewSize/sizeof (CHAR16), Source, SourceLen); return *Destination; } @@ -276,15 +273,15 @@ InternalStrnCatGrow ( static CHAR16 * GetPcdTypeString ( - IN CONST EFI_GUID *TokenSpace, - IN EFI_PCD_TYPE PcdType + IN CONST EFI_GUID *TokenSpace, + IN EFI_PCD_TYPE PcdType ) { - UINTN BufLen; - CHAR16 *RetString; + UINTN BufLen; + CHAR16 *RetString; - BufLen = 0; - RetString = NULL; + BufLen = 0; + RetString = NULL; switch (PcdType) { case EFI_PCD_TYPE_8: @@ -329,18 +326,18 @@ GetPcdTypeString ( static VOID DumpPcdInfo ( - IN CONST EFI_GUID *TokenSpace, - IN UINTN TokenNumber, - IN EFI_PCD_INFO *PcdInfo + IN CONST EFI_GUID *TokenSpace, + IN UINTN TokenNumber, + IN EFI_PCD_INFO *PcdInfo ) { - CHAR16 *RetString; - UINT8 Uint8; - UINT16 Uint16; - UINT32 Uint32; - UINT64 Uint64; - BOOLEAN Boolean; - VOID *PcdData; + CHAR16 *RetString; + UINT8 Uint8; + UINT16 Uint16; + UINT32 Uint32; + UINT64 Uint64; + BOOLEAN Boolean; + VOID *PcdData; RetString = NULL; @@ -363,6 +360,7 @@ DumpPcdInfo ( } else { Uint8 = mPiPcd->Get8 (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint8); break; case EFI_PCD_TYPE_16: @@ -371,6 +369,7 @@ DumpPcdInfo ( } else { Uint16 = mPiPcd->Get16 (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint16); break; case EFI_PCD_TYPE_32: @@ -379,6 +378,7 @@ DumpPcdInfo ( } else { Uint32 = mPiPcd->Get32 (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint32); break; case EFI_PCD_TYPE_64: @@ -387,6 +387,7 @@ DumpPcdInfo ( } else { Uint64 = mPiPcd->Get64 (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%lx\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint64); break; case EFI_PCD_TYPE_BOOL: @@ -395,6 +396,7 @@ DumpPcdInfo ( } else { Boolean = mPiPcd->GetBool (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = %a\n", TokenNumber, RetString, PcdInfo->PcdSize, Boolean ? "TRUE" : "FALSE"); break; case EFI_PCD_TYPE_PTR: @@ -403,6 +405,7 @@ DumpPcdInfo ( } else { PcdData = mPiPcd->GetPtr (TokenSpace, TokenNumber); } + Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize); DumpHex (2, 0, PcdInfo->PcdSize, PcdData); break; @@ -413,6 +416,7 @@ DumpPcdInfo ( if (RetString != NULL) { FreePool (RetString); } + Print (L"\n"); } @@ -429,20 +433,20 @@ DumpPcdInfo ( static EFI_STATUS ProcessPcd ( - IN CHAR16 *InputPcdName + IN CHAR16 *InputPcdName ) { - EFI_STATUS Status; - EFI_GUID *TokenSpace; - UINTN TokenNumber; - EFI_PCD_INFO PcdInfo; - BOOLEAN Found; - UINTN PcdNameSize; + EFI_STATUS Status; + EFI_GUID *TokenSpace; + UINTN TokenNumber; + EFI_PCD_INFO PcdInfo; + BOOLEAN Found; + UINTN PcdNameSize; PcdInfo.PcdName = NULL; PcdInfo.PcdSize = 0; PcdInfo.PcdType = 0xFF; - Found = FALSE; + Found = FALSE; Print (L"Current system SKU ID: 0x%x\n\n", mPiPcdInfo->GetSku ()); @@ -451,7 +455,7 @@ ProcessPcd ( TokenNumber = 0; do { Status = mPiPcd->GetNextToken (TokenSpace, &TokenNumber); - if (!EFI_ERROR (Status) && TokenNumber != 0) { + if (!EFI_ERROR (Status) && (TokenNumber != 0)) { if (TokenSpace == NULL) { // // PCD in default Token Space. @@ -460,27 +464,32 @@ ProcessPcd ( } else { mPiPcdInfo->GetInfo (TokenSpace, TokenNumber, &PcdInfo); } + if (InputPcdName != NULL) { if (PcdInfo.PcdName == NULL) { continue; } + PcdNameSize = AsciiStrSize (PcdInfo.PcdName) * sizeof (CHAR16); if (mTempPcdNameBuffer == NULL) { mTempPcdNameBufferSize = PcdNameSize; - mTempPcdNameBuffer = AllocatePool (mTempPcdNameBufferSize); + mTempPcdNameBuffer = AllocatePool (mTempPcdNameBufferSize); } else if (mTempPcdNameBufferSize < PcdNameSize) { - mTempPcdNameBuffer = ReallocatePool (mTempPcdNameBufferSize, PcdNameSize, mTempPcdNameBuffer); + mTempPcdNameBuffer = ReallocatePool (mTempPcdNameBufferSize, PcdNameSize, mTempPcdNameBuffer); mTempPcdNameBufferSize = PcdNameSize; } + if (mTempPcdNameBuffer == NULL) { return EFI_OUT_OF_RESOURCES; } + AsciiStrToUnicodeStrS (PcdInfo.PcdName, mTempPcdNameBuffer, mTempPcdNameBufferSize / sizeof (CHAR16)); // // Compare the input PCD name with the PCD name in PCD database. // if ((StrStr (mTempPcdNameBuffer, InputPcdName) != NULL) || - (mUnicodeCollation != NULL && mUnicodeCollation->MetaiMatch (mUnicodeCollation, mTempPcdNameBuffer, InputPcdName))) { + ((mUnicodeCollation != NULL) && mUnicodeCollation->MetaiMatch (mUnicodeCollation, mTempPcdNameBuffer, InputPcdName))) + { // // Found matched PCD. // @@ -493,7 +502,7 @@ ProcessPcd ( } } while (!EFI_ERROR (Status) && TokenNumber != 0); - Status = mPiPcd->GetNextTokenSpace ((CONST EFI_GUID **) &TokenSpace); + Status = mPiPcd->GetNextTokenSpace ((CONST EFI_GUID **)&TokenSpace); } while (!EFI_ERROR (Status) && TokenSpace != NULL); if ((InputPcdName != NULL) && !Found) { @@ -503,6 +512,7 @@ ProcessPcd ( Print (L"%EError. %NNo matching PCD found: %s.\n", InputPcdName); return EFI_NOT_FOUND; } + return EFI_SUCCESS; } @@ -526,35 +536,35 @@ DumpDynPcdMain ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - CHAR16 *InputPcdName; + EFI_STATUS Status; + CHAR16 *InputPcdName; - InputPcdName = NULL; + InputPcdName = NULL; - Status = gBS->LocateProtocol(&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID **) &mUnicodeCollation); + Status = gBS->LocateProtocol (&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID **)&mUnicodeCollation); if (EFI_ERROR (Status)) { mUnicodeCollation = NULL; } - Status = gBS->LocateProtocol (&gEfiPcdProtocolGuid, NULL, (VOID **) &mPiPcd); + Status = gBS->LocateProtocol (&gEfiPcdProtocolGuid, NULL, (VOID **)&mPiPcd); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPI PCD protocol is not present.\n"); return Status; } - Status = gBS->LocateProtocol (&gEfiGetPcdInfoProtocolGuid, NULL, (VOID **) &mPiPcdInfo); + Status = gBS->LocateProtocol (&gEfiGetPcdInfoProtocolGuid, NULL, (VOID **)&mPiPcdInfo); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPI PCD info protocol is not present.\n"); return Status; } - Status = gBS->LocateProtocol (&gPcdProtocolGuid, NULL, (VOID **) &mPcd); + Status = gBS->LocateProtocol (&gPcdProtocolGuid, NULL, (VOID **)&mPcd); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPCD protocol is not present.\n"); return Status; } - Status = gBS->LocateProtocol (&gGetPcdInfoProtocolGuid, NULL, (VOID **) &mPcdInfo); + Status = gBS->LocateProtocol (&gGetPcdInfoProtocolGuid, NULL, (VOID **)&mPcdInfo); if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NPCD info protocol is not present.\n"); return Status; @@ -563,33 +573,33 @@ DumpDynPcdMain ( // // get the command line arguments // - Status = GetArg(); - if (EFI_ERROR(Status)){ + Status = GetArg (); + if (EFI_ERROR (Status)) { Print (L"DumpDynPcd: %EError. %NThe input parameters are not recognized.\n"); Status = EFI_INVALID_PARAMETER; return Status; } - if (Argc > 2){ + if (Argc > 2) { Print (L"DumpDynPcd: %EError. %NToo many arguments specified.\n"); Status = EFI_INVALID_PARAMETER; return Status; } - if (Argc == 1){ + if (Argc == 1) { Status = ProcessPcd (InputPcdName); goto Done; } - if ((StrCmp(Argv[1], L"-?") == 0)||(StrCmp(Argv[1], L"-h") == 0)||(StrCmp(Argv[1], L"-H") == 0)){ + if ((StrCmp (Argv[1], L"-?") == 0) || (StrCmp (Argv[1], L"-h") == 0) || (StrCmp (Argv[1], L"-H") == 0)) { ShowHelp (); goto Done; } else { - if ((StrCmp(Argv[1], L"-v") == 0)||(StrCmp(Argv[1], L"-V") == 0)){ + if ((StrCmp (Argv[1], L"-v") == 0) || (StrCmp (Argv[1], L"-V") == 0)) { ShowVersion (); goto Done; } else { - if (StrStr(Argv[1], L"-") != NULL){ + if (StrStr (Argv[1], L"-") != NULL) { Print (L"DumpDynPcd: %EError. %NThe argument '%B%s%N' is invalid.\n", Argv[1]); goto Done; } @@ -597,9 +607,9 @@ DumpDynPcdMain ( } InputPcdName = Argv[1]; - Status = ProcessPcd (InputPcdName); + Status = ProcessPcd (InputPcdName); - Done: +Done: if (mTempPcdNameBuffer != NULL) { FreePool (mTempPcdNameBuffer); @@ -607,4 +617,3 @@ DumpDynPcdMain ( return Status; } - diff --git a/MdeModulePkg/Application/HelloWorld/HelloWorld.c b/MdeModulePkg/Application/HelloWorld/HelloWorld.c index e45a3746e7..ab581c040c 100644 --- a/MdeModulePkg/Application/HelloWorld/HelloWorld.c +++ b/MdeModulePkg/Application/HelloWorld/HelloWorld.c @@ -20,7 +20,7 @@ // the resource section. Thus the application can use '-?' option to show help message in // Shell. // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_STRING_ID mStringHelpTokenId = STRING_TOKEN (STR_HELLO_WORLD_HELP_INFORMATION); +GLOBAL_REMOVE_IF_UNREFERENCED EFI_STRING_ID mStringHelpTokenId = STRING_TOKEN (STR_HELLO_WORLD_HELP_INFORMATION); /** The user Entry Point for Application. The user code starts with this function @@ -40,7 +40,7 @@ UefiMain ( IN EFI_SYSTEM_TABLE *SystemTable ) { - UINT32 Index; + UINT32 Index; Index = 0; @@ -48,11 +48,11 @@ UefiMain ( // Three PCD type (FeatureFlag, UINT32 and String) are used as the sample. // if (FeaturePcdGet (PcdHelloWorldPrintEnable)) { - for (Index = 0; Index < PcdGet32 (PcdHelloWorldPrintTimes); Index ++) { + for (Index = 0; Index < PcdGet32 (PcdHelloWorldPrintTimes); Index++) { // // Use UefiLib Print API to print string to UEFI console // - Print ((CHAR16*)PcdGetPtr (PcdHelloWorldPrintString)); + Print ((CHAR16 *)PcdGetPtr (PcdHelloWorldPrintString)); } } diff --git a/MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c b/MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c index 99a2d52db1..326603503f 100644 --- a/MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c +++ b/MdeModulePkg/Application/MemoryProfileInfo/MemoryProfileInfo.c @@ -24,7 +24,7 @@ #include #include -CHAR8 *mActionString[] = { +CHAR8 *mActionString[] = { "Unknown", "gBS->AllocatePages", "gBS->FreePages", @@ -32,7 +32,7 @@ CHAR8 *mActionString[] = { "gBS->FreePool", }; -CHAR8 *mSmmActionString[] = { +CHAR8 *mSmmActionString[] = { "SmmUnknown", "gSmst->SmmAllocatePages", "gSmst->SmmFreePages", @@ -41,37 +41,37 @@ CHAR8 *mSmmActionString[] = { }; typedef struct { - MEMORY_PROFILE_ACTION Action; - CHAR8 *String; + MEMORY_PROFILE_ACTION Action; + CHAR8 *String; } ACTION_STRING; -ACTION_STRING mExtActionString[] = { - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, "Lib:AllocatePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, "Lib:AllocateRuntimePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES, "Lib:AllocateReservedPages"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_PAGES, "Lib:FreePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, "Lib:AllocateAlignedPages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, "Lib:AllocateAlignedRuntimePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES, "Lib:AllocateAlignedReservedPages"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES, "Lib:FreeAlignedPages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, "Lib:AllocatePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, "Lib:AllocateRuntimePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL, "Lib:AllocateReservedPool"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_POOL, "Lib:FreePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, "Lib:AllocateZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, "Lib:AllocateRuntimeZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL, "Lib:AllocateReservedZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, "Lib:AllocateCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, "Lib:AllocateRuntimeCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL, "Lib:AllocateReservedCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, "Lib:ReallocatePool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, "Lib:ReallocateRuntimePool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL, "Lib:ReallocateReservedPool"}, +ACTION_STRING mExtActionString[] = { + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, "Lib:AllocatePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, "Lib:AllocateRuntimePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES, "Lib:AllocateReservedPages" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_PAGES, "Lib:FreePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, "Lib:AllocateAlignedPages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, "Lib:AllocateAlignedRuntimePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES, "Lib:AllocateAlignedReservedPages" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES, "Lib:FreeAlignedPages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, "Lib:AllocatePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, "Lib:AllocateRuntimePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL, "Lib:AllocateReservedPool" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_POOL, "Lib:FreePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, "Lib:AllocateZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, "Lib:AllocateRuntimeZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL, "Lib:AllocateReservedZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, "Lib:AllocateCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, "Lib:AllocateRuntimeCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL, "Lib:AllocateReservedCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, "Lib:ReallocatePool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, "Lib:ReallocateRuntimePool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL, "Lib:ReallocateReservedPool" }, }; -CHAR8 mUserDefinedActionString[] = {"UserDefined-0x80000000"}; +CHAR8 mUserDefinedActionString[] = { "UserDefined-0x80000000" }; -CHAR8 *mMemoryTypeString[] = { +CHAR8 *mMemoryTypeString[] = { "EfiReservedMemoryType", "EfiLoaderCode", "EfiLoaderData", @@ -91,7 +91,7 @@ CHAR8 *mMemoryTypeString[] = { "EfiOemReserved", }; -CHAR8 *mSubsystemString[] = { +CHAR8 *mSubsystemString[] = { "Unknown", "NATIVE", "WINDOWS_GUI", @@ -110,7 +110,7 @@ CHAR8 *mSubsystemString[] = { "Unknown", }; -CHAR8 *mFileTypeString[] = { +CHAR8 *mFileTypeString[] = { "Unknown", "RAW", "FREEFORM", @@ -128,27 +128,27 @@ CHAR8 *mFileTypeString[] = { }; #define PROFILE_NAME_STRING_LENGTH 64 -CHAR8 mNameString[PROFILE_NAME_STRING_LENGTH + 1]; +CHAR8 mNameString[PROFILE_NAME_STRING_LENGTH + 1]; // // Profile summary information // -#define MEMORY_PROFILE_ALLOC_SUMMARY_INFO_SIGNATURE SIGNATURE_32 ('M','P','A','S') -#define MEMORY_PROFILE_ALLOC_SUMMARY_INFO_REVISION 0x0001 +#define MEMORY_PROFILE_ALLOC_SUMMARY_INFO_SIGNATURE SIGNATURE_32 ('M','P','A','S') +#define MEMORY_PROFILE_ALLOC_SUMMARY_INFO_REVISION 0x0001 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - PHYSICAL_ADDRESS CallerAddress; - MEMORY_PROFILE_ACTION Action; - CHAR8 *ActionString; - UINT32 AllocateCount; - UINT64 TotalSize; + MEMORY_PROFILE_COMMON_HEADER Header; + PHYSICAL_ADDRESS CallerAddress; + MEMORY_PROFILE_ACTION Action; + CHAR8 *ActionString; + UINT32 AllocateCount; + UINT64 TotalSize; } MEMORY_PROFILE_ALLOC_SUMMARY_INFO; typedef struct { - UINT32 Signature; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO AllocSummaryInfo; - LIST_ENTRY Link; + UINT32 Signature; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO AllocSummaryInfo; + LIST_ENTRY Link; } MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA; typedef struct { @@ -159,13 +159,13 @@ typedef struct { } MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA; typedef struct { - UINT32 Signature; - MEMORY_PROFILE_CONTEXT *Context; - LIST_ENTRY *DriverSummaryInfoList; + UINT32 Signature; + MEMORY_PROFILE_CONTEXT *Context; + LIST_ENTRY *DriverSummaryInfoList; } MEMORY_PROFILE_CONTEXT_SUMMARY_DATA; -LIST_ENTRY mImageSummaryQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageSummaryQueue); -MEMORY_PROFILE_CONTEXT_SUMMARY_DATA mMemoryProfileContextSummary; +LIST_ENTRY mImageSummaryQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageSummaryQueue); +MEMORY_PROFILE_CONTEXT_SUMMARY_DATA mMemoryProfileContextSummary; /** Get the file name portion of the Pdb File Name. @@ -181,14 +181,14 @@ MEMORY_PROFILE_CONTEXT_SUMMARY_DATA mMemoryProfileContextSummary; **/ VOID GetShortPdbFileName ( - IN CHAR8 *PdbFileName, - OUT CHAR8 *AsciiBuffer + IN CHAR8 *PdbFileName, + OUT CHAR8 *AsciiBuffer ) { - UINTN IndexPdb; // Current work location within a Pdb string. - UINTN IndexBuffer; // Current work location within a Buffer string. - UINTN StartIndex; - UINTN EndIndex; + UINTN IndexPdb; // Current work location within a Pdb string. + UINTN IndexBuffer; // Current work location within a Buffer string. + UINTN StartIndex; + UINTN EndIndex; ZeroMem (AsciiBuffer, PROFILE_NAME_STRING_LENGTH + 1); @@ -196,7 +196,9 @@ GetShortPdbFileName ( AsciiStrnCpyS (AsciiBuffer, PROFILE_NAME_STRING_LENGTH + 1, " ", 1); } else { StartIndex = 0; - for (EndIndex = 0; PdbFileName[EndIndex] != 0; EndIndex++); + for (EndIndex = 0; PdbFileName[EndIndex] != 0; EndIndex++) { + } + for (IndexPdb = 0; PdbFileName[IndexPdb] != 0; IndexPdb++) { if ((PdbFileName[IndexPdb] == '\\') || (PdbFileName[IndexPdb] == '/')) { StartIndex = IndexPdb + 1; @@ -233,18 +235,18 @@ GetShortPdbFileName ( **/ CHAR8 * GetDriverNameString ( - IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo - ) + IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo + ) { - EFI_STATUS Status; - CHAR16 *NameString; - UINTN StringSize; + EFI_STATUS Status; + CHAR16 *NameString; + UINTN StringSize; // // Method 1: Get the name string from image PDB // if (DriverInfo->PdbStringOffset != 0) { - GetShortPdbFileName ((CHAR8 *) ((UINTN) DriverInfo + DriverInfo->PdbStringOffset), mNameString); + GetShortPdbFileName ((CHAR8 *)((UINTN)DriverInfo + DriverInfo->PdbStringOffset), mNameString); return mNameString; } @@ -254,13 +256,13 @@ GetDriverNameString ( // NameString = NULL; StringSize = 0; - Status = GetSectionFromAnyFv ( - &DriverInfo->FileName, - EFI_SECTION_USER_INTERFACE, - 0, - (VOID **) &NameString, - &StringSize - ); + Status = GetSectionFromAnyFv ( + &DriverInfo->FileName, + EFI_SECTION_USER_INTERFACE, + 0, + (VOID **)&NameString, + &StringSize + ); if (!EFI_ERROR (Status)) { // // Method 2: Get the name string from FFS UI section @@ -268,6 +270,7 @@ GetDriverNameString ( if (StrLen (NameString) > PROFILE_NAME_STRING_LENGTH) { NameString[PROFILE_NAME_STRING_LENGTH] = 0; } + UnicodeStrToAsciiStrS (NameString, mNameString, sizeof (mNameString)); FreePool (NameString); return mNameString; @@ -291,17 +294,17 @@ GetDriverNameString ( **/ CHAR8 * ProfileMemoryTypeToStr ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - UINTN Index; + UINTN Index; - if ((UINT32) MemoryType >= 0x80000000) { + if ((UINT32)MemoryType >= 0x80000000) { // // OS reserved memory type. // Index = EfiMaxMemoryType; - } else if ((UINT32) MemoryType >= 0x70000000) { + } else if ((UINT32)MemoryType >= 0x70000000) { // // OEM reserved memory type. // @@ -331,30 +334,33 @@ ProfileActionToStr ( IN BOOLEAN IsForSmm ) { - UINTN Index; - UINTN ActionStringCount; - CHAR8 **ActionString; + UINTN Index; + UINTN ActionStringCount; + CHAR8 **ActionString; if (IsForSmm) { - ActionString = mSmmActionString; + ActionString = mSmmActionString; ActionStringCount = ARRAY_SIZE (mSmmActionString); } else { - ActionString = mActionString; + ActionString = mActionString; ActionStringCount = ARRAY_SIZE (mActionString); } - if ((UINTN) (UINT32) Action < ActionStringCount) { + if ((UINTN)(UINT32)Action < ActionStringCount) { return ActionString[Action]; } + for (Index = 0; Index < ARRAY_SIZE (mExtActionString); Index++) { if (mExtActionString[Index].Action == Action) { return mExtActionString[Index].String; } } + if ((Action & MEMORY_PROFILE_ACTION_USER_DEFINED_MASK) != 0) { if (UserDefinedActionString != NULL) { return UserDefinedActionString; } + AsciiSPrint (mUserDefinedActionString, sizeof (mUserDefinedActionString), "UserDefined-0x%08x", Action); return mUserDefinedActionString; } @@ -376,20 +382,20 @@ ProfileActionToStr ( **/ MEMORY_PROFILE_ALLOC_INFO * DumpMemoryProfileAllocInfo ( - IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo, - IN UINTN AllocIndex, - IN MEMORY_PROFILE_ALLOC_INFO *AllocInfo, - IN BOOLEAN IsForSmm + IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo, + IN UINTN AllocIndex, + IN MEMORY_PROFILE_ALLOC_INFO *AllocInfo, + IN BOOLEAN IsForSmm ) { - CHAR8 *ActionString; + CHAR8 *ActionString; if (AllocInfo->Header.Signature != MEMORY_PROFILE_ALLOC_INFO_SIGNATURE) { return NULL; } if (AllocInfo->ActionStringOffset != 0) { - ActionString = (CHAR8 *) ((UINTN) AllocInfo + AllocInfo->ActionStringOffset); + ActionString = (CHAR8 *)((UINTN)AllocInfo + AllocInfo->ActionStringOffset); } else { ActionString = NULL; } @@ -398,14 +404,14 @@ DumpMemoryProfileAllocInfo ( Print (L" Signature - 0x%08x\n", AllocInfo->Header.Signature); Print (L" Length - 0x%04x\n", AllocInfo->Header.Length); Print (L" Revision - 0x%04x\n", AllocInfo->Header.Revision); - Print (L" CallerAddress - 0x%016lx (Offset: 0x%08x)\n", AllocInfo->CallerAddress, (UINTN) (AllocInfo->CallerAddress - DriverInfo->ImageBase)); + Print (L" CallerAddress - 0x%016lx (Offset: 0x%08x)\n", AllocInfo->CallerAddress, (UINTN)(AllocInfo->CallerAddress - DriverInfo->ImageBase)); Print (L" SequenceId - 0x%08x\n", AllocInfo->SequenceId); Print (L" Action - 0x%08x (%a)\n", AllocInfo->Action, ProfileActionToStr (AllocInfo->Action, ActionString, IsForSmm)); Print (L" MemoryType - 0x%08x (%a)\n", AllocInfo->MemoryType, ProfileMemoryTypeToStr (AllocInfo->MemoryType)); Print (L" Buffer - 0x%016lx\n", AllocInfo->Buffer); Print (L" Size - 0x%016lx\n", AllocInfo->Size); - return (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) AllocInfo + AllocInfo->Header.Length); + return (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)AllocInfo + AllocInfo->Header.Length); } /** @@ -421,19 +427,20 @@ DumpMemoryProfileAllocInfo ( **/ MEMORY_PROFILE_DRIVER_INFO * DumpMemoryProfileDriverInfo ( - IN UINTN DriverIndex, - IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo, - IN BOOLEAN IsForSmm + IN UINTN DriverIndex, + IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo, + IN BOOLEAN IsForSmm ) { - UINTN TypeIndex; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - UINTN AllocIndex; - CHAR8 *NameString; + UINTN TypeIndex; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + UINTN AllocIndex; + CHAR8 *NameString; if (DriverInfo->Header.Signature != MEMORY_PROFILE_DRIVER_INFO_SIGNATURE) { return NULL; } + Print (L" MEMORY_PROFILE_DRIVER_INFO (0x%x)\n", DriverIndex); Print (L" Signature - 0x%08x\n", DriverInfo->Header.Signature); Print (L" Length - 0x%04x\n", DriverInfo->Header.Length); @@ -441,32 +448,36 @@ DumpMemoryProfileDriverInfo ( NameString = GetDriverNameString (DriverInfo); Print (L" FileName - %a\n", NameString); if (DriverInfo->PdbStringOffset != 0) { - Print (L" Pdb - %a\n", (CHAR8 *) ((UINTN) DriverInfo + DriverInfo->PdbStringOffset)); + Print (L" Pdb - %a\n", (CHAR8 *)((UINTN)DriverInfo + DriverInfo->PdbStringOffset)); } + Print (L" ImageBase - 0x%016lx\n", DriverInfo->ImageBase); Print (L" ImageSize - 0x%016lx\n", DriverInfo->ImageSize); Print (L" EntryPoint - 0x%016lx\n", DriverInfo->EntryPoint); - Print (L" ImageSubsystem - 0x%04x (%a)\n", DriverInfo->ImageSubsystem, mSubsystemString[(DriverInfo->ImageSubsystem < sizeof(mSubsystemString)/sizeof(mSubsystemString[0])) ? DriverInfo->ImageSubsystem : 0]); - Print (L" FileType - 0x%02x (%a)\n", DriverInfo->FileType, mFileTypeString[(DriverInfo->FileType < sizeof(mFileTypeString)/sizeof(mFileTypeString[0])) ? DriverInfo->FileType : 0]); + Print (L" ImageSubsystem - 0x%04x (%a)\n", DriverInfo->ImageSubsystem, mSubsystemString[(DriverInfo->ImageSubsystem < sizeof (mSubsystemString)/sizeof (mSubsystemString[0])) ? DriverInfo->ImageSubsystem : 0]); + Print (L" FileType - 0x%02x (%a)\n", DriverInfo->FileType, mFileTypeString[(DriverInfo->FileType < sizeof (mFileTypeString)/sizeof (mFileTypeString[0])) ? DriverInfo->FileType : 0]); Print (L" CurrentUsage - 0x%016lx\n", DriverInfo->CurrentUsage); Print (L" PeakUsage - 0x%016lx\n", DriverInfo->PeakUsage); for (TypeIndex = 0; TypeIndex < sizeof (DriverInfo->CurrentUsageByType) / sizeof (DriverInfo->CurrentUsageByType[0]); TypeIndex++) { if ((DriverInfo->CurrentUsageByType[TypeIndex] != 0) || - (DriverInfo->PeakUsageByType[TypeIndex] != 0)) { + (DriverInfo->PeakUsageByType[TypeIndex] != 0)) + { Print (L" CurrentUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, DriverInfo->CurrentUsageByType[TypeIndex], mMemoryTypeString[TypeIndex]); Print (L" PeakUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, DriverInfo->PeakUsageByType[TypeIndex], mMemoryTypeString[TypeIndex]); } } + Print (L" AllocRecordCount - 0x%08x\n", DriverInfo->AllocRecordCount); - AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) DriverInfo + DriverInfo->Header.Length); + AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)DriverInfo + DriverInfo->Header.Length); for (AllocIndex = 0; AllocIndex < DriverInfo->AllocRecordCount; AllocIndex++) { AllocInfo = DumpMemoryProfileAllocInfo (DriverInfo, AllocIndex, AllocInfo, IsForSmm); if (AllocInfo == NULL) { return NULL; } } - return (MEMORY_PROFILE_DRIVER_INFO *) AllocInfo; + + return (MEMORY_PROFILE_DRIVER_INFO *)AllocInfo; } /** @@ -481,17 +492,18 @@ DumpMemoryProfileDriverInfo ( **/ VOID * DumpMemoryProfileContext ( - IN MEMORY_PROFILE_CONTEXT *Context, - IN BOOLEAN IsForSmm + IN MEMORY_PROFILE_CONTEXT *Context, + IN BOOLEAN IsForSmm ) { - UINTN TypeIndex; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - UINTN DriverIndex; + UINTN TypeIndex; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + UINTN DriverIndex; if (Context->Header.Signature != MEMORY_PROFILE_CONTEXT_SIGNATURE) { return NULL; } + Print (L"MEMORY_PROFILE_CONTEXT\n"); Print (L" Signature - 0x%08x\n", Context->Header.Signature); Print (L" Length - 0x%04x\n", Context->Header.Length); @@ -500,23 +512,26 @@ DumpMemoryProfileContext ( Print (L" PeakTotalUsage - 0x%016lx\n", Context->PeakTotalUsage); for (TypeIndex = 0; TypeIndex < sizeof (Context->CurrentTotalUsageByType) / sizeof (Context->CurrentTotalUsageByType[0]); TypeIndex++) { if ((Context->CurrentTotalUsageByType[TypeIndex] != 0) || - (Context->PeakTotalUsageByType[TypeIndex] != 0)) { + (Context->PeakTotalUsageByType[TypeIndex] != 0)) + { Print (L" CurrentTotalUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, Context->CurrentTotalUsageByType[TypeIndex], mMemoryTypeString[TypeIndex]); Print (L" PeakTotalUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, Context->PeakTotalUsageByType[TypeIndex], mMemoryTypeString[TypeIndex]); } } + Print (L" TotalImageSize - 0x%016lx\n", Context->TotalImageSize); Print (L" ImageCount - 0x%08x\n", Context->ImageCount); Print (L" SequenceCount - 0x%08x\n", Context->SequenceCount); - DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *) ((UINTN) Context + Context->Header.Length); + DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *)((UINTN)Context + Context->Header.Length); for (DriverIndex = 0; DriverIndex < Context->ImageCount; DriverIndex++) { DriverInfo = DumpMemoryProfileDriverInfo (DriverIndex, DriverInfo, IsForSmm); if (DriverInfo == NULL) { return NULL; } } - return (VOID *) DriverInfo; + + return (VOID *)DriverInfo; } /** @@ -537,6 +552,7 @@ DumpMemoryProfileDescriptor ( if (Descriptor->Header.Signature != MEMORY_PROFILE_DESCRIPTOR_SIGNATURE) { return NULL; } + Print (L" MEMORY_PROFILE_DESCRIPTOR (0x%x)\n", DescriptorIndex); Print (L" Signature - 0x%08x\n", Descriptor->Header.Signature); Print (L" Length - 0x%04x\n", Descriptor->Header.Length); @@ -544,7 +560,7 @@ DumpMemoryProfileDescriptor ( Print (L" Address - 0x%016lx\n", Descriptor->Address); Print (L" Size - 0x%016lx\n", Descriptor->Size); - return (MEMORY_PROFILE_DESCRIPTOR *) ((UINTN) Descriptor + Descriptor->Header.Length); + return (MEMORY_PROFILE_DESCRIPTOR *)((UINTN)Descriptor + Descriptor->Header.Length); } /** @@ -557,15 +573,16 @@ DumpMemoryProfileDescriptor ( **/ VOID * DumpMemoryProfileFreeMemory ( - IN MEMORY_PROFILE_FREE_MEMORY *FreeMemory + IN MEMORY_PROFILE_FREE_MEMORY *FreeMemory ) { - MEMORY_PROFILE_DESCRIPTOR *Descriptor; - UINTN DescriptorIndex; + MEMORY_PROFILE_DESCRIPTOR *Descriptor; + UINTN DescriptorIndex; if (FreeMemory->Header.Signature != MEMORY_PROFILE_FREE_MEMORY_SIGNATURE) { return NULL; } + Print (L"MEMORY_PROFILE_FREE_MEMORY\n"); Print (L" Signature - 0x%08x\n", FreeMemory->Header.Signature); Print (L" Length - 0x%04x\n", FreeMemory->Header.Length); @@ -573,7 +590,7 @@ DumpMemoryProfileFreeMemory ( Print (L" TotalFreeMemoryPages - 0x%016lx\n", FreeMemory->TotalFreeMemoryPages); Print (L" FreeMemoryEntryCount - 0x%08x\n", FreeMemory->FreeMemoryEntryCount); - Descriptor = (MEMORY_PROFILE_DESCRIPTOR *) ((UINTN) FreeMemory + FreeMemory->Header.Length); + Descriptor = (MEMORY_PROFILE_DESCRIPTOR *)((UINTN)FreeMemory + FreeMemory->Header.Length); for (DescriptorIndex = 0; DescriptorIndex < FreeMemory->FreeMemoryEntryCount; DescriptorIndex++) { Descriptor = DumpMemoryProfileDescriptor (DescriptorIndex, Descriptor); if (Descriptor == NULL) { @@ -581,7 +598,7 @@ DumpMemoryProfileFreeMemory ( } } - return (VOID *) Descriptor; + return (VOID *)Descriptor; } /** @@ -594,22 +611,23 @@ DumpMemoryProfileFreeMemory ( **/ VOID * DumpMemoryProfileMemoryRange ( - IN MEMORY_PROFILE_MEMORY_RANGE *MemoryRange + IN MEMORY_PROFILE_MEMORY_RANGE *MemoryRange ) { - MEMORY_PROFILE_DESCRIPTOR *Descriptor; - UINTN DescriptorIndex; + MEMORY_PROFILE_DESCRIPTOR *Descriptor; + UINTN DescriptorIndex; if (MemoryRange->Header.Signature != MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE) { return NULL; } + Print (L"MEMORY_PROFILE_MEMORY_RANGE\n"); Print (L" Signature - 0x%08x\n", MemoryRange->Header.Signature); Print (L" Length - 0x%04x\n", MemoryRange->Header.Length); Print (L" Revision - 0x%04x\n", MemoryRange->Header.Revision); Print (L" MemoryRangeCount - 0x%08x\n", MemoryRange->MemoryRangeCount); - Descriptor = (MEMORY_PROFILE_DESCRIPTOR *) ((UINTN) MemoryRange + MemoryRange->Header.Length); + Descriptor = (MEMORY_PROFILE_DESCRIPTOR *)((UINTN)MemoryRange + MemoryRange->Header.Length); for (DescriptorIndex = 0; DescriptorIndex < MemoryRange->MemoryRangeCount; DescriptorIndex++) { Descriptor = DumpMemoryProfileDescriptor (DescriptorIndex, Descriptor); if (Descriptor == NULL) { @@ -617,7 +635,7 @@ DumpMemoryProfileMemoryRange ( } } - return (VOID *) Descriptor; + return (VOID *)Descriptor; } /** @@ -632,28 +650,30 @@ DumpMemoryProfileMemoryRange ( **/ VOID * ScanMemoryProfileBySignature ( - IN PHYSICAL_ADDRESS ProfileBuffer, - IN UINT64 ProfileSize, - IN UINT32 Signature + IN PHYSICAL_ADDRESS ProfileBuffer, + IN UINT64 ProfileSize, + IN UINT32 Signature ) { MEMORY_PROFILE_COMMON_HEADER *CommonHeader; - UINTN ProfileEnd; + UINTN ProfileEnd; - ProfileEnd = (UINTN) (ProfileBuffer + ProfileSize); - CommonHeader = (MEMORY_PROFILE_COMMON_HEADER *) (UINTN) ProfileBuffer; - while ((UINTN) CommonHeader < ProfileEnd) { + ProfileEnd = (UINTN)(ProfileBuffer + ProfileSize); + CommonHeader = (MEMORY_PROFILE_COMMON_HEADER *)(UINTN)ProfileBuffer; + while ((UINTN)CommonHeader < ProfileEnd) { if (CommonHeader->Signature == Signature) { // // Found it. // - return (VOID *) CommonHeader; + return (VOID *)CommonHeader; } + if (CommonHeader->Length == 0) { ASSERT (FALSE); return NULL; } - CommonHeader = (MEMORY_PROFILE_COMMON_HEADER *) ((UINTN) CommonHeader + CommonHeader->Length); + + CommonHeader = (MEMORY_PROFILE_COMMON_HEADER *)((UINTN)CommonHeader + CommonHeader->Length); } return NULL; @@ -670,26 +690,26 @@ ScanMemoryProfileBySignature ( **/ VOID DumpMemoryProfile ( - IN PHYSICAL_ADDRESS ProfileBuffer, - IN UINT64 ProfileSize, - IN BOOLEAN IsForSmm + IN PHYSICAL_ADDRESS ProfileBuffer, + IN UINT64 ProfileSize, + IN BOOLEAN IsForSmm ) { - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_FREE_MEMORY *FreeMemory; - MEMORY_PROFILE_MEMORY_RANGE *MemoryRange; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_FREE_MEMORY *FreeMemory; + MEMORY_PROFILE_MEMORY_RANGE *MemoryRange; - Context = (MEMORY_PROFILE_CONTEXT *) ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_CONTEXT_SIGNATURE); + Context = (MEMORY_PROFILE_CONTEXT *)ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_CONTEXT_SIGNATURE); if (Context != NULL) { DumpMemoryProfileContext (Context, IsForSmm); } - FreeMemory = (MEMORY_PROFILE_FREE_MEMORY *) ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_FREE_MEMORY_SIGNATURE); + FreeMemory = (MEMORY_PROFILE_FREE_MEMORY *)ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_FREE_MEMORY_SIGNATURE); if (FreeMemory != NULL) { DumpMemoryProfileFreeMemory (FreeMemory); } - MemoryRange = (MEMORY_PROFILE_MEMORY_RANGE *) ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE); + MemoryRange = (MEMORY_PROFILE_MEMORY_RANGE *)ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE); if (MemoryRange != NULL) { DumpMemoryProfileMemoryRange (MemoryRange); } @@ -706,20 +726,21 @@ DumpMemoryProfile ( **/ MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA * GetAllocSummaryInfoByCallerAddress ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData ) { - LIST_ENTRY *AllocSummaryInfoList; - LIST_ENTRY *AllocSummaryLink; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; + LIST_ENTRY *AllocSummaryInfoList; + LIST_ENTRY *AllocSummaryLink; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; AllocSummaryInfoList = DriverSummaryInfoData->AllocSummaryInfoList; for (AllocSummaryLink = AllocSummaryInfoList->ForwardLink; AllocSummaryLink != AllocSummaryInfoList; - AllocSummaryLink = AllocSummaryLink->ForwardLink) { + AllocSummaryLink = AllocSummaryLink->ForwardLink) + { AllocSummaryInfoData = CR ( AllocSummaryLink, MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA, @@ -731,6 +752,7 @@ GetAllocSummaryInfoByCallerAddress ( return AllocSummaryInfoData; } } + return NULL; } @@ -746,12 +768,12 @@ GetAllocSummaryInfoByCallerAddress ( **/ MEMORY_PROFILE_ALLOC_INFO * CreateAllocSummaryInfo ( - IN OUT MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData, - IN MEMORY_PROFILE_ALLOC_INFO *AllocInfo + IN OUT MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData, + IN MEMORY_PROFILE_ALLOC_INFO *AllocInfo ) { - MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; if (AllocInfo->Header.Signature != MEMORY_PROFILE_ALLOC_INFO_SIGNATURE) { return NULL; @@ -764,27 +786,29 @@ CreateAllocSummaryInfo ( return NULL; } - AllocSummaryInfoData->Signature = MEMORY_PROFILE_ALLOC_SUMMARY_INFO_SIGNATURE; - AllocSummaryInfo = &AllocSummaryInfoData->AllocSummaryInfo; + AllocSummaryInfoData->Signature = MEMORY_PROFILE_ALLOC_SUMMARY_INFO_SIGNATURE; + AllocSummaryInfo = &AllocSummaryInfoData->AllocSummaryInfo; AllocSummaryInfo->Header.Signature = MEMORY_PROFILE_ALLOC_SUMMARY_INFO_SIGNATURE; AllocSummaryInfo->Header.Length = sizeof (*AllocSummaryInfo); AllocSummaryInfo->Header.Revision = MEMORY_PROFILE_ALLOC_SUMMARY_INFO_REVISION; - AllocSummaryInfo->CallerAddress = AllocInfo->CallerAddress; - AllocSummaryInfo->Action = AllocInfo->Action; + AllocSummaryInfo->CallerAddress = AllocInfo->CallerAddress; + AllocSummaryInfo->Action = AllocInfo->Action; if (AllocInfo->ActionStringOffset != 0) { - AllocSummaryInfo->ActionString = (CHAR8 *) ((UINTN) AllocInfo + AllocInfo->ActionStringOffset); + AllocSummaryInfo->ActionString = (CHAR8 *)((UINTN)AllocInfo + AllocInfo->ActionStringOffset); } else { - AllocSummaryInfo->ActionString = NULL; + AllocSummaryInfo->ActionString = NULL; } + AllocSummaryInfo->AllocateCount = 0; AllocSummaryInfo->TotalSize = 0; InsertTailList (DriverSummaryInfoData->AllocSummaryInfoList, &AllocSummaryInfoData->Link); } + AllocSummaryInfo = &AllocSummaryInfoData->AllocSummaryInfo; - AllocSummaryInfo->AllocateCount ++; + AllocSummaryInfo->AllocateCount++; AllocSummaryInfo->TotalSize += AllocInfo->Size; - return (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) AllocInfo + AllocInfo->Header.Length); + return (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)AllocInfo + AllocInfo->Header.Length); } /** @@ -799,13 +823,13 @@ CreateAllocSummaryInfo ( **/ MEMORY_PROFILE_DRIVER_INFO * CreateDriverSummaryInfo ( - IN OUT MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData, - IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo + IN OUT MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData, + IN MEMORY_PROFILE_DRIVER_INFO *DriverInfo ) { - MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - UINTN AllocIndex; + MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + UINTN AllocIndex; if (DriverInfo->Header.Signature != MEMORY_PROFILE_DRIVER_INFO_SIGNATURE) { return NULL; @@ -815,20 +839,22 @@ CreateDriverSummaryInfo ( if (DriverSummaryInfoData == NULL) { return NULL; } - DriverSummaryInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; - DriverSummaryInfoData->DriverInfo = DriverInfo; - DriverSummaryInfoData->AllocSummaryInfoList = (LIST_ENTRY *) (DriverSummaryInfoData + 1); + + DriverSummaryInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; + DriverSummaryInfoData->DriverInfo = DriverInfo; + DriverSummaryInfoData->AllocSummaryInfoList = (LIST_ENTRY *)(DriverSummaryInfoData + 1); InitializeListHead (DriverSummaryInfoData->AllocSummaryInfoList); InsertTailList (ContextSummaryData->DriverSummaryInfoList, &DriverSummaryInfoData->Link); - AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) DriverInfo + DriverInfo->Header.Length); + AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)DriverInfo + DriverInfo->Header.Length); for (AllocIndex = 0; AllocIndex < DriverInfo->AllocRecordCount; AllocIndex++) { AllocInfo = CreateAllocSummaryInfo (DriverSummaryInfoData, AllocInfo); if (AllocInfo == NULL) { return NULL; } } - return (MEMORY_PROFILE_DRIVER_INFO *) AllocInfo; + + return (MEMORY_PROFILE_DRIVER_INFO *)AllocInfo; } /** @@ -842,24 +868,24 @@ CreateDriverSummaryInfo ( **/ MEMORY_PROFILE_CONTEXT_SUMMARY_DATA * CreateContextSummaryData ( - IN PHYSICAL_ADDRESS ProfileBuffer, - IN UINT64 ProfileSize + IN PHYSICAL_ADDRESS ProfileBuffer, + IN UINT64 ProfileSize ) { - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - UINTN DriverIndex; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + UINTN DriverIndex; - Context = (MEMORY_PROFILE_CONTEXT *) ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_CONTEXT_SIGNATURE); + Context = (MEMORY_PROFILE_CONTEXT *)ScanMemoryProfileBySignature (ProfileBuffer, ProfileSize, MEMORY_PROFILE_CONTEXT_SIGNATURE); if (Context == NULL) { return NULL; } - mMemoryProfileContextSummary.Signature = MEMORY_PROFILE_CONTEXT_SIGNATURE; - mMemoryProfileContextSummary.Context = Context; + mMemoryProfileContextSummary.Signature = MEMORY_PROFILE_CONTEXT_SIGNATURE; + mMemoryProfileContextSummary.Context = Context; mMemoryProfileContextSummary.DriverSummaryInfoList = &mImageSummaryQueue; - DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *) ((UINTN) Context + Context->Header.Length); + DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *)((UINTN)Context + Context->Header.Length); for (DriverIndex = 0; DriverIndex < Context->ImageCount; DriverIndex++) { DriverInfo = CreateDriverSummaryInfo (&mMemoryProfileContextSummary, DriverInfo); if (DriverInfo == NULL) { @@ -880,22 +906,22 @@ CreateContextSummaryData ( **/ VOID DumpContextSummaryData ( - IN MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData, - IN BOOLEAN IsForSmm + IN MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData, + IN BOOLEAN IsForSmm ) { - MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; - LIST_ENTRY *DriverSummaryInfoList; - LIST_ENTRY *DriverSummaryLink; - LIST_ENTRY *AllocSummaryInfoList; - LIST_ENTRY *AllocSummaryLink; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; - CHAR8 *NameString; + MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; + LIST_ENTRY *DriverSummaryInfoList; + LIST_ENTRY *DriverSummaryLink; + LIST_ENTRY *AllocSummaryInfoList; + LIST_ENTRY *AllocSummaryLink; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO *AllocSummaryInfo; + CHAR8 *NameString; if (ContextSummaryData == NULL) { - return ; + return; } Print (L"\nSummary Data:\n"); @@ -903,7 +929,8 @@ DumpContextSummaryData ( DriverSummaryInfoList = ContextSummaryData->DriverSummaryInfoList; for (DriverSummaryLink = DriverSummaryInfoList->ForwardLink; DriverSummaryLink != DriverSummaryInfoList; - DriverSummaryLink = DriverSummaryLink->ForwardLink) { + DriverSummaryLink = DriverSummaryLink->ForwardLink) + { DriverSummaryInfoData = CR ( DriverSummaryLink, MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA, @@ -920,17 +947,19 @@ DumpContextSummaryData ( } if (DriverInfo->PdbStringOffset != 0) { - Print (L" (Pdb - %a)\n", (CHAR8 *) ((UINTN) DriverInfo + DriverInfo->PdbStringOffset)); + Print (L" (Pdb - %a)\n", (CHAR8 *)((UINTN)DriverInfo + DriverInfo->PdbStringOffset)); } else { Print (L"\n"); } + Print (L"Caller List:\n"); - Print(L" Count Size RVA Action\n"); - Print(L"========== ================== ================== (================================)\n"); + Print (L" Count Size RVA Action\n"); + Print (L"========== ================== ================== (================================)\n"); AllocSummaryInfoList = DriverSummaryInfoData->AllocSummaryInfoList; for (AllocSummaryLink = AllocSummaryInfoList->ForwardLink; AllocSummaryLink != AllocSummaryInfoList; - AllocSummaryLink = AllocSummaryLink->ForwardLink) { + AllocSummaryLink = AllocSummaryLink->ForwardLink) + { AllocSummaryInfoData = CR ( AllocSummaryLink, MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA, @@ -939,7 +968,8 @@ DumpContextSummaryData ( ); AllocSummaryInfo = &AllocSummaryInfoData->AllocSummaryInfo; - Print(L"0x%08x 0x%016lx <== 0x%016lx", + Print ( + L"0x%08x 0x%016lx <== 0x%016lx", AllocSummaryInfo->AllocateCount, AllocSummaryInfo->TotalSize, AllocSummaryInfo->CallerAddress - DriverInfo->ImageBase @@ -947,7 +977,8 @@ DumpContextSummaryData ( Print (L" (%a)\n", ProfileActionToStr (AllocSummaryInfo->Action, AllocSummaryInfo->ActionString, IsForSmm)); } } - return ; + + return; } /** @@ -958,24 +989,25 @@ DumpContextSummaryData ( **/ VOID DestroyContextSummaryData ( - IN OUT MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData + IN OUT MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *ContextSummaryData ) { - MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; - MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; - LIST_ENTRY *DriverSummaryInfoList; - LIST_ENTRY *DriverSummaryLink; - LIST_ENTRY *AllocSummaryInfoList; - LIST_ENTRY *AllocSummaryLink; + MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA *DriverSummaryInfoData; + MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA *AllocSummaryInfoData; + LIST_ENTRY *DriverSummaryInfoList; + LIST_ENTRY *DriverSummaryLink; + LIST_ENTRY *AllocSummaryInfoList; + LIST_ENTRY *AllocSummaryLink; if (ContextSummaryData == NULL) { - return ; + return; } DriverSummaryInfoList = ContextSummaryData->DriverSummaryInfoList; for (DriverSummaryLink = DriverSummaryInfoList->ForwardLink; DriverSummaryLink != DriverSummaryInfoList; - ) { + ) + { DriverSummaryInfoData = CR ( DriverSummaryLink, MEMORY_PROFILE_DRIVER_SUMMARY_INFO_DATA, @@ -987,7 +1019,8 @@ DestroyContextSummaryData ( AllocSummaryInfoList = DriverSummaryInfoData->AllocSummaryInfoList; for (AllocSummaryLink = AllocSummaryInfoList->ForwardLink; AllocSummaryLink != AllocSummaryInfoList; - ) { + ) + { AllocSummaryInfoData = CR ( AllocSummaryLink, MEMORY_PROFILE_ALLOC_SUMMARY_INFO_DATA, @@ -1003,7 +1036,8 @@ DestroyContextSummaryData ( RemoveEntryList (&DriverSummaryInfoData->Link); FreePool (DriverSummaryInfoData); } - return ; + + return; } /** @@ -1018,14 +1052,14 @@ GetUefiMemoryProfileData ( VOID ) { - EFI_STATUS Status; - EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; - VOID *Data; - UINT64 Size; - MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *MemoryProfileContextSummaryData; - BOOLEAN RecordingState; - - Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID **) &ProfileProtocol); + EFI_STATUS Status; + EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; + VOID *Data; + UINT64 Size; + MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *MemoryProfileContextSummaryData; + BOOLEAN RecordingState; + + Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID **)&ProfileProtocol); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UefiMemoryProfile: Locate MemoryProfile protocol - %r\n", Status)); return Status; @@ -1035,13 +1069,13 @@ GetUefiMemoryProfileData ( // Set recording state if needed. // RecordingState = MEMORY_PROFILE_RECORDING_DISABLE; - Status = ProfileProtocol->GetRecordingState (ProfileProtocol, &RecordingState); + Status = ProfileProtocol->GetRecordingState (ProfileProtocol, &RecordingState); if (RecordingState == MEMORY_PROFILE_RECORDING_ENABLE) { ProfileProtocol->SetRecordingState (ProfileProtocol, MEMORY_PROFILE_RECORDING_DISABLE); } - Size = 0; - Data = NULL; + Size = 0; + Data = NULL; Status = ProfileProtocol->GetData ( ProfileProtocol, &Size, @@ -1052,7 +1086,7 @@ GetUefiMemoryProfileData ( goto Done; } - Data = AllocateZeroPool ((UINTN) Size); + Data = AllocateZeroPool ((UINTN)Size); if (Data == NULL) { Status = EFI_OUT_OF_RESOURCES; Print (L"UefiMemoryProfile: AllocateZeroPool (0x%x) - %r\n", Size, Status); @@ -1069,15 +1103,14 @@ GetUefiMemoryProfileData ( goto Done; } - Print (L"UefiMemoryProfileSize - 0x%x\n", Size); Print (L"======= UefiMemoryProfile begin =======\n"); - DumpMemoryProfile ((PHYSICAL_ADDRESS) (UINTN) Data, Size, FALSE); + DumpMemoryProfile ((PHYSICAL_ADDRESS)(UINTN)Data, Size, FALSE); // // Dump summary information // - MemoryProfileContextSummaryData = CreateContextSummaryData ((PHYSICAL_ADDRESS) (UINTN) Data, Size); + MemoryProfileContextSummaryData = CreateContextSummaryData ((PHYSICAL_ADDRESS)(UINTN)Data, Size); if (MemoryProfileContextSummaryData != NULL) { DumpContextSummaryData (MemoryProfileContextSummaryData, FALSE); DestroyContextSummaryData (MemoryProfileContextSummaryData); @@ -1112,29 +1145,29 @@ GetSmramProfileData ( VOID ) { - EFI_STATUS Status; - UINTN CommSize; - UINT8 *CommBuffer; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *CommGetProfileInfo; - SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *CommGetProfileData; - SMRAM_PROFILE_PARAMETER_RECORDING_STATE *CommRecordingState; - UINTN ProfileSize; - VOID *ProfileBuffer; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - UINTN MinimalSizeNeeded; - EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; - UINT32 Index; - EFI_MEMORY_DESCRIPTOR *Entry; - VOID *Buffer; - UINTN Size; - UINTN Offset; - MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *MemoryProfileContextSummaryData; - BOOLEAN RecordingState; + EFI_STATUS Status; + UINTN CommSize; + UINT8 *CommBuffer; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *CommGetProfileInfo; + SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *CommGetProfileData; + SMRAM_PROFILE_PARAMETER_RECORDING_STATE *CommRecordingState; + UINTN ProfileSize; + VOID *ProfileBuffer; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + UINTN MinimalSizeNeeded; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; + UINT32 Index; + EFI_MEMORY_DESCRIPTOR *Entry; + VOID *Buffer; + UINTN Size; + UINTN Offset; + MEMORY_PROFILE_CONTEXT_SUMMARY_DATA *MemoryProfileContextSummaryData; + BOOLEAN RecordingState; ProfileBuffer = NULL; - Status = gBS->LocateProtocol (&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **) &SmmCommunication); + Status = gBS->LocateProtocol (&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **)&SmmCommunication); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SmramProfile: Locate SmmCommunication protocol - %r\n", Status)); return Status; @@ -1142,56 +1175,73 @@ GetSmramProfileData ( MinimalSizeNeeded = sizeof (EFI_GUID) + sizeof (UINTN) + - MAX (sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO), - MAX (sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET), - sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE))); - MinimalSizeNeeded += MAX (sizeof (MEMORY_PROFILE_CONTEXT), - MAX (sizeof (MEMORY_PROFILE_DRIVER_INFO), - MAX (sizeof (MEMORY_PROFILE_ALLOC_INFO), - MAX (sizeof (MEMORY_PROFILE_DESCRIPTOR), - MAX (sizeof (MEMORY_PROFILE_FREE_MEMORY), - sizeof (MEMORY_PROFILE_MEMORY_RANGE)))))); + MAX ( + sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO), + MAX ( + sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET), + sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE) + ) + ); + MinimalSizeNeeded += MAX ( + sizeof (MEMORY_PROFILE_CONTEXT), + MAX ( + sizeof (MEMORY_PROFILE_DRIVER_INFO), + MAX ( + sizeof (MEMORY_PROFILE_ALLOC_INFO), + MAX ( + sizeof (MEMORY_PROFILE_DESCRIPTOR), + MAX ( + sizeof (MEMORY_PROFILE_FREE_MEMORY), + sizeof (MEMORY_PROFILE_MEMORY_RANGE) + ) + ) + ) + ) + ); Status = EfiGetSystemConfigurationTable ( &gEdkiiPiSmmCommunicationRegionTableGuid, - (VOID **) &PiSmmCommunicationRegionTable + (VOID **)&PiSmmCommunicationRegionTable ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SmramProfile: Get PiSmmCommunicationRegionTable - %r\n", Status)); return Status; } + ASSERT (PiSmmCommunicationRegionTable != NULL); - Entry = (EFI_MEMORY_DESCRIPTOR *) (PiSmmCommunicationRegionTable + 1); - Size = 0; + Entry = (EFI_MEMORY_DESCRIPTOR *)(PiSmmCommunicationRegionTable + 1); + Size = 0; for (Index = 0; Index < PiSmmCommunicationRegionTable->NumberOfEntries; Index++) { if (Entry->Type == EfiConventionalMemory) { - Size = EFI_PAGES_TO_SIZE ((UINTN) Entry->NumberOfPages); + Size = EFI_PAGES_TO_SIZE ((UINTN)Entry->NumberOfPages); if (Size >= MinimalSizeNeeded) { break; } } - Entry = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) Entry + PiSmmCommunicationRegionTable->DescriptorSize); + + Entry = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Entry + PiSmmCommunicationRegionTable->DescriptorSize); } + ASSERT (Index < PiSmmCommunicationRegionTable->NumberOfEntries); - CommBuffer = (UINT8 *) (UINTN) Entry->PhysicalStart; + CommBuffer = (UINT8 *)(UINTN)Entry->PhysicalStart; // // Set recording state if needed. // RecordingState = MEMORY_PROFILE_RECORDING_DISABLE; - CommHeader = (EFI_SMM_COMMUNICATE_HEADER *) &CommBuffer[0]; + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof (gEdkiiMemoryProfileGuid)); CommHeader->MessageLength = sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE); - CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *) &CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; CommRecordingState->Header.Command = SMRAM_PROFILE_COMMAND_GET_RECORDING_STATE; CommRecordingState->Header.DataLength = sizeof (*CommRecordingState); CommRecordingState->Header.ReturnStatus = (UINT64)-1; CommRecordingState->RecordingState = MEMORY_PROFILE_RECORDING_DISABLE; CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + CommHeader->MessageLength; - Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); + Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SmramProfile: SmmCommunication - %r\n", Status)); return Status; @@ -1201,13 +1251,14 @@ GetSmramProfileData ( Print (L"SmramProfile: GetRecordingState - 0x%0x\n", CommRecordingState->Header.ReturnStatus); return EFI_SUCCESS; } + RecordingState = CommRecordingState->RecordingState; if (RecordingState == MEMORY_PROFILE_RECORDING_ENABLE) { - CommHeader = (EFI_SMM_COMMUNICATE_HEADER *) &CommBuffer[0]; + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof (gEdkiiMemoryProfileGuid)); CommHeader->MessageLength = sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE); - CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *) &CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; CommRecordingState->Header.Command = SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE; CommRecordingState->Header.DataLength = sizeof (*CommRecordingState); CommRecordingState->Header.ReturnStatus = (UINT64)-1; @@ -1220,18 +1271,18 @@ GetSmramProfileData ( // // Get Size // - CommHeader = (EFI_SMM_COMMUNICATE_HEADER *) &CommBuffer[0]; + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof (gEdkiiMemoryProfileGuid)); CommHeader->MessageLength = sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO); - CommGetProfileInfo = (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *) &CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommGetProfileInfo = (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; CommGetProfileInfo->Header.Command = SMRAM_PROFILE_COMMAND_GET_PROFILE_INFO; CommGetProfileInfo->Header.DataLength = sizeof (*CommGetProfileInfo); CommGetProfileInfo->Header.ReturnStatus = (UINT64)-1; CommGetProfileInfo->ProfileSize = 0; CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + CommHeader->MessageLength; - Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); + Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); ASSERT_EFI_ERROR (Status); if (CommGetProfileInfo->Header.ReturnStatus != 0) { @@ -1240,7 +1291,7 @@ GetSmramProfileData ( goto Done; } - ProfileSize = (UINTN) CommGetProfileInfo->ProfileSize; + ProfileSize = (UINTN)CommGetProfileInfo->ProfileSize; // // Get Data @@ -1252,28 +1303,29 @@ GetSmramProfileData ( goto Done; } - CommHeader = (EFI_SMM_COMMUNICATE_HEADER *) &CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof(gEdkiiMemoryProfileGuid)); + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; + CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof (gEdkiiMemoryProfileGuid)); CommHeader->MessageLength = sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET); - CommGetProfileData = (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *) &CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommGetProfileData = (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; CommGetProfileData->Header.Command = SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA_BY_OFFSET; CommGetProfileData->Header.DataLength = sizeof (*CommGetProfileData); CommGetProfileData->Header.ReturnStatus = (UINT64)-1; CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + CommHeader->MessageLength; - Buffer = (UINT8 *) CommHeader + CommSize; - Size -= CommSize; + Buffer = (UINT8 *)CommHeader + CommSize; + Size -= CommSize; - CommGetProfileData->ProfileBuffer = (PHYSICAL_ADDRESS) (UINTN) Buffer; - CommGetProfileData->ProfileOffset = 0; + CommGetProfileData->ProfileBuffer = (PHYSICAL_ADDRESS)(UINTN)Buffer; + CommGetProfileData->ProfileOffset = 0; while (CommGetProfileData->ProfileOffset < ProfileSize) { - Offset = (UINTN) CommGetProfileData->ProfileOffset; + Offset = (UINTN)CommGetProfileData->ProfileOffset; if (Size <= (ProfileSize - CommGetProfileData->ProfileOffset)) { - CommGetProfileData->ProfileSize = (UINT64) Size; + CommGetProfileData->ProfileSize = (UINT64)Size; } else { - CommGetProfileData->ProfileSize = (UINT64) (ProfileSize - CommGetProfileData->ProfileOffset); + CommGetProfileData->ProfileSize = (UINT64)(ProfileSize - CommGetProfileData->ProfileOffset); } + Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); ASSERT_EFI_ERROR (Status); @@ -1282,18 +1334,18 @@ GetSmramProfileData ( Print (L"GetProfileData - 0x%x\n", CommGetProfileData->Header.ReturnStatus); goto Done; } - CopyMem ((UINT8 *) ProfileBuffer + Offset, (VOID *) (UINTN) CommGetProfileData->ProfileBuffer, (UINTN) CommGetProfileData->ProfileSize); - } + CopyMem ((UINT8 *)ProfileBuffer + Offset, (VOID *)(UINTN)CommGetProfileData->ProfileBuffer, (UINTN)CommGetProfileData->ProfileSize); + } Print (L"SmramProfileSize - 0x%x\n", ProfileSize); Print (L"======= SmramProfile begin =======\n"); - DumpMemoryProfile ((PHYSICAL_ADDRESS) (UINTN) ProfileBuffer, ProfileSize, TRUE); + DumpMemoryProfile ((PHYSICAL_ADDRESS)(UINTN)ProfileBuffer, ProfileSize, TRUE); // // Dump summary information // - MemoryProfileContextSummaryData = CreateContextSummaryData ((PHYSICAL_ADDRESS) (UINTN) ProfileBuffer, ProfileSize); + MemoryProfileContextSummaryData = CreateContextSummaryData ((PHYSICAL_ADDRESS)(UINTN)ProfileBuffer, ProfileSize); if (MemoryProfileContextSummaryData != NULL) { DumpContextSummaryData (MemoryProfileContextSummaryData, TRUE); DestroyContextSummaryData (MemoryProfileContextSummaryData); @@ -1310,11 +1362,11 @@ Done: // Restore recording state if needed. // if (RecordingState == MEMORY_PROFILE_RECORDING_ENABLE) { - CommHeader = (EFI_SMM_COMMUNICATE_HEADER *) &CommBuffer[0]; + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; CopyMem (&CommHeader->HeaderGuid, &gEdkiiMemoryProfileGuid, sizeof (gEdkiiMemoryProfileGuid)); CommHeader->MessageLength = sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE); - CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *) &CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; CommRecordingState->Header.Command = SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE; CommRecordingState->Header.DataLength = sizeof (*CommRecordingState); CommRecordingState->Header.ReturnStatus = (UINT64)-1; @@ -1341,11 +1393,11 @@ Done: EFI_STATUS EFIAPI UefiMain ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = GetUefiMemoryProfileData (); if (EFI_ERROR (Status)) { diff --git a/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.c b/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.c index 4153074b7a..69baf1c51d 100644 --- a/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.c +++ b/MdeModulePkg/Application/SmiHandlerProfileInfo/SmiHandlerProfileInfo.c @@ -23,7 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #define PROFILE_NAME_STRING_LENGTH 64 -CHAR8 mNameString[PROFILE_NAME_STRING_LENGTH + 1]; +CHAR8 mNameString[PROFILE_NAME_STRING_LENGTH + 1]; VOID *mSmiHandlerProfileDatabase; UINTN mSmiHandlerProfileDatabaseSize; @@ -41,6 +41,7 @@ InternalDumpData ( ) { UINTN Index; + for (Index = 0; Index < Size; Index++) { Print (L"%02x", (UINTN)Data[Index]); if ((Index + 1) != Size) { @@ -53,79 +54,82 @@ InternalDumpData ( Get SMI handler profile database. **/ VOID -GetSmiHandlerProfileDatabase( +GetSmiHandlerProfileDatabase ( VOID ) { - EFI_STATUS Status; - UINTN CommSize; - UINT8 *CommBuffer; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *CommGetInfo; - SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *CommGetData; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - UINTN MinimalSizeNeeded; - EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; - UINT32 Index; - EFI_MEMORY_DESCRIPTOR *Entry; - VOID *Buffer; - UINTN Size; - UINTN Offset; - - Status = gBS->LocateProtocol(&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **)&SmmCommunication); - if (EFI_ERROR(Status)) { - Print(L"SmiHandlerProfile: Locate SmmCommunication protocol - %r\n", Status); - return ; + EFI_STATUS Status; + UINTN CommSize; + UINT8 *CommBuffer; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *CommGetInfo; + SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *CommGetData; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + UINTN MinimalSizeNeeded; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; + UINT32 Index; + EFI_MEMORY_DESCRIPTOR *Entry; + VOID *Buffer; + UINTN Size; + UINTN Offset; + + Status = gBS->LocateProtocol (&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **)&SmmCommunication); + if (EFI_ERROR (Status)) { + Print (L"SmiHandlerProfile: Locate SmmCommunication protocol - %r\n", Status); + return; } MinimalSizeNeeded = EFI_PAGE_SIZE; - Status = EfiGetSystemConfigurationTable( + Status = EfiGetSystemConfigurationTable ( &gEdkiiPiSmmCommunicationRegionTableGuid, (VOID **)&PiSmmCommunicationRegionTable ); - if (EFI_ERROR(Status)) { - Print(L"SmiHandlerProfile: Get PiSmmCommunicationRegionTable - %r\n", Status); - return ; + if (EFI_ERROR (Status)) { + Print (L"SmiHandlerProfile: Get PiSmmCommunicationRegionTable - %r\n", Status); + return; } - ASSERT(PiSmmCommunicationRegionTable != NULL); + + ASSERT (PiSmmCommunicationRegionTable != NULL); Entry = (EFI_MEMORY_DESCRIPTOR *)(PiSmmCommunicationRegionTable + 1); - Size = 0; + Size = 0; for (Index = 0; Index < PiSmmCommunicationRegionTable->NumberOfEntries; Index++) { if (Entry->Type == EfiConventionalMemory) { - Size = EFI_PAGES_TO_SIZE((UINTN)Entry->NumberOfPages); + Size = EFI_PAGES_TO_SIZE ((UINTN)Entry->NumberOfPages); if (Size >= MinimalSizeNeeded) { break; } } + Entry = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Entry + PiSmmCommunicationRegionTable->DescriptorSize); } - ASSERT(Index < PiSmmCommunicationRegionTable->NumberOfEntries); + + ASSERT (Index < PiSmmCommunicationRegionTable->NumberOfEntries); CommBuffer = (UINT8 *)(UINTN)Entry->PhysicalStart; // // Get Size // CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem(&CommHeader->HeaderGuid, &gSmiHandlerProfileGuid, sizeof(gSmiHandlerProfileGuid)); - CommHeader->MessageLength = sizeof(SMI_HANDLER_PROFILE_PARAMETER_GET_INFO); + CopyMem (&CommHeader->HeaderGuid, &gSmiHandlerProfileGuid, sizeof (gSmiHandlerProfileGuid)); + CommHeader->MessageLength = sizeof (SMI_HANDLER_PROFILE_PARAMETER_GET_INFO); - CommGetInfo = (SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *)&CommBuffer[OFFSET_OF(EFI_SMM_COMMUNICATE_HEADER, Data)]; - CommGetInfo->Header.Command = SMI_HANDLER_PROFILE_COMMAND_GET_INFO; - CommGetInfo->Header.DataLength = sizeof(*CommGetInfo); + CommGetInfo = (SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommGetInfo->Header.Command = SMI_HANDLER_PROFILE_COMMAND_GET_INFO; + CommGetInfo->Header.DataLength = sizeof (*CommGetInfo); CommGetInfo->Header.ReturnStatus = (UINT64)-1; - CommGetInfo->DataSize = 0; + CommGetInfo->DataSize = 0; - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + CommHeader->MessageLength; - Status = SmmCommunication->Communicate(SmmCommunication, CommBuffer, &CommSize); - if (EFI_ERROR(Status)) { - Print(L"SmiHandlerProfile: SmmCommunication - %r\n", Status); - return ; + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + CommHeader->MessageLength; + Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); + if (EFI_ERROR (Status)) { + Print (L"SmiHandlerProfile: SmmCommunication - %r\n", Status); + return; } if (CommGetInfo->Header.ReturnStatus != 0) { - Print(L"SmiHandlerProfile: GetInfo - 0x%0x\n", CommGetInfo->Header.ReturnStatus); - return ; + Print (L"SmiHandlerProfile: GetInfo - 0x%0x\n", CommGetInfo->Header.ReturnStatus); + return; } mSmiHandlerProfileDatabaseSize = (UINTN)CommGetInfo->DataSize; @@ -133,25 +137,25 @@ GetSmiHandlerProfileDatabase( // // Get Data // - mSmiHandlerProfileDatabase = AllocateZeroPool(mSmiHandlerProfileDatabaseSize); + mSmiHandlerProfileDatabase = AllocateZeroPool (mSmiHandlerProfileDatabaseSize); if (mSmiHandlerProfileDatabase == NULL) { Status = EFI_OUT_OF_RESOURCES; - Print(L"SmiHandlerProfile: AllocateZeroPool (0x%x) for dump buffer - %r\n", mSmiHandlerProfileDatabaseSize, Status); - return ; + Print (L"SmiHandlerProfile: AllocateZeroPool (0x%x) for dump buffer - %r\n", mSmiHandlerProfileDatabaseSize, Status); + return; } CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem(&CommHeader->HeaderGuid, &gSmiHandlerProfileGuid, sizeof(gSmiHandlerProfileGuid)); - CommHeader->MessageLength = sizeof(SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET); + CopyMem (&CommHeader->HeaderGuid, &gSmiHandlerProfileGuid, sizeof (gSmiHandlerProfileGuid)); + CommHeader->MessageLength = sizeof (SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET); - CommGetData = (SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *)&CommBuffer[OFFSET_OF(EFI_SMM_COMMUNICATE_HEADER, Data)]; - CommGetData->Header.Command = SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET; - CommGetData->Header.DataLength = sizeof(*CommGetData); + CommGetData = (SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + CommGetData->Header.Command = SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET; + CommGetData->Header.DataLength = sizeof (*CommGetData); CommGetData->Header.ReturnStatus = (UINT64)-1; - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + CommHeader->MessageLength; - Buffer = (UINT8 *)CommHeader + CommSize; - Size -= CommSize; + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + CommHeader->MessageLength; + Buffer = (UINT8 *)CommHeader + CommSize; + Size -= CommSize; CommGetData->DataBuffer = (PHYSICAL_ADDRESS)(UINTN)Buffer; CommGetData->DataOffset = 0; @@ -162,21 +166,23 @@ GetSmiHandlerProfileDatabase( } else { CommGetData->DataSize = (UINT64)(mSmiHandlerProfileDatabaseSize - CommGetData->DataOffset); } - Status = SmmCommunication->Communicate(SmmCommunication, CommBuffer, &CommSize); - ASSERT_EFI_ERROR(Status); + + Status = SmmCommunication->Communicate (SmmCommunication, CommBuffer, &CommSize); + ASSERT_EFI_ERROR (Status); if (CommGetData->Header.ReturnStatus != 0) { - FreePool(mSmiHandlerProfileDatabase); + FreePool (mSmiHandlerProfileDatabase); mSmiHandlerProfileDatabase = NULL; - Print(L"SmiHandlerProfile: GetData - 0x%x\n", CommGetData->Header.ReturnStatus); - return ; + Print (L"SmiHandlerProfile: GetData - 0x%x\n", CommGetData->Header.ReturnStatus); + return; } - CopyMem((UINT8 *)mSmiHandlerProfileDatabase + Offset, (VOID *)(UINTN)CommGetData->DataBuffer, (UINTN)CommGetData->DataSize); + + CopyMem ((UINT8 *)mSmiHandlerProfileDatabase + Offset, (VOID *)(UINTN)CommGetData->DataBuffer, (UINTN)CommGetData->DataSize); } DEBUG ((DEBUG_INFO, "SmiHandlerProfileSize - 0x%x\n", mSmiHandlerProfileDatabaseSize)); - return ; + return; } /** @@ -193,14 +199,14 @@ GetSmiHandlerProfileDatabase( **/ VOID GetShortPdbFileName ( - IN CHAR8 *PdbFileName, - OUT CHAR8 *AsciiBuffer + IN CHAR8 *PdbFileName, + OUT CHAR8 *AsciiBuffer ) { - UINTN IndexPdb; // Current work location within a Pdb string. - UINTN IndexBuffer; // Current work location within a Buffer string. - UINTN StartIndex; - UINTN EndIndex; + UINTN IndexPdb; // Current work location within a Pdb string. + UINTN IndexBuffer; // Current work location within a Buffer string. + UINTN StartIndex; + UINTN EndIndex; ZeroMem (AsciiBuffer, PROFILE_NAME_STRING_LENGTH + 1); @@ -208,7 +214,9 @@ GetShortPdbFileName ( AsciiStrnCpyS (AsciiBuffer, PROFILE_NAME_STRING_LENGTH + 1, " ", 1); } else { StartIndex = 0; - for (EndIndex = 0; PdbFileName[EndIndex] != 0; EndIndex++); + for (EndIndex = 0; PdbFileName[EndIndex] != 0; EndIndex++) { + } + for (IndexPdb = 0; PdbFileName[IndexPdb] != 0; IndexPdb++) { if ((PdbFileName[IndexPdb] == '\\') || (PdbFileName[IndexPdb] == '/')) { StartIndex = IndexPdb + 1; @@ -248,9 +256,9 @@ GetDriverNameString ( IN SMM_CORE_IMAGE_DATABASE_STRUCTURE *ImageStruct ) { - EFI_STATUS Status; - CHAR16 *NameString; - UINTN StringSize; + EFI_STATUS Status; + CHAR16 *NameString; + UINTN StringSize; if (ImageStruct == NULL) { return "???"; @@ -260,7 +268,7 @@ GetDriverNameString ( // Method 1: Get the name string from image PDB // if (ImageStruct->PdbStringOffset != 0) { - GetShortPdbFileName ((CHAR8 *) ((UINTN) ImageStruct + ImageStruct->PdbStringOffset), mNameString); + GetShortPdbFileName ((CHAR8 *)((UINTN)ImageStruct + ImageStruct->PdbStringOffset), mNameString); return mNameString; } @@ -270,13 +278,13 @@ GetDriverNameString ( // NameString = NULL; StringSize = 0; - Status = GetSectionFromAnyFv ( - &ImageStruct->FileGuid, - EFI_SECTION_USER_INTERFACE, - 0, - (VOID **) &NameString, - &StringSize - ); + Status = GetSectionFromAnyFv ( + &ImageStruct->FileGuid, + EFI_SECTION_USER_INTERFACE, + 0, + (VOID **)&NameString, + &StringSize + ); if (!EFI_ERROR (Status)) { // // Method 2: Get the name string from FFS UI section @@ -284,6 +292,7 @@ GetDriverNameString ( if (StrLen (NameString) > PROFILE_NAME_STRING_LENGTH) { NameString[PROFILE_NAME_STRING_LENGTH] = 0; } + UnicodeStrToAsciiStrS (NameString, mNameString, sizeof (mNameString)); FreePool (NameString); return mNameString; @@ -306,7 +315,7 @@ GetDriverNameString ( **/ SMM_CORE_IMAGE_DATABASE_STRUCTURE * GetImageFromRef ( - IN UINTN ImageRef + IN UINTN ImageRef ) { SMM_CORE_IMAGE_DATABASE_STRUCTURE *ImageStruct; @@ -318,6 +327,7 @@ GetImageFromRef ( return ImageStruct; } } + ImageStruct = (VOID *)((UINTN)ImageStruct + ImageStruct->Header.Length); } @@ -328,7 +338,7 @@ GetImageFromRef ( Dump SMM loaded image information. **/ VOID -DumpSmmLoadedImage( +DumpSmmLoadedImage ( VOID ) { @@ -340,19 +350,21 @@ DumpSmmLoadedImage( while ((UINTN)ImageStruct < (UINTN)mSmiHandlerProfileDatabase + mSmiHandlerProfileDatabaseSize) { if (ImageStruct->Header.Signature == SMM_CORE_IMAGE_DATABASE_SIGNATURE) { NameString = GetDriverNameString (ImageStruct); - Print(L" ImageBase, ImageStruct->ImageSize); + Print (L" ImageBase, ImageStruct->ImageSize); if (ImageStruct->EntryPoint != 0) { - Print(L" EntryPoint=\"0x%lx\"", ImageStruct->EntryPoint); + Print (L" EntryPoint=\"0x%lx\"", ImageStruct->EntryPoint); } - Print(L" FvFile=\"%g\"", &ImageStruct->FileGuid); - Print(L" RefId=\"0x%x\"", ImageStruct->ImageRef); - Print(L">\n"); + + Print (L" FvFile=\"%g\"", &ImageStruct->FileGuid); + Print (L" RefId=\"0x%x\"", ImageStruct->ImageRef); + Print (L">\n"); if (ImageStruct->PdbStringOffset != 0) { PdbString = (CHAR8 *)((UINTN)ImageStruct + ImageStruct->PdbStringOffset); - Print(L" %a\n", PdbString); + Print (L" %a\n", PdbString); } - Print(L" \n"); + + Print (L" \n"); } ImageStruct = (VOID *)((UINTN)ImageStruct + ImageStruct->Header.Length); @@ -361,7 +373,7 @@ DumpSmmLoadedImage( return; } -CHAR8 *mSxTypeString[] = { +CHAR8 *mSxTypeString[] = { "SxS0", "SxS1", "SxS2", @@ -382,15 +394,15 @@ SxTypeToString ( IN EFI_SLEEP_TYPE Type ) { - if (Type >= 0 && Type < ARRAY_SIZE(mSxTypeString)) { + if ((Type >= 0) && (Type < ARRAY_SIZE (mSxTypeString))) { return mSxTypeString[Type]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Type); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Type); return mNameString; } } -CHAR8 *mSxPhaseString[] = { +CHAR8 *mSxPhaseString[] = { "SxEntry", "SxExit", }; @@ -404,18 +416,18 @@ CHAR8 *mSxPhaseString[] = { **/ CHAR8 * SxPhaseToString ( - IN EFI_SLEEP_PHASE Phase + IN EFI_SLEEP_PHASE Phase ) { - if (Phase >= 0 && Phase < ARRAY_SIZE(mSxPhaseString)) { + if ((Phase >= 0) && (Phase < ARRAY_SIZE (mSxPhaseString))) { return mSxPhaseString[Phase]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Phase); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Phase); return mNameString; } } -CHAR8 *mPowerButtonPhaseString[] = { +CHAR8 *mPowerButtonPhaseString[] = { "PowerButtonEntry", "PowerButtonExit", }; @@ -432,15 +444,15 @@ PowerButtonPhaseToString ( IN EFI_POWER_BUTTON_PHASE Phase ) { - if (Phase >= 0 && Phase < ARRAY_SIZE(mPowerButtonPhaseString)) { + if ((Phase >= 0) && (Phase < ARRAY_SIZE (mPowerButtonPhaseString))) { return mPowerButtonPhaseString[Phase]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Phase); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Phase); return mNameString; } } -CHAR8 *mStandbyButtonPhaseString[] = { +CHAR8 *mStandbyButtonPhaseString[] = { "StandbyButtonEntry", "StandbyButtonExit", }; @@ -457,15 +469,15 @@ StandbyButtonPhaseToString ( IN EFI_STANDBY_BUTTON_PHASE Phase ) { - if (Phase >= 0 && Phase < ARRAY_SIZE(mStandbyButtonPhaseString)) { + if ((Phase >= 0) && (Phase < ARRAY_SIZE (mStandbyButtonPhaseString))) { return mStandbyButtonPhaseString[Phase]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Phase); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Phase); return mNameString; } } -CHAR8 *mIoTrapTypeString[] = { +CHAR8 *mIoTrapTypeString[] = { "WriteTrap", "ReadTrap", "ReadWriteTrap", @@ -483,15 +495,15 @@ IoTrapTypeToString ( IN EFI_SMM_IO_TRAP_DISPATCH_TYPE Type ) { - if (Type >= 0 && Type < ARRAY_SIZE(mIoTrapTypeString)) { + if ((Type >= 0) && (Type < ARRAY_SIZE (mIoTrapTypeString))) { return mIoTrapTypeString[Type]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Type); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Type); return mNameString; } } -CHAR8 *mUsbTypeString[] = { +CHAR8 *mUsbTypeString[] = { "UsbLegacy", "UsbWake", }; @@ -505,13 +517,13 @@ CHAR8 *mUsbTypeString[] = { **/ CHAR8 * UsbTypeToString ( - IN EFI_USB_SMI_TYPE Type + IN EFI_USB_SMI_TYPE Type ) { - if (Type >= 0 && Type < ARRAY_SIZE(mUsbTypeString)) { + if ((Type >= 0) && (Type < ARRAY_SIZE (mUsbTypeString))) { return mUsbTypeString[Type]; } else { - AsciiSPrint (mNameString, sizeof(mNameString), "0x%x", Type); + AsciiSPrint (mNameString, sizeof (mNameString), "0x%x", Type); return mNameString; } } @@ -525,42 +537,42 @@ UsbTypeToString ( **/ VOID DumpSmiChildContext ( - IN EFI_GUID *HandlerType, - IN VOID *Context, - IN UINTN ContextSize + IN EFI_GUID *HandlerType, + IN VOID *Context, + IN UINTN ContextSize ) { - CHAR16 *Str; + CHAR16 *Str; if (CompareGuid (HandlerType, &gEfiSmmSwDispatch2ProtocolGuid)) { - Print(L" SwSmi=\"0x%lx\"", ((SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT *)Context)->SwSmiInputValue); + Print (L" SwSmi=\"0x%lx\"", ((SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT *)Context)->SwSmiInputValue); } else if (CompareGuid (HandlerType, &gEfiSmmSxDispatch2ProtocolGuid)) { - Print(L" SxType=\"%a\"", SxTypeToString(((EFI_SMM_SX_REGISTER_CONTEXT *)Context)->Type)); - Print(L" SxPhase=\"%a\"", SxPhaseToString(((EFI_SMM_SX_REGISTER_CONTEXT *)Context)->Phase)); + Print (L" SxType=\"%a\"", SxTypeToString (((EFI_SMM_SX_REGISTER_CONTEXT *)Context)->Type)); + Print (L" SxPhase=\"%a\"", SxPhaseToString (((EFI_SMM_SX_REGISTER_CONTEXT *)Context)->Phase)); } else if (CompareGuid (HandlerType, &gEfiSmmPowerButtonDispatch2ProtocolGuid)) { - Print(L" PowerButtonPhase=\"%a\"", PowerButtonPhaseToString(((EFI_SMM_POWER_BUTTON_REGISTER_CONTEXT *)Context)->Phase)); + Print (L" PowerButtonPhase=\"%a\"", PowerButtonPhaseToString (((EFI_SMM_POWER_BUTTON_REGISTER_CONTEXT *)Context)->Phase)); } else if (CompareGuid (HandlerType, &gEfiSmmStandbyButtonDispatch2ProtocolGuid)) { - Print(L" StandbyButtonPhase=\"%a\"", StandbyButtonPhaseToString(((EFI_SMM_STANDBY_BUTTON_REGISTER_CONTEXT *)Context)->Phase)); + Print (L" StandbyButtonPhase=\"%a\"", StandbyButtonPhaseToString (((EFI_SMM_STANDBY_BUTTON_REGISTER_CONTEXT *)Context)->Phase)); } else if (CompareGuid (HandlerType, &gEfiSmmPeriodicTimerDispatch2ProtocolGuid)) { - Print(L" PeriodicTimerPeriod=\"%ld\"", ((EFI_SMM_PERIODIC_TIMER_REGISTER_CONTEXT *)Context)->Period); - Print(L" PeriodicTimerSmiTickInterval=\"%ld\"", ((EFI_SMM_PERIODIC_TIMER_REGISTER_CONTEXT *)Context)->SmiTickInterval); + Print (L" PeriodicTimerPeriod=\"%ld\"", ((EFI_SMM_PERIODIC_TIMER_REGISTER_CONTEXT *)Context)->Period); + Print (L" PeriodicTimerSmiTickInterval=\"%ld\"", ((EFI_SMM_PERIODIC_TIMER_REGISTER_CONTEXT *)Context)->SmiTickInterval); } else if (CompareGuid (HandlerType, &gEfiSmmGpiDispatch2ProtocolGuid)) { - Print(L" GpiNum=\"0x%lx\"", ((EFI_SMM_GPI_REGISTER_CONTEXT *)Context)->GpiNum); + Print (L" GpiNum=\"0x%lx\"", ((EFI_SMM_GPI_REGISTER_CONTEXT *)Context)->GpiNum); } else if (CompareGuid (HandlerType, &gEfiSmmIoTrapDispatch2ProtocolGuid)) { - Print(L" IoTrapAddress=\"0x%x\"", ((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Address); - Print(L" IoTrapLength=\"0x%x\"", ((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Length); - Print(L" IoTrapType=\"%a\"", IoTrapTypeToString(((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Type)); + Print (L" IoTrapAddress=\"0x%x\"", ((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Address); + Print (L" IoTrapLength=\"0x%x\"", ((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Length); + Print (L" IoTrapType=\"%a\"", IoTrapTypeToString (((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Type)); } else if (CompareGuid (HandlerType, &gEfiSmmUsbDispatch2ProtocolGuid)) { - Print(L" UsbType=\"0x%x\"", UsbTypeToString(((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context)->Type)); - Str = ConvertDevicePathToText((EFI_DEVICE_PATH_PROTOCOL *)(((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context) + 1), TRUE, TRUE); - Print(L" UsbDevicePath=\"%s\"", Str); + Print (L" UsbType=\"0x%x\"", UsbTypeToString (((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context)->Type)); + Str = ConvertDevicePathToText ((EFI_DEVICE_PATH_PROTOCOL *)(((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context) + 1), TRUE, TRUE); + Print (L" UsbDevicePath=\"%s\"", Str); if (Str != NULL) { FreePool (Str); } } else { - Print(L" Context=\""); + Print (L" Context=\""); InternalDumpData (Context, ContextSize); - Print(L"\""); + Print (L"\""); } } @@ -570,8 +582,8 @@ DumpSmiChildContext ( @param HandlerCategory SMI handler category **/ VOID -DumpSmiHandler( - IN UINT32 HandlerCategory +DumpSmiHandler ( + IN UINT32 HandlerCategory ) { SMM_CORE_SMI_DATABASE_STRUCTURE *SmiStruct; @@ -584,39 +596,46 @@ DumpSmiHandler( while ((UINTN)SmiStruct < (UINTN)mSmiHandlerProfileDatabase + mSmiHandlerProfileDatabaseSize) { if ((SmiStruct->Header.Signature == SMM_CORE_SMI_DATABASE_SIGNATURE) && (SmiStruct->HandlerCategory == HandlerCategory)) { SmiHandlerStruct = (VOID *)(SmiStruct + 1); - Print(L" HandlerType)) { - Print(L" HandlerType=\"%g\"", &SmiStruct->HandlerType); + Print (L" HandlerType=\"%g\"", &SmiStruct->HandlerType); } - Print(L">\n"); + + Print (L">\n"); for (Index = 0; Index < SmiStruct->HandlerCount; Index++) { - Print(L" ContextBufferSize != 0) { DumpSmiChildContext (&SmiStruct->HandlerType, (UINT8 *)SmiHandlerStruct + SmiHandlerStruct->ContextBufferOffset, SmiHandlerStruct->ContextBufferSize); } - Print(L">\n"); - ImageStruct = GetImageFromRef((UINTN)SmiHandlerStruct->ImageRef); - NameString = GetDriverNameString (ImageStruct); - Print(L" \n", SmiHandlerStruct->ImageRef, NameString); + + Print (L">\n"); + ImageStruct = GetImageFromRef ((UINTN)SmiHandlerStruct->ImageRef); + NameString = GetDriverNameString (ImageStruct); + Print (L" \n", SmiHandlerStruct->ImageRef, NameString); if ((ImageStruct != NULL) && (ImageStruct->PdbStringOffset != 0)) { - Print(L" %a\n", (UINT8 *)ImageStruct + ImageStruct->PdbStringOffset); + Print (L" %a\n", (UINT8 *)ImageStruct + ImageStruct->PdbStringOffset); } - Print(L" \n"); - Print(L" \n", SmiHandlerStruct->Handler); + + Print (L" \n"); + Print (L" \n", SmiHandlerStruct->Handler); if (ImageStruct != NULL) { - Print(L" 0x%x\n", (UINTN) (SmiHandlerStruct->Handler - ImageStruct->ImageBase)); + Print (L" 0x%x\n", (UINTN)(SmiHandlerStruct->Handler - ImageStruct->ImageBase)); } - Print(L" \n", SmiHandlerStruct->Handler); - Print(L" \n", SmiHandlerStruct->CallerAddr); + + Print (L" \n", SmiHandlerStruct->Handler); + Print (L" \n", SmiHandlerStruct->CallerAddr); if (ImageStruct != NULL) { - Print(L" 0x%x\n", (UINTN) (SmiHandlerStruct->CallerAddr - ImageStruct->ImageBase)); + Print (L" 0x%x\n", (UINTN)(SmiHandlerStruct->CallerAddr - ImageStruct->ImageBase)); } - Print(L" \n", SmiHandlerStruct->Handler); + + Print (L" \n", SmiHandlerStruct->Handler); SmiHandlerStruct = (VOID *)((UINTN)SmiHandlerStruct + SmiHandlerStruct->Length); - Print(L" \n"); + Print (L" \n"); } - Print(L" \n"); + + Print (L" \n"); } + SmiStruct = (VOID *)((UINTN)SmiStruct + SmiStruct->Header.Length); } @@ -635,11 +654,11 @@ DumpSmiHandler( EFI_STATUS EFIAPI SmiHandlerProfileInfoEntrypoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - GetSmiHandlerProfileDatabase(); + GetSmiHandlerProfileDatabase (); if (mSmiHandlerProfileDatabase == NULL) { return EFI_SUCCESS; @@ -648,38 +667,38 @@ SmiHandlerProfileInfoEntrypoint ( // // Dump all image // - Print(L"\n"); - Print(L"\n"); - Print(L"\n"); - Print(L" \n"); - DumpSmmLoadedImage(); - Print(L"\n\n"); + Print (L"\n"); + Print (L"\n"); + Print (L"\n"); + Print (L" \n"); + DumpSmmLoadedImage (); + Print (L"\n\n"); // // Dump SMI Handler // - Print(L"\n"); - Print(L" \n\n"); - Print(L" \n"); - Print(L" \n"); - DumpSmiHandler(SmmCoreSmiHandlerCategoryRootHandler); - Print(L" \n\n"); - - Print(L" \n"); - Print(L" \n"); - DumpSmiHandler(SmmCoreSmiHandlerCategoryGuidHandler); - Print(L" \n\n"); - - Print(L" \n"); - Print(L" \n"); - DumpSmiHandler(SmmCoreSmiHandlerCategoryHardwareHandler); - Print(L" \n\n"); - - Print(L"\n"); - Print(L"\n"); + Print (L"\n"); + Print (L" \n\n"); + Print (L" \n"); + Print (L" \n"); + DumpSmiHandler (SmmCoreSmiHandlerCategoryRootHandler); + Print (L" \n\n"); + + Print (L" \n"); + Print (L" \n"); + DumpSmiHandler (SmmCoreSmiHandlerCategoryGuidHandler); + Print (L" \n\n"); + + Print (L" \n"); + Print (L" \n"); + DumpSmiHandler (SmmCoreSmiHandlerCategoryHardwareHandler); + Print (L" \n\n"); + + Print (L"\n"); + Print (L"\n"); if (mSmiHandlerProfileDatabase != NULL) { - FreePool(mSmiHandlerProfileDatabase); + FreePool (mSmiHandlerProfileDatabase); } return EFI_SUCCESS; diff --git a/MdeModulePkg/Application/UiApp/FrontPage.c b/MdeModulePkg/Application/UiApp/FrontPage.c index 4b95cccb5c..cc9569e225 100644 --- a/MdeModulePkg/Application/UiApp/FrontPage.c +++ b/MdeModulePkg/Application/UiApp/FrontPage.c @@ -10,29 +10,29 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "FrontPage.h" #include "FrontPageCustomizedUi.h" -#define MAX_STRING_LEN 200 +#define MAX_STRING_LEN 200 -EFI_GUID mFrontPageGuid = FRONT_PAGE_FORMSET_GUID; +EFI_GUID mFrontPageGuid = FRONT_PAGE_FORMSET_GUID; -BOOLEAN mResetRequired = FALSE; +BOOLEAN mResetRequired = FALSE; -EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2; -CHAR8 *mLanguageString; -BOOLEAN mModeInitialized = FALSE; +EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2; +CHAR8 *mLanguageString; +BOOLEAN mModeInitialized = FALSE; // // Boot video resolution and text mode. // -UINT32 mBootHorizontalResolution = 0; -UINT32 mBootVerticalResolution = 0; -UINT32 mBootTextModeColumn = 0; -UINT32 mBootTextModeRow = 0; +UINT32 mBootHorizontalResolution = 0; +UINT32 mBootVerticalResolution = 0; +UINT32 mBootTextModeColumn = 0; +UINT32 mBootTextModeRow = 0; // // BIOS setup video resolution and text mode. // -UINT32 mSetupTextModeColumn = 0; -UINT32 mSetupTextModeRow = 0; -UINT32 mSetupHorizontalResolution = 0; -UINT32 mSetupVerticalResolution = 0; +UINT32 mSetupTextModeColumn = 0; +UINT32 mSetupTextModeRow = 0; +UINT32 mSetupHorizontalResolution = 0; +UINT32 mSetupVerticalResolution = 0; FRONT_PAGE_CALLBACK_DATA gFrontPagePrivate = { FRONT_PAGE_CALLBACK_DATA_SIGNATURE, @@ -52,21 +52,22 @@ HII_VENDOR_DEVICE_PATH mFrontPageHiiVendorDevicePath = { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, // // {8E6D99EE-7531-48f8-8745-7F6144468FF2} // - { 0x8e6d99ee, 0x7531, 0x48f8, { 0x87, 0x45, 0x7f, 0x61, 0x44, 0x46, 0x8f, 0xf2 } } + { 0x8e6d99ee, 0x7531, 0x48f8, { 0x87, 0x45, 0x7f, 0x61, 0x44, 0x46, 0x8f, 0xf2 } + } }, { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (END_DEVICE_PATH_LENGTH), - (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8) + (UINT8)(END_DEVICE_PATH_LENGTH), + (UINT8)((END_DEVICE_PATH_LENGTH) >> 8) } } }; @@ -105,15 +106,16 @@ UpdateFrontPageBannerStrings ( EFI_STATUS EFIAPI FakeExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { - if (Progress == NULL || Results == NULL) { + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } + *Progress = Request; return EFI_NOT_FOUND; } @@ -137,12 +139,12 @@ FakeExtractConfig ( EFI_STATUS EFIAPI FakeRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - if (Configuration == NULL || Progress == NULL) { + if ((Configuration == NULL) || (Progress == NULL)) { return EFI_INVALID_PARAMETER; } @@ -172,12 +174,12 @@ FakeRouteConfig ( EFI_STATUS EFIAPI FrontPageCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { return UiFrontPageCallbackHandler (gFrontPagePrivate.HiiHandle, Action, QuestionId, Type, Value, ActionRequest); @@ -193,10 +195,10 @@ UpdateFrontPageForm ( VOID ) { - VOID *StartOpCodeHandle; - VOID *EndOpCodeHandle; - EFI_IFR_GUID_LABEL *StartGuidLabel; - EFI_IFR_GUID_LABEL *EndGuidLabel; + VOID *StartOpCodeHandle; + VOID *EndOpCodeHandle; + EFI_IFR_GUID_LABEL *StartGuidLabel; + EFI_IFR_GUID_LABEL *EndGuidLabel; // // Allocate space for creation of UpdateData Buffer @@ -209,18 +211,18 @@ UpdateFrontPageForm ( // // Create Hii Extend Label OpCode as the start opcode // - StartGuidLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + StartGuidLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); StartGuidLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; StartGuidLabel->Number = LABEL_FRANTPAGE_INFORMATION; // // Create Hii Extend Label OpCode as the end opcode // - EndGuidLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + EndGuidLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); EndGuidLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; EndGuidLabel->Number = LABEL_END; // - //Updata Front Page form + // Updata Front Page form // UiCustomizeFrontPage ( gFrontPagePrivate.HiiHandle, @@ -252,11 +254,12 @@ InitializeFrontPage ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; + // // Locate Hii relative protocols // - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &gFormBrowser2); + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&gFormBrowser2); if (EFI_ERROR (Status)) { return Status; } @@ -265,14 +268,14 @@ InitializeFrontPage ( // Install Device Path Protocol and Config Access protocol to driver handle // gFrontPagePrivate.DriverHandle = NULL; - Status = gBS->InstallMultipleProtocolInterfaces ( - &gFrontPagePrivate.DriverHandle, - &gEfiDevicePathProtocolGuid, - &mFrontPageHiiVendorDevicePath, - &gEfiHiiConfigAccessProtocolGuid, - &gFrontPagePrivate.ConfigAccess, - NULL - ); + Status = gBS->InstallMultipleProtocolInterfaces ( + &gFrontPagePrivate.DriverHandle, + &gEfiDevicePathProtocolGuid, + &mFrontPageHiiVendorDevicePath, + &gEfiHiiConfigAccessProtocolGuid, + &gFrontPagePrivate.ConfigAccess, + NULL + ); ASSERT_EFI_ERROR (Status); // @@ -288,14 +291,14 @@ InitializeFrontPage ( ASSERT (gFrontPagePrivate.HiiHandle != NULL); // - //Updata Front Page banner strings + // Updata Front Page banner strings // UpdateFrontPageBannerStrings (); // // Update front page menus. // - UpdateFrontPageForm(); + UpdateFrontPageForm (); return Status; } @@ -324,15 +327,15 @@ CallFrontPage ( ); ActionRequest = EFI_BROWSER_ACTION_REQUEST_NONE; - Status = gFormBrowser2->SendForm ( - gFormBrowser2, - &gFrontPagePrivate.HiiHandle, - 1, - &mFrontPageGuid, - 0, - NULL, - &ActionRequest - ); + Status = gFormBrowser2->SendForm ( + gFormBrowser2, + &gFrontPagePrivate.HiiHandle, + 1, + &mFrontPageGuid, + 0, + NULL, + &ActionRequest + ); // // Check whether user change any option setting which needs a reset to be effective // @@ -348,11 +351,12 @@ CallFrontPage ( **/ VOID -FreeFrontPage( +FreeFrontPage ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; + Status = gBS->UninstallMultipleProtocolInterfaces ( gFrontPagePrivate.DriverHandle, &gEfiDevicePathProtocolGuid, @@ -383,9 +387,9 @@ FreeFrontPage( **/ VOID ConvertProcessorToString ( - IN UINT16 ProcessorFrequency, - IN UINT16 Base10Exponent, - OUT CHAR16 **String + IN UINT16 ProcessorFrequency, + IN UINT16 Base10Exponent, + OUT CHAR16 **String ) { CHAR16 *StringBuffer; @@ -395,13 +399,14 @@ ConvertProcessorToString ( if (Base10Exponent >= 6) { FreqMhz = ProcessorFrequency; - for (Index = 0; Index < (UINT32) Base10Exponent - 6; Index++) { + for (Index = 0; Index < (UINT32)Base10Exponent - 6; Index++) { FreqMhz *= 10; } } else { FreqMhz = 0; } - DestMax = 0x20 / sizeof (CHAR16); + + DestMax = 0x20 / sizeof (CHAR16); StringBuffer = AllocateZeroPool (0x20); ASSERT (StringBuffer != NULL); UnicodeValueToStringS (StringBuffer, sizeof (CHAR16) * DestMax, LEFT_JUSTIFY, FreqMhz / 1000, 3); @@ -415,11 +420,10 @@ ConvertProcessorToString ( 2 ); StrCatS (StringBuffer, DestMax, L" GHz"); - *String = (CHAR16 *) StringBuffer; - return ; + *String = (CHAR16 *)StringBuffer; + return; } - /** Convert Memory Size to a string. @@ -429,8 +433,8 @@ ConvertProcessorToString ( **/ VOID ConvertMemorySizeToString ( - IN UINT32 MemorySize, - OUT CHAR16 **String + IN UINT32 MemorySize, + OUT CHAR16 **String ) { CHAR16 *StringBuffer; @@ -440,9 +444,9 @@ ConvertMemorySizeToString ( UnicodeValueToStringS (StringBuffer, 0x24, LEFT_JUSTIFY, MemorySize, 10); StrCatS (StringBuffer, 0x24 / sizeof (CHAR16), L" MB RAM"); - *String = (CHAR16 *) StringBuffer; + *String = (CHAR16 *)StringBuffer; - return ; + return; } /** @@ -459,12 +463,12 @@ ConvertMemorySizeToString ( **/ EFI_STATUS GetOptionalStringByIndex ( - IN CHAR8 *OptionalStrStart, - IN UINT8 Index, - OUT CHAR16 **String + IN CHAR8 *OptionalStrStart, + IN UINT8 Index, + OUT CHAR16 **String ) { - UINTN StrSize; + UINTN StrSize; if (Index == 0) { *String = AllocateZeroPool (sizeof (CHAR16)); @@ -492,7 +496,6 @@ GetOptionalStringByIndex ( return EFI_SUCCESS; } - /** Update the banner information for the Front Page based on Smbios information. @@ -503,22 +506,22 @@ UpdateFrontPageBannerStrings ( VOID ) { - UINT8 StrIndex; - CHAR16 *NewString; - CHAR16 *FirmwareVersionString; - EFI_STATUS Status; - EFI_SMBIOS_HANDLE SmbiosHandle; - EFI_SMBIOS_PROTOCOL *Smbios; - SMBIOS_TABLE_TYPE0 *Type0Record; - SMBIOS_TABLE_TYPE1 *Type1Record; - SMBIOS_TABLE_TYPE4 *Type4Record; - SMBIOS_TABLE_TYPE19 *Type19Record; - EFI_SMBIOS_TABLE_HEADER *Record; - UINT64 InstalledMemory; - BOOLEAN FoundCpu; + UINT8 StrIndex; + CHAR16 *NewString; + CHAR16 *FirmwareVersionString; + EFI_STATUS Status; + EFI_SMBIOS_HANDLE SmbiosHandle; + EFI_SMBIOS_PROTOCOL *Smbios; + SMBIOS_TABLE_TYPE0 *Type0Record; + SMBIOS_TABLE_TYPE1 *Type1Record; + SMBIOS_TABLE_TYPE4 *Type4Record; + SMBIOS_TABLE_TYPE19 *Type19Record; + EFI_SMBIOS_TABLE_HEADER *Record; + UINT64 InstalledMemory; + BOOLEAN FoundCpu; InstalledMemory = 0; - FoundCpu = 0; + FoundCpu = 0; // // Update default banner string. @@ -546,7 +549,7 @@ UpdateFrontPageBannerStrings ( // // Update Front Page banner strings base on SmBios Table. // - Status = gBS->LocateProtocol (&gEfiSmbiosProtocolGuid, NULL, (VOID **) &Smbios); + Status = gBS->LocateProtocol (&gEfiSmbiosProtocolGuid, NULL, (VOID **)&Smbios); if (EFI_ERROR (Status)) { // // Smbios protocol not found, get the default value. @@ -580,17 +583,17 @@ UpdateFrontPageBannerStrings ( } SmbiosHandle = SMBIOS_HANDLE_PI_RESERVED; - Status = Smbios->GetNext (Smbios, &SmbiosHandle, NULL, &Record, NULL); - while (!EFI_ERROR(Status)) { + Status = Smbios->GetNext (Smbios, &SmbiosHandle, NULL, &Record, NULL); + while (!EFI_ERROR (Status)) { if (Record->Type == SMBIOS_TYPE_BIOS_INFORMATION) { - Type0Record = (SMBIOS_TABLE_TYPE0 *) Record; - StrIndex = Type0Record->BiosVersion; - GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type0Record + Type0Record->Hdr.Length), StrIndex, &NewString); + Type0Record = (SMBIOS_TABLE_TYPE0 *)Record; + StrIndex = Type0Record->BiosVersion; + GetOptionalStringByIndex ((CHAR8 *)((UINT8 *)Type0Record + Type0Record->Hdr.Length), StrIndex, &NewString); - FirmwareVersionString = (CHAR16 *) PcdGetPtr (PcdFirmwareVersionString); + FirmwareVersionString = (CHAR16 *)PcdGetPtr (PcdFirmwareVersionString); if (*FirmwareVersionString != 0x0000 ) { FreePool (NewString); - NewString = (CHAR16 *) PcdGetPtr (PcdFirmwareVersionString); + NewString = (CHAR16 *)PcdGetPtr (PcdFirmwareVersionString); UiCustomizeFrontPageBanner (3, TRUE, &NewString); HiiSetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_FRONT_PAGE_BIOS_VERSION), NewString, NULL); } else { @@ -601,27 +604,27 @@ UpdateFrontPageBannerStrings ( } if (Record->Type == SMBIOS_TYPE_SYSTEM_INFORMATION) { - Type1Record = (SMBIOS_TABLE_TYPE1 *) Record; - StrIndex = Type1Record->ProductName; - GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type1Record + Type1Record->Hdr.Length), StrIndex, &NewString); + Type1Record = (SMBIOS_TABLE_TYPE1 *)Record; + StrIndex = Type1Record->ProductName; + GetOptionalStringByIndex ((CHAR8 *)((UINT8 *)Type1Record + Type1Record->Hdr.Length), StrIndex, &NewString); UiCustomizeFrontPageBanner (1, TRUE, &NewString); HiiSetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_FRONT_PAGE_COMPUTER_MODEL), NewString, NULL); FreePool (NewString); } if ((Record->Type == SMBIOS_TYPE_PROCESSOR_INFORMATION) && !FoundCpu) { - Type4Record = (SMBIOS_TABLE_TYPE4 *) Record; + Type4Record = (SMBIOS_TABLE_TYPE4 *)Record; // // The information in the record should be only valid when the CPU Socket is populated. // if ((Type4Record->Status & SMBIOS_TYPE4_CPU_SOCKET_POPULATED) == SMBIOS_TYPE4_CPU_SOCKET_POPULATED) { StrIndex = Type4Record->ProcessorVersion; - GetOptionalStringByIndex ((CHAR8*)((UINT8*)Type4Record + Type4Record->Hdr.Length), StrIndex, &NewString); + GetOptionalStringByIndex ((CHAR8 *)((UINT8 *)Type4Record + Type4Record->Hdr.Length), StrIndex, &NewString); UiCustomizeFrontPageBanner (2, TRUE, &NewString); HiiSetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_FRONT_PAGE_CPU_MODEL), NewString, NULL); FreePool (NewString); - ConvertProcessorToString(Type4Record->CurrentSpeed, 6, &NewString); + ConvertProcessorToString (Type4Record->CurrentSpeed, 6, &NewString); UiCustomizeFrontPageBanner (2, FALSE, &NewString); HiiSetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_FRONT_PAGE_CPU_SPEED), NewString, NULL); FreePool (NewString); @@ -631,13 +634,19 @@ UpdateFrontPageBannerStrings ( } if ( Record->Type == SMBIOS_TYPE_MEMORY_ARRAY_MAPPED_ADDRESS ) { - Type19Record = (SMBIOS_TABLE_TYPE19 *) Record; + Type19Record = (SMBIOS_TABLE_TYPE19 *)Record; if (Type19Record->StartingAddress != 0xFFFFFFFF ) { - InstalledMemory += RShiftU64(Type19Record->EndingAddress - - Type19Record->StartingAddress + 1, 10); + InstalledMemory += RShiftU64 ( + Type19Record->EndingAddress - + Type19Record->StartingAddress + 1, + 10 + ); } else { - InstalledMemory += RShiftU64(Type19Record->ExtendedEndingAddress - - Type19Record->ExtendedStartingAddress + 1, 20); + InstalledMemory += RShiftU64 ( + Type19Record->ExtendedEndingAddress - + Type19Record->ExtendedStartingAddress + 1, + 20 + ); } } @@ -647,7 +656,7 @@ UpdateFrontPageBannerStrings ( // // Now update the total installed RAM size // - ConvertMemorySizeToString ((UINT32)InstalledMemory, &NewString ); + ConvertMemorySizeToString ((UINT32)InstalledMemory, &NewString); UiCustomizeFrontPageBanner (3, FALSE, &NewString); HiiSetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_FRONT_PAGE_MEMORY_SIZE), NewString, NULL); FreePool (NewString); @@ -695,7 +704,7 @@ UiSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -704,7 +713,7 @@ UiSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -733,7 +742,7 @@ UiSetConsoleMode ( } if (GraphicsOutput != NULL) { - MaxGopMode = GraphicsOutput->Mode->MaxMode; + MaxGopMode = GraphicsOutput->Mode->MaxMode; } if (SimpleTextOut != NULL) { @@ -749,22 +758,24 @@ UiSetConsoleMode ( // for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( - GraphicsOutput, - ModeNumber, - &SizeOfInfo, - &Info - ); + GraphicsOutput, + ModeNumber, + &SizeOfInfo, + &Info + ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == NewHorizontalResolution) && - (Info->VerticalResolution == NewVerticalResolution)) { + (Info->VerticalResolution == NewVerticalResolution)) + { if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) && - (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) { + (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) + { // // Current resolution is same with required resolution, check if text mode need be set // Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow); ASSERT_EFI_ERROR (Status); - if (CurrentColumn == NewColumns && CurrentRow == NewRows) { + if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // If current text mode is same with required text mode. Do nothing // @@ -776,7 +787,7 @@ UiSetConsoleMode ( // for (Index = 0; Index < MaxTextMode; Index++) { Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // Required text mode is supported, set it. @@ -795,6 +806,7 @@ UiSetConsoleMode ( } } } + if (Index == MaxTextMode) { // // If required text mode is not supported, return error. @@ -815,6 +827,7 @@ UiSetConsoleMode ( } } } + FreePool (Info); } } @@ -845,19 +858,21 @@ UiSetConsoleMode ( // Locate all the handles with GOP protocol and reconnect it. // Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextOutProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextOutProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); } + for (Index = 0; Index < HandleCount; Index++) { gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } + if (HandleBuffer != NULL) { FreePool (HandleBuffer); } @@ -885,12 +900,12 @@ InitializeUserInterface ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_HII_HANDLE HiiHandle; - EFI_STATUS Status; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; - EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; - UINTN BootTextColumn; - UINTN BootTextRow; + EFI_HII_HANDLE HiiHandle; + EFI_STATUS Status; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; + UINTN BootTextColumn; + UINTN BootTextRow; if (!mModeInitialized) { // @@ -900,7 +915,7 @@ InitializeUserInterface ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -909,7 +924,7 @@ InitializeUserInterface ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -942,7 +957,7 @@ InitializeUserInterface ( mSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn); mSetupTextModeRow = PcdGet32 (PcdSetupConOutRow); - mModeInitialized = TRUE; + mModeInitialized = TRUE; } gBS->SetWatchdogTimer (0x0000, 0x0000, 0x0000, NULL); @@ -976,11 +991,11 @@ InitializeUserInterface ( VOID EFIAPI UiEntry ( - IN BOOLEAN ConnectAllHappened + IN BOOLEAN ConnectAllHappened ) { - EFI_STATUS Status; - EFI_BOOT_LOGO_PROTOCOL *BootLogo; + EFI_STATUS Status; + EFI_BOOT_LOGO_PROTOCOL *BootLogo; // // Enter Setup page. @@ -1006,7 +1021,7 @@ UiEntry ( // // Boot Logo is corrupted, report it using Boot Logo protocol. // - Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); + Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **)&BootLogo); if (!EFI_ERROR (Status) && (BootLogo != NULL)) { BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0); } @@ -1023,7 +1038,7 @@ UiEntry ( } // - //Will leave browser, check any reset required change is applied? if yes, reset system + // Will leave browser, check any reset required change is applied? if yes, reset system // SetupResetReminder (); } @@ -1034,10 +1049,6 @@ UiEntry ( // user change any option setting which needs a reset to be effective, and the reset will be applied according to the user selection. // - - - - /** Record the info that a reset is required. A module boolean variable is used to record whether a reset is required. @@ -1052,10 +1063,6 @@ EnableResetRequired ( mResetRequired = TRUE; } - - - - /** Check if user changed any option setting which needs a system reset to be effective. @@ -1069,7 +1076,6 @@ IsResetRequired ( return mResetRequired; } - /** Check whether a reset is needed, and finish the reset reminder feature. If a reset is needed, Popup a menu to notice user, and finish the feature @@ -1082,15 +1088,14 @@ SetupResetReminder ( VOID ) { - EFI_INPUT_KEY Key; - CHAR16 *StringBuffer1; - CHAR16 *StringBuffer2; + EFI_INPUT_KEY Key; + CHAR16 *StringBuffer1; + CHAR16 *StringBuffer2; // - //check any reset required change is applied? if yes, reset system + // check any reset required change is applied? if yes, reset system // if (IsResetRequired ()) { - StringBuffer1 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16)); ASSERT (StringBuffer1 != NULL); StringBuffer2 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16)); @@ -1110,4 +1115,3 @@ SetupResetReminder ( gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); } } - diff --git a/MdeModulePkg/Application/UiApp/FrontPage.h b/MdeModulePkg/Application/UiApp/FrontPage.h index 36207287b9..20c4f5f9a7 100644 --- a/MdeModulePkg/Application/UiApp/FrontPage.h +++ b/MdeModulePkg/Application/UiApp/FrontPage.h @@ -18,24 +18,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // extern UINT8 FrontPageVfrBin[]; -extern EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2; +extern EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2; - -#define SMBIOS_TYPE4_CPU_SOCKET_POPULATED BIT6 +#define SMBIOS_TYPE4_CPU_SOCKET_POPULATED BIT6 // // This is the VFR compiler generated header file which defines the // string identifiers. // -#define PRINTABLE_LANGUAGE_NAME_STRING_ID 0x0001 +#define PRINTABLE_LANGUAGE_NAME_STRING_ID 0x0001 // // These are defined as the same with vfr file // -#define FRONT_PAGE_FORM_ID 0x1000 +#define FRONT_PAGE_FORM_ID 0x1000 -#define LABEL_FRANTPAGE_INFORMATION 0x1000 -#define LABEL_END 0xffff +#define LABEL_FRANTPAGE_INFORMATION 0x1000 +#define LABEL_END 0xffff #define FRONT_PAGE_FORMSET_GUID \ { \ @@ -45,22 +44,21 @@ extern EFI_FORM_BROWSER2_PROTOCOL *gFormBrowser2; #define FRONT_PAGE_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('F', 'P', 'C', 'B') typedef struct { - UINTN Signature; + UINTN Signature; // // HII relative handles // - EFI_HII_HANDLE HiiHandle; - EFI_HANDLE DriverHandle; - EFI_STRING_ID *LanguageToken; + EFI_HII_HANDLE HiiHandle; + EFI_HANDLE DriverHandle; + EFI_STRING_ID *LanguageToken; // // Produced protocols // - EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; + EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; } FRONT_PAGE_CALLBACK_DATA; - #define EFI_FP_CALLBACK_DATA_FROM_THIS(a) \ CR (a, \ FRONT_PAGE_CALLBACK_DATA, \ @@ -93,10 +91,10 @@ typedef struct { EFI_STATUS EFIAPI FakeExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ); /** @@ -118,9 +116,9 @@ FakeExtractConfig ( EFI_STATUS EFIAPI FakeRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ); /** @@ -144,12 +142,12 @@ FakeRouteConfig ( EFI_STATUS EFIAPI FrontPageCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); /** @@ -177,9 +175,9 @@ InitializeFrontPage ( **/ EFI_STATUS GetProducerString ( - IN EFI_GUID *ProducerGuid, - IN EFI_STRING_ID Token, - OUT CHAR16 **String + IN EFI_GUID *ProducerGuid, + IN EFI_STRING_ID Token, + OUT CHAR16 **String ); /** @@ -192,7 +190,7 @@ GetProducerString ( VOID EFIAPI UiEntry ( - IN BOOLEAN ConnectAllHappened + IN BOOLEAN ConnectAllHappened ); /** @@ -206,8 +204,7 @@ UiEntry ( **/ CHAR16 * ExtractDevicePathFromHiiHandle ( - IN EFI_HII_HANDLE Handle + IN EFI_HII_HANDLE Handle ); #endif // _FRONT_PAGE_H_ - diff --git a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.c b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.c index e6d0be548c..f2458ec5a0 100644 --- a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.c +++ b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.c @@ -37,7 +37,7 @@ UiCustomizeFrontPage ( // // Create empty line. // - UiCreateEmptyLine(HiiHandle, StartOpCodeHandle); + UiCreateEmptyLine (HiiHandle, StartOpCodeHandle); // // Find third party drivers which need to be shown in the front page. @@ -47,17 +47,17 @@ UiCustomizeFrontPage ( // // Create empty line. // - UiCreateEmptyLine(HiiHandle, StartOpCodeHandle); + UiCreateEmptyLine (HiiHandle, StartOpCodeHandle); // // Create "Continue" menu. // - UiCreateContinueMenu(HiiHandle, StartOpCodeHandle); + UiCreateContinueMenu (HiiHandle, StartOpCodeHandle); // // Create reset menu. // - UiCreateResetMenu(HiiHandle, StartOpCodeHandle); + UiCreateResetMenu (HiiHandle, StartOpCodeHandle); } /** @@ -80,15 +80,15 @@ UiCustomizeFrontPage ( **/ EFI_STATUS UiFrontPageCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - EFI_STATUS Status; + EFI_STATUS Status; if (UiSupportLibCallbackHandler (HiiHandle, Action, QuestionId, Type, Value, ActionRequest, &Status)) { return Status; @@ -121,19 +121,21 @@ UiFrontPageCallbackHandler ( **/ VOID UiCustomizeFrontPageBanner ( - IN UINTN LineIndex, - IN BOOLEAN LeftOrRight, - IN OUT EFI_STRING *BannerStr + IN UINTN LineIndex, + IN BOOLEAN LeftOrRight, + IN OUT EFI_STRING *BannerStr ) { if ((LineIndex == 5) && LeftOrRight) { // Update STR_CUSTOMIZE_BANNER_LINE5_LEFT - if (PcdGetBool(PcdTestKeyUsed)) { + if (PcdGetBool (PcdTestKeyUsed)) { if (BannerStr != NULL) { - FreePool(*BannerStr); + FreePool (*BannerStr); } - *BannerStr = HiiGetString(gFrontPagePrivate.HiiHandle, STRING_TOKEN(STR_TEST_KEY_USED), NULL); + + *BannerStr = HiiGetString (gFrontPagePrivate.HiiHandle, STRING_TOKEN (STR_TEST_KEY_USED), NULL); } } + return; } diff --git a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.h b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.h index 648f30338f..b53909e217 100644 --- a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.h +++ b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUi.h @@ -33,9 +33,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID UiCustomizeFrontPageBanner ( - IN UINTN LineIndex, - IN BOOLEAN LeftOrRight, - IN OUT EFI_STRING *BannerStr + IN UINTN LineIndex, + IN BOOLEAN LeftOrRight, + IN OUT EFI_STRING *BannerStr ); /** @@ -71,12 +71,12 @@ UiCustomizeFrontPage ( **/ EFI_STATUS UiFrontPageCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); #endif diff --git a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.c b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.c index 858fdfc53d..8bc7883bb7 100644 --- a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.c +++ b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.c @@ -30,29 +30,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // This is the VFR compiler generated header file which defines the // string identifiers. // -#define PRINTABLE_LANGUAGE_NAME_STRING_ID 0x0001 +#define PRINTABLE_LANGUAGE_NAME_STRING_ID 0x0001 -#define UI_HII_DRIVER_LIST_SIZE 0x8 +#define UI_HII_DRIVER_LIST_SIZE 0x8 -#define FRONT_PAGE_KEY_CONTINUE 0x1000 -#define FRONT_PAGE_KEY_RESET 0x1001 -#define FRONT_PAGE_KEY_LANGUAGE 0x1002 -#define FRONT_PAGE_KEY_DRIVER 0x2000 +#define FRONT_PAGE_KEY_CONTINUE 0x1000 +#define FRONT_PAGE_KEY_RESET 0x1001 +#define FRONT_PAGE_KEY_LANGUAGE 0x1002 +#define FRONT_PAGE_KEY_DRIVER 0x2000 typedef struct { - EFI_STRING_ID PromptId; - EFI_STRING_ID HelpId; - EFI_STRING_ID DevicePathId; - EFI_GUID FormSetGuid; - BOOLEAN EmptyLineAfter; + EFI_STRING_ID PromptId; + EFI_STRING_ID HelpId; + EFI_STRING_ID DevicePathId; + EFI_GUID FormSetGuid; + BOOLEAN EmptyLineAfter; } UI_HII_DRIVER_INSTANCE; -CHAR8 *gLanguageString; -EFI_STRING_ID *gLanguageToken; -UI_HII_DRIVER_INSTANCE *gHiiDriverList; -extern EFI_HII_HANDLE gStringPackHandle; -UINT8 gCurrentLanguageIndex; - +CHAR8 *gLanguageString; +EFI_STRING_ID *gLanguageToken; +UI_HII_DRIVER_INSTANCE *gHiiDriverList; +extern EFI_HII_HANDLE gStringPackHandle; +UINT8 gCurrentLanguageIndex; /** Get next language from language code list (with separator ';'). @@ -68,8 +67,8 @@ UINT8 gCurrentLanguageIndex; **/ VOID GetNextLanguage ( - IN OUT CHAR8 **LangCode, - OUT CHAR8 *Lang + IN OUT CHAR8 **LangCode, + OUT CHAR8 *Lang ) { UINTN Index; @@ -79,7 +78,7 @@ GetNextLanguage ( ASSERT (*LangCode != NULL); ASSERT (Lang != NULL); - Index = 0; + Index = 0; StringPtr = *LangCode; while (StringPtr[Index] != 0 && StringPtr[Index] != ';') { Index++; @@ -91,6 +90,7 @@ GetNextLanguage ( if (StringPtr[Index] == ';') { Index++; } + *LangCode = StringPtr + Index; } @@ -106,13 +106,13 @@ GetNextLanguage ( **/ EFI_STATUS LanguageChangeHandler ( - IN EFI_IFR_TYPE_VALUE *Value + IN EFI_IFR_TYPE_VALUE *Value ) { - CHAR8 *LangCode; - CHAR8 *Lang; - UINTN Index; - EFI_STATUS Status; + CHAR8 *LangCode; + CHAR8 *Lang; + UINTN Index; + EFI_STATUS Status; // // Allocate working buffer for RFC 4646 language in supported LanguageString. @@ -120,7 +120,7 @@ LanguageChangeHandler ( Lang = AllocatePool (AsciiStrSize (gLanguageString)); ASSERT (Lang != NULL); - Index = 0; + Index = 0; LangCode = gLanguageString; while (*LangCode != 0) { GetNextLanguage (&LangCode, Lang); @@ -148,6 +148,7 @@ LanguageChangeHandler ( } else { ASSERT (FALSE); } + FreePool (Lang); return EFI_SUCCESS; @@ -172,28 +173,30 @@ LanguageChangeHandler ( **/ BOOLEAN UiSupportLibCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest, - OUT EFI_STATUS *Status + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest, + OUT EFI_STATUS *Status ) { - if (QuestionId != FRONT_PAGE_KEY_CONTINUE && - QuestionId != FRONT_PAGE_KEY_RESET && - QuestionId != FRONT_PAGE_KEY_LANGUAGE) { + if ((QuestionId != FRONT_PAGE_KEY_CONTINUE) && + (QuestionId != FRONT_PAGE_KEY_RESET) && + (QuestionId != FRONT_PAGE_KEY_LANGUAGE)) + { return FALSE; } if (Action == EFI_BROWSER_ACTION_RETRIEVE) { if (QuestionId == FRONT_PAGE_KEY_LANGUAGE) { Value->u8 = gCurrentLanguageIndex; - *Status = EFI_SUCCESS; + *Status = EFI_SUCCESS; } else { *Status = EFI_UNSUPPORTED; } + return TRUE; } @@ -213,26 +216,26 @@ UiSupportLibCallbackHandler ( *Status = EFI_SUCCESS; switch (QuestionId) { - case FRONT_PAGE_KEY_CONTINUE: - // - // This is the continue - clear the screen and return an error to get out of FrontPage loop - // - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; - break; - - case FRONT_PAGE_KEY_LANGUAGE: - *Status = LanguageChangeHandler(Value); - break; - - case FRONT_PAGE_KEY_RESET: - // - // Reset - // - gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); - *Status = EFI_UNSUPPORTED; - - default: - break; + case FRONT_PAGE_KEY_CONTINUE: + // + // This is the continue - clear the screen and return an error to get out of FrontPage loop + // + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; + break; + + case FRONT_PAGE_KEY_LANGUAGE: + *Status = LanguageChangeHandler (Value); + break; + + case FRONT_PAGE_KEY_RESET: + // + // Reset + // + gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); + *Status = EFI_UNSUPPORTED; + + default: + break; } } @@ -248,20 +251,20 @@ UiSupportLibCallbackHandler ( **/ VOID UiCreateLanguageMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { - CHAR8 *LangCode; - CHAR8 *Lang; - UINTN LangSize; - CHAR8 *CurrentLang; - UINTN OptionCount; - CHAR16 *StringBuffer; - VOID *OptionsOpCodeHandle; - UINTN StringSize; - EFI_STATUS Status; - EFI_HII_STRING_PROTOCOL *HiiString; + CHAR8 *LangCode; + CHAR8 *Lang; + UINTN LangSize; + CHAR8 *CurrentLang; + UINTN OptionCount; + CHAR16 *StringBuffer; + VOID *OptionsOpCodeHandle; + UINTN StringSize; + EFI_STATUS Status; + EFI_HII_STRING_PROTOCOL *HiiString; Lang = NULL; StringBuffer = NULL; @@ -272,17 +275,17 @@ UiCreateLanguageMenu ( OptionsOpCodeHandle = HiiAllocateOpCodeHandle (); ASSERT (OptionsOpCodeHandle != NULL); - GetEfiGlobalVariable2 (L"PlatformLang", (VOID**)&CurrentLang, NULL); + GetEfiGlobalVariable2 (L"PlatformLang", (VOID **)&CurrentLang, NULL); // // Get Support language list from variable. // - GetEfiGlobalVariable2 (L"PlatformLangCodes", (VOID**)&gLanguageString, NULL); + GetEfiGlobalVariable2 (L"PlatformLangCodes", (VOID **)&gLanguageString, NULL); if (gLanguageString == NULL) { gLanguageString = AllocateCopyPool ( - AsciiStrSize ((CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes)), - (CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes) - ); + AsciiStrSize ((CHAR8 *)PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes)), + (CHAR8 *)PcdGetPtr (PcdUefiVariableDefaultPlatformLangCodes) + ); ASSERT (gLanguageString != NULL); } @@ -291,13 +294,13 @@ UiCreateLanguageMenu ( // Count the language list number. // LangCode = gLanguageString; - Lang = AllocatePool (AsciiStrSize (gLanguageString)); + Lang = AllocatePool (AsciiStrSize (gLanguageString)); ASSERT (Lang != NULL); OptionCount = 0; while (*LangCode != 0) { GetNextLanguage (&LangCode, Lang); - OptionCount ++; + OptionCount++; } // @@ -306,16 +309,16 @@ UiCreateLanguageMenu ( gLanguageToken = AllocateZeroPool ((OptionCount + 1) * sizeof (EFI_STRING_ID)); ASSERT (gLanguageToken != NULL); - Status = gBS->LocateProtocol (&gEfiHiiStringProtocolGuid, NULL, (VOID **) &HiiString); + Status = gBS->LocateProtocol (&gEfiHiiStringProtocolGuid, NULL, (VOID **)&HiiString); ASSERT_EFI_ERROR (Status); - LangCode = gLanguageString; - OptionCount = 0; + LangCode = gLanguageString; + OptionCount = 0; while (*LangCode != 0) { GetNextLanguage (&LangCode, Lang); StringSize = 0; - Status = HiiString->GetString (HiiString, Lang, HiiHandle, PRINTABLE_LANGUAGE_NAME_STRING_ID, StringBuffer, &StringSize, NULL); + Status = HiiString->GetString (HiiString, Lang, HiiHandle, PRINTABLE_LANGUAGE_NAME_STRING_ID, StringBuffer, &StringSize, NULL); if (Status == EFI_BUFFER_TOO_SMALL) { StringBuffer = AllocateZeroPool (StringSize); ASSERT (StringBuffer != NULL); @@ -324,7 +327,7 @@ UiCreateLanguageMenu ( } if (EFI_ERROR (Status)) { - LangSize = AsciiStrSize (Lang); + LangSize = AsciiStrSize (Lang); StringBuffer = AllocatePool (LangSize * sizeof (CHAR16)); ASSERT (StringBuffer != NULL); AsciiStrToUnicodeStrS (Lang, StringBuffer, LangSize); @@ -339,31 +342,32 @@ UiCreateLanguageMenu ( } ASSERT (gLanguageToken != NULL); - LangCode = gLanguageString; + LangCode = gLanguageString; OptionCount = 0; if (Lang == NULL) { Lang = AllocatePool (AsciiStrSize (gLanguageString)); ASSERT (Lang != NULL); } + while (*LangCode != 0) { GetNextLanguage (&LangCode, Lang); - if (CurrentLang != NULL && AsciiStrCmp (Lang, CurrentLang) == 0) { + if ((CurrentLang != NULL) && (AsciiStrCmp (Lang, CurrentLang) == 0)) { HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, gLanguageToken[OptionCount], EFI_IFR_OPTION_DEFAULT, EFI_IFR_NUMERIC_SIZE_1, - (UINT8) OptionCount + (UINT8)OptionCount ); - gCurrentLanguageIndex = (UINT8) OptionCount; + gCurrentLanguageIndex = (UINT8)OptionCount; } else { HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, gLanguageToken[OptionCount], 0, EFI_IFR_NUMERIC_SIZE_1, - (UINT8) OptionCount + (UINT8)OptionCount ); } @@ -373,6 +377,7 @@ UiCreateLanguageMenu ( if (CurrentLang != NULL) { FreePool (CurrentLang); } + FreePool (Lang); HiiCreateOneOfOpCode ( @@ -398,8 +403,8 @@ UiCreateLanguageMenu ( **/ VOID UiCreateContinueMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateActionOpCode ( @@ -421,8 +426,8 @@ UiCreateContinueMenu ( **/ VOID UiCreateEmptyLine ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateSubTitleOpCode (StartOpCodeHandle, STRING_TOKEN (STR_NULL_STRING), 0, 0, 0); @@ -437,8 +442,8 @@ UiCreateEmptyLine ( **/ VOID UiCreateResetMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateActionOpCode ( @@ -462,11 +467,11 @@ UiCreateResetMenu ( **/ CHAR16 * ExtractDevicePathFromHiiHandle ( - IN EFI_HII_HANDLE Handle + IN EFI_HII_HANDLE Handle ) { - EFI_STATUS Status; - EFI_HANDLE DriverHandle; + EFI_STATUS Status; + EFI_HANDLE DriverHandle; ASSERT (Handle != NULL); @@ -479,7 +484,7 @@ ExtractDevicePathFromHiiHandle ( return NULL; } - return ConvertDevicePathToText(DevicePathFromHandle (DriverHandle), FALSE, FALSE); + return ConvertDevicePathToText (DevicePathFromHandle (DriverHandle), FALSE, FALSE); } /** @@ -496,49 +501,49 @@ ExtractDevicePathFromHiiHandle ( **/ BOOLEAN RequiredDriver ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *Guid, - OUT EFI_STRING_ID *PromptId, - OUT EFI_STRING_ID *HelpId, - OUT VOID *FormsetGuid + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *Guid, + OUT EFI_STRING_ID *PromptId, + OUT EFI_STRING_ID *HelpId, + OUT VOID *FormsetGuid ) { - EFI_STATUS Status; - UINT8 ClassGuidNum; - EFI_GUID *ClassGuid; - EFI_IFR_FORM_SET *Buffer; - UINTN BufferSize; - UINT8 *Ptr; - UINTN TempSize; - BOOLEAN RetVal; - - Status = HiiGetFormSetFromHiiHandle(HiiHandle, &Buffer,&BufferSize); + EFI_STATUS Status; + UINT8 ClassGuidNum; + EFI_GUID *ClassGuid; + EFI_IFR_FORM_SET *Buffer; + UINTN BufferSize; + UINT8 *Ptr; + UINTN TempSize; + BOOLEAN RetVal; + + Status = HiiGetFormSetFromHiiHandle (HiiHandle, &Buffer, &BufferSize); if (EFI_ERROR (Status)) { return FALSE; } - RetVal = FALSE; + RetVal = FALSE; TempSize = 0; - Ptr = (UINT8 *) Buffer; - while(TempSize < BufferSize) { - TempSize += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + Ptr = (UINT8 *)Buffer; + while (TempSize < BufferSize) { + TempSize += ((EFI_IFR_OP_HEADER *)Ptr)->Length; - if (((EFI_IFR_OP_HEADER *) Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)){ - Ptr += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + if (((EFI_IFR_OP_HEADER *)Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)) { + Ptr += ((EFI_IFR_OP_HEADER *)Ptr)->Length; continue; } - ClassGuidNum = (UINT8) (((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); - ClassGuid = (EFI_GUID *) (VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); + ClassGuidNum = (UINT8)(((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); + ClassGuid = (EFI_GUID *)(VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); while (ClassGuidNum-- > 0) { - if (!CompareGuid (Guid, ClassGuid)){ - ClassGuid ++; + if (!CompareGuid (Guid, ClassGuid)) { + ClassGuid++; continue; } *PromptId = ((EFI_IFR_FORM_SET *)Ptr)->FormSetTitle; - *HelpId = ((EFI_IFR_FORM_SET *)Ptr)->Help; - CopyMem (FormsetGuid, &((EFI_IFR_FORM_SET *) Ptr)->Guid, sizeof (EFI_GUID)); + *HelpId = ((EFI_IFR_FORM_SET *)Ptr)->Help; + CopyMem (FormsetGuid, &((EFI_IFR_FORM_SET *)Ptr)->Guid, sizeof (EFI_GUID)); RetVal = TRUE; } } @@ -562,23 +567,23 @@ RequiredDriver ( **/ EFI_STATUS UiListThirdPartyDrivers ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *ClassGuid, - IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *ClassGuid, + IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, + IN VOID *StartOpCodeHandle ) { - UINTN Index; - EFI_STRING String; - EFI_STRING_ID Token; - EFI_STRING_ID TokenHelp; - EFI_HII_HANDLE *HiiHandles; - CHAR16 *DevicePathStr; - UINTN Count; - UINTN CurrentSize; - UI_HII_DRIVER_INSTANCE *DriverListPtr; - EFI_STRING NewName; - BOOLEAN EmptyLineAfter; + UINTN Index; + EFI_STRING String; + EFI_STRING_ID Token; + EFI_STRING_ID TokenHelp; + EFI_HII_HANDLE *HiiHandles; + CHAR16 *DevicePathStr; + UINTN Count; + UINTN CurrentSize; + UI_HII_DRIVER_INSTANCE *DriverListPtr; + EFI_STRING NewName; + BOOLEAN EmptyLineAfter; if (gHiiDriverList != NULL) { FreePool (gHiiDriverList); @@ -590,7 +595,7 @@ UiListThirdPartyDrivers ( gHiiDriverList = AllocateZeroPool (UI_HII_DRIVER_LIST_SIZE * sizeof (UI_HII_DRIVER_INSTANCE)); ASSERT (gHiiDriverList != NULL); DriverListPtr = gHiiDriverList; - CurrentSize = UI_HII_DRIVER_LIST_SIZE; + CurrentSize = UI_HII_DRIVER_LIST_SIZE; for (Index = 0, Count = 0; HiiHandles[Index] != NULL; Index++) { if (!RequiredDriver (HiiHandles[Index], ClassGuid, &Token, &TokenHelp, &gHiiDriverList[Count].FormSetGuid)) { @@ -608,10 +613,11 @@ UiListThirdPartyDrivers ( EmptyLineAfter = FALSE; if (SpecialHandlerFn (String, &NewName, &EmptyLineAfter)) { FreePool (String); - String = NewName; + String = NewName; DriverListPtr[Count].EmptyLineAfter = EmptyLineAfter; } } + DriverListPtr[Count].PromptId = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); @@ -620,11 +626,12 @@ UiListThirdPartyDrivers ( String = HiiGetString (gStringPackHandle, STRING_TOKEN (STR_MISSING_STRING), NULL); ASSERT (String != NULL); } + DriverListPtr[Count].HelpId = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); - DevicePathStr = ExtractDevicePathFromHiiHandle(HiiHandles[Index]); - if (DevicePathStr != NULL){ + DevicePathStr = ExtractDevicePathFromHiiHandle (HiiHandles[Index]); + if (DevicePathStr != NULL) { DriverListPtr[Count].DevicePathId = HiiSetString (HiiHandle, 0, DevicePathStr, NULL); FreePool (DevicePathStr); } else { @@ -636,12 +643,12 @@ UiListThirdPartyDrivers ( DriverListPtr = ReallocatePool ( CurrentSize * sizeof (UI_HII_DRIVER_INSTANCE), (Count + UI_HII_DRIVER_LIST_SIZE) - * sizeof (UI_HII_DRIVER_INSTANCE), + * sizeof (UI_HII_DRIVER_INSTANCE), gHiiDriverList ); ASSERT (DriverListPtr != NULL); gHiiDriverList = DriverListPtr; - CurrentSize += UI_HII_DRIVER_LIST_SIZE; + CurrentSize += UI_HII_DRIVER_LIST_SIZE; } } @@ -655,17 +662,17 @@ UiListThirdPartyDrivers ( gHiiDriverList[Index].PromptId, gHiiDriverList[Index].HelpId, 0, - (EFI_QUESTION_ID) (Index + FRONT_PAGE_KEY_DRIVER), + (EFI_QUESTION_ID)(Index + FRONT_PAGE_KEY_DRIVER), 0, &gHiiDriverList[Index].FormSetGuid, gHiiDriverList[Index].DevicePathId - ); + ); if (gHiiDriverList[Index].EmptyLineAfter) { UiCreateEmptyLine (HiiHandle, StartOpCodeHandle); } - Index ++; + Index++; } return EFI_SUCCESS; diff --git a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.h b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.h index 7be45849f9..c4fddebc27 100644 --- a/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.h +++ b/MdeModulePkg/Application/UiApp/FrontPageCustomizedUiSupport.h @@ -18,8 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID UiCreateContinueMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -31,8 +31,8 @@ UiCreateContinueMenu ( **/ VOID UiCreateEmptyLine ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -44,8 +44,8 @@ UiCreateEmptyLine ( **/ VOID UiCreateLanguageMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -57,8 +57,8 @@ UiCreateLanguageMenu ( **/ VOID UiCreateResetMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -77,7 +77,7 @@ BOOLEAN IN CHAR16 *DriverName, OUT CHAR16 **NewName, OUT BOOLEAN *EmptyLineAfter -); + ); /** Search the drivers in the system which need to show in the front page @@ -93,10 +93,10 @@ BOOLEAN **/ EFI_STATUS UiListThirdPartyDrivers ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *ClassGuid, - IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *ClassGuid, + IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, + IN VOID *StartOpCodeHandle ); /** @@ -118,13 +118,13 @@ UiListThirdPartyDrivers ( **/ BOOLEAN UiSupportLibCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest, - OUT EFI_STATUS *Status + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest, + OUT EFI_STATUS *Status ); #endif diff --git a/MdeModulePkg/Application/UiApp/String.c b/MdeModulePkg/Application/UiApp/String.c index a4d0c32108..f6548fcd32 100644 --- a/MdeModulePkg/Application/UiApp/String.c +++ b/MdeModulePkg/Application/UiApp/String.c @@ -9,36 +9,36 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ui.h" #include "FrontPage.h" -EFI_HII_HANDLE gStringPackHandle; +EFI_HII_HANDLE gStringPackHandle; -EFI_GUID mUiStringPackGuid = { +EFI_GUID mUiStringPackGuid = { 0x136a3048, 0x752a, 0x4bf6, { 0xa7, 0x57, 0x9, 0x36, 0x11, 0x95, 0x38, 0xed } }; EFI_GUID mFontPackageGuid = { - 0x78941450, 0x90ab, 0x4fb1, {0xb7, 0x5f, 0x58, 0x92, 0x14, 0xe2, 0x4a, 0xc} + 0x78941450, 0x90ab, 0x4fb1, { 0xb7, 0x5f, 0x58, 0x92, 0x14, 0xe2, 0x4a, 0xc } }; -#define NARROW_GLYPH_NUMBER 8 -#define WIDE_GLYPH_NUMBER 75 +#define NARROW_GLYPH_NUMBER 8 +#define WIDE_GLYPH_NUMBER 75 typedef struct { /// /// This 4-bytes total array length is required by HiiAddPackages() /// - UINT32 Length; + UINT32 Length; // // This is the Font package definition // - EFI_HII_PACKAGE_HEADER Header; - UINT16 NumberOfNarrowGlyphs; - UINT16 NumberOfWideGlyphs; - EFI_NARROW_GLYPH NarrowArray[NARROW_GLYPH_NUMBER]; - EFI_WIDE_GLYPH WideArray[WIDE_GLYPH_NUMBER]; + EFI_HII_PACKAGE_HEADER Header; + UINT16 NumberOfNarrowGlyphs; + UINT16 NumberOfWideGlyphs; + EFI_NARROW_GLYPH NarrowArray[NARROW_GLYPH_NUMBER]; + EFI_WIDE_GLYPH WideArray[WIDE_GLYPH_NUMBER]; } FONT_PACK_BIN; -FONT_PACK_BIN mFontBin = { +FONT_PACK_BIN mFontBin = { sizeof (FONT_PACK_BIN), { sizeof (FONT_PACK_BIN) - sizeof (UINT32), @@ -260,11 +260,11 @@ InitializeStringSupport ( ) { gStringPackHandle = HiiAddPackages ( - &mUiStringPackGuid, - gImageHandle, - UiAppStrings, - NULL - ); + &mUiStringPackGuid, + gImageHandle, + UiAppStrings, + NULL + ); ASSERT (gStringPackHandle != NULL); } @@ -292,7 +292,7 @@ UninitializeStringSupport ( **/ CHAR16 * GetStringById ( - IN EFI_STRING_ID Id + IN EFI_STRING_ID Id ) { return HiiGetString (gStringPackHandle, Id, NULL); diff --git a/MdeModulePkg/Application/UiApp/String.h b/MdeModulePkg/Application/UiApp/String.h index 3dc4c3316b..2ecdb6e790 100644 --- a/MdeModulePkg/Application/UiApp/String.h +++ b/MdeModulePkg/Application/UiApp/String.h @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _STRING_H_ #define _STRING_H_ -extern EFI_HII_HANDLE gStringPackHandle; +extern EFI_HII_HANDLE gStringPackHandle; // // This is the VFR compiler generated header file which defines the @@ -38,7 +38,7 @@ extern UINT8 BdsDxeStrings[]; **/ CHAR16 * GetStringById ( - IN EFI_STRING_ID Id + IN EFI_STRING_ID Id ); /** diff --git a/MdeModulePkg/Application/UiApp/Ui.h b/MdeModulePkg/Application/UiApp/Ui.h index 56e54033b8..b2947a6312 100644 --- a/MdeModulePkg/Application/UiApp/Ui.h +++ b/MdeModulePkg/Application/UiApp/Ui.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _BDS_MODULE_H_ #define _BDS_MODULE_H_ @@ -37,18 +36,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; #pragma pack() - // -//The interface functions related to the Setup Browser Reset Reminder feature +// The interface functions related to the Setup Browser Reset Reminder feature // - /** Record the info that a reset is required. A module boolean variable is used to record whether a reset is required. @@ -60,8 +57,6 @@ EnableResetRequired ( VOID ); - - /** Check whether platform policy enables the reset reminder feature. The default is enabled. diff --git a/MdeModulePkg/Application/VariableInfo/VariableInfo.c b/MdeModulePkg/Application/VariableInfo/VariableInfo.c index a7df365b58..3dee41eb4b 100644 --- a/MdeModulePkg/Application/VariableInfo/VariableInfo.c +++ b/MdeModulePkg/Application/VariableInfo/VariableInfo.c @@ -41,23 +41,25 @@ EFI_MM_COMMUNICATION2_PROTOCOL *mMmCommunication2 = NULL; EFI_STATUS EFIAPI GetVariableStatisticsData ( - IN OUT EFI_MM_COMMUNICATE_HEADER *SmmCommunicateHeader, - IN OUT UINTN *SmmCommunicateSize + IN OUT EFI_MM_COMMUNICATE_HEADER *SmmCommunicateHeader, + IN OUT UINTN *SmmCommunicateSize ) { - EFI_STATUS Status; - SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; + EFI_STATUS Status; + SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; CopyGuid (&SmmCommunicateHeader->HeaderGuid, &gEfiSmmVariableProtocolGuid); SmmCommunicateHeader->MessageLength = *SmmCommunicateSize - OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data); - SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) &SmmCommunicateHeader->Data[0]; + SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)&SmmCommunicateHeader->Data[0]; SmmVariableFunctionHeader->Function = SMM_VARIABLE_FUNCTION_GET_STATISTICS; - Status = mMmCommunication2->Communicate (mMmCommunication2, - SmmCommunicateHeader, - SmmCommunicateHeader, - SmmCommunicateSize); + Status = mMmCommunication2->Communicate ( + mMmCommunication2, + SmmCommunicateHeader, + SmmCommunicateHeader, + SmmCommunicateSize + ); ASSERT_EFI_ERROR (Status); Status = SmmVariableFunctionHeader->ReturnStatus; @@ -77,62 +79,65 @@ PrintInfoFromSmm ( VOID ) { - EFI_STATUS Status; - VARIABLE_INFO_ENTRY *VariableInfo; - EFI_MM_COMMUNICATE_HEADER *CommBuffer; - UINTN RealCommSize; - UINTN CommSize; - SMM_VARIABLE_COMMUNICATE_HEADER *FunctionHeader; - EFI_SMM_VARIABLE_PROTOCOL *Smmvariable; - EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; - UINT32 Index; - EFI_MEMORY_DESCRIPTOR *Entry; - UINTN Size; - UINTN MaxSize; - - Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **) &Smmvariable); + EFI_STATUS Status; + VARIABLE_INFO_ENTRY *VariableInfo; + EFI_MM_COMMUNICATE_HEADER *CommBuffer; + UINTN RealCommSize; + UINTN CommSize; + SMM_VARIABLE_COMMUNICATE_HEADER *FunctionHeader; + EFI_SMM_VARIABLE_PROTOCOL *Smmvariable; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; + UINT32 Index; + EFI_MEMORY_DESCRIPTOR *Entry; + UINTN Size; + UINTN MaxSize; + + Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **)&Smmvariable); if (EFI_ERROR (Status)) { return Status; } - Status = gBS->LocateProtocol (&gEfiMmCommunication2ProtocolGuid, NULL, (VOID **) &mMmCommunication2); + Status = gBS->LocateProtocol (&gEfiMmCommunication2ProtocolGuid, NULL, (VOID **)&mMmCommunication2); if (EFI_ERROR (Status)) { return Status; } - CommBuffer = NULL; + CommBuffer = NULL; RealCommSize = 0; - Status = EfiGetSystemConfigurationTable ( - &gEdkiiPiSmmCommunicationRegionTableGuid, - (VOID **) &PiSmmCommunicationRegionTable - ); + Status = EfiGetSystemConfigurationTable ( + &gEdkiiPiSmmCommunicationRegionTableGuid, + (VOID **)&PiSmmCommunicationRegionTable + ); if (EFI_ERROR (Status)) { return Status; } + ASSERT (PiSmmCommunicationRegionTable != NULL); - Entry = (EFI_MEMORY_DESCRIPTOR *) (PiSmmCommunicationRegionTable + 1); - Size = 0; + Entry = (EFI_MEMORY_DESCRIPTOR *)(PiSmmCommunicationRegionTable + 1); + Size = 0; MaxSize = 0; for (Index = 0; Index < PiSmmCommunicationRegionTable->NumberOfEntries; Index++) { if (Entry->Type == EfiConventionalMemory) { - Size = EFI_PAGES_TO_SIZE ((UINTN) Entry->NumberOfPages); + Size = EFI_PAGES_TO_SIZE ((UINTN)Entry->NumberOfPages); if (Size > (SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (VARIABLE_INFO_ENTRY))) { if (Size > MaxSize) { - MaxSize = Size; + MaxSize = Size; RealCommSize = MaxSize; - CommBuffer = (EFI_MM_COMMUNICATE_HEADER *) (UINTN) Entry->PhysicalStart; + CommBuffer = (EFI_MM_COMMUNICATE_HEADER *)(UINTN)Entry->PhysicalStart; } } } - Entry = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) Entry + PiSmmCommunicationRegionTable->DescriptorSize); + + Entry = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Entry + PiSmmCommunicationRegionTable->DescriptorSize); } + ASSERT (CommBuffer != NULL); ZeroMem (CommBuffer, RealCommSize); Print (L"SMM Driver Non-Volatile Variables:\n"); do { CommSize = RealCommSize; - Status = GetVariableStatisticsData (CommBuffer, &CommSize); + Status = GetVariableStatisticsData (CommBuffer, &CommSize); if (Status == EFI_BUFFER_TOO_SMALL) { Print (L"The generic SMM communication buffer provided by SmmCommunicationRegionTable is too small\n"); return Status; @@ -142,19 +147,19 @@ PrintInfoFromSmm ( break; } - FunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) CommBuffer->Data; - VariableInfo = (VARIABLE_INFO_ENTRY *) FunctionHeader->Data; + FunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)CommBuffer->Data; + VariableInfo = (VARIABLE_INFO_ENTRY *)FunctionHeader->Data; if (!VariableInfo->Volatile) { Print ( - L"%g R%03d(%03d) W%03d D%03d:%s\n", - &VariableInfo->VendorGuid, - VariableInfo->ReadCount, - VariableInfo->CacheCount, - VariableInfo->WriteCount, - VariableInfo->DeleteCount, - (CHAR16 *)(VariableInfo + 1) - ); + L"%g R%03d(%03d) W%03d D%03d:%s\n", + &VariableInfo->VendorGuid, + VariableInfo->ReadCount, + VariableInfo->CacheCount, + VariableInfo->WriteCount, + VariableInfo->DeleteCount, + (CHAR16 *)(VariableInfo + 1) + ); } } while (TRUE); @@ -162,7 +167,7 @@ PrintInfoFromSmm ( ZeroMem (CommBuffer, RealCommSize); do { CommSize = RealCommSize; - Status = GetVariableStatisticsData (CommBuffer, &CommSize); + Status = GetVariableStatisticsData (CommBuffer, &CommSize); if (Status == EFI_BUFFER_TOO_SMALL) { Print (L"The generic SMM communication buffer provided by SmmCommunicationRegionTable is too small\n"); return Status; @@ -172,19 +177,19 @@ PrintInfoFromSmm ( break; } - FunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) CommBuffer->Data; - VariableInfo = (VARIABLE_INFO_ENTRY *) FunctionHeader->Data; + FunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *)CommBuffer->Data; + VariableInfo = (VARIABLE_INFO_ENTRY *)FunctionHeader->Data; if (VariableInfo->Volatile) { Print ( - L"%g R%03d(%03d) W%03d D%03d:%s\n", - &VariableInfo->VendorGuid, - VariableInfo->ReadCount, - VariableInfo->CacheCount, - VariableInfo->WriteCount, - VariableInfo->DeleteCount, - (CHAR16 *)(VariableInfo + 1) - ); + L"%g R%03d(%03d) W%03d D%03d:%s\n", + &VariableInfo->VendorGuid, + VariableInfo->ReadCount, + VariableInfo->CacheCount, + VariableInfo->WriteCount, + VariableInfo->DeleteCount, + (CHAR16 *)(VariableInfo + 1) + ); } } while (TRUE); @@ -210,14 +215,14 @@ UefiMain ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS RuntimeDxeStatus; - EFI_STATUS SmmStatus; - VARIABLE_INFO_ENTRY *VariableInfo; - VARIABLE_INFO_ENTRY *Entry; + EFI_STATUS RuntimeDxeStatus; + EFI_STATUS SmmStatus; + VARIABLE_INFO_ENTRY *VariableInfo; + VARIABLE_INFO_ENTRY *Entry; - RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **) &Entry); + RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **)&Entry); if (EFI_ERROR (RuntimeDxeStatus) || (Entry == NULL)) { - RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **) &Entry); + RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **)&Entry); } if (!EFI_ERROR (RuntimeDxeStatus) && (Entry != NULL)) { @@ -253,6 +258,7 @@ UefiMain ( VariableInfo->Name ); } + VariableInfo = VariableInfo->Next; } while (VariableInfo != NULL); } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c index 7636ad27c8..7b97887c5d 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciMode.c @@ -10,9 +10,9 @@ #include "AhciPei.h" -#define ATA_CMD_TRUST_NON_DATA 0x5B -#define ATA_CMD_TRUST_RECEIVE 0x5C -#define ATA_CMD_TRUST_SEND 0x5E +#define ATA_CMD_TRUST_NON_DATA 0x5B +#define ATA_CMD_TRUST_RECEIVE 0x5C +#define ATA_CMD_TRUST_SEND 0x5E // // Look up table (IsWrite) for EFI_ATA_PASS_THRU_CMD_PROTOCOL @@ -25,7 +25,7 @@ EFI_ATA_PASS_THRU_CMD_PROTOCOL mAtaPassThruCmdProtocols[2] = { // // Look up table (Lba48Bit, IsIsWrite) for ATA_CMD // -UINT8 mAtaCommands[2][2] = { +UINT8 mAtaCommands[2][2] = { { ATA_CMD_READ_SECTORS, // 28-bit LBA; PIO read ATA_CMD_WRITE_SECTORS // 28-bit LBA; PIO write @@ -47,16 +47,16 @@ UINT8 mAtaTrustCommands[2] = { // // Look up table (Lba48Bit) for maximum transfer block number // -#define MAX_28BIT_TRANSFER_BLOCK_NUM 0x100 +#define MAX_28BIT_TRANSFER_BLOCK_NUM 0x100 // // Due to limited resource for VTd PEI DMA buffer on platforms, the driver // limits the maximum transfer block number for 48-bit addressing. // Here, setting to 0x800 means that for device with 512-byte block size, the // maximum buffer for DMA mapping will be 1M bytes in size. // -#define MAX_48BIT_TRANSFER_BLOCK_NUM 0x800 +#define MAX_48BIT_TRANSFER_BLOCK_NUM 0x800 -UINT32 mMaxTransferBlockNumber[2] = { +UINT32 mMaxTransferBlockNumber[2] = { MAX_28BIT_TRANSFER_BLOCK_NUM, MAX_48BIT_TRANSFER_BLOCK_NUM }; @@ -64,8 +64,7 @@ UINT32 mMaxTransferBlockNumber[2] = { // // The maximum total sectors count in 28 bit addressing mode // -#define MAX_28BIT_ADDRESSING_CAPACITY 0xfffffff - +#define MAX_28BIT_ADDRESSING_CAPACITY 0xfffffff /** Read AHCI Operation register. @@ -78,11 +77,11 @@ UINT32 mMaxTransferBlockNumber[2] = { **/ UINT32 AhciReadReg ( - IN UINTN AhciBar, - IN UINT32 Offset + IN UINTN AhciBar, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; Data = 0; Data = MmioRead32 (AhciBar + Offset); @@ -100,9 +99,9 @@ AhciReadReg ( **/ VOID AhciWriteReg ( - IN UINTN AhciBar, - IN UINT32 Offset, - IN UINT32 Data + IN UINTN AhciBar, + IN UINT32 Offset, + IN UINT32 Data ) { MmioWrite32 (AhciBar + Offset, Data); @@ -118,12 +117,12 @@ AhciWriteReg ( **/ VOID AhciAndReg ( - IN UINTN AhciBar, - IN UINT32 Offset, - IN UINT32 AndData + IN UINTN AhciBar, + IN UINT32 Offset, + IN UINT32 AndData ) { - UINT32 Data; + UINT32 Data; Data = AhciReadReg (AhciBar, Offset); Data &= AndData; @@ -141,12 +140,12 @@ AhciAndReg ( **/ VOID AhciOrReg ( - IN UINTN AhciBar, - IN UINT32 Offset, - IN UINT32 OrData + IN UINTN AhciBar, + IN UINT32 Offset, + IN UINT32 OrData ) { - UINT32 Data; + UINT32 Data; Data = AhciReadReg (AhciBar, Offset); Data |= OrData; @@ -171,17 +170,17 @@ AhciOrReg ( EFI_STATUS EFIAPI AhciWaitMmioSet ( - IN UINTN AhciBar, - IN UINT32 Offset, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT32 Offset, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT32 Delay; + UINT32 Value; + UINT32 Delay; - Delay = (UINT32) (DivU64x32(Timeout, 1000) + 1); + Delay = (UINT32)(DivU64x32 (Timeout, 1000) + 1); do { Value = AhciReadReg (AhciBar, Offset) & MaskValue; @@ -196,7 +195,6 @@ AhciWaitMmioSet ( MicroSecondDelay (100); Delay--; - } while (Delay > 0); return EFI_TIMEOUT; @@ -215,14 +213,14 @@ AhciWaitMmioSet ( **/ EFI_STATUS AhciCheckMemSet ( - IN UINTN Address, - IN UINT32 MaskValue, - IN UINT32 TestValue + IN UINTN Address, + IN UINT32 MaskValue, + IN UINT32 TestValue ) { - UINT32 Value; + UINT32 Value; - Value = *(volatile UINT32 *) Address; + Value = *(volatile UINT32 *)Address; Value &= MaskValue; if (Value == TestValue) { @@ -246,15 +244,15 @@ AhciCheckMemSet ( **/ EFI_STATUS AhciWaitMemSet ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN EFI_PHYSICAL_ADDRESS Address, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT64 Delay; - BOOLEAN InfiniteWait; + UINT32 Value; + UINT64 Delay; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -273,7 +271,7 @@ AhciWaitMemSet ( // compiler from optimizing the access to the memory address // to only read once. // - Value = *(volatile UINT32 *) (UINTN) Address; + Value = *(volatile UINT32 *)(UINTN)Address; Value &= MaskValue; if (Value == TestValue) { @@ -286,7 +284,6 @@ AhciWaitMemSet ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -303,11 +300,11 @@ AhciWaitMemSet ( **/ VOID AhciClearPortStatus ( - IN UINTN AhciBar, - IN UINT8 Port + IN UINTN AhciBar, + IN UINT8 Port ) { - UINT32 Offset; + UINT32 Offset; // // Clear any error status @@ -341,12 +338,12 @@ AhciClearPortStatus ( **/ EFI_STATUS AhciEnableFisReceive ( - IN UINTN AhciBar, - IN UINT8 Port, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; + UINT32 Offset; Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; AhciOrReg (AhciBar, Offset, AHCI_PORT_CMD_FRE); @@ -369,13 +366,13 @@ AhciEnableFisReceive ( **/ EFI_STATUS AhciDisableFisReceive ( - IN UINTN AhciBar, - IN UINT8 Port, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; - UINT32 Data; + UINT32 Offset; + UINT32 Data; Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; Data = AhciReadReg (AhciBar, Offset); @@ -395,7 +392,7 @@ AhciDisableFisReceive ( return EFI_SUCCESS; } - AhciAndReg (AhciBar, Offset, (UINT32)~(AHCI_PORT_CMD_FRE)); + AhciAndReg (AhciBar, Offset, (UINT32) ~(AHCI_PORT_CMD_FRE)); return AhciWaitMmioSet ( AhciBar, @@ -423,26 +420,26 @@ AhciDisableFisReceive ( **/ VOID AhciBuildCommand ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN EFI_AHCI_COMMAND_FIS *CommandFis, - IN EFI_AHCI_COMMAND_LIST *CommandList, - IN UINT8 CommandSlotNumber, - IN OUT VOID *DataPhysicalAddr, - IN UINT32 DataLength + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN EFI_AHCI_COMMAND_FIS *CommandFis, + IN EFI_AHCI_COMMAND_LIST *CommandList, + IN UINT8 CommandSlotNumber, + IN OUT VOID *DataPhysicalAddr, + IN UINT32 DataLength ) { - EFI_AHCI_REGISTERS *AhciRegisters; - UINTN AhciBar; - UINT64 BaseAddr; - UINT32 PrdtNumber; - UINT32 PrdtIndex; - UINTN RemainedData; - UINTN MemAddr; - DATA_64 Data64; - UINT32 Offset; + EFI_AHCI_REGISTERS *AhciRegisters; + UINTN AhciBar; + UINT64 BaseAddr; + UINT32 PrdtNumber; + UINT32 PrdtIndex; + UINTN RemainedData; + UINTN MemAddr; + DATA_64 Data64; + UINT32 Offset; AhciRegisters = &Private->AhciRegisters; AhciBar = Private->MmioBase; @@ -467,11 +464,11 @@ AhciBuildCommand ( return; } - Data64.Uint64 = (UINTN) (AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * FisIndex; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * FisIndex; BaseAddr = Data64.Uint64; - ZeroMem ((VOID *)((UINTN) BaseAddr), sizeof (EFI_AHCI_RECEIVED_FIS)); + ZeroMem ((VOID *)((UINTN)BaseAddr), sizeof (EFI_AHCI_RECEIVED_FIS)); ZeroMem (AhciRegisters->AhciCmdTable, sizeof (EFI_AHCI_COMMAND_TABLE)); @@ -480,10 +477,10 @@ AhciBuildCommand ( CopyMem (&AhciRegisters->AhciCmdTable->CommandFis, CommandFis, sizeof (EFI_AHCI_COMMAND_FIS)); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; - AhciAndReg (AhciBar, Offset, (UINT32)~(AHCI_PORT_CMD_DLAE | AHCI_PORT_CMD_ATAPI)); + AhciAndReg (AhciBar, Offset, (UINT32) ~(AHCI_PORT_CMD_DLAE | AHCI_PORT_CMD_ATAPI)); - RemainedData = (UINTN) DataLength; - MemAddr = (UINTN) DataPhysicalAddr; + RemainedData = (UINTN)DataLength; + MemAddr = (UINTN)DataPhysicalAddr; CommandList->AhciCmdPrdtl = PrdtNumber; for (PrdtIndex = 0; PrdtIndex < PrdtNumber; PrdtIndex++) { @@ -493,11 +490,11 @@ AhciBuildCommand ( AhciRegisters->AhciCmdTable->PrdtTable[PrdtIndex].AhciPrdtDbc = AHCI_MAX_DATA_PER_PRDT - 1; } - Data64.Uint64 = (UINT64)MemAddr; + Data64.Uint64 = (UINT64)MemAddr; AhciRegisters->AhciCmdTable->PrdtTable[PrdtIndex].AhciPrdtDba = Data64.Uint32.Lower32; AhciRegisters->AhciCmdTable->PrdtTable[PrdtIndex].AhciPrdtDbau = Data64.Uint32.Upper32; - RemainedData -= AHCI_MAX_DATA_PER_PRDT; - MemAddr += AHCI_MAX_DATA_PER_PRDT; + RemainedData -= AHCI_MAX_DATA_PER_PRDT; + MemAddr += AHCI_MAX_DATA_PER_PRDT; } // @@ -508,12 +505,12 @@ AhciBuildCommand ( } CopyMem ( - (VOID *) ((UINTN) AhciRegisters->AhciCmdList + (UINTN) CommandSlotNumber * sizeof (EFI_AHCI_COMMAND_LIST)), + (VOID *)((UINTN)AhciRegisters->AhciCmdList + (UINTN)CommandSlotNumber * sizeof (EFI_AHCI_COMMAND_LIST)), CommandList, sizeof (EFI_AHCI_COMMAND_LIST) ); - Data64.Uint64 = (UINT64)(UINTN) AhciRegisters->AhciCmdTable; + Data64.Uint64 = (UINT64)(UINTN)AhciRegisters->AhciCmdTable; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdCtba = Data64.Uint32.Lower32; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdCtbau = Data64.Uint32.Upper32; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdPmp = PortMultiplier; @@ -530,8 +527,8 @@ AhciBuildCommand ( **/ VOID AhciBuildCommandFis ( - IN OUT EFI_AHCI_COMMAND_FIS *CmdFis, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock + IN OUT EFI_AHCI_COMMAND_FIS *CmdFis, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock ) { ZeroMem (CmdFis, sizeof (EFI_AHCI_COMMAND_FIS)); @@ -540,25 +537,25 @@ AhciBuildCommandFis ( // // Indicator it's a command // - CmdFis->AhciCFisCmdInd = 0x1; - CmdFis->AhciCFisCmd = AtaCommandBlock->AtaCommand; + CmdFis->AhciCFisCmdInd = 0x1; + CmdFis->AhciCFisCmd = AtaCommandBlock->AtaCommand; - CmdFis->AhciCFisFeature = AtaCommandBlock->AtaFeatures; - CmdFis->AhciCFisFeatureExp = AtaCommandBlock->AtaFeaturesExp; + CmdFis->AhciCFisFeature = AtaCommandBlock->AtaFeatures; + CmdFis->AhciCFisFeatureExp = AtaCommandBlock->AtaFeaturesExp; - CmdFis->AhciCFisSecNum = AtaCommandBlock->AtaSectorNumber; - CmdFis->AhciCFisSecNumExp = AtaCommandBlock->AtaSectorNumberExp; + CmdFis->AhciCFisSecNum = AtaCommandBlock->AtaSectorNumber; + CmdFis->AhciCFisSecNumExp = AtaCommandBlock->AtaSectorNumberExp; - CmdFis->AhciCFisClyLow = AtaCommandBlock->AtaCylinderLow; - CmdFis->AhciCFisClyLowExp = AtaCommandBlock->AtaCylinderLowExp; + CmdFis->AhciCFisClyLow = AtaCommandBlock->AtaCylinderLow; + CmdFis->AhciCFisClyLowExp = AtaCommandBlock->AtaCylinderLowExp; - CmdFis->AhciCFisClyHigh = AtaCommandBlock->AtaCylinderHigh; - CmdFis->AhciCFisClyHighExp = AtaCommandBlock->AtaCylinderHighExp; + CmdFis->AhciCFisClyHigh = AtaCommandBlock->AtaCylinderHigh; + CmdFis->AhciCFisClyHighExp = AtaCommandBlock->AtaCylinderHighExp; CmdFis->AhciCFisSecCount = AtaCommandBlock->AtaSectorCount; CmdFis->AhciCFisSecCountExp = AtaCommandBlock->AtaSectorCountExp; - CmdFis->AhciCFisDevHead = (UINT8) (AtaCommandBlock->AtaDeviceHead | 0xE0); + CmdFis->AhciCFisDevHead = (UINT8)(AtaCommandBlock->AtaDeviceHead | 0xE0); } /** @@ -575,13 +572,13 @@ AhciBuildCommandFis ( **/ EFI_STATUS AhciStopCommand ( - IN UINTN AhciBar, - IN UINT8 Port, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; - UINT32 Data; + UINT32 Offset; + UINT32 Data; Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; Data = AhciReadReg (AhciBar, Offset); @@ -591,7 +588,7 @@ AhciStopCommand ( } if ((Data & AHCI_PORT_CMD_ST) != 0) { - AhciAndReg (AhciBar, Offset, (UINT32)~(AHCI_PORT_CMD_ST)); + AhciAndReg (AhciBar, Offset, (UINT32) ~(AHCI_PORT_CMD_ST)); } return AhciWaitMmioSet ( @@ -618,26 +615,26 @@ AhciStopCommand ( **/ EFI_STATUS AhciStartCommand ( - IN UINTN AhciBar, - IN UINT8 Port, - IN UINT8 CommandSlot, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT8 Port, + IN UINT8 CommandSlot, + IN UINT64 Timeout ) { - UINT32 CmdSlotBit; - EFI_STATUS Status; - UINT32 PortStatus; - UINT32 StartCmd; - UINT32 PortTfd; - UINT32 Offset; - UINT32 Capability; + UINT32 CmdSlotBit; + EFI_STATUS Status; + UINT32 PortStatus; + UINT32 StartCmd; + UINT32 PortTfd; + UINT32 Offset; + UINT32 Capability; // // Collect AHCI controller information // Capability = AhciReadReg (AhciBar, AHCI_CAPABILITY_OFFSET); - CmdSlotBit = (UINT32) (1 << CommandSlot); + CmdSlotBit = (UINT32)(1 << CommandSlot); AhciClearPortStatus ( AhciBar, @@ -653,17 +650,17 @@ AhciStartCommand ( return Status; } - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; PortStatus = AhciReadReg (AhciBar, Offset); StartCmd = 0; if ((PortStatus & AHCI_PORT_CMD_ALPE) != 0) { - StartCmd = AhciReadReg (AhciBar, Offset); + StartCmd = AhciReadReg (AhciBar, Offset); StartCmd &= ~AHCI_PORT_CMD_ICC_MASK; StartCmd |= AHCI_PORT_CMD_ACTIVE; } - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; PortTfd = AhciReadReg (AhciBar, Offset); if ((PortTfd & (AHCI_PORT_TFD_BSY | AHCI_PORT_TFD_DRQ)) != 0) { @@ -689,7 +686,7 @@ AhciStartCommand ( // Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CI; AhciAndReg (AhciBar, Offset, 0); - AhciOrReg (AhciBar, Offset, CmdSlotBit); + AhciOrReg (AhciBar, Offset, CmdSlotBit); return EFI_SUCCESS; } @@ -718,40 +715,40 @@ AhciStartCommand ( **/ EFI_STATUS AhciPioTransfer ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout ) { - EFI_STATUS Status; - EDKII_IOMMU_OPERATION MapOp; - UINTN MapLength; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *MapData; - EFI_AHCI_REGISTERS *AhciRegisters; - UINTN AhciBar; - BOOLEAN InfiniteWait; - UINT32 Offset; - UINT32 OldRfisLo; - UINT32 OldRfisHi; - UINT32 OldCmdListLo; - UINT32 OldCmdListHi; - DATA_64 Data64; - UINT32 FisBaseAddr; - UINT32 Delay; - EFI_AHCI_COMMAND_FIS CFis; - EFI_AHCI_COMMAND_LIST CmdList; - UINT32 PortTfd; - UINT32 PrdCount; - BOOLEAN PioFisReceived; - BOOLEAN D2hFisReceived; + EFI_STATUS Status; + EDKII_IOMMU_OPERATION MapOp; + UINTN MapLength; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *MapData; + EFI_AHCI_REGISTERS *AhciRegisters; + UINTN AhciBar; + BOOLEAN InfiniteWait; + UINT32 Offset; + UINT32 OldRfisLo; + UINT32 OldRfisHi; + UINT32 OldCmdListLo; + UINT32 OldCmdListHi; + DATA_64 Data64; + UINT32 FisBaseAddr; + UINT32 Delay; + EFI_AHCI_COMMAND_FIS CFis; + EFI_AHCI_COMMAND_LIST CmdList; + UINT32 PortTfd; + UINT32 PrdCount; + BOOLEAN PioFisReceived; + BOOLEAN D2hFisReceived; // // Current driver implementation supports up to a maximum of AHCI_MAX_PRDT_NUMBER @@ -762,14 +759,16 @@ AhciPioTransfer ( DEBUG_ERROR, "%a: Driver only support a maximum of 0x%x PRDT entries, " "current number of data byte 0x%x is too large, maximum allowed is 0x%x.\n", - __FUNCTION__, AHCI_MAX_PRDT_NUMBER, DataCount, + __FUNCTION__, + AHCI_MAX_PRDT_NUMBER, + DataCount, AHCI_MAX_PRDT_NUMBER * AHCI_MAX_DATA_PER_PRDT )); return EFI_UNSUPPORTED; } - MapOp = Read ? EdkiiIoMmuOperationBusMasterWrite : - EdkiiIoMmuOperationBusMasterRead; + MapOp = Read ? EdkiiIoMmuOperationBusMasterWrite : + EdkiiIoMmuOperationBusMasterRead; MapLength = DataCount; Status = IoMmuMap ( MapOp, @@ -783,9 +782,9 @@ AhciPioTransfer ( return EFI_OUT_OF_RESOURCES; } - AhciRegisters = &Private->AhciRegisters; - AhciBar = Private->MmioBase; - InfiniteWait = (Timeout == 0) ? TRUE : FALSE; + AhciRegisters = &Private->AhciRegisters; + AhciBar = Private->MmioBase; + InfiniteWait = (Timeout == 0) ? TRUE : FALSE; // // Fill FIS base address register @@ -794,23 +793,23 @@ AhciPioTransfer ( OldRfisLo = AhciReadReg (AhciBar, Offset); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FBU; OldRfisHi = AhciReadReg (AhciBar, Offset); - Data64.Uint64 = (UINTN) (AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * FisIndex; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * FisIndex; Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FB; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Lower32); - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FBU; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FBU; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Upper32); // // Single task environment, we only use one command table for all port // - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLB; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLB; OldCmdListLo = AhciReadReg (AhciBar, Offset); - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLBU; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLBU; OldCmdListHi = AhciReadReg (AhciBar, Offset); - Data64.Uint64 = (UINTN) (AhciRegisters->AhciCmdList); + Data64.Uint64 = (UINTN)(AhciRegisters->AhciCmdList); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLB; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Lower32); - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLBU; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLBU; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Upper32); // @@ -854,16 +853,17 @@ AhciPioTransfer ( // Wait device sends the PIO setup fis before data transfer // Status = EFI_TIMEOUT; - Delay = (UINT32) DivU64x32 (Timeout, 1000) + 1; + Delay = (UINT32)DivU64x32 (Timeout, 1000) + 1; do { PioFisReceived = FALSE; D2hFisReceived = FALSE; - Offset = FisBaseAddr + AHCI_PIO_FIS_OFFSET; - Status = AhciCheckMemSet (Offset, AHCI_FIS_TYPE_MASK, AHCI_FIS_PIO_SETUP); + Offset = FisBaseAddr + AHCI_PIO_FIS_OFFSET; + Status = AhciCheckMemSet (Offset, AHCI_FIS_TYPE_MASK, AHCI_FIS_PIO_SETUP); if (!EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "%a: PioFisReceived.\n", __FUNCTION__)); PioFisReceived = TRUE; } + // // According to SATA 2.6 spec section 11.7, D2h FIS means an error encountered. // But Qemu and Marvel 9230 sata controller may just receive a D2h FIS from @@ -879,8 +879,8 @@ AhciPioTransfer ( } if (PioFisReceived || D2hFisReceived) { - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; - PortTfd = AhciReadReg (AhciBar, (UINT32) Offset); + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; + PortTfd = AhciReadReg (AhciBar, (UINT32)Offset); // // PxTFD will be updated if there is a D2H or SetupFIS received. // @@ -889,7 +889,7 @@ AhciPioTransfer ( break; } - PrdCount = *(volatile UINT32 *) (&(AhciRegisters->AhciCmdList[0].AhciCmdPrdbc)); + PrdCount = *(volatile UINT32 *)(&(AhciRegisters->AhciCmdList[0].AhciCmdPrdbc)); if (PrdCount == DataCount) { Status = EFI_SUCCESS; break; @@ -899,7 +899,7 @@ AhciPioTransfer ( // // Stall for 100 microseconds. // - MicroSecondDelay(100); + MicroSecondDelay (100); Delay--; if (Delay == 0) { @@ -922,8 +922,8 @@ AhciPioTransfer ( goto Exit; } - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; - PortTfd = AhciReadReg (AhciBar, (UINT32) Offset); + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; + PortTfd = AhciReadReg (AhciBar, (UINT32)Offset); if ((PortTfd & AHCI_PORT_TFD_ERR) != 0) { Status = EFI_DEVICE_ERROR; } @@ -979,25 +979,25 @@ Exit: **/ EFI_STATUS AhciNonDataTransfer ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout ) { - EFI_STATUS Status; - UINTN AhciBar; - EFI_AHCI_REGISTERS *AhciRegisters; - UINTN FisBaseAddr; - UINTN Offset; - UINT32 PortTfd; - EFI_AHCI_COMMAND_FIS CFis; - EFI_AHCI_COMMAND_LIST CmdList; - - AhciBar = Private->MmioBase; + EFI_STATUS Status; + UINTN AhciBar; + EFI_AHCI_REGISTERS *AhciRegisters; + UINTN FisBaseAddr; + UINTN Offset; + UINT32 PortTfd; + EFI_AHCI_COMMAND_FIS CFis; + EFI_AHCI_COMMAND_LIST CmdList; + + AhciBar = Private->MmioBase; AhciRegisters = &Private->AhciRegisters; // @@ -1047,8 +1047,8 @@ AhciNonDataTransfer ( goto Exit; } - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; - PortTfd = AhciReadReg (AhciBar, (UINT32) Offset); + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; + PortTfd = AhciReadReg (AhciBar, (UINT32)Offset); if ((PortTfd & AHCI_PORT_TFD_ERR) != 0) { Status = EFI_DEVICE_ERROR; } @@ -1082,13 +1082,13 @@ Exit: **/ EFI_STATUS AhciReset ( - IN UINTN AhciBar, - IN UINT64 Timeout + IN UINTN AhciBar, + IN UINT64 Timeout ) { - UINT32 Delay; - UINT32 Value; - UINT32 Capability; + UINT32 Delay; + UINT32 Value; + UINT32 Capability; // // Collect AHCI controller information @@ -1104,10 +1104,10 @@ AhciReset ( AhciOrReg (AhciBar, AHCI_GHC_OFFSET, AHCI_GHC_RESET); - Delay = (UINT32) (DivU64x32(Timeout, 1000) + 1); + Delay = (UINT32)(DivU64x32 (Timeout, 1000) + 1); do { - Value = AhciReadReg(AhciBar, AHCI_GHC_OFFSET); + Value = AhciReadReg (AhciBar, AHCI_GHC_OFFSET); if ((Value & AHCI_GHC_RESET) == 0) { return EFI_SUCCESS; } @@ -1115,7 +1115,7 @@ AhciReset ( // // Stall for 100 microseconds. // - MicroSecondDelay(100); + MicroSecondDelay (100); Delay--; } while (Delay > 0); @@ -1141,16 +1141,16 @@ AhciReset ( **/ EFI_STATUS AhciIdentify ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN ATA_IDENTIFY_DATA *Buffer + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN ATA_IDENTIFY_DATA *Buffer ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK Acb; - EFI_ATA_STATUS_BLOCK Asb; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK Acb; + EFI_ATA_STATUS_BLOCK Asb; if (Buffer == NULL) { return EFI_INVALID_PARAMETER; @@ -1178,7 +1178,6 @@ AhciIdentify ( return Status; } - /** Collect the number of bits set within a port bitmap. @@ -1189,10 +1188,10 @@ AhciIdentify ( **/ UINT8 AhciGetNumberOfPortsFromMap ( - IN UINT32 PortBitMap + IN UINT32 PortBitMap ) { - UINT8 NumberOfPorts; + UINT8 NumberOfPorts; NumberOfPorts = 0; @@ -1200,6 +1199,7 @@ AhciGetNumberOfPortsFromMap ( if ((PortBitMap & ((UINT32)BIT0)) != 0) { NumberOfPorts++; } + PortBitMap = PortBitMap >> 1; } @@ -1220,9 +1220,9 @@ AhciGetNumberOfPortsFromMap ( **/ EFI_STATUS AhciGetPortFromMap ( - IN UINT32 PortBitMap, - IN UINT8 PortIndex, - OUT UINT8 *Port + IN UINT32 PortBitMap, + IN UINT8 PortIndex, + OUT UINT8 *Port ) { if (PortIndex == 0) { @@ -1242,6 +1242,7 @@ AhciGetPortFromMap ( return EFI_SUCCESS; } } + PortBitMap = PortBitMap >> 1; *Port = *Port + 1; } @@ -1260,22 +1261,22 @@ AhciGetPortFromMap ( **/ EFI_STATUS AhciCreateTransferDescriptor ( - IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private + IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINTN AhciBar; - EFI_AHCI_REGISTERS *AhciRegisters; - EFI_PHYSICAL_ADDRESS DeviceAddress; - VOID *Base; - VOID *Mapping; - UINT32 Capability; - UINT32 PortImplementBitMap; - UINT8 MaxPortNumber; - UINT8 MaxCommandSlotNumber; - UINTN MaxRFisSize; - UINTN MaxCmdListSize; - UINTN MaxCmdTableSize; + EFI_STATUS Status; + UINTN AhciBar; + EFI_AHCI_REGISTERS *AhciRegisters; + EFI_PHYSICAL_ADDRESS DeviceAddress; + VOID *Base; + VOID *Mapping; + UINT32 Capability; + UINT32 PortImplementBitMap; + UINT8 MaxPortNumber; + UINT8 MaxCommandSlotNumber; + UINTN MaxRFisSize; + UINTN MaxCmdListSize; + UINTN MaxCmdTableSize; AhciBar = Private->MmioBase; AhciRegisters = &Private->AhciRegisters; @@ -1288,7 +1289,7 @@ AhciCreateTransferDescriptor ( // // Get the number of command slots per port supported by this HBA. // - MaxCommandSlotNumber = (UINT8) (((Capability & 0x1F00) >> 8) + 1); + MaxCommandSlotNumber = (UINT8)(((Capability & 0x1F00) >> 8) + 1); ASSERT (MaxCommandSlotNumber > 0); if (MaxCommandSlotNumber == 0) { return EFI_DEVICE_ERROR; @@ -1299,10 +1300,11 @@ AhciCreateTransferDescriptor ( // allocated for recived FIS. // PortImplementBitMap = AhciReadReg (AhciBar, AHCI_PI_OFFSET); - MaxPortNumber = (UINT8)(UINTN)(HighBitSet32(PortImplementBitMap) + 1); + MaxPortNumber = (UINT8)(UINTN)(HighBitSet32 (PortImplementBitMap) + 1); if (MaxPortNumber == 0) { return EFI_DEVICE_ERROR; } + // // Get the number of ports that actually needed to be initialized. // @@ -1312,16 +1314,17 @@ AhciCreateTransferDescriptor ( // Allocate memory for received FIS. // MaxRFisSize = MaxPortNumber * sizeof (EFI_AHCI_RECEIVED_FIS); - Status = IoMmuAllocateBuffer ( - EFI_SIZE_TO_PAGES (MaxRFisSize), - &Base, - &DeviceAddress, - &Mapping - ); + Status = IoMmuAllocateBuffer ( + EFI_SIZE_TO_PAGES (MaxRFisSize), + &Base, + &DeviceAddress, + &Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS) (UINTN) Base)); + + ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS)(UINTN)Base)); AhciRegisters->AhciRFis = Base; AhciRegisters->AhciRFisMap = Mapping; AhciRegisters->MaxRFisSize = MaxRFisSize; @@ -1333,17 +1336,18 @@ AhciCreateTransferDescriptor ( // list for each port. // MaxCmdListSize = 1 * sizeof (EFI_AHCI_COMMAND_LIST); - Status = IoMmuAllocateBuffer ( - EFI_SIZE_TO_PAGES (MaxCmdListSize), - &Base, - &DeviceAddress, - &Mapping - ); + Status = IoMmuAllocateBuffer ( + EFI_SIZE_TO_PAGES (MaxCmdListSize), + &Base, + &DeviceAddress, + &Mapping + ); if (EFI_ERROR (Status)) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS) (UINTN) Base)); + + ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS)(UINTN)Base)); AhciRegisters->AhciCmdList = Base; AhciRegisters->AhciCmdListMap = Mapping; AhciRegisters->MaxCmdListSize = MaxCmdListSize; @@ -1354,17 +1358,18 @@ AhciCreateTransferDescriptor ( // According to AHCI 1.3 spec, a PRD table can contain maximum 65535 entries. // MaxCmdTableSize = sizeof (EFI_AHCI_COMMAND_TABLE); - Status = IoMmuAllocateBuffer ( - EFI_SIZE_TO_PAGES (MaxCmdTableSize), - &Base, - &DeviceAddress, - &Mapping - ); + Status = IoMmuAllocateBuffer ( + EFI_SIZE_TO_PAGES (MaxCmdTableSize), + &Base, + &DeviceAddress, + &Mapping + ); if (EFI_ERROR (Status)) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS) (UINTN) Base)); + + ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS)(UINTN)Base)); AhciRegisters->AhciCmdTable = Base; AhciRegisters->AhciCmdTableMap = Mapping; AhciRegisters->MaxCmdTableSize = MaxCmdTableSize; @@ -1375,19 +1380,19 @@ AhciCreateTransferDescriptor ( ErrorExit: if (AhciRegisters->AhciRFisMap != NULL) { IoMmuFreeBuffer ( - EFI_SIZE_TO_PAGES (AhciRegisters->MaxRFisSize), - AhciRegisters->AhciRFis, - AhciRegisters->AhciRFisMap - ); + EFI_SIZE_TO_PAGES (AhciRegisters->MaxRFisSize), + AhciRegisters->AhciRFis, + AhciRegisters->AhciRFisMap + ); AhciRegisters->AhciRFis = NULL; } if (AhciRegisters->AhciCmdListMap != NULL) { IoMmuFreeBuffer ( - EFI_SIZE_TO_PAGES (AhciRegisters->MaxCmdListSize), - AhciRegisters->AhciCmdList, - AhciRegisters->AhciCmdListMap - ); + EFI_SIZE_TO_PAGES (AhciRegisters->MaxCmdListSize), + AhciRegisters->AhciCmdList, + AhciRegisters->AhciCmdListMap + ); AhciRegisters->AhciCmdList = NULL; } @@ -1408,12 +1413,12 @@ ErrorExit: **/ EFI_LBA GetAtapi6Capacity ( - IN ATA_IDENTIFY_DATA *IdentifyData + IN ATA_IDENTIFY_DATA *IdentifyData ) { - EFI_LBA Capacity; - EFI_LBA TmpLba; - UINTN Index; + EFI_LBA Capacity; + EFI_LBA TmpLba; + UINTN Index; if ((IdentifyData->command_set_supported_83 & BIT10) == 0) { // @@ -1430,7 +1435,7 @@ GetAtapi6Capacity ( // // Lower byte goes first: word[100] is the lowest word, word[103] is highest // - TmpLba = IdentifyData->maximum_lba_for_48bit_addressing[Index]; + TmpLba = IdentifyData->maximum_lba_for_48bit_addressing[Index]; Capacity |= LShiftU64 (TmpLba, 16 * Index); } @@ -1458,29 +1463,35 @@ GetAtapi6Capacity ( **/ EFI_STATUS IdentifyAtaDevice ( - IN OUT PEI_AHCI_ATA_DEVICE_DATA *DeviceData + IN OUT PEI_AHCI_ATA_DEVICE_DATA *DeviceData ) { - ATA_IDENTIFY_DATA *IdentifyData; - EFI_PEI_BLOCK_IO2_MEDIA *Media; - EFI_LBA Capacity; - UINT32 MaxSectorCount; - UINT16 PhyLogicSectorSupport; + ATA_IDENTIFY_DATA *IdentifyData; + EFI_PEI_BLOCK_IO2_MEDIA *Media; + EFI_LBA Capacity; + UINT32 MaxSectorCount; + UINT16 PhyLogicSectorSupport; IdentifyData = DeviceData->IdentifyData; Media = &DeviceData->Media; if ((IdentifyData->config & BIT15) != 0) { DEBUG (( - DEBUG_ERROR, "%a: Not a hard disk device on Port 0x%x PortMultiplierPort 0x%x\n", - __FUNCTION__, DeviceData->Port, DeviceData->PortMultiplier + DEBUG_ERROR, + "%a: Not a hard disk device on Port 0x%x PortMultiplierPort 0x%x\n", + __FUNCTION__, + DeviceData->Port, + DeviceData->PortMultiplier )); return EFI_UNSUPPORTED; } DEBUG (( - DEBUG_INFO, "%a: Identify Device: Port 0x%x PortMultiplierPort 0x%x\n", - __FUNCTION__, DeviceData->Port, DeviceData->PortMultiplier + DEBUG_INFO, + "%a: Identify Device: Port 0x%x PortMultiplierPort 0x%x\n", + __FUNCTION__, + DeviceData->Port, + DeviceData->PortMultiplier )); // @@ -1502,7 +1513,7 @@ IdentifyAtaDevice ( // This is a hard disk <= 120GB capacity, treat it as normal hard disk // Capacity = ((UINT32)IdentifyData->user_addressable_sectors_hi << 16) | - IdentifyData->user_addressable_sectors_lo; + IdentifyData->user_addressable_sectors_lo; DeviceData->Lba48Bit = FALSE; } @@ -1510,7 +1521,8 @@ IdentifyAtaDevice ( DEBUG ((DEBUG_ERROR, "%a: Invalid Capacity (0) for ATA device.\n", __FUNCTION__)); return EFI_UNSUPPORTED; } - Media->LastBlock = (EFI_PEI_LBA) (Capacity - 1); + + Media->LastBlock = (EFI_PEI_LBA)(Capacity - 1); Media->BlockSize = 0x200; // @@ -1518,16 +1530,18 @@ IdentifyAtaDevice ( // PhyLogicSectorSupport = IdentifyData->phy_logic_sector_support; DEBUG (( - DEBUG_INFO, "%a: PhyLogicSectorSupport = 0x%x\n", - __FUNCTION__, PhyLogicSectorSupport + DEBUG_INFO, + "%a: PhyLogicSectorSupport = 0x%x\n", + __FUNCTION__, + PhyLogicSectorSupport )); if ((PhyLogicSectorSupport & (BIT14 | BIT15)) == BIT14) { // // Check logical block size // if ((PhyLogicSectorSupport & BIT12) != 0) { - Media->BlockSize = (UINT32) (((IdentifyData->logic_sector_size_hi << 16) | - IdentifyData->logic_sector_size_lo) * sizeof (UINT16)); + Media->BlockSize = (UINT32)(((IdentifyData->logic_sector_size_hi << 16) | + IdentifyData->logic_sector_size_lo) * sizeof (UINT16)); } } @@ -1541,8 +1555,11 @@ IdentifyAtaDevice ( } DEBUG (( - DEBUG_INFO, "%a: BlockSize = 0x%x, LastBlock = 0x%lx\n", - __FUNCTION__, Media->BlockSize, Media->LastBlock + DEBUG_INFO, + "%a: BlockSize = 0x%x, LastBlock = 0x%lx\n", + __FUNCTION__, + Media->BlockSize, + Media->LastBlock )); if ((IdentifyData->trusted_computing_support & BIT0) != 0) { @@ -1583,16 +1600,16 @@ IdentifyAtaDevice ( **/ EFI_STATUS CreateNewDevice ( - IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINTN DeviceIndex, - IN UINT16 Port, - IN UINT16 PortMultiplier, - IN UINT8 FisIndex, - IN ATA_IDENTIFY_DATA *IdentifyData + IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINTN DeviceIndex, + IN UINT16 Port, + IN UINT16 PortMultiplier, + IN UINT8 FisIndex, + IN ATA_IDENTIFY_DATA *IdentifyData ) { - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - EFI_STATUS Status; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + EFI_STATUS Status; DeviceData = AllocateZeroPool (sizeof (PEI_AHCI_ATA_DEVICE_DATA)); if (DeviceData == NULL) { @@ -1622,6 +1639,7 @@ CreateNewDevice ( Private->TrustComputingDevices++; DeviceData->TrustComputingDeviceIndex = Private->TrustComputingDevices; } + Private->ActiveDevices++; InsertTailList (&Private->DeviceList, &DeviceData->Link); @@ -1644,25 +1662,25 @@ CreateNewDevice ( **/ EFI_STATUS AhciModeInitialization ( - IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private + IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINTN AhciBar; - UINT32 Capability; - UINT32 Value; - UINT8 MaxPortNumber; - UINT32 PortImplementBitMap; - UINT32 PortInitializeBitMap; - EFI_AHCI_REGISTERS *AhciRegisters; - UINT8 PortIndex; - UINT8 Port; - DATA_64 Data64; - UINT32 Data; - UINT32 Offset; - UINT32 PhyDetectDelay; - UINTN DeviceIndex; - ATA_IDENTIFY_DATA IdentifyData; + EFI_STATUS Status; + UINTN AhciBar; + UINT32 Capability; + UINT32 Value; + UINT8 MaxPortNumber; + UINT32 PortImplementBitMap; + UINT32 PortInitializeBitMap; + EFI_AHCI_REGISTERS *AhciRegisters; + UINT8 PortIndex; + UINT8 Port; + DATA_64 Data64; + UINT32 Data; + UINT32 Offset; + UINT32 PhyDetectDelay; + UINTN DeviceIndex; + ATA_IDENTIFY_DATA IdentifyData; AhciBar = Private->MmioBase; @@ -1690,7 +1708,8 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Transfer-related data allocation failed with %r.\n", - __FUNCTION__, Status + __FUNCTION__, + Status )); return EFI_OUT_OF_RESOURCES; } @@ -1698,7 +1717,7 @@ AhciModeInitialization ( // // Get the number of command slots per port supported by this HBA. // - MaxPortNumber = (UINT8) ((Capability & 0x1F) + 1); + MaxPortNumber = (UINT8)((Capability & 0x1F) + 1); // // Get the bit map of those ports exposed by this HBA. @@ -1710,7 +1729,7 @@ AhciModeInitialization ( // // Get the number of ports that actually needed to be initialized. // - MaxPortNumber = MIN (MaxPortNumber, (UINT8)(UINTN)(HighBitSet32(PortImplementBitMap) + 1)); + MaxPortNumber = MIN (MaxPortNumber, (UINT8)(UINTN)(HighBitSet32 (PortImplementBitMap) + 1)); MaxPortNumber = MIN (MaxPortNumber, AhciGetNumberOfPortsFromMap (Private->PortBitMap)); PortInitializeBitMap = Private->PortBitMap & PortImplementBitMap; @@ -1719,7 +1738,7 @@ AhciModeInitialization ( // // Enumerate ATA ports // - for (PortIndex = 1; PortIndex <= MaxPortNumber; PortIndex ++) { + for (PortIndex = 1; PortIndex <= MaxPortNumber; PortIndex++) { Status = AhciGetPortFromMap (PortInitializeBitMap, PortIndex, &Port); if (EFI_ERROR (Status)) { // @@ -1733,21 +1752,21 @@ AhciModeInitialization ( // Initialize FIS Base Address Register and Command List Base Address // Register for use. // - Data64.Uint64 = (UINTN) (AhciRegisters->AhciRFis) + + Data64.Uint64 = (UINTN)(AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * (PortIndex - 1); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FB; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Lower32); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_FBU; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Upper32); - Data64.Uint64 = (UINTN) (AhciRegisters->AhciCmdList); - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLB; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciCmdList); + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLB; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Lower32); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CLBU; AhciWriteReg (AhciBar, Offset, Data64.Uint32.Upper32); Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_CMD; - Data = AhciReadReg (AhciBar, Offset); + Data = AhciReadReg (AhciBar, Offset); if ((Data & AHCI_PORT_CMD_CPD) != 0) { AhciOrReg (AhciBar, Offset, AHCI_PORT_CMD_POD); } @@ -1777,7 +1796,7 @@ AhciModeInitialization ( // Wait no longer than 15 ms to wait the Phy to detect the presence of a device. // PhyDetectDelay = AHCI_BUS_PHY_DETECT_TIMEOUT; - Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_SSTS; + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_SSTS; do { Data = AhciReadReg (AhciBar, Offset) & AHCI_PORT_SSTS_DET_MASK; if ((Data == AHCI_PORT_SSTS_DET_PCE) || (Data == AHCI_PORT_SSTS_DET)) { @@ -1806,9 +1825,10 @@ AhciModeInitialization ( PhyDetectDelay = 16 * 1000; do { Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_SERR; - if (AhciReadReg(AhciBar, Offset) != 0) { + if (AhciReadReg (AhciBar, Offset) != 0) { AhciWriteReg (AhciBar, Offset, AhciReadReg (AhciBar, Offset)); } + Offset = AHCI_PORT_START + Port * AHCI_PORT_REG_WIDTH + AHCI_PORT_TFD; Data = AhciReadReg (AhciBar, Offset) & AHCI_PORT_TFD_MASK; @@ -1824,7 +1844,9 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Port %d device presence detected but phy not ready (TFD=0x%x).\n", - __FUNCTION__, Port, Data + __FUNCTION__, + Port, + Data )); continue; } @@ -1844,7 +1866,8 @@ AhciModeInitialization ( DEBUG (( DEBUG_ERROR, "%a: Error occurred when waiting for the first D2H register FIS - %r\n", - __FUNCTION__, Status + __FUNCTION__, + Status )); continue; } @@ -1856,6 +1879,7 @@ AhciModeInitialization ( DEBUG ((DEBUG_ERROR, "%a: AhciIdentify() failed with %r\n", __FUNCTION__, Status)); continue; } + DEBUG ((DEBUG_INFO, "%a: ATA hard disk found on Port %d.\n", __FUNCTION__, Port)); } else { continue; @@ -1898,17 +1922,17 @@ AhciModeInitialization ( **/ EFI_STATUS TransferAtaDevice ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - IN OUT VOID *Buffer, - IN EFI_LBA StartLba, - IN UINT32 TransferLength, - IN BOOLEAN IsWrite + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + IN OUT VOID *Buffer, + IN EFI_LBA StartLba, + IN UINT32 TransferLength, + IN BOOLEAN IsWrite ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - EDKII_PEI_ATA_PASS_THRU_PPI *AtaPassThru; - EFI_ATA_COMMAND_BLOCK Acb; - EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + EDKII_PEI_ATA_PASS_THRU_PPI *AtaPassThru; + EFI_ATA_COMMAND_BLOCK Acb; + EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; Private = DeviceData->Private; AtaPassThru = &Private->AtaPassThruPpi; @@ -1916,10 +1940,11 @@ TransferAtaDevice ( // // Ensure Lba48Bit and IsWrite are valid boolean values // - ASSERT ((UINTN) DeviceData->Lba48Bit < 2); - ASSERT ((UINTN) IsWrite < 2); - if (((UINTN) DeviceData->Lba48Bit >= 2) || - ((UINTN) IsWrite >= 2)) { + ASSERT ((UINTN)DeviceData->Lba48Bit < 2); + ASSERT ((UINTN)IsWrite < 2); + if (((UINTN)DeviceData->Lba48Bit >= 2) || + ((UINTN)IsWrite >= 2)) + { return EFI_INVALID_PARAMETER; } @@ -1927,21 +1952,21 @@ TransferAtaDevice ( // Prepare for ATA command block. // ZeroMem (&Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); - Acb.AtaCommand = mAtaCommands[DeviceData->Lba48Bit][IsWrite]; - Acb.AtaSectorNumber = (UINT8) StartLba; - Acb.AtaCylinderLow = (UINT8) RShiftU64 (StartLba, 8); - Acb.AtaCylinderHigh = (UINT8) RShiftU64 (StartLba, 16); - Acb.AtaDeviceHead = (UINT8) (BIT7 | BIT6 | BIT5 | - (DeviceData->PortMultiplier == 0xFFFF ? + Acb.AtaCommand = mAtaCommands[DeviceData->Lba48Bit][IsWrite]; + Acb.AtaSectorNumber = (UINT8)StartLba; + Acb.AtaCylinderLow = (UINT8)RShiftU64 (StartLba, 8); + Acb.AtaCylinderHigh = (UINT8)RShiftU64 (StartLba, 16); + Acb.AtaDeviceHead = (UINT8)(BIT7 | BIT6 | BIT5 | + (DeviceData->PortMultiplier == 0xFFFF ? 0 : (DeviceData->PortMultiplier << 4))); - Acb.AtaSectorCount = (UINT8) TransferLength; + Acb.AtaSectorCount = (UINT8)TransferLength; if (DeviceData->Lba48Bit) { - Acb.AtaSectorNumberExp = (UINT8) RShiftU64 (StartLba, 24); - Acb.AtaCylinderLowExp = (UINT8) RShiftU64 (StartLba, 32); - Acb.AtaCylinderHighExp = (UINT8) RShiftU64 (StartLba, 40); - Acb.AtaSectorCountExp = (UINT8) (TransferLength >> 8); + Acb.AtaSectorNumberExp = (UINT8)RShiftU64 (StartLba, 24); + Acb.AtaCylinderLowExp = (UINT8)RShiftU64 (StartLba, 32); + Acb.AtaCylinderHighExp = (UINT8)RShiftU64 (StartLba, 40); + Acb.AtaSectorCountExp = (UINT8)(TransferLength >> 8); } else { - Acb.AtaDeviceHead = (UINT8) (Acb.AtaDeviceHead | RShiftU64 (StartLba, 24)); + Acb.AtaDeviceHead = (UINT8)(Acb.AtaDeviceHead | RShiftU64 (StartLba, 24)); } // @@ -1952,9 +1977,10 @@ TransferAtaDevice ( Packet.OutDataBuffer = Buffer; Packet.OutTransferLength = TransferLength; } else { - Packet.InDataBuffer = Buffer; - Packet.InTransferLength = TransferLength; + Packet.InDataBuffer = Buffer; + Packet.InTransferLength = TransferLength; } + Packet.Asb = NULL; Packet.Acb = &Acb; Packet.Protocol = mAtaPassThruCmdProtocols[IsWrite]; @@ -2035,22 +2061,22 @@ TransferAtaDevice ( **/ EFI_STATUS TrustTransferAtaDevice ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - EDKII_PEI_ATA_PASS_THRU_PPI *AtaPassThru; - EFI_ATA_COMMAND_BLOCK Acb; - EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - VOID *NewBuffer; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + EDKII_PEI_ATA_PASS_THRU_PPI *AtaPassThru; + EFI_ATA_COMMAND_BLOCK Acb; + EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + VOID *NewBuffer; Private = DeviceData->Private; AtaPassThru = &Private->AtaPassThruPpi; @@ -2058,8 +2084,8 @@ TrustTransferAtaDevice ( // // Ensure IsTrustSend are valid boolean values // - ASSERT ((UINTN) IsTrustSend < 2); - if ((UINTN) IsTrustSend >= 2) { + ASSERT ((UINTN)IsTrustSend < 2); + if ((UINTN)IsTrustSend >= 2) { return EFI_INVALID_PARAMETER; } @@ -2068,22 +2094,23 @@ TrustTransferAtaDevice ( // ZeroMem (&Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); if (TransferLength == 0) { - Acb.AtaCommand = ATA_CMD_TRUST_NON_DATA; + Acb.AtaCommand = ATA_CMD_TRUST_NON_DATA; } else { - Acb.AtaCommand = mAtaTrustCommands[IsTrustSend]; + Acb.AtaCommand = mAtaTrustCommands[IsTrustSend]; } - Acb.AtaFeatures = SecurityProtocolId; - Acb.AtaSectorCount = (UINT8) (TransferLength / 512); - Acb.AtaSectorNumber = (UINT8) ((TransferLength / 512) >> 8); + + Acb.AtaFeatures = SecurityProtocolId; + Acb.AtaSectorCount = (UINT8)(TransferLength / 512); + Acb.AtaSectorNumber = (UINT8)((TransferLength / 512) >> 8); // // NOTE: ATA Spec has no explicitly definition for Security Protocol Specific layout. // Here use big endian for Cylinder register. // - Acb.AtaCylinderHigh = (UINT8) SecurityProtocolSpecificData; - Acb.AtaCylinderLow = (UINT8) (SecurityProtocolSpecificData >> 8); - Acb.AtaDeviceHead = (UINT8) (BIT7 | BIT6 | BIT5 | - (DeviceData->PortMultiplier == 0xFFFF ? - 0 : (DeviceData->PortMultiplier << 4))); + Acb.AtaCylinderHigh = (UINT8)SecurityProtocolSpecificData; + Acb.AtaCylinderLow = (UINT8)(SecurityProtocolSpecificData >> 8); + Acb.AtaDeviceHead = (UINT8)(BIT7 | BIT6 | BIT5 | + (DeviceData->PortMultiplier == 0xFFFF ? + 0 : (DeviceData->PortMultiplier << 4))); // // Prepare for ATA pass through packet. @@ -2092,14 +2119,15 @@ TrustTransferAtaDevice ( if (TransferLength == 0) { Packet.InTransferLength = 0; Packet.OutTransferLength = 0; - Packet.Protocol = EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA; + Packet.Protocol = EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA; } else if (IsTrustSend) { // // Check the alignment of the incoming buffer prior to invoking underlying // ATA PassThru PPI. // if ((AtaPassThru->Mode->IoAlign > 1) && - !IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) { + !IS_ALIGNED (Buffer, AtaPassThru->Mode->IoAlign)) + { NewBuffer = AllocateAlignedPages ( EFI_SIZE_TO_PAGES (TransferLength), AtaPassThru->Mode->IoAlign @@ -2111,18 +2139,20 @@ TrustTransferAtaDevice ( CopyMem (NewBuffer, Buffer, TransferLength); Buffer = NewBuffer; } - Packet.OutDataBuffer = Buffer; - Packet.OutTransferLength = (UINT32) TransferLength; - Packet.Protocol = mAtaPassThruCmdProtocols[IsTrustSend]; + + Packet.OutDataBuffer = Buffer; + Packet.OutTransferLength = (UINT32)TransferLength; + Packet.Protocol = mAtaPassThruCmdProtocols[IsTrustSend]; } else { - Packet.InDataBuffer = Buffer; - Packet.InTransferLength = (UINT32) TransferLength; - Packet.Protocol = mAtaPassThruCmdProtocols[IsTrustSend]; + Packet.InDataBuffer = Buffer; + Packet.InTransferLength = (UINT32)TransferLength; + Packet.Protocol = mAtaPassThruCmdProtocols[IsTrustSend]; } - Packet.Asb = NULL; - Packet.Acb = &Acb; - Packet.Timeout = Timeout; - Packet.Length = EFI_ATA_PASS_THRU_LENGTH_BYTES; + + Packet.Asb = NULL; + Packet.Acb = &Acb; + Packet.Timeout = Timeout; + Packet.Length = EFI_ATA_PASS_THRU_LENGTH_BYTES; Status = AtaPassThru->PassThru ( AtaPassThru, @@ -2135,5 +2165,6 @@ TrustTransferAtaDevice ( *TransferLengthOut = Packet.InTransferLength; } } + return Status; } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c index 31b072c118..208b7e9a36 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.c @@ -40,7 +40,6 @@ EFI_PEI_NOTIFY_DESCRIPTOR mAhciEndOfPeiNotifyListTemplate = { AhciPeimEndOfPei }; - /** Free the DMA resources allocated by an ATA AHCI controller. @@ -50,10 +49,10 @@ EFI_PEI_NOTIFY_DESCRIPTOR mAhciEndOfPeiNotifyListTemplate = { **/ VOID AhciFreeDmaResource ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_AHCI_REGISTERS *AhciRegisters; + EFI_AHCI_REGISTERS *AhciRegisters; ASSERT (Private != NULL); @@ -61,18 +60,18 @@ AhciFreeDmaResource ( if (AhciRegisters->AhciRFisMap != NULL) { IoMmuFreeBuffer ( - EFI_SIZE_TO_PAGES (AhciRegisters->MaxRFisSize), - AhciRegisters->AhciRFis, - AhciRegisters->AhciRFisMap - ); + EFI_SIZE_TO_PAGES (AhciRegisters->MaxRFisSize), + AhciRegisters->AhciRFis, + AhciRegisters->AhciRFisMap + ); } if (AhciRegisters->AhciCmdListMap != NULL) { IoMmuFreeBuffer ( - EFI_SIZE_TO_PAGES (AhciRegisters->MaxCmdListSize), - AhciRegisters->AhciCmdList, - AhciRegisters->AhciCmdListMap - ); + EFI_SIZE_TO_PAGES (AhciRegisters->MaxCmdListSize), + AhciRegisters->AhciCmdList, + AhciRegisters->AhciCmdListMap + ); } if (AhciRegisters->AhciCmdTableMap != NULL) { @@ -82,7 +81,6 @@ AhciFreeDmaResource ( AhciRegisters->AhciCmdTableMap ); } - } /** @@ -104,7 +102,7 @@ AhciPeimEndOfPei ( IN VOID *Ppi ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY (NotifyDescriptor); AhciFreeDmaResource (Private); @@ -124,20 +122,20 @@ AhciPeimEndOfPei ( EFI_STATUS EFIAPI AtaAhciPeimEntry ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - EFI_BOOT_MODE BootMode; - EDKII_ATA_AHCI_HOST_CONTROLLER_PPI *AhciHcPpi; - UINT8 Controller; - UINTN MmioBase; - UINTN DevicePathLength; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINT32 PortBitMap; - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - UINT8 NumberOfPorts; + EFI_STATUS Status; + EFI_BOOT_MODE BootMode; + EDKII_ATA_AHCI_HOST_CONTROLLER_PPI *AhciHcPpi; + UINT8 Controller; + UINTN MmioBase; + UINTN DevicePathLength; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINT32 PortBitMap; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + UINT8 NumberOfPorts; DEBUG ((DEBUG_INFO, "%a: Enters.\n", __FUNCTION__)); @@ -157,7 +155,7 @@ AtaAhciPeimEntry ( &gEdkiiPeiAtaAhciHostControllerPpiGuid, 0, NULL, - (VOID **) &AhciHcPpi + (VOID **)&AhciHcPpi ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Failed to locate AtaAhciHostControllerPpi.\n", __FUNCTION__)); @@ -187,8 +185,10 @@ AtaAhciPeimEntry ( ); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_ERROR, "%a: Fail to allocate get the device path for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Fail to allocate get the device path for Controller %d.\n", + __FUNCTION__, + Controller )); return Status; } @@ -199,8 +199,10 @@ AtaAhciPeimEntry ( Status = AhciIsHcDevicePathValid (DevicePath, DevicePathLength); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_ERROR, "%a: The device path is invalid for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: The device path is invalid for Controller %d.\n", + __FUNCTION__, + Controller )); Controller++; continue; @@ -231,8 +233,10 @@ AtaAhciPeimEntry ( Private = AllocateZeroPool (sizeof (PEI_AHCI_CONTROLLER_PRIVATE_DATA)); if (Private == NULL) { DEBUG (( - DEBUG_ERROR, "%a: Fail to allocate private data for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Fail to allocate private data for Controller %d.\n", + __FUNCTION__, + Controller )); return EFI_OUT_OF_RESOURCES; } @@ -260,8 +264,8 @@ AtaAhciPeimEntry ( continue; } - Private->AtaPassThruMode.Attributes = EFI_ATA_PASS_THRU_ATTRIBUTES_PHYSICAL | - EFI_ATA_PASS_THRU_ATTRIBUTES_LOGICAL; + Private->AtaPassThruMode.Attributes = EFI_ATA_PASS_THRU_ATTRIBUTES_PHYSICAL | + EFI_ATA_PASS_THRU_ATTRIBUTES_LOGICAL; Private->AtaPassThruMode.IoAlign = sizeof (UINTN); Private->AtaPassThruPpi.Revision = EDKII_PEI_ATA_PASS_THRU_PPI_REVISION; Private->AtaPassThruPpi.Mode = &Private->AtaPassThruMode; @@ -274,18 +278,18 @@ AtaAhciPeimEntry ( &mAhciAtaPassThruPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->AtaPassThruPpiList.Ppi = &Private->AtaPassThruPpi; + Private->AtaPassThruPpiList.Ppi = &Private->AtaPassThruPpi; PeiServicesInstallPpi (&Private->AtaPassThruPpiList); - Private->BlkIoPpi.GetNumberOfBlockDevices = AhciBlockIoGetDeviceNo; - Private->BlkIoPpi.GetBlockDeviceMediaInfo = AhciBlockIoGetMediaInfo; - Private->BlkIoPpi.ReadBlocks = AhciBlockIoReadBlocks; + Private->BlkIoPpi.GetNumberOfBlockDevices = AhciBlockIoGetDeviceNo; + Private->BlkIoPpi.GetBlockDeviceMediaInfo = AhciBlockIoGetMediaInfo; + Private->BlkIoPpi.ReadBlocks = AhciBlockIoReadBlocks; CopyMem ( &Private->BlkIoPpiList, &mAhciBlkIoPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->BlkIoPpiList.Ppi = &Private->BlkIoPpi; + Private->BlkIoPpiList.Ppi = &Private->BlkIoPpi; PeiServicesInstallPpi (&Private->BlkIoPpiList); Private->BlkIo2Ppi.Revision = EFI_PEI_RECOVERY_BLOCK_IO2_PPI_REVISION; @@ -297,14 +301,15 @@ AtaAhciPeimEntry ( &mAhciBlkIo2PpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->BlkIo2PpiList.Ppi = &Private->BlkIo2Ppi; + Private->BlkIo2PpiList.Ppi = &Private->BlkIo2Ppi; PeiServicesInstallPpi (&Private->BlkIo2PpiList); if (Private->TrustComputingDevices != 0) { DEBUG (( DEBUG_INFO, "%a: Security Security Command PPI will be produced for Controller %d.\n", - __FUNCTION__, Controller + __FUNCTION__, + Controller )); Private->StorageSecurityPpi.Revision = EDKII_STORAGE_SECURITY_PPI_REVISION; Private->StorageSecurityPpi.GetNumberofDevices = AhciStorageSecurityGetDeviceNo; @@ -316,7 +321,7 @@ AtaAhciPeimEntry ( &mAhciStorageSecurityPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->StorageSecurityPpiList.Ppi = &Private->StorageSecurityPpi; + Private->StorageSecurityPpiList.Ppi = &Private->StorageSecurityPpi; PeiServicesInstallPpi (&Private->StorageSecurityPpiList); } @@ -325,11 +330,13 @@ AtaAhciPeimEntry ( &mAhciEndOfPeiNotifyListTemplate, sizeof (EFI_PEI_NOTIFY_DESCRIPTOR) ); - PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); + PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); DEBUG (( - DEBUG_INFO, "%a: Controller %d has been successfully initialized.\n", - __FUNCTION__, Controller + DEBUG_INFO, + "%a: Controller %d has been successfully initialized.\n", + __FUNCTION__, + Controller )); Controller++; } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h index 2be78076be..43ad4639bd 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPei.h @@ -33,7 +33,7 @@ // // Structure forward declarations // -typedef struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA PEI_AHCI_CONTROLLER_PRIVATE_DATA; +typedef struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA PEI_AHCI_CONTROLLER_PRIVATE_DATA; #include "AhciPeiPassThru.h" #include "AhciPeiBlockIo.h" @@ -46,107 +46,107 @@ typedef struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA PEI_AHCI_CONTROLLER_PRIVATE_DA // Refer SATA1.0a spec section 5.2, the Phy detection time should be less than 10ms. // The value is in millisecond units. Add a bit of margin for robustness. // -#define AHCI_BUS_PHY_DETECT_TIMEOUT 15 +#define AHCI_BUS_PHY_DETECT_TIMEOUT 15 // // Refer SATA1.0a spec, the bus reset time should be less than 1s. // The value is in 100ns units. // -#define AHCI_PEI_RESET_TIMEOUT 10000000 +#define AHCI_PEI_RESET_TIMEOUT 10000000 // // Time out Value for ATA pass through protocol, in 100ns units. // -#define ATA_TIMEOUT 30000000 +#define ATA_TIMEOUT 30000000 // // Maximal number of Physical Region Descriptor Table entries supported. // -#define AHCI_MAX_PRDT_NUMBER 8 +#define AHCI_MAX_PRDT_NUMBER 8 -#define AHCI_CAPABILITY_OFFSET 0x0000 -#define AHCI_CAP_SAM BIT18 -#define AHCI_CAP_SSS BIT27 +#define AHCI_CAPABILITY_OFFSET 0x0000 +#define AHCI_CAP_SAM BIT18 +#define AHCI_CAP_SSS BIT27 -#define AHCI_GHC_OFFSET 0x0004 -#define AHCI_GHC_RESET BIT0 -#define AHCI_GHC_ENABLE BIT31 +#define AHCI_GHC_OFFSET 0x0004 +#define AHCI_GHC_RESET BIT0 +#define AHCI_GHC_ENABLE BIT31 -#define AHCI_IS_OFFSET 0x0008 -#define AHCI_PI_OFFSET 0x000C +#define AHCI_IS_OFFSET 0x0008 +#define AHCI_PI_OFFSET 0x000C -#define AHCI_MAX_PORTS 32 +#define AHCI_MAX_PORTS 32 typedef struct { - UINT32 Lower32; - UINT32 Upper32; + UINT32 Lower32; + UINT32 Upper32; } DATA_32; typedef union { - DATA_32 Uint32; - UINT64 Uint64; + DATA_32 Uint32; + UINT64 Uint64; } DATA_64; -#define AHCI_ATAPI_SIG_MASK 0xFFFF0000 -#define AHCI_ATA_DEVICE_SIG 0x00000000 +#define AHCI_ATAPI_SIG_MASK 0xFFFF0000 +#define AHCI_ATA_DEVICE_SIG 0x00000000 // // Each PRDT entry can point to a memory block up to 4M byte // -#define AHCI_MAX_DATA_PER_PRDT 0x400000 +#define AHCI_MAX_DATA_PER_PRDT 0x400000 -#define AHCI_FIS_REGISTER_H2D 0x27 //Register FIS - Host to Device -#define AHCI_FIS_REGISTER_H2D_LENGTH 20 -#define AHCI_FIS_REGISTER_D2H 0x34 //Register FIS - Device to Host -#define AHCI_FIS_PIO_SETUP 0x5F //PIO Setup FIS - Device to Host +#define AHCI_FIS_REGISTER_H2D 0x27 // Register FIS - Host to Device +#define AHCI_FIS_REGISTER_H2D_LENGTH 20 +#define AHCI_FIS_REGISTER_D2H 0x34 // Register FIS - Device to Host +#define AHCI_FIS_PIO_SETUP 0x5F // PIO Setup FIS - Device to Host -#define AHCI_D2H_FIS_OFFSET 0x40 -#define AHCI_PIO_FIS_OFFSET 0x20 -#define AHCI_FIS_TYPE_MASK 0xFF +#define AHCI_D2H_FIS_OFFSET 0x40 +#define AHCI_PIO_FIS_OFFSET 0x20 +#define AHCI_FIS_TYPE_MASK 0xFF // // Port register // -#define AHCI_PORT_START 0x0100 -#define AHCI_PORT_REG_WIDTH 0x0080 -#define AHCI_PORT_CLB 0x0000 -#define AHCI_PORT_CLBU 0x0004 -#define AHCI_PORT_FB 0x0008 -#define AHCI_PORT_FBU 0x000C -#define AHCI_PORT_IS 0x0010 -#define AHCI_PORT_IE 0x0014 -#define AHCI_PORT_CMD 0x0018 -#define AHCI_PORT_CMD_ST BIT0 -#define AHCI_PORT_CMD_SUD BIT1 -#define AHCI_PORT_CMD_POD BIT2 -#define AHCI_PORT_CMD_CLO BIT3 -#define AHCI_PORT_CMD_FRE BIT4 -#define AHCI_PORT_CMD_FR BIT14 -#define AHCI_PORT_CMD_CR BIT15 -#define AHCI_PORT_CMD_CPD BIT20 -#define AHCI_PORT_CMD_ATAPI BIT24 -#define AHCI_PORT_CMD_DLAE BIT25 -#define AHCI_PORT_CMD_ALPE BIT26 -#define AHCI_PORT_CMD_ACTIVE (1 << 28) -#define AHCI_PORT_CMD_ICC_MASK (BIT28 | BIT29 | BIT30 | BIT31) - -#define AHCI_PORT_TFD 0x0020 -#define AHCI_PORT_TFD_ERR BIT0 -#define AHCI_PORT_TFD_DRQ BIT3 -#define AHCI_PORT_TFD_BSY BIT7 -#define AHCI_PORT_TFD_MASK (BIT7 | BIT3 | BIT0) - -#define AHCI_PORT_SIG 0x0024 -#define AHCI_PORT_SSTS 0x0028 -#define AHCI_PORT_SSTS_DET_MASK 0x000F -#define AHCI_PORT_SSTS_DET 0x0001 -#define AHCI_PORT_SSTS_DET_PCE 0x0003 - -#define AHCI_PORT_SCTL 0x002C -#define AHCI_PORT_SCTL_IPM_INIT 0x0300 - -#define AHCI_PORT_SERR 0x0030 -#define AHCI_PORT_CI 0x0038 - -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) -#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) +#define AHCI_PORT_START 0x0100 +#define AHCI_PORT_REG_WIDTH 0x0080 +#define AHCI_PORT_CLB 0x0000 +#define AHCI_PORT_CLBU 0x0004 +#define AHCI_PORT_FB 0x0008 +#define AHCI_PORT_FBU 0x000C +#define AHCI_PORT_IS 0x0010 +#define AHCI_PORT_IE 0x0014 +#define AHCI_PORT_CMD 0x0018 +#define AHCI_PORT_CMD_ST BIT0 +#define AHCI_PORT_CMD_SUD BIT1 +#define AHCI_PORT_CMD_POD BIT2 +#define AHCI_PORT_CMD_CLO BIT3 +#define AHCI_PORT_CMD_FRE BIT4 +#define AHCI_PORT_CMD_FR BIT14 +#define AHCI_PORT_CMD_CR BIT15 +#define AHCI_PORT_CMD_CPD BIT20 +#define AHCI_PORT_CMD_ATAPI BIT24 +#define AHCI_PORT_CMD_DLAE BIT25 +#define AHCI_PORT_CMD_ALPE BIT26 +#define AHCI_PORT_CMD_ACTIVE (1 << 28) +#define AHCI_PORT_CMD_ICC_MASK (BIT28 | BIT29 | BIT30 | BIT31) + +#define AHCI_PORT_TFD 0x0020 +#define AHCI_PORT_TFD_ERR BIT0 +#define AHCI_PORT_TFD_DRQ BIT3 +#define AHCI_PORT_TFD_BSY BIT7 +#define AHCI_PORT_TFD_MASK (BIT7 | BIT3 | BIT0) + +#define AHCI_PORT_SIG 0x0024 +#define AHCI_PORT_SSTS 0x0028 +#define AHCI_PORT_SSTS_DET_MASK 0x000F +#define AHCI_PORT_SSTS_DET 0x0001 +#define AHCI_PORT_SSTS_DET_PCE 0x0003 + +#define AHCI_PORT_SCTL 0x002C +#define AHCI_PORT_SCTL_IPM_INIT 0x0300 + +#define AHCI_PORT_SERR 0x0030 +#define AHCI_PORT_CI 0x0038 + +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define TIMER_PERIOD_SECONDS(Seconds) MultU64x32((UINT64)(Seconds), 10000000) #pragma pack(1) @@ -170,19 +170,19 @@ typedef struct { // The entry Data structure is listed at the following. // typedef struct { - UINT32 AhciCmdCfl:5; //Command FIS Length - UINT32 AhciCmdA:1; //ATAPI - UINT32 AhciCmdW:1; //Write - UINT32 AhciCmdP:1; //Prefetchable - UINT32 AhciCmdR:1; //Reset - UINT32 AhciCmdB:1; //BIST - UINT32 AhciCmdC:1; //Clear Busy upon R_OK - UINT32 AhciCmdRsvd:1; - UINT32 AhciCmdPmp:4; //Port Multiplier Port - UINT32 AhciCmdPrdtl:16; //Physical Region Descriptor Table Length - UINT32 AhciCmdPrdbc; //Physical Region Descriptor Byte Count - UINT32 AhciCmdCtba; //Command Table Descriptor Base Address - UINT32 AhciCmdCtbau; //Command Table Descriptor Base Address Upper 32-BITs + UINT32 AhciCmdCfl : 5; // Command FIS Length + UINT32 AhciCmdA : 1; // ATAPI + UINT32 AhciCmdW : 1; // Write + UINT32 AhciCmdP : 1; // Prefetchable + UINT32 AhciCmdR : 1; // Reset + UINT32 AhciCmdB : 1; // BIST + UINT32 AhciCmdC : 1; // Clear Busy upon R_OK + UINT32 AhciCmdRsvd : 1; + UINT32 AhciCmdPmp : 4; // Port Multiplier Port + UINT32 AhciCmdPrdtl : 16; // Physical Region Descriptor Table Length + UINT32 AhciCmdPrdbc; // Physical Region Descriptor Byte Count + UINT32 AhciCmdCtba; // Command Table Descriptor Base Address + UINT32 AhciCmdCtbau; // Command Table Descriptor Base Address Upper 32-BITs UINT32 AhciCmdRsvd1[4]; } EFI_AHCI_COMMAND_LIST; @@ -192,28 +192,28 @@ typedef struct { // specified in the Serial ATA Revision 2.6 specification. // typedef struct { - UINT8 AhciCFisType; - UINT8 AhciCFisPmNum:4; - UINT8 AhciCFisRsvd:1; - UINT8 AhciCFisRsvd1:1; - UINT8 AhciCFisRsvd2:1; - UINT8 AhciCFisCmdInd:1; - UINT8 AhciCFisCmd; - UINT8 AhciCFisFeature; - UINT8 AhciCFisSecNum; - UINT8 AhciCFisClyLow; - UINT8 AhciCFisClyHigh; - UINT8 AhciCFisDevHead; - UINT8 AhciCFisSecNumExp; - UINT8 AhciCFisClyLowExp; - UINT8 AhciCFisClyHighExp; - UINT8 AhciCFisFeatureExp; - UINT8 AhciCFisSecCount; - UINT8 AhciCFisSecCountExp; - UINT8 AhciCFisRsvd3; - UINT8 AhciCFisControl; - UINT8 AhciCFisRsvd4[4]; - UINT8 AhciCFisRsvd5[44]; + UINT8 AhciCFisType; + UINT8 AhciCFisPmNum : 4; + UINT8 AhciCFisRsvd : 1; + UINT8 AhciCFisRsvd1 : 1; + UINT8 AhciCFisRsvd2 : 1; + UINT8 AhciCFisCmdInd : 1; + UINT8 AhciCFisCmd; + UINT8 AhciCFisFeature; + UINT8 AhciCFisSecNum; + UINT8 AhciCFisClyLow; + UINT8 AhciCFisClyHigh; + UINT8 AhciCFisDevHead; + UINT8 AhciCFisSecNumExp; + UINT8 AhciCFisClyLowExp; + UINT8 AhciCFisClyHighExp; + UINT8 AhciCFisFeatureExp; + UINT8 AhciCFisSecCount; + UINT8 AhciCFisSecCountExp; + UINT8 AhciCFisRsvd3; + UINT8 AhciCFisControl; + UINT8 AhciCFisRsvd4[4]; + UINT8 AhciCFisRsvd5[44]; } EFI_AHCI_COMMAND_FIS; // @@ -230,12 +230,12 @@ typedef struct { // list entry for this command slot. // typedef struct { - UINT32 AhciPrdtDba; //Data Base Address - UINT32 AhciPrdtDbau; //Data Base Address Upper 32-BITs + UINT32 AhciPrdtDba; // Data Base Address + UINT32 AhciPrdtDbau; // Data Base Address Upper 32-BITs UINT32 AhciPrdtRsvd; - UINT32 AhciPrdtDbc:22; //Data Byte Count - UINT32 AhciPrdtRsvd1:9; - UINT32 AhciPrdtIoc:1; //Interrupt on Completion + UINT32 AhciPrdtDbc : 22; // Data Byte Count + UINT32 AhciPrdtRsvd1 : 9; + UINT32 AhciPrdtIoc : 1; // Interrupt on Completion } EFI_AHCI_COMMAND_PRDT; // @@ -268,7 +268,7 @@ typedef struct { // // Unique signature for AHCI ATA device information structure. // -#define AHCI_PEI_ATA_DEVICE_DATA_SIGNATURE SIGNATURE_32 ('A', 'P', 'A', 'D') +#define AHCI_PEI_ATA_DEVICE_DATA_SIGNATURE SIGNATURE_32 ('A', 'P', 'A', 'D') // // AHCI mode device information structure. @@ -301,7 +301,7 @@ typedef struct { // // Unique signature for private data structure. // -#define AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('A','P','C','P') +#define AHCI_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('A','P','C','P') // // ATA AHCI controller private data structure. @@ -348,7 +348,7 @@ struct _PEI_AHCI_CONTROLLER_PRIVATE_DATA { // // Global variables // -extern UINT32 mMaxTransferBlockNumber[2]; +extern UINT32 mMaxTransferBlockNumber[2]; // // Internal functions @@ -394,9 +394,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** @@ -420,11 +420,11 @@ IoMmuFreeBuffer ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -438,7 +438,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -470,7 +470,7 @@ AhciPeimEndOfPei ( **/ UINT8 AhciGetNumberOfPortsFromMap ( - IN UINT32 PortBitMap + IN UINT32 PortBitMap ); /** @@ -497,16 +497,16 @@ AhciGetNumberOfPortsFromMap ( **/ EFI_STATUS AhciPioTransfer ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout ); /** @@ -529,13 +529,13 @@ AhciPioTransfer ( **/ EFI_STATUS AhciNonDataTransfer ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT8 FisIndex, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT8 FisIndex, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout ); /** @@ -554,7 +554,7 @@ AhciNonDataTransfer ( **/ EFI_STATUS AhciModeInitialization ( - IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private + IN OUT PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private ); /** @@ -576,11 +576,11 @@ AhciModeInitialization ( **/ EFI_STATUS TransferAtaDevice ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - IN OUT VOID *Buffer, - IN EFI_LBA StartLba, - IN UINT32 TransferLength, - IN BOOLEAN IsWrite + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + IN OUT VOID *Buffer, + IN EFI_LBA StartLba, + IN UINT32 TransferLength, + IN BOOLEAN IsWrite ); /** @@ -621,14 +621,14 @@ TransferAtaDevice ( **/ EFI_STATUS TrustTransferAtaDevice ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ); /** @@ -662,9 +662,9 @@ NextDevicePathNode ( **/ EFI_STATUS GetDevicePathInstanceSize ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINTN *InstanceSize, - OUT BOOLEAN *EntireDevicePathEnd + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINTN *InstanceSize, + OUT BOOLEAN *EntireDevicePathEnd ); /** @@ -680,8 +680,8 @@ GetDevicePathInstanceSize ( **/ EFI_STATUS AhciIsHcDevicePathValid ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN UINTN DevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN UINTN DevicePathLength ); /** @@ -702,11 +702,11 @@ AhciIsHcDevicePathValid ( **/ EFI_STATUS AhciBuildDevicePath ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -723,9 +723,9 @@ AhciBuildDevicePath ( **/ UINT8 AhciS3GetEumeratePorts ( - IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, - IN UINTN HcDevicePathLength, - OUT UINT32 *PortBitMap + IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, + IN UINTN HcDevicePathLength, + OUT UINT32 *PortBitMap ); #endif diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c index e7c7a39539..c5d1f3fffb 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.c @@ -23,12 +23,12 @@ **/ PEI_AHCI_ATA_DEVICE_DATA * SearchDeviceByIndex ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINTN DeviceIndex + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINTN DeviceIndex ) { - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - LIST_ENTRY *Node; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + LIST_ENTRY *Node; if ((DeviceIndex == 0) || (DeviceIndex > Private->ActiveDevices)) { return NULL; @@ -66,26 +66,26 @@ SearchDeviceByIndex ( **/ EFI_STATUS AccessAtaDevice ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - IN OUT UINT8 *Buffer, - IN EFI_LBA StartLba, - IN UINTN NumberOfBlocks + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + IN OUT UINT8 *Buffer, + IN EFI_LBA StartLba, + IN UINTN NumberOfBlocks ) { - EFI_STATUS Status; - UINTN MaxTransferBlockNumber; - UINTN TransferBlockNumber; - UINTN BlockSize; + EFI_STATUS Status; + UINTN MaxTransferBlockNumber; + UINTN TransferBlockNumber; + UINTN BlockSize; // // Ensure Lba48Bit is a valid boolean value // - ASSERT ((UINTN) DeviceData->Lba48Bit < 2); - if ((UINTN) DeviceData->Lba48Bit >= 2) { + ASSERT ((UINTN)DeviceData->Lba48Bit < 2); + if ((UINTN)DeviceData->Lba48Bit >= 2) { return EFI_INVALID_PARAMETER; } - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; MaxTransferBlockNumber = mMaxTransferBlockNumber[DeviceData->Lba48Bit]; BlockSize = DeviceData->Media.BlockSize; @@ -93,20 +93,24 @@ AccessAtaDevice ( if (NumberOfBlocks > MaxTransferBlockNumber) { TransferBlockNumber = MaxTransferBlockNumber; NumberOfBlocks -= MaxTransferBlockNumber; - } else { + } else { TransferBlockNumber = NumberOfBlocks; NumberOfBlocks = 0; } + DEBUG (( - DEBUG_BLKIO, "%a: Blocking AccessAtaDevice, TransferBlockNumber = %x; StartLba = %x\n", - __FUNCTION__, TransferBlockNumber, StartLba + DEBUG_BLKIO, + "%a: Blocking AccessAtaDevice, TransferBlockNumber = %x; StartLba = %x\n", + __FUNCTION__, + TransferBlockNumber, + StartLba )); Status = TransferAtaDevice ( DeviceData, Buffer, StartLba, - (UINT32) TransferBlockNumber, + (UINT32)TransferBlockNumber, FALSE // Read ); if (EFI_ERROR (Status)) { @@ -134,15 +138,15 @@ AccessAtaDevice ( **/ EFI_STATUS AhciRead ( - IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, - OUT VOID *Buffer, - IN EFI_LBA StartLba, - IN UINTN BufferSize + IN PEI_AHCI_ATA_DEVICE_DATA *DeviceData, + OUT VOID *Buffer, + IN EFI_LBA StartLba, + IN UINTN BufferSize ) { - EFI_STATUS Status; - UINTN BlockSize; - UINTN NumberOfBlocks; + EFI_STATUS Status; + UINTN BlockSize; + UINTN NumberOfBlocks; // // Check parameters. @@ -163,7 +167,8 @@ AhciRead ( if (StartLba > DeviceData->Media.LastBlock) { return EFI_INVALID_PARAMETER; } - NumberOfBlocks = BufferSize / BlockSize; + + NumberOfBlocks = BufferSize / BlockSize; if (NumberOfBlocks - 1 > DeviceData->Media.LastBlock - StartLba) { return EFI_INVALID_PARAMETER; } @@ -176,7 +181,6 @@ AhciRead ( return Status; } - /** Gets the count of block I/O devices that one specific block driver detects. @@ -201,13 +205,13 @@ AhciBlockIoGetDeviceNo ( OUT UINTN *NumberBlockDevices ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberBlockDevices == NULL) { + if ((This == NULL) || (NumberBlockDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO (This); + Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO (This); *NumberBlockDevices = Private->ActiveDevices; return EFI_SUCCESS; @@ -263,10 +267,10 @@ AhciBlockIoGetMediaInfo ( OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } @@ -276,9 +280,9 @@ AhciBlockIoGetMediaInfo ( return EFI_NOT_FOUND; } - MediaInfo->DeviceType = (EFI_PEI_BLOCK_DEVICE_TYPE) EDKII_PEI_BLOCK_DEVICE_TYPE_ATA_HARD_DISK; + MediaInfo->DeviceType = (EFI_PEI_BLOCK_DEVICE_TYPE)EDKII_PEI_BLOCK_DEVICE_TYPE_ATA_HARD_DISK; MediaInfo->MediaPresent = TRUE; - MediaInfo->LastBlock = (UINTN) DeviceData->Media.LastBlock; + MediaInfo->LastBlock = (UINTN)DeviceData->Media.LastBlock; MediaInfo->BlockSize = DeviceData->Media.BlockSize; return EFI_SUCCESS; @@ -329,8 +333,8 @@ AhciBlockIoReadBlocks ( OUT VOID *Buffer ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; if (This == NULL) { return EFI_INVALID_PARAMETER; @@ -369,13 +373,13 @@ AhciBlockIoGetDeviceNo2 ( OUT UINTN *NumberBlockDevices ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberBlockDevices == NULL) { + if ((This == NULL) || (NumberBlockDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2 (This); + Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2 (This); *NumberBlockDevices = Private->ActiveDevices; return EFI_SUCCESS; @@ -431,10 +435,10 @@ AhciBlockIoGetMediaInfo2 ( OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } @@ -498,7 +502,7 @@ AhciBlockIoReadBlocks2 ( OUT VOID *Buffer ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; if (This == NULL) { return EFI_INVALID_PARAMETER; diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.h index 5896ae5acf..451a7cc936 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiBlockIo.h @@ -14,7 +14,7 @@ // // ATA hard disk device for EFI_PEI_BLOCK_DEVICE_TYPE // -#define EDKII_PEI_BLOCK_DEVICE_TYPE_ATA_HARD_DISK 8 +#define EDKII_PEI_BLOCK_DEVICE_TYPE_ATA_HARD_DISK 8 /** Gets the count of block I/O devices that one specific block driver detects. diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c index 191b78c885..d5ed93dc4f 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.c @@ -25,20 +25,21 @@ **/ PEI_AHCI_ATA_DEVICE_DATA * SearchDeviceByPort ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT16 Port, - IN UINT16 PortMultiplierPort + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT16 Port, + IN UINT16 PortMultiplierPort ) { - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - LIST_ENTRY *Node; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + LIST_ENTRY *Node; Node = GetFirstNode (&Private->DeviceList); while (!IsNull (&Private->DeviceList, Node)) { DeviceData = AHCI_PEI_ATA_DEVICE_INFO_FROM_THIS (Node); if ((DeviceData->Port == Port) && - (DeviceData->PortMultiplier == PortMultiplierPort)) { + (DeviceData->PortMultiplier == PortMultiplierPort)) + { return DeviceData; } @@ -82,21 +83,21 @@ SearchDeviceByPort ( **/ EFI_STATUS AhciPassThruExecute ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN UINT8 FisIndex, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN UINT8 FisIndex, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet ) { - EFI_STATUS Status; + EFI_STATUS Status; switch (Packet->Protocol) { case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA: Status = AhciNonDataTransfer ( Private, - (UINT8) Port, - (UINT8) PortMultiplierPort, + (UINT8)Port, + (UINT8)PortMultiplierPort, FisIndex, Packet->Acb, Packet->Asb, @@ -106,8 +107,8 @@ AhciPassThruExecute ( case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN: Status = AhciPioTransfer ( Private, - (UINT8) Port, - (UINT8) PortMultiplierPort, + (UINT8)Port, + (UINT8)PortMultiplierPort, FisIndex, TRUE, Packet->Acb, @@ -120,8 +121,8 @@ AhciPassThruExecute ( case EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_OUT: Status = AhciPioTransfer ( Private, - (UINT8) Port, - (UINT8) PortMultiplierPort, + (UINT8)Port, + (UINT8)PortMultiplierPort, FisIndex, FALSE, Packet->Acb, @@ -176,19 +177,19 @@ AhciPassThruExecute ( EFI_STATUS EFIAPI AhciAtaPassThruPassThru ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet ) { - UINT32 IoAlign; - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - UINT32 MaxSectorCount; - UINT32 BlockSize; + UINT32 IoAlign; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + UINT32 MaxSectorCount; + UINT32 BlockSize; - if (This == NULL || Packet == NULL) { + if ((This == NULL) || (Packet == NULL)) { return EFI_INVALID_PARAMETER; } @@ -205,7 +206,7 @@ AhciAtaPassThruPassThru ( return EFI_INVALID_PARAMETER; } - Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_PASS_THRU (This); + Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_PASS_THRU (This); DeviceData = SearchDeviceByPort (Private, Port, PortMultiplierPort); if (DeviceData == NULL) { return EFI_NOT_FOUND; @@ -218,7 +219,8 @@ AhciAtaPassThruPassThru ( // Convert the transfer length from sector count to byte. // if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) && - (Packet->InTransferLength != 0)) { + (Packet->InTransferLength != 0)) + { Packet->InTransferLength = Packet->InTransferLength * BlockSize; } @@ -226,7 +228,8 @@ AhciAtaPassThruPassThru ( // Convert the transfer length from sector count to byte. // if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) && - (Packet->OutTransferLength != 0)) { + (Packet->OutTransferLength != 0)) + { Packet->OutTransferLength = Packet->OutTransferLength * BlockSize; } @@ -236,7 +239,8 @@ AhciAtaPassThruPassThru ( // command, then no data is transferred and EFI_BAD_BUFFER_SIZE is returned. // if (((Packet->InTransferLength != 0) && (Packet->InTransferLength > MaxSectorCount * BlockSize)) || - ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) { + ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) + { return EFI_BAD_BUFFER_SIZE; } @@ -284,15 +288,15 @@ AhciAtaPassThruPassThru ( EFI_STATUS EFIAPI AhciAtaPassThruGetNextPort ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN OUT UINT16 *Port + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN OUT UINT16 *Port ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - LIST_ENTRY *Node; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + LIST_ENTRY *Node; - if (This == NULL || Port == NULL) { + if ((This == NULL) || (Port == NULL)) { return EFI_INVALID_PARAMETER; } @@ -318,7 +322,7 @@ AhciAtaPassThruGetNextPort ( while (!IsNull (&Private->DeviceList, Node)) { DeviceData = AHCI_PEI_ATA_DEVICE_INFO_FROM_THIS (Node); - if (DeviceData->Port > *Port){ + if (DeviceData->Port > *Port) { *Port = DeviceData->Port; goto Exit; } @@ -393,16 +397,16 @@ Exit: EFI_STATUS EFIAPI AhciAtaPassThruGetNextDevice ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN UINT16 Port, - IN OUT UINT16 *PortMultiplierPort + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN UINT16 Port, + IN OUT UINT16 *PortMultiplierPort ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - LIST_ENTRY *Node; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + LIST_ENTRY *Node; - if (This == NULL || PortMultiplierPort == NULL) { + if ((This == NULL) || (PortMultiplierPort == NULL)) { return EFI_INVALID_PARAMETER; } @@ -425,7 +429,8 @@ AhciAtaPassThruGetNextDevice ( DeviceData = AHCI_PEI_ATA_DEVICE_INFO_FROM_THIS (Node); if ((DeviceData->Port == Port) && - (DeviceData->PortMultiplier > *PortMultiplierPort)){ + (DeviceData->PortMultiplier > *PortMultiplierPort)) + { *PortMultiplierPort = DeviceData->PortMultiplier; goto Exit; } @@ -444,7 +449,7 @@ AhciAtaPassThruGetNextDevice ( while (!IsNull (&Private->DeviceList, Node)) { DeviceData = AHCI_PEI_ATA_DEVICE_INFO_FROM_THIS (Node); - if (DeviceData->Port == Port){ + if (DeviceData->Port == Port) { *PortMultiplierPort = DeviceData->PortMultiplier; goto Exit; } @@ -490,14 +495,14 @@ Exit: EFI_STATUS EFIAPI AhciAtaPassThruGetDevicePath ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || DevicePathLength == NULL || DevicePath == NULL) { + if ((This == NULL) || (DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.h index 94395aade4..de61916ba2 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiPassThru.h @@ -49,10 +49,10 @@ EFI_STATUS EFIAPI AhciAtaPassThruPassThru ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet ); /** @@ -90,8 +90,8 @@ AhciAtaPassThruPassThru ( EFI_STATUS EFIAPI AhciAtaPassThruGetNextPort ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN OUT UINT16 *Port + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN OUT UINT16 *Port ); /** @@ -144,9 +144,9 @@ AhciAtaPassThruGetNextPort ( EFI_STATUS EFIAPI AhciAtaPassThruGetNextDevice ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - IN UINT16 Port, - IN OUT UINT16 *PortMultiplierPort + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + IN UINT16 Port, + IN OUT UINT16 *PortMultiplierPort ); /** @@ -169,9 +169,9 @@ AhciAtaPassThruGetNextDevice ( EFI_STATUS EFIAPI AhciAtaPassThruGetDevicePath ( - IN EDKII_PEI_ATA_PASS_THRU_PPI *This, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_ATA_PASS_THRU_PPI *This, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); #endif diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c index bf0489fa6b..42e4203a22 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiS3.c @@ -28,19 +28,19 @@ **/ UINT8 AhciS3GetEumeratePorts ( - IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, - IN UINTN HcDevicePathLength, - OUT UINT32 *PortBitMap + IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, + IN UINTN HcDevicePathLength, + OUT UINT32 *PortBitMap ) { - EFI_STATUS Status; - UINT8 DummyData; - UINTN S3InitDevicesLength; - EFI_DEVICE_PATH_PROTOCOL *S3InitDevices; - EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; - UINTN DevicePathInstLength; - BOOLEAN EntireEnd; - SATA_DEVICE_PATH *SataDeviceNode; + EFI_STATUS Status; + UINT8 DummyData; + UINTN S3InitDevicesLength; + EFI_DEVICE_PATH_PROTOCOL *S3InitDevices; + EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; + UINTN DevicePathInstLength; + BOOLEAN EntireEnd; + SATA_DEVICE_PATH *SataDeviceNode; *PortBitMap = 0; @@ -51,7 +51,7 @@ AhciS3GetEumeratePorts ( S3InitDevices = NULL; S3InitDevicesLength = sizeof (DummyData); EntireEnd = FALSE; - Status = RestoreLockBox (&gS3StorageDeviceInitListGuid, &DummyData, &S3InitDevicesLength); + Status = RestoreLockBox (&gS3StorageDeviceInitListGuid, &DummyData, &S3InitDevicesLength); if (Status != EFI_BUFFER_TOO_SMALL) { return 0; } else { @@ -87,7 +87,7 @@ AhciS3GetEumeratePorts ( } DevicePathInst = S3InitDevices; - S3InitDevices = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN) S3InitDevices + DevicePathInstLength); + S3InitDevices = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)S3InitDevices + DevicePathInstLength); if (HcDevicePathLength >= DevicePathInstLength) { continue; @@ -101,25 +101,30 @@ AhciS3GetEumeratePorts ( DevicePathInst, HcDevicePath, HcDevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL) - ) == 0) { + ) == 0) + { // // Get the port number. // while (DevicePathInst->Type != END_DEVICE_PATH_TYPE) { if ((DevicePathInst->Type == MESSAGING_DEVICE_PATH) && - (DevicePathInst->SubType == MSG_SATA_DP)) { - SataDeviceNode = (SATA_DEVICE_PATH *) DevicePathInst; + (DevicePathInst->SubType == MSG_SATA_DP)) + { + SataDeviceNode = (SATA_DEVICE_PATH *)DevicePathInst; // // For now, the driver only support upto AHCI_MAX_PORTS ports and // devices directly connected to a HBA. // if ((SataDeviceNode->HBAPortNumber >= AHCI_MAX_PORTS) || - (SataDeviceNode->PortMultiplierPortNumber != 0xFFFF)) { + (SataDeviceNode->PortMultiplierPortNumber != 0xFFFF)) + { break; } + *PortBitMap |= (UINT32)BIT0 << SataDeviceNode->HBAPortNumber; break; } + DevicePathInst = NextDevicePathNode (DevicePathInst); } } diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.c b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.c index 1bc25a7888..40e042082c 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.c @@ -24,12 +24,12 @@ **/ PEI_AHCI_ATA_DEVICE_DATA * SearchTrustComputingDeviceByIndex ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINTN TrustComputingDeviceIndex + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINTN TrustComputingDeviceIndex ) { - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - LIST_ENTRY *Node; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + LIST_ENTRY *Node; Node = GetFirstNode (&Private->DeviceList); while (!IsNull (&Private->DeviceList, Node)) { @@ -58,17 +58,17 @@ SearchTrustComputingDeviceByIndex ( EFI_STATUS EFIAPI AhciStorageSecurityGetDeviceNo ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - OUT UINTN *NumberofDevices + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + OUT UINTN *NumberofDevices ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberofDevices == NULL) { + if ((This == NULL) || (NumberofDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_STROAGE_SECURITY (This); + Private = GET_AHCI_PEIM_HC_PRIVATE_DATA_FROM_THIS_STROAGE_SECURITY (This); *NumberofDevices = Private->TrustComputingDevices; return EFI_SUCCESS; @@ -102,17 +102,17 @@ AhciStorageSecurityGetDeviceNo ( EFI_STATUS EFIAPI AhciStorageSecurityGetDevicePath ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - IN UINTN DeviceIndex, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + IN UINTN DeviceIndex, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; - EFI_STATUS Status; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + EFI_STATUS Status; - if (This == NULL || DevicePathLength == NULL || DevicePath == NULL) { + if ((This == NULL) || (DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } @@ -229,18 +229,18 @@ AhciStorageSecurityGetDevicePath ( EFI_STATUS EFIAPI AhciStorageSecurityReceiveData ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - IN UINTN DeviceIndex, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + IN UINTN DeviceIndex, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; if ((PayloadBuffer == NULL) || (PayloadTransferSize == NULL) || (PayloadBufferSize == 0)) { return EFI_INVALID_PARAMETER; @@ -349,8 +349,8 @@ AhciStorageSecuritySendData ( IN VOID *PayloadBuffer ) { - PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; - PEI_AHCI_ATA_DEVICE_DATA *DeviceData; + PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private; + PEI_AHCI_ATA_DEVICE_DATA *DeviceData; if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) { return EFI_INVALID_PARAMETER; diff --git a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.h b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.h index 905cdb88a7..a13533ea57 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.h +++ b/MdeModulePkg/Bus/Ata/AhciPei/AhciPeiStorageSecurity.h @@ -24,8 +24,8 @@ EFI_STATUS EFIAPI AhciStorageSecurityGetDeviceNo ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - OUT UINTN *NumberofDevices + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + OUT UINTN *NumberofDevices ); /** @@ -56,10 +56,10 @@ AhciStorageSecurityGetDeviceNo ( EFI_STATUS EFIAPI AhciStorageSecurityGetDevicePath ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - IN UINTN DeviceIndex, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + IN UINTN DeviceIndex, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -151,14 +151,14 @@ AhciStorageSecurityGetDevicePath ( EFI_STATUS EFIAPI AhciStorageSecurityReceiveData ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - IN UINTN DeviceIndex, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + IN UINTN DeviceIndex, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ); /** diff --git a/MdeModulePkg/Bus/Ata/AhciPei/DevicePath.c b/MdeModulePkg/Bus/Ata/AhciPei/DevicePath.c index 65d6fcb32a..81f8743d40 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/DevicePath.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/DevicePath.c @@ -17,8 +17,8 @@ SATA_DEVICE_PATH mAhciSataDevicePathNodeTemplate = { MESSAGING_DEVICE_PATH, MSG_SATA_DP, { - (UINT8) (sizeof (SATA_DEVICE_PATH)), - (UINT8) ((sizeof (SATA_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (SATA_DEVICE_PATH)), + (UINT8)((sizeof (SATA_DEVICE_PATH)) >> 8) } }, 0x0, // HBAPortNumber @@ -33,8 +33,8 @@ EFI_DEVICE_PATH_PROTOCOL mAhciEndDevicePathNodeTemplate = { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL)), - (UINT8) ((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) + (UINT8)(sizeof (EFI_DEVICE_PATH_PROTOCOL)), + (UINT8)((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) } }; @@ -79,7 +79,7 @@ NextDevicePathNode ( ) { ASSERT (Node != NULL); - return (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)(Node) + DevicePathNodeLength(Node)); + return (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)(Node) + DevicePathNodeLength (Node)); } /** @@ -97,14 +97,14 @@ NextDevicePathNode ( **/ EFI_STATUS GetDevicePathInstanceSize ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINTN *InstanceSize, - OUT BOOLEAN *EntireDevicePathEnd + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINTN *InstanceSize, + OUT BOOLEAN *EntireDevicePathEnd ) { - EFI_DEVICE_PATH_PROTOCOL *Walker; + EFI_DEVICE_PATH_PROTOCOL *Walker; - if (DevicePath == NULL || InstanceSize == NULL || EntireDevicePathEnd == NULL) { + if ((DevicePath == NULL) || (InstanceSize == NULL) || (EntireDevicePathEnd == NULL)) { return EFI_INVALID_PARAMETER; } @@ -130,7 +130,7 @@ GetDevicePathInstanceSize ( // // Compute the size of the device path instance // - *InstanceSize = ((UINTN) Walker - (UINTN) (DevicePath)) + sizeof (EFI_DEVICE_PATH_PROTOCOL); + *InstanceSize = ((UINTN)Walker - (UINTN)(DevicePath)) + sizeof (EFI_DEVICE_PATH_PROTOCOL); return EFI_SUCCESS; } @@ -148,12 +148,12 @@ GetDevicePathInstanceSize ( **/ EFI_STATUS AhciIsHcDevicePathValid ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN UINTN DevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN UINTN DevicePathLength ) { - EFI_DEVICE_PATH_PROTOCOL *Start; - UINTN Size; + EFI_DEVICE_PATH_PROTOCOL *Start; + UINTN Size; if (DevicePath == NULL) { return EFI_INVALID_PARAMETER; @@ -168,22 +168,24 @@ AhciIsHcDevicePathValid ( Start = DevicePath; while (!(DevicePath->Type == END_DEVICE_PATH_TYPE && - DevicePath->SubType == END_ENTIRE_DEVICE_PATH_SUBTYPE)) { + DevicePath->SubType == END_ENTIRE_DEVICE_PATH_SUBTYPE)) + { DevicePath = NextDevicePathNode (DevicePath); // // Prevent overflow and invalid zero in the 'Length' field of a device path // node. // - if ((UINTN) DevicePath <= (UINTN) Start) { + if ((UINTN)DevicePath <= (UINTN)Start) { return EFI_INVALID_PARAMETER; } // // Prevent touching memory beyond given DevicePathLength. // - if ((UINTN) DevicePath - (UINTN) Start > - DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL)) { + if ((UINTN)DevicePath - (UINTN)Start > + DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL)) + { return EFI_INVALID_PARAMETER; } } @@ -191,7 +193,7 @@ AhciIsHcDevicePathValid ( // // Check if the device path and its size match each other. // - Size = ((UINTN) DevicePath - (UINTN) Start) + sizeof (EFI_DEVICE_PATH_PROTOCOL); + Size = ((UINTN)DevicePath - (UINTN)Start) + sizeof (EFI_DEVICE_PATH_PROTOCOL); if (Size != DevicePathLength) { return EFI_INVALID_PARAMETER; } @@ -217,17 +219,17 @@ AhciIsHcDevicePathValid ( **/ EFI_STATUS AhciBuildDevicePath ( - IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN PEI_AHCI_CONTROLLER_PRIVATE_DATA *Private, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - EFI_DEVICE_PATH_PROTOCOL *DevicePathWalker; - SATA_DEVICE_PATH *SataDeviceNode; + EFI_DEVICE_PATH_PROTOCOL *DevicePathWalker; + SATA_DEVICE_PATH *SataDeviceNode; - if (DevicePathLength == NULL || DevicePath == NULL) { + if ((DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } @@ -251,8 +253,8 @@ AhciBuildDevicePath ( // // Construct the SATA device node // - DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *) ((UINT8 *)DevicePathWalker + - (Private->DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL))); + DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)DevicePathWalker + + (Private->DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL))); CopyMem ( DevicePathWalker, &mAhciSataDevicePathNodeTemplate, @@ -265,8 +267,8 @@ AhciBuildDevicePath ( // // Construct the end device node // - DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *) ((UINT8 *)DevicePathWalker + - sizeof (SATA_DEVICE_PATH)); + DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)DevicePathWalker + + sizeof (SATA_DEVICE_PATH)); CopyMem ( DevicePathWalker, &mAhciEndDevicePathNodeTemplate, diff --git a/MdeModulePkg/Bus/Ata/AhciPei/DmaMem.c b/MdeModulePkg/Bus/Ata/AhciPei/DmaMem.c index 3a506d8c2c..c4c08988d5 100644 --- a/MdeModulePkg/Bus/Ata/AhciPei/DmaMem.c +++ b/MdeModulePkg/Bus/Ata/AhciPei/DmaMem.c @@ -20,15 +20,15 @@ GetIoMmu ( VOID ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = NULL; Status = PeiServicesLocatePpi ( &gEdkiiIoMmuPpiGuid, 0, NULL, - (VOID **) &IoMmu + (VOID **)&IoMmu ); if (!EFI_ERROR (Status) && (IoMmu != NULL)) { return IoMmu; @@ -58,48 +58,50 @@ GetIoMmu ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { - EFI_STATUS Status; - UINT64 Attribute; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + UINT64 Attribute; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); if (IoMmu != NULL) { Status = IoMmu->Map ( - IoMmu, - Operation, - HostAddress, - NumberOfBytes, - DeviceAddress, - Mapping - ); + IoMmu, + Operation, + HostAddress, + NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -110,9 +112,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -127,11 +130,11 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); @@ -141,6 +144,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -175,7 +179,7 @@ IoMmuAllocateBuffer ( EFI_PHYSICAL_ADDRESS HostPhyAddress; EDKII_IOMMU_PPI *IoMmu; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; IoMmu = GetIoMmu (); @@ -192,18 +196,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = IoMmu->Map ( - IoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = IoMmu->Map ( + IoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -221,10 +226,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -242,13 +249,13 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); @@ -259,5 +266,6 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c index aec7d0cfbe..a240be940d 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.c @@ -25,7 +25,7 @@ AhciReadReg ( IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; ASSERT (PciIo != NULL); @@ -35,7 +35,7 @@ AhciReadReg ( PciIo, EfiPciIoWidthUint32, EFI_AHCI_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); @@ -65,12 +65,12 @@ AhciWriteReg ( PciIo, EfiPciIoWidthUint32, EFI_AHCI_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); - return ; + return; } /** @@ -89,11 +89,11 @@ AhciAndReg ( IN UINT32 AndData ) { - UINT32 Data; + UINT32 Data; ASSERT (PciIo != NULL); - Data = AhciReadReg (PciIo, Offset); + Data = AhciReadReg (PciIo, Offset); Data &= AndData; @@ -116,11 +116,11 @@ AhciOrReg ( IN UINT32 OrData ) { - UINT32 Data; + UINT32 Data; ASSERT (PciIo != NULL); - Data = AhciReadReg (PciIo, Offset); + Data = AhciReadReg (PciIo, Offset); Data |= OrData; @@ -143,16 +143,16 @@ AhciOrReg ( EFI_STATUS EFIAPI AhciWaitMmioSet ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINTN Offset, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINTN Offset, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT64 Delay; - BOOLEAN InfiniteWait; + UINT32 Value; + UINT64 Delay; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -166,7 +166,7 @@ AhciWaitMmioSet ( // // Access PCI MMIO space to see if the value is the tested one. // - Value = AhciReadReg (PciIo, (UINT32) Offset) & MaskValue; + Value = AhciReadReg (PciIo, (UINT32)Offset) & MaskValue; if (Value == TestValue) { return EFI_SUCCESS; @@ -178,7 +178,6 @@ AhciWaitMmioSet ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -199,15 +198,15 @@ AhciWaitMmioSet ( EFI_STATUS EFIAPI AhciWaitMemSet ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN EFI_PHYSICAL_ADDRESS Address, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT64 Delay; - BOOLEAN InfiniteWait; + UINT32 Value; + UINT64 Delay; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -226,7 +225,7 @@ AhciWaitMemSet ( // compiler from optimizing the access to the memory address // to only read once. // - Value = *(volatile UINT32 *) (UINTN) Address; + Value = *(volatile UINT32 *)(UINTN)Address; Value &= MaskValue; if (Value == TestValue) { @@ -239,7 +238,6 @@ AhciWaitMemSet ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -258,14 +256,14 @@ AhciWaitMemSet ( EFI_STATUS EFIAPI AhciCheckMemSet ( - IN UINTN Address, - IN UINT32 MaskValue, - IN UINT32 TestValue + IN UINTN Address, + IN UINT32 MaskValue, + IN UINT32 TestValue ) { - UINT32 Value; + UINT32 Value; - Value = *(volatile UINT32 *) Address; + Value = *(volatile UINT32 *)Address; Value &= MaskValue; if (Value == TestValue) { @@ -275,7 +273,6 @@ AhciCheckMemSet ( return EFI_NOT_READY; } - /** Clear the port interrupt and error status. It will also clear @@ -288,11 +285,11 @@ AhciCheckMemSet ( VOID EFIAPI AhciClearPortStatus ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port ) { - UINT32 Offset; + UINT32 Offset; // // Clear any error status @@ -325,16 +322,16 @@ AhciClearPortStatus ( VOID EFIAPI AhciDumpPortStatus ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - UINTN Offset; - UINT32 Data; - UINTN FisBaseAddr; - EFI_STATUS Status; + UINTN Offset; + UINT32 Data; + UINTN FisBaseAddr; + EFI_STATUS Status; ASSERT (PciIo != NULL); @@ -358,7 +355,7 @@ AhciDumpPortStatus ( Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; Data = AhciReadReg (PciIo, (UINT32)Offset); - AtaStatusBlock->AtaStatus = (UINT8)Data; + AtaStatusBlock->AtaStatus = (UINT8)Data; if ((AtaStatusBlock->AtaStatus & BIT0) != 0) { AtaStatusBlock->AtaError = (UINT8)(Data >> 8); } @@ -366,7 +363,6 @@ AhciDumpPortStatus ( } } - /** Enable the FIS running for giving port. @@ -382,12 +378,12 @@ AhciDumpPortStatus ( EFI_STATUS EFIAPI AhciEnableFisReceive ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; + UINT32 Offset; Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; AhciOrReg (PciIo, Offset, EFI_AHCI_PORT_CMD_FRE); @@ -411,13 +407,13 @@ AhciEnableFisReceive ( EFI_STATUS EFIAPI AhciDisableFisReceive ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; - UINT32 Data; + UINT32 Offset; + UINT32 Data; Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; Data = AhciReadReg (PciIo, Offset); @@ -436,7 +432,7 @@ AhciDisableFisReceive ( return EFI_SUCCESS; } - AhciAndReg (PciIo, Offset, (UINT32)~(EFI_AHCI_PORT_CMD_FRE)); + AhciAndReg (PciIo, Offset, (UINT32) ~(EFI_AHCI_PORT_CMD_FRE)); return AhciWaitMmioSet ( PciIo, @@ -447,8 +443,6 @@ AhciDisableFisReceive ( ); } - - /** Build the command list, command table and prepare the fis receiver. @@ -468,26 +462,26 @@ AhciDisableFisReceive ( VOID EFIAPI AhciBuildCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_COMMAND_FIS *CommandFis, - IN EFI_AHCI_COMMAND_LIST *CommandList, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN UINT8 CommandSlotNumber, - IN OUT VOID *DataPhysicalAddr, - IN UINT32 DataLength + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_COMMAND_FIS *CommandFis, + IN EFI_AHCI_COMMAND_LIST *CommandList, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN UINT8 CommandSlotNumber, + IN OUT VOID *DataPhysicalAddr, + IN UINT32 DataLength ) { - UINT64 BaseAddr; - UINT32 PrdtNumber; - UINT32 PrdtIndex; - UINTN RemainedData; - UINTN MemAddr; - DATA_64 Data64; - UINT32 Offset; + UINT64 BaseAddr; + UINT32 PrdtNumber; + UINT32 PrdtIndex; + UINTN RemainedData; + UINTN MemAddr; + DATA_64 Data64; + UINT32 Offset; // // Filling the PRDT @@ -501,11 +495,11 @@ AhciBuildCommand ( // ASSERT (PrdtNumber <= 65535); - Data64.Uint64 = (UINTN) (AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * Port; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciRFis) + sizeof (EFI_AHCI_RECEIVED_FIS) * Port; BaseAddr = Data64.Uint64; - ZeroMem ((VOID *)((UINTN) BaseAddr), sizeof (EFI_AHCI_RECEIVED_FIS)); + ZeroMem ((VOID *)((UINTN)BaseAddr), sizeof (EFI_AHCI_RECEIVED_FIS)); ZeroMem (AhciRegisters->AhciCommandTable, sizeof (EFI_AHCI_COMMAND_TABLE)); @@ -526,11 +520,11 @@ AhciBuildCommand ( AhciOrReg (PciIo, Offset, (EFI_AHCI_PORT_CMD_DLAE | EFI_AHCI_PORT_CMD_ATAPI)); } else { - AhciAndReg (PciIo, Offset, (UINT32)~(EFI_AHCI_PORT_CMD_DLAE | EFI_AHCI_PORT_CMD_ATAPI)); + AhciAndReg (PciIo, Offset, (UINT32) ~(EFI_AHCI_PORT_CMD_DLAE | EFI_AHCI_PORT_CMD_ATAPI)); } - RemainedData = (UINTN) DataLength; - MemAddr = (UINTN) DataPhysicalAddr; + RemainedData = (UINTN)DataLength; + MemAddr = (UINTN)DataPhysicalAddr; CommandList->AhciCmdPrdtl = PrdtNumber; for (PrdtIndex = 0; PrdtIndex < PrdtNumber; PrdtIndex++) { @@ -540,11 +534,11 @@ AhciBuildCommand ( AhciRegisters->AhciCommandTable->PrdtTable[PrdtIndex].AhciPrdtDbc = EFI_AHCI_MAX_DATA_PER_PRDT - 1; } - Data64.Uint64 = (UINT64)MemAddr; + Data64.Uint64 = (UINT64)MemAddr; AhciRegisters->AhciCommandTable->PrdtTable[PrdtIndex].AhciPrdtDba = Data64.Uint32.Lower32; AhciRegisters->AhciCommandTable->PrdtTable[PrdtIndex].AhciPrdtDbau = Data64.Uint32.Upper32; - RemainedData -= EFI_AHCI_MAX_DATA_PER_PRDT; - MemAddr += EFI_AHCI_MAX_DATA_PER_PRDT; + RemainedData -= EFI_AHCI_MAX_DATA_PER_PRDT; + MemAddr += EFI_AHCI_MAX_DATA_PER_PRDT; } // @@ -555,16 +549,15 @@ AhciBuildCommand ( } CopyMem ( - (VOID *) ((UINTN) AhciRegisters->AhciCmdList + (UINTN) CommandSlotNumber * sizeof (EFI_AHCI_COMMAND_LIST)), + (VOID *)((UINTN)AhciRegisters->AhciCmdList + (UINTN)CommandSlotNumber * sizeof (EFI_AHCI_COMMAND_LIST)), CommandList, sizeof (EFI_AHCI_COMMAND_LIST) ); - Data64.Uint64 = (UINT64)(UINTN) AhciRegisters->AhciCommandTablePciAddr; + Data64.Uint64 = (UINT64)(UINTN)AhciRegisters->AhciCommandTablePciAddr; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdCtba = Data64.Uint32.Lower32; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdCtbau = Data64.Uint32.Upper32; AhciRegisters->AhciCmdList[CommandSlotNumber].AhciCmdPmp = PortMultiplier; - } /** @@ -577,8 +570,8 @@ AhciBuildCommand ( VOID EFIAPI AhciBuildCommandFis ( - IN OUT EFI_AHCI_COMMAND_FIS *CmdFis, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock + IN OUT EFI_AHCI_COMMAND_FIS *CmdFis, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock ) { ZeroMem (CmdFis, sizeof (EFI_AHCI_COMMAND_FIS)); @@ -587,25 +580,25 @@ AhciBuildCommandFis ( // // Indicator it's a command // - CmdFis->AhciCFisCmdInd = 0x1; - CmdFis->AhciCFisCmd = AtaCommandBlock->AtaCommand; + CmdFis->AhciCFisCmdInd = 0x1; + CmdFis->AhciCFisCmd = AtaCommandBlock->AtaCommand; - CmdFis->AhciCFisFeature = AtaCommandBlock->AtaFeatures; - CmdFis->AhciCFisFeatureExp = AtaCommandBlock->AtaFeaturesExp; + CmdFis->AhciCFisFeature = AtaCommandBlock->AtaFeatures; + CmdFis->AhciCFisFeatureExp = AtaCommandBlock->AtaFeaturesExp; - CmdFis->AhciCFisSecNum = AtaCommandBlock->AtaSectorNumber; - CmdFis->AhciCFisSecNumExp = AtaCommandBlock->AtaSectorNumberExp; + CmdFis->AhciCFisSecNum = AtaCommandBlock->AtaSectorNumber; + CmdFis->AhciCFisSecNumExp = AtaCommandBlock->AtaSectorNumberExp; - CmdFis->AhciCFisClyLow = AtaCommandBlock->AtaCylinderLow; - CmdFis->AhciCFisClyLowExp = AtaCommandBlock->AtaCylinderLowExp; + CmdFis->AhciCFisClyLow = AtaCommandBlock->AtaCylinderLow; + CmdFis->AhciCFisClyLowExp = AtaCommandBlock->AtaCylinderLowExp; - CmdFis->AhciCFisClyHigh = AtaCommandBlock->AtaCylinderHigh; - CmdFis->AhciCFisClyHighExp = AtaCommandBlock->AtaCylinderHighExp; + CmdFis->AhciCFisClyHigh = AtaCommandBlock->AtaCylinderHigh; + CmdFis->AhciCFisClyHighExp = AtaCommandBlock->AtaCylinderHighExp; CmdFis->AhciCFisSecCount = AtaCommandBlock->AtaSectorCount; CmdFis->AhciCFisSecCountExp = AtaCommandBlock->AtaSectorCountExp; - CmdFis->AhciCFisDevHead = (UINT8) (AtaCommandBlock->AtaDeviceHead | 0xE0); + CmdFis->AhciCFisDevHead = (UINT8)(AtaCommandBlock->AtaDeviceHead | 0xE0); } /** @@ -621,11 +614,11 @@ EFI_STATUS AhciWaitDeviceReady ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN UINT8 Port - ) + ) { - UINT32 PhyDetectDelay; - UINT32 Data; - UINT32 Offset; + UINT32 PhyDetectDelay; + UINT32 Data; + UINT32 Offset; // // According to SATA1.0a spec section 5.2, we need to wait for PxTFD.BSY and PxTFD.DRQ @@ -634,9 +627,10 @@ AhciWaitDeviceReady ( PhyDetectDelay = 16 * 1000; do { Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_SERR; - if (AhciReadReg(PciIo, Offset) != 0) { - AhciWriteReg (PciIo, Offset, AhciReadReg(PciIo, Offset)); + if (AhciReadReg (PciIo, Offset) != 0) { + AhciWriteReg (PciIo, Offset, AhciReadReg (PciIo, Offset)); } + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; Data = AhciReadReg (PciIo, Offset) & EFI_AHCI_PORT_TFD_MASK; @@ -656,7 +650,6 @@ AhciWaitDeviceReady ( } } - /** Reset the SATA port. Algorithm follows AHCI spec 1.3.1 section 10.4.2 @@ -681,7 +674,7 @@ AhciResetPort ( // SW is required to keep DET set to 0x1 at least for 1 milisecond to ensure that // at least one COMRESET signal is sent. // - MicroSecondDelay(1000); + MicroSecondDelay (1000); AhciAndReg (PciIo, Offset, ~(UINT32)EFI_AHCI_PORT_SSTS_DET_MASK); Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_SSTS; @@ -715,7 +708,7 @@ AhciRecoverPortError ( UINT32 PortTfd; EFI_STATUS Status; - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_IS; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_IS; PortInterrupt = AhciReadReg (PciIo, Offset); if ((PortInterrupt & EFI_AHCI_PORT_IS_FATAL_ERROR_MASK) == 0) { // @@ -738,7 +731,7 @@ AhciRecoverPortError ( // If TFD.BSY or TFD.DRQ is still set it means that drive is hung and software has // to reset it before sending any additional commands. // - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; PortTfd = AhciReadReg (PciIo, Offset); if ((PortTfd & (EFI_AHCI_PORT_TFD_BSY | EFI_AHCI_PORT_TFD_DRQ)) != 0) { Status = AhciResetPort (PciIo, Port); @@ -768,16 +761,17 @@ AhciCheckFisReceived ( IN SATA_FIS_TYPE FisType ) { - UINT32 Offset; - UINT32 PortInterrupt; - UINT32 PortTfd; + UINT32 Offset; + UINT32 PortInterrupt; + UINT32 PortTfd; - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_IS; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_IS; PortInterrupt = AhciReadReg (PciIo, Offset); if ((PortInterrupt & EFI_AHCI_PORT_IS_ERROR_MASK) != 0) { DEBUG ((DEBUG_ERROR, "AHCI: Error interrupt reported PxIS: %X\n", PortInterrupt)); return EFI_DEVICE_ERROR; } + // // For PIO setup FIS - According to SATA 2.6 spec section 11.7, D2h FIS means an error encountered. // But Qemu and Marvel 9230 sata controller may just receive a D2h FIS from device @@ -786,10 +780,11 @@ AhciCheckFisReceived ( // By this way, we can know if there is a real error happened. // if (((FisType == SataFisD2H) && ((PortInterrupt & EFI_AHCI_PORT_IS_DHRS) != 0)) || - ((FisType == SataFisPioSetup) && (PortInterrupt & (EFI_AHCI_PORT_IS_PSS | EFI_AHCI_PORT_IS_DHRS)) != 0) || - ((FisType == SataFisDmaSetup) && (PortInterrupt & (EFI_AHCI_PORT_IS_DSS | EFI_AHCI_PORT_IS_DHRS)) != 0)) { - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; - PortTfd = AhciReadReg (PciIo, (UINT32) Offset); + ((FisType == SataFisPioSetup) && ((PortInterrupt & (EFI_AHCI_PORT_IS_PSS | EFI_AHCI_PORT_IS_DHRS)) != 0)) || + ((FisType == SataFisDmaSetup) && ((PortInterrupt & (EFI_AHCI_PORT_IS_DSS | EFI_AHCI_PORT_IS_DHRS)) != 0))) + { + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; + PortTfd = AhciReadReg (PciIo, (UINT32)Offset); if ((PortTfd & EFI_AHCI_PORT_TFD_ERR) != 0) { return EFI_DEVICE_ERROR; } else { @@ -836,6 +831,7 @@ AhciWaitUntilFisReceived ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 100 microseconds. // @@ -929,30 +925,30 @@ AhciPrintStatusBlock ( EFI_STATUS EFIAPI AhciPioTransfer ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *Map; - UINTN MapLength; - EFI_PCI_IO_PROTOCOL_OPERATION Flag; - EFI_AHCI_COMMAND_FIS CFis; - EFI_AHCI_COMMAND_LIST CmdList; - UINT32 PrdCount; - UINT32 Retry; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *Map; + UINTN MapLength; + EFI_PCI_IO_PROTOCOL_OPERATION Flag; + EFI_AHCI_COMMAND_FIS CFis; + EFI_AHCI_COMMAND_LIST CmdList; + UINT32 PrdCount; + UINT32 Retry; if (Read) { Flag = EfiPciIoOperationBusMasterWrite; @@ -964,14 +960,14 @@ AhciPioTransfer ( // construct command list and command table with pci bus address // MapLength = DataCount; - Status = PciIo->Map ( - PciIo, - Flag, - MemoryAddr, - &MapLength, - &PhyAddr, - &Map - ); + Status = PciIo->Map ( + PciIo, + Flag, + MemoryAddr, + &MapLength, + &PhyAddr, + &Map + ); if (EFI_ERROR (Status) || (DataCount != MapLength)) { return EFI_BAD_BUFFER_SIZE; @@ -1005,11 +1001,11 @@ AhciPioTransfer ( DEBUG ((DEBUG_VERBOSE, "Starting command for PIO transfer:\n")); AhciPrintCommandBlock (AtaCommandBlock, DEBUG_VERBOSE); Status = AhciStartCommand ( - PciIo, - Port, - 0, - Timeout - ); + PciIo, + Port, + 0, + Timeout + ); if (EFI_ERROR (Status)) { break; } @@ -1017,7 +1013,7 @@ AhciPioTransfer ( if (Read && (AtapiCommand == 0)) { Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisPioSetup); if (Status == EFI_SUCCESS) { - PrdCount = *(volatile UINT32 *) (&(AhciRegisters->AhciCmdList[0].AhciCmdPrdbc)); + PrdCount = *(volatile UINT32 *)(&(AhciRegisters->AhciCmdList[0].AhciCmdPrdbc)); if (PrdCount == DataCount) { Status = EFI_SUCCESS; } else { @@ -1052,9 +1048,9 @@ AhciPioTransfer ( ); PciIo->Unmap ( - PciIo, - Map - ); + PciIo, + Map + ); AhciDumpPortStatus (PciIo, AhciRegisters, Port, AtaStatusBlock); @@ -1101,31 +1097,31 @@ AhciPioTransfer ( EFI_STATUS EFIAPI AhciDmaTransfer ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *Map; - UINTN MapLength; - EFI_PCI_IO_PROTOCOL_OPERATION Flag; - EFI_AHCI_COMMAND_FIS CFis; - EFI_AHCI_COMMAND_LIST CmdList; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_TPL OldTpl; - UINT32 Retry; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *Map; + UINTN MapLength; + EFI_PCI_IO_PROTOCOL_OPERATION Flag; + EFI_AHCI_COMMAND_FIS CFis; + EFI_AHCI_COMMAND_LIST CmdList; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_TPL OldTpl; + UINT32 Retry; Map = NULL; PciIo = Instance->PciIo; @@ -1151,24 +1147,25 @@ AhciDmaTransfer ( } MapLength = DataCount; - Status = PciIo->Map ( - PciIo, - Flag, - MemoryAddr, - &MapLength, - &PhyAddr, - &Map - ); + Status = PciIo->Map ( + PciIo, + Flag, + MemoryAddr, + &MapLength, + &PhyAddr, + &Map + ); if (EFI_ERROR (Status) || (DataCount != MapLength)) { return EFI_BAD_BUFFER_SIZE; } + if (Task != NULL) { Task->Map = Map; } } - if (Task == NULL || (Task != NULL && !Task->IsStart)) { + if ((Task == NULL) || ((Task != NULL) && !Task->IsStart)) { AhciBuildCommandFis (&CFis, AtaCommandBlock); ZeroMem (&CmdList, sizeof (EFI_AHCI_COMMAND_LIST)); @@ -1191,6 +1188,7 @@ AhciDmaTransfer ( // MicroSecondDelay (100); } + gBS->RestoreTPL (OldTpl); for (Retry = 0; Retry < AHCI_COMMAND_RETRIES; Retry++) { AhciBuildCommand ( @@ -1210,14 +1208,15 @@ AhciDmaTransfer ( DEBUG ((DEBUG_VERBOSE, "Starting command for sync DMA transfer:\n")); AhciPrintCommandBlock (AtaCommandBlock, DEBUG_VERBOSE); Status = AhciStartCommand ( - PciIo, - Port, - 0, - Timeout - ); + PciIo, + Port, + 0, + Timeout + ); if (EFI_ERROR (Status)) { break; } + Status = AhciWaitUntilFisReceived (PciIo, Port, Timeout, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { DEBUG ((DEBUG_ERROR, "DMA command failed at retry: %d\n", Retry)); @@ -1248,15 +1247,16 @@ AhciDmaTransfer ( DEBUG ((DEBUG_VERBOSE, "Starting command for async DMA transfer:\n")); AhciPrintCommandBlock (AtaCommandBlock, DEBUG_VERBOSE); Status = AhciStartCommand ( - PciIo, - Port, - 0, - Timeout - ); + PciIo, + Port, + 0, + Timeout + ); if (!EFI_ERROR (Status)) { Task->IsStart = TRUE; } } + if (Task->IsStart) { Status = AhciCheckFisReceived (PciIo, Port, SataFisD2H); if (Status == EFI_DEVICE_ERROR) { @@ -1270,12 +1270,12 @@ AhciDmaTransfer ( // if (Status == EFI_SUCCESS) { Task->IsStart = FALSE; - Status = EFI_NOT_READY; + Status = EFI_NOT_READY; } } if (Status == EFI_NOT_READY) { - if (!Task->InfiniteWait && Task->RetryTimes == 0) { + if (!Task->InfiniteWait && (Task->RetryTimes == 0)) { Status = EFI_TIMEOUT; } else { Task->RetryTimes--; @@ -1291,9 +1291,10 @@ AhciDmaTransfer ( // EFI_NOT_READY that means the command doesn't finished, try again.), first do the // context cleanup, then set the packet's Asb status. // - if (Task == NULL || + if ((Task == NULL) || ((Task != NULL) && (Status != EFI_NOT_READY)) - ) { + ) + { AhciStopCommand ( PciIo, Port, @@ -1358,22 +1359,22 @@ AhciDmaTransfer ( EFI_STATUS EFIAPI AhciNonDataTransfer ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ) { - EFI_STATUS Status; - EFI_AHCI_COMMAND_FIS CFis; - EFI_AHCI_COMMAND_LIST CmdList; - UINT32 Retry; + EFI_STATUS Status; + EFI_AHCI_COMMAND_FIS CFis; + EFI_AHCI_COMMAND_LIST CmdList; + UINT32 Retry; // // Package read needed @@ -1402,11 +1403,11 @@ AhciNonDataTransfer ( DEBUG ((DEBUG_VERBOSE, "Starting command for non data transfer:\n")); AhciPrintCommandBlock (AtaCommandBlock, DEBUG_VERBOSE); Status = AhciStartCommand ( - PciIo, - Port, - 0, - Timeout - ); + PciIo, + Port, + 0, + Timeout + ); if (EFI_ERROR (Status)) { break; } @@ -1467,13 +1468,13 @@ AhciNonDataTransfer ( EFI_STATUS EFIAPI AhciStopCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT64 Timeout ) { - UINT32 Offset; - UINT32 Data; + UINT32 Offset; + UINT32 Data; Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; Data = AhciReadReg (PciIo, Offset); @@ -1483,7 +1484,7 @@ AhciStopCommand ( } if ((Data & EFI_AHCI_PORT_CMD_ST) != 0) { - AhciAndReg (PciIo, Offset, (UINT32)~(EFI_AHCI_PORT_CMD_ST)); + AhciAndReg (PciIo, Offset, (UINT32) ~(EFI_AHCI_PORT_CMD_ST)); } return AhciWaitMmioSet ( @@ -1511,26 +1512,26 @@ AhciStopCommand ( EFI_STATUS EFIAPI AhciStartCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT8 CommandSlot, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT8 CommandSlot, + IN UINT64 Timeout ) { - UINT32 CmdSlotBit; - EFI_STATUS Status; - UINT32 PortStatus; - UINT32 StartCmd; - UINT32 PortTfd; - UINT32 Offset; - UINT32 Capability; + UINT32 CmdSlotBit; + EFI_STATUS Status; + UINT32 PortStatus; + UINT32 StartCmd; + UINT32 PortTfd; + UINT32 Offset; + UINT32 Capability; // // Collect AHCI controller information // - Capability = AhciReadReg(PciIo, EFI_AHCI_CAPABILITY_OFFSET); + Capability = AhciReadReg (PciIo, EFI_AHCI_CAPABILITY_OFFSET); - CmdSlotBit = (UINT32) (1 << CommandSlot); + CmdSlotBit = (UINT32)(1 << CommandSlot); AhciClearPortStatus ( PciIo, @@ -1547,17 +1548,17 @@ AhciStartCommand ( return Status; } - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; PortStatus = AhciReadReg (PciIo, Offset); StartCmd = 0; if ((PortStatus & EFI_AHCI_PORT_CMD_ALPE) != 0) { - StartCmd = AhciReadReg (PciIo, Offset); + StartCmd = AhciReadReg (PciIo, Offset); StartCmd &= ~EFI_AHCI_PORT_CMD_ICC_MASK; StartCmd |= EFI_AHCI_PORT_CMD_ACTIVE; } - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_TFD; PortTfd = AhciReadReg (PciIo, Offset); if ((PortTfd & (EFI_AHCI_PORT_TFD_BSY | EFI_AHCI_PORT_TFD_DRQ)) != 0) { @@ -1588,7 +1589,6 @@ AhciStartCommand ( return EFI_SUCCESS; } - /** Do AHCI HBA reset. @@ -1603,17 +1603,17 @@ AhciStartCommand ( EFI_STATUS EFIAPI AhciReset ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT64 Timeout ) { - UINT64 Delay; - UINT32 Value; + UINT64 Delay; + UINT32 Value; // // Make sure that GHC.AE bit is set before accessing any AHCI registers. // - Value = AhciReadReg(PciIo, EFI_AHCI_GHC_OFFSET); + Value = AhciReadReg (PciIo, EFI_AHCI_GHC_OFFSET); if ((Value & EFI_AHCI_GHC_ENABLE) == 0) { AhciOrReg (PciIo, EFI_AHCI_GHC_OFFSET, EFI_AHCI_GHC_ENABLE); @@ -1621,10 +1621,10 @@ AhciReset ( AhciOrReg (PciIo, EFI_AHCI_GHC_OFFSET, EFI_AHCI_GHC_RESET); - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { - Value = AhciReadReg(PciIo, EFI_AHCI_GHC_OFFSET); + Value = AhciReadReg (PciIo, EFI_AHCI_GHC_OFFSET); if ((Value & EFI_AHCI_GHC_RESET) == 0) { break; @@ -1633,7 +1633,7 @@ AhciReset ( // // Stall for 100 microseconds. // - MicroSecondDelay(100); + MicroSecondDelay (100); Delay--; } while (Delay > 0); @@ -1661,19 +1661,19 @@ AhciReset ( EFI_STATUS EFIAPI AhciAtaSmartReturnStatusCheck ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - UINT8 LBAMid; - UINT8 LBAHigh; - UINTN FisBaseAddr; - UINT32 Value; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + UINT8 LBAMid; + UINT8 LBAHigh; + UINTN FisBaseAddr; + UINT32 Value; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); @@ -1713,7 +1713,7 @@ AhciAtaSmartReturnStatusCheck ( FisBaseAddr = (UINTN)AhciRegisters->AhciRFis + Port * sizeof (EFI_AHCI_RECEIVED_FIS); - Value = *(UINT32 *) (FisBaseAddr + EFI_AHCI_D2H_FIS_OFFSET); + Value = *(UINT32 *)(FisBaseAddr + EFI_AHCI_D2H_FIS_OFFSET); if ((Value & EFI_AHCI_FIS_TYPE_MASK) == EFI_AHCI_FIS_REGISTER_D2H) { LBAMid = ((UINT8 *)(UINTN)(FisBaseAddr + EFI_AHCI_D2H_FIS_OFFSET))[5]; @@ -1725,18 +1725,18 @@ AhciAtaSmartReturnStatusCheck ( // DEBUG ((DEBUG_INFO, "The S.M.A.R.T threshold exceeded condition is not detected\n")); REPORT_STATUS_CODE ( - EFI_PROGRESS_CODE, - (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_UNDERTHRESHOLD) - ); + EFI_PROGRESS_CODE, + (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_UNDERTHRESHOLD) + ); } else if ((LBAMid == 0xf4) && (LBAHigh == 0x2c)) { // // The threshold exceeded condition is detected by the device // DEBUG ((DEBUG_INFO, "The S.M.A.R.T threshold exceeded condition is detected\n")); REPORT_STATUS_CODE ( - EFI_PROGRESS_CODE, - (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_OVERTHRESHOLD) - ); + EFI_PROGRESS_CODE, + (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_OVERTHRESHOLD) + ); } } @@ -1757,16 +1757,16 @@ AhciAtaSmartReturnStatusCheck ( VOID EFIAPI AhciAtaSmartSupport ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_IDENTIFY_DATA *IdentifyData, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_IDENTIFY_DATA *IdentifyData, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; // // Detect if the device supports S.M.A.R.T. @@ -1775,8 +1775,12 @@ AhciAtaSmartSupport ( // // S.M.A.R.T is not supported by the device // - DEBUG ((DEBUG_INFO, "S.M.A.R.T feature is not supported at port [%d] PortMultiplier [%d]!\n", - Port, PortMultiplier)); + DEBUG (( + DEBUG_INFO, + "S.M.A.R.T feature is not supported at port [%d] PortMultiplier [%d]!\n", + Port, + PortMultiplier + )); REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MINOR, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_NOTSUPPORTED) @@ -1786,7 +1790,6 @@ AhciAtaSmartSupport ( // Check if the feature is enabled. If not, then enable S.M.A.R.T. // if ((IdentifyData->AtaData.command_set_feature_enb_85 & 0x0001) != 0x0001) { - REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_DISABLE) @@ -1815,7 +1818,6 @@ AhciAtaSmartSupport ( NULL ); - if (!EFI_ERROR (Status)) { // // Send S.M.A.R.T AutoSave command to device @@ -1851,11 +1853,15 @@ AhciAtaSmartSupport ( AtaStatusBlock ); - DEBUG ((DEBUG_INFO, "Enabled S.M.A.R.T feature at port [%d] PortMultiplier [%d]!\n", - Port, PortMultiplier)); + DEBUG (( + DEBUG_INFO, + "Enabled S.M.A.R.T feature at port [%d] PortMultiplier [%d]!\n", + Port, + PortMultiplier + )); } - return ; + return; } /** @@ -1876,18 +1882,18 @@ AhciAtaSmartSupport ( EFI_STATUS EFIAPI AhciIdentify ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN OUT EFI_IDENTIFY_DATA *Buffer + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN OUT EFI_IDENTIFY_DATA *Buffer ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; - if (PciIo == NULL || AhciRegisters == NULL || Buffer == NULL) { + if ((PciIo == NULL) || (AhciRegisters == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1934,18 +1940,18 @@ AhciIdentify ( EFI_STATUS EFIAPI AhciIdentifyPacket ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN OUT EFI_IDENTIFY_DATA *Buffer + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN OUT EFI_IDENTIFY_DATA *Buffer ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; - if (PciIo == NULL || AhciRegisters == NULL) { + if ((PciIo == NULL) || (AhciRegisters == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1994,29 +2000,29 @@ AhciIdentifyPacket ( EFI_STATUS EFIAPI AhciDeviceSetFeature ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN UINT16 Feature, - IN UINT32 FeatureSpecificData, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN UINT16 Feature, + IN UINT32 FeatureSpecificData, + IN UINT64 Timeout ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); ZeroMem (&AtaStatusBlock, sizeof (EFI_ATA_STATUS_BLOCK)); AtaCommandBlock.AtaCommand = ATA_CMD_SET_FEATURES; - AtaCommandBlock.AtaFeatures = (UINT8) Feature; - AtaCommandBlock.AtaFeaturesExp = (UINT8) (Feature >> 8); - AtaCommandBlock.AtaSectorCount = (UINT8) FeatureSpecificData; - AtaCommandBlock.AtaSectorNumber = (UINT8) (FeatureSpecificData >> 8); - AtaCommandBlock.AtaCylinderLow = (UINT8) (FeatureSpecificData >> 16); - AtaCommandBlock.AtaCylinderHigh = (UINT8) (FeatureSpecificData >> 24); + AtaCommandBlock.AtaFeatures = (UINT8)Feature; + AtaCommandBlock.AtaFeaturesExp = (UINT8)(Feature >> 8); + AtaCommandBlock.AtaSectorCount = (UINT8)FeatureSpecificData; + AtaCommandBlock.AtaSectorNumber = (UINT8)(FeatureSpecificData >> 8); + AtaCommandBlock.AtaCylinderLow = (UINT8)(FeatureSpecificData >> 16); + AtaCommandBlock.AtaCylinderHigh = (UINT8)(FeatureSpecificData >> 24); Status = AhciNonDataTransfer ( PciIo, @@ -2052,46 +2058,46 @@ AhciDeviceSetFeature ( EFI_STATUS EFIAPI AhciPacketCommandExecute ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet ) { - EFI_STATUS Status; - VOID *Buffer; - UINT32 Length; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; - BOOLEAN Read; - - if (Packet == NULL || Packet->Cdb == NULL) { + EFI_STATUS Status; + VOID *Buffer; + UINT32 Length; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; + BOOLEAN Read; + + if ((Packet == NULL) || (Packet->Cdb == NULL)) { return EFI_INVALID_PARAMETER; } ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); ZeroMem (&AtaStatusBlock, sizeof (EFI_ATA_STATUS_BLOCK)); - AtaCommandBlock.AtaCommand = ATA_CMD_PACKET; + AtaCommandBlock.AtaCommand = ATA_CMD_PACKET; // // No OVL; No DMA // - AtaCommandBlock.AtaFeatures = 0x00; + AtaCommandBlock.AtaFeatures = 0x00; // // set the transfersize to ATAPI_MAX_BYTE_COUNT to let the device // determine how many data should be transferred. // - AtaCommandBlock.AtaCylinderLow = (UINT8) (ATAPI_MAX_BYTE_COUNT & 0x00ff); - AtaCommandBlock.AtaCylinderHigh = (UINT8) (ATAPI_MAX_BYTE_COUNT >> 8); + AtaCommandBlock.AtaCylinderLow = (UINT8)(ATAPI_MAX_BYTE_COUNT & 0x00ff); + AtaCommandBlock.AtaCylinderHigh = (UINT8)(ATAPI_MAX_BYTE_COUNT >> 8); if (Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ) { Buffer = Packet->InDataBuffer; Length = Packet->InTransferLength; - Read = TRUE; + Read = TRUE; } else { Buffer = Packet->OutDataBuffer; Length = Packet->OutTransferLength; - Read = FALSE; + Read = FALSE; } if (Length == 0) { @@ -2124,6 +2130,7 @@ AhciPacketCommandExecute ( NULL ); } + return Status; } @@ -2137,13 +2144,13 @@ AhciPacketCommandExecute ( EFI_STATUS EFIAPI AhciCreateTransferDescriptor ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN OUT EFI_AHCI_REGISTERS *AhciRegisters + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN OUT EFI_AHCI_REGISTERS *AhciRegisters ) { - EFI_STATUS Status; - UINTN Bytes; - VOID *Buffer; + EFI_STATUS Status; + UINTN Bytes; + VOID *Buffer; UINT32 Capability; UINT32 PortImplementBitMap; @@ -2161,31 +2168,31 @@ AhciCreateTransferDescriptor ( // // Collect AHCI controller information // - Capability = AhciReadReg(PciIo, EFI_AHCI_CAPABILITY_OFFSET); + Capability = AhciReadReg (PciIo, EFI_AHCI_CAPABILITY_OFFSET); // // Get the number of command slots per port supported by this HBA. // - MaxCommandSlotNumber = (UINT8) (((Capability & 0x1F00) >> 8) + 1); - Support64Bit = (BOOLEAN) (((Capability & BIT31) != 0) ? TRUE : FALSE); + MaxCommandSlotNumber = (UINT8)(((Capability & 0x1F00) >> 8) + 1); + Support64Bit = (BOOLEAN)(((Capability & BIT31) != 0) ? TRUE : FALSE); - PortImplementBitMap = AhciReadReg(PciIo, EFI_AHCI_PI_OFFSET); + PortImplementBitMap = AhciReadReg (PciIo, EFI_AHCI_PI_OFFSET); // // Get the highest bit of implemented ports which decides how many bytes are allocated for received FIS. // - MaxPortNumber = (UINT8)(UINTN)(HighBitSet32(PortImplementBitMap) + 1); + MaxPortNumber = (UINT8)(UINTN)(HighBitSet32 (PortImplementBitMap) + 1); if (MaxPortNumber == 0) { return EFI_DEVICE_ERROR; } - MaxReceiveFisSize = MaxPortNumber * sizeof (EFI_AHCI_RECEIVED_FIS); - Status = PciIo->AllocateBuffer ( - PciIo, - AllocateAnyPages, - EfiBootServicesData, - EFI_SIZE_TO_PAGES ((UINTN) MaxReceiveFisSize), - &Buffer, - 0 - ); + MaxReceiveFisSize = MaxPortNumber * sizeof (EFI_AHCI_RECEIVED_FIS); + Status = PciIo->AllocateBuffer ( + PciIo, + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES ((UINTN)MaxReceiveFisSize), + &Buffer, + 0 + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; @@ -2195,7 +2202,7 @@ AhciCreateTransferDescriptor ( AhciRegisters->AhciRFis = Buffer; AhciRegisters->MaxReceiveFisSize = MaxReceiveFisSize; - Bytes = (UINTN)MaxReceiveFisSize; + Bytes = (UINTN)MaxReceiveFisSize; Status = PciIo->Map ( PciIo, @@ -2221,22 +2228,23 @@ AhciCreateTransferDescriptor ( Status = EFI_DEVICE_ERROR; goto Error5; } + AhciRegisters->AhciRFisPciAddr = (EFI_AHCI_RECEIVED_FIS *)(UINTN)AhciRFisPciAddr; // // Allocate memory for command list // Note that the implementation is a single task model which only use a command list for all ports. // - Buffer = NULL; + Buffer = NULL; MaxCommandListSize = MaxCommandSlotNumber * sizeof (EFI_AHCI_COMMAND_LIST); - Status = PciIo->AllocateBuffer ( - PciIo, - AllocateAnyPages, - EfiBootServicesData, - EFI_SIZE_TO_PAGES ((UINTN) MaxCommandListSize), - &Buffer, - 0 - ); + Status = PciIo->AllocateBuffer ( + PciIo, + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES ((UINTN)MaxCommandListSize), + &Buffer, + 0 + ); if (EFI_ERROR (Status)) { // @@ -2250,7 +2258,7 @@ AhciCreateTransferDescriptor ( AhciRegisters->AhciCmdList = Buffer; AhciRegisters->MaxCommandListSize = MaxCommandListSize; - Bytes = (UINTN)MaxCommandListSize; + Bytes = (UINTN)MaxCommandListSize; Status = PciIo->Map ( PciIo, @@ -2276,20 +2284,21 @@ AhciCreateTransferDescriptor ( Status = EFI_DEVICE_ERROR; goto Error3; } + AhciRegisters->AhciCmdListPciAddr = (EFI_AHCI_COMMAND_LIST *)(UINTN)AhciCmdListPciAddr; // // Allocate memory for command table // According to AHCI 1.3 spec, a PRD table can contain maximum 65535 entries. // - Buffer = NULL; + Buffer = NULL; MaxCommandTableSize = sizeof (EFI_AHCI_COMMAND_TABLE); Status = PciIo->AllocateBuffer ( PciIo, AllocateAnyPages, EfiBootServicesData, - EFI_SIZE_TO_PAGES ((UINTN) MaxCommandTableSize), + EFI_SIZE_TO_PAGES ((UINTN)MaxCommandTableSize), &Buffer, 0 ); @@ -2306,7 +2315,7 @@ AhciCreateTransferDescriptor ( AhciRegisters->AhciCommandTable = Buffer; AhciRegisters->MaxCommandTableSize = MaxCommandTableSize; - Bytes = (UINTN)MaxCommandTableSize; + Bytes = (UINTN)MaxCommandTableSize; Status = PciIo->Map ( PciIo, @@ -2332,6 +2341,7 @@ AhciCreateTransferDescriptor ( Status = EFI_DEVICE_ERROR; goto Error1; } + AhciRegisters->AhciCommandTablePciAddr = (EFI_AHCI_COMMAND_TABLE *)(UINTN)AhciCommandTablePciAddr; return EFI_SUCCESS; @@ -2346,7 +2356,7 @@ Error1: Error2: PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) MaxCommandTableSize), + EFI_SIZE_TO_PAGES ((UINTN)MaxCommandTableSize), AhciRegisters->AhciCommandTable ); Error3: @@ -2357,7 +2367,7 @@ Error3: Error4: PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) MaxCommandListSize), + EFI_SIZE_TO_PAGES ((UINTN)MaxCommandListSize), AhciRegisters->AhciCmdList ); Error5: @@ -2368,7 +2378,7 @@ Error5: Error6: PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) MaxReceiveFisSize), + EFI_SIZE_TO_PAGES ((UINTN)MaxReceiveFisSize), AhciRegisters->AhciRFis ); @@ -2391,19 +2401,19 @@ Error6: **/ EFI_STATUS AhciReadLogExt ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN OUT UINT8 *Buffer, - IN UINT8 LogNumber, - IN UINT8 PageNumber + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN OUT UINT8 *Buffer, + IN UINT8 LogNumber, + IN UINT8 PageNumber ) { - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; - if (PciIo == NULL || AhciRegisters == NULL || Buffer == NULL) { + if ((PciIo == NULL) || (AhciRegisters == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -2450,11 +2460,11 @@ AhciReadLogExt ( **/ EFI_STATUS AhciEnableDevSlp ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_IDENTIFY_DATA *IdentifyData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_IDENTIFY_DATA *IdentifyData ) { EFI_STATUS Status; @@ -2488,19 +2498,28 @@ AhciEnableDevSlp ( DEBUG ((DEBUG_INFO, "Port CMD/DEVSLP = %08x / %08x\n", PortCmd, PortDevSlp)); if (((PortDevSlp & AHCI_PORT_DEVSLP_DSP) == 0) || ((PortCmd & (EFI_AHCI_PORT_CMD_HPCP | EFI_AHCI_PORT_CMD_MPSP)) != 0) - ) { + ) + { return EFI_UNSUPPORTED; } // // Do not enable DevSlp if the device doesn't support DevSlp // - DEBUG ((DEBUG_INFO, "IDENTIFY DEVICE: [77] = %04x, [78] = %04x, [79] = %04x\n", - IdentifyData->AtaData.reserved_77, - IdentifyData->AtaData.serial_ata_features_supported, IdentifyData->AtaData.serial_ata_features_enabled)); + DEBUG (( + DEBUG_INFO, + "IDENTIFY DEVICE: [77] = %04x, [78] = %04x, [79] = %04x\n", + IdentifyData->AtaData.reserved_77, + IdentifyData->AtaData.serial_ata_features_supported, + IdentifyData->AtaData.serial_ata_features_enabled + )); if ((IdentifyData->AtaData.serial_ata_features_supported & BIT8) == 0) { - DEBUG ((DEBUG_INFO, "DevSlp feature is not supported for device at port [%d] PortMultiplier [%d]!\n", - Port, PortMultiplier)); + DEBUG (( + DEBUG_INFO, + "DevSlp feature is not supported for device at port [%d] PortMultiplier [%d]!\n", + Port, + PortMultiplier + )); return EFI_UNSUPPORTED; } @@ -2509,16 +2528,27 @@ AhciEnableDevSlp ( // if ((IdentifyData->AtaData.serial_ata_features_enabled & BIT8) != 0) { Status = AhciDeviceSetFeature ( - PciIo, AhciRegisters, Port, 0, ATA_SUB_CMD_ENABLE_SATA_FEATURE, 0x09, ATA_ATAPI_TIMEOUT - ); - DEBUG ((DEBUG_INFO, "DevSlp set feature for device at port [%d] PortMultiplier [%d] - %r\n", - Port, PortMultiplier, Status)); + PciIo, + AhciRegisters, + Port, + 0, + ATA_SUB_CMD_ENABLE_SATA_FEATURE, + 0x09, + ATA_ATAPI_TIMEOUT + ); + DEBUG (( + DEBUG_INFO, + "DevSlp set feature for device at port [%d] PortMultiplier [%d] - %r\n", + Port, + PortMultiplier, + Status + )); if (EFI_ERROR (Status)) { return Status; } } - Status = AhciReadLogExt(PciIo, AhciRegisters, Port, PortMultiplier, LogData, 0x30, 0x08); + Status = AhciReadLogExt (PciIo, AhciRegisters, Port, PortMultiplier, LogData, 0x30, 0x08); // // Clear PxCMD.ST and PxDEVSLP.ADSE before updating PxDEVSLP.DITO and PxDEVSLP.MDAT. @@ -2541,8 +2571,13 @@ AhciEnableDevSlp ( ZeroMem (&DevSlpTiming, sizeof (DevSlpTiming)); } else { CopyMem (&DevSlpTiming, &LogData[48], sizeof (DevSlpTiming)); - DEBUG ((DEBUG_INFO, "DevSlpTiming: Supported(%d), Deto(%d), Madt(%d)\n", - DevSlpTiming.Supported, DevSlpTiming.Deto, DevSlpTiming.Madt)); + DEBUG (( + DEBUG_INFO, + "DevSlpTiming: Supported(%d), Deto(%d), Madt(%d)\n", + DevSlpTiming.Supported, + DevSlpTiming.Deto, + DevSlpTiming.Madt + )); } // @@ -2574,11 +2609,16 @@ AhciEnableDevSlp ( } } - AhciWriteReg (PciIo, Offset + EFI_AHCI_PORT_CMD, PortCmd); - DEBUG ((DEBUG_INFO, "Enabled DevSlp feature at port [%d] PortMultiplier [%d], Port CMD/DEVSLP = %08x / %08x\n", - Port, PortMultiplier, PortCmd, PortDevSlp)); + DEBUG (( + DEBUG_INFO, + "Enabled DevSlp feature at port [%d] PortMultiplier [%d], Port CMD/DEVSLP = %08x / %08x\n", + Port, + PortMultiplier, + PortCmd, + PortDevSlp + )); return EFI_SUCCESS; } @@ -2595,28 +2635,38 @@ AhciEnableDevSlp ( **/ EFI_STATUS AhciSpinUpDisk ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN OUT EFI_IDENTIFY_DATA *IdentifyData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN OUT EFI_IDENTIFY_DATA *IdentifyData ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_ATA_STATUS_BLOCK AtaStatusBlock; - UINT8 Buffer[512]; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_ATA_STATUS_BLOCK AtaStatusBlock; + UINT8 Buffer[512]; if (IdentifyData->AtaData.specific_config == ATA_SPINUP_CFG_REQUIRED_IDD_INCOMPLETE) { // // Use SET_FEATURE subcommand to spin up the device. // Status = AhciDeviceSetFeature ( - PciIo, AhciRegisters, Port, PortMultiplier, - ATA_SUB_CMD_PUIS_SET_DEVICE_SPINUP, 0x00, ATA_SPINUP_TIMEOUT + PciIo, + AhciRegisters, + Port, + PortMultiplier, + ATA_SUB_CMD_PUIS_SET_DEVICE_SPINUP, + 0x00, + ATA_SPINUP_TIMEOUT ); - DEBUG ((DEBUG_INFO, "CMD_PUIS_SET_DEVICE_SPINUP for device at port [%d] PortMultiplier [%d] - %r!\n", - Port, PortMultiplier, Status)); + DEBUG (( + DEBUG_INFO, + "CMD_PUIS_SET_DEVICE_SPINUP for device at port [%d] PortMultiplier [%d] - %r!\n", + Port, + PortMultiplier, + Status + )); if (EFI_ERROR (Status)) { return Status; } @@ -2631,8 +2681,8 @@ AhciSpinUpDisk ( // // Perform READ SECTORS PIO Data-In command to Read LBA 0 // - AtaCommandBlock.AtaCommand = ATA_CMD_READ_SECTORS; - AtaCommandBlock.AtaSectorCount = 0x1; + AtaCommandBlock.AtaCommand = ATA_CMD_READ_SECTORS; + AtaCommandBlock.AtaSectorCount = 0x1; Status = AhciPioTransfer ( PciIo, @@ -2649,8 +2699,13 @@ AhciSpinUpDisk ( ATA_SPINUP_TIMEOUT, NULL ); - DEBUG ((DEBUG_INFO, "Read LBA 0 for device at port [%d] PortMultiplier [%d] - %r!\n", - Port, PortMultiplier, Status)); + DEBUG (( + DEBUG_INFO, + "Read LBA 0 for device at port [%d] PortMultiplier [%d] - %r!\n", + Port, + PortMultiplier, + Status + )); if (EFI_ERROR (Status)) { return Status; } @@ -2662,14 +2717,24 @@ AhciSpinUpDisk ( ZeroMem (IdentifyData, sizeof (*IdentifyData)); Status = AhciIdentify (PciIo, AhciRegisters, Port, PortMultiplier, IdentifyData); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "Read IDD failed for device at port [%d] PortMultiplier [%d] - %r!\n", - Port, PortMultiplier, Status)); + DEBUG (( + DEBUG_ERROR, + "Read IDD failed for device at port [%d] PortMultiplier [%d] - %r!\n", + Port, + PortMultiplier, + Status + )); return Status; } - DEBUG ((DEBUG_INFO, "IDENTIFY DEVICE: [0] = %016x, [2] = %016x, [83] = %016x, [86] = %016x\n", - IdentifyData->AtaData.config, IdentifyData->AtaData.specific_config, - IdentifyData->AtaData.command_set_supported_83, IdentifyData->AtaData.command_set_feature_enb_86)); + DEBUG (( + DEBUG_INFO, + "IDENTIFY DEVICE: [0] = %016x, [2] = %016x, [83] = %016x, [86] = %016x\n", + IdentifyData->AtaData.config, + IdentifyData->AtaData.specific_config, + IdentifyData->AtaData.command_set_supported_83, + IdentifyData->AtaData.command_set_feature_enb_86 + )); // // Check if IDD is incomplete // @@ -2691,13 +2756,13 @@ AhciSpinUpDisk ( **/ EFI_STATUS AhciPuisEnable ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EFI_SUCCESS; if (mAtaAtapiPolicy->PuisEnable == 0) { @@ -2705,10 +2770,17 @@ AhciPuisEnable ( } else if (mAtaAtapiPolicy->PuisEnable == 1) { Status = AhciDeviceSetFeature (PciIo, AhciRegisters, Port, PortMultiplier, ATA_SUB_CMD_ENABLE_PUIS, 0x00, ATA_ATAPI_TIMEOUT); } - DEBUG ((DEBUG_INFO, "%a PUIS feature at port [%d] PortMultiplier [%d] - %r!\n", + + DEBUG (( + DEBUG_INFO, + "%a PUIS feature at port [%d] PortMultiplier [%d] - %r!\n", (mAtaAtapiPolicy->PuisEnable == 0) ? "Disable" : ( - (mAtaAtapiPolicy->PuisEnable == 1) ? "Enable" : "Skip" - ), Port, PortMultiplier, Status)); + (mAtaAtapiPolicy->PuisEnable == 1) ? "Enable" : "Skip" + ), + Port, + PortMultiplier, + Status + )); return Status; } @@ -2723,28 +2795,28 @@ AhciPuisEnable ( EFI_STATUS EFIAPI AhciModeInitialization ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeInit; - UINT32 Capability; - UINT8 MaxPortNumber; - UINT32 PortImplementBitMap; - - EFI_AHCI_REGISTERS *AhciRegisters; - - UINT8 Port; - DATA_64 Data64; - UINT32 Offset; - UINT32 Data; - EFI_IDENTIFY_DATA Buffer; - EFI_ATA_DEVICE_TYPE DeviceType; - EFI_ATA_COLLECTIVE_MODE *SupportedModes; - EFI_ATA_TRANSFER_MODE TransferMode; - UINT32 PhyDetectDelay; - UINT32 Value; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeInit; + UINT32 Capability; + UINT8 MaxPortNumber; + UINT32 PortImplementBitMap; + + EFI_AHCI_REGISTERS *AhciRegisters; + + UINT8 Port; + DATA_64 Data64; + UINT32 Offset; + UINT32 Data; + EFI_IDENTIFY_DATA Buffer; + EFI_ATA_DEVICE_TYPE DeviceType; + EFI_ATA_COLLECTIVE_MODE *SupportedModes; + EFI_ATA_TRANSFER_MODE TransferMode; + UINT32 PhyDetectDelay; + UINT32 Value; if (Instance == NULL) { return EFI_INVALID_PARAMETER; @@ -2767,7 +2839,7 @@ AhciModeInitialization ( // // Make sure that GHC.AE bit is set before accessing any AHCI registers. // - Value = AhciReadReg(PciIo, EFI_AHCI_GHC_OFFSET); + Value = AhciReadReg (PciIo, EFI_AHCI_GHC_OFFSET); if ((Value & EFI_AHCI_GHC_ENABLE) == 0) { AhciOrReg (PciIo, EFI_AHCI_GHC_OFFSET, EFI_AHCI_GHC_ENABLE); @@ -2785,31 +2857,33 @@ AhciModeInitialization ( NULL ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "AhciModeInitialization: failed to enable 64-bit DMA on 64-bit capable controller (%r)\n", - Status)); + Status + )); } } // // Get the number of command slots per port supported by this HBA. // - MaxPortNumber = (UINT8) ((Capability & 0x1F) + 1); + MaxPortNumber = (UINT8)((Capability & 0x1F) + 1); // // Get the bit map of those ports exposed by this HBA. // It indicates which ports that the HBA supports are available for software to use. // - PortImplementBitMap = AhciReadReg(PciIo, EFI_AHCI_PI_OFFSET); + PortImplementBitMap = AhciReadReg (PciIo, EFI_AHCI_PI_OFFSET); AhciRegisters = &Instance->AhciRegisters; - Status = AhciCreateTransferDescriptor (PciIo, AhciRegisters); + Status = AhciCreateTransferDescriptor (PciIo, AhciRegisters); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - for (Port = 0; Port < EFI_AHCI_MAX_PORTS; Port ++) { + for (Port = 0; Port < EFI_AHCI_MAX_PORTS; Port++) { if ((PortImplementBitMap & (((UINT32)BIT0) << Port)) != 0) { // // According to AHCI spec, MaxPortNumber should be equal or greater than the number of implemented ports. @@ -2827,20 +2901,20 @@ AhciModeInitialization ( // // Initialize FIS Base Address Register and Command List Base Address Register for use. // - Data64.Uint64 = (UINTN) (AhciRegisters->AhciRFisPciAddr) + sizeof (EFI_AHCI_RECEIVED_FIS) * Port; - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_FB; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciRFisPciAddr) + sizeof (EFI_AHCI_RECEIVED_FIS) * Port; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_FB; AhciWriteReg (PciIo, Offset, Data64.Uint32.Lower32); Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_FBU; AhciWriteReg (PciIo, Offset, Data64.Uint32.Upper32); - Data64.Uint64 = (UINTN) (AhciRegisters->AhciCmdListPciAddr); - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CLB; + Data64.Uint64 = (UINTN)(AhciRegisters->AhciCmdListPciAddr); + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CLB; AhciWriteReg (PciIo, Offset, Data64.Uint32.Lower32); Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CLBU; AhciWriteReg (PciIo, Offset, Data64.Uint32.Upper32); Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_CMD; - Data = AhciReadReg (PciIo, Offset); + Data = AhciReadReg (PciIo, Offset); if ((Data & EFI_AHCI_PORT_CMD_CPD) != 0) { AhciOrReg (PciIo, Offset, EFI_AHCI_PORT_CMD_POD); } @@ -2875,7 +2949,7 @@ AhciModeInitialization ( // Wait for the Phy to detect the presence of a device. // PhyDetectDelay = EFI_AHCI_BUS_PHY_DETECT_TIMEOUT; - Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_SSTS; + Offset = EFI_AHCI_PORT_START + Port * EFI_AHCI_PORT_REG_WIDTH + EFI_AHCI_PORT_SSTS; do { Data = AhciReadReg (PciIo, Offset) & EFI_AHCI_PORT_SSTS_DET_MASK; if ((Data == EFI_AHCI_PORT_SSTS_DET_PCE) || (Data == EFI_AHCI_PORT_SSTS_DET)) { @@ -2910,7 +2984,7 @@ AhciModeInitialization ( Offset, 0x0000FFFF, 0x00000101, - EFI_TIMER_PERIOD_SECONDS(16) + EFI_TIMER_PERIOD_SECONDS (16) ); if (EFI_ERROR (Status)) { continue; @@ -2934,9 +3008,12 @@ AhciModeInitialization ( } DEBUG (( - DEBUG_INFO, "IDENTIFY DEVICE: [0] = %016x, [2] = %016x, [83] = %016x, [86] = %016x\n", - Buffer.AtaData.config, Buffer.AtaData.specific_config, - Buffer.AtaData.command_set_supported_83, Buffer.AtaData.command_set_feature_enb_86 + DEBUG_INFO, + "IDENTIFY DEVICE: [0] = %016x, [2] = %016x, [83] = %016x, [86] = %016x\n", + Buffer.AtaData.config, + Buffer.AtaData.specific_config, + Buffer.AtaData.command_set_supported_83, + Buffer.AtaData.command_set_feature_enb_86 )); if ((Buffer.AtaData.config & BIT2) != 0) { // @@ -2959,8 +3036,14 @@ AhciModeInitialization ( } else { continue; } - DEBUG ((DEBUG_INFO, "port [%d] port multitplier [%d] has a [%a]\n", - Port, 0, DeviceType == EfiIdeCdrom ? "cdrom" : "harddisk")); + + DEBUG (( + DEBUG_INFO, + "port [%d] port multitplier [%d] has a [%a]\n", + Port, + 0, + DeviceType == EfiIdeCdrom ? "cdrom" : "harddisk" + )); // // If the device is a hard disk, then try to enable S.M.A.R.T feature @@ -3004,7 +3087,7 @@ AhciModeInitialization ( TransferMode.ModeCategory = EFI_ATA_MODE_FLOW_PIO; } - TransferMode.ModeNumber = (UINT8) (SupportedModes->PioMode.Mode); + TransferMode.ModeNumber = (UINT8)(SupportedModes->PioMode.Mode); // // Set supported DMA mode on this IDE device. Note that UDMA & MDMA can't @@ -3014,10 +3097,10 @@ AhciModeInitialization ( // if (SupportedModes->UdmaMode.Valid) { TransferMode.ModeCategory = EFI_ATA_MODE_UDMA; - TransferMode.ModeNumber = (UINT8) (SupportedModes->UdmaMode.Mode); + TransferMode.ModeNumber = (UINT8)(SupportedModes->UdmaMode.Mode); } else if (SupportedModes->MultiWordDmaMode.Valid) { TransferMode.ModeCategory = EFI_ATA_MODE_MDMA; - TransferMode.ModeNumber = (UINT8) SupportedModes->MultiWordDmaMode.Mode; + TransferMode.ModeNumber = (UINT8)SupportedModes->MultiWordDmaMode.Mode; } Status = AhciDeviceSetFeature (PciIo, AhciRegisters, Port, 0, 0x03, (UINT32)(*(UINT8 *)&TransferMode), ATA_ATAPI_TIMEOUT); diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h index ced2648970..7802ebd200 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AhciMode.h @@ -5,192 +5,193 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __ATA_HC_AHCI_MODE_H__ #define __ATA_HC_AHCI_MODE_H__ -#define EFI_AHCI_BAR_INDEX 0x05 +#define EFI_AHCI_BAR_INDEX 0x05 -#define EFI_AHCI_CAPABILITY_OFFSET 0x0000 -#define EFI_AHCI_CAP_SAM BIT18 -#define EFI_AHCI_CAP_SSS BIT27 -#define EFI_AHCI_CAP_S64A BIT31 -#define EFI_AHCI_GHC_OFFSET 0x0004 -#define EFI_AHCI_GHC_RESET BIT0 -#define EFI_AHCI_GHC_IE BIT1 -#define EFI_AHCI_GHC_ENABLE BIT31 -#define EFI_AHCI_IS_OFFSET 0x0008 -#define EFI_AHCI_PI_OFFSET 0x000C +#define EFI_AHCI_CAPABILITY_OFFSET 0x0000 +#define EFI_AHCI_CAP_SAM BIT18 +#define EFI_AHCI_CAP_SSS BIT27 +#define EFI_AHCI_CAP_S64A BIT31 +#define EFI_AHCI_GHC_OFFSET 0x0004 +#define EFI_AHCI_GHC_RESET BIT0 +#define EFI_AHCI_GHC_IE BIT1 +#define EFI_AHCI_GHC_ENABLE BIT31 +#define EFI_AHCI_IS_OFFSET 0x0008 +#define EFI_AHCI_PI_OFFSET 0x000C -#define EFI_AHCI_MAX_PORTS 32 +#define EFI_AHCI_MAX_PORTS 32 -#define AHCI_CAPABILITY2_OFFSET 0x0024 -#define AHCI_CAP2_SDS BIT3 -#define AHCI_CAP2_SADM BIT4 +#define AHCI_CAPABILITY2_OFFSET 0x0024 +#define AHCI_CAP2_SDS BIT3 +#define AHCI_CAP2_SADM BIT4 typedef struct { - UINT32 Lower32; - UINT32 Upper32; + UINT32 Lower32; + UINT32 Upper32; } DATA_32; typedef union { - DATA_32 Uint32; - UINT64 Uint64; + DATA_32 Uint32; + UINT64 Uint64; } DATA_64; // // Refer SATA1.0a spec section 5.2, the Phy detection time should be less than 10ms. // Add a bit of margin for robustness. // -#define EFI_AHCI_BUS_PHY_DETECT_TIMEOUT 15 +#define EFI_AHCI_BUS_PHY_DETECT_TIMEOUT 15 // // Refer SATA1.0a spec, the FIS enable time should be less than 500ms. // -#define EFI_AHCI_PORT_CMD_FR_CLEAR_TIMEOUT EFI_TIMER_PERIOD_MILLISECONDS(500) +#define EFI_AHCI_PORT_CMD_FR_CLEAR_TIMEOUT EFI_TIMER_PERIOD_MILLISECONDS(500) // // Refer SATA1.0a spec, the bus reset time should be less than 1s. // -#define EFI_AHCI_BUS_RESET_TIMEOUT EFI_TIMER_PERIOD_SECONDS(1) +#define EFI_AHCI_BUS_RESET_TIMEOUT EFI_TIMER_PERIOD_SECONDS(1) -#define EFI_AHCI_ATAPI_DEVICE_SIG 0xEB140000 -#define EFI_AHCI_ATA_DEVICE_SIG 0x00000000 -#define EFI_AHCI_PORT_MULTIPLIER_SIG 0x96690000 -#define EFI_AHCI_ATAPI_SIG_MASK 0xFFFF0000 +#define EFI_AHCI_ATAPI_DEVICE_SIG 0xEB140000 +#define EFI_AHCI_ATA_DEVICE_SIG 0x00000000 +#define EFI_AHCI_PORT_MULTIPLIER_SIG 0x96690000 +#define EFI_AHCI_ATAPI_SIG_MASK 0xFFFF0000 // // Each PRDT entry can point to a memory block up to 4M byte // -#define EFI_AHCI_MAX_DATA_PER_PRDT 0x400000 - -#define EFI_AHCI_FIS_REGISTER_H2D 0x27 //Register FIS - Host to Device -#define EFI_AHCI_FIS_REGISTER_H2D_LENGTH 20 -#define EFI_AHCI_FIS_REGISTER_D2H 0x34 //Register FIS - Device to Host -#define EFI_AHCI_FIS_REGISTER_D2H_LENGTH 20 -#define EFI_AHCI_FIS_DMA_ACTIVATE 0x39 //DMA Activate FIS - Device to Host -#define EFI_AHCI_FIS_DMA_ACTIVATE_LENGTH 4 -#define EFI_AHCI_FIS_DMA_SETUP 0x41 //DMA Setup FIS - Bi-directional -#define EFI_AHCI_FIS_DMA_SETUP_LENGTH 28 -#define EFI_AHCI_FIS_DATA 0x46 //Data FIS - Bi-directional -#define EFI_AHCI_FIS_BIST 0x58 //BIST Activate FIS - Bi-directional -#define EFI_AHCI_FIS_BIST_LENGTH 12 -#define EFI_AHCI_FIS_PIO_SETUP 0x5F //PIO Setup FIS - Device to Host -#define EFI_AHCI_FIS_PIO_SETUP_LENGTH 20 -#define EFI_AHCI_FIS_SET_DEVICE 0xA1 //Set Device Bits FIS - Device to Host -#define EFI_AHCI_FIS_SET_DEVICE_LENGTH 8 - -#define EFI_AHCI_D2H_FIS_OFFSET 0x40 -#define EFI_AHCI_DMA_FIS_OFFSET 0x00 -#define EFI_AHCI_PIO_FIS_OFFSET 0x20 -#define EFI_AHCI_SDB_FIS_OFFSET 0x58 -#define EFI_AHCI_FIS_TYPE_MASK 0xFF -#define EFI_AHCI_U_FIS_OFFSET 0x60 +#define EFI_AHCI_MAX_DATA_PER_PRDT 0x400000 + +#define EFI_AHCI_FIS_REGISTER_H2D 0x27 // Register FIS - Host to Device +#define EFI_AHCI_FIS_REGISTER_H2D_LENGTH 20 +#define EFI_AHCI_FIS_REGISTER_D2H 0x34 // Register FIS - Device to Host +#define EFI_AHCI_FIS_REGISTER_D2H_LENGTH 20 +#define EFI_AHCI_FIS_DMA_ACTIVATE 0x39 // DMA Activate FIS - Device to Host +#define EFI_AHCI_FIS_DMA_ACTIVATE_LENGTH 4 +#define EFI_AHCI_FIS_DMA_SETUP 0x41 // DMA Setup FIS - Bi-directional +#define EFI_AHCI_FIS_DMA_SETUP_LENGTH 28 +#define EFI_AHCI_FIS_DATA 0x46 // Data FIS - Bi-directional +#define EFI_AHCI_FIS_BIST 0x58 // BIST Activate FIS - Bi-directional +#define EFI_AHCI_FIS_BIST_LENGTH 12 +#define EFI_AHCI_FIS_PIO_SETUP 0x5F // PIO Setup FIS - Device to Host +#define EFI_AHCI_FIS_PIO_SETUP_LENGTH 20 +#define EFI_AHCI_FIS_SET_DEVICE 0xA1 // Set Device Bits FIS - Device to Host +#define EFI_AHCI_FIS_SET_DEVICE_LENGTH 8 + +#define EFI_AHCI_D2H_FIS_OFFSET 0x40 +#define EFI_AHCI_DMA_FIS_OFFSET 0x00 +#define EFI_AHCI_PIO_FIS_OFFSET 0x20 +#define EFI_AHCI_SDB_FIS_OFFSET 0x58 +#define EFI_AHCI_FIS_TYPE_MASK 0xFF +#define EFI_AHCI_U_FIS_OFFSET 0x60 // // Port register // -#define EFI_AHCI_PORT_START 0x0100 -#define EFI_AHCI_PORT_REG_WIDTH 0x0080 -#define EFI_AHCI_PORT_CLB 0x0000 -#define EFI_AHCI_PORT_CLBU 0x0004 -#define EFI_AHCI_PORT_FB 0x0008 -#define EFI_AHCI_PORT_FBU 0x000C -#define EFI_AHCI_PORT_IS 0x0010 -#define EFI_AHCI_PORT_IS_DHRS BIT0 -#define EFI_AHCI_PORT_IS_PSS BIT1 -#define EFI_AHCI_PORT_IS_DSS BIT2 -#define EFI_AHCI_PORT_IS_SDBS BIT3 -#define EFI_AHCI_PORT_IS_UFS BIT4 -#define EFI_AHCI_PORT_IS_DPS BIT5 -#define EFI_AHCI_PORT_IS_PCS BIT6 -#define EFI_AHCI_PORT_IS_DIS BIT7 -#define EFI_AHCI_PORT_IS_PRCS BIT22 -#define EFI_AHCI_PORT_IS_IPMS BIT23 -#define EFI_AHCI_PORT_IS_OFS BIT24 -#define EFI_AHCI_PORT_IS_INFS BIT26 -#define EFI_AHCI_PORT_IS_IFS BIT27 -#define EFI_AHCI_PORT_IS_HBDS BIT28 -#define EFI_AHCI_PORT_IS_HBFS BIT29 -#define EFI_AHCI_PORT_IS_TFES BIT30 -#define EFI_AHCI_PORT_IS_CPDS BIT31 -#define EFI_AHCI_PORT_IS_CLEAR 0xFFFFFFFF -#define EFI_AHCI_PORT_IS_FIS_CLEAR 0x0000000F -#define EFI_AHCI_PORT_IS_ERROR_MASK (EFI_AHCI_PORT_IS_INFS | EFI_AHCI_PORT_IS_IFS | EFI_AHCI_PORT_IS_HBDS | EFI_AHCI_PORT_IS_HBFS | EFI_AHCI_PORT_IS_TFES) -#define EFI_AHCI_PORT_IS_FATAL_ERROR_MASK (EFI_AHCI_PORT_IS_IFS | EFI_AHCI_PORT_IS_HBDS | EFI_AHCI_PORT_IS_HBFS | EFI_AHCI_PORT_IS_TFES) - -#define EFI_AHCI_PORT_IE 0x0014 -#define EFI_AHCI_PORT_CMD 0x0018 -#define EFI_AHCI_PORT_CMD_ST_MASK 0xFFFFFFFE -#define EFI_AHCI_PORT_CMD_ST BIT0 -#define EFI_AHCI_PORT_CMD_SUD BIT1 -#define EFI_AHCI_PORT_CMD_POD BIT2 -#define EFI_AHCI_PORT_CMD_CLO BIT3 -#define EFI_AHCI_PORT_CMD_FRE BIT4 -#define EFI_AHCI_PORT_CMD_CCS_MASK (BIT8 | BIT9 | BIT10 | BIT11 | BIT12) -#define EFI_AHCI_PORT_CMD_CCS_SHIFT 8 -#define EFI_AHCI_PORT_CMD_FR BIT14 -#define EFI_AHCI_PORT_CMD_CR BIT15 -#define EFI_AHCI_PORT_CMD_MASK ~(EFI_AHCI_PORT_CMD_ST | EFI_AHCI_PORT_CMD_FRE | EFI_AHCI_PORT_CMD_COL) -#define EFI_AHCI_PORT_CMD_PMA BIT17 -#define EFI_AHCI_PORT_CMD_HPCP BIT18 -#define EFI_AHCI_PORT_CMD_MPSP BIT19 -#define EFI_AHCI_PORT_CMD_CPD BIT20 -#define EFI_AHCI_PORT_CMD_ESP BIT21 -#define EFI_AHCI_PORT_CMD_ATAPI BIT24 -#define EFI_AHCI_PORT_CMD_DLAE BIT25 -#define EFI_AHCI_PORT_CMD_ALPE BIT26 -#define EFI_AHCI_PORT_CMD_ASP BIT27 -#define EFI_AHCI_PORT_CMD_ICC_MASK (BIT28 | BIT29 | BIT30 | BIT31) -#define EFI_AHCI_PORT_CMD_ACTIVE (1 << 28 ) -#define EFI_AHCI_PORT_TFD 0x0020 -#define EFI_AHCI_PORT_TFD_MASK (BIT7 | BIT3 | BIT0) -#define EFI_AHCI_PORT_TFD_BSY BIT7 -#define EFI_AHCI_PORT_TFD_DRQ BIT3 -#define EFI_AHCI_PORT_TFD_ERR BIT0 -#define EFI_AHCI_PORT_TFD_ERR_MASK 0x00FF00 -#define EFI_AHCI_PORT_SIG 0x0024 -#define EFI_AHCI_PORT_SSTS 0x0028 -#define EFI_AHCI_PORT_SSTS_DET_MASK 0x000F -#define EFI_AHCI_PORT_SSTS_DET 0x0001 -#define EFI_AHCI_PORT_SSTS_DET_PCE 0x0003 -#define EFI_AHCI_PORT_SSTS_SPD_MASK 0x00F0 -#define EFI_AHCI_PORT_SCTL 0x002C -#define EFI_AHCI_PORT_SCTL_DET_MASK 0x000F -#define EFI_AHCI_PORT_SCTL_MASK (~EFI_AHCI_PORT_SCTL_DET_MASK) -#define EFI_AHCI_PORT_SCTL_DET_INIT 0x0001 -#define EFI_AHCI_PORT_SCTL_DET_PHYCOMM 0x0003 -#define EFI_AHCI_PORT_SCTL_SPD_MASK 0x00F0 -#define EFI_AHCI_PORT_SCTL_IPM_MASK 0x0F00 -#define EFI_AHCI_PORT_SCTL_IPM_INIT 0x0300 -#define EFI_AHCI_PORT_SCTL_IPM_PSD 0x0100 -#define EFI_AHCI_PORT_SCTL_IPM_SSD 0x0200 -#define EFI_AHCI_PORT_SERR 0x0030 -#define EFI_AHCI_PORT_SERR_RDIE BIT0 -#define EFI_AHCI_PORT_SERR_RCE BIT1 -#define EFI_AHCI_PORT_SERR_TDIE BIT8 -#define EFI_AHCI_PORT_SERR_PCDIE BIT9 -#define EFI_AHCI_PORT_SERR_PE BIT10 -#define EFI_AHCI_PORT_SERR_IE BIT11 -#define EFI_AHCI_PORT_SERR_PRC BIT16 -#define EFI_AHCI_PORT_SERR_PIE BIT17 -#define EFI_AHCI_PORT_SERR_CW BIT18 -#define EFI_AHCI_PORT_SERR_BDE BIT19 -#define EFI_AHCI_PORT_SERR_DE BIT20 -#define EFI_AHCI_PORT_SERR_CRCE BIT21 -#define EFI_AHCI_PORT_SERR_HE BIT22 -#define EFI_AHCI_PORT_SERR_LSE BIT23 -#define EFI_AHCI_PORT_SERR_TSTE BIT24 -#define EFI_AHCI_PORT_SERR_UFT BIT25 -#define EFI_AHCI_PORT_SERR_EX BIT26 -#define EFI_AHCI_PORT_ERR_CLEAR 0xFFFFFFFF -#define EFI_AHCI_PORT_SACT 0x0034 -#define EFI_AHCI_PORT_CI 0x0038 -#define EFI_AHCI_PORT_SNTF 0x003C -#define AHCI_PORT_DEVSLP 0x0044 -#define AHCI_PORT_DEVSLP_ADSE BIT0 -#define AHCI_PORT_DEVSLP_DSP BIT1 -#define AHCI_PORT_DEVSLP_DETO_MASK 0x000003FC -#define AHCI_PORT_DEVSLP_MDAT_MASK 0x00007C00 -#define AHCI_PORT_DEVSLP_DITO_MASK 0x01FF8000 -#define AHCI_PORT_DEVSLP_DM_MASK 0x1E000000 +#define EFI_AHCI_PORT_START 0x0100 +#define EFI_AHCI_PORT_REG_WIDTH 0x0080 +#define EFI_AHCI_PORT_CLB 0x0000 +#define EFI_AHCI_PORT_CLBU 0x0004 +#define EFI_AHCI_PORT_FB 0x0008 +#define EFI_AHCI_PORT_FBU 0x000C +#define EFI_AHCI_PORT_IS 0x0010 +#define EFI_AHCI_PORT_IS_DHRS BIT0 +#define EFI_AHCI_PORT_IS_PSS BIT1 +#define EFI_AHCI_PORT_IS_DSS BIT2 +#define EFI_AHCI_PORT_IS_SDBS BIT3 +#define EFI_AHCI_PORT_IS_UFS BIT4 +#define EFI_AHCI_PORT_IS_DPS BIT5 +#define EFI_AHCI_PORT_IS_PCS BIT6 +#define EFI_AHCI_PORT_IS_DIS BIT7 +#define EFI_AHCI_PORT_IS_PRCS BIT22 +#define EFI_AHCI_PORT_IS_IPMS BIT23 +#define EFI_AHCI_PORT_IS_OFS BIT24 +#define EFI_AHCI_PORT_IS_INFS BIT26 +#define EFI_AHCI_PORT_IS_IFS BIT27 +#define EFI_AHCI_PORT_IS_HBDS BIT28 +#define EFI_AHCI_PORT_IS_HBFS BIT29 +#define EFI_AHCI_PORT_IS_TFES BIT30 +#define EFI_AHCI_PORT_IS_CPDS BIT31 +#define EFI_AHCI_PORT_IS_CLEAR 0xFFFFFFFF +#define EFI_AHCI_PORT_IS_FIS_CLEAR 0x0000000F +#define EFI_AHCI_PORT_IS_ERROR_MASK (EFI_AHCI_PORT_IS_INFS | EFI_AHCI_PORT_IS_IFS | EFI_AHCI_PORT_IS_HBDS | EFI_AHCI_PORT_IS_HBFS | EFI_AHCI_PORT_IS_TFES) +#define EFI_AHCI_PORT_IS_FATAL_ERROR_MASK (EFI_AHCI_PORT_IS_IFS | EFI_AHCI_PORT_IS_HBDS | EFI_AHCI_PORT_IS_HBFS | EFI_AHCI_PORT_IS_TFES) + +#define EFI_AHCI_PORT_IE 0x0014 +#define EFI_AHCI_PORT_CMD 0x0018 +#define EFI_AHCI_PORT_CMD_ST_MASK 0xFFFFFFFE +#define EFI_AHCI_PORT_CMD_ST BIT0 +#define EFI_AHCI_PORT_CMD_SUD BIT1 +#define EFI_AHCI_PORT_CMD_POD BIT2 +#define EFI_AHCI_PORT_CMD_CLO BIT3 +#define EFI_AHCI_PORT_CMD_FRE BIT4 +#define EFI_AHCI_PORT_CMD_CCS_MASK (BIT8 | BIT9 | BIT10 | BIT11 | BIT12) +#define EFI_AHCI_PORT_CMD_CCS_SHIFT 8 +#define EFI_AHCI_PORT_CMD_FR BIT14 +#define EFI_AHCI_PORT_CMD_CR BIT15 +#define EFI_AHCI_PORT_CMD_MASK ~(EFI_AHCI_PORT_CMD_ST | EFI_AHCI_PORT_CMD_FRE | EFI_AHCI_PORT_CMD_COL) +#define EFI_AHCI_PORT_CMD_PMA BIT17 +#define EFI_AHCI_PORT_CMD_HPCP BIT18 +#define EFI_AHCI_PORT_CMD_MPSP BIT19 +#define EFI_AHCI_PORT_CMD_CPD BIT20 +#define EFI_AHCI_PORT_CMD_ESP BIT21 +#define EFI_AHCI_PORT_CMD_ATAPI BIT24 +#define EFI_AHCI_PORT_CMD_DLAE BIT25 +#define EFI_AHCI_PORT_CMD_ALPE BIT26 +#define EFI_AHCI_PORT_CMD_ASP BIT27 +#define EFI_AHCI_PORT_CMD_ICC_MASK (BIT28 | BIT29 | BIT30 | BIT31) +#define EFI_AHCI_PORT_CMD_ACTIVE (1 << 28 ) +#define EFI_AHCI_PORT_TFD 0x0020 +#define EFI_AHCI_PORT_TFD_MASK (BIT7 | BIT3 | BIT0) +#define EFI_AHCI_PORT_TFD_BSY BIT7 +#define EFI_AHCI_PORT_TFD_DRQ BIT3 +#define EFI_AHCI_PORT_TFD_ERR BIT0 +#define EFI_AHCI_PORT_TFD_ERR_MASK 0x00FF00 +#define EFI_AHCI_PORT_SIG 0x0024 +#define EFI_AHCI_PORT_SSTS 0x0028 +#define EFI_AHCI_PORT_SSTS_DET_MASK 0x000F +#define EFI_AHCI_PORT_SSTS_DET 0x0001 +#define EFI_AHCI_PORT_SSTS_DET_PCE 0x0003 +#define EFI_AHCI_PORT_SSTS_SPD_MASK 0x00F0 +#define EFI_AHCI_PORT_SCTL 0x002C +#define EFI_AHCI_PORT_SCTL_DET_MASK 0x000F +#define EFI_AHCI_PORT_SCTL_MASK (~EFI_AHCI_PORT_SCTL_DET_MASK) +#define EFI_AHCI_PORT_SCTL_DET_INIT 0x0001 +#define EFI_AHCI_PORT_SCTL_DET_PHYCOMM 0x0003 +#define EFI_AHCI_PORT_SCTL_SPD_MASK 0x00F0 +#define EFI_AHCI_PORT_SCTL_IPM_MASK 0x0F00 +#define EFI_AHCI_PORT_SCTL_IPM_INIT 0x0300 +#define EFI_AHCI_PORT_SCTL_IPM_PSD 0x0100 +#define EFI_AHCI_PORT_SCTL_IPM_SSD 0x0200 +#define EFI_AHCI_PORT_SERR 0x0030 +#define EFI_AHCI_PORT_SERR_RDIE BIT0 +#define EFI_AHCI_PORT_SERR_RCE BIT1 +#define EFI_AHCI_PORT_SERR_TDIE BIT8 +#define EFI_AHCI_PORT_SERR_PCDIE BIT9 +#define EFI_AHCI_PORT_SERR_PE BIT10 +#define EFI_AHCI_PORT_SERR_IE BIT11 +#define EFI_AHCI_PORT_SERR_PRC BIT16 +#define EFI_AHCI_PORT_SERR_PIE BIT17 +#define EFI_AHCI_PORT_SERR_CW BIT18 +#define EFI_AHCI_PORT_SERR_BDE BIT19 +#define EFI_AHCI_PORT_SERR_DE BIT20 +#define EFI_AHCI_PORT_SERR_CRCE BIT21 +#define EFI_AHCI_PORT_SERR_HE BIT22 +#define EFI_AHCI_PORT_SERR_LSE BIT23 +#define EFI_AHCI_PORT_SERR_TSTE BIT24 +#define EFI_AHCI_PORT_SERR_UFT BIT25 +#define EFI_AHCI_PORT_SERR_EX BIT26 +#define EFI_AHCI_PORT_ERR_CLEAR 0xFFFFFFFF +#define EFI_AHCI_PORT_SACT 0x0034 +#define EFI_AHCI_PORT_CI 0x0038 +#define EFI_AHCI_PORT_SNTF 0x003C +#define AHCI_PORT_DEVSLP 0x0044 +#define AHCI_PORT_DEVSLP_ADSE BIT0 +#define AHCI_PORT_DEVSLP_DSP BIT1 +#define AHCI_PORT_DEVSLP_DETO_MASK 0x000003FC +#define AHCI_PORT_DEVSLP_MDAT_MASK 0x00007C00 +#define AHCI_PORT_DEVSLP_DITO_MASK 0x01FF8000 +#define AHCI_PORT_DEVSLP_DM_MASK 0x1E000000 #define AHCI_COMMAND_RETRIES 5 @@ -200,20 +201,20 @@ typedef union { // The entry data structure is listed at the following. // typedef struct { - UINT32 AhciCmdCfl:5; //Command FIS Length - UINT32 AhciCmdA:1; //ATAPI - UINT32 AhciCmdW:1; //Write - UINT32 AhciCmdP:1; //Prefetchable - UINT32 AhciCmdR:1; //Reset - UINT32 AhciCmdB:1; //BIST - UINT32 AhciCmdC:1; //Clear Busy upon R_OK - UINT32 AhciCmdRsvd:1; - UINT32 AhciCmdPmp:4; //Port Multiplier Port - UINT32 AhciCmdPrdtl:16; //Physical Region Descriptor Table Length - UINT32 AhciCmdPrdbc; //Physical Region Descriptor Byte Count - UINT32 AhciCmdCtba; //Command Table Descriptor Base Address - UINT32 AhciCmdCtbau; //Command Table Descriptor Base Address Upper 32-BITs - UINT32 AhciCmdRsvd1[4]; + UINT32 AhciCmdCfl : 5; // Command FIS Length + UINT32 AhciCmdA : 1; // ATAPI + UINT32 AhciCmdW : 1; // Write + UINT32 AhciCmdP : 1; // Prefetchable + UINT32 AhciCmdR : 1; // Reset + UINT32 AhciCmdB : 1; // BIST + UINT32 AhciCmdC : 1; // Clear Busy upon R_OK + UINT32 AhciCmdRsvd : 1; + UINT32 AhciCmdPmp : 4; // Port Multiplier Port + UINT32 AhciCmdPrdtl : 16; // Physical Region Descriptor Table Length + UINT32 AhciCmdPrdbc; // Physical Region Descriptor Byte Count + UINT32 AhciCmdCtba; // Command Table Descriptor Base Address + UINT32 AhciCmdCtbau; // Command Table Descriptor Base Address Upper 32-BITs + UINT32 AhciCmdRsvd1[4]; } EFI_AHCI_COMMAND_LIST; // @@ -223,11 +224,11 @@ typedef struct { // typedef struct { UINT8 AhciCFisType; - UINT8 AhciCFisPmNum:4; - UINT8 AhciCFisRsvd:1; - UINT8 AhciCFisRsvd1:1; - UINT8 AhciCFisRsvd2:1; - UINT8 AhciCFisCmdInd:1; + UINT8 AhciCFisPmNum : 4; + UINT8 AhciCFisRsvd : 1; + UINT8 AhciCFisRsvd1 : 1; + UINT8 AhciCFisRsvd2 : 1; + UINT8 AhciCFisCmdInd : 1; UINT8 AhciCFisCmd; UINT8 AhciCFisFeature; UINT8 AhciCFisSecNum; @@ -266,12 +267,12 @@ typedef struct { // list entry for this command slot. // typedef struct { - UINT32 AhciPrdtDba; //Data Base Address - UINT32 AhciPrdtDbau; //Data Base Address Upper 32-BITs - UINT32 AhciPrdtRsvd; - UINT32 AhciPrdtDbc:22; //Data Byte Count - UINT32 AhciPrdtRsvd1:9; - UINT32 AhciPrdtIoc:1; //Interrupt on Completion + UINT32 AhciPrdtDba; // Data Base Address + UINT32 AhciPrdtDbau; // Data Base Address Upper 32-BITs + UINT32 AhciPrdtRsvd; + UINT32 AhciPrdtDbc : 22; // Data Byte Count + UINT32 AhciPrdtRsvd1 : 9; + UINT32 AhciPrdtIoc : 1; // Interrupt on Completion } EFI_AHCI_COMMAND_PRDT; // @@ -288,24 +289,24 @@ typedef struct { // Received FIS structure // typedef struct { - UINT8 AhciDmaSetupFis[0x1C]; // Dma Setup Fis: offset 0x00 - UINT8 AhciDmaSetupFisRsvd[0x04]; - UINT8 AhciPioSetupFis[0x14]; // Pio Setup Fis: offset 0x20 - UINT8 AhciPioSetupFisRsvd[0x0C]; - UINT8 AhciD2HRegisterFis[0x14]; // D2H Register Fis: offset 0x40 - UINT8 AhciD2HRegisterFisRsvd[0x04]; - UINT64 AhciSetDeviceBitsFis; // Set Device Bits Fix: offset 0x58 - UINT8 AhciUnknownFis[0x40]; // Unknown Fis: offset 0x60 - UINT8 AhciUnknownFisRsvd[0x60]; + UINT8 AhciDmaSetupFis[0x1C]; // Dma Setup Fis: offset 0x00 + UINT8 AhciDmaSetupFisRsvd[0x04]; + UINT8 AhciPioSetupFis[0x14]; // Pio Setup Fis: offset 0x20 + UINT8 AhciPioSetupFisRsvd[0x0C]; + UINT8 AhciD2HRegisterFis[0x14]; // D2H Register Fis: offset 0x40 + UINT8 AhciD2HRegisterFisRsvd[0x04]; + UINT64 AhciSetDeviceBitsFis; // Set Device Bits Fix: offset 0x58 + UINT8 AhciUnknownFis[0x40]; // Unknown Fis: offset 0x60 + UINT8 AhciUnknownFisRsvd[0x60]; } EFI_AHCI_RECEIVED_FIS; typedef struct { - UINT8 Madt : 5; - UINT8 Reserved_5 : 3; - UINT8 Deto; - UINT16 Reserved_16; - UINT32 Reserved_32 : 31; - UINT32 Supported : 1; + UINT8 Madt : 5; + UINT8 Reserved_5 : 3; + UINT8 Deto; + UINT16 Reserved_16; + UINT32 Reserved_32 : 31; + UINT32 Supported : 1; } DEVSLP_TIMING_VARIABLES; #pragma pack() @@ -343,11 +344,11 @@ typedef struct { EFI_STATUS EFIAPI AhciPacketCommandExecute ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet ); /** @@ -366,10 +367,10 @@ AhciPacketCommandExecute ( EFI_STATUS EFIAPI AhciStartCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT8 CommandSlot, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT8 CommandSlot, + IN UINT64 Timeout ); /** @@ -387,10 +388,9 @@ AhciStartCommand ( EFI_STATUS EFIAPI AhciStopCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Port, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Port, + IN UINT64 Timeout ); #endif - diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c index 1c94b5f39d..1070516b35 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.c @@ -12,7 +12,7 @@ // // EFI_DRIVER_BINDING_PROTOCOL instance // -EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding = { AtaAtapiPassThruSupported, AtaAtapiPassThruStart, AtaAtapiPassThruStop, @@ -21,7 +21,7 @@ EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding = { NULL }; -ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = { +ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = { ATA_ATAPI_PASS_THRU_SIGNATURE, 0, // Controller Handle NULL, // PciIo Protocol @@ -78,8 +78,8 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = { }, EfiAtaUnknownMode, // Work Mode { // IdeRegisters - {0}, - {0} + { 0 }, + { 0 } }, { // AhciRegisters 0 @@ -101,13 +101,13 @@ ATA_ATAPI_PASS_THRU_INSTANCE gAtaAtapiPassThruInstanceTemplate = { } }; -ATAPI_DEVICE_PATH mAtapiDevicePathTemplate = { +ATAPI_DEVICE_PATH mAtapiDevicePathTemplate = { { MESSAGING_DEVICE_PATH, MSG_ATAPI_DP, { - (UINT8) (sizeof (ATAPI_DEVICE_PATH)), - (UINT8) ((sizeof (ATAPI_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (ATAPI_DEVICE_PATH)), + (UINT8)((sizeof (ATAPI_DEVICE_PATH)) >> 8) } }, 0, @@ -115,13 +115,13 @@ ATAPI_DEVICE_PATH mAtapiDevicePathTemplate = { 0 }; -SATA_DEVICE_PATH mSataDevicePathTemplate = { +SATA_DEVICE_PATH mSataDevicePathTemplate = { { MESSAGING_DEVICE_PATH, MSG_SATA_DP, { - (UINT8) (sizeof (SATA_DEVICE_PATH)), - (UINT8) ((sizeof (SATA_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (SATA_DEVICE_PATH)), + (UINT8)((sizeof (SATA_DEVICE_PATH)) >> 8) } }, 0, @@ -129,15 +129,15 @@ SATA_DEVICE_PATH mSataDevicePathTemplate = { 0 }; -UINT8 mScsiId[TARGET_MAX_BYTES] = { +UINT8 mScsiId[TARGET_MAX_BYTES] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; -EDKII_ATA_ATAPI_POLICY_PROTOCOL *mAtaAtapiPolicy; -EDKII_ATA_ATAPI_POLICY_PROTOCOL mDefaultAtaAtapiPolicy = { +EDKII_ATA_ATAPI_POLICY_PROTOCOL *mAtaAtapiPolicy; +EDKII_ATA_ATAPI_POLICY_PROTOCOL mDefaultAtaAtapiPolicy = { EDKII_ATA_ATAPI_POLICY_VERSION, 2, // PuisEnable 0, // DeviceSleepEnable @@ -183,11 +183,11 @@ EDKII_ATA_ATAPI_POLICY_PROTOCOL mDefaultAtaAtapiPolicy = { EFI_STATUS EFIAPI AtaPassThruPassThruExecute ( - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN ATA_NONBLOCK_TASK *Task OPTIONAL + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN ATA_NONBLOCK_TASK *Task OPTIONAL ) { EFI_ATA_PASS_THRU_CMD_PROTOCOL Protocol; @@ -271,11 +271,12 @@ AtaPassThruPassThruExecute ( Task ); break; - default : + default: return EFI_UNSUPPORTED; } + break; - case EfiAtaAhciMode : + case EfiAtaAhciMode: if (PortMultiplierPort == 0xFFFF) { // // If there is no port multiplier, PortMultiplierPort will be 0xFFFF @@ -284,6 +285,7 @@ AtaPassThruPassThruExecute ( // PortMultiplierPort = 0; } + switch (Protocol) { case EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA: Status = AhciNonDataTransfer ( @@ -367,9 +369,10 @@ AtaPassThruPassThruExecute ( Task ); break; - default : + default: return EFI_UNSUPPORTED; } + break; default: @@ -392,16 +395,16 @@ VOID EFIAPI AsyncNonBlockingTransferRoutine ( EFI_EVENT Event, - VOID* Context + VOID *Context ) { - LIST_ENTRY *Entry; - LIST_ENTRY *EntryHeader; - ATA_NONBLOCK_TASK *Task; - EFI_STATUS Status; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Entry; + LIST_ENTRY *EntryHeader; + ATA_NONBLOCK_TASK *Task; + EFI_STATUS Status; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - Instance = (ATA_ATAPI_PASS_THRU_INSTANCE *) Context; + Instance = (ATA_ATAPI_PASS_THRU_INSTANCE *)Context; EntryHeader = &Instance->NonBlockingTaskList; // // Get the Tasks from the Tasks List and execute it, until there is @@ -459,11 +462,11 @@ AsyncNonBlockingTransferRoutine ( EFI_STATUS EFIAPI InitializeAtaAtapiPassThru ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -526,9 +529,9 @@ InitializeAtaAtapiPassThru ( EFI_STATUS EFIAPI AtaAtapiPassThruSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; @@ -544,7 +547,7 @@ AtaAtapiPassThruSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID *) &ParentDevicePath, + (VOID *)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -555,20 +558,21 @@ AtaAtapiPassThruSupported ( // return Status; } + // // Close the protocol because we don't use it here // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); Status = gBS->OpenProtocol ( Controller, &gEfiIdeControllerInitProtocolGuid, - (VOID **) &IdeControllerInit, + (VOID **)&IdeControllerInit, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -585,11 +589,11 @@ AtaAtapiPassThruSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiIdeControllerInitProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiIdeControllerInitProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Now test the EfiPciIoProtocol @@ -597,7 +601,7 @@ AtaAtapiPassThruSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -605,6 +609,7 @@ AtaAtapiPassThruSupported ( if (EFI_ERROR (Status)) { return Status; } + // // Now further check the PCI header: Base class (offset 0x0B) and // Sub Class (offset 0x0A). This controller should be an ATA controller @@ -665,9 +670,9 @@ AtaAtapiPassThruSupported ( EFI_STATUS EFIAPI AtaAtapiPassThruStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; @@ -684,14 +689,14 @@ AtaAtapiPassThruStart ( DEBUG ((DEBUG_INFO, "==AtaAtapiPassThru Start== Controller = %x\n", Controller)); - Status = gBS->OpenProtocol ( - Controller, - &gEfiIdeControllerInitProtocolGuid, - (VOID **) &IdeControllerInit, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiIdeControllerInitProtocolGuid, + (VOID **)&IdeControllerInit, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Open Ide_Controller_Init Error, Status=%r", Status)); @@ -701,7 +706,7 @@ AtaAtapiPassThruStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -730,12 +735,12 @@ AtaAtapiPassThruStart ( ); if (!EFI_ERROR (Status)) { EnabledPciAttributes &= (UINT64)EFI_PCI_DEVICE_ENABLE; - Status = PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationEnable, - EnabledPciAttributes, - NULL - ); + Status = PciIo->Attributes ( + PciIo, + EfiPciIoAttributeOperationEnable, + EnabledPciAttributes, + NULL + ); } if (EFI_ERROR (Status)) { @@ -765,8 +770,8 @@ AtaAtapiPassThruStart ( Instance->OriginalPciAttributes = OriginalPciAttributes; Instance->AtaPassThru.Mode = &Instance->AtaPassThruMode; Instance->ExtScsiPassThru.Mode = &Instance->ExtScsiPassThruMode; - InitializeListHead(&Instance->DeviceList); - InitializeListHead(&Instance->NonBlockingTaskList); + InitializeListHead (&Instance->DeviceList); + InitializeListHead (&Instance->NonBlockingTaskList); Instance->TimerEvent = NULL; @@ -799,8 +804,10 @@ AtaAtapiPassThruStart ( Status = gBS->InstallMultipleProtocolInterfaces ( &Controller, - &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru), - &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru), + &gEfiAtaPassThruProtocolGuid, + &(Instance->AtaPassThru), + &gEfiExtScsiPassThruProtocolGuid, + &(Instance->ExtScsiPassThru), NULL ); ASSERT_EFI_ERROR (Status); @@ -828,6 +835,7 @@ ErrorExit: DestroyDeviceInfoList (Instance); FreePool (Instance); } + return EFI_UNSUPPORTED; } @@ -860,24 +868,24 @@ ErrorExit: EFI_STATUS EFIAPI AtaAtapiPassThruStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_AHCI_REGISTERS *AhciRegisters; + EFI_STATUS Status; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_AHCI_REGISTERS *AhciRegisters; DEBUG ((DEBUG_INFO, "==AtaAtapiPassThru Stop== Controller = %x\n", Controller)); Status = gBS->OpenProtocol ( Controller, &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, + (VOID **)&AtaPassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -891,8 +899,10 @@ AtaAtapiPassThruStop ( Status = gBS->UninstallMultipleProtocolInterfaces ( Controller, - &gEfiAtaPassThruProtocolGuid, &(Instance->AtaPassThru), - &gEfiExtScsiPassThruProtocolGuid, &(Instance->ExtScsiPassThru), + &gEfiAtaPassThruProtocolGuid, + &(Instance->AtaPassThru), + &gEfiExtScsiPassThruProtocolGuid, + &(Instance->ExtScsiPassThru), NULL ); @@ -917,6 +927,7 @@ AtaAtapiPassThruStop ( gBS->CloseEvent (Instance->TimerEvent); Instance->TimerEvent = NULL; } + DestroyAsynTaskList (Instance, FALSE); // // Free allocated resource @@ -947,7 +958,7 @@ AtaAtapiPassThruStop ( ); PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxCommandTableSize), + EFI_SIZE_TO_PAGES ((UINTN)AhciRegisters->MaxCommandTableSize), AhciRegisters->AhciCommandTable ); PciIo->Unmap ( @@ -956,7 +967,7 @@ AtaAtapiPassThruStop ( ); PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxCommandListSize), + EFI_SIZE_TO_PAGES ((UINTN)AhciRegisters->MaxCommandListSize), AhciRegisters->AhciCmdList ); PciIo->Unmap ( @@ -965,7 +976,7 @@ AtaAtapiPassThruStop ( ); PciIo->FreeBuffer ( PciIo, - EFI_SIZE_TO_PAGES ((UINTN) AhciRegisters->MaxReceiveFisSize), + EFI_SIZE_TO_PAGES ((UINTN)AhciRegisters->MaxReceiveFisSize), AhciRegisters->AhciRFis ); } @@ -1002,9 +1013,9 @@ LIST_ENTRY * EFIAPI SearchDeviceInfoList ( IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN UINT16 Port, - IN UINT16 PortMultiplier, - IN EFI_ATA_DEVICE_TYPE DeviceType + IN UINT16 Port, + IN UINT16 PortMultiplier, + IN EFI_ATA_DEVICE_TYPE DeviceType ) { EFI_ATA_DEVICE_INFO *DeviceInfo; @@ -1022,13 +1033,15 @@ SearchDeviceInfoList ( // if ((Instance->Mode == EfiAtaAhciMode) && (DeviceInfo->Type == EfiIdeCdrom) && - (PortMultiplier == 0xFF)) { - PortMultiplier = 0xFFFF; + (PortMultiplier == 0xFF)) + { + PortMultiplier = 0xFFFF; } if ((DeviceInfo->Type == DeviceType) && (Port == DeviceInfo->Port) && - (PortMultiplier == DeviceInfo->PortMultiplier)) { + (PortMultiplier == DeviceInfo->PortMultiplier)) + { return Node; } @@ -1056,11 +1069,11 @@ SearchDeviceInfoList ( EFI_STATUS EFIAPI CreateNewDeviceInfo ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN UINT16 Port, - IN UINT16 PortMultiplier, - IN EFI_ATA_DEVICE_TYPE DeviceType, - IN EFI_IDENTIFY_DATA *IdentifyData + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN UINT16 Port, + IN UINT16 PortMultiplier, + IN EFI_ATA_DEVICE_TYPE DeviceType, + IN EFI_IDENTIFY_DATA *IdentifyData ) { EFI_ATA_DEVICE_INFO *DeviceInfo; @@ -1114,6 +1127,7 @@ DestroyDeviceInfoList ( if (DeviceInfo->IdentifyData != NULL) { FreePool (DeviceInfo->IdentifyData); } + FreePool (DeviceInfo); } } @@ -1129,14 +1143,14 @@ DestroyDeviceInfoList ( VOID EFIAPI DestroyAsynTaskList ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, IN BOOLEAN IsSigEvent ) { - LIST_ENTRY *Entry; - LIST_ENTRY *DelEntry; - ATA_NONBLOCK_TASK *Task; - EFI_TPL OldTpl; + LIST_ENTRY *Entry; + LIST_ENTRY *DelEntry; + ATA_NONBLOCK_TASK *Task; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); if (!IsListEmpty (&Instance->NonBlockingTaskList)) { @@ -1144,8 +1158,9 @@ DestroyAsynTaskList ( // Free the Subtask list. // for (Entry = (&Instance->NonBlockingTaskList)->ForwardLink; - Entry != (&Instance->NonBlockingTaskList); - ) { + Entry != (&Instance->NonBlockingTaskList); + ) + { DelEntry = Entry; Entry = Entry->ForwardLink; Task = ATA_NON_BLOCK_TASK_FROM_ENTRY (DelEntry); @@ -1155,9 +1170,11 @@ DestroyAsynTaskList ( Task->Packet->Asb->AtaStatus = 0x01; gBS->SignalEvent (Task->Event); } + FreePool (Task); } } + gBS->RestoreTPL (OldTpl); } @@ -1175,12 +1192,12 @@ DestroyAsynTaskList ( EFI_STATUS EFIAPI EnumerateAttachedDevice ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ) { - EFI_STATUS Status; - PCI_TYPE00 PciData; - UINT8 ClassCode; + EFI_STATUS Status; + PCI_TYPE00 PciData; + UINT8 ClassCode; Status = EFI_SUCCESS; @@ -1196,7 +1213,7 @@ EnumerateAttachedDevice ( ClassCode = PciData.Hdr.ClassCode[1]; switch (ClassCode) { - case PCI_CLASS_MASS_STORAGE_IDE : + case PCI_CLASS_MASS_STORAGE_IDE: // // The ATA controller is working at IDE mode // @@ -1207,8 +1224,9 @@ EnumerateAttachedDevice ( Status = EFI_DEVICE_ERROR; goto Done; } + break; - case PCI_CLASS_MASS_STORAGE_SATADPA : + case PCI_CLASS_MASS_STORAGE_SATADPA: // // The ATA controller is working at AHCI mode // @@ -1222,7 +1240,7 @@ EnumerateAttachedDevice ( } break; - default : + default: Status = EFI_UNSUPPORTED; } @@ -1262,41 +1280,41 @@ Done: EFI_STATUS EFIAPI AtaPassThruPassThru ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; - EFI_IDENTIFY_DATA *IdentifyData; - UINT64 Capacity; - UINT32 MaxSectorCount; - ATA_NONBLOCK_TASK *Task; - EFI_TPL OldTpl; - UINT32 BlockSize; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; + EFI_IDENTIFY_DATA *IdentifyData; + UINT64 Capacity; + UINT32 MaxSectorCount; + ATA_NONBLOCK_TASK *Task; + EFI_TPL OldTpl; + UINT32 BlockSize; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->Asb, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->Asb, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk); if (Node == NULL) { - Node = SearchDeviceInfoList(Instance, Port, PortMultiplierPort, EfiIdeCdrom); + Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeCdrom); if (Node == NULL) { return EFI_INVALID_PARAMETER; } @@ -1327,7 +1345,7 @@ AtaPassThruPassThru ( // Check logical block size // if ((IdentifyData->AtaData.phy_logic_sector_support & BIT12) != 0) { - BlockSize = (UINT32) (((IdentifyData->AtaData.logic_sector_size_hi << 16) | IdentifyData->AtaData.logic_sector_size_lo) * sizeof (UINT16)); + BlockSize = (UINT32)(((IdentifyData->AtaData.logic_sector_size_hi << 16) | IdentifyData->AtaData.logic_sector_size_lo) * sizeof (UINT16)); } } @@ -1335,7 +1353,8 @@ AtaPassThruPassThru ( // convert the transfer length from sector count to byte. // if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) && - (Packet->InTransferLength != 0)) { + (Packet->InTransferLength != 0)) + { Packet->InTransferLength = Packet->InTransferLength * BlockSize; } @@ -1343,7 +1362,8 @@ AtaPassThruPassThru ( // convert the transfer length from sector count to byte. // if (((Packet->Length & EFI_ATA_PASS_THRU_LENGTH_BYTES) == 0) && - (Packet->OutTransferLength != 0)) { + (Packet->OutTransferLength != 0)) + { Packet->OutTransferLength = Packet->OutTransferLength * BlockSize; } @@ -1353,7 +1373,8 @@ AtaPassThruPassThru ( // is returned. // if (((Packet->InTransferLength != 0) && (Packet->InTransferLength > MaxSectorCount * BlockSize)) || - ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) { + ((Packet->OutTransferLength != 0) && (Packet->OutTransferLength > MaxSectorCount * BlockSize))) + { return EFI_BAD_BUFFER_SIZE; } @@ -1372,7 +1393,7 @@ AtaPassThruPassThru ( Task->Packet = Packet; Task->Event = Event; Task->IsStart = FALSE; - Task->RetryTimes = DivU64x32(Packet->Timeout, 1000) + 1; + Task->RetryTimes = DivU64x32 (Packet->Timeout, 1000) + 1; if (Packet->Timeout == 0) { Task->InfiniteWait = TRUE; } else { @@ -1429,13 +1450,13 @@ AtaPassThruPassThru ( EFI_STATUS EFIAPI AtaPassThruGetNextPort ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN OUT UINT16 *Port + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN OUT UINT16 *Port ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -1468,7 +1489,8 @@ AtaPassThruGetNextPort ( DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node); if ((DeviceInfo->Type == EfiIdeHarddisk) && - (DeviceInfo->Port > *Port)){ + (DeviceInfo->Port > *Port)) + { *Port = DeviceInfo->Port; goto Exit; } @@ -1538,14 +1560,14 @@ Exit: EFI_STATUS EFIAPI AtaPassThruGetNextDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN OUT UINT16 *PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN OUT UINT16 *PortMultiplierPort ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -1570,8 +1592,9 @@ AtaPassThruGetNextDevice ( DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node); if ((DeviceInfo->Type == EfiIdeHarddisk) && - (DeviceInfo->Port == Port) && - (DeviceInfo->PortMultiplier > *PortMultiplierPort)){ + (DeviceInfo->Port == Port) && + (DeviceInfo->PortMultiplier > *PortMultiplierPort)) + { *PortMultiplierPort = DeviceInfo->PortMultiplier; goto Exit; } @@ -1590,7 +1613,8 @@ AtaPassThruGetNextDevice ( DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node); if ((DeviceInfo->Type == EfiIdeHarddisk) && - (DeviceInfo->Port == Port)){ + (DeviceInfo->Port == Port)) + { *PortMultiplierPort = DeviceInfo->PortMultiplier; goto Exit; } @@ -1650,15 +1674,15 @@ Exit: EFI_STATUS EFIAPI AtaPassThruBuildDevicePath ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - EFI_DEV_PATH *DevicePathNode; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; + EFI_DEV_PATH *DevicePathNode; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -1669,7 +1693,7 @@ AtaPassThruBuildDevicePath ( return EFI_INVALID_PARAMETER; } - Node = SearchDeviceInfoList(Instance, Port, PortMultiplierPort, EfiIdeHarddisk); + Node = SearchDeviceInfoList (Instance, Port, PortMultiplierPort, EfiIdeHarddisk); if (Node == NULL) { return EFI_NOT_FOUND; } @@ -1679,8 +1703,9 @@ AtaPassThruBuildDevicePath ( if (DevicePathNode == NULL) { return EFI_OUT_OF_RESOURCES; } - DevicePathNode->Atapi.PrimarySecondary = (UINT8) Port; - DevicePathNode->Atapi.SlaveMaster = (UINT8) PortMultiplierPort; + + DevicePathNode->Atapi.PrimarySecondary = (UINT8)Port; + DevicePathNode->Atapi.SlaveMaster = (UINT8)PortMultiplierPort; DevicePathNode->Atapi.Lun = 0; } else { DevicePathNode = AllocateCopyPool (sizeof (SATA_DEVICE_PATH), &mSataDevicePathTemplate); @@ -1693,7 +1718,7 @@ AtaPassThruBuildDevicePath ( DevicePathNode->Sata.Lun = 0; } - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) DevicePathNode; + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)DevicePathNode; return EFI_SUCCESS; } @@ -1737,22 +1762,22 @@ AtaPassThruBuildDevicePath ( EFI_STATUS EFIAPI AtaPassThruGetDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT16 *Port, - OUT UINT16 *PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT16 *Port, + OUT UINT16 *PortMultiplierPort ) { - EFI_DEV_PATH *DevicePathNode; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; + EFI_DEV_PATH *DevicePathNode; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); // // Validate parameters passed in. // - if (DevicePath == NULL || Port == NULL || PortMultiplierPort == NULL) { + if ((DevicePath == NULL) || (Port == NULL) || (PortMultiplierPort == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1761,13 +1786,14 @@ AtaPassThruGetDevice ( // if ((DevicePath->Type != MESSAGING_DEVICE_PATH) || ((DevicePath->SubType != MSG_SATA_DP) && - (DevicePath->SubType != MSG_ATAPI_DP)) || - ((DevicePathNodeLength(DevicePath) != sizeof(ATAPI_DEVICE_PATH)) && - (DevicePathNodeLength(DevicePath) != sizeof(SATA_DEVICE_PATH)))) { + (DevicePath->SubType != MSG_ATAPI_DP)) || + ((DevicePathNodeLength (DevicePath) != sizeof (ATAPI_DEVICE_PATH)) && + (DevicePathNodeLength (DevicePath) != sizeof (SATA_DEVICE_PATH)))) + { return EFI_UNSUPPORTED; } - DevicePathNode = (EFI_DEV_PATH *) DevicePath; + DevicePathNode = (EFI_DEV_PATH *)DevicePath; if (Instance->Mode == EfiAtaIdeMode) { *Port = DevicePathNode->Atapi.PrimarySecondary; @@ -1777,7 +1803,7 @@ AtaPassThruGetDevice ( *PortMultiplierPort = DevicePathNode->Sata.PortMultiplierPortNumber; } - Node = SearchDeviceInfoList(Instance, *Port, *PortMultiplierPort, EfiIdeHarddisk); + Node = SearchDeviceInfoList (Instance, *Port, *PortMultiplierPort, EfiIdeHarddisk); if (Node == NULL) { return EFI_NOT_FOUND; @@ -1813,8 +1839,8 @@ AtaPassThruGetDevice ( EFI_STATUS EFIAPI AtaPassThruResetPort ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port ) { // @@ -1857,13 +1883,13 @@ AtaPassThruResetPort ( EFI_STATUS EFIAPI AtaPassThruResetDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; Instance = ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -1900,12 +1926,12 @@ AtaPassThruResetDevice ( EFI_STATUS EFIAPI AtaPacketRequestSense ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN VOID *SenseData, - IN UINT8 SenseDataLength, - IN UINT64 Timeout + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN VOID *SenseData, + IN UINT8 SenseDataLength, + IN UINT64 Timeout ) { EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET Packet; @@ -1974,24 +2000,24 @@ AtaPacketRequestSense ( EFI_STATUS EFIAPI ExtScsiPassThruPassThru ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { - EFI_STATUS Status; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - UINT8 Port; - UINT8 PortMultiplier; - EFI_ATA_HC_WORK_MODE Mode; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; - BOOLEAN SenseReq; - EFI_SCSI_SENSE_DATA *PtrSenseData; - UINTN SenseDataLen; - EFI_STATUS SenseStatus; + EFI_STATUS Status; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + UINT8 Port; + UINT8 PortMultiplier; + EFI_ATA_HC_WORK_MODE Mode; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; + BOOLEAN SenseReq; + EFI_SCSI_SENSE_DATA *PtrSenseData; + UINTN SenseDataLen; + EFI_STATUS SenseStatus; SenseDataLen = 0; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -2004,7 +2030,8 @@ ExtScsiPassThruPassThru ( // Don't support variable length CDB // if ((Packet->CdbLength != 6) && (Packet->CdbLength != 10) && - (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) { + (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) + { return EFI_INVALID_PARAMETER; } @@ -2012,15 +2039,15 @@ ExtScsiPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } @@ -2045,7 +2072,7 @@ ExtScsiPassThruPassThru ( Port = Target[0]; PortMultiplier = Target[1]; - Node = SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom); + Node = SearchDeviceInfoList (Instance, Port, PortMultiplier, EfiIdeCdrom); if (Node == NULL) { return EFI_INVALID_PARAMETER; } @@ -2057,7 +2084,7 @@ ExtScsiPassThruPassThru ( // Normally it should NOT be passed down through ExtScsiPassThru protocol interface. // But to response EFI_DISK_INFO.Identify() request from ScsiDisk, we should handle this command. // - if (*((UINT8*)Packet->Cdb) == ATA_CMD_IDENTIFY_DEVICE) { + if (*((UINT8 *)Packet->Cdb) == ATA_CMD_IDENTIFY_DEVICE) { CopyMem (Packet->InDataBuffer, DeviceInfo->IdentifyData, sizeof (EFI_IDENTIFY_DATA)); // // For IDENTIFY DEVICE cmd, we don't need to get sense data. @@ -2088,9 +2115,10 @@ ExtScsiPassThruPassThru ( // PortMultiplier = 0; } + Status = AhciPacketCommandExecute (Instance->PciIo, &Instance->AhciRegisters, Port, PortMultiplier, Packet); break; - default : + default: Status = EFI_DEVICE_ERROR; break; } @@ -2098,7 +2126,7 @@ ExtScsiPassThruPassThru ( // // If the cmd doesn't get executed correctly, then check sense data. // - if (EFI_ERROR (Status) && (Packet->SenseDataLength != 0) && (*((UINT8*)Packet->Cdb) != ATA_CMD_REQUEST_SENSE)) { + if (EFI_ERROR (Status) && (Packet->SenseDataLength != 0) && (*((UINT8 *)Packet->Cdb) != ATA_CMD_REQUEST_SENSE)) { PtrSenseData = AllocateAlignedPages (EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA)), This->Mode->IoAlign); if (PtrSenseData == NULL) { return EFI_DEVICE_ERROR; @@ -2117,7 +2145,7 @@ ExtScsiPassThruPassThru ( break; } - CopyMem ((UINT8*)Packet->SenseData + SenseDataLen, PtrSenseData, sizeof (EFI_SCSI_SENSE_DATA)); + CopyMem ((UINT8 *)Packet->SenseData + SenseDataLen, PtrSenseData, sizeof (EFI_SCSI_SENSE_DATA)); SenseDataLen += sizeof (EFI_SCSI_SENSE_DATA); // @@ -2125,12 +2153,15 @@ ExtScsiPassThruPassThru ( // skip the loop. // if ((PtrSenseData->Sense_Key == EFI_SCSI_SK_NO_SENSE) || - (SenseDataLen + sizeof (EFI_SCSI_SENSE_DATA) > Packet->SenseDataLength)) { + (SenseDataLen + sizeof (EFI_SCSI_SENSE_DATA) > Packet->SenseDataLength)) + { SenseReq = FALSE; } } + FreeAlignedPages (PtrSenseData, EFI_SIZE_TO_PAGES (sizeof (EFI_SCSI_SENSE_DATA))); } + // // Update the SenseDataLength field to the data length received. // @@ -2167,20 +2198,20 @@ ExtScsiPassThruPassThru ( EFI_STATUS EFIAPI ExtScsiPassThruGetNextTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target, - IN OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target, + IN OUT UINT64 *Lun ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; - UINT8 *Target8; - UINT16 *Target16; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; + UINT8 *Target8; + UINT16 *Target16; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if (Target == NULL || Lun == NULL) { + if ((Target == NULL) || (Lun == NULL)) { return EFI_INVALID_PARAMETER; } @@ -2191,7 +2222,7 @@ ExtScsiPassThruGetNextTargetLun ( Target8 = *Target; Target16 = (UINT16 *)*Target; - if (CompareMem(Target8, mScsiId, TARGET_MAX_BYTES) != 0) { + if (CompareMem (Target8, mScsiId, TARGET_MAX_BYTES) != 0) { // // For ATAPI device, we use 2 least significant bytes to represent the location of SCSI device. // So the higher bytes in Target array should be 0xFF. @@ -2205,7 +2236,8 @@ ExtScsiPassThruGetNextTargetLun ( // previous target id to see if it is returned by previous call. // if ((*Target16 != Instance->PreviousTargetId) || - (*Lun != Instance->PreviousLun)) { + (*Lun != Instance->PreviousLun)) + { return EFI_INVALID_PARAMETER; } @@ -2223,9 +2255,10 @@ ExtScsiPassThruGetNextTargetLun ( DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node); if ((DeviceInfo->Type == EfiIdeCdrom) && - ((Target8[0] < DeviceInfo->Port) || - ((Target8[0] == DeviceInfo->Port) && - (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) { + ((Target8[0] < DeviceInfo->Port) || + ((Target8[0] == DeviceInfo->Port) && + (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) + { Target8[0] = (UINT8)DeviceInfo->Port; Target8[1] = (UINT8)DeviceInfo->PortMultiplier; goto Exit; @@ -2297,16 +2330,16 @@ Exit: EFI_STATUS EFIAPI ExtScsiPassThruBuildDevicePath ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - EFI_DEV_PATH *DevicePathNode; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - UINT8 Port; - UINT8 PortMultiplier; + EFI_DEV_PATH *DevicePathNode; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + UINT8 Port; + UINT8 PortMultiplier; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -2327,7 +2360,7 @@ ExtScsiPassThruBuildDevicePath ( return EFI_NOT_FOUND; } - if (SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom) == NULL) { + if (SearchDeviceInfoList (Instance, Port, PortMultiplier, EfiIdeCdrom) == NULL) { return EFI_NOT_FOUND; } @@ -2339,14 +2372,14 @@ ExtScsiPassThruBuildDevicePath ( DevicePathNode->Atapi.PrimarySecondary = Port; DevicePathNode->Atapi.SlaveMaster = PortMultiplier; - DevicePathNode->Atapi.Lun = (UINT16) Lun; + DevicePathNode->Atapi.Lun = (UINT16)Lun; } else { DevicePathNode = AllocateCopyPool (sizeof (SATA_DEVICE_PATH), &mSataDevicePathTemplate); if (DevicePathNode == NULL) { return EFI_OUT_OF_RESOURCES; } - DevicePathNode->Sata.HBAPortNumber = Port; + DevicePathNode->Sata.HBAPortNumber = Port; // // For CD-ROM working in the AHCI mode, only 8 bits are used to record // the PortMultiplier information. If the CD-ROM is directly attached @@ -2354,10 +2387,10 @@ ExtScsiPassThruBuildDevicePath ( // to 0xFFFF according to the UEFI spec. // DevicePathNode->Sata.PortMultiplierPortNumber = PortMultiplier == 0xFF ? 0xFFFF : PortMultiplier; - DevicePathNode->Sata.Lun = (UINT16) Lun; + DevicePathNode->Sata.Lun = (UINT16)Lun; } - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) DevicePathNode; + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)DevicePathNode; return EFI_SUCCESS; } @@ -2384,54 +2417,56 @@ ExtScsiPassThruBuildDevicePath ( EFI_STATUS EFIAPI ExtScsiPassThruGetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 **Target, + OUT UINT64 *Lun ) { - EFI_DEV_PATH *DevicePathNode; - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; + EFI_DEV_PATH *DevicePathNode; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); // // Validate parameters passed in. // - if (DevicePath == NULL || Target == NULL || Lun == NULL) { + if ((DevicePath == NULL) || (Target == NULL) || (Lun == NULL)) { return EFI_INVALID_PARAMETER; } if (*Target == NULL) { return EFI_INVALID_PARAMETER; } + // // Check whether the DevicePath belongs to SCSI_DEVICE_PATH // if ((DevicePath->Type != MESSAGING_DEVICE_PATH) || ((DevicePath->SubType != MSG_ATAPI_DP) && - (DevicePath->SubType != MSG_SATA_DP)) || - ((DevicePathNodeLength(DevicePath) != sizeof(ATAPI_DEVICE_PATH)) && - (DevicePathNodeLength(DevicePath) != sizeof(SATA_DEVICE_PATH)))) { + (DevicePath->SubType != MSG_SATA_DP)) || + ((DevicePathNodeLength (DevicePath) != sizeof (ATAPI_DEVICE_PATH)) && + (DevicePathNodeLength (DevicePath) != sizeof (SATA_DEVICE_PATH)))) + { return EFI_UNSUPPORTED; } SetMem (*Target, TARGET_MAX_BYTES, 0xFF); - DevicePathNode = (EFI_DEV_PATH *) DevicePath; + DevicePathNode = (EFI_DEV_PATH *)DevicePath; if (Instance->Mode == EfiAtaIdeMode) { - (*Target)[0] = (UINT8) DevicePathNode->Atapi.PrimarySecondary; - (*Target)[1] = (UINT8) DevicePathNode->Atapi.SlaveMaster; - *Lun = (UINT8) DevicePathNode->Atapi.Lun; + (*Target)[0] = (UINT8)DevicePathNode->Atapi.PrimarySecondary; + (*Target)[1] = (UINT8)DevicePathNode->Atapi.SlaveMaster; + *Lun = (UINT8)DevicePathNode->Atapi.Lun; } else { - (*Target)[0] = (UINT8) DevicePathNode->Sata.HBAPortNumber; - (*Target)[1] = (UINT8) DevicePathNode->Sata.PortMultiplierPortNumber; - *Lun = (UINT8) DevicePathNode->Sata.Lun; + (*Target)[0] = (UINT8)DevicePathNode->Sata.HBAPortNumber; + (*Target)[1] = (UINT8)DevicePathNode->Sata.PortMultiplierPortNumber; + *Lun = (UINT8)DevicePathNode->Sata.Lun; } - Node = SearchDeviceInfoList(Instance, (*Target)[0], (*Target)[1], EfiIdeCdrom); + Node = SearchDeviceInfoList (Instance, (*Target)[0], (*Target)[1], EfiIdeCdrom); if (Node == NULL) { return EFI_NOT_FOUND; @@ -2458,7 +2493,7 @@ ExtScsiPassThruGetTargetLun ( EFI_STATUS EFIAPI ExtScsiPassThruResetChannel ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This ) { // @@ -2489,15 +2524,15 @@ ExtScsiPassThruResetChannel ( EFI_STATUS EFIAPI ExtScsiPassThruResetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - UINT8 Port; - UINT8 PortMultiplier; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + UINT8 Port; + UINT8 PortMultiplier; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); // @@ -2506,6 +2541,7 @@ ExtScsiPassThruResetTargetLun ( if (Lun != 0) { return EFI_INVALID_PARAMETER; } + // // The layout of Target array: // ________________________________________________________________________ @@ -2520,7 +2556,7 @@ ExtScsiPassThruResetTargetLun ( Port = Target[0]; PortMultiplier = Target[1]; - Node = SearchDeviceInfoList(Instance, Port, PortMultiplier, EfiIdeCdrom); + Node = SearchDeviceInfoList (Instance, Port, PortMultiplier, EfiIdeCdrom); if (Node == NULL) { return EFI_INVALID_PARAMETER; } @@ -2556,26 +2592,26 @@ ExtScsiPassThruResetTargetLun ( EFI_STATUS EFIAPI ExtScsiPassThruGetNextTarget ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target ) { - ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - LIST_ENTRY *Node; - EFI_ATA_DEVICE_INFO *DeviceInfo; - UINT8 *Target8; - UINT16 *Target16; + ATA_ATAPI_PASS_THRU_INSTANCE *Instance; + LIST_ENTRY *Node; + EFI_ATA_DEVICE_INFO *DeviceInfo; + UINT8 *Target8; + UINT16 *Target16; Instance = EXT_SCSI_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if (Target == NULL || *Target == NULL) { + if ((Target == NULL) || (*Target == NULL)) { return EFI_INVALID_PARAMETER; } Target8 = *Target; Target16 = (UINT16 *)*Target; - if (CompareMem(Target8, mScsiId, TARGET_MAX_BYTES) != 0) { + if (CompareMem (Target8, mScsiId, TARGET_MAX_BYTES) != 0) { // // For ATAPI device, we use 2 least significant bytes to represent the location of SCSI device. // So the higher bytes in Target array should be 0xFF. @@ -2605,9 +2641,10 @@ ExtScsiPassThruGetNextTarget ( DeviceInfo = ATA_ATAPI_DEVICE_INFO_FROM_THIS (Node); if ((DeviceInfo->Type == EfiIdeCdrom) && - ((Target8[0] < DeviceInfo->Port) || - ((Target8[0] == DeviceInfo->Port) && - (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) { + ((Target8[0] < DeviceInfo->Port) || + ((Target8[0] == DeviceInfo->Port) && + (Target8[1] < (UINT8)DeviceInfo->PortMultiplier)))) + { Target8[0] = (UINT8)DeviceInfo->Port; Target8[1] = (UINT8)DeviceInfo->PortMultiplier; goto Exit; diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h index 5f582b9b3e..62ba6d6680 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.h @@ -5,6 +5,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __ATA_ATAPI_PASS_THRU_H__ #define __ATA_ATAPI_PASS_THRU_H__ @@ -36,14 +37,14 @@ #include "IdeMode.h" #include "AhciMode.h" -extern EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gAtaAtapiPassThruComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gAtaAtapiPassThruComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gAtaAtapiPassThruDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gAtaAtapiPassThruComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gAtaAtapiPassThruComponentName2; -extern EDKII_ATA_ATAPI_POLICY_PROTOCOL *mAtaAtapiPolicy; +extern EDKII_ATA_ATAPI_POLICY_PROTOCOL *mAtaAtapiPolicy; -#define ATA_ATAPI_PASS_THRU_SIGNATURE SIGNATURE_32 ('a', 'a', 'p', 't') -#define ATA_ATAPI_DEVICE_SIGNATURE SIGNATURE_32 ('a', 'd', 'e', 'v') +#define ATA_ATAPI_PASS_THRU_SIGNATURE SIGNATURE_32 ('a', 'a', 'p', 't') +#define ATA_ATAPI_DEVICE_SIGNATURE SIGNATURE_32 ('a', 'd', 'e', 'v') #define ATA_NONBLOCKING_TASK_SIGNATURE SIGNATURE_32 ('a', 't', 's', 'k') typedef struct _ATA_NONBLOCK_TASK ATA_NONBLOCK_TASK; @@ -66,88 +67,88 @@ typedef enum { // Ahci mode device info // typedef struct { - UINT32 Signature; - LIST_ENTRY Link; + UINT32 Signature; + LIST_ENTRY Link; - UINT16 Port; - UINT16 PortMultiplier; - EFI_ATA_DEVICE_TYPE Type; + UINT16 Port; + UINT16 PortMultiplier; + EFI_ATA_DEVICE_TYPE Type; - EFI_IDENTIFY_DATA *IdentifyData; + EFI_IDENTIFY_DATA *IdentifyData; } EFI_ATA_DEVICE_INFO; typedef struct { - UINT32 Signature; + UINT32 Signature; - EFI_HANDLE ControllerHandle; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeControllerInit; + EFI_HANDLE ControllerHandle; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeControllerInit; - EFI_ATA_PASS_THRU_MODE AtaPassThruMode; - EFI_ATA_PASS_THRU_PROTOCOL AtaPassThru; - EFI_EXT_SCSI_PASS_THRU_MODE ExtScsiPassThruMode; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL ExtScsiPassThru; + EFI_ATA_PASS_THRU_MODE AtaPassThruMode; + EFI_ATA_PASS_THRU_PROTOCOL AtaPassThru; + EFI_EXT_SCSI_PASS_THRU_MODE ExtScsiPassThruMode; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL ExtScsiPassThru; - EFI_ATA_HC_WORK_MODE Mode; + EFI_ATA_HC_WORK_MODE Mode; - EFI_IDE_REGISTERS IdeRegisters[EfiIdeMaxChannel]; - EFI_AHCI_REGISTERS AhciRegisters; + EFI_IDE_REGISTERS IdeRegisters[EfiIdeMaxChannel]; + EFI_AHCI_REGISTERS AhciRegisters; // // The attached device list // - LIST_ENTRY DeviceList; - UINT64 EnabledPciAttributes; - UINT64 OriginalPciAttributes; + LIST_ENTRY DeviceList; + UINT64 EnabledPciAttributes; + UINT64 OriginalPciAttributes; // // For AtaPassThru protocol, using the following bytes to record the previous call in // GetNextPort()/GetNextDevice(). // - UINT16 PreviousPort; - UINT16 PreviousPortMultiplier; + UINT16 PreviousPort; + UINT16 PreviousPortMultiplier; // // For ExtScsiPassThru protocol, using the following bytes to record the previous call in // GetNextTarget()/GetNextTargetLun(). // - UINT16 PreviousTargetId; - UINT64 PreviousLun; + UINT16 PreviousTargetId; + UINT64 PreviousLun; // // For Non-blocking. // - EFI_EVENT TimerEvent; - LIST_ENTRY NonBlockingTaskList; + EFI_EVENT TimerEvent; + LIST_ENTRY NonBlockingTaskList; } ATA_ATAPI_PASS_THRU_INSTANCE; // // Task for Non-blocking mode. // struct _ATA_NONBLOCK_TASK { - UINT32 Signature; - LIST_ENTRY Link; - - UINT16 Port; - UINT16 PortMultiplier; - EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet; - BOOLEAN IsStart; - EFI_EVENT Event; - UINT64 RetryTimes; - BOOLEAN InfiniteWait; - VOID *Map; // Pointer to map. - VOID *TableMap; // Pointer to PRD table map. - EFI_ATA_DMA_PRD *MapBaseAddress; // Pointer to range Base address for Map. - UINTN PageCount; // The page numbers used by PCIO freebuffer. + UINT32 Signature; + LIST_ENTRY Link; + + UINT16 Port; + UINT16 PortMultiplier; + EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet; + BOOLEAN IsStart; + EFI_EVENT Event; + UINT64 RetryTimes; + BOOLEAN InfiniteWait; + VOID *Map; // Pointer to map. + VOID *TableMap; // Pointer to PRD table map. + EFI_ATA_DMA_PRD *MapBaseAddress; // Pointer to range Base address for Map. + UINTN PageCount; // The page numbers used by PCIO freebuffer. }; // // Timeout value which uses 100ns as a unit. // It means 3 second span. // -#define ATA_ATAPI_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) -#define ATA_SPINUP_TIMEOUT EFI_TIMER_PERIOD_SECONDS(10) +#define ATA_ATAPI_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) +#define ATA_SPINUP_TIMEOUT EFI_TIMER_PERIOD_SECONDS(10) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define ATA_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ @@ -295,11 +296,11 @@ AtaAtapiPassThruComponentNameGetDriverName ( EFI_STATUS EFIAPI AtaAtapiPassThruComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -347,9 +348,9 @@ AtaAtapiPassThruComponentNameGetControllerName ( EFI_STATUS EFIAPI AtaAtapiPassThruSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -390,9 +391,9 @@ AtaAtapiPassThruSupported ( EFI_STATUS EFIAPI AtaAtapiPassThruStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -424,10 +425,10 @@ AtaAtapiPassThruStart ( EFI_STATUS EFIAPI AtaAtapiPassThruStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -446,9 +447,9 @@ LIST_ENTRY * EFIAPI SearchDeviceInfoList ( IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN UINT16 Port, - IN UINT16 PortMultiplier, - IN EFI_ATA_DEVICE_TYPE DeviceType + IN UINT16 Port, + IN UINT16 PortMultiplier, + IN EFI_ATA_DEVICE_TYPE DeviceType ); /** @@ -470,10 +471,10 @@ EFI_STATUS EFIAPI CreateNewDeviceInfo ( IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN UINT16 Port, - IN UINT16 PortMultiplier, - IN EFI_ATA_DEVICE_TYPE DeviceType, - IN EFI_IDENTIFY_DATA *IdentifyData + IN UINT16 Port, + IN UINT16 PortMultiplier, + IN EFI_ATA_DEVICE_TYPE DeviceType, + IN EFI_IDENTIFY_DATA *IdentifyData ); /** @@ -499,7 +500,7 @@ DestroyDeviceInfoList ( VOID EFIAPI DestroyAsynTaskList ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, IN BOOLEAN IsSigEvent ); @@ -517,7 +518,7 @@ DestroyAsynTaskList ( EFI_STATUS EFIAPI EnumerateAttachedDevice ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ); /** @@ -532,7 +533,7 @@ VOID EFIAPI AsyncNonBlockingTransferRoutine ( EFI_EVENT Event, - VOID* Context + VOID *Context ); /** @@ -567,11 +568,11 @@ AsyncNonBlockingTransferRoutine ( EFI_STATUS EFIAPI AtaPassThruPassThru ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ); /** @@ -608,8 +609,8 @@ AtaPassThruPassThru ( EFI_STATUS EFIAPI AtaPassThruGetNextPort ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN OUT UINT16 *Port + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN OUT UINT16 *Port ); /** @@ -657,9 +658,9 @@ AtaPassThruGetNextPort ( EFI_STATUS EFIAPI AtaPassThruGetNextDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN OUT UINT16 *PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN OUT UINT16 *PortMultiplierPort ); /** @@ -697,10 +698,10 @@ AtaPassThruGetNextDevice ( EFI_STATUS EFIAPI AtaPassThruBuildDevicePath ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -743,10 +744,10 @@ AtaPassThruBuildDevicePath ( EFI_STATUS EFIAPI AtaPassThruGetDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT16 *Port, - OUT UINT16 *PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT16 *Port, + OUT UINT16 *PortMultiplierPort ); /** @@ -776,8 +777,8 @@ AtaPassThruGetDevice ( EFI_STATUS EFIAPI AtaPassThruResetPort ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port ); /** @@ -814,9 +815,9 @@ AtaPassThruResetPort ( EFI_STATUS EFIAPI AtaPassThruResetDevice ( - IN EFI_ATA_PASS_THRU_PROTOCOL *This, - IN UINT16 Port, - IN UINT16 PortMultiplierPort + IN EFI_ATA_PASS_THRU_PROTOCOL *This, + IN UINT16 Port, + IN UINT16 PortMultiplierPort ); /** @@ -863,11 +864,11 @@ AtaPassThruResetDevice ( EFI_STATUS EFIAPI ExtScsiPassThruPassThru ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ); /** @@ -899,9 +900,9 @@ ExtScsiPassThruPassThru ( EFI_STATUS EFIAPI ExtScsiPassThruGetNextTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target, - IN OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target, + IN OUT UINT64 *Lun ); /** @@ -934,10 +935,10 @@ ExtScsiPassThruGetNextTargetLun ( EFI_STATUS EFIAPI ExtScsiPassThruBuildDevicePath ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -962,10 +963,10 @@ ExtScsiPassThruBuildDevicePath ( EFI_STATUS EFIAPI ExtScsiPassThruGetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 **Target, + OUT UINT64 *Lun ); /** @@ -982,7 +983,7 @@ ExtScsiPassThruGetTargetLun ( EFI_STATUS EFIAPI ExtScsiPassThruResetChannel ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This ); /** @@ -1007,9 +1008,9 @@ ExtScsiPassThruResetChannel ( EFI_STATUS EFIAPI ExtScsiPassThruResetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun ); /** @@ -1037,8 +1038,8 @@ ExtScsiPassThruResetTargetLun ( EFI_STATUS EFIAPI ExtScsiPassThruGetNextTarget ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target ); /** @@ -1052,7 +1053,7 @@ ExtScsiPassThruGetNextTarget ( EFI_STATUS EFIAPI IdeModeInitialization ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ); /** @@ -1066,7 +1067,7 @@ IdeModeInitialization ( EFI_STATUS EFIAPI AhciModeInitialization ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ); /** @@ -1094,16 +1095,16 @@ AhciModeInitialization ( EFI_STATUS EFIAPI AhciNonDataTransfer ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ); /** @@ -1134,19 +1135,19 @@ AhciNonDataTransfer ( EFI_STATUS EFIAPI AhciDmaTransfer ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ); /** @@ -1177,19 +1178,19 @@ AhciDmaTransfer ( EFI_STATUS EFIAPI AhciPioTransfer ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_AHCI_REGISTERS *AhciRegisters, - IN UINT8 Port, - IN UINT8 PortMultiplier, - IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, - IN UINT8 AtapiCommandLength, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN OUT VOID *MemoryAddr, - IN UINT32 DataCount, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_AHCI_REGISTERS *AhciRegisters, + IN UINT8 Port, + IN UINT8 PortMultiplier, + IN EFI_AHCI_ATAPI_COMMAND *AtapiCommand OPTIONAL, + IN UINT8 AtapiCommandLength, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN OUT VOID *MemoryAddr, + IN UINT32 DataCount, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ); /** @@ -1213,12 +1214,12 @@ AhciPioTransfer ( EFI_STATUS EFIAPI AtaNonDataCommandIn ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ); /** @@ -1284,16 +1285,15 @@ AtaUdmaInOut ( EFI_STATUS EFIAPI AtaPioDataInOut ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN OUT VOID *Buffer, - IN UINT64 ByteCount, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN OUT VOID *Buffer, + IN UINT64 ByteCount, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ); #endif - diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/ComponentName.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/ComponentName.c index 663f777e15..cda5dbe8cd 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/ComponentName.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/ComponentName.c @@ -11,22 +11,22 @@ // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruDriverNameTable[] = { { "eng;en", L"AtaAtapiPassThru Driver" }, - { NULL , NULL } + { NULL, NULL } }; // // Controller name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruIdeControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruIdeControllerNameTable[] = { { "eng;en", L"IDE Controller" }, - { NULL , NULL } + { NULL, NULL } }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruAhciControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaAtapiPassThruAhciControllerNameTable[] = { { "eng;en", L"AHCI Controller" }, - { NULL , NULL } + { NULL, NULL } }; // @@ -41,9 +41,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gAtaAtapiPassThruComp // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gAtaAtapiPassThruComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) AtaAtapiPassThruComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) AtaAtapiPassThruComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gAtaAtapiPassThruComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)AtaAtapiPassThruComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)AtaAtapiPassThruComponentNameGetControllerName, "en" }; @@ -103,7 +103,6 @@ AtaAtapiPassThruComponentNameGetDriverName ( ); } - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -175,11 +174,11 @@ AtaAtapiPassThruComponentNameGetDriverName ( EFI_STATUS EFIAPI AtaAtapiPassThruComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { EFI_STATUS Status; @@ -187,7 +186,7 @@ AtaAtapiPassThruComponentNameGetControllerName ( VOID *Interface; ATA_ATAPI_PASS_THRU_INSTANCE *Instance; - if (Language == NULL || ControllerName == NULL) { + if ((Language == NULL) || (ControllerName == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.c b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.c index 9a6d0e60e4..75403886e4 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.c +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.c @@ -19,11 +19,11 @@ UINT8 EFIAPI IdeReadPortB ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port ) { - UINT8 Data; + UINT8 Data; ASSERT (PciIo != NULL); @@ -35,7 +35,7 @@ IdeReadPortB ( PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, 1, &Data ); @@ -52,9 +52,9 @@ IdeReadPortB ( VOID EFIAPI IdeWritePortB ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port, - IN UINT8 Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port, + IN UINT8 Data ) { ASSERT (PciIo != NULL); @@ -66,7 +66,7 @@ IdeWritePortB ( PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, 1, &Data ); @@ -82,9 +82,9 @@ IdeWritePortB ( VOID EFIAPI IdeWritePortW ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port, - IN UINT16 Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port, + IN UINT16 Data ) { ASSERT (PciIo != NULL); @@ -96,7 +96,7 @@ IdeWritePortW ( PciIo, EfiPciIoWidthUint16, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, 1, &Data ); @@ -112,9 +112,9 @@ IdeWritePortW ( VOID EFIAPI IdeWritePortDW ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port, - IN UINT32 Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port, + IN UINT32 Data ) { ASSERT (PciIo != NULL); @@ -126,7 +126,7 @@ IdeWritePortDW ( PciIo, EfiPciIoWidthUint32, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, 1, &Data ); @@ -146,10 +146,10 @@ IdeWritePortDW ( VOID EFIAPI IdeWritePortWMultiple ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port, - IN UINTN Count, - IN VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port, + IN UINTN Count, + IN VOID *Buffer ) { ASSERT (PciIo != NULL); @@ -162,11 +162,10 @@ IdeWritePortWMultiple ( PciIo, EfiPciIoWidthFifoUint16, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, Count, - (UINT16 *) Buffer + (UINT16 *)Buffer ); - } /** @@ -183,10 +182,10 @@ IdeWritePortWMultiple ( VOID EFIAPI IdeReadPortWMultiple ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT16 Port, - IN UINTN Count, - IN VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT16 Port, + IN UINTN Count, + IN VOID *Buffer ) { ASSERT (PciIo != NULL); @@ -199,11 +198,10 @@ IdeReadPortWMultiple ( PciIo, EfiPciIoWidthFifoUint16, EFI_PCI_IO_PASS_THROUGH_BAR, - (UINT64) Port, + (UINT64)Port, Count, - (UINT16 *) Buffer + (UINT16 *)Buffer ); - } /** @@ -219,12 +217,12 @@ IdeReadPortWMultiple ( VOID EFIAPI DumpAllIdeRegisters ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_ATA_STATUS_BLOCK StatusBlock; + EFI_ATA_STATUS_BLOCK StatusBlock; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -284,6 +282,7 @@ DumpAllIdeRegisters ( DEBUG ((DEBUG_ERROR, "CheckRegisterStatus()-- %02x : Error : Address Mark Not Found\n", StatusBlock.AtaError)); } } + DEBUG_CODE_END (); } @@ -301,11 +300,11 @@ DumpAllIdeRegisters ( EFI_STATUS EFIAPI CheckStatusRegister ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters ) { - UINT8 StatusRegister; + UINT8 StatusRegister; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -319,6 +318,7 @@ CheckStatusRegister ( return EFI_DEVICE_ERROR; } } + return EFI_SUCCESS; } @@ -342,14 +342,14 @@ CheckStatusRegister ( EFI_STATUS EFIAPI DRQClear ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN UINT64 Timeout ) { - UINT64 Delay; - UINT8 StatusRegister; - BOOLEAN InfiniteWait; + UINT64 Delay; + UINT8 StatusRegister; + BOOLEAN InfiniteWait; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -360,7 +360,7 @@ DRQClear ( InfiniteWait = FALSE; } - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus); @@ -381,11 +381,11 @@ DRQClear ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; } + /** This function is used to poll for the DRQ bit clear in the Alternate Status Register. DRQ is cleared when the device is finished @@ -410,9 +410,9 @@ DRQClear2 ( IN UINT64 Timeout ) { - UINT64 Delay; - UINT8 AltRegister; - BOOLEAN InfiniteWait; + UINT64 Delay; + UINT8 AltRegister; + BOOLEAN InfiniteWait; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -423,7 +423,7 @@ DRQClear2 ( InfiniteWait = FALSE; } - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { AltRegister = IdeReadPortB (PciIo, IdeRegisters->AltOrDev); @@ -444,7 +444,6 @@ DRQClear2 ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -485,10 +484,10 @@ DRQReady ( IN UINT64 Timeout ) { - UINT64 Delay; - UINT8 StatusRegister; - UINT8 ErrorRegister; - BOOLEAN InfiniteWait; + UINT64 Delay; + UINT8 StatusRegister; + UINT8 ErrorRegister; + BOOLEAN InfiniteWait; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -499,7 +498,7 @@ DRQReady ( InfiniteWait = FALSE; } - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { // // Read Status Register will clear interrupt @@ -516,6 +515,7 @@ DRQReady ( if ((ErrorRegister & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { return EFI_ABORTED; } + return EFI_DEVICE_ERROR; } @@ -536,6 +536,7 @@ DRQReady ( return EFI_TIMEOUT; } + /** This function is used to poll for the DRQ bit set in the Alternate Status Register. DRQ is set when the device is ready to transfer data. So this function is called after @@ -569,10 +570,10 @@ DRQReady2 ( IN UINT64 Timeout ) { - UINT64 Delay; - UINT8 AltRegister; - UINT8 ErrorRegister; - BOOLEAN InfiniteWait; + UINT64 Delay; + UINT8 AltRegister; + UINT8 ErrorRegister; + BOOLEAN InfiniteWait; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -583,7 +584,7 @@ DRQReady2 ( InfiniteWait = FALSE; } - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { // @@ -600,6 +601,7 @@ DRQReady2 ( if ((ErrorRegister & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { return EFI_ABORTED; } + return EFI_DEVICE_ERROR; } @@ -621,9 +623,6 @@ DRQReady2 ( return EFI_TIMEOUT; } - - - /** This function is used to poll for the BSY bit clear in the Status Register. BSY is clear when the device is not busy. Every command must be sent after device is not busy. @@ -645,9 +644,9 @@ WaitForBSYClear ( IN UINT64 Timeout ) { - UINT64 Delay; - UINT8 StatusRegister; - BOOLEAN InfiniteWait; + UINT64 Delay; + UINT8 StatusRegister; + BOOLEAN InfiniteWait; ASSERT (PciIo != NULL); ASSERT (IdeRegisters != NULL); @@ -658,7 +657,7 @@ WaitForBSYClear ( InfiniteWait = FALSE; } - Delay = DivU64x32(Timeout, 1000) + 1; + Delay = DivU64x32 (Timeout, 1000) + 1; do { StatusRegister = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus); @@ -672,13 +671,11 @@ WaitForBSYClear ( MicroSecondDelay (100); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; } - /** Get IDE i/o port registers' base addresses by mode. @@ -729,15 +726,15 @@ WaitForBSYClear ( EFI_STATUS EFIAPI GetIdeRegisterIoAddr ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN OUT EFI_IDE_REGISTERS *IdeRegisters + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN OUT EFI_IDE_REGISTERS *IdeRegisters ) { - EFI_STATUS Status; - PCI_TYPE00 PciData; - UINT16 CommandBlockBaseAddr; - UINT16 ControlBlockBaseAddr; - UINT16 BusMasterBaseAddr; + EFI_STATUS Status; + PCI_TYPE00 PciData; + UINT16 CommandBlockBaseAddr; + UINT16 ControlBlockBaseAddr; + UINT16 BusMasterBaseAddr; if ((PciIo == NULL) || (IdeRegisters == NULL)) { return EFI_INVALID_PARAMETER; @@ -755,7 +752,7 @@ GetIdeRegisterIoAddr ( return Status; } - BusMasterBaseAddr = (UINT16) ((PciData.Device.Bar[4] & 0x0000fff0)); + BusMasterBaseAddr = (UINT16)((PciData.Device.Bar[4] & 0x0000fff0)); if ((PciData.Hdr.ClassCode[0] & IDE_PRIMARY_OPERATING_MODE) == 0) { CommandBlockBaseAddr = 0x1f0; @@ -764,26 +761,27 @@ GetIdeRegisterIoAddr ( // // The BARs should be of IO type // - if ((PciData.Device.Bar[0] & BIT0) == 0 || - (PciData.Device.Bar[1] & BIT0) == 0) { + if (((PciData.Device.Bar[0] & BIT0) == 0) || + ((PciData.Device.Bar[1] & BIT0) == 0)) + { return EFI_UNSUPPORTED; } - CommandBlockBaseAddr = (UINT16) (PciData.Device.Bar[0] & 0x0000fff8); - ControlBlockBaseAddr = (UINT16) ((PciData.Device.Bar[1] & 0x0000fffc) + 2); + CommandBlockBaseAddr = (UINT16)(PciData.Device.Bar[0] & 0x0000fff8); + ControlBlockBaseAddr = (UINT16)((PciData.Device.Bar[1] & 0x0000fffc) + 2); } // // Calculate IDE primary channel I/O register base address. // IdeRegisters[EfiIdePrimary].Data = CommandBlockBaseAddr; - IdeRegisters[EfiIdePrimary].ErrOrFeature = (UINT16) (CommandBlockBaseAddr + 0x01); - IdeRegisters[EfiIdePrimary].SectorCount = (UINT16) (CommandBlockBaseAddr + 0x02); - IdeRegisters[EfiIdePrimary].SectorNumber = (UINT16) (CommandBlockBaseAddr + 0x03); - IdeRegisters[EfiIdePrimary].CylinderLsb = (UINT16) (CommandBlockBaseAddr + 0x04); - IdeRegisters[EfiIdePrimary].CylinderMsb = (UINT16) (CommandBlockBaseAddr + 0x05); - IdeRegisters[EfiIdePrimary].Head = (UINT16) (CommandBlockBaseAddr + 0x06); - IdeRegisters[EfiIdePrimary].CmdOrStatus = (UINT16) (CommandBlockBaseAddr + 0x07); + IdeRegisters[EfiIdePrimary].ErrOrFeature = (UINT16)(CommandBlockBaseAddr + 0x01); + IdeRegisters[EfiIdePrimary].SectorCount = (UINT16)(CommandBlockBaseAddr + 0x02); + IdeRegisters[EfiIdePrimary].SectorNumber = (UINT16)(CommandBlockBaseAddr + 0x03); + IdeRegisters[EfiIdePrimary].CylinderLsb = (UINT16)(CommandBlockBaseAddr + 0x04); + IdeRegisters[EfiIdePrimary].CylinderMsb = (UINT16)(CommandBlockBaseAddr + 0x05); + IdeRegisters[EfiIdePrimary].Head = (UINT16)(CommandBlockBaseAddr + 0x06); + IdeRegisters[EfiIdePrimary].CmdOrStatus = (UINT16)(CommandBlockBaseAddr + 0x07); IdeRegisters[EfiIdePrimary].AltOrDev = ControlBlockBaseAddr; IdeRegisters[EfiIdePrimary].BusMasterBaseAddr = BusMasterBaseAddr; @@ -794,33 +792,33 @@ GetIdeRegisterIoAddr ( // // The BARs should be of IO type // - if ((PciData.Device.Bar[2] & BIT0) == 0 || - (PciData.Device.Bar[3] & BIT0) == 0) { + if (((PciData.Device.Bar[2] & BIT0) == 0) || + ((PciData.Device.Bar[3] & BIT0) == 0)) + { return EFI_UNSUPPORTED; } - CommandBlockBaseAddr = (UINT16) (PciData.Device.Bar[2] & 0x0000fff8); - ControlBlockBaseAddr = (UINT16) ((PciData.Device.Bar[3] & 0x0000fffc) + 2); + CommandBlockBaseAddr = (UINT16)(PciData.Device.Bar[2] & 0x0000fff8); + ControlBlockBaseAddr = (UINT16)((PciData.Device.Bar[3] & 0x0000fffc) + 2); } // // Calculate IDE secondary channel I/O register base address. // IdeRegisters[EfiIdeSecondary].Data = CommandBlockBaseAddr; - IdeRegisters[EfiIdeSecondary].ErrOrFeature = (UINT16) (CommandBlockBaseAddr + 0x01); - IdeRegisters[EfiIdeSecondary].SectorCount = (UINT16) (CommandBlockBaseAddr + 0x02); - IdeRegisters[EfiIdeSecondary].SectorNumber = (UINT16) (CommandBlockBaseAddr + 0x03); - IdeRegisters[EfiIdeSecondary].CylinderLsb = (UINT16) (CommandBlockBaseAddr + 0x04); - IdeRegisters[EfiIdeSecondary].CylinderMsb = (UINT16) (CommandBlockBaseAddr + 0x05); - IdeRegisters[EfiIdeSecondary].Head = (UINT16) (CommandBlockBaseAddr + 0x06); - IdeRegisters[EfiIdeSecondary].CmdOrStatus = (UINT16) (CommandBlockBaseAddr + 0x07); + IdeRegisters[EfiIdeSecondary].ErrOrFeature = (UINT16)(CommandBlockBaseAddr + 0x01); + IdeRegisters[EfiIdeSecondary].SectorCount = (UINT16)(CommandBlockBaseAddr + 0x02); + IdeRegisters[EfiIdeSecondary].SectorNumber = (UINT16)(CommandBlockBaseAddr + 0x03); + IdeRegisters[EfiIdeSecondary].CylinderLsb = (UINT16)(CommandBlockBaseAddr + 0x04); + IdeRegisters[EfiIdeSecondary].CylinderMsb = (UINT16)(CommandBlockBaseAddr + 0x05); + IdeRegisters[EfiIdeSecondary].Head = (UINT16)(CommandBlockBaseAddr + 0x06); + IdeRegisters[EfiIdeSecondary].CmdOrStatus = (UINT16)(CommandBlockBaseAddr + 0x07); IdeRegisters[EfiIdeSecondary].AltOrDev = ControlBlockBaseAddr; - IdeRegisters[EfiIdeSecondary].BusMasterBaseAddr = (UINT16) (BusMasterBaseAddr + 0x8); + IdeRegisters[EfiIdeSecondary].BusMasterBaseAddr = (UINT16)(BusMasterBaseAddr + 0x8); return EFI_SUCCESS; } - /** Send ATA Ext command into device with NON_DATA protocol. @@ -836,10 +834,10 @@ GetIdeRegisterIoAddr ( EFI_STATUS EFIAPI AtaIssueCommand ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN UINT64 Timeout ) { EFI_STATUS Status; @@ -861,7 +859,7 @@ AtaIssueCommand ( // // Select device (bit4), set LBA mode(bit6) (use 0xe0 for compatibility) // - IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8) (0xe0 | DeviceHead)); + IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)(0xe0 | DeviceHead)); // // set all the command parameters @@ -934,15 +932,15 @@ AtaIssueCommand ( EFI_STATUS EFIAPI AtaPioDataInOut ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN OUT VOID *Buffer, - IN UINT64 ByteCount, - IN BOOLEAN Read, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN OUT VOID *Buffer, + IN UINT64 ByteCount, + IN BOOLEAN Read, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ) { UINTN WordCount; @@ -963,7 +961,7 @@ AtaPioDataInOut ( goto Exit; } - Buffer16 = (UINT16 *) Buffer; + Buffer16 = (UINT16 *)Buffer; // // According to PIO data in protocol, host can perform a series of reads to @@ -987,7 +985,7 @@ AtaPioDataInOut ( // WordCount = 0; - while (WordCount < RShiftU64(ByteCount, 1)) { + while (WordCount < RShiftU64 (ByteCount, 1)) { // // Poll DRQ bit set, data transfer can be performed only when DRQ is ready // @@ -1000,8 +998,8 @@ AtaPioDataInOut ( // // Get the byte count for one series of read // - if ((WordCount + Increment) > RShiftU64(ByteCount, 1)) { - Increment = (UINTN)(RShiftU64(ByteCount, 1) - WordCount); + if ((WordCount + Increment) > RShiftU64 (ByteCount, 1)) { + Increment = (UINTN)(RShiftU64 (ByteCount, 1) - WordCount); } if (Read) { @@ -1069,12 +1067,12 @@ Exit: EFI_STATUS EFIAPI AtaNonDataCommandIn ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, - IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, - IN UINT64 Timeout, - IN ATA_NONBLOCK_TASK *Task + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN EFI_ATA_COMMAND_BLOCK *AtaCommandBlock, + IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock, + IN UINT64 Timeout, + IN ATA_NONBLOCK_TASK *Task ) { EFI_STATUS Status; @@ -1133,16 +1131,16 @@ Exit: **/ EFI_STATUS AtaUdmStatusWait ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN UINT64 Timeout - ) + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN UINT64 Timeout + ) { - UINT8 RegisterValue; - EFI_STATUS Status; - UINT16 IoPortForBmis; - UINT64 Delay; - BOOLEAN InfiniteWait; + UINT8 RegisterValue; + EFI_STATUS Status; + UINT16 IoPortForBmis; + UINT64 Delay; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -1159,7 +1157,7 @@ AtaUdmStatusWait ( break; } - IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); + IoPortForBmis = (UINT16)(IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); RegisterValue = IdeReadPortB (PciIo, IoPortForBmis); if (((RegisterValue & BMIS_ERROR) != 0) || (Timeout == 0)) { DEBUG ((DEBUG_ERROR, "ATA UDMA operation fails\n")); @@ -1171,6 +1169,7 @@ AtaUdmStatusWait ( Status = EFI_SUCCESS; break; } + // // Stall for 100 microseconds. // @@ -1197,14 +1196,14 @@ AtaUdmStatusWait ( **/ EFI_STATUS AtaUdmStatusCheck ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN ATA_NONBLOCK_TASK *Task, - IN EFI_IDE_REGISTERS *IdeRegisters - ) + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN ATA_NONBLOCK_TASK *Task, + IN EFI_IDE_REGISTERS *IdeRegisters + ) { - UINT8 RegisterValue; - UINT16 IoPortForBmis; - EFI_STATUS Status; + UINT8 RegisterValue; + UINT16 IoPortForBmis; + EFI_STATUS Status; Task->RetryTimes--; @@ -1213,7 +1212,7 @@ AtaUdmStatusCheck ( return EFI_DEVICE_ERROR; } - IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); + IoPortForBmis = (UINT16)(IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); RegisterValue = IdeReadPortB (PciIo, IoPortForBmis); if ((RegisterValue & BMIS_ERROR) != 0) { @@ -1273,36 +1272,36 @@ AtaUdmaInOut ( IN ATA_NONBLOCK_TASK *Task ) { - EFI_STATUS Status; - UINT16 IoPortForBmic; - UINT16 IoPortForBmis; - UINT16 IoPortForBmid; - - UINTN PrdTableSize; - EFI_PHYSICAL_ADDRESS PrdTableMapAddr; - VOID *PrdTableMap; - EFI_PHYSICAL_ADDRESS PrdTableBaseAddr; - EFI_ATA_DMA_PRD *TempPrdBaseAddr; - UINTN PrdTableNum; - - UINT8 RegisterValue; - UINTN PageCount; - UINTN ByteCount; - UINTN ByteRemaining; - UINT8 DeviceControl; - - VOID *BufferMap; - EFI_PHYSICAL_ADDRESS BufferMapAddress; - EFI_PCI_IO_PROTOCOL_OPERATION PciIoOperation; - - UINT8 DeviceHead; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_TPL OldTpl; - - UINTN AlignmentMask; - UINTN RealPageCount; - EFI_PHYSICAL_ADDRESS BaseAddr; - EFI_PHYSICAL_ADDRESS BaseMapAddr; + EFI_STATUS Status; + UINT16 IoPortForBmic; + UINT16 IoPortForBmis; + UINT16 IoPortForBmid; + + UINTN PrdTableSize; + EFI_PHYSICAL_ADDRESS PrdTableMapAddr; + VOID *PrdTableMap; + EFI_PHYSICAL_ADDRESS PrdTableBaseAddr; + EFI_ATA_DMA_PRD *TempPrdBaseAddr; + UINTN PrdTableNum; + + UINT8 RegisterValue; + UINTN PageCount; + UINTN ByteCount; + UINTN ByteRemaining; + UINT8 DeviceControl; + + VOID *BufferMap; + EFI_PHYSICAL_ADDRESS BufferMapAddress; + EFI_PCI_IO_PROTOCOL_OPERATION PciIoOperation; + + UINT8 DeviceHead; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_TPL OldTpl; + + UINTN AlignmentMask; + UINTN RealPageCount; + EFI_PHYSICAL_ADDRESS BaseAddr; + EFI_PHYSICAL_ADDRESS BaseMapAddr; Status = EFI_SUCCESS; PrdTableMap = NULL; @@ -1329,6 +1328,7 @@ AtaUdmaInOut ( // MicroSecondDelay (1000); } + gBS->RestoreTPL (OldTpl); // @@ -1341,9 +1341,9 @@ AtaUdmaInOut ( // // Set relevant IO Port address. // - IoPortForBmic = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIC_OFFSET); - IoPortForBmis = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); - IoPortForBmid = (UINT16) (IdeRegisters->BusMasterBaseAddr + BMID_OFFSET); + IoPortForBmic = (UINT16)(IdeRegisters->BusMasterBaseAddr + BMIC_OFFSET); + IoPortForBmis = (UINT16)(IdeRegisters->BusMasterBaseAddr + BMIS_OFFSET); + IoPortForBmid = (UINT16)(IdeRegisters->BusMasterBaseAddr + BMID_OFFSET); // // For Blocking mode, start the command. @@ -1355,7 +1355,7 @@ AtaUdmaInOut ( // Calculate the number of PRD entry. // Every entry in PRD table can specify a 64K memory region. // - PrdTableNum = (UINTN)(RShiftU64(DataLength, 16) + 1); + PrdTableNum = (UINTN)(RShiftU64 (DataLength, 16) + 1); // // Make sure that the memory region of PRD table is not cross 64K boundary @@ -1378,14 +1378,14 @@ AtaUdmaInOut ( // ASSERT (RealPageCount > PageCount); - Status = PciIo->AllocateBuffer ( - PciIo, - AllocateAnyPages, - EfiBootServicesData, - RealPageCount, - (VOID **)&BaseAddr, - 0 - ); + Status = PciIo->AllocateBuffer ( + PciIo, + AllocateAnyPages, + EfiBootServicesData, + RealPageCount, + (VOID **)&BaseAddr, + 0 + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } @@ -1394,7 +1394,7 @@ AtaUdmaInOut ( Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, - (VOID*)(UINTN)BaseAddr, + (VOID *)(UINTN)BaseAddr, &ByteCount, &BaseMapAddr, &PrdTableMap @@ -1405,18 +1405,18 @@ AtaUdmaInOut ( // it means the DMA operation may be broken into several discontinuous smaller chunks. // Can't handle this case. // - PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr); + PciIo->FreeBuffer (PciIo, RealPageCount, (VOID *)(UINTN)BaseAddr); return EFI_OUT_OF_RESOURCES; } - ZeroMem ((VOID *) ((UINTN) BaseAddr), ByteCount); + ZeroMem ((VOID *)((UINTN)BaseAddr), ByteCount); // // Calculate the 64K align address as PRD Table base address. // AlignmentMask = SIZE_64KB - 1; - PrdTableBaseAddr = ((UINTN) BaseAddr + AlignmentMask) & ~AlignmentMask; - PrdTableMapAddr = ((UINTN) BaseMapAddr + AlignmentMask) & ~AlignmentMask; + PrdTableBaseAddr = ((UINTN)BaseAddr + AlignmentMask) & ~AlignmentMask; + PrdTableMapAddr = ((UINTN)BaseMapAddr + AlignmentMask) & ~AlignmentMask; // // Map the host address of DataBuffer to DMA master address. @@ -1438,7 +1438,7 @@ AtaUdmaInOut ( ); if (EFI_ERROR (Status) || (ByteCount != DataLength)) { PciIo->Unmap (PciIo, PrdTableMap); - PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr); + PciIo->FreeBuffer (PciIo, RealPageCount, (VOID *)(UINTN)BaseAddr); return EFI_OUT_OF_RESOURCES; } @@ -1452,17 +1452,17 @@ AtaUdmaInOut ( // Fill the PRD table with appropriate bus master address of data buffer and data length. // ByteRemaining = ByteCount; - TempPrdBaseAddr = (EFI_ATA_DMA_PRD*)(UINTN)PrdTableBaseAddr; + TempPrdBaseAddr = (EFI_ATA_DMA_PRD *)(UINTN)PrdTableBaseAddr; while (ByteRemaining != 0) { if (ByteRemaining <= 0x10000) { - TempPrdBaseAddr->RegionBaseAddr = (UINT32) ((UINTN) BufferMapAddress); - TempPrdBaseAddr->ByteCount = (UINT16) ByteRemaining; + TempPrdBaseAddr->RegionBaseAddr = (UINT32)((UINTN)BufferMapAddress); + TempPrdBaseAddr->ByteCount = (UINT16)ByteRemaining; TempPrdBaseAddr->EndOfTable = 0x8000; break; } - TempPrdBaseAddr->RegionBaseAddr = (UINT32) ((UINTN) BufferMapAddress); - TempPrdBaseAddr->ByteCount = (UINT16) 0x0; + TempPrdBaseAddr->RegionBaseAddr = (UINT32)((UINTN)BufferMapAddress); + TempPrdBaseAddr->ByteCount = (UINT16)0x0; ByteRemaining -= 0x10000; BufferMapAddress += 0x10000; @@ -1485,7 +1485,7 @@ AtaUdmaInOut ( // // Read BMIS register and clear ERROR and INTR bit // - RegisterValue = IdeReadPortB(PciIo, IoPortForBmis); + RegisterValue = IdeReadPortB (PciIo, IoPortForBmis); RegisterValue |= (BMIS_INTERRUPT | BMIS_ERROR); IdeWritePortB (PciIo, IoPortForBmis, RegisterValue); @@ -1497,18 +1497,19 @@ AtaUdmaInOut ( // // Set BMIC register to identify the operation direction // - RegisterValue = IdeReadPortB(PciIo, IoPortForBmic); + RegisterValue = IdeReadPortB (PciIo, IoPortForBmic); if (Read) { RegisterValue |= BMIC_NREAD; } else { - RegisterValue &= ~((UINT8) BMIC_NREAD); + RegisterValue &= ~((UINT8)BMIC_NREAD); } + IdeWritePortB (PciIo, IoPortForBmic, RegisterValue); if (Task != NULL) { Task->Map = BufferMap; Task->TableMap = PrdTableMap; - Task->MapBaseAddress = (EFI_ATA_DMA_PRD*)(UINTN)BaseAddr; + Task->MapBaseAddress = (EFI_ATA_DMA_PRD *)(UINTN)BaseAddr; Task->PageCount = RealPageCount; Task->IsStart = TRUE; } @@ -1528,13 +1529,13 @@ AtaUdmaInOut ( Status = EFI_DEVICE_ERROR; goto Exit; } + // // Set START bit of BMIC register // - RegisterValue = IdeReadPortB(PciIo, IoPortForBmic); + RegisterValue = IdeReadPortB (PciIo, IoPortForBmic); RegisterValue |= BMIC_START; - IdeWritePortB(PciIo, IoPortForBmic, RegisterValue); - + IdeWritePortB (PciIo, IoPortForBmic, RegisterValue); } // @@ -1552,7 +1553,7 @@ AtaUdmaInOut ( // out, or a error has been happened, it needs to clear the register and free // buffer. // - if ((Task == NULL) || Status != EFI_NOT_READY) { + if ((Task == NULL) || (Status != EFI_NOT_READY)) { // // Read BMIS register and clear ERROR and INTR bit // @@ -1563,13 +1564,13 @@ AtaUdmaInOut ( // // Read Status Register of IDE device to clear interrupt // - RegisterValue = IdeReadPortB(PciIo, IdeRegisters->CmdOrStatus); + RegisterValue = IdeReadPortB (PciIo, IdeRegisters->CmdOrStatus); // // Clear START bit of BMIC register // - RegisterValue = IdeReadPortB(PciIo, IoPortForBmic); - RegisterValue &= ~((UINT8) BMIC_START); + RegisterValue = IdeReadPortB (PciIo, IoPortForBmic); + RegisterValue &= ~((UINT8)BMIC_START); IdeWritePortB (PciIo, IoPortForBmic, RegisterValue); // @@ -1582,21 +1583,20 @@ AtaUdmaInOut ( // Stall for 10 milliseconds. // MicroSecondDelay (10000); - } Exit: // // Free all allocated resource // - if ((Task == NULL) || Status != EFI_NOT_READY) { + if ((Task == NULL) || (Status != EFI_NOT_READY)) { if (Task != NULL) { PciIo->Unmap (PciIo, Task->TableMap); PciIo->FreeBuffer (PciIo, Task->PageCount, Task->MapBaseAddress); PciIo->Unmap (PciIo, Task->Map); } else { PciIo->Unmap (PciIo, PrdTableMap); - PciIo->FreeBuffer (PciIo, RealPageCount, (VOID*)(UINTN)BaseAddr); + PciIo->FreeBuffer (PciIo, RealPageCount, (VOID *)(UINTN)BaseAddr); PciIo->Unmap (PciIo, BufferMap); } @@ -1622,12 +1622,12 @@ Exit: EFI_STATUS EFIAPI AtaPacketReadPendingData ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters ) { - UINT8 AltRegister; - UINT16 TempWordBuffer; + UINT8 AltRegister; + UINT16 TempWordBuffer; AltRegister = IdeReadPortB (PciIo, IdeRegisters->AltOrDev); if ((AltRegister & ATA_STSREG_BSY) == ATA_STSREG_BSY) { @@ -1646,6 +1646,7 @@ AtaPacketReadPendingData ( TempWordBuffer = IdeReadPortB (PciIo, IdeRegisters->AltOrDev); } } + return EFI_SUCCESS; } @@ -1670,12 +1671,12 @@ AtaPacketReadPendingData ( EFI_STATUS EFIAPI AtaPacketReadWrite ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN OUT VOID *Buffer, - IN OUT UINT32 *ByteCount, - IN BOOLEAN Read, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN OUT VOID *Buffer, + IN OUT UINT32 *ByteCount, + IN BOOLEAN Read, + IN UINT64 Timeout ) { UINT32 RequiredWordCount; @@ -1803,17 +1804,17 @@ AtaPacketReadWrite ( EFI_STATUS EFIAPI AtaPacketCommandExecute ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet ) { - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - EFI_STATUS Status; - UINT8 Count; - UINT8 PacketCommand[12]; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_STATUS Status; + UINT8 Count; + UINT8 PacketCommand[12]; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); @@ -1836,9 +1837,9 @@ AtaPacketCommandExecute ( // set the transfersize to ATAPI_MAX_BYTE_COUNT to let the device // determine how many data should be transferred. // - AtaCommandBlock.AtaCylinderLow = (UINT8) (ATAPI_MAX_BYTE_COUNT & 0x00ff); - AtaCommandBlock.AtaCylinderHigh = (UINT8) (ATAPI_MAX_BYTE_COUNT >> 8); - AtaCommandBlock.AtaDeviceHead = (UINT8) (Device << 0x4); + AtaCommandBlock.AtaCylinderLow = (UINT8)(ATAPI_MAX_BYTE_COUNT & 0x00ff); + AtaCommandBlock.AtaCylinderHigh = (UINT8)(ATAPI_MAX_BYTE_COUNT >> 8); + AtaCommandBlock.AtaDeviceHead = (UINT8)(Device << 0x4); AtaCommandBlock.AtaCommand = ATA_CMD_PACKET; IdeWritePortB (PciIo, IdeRegisters->Head, (UINT8)(0xe0 | (Device << 0x4))); @@ -1864,7 +1865,7 @@ AtaPacketCommandExecute ( // Send out ATAPI command packet // for (Count = 0; Count < 6; Count++) { - IdeWritePortW (PciIo, IdeRegisters->Data, *((UINT16*)PacketCommand + Count)); + IdeWritePortW (PciIo, IdeRegisters->Data, *((UINT16 *)PacketCommand + Count)); // // Stall for 10 microseconds. // @@ -1897,7 +1898,6 @@ AtaPacketCommandExecute ( return Status; } - /** Set the calculated Best transfer mode to a detected device. @@ -1922,8 +1922,8 @@ SetDeviceTransferMode ( IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); @@ -1971,14 +1971,14 @@ SetDriveParameters ( IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); AtaCommandBlock.AtaCommand = ATA_CMD_INIT_DRIVE_PARAM; AtaCommandBlock.AtaSectorCount = DriveParameters->Sector; - AtaCommandBlock.AtaDeviceHead = (UINT8) ((Device << 0x4) + DriveParameters->Heads); + AtaCommandBlock.AtaDeviceHead = (UINT8)((Device << 0x4) + DriveParameters->Heads); // // Send Init drive parameters @@ -2032,10 +2032,10 @@ IdeAtaSmartReturnStatusCheck ( IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; - UINT8 LBAMid; - UINT8 LBAHigh; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + UINT8 LBAMid; + UINT8 LBAHigh; ZeroMem (&AtaCommandBlock, sizeof (EFI_ATA_COMMAND_BLOCK)); @@ -2043,7 +2043,7 @@ IdeAtaSmartReturnStatusCheck ( AtaCommandBlock.AtaFeatures = ATA_SMART_RETURN_STATUS; AtaCommandBlock.AtaCylinderLow = ATA_CONSTANT_4F; AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2; - AtaCommandBlock.AtaDeviceHead = (UINT8) ((Device << 0x4) | 0xe0); + AtaCommandBlock.AtaDeviceHead = (UINT8)((Device << 0x4) | 0xe0); // // Send S.M.A.R.T Read Return Status command to device @@ -2079,18 +2079,18 @@ IdeAtaSmartReturnStatusCheck ( // DEBUG ((DEBUG_INFO, "The S.M.A.R.T threshold exceeded condition is not detected\n")); REPORT_STATUS_CODE ( - EFI_PROGRESS_CODE, - (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_UNDERTHRESHOLD) - ); + EFI_PROGRESS_CODE, + (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_UNDERTHRESHOLD) + ); } else if ((LBAMid == 0xf4) && (LBAHigh == 0x2c)) { // // The threshold exceeded condition is detected by the device // DEBUG ((DEBUG_INFO, "The S.M.A.R.T threshold exceeded condition is detected\n")); REPORT_STATUS_CODE ( - EFI_PROGRESS_CODE, - (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_OVERTHRESHOLD) - ); + EFI_PROGRESS_CODE, + (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_OVERTHRESHOLD) + ); } return EFI_SUCCESS; @@ -2116,8 +2116,8 @@ IdeAtaSmartSupport ( IN OUT EFI_ATA_STATUS_BLOCK *AtaStatusBlock ) { - EFI_STATUS Status; - EFI_ATA_COMMAND_BLOCK AtaCommandBlock; + EFI_STATUS Status; + EFI_ATA_COMMAND_BLOCK AtaCommandBlock; // // Detect if the device supports S.M.A.R.T. @@ -2126,8 +2126,12 @@ IdeAtaSmartSupport ( // // S.M.A.R.T is not supported by the device // - DEBUG ((DEBUG_INFO, "S.M.A.R.T feature is not supported at [%a] channel [%a] device!\n", - (Channel == 1) ? "secondary" : "primary", (Device == 1) ? "slave" : "master")); + DEBUG (( + DEBUG_INFO, + "S.M.A.R.T feature is not supported at [%a] channel [%a] device!\n", + (Channel == 1) ? "secondary" : "primary", + (Device == 1) ? "slave" : "master" + )); REPORT_STATUS_CODE ( EFI_ERROR_CODE | EFI_ERROR_MINOR, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_NOTSUPPORTED) @@ -2137,7 +2141,6 @@ IdeAtaSmartSupport ( // Check if the feature is enabled. If not, then enable S.M.A.R.T. // if ((IdentifyData->AtaData.command_set_feature_enb_85 & 0x0001) != 0x0001) { - REPORT_STATUS_CODE ( EFI_PROGRESS_CODE, (EFI_IO_BUS_ATA_ATAPI | EFI_IOB_ATA_BUS_SMART_DISABLE) @@ -2149,7 +2152,7 @@ IdeAtaSmartSupport ( AtaCommandBlock.AtaFeatures = ATA_SMART_ENABLE_OPERATION; AtaCommandBlock.AtaCylinderLow = ATA_CONSTANT_4F; AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2; - AtaCommandBlock.AtaDeviceHead = (UINT8) ((Device << 0x4) | 0xe0); + AtaCommandBlock.AtaDeviceHead = (UINT8)((Device << 0x4) | 0xe0); // // Send S.M.A.R.T Enable command to device @@ -2174,7 +2177,7 @@ IdeAtaSmartSupport ( AtaCommandBlock.AtaSectorCount = 0xF1; AtaCommandBlock.AtaCylinderLow = ATA_CONSTANT_4F; AtaCommandBlock.AtaCylinderHigh = ATA_CONSTANT_C2; - AtaCommandBlock.AtaDeviceHead = (UINT8) ((Device << 0x4) | 0xe0); + AtaCommandBlock.AtaDeviceHead = (UINT8)((Device << 0x4) | 0xe0); Status = AtaNonDataCommandIn ( Instance->PciIo, @@ -2195,15 +2198,17 @@ IdeAtaSmartSupport ( } } - DEBUG ((DEBUG_INFO, "Enabled S.M.A.R.T feature at [%a] channel [%a] device!\n", - (Channel == 1) ? "secondary" : "primary", (Device == 1) ? "slave" : "master")); - + DEBUG (( + DEBUG_INFO, + "Enabled S.M.A.R.T feature at [%a] channel [%a] device!\n", + (Channel == 1) ? "secondary" : "primary", + (Device == 1) ? "slave" : "master" + )); } - return ; + return; } - /** Sends out an ATA Identify Command to the specified device. @@ -2315,7 +2320,7 @@ AtaIdentifyPacket ( Status = AtaPioDataInOut ( Instance->PciIo, &Instance->IdeRegisters[Channel], - (VOID *) Buffer, + (VOID *)Buffer, sizeof (EFI_IDENTIFY_DATA), TRUE, &AtaCommandBlock, @@ -2327,7 +2332,6 @@ AtaIdentifyPacket ( return Status; } - /** This function is used for detect whether the IDE device exists in the specified Channel as the specified Device Number. @@ -2357,22 +2361,22 @@ DetectAndConfigIdeDevice ( IN UINT8 IdeChannel ) { - EFI_STATUS Status; - UINT8 SectorCountReg; - UINT8 LBALowReg; - UINT8 LBAMidReg; - UINT8 LBAHighReg; - EFI_ATA_DEVICE_TYPE DeviceType; - UINT8 IdeDevice; - EFI_IDE_REGISTERS *IdeRegisters; - EFI_IDENTIFY_DATA Buffer; + EFI_STATUS Status; + UINT8 SectorCountReg; + UINT8 LBALowReg; + UINT8 LBAMidReg; + UINT8 LBAHighReg; + EFI_ATA_DEVICE_TYPE DeviceType; + UINT8 IdeDevice; + EFI_IDE_REGISTERS *IdeRegisters; + EFI_IDENTIFY_DATA Buffer; EFI_IDE_CONTROLLER_INIT_PROTOCOL *IdeInit; EFI_PCI_IO_PROTOCOL *PciIo; - EFI_ATA_COLLECTIVE_MODE *SupportedModes; - EFI_ATA_TRANSFER_MODE TransferMode; - EFI_ATA_DRIVE_PARMS DriveParameters; + EFI_ATA_COLLECTIVE_MODE *SupportedModes; + EFI_ATA_TRANSFER_MODE TransferMode; + EFI_ATA_DRIVE_PARMS DriveParameters; IdeRegisters = &Instance->IdeRegisters[IdeChannel]; IdeInit = Instance->IdeControllerInit; @@ -2392,7 +2396,7 @@ DetectAndConfigIdeDevice ( Status = WaitForBSYClear (PciIo, IdeRegisters, 350000000); if (EFI_ERROR (Status)) { - DEBUG((DEBUG_ERROR, "New detecting method: Send Execute Diagnostic Command: WaitForBSYClear: Status: %d\n", Status)); + DEBUG ((DEBUG_ERROR, "New detecting method: Send Execute Diagnostic Command: WaitForBSYClear: Status: %d\n", Status)); continue; } @@ -2453,9 +2457,13 @@ DetectAndConfigIdeDevice ( continue; } - DEBUG ((DEBUG_INFO, "[%a] channel [%a] [%a] device\n", - (IdeChannel == 1) ? "secondary" : "primary ", (IdeDevice == 1) ? "slave " : "master", - DeviceType == EfiIdeCdrom ? "cdrom " : "harddisk")); + DEBUG (( + DEBUG_INFO, + "[%a] channel [%a] [%a] device\n", + (IdeChannel == 1) ? "secondary" : "primary ", + (IdeDevice == 1) ? "slave " : "master", + DeviceType == EfiIdeCdrom ? "cdrom " : "harddisk" + )); // // If the device is a hard disk, then try to enable S.M.A.R.T feature // @@ -2497,9 +2505,9 @@ DetectAndConfigIdeDevice ( TransferMode.ModeCategory = EFI_ATA_MODE_FLOW_PIO; } - TransferMode.ModeNumber = (UINT8) (SupportedModes->PioMode.Mode); + TransferMode.ModeNumber = (UINT8)(SupportedModes->PioMode.Mode); - if (SupportedModes->ExtModeCount == 0){ + if (SupportedModes->ExtModeCount == 0) { Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL); if (EFI_ERROR (Status)) { @@ -2516,8 +2524,8 @@ DetectAndConfigIdeDevice ( // if (SupportedModes->UdmaMode.Valid) { TransferMode.ModeCategory = EFI_ATA_MODE_UDMA; - TransferMode.ModeNumber = (UINT8) (SupportedModes->UdmaMode.Mode); - Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL); + TransferMode.ModeNumber = (UINT8)(SupportedModes->UdmaMode.Mode); + Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Set transfer Mode Fail, Status = %r\n", Status)); @@ -2525,8 +2533,8 @@ DetectAndConfigIdeDevice ( } } else if (SupportedModes->MultiWordDmaMode.Valid) { TransferMode.ModeCategory = EFI_ATA_MODE_MDMA; - TransferMode.ModeNumber = (UINT8) SupportedModes->MultiWordDmaMode.Mode; - Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL); + TransferMode.ModeNumber = (UINT8)SupportedModes->MultiWordDmaMode.Mode; + Status = SetDeviceTransferMode (Instance, IdeChannel, IdeDevice, &TransferMode, NULL); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Set transfer Mode Fail, Status = %r\n", Status)); @@ -2543,9 +2551,9 @@ DetectAndConfigIdeDevice ( // // Init driver parameters // - DriveParameters.Sector = (UINT8) ((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->sectors_per_track; - DriveParameters.Heads = (UINT8) (((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->heads - 1); - DriveParameters.MultipleSector = (UINT8) ((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->multi_sector_cmd_max_sct_cnt; + DriveParameters.Sector = (UINT8)((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->sectors_per_track; + DriveParameters.Heads = (UINT8)(((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->heads - 1); + DriveParameters.MultipleSector = (UINT8)((ATA5_IDENTIFY_DATA *)(&Buffer.AtaData))->multi_sector_cmd_max_sct_cnt; Status = SetDriveParameters (Instance, IdeChannel, IdeDevice, &DriveParameters, NULL); } @@ -2568,10 +2576,10 @@ DetectAndConfigIdeDevice ( REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_PERIPHERAL_FIXED_MEDIA | EFI_P_PC_ENABLE)); } } + return EFI_SUCCESS; } - /** Initialize ATA host controller at IDE mode. @@ -2583,7 +2591,7 @@ DetectAndConfigIdeDevice ( EFI_STATUS EFIAPI IdeModeInitialization ( - IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance + IN ATA_ATAPI_PASS_THRU_INSTANCE *Instance ) { EFI_STATUS Status; diff --git a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.h b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.h index c39ebd0667..ce6c9151cd 100644 --- a/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.h +++ b/MdeModulePkg/Bus/Ata/AtaAtapiPassThru/IdeMode.h @@ -5,6 +5,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __ATA_HC_IDE_MODE_H__ #define __ATA_HC_IDE_MODE_H__ @@ -59,50 +60,50 @@ typedef enum { #define BMIS_INTERRUPT BIT2 #define BMIS_ERROR BIT1 -#define BMIC_OFFSET 0x00 -#define BMIS_OFFSET 0x02 -#define BMID_OFFSET 0x04 +#define BMIC_OFFSET 0x00 +#define BMIS_OFFSET 0x02 +#define BMID_OFFSET 0x04 // // IDE transfer mode // -#define EFI_ATA_MODE_DEFAULT_PIO 0x00 -#define EFI_ATA_MODE_FLOW_PIO 0x01 -#define EFI_ATA_MODE_MDMA 0x04 -#define EFI_ATA_MODE_UDMA 0x08 +#define EFI_ATA_MODE_DEFAULT_PIO 0x00 +#define EFI_ATA_MODE_FLOW_PIO 0x01 +#define EFI_ATA_MODE_MDMA 0x04 +#define EFI_ATA_MODE_UDMA 0x08 typedef struct { - UINT32 RegionBaseAddr; - UINT16 ByteCount; - UINT16 EndOfTable; + UINT32 RegionBaseAddr; + UINT16 ByteCount; + UINT16 EndOfTable; } EFI_ATA_DMA_PRD; typedef struct { - UINT8 ModeNumber : 3; - UINT8 ModeCategory : 5; + UINT8 ModeNumber : 3; + UINT8 ModeCategory : 5; } EFI_ATA_TRANSFER_MODE; typedef struct { - UINT8 Sector; - UINT8 Heads; - UINT8 MultipleSector; + UINT8 Sector; + UINT8 Heads; + UINT8 MultipleSector; } EFI_ATA_DRIVE_PARMS; // // IDE registers set // typedef struct { - UINT16 Data; - UINT16 ErrOrFeature; - UINT16 SectorCount; - UINT16 SectorNumber; - UINT16 CylinderLsb; - UINT16 CylinderMsb; - UINT16 Head; - UINT16 CmdOrStatus; - UINT16 AltOrDev; - - UINT16 BusMasterBaseAddr; + UINT16 Data; + UINT16 ErrOrFeature; + UINT16 SectorCount; + UINT16 SectorNumber; + UINT16 CylinderLsb; + UINT16 CylinderMsb; + UINT16 Head; + UINT16 CmdOrStatus; + UINT16 AltOrDev; + + UINT16 BusMasterBaseAddr; } EFI_IDE_REGISTERS; // @@ -164,8 +165,8 @@ typedef struct { EFI_STATUS EFIAPI GetIdeRegisterIoAddr ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN OUT EFI_IDE_REGISTERS *IdeRegisters + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN OUT EFI_IDE_REGISTERS *IdeRegisters ); /** @@ -187,12 +188,11 @@ GetIdeRegisterIoAddr ( EFI_STATUS EFIAPI AtaPacketCommandExecute ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_IDE_REGISTERS *IdeRegisters, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_IDE_REGISTERS *IdeRegisters, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet ); #endif - diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c index 6c3268896b..a729c087ff 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c @@ -15,7 +15,7 @@ // // ATA Bus Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding = { AtaBusDriverBindingSupported, AtaBusDriverBindingStart, AtaBusDriverBindingStop, @@ -27,9 +27,9 @@ EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding = { // // Template for ATA Child Device. // -ATA_DEVICE gAtaDeviceTemplate = { - ATA_DEVICE_SIGNATURE, // Signature - NULL, // Handle +ATA_DEVICE gAtaDeviceTemplate = { + ATA_DEVICE_SIGNATURE, // Signature + NULL, // Handle { // BlockIo EFI_BLOCK_IO_PROTOCOL_REVISION, NULL, @@ -65,25 +65,27 @@ ATA_DEVICE gAtaDeviceTemplate = { AtaDiskInfoSenseData, AtaDiskInfoWhichIde }, - NULL, // DevicePath + NULL, // DevicePath { AtaStorageSecurityReceiveData, AtaStorageSecuritySendData }, - NULL, // AtaBusDriverData - 0, // Port - 0, // PortMultiplierPort - { 0, }, // Packet - {{ 0}, }, // Acb - NULL, // Asb - FALSE, // UdmaValid - FALSE, // Lba48Bit - NULL, // IdentifyData - NULL, // ControllerNameTable - {L'\0', }, // ModelName - {NULL, NULL}, // AtaTaskList - {NULL, NULL}, // AtaSubTaskList - FALSE // Abort + NULL, // AtaBusDriverData + 0, // Port + 0, // PortMultiplierPort + { 0, }, // Packet + { + { 0 }, + }, // Acb + NULL, // Asb + FALSE, // UdmaValid + FALSE, // Lba48Bit + NULL, // IdentifyData + NULL, // ControllerNameTable + { L'\0', }, // ModelName + { NULL, NULL }, // AtaTaskList + { NULL, NULL }, // AtaSubTaskList + FALSE // Abort }; /** @@ -101,8 +103,8 @@ ATA_DEVICE gAtaDeviceTemplate = { **/ VOID * AllocateAlignedBuffer ( - IN ATA_DEVICE *AtaDevice, - IN UINTN BufferSize + IN ATA_DEVICE *AtaDevice, + IN UINTN BufferSize ) { return AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), AtaDevice->AtaBusDriverData->AtaPassThru->Mode->IoAlign); @@ -120,8 +122,8 @@ AllocateAlignedBuffer ( **/ VOID FreeAlignedBuffer ( - IN VOID *Buffer, - IN UINTN BufferSize + IN VOID *Buffer, + IN UINTN BufferSize ) { if (Buffer != NULL) { @@ -129,7 +131,6 @@ FreeAlignedBuffer ( } } - /** Release all the resources allocated for the ATA device. @@ -143,11 +144,11 @@ ReleaseAtaResources ( IN ATA_DEVICE *AtaDevice ) { - ATA_BUS_ASYN_SUB_TASK *SubTask; - ATA_BUS_ASYN_TASK *AtaTask; - LIST_ENTRY *Entry; - LIST_ENTRY *DelEntry; - EFI_TPL OldTpl; + ATA_BUS_ASYN_SUB_TASK *SubTask; + ATA_BUS_ASYN_TASK *AtaTask; + LIST_ENTRY *Entry; + LIST_ENTRY *DelEntry; + EFI_TPL OldTpl; FreeUnicodeStringTable (AtaDevice->ControllerNameTable); FreeAlignedBuffer (AtaDevice->Asb, sizeof (EFI_ATA_STATUS_BLOCK)); @@ -155,14 +156,16 @@ ReleaseAtaResources ( if (AtaDevice->DevicePath != NULL) { FreePool (AtaDevice->DevicePath); } + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); if (!IsListEmpty (&AtaDevice->AtaSubTaskList)) { // // Free the Subtask list. // - for(Entry = AtaDevice->AtaSubTaskList.ForwardLink; - Entry != (&AtaDevice->AtaSubTaskList); - ) { + for (Entry = AtaDevice->AtaSubTaskList.ForwardLink; + Entry != (&AtaDevice->AtaSubTaskList); + ) + { DelEntry = Entry; Entry = Entry->ForwardLink; SubTask = ATA_ASYN_SUB_TASK_FROM_ENTRY (DelEntry); @@ -171,13 +174,15 @@ ReleaseAtaResources ( FreeAtaSubTask (SubTask); } } + if (!IsListEmpty (&AtaDevice->AtaTaskList)) { // // Free the Subtask list. // - for(Entry = AtaDevice->AtaTaskList.ForwardLink; - Entry != (&AtaDevice->AtaTaskList); - ) { + for (Entry = AtaDevice->AtaTaskList.ForwardLink; + Entry != (&AtaDevice->AtaTaskList); + ) + { DelEntry = Entry; Entry = Entry->ForwardLink; AtaTask = ATA_ASYN_TASK_FROM_ENTRY (DelEntry); @@ -186,11 +191,11 @@ ReleaseAtaResources ( FreePool (AtaTask); } } + gBS->RestoreTPL (OldTpl); FreePool (AtaDevice); } - /** Registers an ATA device. @@ -210,29 +215,29 @@ ReleaseAtaResources ( **/ EFI_STATUS RegisterAtaDevice ( - IN OUT ATA_BUS_DRIVER_DATA *AtaBusDriverData, - IN UINT16 Port, - IN UINT16 PortMultiplierPort + IN OUT ATA_BUS_DRIVER_DATA *AtaBusDriverData, + IN UINT16 Port, + IN UINT16 PortMultiplierPort ) { - EFI_STATUS Status; - ATA_DEVICE *AtaDevice; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - EFI_HANDLE DeviceHandle; - - AtaDevice = NULL; - NewDevicePathNode = NULL; - DevicePath = NULL; + EFI_STATUS Status; + ATA_DEVICE *AtaDevice; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + EFI_HANDLE DeviceHandle; + + AtaDevice = NULL; + NewDevicePathNode = NULL; + DevicePath = NULL; RemainingDevicePath = NULL; // // Build device path // AtaPassThru = AtaBusDriverData->AtaPassThru; - Status = AtaPassThru->BuildDevicePath (AtaPassThru, Port, PortMultiplierPort, &NewDevicePathNode); + Status = AtaPassThru->BuildDevicePath (AtaPassThru, Port, PortMultiplierPort, &NewDevicePathNode); if (EFI_ERROR (Status)) { goto Done; } @@ -243,10 +248,10 @@ RegisterAtaDevice ( goto Done; } - DeviceHandle = NULL; + DeviceHandle = NULL; RemainingDevicePath = DevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) { + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (RemainingDevicePath)) { Status = EFI_ALREADY_STARTED; FreePool (DevicePath); goto Done; @@ -270,11 +275,12 @@ RegisterAtaDevice ( AtaDevice->DevicePath = DevicePath; AtaDevice->Port = Port; AtaDevice->PortMultiplierPort = PortMultiplierPort; - AtaDevice->Asb = AllocateAlignedBuffer (AtaDevice, sizeof (EFI_ATA_STATUS_BLOCK)); + AtaDevice->Asb = AllocateAlignedBuffer (AtaDevice, sizeof (EFI_ATA_STATUS_BLOCK)); if (AtaDevice->Asb == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } + AtaDevice->IdentifyData = AllocateAlignedBuffer (AtaDevice, sizeof (ATA_IDENTIFY_DATA)); if (AtaDevice->IdentifyData == NULL) { Status = EFI_OUT_OF_RESOURCES; @@ -368,13 +374,14 @@ RegisterAtaDevice ( if (EFI_ERROR (Status)) { goto Done; } + DEBUG ((DEBUG_INFO, "Successfully Install Storage Security Protocol on the ATA device\n")); } gBS->OpenProtocol ( AtaBusDriverData->Controller, &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, + (VOID **)&AtaPassThru, AtaBusDriverData->DriverBindingHandle, AtaDevice->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -389,10 +396,10 @@ Done: ReleaseAtaResources (AtaDevice); DEBUG ((DEBUG_ERROR | DEBUG_INIT, "Failed to initialize Port %x PortMultiplierPort %x, status = %r\n", Port, PortMultiplierPort, Status)); } + return Status; } - /** Unregisters an ATA device. @@ -409,25 +416,25 @@ Done: **/ EFI_STATUS UnregisterAtaDevice ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - EFI_BLOCK_IO2_PROTOCOL *BlockIo2; - ATA_DEVICE *AtaDevice; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *StorageSecurity; + EFI_STATUS Status; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + EFI_BLOCK_IO2_PROTOCOL *BlockIo2; + ATA_DEVICE *AtaDevice; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *StorageSecurity; - BlockIo2 = NULL; - BlockIo = NULL; + BlockIo2 = NULL; + BlockIo = NULL; Status = gBS->OpenProtocol ( Handle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -439,7 +446,7 @@ UnregisterAtaDevice ( Status = gBS->OpenProtocol ( Handle, &gEfiBlockIo2ProtocolGuid, - (VOID **) &BlockIo2, + (VOID **)&BlockIo2, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -488,13 +495,13 @@ UnregisterAtaDevice ( if (EFI_ERROR (Status)) { gBS->OpenProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, - This->DriverBindingHandle, - Handle, - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + (VOID **)&AtaPassThru, + This->DriverBindingHandle, + Handle, + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); return Status; } @@ -504,7 +511,7 @@ UnregisterAtaDevice ( Status = gBS->OpenProtocol ( Handle, &gEfiStorageSecurityCommandProtocolGuid, - (VOID **) &StorageSecurity, + (VOID **)&StorageSecurity, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -518,13 +525,13 @@ UnregisterAtaDevice ( ); if (EFI_ERROR (Status)) { gBS->OpenProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, - This->DriverBindingHandle, - Handle, - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + (VOID **)&AtaPassThru, + This->DriverBindingHandle, + Handle, + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); return Status; } } @@ -533,8 +540,6 @@ UnregisterAtaDevice ( return EFI_SUCCESS; } - - /** Tests to see if this driver supports a given controller. If a child device is provided, it further tests to see if this driver supports creating a handle for the specified child device. @@ -585,11 +590,11 @@ AtaBusDriverBindingSupported ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - UINT16 Port; - UINT16 PortMultiplierPort; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + UINT16 Port; + UINT16 PortMultiplierPort; // // Test EFI_ATA_PASS_THRU_PROTOCOL on controller handle. @@ -597,7 +602,7 @@ AtaBusDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, + (VOID **)&AtaPassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -619,11 +624,11 @@ AtaBusDriverBindingSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_UNSUPPORTED; } @@ -637,11 +642,11 @@ AtaBusDriverBindingSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); return Status; } } @@ -650,11 +655,11 @@ AtaBusDriverBindingSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Open the EFI Device Path protocol needed to perform the supported test @@ -662,7 +667,7 @@ AtaBusDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -670,7 +675,6 @@ AtaBusDriverBindingSupported ( return Status; } - /** Starts a device controller or a bus controller. @@ -714,19 +718,19 @@ AtaBusDriverBindingStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - ATA_BUS_DRIVER_DATA *AtaBusDriverData; - UINT16 Port; - UINT16 PortMultiplierPort; + EFI_STATUS Status; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + ATA_BUS_DRIVER_DATA *AtaBusDriverData; + UINT16 Port; + UINT16 PortMultiplierPort; AtaBusDriverData = NULL; Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -747,7 +751,7 @@ AtaBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiAtaPassThruProtocolGuid, - (VOID **) &AtaPassThru, + (VOID **)&AtaPassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -766,9 +770,9 @@ AtaBusDriverBindingStart ( goto ErrorExit; } - AtaBusDriverData->AtaPassThru = AtaPassThru; - AtaBusDriverData->Controller = Controller; - AtaBusDriverData->ParentDevicePath = ParentDevicePath; + AtaBusDriverData->AtaPassThru = AtaPassThru; + AtaBusDriverData->Controller = Controller; + AtaBusDriverData->ParentDevicePath = ParentDevicePath; AtaBusDriverData->DriverBindingHandle = This->DriverBindingHandle; Status = gBS->InstallMultipleProtocolInterfaces ( @@ -780,12 +784,11 @@ AtaBusDriverBindingStart ( if (EFI_ERROR (Status)) { goto ErrorExit; } - } else { Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &AtaBusDriverData, + (VOID **)&AtaBusDriverData, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -826,14 +829,16 @@ AtaBusDriverBindingStart ( // break; } + RegisterAtaDevice (AtaBusDriverData, Port, PortMultiplierPort); } } + Status = EFI_SUCCESS; } else if (!IsDevicePathEnd (RemainingDevicePath)) { Status = AtaPassThru->GetDevice (AtaPassThru, RemainingDevicePath, &Port, &PortMultiplierPort); if (!EFI_ERROR (Status)) { - Status = RegisterAtaDevice (AtaBusDriverData,Port, PortMultiplierPort); + Status = RegisterAtaDevice (AtaBusDriverData, Port, PortMultiplierPort); } } @@ -852,17 +857,15 @@ ErrorExit: } gBS->CloseProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); return Status; - } - /** Stops a device controller or a bus controller. @@ -892,42 +895,42 @@ ErrorExit: EFI_STATUS EFIAPI AtaBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - BOOLEAN AllChildrenStopped; - UINTN Index; - ATA_BUS_DRIVER_DATA *AtaBusDriverData; + EFI_STATUS Status; + BOOLEAN AllChildrenStopped; + UINTN Index; + ATA_BUS_DRIVER_DATA *AtaBusDriverData; if (NumberOfChildren == 0) { Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &AtaBusDriverData, + (VOID **)&AtaBusDriverData, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( - Controller, - &gEfiCallerIdGuid, - AtaBusDriverData, - NULL - ); + Controller, + &gEfiCallerIdGuid, + AtaBusDriverData, + NULL + ); FreePool (AtaBusDriverData); } gBS->CloseProtocol ( - Controller, - &gEfiAtaPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiAtaPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_SUCCESS; } @@ -935,7 +938,6 @@ AtaBusDriverBindingStop ( AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - Status = UnregisterAtaDevice (This, Controller, ChildHandleBuffer[Index]); if (EFI_ERROR (Status)) { AllChildrenStopped = FALSE; @@ -949,7 +951,6 @@ AtaBusDriverBindingStop ( return EFI_SUCCESS; } - /** Reset the Block Device. @@ -964,13 +965,13 @@ AtaBusDriverBindingStop ( EFI_STATUS EFIAPI AtaBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - ATA_DEVICE *AtaDevice; - EFI_TPL OldTpl; + EFI_STATUS Status; + ATA_DEVICE *AtaDevice; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); @@ -986,7 +987,6 @@ AtaBlockIoReset ( return Status; } - /** Read/Write BufferSize bytes from Lba from/into Buffer. @@ -1015,30 +1015,30 @@ AtaBlockIoReset ( **/ EFI_STATUS BlockIoReadWrite ( - IN VOID *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer, - IN BOOLEAN IsBlockIo2, - IN BOOLEAN IsWrite + IN VOID *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer, + IN BOOLEAN IsBlockIo2, + IN BOOLEAN IsWrite ) { - ATA_DEVICE *AtaDevice; - EFI_STATUS Status; - EFI_TPL OldTpl; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN IoAlign; + ATA_DEVICE *AtaDevice; + EFI_STATUS Status; + EFI_TPL OldTpl; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN IoAlign; if (IsBlockIo2) { - Media = ((EFI_BLOCK_IO2_PROTOCOL *) This)->Media; - AtaDevice = ATA_DEVICE_FROM_BLOCK_IO2 (This); + Media = ((EFI_BLOCK_IO2_PROTOCOL *)This)->Media; + AtaDevice = ATA_DEVICE_FROM_BLOCK_IO2 (This); } else { - Media = ((EFI_BLOCK_IO_PROTOCOL *) This)->Media; - AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (This); + Media = ((EFI_BLOCK_IO_PROTOCOL *)This)->Media; + AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (This); } if (MediaId != Media->MediaId) { @@ -1057,6 +1057,7 @@ BlockIoReadWrite ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -1065,13 +1066,13 @@ BlockIoReadWrite ( return EFI_BAD_BUFFER_SIZE; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1087,7 +1088,6 @@ BlockIoReadWrite ( return Status; } - /** Read BufferSize bytes from Lba into Buffer. @@ -1110,17 +1110,16 @@ BlockIoReadWrite ( EFI_STATUS EFIAPI AtaBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - return BlockIoReadWrite ((VOID *) This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, FALSE); + return BlockIoReadWrite ((VOID *)This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, FALSE); } - /** Write BufferSize bytes from Lba into Buffer. @@ -1144,17 +1143,16 @@ AtaBlockIoReadBlocks ( EFI_STATUS EFIAPI AtaBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { - return BlockIoReadWrite ((VOID *) This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, TRUE); + return BlockIoReadWrite ((VOID *)This, MediaId, Lba, NULL, BufferSize, Buffer, FALSE, TRUE); } - /** Flush the Block Device. @@ -1168,7 +1166,7 @@ AtaBlockIoWriteBlocks ( EFI_STATUS EFIAPI AtaBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ) { // @@ -1195,9 +1193,9 @@ AtaBlockIoResetEx ( IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - ATA_DEVICE *AtaDevice; - EFI_TPL OldTpl; + EFI_STATUS Status; + ATA_DEVICE *AtaDevice; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); @@ -1252,10 +1250,9 @@ AtaBlockIoReadBlocksEx ( OUT VOID *Buffer ) { - return BlockIoReadWrite ((VOID *) This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, FALSE); + return BlockIoReadWrite ((VOID *)This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, FALSE); } - /** Write BufferSize bytes from Lba into Buffer. @@ -1289,10 +1286,9 @@ AtaBlockIoWriteBlocksEx ( IN VOID *Buffer ) { - return BlockIoReadWrite ((VOID *) This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, TRUE); + return BlockIoReadWrite ((VOID *)This, MediaId, Lba, Token, BufferSize, Buffer, TRUE, TRUE); } - /** Flush the Block Device. @@ -1314,12 +1310,14 @@ AtaBlockIoFlushBlocksEx ( // // Signal event and return directly. // - if (Token != NULL && Token->Event != NULL) { + if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } + /** Provides inquiry information for the controller type. @@ -1339,15 +1337,14 @@ AtaBlockIoFlushBlocksEx ( EFI_STATUS EFIAPI AtaDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ) { return EFI_NOT_FOUND; } - /** Provides identify information for the controller type. @@ -1369,13 +1366,13 @@ AtaDiskInfoInquiry ( EFI_STATUS EFIAPI AtaDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ) { - EFI_STATUS Status; - ATA_DEVICE *AtaDevice; + EFI_STATUS Status; + ATA_DEVICE *AtaDevice; AtaDevice = ATA_DEVICE_FROM_DISK_INFO (This); @@ -1384,12 +1381,12 @@ AtaDiskInfoIdentify ( Status = EFI_SUCCESS; CopyMem (IdentifyData, AtaDevice->IdentifyData, sizeof (ATA_IDENTIFY_DATA)); } + *IdentifyDataSize = sizeof (ATA_IDENTIFY_DATA); return Status; } - /** Provides sense data information for the controller type. @@ -1410,16 +1407,15 @@ AtaDiskInfoIdentify ( EFI_STATUS EFIAPI AtaDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ) { return EFI_NOT_FOUND; } - /** This function is used by the IDE bus driver to get controller information. @@ -1434,16 +1430,16 @@ AtaDiskInfoSenseData ( EFI_STATUS EFIAPI AtaDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ) { - ATA_DEVICE *AtaDevice; + ATA_DEVICE *AtaDevice; - AtaDevice = ATA_DEVICE_FROM_DISK_INFO (This); - *IdeChannel = AtaDevice->Port; - *IdeDevice = AtaDevice->PortMultiplierPort; + AtaDevice = ATA_DEVICE_FROM_DISK_INFO (This); + *IdeChannel = AtaDevice->Port; + *IdeDevice = AtaDevice->PortMultiplierPort; return EFI_SUCCESS; } @@ -1523,22 +1519,22 @@ AtaDiskInfoWhichIde ( EFI_STATUS EFIAPI AtaStorageSecurityReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ) { - EFI_STATUS Status; - ATA_DEVICE *Private; - EFI_TPL OldTpl; + EFI_STATUS Status; + ATA_DEVICE *Private; + EFI_TPL OldTpl; DEBUG ((DEBUG_INFO, "EFI Storage Security Protocol - Read\n")); - if ((PayloadBuffer == NULL || PayloadTransferSize == NULL) && PayloadBufferSize != 0) { + if (((PayloadBuffer == NULL) || (PayloadTransferSize == NULL)) && (PayloadBufferSize != 0)) { return EFI_INVALID_PARAMETER; } @@ -1634,18 +1630,18 @@ AtaStorageSecurityReceiveData ( EFI_STATUS EFIAPI AtaStorageSecuritySendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ) { - EFI_STATUS Status; - ATA_DEVICE *Private; - EFI_TPL OldTpl; + EFI_STATUS Status; + ATA_DEVICE *Private; + EFI_TPL OldTpl; DEBUG ((DEBUG_INFO, "EFI Storage Security Protocol - Send\n")); if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) { @@ -1687,12 +1683,12 @@ AtaStorageSecuritySendData ( **/ EFI_STATUS EFIAPI -InitializeAtaBus( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeAtaBus ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h index a5a8652099..4428c484fd 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h @@ -38,27 +38,27 @@ // // Time out value for ATA pass through protocol // -#define ATA_TIMEOUT EFI_TIMER_PERIOD_SECONDS (3) +#define ATA_TIMEOUT EFI_TIMER_PERIOD_SECONDS (3) // // Maximum number of times to retry ATA command // -#define MAX_RETRY_TIMES 3 +#define MAX_RETRY_TIMES 3 // // The maximum total sectors count in 28 bit addressing mode // -#define MAX_28BIT_ADDRESSING_CAPACITY 0xfffffff +#define MAX_28BIT_ADDRESSING_CAPACITY 0xfffffff // // The maximum ATA transaction sector count in 28 bit addressing mode. // -#define MAX_28BIT_TRANSFER_BLOCK_NUM 0x100 +#define MAX_28BIT_TRANSFER_BLOCK_NUM 0x100 // // The maximum ATA transaction sector count in 48 bit addressing mode. // -//#define MAX_48BIT_TRANSFER_BLOCK_NUM 0x10000 +// #define MAX_48BIT_TRANSFER_BLOCK_NUM 0x10000 // // BugBug: if the TransferLength is equal with 0x10000 (the 48bit max length), @@ -66,109 +66,109 @@ // seems not ready. Change the Maximum Sector Numbers to 0xFFFF to work round // this issue. // -#define MAX_48BIT_TRANSFER_BLOCK_NUM 0xFFFF +#define MAX_48BIT_TRANSFER_BLOCK_NUM 0xFFFF // // The maximum model name in ATA identify data // -#define MAX_MODEL_NAME_LEN 40 +#define MAX_MODEL_NAME_LEN 40 -#define ATA_TASK_SIGNATURE SIGNATURE_32 ('A', 'T', 'S', 'K') -#define ATA_DEVICE_SIGNATURE SIGNATURE_32 ('A', 'B', 'I', 'D') -#define ATA_SUB_TASK_SIGNATURE SIGNATURE_32 ('A', 'S', 'T', 'S') -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define ATA_TASK_SIGNATURE SIGNATURE_32 ('A', 'T', 'S', 'K') +#define ATA_DEVICE_SIGNATURE SIGNATURE_32 ('A', 'B', 'I', 'D') +#define ATA_SUB_TASK_SIGNATURE SIGNATURE_32 ('A', 'S', 'T', 'S') +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) // // ATA bus data structure for ATA controller // typedef struct { - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_HANDLE Controller; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_HANDLE DriverBindingHandle; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_HANDLE Controller; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_HANDLE DriverBindingHandle; } ATA_BUS_DRIVER_DATA; // // ATA device data structure for each child device // typedef struct { - UINT32 Signature; + UINT32 Signature; - EFI_HANDLE Handle; - EFI_BLOCK_IO_PROTOCOL BlockIo; - EFI_BLOCK_IO2_PROTOCOL BlockIo2; - EFI_BLOCK_IO_MEDIA BlockMedia; - EFI_DISK_INFO_PROTOCOL DiskInfo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; + EFI_HANDLE Handle; + EFI_BLOCK_IO_PROTOCOL BlockIo; + EFI_BLOCK_IO2_PROTOCOL BlockIo2; + EFI_BLOCK_IO_MEDIA BlockMedia; + EFI_DISK_INFO_PROTOCOL DiskInfo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; - ATA_BUS_DRIVER_DATA *AtaBusDriverData; - UINT16 Port; - UINT16 PortMultiplierPort; + ATA_BUS_DRIVER_DATA *AtaBusDriverData; + UINT16 Port; + UINT16 PortMultiplierPort; // // Buffer for the execution of ATA pass through protocol // - EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; - EFI_ATA_COMMAND_BLOCK Acb; - EFI_ATA_STATUS_BLOCK *Asb; + EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; + EFI_ATA_COMMAND_BLOCK Acb; + EFI_ATA_STATUS_BLOCK *Asb; - BOOLEAN UdmaValid; - BOOLEAN Lba48Bit; + BOOLEAN UdmaValid; + BOOLEAN Lba48Bit; // // Cached data for ATA identify data // - ATA_IDENTIFY_DATA *IdentifyData; + ATA_IDENTIFY_DATA *IdentifyData; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; - CHAR16 ModelName[MAX_MODEL_NAME_LEN + 1]; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; + CHAR16 ModelName[MAX_MODEL_NAME_LEN + 1]; - LIST_ENTRY AtaTaskList; - LIST_ENTRY AtaSubTaskList; - BOOLEAN Abort; + LIST_ENTRY AtaTaskList; + LIST_ENTRY AtaSubTaskList; + BOOLEAN Abort; } ATA_DEVICE; // // Sub-Task for the non blocking I/O // typedef struct { - UINT32 Signature; - ATA_DEVICE *AtaDevice; - EFI_BLOCK_IO2_TOKEN *Token; - UINTN *UnsignalledEventCount; - EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; - BOOLEAN *IsError;// Indicate whether meeting error during source allocation for new task. - LIST_ENTRY TaskEntry; + UINT32 Signature; + ATA_DEVICE *AtaDevice; + EFI_BLOCK_IO2_TOKEN *Token; + UINTN *UnsignalledEventCount; + EFI_ATA_PASS_THRU_COMMAND_PACKET Packet; + BOOLEAN *IsError;// Indicate whether meeting error during source allocation for new task. + LIST_ENTRY TaskEntry; } ATA_BUS_ASYN_SUB_TASK; // // Task for the non blocking I/O // typedef struct { - UINT32 Signature; - EFI_BLOCK_IO2_TOKEN *Token; - ATA_DEVICE *AtaDevice; - UINT8 *Buffer; - EFI_LBA StartLba; - UINTN NumberOfBlocks; - BOOLEAN IsWrite; - LIST_ENTRY TaskEntry; + UINT32 Signature; + EFI_BLOCK_IO2_TOKEN *Token; + ATA_DEVICE *AtaDevice; + UINT8 *Buffer; + EFI_LBA StartLba; + UINTN NumberOfBlocks; + BOOLEAN IsWrite; + LIST_ENTRY TaskEntry; } ATA_BUS_ASYN_TASK; -#define ATA_DEVICE_FROM_BLOCK_IO(a) CR (a, ATA_DEVICE, BlockIo, ATA_DEVICE_SIGNATURE) -#define ATA_DEVICE_FROM_BLOCK_IO2(a) CR (a, ATA_DEVICE, BlockIo2, ATA_DEVICE_SIGNATURE) -#define ATA_DEVICE_FROM_DISK_INFO(a) CR (a, ATA_DEVICE, DiskInfo, ATA_DEVICE_SIGNATURE) -#define ATA_DEVICE_FROM_STORAGE_SECURITY(a) CR (a, ATA_DEVICE, StorageSecurity, ATA_DEVICE_SIGNATURE) -#define ATA_ASYN_SUB_TASK_FROM_ENTRY(a) CR (a, ATA_BUS_ASYN_SUB_TASK, TaskEntry, ATA_SUB_TASK_SIGNATURE) -#define ATA_ASYN_TASK_FROM_ENTRY(a) CR (a, ATA_BUS_ASYN_TASK, TaskEntry, ATA_TASK_SIGNATURE) +#define ATA_DEVICE_FROM_BLOCK_IO(a) CR (a, ATA_DEVICE, BlockIo, ATA_DEVICE_SIGNATURE) +#define ATA_DEVICE_FROM_BLOCK_IO2(a) CR (a, ATA_DEVICE, BlockIo2, ATA_DEVICE_SIGNATURE) +#define ATA_DEVICE_FROM_DISK_INFO(a) CR (a, ATA_DEVICE, DiskInfo, ATA_DEVICE_SIGNATURE) +#define ATA_DEVICE_FROM_STORAGE_SECURITY(a) CR (a, ATA_DEVICE, StorageSecurity, ATA_DEVICE_SIGNATURE) +#define ATA_ASYN_SUB_TASK_FROM_ENTRY(a) CR (a, ATA_BUS_ASYN_SUB_TASK, TaskEntry, ATA_SUB_TASK_SIGNATURE) +#define ATA_ASYN_TASK_FROM_ENTRY(a) CR (a, ATA_BUS_ASYN_TASK, TaskEntry, ATA_TASK_SIGNATURE) // // Global Variables // -extern EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gAtaBusComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gAtaBusComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gAtaBusDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gAtaBusComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gAtaBusComponentName2; /** Allocates an aligned buffer for ATA device. @@ -185,8 +185,8 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gAtaBusComponentName2; **/ VOID * AllocateAlignedBuffer ( - IN ATA_DEVICE *AtaDevice, - IN UINTN BufferSize + IN ATA_DEVICE *AtaDevice, + IN UINTN BufferSize ); /** @@ -201,8 +201,8 @@ AllocateAlignedBuffer ( **/ VOID FreeAlignedBuffer ( - IN VOID *Buffer, - IN UINTN BufferSize + IN VOID *Buffer, + IN UINTN BufferSize ); /** @@ -230,10 +230,9 @@ FreeAtaSubTask ( **/ EFI_STATUS ResetAtaDevice ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ); - /** Discovers whether it is a valid ATA device. @@ -250,7 +249,7 @@ ResetAtaDevice ( **/ EFI_STATUS DiscoverAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice + IN OUT ATA_DEVICE *AtaDevice ); /** @@ -272,13 +271,13 @@ DiscoverAtaDevice ( **/ EFI_STATUS -AccessAtaDevice( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT UINT8 *Buffer, - IN EFI_LBA StartLba, - IN UINTN NumberOfBlocks, - IN BOOLEAN IsWrite, - IN OUT EFI_BLOCK_IO2_TOKEN *Token +AccessAtaDevice ( + IN OUT ATA_DEVICE *AtaDevice, + IN OUT UINT8 *Buffer, + IN EFI_LBA StartLba, + IN UINTN NumberOfBlocks, + IN BOOLEAN IsWrite, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -313,19 +312,20 @@ AccessAtaDevice( EFI_STATUS EFIAPI TrustTransferAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN OUT ATA_DEVICE *AtaDevice, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ); // // Protocol interface prototypes // + /** Tests to see if this driver supports a given controller. If a child device is provided, it further tests to see if this driver supports creating a handle for the specified child device. @@ -448,13 +448,12 @@ AtaBusDriverBindingStart ( EFI_STATUS EFIAPI AtaBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); - /** Retrieves a Unicode string that is the user readable name of the driver. @@ -502,7 +501,6 @@ AtaBusComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -574,14 +572,13 @@ AtaBusComponentNameGetDriverName ( EFI_STATUS EFIAPI AtaBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); - /** Reset the Block Device. @@ -596,11 +593,10 @@ AtaBusComponentNameGetControllerName ( EFI_STATUS EFIAPI AtaBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); - /** Read BufferSize bytes from Lba into Buffer. @@ -623,14 +619,13 @@ AtaBlockIoReset ( EFI_STATUS EFIAPI AtaBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ); - /** Write BufferSize bytes from Lba into Buffer. @@ -654,14 +649,13 @@ AtaBlockIoReadBlocks ( EFI_STATUS EFIAPI AtaBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); - /** Flush the Block Device. @@ -675,7 +669,7 @@ AtaBlockIoWriteBlocks ( EFI_STATUS EFIAPI AtaBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ); /** @@ -797,7 +791,7 @@ AtaBlockIoFlushBlocksEx ( VOID EFIAPI AtaTerminateNonBlockingTask ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ); /** @@ -819,12 +813,11 @@ AtaTerminateNonBlockingTask ( EFI_STATUS EFIAPI AtaDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ); - /** Provides identify information for the controller type. @@ -846,12 +839,11 @@ AtaDiskInfoInquiry ( EFI_STATUS EFIAPI AtaDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ); - /** Provides sense data information for the controller type. @@ -872,13 +864,12 @@ AtaDiskInfoIdentify ( EFI_STATUS EFIAPI AtaDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ); - /** This function is used by the IDE bus driver to get controller information. @@ -893,9 +884,9 @@ AtaDiskInfoSenseData ( EFI_STATUS EFIAPI AtaDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ); /** @@ -973,14 +964,14 @@ AtaDiskInfoWhichIde ( EFI_STATUS EFIAPI AtaStorageSecurityReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ); /** @@ -1047,13 +1038,13 @@ AtaStorageSecurityReceiveData ( EFI_STATUS EFIAPI AtaStorageSecuritySendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ); /** @@ -1069,7 +1060,7 @@ AtaStorageSecuritySendData ( **/ VOID InitiateTPerReset ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ); #endif diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c index c947a778a0..4334169d25 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c @@ -19,16 +19,16 @@ #include "AtaBus.h" -#define ATA_CMD_TRUST_NON_DATA 0x5B -#define ATA_CMD_TRUST_RECEIVE 0x5C -#define ATA_CMD_TRUST_RECEIVE_DMA 0x5D -#define ATA_CMD_TRUST_SEND 0x5E -#define ATA_CMD_TRUST_SEND_DMA 0x5F +#define ATA_CMD_TRUST_NON_DATA 0x5B +#define ATA_CMD_TRUST_RECEIVE 0x5C +#define ATA_CMD_TRUST_RECEIVE_DMA 0x5D +#define ATA_CMD_TRUST_SEND 0x5E +#define ATA_CMD_TRUST_SEND_DMA 0x5F // // Look up table (UdmaValid, IsWrite) for EFI_ATA_PASS_THRU_CMD_PROTOCOL // -EFI_ATA_PASS_THRU_CMD_PROTOCOL mAtaPassThruCmdProtocols[][2] = { +EFI_ATA_PASS_THRU_CMD_PROTOCOL mAtaPassThruCmdProtocols[][2] = { { EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN, EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_OUT @@ -42,7 +42,7 @@ EFI_ATA_PASS_THRU_CMD_PROTOCOL mAtaPassThruCmdProtocols[][2] = { // // Look up table (UdmaValid, Lba48Bit, IsIsWrite) for ATA_CMD // -UINT8 mAtaCommands[][2][2] = { +UINT8 mAtaCommands[][2][2] = { { { ATA_CMD_READ_SECTORS, // 28-bit LBA; PIO read @@ -68,7 +68,7 @@ UINT8 mAtaCommands[][2][2] = { // // Look up table (UdmaValid, IsTrustSend) for ATA_CMD // -UINT8 mAtaTrustCommands[2][2] = { +UINT8 mAtaTrustCommands[2][2] = { { ATA_CMD_TRUST_RECEIVE, // PIO read ATA_CMD_TRUST_SEND // PIO write @@ -79,16 +79,14 @@ UINT8 mAtaTrustCommands[2][2] = { } }; - // // Look up table (Lba48Bit) for maximum transfer block number // -UINTN mMaxTransferBlockNumber[] = { +UINTN mMaxTransferBlockNumber[] = { MAX_28BIT_TRANSFER_BLOCK_NUM, MAX_48BIT_TRANSFER_BLOCK_NUM }; - /** Wrapper for EFI_ATA_PASS_THRU_PROTOCOL.PassThru(). @@ -112,21 +110,21 @@ UINTN mMaxTransferBlockNumber[] = { **/ EFI_STATUS AtaDevicePassThru ( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *TaskPacket OPTIONAL, - IN OUT EFI_EVENT Event OPTIONAL + IN OUT ATA_DEVICE *AtaDevice, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *TaskPacket OPTIONAL, + IN OUT EFI_EVENT Event OPTIONAL ) { - EFI_STATUS Status; - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; - EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet; + EFI_STATUS Status; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_ATA_PASS_THRU_COMMAND_PACKET *Packet; // // Assemble packet. If it is non blocking mode, the Ata driver should keep each // subtask and clean them when the event is signaled. // if (TaskPacket != NULL) { - Packet = TaskPacket; + Packet = TaskPacket; Packet->Asb = AllocateAlignedBuffer (AtaDevice, sizeof (EFI_ATA_STATUS_BLOCK)); if (Packet->Asb == NULL) { return EFI_OUT_OF_RESOURCES; @@ -135,7 +133,7 @@ AtaDevicePassThru ( CopyMem (Packet->Asb, AtaDevice->Asb, sizeof (EFI_ATA_STATUS_BLOCK)); Packet->Acb = AllocateCopyPool (sizeof (EFI_ATA_COMMAND_BLOCK), &AtaDevice->Acb); } else { - Packet = &AtaDevice->Packet; + Packet = &AtaDevice->Packet; Packet->Asb = AtaDevice->Asb; Packet->Acb = &AtaDevice->Acb; } @@ -159,7 +157,6 @@ AtaDevicePassThru ( return Status; } - /** Wrapper for EFI_ATA_PASS_THRU_PROTOCOL.ResetDevice(). @@ -173,10 +170,10 @@ AtaDevicePassThru ( **/ EFI_STATUS ResetAtaDevice ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ) { - EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; + EFI_ATA_PASS_THRU_PROTOCOL *AtaPassThru; AtaPassThru = AtaDevice->AtaBusDriverData->AtaPassThru; @@ -196,7 +193,6 @@ ResetAtaDevice ( ); } - /** Prints ATA model name to ATA device structure. @@ -216,20 +212,20 @@ PrintAtaModelName ( CHAR8 *Source; CHAR16 *Destination; - Source = AtaDevice->IdentifyData->ModelName; + Source = AtaDevice->IdentifyData->ModelName; Destination = AtaDevice->ModelName; // // Swap the byte order in the original module name. // for (Index = 0; Index < MAX_MODEL_NAME_LEN; Index += 2) { - Destination[Index] = Source[Index + 1]; - Destination[Index + 1] = Source[Index]; + Destination[Index] = Source[Index + 1]; + Destination[Index + 1] = Source[Index]; } + AtaDevice->ModelName[MAX_MODEL_NAME_LEN] = L'\0'; } - /** Gets ATA device Capacity according to ATA 6. @@ -244,13 +240,13 @@ PrintAtaModelName ( **/ EFI_LBA GetAtapi6Capacity ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ) { - EFI_LBA Capacity; - EFI_LBA TmpLba; - UINTN Index; - ATA_IDENTIFY_DATA *IdentifyData; + EFI_LBA Capacity; + EFI_LBA TmpLba; + UINTN Index; + ATA_IDENTIFY_DATA *IdentifyData; IdentifyData = AtaDevice->IdentifyData; if ((IdentifyData->command_set_supported_83 & BIT10) == 0) { @@ -268,14 +264,13 @@ GetAtapi6Capacity ( // // Lower byte goes first: word[100] is the lowest word, word[103] is highest // - TmpLba = IdentifyData->maximum_lba_for_48bit_addressing[Index]; + TmpLba = IdentifyData->maximum_lba_for_48bit_addressing[Index]; Capacity |= LShiftU64 (TmpLba, 16 * Index); } return Capacity; } - /** Identifies ATA device via the Identify data. @@ -291,14 +286,14 @@ GetAtapi6Capacity ( **/ EFI_STATUS IdentifyAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice + IN OUT ATA_DEVICE *AtaDevice ) { - ATA_IDENTIFY_DATA *IdentifyData; - EFI_BLOCK_IO_MEDIA *BlockMedia; - EFI_LBA Capacity; - UINT16 PhyLogicSectorSupport; - UINT16 UdmaMode; + ATA_IDENTIFY_DATA *IdentifyData; + EFI_BLOCK_IO_MEDIA *BlockMedia; + EFI_LBA Capacity; + UINT16 PhyLogicSectorSupport; + UINT16 UdmaMode; IdentifyData = AtaDevice->IdentifyData; @@ -334,16 +329,16 @@ IdentifyAtaDevice ( // // This is a hard disk <= 120GB capacity, treat it as normal hard disk // - Capacity = ((UINT32)IdentifyData->user_addressable_sectors_hi << 16) | IdentifyData->user_addressable_sectors_lo; + Capacity = ((UINT32)IdentifyData->user_addressable_sectors_hi << 16) | IdentifyData->user_addressable_sectors_lo; AtaDevice->Lba48Bit = FALSE; } // // Block Media Information: // - BlockMedia = &AtaDevice->BlockMedia; + BlockMedia = &AtaDevice->BlockMedia; BlockMedia->LastBlock = Capacity - 1; - BlockMedia->IoAlign = AtaDevice->AtaBusDriverData->AtaPassThru->Mode->IoAlign; + BlockMedia->IoAlign = AtaDevice->AtaBusDriverData->AtaPassThru->Mode->IoAlign; // // Check whether Long Physical Sector Feature is supported // @@ -353,23 +348,26 @@ IdentifyAtaDevice ( // Check whether one physical block contains multiple physical blocks // if ((PhyLogicSectorSupport & BIT13) != 0) { - BlockMedia->LogicalBlocksPerPhysicalBlock = (UINT32) (1 << (PhyLogicSectorSupport & 0x000f)); + BlockMedia->LogicalBlocksPerPhysicalBlock = (UINT32)(1 << (PhyLogicSectorSupport & 0x000f)); // // Check lowest alignment of logical blocks within physical block // if ((IdentifyData->alignment_logic_in_phy_blocks & (BIT14 | BIT15)) == BIT14) { - BlockMedia->LowestAlignedLba = (EFI_LBA) ((BlockMedia->LogicalBlocksPerPhysicalBlock - ((UINT32)IdentifyData->alignment_logic_in_phy_blocks & 0x3fff)) % - BlockMedia->LogicalBlocksPerPhysicalBlock); + BlockMedia->LowestAlignedLba = (EFI_LBA)((BlockMedia->LogicalBlocksPerPhysicalBlock - ((UINT32)IdentifyData->alignment_logic_in_phy_blocks & 0x3fff)) % + BlockMedia->LogicalBlocksPerPhysicalBlock); } } + // // Check logical block size // if ((PhyLogicSectorSupport & BIT12) != 0) { - BlockMedia->BlockSize = (UINT32) (((IdentifyData->logic_sector_size_hi << 16) | IdentifyData->logic_sector_size_lo) * sizeof (UINT16)); + BlockMedia->BlockSize = (UINT32)(((IdentifyData->logic_sector_size_hi << 16) | IdentifyData->logic_sector_size_lo) * sizeof (UINT16)); } + AtaDevice->BlockIo.Revision = EFI_BLOCK_IO_PROTOCOL_REVISION2; } + // // Get ATA model name from identify data structure. // @@ -378,7 +376,6 @@ IdentifyAtaDevice ( return EFI_SUCCESS; } - /** Discovers whether it is a valid ATA device. @@ -395,7 +392,7 @@ IdentifyAtaDevice ( **/ EFI_STATUS DiscoverAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice + IN OUT ATA_DEVICE *AtaDevice ) { EFI_STATUS Status; @@ -406,19 +403,19 @@ DiscoverAtaDevice ( // // Prepare for ATA command block. // - Acb = ZeroMem (&AtaDevice->Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); - Acb->AtaCommand = ATA_CMD_IDENTIFY_DRIVE; - Acb->AtaDeviceHead = (UINT8) (BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); + Acb = ZeroMem (&AtaDevice->Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); + Acb->AtaCommand = ATA_CMD_IDENTIFY_DRIVE; + Acb->AtaDeviceHead = (UINT8)(BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); // // Prepare for ATA pass through packet. // - Packet = ZeroMem (&AtaDevice->Packet, sizeof (EFI_ATA_PASS_THRU_COMMAND_PACKET)); - Packet->InDataBuffer = AtaDevice->IdentifyData; + Packet = ZeroMem (&AtaDevice->Packet, sizeof (EFI_ATA_PASS_THRU_COMMAND_PACKET)); + Packet->InDataBuffer = AtaDevice->IdentifyData; Packet->InTransferLength = sizeof (ATA_IDENTIFY_DATA); - Packet->Protocol = EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN; - Packet->Length = EFI_ATA_PASS_THRU_LENGTH_BYTES | EFI_ATA_PASS_THRU_LENGTH_SECTOR_COUNT; - Packet->Timeout = ATA_TIMEOUT; + Packet->Protocol = EFI_ATA_PASS_THRU_PROTOCOL_PIO_DATA_IN; + Packet->Length = EFI_ATA_PASS_THRU_LENGTH_BYTES | EFI_ATA_PASS_THRU_LENGTH_SECTOR_COUNT; + Packet->Timeout = ATA_TIMEOUT; Retry = MAX_RETRY_TIMES; do { @@ -463,13 +460,13 @@ DiscoverAtaDevice ( **/ EFI_STATUS TransferAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *TaskPacket OPTIONAL, - IN OUT VOID *Buffer, - IN EFI_LBA StartLba, - IN UINT32 TransferLength, - IN BOOLEAN IsWrite, - IN EFI_EVENT Event OPTIONAL + IN OUT ATA_DEVICE *AtaDevice, + IN OUT EFI_ATA_PASS_THRU_COMMAND_PACKET *TaskPacket OPTIONAL, + IN OUT VOID *Buffer, + IN EFI_LBA StartLba, + IN UINT32 TransferLength, + IN BOOLEAN IsWrite, + IN EFI_EVENT Event OPTIONAL ) { EFI_ATA_COMMAND_BLOCK *Acb; @@ -478,26 +475,26 @@ TransferAtaDevice ( // // Ensure AtaDevice->UdmaValid, AtaDevice->Lba48Bit and IsWrite are valid boolean values // - ASSERT ((UINTN) AtaDevice->UdmaValid < 2); - ASSERT ((UINTN) AtaDevice->Lba48Bit < 2); - ASSERT ((UINTN) IsWrite < 2); + ASSERT ((UINTN)AtaDevice->UdmaValid < 2); + ASSERT ((UINTN)AtaDevice->Lba48Bit < 2); + ASSERT ((UINTN)IsWrite < 2); // // Prepare for ATA command block. // - Acb = ZeroMem (&AtaDevice->Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); - Acb->AtaCommand = mAtaCommands[AtaDevice->UdmaValid][AtaDevice->Lba48Bit][IsWrite]; - Acb->AtaSectorNumber = (UINT8) StartLba; - Acb->AtaCylinderLow = (UINT8) RShiftU64 (StartLba, 8); - Acb->AtaCylinderHigh = (UINT8) RShiftU64 (StartLba, 16); - Acb->AtaDeviceHead = (UINT8) (BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); - Acb->AtaSectorCount = (UINT8) TransferLength; + Acb = ZeroMem (&AtaDevice->Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); + Acb->AtaCommand = mAtaCommands[AtaDevice->UdmaValid][AtaDevice->Lba48Bit][IsWrite]; + Acb->AtaSectorNumber = (UINT8)StartLba; + Acb->AtaCylinderLow = (UINT8)RShiftU64 (StartLba, 8); + Acb->AtaCylinderHigh = (UINT8)RShiftU64 (StartLba, 16); + Acb->AtaDeviceHead = (UINT8)(BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); + Acb->AtaSectorCount = (UINT8)TransferLength; if (AtaDevice->Lba48Bit) { - Acb->AtaSectorNumberExp = (UINT8) RShiftU64 (StartLba, 24); - Acb->AtaCylinderLowExp = (UINT8) RShiftU64 (StartLba, 32); - Acb->AtaCylinderHighExp = (UINT8) RShiftU64 (StartLba, 40); - Acb->AtaSectorCountExp = (UINT8) (TransferLength >> 8); + Acb->AtaSectorNumberExp = (UINT8)RShiftU64 (StartLba, 24); + Acb->AtaCylinderLowExp = (UINT8)RShiftU64 (StartLba, 32); + Acb->AtaCylinderHighExp = (UINT8)RShiftU64 (StartLba, 40); + Acb->AtaSectorCountExp = (UINT8)(TransferLength >> 8); } else { - Acb->AtaDeviceHead = (UINT8) (Acb->AtaDeviceHead | RShiftU64 (StartLba, 24)); + Acb->AtaDeviceHead = (UINT8)(Acb->AtaDeviceHead | RShiftU64 (StartLba, 24)); } // @@ -510,15 +507,15 @@ TransferAtaDevice ( } if (IsWrite) { - Packet->OutDataBuffer = Buffer; + Packet->OutDataBuffer = Buffer; Packet->OutTransferLength = TransferLength; } else { - Packet->InDataBuffer = Buffer; + Packet->InDataBuffer = Buffer; Packet->InTransferLength = TransferLength; } Packet->Protocol = mAtaPassThruCmdProtocols[AtaDevice->UdmaValid][IsWrite]; - Packet->Length = EFI_ATA_PASS_THRU_LENGTH_SECTOR_COUNT; + Packet->Length = EFI_ATA_PASS_THRU_LENGTH_SECTOR_COUNT; // // |------------------------|-----------------|------------------------|-----------------| // | ATA PIO Transfer Mode | Transfer Rate | ATA DMA Transfer Mode | Transfer Rate | @@ -544,12 +541,12 @@ TransferAtaDevice ( // // Calculate the maximum timeout value for DMA read/write operation. // - Packet->Timeout = EFI_TIMER_PERIOD_SECONDS (DivU64x32 (MultU64x32 (TransferLength, AtaDevice->BlockMedia.BlockSize), 2100000) + 31); + Packet->Timeout = EFI_TIMER_PERIOD_SECONDS (DivU64x32 (MultU64x32 (TransferLength, AtaDevice->BlockMedia.BlockSize), 2100000) + 31); } else { // // Calculate the maximum timeout value for PIO read/write operation // - Packet->Timeout = EFI_TIMER_PERIOD_SECONDS (DivU64x32 (MultU64x32 (TransferLength, AtaDevice->BlockMedia.BlockSize), 3300000) + 31); + Packet->Timeout = EFI_TIMER_PERIOD_SECONDS (DivU64x32 (MultU64x32 (TransferLength, AtaDevice->BlockMedia.BlockSize), 3300000) + 31); } return AtaDevicePassThru (AtaDevice, TaskPacket, Event); @@ -570,6 +567,7 @@ FreeAtaSubTask ( if (Task->Packet.Asb != NULL) { FreeAlignedBuffer (Task->Packet.Asb, sizeof (EFI_ATA_STATUS_BLOCK)); } + if (Task->Packet.Acb != NULL) { FreePool (Task->Packet.Acb); } @@ -590,14 +588,14 @@ FreeAtaSubTask ( VOID EFIAPI AtaTerminateNonBlockingTask ( - IN ATA_DEVICE *AtaDevice + IN ATA_DEVICE *AtaDevice ) { - BOOLEAN SubTaskEmpty; - EFI_TPL OldTpl; - ATA_BUS_ASYN_TASK *AtaTask; - LIST_ENTRY *Entry; - LIST_ENTRY *List; + BOOLEAN SubTaskEmpty; + EFI_TPL OldTpl; + ATA_BUS_ASYN_TASK *AtaTask; + LIST_ENTRY *Entry; + LIST_ENTRY *List; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); // @@ -607,13 +605,14 @@ AtaTerminateNonBlockingTask ( List = &AtaDevice->AtaTaskList; for (Entry = GetFirstNode (List); !IsNull (List, Entry);) { - AtaTask = ATA_ASYN_TASK_FROM_ENTRY (Entry); + AtaTask = ATA_ASYN_TASK_FROM_ENTRY (Entry); AtaTask->Token->TransactionStatus = EFI_ABORTED; gBS->SignalEvent (AtaTask->Token->Event); Entry = RemoveEntryList (Entry); FreePool (AtaTask); } + gBS->RestoreTPL (OldTpl); do { @@ -628,7 +627,7 @@ AtaTerminateNonBlockingTask ( // // Aborting operation has been done. From now on, don't need to abort normal operation. // - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); AtaDevice->Abort = FALSE; gBS->RestoreTPL (OldTpl); } @@ -644,17 +643,17 @@ AtaTerminateNonBlockingTask ( VOID EFIAPI AtaNonBlockingCallBack ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - ATA_BUS_ASYN_SUB_TASK *Task; - ATA_BUS_ASYN_TASK *AtaTask; - ATA_DEVICE *AtaDevice; - LIST_ENTRY *Entry; - EFI_STATUS Status; + ATA_BUS_ASYN_SUB_TASK *Task; + ATA_BUS_ASYN_TASK *AtaTask; + ATA_DEVICE *AtaDevice; + LIST_ENTRY *Entry; + EFI_STATUS Status; - Task = (ATA_BUS_ASYN_SUB_TASK *) Context; + Task = (ATA_BUS_ASYN_SUB_TASK *)Context; gBS->CloseEvent (Event); AtaDevice = Task->AtaDevice; @@ -682,7 +681,7 @@ AtaNonBlockingCallBack ( // // Reduce the SubEventCount, till it comes to zero. // - (*Task->UnsignalledEventCount) --; + (*Task->UnsignalledEventCount)--; DEBUG ((DEBUG_BLKIO, "UnsignalledEventCount = %d\n", *Task->UnsignalledEventCount)); // @@ -702,7 +701,6 @@ AtaNonBlockingCallBack ( FreePool (Task->UnsignalledEventCount); FreePool (Task->IsError); - // // Finish all subtasks and move to the next task in AtaTaskList. // @@ -723,6 +721,7 @@ AtaNonBlockingCallBack ( AtaTask->Token->TransactionStatus = Status; gBS->SignalEvent (AtaTask->Token->Event); } + RemoveEntryList (Entry); FreePool (AtaTask); } @@ -763,27 +762,27 @@ AtaNonBlockingCallBack ( **/ EFI_STATUS -AccessAtaDevice( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT UINT8 *Buffer, - IN EFI_LBA StartLba, - IN UINTN NumberOfBlocks, - IN BOOLEAN IsWrite, - IN OUT EFI_BLOCK_IO2_TOKEN *Token +AccessAtaDevice ( + IN OUT ATA_DEVICE *AtaDevice, + IN OUT UINT8 *Buffer, + IN EFI_LBA StartLba, + IN UINTN NumberOfBlocks, + IN BOOLEAN IsWrite, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - UINTN MaxTransferBlockNumber; - UINTN TransferBlockNumber; - UINTN BlockSize; - ATA_BUS_ASYN_SUB_TASK *SubTask; - UINTN *EventCount; - UINTN TempCount; - ATA_BUS_ASYN_TASK *AtaTask; - EFI_EVENT SubEvent; - UINTN Index; - BOOLEAN *IsError; - EFI_TPL OldTpl; + EFI_STATUS Status; + UINTN MaxTransferBlockNumber; + UINTN TransferBlockNumber; + UINTN BlockSize; + ATA_BUS_ASYN_SUB_TASK *SubTask; + UINTN *EventCount; + UINTN TempCount; + ATA_BUS_ASYN_TASK *AtaTask; + EFI_EVENT SubEvent; + UINTN Index; + BOOLEAN *IsError; + EFI_TPL OldTpl; TempCount = 0; Status = EFI_SUCCESS; @@ -797,7 +796,7 @@ AccessAtaDevice( // // Ensure AtaDevice->Lba48Bit is a valid boolean value // - ASSERT ((UINTN) AtaDevice->Lba48Bit < 2); + ASSERT ((UINTN)AtaDevice->Lba48Bit < 2); MaxTransferBlockNumber = mMaxTransferBlockNumber[AtaDevice->Lba48Bit]; BlockSize = AtaDevice->BlockMedia.BlockSize; @@ -813,6 +812,7 @@ AccessAtaDevice( gBS->RestoreTPL (OldTpl); return EFI_OUT_OF_RESOURCES; } + AtaTask->AtaDevice = AtaDevice; AtaTask->Buffer = Buffer; AtaTask->IsWrite = IsWrite; @@ -825,10 +825,11 @@ AccessAtaDevice( gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; } + gBS->RestoreTPL (OldTpl); Token->TransactionStatus = EFI_SUCCESS; - EventCount = AllocateZeroPool (sizeof (UINTN)); + EventCount = AllocateZeroPool (sizeof (UINTN)); if (EventCount == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -838,8 +839,9 @@ AccessAtaDevice( FreePool (EventCount); return EFI_OUT_OF_RESOURCES; } + DEBUG ((DEBUG_BLKIO, "Allocation IsError Addr=%x\n", IsError)); - *IsError = FALSE; + *IsError = FALSE; TempCount = (NumberOfBlocks + MaxTransferBlockNumber - 1) / MaxTransferBlockNumber; *EventCount = TempCount; DEBUG ((DEBUG_BLKIO, "AccessAtaDevice, NumberOfBlocks=%x\n", NumberOfBlocks)); @@ -858,7 +860,7 @@ AccessAtaDevice( if (NumberOfBlocks > MaxTransferBlockNumber) { TransferBlockNumber = MaxTransferBlockNumber; NumberOfBlocks -= MaxTransferBlockNumber; - } else { + } else { TransferBlockNumber = NumberOfBlocks; NumberOfBlocks = 0; } @@ -876,7 +878,7 @@ AccessAtaDevice( goto EXIT; } - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); SubTask->UnsignalledEventCount = EventCount; SubTask->Signature = ATA_SUB_TASK_SIGNATURE; SubTask->AtaDevice = AtaDevice; @@ -901,13 +903,13 @@ AccessAtaDevice( goto EXIT; } - Status = TransferAtaDevice (AtaDevice, &SubTask->Packet, Buffer, StartLba, (UINT32) TransferBlockNumber, IsWrite, SubEvent); + Status = TransferAtaDevice (AtaDevice, &SubTask->Packet, Buffer, StartLba, (UINT32)TransferBlockNumber, IsWrite, SubEvent); } else { // // Blocking Mode. // DEBUG ((DEBUG_BLKIO, "Blocking AccessAtaDevice, TransferBlockNumber=%x; StartLba = %x\n", TransferBlockNumber, StartLba)); - Status = TransferAtaDevice (AtaDevice, NULL, Buffer, StartLba, (UINT32) TransferBlockNumber, IsWrite, NULL); + Status = TransferAtaDevice (AtaDevice, NULL, Buffer, StartLba, (UINT32)TransferBlockNumber, IsWrite, NULL); } if (EFI_ERROR (Status)) { @@ -925,10 +927,10 @@ EXIT: // Release resource at non-blocking mode. // if (EFI_ERROR (Status)) { - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); Token->TransactionStatus = Status; - *EventCount = (*EventCount) - (TempCount - Index); - *IsError = TRUE; + *EventCount = (*EventCount) - (TempCount - Index); + *IsError = TRUE; if (*EventCount == 0) { FreePool (EventCount); @@ -943,6 +945,7 @@ EXIT: if (SubEvent != NULL) { gBS->CloseEvent (SubEvent); } + gBS->RestoreTPL (OldTpl); } } @@ -982,14 +985,14 @@ EXIT: EFI_STATUS EFIAPI TrustTransferAtaDevice ( - IN OUT ATA_DEVICE *AtaDevice, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN OUT ATA_DEVICE *AtaDevice, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ) { EFI_ATA_COMMAND_BLOCK *Acb; @@ -1001,27 +1004,28 @@ TrustTransferAtaDevice ( // // Ensure AtaDevice->UdmaValid and IsTrustSend are valid boolean values // - ASSERT ((UINTN) AtaDevice->UdmaValid < 2); - ASSERT ((UINTN) IsTrustSend < 2); + ASSERT ((UINTN)AtaDevice->UdmaValid < 2); + ASSERT ((UINTN)IsTrustSend < 2); // // Prepare for ATA command block. // Acb = ZeroMem (&AtaDevice->Acb, sizeof (EFI_ATA_COMMAND_BLOCK)); if (TransferLength == 0) { - Acb->AtaCommand = ATA_CMD_TRUST_NON_DATA; + Acb->AtaCommand = ATA_CMD_TRUST_NON_DATA; } else { - Acb->AtaCommand = mAtaTrustCommands[AtaDevice->UdmaValid][IsTrustSend]; + Acb->AtaCommand = mAtaTrustCommands[AtaDevice->UdmaValid][IsTrustSend]; } - Acb->AtaFeatures = SecurityProtocolId; - Acb->AtaSectorCount = (UINT8) (TransferLength / 512); - Acb->AtaSectorNumber = (UINT8) ((TransferLength / 512) >> 8); + + Acb->AtaFeatures = SecurityProtocolId; + Acb->AtaSectorCount = (UINT8)(TransferLength / 512); + Acb->AtaSectorNumber = (UINT8)((TransferLength / 512) >> 8); // // NOTE: ATA Spec has no explicitly definition for Security Protocol Specific layout. // Here use big endian for Cylinder register. // - Acb->AtaCylinderHigh = (UINT8) SecurityProtocolSpecificData; - Acb->AtaCylinderLow = (UINT8) (SecurityProtocolSpecificData >> 8); - Acb->AtaDeviceHead = (UINT8) (BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); + Acb->AtaCylinderHigh = (UINT8)SecurityProtocolSpecificData; + Acb->AtaCylinderLow = (UINT8)(SecurityProtocolSpecificData >> 8); + Acb->AtaDeviceHead = (UINT8)(BIT7 | BIT6 | BIT5 | (AtaDevice->PortMultiplierPort == 0xFFFF ? 0 : (AtaDevice->PortMultiplierPort << 4))); // // Prepare for ATA pass through packet. @@ -1030,7 +1034,7 @@ TrustTransferAtaDevice ( if (TransferLength == 0) { Packet->InTransferLength = 0; Packet->OutTransferLength = 0; - Packet->Protocol = EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA; + Packet->Protocol = EFI_ATA_PASS_THRU_PROTOCOL_ATA_NON_DATA; } else if (IsTrustSend) { // // Check the alignment of the incoming buffer prior to invoking underlying ATA PassThru @@ -1046,22 +1050,25 @@ TrustTransferAtaDevice ( FreePool (Buffer); Buffer = NewBuffer; } - Packet->OutDataBuffer = Buffer; - Packet->OutTransferLength = (UINT32) TransferLength; - Packet->Protocol = mAtaPassThruCmdProtocols[AtaDevice->UdmaValid][IsTrustSend]; + + Packet->OutDataBuffer = Buffer; + Packet->OutTransferLength = (UINT32)TransferLength; + Packet->Protocol = mAtaPassThruCmdProtocols[AtaDevice->UdmaValid][IsTrustSend]; } else { - Packet->InDataBuffer = Buffer; - Packet->InTransferLength = (UINT32) TransferLength; - Packet->Protocol = mAtaPassThruCmdProtocols[AtaDevice->UdmaValid][IsTrustSend]; + Packet->InDataBuffer = Buffer; + Packet->InTransferLength = (UINT32)TransferLength; + Packet->Protocol = mAtaPassThruCmdProtocols[AtaDevice->UdmaValid][IsTrustSend]; } - Packet->Length = EFI_ATA_PASS_THRU_LENGTH_BYTES; - Packet->Timeout = Timeout; + + Packet->Length = EFI_ATA_PASS_THRU_LENGTH_BYTES; + Packet->Timeout = Timeout; Status = AtaDevicePassThru (AtaDevice, NULL, NULL); if (TransferLengthOut != NULL) { - if (! IsTrustSend) { + if (!IsTrustSend) { *TransferLengthOut = Packet->InTransferLength; } } + return Status; } diff --git a/MdeModulePkg/Bus/Ata/AtaBusDxe/ComponentName.c b/MdeModulePkg/Bus/Ata/AtaBusDxe/ComponentName.c index bb219072fb..920e26cc75 100644 --- a/MdeModulePkg/Bus/Ata/AtaBusDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Ata/AtaBusDxe/ComponentName.c @@ -11,20 +11,19 @@ // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaBusDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaBusDriverNameTable[] = { { "eng;en", L"ATA Bus Driver" }, - { NULL , NULL } + { NULL, NULL } }; // // Controller name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaBusControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mAtaBusControllerNameTable[] = { { "eng;en", L"ATA Controller" }, - { NULL , NULL } + { NULL, NULL } }; - // // EFI Component Name Protocol // @@ -37,9 +36,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gAtaBusComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gAtaBusComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) AtaBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) AtaBusComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gAtaBusComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)AtaBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)AtaBusComponentNameGetControllerName, "en" }; @@ -99,7 +98,6 @@ AtaBusComponentNameGetDriverName ( ); } - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -171,11 +169,11 @@ AtaBusComponentNameGetDriverName ( EFI_STATUS EFIAPI AtaBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { EFI_STATUS Status; @@ -205,13 +203,14 @@ AtaBusComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the child context // Status = gBS->OpenProtocol ( ChildHandle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, gAtaBusDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -219,9 +218,11 @@ AtaBusComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } - AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (BlockIo); - ControllerNameTable =AtaDevice->ControllerNameTable; + + AtaDevice = ATA_DEVICE_FROM_BLOCK_IO (BlockIo); + ControllerNameTable = AtaDevice->ControllerNameTable; } + return LookupUnicodeString2 ( Language, This->SupportedLanguages, diff --git a/MdeModulePkg/Bus/I2c/I2cDxe/I2cBus.c b/MdeModulePkg/Bus/I2c/I2cDxe/I2cBus.c index fa58632703..eafd3bc851 100644 --- a/MdeModulePkg/Bus/I2c/I2cDxe/I2cBus.c +++ b/MdeModulePkg/Bus/I2c/I2cDxe/I2cBus.c @@ -12,7 +12,7 @@ // // EFI_DRIVER_BINDING_PROTOCOL instance // -EFI_DRIVER_BINDING_PROTOCOL gI2cBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gI2cBusDriverBinding = { I2cBusDriverSupported, I2cBusDriverStart, I2cBusDriverStop, @@ -24,7 +24,7 @@ EFI_DRIVER_BINDING_PROTOCOL gI2cBusDriverBinding = { // // Template for I2C Bus Child Device. // -I2C_DEVICE_CONTEXT gI2cDeviceContextTemplate = { +I2C_DEVICE_CONTEXT gI2cDeviceContextTemplate = { I2C_DEVICE_SIGNATURE, NULL, { // I2cIo Protocol @@ -42,13 +42,13 @@ I2C_DEVICE_CONTEXT gI2cDeviceContextTemplate = { // // Template for controller device path node. // -CONTROLLER_DEVICE_PATH gControllerDevicePathTemplate = { +CONTROLLER_DEVICE_PATH gControllerDevicePathTemplate = { { HARDWARE_DEVICE_PATH, HW_CONTROLLER_DP, { - (UINT8) (sizeof (CONTROLLER_DEVICE_PATH)), - (UINT8) ((sizeof (CONTROLLER_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (CONTROLLER_DEVICE_PATH)), + (UINT8)((sizeof (CONTROLLER_DEVICE_PATH)) >> 8) } }, 0 @@ -57,39 +57,40 @@ CONTROLLER_DEVICE_PATH gControllerDevicePathTemplate = { // // Template for vendor device path node. // -VENDOR_DEVICE_PATH gVendorDevicePathTemplate = { +VENDOR_DEVICE_PATH gVendorDevicePathTemplate = { { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, - { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }} + { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } + } }; // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mI2cBusDriverNameTable[] = { - { "eng;en", (CHAR16 *) L"I2C Bus Driver" }, - { NULL , NULL } +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mI2cBusDriverNameTable[] = { + { "eng;en", (CHAR16 *)L"I2C Bus Driver" }, + { NULL, NULL } }; // // EFI Component Name Protocol // GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gI2cBusComponentName = { - (EFI_COMPONENT_NAME_GET_DRIVER_NAME) I2cBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME_GET_CONTROLLER_NAME) I2cBusComponentNameGetControllerName, + (EFI_COMPONENT_NAME_GET_DRIVER_NAME)I2cBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME_GET_CONTROLLER_NAME)I2cBusComponentNameGetControllerName, "eng" }; // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gI2cBusComponentName2 = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gI2cBusComponentName2 = { I2cBusComponentNameGetDriverName, I2cBusComponentNameGetControllerName, "en" @@ -138,8 +139,8 @@ EFI_STATUS EFIAPI I2cBusComponentNameGetDriverName ( IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -222,11 +223,11 @@ I2cBusComponentNameGetDriverName ( EFI_STATUS EFIAPI I2cBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; @@ -254,16 +255,16 @@ CheckRemainingDevicePath ( IN UINT32 RemainingControllerNumber ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *SystemDevicePath; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; - UINTN EntryCount; - UINTN Index; - BOOLEAN SystemHasControllerNode; - UINT32 SystemControllerNumber; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *SystemDevicePath; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; + UINTN EntryCount; + UINTN Index; + BOOLEAN SystemHasControllerNode; + UINT32 SystemControllerNumber; SystemHasControllerNode = FALSE; - SystemControllerNumber = 0; + SystemControllerNumber = 0; Status = gBS->OpenProtocolInformation ( Controller, @@ -280,7 +281,7 @@ CheckRemainingDevicePath ( Status = gBS->OpenProtocol ( OpenInfoBuffer[Index].ControllerHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &SystemDevicePath, + (VOID **)&SystemDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -291,7 +292,8 @@ CheckRemainingDevicePath ( // while (!IsDevicePathEnd (SystemDevicePath)) { if ((DevicePathType (SystemDevicePath) == HARDWARE_DEVICE_PATH) && - (DevicePathSubType (SystemDevicePath) == HW_VENDOR_DP)) { + (DevicePathSubType (SystemDevicePath) == HW_VENDOR_DP)) + { // // Check if vendor device path is same between system device path and remaining device path // @@ -301,31 +303,37 @@ CheckRemainingDevicePath ( // SystemDevicePath = NextDevicePathNode (SystemDevicePath); if ((DevicePathType (SystemDevicePath) == HARDWARE_DEVICE_PATH) && - (DevicePathSubType (SystemDevicePath) == HW_CONTROLLER_DP)) { + (DevicePathSubType (SystemDevicePath) == HW_CONTROLLER_DP)) + { SystemHasControllerNode = TRUE; - SystemControllerNumber = ((CONTROLLER_DEVICE_PATH *) SystemDevicePath)->ControllerNumber; + SystemControllerNumber = ((CONTROLLER_DEVICE_PATH *)SystemDevicePath)->ControllerNumber; } else { SystemHasControllerNode = FALSE; - SystemControllerNumber = 0; + SystemControllerNumber = 0; } + if (((SystemHasControllerNode) && (!RemainingHasControllerNode) && (SystemControllerNumber == 0)) || ((!SystemHasControllerNode) && (RemainingHasControllerNode) && (RemainingControllerNumber == 0)) || ((SystemHasControllerNode) && (RemainingHasControllerNode) && (SystemControllerNumber == RemainingControllerNumber)) || - ((!SystemHasControllerNode) && (!RemainingHasControllerNode))) { - DEBUG ((DEBUG_ERROR, "This I2C device has been already started.\n")); - Status = EFI_UNSUPPORTED; - break; + ((!SystemHasControllerNode) && (!RemainingHasControllerNode))) + { + DEBUG ((DEBUG_ERROR, "This I2C device has been already started.\n")); + Status = EFI_UNSUPPORTED; + break; } } } + SystemDevicePath = NextDevicePathNode (SystemDevicePath); } + if (EFI_ERROR (Status)) { break; } } } } + FreePool (OpenInfoBuffer); return Status; } @@ -380,16 +388,16 @@ I2cBusDriverSupported ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; - EFI_I2C_HOST_PROTOCOL *I2cHost; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_DEVICE_PATH_PROTOCOL *DevPathNode; - BOOLEAN RemainingHasControllerNode; - UINT32 RemainingControllerNumber; + EFI_STATUS Status; + EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; + EFI_I2C_HOST_PROTOCOL *I2cHost; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevPathNode; + BOOLEAN RemainingHasControllerNode; + UINT32 RemainingControllerNumber; RemainingHasControllerNode = FALSE; - RemainingControllerNumber = 0; + RemainingControllerNumber = 0; // // Determine if the I2c Enumerate Protocol is available @@ -397,7 +405,7 @@ I2cBusDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cEnumerateProtocolGuid, - (VOID **) &I2cEnumerate, + (VOID **)&I2cEnumerate, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -408,17 +416,17 @@ I2cBusDriverSupported ( if (!EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiI2cEnumerateProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cEnumerateProtocolGuid, + This->DriverBindingHandle, + Controller + ); } Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -430,11 +438,11 @@ I2cBusDriverSupported ( if (!EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if ((RemainingDevicePath != NULL) && !IsDevicePathEnd (RemainingDevicePath)) { @@ -442,20 +450,23 @@ I2cBusDriverSupported ( // Check if the first node of RemainingDevicePath is a hardware vendor device path // if ((DevicePathType (RemainingDevicePath) != HARDWARE_DEVICE_PATH) || - (DevicePathSubType (RemainingDevicePath) != HW_VENDOR_DP)) { + (DevicePathSubType (RemainingDevicePath) != HW_VENDOR_DP)) + { return EFI_UNSUPPORTED; } + // // Check if the second node of RemainingDevicePath is a controller node // DevPathNode = NextDevicePathNode (RemainingDevicePath); if (!IsDevicePathEnd (DevPathNode)) { if ((DevicePathType (DevPathNode) != HARDWARE_DEVICE_PATH) || - (DevicePathSubType (DevPathNode) != HW_CONTROLLER_DP)) { + (DevicePathSubType (DevPathNode) != HW_CONTROLLER_DP)) + { return EFI_UNSUPPORTED; } else { RemainingHasControllerNode = TRUE; - RemainingControllerNumber = ((CONTROLLER_DEVICE_PATH *) DevPathNode)->ControllerNumber; + RemainingControllerNumber = ((CONTROLLER_DEVICE_PATH *)DevPathNode)->ControllerNumber; } } } @@ -466,7 +477,7 @@ I2cBusDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cHostProtocolGuid, - (VOID **) &I2cHost, + (VOID **)&I2cHost, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -474,17 +485,17 @@ I2cBusDriverSupported ( if (!EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiI2cHostProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cHostProtocolGuid, + This->DriverBindingHandle, + Controller + ); } - if (Status == EFI_ALREADY_STARTED) { if ((RemainingDevicePath == NULL) || - ((RemainingDevicePath != NULL) && IsDevicePathEnd (RemainingDevicePath))) { + ((RemainingDevicePath != NULL) && IsDevicePathEnd (RemainingDevicePath))) + { // // If RemainingDevicePath is NULL or is the End of Device Path Node, return EFI_SUCCESS. // @@ -549,16 +560,16 @@ I2cBusDriverStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; - EFI_I2C_HOST_PROTOCOL *I2cHost; - I2C_BUS_CONTEXT *I2cBusContext; - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; + EFI_I2C_HOST_PROTOCOL *I2cHost; + I2C_BUS_CONTEXT *I2cBusContext; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - I2cBusContext = NULL; - ParentDevicePath = NULL; - I2cEnumerate = NULL; - I2cHost = NULL; + I2cBusContext = NULL; + ParentDevicePath = NULL; + I2cEnumerate = NULL; + I2cHost = NULL; // // Determine if the I2C controller is available @@ -566,7 +577,7 @@ I2cBusDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cHostProtocolGuid, - (VOID**)&I2cHost, + (VOID **)&I2cHost, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -580,7 +591,7 @@ I2cBusDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &I2cBusContext, + (VOID **)&I2cBusContext, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -597,7 +608,7 @@ I2cBusDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cEnumerateProtocolGuid, - (VOID**)&I2cEnumerate, + (VOID **)&I2cEnumerate, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -608,13 +619,13 @@ I2cBusDriverStart ( } Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&ParentDevicePath, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { DEBUG ((DEBUG_ERROR, "I2cBus: open device path error, Status = %r\n", Status)); goto Error; @@ -661,7 +672,7 @@ I2cBusDriverStart ( // // Parent controller used to create children // - I2cBusContext->Controller = Controller; + I2cBusContext->Controller = Controller; // // Parent controller device path used to create children device path // @@ -693,29 +704,29 @@ Error: DEBUG ((DEBUG_ERROR, "I2cBus: Start() function failed, Status = %r\n", Status)); if (ParentDevicePath != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if (I2cHost != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiI2cHostProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cHostProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if (I2cEnumerate != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiI2cEnumerateProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cEnumerateProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if (I2cBusContext != NULL) { @@ -735,7 +746,6 @@ Error: return Status; } - /** Stops a device controller or a bus controller. @@ -771,60 +781,60 @@ I2cBusDriverStop ( IN EFI_HANDLE *ChildHandleBuffer ) { - I2C_BUS_CONTEXT *I2cBusContext; - EFI_STATUS Status; - BOOLEAN AllChildrenStopped; - UINTN Index; + I2C_BUS_CONTEXT *I2cBusContext; + EFI_STATUS Status; + BOOLEAN AllChildrenStopped; + UINTN Index; if (NumberOfChildren == 0) { gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiI2cHostProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cHostProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiI2cEnumerateProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cEnumerateProtocolGuid, + This->DriverBindingHandle, + Controller + ); Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &I2cBusContext, + (VOID **)&I2cBusContext, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( - Controller, - &gEfiCallerIdGuid, - I2cBusContext, - NULL - ); + Controller, + &gEfiCallerIdGuid, + I2cBusContext, + NULL + ); // // No more child now, free bus context data. // FreePool (I2cBusContext); } + return Status; } AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - Status = UnRegisterI2cDevice (This, Controller, ChildHandleBuffer[Index]); if (EFI_ERROR (Status)) { AllChildrenStopped = FALSE; @@ -834,6 +844,7 @@ I2cBusDriverStop ( if (!AllChildrenStopped) { return EFI_DEVICE_ERROR; } + return EFI_SUCCESS; } @@ -853,22 +864,22 @@ I2cBusDriverStop ( **/ EFI_STATUS RegisterI2cDevice ( - IN I2C_BUS_CONTEXT *I2cBusContext, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN I2C_BUS_CONTEXT *I2cBusContext, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - I2C_DEVICE_CONTEXT *I2cDeviceContext; - EFI_STATUS Status; - CONST EFI_I2C_DEVICE *Device; - CONST EFI_I2C_DEVICE *TempDevice; - UINT32 RemainingPathDeviceIndex; - EFI_DEVICE_PATH_PROTOCOL *DevPathNode; - BOOLEAN BuildControllerNode; - UINTN Count; - - Status = EFI_SUCCESS; - BuildControllerNode = TRUE; + I2C_DEVICE_CONTEXT *I2cDeviceContext; + EFI_STATUS Status; + CONST EFI_I2C_DEVICE *Device; + CONST EFI_I2C_DEVICE *TempDevice; + UINT32 RemainingPathDeviceIndex; + EFI_DEVICE_PATH_PROTOCOL *DevPathNode; + BOOLEAN BuildControllerNode; + UINTN Count; + + Status = EFI_SUCCESS; + BuildControllerNode = TRUE; // // Default DeviceIndex @@ -884,12 +895,13 @@ RegisterI2cDevice ( // DevPathNode = NextDevicePathNode (RemainingDevicePath); if ((DevicePathType (DevPathNode) == HARDWARE_DEVICE_PATH) && - (DevicePathSubType(DevPathNode) == HW_CONTROLLER_DP)) { + (DevicePathSubType (DevPathNode) == HW_CONTROLLER_DP)) + { // // RemainingDevicePath != NULL and RemainingDevicePath contains Controller Node, // add Controller Node to Device Path on child handle. // - RemainingPathDeviceIndex = ((CONTROLLER_DEVICE_PATH *) DevPathNode)->ControllerNumber; + RemainingPathDeviceIndex = ((CONTROLLER_DEVICE_PATH *)DevPathNode)->ControllerNumber; } else { // // RemainingDevicePath != NULL and RemainingDevicePath does not contain Controller Node, @@ -908,12 +920,13 @@ RegisterI2cDevice ( // Get the next I2C device // Status = I2cBusContext->I2cEnumerate->Enumerate (I2cBusContext->I2cEnumerate, &Device); - if (EFI_ERROR (Status) || Device == NULL) { + if (EFI_ERROR (Status) || (Device == NULL)) { if (RemainingDevicePath != NULL) { Status = EFI_NOT_FOUND; } else { Status = EFI_SUCCESS; } + break; } @@ -937,14 +950,16 @@ RegisterI2cDevice ( // Get the next I2C device // Status = I2cBusContext->I2cEnumerate->Enumerate (I2cBusContext->I2cEnumerate, &TempDevice); - if (EFI_ERROR (Status) || TempDevice == NULL) { + if (EFI_ERROR (Status) || (TempDevice == NULL)) { Status = EFI_SUCCESS; break; } + if (CompareGuid (Device->DeviceGuid, TempDevice->DeviceGuid)) { Count++; } } + if (Count == 1) { // // RemainingDevicePath == NULL and only DeviceIndex 0 is present on the I2C bus, @@ -958,7 +973,8 @@ RegisterI2cDevice ( // Find I2C device reported in Remaining Device Path // if ((!CompareGuid (&((VENDOR_DEVICE_PATH *)RemainingDevicePath)->Guid, Device->DeviceGuid)) || - (RemainingPathDeviceIndex != Device->DeviceIndex)) { + (RemainingPathDeviceIndex != Device->DeviceIndex)) + { continue; } } @@ -976,11 +992,11 @@ RegisterI2cDevice ( // // Initialize the specific device context // - I2cDeviceContext->I2cBusContext = I2cBusContext; - I2cDeviceContext->I2cDevice = Device; - I2cDeviceContext->I2cIo.DeviceGuid = Device->DeviceGuid; - I2cDeviceContext->I2cIo.DeviceIndex = Device->DeviceIndex; - I2cDeviceContext->I2cIo.HardwareRevision = Device->HardwareRevision; + I2cDeviceContext->I2cBusContext = I2cBusContext; + I2cDeviceContext->I2cDevice = Device; + I2cDeviceContext->I2cIo.DeviceGuid = Device->DeviceGuid; + I2cDeviceContext->I2cIo.DeviceIndex = Device->DeviceIndex; + I2cDeviceContext->I2cIo.HardwareRevision = Device->HardwareRevision; I2cDeviceContext->I2cIo.I2cControllerCapabilities = I2cBusContext->I2cHost->I2cControllerCapabilities; // @@ -996,12 +1012,13 @@ RegisterI2cDevice ( // Install the protocol // Status = gBS->InstallMultipleProtocolInterfaces ( - &I2cDeviceContext->Handle, - &gEfiI2cIoProtocolGuid, - &I2cDeviceContext->I2cIo, - &gEfiDevicePathProtocolGuid, - I2cDeviceContext->DevicePath, - NULL ); + &I2cDeviceContext->Handle, + &gEfiI2cIoProtocolGuid, + &I2cDeviceContext->I2cIo, + &gEfiDevicePathProtocolGuid, + I2cDeviceContext->DevicePath, + NULL + ); if (EFI_ERROR (Status)) { // // Free resources for this I2C device @@ -1016,7 +1033,7 @@ RegisterI2cDevice ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cHostProtocolGuid, - (VOID **) &I2cBusContext->I2cHost, + (VOID **)&I2cBusContext->I2cHost, I2cBusContext->DriverBindingHandle, I2cDeviceContext->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -1048,7 +1065,6 @@ RegisterI2cDevice ( return Status; } - /** Queue an I2C transaction for execution on the I2C device. @@ -1130,11 +1146,11 @@ I2cBusQueueRequest ( OUT EFI_STATUS *I2cStatus OPTIONAL ) { - CONST EFI_I2C_DEVICE *I2cDevice; - I2C_BUS_CONTEXT *I2cBusContext; - CONST EFI_I2C_HOST_PROTOCOL *I2cHost; - I2C_DEVICE_CONTEXT *I2cDeviceContext; - EFI_STATUS Status; + CONST EFI_I2C_DEVICE *I2cDevice; + I2C_BUS_CONTEXT *I2cBusContext; + CONST EFI_I2C_HOST_PROTOCOL *I2cHost; + I2C_DEVICE_CONTEXT *I2cDeviceContext; + EFI_STATUS Status; if (RequestPacket == NULL) { return EFI_INVALID_PARAMETER; @@ -1161,7 +1177,7 @@ I2cBusQueueRequest ( Status = I2cHost->QueueRequest ( I2cHost, I2cDevice->I2cBusConfiguration, - I2cDevice->SlaveAddressArray [SlaveAddressIndex], + I2cDevice->SlaveAddressArray[SlaveAddressIndex], Event, RequestPacket, I2cStatus @@ -1180,7 +1196,7 @@ I2cBusQueueRequest ( **/ VOID ReleaseI2cDeviceContext ( - IN I2C_DEVICE_CONTEXT *I2cDeviceContext + IN I2C_DEVICE_CONTEXT *I2cDeviceContext ) { if (I2cDeviceContext == NULL) { @@ -1210,22 +1226,22 @@ ReleaseI2cDeviceContext ( **/ EFI_STATUS UnRegisterI2cDevice ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - I2C_DEVICE_CONTEXT *I2cDeviceContext; - EFI_I2C_IO_PROTOCOL *I2cIo; - EFI_I2C_HOST_PROTOCOL *I2cHost; + EFI_STATUS Status; + I2C_DEVICE_CONTEXT *I2cDeviceContext; + EFI_I2C_IO_PROTOCOL *I2cIo; + EFI_I2C_HOST_PROTOCOL *I2cHost; I2cIo = NULL; Status = gBS->OpenProtocol ( Handle, &gEfiI2cIoProtocolGuid, - (VOID **) &I2cIo, + (VOID **)&I2cIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1267,13 +1283,13 @@ UnRegisterI2cDevice ( // Keep parent and child relationship // gBS->OpenProtocol ( - Controller, - &gEfiI2cHostProtocolGuid, - (VOID **) &I2cHost, - This->DriverBindingHandle, - Handle, - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiI2cHostProtocolGuid, + (VOID **)&I2cHost, + This->DriverBindingHandle, + Handle, + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); return Status; } @@ -1299,8 +1315,8 @@ UnRegisterI2cDevice ( **/ EFI_STATUS I2cBusDevicePathAppend ( - IN I2C_DEVICE_CONTEXT *I2cDeviceContext, - IN BOOLEAN BuildControllerNode + IN I2C_DEVICE_CONTEXT *I2cDeviceContext, + IN BOOLEAN BuildControllerNode ) { EFI_DEVICE_PATH_PROTOCOL *PreviousDevicePath; @@ -1311,10 +1327,10 @@ I2cBusDevicePathAppend ( // Build vendor device path // CopyMem (&gVendorDevicePathTemplate.Guid, I2cDeviceContext->I2cDevice->DeviceGuid, sizeof (EFI_GUID)); - I2cDeviceContext->DevicePath = AppendDevicePathNode ( - I2cDeviceContext->I2cBusContext->ParentDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &gVendorDevicePathTemplate - ); + I2cDeviceContext->DevicePath = AppendDevicePathNode ( + I2cDeviceContext->I2cBusContext->ParentDevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&gVendorDevicePathTemplate + ); ASSERT (I2cDeviceContext->DevicePath != NULL); if (I2cDeviceContext->DevicePath == NULL) { return EFI_OUT_OF_RESOURCES; @@ -1324,12 +1340,12 @@ I2cBusDevicePathAppend ( // // Build the final I2C device path with controller node // - PreviousDevicePath = I2cDeviceContext->DevicePath; + PreviousDevicePath = I2cDeviceContext->DevicePath; gControllerDevicePathTemplate.ControllerNumber = I2cDeviceContext->I2cDevice->DeviceIndex; - I2cDeviceContext->DevicePath = AppendDevicePathNode ( - I2cDeviceContext->DevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &gControllerDevicePathTemplate - ); + I2cDeviceContext->DevicePath = AppendDevicePathNode ( + I2cDeviceContext->DevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&gControllerDevicePathTemplate + ); gBS->FreePool (PreviousDevicePath); ASSERT (I2cDeviceContext->DevicePath != NULL); if (I2cDeviceContext->DevicePath == NULL) { @@ -1353,12 +1369,12 @@ I2cBusDevicePathAppend ( **/ EFI_STATUS EFIAPI -InitializeI2cBus( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeI2cBus ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -1373,7 +1389,6 @@ InitializeI2cBus( ); ASSERT_EFI_ERROR (Status); - return Status; } @@ -1392,15 +1407,15 @@ InitializeI2cBus( EFI_STATUS EFIAPI I2cBusUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ) { - EFI_STATUS Status; - EFI_HANDLE *DeviceHandleBuffer; - UINTN DeviceHandleCount; - UINTN Index; - EFI_COMPONENT_NAME_PROTOCOL *ComponentName; - EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; + EFI_STATUS Status; + EFI_HANDLE *DeviceHandleBuffer; + UINTN DeviceHandleCount; + UINTN Index; + EFI_COMPONENT_NAME_PROTOCOL *ComponentName; + EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; // // Get the list of all I2C Controller handles in the handle database. @@ -1455,7 +1470,7 @@ I2cBusUnload ( Status = gBS->HandleProtocol ( gI2cBusDriverBinding.DriverBindingHandle, &gEfiComponentNameProtocolGuid, - (VOID **) &ComponentName + (VOID **)&ComponentName ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( @@ -1468,7 +1483,7 @@ I2cBusUnload ( Status = gBS->HandleProtocol ( gI2cBusDriverBinding.DriverBindingHandle, &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName2 + (VOID **)&ComponentName2 ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( diff --git a/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.c b/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.c index bb5d83927c..0c733f0c3d 100644 --- a/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.c +++ b/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.c @@ -20,21 +20,21 @@ **/ EFI_STATUS EFIAPI -InitializeI2c( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeI2c ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). // - Status = InitializeI2cHost ( ImageHandle, SystemTable ); - if ( !EFI_ERROR ( Status )) - { - Status = InitializeI2cBus ( ImageHandle, SystemTable ); + Status = InitializeI2cHost (ImageHandle, SystemTable); + if ( !EFI_ERROR (Status)) { + Status = InitializeI2cBus (ImageHandle, SystemTable); } + return Status; } @@ -53,17 +53,18 @@ InitializeI2c( EFI_STATUS EFIAPI I2cUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Disconnect the drivers // - Status = I2cBusUnload ( ImageHandle ); - if ( !EFI_ERROR ( Status )) { - Status = I2cHostUnload ( ImageHandle ); + Status = I2cBusUnload (ImageHandle); + if ( !EFI_ERROR (Status)) { + Status = I2cHostUnload (ImageHandle); } + return Status; } diff --git a/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.h b/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.h index 49f1e9b17b..c684fa4437 100644 --- a/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.h +++ b/MdeModulePkg/Bus/I2c/I2cDxe/I2cDxe.h @@ -30,24 +30,24 @@ #include #include -#define I2C_DEVICE_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'D') -#define I2C_HOST_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'H') -#define I2C_REQUEST_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'R') +#define I2C_DEVICE_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'D') +#define I2C_HOST_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'H') +#define I2C_REQUEST_SIGNATURE SIGNATURE_32 ('I', '2', 'C', 'R') // // Synchronize access to the list of requests // -#define TPL_I2C_SYNC TPL_NOTIFY +#define TPL_I2C_SYNC TPL_NOTIFY // // I2C bus context // typedef struct { - EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; - EFI_I2C_HOST_PROTOCOL *I2cHost; - EFI_HANDLE Controller; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_HANDLE DriverBindingHandle; + EFI_I2C_ENUMERATE_PROTOCOL *I2cEnumerate; + EFI_I2C_HOST_PROTOCOL *I2cHost; + EFI_HANDLE Controller; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_HANDLE DriverBindingHandle; } I2C_BUS_CONTEXT; // @@ -57,36 +57,36 @@ typedef struct { // // Structure identification // - UINT32 Signature; + UINT32 Signature; // // I2c device handle // - EFI_HANDLE Handle; + EFI_HANDLE Handle; // // Upper level API to support the I2C device I/O // - EFI_I2C_IO_PROTOCOL I2cIo; + EFI_I2C_IO_PROTOCOL I2cIo; // // Device path for this device // - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; // // Platform specific data for this device // - CONST EFI_I2C_DEVICE *I2cDevice; + CONST EFI_I2C_DEVICE *I2cDevice; // // Context for the common I/O support including the // lower level API to the host controller. // - I2C_BUS_CONTEXT *I2cBusContext; + I2C_BUS_CONTEXT *I2cBusContext; } I2C_DEVICE_CONTEXT; -#define I2C_DEVICE_CONTEXT_FROM_PROTOCOL(a) CR (a, I2C_DEVICE_CONTEXT, I2cIo, I2C_DEVICE_SIGNATURE) +#define I2C_DEVICE_CONTEXT_FROM_PROTOCOL(a) CR (a, I2C_DEVICE_CONTEXT, I2cIo, I2C_DEVICE_SIGNATURE) // // I2C Request @@ -95,41 +95,41 @@ typedef struct { // // Signature // - UINT32 Signature; + UINT32 Signature; // // Next request in the pending request list // - LIST_ENTRY Link; + LIST_ENTRY Link; // // I2C bus configuration for the operation // - UINTN I2cBusConfiguration; + UINTN I2cBusConfiguration; // // I2C slave address for the operation // - UINTN SlaveAddress; + UINTN SlaveAddress; // // Event to set for asynchronous operations, NULL for // synchronous operations // - EFI_EVENT Event; + EFI_EVENT Event; // // I2C operation description // - EFI_I2C_REQUEST_PACKET *RequestPacket; + EFI_I2C_REQUEST_PACKET *RequestPacket; // // Optional buffer to receive the I2C operation completion status // - EFI_STATUS *Status; + EFI_STATUS *Status; } I2C_REQUEST; -#define I2C_REQUEST_FROM_ENTRY(a) CR (a, I2C_REQUEST, Link, I2C_REQUEST_SIGNATURE); +#define I2C_REQUEST_FROM_ENTRY(a) CR (a, I2C_REQUEST, Link, I2C_REQUEST_SIGNATURE); // // I2C host context @@ -138,66 +138,66 @@ typedef struct { // // Structure identification // - UINTN Signature; + UINTN Signature; // // Current I2C bus configuration // - UINTN I2cBusConfiguration; + UINTN I2cBusConfiguration; // // I2C bus configuration management event // - EFI_EVENT I2cBusConfigurationEvent; + EFI_EVENT I2cBusConfigurationEvent; // // I2C operation completion event // - EFI_EVENT I2cEvent; + EFI_EVENT I2cEvent; // // I2C operation and I2C bus configuration management status // - EFI_STATUS Status; + EFI_STATUS Status; // // I2C bus configuration management operation pending // - BOOLEAN I2cBusConfigurationManagementPending; + BOOLEAN I2cBusConfigurationManagementPending; // // I2C request list maintained by I2C Host // - LIST_ENTRY RequestList; + LIST_ENTRY RequestList; // // Upper level API // - EFI_I2C_HOST_PROTOCOL I2cHost; + EFI_I2C_HOST_PROTOCOL I2cHost; // // I2C bus configuration management protocol // - EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; + EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; // // Lower level API for I2C master (controller) // - EFI_I2C_MASTER_PROTOCOL *I2cMaster; + EFI_I2C_MASTER_PROTOCOL *I2cMaster; } I2C_HOST_CONTEXT; -#define I2C_HOST_CONTEXT_FROM_PROTOCOL(a) CR (a, I2C_HOST_CONTEXT, I2cHost, I2C_HOST_SIGNATURE) +#define I2C_HOST_CONTEXT_FROM_PROTOCOL(a) CR (a, I2C_HOST_CONTEXT, I2cHost, I2C_HOST_SIGNATURE) // // Global Variables // -extern EFI_COMPONENT_NAME_PROTOCOL gI2cBusComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gI2cBusComponentName2; -extern EFI_DRIVER_BINDING_PROTOCOL gI2cBusDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gI2cBusComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gI2cBusComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gI2cBusDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gI2cHostComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gI2cHostComponentName2; -extern EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gI2cHostComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gI2cHostComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding; /** Start the I2C driver @@ -217,7 +217,7 @@ extern EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding; EFI_STATUS RegisterI2cDevice ( IN I2C_BUS_CONTEXT *I2cBus, - IN EFI_HANDLE Controller, + IN EFI_HANDLE Controller, IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); @@ -237,9 +237,9 @@ RegisterI2cDevice ( **/ EFI_STATUS UnRegisterI2cDevice ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ); /** @@ -256,8 +256,8 @@ UnRegisterI2cDevice ( **/ EFI_STATUS I2cBusDevicePathAppend ( - IN I2C_DEVICE_CONTEXT *I2cDeviceContext, - IN BOOLEAN BuildControllerNode + IN I2C_DEVICE_CONTEXT *I2cDeviceContext, + IN BOOLEAN BuildControllerNode ); /** @@ -514,9 +514,9 @@ I2cBusDriverStop ( EFI_STATUS EFIAPI I2cBusComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ); /** @@ -590,11 +590,11 @@ I2cBusComponentNameGetDriverName ( EFI_STATUS EFIAPI I2cBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -610,9 +610,9 @@ I2cBusComponentNameGetControllerName ( **/ EFI_STATUS EFIAPI -InitializeI2cBus( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeI2cBus ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); /** @@ -630,7 +630,7 @@ InitializeI2cBus( EFI_STATUS EFIAPI I2cBusUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ); /** @@ -643,7 +643,7 @@ I2cBusUnload ( **/ VOID ReleaseI2cDeviceContext ( - IN I2C_DEVICE_CONTEXT *I2cDeviceContext + IN I2C_DEVICE_CONTEXT *I2cDeviceContext ); /** @@ -657,8 +657,8 @@ ReleaseI2cDeviceContext ( **/ EFI_STATUS I2cHostRequestComplete ( - I2C_HOST_CONTEXT *I2cHost, - EFI_STATUS Status + I2C_HOST_CONTEXT *I2cHost, + EFI_STATUS Status ); /** @@ -688,7 +688,7 @@ I2cHostRequestComplete ( **/ EFI_STATUS I2cHostRequestEnable ( - I2C_HOST_CONTEXT *I2cHost + I2C_HOST_CONTEXT *I2cHost ); /** @@ -779,9 +779,9 @@ I2cHostDriverSupported ( EFI_STATUS EFIAPI I2cHostDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -813,10 +813,10 @@ I2cHostDriverStart ( EFI_STATUS EFIAPI I2cHostDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -861,9 +861,9 @@ I2cHostDriverStop ( EFI_STATUS EFIAPI I2cHostComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ); /** @@ -937,11 +937,11 @@ I2cHostComponentNameGetDriverName ( EFI_STATUS EFIAPI I2cHostComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -956,8 +956,8 @@ I2cHostComponentNameGetControllerName ( VOID EFIAPI I2cHostRequestCompleteEvent ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -972,8 +972,8 @@ I2cHostRequestCompleteEvent ( VOID EFIAPI I2cHostI2cBusConfigurationAvailable ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -1065,9 +1065,9 @@ I2cHostQueueRequest ( **/ EFI_STATUS EFIAPI -InitializeI2cHost( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeI2cHost ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); /** @@ -1085,7 +1085,7 @@ InitializeI2cHost( EFI_STATUS EFIAPI I2cHostUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ); -#endif // __I2C_DXE_H__ +#endif // __I2C_DXE_H__ diff --git a/MdeModulePkg/Bus/I2c/I2cDxe/I2cHost.c b/MdeModulePkg/Bus/I2c/I2cDxe/I2cHost.c index 8dec43bcb1..a4b3302b6b 100644 --- a/MdeModulePkg/Bus/I2c/I2cDxe/I2cHost.c +++ b/MdeModulePkg/Bus/I2c/I2cDxe/I2cHost.c @@ -10,7 +10,7 @@ #include "I2cDxe.h" -EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding = { I2cHostDriverSupported, I2cHostDriverStart, I2cHostDriverStop, @@ -22,24 +22,24 @@ EFI_DRIVER_BINDING_PROTOCOL gI2cHostDriverBinding = { // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mI2cHostDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mI2cHostDriverNameTable[] = { { "eng;en", L"I2c Host Driver" }, - { NULL , NULL } + { NULL, NULL } }; // // EFI Component Name Protocol // GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gI2cHostComponentName = { - (EFI_COMPONENT_NAME_GET_DRIVER_NAME) I2cHostComponentNameGetDriverName, - (EFI_COMPONENT_NAME_GET_CONTROLLER_NAME) I2cHostComponentNameGetControllerName, + (EFI_COMPONENT_NAME_GET_DRIVER_NAME)I2cHostComponentNameGetDriverName, + (EFI_COMPONENT_NAME_GET_CONTROLLER_NAME)I2cHostComponentNameGetControllerName, "eng" }; // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gI2cHostComponentName2 = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gI2cHostComponentName2 = { I2cHostComponentNameGetDriverName, I2cHostComponentNameGetControllerName, "en" @@ -88,8 +88,8 @@ EFI_STATUS EFIAPI I2cHostComponentNameGetDriverName ( IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -172,11 +172,11 @@ I2cHostComponentNameGetDriverName ( EFI_STATUS EFIAPI I2cHostComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME2_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME2_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; @@ -232,9 +232,9 @@ I2cHostDriverSupported ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_I2C_MASTER_PROTOCOL *I2cMaster; - EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; - EFI_STATUS Status; + EFI_I2C_MASTER_PROTOCOL *I2cMaster; + EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; + EFI_STATUS Status; // // Locate I2C Bus Configuration Management Protocol @@ -255,11 +255,11 @@ I2cHostDriverSupported ( // Close the protocol because we don't use it here // gBS->CloseProtocol ( - Controller, - &gEfiI2cBusConfigurationManagementProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cBusConfigurationManagementProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Locate I2C Master Protocol @@ -317,15 +317,15 @@ I2cHostDriverSupported ( EFI_STATUS EFIAPI I2cHostDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_I2C_MASTER_PROTOCOL *I2cMaster; - EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; - I2C_HOST_CONTEXT *I2cHostContext; + EFI_STATUS Status; + EFI_I2C_MASTER_PROTOCOL *I2cMaster; + EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; + I2C_HOST_CONTEXT *I2cHostContext; I2cMaster = NULL; I2cHostContext = NULL; @@ -379,8 +379,8 @@ I2cHostDriverStart ( I2cHostContext->Signature = I2C_HOST_SIGNATURE; I2cHostContext->I2cMaster = I2cMaster; I2cHostContext->I2cBusConfigurationManagement = I2cBusConfigurationManagement; - I2cHostContext->I2cBusConfiguration = (UINTN) -1; - InitializeListHead(&I2cHostContext->RequestList); + I2cHostContext->I2cBusConfiguration = (UINTN)-1; + InitializeListHead (&I2cHostContext->RequestList); // // Reset the controller @@ -441,11 +441,11 @@ Exit: DEBUG ((DEBUG_ERROR, "I2cHost: Start() function failed, Status = %r\n", Status)); if (I2cBusConfigurationManagement != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiI2cBusConfigurationManagementProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiI2cBusConfigurationManagementProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if ((I2cHostContext != NULL) && (I2cHostContext->I2cEvent != NULL)) { @@ -501,16 +501,16 @@ Exit: EFI_STATUS EFIAPI I2cHostDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - I2C_HOST_CONTEXT *I2cHostContext; - EFI_I2C_HOST_PROTOCOL *I2cHost; - EFI_TPL TplPrevious; + EFI_STATUS Status; + I2C_HOST_CONTEXT *I2cHostContext; + EFI_I2C_HOST_PROTOCOL *I2cHost; + EFI_TPL TplPrevious; TplPrevious = EfiGetCurrentTpl (); if (TplPrevious > TPL_I2C_SYNC) { @@ -521,7 +521,7 @@ I2cHostDriverStop ( Status = gBS->OpenProtocol ( Controller, &gEfiI2cHostProtocolGuid, - (VOID **) &I2cHost, + (VOID **)&I2cHost, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -542,9 +542,9 @@ I2cHostDriverStop ( // If there is pending request or pending bus configuration, do not stop // Status = EFI_DEVICE_ERROR; - if (( !I2cHostContext->I2cBusConfigurationManagementPending ) - && IsListEmpty (&I2cHostContext->RequestList)) { - + if ( (!I2cHostContext->I2cBusConfigurationManagementPending) + && IsListEmpty (&I2cHostContext->RequestList)) + { // // Remove the I2C host protocol // @@ -602,16 +602,16 @@ I2cHostDriverStop ( VOID EFIAPI I2cHostI2cBusConfigurationAvailable ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - I2C_HOST_CONTEXT *I2cHostContext; - EFI_I2C_MASTER_PROTOCOL *I2cMaster; - I2C_REQUEST *I2cRequest; - LIST_ENTRY *EntryHeader; - LIST_ENTRY *Entry; - EFI_STATUS Status; + I2C_HOST_CONTEXT *I2cHostContext; + EFI_I2C_MASTER_PROTOCOL *I2cMaster; + I2C_REQUEST *I2cRequest; + LIST_ENTRY *EntryHeader; + LIST_ENTRY *Entry; + EFI_STATUS Status; // // Mark this I2C bus configuration management operation as complete @@ -637,7 +637,7 @@ I2cHostI2cBusConfigurationAvailable ( // Unknown I2C bus configuration // Force next operation to enable the I2C bus configuration // - I2cHostContext->I2cBusConfiguration = (UINTN) -1; + I2cHostContext->I2cBusConfiguration = (UINTN)-1; // // Do not continue current I2C request @@ -649,8 +649,8 @@ I2cHostI2cBusConfigurationAvailable ( // Get the first request in the link with FIFO order // EntryHeader = &I2cHostContext->RequestList; - Entry = GetFirstNode (EntryHeader); - I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); + Entry = GetFirstNode (EntryHeader); + I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); // // Update the I2C bus configuration of the current I2C request @@ -669,7 +669,7 @@ I2cHostI2cBusConfigurationAvailable ( ); if (EFI_ERROR (Status)) { - DEBUG((DEBUG_ERROR, "I2cHostI2cBusConfigurationAvailable: Error starting I2C operation, %r\n", Status)); + DEBUG ((DEBUG_ERROR, "I2cHostI2cBusConfigurationAvailable: Error starting I2C operation, %r\n", Status)); } } @@ -686,20 +686,20 @@ I2cHostI2cBusConfigurationAvailable ( **/ EFI_STATUS I2cHostRequestComplete ( - I2C_HOST_CONTEXT *I2cHostContext, - EFI_STATUS Status + I2C_HOST_CONTEXT *I2cHostContext, + EFI_STATUS Status ) { - I2C_REQUEST *I2cRequest; - LIST_ENTRY *EntryHeader; - LIST_ENTRY *Entry; + I2C_REQUEST *I2cRequest; + LIST_ENTRY *EntryHeader; + LIST_ENTRY *Entry; // // Remove the current I2C request from the list // EntryHeader = &I2cHostContext->RequestList; - Entry = GetFirstNode (EntryHeader); - I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); + Entry = GetFirstNode (EntryHeader); + I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); // // Save the status for QueueRequest @@ -725,7 +725,7 @@ I2cHostRequestComplete ( // // If there is more I2C request, start next one // - if(!IsListEmpty (EntryHeader)) { + if (!IsListEmpty (EntryHeader)) { I2cHostRequestEnable (I2cHostContext); } @@ -744,11 +744,11 @@ I2cHostRequestComplete ( VOID EFIAPI I2cHostRequestCompleteEvent ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - I2C_HOST_CONTEXT *I2cHostContext; + I2C_HOST_CONTEXT *I2cHostContext; // // Handle the completion event @@ -784,16 +784,16 @@ I2cHostRequestCompleteEvent ( **/ EFI_STATUS I2cHostRequestEnable ( - I2C_HOST_CONTEXT *I2cHostContext + I2C_HOST_CONTEXT *I2cHostContext ) { - UINTN I2cBusConfiguration; - CONST EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; - I2C_REQUEST *I2cRequest; - EFI_STATUS Status; - EFI_TPL TplPrevious; - LIST_ENTRY *EntryHeader; - LIST_ENTRY *Entry; + UINTN I2cBusConfiguration; + CONST EFI_I2C_BUS_CONFIGURATION_MANAGEMENT_PROTOCOL *I2cBusConfigurationManagement; + I2C_REQUEST *I2cRequest; + EFI_STATUS Status; + EFI_TPL TplPrevious; + LIST_ENTRY *EntryHeader; + LIST_ENTRY *Entry; // // Assume pending request @@ -807,7 +807,7 @@ I2cHostRequestEnable ( // EntryHeader = &I2cHostContext->RequestList; Entry = GetFirstNode (EntryHeader); - I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); + I2cRequest = I2C_REQUEST_FROM_ENTRY (Entry); I2cBusConfiguration = I2cRequest->I2cBusConfiguration; @@ -820,16 +820,16 @@ I2cHostRequestEnable ( // Update bus configuration for this device's requesting bus configuration // Status = I2cBusConfigurationManagement->EnableI2cBusConfiguration ( - I2cBusConfigurationManagement, - I2cBusConfiguration, - I2cHostContext->I2cBusConfigurationEvent, - &I2cHostContext->Status - ); + I2cBusConfigurationManagement, + I2cBusConfiguration, + I2cHostContext->I2cBusConfigurationEvent, + &I2cHostContext->Status + ); } else { // // I2C bus configuration is same, no need change configuration and start I2c transaction directly // - TplPrevious = gBS->RaiseTPL ( TPL_I2C_SYNC ); + TplPrevious = gBS->RaiseTPL (TPL_I2C_SYNC); // // Same I2C bus configuration @@ -840,8 +840,9 @@ I2cHostRequestEnable ( // // Release the thread synchronization // - gBS->RestoreTPL ( TplPrevious ); + gBS->RestoreTPL (TplPrevious); } + return Status; } @@ -965,12 +966,12 @@ I2cHostQueueRequest ( // For synchronous transaction, register an event used to wait for finishing synchronous transaction // Status = gBS->CreateEvent ( - 0, - TPL_I2C_SYNC, - NULL, - NULL, - &SyncEvent - ); + 0, + TPL_I2C_SYNC, + NULL, + NULL, + &SyncEvent + ); if (EFI_ERROR (Status)) { return Status; } @@ -1007,7 +1008,7 @@ I2cHostQueueRequest ( // // Copy request packet into private buffer, as RequestPacket may be freed during asynchronous transaction // - RequestPacketSize = sizeof (UINTN) + RequestPacket->OperationCount * sizeof (EFI_I2C_OPERATION); + RequestPacketSize = sizeof (UINTN) + RequestPacket->OperationCount * sizeof (EFI_I2C_OPERATION); I2cRequest->RequestPacket = AllocateZeroPool (RequestPacketSize); ASSERT (I2cRequest->RequestPacket != NULL); CopyMem (I2cRequest->RequestPacket, RequestPacket, RequestPacketSize); @@ -1015,7 +1016,7 @@ I2cHostQueueRequest ( // // Synchronize with the other threads // - gBS->RaiseTPL ( TPL_I2C_SYNC ); + gBS->RaiseTPL (TPL_I2C_SYNC); FirstRequest = IsListEmpty (&I2cHostContext->RequestList); @@ -1085,12 +1086,12 @@ I2cHostQueueRequest ( **/ EFI_STATUS EFIAPI -InitializeI2cHost( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeI2cHost ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -1122,15 +1123,15 @@ InitializeI2cHost( EFI_STATUS EFIAPI I2cHostUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ) { - EFI_STATUS Status; - EFI_HANDLE *DeviceHandleBuffer; - UINTN DeviceHandleCount; - UINTN Index; - EFI_COMPONENT_NAME_PROTOCOL *ComponentName; - EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; + EFI_STATUS Status; + EFI_HANDLE *DeviceHandleBuffer; + UINTN DeviceHandleCount; + UINTN Index; + EFI_COMPONENT_NAME_PROTOCOL *ComponentName; + EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; // // Get the list of all I2C Controller handles in the handle database. @@ -1185,7 +1186,7 @@ I2cHostUnload ( Status = gBS->HandleProtocol ( gI2cHostDriverBinding.DriverBindingHandle, &gEfiComponentNameProtocolGuid, - (VOID **) &ComponentName + (VOID **)&ComponentName ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( @@ -1198,7 +1199,7 @@ I2cHostUnload ( Status = gBS->HandleProtocol ( gI2cHostDriverBinding.DriverBindingHandle, &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName2 + (VOID **)&ComponentName2 ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( diff --git a/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.c b/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.c index 84f4c5d16c..85b04bd97e 100644 --- a/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.c @@ -12,9 +12,9 @@ // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mIsaBusDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mIsaBusDriverNameTable[] = { { "eng;en", L"PI ISA BUS Driver" }, - { NULL , NULL } + { NULL, NULL } }; // @@ -29,9 +29,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gIsaBusComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gIsaBusComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) IsaBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) IsaBusComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gIsaBusComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)IsaBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)IsaBusComponentNameGetControllerName, "en" }; @@ -91,7 +91,6 @@ IsaBusComponentNameGetDriverName ( ); } - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -163,11 +162,11 @@ IsaBusComponentNameGetDriverName ( EFI_STATUS EFIAPI IsaBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.h b/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.h index c8d4601e8b..e19dbbd4c1 100644 --- a/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.h +++ b/MdeModulePkg/Bus/Isa/IsaBusDxe/ComponentName.h @@ -13,8 +13,8 @@ #include #include -extern EFI_COMPONENT_NAME_PROTOCOL gIsaBusComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gIsaBusComponentName2; +extern EFI_COMPONENT_NAME_PROTOCOL gIsaBusComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gIsaBusComponentName2; /** Retrieves a Unicode string that is the user readable name of the driver. @@ -63,7 +63,6 @@ IsaBusComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -135,11 +134,11 @@ IsaBusComponentNameGetDriverName ( EFI_STATUS EFIAPI IsaBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); #endif diff --git a/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.c b/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.c index ccda7c3f70..38ea13a203 100644 --- a/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.c +++ b/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.c @@ -43,13 +43,13 @@ EFI_STATUS EFIAPI IsaBusDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - VOID *Instance; + EFI_STATUS Status; + VOID *Instance; Status = gBS->OpenProtocol ( Controller, @@ -61,11 +61,11 @@ IsaBusDriverBindingSupported ( ); if (!EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiIsaHcProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiIsaHcProtocolGuid, + This->DriverBindingHandle, + Controller + ); } if (EFI_ERROR (Status)) { @@ -82,17 +82,17 @@ IsaBusDriverBindingSupported ( ); if (!EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); } return Status; } -ISA_BUS_CHILD_PRIVATE_DATA mIsaBusChildPrivateTemplate = { +ISA_BUS_CHILD_PRIVATE_DATA mIsaBusChildPrivateTemplate = { ISA_BUS_CHILD_PRIVATE_DATA_SIGNATURE, FALSE }; @@ -123,10 +123,10 @@ IsaBusCreateChild ( IN OUT EFI_HANDLE *ChildHandle ) { - EFI_STATUS Status; - ISA_BUS_PRIVATE_DATA *Private; - EFI_ISA_HC_PROTOCOL *IsaHc; - ISA_BUS_CHILD_PRIVATE_DATA *Child; + EFI_STATUS Status; + ISA_BUS_PRIVATE_DATA *Private; + EFI_ISA_HC_PROTOCOL *IsaHc; + ISA_BUS_CHILD_PRIVATE_DATA *Child; Private = ISA_BUS_PRIVATE_DATA_FROM_THIS (This); @@ -137,8 +137,10 @@ IsaBusCreateChild ( Status = gBS->InstallMultipleProtocolInterfaces ( ChildHandle, - &gEfiIsaHcProtocolGuid, Private->IsaHc, - &gEfiCallerIdGuid, Child, + &gEfiIsaHcProtocolGuid, + Private->IsaHc, + &gEfiCallerIdGuid, + Child, NULL ); if (EFI_ERROR (Status)) { @@ -149,7 +151,7 @@ IsaBusCreateChild ( return gBS->OpenProtocol ( Private->IsaHcHandle, &gEfiIsaHcProtocolGuid, - (VOID **) &IsaHc, + (VOID **)&IsaHc, gIsaBusDriverBinding.DriverBindingHandle, *ChildHandle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -177,21 +179,21 @@ IsaBusCreateChild ( EFI_STATUS EFIAPI IsaBusDestroyChild ( - IN EFI_SERVICE_BINDING_PROTOCOL *This, - IN EFI_HANDLE ChildHandle + IN EFI_SERVICE_BINDING_PROTOCOL *This, + IN EFI_HANDLE ChildHandle ) { - EFI_STATUS Status; - ISA_BUS_PRIVATE_DATA *Private; - EFI_ISA_HC_PROTOCOL *IsaHc; - ISA_BUS_CHILD_PRIVATE_DATA *Child; + EFI_STATUS Status; + ISA_BUS_PRIVATE_DATA *Private; + EFI_ISA_HC_PROTOCOL *IsaHc; + ISA_BUS_CHILD_PRIVATE_DATA *Child; Private = ISA_BUS_PRIVATE_DATA_FROM_THIS (This); Status = gBS->OpenProtocol ( ChildHandle, &gEfiCallerIdGuid, - (VOID **) &Child, + (VOID **)&Child, gIsaBusDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -207,25 +209,27 @@ IsaBusDestroyChild ( } Child->InDestroying = TRUE; - Status = gBS->CloseProtocol ( - Private->IsaHcHandle, - &gEfiIsaHcProtocolGuid, - gIsaBusDriverBinding.DriverBindingHandle, - ChildHandle - ); + Status = gBS->CloseProtocol ( + Private->IsaHcHandle, + &gEfiIsaHcProtocolGuid, + gIsaBusDriverBinding.DriverBindingHandle, + ChildHandle + ); ASSERT_EFI_ERROR (Status); if (!EFI_ERROR (Status)) { Status = gBS->UninstallMultipleProtocolInterfaces ( ChildHandle, - &gEfiIsaHcProtocolGuid, Private->IsaHc, - &gEfiCallerIdGuid, Child, + &gEfiIsaHcProtocolGuid, + Private->IsaHc, + &gEfiCallerIdGuid, + Child, NULL ); if (EFI_ERROR (Status)) { gBS->OpenProtocol ( Private->IsaHcHandle, &gEfiIsaHcProtocolGuid, - (VOID **) &IsaHc, + (VOID **)&IsaHc, gIsaBusDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -242,7 +246,7 @@ IsaBusDestroyChild ( return Status; } -ISA_BUS_PRIVATE_DATA mIsaBusPrivateTemplate = { +ISA_BUS_PRIVATE_DATA mIsaBusPrivateTemplate = { ISA_BUS_PRIVATE_DATA_SIGNATURE, { IsaBusCreateChild, @@ -278,19 +282,19 @@ ISA_BUS_PRIVATE_DATA mIsaBusPrivateTemplate = { EFI_STATUS EFIAPI IsaBusDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - ISA_BUS_PRIVATE_DATA *Private; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + ISA_BUS_PRIVATE_DATA *Private; Status = gBS->OpenProtocol ( Controller, &gEfiIsaHcProtocolGuid, - (VOID **) &mIsaBusPrivateTemplate.IsaHc, + (VOID **)&mIsaBusPrivateTemplate.IsaHc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -302,7 +306,7 @@ IsaBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -324,7 +328,8 @@ IsaBusDriverBindingStart ( Status = gBS->InstallMultipleProtocolInterfaces ( &Controller, - &gEfiIsaHcServiceBindingProtocolGuid, &Private->ServiceBinding, + &gEfiIsaHcServiceBindingProtocolGuid, + &Private->ServiceBinding, NULL ); ASSERT_EFI_ERROR (Status); @@ -350,22 +355,22 @@ IsaBusDriverBindingStart ( EFI_STATUS EFIAPI IsaBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding; - ISA_BUS_PRIVATE_DATA *Private; - UINTN Index; - BOOLEAN AllChildrenStopped; + EFI_STATUS Status; + EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding; + ISA_BUS_PRIVATE_DATA *Private; + UINTN Index; + BOOLEAN AllChildrenStopped; Status = gBS->OpenProtocol ( Controller, &gEfiIsaHcServiceBindingProtocolGuid, - (VOID **) &ServiceBinding, + (VOID **)&ServiceBinding, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -379,7 +384,8 @@ IsaBusDriverBindingStop ( if (NumberOfChildren == 0) { Status = gBS->UninstallMultipleProtocolInterfaces ( Controller, - &gEfiIsaHcServiceBindingProtocolGuid, &Private->ServiceBinding, + &gEfiIsaHcServiceBindingProtocolGuid, + &Private->ServiceBinding, NULL ); if (!EFI_ERROR (Status)) { @@ -415,7 +421,7 @@ IsaBusDriverBindingStop ( // // ISA Bus Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gIsaBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gIsaBusDriverBinding = { IsaBusDriverBindingSupported, IsaBusDriverBindingStart, IsaBusDriverBindingStop, @@ -440,7 +446,7 @@ InitializeIsaBus ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, diff --git a/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.h b/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.h index 939a08b509..102f84a828 100644 --- a/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.h +++ b/MdeModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.h @@ -26,15 +26,15 @@ typedef struct { EFI_ISA_HC_PROTOCOL *IsaHc; ///< ISA HC protocol produced by the ISA Host Controller driver EFI_HANDLE IsaHcHandle; ///< ISA HC handle created by the ISA Host Controller driver } ISA_BUS_PRIVATE_DATA; -#define ISA_BUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('_', 'i', 's', 'b') -#define ISA_BUS_PRIVATE_DATA_FROM_THIS(a) CR (a, ISA_BUS_PRIVATE_DATA, ServiceBinding, ISA_BUS_PRIVATE_DATA_SIGNATURE) +#define ISA_BUS_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('_', 'i', 's', 'b') +#define ISA_BUS_PRIVATE_DATA_FROM_THIS(a) CR (a, ISA_BUS_PRIVATE_DATA, ServiceBinding, ISA_BUS_PRIVATE_DATA_SIGNATURE) typedef struct { - UINT32 Signature; - BOOLEAN InDestroying; ///< Flag to avoid DestroyChild() re-entry. + UINT32 Signature; + BOOLEAN InDestroying; ///< Flag to avoid DestroyChild() re-entry. } ISA_BUS_CHILD_PRIVATE_DATA; -#define ISA_BUS_CHILD_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('_', 'i', 's', 'c') +#define ISA_BUS_CHILD_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('_', 'i', 's', 'c') -extern EFI_DRIVER_BINDING_PROTOCOL gIsaBusDriverBinding; +extern EFI_DRIVER_BINDING_PROTOCOL gIsaBusDriverBinding; #endif diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/ComponentName.c b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/ComponentName.c index 3d2e9de67b..d36e2becd6 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/ComponentName.c @@ -11,6 +11,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -58,7 +59,6 @@ Ps2KeyboardComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -130,14 +130,13 @@ Ps2KeyboardComponentNameGetDriverName ( EFI_STATUS EFIAPI Ps2KeyboardComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); - // // EFI Component Name Protocol // @@ -150,14 +149,13 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gPs2KeyboardComponent // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPs2KeyboardComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) Ps2KeyboardComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) Ps2KeyboardComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPs2KeyboardComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)Ps2KeyboardComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)Ps2KeyboardComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPs2KeyboardDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPs2KeyboardDriverNameTable[] = { { "eng;en", L"PS/2 Keyboard Driver" @@ -295,16 +293,17 @@ Ps2KeyboardComponentNameGetDriverName ( EFI_STATUS EFIAPI Ps2KeyboardComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + EFI_STATUS Status; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + // // This is a device driver, so ChildHandle must be NULL. // @@ -319,13 +318,14 @@ Ps2KeyboardComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, &gEfiSimpleTextInProtocolGuid, - (VOID **) &ConIn, + (VOID **)&ConIn, gKeyboardControllerDriver.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c index d8d050b0a9..77dc226222 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdCtrller.c @@ -9,13 +9,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ps2Keyboard.h" struct { - UINT8 ScanCode; ///< follows value defined in Scan Code Set1 - UINT16 EfiScanCode; - CHAR16 UnicodeChar; - CHAR16 ShiftUnicodeChar; -} -ConvertKeyboardScanCodeToEfiKey[] = { - + UINT8 ScanCode; ///< follows value defined in Scan Code Set1 + UINT16 EfiScanCode; + CHAR16 UnicodeChar; + CHAR16 ShiftUnicodeChar; +} ConvertKeyboardScanCodeToEfiKey[] = { { 0x01, // Escape SCAN_ESC, @@ -335,7 +333,7 @@ ConvertKeyboardScanCodeToEfiKey[] = { L'?' }, { - 0x36, //Right Shift + 0x36, // Right Shift SCAN_NULL, 0x0000, 0x0000 @@ -347,7 +345,7 @@ ConvertKeyboardScanCodeToEfiKey[] = { L'*' }, { - 0x38, //Left Alt/Extended Right Alt + 0x38, // Left Alt/Extended Right Alt SCAN_NULL, 0x0000, 0x0000 @@ -359,7 +357,7 @@ ConvertKeyboardScanCodeToEfiKey[] = { L' ' }, { - 0x3A, //CapsLock + 0x3A, // CapsLock SCAN_NULL, 0x0000, 0x0000 @@ -527,19 +525,19 @@ ConvertKeyboardScanCodeToEfiKey[] = { 0x0000 }, { - 0x5B, //Left LOGO + 0x5B, // Left LOGO SCAN_NULL, 0x0000, 0x0000 }, { - 0x5C, //Right LOGO + 0x5C, // Right LOGO SCAN_NULL, 0x0000, 0x0000 }, { - 0x5D, //Menu key + 0x5D, // Menu key SCAN_NULL, 0x0000, 0x0000 @@ -557,9 +555,7 @@ ConvertKeyboardScanCodeToEfiKey[] = { // UINTN mWaitForValueTimeOut = KEYBOARD_WAITFORVALUE_TIMEOUT; -BOOLEAN mEnableMouseInterface; - - +BOOLEAN mEnableMouseInterface; /** Return the count of scancode in the queue. @@ -570,7 +566,7 @@ BOOLEAN mEnableMouseInterface; **/ UINTN GetScancodeBufCount ( - IN SCAN_CODE_QUEUE *Queue + IN SCAN_CODE_QUEUE *Queue ) { if (Queue->Head <= Queue->Tail) { @@ -594,13 +590,13 @@ GetScancodeBufCount ( **/ EFI_STATUS GetScancodeBufHead ( - IN SCAN_CODE_QUEUE *Queue, - IN UINTN Count, - OUT UINT8 *Buf + IN SCAN_CODE_QUEUE *Queue, + IN UINTN Count, + OUT UINT8 *Buf ) { - UINTN Index; - UINTN Pos; + UINTN Index; + UINTN Pos; // // check the valid range of parameter 'Count' @@ -608,6 +604,7 @@ GetScancodeBufHead ( if (GetScancodeBufCount (Queue) < Count) { return EFI_NOT_READY; } + // // retrieve the values // @@ -632,12 +629,12 @@ GetScancodeBufHead ( **/ EFI_STATUS PopScancodeBufHead ( - IN SCAN_CODE_QUEUE *Queue, - IN UINTN Count, - OUT UINT8 *Buf OPTIONAL + IN SCAN_CODE_QUEUE *Queue, + IN UINTN Count, + OUT UINT8 *Buf OPTIONAL ) { - UINTN Index; + UINTN Index; // // Check the valid range of parameter 'Count' @@ -645,6 +642,7 @@ PopScancodeBufHead ( if (GetScancodeBufCount (Queue) < Count) { return EFI_NOT_READY; } + // // Retrieve and remove the values // @@ -665,8 +663,8 @@ PopScancodeBufHead ( **/ VOID PushScancodeBufTail ( - IN SCAN_CODE_QUEUE *Queue, - IN UINT8 Scancode + IN SCAN_CODE_QUEUE *Queue, + IN UINT8 Scancode ) { if (GetScancodeBufCount (Queue) == KEYBOARD_SCAN_CODE_MAX_COUNT - 1) { @@ -674,7 +672,7 @@ PushScancodeBufTail ( } Queue->Buffer[Queue->Tail] = Scancode; - Queue->Tail = (Queue->Tail + 1) % KEYBOARD_SCAN_CODE_MAX_COUNT; + Queue->Tail = (Queue->Tail + 1) % KEYBOARD_SCAN_CODE_MAX_COUNT; } /** @@ -687,7 +685,7 @@ PushScancodeBufTail ( **/ UINT8 KeyReadDataRegister ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ) { @@ -703,8 +701,8 @@ KeyReadDataRegister ( **/ VOID KeyWriteDataRegister ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN UINT8 Data + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN UINT8 Data ) { IoWrite8 (ConsoleIn->DataRegisterAddress, Data); @@ -720,7 +718,7 @@ KeyWriteDataRegister ( **/ UINT8 KeyReadStatusRegister ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ) { return IoRead8 (ConsoleIn->StatusRegisterAddress); @@ -735,8 +733,8 @@ KeyReadStatusRegister ( **/ VOID KeyWriteCommandRegister ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN UINT8 Data + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN UINT8 Data ) { IoWrite8 (ConsoleIn->CommandRegisterAddress, Data); @@ -751,8 +749,8 @@ KeyWriteCommandRegister ( **/ VOID KeyboardError ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN CHAR16 *ErrMsg + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN CHAR16 *ErrMsg ) { ConsoleIn->KeyboardErr = TRUE; @@ -772,28 +770,28 @@ KeyboardError ( VOID EFIAPI KeyboardTimerHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - UINT8 Data; - EFI_TPL OldTpl; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + UINT8 Data; + EFI_TPL OldTpl; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *) Context; + ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *)Context; // // Enter critical section // OldTpl = gBS->RaiseTPL (TPL_NOTIFY); - if (((KEYBOARD_CONSOLE_IN_DEV *) Context)->KeyboardErr) { + if (((KEYBOARD_CONSOLE_IN_DEV *)Context)->KeyboardErr) { // // Leave critical section and return // gBS->RestoreTPL (OldTpl); - return ; + return; } // @@ -805,14 +803,16 @@ KeyboardTimerHandler ( // while ((KeyReadStatusRegister (ConsoleIn) & (KEYBOARD_STATUS_REGISTER_TRANSMIT_TIMEOUT|KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA)) == - KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA - ) { + KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA + ) + { // // Read one byte of the scan code and store it into the memory buffer // Data = KeyReadDataRegister (ConsoleIn); PushScancodeBufTail (&ConsoleIn->ScancodeQueue, Data); } + KeyGetchar (ConsoleIn); // @@ -876,15 +876,15 @@ KeyboardRead ( **/ EFI_STATUS KeyboardWrite ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN UINT8 Data + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN UINT8 Data ) { UINT32 TimeOut; UINT32 RegEmptied; - TimeOut = 0; - RegEmptied = 0; + TimeOut = 0; + RegEmptied = 0; // // wait for input buffer empty @@ -901,6 +901,7 @@ KeyboardWrite ( if (RegEmptied == 0) { return EFI_TIMEOUT; } + // // Write it // @@ -921,15 +922,15 @@ KeyboardWrite ( **/ EFI_STATUS KeyboardCommand ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN UINT8 Data + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN UINT8 Data ) { UINT32 TimeOut; UINT32 RegEmptied; - TimeOut = 0; - RegEmptied = 0; + TimeOut = 0; + RegEmptied = 0; // // Wait For Input Buffer Empty @@ -946,6 +947,7 @@ KeyboardCommand ( if (RegEmptied == 0) { return EFI_TIMEOUT; } + // // issue the command // @@ -985,8 +987,8 @@ KeyboardCommand ( **/ EFI_STATUS KeyboardWaitForValue ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN UINT8 Value + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN UINT8 Value ) { UINT8 Data; @@ -994,9 +996,9 @@ KeyboardWaitForValue ( UINT32 SumTimeOut; UINT32 GotIt; - GotIt = 0; - TimeOut = 0; - SumTimeOut = 0; + GotIt = 0; + TimeOut = 0; + SumTimeOut = 0; // // Make sure the initial value of 'Data' is different from 'Value' @@ -1005,6 +1007,7 @@ KeyboardWaitForValue ( if (Data == Value) { Data = 1; } + // // Read from 8042 (multiple times if needed) // until the expected value appears @@ -1034,6 +1037,7 @@ KeyboardWaitForValue ( break; } } + // // Check results // @@ -1042,7 +1046,6 @@ KeyboardWaitForValue ( } else { return EFI_TIMEOUT; } - } /** @@ -1056,7 +1059,7 @@ KeyboardWaitForValue ( **/ EFI_STATUS UpdateStatusLights ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ) { EFI_STATUS Status; @@ -1106,28 +1109,28 @@ UpdateStatusLights ( **/ VOID InitializeKeyState ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - OUT EFI_KEY_STATE *KeyState + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + OUT EFI_KEY_STATE *KeyState ) { - KeyState->KeyShiftState = EFI_SHIFT_STATE_VALID - | (ConsoleIn->LeftCtrl ? EFI_LEFT_CONTROL_PRESSED : 0) - | (ConsoleIn->RightCtrl ? EFI_RIGHT_CONTROL_PRESSED : 0) - | (ConsoleIn->LeftAlt ? EFI_LEFT_ALT_PRESSED : 0) - | (ConsoleIn->RightAlt ? EFI_RIGHT_ALT_PRESSED : 0) - | (ConsoleIn->LeftShift ? EFI_LEFT_SHIFT_PRESSED : 0) - | (ConsoleIn->RightShift ? EFI_RIGHT_SHIFT_PRESSED : 0) - | (ConsoleIn->LeftLogo ? EFI_LEFT_LOGO_PRESSED : 0) - | (ConsoleIn->RightLogo ? EFI_RIGHT_LOGO_PRESSED : 0) - | (ConsoleIn->Menu ? EFI_MENU_KEY_PRESSED : 0) - | (ConsoleIn->SysReq ? EFI_SYS_REQ_PRESSED : 0) - ; + KeyState->KeyShiftState = EFI_SHIFT_STATE_VALID + | (ConsoleIn->LeftCtrl ? EFI_LEFT_CONTROL_PRESSED : 0) + | (ConsoleIn->RightCtrl ? EFI_RIGHT_CONTROL_PRESSED : 0) + | (ConsoleIn->LeftAlt ? EFI_LEFT_ALT_PRESSED : 0) + | (ConsoleIn->RightAlt ? EFI_RIGHT_ALT_PRESSED : 0) + | (ConsoleIn->LeftShift ? EFI_LEFT_SHIFT_PRESSED : 0) + | (ConsoleIn->RightShift ? EFI_RIGHT_SHIFT_PRESSED : 0) + | (ConsoleIn->LeftLogo ? EFI_LEFT_LOGO_PRESSED : 0) + | (ConsoleIn->RightLogo ? EFI_RIGHT_LOGO_PRESSED : 0) + | (ConsoleIn->Menu ? EFI_MENU_KEY_PRESSED : 0) + | (ConsoleIn->SysReq ? EFI_SYS_REQ_PRESSED : 0) + ; KeyState->KeyToggleState = EFI_TOGGLE_STATE_VALID - | (ConsoleIn->CapsLock ? EFI_CAPS_LOCK_ACTIVE : 0) - | (ConsoleIn->NumLock ? EFI_NUM_LOCK_ACTIVE : 0) - | (ConsoleIn->ScrollLock ? EFI_SCROLL_LOCK_ACTIVE : 0) - | (ConsoleIn->IsSupportPartialKey ? EFI_KEY_STATE_EXPOSED : 0) - ; + | (ConsoleIn->CapsLock ? EFI_CAPS_LOCK_ACTIVE : 0) + | (ConsoleIn->NumLock ? EFI_NUM_LOCK_ACTIVE : 0) + | (ConsoleIn->ScrollLock ? EFI_SCROLL_LOCK_ACTIVE : 0) + | (ConsoleIn->IsSupportPartialKey ? EFI_KEY_STATE_EXPOSED : 0) + ; } /** @@ -1140,7 +1143,7 @@ InitializeKeyState ( **/ VOID KeyGetchar ( - IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ) { EFI_STATUS Status; @@ -1154,8 +1157,8 @@ KeyGetchar ( // // 3 bytes most // - UINT8 ScancodeArr[3]; - UINT32 ScancodeArrPos; + UINT8 ScancodeArr[3]; + UINT32 ScancodeArrPos; // // Check if there are enough bytes of scancode representing a single key @@ -1165,32 +1168,33 @@ KeyGetchar ( Extend0 = FALSE; Extend1 = FALSE; ScancodeArrPos = 0; - Status = GetScancodeBufHead (&ConsoleIn->ScancodeQueue, ScancodeArrPos + 1, ScancodeArr); + Status = GetScancodeBufHead (&ConsoleIn->ScancodeQueue, ScancodeArrPos + 1, ScancodeArr); if (EFI_ERROR (Status)) { - return ; + return; } if (ScancodeArr[ScancodeArrPos] == SCANCODE_EXTENDED0) { // // E0 to look ahead 2 bytes // - Extend0 = TRUE; + Extend0 = TRUE; ScancodeArrPos = 1; Status = GetScancodeBufHead (&ConsoleIn->ScancodeQueue, ScancodeArrPos + 1, ScancodeArr); if (EFI_ERROR (Status)) { - return ; + return; } } else if (ScancodeArr[ScancodeArrPos] == SCANCODE_EXTENDED1) { // // E1 to look ahead 3 bytes // - Extend1 = TRUE; + Extend1 = TRUE; ScancodeArrPos = 2; Status = GetScancodeBufHead (&ConsoleIn->ScancodeQueue, ScancodeArrPos + 1, ScancodeArr); if (EFI_ERROR (Status)) { - return ; + return; } } + // // if we reach this position, scancodes for a key is in buffer now,pop them // @@ -1207,115 +1211,123 @@ KeyGetchar ( // Check for special keys and update the driver state. // switch (ScanCode) { + case SCANCODE_CTRL_MAKE: + if (Extend0) { + ConsoleIn->RightCtrl = TRUE; + } else { + ConsoleIn->LeftCtrl = TRUE; + } - case SCANCODE_CTRL_MAKE: - if (Extend0) { - ConsoleIn->RightCtrl = TRUE; - } else { - ConsoleIn->LeftCtrl = TRUE; - } - break; - case SCANCODE_CTRL_BREAK: - if (Extend0) { - ConsoleIn->RightCtrl = FALSE; - } else { - ConsoleIn->LeftCtrl = FALSE; - } - break; + break; + case SCANCODE_CTRL_BREAK: + if (Extend0) { + ConsoleIn->RightCtrl = FALSE; + } else { + ConsoleIn->LeftCtrl = FALSE; + } - case SCANCODE_ALT_MAKE: + break; + + case SCANCODE_ALT_MAKE: if (Extend0) { ConsoleIn->RightAlt = TRUE; } else { - ConsoleIn->LeftAlt = TRUE; + ConsoleIn->LeftAlt = TRUE; } - break; - case SCANCODE_ALT_BREAK: + + break; + case SCANCODE_ALT_BREAK: if (Extend0) { ConsoleIn->RightAlt = FALSE; } else { - ConsoleIn->LeftAlt = FALSE; + ConsoleIn->LeftAlt = FALSE; } - break; - case SCANCODE_LEFT_SHIFT_MAKE: - // - // To avoid recognize PRNT_SCRN key as a L_SHIFT key - // because PRNT_SCRN key generates E0 followed by L_SHIFT scan code. - // If it the second byte of the PRNT_ScRN skip it. - // - if (!Extend0) { - ConsoleIn->LeftShift = TRUE; break; - } - continue; - case SCANCODE_LEFT_SHIFT_BREAK: - if (!Extend0) { - ConsoleIn->LeftShift = FALSE; - } - break; + case SCANCODE_LEFT_SHIFT_MAKE: + // + // To avoid recognize PRNT_SCRN key as a L_SHIFT key + // because PRNT_SCRN key generates E0 followed by L_SHIFT scan code. + // If it the second byte of the PRNT_ScRN skip it. + // + if (!Extend0) { + ConsoleIn->LeftShift = TRUE; + break; + } - case SCANCODE_RIGHT_SHIFT_MAKE: - ConsoleIn->RightShift = TRUE; - break; - case SCANCODE_RIGHT_SHIFT_BREAK: - ConsoleIn->RightShift = FALSE; - break; + continue; - case SCANCODE_LEFT_LOGO_MAKE: - ConsoleIn->LeftLogo = TRUE; - break; - case SCANCODE_LEFT_LOGO_BREAK: - ConsoleIn->LeftLogo = FALSE; - break; + case SCANCODE_LEFT_SHIFT_BREAK: + if (!Extend0) { + ConsoleIn->LeftShift = FALSE; + } - case SCANCODE_RIGHT_LOGO_MAKE: - ConsoleIn->RightLogo = TRUE; - break; - case SCANCODE_RIGHT_LOGO_BREAK: - ConsoleIn->RightLogo = FALSE; - break; + break; - case SCANCODE_MENU_MAKE: - ConsoleIn->Menu = TRUE; - break; - case SCANCODE_MENU_BREAK: - ConsoleIn->Menu = FALSE; - break; + case SCANCODE_RIGHT_SHIFT_MAKE: + ConsoleIn->RightShift = TRUE; + break; + case SCANCODE_RIGHT_SHIFT_BREAK: + ConsoleIn->RightShift = FALSE; + break; + + case SCANCODE_LEFT_LOGO_MAKE: + ConsoleIn->LeftLogo = TRUE; + break; + case SCANCODE_LEFT_LOGO_BREAK: + ConsoleIn->LeftLogo = FALSE; + break; + + case SCANCODE_RIGHT_LOGO_MAKE: + ConsoleIn->RightLogo = TRUE; + break; + case SCANCODE_RIGHT_LOGO_BREAK: + ConsoleIn->RightLogo = FALSE; + break; + + case SCANCODE_MENU_MAKE: + ConsoleIn->Menu = TRUE; + break; + case SCANCODE_MENU_BREAK: + ConsoleIn->Menu = FALSE; + break; + + case SCANCODE_SYS_REQ_MAKE: + if (Extend0) { + ConsoleIn->SysReq = TRUE; + } + + break; + case SCANCODE_SYS_REQ_BREAK: + if (Extend0) { + ConsoleIn->SysReq = FALSE; + } - case SCANCODE_SYS_REQ_MAKE: - if (Extend0) { + break; + + case SCANCODE_SYS_REQ_MAKE_WITH_ALT: ConsoleIn->SysReq = TRUE; - } - break; - case SCANCODE_SYS_REQ_BREAK: - if (Extend0) { + break; + case SCANCODE_SYS_REQ_BREAK_WITH_ALT: ConsoleIn->SysReq = FALSE; - } - break; - - case SCANCODE_SYS_REQ_MAKE_WITH_ALT: - ConsoleIn->SysReq = TRUE; - break; - case SCANCODE_SYS_REQ_BREAK_WITH_ALT: - ConsoleIn->SysReq = FALSE; - break; + break; - case SCANCODE_CAPS_LOCK_MAKE: - ConsoleIn->CapsLock = (BOOLEAN)!ConsoleIn->CapsLock; - UpdateStatusLights (ConsoleIn); - break; - case SCANCODE_NUM_LOCK_MAKE: - ConsoleIn->NumLock = (BOOLEAN)!ConsoleIn->NumLock; - UpdateStatusLights (ConsoleIn); - break; - case SCANCODE_SCROLL_LOCK_MAKE: - if (!Extend0) { - ConsoleIn->ScrollLock = (BOOLEAN)!ConsoleIn->ScrollLock; + case SCANCODE_CAPS_LOCK_MAKE: + ConsoleIn->CapsLock = (BOOLEAN) !ConsoleIn->CapsLock; UpdateStatusLights (ConsoleIn); - } - break; + break; + case SCANCODE_NUM_LOCK_MAKE: + ConsoleIn->NumLock = (BOOLEAN) !ConsoleIn->NumLock; + UpdateStatusLights (ConsoleIn); + break; + case SCANCODE_SCROLL_LOCK_MAKE: + if (!Extend0) { + ConsoleIn->ScrollLock = (BOOLEAN) !ConsoleIn->ScrollLock; + UpdateStatusLights (ConsoleIn); + } + + break; } } @@ -1333,9 +1345,10 @@ KeyGetchar ( // Handle Ctrl+Alt+Del hotkey // if ((ConsoleIn->LeftCtrl || ConsoleIn->RightCtrl) && - (ConsoleIn->LeftAlt || ConsoleIn->RightAlt ) && - ScanCode == SCANCODE_DELETE_MAKE - ) { + (ConsoleIn->LeftAlt || ConsoleIn->RightAlt) && + (ScanCode == SCANCODE_DELETE_MAKE) + ) + { gRT->ResetSystem (EfiResetWarm, EFI_SUCCESS, 0, NULL); } @@ -1349,34 +1362,34 @@ KeyGetchar ( // // Key Pad "/" shares the same scancode as that of "/" except Key Pad "/" has E0 prefix // - if (Extend0 && ScanCode == 0x35) { + if (Extend0 && (ScanCode == 0x35)) { KeyData.Key.UnicodeChar = L'/'; KeyData.Key.ScanCode = SCAN_NULL; - // - // PAUSE shares the same scancode as that of NUM except PAUSE has E1 prefix - // - } else if (Extend1 && ScanCode == SCANCODE_NUM_LOCK_MAKE) { + // + // PAUSE shares the same scancode as that of NUM except PAUSE has E1 prefix + // + } else if (Extend1 && (ScanCode == SCANCODE_NUM_LOCK_MAKE)) { KeyData.Key.UnicodeChar = CHAR_NULL; KeyData.Key.ScanCode = SCAN_PAUSE; - // - // PAUSE shares the same scancode as that of SCROLL except PAUSE (CTRL pressed) has E0 prefix - // - } else if (Extend0 && ScanCode == SCANCODE_SCROLL_LOCK_MAKE) { + // + // PAUSE shares the same scancode as that of SCROLL except PAUSE (CTRL pressed) has E0 prefix + // + } else if (Extend0 && (ScanCode == SCANCODE_SCROLL_LOCK_MAKE)) { KeyData.Key.UnicodeChar = CHAR_NULL; KeyData.Key.ScanCode = SCAN_PAUSE; - // - // PRNT_SCRN shares the same scancode as that of Key Pad "*" except PRNT_SCRN has E0 prefix - // - } else if (Extend0 && ScanCode == SCANCODE_SYS_REQ_MAKE) { + // + // PRNT_SCRN shares the same scancode as that of Key Pad "*" except PRNT_SCRN has E0 prefix + // + } else if (Extend0 && (ScanCode == SCANCODE_SYS_REQ_MAKE)) { KeyData.Key.UnicodeChar = CHAR_NULL; KeyData.Key.ScanCode = SCAN_NULL; - // - // Except the above special case, all others can be handled by convert table - // + // + // Except the above special case, all others can be handled by convert table + // } else { for (Index = 0; ConvertKeyboardScanCodeToEfiKey[Index].ScanCode != TABLE_END; Index++) { if (ScanCode == ConvertKeyboardScanCodeToEfiKey[Index].ScanCode) { @@ -1384,7 +1397,8 @@ KeyGetchar ( KeyData.Key.UnicodeChar = ConvertKeyboardScanCodeToEfiKey[Index].UnicodeChar; if ((ConsoleIn->LeftShift || ConsoleIn->RightShift) && - (ConvertKeyboardScanCodeToEfiKey[Index].UnicodeChar != ConvertKeyboardScanCodeToEfiKey[Index].ShiftUnicodeChar)) { + (ConvertKeyboardScanCodeToEfiKey[Index].UnicodeChar != ConvertKeyboardScanCodeToEfiKey[Index].ShiftUnicodeChar)) + { KeyData.Key.UnicodeChar = ConvertKeyboardScanCodeToEfiKey[Index].ShiftUnicodeChar; // // Need not return associated shift state if a class of printable characters that @@ -1392,16 +1406,18 @@ KeyGetchar ( // KeyData.KeyState.KeyShiftState &= ~(EFI_LEFT_SHIFT_PRESSED | EFI_RIGHT_SHIFT_PRESSED); } + // // alphabetic key is affected by CapsLock State // if (ConsoleIn->CapsLock) { - if (KeyData.Key.UnicodeChar >= L'a' && KeyData.Key.UnicodeChar <= L'z') { - KeyData.Key.UnicodeChar = (UINT16) (KeyData.Key.UnicodeChar - L'a' + L'A'); - } else if (KeyData.Key.UnicodeChar >= L'A' && KeyData.Key.UnicodeChar <= L'Z') { - KeyData.Key.UnicodeChar = (UINT16) (KeyData.Key.UnicodeChar - L'A' + L'a'); + if ((KeyData.Key.UnicodeChar >= L'a') && (KeyData.Key.UnicodeChar <= L'z')) { + KeyData.Key.UnicodeChar = (UINT16)(KeyData.Key.UnicodeChar - L'a' + L'A'); + } else if ((KeyData.Key.UnicodeChar >= L'A') && (KeyData.Key.UnicodeChar <= L'Z')) { + KeyData.Key.UnicodeChar = (UINT16)(KeyData.Key.UnicodeChar - L'A' + L'a'); } } + break; } } @@ -1410,10 +1426,10 @@ KeyGetchar ( // // distinguish numeric key pad keys' 'up symbol' and 'down symbol' // - if (ScanCode >= 0x47 && ScanCode <= 0x53) { + if ((ScanCode >= 0x47) && (ScanCode <= 0x53)) { if (ConsoleIn->NumLock && !(ConsoleIn->LeftShift || ConsoleIn->RightShift) && !Extend0) { KeyData.Key.ScanCode = SCAN_NULL; - } else if (ScanCode != 0x4a && ScanCode != 0x4e) { + } else if ((ScanCode != 0x4a) && (ScanCode != 0x4e)) { KeyData.Key.UnicodeChar = CHAR_NULL; } } @@ -1421,9 +1437,9 @@ KeyGetchar ( // // If the key can not be converted then just return. // - if (KeyData.Key.ScanCode == SCAN_NULL && KeyData.Key.UnicodeChar == CHAR_NULL) { + if ((KeyData.Key.ScanCode == SCAN_NULL) && (KeyData.Key.UnicodeChar == CHAR_NULL)) { if (!ConsoleIn->IsSupportPartialKey) { - return ; + return; } } @@ -1465,28 +1481,28 @@ KeyGetchar ( **/ EFI_STATUS InitKeyboard ( - IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN BOOLEAN ExtendedVerification + IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - EFI_STATUS Status1; - UINT8 CommandByte; - EFI_PS2_POLICY_PROTOCOL *Ps2Policy; - UINT32 TryTime; + EFI_STATUS Status; + EFI_STATUS Status1; + UINT8 CommandByte; + EFI_PS2_POLICY_PROTOCOL *Ps2Policy; + UINT32 TryTime; - Status = EFI_SUCCESS; - mEnableMouseInterface = TRUE; - TryTime = 0; + Status = EFI_SUCCESS; + mEnableMouseInterface = TRUE; + TryTime = 0; // // Get Ps2 policy to set this // gBS->LocateProtocol ( - &gEfiPs2PolicyProtocolGuid, - NULL, - (VOID **) &Ps2Policy - ); + &gEfiPs2PolicyProtocolGuid, + NULL, + (VOID **)&Ps2Policy + ); REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, @@ -1501,8 +1517,9 @@ InitKeyboard ( if ((KeyReadStatusRegister (ConsoleIn) & KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA) != 0) { while (!EFI_ERROR (Status) && TryTime < KEYBOARD_MAX_TRY) { Status = KeyboardRead (ConsoleIn, &CommandByte); - TryTime ++; + TryTime++; } + // // Exceed the max try times. The device may be error. // @@ -1511,6 +1528,7 @@ InitKeyboard ( goto Done; } } + // // We should disable mouse interface during the initialization process // since mouse device output could block keyboard device output in the @@ -1544,6 +1562,7 @@ InitKeyboard ( KeyboardError (ConsoleIn, L"\n\r"); goto Done; } + // // Test the mouse enabling bit // @@ -1597,16 +1616,17 @@ InitKeyboard ( goto Done; } } + // // Don't enable mouse interface later // mEnableMouseInterface = FALSE; - } if (Ps2Policy != NULL) { Ps2Policy->Ps2InitHardware (ConsoleIn->Handle); } + // // Write 8042 Command Byte, set System Flag // While at the same time: @@ -1640,10 +1660,10 @@ InitKeyboard ( // // Clear Memory Scancode Buffer // - ConsoleIn->ScancodeQueue.Head = 0; - ConsoleIn->ScancodeQueue.Tail = 0; - ConsoleIn->EfiKeyQueue.Head = 0; - ConsoleIn->EfiKeyQueue.Tail = 0; + ConsoleIn->ScancodeQueue.Head = 0; + ConsoleIn->ScancodeQueue.Tail = 0; + ConsoleIn->EfiKeyQueue.Head = 0; + ConsoleIn->EfiKeyQueue.Tail = 0; ConsoleIn->EfiKeyQueueForNotify.Head = 0; ConsoleIn->EfiKeyQueueForNotify.Tail = 0; @@ -1692,6 +1712,7 @@ InitKeyboard ( ); goto Done; } + // // Keyboard reset with a BAT(Basic Assurance Test) // @@ -1706,12 +1727,13 @@ InitKeyboard ( KeyboardError (ConsoleIn, L"Some specific value not acquired from 8042 controller!\n\r"); goto Done; } + // // wait for BAT completion code // - mWaitForValueTimeOut = KEYBOARD_BAT_TIMEOUT; + mWaitForValueTimeOut = KEYBOARD_BAT_TIMEOUT; - Status = KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_BAT_SUCCESS); + Status = KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_BAT_SUCCESS); if (EFI_ERROR (Status)) { KeyboardError (ConsoleIn, L"Keyboard self test failed!\n\r"); goto Done; @@ -1746,43 +1768,46 @@ InitKeyboard ( goto Done; } - // - // Clear Keyboard Scancode Buffer - // - Status = KeyboardWrite (ConsoleIn, KEYBOARD_8048_COMMAND_CLEAR_OUTPUT_DATA); - if (EFI_ERROR (Status)) { - KeyboardError (ConsoleIn, L"8042 controller data write error!\n\r"); - goto Done; - } - - Status = KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_ACK); - if (EFI_ERROR (Status)) { - KeyboardError (ConsoleIn, L"Some specific value not acquired from 8042 controller!\n\r"); - goto Done; - } - // - if (Ps2Policy != NULL) { - if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_CAPSLOCK) == EFI_KEYBOARD_CAPSLOCK) { - ConsoleIn->CapsLock = TRUE; + // + // Clear Keyboard Scancode Buffer + // + Status = KeyboardWrite (ConsoleIn, KEYBOARD_8048_COMMAND_CLEAR_OUTPUT_DATA); + if (EFI_ERROR (Status)) { + KeyboardError (ConsoleIn, L"8042 controller data write error!\n\r"); + goto Done; } - if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_NUMLOCK) == EFI_KEYBOARD_NUMLOCK) { - ConsoleIn->NumLock = TRUE; + Status = KeyboardWaitForValue (ConsoleIn, KEYBOARD_8048_RETURN_8042_ACK); + if (EFI_ERROR (Status)) { + KeyboardError (ConsoleIn, L"Some specific value not acquired from 8042 controller!\n\r"); + goto Done; } - if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_SCROLLLOCK) == EFI_KEYBOARD_SCROLLLOCK) { - ConsoleIn->ScrollLock = TRUE; + // + if (Ps2Policy != NULL) { + if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_CAPSLOCK) == EFI_KEYBOARD_CAPSLOCK) { + ConsoleIn->CapsLock = TRUE; + } + + if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_NUMLOCK) == EFI_KEYBOARD_NUMLOCK) { + ConsoleIn->NumLock = TRUE; + } + + if ((Ps2Policy->KeyboardLight & EFI_KEYBOARD_SCROLLLOCK) == EFI_KEYBOARD_SCROLLLOCK) { + ConsoleIn->ScrollLock = TRUE; + } } - } - // - // Update Keyboard Lights - // - Status = UpdateStatusLights (ConsoleIn); - if (EFI_ERROR (Status)) { - KeyboardError (ConsoleIn, L"Update keyboard status lights error!\n\r"); - goto Done; + + // + // Update Keyboard Lights + // + Status = UpdateStatusLights (ConsoleIn); + if (EFI_ERROR (Status)) { + KeyboardError (ConsoleIn, L"Update keyboard status lights error!\n\r"); + goto Done; } } + // // At last, we can now enable the mouse interface if appropriate // @@ -1804,10 +1829,8 @@ Done: } else { return EFI_DEVICE_ERROR; } - } - /** Check whether there is Ps/2 Keyboard device in system by 0xF4 Keyboard Command If Keyboard receives 0xF4, it will respond with 'ACK'. If it doesn't respond, the device @@ -1821,11 +1844,11 @@ Done: BOOLEAN EFIAPI CheckKeyboardConnect ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ) { - EFI_STATUS Status; - UINTN WaitForValueTimeOutBcakup; + EFI_STATUS Status; + UINTN WaitForValueTimeOutBcakup; // // enable keyboard itself and wait for its ack @@ -1840,15 +1863,16 @@ CheckKeyboardConnect ( if (EFI_ERROR (Status)) { return FALSE; } + // // wait for 1s // WaitForValueTimeOutBcakup = mWaitForValueTimeOut; - mWaitForValueTimeOut = KEYBOARD_WAITFORVALUE_TIMEOUT; - Status = KeyboardWaitForValue ( - ConsoleIn, - KEYBOARD_CMDECHO_ACK - ); + mWaitForValueTimeOut = KEYBOARD_WAITFORVALUE_TIMEOUT; + Status = KeyboardWaitForValue ( + ConsoleIn, + KEYBOARD_CMDECHO_ACK + ); mWaitForValueTimeOut = WaitForValueTimeOutBcakup; if (EFI_ERROR (Status)) { @@ -1860,4 +1884,3 @@ CheckKeyboardConnect ( return TRUE; } } - diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c index 835f33cfa8..b1ab17af37 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Ps2Keyboard.h" /** @@ -20,10 +19,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ BOOLEAN IsEfikeyBufEmpty ( - IN EFI_KEY_QUEUE *Queue + IN EFI_KEY_QUEUE *Queue ) { - return (BOOLEAN) (Queue->Head == Queue->Tail); + return (BOOLEAN)(Queue->Head == Queue->Tail); } /** @@ -37,19 +36,21 @@ IsEfikeyBufEmpty ( **/ EFI_STATUS PopEfikeyBufHead ( - IN EFI_KEY_QUEUE *Queue, - OUT EFI_KEY_DATA *KeyData OPTIONAL + IN EFI_KEY_QUEUE *Queue, + OUT EFI_KEY_DATA *KeyData OPTIONAL ) { if (IsEfikeyBufEmpty (Queue)) { return EFI_NOT_READY; } + // // Retrieve and remove the values // if (KeyData != NULL) { CopyMem (KeyData, &Queue->Buffer[Queue->Head], sizeof (EFI_KEY_DATA)); } + Queue->Head = (Queue->Head + 1) % KEYBOARD_EFI_KEY_MAX_COUNT; return EFI_SUCCESS; } @@ -62,8 +63,8 @@ PopEfikeyBufHead ( **/ VOID PushEfikeyBufTail ( - IN EFI_KEY_QUEUE *Queue, - IN EFI_KEY_DATA *KeyData + IN EFI_KEY_QUEUE *Queue, + IN EFI_KEY_DATA *KeyData ) { if ((Queue->Tail + 1) % KEYBOARD_EFI_KEY_MAX_COUNT == Queue->Head) { @@ -72,6 +73,7 @@ PushEfikeyBufTail ( // PopEfikeyBufHead (Queue, NULL); } + CopyMem (&Queue->Buffer[Queue->Tail], KeyData, sizeof (EFI_KEY_DATA)); Queue->Tail = (Queue->Tail + 1) % KEYBOARD_EFI_KEY_MAX_COUNT; } @@ -98,24 +100,27 @@ IsKeyRegistered ( ASSERT (RegsiteredData != NULL && InputData != NULL); if ((RegsiteredData->Key.ScanCode != InputData->Key.ScanCode) || - (RegsiteredData->Key.UnicodeChar != InputData->Key.UnicodeChar)) { + (RegsiteredData->Key.UnicodeChar != InputData->Key.UnicodeChar)) + { return FALSE; } // // Assume KeyShiftState/KeyToggleState = 0 in Registered key data means these state could be ignored. // - if (RegsiteredData->KeyState.KeyShiftState != 0 && - RegsiteredData->KeyState.KeyShiftState != InputData->KeyState.KeyShiftState) { + if ((RegsiteredData->KeyState.KeyShiftState != 0) && + (RegsiteredData->KeyState.KeyShiftState != InputData->KeyState.KeyShiftState)) + { return FALSE; } - if (RegsiteredData->KeyState.KeyToggleState != 0 && - RegsiteredData->KeyState.KeyToggleState != InputData->KeyState.KeyToggleState) { + + if ((RegsiteredData->KeyState.KeyToggleState != 0) && + (RegsiteredData->KeyState.KeyToggleState != InputData->KeyState.KeyToggleState)) + { return FALSE; } return TRUE; - } /** @@ -136,13 +141,13 @@ IsKeyRegistered ( **/ EFI_STATUS KeyboardReadKeyStrokeWorker ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev, - OUT EFI_KEY_DATA *KeyData + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev, + OUT EFI_KEY_DATA *KeyData ) { - EFI_STATUS Status; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_TPL OldTpl; if (KeyData == NULL) { return EFI_INVALID_PARAMETER; @@ -185,9 +190,9 @@ KeyboardEfiReset ( IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - EFI_TPL OldTpl; + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + EFI_TPL OldTpl; ConsoleIn = KEYBOARD_CONSOLE_IN_DEV_FROM_THIS (This); if (ConsoleIn->KeyboardErr) { @@ -232,6 +237,7 @@ KeyboardEfiReset ( ConsoleIn->DevicePath ); } + // // Report the status If keyboard is locked // @@ -261,9 +267,9 @@ KeyboardReadKeyStroke ( OUT EFI_INPUT_KEY *Key ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - EFI_KEY_DATA KeyData; + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + EFI_KEY_DATA KeyData; ConsoleIn = KEYBOARD_CONSOLE_IN_DEV_FROM_THIS (This); @@ -280,21 +286,23 @@ KeyboardReadKeyStroke ( if (EFI_ERROR (Status)) { return Status; } + // // If it is partial keystroke, skip it. // - if (KeyData.Key.ScanCode == SCAN_NULL && KeyData.Key.UnicodeChar == CHAR_NULL) { + if ((KeyData.Key.ScanCode == SCAN_NULL) && (KeyData.Key.UnicodeChar == CHAR_NULL)) { continue; } + // // Translate the CTRL-Alpha characters to their corresponding control value // (ctrl-a = 0x0001 through ctrl-Z = 0x001A) // if ((KeyData.KeyState.KeyShiftState & (EFI_LEFT_CONTROL_PRESSED | EFI_RIGHT_CONTROL_PRESSED)) != 0) { - if (KeyData.Key.UnicodeChar >= L'a' && KeyData.Key.UnicodeChar <= L'z') { - KeyData.Key.UnicodeChar = (CHAR16) (KeyData.Key.UnicodeChar - L'a' + 1); - } else if (KeyData.Key.UnicodeChar >= L'A' && KeyData.Key.UnicodeChar <= L'Z') { - KeyData.Key.UnicodeChar = (CHAR16) (KeyData.Key.UnicodeChar - L'A' + 1); + if ((KeyData.Key.UnicodeChar >= L'a') && (KeyData.Key.UnicodeChar <= L'z')) { + KeyData.Key.UnicodeChar = (CHAR16)(KeyData.Key.UnicodeChar - L'a' + 1); + } else if ((KeyData.Key.UnicodeChar >= L'A') && (KeyData.Key.UnicodeChar <= L'Z')) { + KeyData.Key.UnicodeChar = (CHAR16)(KeyData.Key.UnicodeChar - L'A' + 1); } } @@ -314,15 +322,15 @@ KeyboardReadKeyStroke ( VOID EFIAPI KeyboardWaitForKey ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_TPL OldTpl; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - EFI_KEY_DATA KeyData; + EFI_TPL OldTpl; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + EFI_KEY_DATA KeyData; - ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *) Context; + ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *)Context; // // Enter critical section @@ -344,10 +352,11 @@ KeyboardWaitForKey ( &(ConsoleIn->EfiKeyQueue.Buffer[ConsoleIn->EfiKeyQueue.Head]), sizeof (EFI_KEY_DATA) ); - if (KeyData.Key.ScanCode == SCAN_NULL && KeyData.Key.UnicodeChar == CHAR_NULL) { + if ((KeyData.Key.ScanCode == SCAN_NULL) && (KeyData.Key.UnicodeChar == CHAR_NULL)) { PopEfikeyBufHead (&ConsoleIn->EfiKeyQueue, &KeyData); continue; } + // // if there is pending value key, signal the event. // @@ -355,6 +364,7 @@ KeyboardWaitForKey ( break; } } + // // Leave critical section and return // @@ -372,8 +382,8 @@ KeyboardWaitForKey ( VOID EFIAPI KeyboardWaitForKeyEx ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { @@ -399,7 +409,7 @@ KeyboardEfiResetEx ( ) { - KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; + KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; ConsoleInDev = TEXT_INPUT_EX_KEYBOARD_CONSOLE_IN_DEV_FROM_THIS (This); @@ -428,12 +438,12 @@ KeyboardEfiResetEx ( EFI_STATUS EFIAPI KeyboardReadKeyStrokeEx ( - IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, - OUT EFI_KEY_DATA *KeyData + IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, + OUT EFI_KEY_DATA *KeyData ) { - KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; + KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; if (KeyData == NULL) { return EFI_INVALID_PARAMETER; @@ -465,9 +475,9 @@ KeyboardSetState ( ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; - EFI_TPL OldTpl; + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; + EFI_TPL OldTpl; if (KeyToggleState == NULL) { return EFI_INVALID_PARAMETER; @@ -501,12 +511,15 @@ KeyboardSetState ( if ((*KeyToggleState & EFI_SCROLL_LOCK_ACTIVE) == EFI_SCROLL_LOCK_ACTIVE) { ConsoleInDev->ScrollLock = TRUE; } + if ((*KeyToggleState & EFI_NUM_LOCK_ACTIVE) == EFI_NUM_LOCK_ACTIVE) { ConsoleInDev->NumLock = TRUE; } + if ((*KeyToggleState & EFI_CAPS_LOCK_ACTIVE) == EFI_CAPS_LOCK_ACTIVE) { ConsoleInDev->CapsLock = TRUE; } + if ((*KeyToggleState & EFI_KEY_STATE_EXPOSED) == EFI_KEY_STATE_EXPOSED) { ConsoleInDev->IsSupportPartialKey = TRUE; } @@ -523,7 +536,6 @@ Exit: gBS->RestoreTPL (OldTpl); return Status; - } /** @@ -553,14 +565,14 @@ KeyboardRegisterKeyNotify ( OUT VOID **NotifyHandle ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; - EFI_TPL OldTpl; - LIST_ENTRY *Link; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *NewNotify; - - if (KeyData == NULL || NotifyHandle == NULL || KeyNotificationFunction == NULL) { + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; + EFI_TPL OldTpl; + LIST_ENTRY *Link; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *NewNotify; + + if ((KeyData == NULL) || (NotifyHandle == NULL) || (KeyNotificationFunction == NULL)) { return EFI_INVALID_PARAMETER; } @@ -584,7 +596,7 @@ KeyboardRegisterKeyNotify ( if (IsKeyRegistered (&CurrentNotify->KeyData, KeyData)) { if (CurrentNotify->KeyNotificationFn == KeyNotificationFunction) { *NotifyHandle = CurrentNotify; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; goto Exit; } } @@ -593,7 +605,7 @@ KeyboardRegisterKeyNotify ( // // Allocate resource to save the notification function // - NewNotify = (KEYBOARD_CONSOLE_IN_EX_NOTIFY *) AllocateZeroPool (sizeof (KEYBOARD_CONSOLE_IN_EX_NOTIFY)); + NewNotify = (KEYBOARD_CONSOLE_IN_EX_NOTIFY *)AllocateZeroPool (sizeof (KEYBOARD_CONSOLE_IN_EX_NOTIFY)); if (NewNotify == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Exit; @@ -604,8 +616,8 @@ KeyboardRegisterKeyNotify ( CopyMem (&NewNotify->KeyData, KeyData, sizeof (EFI_KEY_DATA)); InsertTailList (&ConsoleInDev->NotifyList, &NewNotify->NotifyEntry); - *NotifyHandle = NewNotify; - Status = EFI_SUCCESS; + *NotifyHandle = NewNotify; + Status = EFI_SUCCESS; Exit: // @@ -613,7 +625,6 @@ Exit: // gBS->RestoreTPL (OldTpl); return Status; - } /** @@ -634,11 +645,11 @@ KeyboardUnregisterKeyNotify ( IN VOID *NotificationHandle ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; - EFI_TPL OldTpl; - LIST_ENTRY *Link; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleInDev; + EFI_TPL OldTpl; + LIST_ENTRY *Link; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; if (NotificationHandle == NULL) { return EFI_INVALID_PARAMETER; @@ -691,19 +702,19 @@ Exit: VOID EFIAPI KeyNotifyProcessHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - EFI_KEY_DATA KeyData; - LIST_ENTRY *Link; - LIST_ENTRY *NotifyList; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; - EFI_TPL OldTpl; + EFI_STATUS Status; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + EFI_KEY_DATA KeyData; + LIST_ENTRY *Link; + LIST_ENTRY *NotifyList; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + EFI_TPL OldTpl; - ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *) Context; + ConsoleIn = (KEYBOARD_CONSOLE_IN_DEV *)Context; // // Invoke notification functions. @@ -722,6 +733,7 @@ KeyNotifyProcessHandler ( if (EFI_ERROR (Status)) { break; } + for (Link = GetFirstNode (NotifyList); !IsNull (NotifyList, Link); Link = GetNextNode (NotifyList, Link)) { CurrentNotify = CR (Link, KEYBOARD_CONSOLE_IN_EX_NOTIFY, NotifyEntry, KEYBOARD_CONSOLE_IN_EX_NOTIFY_SIGNATURE); if (IsKeyRegistered (&CurrentNotify->KeyData, &KeyData)) { @@ -730,4 +742,3 @@ KeyNotifyProcessHandler ( } } } - diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.c b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.c index 855fda742e..a328931f59 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.c +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.c @@ -13,6 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Function prototypes // + /** Test controller is a keyboard Controller. @@ -26,9 +27,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI KbdControllerDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -43,9 +44,9 @@ KbdControllerDriverSupported ( EFI_STATUS EFIAPI KbdControllerDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -65,10 +66,10 @@ KbdControllerDriverStart ( EFI_STATUS EFIAPI KbdControllerDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -81,13 +82,13 @@ KbdControllerDriverStop ( **/ EFI_STATUS KbdFreeNotifyList ( - IN OUT LIST_ENTRY *ListHead + IN OUT LIST_ENTRY *ListHead ); // // DriverBinding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gKeyboardControllerDriver = { +EFI_DRIVER_BINDING_PROTOCOL gKeyboardControllerDriver = { KbdControllerDriverSupported, KbdControllerDriverStart, KbdControllerDriverStop, @@ -109,15 +110,15 @@ EFI_DRIVER_BINDING_PROTOCOL gKeyboardControllerDriver = { EFI_STATUS EFIAPI KbdControllerDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_SIO_PROTOCOL *Sio; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - ACPI_HID_DEVICE_PATH *Acpi; + EFI_STATUS Status; + EFI_SIO_PROTOCOL *Sio; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + ACPI_HID_DEVICE_PATH *Acpi; // // Check whether the controller is keyboard. @@ -125,7 +126,7 @@ KbdControllerDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -135,16 +136,17 @@ KbdControllerDriverSupported ( } do { - Acpi = (ACPI_HID_DEVICE_PATH *) DevicePath; + Acpi = (ACPI_HID_DEVICE_PATH *)DevicePath; DevicePath = NextDevicePathNode (DevicePath); } while (!IsDevicePathEnd (DevicePath)); - if (DevicePathType (Acpi) != ACPI_DEVICE_PATH || - (DevicePathSubType (Acpi) != ACPI_DP && DevicePathSubType (Acpi) != ACPI_EXTENDED_DP)) { + if ((DevicePathType (Acpi) != ACPI_DEVICE_PATH) || + ((DevicePathSubType (Acpi) != ACPI_DP) && (DevicePathSubType (Acpi) != ACPI_EXTENDED_DP))) + { return EFI_UNSUPPORTED; } - if (Acpi->HID != EISA_PNP_ID (0x303) || Acpi->UID != 0) { + if ((Acpi->HID != EISA_PNP_ID (0x303)) || (Acpi->UID != 0)) { return EFI_UNSUPPORTED; } @@ -154,7 +156,7 @@ KbdControllerDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiSioProtocolGuid, - (VOID **) &Sio, + (VOID **)&Sio, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -188,25 +190,25 @@ KbdControllerDriverSupported ( EFI_STATUS EFIAPI KbdControllerDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_STATUS Status1; - EFI_SIO_PROTOCOL *Sio; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - UINT8 Data; - EFI_STATUS_CODE_VALUE StatusCode; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_STATUS Status; + EFI_STATUS Status1; + EFI_SIO_PROTOCOL *Sio; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + UINT8 Data; + EFI_STATUS_CODE_VALUE StatusCode; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; StatusCode = 0; Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,6 +216,7 @@ KbdControllerDriverStart ( if (EFI_ERROR (Status)) { return Status; } + // // Report that the keyboard is being enabled // @@ -229,7 +232,7 @@ KbdControllerDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiSioProtocolGuid, - (VOID **) &Sio, + (VOID **)&Sio, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -237,15 +240,17 @@ KbdControllerDriverStart ( if (EFI_ERROR (Status)) { return Status; } + // // Allocate private data // ConsoleIn = AllocateZeroPool (sizeof (KEYBOARD_CONSOLE_IN_DEV)); if (ConsoleIn == NULL) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } + // // Setup the device instance // @@ -283,8 +288,8 @@ KbdControllerDriverStart ( // If nobody decodes KBC I/O port, it will read back as 0xFF. // Check the Time-Out and Parity bit to see if it has an active KBC in system // - Status = EFI_DEVICE_ERROR; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_NOT_DETECTED; + Status = EFI_DEVICE_ERROR; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_NOT_DETECTED; goto ErrorExit; } } @@ -300,10 +305,11 @@ KbdControllerDriverStart ( &((ConsoleIn->ConIn).WaitForKey) ); if (EFI_ERROR (Status)) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } + // // Setup the WaitForKeyEx event // @@ -315,10 +321,11 @@ KbdControllerDriverStart ( &(ConsoleIn->ConInEx.WaitForKeyEx) ); if (EFI_ERROR (Status)) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } + // Setup a periodic timer, used for reading keystrokes at a fixed interval // Status = gBS->CreateEvent ( @@ -329,8 +336,8 @@ KbdControllerDriverStart ( &ConsoleIn->TimerEvent ); if (EFI_ERROR (Status)) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } @@ -340,8 +347,8 @@ KbdControllerDriverStart ( KEYBOARD_TIMER_INTERVAL ); if (EFI_ERROR (Status)) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } @@ -353,8 +360,8 @@ KbdControllerDriverStart ( &ConsoleIn->KeyNotifyProcessEvent ); if (EFI_ERROR (Status)) { - Status = EFI_OUT_OF_RESOURCES; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; + Status = EFI_OUT_OF_RESOURCES; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_CONTROLLER_ERROR; goto ErrorExit; } @@ -369,8 +376,8 @@ KbdControllerDriverStart ( // Status = ConsoleIn->ConInEx.Reset (&ConsoleIn->ConInEx, FeaturePcdGet (PcdPs2KbdExtendedVerification)); if (EFI_ERROR (Status)) { - Status = EFI_DEVICE_ERROR; - StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_NOT_DETECTED; + Status = EFI_DEVICE_ERROR; + StatusCode = EFI_PERIPHERAL_KEYBOARD | EFI_P_EC_NOT_DETECTED; goto ErrorExit; } @@ -396,7 +403,6 @@ KbdControllerDriverStart ( FALSE ); - // // Install protocol interfaces for the keyboard device. // @@ -434,16 +440,20 @@ ErrorExit: if ((ConsoleIn != NULL) && (ConsoleIn->TimerEvent != NULL)) { gBS->CloseEvent (ConsoleIn->TimerEvent); } + if ((ConsoleIn != NULL) && (ConsoleIn->ConInEx.WaitForKeyEx != NULL)) { gBS->CloseEvent (ConsoleIn->ConInEx.WaitForKeyEx); } + if ((ConsoleIn != NULL) && (ConsoleIn->KeyNotifyProcessEvent != NULL)) { gBS->CloseEvent (ConsoleIn->KeyNotifyProcessEvent); } + KbdFreeNotifyList (&ConsoleIn->NotifyList); if ((ConsoleIn != NULL) && (ConsoleIn->ControllerNameTable != NULL)) { FreeUnicodeStringTable (ConsoleIn->ControllerNameTable); } + // // Since there will be no timer handler for keyboard input any more, // exhaust input data just in case there is still keyboard data left @@ -451,7 +461,7 @@ ErrorExit: if (ConsoleIn != NULL) { Status1 = EFI_SUCCESS; while (!EFI_ERROR (Status1) && (Status != EFI_DEVICE_ERROR)) { - Status1 = KeyboardRead (ConsoleIn, &Data);; + Status1 = KeyboardRead (ConsoleIn, &Data); } } @@ -486,16 +496,16 @@ ErrorExit: EFI_STATUS EFIAPI KbdControllerDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; - KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; - UINT8 Data; + EFI_STATUS Status; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; + KEYBOARD_CONSOLE_IN_DEV *ConsoleIn; + UINT8 Data; // // Disable Keyboard @@ -503,7 +513,7 @@ KbdControllerDriverStop ( Status = gBS->OpenProtocol ( Controller, &gEfiSimpleTextInProtocolGuid, - (VOID **) &ConIn, + (VOID **)&ConIn, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -511,6 +521,7 @@ KbdControllerDriverStop ( if (EFI_ERROR (Status)) { return Status; } + Status = gBS->OpenProtocol ( Controller, &gEfiSimpleTextInputExProtocolGuid, @@ -545,8 +556,9 @@ KbdControllerDriverStop ( // Status = EFI_SUCCESS; while (!EFI_ERROR (Status)) { - Status = KeyboardRead (ConsoleIn, &Data);; + Status = KeyboardRead (ConsoleIn, &Data); } + // // Uninstall the SimpleTextIn and SimpleTextInEx protocols // @@ -576,14 +588,17 @@ KbdControllerDriverStop ( gBS->CloseEvent ((ConsoleIn->ConIn).WaitForKey); (ConsoleIn->ConIn).WaitForKey = NULL; } + if (ConsoleIn->ConInEx.WaitForKeyEx != NULL) { gBS->CloseEvent (ConsoleIn->ConInEx.WaitForKeyEx); ConsoleIn->ConInEx.WaitForKeyEx = NULL; } + if (ConsoleIn->KeyNotifyProcessEvent != NULL) { gBS->CloseEvent (ConsoleIn->KeyNotifyProcessEvent); ConsoleIn->KeyNotifyProcessEvent = NULL; } + KbdFreeNotifyList (&ConsoleIn->NotifyList); FreeUnicodeStringTable (ConsoleIn->ControllerNameTable); gBS->FreePool (ConsoleIn); @@ -601,14 +616,15 @@ KbdControllerDriverStop ( **/ EFI_STATUS KbdFreeNotifyList ( - IN OUT LIST_ENTRY *ListHead + IN OUT LIST_ENTRY *ListHead ) { - KEYBOARD_CONSOLE_IN_EX_NOTIFY *NotifyNode; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *NotifyNode; if (ListHead == NULL) { return EFI_INVALID_PARAMETER; } + while (!IsListEmpty (ListHead)) { NotifyNode = CR ( ListHead->ForwardLink, @@ -635,12 +651,12 @@ KbdFreeNotifyList ( **/ EFI_STATUS EFIAPI -InitializePs2Keyboard( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializePs2Keyboard ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -655,7 +671,5 @@ InitializePs2Keyboard( ); ASSERT_EFI_ERROR (Status); - return Status; } - diff --git a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h index c2762db038..ca1dd9b2c2 100644 --- a/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h +++ b/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h @@ -41,79 +41,79 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gPs2KeyboardComponentName2; // // Driver Private Data // -#define KEYBOARD_CONSOLE_IN_DEV_SIGNATURE SIGNATURE_32 ('k', 'k', 'e', 'y') -#define KEYBOARD_CONSOLE_IN_EX_NOTIFY_SIGNATURE SIGNATURE_32 ('k', 'c', 'e', 'n') +#define KEYBOARD_CONSOLE_IN_DEV_SIGNATURE SIGNATURE_32 ('k', 'k', 'e', 'y') +#define KEYBOARD_CONSOLE_IN_EX_NOTIFY_SIGNATURE SIGNATURE_32 ('k', 'c', 'e', 'n') typedef struct _KEYBOARD_CONSOLE_IN_EX_NOTIFY { - UINTN Signature; - EFI_KEY_DATA KeyData; - EFI_KEY_NOTIFY_FUNCTION KeyNotificationFn; - LIST_ENTRY NotifyEntry; + UINTN Signature; + EFI_KEY_DATA KeyData; + EFI_KEY_NOTIFY_FUNCTION KeyNotificationFn; + LIST_ENTRY NotifyEntry; } KEYBOARD_CONSOLE_IN_EX_NOTIFY; #define KEYBOARD_SCAN_CODE_MAX_COUNT 32 typedef struct { - UINT8 Buffer[KEYBOARD_SCAN_CODE_MAX_COUNT]; - UINTN Head; - UINTN Tail; + UINT8 Buffer[KEYBOARD_SCAN_CODE_MAX_COUNT]; + UINTN Head; + UINTN Tail; } SCAN_CODE_QUEUE; -#define KEYBOARD_EFI_KEY_MAX_COUNT 256 +#define KEYBOARD_EFI_KEY_MAX_COUNT 256 typedef struct { - EFI_KEY_DATA Buffer[KEYBOARD_EFI_KEY_MAX_COUNT]; - UINTN Head; - UINTN Tail; + EFI_KEY_DATA Buffer[KEYBOARD_EFI_KEY_MAX_COUNT]; + UINTN Head; + UINTN Tail; } EFI_KEY_QUEUE; typedef struct { - UINTN Signature; - - EFI_HANDLE Handle; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL ConIn; - EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL ConInEx; - - EFI_EVENT TimerEvent; - - UINT32 DataRegisterAddress; - UINT32 StatusRegisterAddress; - UINT32 CommandRegisterAddress; - - BOOLEAN LeftCtrl; - BOOLEAN RightCtrl; - BOOLEAN LeftAlt; - BOOLEAN RightAlt; - BOOLEAN LeftShift; - BOOLEAN RightShift; - BOOLEAN LeftLogo; - BOOLEAN RightLogo; - BOOLEAN Menu; - BOOLEAN SysReq; - - BOOLEAN CapsLock; - BOOLEAN NumLock; - BOOLEAN ScrollLock; - - BOOLEAN IsSupportPartialKey; + UINTN Signature; + + EFI_HANDLE Handle; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL ConIn; + EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL ConInEx; + + EFI_EVENT TimerEvent; + + UINT32 DataRegisterAddress; + UINT32 StatusRegisterAddress; + UINT32 CommandRegisterAddress; + + BOOLEAN LeftCtrl; + BOOLEAN RightCtrl; + BOOLEAN LeftAlt; + BOOLEAN RightAlt; + BOOLEAN LeftShift; + BOOLEAN RightShift; + BOOLEAN LeftLogo; + BOOLEAN RightLogo; + BOOLEAN Menu; + BOOLEAN SysReq; + + BOOLEAN CapsLock; + BOOLEAN NumLock; + BOOLEAN ScrollLock; + + BOOLEAN IsSupportPartialKey; // // Queue storing key scancodes // - SCAN_CODE_QUEUE ScancodeQueue; - EFI_KEY_QUEUE EfiKeyQueue; - EFI_KEY_QUEUE EfiKeyQueueForNotify; + SCAN_CODE_QUEUE ScancodeQueue; + EFI_KEY_QUEUE EfiKeyQueue; + EFI_KEY_QUEUE EfiKeyQueueForNotify; // // Error state // - BOOLEAN KeyboardErr; + BOOLEAN KeyboardErr; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; // // Notification Function List // - LIST_ENTRY NotifyList; - EFI_EVENT KeyNotifyProcessEvent; + LIST_ENTRY NotifyList; + EFI_EVENT KeyNotifyProcessEvent; } KEYBOARD_CONSOLE_IN_DEV; #define KEYBOARD_CONSOLE_IN_DEV_FROM_THIS(a) CR (a, KEYBOARD_CONSOLE_IN_DEV, ConIn, KEYBOARD_CONSOLE_IN_DEV_SIGNATURE) @@ -124,11 +124,12 @@ typedef struct { KEYBOARD_CONSOLE_IN_DEV_SIGNATURE \ ) -#define TABLE_END 0x0 +#define TABLE_END 0x0 // // Driver entry point // + /** The user Entry Point for module Ps2Keyboard. The user code starts with this function. @@ -142,58 +143,57 @@ typedef struct { EFI_STATUS EFIAPI InstallPs2KeyboardDriver ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); #define KEYBOARD_8042_DATA_REGISTER 0x60 #define KEYBOARD_8042_STATUS_REGISTER 0x64 #define KEYBOARD_8042_COMMAND_REGISTER 0x64 -#define KEYBOARD_KBEN 0xF4 -#define KEYBOARD_CMDECHO_ACK 0xFA - -#define KEYBOARD_MAX_TRY 256 // 256 -#define KEYBOARD_TIMEOUT 65536 // 0.07s -#define KEYBOARD_WAITFORVALUE_TIMEOUT 1000000 // 1s -#define KEYBOARD_BAT_TIMEOUT 4000000 // 4s -#define KEYBOARD_TIMER_INTERVAL 200000 // 0.02s -#define SCANCODE_EXTENDED0 0xE0 -#define SCANCODE_EXTENDED1 0xE1 -#define SCANCODE_CTRL_MAKE 0x1D -#define SCANCODE_CTRL_BREAK 0x9D -#define SCANCODE_ALT_MAKE 0x38 -#define SCANCODE_ALT_BREAK 0xB8 -#define SCANCODE_LEFT_SHIFT_MAKE 0x2A -#define SCANCODE_LEFT_SHIFT_BREAK 0xAA -#define SCANCODE_RIGHT_SHIFT_MAKE 0x36 -#define SCANCODE_RIGHT_SHIFT_BREAK 0xB6 -#define SCANCODE_CAPS_LOCK_MAKE 0x3A -#define SCANCODE_NUM_LOCK_MAKE 0x45 -#define SCANCODE_SCROLL_LOCK_MAKE 0x46 -#define SCANCODE_DELETE_MAKE 0x53 -#define SCANCODE_LEFT_LOGO_MAKE 0x5B //GUI key defined in Keyboard scan code -#define SCANCODE_LEFT_LOGO_BREAK 0xDB -#define SCANCODE_RIGHT_LOGO_MAKE 0x5C -#define SCANCODE_RIGHT_LOGO_BREAK 0xDC -#define SCANCODE_MENU_MAKE 0x5D //APPS key defined in Keyboard scan code -#define SCANCODE_MENU_BREAK 0xDD -#define SCANCODE_SYS_REQ_MAKE 0x37 -#define SCANCODE_SYS_REQ_BREAK 0xB7 -#define SCANCODE_SYS_REQ_MAKE_WITH_ALT 0x54 -#define SCANCODE_SYS_REQ_BREAK_WITH_ALT 0xD4 - -#define SCANCODE_MAX_MAKE 0x60 - - -#define KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA BIT0 ///< 0 - Output register has no data; 1 - Output register has data -#define KEYBOARD_STATUS_REGISTER_HAS_INPUT_DATA BIT1 ///< 0 - Input register has no data; 1 - Input register has data -#define KEYBOARD_STATUS_REGISTER_SYSTEM_FLAG BIT2 ///< Set to 0 after power on reset -#define KEYBOARD_STATUS_REGISTER_INPUT_DATA_TYPE BIT3 ///< 0 - Data in input register is data; 1 - Data in input register is command -#define KEYBOARD_STATUS_REGISTER_ENABLE_FLAG BIT4 ///< 0 - Keyboard is disable; 1 - Keyboard is enable -#define KEYBOARD_STATUS_REGISTER_TRANSMIT_TIMEOUT BIT5 ///< 0 - Transmit is complete without timeout; 1 - Transmit is timeout without complete -#define KEYBOARD_STATUS_REGISTER_RECEIVE_TIMEOUT BIT6 ///< 0 - Receive is complete without timeout; 1 - Receive is timeout without complete -#define KEYBOARD_STATUS_REGISTER_PARITY BIT7 ///< 0 - Odd parity; 1 - Even parity +#define KEYBOARD_KBEN 0xF4 +#define KEYBOARD_CMDECHO_ACK 0xFA + +#define KEYBOARD_MAX_TRY 256 // 256 +#define KEYBOARD_TIMEOUT 65536 // 0.07s +#define KEYBOARD_WAITFORVALUE_TIMEOUT 1000000 // 1s +#define KEYBOARD_BAT_TIMEOUT 4000000 // 4s +#define KEYBOARD_TIMER_INTERVAL 200000 // 0.02s +#define SCANCODE_EXTENDED0 0xE0 +#define SCANCODE_EXTENDED1 0xE1 +#define SCANCODE_CTRL_MAKE 0x1D +#define SCANCODE_CTRL_BREAK 0x9D +#define SCANCODE_ALT_MAKE 0x38 +#define SCANCODE_ALT_BREAK 0xB8 +#define SCANCODE_LEFT_SHIFT_MAKE 0x2A +#define SCANCODE_LEFT_SHIFT_BREAK 0xAA +#define SCANCODE_RIGHT_SHIFT_MAKE 0x36 +#define SCANCODE_RIGHT_SHIFT_BREAK 0xB6 +#define SCANCODE_CAPS_LOCK_MAKE 0x3A +#define SCANCODE_NUM_LOCK_MAKE 0x45 +#define SCANCODE_SCROLL_LOCK_MAKE 0x46 +#define SCANCODE_DELETE_MAKE 0x53 +#define SCANCODE_LEFT_LOGO_MAKE 0x5B// GUI key defined in Keyboard scan code +#define SCANCODE_LEFT_LOGO_BREAK 0xDB +#define SCANCODE_RIGHT_LOGO_MAKE 0x5C +#define SCANCODE_RIGHT_LOGO_BREAK 0xDC +#define SCANCODE_MENU_MAKE 0x5D// APPS key defined in Keyboard scan code +#define SCANCODE_MENU_BREAK 0xDD +#define SCANCODE_SYS_REQ_MAKE 0x37 +#define SCANCODE_SYS_REQ_BREAK 0xB7 +#define SCANCODE_SYS_REQ_MAKE_WITH_ALT 0x54 +#define SCANCODE_SYS_REQ_BREAK_WITH_ALT 0xD4 + +#define SCANCODE_MAX_MAKE 0x60 + +#define KEYBOARD_STATUS_REGISTER_HAS_OUTPUT_DATA BIT0 ///< 0 - Output register has no data; 1 - Output register has data +#define KEYBOARD_STATUS_REGISTER_HAS_INPUT_DATA BIT1 ///< 0 - Input register has no data; 1 - Input register has data +#define KEYBOARD_STATUS_REGISTER_SYSTEM_FLAG BIT2 ///< Set to 0 after power on reset +#define KEYBOARD_STATUS_REGISTER_INPUT_DATA_TYPE BIT3 ///< 0 - Data in input register is data; 1 - Data in input register is command +#define KEYBOARD_STATUS_REGISTER_ENABLE_FLAG BIT4 ///< 0 - Keyboard is disable; 1 - Keyboard is enable +#define KEYBOARD_STATUS_REGISTER_TRANSMIT_TIMEOUT BIT5 ///< 0 - Transmit is complete without timeout; 1 - Transmit is timeout without complete +#define KEYBOARD_STATUS_REGISTER_RECEIVE_TIMEOUT BIT6 ///< 0 - Receive is complete without timeout; 1 - Receive is timeout without complete +#define KEYBOARD_STATUS_REGISTER_PARITY BIT7 ///< 0 - Odd parity; 1 - Even parity #define KEYBOARD_8042_COMMAND_READ 0x20 #define KEYBOARD_8042_COMMAND_WRITE 0x60 @@ -203,14 +203,13 @@ InstallPs2KeyboardDriver ( #define KEYBOARD_8042_COMMAND_KEYBOARD_INTERFACE_SELF_TEST 0xAB #define KEYBOARD_8042_COMMAND_DISABLE_KEYBOARD_INTERFACE 0xAD -#define KEYBOARD_8048_COMMAND_CLEAR_OUTPUT_DATA 0xF4 -#define KEYBOARD_8048_COMMAND_RESET 0xFF -#define KEYBOARD_8048_COMMAND_SELECT_SCAN_CODE_SET 0xF0 - -#define KEYBOARD_8048_RETURN_8042_BAT_SUCCESS 0xAA -#define KEYBOARD_8048_RETURN_8042_BAT_ERROR 0xFC -#define KEYBOARD_8048_RETURN_8042_ACK 0xFA +#define KEYBOARD_8048_COMMAND_CLEAR_OUTPUT_DATA 0xF4 +#define KEYBOARD_8048_COMMAND_RESET 0xFF +#define KEYBOARD_8048_COMMAND_SELECT_SCAN_CODE_SET 0xF0 +#define KEYBOARD_8048_RETURN_8042_BAT_SUCCESS 0xAA +#define KEYBOARD_8048_RETURN_8042_BAT_ERROR 0xFC +#define KEYBOARD_8048_RETURN_8042_ACK 0xFA // // Keyboard Controller Status @@ -221,6 +220,7 @@ InstallPs2KeyboardDriver ( // // Other functions that are used among .c files // + /** Show keyboard status lights according to indicators in ConsoleIn. @@ -232,7 +232,7 @@ InstallPs2KeyboardDriver ( **/ EFI_STATUS UpdateStatusLights ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ); /** @@ -261,7 +261,7 @@ KeyboardRead ( **/ VOID KeyGetchar ( - IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ); /** @@ -273,8 +273,8 @@ KeyGetchar ( VOID EFIAPI KeyNotifyProcessHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -290,11 +290,10 @@ KeyNotifyProcessHandler ( **/ EFI_STATUS InitKeyboard ( - IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - IN BOOLEAN ExtendedVerification + IN OUT KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + IN BOOLEAN ExtendedVerification ); - /** Timer event handler: read a series of scancodes from 8042 and put them into memory scancode buffer. @@ -309,8 +308,8 @@ InitKeyboard ( VOID EFIAPI KeyboardTimerHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -358,8 +357,8 @@ KeyboardReadKeyStroke ( VOID EFIAPI KeyboardWaitForKey ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -372,7 +371,7 @@ KeyboardWaitForKey ( **/ UINT8 KeyReadStatusRegister ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ); /** @@ -388,7 +387,7 @@ KeyReadStatusRegister ( BOOLEAN EFIAPI CheckKeyboardConnect ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn ); /** @@ -402,8 +401,8 @@ CheckKeyboardConnect ( VOID EFIAPI KeyboardWaitForKeyEx ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); // @@ -447,8 +446,8 @@ KeyboardEfiResetEx ( EFI_STATUS EFIAPI KeyboardReadKeyStrokeEx ( - IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, - OUT EFI_KEY_DATA *KeyData + IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, + OUT EFI_KEY_DATA *KeyData ); /** @@ -526,8 +525,8 @@ KeyboardUnregisterKeyNotify ( **/ VOID PushEfikeyBufTail ( - IN EFI_KEY_QUEUE *Queue, - IN EFI_KEY_DATA *KeyData + IN EFI_KEY_QUEUE *Queue, + IN EFI_KEY_DATA *KeyData ); /** @@ -556,8 +555,8 @@ IsKeyRegistered ( **/ VOID InitializeKeyState ( - IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, - OUT EFI_KEY_STATE *KeyState + IN KEYBOARD_CONSOLE_IN_DEV *ConsoleIn, + OUT EFI_KEY_STATE *KeyState ); #endif diff --git a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.c b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.c index d8fed87c16..d31665c25d 100644 --- a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.c +++ b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.c @@ -9,9 +9,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ps2Mouse.h" #include "CommPs2.h" -UINT8 SampleRateTbl[MaxSampleRate] = { 0xa, 0x14, 0x28, 0x3c, 0x50, 0x64, 0xc8 }; +UINT8 SampleRateTbl[MaxSampleRate] = { 0xa, 0x14, 0x28, 0x3c, 0x50, 0x64, 0xc8 }; -UINT8 ResolutionTbl[MaxResolution] = { 0, 1, 2, 3 }; +UINT8 ResolutionTbl[MaxResolution] = { 0, 1, 2, 3 }; /** Issue self test command via IsaIo interface. @@ -34,6 +34,7 @@ KbcSelfTest ( if (EFI_ERROR (Status)) { return Status; } + // // Read return code // @@ -45,6 +46,7 @@ KbcSelfTest ( if (Data != 0x55) { return EFI_DEVICE_ERROR; } + // // Set system flag // @@ -63,7 +65,7 @@ KbcSelfTest ( return Status; } - Data |= CMD_SYS_FLAG; + Data |= CMD_SYS_FLAG; Status = Out8042Data (Data); if (EFI_ERROR (Status)) { return Status; @@ -149,7 +151,7 @@ KbcDisableKb ( **/ EFI_STATUS CheckKbStatus ( - OUT BOOLEAN *KeyboardEnable + OUT BOOLEAN *KeyboardEnable ) { EFI_STATUS Status; @@ -167,6 +169,7 @@ CheckKbStatus ( if (EFI_ERROR (Status)) { return Status; } + // // Check keyboard enable or not // @@ -201,6 +204,7 @@ PS2MouseReset ( if (EFI_ERROR (Status)) { return Status; } + // // Check BAT Complete Code // @@ -212,6 +216,7 @@ PS2MouseReset ( if (EFI_ERROR (Status)) { return Status; } + // // Check BAT Complete Code // @@ -231,7 +236,7 @@ PS2MouseReset ( **/ EFI_STATUS PS2MouseSetSampleRate ( - IN MOUSE_SR SampleRate + IN MOUSE_SR SampleRate ) { EFI_STATUS Status; @@ -258,7 +263,7 @@ PS2MouseSetSampleRate ( **/ EFI_STATUS PS2MouseSetResolution ( - IN MOUSE_RE Resolution + IN MOUSE_RE Resolution ) { EFI_STATUS Status; @@ -285,7 +290,7 @@ PS2MouseSetResolution ( **/ EFI_STATUS PS2MouseSetScaling ( - IN MOUSE_SF Scaling + IN MOUSE_SF Scaling ) { // @@ -321,7 +326,7 @@ PS2MouseEnable ( **/ EFI_STATUS PS2MouseGetPacket ( - PS2_MOUSE_DEV *MouseDev + PS2_MOUSE_DEV *MouseDev ) { @@ -336,111 +341,112 @@ PS2MouseGetPacket ( BOOLEAN LButton; BOOLEAN RButton; - KeyboardEnable = FALSE; - State = PS2_READ_BYTE_ONE; + KeyboardEnable = FALSE; + State = PS2_READ_BYTE_ONE; // // State machine to get mouse packet // while (1) { - switch (State) { - case PS2_READ_BYTE_ONE: - // - // Read mouse first byte data, if failed, immediately return - // - KbcDisableAux (); - Count = 1; - Status = PS2MouseRead (&Data, &Count, State); - if (EFI_ERROR (Status)) { - KbcEnableAux (); - return EFI_NOT_READY; - } - - if (Count != 1) { - KbcEnableAux (); - return EFI_NOT_READY; - } - - if (IS_PS2_SYNC_BYTE (Data)) { - Packet[0] = Data; - State = PS2_READ_DATA_BYTE; - - CheckKbStatus (&KeyboardEnable); - KbcDisableKb (); - KbcEnableAux (); - } - break; + case PS2_READ_BYTE_ONE: + // + // Read mouse first byte data, if failed, immediately return + // + KbcDisableAux (); + Count = 1; + Status = PS2MouseRead (&Data, &Count, State); + if (EFI_ERROR (Status)) { + KbcEnableAux (); + return EFI_NOT_READY; + } - case PS2_READ_DATA_BYTE: - Count = 2; - Status = PS2MouseRead ((Packet + 1), &Count, State); - if (EFI_ERROR (Status)) { - if (KeyboardEnable) { - KbcEnableKb (); + if (Count != 1) { + KbcEnableAux (); + return EFI_NOT_READY; + } + + if (IS_PS2_SYNC_BYTE (Data)) { + Packet[0] = Data; + State = PS2_READ_DATA_BYTE; + + CheckKbStatus (&KeyboardEnable); + KbcDisableKb (); + KbcEnableAux (); + } + + break; + + case PS2_READ_DATA_BYTE: + Count = 2; + Status = PS2MouseRead ((Packet + 1), &Count, State); + if (EFI_ERROR (Status)) { + if (KeyboardEnable) { + KbcEnableKb (); + } + + return EFI_NOT_READY; + } + + if (Count != 2) { + if (KeyboardEnable) { + KbcEnableKb (); + } + + return EFI_NOT_READY; } - return EFI_NOT_READY; - } + State = PS2_PROCESS_PACKET; + break; - if (Count != 2) { + case PS2_PROCESS_PACKET: if (KeyboardEnable) { KbcEnableKb (); } - return EFI_NOT_READY; - } + // + // Decode the packet + // + RelativeMovementX = Packet[1]; + RelativeMovementY = Packet[2]; + // + // Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 + // Byte 0 | Y overflow | X overflow | Y sign bit | X sign bit | Always 1 | Middle Btn | Right Btn | Left Btn + // Byte 1 | 8 bit X Movement + // Byte 2 | 8 bit Y Movement + // + // X sign bit + 8 bit X Movement : 9-bit signed twos complement integer that presents the relative displacement of the device in the X direction since the last data transmission. + // Y sign bit + 8 bit Y Movement : Same as X sign bit + 8 bit X Movement. + // + // + // First, Clear X and Y high 8 bits + // + RelativeMovementX = (INT16)(RelativeMovementX & 0xFF); + RelativeMovementY = (INT16)(RelativeMovementY & 0xFF); + // + // Second, if the 9-bit signed twos complement integer is negative, set the high 8 bit 0xff + // + if ((Packet[0] & 0x10) != 0) { + RelativeMovementX = (INT16)(RelativeMovementX | 0xFF00); + } - State = PS2_PROCESS_PACKET; - break; + if ((Packet[0] & 0x20) != 0) { + RelativeMovementY = (INT16)(RelativeMovementY | 0xFF00); + } + + RButton = (UINT8)(Packet[0] & 0x2); + LButton = (UINT8)(Packet[0] & 0x1); + + // + // Update mouse state + // + MouseDev->State.RelativeMovementX += RelativeMovementX; + MouseDev->State.RelativeMovementY -= RelativeMovementY; + MouseDev->State.RightButton = (UINT8)(RButton ? TRUE : FALSE); + MouseDev->State.LeftButton = (UINT8)(LButton ? TRUE : FALSE); + MouseDev->StateChanged = TRUE; - case PS2_PROCESS_PACKET: - if (KeyboardEnable) { - KbcEnableKb (); - } - // - // Decode the packet - // - RelativeMovementX = Packet[1]; - RelativeMovementY = Packet[2]; - // - // Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 - // Byte 0 | Y overflow | X overflow | Y sign bit | X sign bit | Always 1 | Middle Btn | Right Btn | Left Btn - // Byte 1 | 8 bit X Movement - // Byte 2 | 8 bit Y Movement - // - // X sign bit + 8 bit X Movement : 9-bit signed twos complement integer that presents the relative displacement of the device in the X direction since the last data transmission. - // Y sign bit + 8 bit Y Movement : Same as X sign bit + 8 bit X Movement. - // - // - // First, Clear X and Y high 8 bits - // - RelativeMovementX = (INT16) (RelativeMovementX & 0xFF); - RelativeMovementY = (INT16) (RelativeMovementY & 0xFF); - // - // Second, if the 9-bit signed twos complement integer is negative, set the high 8 bit 0xff - // - if ((Packet[0] & 0x10) != 0) { - RelativeMovementX = (INT16) (RelativeMovementX | 0xFF00); - } - if ((Packet[0] & 0x20) != 0) { - RelativeMovementY = (INT16) (RelativeMovementY | 0xFF00); - } - - - RButton = (UINT8) (Packet[0] & 0x2); - LButton = (UINT8) (Packet[0] & 0x1); - - // - // Update mouse state - // - MouseDev->State.RelativeMovementX += RelativeMovementX; - MouseDev->State.RelativeMovementY -= RelativeMovementY; - MouseDev->State.RightButton = (UINT8) (RButton ? TRUE : FALSE); - MouseDev->State.LeftButton = (UINT8) (LButton ? TRUE : FALSE); - MouseDev->StateChanged = TRUE; - - return EFI_SUCCESS; + return EFI_SUCCESS; } } } @@ -456,15 +462,15 @@ PS2MouseGetPacket ( **/ EFI_STATUS PS2MouseRead ( - OUT UINT8 *Buffer, - IN OUT UINTN *BufSize, - IN UINTN State + OUT UINT8 *Buffer, + IN OUT UINTN *BufSize, + IN UINTN State ) { EFI_STATUS Status; UINTN BytesRead; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; if (State == PS2_READ_BYTE_ONE) { // @@ -478,17 +484,18 @@ PS2MouseRead ( } for (BytesRead = 0; BytesRead < *BufSize; BytesRead++) { - Status = WaitOutputFull (TIMEOUT); if (EFI_ERROR (Status)) { break; } + Buffer[BytesRead] = IoRead8 (KBC_DATA_PORT); } + // // Verify the correct number of bytes read // - if (BytesRead == 0 || BytesRead != *BufSize) { + if ((BytesRead == 0) || (BytesRead != *BufSize)) { Status = EFI_NOT_FOUND; } @@ -499,6 +506,7 @@ PS2MouseRead ( // // 8042 I/O function // + /** I/O work flow of outing 8042 command. @@ -509,7 +517,7 @@ PS2MouseRead ( **/ EFI_STATUS Out8042Command ( - IN UINT8 Command + IN UINT8 Command ) { EFI_STATUS Status; @@ -521,6 +529,7 @@ Out8042Command ( if (EFI_ERROR (Status)) { return Status; } + // // Send command // @@ -544,10 +553,11 @@ Out8042Command ( **/ EFI_STATUS Out8042Data ( - IN UINT8 Data + IN UINT8 Data ) { EFI_STATUS Status; + // // Wait keyboard controller input buffer empty // @@ -570,10 +580,10 @@ Out8042Data ( **/ EFI_STATUS In8042Data ( - IN OUT UINT8 *Data + IN OUT UINT8 *Data ) { - UINTN Delay; + UINTN Delay; Delay = TIMEOUT / 50; @@ -609,8 +619,8 @@ In8042Data ( **/ EFI_STATUS Out8042AuxCommand ( - IN UINT8 Command, - IN BOOLEAN Resend + IN UINT8 Command, + IN BOOLEAN Resend ) { EFI_STATUS Status; @@ -623,6 +633,7 @@ Out8042AuxCommand ( if (EFI_ERROR (Status)) { return Status; } + // // Send write to auxiliary device command // @@ -632,6 +643,7 @@ Out8042AuxCommand ( if (EFI_ERROR (Status)) { return Status; } + // // Send auxiliary device command // @@ -650,13 +662,11 @@ Out8042AuxCommand ( // Receive mouse acknowledge, command send success // return EFI_SUCCESS; - } else if (Resend) { // // Resend fail // return EFI_DEVICE_ERROR; - } else if (Data == PS2_RESEND) { // // Resend command @@ -665,13 +675,11 @@ Out8042AuxCommand ( if (EFI_ERROR (Status)) { return Status; } - } else { // // Invalid return code // return EFI_DEVICE_ERROR; - } return EFI_SUCCESS; @@ -687,10 +695,11 @@ Out8042AuxCommand ( **/ EFI_STATUS Out8042AuxData ( - IN UINT8 Data + IN UINT8 Data ) { EFI_STATUS Status; + // // Wait keyboard controller input buffer empty // @@ -698,6 +707,7 @@ Out8042AuxData ( if (EFI_ERROR (Status)) { return Status; } + // // Send write to auxiliary device command // @@ -728,7 +738,7 @@ Out8042AuxData ( **/ EFI_STATUS In8042AuxData ( - IN OUT UINT8 *Data + IN OUT UINT8 *Data ) { EFI_STATUS Status; @@ -746,7 +756,6 @@ In8042AuxData ( return EFI_SUCCESS; } - /** Check keyboard controller status, if it is output buffer full and for auxiliary device. @@ -758,7 +767,7 @@ CheckForInput ( VOID ) { - UINT8 Data; + UINT8 Data; Data = IoRead8 (KBC_CMD_STS_PORT); @@ -782,11 +791,11 @@ CheckForInput ( **/ EFI_STATUS WaitInputEmpty ( - IN UINTN Timeout + IN UINTN Timeout ) { - UINTN Delay; - UINT8 Data; + UINTN Delay; + UINT8 Data; Delay = Timeout / 50; @@ -821,11 +830,11 @@ WaitInputEmpty ( **/ EFI_STATUS WaitOutputFull ( - IN UINTN Timeout + IN UINTN Timeout ) { - UINTN Delay; - UINT8 Data; + UINTN Delay; + UINT8 Data; Delay = Timeout / 50; diff --git a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.h b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.h index 60da421211..cc4486fbc2 100644 --- a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.h +++ b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/CommPs2.h @@ -11,18 +11,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ps2Mouse.h" -#define PS2_PACKET_LENGTH 3 -#define PS2_SYNC_MASK 0xc -#define PS2_SYNC_BYTE 0x8 +#define PS2_PACKET_LENGTH 3 +#define PS2_SYNC_MASK 0xc +#define PS2_SYNC_BYTE 0x8 #define IS_PS2_SYNC_BYTE(byte) ((byte & PS2_SYNC_MASK) == PS2_SYNC_BYTE) -#define PS2_READ_BYTE_ONE 0 -#define PS2_READ_DATA_BYTE 1 -#define PS2_PROCESS_PACKET 2 +#define PS2_READ_BYTE_ONE 0 +#define PS2_READ_DATA_BYTE 1 +#define PS2_PROCESS_PACKET 2 -#define TIMEOUT 50000 -#define BAT_TIMEOUT 500000 +#define TIMEOUT 50000 +#define BAT_TIMEOUT 500000 // // 8042 I/O Port @@ -42,31 +42,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define ENABLE_KB 0xae #define WRITE_AUX_DEV 0xd4 -#define CMD_SYS_FLAG 0x04 -#define CMD_KB_STS 0x10 -#define CMD_KB_DIS 0x10 -#define CMD_KB_EN 0x0 +#define CMD_SYS_FLAG 0x04 +#define CMD_KB_STS 0x10 +#define CMD_KB_DIS 0x10 +#define CMD_KB_EN 0x0 // // 8042 Auxiliary Device Command // -#define SETSF1_CMD 0xe6 -#define SETSF2_CMD 0xe7 -#define SETRE_CMD 0xe8 -#define READ_CMD 0xeb -#define SETRM_CMD 0xf0 -#define SETSR_CMD 0xf3 -#define ENABLE_CMD 0xf4 -#define DISABLE_CMD 0xf5 -#define RESET_CMD 0xff +#define SETSF1_CMD 0xe6 +#define SETSF2_CMD 0xe7 +#define SETRE_CMD 0xe8 +#define READ_CMD 0xeb +#define SETRM_CMD 0xf0 +#define SETSR_CMD 0xf3 +#define ENABLE_CMD 0xf4 +#define DISABLE_CMD 0xf5 +#define RESET_CMD 0xff // // return code // -#define PS2_ACK 0xfa -#define PS2_RESEND 0xfe -#define PS2MOUSE_BAT1 0xaa -#define PS2MOUSE_BAT2 0x0 +#define PS2_ACK 0xfa +#define PS2_RESEND 0xfe +#define PS2MOUSE_BAT1 0xaa +#define PS2MOUSE_BAT2 0x0 // // Keyboard Controller Status @@ -78,7 +78,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// General Time Out /// -#define KBC_TIM 0x40 +#define KBC_TIM 0x40 /// /// Output buffer for auxiliary device (PS/2): /// 0 - Holds keyboard data @@ -176,7 +176,7 @@ KbcDisableKb ( **/ EFI_STATUS CheckKbStatus ( - OUT BOOLEAN *KeyboardEnable + OUT BOOLEAN *KeyboardEnable ); /** @@ -198,7 +198,7 @@ PS2MouseReset ( **/ EFI_STATUS PS2MouseSetSampleRate ( - IN MOUSE_SR SampleRate + IN MOUSE_SR SampleRate ); /** @@ -210,7 +210,7 @@ PS2MouseSetSampleRate ( **/ EFI_STATUS PS2MouseSetResolution ( - IN MOUSE_RE Resolution + IN MOUSE_RE Resolution ); /** @@ -222,7 +222,7 @@ PS2MouseSetResolution ( **/ EFI_STATUS PS2MouseSetScaling ( - IN MOUSE_SF Scaling + IN MOUSE_SF Scaling ); /** @@ -246,7 +246,7 @@ PS2MouseEnable ( **/ EFI_STATUS PS2MouseGetPacket ( - PS2_MOUSE_DEV *MouseDev + PS2_MOUSE_DEV *MouseDev ); /** @@ -260,14 +260,15 @@ PS2MouseGetPacket ( **/ EFI_STATUS PS2MouseRead ( - OUT UINT8 *Buffer, - IN OUT UINTN *BufSize, - IN UINTN State + OUT UINT8 *Buffer, + IN OUT UINTN *BufSize, + IN UINTN State ); // // 8042 I/O function // + /** I/O work flow of outing 8042 command. @@ -278,7 +279,7 @@ PS2MouseRead ( **/ EFI_STATUS Out8042Command ( - IN UINT8 Command + IN UINT8 Command ); /** @@ -291,7 +292,7 @@ Out8042Command ( **/ EFI_STATUS In8042Data ( - IN OUT UINT8 *Data + IN OUT UINT8 *Data ); /** @@ -304,7 +305,7 @@ In8042Data ( **/ EFI_STATUS Out8042Data ( - IN UINT8 Data + IN UINT8 Data ); /** @@ -318,8 +319,8 @@ Out8042Data ( **/ EFI_STATUS Out8042AuxCommand ( - IN UINT8 Command, - IN BOOLEAN Resend + IN UINT8 Command, + IN BOOLEAN Resend ); /** @@ -332,7 +333,7 @@ Out8042AuxCommand ( **/ EFI_STATUS In8042AuxData ( - IN OUT UINT8 *Data + IN OUT UINT8 *Data ); /** @@ -345,7 +346,7 @@ In8042AuxData ( **/ EFI_STATUS Out8042AuxData ( - IN UINT8 Data + IN UINT8 Data ); /** @@ -369,7 +370,7 @@ CheckForInput ( **/ EFI_STATUS WaitInputEmpty ( - IN UINTN Timeout + IN UINTN Timeout ); /** @@ -382,8 +383,7 @@ WaitInputEmpty ( **/ EFI_STATUS WaitOutputFull ( - IN UINTN Timeout + IN UINTN Timeout ); #endif - diff --git a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/ComponentName.c b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/ComponentName.c index 3dd8efb1dc..94ab267d92 100644 --- a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/ComponentName.c @@ -20,14 +20,13 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gPs2MouseComponentNam // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPs2MouseComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) Ps2MouseComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) Ps2MouseComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPs2MouseComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)Ps2MouseComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)Ps2MouseComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPs2MouseDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPs2MouseDriverNameTable[] = { { "eng;en", L"PS/2 Mouse Driver" @@ -165,16 +164,16 @@ Ps2MouseComponentNameGetDriverName ( EFI_STATUS EFIAPI Ps2MouseComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; - PS2_MOUSE_DEV *MouseDev; + EFI_STATUS Status; + EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; + PS2_MOUSE_DEV *MouseDev; // // This is a device driver, so ChildHandle must be NULL. @@ -182,6 +181,7 @@ Ps2MouseComponentNameGetControllerName ( if (ChildHandle != NULL) { return EFI_UNSUPPORTED; } + // // Check Controller's handle // @@ -190,13 +190,14 @@ Ps2MouseComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, &gEfiSimplePointerProtocolGuid, - (VOID **) &SimplePointerProtocol, + (VOID **)&SimplePointerProtocol, gPS2MouseDriver.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL diff --git a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.c b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.c index ebcb2a43dc..fb61f75e08 100644 --- a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.c +++ b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.c @@ -13,7 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// DriverBinding Protocol Instance /// -EFI_DRIVER_BINDING_PROTOCOL gPS2MouseDriver = { +EFI_DRIVER_BINDING_PROTOCOL gPS2MouseDriver = { PS2MouseDriverSupported, PS2MouseDriverStart, PS2MouseDriverStop, @@ -39,15 +39,15 @@ EFI_DRIVER_BINDING_PROTOCOL gPS2MouseDriver = { EFI_STATUS EFIAPI PS2MouseDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_SIO_PROTOCOL *Sio; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - ACPI_HID_DEVICE_PATH *Acpi; + EFI_STATUS Status; + EFI_SIO_PROTOCOL *Sio; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + ACPI_HID_DEVICE_PATH *Acpi; // // Check whether the controller is keyboard. @@ -55,7 +55,7 @@ PS2MouseDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -65,37 +65,38 @@ PS2MouseDriverSupported ( } do { - Acpi = (ACPI_HID_DEVICE_PATH *) DevicePath; + Acpi = (ACPI_HID_DEVICE_PATH *)DevicePath; DevicePath = NextDevicePathNode (DevicePath); } while (!IsDevicePathEnd (DevicePath)); - if (DevicePathType (Acpi) != ACPI_DEVICE_PATH || - (DevicePathSubType (Acpi) != ACPI_DP && DevicePathSubType (Acpi) != ACPI_EXTENDED_DP)) { + if ((DevicePathType (Acpi) != ACPI_DEVICE_PATH) || + ((DevicePathSubType (Acpi) != ACPI_DP) && (DevicePathSubType (Acpi) != ACPI_EXTENDED_DP))) + { return EFI_UNSUPPORTED; } switch (Acpi->HID) { - case EISA_PNP_ID (0xF03): + case EISA_PNP_ID (0xF03): // // Microsoft PS/2 style mouse // - case EISA_PNP_ID (0xF13): - // - // PS/2 Port for PS/2-style Mice - // - break; - - case EISA_PNP_ID (0x303): - // - // IBM Enhanced (101/102-key, PS/2 mouse support) - // - if (Acpi->UID == 1) { + case EISA_PNP_ID (0xF13): + // + // PS/2 Port for PS/2-style Mice + // break; - } - default: - return EFI_UNSUPPORTED; - break; + case EISA_PNP_ID (0x303): + // + // IBM Enhanced (101/102-key, PS/2 mouse support) + // + if (Acpi->UID == 1) { + break; + } + + default: + return EFI_UNSUPPORTED; + break; } // @@ -104,7 +105,7 @@ PS2MouseDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiSioProtocolGuid, - (VOID **) &Sio, + (VOID **)&Sio, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -143,21 +144,21 @@ PS2MouseDriverSupported ( EFI_STATUS EFIAPI PS2MouseDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_STATUS EmptyStatus; - EFI_SIO_PROTOCOL *Sio; - PS2_MOUSE_DEV *MouseDev; - UINT8 Data; - EFI_TPL OldTpl; - EFI_STATUS_CODE_VALUE StatusCode; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_STATUS Status; + EFI_STATUS EmptyStatus; + EFI_SIO_PROTOCOL *Sio; + PS2_MOUSE_DEV *MouseDev; + UINT8 Data; + EFI_TPL OldTpl; + EFI_STATUS_CODE_VALUE StatusCode; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; - StatusCode = 0; + StatusCode = 0; // // Open the device path protocol @@ -165,7 +166,7 @@ PS2MouseDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -173,6 +174,7 @@ PS2MouseDriverStart ( if (EFI_ERROR (Status)) { return Status; } + // // Report that the keyboard is being enabled // @@ -188,7 +190,7 @@ PS2MouseDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiSioProtocolGuid, - (VOID **) &Sio, + (VOID **)&Sio, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -196,6 +198,7 @@ PS2MouseDriverStart ( if (EFI_ERROR (Status)) { return Status; } + // // Raise TPL to avoid keyboard operation impact // @@ -209,6 +212,7 @@ PS2MouseDriverStart ( Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } + // // Setup the device instance // @@ -223,14 +227,14 @@ PS2MouseDriverStart ( // // Resolution = 4 counts/mm // - MouseDev->Mode.ResolutionX = 4; - MouseDev->Mode.ResolutionY = 4; - MouseDev->Mode.LeftButton = TRUE; - MouseDev->Mode.RightButton = TRUE; + MouseDev->Mode.ResolutionX = 4; + MouseDev->Mode.ResolutionY = 4; + MouseDev->Mode.LeftButton = TRUE; + MouseDev->Mode.RightButton = TRUE; - MouseDev->SimplePointerProtocol.Reset = MouseReset; - MouseDev->SimplePointerProtocol.GetState = MouseGetState; - MouseDev->SimplePointerProtocol.Mode = &(MouseDev->Mode); + MouseDev->SimplePointerProtocol.Reset = MouseReset; + MouseDev->SimplePointerProtocol.GetState = MouseGetState; + MouseDev->SimplePointerProtocol.Mode = &(MouseDev->Mode); // // Initialize keyboard controller if necessary @@ -275,15 +279,15 @@ PS2MouseDriverStart ( // Reset the mouse // Status = MouseDev->SimplePointerProtocol.Reset ( - &MouseDev->SimplePointerProtocol, - FeaturePcdGet (PcdPs2MouseExtendedVerification) - ); + &MouseDev->SimplePointerProtocol, + FeaturePcdGet (PcdPs2MouseExtendedVerification) + ); if (EFI_ERROR (Status)) { // // mouse not connected // - Status = EFI_SUCCESS; - StatusCode = EFI_PERIPHERAL_MOUSE | EFI_P_EC_NOT_DETECTED; + Status = EFI_SUCCESS; + StatusCode = EFI_PERIPHERAL_MOUSE | EFI_P_EC_NOT_DETECTED; goto ErrorExit; } @@ -307,6 +311,7 @@ PS2MouseDriverStart ( Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } + // // Setup a periodic timer, used to poll mouse state // @@ -321,6 +326,7 @@ PS2MouseDriverStart ( Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } + // // Start timer to poll mouse (100 samples per second) // @@ -346,7 +352,6 @@ PS2MouseDriverStart ( FALSE ); - // // Install protocol interfaces for the mouse device. // @@ -441,21 +446,21 @@ ErrorExit: EFI_STATUS EFIAPI PS2MouseDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; - PS2_MOUSE_DEV *MouseDev; - UINT8 Data; + EFI_STATUS Status; + EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; + PS2_MOUSE_DEV *MouseDev; + UINT8 Data; Status = gBS->OpenProtocol ( Controller, &gEfiSimplePointerProtocolGuid, - (VOID **) &SimplePointerProtocol, + (VOID **)&SimplePointerProtocol, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -535,15 +540,15 @@ PS2MouseDriverStop ( EFI_STATUS EFIAPI MouseReset ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - PS2_MOUSE_DEV *MouseDev; - EFI_TPL OldTpl; - BOOLEAN KeyboardEnable; - UINT8 Data; + EFI_STATUS Status; + PS2_MOUSE_DEV *MouseDev; + EFI_TPL OldTpl; + BOOLEAN KeyboardEnable; + UINT8 Data; MouseDev = PS2_MOUSE_DEV_FROM_THIS (This); @@ -625,6 +630,7 @@ MouseReset ( goto Exit; } } + Exit: gBS->RestoreTPL (OldTpl); @@ -646,11 +652,11 @@ Exit: **/ BOOLEAN CheckMouseConnect ( - IN PS2_MOUSE_DEV *MouseDev + IN PS2_MOUSE_DEV *MouseDev ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = PS2MouseEnable (); if (!EFI_ERROR (Status)) { @@ -673,12 +679,12 @@ CheckMouseConnect ( EFI_STATUS EFIAPI MouseGetState ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN OUT EFI_SIMPLE_POINTER_STATE *State + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN OUT EFI_SIMPLE_POINTER_STATE *State ) { - PS2_MOUSE_DEV *MouseDev; - EFI_TPL OldTpl; + PS2_MOUSE_DEV *MouseDev; + EFI_TPL OldTpl; MouseDev = PS2_MOUSE_DEV_FROM_THIS (This); @@ -717,13 +723,13 @@ MouseGetState ( VOID EFIAPI MouseWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - PS2_MOUSE_DEV *MouseDev; + PS2_MOUSE_DEV *MouseDev; - MouseDev = (PS2_MOUSE_DEV *) Context; + MouseDev = (PS2_MOUSE_DEV *)Context; // // Someone is waiting on the mouse event, if there's @@ -732,7 +738,6 @@ MouseWaitForInput ( if (MouseDev->StateChanged) { gBS->SignalEvent (Event); } - } /** @@ -751,9 +756,9 @@ PollMouse ( ) { - PS2_MOUSE_DEV *MouseDev; + PS2_MOUSE_DEV *MouseDev; - MouseDev = (PS2_MOUSE_DEV *) Context; + MouseDev = (PS2_MOUSE_DEV *)Context; // // Polling mouse packet data @@ -773,12 +778,12 @@ PollMouse ( **/ EFI_STATUS EFIAPI -InitializePs2Mouse( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializePs2Mouse ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -793,7 +798,5 @@ InitializePs2Mouse( ); ASSERT_EFI_ERROR (Status); - return Status; } - diff --git a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.h b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.h index 1f7c310ad1..968cb47e82 100644 --- a/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.h +++ b/MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2Mouse.h @@ -69,29 +69,29 @@ typedef enum { // // Driver Private Data // -#define PS2_MOUSE_DEV_SIGNATURE SIGNATURE_32 ('p', 's', '2', 'm') +#define PS2_MOUSE_DEV_SIGNATURE SIGNATURE_32 ('p', 's', '2', 'm') typedef struct { - UINTN Signature; + UINTN Signature; - EFI_HANDLE Handle; - EFI_SIMPLE_POINTER_PROTOCOL SimplePointerProtocol; - EFI_SIMPLE_POINTER_STATE State; - EFI_SIMPLE_POINTER_MODE Mode; - BOOLEAN StateChanged; + EFI_HANDLE Handle; + EFI_SIMPLE_POINTER_PROTOCOL SimplePointerProtocol; + EFI_SIMPLE_POINTER_STATE State; + EFI_SIMPLE_POINTER_MODE Mode; + BOOLEAN StateChanged; // // PS2 Mouse device specific information // - MOUSE_SR SampleRate; - MOUSE_RE Resolution; - MOUSE_SF Scaling; - UINT8 DataPackageSize; + MOUSE_SR SampleRate; + MOUSE_RE Resolution; + MOUSE_SF Scaling; + UINT8 DataPackageSize; - EFI_EVENT TimerEvent; + EFI_EVENT TimerEvent; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } PS2_MOUSE_DEV; #define PS2_MOUSE_DEV_FROM_THIS(a) CR (a, PS2_MOUSE_DEV, SimplePointerProtocol, PS2_MOUSE_DEV_SIGNATURE) @@ -99,6 +99,7 @@ typedef struct { // // Function prototypes // + /** Test to see if this driver supports ControllerHandle. Any ControllerHandle than contains a IsaIo protocol can be supported. @@ -116,9 +117,9 @@ typedef struct { EFI_STATUS EFIAPI PS2MouseDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -139,9 +140,9 @@ PS2MouseDriverSupported ( EFI_STATUS EFIAPI PS2MouseDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -161,15 +162,16 @@ PS2MouseDriverStart ( EFI_STATUS EFIAPI PS2MouseDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -217,7 +219,6 @@ Ps2MouseComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -289,11 +290,11 @@ Ps2MouseComponentNameGetDriverName ( EFI_STATUS EFIAPI Ps2MouseComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -311,8 +312,8 @@ Ps2MouseComponentNameGetControllerName ( EFI_STATUS EFIAPI MouseReset ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -328,8 +329,8 @@ MouseReset ( EFI_STATUS EFIAPI MouseGetState ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN OUT EFI_SIMPLE_POINTER_STATE *State + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN OUT EFI_SIMPLE_POINTER_STATE *State ); /** @@ -344,8 +345,8 @@ MouseGetState ( VOID EFIAPI MouseWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -373,7 +374,7 @@ PollMouse ( **/ EFI_STATUS In8042Data ( - IN OUT UINT8 *Data + IN OUT UINT8 *Data ); /** @@ -387,7 +388,7 @@ In8042Data ( **/ BOOLEAN CheckMouseConnect ( - IN PS2_MOUSE_DEV *MouseDev + IN PS2_MOUSE_DEV *MouseDev ); #endif diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.c index a2132d072b..ee83af2789 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ehci.h" - // // EFI Component Name Protocol // @@ -22,19 +21,17 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gEhciComponentName = // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gEhciComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) EhciComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) EhciComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gEhciComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)EhciComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)EhciComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEhciDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEhciDriverNameTable[] = { { "eng;en", L"Usb Ehci Driver" }, - { NULL , NULL } + { NULL, NULL } }; - /** Retrieves a Unicode string that is the user readable name of the driver. @@ -162,16 +159,16 @@ EhciComponentNameGetDriverName ( EFI_STATUS EFIAPI EhciComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - USB2_HC_DEV *EhciDev; - EFI_USB2_HC_PROTOCOL *Usb2Hc; + EFI_STATUS Status; + USB2_HC_DEV *EhciDev; + EFI_USB2_HC_PROTOCOL *Usb2Hc; // // This is a device driver, so ChildHandle must be NULL. @@ -179,6 +176,7 @@ EhciComponentNameGetControllerName ( if (ChildHandle != NULL) { return EFI_UNSUPPORTED; } + // // Make sure this driver is currently managing ControllerHandle // @@ -190,13 +188,14 @@ EhciComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, gEhciDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,5 +213,4 @@ EhciComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gEhciComponentName) ); - } diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.h b/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.h index 739592a6f6..d67cbf0709 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/ComponentName.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _COMPONENT_NAME_H_ #define _COMPONENT_NAME_H_ - /** Retrieves a Unicode string that is the user readable name of the driver. @@ -58,7 +57,6 @@ EhciComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -130,12 +128,11 @@ EhciComponentNameGetDriverName ( EFI_STATUS EFIAPI EhciComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); #endif - diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c index 0e41ee17ec..0b7270f4e9 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.c @@ -16,7 +16,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Ehci.h" // @@ -24,23 +23,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // to the UEFI protocol's port state (change). // USB_PORT_STATE_MAP mUsbPortStateMap[] = { - {PORTSC_CONN, USB_PORT_STAT_CONNECTION}, - {PORTSC_ENABLED, USB_PORT_STAT_ENABLE}, - {PORTSC_SUSPEND, USB_PORT_STAT_SUSPEND}, - {PORTSC_OVERCUR, USB_PORT_STAT_OVERCURRENT}, - {PORTSC_RESET, USB_PORT_STAT_RESET}, - {PORTSC_POWER, USB_PORT_STAT_POWER}, - {PORTSC_OWNER, USB_PORT_STAT_OWNER} + { PORTSC_CONN, USB_PORT_STAT_CONNECTION }, + { PORTSC_ENABLED, USB_PORT_STAT_ENABLE }, + { PORTSC_SUSPEND, USB_PORT_STAT_SUSPEND }, + { PORTSC_OVERCUR, USB_PORT_STAT_OVERCURRENT }, + { PORTSC_RESET, USB_PORT_STAT_RESET }, + { PORTSC_POWER, USB_PORT_STAT_POWER }, + { PORTSC_OWNER, USB_PORT_STAT_OWNER } }; USB_PORT_STATE_MAP mUsbPortChangeMap[] = { - {PORTSC_CONN_CHANGE, USB_PORT_STAT_C_CONNECTION}, - {PORTSC_ENABLE_CHANGE, USB_PORT_STAT_C_ENABLE}, - {PORTSC_OVERCUR_CHANGE, USB_PORT_STAT_C_OVERCURRENT} + { PORTSC_CONN_CHANGE, USB_PORT_STAT_C_CONNECTION }, + { PORTSC_ENABLE_CHANGE, USB_PORT_STAT_C_ENABLE }, + { PORTSC_OVERCUR_CHANGE, USB_PORT_STAT_C_OVERCURRENT } }; EFI_DRIVER_BINDING_PROTOCOL -gEhciDriverBinding = { + gEhciDriverBinding = { EhcDriverBindingSupported, EhcDriverBindingStart, EhcDriverBindingStop, @@ -71,19 +70,19 @@ EhcGetCapability ( OUT UINT8 *Is64BitCapable ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; if ((MaxSpeed == NULL) || (PortNumber == NULL) || (Is64BitCapable == NULL)) { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); *MaxSpeed = EFI_USB_SPEED_HIGH; - *PortNumber = (UINT8) (Ehc->HcStructParams & HCSP_NPORTS); - *Is64BitCapable = (UINT8) Ehc->Support64BitDma; + *PortNumber = (UINT8)(Ehc->HcStructParams & HCSP_NPORTS); + *Is64BitCapable = (UINT8)Ehc->Support64BitDma; DEBUG ((DEBUG_INFO, "EhcGetCapability: %d ports, 64 bit %d\n", *PortNumber, *Is64BitCapable)); @@ -91,7 +90,6 @@ EhcGetCapability ( return EFI_SUCCESS; } - /** Provides software reset for the USB host controller. @@ -108,13 +106,13 @@ EhcGetCapability ( EFI_STATUS EFIAPI EhcReset ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT16 Attributes + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT16 Attributes ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + EFI_STATUS Status; Ehc = EHC_FROM_THIS (This); @@ -129,55 +127,55 @@ EhcReset ( ); } - OldTpl = gBS->RaiseTPL (EHC_TPL); + OldTpl = gBS->RaiseTPL (EHC_TPL); switch (Attributes) { - case EFI_USB_HC_RESET_GLOBAL: - // - // Flow through, same behavior as Host Controller Reset - // - case EFI_USB_HC_RESET_HOST_CONTROLLER: + case EFI_USB_HC_RESET_GLOBAL: // - // Host Controller must be Halt when Reset it + // Flow through, same behavior as Host Controller Reset // - if (EhcIsDebugPortInUse (Ehc, NULL)) { - Status = EFI_SUCCESS; - goto ON_EXIT; - } + case EFI_USB_HC_RESET_HOST_CONTROLLER: + // + // Host Controller must be Halt when Reset it + // + if (EhcIsDebugPortInUse (Ehc, NULL)) { + Status = EFI_SUCCESS; + goto ON_EXIT; + } - if (!EhcIsHalt (Ehc)) { - Status = EhcHaltHC (Ehc, EHC_GENERIC_TIMEOUT); + if (!EhcIsHalt (Ehc)) { + Status = EhcHaltHC (Ehc, EHC_GENERIC_TIMEOUT); - if (EFI_ERROR (Status)) { - Status = EFI_DEVICE_ERROR; - goto ON_EXIT; + if (EFI_ERROR (Status)) { + Status = EFI_DEVICE_ERROR; + goto ON_EXIT; + } } - } - // - // Clean up the asynchronous transfers, currently only - // interrupt supports asynchronous operation. - // - EhciDelAllAsyncIntTransfers (Ehc); - EhcAckAllInterrupt (Ehc); - EhcFreeSched (Ehc); + // + // Clean up the asynchronous transfers, currently only + // interrupt supports asynchronous operation. + // + EhciDelAllAsyncIntTransfers (Ehc); + EhcAckAllInterrupt (Ehc); + EhcFreeSched (Ehc); - Status = EhcResetHC (Ehc, EHC_RESET_TIMEOUT); + Status = EhcResetHC (Ehc, EHC_RESET_TIMEOUT); - if (EFI_ERROR (Status)) { - goto ON_EXIT; - } + if (EFI_ERROR (Status)) { + goto ON_EXIT; + } - Status = EhcInitHC (Ehc); - break; + Status = EhcInitHC (Ehc); + break; - case EFI_USB_HC_RESET_GLOBAL_WITH_DEBUG: - case EFI_USB_HC_RESET_HOST_WITH_DEBUG: - Status = EFI_UNSUPPORTED; - break; + case EFI_USB_HC_RESET_GLOBAL_WITH_DEBUG: + case EFI_USB_HC_RESET_HOST_WITH_DEBUG: + Status = EFI_UNSUPPORTED; + break; - default: - Status = EFI_INVALID_PARAMETER; + default: + Status = EFI_INVALID_PARAMETER; } ON_EXIT: @@ -186,7 +184,6 @@ ON_EXIT: return Status; } - /** Retrieve the current state of the USB host controller. @@ -207,15 +204,15 @@ EhcGetState ( OUT EFI_USB_HC_STATE *State ) { - EFI_TPL OldTpl; - USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + USB2_HC_DEV *Ehc; if (State == NULL) { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); if (EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT)) { *State = EfiUsbHcStateHalt; @@ -229,7 +226,6 @@ EhcGetState ( return EFI_SUCCESS; } - /** Sets the USB host controller to a specific state. @@ -245,14 +241,14 @@ EhcGetState ( EFI_STATUS EFIAPI EhcSetState ( - IN EFI_USB2_HC_PROTOCOL *This, - IN EFI_USB_HC_STATE State + IN EFI_USB2_HC_PROTOCOL *This, + IN EFI_USB_HC_STATE State ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - EFI_STATUS Status; - EFI_USB_HC_STATE CurState; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_USB_HC_STATE CurState; Status = EhcGetState (This, &CurState); @@ -264,39 +260,39 @@ EhcSetState ( return EFI_SUCCESS; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); switch (State) { - case EfiUsbHcStateHalt: - Status = EhcHaltHC (Ehc, EHC_GENERIC_TIMEOUT); - break; - - case EfiUsbHcStateOperational: - if (EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_SYS_ERROR)) { - Status = EFI_DEVICE_ERROR; + case EfiUsbHcStateHalt: + Status = EhcHaltHC (Ehc, EHC_GENERIC_TIMEOUT); break; - } - // - // Software must not write a one to this field unless the host controller - // is in the Halted state. Doing so will yield undefined results. - // refers to Spec[EHCI1.0-2.3.1] - // - if (!EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT)) { - Status = EFI_DEVICE_ERROR; - break; - } + case EfiUsbHcStateOperational: + if (EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_SYS_ERROR)) { + Status = EFI_DEVICE_ERROR; + break; + } - Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); - break; + // + // Software must not write a one to this field unless the host controller + // is in the Halted state. Doing so will yield undefined results. + // refers to Spec[EHCI1.0-2.3.1] + // + if (!EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT)) { + Status = EFI_DEVICE_ERROR; + break; + } - case EfiUsbHcStateSuspend: - Status = EFI_UNSUPPORTED; - break; + Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); + break; - default: - Status = EFI_INVALID_PARAMETER; + case EfiUsbHcStateSuspend: + Status = EFI_UNSUPPORTED; + break; + + default: + Status = EFI_INVALID_PARAMETER; } DEBUG ((DEBUG_INFO, "EhcSetState: exit status %r\n", Status)); @@ -304,7 +300,6 @@ EhcSetState ( return Status; } - /** Retrieves the current status of a USB root hub port. @@ -327,23 +322,23 @@ EhcGetRootHubPortStatus ( OUT EFI_USB_PORT_STATUS *PortStatus ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - UINTN Index; - UINTN MapSize; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + UINTN Index; + UINTN MapSize; + EFI_STATUS Status; if (PortStatus == NULL) { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); + OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); - Status = EFI_SUCCESS; + Ehc = EHC_FROM_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -352,15 +347,15 @@ EhcGetRootHubPortStatus ( goto ON_EXIT; } - Offset = (UINT32) (EHC_PORT_STAT_OFFSET + (4 * PortNumber)); - PortStatus->PortStatus = 0; - PortStatus->PortChangeStatus = 0; + Offset = (UINT32)(EHC_PORT_STAT_OFFSET + (4 * PortNumber)); + PortStatus->PortStatus = 0; + PortStatus->PortChangeStatus = 0; if (EhcIsDebugPortInUse (Ehc, &PortNumber)) { goto ON_EXIT; } - State = EhcReadOpReg (Ehc, Offset); + State = EhcReadOpReg (Ehc, Offset); // // Identify device speed. If in K state, it is low speed. @@ -370,7 +365,6 @@ EhcGetRootHubPortStatus ( // if (EHC_BIT_IS_SET (State, PORTSC_LINESTATE_K)) { PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; - } else if (EHC_BIT_IS_SET (State, PORTSC_ENABLED)) { PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; } @@ -382,7 +376,7 @@ EhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (EHC_BIT_IS_SET (State, mUsbPortStateMap[Index].HwState)) { - PortStatus->PortStatus = (UINT16) (PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); + PortStatus->PortStatus = (UINT16)(PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); } } @@ -390,7 +384,7 @@ EhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (EHC_BIT_IS_SET (State, mUsbPortChangeMap[Index].HwState)) { - PortStatus->PortChangeStatus = (UINT16) (PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); + PortStatus->PortChangeStatus = (UINT16)(PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); } } @@ -399,7 +393,6 @@ ON_EXIT: return Status; } - /** Sets a feature for the specified root hub port. @@ -420,16 +413,16 @@ EhcSetRootHubPortFeature ( IN EFI_USB_PORT_FEATURE PortFeature ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; - - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); - Status = EFI_SUCCESS; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; + + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -438,8 +431,8 @@ EhcSetRootHubPortFeature ( goto ON_EXIT; } - Offset = (UINT32) (EHC_PORT_STAT_OFFSET + (4 * PortNumber)); - State = EhcReadOpReg (Ehc, Offset); + Offset = (UINT32)(EHC_PORT_STAT_OFFSET + (4 * PortNumber)); + State = EhcReadOpReg (Ehc, Offset); // // Mask off the port status change bits, these bits are @@ -448,58 +441,59 @@ EhcSetRootHubPortFeature ( State &= ~PORTSC_CHANGE_MASK; switch (PortFeature) { - case EfiUsbPortEnable: - // - // Sofeware can't set this bit, Port can only be enable by - // EHCI as a part of the reset and enable - // - State |= PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnable: + // + // Sofeware can't set this bit, Port can only be enable by + // EHCI as a part of the reset and enable + // + State |= PORTSC_ENABLED; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortSuspend: - State |= PORTSC_SUSPEND; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortSuspend: + State |= PORTSC_SUSPEND; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortReset: - // - // Make sure Host Controller not halt before reset it - // - if (EhcIsHalt (Ehc)) { - Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); + case EfiUsbPortReset: + // + // Make sure Host Controller not halt before reset it + // + if (EhcIsHalt (Ehc)) { + Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "EhcSetRootHubPortFeature :failed to start HC - %r\n", Status)); - break; + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_INFO, "EhcSetRootHubPortFeature :failed to start HC - %r\n", Status)); + break; + } } - } - - // - // Set one to PortReset bit must also set zero to PortEnable bit - // - State |= PORTSC_RESET; - State &= ~PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; - case EfiUsbPortPower: - // - // Set port power bit when PPC is 1 - // - if ((Ehc->HcCapParams & HCSP_PPC) == HCSP_PPC) { - State |= PORTSC_POWER; + // + // Set one to PortReset bit must also set zero to PortEnable bit + // + State |= PORTSC_RESET; + State &= ~PORTSC_ENABLED; EhcWriteOpReg (Ehc, Offset, State); - } - break; + break; - case EfiUsbPortOwner: - State |= PORTSC_OWNER; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortPower: + // + // Set port power bit when PPC is 1 + // + if ((Ehc->HcCapParams & HCSP_PPC) == HCSP_PPC) { + State |= PORTSC_POWER; + EhcWriteOpReg (Ehc, Offset, State); + } - default: - Status = EFI_INVALID_PARAMETER; + break; + + case EfiUsbPortOwner: + State |= PORTSC_OWNER; + EhcWriteOpReg (Ehc, Offset, State); + break; + + default: + Status = EFI_INVALID_PARAMETER; } ON_EXIT: @@ -509,7 +503,6 @@ ON_EXIT: return Status; } - /** Clears a feature for the specified root hub port. @@ -533,16 +526,16 @@ EhcClearRootHubPortFeature ( IN EFI_USB_PORT_FEATURE PortFeature ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; - - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); - Status = EFI_SUCCESS; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; + + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -551,90 +544,91 @@ EhcClearRootHubPortFeature ( goto ON_EXIT; } - Offset = EHC_PORT_STAT_OFFSET + (4 * PortNumber); - State = EhcReadOpReg (Ehc, Offset); + Offset = EHC_PORT_STAT_OFFSET + (4 * PortNumber); + State = EhcReadOpReg (Ehc, Offset); State &= ~PORTSC_CHANGE_MASK; switch (PortFeature) { - case EfiUsbPortEnable: - // - // Clear PORT_ENABLE feature means disable port. - // - State &= ~PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; - - case EfiUsbPortSuspend: - // - // A write of zero to this bit is ignored by the host - // controller. The host controller will unconditionally - // set this bit to a zero when: - // 1. software sets the Forct Port Resume bit to a zero from a one. - // 2. software sets the Port Reset bit to a one frome a zero. - // - State &= ~PORSTSC_RESUME; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnable: + // + // Clear PORT_ENABLE feature means disable port. + // + State &= ~PORTSC_ENABLED; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortReset: - // - // Clear PORT_RESET means clear the reset signal. - // - State &= ~PORTSC_RESET; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortSuspend: + // + // A write of zero to this bit is ignored by the host + // controller. The host controller will unconditionally + // set this bit to a zero when: + // 1. software sets the Forct Port Resume bit to a zero from a one. + // 2. software sets the Port Reset bit to a one frome a zero. + // + State &= ~PORSTSC_RESUME; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortOwner: - // - // Clear port owner means this port owned by EHC - // - State &= ~PORTSC_OWNER; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortReset: + // + // Clear PORT_RESET means clear the reset signal. + // + State &= ~PORTSC_RESET; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortConnectChange: - // - // Clear connect status change - // - State |= PORTSC_CONN_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortOwner: + // + // Clear port owner means this port owned by EHC + // + State &= ~PORTSC_OWNER; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortEnableChange: - // - // Clear enable status change - // - State |= PORTSC_ENABLE_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortConnectChange: + // + // Clear connect status change + // + State |= PORTSC_CONN_CHANGE; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortOverCurrentChange: - // - // Clear PortOverCurrent change - // - State |= PORTSC_OVERCUR_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnableChange: + // + // Clear enable status change + // + State |= PORTSC_ENABLE_CHANGE; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortPower: - // - // Clear port power bit when PPC is 1 - // - if ((Ehc->HcCapParams & HCSP_PPC) == HCSP_PPC) { - State &= ~PORTSC_POWER; + case EfiUsbPortOverCurrentChange: + // + // Clear PortOverCurrent change + // + State |= PORTSC_OVERCUR_CHANGE; EhcWriteOpReg (Ehc, Offset, State); - } - break; - case EfiUsbPortSuspendChange: - case EfiUsbPortResetChange: - // - // Not supported or not related operation - // - break; + break; - default: - Status = EFI_INVALID_PARAMETER; - break; + case EfiUsbPortPower: + // + // Clear port power bit when PPC is 1 + // + if ((Ehc->HcCapParams & HCSP_PPC) == HCSP_PPC) { + State &= ~PORTSC_POWER; + EhcWriteOpReg (Ehc, Offset, State); + } + + break; + case EfiUsbPortSuspendChange: + case EfiUsbPortResetChange: + // + // Not supported or not related operation + // + break; + + default: + Status = EFI_INVALID_PARAMETER; + break; } ON_EXIT: @@ -643,7 +637,6 @@ ON_EXIT: return Status; } - /** Submits control transfer to a target USB device. @@ -684,11 +677,11 @@ EhcControlTransfer ( OUT UINT32 *TransferResult ) { - USB2_HC_DEV *Ehc; - URB *Urb; - EFI_TPL OldTpl; - UINT8 Endpoint; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + URB *Urb; + EFI_TPL OldTpl; + UINT8 Endpoint; + EFI_STATUS Status; // // Validate parameters @@ -699,22 +692,26 @@ EhcControlTransfer ( if ((TransferDirection != EfiUsbDataIn) && (TransferDirection != EfiUsbDataOut) && - (TransferDirection != EfiUsbNoData)) { + (TransferDirection != EfiUsbNoData)) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection == EfiUsbNoData) && - ((Data != NULL) || (*DataLength != 0))) { + ((Data != NULL) || (*DataLength != 0))) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection != EfiUsbNoData) && - ((Data == NULL) || (*DataLength == 0))) { + ((Data == NULL) || (*DataLength == 0))) + { return EFI_INVALID_PARAMETER; } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && - (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) { + (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) + { return EFI_INVALID_PARAMETER; } @@ -722,8 +719,8 @@ EhcControlTransfer ( return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); Status = EFI_DEVICE_ERROR; *TransferResult = EFI_USB_ERR_SYSTEM; @@ -746,23 +743,23 @@ EhcControlTransfer ( // endpoint is bidirectional. EhcCreateUrb expects this // combination of Ep addr and its direction. // - Endpoint = (UINT8) (0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); - Urb = EhcCreateUrb ( - Ehc, - DeviceAddress, - Endpoint, - DeviceSpeed, - 0, - MaximumPacketLength, - Translator, - EHC_CTRL_TRANSFER, - Request, - Data, - *DataLength, - NULL, - NULL, - 1 - ); + Endpoint = (UINT8)(0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); + Urb = EhcCreateUrb ( + Ehc, + DeviceAddress, + Endpoint, + DeviceSpeed, + 0, + MaximumPacketLength, + Translator, + EHC_CTRL_TRANSFER, + Request, + Data, + *DataLength, + NULL, + NULL, + 1 + ); if (Urb == NULL) { DEBUG ((DEBUG_ERROR, "EhcControlTransfer: failed to create URB")); @@ -800,7 +797,6 @@ ON_EXIT: return Status; } - /** Submits bulk transfer to a bulk endpoint of a USB device. @@ -848,16 +844,17 @@ EhcBulkTransfer ( OUT UINT32 *TransferResult ) { - USB2_HC_DEV *Ehc; - URB *Urb; - EFI_TPL OldTpl; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + URB *Urb; + EFI_TPL OldTpl; + EFI_STATUS Status; // // Validate the parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -867,12 +864,13 @@ EhcBulkTransfer ( if ((DeviceSpeed == EFI_USB_SPEED_LOW) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || - ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) { + ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) + { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -940,7 +938,6 @@ ON_EXIT: return Status; } - /** Submits an asynchronous interrupt transfer to an interrupt endpoint of a USB device. @@ -973,24 +970,24 @@ ON_EXIT: EFI_STATUS EFIAPI EhcAsyncInterruptTransfer ( - IN EFI_USB2_HC_PROTOCOL * This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN BOOLEAN IsNewTransfer, - IN OUT UINT8 *DataToggle, - IN UINTN PollingInterval, - IN UINTN DataLength, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR * Translator, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK CallBackFunction, - IN VOID *Context OPTIONAL + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN BOOLEAN IsNewTransfer, + IN OUT UINT8 *DataToggle, + IN UINTN PollingInterval, + IN UINTN DataLength, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK CallBackFunction, + IN VOID *Context OPTIONAL ) { - USB2_HC_DEV *Ehc; - URB *Urb; - EFI_TPL OldTpl; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + URB *Urb; + EFI_TPL OldTpl; + EFI_STATUS Status; // // Validate parameters @@ -1013,8 +1010,8 @@ EhcAsyncInterruptTransfer ( } } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); // // Delete Async interrupt transfer request. DataToggle will return @@ -1065,7 +1062,6 @@ ON_EXIT: return Status; } - /** Submits synchronous interrupt transfer to an interrupt endpoint of a USB device. @@ -1109,16 +1105,17 @@ EhcSyncInterruptTransfer ( OUT UINT32 *TransferResult ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - URB *Urb; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + URB *Urb; + EFI_STATUS Status; // // Validates parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -1128,12 +1125,13 @@ EhcSyncInterruptTransfer ( if (((DeviceSpeed == EFI_USB_SPEED_LOW) && (MaximumPacketLength != 8)) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || - ((DeviceSpeed == EFI_USB_SPEED_HIGH) && (MaximumPacketLength > 3072))) { + ((DeviceSpeed == EFI_USB_SPEED_HIGH) && (MaximumPacketLength > 3072))) + { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = EHC_FROM_THIS (This); + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = EHC_FROM_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -1195,7 +1193,6 @@ ON_EXIT: return Status; } - /** Submits isochronous transfer to a target USB device. @@ -1235,7 +1232,6 @@ EhcIsochronousTransfer ( return EFI_UNSUPPORTED; } - /** Submits Async isochronous transfer to a target USB device. @@ -1291,8 +1287,8 @@ EhcAsyncIsochronousTransfer ( EFI_STATUS EFIAPI EhcDriverEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return EfiLibInstallDriverBindingComponentName2 ( @@ -1305,7 +1301,6 @@ EhcDriverEntryPoint ( ); } - /** Test to see if this driver supports ControllerHandle. Any ControllerHandle that has Usb2HcProtocol installed will @@ -1322,14 +1317,14 @@ EhcDriverEntryPoint ( EFI_STATUS EFIAPI EhcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - USB_CLASSC UsbClassCReg; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + USB_CLASSC UsbClassCReg; // // Test whether there is PCI IO Protocol attached on the controller handle. @@ -1337,7 +1332,7 @@ EhcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1363,9 +1358,9 @@ EhcDriverBindingSupported ( // // Test whether the controller belongs to Ehci type // - if ((UsbClassCReg.BaseCode != PCI_CLASS_SERIAL) || (UsbClassCReg.SubClassCode != PCI_CLASS_SERIAL_USB) - || ((UsbClassCReg.ProgInterface != PCI_IF_EHCI) && (UsbClassCReg.ProgInterface != PCI_IF_UHCI) && (UsbClassCReg.ProgInterface != PCI_IF_OHCI))) { - + if ( (UsbClassCReg.BaseCode != PCI_CLASS_SERIAL) || (UsbClassCReg.SubClassCode != PCI_CLASS_SERIAL_USB) + || ((UsbClassCReg.ProgInterface != PCI_IF_EHCI) && (UsbClassCReg.ProgInterface != PCI_IF_UHCI) && (UsbClassCReg.ProgInterface != PCI_IF_OHCI))) + { Status = EFI_UNSUPPORTED; } @@ -1391,15 +1386,15 @@ ON_EXIT: **/ EFI_STATUS EhcGetUsbDebugPortInfo ( - IN USB2_HC_DEV *Ehc - ) + IN USB2_HC_DEV *Ehc + ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT16 PciStatus; - UINT8 CapabilityPtr; - UINT8 CapabilityId; - UINT16 DebugPort; - EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 PciStatus; + UINT8 CapabilityPtr; + UINT8 CapabilityId; + UINT16 DebugPort; + EFI_STATUS Status; ASSERT (Ehc->PciIo != NULL); PciIo = Ehc->PciIo; @@ -1503,7 +1498,6 @@ EhcGetUsbDebugPortInfo ( return EFI_SUCCESS; } - /** Create and initialize a USB2_HC_DEV. @@ -1522,8 +1516,8 @@ EhcCreateUsb2Hc ( IN UINT64 OriginalPciAttributes ) { - USB2_HC_DEV *Ehc; - EFI_STATUS Status; + USB2_HC_DEV *Ehc; + EFI_STATUS Status; Ehc = AllocateZeroPool (sizeof (USB2_HC_DEV)); @@ -1534,23 +1528,23 @@ EhcCreateUsb2Hc ( // // Init EFI_USB2_HC_PROTOCOL interface and private data structure // - Ehc->Signature = USB2_HC_DEV_SIGNATURE; - - Ehc->Usb2Hc.GetCapability = EhcGetCapability; - Ehc->Usb2Hc.Reset = EhcReset; - Ehc->Usb2Hc.GetState = EhcGetState; - Ehc->Usb2Hc.SetState = EhcSetState; - Ehc->Usb2Hc.ControlTransfer = EhcControlTransfer; - Ehc->Usb2Hc.BulkTransfer = EhcBulkTransfer; - Ehc->Usb2Hc.AsyncInterruptTransfer = EhcAsyncInterruptTransfer; - Ehc->Usb2Hc.SyncInterruptTransfer = EhcSyncInterruptTransfer; - Ehc->Usb2Hc.IsochronousTransfer = EhcIsochronousTransfer; - Ehc->Usb2Hc.AsyncIsochronousTransfer = EhcAsyncIsochronousTransfer; - Ehc->Usb2Hc.GetRootHubPortStatus = EhcGetRootHubPortStatus; - Ehc->Usb2Hc.SetRootHubPortFeature = EhcSetRootHubPortFeature; - Ehc->Usb2Hc.ClearRootHubPortFeature = EhcClearRootHubPortFeature; - Ehc->Usb2Hc.MajorRevision = 0x2; - Ehc->Usb2Hc.MinorRevision = 0x0; + Ehc->Signature = USB2_HC_DEV_SIGNATURE; + + Ehc->Usb2Hc.GetCapability = EhcGetCapability; + Ehc->Usb2Hc.Reset = EhcReset; + Ehc->Usb2Hc.GetState = EhcGetState; + Ehc->Usb2Hc.SetState = EhcSetState; + Ehc->Usb2Hc.ControlTransfer = EhcControlTransfer; + Ehc->Usb2Hc.BulkTransfer = EhcBulkTransfer; + Ehc->Usb2Hc.AsyncInterruptTransfer = EhcAsyncInterruptTransfer; + Ehc->Usb2Hc.SyncInterruptTransfer = EhcSyncInterruptTransfer; + Ehc->Usb2Hc.IsochronousTransfer = EhcIsochronousTransfer; + Ehc->Usb2Hc.AsyncIsochronousTransfer = EhcAsyncIsochronousTransfer; + Ehc->Usb2Hc.GetRootHubPortStatus = EhcGetRootHubPortStatus; + Ehc->Usb2Hc.SetRootHubPortFeature = EhcSetRootHubPortFeature; + Ehc->Usb2Hc.ClearRootHubPortFeature = EhcClearRootHubPortFeature; + Ehc->Usb2Hc.MajorRevision = 0x2; + Ehc->Usb2Hc.MinorRevision = 0x0; Ehc->PciIo = PciIo; Ehc->DevicePath = DevicePath; @@ -1603,14 +1597,14 @@ EhcCreateUsb2Hc ( VOID EFIAPI EhcExitBootService ( - EFI_EVENT Event, - VOID *Context + EFI_EVENT Event, + VOID *Context ) { - USB2_HC_DEV *Ehc; + USB2_HC_DEV *Ehc; - Ehc = (USB2_HC_DEV *) Context; + Ehc = (USB2_HC_DEV *)Context; // // Reset the Host Controller @@ -1618,7 +1612,6 @@ EhcExitBootService ( EhcResetHC (Ehc, EHC_RESET_TIMEOUT); } - /** Starting the Usb EHCI Driver. @@ -1635,30 +1628,30 @@ EhcExitBootService ( EFI_STATUS EFIAPI EhcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - USB2_HC_DEV *Ehc; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_PCI_IO_PROTOCOL *Instance; - UINT64 Supports; - UINT64 OriginalPciAttributes; - BOOLEAN PciAttributesSaved; - USB_CLASSC UsbClassCReg; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - UINTN Index; - UINTN CompanionSegmentNumber; - UINTN CompanionBusNumber; - UINTN CompanionDeviceNumber; - UINTN CompanionFunctionNumber; - UINTN EhciSegmentNumber; - UINTN EhciBusNumber; - UINTN EhciDeviceNumber; - UINTN EhciFunctionNumber; + EFI_STATUS Status; + USB2_HC_DEV *Ehc; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *Instance; + UINT64 Supports; + UINT64 OriginalPciAttributes; + BOOLEAN PciAttributesSaved; + USB_CLASSC UsbClassCReg; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + UINTN Index; + UINTN CompanionSegmentNumber; + UINTN CompanionBusNumber; + UINTN CompanionDeviceNumber; + UINTN CompanionFunctionNumber; + UINTN EhciSegmentNumber; + UINTN EhciBusNumber; + UINTN EhciDeviceNumber; + UINTN EhciFunctionNumber; EFI_DEVICE_PATH_PROTOCOL *HcDevicePath; // @@ -1667,7 +1660,7 @@ EhcDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1681,14 +1674,14 @@ EhcDriverBindingStart ( // Open Device Path Protocol for on USB host controller // HcDevicePath = NULL; - Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &HcDevicePath, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&HcDevicePath, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); PciAttributesSaved = FALSE; // @@ -1704,6 +1697,7 @@ EhcDriverBindingStart ( if (EFI_ERROR (Status)) { goto CLOSE_PCIIO; } + PciAttributesSaved = TRUE; Status = PciIo->Attributes ( @@ -1714,12 +1708,12 @@ EhcDriverBindingStart ( ); if (!EFI_ERROR (Status)) { Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE; - Status = PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationEnable, - Supports, - NULL - ); + Status = PciIo->Attributes ( + PciIo, + EfiPciIoAttributeOperationEnable, + Supports, + NULL + ); } if (EFI_ERROR (Status)) { @@ -1742,21 +1736,23 @@ EhcDriverBindingStart ( Status = EFI_UNSUPPORTED; goto CLOSE_PCIIO; } + // // Determine if the device is UHCI or OHCI host controller or not. If yes, then find out the // companion usb ehci host controller and force EHCI driver get attached to it before // UHCI or OHCI driver attaches to UHCI or OHCI host controller. // - if ((UsbClassCReg.ProgInterface == PCI_IF_UHCI || UsbClassCReg.ProgInterface == PCI_IF_OHCI) && - (UsbClassCReg.BaseCode == PCI_CLASS_SERIAL) && - (UsbClassCReg.SubClassCode == PCI_CLASS_SERIAL_USB)) { + if (((UsbClassCReg.ProgInterface == PCI_IF_UHCI) || (UsbClassCReg.ProgInterface == PCI_IF_OHCI)) && + (UsbClassCReg.BaseCode == PCI_CLASS_SERIAL) && + (UsbClassCReg.SubClassCode == PCI_CLASS_SERIAL_USB)) + { Status = PciIo->GetLocation ( - PciIo, - &CompanionSegmentNumber, - &CompanionBusNumber, - &CompanionDeviceNumber, - &CompanionFunctionNumber - ); + PciIo, + &CompanionSegmentNumber, + &CompanionBusNumber, + &CompanionDeviceNumber, + &CompanionFunctionNumber + ); if (EFI_ERROR (Status)) { goto CLOSE_PCIIO; } @@ -1777,19 +1773,19 @@ EhcDriverBindingStart ( // Get the device path on this handle // Status = gBS->HandleProtocol ( - HandleBuffer[Index], - &gEfiPciIoProtocolGuid, - (VOID **)&Instance - ); + HandleBuffer[Index], + &gEfiPciIoProtocolGuid, + (VOID **)&Instance + ); ASSERT_EFI_ERROR (Status); Status = Instance->Pci.Read ( - Instance, - EfiPciIoWidthUint8, - PCI_CLASSCODE_OFFSET, - sizeof (USB_CLASSC) / sizeof (UINT8), - &UsbClassCReg - ); + Instance, + EfiPciIoWidthUint8, + PCI_CLASSCODE_OFFSET, + sizeof (USB_CLASSC) / sizeof (UINT8), + &UsbClassCReg + ); if (EFI_ERROR (Status)) { Status = EFI_UNSUPPORTED; @@ -1797,33 +1793,36 @@ EhcDriverBindingStart ( } if ((UsbClassCReg.ProgInterface == PCI_IF_EHCI) && - (UsbClassCReg.BaseCode == PCI_CLASS_SERIAL) && - (UsbClassCReg.SubClassCode == PCI_CLASS_SERIAL_USB)) { + (UsbClassCReg.BaseCode == PCI_CLASS_SERIAL) && + (UsbClassCReg.SubClassCode == PCI_CLASS_SERIAL_USB)) + { Status = Instance->GetLocation ( - Instance, - &EhciSegmentNumber, - &EhciBusNumber, - &EhciDeviceNumber, - &EhciFunctionNumber - ); + Instance, + &EhciSegmentNumber, + &EhciBusNumber, + &EhciDeviceNumber, + &EhciFunctionNumber + ); if (EFI_ERROR (Status)) { goto CLOSE_PCIIO; } + // // Currently, the judgment on the companion usb host controller is through the // same bus number, which may vary on different platform. // if (EhciBusNumber == CompanionBusNumber) { gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); - EhcDriverBindingStart(This, HandleBuffer[Index], NULL); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); + EhcDriverBindingStart (This, HandleBuffer[Index], NULL); } } } + Status = EFI_NOT_FOUND; goto CLOSE_PCIIO; } @@ -1854,9 +1853,13 @@ EhcDriverBindingStart ( if (!EFI_ERROR (Status)) { Ehc->Support64BitDma = TRUE; } else { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: failed to enable 64-bit DMA on 64-bit capable controller @ %p (%r)\n", - __FUNCTION__, Controller, Status)); + __FUNCTION__, + Controller, + Status + )); } } @@ -1937,7 +1940,6 @@ EhcDriverBindingStart ( FALSE ); - DEBUG ((DEBUG_INFO, "EhcDriverBindingStart: EHCI started for controller @ %p\n", Controller)); return EFI_SUCCESS; @@ -1959,11 +1961,11 @@ CLOSE_PCIIO: // Restore original PCI attributes // PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationSet, - OriginalPciAttributes, - NULL - ); + PciIo, + EfiPciIoAttributeOperationSet, + OriginalPciAttributes, + NULL + ); } gBS->CloseProtocol ( @@ -1976,7 +1978,6 @@ CLOSE_PCIIO: return Status; } - /** Stop this driver on ControllerHandle. Support stopping any child handles created by this driver. @@ -1993,10 +1994,10 @@ CLOSE_PCIIO: EFI_STATUS EFIAPI EhcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -2012,7 +2013,7 @@ EhcDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -2066,11 +2067,11 @@ EhcDriverBindingStop ( // Restore original PCI attributes // PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationSet, - Ehc->OriginalPciAttributes, - NULL - ); + PciIo, + EfiPciIoAttributeOperationSet, + Ehc->OriginalPciAttributes, + NULL + ); gBS->CloseProtocol ( Controller, diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.h b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.h index 65933d9439..393cc209dc 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/Ehci.h @@ -11,7 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_H_ #define _EFI_EHCI_H_ - #include #include @@ -31,7 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -typedef struct _USB2_HC_DEV USB2_HC_DEV; +typedef struct _USB2_HC_DEV USB2_HC_DEV; #include "UsbHcMem.h" #include "EhciReg.h" @@ -44,64 +43,63 @@ typedef struct _USB2_HC_DEV USB2_HC_DEV; // EHC timeout experience values // -#define EHC_1_MICROSECOND 1 -#define EHC_1_MILLISECOND (1000 * EHC_1_MICROSECOND) -#define EHC_1_SECOND (1000 * EHC_1_MILLISECOND) +#define EHC_1_MICROSECOND 1 +#define EHC_1_MILLISECOND (1000 * EHC_1_MICROSECOND) +#define EHC_1_SECOND (1000 * EHC_1_MILLISECOND) // // EHCI register operation timeout, set by experience // -#define EHC_RESET_TIMEOUT (1 * EHC_1_SECOND) -#define EHC_GENERIC_TIMEOUT (10 * EHC_1_MILLISECOND) +#define EHC_RESET_TIMEOUT (1 * EHC_1_SECOND) +#define EHC_GENERIC_TIMEOUT (10 * EHC_1_MILLISECOND) // // Wait for roothub port power stable, refers to Spec[EHCI1.0-2.3.9] // -#define EHC_ROOT_PORT_RECOVERY_STALL (20 * EHC_1_MILLISECOND) +#define EHC_ROOT_PORT_RECOVERY_STALL (20 * EHC_1_MILLISECOND) // // Sync and Async transfer polling interval, set by experience, // and the unit of Async is 100us, means 1ms as interval. // -#define EHC_SYNC_POLL_INTERVAL (1 * EHC_1_MILLISECOND) -#define EHC_ASYNC_POLL_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) +#define EHC_SYNC_POLL_INTERVAL (1 * EHC_1_MILLISECOND) +#define EHC_ASYNC_POLL_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) // // EHCI debug port control status register bit definition // -#define USB_DEBUG_PORT_IN_USE BIT10 -#define USB_DEBUG_PORT_ENABLE BIT28 -#define USB_DEBUG_PORT_OWNER BIT30 -#define USB_DEBUG_PORT_IN_USE_MASK (USB_DEBUG_PORT_IN_USE | \ +#define USB_DEBUG_PORT_IN_USE BIT10 +#define USB_DEBUG_PORT_ENABLE BIT28 +#define USB_DEBUG_PORT_OWNER BIT30 +#define USB_DEBUG_PORT_IN_USE_MASK (USB_DEBUG_PORT_IN_USE | \ USB_DEBUG_PORT_OWNER) // // EHC raises TPL to TPL_NOTIFY to serialize all its operations // to protect shared data structures. // -#define EHC_TPL TPL_NOTIFY - -#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) +#define EHC_TPL TPL_NOTIFY +#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) -#define EHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) -#define EHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) -#define EHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define EHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) +#define EHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) +#define EHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) #define EHC_REG_BIT_IS_SET(Ehc, Offset, Bit) \ (EHC_BIT_IS_SET(EhcReadOpReg ((Ehc), (Offset)), (Bit))) #define USB2_HC_DEV_SIGNATURE SIGNATURE_32 ('e', 'h', 'c', 'i') -#define EHC_FROM_THIS(a) CR(a, USB2_HC_DEV, Usb2Hc, USB2_HC_DEV_SIGNATURE) +#define EHC_FROM_THIS(a) CR(a, USB2_HC_DEV, Usb2Hc, USB2_HC_DEV_SIGNATURE) struct _USB2_HC_DEV { - UINTN Signature; - EFI_USB2_HC_PROTOCOL Usb2Hc; + UINTN Signature; + EFI_USB2_HC_PROTOCOL Usb2Hc; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINT64 OriginalPciAttributes; - USBHC_MEM_POOL *MemPool; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINT64 OriginalPciAttributes; + USBHC_MEM_POOL *MemPool; // // Schedule data shared between asynchronous and periodic @@ -112,58 +110,57 @@ struct _USB2_HC_DEV { // For control transfer, even the short read happens, try the // status stage. // - EHC_QTD *ShortReadStop; - EFI_EVENT PollTimer; + EHC_QTD *ShortReadStop; + EFI_EVENT PollTimer; // // ExitBootServicesEvent is used to stop the EHC DMA operation // after exit boot service. // - EFI_EVENT ExitBootServiceEvent; + EFI_EVENT ExitBootServiceEvent; // // Asynchronous(bulk and control) transfer schedule data: // ReclaimHead is used as the head of the asynchronous transfer // list. It acts as the reclamation header. // - EHC_QH *ReclaimHead; + EHC_QH *ReclaimHead; // // Periodic (interrupt) transfer schedule data: // - VOID *PeriodFrame; // the buffer pointed by this pointer is used to store pci bus address of the QH descriptor. - VOID *PeriodFrameHost; // the buffer pointed by this pointer is used to store host memory address of the QH descriptor. - VOID *PeriodFrameMap; + VOID *PeriodFrame; // the buffer pointed by this pointer is used to store pci bus address of the QH descriptor. + VOID *PeriodFrameHost; // the buffer pointed by this pointer is used to store host memory address of the QH descriptor. + VOID *PeriodFrameMap; - EHC_QH *PeriodOne; - LIST_ENTRY AsyncIntTransfers; + EHC_QH *PeriodOne; + LIST_ENTRY AsyncIntTransfers; // // EHCI configuration data // - UINT32 HcStructParams; // Cache of HC structure parameter, EHC_HCSPARAMS_OFFSET - UINT32 HcCapParams; // Cache of HC capability parameter, HCCPARAMS - UINT32 CapLen; // Capability length + UINT32 HcStructParams; // Cache of HC structure parameter, EHC_HCSPARAMS_OFFSET + UINT32 HcCapParams; // Cache of HC capability parameter, HCCPARAMS + UINT32 CapLen; // Capability length // // Misc // - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; // // EHCI debug port info // - UINT16 DebugPortOffset; // The offset of debug port mmio register - UINT8 DebugPortBarNum; // The bar number of debug port mmio register - UINT8 DebugPortNum; // The port number of usb debug port + UINT16 DebugPortOffset; // The offset of debug port mmio register + UINT8 DebugPortBarNum; // The bar number of debug port mmio register + UINT8 DebugPortNum; // The port number of usb debug port - BOOLEAN Support64BitDma; // Whether 64 bit DMA may be used with this device + BOOLEAN Support64BitDma; // Whether 64 bit DMA may be used with this device }; - -extern EFI_DRIVER_BINDING_PROTOCOL gEhciDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gEhciComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gEhciComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gEhciDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gEhciComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gEhciComponentName2; /** Test to see if this driver supports ControllerHandle. Any @@ -181,9 +178,9 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gEhciComponentName2; EFI_STATUS EFIAPI EhcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -202,9 +199,9 @@ EhcDriverBindingSupported ( EFI_STATUS EFIAPI EhcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -223,11 +220,10 @@ EhcDriverBindingStart ( EFI_STATUS EFIAPI EhcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); #endif - diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.c index 55cbb68570..79888bf3a5 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.c @@ -8,7 +8,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Ehci.h" /** @@ -19,7 +18,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID EhcDumpStatus ( - IN UINT32 State + IN UINT32 State ) { if (EHC_BIT_IS_SET (State, QTD_STAT_DO_PING)) { @@ -57,7 +56,6 @@ EhcDumpStatus ( DEBUG ((DEBUG_VERBOSE, "\n")); } - /** Dump the fields of a QTD. @@ -67,12 +65,12 @@ EhcDumpStatus ( **/ VOID EhcDumpQtd ( - IN EHC_QTD *Qtd, - IN CHAR8 *Msg + IN EHC_QTD *Qtd, + IN CHAR8 *Msg ) { - QTD_HW *QtdHw; - UINTN Index; + QTD_HW *QtdHw; + UINTN Index; if (Msg != NULL) { DEBUG ((DEBUG_VERBOSE, Msg)); @@ -89,13 +87,10 @@ EhcDumpQtd ( if (QtdHw->Pid == QTD_PID_SETUP) { DEBUG ((DEBUG_VERBOSE, "PID : Setup\n")); - } else if (QtdHw->Pid == QTD_PID_INPUT) { DEBUG ((DEBUG_VERBOSE, "PID : IN\n")); - } else if (QtdHw->Pid == QTD_PID_OUTPUT) { DEBUG ((DEBUG_VERBOSE, "PID : OUT\n")); - } DEBUG ((DEBUG_VERBOSE, "Error Count : %d\n", QtdHw->ErrCnt)); @@ -109,7 +104,6 @@ EhcDumpQtd ( } } - /** Dump the queue head. @@ -120,22 +114,27 @@ EhcDumpQtd ( **/ VOID EhcDumpQh ( - IN EHC_QH *Qh, - IN CHAR8 *Msg, - IN BOOLEAN DumpBuf + IN EHC_QH *Qh, + IN CHAR8 *Msg, + IN BOOLEAN DumpBuf ) { - EHC_QTD *Qtd; - QH_HW *QhHw; - LIST_ENTRY *Entry; - UINTN Index; + EHC_QTD *Qtd; + QH_HW *QhHw; + LIST_ENTRY *Entry; + UINTN Index; if (Msg != NULL) { DEBUG ((DEBUG_VERBOSE, Msg)); } - DEBUG ((DEBUG_VERBOSE, "Queue head @ 0x%p, interval %ld, next qh %p\n", - Qh, (UINT64)Qh->Interval, Qh->NextQh)); + DEBUG (( + DEBUG_VERBOSE, + "Queue head @ 0x%p, interval %ld, next qh %p\n", + Qh, + (UINT64)Qh->Interval, + Qh->NextQh + )); QhHw = &Qh->QhHw; @@ -166,10 +165,8 @@ EhcDumpQh ( if (QhHw->Pid == QTD_PID_SETUP) { DEBUG ((DEBUG_VERBOSE, "PID : Setup\n")); - } else if (QhHw->Pid == QTD_PID_INPUT) { DEBUG ((DEBUG_VERBOSE, "PID : IN\n")); - } else if (QhHw->Pid == QTD_PID_OUTPUT) { DEBUG ((DEBUG_VERBOSE, "PID : OUT\n")); } @@ -196,7 +193,6 @@ EhcDumpQh ( } } - /** Dump the buffer in the form of hex. @@ -206,15 +202,15 @@ EhcDumpQh ( **/ VOID EhcDumpBuf ( - IN UINT8 *Buf, - IN UINTN Len + IN UINT8 *Buf, + IN UINTN Len ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Len; Index++) { if (Index % 16 == 0) { - DEBUG ((DEBUG_VERBOSE,"\n")); + DEBUG ((DEBUG_VERBOSE, "\n")); } DEBUG ((DEBUG_VERBOSE, "%02x ", Buf[Index])); diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.h b/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.h index eff85dcec8..2ed2d46f96 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciDebug.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_DEBUG_H_ #define _EFI_EHCI_DEBUG_H_ - /** Dump the fields of a QTD. @@ -20,11 +19,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID EhcDumpQtd ( - IN EHC_QTD *Qtd, - IN CHAR8 *Msg + IN EHC_QTD *Qtd, + IN CHAR8 *Msg ); - /** Dump the queue head. @@ -35,12 +33,11 @@ EhcDumpQtd ( **/ VOID EhcDumpQh ( - IN EHC_QH *Qh, - IN CHAR8 *Msg, - IN BOOLEAN DumpBuf + IN EHC_QH *Qh, + IN CHAR8 *Msg, + IN BOOLEAN DumpBuf ); - /** Dump the buffer in the form of hex. @@ -50,9 +47,8 @@ EhcDumpQh ( **/ VOID EhcDumpBuf ( - IN UINT8 *Buf, - IN UINTN Len + IN UINT8 *Buf, + IN UINTN Len ); - #endif diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.c index 7bd01c1aee..912048eee9 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.c @@ -7,10 +7,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Ehci.h" - /** Read EHCI capability register. @@ -23,18 +21,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT32 EhcReadCapRegister ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; Status = Ehc->PciIo->Mem.Read ( Ehc->PciIo, EfiPciIoWidthUint32, EHC_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); @@ -59,12 +57,12 @@ EhcReadCapRegister ( **/ UINT32 EhcReadDbgRegister ( - IN CONST USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN CONST USB2_HC_DEV *Ehc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; Status = Ehc->PciIo->Mem.Read ( Ehc->PciIo, @@ -83,7 +81,6 @@ EhcReadDbgRegister ( return Data; } - /** Check whether the host controller has an in-use debug port. @@ -105,11 +102,11 @@ EhcReadDbgRegister ( **/ BOOLEAN EhcIsDebugPortInUse ( - IN CONST USB2_HC_DEV *Ehc, - IN CONST UINT8 *PortNumber OPTIONAL + IN CONST USB2_HC_DEV *Ehc, + IN CONST UINT8 *PortNumber OPTIONAL ) { - UINT32 State; + UINT32 State; if (Ehc->DebugPortNum == 0) { // @@ -121,7 +118,7 @@ EhcIsDebugPortInUse ( // // The Debug Port Number field in HCSPARAMS is one-based. // - if (PortNumber != NULL && *PortNumber != Ehc->DebugPortNum - 1) { + if ((PortNumber != NULL) && (*PortNumber != Ehc->DebugPortNum - 1)) { // // The caller specified a port, but it's not the debug port of the host // controller. @@ -132,11 +129,10 @@ EhcIsDebugPortInUse ( // // Deduce usage from the Control Register. // - State = EhcReadDbgRegister(Ehc, 0); + State = EhcReadDbgRegister (Ehc, 0); return (State & USB_DEBUG_PORT_IN_USE_MASK) == USB_DEBUG_PORT_IN_USE_MASK; } - /** Read EHCI Operation register. @@ -149,12 +145,12 @@ EhcIsDebugPortInUse ( **/ UINT32 EhcReadOpReg ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; ASSERT (Ehc->CapLen != 0); @@ -175,7 +171,6 @@ EhcReadOpReg ( return Data; } - /** Write the data to the EHCI operation register. @@ -186,12 +181,12 @@ EhcReadOpReg ( **/ VOID EhcWriteOpReg ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Data + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Ehc->CapLen != 0); @@ -209,7 +204,6 @@ EhcWriteOpReg ( } } - /** Set one bit of the operational register while keeping other bits. @@ -220,19 +214,18 @@ EhcWriteOpReg ( **/ VOID EhcSetOpRegBit ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = EhcReadOpReg (Ehc, Offset); Data |= Bit; EhcWriteOpReg (Ehc, Offset, Data); } - /** Clear one bit of the operational register while keeping other bits. @@ -243,19 +236,18 @@ EhcSetOpRegBit ( **/ VOID EhcClearOpRegBit ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = EhcReadOpReg (Ehc, Offset); Data &= ~Bit; EhcWriteOpReg (Ehc, Offset, Data); } - /** Wait the operation register's bit as specified by Bit to become set (or clear). @@ -272,14 +264,14 @@ EhcClearOpRegBit ( **/ EFI_STATUS EhcWaitOpRegBit ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ) { - UINT32 Index; + UINT32 Index; for (Index = 0; Index < Timeout / EHC_SYNC_POLL_INTERVAL + 1; Index++) { if (EHC_REG_BIT_IS_SET (Ehc, Offset, Bit) == WaitToSet) { @@ -292,7 +284,6 @@ EhcWaitOpRegBit ( return EFI_TIMEOUT; } - /** Add support for UEFI Over Legacy (UoL) feature, stop the legacy USB SMI support. @@ -302,13 +293,13 @@ EhcWaitOpRegBit ( **/ VOID EhcClearLegacySupport ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { - UINT32 ExtendCap; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT32 Value; - UINT32 TimeOut; + UINT32 ExtendCap; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT32 Value; + UINT32 TimeOut; DEBUG ((DEBUG_INFO, "EhcClearLegacySupport: called to clear legacy support\n")); @@ -337,8 +328,6 @@ EhcClearLegacySupport ( PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, ExtendCap + 0x4, 1, &Value); } - - /** Set door bell and wait it to be ACKed by host controller. This function is used to synchronize with the hardware. @@ -352,12 +341,12 @@ EhcClearLegacySupport ( **/ EFI_STATUS EhcSetAndWaitDoorBell ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; - UINT32 Data; + EFI_STATUS Status; + UINT32 Data; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_IAAD); @@ -376,7 +365,6 @@ EhcSetAndWaitDoorBell ( return Status; } - /** Clear all the interrutp status bits, these bits are Write-Clean. @@ -386,13 +374,12 @@ EhcSetAndWaitDoorBell ( **/ VOID EhcAckAllInterrupt ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { EhcWriteOpReg (Ehc, EHC_USBSTS_OFFSET, USBSTS_INTACK_MASK); } - /** Enable the periodic schedule then wait EHC to actually enable it. @@ -406,11 +393,11 @@ EhcAckAllInterrupt ( **/ EFI_STATUS EhcEnablePeriodSchd ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_ENABLE_PERIOD); @@ -418,11 +405,6 @@ EhcEnablePeriodSchd ( return Status; } - - - - - /** Enable asynchrounous schedule. @@ -435,11 +417,11 @@ EhcEnablePeriodSchd ( **/ EFI_STATUS EhcEnableAsyncSchd ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_ENABLE_ASYNC); @@ -447,12 +429,6 @@ EhcEnableAsyncSchd ( return Status; } - - - - - - /** Whether Ehc is halted. @@ -464,13 +440,12 @@ EhcEnableAsyncSchd ( **/ BOOLEAN EhcIsHalt ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { return EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT); } - /** Whether system error occurred. @@ -482,13 +457,12 @@ EhcIsHalt ( **/ BOOLEAN EhcIsSysError ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { return EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_SYS_ERROR); } - /** Reset the host controller. @@ -501,11 +475,11 @@ EhcIsSysError ( **/ EFI_STATUS EhcResetHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Host can only be reset when it is halt. If not so, halt it @@ -523,7 +497,6 @@ EhcResetHC ( return Status; } - /** Halt the host controller. @@ -536,18 +509,17 @@ EhcResetHC ( **/ EFI_STATUS EhcHaltHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcClearOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_RUN); Status = EhcWaitOpRegBit (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT, TRUE, Timeout); return Status; } - /** Set the EHCI to run. @@ -560,18 +532,17 @@ EhcHaltHC ( **/ EFI_STATUS EhcRunHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_RUN); Status = EhcWaitOpRegBit (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT, FALSE, Timeout); return Status; } - /** Initialize the HC hardware. EHCI spec lists the five things to do to initialize the hardware: @@ -589,12 +560,12 @@ EhcRunHC ( **/ EFI_STATUS EhcInitHC ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { - EFI_STATUS Status; - UINT32 Index; - UINT32 RegVal; + EFI_STATUS Status; + UINT32 Index; + UINT32 RegVal; // This ASSERT crashes the BeagleBoard. There is some issue in the USB stack. // This ASSERT needs to be removed so the BeagleBoard will boot. When we fix @@ -629,15 +600,15 @@ EhcInitHC ( // 3. Power up all ports if EHCI has Port Power Control (PPC) support // if (Ehc->HcStructParams & HCSP_PPC) { - for (Index = 0; Index < (UINT8) (Ehc->HcStructParams & HCSP_NPORTS); Index++) { + for (Index = 0; Index < (UINT8)(Ehc->HcStructParams & HCSP_NPORTS); Index++) { // // Do not clear port status bits on initialization. Otherwise devices will // not enumerate properly at startup. // - RegVal = EhcReadOpReg(Ehc, (UINT32)(EHC_PORT_STAT_OFFSET + (4 * Index))); + RegVal = EhcReadOpReg (Ehc, (UINT32)(EHC_PORT_STAT_OFFSET + (4 * Index))); RegVal &= ~PORTSC_CHANGE_MASK; RegVal |= PORTSC_POWER; - EhcWriteOpReg (Ehc, (UINT32) (EHC_PORT_STAT_OFFSET + (4 * Index)), RegVal); + EhcWriteOpReg (Ehc, (UINT32)(EHC_PORT_STAT_OFFSET + (4 * Index)), RegVal); } } diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.h b/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.h index 911cd2135f..064de362cb 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciReg.h @@ -14,20 +14,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // EHCI register offset // - // // Capability register offset // -#define EHC_CAPLENGTH_OFFSET 0 // Capability register length offset -#define EHC_HCSPARAMS_OFFSET 0x04 // Structural Parameters 04-07h -#define EHC_HCCPARAMS_OFFSET 0x08 // Capability parameters offset +#define EHC_CAPLENGTH_OFFSET 0 // Capability register length offset +#define EHC_HCSPARAMS_OFFSET 0x04 // Structural Parameters 04-07h +#define EHC_HCCPARAMS_OFFSET 0x08 // Capability parameters offset // // Capability register bit definition // -#define HCSP_NPORTS 0x0F // Number of root hub port -#define HCSP_PPC 0x10 // Port Power Control -#define HCCP_64BIT 0x01 // 64-bit addressing capability +#define HCSP_NPORTS 0x0F // Number of root hub port +#define HCSP_PPC 0x10 // Port Power Control +#define HCCP_64BIT 0x01 // 64-bit addressing capability // // Operational register offset @@ -42,66 +41,66 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EHC_CONFIG_FLAG_OFFSET 0x40 // Configure flag register offset #define EHC_PORT_STAT_OFFSET 0x44 // Port status/control offset -#define EHC_FRAME_LEN 1024 +#define EHC_FRAME_LEN 1024 // // Register bit definition // -#define CONFIGFLAG_ROUTE_EHC 0x01 // Route port to EHC - -#define USBCMD_RUN 0x01 // Run/stop -#define USBCMD_RESET 0x02 // Start the host controller reset -#define USBCMD_ENABLE_PERIOD 0x10 // Enable periodic schedule -#define USBCMD_ENABLE_ASYNC 0x20 // Enable asynchronous schedule -#define USBCMD_IAAD 0x40 // Interrupt on async advance doorbell - -#define USBSTS_IAA 0x20 // Interrupt on async advance -#define USBSTS_PERIOD_ENABLED 0x4000 // Periodic schedule status -#define USBSTS_ASYNC_ENABLED 0x8000 // Asynchronous schedule status -#define USBSTS_HALT 0x1000 // Host controller halted -#define USBSTS_SYS_ERROR 0x10 // Host system error -#define USBSTS_INTACK_MASK 0x003F // Mask for the interrupt ACK, the WC +#define CONFIGFLAG_ROUTE_EHC 0x01 // Route port to EHC + +#define USBCMD_RUN 0x01 // Run/stop +#define USBCMD_RESET 0x02 // Start the host controller reset +#define USBCMD_ENABLE_PERIOD 0x10 // Enable periodic schedule +#define USBCMD_ENABLE_ASYNC 0x20 // Enable asynchronous schedule +#define USBCMD_IAAD 0x40 // Interrupt on async advance doorbell + +#define USBSTS_IAA 0x20 // Interrupt on async advance +#define USBSTS_PERIOD_ENABLED 0x4000 // Periodic schedule status +#define USBSTS_ASYNC_ENABLED 0x8000 // Asynchronous schedule status +#define USBSTS_HALT 0x1000 // Host controller halted +#define USBSTS_SYS_ERROR 0x10 // Host system error +#define USBSTS_INTACK_MASK 0x003F // Mask for the interrupt ACK, the WC // (write clean) bits in USBSTS register -#define PORTSC_CONN 0x01 // Current Connect Status -#define PORTSC_CONN_CHANGE 0x02 // Connect Status Change -#define PORTSC_ENABLED 0x04 // Port Enable / Disable -#define PORTSC_ENABLE_CHANGE 0x08 // Port Enable / Disable Change -#define PORTSC_OVERCUR 0x10 // Over current Active -#define PORTSC_OVERCUR_CHANGE 0x20 // Over current Change -#define PORSTSC_RESUME 0x40 // Force Port Resume -#define PORTSC_SUSPEND 0x80 // Port Suspend State -#define PORTSC_RESET 0x100 // Port Reset -#define PORTSC_LINESTATE_K 0x400 // Line Status K-state -#define PORTSC_LINESTATE_J 0x800 // Line Status J-state -#define PORTSC_POWER 0x1000 // Port Power -#define PORTSC_OWNER 0x2000 // Port Owner -#define PORTSC_CHANGE_MASK 0x2A // Mask of the port change bits, +#define PORTSC_CONN 0x01 // Current Connect Status +#define PORTSC_CONN_CHANGE 0x02 // Connect Status Change +#define PORTSC_ENABLED 0x04 // Port Enable / Disable +#define PORTSC_ENABLE_CHANGE 0x08 // Port Enable / Disable Change +#define PORTSC_OVERCUR 0x10 // Over current Active +#define PORTSC_OVERCUR_CHANGE 0x20 // Over current Change +#define PORSTSC_RESUME 0x40 // Force Port Resume +#define PORTSC_SUSPEND 0x80 // Port Suspend State +#define PORTSC_RESET 0x100 // Port Reset +#define PORTSC_LINESTATE_K 0x400 // Line Status K-state +#define PORTSC_LINESTATE_J 0x800 // Line Status J-state +#define PORTSC_POWER 0x1000 // Port Power +#define PORTSC_OWNER 0x2000 // Port Owner +#define PORTSC_CHANGE_MASK 0x2A // Mask of the port change bits, // they are WC (write clean) // // PCI Configuration Registers // -#define EHC_BAR_INDEX 0 // how many bytes away from USB_BASE to 0x10 +#define EHC_BAR_INDEX 0 // how many bytes away from USB_BASE to 0x10 // // Debug port capability id // -#define EHC_DEBUG_PORT_CAP_ID 0x0A +#define EHC_DEBUG_PORT_CAP_ID 0x0A -#define EHC_LINK_TERMINATED(Link) (((Link) & 0x01) != 0) +#define EHC_LINK_TERMINATED(Link) (((Link) & 0x01) != 0) #define EHC_ADDR(High, QhHw32) \ ((VOID *) (UINTN) (LShiftU64 ((High), 32) | ((QhHw32) & 0xFFFFFFF0))) -#define EHCI_IS_DATAIN(EndpointAddr) EHC_BIT_IS_SET((EndpointAddr), 0x80) +#define EHCI_IS_DATAIN(EndpointAddr) EHC_BIT_IS_SET((EndpointAddr), 0x80) // // Structure to map the hardware port states to the // UEFI's port states. // typedef struct { - UINT16 HwState; - UINT16 UefiState; + UINT16 HwState; + UINT16 UefiState; } USB_PORT_STATE_MAP; // @@ -109,9 +108,9 @@ typedef struct { // #pragma pack(1) typedef struct { - UINT8 ProgInterface; - UINT8 SubClassCode; - UINT8 BaseCode; + UINT8 ProgInterface; + UINT8 SubClassCode; + UINT8 BaseCode; } USB_CLASSC; #pragma pack() @@ -126,8 +125,8 @@ typedef struct { **/ UINT32 EhcReadCapRegister ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset ); /** @@ -151,8 +150,8 @@ EhcReadCapRegister ( **/ BOOLEAN EhcIsDebugPortInUse ( - IN CONST USB2_HC_DEV *Ehc, - IN CONST UINT8 *PortNumber OPTIONAL + IN CONST USB2_HC_DEV *Ehc, + IN CONST UINT8 *PortNumber OPTIONAL ); /** @@ -166,11 +165,10 @@ EhcIsDebugPortInUse ( **/ UINT32 EhcReadOpReg ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset ); - /** Write the data to the EHCI operation register. @@ -181,9 +179,9 @@ EhcReadOpReg ( **/ VOID EhcWriteOpReg ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Data + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -196,9 +194,9 @@ EhcWriteOpReg ( **/ VOID EhcSetOpRegBit ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -211,9 +209,9 @@ EhcSetOpRegBit ( **/ VOID EhcClearOpRegBit ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -225,11 +223,9 @@ EhcClearOpRegBit ( **/ VOID EhcClearLegacySupport ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - - /** Set door bell and wait it to be ACKed by host controller. This function is used to synchronize with the hardware. @@ -243,11 +239,10 @@ EhcClearLegacySupport ( **/ EFI_STATUS EhcSetAndWaitDoorBell ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ); - /** Clear all the interrutp status bits, these bits are Write-Clean. @@ -256,11 +251,9 @@ EhcSetAndWaitDoorBell ( **/ VOID EhcAckAllInterrupt ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - - /** Whether Ehc is halted. @@ -272,10 +265,9 @@ EhcAckAllInterrupt ( **/ BOOLEAN EhcIsHalt ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - /** Whether system error occurred. @@ -287,10 +279,9 @@ EhcIsHalt ( **/ BOOLEAN EhcIsSysError ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - /** Reset the host controller. @@ -303,11 +294,10 @@ EhcIsSysError ( **/ EFI_STATUS EhcResetHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ); - /** Halt the host controller. @@ -320,11 +310,10 @@ EhcResetHC ( **/ EFI_STATUS EhcHaltHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ); - /** Set the EHCI to run. @@ -337,12 +326,10 @@ EhcHaltHC ( **/ EFI_STATUS EhcRunHC ( - IN USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN USB2_HC_DEV *Ehc, + IN UINT32 Timeout ); - - /** Initialize the HC hardware. EHCI spec lists the five things to do to initialize the hardware: @@ -360,7 +347,7 @@ EhcRunHC ( **/ EFI_STATUS EhcInitHC ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); #endif diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c index 34ee40c4bb..5da26afbe1 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.c @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ehci.h" - /** Create helper QTD/QH for the EHCI device. @@ -22,14 +21,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EhcCreateHelpQ ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { - USB_ENDPOINT Ep; - EHC_QH *Qh; - QH_HW *QhHw; - EHC_QTD *Qtd; - EFI_PHYSICAL_ADDRESS PciAddr; + USB_ENDPOINT Ep; + EHC_QH *Qh; + QH_HW *QhHw; + EHC_QTD *Qtd; + EFI_PHYSICAL_ADDRESS PciAddr; // // Create an inactive Qtd to terminate the short packet read. @@ -40,25 +39,25 @@ EhcCreateHelpQ ( return EFI_OUT_OF_RESOURCES; } - Qtd->QtdHw.Status = QTD_STAT_HALTED; - Ehc->ShortReadStop = Qtd; + Qtd->QtdHw.Status = QTD_STAT_HALTED; + Ehc->ShortReadStop = Qtd; // // Create a QH to act as the EHC reclamation header. // Set the header to loopback to itself. // - Ep.DevAddr = 0; - Ep.EpAddr = 1; - Ep.Direction = EfiUsbDataIn; - Ep.DevSpeed = EFI_USB_SPEED_HIGH; - Ep.MaxPacket = 64; - Ep.HubAddr = 0; - Ep.HubPort = 0; - Ep.Toggle = 0; - Ep.Type = EHC_BULK_TRANSFER; - Ep.PollRate = 1; - - Qh = EhcCreateQh (Ehc, &Ep); + Ep.DevAddr = 0; + Ep.EpAddr = 1; + Ep.Direction = EfiUsbDataIn; + Ep.DevSpeed = EFI_USB_SPEED_HIGH; + Ep.MaxPacket = 64; + Ep.HubAddr = 0; + Ep.HubPort = 0; + Ep.Toggle = 0; + Ep.Type = EHC_BULK_TRANSFER; + Ep.PollRate = 1; + + Qh = EhcCreateQh (Ehc, &Ep); if (Qh == NULL) { return EFI_OUT_OF_RESOURCES; @@ -66,7 +65,7 @@ EhcCreateHelpQ ( PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh, sizeof (EHC_QH)); QhHw = &Qh->QhHw; - QhHw->HorizonLink = QH_LINK (PciAddr + OFFSET_OF(EHC_QH, QhHw), EHC_TYPE_QH, FALSE); + QhHw->HorizonLink = QH_LINK (PciAddr + OFFSET_OF (EHC_QH, QhHw), EHC_TYPE_QH, FALSE); QhHw->Status = QTD_STAT_HALTED; QhHw->ReclaimHead = 1; Qh->NextQh = Qh; @@ -75,10 +74,10 @@ EhcCreateHelpQ ( // // Create a dummy QH to act as the terminator for periodical schedule // - Ep.EpAddr = 2; - Ep.Type = EHC_INT_TRANSFER_SYNC; + Ep.EpAddr = 2; + Ep.Type = EHC_INT_TRANSFER_SYNC; - Qh = EhcCreateQh (Ehc, &Ep); + Qh = EhcCreateQh (Ehc, &Ep); if (Qh == NULL) { return EFI_OUT_OF_RESOURCES; @@ -90,7 +89,6 @@ EhcCreateHelpQ ( return EFI_SUCCESS; } - /** Initialize the schedule data structure such as frame list. @@ -102,7 +100,7 @@ EhcCreateHelpQ ( **/ EFI_STATUS EhcInitSched ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { EFI_PCI_IO_PROTOCOL *PciIo; @@ -154,8 +152,8 @@ EhcInitSched ( return EFI_OUT_OF_RESOURCES; } - Ehc->PeriodFrame = Buf; - Ehc->PeriodFrameMap = Map; + Ehc->PeriodFrame = Buf; + Ehc->PeriodFrameMap = Map; // // Program the FRAMELISTBASE register with the low 32 bit addr @@ -191,13 +189,13 @@ EhcInitSched ( // // Initialize the frame list entries then set the registers // - Ehc->PeriodFrameHost = AllocateZeroPool (EHC_FRAME_LEN * sizeof (UINTN)); + Ehc->PeriodFrameHost = AllocateZeroPool (EHC_FRAME_LEN * sizeof (UINTN)); if (Ehc->PeriodFrameHost == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->PeriodOne, sizeof (EHC_QH)); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->PeriodOne, sizeof (EHC_QH)); for (Index = 0; Index < EHC_FRAME_LEN; Index++) { // @@ -242,7 +240,6 @@ ErrorExit1: return Status; } - /** Free the schedule data. It may be partially initialized. @@ -251,10 +248,10 @@ ErrorExit1: **/ VOID EhcFreeSched ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; EhcWriteOpReg (Ehc, EHC_FRAME_BASE_OFFSET, 0); EhcWriteOpReg (Ehc, EHC_ASYNC_HEAD_OFFSET, 0); @@ -300,7 +297,6 @@ EhcFreeSched ( } } - /** Link the queue head to the asynchronous schedule list. UEFI only supports one CTRL/BULK transfer at a time @@ -314,30 +310,29 @@ EhcFreeSched ( **/ VOID EhcLinkQhToAsync ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ) { - EHC_QH *Head; - EFI_PHYSICAL_ADDRESS PciAddr; + EHC_QH *Head; + EFI_PHYSICAL_ADDRESS PciAddr; // // Append the queue head after the reclaim header, then // fix the hardware visiable parts (EHCI R1.0 page 72). // ReclaimHead is always linked to the EHCI's AsynListAddr. // - Head = Ehc->ReclaimHead; + Head = Ehc->ReclaimHead; - Qh->NextQh = Head->NextQh; - Head->NextQh = Qh; + Qh->NextQh = Head->NextQh; + Head->NextQh = Qh; - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh->NextQh, sizeof (EHC_QH)); - Qh->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Head->NextQh, sizeof (EHC_QH)); - Head->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh->NextQh, sizeof (EHC_QH)); + Qh->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Head->NextQh, sizeof (EHC_QH)); + Head->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); } - /** Unlink a queue head from the asynchronous schedule list. Need to synchronize with hardware. @@ -348,13 +343,13 @@ EhcLinkQhToAsync ( **/ VOID EhcUnlinkQhFromAsync ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ) { - EHC_QH *Head; - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS PciAddr; + EHC_QH *Head; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS PciAddr; ASSERT (Ehc->ReclaimHead->NextQh == Qh); @@ -363,13 +358,13 @@ EhcUnlinkQhFromAsync ( // visiable part: Only need to loopback the ReclaimHead. The Qh // is pointing to ReclaimHead (which is staill in the list). // - Head = Ehc->ReclaimHead; + Head = Ehc->ReclaimHead; - Head->NextQh = Qh->NextQh; - Qh->NextQh = NULL; + Head->NextQh = Qh->NextQh; + Qh->NextQh = NULL; - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Head->NextQh, sizeof (EHC_QH)); - Head->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Head->NextQh, sizeof (EHC_QH)); + Head->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); // // Set and wait the door bell to synchronize with the hardware @@ -381,7 +376,6 @@ EhcUnlinkQhFromAsync ( } } - /** Link a queue head for interrupt transfer to the periodic schedule frame list. This code is very much the same as @@ -393,23 +387,23 @@ EhcUnlinkQhFromAsync ( **/ VOID EhcLinkQhToPeriod ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ) { - UINTN Index; - EHC_QH *Prev; - EHC_QH *Next; - EFI_PHYSICAL_ADDRESS PciAddr; + UINTN Index; + EHC_QH *Prev; + EHC_QH *Next; + EFI_PHYSICAL_ADDRESS PciAddr; for (Index = 0; Index < EHC_FRAME_LEN; Index += Qh->Interval) { // // First QH can't be NULL because we always keep PeriodOne // heads on the frame list // - ASSERT (!EHC_LINK_TERMINATED (((UINT32*)Ehc->PeriodFrame)[Index])); - Next = (EHC_QH*)((UINTN*)Ehc->PeriodFrameHost)[Index]; - Prev = NULL; + ASSERT (!EHC_LINK_TERMINATED (((UINT32 *)Ehc->PeriodFrame)[Index])); + Next = (EHC_QH *)((UINTN *)Ehc->PeriodFrameHost)[Index]; + Prev = NULL; // // Now, insert the queue head (Qh) into this frame: @@ -422,8 +416,8 @@ EhcLinkQhToPeriod ( // Then, insert the Qh between then // while (Next->Interval > Qh->Interval) { - Prev = Next; - Next = Next->NextQh; + Prev = Next; + Next = Next->NextQh; } ASSERT (Next != NULL); @@ -449,15 +443,15 @@ EhcLinkQhToPeriod ( // ASSERT ((Index == 0) && (Qh->NextQh == NULL)); - Prev = Next; - Next = Next->NextQh; + Prev = Next; + Next = Next->NextQh; - Qh->NextQh = Next; - Prev->NextQh = Qh; + Qh->NextQh = Next; + Prev->NextQh = Qh; - Qh->QhHw.HorizonLink = Prev->QhHw.HorizonLink; - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh, sizeof (EHC_QH)); - Prev->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + Qh->QhHw.HorizonLink = Prev->QhHw.HorizonLink; + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh, sizeof (EHC_QH)); + Prev->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); break; } @@ -467,24 +461,23 @@ EhcLinkQhToPeriod ( // guarranted by 2^n polling interval. // if (Qh->NextQh == NULL) { - Qh->NextQh = Next; - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Next, sizeof (EHC_QH)); - Qh->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + Qh->NextQh = Next; + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Next, sizeof (EHC_QH)); + Qh->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); } PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Qh, sizeof (EHC_QH)); if (Prev == NULL) { - ((UINT32*)Ehc->PeriodFrame)[Index] = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); - ((UINTN*)Ehc->PeriodFrameHost)[Index] = (UINTN)Qh; + ((UINT32 *)Ehc->PeriodFrame)[Index] = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + ((UINTN *)Ehc->PeriodFrameHost)[Index] = (UINTN)Qh; } else { - Prev->NextQh = Qh; - Prev->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); + Prev->NextQh = Qh; + Prev->QhHw.HorizonLink = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); } } } - /** Unlink an interrupt queue head from the periodic schedule frame list. @@ -495,30 +488,30 @@ EhcLinkQhToPeriod ( **/ VOID EhcUnlinkQhFromPeriod ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ) { - UINTN Index; - EHC_QH *Prev; - EHC_QH *This; + UINTN Index; + EHC_QH *Prev; + EHC_QH *This; for (Index = 0; Index < EHC_FRAME_LEN; Index += Qh->Interval) { // // Frame link can't be NULL because we always keep PeroidOne // on the frame list // - ASSERT (!EHC_LINK_TERMINATED (((UINT32*)Ehc->PeriodFrame)[Index])); - This = (EHC_QH*)((UINTN*)Ehc->PeriodFrameHost)[Index]; - Prev = NULL; + ASSERT (!EHC_LINK_TERMINATED (((UINT32 *)Ehc->PeriodFrame)[Index])); + This = (EHC_QH *)((UINTN *)Ehc->PeriodFrameHost)[Index]; + Prev = NULL; // // Walk through the frame's QH list to find the // queue head to remove // while ((This != NULL) && (This != Qh)) { - Prev = This; - This = This->NextQh; + Prev = This; + This = This->NextQh; } // @@ -533,16 +526,15 @@ EhcUnlinkQhFromPeriod ( // // Qh is the first entry in the frame // - ((UINT32*)Ehc->PeriodFrame)[Index] = Qh->QhHw.HorizonLink; - ((UINTN*)Ehc->PeriodFrameHost)[Index] = (UINTN)Qh->NextQh; + ((UINT32 *)Ehc->PeriodFrame)[Index] = Qh->QhHw.HorizonLink; + ((UINTN *)Ehc->PeriodFrameHost)[Index] = (UINTN)Qh->NextQh; } else { - Prev->NextQh = Qh->NextQh; - Prev->QhHw.HorizonLink = Qh->QhHw.HorizonLink; + Prev->NextQh = Qh->NextQh; + Prev->QhHw.HorizonLink = Qh->QhHw.HorizonLink; } } } - /** Check the URB's execution result and update the URB's result accordingly. @@ -555,23 +547,23 @@ EhcUnlinkQhFromPeriod ( **/ BOOLEAN EhcCheckUrbResult ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ) { - LIST_ENTRY *Entry; - EHC_QTD *Qtd; - QTD_HW *QtdHw; - UINT8 State; - BOOLEAN Finished; - EFI_PHYSICAL_ADDRESS PciAddr; + LIST_ENTRY *Entry; + EHC_QTD *Qtd; + QTD_HW *QtdHw; + UINT8 State; + BOOLEAN Finished; + EFI_PHYSICAL_ADDRESS PciAddr; ASSERT ((Ehc != NULL) && (Urb != NULL) && (Urb->Qh != NULL)); - Finished = TRUE; - Urb->Completed = 0; + Finished = TRUE; + Urb->Completed = 0; - Urb->Result = EFI_USB_NOERROR; + Urb->Result = EFI_USB_NOERROR; if (EhcIsHalt (Ehc) || EhcIsSysError (Ehc)) { Urb->Result |= EFI_USB_ERR_SYSTEM; @@ -581,7 +573,7 @@ EhcCheckUrbResult ( BASE_LIST_FOR_EACH (Entry, &Urb->Qh->Qtds) { Qtd = EFI_LIST_CONTAINER (Entry, EHC_QTD, QtdList); QtdHw = &Qtd->QtdHw; - State = (UINT8) QtdHw->Status; + State = (UINT8)QtdHw->Status; if (EHC_BIT_IS_SET (State, QTD_STAT_HALTED)) { // @@ -606,7 +598,6 @@ EhcCheckUrbResult ( Finished = TRUE; goto ON_EXIT; - } else if (EHC_BIT_IS_SET (State, QTD_STAT_ACTIVE)) { // // The QTD is still active, no need to check furthur. @@ -615,7 +606,6 @@ EhcCheckUrbResult ( Finished = FALSE; goto ON_EXIT; - } else { // // This QTD is finished OK or met short packet read. Update the @@ -657,12 +647,11 @@ ON_EXIT: // NOTICE: don't move DT update before the loop, otherwise there is // a race condition that DT is wrong. // - Urb->DataToggle = (UINT8) Urb->Qh->QhHw.DataToggle; + Urb->DataToggle = (UINT8)Urb->Qh->QhHw.DataToggle; return Finished; } - /** Execute the transfer by polling the URB. This is a synchronous operation. @@ -677,16 +666,16 @@ ON_EXIT: **/ EFI_STATUS EhcExecTransfer ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb, - IN UINTN TimeOut + IN USB2_HC_DEV *Ehc, + IN URB *Urb, + IN UINTN TimeOut ) { - EFI_STATUS Status; - UINTN Index; - UINTN Loop; - BOOLEAN Finished; - BOOLEAN InfiniteLoop; + EFI_STATUS Status; + UINTN Index; + UINTN Loop; + BOOLEAN Finished; + BOOLEAN InfiniteLoop; Status = EFI_SUCCESS; Loop = TimeOut * EHC_1_MILLISECOND; @@ -717,7 +706,6 @@ EhcExecTransfer ( EhcDumpQh (Urb->Qh, NULL, FALSE); Status = EFI_TIMEOUT; - } else if (Urb->Result != EFI_USB_NOERROR) { DEBUG ((DEBUG_ERROR, "EhcExecTransfer: transfer failed with %x\n", Urb->Result)); EhcDumpQh (Urb->Qh, NULL, FALSE); @@ -728,7 +716,6 @@ EhcExecTransfer ( return Status; } - /** Delete a single asynchronous interrupt transfer for the device and endpoint. @@ -744,10 +731,10 @@ EhcExecTransfer ( **/ EFI_STATUS EhciDelAsyncIntTransfer ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpNum, - OUT UINT8 *DataToggle + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpNum, + OUT UINT8 *DataToggle ) { LIST_ENTRY *Entry; @@ -762,7 +749,8 @@ EhciDelAsyncIntTransfer ( Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); if ((Urb->Ep.DevAddr == DevAddr) && (Urb->Ep.EpAddr == EpNum) && - (Urb->Ep.Direction == Direction)) { + (Urb->Ep.Direction == Direction)) + { // // Check the URB status to retrieve the next data toggle // from the associated queue head. @@ -782,7 +770,6 @@ EhciDelAsyncIntTransfer ( return EFI_NOT_FOUND; } - /** Remove all the asynchronous interrutp transfers. @@ -791,12 +778,12 @@ EhciDelAsyncIntTransfer ( **/ VOID EhciDelAllAsyncIntTransfers ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ) { - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - URB *Urb; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + URB *Urb; BASE_LIST_FOR_EACH_SAFE (Entry, Next, &Ehc->AsyncIntTransfers) { Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); @@ -830,21 +817,21 @@ EhciDelAllAsyncIntTransfers ( **/ URB * EhciInsertAsyncIntTransfer ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ) { - VOID *Data; - URB *Urb; + VOID *Data; + URB *Urb; Data = AllocatePool (DataLen); @@ -899,16 +886,16 @@ EhciInsertAsyncIntTransfer ( **/ EFI_STATUS EhcFlushAsyncIntMap ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS PhyAddr; - EFI_PCI_IO_PROTOCOL_OPERATION MapOp; - EFI_PCI_IO_PROTOCOL *PciIo; - UINTN Len; - VOID *Map; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_PCI_IO_PROTOCOL_OPERATION MapOp; + EFI_PCI_IO_PROTOCOL *PciIo; + UINTN Len; + VOID *Map; PciIo = Ehc->PciIo; Len = Urb->DataLen; @@ -931,15 +918,14 @@ EhcFlushAsyncIntMap ( goto ON_ERROR; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; return EFI_SUCCESS; ON_ERROR: return EFI_DEVICE_ERROR; } - /** Update the queue head for next round of asynchronous transfer. @@ -949,17 +935,17 @@ ON_ERROR: **/ VOID EhcUpdateAsyncRequest ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ) { - LIST_ENTRY *Entry; - EHC_QTD *FirstQtd; - QH_HW *QhHw; - EHC_QTD *Qtd; - QTD_HW *QtdHw; - UINTN Index; - EFI_PHYSICAL_ADDRESS PciAddr; + LIST_ENTRY *Entry; + EHC_QTD *FirstQtd; + QH_HW *QhHw; + EHC_QTD *Qtd; + QTD_HW *QtdHw; + UINTN Index; + EFI_PHYSICAL_ADDRESS PciAddr; Qtd = NULL; @@ -985,13 +971,13 @@ EhcUpdateAsyncRequest ( QtdHw->Status = QTD_STAT_ACTIVE; QtdHw->ErrCnt = QTD_MAX_ERR; QtdHw->CurPage = 0; - QtdHw->TotalBytes = (UINT32) Qtd->DataLen; + QtdHw->TotalBytes = (UINT32)Qtd->DataLen; // // calculate physical address by offset. // - PciAddr = (UINTN)Urb->DataPhy + ((UINTN)Qtd->Data - (UINTN)Urb->Data); - QtdHw->Page[0] = EHC_LOW_32BIT (PciAddr); - QtdHw->PageHigh[0]= EHC_HIGH_32BIT (PciAddr); + PciAddr = (UINTN)Urb->DataPhy + ((UINTN)Qtd->Data - (UINTN)Urb->Data); + QtdHw->Page[0] = EHC_LOW_32BIT (PciAddr); + QtdHw->PageHigh[0] = EHC_HIGH_32BIT (PciAddr); } // @@ -1000,30 +986,29 @@ EhcUpdateAsyncRequest ( // zero out the overlay area and set NextQtd to the first // QTD. DateToggle bit is left untouched. // - QhHw = &Urb->Qh->QhHw; - QhHw->CurQtd = QTD_LINK (0, TRUE); - QhHw->AltQtd = 0; + QhHw = &Urb->Qh->QhHw; + QhHw->CurQtd = QTD_LINK (0, TRUE); + QhHw->AltQtd = 0; - QhHw->Status = 0; - QhHw->Pid = 0; - QhHw->ErrCnt = 0; - QhHw->CurPage = 0; - QhHw->Ioc = 0; - QhHw->TotalBytes = 0; + QhHw->Status = 0; + QhHw->Pid = 0; + QhHw->ErrCnt = 0; + QhHw->CurPage = 0; + QhHw->Ioc = 0; + QhHw->TotalBytes = 0; for (Index = 0; Index < 5; Index++) { QhHw->Page[Index] = 0; QhHw->PageHigh[Index] = 0; } - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, FirstQtd, sizeof (EHC_QTD)); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, FirstQtd, sizeof (EHC_QTD)); QhHw->NextQtd = QTD_LINK (PciAddr, FALSE); } - return ; + return; } - /** Interrupt transfer periodic check handler. @@ -1034,21 +1019,21 @@ EhcUpdateAsyncRequest ( VOID EFIAPI EhcMonitorAsyncRequests ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB2_HC_DEV *Ehc; - EFI_TPL OldTpl; - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - BOOLEAN Finished; - UINT8 *ProcBuf; - URB *Urb; - EFI_STATUS Status; - - OldTpl = gBS->RaiseTPL (EHC_TPL); - Ehc = (USB2_HC_DEV *) Context; + USB2_HC_DEV *Ehc; + EFI_TPL OldTpl; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + BOOLEAN Finished; + UINT8 *ProcBuf; + URB *Urb; + EFI_STATUS Status; + + OldTpl = gBS->RaiseTPL (EHC_TPL); + Ehc = (USB2_HC_DEV *)Context; BASE_LIST_FOR_EACH_SAFE (Entry, Next, &Ehc->AsyncIntTransfers) { Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); @@ -1113,7 +1098,7 @@ EhcMonitorAsyncRequests ( // his callback. Some drivers may has a lower TPL restriction. // gBS->RestoreTPL (OldTpl); - (Urb->Callback) (ProcBuf, Urb->Completed, Urb->Context, Urb->Result); + (Urb->Callback)(ProcBuf, Urb->Completed, Urb->Context, Urb->Result); OldTpl = gBS->RaiseTPL (EHC_TPL); } diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.h b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.h index 34fb9a3be2..b5fc616952 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciSched.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_SCHED_H_ #define _EFI_EHCI_SCHED_H_ - /** Initialize the schedule data structure such as frame list. @@ -22,10 +21,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EhcInitSched ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - /** Free the schedule data. It may be partially initialized. @@ -34,10 +32,9 @@ EhcInitSched ( **/ VOID EhcFreeSched ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); - /** Link the queue head to the asynchronous schedule list. UEFI only supports one CTRL/BULK transfer at a time @@ -51,11 +48,10 @@ EhcFreeSched ( **/ VOID EhcLinkQhToAsync ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ); - /** Unlink a queue head from the asynchronous schedule list. Need to synchronize with hardware. @@ -66,11 +62,10 @@ EhcLinkQhToAsync ( **/ VOID EhcUnlinkQhFromAsync ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ); - /** Link a queue head for interrupt transfer to the periodic schedule frame list. This code is very much the same as @@ -82,11 +77,10 @@ EhcUnlinkQhFromAsync ( **/ VOID EhcLinkQhToPeriod ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ); - /** Unlink an interrupt queue head from the periodic schedule frame list. @@ -97,12 +91,10 @@ EhcLinkQhToPeriod ( **/ VOID EhcUnlinkQhFromPeriod ( - IN USB2_HC_DEV *Ehc, - IN EHC_QH *Qh + IN USB2_HC_DEV *Ehc, + IN EHC_QH *Qh ); - - /** Execute the transfer by polling the URB. This is a synchronous operation. @@ -117,12 +109,11 @@ EhcUnlinkQhFromPeriod ( **/ EFI_STATUS EhcExecTransfer ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb, - IN UINTN TimeOut + IN USB2_HC_DEV *Ehc, + IN URB *Urb, + IN UINTN TimeOut ); - /** Delete a single asynchronous interrupt transfer for the device and endpoint. @@ -138,13 +129,12 @@ EhcExecTransfer ( **/ EFI_STATUS EhciDelAsyncIntTransfer ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpNum, - OUT UINT8 *DataToggle + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpNum, + OUT UINT8 *DataToggle ); - /** Remove all the asynchronous interrutp transfers. @@ -153,7 +143,7 @@ EhciDelAsyncIntTransfer ( **/ VOID EhciDelAllAsyncIntTransfers ( - IN USB2_HC_DEV *Ehc + IN USB2_HC_DEV *Ehc ); /** @@ -177,17 +167,17 @@ EhciDelAllAsyncIntTransfers ( **/ URB * EhciInsertAsyncIntTransfer ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ); /** @@ -200,8 +190,8 @@ EhciInsertAsyncIntTransfer ( VOID EFIAPI EhcMonitorAsyncRequests ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); #endif diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.c b/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.c index 37cef6d130..a2b0b99d33 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.c @@ -11,7 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Ehci.h" - /** Create a single QTD to hold the data. @@ -28,20 +27,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EHC_QTD * EhcCreateQtd ( - IN USB2_HC_DEV *Ehc, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN UINT8 PktId, - IN UINT8 Toggle, - IN UINTN MaxPacket + IN USB2_HC_DEV *Ehc, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN UINT8 PktId, + IN UINT8 Toggle, + IN UINTN MaxPacket ) { - EHC_QTD *Qtd; - QTD_HW *QtdHw; - UINTN Index; - UINTN Len; - UINTN ThisBufLen; + EHC_QTD *Qtd; + QTD_HW *QtdHw; + UINTN Index; + UINTN Len; + UINTN ThisBufLen; ASSERT (Ehc != NULL); @@ -51,9 +50,9 @@ EhcCreateQtd ( return NULL; } - Qtd->Signature = EHC_QTD_SIG; - Qtd->Data = Data; - Qtd->DataLen = 0; + Qtd->Signature = EHC_QTD_SIG; + Qtd->Data = Data; + Qtd->DataLen = 0; InitializeListHead (&Qtd->QtdList); @@ -79,18 +78,18 @@ EhcCreateQtd ( // compute the offset and clear Reserved fields. This is already // done in the data point. // - QtdHw->Page[Index] = EHC_LOW_32BIT (DataPhy); - QtdHw->PageHigh[Index] = EHC_HIGH_32BIT (DataPhy); + QtdHw->Page[Index] = EHC_LOW_32BIT (DataPhy); + QtdHw->PageHigh[Index] = EHC_HIGH_32BIT (DataPhy); - ThisBufLen = QTD_BUF_LEN - (EHC_LOW_32BIT (DataPhy) & QTD_BUF_MASK); + ThisBufLen = QTD_BUF_LEN - (EHC_LOW_32BIT (DataPhy) & QTD_BUF_MASK); if (Len + ThisBufLen >= DataLen) { Len = DataLen; break; } - Len += ThisBufLen; - Data += ThisBufLen; + Len += ThisBufLen; + Data += ThisBufLen; DataPhy += ThisBufLen; } @@ -104,15 +103,13 @@ EhcCreateQtd ( Len = Len - Len % MaxPacket; } - QtdHw->TotalBytes = (UINT32) Len; + QtdHw->TotalBytes = (UINT32)Len; Qtd->DataLen = Len; } return Qtd; } - - /** Initialize the queue head for interrupt transfer, that is, initialize the following three fields: @@ -126,8 +123,8 @@ EhcCreateQtd ( **/ VOID EhcInitIntQh ( - IN USB_ENDPOINT *Ep, - IN QH_HW *QhHw + IN USB_ENDPOINT *Ep, + IN QH_HW *QhHw ) { // @@ -139,7 +136,7 @@ EhcInitIntQh ( // if (Ep->DevSpeed == EFI_USB_SPEED_HIGH) { QhHw->SMask = QH_MICROFRAME_0; - return ; + return; } // @@ -157,8 +154,6 @@ EhcInitIntQh ( QhHw->CMask = QH_MICROFRAME_3 | QH_MICROFRAME_4 | QH_MICROFRAME_5; } - - /** Allocate and initialize a EHCI queue head. @@ -170,12 +165,12 @@ EhcInitIntQh ( **/ EHC_QH * EhcCreateQh ( - IN USB2_HC_DEV *Ehci, - IN USB_ENDPOINT *Ep + IN USB2_HC_DEV *Ehci, + IN USB_ENDPOINT *Ep ) { - EHC_QH *Qh; - QH_HW *QhHw; + EHC_QH *Qh; + QH_HW *QhHw; Qh = UsbHcAllocateMem (Ehci->MemPool, sizeof (EHC_QH)); @@ -183,68 +178,68 @@ EhcCreateQh ( return NULL; } - Qh->Signature = EHC_QH_SIG; - Qh->NextQh = NULL; - Qh->Interval = Ep->PollRate; + Qh->Signature = EHC_QH_SIG; + Qh->NextQh = NULL; + Qh->Interval = Ep->PollRate; InitializeListHead (&Qh->Qtds); - QhHw = &Qh->QhHw; - QhHw->HorizonLink = QH_LINK (NULL, 0, TRUE); - QhHw->DeviceAddr = Ep->DevAddr; - QhHw->Inactive = 0; - QhHw->EpNum = Ep->EpAddr; - QhHw->EpSpeed = Ep->DevSpeed; - QhHw->DtCtrl = 0; - QhHw->ReclaimHead = 0; - QhHw->MaxPacketLen = (UINT32) Ep->MaxPacket; - QhHw->CtrlEp = 0; - QhHw->NakReload = QH_NAK_RELOAD; - QhHw->HubAddr = Ep->HubAddr; - QhHw->PortNum = Ep->HubPort; - QhHw->Multiplier = 1; - QhHw->DataToggle = Ep->Toggle; + QhHw = &Qh->QhHw; + QhHw->HorizonLink = QH_LINK (NULL, 0, TRUE); + QhHw->DeviceAddr = Ep->DevAddr; + QhHw->Inactive = 0; + QhHw->EpNum = Ep->EpAddr; + QhHw->EpSpeed = Ep->DevSpeed; + QhHw->DtCtrl = 0; + QhHw->ReclaimHead = 0; + QhHw->MaxPacketLen = (UINT32)Ep->MaxPacket; + QhHw->CtrlEp = 0; + QhHw->NakReload = QH_NAK_RELOAD; + QhHw->HubAddr = Ep->HubAddr; + QhHw->PortNum = Ep->HubPort; + QhHw->Multiplier = 1; + QhHw->DataToggle = Ep->Toggle; if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { QhHw->Status |= QTD_STAT_DO_SS; } switch (Ep->Type) { - case EHC_CTRL_TRANSFER: - // - // Special initialization for the control transfer: - // 1. Control transfer initialize data toggle from each QTD - // 2. Set the Control Endpoint Flag (C) for low/full speed endpoint. - // - QhHw->DtCtrl = 1; + case EHC_CTRL_TRANSFER: + // + // Special initialization for the control transfer: + // 1. Control transfer initialize data toggle from each QTD + // 2. Set the Control Endpoint Flag (C) for low/full speed endpoint. + // + QhHw->DtCtrl = 1; - if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { - QhHw->CtrlEp = 1; - } - break; + if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { + QhHw->CtrlEp = 1; + } - case EHC_INT_TRANSFER_ASYNC: - case EHC_INT_TRANSFER_SYNC: - // - // Special initialization for the interrupt transfer - // to set the S-Mask and C-Mask - // - QhHw->NakReload = 0; - EhcInitIntQh (Ep, QhHw); - break; + break; - case EHC_BULK_TRANSFER: - if ((Ep->DevSpeed == EFI_USB_SPEED_HIGH) && (Ep->Direction == EfiUsbDataOut)) { - QhHw->Status |= QTD_STAT_DO_PING; - } + case EHC_INT_TRANSFER_ASYNC: + case EHC_INT_TRANSFER_SYNC: + // + // Special initialization for the interrupt transfer + // to set the S-Mask and C-Mask + // + QhHw->NakReload = 0; + EhcInitIntQh (Ep, QhHw); + break; + + case EHC_BULK_TRANSFER: + if ((Ep->DevSpeed == EFI_USB_SPEED_HIGH) && (Ep->Direction == EfiUsbDataOut)) { + QhHw->Status |= QTD_STAT_DO_PING; + } - break; + break; } return Qh; } - /** Convert the poll interval from application to that be used by EHCI interface data structure. Only need @@ -260,10 +255,10 @@ EhcCreateQh ( **/ UINTN EhcConvertPollRate ( - IN UINTN Interval + IN UINTN Interval ) { - UINTN BitCount; + UINTN BitCount; if (Interval == 0) { return 1; @@ -282,7 +277,6 @@ EhcConvertPollRate ( return (UINTN)1 << (BitCount - 1); } - /** Free a list of QTDs. @@ -292,13 +286,13 @@ EhcConvertPollRate ( **/ VOID EhcFreeQtds ( - IN USB2_HC_DEV *Ehc, - IN LIST_ENTRY *Qtds + IN USB2_HC_DEV *Ehc, + IN LIST_ENTRY *Qtds ) { - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - EHC_QTD *Qtd; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + EHC_QTD *Qtd; BASE_LIST_FOR_EACH_SAFE (Entry, Next, Qtds) { Qtd = EFI_LIST_CONTAINER (Entry, EHC_QTD, QtdList); @@ -308,7 +302,6 @@ EhcFreeQtds ( } } - /** Free an allocated URB. It is possible for it to be partially inited. @@ -318,11 +311,11 @@ EhcFreeQtds ( **/ VOID EhcFreeUrb ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; PciIo = Ehc->PciIo; @@ -346,7 +339,6 @@ EhcFreeUrb ( gBS->FreePool (Urb); } - /** Create a list of QTDs for the URB. @@ -359,21 +351,21 @@ EhcFreeUrb ( **/ EFI_STATUS EhcCreateQtds ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ) { - USB_ENDPOINT *Ep; - EHC_QH *Qh; - EHC_QTD *Qtd; - EHC_QTD *StatusQtd; - EHC_QTD *NextQtd; - LIST_ENTRY *Entry; - UINT32 AlterNext; - UINT8 Toggle; - UINTN Len; - UINT8 Pid; - EFI_PHYSICAL_ADDRESS PhyAddr; + USB_ENDPOINT *Ep; + EHC_QH *Qh; + EHC_QTD *Qtd; + EHC_QTD *StatusQtd; + EHC_QTD *NextQtd; + LIST_ENTRY *Entry; + UINT32 AlterNext; + UINT8 Toggle; + UINTN Len; + UINT8 Pid; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT ((Urb != NULL) && (Urb->Qh != NULL)); @@ -389,7 +381,7 @@ EhcCreateQtds ( StatusQtd = NULL; AlterNext = QTD_LINK (NULL, TRUE); - PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->ShortReadStop, sizeof (EHC_QTD)); + PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->ShortReadStop, sizeof (EHC_QTD)); if (Ep->Direction == EfiUsbDataIn) { AlterNext = QTD_LINK (PhyAddr, FALSE); } @@ -448,8 +440,8 @@ EhcCreateQtds ( while (Len < Urb->DataLen) { Qtd = EhcCreateQtd ( Ehc, - (UINT8 *) Urb->Data + Len, - (UINT8 *) Urb->DataPhy + Len, + (UINT8 *)Urb->Data + Len, + (UINT8 *)Urb->DataPhy + Len, Urb->DataLen - Len, Pid, Toggle, @@ -467,7 +459,7 @@ EhcCreateQtds ( // Switch the Toggle bit if odd number of packets are included in the QTD. // if (((Qtd->DataLen + Ep->MaxPacket - 1) / Ep->MaxPacket) % 2) { - Toggle = (UINT8) (1 - Toggle); + Toggle = (UINT8)(1 - Toggle); } Len += Qtd->DataLen; @@ -493,17 +485,17 @@ EhcCreateQtds ( break; } - NextQtd = EFI_LIST_CONTAINER (Entry->ForwardLink, EHC_QTD, QtdList); - PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, NextQtd, sizeof (EHC_QTD)); - Qtd->QtdHw.NextQtd = QTD_LINK (PhyAddr, FALSE); + NextQtd = EFI_LIST_CONTAINER (Entry->ForwardLink, EHC_QTD, QtdList); + PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, NextQtd, sizeof (EHC_QTD)); + Qtd->QtdHw.NextQtd = QTD_LINK (PhyAddr, FALSE); } // // Link the QTDs to the queue head // - NextQtd = EFI_LIST_CONTAINER (Qh->Qtds.ForwardLink, EHC_QTD, QtdList); - PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, NextQtd, sizeof (EHC_QTD)); - Qh->QhHw.NextQtd = QTD_LINK (PhyAddr, FALSE); + NextQtd = EFI_LIST_CONTAINER (Qh->Qtds.ForwardLink, EHC_QTD, QtdList); + PhyAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, NextQtd, sizeof (EHC_QTD)); + Qh->QhHw.NextQtd = QTD_LINK (PhyAddr, FALSE); return EFI_SUCCESS; ON_ERROR: @@ -511,7 +503,6 @@ ON_ERROR: return EFI_OUT_OF_RESOURCES; } - /** Create a new URB and its associated QTD. @@ -535,30 +526,30 @@ ON_ERROR: **/ URB * EhcCreateUrb ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ) { - USB_ENDPOINT *Ep; - EFI_PHYSICAL_ADDRESS PhyAddr; - EFI_PCI_IO_PROTOCOL_OPERATION MapOp; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINTN Len; - URB *Urb; - VOID *Map; + USB_ENDPOINT *Ep; + EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_PCI_IO_PROTOCOL_OPERATION MapOp; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINTN Len; + URB *Urb; + VOID *Map; Urb = AllocateZeroPool (sizeof (URB)); @@ -566,38 +557,38 @@ EhcCreateUrb ( return NULL; } - Urb->Signature = EHC_URB_SIG; + Urb->Signature = EHC_URB_SIG; InitializeListHead (&Urb->UrbList); - Ep = &Urb->Ep; - Ep->DevAddr = DevAddr; - Ep->EpAddr = (UINT8) (EpAddr & 0x0F); - Ep->Direction = (((EpAddr & 0x80) != 0) ? EfiUsbDataIn : EfiUsbDataOut); - Ep->DevSpeed = DevSpeed; - Ep->MaxPacket = MaxPacket; + Ep = &Urb->Ep; + Ep->DevAddr = DevAddr; + Ep->EpAddr = (UINT8)(EpAddr & 0x0F); + Ep->Direction = (((EpAddr & 0x80) != 0) ? EfiUsbDataIn : EfiUsbDataOut); + Ep->DevSpeed = DevSpeed; + Ep->MaxPacket = MaxPacket; - Ep->HubAddr = 0; - Ep->HubPort = 0; + Ep->HubAddr = 0; + Ep->HubPort = 0; if (DevSpeed != EFI_USB_SPEED_HIGH) { ASSERT (Hub != NULL); - Ep->HubAddr = Hub->TranslatorHubAddress; - Ep->HubPort = Hub->TranslatorPortNumber; + Ep->HubAddr = Hub->TranslatorHubAddress; + Ep->HubPort = Hub->TranslatorPortNumber; } - Ep->Toggle = Toggle; - Ep->Type = Type; - Ep->PollRate = EhcConvertPollRate (Interval); + Ep->Toggle = Toggle; + Ep->Type = Type; + Ep->PollRate = EhcConvertPollRate (Interval); - Urb->Request = Request; - Urb->Data = Data; - Urb->DataLen = DataLen; - Urb->Callback = Callback; - Urb->Context = Context; + Urb->Request = Request; + Urb->Data = Data; + Urb->DataLen = DataLen; + Urb->Callback = Callback; + Urb->Context = Context; - PciIo = Ehc->PciIo; - Urb->Qh = EhcCreateQh (Ehc, &Urb->Ep); + PciIo = Ehc->PciIo; + Urb->Qh = EhcCreateQh (Ehc, &Urb->Ep); if (Urb->Qh == NULL) { goto ON_ERROR; @@ -607,20 +598,20 @@ EhcCreateUrb ( // Map the request and user data // if (Request != NULL) { - Len = sizeof (EFI_USB_DEVICE_REQUEST); - MapOp = EfiPciIoOperationBusMasterRead; - Status = PciIo->Map (PciIo, MapOp, Request, &Len, &PhyAddr, &Map); + Len = sizeof (EFI_USB_DEVICE_REQUEST); + MapOp = EfiPciIoOperationBusMasterRead; + Status = PciIo->Map (PciIo, MapOp, Request, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != sizeof (EFI_USB_DEVICE_REQUEST))) { goto ON_ERROR; } - Urb->RequestPhy = (VOID *) ((UINTN) PhyAddr); + Urb->RequestPhy = (VOID *)((UINTN)PhyAddr); Urb->RequestMap = Map; } if (Data != NULL) { - Len = DataLen; + Len = DataLen; if (Ep->Direction == EfiUsbDataIn) { MapOp = EfiPciIoOperationBusMasterWrite; @@ -628,14 +619,14 @@ EhcCreateUrb ( MapOp = EfiPciIoOperationBusMasterRead; } - Status = PciIo->Map (PciIo, MapOp, Data, &Len, &PhyAddr, &Map); + Status = PciIo->Map (PciIo, MapOp, Data, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != DataLen)) { goto ON_ERROR; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; } Status = EhcCreateQtds (Ehc, Urb); diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.h b/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.h index 6342bf6b1c..ae8bfc2ba7 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/EhciUrb.h @@ -11,7 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_URB_H_ #define _EFI_EHCI_URB_H_ - typedef struct _EHC_QTD EHC_QTD; typedef struct _EHC_QH EHC_QH; typedef struct _URB URB; @@ -24,51 +23,51 @@ typedef struct _URB URB; #define EHC_INT_TRANSFER_SYNC 0x04 #define EHC_INT_TRANSFER_ASYNC 0x08 -#define EHC_QTD_SIG SIGNATURE_32 ('U', 'S', 'B', 'T') -#define EHC_QH_SIG SIGNATURE_32 ('U', 'S', 'B', 'H') -#define EHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') +#define EHC_QTD_SIG SIGNATURE_32 ('U', 'S', 'B', 'T') +#define EHC_QH_SIG SIGNATURE_32 ('U', 'S', 'B', 'H') +#define EHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') // // Hardware related bit definitions // -#define EHC_TYPE_ITD 0x00 -#define EHC_TYPE_QH 0x02 -#define EHC_TYPE_SITD 0x04 -#define EHC_TYPE_FSTN 0x06 - -#define QH_NAK_RELOAD 3 -#define QH_HSHBW_MULTI 1 - -#define QTD_MAX_ERR 3 -#define QTD_PID_OUTPUT 0x00 -#define QTD_PID_INPUT 0x01 -#define QTD_PID_SETUP 0x02 - -#define QTD_STAT_DO_OUT 0 -#define QTD_STAT_DO_SS 0 -#define QTD_STAT_DO_PING 0x01 -#define QTD_STAT_DO_CS 0x02 -#define QTD_STAT_TRANS_ERR 0x08 -#define QTD_STAT_BABBLE_ERR 0x10 -#define QTD_STAT_BUFF_ERR 0x20 -#define QTD_STAT_HALTED 0x40 -#define QTD_STAT_ACTIVE 0x80 -#define QTD_STAT_ERR_MASK (QTD_STAT_TRANS_ERR | QTD_STAT_BABBLE_ERR | QTD_STAT_BUFF_ERR) - -#define QTD_MAX_BUFFER 4 -#define QTD_BUF_LEN 4096 -#define QTD_BUF_MASK 0x0FFF - -#define QH_MICROFRAME_0 0x01 -#define QH_MICROFRAME_1 0x02 -#define QH_MICROFRAME_2 0x04 -#define QH_MICROFRAME_3 0x08 -#define QH_MICROFRAME_4 0x10 -#define QH_MICROFRAME_5 0x20 -#define QH_MICROFRAME_6 0x40 -#define QH_MICROFRAME_7 0x80 - -#define USB_ERR_SHORT_PACKET 0x200 +#define EHC_TYPE_ITD 0x00 +#define EHC_TYPE_QH 0x02 +#define EHC_TYPE_SITD 0x04 +#define EHC_TYPE_FSTN 0x06 + +#define QH_NAK_RELOAD 3 +#define QH_HSHBW_MULTI 1 + +#define QTD_MAX_ERR 3 +#define QTD_PID_OUTPUT 0x00 +#define QTD_PID_INPUT 0x01 +#define QTD_PID_SETUP 0x02 + +#define QTD_STAT_DO_OUT 0 +#define QTD_STAT_DO_SS 0 +#define QTD_STAT_DO_PING 0x01 +#define QTD_STAT_DO_CS 0x02 +#define QTD_STAT_TRANS_ERR 0x08 +#define QTD_STAT_BABBLE_ERR 0x10 +#define QTD_STAT_BUFF_ERR 0x20 +#define QTD_STAT_HALTED 0x40 +#define QTD_STAT_ACTIVE 0x80 +#define QTD_STAT_ERR_MASK (QTD_STAT_TRANS_ERR | QTD_STAT_BABBLE_ERR | QTD_STAT_BUFF_ERR) + +#define QTD_MAX_BUFFER 4 +#define QTD_BUF_LEN 4096 +#define QTD_BUF_MASK 0x0FFF + +#define QH_MICROFRAME_0 0x01 +#define QH_MICROFRAME_1 0x02 +#define QH_MICROFRAME_2 0x04 +#define QH_MICROFRAME_3 0x08 +#define QH_MICROFRAME_4 0x10 +#define QH_MICROFRAME_5 0x20 +#define QH_MICROFRAME_6 0x40 +#define QH_MICROFRAME_7 0x80 + +#define USB_ERR_SHORT_PACKET 0x200 // // Fill in the hardware link point: pass in a EHC_QH/QH_HW @@ -77,7 +76,7 @@ typedef struct _URB URB; #define QH_LINK(Addr, Type, Term) \ ((UINT32) ((EHC_LOW_32BIT (Addr) & 0xFFFFFFE0) | (Type) | ((Term) ? 1 : 0))) -#define QTD_LINK(Addr, Term) QH_LINK((Addr), 0, (Term)) +#define QTD_LINK(Addr, Term) QH_LINK((Addr), 0, (Term)) // // The defination of EHCI hardware used data structure for @@ -87,77 +86,76 @@ typedef struct _URB URB; // #pragma pack(1) typedef struct { - UINT32 NextQtd; - UINT32 AltNext; - - UINT32 Status : 8; - UINT32 Pid : 2; - UINT32 ErrCnt : 2; - UINT32 CurPage : 3; - UINT32 Ioc : 1; - UINT32 TotalBytes : 15; - UINT32 DataToggle : 1; - - UINT32 Page[5]; - UINT32 PageHigh[5]; + UINT32 NextQtd; + UINT32 AltNext; + + UINT32 Status : 8; + UINT32 Pid : 2; + UINT32 ErrCnt : 2; + UINT32 CurPage : 3; + UINT32 Ioc : 1; + UINT32 TotalBytes : 15; + UINT32 DataToggle : 1; + + UINT32 Page[5]; + UINT32 PageHigh[5]; } QTD_HW; typedef struct { - UINT32 HorizonLink; + UINT32 HorizonLink; // // Endpoint capabilities/Characteristics DWord 1 and DWord 2 // - UINT32 DeviceAddr : 7; - UINT32 Inactive : 1; - UINT32 EpNum : 4; - UINT32 EpSpeed : 2; - UINT32 DtCtrl : 1; - UINT32 ReclaimHead : 1; - UINT32 MaxPacketLen : 11; - UINT32 CtrlEp : 1; - UINT32 NakReload : 4; - - UINT32 SMask : 8; - UINT32 CMask : 8; - UINT32 HubAddr : 7; - UINT32 PortNum : 7; - UINT32 Multiplier : 2; + UINT32 DeviceAddr : 7; + UINT32 Inactive : 1; + UINT32 EpNum : 4; + UINT32 EpSpeed : 2; + UINT32 DtCtrl : 1; + UINT32 ReclaimHead : 1; + UINT32 MaxPacketLen : 11; + UINT32 CtrlEp : 1; + UINT32 NakReload : 4; + + UINT32 SMask : 8; + UINT32 CMask : 8; + UINT32 HubAddr : 7; + UINT32 PortNum : 7; + UINT32 Multiplier : 2; // // Transaction execution overlay area // - UINT32 CurQtd; - UINT32 NextQtd; - UINT32 AltQtd; - - UINT32 Status : 8; - UINT32 Pid : 2; - UINT32 ErrCnt : 2; - UINT32 CurPage : 3; - UINT32 Ioc : 1; - UINT32 TotalBytes : 15; - UINT32 DataToggle : 1; - - UINT32 Page[5]; - UINT32 PageHigh[5]; + UINT32 CurQtd; + UINT32 NextQtd; + UINT32 AltQtd; + + UINT32 Status : 8; + UINT32 Pid : 2; + UINT32 ErrCnt : 2; + UINT32 CurPage : 3; + UINT32 Ioc : 1; + UINT32 TotalBytes : 15; + UINT32 DataToggle : 1; + + UINT32 Page[5]; + UINT32 PageHigh[5]; } QH_HW; #pragma pack() - // // Endpoint address and its capabilities // typedef struct _USB_ENDPOINT { - UINT8 DevAddr; - UINT8 EpAddr; // Endpoint address, no direction encoded in - EFI_USB_DATA_DIRECTION Direction; - UINT8 DevSpeed; - UINTN MaxPacket; - UINT8 HubAddr; - UINT8 HubPort; - UINT8 Toggle; // Data toggle, not used for control transfer - UINTN Type; - UINTN PollRate; // Polling interval used by EHCI + UINT8 DevAddr; + UINT8 EpAddr; // Endpoint address, no direction encoded in + EFI_USB_DATA_DIRECTION Direction; + UINT8 DevSpeed; + UINTN MaxPacket; + UINT8 HubAddr; + UINT8 HubPort; + UINT8 Toggle; // Data toggle, not used for control transfer + UINTN Type; + UINTN PollRate; // Polling interval used by EHCI } USB_ENDPOINT; // @@ -165,11 +163,11 @@ typedef struct _USB_ENDPOINT { // QTD generated from a URB. Don't add fields before QtdHw. // struct _EHC_QTD { - QTD_HW QtdHw; - UINT32 Signature; - LIST_ENTRY QtdList; // The list of QTDs to one end point - UINT8 *Data; // Buffer of the original data - UINTN DataLen; // Original amount of data in this QTD + QTD_HW QtdHw; + UINT32 Signature; + LIST_ENTRY QtdList; // The list of QTDs to one end point + UINT8 *Data; // Buffer of the original data + UINTN DataLen; // Original amount of data in this QTD }; // @@ -188,11 +186,11 @@ struct _EHC_QTD { // as the reclamation header. New transfer is inserted after this QH. // struct _EHC_QH { - QH_HW QhHw; - UINT32 Signature; - EHC_QH *NextQh; // The queue head pointed to by horizontal link - LIST_ENTRY Qtds; // The list of QTDs to this queue head - UINTN Interval; + QH_HW QhHw; + UINT32 Signature; + EHC_QH *NextQh; // The queue head pointed to by horizontal link + LIST_ENTRY Qtds; // The list of QTDs to this queue head + UINTN Interval; }; // @@ -200,38 +198,36 @@ struct _EHC_QH { // usb requests. // struct _URB { - UINT32 Signature; - LIST_ENTRY UrbList; + UINT32 Signature; + LIST_ENTRY UrbList; // // Transaction information // - USB_ENDPOINT Ep; - EFI_USB_DEVICE_REQUEST *Request; // Control transfer only - VOID *RequestPhy; // Address of the mapped request - VOID *RequestMap; - VOID *Data; - UINTN DataLen; - VOID *DataPhy; // Address of the mapped user data - VOID *DataMap; - EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; - VOID *Context; + USB_ENDPOINT Ep; + EFI_USB_DEVICE_REQUEST *Request; // Control transfer only + VOID *RequestPhy; // Address of the mapped request + VOID *RequestMap; + VOID *Data; + UINTN DataLen; + VOID *DataPhy; // Address of the mapped user data + VOID *DataMap; + EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; + VOID *Context; // // Schedule data // - EHC_QH *Qh; + EHC_QH *Qh; // // Transaction result // - UINT32 Result; - UINTN Completed; // completed data length - UINT8 DataToggle; + UINT32 Result; + UINTN Completed; // completed data length + UINT8 DataToggle; }; - - /** Create a single QTD to hold the data. @@ -248,17 +244,15 @@ struct _URB { **/ EHC_QTD * EhcCreateQtd ( - IN USB2_HC_DEV *Ehc, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN UINT8 PktId, - IN UINT8 Toggle, - IN UINTN MaxPacket + IN USB2_HC_DEV *Ehc, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN UINT8 PktId, + IN UINT8 Toggle, + IN UINTN MaxPacket ); - - /** Allocate and initialize a EHCI queue head. @@ -270,11 +264,10 @@ EhcCreateQtd ( **/ EHC_QH * EhcCreateQh ( - IN USB2_HC_DEV *Ehci, - IN USB_ENDPOINT *Ep + IN USB2_HC_DEV *Ehci, + IN USB_ENDPOINT *Ep ); - /** Free an allocated URB. It is possible for it to be partially inited. @@ -284,11 +277,10 @@ EhcCreateQh ( **/ VOID EhcFreeUrb ( - IN USB2_HC_DEV *Ehc, - IN URB *Urb + IN USB2_HC_DEV *Ehc, + IN URB *Urb ); - /** Create a new URB and its associated QTD. @@ -312,19 +304,20 @@ EhcFreeUrb ( **/ URB * EhcCreateUrb ( - IN USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ); + #endif diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.c b/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.c index f39d0b57c0..0a3ceb9f71 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.c @@ -7,10 +7,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Ehci.h" - /** Allocate a block of memory to be used by the buffer pool. @@ -22,17 +20,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USBHC_MEM_BLOCK * UsbHcAllocMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Pages + IN USBHC_MEM_POOL *Pool, + IN UINTN Pages ) { - USBHC_MEM_BLOCK *Block; - EFI_PCI_IO_PROTOCOL *PciIo; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - UINTN Bytes; - EFI_STATUS Status; + USBHC_MEM_BLOCK *Block; + EFI_PCI_IO_PROTOCOL *PciIo; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + UINTN Bytes; + EFI_STATUS Status; PciIo = Pool->PciIo; @@ -47,9 +45,9 @@ UsbHcAllocMemBlock ( // ASSERT (USBHC_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); - Block->Bits = AllocateZeroPool (Block->BitsLen); + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); + Block->Bits = AllocateZeroPool (Block->BitsLen); if (Block->Bits == NULL) { gBS->FreePool (Block); @@ -73,7 +71,7 @@ UsbHcAllocMemBlock ( goto FREE_BITARRAY; } - Bytes = EFI_PAGES_TO_SIZE (Pages); + Bytes = EFI_PAGES_TO_SIZE (Pages); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, @@ -96,9 +94,9 @@ UsbHcAllocMemBlock ( goto FREE_BUFFER; } - Block->BufHost = BufHost; - Block->Buf = (UINT8 *) ((UINTN) MappedAddr); - Block->Mapping = Mapping; + Block->BufHost = BufHost; + Block->Buf = (UINT8 *)((UINTN)MappedAddr); + Block->Mapping = Mapping; return Block; @@ -111,7 +109,6 @@ FREE_BITARRAY: return NULL; } - /** Free the memory block from the memory pool. @@ -121,11 +118,11 @@ FREE_BITARRAY: **/ VOID UsbHcFreeMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_POOL *Pool, + IN USBHC_MEM_BLOCK *Block ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; ASSERT ((Pool != NULL) && (Block != NULL)); @@ -141,7 +138,6 @@ UsbHcFreeMemBlock ( gBS->FreePool (Block); } - /** Alloc some memory from the block. @@ -154,22 +150,22 @@ UsbHcFreeMemBlock ( **/ VOID * UsbHcAllocMemFromBlock ( - IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN USBHC_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -185,13 +181,12 @@ UsbHcAllocMemFromBlock ( } NEXT_BIT (Byte, Bit); - } else { NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -202,13 +197,13 @@ UsbHcAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -226,16 +221,16 @@ UsbHcAllocMemFromBlock ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINTN AllocSize; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINTN Offset; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINTN AllocSize; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINTN Offset; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); @@ -249,7 +244,7 @@ UsbHcGetPciAddressForHostMem ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->BufHost <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { + if ((Block->BufHost <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { break; } } @@ -258,12 +253,11 @@ UsbHcGetPciAddressForHostMem ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *)Mem - Block->BufHost; - PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN) (Block->Buf + Offset); + Offset = (UINT8 *)Mem - Block->BufHost; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->Buf + Offset); return PhyAddr; } - /** Insert the memory block to the pool's list of the blocks. @@ -273,8 +267,8 @@ UsbHcGetPciAddressForHostMem ( **/ VOID UsbHcInsertMemBlockToPool ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -282,7 +276,6 @@ UsbHcInsertMemBlockToPool ( Head->Next = Block; } - /** Is the memory block empty? @@ -294,10 +287,10 @@ UsbHcInsertMemBlockToPool ( **/ BOOLEAN UsbHcIsMemBlockEmpty ( - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Block ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -308,7 +301,6 @@ UsbHcIsMemBlockEmpty ( return TRUE; } - /** Unlink the memory block from the pool's list. @@ -318,11 +310,11 @@ UsbHcIsMemBlockEmpty ( **/ VOID UsbHcUnlinkMemBlock ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *BlockToUnlink + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *BlockToUnlink ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT ((Head != NULL) && (BlockToUnlink != NULL)); @@ -335,7 +327,6 @@ UsbHcUnlinkMemBlock ( } } - /** Initialize the memory management pool for the host controller. @@ -355,7 +346,7 @@ UsbHcInitMemPool ( IN UINT32 Which4G ) { - USBHC_MEM_POOL *Pool; + USBHC_MEM_POOL *Pool; Pool = AllocatePool (sizeof (USBHC_MEM_POOL)); @@ -376,7 +367,6 @@ UsbHcInitMemPool ( return Pool; } - /** Release the memory management pool. @@ -388,10 +378,10 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -410,7 +400,6 @@ UsbHcFreeMemPool ( return EFI_SUCCESS; } - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -423,16 +412,16 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - USBHC_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = USBHC_MEM_ROUND (Size); @@ -487,7 +476,6 @@ UsbHcAllocateMem ( return Mem; } - /** Free the allocated memory back to the memory pool. @@ -498,22 +486,22 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -524,8 +512,8 @@ UsbHcFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; - Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; + Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; + Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -533,7 +521,7 @@ UsbHcFreeMem ( for (Count = 0; Count < (AllocSize / USBHC_MEM_UNIT); Count++) { ASSERT (USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -556,5 +544,5 @@ UsbHcFreeMem ( UsbHcFreeMemBlock (Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.h b/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.h index ace20832c1..999e795386 100644 --- a/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/EhciDxe/UsbHcMem.h @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_MEM_H_ #define _EFI_EHCI_MEM_H_ -#define USB_HC_BIT(a) ((UINTN)(1 << (a))) +#define USB_HC_BIT(a) ((UINTN)(1 << (a))) #define USB_HC_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & USB_HC_BIT(Bit)) == USB_HC_BIT(Bit))) @@ -20,13 +20,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _USBHC_MEM_BLOCK USBHC_MEM_BLOCK; struct _USBHC_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - USBHC_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + USBHC_MEM_BLOCK *Next; }; // @@ -35,16 +35,16 @@ struct _USBHC_MEM_BLOCK { // data to be on the same 4G memory. // typedef struct _USBHC_MEM_POOL { - EFI_PCI_IO_PROTOCOL *PciIo; - BOOLEAN Check4G; - UINT32 Which4G; - USBHC_MEM_BLOCK *Head; + EFI_PCI_IO_PROTOCOL *PciIo; + BOOLEAN Check4G; + UINT32 Which4G; + USBHC_MEM_BLOCK *Head; } USBHC_MEM_POOL; // // Memory allocation unit, must be 2^n, n>4 // -#define USBHC_MEM_UNIT 64 +#define USBHC_MEM_UNIT 64 #define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) #define USBHC_MEM_DEFAULT_PAGES 16 @@ -63,8 +63,6 @@ typedef struct _USBHC_MEM_POOL { } \ } while (0) - - /** Initialize the memory management pool for the host controller. @@ -84,7 +82,6 @@ UsbHcInitMemPool ( IN UINT32 Which4G ); - /** Release the memory management pool. @@ -96,10 +93,9 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ); - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -112,11 +108,10 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ); - /** Free the allocated memory back to the memory pool. @@ -127,9 +122,9 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -143,9 +138,9 @@ UsbHcFreeMem ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); #endif diff --git a/MdeModulePkg/Bus/Pci/EhciPei/DmaMem.c b/MdeModulePkg/Bus/Pci/EhciPei/DmaMem.c index 63870a129a..320fb30bc1 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/DmaMem.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/DmaMem.c @@ -39,8 +39,8 @@ IoMmuMap ( OUT VOID **Mapping ) { - EFI_STATUS Status; - UINT64 Attribute; + EFI_STATUS Status; + UINT64 Attribute; if (IoMmu != NULL) { Status = IoMmu->Map ( @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -82,10 +84,11 @@ IoMmuMap ( return Status; } } else { - *DeviceAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,8 +101,8 @@ IoMmuMap ( **/ VOID IoMmuUnmap ( - IN EDKII_IOMMU_PPI *IoMmu, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN VOID *Mapping ) { if (IoMmu != NULL) { @@ -140,9 +143,9 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; - *Mapping = NULL; + *Mapping = NULL; if (IoMmu != NULL) { Status = IoMmu->AllocateBuffer ( @@ -157,19 +160,20 @@ IoMmuAllocateBuffer ( } NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); - Status = IoMmu->Map ( - IoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + Status = IoMmu->Map ( + IoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { IoMmu->FreeBuffer (IoMmu, Pages, *HostAddress); *HostAddress = NULL; return EFI_OUT_OF_RESOURCES; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -178,7 +182,7 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { IoMmu->Unmap (IoMmu, *Mapping); IoMmu->FreeBuffer (IoMmu, Pages, *HostAddress); - *Mapping = NULL; + *Mapping = NULL; *HostAddress = NULL; return Status; } @@ -191,10 +195,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *) (UINTN) HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -209,10 +215,10 @@ IoMmuAllocateBuffer ( **/ VOID IoMmuFreeBuffer ( - IN EDKII_IOMMU_PPI *IoMmu, - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { if (IoMmu != NULL) { @@ -230,14 +236,13 @@ IoMmuFreeBuffer ( **/ VOID IoMmuInit ( - OUT EDKII_IOMMU_PPI **IoMmu + OUT EDKII_IOMMU_PPI **IoMmu ) { PeiServicesLocatePpi ( &gEdkiiIoMmuPpiGuid, 0, NULL, - (VOID **) IoMmu + (VOID **)IoMmu ); } - diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.c b/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.c index cd1f87911b..37dd9012e2 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.c @@ -15,19 +15,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // to the UEFI protocol's port state (change). // USB_PORT_STATE_MAP mUsbPortStateMap[] = { - {PORTSC_CONN, USB_PORT_STAT_CONNECTION}, - {PORTSC_ENABLED, USB_PORT_STAT_ENABLE}, - {PORTSC_SUSPEND, USB_PORT_STAT_SUSPEND}, - {PORTSC_OVERCUR, USB_PORT_STAT_OVERCURRENT}, - {PORTSC_RESET, USB_PORT_STAT_RESET}, - {PORTSC_POWER, USB_PORT_STAT_POWER}, - {PORTSC_OWNER, USB_PORT_STAT_OWNER} + { PORTSC_CONN, USB_PORT_STAT_CONNECTION }, + { PORTSC_ENABLED, USB_PORT_STAT_ENABLE }, + { PORTSC_SUSPEND, USB_PORT_STAT_SUSPEND }, + { PORTSC_OVERCUR, USB_PORT_STAT_OVERCURRENT }, + { PORTSC_RESET, USB_PORT_STAT_RESET }, + { PORTSC_POWER, USB_PORT_STAT_POWER }, + { PORTSC_OWNER, USB_PORT_STAT_OWNER } }; USB_PORT_STATE_MAP mUsbPortChangeMap[] = { - {PORTSC_CONN_CHANGE, USB_PORT_STAT_C_CONNECTION}, - {PORTSC_ENABLE_CHANGE, USB_PORT_STAT_C_ENABLE}, - {PORTSC_OVERCUR_CHANGE, USB_PORT_STAT_C_OVERCURRENT} + { PORTSC_CONN_CHANGE, USB_PORT_STAT_C_CONNECTION }, + { PORTSC_ENABLE_CHANGE, USB_PORT_STAT_C_ENABLE }, + { PORTSC_OVERCUR_CHANGE, USB_PORT_STAT_C_OVERCURRENT } }; /** @@ -41,11 +41,11 @@ USB_PORT_STATE_MAP mUsbPortChangeMap[] = { **/ UINT32 EhcReadOpReg ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; ASSERT (Ehc->CapLen != 0); @@ -64,16 +64,14 @@ EhcReadOpReg ( **/ VOID EhcWriteOpReg ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Data ) { - ASSERT (Ehc->CapLen != 0); - MmioWrite32(Ehc->UsbHostControllerBaseAddress + Ehc->CapLen + Offset, Data); - + MmioWrite32 (Ehc->UsbHostControllerBaseAddress + Ehc->CapLen + Offset, Data); } /** @@ -86,12 +84,12 @@ EhcWriteOpReg ( **/ VOID EhcSetOpRegBit ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = EhcReadOpReg (Ehc, Offset); Data |= Bit; @@ -108,12 +106,12 @@ EhcSetOpRegBit ( **/ VOID EhcClearOpRegBit ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = EhcReadOpReg (Ehc, Offset); Data &= ~Bit; @@ -136,14 +134,14 @@ EhcClearOpRegBit ( **/ EFI_STATUS EhcWaitOpRegBit ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ) { - UINT32 Index; + UINT32 Index; for (Index = 0; Index < Timeout / EHC_SYNC_POLL_INTERVAL + 1; Index++) { if (EHC_REG_BIT_IS_SET (Ehc, Offset, Bit) == WaitToSet) { @@ -167,13 +165,13 @@ EhcWaitOpRegBit ( **/ UINT32 EhcReadCapRegister ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; - Data = MmioRead32(Ehc->UsbHostControllerBaseAddress + Offset); + Data = MmioRead32 (Ehc->UsbHostControllerBaseAddress + Offset); return Data; } @@ -191,12 +189,12 @@ EhcReadCapRegister ( **/ EFI_STATUS EhcSetAndWaitDoorBell ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; - UINT32 Data; + EFI_STATUS Status; + UINT32 Data; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_IAAD); @@ -224,7 +222,7 @@ EhcSetAndWaitDoorBell ( **/ VOID EhcAckAllInterrupt ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { EhcWriteOpReg (Ehc, EHC_USBSTS_OFFSET, USBSTS_INTACK_MASK); @@ -243,11 +241,11 @@ EhcAckAllInterrupt ( **/ EFI_STATUS EhcEnablePeriodSchd ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_ENABLE_PERIOD); @@ -267,11 +265,11 @@ EhcEnablePeriodSchd ( **/ EFI_STATUS EhcEnableAsyncSchd ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_ENABLE_ASYNC); @@ -290,7 +288,7 @@ EhcEnableAsyncSchd ( **/ BOOLEAN EhcIsHalt ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { return EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT); @@ -307,7 +305,7 @@ EhcIsHalt ( **/ BOOLEAN EhcIsSysError ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { return EHC_REG_BIT_IS_SET (Ehc, EHC_USBSTS_OFFSET, USBSTS_SYS_ERROR); @@ -325,11 +323,11 @@ EhcIsSysError ( **/ EFI_STATUS EhcResetHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Host can only be reset when it is halt. If not so, halt it @@ -359,11 +357,11 @@ EhcResetHC ( **/ EFI_STATUS EhcHaltHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcClearOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_RUN); Status = EhcWaitOpRegBit (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT, TRUE, Timeout); @@ -382,11 +380,11 @@ EhcHaltHC ( **/ EFI_STATUS EhcRunHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; EhcSetOpRegBit (Ehc, EHC_USBCMD_OFFSET, USBCMD_RUN); Status = EhcWaitOpRegBit (Ehc, EHC_USBSTS_OFFSET, USBSTS_HALT, FALSE, Timeout); @@ -401,12 +399,12 @@ EhcRunHC ( **/ VOID EhcPowerOnAllPorts ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { - UINT8 PortNumber; - UINT8 Index; - UINT32 RegVal; + UINT8 PortNumber; + UINT8 Index; + UINT32 RegVal; PortNumber = (UINT8)(Ehc->HcStructParams & HCSP_NPORTS); for (Index = 0; Index < PortNumber; Index++) { @@ -414,7 +412,7 @@ EhcPowerOnAllPorts ( // Do not clear port status bits on initialization. Otherwise devices will // not enumerate properly at startup. // - RegVal = EhcReadOpReg(Ehc, EHC_PORT_STAT_OFFSET + 4 * Index); + RegVal = EhcReadOpReg (Ehc, EHC_PORT_STAT_OFFSET + 4 * Index); RegVal &= ~PORTSC_CHANGE_MASK; RegVal |= PORTSC_POWER; EhcWriteOpReg (Ehc, EHC_PORT_STAT_OFFSET + 4 * Index, RegVal); @@ -438,12 +436,12 @@ EhcPowerOnAllPorts ( **/ EFI_STATUS EhcInitHC ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS TempPtr; - UINTN PageNumber; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS TempPtr; + UINTN PageNumber; ASSERT (EhcIsHalt (Ehc)); @@ -454,13 +452,14 @@ EhcInitHC ( if (Ehc->PeriodFrame != NULL) { EhcFreeSched (Ehc); } - PageNumber = sizeof(PEI_URB)/PAGESIZE +1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - PageNumber, - &TempPtr - ); - Ehc->Urb = (PEI_URB *) ((UINTN) TempPtr); + + PageNumber = sizeof (PEI_URB)/PAGESIZE +1; + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + PageNumber, + &TempPtr + ); + Ehc->Urb = (PEI_URB *)((UINTN)TempPtr); if (Ehc->Urb == NULL) { return Status; } @@ -473,6 +472,7 @@ EhcInitHC ( if (EFI_ERROR (Status)) { return Status; } + // // 1. Program the CTRLDSSEGMENT register with the high 32 bit addr // @@ -563,15 +563,16 @@ EhcBulkTransfer ( OUT UINT32 *TransferResult ) { - PEI_USB2_HC_DEV *Ehc; - PEI_URB *Urb; - EFI_STATUS Status; + PEI_USB2_HC_DEV *Ehc; + PEI_URB *Urb; + EFI_STATUS Status; // // Validate the parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -581,11 +582,12 @@ EhcBulkTransfer ( if ((DeviceSpeed == EFI_USB_SPEED_LOW) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || - ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) { + ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) + { return EFI_INVALID_PARAMETER; } - Ehc =PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS(This); + Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -656,13 +658,13 @@ ON_EXIT: EFI_STATUS EFIAPI EhcGetRootHubPortNumber ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - OUT UINT8 *PortNumber + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + OUT UINT8 *PortNumber ) { + PEI_USB2_HC_DEV *EhcDev; - PEI_USB2_HC_DEV *EhcDev; EhcDev = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); if (PortNumber == NULL) { @@ -671,7 +673,6 @@ EhcGetRootHubPortNumber ( *PortNumber = (UINT8)(EhcDev->HcStructParams & HCSP_NPORTS); return EFI_SUCCESS; - } /** @@ -692,20 +693,20 @@ EhcGetRootHubPortNumber ( EFI_STATUS EFIAPI EhcClearRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - PEI_USB2_HC_DEV *Ehc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; + PEI_USB2_HC_DEV *Ehc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; - Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); - Status = EFI_SUCCESS; + Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -714,82 +715,82 @@ EhcClearRootHubPortFeature ( goto ON_EXIT; } - Offset = EHC_PORT_STAT_OFFSET + (4 * PortNumber); - State = EhcReadOpReg (Ehc, Offset); + Offset = EHC_PORT_STAT_OFFSET + (4 * PortNumber); + State = EhcReadOpReg (Ehc, Offset); State &= ~PORTSC_CHANGE_MASK; switch (PortFeature) { - case EfiUsbPortEnable: - // - // Clear PORT_ENABLE feature means disable port. - // - State &= ~PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnable: + // + // Clear PORT_ENABLE feature means disable port. + // + State &= ~PORTSC_ENABLED; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortSuspend: - // - // A write of zero to this bit is ignored by the host - // controller. The host controller will unconditionally - // set this bit to a zero when: - // 1. software sets the Forct Port Resume bit to a zero from a one. - // 2. software sets the Port Reset bit to a one frome a zero. - // - State &= ~PORSTSC_RESUME; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortSuspend: + // + // A write of zero to this bit is ignored by the host + // controller. The host controller will unconditionally + // set this bit to a zero when: + // 1. software sets the Forct Port Resume bit to a zero from a one. + // 2. software sets the Port Reset bit to a one frome a zero. + // + State &= ~PORSTSC_RESUME; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortReset: - // - // Clear PORT_RESET means clear the reset signal. - // - State &= ~PORTSC_RESET; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortReset: + // + // Clear PORT_RESET means clear the reset signal. + // + State &= ~PORTSC_RESET; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortOwner: - // - // Clear port owner means this port owned by EHC - // - State &= ~PORTSC_OWNER; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortOwner: + // + // Clear port owner means this port owned by EHC + // + State &= ~PORTSC_OWNER; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortConnectChange: - // - // Clear connect status change - // - State |= PORTSC_CONN_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortConnectChange: + // + // Clear connect status change + // + State |= PORTSC_CONN_CHANGE; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortEnableChange: - // - // Clear enable status change - // - State |= PORTSC_ENABLE_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnableChange: + // + // Clear enable status change + // + State |= PORTSC_ENABLE_CHANGE; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortOverCurrentChange: - // - // Clear PortOverCurrent change - // - State |= PORTSC_OVERCUR_CHANGE; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortOverCurrentChange: + // + // Clear PortOverCurrent change + // + State |= PORTSC_OVERCUR_CHANGE; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortPower: - case EfiUsbPortSuspendChange: - case EfiUsbPortResetChange: - // - // Not supported or not related operation - // - break; + case EfiUsbPortPower: + case EfiUsbPortSuspendChange: + case EfiUsbPortResetChange: + // + // Not supported or not related operation + // + break; - default: - Status = EFI_INVALID_PARAMETER; - break; + default: + Status = EFI_INVALID_PARAMETER; + break; } ON_EXIT: @@ -812,20 +813,20 @@ ON_EXIT: EFI_STATUS EFIAPI EhcSetRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - PEI_USB2_HC_DEV *Ehc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; + PEI_USB2_HC_DEV *Ehc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; - Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); - Status = EFI_SUCCESS; + Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -834,8 +835,8 @@ EhcSetRootHubPortFeature ( goto ON_EXIT; } - Offset = (UINT32) (EHC_PORT_STAT_OFFSET + (4 * PortNumber)); - State = EhcReadOpReg (Ehc, Offset); + Offset = (UINT32)(EHC_PORT_STAT_OFFSET + (4 * PortNumber)); + State = EhcReadOpReg (Ehc, Offset); // // Mask off the port status change bits, these bits are @@ -844,54 +845,54 @@ EhcSetRootHubPortFeature ( State &= ~PORTSC_CHANGE_MASK; switch (PortFeature) { - case EfiUsbPortEnable: - // - // Sofeware can't set this bit, Port can only be enable by - // EHCI as a part of the reset and enable - // - State |= PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortEnable: + // + // Sofeware can't set this bit, Port can only be enable by + // EHCI as a part of the reset and enable + // + State |= PORTSC_ENABLED; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortSuspend: - State |= PORTSC_SUSPEND; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortSuspend: + State |= PORTSC_SUSPEND; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortReset: - // - // Make sure Host Controller not halt before reset it - // - if (EhcIsHalt (Ehc)) { - Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); + case EfiUsbPortReset: + // + // Make sure Host Controller not halt before reset it + // + if (EhcIsHalt (Ehc)) { + Status = EhcRunHC (Ehc, EHC_GENERIC_TIMEOUT); - if (EFI_ERROR (Status)) { - break; + if (EFI_ERROR (Status)) { + break; + } } - } - // - // Set one to PortReset bit must also set zero to PortEnable bit - // - State |= PORTSC_RESET; - State &= ~PORTSC_ENABLED; - EhcWriteOpReg (Ehc, Offset, State); - break; + // + // Set one to PortReset bit must also set zero to PortEnable bit + // + State |= PORTSC_RESET; + State &= ~PORTSC_ENABLED; + EhcWriteOpReg (Ehc, Offset, State); + break; - case EfiUsbPortPower: - // - // Not supported, ignore the operation - // - Status = EFI_SUCCESS; - break; + case EfiUsbPortPower: + // + // Not supported, ignore the operation + // + Status = EFI_SUCCESS; + break; - case EfiUsbPortOwner: - State |= PORTSC_OWNER; - EhcWriteOpReg (Ehc, Offset, State); - break; + case EfiUsbPortOwner: + State |= PORTSC_OWNER; + EhcWriteOpReg (Ehc, Offset, State); + break; - default: - Status = EFI_INVALID_PARAMETER; + default: + Status = EFI_INVALID_PARAMETER; } ON_EXIT: @@ -914,26 +915,26 @@ ON_EXIT: EFI_STATUS EFIAPI EhcGetRootHubPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - OUT EFI_USB_PORT_STATUS *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + OUT EFI_USB_PORT_STATUS *PortStatus ) { - PEI_USB2_HC_DEV *Ehc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - UINTN Index; - UINTN MapSize; - EFI_STATUS Status; + PEI_USB2_HC_DEV *Ehc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + UINTN Index; + UINTN MapSize; + EFI_STATUS Status; if (PortStatus == NULL) { return EFI_INVALID_PARAMETER; } - Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS(This); - Status = EFI_SUCCESS; + Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Ehc->HcStructParams & HCSP_NPORTS); @@ -942,11 +943,11 @@ EhcGetRootHubPortStatus ( goto ON_EXIT; } - Offset = (UINT32) (EHC_PORT_STAT_OFFSET + (4 * PortNumber)); - PortStatus->PortStatus = 0; - PortStatus->PortChangeStatus = 0; + Offset = (UINT32)(EHC_PORT_STAT_OFFSET + (4 * PortNumber)); + PortStatus->PortStatus = 0; + PortStatus->PortChangeStatus = 0; - State = EhcReadOpReg (Ehc, Offset); + State = EhcReadOpReg (Ehc, Offset); // // Identify device speed. If in K state, it is low speed. @@ -956,7 +957,6 @@ EhcGetRootHubPortStatus ( // if (EHC_BIT_IS_SET (State, PORTSC_LINESTATE_K)) { PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; - } else if (EHC_BIT_IS_SET (State, PORTSC_ENABLED)) { PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; } @@ -968,7 +968,7 @@ EhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (EHC_BIT_IS_SET (State, mUsbPortStateMap[Index].HwState)) { - PortStatus->PortStatus = (UINT16) (PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); + PortStatus->PortStatus = (UINT16)(PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); } } @@ -976,7 +976,7 @@ EhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (EHC_BIT_IS_SET (State, mUsbPortChangeMap[Index].HwState)) { - PortStatus->PortChangeStatus = (UINT16) (PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); + PortStatus->PortChangeStatus = (UINT16)(PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); } } @@ -1027,10 +1027,10 @@ EhcControlTransfer ( OUT UINT32 *TransferResult ) { - PEI_USB2_HC_DEV *Ehc; - PEI_URB *Urb; - UINT8 Endpoint; - EFI_STATUS Status; + PEI_USB2_HC_DEV *Ehc; + PEI_URB *Urb; + UINT8 Endpoint; + EFI_STATUS Status; // // Validate parameters @@ -1041,33 +1041,37 @@ EhcControlTransfer ( if ((TransferDirection != EfiUsbDataIn) && (TransferDirection != EfiUsbDataOut) && - (TransferDirection != EfiUsbNoData)) { + (TransferDirection != EfiUsbNoData)) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection == EfiUsbNoData) && - ((Data != NULL) || (*DataLength != 0))) { + ((Data != NULL) || (*DataLength != 0))) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection != EfiUsbNoData) && - ((Data == NULL) || (*DataLength == 0))) { + ((Data == NULL) || (*DataLength == 0))) + { return EFI_INVALID_PARAMETER; } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && - (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) { + (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) + { return EFI_INVALID_PARAMETER; } - if ((DeviceSpeed == EFI_USB_SPEED_LOW) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || - ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) { + ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512))) + { return EFI_INVALID_PARAMETER; } - Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); + Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS (This); Status = EFI_DEVICE_ERROR; *TransferResult = EFI_USB_ERR_SYSTEM; @@ -1088,23 +1092,23 @@ EhcControlTransfer ( // endpoint is bidirectional. EhcCreateUrb expects this // combination of Ep addr and its direction. // - Endpoint = (UINT8) (0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); - Urb = EhcCreateUrb ( - Ehc, - DeviceAddress, - Endpoint, - DeviceSpeed, - 0, - MaximumPacketLength, - Translator, - EHC_CTRL_TRANSFER, - Request, - Data, - *DataLength, - NULL, - NULL, - 1 - ); + Endpoint = (UINT8)(0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); + Urb = EhcCreateUrb ( + Ehc, + DeviceAddress, + Endpoint, + DeviceSpeed, + 0, + MaximumPacketLength, + Translator, + EHC_CTRL_TRANSFER, + Request, + Data, + *DataLength, + NULL, + NULL, + 1 + ); if (Urb == NULL) { Status = EFI_OUT_OF_RESOURCES; @@ -1152,7 +1156,7 @@ EhcEndOfPei ( IN VOID *Ppi ) { - PEI_USB2_HC_DEV *Ehc; + PEI_USB2_HC_DEV *Ehc; Ehc = PEI_RECOVERY_USB_EHC_DEV_FROM_THIS_NOTIFY (NotifyDescriptor); @@ -1177,14 +1181,14 @@ EhcPeimEntry ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - PEI_USB_CONTROLLER_PPI *ChipSetUsbControllerPpi; - EFI_STATUS Status; - UINT8 Index; - UINTN ControllerType; - UINTN BaseAddress; - UINTN MemPages; - PEI_USB2_HC_DEV *EhcDev; - EFI_PHYSICAL_ADDRESS TempPtr; + PEI_USB_CONTROLLER_PPI *ChipSetUsbControllerPpi; + EFI_STATUS Status; + UINT8 Index; + UINTN ControllerType; + UINTN BaseAddress; + UINTN MemPages; + PEI_USB2_HC_DEV *EhcDev; + EFI_PHYSICAL_ADDRESS TempPtr; // // Shadow this PEIM to run from memory @@ -1197,7 +1201,7 @@ EhcPeimEntry ( &gPeiUsbControllerPpiGuid, 0, NULL, - (VOID **) &ChipSetUsbControllerPpi + (VOID **)&ChipSetUsbControllerPpi ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; @@ -1206,7 +1210,7 @@ EhcPeimEntry ( Index = 0; while (TRUE) { Status = ChipSetUsbControllerPpi->GetUsbController ( - (EFI_PEI_SERVICES **) PeiServices, + (EFI_PEI_SERVICES **)PeiServices, ChipSetUsbControllerPpi, Index, &ControllerType, @@ -1228,24 +1232,23 @@ EhcPeimEntry ( } MemPages = sizeof (PEI_USB2_HC_DEV) / PAGESIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &TempPtr + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - ZeroMem((VOID *)(UINTN)TempPtr, MemPages*PAGESIZE); - EhcDev = (PEI_USB2_HC_DEV *) ((UINTN) TempPtr); + ZeroMem ((VOID *)(UINTN)TempPtr, MemPages*PAGESIZE); + EhcDev = (PEI_USB2_HC_DEV *)((UINTN)TempPtr); EhcDev->Signature = USB2_HC_DEV_SIGNATURE; IoMmuInit (&EhcDev->IoMmu); - EhcDev->UsbHostControllerBaseAddress = (UINT32) BaseAddress; - + EhcDev->UsbHostControllerBaseAddress = (UINT32)BaseAddress; EhcDev->HcStructParams = EhcReadCapRegister (EhcDev, EHC_HCSPARAMS_OFFSET); EhcDev->HcCapParams = EhcReadCapRegister (EhcDev, EHC_HCCPARAMS_OFFSET); @@ -1258,16 +1261,16 @@ EhcPeimEntry ( return Status; } - EhcDev->Usb2HostControllerPpi.ControlTransfer = EhcControlTransfer; - EhcDev->Usb2HostControllerPpi.BulkTransfer = EhcBulkTransfer; - EhcDev->Usb2HostControllerPpi.GetRootHubPortNumber = EhcGetRootHubPortNumber; - EhcDev->Usb2HostControllerPpi.GetRootHubPortStatus = EhcGetRootHubPortStatus; - EhcDev->Usb2HostControllerPpi.SetRootHubPortFeature = EhcSetRootHubPortFeature; - EhcDev->Usb2HostControllerPpi.ClearRootHubPortFeature = EhcClearRootHubPortFeature; + EhcDev->Usb2HostControllerPpi.ControlTransfer = EhcControlTransfer; + EhcDev->Usb2HostControllerPpi.BulkTransfer = EhcBulkTransfer; + EhcDev->Usb2HostControllerPpi.GetRootHubPortNumber = EhcGetRootHubPortNumber; + EhcDev->Usb2HostControllerPpi.GetRootHubPortStatus = EhcGetRootHubPortStatus; + EhcDev->Usb2HostControllerPpi.SetRootHubPortFeature = EhcSetRootHubPortFeature; + EhcDev->Usb2HostControllerPpi.ClearRootHubPortFeature = EhcClearRootHubPortFeature; EhcDev->PpiDescriptor.Flags = (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - EhcDev->PpiDescriptor.Guid = &gPeiUsb2HostControllerPpiGuid; - EhcDev->PpiDescriptor.Ppi = &EhcDev->Usb2HostControllerPpi; + EhcDev->PpiDescriptor.Guid = &gPeiUsb2HostControllerPpiGuid; + EhcDev->PpiDescriptor.Ppi = &EhcDev->Usb2HostControllerPpi; Status = PeiServicesInstallPpi (&EhcDev->PpiDescriptor); if (EFI_ERROR (Status)) { @@ -1275,8 +1278,8 @@ EhcPeimEntry ( continue; } - EhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - EhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; + EhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); + EhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; EhcDev->EndOfPeiNotifyList.Notify = EhcEndOfPei; PeiServicesNotifyPpi (&EhcDev->EndOfPeiNotifyList); @@ -1296,12 +1299,11 @@ EhcPeimEntry ( **/ EFI_STATUS InitializeUsbHC ( - IN PEI_USB2_HC_DEV *EhcDev + IN PEI_USB2_HC_DEV *EhcDev ) { EFI_STATUS Status; - EhcResetHC (EhcDev, EHC_RESET_TIMEOUT); Status = EhcInitHC (EhcDev); diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.h b/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.h index 8e5b6418e6..c83886c240 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.h +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhcPeim.h @@ -28,46 +28,44 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _PEI_USB2_HC_DEV PEI_USB2_HC_DEV; -#define EFI_LIST_ENTRY LIST_ENTRY +#define EFI_LIST_ENTRY LIST_ENTRY #include "UsbHcMem.h" #include "EhciReg.h" #include "EhciUrb.h" #include "EhciSched.h" -#define EFI_USB_SPEED_FULL 0x0000 -#define EFI_USB_SPEED_LOW 0x0001 -#define EFI_USB_SPEED_HIGH 0x0002 +#define EFI_USB_SPEED_FULL 0x0000 +#define EFI_USB_SPEED_LOW 0x0001 +#define EFI_USB_SPEED_HIGH 0x0002 -#define PAGESIZE 4096 +#define PAGESIZE 4096 -#define EHC_1_MICROSECOND 1 -#define EHC_1_MILLISECOND (1000 * EHC_1_MICROSECOND) -#define EHC_1_SECOND (1000 * EHC_1_MILLISECOND) +#define EHC_1_MICROSECOND 1 +#define EHC_1_MILLISECOND (1000 * EHC_1_MICROSECOND) +#define EHC_1_SECOND (1000 * EHC_1_MILLISECOND) // // EHCI register operation timeout, set by experience // -#define EHC_RESET_TIMEOUT (1 * EHC_1_SECOND) -#define EHC_GENERIC_TIMEOUT (10 * EHC_1_MILLISECOND) - +#define EHC_RESET_TIMEOUT (1 * EHC_1_SECOND) +#define EHC_GENERIC_TIMEOUT (10 * EHC_1_MILLISECOND) // // Wait for roothub port power stable, refers to Spec[EHCI1.0-2.3.9] // -#define EHC_ROOT_PORT_RECOVERY_STALL (20 * EHC_1_MILLISECOND) +#define EHC_ROOT_PORT_RECOVERY_STALL (20 * EHC_1_MILLISECOND) // // Sync transfer polling interval, set by experience. // -#define EHC_SYNC_POLL_INTERVAL (6 * EHC_1_MILLISECOND) - -#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) +#define EHC_SYNC_POLL_INTERVAL (6 * EHC_1_MILLISECOND) +#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) -#define EHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) -#define EHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) -#define EHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define EHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) +#define EHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) +#define EHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) #define EHC_REG_BIT_IS_SET(Ehc, Offset, Bit) \ (EHC_BIT_IS_SET(EhcReadOpReg ((Ehc), (Offset)), (Bit))) @@ -75,18 +73,18 @@ typedef struct _PEI_USB2_HC_DEV PEI_USB2_HC_DEV; #define USB2_HC_DEV_SIGNATURE SIGNATURE_32 ('e', 'h', 'c', 'i') struct _PEI_USB2_HC_DEV { - UINTN Signature; - PEI_USB2_HOST_CONTROLLER_PPI Usb2HostControllerPpi; - EDKII_IOMMU_PPI *IoMmu; - EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; + UINTN Signature; + PEI_USB2_HOST_CONTROLLER_PPI Usb2HostControllerPpi; + EDKII_IOMMU_PPI *IoMmu; + EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; // // EndOfPei callback is used to stop the EHC DMA operation // after exit PEI phase. // - EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; - UINT32 UsbHostControllerBaseAddress; - PEI_URB *Urb; - USBHC_MEM_POOL *MemPool; + EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; + UINT32 UsbHostControllerBaseAddress; + PEI_URB *Urb; + USBHC_MEM_POOL *MemPool; // // Schedule data shared between asynchronous and periodic @@ -97,36 +95,36 @@ struct _PEI_USB2_HC_DEV { // For control transfer, even the short read happens, try the // status stage. // - PEI_EHC_QTD *ShortReadStop; - EFI_EVENT PollTimer; + PEI_EHC_QTD *ShortReadStop; + EFI_EVENT PollTimer; // // Asynchronous(bulk and control) transfer schedule data: // ReclaimHead is used as the head of the asynchronous transfer // list. It acts as the reclamation header. // - PEI_EHC_QH *ReclaimHead; + PEI_EHC_QH *ReclaimHead; // // Periodic (interrupt) transfer schedule data: // - VOID *PeriodFrame; // Mapped as common buffer - VOID *PeriodFrameMap; + VOID *PeriodFrame; // Mapped as common buffer + VOID *PeriodFrameMap; - PEI_EHC_QH *PeriodOne; - EFI_LIST_ENTRY AsyncIntTransfers; + PEI_EHC_QH *PeriodOne; + EFI_LIST_ENTRY AsyncIntTransfers; // // EHCI configuration data // - UINT32 HcStructParams; // Cache of HC structure parameter, EHC_HCSPARAMS_OFFSET - UINT32 HcCapParams; // Cache of HC capability parameter, HCCPARAMS - UINT32 CapLen; // Capability length - UINT32 High32bitAddr; + UINT32 HcStructParams; // Cache of HC structure parameter, EHC_HCSPARAMS_OFFSET + UINT32 HcCapParams; // Cache of HC capability parameter, HCCPARAMS + UINT32 CapLen; // Capability length + UINT32 High32bitAddr; }; -#define PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS(a) CR (a, PEI_USB2_HC_DEV, Usb2HostControllerPpi, USB2_HC_DEV_SIGNATURE) -#define PEI_RECOVERY_USB_EHC_DEV_FROM_THIS_NOTIFY(a) CR (a, PEI_USB2_HC_DEV, EndOfPeiNotifyList, USB2_HC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_EHC_DEV_FROM_EHCI_THIS(a) CR (a, PEI_USB2_HC_DEV, Usb2HostControllerPpi, USB2_HC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_EHC_DEV_FROM_THIS_NOTIFY(a) CR (a, PEI_USB2_HC_DEV, EndOfPeiNotifyList, USB2_HC_DEV_SIGNATURE) /** @param EhcDev EHCI Device. @@ -137,7 +135,7 @@ struct _PEI_USB2_HC_DEV { **/ EFI_STATUS InitializeUsbHC ( - IN PEI_USB2_HC_DEV *EhcDev + IN PEI_USB2_HC_DEV *EhcDev ); /** @@ -154,9 +152,9 @@ InitializeUsbHC ( **/ USBHC_MEM_POOL * UsbHcInitMemPool ( - IN PEI_USB2_HC_DEV *Ehc, - IN BOOLEAN Check4G, - IN UINT32 Which4G + IN PEI_USB2_HC_DEV *Ehc, + IN BOOLEAN Check4G, + IN UINT32 Which4G ) ; @@ -172,8 +170,8 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool ) ; @@ -190,9 +188,9 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) ; @@ -207,10 +205,10 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) ; @@ -253,8 +251,8 @@ IoMmuMap ( **/ VOID IoMmuUnmap ( - IN EDKII_IOMMU_PPI *IoMmu, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN VOID *Mapping ); /** @@ -296,10 +294,10 @@ IoMmuAllocateBuffer ( **/ VOID IoMmuFreeBuffer ( - IN EDKII_IOMMU_PPI *IoMmu, - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** @@ -310,7 +308,7 @@ IoMmuFreeBuffer ( **/ VOID IoMmuInit ( - OUT EDKII_IOMMU_PPI **IoMmu + OUT EDKII_IOMMU_PPI **IoMmu ); #endif diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciReg.h b/MdeModulePkg/Bus/Pci/EhciPei/EhciReg.h index 98113519a5..2a438f1bbe 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciReg.h +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciReg.h @@ -10,20 +10,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_REG_H_ #define _EFI_EHCI_REG_H_ - - // // Capability register offset // -#define EHC_CAPLENGTH_OFFSET 0 // Capability register length offset -#define EHC_HCSPARAMS_OFFSET 0x04 // Structural Parameters 04-07h -#define EHC_HCCPARAMS_OFFSET 0x08 // Capability parameters offset +#define EHC_CAPLENGTH_OFFSET 0 // Capability register length offset +#define EHC_HCSPARAMS_OFFSET 0x04 // Structural Parameters 04-07h +#define EHC_HCCPARAMS_OFFSET 0x08 // Capability parameters offset // // Capability register bit definition // -#define HCSP_NPORTS 0x0F // Number of root hub port -#define HCCP_64BIT 0x01 // 64-bit addressing capability +#define HCSP_NPORTS 0x0F // Number of root hub port +#define HCCP_64BIT 0x01 // 64-bit addressing capability // // Operational register offset @@ -38,61 +36,61 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EHC_CONFIG_FLAG_OFFSET 0x40 // Configure flag register offset #define EHC_PORT_STAT_OFFSET 0x44 // Port status/control offset -#define EHC_FRAME_LEN 1024 +#define EHC_FRAME_LEN 1024 // // Register bit definition // -#define CONFIGFLAG_ROUTE_EHC 0x01 // Route port to EHC - -#define USBCMD_RUN 0x01 // Run/stop -#define USBCMD_RESET 0x02 // Start the host controller reset -#define USBCMD_ENABLE_PERIOD 0x10 // Enable periodic schedule -#define USBCMD_ENABLE_ASYNC 0x20 // Enable asynchronous schedule -#define USBCMD_IAAD 0x40 // Interrupt on async advance doorbell - -#define USBSTS_IAA 0x20 // Interrupt on async advance -#define USBSTS_PERIOD_ENABLED 0x4000 // Periodic schedule status -#define USBSTS_ASYNC_ENABLED 0x8000 // Asynchronous schedule status -#define USBSTS_HALT 0x1000 // Host controller halted -#define USBSTS_SYS_ERROR 0x10 // Host system error -#define USBSTS_INTACK_MASK 0x003F // Mask for the interrupt ACK, the WC +#define CONFIGFLAG_ROUTE_EHC 0x01 // Route port to EHC + +#define USBCMD_RUN 0x01 // Run/stop +#define USBCMD_RESET 0x02 // Start the host controller reset +#define USBCMD_ENABLE_PERIOD 0x10 // Enable periodic schedule +#define USBCMD_ENABLE_ASYNC 0x20 // Enable asynchronous schedule +#define USBCMD_IAAD 0x40 // Interrupt on async advance doorbell + +#define USBSTS_IAA 0x20 // Interrupt on async advance +#define USBSTS_PERIOD_ENABLED 0x4000 // Periodic schedule status +#define USBSTS_ASYNC_ENABLED 0x8000 // Asynchronous schedule status +#define USBSTS_HALT 0x1000 // Host controller halted +#define USBSTS_SYS_ERROR 0x10 // Host system error +#define USBSTS_INTACK_MASK 0x003F // Mask for the interrupt ACK, the WC // (write clean) bits in USBSTS register -#define PORTSC_CONN 0x01 // Current Connect Status -#define PORTSC_CONN_CHANGE 0x02 // Connect Status Change -#define PORTSC_ENABLED 0x04 // Port Enable / Disable -#define PORTSC_ENABLE_CHANGE 0x08 // Port Enable / Disable Change -#define PORTSC_OVERCUR 0x10 // Over current Active -#define PORTSC_OVERCUR_CHANGE 0x20 // Over current Change -#define PORSTSC_RESUME 0x40 // Force Port Resume -#define PORTSC_SUSPEND 0x80 // Port Suspend State -#define PORTSC_RESET 0x100 // Port Reset -#define PORTSC_LINESTATE_K 0x400 // Line Status K-state -#define PORTSC_LINESTATE_J 0x800 // Line Status J-state -#define PORTSC_POWER 0x1000 // Port Power -#define PORTSC_OWNER 0x2000 // Port Owner -#define PORTSC_CHANGE_MASK 0x2A // Mask of the port change bits, +#define PORTSC_CONN 0x01 // Current Connect Status +#define PORTSC_CONN_CHANGE 0x02 // Connect Status Change +#define PORTSC_ENABLED 0x04 // Port Enable / Disable +#define PORTSC_ENABLE_CHANGE 0x08 // Port Enable / Disable Change +#define PORTSC_OVERCUR 0x10 // Over current Active +#define PORTSC_OVERCUR_CHANGE 0x20 // Over current Change +#define PORSTSC_RESUME 0x40 // Force Port Resume +#define PORTSC_SUSPEND 0x80 // Port Suspend State +#define PORTSC_RESET 0x100 // Port Reset +#define PORTSC_LINESTATE_K 0x400 // Line Status K-state +#define PORTSC_LINESTATE_J 0x800 // Line Status J-state +#define PORTSC_POWER 0x1000 // Port Power +#define PORTSC_OWNER 0x2000 // Port Owner +#define PORTSC_CHANGE_MASK 0x2A // Mask of the port change bits, // they are WC (write clean) // // PCI Configuration Registers // -#define EHC_BAR_INDEX 0 // how many bytes away from USB_BASE to 0x10 +#define EHC_BAR_INDEX 0 // how many bytes away from USB_BASE to 0x10 -#define EHC_LINK_TERMINATED(Link) (((Link) & 0x01) != 0) +#define EHC_LINK_TERMINATED(Link) (((Link) & 0x01) != 0) #define EHC_ADDR(High, QhHw32) \ ((VOID *) (UINTN) (LShiftU64 ((High), 32) | ((QhHw32) & 0xFFFFFFF0))) -#define EHCI_IS_DATAIN(EndpointAddr) EHC_BIT_IS_SET((EndpointAddr), 0x80) +#define EHCI_IS_DATAIN(EndpointAddr) EHC_BIT_IS_SET((EndpointAddr), 0x80) // // Structure to map the hardware port states to the // UEFI's port states. // typedef struct { - UINT16 HwState; - UINT16 UefiState; + UINT16 HwState; + UINT16 UefiState; } USB_PORT_STATE_MAP; // @@ -100,13 +98,12 @@ typedef struct { // #pragma pack(1) typedef struct { - UINT8 Pi; - UINT8 SubClassCode; - UINT8 BaseCode; + UINT8 Pi; + UINT8 SubClassCode; + UINT8 BaseCode; } USB_CLASSC; #pragma pack() - /** Read EHCI capability register. @@ -118,8 +115,8 @@ typedef struct { **/ UINT32 EhcReadCapRegister ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset ) ; @@ -134,8 +131,8 @@ EhcReadCapRegister ( **/ UINT32 EhcReadOpReg ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset ) ; @@ -149,9 +146,9 @@ EhcReadOpReg ( **/ VOID EhcWriteOpReg ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Offset, + IN UINT32 Data ) ; @@ -163,7 +160,7 @@ EhcWriteOpReg ( **/ VOID EhcClearLegacySupport ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -180,8 +177,8 @@ EhcClearLegacySupport ( **/ EFI_STATUS EhcSetAndWaitDoorBell ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) ; @@ -194,7 +191,7 @@ EhcSetAndWaitDoorBell ( **/ VOID EhcAckAllInterrupt ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -209,7 +206,7 @@ EhcAckAllInterrupt ( **/ BOOLEAN EhcIsHalt ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -224,7 +221,7 @@ EhcIsHalt ( **/ BOOLEAN EhcIsSysError ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -240,8 +237,8 @@ EhcIsSysError ( **/ EFI_STATUS EhcResetHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) ; @@ -257,8 +254,8 @@ EhcResetHC ( **/ EFI_STATUS EhcHaltHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) ; @@ -274,8 +271,8 @@ EhcHaltHC ( **/ EFI_STATUS EhcRunHC ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT32 Timeout + IN PEI_USB2_HC_DEV *Ehc, + IN UINT32 Timeout ) ; @@ -296,7 +293,7 @@ EhcRunHC ( **/ EFI_STATUS EhcInitHC ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.c b/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.c index 311f501980..db2406b0d2 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.c @@ -22,13 +22,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EhcCreateHelpQ ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { - USB_ENDPOINT Ep; - PEI_EHC_QH *Qh; - QH_HW *QhHw; - PEI_EHC_QTD *Qtd; + USB_ENDPOINT Ep; + PEI_EHC_QH *Qh; + QH_HW *QhHw; + PEI_EHC_QTD *Qtd; // // Create an inactive Qtd to terminate the short packet read. @@ -39,25 +39,25 @@ EhcCreateHelpQ ( return EFI_OUT_OF_RESOURCES; } - Qtd->QtdHw.Status = QTD_STAT_HALTED; - Ehc->ShortReadStop = Qtd; + Qtd->QtdHw.Status = QTD_STAT_HALTED; + Ehc->ShortReadStop = Qtd; // // Create a QH to act as the EHC reclamation header. // Set the header to loopback to itself. // - Ep.DevAddr = 0; - Ep.EpAddr = 1; - Ep.Direction = EfiUsbDataIn; - Ep.DevSpeed = EFI_USB_SPEED_HIGH; - Ep.MaxPacket = 64; - Ep.HubAddr = 0; - Ep.HubPort = 0; - Ep.Toggle = 0; - Ep.Type = EHC_BULK_TRANSFER; - Ep.PollRate = 1; - - Qh = EhcCreateQh (Ehc, &Ep); + Ep.DevAddr = 0; + Ep.EpAddr = 1; + Ep.Direction = EfiUsbDataIn; + Ep.DevSpeed = EFI_USB_SPEED_HIGH; + Ep.MaxPacket = 64; + Ep.HubAddr = 0; + Ep.HubPort = 0; + Ep.Toggle = 0; + Ep.Type = EHC_BULK_TRANSFER; + Ep.PollRate = 1; + + Qh = EhcCreateQh (Ehc, &Ep); if (Qh == NULL) { return EFI_OUT_OF_RESOURCES; @@ -72,10 +72,10 @@ EhcCreateHelpQ ( // // Create a dummy QH to act as the terminator for periodical schedule // - Ep.EpAddr = 2; - Ep.Type = EHC_INT_TRANSFER_SYNC; + Ep.EpAddr = 2; + Ep.Type = EHC_INT_TRANSFER_SYNC; - Qh = EhcCreateQh (Ehc, &Ep); + Qh = EhcCreateQh (Ehc, &Ep); if (Qh == NULL) { return EFI_OUT_OF_RESOURCES; @@ -98,7 +98,7 @@ EhcCreateHelpQ ( **/ EFI_STATUS EhcInitSched ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { VOID *Buf; @@ -132,9 +132,9 @@ EhcInitSched ( return EFI_OUT_OF_RESOURCES; } - Ehc->PeriodFrame = Buf; - Ehc->PeriodFrameMap = Map; - Ehc->High32bitAddr = EHC_HIGH_32BIT (PhyAddr); + Ehc->PeriodFrame = Buf; + Ehc->PeriodFrameMap = Map; + Ehc->High32bitAddr = EHC_HIGH_32BIT (PhyAddr); // // Init memory pool management then create the helper @@ -160,8 +160,8 @@ EhcInitSched ( // // Initialize the frame list entries then set the registers // - Desc = (UINT32 *) Ehc->PeriodFrame; - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->PeriodOne, sizeof (PEI_EHC_QH)); + Desc = (UINT32 *)Ehc->PeriodFrame; + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->PeriodOne, sizeof (PEI_EHC_QH)); for (Index = 0; Index < EHC_FRAME_LEN; Index++) { Desc[Index] = QH_LINK (PciAddr, EHC_TYPE_QH, FALSE); } @@ -173,7 +173,7 @@ EhcInitSched ( // Only need to set the AsynListAddr register to // the reclamation header // - PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->ReclaimHead, sizeof (PEI_EHC_QH)); + PciAddr = UsbHcGetPciAddressForHostMem (Ehc->MemPool, Ehc->ReclaimHead, sizeof (PEI_EHC_QH)); EhcWriteOpReg (Ehc, EHC_ASYNC_HEAD_OFFSET, EHC_LOW_32BIT (PciAddr)); return EFI_SUCCESS; } @@ -186,7 +186,7 @@ EhcInitSched ( **/ VOID EhcFreeSched ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) { EhcWriteOpReg (Ehc, EHC_FRAME_BASE_OFFSET, 0); @@ -231,24 +231,24 @@ EhcFreeSched ( **/ VOID EhcLinkQhToAsync ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_EHC_QH *Qh + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_EHC_QH *Qh ) { - PEI_EHC_QH *Head; + PEI_EHC_QH *Head; // // Append the queue head after the reclaim header, then // fix the hardware visiable parts (EHCI R1.0 page 72). // ReclaimHead is always linked to the EHCI's AsynListAddr. // - Head = Ehc->ReclaimHead; + Head = Ehc->ReclaimHead; - Qh->NextQh = Head->NextQh; - Head->NextQh = Qh; + Qh->NextQh = Head->NextQh; + Head->NextQh = Qh; - Qh->QhHw.HorizonLink = QH_LINK (Head, EHC_TYPE_QH, FALSE);; - Head->QhHw.HorizonLink = QH_LINK (Qh, EHC_TYPE_QH, FALSE); + Qh->QhHw.HorizonLink = QH_LINK (Head, EHC_TYPE_QH, FALSE); + Head->QhHw.HorizonLink = QH_LINK (Qh, EHC_TYPE_QH, FALSE); } /** @@ -261,11 +261,11 @@ EhcLinkQhToAsync ( **/ VOID EhcUnlinkQhFromAsync ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_EHC_QH *Qh + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_EHC_QH *Qh ) { - PEI_EHC_QH *Head; + PEI_EHC_QH *Head; ASSERT (Ehc->ReclaimHead->NextQh == Qh); @@ -274,12 +274,12 @@ EhcUnlinkQhFromAsync ( // visiable part: Only need to loopback the ReclaimHead. The Qh // is pointing to ReclaimHead (which is staill in the list). // - Head = Ehc->ReclaimHead; + Head = Ehc->ReclaimHead; - Head->NextQh = Qh->NextQh; - Qh->NextQh = NULL; + Head->NextQh = Qh->NextQh; + Qh->NextQh = NULL; - Head->QhHw.HorizonLink = QH_LINK (Head, EHC_TYPE_QH, FALSE); + Head->QhHw.HorizonLink = QH_LINK (Head, EHC_TYPE_QH, FALSE); // // Set and wait the door bell to synchronize with the hardware @@ -302,22 +302,22 @@ EhcUnlinkQhFromAsync ( **/ BOOLEAN EhcCheckUrbResult ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb ) { - EFI_LIST_ENTRY *Entry; - PEI_EHC_QTD *Qtd; - QTD_HW *QtdHw; - UINT8 State; - BOOLEAN Finished; + EFI_LIST_ENTRY *Entry; + PEI_EHC_QTD *Qtd; + QTD_HW *QtdHw; + UINT8 State; + BOOLEAN Finished; ASSERT ((Ehc != NULL) && (Urb != NULL) && (Urb->Qh != NULL)); - Finished = TRUE; - Urb->Completed = 0; + Finished = TRUE; + Urb->Completed = 0; - Urb->Result = EFI_USB_NOERROR; + Urb->Result = EFI_USB_NOERROR; if (EhcIsHalt (Ehc) || EhcIsSysError (Ehc)) { Urb->Result |= EFI_USB_ERR_SYSTEM; @@ -327,7 +327,7 @@ EhcCheckUrbResult ( BASE_LIST_FOR_EACH (Entry, &Urb->Qh->Qtds) { Qtd = EFI_LIST_CONTAINER (Entry, PEI_EHC_QTD, QtdList); QtdHw = &Qtd->QtdHw; - State = (UINT8) QtdHw->Status; + State = (UINT8)QtdHw->Status; if (EHC_BIT_IS_SET (State, QTD_STAT_HALTED)) { // @@ -352,7 +352,6 @@ EhcCheckUrbResult ( Finished = TRUE; goto ON_EXIT; - } else if (EHC_BIT_IS_SET (State, QTD_STAT_ACTIVE)) { // // The QTD is still active, no need to check furthur. @@ -361,7 +360,6 @@ EhcCheckUrbResult ( Finished = FALSE; goto ON_EXIT; - } else { // // This QTD is finished OK or met short packet read. Update the @@ -372,7 +370,7 @@ EhcCheckUrbResult ( } if ((QtdHw->TotalBytes != 0) && (QtdHw->Pid == QTD_PID_INPUT)) { - //EHC_DUMP_QH ((Urb->Qh, "Short packet read", FALSE)); + // EHC_DUMP_QH ((Urb->Qh, "Short packet read", FALSE)); // // Short packet read condition. If it isn't a setup transfer, @@ -381,7 +379,6 @@ EhcCheckUrbResult ( // Status Stage of the setup transfer to get the finial result // if (QtdHw->AltNext == QTD_LINK (Ehc->ShortReadStop, FALSE)) { - Finished = TRUE; goto ON_EXIT; } @@ -399,7 +396,7 @@ ON_EXIT: // NOTICE: don't move DT update before the loop, otherwise there is // a race condition that DT is wrong. // - Urb->DataToggle = (UINT8) Urb->Qh->QhHw.DataToggle; + Urb->DataToggle = (UINT8)Urb->Qh->QhHw.DataToggle; return Finished; } @@ -418,19 +415,19 @@ ON_EXIT: **/ EFI_STATUS EhcExecTransfer ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb, - IN UINTN TimeOut + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb, + IN UINTN TimeOut ) { - EFI_STATUS Status; - UINTN Index; - UINTN Loop; - BOOLEAN Finished; - BOOLEAN InfiniteLoop; - - Status = EFI_SUCCESS; - Loop = TimeOut * EHC_1_MILLISECOND; + EFI_STATUS Status; + UINTN Index; + UINTN Loop; + BOOLEAN Finished; + BOOLEAN InfiniteLoop; + + Status = EFI_SUCCESS; + Loop = TimeOut * EHC_1_MILLISECOND; Finished = FALSE; InfiniteLoop = FALSE; @@ -460,4 +457,3 @@ EhcExecTransfer ( return Status; } - diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.h b/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.h index 60f8cb8152..6cba2d3e35 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.h +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciSched.h @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EhcInitSched ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -33,7 +33,7 @@ EhcInitSched ( **/ VOID EhcFreeSched ( - IN PEI_USB2_HC_DEV *Ehc + IN PEI_USB2_HC_DEV *Ehc ) ; @@ -50,8 +50,8 @@ EhcFreeSched ( **/ VOID EhcLinkQhToAsync ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_EHC_QH *Qh + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_EHC_QH *Qh ) ; @@ -65,8 +65,8 @@ EhcLinkQhToAsync ( **/ VOID EhcUnlinkQhFromAsync ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_EHC_QH *Qh + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_EHC_QH *Qh ) ; @@ -84,9 +84,9 @@ EhcUnlinkQhFromAsync ( **/ EFI_STATUS EhcExecTransfer ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb, - IN UINTN TimeOut + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb, + IN UINTN TimeOut ) ; diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c index df512ed6fa..1ad7f3a56a 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c @@ -27,19 +27,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ PEI_EHC_QTD * EhcCreateQtd ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT8 *Data, - IN UINTN DataLen, - IN UINT8 PktId, - IN UINT8 Toggle, - IN UINTN MaxPacket + IN PEI_USB2_HC_DEV *Ehc, + IN UINT8 *Data, + IN UINTN DataLen, + IN UINT8 PktId, + IN UINT8 Toggle, + IN UINTN MaxPacket ) { - PEI_EHC_QTD *Qtd; - QTD_HW *QtdHw; - UINTN Index; - UINTN Len; - UINTN ThisBufLen; + PEI_EHC_QTD *Qtd; + QTD_HW *QtdHw; + UINTN Index; + UINTN Len; + UINTN ThisBufLen; ASSERT (Ehc != NULL); @@ -49,9 +49,9 @@ EhcCreateQtd ( return NULL; } - Qtd->Signature = EHC_QTD_SIG; - Qtd->Data = Data; - Qtd->DataLen = 0; + Qtd->Signature = EHC_QTD_SIG; + Qtd->Data = Data; + Qtd->DataLen = 0; InitializeListHead (&Qtd->QtdList); @@ -77,17 +77,17 @@ EhcCreateQtd ( // compute the offset and clear Reserved fields. This is already // done in the data point. // - QtdHw->Page[Index] = EHC_LOW_32BIT (Data); - QtdHw->PageHigh[Index] = EHC_HIGH_32BIT (Data); + QtdHw->Page[Index] = EHC_LOW_32BIT (Data); + QtdHw->PageHigh[Index] = EHC_HIGH_32BIT (Data); - ThisBufLen = QTD_BUF_LEN - (EHC_LOW_32BIT (Data) & QTD_BUF_MASK); + ThisBufLen = QTD_BUF_LEN - (EHC_LOW_32BIT (Data) & QTD_BUF_MASK); if (Len + ThisBufLen >= DataLen) { Len = DataLen; break; } - Len += ThisBufLen; + Len += ThisBufLen; Data += ThisBufLen; } @@ -101,7 +101,7 @@ EhcCreateQtd ( Len = Len - Len % MaxPacket; } - QtdHw->TotalBytes = (UINT32) Len; + QtdHw->TotalBytes = (UINT32)Len; Qtd->DataLen = Len; } @@ -121,8 +121,8 @@ EhcCreateQtd ( **/ VOID EhcInitIntQh ( - IN USB_ENDPOINT *Ep, - IN QH_HW *QhHw + IN USB_ENDPOINT *Ep, + IN QH_HW *QhHw ) { // @@ -134,7 +134,7 @@ EhcInitIntQh ( // if (Ep->DevSpeed == EFI_USB_SPEED_HIGH) { QhHw->SMask = QH_MICROFRAME_0; - return ; + return; } // @@ -163,12 +163,12 @@ EhcInitIntQh ( **/ PEI_EHC_QH * EhcCreateQh ( - IN PEI_USB2_HC_DEV *Ehci, - IN USB_ENDPOINT *Ep + IN PEI_USB2_HC_DEV *Ehci, + IN USB_ENDPOINT *Ep ) { - PEI_EHC_QH *Qh; - QH_HW *QhHw; + PEI_EHC_QH *Qh; + QH_HW *QhHw; Qh = UsbHcAllocateMem (Ehci, Ehci->MemPool, sizeof (PEI_EHC_QH)); @@ -176,62 +176,63 @@ EhcCreateQh ( return NULL; } - Qh->Signature = EHC_QH_SIG; - Qh->NextQh = NULL; - Qh->Interval = Ep->PollRate; + Qh->Signature = EHC_QH_SIG; + Qh->NextQh = NULL; + Qh->Interval = Ep->PollRate; InitializeListHead (&Qh->Qtds); - QhHw = &Qh->QhHw; - QhHw->HorizonLink = QH_LINK (NULL, 0, TRUE); - QhHw->DeviceAddr = Ep->DevAddr; - QhHw->Inactive = 0; - QhHw->EpNum = Ep->EpAddr; - QhHw->EpSpeed = Ep->DevSpeed; - QhHw->DtCtrl = 0; - QhHw->ReclaimHead = 0; - QhHw->MaxPacketLen = (UINT32) Ep->MaxPacket; - QhHw->CtrlEp = 0; - QhHw->NakReload = QH_NAK_RELOAD; - QhHw->HubAddr = Ep->HubAddr; - QhHw->PortNum = Ep->HubPort; - QhHw->Multiplier = 1; - QhHw->DataToggle = Ep->Toggle; + QhHw = &Qh->QhHw; + QhHw->HorizonLink = QH_LINK (NULL, 0, TRUE); + QhHw->DeviceAddr = Ep->DevAddr; + QhHw->Inactive = 0; + QhHw->EpNum = Ep->EpAddr; + QhHw->EpSpeed = Ep->DevSpeed; + QhHw->DtCtrl = 0; + QhHw->ReclaimHead = 0; + QhHw->MaxPacketLen = (UINT32)Ep->MaxPacket; + QhHw->CtrlEp = 0; + QhHw->NakReload = QH_NAK_RELOAD; + QhHw->HubAddr = Ep->HubAddr; + QhHw->PortNum = Ep->HubPort; + QhHw->Multiplier = 1; + QhHw->DataToggle = Ep->Toggle; if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { QhHw->Status |= QTD_STAT_DO_SS; } switch (Ep->Type) { - case EHC_CTRL_TRANSFER: - // - // Special initialization for the control transfer: - // 1. Control transfer initialize data toggle from each QTD - // 2. Set the Control Endpoint Flag (C) for low/full speed endpoint. - // - QhHw->DtCtrl = 1; + case EHC_CTRL_TRANSFER: + // + // Special initialization for the control transfer: + // 1. Control transfer initialize data toggle from each QTD + // 2. Set the Control Endpoint Flag (C) for low/full speed endpoint. + // + QhHw->DtCtrl = 1; - if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { - QhHw->CtrlEp = 1; - } - break; + if (Ep->DevSpeed != EFI_USB_SPEED_HIGH) { + QhHw->CtrlEp = 1; + } - case EHC_INT_TRANSFER_ASYNC: - case EHC_INT_TRANSFER_SYNC: - // - // Special initialization for the interrupt transfer - // to set the S-Mask and C-Mask - // - QhHw->NakReload = 0; - EhcInitIntQh (Ep, QhHw); - break; + break; - case EHC_BULK_TRANSFER: - if ((Ep->DevSpeed == EFI_USB_SPEED_HIGH) && (Ep->Direction == EfiUsbDataOut)) { - QhHw->Status |= QTD_STAT_DO_PING; - } + case EHC_INT_TRANSFER_ASYNC: + case EHC_INT_TRANSFER_SYNC: + // + // Special initialization for the interrupt transfer + // to set the S-Mask and C-Mask + // + QhHw->NakReload = 0; + EhcInitIntQh (Ep, QhHw); + break; + + case EHC_BULK_TRANSFER: + if ((Ep->DevSpeed == EFI_USB_SPEED_HIGH) && (Ep->Direction == EfiUsbDataOut)) { + QhHw->Status |= QTD_STAT_DO_PING; + } - break; + break; } return Qh; @@ -252,10 +253,10 @@ EhcCreateQh ( **/ UINTN EhcConvertPollRate ( - IN UINTN Interval + IN UINTN Interval ) { - UINTN BitCount; + UINTN BitCount; if (Interval == 0) { return 1; @@ -283,13 +284,13 @@ EhcConvertPollRate ( **/ VOID EhcFreeQtds ( - IN PEI_USB2_HC_DEV *Ehc, - IN EFI_LIST_ENTRY *Qtds + IN PEI_USB2_HC_DEV *Ehc, + IN EFI_LIST_ENTRY *Qtds ) { - EFI_LIST_ENTRY *Entry; - EFI_LIST_ENTRY *Next; - PEI_EHC_QTD *Qtd; + EFI_LIST_ENTRY *Entry; + EFI_LIST_ENTRY *Next; + PEI_EHC_QTD *Qtd; BASE_LIST_FOR_EACH_SAFE (Entry, Next, Qtds) { Qtd = EFI_LIST_CONTAINER (Entry, PEI_EHC_QTD, QtdList); @@ -308,8 +309,8 @@ EhcFreeQtds ( **/ VOID EhcFreeUrb ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb ) { if (Urb->RequestPhy != NULL) { @@ -342,20 +343,20 @@ EhcFreeUrb ( **/ EFI_STATUS EhcCreateQtds ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb ) { - USB_ENDPOINT *Ep; - PEI_EHC_QH *Qh; - PEI_EHC_QTD *Qtd; - PEI_EHC_QTD *StatusQtd; - PEI_EHC_QTD *NextQtd; - EFI_LIST_ENTRY *Entry; - UINT32 AlterNext; - UINT8 Toggle; - UINTN Len; - UINT8 Pid; + USB_ENDPOINT *Ep; + PEI_EHC_QH *Qh; + PEI_EHC_QTD *Qtd; + PEI_EHC_QTD *StatusQtd; + PEI_EHC_QTD *NextQtd; + EFI_LIST_ENTRY *Entry; + UINT32 AlterNext; + UINT8 Toggle; + UINTN Len; + UINT8 Pid; ASSERT ((Urb != NULL) && (Urb->Qh != NULL)); @@ -428,7 +429,7 @@ EhcCreateQtds ( while (Len < Urb->DataLen) { Qtd = EhcCreateQtd ( Ehc, - (UINT8 *) Urb->DataPhy + Len, + (UINT8 *)Urb->DataPhy + Len, Urb->DataLen - Len, Pid, Toggle, @@ -446,7 +447,7 @@ EhcCreateQtds ( // Switch the Toggle bit if odd number of packets are included in the QTD. // if (((Qtd->DataLen + Ep->MaxPacket - 1) / Ep->MaxPacket) % 2) { - Toggle = (UINT8) (1 - Toggle); + Toggle = (UINT8)(1 - Toggle); } Len += Qtd->DataLen; @@ -472,15 +473,15 @@ EhcCreateQtds ( break; } - NextQtd = EFI_LIST_CONTAINER (Entry->ForwardLink, PEI_EHC_QTD, QtdList); - Qtd->QtdHw.NextQtd = QTD_LINK (NextQtd, FALSE); + NextQtd = EFI_LIST_CONTAINER (Entry->ForwardLink, PEI_EHC_QTD, QtdList); + Qtd->QtdHw.NextQtd = QTD_LINK (NextQtd, FALSE); } // // Link the QTDs to the queue head // - NextQtd = EFI_LIST_CONTAINER (Qh->Qtds.ForwardLink, PEI_EHC_QTD, QtdList); - Qh->QhHw.NextQtd = QTD_LINK (NextQtd, FALSE); + NextQtd = EFI_LIST_CONTAINER (Qh->Qtds.ForwardLink, PEI_EHC_QTD, QtdList); + Qh->QhHw.NextQtd = QTD_LINK (NextQtd, FALSE); return EFI_SUCCESS; ON_ERROR: @@ -511,63 +512,63 @@ ON_ERROR: **/ PEI_URB * EhcCreateUrb ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN PEI_USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ) { - USB_ENDPOINT *Ep; - EFI_PHYSICAL_ADDRESS PhyAddr; - EDKII_IOMMU_OPERATION MapOp; - EFI_STATUS Status; - UINTN Len; - PEI_URB *Urb; - VOID *Map; + USB_ENDPOINT *Ep; + EFI_PHYSICAL_ADDRESS PhyAddr; + EDKII_IOMMU_OPERATION MapOp; + EFI_STATUS Status; + UINTN Len; + PEI_URB *Urb; + VOID *Map; Map = NULL; - Urb = Ehc->Urb; - Urb->Signature = EHC_URB_SIG; + Urb = Ehc->Urb; + Urb->Signature = EHC_URB_SIG; InitializeListHead (&Urb->UrbList); - Ep = &Urb->Ep; - Ep->DevAddr = DevAddr; - Ep->EpAddr = (UINT8) (EpAddr & 0x0F); - Ep->Direction = (((EpAddr & 0x80) != 0) ? EfiUsbDataIn : EfiUsbDataOut); - Ep->DevSpeed = DevSpeed; - Ep->MaxPacket = MaxPacket; + Ep = &Urb->Ep; + Ep->DevAddr = DevAddr; + Ep->EpAddr = (UINT8)(EpAddr & 0x0F); + Ep->Direction = (((EpAddr & 0x80) != 0) ? EfiUsbDataIn : EfiUsbDataOut); + Ep->DevSpeed = DevSpeed; + Ep->MaxPacket = MaxPacket; - Ep->HubAddr = 0; - Ep->HubPort = 0; + Ep->HubAddr = 0; + Ep->HubPort = 0; if (DevSpeed != EFI_USB_SPEED_HIGH) { ASSERT (Hub != NULL); - Ep->HubAddr = Hub->TranslatorHubAddress; - Ep->HubPort = Hub->TranslatorPortNumber; + Ep->HubAddr = Hub->TranslatorHubAddress; + Ep->HubPort = Hub->TranslatorPortNumber; } - Ep->Toggle = Toggle; - Ep->Type = Type; - Ep->PollRate = EhcConvertPollRate (Interval); + Ep->Toggle = Toggle; + Ep->Type = Type; + Ep->PollRate = EhcConvertPollRate (Interval); - Urb->Request = Request; - Urb->Data = Data; - Urb->DataLen = DataLen; - Urb->Callback = Callback; - Urb->Context = Context; - Urb->Qh = EhcCreateQh (Ehc, &Urb->Ep); + Urb->Request = Request; + Urb->Data = Data; + Urb->DataLen = DataLen; + Urb->Callback = Callback; + Urb->Context = Context; + Urb->Qh = EhcCreateQh (Ehc, &Urb->Ep); if (Urb->Qh == NULL) { goto ON_ERROR; @@ -575,27 +576,27 @@ EhcCreateUrb ( Urb->RequestPhy = NULL; Urb->RequestMap = NULL; - Urb->DataPhy = NULL; - Urb->DataMap = NULL; + Urb->DataPhy = NULL; + Urb->DataMap = NULL; // // Map the request and user data // if (Request != NULL) { - Len = sizeof (EFI_USB_DEVICE_REQUEST); - MapOp = EdkiiIoMmuOperationBusMasterRead; - Status = IoMmuMap (Ehc->IoMmu, MapOp, Request, &Len, &PhyAddr, &Map); + Len = sizeof (EFI_USB_DEVICE_REQUEST); + MapOp = EdkiiIoMmuOperationBusMasterRead; + Status = IoMmuMap (Ehc->IoMmu, MapOp, Request, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != sizeof (EFI_USB_DEVICE_REQUEST))) { goto ON_ERROR; } - Urb->RequestPhy = (VOID *) ((UINTN) PhyAddr); + Urb->RequestPhy = (VOID *)((UINTN)PhyAddr); Urb->RequestMap = Map; } if (Data != NULL) { - Len = DataLen; + Len = DataLen; if (Ep->Direction == EfiUsbDataIn) { MapOp = EdkiiIoMmuOperationBusMasterWrite; @@ -603,14 +604,14 @@ EhcCreateUrb ( MapOp = EdkiiIoMmuOperationBusMasterRead; } - Status = IoMmuMap (Ehc->IoMmu, MapOp, Data, &Len, &PhyAddr, &Map); + Status = IoMmuMap (Ehc->IoMmu, MapOp, Data, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != DataLen)) { goto ON_ERROR; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; } Status = EhcCreateQtds (Ehc, Urb); diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.h b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.h index 756b663fdb..9b8aa5de62 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.h +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.h @@ -10,60 +10,60 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_URB_H_ #define _EFI_EHCI_URB_H_ -typedef struct _PEI_EHC_QTD PEI_EHC_QTD; -typedef struct _PEI_EHC_QH PEI_EHC_QH; -typedef struct _PEI_URB PEI_URB; +typedef struct _PEI_EHC_QTD PEI_EHC_QTD; +typedef struct _PEI_EHC_QH PEI_EHC_QH; +typedef struct _PEI_URB PEI_URB; #define EHC_CTRL_TRANSFER 0x01 #define EHC_BULK_TRANSFER 0x02 #define EHC_INT_TRANSFER_SYNC 0x04 #define EHC_INT_TRANSFER_ASYNC 0x08 -#define EHC_QTD_SIG SIGNATURE_32 ('U', 'S', 'B', 'T') -#define EHC_QH_SIG SIGNATURE_32 ('U', 'S', 'B', 'H') -#define EHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') +#define EHC_QTD_SIG SIGNATURE_32 ('U', 'S', 'B', 'T') +#define EHC_QH_SIG SIGNATURE_32 ('U', 'S', 'B', 'H') +#define EHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') // // Hardware related bit definitions // -#define EHC_TYPE_ITD 0x00 -#define EHC_TYPE_QH 0x02 -#define EHC_TYPE_SITD 0x04 -#define EHC_TYPE_FSTN 0x06 - -#define QH_NAK_RELOAD 3 -#define QH_HSHBW_MULTI 1 - -#define QTD_MAX_ERR 3 -#define QTD_PID_OUTPUT 0x00 -#define QTD_PID_INPUT 0x01 -#define QTD_PID_SETUP 0x02 - -#define QTD_STAT_DO_OUT 0 -#define QTD_STAT_DO_SS 0 -#define QTD_STAT_DO_PING 0x01 -#define QTD_STAT_DO_CS 0x02 -#define QTD_STAT_TRANS_ERR 0x08 -#define QTD_STAT_BABBLE_ERR 0x10 -#define QTD_STAT_BUFF_ERR 0x20 -#define QTD_STAT_HALTED 0x40 -#define QTD_STAT_ACTIVE 0x80 -#define QTD_STAT_ERR_MASK (QTD_STAT_TRANS_ERR | QTD_STAT_BABBLE_ERR | QTD_STAT_BUFF_ERR) - -#define QTD_MAX_BUFFER 4 -#define QTD_BUF_LEN 4096 -#define QTD_BUF_MASK 0x0FFF - -#define QH_MICROFRAME_0 0x01 -#define QH_MICROFRAME_1 0x02 -#define QH_MICROFRAME_2 0x04 -#define QH_MICROFRAME_3 0x08 -#define QH_MICROFRAME_4 0x10 -#define QH_MICROFRAME_5 0x20 -#define QH_MICROFRAME_6 0x40 -#define QH_MICROFRAME_7 0x80 - -#define USB_ERR_SHORT_PACKET 0x200 +#define EHC_TYPE_ITD 0x00 +#define EHC_TYPE_QH 0x02 +#define EHC_TYPE_SITD 0x04 +#define EHC_TYPE_FSTN 0x06 + +#define QH_NAK_RELOAD 3 +#define QH_HSHBW_MULTI 1 + +#define QTD_MAX_ERR 3 +#define QTD_PID_OUTPUT 0x00 +#define QTD_PID_INPUT 0x01 +#define QTD_PID_SETUP 0x02 + +#define QTD_STAT_DO_OUT 0 +#define QTD_STAT_DO_SS 0 +#define QTD_STAT_DO_PING 0x01 +#define QTD_STAT_DO_CS 0x02 +#define QTD_STAT_TRANS_ERR 0x08 +#define QTD_STAT_BABBLE_ERR 0x10 +#define QTD_STAT_BUFF_ERR 0x20 +#define QTD_STAT_HALTED 0x40 +#define QTD_STAT_ACTIVE 0x80 +#define QTD_STAT_ERR_MASK (QTD_STAT_TRANS_ERR | QTD_STAT_BABBLE_ERR | QTD_STAT_BUFF_ERR) + +#define QTD_MAX_BUFFER 4 +#define QTD_BUF_LEN 4096 +#define QTD_BUF_MASK 0x0FFF + +#define QH_MICROFRAME_0 0x01 +#define QH_MICROFRAME_1 0x02 +#define QH_MICROFRAME_2 0x04 +#define QH_MICROFRAME_3 0x08 +#define QH_MICROFRAME_4 0x10 +#define QH_MICROFRAME_5 0x20 +#define QH_MICROFRAME_6 0x40 +#define QH_MICROFRAME_7 0x80 + +#define USB_ERR_SHORT_PACKET 0x200 // // Fill in the hardware link point: pass in a EHC_QH/QH_HW @@ -72,7 +72,7 @@ typedef struct _PEI_URB PEI_URB; #define QH_LINK(Addr, Type, Term) \ ((UINT32) ((EHC_LOW_32BIT (Addr) & 0xFFFFFFE0) | (Type) | ((Term) ? 1 : 0))) -#define QTD_LINK(Addr, Term) QH_LINK((Addr), 0, (Term)) +#define QTD_LINK(Addr, Term) QH_LINK((Addr), 0, (Term)) // // The defination of EHCI hardware used data structure for @@ -82,77 +82,76 @@ typedef struct _PEI_URB PEI_URB; // #pragma pack(1) typedef struct { - UINT32 NextQtd; - UINT32 AltNext; - - UINT32 Status : 8; - UINT32 Pid : 2; - UINT32 ErrCnt : 2; - UINT32 CurPage : 3; - UINT32 Ioc : 1; - UINT32 TotalBytes : 15; - UINT32 DataToggle : 1; - - UINT32 Page[5]; - UINT32 PageHigh[5]; + UINT32 NextQtd; + UINT32 AltNext; + + UINT32 Status : 8; + UINT32 Pid : 2; + UINT32 ErrCnt : 2; + UINT32 CurPage : 3; + UINT32 Ioc : 1; + UINT32 TotalBytes : 15; + UINT32 DataToggle : 1; + + UINT32 Page[5]; + UINT32 PageHigh[5]; } QTD_HW; typedef struct { - UINT32 HorizonLink; + UINT32 HorizonLink; // // Endpoint capabilities/Characteristics DWord 1 and DWord 2 // - UINT32 DeviceAddr : 7; - UINT32 Inactive : 1; - UINT32 EpNum : 4; - UINT32 EpSpeed : 2; - UINT32 DtCtrl : 1; - UINT32 ReclaimHead : 1; - UINT32 MaxPacketLen : 11; - UINT32 CtrlEp : 1; - UINT32 NakReload : 4; - - UINT32 SMask : 8; - UINT32 CMask : 8; - UINT32 HubAddr : 7; - UINT32 PortNum : 7; - UINT32 Multiplier : 2; + UINT32 DeviceAddr : 7; + UINT32 Inactive : 1; + UINT32 EpNum : 4; + UINT32 EpSpeed : 2; + UINT32 DtCtrl : 1; + UINT32 ReclaimHead : 1; + UINT32 MaxPacketLen : 11; + UINT32 CtrlEp : 1; + UINT32 NakReload : 4; + + UINT32 SMask : 8; + UINT32 CMask : 8; + UINT32 HubAddr : 7; + UINT32 PortNum : 7; + UINT32 Multiplier : 2; // // Transaction execution overlay area // - UINT32 CurQtd; - UINT32 NextQtd; - UINT32 AltQtd; - - UINT32 Status : 8; - UINT32 Pid : 2; - UINT32 ErrCnt : 2; - UINT32 CurPage : 3; - UINT32 Ioc : 1; - UINT32 TotalBytes : 15; - UINT32 DataToggle : 1; - - UINT32 Page[5]; - UINT32 PageHigh[5]; + UINT32 CurQtd; + UINT32 NextQtd; + UINT32 AltQtd; + + UINT32 Status : 8; + UINT32 Pid : 2; + UINT32 ErrCnt : 2; + UINT32 CurPage : 3; + UINT32 Ioc : 1; + UINT32 TotalBytes : 15; + UINT32 DataToggle : 1; + + UINT32 Page[5]; + UINT32 PageHigh[5]; } QH_HW; #pragma pack() - // // Endpoint address and its capabilities // typedef struct _USB_ENDPOINT { - UINT8 DevAddr; - UINT8 EpAddr; // Endpoint address, no direction encoded in - EFI_USB_DATA_DIRECTION Direction; - UINT8 DevSpeed; - UINTN MaxPacket; - UINT8 HubAddr; - UINT8 HubPort; - UINT8 Toggle; // Data toggle, not used for control transfer - UINTN Type; - UINTN PollRate; // Polling interval used by EHCI + UINT8 DevAddr; + UINT8 EpAddr; // Endpoint address, no direction encoded in + EFI_USB_DATA_DIRECTION Direction; + UINT8 DevSpeed; + UINTN MaxPacket; + UINT8 HubAddr; + UINT8 HubPort; + UINT8 Toggle; // Data toggle, not used for control transfer + UINTN Type; + UINTN PollRate; // Polling interval used by EHCI } USB_ENDPOINT; // @@ -160,15 +159,13 @@ typedef struct _USB_ENDPOINT { // QTD generated from a URB. Don't add fields before QtdHw. // struct _PEI_EHC_QTD { - QTD_HW QtdHw; - UINT32 Signature; - EFI_LIST_ENTRY QtdList; // The list of QTDs to one end point - UINT8 *Data; // Buffer of the original data - UINTN DataLen; // Original amount of data in this QTD + QTD_HW QtdHw; + UINT32 Signature; + EFI_LIST_ENTRY QtdList; // The list of QTDs to one end point + UINT8 *Data; // Buffer of the original data + UINTN DataLen; // Original amount of data in this QTD }; - - // // Software QH structure. All three different transaction types // supported by UEFI USB, that is the control/bulk/interrupt @@ -185,11 +182,11 @@ struct _PEI_EHC_QTD { // as the reclamation header. New transfer is inserted after this QH. // struct _PEI_EHC_QH { - QH_HW QhHw; - UINT32 Signature; - PEI_EHC_QH *NextQh; // The queue head pointed to by horizontal link - EFI_LIST_ENTRY Qtds; // The list of QTDs to this queue head - UINTN Interval; + QH_HW QhHw; + UINT32 Signature; + PEI_EHC_QH *NextQh; // The queue head pointed to by horizontal link + EFI_LIST_ENTRY Qtds; // The list of QTDs to this queue head + UINTN Interval; }; // @@ -197,34 +194,34 @@ struct _PEI_EHC_QH { // usb requests. // struct _PEI_URB { - UINT32 Signature; - EFI_LIST_ENTRY UrbList; + UINT32 Signature; + EFI_LIST_ENTRY UrbList; // // Transaction information // - USB_ENDPOINT Ep; - EFI_USB_DEVICE_REQUEST *Request; // Control transfer only - VOID *RequestPhy; // Address of the mapped request - VOID *RequestMap; - VOID *Data; - UINTN DataLen; - VOID *DataPhy; // Address of the mapped user data - VOID *DataMap; - EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; - VOID *Context; + USB_ENDPOINT Ep; + EFI_USB_DEVICE_REQUEST *Request; // Control transfer only + VOID *RequestPhy; // Address of the mapped request + VOID *RequestMap; + VOID *Data; + UINTN DataLen; + VOID *DataPhy; // Address of the mapped user data + VOID *DataMap; + EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; + VOID *Context; // // Schedule data // - PEI_EHC_QH *Qh; + PEI_EHC_QH *Qh; // // Transaction result // - UINT32 Result; - UINTN Completed; // completed data length - UINT8 DataToggle; + UINT32 Result; + UINTN Completed; // completed data length + UINT8 DataToggle; }; /** @@ -243,12 +240,12 @@ struct _PEI_URB { **/ PEI_EHC_QTD * EhcCreateQtd ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT8 *Data, - IN UINTN DataLen, - IN UINT8 PktId, - IN UINT8 Toggle, - IN UINTN MaxPacket + IN PEI_USB2_HC_DEV *Ehc, + IN UINT8 *Data, + IN UINTN DataLen, + IN UINT8 PktId, + IN UINT8 Toggle, + IN UINTN MaxPacket ) ; @@ -263,8 +260,8 @@ EhcCreateQtd ( **/ PEI_EHC_QH * EhcCreateQh ( - IN PEI_USB2_HC_DEV *Ehci, - IN USB_ENDPOINT *Ep + IN PEI_USB2_HC_DEV *Ehci, + IN USB_ENDPOINT *Ep ) ; @@ -277,8 +274,8 @@ EhcCreateQh ( **/ VOID EhcFreeUrb ( - IN PEI_USB2_HC_DEV *Ehc, - IN PEI_URB *Urb + IN PEI_USB2_HC_DEV *Ehc, + IN PEI_URB *Urb ) ; @@ -305,20 +302,21 @@ EhcFreeUrb ( **/ PEI_URB * EhcCreateUrb ( - IN PEI_USB2_HC_DEV *Ehc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINT8 Toggle, - IN UINTN MaxPacket, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context, - IN UINTN Interval + IN PEI_USB2_HC_DEV *Ehc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINT8 Toggle, + IN UINTN MaxPacket, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Hub, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context, + IN UINTN Interval ) ; + #endif diff --git a/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.c b/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.c index 269b3edb84..4b1fdcec80 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.c @@ -22,30 +22,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USBHC_MEM_BLOCK * UsbHcAllocMemBlock ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN UINTN Pages + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN UINTN Pages ) { - USBHC_MEM_BLOCK *Block; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - EFI_STATUS Status; - UINTN PageNumber; - EFI_PHYSICAL_ADDRESS TempPtr; - - Mapping = NULL; - PageNumber = sizeof(USBHC_MEM_BLOCK)/PAGESIZE +1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - PageNumber, - &TempPtr - ); + USBHC_MEM_BLOCK *Block; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + EFI_STATUS Status; + UINTN PageNumber; + EFI_PHYSICAL_ADDRESS TempPtr; + + Mapping = NULL; + PageNumber = sizeof (USBHC_MEM_BLOCK)/PAGESIZE +1; + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + PageNumber, + &TempPtr + ); if (EFI_ERROR (Status)) { - return NULL; + return NULL; } + ZeroMem ((VOID *)(UINTN)TempPtr, PageNumber*EFI_PAGE_SIZE); // @@ -54,34 +55,36 @@ UsbHcAllocMemBlock ( // ASSERT (USBHC_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block = (USBHC_MEM_BLOCK*)(UINTN)TempPtr; - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); + Block = (USBHC_MEM_BLOCK *)(UINTN)TempPtr; + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); PageNumber = (Block->BitsLen)/PAGESIZE +1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - PageNumber, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + PageNumber, + &TempPtr + ); + + if (EFI_ERROR (Status)) { + return NULL; + } - if (EFI_ERROR (Status)) { - return NULL; - } ZeroMem ((VOID *)(UINTN)TempPtr, PageNumber*EFI_PAGE_SIZE); - Block->Bits = (UINT8 *)(UINTN)TempPtr; + Block->Bits = (UINT8 *)(UINTN)TempPtr; Status = IoMmuAllocateBuffer ( Ehc->IoMmu, Pages, - (VOID **) &BufHost, + (VOID **)&BufHost, &MappedAddr, &Mapping ); if (EFI_ERROR (Status)) { return NULL; } + ZeroMem (BufHost, Pages*EFI_PAGE_SIZE); // @@ -89,16 +92,15 @@ UsbHcAllocMemBlock ( // should be restricted into the same 4G // if (Pool->Check4G && (Pool->Which4G != USB_HC_HIGH_32BIT (MappedAddr))) { - return NULL; + return NULL; } - Block->BufHost = BufHost; - Block->Buf = (UINT8 *) ((UINTN) MappedAddr); - Block->Mapping = Mapping; - Block->Next = NULL; + Block->BufHost = BufHost; + Block->Buf = (UINT8 *)((UINTN)MappedAddr); + Block->Mapping = Mapping; + Block->Next = NULL; return Block; - } /** @@ -111,9 +113,9 @@ UsbHcAllocMemBlock ( **/ VOID UsbHcFreeMemBlock ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN USBHC_MEM_BLOCK *Block + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Pool != NULL) && (Block != NULL)); @@ -133,22 +135,22 @@ UsbHcFreeMemBlock ( **/ VOID * UsbHcAllocMemFromBlock ( - IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN USBHC_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -164,13 +166,12 @@ UsbHcAllocMemFromBlock ( } NEXT_BIT (Byte, Bit); - } else { NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -181,13 +182,13 @@ UsbHcAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -205,16 +206,16 @@ UsbHcAllocMemFromBlock ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINTN AllocSize; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINTN Offset; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINTN AllocSize; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINTN Offset; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); @@ -228,7 +229,7 @@ UsbHcGetPciAddressForHostMem ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->BufHost <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { + if ((Block->BufHost <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { break; } } @@ -237,8 +238,8 @@ UsbHcGetPciAddressForHostMem ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *)Mem - Block->BufHost; - PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN) (Block->Buf + Offset); + Offset = (UINT8 *)Mem - Block->BufHost; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->Buf + Offset); return PhyAddr; } @@ -251,8 +252,8 @@ UsbHcGetPciAddressForHostMem ( **/ VOID UsbHcInsertMemBlockToPool ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -271,11 +272,10 @@ UsbHcInsertMemBlockToPool ( **/ BOOLEAN UsbHcIsMemBlockEmpty ( - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Block ) { - UINTN Index; - + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -286,7 +286,6 @@ UsbHcIsMemBlockEmpty ( return TRUE; } - /** Initialize the memory management pool for the host controller. @@ -301,29 +300,30 @@ UsbHcIsMemBlockEmpty ( **/ USBHC_MEM_POOL * UsbHcInitMemPool ( - IN PEI_USB2_HC_DEV *Ehc, - IN BOOLEAN Check4G, - IN UINT32 Which4G + IN PEI_USB2_HC_DEV *Ehc, + IN BOOLEAN Check4G, + IN UINT32 Which4G ) { - USBHC_MEM_POOL *Pool; - UINTN PageNumber; - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS TempPtr; - - PageNumber = sizeof(USBHC_MEM_POOL)/PAGESIZE +1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - PageNumber, - &TempPtr - ); + USBHC_MEM_POOL *Pool; + UINTN PageNumber; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS TempPtr; + + PageNumber = sizeof (USBHC_MEM_POOL)/PAGESIZE +1; + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + PageNumber, + &TempPtr + ); + + if (EFI_ERROR (Status)) { + return NULL; + } - if (EFI_ERROR (Status)) { - return NULL; - } ZeroMem ((VOID *)(UINTN)TempPtr, PageNumber*EFI_PAGE_SIZE); - Pool = (USBHC_MEM_POOL *) ((UINTN) TempPtr); + Pool = (USBHC_MEM_POOL *)((UINTN)TempPtr); Pool->Check4G = Check4G; Pool->Which4G = Which4G; @@ -348,11 +348,11 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -381,17 +381,17 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - USBHC_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = USBHC_MEM_ROUND (Size); @@ -425,7 +425,8 @@ UsbHcAllocateMem ( } else { Pages = USBHC_MEM_DEFAULT_PAGES; } - NewBlock = UsbHcAllocMemBlock (Ehc,Pool, Pages); + + NewBlock = UsbHcAllocMemBlock (Ehc, Pool, Pages); if (NewBlock == NULL) { return NULL; @@ -455,23 +456,23 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN PEI_USB2_HC_DEV *Ehc, - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN PEI_USB2_HC_DEV *Ehc, + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -482,8 +483,8 @@ UsbHcFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) / 8; - Bit = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) % 8; + Byte = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) / 8; + Bit = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -491,7 +492,7 @@ UsbHcFreeMem ( for (Count = 0; Count < (AllocSize / USBHC_MEM_UNIT); Count++) { ASSERT (USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -513,5 +514,5 @@ UsbHcFreeMem ( UsbHcFreeMemBlock (Ehc, Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.h b/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.h index 21b2d7fa9f..7151dbc6e4 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/EhciPei/UsbHcMem.h @@ -13,7 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define USB_HC_BIT(a) ((UINTN)(1 << (a))) +#define USB_HC_BIT(a) ((UINTN)(1 << (a))) #define USB_HC_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & USB_HC_BIT(Bit)) == USB_HC_BIT(Bit))) @@ -24,13 +24,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _USBHC_MEM_BLOCK USBHC_MEM_BLOCK; struct _USBHC_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - USBHC_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + USBHC_MEM_BLOCK *Next; }; // @@ -39,15 +39,15 @@ struct _USBHC_MEM_BLOCK { // data to be on the same 4G memory. // typedef struct _USBHC_MEM_POOL { - BOOLEAN Check4G; - UINT32 Which4G; - USBHC_MEM_BLOCK *Head; + BOOLEAN Check4G; + UINT32 Which4G; + USBHC_MEM_BLOCK *Head; } USBHC_MEM_POOL; // // Memory allocation unit, must be 2^n, n>4 // -#define USBHC_MEM_UNIT 64 +#define USBHC_MEM_UNIT 64 #define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) #define USBHC_MEM_DEFAULT_PAGES 16 @@ -66,7 +66,6 @@ typedef struct _USBHC_MEM_POOL { } \ } while (0) - /** Calculate the corresponding pci bus address according to the Mem parameter. @@ -78,9 +77,9 @@ typedef struct _USBHC_MEM_POOL { **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); #endif diff --git a/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.c b/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.c index 436d5971d0..3f5462c257 100644 --- a/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.c +++ b/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.c @@ -26,8 +26,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI AtapiPeimEntry ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { PEI_ATA_CONTROLLER_PPI *AtaControllerPpi; @@ -40,11 +40,11 @@ AtapiPeimEntry ( } Status = PeiServicesLocatePpi ( - &gPeiAtaControllerPpiGuid, - 0, - NULL, - (VOID **) &AtaControllerPpi - ); + &gPeiAtaControllerPpiGuid, + 0, + NULL, + (VOID **)&AtaControllerPpi + ); ASSERT_EFI_ERROR (Status); AtapiBlkIoDev = AllocatePages (EFI_SIZE_TO_PAGES (sizeof (*AtapiBlkIoDev))); @@ -60,21 +60,21 @@ AtapiPeimEntry ( // AtapiEnumerateDevices (AtapiBlkIoDev); - AtapiBlkIoDev->AtapiBlkIo.GetNumberOfBlockDevices = AtapiGetNumberOfBlockDevices; - AtapiBlkIoDev->AtapiBlkIo.GetBlockDeviceMediaInfo = AtapiGetBlockDeviceMediaInfo; - AtapiBlkIoDev->AtapiBlkIo.ReadBlocks = AtapiReadBlocks; + AtapiBlkIoDev->AtapiBlkIo.GetNumberOfBlockDevices = AtapiGetNumberOfBlockDevices; + AtapiBlkIoDev->AtapiBlkIo.GetBlockDeviceMediaInfo = AtapiGetBlockDeviceMediaInfo; + AtapiBlkIoDev->AtapiBlkIo.ReadBlocks = AtapiReadBlocks; AtapiBlkIoDev->AtapiBlkIo2.Revision = EFI_PEI_RECOVERY_BLOCK_IO2_PPI_REVISION; AtapiBlkIoDev->AtapiBlkIo2.GetNumberOfBlockDevices = AtapiGetNumberOfBlockDevices2; AtapiBlkIoDev->AtapiBlkIo2.GetBlockDeviceMediaInfo = AtapiGetBlockDeviceMediaInfo2; AtapiBlkIoDev->AtapiBlkIo2.ReadBlocks = AtapiReadBlocks2; - AtapiBlkIoDev->PpiDescriptor.Flags = EFI_PEI_PPI_DESCRIPTOR_PPI; - AtapiBlkIoDev->PpiDescriptor.Guid = &gEfiPeiVirtualBlockIoPpiGuid; - AtapiBlkIoDev->PpiDescriptor.Ppi = &AtapiBlkIoDev->AtapiBlkIo; + AtapiBlkIoDev->PpiDescriptor.Flags = EFI_PEI_PPI_DESCRIPTOR_PPI; + AtapiBlkIoDev->PpiDescriptor.Guid = &gEfiPeiVirtualBlockIoPpiGuid; + AtapiBlkIoDev->PpiDescriptor.Ppi = &AtapiBlkIoDev->AtapiBlkIo; - AtapiBlkIoDev->PpiDescriptor2.Flags = (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - AtapiBlkIoDev->PpiDescriptor2.Guid = &gEfiPeiVirtualBlockIo2PpiGuid; - AtapiBlkIoDev->PpiDescriptor2.Ppi = &AtapiBlkIoDev->AtapiBlkIo2; + AtapiBlkIoDev->PpiDescriptor2.Flags = (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); + AtapiBlkIoDev->PpiDescriptor2.Guid = &gEfiPeiVirtualBlockIo2PpiGuid; + AtapiBlkIoDev->PpiDescriptor2.Ppi = &AtapiBlkIoDev->AtapiBlkIo2; DEBUG ((DEBUG_INFO, "Atatpi Device Count is %d\n", AtapiBlkIoDev->DeviceCount)); if (AtapiBlkIoDev->DeviceCount != 0) { @@ -109,16 +109,16 @@ AtapiPeimEntry ( EFI_STATUS EFIAPI AtapiGetNumberOfBlockDevices ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + OUT UINTN *NumberBlockDevices ) { ATAPI_BLK_IO_DEV *AtapiBlkIoDev; AtapiBlkIoDev = NULL; - AtapiBlkIoDev = PEI_RECOVERY_ATAPI_FROM_BLKIO_THIS (This); + AtapiBlkIoDev = PEI_RECOVERY_ATAPI_FROM_BLKIO_THIS (This); *NumberBlockDevices = AtapiBlkIoDev->DeviceCount; @@ -156,10 +156,10 @@ AtapiGetNumberOfBlockDevices ( EFI_STATUS EFIAPI AtapiGetBlockDeviceMediaInfo ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { UINTN DeviceCount; @@ -169,13 +169,13 @@ AtapiGetBlockDeviceMediaInfo ( AtapiBlkIoDev = NULL; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } AtapiBlkIoDev = PEI_RECOVERY_ATAPI_FROM_BLKIO_THIS (This); - DeviceCount = AtapiBlkIoDev->DeviceCount; + DeviceCount = AtapiBlkIoDev->DeviceCount; // // DeviceIndex is a value from 1 to NumberBlockDevices. @@ -214,7 +214,7 @@ AtapiGetBlockDeviceMediaInfo ( // // Get media info from AtapiBlkIoDev // - CopyMem (MediaInfo, &AtapiBlkIoDev->DeviceInfo[Index].MediaInfo, sizeof(EFI_PEI_BLOCK_IO_MEDIA)); + CopyMem (MediaInfo, &AtapiBlkIoDev->DeviceInfo[Index].MediaInfo, sizeof (EFI_PEI_BLOCK_IO_MEDIA)); return EFI_SUCCESS; } @@ -256,15 +256,14 @@ AtapiGetBlockDeviceMediaInfo ( EFI_STATUS EFIAPI AtapiReadBlocks ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_PEI_BLOCK_IO_MEDIA MediaInfo; EFI_STATUS Status; UINTN NumberOfBlocks; @@ -288,11 +287,11 @@ AtapiReadBlocks ( } Status = AtapiGetBlockDeviceMediaInfo ( - PeiServices, - This, - DeviceIndex, - &MediaInfo - ); + PeiServices, + This, + DeviceIndex, + &MediaInfo + ); if (Status != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } @@ -314,13 +313,13 @@ AtapiReadBlocks ( } Status = ReadSectors ( - AtapiBlkIoDev, - AtapiBlkIoDev->DeviceInfo[DeviceIndex - 1].DevicePosition, - Buffer, - StartLBA, - NumberOfBlocks, - BlockSize - ); + AtapiBlkIoDev, + AtapiBlkIoDev->DeviceInfo[DeviceIndex - 1].DevicePosition, + Buffer, + StartLBA, + NumberOfBlocks, + BlockSize + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } @@ -350,9 +349,9 @@ AtapiReadBlocks ( EFI_STATUS EFIAPI AtapiGetNumberOfBlockDevices2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ) { EFI_STATUS Status; @@ -400,19 +399,19 @@ AtapiGetNumberOfBlockDevices2 ( EFI_STATUS EFIAPI AtapiGetBlockDeviceMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - ATAPI_BLK_IO_DEV *AtapiBlkIoDev; - EFI_STATUS Status; - EFI_PEI_BLOCK_IO_MEDIA Media; + ATAPI_BLK_IO_DEV *AtapiBlkIoDev; + EFI_STATUS Status; + EFI_PEI_BLOCK_IO_MEDIA Media; AtapiBlkIoDev = NULL; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } @@ -427,10 +426,11 @@ AtapiGetBlockDeviceMediaInfo2 ( if (EFI_ERROR (Status)) { return Status; } + // // Get media info from AtapiBlkIoDev // - CopyMem (MediaInfo, &AtapiBlkIoDev->DeviceInfo[DeviceIndex - 1].MediaInfo2, sizeof(EFI_PEI_BLOCK_IO2_MEDIA)); + CopyMem (MediaInfo, &AtapiBlkIoDev->DeviceInfo[DeviceIndex - 1].MediaInfo2, sizeof (EFI_PEI_BLOCK_IO2_MEDIA)); return EFI_SUCCESS; } @@ -472,16 +472,16 @@ AtapiGetBlockDeviceMediaInfo2 ( EFI_STATUS EFIAPI AtapiReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - ATAPI_BLK_IO_DEV *AtapiBlkIoDev; + EFI_STATUS Status; + ATAPI_BLK_IO_DEV *AtapiBlkIoDev; AtapiBlkIoDev = NULL; @@ -503,7 +503,6 @@ AtapiReadBlocks2 ( return Status; } - /** Enumerate Atapi devices. @@ -517,19 +516,19 @@ AtapiEnumerateDevices ( IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev ) { - UINT8 Index1; - UINT8 Index2; - UINTN DevicePosition; - EFI_PEI_BLOCK_IO_MEDIA MediaInfo; - EFI_PEI_BLOCK_IO2_MEDIA MediaInfo2; - EFI_STATUS Status; - UINTN DeviceCount; - UINT16 CommandBlockBaseAddr; - UINT16 ControlBlockBaseAddr; - UINT32 IdeEnabledNumber; - IDE_REGS_BASE_ADDR IdeRegsBaseAddr[MAX_IDE_CHANNELS]; - - DeviceCount = 0; + UINT8 Index1; + UINT8 Index2; + UINTN DevicePosition; + EFI_PEI_BLOCK_IO_MEDIA MediaInfo; + EFI_PEI_BLOCK_IO2_MEDIA MediaInfo2; + EFI_STATUS Status; + UINTN DeviceCount; + UINT16 CommandBlockBaseAddr; + UINT16 ControlBlockBaseAddr; + UINT32 IdeEnabledNumber; + IDE_REGS_BASE_ADDR IdeRegsBaseAddr[MAX_IDE_CHANNELS]; + + DeviceCount = 0; DevicePosition = 0; // @@ -540,10 +539,10 @@ AtapiEnumerateDevices ( // Enable Sata and IDE controller. // AtapiBlkIoDev->AtaControllerPpi->EnableAtaChannel ( - (EFI_PEI_SERVICES **) GetPeiServicesTablePointer(), - AtapiBlkIoDev->AtaControllerPpi, - PEI_ICH_IDE_PRIMARY | PEI_ICH_IDE_SECONDARY - ); + (EFI_PEI_SERVICES **)GetPeiServicesTablePointer (), + AtapiBlkIoDev->AtaControllerPpi, + PEI_ICH_IDE_PRIMARY | PEI_ICH_IDE_SECONDARY + ); // // Allow SATA Devices to spin-up. This is needed if @@ -556,28 +555,28 @@ AtapiEnumerateDevices ( // Get four channels (primary or secondary Pata, Sata Channel) Command and Control Regs Base address. // IdeEnabledNumber = AtapiBlkIoDev->AtaControllerPpi->GetIdeRegsBaseAddr ( - (EFI_PEI_SERVICES **) GetPeiServicesTablePointer(), - AtapiBlkIoDev->AtaControllerPpi, - IdeRegsBaseAddr - ); + (EFI_PEI_SERVICES **)GetPeiServicesTablePointer (), + AtapiBlkIoDev->AtaControllerPpi, + IdeRegsBaseAddr + ); // // Using Command and Control Regs Base Address to fill other registers. // - for (Index1 = 0; Index1 < IdeEnabledNumber; Index1 ++) { - CommandBlockBaseAddr = IdeRegsBaseAddr[Index1].CommandBlockBaseAddr; + for (Index1 = 0; Index1 < IdeEnabledNumber; Index1++) { + CommandBlockBaseAddr = IdeRegsBaseAddr[Index1].CommandBlockBaseAddr; AtapiBlkIoDev->IdeIoPortReg[Index1].Data = CommandBlockBaseAddr; - AtapiBlkIoDev->IdeIoPortReg[Index1].Reg1.Feature = (UINT16) (CommandBlockBaseAddr + 0x1); - AtapiBlkIoDev->IdeIoPortReg[Index1].SectorCount = (UINT16) (CommandBlockBaseAddr + 0x2); - AtapiBlkIoDev->IdeIoPortReg[Index1].SectorNumber = (UINT16) (CommandBlockBaseAddr + 0x3); - AtapiBlkIoDev->IdeIoPortReg[Index1].CylinderLsb = (UINT16) (CommandBlockBaseAddr + 0x4); - AtapiBlkIoDev->IdeIoPortReg[Index1].CylinderMsb = (UINT16) (CommandBlockBaseAddr + 0x5); - AtapiBlkIoDev->IdeIoPortReg[Index1].Head = (UINT16) (CommandBlockBaseAddr + 0x6); - AtapiBlkIoDev->IdeIoPortReg[Index1].Reg.Command = (UINT16) (CommandBlockBaseAddr + 0x7); - - ControlBlockBaseAddr = IdeRegsBaseAddr[Index1].ControlBlockBaseAddr; + AtapiBlkIoDev->IdeIoPortReg[Index1].Reg1.Feature = (UINT16)(CommandBlockBaseAddr + 0x1); + AtapiBlkIoDev->IdeIoPortReg[Index1].SectorCount = (UINT16)(CommandBlockBaseAddr + 0x2); + AtapiBlkIoDev->IdeIoPortReg[Index1].SectorNumber = (UINT16)(CommandBlockBaseAddr + 0x3); + AtapiBlkIoDev->IdeIoPortReg[Index1].CylinderLsb = (UINT16)(CommandBlockBaseAddr + 0x4); + AtapiBlkIoDev->IdeIoPortReg[Index1].CylinderMsb = (UINT16)(CommandBlockBaseAddr + 0x5); + AtapiBlkIoDev->IdeIoPortReg[Index1].Head = (UINT16)(CommandBlockBaseAddr + 0x6); + AtapiBlkIoDev->IdeIoPortReg[Index1].Reg.Command = (UINT16)(CommandBlockBaseAddr + 0x7); + + ControlBlockBaseAddr = IdeRegsBaseAddr[Index1].ControlBlockBaseAddr; AtapiBlkIoDev->IdeIoPortReg[Index1].Alt.DeviceControl = ControlBlockBaseAddr; - AtapiBlkIoDev->IdeIoPortReg[Index1].DriveAddress = (UINT16) (ControlBlockBaseAddr + 0x1); + AtapiBlkIoDev->IdeIoPortReg[Index1].DriveAddress = (UINT16)(ControlBlockBaseAddr + 0x1); // // Scan IDE bus for ATAPI devices IDE or Sata device @@ -596,7 +595,7 @@ AtapiEnumerateDevices ( // // Retrieve Media Info // - Status = DetectMedia (AtapiBlkIoDev, DevicePosition, &MediaInfo, &MediaInfo2); + Status = DetectMedia (AtapiBlkIoDev, DevicePosition, &MediaInfo, &MediaInfo2); CopyMem (&(AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo), &MediaInfo, sizeof (MediaInfo)); CopyMem (&(AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo2), &MediaInfo2, sizeof (MediaInfo2)); @@ -606,11 +605,12 @@ AtapiEnumerateDevices ( DEBUG ((DEBUG_INFO, "Atatpi BlockSize is 0x%x\n", MediaInfo.BlockSize)); if (EFI_ERROR (Status)) { - AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo.MediaPresent = FALSE; - AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo.LastBlock = 0; + AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo.MediaPresent = FALSE; + AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo.LastBlock = 0; AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo2.MediaPresent = FALSE; AtapiBlkIoDev->DeviceInfo[DeviceCount].MediaInfo2.LastBlock = 0; } + DeviceCount += 1; } } @@ -633,10 +633,10 @@ AtapiEnumerateDevices ( **/ BOOLEAN DiscoverAtapiDevice ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ) { EFI_STATUS Status; @@ -644,11 +644,11 @@ DiscoverAtapiDevice ( if (!DetectIDEController (AtapiBlkIoDev, DevicePosition)) { return FALSE; } + // // test if it is an ATAPI device (only supported device) // if (ATAPIIdentify (AtapiBlkIoDev, DevicePosition) == EFI_SUCCESS) { - Status = Inquiry (AtapiBlkIoDev, DevicePosition, MediaInfo, MediaInfo2); if (!EFI_ERROR (Status)) { return TRUE; @@ -673,9 +673,9 @@ DiscoverAtapiDevice ( **/ EFI_STATUS CheckPowerMode ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN UINT8 AtaCommand + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN UINT8 AtaCommand ) { UINT8 Channel; @@ -690,8 +690,8 @@ CheckPowerMode ( UINT8 ErrorValue; UINT8 SectorCountValue; - Channel = (UINT8) (DevicePosition / 2); - Device = (UINT8) (DevicePosition % 2); + Channel = (UINT8)(DevicePosition / 2); + Device = (UINT8)(DevicePosition % 2); ASSERT (Channel < MAX_IDE_CHANNELS); @@ -704,7 +704,7 @@ CheckPowerMode ( // // select device // - IoWrite8 (HeadRegister, (UINT8) ((Device << 4) | 0xe0)); + IoWrite8 (HeadRegister, (UINT8)((Device << 4) | 0xe0)); // // refresh the SectorCount register @@ -715,14 +715,14 @@ CheckPowerMode ( // // select device // - IoWrite8 (HeadRegister, (UINT8) ((Device << 4) | 0xe0)); + IoWrite8 (HeadRegister, (UINT8)((Device << 4) | 0xe0)); Status = DRDYReady (AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), 100); // // select device // - IoWrite8 (HeadRegister, (UINT8) ((Device << 4) | 0xe0)); + IoWrite8 (HeadRegister, (UINT8)((Device << 4) | 0xe0)); // // send 'check power' commandd via Command Register // @@ -766,7 +766,7 @@ CheckPowerMode ( // Write SectorCount 0x55 but return valid state value. Maybe no device // exists or some slow kind of ATAPI device exists. // - IoWrite8 (HeadRegister, (UINT8) ((Device << 4) | 0xe0)); + IoWrite8 (HeadRegister, (UINT8)((Device << 4) | 0xe0)); // // write 0x55 and 0xaa to SectorCounter register, @@ -781,6 +781,7 @@ CheckPowerMode ( if (SectorCountValue != 0x55) { return EFI_NOT_FOUND; } + // // Send a "ATAPI TEST UNIT READY" command ... slow but accurate // @@ -803,15 +804,15 @@ CheckPowerMode ( **/ BOOLEAN DetectIDEController ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition ) { UINT8 Channel; EFI_STATUS Status; UINT8 AtaCommand; - Channel = (UINT8) (DevicePosition / 2); + Channel = (UINT8)(DevicePosition / 2); ASSERT (Channel < MAX_IDE_CHANNELS); // @@ -821,11 +822,12 @@ DetectIDEController ( if (EFI_ERROR (Status)) { return FALSE; } + // // Send 'check power' command for IDE device // - AtaCommand = 0xE5; - Status = CheckPowerMode (AtapiBlkIoDev, DevicePosition, AtaCommand); + AtaCommand = 0xE5; + Status = CheckPowerMode (AtapiBlkIoDev, DevicePosition, AtaCommand); if ((Status == EFI_ABORTED) || (Status == EFI_SUCCESS)) { return TRUE; } @@ -855,20 +857,20 @@ WaitForBSYClear ( UINT16 StatusRegister; UINT8 StatusValue; - StatusValue = 0; + StatusValue = 0; - StatusRegister = IdeIoRegisters->Reg.Status; + StatusRegister = IdeIoRegisters->Reg.Status; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { StatusValue = IoRead8 (StatusRegister); if ((StatusValue & ATA_STSREG_BSY) == 0x00) { break; } + MicroSecondDelay (250); Delay--; - } while (Delay != 0); if (Delay == 0) { @@ -901,11 +903,11 @@ DRDYReady ( UINT8 StatusValue; UINT8 ErrValue; - StatusValue = 0; + StatusValue = 0; - StatusRegister = IdeIoRegisters->Reg.Status; + StatusRegister = IdeIoRegisters->Reg.Status; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { StatusValue = IoRead8 (StatusRegister); // @@ -915,17 +917,16 @@ DRDYReady ( break; } - if ((StatusValue & (ATA_STSREG_ERR | ATA_STSREG_BSY)) == ATA_STSREG_ERR) { - ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); - if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { - return EFI_ABORTED; + if ((StatusValue & (ATA_STSREG_ERR | ATA_STSREG_BSY)) == ATA_STSREG_ERR) { + ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); + if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { + return EFI_ABORTED; + } } - } MicroSecondDelay (250); Delay--; - } while (Delay != 0); if (Delay == 0) { @@ -958,13 +959,12 @@ DRQClear ( UINT8 StatusValue; UINT8 ErrValue; - StatusValue = 0; + StatusValue = 0; - StatusRegister = IdeIoRegisters->Reg.Status; + StatusRegister = IdeIoRegisters->Reg.Status; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { - StatusValue = IoRead8 (StatusRegister); // @@ -974,12 +974,12 @@ DRQClear ( break; } - if ((StatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { - ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); - if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { - return EFI_ABORTED; + if ((StatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { + ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); + if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { + return EFI_ABORTED; + } } - } MicroSecondDelay (250); @@ -1016,13 +1016,12 @@ DRQClear2 ( UINT8 AltStatusValue; UINT8 ErrValue; - AltStatusValue = 0; + AltStatusValue = 0; AltStatusRegister = IdeIoRegisters->Alt.AltStatus; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { - AltStatusValue = IoRead8 (AltStatusRegister); // @@ -1032,12 +1031,12 @@ DRQClear2 ( break; } - if ((AltStatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { - ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); - if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { - return EFI_ABORTED; + if ((AltStatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { + ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); + if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { + return EFI_ABORTED; + } } - } MicroSecondDelay (250); @@ -1075,12 +1074,12 @@ DRQReady ( UINT8 StatusValue; UINT8 ErrValue; - StatusValue = 0; - ErrValue = 0; + StatusValue = 0; + ErrValue = 0; - StatusRegister = IdeIoRegisters->Reg.Status; + StatusRegister = IdeIoRegisters->Reg.Status; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { // // read Status Register will clear interrupt @@ -1095,12 +1094,12 @@ DRQReady ( } if ((StatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { - ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { return EFI_ABORTED; } } + MicroSecondDelay (250); Delay--; @@ -1137,13 +1136,12 @@ DRQReady2 ( UINT8 AltStatusValue; UINT8 ErrValue; - AltStatusValue = 0; + AltStatusValue = 0; AltStatusRegister = IdeIoRegisters->Alt.AltStatus; - Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; + Delay = ((TimeoutInMilliSeconds * STALL_1_MILLI_SECOND) / 250) + 1; do { - AltStatusValue = IoRead8 (AltStatusRegister); // @@ -1154,12 +1152,12 @@ DRQReady2 ( } if ((AltStatusValue & (ATA_STSREG_BSY | ATA_STSREG_ERR)) == ATA_STSREG_ERR) { - ErrValue = IoRead8 (IdeIoRegisters->Reg1.Error); if ((ErrValue & ATA_ERRREG_ABRT) == ATA_ERRREG_ABRT) { return EFI_ABORTED; } } + MicroSecondDelay (250); Delay--; @@ -1184,21 +1182,19 @@ DRQReady2 ( **/ EFI_STATUS CheckErrorStatus ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINT16 StatusReg + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINT16 StatusReg ) { - UINT8 StatusValue; + UINT8 StatusValue; StatusValue = IoRead8 (StatusReg); if ((StatusValue & (ATA_STSREG_ERR | ATA_STSREG_DWF | ATA_STSREG_CORR)) == 0) { - return EFI_SUCCESS; } return EFI_DEVICE_ERROR; - } /** @@ -1213,8 +1209,8 @@ CheckErrorStatus ( **/ EFI_STATUS ATAPIIdentify ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition ) { ATAPI_IDENTIFY_DATA AtapiIdentifyData; @@ -1229,19 +1225,19 @@ ATAPIIdentify ( UINT16 CylinderLsbReg; UINT16 CylinderMsbReg; - UINT32 WordCount; - UINT32 Increment; - UINT32 Index; - UINT32 ByteCount; - UINT16 *Buffer16; + UINT32 WordCount; + UINT32 Increment; + UINT32 Index; + UINT32 ByteCount; + UINT16 *Buffer16; - EFI_STATUS Status; + EFI_STATUS Status; - ByteCount = sizeof (AtapiIdentifyData); - Buffer16 = (UINT16 *) &AtapiIdentifyData; + ByteCount = sizeof (AtapiIdentifyData); + Buffer16 = (UINT16 *)&AtapiIdentifyData; - Channel = (UINT8) (DevicePosition / 2); - Device = (UINT8) (DevicePosition % 2); + Channel = (UINT8)(DevicePosition / 2); + Device = (UINT8)(DevicePosition % 2); ASSERT (Channel < MAX_IDE_CHANNELS); @@ -1261,9 +1257,11 @@ ATAPIIdentify ( AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), ATATIMEOUT - ) != EFI_SUCCESS) { + ) != EFI_SUCCESS) + { return EFI_DEVICE_ERROR; } + // // select device via Head/Device register. // Before write Head/Device register, BSY and DRQ must be 0. @@ -1271,11 +1269,12 @@ ATAPIIdentify ( if (DRQClear2 (AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), ATATIMEOUT) != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } + // // e0:1110,0000-- bit7 and bit5 are reserved bits. // bit6 set means LBA mode // - IoWrite8 (HeadReg, (UINT8) ((Device << 4) | 0xe0)); + IoWrite8 (HeadReg, (UINT8)((Device << 4) | 0xe0)); // // set all the command parameters @@ -1285,8 +1284,8 @@ ATAPIIdentify ( AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), ATATIMEOUT - ) != EFI_SUCCESS) { - + ) != EFI_SUCCESS) + { return EFI_DEVICE_ERROR; } @@ -1330,15 +1329,16 @@ ATAPIIdentify ( } if (CheckErrorStatus (AtapiBlkIoDev, StatusReg) != EFI_SUCCESS) { - return EFI_DEVICE_ERROR; } + // // Get the byte count for one series of read // if ((WordCount + Increment) > ByteCount / 2) { Increment = ByteCount / 2 - WordCount; } + // // perform a series of read without check DRQ ready // @@ -1347,8 +1347,8 @@ ATAPIIdentify ( } WordCount += Increment; - } + // // while // @@ -1356,12 +1356,12 @@ ATAPIIdentify ( AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), ATATIMEOUT - ) != EFI_SUCCESS) { + ) != EFI_SUCCESS) + { return CheckErrorStatus (AtapiBlkIoDev, StatusReg); } return EFI_SUCCESS; - } /** @@ -1377,8 +1377,8 @@ ATAPIIdentify ( **/ EFI_STATUS TestUnitReady ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition ) { ATAPI_PACKET_COMMAND Packet; @@ -1442,26 +1442,26 @@ AtapiPacketCommandIn ( // // required transfer data in word unit. // - UINT32 RequiredWordCount; + UINT32 RequiredWordCount; // // actual transfer data in word unit. // - UINT32 ActualWordCount; + UINT32 ActualWordCount; - Channel = (UINT8) (DevicePosition / 2); - Device = (UINT8) (DevicePosition % 2); + Channel = (UINT8)(DevicePosition / 2); + Device = (UINT8)(DevicePosition % 2); ASSERT (Channel < MAX_IDE_CHANNELS); - StatusReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Status; - HeadReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Head; - CommandReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Command; - FeatureReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg1.Feature; - CylinderLsbReg = AtapiBlkIoDev->IdeIoPortReg[Channel].CylinderLsb; - CylinderMsbReg = AtapiBlkIoDev->IdeIoPortReg[Channel].CylinderMsb; - DeviceControlReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Alt.DeviceControl; - DataReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Data; + StatusReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Status; + HeadReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Head; + CommandReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Command; + FeatureReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg1.Feature; + CylinderLsbReg = AtapiBlkIoDev->IdeIoPortReg[Channel].CylinderLsb; + CylinderMsbReg = AtapiBlkIoDev->IdeIoPortReg[Channel].CylinderMsb; + DeviceControlReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Alt.DeviceControl; + DataReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Data; // // Set all the command parameters by fill related registers. @@ -1471,14 +1471,16 @@ AtapiPacketCommandIn ( AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), ATATIMEOUT - ) != EFI_SUCCESS) { + ) != EFI_SUCCESS) + { return EFI_DEVICE_ERROR; } + // // Select device via Device/Head Register. // DEFAULT_CMD: 0xa0 (1010,0000) // - IoWrite8 (HeadReg, (UINT8) ((Device << 4) | ATA_DEFAULT_CMD)); + IoWrite8 (HeadReg, (UINT8)((Device << 4) | ATA_DEFAULT_CMD)); // // No OVL; No DMA @@ -1489,8 +1491,8 @@ AtapiPacketCommandIn ( // set the transfersize to MAX_ATAPI_BYTE_COUNT to let the device // determine how many data should be transfered. // - IoWrite8 (CylinderLsbReg, (UINT8) (ATAPI_MAX_BYTE_COUNT & 0x00ff)); - IoWrite8 (CylinderMsbReg, (UINT8) (ATAPI_MAX_BYTE_COUNT >> 8)); + IoWrite8 (CylinderLsbReg, (UINT8)(ATAPI_MAX_BYTE_COUNT & 0x00ff)); + IoWrite8 (CylinderMsbReg, (UINT8)(ATAPI_MAX_BYTE_COUNT >> 8)); // // DEFAULT_CTL:0x0a (0000,1010) @@ -1508,6 +1510,7 @@ AtapiPacketCommandIn ( if (Status != EFI_SUCCESS) { return Status; } + // // Send out command packet // @@ -1527,9 +1530,10 @@ AtapiPacketCommandIn ( return EFI_DEVICE_ERROR; } - if (Buffer == NULL || ByteCount == 0) { + if ((Buffer == NULL) || (ByteCount == 0)) { return EFI_SUCCESS; } + // // call PioReadWriteData() function to get // requested transfer data form device. @@ -1541,7 +1545,7 @@ AtapiPacketCommandIn ( // ActualWordCount = 0; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; while ((Status == EFI_SUCCESS) && (ActualWordCount < RequiredWordCount)) { // // before each data transfer stream, the host should poll DRQ bit ready, @@ -1551,9 +1555,11 @@ AtapiPacketCommandIn ( AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), TimeoutInMilliSeconds - ) != EFI_SUCCESS) { + ) != EFI_SUCCESS) + { return CheckErrorStatus (AtapiBlkIoDev, StatusReg); } + // // read Status Register will clear interrupt // @@ -1562,30 +1568,28 @@ AtapiPacketCommandIn ( // // get current data transfer size from Cylinder Registers. // - WordCount = IoRead8 (CylinderMsbReg) << 8; - WordCount = WordCount | IoRead8 (CylinderLsbReg); - WordCount = WordCount & 0xffff; + WordCount = IoRead8 (CylinderMsbReg) << 8; + WordCount = WordCount | IoRead8 (CylinderLsbReg); + WordCount = WordCount & 0xffff; WordCount /= 2; // // perform a series data In/Out. // for (Index = 0; (Index < WordCount) && (ActualWordCount < RequiredWordCount); Index++, ActualWordCount++) { - *PtrBuffer = IoRead16 (DataReg); PtrBuffer++; - } - if (((ATAPI_REQUEST_SENSE_CMD *) Packet)->opcode == ATA_CMD_REQUEST_SENSE && ActualWordCount >= 4) { + if ((((ATAPI_REQUEST_SENSE_CMD *)Packet)->opcode == ATA_CMD_REQUEST_SENSE) && (ActualWordCount >= 4)) { RequiredWordCount = MIN ( RequiredWordCount, - (UINT32) (4 + (((ATAPI_REQUEST_SENSE_DATA *) Buffer)->addnl_sense_length / 2)) + (UINT32)(4 + (((ATAPI_REQUEST_SENSE_DATA *)Buffer)->addnl_sense_length / 2)) ); } - } + // // After data transfer is completed, normally, DRQ bit should clear. // @@ -1593,6 +1597,7 @@ AtapiPacketCommandIn ( if (Status != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } + // // read status register to check whether error happens. // @@ -1616,15 +1621,15 @@ AtapiPacketCommandIn ( **/ EFI_STATUS Inquiry ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ) { - ATAPI_PACKET_COMMAND Packet; - EFI_STATUS Status; - ATAPI_INQUIRY_DATA Idata; + ATAPI_PACKET_COMMAND Packet; + EFI_STATUS Status; + ATAPI_INQUIRY_DATA Idata; // // prepare command packet for the ATAPI Inquiry Packet Command. @@ -1632,64 +1637,65 @@ Inquiry ( ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); ZeroMem (&Idata, sizeof (ATAPI_INQUIRY_DATA)); - Packet.Inquiry.opcode = ATA_CMD_INQUIRY; - Packet.Inquiry.page_code = 0; - Packet.Inquiry.allocation_length = (UINT8) sizeof (ATAPI_INQUIRY_DATA); + Packet.Inquiry.opcode = ATA_CMD_INQUIRY; + Packet.Inquiry.page_code = 0; + Packet.Inquiry.allocation_length = (UINT8)sizeof (ATAPI_INQUIRY_DATA); // // Send command packet and get requested Inquiry data. // Status = AtapiPacketCommandIn ( - AtapiBlkIoDev, - DevicePosition, - &Packet, - (UINT16 *) (&Idata), - sizeof (ATAPI_INQUIRY_DATA), - ATAPITIMEOUT - //50 - ); + AtapiBlkIoDev, + DevicePosition, + &Packet, + (UINT16 *)(&Idata), + sizeof (ATAPI_INQUIRY_DATA), + ATAPITIMEOUT + // 50 + ); if (Status != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } + // // Identify device type via INQUIRY data. // switch (Idata.peripheral_type & 0x1f) { - case 0x00: - // - // Magnetic Disk - // - MediaInfo->DeviceType = IdeLS120; - MediaInfo->MediaPresent = FALSE; - MediaInfo->LastBlock = 0; - MediaInfo->BlockSize = 0x200; - MediaInfo2->InterfaceType = MSG_ATAPI_DP; - MediaInfo2->RemovableMedia = TRUE; - MediaInfo2->MediaPresent = FALSE; - MediaInfo2->ReadOnly = FALSE; - MediaInfo2->BlockSize = 0x200; - MediaInfo2->LastBlock = 0; - break; - - case 0x05: - // - // CD-ROM - // - MediaInfo->DeviceType = IdeCDROM; - MediaInfo->MediaPresent = FALSE; - MediaInfo->LastBlock = 0; - MediaInfo->BlockSize = 0x800; - MediaInfo2->InterfaceType = MSG_ATAPI_DP; - MediaInfo2->RemovableMedia = TRUE; - MediaInfo2->MediaPresent = FALSE; - MediaInfo2->ReadOnly = TRUE; - MediaInfo2->BlockSize = 0x200; - MediaInfo2->LastBlock = 0; - break; - - default: - return EFI_UNSUPPORTED; + case 0x00: + // + // Magnetic Disk + // + MediaInfo->DeviceType = IdeLS120; + MediaInfo->MediaPresent = FALSE; + MediaInfo->LastBlock = 0; + MediaInfo->BlockSize = 0x200; + MediaInfo2->InterfaceType = MSG_ATAPI_DP; + MediaInfo2->RemovableMedia = TRUE; + MediaInfo2->MediaPresent = FALSE; + MediaInfo2->ReadOnly = FALSE; + MediaInfo2->BlockSize = 0x200; + MediaInfo2->LastBlock = 0; + break; + + case 0x05: + // + // CD-ROM + // + MediaInfo->DeviceType = IdeCDROM; + MediaInfo->MediaPresent = FALSE; + MediaInfo->LastBlock = 0; + MediaInfo->BlockSize = 0x800; + MediaInfo2->InterfaceType = MSG_ATAPI_DP; + MediaInfo2->RemovableMedia = TRUE; + MediaInfo2->MediaPresent = FALSE; + MediaInfo2->ReadOnly = TRUE; + MediaInfo2->BlockSize = 0x200; + MediaInfo2->LastBlock = 0; + break; + + default: + return EFI_UNSUPPORTED; } return EFI_SUCCESS; @@ -1712,13 +1718,12 @@ Inquiry ( **/ EFI_STATUS DetectMedia ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ) { - UINTN Index; UINTN RetryNum; UINTN MaxRetryNum; @@ -1738,7 +1743,6 @@ DetectMedia ( // the device will produce corresponding Sense data. // for (Index = 0; Index < 2; Index++) { - Status = TestUnitReady (AtapiBlkIoDev, DevicePosition); if (Status != EFI_SUCCESS) { Status = ResetDevice (AtapiBlkIoDev, DevicePosition, FALSE); @@ -1746,24 +1750,23 @@ DetectMedia ( if (Status != EFI_SUCCESS) { ResetDevice (AtapiBlkIoDev, DevicePosition, TRUE); } - } else { break; } } - SenseCounts = MAX_SENSE_KEY_COUNT; - Status = EFI_SUCCESS; - NeedReadCapacity = TRUE; + SenseCounts = MAX_SENSE_KEY_COUNT; + Status = EFI_SUCCESS; + NeedReadCapacity = TRUE; for (Index = 0; Index < 5; Index++) { SenseCounts = MAX_SENSE_KEY_COUNT; - Status = RequestSense ( - AtapiBlkIoDev, - DevicePosition, - SenseBuffers, - &SenseCounts - ); + Status = RequestSense ( + AtapiBlkIoDev, + DevicePosition, + SenseBuffers, + &SenseCounts + ); DEBUG ((DEBUG_INFO, "Atapi Request Sense Count is %d\n", SenseCounts)); if (IsDeviceStateUnclear (SenseBuffers, SenseCounts) || IsNoMedia (SenseBuffers, SenseCounts)) { // @@ -1776,12 +1779,10 @@ DetectMedia ( } if (Status == EFI_SUCCESS) { - if (IsNoMedia (SenseBuffers, SenseCounts)) { - - NeedReadCapacity = FALSE; - MediaInfo->MediaPresent = FALSE; - MediaInfo->LastBlock = 0; + NeedReadCapacity = FALSE; + MediaInfo->MediaPresent = FALSE; + MediaInfo->LastBlock = 0; MediaInfo2->MediaPresent = FALSE; MediaInfo2->LastBlock = 0; } @@ -1801,19 +1802,16 @@ DetectMedia ( // initial retry once // for (Index = 0; (Index < RetryNum) && (Index < MaxRetryNum); Index++) { - Status = ReadCapacity (AtapiBlkIoDev, DevicePosition, MediaInfo, MediaInfo2); MicroSecondDelay (200000); SenseCounts = MAX_SENSE_KEY_COUNT; if (Status != EFI_SUCCESS) { - Status = RequestSense (AtapiBlkIoDev, DevicePosition, SenseBuffers, &SenseCounts); // // If Request Sense data failed, reset the device and retry. // if (Status != EFI_SUCCESS) { - Status = ResetDevice (AtapiBlkIoDev, DevicePosition, FALSE); // // if ATAPI soft reset fail, @@ -1829,13 +1827,13 @@ DetectMedia ( // continue; } + // // No Media // if (IsNoMedia (SenseBuffers, SenseCounts)) { - - MediaInfo->MediaPresent = FALSE; - MediaInfo->LastBlock = 0; + MediaInfo->MediaPresent = FALSE; + MediaInfo->LastBlock = 0; MediaInfo2->MediaPresent = FALSE; MediaInfo2->LastBlock = 0; break; @@ -1857,15 +1855,13 @@ DetectMedia ( return EFI_DEVICE_ERROR; } } + // // if read capacity fail not for above reasons, retry once more // RetryNum++; - } - } - } return EFI_SUCCESS; @@ -1898,18 +1894,17 @@ ResetDevice ( UINT8 Channel; UINT8 Device; - Channel = (UINT8) (DevicePosition / 2); - Device = (UINT8) (DevicePosition % 2); + Channel = (UINT8)(DevicePosition / 2); + Device = (UINT8)(DevicePosition % 2); ASSERT (Channel < MAX_IDE_CHANNELS); - DeviceControlReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Alt.DeviceControl; - CommandReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Command; - HeadReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Head; + DeviceControlReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Alt.DeviceControl; + CommandReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Reg.Command; + HeadReg = AtapiBlkIoDev->IdeIoPortReg[Channel].Head; if (Extensive) { - - DevControl = 0; + DevControl = 0; DevControl |= ATA_CTLREG_SRST; // // set SRST bit to initiate soft reset @@ -1940,13 +1935,12 @@ ResetDevice ( if (WaitForBSYClear (AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), 31000) == EFI_TIMEOUT) { return EFI_DEVICE_ERROR; } - } else { // // for ATAPI device, no need to wait DRDY ready after device selecting. // bit7 and bit5 are both set to 1 for backward compatibility // - DeviceSelect = (UINT8) (((BIT7 | BIT5) | (Device << 4))); + DeviceSelect = (UINT8)(((BIT7 | BIT5) | (Device << 4))); IoWrite8 (HeadReg, DeviceSelect); Command = ATA_CMD_SOFT_RESET; @@ -1959,6 +1953,7 @@ ResetDevice ( if (WaitForBSYClear (AtapiBlkIoDev, &(AtapiBlkIoDev->IdeIoPortReg[Channel]), 31000) != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } + // // stall 5 seconds to make the device status stable // @@ -1966,7 +1961,6 @@ ResetDevice ( } return EFI_SUCCESS; - } /** @@ -1983,17 +1977,17 @@ ResetDevice ( **/ EFI_STATUS RequestSense ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN ATAPI_REQUEST_SENSE_DATA *SenseBuffers, - IN OUT UINT8 *SenseCounts + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN ATAPI_REQUEST_SENSE_DATA *SenseBuffers, + IN OUT UINT8 *SenseCounts ) { - EFI_STATUS Status; - ATAPI_REQUEST_SENSE_DATA *Sense; - UINT16 *Ptr; - BOOLEAN SenseReq; - ATAPI_PACKET_COMMAND Packet; + EFI_STATUS Status; + ATAPI_REQUEST_SENSE_DATA *Sense; + UINT16 *Ptr; + BOOLEAN SenseReq; + ATAPI_PACKET_COMMAND Packet; ZeroMem (SenseBuffers, sizeof (ATAPI_REQUEST_SENSE_DATA) * (*SenseCounts)); // @@ -2001,9 +1995,9 @@ RequestSense ( // ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); Packet.RequestSence.opcode = ATA_CMD_REQUEST_SENSE; - Packet.RequestSence.allocation_length = (UINT8) sizeof (ATAPI_REQUEST_SENSE_DATA); + Packet.RequestSence.allocation_length = (UINT8)sizeof (ATAPI_REQUEST_SENSE_DATA); - Ptr = (UINT16 *) SenseBuffers; + Ptr = (UINT16 *)SenseBuffers; // // initialize pointer // @@ -2012,20 +2006,19 @@ RequestSense ( // request sense data from device continiously until no sense data exists in the device. // for (SenseReq = TRUE; SenseReq;) { - - Sense = (ATAPI_REQUEST_SENSE_DATA *) Ptr; + Sense = (ATAPI_REQUEST_SENSE_DATA *)Ptr; // // send out Request Sense Packet Command and get one Sense data form device // Status = AtapiPacketCommandIn ( - AtapiBlkIoDev, - DevicePosition, - &Packet, - Ptr, - sizeof (ATAPI_REQUEST_SENSE_DATA), - ATAPITIMEOUT - ); + AtapiBlkIoDev, + DevicePosition, + &Packet, + Ptr, + sizeof (ATAPI_REQUEST_SENSE_DATA), + ATAPITIMEOUT + ); // // failed to get Sense data // @@ -2042,6 +2035,7 @@ RequestSense ( if (*SenseCounts > MAX_SENSE_KEY_COUNT) { return EFI_SUCCESS; } + // // We limit MAX sense data count to 20 in order to avoid dead loop. Some // incompatible ATAPI devices don't retrive NO_SENSE when there is no media. @@ -2049,7 +2043,6 @@ RequestSense ( // supposed to be large enough for any ATAPI device. // if ((Sense->sense_key != ATA_SK_NO_SENSE) && ((*SenseCounts) < 20)) { - Ptr += sizeof (ATAPI_REQUEST_SENSE_DATA) / 2; // // Ptr is word based pointer @@ -2081,65 +2074,61 @@ RequestSense ( **/ EFI_STATUS ReadCapacity ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ) { - EFI_STATUS Status; - ATAPI_PACKET_COMMAND Packet; + EFI_STATUS Status; + ATAPI_PACKET_COMMAND Packet; // // used for capacity data returned from ATAPI device // - ATAPI_READ_CAPACITY_DATA Data; - ATAPI_READ_FORMAT_CAPACITY_DATA FormatData; + ATAPI_READ_CAPACITY_DATA Data; + ATAPI_READ_FORMAT_CAPACITY_DATA FormatData; ZeroMem (&Data, sizeof (Data)); ZeroMem (&FormatData, sizeof (FormatData)); if (MediaInfo->DeviceType == IdeCDROM) { - ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); Packet.Inquiry.opcode = ATA_CMD_READ_CAPACITY; - Status = AtapiPacketCommandIn ( - AtapiBlkIoDev, - DevicePosition, - &Packet, - (UINT16 *) (&Data), - sizeof (ATAPI_READ_CAPACITY_DATA), - ATAPITIMEOUT - ); - + Status = AtapiPacketCommandIn ( + AtapiBlkIoDev, + DevicePosition, + &Packet, + (UINT16 *)(&Data), + sizeof (ATAPI_READ_CAPACITY_DATA), + ATAPITIMEOUT + ); } else { // // DeviceType == IdeLS120 // ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); - Packet.ReadFormatCapacity.opcode = ATA_CMD_READ_FORMAT_CAPACITY; - Packet.ReadFormatCapacity.allocation_length_lo = 12; - Status = AtapiPacketCommandIn ( - AtapiBlkIoDev, - DevicePosition, - &Packet, - (UINT16 *) (&FormatData), - sizeof (ATAPI_READ_FORMAT_CAPACITY_DATA), - ATAPITIMEOUT*10 - ); + Packet.ReadFormatCapacity.opcode = ATA_CMD_READ_FORMAT_CAPACITY; + Packet.ReadFormatCapacity.allocation_length_lo = 12; + Status = AtapiPacketCommandIn ( + AtapiBlkIoDev, + DevicePosition, + &Packet, + (UINT16 *)(&FormatData), + sizeof (ATAPI_READ_FORMAT_CAPACITY_DATA), + ATAPITIMEOUT*10 + ); } if (Status == EFI_SUCCESS) { - if (MediaInfo->DeviceType == IdeCDROM) { - - MediaInfo->LastBlock = ((UINT32) Data.LastLba3 << 24) | (Data.LastLba2 << 16) | (Data.LastLba1 << 8) | Data.LastLba0; + MediaInfo->LastBlock = ((UINT32)Data.LastLba3 << 24) | (Data.LastLba2 << 16) | (Data.LastLba1 << 8) | Data.LastLba0; MediaInfo->MediaPresent = TRUE; // // Because the user data portion in the sector of the Data CD supported // is always 800h // - MediaInfo->BlockSize = 0x800; + MediaInfo->BlockSize = 0x800; MediaInfo2->LastBlock = MediaInfo->LastBlock; MediaInfo2->MediaPresent = MediaInfo->MediaPresent; @@ -2147,32 +2136,29 @@ ReadCapacity ( } if (MediaInfo->DeviceType == IdeLS120) { - if (FormatData.DesCode == 3) { - MediaInfo->MediaPresent = FALSE; - MediaInfo->LastBlock = 0; + MediaInfo->MediaPresent = FALSE; + MediaInfo->LastBlock = 0; MediaInfo2->MediaPresent = FALSE; MediaInfo2->LastBlock = 0; } else { - MediaInfo->LastBlock = ((UINT32) FormatData.LastLba3 << 24) | - (FormatData.LastLba2 << 16) | - (FormatData.LastLba1 << 8) | - FormatData.LastLba0; + MediaInfo->LastBlock = ((UINT32)FormatData.LastLba3 << 24) | + (FormatData.LastLba2 << 16) | + (FormatData.LastLba1 << 8) | + FormatData.LastLba0; MediaInfo->LastBlock--; MediaInfo->MediaPresent = TRUE; - MediaInfo->BlockSize = 0x200; + MediaInfo->BlockSize = 0x200; MediaInfo2->LastBlock = MediaInfo->LastBlock; MediaInfo2->MediaPresent = MediaInfo->MediaPresent; MediaInfo2->BlockSize = (UINT32)MediaInfo->BlockSize; - } } return EFI_SUCCESS; - } else { return EFI_DEVICE_ERROR; } @@ -2194,15 +2180,14 @@ ReadCapacity ( **/ EFI_STATUS ReadSectors ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN VOID *Buffer, - IN EFI_PEI_LBA StartLba, - IN UINTN NumberOfBlocks, - IN UINTN BlockSize + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN VOID *Buffer, + IN EFI_PEI_LBA StartLba, + IN UINTN NumberOfBlocks, + IN UINTN BlockSize ) { - ATAPI_PACKET_COMMAND Packet; ATAPI_READ10_CMD *Read10Packet; EFI_STATUS Status; @@ -2217,27 +2202,27 @@ ReadSectors ( // fill command packet for Read(10) command // ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); - Read10Packet = &Packet.Read10; - Lba32 = (UINT32) StartLba; - PtrBuffer = Buffer; + Read10Packet = &Packet.Read10; + Lba32 = (UINT32)StartLba; + PtrBuffer = Buffer; // // limit the data bytes that can be transfered by one Read(10) Command // - MaxBlock = (UINT16) (0x10000 / BlockSize); + MaxBlock = (UINT16)(0x10000 / BlockSize); // // (64k bytes) // BlocksRemaining = NumberOfBlocks; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { - SectorCount = (UINT16) BlocksRemaining; + SectorCount = (UINT16)BlocksRemaining; } else { SectorCount = MaxBlock; } + // // fill the Packet data sturcture // @@ -2247,34 +2232,34 @@ ReadSectors ( // Lba0 ~ Lba3 specify the start logical block address of the data transfer. // Lba0 is MSB, Lba3 is LSB // - Read10Packet->Lba3 = (UINT8) (Lba32 & 0xff); - Read10Packet->Lba2 = (UINT8) (Lba32 >> 8); - Read10Packet->Lba1 = (UINT8) (Lba32 >> 16); - Read10Packet->Lba0 = (UINT8) (Lba32 >> 24); + Read10Packet->Lba3 = (UINT8)(Lba32 & 0xff); + Read10Packet->Lba2 = (UINT8)(Lba32 >> 8); + Read10Packet->Lba1 = (UINT8)(Lba32 >> 16); + Read10Packet->Lba0 = (UINT8)(Lba32 >> 24); // // TranLen0 ~ TranLen1 specify the transfer length in block unit. // TranLen0 is MSB, TranLen is LSB // - Read10Packet->TranLen1 = (UINT8) (SectorCount & 0xff); - Read10Packet->TranLen0 = (UINT8) (SectorCount >> 8); + Read10Packet->TranLen1 = (UINT8)(SectorCount & 0xff); + Read10Packet->TranLen0 = (UINT8)(SectorCount >> 8); - ByteCount = (UINT32) (SectorCount * BlockSize); + ByteCount = (UINT32)(SectorCount * BlockSize); Status = AtapiPacketCommandIn ( - AtapiBlkIoDev, - DevicePosition, - &Packet, - (UINT16 *) PtrBuffer, - ByteCount, - ATAPILONGTIMEOUT - ); + AtapiBlkIoDev, + DevicePosition, + &Packet, + (UINT16 *)PtrBuffer, + ByteCount, + ATAPILONGTIMEOUT + ); if (Status != EFI_SUCCESS) { return Status; } - Lba32 += SectorCount; - PtrBuffer = (UINT8 *) PtrBuffer + SectorCount * BlockSize; + Lba32 += SectorCount; + PtrBuffer = (UINT8 *)PtrBuffer + SectorCount * BlockSize; BlocksRemaining -= SectorCount; } @@ -2303,10 +2288,9 @@ IsNoMedia ( IsNoMedia = FALSE; - SensePtr = SenseData; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - if ((SensePtr->sense_key == ATA_SK_NOT_READY) && (SensePtr->addnl_sense_code == ATA_ASC_NO_MEDIA)) { IsNoMedia = TRUE; } @@ -2329,20 +2313,19 @@ IsNoMedia ( **/ BOOLEAN IsDeviceStateUnclear ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { ATAPI_REQUEST_SENSE_DATA *SensePtr; UINTN Index; BOOLEAN Unclear; - Unclear = FALSE; + Unclear = FALSE; - SensePtr = SenseData; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - if (SensePtr->sense_key == 0x06) { // // Sense key is 0x06 means the device is just be reset or media just @@ -2378,51 +2361,50 @@ IsMediaError ( UINTN Index; BOOLEAN IsError; - IsError = FALSE; + IsError = FALSE; - SensePtr = SenseData; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->sense_key) { + case ATA_SK_MEDIUM_ERROR: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_MEDIA_ERR1: + // + // fall through + // + case ATA_ASC_MEDIA_ERR2: + // + // fall through + // + case ATA_ASC_MEDIA_ERR3: + // + // fall through + // + case ATA_ASC_MEDIA_ERR4: + IsError = TRUE; + break; - case ATA_SK_MEDIUM_ERROR: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_MEDIA_ERR1: - // - // fall through - // - case ATA_ASC_MEDIA_ERR2: - // - // fall through - // - case ATA_ASC_MEDIA_ERR3: - // - // fall through - // - case ATA_ASC_MEDIA_ERR4: - IsError = TRUE; - break; + default: + break; + } - default: break; - } - break; + case ATA_SK_NOT_READY: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_MEDIA_UPSIDE_DOWN: + IsError = TRUE; + break; + + default: + break; + } - case ATA_SK_NOT_READY: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_MEDIA_UPSIDE_DOWN: - IsError = TRUE; break; default: break; - } - break; - - default: - break; } SensePtr++; @@ -2444,47 +2426,47 @@ IsMediaError ( **/ BOOLEAN IsDriveReady ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts, - OUT BOOLEAN *NeedRetry + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts, + OUT BOOLEAN *NeedRetry ) { ATAPI_REQUEST_SENSE_DATA *SensePtr; UINTN Index; BOOLEAN IsReady; - IsReady = TRUE; - *NeedRetry = FALSE; + IsReady = TRUE; + *NeedRetry = FALSE; - SensePtr = SenseData; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->sense_key) { - - case ATA_SK_NOT_READY: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_NOT_READY: - switch (SensePtr->addnl_sense_code_qualifier) { - case ATA_ASCQ_IN_PROGRESS: - IsReady = FALSE; - *NeedRetry = TRUE; - break; - - default: - IsReady = FALSE; - *NeedRetry = FALSE; - break; + case ATA_SK_NOT_READY: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_NOT_READY: + switch (SensePtr->addnl_sense_code_qualifier) { + case ATA_ASCQ_IN_PROGRESS: + IsReady = FALSE; + *NeedRetry = TRUE; + break; + + default: + IsReady = FALSE; + *NeedRetry = FALSE; + break; + } + + break; + + default: + break; } + break; default: break; - } - break; - - default: - break; } SensePtr++; diff --git a/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.h b/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.h index 8851b11185..abc1dc661b 100644 --- a/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.h +++ b/MdeModulePkg/Bus/Pci/IdeBusPei/AtapiPeim.h @@ -26,12 +26,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - #include -#define MAX_SENSE_KEY_COUNT 6 -#define MAX_IDE_CHANNELS 4 // Ide and Sata Primary, Secondary Channel. -#define MAX_IDE_DEVICES 8 // Ide, Sata Primary, Secondary and Master, Slave device. +#define MAX_SENSE_KEY_COUNT 6 +#define MAX_IDE_CHANNELS 4 // Ide and Sata Primary, Secondary Channel. +#define MAX_IDE_DEVICES 8 // Ide, Sata Primary, Secondary and Master, Slave device. typedef enum { IdePrimary = 0, @@ -40,72 +39,69 @@ typedef enum { } EFI_IDE_CHANNEL; typedef enum { - IdeMaster = 0, - IdeSlave = 1, - IdeMaxDevice = 2 + IdeMaster = 0, + IdeSlave = 1, + IdeMaxDevice = 2 } EFI_IDE_DEVICE; // // IDE Registers // typedef union { - UINT16 Command; /* when write */ - UINT16 Status; /* when read */ + UINT16 Command; /* when write */ + UINT16 Status; /* when read */ } IDE_CMD_OR_STATUS; typedef union { - UINT16 Error; /* when read */ - UINT16 Feature; /* when write */ + UINT16 Error; /* when read */ + UINT16 Feature; /* when write */ } IDE_ERROR_OR_FEATURE; typedef union { - UINT16 AltStatus; /* when read */ - UINT16 DeviceControl; /* when write */ + UINT16 AltStatus; /* when read */ + UINT16 DeviceControl; /* when write */ } IDE_ALTSTATUS_OR_DEVICECONTROL; // // IDE registers set // typedef struct { - UINT16 Data; - IDE_ERROR_OR_FEATURE Reg1; - UINT16 SectorCount; - UINT16 SectorNumber; - UINT16 CylinderLsb; - UINT16 CylinderMsb; - UINT16 Head; - IDE_CMD_OR_STATUS Reg; - - IDE_ALTSTATUS_OR_DEVICECONTROL Alt; - UINT16 DriveAddress; + UINT16 Data; + IDE_ERROR_OR_FEATURE Reg1; + UINT16 SectorCount; + UINT16 SectorNumber; + UINT16 CylinderLsb; + UINT16 CylinderMsb; + UINT16 Head; + IDE_CMD_OR_STATUS Reg; + + IDE_ALTSTATUS_OR_DEVICECONTROL Alt; + UINT16 DriveAddress; } IDE_BASE_REGISTERS; typedef struct { - - UINTN DevicePosition; - EFI_PEI_BLOCK_IO_MEDIA MediaInfo; - EFI_PEI_BLOCK_IO2_MEDIA MediaInfo2; - + UINTN DevicePosition; + EFI_PEI_BLOCK_IO_MEDIA MediaInfo; + EFI_PEI_BLOCK_IO2_MEDIA MediaInfo2; } PEI_ATAPI_DEVICE_INFO; #define ATAPI_BLK_IO_DEV_SIGNATURE SIGNATURE_32 ('a', 'b', 'i', 'o') typedef struct { - UINTN Signature; + UINTN Signature; - EFI_PEI_RECOVERY_BLOCK_IO_PPI AtapiBlkIo; - EFI_PEI_RECOVERY_BLOCK_IO2_PPI AtapiBlkIo2; - EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; - EFI_PEI_PPI_DESCRIPTOR PpiDescriptor2; - PEI_ATA_CONTROLLER_PPI *AtaControllerPpi; + EFI_PEI_RECOVERY_BLOCK_IO_PPI AtapiBlkIo; + EFI_PEI_RECOVERY_BLOCK_IO2_PPI AtapiBlkIo2; + EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; + EFI_PEI_PPI_DESCRIPTOR PpiDescriptor2; + PEI_ATA_CONTROLLER_PPI *AtaControllerPpi; - UINTN DeviceCount; - PEI_ATAPI_DEVICE_INFO DeviceInfo[MAX_IDE_DEVICES]; //for max 8 device - IDE_BASE_REGISTERS IdeIoPortReg[MAX_IDE_CHANNELS]; //for max 4 channel. + UINTN DeviceCount; + PEI_ATAPI_DEVICE_INFO DeviceInfo[MAX_IDE_DEVICES]; // for max 8 device + IDE_BASE_REGISTERS IdeIoPortReg[MAX_IDE_CHANNELS]; // for max 4 channel. } ATAPI_BLK_IO_DEV; -#define PEI_RECOVERY_ATAPI_FROM_BLKIO_THIS(a) CR (a, ATAPI_BLK_IO_DEV, AtapiBlkIo, ATAPI_BLK_IO_DEV_SIGNATURE) -#define PEI_RECOVERY_ATAPI_FROM_BLKIO2_THIS(a) CR (a, ATAPI_BLK_IO_DEV, AtapiBlkIo2, ATAPI_BLK_IO_DEV_SIGNATURE) - +#define PEI_RECOVERY_ATAPI_FROM_BLKIO_THIS(a) CR (a, ATAPI_BLK_IO_DEV, AtapiBlkIo, ATAPI_BLK_IO_DEV_SIGNATURE) +#define PEI_RECOVERY_ATAPI_FROM_BLKIO2_THIS(a) CR (a, ATAPI_BLK_IO_DEV, AtapiBlkIo2, ATAPI_BLK_IO_DEV_SIGNATURE) #define STALL_1_MILLI_SECOND 1000 // stall 1 ms #define STALL_1_SECONDS 1000 * STALL_1_MILLI_SECOND @@ -152,9 +148,9 @@ typedef struct { EFI_STATUS EFIAPI AtapiGetNumberOfBlockDevices ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -188,10 +184,10 @@ AtapiGetNumberOfBlockDevices ( EFI_STATUS EFIAPI AtapiGetBlockDeviceMediaInfo ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ); /** @@ -231,12 +227,12 @@ AtapiGetBlockDeviceMediaInfo ( EFI_STATUS EFIAPI AtapiReadBlocks ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -261,9 +257,9 @@ AtapiReadBlocks ( EFI_STATUS EFIAPI AtapiGetNumberOfBlockDevices2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -297,10 +293,10 @@ AtapiGetNumberOfBlockDevices2 ( EFI_STATUS EFIAPI AtapiGetBlockDeviceMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ); /** @@ -340,12 +336,12 @@ AtapiGetBlockDeviceMediaInfo2 ( EFI_STATUS EFIAPI AtapiReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); // @@ -379,10 +375,10 @@ AtapiEnumerateDevices ( **/ BOOLEAN DiscoverAtapiDevice ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ); /** @@ -397,8 +393,8 @@ DiscoverAtapiDevice ( **/ BOOLEAN DetectIDEController ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition ); /** @@ -523,8 +519,8 @@ DRQReady2 ( **/ EFI_STATUS CheckErrorStatus ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINT16 StatusReg + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINT16 StatusReg ); /** @@ -539,8 +535,8 @@ CheckErrorStatus ( **/ EFI_STATUS ATAPIIdentify ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition ); /** @@ -556,9 +552,9 @@ ATAPIIdentify ( **/ EFI_STATUS TestUnitReady ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition - ) ; + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition + ); /** Send out ATAPI commands conforms to the Packet Command with PIO Data In Protocol. @@ -600,10 +596,10 @@ AtapiPacketCommandIn ( **/ EFI_STATUS Inquiry ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ); /** @@ -623,10 +619,10 @@ Inquiry ( **/ EFI_STATUS DetectMedia ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ); /** @@ -683,10 +679,10 @@ RequestSense ( **/ EFI_STATUS ReadCapacity ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, - IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo, + IN OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo2 ); /** @@ -705,12 +701,12 @@ ReadCapacity ( **/ EFI_STATUS ReadSectors ( - IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, - IN UINTN DevicePosition, - IN VOID *Buffer, - IN EFI_PEI_LBA StartLba, - IN UINTN NumberOfBlocks, - IN UINTN BlockSize + IN ATAPI_BLK_IO_DEV *AtapiBlkIoDev, + IN UINTN DevicePosition, + IN VOID *Buffer, + IN EFI_PEI_LBA StartLba, + IN UINTN NumberOfBlocks, + IN UINTN BlockSize ); /** @@ -725,8 +721,8 @@ ReadSectors ( **/ BOOLEAN IsNoMedia ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -741,8 +737,8 @@ IsNoMedia ( **/ BOOLEAN IsDeviceStateUnclear ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -757,8 +753,8 @@ IsDeviceStateUnclear ( **/ BOOLEAN IsMediaError ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -774,9 +770,9 @@ IsMediaError ( **/ BOOLEAN IsDriveReady ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts, - OUT BOOLEAN *NeedRetry + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts, + OUT BOOLEAN *NeedRetry ); #endif diff --git a/MdeModulePkg/Bus/Pci/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c b/MdeModulePkg/Bus/Pci/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c index be9f873c39..aae16cd856 100644 --- a/MdeModulePkg/Bus/Pci/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c +++ b/MdeModulePkg/Bus/Pci/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.c @@ -21,32 +21,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include typedef struct { - UINT64 VendorId; - UINT64 DeviceId; - UINT64 RevisionId; - UINT64 SubsystemVendorId; - UINT64 SubsystemDeviceId; + UINT64 VendorId; + UINT64 DeviceId; + UINT64 RevisionId; + UINT64 SubsystemVendorId; + UINT64 SubsystemDeviceId; } EFI_PCI_DEVICE_HEADER_INFO; typedef struct { - UINT64 ResType; - UINT64 GenFlag; - UINT64 SpecificFlag; - UINT64 AddrSpaceGranularity; - UINT64 AddrRangeMin; - UINT64 AddrRangeMax; - UINT64 AddrTranslationOffset; - UINT64 AddrLen; + UINT64 ResType; + UINT64 GenFlag; + UINT64 SpecificFlag; + UINT64 AddrSpaceGranularity; + UINT64 AddrRangeMin; + UINT64 AddrRangeMax; + UINT64 AddrTranslationOffset; + UINT64 AddrLen; } EFI_PCI_RESOUCE_DESCRIPTOR; #define PCI_DEVICE_ID(VendorId, DeviceId, Revision, SubVendorId, SubDeviceId) \ VendorId, DeviceId, Revision, SubVendorId, SubDeviceId -#define DEVICE_INF_TAG 0xFFF2 -#define DEVICE_RES_TAG 0xFFF1 -#define LIST_END_TAG 0x0000 +#define DEVICE_INF_TAG 0xFFF2 +#define DEVICE_RES_TAG 0xFFF1 +#define LIST_END_TAG 0x0000 -#define EVEN_ALIGN 0xFFFFFFFFFFFFFFFEULL +#define EVEN_ALIGN 0xFFFFFFFFFFFFFFFEULL /** Returns a list of ACPI resource descriptors that detail the special @@ -82,7 +82,7 @@ PCheckDevice ( // // Handle onto which the Incompatible PCI Device List is installed // -EFI_HANDLE mIncompatiblePciDeviceSupportHandle = NULL; +EFI_HANDLE mIncompatiblePciDeviceSupportHandle = NULL; // // The Incompatible PCI Device Support Protocol instance produced by this driver @@ -94,7 +94,7 @@ EFI_INCOMPATIBLE_PCI_DEVICE_SUPPORT_PROTOCOL mIncompatiblePciDeviceSupport = { // // The incompatible PCI devices list template // -GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { +GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // // DEVICE_INF_TAG, // PCI_DEVICE_ID (VendorID, DeviceID, Revision, SubVendorId, SubDeviceId), @@ -106,7 +106,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // Device Adaptec 9004 // DEVICE_INF_TAG, - PCI_DEVICE_ID(0x9004, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), + PCI_DEVICE_ID (0x9004, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), DEVICE_RES_TAG, ACPI_ADDRESS_SPACE_TYPE_IO, 0, @@ -120,7 +120,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // Device Adaptec 9005 // DEVICE_INF_TAG, - PCI_DEVICE_ID(0x9005, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), + PCI_DEVICE_ID (0x9005, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), DEVICE_RES_TAG, ACPI_ADDRESS_SPACE_TYPE_IO, 0, @@ -134,7 +134,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // Device QLogic 1007 // DEVICE_INF_TAG, - PCI_DEVICE_ID(0x1077, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), + PCI_DEVICE_ID (0x1077, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), DEVICE_RES_TAG, ACPI_ADDRESS_SPACE_TYPE_IO, 0, @@ -148,7 +148,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // Device Agilent 103C // DEVICE_INF_TAG, - PCI_DEVICE_ID(0x103C, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), + PCI_DEVICE_ID (0x103C, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), DEVICE_RES_TAG, ACPI_ADDRESS_SPACE_TYPE_IO, 0, @@ -162,7 +162,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { // Device Agilent 15BC // DEVICE_INF_TAG, - PCI_DEVICE_ID(0x15BC, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), + PCI_DEVICE_ID (0x15BC, MAX_UINT64, MAX_UINT64, MAX_UINT64, MAX_UINT64), DEVICE_RES_TAG, ACPI_ADDRESS_SPACE_TYPE_IO, 0, @@ -178,7 +178,6 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { LIST_END_TAG }; - /** Entry point of the incompatible pci device support code. Setup an incompatible device list template and install EFI Incompatible PCI Device Support protocol. @@ -193,11 +192,11 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mIncompatiblePciDeviceList[] = { EFI_STATUS EFIAPI IncompatiblePciDeviceSupportEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install EFI Incompatible PCI Device Support Protocol on a new handle @@ -244,15 +243,15 @@ PCheckDevice ( OUT VOID **Configuration ) { - UINT64 Tag; - UINT64 *ListPtr; - UINT64 *TempListPtr; - EFI_PCI_DEVICE_HEADER_INFO *Header; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *AcpiPtr; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *OldAcpiPtr; - EFI_PCI_RESOUCE_DESCRIPTOR *Dsc; - EFI_ACPI_END_TAG_DESCRIPTOR *PtrEnd; - UINTN Index; + UINT64 Tag; + UINT64 *ListPtr; + UINT64 *TempListPtr; + EFI_PCI_DEVICE_HEADER_INFO *Header; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *AcpiPtr; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *OldAcpiPtr; + EFI_PCI_RESOUCE_DESCRIPTOR *Dsc; + EFI_ACPI_END_TAG_DESCRIPTOR *PtrEnd; + UINTN Index; // // Validate the parameters @@ -260,120 +259,121 @@ PCheckDevice ( if (Configuration == NULL) { return EFI_INVALID_PARAMETER; } + // // Initialize the return value to NULL // - * (VOID **) Configuration = NULL; + *(VOID **)Configuration = NULL; - ListPtr = mIncompatiblePciDeviceList; + ListPtr = mIncompatiblePciDeviceList; while (*ListPtr != LIST_END_TAG) { - Tag = *ListPtr; switch (Tag) { - case DEVICE_INF_TAG: - Header = (EFI_PCI_DEVICE_HEADER_INFO *) (ListPtr + 1); - ListPtr = ListPtr + 1 + sizeof (EFI_PCI_DEVICE_HEADER_INFO) / sizeof (UINT64); - // - // See if the Header matches the parameters passed in - // - if ((Header->VendorId != MAX_UINT64) && (VendorId != MAX_UINTN)) { - if (Header->VendorId != VendorId) { - continue; + case DEVICE_INF_TAG: + Header = (EFI_PCI_DEVICE_HEADER_INFO *)(ListPtr + 1); + ListPtr = ListPtr + 1 + sizeof (EFI_PCI_DEVICE_HEADER_INFO) / sizeof (UINT64); + // + // See if the Header matches the parameters passed in + // + if ((Header->VendorId != MAX_UINT64) && (VendorId != MAX_UINTN)) { + if (Header->VendorId != VendorId) { + continue; + } } - } - if ((Header->DeviceId != MAX_UINT64) && (DeviceId != MAX_UINTN)) { - if (DeviceId != Header->DeviceId) { - continue; + if ((Header->DeviceId != MAX_UINT64) && (DeviceId != MAX_UINTN)) { + if (DeviceId != Header->DeviceId) { + continue; + } } - } - if ((Header->RevisionId != MAX_UINT64) && (RevisionId != MAX_UINTN)) { - if (RevisionId != Header->RevisionId) { - continue; + if ((Header->RevisionId != MAX_UINT64) && (RevisionId != MAX_UINTN)) { + if (RevisionId != Header->RevisionId) { + continue; + } } - } - if ((Header->SubsystemVendorId != MAX_UINT64) && (SubsystemVendorId != MAX_UINTN)) { - if (SubsystemVendorId != Header->SubsystemVendorId) { - continue; + if ((Header->SubsystemVendorId != MAX_UINT64) && (SubsystemVendorId != MAX_UINTN)) { + if (SubsystemVendorId != Header->SubsystemVendorId) { + continue; + } } - } - if ((Header->SubsystemDeviceId != MAX_UINT64) && (SubsystemDeviceId != MAX_UINTN)) { - if (SubsystemDeviceId != Header->SubsystemDeviceId) { - continue; + if ((Header->SubsystemDeviceId != MAX_UINT64) && (SubsystemDeviceId != MAX_UINTN)) { + if (SubsystemDeviceId != Header->SubsystemDeviceId) { + continue; + } } - } - // - // Matched an item, so construct the ACPI descriptor for the resource. - // - // - // Count the resource items so that to allocate space - // - for (Index = 0, TempListPtr = ListPtr; *TempListPtr == DEVICE_RES_TAG; Index++) { - TempListPtr = TempListPtr + 1 + ((sizeof (EFI_PCI_RESOUCE_DESCRIPTOR)) / sizeof (UINT64)); - } - // - // If there is at least one type of resource request, - // allocate an acpi resource node - // - if (Index == 0) { - return EFI_UNSUPPORTED; - } - - AcpiPtr = AllocateZeroPool (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) * Index + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR)); - if (AcpiPtr == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - OldAcpiPtr = AcpiPtr; - // - // Fill the EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR structure - // according to the EFI_PCI_RESOUCE_DESCRIPTOR structure - // - for (; *ListPtr == DEVICE_RES_TAG;) { - - Dsc = (EFI_PCI_RESOUCE_DESCRIPTOR *) (ListPtr + 1); - - AcpiPtr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - AcpiPtr->Len = (UINT16) sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; - AcpiPtr->ResType = (UINT8) Dsc->ResType; - AcpiPtr->GenFlag = (UINT8) Dsc->GenFlag; - AcpiPtr->SpecificFlag = (UINT8) Dsc->SpecificFlag; - AcpiPtr->AddrSpaceGranularity = Dsc->AddrSpaceGranularity;; - AcpiPtr->AddrRangeMin = Dsc->AddrRangeMin; - AcpiPtr->AddrRangeMax = Dsc->AddrRangeMax; - AcpiPtr->AddrTranslationOffset = Dsc->AddrTranslationOffset; - AcpiPtr->AddrLen = Dsc->AddrLen; + // + // Matched an item, so construct the ACPI descriptor for the resource. + // + // + // Count the resource items so that to allocate space + // + for (Index = 0, TempListPtr = ListPtr; *TempListPtr == DEVICE_RES_TAG; Index++) { + TempListPtr = TempListPtr + 1 + ((sizeof (EFI_PCI_RESOUCE_DESCRIPTOR)) / sizeof (UINT64)); + } + + // + // If there is at least one type of resource request, + // allocate an acpi resource node + // + if (Index == 0) { + return EFI_UNSUPPORTED; + } + + AcpiPtr = AllocateZeroPool (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) * Index + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR)); + if (AcpiPtr == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + OldAcpiPtr = AcpiPtr; + // + // Fill the EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR structure + // according to the EFI_PCI_RESOUCE_DESCRIPTOR structure + // + for ( ; *ListPtr == DEVICE_RES_TAG;) { + Dsc = (EFI_PCI_RESOUCE_DESCRIPTOR *)(ListPtr + 1); + + AcpiPtr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + AcpiPtr->Len = (UINT16)sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; + AcpiPtr->ResType = (UINT8)Dsc->ResType; + AcpiPtr->GenFlag = (UINT8)Dsc->GenFlag; + AcpiPtr->SpecificFlag = (UINT8)Dsc->SpecificFlag; + AcpiPtr->AddrSpaceGranularity = Dsc->AddrSpaceGranularity; + AcpiPtr->AddrRangeMin = Dsc->AddrRangeMin; + AcpiPtr->AddrRangeMax = Dsc->AddrRangeMax; + AcpiPtr->AddrTranslationOffset = Dsc->AddrTranslationOffset; + AcpiPtr->AddrLen = Dsc->AddrLen; + + ListPtr = ListPtr + 1 + ((sizeof (EFI_PCI_RESOUCE_DESCRIPTOR)) / sizeof (UINT64)); + AcpiPtr++; + } + + // + // Put the checksum + // + PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *)(AcpiPtr); + PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; + PtrEnd->Checksum = 0; + + *(VOID **)Configuration = OldAcpiPtr; + + return EFI_SUCCESS; + + case DEVICE_RES_TAG: + // + // Adjust the pointer to the next PCI resource descriptor item + // ListPtr = ListPtr + 1 + ((sizeof (EFI_PCI_RESOUCE_DESCRIPTOR)) / sizeof (UINT64)); - AcpiPtr++; - } - // - // Put the checksum - // - PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *) (AcpiPtr); - PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; - PtrEnd->Checksum = 0; - - *(VOID **) Configuration = OldAcpiPtr; - - return EFI_SUCCESS; - - case DEVICE_RES_TAG: - // - // Adjust the pointer to the next PCI resource descriptor item - // - ListPtr = ListPtr + 1 + ((sizeof (EFI_PCI_RESOUCE_DESCRIPTOR)) / sizeof (UINT64)); - break; - - default: - return EFI_UNSUPPORTED; + break; + + default: + return EFI_UNSUPPORTED; } } return EFI_UNSUPPORTED; } - diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/ComponentName.c index 74b6e281b3..af1b2e5526 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/ComponentName.c @@ -17,12 +17,12 @@ // STATIC -EFI_UNICODE_STRING_TABLE mDriverNameTable[] = { +EFI_UNICODE_STRING_TABLE mDriverNameTable[] = { { "eng;en", L"PCI I/O protocol emulation driver for non-discoverable devices" }, - { NULL, NULL } + { NULL, NULL } }; -EFI_COMPONENT_NAME_PROTOCOL gComponentName; +EFI_COMPONENT_NAME_PROTOCOL gComponentName; /** Retrieves a Unicode string that is the user readable name of the UEFI Driver. @@ -49,9 +49,9 @@ STATIC EFI_STATUS EFIAPI NonDiscoverablePciGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -93,24 +93,24 @@ STATIC EFI_STATUS EFIAPI NonDiscoverablePciGetDeviceName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE DeviceHandle, - IN EFI_HANDLE ChildHandle, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE DeviceHandle, + IN EFI_HANDLE ChildHandle, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; } -EFI_COMPONENT_NAME_PROTOCOL gComponentName = { +EFI_COMPONENT_NAME_PROTOCOL gComponentName = { &NonDiscoverablePciGetDriverName, &NonDiscoverablePciGetDeviceName, "eng" // SupportedLanguages, ISO 639-2 language codes }; -EFI_COMPONENT_NAME2_PROTOCOL gComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) &NonDiscoverablePciGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) &NonDiscoverablePciGetDeviceName, +EFI_COMPONENT_NAME2_PROTOCOL gComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)&NonDiscoverablePciGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)&NonDiscoverablePciGetDeviceName, "en" // SupportedLanguages, RFC 4646 language codes }; diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.c b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.c index 5c93e2a766..96fc03979c 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.c +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.c @@ -10,16 +10,16 @@ #include -#define MAX_NON_DISCOVERABLE_PCI_DEVICE_ID (32 * 256) +#define MAX_NON_DISCOVERABLE_PCI_DEVICE_ID (32 * 256) -STATIC UINTN mUniqueIdCounter = 0; -EFI_CPU_ARCH_PROTOCOL *mCpu; +STATIC UINTN mUniqueIdCounter = 0; +EFI_CPU_ARCH_PROTOCOL *mCpu; // // We only support the following device types // STATIC -CONST EFI_GUID * CONST +CONST EFI_GUID *CONST SupportedNonDiscoverableDevices[] = { &gEdkiiNonDiscoverableAhciDeviceGuid, &gEdkiiNonDiscoverableEhciDeviceGuid, @@ -63,27 +63,31 @@ STATIC EFI_STATUS EFIAPI NonDiscoverablePciDeviceSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE DeviceHandle, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE DeviceHandle, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - NON_DISCOVERABLE_DEVICE *Device; - EFI_STATUS Status; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - INTN Idx; - - Status = gBS->OpenProtocol (DeviceHandle, - &gEdkiiNonDiscoverableDeviceProtocolGuid, (VOID **)&Device, - This->DriverBindingHandle, DeviceHandle, - EFI_OPEN_PROTOCOL_BY_DRIVER); + NON_DISCOVERABLE_DEVICE *Device; + EFI_STATUS Status; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + INTN Idx; + + Status = gBS->OpenProtocol ( + DeviceHandle, + &gEdkiiNonDiscoverableDeviceProtocolGuid, + (VOID **)&Device, + This->DriverBindingHandle, + DeviceHandle, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (EFI_ERROR (Status)) { return Status; } Status = EFI_UNSUPPORTED; for (Idx = 0; Idx < ARRAY_SIZE (SupportedNonDiscoverableDevices); Idx++) { - if (CompareGuid (Device->Type, SupportedNonDiscoverableDevices [Idx])) { + if (CompareGuid (Device->Type, SupportedNonDiscoverableDevices[Idx])) { Status = EFI_SUCCESS; break; } @@ -98,17 +102,23 @@ NonDiscoverablePciDeviceSupported ( // that they only describe things that we can handle // for (Desc = Device->Resources; Desc->Desc != ACPI_END_TAG_DESCRIPTOR; - Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) { - if (Desc->Desc != ACPI_ADDRESS_SPACE_DESCRIPTOR || - Desc->ResType != ACPI_ADDRESS_SPACE_TYPE_MEM) { + Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) + { + if ((Desc->Desc != ACPI_ADDRESS_SPACE_DESCRIPTOR) || + (Desc->ResType != ACPI_ADDRESS_SPACE_TYPE_MEM)) + { Status = EFI_UNSUPPORTED; break; } } CloseProtocol: - gBS->CloseProtocol (DeviceHandle, &gEdkiiNonDiscoverableDeviceProtocolGuid, - This->DriverBindingHandle, DeviceHandle); + gBS->CloseProtocol ( + DeviceHandle, + &gEdkiiNonDiscoverableDeviceProtocolGuid, + This->DriverBindingHandle, + DeviceHandle + ); return Status; } @@ -130,13 +140,13 @@ STATIC EFI_STATUS EFIAPI NonDiscoverablePciDeviceStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE DeviceHandle, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE DeviceHandle, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_STATUS Status; ASSERT (mUniqueIdCounter < MAX_NON_DISCOVERABLE_PCI_DEVICE_ID); if (mUniqueIdCounter >= MAX_NON_DISCOVERABLE_PCI_DEVICE_ID) { @@ -148,10 +158,14 @@ NonDiscoverablePciDeviceStart ( return EFI_OUT_OF_RESOURCES; } - Status = gBS->OpenProtocol (DeviceHandle, + Status = gBS->OpenProtocol ( + DeviceHandle, &gEdkiiNonDiscoverableDeviceProtocolGuid, - (VOID **)&Dev->Device, This->DriverBindingHandle, - DeviceHandle, EFI_OPEN_PROTOCOL_BY_DRIVER); + (VOID **)&Dev->Device, + This->DriverBindingHandle, + DeviceHandle, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (EFI_ERROR (Status)) { goto FreeDev; } @@ -163,8 +177,12 @@ NonDiscoverablePciDeviceStart ( // EFI_PCI_IO_PROTOCOL interface. // Dev->Signature = NON_DISCOVERABLE_PCI_DEVICE_SIG; - Status = gBS->InstallProtocolInterface (&DeviceHandle, &gEfiPciIoProtocolGuid, - EFI_NATIVE_INTERFACE, &Dev->PciIo); + Status = gBS->InstallProtocolInterface ( + &DeviceHandle, + &gEfiPciIoProtocolGuid, + EFI_NATIVE_INTERFACE, + &Dev->PciIo + ); if (EFI_ERROR (Status)) { goto CloseProtocol; } @@ -174,8 +192,12 @@ NonDiscoverablePciDeviceStart ( return EFI_SUCCESS; CloseProtocol: - gBS->CloseProtocol (DeviceHandle, &gEdkiiNonDiscoverableDeviceProtocolGuid, - This->DriverBindingHandle, DeviceHandle); + gBS->CloseProtocol ( + DeviceHandle, + &gEdkiiNonDiscoverableDeviceProtocolGuid, + This->DriverBindingHandle, + DeviceHandle + ); FreeDev: FreePool (Dev); @@ -199,19 +221,24 @@ STATIC EFI_STATUS EFIAPI NonDiscoverablePciDeviceStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE DeviceHandle, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE DeviceHandle, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - NON_DISCOVERABLE_PCI_DEVICE *Dev; - - Status = gBS->OpenProtocol (DeviceHandle, &gEfiPciIoProtocolGuid, - (VOID **)&PciIo, This->DriverBindingHandle, DeviceHandle, - EFI_OPEN_PROTOCOL_GET_PROTOCOL); + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + + Status = gBS->OpenProtocol ( + DeviceHandle, + &gEfiPciIoProtocolGuid, + (VOID **)&PciIo, + This->DriverBindingHandle, + DeviceHandle, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); if (EFI_ERROR (Status)) { return Status; } @@ -221,27 +248,33 @@ NonDiscoverablePciDeviceStop ( // // Handle Stop() requests for in-use driver instances gracefully. // - Status = gBS->UninstallProtocolInterface (DeviceHandle, - &gEfiPciIoProtocolGuid, &Dev->PciIo); + Status = gBS->UninstallProtocolInterface ( + DeviceHandle, + &gEfiPciIoProtocolGuid, + &Dev->PciIo + ); if (EFI_ERROR (Status)) { return Status; } - gBS->CloseProtocol (DeviceHandle, &gEdkiiNonDiscoverableDeviceProtocolGuid, - This->DriverBindingHandle, DeviceHandle); + gBS->CloseProtocol ( + DeviceHandle, + &gEdkiiNonDiscoverableDeviceProtocolGuid, + This->DriverBindingHandle, + DeviceHandle + ); FreePool (Dev); return EFI_SUCCESS; } - // // The static object that groups the Supported() (ie. probe), Start() and // Stop() functions of the driver together. Refer to UEFI Spec 2.3.1 + Errata // C, 10.1 EFI Driver Binding Protocol. // -STATIC EFI_DRIVER_BINDING_PROTOCOL gDriverBinding = { +STATIC EFI_DRIVER_BINDING_PROTOCOL gDriverBinding = { &NonDiscoverablePciDeviceSupported, &NonDiscoverablePciDeviceStart, &NonDiscoverablePciDeviceStop, @@ -263,14 +296,14 @@ STATIC EFI_DRIVER_BINDING_PROTOCOL gDriverBinding = { EFI_STATUS EFIAPI NonDiscoverablePciDeviceDxeEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&mCpu); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); return EfiLibInstallDriverBindingComponentName2 ( ImageHandle, diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c index 363c4a765b..c1c5c6267c 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.c @@ -16,10 +16,10 @@ #include typedef struct { - EFI_PHYSICAL_ADDRESS AllocAddress; - VOID *HostAddress; - EFI_PCI_IO_PROTOCOL_OPERATION Operation; - UINTN NumberOfBytes; + EFI_PHYSICAL_ADDRESS AllocAddress; + VOID *HostAddress; + EFI_PCI_IO_PROTOCOL_OPERATION Operation; + UINTN NumberOfBytes; } NON_DISCOVERABLE_PCI_DEVICE_MAP_INFO; /** @@ -33,12 +33,12 @@ typedef struct { STATIC EFI_STATUS GetBarResource ( - IN NON_DISCOVERABLE_PCI_DEVICE *Dev, - IN UINT8 BarIndex, - OUT EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR **Descriptor + IN NON_DISCOVERABLE_PCI_DEVICE *Dev, + IN UINT8 BarIndex, + OUT EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR **Descriptor ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; if (BarIndex < Dev->BarOffset) { return EFI_NOT_FOUND; @@ -52,8 +52,8 @@ GetBarResource ( for (Desc = Dev->Device->Resources; Desc->Desc != ACPI_END_TAG_DESCRIPTOR; - Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) { - + Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) + { if (BarIndex == 0) { *Descriptor = Desc; return EFI_SUCCESS; @@ -61,6 +61,7 @@ GetBarResource ( BarIndex -= 1; } + return EFI_NOT_FOUND; } @@ -83,20 +84,20 @@ STATIC EFI_STATUS EFIAPI PciIoPollMem ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINT64 Mask, - IN UINT64 Value, - IN UINT64 Delay, - OUT UINT64 *Result + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINT64 Mask, + IN UINT64 Value, + IN UINT64 Delay, + OUT UINT64 *Result ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - UINTN Count; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + UINTN Count; + EFI_STATUS Status; if ((UINT32)Width > EfiPciIoWidthUint64) { return EFI_INVALID_PARAMETER; @@ -106,7 +107,7 @@ PciIoPollMem ( return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Count = 1; Status = GetBarResource (Dev, BarIndex, &Desc); @@ -141,20 +142,20 @@ STATIC EFI_STATUS EFIAPI PciIoPollIo ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINT64 Mask, - IN UINT64 Value, - IN UINT64 Delay, - OUT UINT64 *Result + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINT64 Mask, + IN UINT64 Value, + IN UINT64 Delay, + OUT UINT64 *Result ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - UINTN Count; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + UINTN Count; + EFI_STATUS Status; if ((UINT32)Width > EfiPciIoWidthUint64) { return EFI_INVALID_PARAMETER; @@ -164,7 +165,7 @@ PciIoPollIo ( return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Count = 1; Status = GetBarResource (Dev, BarIndex, &Desc); @@ -200,48 +201,51 @@ STATIC EFI_STATUS EFIAPI PciIoMemRW ( - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINTN Count, - IN UINTN DstStride, - IN VOID *Dst, - IN UINTN SrcStride, - OUT CONST VOID *Src + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINTN Count, + IN UINTN DstStride, + IN VOID *Dst, + IN UINTN SrcStride, + OUT CONST VOID *Src ) { - volatile UINT8 *Dst8; - volatile UINT16 *Dst16; - volatile UINT32 *Dst32; - volatile CONST UINT8 *Src8; - volatile CONST UINT16 *Src16; - volatile CONST UINT32 *Src32; + volatile UINT8 *Dst8; + volatile UINT16 *Dst16; + volatile UINT32 *Dst32; + volatile CONST UINT8 *Src8; + volatile CONST UINT16 *Src16; + volatile CONST UINT32 *Src32; // // Loop for each iteration and move the data // switch (Width & 0x3) { - case EfiPciWidthUint8: - Dst8 = (UINT8 *)Dst; - Src8 = (UINT8 *)Src; - for (;Count > 0; Count--, Dst8 += DstStride, Src8 += SrcStride) { - *Dst8 = *Src8; - } - break; - case EfiPciWidthUint16: - Dst16 = (UINT16 *)Dst; - Src16 = (UINT16 *)Src; - for (;Count > 0; Count--, Dst16 += DstStride, Src16 += SrcStride) { - *Dst16 = *Src16; - } - break; - case EfiPciWidthUint32: - Dst32 = (UINT32 *)Dst; - Src32 = (UINT32 *)Src; - for (;Count > 0; Count--, Dst32 += DstStride, Src32 += SrcStride) { - *Dst32 = *Src32; - } - break; - default: - return EFI_INVALID_PARAMETER; + case EfiPciWidthUint8: + Dst8 = (UINT8 *)Dst; + Src8 = (UINT8 *)Src; + for ( ; Count > 0; Count--, Dst8 += DstStride, Src8 += SrcStride) { + *Dst8 = *Src8; + } + + break; + case EfiPciWidthUint16: + Dst16 = (UINT16 *)Dst; + Src16 = (UINT16 *)Src; + for ( ; Count > 0; Count--, Dst16 += DstStride, Src16 += SrcStride) { + *Dst16 = *Src16; + } + + break; + case EfiPciWidthUint32: + Dst32 = (UINT32 *)Dst; + Src32 = (UINT32 *)Src; + for ( ; Count > 0; Count--, Dst32 += DstStride, Src32 += SrcStride) { + *Dst32 = *Src32; + } + + break; + default: + return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; @@ -271,25 +275,25 @@ STATIC EFI_STATUS EFIAPI PciIoMemRead ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINTN Count, + IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - UINTN AlignMask; - VOID *Address; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + UINTN AlignMask; + VOID *Address; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_STATUS Status; if (Buffer == NULL) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); // // Only allow accesses to the BARs we emulate @@ -303,34 +307,35 @@ PciIoMemRead ( return EFI_UNSUPPORTED; } - Address = (VOID *)(UINTN)(Desc->AddrRangeMin + Offset); + Address = (VOID *)(UINTN)(Desc->AddrRangeMin + Offset); AlignMask = (1 << (Width & 0x03)) - 1; if ((UINTN)Address & AlignMask) { return EFI_INVALID_PARAMETER; } switch (Width) { - case EfiPciIoWidthUint8: - case EfiPciIoWidthUint16: - case EfiPciIoWidthUint32: - case EfiPciIoWidthUint64: - return PciIoMemRW (Width, Count, 1, Buffer, 1, Address); - - case EfiPciIoWidthFifoUint8: - case EfiPciIoWidthFifoUint16: - case EfiPciIoWidthFifoUint32: - case EfiPciIoWidthFifoUint64: - return PciIoMemRW (Width, Count, 1, Buffer, 0, Address); - - case EfiPciIoWidthFillUint8: - case EfiPciIoWidthFillUint16: - case EfiPciIoWidthFillUint32: - case EfiPciIoWidthFillUint64: - return PciIoMemRW (Width, Count, 0, Buffer, 1, Address); - - default: - break; + case EfiPciIoWidthUint8: + case EfiPciIoWidthUint16: + case EfiPciIoWidthUint32: + case EfiPciIoWidthUint64: + return PciIoMemRW (Width, Count, 1, Buffer, 1, Address); + + case EfiPciIoWidthFifoUint8: + case EfiPciIoWidthFifoUint16: + case EfiPciIoWidthFifoUint32: + case EfiPciIoWidthFifoUint64: + return PciIoMemRW (Width, Count, 1, Buffer, 0, Address); + + case EfiPciIoWidthFillUint8: + case EfiPciIoWidthFillUint16: + case EfiPciIoWidthFillUint32: + case EfiPciIoWidthFillUint64: + return PciIoMemRW (Width, Count, 0, Buffer, 1, Address); + + default: + break; } + return EFI_INVALID_PARAMETER; } @@ -358,25 +363,25 @@ STATIC EFI_STATUS EFIAPI PciIoMemWrite ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINTN Count, + IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - UINTN AlignMask; - VOID *Address; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + UINTN AlignMask; + VOID *Address; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_STATUS Status; if (Buffer == NULL) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); // // Only allow accesses to the BARs we emulate @@ -390,34 +395,35 @@ PciIoMemWrite ( return EFI_UNSUPPORTED; } - Address = (VOID *)(UINTN)(Desc->AddrRangeMin + Offset); + Address = (VOID *)(UINTN)(Desc->AddrRangeMin + Offset); AlignMask = (1 << (Width & 0x03)) - 1; if ((UINTN)Address & AlignMask) { return EFI_INVALID_PARAMETER; } switch (Width) { - case EfiPciIoWidthUint8: - case EfiPciIoWidthUint16: - case EfiPciIoWidthUint32: - case EfiPciIoWidthUint64: - return PciIoMemRW (Width, Count, 1, Address, 1, Buffer); - - case EfiPciIoWidthFifoUint8: - case EfiPciIoWidthFifoUint16: - case EfiPciIoWidthFifoUint32: - case EfiPciIoWidthFifoUint64: - return PciIoMemRW (Width, Count, 0, Address, 1, Buffer); - - case EfiPciIoWidthFillUint8: - case EfiPciIoWidthFillUint16: - case EfiPciIoWidthFillUint32: - case EfiPciIoWidthFillUint64: - return PciIoMemRW (Width, Count, 1, Address, 0, Buffer); - - default: - break; + case EfiPciIoWidthUint8: + case EfiPciIoWidthUint16: + case EfiPciIoWidthUint32: + case EfiPciIoWidthUint64: + return PciIoMemRW (Width, Count, 1, Address, 1, Buffer); + + case EfiPciIoWidthFifoUint8: + case EfiPciIoWidthFifoUint16: + case EfiPciIoWidthFifoUint32: + case EfiPciIoWidthFifoUint64: + return PciIoMemRW (Width, Count, 0, Address, 1, Buffer); + + case EfiPciIoWidthFillUint8: + case EfiPciIoWidthFillUint16: + case EfiPciIoWidthFillUint32: + case EfiPciIoWidthFillUint64: + return PciIoMemRW (Width, Count, 1, Address, 0, Buffer); + + default: + break; } + return EFI_INVALID_PARAMETER; } @@ -438,17 +444,17 @@ STATIC EFI_STATUS EFIAPI PciIoIoRead ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINTN Count, + IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_STATUS Status; if ((UINT32)Width >= EfiPciIoWidthMaximum) { return EFI_INVALID_PARAMETER; @@ -458,7 +464,7 @@ PciIoIoRead ( return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Status = GetBarResource (Dev, BarIndex, &Desc); if (EFI_ERROR (Status)) { @@ -490,17 +496,17 @@ STATIC EFI_STATUS EFIAPI PciIoIoWrite ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 BarIndex, - IN UINT64 Offset, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 BarIndex, + IN UINT64 Offset, + IN UINTN Count, + IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_STATUS Status; if ((UINT32)Width >= EfiPciIoWidthMaximum) { return EFI_INVALID_PARAMETER; @@ -510,7 +516,7 @@ PciIoIoWrite ( return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Status = GetBarResource (Dev, BarIndex, &Desc); if (EFI_ERROR (Status)) { @@ -547,17 +553,17 @@ PciIoPciRead ( IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - VOID *Address; - UINTN Length; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + VOID *Address; + UINTN Length; - if (Width < 0 || Width >= EfiPciIoWidthMaximum || Buffer == NULL) { + if ((Width < 0) || (Width >= EfiPciIoWidthMaximum) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Address = (UINT8 *)&Dev->ConfigSpace + Offset; - Length = Count << ((UINTN)Width & 0x3); + Length = Count << ((UINTN)Width & 0x3); if (Offset >= sizeof (Dev->ConfigSpace)) { ZeroMem (Buffer, Length); @@ -574,6 +580,7 @@ PciIoPciRead ( Count -= Length >> ((UINTN)Width & 0x3); } + return PciIoMemRW (Width, Count, 1, Buffer, 1, Address); } @@ -597,21 +604,21 @@ STATIC EFI_STATUS EFIAPI PciIoPciWrite ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT32 Offset, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT32 Offset, + IN UINTN Count, + IN OUT VOID *Buffer ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - VOID *Address; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + VOID *Address; - if (Width < 0 || Width >= EfiPciIoWidthMaximum || Buffer == NULL) { + if ((Width < 0) || (Width >= EfiPciIoWidthMaximum) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Address = (UINT8 *)&Dev->ConfigSpace + Offset; if (Offset + (Count << ((UINTN)Width & 0x3)) > sizeof (Dev->ConfigSpace)) { @@ -643,25 +650,25 @@ STATIC EFI_STATUS EFIAPI PciIoCopyMem ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 DestBarIndex, - IN UINT64 DestOffset, - IN UINT8 SrcBarIndex, - IN UINT64 SrcOffset, - IN UINTN Count + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 DestBarIndex, + IN UINT64 DestOffset, + IN UINT8 SrcBarIndex, + IN UINT64 SrcOffset, + IN UINTN Count ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *DestDesc; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *SrcDesc; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *DestDesc; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *SrcDesc; + EFI_STATUS Status; if ((UINT32)Width > EfiPciIoWidthUint64) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Status = GetBarResource (Dev, DestBarIndex, &DestDesc); if (EFI_ERROR (Status)) { @@ -720,16 +727,18 @@ CoherentPciIoMap ( EFI_STATUS Status; NON_DISCOVERABLE_PCI_DEVICE_MAP_INFO *MapInfo; - if (Operation != EfiPciIoOperationBusMasterRead && - Operation != EfiPciIoOperationBusMasterWrite && - Operation != EfiPciIoOperationBusMasterCommonBuffer) { + if ((Operation != EfiPciIoOperationBusMasterRead) && + (Operation != EfiPciIoOperationBusMasterWrite) && + (Operation != EfiPciIoOperationBusMasterCommonBuffer)) + { return EFI_INVALID_PARAMETER; } - if (HostAddress == NULL || - NumberOfBytes == NULL || - DeviceAddress == NULL || - Mapping == NULL) { + if ((HostAddress == NULL) || + (NumberOfBytes == NULL) || + (DeviceAddress == NULL) || + (Mapping == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -737,10 +746,10 @@ CoherentPciIoMap ( // If HostAddress exceeds 4 GB, and this device does not support 64-bit DMA // addressing, we need to allocate a bounce buffer and copy over the data. // - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); - if ((Dev->Attributes & EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0 && - (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress + *NumberOfBytes > SIZE_4GB) { - + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); + if (((Dev->Attributes & EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) && + ((EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress + *NumberOfBytes > SIZE_4GB)) + { // // Bounce buffering is not possible for consistent mappings // @@ -753,14 +762,17 @@ CoherentPciIoMap ( return EFI_OUT_OF_RESOURCES; } - MapInfo->AllocAddress = MAX_UINT32; - MapInfo->HostAddress = HostAddress; - MapInfo->Operation = Operation; + MapInfo->AllocAddress = MAX_UINT32; + MapInfo->HostAddress = HostAddress; + MapInfo->Operation = Operation; MapInfo->NumberOfBytes = *NumberOfBytes; - Status = gBS->AllocatePages (AllocateMaxAddress, EfiBootServicesData, + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiBootServicesData, EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes), - &MapInfo->AllocAddress); + &MapInfo->AllocAddress + ); if (EFI_ERROR (Status)) { // // If we fail here, it is likely because the system has no memory below @@ -770,16 +782,22 @@ CoherentPciIoMap ( FreePool (MapInfo); return EFI_DEVICE_ERROR; } + if (Operation == EfiPciIoOperationBusMasterRead) { - gBS->CopyMem ((VOID *)(UINTN)MapInfo->AllocAddress, HostAddress, - *NumberOfBytes); + gBS->CopyMem ( + (VOID *)(UINTN)MapInfo->AllocAddress, + HostAddress, + *NumberOfBytes + ); } + *DeviceAddress = MapInfo->AllocAddress; - *Mapping = MapInfo; + *Mapping = MapInfo; } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; + *Mapping = NULL; } + return EFI_SUCCESS; } @@ -796,8 +814,8 @@ STATIC EFI_STATUS EFIAPI CoherentPciIoUnmap ( - IN EFI_PCI_IO_PROTOCOL *This, - IN VOID *Mapping + IN EFI_PCI_IO_PROTOCOL *This, + IN VOID *Mapping ) { NON_DISCOVERABLE_PCI_DEVICE_MAP_INFO *MapInfo; @@ -805,13 +823,20 @@ CoherentPciIoUnmap ( MapInfo = Mapping; if (MapInfo != NULL) { if (MapInfo->Operation == EfiPciIoOperationBusMasterWrite) { - gBS->CopyMem (MapInfo->HostAddress, (VOID *)(UINTN)MapInfo->AllocAddress, - MapInfo->NumberOfBytes); + gBS->CopyMem ( + MapInfo->HostAddress, + (VOID *)(UINTN)MapInfo->AllocAddress, + MapInfo->NumberOfBytes + ); } - gBS->FreePages (MapInfo->AllocAddress, - EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes)); + + gBS->FreePages ( + MapInfo->AllocAddress, + EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes) + ); FreePool (MapInfo); } + return EFI_SUCCESS; } @@ -838,21 +863,22 @@ STATIC EFI_STATUS EFIAPI CoherentPciIoAllocateBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_PHYSICAL_ADDRESS AllocAddress; - EFI_ALLOCATE_TYPE AllocType; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_PHYSICAL_ADDRESS AllocAddress; + EFI_ALLOCATE_TYPE AllocType; + EFI_STATUS Status; if ((Attributes & ~(EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE | - EFI_PCI_ATTRIBUTE_MEMORY_CACHED)) != 0) { + EFI_PCI_ATTRIBUTE_MEMORY_CACHED)) != 0) + { return EFI_UNSUPPORTED; } @@ -861,7 +887,8 @@ CoherentPciIoAllocateBuffer ( } if ((MemoryType != EfiBootServicesData) && - (MemoryType != EfiRuntimeServicesData)) { + (MemoryType != EfiRuntimeServicesData)) + { return EFI_INVALID_PARAMETER; } @@ -870,10 +897,10 @@ CoherentPciIoAllocateBuffer ( // been set. If the system has no memory available below 4 GB, there // is little we can do except propagate the error. // - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); if ((Dev->Attributes & EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) { AllocAddress = MAX_UINT32; - AllocType = AllocateMaxAddress; + AllocType = AllocateMaxAddress; } else { AllocType = AllocateAnyPages; } @@ -882,6 +909,7 @@ CoherentPciIoAllocateBuffer ( if (!EFI_ERROR (Status)) { *HostAddress = (VOID *)(UINTN)AllocAddress; } + return Status; } @@ -899,9 +927,9 @@ STATIC EFI_STATUS EFIAPI CoherentPciIoFreeBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EFI_PCI_IO_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ) { FreePages (HostAddress, Pages); @@ -923,18 +951,18 @@ STATIC EFI_STATUS EFIAPI NonCoherentPciIoFreeBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EFI_PCI_IO_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - LIST_ENTRY *Entry; - EFI_STATUS Status; - NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *Alloc; - BOOLEAN Found; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + LIST_ENTRY *Entry; + EFI_STATUS Status; + NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *Alloc; + BOOLEAN Found; - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Found = FALSE; Alloc = NULL; @@ -945,10 +973,10 @@ NonCoherentPciIoFreeBuffer ( // for (Entry = Dev->UncachedAllocationList.ForwardLink; Entry != &Dev->UncachedAllocationList; - Entry = Entry->ForwardLink) { - + Entry = Entry->ForwardLink) + { Alloc = BASE_CR (Entry, NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION, List); - if (Alloc->HostAddress == HostAddress && Alloc->NumPages == Pages) { + if ((Alloc->HostAddress == HostAddress) && (Alloc->NumPages == Pages)) { // // We are freeing the exact allocation we were given // before by AllocateBuffer() @@ -968,7 +996,8 @@ NonCoherentPciIoFreeBuffer ( Status = gDS->SetMemorySpaceAttributes ( (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, EFI_PAGES_TO_SIZE (Pages), - Alloc->Attributes); + Alloc->Attributes + ); if (EFI_ERROR (Status)) { goto FreeAlloc; } @@ -1007,36 +1036,43 @@ STATIC EFI_STATUS EFIAPI NonCoherentPciIoAllocateBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor; - EFI_STATUS Status; - UINT64 MemType; - NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *Alloc; - VOID *AllocAddress; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor; + EFI_STATUS Status; + UINT64 MemType; + NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION *Alloc; + VOID *AllocAddress; if (HostAddress == NULL) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); - Status = CoherentPciIoAllocateBuffer (This, Type, MemoryType, Pages, - &AllocAddress, Attributes); + Status = CoherentPciIoAllocateBuffer ( + This, + Type, + MemoryType, + Pages, + &AllocAddress, + Attributes + ); if (EFI_ERROR (Status)) { return Status; } Status = gDS->GetMemorySpaceDescriptor ( (EFI_PHYSICAL_ADDRESS)(UINTN)AllocAddress, - &GcdDescriptor); + &GcdDescriptor + ); if (EFI_ERROR (Status)) { goto FreeBuffer; } @@ -1049,8 +1085,9 @@ NonCoherentPciIoAllocateBuffer ( // // Set the preferred memory attributes // - if ((Attributes & EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE) != 0 || - (GcdDescriptor.Capabilities & EFI_MEMORY_UC) == 0) { + if (((Attributes & EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE) != 0) || + ((GcdDescriptor.Capabilities & EFI_MEMORY_UC) == 0)) + { // // Use write combining if it was requested, or if it is the only // type supported by the region. @@ -1066,8 +1103,8 @@ NonCoherentPciIoAllocateBuffer ( } Alloc->HostAddress = AllocAddress; - Alloc->NumPages = Pages; - Alloc->Attributes = GcdDescriptor.Attributes; + Alloc->NumPages = Pages; + Alloc->Attributes = GcdDescriptor.Attributes; // // Record this allocation in the linked list, so we @@ -1078,7 +1115,8 @@ NonCoherentPciIoAllocateBuffer ( Status = gDS->SetMemorySpaceAttributes ( (EFI_PHYSICAL_ADDRESS)(UINTN)AllocAddress, EFI_PAGES_TO_SIZE (Pages), - MemType); + MemType + ); if (EFI_ERROR (Status)) { goto RemoveList; } @@ -1087,7 +1125,8 @@ NonCoherentPciIoAllocateBuffer ( mCpu, (EFI_PHYSICAL_ADDRESS)(UINTN)AllocAddress, EFI_PAGES_TO_SIZE (Pages), - EfiCpuFlushTypeInvalidate); + EfiCpuFlushTypeInvalidate + ); if (EFI_ERROR (Status)) { goto RemoveList; } @@ -1144,16 +1183,18 @@ NonCoherentPciIoMap ( EFI_GCD_MEMORY_SPACE_DESCRIPTOR GcdDescriptor; BOOLEAN Bounce; - if (HostAddress == NULL || - NumberOfBytes == NULL || - DeviceAddress == NULL || - Mapping == NULL) { + if ((HostAddress == NULL) || + (NumberOfBytes == NULL) || + (DeviceAddress == NULL) || + (Mapping == NULL)) + { return EFI_INVALID_PARAMETER; } - if (Operation != EfiPciIoOperationBusMasterRead && - Operation != EfiPciIoOperationBusMasterWrite && - Operation != EfiPciIoOperationBusMasterCommonBuffer) { + if ((Operation != EfiPciIoOperationBusMasterRead) && + (Operation != EfiPciIoOperationBusMasterWrite) && + (Operation != EfiPciIoOperationBusMasterCommonBuffer)) + { return EFI_INVALID_PARAMETER; } @@ -1162,11 +1203,11 @@ NonCoherentPciIoMap ( return EFI_OUT_OF_RESOURCES; } - MapInfo->HostAddress = HostAddress; - MapInfo->Operation = Operation; + MapInfo->HostAddress = HostAddress; + MapInfo->Operation = Operation; MapInfo->NumberOfBytes = *NumberOfBytes; - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); // // If this device does not support 64-bit DMA addressing, we need to allocate @@ -1177,33 +1218,37 @@ NonCoherentPciIoMap ( if (!Bounce) { switch (Operation) { - case EfiPciIoOperationBusMasterRead: - case EfiPciIoOperationBusMasterWrite: - // - // For streaming DMA, it is sufficient if the buffer is aligned to - // the CPUs DMA buffer alignment. - // - AlignMask = mCpu->DmaBufferAlignment - 1; - if ((((UINTN) HostAddress | *NumberOfBytes) & AlignMask) == 0) { - break; - } + case EfiPciIoOperationBusMasterRead: + case EfiPciIoOperationBusMasterWrite: + // + // For streaming DMA, it is sufficient if the buffer is aligned to + // the CPUs DMA buffer alignment. + // + AlignMask = mCpu->DmaBufferAlignment - 1; + if ((((UINTN)HostAddress | *NumberOfBytes) & AlignMask) == 0) { + break; + } + // fall through - case EfiPciIoOperationBusMasterCommonBuffer: - // - // Check whether the host address refers to an uncached mapping. - // - Status = gDS->GetMemorySpaceDescriptor ( - (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, - &GcdDescriptor); - if (EFI_ERROR (Status) || - (GcdDescriptor.Attributes & (EFI_MEMORY_WB|EFI_MEMORY_WT)) != 0) { - Bounce = TRUE; - } - break; + case EfiPciIoOperationBusMasterCommonBuffer: + // + // Check whether the host address refers to an uncached mapping. + // + Status = gDS->GetMemorySpaceDescriptor ( + (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, + &GcdDescriptor + ); + if (EFI_ERROR (Status) || + ((GcdDescriptor.Attributes & (EFI_MEMORY_WB|EFI_MEMORY_WT)) != 0)) + { + Bounce = TRUE; + } - default: - ASSERT (FALSE); + break; + + default: + ASSERT (FALSE); } } @@ -1213,20 +1258,27 @@ NonCoherentPciIoMap ( goto FreeMapInfo; } - Status = NonCoherentPciIoAllocateBuffer (This, AllocateAnyPages, - EfiBootServicesData, EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes), - &AllocAddress, EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE); + Status = NonCoherentPciIoAllocateBuffer ( + This, + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes), + &AllocAddress, + EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE + ); if (EFI_ERROR (Status)) { goto FreeMapInfo; } + MapInfo->AllocAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)AllocAddress; if (Operation == EfiPciIoOperationBusMasterRead) { gBS->CopyMem (AllocAddress, HostAddress, *NumberOfBytes); } + *DeviceAddress = MapInfo->AllocAddress; } else { MapInfo->AllocAddress = 0; - *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; + *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; // // We are not using a bounce buffer: the mapping is sufficiently @@ -1238,8 +1290,12 @@ NonCoherentPciIoMap ( // may be written back unexpectedly, and clobber the data written to // main memory by the device. // - mCpu->FlushDataCache (mCpu, (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, - *NumberOfBytes, EfiCpuFlushTypeWriteBack); + mCpu->FlushDataCache ( + mCpu, + (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, + *NumberOfBytes, + EfiCpuFlushTypeWriteBack + ); } *Mapping = MapInfo; @@ -1264,8 +1320,8 @@ STATIC EFI_STATUS EFIAPI NonCoherentPciIoUnmap ( - IN EFI_PCI_IO_PROTOCOL *This, - IN VOID *Mapping + IN EFI_PCI_IO_PROTOCOL *This, + IN VOID *Mapping ) { NON_DISCOVERABLE_PCI_DEVICE_MAP_INFO *MapInfo; @@ -1281,12 +1337,18 @@ NonCoherentPciIoUnmap ( // and free the buffer. // if (MapInfo->Operation == EfiPciIoOperationBusMasterWrite) { - gBS->CopyMem (MapInfo->HostAddress, (VOID *)(UINTN)MapInfo->AllocAddress, - MapInfo->NumberOfBytes); + gBS->CopyMem ( + MapInfo->HostAddress, + (VOID *)(UINTN)MapInfo->AllocAddress, + MapInfo->NumberOfBytes + ); } - NonCoherentPciIoFreeBuffer (This, + + NonCoherentPciIoFreeBuffer ( + This, EFI_SIZE_TO_PAGES (MapInfo->NumberOfBytes), - (VOID *)(UINTN)MapInfo->AllocAddress); + (VOID *)(UINTN)MapInfo->AllocAddress + ); } else { // // We are *not* using a bounce buffer: if this is a bus master write, @@ -1294,11 +1356,15 @@ NonCoherentPciIoUnmap ( // data written by the device. // if (MapInfo->Operation == EfiPciIoOperationBusMasterWrite) { - mCpu->FlushDataCache (mCpu, + mCpu->FlushDataCache ( + mCpu, (EFI_PHYSICAL_ADDRESS)(UINTN)MapInfo->HostAddress, - MapInfo->NumberOfBytes, EfiCpuFlushTypeInvalidate); + MapInfo->NumberOfBytes, + EfiCpuFlushTypeInvalidate + ); } } + FreePool (MapInfo); return EFI_SUCCESS; } @@ -1313,7 +1379,7 @@ STATIC EFI_STATUS EFIAPI PciIoFlush ( - IN EFI_PCI_IO_PROTOCOL *This + IN EFI_PCI_IO_PROTOCOL *This ) { return EFI_SUCCESS; @@ -1343,16 +1409,17 @@ PciIoGetLocation ( OUT UINTN *FunctionNumber ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; + NON_DISCOVERABLE_PCI_DEVICE *Dev; - if (SegmentNumber == NULL || - BusNumber == NULL || - DeviceNumber == NULL || - FunctionNumber == NULL) { + if ((SegmentNumber == NULL) || + (BusNumber == NULL) || + (DeviceNumber == NULL) || + (FunctionNumber == NULL)) + { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); *SegmentNumber = 0xff; *BusNumber = Dev->UniqueId >> 5; @@ -1391,10 +1458,10 @@ PciIoAttributes ( OUT UINT64 *Result OPTIONAL ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - BOOLEAN Enable; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + BOOLEAN Enable; - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); if ((Attributes & (~(DEV_SUPPORTED_ATTRIBUTES))) != 0) { return EFI_UNSUPPORTED; @@ -1402,43 +1469,46 @@ PciIoAttributes ( Enable = FALSE; switch (Operation) { - case EfiPciIoAttributeOperationGet: - if (Result == NULL) { - return EFI_INVALID_PARAMETER; - } - *Result = Dev->Attributes; - break; + case EfiPciIoAttributeOperationGet: + if (Result == NULL) { + return EFI_INVALID_PARAMETER; + } - case EfiPciIoAttributeOperationSupported: - if (Result == NULL) { - return EFI_INVALID_PARAMETER; - } - *Result = DEV_SUPPORTED_ATTRIBUTES; - break; + *Result = Dev->Attributes; + break; - case EfiPciIoAttributeOperationEnable: - Attributes |= Dev->Attributes; - case EfiPciIoAttributeOperationSet: - Enable = ((~Dev->Attributes & Attributes) & EFI_PCI_DEVICE_ENABLE) != 0; - Dev->Attributes = Attributes; - break; + case EfiPciIoAttributeOperationSupported: + if (Result == NULL) { + return EFI_INVALID_PARAMETER; + } - case EfiPciIoAttributeOperationDisable: - Dev->Attributes &= ~Attributes; - break; + *Result = DEV_SUPPORTED_ATTRIBUTES; + break; - default: - return EFI_INVALID_PARAMETER; - }; + case EfiPciIoAttributeOperationEnable: + Attributes |= Dev->Attributes; + case EfiPciIoAttributeOperationSet: + Enable = ((~Dev->Attributes & Attributes) & EFI_PCI_DEVICE_ENABLE) != 0; + Dev->Attributes = Attributes; + break; + + case EfiPciIoAttributeOperationDisable: + Dev->Attributes &= ~Attributes; + break; + + default: + return EFI_INVALID_PARAMETER; + } // // If we're setting any of the EFI_PCI_DEVICE_ENABLE bits, perform // the device specific initialization now. // - if (Enable && !Dev->Enabled && Dev->Device->Initialize != NULL) { + if (Enable && !Dev->Enabled && (Dev->Device->Initialize != NULL)) { Dev->Device->Initialize (Dev->Device); Dev->Enabled = TRUE; } + return EFI_SUCCESS; } @@ -1468,23 +1538,23 @@ STATIC EFI_STATUS EFIAPI PciIoGetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINT8 BarIndex, - OUT UINT64 *Supports OPTIONAL, - OUT VOID **Resources OPTIONAL + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT8 BarIndex, + OUT UINT64 *Supports OPTIONAL, + OUT VOID **Resources OPTIONAL ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; - EFI_ACPI_END_TAG_DESCRIPTOR *End; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; + EFI_ACPI_END_TAG_DESCRIPTOR *End; + EFI_STATUS Status; - if (Supports == NULL && Resources == NULL) { + if ((Supports == NULL) && (Resources == NULL)) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Status = GetBarResource (Dev, BarIndex, &BarDesc); if (EFI_ERROR (Status)) { @@ -1499,20 +1569,23 @@ PciIoGetBarAttributes ( } if (Resources != NULL) { - Descriptor = AllocatePool (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + - sizeof (EFI_ACPI_END_TAG_DESCRIPTOR)); + Descriptor = AllocatePool ( + sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR) + ); if (Descriptor == NULL) { return EFI_OUT_OF_RESOURCES; } CopyMem (Descriptor, BarDesc, sizeof *Descriptor); - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) (Descriptor + 1); + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)(Descriptor + 1); End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0; *Resources = Descriptor; } + return EFI_SUCCESS; } @@ -1533,32 +1606,32 @@ STATIC EFI_STATUS EFIAPI PciIoSetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINT64 Attributes, - IN UINT8 BarIndex, - IN OUT UINT64 *Offset, - IN OUT UINT64 *Length + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT64 Attributes, + IN UINT8 BarIndex, + IN OUT UINT64 *Offset, + IN OUT UINT64 *Length ) { - NON_DISCOVERABLE_PCI_DEVICE *Dev; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_PCI_IO_PROTOCOL_WIDTH Width; - UINTN Count; - EFI_STATUS Status; + NON_DISCOVERABLE_PCI_DEVICE *Dev; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_PCI_IO_PROTOCOL_WIDTH Width; + UINTN Count; + EFI_STATUS Status; if ((Attributes & (~DEV_SUPPORTED_ATTRIBUTES)) != 0) { return EFI_UNSUPPORTED; } - if (Offset == NULL || Length == NULL) { + if ((Offset == NULL) || (Length == NULL)) { return EFI_INVALID_PARAMETER; } - Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(This); + Dev = NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO (This); Width = EfiPciIoWidthUint8; - Count = (UINT32) *Length; + Count = (UINT32)*Length; - Status = GetBarResource(Dev, BarIndex, &Desc); + Status = GetBarResource (Dev, BarIndex, &Desc); if (EFI_ERROR (Status)) { return Status; } @@ -1571,13 +1644,13 @@ PciIoSetBarAttributes ( return EFI_UNSUPPORTED; } -STATIC CONST EFI_PCI_IO_PROTOCOL PciIoTemplate = +STATIC CONST EFI_PCI_IO_PROTOCOL PciIoTemplate = { PciIoPollMem, PciIoPollIo, - { PciIoMemRead, PciIoMemWrite }, - { PciIoIoRead, PciIoIoWrite }, - { PciIoPciRead, PciIoPciWrite }, + { PciIoMemRead, PciIoMemWrite }, + { PciIoIoRead, PciIoIoWrite }, + { PciIoPciRead, PciIoPciWrite }, PciIoCopyMem, CoherentPciIoMap, CoherentPciIoUnmap, @@ -1600,11 +1673,11 @@ STATIC CONST EFI_PCI_IO_PROTOCOL PciIoTemplate = **/ VOID InitializePciIoProtocol ( - NON_DISCOVERABLE_PCI_DEVICE *Dev + NON_DISCOVERABLE_PCI_DEVICE *Dev ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - INTN Idx; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + INTN Idx; InitializeListHead (&Dev->UncachedAllocationList); @@ -1612,62 +1685,83 @@ InitializePciIoProtocol ( Dev->ConfigSpace.Hdr.DeviceId = PCI_ID_DEVICE_DONTCARE; // Copy protocol structure - CopyMem(&Dev->PciIo, &PciIoTemplate, sizeof PciIoTemplate); + CopyMem (&Dev->PciIo, &PciIoTemplate, sizeof PciIoTemplate); if (Dev->Device->DmaType == NonDiscoverableDeviceDmaTypeNonCoherent) { - Dev->PciIo.AllocateBuffer = NonCoherentPciIoAllocateBuffer; - Dev->PciIo.FreeBuffer = NonCoherentPciIoFreeBuffer; - Dev->PciIo.Map = NonCoherentPciIoMap; - Dev->PciIo.Unmap = NonCoherentPciIoUnmap; + Dev->PciIo.AllocateBuffer = NonCoherentPciIoAllocateBuffer; + Dev->PciIo.FreeBuffer = NonCoherentPciIoFreeBuffer; + Dev->PciIo.Map = NonCoherentPciIoMap; + Dev->PciIo.Unmap = NonCoherentPciIoUnmap; } if (CompareGuid (Dev->Device->Type, &gEdkiiNonDiscoverableAhciDeviceGuid)) { Dev->ConfigSpace.Hdr.ClassCode[0] = PCI_IF_MASS_STORAGE_AHCI; Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_CLASS_MASS_STORAGE_SATADPA; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_MASS_STORAGE; - Dev->BarOffset = 5; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableEhciDeviceGuid)) { + Dev->BarOffset = 5; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableEhciDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = PCI_IF_EHCI; Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_CLASS_SERIAL_USB; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_SERIAL; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableNvmeDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableNvmeDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = 0x2; // PCI_IF_NVMHCI Dev->ConfigSpace.Hdr.ClassCode[1] = 0x8; // PCI_CLASS_MASS_STORAGE_NVM Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_MASS_STORAGE; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableOhciDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableOhciDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = PCI_IF_OHCI; Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_CLASS_SERIAL_USB; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_SERIAL; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableSdhciDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableSdhciDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = 0x0; // don't care Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_SUBCLASS_SD_HOST_CONTROLLER; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_SYSTEM_PERIPHERAL; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableXhciDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableXhciDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = PCI_IF_XHCI; Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_CLASS_SERIAL_USB; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_SERIAL; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableUhciDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableUhciDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = PCI_IF_UHCI; Dev->ConfigSpace.Hdr.ClassCode[1] = PCI_CLASS_SERIAL_USB; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_SERIAL; - Dev->BarOffset = 0; - } else if (CompareGuid (Dev->Device->Type, - &gEdkiiNonDiscoverableUfsDeviceGuid)) { + Dev->BarOffset = 0; + } else if (CompareGuid ( + Dev->Device->Type, + &gEdkiiNonDiscoverableUfsDeviceGuid + )) + { Dev->ConfigSpace.Hdr.ClassCode[0] = 0x0; // don't care Dev->ConfigSpace.Hdr.ClassCode[1] = 0x9; // UFS controller subclass; Dev->ConfigSpace.Hdr.ClassCode[2] = PCI_CLASS_MASS_STORAGE; - Dev->BarOffset = 0; + Dev->BarOffset = 0; } else { ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER); } @@ -1678,16 +1772,19 @@ InitializePciIoProtocol ( Idx = Dev->BarOffset; for (Desc = Dev->Device->Resources, Dev->BarCount = 0; Desc->Desc != ACPI_END_TAG_DESCRIPTOR; - Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) { - + Desc = (VOID *)((UINT8 *)Desc + Desc->Len + 3)) + { ASSERT (Desc->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR); ASSERT (Desc->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM); - if (Idx >= PCI_MAX_BAR || - (Idx == PCI_MAX_BAR - 1 && Desc->AddrSpaceGranularity == 64)) { - DEBUG ((DEBUG_ERROR, + if ((Idx >= PCI_MAX_BAR) || + ((Idx == PCI_MAX_BAR - 1) && (Desc->AddrSpaceGranularity == 64))) + { + DEBUG (( + DEBUG_ERROR, "%a: resource count exceeds number of emulated BARs\n", - __FUNCTION__)); + __FUNCTION__ + )); ASSERT (FALSE); break; } @@ -1696,9 +1793,11 @@ InitializePciIoProtocol ( Dev->BarCount++; if (Desc->AddrSpaceGranularity == 64) { - Dev->ConfigSpace.Device.Bar[Idx] |= 0x4; + Dev->ConfigSpace.Device.Bar[Idx] |= 0x4; Dev->ConfigSpace.Device.Bar[++Idx] = (UINT32)RShiftU64 ( - Desc->AddrRangeMin, 32); + Desc->AddrRangeMin, + 32 + ); } } } diff --git a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.h b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.h index 3e6df3bebd..41e591e80c 100644 --- a/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.h +++ b/MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceIo.h @@ -24,7 +24,7 @@ #include #include -#define NON_DISCOVERABLE_PCI_DEVICE_SIG SIGNATURE_32 ('P', 'P', 'I', 'D') +#define NON_DISCOVERABLE_PCI_DEVICE_SIG SIGNATURE_32 ('P', 'P', 'I', 'D') #define NON_DISCOVERABLE_PCI_DEVICE_FROM_PCI_IO(PciIoPointer) \ CR (PciIoPointer, NON_DISCOVERABLE_PCI_DEVICE, PciIo, \ @@ -33,74 +33,74 @@ #define DEV_SUPPORTED_ATTRIBUTES \ (EFI_PCI_DEVICE_ENABLE | EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE) -#define PCI_ID_VENDOR_UNKNOWN 0xffff -#define PCI_ID_DEVICE_DONTCARE 0x0000 +#define PCI_ID_VENDOR_UNKNOWN 0xffff +#define PCI_ID_DEVICE_DONTCARE 0x0000 -extern EFI_CPU_ARCH_PROTOCOL *mCpu; +extern EFI_CPU_ARCH_PROTOCOL *mCpu; typedef struct { // // The linked-list next pointer // - LIST_ENTRY List; + LIST_ENTRY List; // // The address of the uncached allocation // - VOID *HostAddress; + VOID *HostAddress; // // The number of pages in the allocation // - UINTN NumPages; + UINTN NumPages; // // The attributes of the allocation // - UINT64 Attributes; + UINT64 Attributes; } NON_DISCOVERABLE_DEVICE_UNCACHED_ALLOCATION; typedef struct { - UINT32 Signature; + UINT32 Signature; // // The bound non-discoverable device protocol instance // - NON_DISCOVERABLE_DEVICE *Device; + NON_DISCOVERABLE_DEVICE *Device; // // The exposed PCI I/O protocol instance. // - EFI_PCI_IO_PROTOCOL PciIo; + EFI_PCI_IO_PROTOCOL PciIo; // // The emulated PCI config space of the device. Only the minimally required // items are assigned. // - PCI_TYPE00 ConfigSpace; + PCI_TYPE00 ConfigSpace; // // The first virtual BAR to assign based on the resources described // by the non-discoverable device. // - UINT32 BarOffset; + UINT32 BarOffset; // // The number of virtual BARs we expose based on the number of // resources // - UINT32 BarCount; + UINT32 BarCount; // // The PCI I/O attributes for this device // - UINT64 Attributes; + UINT64 Attributes; // // Whether this device has been enabled // - BOOLEAN Enabled; + BOOLEAN Enabled; // // Linked list to keep track of uncached allocations performed // on behalf of this device // - LIST_ENTRY UncachedAllocationList; + LIST_ENTRY UncachedAllocationList; // // Unique ID for this device instance: needed so that we can report unique // segment/bus/device number for each device instance. Note that this number // may change when disconnecting/reconnecting the driver. // - UINTN UniqueId; + UINTN UniqueId; } NON_DISCOVERABLE_PCI_DEVICE; /** @@ -111,10 +111,10 @@ typedef struct { **/ VOID InitializePciIoProtocol ( - NON_DISCOVERABLE_PCI_DEVICE *Device + NON_DISCOVERABLE_PCI_DEVICE *Device ); -extern EFI_COMPONENT_NAME_PROTOCOL gComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gComponentName2; +extern EFI_COMPONENT_NAME_PROTOCOL gComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gComponentName2; #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/ComponentName.c index 7ef345eec4..a58646b433 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/ComponentName.c @@ -12,7 +12,7 @@ // // EFI Component Name Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gNvmExpressComponentName = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gNvmExpressComponentName = { NvmExpressComponentNameGetDriverName, NvmExpressComponentNameGetControllerName, "eng" @@ -21,20 +21,20 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gNvmExpressComponentNa // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gNvmExpressComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) NvmExpressComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) NvmExpressComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gNvmExpressComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)NvmExpressComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)NvmExpressComponentNameGetControllerName, "en" }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mNvmExpressDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mNvmExpressDriverNameTable[] = { { "eng;en", L"NVM Express Driver" }, - { NULL, NULL } + { NULL, NULL } }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mNvmExpressControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mNvmExpressControllerNameTable[] = { { "eng;en", L"NVM Express Controller" }, - { NULL, NULL } + { NULL, NULL } }; /** @@ -79,9 +79,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mNvmExpressControllerName EFI_STATUS EFIAPI NvmExpressComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -164,17 +164,17 @@ NvmExpressComponentNameGetDriverName ( EFI_STATUS EFIAPI NvmExpressComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_STATUS Status; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; // // Make sure this driver is currently managing ControllHandle @@ -198,13 +198,14 @@ NvmExpressComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the child context // Status = gBS->OpenProtocol ( ChildHandle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, gNvmExpressDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -212,7 +213,8 @@ NvmExpressComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } - Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (BlockIo); + + Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (BlockIo); ControllerNameTable = Device->ControllerNameTable; } @@ -223,5 +225,4 @@ NvmExpressComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gNvmExpressComponentName) ); - } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c index f60c2fcd79..9d40f67e8e 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c @@ -12,7 +12,7 @@ // // NVM Express Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gNvmExpressDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gNvmExpressDriverBinding = { NvmExpressDriverBindingSupported, NvmExpressDriverBindingStart, NvmExpressDriverBindingStop, @@ -24,7 +24,7 @@ EFI_DRIVER_BINDING_PROTOCOL gNvmExpressDriverBinding = { // // NVM Express EFI Driver Supported EFI Version Protocol Instance // -EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL gNvmExpressDriverSupportedEfiVersion = { +EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL gNvmExpressDriverSupportedEfiVersion = { sizeof (EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL), // Size of Protocol structure. 0 // Version number to be filled at start up. }; @@ -32,7 +32,7 @@ EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL gNvmExpressDriverSupportedEfiVersion = // // Template for NVM Express Pass Thru Mode data structure. // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_NVM_EXPRESS_PASS_THRU_MODE gEfiNvmExpressPassThruMode = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_NVM_EXPRESS_PASS_THRU_MODE gEfiNvmExpressPassThruMode = { EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL | EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_NONBLOCKIO | @@ -56,24 +56,24 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_NVM_EXPRESS_PASS_THRU_MODE gEfiNvmExpressPassT **/ EFI_STATUS EnumerateNvmeDevNamespace ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - UINT32 NamespaceId + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + UINT32 NamespaceId ) { - NVME_ADMIN_NAMESPACE_DATA *NamespaceData; - EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_HANDLE DeviceHandle; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - UINT32 Lbads; - UINT32 Flbas; - UINT32 LbaFmtIdx; - UINT8 Sn[21]; - UINT8 Mn[41]; - VOID *DummyInterface; + NVME_ADMIN_NAMESPACE_DATA *NamespaceData; + EFI_DEVICE_PATH_PROTOCOL *NewDevicePathNode; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_HANDLE DeviceHandle; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + UINT32 Lbads; + UINT32 Flbas; + UINT32 LbaFmtIdx; + UINT8 Sn[21]; + UINT8 Mn[41]; + VOID *DummyInterface; NewDevicePathNode = NULL; DevicePath = NULL; @@ -82,8 +82,8 @@ EnumerateNvmeDevNamespace ( // // Allocate a buffer for Identify Namespace data // - NamespaceData = AllocateZeroPool(sizeof (NVME_ADMIN_NAMESPACE_DATA)); - if(NamespaceData == NULL) { + NamespaceData = AllocateZeroPool (sizeof (NVME_ADMIN_NAMESPACE_DATA)); + if (NamespaceData == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -96,9 +96,10 @@ EnumerateNvmeDevNamespace ( NamespaceId, (VOID *)NamespaceData ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Exit; } + // // Validate Namespace // @@ -108,7 +109,7 @@ EnumerateNvmeDevNamespace ( // // allocate device private data for each discovered namespace // - Device = AllocateZeroPool(sizeof(NVME_DEVICE_PRIVATE_DATA)); + Device = AllocateZeroPool (sizeof (NVME_DEVICE_PRIVATE_DATA)); if (Device == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Exit; @@ -117,9 +118,9 @@ EnumerateNvmeDevNamespace ( // // Initialize SSD namespace instance data // - Device->Signature = NVME_DEVICE_PRIVATE_DATA_SIGNATURE; - Device->NamespaceId = NamespaceId; - Device->NamespaceUuid = NamespaceData->Eui64; + Device->Signature = NVME_DEVICE_PRIVATE_DATA_SIGNATURE; + Device->NamespaceId = NamespaceId; + Device->NamespaceUuid = NamespaceData->Eui64; Device->ControllerHandle = Private->ControllerHandle; Device->DriverBindingHandle = Private->DriverBindingHandle; @@ -128,17 +129,17 @@ EnumerateNvmeDevNamespace ( // // Build BlockIo media structure // - Device->Media.MediaId = 0; - Device->Media.RemovableMedia = FALSE; - Device->Media.MediaPresent = TRUE; + Device->Media.MediaId = 0; + Device->Media.RemovableMedia = FALSE; + Device->Media.MediaPresent = TRUE; Device->Media.LogicalPartition = FALSE; - Device->Media.ReadOnly = FALSE; - Device->Media.WriteCaching = FALSE; - Device->Media.IoAlign = Private->PassThruMode.IoAlign; + Device->Media.ReadOnly = FALSE; + Device->Media.WriteCaching = FALSE; + Device->Media.IoAlign = Private->PassThruMode.IoAlign; - Flbas = NamespaceData->Flbas; - LbaFmtIdx = Flbas & 0xF; - Lbads = NamespaceData->LbaFormat[LbaFmtIdx].Lbads; + Flbas = NamespaceData->Flbas; + LbaFmtIdx = Flbas & 0xF; + Lbads = NamespaceData->LbaFormat[LbaFmtIdx].Lbads; Device->Media.BlockSize = (UINT32)1 << Lbads; Device->Media.LastBlock = NamespaceData->Nsze - 1; @@ -148,21 +149,21 @@ EnumerateNvmeDevNamespace ( // // Create BlockIo Protocol instance // - Device->BlockIo.Revision = EFI_BLOCK_IO_PROTOCOL_REVISION2; - Device->BlockIo.Media = &Device->Media; - Device->BlockIo.Reset = NvmeBlockIoReset; - Device->BlockIo.ReadBlocks = NvmeBlockIoReadBlocks; - Device->BlockIo.WriteBlocks = NvmeBlockIoWriteBlocks; - Device->BlockIo.FlushBlocks = NvmeBlockIoFlushBlocks; + Device->BlockIo.Revision = EFI_BLOCK_IO_PROTOCOL_REVISION2; + Device->BlockIo.Media = &Device->Media; + Device->BlockIo.Reset = NvmeBlockIoReset; + Device->BlockIo.ReadBlocks = NvmeBlockIoReadBlocks; + Device->BlockIo.WriteBlocks = NvmeBlockIoWriteBlocks; + Device->BlockIo.FlushBlocks = NvmeBlockIoFlushBlocks; // // Create BlockIo2 Protocol instance // - Device->BlockIo2.Media = &Device->Media; - Device->BlockIo2.Reset = NvmeBlockIoResetEx; - Device->BlockIo2.ReadBlocksEx = NvmeBlockIoReadBlocksEx; - Device->BlockIo2.WriteBlocksEx = NvmeBlockIoWriteBlocksEx; - Device->BlockIo2.FlushBlocksEx = NvmeBlockIoFlushBlocksEx; + Device->BlockIo2.Media = &Device->Media; + Device->BlockIo2.Reset = NvmeBlockIoResetEx; + Device->BlockIo2.ReadBlocksEx = NvmeBlockIoReadBlocksEx; + Device->BlockIo2.WriteBlocksEx = NvmeBlockIoWriteBlocksEx; + Device->BlockIo2.FlushBlocksEx = NvmeBlockIoFlushBlocksEx; InitializeListHead (&Device->AsyncQueue); // @@ -186,7 +187,7 @@ EnumerateNvmeDevNamespace ( &NewDevicePathNode ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Exit; } @@ -199,10 +200,10 @@ EnumerateNvmeDevNamespace ( goto Exit; } - DeviceHandle = NULL; + DeviceHandle = NULL; RemainingDevicePath = DevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) { + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (RemainingDevicePath)) { Status = EFI_ALREADY_STARTED; FreePool (DevicePath); goto Exit; @@ -228,7 +229,7 @@ EnumerateNvmeDevNamespace ( NULL ); - if(EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Exit; } @@ -242,7 +243,7 @@ EnumerateNvmeDevNamespace ( EFI_NATIVE_INTERFACE, &Device->StorageSecurity ); - if(EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( Device->DeviceHandle, &gEfiDevicePathProtocolGuid, @@ -262,7 +263,7 @@ EnumerateNvmeDevNamespace ( gBS->OpenProtocol ( Private->ControllerHandle, &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &DummyInterface, + (VOID **)&DummyInterface, Private->DriverBindingHandle, Device->DeviceHandle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -304,7 +305,7 @@ EnumerateNvmeDevNamespace ( } Exit: - if(NamespaceData != NULL) { + if (NamespaceData != NULL) { FreePool (NamespaceData); } @@ -312,12 +313,14 @@ Exit: FreePool (NewDevicePathNode); } - if(EFI_ERROR(Status) && (Device != NULL) && (Device->DevicePath != NULL)) { + if (EFI_ERROR (Status) && (Device != NULL) && (Device->DevicePath != NULL)) { FreePool (Device->DevicePath); } - if(EFI_ERROR(Status) && (Device != NULL)) { + + if (EFI_ERROR (Status) && (Device != NULL)) { FreePool (Device); } + return Status; } @@ -333,15 +336,15 @@ Exit: **/ EFI_STATUS DiscoverAllNamespaces ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINT32 NamespaceId; - EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *Passthru; + EFI_STATUS Status; + UINT32 NamespaceId; + EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *Passthru; - NamespaceId = 0xFFFFFFFF; - Passthru = &Private->Passthru; + NamespaceId = 0xFFFFFFFF; + Passthru = &Private->Passthru; while (TRUE) { Status = Passthru->GetNextNamespace ( @@ -358,7 +361,7 @@ DiscoverAllNamespaces ( NamespaceId ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } } @@ -382,25 +385,25 @@ DiscoverAllNamespaces ( **/ EFI_STATUS UnregisterNvmeNamespace ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *StorageSecurity; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; - VOID *DummyInterface; + EFI_STATUS Status; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *StorageSecurity; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; + VOID *DummyInterface; BlockIo = NULL; Status = gBS->OpenProtocol ( Handle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -409,7 +412,7 @@ UnregisterNvmeNamespace ( return Status; } - Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (BlockIo); + Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (BlockIo); // // Wait for the device's asynchronous I/O queue to become empty. @@ -457,7 +460,7 @@ UnregisterNvmeNamespace ( gBS->OpenProtocol ( Controller, &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &DummyInterface, + (VOID **)&DummyInterface, This->DriverBindingHandle, Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -471,7 +474,7 @@ UnregisterNvmeNamespace ( Status = gBS->OpenProtocol ( Handle, &gEfiStorageSecurityCommandProtocolGuid, - (VOID **) &StorageSecurity, + (VOID **)&StorageSecurity, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -485,18 +488,18 @@ UnregisterNvmeNamespace ( ); if (EFI_ERROR (Status)) { gBS->OpenProtocol ( - Controller, - &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &DummyInterface, - This->DriverBindingHandle, - Handle, - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiNvmExpressPassThruProtocolGuid, + (VOID **)&DummyInterface, + This->DriverBindingHandle, + Handle, + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); return Status; } } - if(Device->DevicePath != NULL) { + if (Device->DevicePath != NULL) { FreePool (Device->DevicePath); } @@ -520,25 +523,25 @@ UnregisterNvmeNamespace ( VOID EFIAPI ProcessAsyncTaskList ( - IN EFI_EVENT Event, - IN VOID* Context + IN EFI_EVENT Event, + IN VOID *Context ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_PCI_IO_PROTOCOL *PciIo; - NVME_CQ *Cq; - UINT16 QueueId; - UINT32 Data; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - NVME_PASS_THRU_ASYNC_REQ *AsyncRequest; - NVME_BLKIO2_SUBTASK *Subtask; - NVME_BLKIO2_REQUEST *BlkIo2Request; - EFI_BLOCK_IO2_TOKEN *Token; - BOOLEAN HasNewItem; - EFI_STATUS Status; - - Private = (NVME_CONTROLLER_PRIVATE_DATA*)Context; + NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_PCI_IO_PROTOCOL *PciIo; + NVME_CQ *Cq; + UINT16 QueueId; + UINT32 Data; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + NVME_PASS_THRU_ASYNC_REQ *AsyncRequest; + NVME_BLKIO2_SUBTASK *Subtask; + NVME_BLKIO2_REQUEST *BlkIo2Request; + EFI_BLOCK_IO2_TOKEN *Token; + BOOLEAN HasNewItem; + EFI_STATUS Status; + + Private = (NVME_CONTROLLER_PRIVATE_DATA *)Context; QueueId = 2; Cq = Private->CqBuffer[QueueId] + Private->CqHdbl[QueueId].Cqh; HasNewItem = FALSE; @@ -549,7 +552,8 @@ ProcessAsyncTaskList ( // for (Link = GetFirstNode (&Private->UnsubmittedSubtasks); !IsNull (&Private->UnsubmittedSubtasks, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Private->UnsubmittedSubtasks, Link); Subtask = NVME_BLKIO2_SUBTASK_FROM_LINK (Link); BlkIo2Request = Subtask->BlockIo2Request; @@ -563,7 +567,8 @@ ProcessAsyncTaskList ( if (Token->TransactionStatus != EFI_SUCCESS) { if (IsListEmpty (&BlkIo2Request->SubtasksQueue) && BlkIo2Request->LastSubtaskSubmitted && - (BlkIo2Request->UnsubmittedSubtaskNum == 0)) { + (BlkIo2Request->UnsubmittedSubtaskNum == 0)) + { // // Remove the BlockIo2 request from the device asynchronous queue. // @@ -594,7 +599,8 @@ ProcessAsyncTaskList ( Token->TransactionStatus = EFI_DEVICE_ERROR; if (IsListEmpty (&BlkIo2Request->SubtasksQueue) && - Subtask->IsLast) { + Subtask->IsLast) + { // // Remove the BlockIo2 request from the device asynchronous queue. // @@ -625,8 +631,9 @@ ProcessAsyncTaskList ( // for (Link = GetFirstNode (&Private->AsyncPassThruQueue); !IsNull (&Private->AsyncPassThruQueue, Link); - Link = NextLink) { - NextLink = GetNextNode (&Private->AsyncPassThruQueue, Link); + Link = NextLink) + { + NextLink = GetNextNode (&Private->AsyncPassThruQueue, Link); AsyncRequest = NVME_PASS_THRU_ASYNC_REQ_FROM_THIS (Link); if (AsyncRequest->CommandId == Cq->Cid) { // @@ -636,7 +643,7 @@ ProcessAsyncTaskList ( CopyMem ( AsyncRequest->Packet->NvmeCompletion, Cq, - sizeof(EFI_NVM_EXPRESS_COMPLETION) + sizeof (EFI_NVM_EXPRESS_COMPLETION) ); // @@ -645,12 +652,15 @@ ProcessAsyncTaskList ( if (AsyncRequest->MapData != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapData); } + if (AsyncRequest->MapMeta != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapMeta); } + if (AsyncRequest->MapPrpList != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapPrpList); } + if (AsyncRequest->PrpListHost != NULL) { PciIo->FreeBuffer ( PciIo, @@ -674,19 +684,19 @@ ProcessAsyncTaskList ( Private->CqHdbl[QueueId].Cqh++; if (Private->CqHdbl[QueueId].Cqh > MIN (NVME_ASYNC_CCQ_SIZE, Private->Cap.Mqes)) { Private->CqHdbl[QueueId].Cqh = 0; - Private->Pt[QueueId] ^= 1; + Private->Pt[QueueId] ^= 1; } Cq = Private->CqBuffer[QueueId] + Private->CqHdbl[QueueId].Cqh; } if (HasNewItem) { - Data = ReadUnaligned32 ((UINT32*)&Private->CqHdbl[QueueId]); + Data = ReadUnaligned32 ((UINT32 *)&Private->CqHdbl[QueueId]); PciIo->Mem.Write ( PciIo, EfiPciIoWidthUint32, NVME_BAR, - NVME_CQHDBL_OFFSET(QueueId, Private->Cap.Dstrd), + NVME_CQHDBL_OFFSET (QueueId, Private->Cap.Dstrd), 1, &Data ); @@ -766,8 +776,9 @@ NvmExpressDriverBindingSupported ( if ((DevicePathNode.DevPath->Type != MESSAGING_DEVICE_PATH) || (DevicePathNode.DevPath->SubType != MSG_NVME_NAMESPACE_DP) || - (DevicePathNodeLength(DevicePathNode.DevPath) != sizeof(NVME_NAMESPACE_DEVICE_PATH))) { - return EFI_UNSUPPORTED; + (DevicePathNodeLength (DevicePathNode.DevPath) != sizeof (NVME_NAMESPACE_DEVICE_PATH))) + { + return EFI_UNSUPPORTED; } } } @@ -778,7 +789,7 @@ NvmExpressDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -807,7 +818,7 @@ NvmExpressDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -853,7 +864,6 @@ Done: return Status; } - /** Starts a device controller or a bus controller. @@ -915,7 +925,7 @@ NvmExpressDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -927,7 +937,7 @@ NvmExpressDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -965,14 +975,14 @@ NvmExpressDriverBindingStart ( AllocateAnyPages, EfiBootServicesData, 6, - (VOID**)&Private->Buffer, + (VOID **)&Private->Buffer, 0 ); if (EFI_ERROR (Status)) { goto Exit; } - Bytes = EFI_PAGES_TO_SIZE (6); + Bytes = EFI_PAGES_TO_SIZE (6); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, @@ -988,7 +998,7 @@ NvmExpressDriverBindingStart ( Private->BufferPciAddr = (UINT8 *)(UINTN)MappedAddr; - Private->Signature = NVME_CONTROLLER_PRIVATE_DATA_SIGNATURE; + Private->Signature = NVME_CONTROLLER_PRIVATE_DATA_SIGNATURE; Private->ControllerHandle = Controller; Private->ImageHandle = This->DriverBindingHandle; Private->DriverBindingHandle = This->DriverBindingHandle; @@ -1004,7 +1014,7 @@ NvmExpressDriverBindingStart ( InitializeListHead (&Private->UnsubmittedSubtasks); Status = NvmeControllerInit (Private); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Exit; } @@ -1046,7 +1056,7 @@ NvmExpressDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &Passthru, + (VOID **)&Passthru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1065,7 +1075,6 @@ NvmExpressDriverBindingStart ( Status = DiscoverAllNamespaces ( Private ); - } else if (!IsDevicePathEnd (RemainingDevicePath)) { // // Enumerate the specified NVME namespace @@ -1127,7 +1136,6 @@ Exit: return Status; } - /** Stops a device controller or a bus controller. @@ -1157,10 +1165,10 @@ Exit: EFI_STATUS EFIAPI NvmExpressDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -1175,7 +1183,7 @@ NvmExpressDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &PassThru, + (VOID **)&PassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1201,11 +1209,11 @@ NvmExpressDriverBindingStop ( } gBS->UninstallMultipleProtocolInterfaces ( - Controller, - &gEfiNvmExpressPassThruProtocolGuid, - PassThru, - NULL - ); + Controller, + &gEfiNvmExpressPassThruProtocolGuid, + PassThru, + NULL + ); if (Private->TimerEvent != NULL) { gBS->CloseEvent (Private->TimerEvent); @@ -1224,17 +1232,17 @@ NvmExpressDriverBindingStop ( } gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); NvmeUnregisterShutdownNotification (); @@ -1272,15 +1280,15 @@ NvmExpressDriverBindingStop ( EFI_STATUS EFIAPI NvmExpressUnload ( - IN EFI_HANDLE ImageHandle + IN EFI_HANDLE ImageHandle ) { - EFI_STATUS Status; - EFI_HANDLE *DeviceHandleBuffer; - UINTN DeviceHandleCount; - UINTN Index; - EFI_COMPONENT_NAME_PROTOCOL *ComponentName; - EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; + EFI_STATUS Status; + EFI_HANDLE *DeviceHandleBuffer; + UINTN DeviceHandleCount; + UINTN Index; + EFI_COMPONENT_NAME_PROTOCOL *ComponentName; + EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; // // Get the list of the device handles managed by this driver. @@ -1289,13 +1297,13 @@ NvmExpressUnload ( // those protocols installed at image handle. // DeviceHandleBuffer = NULL; - Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiNvmExpressPassThruProtocolGuid, - NULL, - &DeviceHandleCount, - &DeviceHandleBuffer - ); + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiNvmExpressPassThruProtocolGuid, + NULL, + &DeviceHandleCount, + &DeviceHandleBuffer + ); if (!EFI_ERROR (Status)) { // @@ -1342,7 +1350,7 @@ NvmExpressUnload ( Status = gBS->HandleProtocol ( ImageHandle, &gEfiComponentNameProtocolGuid, - (VOID **) &ComponentName + (VOID **)&ComponentName ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( @@ -1355,7 +1363,7 @@ NvmExpressUnload ( Status = gBS->HandleProtocol ( ImageHandle, &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName2 + (VOID **)&ComponentName2 ); if (!EFI_ERROR (Status)) { gBS->UninstallProtocolInterface ( @@ -1374,6 +1382,7 @@ EXIT: if (DeviceHandleBuffer != NULL) { gBS->FreePool (DeviceHandleBuffer); } + return Status; } @@ -1394,7 +1403,7 @@ NvmExpressDriverEntry ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, @@ -1411,12 +1420,12 @@ NvmExpressDriverEntry ( // EFI drivers that are on PCI and other plug in cards. // gNvmExpressDriverSupportedEfiVersion.FirmwareVersion = 0x00020028; - Status = gBS->InstallMultipleProtocolInterfaces ( - &ImageHandle, - &gEfiDriverSupportedEfiVersionProtocolGuid, - &gNvmExpressDriverSupportedEfiVersion, - NULL - ); + Status = gBS->InstallMultipleProtocolInterfaces ( + &ImageHandle, + &gEfiDriverSupportedEfiVersionProtocolGuid, + &gNvmExpressDriverSupportedEfiVersion, + NULL + ); ASSERT_EFI_ERROR (Status); return Status; } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.h b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.h index 45a1447500..4c26b2e1b4 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.h @@ -41,8 +41,8 @@ #include #include -typedef struct _NVME_CONTROLLER_PRIVATE_DATA NVME_CONTROLLER_PRIVATE_DATA; -typedef struct _NVME_DEVICE_PRIVATE_DATA NVME_DEVICE_PRIVATE_DATA; +typedef struct _NVME_CONTROLLER_PRIVATE_DATA NVME_CONTROLLER_PRIVATE_DATA; +typedef struct _NVME_DEVICE_PRIVATE_DATA NVME_DEVICE_PRIVATE_DATA; #include "NvmExpressBlockIo.h" #include "NvmExpressDiskInfo.h" @@ -53,67 +53,67 @@ extern EFI_COMPONENT_NAME_PROTOCOL gNvmExpressComponentName; extern EFI_COMPONENT_NAME2_PROTOCOL gNvmExpressComponentName2; extern EFI_DRIVER_SUPPORTED_EFI_VERSION_PROTOCOL gNvmExpressDriverSupportedEfiVersion; -#define PCI_CLASS_MASS_STORAGE_NVM 0x08 // mass storage sub-class non-volatile memory. -#define PCI_IF_NVMHCI 0x02 // mass storage programming interface NVMHCI. +#define PCI_CLASS_MASS_STORAGE_NVM 0x08 // mass storage sub-class non-volatile memory. +#define PCI_IF_NVMHCI 0x02 // mass storage programming interface NVMHCI. -#define NVME_ASQ_SIZE 1 // Number of admin submission queue entries, which is 0-based -#define NVME_ACQ_SIZE 1 // Number of admin completion queue entries, which is 0-based +#define NVME_ASQ_SIZE 1 // Number of admin submission queue entries, which is 0-based +#define NVME_ACQ_SIZE 1 // Number of admin completion queue entries, which is 0-based -#define NVME_CSQ_SIZE 1 // Number of I/O submission queue entries, which is 0-based -#define NVME_CCQ_SIZE 1 // Number of I/O completion queue entries, which is 0-based +#define NVME_CSQ_SIZE 1 // Number of I/O submission queue entries, which is 0-based +#define NVME_CCQ_SIZE 1 // Number of I/O completion queue entries, which is 0-based // // Number of asynchronous I/O submission queue entries, which is 0-based. // The asynchronous I/O submission queue size is 4kB in total. // -#define NVME_ASYNC_CSQ_SIZE 63 +#define NVME_ASYNC_CSQ_SIZE 63 // // Number of asynchronous I/O completion queue entries, which is 0-based. // The asynchronous I/O completion queue size is 4kB in total. // -#define NVME_ASYNC_CCQ_SIZE 255 +#define NVME_ASYNC_CCQ_SIZE 255 -#define NVME_MAX_QUEUES 3 // Number of queues supported by the driver +#define NVME_MAX_QUEUES 3 // Number of queues supported by the driver -#define NVME_CONTROLLER_ID 0 +#define NVME_CONTROLLER_ID 0 // // Time out value for Nvme transaction execution // -#define NVME_GENERIC_TIMEOUT EFI_TIMER_PERIOD_SECONDS (5) +#define NVME_GENERIC_TIMEOUT EFI_TIMER_PERIOD_SECONDS (5) // // Nvme async transfer timer interval, set by experience. // -#define NVME_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS (1) +#define NVME_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS (1) // // Unique signature for private data structure. // -#define NVME_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('N','V','M','E') +#define NVME_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('N','V','M','E') // // Nvme private data structure. // struct _NVME_CONTROLLER_PRIVATE_DATA { - UINT32 Signature; + UINT32 Signature; - EFI_HANDLE ControllerHandle; - EFI_HANDLE ImageHandle; - EFI_HANDLE DriverBindingHandle; + EFI_HANDLE ControllerHandle; + EFI_HANDLE ImageHandle; + EFI_HANDLE DriverBindingHandle; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 PciAttributes; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 PciAttributes; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_NVM_EXPRESS_PASS_THRU_MODE PassThruMode; - EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL Passthru; + EFI_NVM_EXPRESS_PASS_THRU_MODE PassThruMode; + EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL Passthru; // // pointer to identify controller data // - NVME_ADMIN_CONTROLLER_DATA *ControllerData; + NVME_ADMIN_CONTROLLER_DATA *ControllerData; // // 6 x 4kB aligned buffers will be carved out of this buffer. @@ -124,45 +124,45 @@ struct _NVME_CONTROLLER_PRIVATE_DATA { // 5th 4kB boundary is the start of I/O submission queue #2. // 6th 4kB boundary is the start of I/O completion queue #2. // - UINT8 *Buffer; - UINT8 *BufferPciAddr; + UINT8 *Buffer; + UINT8 *BufferPciAddr; // // Pointers to 4kB aligned submission & completion queues. // - NVME_SQ *SqBuffer[NVME_MAX_QUEUES]; - NVME_CQ *CqBuffer[NVME_MAX_QUEUES]; - NVME_SQ *SqBufferPciAddr[NVME_MAX_QUEUES]; - NVME_CQ *CqBufferPciAddr[NVME_MAX_QUEUES]; + NVME_SQ *SqBuffer[NVME_MAX_QUEUES]; + NVME_CQ *CqBuffer[NVME_MAX_QUEUES]; + NVME_SQ *SqBufferPciAddr[NVME_MAX_QUEUES]; + NVME_CQ *CqBufferPciAddr[NVME_MAX_QUEUES]; // // Submission and completion queue indices. // - NVME_SQTDBL SqTdbl[NVME_MAX_QUEUES]; - NVME_CQHDBL CqHdbl[NVME_MAX_QUEUES]; - UINT16 AsyncSqHead; + NVME_SQTDBL SqTdbl[NVME_MAX_QUEUES]; + NVME_CQHDBL CqHdbl[NVME_MAX_QUEUES]; + UINT16 AsyncSqHead; // // Flag to indicate internal IO queue creation. // - BOOLEAN CreateIoQueue; + BOOLEAN CreateIoQueue; - UINT8 Pt[NVME_MAX_QUEUES]; - UINT16 Cid[NVME_MAX_QUEUES]; + UINT8 Pt[NVME_MAX_QUEUES]; + UINT16 Cid[NVME_MAX_QUEUES]; // // Nvme controller capabilities // - NVME_CAP Cap; + NVME_CAP Cap; - VOID *Mapping; + VOID *Mapping; // // For Non-blocking operations. // - EFI_EVENT TimerEvent; - LIST_ENTRY AsyncPassThruQueue; - LIST_ENTRY UnsubmittedSubtasks; + EFI_EVENT TimerEvent; + LIST_ENTRY AsyncPassThruQueue; + LIST_ENTRY UnsubmittedSubtasks; }; #define NVME_CONTROLLER_PRIVATE_DATA_FROM_PASS_THRU(a) \ @@ -175,7 +175,7 @@ struct _NVME_CONTROLLER_PRIVATE_DATA { // // Unique signature for private data structure. // -#define NVME_DEVICE_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X','S','S','D') +#define NVME_DEVICE_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('X','S','S','D') // // Nvme device private data structure @@ -208,7 +208,6 @@ struct _NVME_DEVICE_PRIVATE_DATA { NVME_ADMIN_NAMESPACE_DATA NamespaceData; NVME_CONTROLLER_PRIVATE_DATA *Controller; - }; // @@ -235,7 +234,7 @@ struct _NVME_DEVICE_PRIVATE_DATA { NVME_DEVICE_PRIVATE_DATA_SIGNATURE \ ) -#define NVME_DEVICE_PRIVATE_DATA_FROM_STORAGE_SECURITY(a)\ +#define NVME_DEVICE_PRIVATE_DATA_FROM_STORAGE_SECURITY(a) \ CR (a, \ NVME_DEVICE_PRIVATE_DATA, \ StorageSecurity, \ @@ -245,38 +244,38 @@ struct _NVME_DEVICE_PRIVATE_DATA { // // Nvme block I/O 2 request. // -#define NVME_BLKIO2_REQUEST_SIGNATURE SIGNATURE_32 ('N', 'B', '2', 'R') +#define NVME_BLKIO2_REQUEST_SIGNATURE SIGNATURE_32 ('N', 'B', '2', 'R') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; + UINT32 Signature; + LIST_ENTRY Link; - EFI_BLOCK_IO2_TOKEN *Token; - UINTN UnsubmittedSubtaskNum; - BOOLEAN LastSubtaskSubmitted; + EFI_BLOCK_IO2_TOKEN *Token; + UINTN UnsubmittedSubtaskNum; + BOOLEAN LastSubtaskSubmitted; // // The queue for Nvme read/write sub-tasks of a BlockIo2 request. // - LIST_ENTRY SubtasksQueue; + LIST_ENTRY SubtasksQueue; } NVME_BLKIO2_REQUEST; #define NVME_BLKIO2_REQUEST_FROM_LINK(a) \ CR (a, NVME_BLKIO2_REQUEST, Link, NVME_BLKIO2_REQUEST_SIGNATURE) -#define NVME_BLKIO2_SUBTASK_SIGNATURE SIGNATURE_32 ('N', 'B', '2', 'S') +#define NVME_BLKIO2_SUBTASK_SIGNATURE SIGNATURE_32 ('N', 'B', '2', 'S') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; + UINT32 Signature; + LIST_ENTRY Link; - BOOLEAN IsLast; - UINT32 NamespaceId; - EFI_EVENT Event; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; + BOOLEAN IsLast; + UINT32 NamespaceId; + EFI_EVENT Event; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; // // The BlockIo2 request this subtask belongs to // - NVME_BLKIO2_REQUEST *BlockIo2Request; + NVME_BLKIO2_REQUEST *BlockIo2Request; } NVME_BLKIO2_SUBTASK; #define NVME_BLKIO2_SUBTASK_FROM_LINK(a) \ @@ -285,20 +284,20 @@ typedef struct { // // Nvme asynchronous passthru request. // -#define NVME_PASS_THRU_ASYNC_REQ_SIG SIGNATURE_32 ('N', 'P', 'A', 'R') +#define NVME_PASS_THRU_ASYNC_REQ_SIG SIGNATURE_32 ('N', 'P', 'A', 'R') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet; - UINT16 CommandId; - VOID *MapPrpList; - UINTN PrpListNo; - VOID *PrpListHost; - VOID *MapData; - VOID *MapMeta; - EFI_EVENT CallerEvent; + UINT32 Signature; + LIST_ENTRY Link; + + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet; + UINT16 CommandId; + VOID *MapPrpList; + UINTN PrpListNo; + VOID *PrpListHost; + VOID *MapData; + VOID *MapMeta; + EFI_EVENT CallerEvent; } NVME_PASS_THRU_ASYNC_REQ; #define NVME_PASS_THRU_ASYNC_REQ_FROM_THIS(a) \ @@ -426,11 +425,11 @@ NvmExpressComponentNameGetDriverName ( EFI_STATUS EFIAPI NvmExpressComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -555,10 +554,10 @@ NvmExpressDriverBindingStart ( EFI_STATUS EFIAPI NvmExpressDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -594,10 +593,10 @@ NvmExpressDriverBindingStop ( EFI_STATUS EFIAPI NvmExpressPassThru ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ); /** @@ -636,8 +635,8 @@ NvmExpressPassThru ( EFI_STATUS EFIAPI NvmExpressGetNextNamespace ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN OUT UINT32 *NamespaceId + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN OUT UINT32 *NamespaceId ); /** @@ -667,9 +666,9 @@ NvmExpressGetNextNamespace ( EFI_STATUS EFIAPI NvmExpressGetNamespace ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT32 *NamespaceId + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT32 *NamespaceId ); /** @@ -706,9 +705,9 @@ NvmExpressGetNamespace ( EFI_STATUS EFIAPI NvmExpressBuildDevicePath ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN UINT32 NamespaceId, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN UINT32 NamespaceId, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -719,7 +718,7 @@ NvmExpressBuildDevicePath ( **/ VOID NvmeDumpStatus ( - IN NVME_CQ *Cq + IN NVME_CQ *Cq ); /** diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c index c63a6537ac..b33c903412 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c @@ -23,27 +23,27 @@ **/ EFI_STATUS ReadSectors ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN UINT64 Buffer, - IN UINT64 Lba, - IN UINT32 Blocks + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN UINT64 Buffer, + IN UINT64 Lba, + IN UINT32 Blocks ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 Bytes; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - UINT32 BlockSize; - - Private = Device->Controller; - BlockSize = Device->Media.BlockSize; - Bytes = Blocks * BlockSize; - - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 Bytes; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + UINT32 BlockSize; + + Private = Device->Controller; + BlockSize = Device->Media.BlockSize; + Bytes = Blocks * BlockSize; + + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; @@ -57,7 +57,7 @@ ReadSectors ( CommandPacket.QueueType = NVME_IO_QUEUE; CommandPacket.NvmeCmd->Cdw10 = (UINT32)Lba; - CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64(Lba, 32); + CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64 (Lba, 32); CommandPacket.NvmeCmd->Cdw12 = (Blocks - 1) & 0xFFFF; CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID | CDW12_VALID; @@ -86,41 +86,41 @@ ReadSectors ( **/ EFI_STATUS WriteSectors ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN UINT64 Buffer, - IN UINT64 Lba, - IN UINT32 Blocks + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN UINT64 Buffer, + IN UINT64 Lba, + IN UINT32 Blocks ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - UINT32 Bytes; - UINT32 BlockSize; - - Private = Device->Controller; - BlockSize = Device->Media.BlockSize; - Bytes = Blocks * BlockSize; - - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + UINT32 Bytes; + UINT32 BlockSize; + + Private = Device->Controller; + BlockSize = Device->Media.BlockSize; + Bytes = Blocks * BlockSize; + + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; CommandPacket.NvmeCmd->Cdw0.Opcode = NVME_IO_WRITE_OPC; - CommandPacket.NvmeCmd->Nsid = Device->NamespaceId; - CommandPacket.TransferBuffer = (VOID *)(UINTN)Buffer; + CommandPacket.NvmeCmd->Nsid = Device->NamespaceId; + CommandPacket.TransferBuffer = (VOID *)(UINTN)Buffer; CommandPacket.TransferLength = Bytes; CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; CommandPacket.QueueType = NVME_IO_QUEUE; CommandPacket.NvmeCmd->Cdw10 = (UINT32)Lba; - CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64(Lba, 32); + CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64 (Lba, 32); // // Set Force Unit Access bit (bit 30) to use write-through behaviour // @@ -155,19 +155,19 @@ WriteSectors ( **/ EFI_STATUS NvmeRead ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - OUT VOID *Buffer, - IN UINT64 Lba, - IN UINTN Blocks + IN NVME_DEVICE_PRIVATE_DATA *Device, + OUT VOID *Buffer, + IN UINT64 Lba, + IN UINTN Blocks ) { - EFI_STATUS Status; - UINT32 BlockSize; - NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 MaxTransferBlocks; - UINTN OrginalBlocks; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + EFI_STATUS Status; + UINT32 BlockSize; + NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 MaxTransferBlocks; + UINTN OrginalBlocks; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; // // Wait for the device's asynchronous I/O queue to become empty. @@ -207,14 +207,22 @@ NvmeRead ( Blocks = 0; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { break; } } - DEBUG ((DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " - "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", __FUNCTION__, Lba, - (UINT64)OrginalBlocks, (UINT64)Blocks, BlockSize, Status)); + DEBUG (( + DEBUG_BLKIO, + "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " + "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", + __FUNCTION__, + Lba, + (UINT64)OrginalBlocks, + (UINT64)Blocks, + BlockSize, + Status + )); return Status; } @@ -233,19 +241,19 @@ NvmeRead ( **/ EFI_STATUS NvmeWrite ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN VOID *Buffer, - IN UINT64 Lba, - IN UINTN Blocks + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN VOID *Buffer, + IN UINT64 Lba, + IN UINTN Blocks ) { - EFI_STATUS Status; - UINT32 BlockSize; - NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 MaxTransferBlocks; - UINTN OrginalBlocks; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + EFI_STATUS Status; + UINT32 BlockSize; + NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 MaxTransferBlocks; + UINTN OrginalBlocks; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; // // Wait for the device's asynchronous I/O queue to become empty. @@ -285,14 +293,22 @@ NvmeWrite ( Blocks = 0; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { break; } } - DEBUG ((DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " - "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", __FUNCTION__, Lba, - (UINT64)OrginalBlocks, (UINT64)Blocks, BlockSize, Status)); + DEBUG (( + DEBUG_BLKIO, + "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " + "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", + __FUNCTION__, + Lba, + (UINT64)OrginalBlocks, + (UINT64)Blocks, + BlockSize, + Status + )); return Status; } @@ -308,28 +324,28 @@ NvmeWrite ( **/ EFI_STATUS NvmeFlush ( - IN NVME_DEVICE_PRIVATE_DATA *Device + IN NVME_DEVICE_PRIVATE_DATA *Device ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; + NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; Private = Device->Controller; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; CommandPacket.NvmeCmd->Cdw0.Opcode = NVME_IO_FLUSH_OPC; - CommandPacket.NvmeCmd->Nsid = Device->NamespaceId; - CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; - CommandPacket.QueueType = NVME_IO_QUEUE; + CommandPacket.NvmeCmd->Nsid = Device->NamespaceId; + CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; + CommandPacket.QueueType = NVME_IO_QUEUE; Status = Private->Passthru.PassThru ( &Private->Passthru, @@ -352,19 +368,19 @@ NvmeFlush ( VOID EFIAPI AsyncIoCallback ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - NVME_BLKIO2_SUBTASK *Subtask; - NVME_BLKIO2_REQUEST *Request; - NVME_CQ *Completion; - EFI_BLOCK_IO2_TOKEN *Token; + NVME_BLKIO2_SUBTASK *Subtask; + NVME_BLKIO2_REQUEST *Request; + NVME_CQ *Completion; + EFI_BLOCK_IO2_TOKEN *Token; gBS->CloseEvent (Event); - Subtask = (NVME_BLKIO2_SUBTASK *) Context; - Completion = (NVME_CQ *) Subtask->CommandPacket->NvmeCompletion; + Subtask = (NVME_BLKIO2_SUBTASK *)Context; + Completion = (NVME_CQ *)Subtask->CommandPacket->NvmeCompletion; Request = Subtask->BlockIo2Request; Token = Request->Token; @@ -379,9 +395,9 @@ AsyncIoCallback ( // // Dump completion entry status for debugging. // - DEBUG_CODE_BEGIN(); - NvmeDumpStatus (Completion); - DEBUG_CODE_END(); + DEBUG_CODE_BEGIN (); + NvmeDumpStatus (Completion); + DEBUG_CODE_END (); } } @@ -422,23 +438,23 @@ AsyncIoCallback ( **/ EFI_STATUS AsyncReadSectors ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN NVME_BLKIO2_REQUEST *Request, - IN UINT64 Buffer, - IN UINT64 Lba, - IN UINT32 Blocks, - IN BOOLEAN IsLast + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN NVME_BLKIO2_REQUEST *Request, + IN UINT64 Buffer, + IN UINT64 Lba, + IN UINT32 Blocks, + IN BOOLEAN IsLast ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 Bytes; - NVME_BLKIO2_SUBTASK *Subtask; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; - EFI_NVM_EXPRESS_COMMAND *Command; - EFI_NVM_EXPRESS_COMPLETION *Completion; - EFI_STATUS Status; - UINT32 BlockSize; - EFI_TPL OldTpl; + NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 Bytes; + NVME_BLKIO2_SUBTASK *Subtask; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; + EFI_NVM_EXPRESS_COMMAND *Command; + EFI_NVM_EXPRESS_COMPLETION *Completion; + EFI_STATUS Status; + UINT32 BlockSize; + EFI_TPL OldTpl; Private = Device->Controller; BlockSize = Device->Media.BlockSize; @@ -488,7 +504,7 @@ AsyncReadSectors ( Subtask, &Subtask->Event ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -504,7 +520,7 @@ AsyncReadSectors ( CommandPacket->QueueType = NVME_IO_QUEUE; CommandPacket->NvmeCmd->Cdw10 = (UINT32)Lba; - CommandPacket->NvmeCmd->Cdw11 = (UINT32)RShiftU64(Lba, 32); + CommandPacket->NvmeCmd->Cdw11 = (UINT32)RShiftU64 (Lba, 32); CommandPacket->NvmeCmd->Cdw12 = (Blocks - 1) & 0xFFFF; CommandPacket->NvmeCmd->Flags = CDW10_VALID | CDW11_VALID | CDW12_VALID; @@ -561,23 +577,23 @@ ErrorExit: **/ EFI_STATUS AsyncWriteSectors ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN NVME_BLKIO2_REQUEST *Request, - IN UINT64 Buffer, - IN UINT64 Lba, - IN UINT32 Blocks, - IN BOOLEAN IsLast + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN NVME_BLKIO2_REQUEST *Request, + IN UINT64 Buffer, + IN UINT64 Lba, + IN UINT32 Blocks, + IN BOOLEAN IsLast ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 Bytes; - NVME_BLKIO2_SUBTASK *Subtask; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; - EFI_NVM_EXPRESS_COMMAND *Command; - EFI_NVM_EXPRESS_COMPLETION *Completion; - EFI_STATUS Status; - UINT32 BlockSize; - EFI_TPL OldTpl; + NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 Bytes; + NVME_BLKIO2_SUBTASK *Subtask; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *CommandPacket; + EFI_NVM_EXPRESS_COMMAND *Command; + EFI_NVM_EXPRESS_COMPLETION *Completion; + EFI_STATUS Status; + UINT32 BlockSize; + EFI_TPL OldTpl; Private = Device->Controller; BlockSize = Device->Media.BlockSize; @@ -627,7 +643,7 @@ AsyncWriteSectors ( Subtask, &Subtask->Event ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -643,7 +659,7 @@ AsyncWriteSectors ( CommandPacket->QueueType = NVME_IO_QUEUE; CommandPacket->NvmeCmd->Cdw10 = (UINT32)Lba; - CommandPacket->NvmeCmd->Cdw11 = (UINT32)RShiftU64(Lba, 32); + CommandPacket->NvmeCmd->Cdw11 = (UINT32)RShiftU64 (Lba, 32); // // Set Force Unit Access bit (bit 30) to use write-through behaviour // @@ -701,21 +717,21 @@ ErrorExit: **/ EFI_STATUS NvmeAsyncRead ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - OUT VOID *Buffer, - IN UINT64 Lba, - IN UINTN Blocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN NVME_DEVICE_PRIVATE_DATA *Device, + OUT VOID *Buffer, + IN UINT64 Lba, + IN UINTN Blocks, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - UINT32 BlockSize; - NVME_CONTROLLER_PRIVATE_DATA *Private; - NVME_BLKIO2_REQUEST *BlkIo2Req; - UINT32 MaxTransferBlocks; - UINTN OrginalBlocks; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + EFI_STATUS Status; + UINT32 BlockSize; + NVME_CONTROLLER_PRIVATE_DATA *Private; + NVME_BLKIO2_REQUEST *BlkIo2Req; + UINT32 MaxTransferBlocks; + UINTN OrginalBlocks; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; Status = EFI_SUCCESS; Private = Device->Controller; @@ -745,7 +761,8 @@ NvmeAsyncRead ( if (Blocks > MaxTransferBlocks) { Status = AsyncReadSectors ( Device, - BlkIo2Req, (UINT64)(UINTN)Buffer, + BlkIo2Req, + (UINT64)(UINTN)Buffer, Lba, MaxTransferBlocks, FALSE @@ -767,7 +784,7 @@ NvmeAsyncRead ( Blocks = 0; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { OldTpl = gBS->RaiseTPL (TPL_NOTIFY); IsEmpty = IsListEmpty (&BlkIo2Req->SubtasksQueue) && (BlkIo2Req->UnsubmittedSubtaskNum == 0); @@ -785,8 +802,8 @@ NvmeAsyncRead ( // should be returned to make sure that the caller does not free // resources still using by these requests. // - Status = EFI_SUCCESS; - Token->TransactionStatus = EFI_DEVICE_ERROR; + Status = EFI_SUCCESS; + Token->TransactionStatus = EFI_DEVICE_ERROR; BlkIo2Req->LastSubtaskSubmitted = TRUE; } @@ -796,9 +813,17 @@ NvmeAsyncRead ( } } - DEBUG ((DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " - "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", __FUNCTION__, Lba, - (UINT64)OrginalBlocks, (UINT64)Blocks, BlockSize, Status)); + DEBUG (( + DEBUG_BLKIO, + "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " + "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", + __FUNCTION__, + Lba, + (UINT64)OrginalBlocks, + (UINT64)Blocks, + BlockSize, + Status + )); return Status; } @@ -820,21 +845,21 @@ NvmeAsyncRead ( **/ EFI_STATUS NvmeAsyncWrite ( - IN NVME_DEVICE_PRIVATE_DATA *Device, - IN VOID *Buffer, - IN UINT64 Lba, - IN UINTN Blocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN NVME_DEVICE_PRIVATE_DATA *Device, + IN VOID *Buffer, + IN UINT64 Lba, + IN UINTN Blocks, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - UINT32 BlockSize; - NVME_CONTROLLER_PRIVATE_DATA *Private; - NVME_BLKIO2_REQUEST *BlkIo2Req; - UINT32 MaxTransferBlocks; - UINTN OrginalBlocks; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + EFI_STATUS Status; + UINT32 BlockSize; + NVME_CONTROLLER_PRIVATE_DATA *Private; + NVME_BLKIO2_REQUEST *BlkIo2Req; + UINT32 MaxTransferBlocks; + UINTN OrginalBlocks; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; Status = EFI_SUCCESS; Private = Device->Controller; @@ -862,14 +887,14 @@ NvmeAsyncWrite ( while (Blocks > 0) { if (Blocks > MaxTransferBlocks) { - Status = AsyncWriteSectors ( - Device, - BlkIo2Req, - (UINT64)(UINTN)Buffer, - Lba, - MaxTransferBlocks, - FALSE - ); + Status = AsyncWriteSectors ( + Device, + BlkIo2Req, + (UINT64)(UINTN)Buffer, + Lba, + MaxTransferBlocks, + FALSE + ); Blocks -= MaxTransferBlocks; Buffer = (VOID *)(UINTN)((UINT64)(UINTN)Buffer + MaxTransferBlocks * BlockSize); @@ -887,7 +912,7 @@ NvmeAsyncWrite ( Blocks = 0; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { OldTpl = gBS->RaiseTPL (TPL_NOTIFY); IsEmpty = IsListEmpty (&BlkIo2Req->SubtasksQueue) && (BlkIo2Req->UnsubmittedSubtaskNum == 0); @@ -905,8 +930,8 @@ NvmeAsyncWrite ( // should be returned to make sure that the caller does not free // resources still using by these requests. // - Status = EFI_SUCCESS; - Token->TransactionStatus = EFI_DEVICE_ERROR; + Status = EFI_SUCCESS; + Token->TransactionStatus = EFI_DEVICE_ERROR; BlkIo2Req->LastSubtaskSubmitted = TRUE; } @@ -916,9 +941,17 @@ NvmeAsyncWrite ( } } - DEBUG ((DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " - "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", __FUNCTION__, Lba, - (UINT64)OrginalBlocks, (UINT64)Blocks, BlockSize, Status)); + DEBUG (( + DEBUG_BLKIO, + "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " + "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", + __FUNCTION__, + Lba, + (UINT64)OrginalBlocks, + (UINT64)Blocks, + BlockSize, + Status + )); return Status; } @@ -937,14 +970,14 @@ NvmeAsyncWrite ( EFI_STATUS EFIAPI NvmeBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_TPL OldTpl; - NVME_CONTROLLER_PRIVATE_DATA *Private; - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; + EFI_TPL OldTpl; + NVME_CONTROLLER_PRIVATE_DATA *Private; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; if (This == NULL) { return EFI_INVALID_PARAMETER; @@ -953,13 +986,13 @@ NvmeBlockIoReset ( // // For Nvm Express subsystem, reset block device means reset controller. // - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (This); + Device = NVME_DEVICE_PRIVATE_DATA_FROM_BLOCK_IO (This); Private = Device->Controller; - Status = NvmeControllerInit (Private); + Status = NvmeControllerInit (Private); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -992,20 +1025,20 @@ NvmeBlockIoReset ( EFI_STATUS EFIAPI NvmeBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN IoAlign; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN IoAlign; + EFI_TPL OldTpl; // // Check parameters. @@ -1033,13 +1066,13 @@ NvmeBlockIoReadBlocks ( return EFI_BAD_BUFFER_SIZE; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1076,20 +1109,20 @@ NvmeBlockIoReadBlocks ( EFI_STATUS EFIAPI NvmeBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN IoAlign; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN IoAlign; + EFI_TPL OldTpl; // // Check parameters. @@ -1117,13 +1150,13 @@ NvmeBlockIoWriteBlocks ( return EFI_BAD_BUFFER_SIZE; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1151,12 +1184,12 @@ NvmeBlockIoWriteBlocks ( EFI_STATUS EFIAPI NvmeBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ) { - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + EFI_TPL OldTpl; // // Check parameters. @@ -1196,11 +1229,11 @@ NvmeBlockIoResetEx ( IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - NVME_DEVICE_PRIVATE_DATA *Device; - NVME_CONTROLLER_PRIVATE_DATA *Private; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + EFI_STATUS Status; + NVME_DEVICE_PRIVATE_DATA *Device; + NVME_CONTROLLER_PRIVATE_DATA *Private; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; if (This == NULL) { return EFI_INVALID_PARAMETER; @@ -1227,7 +1260,7 @@ NvmeBlockIoResetEx ( OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - Status = NvmeControllerInit (Private); + Status = NvmeControllerInit (Private); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -1278,21 +1311,21 @@ NvmeBlockIoResetEx ( EFI_STATUS EFIAPI NvmeBlockIoReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN IoAlign; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN IoAlign; + EFI_TPL OldTpl; // // Check parameters. @@ -1316,6 +1349,7 @@ NvmeBlockIoReadBlocksEx ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -1324,13 +1358,13 @@ NvmeBlockIoReadBlocksEx ( return EFI_BAD_BUFFER_SIZE; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1340,7 +1374,7 @@ NvmeBlockIoReadBlocksEx ( if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; - Status = NvmeAsyncRead (Device, Buffer, Lba, NumberOfBlocks, Token); + Status = NvmeAsyncRead (Device, Buffer, Lba, NumberOfBlocks, Token); } else { Status = NvmeRead (Device, Buffer, Lba, NumberOfBlocks); } @@ -1391,20 +1425,20 @@ EFI_STATUS EFIAPI NvmeBlockIoWriteBlocksEx ( IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ) { - NVME_DEVICE_PRIVATE_DATA *Device; - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN IoAlign; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN IoAlign; + EFI_TPL OldTpl; // // Check parameters. @@ -1428,6 +1462,7 @@ NvmeBlockIoWriteBlocksEx ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -1436,13 +1471,13 @@ NvmeBlockIoWriteBlocksEx ( return EFI_BAD_BUFFER_SIZE; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if ((Lba + NumberOfBlocks - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1452,7 +1487,7 @@ NvmeBlockIoWriteBlocksEx ( if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; - Status = NvmeAsyncWrite (Device, Buffer, Lba, NumberOfBlocks, Token); + Status = NvmeAsyncWrite (Device, Buffer, Lba, NumberOfBlocks, Token); } else { Status = NvmeWrite (Device, Buffer, Lba, NumberOfBlocks); } @@ -1488,13 +1523,13 @@ NvmeBlockIoWriteBlocksEx ( EFI_STATUS EFIAPI NvmeBlockIoFlushBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN OUT EFI_BLOCK_IO2_TOKEN *Token + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ) { - NVME_DEVICE_PRIVATE_DATA *Device; - BOOLEAN IsEmpty; - EFI_TPL OldTpl; + NVME_DEVICE_PRIVATE_DATA *Device; + BOOLEAN IsEmpty; + EFI_TPL OldTpl; // // Check parameters. @@ -1560,21 +1595,21 @@ NvmeBlockIoFlushBlocksEx ( **/ EFI_STATUS TrustTransferNvmeDevice ( - IN OUT NVME_CONTROLLER_PRIVATE_DATA *Private, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN OUT NVME_CONTROLLER_PRIVATE_DATA *Private, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - UINT16 SpecificData; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + UINT16 SpecificData; ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); @@ -1615,10 +1650,10 @@ TrustTransferNvmeDevice ( ); if (!IsTrustSend) { - if (EFI_ERROR (Status)) { + if (EFI_ERROR (Status)) { *TransferLengthOut = 0; } else { - *TransferLengthOut = (UINTN) TransferLength; + *TransferLengthOut = (UINTN)TransferLength; } } @@ -1700,20 +1735,20 @@ TrustTransferNvmeDevice ( EFI_STATUS EFIAPI NvmeStorageSecurityReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ) { - EFI_STATUS Status; - NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + NVME_DEVICE_PRIVATE_DATA *Device; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; if ((PayloadBuffer == NULL) || (PayloadTransferSize == NULL) || (PayloadBufferSize == 0)) { return EFI_INVALID_PARAMETER; @@ -1807,19 +1842,19 @@ NvmeStorageSecurityReceiveData ( EFI_STATUS EFIAPI NvmeStorageSecuritySendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ) { - EFI_STATUS Status; - NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + NVME_DEVICE_PRIVATE_DATA *Device; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) { return EFI_INVALID_PARAMETER; @@ -1848,7 +1883,3 @@ NvmeStorageSecuritySendData ( return Status; } - - - - diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h index ba00dde440..8cad15efd3 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h @@ -23,8 +23,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI NvmeBlockIoReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -49,11 +49,11 @@ NvmeBlockIoReset ( EFI_STATUS EFIAPI NvmeBlockIoReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -79,11 +79,11 @@ NvmeBlockIoReadBlocks ( EFI_STATUS EFIAPI NvmeBlockIoWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -99,7 +99,7 @@ NvmeBlockIoWriteBlocks ( EFI_STATUS EFIAPI NvmeBlockIoFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ); /** @@ -162,12 +162,12 @@ NvmeBlockIoResetEx ( EFI_STATUS EFIAPI NvmeBlockIoReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -212,11 +212,11 @@ EFI_STATUS EFIAPI NvmeBlockIoWriteBlocksEx ( IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -246,8 +246,8 @@ NvmeBlockIoWriteBlocksEx ( EFI_STATUS EFIAPI NvmeBlockIoFlushBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN OUT EFI_BLOCK_IO2_TOKEN *Token + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -325,14 +325,14 @@ NvmeBlockIoFlushBlocksEx ( EFI_STATUS EFIAPI NvmeStorageSecurityReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ); /** @@ -399,13 +399,13 @@ NvmeStorageSecurityReceiveData ( EFI_STATUS EFIAPI NvmeStorageSecuritySendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ); #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.c index 10b79d4ad7..9a5ca67300 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.c @@ -8,7 +8,7 @@ #include "NvmExpress.h" -EFI_DISK_INFO_PROTOCOL gNvmExpressDiskInfoProtocolTemplate = { +EFI_DISK_INFO_PROTOCOL gNvmExpressDiskInfoProtocolTemplate = { EFI_DISK_INFO_NVME_INTERFACE_GUID, NvmExpressDiskInfoInquiry, NvmExpressDiskInfoIdentify, @@ -27,13 +27,12 @@ EFI_DISK_INFO_PROTOCOL gNvmExpressDiskInfoProtocolTemplate = { **/ VOID InitializeDiskInfo ( - IN NVME_DEVICE_PRIVATE_DATA *Device + IN NVME_DEVICE_PRIVATE_DATA *Device ) { CopyMem (&Device->DiskInfo, &gNvmExpressDiskInfoProtocolTemplate, sizeof (EFI_DISK_INFO_PROTOCOL)); } - /** Provides inquiry information for the controller type. @@ -53,15 +52,14 @@ InitializeDiskInfo ( EFI_STATUS EFIAPI NvmExpressDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ) { return EFI_NOT_FOUND; } - /** Provides identify information for the controller type. @@ -83,13 +81,13 @@ NvmExpressDiskInfoInquiry ( EFI_STATUS EFIAPI NvmExpressDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ) { - EFI_STATUS Status; - NVME_DEVICE_PRIVATE_DATA *Device; + EFI_STATUS Status; + NVME_DEVICE_PRIVATE_DATA *Device; Device = NVME_DEVICE_PRIVATE_DATA_FROM_DISK_INFO (This); @@ -98,6 +96,7 @@ NvmExpressDiskInfoIdentify ( Status = EFI_SUCCESS; CopyMem (IdentifyData, &Device->NamespaceData, sizeof (Device->NamespaceData)); } + *IdentifyDataSize = sizeof (Device->NamespaceData); return Status; } @@ -122,16 +121,15 @@ NvmExpressDiskInfoIdentify ( EFI_STATUS EFIAPI NvmExpressDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ) { return EFI_NOT_FOUND; } - /** This function is used to get controller information. @@ -146,11 +144,10 @@ NvmExpressDiskInfoSenseData ( EFI_STATUS EFIAPI NvmExpressDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ) { return EFI_UNSUPPORTED; } - diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.h b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.h index b19e6f0a3b..22135ca262 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDiskInfo.h @@ -20,10 +20,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID InitializeDiskInfo ( - IN NVME_DEVICE_PRIVATE_DATA *Device + IN NVME_DEVICE_PRIVATE_DATA *Device ); - /** Provides inquiry information for the controller type. @@ -43,9 +42,9 @@ InitializeDiskInfo ( EFI_STATUS EFIAPI NvmExpressDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ); /** @@ -69,9 +68,9 @@ NvmExpressDiskInfoInquiry ( EFI_STATUS EFIAPI NvmExpressDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ); /** @@ -94,13 +93,12 @@ NvmExpressDiskInfoIdentify ( EFI_STATUS EFIAPI NvmExpressDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ); - /** This function is used to get controller information. @@ -115,9 +113,9 @@ NvmExpressDiskInfoSenseData ( EFI_STATUS EFIAPI NvmExpressDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.c index 08f9d50ff5..ac77afe113 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.c @@ -9,13 +9,13 @@ #include "NvmExpress.h" -#define NVME_SHUTDOWN_PROCESS_TIMEOUT 45 +#define NVME_SHUTDOWN_PROCESS_TIMEOUT 45 // // The number of NVME controllers managed by this driver, used by // NvmeRegisterShutdownNotification() and NvmeUnregisterShutdownNotification(). // -UINTN mNvmeControllerNumber = 0; +UINTN mNvmeControllerNumber = 0; /** Read Nvm Express controller capability register. @@ -29,13 +29,13 @@ UINTN mNvmeControllerNumber = 0; **/ EFI_STATUS ReadNvmeControllerCapabilities ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_CAP *Cap + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_CAP *Cap ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT64 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT64 Data; PciIo = Private->PciIo; Status = PciIo->Mem.Read ( @@ -47,11 +47,11 @@ ReadNvmeControllerCapabilities ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } - WriteUnaligned64 ((UINT64*)Cap, Data); + WriteUnaligned64 ((UINT64 *)Cap, Data); return EFI_SUCCESS; } @@ -67,13 +67,13 @@ ReadNvmeControllerCapabilities ( **/ EFI_STATUS ReadNvmeControllerConfiguration ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_CC *Cc + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_CC *Cc ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT32 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT32 Data; PciIo = Private->PciIo; Status = PciIo->Mem.Read ( @@ -85,11 +85,11 @@ ReadNvmeControllerConfiguration ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } - WriteUnaligned32 ((UINT32*)Cc, Data); + WriteUnaligned32 ((UINT32 *)Cc, Data); return EFI_SUCCESS; } @@ -105,16 +105,16 @@ ReadNvmeControllerConfiguration ( **/ EFI_STATUS WriteNvmeControllerConfiguration ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_CC *Cc + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_CC *Cc ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT32 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT32 Data; PciIo = Private->PciIo; - Data = ReadUnaligned32 ((UINT32*)Cc); + Data = ReadUnaligned32 ((UINT32 *)Cc); Status = PciIo->Mem.Write ( PciIo, EfiPciIoWidthUint32, @@ -124,7 +124,7 @@ WriteNvmeControllerConfiguration ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -151,13 +151,13 @@ WriteNvmeControllerConfiguration ( **/ EFI_STATUS ReadNvmeControllerStatus ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_CSTS *Csts + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_CSTS *Csts ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT32 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT32 Data; PciIo = Private->PciIo; Status = PciIo->Mem.Read ( @@ -169,16 +169,14 @@ ReadNvmeControllerStatus ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } - WriteUnaligned32 ((UINT32*)Csts, Data); + WriteUnaligned32 ((UINT32 *)Csts, Data); return EFI_SUCCESS; } - - /** Write Nvm Express admin queue attributes register. @@ -191,16 +189,16 @@ ReadNvmeControllerStatus ( **/ EFI_STATUS WriteNvmeAdminQueueAttributes ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_AQA *Aqa + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_AQA *Aqa ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT32 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT32 Data; PciIo = Private->PciIo; - Data = ReadUnaligned32 ((UINT32*)Aqa); + Data = ReadUnaligned32 ((UINT32 *)Aqa); Status = PciIo->Mem.Write ( PciIo, EfiPciIoWidthUint32, @@ -210,7 +208,7 @@ WriteNvmeAdminQueueAttributes ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -220,7 +218,6 @@ WriteNvmeAdminQueueAttributes ( return EFI_SUCCESS; } - /** Write Nvm Express admin submission queue base address register. @@ -233,16 +230,16 @@ WriteNvmeAdminQueueAttributes ( **/ EFI_STATUS WriteNvmeAdminSubmissionQueueBaseAddress ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_ASQ *Asq + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_ASQ *Asq ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT64 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT64 Data; - PciIo = Private->PciIo; - Data = ReadUnaligned64 ((UINT64*)Asq); + PciIo = Private->PciIo; + Data = ReadUnaligned64 ((UINT64 *)Asq); Status = PciIo->Mem.Write ( PciIo, @@ -253,7 +250,7 @@ WriteNvmeAdminSubmissionQueueBaseAddress ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -262,8 +259,6 @@ WriteNvmeAdminSubmissionQueueBaseAddress ( return EFI_SUCCESS; } - - /** Write Nvm Express admin completion queue base address register. @@ -276,16 +271,16 @@ WriteNvmeAdminSubmissionQueueBaseAddress ( **/ EFI_STATUS WriteNvmeAdminCompletionQueueBaseAddress ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN NVME_ACQ *Acq + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN NVME_ACQ *Acq ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT64 Data; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT64 Data; - PciIo = Private->PciIo; - Data = ReadUnaligned64 ((UINT64*)Acq); + PciIo = Private->PciIo; + Data = ReadUnaligned64 ((UINT64 *)Acq); Status = PciIo->Mem.Write ( PciIo, @@ -296,7 +291,7 @@ WriteNvmeAdminCompletionQueueBaseAddress ( &Data ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -316,20 +311,20 @@ WriteNvmeAdminCompletionQueueBaseAddress ( **/ EFI_STATUS NvmeDisableController ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - NVME_CC Cc; - NVME_CSTS Csts; - EFI_STATUS Status; - UINT32 Index; - UINT8 Timeout; + NVME_CC Cc; + NVME_CSTS Csts; + EFI_STATUS Status; + UINT32 Index; + UINT8 Timeout; // // Read Controller Configuration Register. // Status = ReadNvmeControllerConfiguration (Private, &Cc); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -340,7 +335,7 @@ NvmeDisableController ( // Status = WriteNvmeControllerConfiguration (Private, &Cc); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -354,15 +349,15 @@ NvmeDisableController ( Timeout = Private->Cap.To; } - for(Index = (Timeout * 500); Index != 0; --Index) { - gBS->Stall(1000); + for (Index = (Timeout * 500); Index != 0; --Index) { + gBS->Stall (1000); // // Check if the controller is initialized // Status = ReadNvmeControllerStatus (Private, &Csts); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -395,14 +390,14 @@ NvmeDisableController ( **/ EFI_STATUS NvmeEnableController ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - NVME_CC Cc; - NVME_CSTS Csts; - EFI_STATUS Status; - UINT32 Index; - UINT8 Timeout; + NVME_CC Cc; + NVME_CSTS Csts; + EFI_STATUS Status; + UINT32 Index; + UINT8 Timeout; // // Enable the controller. @@ -414,7 +409,7 @@ NvmeEnableController ( Cc.Iocqes = 4; Status = WriteNvmeControllerConfiguration (Private, &Cc); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -428,15 +423,15 @@ NvmeEnableController ( Timeout = Private->Cap.To; } - for(Index = (Timeout * 500); Index != 0; --Index) { - gBS->Stall(1000); + for (Index = (Timeout * 500); Index != 0; --Index) { + gBS->Stall (1000); // // Check if the controller is initialized // Status = ReadNvmeControllerStatus (Private, &Csts); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -469,25 +464,25 @@ NvmeEnableController ( **/ EFI_STATUS NvmeIdentifyController ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN VOID *Buffer + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN VOID *Buffer ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; // // According to Nvm Express 1.1 spec Figure 38, When not used, the field shall be cleared to 0h. // For the Identify command, the Namespace Identifier is only used for the Namespace data structure. // - Command.Nsid = 0; + Command.Nsid = 0; CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; @@ -498,8 +493,8 @@ NvmeIdentifyController ( // // Set bit 0 (Cns bit) to 1 to identify a controller // - Command.Cdw10 = 1; - Command.Flags = CDW10_VALID; + Command.Cdw10 = 1; + Command.Flags = CDW10_VALID; Status = Private->Passthru.PassThru ( &Private->Passthru, @@ -524,25 +519,25 @@ NvmeIdentifyController ( **/ EFI_STATUS NvmeIdentifyNamespace ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN VOID *Buffer + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN VOID *Buffer ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; - Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; - Command.Nsid = NamespaceId; + Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; + Command.Nsid = NamespaceId; CommandPacket.TransferBuffer = Buffer; CommandPacket.TransferLength = sizeof (NVME_ADMIN_NAMESPACE_DATA); CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; @@ -574,30 +569,30 @@ NvmeIdentifyNamespace ( **/ EFI_STATUS NvmeCreateIoCompletionQueue ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - NVME_ADMIN_CRIOCQ CrIoCq; - UINT32 Index; - UINT16 QueueSize; - - Status = EFI_SUCCESS; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + NVME_ADMIN_CRIOCQ CrIoCq; + UINT32 Index; + UINT16 QueueSize; + + Status = EFI_SUCCESS; Private->CreateIoQueue = TRUE; for (Index = 1; Index < NVME_MAX_QUEUES; Index++) { - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); - ZeroMem (&CrIoCq, sizeof(NVME_ADMIN_CRIOCQ)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CrIoCq, sizeof (NVME_ADMIN_CRIOCQ)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; - Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_CMD; + Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_CMD; CommandPacket.TransferBuffer = Private->CqBufferPciAddr[Index]; CommandPacket.TransferLength = EFI_PAGE_SIZE; CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; @@ -646,30 +641,30 @@ NvmeCreateIoCompletionQueue ( **/ EFI_STATUS NvmeCreateIoSubmissionQueue ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - NVME_ADMIN_CRIOSQ CrIoSq; - UINT32 Index; - UINT16 QueueSize; - - Status = EFI_SUCCESS; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + NVME_ADMIN_CRIOSQ CrIoSq; + UINT32 Index; + UINT16 QueueSize; + + Status = EFI_SUCCESS; Private->CreateIoQueue = TRUE; for (Index = 1; Index < NVME_MAX_QUEUES; Index++) { - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); - ZeroMem (&CrIoSq, sizeof(NVME_ADMIN_CRIOSQ)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CrIoSq, sizeof (NVME_ADMIN_CRIOSQ)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; - Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_CMD; + Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_CMD; CommandPacket.TransferBuffer = Private->SqBufferPciAddr[Index]; CommandPacket.TransferLength = EFI_PAGE_SIZE; CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; @@ -720,17 +715,18 @@ NvmeCreateIoSubmissionQueue ( **/ EFI_STATUS NvmeControllerInit ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Supports; - NVME_AQA Aqa; - NVME_ASQ Asq; - NVME_ACQ Acq; - UINT8 Sn[21]; - UINT8 Mn[41]; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Supports; + NVME_AQA Aqa; + NVME_ASQ Asq; + NVME_ACQ Acq; + UINT8 Sn[21]; + UINT8 Mn[41]; + // // Save original PCI attributes and enable this controller. // @@ -799,12 +795,12 @@ NvmeControllerInit ( // ASSERT ((Private->Cap.Mpsmin + 12) <= EFI_PAGE_SHIFT); - Private->Cid[0] = 0; - Private->Cid[1] = 0; - Private->Cid[2] = 0; - Private->Pt[0] = 0; - Private->Pt[1] = 0; - Private->Pt[2] = 0; + Private->Cid[0] = 0; + Private->Cid[1] = 0; + Private->Cid[2] = 0; + Private->Pt[0] = 0; + Private->Pt[1] = 0; + Private->Pt[2] = 0; Private->SqTdbl[0].Sqt = 0; Private->SqTdbl[1].Sqt = 0; Private->SqTdbl[2].Sqt = 0; @@ -815,7 +811,7 @@ NvmeControllerInit ( Status = NvmeDisableController (Private); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -869,7 +865,7 @@ NvmeControllerInit ( // Status = WriteNvmeAdminQueueAttributes (Private, &Aqa); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -878,7 +874,7 @@ NvmeControllerInit ( // Status = WriteNvmeAdminSubmissionQueueBaseAddress (Private, &Asq); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -887,12 +883,12 @@ NvmeControllerInit ( // Status = WriteNvmeAdminCompletionQueueBaseAddress (Private, &Acq); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } Status = NvmeEnableController (Private); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -900,7 +896,7 @@ NvmeControllerInit ( // Allocate buffer for Identify Controller data // if (Private->ControllerData == NULL) { - Private->ControllerData = (NVME_ADMIN_CONTROLLER_DATA *)AllocateZeroPool (sizeof(NVME_ADMIN_CONTROLLER_DATA)); + Private->ControllerData = (NVME_ADMIN_CONTROLLER_DATA *)AllocateZeroPool (sizeof (NVME_ADMIN_CONTROLLER_DATA)); if (Private->ControllerData == NULL) { return EFI_OUT_OF_RESOURCES; @@ -912,8 +908,8 @@ NvmeControllerInit ( // Status = NvmeIdentifyController (Private, Private->ControllerData); - if (EFI_ERROR(Status)) { - FreePool(Private->ControllerData); + if (EFI_ERROR (Status)) { + FreePool (Private->ControllerData); Private->ControllerData = NULL; return EFI_NOT_FOUND; } @@ -928,13 +924,13 @@ NvmeControllerInit ( DEBUG ((DEBUG_INFO, " == NVME IDENTIFY CONTROLLER DATA ==\n")); DEBUG ((DEBUG_INFO, " PCI VID : 0x%x\n", Private->ControllerData->Vid)); DEBUG ((DEBUG_INFO, " PCI SSVID : 0x%x\n", Private->ControllerData->Ssvid)); - DEBUG ((DEBUG_INFO, " SN : %a\n", Sn)); - DEBUG ((DEBUG_INFO, " MN : %a\n", Mn)); - DEBUG ((DEBUG_INFO, " FR : 0x%x\n", *((UINT64*)Private->ControllerData->Fr))); - DEBUG ((DEBUG_INFO, " TNVMCAP (high 8-byte) : 0x%lx\n", *((UINT64*)(Private->ControllerData->Tnvmcap + 8)))); - DEBUG ((DEBUG_INFO, " TNVMCAP (low 8-byte) : 0x%lx\n", *((UINT64*)Private->ControllerData->Tnvmcap))); + DEBUG ((DEBUG_INFO, " SN : %a\n", Sn)); + DEBUG ((DEBUG_INFO, " MN : %a\n", Mn)); + DEBUG ((DEBUG_INFO, " FR : 0x%x\n", *((UINT64 *)Private->ControllerData->Fr))); + DEBUG ((DEBUG_INFO, " TNVMCAP (high 8-byte) : 0x%lx\n", *((UINT64 *)(Private->ControllerData->Tnvmcap + 8)))); + DEBUG ((DEBUG_INFO, " TNVMCAP (low 8-byte) : 0x%lx\n", *((UINT64 *)Private->ControllerData->Tnvmcap))); DEBUG ((DEBUG_INFO, " RAB : 0x%x\n", Private->ControllerData->Rab)); - DEBUG ((DEBUG_INFO, " IEEE : 0x%x\n", *(UINT32*)Private->ControllerData->Ieee_oui)); + DEBUG ((DEBUG_INFO, " IEEE : 0x%x\n", *(UINT32 *)Private->ControllerData->Ieee_oui)); DEBUG ((DEBUG_INFO, " AERL : 0x%x\n", Private->ControllerData->Aerl)); DEBUG ((DEBUG_INFO, " SQES : 0x%x\n", Private->ControllerData->Sqes)); DEBUG ((DEBUG_INFO, " CQES : 0x%x\n", Private->ControllerData->Cqes)); @@ -945,8 +941,8 @@ NvmeControllerInit ( // One for blocking I/O, one for non-blocking I/O. // Status = NvmeCreateIoCompletionQueue (Private); - if (EFI_ERROR(Status)) { - return Status; + if (EFI_ERROR (Status)) { + return Status; } // @@ -976,24 +972,24 @@ NvmeControllerInit ( VOID EFIAPI NvmeShutdownAllControllers ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN HandleIndex; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfos; - UINTN OpenInfoCount; - UINTN OpenInfoIndex; - EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *NvmePassThru; - NVME_CC Cc; - NVME_CSTS Csts; - UINTN Index; - NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_STATUS Status; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN HandleIndex; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfos; + UINTN OpenInfoCount; + UINTN OpenInfoIndex; + EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *NvmePassThru; + NVME_CC Cc; + NVME_CSTS Csts; + UINTN Index; + NVME_CONTROLLER_PRIVATE_DATA *Private; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -1023,11 +1019,12 @@ NvmeShutdownAllControllers ( // gImageHandle equals to DriverBinding handle for this driver. // if (((OpenInfos[OpenInfoIndex].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) && - (OpenInfos[OpenInfoIndex].AgentHandle == gImageHandle)) { + (OpenInfos[OpenInfoIndex].AgentHandle == gImageHandle)) + { Status = gBS->OpenProtocol ( OpenInfos[OpenInfoIndex].ControllerHandle, &gEfiNvmExpressPassThruProtocolGuid, - (VOID **) &NvmePassThru, + (VOID **)&NvmePassThru, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1035,22 +1032,24 @@ NvmeShutdownAllControllers ( if (EFI_ERROR (Status)) { continue; } + Private = NVME_CONTROLLER_PRIVATE_DATA_FROM_PASS_THRU (NvmePassThru); // // Read Controller Configuration Register. // Status = ReadNvmeControllerConfiguration (Private, &Cc); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } + // // The host should set the Shutdown Notification (CC.SHN) field to 01b // to indicate a normal shutdown operation. // Cc.Shn = NVME_CC_SHN_NORMAL_SHUTDOWN; Status = WriteNvmeControllerConfiguration (Private, &Cc); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } @@ -1061,10 +1060,11 @@ NvmeShutdownAllControllers ( // for (Index = 0; Index < NVME_SHUTDOWN_PROCESS_TIMEOUT * 100; Index++) { Status = ReadNvmeControllerStatus (Private, &Csts); - if (!EFI_ERROR(Status) && (Csts.Shst == NVME_CSTS_SHST_SHUTDOWN_COMPLETED)) { - DEBUG((DEBUG_INFO, "NvmeShutdownController: shutdown processing is completed after %dms.\n", Index * 10)); + if (!EFI_ERROR (Status) && (Csts.Shst == NVME_CSTS_SHST_SHUTDOWN_COMPLETED)) { + DEBUG ((DEBUG_INFO, "NvmeShutdownController: shutdown processing is completed after %dms.\n", Index * 10)); break; } + // // Stall for 10ms // @@ -1072,7 +1072,7 @@ NvmeShutdownAllControllers ( } if (Index == NVME_SHUTDOWN_PROCESS_TIMEOUT * 100) { - DEBUG((DEBUG_ERROR, "NvmeShutdownController: shutdown processing is timed out\n")); + DEBUG ((DEBUG_ERROR, "NvmeShutdownController: shutdown processing is timed out\n")); } } } @@ -1089,12 +1089,12 @@ NvmeRegisterShutdownNotification ( VOID ) { - EFI_STATUS Status; - EFI_RESET_NOTIFICATION_PROTOCOL *ResetNotify; + EFI_STATUS Status; + EFI_RESET_NOTIFICATION_PROTOCOL *ResetNotify; mNvmeControllerNumber++; if (mNvmeControllerNumber == 1) { - Status = gBS->LocateProtocol (&gEfiResetNotificationProtocolGuid, NULL, (VOID **) &ResetNotify); + Status = gBS->LocateProtocol (&gEfiResetNotificationProtocolGuid, NULL, (VOID **)&ResetNotify); if (!EFI_ERROR (Status)) { Status = ResetNotify->RegisterResetNotify (ResetNotify, NvmeShutdownAllControllers); ASSERT_EFI_ERROR (Status); @@ -1114,12 +1114,12 @@ NvmeUnregisterShutdownNotification ( VOID ) { - EFI_STATUS Status; - EFI_RESET_NOTIFICATION_PROTOCOL *ResetNotify; + EFI_STATUS Status; + EFI_RESET_NOTIFICATION_PROTOCOL *ResetNotify; mNvmeControllerNumber--; if (mNvmeControllerNumber == 0) { - Status = gBS->LocateProtocol (&gEfiResetNotificationProtocolGuid, NULL, (VOID **) &ResetNotify); + Status = gBS->LocateProtocol (&gEfiResetNotificationProtocolGuid, NULL, (VOID **)&ResetNotify); if (!EFI_ERROR (Status)) { Status = ResetNotify->UnregisterResetNotify (ResetNotify, NvmeShutdownAllControllers); ASSERT_EFI_ERROR (Status); diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.h b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.h index 60b3770580..a08c4e974e 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressHci.h @@ -11,12 +11,12 @@ #ifndef _NVME_HCI_H_ #define _NVME_HCI_H_ -#define NVME_BAR 0 +#define NVME_BAR 0 // // Offset from the beginning of private data queue buffer // -#define NVME_ASQ_BUF_OFFSET EFI_PAGE_SIZE +#define NVME_ASQ_BUF_OFFSET EFI_PAGE_SIZE /** Initialize the Nvm Express controller. @@ -29,7 +29,7 @@ **/ EFI_STATUS NvmeControllerInit ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ); /** @@ -44,8 +44,8 @@ NvmeControllerInit ( **/ EFI_STATUS NvmeIdentifyController ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN VOID *Buffer + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN VOID *Buffer ); /** @@ -61,10 +61,9 @@ NvmeIdentifyController ( **/ EFI_STATUS NvmeIdentifyNamespace ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN VOID *Buffer + IN NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN VOID *Buffer ); #endif - diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c index a46a098258..f37baa626a 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c @@ -18,7 +18,7 @@ **/ VOID NvmeDumpStatus ( - IN NVME_CQ *Cq + IN NVME_CQ *Cq ) { DEBUG ((DEBUG_VERBOSE, "Dump NVMe Completion Entry Status from [0x%x]:\n", Cq)); @@ -97,6 +97,7 @@ NvmeDumpStatus ( DEBUG ((DEBUG_VERBOSE, "Reservation Conflict\n")); break; } + break; case 0x1: @@ -159,6 +160,7 @@ NvmeDumpStatus ( DEBUG ((DEBUG_VERBOSE, "Attempted Write to Read Only Range\n")); break; } + break; case 0x2: @@ -185,6 +187,7 @@ NvmeDumpStatus ( DEBUG ((DEBUG_VERBOSE, "Access Denied\n")); break; } + break; default: @@ -206,24 +209,24 @@ NvmeDumpStatus ( @retval The pointer to the first PRP List of the PRP lists. **/ -VOID* +VOID * NvmeCreatePrpList ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_PHYSICAL_ADDRESS PhysicalAddr, - IN UINTN Pages, - OUT VOID **PrpListHost, - IN OUT UINTN *PrpListNo, - OUT VOID **Mapping + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_PHYSICAL_ADDRESS PhysicalAddr, + IN UINTN Pages, + OUT VOID **PrpListHost, + IN OUT UINTN *PrpListNo, + OUT VOID **Mapping ) { - UINTN PrpEntryNo; - UINT64 PrpListBase; - UINTN PrpListIndex; - UINTN PrpEntryIndex; - UINT64 Remainder; - EFI_PHYSICAL_ADDRESS PrpListPhyAddr; - UINTN Bytes; - EFI_STATUS Status; + UINTN PrpEntryNo; + UINT64 PrpListBase; + UINTN PrpListIndex; + UINTN PrpEntryIndex; + UINT64 Remainder; + EFI_PHYSICAL_ADDRESS PrpListPhyAddr; + UINTN Bytes; + EFI_STATUS Status; // // The number of Prp Entry in a memory page. @@ -257,7 +260,7 @@ NvmeCreatePrpList ( return NULL; } - Bytes = EFI_PAGES_TO_SIZE (*PrpListNo); + Bytes = EFI_PAGES_TO_SIZE (*PrpListNo); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, @@ -271,45 +274,46 @@ NvmeCreatePrpList ( DEBUG ((DEBUG_ERROR, "NvmeCreatePrpList: create PrpList failure!\n")); goto EXIT; } + // // Fill all PRP lists except of last one. // ZeroMem (*PrpListHost, Bytes); for (PrpListIndex = 0; PrpListIndex < *PrpListNo - 1; ++PrpListIndex) { - PrpListBase = *(UINT64*)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; + PrpListBase = *(UINT64 *)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; for (PrpEntryIndex = 0; PrpEntryIndex < PrpEntryNo; ++PrpEntryIndex) { if (PrpEntryIndex != PrpEntryNo - 1) { // // Fill all PRP entries except of last one. // - *((UINT64*)(UINTN)PrpListBase + PrpEntryIndex) = PhysicalAddr; - PhysicalAddr += EFI_PAGE_SIZE; + *((UINT64 *)(UINTN)PrpListBase + PrpEntryIndex) = PhysicalAddr; + PhysicalAddr += EFI_PAGE_SIZE; } else { // // Fill last PRP entries with next PRP List pointer. // - *((UINT64*)(UINTN)PrpListBase + PrpEntryIndex) = PrpListPhyAddr + (PrpListIndex + 1) * EFI_PAGE_SIZE; + *((UINT64 *)(UINTN)PrpListBase + PrpEntryIndex) = PrpListPhyAddr + (PrpListIndex + 1) * EFI_PAGE_SIZE; } } } + // // Fill last PRP list. // - PrpListBase = *(UINT64*)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; + PrpListBase = *(UINT64 *)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; for (PrpEntryIndex = 0; PrpEntryIndex < Remainder; ++PrpEntryIndex) { - *((UINT64*)(UINTN)PrpListBase + PrpEntryIndex) = PhysicalAddr; - PhysicalAddr += EFI_PAGE_SIZE; + *((UINT64 *)(UINTN)PrpListBase + PrpEntryIndex) = PhysicalAddr; + PhysicalAddr += EFI_PAGE_SIZE; } - return (VOID*)(UINTN)PrpListPhyAddr; + return (VOID *)(UINTN)PrpListPhyAddr; EXIT: PciIo->FreeBuffer (PciIo, *PrpListNo, *PrpListHost); return NULL; } - /** Aborts the asynchronous PassThru requests. @@ -322,18 +326,18 @@ EXIT: **/ EFI_STATUS AbortAsyncPassThruTasks ( - IN NVME_CONTROLLER_PRIVATE_DATA *Private + IN NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_PCI_IO_PROTOCOL *PciIo; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - NVME_BLKIO2_SUBTASK *Subtask; - NVME_BLKIO2_REQUEST *BlkIo2Request; - NVME_PASS_THRU_ASYNC_REQ *AsyncRequest; - EFI_BLOCK_IO2_TOKEN *Token; - EFI_TPL OldTpl; - EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + NVME_BLKIO2_SUBTASK *Subtask; + NVME_BLKIO2_REQUEST *BlkIo2Request; + NVME_PASS_THRU_ASYNC_REQ *AsyncRequest; + EFI_BLOCK_IO2_TOKEN *Token; + EFI_TPL OldTpl; + EFI_STATUS Status; PciIo = Private->PciIo; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); @@ -343,7 +347,8 @@ AbortAsyncPassThruTasks ( // for (Link = GetFirstNode (&Private->UnsubmittedSubtasks); !IsNull (&Private->UnsubmittedSubtasks, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Private->UnsubmittedSubtasks, Link); Subtask = NVME_BLKIO2_SUBTASK_FROM_LINK (Link); BlkIo2Request = Subtask->BlockIo2Request; @@ -353,6 +358,7 @@ AbortAsyncPassThruTasks ( if (Subtask->IsLast) { BlkIo2Request->LastSubtaskSubmitted = TRUE; } + Token->TransactionStatus = EFI_ABORTED; RemoveEntryList (Link); @@ -365,19 +371,23 @@ AbortAsyncPassThruTasks ( // for (Link = GetFirstNode (&Private->AsyncPassThruQueue); !IsNull (&Private->AsyncPassThruQueue, Link); - Link = NextLink) { - NextLink = GetNextNode (&Private->AsyncPassThruQueue, Link); + Link = NextLink) + { + NextLink = GetNextNode (&Private->AsyncPassThruQueue, Link); AsyncRequest = NVME_PASS_THRU_ASYNC_REQ_FROM_THIS (Link); if (AsyncRequest->MapData != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapData); } + if (AsyncRequest->MapMeta != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapMeta); } + if (AsyncRequest->MapPrpList != NULL) { PciIo->Unmap (PciIo, AsyncRequest->MapPrpList); } + if (AsyncRequest->PrpListHost != NULL) { PciIo->FreeBuffer ( PciIo, @@ -392,7 +402,8 @@ AbortAsyncPassThruTasks ( } if (IsListEmpty (&Private->AsyncPassThruQueue) && - IsListEmpty (&Private->UnsubmittedSubtasks)) { + IsListEmpty (&Private->UnsubmittedSubtasks)) + { Status = EFI_SUCCESS; } else { Status = EFI_DEVICE_ERROR; @@ -403,7 +414,6 @@ AbortAsyncPassThruTasks ( return Status; } - /** Sends an NVM Express Command Packet to an NVM Express controller or namespace. This function supports both blocking I/O and non-blocking I/O. The blocking I/O functionality is required, and the non-blocking @@ -439,10 +449,10 @@ AbortAsyncPassThruTasks ( EFI_STATUS EFIAPI NvmExpressPassThru ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { NVME_CONTROLLER_PRIVATE_DATA *Private; @@ -483,7 +493,7 @@ NvmExpressPassThru ( return EFI_INVALID_PARAMETER; } - if (Packet->QueueType != NVME_ADMIN_QUEUE && Packet->QueueType != NVME_IO_QUEUE) { + if ((Packet->QueueType != NVME_ADMIN_QUEUE) && (Packet->QueueType != NVME_IO_QUEUE)) { return EFI_INVALID_PARAMETER; } @@ -492,31 +502,33 @@ NvmExpressPassThru ( // EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL set is an illegal // configuration. // - Attributes = This->Mode->Attributes; + Attributes = This->Mode->Attributes; if ((Attributes & (EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | - EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL)) == 0) { + EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL)) == 0) + { return EFI_INVALID_PARAMETER; } // // Buffer alignment check for TransferBuffer & MetadataBuffer. // - IoAlign = This->Mode->IoAlign; - if (IoAlign > 0 && (((UINTN) Packet->TransferBuffer & (IoAlign - 1)) != 0)) { + IoAlign = This->Mode->IoAlign; + if ((IoAlign > 0) && (((UINTN)Packet->TransferBuffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } - if (IoAlign > 0 && (((UINTN) Packet->MetadataBuffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Packet->MetadataBuffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } - Private = NVME_CONTROLLER_PRIVATE_DATA_FROM_PASS_THRU (This); + Private = NVME_CONTROLLER_PRIVATE_DATA_FROM_PASS_THRU (This); // // Check NamespaceId is valid or not. // if ((NamespaceId > Private->ControllerData->Nn) && - (NamespaceId != (UINT32) -1)) { + (NamespaceId != (UINT32)-1)) + { return EFI_INVALID_PARAMETER; } @@ -555,13 +567,15 @@ NvmExpressPassThru ( // Submission queue full check. // if ((Private->SqTdbl[QueueId].Sqt + 1) % QueueSize == - Private->AsyncSqHead) { + Private->AsyncSqHead) + { return EFI_NOT_READY; } } } - Sq = Private->SqBuffer[QueueId] + Private->SqTdbl[QueueId].Sqt; - Cq = Private->CqBuffer[QueueId] + Private->CqHdbl[QueueId].Cqh; + + Sq = Private->SqBuffer[QueueId] + Private->SqTdbl[QueueId].Sqt; + Cq = Private->CqBuffer[QueueId] + Private->CqHdbl[QueueId].Cqh; if (Packet->NvmeCmd->Nsid != NamespaceId) { return EFI_INVALID_PARAMETER; @@ -584,7 +598,8 @@ NvmExpressPassThru ( Sq->Prp[0] = (UINT64)(UINTN)Packet->TransferBuffer; if ((Packet->QueueType == NVME_ADMIN_QUEUE) && - ((Sq->Opc == NVME_ADMIN_CRIOCQ_CMD) || (Sq->Opc == NVME_ADMIN_CRIOSQ_CMD))) { + ((Sq->Opc == NVME_ADMIN_CRIOCQ_CMD) || (Sq->Opc == NVME_ADMIN_CRIOSQ_CMD))) + { // // Currently, we only use the IO Completion/Submission queues created internally // by this driver during controller initialization. Any other IO queues created @@ -601,7 +616,8 @@ NvmExpressPassThru ( // If the NVMe cmd has data in or out, then mapping the user buffer to the PCI controller specific addresses. // if (((Packet->TransferLength != 0) && (Packet->TransferBuffer == NULL)) || - ((Packet->TransferLength == 0) && (Packet->TransferBuffer != NULL))) { + ((Packet->TransferLength == 0) && (Packet->TransferBuffer != NULL))) + { return EFI_INVALID_PARAMETER; } @@ -613,14 +629,14 @@ NvmExpressPassThru ( if ((Packet->TransferLength != 0) && (Packet->TransferBuffer != NULL)) { MapLength = Packet->TransferLength; - Status = PciIo->Map ( - PciIo, - Flag, - Packet->TransferBuffer, - &MapLength, - &PhyAddr, - &MapData - ); + Status = PciIo->Map ( + PciIo, + Flag, + Packet->TransferBuffer, + &MapLength, + &PhyAddr, + &MapData + ); if (EFI_ERROR (Status) || (Packet->TransferLength != MapLength)) { return EFI_OUT_OF_RESOURCES; } @@ -629,16 +645,16 @@ NvmExpressPassThru ( Sq->Prp[1] = 0; } - if((Packet->MetadataLength != 0) && (Packet->MetadataBuffer != NULL)) { + if ((Packet->MetadataLength != 0) && (Packet->MetadataBuffer != NULL)) { MapLength = Packet->MetadataLength; - Status = PciIo->Map ( - PciIo, - Flag, - Packet->MetadataBuffer, - &MapLength, - &PhyAddr, - &MapMeta - ); + Status = PciIo->Map ( + PciIo, + Flag, + Packet->MetadataBuffer, + &MapLength, + &PhyAddr, + &MapMeta + ); if (EFI_ERROR (Status) || (Packet->MetadataLength != MapLength)) { PciIo->Unmap ( PciIo, @@ -647,9 +663,11 @@ NvmExpressPassThru ( return EFI_OUT_OF_RESOURCES; } + Sq->Mptr = PhyAddr; } } + // // If the buffer size spans more than two memory pages (page size as defined in CC.Mps), // then build a PRP list in the second PRP submission queue entry. @@ -662,7 +680,7 @@ NvmExpressPassThru ( // Create PrpList for remaining data buffer. // PhyAddr = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1); - Prp = NvmeCreatePrpList (PciIo, PhyAddr, EFI_SIZE_TO_PAGES(Offset + Bytes) - 1, &PrpListHost, &PrpListNo, &MapPrpList); + Prp = NvmeCreatePrpList (PciIo, PhyAddr, EFI_SIZE_TO_PAGES (Offset + Bytes) - 1, &PrpListHost, &PrpListNo, &MapPrpList); if (Prp == NULL) { Status = EFI_OUT_OF_RESOURCES; goto EXIT; @@ -673,28 +691,35 @@ NvmExpressPassThru ( Sq->Prp[1] = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1); } - if(Packet->NvmeCmd->Flags & CDW2_VALID) { + if (Packet->NvmeCmd->Flags & CDW2_VALID) { Sq->Rsvd2 = (UINT64)Packet->NvmeCmd->Cdw2; } - if(Packet->NvmeCmd->Flags & CDW3_VALID) { + + if (Packet->NvmeCmd->Flags & CDW3_VALID) { Sq->Rsvd2 |= LShiftU64 ((UINT64)Packet->NvmeCmd->Cdw3, 32); } - if(Packet->NvmeCmd->Flags & CDW10_VALID) { + + if (Packet->NvmeCmd->Flags & CDW10_VALID) { Sq->Payload.Raw.Cdw10 = Packet->NvmeCmd->Cdw10; } - if(Packet->NvmeCmd->Flags & CDW11_VALID) { + + if (Packet->NvmeCmd->Flags & CDW11_VALID) { Sq->Payload.Raw.Cdw11 = Packet->NvmeCmd->Cdw11; } - if(Packet->NvmeCmd->Flags & CDW12_VALID) { + + if (Packet->NvmeCmd->Flags & CDW12_VALID) { Sq->Payload.Raw.Cdw12 = Packet->NvmeCmd->Cdw12; } - if(Packet->NvmeCmd->Flags & CDW13_VALID) { + + if (Packet->NvmeCmd->Flags & CDW13_VALID) { Sq->Payload.Raw.Cdw13 = Packet->NvmeCmd->Cdw13; } - if(Packet->NvmeCmd->Flags & CDW14_VALID) { + + if (Packet->NvmeCmd->Flags & CDW14_VALID) { Sq->Payload.Raw.Cdw14 = Packet->NvmeCmd->Cdw14; } - if(Packet->NvmeCmd->Flags & CDW15_VALID) { + + if (Packet->NvmeCmd->Flags & CDW15_VALID) { Sq->Payload.Raw.Cdw15 = Packet->NvmeCmd->Cdw15; } @@ -707,15 +732,16 @@ NvmExpressPassThru ( } else { Private->SqTdbl[QueueId].Sqt ^= 1; } - Data = ReadUnaligned32 ((UINT32*)&Private->SqTdbl[QueueId]); + + Data = ReadUnaligned32 ((UINT32 *)&Private->SqTdbl[QueueId]); Status = PciIo->Mem.Write ( - PciIo, - EfiPciIoWidthUint32, - NVME_BAR, - NVME_SQTDBL_OFFSET(QueueId, Private->Cap.Dstrd), - 1, - &Data - ); + PciIo, + EfiPciIoWidthUint32, + NVME_BAR, + NVME_SQTDBL_OFFSET (QueueId, Private->Cap.Dstrd), + 1, + &Data + ); if (EFI_ERROR (Status)) { goto EXIT; @@ -732,15 +758,15 @@ NvmExpressPassThru ( goto EXIT; } - AsyncRequest->Signature = NVME_PASS_THRU_ASYNC_REQ_SIG; - AsyncRequest->Packet = Packet; - AsyncRequest->CommandId = Sq->Cid; - AsyncRequest->CallerEvent = Event; - AsyncRequest->MapData = MapData; - AsyncRequest->MapMeta = MapMeta; - AsyncRequest->MapPrpList = MapPrpList; - AsyncRequest->PrpListNo = PrpListNo; - AsyncRequest->PrpListHost = PrpListHost; + AsyncRequest->Signature = NVME_PASS_THRU_ASYNC_REQ_SIG; + AsyncRequest->Packet = Packet; + AsyncRequest->CommandId = Sq->Cid; + AsyncRequest->CallerEvent = Event; + AsyncRequest->MapData = MapData; + AsyncRequest->MapMeta = MapMeta; + AsyncRequest->MapPrpList = MapPrpList; + AsyncRequest->PrpListNo = PrpListNo; + AsyncRequest->PrpListHost = PrpListHost; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Private->AsyncPassThruQueue, &AsyncRequest->Link); @@ -760,9 +786,9 @@ NvmExpressPassThru ( goto EXIT; } - Status = gBS->SetTimer(TimerEvent, TimerRelative, Packet->CommandTimeout); + Status = gBS->SetTimer (TimerEvent, TimerRelative, Packet->CommandTimeout); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto EXIT; } @@ -788,14 +814,15 @@ NvmExpressPassThru ( // // Dump every completion entry status for debugging. // - DEBUG_CODE_BEGIN(); - NvmeDumpStatus(Cq); - DEBUG_CODE_END(); + DEBUG_CODE_BEGIN (); + NvmeDumpStatus (Cq); + DEBUG_CODE_END (); } + // // Copy the Respose Queue entry for this command to the callers response buffer // - CopyMem(Packet->NvmeCompletion, Cq, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + CopyMem (Packet->NvmeCompletion, Cq, sizeof (EFI_NVM_EXPRESS_COMPLETION)); } else { // // Timeout occurs for an NVMe command. Reset the controller to abort the @@ -840,16 +867,16 @@ NvmExpressPassThru ( Private->Pt[QueueId] ^= 1; } - Data = ReadUnaligned32 ((UINT32*)&Private->CqHdbl[QueueId]); + Data = ReadUnaligned32 ((UINT32 *)&Private->CqHdbl[QueueId]); PreviousStatus = Status; - Status = PciIo->Mem.Write ( - PciIo, - EfiPciIoWidthUint32, - NVME_BAR, - NVME_CQHDBL_OFFSET(QueueId, Private->Cap.Dstrd), - 1, - &Data - ); + Status = PciIo->Mem.Write ( + PciIo, + EfiPciIoWidthUint32, + NVME_BAR, + NVME_CQHDBL_OFFSET (QueueId, Private->Cap.Dstrd), + 1, + &Data + ); // The return status of PciIo->Mem.Write should not override // previous status if previous status contains error. Status = EFI_ERROR (PreviousStatus) ? PreviousStatus : Status; @@ -892,6 +919,7 @@ EXIT: if (TimerEvent != NULL) { gBS->CloseEvent (TimerEvent); } + return Status; } @@ -931,14 +959,14 @@ EXIT: EFI_STATUS EFIAPI NvmExpressGetNextNamespace ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN OUT UINT32 *NamespaceId + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN OUT UINT32 *NamespaceId ) { - NVME_CONTROLLER_PRIVATE_DATA *Private; - NVME_ADMIN_NAMESPACE_DATA *NamespaceData; - UINT32 NextNamespaceId; - EFI_STATUS Status; + NVME_CONTROLLER_PRIVATE_DATA *Private; + NVME_ADMIN_NAMESPACE_DATA *NamespaceData; + UINT32 NextNamespaceId; + EFI_STATUS Status; if ((This == NULL) || (NamespaceId == NULL)) { return EFI_INVALID_PARAMETER; @@ -966,7 +994,7 @@ NvmExpressGetNextNamespace ( } Status = NvmeIdentifyNamespace (Private, NextNamespaceId, NamespaceData); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Done; } @@ -990,7 +1018,7 @@ NvmExpressGetNextNamespace ( } Status = NvmeIdentifyNamespace (Private, NextNamespaceId, NamespaceData); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Done; } @@ -999,7 +1027,7 @@ NvmExpressGetNextNamespace ( Done: if (NamespaceData != NULL) { - FreePool(NamespaceData); + FreePool (NamespaceData); } return Status; @@ -1032,13 +1060,13 @@ Done: EFI_STATUS EFIAPI NvmExpressGetNamespace ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT32 *NamespaceId + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT32 *NamespaceId ) { - NVME_NAMESPACE_DEVICE_PATH *Node; - NVME_CONTROLLER_PRIVATE_DATA *Private; + NVME_NAMESPACE_DEVICE_PATH *Node; + NVME_CONTROLLER_PRIVATE_DATA *Private; if ((This == NULL) || (DevicePath == NULL) || (NamespaceId == NULL)) { return EFI_INVALID_PARAMETER; @@ -1052,7 +1080,7 @@ NvmExpressGetNamespace ( Private = NVME_CONTROLLER_PRIVATE_DATA_FROM_PASS_THRU (This); if (DevicePath->SubType == MSG_NVME_NAMESPACE_DP) { - if (DevicePathNodeLength(DevicePath) != sizeof(NVME_NAMESPACE_DEVICE_PATH)) { + if (DevicePathNodeLength (DevicePath) != sizeof (NVME_NAMESPACE_DEVICE_PATH)) { return EFI_NOT_FOUND; } @@ -1060,7 +1088,8 @@ NvmExpressGetNamespace ( // Check NamespaceId in the device path node is valid or not. // if ((Node->NamespaceId == 0) || - (Node->NamespaceId > Private->ControllerData->Nn)) { + (Node->NamespaceId > Private->ControllerData->Nn)) + { return EFI_NOT_FOUND; } @@ -1106,15 +1135,15 @@ NvmExpressGetNamespace ( EFI_STATUS EFIAPI NvmExpressBuildDevicePath ( - IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, - IN UINT32 NamespaceId, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *This, + IN UINT32 NamespaceId, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - NVME_NAMESPACE_DEVICE_PATH *Node; - NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_STATUS Status; - NVME_ADMIN_NAMESPACE_DATA *NamespaceData; + NVME_NAMESPACE_DEVICE_PATH *Node; + NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_STATUS Status; + NVME_ADMIN_NAMESPACE_DATA *NamespaceData; // // Validate parameters @@ -1130,7 +1159,8 @@ NvmExpressBuildDevicePath ( // Check NamespaceId is valid or not. // if ((NamespaceId == 0) || - (NamespaceId > Private->ControllerData->Nn)) { + (NamespaceId > Private->ControllerData->Nn)) + { return EFI_NOT_FOUND; } @@ -1142,14 +1172,14 @@ NvmExpressBuildDevicePath ( Node->Header.Type = MESSAGING_DEVICE_PATH; Node->Header.SubType = MSG_NVME_NAMESPACE_DP; SetDevicePathNodeLength (&Node->Header, sizeof (NVME_NAMESPACE_DEVICE_PATH)); - Node->NamespaceId = NamespaceId; + Node->NamespaceId = NamespaceId; // // Allocate a buffer for Identify Namespace data. // NamespaceData = NULL; - NamespaceData = AllocateZeroPool(sizeof (NVME_ADMIN_NAMESPACE_DATA)); - if(NamespaceData == NULL) { + NamespaceData = AllocateZeroPool (sizeof (NVME_ADMIN_NAMESPACE_DATA)); + if (NamespaceData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Exit; } @@ -1163,7 +1193,7 @@ NvmExpressBuildDevicePath ( (VOID *)NamespaceData ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Exit; } @@ -1172,7 +1202,7 @@ NvmExpressBuildDevicePath ( *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)Node; Exit: - if(NamespaceData != NULL) { + if (NamespaceData != NULL) { FreePool (NamespaceData); } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/DevicePath.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/DevicePath.c index 6f9ff4b7dd..9b454a7dd8 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/DevicePath.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/DevicePath.c @@ -17,8 +17,8 @@ NVME_NAMESPACE_DEVICE_PATH mNvmeDevicePathNodeTemplate = { MESSAGING_DEVICE_PATH, MSG_NVME_NAMESPACE_DP, { - (UINT8) (sizeof (NVME_NAMESPACE_DEVICE_PATH)), - (UINT8) ((sizeof (NVME_NAMESPACE_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (NVME_NAMESPACE_DEVICE_PATH)), + (UINT8)((sizeof (NVME_NAMESPACE_DEVICE_PATH)) >> 8) } }, 0x0, // NamespaceId @@ -32,8 +32,8 @@ EFI_DEVICE_PATH_PROTOCOL mNvmeEndDevicePathNodeTemplate = { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL)), - (UINT8) ((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) + (UINT8)(sizeof (EFI_DEVICE_PATH_PROTOCOL)), + (UINT8)((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) } }; @@ -78,7 +78,7 @@ NextDevicePathNode ( ) { ASSERT (Node != NULL); - return (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)(Node) + DevicePathNodeLength(Node)); + return (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)(Node) + DevicePathNodeLength (Node)); } /** @@ -96,14 +96,14 @@ NextDevicePathNode ( **/ EFI_STATUS GetDevicePathInstanceSize ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINTN *InstanceSize, - OUT BOOLEAN *EntireDevicePathEnd + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINTN *InstanceSize, + OUT BOOLEAN *EntireDevicePathEnd ) { - EFI_DEVICE_PATH_PROTOCOL *Walker; + EFI_DEVICE_PATH_PROTOCOL *Walker; - if (DevicePath == NULL || InstanceSize == NULL || EntireDevicePathEnd == NULL) { + if ((DevicePath == NULL) || (InstanceSize == NULL) || (EntireDevicePathEnd == NULL)) { return EFI_INVALID_PARAMETER; } @@ -129,7 +129,7 @@ GetDevicePathInstanceSize ( // // Compute the size of the device path instance // - *InstanceSize = ((UINTN) Walker - (UINTN) (DevicePath)) + sizeof (EFI_DEVICE_PATH_PROTOCOL); + *InstanceSize = ((UINTN)Walker - (UINTN)(DevicePath)) + sizeof (EFI_DEVICE_PATH_PROTOCOL); return EFI_SUCCESS; } @@ -147,12 +147,12 @@ GetDevicePathInstanceSize ( **/ EFI_STATUS NvmeIsHcDevicePathValid ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN UINTN DevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN UINTN DevicePathLength ) { - EFI_DEVICE_PATH_PROTOCOL *Start; - UINTN Size; + EFI_DEVICE_PATH_PROTOCOL *Start; + UINTN Size; if (DevicePath == NULL) { return EFI_INVALID_PARAMETER; @@ -167,22 +167,24 @@ NvmeIsHcDevicePathValid ( Start = DevicePath; while (!(DevicePath->Type == END_DEVICE_PATH_TYPE && - DevicePath->SubType == END_ENTIRE_DEVICE_PATH_SUBTYPE)) { + DevicePath->SubType == END_ENTIRE_DEVICE_PATH_SUBTYPE)) + { DevicePath = NextDevicePathNode (DevicePath); // // Prevent overflow and invalid zero in the 'Length' field of a device path // node. // - if ((UINTN) DevicePath <= (UINTN) Start) { + if ((UINTN)DevicePath <= (UINTN)Start) { return EFI_INVALID_PARAMETER; } // // Prevent touching memory beyond given DevicePathLength. // - if ((UINTN) DevicePath - (UINTN) Start > - DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL)) { + if ((UINTN)DevicePath - (UINTN)Start > + DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL)) + { return EFI_INVALID_PARAMETER; } } @@ -190,7 +192,7 @@ NvmeIsHcDevicePathValid ( // // Check if the device path and its size match exactly with each other. // - Size = ((UINTN) DevicePath - (UINTN) Start) + sizeof (EFI_DEVICE_PATH_PROTOCOL); + Size = ((UINTN)DevicePath - (UINTN)Start) + sizeof (EFI_DEVICE_PATH_PROTOCOL); if (Size != DevicePathLength) { return EFI_INVALID_PARAMETER; } @@ -217,17 +219,17 @@ NvmeIsHcDevicePathValid ( **/ EFI_STATUS NvmeBuildDevicePath ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN UINT64 NamespaceUuid, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN UINT64 NamespaceUuid, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - EFI_DEVICE_PATH_PROTOCOL *DevicePathWalker; - NVME_NAMESPACE_DEVICE_PATH *NvmeDeviceNode; + EFI_DEVICE_PATH_PROTOCOL *DevicePathWalker; + NVME_NAMESPACE_DEVICE_PATH *NvmeDeviceNode; - if (DevicePathLength == NULL || DevicePath == NULL) { + if ((DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } @@ -251,8 +253,8 @@ NvmeBuildDevicePath ( // // Construct the Nvm Express device node // - DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *) ((UINT8 *)DevicePathWalker + - (Private->DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL))); + DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)DevicePathWalker + + (Private->DevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL))); CopyMem ( DevicePathWalker, &mNvmeDevicePathNodeTemplate, @@ -265,8 +267,8 @@ NvmeBuildDevicePath ( // // Construct the end device node // - DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *) ((UINT8 *)DevicePathWalker + - sizeof (NVME_NAMESPACE_DEVICE_PATH)); + DevicePathWalker = (EFI_DEVICE_PATH_PROTOCOL *)((UINT8 *)DevicePathWalker + + sizeof (NVME_NAMESPACE_DEVICE_PATH)); CopyMem ( DevicePathWalker, &mNvmeEndDevicePathNodeTemplate, diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/DmaMem.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/DmaMem.c index 7b049b9e4a..36bebc5bc1 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/DmaMem.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/DmaMem.c @@ -20,15 +20,15 @@ GetIoMmu ( VOID ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = NULL; Status = PeiServicesLocatePpi ( &gEdkiiIoMmuPpiGuid, 0, NULL, - (VOID **) &IoMmu + (VOID **)&IoMmu ); if (!EFI_ERROR (Status) && (IoMmu != NULL)) { return IoMmu; @@ -58,48 +58,50 @@ GetIoMmu ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { - EFI_STATUS Status; - UINT64 Attribute; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + UINT64 Attribute; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); if (IoMmu != NULL) { Status = IoMmu->Map ( - IoMmu, - Operation, - HostAddress, - NumberOfBytes, - DeviceAddress, - Mapping - ); + IoMmu, + Operation, + HostAddress, + NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -110,9 +112,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -127,11 +130,11 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); @@ -141,6 +144,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -175,7 +179,7 @@ IoMmuAllocateBuffer ( EFI_PHYSICAL_ADDRESS HostPhyAddress; EDKII_IOMMU_PPI *IoMmu; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; IoMmu = GetIoMmu (); @@ -192,18 +196,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = IoMmu->Map ( - IoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = IoMmu->Map ( + IoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -221,10 +226,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -242,13 +249,13 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { - EFI_STATUS Status; - EDKII_IOMMU_PPI *IoMmu; + EFI_STATUS Status; + EDKII_IOMMU_PPI *IoMmu; IoMmu = GetIoMmu (); @@ -259,5 +266,6 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c index a8cb7f3a67..f73053fc3f 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c @@ -53,19 +53,19 @@ EFI_PEI_NOTIFY_DESCRIPTOR mNvmeEndOfPeiNotifyListTemplate = { **/ EFI_STATUS EnumerateNvmeDevNamespace ( - IN OUT PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId + IN OUT PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId ) { - EFI_STATUS Status; - NVME_ADMIN_NAMESPACE_DATA *NamespaceData; - PEI_NVME_NAMESPACE_INFO *NamespaceInfo; - UINT32 DeviceIndex; - UINT32 Lbads; - UINT32 Flbas; - UINT32 LbaFmtIdx; - - NamespaceData = (NVME_ADMIN_NAMESPACE_DATA *) AllocateZeroPool (sizeof (NVME_ADMIN_NAMESPACE_DATA)); + EFI_STATUS Status; + NVME_ADMIN_NAMESPACE_DATA *NamespaceData; + PEI_NVME_NAMESPACE_INFO *NamespaceInfo; + UINT32 DeviceIndex; + UINT32 Lbads; + UINT32 Flbas; + UINT32 LbaFmtIdx; + + NamespaceData = (NVME_ADMIN_NAMESPACE_DATA *)AllocateZeroPool (sizeof (NVME_ADMIN_NAMESPACE_DATA)); if (NamespaceData == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -92,8 +92,8 @@ EnumerateNvmeDevNamespace ( goto Exit; } - DeviceIndex = Private->ActiveNamespaceNum; - NamespaceInfo = &Private->NamespaceInfo[DeviceIndex]; + DeviceIndex = Private->ActiveNamespaceNum; + NamespaceInfo = &Private->NamespaceInfo[DeviceIndex]; NamespaceInfo->NamespaceId = NamespaceId; NamespaceInfo->NamespaceUuid = NamespaceData->Eui64; NamespaceInfo->Controller = Private; @@ -110,8 +110,8 @@ EnumerateNvmeDevNamespace ( NamespaceInfo->Media.RemovableMedia = FALSE; NamespaceInfo->Media.MediaPresent = TRUE; NamespaceInfo->Media.ReadOnly = FALSE; - NamespaceInfo->Media.BlockSize = (UINT32) 1 << Lbads; - NamespaceInfo->Media.LastBlock = (EFI_PEI_LBA) NamespaceData->Nsze - 1; + NamespaceInfo->Media.BlockSize = (UINT32)1 << Lbads; + NamespaceInfo->Media.LastBlock = (EFI_PEI_LBA)NamespaceData->Nsze - 1; DEBUG (( DEBUG_INFO, "%a: Namespace ID %d - BlockSize = 0x%x, LastBlock = 0x%lx\n", @@ -140,10 +140,10 @@ Exit: **/ EFI_STATUS NvmeDiscoverNamespaces ( - IN OUT PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN OUT PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - UINT32 NamespaceId; + UINT32 NamespaceId; Private->ActiveNamespaceNum = 0; Private->NamespaceInfo = AllocateZeroPool (Private->ControllerData->Nn * sizeof (PEI_NVME_NAMESPACE_INFO)); @@ -161,6 +161,7 @@ NvmeDiscoverNamespaces ( // EnumerateNvmeDevNamespace (Private, NamespaceId); } + if (Private->ActiveNamespaceNum == 0) { return EFI_NOT_FOUND; } @@ -187,7 +188,7 @@ NvmePeimEndOfPei ( IN VOID *Ppi ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY (NotifyDescriptor); NvmeFreeDmaResource (Private); @@ -207,19 +208,19 @@ NvmePeimEndOfPei ( EFI_STATUS EFIAPI NvmExpressPeimEntry ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - EFI_BOOT_MODE BootMode; - EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI *NvmeHcPpi; - UINT8 Controller; - UINTN MmioBase; - UINTN DevicePathLength; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_PHYSICAL_ADDRESS DeviceAddress; + EFI_STATUS Status; + EFI_BOOT_MODE BootMode; + EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI *NvmeHcPpi; + UINT8 Controller; + UINTN MmioBase; + UINTN DevicePathLength; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_PHYSICAL_ADDRESS DeviceAddress; DEBUG ((DEBUG_INFO, "%a: Enters.\n", __FUNCTION__)); @@ -239,7 +240,7 @@ NvmExpressPeimEntry ( &gEdkiiPeiNvmExpressHostControllerPpiGuid, 0, NULL, - (VOID **) &NvmeHcPpi + (VOID **)&NvmeHcPpi ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Fail to locate NvmeHostControllerPpi.\n", __FUNCTION__)); @@ -269,8 +270,10 @@ NvmExpressPeimEntry ( ); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_ERROR, "%a: Fail to allocate get the device path for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Fail to allocate get the device path for Controller %d.\n", + __FUNCTION__, + Controller )); return Status; } @@ -281,8 +284,10 @@ NvmExpressPeimEntry ( Status = NvmeIsHcDevicePathValid (DevicePath, DevicePathLength); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_ERROR, "%a: The device path is invalid for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: The device path is invalid for Controller %d.\n", + __FUNCTION__, + Controller )); Controller++; continue; @@ -295,10 +300,13 @@ NvmExpressPeimEntry ( // during S3 resume. // if ((BootMode == BOOT_ON_S3_RESUME) && - (NvmeS3SkipThisController (DevicePath, DevicePathLength))) { + (NvmeS3SkipThisController (DevicePath, DevicePathLength))) + { DEBUG (( - DEBUG_ERROR, "%a: Controller %d is skipped during S3.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Controller %d is skipped during S3.\n", + __FUNCTION__, + Controller )); Controller++; continue; @@ -310,8 +318,10 @@ NvmExpressPeimEntry ( Private = AllocateZeroPool (sizeof (PEI_NVME_CONTROLLER_PRIVATE_DATA)); if (Private == NULL) { DEBUG (( - DEBUG_ERROR, "%a: Fail to allocate private data for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Fail to allocate private data for Controller %d.\n", + __FUNCTION__, + Controller )); return EFI_OUT_OF_RESOURCES; } @@ -327,12 +337,15 @@ NvmExpressPeimEntry ( ); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_ERROR, "%a: Fail to allocate DMA buffers for Controller %d.\n", - __FUNCTION__, Controller + DEBUG_ERROR, + "%a: Fail to allocate DMA buffers for Controller %d.\n", + __FUNCTION__, + Controller )); return Status; } - ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS) (UINTN) Private->Buffer)); + + ASSERT (DeviceAddress == ((EFI_PHYSICAL_ADDRESS)(UINTN)Private->Buffer)); DEBUG ((DEBUG_INFO, "%a: DMA buffer base at 0x%x\n", __FUNCTION__, Private->Buffer)); // @@ -351,7 +364,9 @@ NvmExpressPeimEntry ( DEBUG (( DEBUG_ERROR, "%a: Controller initialization fail for Controller %d with Status - %r.\n", - __FUNCTION__, Controller, Status + __FUNCTION__, + Controller, + Status )); NvmeFreeDmaResource (Private); Controller++; @@ -369,7 +384,9 @@ NvmExpressPeimEntry ( DEBUG (( DEBUG_ERROR, "%a: Namespaces discovery fail for Controller %d with Status - %r.\n", - __FUNCTION__, Controller, Status + __FUNCTION__, + Controller, + Status )); NvmeFreeDmaResource (Private); Controller++; @@ -379,35 +396,35 @@ NvmExpressPeimEntry ( // // Nvm Express Pass Thru PPI // - Private->PassThruMode.Attributes = EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | - EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL | - EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_CMD_SET_NVM; - Private->PassThruMode.IoAlign = sizeof (UINTN); - Private->PassThruMode.NvmeVersion = EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI_REVISION; - Private->NvmePassThruPpi.Mode = &Private->PassThruMode; - Private->NvmePassThruPpi.GetDevicePath = NvmePassThruGetDevicePath; - Private->NvmePassThruPpi.GetNextNameSpace = NvmePassThruGetNextNameSpace; - Private->NvmePassThruPpi.PassThru = NvmePassThru; + Private->PassThruMode.Attributes = EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | + EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL | + EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_CMD_SET_NVM; + Private->PassThruMode.IoAlign = sizeof (UINTN); + Private->PassThruMode.NvmeVersion = EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI_REVISION; + Private->NvmePassThruPpi.Mode = &Private->PassThruMode; + Private->NvmePassThruPpi.GetDevicePath = NvmePassThruGetDevicePath; + Private->NvmePassThruPpi.GetNextNameSpace = NvmePassThruGetNextNameSpace; + Private->NvmePassThruPpi.PassThru = NvmePassThru; CopyMem ( &Private->NvmePassThruPpiList, &mNvmePassThruPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->NvmePassThruPpiList.Ppi = &Private->NvmePassThruPpi; + Private->NvmePassThruPpiList.Ppi = &Private->NvmePassThruPpi; PeiServicesInstallPpi (&Private->NvmePassThruPpiList); // // Block Io PPI // - Private->BlkIoPpi.GetNumberOfBlockDevices = NvmeBlockIoPeimGetDeviceNo; - Private->BlkIoPpi.GetBlockDeviceMediaInfo = NvmeBlockIoPeimGetMediaInfo; - Private->BlkIoPpi.ReadBlocks = NvmeBlockIoPeimReadBlocks; + Private->BlkIoPpi.GetNumberOfBlockDevices = NvmeBlockIoPeimGetDeviceNo; + Private->BlkIoPpi.GetBlockDeviceMediaInfo = NvmeBlockIoPeimGetMediaInfo; + Private->BlkIoPpi.ReadBlocks = NvmeBlockIoPeimReadBlocks; CopyMem ( &Private->BlkIoPpiList, &mNvmeBlkIoPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->BlkIoPpiList.Ppi = &Private->BlkIoPpi; + Private->BlkIoPpiList.Ppi = &Private->BlkIoPpi; Private->BlkIo2Ppi.Revision = EFI_PEI_RECOVERY_BLOCK_IO2_PPI_REVISION; Private->BlkIo2Ppi.GetNumberOfBlockDevices = NvmeBlockIoPeimGetDeviceNo2; @@ -418,7 +435,7 @@ NvmExpressPeimEntry ( &mNvmeBlkIo2PpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->BlkIo2PpiList.Ppi = &Private->BlkIo2Ppi; + Private->BlkIo2PpiList.Ppi = &Private->BlkIo2Ppi; PeiServicesInstallPpi (&Private->BlkIoPpiList); // @@ -428,7 +445,8 @@ NvmExpressPeimEntry ( DEBUG (( DEBUG_INFO, "%a: Security Security Command PPI will be produced for Controller %d.\n", - __FUNCTION__, Controller + __FUNCTION__, + Controller )); Private->StorageSecurityPpi.Revision = EDKII_STORAGE_SECURITY_PPI_REVISION; Private->StorageSecurityPpi.GetNumberofDevices = NvmeStorageSecurityGetDeviceNo; @@ -440,7 +458,7 @@ NvmExpressPeimEntry ( &mNvmeStorageSecurityPpiListTemplate, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - Private->StorageSecurityPpiList.Ppi = &Private->StorageSecurityPpi; + Private->StorageSecurityPpiList.Ppi = &Private->StorageSecurityPpi; PeiServicesInstallPpi (&Private->StorageSecurityPpiList); } @@ -449,11 +467,13 @@ NvmExpressPeimEntry ( &mNvmeEndOfPeiNotifyListTemplate, sizeof (EFI_PEI_NOTIFY_DESCRIPTOR) ); - PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); + PeiServicesNotifyPpi (&Private->EndOfPeiNotifyList); DEBUG (( - DEBUG_INFO, "%a: Controller %d has been successfully initialized.\n", - __FUNCTION__, Controller + DEBUG_INFO, + "%a: Controller %d has been successfully initialized.\n", + __FUNCTION__, + Controller )); Controller++; } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.h b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.h index 8cd905191b..78a6b70165 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.h @@ -44,68 +44,68 @@ typedef struct _PEI_NVME_CONTROLLER_PRIVATE_DATA PEI_NVME_CONTROLLER_PRIVATE_DA // // NVME PEI driver implementation related definitions // -#define NVME_MAX_QUEUES 2 // Number of I/O queues supported by the driver, 1 for AQ, 1 for CQ -#define NVME_ASQ_SIZE 1 // Number of admin submission queue entries, which is 0-based -#define NVME_ACQ_SIZE 1 // Number of admin completion queue entries, which is 0-based -#define NVME_CSQ_SIZE 63 // Number of I/O submission queue entries, which is 0-based -#define NVME_CCQ_SIZE 63 // Number of I/O completion queue entries, which is 0-based -#define NVME_PRP_SIZE (8) // Pages of PRP list +#define NVME_MAX_QUEUES 2 // Number of I/O queues supported by the driver, 1 for AQ, 1 for CQ +#define NVME_ASQ_SIZE 1 // Number of admin submission queue entries, which is 0-based +#define NVME_ACQ_SIZE 1 // Number of admin completion queue entries, which is 0-based +#define NVME_CSQ_SIZE 63 // Number of I/O submission queue entries, which is 0-based +#define NVME_CCQ_SIZE 63 // Number of I/O completion queue entries, which is 0-based +#define NVME_PRP_SIZE (8) // Pages of PRP list #define NVME_MEM_MAX_PAGES \ ( \ - 1 /* ASQ */ + \ - 1 /* ACQ */ + \ - 1 /* SQs */ + \ - 1 /* CQs */ + \ + 1 /* ASQ */ + \ + 1 /* ACQ */ + \ + 1 /* SQs */ + \ + 1 /* CQs */ + \ NVME_PRP_SIZE) /* PRPs */ -#define NVME_ADMIN_QUEUE 0x00 -#define NVME_IO_QUEUE 0x01 -#define NVME_GENERIC_TIMEOUT 5000000 // Generic PassThru command timeout value, in us unit -#define NVME_POLL_INTERVAL 100 // Poll interval for PassThru command, in us unit +#define NVME_ADMIN_QUEUE 0x00 +#define NVME_IO_QUEUE 0x01 +#define NVME_GENERIC_TIMEOUT 5000000 // Generic PassThru command timeout value, in us unit +#define NVME_POLL_INTERVAL 100 // Poll interval for PassThru command, in us unit // // Nvme namespace data structure. // struct _PEI_NVME_NAMESPACE_INFO { - UINT32 NamespaceId; - UINT64 NamespaceUuid; - EFI_PEI_BLOCK_IO2_MEDIA Media; + UINT32 NamespaceId; + UINT64 NamespaceUuid; + EFI_PEI_BLOCK_IO2_MEDIA Media; - PEI_NVME_CONTROLLER_PRIVATE_DATA *Controller; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Controller; }; -#define NVME_CONTROLLER_NSID 0 +#define NVME_CONTROLLER_NSID 0 // // Unique signature for private data structure. // -#define NVME_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('N','V','P','C') +#define NVME_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('N','V','P','C') // // Nvme controller private data structure. // struct _PEI_NVME_CONTROLLER_PRIVATE_DATA { - UINT32 Signature; - UINTN MmioBase; - EFI_NVM_EXPRESS_PASS_THRU_MODE PassThruMode; - UINTN DevicePathLength; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - - EFI_PEI_RECOVERY_BLOCK_IO_PPI BlkIoPpi; - EFI_PEI_RECOVERY_BLOCK_IO2_PPI BlkIo2Ppi; - EDKII_PEI_STORAGE_SECURITY_CMD_PPI StorageSecurityPpi; - EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI NvmePassThruPpi; - EFI_PEI_PPI_DESCRIPTOR BlkIoPpiList; - EFI_PEI_PPI_DESCRIPTOR BlkIo2PpiList; - EFI_PEI_PPI_DESCRIPTOR StorageSecurityPpiList; - EFI_PEI_PPI_DESCRIPTOR NvmePassThruPpiList; - EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; + UINT32 Signature; + UINTN MmioBase; + EFI_NVM_EXPRESS_PASS_THRU_MODE PassThruMode; + UINTN DevicePathLength; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + + EFI_PEI_RECOVERY_BLOCK_IO_PPI BlkIoPpi; + EFI_PEI_RECOVERY_BLOCK_IO2_PPI BlkIo2Ppi; + EDKII_PEI_STORAGE_SECURITY_CMD_PPI StorageSecurityPpi; + EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI NvmePassThruPpi; + EFI_PEI_PPI_DESCRIPTOR BlkIoPpiList; + EFI_PEI_PPI_DESCRIPTOR BlkIo2PpiList; + EFI_PEI_PPI_DESCRIPTOR StorageSecurityPpiList; + EFI_PEI_PPI_DESCRIPTOR NvmePassThruPpiList; + EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; // // Pointer to identify controller data // - NVME_ADMIN_CONTROLLER_DATA *ControllerData; + NVME_ADMIN_CONTROLLER_DATA *ControllerData; // // (4 + NVME_PRP_SIZE) x 4kB aligned buffers will be carved out of this buffer @@ -115,34 +115,34 @@ struct _PEI_NVME_CONTROLLER_PRIVATE_DATA { // 4th 4kB boundary is the start of I/O completion queue // 5th 4kB boundary is the start of PRP list buffers // - VOID *Buffer; - VOID *BufferMapping; + VOID *Buffer; + VOID *BufferMapping; // // Pointers to 4kB aligned submission & completion queues // - NVME_SQ *SqBuffer[NVME_MAX_QUEUES]; - NVME_CQ *CqBuffer[NVME_MAX_QUEUES]; + NVME_SQ *SqBuffer[NVME_MAX_QUEUES]; + NVME_CQ *CqBuffer[NVME_MAX_QUEUES]; // // Submission and completion queue indices // - NVME_SQTDBL SqTdbl[NVME_MAX_QUEUES]; - NVME_CQHDBL CqHdbl[NVME_MAX_QUEUES]; + NVME_SQTDBL SqTdbl[NVME_MAX_QUEUES]; + NVME_CQHDBL CqHdbl[NVME_MAX_QUEUES]; - UINT8 Pt[NVME_MAX_QUEUES]; - UINT16 Cid[NVME_MAX_QUEUES]; + UINT8 Pt[NVME_MAX_QUEUES]; + UINT16 Cid[NVME_MAX_QUEUES]; // // Nvme controller capabilities // - NVME_CAP Cap; + NVME_CAP Cap; // // Namespaces information on the controller // - UINT32 ActiveNamespaceNum; - PEI_NVME_NAMESPACE_INFO *NamespaceInfo; + UINT32 ActiveNamespaceNum; + PEI_NVME_NAMESPACE_INFO *NamespaceInfo; }; #define GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO(a) \ @@ -156,7 +156,6 @@ struct _PEI_NVME_CONTROLLER_PRIVATE_DATA { #define GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) \ CR (a, PEI_NVME_CONTROLLER_PRIVATE_DATA, EndOfPeiNotifyList, NVME_PEI_CONTROLLER_PRIVATE_DATA_SIGNATURE) - // // Internal functions // @@ -201,9 +200,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** @@ -227,11 +226,11 @@ IoMmuFreeBuffer ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -245,7 +244,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -282,9 +281,9 @@ NvmePeimEndOfPei ( **/ EFI_STATUS GetDevicePathInstanceSize ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINTN *InstanceSize, - OUT BOOLEAN *EntireDevicePathEnd + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINTN *InstanceSize, + OUT BOOLEAN *EntireDevicePathEnd ); /** @@ -300,8 +299,8 @@ GetDevicePathInstanceSize ( **/ EFI_STATUS NvmeIsHcDevicePathValid ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN UINTN DevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN UINTN DevicePathLength ); /** @@ -323,11 +322,11 @@ NvmeIsHcDevicePathValid ( **/ EFI_STATUS NvmeBuildDevicePath ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN UINT64 NamespaceUuid, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN UINT64 NamespaceUuid, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -342,8 +341,8 @@ NvmeBuildDevicePath ( **/ BOOLEAN NvmeS3SkipThisController ( - IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, - IN UINTN HcDevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, + IN UINTN HcDevicePathLength ); #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c index a9bf4f8190..576481dcee 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.c @@ -24,29 +24,29 @@ **/ EFI_STATUS ReadSectors ( - IN PEI_NVME_NAMESPACE_INFO *NamespaceInfo, - OUT UINTN Buffer, - IN UINT64 Lba, - IN UINT32 Blocks + IN PEI_NVME_NAMESPACE_INFO *NamespaceInfo, + OUT UINTN Buffer, + IN UINT64 Lba, + IN UINT32 Blocks ) { - EFI_STATUS Status; - UINT32 BlockSize; - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 Bytes; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *NvmePassThru; - - Private = NamespaceInfo->Controller; + EFI_STATUS Status; + UINT32 BlockSize; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 Bytes; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *NvmePassThru; + + Private = NamespaceInfo->Controller; NvmePassThru = &Private->NvmePassThruPpi; - BlockSize = NamespaceInfo->Media.BlockSize; - Bytes = Blocks * BlockSize; + BlockSize = NamespaceInfo->Media.BlockSize; + Bytes = Blocks * BlockSize; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; @@ -60,7 +60,7 @@ ReadSectors ( CommandPacket.QueueType = NVME_IO_QUEUE; CommandPacket.NvmeCmd->Cdw10 = (UINT32)Lba; - CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64(Lba, 32); + CommandPacket.NvmeCmd->Cdw11 = (UINT32)RShiftU64 (Lba, 32); CommandPacket.NvmeCmd->Cdw12 = (Blocks - 1) & 0xFFFF; CommandPacket.NvmeCmd->Flags = CDW10_VALID | CDW11_VALID | CDW12_VALID; @@ -88,18 +88,18 @@ ReadSectors ( **/ EFI_STATUS NvmeRead ( - IN PEI_NVME_NAMESPACE_INFO *NamespaceInfo, - OUT UINTN Buffer, - IN UINT64 Lba, - IN UINTN Blocks + IN PEI_NVME_NAMESPACE_INFO *NamespaceInfo, + OUT UINTN Buffer, + IN UINT64 Lba, + IN UINTN Blocks ) { - EFI_STATUS Status; - UINT32 Retries; - UINT32 BlockSize; - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 MaxTransferBlocks; - UINTN OrginalBlocks; + EFI_STATUS Status; + UINT32 Retries; + UINT32 BlockSize; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 MaxTransferBlocks; + UINTN OrginalBlocks; Status = EFI_SUCCESS; Retries = 0; @@ -120,14 +120,15 @@ NvmeRead ( Lba, Blocks > MaxTransferBlocks ? MaxTransferBlocks : (UINT32)Blocks ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { Retries++; MaxTransferBlocks = MaxTransferBlocks >> 1; - if (Retries > NVME_READ_MAX_RETRY || MaxTransferBlocks < 1) { + if ((Retries > NVME_READ_MAX_RETRY) || (MaxTransferBlocks < 1)) { DEBUG ((DEBUG_ERROR, "%a: ReadSectors fail, Status - %r\n", __FUNCTION__, Status)); break; } + DEBUG (( DEBUG_BLKIO, "%a: ReadSectors fail, retry with smaller transfer block number - 0x%x\n", @@ -142,13 +143,21 @@ NvmeRead ( Buffer += (MaxTransferBlocks * BlockSize); Lba += MaxTransferBlocks; } else { - Blocks = 0; + Blocks = 0; } } - DEBUG ((DEBUG_BLKIO, "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " - "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", __FUNCTION__, Lba, - (UINT64)OrginalBlocks, (UINT64)Blocks, BlockSize, Status)); + DEBUG (( + DEBUG_BLKIO, + "%a: Lba = 0x%08Lx, Original = 0x%08Lx, " + "Remaining = 0x%08Lx, BlockSize = 0x%x, Status = %r\n", + __FUNCTION__, + Lba, + (UINT64)OrginalBlocks, + (UINT64)Blocks, + BlockSize, + Status + )); return Status; } @@ -176,13 +185,13 @@ NvmeBlockIoPeimGetDeviceNo ( OUT UINTN *NumberBlockDevices ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberBlockDevices == NULL) { + if ((This == NULL) || (NumberBlockDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO (This); + Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO (This); *NumberBlockDevices = Private->ActiveNamespaceNum; return EFI_SUCCESS; @@ -238,9 +247,9 @@ NvmeBlockIoPeimGetMediaInfo ( OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } @@ -250,7 +259,7 @@ NvmeBlockIoPeimGetMediaInfo ( return EFI_INVALID_PARAMETER; } - MediaInfo->DeviceType = (EFI_PEI_BLOCK_DEVICE_TYPE) EDKII_PEI_BLOCK_DEVICE_TYPE_NVME; + MediaInfo->DeviceType = (EFI_PEI_BLOCK_DEVICE_TYPE)EDKII_PEI_BLOCK_DEVICE_TYPE_NVME; MediaInfo->MediaPresent = TRUE; MediaInfo->LastBlock = (UINTN)Private->NamespaceInfo[DeviceIndex-1].Media.LastBlock; MediaInfo->BlockSize = Private->NamespaceInfo[DeviceIndex-1].Media.BlockSize; @@ -303,17 +312,17 @@ NvmeBlockIoPeimReadBlocks ( OUT VOID *Buffer ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - PEI_NVME_NAMESPACE_INFO *NamespaceInfo; - UINT32 BlockSize; - UINTN NumberOfBlocks; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_NAMESPACE_INFO *NamespaceInfo; + UINT32 BlockSize; + UINTN NumberOfBlocks; Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO (This); // // Check parameters // - if (This == NULL || Buffer == NULL) { + if ((This == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -329,7 +338,7 @@ NvmeBlockIoPeimReadBlocks ( // Check BufferSize and StartLBA // NamespaceInfo = &(Private->NamespaceInfo[DeviceIndex - 1]); - BlockSize = NamespaceInfo->Media.BlockSize; + BlockSize = NamespaceInfo->Media.BlockSize; if (BufferSize % BlockSize != 0) { return EFI_BAD_BUFFER_SIZE; } @@ -337,6 +346,7 @@ NvmeBlockIoPeimReadBlocks ( if (StartLBA > NamespaceInfo->Media.LastBlock) { return EFI_INVALID_PARAMETER; } + NumberOfBlocks = BufferSize / BlockSize; if (NumberOfBlocks - 1 > NamespaceInfo->Media.LastBlock - StartLBA) { return EFI_INVALID_PARAMETER; @@ -369,13 +379,13 @@ NvmeBlockIoPeimGetDeviceNo2 ( OUT UINTN *NumberBlockDevices ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberBlockDevices == NULL) { + if ((This == NULL) || (NumberBlockDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2 (This); + Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2 (This); *NumberBlockDevices = Private->ActiveNamespaceNum; return EFI_SUCCESS; @@ -431,22 +441,22 @@ NvmeBlockIoPeimGetMediaInfo2 ( OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - EFI_STATUS Status; - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_PEI_BLOCK_IO_MEDIA Media; + EFI_STATUS Status; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_PEI_BLOCK_IO_MEDIA Media; - if (This == NULL || MediaInfo == NULL) { + if ((This == NULL) || (MediaInfo == NULL)) { return EFI_INVALID_PARAMETER; } Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_BLKIO2 (This); - Status = NvmeBlockIoPeimGetMediaInfo ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - &Media - ); + Status = NvmeBlockIoPeimGetMediaInfo ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + &Media + ); if (EFI_ERROR (Status)) { return Status; } @@ -505,7 +515,7 @@ NvmeBlockIoPeimReadBlocks2 ( OUT VOID *Buffer ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; if (This == NULL) { return EFI_INVALID_PARAMETER; diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.h b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.h index 2c7065cb79..9c0a1eadf8 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiBlockIo.h @@ -14,9 +14,9 @@ // // Nvme device for EFI_PEI_BLOCK_DEVICE_TYPE // -#define EDKII_PEI_BLOCK_DEVICE_TYPE_NVME 7 +#define EDKII_PEI_BLOCK_DEVICE_TYPE_NVME 7 -#define NVME_READ_MAX_RETRY 3 +#define NVME_READ_MAX_RETRY 3 /** Gets the count of block I/O devices that one specific block driver detects. diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c index 1d7e3d26e0..ac956bdce4 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.c @@ -22,14 +22,14 @@ **/ EFI_STATUS NvmeMmioRead ( - IN OUT VOID *MemBuffer, - IN UINTN MmioAddr, - IN UINTN Size + IN OUT VOID *MemBuffer, + IN UINTN MmioAddr, + IN UINTN Size ) { - UINTN Offset; - UINT8 Data; - UINT8 *Ptr; + UINTN Offset; + UINT8 Data; + UINT8 *Ptr; // priority has adjusted switch (Size) { @@ -52,9 +52,10 @@ NvmeMmioRead ( default: Ptr = (UINT8 *)MemBuffer; for (Offset = 0; Offset < Size; Offset += 1) { - Data = MmioRead8 (MmioAddr + Offset); + Data = MmioRead8 (MmioAddr + Offset); Ptr[Offset] = Data; } + break; } @@ -73,14 +74,14 @@ NvmeMmioRead ( **/ EFI_STATUS NvmeMmioWrite ( - IN OUT UINTN MmioAddr, - IN VOID *MemBuffer, - IN UINTN Size + IN OUT UINTN MmioAddr, + IN VOID *MemBuffer, + IN UINTN Size ) { - UINTN Offset; - UINT8 Data; - UINT8 *Ptr; + UINTN Offset; + UINT8 Data; + UINT8 *Ptr; // priority has adjusted switch (Size) { @@ -106,6 +107,7 @@ NvmeMmioWrite ( Data = Ptr[Offset]; MmioWrite8 (MmioAddr + Offset, Data); } + break; } @@ -122,18 +124,18 @@ NvmeMmioWrite ( **/ UINT32 NvmeBaseMemPageOffset ( - IN UINTN BaseMemIndex + IN UINTN BaseMemIndex ) { - UINT32 Pages; - UINTN Index; - UINT32 PageSizeList[5]; + UINT32 Pages; + UINTN Index; + UINT32 PageSizeList[5]; - PageSizeList[0] = 1; /* ASQ */ - PageSizeList[1] = 1; /* ACQ */ - PageSizeList[2] = 1; /* SQs */ - PageSizeList[3] = 1; /* CQs */ - PageSizeList[4] = NVME_PRP_SIZE; /* PRPs */ + PageSizeList[0] = 1; /* ASQ */ + PageSizeList[1] = 1; /* ACQ */ + PageSizeList[2] = 1; /* SQs */ + PageSizeList[3] = 1; /* CQs */ + PageSizeList[4] = NVME_PRP_SIZE; /* PRPs */ if (BaseMemIndex > MAX_BASEMEM_COUNT) { DEBUG ((DEBUG_ERROR, "%a: The input BaseMem index is invalid.\n", __FUNCTION__)); @@ -161,14 +163,14 @@ NvmeBaseMemPageOffset ( **/ EFI_STATUS NvmeWaitController ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN BOOLEAN WaitReady + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN BOOLEAN WaitReady ) { - NVME_CSTS Csts; - EFI_STATUS Status; - UINT32 Index; - UINT8 Timeout; + NVME_CSTS Csts; + EFI_STATUS Status; + UINT32 Index; + UINT8 Timeout; // // Cap.To specifies max delay time in 500ms increments for Csts.Rdy to set after @@ -181,19 +183,19 @@ NvmeWaitController ( } Status = EFI_SUCCESS; - for(Index = (Timeout * 500); Index != 0; --Index) { + for (Index = (Timeout * 500); Index != 0; --Index) { MicroSecondDelay (1000); // // Check if the controller is initialized // Status = NVME_GET_CSTS (Private, &Csts); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: NVME_GET_CSTS fail, Status - %r\n", __FUNCTION__, Status)); return Status; } - if ((BOOLEAN) Csts.Rdy == WaitReady) { + if ((BOOLEAN)Csts.Rdy == WaitReady) { break; } } @@ -216,12 +218,12 @@ NvmeWaitController ( **/ EFI_STATUS NvmeDisableController ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - NVME_CC Cc; - NVME_CSTS Csts; - EFI_STATUS Status; + NVME_CC Cc; + NVME_CSTS Csts; + EFI_STATUS Status; Status = NVME_GET_CSTS (Private, &Csts); @@ -271,11 +273,11 @@ ErrorExit: **/ EFI_STATUS NvmeEnableController ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - NVME_CC Cc; - EFI_STATUS Status; + NVME_CC Cc; + EFI_STATUS Status; // // Enable the controller @@ -316,25 +318,25 @@ ErrorExit: **/ EFI_STATUS NvmeIdentifyController ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN VOID *Buffer + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN VOID *Buffer ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; // // According to Nvm Express 1.1 spec Figure 38, When not used, the field shall be cleared to 0h. // For the Identify command, the Namespace Identifier is only used for the Namespace Data structure. // - Command.Nsid = 0; + Command.Nsid = 0; CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; @@ -369,19 +371,19 @@ NvmeIdentifyController ( **/ EFI_STATUS NvmeIdentifyNamespace ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN VOID *Buffer + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN VOID *Buffer ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; Command.Nsid = NamespaceId; @@ -414,11 +416,11 @@ NvmeIdentifyNamespace ( **/ VOID NvmeDumpControllerData ( - IN NVME_ADMIN_CONTROLLER_DATA *ControllerData + IN NVME_ADMIN_CONTROLLER_DATA *ControllerData ) { - UINT8 Sn[21]; - UINT8 Mn[41]; + UINT8 Sn[21]; + UINT8 Mn[41]; CopyMem (Sn, ControllerData->Sn, sizeof (ControllerData->Sn)); Sn[20] = 0; @@ -428,11 +430,11 @@ NvmeDumpControllerData ( DEBUG ((DEBUG_INFO, " == NVME IDENTIFY CONTROLLER DATA ==\n")); DEBUG ((DEBUG_INFO, " PCI VID : 0x%x\n", ControllerData->Vid)); DEBUG ((DEBUG_INFO, " PCI SSVID : 0x%x\n", ControllerData->Ssvid)); - DEBUG ((DEBUG_INFO, " SN : %a\n", Sn)); - DEBUG ((DEBUG_INFO, " MN : %a\n", Mn)); - DEBUG ((DEBUG_INFO, " FR : 0x%lx\n", *((UINT64*)ControllerData->Fr))); + DEBUG ((DEBUG_INFO, " SN : %a\n", Sn)); + DEBUG ((DEBUG_INFO, " MN : %a\n", Mn)); + DEBUG ((DEBUG_INFO, " FR : 0x%lx\n", *((UINT64 *)ControllerData->Fr))); DEBUG ((DEBUG_INFO, " RAB : 0x%x\n", ControllerData->Rab)); - DEBUG ((DEBUG_INFO, " IEEE : 0x%x\n", *(UINT32*)ControllerData->Ieee_oui)); + DEBUG ((DEBUG_INFO, " IEEE : 0x%x\n", *(UINT32 *)ControllerData->Ieee_oui)); DEBUG ((DEBUG_INFO, " AERL : 0x%x\n", ControllerData->Aerl)); DEBUG ((DEBUG_INFO, " SQES : 0x%x\n", ControllerData->Sqes)); DEBUG ((DEBUG_INFO, " CQES : 0x%x\n", ControllerData->Cqes)); @@ -451,24 +453,24 @@ NvmeDumpControllerData ( **/ EFI_STATUS NvmeCreateIoCompletionQueue ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - NVME_ADMIN_CRIOCQ CrIoCq; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + NVME_ADMIN_CRIOCQ CrIoCq; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); - ZeroMem (&CrIoCq, sizeof(NVME_ADMIN_CRIOCQ)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CrIoCq, sizeof (NVME_ADMIN_CRIOCQ)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; - Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_CMD; + Command.Cdw0.Opcode = NVME_ADMIN_CRIOCQ_CMD; CommandPacket.TransferBuffer = Private->CqBuffer[NVME_IO_QUEUE]; CommandPacket.TransferLength = EFI_PAGE_SIZE; CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; @@ -499,24 +501,24 @@ NvmeCreateIoCompletionQueue ( **/ EFI_STATUS NvmeCreateIoSubmissionQueue ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - NVME_ADMIN_CRIOSQ CrIoSq; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + NVME_ADMIN_CRIOSQ CrIoSq; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); - ZeroMem (&CrIoSq, sizeof(NVME_ADMIN_CRIOSQ)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CrIoSq, sizeof (NVME_ADMIN_CRIOSQ)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; - Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_CMD; + Command.Cdw0.Opcode = NVME_ADMIN_CRIOSQ_CMD; CommandPacket.TransferBuffer = Private->SqBuffer[NVME_IO_QUEUE]; CommandPacket.TransferLength = EFI_PAGE_SIZE; CommandPacket.CommandTimeout = NVME_GENERIC_TIMEOUT; @@ -549,15 +551,15 @@ NvmeCreateIoSubmissionQueue ( **/ EFI_STATUS NvmeControllerInit ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINTN Index; - NVME_AQA Aqa; - NVME_ASQ Asq; - NVME_ACQ Acq; - NVME_VER Ver; + EFI_STATUS Status; + UINTN Index; + NVME_AQA Aqa; + NVME_ASQ Asq; + NVME_ACQ Acq; + NVME_VER Ver; // // Dump the NVME controller implementation version @@ -589,6 +591,7 @@ NvmeControllerInit ( ZeroMem ((VOID *)(UINTN)(&Private->SqTdbl[Index]), sizeof (NVME_SQTDBL)); ZeroMem ((VOID *)(UINTN)(&Private->CqHdbl[Index]), sizeof (NVME_CQHDBL)); } + ZeroMem (Private->Buffer, EFI_PAGE_SIZE * NVME_MEM_MAX_PAGES); // @@ -657,11 +660,13 @@ NvmeControllerInit ( return EFI_OUT_OF_RESOURCES; } } + Status = NvmeIdentifyController (Private, Private->ControllerData); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: NvmeIdentifyController fail, Status - %r\n", __FUNCTION__, Status)); return Status; } + NvmeDumpControllerData (Private->ControllerData); // @@ -684,6 +689,7 @@ NvmeControllerInit ( DEBUG ((DEBUG_ERROR, "%a: Create IO completion queue fail, Status - %r\n", __FUNCTION__, Status)); return Status; } + Status = NvmeCreateIoSubmissionQueue (Private); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Create IO submission queue fail, Status - %r\n", __FUNCTION__, Status)); @@ -700,17 +706,17 @@ NvmeControllerInit ( **/ VOID NvmeFreeDmaResource ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ) { ASSERT (Private != NULL); if (Private->BufferMapping != NULL) { IoMmuFreeBuffer ( - NVME_MEM_MAX_PAGES, - Private->Buffer, - Private->BufferMapping - ); + NVME_MEM_MAX_PAGES, + Private->Buffer, + Private->BufferMapping + ); } return; diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.h b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.h index 89fee735fe..a6bec510f0 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiHci.h @@ -43,14 +43,13 @@ enum { // // All of base memories are 4K(0x1000) alignment // -#define ALIGN(v, a) (UINTN)((((v) - 1) | ((a) - 1)) + 1) -#define NVME_MEM_BASE(Private) ((UINTN)(Private->Buffer)) -#define NVME_ASQ_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_ASQ)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) -#define NVME_ACQ_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_ACQ)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) -#define NVME_SQ_BASE(Private, Index) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_SQ) + ((Index)*(NVME_MAX_QUEUES-1))) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) -#define NVME_CQ_BASE(Private, Index) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_CQ) + ((Index)*(NVME_MAX_QUEUES-1))) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) -#define NVME_PRP_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_PRP)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) - +#define ALIGN(v, a) (UINTN)((((v) - 1) | ((a) - 1)) + 1) +#define NVME_MEM_BASE(Private) ((UINTN)(Private->Buffer)) +#define NVME_ASQ_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_ASQ)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) +#define NVME_ACQ_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_ACQ)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) +#define NVME_SQ_BASE(Private, Index) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_SQ) + ((Index)*(NVME_MAX_QUEUES-1))) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) +#define NVME_CQ_BASE(Private, Index) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_CQ) + ((Index)*(NVME_MAX_QUEUES-1))) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) +#define NVME_PRP_BASE(Private) (ALIGN (NVME_MEM_BASE(Private) + ((NvmeBaseMemPageOffset (BASEMEM_PRP)) * EFI_PAGE_SIZE), EFI_PAGE_SIZE)) /** Transfer MMIO Data to memory. @@ -64,9 +63,9 @@ enum { **/ EFI_STATUS NvmeMmioRead ( - IN OUT VOID *MemBuffer, - IN UINTN MmioAddr, - IN UINTN Size + IN OUT VOID *MemBuffer, + IN UINTN MmioAddr, + IN UINTN Size ); /** @@ -81,9 +80,9 @@ NvmeMmioRead ( **/ EFI_STATUS NvmeMmioWrite ( - IN OUT UINTN MmioAddr, - IN VOID *MemBuffer, - IN UINTN Size + IN OUT UINTN MmioAddr, + IN VOID *MemBuffer, + IN UINTN Size ); /** @@ -96,7 +95,7 @@ NvmeMmioWrite ( **/ UINT32 NvmeBaseMemPageOffset ( - IN UINTN BaseMemIndex + IN UINTN BaseMemIndex ); /** @@ -110,7 +109,7 @@ NvmeBaseMemPageOffset ( **/ EFI_STATUS NvmeControllerInit ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ); /** @@ -126,9 +125,9 @@ NvmeControllerInit ( **/ EFI_STATUS NvmeIdentifyNamespace ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN VOID *Buffer + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN VOID *Buffer ); /** @@ -139,7 +138,7 @@ NvmeIdentifyNamespace ( **/ VOID NvmeFreeDmaResource ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private ); #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c index 370a54e5a2..dc280ec4e3 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.c @@ -22,22 +22,22 @@ **/ UINT64 NvmeCreatePrpList ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN EFI_PHYSICAL_ADDRESS PhysicalAddr, - IN UINTN Pages + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN EFI_PHYSICAL_ADDRESS PhysicalAddr, + IN UINTN Pages ) { - UINTN PrpEntryNo; - UINTN PrpListNo; - UINT64 PrpListBase; - VOID *PrpListHost; - UINTN PrpListIndex; - UINTN PrpEntryIndex; - UINT64 Remainder; - EFI_PHYSICAL_ADDRESS PrpListPhyAddr; - UINTN Bytes; - UINT8 *PrpEntry; - EFI_PHYSICAL_ADDRESS NewPhyAddr; + UINTN PrpEntryNo; + UINTN PrpListNo; + UINT64 PrpListBase; + VOID *PrpListHost; + UINTN PrpListIndex; + UINTN PrpEntryIndex; + UINT64 Remainder; + EFI_PHYSICAL_ADDRESS PrpListPhyAddr; + UINTN Bytes; + UINT8 *PrpEntry; + EFI_PHYSICAL_ADDRESS NewPhyAddr; // // The number of Prp Entry in a memory page. @@ -47,7 +47,7 @@ NvmeCreatePrpList ( // // Calculate total PrpList number. // - PrpListNo = (UINTN) DivU64x64Remainder ((UINT64)Pages, (UINT64)PrpEntryNo, &Remainder); + PrpListNo = (UINTN)DivU64x64Remainder ((UINT64)Pages, (UINT64)PrpEntryNo, &Remainder); if (Remainder != 0) { PrpListNo += 1; } @@ -62,9 +62,10 @@ NvmeCreatePrpList ( )); return 0; } - PrpListHost = (VOID *)(UINTN) NVME_PRP_BASE (Private); - Bytes = EFI_PAGES_TO_SIZE (PrpListNo); + PrpListHost = (VOID *)(UINTN)NVME_PRP_BASE (Private); + + Bytes = EFI_PAGES_TO_SIZE (PrpListNo); PrpListPhyAddr = (UINT64)(UINTN)(PrpListHost); // @@ -75,19 +76,19 @@ NvmeCreatePrpList ( PrpListBase = (UINTN)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; for (PrpEntryIndex = 0; PrpEntryIndex < PrpEntryNo; ++PrpEntryIndex) { - PrpEntry = (UINT8 *)(UINTN) (PrpListBase + PrpEntryIndex * sizeof(UINT64)); + PrpEntry = (UINT8 *)(UINTN)(PrpListBase + PrpEntryIndex * sizeof (UINT64)); if (PrpEntryIndex != PrpEntryNo - 1) { // // Fill all PRP entries except of last one. // - CopyMem (PrpEntry, (VOID *)(UINTN) (&PhysicalAddr), sizeof (UINT64)); + CopyMem (PrpEntry, (VOID *)(UINTN)(&PhysicalAddr), sizeof (UINT64)); PhysicalAddr += EFI_PAGE_SIZE; } else { // // Fill last PRP entries with next PRP List pointer. // NewPhyAddr = (PrpListPhyAddr + (PrpListIndex + 1) * EFI_PAGE_SIZE); - CopyMem (PrpEntry, (VOID *)(UINTN) (&NewPhyAddr), sizeof (UINT64)); + CopyMem (PrpEntry, (VOID *)(UINTN)(&NewPhyAddr), sizeof (UINT64)); } } } @@ -97,8 +98,8 @@ NvmeCreatePrpList ( // PrpListBase = (UINTN)PrpListHost + PrpListIndex * EFI_PAGE_SIZE; for (PrpEntryIndex = 0; PrpEntryIndex < ((Remainder != 0) ? Remainder : PrpEntryNo); ++PrpEntryIndex) { - PrpEntry = (UINT8 *)(UINTN) (PrpListBase + PrpEntryIndex * sizeof(UINT64)); - CopyMem (PrpEntry, (VOID *)(UINTN) (&PhysicalAddr), sizeof (UINT64)); + PrpEntry = (UINT8 *)(UINTN)(PrpListBase + PrpEntryIndex * sizeof (UINT64)); + CopyMem (PrpEntry, (VOID *)(UINTN)(&PhysicalAddr), sizeof (UINT64)); PhysicalAddr += EFI_PAGE_SIZE; } @@ -114,10 +115,10 @@ NvmeCreatePrpList ( **/ EFI_STATUS NvmeCheckCqStatus ( - IN NVME_CQ *Cq + IN NVME_CQ *Cq ) { - if (Cq->Sct == 0x0 && Cq->Sc == 0x0) { + if ((Cq->Sct == 0x0) && (Cq->Sc == 0x0)) { return EFI_SUCCESS; } @@ -202,6 +203,7 @@ NvmeCheckCqStatus ( DEBUG ((DEBUG_INFO, "Reservation Conflict\n")); break; } + break; case 0x1: @@ -264,6 +266,7 @@ NvmeCheckCqStatus ( DEBUG ((DEBUG_INFO, "Attempted Write to Read Only Range\n")); break; } + break; case 0x2: @@ -290,6 +293,7 @@ NvmeCheckCqStatus ( DEBUG ((DEBUG_INFO, "Access Denied\n")); break; } + break; default: @@ -333,26 +337,26 @@ NvmeCheckCqStatus ( **/ EFI_STATUS NvmePassThruExecute ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet ) { - EFI_STATUS Status; - NVME_SQ *Sq; - NVME_CQ *Cq; - UINT8 QueueId; - UINTN SqSize; - UINTN CqSize; - EDKII_IOMMU_OPERATION MapOp; - UINTN MapLength; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *MapData; - VOID *MapMeta; - UINT32 Bytes; - UINT32 Offset; - UINT32 Data32; - UINT64 Timer; + EFI_STATUS Status; + NVME_SQ *Sq; + NVME_CQ *Cq; + UINT8 QueueId; + UINTN SqSize; + UINTN CqSize; + EDKII_IOMMU_OPERATION MapOp; + UINTN MapLength; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *MapData; + VOID *MapMeta; + UINT32 Bytes; + UINT32 Offset; + UINT32 Data32; + UINT64 Timer; // // Check the data fields in Packet parameter @@ -378,7 +382,7 @@ NvmePassThruExecute ( return EFI_INVALID_PARAMETER; } - if (Packet->QueueType != NVME_ADMIN_QUEUE && Packet->QueueType != NVME_IO_QUEUE) { + if ((Packet->QueueType != NVME_ADMIN_QUEUE) && (Packet->QueueType != NVME_IO_QUEUE)) { DEBUG (( DEBUG_ERROR, "%a, Invalid parameter: QueueId(%lx)\n", @@ -413,7 +417,7 @@ NvmePassThruExecute ( ZeroMem (Sq, sizeof (NVME_SQ)); Sq->Opc = (UINT8)Packet->NvmeCmd->Cdw0.Opcode; Sq->Fuse = (UINT8)Packet->NvmeCmd->Cdw0.FusedOperation; - Sq->Cid = Private->Cid[QueueId]++;; + Sq->Cid = Private->Cid[QueueId]++; Sq->Nsid = Packet->NvmeCmd->Nsid; // @@ -436,7 +440,8 @@ NvmePassThruExecute ( // if ((Sq->Opc & (BIT0 | BIT1)) != 0) { if (((Packet->TransferLength != 0) && (Packet->TransferBuffer == NULL)) || - ((Packet->TransferLength == 0) && (Packet->TransferBuffer != NULL))) { + ((Packet->TransferLength == 0) && (Packet->TransferBuffer != NULL))) + { return EFI_INVALID_PARAMETER; } @@ -445,9 +450,11 @@ NvmePassThruExecute ( // allocated internally by the driver. // if ((Packet->QueueType == NVME_ADMIN_QUEUE) && - ((Sq->Opc == NVME_ADMIN_CRIOCQ_CMD) || (Sq->Opc == NVME_ADMIN_CRIOSQ_CMD))) { + ((Sq->Opc == NVME_ADMIN_CRIOCQ_CMD) || (Sq->Opc == NVME_ADMIN_CRIOSQ_CMD))) + { if ((Packet->TransferBuffer != Private->SqBuffer[NVME_IO_QUEUE]) && - (Packet->TransferBuffer != Private->CqBuffer[NVME_IO_QUEUE])) { + (Packet->TransferBuffer != Private->CqBuffer[NVME_IO_QUEUE])) + { DEBUG (( DEBUG_ERROR, "%a: Does not support external IO queues creation request.\n", @@ -464,13 +471,13 @@ NvmePassThruExecute ( if ((Packet->TransferLength != 0) && (Packet->TransferBuffer != NULL)) { MapLength = Packet->TransferLength; - Status = IoMmuMap ( - MapOp, - Packet->TransferBuffer, - &MapLength, - &PhyAddr, - &MapData - ); + Status = IoMmuMap ( + MapOp, + Packet->TransferBuffer, + &MapLength, + &PhyAddr, + &MapData + ); if (EFI_ERROR (Status) || (MapLength != Packet->TransferLength)) { Status = EFI_OUT_OF_RESOURCES; DEBUG ((DEBUG_ERROR, "%a: Fail to map data buffer.\n", __FUNCTION__)); @@ -480,20 +487,21 @@ NvmePassThruExecute ( Sq->Prp[0] = PhyAddr; } - if((Packet->MetadataLength != 0) && (Packet->MetadataBuffer != NULL)) { + if ((Packet->MetadataLength != 0) && (Packet->MetadataBuffer != NULL)) { MapLength = Packet->MetadataLength; - Status = IoMmuMap ( - MapOp, - Packet->MetadataBuffer, - &MapLength, - &PhyAddr, - &MapMeta - ); + Status = IoMmuMap ( + MapOp, + Packet->MetadataBuffer, + &MapLength, + &PhyAddr, + &MapMeta + ); if (EFI_ERROR (Status) || (MapLength != Packet->MetadataLength)) { Status = EFI_OUT_OF_RESOURCES; DEBUG ((DEBUG_ERROR, "%a: Fail to map meta data buffer.\n", __FUNCTION__)); goto Exit; } + Sq->Mptr = PhyAddr; } } @@ -510,18 +518,17 @@ NvmePassThruExecute ( // // Create PrpList for remaining Data Buffer. // - PhyAddr = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1); + PhyAddr = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1); Sq->Prp[1] = NvmeCreatePrpList ( Private, PhyAddr, - EFI_SIZE_TO_PAGES(Offset + Bytes) - 1 + EFI_SIZE_TO_PAGES (Offset + Bytes) - 1 ); if (Sq->Prp[1] == 0) { Status = EFI_OUT_OF_RESOURCES; DEBUG ((DEBUG_ERROR, "%a: Create PRP list fail, Status - %r\n", __FUNCTION__, Status)); goto Exit; } - } else if ((Offset + Bytes) > EFI_PAGE_SIZE) { Sq->Prp[1] = (Sq->Prp[0] + EFI_PAGE_SIZE) & ~(EFI_PAGE_SIZE - 1); } @@ -529,18 +536,23 @@ NvmePassThruExecute ( if (Packet->NvmeCmd->Flags & CDW10_VALID) { Sq->Payload.Raw.Cdw10 = Packet->NvmeCmd->Cdw10; } + if (Packet->NvmeCmd->Flags & CDW11_VALID) { Sq->Payload.Raw.Cdw11 = Packet->NvmeCmd->Cdw11; } + if (Packet->NvmeCmd->Flags & CDW12_VALID) { Sq->Payload.Raw.Cdw12 = Packet->NvmeCmd->Cdw12; } + if (Packet->NvmeCmd->Flags & CDW13_VALID) { Sq->Payload.Raw.Cdw13 = Packet->NvmeCmd->Cdw13; } + if (Packet->NvmeCmd->Flags & CDW14_VALID) { Sq->Payload.Raw.Cdw14 = Packet->NvmeCmd->Cdw14; } + if (Packet->NvmeCmd->Flags & CDW15_VALID) { Sq->Payload.Raw.Cdw15 = Packet->NvmeCmd->Cdw15; } @@ -552,6 +564,7 @@ NvmePassThruExecute ( if (Private->SqTdbl[QueueId].Sqt == SqSize) { Private->SqTdbl[QueueId].Sqt = 0; } + Data32 = ReadUnaligned32 ((UINT32 *)&Private->SqTdbl[QueueId]); Status = NVME_SET_SQTDBL (Private, QueueId, &Data32); if (EFI_ERROR (Status)) { @@ -588,6 +601,7 @@ NvmePassThruExecute ( // Status = EFI_TIMEOUT; } + goto Exit; } @@ -597,7 +611,7 @@ NvmePassThruExecute ( Private->CqHdbl[QueueId].Cqh++; if (Private->CqHdbl[QueueId].Cqh == CqSize) { Private->CqHdbl[QueueId].Cqh = 0; - Private->Pt[QueueId] ^= 1; + Private->Pt[QueueId] ^= 1; } // @@ -643,14 +657,14 @@ Exit: EFI_STATUS EFIAPI NvmePassThruGetDevicePath ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || DevicePathLength == NULL || DevicePath == NULL) { + if ((This == NULL) || (DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } @@ -705,15 +719,15 @@ NvmePassThruGetDevicePath ( EFI_STATUS EFIAPI NvmePassThruGetNextNameSpace ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - IN OUT UINT32 *NamespaceId + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + IN OUT UINT32 *NamespaceId ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - UINT32 DeviceIndex; - EFI_STATUS Status; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + UINT32 DeviceIndex; + EFI_STATUS Status; - if (This == NULL || NamespaceId == NULL) { + if ((This == NULL) || (NamespaceId == NULL)) { return EFI_INVALID_PARAMETER; } @@ -736,7 +750,7 @@ NvmePassThruGetNextNameSpace ( // Start with the first namespace ID // *NamespaceId = Private->NamespaceInfo[0].NamespaceId; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } else { if (*NamespaceId > Private->ControllerData->Nn) { return EFI_INVALID_PARAMETER; @@ -750,15 +764,15 @@ NvmePassThruGetNextNameSpace ( if (*NamespaceId == Private->NamespaceInfo[DeviceIndex].NamespaceId) { if ((DeviceIndex + 1) < Private->ActiveNamespaceNum) { *NamespaceId = Private->NamespaceInfo[DeviceIndex + 1].NamespaceId; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } + break; } } } return Status; - } /** @@ -795,15 +809,15 @@ NvmePassThruGetNextNameSpace ( EFI_STATUS EFIAPI NvmePassThru ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_STATUS Status; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_STATUS Status; - if (This == NULL || Packet == NULL) { + if ((This == NULL) || (Packet == NULL)) { return EFI_INVALID_PARAMETER; } @@ -812,7 +826,8 @@ NvmePassThru ( // Check NamespaceId is valid or not. // if ((NamespaceId > Private->ControllerData->Nn) && - (NamespaceId != (UINT32) -1)) { + (NamespaceId != (UINT32)-1)) + { return EFI_INVALID_PARAMETER; } @@ -823,6 +838,4 @@ NvmePassThru ( ); return Status; - } - diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.h b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.h index 00e8f0abda..080e785126 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiPassThru.h @@ -11,8 +11,6 @@ #ifndef _NVM_EXPRESS_PEI_PASSTHRU_H_ #define _NVM_EXPRESS_PEI_PASSTHRU_H_ - - /** Sends an NVM Express Command Packet to an NVM Express controller or namespace. This function only supports blocking execution of the command. @@ -46,9 +44,9 @@ **/ EFI_STATUS NvmePassThruExecute ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet ); /** @@ -71,9 +69,9 @@ NvmePassThruExecute ( EFI_STATUS EFIAPI NvmePassThruGetDevicePath ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - OUT UINTN *DevicePathLength, - OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + OUT UINTN *DevicePathLength, + OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -115,8 +113,8 @@ NvmePassThruGetDevicePath ( EFI_STATUS EFIAPI NvmePassThruGetNextNameSpace ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - IN OUT UINT32 *NamespaceId + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + IN OUT UINT32 *NamespaceId ); /** @@ -153,9 +151,9 @@ NvmePassThruGetNextNameSpace ( EFI_STATUS EFIAPI NvmePassThru ( - IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, - IN UINT32 NamespaceId, - IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet + IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, + IN UINT32 NamespaceId, + IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet ); #endif diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c index f409285d54..d704c62eaa 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c @@ -26,18 +26,18 @@ **/ BOOLEAN NvmeS3SkipThisController ( - IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, - IN UINTN HcDevicePathLength + IN EFI_DEVICE_PATH_PROTOCOL *HcDevicePath, + IN UINTN HcDevicePathLength ) { - EFI_STATUS Status; - UINT8 DummyData; - UINTN S3InitDevicesLength; - EFI_DEVICE_PATH_PROTOCOL *S3InitDevices; - EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; - UINTN DevicePathInstLength; - BOOLEAN EntireEnd; - BOOLEAN Skip; + EFI_STATUS Status; + UINT8 DummyData; + UINTN S3InitDevicesLength; + EFI_DEVICE_PATH_PROTOCOL *S3InitDevices; + EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; + UINTN DevicePathInstLength; + BOOLEAN EntireEnd; + BOOLEAN Skip; // // From the LockBox, get the list of device paths for devices need to be @@ -47,7 +47,7 @@ NvmeS3SkipThisController ( S3InitDevicesLength = sizeof (DummyData); EntireEnd = FALSE; Skip = TRUE; - Status = RestoreLockBox (&gS3StorageDeviceInitListGuid, &DummyData, &S3InitDevicesLength); + Status = RestoreLockBox (&gS3StorageDeviceInitListGuid, &DummyData, &S3InitDevicesLength); if (Status != EFI_BUFFER_TOO_SMALL) { return Skip; } else { @@ -83,7 +83,7 @@ NvmeS3SkipThisController ( } DevicePathInst = S3InitDevices; - S3InitDevices = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN) S3InitDevices + DevicePathInstLength); + S3InitDevices = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)S3InitDevices + DevicePathInstLength); if (HcDevicePathLength >= DevicePathInstLength) { continue; @@ -97,7 +97,8 @@ NvmeS3SkipThisController ( DevicePathInst, HcDevicePath, HcDevicePathLength - sizeof (EFI_DEVICE_PATH_PROTOCOL) - ) == 0) { + ) == 0) + { Skip = FALSE; break; } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.c index 094d61bb8a..d45487efed 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.c @@ -47,27 +47,27 @@ **/ EFI_STATUS TrustTransferNvmeDevice ( - IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, - IN OUT VOID *Buffer, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN TransferLength, - IN BOOLEAN IsTrustSend, - IN UINT64 Timeout, - OUT UINTN *TransferLengthOut + IN PEI_NVME_CONTROLLER_PRIVATE_DATA *Private, + IN OUT VOID *Buffer, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN TransferLength, + IN BOOLEAN IsTrustSend, + IN UINT64 Timeout, + OUT UINTN *TransferLengthOut ) { - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - EFI_STATUS Status; - UINT16 SpecificData; - EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *NvmePassThru; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + EFI_STATUS Status; + UINT16 SpecificData; + EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *NvmePassThru; NvmePassThru = &Private->NvmePassThruPpi; - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; @@ -103,10 +103,10 @@ TrustTransferNvmeDevice ( ); if (!IsTrustSend) { - if (EFI_ERROR (Status)) { + if (EFI_ERROR (Status)) { *TransferLengthOut = 0; } else { - *TransferLengthOut = (UINTN) TransferLength; + *TransferLengthOut = (UINTN)TransferLength; } } @@ -126,17 +126,17 @@ TrustTransferNvmeDevice ( EFI_STATUS EFIAPI NvmeStorageSecurityGetDeviceNo ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - OUT UINTN *NumberofDevices + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + OUT UINTN *NumberofDevices ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || NumberofDevices == NULL) { + if ((This == NULL) || (NumberofDevices == NULL)) { return EFI_INVALID_PARAMETER; } - Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_STROAGE_SECURITY (This); + Private = GET_NVME_PEIM_HC_PRIVATE_DATA_FROM_THIS_STROAGE_SECURITY (This); *NumberofDevices = Private->ActiveNamespaceNum; return EFI_SUCCESS; @@ -176,9 +176,9 @@ NvmeStorageSecurityGetDevicePath ( OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - if (This == NULL || DevicePathLength == NULL || DevicePath == NULL) { + if ((This == NULL) || (DevicePathLength == NULL) || (DevicePath == NULL)) { return EFI_INVALID_PARAMETER; } @@ -295,8 +295,8 @@ NvmeStorageSecurityReceiveData ( OUT UINTN *PayloadTransferSize ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_STATUS Status; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_STATUS Status; if ((PayloadBuffer == NULL) || (PayloadTransferSize == NULL) || (PayloadBufferSize == 0)) { return EFI_INVALID_PARAMETER; @@ -394,8 +394,8 @@ NvmeStorageSecuritySendData ( IN VOID *PayloadBuffer ) { - PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; - EFI_STATUS Status; + PEI_NVME_CONTROLLER_PRIVATE_DATA *Private; + EFI_STATUS Status; if ((PayloadBuffer == NULL) && (PayloadBufferSize != 0)) { return EFI_INVALID_PARAMETER; diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.h b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.h index 18f3e1ce26..16351882ef 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.h +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiStorageSecurity.h @@ -24,8 +24,8 @@ EFI_STATUS EFIAPI NvmeStorageSecurityGetDeviceNo ( - IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, - OUT UINTN *NumberofDevices + IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, + OUT UINTN *NumberofDevices ); /** diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.c index ff2a2314fa..a7118cc16c 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.c @@ -20,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gPciBusComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPciBusComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) PciBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) PciBusComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPciBusComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)PciBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)PciBusComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPciBusDriverNameTable[] = { - { "eng;en", (CHAR16 *) L"PCI Bus Driver" }, - { NULL , NULL } +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mPciBusDriverNameTable[] = { + { "eng;en", (CHAR16 *)L"PCI Bus Driver" }, + { NULL, NULL } }; /** @@ -159,11 +158,11 @@ PciBusComponentNameGetDriverName ( EFI_STATUS EFIAPI PciBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.h b/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.h index b211391b35..0e46a13b42 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/ComponentName.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _EFI_PCI_BUS_COMPONENT_NAME_H_ #define _EFI_PCI_BUS_COMPONENT_NAME_H_ @@ -16,6 +15,7 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gPciBusComponentName2; // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -63,7 +63,6 @@ PciBusComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -135,12 +134,11 @@ PciBusComponentNameGetDriverName ( EFI_STATUS EFIAPI PciBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); - #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c index 64284ac825..337b2090d9 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c @@ -18,7 +18,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // PCI Bus Driver Global Variables // -EFI_DRIVER_BINDING_PROTOCOL gPciBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gPciBusDriverBinding = { PciBusDriverBindingSupported, PciBusDriverBindingStart, PciBusDriverBindingStop, @@ -29,17 +29,17 @@ EFI_DRIVER_BINDING_PROTOCOL gPciBusDriverBinding = { EFI_HANDLE gPciHostBrigeHandles[PCI_MAX_HOST_BRIDGE_NUM]; EFI_INCOMPATIBLE_PCI_DEVICE_SUPPORT_PROTOCOL *gIncompatiblePciDeviceSupport = NULL; -UINTN gPciHostBridgeNumber = 0; -BOOLEAN gFullEnumeration = TRUE; -UINT64 gAllOne = 0xFFFFFFFFFFFFFFFFULL; -UINT64 gAllZero = 0; +UINTN gPciHostBridgeNumber = 0; +BOOLEAN gFullEnumeration = TRUE; +UINT64 gAllOne = 0xFFFFFFFFFFFFFFFFULL; +UINT64 gAllZero = 0; -EFI_PCI_PLATFORM_PROTOCOL *gPciPlatformProtocol; -EFI_PCI_OVERRIDE_PROTOCOL *gPciOverrideProtocol; -EDKII_IOMMU_PROTOCOL *mIoMmuProtocol; -EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; +EFI_PCI_PLATFORM_PROTOCOL *gPciPlatformProtocol; +EFI_PCI_OVERRIDE_PROTOCOL *gPciOverrideProtocol; +EDKII_IOMMU_PROTOCOL *mIoMmuProtocol; +EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_PCI_HOTPLUG_REQUEST_PROTOCOL mPciHotPlugRequest = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_PCI_HOTPLUG_REQUEST_PROTOCOL mPciHotPlugRequest = { PciHotPlugRequestNotify }; @@ -61,8 +61,8 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_PCI_HOTPLUG_REQUEST_PROTOCOL mPciHotPlugReques EFI_STATUS EFIAPI PciBusEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; @@ -119,15 +119,15 @@ PciBusEntryPoint ( EFI_STATUS EFIAPI PciBusDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - EFI_DEV_PATH_PTR Node; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_DEV_PATH_PTR Node; // // Check RemainingDevicePath validation @@ -143,9 +143,10 @@ PciBusDriverBindingSupported ( // check its validation // Node.DevPath = RemainingDevicePath; - if (Node.DevPath->Type != HARDWARE_DEVICE_PATH || - Node.DevPath->SubType != HW_PCI_DP || - DevicePathNodeLength(Node.DevPath) != sizeof(PCI_DEVICE_PATH)) { + if ((Node.DevPath->Type != HARDWARE_DEVICE_PATH) || + (Node.DevPath->SubType != HW_PCI_DP) || + (DevicePathNodeLength (Node.DevPath) != sizeof (PCI_DEVICE_PATH))) + { return EFI_UNSUPPORTED; } } @@ -157,7 +158,7 @@ PciBusDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -174,11 +175,11 @@ PciBusDriverBindingSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiPciRootBridgeIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciRootBridgeIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Open the EFI Device Path protocol needed to perform the supported test @@ -186,7 +187,7 @@ PciBusDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -203,11 +204,11 @@ PciBusDriverBindingSupported ( // Close protocol, don't use device path protocol in the Support() function // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_SUCCESS; } @@ -234,9 +235,9 @@ PciBusDriverBindingStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; // // Initialize PciRootBridgeIo to suppress incorrect compiler warning. @@ -259,7 +260,7 @@ PciBusDriverBindingStart ( gBS->LocateProtocol ( &gEfiIncompatiblePciDeviceSupportProtocolGuid, NULL, - (VOID **) &gIncompatiblePciDeviceSupport + (VOID **)&gIncompatiblePciDeviceSupport ); // @@ -268,10 +269,10 @@ PciBusDriverBindingStart ( // gPciPlatformProtocol = NULL; gBS->LocateProtocol ( - &gEfiPciPlatformProtocolGuid, - NULL, - (VOID **) &gPciPlatformProtocol - ); + &gEfiPciPlatformProtocolGuid, + NULL, + (VOID **)&gPciPlatformProtocol + ); // // If PCI Platform protocol doesn't exist, try to Pci Override Protocol. @@ -279,32 +280,32 @@ PciBusDriverBindingStart ( if (gPciPlatformProtocol == NULL) { gPciOverrideProtocol = NULL; gBS->LocateProtocol ( - &gEfiPciOverrideProtocolGuid, - NULL, - (VOID **) &gPciOverrideProtocol - ); + &gEfiPciOverrideProtocolGuid, + NULL, + (VOID **)&gPciOverrideProtocol + ); } if (mIoMmuProtocol == NULL) { gBS->LocateProtocol ( - &gEdkiiIoMmuProtocolGuid, - NULL, - (VOID **) &mIoMmuProtocol - ); + &gEdkiiIoMmuProtocolGuid, + NULL, + (VOID **)&mIoMmuProtocol + ); } if (mDeviceSecurityProtocol == NULL) { gBS->LocateProtocol ( - &gEdkiiDeviceSecurityProtocolGuid, - NULL, - (VOID **) &mDeviceSecurityProtocol - ); + &gEdkiiDeviceSecurityProtocolGuid, + NULL, + (VOID **)&mDeviceSecurityProtocol + ); } if (PcdGetBool (PcdPciDisableBusEnumeration)) { gFullEnumeration = FALSE; } else { - gFullEnumeration = (BOOLEAN) ((SearchHostBridgeHandle (Controller) ? FALSE : TRUE)); + gFullEnumeration = (BOOLEAN)((SearchHostBridgeHandle (Controller) ? FALSE : TRUE)); } // @@ -313,7 +314,7 @@ PciBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -342,7 +343,7 @@ PciBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, gPciBusDriverBinding.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -399,10 +400,10 @@ PciBusDriverBindingStart ( EFI_STATUS EFIAPI PciBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -414,17 +415,17 @@ PciBusDriverBindingStop ( // Close the bus driver // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiPciRootBridgeIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciRootBridgeIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); DestroyRootBridgeByHandle ( Controller @@ -440,7 +441,6 @@ PciBusDriverBindingStop ( AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - // // De register all the pci device // @@ -457,4 +457,3 @@ PciBusDriverBindingStop ( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h index a619a68526..4b58c3ea9b 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _EFI_PCI_BUS_H_ #define _EFI_PCI_BUS_H_ @@ -44,15 +43,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -typedef struct _PCI_IO_DEVICE PCI_IO_DEVICE; -typedef struct _PCI_BAR PCI_BAR; +typedef struct _PCI_IO_DEVICE PCI_IO_DEVICE; +typedef struct _PCI_BAR PCI_BAR; #define EFI_PCI_RID(Bus, Device, Function) (((UINT32)Bus << 8) + ((UINT32)Device << 3) + (UINT32)Function) #define EFI_PCI_BUS_OF_RID(RID) ((UINT32)RID >> 8) -#define EFI_PCI_IOV_POLICY_ARI 0x0001 -#define EFI_PCI_IOV_POLICY_SRIOV 0x0002 -#define EFI_PCI_IOV_POLICY_MRIOV 0x0004 +#define EFI_PCI_IOV_POLICY_ARI 0x0001 +#define EFI_PCI_IOV_POLICY_SRIOV 0x0002 +#define EFI_PCI_IOV_POLICY_MRIOV 0x0004 typedef enum { PciBarTypeUnknown = 0, @@ -81,11 +80,11 @@ typedef enum { #include "PciHotPlugSupport.h" #include "PciLib.h" -#define VGABASE1 0x3B0 -#define VGALIMIT1 0x3BB +#define VGABASE1 0x3B0 +#define VGALIMIT1 0x3BB -#define VGABASE2 0x3C0 -#define VGALIMIT2 0x3DF +#define VGABASE2 0x3C0 +#define VGALIMIT2 0x3DF #define ISABASE 0x100 #define ISALIMIT 0x3FF @@ -94,63 +93,63 @@ typedef enum { // PCI BAR parameters // struct _PCI_BAR { - UINT64 BaseAddress; - UINT64 Length; - UINT64 Alignment; - PCI_BAR_TYPE BarType; - BOOLEAN BarTypeFixed; - UINT16 Offset; + UINT64 BaseAddress; + UINT64 Length; + UINT64 Alignment; + PCI_BAR_TYPE BarType; + BOOLEAN BarTypeFixed; + UINT16 Offset; }; // // defined in PCI Card Specification, 8.0 // -#define PCI_CARD_MEMORY_BASE_0 0x1C -#define PCI_CARD_MEMORY_LIMIT_0 0x20 -#define PCI_CARD_MEMORY_BASE_1 0x24 -#define PCI_CARD_MEMORY_LIMIT_1 0x28 -#define PCI_CARD_IO_BASE_0_LOWER 0x2C -#define PCI_CARD_IO_BASE_0_UPPER 0x2E -#define PCI_CARD_IO_LIMIT_0_LOWER 0x30 -#define PCI_CARD_IO_LIMIT_0_UPPER 0x32 -#define PCI_CARD_IO_BASE_1_LOWER 0x34 -#define PCI_CARD_IO_BASE_1_UPPER 0x36 -#define PCI_CARD_IO_LIMIT_1_LOWER 0x38 -#define PCI_CARD_IO_LIMIT_1_UPPER 0x3A -#define PCI_CARD_BRIDGE_CONTROL 0x3E - -#define PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE BIT8 -#define PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE BIT9 - -#define RB_IO_RANGE 1 -#define RB_MEM32_RANGE 2 -#define RB_PMEM32_RANGE 3 -#define RB_MEM64_RANGE 4 -#define RB_PMEM64_RANGE 5 - -#define PPB_BAR_0 0 -#define PPB_BAR_1 1 -#define PPB_IO_RANGE 2 -#define PPB_MEM32_RANGE 3 -#define PPB_PMEM32_RANGE 4 -#define PPB_PMEM64_RANGE 5 -#define PPB_MEM64_RANGE 0xFF - -#define P2C_BAR_0 0 -#define P2C_MEM_1 1 -#define P2C_MEM_2 2 -#define P2C_IO_1 3 -#define P2C_IO_2 4 - -#define EFI_BRIDGE_IO32_DECODE_SUPPORTED 0x0001 -#define EFI_BRIDGE_PMEM32_DECODE_SUPPORTED 0x0002 -#define EFI_BRIDGE_PMEM64_DECODE_SUPPORTED 0x0004 -#define EFI_BRIDGE_IO16_DECODE_SUPPORTED 0x0008 -#define EFI_BRIDGE_PMEM_MEM_COMBINE_SUPPORTED 0x0010 -#define EFI_BRIDGE_MEM64_DECODE_SUPPORTED 0x0020 -#define EFI_BRIDGE_MEM32_DECODE_SUPPORTED 0x0040 - -#define PCI_MAX_HOST_BRIDGE_NUM 0x0010 +#define PCI_CARD_MEMORY_BASE_0 0x1C +#define PCI_CARD_MEMORY_LIMIT_0 0x20 +#define PCI_CARD_MEMORY_BASE_1 0x24 +#define PCI_CARD_MEMORY_LIMIT_1 0x28 +#define PCI_CARD_IO_BASE_0_LOWER 0x2C +#define PCI_CARD_IO_BASE_0_UPPER 0x2E +#define PCI_CARD_IO_LIMIT_0_LOWER 0x30 +#define PCI_CARD_IO_LIMIT_0_UPPER 0x32 +#define PCI_CARD_IO_BASE_1_LOWER 0x34 +#define PCI_CARD_IO_BASE_1_UPPER 0x36 +#define PCI_CARD_IO_LIMIT_1_LOWER 0x38 +#define PCI_CARD_IO_LIMIT_1_UPPER 0x3A +#define PCI_CARD_BRIDGE_CONTROL 0x3E + +#define PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE BIT8 +#define PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE BIT9 + +#define RB_IO_RANGE 1 +#define RB_MEM32_RANGE 2 +#define RB_PMEM32_RANGE 3 +#define RB_MEM64_RANGE 4 +#define RB_PMEM64_RANGE 5 + +#define PPB_BAR_0 0 +#define PPB_BAR_1 1 +#define PPB_IO_RANGE 2 +#define PPB_MEM32_RANGE 3 +#define PPB_PMEM32_RANGE 4 +#define PPB_PMEM64_RANGE 5 +#define PPB_MEM64_RANGE 0xFF + +#define P2C_BAR_0 0 +#define P2C_MEM_1 1 +#define P2C_MEM_2 2 +#define P2C_IO_1 3 +#define P2C_IO_2 4 + +#define EFI_BRIDGE_IO32_DECODE_SUPPORTED 0x0001 +#define EFI_BRIDGE_PMEM32_DECODE_SUPPORTED 0x0002 +#define EFI_BRIDGE_PMEM64_DECODE_SUPPORTED 0x0004 +#define EFI_BRIDGE_IO16_DECODE_SUPPORTED 0x0008 +#define EFI_BRIDGE_PMEM_MEM_COMBINE_SUPPORTED 0x0010 +#define EFI_BRIDGE_MEM64_DECODE_SUPPORTED 0x0020 +#define EFI_BRIDGE_MEM32_DECODE_SUPPORTED 0x0040 + +#define PCI_MAX_HOST_BRIDGE_NUM 0x0010 // // Define option for attribute @@ -158,130 +157,130 @@ struct _PCI_BAR { #define EFI_SET_SUPPORTS 0 #define EFI_SET_ATTRIBUTES 1 -#define PCI_IO_DEVICE_SIGNATURE SIGNATURE_32 ('p', 'c', 'i', 'o') +#define PCI_IO_DEVICE_SIGNATURE SIGNATURE_32 ('p', 'c', 'i', 'o') struct _PCI_IO_DEVICE { - UINT32 Signature; - EFI_HANDLE Handle; - EFI_PCI_IO_PROTOCOL PciIo; - LIST_ENTRY Link; + UINT32 Signature; + EFI_HANDLE Handle; + EFI_PCI_IO_PROTOCOL PciIo; + LIST_ENTRY Link; - EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL PciDriverOverride; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - EFI_LOAD_FILE2_PROTOCOL LoadFile2; + EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL PciDriverOverride; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_LOAD_FILE2_PROTOCOL LoadFile2; // // PCI configuration space header type // - PCI_TYPE00 Pci; + PCI_TYPE00 Pci; // // Bus number, Device number, Function number // - UINT8 BusNumber; - UINT8 DeviceNumber; - UINT8 FunctionNumber; + UINT8 BusNumber; + UINT8 DeviceNumber; + UINT8 FunctionNumber; // // BAR for this PCI Device // - PCI_BAR PciBar[PCI_MAX_BAR]; + PCI_BAR PciBar[PCI_MAX_BAR]; // // The bridge device this pci device is subject to // - PCI_IO_DEVICE *Parent; + PCI_IO_DEVICE *Parent; // // A linked list for children Pci Device if it is bridge device // - LIST_ENTRY ChildList; + LIST_ENTRY ChildList; // // TRUE if the PCI bus driver creates the handle for this PCI device // - BOOLEAN Registered; + BOOLEAN Registered; // // TRUE if the PCI bus driver successfully allocates the resource required by // this PCI device // - BOOLEAN Allocated; + BOOLEAN Allocated; // // The attribute this PCI device currently set // - UINT64 Attributes; + UINT64 Attributes; // // The attributes this PCI device actually supports // - UINT64 Supports; + UINT64 Supports; // // The resource decode the bridge supports // - UINT32 Decodes; + UINT32 Decodes; // // TRUE if the ROM image is from the PCI Option ROM BAR // - BOOLEAN EmbeddedRom; + BOOLEAN EmbeddedRom; // // The OptionRom Size // - UINT32 RomSize; + UINT32 RomSize; // // TRUE if all OpROM (in device or in platform specific position) have been processed // - BOOLEAN AllOpRomProcessed; + BOOLEAN AllOpRomProcessed; // // TRUE if there is any EFI driver in the OptionRom // - BOOLEAN BusOverride; + BOOLEAN BusOverride; // // A list tracking reserved resource on a bridge device // - LIST_ENTRY ReservedResourceList; + LIST_ENTRY ReservedResourceList; // // A list tracking image handle of platform specific overriding driver // - LIST_ENTRY OptionRomDriverList; + LIST_ENTRY OptionRomDriverList; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ResourcePaddingDescriptors; - EFI_HPC_PADDING_ATTRIBUTES PaddingAttributes; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ResourcePaddingDescriptors; + EFI_HPC_PADDING_ATTRIBUTES PaddingAttributes; // // Bus number ranges for a PCI Root Bridge device // - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BusNumberRanges; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BusNumberRanges; - BOOLEAN IsPciExp; + BOOLEAN IsPciExp; // // For SR-IOV // - UINT8 PciExpressCapabilityOffset; - UINT32 AriCapabilityOffset; - UINT32 SrIovCapabilityOffset; - UINT32 MrIovCapabilityOffset; - PCI_BAR VfPciBar[PCI_MAX_BAR]; - UINT32 SystemPageSize; - UINT16 InitialVFs; - UINT16 ReservedBusNum; + UINT8 PciExpressCapabilityOffset; + UINT32 AriCapabilityOffset; + UINT32 SrIovCapabilityOffset; + UINT32 MrIovCapabilityOffset; + PCI_BAR VfPciBar[PCI_MAX_BAR]; + UINT32 SystemPageSize; + UINT16 InitialVFs; + UINT16 ReservedBusNum; // // Per PCI to PCI Bridge spec, I/O window is 4K aligned, // but some chipsets support non-standard I/O window alignments less than 4K. // This field is used to support this case. // - UINT16 BridgeIoAlignment; - UINT32 ResizableBarOffset; - UINT32 ResizableBarNumber; + UINT16 BridgeIoAlignment; + UINT32 ResizableBarOffset; + UINT32 ResizableBarNumber; }; #define PCI_IO_DEVICE_FROM_PCI_IO_THIS(a) \ @@ -296,24 +295,22 @@ struct _PCI_IO_DEVICE { #define PCI_IO_DEVICE_FROM_LOAD_FILE2_THIS(a) \ CR (a, PCI_IO_DEVICE, LoadFile2, PCI_IO_DEVICE_SIGNATURE) - - // // Global Variables // -extern EFI_INCOMPATIBLE_PCI_DEVICE_SUPPORT_PROTOCOL *gIncompatiblePciDeviceSupport; -extern EFI_DRIVER_BINDING_PROTOCOL gPciBusDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gPciBusComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gPciBusComponentName2; -extern BOOLEAN gFullEnumeration; -extern UINTN gPciHostBridgeNumber; -extern EFI_HANDLE gPciHostBrigeHandles[PCI_MAX_HOST_BRIDGE_NUM]; -extern UINT64 gAllOne; -extern UINT64 gAllZero; -extern EFI_PCI_PLATFORM_PROTOCOL *gPciPlatformProtocol; -extern EFI_PCI_OVERRIDE_PROTOCOL *gPciOverrideProtocol; -extern BOOLEAN mReserveIsaAliases; -extern BOOLEAN mReserveVgaAliases; +extern EFI_INCOMPATIBLE_PCI_DEVICE_SUPPORT_PROTOCOL *gIncompatiblePciDeviceSupport; +extern EFI_DRIVER_BINDING_PROTOCOL gPciBusDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gPciBusComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gPciBusComponentName2; +extern BOOLEAN gFullEnumeration; +extern UINTN gPciHostBridgeNumber; +extern EFI_HANDLE gPciHostBrigeHandles[PCI_MAX_HOST_BRIDGE_NUM]; +extern UINT64 gAllOne; +extern UINT64 gAllZero; +extern EFI_PCI_PLATFORM_PROTOCOL *gPciPlatformProtocol; +extern EFI_PCI_OVERRIDE_PROTOCOL *gPciOverrideProtocol; +extern BOOLEAN mReserveIsaAliases; +extern BOOLEAN mReserveVgaAliases; /** Macro that checks whether device is a GFX device. @@ -324,7 +321,7 @@ extern BOOLEAN mReserveVgaAliases; @retval FALSE Device is not a GFX device. **/ -#define IS_PCI_GFX(_p) IS_CLASS2 (_p, PCI_CLASS_DISPLAY, PCI_CLASS_DISPLAY_OTHER) +#define IS_PCI_GFX(_p) IS_CLASS2 (_p, PCI_CLASS_DISPLAY, PCI_CLASS_DISPLAY_OTHER) /** Test to see if this driver supports ControllerHandle. Any ControllerHandle @@ -343,9 +340,9 @@ extern BOOLEAN mReserveVgaAliases; EFI_STATUS EFIAPI PciBusDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -365,9 +362,9 @@ PciBusDriverBindingSupported ( EFI_STATUS EFIAPI PciBusDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -387,10 +384,10 @@ PciBusDriverBindingStart ( EFI_STATUS EFIAPI PciBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c index 6283d60220..ba4b099bc5 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.c @@ -22,19 +22,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PciOperateRegister ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 Command, - IN UINT8 Offset, - IN UINT8 Operation, - OUT UINT16 *PtrCommand + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 Command, + IN UINT8 Offset, + IN UINT8 Operation, + OUT UINT16 *PtrCommand ) { - UINT16 OldCommand; - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 OldCommand; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; - OldCommand = 0; - PciIo = &PciIoDevice->PciIo; + OldCommand = 0; + PciIo = &PciIoDevice->PciIo; if (Operation != EFI_SET_REGISTER) { Status = PciIo->Pci.Read ( @@ -52,9 +52,9 @@ PciOperateRegister ( } if (Operation == EFI_ENABLE_REGISTER) { - OldCommand = (UINT16) (OldCommand | Command); + OldCommand = (UINT16)(OldCommand | Command); } else if (Operation == EFI_DISABLE_REGISTER) { - OldCommand = (UINT16) (OldCommand & ~(Command)); + OldCommand = (UINT16)(OldCommand & ~(Command)); } else { OldCommand = Command; } @@ -124,10 +124,8 @@ LocateCapabilityRegBlock ( if (*Offset != 0) { CapabilityPtr = *Offset; } else { - CapabilityPtr = 0; if (IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) { - PciIoDevice->PciIo.Pci.Read ( &PciIoDevice->PciIo, EfiPciIoWidthUint8, @@ -136,7 +134,6 @@ LocateCapabilityRegBlock ( &CapabilityPtr ); } else { - PciIoDevice->PciIo.Pci.Read ( &PciIoDevice->PciIo, EfiPciIoWidthUint8, @@ -156,12 +153,12 @@ LocateCapabilityRegBlock ( &CapabilityEntry ); - CapabilityID = (UINT8) CapabilityEntry; + CapabilityID = (UINT8)CapabilityEntry; if (CapabilityID == CapId) { *Offset = CapabilityPtr; if (NextRegBlock != NULL) { - *NextRegBlock = (UINT8) (CapabilityEntry >> 8); + *NextRegBlock = (UINT8)(CapabilityEntry >> 8); } return EFI_SUCCESS; @@ -171,11 +168,11 @@ LocateCapabilityRegBlock ( // Certain PCI device may incorrectly have capability pointing to itself, // break to avoid dead loop. // - if (CapabilityPtr == (UINT8) (CapabilityEntry >> 8)) { + if (CapabilityPtr == (UINT8)(CapabilityEntry >> 8)) { break; } - CapabilityPtr = (UINT8) (CapabilityEntry >> 8); + CapabilityPtr = (UINT8)(CapabilityEntry >> 8); } return EFI_NOT_FOUND; @@ -196,16 +193,16 @@ LocateCapabilityRegBlock ( **/ EFI_STATUS LocatePciExpressCapabilityRegBlock ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 CapId, - IN OUT UINT32 *Offset, - OUT UINT32 *NextRegBlock OPTIONAL + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 CapId, + IN OUT UINT32 *Offset, + OUT UINT32 *NextRegBlock OPTIONAL ) { - EFI_STATUS Status; - UINT32 CapabilityPtr; - UINT32 CapabilityEntry; - UINT16 CapabilityID; + EFI_STATUS Status; + UINT32 CapabilityPtr; + UINT32 CapabilityEntry; + UINT16 CapabilityID; // // To check the capability of this device supports @@ -225,13 +222,13 @@ LocatePciExpressCapabilityRegBlock ( // Mask it to DWORD alignment per PCI spec // CapabilityPtr &= 0xFFC; - Status = PciIoDevice->PciIo.Pci.Read ( - &PciIoDevice->PciIo, - EfiPciIoWidthUint32, - CapabilityPtr, - 1, - &CapabilityEntry - ); + Status = PciIoDevice->PciIo.Pci.Read ( + &PciIoDevice->PciIo, + EfiPciIoWidthUint32, + CapabilityPtr, + 1, + &CapabilityEntry + ); if (EFI_ERROR (Status)) { break; } @@ -249,7 +246,7 @@ LocatePciExpressCapabilityRegBlock ( break; } - CapabilityID = (UINT16) CapabilityEntry; + CapabilityID = (UINT16)CapabilityEntry; if (CapabilityID == CapId) { *Offset = CapabilityPtr; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h index cf9903270d..1822afea97 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciCommand.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _EFI_PCI_COMMAND_H_ #define _EFI_PCI_COMMAND_H_ @@ -16,7 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // They should be cleared at the beginning. The other registers // are owned by chipset, we should not touch them. // -#define EFI_PCI_COMMAND_BITS_OWNED ( \ +#define EFI_PCI_COMMAND_BITS_OWNED ( \ EFI_PCI_COMMAND_IO_SPACE | \ EFI_PCI_COMMAND_MEMORY_SPACE | \ EFI_PCI_COMMAND_BUS_MASTER | \ @@ -31,7 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // They should be cleared at the beginning. The other registers // are owned by chipset, we should not touch them. // -#define EFI_PCI_BRIDGE_CONTROL_BITS_OWNED ( \ +#define EFI_PCI_BRIDGE_CONTROL_BITS_OWNED ( \ EFI_PCI_BRIDGE_CONTROL_ISA | \ EFI_PCI_BRIDGE_CONTROL_VGA | \ EFI_PCI_BRIDGE_CONTROL_VGA_16 | \ @@ -44,13 +43,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // They should be cleared at the beginning. The other registers // are owned by chipset, we should not touch them. // -#define EFI_PCCARD_BRIDGE_CONTROL_BITS_OWNED ( \ +#define EFI_PCCARD_BRIDGE_CONTROL_BITS_OWNED ( \ EFI_PCI_BRIDGE_CONTROL_ISA | \ EFI_PCI_BRIDGE_CONTROL_VGA | \ EFI_PCI_BRIDGE_CONTROL_FAST_BACK_TO_BACK \ ) - #define EFI_GET_REGISTER 1 #define EFI_SET_REGISTER 2 #define EFI_ENABLE_REGISTER 3 @@ -70,11 +68,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PciOperateRegister ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 Command, - IN UINT8 Offset, - IN UINT8 Operation, - OUT UINT16 *PtrCommand + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 Command, + IN UINT8 Offset, + IN UINT8 Operation, + OUT UINT16 *PtrCommand ); /** @@ -127,10 +125,10 @@ LocateCapabilityRegBlock ( **/ EFI_STATUS LocatePciExpressCapabilityRegBlock ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 CapId, - IN OUT UINT32 *Offset, - OUT UINT32 *NextRegBlock OPTIONAL + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 CapId, + IN OUT UINT32 *Offset, + OUT UINT32 *NextRegBlock OPTIONAL ); /** @@ -142,7 +140,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_READ_COMMAND_REGISTER(a,b) \ +#define PCI_READ_COMMAND_REGISTER(a, b) \ PciOperateRegister (a, 0, PCI_COMMAND_OFFSET, EFI_GET_REGISTER, b) /** @@ -154,7 +152,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_SET_COMMAND_REGISTER(a,b) \ +#define PCI_SET_COMMAND_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_COMMAND_OFFSET, EFI_SET_REGISTER, NULL) /** @@ -166,7 +164,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_ENABLE_COMMAND_REGISTER(a,b) \ +#define PCI_ENABLE_COMMAND_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_COMMAND_OFFSET, EFI_ENABLE_REGISTER, NULL) /** @@ -178,7 +176,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_DISABLE_COMMAND_REGISTER(a,b) \ +#define PCI_DISABLE_COMMAND_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_COMMAND_OFFSET, EFI_DISABLE_REGISTER, NULL) /** @@ -190,7 +188,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_READ_BRIDGE_CONTROL_REGISTER(a,b) \ +#define PCI_READ_BRIDGE_CONTROL_REGISTER(a, b) \ PciOperateRegister (a, 0, PCI_BRIDGE_CONTROL_REGISTER_OFFSET, EFI_GET_REGISTER, b) /** @@ -202,7 +200,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_SET_BRIDGE_CONTROL_REGISTER(a,b) \ +#define PCI_SET_BRIDGE_CONTROL_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_BRIDGE_CONTROL_REGISTER_OFFSET, EFI_SET_REGISTER, NULL) /** @@ -214,7 +212,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_ENABLE_BRIDGE_CONTROL_REGISTER(a,b) \ +#define PCI_ENABLE_BRIDGE_CONTROL_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_BRIDGE_CONTROL_REGISTER_OFFSET, EFI_ENABLE_REGISTER, NULL) /** @@ -226,7 +224,7 @@ LocatePciExpressCapabilityRegBlock ( @return status of PciIo operation **/ -#define PCI_DISABLE_BRIDGE_CONTROL_REGISTER(a,b) \ +#define PCI_DISABLE_BRIDGE_CONTROL_REGISTER(a, b) \ PciOperateRegister (a, b, PCI_BRIDGE_CONTROL_REGISTER_OFFSET, EFI_DISABLE_REGISTER, NULL) #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.c index 292dd25da8..581e9075ad 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.c @@ -35,7 +35,7 @@ InitializePciDevicePool ( **/ VOID InsertRootBridge ( - IN PCI_IO_DEVICE *RootBridge + IN PCI_IO_DEVICE *RootBridge ) { InsertTailList (&mPciDevicePool, &(RootBridge->Link)); @@ -51,8 +51,8 @@ InsertRootBridge ( **/ VOID InsertPciDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_IO_DEVICE *PciDeviceNode + IN PCI_IO_DEVICE *Bridge, + IN PCI_IO_DEVICE *PciDeviceNode ) { InsertTailList (&Bridge->ChildList, &(PciDeviceNode->Link)); @@ -67,7 +67,7 @@ InsertPciDevice ( **/ VOID DestroyRootBridge ( - IN PCI_IO_DEVICE *RootBridge + IN PCI_IO_DEVICE *RootBridge ) { DestroyPciDeviceTree (RootBridge); @@ -85,7 +85,7 @@ DestroyRootBridge ( **/ VOID FreePciDevice ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { ASSERT (PciIoDevice != NULL); @@ -116,14 +116,13 @@ FreePciDevice ( **/ VOID DestroyPciDeviceTree ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; while (!IsListEmpty (&Bridge->ChildList)) { - CurrentLink = Bridge->ChildList.ForwardLink; // @@ -156,12 +155,11 @@ DestroyPciDeviceTree ( **/ EFI_STATUS DestroyRootBridgeByHandle ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ) { - - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; CurrentLink = mPciDevicePool.ForwardLink; @@ -169,7 +167,6 @@ DestroyRootBridgeByHandle ( Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (Temp->Handle == Controller) { - RemoveEntryList (CurrentLink); DestroyPciDeviceTree (Temp); @@ -202,17 +199,17 @@ DestroyRootBridgeByHandle ( **/ EFI_STATUS RegisterPciDevice ( - IN EFI_HANDLE Controller, - IN PCI_IO_DEVICE *PciIoDevice, - OUT EFI_HANDLE *Handle OPTIONAL + IN EFI_HANDLE Controller, + IN PCI_IO_DEVICE *PciIoDevice, + OUT EFI_HANDLE *Handle OPTIONAL ) { - EFI_STATUS Status; - VOID *PlatformOpRomBuffer; - UINTN PlatformOpRomSize; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT8 Data8; - BOOLEAN HasEfiImage; + EFI_STATUS Status; + VOID *PlatformOpRomBuffer; + UINTN PlatformOpRomSize; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 Data8; + BOOLEAN HasEfiImage; // // Install the pciio protocol, device path protocol @@ -240,7 +237,6 @@ RegisterPciDevice ( // Process OpRom // if (!PciIoDevice->AllOpRomProcessed) { - // // Get the OpRom provided by platform // @@ -253,7 +249,7 @@ RegisterPciDevice ( ); if (!EFI_ERROR (Status)) { PciIoDevice->EmbeddedRom = FALSE; - PciIoDevice->RomSize = (UINT32) PlatformOpRomSize; + PciIoDevice->RomSize = (UINT32)PlatformOpRomSize; PciIoDevice->PciIo.RomSize = PlatformOpRomSize; PciIoDevice->PciIo.RomImage = PlatformOpRomBuffer; // @@ -279,7 +275,7 @@ RegisterPciDevice ( ); if (!EFI_ERROR (Status)) { PciIoDevice->EmbeddedRom = FALSE; - PciIoDevice->RomSize = (UINT32) PlatformOpRomSize; + PciIoDevice->RomSize = (UINT32)PlatformOpRomSize; PciIoDevice->PciIo.RomSize = PlatformOpRomSize; PciIoDevice->PciIo.RomImage = PlatformOpRomBuffer; // @@ -324,9 +320,7 @@ RegisterPciDevice ( } } - if (!PciIoDevice->AllOpRomProcessed) { - PciIoDevice->AllOpRomProcessed = TRUE; // @@ -374,7 +368,7 @@ RegisterPciDevice ( Status = gBS->OpenProtocol ( Controller, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &(PciIoDevice->PciRootBridgeIo), + (VOID **)&(PciIoDevice->PciRootBridgeIo), gPciBusDriverBinding.DriverBindingHandle, PciIoDevice->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -405,15 +399,14 @@ RegisterPciDevice ( **/ VOID RemoveAllPciDeviceOnBridge ( - EFI_HANDLE RootBridgeHandle, - PCI_IO_DEVICE *Bridge + EFI_HANDLE RootBridgeHandle, + PCI_IO_DEVICE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; while (!IsListEmpty (&Bridge->ChildList)) { - CurrentLink = Bridge->ChildList.ForwardLink; Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); @@ -453,22 +446,22 @@ RemoveAllPciDeviceOnBridge ( **/ EFI_STATUS DeRegisterPciDevice ( - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; - PCI_IO_DEVICE *Node; - LIST_ENTRY *CurrentLink; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *Node; + LIST_ENTRY *CurrentLink; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; Status = gBS->OpenProtocol ( Handle, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, gPciBusDriverBinding.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -488,12 +481,11 @@ DeRegisterPciDevice ( // if (!IsListEmpty (&PciIoDevice->ChildList)) { - CurrentLink = PciIoDevice->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) { - Node = PCI_IO_DEVICE_FROM_LINK (CurrentLink); - Status = DeRegisterPciDevice (Controller, Node->Handle); + Node = PCI_IO_DEVICE_FROM_LINK (CurrentLink); + Status = DeRegisterPciDevice (Controller, Node->Handle); if (EFI_ERROR (Status)) { return Status; @@ -559,22 +551,22 @@ DeRegisterPciDevice ( NULL ); } + // // Restore Status // Status = EFI_SUCCESS; } - if (EFI_ERROR (Status)) { gBS->OpenProtocol ( - Controller, - &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, - gPciBusDriverBinding.DriverBindingHandle, - Handle, - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiPciRootBridgeIoProtocolGuid, + (VOID **)&PciRootBridgeIo, + gPciBusDriverBinding.DriverBindingHandle, + Handle, + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); return Status; } @@ -586,7 +578,6 @@ DeRegisterPciDevice ( PciIoDevice->Registered = FALSE; PciIoDevice->Handle = NULL; } else { - // // Handle may be closed before // @@ -613,11 +604,11 @@ DeRegisterPciDevice ( **/ EFI_STATUS StartPciDevicesOnBridge ( - IN EFI_HANDLE Controller, - IN PCI_IO_DEVICE *RootBridge, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath, - IN OUT UINT8 *NumberOfChildren, - IN OUT EFI_HANDLE *ChildHandleBuffer + IN EFI_HANDLE Controller, + IN PCI_IO_DEVICE *RootBridge, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath, + IN OUT UINT8 *NumberOfChildren, + IN OUT EFI_HANDLE *ChildHandleBuffer ) { @@ -632,14 +623,13 @@ StartPciDevicesOnBridge ( CurrentLink = RootBridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &RootBridge->ChildList) { - PciIoDevice = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (RemainingDevicePath != NULL) { - Node.DevPath = RemainingDevicePath; - if (Node.Pci->Device != PciIoDevice->DeviceNumber || - Node.Pci->Function != PciIoDevice->FunctionNumber) { + if ((Node.Pci->Device != PciIoDevice->DeviceNumber) || + (Node.Pci->Function != PciIoDevice->FunctionNumber)) + { CurrentLink = CurrentLink->ForwardLink; continue; } @@ -661,10 +651,9 @@ StartPciDevicesOnBridge ( PciIoDevice, NULL ); - } - if (NumberOfChildren != NULL && ChildHandleBuffer != NULL && PciIoDevice->Registered) { + if ((NumberOfChildren != NULL) && (ChildHandleBuffer != NULL) && PciIoDevice->Registered) { ChildHandleBuffer[*NumberOfChildren] = PciIoDevice->Handle; (*NumberOfChildren)++; } @@ -705,15 +694,12 @@ StartPciDevicesOnBridge ( return Status; } else { - // // Currently, the PCI bus driver only support PCI-PCI bridge // return EFI_UNSUPPORTED; } - } else { - // // If remaining device path is NULL, // try to enable all the pci devices under this bridge @@ -724,10 +710,9 @@ StartPciDevicesOnBridge ( PciIoDevice, NULL ); - } - if (NumberOfChildren != NULL && ChildHandleBuffer != NULL && PciIoDevice->Registered) { + if ((NumberOfChildren != NULL) && (ChildHandleBuffer != NULL) && PciIoDevice->Registered) { ChildHandleBuffer[*NumberOfChildren] = PciIoDevice->Handle; (*NumberOfChildren)++; } @@ -754,7 +739,6 @@ StartPciDevicesOnBridge ( Supports, NULL ); - } CurrentLink = CurrentLink->ForwardLink; @@ -780,12 +764,12 @@ StartPciDevicesOnBridge ( **/ EFI_STATUS StartPciDevices ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ) { - PCI_IO_DEVICE *RootBridge; - EFI_HANDLE ThisHostBridge; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *RootBridge; + EFI_HANDLE ThisHostBridge; + LIST_ENTRY *CurrentLink; RootBridge = GetRootBridgeByHandle (Controller); ASSERT (RootBridge != NULL); @@ -794,19 +778,18 @@ StartPciDevices ( CurrentLink = mPciDevicePool.ForwardLink; while (CurrentLink != NULL && CurrentLink != &mPciDevicePool) { - RootBridge = PCI_IO_DEVICE_FROM_LINK (CurrentLink); // // Locate the right root bridge to start // if (RootBridge->PciRootBridgeIo->ParentHandle == ThisHostBridge) { StartPciDevicesOnBridge ( - RootBridge->Handle, - RootBridge, - NULL, - NULL, - NULL - ); + RootBridge->Handle, + RootBridge, + NULL, + NULL, + NULL + ); } CurrentLink = CurrentLink->ForwardLink; @@ -826,27 +809,27 @@ StartPciDevices ( **/ PCI_IO_DEVICE * CreateRootBridge ( - IN EFI_HANDLE RootBridgeHandle + IN EFI_HANDLE RootBridgeHandle ) { - EFI_STATUS Status; - PCI_IO_DEVICE *Dev; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_STATUS Status; + PCI_IO_DEVICE *Dev; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; Dev = AllocateZeroPool (sizeof (PCI_IO_DEVICE)); if (Dev == NULL) { return NULL; } - Dev->Signature = PCI_IO_DEVICE_SIGNATURE; - Dev->Handle = RootBridgeHandle; + Dev->Signature = PCI_IO_DEVICE_SIGNATURE; + Dev->Handle = RootBridgeHandle; InitializeListHead (&Dev->ChildList); Status = gBS->OpenProtocol ( RootBridgeHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, gPciBusDriverBinding.DriverBindingHandle, RootBridgeHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -868,7 +851,7 @@ CreateRootBridge ( Status = gBS->OpenProtocol ( RootBridgeHandle, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, gPciBusDriverBinding.DriverBindingHandle, RootBridgeHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -909,16 +892,15 @@ CreateRootBridge ( **/ PCI_IO_DEVICE * GetRootBridgeByHandle ( - EFI_HANDLE RootBridgeHandle + EFI_HANDLE RootBridgeHandle ) { - PCI_IO_DEVICE *RootBridgeDev; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *RootBridgeDev; + LIST_ENTRY *CurrentLink; CurrentLink = mPciDevicePool.ForwardLink; while (CurrentLink != NULL && CurrentLink != &mPciDevicePool) { - RootBridgeDev = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (RootBridgeDev->Handle == RootBridgeHandle) { return RootBridgeDev; @@ -942,18 +924,16 @@ GetRootBridgeByHandle ( **/ BOOLEAN PciDeviceExisted ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *Bridge, + IN PCI_IO_DEVICE *PciIoDevice ) { - - PCI_IO_DEVICE *Temp; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (Temp == PciIoDevice) { @@ -982,20 +962,18 @@ PciDeviceExisted ( **/ PCI_IO_DEVICE * LocateVgaDeviceOnHostBridge ( - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE HostBridgeHandle ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *PciIoDevice; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *PciIoDevice; CurrentLink = mPciDevicePool.ForwardLink; while (CurrentLink != NULL && CurrentLink != &mPciDevicePool) { - PciIoDevice = PCI_IO_DEVICE_FROM_LINK (CurrentLink); - if (PciIoDevice->PciRootBridgeIo->ParentHandle== HostBridgeHandle) { - + if (PciIoDevice->PciRootBridgeIo->ParentHandle == HostBridgeHandle) { PciIoDevice = LocateVgaDevice (PciIoDevice); if (PciIoDevice != NULL) { @@ -1019,28 +997,27 @@ LocateVgaDeviceOnHostBridge ( **/ PCI_IO_DEVICE * LocateVgaDevice ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *PciIoDevice; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *PciIoDevice; CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { - PciIoDevice = PCI_IO_DEVICE_FROM_LINK (CurrentLink); - if (IS_PCI_VGA(&PciIoDevice->Pci) && - (PciIoDevice->Attributes & - (EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY | - EFI_PCI_IO_ATTRIBUTE_VGA_IO | - EFI_PCI_IO_ATTRIBUTE_VGA_IO_16)) != 0) { + if (IS_PCI_VGA (&PciIoDevice->Pci) && + ((PciIoDevice->Attributes & + (EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY | + EFI_PCI_IO_ATTRIBUTE_VGA_IO | + EFI_PCI_IO_ATTRIBUTE_VGA_IO_16)) != 0)) + { return PciIoDevice; } if (IS_PCI_BRIDGE (&PciIoDevice->Pci)) { - PciIoDevice = LocateVgaDevice (PciIoDevice); if (PciIoDevice != NULL) { @@ -1053,4 +1030,3 @@ LocateVgaDevice ( return NULL; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.h index 3dae540da7..ca367e7b92 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDeviceSupport.h @@ -26,7 +26,7 @@ InitializePciDevicePool ( **/ VOID InsertRootBridge ( - IN PCI_IO_DEVICE *RootBridge + IN PCI_IO_DEVICE *RootBridge ); /** @@ -39,8 +39,8 @@ InsertRootBridge ( **/ VOID InsertPciDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_IO_DEVICE *PciDeviceNode + IN PCI_IO_DEVICE *Bridge, + IN PCI_IO_DEVICE *PciDeviceNode ); /** @@ -51,7 +51,7 @@ InsertPciDevice ( **/ VOID DestroyRootBridge ( - IN PCI_IO_DEVICE *RootBridge + IN PCI_IO_DEVICE *RootBridge ); /** @@ -63,7 +63,7 @@ DestroyRootBridge ( **/ VOID DestroyPciDeviceTree ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ); /** @@ -81,7 +81,7 @@ DestroyPciDeviceTree ( **/ EFI_STATUS DestroyRootBridgeByHandle ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ); /** @@ -101,9 +101,9 @@ DestroyRootBridgeByHandle ( **/ EFI_STATUS RegisterPciDevice ( - IN EFI_HANDLE Controller, - IN PCI_IO_DEVICE *PciIoDevice, - OUT EFI_HANDLE *Handle OPTIONAL + IN EFI_HANDLE Controller, + IN PCI_IO_DEVICE *PciIoDevice, + OUT EFI_HANDLE *Handle OPTIONAL ); /** @@ -116,8 +116,8 @@ RegisterPciDevice ( **/ VOID RemoveAllPciDeviceOnBridge ( - EFI_HANDLE RootBridgeHandle, - PCI_IO_DEVICE *Bridge + EFI_HANDLE RootBridgeHandle, + PCI_IO_DEVICE *Bridge ); /** @@ -135,8 +135,8 @@ RemoveAllPciDeviceOnBridge ( **/ EFI_STATUS DeRegisterPciDevice ( - IN EFI_HANDLE Controller, - IN EFI_HANDLE Handle + IN EFI_HANDLE Controller, + IN EFI_HANDLE Handle ); /** @@ -156,11 +156,11 @@ DeRegisterPciDevice ( **/ EFI_STATUS StartPciDevicesOnBridge ( - IN EFI_HANDLE Controller, - IN PCI_IO_DEVICE *RootBridge, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath, - IN OUT UINT8 *NumberOfChildren, - IN OUT EFI_HANDLE *ChildHandleBuffer + IN EFI_HANDLE Controller, + IN PCI_IO_DEVICE *RootBridge, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath, + IN OUT UINT8 *NumberOfChildren, + IN OUT EFI_HANDLE *ChildHandleBuffer ); /** @@ -175,7 +175,7 @@ StartPciDevicesOnBridge ( **/ EFI_STATUS StartPciDevices ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ); /** @@ -189,7 +189,7 @@ StartPciDevices ( **/ PCI_IO_DEVICE * CreateRootBridge ( - IN EFI_HANDLE RootBridgeHandle + IN EFI_HANDLE RootBridgeHandle ); /** @@ -203,10 +203,9 @@ CreateRootBridge ( **/ PCI_IO_DEVICE * GetRootBridgeByHandle ( - EFI_HANDLE RootBridgeHandle + EFI_HANDLE RootBridgeHandle ); - /** Judge whether Pci device existed. @@ -219,8 +218,8 @@ GetRootBridgeByHandle ( **/ BOOLEAN PciDeviceExisted ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *Bridge, + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -233,7 +232,7 @@ PciDeviceExisted ( **/ PCI_IO_DEVICE * LocateVgaDeviceOnHostBridge ( - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE HostBridgeHandle ); /** @@ -246,10 +245,9 @@ LocateVgaDeviceOnHostBridge ( **/ PCI_IO_DEVICE * LocateVgaDevice ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ); - /** Destroy a pci device node. @@ -260,7 +258,7 @@ LocateVgaDevice ( **/ VOID FreePciDevice ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.c index 3531e6b6ef..c829408bcb 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.c @@ -16,7 +16,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID InitializePciDriverOverrideInstance ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ) { PciIoDevice->PciDriverOverride.GetDriver = GetDriver; @@ -31,16 +31,16 @@ InitializePciDriverOverrideInstance ( **/ EFI_HANDLE LocateImageHandle ( - IN EFI_DEVICE_PATH_PROTOCOL *ImagePath + IN EFI_DEVICE_PATH_PROTOCOL *ImagePath ) { - EFI_STATUS Status; - EFI_HANDLE *Handles; - UINTN Index; - UINTN HandleNum; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINTN ImagePathSize; - EFI_HANDLE ImageHandle; + EFI_STATUS Status; + EFI_HANDLE *Handles; + UINTN Index; + UINTN HandleNum; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINTN ImagePathSize; + EFI_HANDLE ImageHandle; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -57,13 +57,15 @@ LocateImageHandle ( ImagePathSize = GetDevicePathSize (ImagePath); for (Index = 0; Index < HandleNum; Index++) { - Status = gBS->HandleProtocol (Handles[Index], &gEfiLoadedImageDevicePathProtocolGuid, (VOID **) &DevicePath); + Status = gBS->HandleProtocol (Handles[Index], &gEfiLoadedImageDevicePathProtocolGuid, (VOID **)&DevicePath); if (EFI_ERROR (Status)) { continue; } + if ((ImagePathSize == GetDevicePathSize (DevicePath)) && (CompareMem (ImagePath, DevicePath, ImagePathSize) == 0) - ) { + ) + { ImageHandle = Handles[Index]; break; } @@ -92,8 +94,8 @@ LocateImageHandle ( EFI_STATUS EFIAPI GetDriver ( - IN EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL *This, - IN OUT EFI_HANDLE *DriverImageHandle + IN EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL *This, + IN OUT EFI_HANDLE *DriverImageHandle ) { PCI_IO_DEVICE *PciIoDevice; @@ -103,12 +105,12 @@ GetDriver ( Override = NULL; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_DRIVER_OVERRIDE_THIS (This); - ReturnNext = (BOOLEAN) (*DriverImageHandle == NULL); + ReturnNext = (BOOLEAN)(*DriverImageHandle == NULL); for ( Link = GetFirstNode (&PciIoDevice->OptionRomDriverList) - ; !IsNull (&PciIoDevice->OptionRomDriverList, Link) - ; Link = GetNextNode (&PciIoDevice->OptionRomDriverList, Link) - ) { - + ; !IsNull (&PciIoDevice->OptionRomDriverList, Link) + ; Link = GetNextNode (&PciIoDevice->OptionRomDriverList, Link) + ) + { Override = DRIVER_OVERRIDE_FROM_LINK (Link); if (ReturnNext) { @@ -159,12 +161,12 @@ GetDriver ( **/ EFI_STATUS AddDriver ( - IN PCI_IO_DEVICE *PciIoDevice, - IN EFI_HANDLE DriverImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *DriverImagePath + IN PCI_IO_DEVICE *PciIoDevice, + IN EFI_HANDLE DriverImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *DriverImagePath ) { - PCI_DRIVER_OVERRIDE_LIST *Node; + PCI_DRIVER_OVERRIDE_LIST *Node; // // Caller should pass in either Image Handle or Image Path, but not both. @@ -182,7 +184,6 @@ AddDriver ( InsertTailList (&PciIoDevice->OptionRomDriverList, &Node->Link); - PciIoDevice->BusOverride = TRUE; + PciIoDevice->BusOverride = TRUE; return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.h index 03447a59c0..78d13d6482 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciDriverOverride.h @@ -6,23 +6,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _EFI_PCI_DRIVER_OVERRRIDE_H_ #define _EFI_PCI_DRIVER_OVERRRIDE_H_ -#define DRIVER_OVERRIDE_SIGNATURE SIGNATURE_32 ('d', 'r', 'o', 'v') +#define DRIVER_OVERRIDE_SIGNATURE SIGNATURE_32 ('d', 'r', 'o', 'v') // // PCI driver override driver image list // typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_HANDLE DriverImageHandle; - EFI_DEVICE_PATH_PROTOCOL *DriverImagePath; + UINT32 Signature; + LIST_ENTRY Link; + EFI_HANDLE DriverImageHandle; + EFI_DEVICE_PATH_PROTOCOL *DriverImagePath; } PCI_DRIVER_OVERRIDE_LIST; - #define DRIVER_OVERRIDE_FROM_LINK(a) \ CR (a, PCI_DRIVER_OVERRIDE_LIST, Link, DRIVER_OVERRIDE_SIGNATURE) @@ -34,7 +32,7 @@ typedef struct { **/ VOID InitializePciDriverOverrideInstance ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ); /** @@ -51,12 +49,11 @@ InitializePciDriverOverrideInstance ( **/ EFI_STATUS AddDriver ( - IN PCI_IO_DEVICE *PciIoDevice, - IN EFI_HANDLE DriverImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *DriverImagePath + IN PCI_IO_DEVICE *PciIoDevice, + IN EFI_HANDLE DriverImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *DriverImagePath ); - /** Uses a bus specific algorithm to retrieve a driver image handle for a controller. @@ -76,8 +73,8 @@ AddDriver ( EFI_STATUS EFIAPI GetDriver ( - IN EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL *This, - IN OUT EFI_HANDLE *DriverImageHandle + IN EFI_BUS_SPECIFIC_DRIVER_OVERRIDE_PROTOCOL *This, + IN OUT EFI_HANDLE *DriverImageHandle ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c index 99f8642f13..3f8c6e6da7 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.c @@ -22,8 +22,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PciEnumerator ( - IN EFI_HANDLE Controller, - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE Controller, + IN EFI_HANDLE HostBridgeHandle ) { EFI_STATUS Status; @@ -35,7 +35,7 @@ PciEnumerator ( Status = gBS->OpenProtocol ( HostBridgeHandle, &gEfiPciHostBridgeResourceAllocationProtocolGuid, - (VOID **) &PciResAlloc, + (VOID **)&PciResAlloc, gPciBusDriverBinding.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -117,22 +117,22 @@ PciRootBridgeEnumerator ( IN PCI_IO_DEVICE *RootBridgeDev ) { - EFI_STATUS Status; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration1; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration2; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration3; - UINT8 SubBusNumber; - UINT8 StartBusNumber; - UINT8 PaddedBusRange; - EFI_HANDLE RootBridgeHandle; - UINT8 Desc; - UINT64 AddrLen; - UINT64 AddrRangeMin; - - SubBusNumber = 0; - StartBusNumber = 0; - PaddedBusRange = 0; + EFI_STATUS Status; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration1; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration2; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration3; + UINT8 SubBusNumber; + UINT8 StartBusNumber; + UINT8 PaddedBusRange; + EFI_HANDLE RootBridgeHandle; + UINT8 Desc; + UINT64 AddrLen; + UINT64 AddrRangeMin; + + SubBusNumber = 0; + StartBusNumber = 0; + PaddedBusRange = 0; // // Get the root bridge handle @@ -151,16 +151,17 @@ PciRootBridgeEnumerator ( Status = PciResAlloc->StartBusEnumeration ( PciResAlloc, RootBridgeHandle, - (VOID **) &Configuration + (VOID **)&Configuration ); if (EFI_ERROR (Status)) { return Status; } - if (Configuration == NULL || Configuration->Desc == ACPI_END_TAG_DESCRIPTOR) { + if ((Configuration == NULL) || (Configuration->Desc == ACPI_END_TAG_DESCRIPTOR)) { return EFI_INVALID_PARAMETER; } + RootBridgeDev->BusNumberRanges = Configuration; // @@ -173,16 +174,17 @@ PciRootBridgeEnumerator ( Configuration2 = Configuration3; } } + // // All other fields other than AddrRangeMin and AddrLen are ignored in a descriptor, // so only need to swap these two fields. // if (Configuration2 != Configuration1) { - AddrRangeMin = Configuration1->AddrRangeMin; + AddrRangeMin = Configuration1->AddrRangeMin; Configuration1->AddrRangeMin = Configuration2->AddrRangeMin; Configuration2->AddrRangeMin = AddrRangeMin; - AddrLen = Configuration1->AddrLen; + AddrLen = Configuration1->AddrLen; Configuration1->AddrLen = Configuration2->AddrLen; Configuration2->AddrLen = AddrLen; } @@ -191,7 +193,7 @@ PciRootBridgeEnumerator ( // // Get the bus number to start with // - StartBusNumber = (UINT8) (Configuration->AddrRangeMin); + StartBusNumber = (UINT8)(Configuration->AddrRangeMin); // // Initialize the subordinate bus number @@ -204,23 +206,22 @@ PciRootBridgeEnumerator ( ResetAllPpbBusNumber ( RootBridgeDev, StartBusNumber - ); + ); // // Assign bus number // Status = PciScanBus ( - RootBridgeDev, - StartBusNumber, - &SubBusNumber, - &PaddedBusRange - ); + RootBridgeDev, + StartBusNumber, + &SubBusNumber, + &PaddedBusRange + ); if (EFI_ERROR (Status)) { return Status; } - // // Assign max bus number scanned // @@ -237,14 +238,15 @@ PciRootBridgeEnumerator ( while (Configuration->AddrRangeMin + Configuration->AddrLen - 1 < SubBusNumber) { Configuration++; } - AddrLen = Configuration->AddrLen; + + AddrLen = Configuration->AddrLen; Configuration->AddrLen = SubBusNumber - Configuration->AddrRangeMin + 1; // // Save the Desc field of the next descriptor. Mark the next descriptor as an END descriptor. // Configuration++; - Desc = Configuration->Desc; + Desc = Configuration->Desc; Configuration->Desc = ACPI_END_TAG_DESCRIPTOR; // @@ -259,7 +261,7 @@ PciRootBridgeEnumerator ( // // Restore changed fields // - Configuration->Desc = Desc; + Configuration->Desc = Desc; (Configuration - 1)->AddrLen = AddrLen; return Status; @@ -276,13 +278,13 @@ PciRootBridgeEnumerator ( **/ VOID ProcessOptionRom ( - IN PCI_IO_DEVICE *Bridge, - IN UINT64 RomBase, - IN UINT64 MaxLength + IN PCI_IO_DEVICE *Bridge, + IN UINT64 RomBase, + IN UINT64 MaxLength ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; // // Go through bridges to reach all devices @@ -291,15 +293,13 @@ ProcessOptionRom ( while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (!IsListEmpty (&Temp->ChildList)) { - // // Go further to process the option rom under this bridge // ProcessOptionRom (Temp, RomBase, MaxLength); } - if (Temp->RomSize != 0 && Temp->RomSize <= MaxLength) { - + if ((Temp->RomSize != 0) && (Temp->RomSize <= MaxLength)) { // // Load and process the option rom // @@ -323,25 +323,25 @@ ProcessOptionRom ( **/ EFI_STATUS PciAssignBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - OUT UINT8 *SubBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + OUT UINT8 *SubBusNumber ) { - EFI_STATUS Status; - PCI_TYPE00 Pci; - UINT8 Device; - UINT8 Func; - UINT64 Address; - UINTN SecondBus; - UINT16 Register; - UINT8 Register8; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_STATUS Status; + PCI_TYPE00 Pci; + UINT8 Device; + UINT8 Func; + UINT64 Address; + UINTN SecondBus; + UINT16 Register; + UINT8 Register8; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; PciRootBridgeIo = Bridge->PciRootBridgeIo; - SecondBus = 0; - Register = 0; + SecondBus = 0; + Register = 0; *SubBusNumber = StartBusNumber; @@ -350,19 +350,18 @@ PciAssignBusNumber ( // for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { - // // Check to see whether a pci device is present // Status = PciDevicePresent ( - PciRootBridgeIo, - &Pci, - StartBusNumber, - Device, - Func - ); - - if (EFI_ERROR (Status) && Func == 0) { + PciRootBridgeIo, + &Pci, + StartBusNumber, + Device, + Func + ); + + if (EFI_ERROR (Status) && (Func == 0)) { // // go to next device if there is no Function 0 // @@ -370,8 +369,8 @@ PciAssignBusNumber ( } if (!EFI_ERROR (Status) && - (IS_PCI_BRIDGE (&Pci) || IS_CARDBUS_BRIDGE (&Pci))) { - + (IS_PCI_BRIDGE (&Pci) || IS_CARDBUS_BRIDGE (&Pci))) + { // // Reserved one bus for cardbus bridge // @@ -379,11 +378,12 @@ PciAssignBusNumber ( if (EFI_ERROR (Status)) { return Status; } + SecondBus = *SubBusNumber; - Register = (UINT16) ((SecondBus << 8) | (UINT16) StartBusNumber); + Register = (UINT16)((SecondBus << 8) | (UINT16)StartBusNumber); - Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x18); + Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x18); Status = PciRootBridgeIo->Pci.Write ( PciRootBridgeIo, @@ -397,32 +397,31 @@ PciAssignBusNumber ( // Initialize SubBusNumber to SecondBus // Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x1A); - Status = PciRootBridgeIo->Pci.Write ( - PciRootBridgeIo, - EfiPciWidthUint8, - Address, - 1, - SubBusNumber - ); + Status = PciRootBridgeIo->Pci.Write ( + PciRootBridgeIo, + EfiPciWidthUint8, + Address, + 1, + SubBusNumber + ); // // If it is PPB, resursively search down this bridge // if (IS_PCI_BRIDGE (&Pci)) { - Register8 = 0xFF; - Status = PciRootBridgeIo->Pci.Write ( - PciRootBridgeIo, - EfiPciWidthUint8, - Address, - 1, - &Register8 - ); + Status = PciRootBridgeIo->Pci.Write ( + PciRootBridgeIo, + EfiPciWidthUint8, + Address, + 1, + &Register8 + ); Status = PciAssignBusNumber ( - Bridge, - (UINT8) (SecondBus), - SubBusNumber - ); + Bridge, + (UINT8)(SecondBus), + SubBusNumber + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -441,11 +440,9 @@ PciAssignBusNumber ( 1, SubBusNumber ); - } - if (Func == 0 && !IS_PCI_MULTI_FUNC (&Pci)) { - + if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) { // // Skip sub functions, this is not a multi function device // @@ -470,16 +467,16 @@ PciAssignBusNumber ( **/ EFI_STATUS DetermineRootBridgeAttributes ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, - IN PCI_IO_DEVICE *RootBridgeDev + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, + IN PCI_IO_DEVICE *RootBridgeDev ) { UINT64 Attributes; EFI_STATUS Status; EFI_HANDLE RootBridgeHandle; - Attributes = 0; - RootBridgeHandle = RootBridgeDev->Handle; + Attributes = 0; + RootBridgeHandle = RootBridgeDev->Handle; // // Get root bridge attribute by calling into pci host bridge resource allocation protocol @@ -524,13 +521,13 @@ DetermineRootBridgeAttributes ( **/ UINT32 GetMaxOptionRomSize ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; - UINT32 MaxOptionRomSize; - UINT32 TempOptionRomSize; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; + UINT32 MaxOptionRomSize; + UINT32 TempOptionRomSize; MaxOptionRomSize = 0; @@ -541,7 +538,6 @@ GetMaxOptionRomSize ( while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (!IsListEmpty (&Temp->ChildList)) { - // // Get max option rom size under this bridge // @@ -554,9 +550,7 @@ GetMaxOptionRomSize ( if (Temp->RomSize > TempOptionRomSize) { TempOptionRomSize = Temp->RomSize; } - } else { - // // For devices get the rom size directly // @@ -588,17 +582,16 @@ GetMaxOptionRomSize ( **/ EFI_STATUS PciHostBridgeDeviceAttribute ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ) { - EFI_HANDLE RootBridgeHandle; - PCI_IO_DEVICE *RootBridgeDev; - EFI_STATUS Status; + EFI_HANDLE RootBridgeHandle; + PCI_IO_DEVICE *RootBridgeDev; + EFI_STATUS Status; RootBridgeHandle = NULL; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { - // // Get RootBridg Device by handle // @@ -615,7 +608,6 @@ PciHostBridgeDeviceAttribute ( if (EFI_ERROR (Status)) { return Status; } - } return EFI_SUCCESS; @@ -642,58 +634,57 @@ GetResourceAllocationStatus ( OUT UINT64 *PMem64ResStatus ) { - UINT8 *Temp; - UINT64 ResStatus; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ACPIAddressDesc; + UINT8 *Temp; + UINT64 ResStatus; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *ACPIAddressDesc; - Temp = (UINT8 *) AcpiConfig; + Temp = (UINT8 *)AcpiConfig; while (*Temp == ACPI_ADDRESS_SPACE_DESCRIPTOR) { - - ACPIAddressDesc = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp; - ResStatus = ACPIAddressDesc->AddrTranslationOffset; + ACPIAddressDesc = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp; + ResStatus = ACPIAddressDesc->AddrTranslationOffset; switch (ACPIAddressDesc->ResType) { - case 0: - if (ACPIAddressDesc->AddrSpaceGranularity == 32) { - if (ACPIAddressDesc->SpecificFlag == 0x06) { - // - // Pmem32 - // - *PMem32ResStatus = ResStatus; - } else { - // - // Mem32 - // - *Mem32ResStatus = ResStatus; + case 0: + if (ACPIAddressDesc->AddrSpaceGranularity == 32) { + if (ACPIAddressDesc->SpecificFlag == 0x06) { + // + // Pmem32 + // + *PMem32ResStatus = ResStatus; + } else { + // + // Mem32 + // + *Mem32ResStatus = ResStatus; + } } - } - if (ACPIAddressDesc->AddrSpaceGranularity == 64) { - if (ACPIAddressDesc->SpecificFlag == 0x06) { - // - // PMem64 - // - *PMem64ResStatus = ResStatus; - } else { - // - // Mem64 - // - *Mem64ResStatus = ResStatus; + if (ACPIAddressDesc->AddrSpaceGranularity == 64) { + if (ACPIAddressDesc->SpecificFlag == 0x06) { + // + // PMem64 + // + *PMem64ResStatus = ResStatus; + } else { + // + // Mem64 + // + *Mem64ResStatus = ResStatus; + } } - } - break; + break; - case 1: - // - // Io - // - *IoResStatus = ResStatus; - break; + case 1: + // + // Io + // + *IoResStatus = ResStatus; + break; - default: - break; + default: + break; } Temp += sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR); @@ -711,18 +702,19 @@ GetResourceAllocationStatus ( **/ EFI_STATUS RejectPciDevice ( - IN PCI_IO_DEVICE *PciDevice + IN PCI_IO_DEVICE *PciDevice ) { - PCI_IO_DEVICE *Bridge; - PCI_IO_DEVICE *Temp; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Bridge; + PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; // // Remove the padding resource from a bridge // - if ( IS_PCI_BRIDGE(&PciDevice->Pci) && - PciDevice->ResourcePaddingDescriptors != NULL ) { + if ( IS_PCI_BRIDGE (&PciDevice->Pci) && + (PciDevice->ResourcePaddingDescriptors != NULL)) + { FreePool (PciDevice->ResourcePaddingDescriptors); PciDevice->ResourcePaddingDescriptors = NULL; return EFI_SUCCESS; @@ -782,10 +774,10 @@ RejectPciDevice ( **/ BOOLEAN IsRejectiveDevice ( - IN PCI_RESOURCE_NODE *PciResNode + IN PCI_RESOURCE_NODE *PciResNode ) { - PCI_IO_DEVICE *Temp; + PCI_IO_DEVICE *Temp; Temp = PciResNode->PciDev; @@ -831,16 +823,16 @@ IsRejectiveDevice ( **/ PCI_RESOURCE_NODE * GetLargerConsumerDevice ( - IN PCI_RESOURCE_NODE *PciResNode1, - IN PCI_RESOURCE_NODE *PciResNode2 + IN PCI_RESOURCE_NODE *PciResNode1, + IN PCI_RESOURCE_NODE *PciResNode2 ) { if (PciResNode2 == NULL) { return PciResNode1; } - if ((IS_PCI_BRIDGE(&(PciResNode2->PciDev->Pci)) || (PciResNode2->PciDev->Parent == NULL)) \ - && (PciResNode2->ResourceUsage != PciResUsagePadding) ) + if ( (IS_PCI_BRIDGE (&(PciResNode2->PciDev->Pci)) || (PciResNode2->PciDev->Parent == NULL)) \ + && (PciResNode2->ResourceUsage != PciResUsagePadding)) { return PciResNode1; } @@ -856,7 +848,6 @@ GetLargerConsumerDevice ( return PciResNode2; } - /** Get the max resource consumer in the host resource pool. @@ -867,19 +858,18 @@ GetLargerConsumerDevice ( **/ PCI_RESOURCE_NODE * GetMaxResourceConsumerDevice ( - IN PCI_RESOURCE_NODE *ResPool + IN PCI_RESOURCE_NODE *ResPool ) { - PCI_RESOURCE_NODE *Temp; - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *PciResNode; - PCI_RESOURCE_NODE *PPBResNode; + PCI_RESOURCE_NODE *Temp; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *PciResNode; + PCI_RESOURCE_NODE *PPBResNode; - PciResNode = NULL; + PciResNode = NULL; CurrentLink = ResPool->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &ResPool->ChildList) { - Temp = RESOURCE_NODE_FROM_LINK (CurrentLink); if (!IsRejectiveDevice (Temp)) { @@ -887,11 +877,11 @@ GetMaxResourceConsumerDevice ( continue; } - if ((IS_PCI_BRIDGE (&(Temp->PciDev->Pci)) || (Temp->PciDev->Parent == NULL)) \ - && (Temp->ResourceUsage != PciResUsagePadding)) + if ( (IS_PCI_BRIDGE (&(Temp->PciDev->Pci)) || (Temp->PciDev->Parent == NULL)) \ + && (Temp->ResourceUsage != PciResUsagePadding)) { - PPBResNode = GetMaxResourceConsumerDevice (Temp); - PciResNode = GetLargerConsumerDevice (PciResNode, PPBResNode); + PPBResNode = GetMaxResourceConsumerDevice (Temp); + PciResNode = GetLargerConsumerDevice (PciResNode, PPBResNode); } else { PciResNode = GetLargerConsumerDevice (PciResNode, Temp); } @@ -922,49 +912,48 @@ GetMaxResourceConsumerDevice ( **/ EFI_STATUS PciHostBridgeAdjustAllocation ( - IN PCI_RESOURCE_NODE *IoPool, - IN PCI_RESOURCE_NODE *Mem32Pool, - IN PCI_RESOURCE_NODE *PMem32Pool, - IN PCI_RESOURCE_NODE *Mem64Pool, - IN PCI_RESOURCE_NODE *PMem64Pool, - IN UINT64 IoResStatus, - IN UINT64 Mem32ResStatus, - IN UINT64 PMem32ResStatus, - IN UINT64 Mem64ResStatus, - IN UINT64 PMem64ResStatus + IN PCI_RESOURCE_NODE *IoPool, + IN PCI_RESOURCE_NODE *Mem32Pool, + IN PCI_RESOURCE_NODE *PMem32Pool, + IN PCI_RESOURCE_NODE *Mem64Pool, + IN PCI_RESOURCE_NODE *PMem64Pool, + IN UINT64 IoResStatus, + IN UINT64 Mem32ResStatus, + IN UINT64 PMem32ResStatus, + IN UINT64 Mem64ResStatus, + IN UINT64 PMem64ResStatus ) { - BOOLEAN AllocationAjusted; - PCI_RESOURCE_NODE *PciResNode; - PCI_RESOURCE_NODE *ResPool[5]; - PCI_IO_DEVICE *RemovedPciDev[5]; - UINT64 ResStatus[5]; - UINTN RemovedPciDevNum; - UINTN DevIndex; - UINTN ResType; - EFI_STATUS Status; - EFI_RESOURCE_ALLOC_FAILURE_ERROR_DATA_PAYLOAD AllocFailExtendedData; + BOOLEAN AllocationAjusted; + PCI_RESOURCE_NODE *PciResNode; + PCI_RESOURCE_NODE *ResPool[5]; + PCI_IO_DEVICE *RemovedPciDev[5]; + UINT64 ResStatus[5]; + UINTN RemovedPciDevNum; + UINTN DevIndex; + UINTN ResType; + EFI_STATUS Status; + EFI_RESOURCE_ALLOC_FAILURE_ERROR_DATA_PAYLOAD AllocFailExtendedData; PciResNode = NULL; ZeroMem (RemovedPciDev, 5 * sizeof (PCI_IO_DEVICE *)); - RemovedPciDevNum = 0; + RemovedPciDevNum = 0; - ResPool[0] = IoPool; - ResPool[1] = Mem32Pool; - ResPool[2] = PMem32Pool; - ResPool[3] = Mem64Pool; - ResPool[4] = PMem64Pool; + ResPool[0] = IoPool; + ResPool[1] = Mem32Pool; + ResPool[2] = PMem32Pool; + ResPool[3] = Mem64Pool; + ResPool[4] = PMem64Pool; - ResStatus[0] = IoResStatus; - ResStatus[1] = Mem32ResStatus; - ResStatus[2] = PMem32ResStatus; - ResStatus[3] = Mem64ResStatus; - ResStatus[4] = PMem64ResStatus; + ResStatus[0] = IoResStatus; + ResStatus[1] = Mem32ResStatus; + ResStatus[2] = PMem32ResStatus; + ResStatus[3] = Mem64ResStatus; + ResStatus[4] = PMem64ResStatus; AllocationAjusted = FALSE; for (ResType = 0; ResType < 5; ResType++) { - if (ResStatus[ResType] == EFI_RESOURCE_SATISFIED) { continue; } @@ -1005,7 +994,9 @@ PciHostBridgeAdjustAllocation ( DEBUG (( DEBUG_ERROR, "PciBus: [%02x|%02x|%02x] was rejected due to resource confliction.\n", - PciResNode->PciDev->BusNumber, PciResNode->PciDev->DeviceNumber, PciResNode->PciDev->FunctionNumber + PciResNode->PciDev->BusNumber, + PciResNode->PciDev->DeviceNumber, + PciResNode->PciDev->FunctionNumber )); // @@ -1015,16 +1006,16 @@ PciHostBridgeAdjustAllocation ( // Have no way to get ReqRes, AllocRes & Bar here // ZeroMem (&AllocFailExtendedData, sizeof (AllocFailExtendedData)); - AllocFailExtendedData.DevicePathSize = (UINT16) sizeof (EFI_DEVICE_PATH_PROTOCOL); - AllocFailExtendedData.DevicePath = (UINT8 *) PciResNode->PciDev->DevicePath; + AllocFailExtendedData.DevicePathSize = (UINT16)sizeof (EFI_DEVICE_PATH_PROTOCOL); + AllocFailExtendedData.DevicePath = (UINT8 *)PciResNode->PciDev->DevicePath; AllocFailExtendedData.Bar = PciResNode->Bar; REPORT_STATUS_CODE_WITH_EXTENDED_DATA ( - EFI_PROGRESS_CODE, - EFI_IO_BUS_PCI | EFI_IOB_EC_RESOURCE_CONFLICT, - (VOID *) &AllocFailExtendedData, - sizeof (AllocFailExtendedData) - ); + EFI_PROGRESS_CODE, + EFI_IO_BUS_PCI | EFI_IOB_EC_RESOURCE_CONFLICT, + (VOID *)&AllocFailExtendedData, + sizeof (AllocFailExtendedData) + ); // // Add it to the array and indicate at least a device has been rejected @@ -1033,6 +1024,7 @@ PciHostBridgeAdjustAllocation ( AllocationAjusted = TRUE; } } + // // End for // @@ -1071,16 +1063,16 @@ ConstructAcpiResourceRequestor ( OUT VOID **Config ) { - UINT8 NumConfig; - UINT8 Aperture; - UINT8 *Configuration; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; - EFI_ACPI_END_TAG_DESCRIPTOR *PtrEnd; + UINT8 NumConfig; + UINT8 Aperture; + UINT8 *Configuration; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; + EFI_ACPI_END_TAG_DESCRIPTOR *PtrEnd; NumConfig = 0; Aperture = 0; - *Config = NULL; + *Config = NULL; // // if there is io request, add to the io aperture @@ -1123,7 +1115,6 @@ ConstructAcpiResourceRequestor ( } if (NumConfig != 0) { - // // If there is at least one type of resource request, // allocate a acpi resource node @@ -1133,18 +1124,18 @@ ConstructAcpiResourceRequestor ( return EFI_OUT_OF_RESOURCES; } - Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; + Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; // // Deal with io aperture // if ((Aperture & 0x01) != 0) { - Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Ptr->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Ptr->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); // // Io // - Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; + Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; // // non ISA range // @@ -1154,16 +1145,17 @@ ConstructAcpiResourceRequestor ( Ptr++; } + // // Deal with mem32 aperture // if ((Aperture & 0x02) != 0) { - Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Ptr->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Ptr->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); // // Mem // - Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; // // Nonprefechable // @@ -1172,8 +1164,8 @@ ConstructAcpiResourceRequestor ( // 32 bit // Ptr->AddrSpaceGranularity = 32; - Ptr->AddrLen = Mem32Node->Length; - Ptr->AddrRangeMax = Mem32Node->Alignment; + Ptr->AddrLen = Mem32Node->Length; + Ptr->AddrRangeMax = Mem32Node->Alignment; Ptr++; } @@ -1182,12 +1174,12 @@ ConstructAcpiResourceRequestor ( // Deal with Pmem32 aperture // if ((Aperture & 0x04) != 0) { - Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Ptr->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Ptr->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); // // Mem // - Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; // // prefechable // @@ -1196,21 +1188,22 @@ ConstructAcpiResourceRequestor ( // 32 bit // Ptr->AddrSpaceGranularity = 32; - Ptr->AddrLen = PMem32Node->Length; - Ptr->AddrRangeMax = PMem32Node->Alignment; + Ptr->AddrLen = PMem32Node->Length; + Ptr->AddrRangeMax = PMem32Node->Alignment; Ptr++; } + // // Deal with mem64 aperture // if ((Aperture & 0x08) != 0) { - Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Ptr->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Ptr->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); // // Mem // - Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; // // nonprefechable // @@ -1219,21 +1212,22 @@ ConstructAcpiResourceRequestor ( // 64 bit // Ptr->AddrSpaceGranularity = 64; - Ptr->AddrLen = Mem64Node->Length; - Ptr->AddrRangeMax = Mem64Node->Alignment; + Ptr->AddrLen = Mem64Node->Length; + Ptr->AddrRangeMax = Mem64Node->Alignment; Ptr++; } + // // Deal with Pmem64 aperture // if ((Aperture & 0x10) != 0) { - Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Ptr->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Ptr->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Ptr->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); // // Mem // - Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Ptr->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; // // prefechable // @@ -1242,8 +1236,8 @@ ConstructAcpiResourceRequestor ( // 64 bit // Ptr->AddrSpaceGranularity = 64; - Ptr->AddrLen = PMem64Node->Length; - Ptr->AddrRangeMax = PMem64Node->Alignment; + Ptr->AddrLen = PMem64Node->Length; + Ptr->AddrRangeMax = PMem64Node->Alignment; Ptr++; } @@ -1251,13 +1245,11 @@ ConstructAcpiResourceRequestor ( // // put the checksum // - PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *) Ptr; - - PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; - PtrEnd->Checksum = 0; + PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *)Ptr; + PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; + PtrEnd->Checksum = 0; } else { - // // If there is no resource request // @@ -1266,9 +1258,9 @@ ConstructAcpiResourceRequestor ( return EFI_OUT_OF_RESOURCES; } - PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *) (Configuration); - PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; - PtrEnd->Checksum = 0; + PtrEnd = (EFI_ACPI_END_TAG_DESCRIPTOR *)(Configuration); + PtrEnd->Desc = ACPI_END_TAG_DESCRIPTOR; + PtrEnd->Checksum = 0; } *Config = Configuration; @@ -1297,9 +1289,9 @@ GetResourceBase ( OUT UINT64 *PMem64Base ) { - UINT8 *Temp; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; - UINT64 ResStatus; + UINT8 *Temp; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; + UINT64 ResStatus; ASSERT (Config != NULL); @@ -1309,58 +1301,57 @@ GetResourceBase ( *Mem64Base = 0xFFFFFFFFFFFFFFFFULL; *PMem64Base = 0xFFFFFFFFFFFFFFFFULL; - Temp = (UINT8 *) Config; + Temp = (UINT8 *)Config; while (*Temp == ACPI_ADDRESS_SPACE_DESCRIPTOR) { - - Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Temp; + Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Temp; ResStatus = Ptr->AddrTranslationOffset; if (ResStatus == EFI_RESOURCE_SATISFIED) { - switch (Ptr->ResType) { - - // - // Memory type aperture - // - case 0: - // - // Check to see the granularity + // Memory type aperture // - if (Ptr->AddrSpaceGranularity == 32) { - if ((Ptr->SpecificFlag & 0x06) != 0) { - *PMem32Base = Ptr->AddrRangeMin; - } else { - *Mem32Base = Ptr->AddrRangeMin; + case 0: + + // + // Check to see the granularity + // + if (Ptr->AddrSpaceGranularity == 32) { + if ((Ptr->SpecificFlag & 0x06) != 0) { + *PMem32Base = Ptr->AddrRangeMin; + } else { + *Mem32Base = Ptr->AddrRangeMin; + } } - } - if (Ptr->AddrSpaceGranularity == 64) { - if ((Ptr->SpecificFlag & 0x06) != 0) { - *PMem64Base = Ptr->AddrRangeMin; - } else { - *Mem64Base = Ptr->AddrRangeMin; + if (Ptr->AddrSpaceGranularity == 64) { + if ((Ptr->SpecificFlag & 0x06) != 0) { + *PMem64Base = Ptr->AddrRangeMin; + } else { + *Mem64Base = Ptr->AddrRangeMin; + } } - } - break; - case 1: + break; - // - // Io type aperture - // - *IoBase = Ptr->AddrRangeMin; - break; + case 1: - default: - break; + // + // Io type aperture + // + *IoBase = Ptr->AddrRangeMin; + break; + default: + break; } + // // End switch // } + // // End for // @@ -1380,28 +1371,28 @@ GetResourceBase ( **/ EFI_STATUS PciBridgeEnumerator ( - IN PCI_IO_DEVICE *BridgeDev + IN PCI_IO_DEVICE *BridgeDev ) { - UINT8 SubBusNumber; - UINT8 StartBusNumber; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; + UINT8 SubBusNumber; + UINT8 StartBusNumber; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; - SubBusNumber = 0; - StartBusNumber = 0; - PciIo = &(BridgeDev->PciIo); - Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x19, 1, &StartBusNumber); + SubBusNumber = 0; + StartBusNumber = 0; + PciIo = &(BridgeDev->PciIo); + Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x19, 1, &StartBusNumber); if (EFI_ERROR (Status)) { return Status; } Status = PciAssignBusNumber ( - BridgeDev, - StartBusNumber, - &SubBusNumber - ); + BridgeDev, + StartBusNumber, + &SubBusNumber + ); if (EFI_ERROR (Status)) { return Status; @@ -1426,7 +1417,6 @@ PciBridgeEnumerator ( } return EFI_SUCCESS; - } /** @@ -1443,17 +1433,17 @@ PciBridgeResourceAllocator ( IN PCI_IO_DEVICE *Bridge ) { - PCI_RESOURCE_NODE *IoBridge; - PCI_RESOURCE_NODE *Mem32Bridge; - PCI_RESOURCE_NODE *PMem32Bridge; - PCI_RESOURCE_NODE *Mem64Bridge; - PCI_RESOURCE_NODE *PMem64Bridge; - UINT64 IoBase; - UINT64 Mem32Base; - UINT64 PMem32Base; - UINT64 Mem64Base; - UINT64 PMem64Base; - EFI_STATUS Status; + PCI_RESOURCE_NODE *IoBridge; + PCI_RESOURCE_NODE *Mem32Bridge; + PCI_RESOURCE_NODE *PMem32Bridge; + PCI_RESOURCE_NODE *Mem64Bridge; + PCI_RESOURCE_NODE *PMem64Bridge; + UINT64 IoBase; + UINT64 Mem32Base; + UINT64 PMem32Base; + UINT64 Mem64Base; + UINT64 PMem64Base; + EFI_STATUS Status; IoBridge = CreateResourceNode ( Bridge, @@ -1596,12 +1586,12 @@ PciBridgeResourceAllocator ( **/ EFI_STATUS GetResourceBaseFromBridge ( - IN PCI_IO_DEVICE *Bridge, - OUT UINT64 *IoBase, - OUT UINT64 *Mem32Base, - OUT UINT64 *PMem32Base, - OUT UINT64 *Mem64Base, - OUT UINT64 *PMem64Base + IN PCI_IO_DEVICE *Bridge, + OUT UINT64 *IoBase, + OUT UINT64 *Mem32Base, + OUT UINT64 *PMem32Base, + OUT UINT64 *Mem64Base, + OUT UINT64 *PMem64Base ) { if (!Bridge->Allocated) { @@ -1615,7 +1605,6 @@ GetResourceBaseFromBridge ( *PMem64Base = gAllOne; if (IS_PCI_BRIDGE (&Bridge->Pci)) { - if (Bridge->PciBar[PPB_IO_RANGE].Length > 0) { *IoBase = Bridge->PciBar[PPB_IO_RANGE].BaseAddress; } @@ -1633,7 +1622,6 @@ GetResourceBaseFromBridge ( } else { *PMem64Base = gAllOne; } - } if (IS_CARDBUS_BRIDGE (&Bridge->Pci)) { @@ -1735,17 +1723,17 @@ GetResourceBaseFromBridge ( **/ EFI_STATUS NotifyPhase ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, - EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, + EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase ) { - EFI_HANDLE HostBridgeHandle; - EFI_HANDLE RootBridgeHandle; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - EFI_STATUS Status; + EFI_HANDLE HostBridgeHandle; + EFI_HANDLE RootBridgeHandle; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_STATUS Status; - HostBridgeHandle = NULL; - RootBridgeHandle = NULL; + HostBridgeHandle = NULL; + RootBridgeHandle = NULL; if (gPciPlatformProtocol != NULL) { // // Get Host Bridge Handle. @@ -1758,7 +1746,7 @@ NotifyPhase ( Status = gBS->HandleProtocol ( RootBridgeHandle, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo + (VOID **)&PciRootBridgeIo ); if (EFI_ERROR (Status)) { @@ -1776,7 +1764,7 @@ NotifyPhase ( Phase, ChipsetEntry ); - } else if (gPciOverrideProtocol != NULL){ + } else if (gPciOverrideProtocol != NULL) { // // Get Host Bridge Handle. // @@ -1788,7 +1776,7 @@ NotifyPhase ( Status = gBS->HandleProtocol ( RootBridgeHandle, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo + (VOID **)&PciRootBridgeIo ); if (EFI_ERROR (Status)) { @@ -1823,7 +1811,6 @@ NotifyPhase ( Phase, ChipsetExit ); - } else if (gPciOverrideProtocol != NULL) { // // Call PlatformPci::PhaseNotify() if the protocol is present. @@ -1865,11 +1852,11 @@ NotifyPhase ( **/ EFI_STATUS PreprocessController ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func, - IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase + IN PCI_IO_DEVICE *Bridge, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func, + IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase ) { EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS RootBridgePciAddress; @@ -1889,7 +1876,7 @@ PreprocessController ( Status = gBS->OpenProtocol ( HostBridgeHandle, &gEfiPciHostBridgeResourceAllocationProtocolGuid, - (VOID **) &PciResAlloc, + (VOID **)&PciResAlloc, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1906,7 +1893,7 @@ PreprocessController ( Bridge = Bridge->Parent; } - RootBridgeHandle = Bridge->Handle; + RootBridgeHandle = Bridge->Handle; RootBridgePciAddress.Register = 0; RootBridgePciAddress.Function = Func; @@ -2002,25 +1989,25 @@ PreprocessController ( EFI_STATUS EFIAPI PciHotPlugRequestNotify ( - IN EFI_PCI_HOTPLUG_REQUEST_PROTOCOL * This, - IN EFI_PCI_HOTPLUG_OPERATION Operation, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath OPTIONAL, - IN OUT UINT8 *NumberOfChildren, - IN OUT EFI_HANDLE * ChildHandleBuffer + IN EFI_PCI_HOTPLUG_REQUEST_PROTOCOL *This, + IN EFI_PCI_HOTPLUG_OPERATION Operation, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, + IN OUT UINT8 *NumberOfChildren, + IN OUT EFI_HANDLE *ChildHandleBuffer ) { - PCI_IO_DEVICE *Bridge; - PCI_IO_DEVICE *Temp; - EFI_PCI_IO_PROTOCOL *PciIo; - UINTN Index; - EFI_HANDLE RootBridgeHandle; - EFI_STATUS Status; + PCI_IO_DEVICE *Bridge; + PCI_IO_DEVICE *Temp; + EFI_PCI_IO_PROTOCOL *PciIo; + UINTN Index; + EFI_HANDLE RootBridgeHandle; + EFI_STATUS Status; // // Check input parameter validity // - if ((Controller == NULL) || (NumberOfChildren == NULL)){ + if ((Controller == NULL) || (NumberOfChildren == NULL)) { return EFI_INVALID_PARAMETER; } @@ -2028,7 +2015,7 @@ PciHotPlugRequestNotify ( return EFI_INVALID_PARAMETER; } - if (Operation == EfiPciHotPlugRequestAdd){ + if (Operation == EfiPciHotPlugRequestAdd) { if (ChildHandleBuffer == NULL) { return EFI_INVALID_PARAMETER; } @@ -2041,7 +2028,7 @@ PciHotPlugRequestNotify ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, gPciBusDriverBinding.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -2078,7 +2065,6 @@ PciHotPlugRequestNotify ( } if (IsListEmpty (&Bridge->ChildList)) { - Status = PciBridgeEnumerator (Bridge); if (EFI_ERROR (Status)) { @@ -2087,25 +2073,23 @@ PciHotPlugRequestNotify ( } Status = StartPciDevicesOnBridge ( - RootBridgeHandle, - Bridge, - RemainingDevicePath, - NumberOfChildren, - ChildHandleBuffer - ); + RootBridgeHandle, + Bridge, + RemainingDevicePath, + NumberOfChildren, + ChildHandleBuffer + ); return Status; } if (Operation == EfiPciHotplugRequestRemove) { - if (*NumberOfChildren == 0) { // // Remove all devices on the bridge // RemoveAllPciDeviceOnBridge (RootBridgeHandle, Bridge); return EFI_SUCCESS; - } for (Index = 0; Index < *NumberOfChildren; Index++) { @@ -2117,8 +2101,8 @@ PciHotPlugRequestNotify ( if (EFI_ERROR (Status)) { return Status; } - } + // // End for // @@ -2139,13 +2123,13 @@ PciHotPlugRequestNotify ( **/ BOOLEAN SearchHostBridgeHandle ( - IN EFI_HANDLE RootBridgeHandle + IN EFI_HANDLE RootBridgeHandle ) { - EFI_HANDLE HostBridgeHandle; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - UINTN Index; - EFI_STATUS Status; + EFI_HANDLE HostBridgeHandle; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + UINTN Index; + EFI_STATUS Status; // // Get the rootbridge Io protocol to find the host bridge handle @@ -2153,7 +2137,7 @@ SearchHostBridgeHandle ( Status = gBS->OpenProtocol ( RootBridgeHandle, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, gPciBusDriverBinding.DriverBindingHandle, RootBridgeHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -2185,10 +2169,10 @@ SearchHostBridgeHandle ( **/ EFI_STATUS AddHostBridgeEnumerator ( - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE HostBridgeHandle ) { - UINTN Index; + UINTN Index; if (HostBridgeHandle == NULL) { return EFI_ABORTED; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.h index 133454126c..2c81def04c 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumerator.h @@ -24,8 +24,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PciEnumerator ( - IN EFI_HANDLE Controller, - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE Controller, + IN EFI_HANDLE HostBridgeHandle ); /** @@ -55,9 +55,9 @@ PciRootBridgeEnumerator ( **/ VOID ProcessOptionRom ( - IN PCI_IO_DEVICE *Bridge, - IN UINT64 RomBase, - IN UINT64 MaxLength + IN PCI_IO_DEVICE *Bridge, + IN UINT64 RomBase, + IN UINT64 MaxLength ); /** @@ -73,9 +73,9 @@ ProcessOptionRom ( **/ EFI_STATUS PciAssignBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - OUT UINT8 *SubBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + OUT UINT8 *SubBusNumber ); /** @@ -91,8 +91,8 @@ PciAssignBusNumber ( **/ EFI_STATUS DetermineRootBridgeAttributes ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, - IN PCI_IO_DEVICE *RootBridgeDev + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, + IN PCI_IO_DEVICE *RootBridgeDev ); /** @@ -105,7 +105,7 @@ DetermineRootBridgeAttributes ( **/ UINT32 GetMaxOptionRomSize ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ); /** @@ -120,7 +120,7 @@ GetMaxOptionRomSize ( **/ EFI_STATUS PciHostBridgeDeviceAttribute ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** @@ -155,7 +155,7 @@ GetResourceAllocationStatus ( **/ EFI_STATUS RejectPciDevice ( - IN PCI_IO_DEVICE *PciDevice + IN PCI_IO_DEVICE *PciDevice ); /** @@ -169,7 +169,7 @@ RejectPciDevice ( **/ BOOLEAN IsRejectiveDevice ( - IN PCI_RESOURCE_NODE *PciResNode + IN PCI_RESOURCE_NODE *PciResNode ); /** @@ -183,8 +183,8 @@ IsRejectiveDevice ( **/ PCI_RESOURCE_NODE * GetLargerConsumerDevice ( - IN PCI_RESOURCE_NODE *PciResNode1, - IN PCI_RESOURCE_NODE *PciResNode2 + IN PCI_RESOURCE_NODE *PciResNode1, + IN PCI_RESOURCE_NODE *PciResNode2 ); /** @@ -197,7 +197,7 @@ GetLargerConsumerDevice ( **/ PCI_RESOURCE_NODE * GetMaxResourceConsumerDevice ( - IN PCI_RESOURCE_NODE *ResPool + IN PCI_RESOURCE_NODE *ResPool ); /** @@ -220,16 +220,16 @@ GetMaxResourceConsumerDevice ( **/ EFI_STATUS PciHostBridgeAdjustAllocation ( - IN PCI_RESOURCE_NODE *IoPool, - IN PCI_RESOURCE_NODE *Mem32Pool, - IN PCI_RESOURCE_NODE *PMem32Pool, - IN PCI_RESOURCE_NODE *Mem64Pool, - IN PCI_RESOURCE_NODE *PMem64Pool, - IN UINT64 IoResStatus, - IN UINT64 Mem32ResStatus, - IN UINT64 PMem32ResStatus, - IN UINT64 Mem64ResStatus, - IN UINT64 PMem64ResStatus + IN PCI_RESOURCE_NODE *IoPool, + IN PCI_RESOURCE_NODE *Mem32Pool, + IN PCI_RESOURCE_NODE *PMem32Pool, + IN PCI_RESOURCE_NODE *Mem64Pool, + IN PCI_RESOURCE_NODE *PMem64Pool, + IN UINT64 IoResStatus, + IN UINT64 Mem32ResStatus, + IN UINT64 PMem32ResStatus, + IN UINT64 Mem64ResStatus, + IN UINT64 PMem64ResStatus ); /** @@ -292,7 +292,7 @@ GetResourceBase ( **/ EFI_STATUS PciBridgeEnumerator ( - IN PCI_IO_DEVICE *BridgeDev + IN PCI_IO_DEVICE *BridgeDev ); /** @@ -325,12 +325,12 @@ PciBridgeResourceAllocator ( **/ EFI_STATUS GetResourceBaseFromBridge ( - IN PCI_IO_DEVICE *Bridge, - OUT UINT64 *IoBase, - OUT UINT64 *Mem32Base, - OUT UINT64 *PMem32Base, - OUT UINT64 *Mem64Base, - OUT UINT64 *PMem64Base + IN PCI_IO_DEVICE *Bridge, + OUT UINT64 *IoBase, + OUT UINT64 *Mem32Base, + OUT UINT64 *PMem32Base, + OUT UINT64 *Mem64Base, + OUT UINT64 *PMem64Base ); /** @@ -343,7 +343,7 @@ GetResourceBaseFromBridge ( **/ EFI_STATUS PciHostBridgeP2CProcess ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** @@ -412,8 +412,8 @@ PciHostBridgeP2CProcess ( **/ EFI_STATUS NotifyPhase ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, - EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc, + EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase ); /** @@ -442,11 +442,11 @@ NotifyPhase ( **/ EFI_STATUS PreprocessController ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func, - IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase + IN PCI_IO_DEVICE *Bridge, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func, + IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase ); /** @@ -475,12 +475,12 @@ PreprocessController ( EFI_STATUS EFIAPI PciHotPlugRequestNotify ( - IN EFI_PCI_HOTPLUG_REQUEST_PROTOCOL * This, - IN EFI_PCI_HOTPLUG_OPERATION Operation, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL * RemainingDevicePath OPTIONAL, - IN OUT UINT8 *NumberOfChildren, - IN OUT EFI_HANDLE * ChildHandleBuffer + IN EFI_PCI_HOTPLUG_REQUEST_PROTOCOL *This, + IN EFI_PCI_HOTPLUG_OPERATION Operation, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL, + IN OUT UINT8 *NumberOfChildren, + IN OUT EFI_HANDLE *ChildHandleBuffer ); /** @@ -494,7 +494,7 @@ PciHotPlugRequestNotify ( **/ BOOLEAN SearchHostBridgeHandle ( - IN EFI_HANDLE RootBridgeHandle + IN EFI_HANDLE RootBridgeHandle ); /** @@ -509,7 +509,7 @@ SearchHostBridgeHandle ( **/ EFI_STATUS AddHostBridgeEnumerator ( - IN EFI_HANDLE HostBridgeHandle + IN EFI_HANDLE HostBridgeHandle ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index 5111bd513a..ed7f2d4ac6 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -9,13 +9,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciBus.h" -extern CHAR16 *mBarTypeStr[]; -extern EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; +extern CHAR16 *mBarTypeStr[]; +extern EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; -#define OLD_ALIGN 0xFFFFFFFFFFFFFFFFULL -#define EVEN_ALIGN 0xFFFFFFFFFFFFFFFEULL -#define SQUAD_ALIGN 0xFFFFFFFFFFFFFFFDULL -#define DQUAD_ALIGN 0xFFFFFFFFFFFFFFFCULL +#define OLD_ALIGN 0xFFFFFFFFFFFFFFFFULL +#define EVEN_ALIGN 0xFFFFFFFFFFFFFFFEULL +#define SQUAD_ALIGN 0xFFFFFFFFFFFFFFFDULL +#define DQUAD_ALIGN 0xFFFFFFFFFFFFFFFCULL /** This routine is used to check whether the pci device is present. @@ -32,11 +32,11 @@ extern EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityP **/ EFI_STATUS PciDevicePresent ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo, - OUT PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo, + OUT PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ) { UINT64 Address; @@ -58,7 +58,7 @@ PciDevicePresent ( Pci ); - if (!EFI_ERROR (Status) && (Pci->Hdr).VendorId != 0xffff) { + if (!EFI_ERROR (Status) && ((Pci->Hdr).VendorId != 0xffff)) { // // Read the entire config header for the device // @@ -91,37 +91,35 @@ PciDevicePresent ( **/ EFI_STATUS PciPciDeviceInfoCollector ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber ) { - EFI_STATUS Status; - PCI_TYPE00 Pci; - UINT8 Device; - UINT8 Func; - UINT8 SecBus; - PCI_IO_DEVICE *PciIoDevice; - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + PCI_TYPE00 Pci; + UINT8 Device; + UINT8 Func; + UINT8 SecBus; + PCI_IO_DEVICE *PciIoDevice; + EFI_PCI_IO_PROTOCOL *PciIo; - Status = EFI_SUCCESS; - SecBus = 0; + Status = EFI_SUCCESS; + SecBus = 0; for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { - for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { - // // Check to see whether PCI device is present // Status = PciDevicePresent ( Bridge->PciRootBridgeIo, &Pci, - (UINT8) StartBusNumber, - (UINT8) Device, - (UINT8) Func + (UINT8)StartBusNumber, + (UINT8)Device, + (UINT8)Func ); - if (EFI_ERROR (Status) && Func == 0) { + if (EFI_ERROR (Status) && (Func == 0)) { // // go to next device if there is no Function 0 // @@ -129,11 +127,10 @@ PciPciDeviceInfoCollector ( } if (!EFI_ERROR (Status)) { - // // Call back to host bridge function // - PreprocessController (Bridge, (UINT8) StartBusNumber, Device, Func, EfiPciBeforeResourceCollection); + PreprocessController (Bridge, (UINT8)StartBusNumber, Device, Func, EfiPciBeforeResourceCollection); // // Collect all the information about the PCI device discovered @@ -141,7 +138,7 @@ PciPciDeviceInfoCollector ( Status = PciSearchDevice ( Bridge, &Pci, - (UINT8) StartBusNumber, + (UINT8)StartBusNumber, Device, Func, &PciIoDevice @@ -152,13 +149,12 @@ PciPciDeviceInfoCollector ( // // if (!EFI_ERROR (Status) && (IS_PCI_BRIDGE (&Pci) || IS_CARDBUS_BRIDGE (&Pci))) { - // // If it is PPB, we need to get the secondary bus to continue the enumeration // - PciIo = &(PciIoDevice->PciIo); + PciIo = &(PciIoDevice->PciIo); - Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, PCI_BRIDGE_SECONDARY_BUS_REGISTER_OFFSET, 1, &SecBus); + Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, PCI_BRIDGE_SECONDARY_BUS_REGISTER_OFFSET, 1, &SecBus); if (EFI_ERROR (Status)) { return Status; @@ -182,20 +178,17 @@ PciPciDeviceInfoCollector ( // Status = PciPciDeviceInfoCollector ( PciIoDevice, - (UINT8) (SecBus) + (UINT8)(SecBus) ); - } - if (Func == 0 && !IS_PCI_MULTI_FUNC (&Pci)) { - + if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) { // // Skip sub functions, this is not a multi function device // Func = PCI_MAX_FUNC; } } - } } @@ -218,15 +211,15 @@ PciPciDeviceInfoCollector ( **/ EFI_STATUS PciSearchDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func, - OUT PCI_IO_DEVICE **PciDevice + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func, + OUT PCI_IO_DEVICE **PciDevice ) { - PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = NULL; @@ -235,12 +228,13 @@ PciSearchDevice ( "PciBus: Discovered %s @ [%02x|%02x|%02x]\n", IS_PCI_BRIDGE (Pci) ? L"PPB" : IS_CARDBUS_BRIDGE (Pci) ? L"P2C" : - L"PCI", - Bus, Device, Func + L"PCI", + Bus, + Device, + Func )); if (!IS_PCI_BRIDGE (Pci)) { - if (IS_CARDBUS_BRIDGE (Pci)) { PciIoDevice = GatherP2CInfo ( Bridge, @@ -253,7 +247,6 @@ PciSearchDevice ( InitializeP2C (PciIoDevice); } } else { - // // Create private data for Pci Device // @@ -264,11 +257,8 @@ PciSearchDevice ( Device, Func ); - } - } else { - // // Create private data for PPB // @@ -305,15 +295,11 @@ PciSearchDevice ( // Detect this function has option rom // if (gFullEnumeration) { - if (!IS_CARDBUS_BRIDGE (Pci)) { - GetOpRomInfo (PciIoDevice); - } ResetPowerManagementFeature (PciIoDevice); - } // @@ -341,28 +327,26 @@ PciSearchDevice ( **/ VOID DumpPpbPaddingResource ( - IN PCI_IO_DEVICE *PciIoDevice, - IN PCI_BAR_TYPE ResourceType + IN PCI_IO_DEVICE *PciIoDevice, + IN PCI_BAR_TYPE ResourceType ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - PCI_BAR_TYPE Type; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + PCI_BAR_TYPE Type; if (PciIoDevice->ResourcePaddingDescriptors == NULL) { return; } - if (ResourceType == PciBarTypeIo16 || ResourceType == PciBarTypeIo32) { + if ((ResourceType == PciBarTypeIo16) || (ResourceType == PciBarTypeIo32)) { ResourceType = PciBarTypeIo; } for (Descriptor = PciIoDevice->ResourcePaddingDescriptors; Descriptor->Desc != ACPI_END_TAG_DESCRIPTOR; Descriptor++) { - Type = PciBarTypeUnknown; - if (Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR && Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_IO) { + if ((Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_IO)) { Type = PciBarTypeIo; - } else if (Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR && Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { - + } else if ((Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM)) { if (Descriptor->AddrSpaceGranularity == 32) { // // prefetchable @@ -400,11 +384,12 @@ DumpPpbPaddingResource ( DEBUG (( DEBUG_INFO, " Padding: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx\n", - mBarTypeStr[Type], Descriptor->AddrRangeMax, Descriptor->AddrLen + mBarTypeStr[Type], + Descriptor->AddrRangeMax, + Descriptor->AddrLen )); } } - } /** @@ -414,10 +399,10 @@ DumpPpbPaddingResource ( **/ VOID DumpPciBars ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < PCI_MAX_BAR; Index++) { if (PciIoDevice->PciBar[Index].BarType == PciBarTypeUnknown) { @@ -427,8 +412,11 @@ DumpPciBars ( DEBUG (( DEBUG_INFO, " BAR[%d]: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx;\tOffset = 0x%02x\n", - Index, mBarTypeStr[MIN (PciIoDevice->PciBar[Index].BarType, PciBarTypeMaxType)], - PciIoDevice->PciBar[Index].Alignment, PciIoDevice->PciBar[Index].Length, PciIoDevice->PciBar[Index].Offset + Index, + mBarTypeStr[MIN (PciIoDevice->PciBar[Index].BarType, PciBarTypeMaxType)], + PciIoDevice->PciBar[Index].Alignment, + PciIoDevice->PciBar[Index].Length, + PciIoDevice->PciBar[Index].Offset )); } @@ -440,10 +428,14 @@ DumpPciBars ( DEBUG (( DEBUG_INFO, " VFBAR[%d]: Type = %s; Alignment = 0x%lx;\tLength = 0x%lx;\tOffset = 0x%02x\n", - Index, mBarTypeStr[MIN (PciIoDevice->VfPciBar[Index].BarType, PciBarTypeMaxType)], - PciIoDevice->VfPciBar[Index].Alignment, PciIoDevice->VfPciBar[Index].Length, PciIoDevice->VfPciBar[Index].Offset + Index, + mBarTypeStr[MIN (PciIoDevice->VfPciBar[Index].BarType, PciBarTypeMaxType)], + PciIoDevice->VfPciBar[Index].Alignment, + PciIoDevice->VfPciBar[Index].Length, + PciIoDevice->VfPciBar[Index].Offset )); } + DEBUG ((DEBUG_INFO, "\n")); } @@ -461,16 +453,16 @@ DumpPciBars ( **/ PCI_IO_DEVICE * GatherDeviceInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ) { - UINTN Offset; - UINTN BarIndex; - PCI_IO_DEVICE *PciIoDevice; + UINTN Offset; + UINTN BarIndex; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = CreatePciIoDevice ( Bridge, @@ -488,9 +480,7 @@ GatherDeviceInfo ( // If it is a full enumeration, disconnect the device in advance // if (gFullEnumeration) { - PCI_DISABLE_COMMAND_REGISTER (PciIoDevice, EFI_PCI_COMMAND_BITS_OWNED); - } // @@ -503,17 +493,19 @@ GatherDeviceInfo ( // // Parse the SR-IOV VF bars // - if (PcdGetBool (PcdSrIovSupport) && PciIoDevice->SrIovCapabilityOffset != 0) { + if (PcdGetBool (PcdSrIovSupport) && (PciIoDevice->SrIovCapabilityOffset != 0)) { for (Offset = PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_BAR0, BarIndex = 0; Offset <= PciIoDevice->SrIovCapabilityOffset + EFI_PCIE_CAPABILITY_ID_SRIOV_BAR5; - BarIndex++) { - + BarIndex++) + { ASSERT (BarIndex < PCI_MAX_BAR); Offset = PciIovParseVfBar (PciIoDevice, Offset, BarIndex); } } - DEBUG_CODE (DumpPciBars (PciIoDevice);); + DEBUG_CODE ( + DumpPciBars (PciIoDevice); + ); return PciIoDevice; } @@ -531,21 +523,21 @@ GatherDeviceInfo ( **/ PCI_IO_DEVICE * GatherPpbInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ) { - PCI_IO_DEVICE *PciIoDevice; - EFI_STATUS Status; - UINT8 Value; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT8 Temp; - UINT32 PMemBaseLimit; - UINT16 PrefetchableMemoryBase; - UINT16 PrefetchableMemoryLimit; + PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + UINT8 Value; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 Temp; + UINT32 PMemBaseLimit; + UINT16 PrefetchableMemoryBase; + UINT16 PrefetchableMemoryLimit; PciIoDevice = CreatePciIoDevice ( Bridge, @@ -566,7 +558,6 @@ GatherPpbInfo ( // Initialize the bridge control register // PCI_DISABLE_BRIDGE_CONTROL_REGISTER (PciIoDevice, EFI_PCI_BRIDGE_CONTROL_BITS_OWNED); - } // @@ -628,11 +619,11 @@ GatherPpbInfo ( } Status = BarExisted ( - PciIoDevice, - 0x24, - NULL, - &PMemBaseLimit - ); + PciIoDevice, + 0x24, + NULL, + &PMemBaseLimit + ); // // Test if it supports 64 memory or not @@ -642,17 +633,18 @@ GatherPpbInfo ( // 0 - the bridge supports only 32 bit addresses. // 1 - the bridge supports 64-bit addresses. // - PrefetchableMemoryBase = (UINT16)(PMemBaseLimit & 0xffff); + PrefetchableMemoryBase = (UINT16)(PMemBaseLimit & 0xffff); PrefetchableMemoryLimit = (UINT16)(PMemBaseLimit >> 16); if (!EFI_ERROR (Status) && - (PrefetchableMemoryBase & 0x000f) == 0x0001 && - (PrefetchableMemoryLimit & 0x000f) == 0x0001) { + ((PrefetchableMemoryBase & 0x000f) == 0x0001) && + ((PrefetchableMemoryLimit & 0x000f) == 0x0001)) + { Status = BarExisted ( - PciIoDevice, - 0x28, - NULL, - NULL - ); + PciIoDevice, + 0x28, + NULL, + NULL + ); if (!EFI_ERROR (Status)) { PciIoDevice->Decodes |= EFI_BRIDGE_PMEM32_DECODE_SUPPORTED; @@ -672,12 +664,11 @@ GatherPpbInfo ( DEBUG_CODE ( DumpPpbPaddingResource (PciIoDevice, PciBarTypeUnknown); DumpPciBars (PciIoDevice); - ); + ); return PciIoDevice; } - /** Create PCI device instance for PCI Card bridge device. @@ -692,14 +683,14 @@ GatherPpbInfo ( **/ PCI_IO_DEVICE * GatherP2CInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ) { - PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = CreatePciIoDevice ( Bridge, @@ -735,7 +726,9 @@ GatherP2CInfo ( EFI_BRIDGE_PMEM32_DECODE_SUPPORTED | EFI_BRIDGE_IO32_DECODE_SUPPORTED; - DEBUG_CODE (DumpPciBars (PciIoDevice);); + DEBUG_CODE ( + DumpPciBars (PciIoDevice); + ); return PciIoDevice; } @@ -751,18 +744,17 @@ GatherP2CInfo ( **/ EFI_DEVICE_PATH_PROTOCOL * CreatePciDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, - IN PCI_IO_DEVICE *PciIoDevice + IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, + IN PCI_IO_DEVICE *PciIoDevice ) { - - PCI_DEVICE_PATH PciNode; + PCI_DEVICE_PATH PciNode; // // Create PCI device path // - PciNode.Header.Type = HARDWARE_DEVICE_PATH; - PciNode.Header.SubType = HW_PCI_DP; + PciNode.Header.Type = HARDWARE_DEVICE_PATH; + PciNode.Header.SubType = HW_PCI_DP; SetDevicePathNodeLength (&PciNode.Header, sizeof (PciNode)); PciNode.Device = PciIoDevice->DeviceNumber; @@ -786,16 +778,16 @@ CreatePciDevicePath ( **/ EFI_STATUS VfBarExisted ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINTN Offset, - OUT UINT32 *BarLengthValue, - OUT UINT32 *OriginalBarValue + IN PCI_IO_DEVICE *PciIoDevice, + IN UINTN Offset, + OUT UINT32 *BarLengthValue, + OUT UINT32 *OriginalBarValue ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT32 OriginalValue; - UINT32 Value; - EFI_TPL OldTpl; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT32 OriginalValue; + UINT32 Value; + EFI_TPL OldTpl; // // Ensure it is called properly @@ -860,36 +852,36 @@ VfBarExisted ( **/ EFI_STATUS BarExisted ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINTN Offset, - OUT UINT32 *BarLengthValue, - OUT UINT32 *OriginalBarValue + IN PCI_IO_DEVICE *PciIoDevice, + IN UINTN Offset, + OUT UINT32 *BarLengthValue, + OUT UINT32 *OriginalBarValue ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT32 OriginalValue; - UINT32 Value; - EFI_TPL OldTpl; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT32 OriginalValue; + UINT32 Value; + EFI_TPL OldTpl; PciIo = &PciIoDevice->PciIo; // // Preserve the original value // - PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8) Offset, 1, &OriginalValue); + PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &OriginalValue); // // Raise TPL to high level to disable timer interrupt while the BAR is probed // OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL); - PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8) Offset, 1, &gAllOne); - PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8) Offset, 1, &Value); + PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &gAllOne); + PciIo->Pci.Read (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &Value); // // Write back the original value // - PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8) Offset, 1, &OriginalValue); + PciIo->Pci.Write (PciIo, EfiPciIoWidthUint32, (UINT8)Offset, 1, &OriginalValue); // // Restore TPL to its original level @@ -925,15 +917,15 @@ BarExisted ( **/ VOID PciTestSupportedAttribute ( - IN PCI_IO_DEVICE *PciIoDevice, - IN OUT UINT16 *Command, - IN OUT UINT16 *BridgeControl, - OUT UINT16 *OldCommand, - OUT UINT16 *OldBridgeControl + IN PCI_IO_DEVICE *PciIoDevice, + IN OUT UINT16 *Command, + IN OUT UINT16 *BridgeControl, + OUT UINT16 *OldCommand, + OUT UINT16 *OldBridgeControl ) { - EFI_TPL OldTpl; - UINT16 CommandValue; + EFI_TPL OldTpl; + UINT16 CommandValue; // // Preserve the original value @@ -943,7 +935,7 @@ PciTestSupportedAttribute ( // // Raise TPL to high level to disable timer interrupt while the BAR is probed // - OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL); + OldTpl = gBS->RaiseTPL (TPL_HIGH_LEVEL); CommandValue = *Command | *OldCommand; PCI_SET_COMMAND_REGISTER (PciIoDevice, CommandValue); @@ -961,7 +953,6 @@ PciTestSupportedAttribute ( gBS->RestoreTPL (OldTpl); if (IS_PCI_BRIDGE (&PciIoDevice->Pci) || IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) { - // // Preserve the original value // @@ -984,7 +975,6 @@ PciTestSupportedAttribute ( // Restore TPL to its original level // gBS->RestoreTPL (OldTpl); - } else { *OldBridgeControl = 0; *BridgeControl = 0; @@ -1002,10 +992,10 @@ PciTestSupportedAttribute ( **/ VOID PciSetDeviceAttribute ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 Command, - IN UINT16 BridgeControl, - IN UINTN Option + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 Command, + IN UINT16 BridgeControl, + IN UINTN Option ) { UINT64 Attributes; @@ -1044,18 +1034,17 @@ PciSetDeviceAttribute ( } if (Option == EFI_SET_SUPPORTS) { - - Attributes |= (UINT64) (EFI_PCI_IO_ATTRIBUTE_MEMORY_WRITE_COMBINE | - EFI_PCI_IO_ATTRIBUTE_MEMORY_CACHED | - EFI_PCI_IO_ATTRIBUTE_MEMORY_DISABLE | - EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE | - EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM | - EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE); + Attributes |= (UINT64)(EFI_PCI_IO_ATTRIBUTE_MEMORY_WRITE_COMBINE | + EFI_PCI_IO_ATTRIBUTE_MEMORY_CACHED | + EFI_PCI_IO_ATTRIBUTE_MEMORY_DISABLE | + EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE | + EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM | + EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE); if (IS_PCI_LPC (&PciIoDevice->Pci)) { - Attributes |= EFI_PCI_IO_ATTRIBUTE_ISA_MOTHERBOARD_IO; - Attributes |= (mReserveIsaAliases ? (UINT64) EFI_PCI_IO_ATTRIBUTE_ISA_IO : \ - (UINT64) EFI_PCI_IO_ATTRIBUTE_ISA_IO_16); + Attributes |= EFI_PCI_IO_ATTRIBUTE_ISA_MOTHERBOARD_IO; + Attributes |= (mReserveIsaAliases ? (UINT64)EFI_PCI_IO_ATTRIBUTE_ISA_IO : \ + (UINT64)EFI_PCI_IO_ATTRIBUTE_ISA_IO_16); } if (IS_PCI_BRIDGE (&PciIoDevice->Pci) || IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) { @@ -1073,7 +1062,6 @@ PciSetDeviceAttribute ( EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO); } } else { - if (IS_PCI_IDE (&PciIoDevice->Pci)) { Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_SECONDARY_IO; Attributes |= EFI_PCI_IO_ATTRIBUTE_IDE_PRIMARY_IO; @@ -1081,16 +1069,15 @@ PciSetDeviceAttribute ( if (IS_PCI_VGA (&PciIoDevice->Pci)) { Attributes |= EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY; - Attributes |= (mReserveVgaAliases ? (UINT64) EFI_PCI_IO_ATTRIBUTE_VGA_IO : \ - (UINT64) EFI_PCI_IO_ATTRIBUTE_VGA_IO_16); + Attributes |= (mReserveVgaAliases ? (UINT64)EFI_PCI_IO_ATTRIBUTE_VGA_IO : \ + (UINT64)EFI_PCI_IO_ATTRIBUTE_VGA_IO_16); } } - PciIoDevice->Supports = Attributes; - PciIoDevice->Supports &= ( (PciIoDevice->Parent->Supports) | \ - EFI_PCI_IO_ATTRIBUTE_IO | EFI_PCI_IO_ATTRIBUTE_MEMORY | \ - EFI_PCI_IO_ATTRIBUTE_BUS_MASTER ); - + PciIoDevice->Supports = Attributes; + PciIoDevice->Supports &= ((PciIoDevice->Parent->Supports) | \ + EFI_PCI_IO_ATTRIBUTE_IO | EFI_PCI_IO_ATTRIBUTE_MEMORY | \ + EFI_PCI_IO_ATTRIBUTE_BUS_MASTER); } else { // // When this attribute is clear, the RomImage and RomSize fields in the PCI IO were @@ -1101,6 +1088,7 @@ PciSetDeviceAttribute ( if (!PciIoDevice->EmbeddedRom) { Attributes |= EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM; } + PciIoDevice->Attributes = Attributes; } } @@ -1117,19 +1105,19 @@ PciSetDeviceAttribute ( **/ EFI_STATUS GetFastBackToBackSupport ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 StatusIndex + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 StatusIndex ) { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT32 StatusRegister; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT32 StatusRegister; // // Read the status register // - PciIo = &PciIoDevice->PciIo; - Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint16, StatusIndex, 1, &StatusRegister); + PciIo = &PciIoDevice->PciIo; + Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint16, StatusIndex, 1, &StatusRegister); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -1153,18 +1141,17 @@ GetFastBackToBackSupport ( **/ VOID ProcessOptionRomLight ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - PCI_IO_DEVICE *Temp; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; // // For RootBridge, PPB , P2C, go recursively to traverse all its children // CurrentLink = PciIoDevice->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) { - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (!IsListEmpty (&Temp->ChildList)) { @@ -1185,17 +1172,17 @@ ProcessOptionRomLight ( **/ EFI_STATUS DetermineDeviceAttribute ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - UINT16 Command; - UINT16 BridgeControl; - UINT16 OldCommand; - UINT16 OldBridgeControl; - BOOLEAN FastB2BSupport; - PCI_IO_DEVICE *Temp; - LIST_ENTRY *CurrentLink; - EFI_STATUS Status; + UINT16 Command; + UINT16 BridgeControl; + UINT16 OldCommand; + UINT16 OldBridgeControl; + BOOLEAN FastB2BSupport; + PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + EFI_STATUS Status; // // For Root Bridge, just copy it by RootBridgeIo protocol @@ -1203,22 +1190,21 @@ DetermineDeviceAttribute ( // if (PciIoDevice->Parent == NULL) { Status = PciIoDevice->PciRootBridgeIo->GetAttributes ( - PciIoDevice->PciRootBridgeIo, - &PciIoDevice->Supports, - &PciIoDevice->Attributes - ); + PciIoDevice->PciRootBridgeIo, + &PciIoDevice->Supports, + &PciIoDevice->Attributes + ); if (EFI_ERROR (Status)) { return Status; } + // // Assume the PCI Root Bridge supports DAC // PciIoDevice->Supports |= (UINT64)(EFI_PCI_IO_ATTRIBUTE_EMBEDDED_DEVICE | - EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM | - EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE); - + EFI_PCI_IO_ATTRIBUTE_EMBEDDED_ROM | + EFI_PCI_IO_ATTRIBUTE_DUAL_ADDRESS_CYCLE); } else { - // // Set the attributes to be checked for common PCI devices and PPB or P2C // Since some devices only support part of them, it is better to set the @@ -1268,12 +1254,12 @@ DetermineDeviceAttribute ( // CurrentLink = PciIoDevice->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &PciIoDevice->ChildList) { - - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); - Status = DetermineDeviceAttribute (Temp); + Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); + Status = DetermineDeviceAttribute (Temp); if (EFI_ERROR (Status)) { return Status; } + // // Detect Fast Back to Back support for the device under the bridge // @@ -1284,13 +1270,12 @@ DetermineDeviceAttribute ( CurrentLink = CurrentLink->ForwardLink; } + // // Set or clear Fast Back to Back bit for the whole bridge // if (!IsListEmpty (&PciIoDevice->ChildList)) { - if (IS_PCI_BRIDGE (&PciIoDevice->Pci)) { - Status = GetFastBackToBackSupport (PciIoDevice, PCI_BRIDGE_STATUS_REGISTER_OFFSET); if (EFI_ERROR (Status) || (!FastB2BSupport)) { @@ -1313,6 +1298,7 @@ DetermineDeviceAttribute ( CurrentLink = CurrentLink->ForwardLink; } } + // // End for IsListEmpty // @@ -1331,14 +1317,14 @@ DetermineDeviceAttribute ( **/ EFI_STATUS UpdatePciInfo ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ) { - EFI_STATUS Status; - UINTN BarIndex; - BOOLEAN SetFlag; - VOID *Configuration; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; + EFI_STATUS Status; + UINTN BarIndex; + BOOLEAN SetFlag; + VOID *Configuration; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; Configuration = NULL; Status = EFI_SUCCESS; @@ -1351,37 +1337,36 @@ UpdatePciInfo ( Status = gBS->LocateProtocol ( &gEfiIncompatiblePciDeviceSupportProtocolGuid, NULL, - (VOID **) &gIncompatiblePciDeviceSupport + (VOID **)&gIncompatiblePciDeviceSupport ); } - if (Status == EFI_SUCCESS) { - // - // Check whether the device belongs to incompatible devices from protocol or not - // If it is , then get its special requirement in the ACPI table - // - Status = gIncompatiblePciDeviceSupport->CheckDevice ( - gIncompatiblePciDeviceSupport, - PciIoDevice->Pci.Hdr.VendorId, - PciIoDevice->Pci.Hdr.DeviceId, - PciIoDevice->Pci.Hdr.RevisionID, - PciIoDevice->Pci.Device.SubsystemVendorID, - PciIoDevice->Pci.Device.SubsystemID, - &Configuration - ); + if (Status == EFI_SUCCESS) { + // + // Check whether the device belongs to incompatible devices from protocol or not + // If it is , then get its special requirement in the ACPI table + // + Status = gIncompatiblePciDeviceSupport->CheckDevice ( + gIncompatiblePciDeviceSupport, + PciIoDevice->Pci.Hdr.VendorId, + PciIoDevice->Pci.Hdr.DeviceId, + PciIoDevice->Pci.Hdr.RevisionID, + PciIoDevice->Pci.Device.SubsystemVendorID, + PciIoDevice->Pci.Device.SubsystemID, + &Configuration + ); } - if (EFI_ERROR (Status) || Configuration == NULL ) { + if (EFI_ERROR (Status) || (Configuration == NULL)) { return EFI_UNSUPPORTED; } // // Update PCI device information from the ACPI table // - Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; + Ptr = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; while (Ptr->Desc != ACPI_END_TAG_DESCRIPTOR) { - if (Ptr->Desc != ACPI_ADDRESS_SPACE_DESCRIPTOR) { // // The format is not support @@ -1393,7 +1378,8 @@ UpdatePciInfo ( if ((Ptr->AddrTranslationOffset != MAX_UINT64) && (Ptr->AddrTranslationOffset != MAX_UINT8) && (Ptr->AddrTranslationOffset != BarIndex) - ) { + ) + { // // Skip updating when AddrTranslationOffset is not MAX_UINT64 or MAX_UINT8 (wide match). // Skip updating when current BarIndex doesn't equal to AddrTranslationOffset. @@ -1404,61 +1390,62 @@ UpdatePciInfo ( SetFlag = FALSE; switch (Ptr->ResType) { - case ACPI_ADDRESS_SPACE_TYPE_MEM: - - // - // Make sure the bar is memory type - // - if (CheckBarType (PciIoDevice, (UINT8) BarIndex, PciBarTypeMem)) { - SetFlag = TRUE; + case ACPI_ADDRESS_SPACE_TYPE_MEM: // - // Ignored if granularity is 0. - // Ignored if PCI BAR is I/O or 32-bit memory. - // If PCI BAR is 64-bit memory and granularity is 32, then - // the PCI BAR resource is allocated below 4GB. - // If PCI BAR is 64-bit memory and granularity is 64, then - // the PCI BAR resource is allocated above 4GB. + // Make sure the bar is memory type // - if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypeMem64) { - switch (Ptr->AddrSpaceGranularity) { - case 32: - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32; - case 64: - PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE; - break; - default: - break; + if (CheckBarType (PciIoDevice, (UINT8)BarIndex, PciBarTypeMem)) { + SetFlag = TRUE; + + // + // Ignored if granularity is 0. + // Ignored if PCI BAR is I/O or 32-bit memory. + // If PCI BAR is 64-bit memory and granularity is 32, then + // the PCI BAR resource is allocated below 4GB. + // If PCI BAR is 64-bit memory and granularity is 64, then + // the PCI BAR resource is allocated above 4GB. + // + if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypeMem64) { + switch (Ptr->AddrSpaceGranularity) { + case 32: + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32; + case 64: + PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE; + break; + default: + break; + } } - } - if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypePMem64) { - switch (Ptr->AddrSpaceGranularity) { - case 32: - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32; - case 64: - PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE; - break; - default: - break; + if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypePMem64) { + switch (Ptr->AddrSpaceGranularity) { + case 32: + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32; + case 64: + PciIoDevice->PciBar[BarIndex].BarTypeFixed = TRUE; + break; + default: + break; + } } } - } - break; - case ACPI_ADDRESS_SPACE_TYPE_IO: + break; - // - // Make sure the bar is IO type - // - if (CheckBarType (PciIoDevice, (UINT8) BarIndex, PciBarTypeIo)) { - SetFlag = TRUE; - } - break; + case ACPI_ADDRESS_SPACE_TYPE_IO: + + // + // Make sure the bar is IO type + // + if (CheckBarType (PciIoDevice, (UINT8)BarIndex, PciBarTypeIo)) { + SetFlag = TRUE; + } + + break; } if (SetFlag) { - // // Update the new alignment for the device // @@ -1492,8 +1479,8 @@ UpdatePciInfo ( **/ VOID SetNewAlign ( - IN OUT UINT64 *Alignment, - IN UINT64 NewAlignment + IN OUT UINT64 *Alignment, + IN UINT64 NewAlignment ) { UINT64 OldAlignment; @@ -1504,27 +1491,29 @@ SetNewAlign ( // so skip it // if ((NewAlignment == 0) || (NewAlignment == OLD_ALIGN)) { - return ; + return; } + // // Check the validity of the parameter // - if (NewAlignment != EVEN_ALIGN && - NewAlignment != SQUAD_ALIGN && - NewAlignment != DQUAD_ALIGN ) { + if ((NewAlignment != EVEN_ALIGN) && + (NewAlignment != SQUAD_ALIGN) && + (NewAlignment != DQUAD_ALIGN)) + { *Alignment = NewAlignment; - return ; + return; } - OldAlignment = (*Alignment) + 1; - ShiftBit = 0; + OldAlignment = (*Alignment) + 1; + ShiftBit = 0; // // Get the first non-zero hex value of the length // while ((OldAlignment & 0x0F) == 0x00) { OldAlignment = RShiftU64 (OldAlignment, 4); - ShiftBit += 4; + ShiftBit += 4; } // @@ -1547,10 +1536,10 @@ SetNewAlign ( // // Update the old value // - NewAlignment = LShiftU64 (OldAlignment, ShiftBit) - 1; - *Alignment = NewAlignment; + NewAlignment = LShiftU64 (OldAlignment, ShiftBit) - 1; + *Alignment = NewAlignment; - return ; + return; } /** @@ -1587,11 +1576,11 @@ PciIovParseVfBar ( Value = 0; Status = VfBarExisted ( - PciIoDevice, - Offset, - &Value, - &OriginalValue - ); + PciIoDevice, + Offset, + &Value, + &OriginalValue + ); if (EFI_ERROR (Status)) { PciIoDevice->VfPciBar[BarIndex].BaseAddress = 0; @@ -1601,133 +1590,130 @@ PciIovParseVfBar ( // // Scan all the BARs anyway // - PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16) Offset; + PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16)Offset; return Offset + 4; } - PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16) Offset; + PciIoDevice->VfPciBar[BarIndex].Offset = (UINT16)Offset; if ((Value & 0x01) != 0) { // // Device I/Os. Impossible // ASSERT (FALSE); return Offset + 4; - } else { - - Mask = 0xfffffff0; + Mask = 0xfffffff0; PciIoDevice->VfPciBar[BarIndex].BaseAddress = OriginalValue & Mask; switch (Value & 0x07) { + // + // memory space; anywhere in 32 bit address space + // + case 0x00: + if ((Value & 0x08) != 0) { + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem32; + } else { + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem32; + } - // - //memory space; anywhere in 32 bit address space - // - case 0x00: - if ((Value & 0x08) != 0) { - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem32; - } else { - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem32; - } + PciIoDevice->VfPciBar[BarIndex].Length = (~(Value & Mask)) + 1; + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; + + // + // Adjust Length + // + PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs); + // + // Adjust Alignment + // + if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; + } - PciIoDevice->VfPciBar[BarIndex].Length = (~(Value & Mask)) + 1; - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; + break; // - // Adjust Length - // - PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs); + // memory space; anywhere in 64 bit address space // - // Adjust Alignment - // - if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; - } + case 0x04: + if ((Value & 0x08) != 0) { + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem64; + } else { + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem64; + } - break; + // + // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar + // is regarded as an extension for the first bar. As a result + // the sizing will be conducted on combined 64 bit value + // Here just store the masked first 32bit value for future size + // calculation + // + PciIoDevice->VfPciBar[BarIndex].Length = Value & Mask; + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; - // - // memory space; anywhere in 64 bit address space - // - case 0x04: - if ((Value & 0x08) != 0) { - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypePMem64; - } else { - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeMem64; - } + if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; + } - // - // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar - // is regarded as an extension for the first bar. As a result - // the sizing will be conducted on combined 64 bit value - // Here just store the masked first 32bit value for future size - // calculation - // - PciIoDevice->VfPciBar[BarIndex].Length = Value & Mask; - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; + // + // Increment the offset to point to next DWORD + // + Offset += 4; - if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; - } + Status = VfBarExisted ( + PciIoDevice, + Offset, + &Value, + &OriginalValue + ); - // - // Increment the offset to point to next DWORD - // - Offset += 4; + if (EFI_ERROR (Status)) { + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeUnknown; + return Offset + 4; + } - Status = VfBarExisted ( - PciIoDevice, - Offset, - &Value, - &OriginalValue - ); + // + // Fix the length to support some special 64 bit BAR + // + Value |= ((UINT32)-1 << HighBitSet32 (Value)); - if (EFI_ERROR (Status)) { - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeUnknown; - return Offset + 4; - } + // + // Calculate the size of 64bit bar + // + PciIoDevice->VfPciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64)OriginalValue, 32); - // - // Fix the length to support some special 64 bit BAR - // - Value |= ((UINT32) -1 << HighBitSet32 (Value)); + PciIoDevice->VfPciBar[BarIndex].Length = PciIoDevice->VfPciBar[BarIndex].Length | LShiftU64 ((UINT64)Value, 32); + PciIoDevice->VfPciBar[BarIndex].Length = (~(PciIoDevice->VfPciBar[BarIndex].Length)) + 1; + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; - // - // Calculate the size of 64bit bar - // - PciIoDevice->VfPciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64) OriginalValue, 32); + // + // Adjust Length + // + PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs); + // + // Adjust Alignment + // + if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; + } - PciIoDevice->VfPciBar[BarIndex].Length = PciIoDevice->VfPciBar[BarIndex].Length | LShiftU64 ((UINT64) Value, 32); - PciIoDevice->VfPciBar[BarIndex].Length = (~(PciIoDevice->VfPciBar[BarIndex].Length)) + 1; - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; + break; // - // Adjust Length - // - PciIoDevice->VfPciBar[BarIndex].Length = MultU64x32 (PciIoDevice->VfPciBar[BarIndex].Length, PciIoDevice->InitialVFs); - // - // Adjust Alignment + // reserved // - if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; - } - - break; + default: + PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeUnknown; + PciIoDevice->VfPciBar[BarIndex].Length = (~(Value & Mask)) + 1; + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; - // - // reserved - // - default: - PciIoDevice->VfPciBar[BarIndex].BarType = PciBarTypeUnknown; - PciIoDevice->VfPciBar[BarIndex].Length = (~(Value & Mask)) + 1; - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->VfPciBar[BarIndex].Length - 1; - - if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { - PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; - } + if (PciIoDevice->VfPciBar[BarIndex].Alignment < PciIoDevice->SystemPageSize - 1) { + PciIoDevice->VfPciBar[BarIndex].Alignment = PciIoDevice->SystemPageSize - 1; + } - break; + break; } } @@ -1786,12 +1772,12 @@ PciParseBar ( // // Some devices don't fully comply to PCI spec 2.2. So be to scan all the BARs anyway // - PciIoDevice->PciBar[BarIndex].Offset = (UINT8) Offset; + PciIoDevice->PciBar[BarIndex].Offset = (UINT8)Offset; return Offset + 4; } PciIoDevice->PciBar[BarIndex].BarTypeFixed = FALSE; - PciIoDevice->PciBar[BarIndex].Offset = (UINT8) Offset; + PciIoDevice->PciBar[BarIndex].Offset = (UINT8)Offset; if ((Value & 0x01) != 0) { // // Device I/Os @@ -1805,7 +1791,6 @@ PciParseBar ( PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeIo32; PciIoDevice->PciBar[BarIndex].Length = ((~(Value & Mask)) + 1); PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; - } else { // // It is a IO16 bar @@ -1813,135 +1798,134 @@ PciParseBar ( PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeIo16; PciIoDevice->PciBar[BarIndex].Length = 0x0000FFFF & ((~(Value & Mask)) + 1); PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; - } + // // Workaround. Some platforms implement IO bar with 0 length // Need to treat it as no-bar // if (PciIoDevice->PciBar[BarIndex].Length == 0) { - PciIoDevice->PciBar[BarIndex].BarType = (PCI_BAR_TYPE) 0; + PciIoDevice->PciBar[BarIndex].BarType = (PCI_BAR_TYPE)0; } - PciIoDevice->PciBar[BarIndex].BaseAddress = OriginalValue & Mask; - + PciIoDevice->PciBar[BarIndex].BaseAddress = OriginalValue & Mask; } else { - - Mask = 0xfffffff0; + Mask = 0xfffffff0; PciIoDevice->PciBar[BarIndex].BaseAddress = OriginalValue & Mask; switch (Value & 0x07) { + // + // memory space; anywhere in 32 bit address space + // + case 0x00: + if ((Value & 0x08) != 0) { + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32; + } else { + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32; + } - // - //memory space; anywhere in 32 bit address space - // - case 0x00: - if ((Value & 0x08) != 0) { - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem32; - } else { - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem32; - } + PciIoDevice->PciBar[BarIndex].Length = (~(Value & Mask)) + 1; + if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { + // + // Force minimum 4KByte alignment for Virtualization technology for Directed I/O + // + PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); + } else { + PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; + } + + break; + + // + // memory space; anywhere in 64 bit address space + // + case 0x04: + if ((Value & 0x08) != 0) { + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem64; + } else { + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem64; + } - PciIoDevice->PciBar[BarIndex].Length = (~(Value & Mask)) + 1; - if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { // - // Force minimum 4KByte alignment for Virtualization technology for Directed I/O + // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar + // is regarded as an extension for the first bar. As a result + // the sizing will be conducted on combined 64 bit value + // Here just store the masked first 32bit value for future size + // calculation // - PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); - } else { + PciIoDevice->PciBar[BarIndex].Length = Value & Mask; PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; - } - break; - // - // memory space; anywhere in 64 bit address space - // - case 0x04: - if ((Value & 0x08) != 0) { - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypePMem64; - } else { - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeMem64; - } + // + // Increment the offset to point to next DWORD + // + Offset += 4; - // - // According to PCI 2.2,if the bar indicates a memory 64 decoding, next bar - // is regarded as an extension for the first bar. As a result - // the sizing will be conducted on combined 64 bit value - // Here just store the masked first 32bit value for future size - // calculation - // - PciIoDevice->PciBar[BarIndex].Length = Value & Mask; - PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; + Status = BarExisted ( + PciIoDevice, + Offset, + &Value, + &OriginalValue + ); - // - // Increment the offset to point to next DWORD - // - Offset += 4; + if (EFI_ERROR (Status)) { + // + // the high 32 bit does not claim any BAR, we need to re-check the low 32 bit BAR again + // + if (PciIoDevice->PciBar[BarIndex].Length == 0) { + // + // some device implement MMIO bar with 0 length, need to treat it as no-bar + // + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown; + return Offset + 4; + } + } - Status = BarExisted ( - PciIoDevice, - Offset, - &Value, - &OriginalValue - ); + // + // Fix the length to support some special 64 bit BAR + // + if (Value == 0) { + DEBUG ((DEBUG_INFO, "[PciBus]BAR probing for upper 32bit of MEM64 BAR returns 0, change to 0xFFFFFFFF.\n")); + Value = (UINT32)-1; + } else { + Value |= ((UINT32)(-1) << HighBitSet32 (Value)); + } - if (EFI_ERROR (Status)) { // - // the high 32 bit does not claim any BAR, we need to re-check the low 32 bit BAR again + // Calculate the size of 64bit bar // - if (PciIoDevice->PciBar[BarIndex].Length == 0) { + PciIoDevice->PciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64)OriginalValue, 32); + + PciIoDevice->PciBar[BarIndex].Length = PciIoDevice->PciBar[BarIndex].Length | LShiftU64 ((UINT64)Value, 32); + PciIoDevice->PciBar[BarIndex].Length = (~(PciIoDevice->PciBar[BarIndex].Length)) + 1; + if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { // - // some device implement MMIO bar with 0 length, need to treat it as no-bar + // Force minimum 4KByte alignment for Virtualization technology for Directed I/O // - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown; - return Offset + 4; + PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); + } else { + PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; } - } - // - // Fix the length to support some special 64 bit BAR - // - if (Value == 0) { - DEBUG ((DEBUG_INFO, "[PciBus]BAR probing for upper 32bit of MEM64 BAR returns 0, change to 0xFFFFFFFF.\n")); - Value = (UINT32) -1; - } else { - Value |= ((UINT32)(-1) << HighBitSet32 (Value)); - } + break; // - // Calculate the size of 64bit bar + // reserved // - PciIoDevice->PciBar[BarIndex].BaseAddress |= LShiftU64 ((UINT64) OriginalValue, 32); - - PciIoDevice->PciBar[BarIndex].Length = PciIoDevice->PciBar[BarIndex].Length | LShiftU64 ((UINT64) Value, 32); - PciIoDevice->PciBar[BarIndex].Length = (~(PciIoDevice->PciBar[BarIndex].Length)) + 1; - if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { - // - // Force minimum 4KByte alignment for Virtualization technology for Directed I/O - // - PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); - } else { - PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; - } - - break; + default: + PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown; + PciIoDevice->PciBar[BarIndex].Length = (~(Value & Mask)) + 1; + if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { + // + // Force minimum 4KByte alignment for Virtualization technology for Directed I/O + // + PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); + } else { + PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; + } - // - // reserved - // - default: - PciIoDevice->PciBar[BarIndex].BarType = PciBarTypeUnknown; - PciIoDevice->PciBar[BarIndex].Length = (~(Value & Mask)) + 1; - if (PciIoDevice->PciBar[BarIndex].Length < (SIZE_4KB)) { - // - // Force minimum 4KByte alignment for Virtualization technology for Directed I/O - // - PciIoDevice->PciBar[BarIndex].Alignment = (SIZE_4KB - 1); - } else { - PciIoDevice->PciBar[BarIndex].Alignment = PciIoDevice->PciBar[BarIndex].Length - 1; - } - break; + break; } } @@ -1970,11 +1954,11 @@ PciParseBar ( **/ VOID InitializePciDevice ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT8 Offset; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 Offset; PciIo = &(PciIoDevice->PciIo); @@ -1996,10 +1980,10 @@ InitializePciDevice ( **/ VOID InitializePpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; PciIo = &(PciIoDevice->PciIo); @@ -2040,10 +2024,10 @@ InitializePpb ( **/ VOID InitializeP2C ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; PciIo = &(PciIoDevice->PciIo); @@ -2081,7 +2065,7 @@ InitializeP2C ( **/ EFI_STATUS AuthenticatePciDevice ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { EDKII_DEVICE_IDENTIFIER DeviceIdentifier; @@ -2094,15 +2078,15 @@ AuthenticatePciDevice ( DeviceIdentifier.Version = EDKII_DEVICE_IDENTIFIER_REVISION; CopyGuid (&DeviceIdentifier.DeviceType, &gEdkiiDeviceIdentifierTypePciGuid); DeviceIdentifier.DeviceHandle = NULL; - Status = gBS->InstallMultipleProtocolInterfaces ( - &DeviceIdentifier.DeviceHandle, - &gEfiDevicePathProtocolGuid, - PciIoDevice->DevicePath, - &gEdkiiDeviceIdentifierTypePciGuid, - &PciIoDevice->PciIo, - NULL - ); - if (EFI_ERROR(Status)) { + Status = gBS->InstallMultipleProtocolInterfaces ( + &DeviceIdentifier.DeviceHandle, + &gEfiDevicePathProtocolGuid, + PciIoDevice->DevicePath, + &gEdkiiDeviceIdentifierTypePciGuid, + &PciIoDevice->PciIo, + NULL + ); + if (EFI_ERROR (Status)) { return Status; } @@ -2115,13 +2099,13 @@ AuthenticatePciDevice ( // No need to check return Status. // gBS->UninstallMultipleProtocolInterfaces ( - DeviceIdentifier.DeviceHandle, - &gEfiDevicePathProtocolGuid, - PciIoDevice->DevicePath, - &gEdkiiDeviceIdentifierTypePciGuid, - &PciIoDevice->PciIo, - NULL - ); + DeviceIdentifier.DeviceHandle, + &gEfiDevicePathProtocolGuid, + PciIoDevice->DevicePath, + &gEdkiiDeviceIdentifierTypePciGuid, + &PciIoDevice->PciIo, + NULL + ); return Status; } @@ -2146,11 +2130,11 @@ AuthenticatePciDevice ( **/ PCI_IO_DEVICE * CreatePciIoDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ) { PCI_IO_DEVICE *PciIoDevice; @@ -2162,14 +2146,14 @@ CreatePciIoDevice ( return NULL; } - PciIoDevice->Signature = PCI_IO_DEVICE_SIGNATURE; - PciIoDevice->Handle = NULL; - PciIoDevice->PciRootBridgeIo = Bridge->PciRootBridgeIo; - PciIoDevice->DevicePath = NULL; - PciIoDevice->BusNumber = Bus; - PciIoDevice->DeviceNumber = Device; - PciIoDevice->FunctionNumber = Func; - PciIoDevice->Decodes = 0; + PciIoDevice->Signature = PCI_IO_DEVICE_SIGNATURE; + PciIoDevice->Handle = NULL; + PciIoDevice->PciRootBridgeIo = Bridge->PciRootBridgeIo; + PciIoDevice->DevicePath = NULL; + PciIoDevice->BusNumber = Bus; + PciIoDevice->DeviceNumber = Device; + PciIoDevice->FunctionNumber = Func; + PciIoDevice->Decodes = 0; if (gFullEnumeration) { PciIoDevice->Allocated = FALSE; @@ -2177,13 +2161,13 @@ CreatePciIoDevice ( PciIoDevice->Allocated = TRUE; } - PciIoDevice->Registered = FALSE; - PciIoDevice->Attributes = 0; - PciIoDevice->Supports = 0; - PciIoDevice->BusOverride = FALSE; - PciIoDevice->AllOpRomProcessed = FALSE; + PciIoDevice->Registered = FALSE; + PciIoDevice->Attributes = 0; + PciIoDevice->Supports = 0; + PciIoDevice->BusOverride = FALSE; + PciIoDevice->AllOpRomProcessed = FALSE; - PciIoDevice->IsPciExp = FALSE; + PciIoDevice->IsPciExp = FALSE; CopyMem (&(PciIoDevice->Pci), Pci, sizeof (PCI_TYPE01)); @@ -2207,12 +2191,12 @@ CreatePciIoDevice ( // Detect if PCI Express Device // PciIoDevice->PciExpressCapabilityOffset = 0; - Status = LocateCapabilityRegBlock ( - PciIoDevice, - EFI_PCI_CAPABILITY_ID_PCIEXP, - &PciIoDevice->PciExpressCapabilityOffset, - NULL - ); + Status = LocateCapabilityRegBlock ( + PciIoDevice, + EFI_PCI_CAPABILITY_ID_PCIEXP, + &PciIoDevice->PciExpressCapabilityOffset, + NULL + ); if (!EFI_ERROR (Status)) { PciIoDevice->IsPciExp = TRUE; } @@ -2224,10 +2208,11 @@ CreatePciIoDevice ( // // If authentication fails, skip this device. // - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { if (PciIoDevice->DevicePath != NULL) { FreePool (PciIoDevice->DevicePath); } + FreePool (PciIoDevice); return NULL; } @@ -2255,32 +2240,32 @@ CreatePciIoDevice ( // ParentPciIo = &Bridge->PciIo; ParentPciIo->Pci.Read ( - ParentPciIo, - EfiPciIoWidthUint32, - Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET, - 1, - &Data32 - ); + ParentPciIo, + EfiPciIoWidthUint32, + Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_OFFSET, + 1, + &Data32 + ); if ((Data32 & EFI_PCIE_CAPABILITY_DEVICE_CAPABILITIES_2_ARI_FORWARDING) != 0) { // // ARI forward support in bridge, so enable it. // ParentPciIo->Pci.Read ( - ParentPciIo, - EfiPciIoWidthUint32, - Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, - 1, - &Data32 - ); + ParentPciIo, + EfiPciIoWidthUint32, + Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, + 1, + &Data32 + ); if ((Data32 & EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING) == 0) { Data32 |= EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_ARI_FORWARDING; ParentPciIo->Pci.Write ( - ParentPciIo, - EfiPciIoWidthUint32, - Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, - 1, - &Data32 - ); + ParentPciIo, + EfiPciIoWidthUint32, + Bridge->PciExpressCapabilityOffset + EFI_PCIE_CAPABILITY_DEVICE_CONTROL_2_OFFSET, + 1, + &Data32 + ); DEBUG (( DEBUG_INFO, " ARI: forwarding enabled for PPB[%02x:%02x:%02x]\n", @@ -2307,17 +2292,17 @@ CreatePciIoDevice ( NULL ); if (!EFI_ERROR (Status)) { - UINT32 SupportedPageSize; - UINT16 VFStride; - UINT16 FirstVFOffset; - UINT16 Data16; - UINT32 PFRid; - UINT32 LastVF; + UINT32 SupportedPageSize; + UINT16 VFStride; + UINT16 FirstVFOffset; + UINT16 Data16; + UINT32 PFRid; + UINT32 LastVF; // // If the SR-IOV device is an ARI device, then Set ARI Capable Hierarchy for the device. // - if (PcdGetBool (PcdAriSupport) && PciIoDevice->AriCapabilityOffset != 0) { + if (PcdGetBool (PcdAriSupport) && (PciIoDevice->AriCapabilityOffset != 0)) { PciIo->Pci.Read ( PciIo, EfiPciIoWidthUint16, @@ -2392,7 +2377,7 @@ CreatePciIoDevice ( // // Calculate LastVF // - PFRid = EFI_PCI_RID(Bus, Device, Func); + PFRid = EFI_PCI_RID (Bus, Device, Func); LastVF = PFRid + FirstVFOffset + (PciIoDevice->InitialVFs - 1) * VFStride; // @@ -2403,12 +2388,16 @@ CreatePciIoDevice ( DEBUG (( DEBUG_INFO, " SR-IOV: SupportedPageSize = 0x%x; SystemPageSize = 0x%x; FirstVFOffset = 0x%x;\n", - SupportedPageSize, PciIoDevice->SystemPageSize >> 12, FirstVFOffset + SupportedPageSize, + PciIoDevice->SystemPageSize >> 12, + FirstVFOffset )); DEBUG (( DEBUG_INFO, " InitialVFs = 0x%x; ReservedBusNum = 0x%x; CapOffset = 0x%x\n", - PciIoDevice->InitialVFs, PciIoDevice->ReservedBusNum, PciIoDevice->SrIovCapabilityOffset + PciIoDevice->InitialVFs, + PciIoDevice->ReservedBusNum, + PciIoDevice->SrIovCapabilityOffset )); } } @@ -2434,17 +2423,17 @@ CreatePciIoDevice ( NULL ); if (!EFI_ERROR (Status)) { - PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL ResizableBarControl; - UINT32 Offset; + PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL ResizableBarControl; + UINT32 Offset; Offset = PciIoDevice->ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER) - + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CAPABILITY), + + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CAPABILITY), PciIo->Pci.Read ( - PciIo, - EfiPciIoWidthUint8, - Offset, - sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL), - &ResizableBarControl - ); + PciIo, + EfiPciIoWidthUint8, + Offset, + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_CONTROL), + &ResizableBarControl + ); PciIoDevice->ResizableBarNumber = ResizableBarControl.Bits.ResizableBarNumber; PciProgramResizableBar (PciIoDevice, PciResizableBarMax); } @@ -2482,16 +2471,15 @@ CreatePciIoDevice ( **/ EFI_STATUS PciEnumeratorLight ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ) { - - EFI_STATUS Status; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - PCI_IO_DEVICE *RootBridgeDev; - UINT16 MinBus; - UINT16 MaxBus; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; + EFI_STATUS Status; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + PCI_IO_DEVICE *RootBridgeDev; + UINT16 MinBus; + UINT16 MaxBus; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; MinBus = 0; MaxBus = PCI_MAX_BUS; @@ -2510,23 +2498,22 @@ PciEnumeratorLight ( Status = gBS->OpenProtocol ( Controller, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, gPciBusDriverBinding.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); - if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) { + if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { return Status; } - Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **) &Descriptors); + Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **)&Descriptors); if (EFI_ERROR (Status)) { return Status; } while (PciGetBusRange (&Descriptors, &MinBus, &MaxBus, NULL) == EFI_SUCCESS) { - // // Create a device node for root bridge device with a NULL host bridge controller handle // @@ -2544,11 +2531,10 @@ PciEnumeratorLight ( Status = PciPciDeviceInfoCollector ( RootBridgeDev, - (UINT8) MinBus + (UINT8)MinBus ); if (!EFI_ERROR (Status)) { - // // Remove those PCI devices which are rejected when full enumeration // @@ -2569,7 +2555,6 @@ PciEnumeratorLight ( // InsertRootBridge (RootBridgeDev); } else { - // // If unsuccessfully, destroy the entire node // @@ -2605,15 +2590,15 @@ PciGetBusRange ( while ((*Descriptors)->Desc != ACPI_END_TAG_DESCRIPTOR) { if ((*Descriptors)->ResType == ACPI_ADDRESS_SPACE_TYPE_BUS) { if (MinBus != NULL) { - *MinBus = (UINT16) (*Descriptors)->AddrRangeMin; + *MinBus = (UINT16)(*Descriptors)->AddrRangeMin; } if (MaxBus != NULL) { - *MaxBus = (UINT16) (*Descriptors)->AddrRangeMax; + *MaxBus = (UINT16)(*Descriptors)->AddrRangeMax; } if (BusRange != NULL) { - *BusRange = (UINT16) (*Descriptors)->AddrLen; + *BusRange = (UINT16)(*Descriptors)->AddrLen; } return EFI_SUCCESS; @@ -2636,12 +2621,12 @@ PciGetBusRange ( **/ EFI_STATUS StartManagingRootBridge ( - IN PCI_IO_DEVICE *RootBridgeDev + IN PCI_IO_DEVICE *RootBridgeDev ) { - EFI_HANDLE RootBridgeHandle; - EFI_STATUS Status; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_HANDLE RootBridgeHandle; + EFI_STATUS Status; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; // // Get the root bridge handle @@ -2655,13 +2640,13 @@ StartManagingRootBridge ( Status = gBS->OpenProtocol ( RootBridgeHandle, &gEfiPciRootBridgeIoProtocolGuid, - (VOID **) &PciRootBridgeIo, + (VOID **)&PciRootBridgeIo, gPciBusDriverBinding.DriverBindingHandle, RootBridgeHandle, EFI_OPEN_PROTOCOL_BY_DRIVER ); - if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) { + if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { return Status; } @@ -2671,7 +2656,6 @@ StartManagingRootBridge ( RootBridgeDev->PciRootBridgeIo = PciRootBridgeIo; return EFI_SUCCESS; - } /** @@ -2685,7 +2669,7 @@ StartManagingRootBridge ( **/ BOOLEAN IsPciDeviceRejected ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { EFI_STATUS Status; @@ -2706,9 +2690,8 @@ IsPciDeviceRejected ( // Only test base registers for P2C // for (BarOffset = 0x1C; BarOffset <= 0x38; BarOffset += 2 * sizeof (UINT32)) { - - Mask = (BarOffset < 0x2C) ? 0xFFFFF000 : 0xFFFFFFFC; - Status = BarExisted (PciIoDevice, BarOffset, &TestValue, &OldValue); + Mask = (BarOffset < 0x2C) ? 0xFFFFF000 : 0xFFFFFFFC; + Status = BarExisted (PciIoDevice, BarOffset, &TestValue, &OldValue); if (EFI_ERROR (Status)) { continue; } @@ -2735,7 +2718,6 @@ IsPciDeviceRejected ( } if ((TestValue & 0x01) != 0) { - // // IO Bar // @@ -2744,9 +2726,7 @@ IsPciDeviceRejected ( if ((TestValue != 0) && (TestValue == (OldValue & Mask))) { return TRUE; } - } else { - // // Mem Bar // @@ -2754,13 +2734,11 @@ IsPciDeviceRejected ( TestValue = TestValue & Mask; if ((TestValue & 0x07) == 0x04) { - // // Mem64 or PMem64 // BarOffset += sizeof (UINT32); if ((TestValue != 0) && (TestValue == (OldValue & Mask))) { - // // Test its high 32-Bit BAR // @@ -2769,9 +2747,7 @@ IsPciDeviceRejected ( return TRUE; } } - } else { - // // Mem32 or PMem32 // @@ -2794,24 +2770,23 @@ IsPciDeviceRejected ( **/ VOID ResetAllPpbBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber ) { - EFI_STATUS Status; - PCI_TYPE00 Pci; - UINT8 Device; - UINT32 Register; - UINT8 Func; - UINT64 Address; - UINT8 SecondaryBus; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + EFI_STATUS Status; + PCI_TYPE00 Pci; + UINT8 Device; + UINT32 Register; + UINT8 Func; + UINT64 Address; + UINT8 SecondaryBus; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; PciRootBridgeIo = Bridge->PciRootBridgeIo; for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { - // // Check to see whether a pci device is present // @@ -2823,7 +2798,7 @@ ResetAllPpbBusNumber ( Func ); - if (EFI_ERROR (Status) && Func == 0) { + if (EFI_ERROR (Status) && (Func == 0)) { // // go to next device if there is no Function 0 // @@ -2831,16 +2806,15 @@ ResetAllPpbBusNumber ( } if (!EFI_ERROR (Status) && (IS_PCI_BRIDGE (&Pci))) { - - Register = 0; - Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x18); - Status = PciRootBridgeIo->Pci.Read ( - PciRootBridgeIo, - EfiPciWidthUint32, - Address, - 1, - &Register - ); + Register = 0; + Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0x18); + Status = PciRootBridgeIo->Pci.Read ( + PciRootBridgeIo, + EfiPciWidthUint32, + Address, + 1, + &Register + ); SecondaryBus = (UINT8)(Register >> 8); if (SecondaryBus != 0) { @@ -2851,16 +2825,16 @@ ResetAllPpbBusNumber ( // Reset register 18h, 19h, 1Ah on PCI Bridge // Register &= 0xFF000000; - Status = PciRootBridgeIo->Pci.Write ( - PciRootBridgeIo, - EfiPciWidthUint32, - Address, - 1, - &Register - ); + Status = PciRootBridgeIo->Pci.Write ( + PciRootBridgeIo, + EfiPciWidthUint32, + Address, + 1, + &Register + ); } - if (Func == 0 && !IS_PCI_MULTI_FUNC (&Pci)) { + if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) { // // Skip sub functions, this is not a multi function device // diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.h index 4581b270c9..0ded4bea4f 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.h @@ -24,11 +24,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PciDevicePresent ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo, - OUT PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo, + OUT PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ); /** @@ -46,8 +46,8 @@ PciDevicePresent ( **/ EFI_STATUS PciPciDeviceInfoCollector ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber ); /** @@ -66,12 +66,12 @@ PciPciDeviceInfoCollector ( **/ EFI_STATUS PciSearchDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func, - OUT PCI_IO_DEVICE **PciDevice + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func, + OUT PCI_IO_DEVICE **PciDevice ); /** @@ -88,11 +88,11 @@ PciSearchDevice ( **/ PCI_IO_DEVICE * GatherDeviceInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ); /** @@ -109,11 +109,11 @@ GatherDeviceInfo ( **/ PCI_IO_DEVICE * GatherPpbInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ); /** @@ -130,11 +130,11 @@ GatherPpbInfo ( **/ PCI_IO_DEVICE * GatherP2CInfo ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ); /** @@ -148,8 +148,8 @@ GatherP2CInfo ( **/ EFI_DEVICE_PATH_PROTOCOL * CreatePciDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, - IN PCI_IO_DEVICE *PciIoDevice + IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -166,10 +166,10 @@ CreatePciDevicePath ( **/ EFI_STATUS VfBarExisted ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINTN Offset, - OUT UINT32 *BarLengthValue, - OUT UINT32 *OriginalBarValue + IN PCI_IO_DEVICE *PciIoDevice, + IN UINTN Offset, + OUT UINT32 *BarLengthValue, + OUT UINT32 *OriginalBarValue ); /** @@ -186,10 +186,10 @@ VfBarExisted ( **/ EFI_STATUS BarExisted ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINTN Offset, - OUT UINT32 *BarLengthValue, - OUT UINT32 *OriginalBarValue + IN PCI_IO_DEVICE *PciIoDevice, + IN UINTN Offset, + OUT UINT32 *BarLengthValue, + OUT UINT32 *OriginalBarValue ); /** @@ -206,11 +206,11 @@ BarExisted ( **/ VOID PciTestSupportedAttribute ( - IN PCI_IO_DEVICE *PciIoDevice, - IN OUT UINT16 *Command, - IN OUT UINT16 *BridgeControl, - OUT UINT16 *OldCommand, - OUT UINT16 *OldBridgeControl + IN PCI_IO_DEVICE *PciIoDevice, + IN OUT UINT16 *Command, + IN OUT UINT16 *BridgeControl, + OUT UINT16 *OldCommand, + OUT UINT16 *OldBridgeControl ); /** @@ -224,10 +224,10 @@ PciTestSupportedAttribute ( **/ VOID PciSetDeviceAttribute ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT16 Command, - IN UINT16 BridgeControl, - IN UINTN Option + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT16 Command, + IN UINT16 BridgeControl, + IN UINTN Option ); /** @@ -242,8 +242,8 @@ PciSetDeviceAttribute ( **/ EFI_STATUS GetFastBackToBackSupport ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 StatusIndex + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 StatusIndex ); /** @@ -254,7 +254,7 @@ GetFastBackToBackSupport ( **/ EFI_STATUS DetermineDeviceAttribute ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -269,7 +269,7 @@ DetermineDeviceAttribute ( **/ EFI_STATUS UpdatePciInfo ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ); /** @@ -281,8 +281,8 @@ UpdatePciInfo ( **/ VOID SetNewAlign ( - IN OUT UINT64 *Alignment, - IN UINT64 NewAlignment + IN OUT UINT64 *Alignment, + IN UINT64 NewAlignment ); /** @@ -329,7 +329,7 @@ PciIovParseVfBar ( **/ VOID InitializePciDevice ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -340,7 +340,7 @@ InitializePciDevice ( **/ VOID InitializePpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -351,7 +351,7 @@ InitializePpb ( **/ VOID InitializeP2C ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -369,11 +369,11 @@ InitializeP2C ( **/ PCI_IO_DEVICE * CreatePciIoDevice ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_TYPE00 *Pci, - IN UINT8 Bus, - IN UINT8 Device, - IN UINT8 Func + IN PCI_IO_DEVICE *Bridge, + IN PCI_TYPE00 *Pci, + IN UINT8 Bus, + IN UINT8 Device, + IN UINT8 Func ); /** @@ -390,7 +390,7 @@ CreatePciIoDevice ( **/ EFI_STATUS PciEnumeratorLight ( - IN EFI_HANDLE Controller + IN EFI_HANDLE Controller ); /** @@ -424,7 +424,7 @@ PciGetBusRange ( **/ EFI_STATUS StartManagingRootBridge ( - IN PCI_IO_DEVICE *RootBridgeDev + IN PCI_IO_DEVICE *RootBridgeDev ); /** @@ -438,7 +438,7 @@ StartManagingRootBridge ( **/ BOOLEAN IsPciDeviceRejected ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -450,8 +450,8 @@ IsPciDeviceRejected ( **/ VOID ResetAllPpbBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber ); /** @@ -463,8 +463,8 @@ ResetAllPpbBusNumber ( **/ VOID DumpPpbPaddingResource ( - IN PCI_IO_DEVICE *PciIoDevice, - IN PCI_BAR_TYPE ResourceType + IN PCI_IO_DEVICE *PciIoDevice, + IN PCI_BAR_TYPE ResourceType ); /** @@ -474,7 +474,7 @@ DumpPpbPaddingResource ( **/ VOID DumpPciBars ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.c index 0dc8ec23b0..810867a200 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.c @@ -13,7 +13,6 @@ EFI_HPC_LOCATION *gPciRootHpcPool = NULL; UINTN gPciRootHpcCount = 0; ROOT_HPC_DATA *gPciRootHpcData = NULL; - /** Event notification function to set Hot Plug controller status. @@ -24,14 +23,14 @@ ROOT_HPC_DATA *gPciRootHpcData = NULL; VOID EFIAPI PciHPCInitialized ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - ROOT_HPC_DATA *HpcData; + ROOT_HPC_DATA *HpcData; - HpcData = (ROOT_HPC_DATA *) Context; - HpcData->Initialized = TRUE; + HpcData = (ROOT_HPC_DATA *)Context; + HpcData->Initialized = TRUE; } /** @@ -46,12 +45,12 @@ PciHPCInitialized ( **/ BOOLEAN EfiCompareDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath1, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath2 + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath1, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath2 ) { - UINTN Size1; - UINTN Size2; + UINTN Size1; + UINTN Size2; Size1 = GetDevicePathSize (DevicePath1); Size2 = GetDevicePathSize (DevicePath2); @@ -100,7 +99,7 @@ InitializeHotPlugSupport ( Status = gBS->LocateProtocol ( &gEfiPciHotPlugInitProtocolGuid, NULL, - (VOID **) &gPciHotPlugInit + (VOID **)&gPciHotPlugInit ); if (EFI_ERROR (Status)) { @@ -114,10 +113,9 @@ InitializeHotPlugSupport ( ); if (!EFI_ERROR (Status)) { - - gPciRootHpcPool = HpcList; - gPciRootHpcCount = HpcCount; - gPciRootHpcData = AllocateZeroPool (sizeof (ROOT_HPC_DATA) * gPciRootHpcCount); + gPciRootHpcPool = HpcList; + gPciRootHpcCount = HpcCount; + gPciRootHpcData = AllocateZeroPool (sizeof (ROOT_HPC_DATA) * gPciRootHpcCount); if (gPciRootHpcData == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -139,16 +137,14 @@ InitializeHotPlugSupport ( **/ BOOLEAN IsRootPciHotPlugBus ( - IN EFI_DEVICE_PATH_PROTOCOL *HpbDevicePath, - OUT UINTN *HpIndex OPTIONAL + IN EFI_DEVICE_PATH_PROTOCOL *HpbDevicePath, + OUT UINTN *HpIndex OPTIONAL ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < gPciRootHpcCount; Index++) { - if (EfiCompareDevicePath (gPciRootHpcPool[Index].HpbDevicePath, HpbDevicePath)) { - if (HpIndex != NULL) { *HpIndex = Index; } @@ -173,16 +169,14 @@ IsRootPciHotPlugBus ( **/ BOOLEAN IsRootPciHotPlugController ( - IN EFI_DEVICE_PATH_PROTOCOL *HpcDevicePath, - OUT UINTN *HpIndex + IN EFI_DEVICE_PATH_PROTOCOL *HpcDevicePath, + OUT UINTN *HpIndex ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < gPciRootHpcCount; Index++) { - if (EfiCompareDevicePath (gPciRootHpcPool[Index].HpcDevicePath, HpcDevicePath)) { - if (HpIndex != NULL) { *HpIndex = Index; } @@ -237,17 +231,16 @@ CreateEventForHpc ( **/ EFI_STATUS AllRootHPCInitialized ( - IN UINTN TimeoutInMicroSeconds + IN UINTN TimeoutInMicroSeconds ) { UINT32 Delay; UINTN Index; - Delay = (UINT32) ((TimeoutInMicroSeconds / 30) + 1); + Delay = (UINT32)((TimeoutInMicroSeconds / 30) + 1); do { for (Index = 0; Index < gPciRootHpcCount; Index++) { - if (gPciRootHpcData[Index].Found && !gPciRootHpcData[Index].Initialized) { break; } @@ -263,7 +256,6 @@ AllRootHPCInitialized ( gBS->Stall (30); Delay--; - } while (Delay > 0); return EFI_TIMEOUT; @@ -280,10 +272,9 @@ AllRootHPCInitialized ( **/ BOOLEAN IsSHPC ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_STATUS Status; UINT8 Offset; @@ -293,11 +284,11 @@ IsSHPC ( Offset = 0; Status = LocateCapabilityRegBlock ( - PciIoDevice, - EFI_PCI_CAPABILITY_ID_SHPC, - &Offset, - NULL - ); + PciIoDevice, + EFI_PCI_CAPABILITY_ID_SHPC, + &Offset, + NULL + ); // // If the PCI-PCI bridge has the hot plug controller build-in, @@ -328,13 +319,13 @@ IsSHPC ( **/ BOOLEAN SupportsPcieHotplug ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - UINT32 Offset; - EFI_STATUS Status; - PCI_REG_PCIE_CAPABILITY Capability; - PCI_REG_PCIE_SLOT_CAPABILITY SlotCapability; + UINT32 Offset; + EFI_STATUS Status; + PCI_REG_PCIE_CAPABILITY Capability; + PCI_REG_PCIE_SLOT_CAPABILITY SlotCapability; if (PciIoDevice == NULL) { return FALSE; @@ -346,6 +337,7 @@ SupportsPcieHotplug ( if (!PciIoDevice->IsPciExp) { return FALSE; } + Offset = PciIoDevice->PciExpressCapabilityOffset + OFFSET_OF (PCI_CAPABILITY_PCIEXP, Capability); Status = PciIoDevice->PciIo.Pci.Read ( @@ -363,12 +355,13 @@ SupportsPcieHotplug ( // Check the contents of the register // switch (Capability.Bits.DevicePortType) { - case PCIE_DEVICE_PORT_TYPE_ROOT_PORT: - case PCIE_DEVICE_PORT_TYPE_DOWNSTREAM_PORT: - break; - default: - return FALSE; + case PCIE_DEVICE_PORT_TYPE_ROOT_PORT: + case PCIE_DEVICE_PORT_TYPE_DOWNSTREAM_PORT: + break; + default: + return FALSE; } + if (!Capability.Bits.SlotImplemented) { return FALSE; } @@ -395,6 +388,7 @@ SupportsPcieHotplug ( if (SlotCapability.Bits.HotPlugCapable) { return TRUE; } + return FALSE; } @@ -406,34 +400,34 @@ SupportsPcieHotplug ( **/ VOID GetResourcePaddingForHpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_STATUS Status; - EFI_HPC_STATE State; - UINT64 PciAddress; - EFI_HPC_PADDING_ATTRIBUTES Attributes; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; + EFI_STATUS Status; + EFI_HPC_STATE State; + UINT64 PciAddress; + EFI_HPC_PADDING_ATTRIBUTES Attributes; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; if (IsPciHotPlugBus (PciIoDevice)) { // // If PCI-PCI bridge device is PCI Hot Plug bus. // PciAddress = EFI_PCI_ADDRESS (PciIoDevice->BusNumber, PciIoDevice->DeviceNumber, PciIoDevice->FunctionNumber, 0); - Status = gPciHotPlugInit->GetResourcePadding ( - gPciHotPlugInit, - PciIoDevice->DevicePath, - PciAddress, - &State, - (VOID **) &Descriptors, - &Attributes - ); + Status = gPciHotPlugInit->GetResourcePadding ( + gPciHotPlugInit, + PciIoDevice->DevicePath, + PciAddress, + &State, + (VOID **)&Descriptors, + &Attributes + ); if (EFI_ERROR (Status)) { return; } - if ((State & EFI_HPC_STATE_ENABLED) != 0 && (State & EFI_HPC_STATE_INITIALIZED) != 0) { + if (((State & EFI_HPC_STATE_ENABLED) != 0) && ((State & EFI_HPC_STATE_INITIALIZED) != 0)) { PciIoDevice->ResourcePaddingDescriptors = Descriptors; PciIoDevice->PaddingAttributes = Attributes; } @@ -453,7 +447,7 @@ GetResourcePaddingForHpb ( **/ BOOLEAN IsPciHotPlugBus ( - PCI_IO_DEVICE *PciIoDevice + PCI_IO_DEVICE *PciIoDevice ) { if (IsSHPC (PciIoDevice)) { @@ -475,10 +469,9 @@ IsPciHotPlugBus ( // // Otherwise, see if it is a Root HPC // - if(IsRootPciHotPlugBus (PciIoDevice->DevicePath, NULL)) { + if (IsRootPciHotPlugBus (PciIoDevice->DevicePath, NULL)) { return TRUE; } return FALSE; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h index e97d75362d..6ee43db250 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciHotPlugSupport.h @@ -12,24 +12,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // stall 1 second, its unit is 100ns // -#define STALL_1_SECOND 1000000 +#define STALL_1_SECOND 1000000 // // PCI Hot Plug controller private data // typedef struct { - EFI_EVENT Event; - BOOLEAN Found; - BOOLEAN Initialized; - VOID *Padding; + EFI_EVENT Event; + BOOLEAN Found; + BOOLEAN Initialized; + VOID *Padding; } ROOT_HPC_DATA; // // Reference of some global variables // -extern EFI_PCI_HOT_PLUG_INIT_PROTOCOL *gPciHotPlugInit; -extern EFI_HPC_LOCATION *gPciRootHpcPool; -extern ROOT_HPC_DATA *gPciRootHpcData; +extern EFI_PCI_HOT_PLUG_INIT_PROTOCOL *gPciHotPlugInit; +extern EFI_HPC_LOCATION *gPciRootHpcPool; +extern ROOT_HPC_DATA *gPciRootHpcData; /** Event notification function to set Hot Plug controller status. @@ -41,8 +41,8 @@ extern ROOT_HPC_DATA *gPciRootHpcData; VOID EFIAPI PciHPCInitialized ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -57,8 +57,8 @@ PciHPCInitialized ( **/ BOOLEAN EfiCompareDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath1, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath2 + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath1, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath2 ); /** @@ -90,7 +90,7 @@ InitializeHotPlugSupport ( **/ BOOLEAN IsPciHotPlugBus ( - PCI_IO_DEVICE *PciIoDevice + PCI_IO_DEVICE *PciIoDevice ); /** @@ -106,8 +106,8 @@ IsPciHotPlugBus ( **/ BOOLEAN IsRootPciHotPlugBus ( - IN EFI_DEVICE_PATH_PROTOCOL *HpbDevicePath, - OUT UINTN *HpIndex OPTIONAL + IN EFI_DEVICE_PATH_PROTOCOL *HpbDevicePath, + OUT UINTN *HpIndex OPTIONAL ); /** @@ -123,8 +123,8 @@ IsRootPciHotPlugBus ( **/ BOOLEAN IsRootPciHotPlugController ( - IN EFI_DEVICE_PATH_PROTOCOL *HpcDevicePath, - OUT UINTN *HpIndex + IN EFI_DEVICE_PATH_PROTOCOL *HpcDevicePath, + OUT UINTN *HpIndex ); /** @@ -153,7 +153,7 @@ CreateEventForHpc ( **/ EFI_STATUS AllRootHPCInitialized ( - IN UINTN TimeoutInMicroSeconds + IN UINTN TimeoutInMicroSeconds ); /** @@ -167,7 +167,7 @@ AllRootHPCInitialized ( **/ BOOLEAN IsSHPC ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -188,7 +188,7 @@ IsSHPC ( **/ BOOLEAN SupportsPcieHotplug ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -199,7 +199,7 @@ SupportsPcieHotplug ( **/ VOID GetResourcePaddingForHpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c index 996d6fbe92..843815d0cb 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciBus.h" -extern EDKII_IOMMU_PROTOCOL *mIoMmuProtocol; +extern EDKII_IOMMU_PROTOCOL *mIoMmuProtocol; // // Pci Io Protocol Interface @@ -50,7 +50,7 @@ EFI_PCI_IO_PROTOCOL mPciIoInterface = { **/ VOID InitializePciIoInstance ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { CopyMem (&PciIoDevice->PciIo, &mPciIoInterface, sizeof (EFI_PCI_IO_PROTOCOL)); @@ -73,12 +73,12 @@ InitializePciIoInstance ( **/ EFI_STATUS PciIoVerifyBarAccess ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 BarIndex, - IN PCI_BAR_TYPE Type, - IN IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN IN UINTN Count, - IN UINT64 *Offset + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 BarIndex, + IN PCI_BAR_TYPE Type, + IN IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN IN UINTN Count, + IN UINT64 *Offset ) { if ((UINT32)Width >= EfiPciIoWidthMaximum) { @@ -104,11 +104,11 @@ PciIoVerifyBarAccess ( // If Width is EfiPciIoWidthFifoUintX then convert to EfiPciIoWidthUintX // If Width is EfiPciIoWidthFillUintX then convert to EfiPciIoWidthUintX // - if (Width >= EfiPciIoWidthFifoUint8 && Width <= EfiPciIoWidthFifoUint64) { + if ((Width >= EfiPciIoWidthFifoUint8) && (Width <= EfiPciIoWidthFifoUint64)) { Count = 1; } - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & 0x03); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & 0x03); if ((*Offset + Count * (UINTN)(1 << Width)) - 1 >= PciIoDevice->PciBar[BarIndex].Length) { return EFI_INVALID_PARAMETER; @@ -149,17 +149,16 @@ PciIoVerifyConfigAccess ( // // If Width is EfiPciIoWidthFillUintX then convert to EfiPciIoWidthUintX // - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & 0x03); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & 0x03); if (PciIoDevice->IsPciExp) { if ((*Offset + Count * (UINTN)(1 << Width)) - 1 >= PCI_EXP_MAX_CONFIG_OFFSET) { return EFI_UNSUPPORTED; } - ExtendOffset = LShiftU64 (*Offset, 32); - *Offset = EFI_PCI_ADDRESS (PciIoDevice->BusNumber, PciIoDevice->DeviceNumber, PciIoDevice->FunctionNumber, 0); - *Offset = (*Offset) | ExtendOffset; - + ExtendOffset = LShiftU64 (*Offset, 32); + *Offset = EFI_PCI_ADDRESS (PciIoDevice->BusNumber, PciIoDevice->DeviceNumber, PciIoDevice->FunctionNumber, 0); + *Offset = (*Offset) | ExtendOffset; } else { if ((*Offset + Count * (UINTN)(1 << Width)) - 1 >= PCI_MAX_CONFIG_OFFSET) { return EFI_UNSUPPORTED; @@ -206,8 +205,8 @@ PciIoPollMem ( OUT UINT64 *Result ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -229,29 +228,34 @@ PciIoPollMem ( // if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { - Status = PciIoMemRead (This, Width, BarIndex, Offset, 1, Result); + Status = PciIoMemRead (This, Width, BarIndex, Offset, 1, Result); if (EFI_ERROR (Status)) { return Status; } - if ((*Result & Mask) == Value || Delay == 0) { + + if (((*Result & Mask) == Value) || (Delay == 0)) { return EFI_SUCCESS; } + do { // // Stall 10 us = 100 * 100ns // gBS->Stall (10); - Status = PciIoMemRead (This, Width, BarIndex, Offset, 1, Result); + Status = PciIoMemRead (This, Width, BarIndex, Offset, 1, Result); if (EFI_ERROR (Status)) { return Status; } + if ((*Result & Mask) == Value) { return EFI_SUCCESS; } + if (Delay <= 100) { return EFI_TIMEOUT; } + Delay -= 100; } while (TRUE); } @@ -259,7 +263,7 @@ PciIoPollMem ( Status = PciIoDevice->PciRootBridgeIo->PollMem ( PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, Offset, Mask, Value, @@ -313,8 +317,8 @@ PciIoPollIo ( OUT UINT64 *Result ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -332,29 +336,34 @@ PciIoPollIo ( // if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { - Status = PciIoIoRead (This, Width, BarIndex, Offset, 1, Result); + Status = PciIoIoRead (This, Width, BarIndex, Offset, 1, Result); if (EFI_ERROR (Status)) { return Status; } - if ((*Result & Mask) == Value || Delay == 0) { + + if (((*Result & Mask) == Value) || (Delay == 0)) { return EFI_SUCCESS; } + do { // // Stall 10 us = 100 * 100ns // gBS->Stall (10); - Status = PciIoIoRead (This, Width, BarIndex, Offset, 1, Result); + Status = PciIoIoRead (This, Width, BarIndex, Offset, 1, Result); if (EFI_ERROR (Status)) { return Status; } + if ((*Result & Mask) == Value) { return EFI_SUCCESS; } + if (Delay <= 100) { return EFI_TIMEOUT; } + Delay -= 100; } while (TRUE); } @@ -362,7 +371,7 @@ PciIoPollIo ( Status = PciIoDevice->PciRootBridgeIo->PollIo ( PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, Offset, Mask, Value, @@ -412,8 +421,8 @@ PciIoMemRead ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -436,18 +445,17 @@ PciIoMemRead ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } - Status = PciIoDevice->PciRootBridgeIo->Mem.Read ( - PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, - Offset, - Count, - Buffer - ); + PciIoDevice->PciRootBridgeIo, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, + Offset, + Count, + Buffer + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -491,8 +499,8 @@ PciIoMemWrite ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -515,17 +523,17 @@ PciIoMemWrite ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->Mem.Write ( - PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, - Offset, - Count, - Buffer - ); + PciIoDevice->PciRootBridgeIo, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, + Offset, + Count, + Buffer + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -569,8 +577,8 @@ PciIoIoRead ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -593,13 +601,13 @@ PciIoIoRead ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->Io.Read ( PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, Offset, Count, Buffer @@ -647,8 +655,8 @@ PciIoIoWrite ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -671,13 +679,13 @@ PciIoIoWrite ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->Io.Write ( PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, Offset, Count, Buffer @@ -722,14 +730,14 @@ PciIoConfigRead ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; - UINT64 Address; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; + UINT64 Address; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); - Address = Offset; - Status = PciIoVerifyConfigAccess (PciIoDevice, Width, Count, &Address); + Address = Offset; + Status = PciIoVerifyConfigAccess (PciIoDevice, Width, Count, &Address); if (EFI_ERROR (Status)) { return Status; } @@ -740,13 +748,13 @@ PciIoConfigRead ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->Pci.Read ( PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, Address, Count, Buffer @@ -791,14 +799,14 @@ PciIoConfigWrite ( IN OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; - UINT64 Address; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; + UINT64 Address; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); - Address = Offset; - Status = PciIoVerifyConfigAccess (PciIoDevice, Width, Count, &Address); + Address = Offset; + Status = PciIoVerifyConfigAccess (PciIoDevice, Width, Count, &Address); if (EFI_ERROR (Status)) { return Status; } @@ -809,17 +817,17 @@ PciIoConfigWrite ( if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { if ((Offset & ((1 << (Width & 0x03)) - 1)) != 0) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->Pci.Write ( - PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, - Address, - Count, - Buffer - ); + PciIoDevice->PciRootBridgeIo, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, + Address, + Count, + Buffer + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -863,17 +871,17 @@ PciIoConfigWrite ( EFI_STATUS EFIAPI PciIoCopyMem ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 DestBarIndex, - IN UINT64 DestOffset, - IN UINT8 SrcBarIndex, - IN UINT64 SrcOffset, - IN UINTN Count + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 DestBarIndex, + IN UINT64 DestOffset, + IN UINT8 SrcBarIndex, + IN UINT64 SrcOffset, + IN UINTN Count ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -881,14 +889,15 @@ PciIoCopyMem ( return EFI_INVALID_PARAMETER; } - if (Width == EfiPciIoWidthFifoUint8 || - Width == EfiPciIoWidthFifoUint16 || - Width == EfiPciIoWidthFifoUint32 || - Width == EfiPciIoWidthFifoUint64 || - Width == EfiPciIoWidthFillUint8 || - Width == EfiPciIoWidthFillUint16 || - Width == EfiPciIoWidthFillUint32 || - Width == EfiPciIoWidthFillUint64) { + if ((Width == EfiPciIoWidthFifoUint8) || + (Width == EfiPciIoWidthFifoUint16) || + (Width == EfiPciIoWidthFifoUint32) || + (Width == EfiPciIoWidthFifoUint64) || + (Width == EfiPciIoWidthFillUint8) || + (Width == EfiPciIoWidthFillUint16) || + (Width == EfiPciIoWidthFillUint32) || + (Width == EfiPciIoWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } @@ -906,19 +915,19 @@ PciIoCopyMem ( // If request is not aligned, then convert request to EfiPciIoWithXXXUint8 // if (FeaturePcdGet (PcdUnalignedPciIoEnable)) { - if ((SrcOffset & ((1 << (Width & 0x03)) - 1)) != 0 || (DestOffset & ((1 << (Width & 0x03)) - 1)) != 0) { + if (((SrcOffset & ((1 << (Width & 0x03)) - 1)) != 0) || ((DestOffset & ((1 << (Width & 0x03)) - 1)) != 0)) { Count *= (UINTN)(1 << (Width & 0x03)); - Width = (EFI_PCI_IO_PROTOCOL_WIDTH) (Width & (~0x03)); + Width = (EFI_PCI_IO_PROTOCOL_WIDTH)(Width & (~0x03)); } } Status = PciIoDevice->PciRootBridgeIo->CopyMem ( - PciIoDevice->PciRootBridgeIo, - (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) Width, - DestOffset, - SrcOffset, - Count - ); + PciIoDevice->PciRootBridgeIo, + (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)Width, + DestOffset, + SrcOffset, + Count + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -972,7 +981,7 @@ PciIoMap ( return EFI_INVALID_PARAMETER; } - if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL || Mapping == NULL) { + if ((HostAddress == NULL) || (NumberOfBytes == NULL) || (DeviceAddress == NULL) || (Mapping == NULL)) { return EFI_INVALID_PARAMETER; } @@ -982,13 +991,13 @@ PciIoMap ( } Status = PciIoDevice->PciRootBridgeIo->Map ( - PciIoDevice->PciRootBridgeIo, - RootBridgeIoOperation, - HostAddress, - NumberOfBytes, - DeviceAddress, - Mapping - ); + PciIoDevice->PciRootBridgeIo, + RootBridgeIoOperation, + HostAddress, + NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -1001,19 +1010,20 @@ PciIoMap ( if (mIoMmuProtocol != NULL) { if (!EFI_ERROR (Status)) { switch (Operation) { - case EfiPciIoOperationBusMasterRead: - IoMmuAttribute = EDKII_IOMMU_ACCESS_READ; - break; - case EfiPciIoOperationBusMasterWrite: - IoMmuAttribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EfiPciIoOperationBusMasterCommonBuffer: - IoMmuAttribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EfiPciIoOperationBusMasterRead: + IoMmuAttribute = EDKII_IOMMU_ACCESS_READ; + break; + case EfiPciIoOperationBusMasterWrite: + IoMmuAttribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EfiPciIoOperationBusMasterCommonBuffer: + IoMmuAttribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + mIoMmuProtocol->SetAttribute ( mIoMmuProtocol, PciIoDevice->Handle, @@ -1043,8 +1053,8 @@ PciIoUnmap ( IN VOID *Mapping ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -1058,9 +1068,9 @@ PciIoUnmap ( } Status = PciIoDevice->PciRootBridgeIo->Unmap ( - PciIoDevice->PciRootBridgeIo, - Mapping - ); + PciIoDevice->PciRootBridgeIo, + Mapping + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -1096,19 +1106,20 @@ PciIoUnmap ( EFI_STATUS EFIAPI PciIoAllocateBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; if ((Attributes & - (~(EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE | EFI_PCI_ATTRIBUTE_MEMORY_CACHED))) != 0){ + (~(EFI_PCI_ATTRIBUTE_MEMORY_WRITE_COMBINE | EFI_PCI_ATTRIBUTE_MEMORY_CACHED))) != 0) + { return EFI_UNSUPPORTED; } @@ -1119,13 +1130,13 @@ PciIoAllocateBuffer ( } Status = PciIoDevice->PciRootBridgeIo->AllocateBuffer ( - PciIoDevice->PciRootBridgeIo, - Type, - MemoryType, - Pages, - HostAddress, - Attributes - ); + PciIoDevice->PciRootBridgeIo, + Type, + MemoryType, + Pages, + HostAddress, + Attributes + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -1153,21 +1164,21 @@ PciIoAllocateBuffer ( EFI_STATUS EFIAPI PciIoFreeBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EFI_PCI_IO_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); Status = PciIoDevice->PciRootBridgeIo->FreeBuffer ( - PciIoDevice->PciRootBridgeIo, - Pages, - HostAddress - ); + PciIoDevice->PciRootBridgeIo, + Pages, + HostAddress + ); if (EFI_ERROR (Status)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -1197,8 +1208,8 @@ PciIoFlush ( IN EFI_PCI_IO_PROTOCOL *This ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); @@ -1239,11 +1250,11 @@ PciIoGetLocation ( OUT UINTN *Function ) { - PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *PciIoDevice; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); - if (Segment == NULL || Bus == NULL || Device == NULL || Function == NULL) { + if ((Segment == NULL) || (Bus == NULL) || (Device == NULL) || (Function == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1269,34 +1280,35 @@ PciIoGetLocation ( **/ BOOLEAN CheckBarType ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 BarIndex, - IN PCI_BAR_TYPE BarType + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 BarIndex, + IN PCI_BAR_TYPE BarType ) { switch (BarType) { + case PciBarTypeMem: + + if ((PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeMem32) && + (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypePMem32) && + (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypePMem64) && + (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeMem64)) + { + return FALSE; + } - case PciBarTypeMem: - - if (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeMem32 && - PciIoDevice->PciBar[BarIndex].BarType != PciBarTypePMem32 && - PciIoDevice->PciBar[BarIndex].BarType != PciBarTypePMem64 && - PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeMem64 ) { - return FALSE; - } - - return TRUE; + return TRUE; - case PciBarTypeIo: - if (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeIo32 && - PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeIo16){ - return FALSE; - } + case PciBarTypeIo: + if ((PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeIo32) && + (PciIoDevice->PciBar[BarIndex].BarType != PciBarTypeIo16)) + { + return FALSE; + } - return TRUE; + return TRUE; - default: - break; + default: + break; } return FALSE; @@ -1329,10 +1341,10 @@ ModifyRootBridgeAttributes ( // Get the current attributes of this PCI device's PCI Root Bridge // Status = PciIoDevice->PciRootBridgeIo->GetAttributes ( - PciIoDevice->PciRootBridgeIo, - &PciRootBridgeSupports, - &PciRootBridgeAttributes - ); + PciIoDevice->PciRootBridgeIo, + &PciRootBridgeSupports, + &PciRootBridgeAttributes + ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -1357,13 +1369,12 @@ ModifyRootBridgeAttributes ( // Call the PCI Root Bridge to attempt to modify the attributes // if ((NewPciRootBridgeAttributes ^ PciRootBridgeAttributes) != 0) { - Status = PciIoDevice->PciRootBridgeIo->SetAttributes ( - PciIoDevice->PciRootBridgeIo, - NewPciRootBridgeAttributes, - NULL, - NULL - ); + PciIoDevice->PciRootBridgeIo, + NewPciRootBridgeAttributes, + NULL, + NULL + ); if (EFI_ERROR (Status)) { // // The PCI Root Bridge could not modify the attributes, so return the error. @@ -1396,8 +1407,8 @@ SupportPaletteSnoopAttributes ( IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation ) { - PCI_IO_DEVICE *Temp; - UINT16 VGACommand; + PCI_IO_DEVICE *Temp; + UINT16 VGACommand; // // Snoop attribute can be only modified by GFX @@ -1428,11 +1439,11 @@ SupportPaletteSnoopAttributes ( // return EFI_SUCCESS; } + // // Check if they are on the same bus // if (Temp->Parent == PciIoDevice->Parent) { - PCI_READ_COMMAND_REGISTER (Temp, &VGACommand); // @@ -1474,7 +1485,6 @@ SupportPaletteSnoopAttributes ( } else { return EFI_UNSUPPORTED; } - } else { // // GFX should be set to snoop @@ -1485,7 +1495,6 @@ SupportPaletteSnoopAttributes ( } else { return EFI_UNSUPPORTED; } - } return EFI_SUCCESS; @@ -1513,72 +1522,73 @@ SupportPaletteSnoopAttributes ( EFI_STATUS EFIAPI PciIoAttributes ( - IN EFI_PCI_IO_PROTOCOL * This, + IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation, IN UINT64 Attributes, OUT UINT64 *Result OPTIONAL ) { - EFI_STATUS Status; + EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; - PCI_IO_DEVICE *UpStreamBridge; - PCI_IO_DEVICE *Temp; + PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *UpStreamBridge; + PCI_IO_DEVICE *Temp; - UINT64 Supports; - UINT64 UpStreamAttributes; - UINT16 BridgeControl; - UINT16 Command; + UINT64 Supports; + UINT64 UpStreamAttributes; + UINT16 BridgeControl; + UINT16 Command; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); switch (Operation) { - case EfiPciIoAttributeOperationGet: - if (Result == NULL) { - return EFI_INVALID_PARAMETER; - } + case EfiPciIoAttributeOperationGet: + if (Result == NULL) { + return EFI_INVALID_PARAMETER; + } - *Result = PciIoDevice->Attributes; - return EFI_SUCCESS; + *Result = PciIoDevice->Attributes; + return EFI_SUCCESS; - case EfiPciIoAttributeOperationSupported: - if (Result == NULL) { - return EFI_INVALID_PARAMETER; - } + case EfiPciIoAttributeOperationSupported: + if (Result == NULL) { + return EFI_INVALID_PARAMETER; + } - *Result = PciIoDevice->Supports; - return EFI_SUCCESS; + *Result = PciIoDevice->Supports; + return EFI_SUCCESS; - case EfiPciIoAttributeOperationSet: - Status = PciIoDevice->PciIo.Attributes ( - &(PciIoDevice->PciIo), - EfiPciIoAttributeOperationEnable, - Attributes, - NULL - ); - if (EFI_ERROR (Status)) { - return EFI_UNSUPPORTED; - } + case EfiPciIoAttributeOperationSet: + Status = PciIoDevice->PciIo.Attributes ( + &(PciIoDevice->PciIo), + EfiPciIoAttributeOperationEnable, + Attributes, + NULL + ); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } - Status = PciIoDevice->PciIo.Attributes ( - &(PciIoDevice->PciIo), - EfiPciIoAttributeOperationDisable, - (~Attributes) & (PciIoDevice->Supports), - NULL - ); - if (EFI_ERROR (Status)) { - return EFI_UNSUPPORTED; - } + Status = PciIoDevice->PciIo.Attributes ( + &(PciIoDevice->PciIo), + EfiPciIoAttributeOperationDisable, + (~Attributes) & (PciIoDevice->Supports), + NULL + ); + if (EFI_ERROR (Status)) { + return EFI_UNSUPPORTED; + } - return EFI_SUCCESS; + return EFI_SUCCESS; - case EfiPciIoAttributeOperationEnable: - case EfiPciIoAttributeOperationDisable: - break; + case EfiPciIoAttributeOperationEnable: + case EfiPciIoAttributeOperationDisable: + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } + // // Just a trick for ENABLE attribute // EFI_PCI_DEVICE_ENABLE is not defined in UEFI spec, which is the internal usage. @@ -1631,7 +1641,6 @@ PciIoAttributes ( // For PPB & P2C, set relevant attribute bits // if (IS_PCI_BRIDGE (&PciIoDevice->Pci) || IS_CARDBUS_BRIDGE (&PciIoDevice->Pci)) { - if ((Attributes & (EFI_PCI_IO_ATTRIBUTE_VGA_IO | EFI_PCI_IO_ATTRIBUTE_VGA_IO_16)) != 0) { BridgeControl |= EFI_PCI_BRIDGE_CONTROL_VGA; } @@ -1647,16 +1656,16 @@ PciIoAttributes ( if ((Attributes & (EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO_16 | EFI_PCI_IO_ATTRIBUTE_VGA_IO_16)) != 0) { BridgeControl |= EFI_PCI_BRIDGE_CONTROL_VGA_16; } - } else { // // Do with the attributes on VGA // Only for VGA's legacy resource, we just can enable once. // if ((Attributes & - (EFI_PCI_IO_ATTRIBUTE_VGA_IO | - EFI_PCI_IO_ATTRIBUTE_VGA_IO_16 | - EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY)) != 0) { + (EFI_PCI_IO_ATTRIBUTE_VGA_IO | + EFI_PCI_IO_ATTRIBUTE_VGA_IO_16 | + EFI_PCI_IO_ATTRIBUTE_VGA_MEMORY)) != 0) + { // // Check if a VGA has been enabled before enabling a new one // @@ -1665,7 +1674,7 @@ PciIoAttributes ( // Check if there have been an active VGA device on the same Host Bridge // Temp = LocateVgaDeviceOnHostBridge (PciIoDevice->PciRootBridgeIo->ParentHandle); - if (Temp != NULL && Temp != PciIoDevice) { + if ((Temp != NULL) && (Temp != PciIoDevice)) { // // An active VGA has been detected, so can not enable another // @@ -1678,7 +1687,6 @@ PciIoAttributes ( // Do with the attributes on GFX // if ((Attributes & (EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO | EFI_PCI_IO_ATTRIBUTE_VGA_PALETTE_IO_16)) != 0) { - if (Operation == EfiPciIoAttributeOperationEnable) { // // Check if snoop can be enabled in current configuration @@ -1686,7 +1694,6 @@ PciIoAttributes ( Status = SupportPaletteSnoopAttributes (PciIoDevice, Operation); if (EFI_ERROR (Status)) { - // // Enable operation is forbidden, so mask the bit in attributes // so as to keep consistent with the actual Status @@ -1696,7 +1703,6 @@ PciIoAttributes ( // // return EFI_UNSUPPORTED; - } } @@ -1718,6 +1724,7 @@ PciIoAttributes ( if ((Attributes & EFI_PCI_IO_ATTRIBUTE_BUS_MASTER) != 0) { Command |= EFI_PCI_COMMAND_BUS_MASTER; } + // // The upstream bridge should be also set to relevant attribute // expect for IO, Mem and BusMaster @@ -1727,7 +1734,7 @@ PciIoAttributes ( EFI_PCI_IO_ATTRIBUTE_MEMORY | EFI_PCI_IO_ATTRIBUTE_BUS_MASTER ) - ); + ); UpStreamBridge = PciIoDevice->Parent; if (Operation == EfiPciIoAttributeOperationEnable) { @@ -1745,13 +1752,12 @@ PciIoAttributes ( // Enable attributes of the upstream bridge // Status = UpStreamBridge->PciIo.Attributes ( - &(UpStreamBridge->PciIo), - EfiPciIoAttributeOperationEnable, - UpStreamAttributes, - NULL - ); + &(UpStreamBridge->PciIo), + EfiPciIoAttributeOperationEnable, + UpStreamAttributes, + NULL + ); } else { - // // Disable relevant attributes to command register and bridge control register // @@ -1761,8 +1767,7 @@ PciIoAttributes ( } PciIoDevice->Attributes &= (~Attributes); - Status = EFI_SUCCESS; - + Status = EFI_SUCCESS; } if (EFI_ERROR (Status)) { @@ -1790,20 +1795,20 @@ PciIoAttributes ( **/ UINT64 GetMmioAddressTranslationOffset ( - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *RootBridgeIo, - UINT64 AddrRangeMin, - UINT64 AddrLen + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *RootBridgeIo, + UINT64 AddrRangeMin, + UINT64 AddrLen ) { - EFI_STATUS Status; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; + EFI_STATUS Status; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; Status = RootBridgeIo->Configuration ( RootBridgeIo, - (VOID **) &Configuration + (VOID **)&Configuration ); if (EFI_ERROR (Status)) { - return (UINT64) -1; + return (UINT64)-1; } // According to UEFI 2.7, EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL::Configuration() @@ -1814,9 +1819,11 @@ GetMmioAddressTranslationOffset ( if ((Configuration->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) && (Configuration->AddrRangeMin + Configuration->AddrTranslationOffset <= AddrRangeMin) && (Configuration->AddrRangeMin + Configuration->AddrLen + Configuration->AddrTranslationOffset >= AddrRangeMin + AddrLen) - ) { + ) + { return Configuration->AddrTranslationOffset; } + Configuration++; } @@ -1824,7 +1831,7 @@ GetMmioAddressTranslationOffset ( // The resource occupied by BAR should be in the range reported by RootBridge. // ASSERT (FALSE); - return (UINT64) -1; + return (UINT64)-1; } /** @@ -1852,19 +1859,19 @@ GetMmioAddressTranslationOffset ( EFI_STATUS EFIAPI PciIoGetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL * This, - IN UINT8 BarIndex, - OUT UINT64 *Supports OPTIONAL, - OUT VOID **Resources OPTIONAL + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT8 BarIndex, + OUT UINT64 *Supports OPTIONAL, + OUT VOID **Resources OPTIONAL ) { - PCI_IO_DEVICE *PciIoDevice; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; + PCI_IO_DEVICE *PciIoDevice; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); - if (Supports == NULL && Resources == NULL) { + if ((Supports == NULL) && (Resources == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1886,69 +1893,69 @@ PciIoGetBarAttributes ( return EFI_OUT_OF_RESOURCES; } - *Resources = Descriptor; + *Resources = Descriptor; Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Descriptor->Len = (UINT16) (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); + Descriptor->Len = (UINT16)(sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3); Descriptor->AddrRangeMin = PciIoDevice->PciBar[BarIndex].BaseAddress; Descriptor->AddrLen = PciIoDevice->PciBar[BarIndex].Length; Descriptor->AddrRangeMax = PciIoDevice->PciBar[BarIndex].Alignment; switch (PciIoDevice->PciBar[BarIndex].BarType) { - case PciBarTypeIo16: - case PciBarTypeIo32: - // - // Io - // - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; - break; + case PciBarTypeIo16: + case PciBarTypeIo32: + // + // Io + // + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; + break; - case PciBarTypePMem32: - // - // prefetchable - // - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case PciBarTypePMem32: + // + // prefetchable + // + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; // // Fall through // - case PciBarTypeMem32: - // - // Mem - // - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - // - // 32 bit - // - Descriptor->AddrSpaceGranularity = 32; - break; + case PciBarTypeMem32: + // + // Mem + // + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + // + // 32 bit + // + Descriptor->AddrSpaceGranularity = 32; + break; - case PciBarTypePMem64: - // - // prefetchable - // - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case PciBarTypePMem64: + // + // prefetchable + // + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; // // Fall through // - case PciBarTypeMem64: - // - // Mem - // - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - // - // 64 bit - // - Descriptor->AddrSpaceGranularity = 64; - break; + case PciBarTypeMem64: + // + // Mem + // + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + // + // 64 bit + // + Descriptor->AddrSpaceGranularity = 64; + break; - default: - break; + default: + break; } // // put the checksum // - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) (Descriptor + 1); + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)(Descriptor + 1); End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0; @@ -1961,7 +1968,7 @@ PciIoGetBarAttributes ( Descriptor->AddrRangeMin, Descriptor->AddrLen ); - if (Descriptor->AddrTranslationOffset == (UINT64) -1) { + if (Descriptor->AddrTranslationOffset == (UINT64)-1) { FreePool (Descriptor); return EFI_UNSUPPORTED; } @@ -2002,30 +2009,31 @@ PciIoGetBarAttributes ( EFI_STATUS EFIAPI PciIoSetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINT64 Attributes, - IN UINT8 BarIndex, - IN OUT UINT64 *Offset, - IN OUT UINT64 *Length + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT64 Attributes, + IN UINT8 BarIndex, + IN OUT UINT64 *Offset, + IN OUT UINT64 *Length ) { - EFI_STATUS Status; - PCI_IO_DEVICE *PciIoDevice; - UINT64 NonRelativeOffset; - UINT64 Supports; + EFI_STATUS Status; + PCI_IO_DEVICE *PciIoDevice; + UINT64 NonRelativeOffset; + UINT64 Supports; PciIoDevice = PCI_IO_DEVICE_FROM_PCI_IO_THIS (This); // // Make sure Offset and Length are not NULL // - if (Offset == NULL || Length == NULL) { + if ((Offset == NULL) || (Length == NULL)) { return EFI_INVALID_PARAMETER; } if (PciIoDevice->PciBar[BarIndex].BarType == PciBarTypeUnknown) { return EFI_UNSUPPORTED; } + // // This driver does not support setting the WRITE_COMBINE or the CACHED attributes. // If Attributes is not 0, then return EFI_UNSUPPORTED. @@ -2035,19 +2043,20 @@ PciIoSetBarAttributes ( if (Attributes != (Attributes & Supports)) { return EFI_UNSUPPORTED; } + // // Attributes must be supported. Make sure the BAR range described by BarIndex, Offset, and // Length are valid for this PCI device. // NonRelativeOffset = *Offset; - Status = PciIoVerifyBarAccess ( - PciIoDevice, - BarIndex, - PciBarTypeMem, - EfiPciIoWidthUint8, - (UINT32) *Length, - &NonRelativeOffset - ); + Status = PciIoVerifyBarAccess ( + PciIoDevice, + BarIndex, + PciBarTypeMem, + EfiPciIoWidthUint8, + (UINT32)*Length, + &NonRelativeOffset + ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -2055,7 +2064,6 @@ PciIoSetBarAttributes ( return EFI_SUCCESS; } - /** Test whether two Pci devices has same parent bridge. @@ -2068,12 +2076,12 @@ PciIoSetBarAttributes ( **/ BOOLEAN PciDevicesOnTheSamePath ( - IN PCI_IO_DEVICE *PciDevice1, - IN PCI_IO_DEVICE *PciDevice2 + IN PCI_IO_DEVICE *PciDevice1, + IN PCI_IO_DEVICE *PciDevice2 ) { - BOOLEAN Existed1; - BOOLEAN Existed2; + BOOLEAN Existed1; + BOOLEAN Existed2; if (PciDevice1->Parent == PciDevice2->Parent) { return TRUE; @@ -2082,5 +2090,5 @@ PciDevicesOnTheSamePath ( Existed1 = PciDeviceExisted (PciDevice1->Parent, PciDevice2); Existed2 = PciDeviceExisted (PciDevice2->Parent, PciDevice1); - return (BOOLEAN) (Existed1 || Existed2); + return (BOOLEAN)(Existed1 || Existed2); } diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h index 5de6222f93..a73bd06bcf 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.h @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID InitializePciIoInstance ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -37,12 +37,12 @@ InitializePciIoInstance ( **/ EFI_STATUS PciIoVerifyBarAccess ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 BarIndex, - IN PCI_BAR_TYPE Type, - IN IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN IN UINTN Count, - IN UINT64 *Offset + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 BarIndex, + IN PCI_BAR_TYPE Type, + IN IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN IN UINTN Count, + IN UINT64 *Offset ); /** @@ -347,13 +347,13 @@ PciIoConfigWrite ( EFI_STATUS EFIAPI PciIoCopyMem ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_PCI_IO_PROTOCOL_WIDTH Width, - IN UINT8 DestBarIndex, - IN UINT64 DestOffset, - IN UINT8 SrcBarIndex, - IN UINT64 SrcOffset, - IN UINTN Count + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_PCI_IO_PROTOCOL_WIDTH Width, + IN UINT8 DestBarIndex, + IN UINT64 DestOffset, + IN UINT8 SrcBarIndex, + IN UINT64 SrcOffset, + IN UINTN Count ); /** @@ -426,12 +426,12 @@ PciIoUnmap ( EFI_STATUS EFIAPI PciIoAllocateBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EFI_PCI_IO_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ); /** @@ -449,9 +449,9 @@ PciIoAllocateBuffer ( EFI_STATUS EFIAPI PciIoFreeBuffer ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EFI_PCI_IO_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ); /** @@ -508,9 +508,9 @@ PciIoGetLocation ( **/ BOOLEAN CheckBarType ( - IN PCI_IO_DEVICE *PciIoDevice, - IN UINT8 BarIndex, - IN PCI_BAR_TYPE BarType + IN PCI_IO_DEVICE *PciIoDevice, + IN UINT8 BarIndex, + IN PCI_BAR_TYPE BarType ); /** @@ -569,7 +569,7 @@ SupportPaletteSnoopAttributes ( EFI_STATUS EFIAPI PciIoAttributes ( - IN EFI_PCI_IO_PROTOCOL * This, + IN EFI_PCI_IO_PROTOCOL *This, IN EFI_PCI_IO_PROTOCOL_ATTRIBUTE_OPERATION Operation, IN UINT64 Attributes, OUT UINT64 *Result OPTIONAL @@ -600,10 +600,10 @@ PciIoAttributes ( EFI_STATUS EFIAPI PciIoGetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL * This, - IN UINT8 BarIndex, - OUT UINT64 *Supports OPTIONAL, - OUT VOID **Resources OPTIONAL + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT8 BarIndex, + OUT UINT64 *Supports OPTIONAL, + OUT VOID **Resources OPTIONAL ); /** @@ -633,14 +633,13 @@ PciIoGetBarAttributes ( EFI_STATUS EFIAPI PciIoSetBarAttributes ( - IN EFI_PCI_IO_PROTOCOL *This, - IN UINT64 Attributes, - IN UINT8 BarIndex, - IN OUT UINT64 *Offset, - IN OUT UINT64 *Length + IN EFI_PCI_IO_PROTOCOL *This, + IN UINT64 Attributes, + IN UINT8 BarIndex, + IN OUT UINT64 *Offset, + IN OUT UINT64 *Length ); - /** Test whether two Pci devices has same parent bridge. @@ -653,8 +652,8 @@ PciIoSetBarAttributes ( **/ BOOLEAN PciDevicesOnTheSamePath ( - IN PCI_IO_DEVICE *PciDevice1, - IN PCI_IO_DEVICE *PciDevice2 + IN PCI_IO_DEVICE *PciDevice1, + IN PCI_IO_DEVICE *PciDevice2 ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c index 0ad1dfa526..63d149b3b8 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciBus.h" GLOBAL_REMOVE_IF_UNREFERENCED -CHAR16 *mBarTypeStr[] = { +CHAR16 *mBarTypeStr[] = { L"Unknow", L" Io16", L" Io32", @@ -22,7 +22,7 @@ CHAR16 *mBarTypeStr[] = { L" Io", L" Mem", L"Unknow" - }; +}; /** Retrieve the max bus number that is assigned to the Root Bridge hierarchy. @@ -35,7 +35,7 @@ CHAR16 *mBarTypeStr[] = { **/ UINT16 PciGetMaxBusNumber ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ) { PCI_IO_DEVICE *RootBridge; @@ -49,6 +49,7 @@ PciGetMaxBusNumber ( while (RootBridge->Parent != NULL) { RootBridge = RootBridge->Parent; } + MaxNumberInRange = 0; // // Iterate the bus number ranges to get max PCI bus number @@ -58,7 +59,8 @@ PciGetMaxBusNumber ( MaxNumberInRange = BusNumberRanges->AddrRangeMin + BusNumberRanges->AddrLen - 1; BusNumberRanges++; } - return (UINT16) MaxNumberInRange; + + return (UINT16)MaxNumberInRange; } /** @@ -69,7 +71,7 @@ PciGetMaxBusNumber ( **/ VOID GetBackPcCardBar ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { UINT32 Address; @@ -91,9 +93,9 @@ GetBackPcCardBar ( &Address ); - (PciIoDevice->PciBar)[P2C_MEM_1].BaseAddress = (UINT64) (Address); - (PciIoDevice->PciBar)[P2C_MEM_1].Length = 0x2000000; - (PciIoDevice->PciBar)[P2C_MEM_1].BarType = PciBarTypeMem32; + (PciIoDevice->PciBar)[P2C_MEM_1].BaseAddress = (UINT64)(Address); + (PciIoDevice->PciBar)[P2C_MEM_1].Length = 0x2000000; + (PciIoDevice->PciBar)[P2C_MEM_1].BarType = PciBarTypeMem32; Address = 0; PciIoDevice->PciIo.Pci.Read ( @@ -103,9 +105,9 @@ GetBackPcCardBar ( 1, &Address ); - (PciIoDevice->PciBar)[P2C_MEM_2].BaseAddress = (UINT64) (Address); - (PciIoDevice->PciBar)[P2C_MEM_2].Length = 0x2000000; - (PciIoDevice->PciBar)[P2C_MEM_2].BarType = PciBarTypePMem32; + (PciIoDevice->PciBar)[P2C_MEM_2].BaseAddress = (UINT64)(Address); + (PciIoDevice->PciBar)[P2C_MEM_2].Length = 0x2000000; + (PciIoDevice->PciBar)[P2C_MEM_2].BarType = PciBarTypePMem32; Address = 0; PciIoDevice->PciIo.Pci.Read ( @@ -115,7 +117,7 @@ GetBackPcCardBar ( 1, &Address ); - (PciIoDevice->PciBar)[P2C_IO_1].BaseAddress = (UINT64) (Address); + (PciIoDevice->PciBar)[P2C_IO_1].BaseAddress = (UINT64)(Address); (PciIoDevice->PciBar)[P2C_IO_1].Length = 0x100; (PciIoDevice->PciBar)[P2C_IO_1].BarType = PciBarTypeIo16; @@ -127,13 +129,12 @@ GetBackPcCardBar ( 1, &Address ); - (PciIoDevice->PciBar)[P2C_IO_2].BaseAddress = (UINT64) (Address); + (PciIoDevice->PciBar)[P2C_IO_2].BaseAddress = (UINT64)(Address); (PciIoDevice->PciBar)[P2C_IO_2].Length = 0x100; (PciIoDevice->PciBar)[P2C_IO_2].BarType = PciBarTypeIo16; - } - if (gPciHotPlugInit != NULL && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { + if ((gPciHotPlugInit != NULL) && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { GetResourcePaddingForHpb (PciIoDevice); } } @@ -148,13 +149,13 @@ GetBackPcCardBar ( **/ VOID RemoveRejectedPciDevices ( - IN EFI_HANDLE RootBridgeHandle, - IN PCI_IO_DEVICE *Bridge + IN EFI_HANDLE RootBridgeHandle, + IN PCI_IO_DEVICE *Bridge ) { - PCI_IO_DEVICE *Temp; - LIST_ENTRY *CurrentLink; - LIST_ENTRY *LastLink; + PCI_IO_DEVICE *Temp; + LIST_ENTRY *CurrentLink; + LIST_ENTRY *LastLink; if (!FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { return; @@ -163,7 +164,6 @@ RemoveRejectedPciDevices ( CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (IS_PCI_BRIDGE (&Temp->Pci)) { @@ -176,7 +176,6 @@ RemoveRejectedPciDevices ( // Skip rejection for all PPBs, while detect rejection for others // if (IsPciDeviceRejected (Temp)) { - // // For P2C, remove all devices on it // @@ -206,41 +205,49 @@ RemoveRejectedPciDevices ( **/ VOID DumpBridgeResource ( - IN PCI_RESOURCE_NODE *BridgeResource + IN PCI_RESOURCE_NODE *BridgeResource ) { - LIST_ENTRY *Link; - PCI_RESOURCE_NODE *Resource; - PCI_BAR *Bar; + LIST_ENTRY *Link; + PCI_RESOURCE_NODE *Resource; + PCI_BAR *Bar; if ((BridgeResource != NULL) && (BridgeResource->Length != 0)) { DEBUG (( - DEBUG_INFO, "Type = %s; Base = 0x%lx;\tLength = 0x%lx;\tAlignment = 0x%lx\n", + DEBUG_INFO, + "Type = %s; Base = 0x%lx;\tLength = 0x%lx;\tAlignment = 0x%lx\n", mBarTypeStr[MIN (BridgeResource->ResType, PciBarTypeMaxType)], BridgeResource->PciDev->PciBar[BridgeResource->Bar].BaseAddress, - BridgeResource->Length, BridgeResource->Alignment + BridgeResource->Length, + BridgeResource->Alignment )); for ( Link = GetFirstNode (&BridgeResource->ChildList) - ; !IsNull (&BridgeResource->ChildList, Link) - ; Link = GetNextNode (&BridgeResource->ChildList, Link) - ) { + ; !IsNull (&BridgeResource->ChildList, Link) + ; Link = GetNextNode (&BridgeResource->ChildList, Link) + ) + { Resource = RESOURCE_NODE_FROM_LINK (Link); if (Resource->ResourceUsage == PciResUsageTypical) { Bar = Resource->Virtual ? Resource->PciDev->VfPciBar : Resource->PciDev->PciBar; DEBUG (( - DEBUG_INFO, " Base = 0x%lx;\tLength = 0x%lx;\tAlignment = 0x%lx;\tOwner = %s [%02x|%02x|%02x:", - Bar[Resource->Bar].BaseAddress, Resource->Length, Resource->Alignment, + DEBUG_INFO, + " Base = 0x%lx;\tLength = 0x%lx;\tAlignment = 0x%lx;\tOwner = %s [%02x|%02x|%02x:", + Bar[Resource->Bar].BaseAddress, + Resource->Length, + Resource->Alignment, IS_PCI_BRIDGE (&Resource->PciDev->Pci) ? L"PPB" : IS_CARDBUS_BRIDGE (&Resource->PciDev->Pci) ? L"P2C" : - L"PCI", - Resource->PciDev->BusNumber, Resource->PciDev->DeviceNumber, + L"PCI", + Resource->PciDev->BusNumber, + Resource->PciDev->DeviceNumber, Resource->PciDev->FunctionNumber )); if ((!IS_PCI_BRIDGE (&Resource->PciDev->Pci) && !IS_CARDBUS_BRIDGE (&Resource->PciDev->Pci)) || (IS_PCI_BRIDGE (&Resource->PciDev->Pci) && (Resource->Bar < PPB_IO_RANGE)) || (IS_CARDBUS_BRIDGE (&Resource->PciDev->Pci) && (Resource->Bar < P2C_MEM_1)) - ) { + ) + { // // The resource requirement comes from the device itself. // @@ -254,9 +261,11 @@ DumpBridgeResource ( } else { DEBUG ((DEBUG_INFO, " Base = Padding;\tLength = 0x%lx;\tAlignment = 0x%lx", Resource->Length, Resource->Alignment)); } + if (BridgeResource->ResType != Resource->ResType) { DEBUG ((DEBUG_INFO, "; Type = %s", mBarTypeStr[MIN (Resource->ResType, PciBarTypeMaxType)])); } + DEBUG ((DEBUG_INFO, "\n")); } } @@ -273,25 +282,27 @@ DumpBridgeResource ( **/ UINTN FindResourceNode ( - IN PCI_IO_DEVICE *Device, - IN PCI_RESOURCE_NODE *BridgeResource, - OUT PCI_RESOURCE_NODE **DeviceResources OPTIONAL + IN PCI_IO_DEVICE *Device, + IN PCI_RESOURCE_NODE *BridgeResource, + OUT PCI_RESOURCE_NODE **DeviceResources OPTIONAL ) { - LIST_ENTRY *Link; - PCI_RESOURCE_NODE *Resource; - UINTN Count; + LIST_ENTRY *Link; + PCI_RESOURCE_NODE *Resource; + UINTN Count; Count = 0; for ( Link = BridgeResource->ChildList.ForwardLink - ; Link != &BridgeResource->ChildList - ; Link = Link->ForwardLink - ) { + ; Link != &BridgeResource->ChildList + ; Link = Link->ForwardLink + ) + { Resource = RESOURCE_NODE_FROM_LINK (Link); if (Resource->PciDev == Device) { if (DeviceResources != NULL) { DeviceResources[Count] = Resource; } + Count++; } } @@ -308,18 +319,18 @@ FindResourceNode ( **/ VOID DumpResourceMap ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_RESOURCE_NODE **Resources, - IN UINTN ResourceCount + IN PCI_IO_DEVICE *Bridge, + IN PCI_RESOURCE_NODE **Resources, + IN UINTN ResourceCount ) { - EFI_STATUS Status; - LIST_ENTRY *Link; - PCI_IO_DEVICE *Device; - UINTN Index; - CHAR16 *Str; - PCI_RESOURCE_NODE **ChildResources; - UINTN ChildResourceCount; + EFI_STATUS Status; + LIST_ENTRY *Link; + PCI_IO_DEVICE *Device; + UINTN Index; + CHAR16 *Str; + PCI_RESOURCE_NODE **ChildResources; + UINTN ChildResourceCount; DEBUG ((DEBUG_INFO, "PciBus: Resource Map for ")); @@ -333,8 +344,11 @@ DumpResourceMap ( ); if (EFI_ERROR (Status)) { DEBUG (( - DEBUG_INFO, "Bridge [%02x|%02x|%02x]\n", - Bridge->BusNumber, Bridge->DeviceNumber, Bridge->FunctionNumber + DEBUG_INFO, + "Bridge [%02x|%02x|%02x]\n", + Bridge->BusNumber, + Bridge->DeviceNumber, + Bridge->FunctionNumber )); } else { Str = ConvertDevicePathToText ( @@ -351,19 +365,21 @@ DumpResourceMap ( for (Index = 0; Index < ResourceCount; Index++) { DumpBridgeResource (Resources[Index]); } + DEBUG ((DEBUG_INFO, "\n")); for ( Link = Bridge->ChildList.ForwardLink - ; Link != &Bridge->ChildList - ; Link = Link->ForwardLink - ) { + ; Link != &Bridge->ChildList + ; Link = Link->ForwardLink + ) + { Device = PCI_IO_DEVICE_FROM_LINK (Link); if (IS_PCI_BRIDGE (&Device->Pci)) { - ChildResourceCount = 0; for (Index = 0; Index < ResourceCount; Index++) { ChildResourceCount += FindResourceNode (Device, Resources[Index], NULL); } + ChildResources = AllocatePool (sizeof (PCI_RESOURCE_NODE *) * ChildResourceCount); ASSERT (ChildResources != NULL); ChildResourceCount = 0; @@ -387,14 +403,14 @@ DumpResourceMap ( **/ BOOLEAN AdjustPciDeviceBarSize ( - IN PCI_IO_DEVICE *RootBridgeDev + IN PCI_IO_DEVICE *RootBridgeDev ) { - PCI_IO_DEVICE *PciIoDevice; - LIST_ENTRY *CurrentLink; - BOOLEAN Adjusted; - UINTN Offset; - UINTN BarIndex; + PCI_IO_DEVICE *PciIoDevice; + LIST_ENTRY *CurrentLink; + BOOLEAN Adjusted; + UINTN Offset; + UINTN BarIndex; Adjusted = FALSE; CurrentLink = RootBridgeDev->ChildList.ForwardLink; @@ -411,7 +427,9 @@ AdjustPciDeviceBarSize ( DEBUG (( DEBUG_ERROR, "PciBus: [%02x|%02x|%02x] Adjust Pci Device Bar Size\n", - PciIoDevice->BusNumber, PciIoDevice->DeviceNumber, PciIoDevice->FunctionNumber + PciIoDevice->BusNumber, + PciIoDevice->DeviceNumber, + PciIoDevice->FunctionNumber )); PciProgramResizableBar (PciIoDevice, PciResizableBarMin); // @@ -420,8 +438,11 @@ AdjustPciDeviceBarSize ( for (Offset = 0x10, BarIndex = 0; Offset <= 0x24 && BarIndex < PCI_MAX_BAR; BarIndex++) { Offset = PciParseBar (PciIoDevice, Offset, BarIndex); } + Adjusted = TRUE; - DEBUG_CODE (DumpPciBars (PciIoDevice);); + DEBUG_CODE ( + DumpPciBars (PciIoDevice); + ); } } @@ -446,7 +467,7 @@ AdjustPciDeviceBarSize ( **/ EFI_STATUS PciHostBridgeResourceAllocator ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ) { PCI_IO_DEVICE *RootBridgeDev; @@ -494,8 +515,8 @@ PciHostBridgeResourceAllocator ( InitializeResourcePool (&Mem64Pool, PciBarTypeMem64); InitializeResourcePool (&PMem64Pool, PciBarTypePMem64); - RootBridgeDev = NULL; - RootBridgeHandle = 0; + RootBridgeDev = NULL; + RootBridgeHandle = 0; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { // @@ -519,7 +540,7 @@ PciHostBridgeResourceAllocator ( IoBridge = CreateResourceNode ( RootBridgeDev, 0, - FeaturePcdGet (PcdPciBridgeIoAlignmentProbe) ? 0x1FF: 0xFFF, + FeaturePcdGet (PcdPciBridgeIoAlignmentProbe) ? 0x1FF : 0xFFF, RB_IO_RANGE, PciBarTypeIo16, PciResUsageTypical @@ -645,6 +666,7 @@ PciHostBridgeResourceAllocator ( return Status; } } + // // End while, at least one Root Bridge should be found. // @@ -665,6 +687,7 @@ PciHostBridgeResourceAllocator ( // return EFI_OUT_OF_RESOURCES; } + // // Allocation succeed. // Get host bridge handle for status report, and then skip the main while @@ -672,7 +695,6 @@ PciHostBridgeResourceAllocator ( HandleExtendedData.Handle = RootBridgeDev->PciRootBridgeIo->ParentHandle; break; - } else { // // If Hot Plug is supported @@ -688,14 +710,14 @@ PciHostBridgeResourceAllocator ( // If the resource allocation is unsuccessful, free resources on bridge // - RootBridgeDev = NULL; - RootBridgeHandle = 0; + RootBridgeDev = NULL; + RootBridgeHandle = 0; - IoResStatus = EFI_RESOURCE_SATISFIED; - Mem32ResStatus = EFI_RESOURCE_SATISFIED; - PMem32ResStatus = EFI_RESOURCE_SATISFIED; - Mem64ResStatus = EFI_RESOURCE_SATISFIED; - PMem64ResStatus = EFI_RESOURCE_SATISFIED; + IoResStatus = EFI_RESOURCE_SATISFIED; + Mem32ResStatus = EFI_RESOURCE_SATISFIED; + PMem32ResStatus = EFI_RESOURCE_SATISFIED; + Mem64ResStatus = EFI_RESOURCE_SATISFIED; + PMem64ResStatus = EFI_RESOURCE_SATISFIED; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { // @@ -741,6 +763,7 @@ PciHostBridgeResourceAllocator ( FreePool (AcpiConfig); } } + // // End while // @@ -755,36 +778,38 @@ PciHostBridgeResourceAllocator ( ZeroMem (&AllocFailExtendedData, sizeof (AllocFailExtendedData)); REPORT_STATUS_CODE_WITH_EXTENDED_DATA ( - EFI_PROGRESS_CODE, - EFI_IO_BUS_PCI | EFI_IOB_EC_RESOURCE_CONFLICT, - (VOID *) &AllocFailExtendedData, - sizeof (AllocFailExtendedData) - ); + EFI_PROGRESS_CODE, + EFI_IO_BUS_PCI | EFI_IOB_EC_RESOURCE_CONFLICT, + (VOID *)&AllocFailExtendedData, + sizeof (AllocFailExtendedData) + ); - // - // When resource conflict happens, adjust the BAR size first. - // Only when adjusting BAR size doesn't help or BAR size cannot be adjusted, - // reject the device who requests largest resource that causes conflict. - // + // + // When resource conflict happens, adjust the BAR size first. + // Only when adjusting BAR size doesn't help or BAR size cannot be adjusted, + // reject the device who requests largest resource that causes conflict. + // ResizableBarAdjusted = FALSE; if (ResizableBarNeedAdjust) { - ResizableBarAdjusted = AdjustPciDeviceBarSize (RootBridgeDev); + ResizableBarAdjusted = AdjustPciDeviceBarSize (RootBridgeDev); ResizableBarNeedAdjust = FALSE; } + if (!ResizableBarAdjusted) { Status = PciHostBridgeAdjustAllocation ( - &IoPool, - &Mem32Pool, - &PMem32Pool, - &Mem64Pool, - &PMem64Pool, - IoResStatus, - Mem32ResStatus, - PMem32ResStatus, - Mem64ResStatus, - PMem64ResStatus - ); + &IoPool, + &Mem32Pool, + &PMem32Pool, + &Mem64Pool, + &PMem64Pool, + IoResStatus, + Mem32ResStatus, + PMem32ResStatus, + Mem64ResStatus, + PMem64ResStatus + ); } + // // Destroy all the resource tree // @@ -801,6 +826,7 @@ PciHostBridgeResourceAllocator ( } } } + // // End main while // @@ -809,11 +835,11 @@ PciHostBridgeResourceAllocator ( // Raise the EFI_IOB_PCI_RES_ALLOC status code // REPORT_STATUS_CODE_WITH_EXTENDED_DATA ( - EFI_PROGRESS_CODE, - EFI_IO_BUS_PCI | EFI_IOB_PCI_RES_ALLOC, - (VOID *) &HandleExtendedData, - sizeof (HandleExtendedData) - ); + EFI_PROGRESS_CODE, + EFI_IO_BUS_PCI | EFI_IOB_PCI_RES_ALLOC, + (VOID *)&HandleExtendedData, + sizeof (HandleExtendedData) + ); // // Notify pci bus driver starts to program the resource @@ -824,9 +850,9 @@ PciHostBridgeResourceAllocator ( return Status; } - RootBridgeDev = NULL; + RootBridgeDev = NULL; - RootBridgeHandle = 0; + RootBridgeHandle = 0; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { // @@ -842,11 +868,11 @@ PciHostBridgeResourceAllocator ( // Get acpi resource node for all the resource types // AcpiConfig = NULL; - Status = PciResAlloc->GetProposedResources ( - PciResAlloc, - RootBridgeDev->Handle, - &AcpiConfig - ); + Status = PciResAlloc->GetProposedResources ( + PciResAlloc, + RootBridgeDev->Handle, + &AcpiConfig + ); if (EFI_ERROR (Status)) { return Status; @@ -930,15 +956,17 @@ PciHostBridgeResourceAllocator ( // The original value is programmed by ProgramResource() above. // DEBUG (( - DEBUG_INFO, "Process Option ROM: BAR Base/Length = %lx/%lx\n", - RootBridgeDev->PciBar[0].BaseAddress, RootBridgeDev->PciBar[0].Length + DEBUG_INFO, + "Process Option ROM: BAR Base/Length = %lx/%lx\n", + RootBridgeDev->PciBar[0].BaseAddress, + RootBridgeDev->PciBar[0].Length )); ProcessOptionRom (RootBridgeDev, RootBridgeDev->PciBar[0].BaseAddress, RootBridgeDev->PciBar[0].Length); - IoBridge ->PciDev->PciBar[IoBridge ->Bar].BaseAddress = IoBase; - Mem32Bridge ->PciDev->PciBar[Mem32Bridge ->Bar].BaseAddress = Mem32Base; + IoBridge->PciDev->PciBar[IoBridge->Bar].BaseAddress = IoBase; + Mem32Bridge->PciDev->PciBar[Mem32Bridge->Bar].BaseAddress = Mem32Base; PMem32Bridge->PciDev->PciBar[PMem32Bridge->Bar].BaseAddress = PMem32Base; - Mem64Bridge ->PciDev->PciBar[Mem64Bridge ->Bar].BaseAddress = Mem64Base; + Mem64Bridge->PciDev->PciBar[Mem64Bridge->Bar].BaseAddress = Mem64Base; PMem64Bridge->PciDev->PciBar[PMem64Bridge->Bar].BaseAddress = PMem64Base; // @@ -952,7 +980,7 @@ PciHostBridgeResourceAllocator ( Resources[3] = Mem64Bridge; Resources[4] = PMem64Bridge; DumpResourceMap (RootBridgeDev, Resources, ARRAY_SIZE (Resources)); - ); + ); FreePool (AcpiConfig); } @@ -989,10 +1017,10 @@ PciHostBridgeResourceAllocator ( **/ EFI_STATUS PciAllocateBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - IN UINT8 NumberOfBuses, - OUT UINT8 *NextBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + IN UINT8 NumberOfBuses, + OUT UINT8 *NextBusNumber ) { PCI_IO_DEVICE *RootBridge; @@ -1014,21 +1042,25 @@ PciAllocateBusNumber ( BusNumberRanges = RootBridge->BusNumberRanges; while (BusNumberRanges->Desc != ACPI_END_TAG_DESCRIPTOR) { MaxNumberInRange = BusNumberRanges->AddrRangeMin + BusNumberRanges->AddrLen - 1; - if (StartBusNumber >= BusNumberRanges->AddrRangeMin && StartBusNumber <= MaxNumberInRange) { + if ((StartBusNumber >= BusNumberRanges->AddrRangeMin) && (StartBusNumber <= MaxNumberInRange)) { NextNumber = (UINT8)(StartBusNumber + NumberOfBuses); while (NextNumber > MaxNumberInRange) { ++BusNumberRanges; if (BusNumberRanges->Desc == ACPI_END_TAG_DESCRIPTOR) { return EFI_OUT_OF_RESOURCES; } - NextNumber = (UINT8)(NextNumber + (BusNumberRanges->AddrRangeMin - (MaxNumberInRange + 1))); + + NextNumber = (UINT8)(NextNumber + (BusNumberRanges->AddrRangeMin - (MaxNumberInRange + 1))); MaxNumberInRange = BusNumberRanges->AddrRangeMin + BusNumberRanges->AddrLen - 1; } + *NextBusNumber = NextNumber; return EFI_SUCCESS; } + BusNumberRanges++; } + return EFI_OUT_OF_RESOURCES; } @@ -1048,38 +1080,38 @@ PciAllocateBusNumber ( **/ EFI_STATUS PciScanBus ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - OUT UINT8 *SubBusNumber, - OUT UINT8 *PaddedBusRange + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + OUT UINT8 *SubBusNumber, + OUT UINT8 *PaddedBusRange ) { - EFI_STATUS Status; - PCI_TYPE00 Pci; - UINT8 Device; - UINT8 Func; - UINT64 Address; - UINT8 SecondBus; - UINT8 PaddedSubBus; - UINT16 Register; - UINTN HpIndex; - PCI_IO_DEVICE *PciDevice; - EFI_EVENT Event; - EFI_HPC_STATE State; - UINT64 PciAddress; - EFI_HPC_PADDING_ATTRIBUTES Attributes; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *NextDescriptors; - UINT16 BusRange; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - BOOLEAN BusPadding; - UINT32 TempReservedBusNum; + EFI_STATUS Status; + PCI_TYPE00 Pci; + UINT8 Device; + UINT8 Func; + UINT64 Address; + UINT8 SecondBus; + UINT8 PaddedSubBus; + UINT16 Register; + UINTN HpIndex; + PCI_IO_DEVICE *PciDevice; + EFI_EVENT Event; + EFI_HPC_STATE State; + UINT64 PciAddress; + EFI_HPC_PADDING_ATTRIBUTES Attributes; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *NextDescriptors; + UINT16 BusRange; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + BOOLEAN BusPadding; + UINT32 TempReservedBusNum; PciRootBridgeIo = Bridge->PciRootBridgeIo; SecondBus = 0; Register = 0; State = 0; - Attributes = (EFI_HPC_PADDING_ATTRIBUTES) 0; + Attributes = (EFI_HPC_PADDING_ATTRIBUTES)0; BusRange = 0; BusPadding = FALSE; PciDevice = NULL; @@ -1088,19 +1120,18 @@ PciScanBus ( for (Device = 0; Device <= PCI_MAX_DEVICE; Device++) { TempReservedBusNum = 0; for (Func = 0; Func <= PCI_MAX_FUNC; Func++) { - // // Check to see whether a pci device is present // Status = PciDevicePresent ( - PciRootBridgeIo, - &Pci, - StartBusNumber, - Device, - Func - ); + PciRootBridgeIo, + &Pci, + StartBusNumber, + Device, + Func + ); - if (EFI_ERROR (Status) && Func == 0) { + if (EFI_ERROR (Status) && (Func == 0)) { // // go to next device if there is no Function 0 // @@ -1115,13 +1146,13 @@ PciScanBus ( // Get the PCI device information // Status = PciSearchDevice ( - Bridge, - &Pci, - StartBusNumber, - Device, - Func, - &PciDevice - ); + Bridge, + &Pci, + StartBusNumber, + Device, + Func, + &PciDevice + ); if (EFI_ERROR (Status)) { continue; @@ -1136,12 +1167,12 @@ PciScanBus ( // EfiPciBeforeChildBusEnumeration for PCI Device Node // PreprocessController ( - PciDevice, - PciDevice->BusNumber, - PciDevice->DeviceNumber, - PciDevice->FunctionNumber, - EfiPciBeforeChildBusEnumeration - ); + PciDevice, + PciDevice->BusNumber, + PciDevice->DeviceNumber, + PciDevice->FunctionNumber, + EfiPciBeforeChildBusEnumeration + ); } if (FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { @@ -1156,7 +1187,6 @@ PciScanBus ( gPciRootHpcData[HpIndex].Found = TRUE; if (!gPciRootHpcData[HpIndex].Initialized) { - Status = CreateEventForHpc (HpIndex, &Event); ASSERT (!EFI_ERROR (Status)); @@ -1175,7 +1205,7 @@ PciScanBus ( PciDevice->DeviceNumber, PciDevice->FunctionNumber, EfiPciBeforeChildBusEnumeration - ); + ); } } } @@ -1192,9 +1222,7 @@ PciScanBus ( // BusPadding = FALSE; if (gPciHotPlugInit != NULL) { - if (IsPciHotPlugBus (PciDevice)) { - // // If it is initialized, get the padded bus range // @@ -1203,7 +1231,7 @@ PciScanBus ( PciDevice->DevicePath, PciAddress, &State, - (VOID **) &Descriptors, + (VOID **)&Descriptors, &Attributes ); @@ -1211,14 +1239,14 @@ PciScanBus ( return Status; } - BusRange = 0; + BusRange = 0; NextDescriptors = Descriptors; - Status = PciGetBusRange ( - &NextDescriptors, - NULL, - NULL, - &BusRange - ); + Status = PciGetBusRange ( + &NextDescriptors, + NULL, + NULL, + &BusRange + ); FreePool (Descriptors); @@ -1238,10 +1266,11 @@ PciScanBus ( if (EFI_ERROR (Status)) { return Status; } + SecondBus = *SubBusNumber; - Register = (UINT16) ((SecondBus << 8) | (UINT16) StartBusNumber); - Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, PCI_BRIDGE_PRIMARY_BUS_REGISTER_OFFSET); + Register = (UINT16)((SecondBus << 8) | (UINT16)StartBusNumber); + Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, PCI_BRIDGE_PRIMARY_BUS_REGISTER_OFFSET); Status = PciRootBridgeIo->Pci.Write ( PciRootBridgeIo, @@ -1251,25 +1280,23 @@ PciScanBus ( &Register ); - // // If it is PPB, resursively search down this bridge // if (IS_PCI_BRIDGE (&Pci)) { - // // Temporarily initialize SubBusNumber to maximum bus number to ensure the // PCI configuration transaction to go through any PPB // - Register = PciGetMaxBusNumber (Bridge); - Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, PCI_BRIDGE_SUBORDINATE_BUS_REGISTER_OFFSET); - Status = PciRootBridgeIo->Pci.Write ( - PciRootBridgeIo, - EfiPciWidthUint8, - Address, - 1, - &Register - ); + Register = PciGetMaxBusNumber (Bridge); + Address = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, PCI_BRIDGE_SUBORDINATE_BUS_REGISTER_OFFSET); + Status = PciRootBridgeIo->Pci.Write ( + PciRootBridgeIo, + EfiPciWidthUint8, + Address, + 1, + &Register + ); // // Nofify EfiPciBeforeChildBusEnumeration for PCI Brige @@ -1283,11 +1310,11 @@ PciScanBus ( ); Status = PciScanBus ( - PciDevice, - SecondBus, - SubBusNumber, - PaddedBusRange - ); + PciDevice, + SecondBus, + SubBusNumber, + PaddedBusRange + ); if (EFI_ERROR (Status)) { return Status; } @@ -1298,17 +1325,19 @@ PciScanBus ( // Ensure the device is enabled and initialized // if ((Attributes == EfiPaddingPciRootBridge) && - (State & EFI_HPC_STATE_ENABLED) != 0 && - (State & EFI_HPC_STATE_INITIALIZED) != 0) { - *PaddedBusRange = (UINT8) ((UINT8) (BusRange) + *PaddedBusRange); + ((State & EFI_HPC_STATE_ENABLED) != 0) && + ((State & EFI_HPC_STATE_INITIALIZED) != 0)) + { + *PaddedBusRange = (UINT8)((UINT8)(BusRange) + *PaddedBusRange); } else { // // Reserve the larger one between the actual occupied bus number and padded bus number // - Status = PciAllocateBusNumber (PciDevice, SecondBus, (UINT8) (BusRange), &PaddedSubBus); + Status = PciAllocateBusNumber (PciDevice, SecondBus, (UINT8)(BusRange), &PaddedSubBus); if (EFI_ERROR (Status)) { return Status; } + *SubBusNumber = MAX (PaddedSubBus, *SubBusNumber); } } @@ -1325,18 +1354,18 @@ PciScanBus ( 1, SubBusNumber ); - } else { + } else { // // It is device. Check PCI IOV for Bus reservation // Go through each function, just reserve the MAX ReservedBusNum for one device // - if (PcdGetBool (PcdSrIovSupport) && PciDevice->SrIovCapabilityOffset != 0) { + if (PcdGetBool (PcdSrIovSupport) && (PciDevice->SrIovCapabilityOffset != 0)) { if (TempReservedBusNum < PciDevice->ReservedBusNum) { - - Status = PciAllocateBusNumber (PciDevice, *SubBusNumber, (UINT8) (PciDevice->ReservedBusNum - TempReservedBusNum), SubBusNumber); + Status = PciAllocateBusNumber (PciDevice, *SubBusNumber, (UINT8)(PciDevice->ReservedBusNum - TempReservedBusNum), SubBusNumber); if (EFI_ERROR (Status)) { return Status; } + TempReservedBusNum = PciDevice->ReservedBusNum; if (Func == 0) { @@ -1348,8 +1377,7 @@ PciScanBus ( } } - if (Func == 0 && !IS_PCI_MULTI_FUNC (&Pci)) { - + if ((Func == 0) && !IS_PCI_MULTI_FUNC (&Pci)) { // // Skip sub functions, this is not a multi function device // @@ -1373,25 +1401,22 @@ PciScanBus ( **/ EFI_STATUS PciRootBridgeP2CProcess ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_IO_DEVICE *Temp; - EFI_HPC_STATE State; - UINT64 PciAddress; - EFI_STATUS Status; + LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; + EFI_HPC_STATE State; + UINT64 PciAddress; + EFI_STATUS Status; CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); if (IS_CARDBUS_BRIDGE (&Temp->Pci)) { - - if (gPciHotPlugInit != NULL && Temp->Allocated && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { - + if ((gPciHotPlugInit != NULL) && Temp->Allocated && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { // // Raise the EFI_IOB_PCI_HPC_INIT status code // @@ -1402,13 +1427,13 @@ PciRootBridgeP2CProcess ( ); PciAddress = EFI_PCI_ADDRESS (Temp->BusNumber, Temp->DeviceNumber, Temp->FunctionNumber, 0); - Status = gPciHotPlugInit->InitializeRootHpc ( - gPciHotPlugInit, - Temp->DevicePath, - PciAddress, - NULL, - &State - ); + Status = gPciHotPlugInit->InitializeRootHpc ( + gPciHotPlugInit, + Temp->DevicePath, + PciAddress, + NULL, + &State + ); if (!EFI_ERROR (Status)) { Status = PciBridgeEnumerator (Temp); @@ -1420,7 +1445,6 @@ PciRootBridgeP2CProcess ( CurrentLink = CurrentLink->ForwardLink; continue; - } } @@ -1446,12 +1470,12 @@ PciRootBridgeP2CProcess ( **/ EFI_STATUS PciHostBridgeP2CProcess ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ) { - EFI_HANDLE RootBridgeHandle; - PCI_IO_DEVICE *RootBridgeDev; - EFI_STATUS Status; + EFI_HANDLE RootBridgeHandle; + PCI_IO_DEVICE *RootBridgeDev; + EFI_STATUS Status; if (!FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { return EFI_SUCCESS; @@ -1460,7 +1484,6 @@ PciHostBridgeP2CProcess ( RootBridgeHandle = NULL; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { - // // Get RootBridg Device by handle // @@ -1474,7 +1497,6 @@ PciHostBridgeP2CProcess ( if (EFI_ERROR (Status)) { return Status; } - } return EFI_SUCCESS; @@ -1496,16 +1518,16 @@ PciHostBridgeEnumerator ( IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ) { - EFI_HANDLE RootBridgeHandle; - PCI_IO_DEVICE *RootBridgeDev; - EFI_STATUS Status; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - UINT16 MinBus; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; - UINT8 StartBusNumber; - LIST_ENTRY RootBridgeList; - LIST_ENTRY *Link; + EFI_HANDLE RootBridgeHandle; + PCI_IO_DEVICE *RootBridgeDev; + EFI_STATUS Status; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + UINT16 MinBus; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptors; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Configuration; + UINT8 StartBusNumber; + LIST_ENTRY RootBridgeList; + LIST_ENTRY *Link; if (FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { InitializeHotPlugSupport (); @@ -1522,10 +1544,9 @@ PciHostBridgeEnumerator ( return Status; } - DEBUG((DEBUG_INFO, "PCI Bus First Scanning\n")); + DEBUG ((DEBUG_INFO, "PCI Bus First Scanning\n")); RootBridgeHandle = NULL; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { - // // if a root bridge instance is found, create root bridge device for it // @@ -1540,15 +1561,16 @@ PciHostBridgeEnumerator ( // Enumerate all the buses under this root bridge // Status = PciRootBridgeEnumerator ( - PciResAlloc, - RootBridgeDev - ); + PciResAlloc, + RootBridgeDev + ); - if (gPciHotPlugInit != NULL && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { + if ((gPciHotPlugInit != NULL) && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { InsertTailList (&RootBridgeList, &(RootBridgeDev->Link)); } else { DestroyRootBridge (RootBridgeDev); } + if (EFI_ERROR (Status)) { return Status; } @@ -1559,14 +1581,15 @@ PciHostBridgeEnumerator ( // NotifyPhase (PciResAlloc, EfiPciHostBridgeEndBusAllocation); - if (gPciHotPlugInit != NULL && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { + if ((gPciHotPlugInit != NULL) && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { // // Reset all assigned PCI bus number in all PPB // RootBridgeHandle = NULL; - Link = GetFirstNode (&RootBridgeList); + Link = GetFirstNode (&RootBridgeList); while ((PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) && - (!IsNull (&RootBridgeList, Link))) { + (!IsNull (&RootBridgeList, Link))) + { RootBridgeDev = PCI_IO_DEVICE_FROM_LINK (Link); // // Get the Bus information @@ -1574,7 +1597,7 @@ PciHostBridgeEnumerator ( Status = PciResAlloc->StartBusEnumeration ( PciResAlloc, RootBridgeHandle, - (VOID **) &Configuration + (VOID **)&Configuration ); if (EFI_ERROR (Status)) { return Status; @@ -1583,12 +1606,12 @@ PciHostBridgeEnumerator ( // // Get the bus number to start with // - StartBusNumber = (UINT8) (Configuration->AddrRangeMin); + StartBusNumber = (UINT8)(Configuration->AddrRangeMin); ResetAllPpbBusNumber ( RootBridgeDev, StartBusNumber - ); + ); FreePool (Configuration); Link = RemoveEntryList (Link); @@ -1614,10 +1637,9 @@ PciHostBridgeEnumerator ( return Status; } - DEBUG((DEBUG_INFO, "PCI Bus Second Scanning\n")); + DEBUG ((DEBUG_INFO, "PCI Bus Second Scanning\n")); RootBridgeHandle = NULL; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { - // // if a root bridge instance is found, create root bridge device for it // @@ -1631,9 +1653,9 @@ PciHostBridgeEnumerator ( // Enumerate all the buses under this root bridge // Status = PciRootBridgeEnumerator ( - PciResAlloc, - RootBridgeDev - ); + PciResAlloc, + RootBridgeDev + ); DestroyRootBridge (RootBridgeDev); if (EFI_ERROR (Status)) { @@ -1658,7 +1680,6 @@ PciHostBridgeEnumerator ( RootBridgeHandle = NULL; while (PciResAlloc->GetNextRootBridge (PciResAlloc, &RootBridgeHandle) == EFI_SUCCESS) { - // // if a root bridge instance is found, create root bridge device for it // @@ -1675,7 +1696,7 @@ PciHostBridgeEnumerator ( } PciRootBridgeIo = RootBridgeDev->PciRootBridgeIo; - Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **) &Descriptors); + Status = PciRootBridgeIo->Configuration (PciRootBridgeIo, (VOID **)&Descriptors); if (EFI_ERROR (Status)) { return Status; @@ -1702,9 +1723,9 @@ PciHostBridgeEnumerator ( // root bridge will then be created // Status = PciPciDeviceInfoCollector ( - RootBridgeDev, - (UINT8) MinBus - ); + RootBridgeDev, + (UINT8)MinBus + ); if (EFI_ERROR (Status)) { return Status; @@ -1738,33 +1759,36 @@ PciProgramResizableBar ( IN PCI_RESIZABLE_BAR_OPERATION ResizableBarOp ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Capabilities; - UINT32 Index; - UINT32 Offset; - INTN Bit; - UINTN ResizableBarNumber; - EFI_STATUS Status; - PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY Entries[PCI_MAX_BAR]; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Capabilities; + UINT32 Index; + UINT32 Offset; + INTN Bit; + UINTN ResizableBarNumber; + EFI_STATUS Status; + PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY Entries[PCI_MAX_BAR]; ASSERT (PciIoDevice->ResizableBarOffset != 0); - DEBUG ((DEBUG_INFO, " Programs Resizable BAR register, offset: 0x%08x, number: %d\n", - PciIoDevice->ResizableBarOffset, PciIoDevice->ResizableBarNumber)); + DEBUG (( + DEBUG_INFO, + " Programs Resizable BAR register, offset: 0x%08x, number: %d\n", + PciIoDevice->ResizableBarOffset, + PciIoDevice->ResizableBarNumber + )); ResizableBarNumber = MIN (PciIoDevice->ResizableBarNumber, PCI_MAX_BAR); - PciIo = &PciIoDevice->PciIo; - Status = PciIo->Pci.Read ( - PciIo, - EfiPciIoWidthUint8, - PciIoDevice->ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER), - sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) * ResizableBarNumber, - (VOID *)(&Entries) - ); + PciIo = &PciIoDevice->PciIo; + Status = PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint8, + PciIoDevice->ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER), + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) * ResizableBarNumber, + (VOID *)(&Entries) + ); ASSERT_EFI_ERROR (Status); for (Index = 0; Index < ResizableBarNumber; Index++) { - // // When the bit of Capabilities Set, indicates that the Function supports // operating with the BAR sized to (2^Bit) MB. @@ -1773,36 +1797,37 @@ PciProgramResizableBar ( // Bit 1 is set: supports operating with the BAR sized to 2 MB // Bit n is set: supports operating with the BAR sized to (2^n) MB // - Capabilities = LShiftU64(Entries[Index].ResizableBarControl.Bits.BarSizeCapability, 28) - | Entries[Index].ResizableBarCapability.Bits.BarSizeCapability; + Capabilities = LShiftU64 (Entries[Index].ResizableBarControl.Bits.BarSizeCapability, 28) + | Entries[Index].ResizableBarCapability.Bits.BarSizeCapability; if (ResizableBarOp == PciResizableBarMax) { - Bit = HighBitSet64(Capabilities); + Bit = HighBitSet64 (Capabilities); } else { ASSERT (ResizableBarOp == PciResizableBarMin); - Bit = LowBitSet64(Capabilities); + Bit = LowBitSet64 (Capabilities); } ASSERT (Bit >= 0); Offset = PciIoDevice->ResizableBarOffset + sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_HEADER) - + Index * sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) - + OFFSET_OF (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY, ResizableBarControl); + + Index * sizeof (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY) + + OFFSET_OF (PCI_EXPRESS_EXTENDED_CAPABILITIES_RESIZABLE_BAR_ENTRY, ResizableBarControl); - Entries[Index].ResizableBarControl.Bits.BarSize = (UINT32) Bit; + Entries[Index].ResizableBarControl.Bits.BarSize = (UINT32)Bit; DEBUG (( DEBUG_INFO, " Resizable Bar: Offset = 0x%x, Bar Size Capability = 0x%016lx, New Bar Size = 0x%lx\n", OFFSET_OF (PCI_TYPE00, Device.Bar[Entries[Index].ResizableBarControl.Bits.BarIndex]), - Capabilities, LShiftU64 (SIZE_1MB, Bit) + Capabilities, + LShiftU64 (SIZE_1MB, Bit) )); PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - Offset, - 1, - &Entries[Index].ResizableBarControl.Uint32 - ); + PciIo, + EfiPciIoWidthUint32, + Offset, + 1, + &Entries[Index].ResizableBarControl.Uint32 + ); } return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h index aeec6d6b6d..5d2551148b 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.h @@ -9,19 +9,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_PCI_LIB_H_ #define _EFI_PCI_LIB_H_ - typedef struct { - EFI_HANDLE Handle; + EFI_HANDLE Handle; } EFI_DEVICE_HANDLE_EXTENDED_DATA_PAYLOAD; typedef struct { - UINT32 Bar; - UINT16 DevicePathSize; - UINT16 ReqResSize; - UINT16 AllocResSize; - UINT8 *DevicePath; - UINT8 *ReqRes; - UINT8 *AllocRes; + UINT32 Bar; + UINT16 DevicePathSize; + UINT16 ReqResSize; + UINT16 AllocResSize; + UINT8 *DevicePath; + UINT8 *ReqRes; + UINT8 *AllocRes; } EFI_RESOURCE_ALLOC_FAILURE_ERROR_DATA_PAYLOAD; typedef enum { @@ -37,7 +36,7 @@ typedef enum { **/ VOID GetBackPcCardBar ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -50,8 +49,8 @@ GetBackPcCardBar ( **/ VOID RemoveRejectedPciDevices ( - IN EFI_HANDLE RootBridgeHandle, - IN PCI_IO_DEVICE *Bridge + IN EFI_HANDLE RootBridgeHandle, + IN PCI_IO_DEVICE *Bridge ); /** @@ -69,7 +68,7 @@ RemoveRejectedPciDevices ( **/ EFI_STATUS PciHostBridgeResourceAllocator ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** @@ -87,10 +86,10 @@ PciHostBridgeResourceAllocator ( **/ EFI_STATUS PciAllocateBusNumber ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - IN UINT8 NumberOfBuses, - OUT UINT8 *NextBusNumber + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + IN UINT8 NumberOfBuses, + OUT UINT8 *NextBusNumber ); /** @@ -109,10 +108,10 @@ PciAllocateBusNumber ( **/ EFI_STATUS PciScanBus ( - IN PCI_IO_DEVICE *Bridge, - IN UINT8 StartBusNumber, - OUT UINT8 *SubBusNumber, - OUT UINT8 *PaddedBusRange + IN PCI_IO_DEVICE *Bridge, + IN UINT8 StartBusNumber, + OUT UINT8 *SubBusNumber, + OUT UINT8 *PaddedBusRange ); /** @@ -126,7 +125,7 @@ PciScanBus ( **/ EFI_STATUS PciRootBridgeP2CProcess ( - IN PCI_IO_DEVICE *Bridge + IN PCI_IO_DEVICE *Bridge ); /** @@ -141,7 +140,7 @@ PciRootBridgeP2CProcess ( **/ EFI_STATUS PciHostBridgeP2CProcess ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *PciResAlloc ); /** @@ -176,4 +175,5 @@ PciProgramResizableBar ( IN PCI_IO_DEVICE *PciIoDevice, IN PCI_RESIZABLE_BAR_OPERATION ResizableBarOp ); + #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c index a981f93f43..89f5f64101 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c @@ -30,26 +30,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS LocalLoadFile2 ( - IN PCI_IO_DEVICE *PciIoDevice, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN OUT UINTN *BufferSize, - IN VOID *Buffer OPTIONAL + IN PCI_IO_DEVICE *PciIoDevice, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN OUT UINTN *BufferSize, + IN VOID *Buffer OPTIONAL ) { - EFI_STATUS Status; - MEDIA_RELATIVE_OFFSET_RANGE_DEVICE_PATH *EfiOpRomImageNode; - EFI_PCI_EXPANSION_ROM_HEADER *EfiRomHeader; - PCI_DATA_STRUCTURE *Pcir; - UINT32 ImageSize; - UINT8 *ImageBuffer; - UINT32 ImageLength; - UINT32 DestinationSize; - UINT32 ScratchSize; - VOID *Scratch; - EFI_DECOMPRESS_PROTOCOL *Decompress; - UINT32 InitializationSize; - - EfiOpRomImageNode = (MEDIA_RELATIVE_OFFSET_RANGE_DEVICE_PATH *) FilePath; + EFI_STATUS Status; + MEDIA_RELATIVE_OFFSET_RANGE_DEVICE_PATH *EfiOpRomImageNode; + EFI_PCI_EXPANSION_ROM_HEADER *EfiRomHeader; + PCI_DATA_STRUCTURE *Pcir; + UINT32 ImageSize; + UINT8 *ImageBuffer; + UINT32 ImageLength; + UINT32 DestinationSize; + UINT32 ScratchSize; + VOID *Scratch; + EFI_DECOMPRESS_PROTOCOL *Decompress; + UINT32 InitializationSize; + + EfiOpRomImageNode = (MEDIA_RELATIVE_OFFSET_RANGE_DEVICE_PATH *)FilePath; if ((EfiOpRomImageNode == NULL) || (DevicePathType (FilePath) != MEDIA_DEVICE_PATH) || (DevicePathSubType (FilePath) != MEDIA_RELATIVE_OFFSET_RANGE_DP) || @@ -58,19 +58,19 @@ LocalLoadFile2 ( (EfiOpRomImageNode->StartingOffset > EfiOpRomImageNode->EndingOffset) || (EfiOpRomImageNode->EndingOffset >= PciIoDevice->RomSize) || (BufferSize == NULL) - ) { + ) + { return EFI_INVALID_PARAMETER; } - EfiRomHeader = (EFI_PCI_EXPANSION_ROM_HEADER *) ( - (UINT8 *) PciIoDevice->PciIo.RomImage + EfiOpRomImageNode->StartingOffset - ); + EfiRomHeader = (EFI_PCI_EXPANSION_ROM_HEADER *)( + (UINT8 *)PciIoDevice->PciIo.RomImage + EfiOpRomImageNode->StartingOffset + ); if (EfiRomHeader->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) { return EFI_NOT_FOUND; } - - Pcir = (PCI_DATA_STRUCTURE *) ((UINT8 *) EfiRomHeader + EfiRomHeader->PcirOffset); + Pcir = (PCI_DATA_STRUCTURE *)((UINT8 *)EfiRomHeader + EfiRomHeader->PcirOffset); ASSERT (Pcir->Signature == PCI_DATA_STRUCTURE_SIGNATURE); if ((Pcir->CodeType == PCI_CODE_TYPE_EFI_IMAGE) && @@ -78,22 +78,22 @@ LocalLoadFile2 ( ((EfiRomHeader->EfiSubsystem == EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER) || (EfiRomHeader->EfiSubsystem == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)) && (EfiRomHeader->CompressionType <= EFI_PCI_EXPANSION_ROM_HEADER_COMPRESSED) - ) { - - ImageSize = Pcir->ImageLength * 512; - InitializationSize = (UINT32) EfiRomHeader->InitializationSize * 512; - if (InitializationSize > ImageSize || EfiRomHeader->EfiImageHeaderOffset >= InitializationSize) { + ) + { + ImageSize = Pcir->ImageLength * 512; + InitializationSize = (UINT32)EfiRomHeader->InitializationSize * 512; + if ((InitializationSize > ImageSize) || (EfiRomHeader->EfiImageHeaderOffset >= InitializationSize)) { return EFI_NOT_FOUND; } - ImageBuffer = (UINT8 *) EfiRomHeader + EfiRomHeader->EfiImageHeaderOffset; - ImageLength = InitializationSize - EfiRomHeader->EfiImageHeaderOffset; + ImageBuffer = (UINT8 *)EfiRomHeader + EfiRomHeader->EfiImageHeaderOffset; + ImageLength = InitializationSize - EfiRomHeader->EfiImageHeaderOffset; if (EfiRomHeader->CompressionType != EFI_PCI_EXPANSION_ROM_HEADER_COMPRESSED) { // // Uncompressed: Copy the EFI Image directly to user's buffer // - if (Buffer == NULL || *BufferSize < ImageLength) { + if ((Buffer == NULL) || (*BufferSize < ImageLength)) { *BufferSize = ImageLength; return EFI_BUFFER_TOO_SMALL; } @@ -101,15 +101,15 @@ LocalLoadFile2 ( *BufferSize = ImageLength; CopyMem (Buffer, ImageBuffer, ImageLength); return EFI_SUCCESS; - } else { // // Compressed: Uncompress before copying // - Status = gBS->LocateProtocol (&gEfiDecompressProtocolGuid, NULL, (VOID **) &Decompress); + Status = gBS->LocateProtocol (&gEfiDecompressProtocolGuid, NULL, (VOID **)&Decompress); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } + Status = Decompress->GetInfo ( Decompress, ImageBuffer, @@ -121,13 +121,13 @@ LocalLoadFile2 ( return EFI_DEVICE_ERROR; } - if (Buffer == NULL || *BufferSize < DestinationSize) { + if ((Buffer == NULL) || (*BufferSize < DestinationSize)) { *BufferSize = DestinationSize; return EFI_BUFFER_TOO_SMALL; } *BufferSize = DestinationSize; - Scratch = AllocatePool (ScratchSize); + Scratch = AllocatePool (ScratchSize); if (Scratch == NULL) { return EFI_DEVICE_ERROR; } @@ -146,6 +146,7 @@ LocalLoadFile2 ( if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } + return EFI_SUCCESS; } } @@ -161,7 +162,7 @@ LocalLoadFile2 ( **/ VOID InitializePciLoadFile2 ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { PciIoDevice->LoadFile2.LoadFile = LoadFile2; @@ -193,18 +194,19 @@ InitializePciLoadFile2 ( EFI_STATUS EFIAPI LoadFile2 ( - IN EFI_LOAD_FILE2_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN BOOLEAN BootPolicy, - IN OUT UINTN *BufferSize, - IN VOID *Buffer OPTIONAL + IN EFI_LOAD_FILE2_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN BOOLEAN BootPolicy, + IN OUT UINTN *BufferSize, + IN VOID *Buffer OPTIONAL ) { - PCI_IO_DEVICE *PciIoDevice; + PCI_IO_DEVICE *PciIoDevice; if (BootPolicy) { return EFI_UNSUPPORTED; } + PciIoDevice = PCI_IO_DEVICE_FROM_LOAD_FILE2_THIS (This); return LocalLoadFile2 ( @@ -227,21 +229,21 @@ LoadFile2 ( **/ EFI_STATUS GetOpRomInfo ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ) { - UINT8 RomBarIndex; - UINT32 AllOnes; - UINT64 Address; - EFI_STATUS Status; - UINT8 Bus; - UINT8 Device; - UINT8 Function; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - - Bus = PciIoDevice->BusNumber; - Device = PciIoDevice->DeviceNumber; - Function = PciIoDevice->FunctionNumber; + UINT8 RomBarIndex; + UINT32 AllOnes; + UINT64 Address; + EFI_STATUS Status; + UINT8 Bus; + UINT8 Device; + UINT8 Function; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + + Bus = PciIoDevice->BusNumber; + Device = PciIoDevice->DeviceNumber; + Function = PciIoDevice->FunctionNumber; PciRootBridgeIo = PciIoDevice->PciRootBridgeIo; @@ -260,6 +262,7 @@ GetOpRomInfo ( // RomBarIndex = PCI_BRIDGE_ROMBAR; } + // // The bit0 is 0 to prevent the enabling of the Rom address decoder // @@ -280,7 +283,7 @@ GetOpRomInfo ( // // Read back // - Status = PciRootBridgeIo->Pci.Read( + Status = PciRootBridgeIo->Pci.Read ( PciRootBridgeIo, EfiPciWidthUint32, Address, @@ -315,8 +318,8 @@ GetOpRomInfo ( **/ BOOLEAN ContainEfiImage ( - IN VOID *RomImage, - IN UINT64 RomSize + IN VOID *RomImage, + IN UINT64 RomSize ) { PCI_EXPANSION_ROM_HEADER *RomHeader; @@ -331,20 +334,21 @@ ContainEfiImage ( do { if (RomHeader->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) { - RomHeader = (PCI_EXPANSION_ROM_HEADER *) ((UINT8 *) RomHeader + 512); + RomHeader = (PCI_EXPANSION_ROM_HEADER *)((UINT8 *)RomHeader + 512); continue; } // // The PCI Data Structure must be DWORD aligned. // - if (RomHeader->PcirOffset == 0 || - (RomHeader->PcirOffset & 3) != 0 || - (UINT8 *) RomHeader + RomHeader->PcirOffset + sizeof (PCI_DATA_STRUCTURE) > (UINT8 *) RomImage + RomSize) { + if ((RomHeader->PcirOffset == 0) || + ((RomHeader->PcirOffset & 3) != 0) || + ((UINT8 *)RomHeader + RomHeader->PcirOffset + sizeof (PCI_DATA_STRUCTURE) > (UINT8 *)RomImage + RomSize)) + { break; } - RomPcir = (PCI_DATA_STRUCTURE *) ((UINT8 *) RomHeader + RomHeader->PcirOffset); + RomPcir = (PCI_DATA_STRUCTURE *)((UINT8 *)RomHeader + RomHeader->PcirOffset); if (RomPcir->Signature != PCI_DATA_STRUCTURE_SIGNATURE) { break; } @@ -354,8 +358,8 @@ ContainEfiImage ( } Indicator = RomPcir->Indicator; - RomHeader = (PCI_EXPANSION_ROM_HEADER *) ((UINT8 *) RomHeader + RomPcir->ImageLength * 512); - } while (((UINT8 *) RomHeader < (UINT8 *) RomImage + RomSize) && ((Indicator & 0x80) == 0x00)); + RomHeader = (PCI_EXPANSION_ROM_HEADER *)((UINT8 *)RomHeader + RomPcir->ImageLength * 512); + } while (((UINT8 *)RomHeader < (UINT8 *)RomImage + RomSize) && ((Indicator & 0x80) == 0x00)); return FALSE; } @@ -372,8 +376,8 @@ ContainEfiImage ( **/ EFI_STATUS LoadOpRomImage ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT64 RomBase + IN PCI_IO_DEVICE *PciDevice, + IN UINT64 RomBase ) { UINT8 RomBarIndex; @@ -392,12 +396,12 @@ LoadOpRomImage ( UINT8 *RomInMemory; UINT8 CodeType; - RomSize = PciDevice->RomSize; + RomSize = PciDevice->RomSize; - Indicator = 0; - RomImageSize = 0; - RomInMemory = NULL; - CodeType = 0xFF; + Indicator = 0; + RomImageSize = 0; + RomInMemory = NULL; + CodeType = 0xFF; // // Get the RomBarIndex @@ -417,6 +421,7 @@ LoadOpRomImage ( // RomBarIndex = PCI_BRIDGE_ROMBAR; } + // // Allocate memory for Rom header and PCIR // @@ -431,16 +436,16 @@ LoadOpRomImage ( return EFI_OUT_OF_RESOURCES; } - RomBar = (UINT32) RomBase; + RomBar = (UINT32)RomBase; // // Enable RomBar // RomDecode (PciDevice, RomBarIndex, RomBar, TRUE); - RomBarOffset = RomBar; - RetStatus = EFI_NOT_FOUND; - FirstCheck = TRUE; + RomBarOffset = RomBar; + RetStatus = EFI_NOT_FOUND; + FirstCheck = TRUE; LegacyImageLength = 0; do { @@ -449,7 +454,7 @@ LoadOpRomImage ( EfiPciWidthUint8, RomBarOffset, sizeof (PCI_EXPANSION_ROM_HEADER), - (UINT8 *) RomHeader + (UINT8 *)RomHeader ); if (RomHeader->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) { @@ -462,23 +467,25 @@ LoadOpRomImage ( } } - FirstCheck = FALSE; - OffsetPcir = RomHeader->PcirOffset; + FirstCheck = FALSE; + OffsetPcir = RomHeader->PcirOffset; // // If the pointer to the PCI Data Structure is invalid, no further images can be located. // The PCI Data Structure must be DWORD aligned. // - if (OffsetPcir == 0 || - (OffsetPcir & 3) != 0 || - RomImageSize + OffsetPcir + sizeof (PCI_DATA_STRUCTURE) > RomSize) { + if ((OffsetPcir == 0) || + ((OffsetPcir & 3) != 0) || + (RomImageSize + OffsetPcir + sizeof (PCI_DATA_STRUCTURE) > RomSize)) + { break; } + PciDevice->PciRootBridgeIo->Mem.Read ( PciDevice->PciRootBridgeIo, EfiPciWidthUint8, RomBarOffset + OffsetPcir, sizeof (PCI_DATA_STRUCTURE), - (UINT8 *) RomPcir + (UINT8 *)RomPcir ); // // If a valid signature is not present in the PCI Data Structure, no further images can be located. @@ -486,16 +493,19 @@ LoadOpRomImage ( if (RomPcir->Signature != PCI_DATA_STRUCTURE_SIGNATURE) { break; } + if (RomImageSize + RomPcir->ImageLength * 512 > RomSize) { break; } + if (RomPcir->CodeType == PCI_CODE_TYPE_PCAT_IMAGE) { - CodeType = PCI_CODE_TYPE_PCAT_IMAGE; + CodeType = PCI_CODE_TYPE_PCAT_IMAGE; LegacyImageLength = ((UINT32)((EFI_LEGACY_EXPANSION_ROM_HEADER *)RomHeader)->Size512) * 512; } - Indicator = RomPcir->Indicator; - RomImageSize = RomImageSize + RomPcir->ImageLength * 512; - RomBarOffset = RomBarOffset + RomPcir->ImageLength * 512; + + Indicator = RomPcir->Indicator; + RomImageSize = RomImageSize + RomPcir->ImageLength * 512; + RomBarOffset = RomBarOffset + RomPcir->ImageLength * 512; } while (((Indicator & 0x80) == 0x00) && ((RomBarOffset - RomBar) < RomSize)); // @@ -508,7 +518,7 @@ LoadOpRomImage ( if (RomImageSize > 0) { RetStatus = EFI_SUCCESS; - Image = AllocatePool ((UINT32) RomImageSize); + Image = AllocatePool ((UINT32)RomImageSize); if (Image == NULL) { RomDecode (PciDevice, RomBarIndex, RomBar, FALSE); FreePool (RomHeader); @@ -523,7 +533,7 @@ LoadOpRomImage ( PciDevice->PciRootBridgeIo, EfiPciWidthUint32, RomBar, - (UINT32) RomImageSize/sizeof(UINT32), + (UINT32)RomImageSize/sizeof (UINT32), Image ); RomInMemory = Image; @@ -570,18 +580,17 @@ LoadOpRomImage ( **/ VOID RomDecode ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT8 RomBarIndex, - IN UINT32 RomBar, - IN BOOLEAN Enable + IN PCI_IO_DEVICE *PciDevice, + IN UINT8 RomBarIndex, + IN UINT32 RomBar, + IN BOOLEAN Enable ) { - UINT32 Value32; - EFI_PCI_IO_PROTOCOL *PciIo; + UINT32 Value32; + EFI_PCI_IO_PROTOCOL *PciIo; PciIo = &PciDevice->PciIo; if (Enable) { - // // set the Rom base address: now is hardcode // enable its decoder @@ -589,7 +598,7 @@ RomDecode ( Value32 = RomBar | 0x1; PciIo->Pci.Write ( PciIo, - (EFI_PCI_IO_PROTOCOL_WIDTH) EfiPciWidthUint32, + (EFI_PCI_IO_PROTOCOL_WIDTH)EfiPciWidthUint32, RomBarIndex, 1, &Value32 @@ -603,14 +612,12 @@ RomDecode ( // // Setting the memory space bit in the function's command register // - PCI_ENABLE_COMMAND_REGISTER(PciDevice, EFI_PCI_COMMAND_MEMORY_SPACE); - + PCI_ENABLE_COMMAND_REGISTER (PciDevice, EFI_PCI_COMMAND_MEMORY_SPACE); } else { - // // disable command register decode to memory // - PCI_DISABLE_COMMAND_REGISTER(PciDevice, EFI_PCI_COMMAND_MEMORY_SPACE); + PCI_DISABLE_COMMAND_REGISTER (PciDevice, EFI_PCI_COMMAND_MEMORY_SPACE); // // Destroy the programmed bar in all the upstream bridge. @@ -623,12 +630,11 @@ RomDecode ( Value32 = 0xFFFFFFFE; PciIo->Pci.Write ( PciIo, - (EFI_PCI_IO_PROTOCOL_WIDTH) EfiPciWidthUint32, + (EFI_PCI_IO_PROTOCOL_WIDTH)EfiPciWidthUint32, RomBarIndex, 1, &Value32 ); - } } @@ -643,7 +649,7 @@ RomDecode ( **/ EFI_STATUS ProcessOpRomImage ( - IN PCI_IO_DEVICE *PciDevice + IN PCI_IO_DEVICE *PciDevice ) { UINT8 Indicator; @@ -665,26 +671,27 @@ ProcessOpRomImage ( // // Get the Address of the Option Rom image // - RomBar = PciDevice->PciIo.RomImage; - RomBarOffset = (UINT8 *) RomBar; - RetStatus = EFI_NOT_FOUND; + RomBar = PciDevice->PciIo.RomImage; + RomBarOffset = (UINT8 *)RomBar; + RetStatus = EFI_NOT_FOUND; if (RomBar == NULL) { return RetStatus; } - ASSERT (((EFI_PCI_EXPANSION_ROM_HEADER *) RomBarOffset)->Signature == PCI_EXPANSION_ROM_HEADER_SIGNATURE); + + ASSERT (((EFI_PCI_EXPANSION_ROM_HEADER *)RomBarOffset)->Signature == PCI_EXPANSION_ROM_HEADER_SIGNATURE); do { - EfiRomHeader = (EFI_PCI_EXPANSION_ROM_HEADER *) RomBarOffset; + EfiRomHeader = (EFI_PCI_EXPANSION_ROM_HEADER *)RomBarOffset; if (EfiRomHeader->Signature != PCI_EXPANSION_ROM_HEADER_SIGNATURE) { RomBarOffset += 512; continue; } - Pcir = (PCI_DATA_STRUCTURE *) (RomBarOffset + EfiRomHeader->PcirOffset); + Pcir = (PCI_DATA_STRUCTURE *)(RomBarOffset + EfiRomHeader->PcirOffset); ASSERT (Pcir->Signature == PCI_DATA_STRUCTURE_SIGNATURE); - ImageSize = (UINT32) (Pcir->ImageLength * 512); - Indicator = Pcir->Indicator; + ImageSize = (UINT32)(Pcir->ImageLength * 512); + Indicator = Pcir->Indicator; // // Skip the image if it is not an EFI PCI Option ROM image @@ -703,11 +710,11 @@ ProcessOpRomImage ( // // Create Pci Option Rom Image device path header // - EfiOpRomImageNode.Header.Type = MEDIA_DEVICE_PATH; - EfiOpRomImageNode.Header.SubType = MEDIA_RELATIVE_OFFSET_RANGE_DP; + EfiOpRomImageNode.Header.Type = MEDIA_DEVICE_PATH; + EfiOpRomImageNode.Header.SubType = MEDIA_RELATIVE_OFFSET_RANGE_DP; SetDevicePathNodeLength (&EfiOpRomImageNode.Header, sizeof (EfiOpRomImageNode)); - EfiOpRomImageNode.StartingOffset = (UINTN) RomBarOffset - (UINTN) RomBar; - EfiOpRomImageNode.EndingOffset = (UINTN) RomBarOffset + ImageSize - 1 - (UINTN) RomBar; + EfiOpRomImageNode.StartingOffset = (UINTN)RomBarOffset - (UINTN)RomBar; + EfiOpRomImageNode.EndingOffset = (UINTN)RomBarOffset + ImageSize - 1 - (UINTN)RomBar; PciOptionRomImageDevicePath = AppendDevicePathNode (PciDevice->DevicePath, &EfiOpRomImageNode.Header); ASSERT (PciOptionRomImageDevicePath != NULL); @@ -752,13 +759,12 @@ ProcessOpRomImage ( RetStatus = EFI_SUCCESS; } } + FreePool (PciOptionRomImageDevicePath); NextImage: RomBarOffset += ImageSize; - - } while (((Indicator & 0x80) == 0x00) && (((UINTN) RomBarOffset - (UINTN) RomBar) < PciDevice->RomSize)); + } while (((Indicator & 0x80) == 0x00) && (((UINTN)RomBarOffset - (UINTN)RomBar) < PciDevice->RomSize)); return RetStatus; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.h index 5c4e9fa3b6..16998a422e 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_PCI_OPTION_ROM_SUPPORT_H_ #define _EFI_PCI_OPTION_ROM_SUPPORT_H_ - /** Initialize a PCI LoadFile2 instance. @@ -18,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID InitializePciLoadFile2 ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); /** @@ -47,11 +46,11 @@ InitializePciLoadFile2 ( EFI_STATUS EFIAPI LoadFile2 ( - IN EFI_LOAD_FILE2_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN BOOLEAN BootPolicy, - IN OUT UINTN *BufferSize, - IN VOID *Buffer OPTIONAL + IN EFI_LOAD_FILE2_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN BOOLEAN BootPolicy, + IN OUT UINTN *BufferSize, + IN VOID *Buffer OPTIONAL ); /** @@ -66,8 +65,8 @@ LoadFile2 ( **/ BOOLEAN ContainEfiImage ( - IN VOID *RomImage, - IN UINT64 RomSize + IN VOID *RomImage, + IN UINT64 RomSize ); /** @@ -82,7 +81,7 @@ ContainEfiImage ( **/ EFI_STATUS GetOpRomInfo ( - IN OUT PCI_IO_DEVICE *PciIoDevice + IN OUT PCI_IO_DEVICE *PciIoDevice ); /** @@ -97,8 +96,8 @@ GetOpRomInfo ( **/ EFI_STATUS LoadOpRomImage ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT64 RomBase + IN PCI_IO_DEVICE *PciDevice, + IN UINT64 RomBase ); /** @@ -113,10 +112,10 @@ LoadOpRomImage ( **/ VOID RomDecode ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT8 RomBarIndex, - IN UINT32 RomBar, - IN BOOLEAN Enable + IN PCI_IO_DEVICE *PciDevice, + IN UINT8 RomBarIndex, + IN UINT32 RomBar, + IN BOOLEAN Enable ); /** @@ -130,7 +129,7 @@ RomDecode ( **/ EFI_STATUS ProcessOpRomImage ( - IN PCI_IO_DEVICE *PciDevice + IN PCI_IO_DEVICE *PciDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.c index c7f3ea5099..ce23964e50 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.c @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS ResetPowerManagementFeature ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { EFI_STATUS Status; @@ -31,11 +31,11 @@ ResetPowerManagementFeature ( PowerManagementRegBlock = 0; Status = LocateCapabilityRegBlock ( - PciIoDevice, - EFI_PCI_CAPABILITY_ID_PMI, - &PowerManagementRegBlock, - NULL - ); + PciIoDevice, + EFI_PCI_CAPABILITY_ID_PMI, + &PowerManagementRegBlock, + NULL + ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; @@ -77,6 +77,6 @@ ResetPowerManagementFeature ( &PowerManagementCSR ); } + return Status; } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.h index b5018dcf11..d11a8fdc68 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciPowerManagement.h @@ -22,7 +22,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS ResetPowerManagementFeature ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.c index 4969ee0f64..8ffd05f327 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.c @@ -11,9 +11,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // The default policy for the PCI bus driver is NOT to reserve I/O ranges for both ISA aliases and VGA aliases. // -BOOLEAN mReserveIsaAliases = FALSE; -BOOLEAN mReserveVgaAliases = FALSE; -BOOLEAN mPolicyDetermined = FALSE; +BOOLEAN mReserveIsaAliases = FALSE; +BOOLEAN mReserveVgaAliases = FALSE; +BOOLEAN mPolicyDetermined = FALSE; /** The function is used to skip VGA range. @@ -24,8 +24,8 @@ BOOLEAN mPolicyDetermined = FALSE; **/ VOID SkipVGAAperture ( - OUT UINT64 *Start, - IN UINT64 Length + OUT UINT64 *Start, + IN UINT64 Length ) { UINT64 Original; @@ -37,7 +37,7 @@ SkipVGAAperture ( // // For legacy VGA, bit 10 to bit 15 is not decoded // - Mask = 0x3FF; + Mask = 0x3FF; Original = *Start; StartOffset = Original & Mask; @@ -56,11 +56,10 @@ SkipVGAAperture ( **/ VOID SkipIsaAliasAperture ( - OUT UINT64 *Start, - IN UINT64 Length + OUT UINT64 *Start, + IN UINT64 Length ) { - UINT64 Original; UINT64 Mask; UINT64 StartOffset; @@ -71,7 +70,7 @@ SkipIsaAliasAperture ( // // For legacy ISA, bit 10 to bit 15 is not decoded // - Mask = 0x3FF; + Mask = 0x3FF; Original = *Start; StartOffset = Original & Mask; @@ -92,14 +91,14 @@ SkipIsaAliasAperture ( **/ VOID InsertResourceNode ( - IN OUT PCI_RESOURCE_NODE *Bridge, - IN PCI_RESOURCE_NODE *ResNode + IN OUT PCI_RESOURCE_NODE *Bridge, + IN PCI_RESOURCE_NODE *ResNode ) { - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *Temp; - UINT64 ResNodeAlignRest; - UINT64 TempAlignRest; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Temp; + UINT64 ResNodeAlignRest; + UINT64 TempAlignRest; ASSERT (Bridge != NULL); ASSERT (ResNode != NULL); @@ -113,8 +112,8 @@ InsertResourceNode ( if (ResNode->Alignment > Temp->Alignment) { break; } else if (ResNode->Alignment == Temp->Alignment) { - ResNodeAlignRest = ResNode->Length & ResNode->Alignment; - TempAlignRest = Temp->Length & Temp->Alignment; + ResNodeAlignRest = ResNode->Length & ResNode->Alignment; + TempAlignRest = Temp->Length & Temp->Alignment; if ((ResNodeAlignRest == 0) || (ResNodeAlignRest >= TempAlignRest)) { break; } @@ -146,14 +145,13 @@ InsertResourceNode ( **/ VOID MergeResourceTree ( - IN PCI_RESOURCE_NODE *Dst, - IN PCI_RESOURCE_NODE *Res, - IN BOOLEAN TypeMerge + IN PCI_RESOURCE_NODE *Dst, + IN PCI_RESOURCE_NODE *Res, + IN BOOLEAN TypeMerge ) { - - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *Temp; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Temp; ASSERT (Dst != NULL); ASSERT (Res != NULL); @@ -161,7 +159,7 @@ MergeResourceTree ( while (!IsListEmpty (&Res->ChildList)) { CurrentLink = Res->ChildList.ForwardLink; - Temp = RESOURCE_NODE_FROM_LINK (CurrentLink); + Temp = RESOURCE_NODE_FROM_LINK (CurrentLink); if (TypeMerge) { Temp->ResType = Dst->ResType; @@ -181,22 +179,22 @@ MergeResourceTree ( **/ VOID CalculateApertureIo16 ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ) { - EFI_STATUS Status; - UINT64 Aperture; - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *Node; - UINT64 Offset; - EFI_PCI_PLATFORM_POLICY PciPolicy; - UINT64 PaddingAperture; + EFI_STATUS Status; + UINT64 Aperture; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Node; + UINT64 Offset; + EFI_PCI_PLATFORM_POLICY PciPolicy; + UINT64 PaddingAperture; if (!mPolicyDetermined) { // // Check PciPlatform policy // - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; PciPolicy = 0; if (gPciPlatformProtocol != NULL) { Status = gPciPlatformProtocol->GetPlatformPolicy ( @@ -205,7 +203,7 @@ CalculateApertureIo16 ( ); } - if (EFI_ERROR (Status) && gPciOverrideProtocol != NULL) { + if (EFI_ERROR (Status) && (gPciOverrideProtocol != NULL)) { Status = gPciOverrideProtocol->GetPlatformPolicy ( gPciOverrideProtocol, &PciPolicy @@ -216,10 +214,12 @@ CalculateApertureIo16 ( if ((PciPolicy & EFI_RESERVE_ISA_IO_ALIAS) != 0) { mReserveIsaAliases = TRUE; } + if ((PciPolicy & EFI_RESERVE_VGA_IO_ALIAS) != 0) { mReserveVgaAliases = TRUE; } } + mPolicyDetermined = TRUE; } @@ -227,32 +227,31 @@ CalculateApertureIo16 ( PaddingAperture = 0; if (Bridge == NULL) { - return ; + return; } // // Assume the bridge is aligned // for ( CurrentLink = GetFirstNode (&Bridge->ChildList) - ; !IsNull (&Bridge->ChildList, CurrentLink) - ; CurrentLink = GetNextNode (&Bridge->ChildList, CurrentLink) - ) { - + ; !IsNull (&Bridge->ChildList, CurrentLink) + ; CurrentLink = GetNextNode (&Bridge->ChildList, CurrentLink) + ) + { Node = RESOURCE_NODE_FROM_LINK (CurrentLink); if (Node->ResourceUsage == PciResUsagePadding) { ASSERT (PaddingAperture == 0); PaddingAperture = Node->Length; continue; } + // // Consider the aperture alignment // Offset = Aperture & (Node->Alignment); if (Offset != 0) { - Aperture = Aperture + (Node->Alignment + 1) - Offset; - } // @@ -334,21 +333,20 @@ CalculateApertureIo16 ( **/ VOID CalculateResourceAperture ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ) { - UINT64 Aperture[2]; - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *Node; + UINT64 Aperture[2]; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Node; if (Bridge == NULL) { - return ; + return; } if (Bridge->ResType == PciBarTypeIo16) { - CalculateApertureIo16 (Bridge); - return ; + return; } Aperture[PciResUsageTypical] = 0; @@ -357,17 +355,20 @@ CalculateResourceAperture ( // Assume the bridge is aligned // for ( CurrentLink = GetFirstNode (&Bridge->ChildList) - ; !IsNull (&Bridge->ChildList, CurrentLink) - ; CurrentLink = GetNextNode (&Bridge->ChildList, CurrentLink) - ) { + ; !IsNull (&Bridge->ChildList, CurrentLink) + ; CurrentLink = GetNextNode (&Bridge->ChildList, CurrentLink) + ) + { Node = RESOURCE_NODE_FROM_LINK (CurrentLink); // // It's possible for a bridge to contain multiple padding resource // nodes due to DegradeResource(). // - ASSERT ((Node->ResourceUsage == PciResUsageTypical) || - (Node->ResourceUsage == PciResUsagePadding)); + ASSERT ( + (Node->ResourceUsage == PciResUsageTypical) || + (Node->ResourceUsage == PciResUsagePadding) + ); ASSERT (Node->ResourceUsage < ARRAY_SIZE (Aperture)); // // Recode current aperture as a offset @@ -419,126 +420,123 @@ CalculateResourceAperture ( **/ VOID GetResourceFromDevice ( - IN PCI_IO_DEVICE *PciDev, - IN OUT PCI_RESOURCE_NODE *IoNode, - IN OUT PCI_RESOURCE_NODE *Mem32Node, - IN OUT PCI_RESOURCE_NODE *PMem32Node, - IN OUT PCI_RESOURCE_NODE *Mem64Node, - IN OUT PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN OUT PCI_RESOURCE_NODE *IoNode, + IN OUT PCI_RESOURCE_NODE *Mem32Node, + IN OUT PCI_RESOURCE_NODE *PMem32Node, + IN OUT PCI_RESOURCE_NODE *Mem64Node, + IN OUT PCI_RESOURCE_NODE *PMem64Node ) { - - UINT8 Index; - PCI_RESOURCE_NODE *Node; - BOOLEAN ResourceRequested; + UINT8 Index; + PCI_RESOURCE_NODE *Node; + BOOLEAN ResourceRequested; Node = NULL; ResourceRequested = FALSE; for (Index = 0; Index < PCI_MAX_BAR; Index++) { - switch ((PciDev->PciBar)[Index].BarType) { + case PciBarTypeMem32: + case PciBarTypeOpRom: - case PciBarTypeMem32: - case PciBarTypeOpRom: - - Node = CreateResourceNode ( - PciDev, - (PciDev->PciBar)[Index].Length, - (PciDev->PciBar)[Index].Alignment, - Index, - (PciDev->PciBar)[Index].BarType, - PciResUsageTypical - ); + Node = CreateResourceNode ( + PciDev, + (PciDev->PciBar)[Index].Length, + (PciDev->PciBar)[Index].Alignment, + Index, + (PciDev->PciBar)[Index].BarType, + PciResUsageTypical + ); - InsertResourceNode ( - Mem32Node, - Node - ); + InsertResourceNode ( + Mem32Node, + Node + ); - ResourceRequested = TRUE; - break; + ResourceRequested = TRUE; + break; - case PciBarTypeMem64: + case PciBarTypeMem64: - Node = CreateResourceNode ( - PciDev, - (PciDev->PciBar)[Index].Length, - (PciDev->PciBar)[Index].Alignment, - Index, - PciBarTypeMem64, - PciResUsageTypical - ); + Node = CreateResourceNode ( + PciDev, + (PciDev->PciBar)[Index].Length, + (PciDev->PciBar)[Index].Alignment, + Index, + PciBarTypeMem64, + PciResUsageTypical + ); - InsertResourceNode ( - Mem64Node, - Node - ); + InsertResourceNode ( + Mem64Node, + Node + ); - ResourceRequested = TRUE; - break; + ResourceRequested = TRUE; + break; - case PciBarTypePMem64: + case PciBarTypePMem64: - Node = CreateResourceNode ( - PciDev, - (PciDev->PciBar)[Index].Length, - (PciDev->PciBar)[Index].Alignment, - Index, - PciBarTypePMem64, - PciResUsageTypical - ); + Node = CreateResourceNode ( + PciDev, + (PciDev->PciBar)[Index].Length, + (PciDev->PciBar)[Index].Alignment, + Index, + PciBarTypePMem64, + PciResUsageTypical + ); - InsertResourceNode ( - PMem64Node, - Node - ); + InsertResourceNode ( + PMem64Node, + Node + ); - ResourceRequested = TRUE; - break; + ResourceRequested = TRUE; + break; - case PciBarTypePMem32: + case PciBarTypePMem32: - Node = CreateResourceNode ( - PciDev, - (PciDev->PciBar)[Index].Length, - (PciDev->PciBar)[Index].Alignment, - Index, - PciBarTypePMem32, - PciResUsageTypical - ); + Node = CreateResourceNode ( + PciDev, + (PciDev->PciBar)[Index].Length, + (PciDev->PciBar)[Index].Alignment, + Index, + PciBarTypePMem32, + PciResUsageTypical + ); - InsertResourceNode ( - PMem32Node, - Node - ); - ResourceRequested = TRUE; - break; + InsertResourceNode ( + PMem32Node, + Node + ); + ResourceRequested = TRUE; + break; - case PciBarTypeIo16: - case PciBarTypeIo32: + case PciBarTypeIo16: + case PciBarTypeIo32: - Node = CreateResourceNode ( - PciDev, - (PciDev->PciBar)[Index].Length, - (PciDev->PciBar)[Index].Alignment, - Index, - PciBarTypeIo16, - PciResUsageTypical - ); + Node = CreateResourceNode ( + PciDev, + (PciDev->PciBar)[Index].Length, + (PciDev->PciBar)[Index].Alignment, + Index, + PciBarTypeIo16, + PciResUsageTypical + ); - InsertResourceNode ( - IoNode, - Node - ); - ResourceRequested = TRUE; - break; + InsertResourceNode ( + IoNode, + Node + ); + ResourceRequested = TRUE; + break; - case PciBarTypeUnknown: - break; + case PciBarTypeUnknown: + break; - default: - break; + default: + break; } } @@ -546,91 +544,90 @@ GetResourceFromDevice ( // Add VF resource // for (Index = 0; Index < PCI_MAX_BAR; Index++) { - switch ((PciDev->VfPciBar)[Index].BarType) { + case PciBarTypeMem32: - case PciBarTypeMem32: - - Node = CreateVfResourceNode ( - PciDev, - (PciDev->VfPciBar)[Index].Length, - (PciDev->VfPciBar)[Index].Alignment, - Index, - PciBarTypeMem32, - PciResUsageTypical - ); + Node = CreateVfResourceNode ( + PciDev, + (PciDev->VfPciBar)[Index].Length, + (PciDev->VfPciBar)[Index].Alignment, + Index, + PciBarTypeMem32, + PciResUsageTypical + ); - InsertResourceNode ( - Mem32Node, - Node - ); + InsertResourceNode ( + Mem32Node, + Node + ); - break; + break; - case PciBarTypeMem64: + case PciBarTypeMem64: - Node = CreateVfResourceNode ( - PciDev, - (PciDev->VfPciBar)[Index].Length, - (PciDev->VfPciBar)[Index].Alignment, - Index, - PciBarTypeMem64, - PciResUsageTypical - ); + Node = CreateVfResourceNode ( + PciDev, + (PciDev->VfPciBar)[Index].Length, + (PciDev->VfPciBar)[Index].Alignment, + Index, + PciBarTypeMem64, + PciResUsageTypical + ); - InsertResourceNode ( - Mem64Node, - Node - ); + InsertResourceNode ( + Mem64Node, + Node + ); - break; + break; - case PciBarTypePMem64: + case PciBarTypePMem64: - Node = CreateVfResourceNode ( - PciDev, - (PciDev->VfPciBar)[Index].Length, - (PciDev->VfPciBar)[Index].Alignment, - Index, - PciBarTypePMem64, - PciResUsageTypical - ); + Node = CreateVfResourceNode ( + PciDev, + (PciDev->VfPciBar)[Index].Length, + (PciDev->VfPciBar)[Index].Alignment, + Index, + PciBarTypePMem64, + PciResUsageTypical + ); - InsertResourceNode ( - PMem64Node, - Node - ); + InsertResourceNode ( + PMem64Node, + Node + ); - break; + break; - case PciBarTypePMem32: + case PciBarTypePMem32: - Node = CreateVfResourceNode ( - PciDev, - (PciDev->VfPciBar)[Index].Length, - (PciDev->VfPciBar)[Index].Alignment, - Index, - PciBarTypePMem32, - PciResUsageTypical - ); + Node = CreateVfResourceNode ( + PciDev, + (PciDev->VfPciBar)[Index].Length, + (PciDev->VfPciBar)[Index].Alignment, + Index, + PciBarTypePMem32, + PciResUsageTypical + ); - InsertResourceNode ( - PMem32Node, - Node - ); - break; + InsertResourceNode ( + PMem32Node, + Node + ); + break; - case PciBarTypeIo16: - case PciBarTypeIo32: - break; + case PciBarTypeIo16: + case PciBarTypeIo32: + break; - case PciBarTypeUnknown: - break; + case PciBarTypeUnknown: + break; - default: - break; + default: + break; } } + // If there is no resource requested from this device, // then we indicate this device has been allocated naturally. // @@ -655,19 +652,19 @@ GetResourceFromDevice ( **/ PCI_RESOURCE_NODE * CreateResourceNode ( - IN PCI_IO_DEVICE *PciDev, - IN UINT64 Length, - IN UINT64 Alignment, - IN UINT8 Bar, - IN PCI_BAR_TYPE ResType, - IN PCI_RESOURCE_USAGE ResUsage + IN PCI_IO_DEVICE *PciDev, + IN UINT64 Length, + IN UINT64 Alignment, + IN UINT8 Bar, + IN PCI_BAR_TYPE ResType, + IN PCI_RESOURCE_USAGE ResUsage ) { - PCI_RESOURCE_NODE *Node; + PCI_RESOURCE_NODE *Node; - Node = NULL; + Node = NULL; - Node = AllocateZeroPool (sizeof (PCI_RESOURCE_NODE)); + Node = AllocateZeroPool (sizeof (PCI_RESOURCE_NODE)); ASSERT (Node != NULL); if (Node == NULL) { return NULL; @@ -702,15 +699,15 @@ CreateResourceNode ( **/ PCI_RESOURCE_NODE * CreateVfResourceNode ( - IN PCI_IO_DEVICE *PciDev, - IN UINT64 Length, - IN UINT64 Alignment, - IN UINT8 Bar, - IN PCI_BAR_TYPE ResType, - IN PCI_RESOURCE_USAGE ResUsage + IN PCI_IO_DEVICE *PciDev, + IN UINT64 Length, + IN UINT64 Alignment, + IN UINT8 Bar, + IN PCI_BAR_TYPE ResType, + IN PCI_RESOURCE_USAGE ResUsage ) { - PCI_RESOURCE_NODE *Node; + PCI_RESOURCE_NODE *Node; Node = CreateResourceNode (PciDev, Length, Alignment, Bar, ResType, ResUsage); if (Node == NULL) { @@ -736,26 +733,25 @@ CreateVfResourceNode ( **/ VOID CreateResourceMap ( - IN PCI_IO_DEVICE *Bridge, - IN OUT PCI_RESOURCE_NODE *IoNode, - IN OUT PCI_RESOURCE_NODE *Mem32Node, - IN OUT PCI_RESOURCE_NODE *PMem32Node, - IN OUT PCI_RESOURCE_NODE *Mem64Node, - IN OUT PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *Bridge, + IN OUT PCI_RESOURCE_NODE *IoNode, + IN OUT PCI_RESOURCE_NODE *Mem32Node, + IN OUT PCI_RESOURCE_NODE *PMem32Node, + IN OUT PCI_RESOURCE_NODE *Mem64Node, + IN OUT PCI_RESOURCE_NODE *PMem64Node ) { - PCI_IO_DEVICE *Temp; - PCI_RESOURCE_NODE *IoBridge; - PCI_RESOURCE_NODE *Mem32Bridge; - PCI_RESOURCE_NODE *PMem32Bridge; - PCI_RESOURCE_NODE *Mem64Bridge; - PCI_RESOURCE_NODE *PMem64Bridge; - LIST_ENTRY *CurrentLink; + PCI_IO_DEVICE *Temp; + PCI_RESOURCE_NODE *IoBridge; + PCI_RESOURCE_NODE *Mem32Bridge; + PCI_RESOURCE_NODE *PMem32Bridge; + PCI_RESOURCE_NODE *Mem64Bridge; + PCI_RESOURCE_NODE *PMem64Bridge; + LIST_ENTRY *CurrentLink; CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != NULL && CurrentLink != &Bridge->ChildList) { - Temp = PCI_IO_DEVICE_FROM_LINK (CurrentLink); // @@ -774,7 +770,6 @@ CreateResourceMap ( ); if (IS_PCI_BRIDGE (&Temp->Pci)) { - // // If the device has children, create a bridge resource node for this PPB // Note: For PPB, memory aperture is aligned with 1MB and IO aperture @@ -910,7 +905,6 @@ CreateResourceMap ( FreePool (PMem64Bridge); PMem64Bridge = NULL; } - } // @@ -976,12 +970,12 @@ CreateResourceMap ( **/ VOID ResourcePaddingPolicy ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ) { // @@ -1015,18 +1009,18 @@ ResourcePaddingPolicy ( **/ VOID DegradeResource ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *Bridge, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ) { - PCI_IO_DEVICE *PciIoDevice; - LIST_ENTRY *ChildDeviceLink; - LIST_ENTRY *ChildNodeLink; - LIST_ENTRY *NextChildNodeLink; - PCI_RESOURCE_NODE *ResourceNode; + PCI_IO_DEVICE *PciIoDevice; + LIST_ENTRY *ChildDeviceLink; + LIST_ENTRY *ChildNodeLink; + LIST_ENTRY *NextChildNodeLink; + PCI_RESOURCE_NODE *ResourceNode; if (FeaturePcdGet (PcdPciDegradeResourceForOptionRom)) { // @@ -1040,15 +1034,17 @@ DegradeResource ( if (!IsListEmpty (&Mem64Node->ChildList)) { ChildNodeLink = Mem64Node->ChildList.ForwardLink; while (ChildNodeLink != &Mem64Node->ChildList) { - ResourceNode = RESOURCE_NODE_FROM_LINK (ChildNodeLink); + ResourceNode = RESOURCE_NODE_FROM_LINK (ChildNodeLink); NextChildNodeLink = ChildNodeLink->ForwardLink; if ((ResourceNode->PciDev == PciIoDevice) && (ResourceNode->Virtual || !PciIoDevice->PciBar[ResourceNode->Bar].BarTypeFixed) - ) { + ) + { RemoveEntryList (ChildNodeLink); InsertResourceNode (Mem32Node, ResourceNode); } + ChildNodeLink = NextChildNodeLink; } } @@ -1056,20 +1052,22 @@ DegradeResource ( if (!IsListEmpty (&PMem64Node->ChildList)) { ChildNodeLink = PMem64Node->ChildList.ForwardLink; while (ChildNodeLink != &PMem64Node->ChildList) { - ResourceNode = RESOURCE_NODE_FROM_LINK (ChildNodeLink); + ResourceNode = RESOURCE_NODE_FROM_LINK (ChildNodeLink); NextChildNodeLink = ChildNodeLink->ForwardLink; if ((ResourceNode->PciDev == PciIoDevice) && (ResourceNode->Virtual || !PciIoDevice->PciBar[ResourceNode->Bar].BarTypeFixed) - ) { + ) + { RemoveEntryList (ChildNodeLink); InsertResourceNode (PMem32Node, ResourceNode); } + ChildNodeLink = NextChildNodeLink; } } - } + ChildDeviceLink = ChildDeviceLink->ForwardLink; } } @@ -1095,11 +1093,11 @@ DegradeResource ( // if the bridge does not support MEM64, degrade MEM64 to MEM32 // if (!BridgeSupportResourceDecode (Bridge, EFI_BRIDGE_MEM64_DECODE_SUPPORTED)) { - MergeResourceTree ( - Mem32Node, - Mem64Node, - TRUE - ); + MergeResourceTree ( + Mem32Node, + Mem64Node, + TRUE + ); } // @@ -1117,7 +1115,7 @@ DegradeResource ( // if both PMEM64 and PMEM32 requests from child devices, which can not be satisfied // by a P2P bridge simultaneously, keep PMEM64 and degrade PMEM32 to MEM32. // - if (!IsListEmpty (&PMem64Node->ChildList) && Bridge->Parent != NULL) { + if (!IsListEmpty (&PMem64Node->ChildList) && (Bridge->Parent != NULL)) { MergeResourceTree ( Mem32Node, PMem32Node, @@ -1174,8 +1172,8 @@ DegradeResource ( **/ BOOLEAN BridgeSupportResourceDecode ( - IN PCI_IO_DEVICE *Bridge, - IN UINT32 Decode + IN PCI_IO_DEVICE *Bridge, + IN UINT32 Decode ) { if (((Bridge->Decodes) & Decode) != 0) { @@ -1199,13 +1197,13 @@ BridgeSupportResourceDecode ( **/ EFI_STATUS ProgramResource ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Bridge + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Bridge ) { - LIST_ENTRY *CurrentLink; - PCI_RESOURCE_NODE *Node; - EFI_STATUS Status; + LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Node; + EFI_STATUS Status; if (Base == gAllOne) { return EFI_OUT_OF_RESOURCES; @@ -1214,11 +1212,9 @@ ProgramResource ( CurrentLink = Bridge->ChildList.ForwardLink; while (CurrentLink != &Bridge->ChildList) { - Node = RESOURCE_NODE_FROM_LINK (CurrentLink); if (!IS_PCI_BRIDGE (&(Node->PciDev->Pci))) { - if (IS_CARDBUS_BRIDGE (&(Node->PciDev->Pci))) { // // Program the PCI Card Bus device @@ -1257,13 +1253,13 @@ ProgramResource ( **/ VOID ProgramBar ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Address; - UINT32 Address32; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Address; + UINT32 Address32; ASSERT (Node->Bar < PCI_MAX_BAR); @@ -1289,59 +1285,58 @@ ProgramBar ( Node->PciDev->Allocated = TRUE; switch ((Node->PciDev->PciBar[Node->Bar]).BarType) { + case PciBarTypeIo16: + case PciBarTypeIo32: + case PciBarTypeMem32: + case PciBarTypePMem32: - case PciBarTypeIo16: - case PciBarTypeIo32: - case PciBarTypeMem32: - case PciBarTypePMem32: - - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->PciBar[Node->Bar]).Offset, - 1, - &Address - ); - // - // Continue to the case PciBarTypeOpRom to set the BaseAddress. - // PciBarTypeOpRom is a virtual BAR only in root bridge, to capture - // the MEM32 resource requirement for Option ROM shadow. - // + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->PciBar[Node->Bar]).Offset, + 1, + &Address + ); + // + // Continue to the case PciBarTypeOpRom to set the BaseAddress. + // PciBarTypeOpRom is a virtual BAR only in root bridge, to capture + // the MEM32 resource requirement for Option ROM shadow. + // - case PciBarTypeOpRom: - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + case PciBarTypeOpRom: + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - break; + break; - case PciBarTypeMem64: - case PciBarTypePMem64: + case PciBarTypeMem64: + case PciBarTypePMem64: - Address32 = (UINT32) (Address & 0x00000000FFFFFFFF); + Address32 = (UINT32)(Address & 0x00000000FFFFFFFF); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->PciBar[Node->Bar]).Offset, - 1, - &Address32 - ); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->PciBar[Node->Bar]).Offset, + 1, + &Address32 + ); - Address32 = (UINT32) RShiftU64 (Address, 32); + Address32 = (UINT32)RShiftU64 (Address, 32); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (UINT8) ((Node->PciDev->PciBar[Node->Bar]).Offset + 4), - 1, - &Address32 - ); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (UINT8)((Node->PciDev->PciBar[Node->Bar]).Offset + 4), + 1, + &Address32 + ); - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - break; + break; - default: - break; + default: + break; } } @@ -1354,13 +1349,13 @@ ProgramBar ( **/ EFI_STATUS ProgramVfBar ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Address; - UINT32 Address32; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Address; + UINT32 Address32; ASSERT (Node->Bar < PCI_MAX_BAR); ASSERT (Node->Virtual); @@ -1379,53 +1374,52 @@ ProgramVfBar ( Node->PciDev->Allocated = TRUE; switch ((Node->PciDev->VfPciBar[Node->Bar]).BarType) { + case PciBarTypeMem32: + case PciBarTypePMem32: - case PciBarTypeMem32: - case PciBarTypePMem32: - - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->VfPciBar[Node->Bar]).Offset, - 1, - &Address - ); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->VfPciBar[Node->Bar]).Offset, + 1, + &Address + ); - Node->PciDev->VfPciBar[Node->Bar].BaseAddress = Address; - break; + Node->PciDev->VfPciBar[Node->Bar].BaseAddress = Address; + break; - case PciBarTypeMem64: - case PciBarTypePMem64: + case PciBarTypeMem64: + case PciBarTypePMem64: - Address32 = (UINT32) (Address & 0x00000000FFFFFFFF); + Address32 = (UINT32)(Address & 0x00000000FFFFFFFF); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->VfPciBar[Node->Bar]).Offset, - 1, - &Address32 - ); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->VfPciBar[Node->Bar]).Offset, + 1, + &Address32 + ); - Address32 = (UINT32) RShiftU64 (Address, 32); + Address32 = (UINT32)RShiftU64 (Address, 32); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - ((Node->PciDev->VfPciBar[Node->Bar]).Offset + 4), - 1, - &Address32 - ); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + ((Node->PciDev->VfPciBar[Node->Bar]).Offset + 4), + 1, + &Address32 + ); - Node->PciDev->VfPciBar[Node->Bar].BaseAddress = Address; - break; + Node->PciDev->VfPciBar[Node->Bar].BaseAddress = Address; + break; - case PciBarTypeIo16: - case PciBarTypeIo32: - break; + case PciBarTypeIo16: + case PciBarTypeIo32: + break; - default: - break; + default: + break; } return EFI_SUCCESS; @@ -1440,24 +1434,24 @@ ProgramVfBar ( **/ VOID ProgramPpbApperture ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Address; - UINT32 Address32; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Address; + UINT32 Address32; Address = 0; // // If no device resource of this PPB, return anyway // Aperture is set default in the initialization code // - if (Node->Length == 0 || Node->ResourceUsage == PciResUsagePadding) { + if ((Node->Length == 0) || (Node->ResourceUsage == PciResUsagePadding)) { // // For padding resource node, just ignore when programming // - return ; + return; } PciIo = &(Node->PciDev->PciIo); @@ -1469,174 +1463,173 @@ ProgramPpbApperture ( Node->PciDev->Allocated = TRUE; switch (Node->Bar) { + case PPB_BAR_0: + case PPB_BAR_1: + switch ((Node->PciDev->PciBar[Node->Bar]).BarType) { + case PciBarTypeIo16: + case PciBarTypeIo32: + case PciBarTypeMem32: + case PciBarTypePMem32: + + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->PciBar[Node->Bar]).Offset, + 1, + &Address + ); - case PPB_BAR_0: - case PPB_BAR_1: - switch ((Node->PciDev->PciBar[Node->Bar]).BarType) { + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; - case PciBarTypeIo16: - case PciBarTypeIo32: - case PciBarTypeMem32: - case PciBarTypePMem32: + case PciBarTypeMem64: + case PciBarTypePMem64: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->PciBar[Node->Bar]).Offset, - 1, - &Address - ); - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; + Address32 = (UINT32)(Address & 0x00000000FFFFFFFF); - case PciBarTypeMem64: - case PciBarTypePMem64: - - Address32 = (UINT32) (Address & 0x00000000FFFFFFFF); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (Node->PciDev->PciBar[Node->Bar]).Offset, + 1, + &Address32 + ); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->PciBar[Node->Bar]).Offset, - 1, - &Address32 - ); + Address32 = (UINT32)RShiftU64 (Address, 32); - Address32 = (UINT32) RShiftU64 (Address, 32); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + (UINT8)((Node->PciDev->PciBar[Node->Bar]).Offset + 4), + 1, + &Address32 + ); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (UINT8) ((Node->PciDev->PciBar[Node->Bar]).Offset + 4), - 1, - &Address32 - ); + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; + default: + break; + } - default: - break; - } - break; + break; - case PPB_IO_RANGE: + case PPB_IO_RANGE: - Address32 = ((UINT32) (Address)) >> 8; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint8, - 0x1C, - 1, - &Address32 - ); + Address32 = ((UINT32)(Address)) >> 8; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint8, + 0x1C, + 1, + &Address32 + ); - Address32 >>= 8; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x30, - 1, - &Address32 - ); + Address32 >>= 8; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x30, + 1, + &Address32 + ); - Address32 = (UINT32) (Address + Node->Length - 1); - Address32 = ((UINT32) (Address32)) >> 8; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint8, - 0x1D, - 1, - &Address32 - ); + Address32 = (UINT32)(Address + Node->Length - 1); + Address32 = ((UINT32)(Address32)) >> 8; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint8, + 0x1D, + 1, + &Address32 + ); - Address32 >>= 8; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x32, - 1, - &Address32 - ); + Address32 >>= 8; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x32, + 1, + &Address32 + ); - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; - case PPB_MEM32_RANGE: + case PPB_MEM32_RANGE: - Address32 = ((UINT32) (Address)) >> 16; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x20, - 1, - &Address32 - ); + Address32 = ((UINT32)(Address)) >> 16; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x20, + 1, + &Address32 + ); - Address32 = (UINT32) (Address + Node->Length - 1); - Address32 = ((UINT32) (Address32)) >> 16; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x22, - 1, - &Address32 - ); + Address32 = (UINT32)(Address + Node->Length - 1); + Address32 = ((UINT32)(Address32)) >> 16; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x22, + 1, + &Address32 + ); - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; - case PPB_PMEM32_RANGE: - case PPB_PMEM64_RANGE: + case PPB_PMEM32_RANGE: + case PPB_PMEM64_RANGE: - Address32 = ((UINT32) (Address)) >> 16; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x24, - 1, - &Address32 - ); + Address32 = ((UINT32)(Address)) >> 16; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x24, + 1, + &Address32 + ); - Address32 = (UINT32) (Address + Node->Length - 1); - Address32 = ((UINT32) (Address32)) >> 16; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint16, - 0x26, - 1, - &Address32 - ); + Address32 = (UINT32)(Address + Node->Length - 1); + Address32 = ((UINT32)(Address32)) >> 16; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + 0x26, + 1, + &Address32 + ); - Address32 = (UINT32) RShiftU64 (Address, 32); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - 0x28, - 1, - &Address32 - ); + Address32 = (UINT32)RShiftU64 (Address, 32); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + 0x28, + 1, + &Address32 + ); - Address32 = (UINT32) RShiftU64 ((Address + Node->Length - 1), 32); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - 0x2C, - 1, - &Address32 - ); + Address32 = (UINT32)RShiftU64 ((Address + Node->Length - 1), 32); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + 0x2C, + 1, + &Address32 + ); - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; - default: - break; + default: + break; } } @@ -1650,15 +1643,16 @@ ProgramPpbApperture ( **/ VOID ProgramUpstreamBridgeForRom ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT32 OptionRomBase, - IN BOOLEAN Enable + IN PCI_IO_DEVICE *PciDevice, + IN UINT32 OptionRomBase, + IN BOOLEAN Enable ) { - PCI_IO_DEVICE *Parent; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT16 Base; - UINT16 Limit; + PCI_IO_DEVICE *Parent; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 Base; + UINT16 Limit; + // // For root bridge, just return. // @@ -1677,9 +1671,9 @@ ProgramUpstreamBridgeForRom ( // // Only cover MMIO for Option ROM. // - Base = (UINT16) (OptionRomBase >> 16); - Limit = (UINT16) ((OptionRomBase + PciDevice->RomSize - 1) >> 16); - PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryBase), 1, &Base); + Base = (UINT16)(OptionRomBase >> 16); + Limit = (UINT16)((OptionRomBase + PciDevice->RomSize - 1) >> 16); + PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryBase), 1, &Base); PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryLimit), 1, &Limit); PCI_ENABLE_COMMAND_REGISTER (Parent, EFI_PCI_COMMAND_MEMORY_SPACE); @@ -1691,14 +1685,15 @@ ProgramUpstreamBridgeForRom ( // // When devices under the bridge contains Option ROM and doesn't require 32bit MMIO. // - Base = (UINT16) gAllOne; - Limit = (UINT16) gAllZero; + Base = (UINT16)gAllOne; + Limit = (UINT16)gAllZero; } else { - Base = (UINT16) ((UINT32) Parent->PciBar[PPB_MEM32_RANGE].BaseAddress >> 16); - Limit = (UINT16) ((UINT32) (Parent->PciBar[PPB_MEM32_RANGE].BaseAddress - + Parent->PciBar[PPB_MEM32_RANGE].Length - 1) >> 16); + Base = (UINT16)((UINT32)Parent->PciBar[PPB_MEM32_RANGE].BaseAddress >> 16); + Limit = (UINT16)((UINT32)(Parent->PciBar[PPB_MEM32_RANGE].BaseAddress + + Parent->PciBar[PPB_MEM32_RANGE].Length - 1) >> 16); } - PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryBase), 1, &Base); + + PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryBase), 1, &Base); PciIo->Pci.Write (PciIo, EfiPciIoWidthUint16, OFFSET_OF (PCI_TYPE01, Bridge.MemoryLimit), 1, &Limit); PCI_DISABLE_COMMAND_REGISTER (Parent, EFI_PCI_COMMAND_MEMORY_SPACE); @@ -1719,11 +1714,11 @@ ProgramUpstreamBridgeForRom ( **/ BOOLEAN ResourceRequestExisted ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ) { if (Bridge != NULL) { - if (!IsListEmpty (&Bridge->ChildList) || Bridge->Length != 0) { + if (!IsListEmpty (&Bridge->ChildList) || (Bridge->Length != 0)) { return TRUE; } } @@ -1741,8 +1736,8 @@ ResourceRequestExisted ( **/ VOID InitializeResourcePool ( - IN OUT PCI_RESOURCE_NODE *ResourcePool, - IN PCI_BAR_TYPE ResourceType + IN OUT PCI_RESOURCE_NODE *ResourcePool, + IN PCI_BAR_TYPE ResourceType ) { ZeroMem (ResourcePool, sizeof (PCI_RESOURCE_NODE)); @@ -1759,17 +1754,16 @@ InitializeResourcePool ( **/ VOID DestroyResourceTree ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ) { - PCI_RESOURCE_NODE *Temp; - LIST_ENTRY *CurrentLink; + PCI_RESOURCE_NODE *Temp; + LIST_ENTRY *CurrentLink; while (!IsListEmpty (&Bridge->ChildList)) { - CurrentLink = Bridge->ChildList.ForwardLink; - Temp = RESOURCE_NODE_FROM_LINK (CurrentLink); + Temp = RESOURCE_NODE_FROM_LINK (CurrentLink); ASSERT (Temp); RemoveEntryList (CurrentLink); @@ -1795,15 +1789,15 @@ DestroyResourceTree ( **/ VOID ResourcePaddingForCardBusBridge ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ) { - PCI_RESOURCE_NODE *Node; + PCI_RESOURCE_NODE *Node; Node = NULL; @@ -1889,14 +1883,14 @@ ResourcePaddingForCardBusBridge ( **/ VOID ProgramP2C ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ) { - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Address; - UINT64 TempAddress; - UINT16 BridgeControl; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Address; + UINT64 TempAddress; + UINT16 BridgeControl; Address = 0; PciIo = &(Node->PciDev->PciIo); @@ -1912,205 +1906,200 @@ ProgramP2C ( Node->PciDev->Allocated = TRUE; switch (Node->Bar) { - - case P2C_BAR_0: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - (Node->PciDev->PciBar[Node->Bar]).Offset, - 1, - &Address - ); - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - break; - - case P2C_MEM_1: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_MEMORY_BASE_0, - 1, - &Address - ); - - TempAddress = Address + Node->Length - 1; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_MEMORY_LIMIT_0, - 1, - &TempAddress - ); - - if (Node->ResType == PciBarTypeMem32) { - // - // Set non-prefetchable bit - // - PciIo->Pci.Read ( + case P2C_BAR_0: + PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + (Node->PciDev->PciBar[Node->Bar]).Offset, 1, - &BridgeControl + &Address ); - BridgeControl &= (UINT16) ~PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + break; + + case P2C_MEM_1: PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_MEMORY_BASE_0, 1, - &BridgeControl + &Address ); - } else { - // - // Set prefetchable bit - // - PciIo->Pci.Read ( + TempAddress = Address + Node->Length - 1; + PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_MEMORY_LIMIT_0, 1, - &BridgeControl + &TempAddress ); - BridgeControl |= PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE; + if (Node->ResType == PciBarTypeMem32) { + // + // Set non-prefetchable bit + // + PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + + BridgeControl &= (UINT16) ~PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + } else { + // + // Set prefetchable bit + // + PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + + BridgeControl |= PCI_CARD_PREFETCHABLE_MEMORY_0_ENABLE; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + } + + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; + + break; + + case P2C_MEM_2: PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_MEMORY_BASE_1, 1, - &BridgeControl + &Address ); - } - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; - break; + TempAddress = Address + Node->Length - 1; - case P2C_MEM_2: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_MEMORY_BASE_1, - 1, - &Address - ); - - TempAddress = Address + Node->Length - 1; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint32, + PCI_CARD_MEMORY_LIMIT_1, + 1, + &TempAddress + ); - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_MEMORY_LIMIT_1, - 1, - &TempAddress - ); + if (Node->ResType == PciBarTypeMem32) { + // + // Set non-prefetchable bit + // + PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + + BridgeControl &= (UINT16) ~(PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE); + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + } else { + // + // Set prefetchable bit + // + PciIo->Pci.Read ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + + BridgeControl |= PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE; + PciIo->Pci.Write ( + PciIo, + EfiPciIoWidthUint16, + PCI_CARD_BRIDGE_CONTROL, + 1, + &BridgeControl + ); + } - if (Node->ResType == PciBarTypeMem32) { + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; + break; - // - // Set non-prefetchable bit - // - PciIo->Pci.Read ( + case P2C_IO_1: + PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_IO_BASE_0_LOWER, 1, - &BridgeControl + &Address ); - BridgeControl &= (UINT16) ~(PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE); + TempAddress = Address + Node->Length - 1; PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_IO_LIMIT_0_LOWER, 1, - &BridgeControl + &TempAddress ); - } else { + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; - // - // Set prefetchable bit - // - PciIo->Pci.Read ( + break; + + case P2C_IO_2: + PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_IO_BASE_1_LOWER, 1, - &BridgeControl + &Address ); - BridgeControl |= PCI_CARD_PREFETCHABLE_MEMORY_1_ENABLE; + TempAddress = Address + Node->Length - 1; PciIo->Pci.Write ( PciIo, - EfiPciIoWidthUint16, - PCI_CARD_BRIDGE_CONTROL, + EfiPciIoWidthUint32, + PCI_CARD_IO_LIMIT_1_LOWER, 1, - &BridgeControl + &TempAddress ); - } - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; - break; - - case P2C_IO_1: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_IO_BASE_0_LOWER, - 1, - &Address - ); - - TempAddress = Address + Node->Length - 1; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_IO_LIMIT_0_LOWER, - 1, - &TempAddress - ); - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; - - break; - - case P2C_IO_2: - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_IO_BASE_1_LOWER, - 1, - &Address - ); - TempAddress = Address + Node->Length - 1; - PciIo->Pci.Write ( - PciIo, - EfiPciIoWidthUint32, - PCI_CARD_IO_LIMIT_1_LOWER, - 1, - &TempAddress - ); - - Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; - Node->PciDev->PciBar[Node->Bar].Length = Node->Length; - Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; - break; + Node->PciDev->PciBar[Node->Bar].BaseAddress = Address; + Node->PciDev->PciBar[Node->Bar].Length = Node->Length; + Node->PciDev->PciBar[Node->Bar].BarType = Node->ResType; + break; - default: - break; + default: + break; } } @@ -2127,34 +2116,32 @@ ProgramP2C ( **/ VOID ApplyResourcePadding ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; - PCI_RESOURCE_NODE *Node; - UINT8 DummyBarIndex; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Ptr; + PCI_RESOURCE_NODE *Node; + UINT8 DummyBarIndex; DummyBarIndex = 0; Ptr = PciDev->ResourcePaddingDescriptors; - while (((EFI_ACPI_END_TAG_DESCRIPTOR *) Ptr)->Desc != ACPI_END_TAG_DESCRIPTOR) { - - if (Ptr->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR && Ptr->ResType == ACPI_ADDRESS_SPACE_TYPE_IO) { + while (((EFI_ACPI_END_TAG_DESCRIPTOR *)Ptr)->Desc != ACPI_END_TAG_DESCRIPTOR) { + if ((Ptr->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Ptr->ResType == ACPI_ADDRESS_SPACE_TYPE_IO)) { if (Ptr->AddrLen != 0) { - Node = CreateResourceNode ( - PciDev, - Ptr->AddrLen, - Ptr->AddrRangeMax, - DummyBarIndex, - PciBarTypeIo16, - PciResUsagePadding - ); + PciDev, + Ptr->AddrLen, + Ptr->AddrRangeMax, + DummyBarIndex, + PciBarTypeIo16, + PciResUsagePadding + ); InsertResourceNode ( IoNode, Node @@ -2165,23 +2152,21 @@ ApplyResourcePadding ( continue; } - if (Ptr->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR && Ptr->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { - + if ((Ptr->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) && (Ptr->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM)) { if (Ptr->AddrSpaceGranularity == 32) { - // // prefetchable // if (Ptr->SpecificFlag == 0x6) { if (Ptr->AddrLen != 0) { Node = CreateResourceNode ( - PciDev, - Ptr->AddrLen, - Ptr->AddrRangeMax, - DummyBarIndex, - PciBarTypePMem32, - PciResUsagePadding - ); + PciDev, + Ptr->AddrLen, + Ptr->AddrRangeMax, + DummyBarIndex, + PciBarTypePMem32, + PciResUsagePadding + ); InsertResourceNode ( PMem32Node, Node @@ -2198,13 +2183,13 @@ ApplyResourcePadding ( if (Ptr->SpecificFlag == 0) { if (Ptr->AddrLen != 0) { Node = CreateResourceNode ( - PciDev, - Ptr->AddrLen, - Ptr->AddrRangeMax, - DummyBarIndex, - PciBarTypeMem32, - PciResUsagePadding - ); + PciDev, + Ptr->AddrLen, + Ptr->AddrRangeMax, + DummyBarIndex, + PciBarTypeMem32, + PciResUsagePadding + ); InsertResourceNode ( Mem32Node, Node @@ -2217,20 +2202,19 @@ ApplyResourcePadding ( } if (Ptr->AddrSpaceGranularity == 64) { - // // prefetchable // if (Ptr->SpecificFlag == 0x6) { if (Ptr->AddrLen != 0) { Node = CreateResourceNode ( - PciDev, - Ptr->AddrLen, - Ptr->AddrRangeMax, - DummyBarIndex, - PciBarTypePMem64, - PciResUsagePadding - ); + PciDev, + Ptr->AddrLen, + Ptr->AddrRangeMax, + DummyBarIndex, + PciBarTypePMem64, + PciResUsagePadding + ); InsertResourceNode ( PMem64Node, Node @@ -2247,13 +2231,13 @@ ApplyResourcePadding ( if (Ptr->SpecificFlag == 0) { if (Ptr->AddrLen != 0) { Node = CreateResourceNode ( - PciDev, - Ptr->AddrLen, - Ptr->AddrRangeMax, - DummyBarIndex, - PciBarTypeMem64, - PciResUsagePadding - ); + PciDev, + Ptr->AddrLen, + Ptr->AddrRangeMax, + DummyBarIndex, + PciBarTypeMem64, + PciResUsagePadding + ); InsertResourceNode ( Mem64Node, Node @@ -2280,13 +2264,12 @@ ApplyResourcePadding ( **/ VOID GetResourcePaddingPpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - if (gPciHotPlugInit != NULL && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { + if ((gPciHotPlugInit != NULL) && FeaturePcdGet (PcdPciBusHotplugDeviceSupport)) { if (PciIoDevice->ResourcePaddingDescriptors == NULL) { GetResourcePaddingForHpb (PciIoDevice); } } } - diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h index 9f2de291ba..1527d4eafa 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciResourceSupport.h @@ -17,18 +17,18 @@ typedef enum { #define PCI_RESOURCE_SIGNATURE SIGNATURE_32 ('p', 'c', 'r', 'c') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - LIST_ENTRY ChildList; - PCI_IO_DEVICE *PciDev; - UINT64 Alignment; - UINT64 Offset; - UINT8 Bar; - PCI_BAR_TYPE ResType; - UINT64 Length; - BOOLEAN Reserved; - PCI_RESOURCE_USAGE ResourceUsage; - BOOLEAN Virtual; + UINT32 Signature; + LIST_ENTRY Link; + LIST_ENTRY ChildList; + PCI_IO_DEVICE *PciDev; + UINT64 Alignment; + UINT64 Offset; + UINT8 Bar; + PCI_BAR_TYPE ResType; + UINT64 Length; + BOOLEAN Reserved; + PCI_RESOURCE_USAGE ResourceUsage; + BOOLEAN Virtual; } PCI_RESOURCE_NODE; #define RESOURCE_NODE_FROM_LINK(a) \ @@ -43,8 +43,8 @@ typedef struct { **/ VOID SkipVGAAperture ( - OUT UINT64 *Start, - IN UINT64 Length + OUT UINT64 *Start, + IN UINT64 Length ); /** @@ -56,8 +56,8 @@ SkipVGAAperture ( **/ VOID SkipIsaAliasAperture ( - OUT UINT64 *Start, - IN UINT64 Length + OUT UINT64 *Start, + IN UINT64 Length ); /** @@ -70,8 +70,8 @@ SkipIsaAliasAperture ( **/ VOID InsertResourceNode ( - IN OUT PCI_RESOURCE_NODE *Bridge, - IN PCI_RESOURCE_NODE *ResNode + IN OUT PCI_RESOURCE_NODE *Bridge, + IN PCI_RESOURCE_NODE *ResNode ); /** @@ -94,9 +94,9 @@ InsertResourceNode ( **/ VOID MergeResourceTree ( - IN PCI_RESOURCE_NODE *Dst, - IN PCI_RESOURCE_NODE *Res, - IN BOOLEAN TypeMerge + IN PCI_RESOURCE_NODE *Dst, + IN PCI_RESOURCE_NODE *Res, + IN BOOLEAN TypeMerge ); /** @@ -108,7 +108,7 @@ MergeResourceTree ( **/ VOID CalculateApertureIo16 ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ); /** @@ -120,7 +120,7 @@ CalculateApertureIo16 ( **/ VOID CalculateResourceAperture ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ); /** @@ -136,12 +136,12 @@ CalculateResourceAperture ( **/ VOID GetResourceFromDevice ( - IN PCI_IO_DEVICE *PciDev, - IN OUT PCI_RESOURCE_NODE *IoNode, - IN OUT PCI_RESOURCE_NODE *Mem32Node, - IN OUT PCI_RESOURCE_NODE *PMem32Node, - IN OUT PCI_RESOURCE_NODE *Mem64Node, - IN OUT PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN OUT PCI_RESOURCE_NODE *IoNode, + IN OUT PCI_RESOURCE_NODE *Mem32Node, + IN OUT PCI_RESOURCE_NODE *PMem32Node, + IN OUT PCI_RESOURCE_NODE *Mem64Node, + IN OUT PCI_RESOURCE_NODE *PMem64Node ); /** @@ -160,12 +160,12 @@ GetResourceFromDevice ( **/ PCI_RESOURCE_NODE * CreateResourceNode ( - IN PCI_IO_DEVICE *PciDev, - IN UINT64 Length, - IN UINT64 Alignment, - IN UINT8 Bar, - IN PCI_BAR_TYPE ResType, - IN PCI_RESOURCE_USAGE ResUsage + IN PCI_IO_DEVICE *PciDev, + IN UINT64 Length, + IN UINT64 Alignment, + IN UINT8 Bar, + IN PCI_BAR_TYPE ResType, + IN PCI_RESOURCE_USAGE ResUsage ); /** @@ -184,12 +184,12 @@ CreateResourceNode ( **/ PCI_RESOURCE_NODE * CreateVfResourceNode ( - IN PCI_IO_DEVICE *PciDev, - IN UINT64 Length, - IN UINT64 Alignment, - IN UINT8 Bar, - IN PCI_BAR_TYPE ResType, - IN PCI_RESOURCE_USAGE ResUsage + IN PCI_IO_DEVICE *PciDev, + IN UINT64 Length, + IN UINT64 Alignment, + IN UINT8 Bar, + IN PCI_BAR_TYPE ResType, + IN PCI_RESOURCE_USAGE ResUsage ); /** @@ -206,12 +206,12 @@ CreateVfResourceNode ( **/ VOID CreateResourceMap ( - IN PCI_IO_DEVICE *Bridge, - IN OUT PCI_RESOURCE_NODE *IoNode, - IN OUT PCI_RESOURCE_NODE *Mem32Node, - IN OUT PCI_RESOURCE_NODE *PMem32Node, - IN OUT PCI_RESOURCE_NODE *Mem64Node, - IN OUT PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *Bridge, + IN OUT PCI_RESOURCE_NODE *IoNode, + IN OUT PCI_RESOURCE_NODE *Mem32Node, + IN OUT PCI_RESOURCE_NODE *PMem32Node, + IN OUT PCI_RESOURCE_NODE *Mem64Node, + IN OUT PCI_RESOURCE_NODE *PMem64Node ); /** @@ -227,12 +227,12 @@ CreateResourceMap ( **/ VOID ResourcePaddingPolicy ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ); /** @@ -251,11 +251,11 @@ ResourcePaddingPolicy ( **/ VOID DegradeResource ( - IN PCI_IO_DEVICE *Bridge, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *Bridge, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ); /** @@ -270,8 +270,8 @@ DegradeResource ( **/ BOOLEAN BridgeSupportResourceDecode ( - IN PCI_IO_DEVICE *Bridge, - IN UINT32 Decode + IN PCI_IO_DEVICE *Bridge, + IN UINT32 Decode ); /** @@ -288,8 +288,8 @@ BridgeSupportResourceDecode ( **/ EFI_STATUS ProgramResource ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Bridge + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Bridge ); /** @@ -301,8 +301,8 @@ ProgramResource ( **/ VOID ProgramBar ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ); /** @@ -314,8 +314,8 @@ ProgramBar ( **/ EFI_STATUS ProgramVfBar ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ); /** @@ -327,8 +327,8 @@ ProgramVfBar ( **/ VOID ProgramPpbApperture ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ); /** @@ -341,9 +341,9 @@ ProgramPpbApperture ( **/ VOID ProgramUpstreamBridgeForRom ( - IN PCI_IO_DEVICE *PciDevice, - IN UINT32 OptionRomBase, - IN BOOLEAN Enable + IN PCI_IO_DEVICE *PciDevice, + IN UINT32 OptionRomBase, + IN BOOLEAN Enable ); /** @@ -357,7 +357,7 @@ ProgramUpstreamBridgeForRom ( **/ BOOLEAN ResourceRequestExisted ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ); /** @@ -370,8 +370,8 @@ ResourceRequestExisted ( **/ VOID InitializeResourcePool ( - IN OUT PCI_RESOURCE_NODE *ResourcePool, - IN PCI_BAR_TYPE ResourceType + IN OUT PCI_RESOURCE_NODE *ResourcePool, + IN PCI_BAR_TYPE ResourceType ); /** @@ -382,7 +382,7 @@ InitializeResourcePool ( **/ VOID DestroyResourceTree ( - IN PCI_RESOURCE_NODE *Bridge + IN PCI_RESOURCE_NODE *Bridge ); /** @@ -398,12 +398,12 @@ DestroyResourceTree ( **/ VOID ResourcePaddingForCardBusBridge ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ); /** @@ -415,8 +415,8 @@ ResourcePaddingForCardBusBridge ( **/ VOID ProgramP2C ( - IN UINT64 Base, - IN PCI_RESOURCE_NODE *Node + IN UINT64 Base, + IN PCI_RESOURCE_NODE *Node ); /** @@ -432,12 +432,12 @@ ProgramP2C ( **/ VOID ApplyResourcePadding ( - IN PCI_IO_DEVICE *PciDev, - IN PCI_RESOURCE_NODE *IoNode, - IN PCI_RESOURCE_NODE *Mem32Node, - IN PCI_RESOURCE_NODE *PMem32Node, - IN PCI_RESOURCE_NODE *Mem64Node, - IN PCI_RESOURCE_NODE *PMem64Node + IN PCI_IO_DEVICE *PciDev, + IN PCI_RESOURCE_NODE *IoNode, + IN PCI_RESOURCE_NODE *Mem32Node, + IN PCI_RESOURCE_NODE *PMem32Node, + IN PCI_RESOURCE_NODE *Mem64Node, + IN PCI_RESOURCE_NODE *PMem64Node ); /** @@ -450,7 +450,7 @@ ApplyResourcePadding ( **/ VOID GetResourcePaddingPpb ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c index 5575a364a1..5535bd3013 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.c @@ -12,18 +12,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // PCI ROM image information // typedef struct { - EFI_HANDLE ImageHandle; - UINTN Seg; - UINT8 Bus; - UINT8 Dev; - UINT8 Func; - VOID *RomImage; - UINT64 RomSize; + EFI_HANDLE ImageHandle; + UINTN Seg; + UINT8 Bus; + UINT8 Dev; + UINT8 Func; + VOID *RomImage; + UINT64 RomSize; } PCI_ROM_IMAGE; -UINTN mNumberOfPciRomImages = 0; -UINTN mMaxNumberOfPciRomImages = 0; -PCI_ROM_IMAGE *mRomImageTable = NULL; +UINTN mNumberOfPciRomImages = 0; +UINTN mMaxNumberOfPciRomImages = 0; +PCI_ROM_IMAGE *mRomImageTable = NULL; /** Add the Rom Image to internal database for later PCI light enumeration. @@ -47,20 +47,21 @@ PciRomAddImageMapping ( IN UINT64 RomSize ) { - UINTN Index; - PCI_ROM_IMAGE *NewTable; + UINTN Index; + PCI_ROM_IMAGE *NewTable; for (Index = 0; Index < mNumberOfPciRomImages; Index++) { - if (mRomImageTable[Index].Seg == Seg && - mRomImageTable[Index].Bus == Bus && - mRomImageTable[Index].Dev == Dev && - mRomImageTable[Index].Func == Func) { + if ((mRomImageTable[Index].Seg == Seg) && + (mRomImageTable[Index].Bus == Bus) && + (mRomImageTable[Index].Dev == Dev) && + (mRomImageTable[Index].Func == Func)) + { // // Expect once RomImage and RomSize are recorded, they will be passed in // later when updating ImageHandle // ASSERT ((mRomImageTable[Index].RomImage == NULL) || (RomImage == mRomImageTable[Index].RomImage)); - ASSERT ((mRomImageTable[Index].RomSize == 0 ) || (RomSize == mRomImageTable[Index].RomSize )); + ASSERT ((mRomImageTable[Index].RomSize == 0) || (RomSize == mRomImageTable[Index].RomSize)); break; } } @@ -76,12 +77,13 @@ PciRomAddImageMapping ( mRomImageTable ); if (NewTable == NULL) { - return ; + return; } mRomImageTable = NewTable; mMaxNumberOfPciRomImages += 0x20; } + // // Record the new PCI device // @@ -108,23 +110,24 @@ PciRomAddImageMapping ( **/ BOOLEAN PciRomGetImageMapping ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ) { - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; - UINTN Index; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *PciRootBridgeIo; + UINTN Index; PciRootBridgeIo = PciIoDevice->PciRootBridgeIo; for (Index = 0; Index < mNumberOfPciRomImages; Index++) { - if (mRomImageTable[Index].Seg == PciRootBridgeIo->SegmentNumber && - mRomImageTable[Index].Bus == PciIoDevice->BusNumber && - mRomImageTable[Index].Dev == PciIoDevice->DeviceNumber && - mRomImageTable[Index].Func == PciIoDevice->FunctionNumber ) { - + if ((mRomImageTable[Index].Seg == PciRootBridgeIo->SegmentNumber) && + (mRomImageTable[Index].Bus == PciIoDevice->BusNumber) && + (mRomImageTable[Index].Dev == PciIoDevice->DeviceNumber) && + (mRomImageTable[Index].Func == PciIoDevice->FunctionNumber)) + { if (mRomImageTable[Index].ImageHandle != NULL) { AddDriver (PciIoDevice, mRomImageTable[Index].ImageHandle, NULL); } + PciIoDevice->PciIo.RomImage = mRomImageTable[Index].RomImage; PciIoDevice->PciIo.RomSize = mRomImageTable[Index].RomSize; return TRUE; diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h index 4c2a4e1988..f90b13a2a9 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciRomTable.h @@ -42,7 +42,7 @@ PciRomAddImageMapping ( **/ BOOLEAN PciRomGetImageMapping ( - IN PCI_IO_DEVICE *PciIoDevice + IN PCI_IO_DEVICE *PciIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c index 5c8f0f46a1..b20bcd310a 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.c @@ -11,18 +11,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciRootBridge.h" #include "PciHostResource.h" -EFI_CPU_IO2_PROTOCOL *mCpuIo; +EFI_CPU_IO2_PROTOCOL *mCpuIo; -GLOBAL_REMOVE_IF_UNREFERENCED CHAR16 *mAcpiAddressSpaceTypeStr[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CHAR16 *mAcpiAddressSpaceTypeStr[] = { L"Mem", L"I/O", L"Bus" }; -GLOBAL_REMOVE_IF_UNREFERENCED CHAR16 *mPciResourceTypeStr[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CHAR16 *mPciResourceTypeStr[] = { L"I/O", L"Mem", L"PMem", L"Mem64", L"PMem64", L"Bus" }; -EDKII_IOMMU_PROTOCOL *mIoMmu; -EFI_EVENT mIoMmuEvent; -VOID *mIoMmuRegistration; +EDKII_IOMMU_PROTOCOL *mIoMmu; +EFI_EVENT mIoMmuEvent; +VOID *mIoMmuRegistration; /** This routine gets translation offset from a root bridge instance by resource type. @@ -34,8 +34,8 @@ VOID *mIoMmuRegistration; **/ UINT64 GetTranslationByResourceType ( - IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, - IN PCI_RESOURCE_TYPE ResourceType + IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, + IN PCI_RESOURCE_TYPE ResourceType ) { switch (ResourceType) { @@ -92,22 +92,24 @@ GetTranslationByResourceType ( **/ EFI_STATUS IntersectIoDescriptor ( - IN UINT64 Base, - IN UINT64 Length, - IN CONST EFI_GCD_IO_SPACE_DESCRIPTOR *Descriptor + IN UINT64 Base, + IN UINT64 Length, + IN CONST EFI_GCD_IO_SPACE_DESCRIPTOR *Descriptor ) { - UINT64 IntersectionBase; - UINT64 IntersectionEnd; - EFI_STATUS Status; + UINT64 IntersectionBase; + UINT64 IntersectionEnd; + EFI_STATUS Status; if (Descriptor->GcdIoType == EfiGcdIoTypeIo) { return EFI_SUCCESS; } IntersectionBase = MAX (Base, Descriptor->BaseAddress); - IntersectionEnd = MIN (Base + Length, - Descriptor->BaseAddress + Descriptor->Length); + IntersectionEnd = MIN ( + Base + Length, + Descriptor->BaseAddress + Descriptor->Length + ); if (IntersectionBase >= IntersectionEnd) { // // The descriptor and the aperture don't overlap. @@ -116,19 +118,36 @@ IntersectIoDescriptor ( } if (Descriptor->GcdIoType == EfiGcdIoTypeNonExistent) { - Status = gDS->AddIoSpace (EfiGcdIoTypeIo, IntersectionBase, - IntersectionEnd - IntersectionBase); + Status = gDS->AddIoSpace ( + EfiGcdIoTypeIo, + IntersectionBase, + IntersectionEnd - IntersectionBase + ); - DEBUG ((EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, - "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, __FUNCTION__, - IntersectionBase, IntersectionEnd, Status)); + DEBUG (( + EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, + "%a: %a: add [%Lx, %Lx): %r\n", + gEfiCallerBaseName, + __FUNCTION__, + IntersectionBase, + IntersectionEnd, + Status + )); return Status; } - DEBUG ((DEBUG_ERROR, "%a: %a: desc [%Lx, %Lx) type %u conflicts with " - "aperture [%Lx, %Lx)\n", gEfiCallerBaseName, __FUNCTION__, - Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length, - (UINT32)Descriptor->GcdIoType, Base, Base + Length)); + DEBUG (( + DEBUG_ERROR, + "%a: %a: desc [%Lx, %Lx) type %u conflicts with " + "aperture [%Lx, %Lx)\n", + gEfiCallerBaseName, + __FUNCTION__, + Descriptor->BaseAddress, + Descriptor->BaseAddress + Descriptor->Length, + (UINT32)Descriptor->GcdIoType, + Base, + Base + Length + )); return EFI_INVALID_PARAMETER; } @@ -144,19 +163,24 @@ IntersectIoDescriptor ( **/ EFI_STATUS AddIoSpace ( - IN UINT64 Base, - IN UINT64 Length + IN UINT64 Base, + IN UINT64 Length ) { - EFI_STATUS Status; - UINTN Index; - UINTN NumberOfDescriptors; - EFI_GCD_IO_SPACE_DESCRIPTOR *IoSpaceMap; + EFI_STATUS Status; + UINTN Index; + UINTN NumberOfDescriptors; + EFI_GCD_IO_SPACE_DESCRIPTOR *IoSpaceMap; Status = gDS->GetIoSpaceMap (&NumberOfDescriptors, &IoSpaceMap); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %a: GetIoSpaceMap(): %r\n", - gEfiCallerBaseName, __FUNCTION__, Status)); + DEBUG (( + DEBUG_ERROR, + "%a: %a: GetIoSpaceMap(): %r\n", + gEfiCallerBaseName, + __FUNCTION__, + Status + )); return Status; } @@ -167,24 +191,26 @@ AddIoSpace ( } } - DEBUG_CODE_BEGIN (); - // - // Make sure there are adjacent descriptors covering [Base, Base + Length). - // It is possible that they have not been merged; merging can be prevented - // by allocation. - // - UINT64 CheckBase; - EFI_STATUS CheckStatus; - EFI_GCD_IO_SPACE_DESCRIPTOR Descriptor; - - for (CheckBase = Base; - CheckBase < Base + Length; - CheckBase = Descriptor.BaseAddress + Descriptor.Length) { - CheckStatus = gDS->GetIoSpaceDescriptor (CheckBase, &Descriptor); - ASSERT_EFI_ERROR (CheckStatus); - ASSERT (Descriptor.GcdIoType == EfiGcdIoTypeIo); - } - DEBUG_CODE_END (); + DEBUG_CODE_BEGIN (); + // + // Make sure there are adjacent descriptors covering [Base, Base + Length). + // It is possible that they have not been merged; merging can be prevented + // by allocation. + // + UINT64 CheckBase; + EFI_STATUS CheckStatus; + EFI_GCD_IO_SPACE_DESCRIPTOR Descriptor; + + for (CheckBase = Base; + CheckBase < Base + Length; + CheckBase = Descriptor.BaseAddress + Descriptor.Length) + { + CheckStatus = gDS->GetIoSpaceDescriptor (CheckBase, &Descriptor); + ASSERT_EFI_ERROR (CheckStatus); + ASSERT (Descriptor.GcdIoType == EfiGcdIoTypeIo); + } + + DEBUG_CODE_END (); FreeIoSpaceMap: FreePool (IoSpaceMap); @@ -233,24 +259,27 @@ FreeIoSpaceMap: **/ EFI_STATUS IntersectMemoryDescriptor ( - IN UINT64 Base, - IN UINT64 Length, - IN UINT64 Capabilities, - IN CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Descriptor + IN UINT64 Base, + IN UINT64 Length, + IN UINT64 Capabilities, + IN CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Descriptor ) { - UINT64 IntersectionBase; - UINT64 IntersectionEnd; - EFI_STATUS Status; + UINT64 IntersectionBase; + UINT64 IntersectionEnd; + EFI_STATUS Status; - if (Descriptor->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo && - (Descriptor->Capabilities & Capabilities) == Capabilities) { + if ((Descriptor->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) && + ((Descriptor->Capabilities & Capabilities) == Capabilities)) + { return EFI_SUCCESS; } IntersectionBase = MAX (Base, Descriptor->BaseAddress); - IntersectionEnd = MIN (Base + Length, - Descriptor->BaseAddress + Descriptor->Length); + IntersectionEnd = MIN ( + Base + Length, + Descriptor->BaseAddress + Descriptor->Length + ); if (IntersectionBase >= IntersectionEnd) { // // The descriptor and the aperture don't overlap. @@ -259,21 +288,39 @@ IntersectMemoryDescriptor ( } if (Descriptor->GcdMemoryType == EfiGcdMemoryTypeNonExistent) { - Status = gDS->AddMemorySpace (EfiGcdMemoryTypeMemoryMappedIo, - IntersectionBase, IntersectionEnd - IntersectionBase, - Capabilities); + Status = gDS->AddMemorySpace ( + EfiGcdMemoryTypeMemoryMappedIo, + IntersectionBase, + IntersectionEnd - IntersectionBase, + Capabilities + ); - DEBUG ((EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, - "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, __FUNCTION__, - IntersectionBase, IntersectionEnd, Status)); + DEBUG (( + EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE, + "%a: %a: add [%Lx, %Lx): %r\n", + gEfiCallerBaseName, + __FUNCTION__, + IntersectionBase, + IntersectionEnd, + Status + )); return Status; } - DEBUG ((DEBUG_ERROR, "%a: %a: desc [%Lx, %Lx) type %u cap %Lx conflicts " - "with aperture [%Lx, %Lx) cap %Lx\n", gEfiCallerBaseName, __FUNCTION__, - Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length, - (UINT32)Descriptor->GcdMemoryType, Descriptor->Capabilities, - Base, Base + Length, Capabilities)); + DEBUG (( + DEBUG_ERROR, + "%a: %a: desc [%Lx, %Lx) type %u cap %Lx conflicts " + "with aperture [%Lx, %Lx) cap %Lx\n", + gEfiCallerBaseName, + __FUNCTION__, + Descriptor->BaseAddress, + Descriptor->BaseAddress + Descriptor->Length, + (UINT32)Descriptor->GcdMemoryType, + Descriptor->Capabilities, + Base, + Base + Length, + Capabilities + )); return EFI_INVALID_PARAMETER; } @@ -290,49 +337,60 @@ IntersectMemoryDescriptor ( **/ EFI_STATUS AddMemoryMappedIoSpace ( - IN UINT64 Base, - IN UINT64 Length, - IN UINT64 Capabilities + IN UINT64 Base, + IN UINT64 Length, + IN UINT64 Capabilities ) { - EFI_STATUS Status; - UINTN Index; - UINTN NumberOfDescriptors; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; + EFI_STATUS Status; + UINTN Index; + UINTN NumberOfDescriptors; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; Status = gDS->GetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "%a: %a: GetMemorySpaceMap(): %r\n", - gEfiCallerBaseName, __FUNCTION__, Status)); + DEBUG (( + DEBUG_ERROR, + "%a: %a: GetMemorySpaceMap(): %r\n", + gEfiCallerBaseName, + __FUNCTION__, + Status + )); return Status; } for (Index = 0; Index < NumberOfDescriptors; Index++) { - Status = IntersectMemoryDescriptor (Base, Length, Capabilities, - &MemorySpaceMap[Index]); + Status = IntersectMemoryDescriptor ( + Base, + Length, + Capabilities, + &MemorySpaceMap[Index] + ); if (EFI_ERROR (Status)) { goto FreeMemorySpaceMap; } } DEBUG_CODE_BEGIN (); - // - // Make sure there are adjacent descriptors covering [Base, Base + Length). - // It is possible that they have not been merged; merging can be prevented - // by allocation and different capabilities. - // - UINT64 CheckBase; - EFI_STATUS CheckStatus; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; - - for (CheckBase = Base; - CheckBase < Base + Length; - CheckBase = Descriptor.BaseAddress + Descriptor.Length) { - CheckStatus = gDS->GetMemorySpaceDescriptor (CheckBase, &Descriptor); - ASSERT_EFI_ERROR (CheckStatus); - ASSERT (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo); - ASSERT ((Descriptor.Capabilities & Capabilities) == Capabilities); - } + // + // Make sure there are adjacent descriptors covering [Base, Base + Length). + // It is possible that they have not been merged; merging can be prevented + // by allocation and different capabilities. + // + UINT64 CheckBase; + EFI_STATUS CheckStatus; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; + + for (CheckBase = Base; + CheckBase < Base + Length; + CheckBase = Descriptor.BaseAddress + Descriptor.Length) + { + CheckStatus = gDS->GetMemorySpaceDescriptor (CheckBase, &Descriptor); + ASSERT_EFI_ERROR (CheckStatus); + ASSERT (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo); + ASSERT ((Descriptor.Capabilities & Capabilities) == Capabilities); + } + DEBUG_CODE_END (); FreeMemorySpaceMap: @@ -351,14 +409,14 @@ FreeMemorySpaceMap: VOID EFIAPI IoMmuProtocolCallback ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = gBS->LocateProtocol (&gEdkiiIoMmuProtocolGuid, NULL, (VOID **)&mIoMmu); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { gBS->CloseEvent (mIoMmuEvent); } } @@ -377,28 +435,28 @@ IoMmuProtocolCallback ( EFI_STATUS EFIAPI InitializePciHostBridge ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - PCI_ROOT_BRIDGE *RootBridges; - UINTN RootBridgeCount; - UINTN Index; - PCI_ROOT_BRIDGE_APERTURE *MemApertures[4]; - UINTN MemApertureIndex; - BOOLEAN ResourceAssigned; - LIST_ENTRY *Link; - UINT64 HostAddress; + EFI_STATUS Status; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + PCI_ROOT_BRIDGE *RootBridges; + UINTN RootBridgeCount; + UINTN Index; + PCI_ROOT_BRIDGE_APERTURE *MemApertures[4]; + UINTN MemApertureIndex; + BOOLEAN ResourceAssigned; + LIST_ENTRY *Link; + UINT64 HostAddress; RootBridges = PciHostBridgeGetRootBridges (&RootBridgeCount); if ((RootBridges == NULL) || (RootBridgeCount == 0)) { return EFI_UNSUPPORTED; } - Status = gBS->LocateProtocol (&gEfiCpuIo2ProtocolGuid, NULL, (VOID **) &mCpuIo); + Status = gBS->LocateProtocol (&gEfiCpuIo2ProtocolGuid, NULL, (VOID **)&mCpuIo); ASSERT_EFI_ERROR (Status); // @@ -407,10 +465,10 @@ InitializePciHostBridge ( HostBridge = AllocateZeroPool (sizeof (PCI_HOST_BRIDGE_INSTANCE)); ASSERT (HostBridge != NULL); - HostBridge->Signature = PCI_HOST_BRIDGE_SIGNATURE; - HostBridge->CanRestarted = TRUE; + HostBridge->Signature = PCI_HOST_BRIDGE_SIGNATURE; + HostBridge->CanRestarted = TRUE; InitializeListHead (&HostBridge->RootBridges); - ResourceAssigned = FALSE; + ResourceAssigned = FALSE; // // Create Root Bridge Device Handle in this Host Bridge @@ -439,8 +497,10 @@ InitializePciHostBridge ( // Base and Limit in PCI_ROOT_BRIDGE_APERTURE are device address. // For GCD resource manipulation, we need to use host address. // - HostAddress = TO_HOST_ADDRESS (RootBridges[Index].Io.Base, - RootBridges[Index].Io.Translation); + HostAddress = TO_HOST_ADDRESS ( + RootBridges[Index].Io.Base, + RootBridges[Index].Io.Translation + ); Status = AddIoSpace ( HostAddress, @@ -478,8 +538,10 @@ InitializePciHostBridge ( // Base and Limit in PCI_ROOT_BRIDGE_APERTURE are device address. // For GCD resource manipulation, we need to use host address. // - HostAddress = TO_HOST_ADDRESS (MemApertures[MemApertureIndex]->Base, - MemApertures[MemApertureIndex]->Translation); + HostAddress = TO_HOST_ADDRESS ( + MemApertures[MemApertureIndex]->Base, + MemApertures[MemApertureIndex]->Translation + ); Status = AddMemoryMappedIoSpace ( HostAddress, MemApertures[MemApertureIndex]->Limit - MemApertures[MemApertureIndex]->Base + 1, @@ -494,6 +556,7 @@ InitializePciHostBridge ( if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "PciHostBridge driver failed to set EFI_MEMORY_UC to MMIO aperture - %r.\n", Status)); } + if (ResourceAssigned) { Status = gDS->AllocateMemorySpace ( EfiGcdAllocateAddress, @@ -508,6 +571,7 @@ InitializePciHostBridge ( } } } + // // Insert Root Bridge Handle Instance // @@ -519,18 +583,19 @@ InitializePciHostBridge ( // PciHostBridgeResourceAllocation protocol. // if (!ResourceAssigned) { - HostBridge->ResAlloc.NotifyPhase = NotifyPhase; - HostBridge->ResAlloc.GetNextRootBridge = GetNextRootBridge; - HostBridge->ResAlloc.GetAllocAttributes = GetAttributes; - HostBridge->ResAlloc.StartBusEnumeration = StartBusEnumeration; - HostBridge->ResAlloc.SetBusNumbers = SetBusNumbers; - HostBridge->ResAlloc.SubmitResources = SubmitResources; + HostBridge->ResAlloc.NotifyPhase = NotifyPhase; + HostBridge->ResAlloc.GetNextRootBridge = GetNextRootBridge; + HostBridge->ResAlloc.GetAllocAttributes = GetAttributes; + HostBridge->ResAlloc.StartBusEnumeration = StartBusEnumeration; + HostBridge->ResAlloc.SetBusNumbers = SetBusNumbers; + HostBridge->ResAlloc.SubmitResources = SubmitResources; HostBridge->ResAlloc.GetProposedResources = GetProposedResources; HostBridge->ResAlloc.PreprocessController = PreprocessController; Status = gBS->InstallMultipleProtocolInterfaces ( &HostBridge->Handle, - &gEfiPciHostBridgeResourceAllocationProtocolGuid, &HostBridge->ResAlloc, + &gEfiPciHostBridgeResourceAllocationProtocolGuid, + &HostBridge->ResAlloc, NULL ); ASSERT_EFI_ERROR (Status); @@ -539,18 +604,22 @@ InitializePciHostBridge ( for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + ) + { + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); RootBridge->RootBridgeIo.ParentHandle = HostBridge->Handle; Status = gBS->InstallMultipleProtocolInterfaces ( &RootBridge->Handle, - &gEfiDevicePathProtocolGuid, RootBridge->DevicePath, - &gEfiPciRootBridgeIoProtocolGuid, &RootBridge->RootBridgeIo, + &gEfiDevicePathProtocolGuid, + RootBridge->DevicePath, + &gEfiPciRootBridgeIoProtocolGuid, + &RootBridge->RootBridgeIo, NULL ); ASSERT_EFI_ERROR (Status); } + PciHostBridgeFreeRootBridges (RootBridges, RootBridgeCount); if (!EFI_ERROR (Status)) { @@ -573,23 +642,24 @@ InitializePciHostBridge ( **/ VOID ResourceConflict ( - IN PCI_HOST_BRIDGE_INSTANCE *HostBridge + IN PCI_HOST_BRIDGE_INSTANCE *HostBridge ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Resources; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - LIST_ENTRY *Link; - UINTN RootBridgeCount; - PCI_RESOURCE_TYPE Index; - PCI_RES_NODE *ResAllocNode; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Resources; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + LIST_ENTRY *Link; + UINTN RootBridgeCount; + PCI_RESOURCE_TYPE Index; + PCI_RES_NODE *ResAllocNode; RootBridgeCount = 0; for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridgeCount++; } @@ -602,61 +672,63 @@ ResourceConflict ( for (Link = GetFirstNode (&HostBridge->RootBridges), Descriptor = Resources ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); for (Index = TypeIo; Index < TypeMax; Index++) { ResAllocNode = &RootBridge->ResAllocNode[Index]; - Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Descriptor->Len = sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; + Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Descriptor->Len = sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; Descriptor->AddrRangeMin = ResAllocNode->Base; Descriptor->AddrRangeMax = ResAllocNode->Alignment; Descriptor->AddrLen = ResAllocNode->Length; Descriptor->SpecificFlag = 0; switch (ResAllocNode->Type) { + case TypeIo: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; + break; + + case TypePMem32: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem32: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 32; + break; + + case TypePMem64: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem64: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 64; + break; + + case TypeBus: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_BUS; + break; - case TypeIo: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; - break; - - case TypePMem32: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem32: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 32; - break; - - case TypePMem64: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem64: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 64; - break; - - case TypeBus: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_BUS; - break; - - default: - break; + default: + break; } Descriptor++; } + // // Terminate the root bridge resources. // - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) Descriptor; - End->Desc = ACPI_END_TAG_DESCRIPTOR; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor; + End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0x0; - Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) (End + 1); + Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)(End + 1); } + // // Terminate the host bridge resources. // - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) Descriptor; - End->Desc = ACPI_END_TAG_DESCRIPTOR; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor; + End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0x0; DEBUG ((DEBUG_ERROR, "Call PciHostBridgeResourceConflict().\n")); @@ -679,14 +751,14 @@ ResourceConflict ( **/ UINT64 AllocateResource ( - BOOLEAN Mmio, - UINT64 Length, - UINTN BitsOfAlignment, - UINT64 BaseAddress, - UINT64 Limit + BOOLEAN Mmio, + UINT64 Length, + UINTN BitsOfAlignment, + UINT64 BaseAddress, + UINT64 Limit ) { - EFI_STATUS Status; + EFI_STATUS Status; if (BaseAddress < Limit) { // @@ -725,9 +797,11 @@ AllocateResource ( if (!EFI_ERROR (Status)) { return BaseAddress; } + BaseAddress += LShiftU64 (1, BitsOfAlignment); } } + return MAX_UINT64; } @@ -746,331 +820,374 @@ AllocateResource ( EFI_STATUS EFIAPI NotifyPhase ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase ) { - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - LIST_ENTRY *Link; - EFI_PHYSICAL_ADDRESS BaseAddress; - UINTN BitsOfAlignment; - UINT64 Alignment; - EFI_STATUS Status; - EFI_STATUS ReturnStatus; - PCI_RESOURCE_TYPE Index; - PCI_RESOURCE_TYPE Index1; - PCI_RESOURCE_TYPE Index2; - BOOLEAN ResNodeHandled[TypeMax]; - UINT64 MaxAlignment; - UINT64 Translation; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + LIST_ENTRY *Link; + EFI_PHYSICAL_ADDRESS BaseAddress; + UINTN BitsOfAlignment; + UINT64 Alignment; + EFI_STATUS Status; + EFI_STATUS ReturnStatus; + PCI_RESOURCE_TYPE Index; + PCI_RESOURCE_TYPE Index1; + PCI_RESOURCE_TYPE Index2; + BOOLEAN ResNodeHandled[TypeMax]; + UINT64 MaxAlignment; + UINT64 Translation; HostBridge = PCI_HOST_BRIDGE_FROM_THIS (This); switch (Phase) { - case EfiPciHostBridgeBeginEnumeration: - if (!HostBridge->CanRestarted) { - return EFI_NOT_READY; - } - // - // Reset Root Bridge - // - for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); - for (Index = TypeIo; Index < TypeMax; Index++) { - RootBridge->ResAllocNode[Index].Type = Index; - RootBridge->ResAllocNode[Index].Base = 0; - RootBridge->ResAllocNode[Index].Length = 0; - RootBridge->ResAllocNode[Index].Status = ResNone; - - RootBridge->ResourceSubmitted = FALSE; + case EfiPciHostBridgeBeginEnumeration: + if (!HostBridge->CanRestarted) { + return EFI_NOT_READY; } - } - HostBridge->CanRestarted = TRUE; - break; + // + // Reset Root Bridge + // + for (Link = GetFirstNode (&HostBridge->RootBridges) + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + for (Index = TypeIo; Index < TypeMax; Index++) { + RootBridge->ResAllocNode[Index].Type = Index; + RootBridge->ResAllocNode[Index].Base = 0; + RootBridge->ResAllocNode[Index].Length = 0; + RootBridge->ResAllocNode[Index].Status = ResNone; + + RootBridge->ResourceSubmitted = FALSE; + } + } - case EfiPciHostBridgeBeginBusAllocation: - // - // No specific action is required here, can perform any chipset specific programing - // - HostBridge->CanRestarted = FALSE; - break; + HostBridge->CanRestarted = TRUE; + break; - case EfiPciHostBridgeEndBusAllocation: - // - // No specific action is required here, can perform any chipset specific programing - // - break; + case EfiPciHostBridgeBeginBusAllocation: + // + // No specific action is required here, can perform any chipset specific programing + // + HostBridge->CanRestarted = FALSE; + break; - case EfiPciHostBridgeBeginResourceAllocation: - // - // No specific action is required here, can perform any chipset specific programing - // - break; + case EfiPciHostBridgeEndBusAllocation: + // + // No specific action is required here, can perform any chipset specific programing + // + break; - case EfiPciHostBridgeAllocateResources: - ReturnStatus = EFI_SUCCESS; + case EfiPciHostBridgeBeginResourceAllocation: + // + // No specific action is required here, can perform any chipset specific programing + // + break; - // - // Make sure the resource for all root bridges has been submitted. - // - for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); - if (!RootBridge->ResourceSubmitted) { - return EFI_NOT_READY; - } - } + case EfiPciHostBridgeAllocateResources: + ReturnStatus = EFI_SUCCESS; - DEBUG ((DEBUG_INFO, "PciHostBridge: NotifyPhase (AllocateResources)\n")); - for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - for (Index = TypeIo; Index < TypeBus; Index++) { - ResNodeHandled[Index] = FALSE; + // + // Make sure the resource for all root bridges has been submitted. + // + for (Link = GetFirstNode (&HostBridge->RootBridges) + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + if (!RootBridge->ResourceSubmitted) { + return EFI_NOT_READY; + } } - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); - DEBUG ((DEBUG_INFO, " RootBridge: %s\n", RootBridge->DevicePathStr)); - - for (Index1 = TypeIo; Index1 < TypeBus; Index1++) { - if (RootBridge->ResAllocNode[Index1].Status == ResNone) { - ResNodeHandled[Index1] = TRUE; - } else { - // - // Allocate the resource node with max alignment at first - // - MaxAlignment = 0; - Index = TypeMax; - for (Index2 = TypeIo; Index2 < TypeBus; Index2++) { - if (ResNodeHandled[Index2]) { - continue; - } - if (MaxAlignment <= RootBridge->ResAllocNode[Index2].Alignment) { - MaxAlignment = RootBridge->ResAllocNode[Index2].Alignment; - Index = Index2; - } - } + DEBUG ((DEBUG_INFO, "PciHostBridge: NotifyPhase (AllocateResources)\n")); + for (Link = GetFirstNode (&HostBridge->RootBridges) + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { + for (Index = TypeIo; Index < TypeBus; Index++) { + ResNodeHandled[Index] = FALSE; + } - ASSERT (Index < TypeMax); - ResNodeHandled[Index] = TRUE; - Alignment = RootBridge->ResAllocNode[Index].Alignment; - BitsOfAlignment = LowBitSet64 (Alignment + 1); - BaseAddress = MAX_UINT64; + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + DEBUG ((DEBUG_INFO, " RootBridge: %s\n", RootBridge->DevicePathStr)); - // - // RESTRICTION: To simplify the situation, we require the alignment of - // Translation must be larger than any BAR alignment in the same root - // bridge, so that resource allocation alignment can be applied to - // both device address and host address. - // - Translation = GetTranslationByResourceType (RootBridge, Index); - if ((Translation & Alignment) != 0) { - DEBUG ((DEBUG_ERROR, "[%a:%d] Translation %lx is not aligned to %lx!\n", - __FUNCTION__, DEBUG_LINE_NUMBER, Translation, Alignment - )); - ASSERT ((Translation & Alignment) == 0); + for (Index1 = TypeIo; Index1 < TypeBus; Index1++) { + if (RootBridge->ResAllocNode[Index1].Status == ResNone) { + ResNodeHandled[Index1] = TRUE; + } else { // - // This may be caused by too large alignment or too small - // Translation; pick the 1st possibility and return out of resource, - // which can also go thru the same process for out of resource - // outside the loop. + // Allocate the resource node with max alignment at first // - ReturnStatus = EFI_OUT_OF_RESOURCES; - continue; - } + MaxAlignment = 0; + Index = TypeMax; + for (Index2 = TypeIo; Index2 < TypeBus; Index2++) { + if (ResNodeHandled[Index2]) { + continue; + } + + if (MaxAlignment <= RootBridge->ResAllocNode[Index2].Alignment) { + MaxAlignment = RootBridge->ResAllocNode[Index2].Alignment; + Index = Index2; + } + } - switch (Index) { - case TypeIo: - // - // Base and Limit in PCI_ROOT_BRIDGE_APERTURE are device address. - // For AllocateResource is manipulating GCD resource, we need to use - // host address here. - // - BaseAddress = AllocateResource ( - FALSE, - RootBridge->ResAllocNode[Index].Length, - MIN (15, BitsOfAlignment), - TO_HOST_ADDRESS (ALIGN_VALUE (RootBridge->Io.Base, Alignment + 1), - RootBridge->Io.Translation), - TO_HOST_ADDRESS (RootBridge->Io.Limit, - RootBridge->Io.Translation) - ); - break; + ASSERT (Index < TypeMax); + ResNodeHandled[Index] = TRUE; + Alignment = RootBridge->ResAllocNode[Index].Alignment; + BitsOfAlignment = LowBitSet64 (Alignment + 1); + BaseAddress = MAX_UINT64; - case TypeMem64: - BaseAddress = AllocateResource ( - TRUE, - RootBridge->ResAllocNode[Index].Length, - MIN (63, BitsOfAlignment), - TO_HOST_ADDRESS (ALIGN_VALUE (RootBridge->MemAbove4G.Base, Alignment + 1), - RootBridge->MemAbove4G.Translation), - TO_HOST_ADDRESS (RootBridge->MemAbove4G.Limit, - RootBridge->MemAbove4G.Translation) - ); - if (BaseAddress != MAX_UINT64) { - break; - } // - // If memory above 4GB is not available, try memory below 4GB + // RESTRICTION: To simplify the situation, we require the alignment of + // Translation must be larger than any BAR alignment in the same root + // bridge, so that resource allocation alignment can be applied to + // both device address and host address. // + Translation = GetTranslationByResourceType (RootBridge, Index); + if ((Translation & Alignment) != 0) { + DEBUG (( + DEBUG_ERROR, + "[%a:%d] Translation %lx is not aligned to %lx!\n", + __FUNCTION__, + DEBUG_LINE_NUMBER, + Translation, + Alignment + )); + ASSERT ((Translation & Alignment) == 0); + // + // This may be caused by too large alignment or too small + // Translation; pick the 1st possibility and return out of resource, + // which can also go thru the same process for out of resource + // outside the loop. + // + ReturnStatus = EFI_OUT_OF_RESOURCES; + continue; + } - case TypeMem32: - BaseAddress = AllocateResource ( - TRUE, - RootBridge->ResAllocNode[Index].Length, - MIN (31, BitsOfAlignment), - TO_HOST_ADDRESS (ALIGN_VALUE (RootBridge->Mem.Base, Alignment + 1), - RootBridge->Mem.Translation), - TO_HOST_ADDRESS (RootBridge->Mem.Limit, - RootBridge->Mem.Translation) - ); - break; + switch (Index) { + case TypeIo: + // + // Base and Limit in PCI_ROOT_BRIDGE_APERTURE are device address. + // For AllocateResource is manipulating GCD resource, we need to use + // host address here. + // + BaseAddress = AllocateResource ( + FALSE, + RootBridge->ResAllocNode[Index].Length, + MIN (15, BitsOfAlignment), + TO_HOST_ADDRESS ( + ALIGN_VALUE (RootBridge->Io.Base, Alignment + 1), + RootBridge->Io.Translation + ), + TO_HOST_ADDRESS ( + RootBridge->Io.Limit, + RootBridge->Io.Translation + ) + ); + break; + + case TypeMem64: + BaseAddress = AllocateResource ( + TRUE, + RootBridge->ResAllocNode[Index].Length, + MIN (63, BitsOfAlignment), + TO_HOST_ADDRESS ( + ALIGN_VALUE (RootBridge->MemAbove4G.Base, Alignment + 1), + RootBridge->MemAbove4G.Translation + ), + TO_HOST_ADDRESS ( + RootBridge->MemAbove4G.Limit, + RootBridge->MemAbove4G.Translation + ) + ); + if (BaseAddress != MAX_UINT64) { + break; + } + + // + // If memory above 4GB is not available, try memory below 4GB + // + + case TypeMem32: + BaseAddress = AllocateResource ( + TRUE, + RootBridge->ResAllocNode[Index].Length, + MIN (31, BitsOfAlignment), + TO_HOST_ADDRESS ( + ALIGN_VALUE (RootBridge->Mem.Base, Alignment + 1), + RootBridge->Mem.Translation + ), + TO_HOST_ADDRESS ( + RootBridge->Mem.Limit, + RootBridge->Mem.Translation + ) + ); + break; + + case TypePMem64: + BaseAddress = AllocateResource ( + TRUE, + RootBridge->ResAllocNode[Index].Length, + MIN (63, BitsOfAlignment), + TO_HOST_ADDRESS ( + ALIGN_VALUE (RootBridge->PMemAbove4G.Base, Alignment + 1), + RootBridge->PMemAbove4G.Translation + ), + TO_HOST_ADDRESS ( + RootBridge->PMemAbove4G.Limit, + RootBridge->PMemAbove4G.Translation + ) + ); + if (BaseAddress != MAX_UINT64) { + break; + } + + // + // If memory above 4GB is not available, try memory below 4GB + // + case TypePMem32: + BaseAddress = AllocateResource ( + TRUE, + RootBridge->ResAllocNode[Index].Length, + MIN (31, BitsOfAlignment), + TO_HOST_ADDRESS ( + ALIGN_VALUE (RootBridge->PMem.Base, Alignment + 1), + RootBridge->PMem.Translation + ), + TO_HOST_ADDRESS ( + RootBridge->PMem.Limit, + RootBridge->PMem.Translation + ) + ); + break; + + default: + ASSERT (FALSE); + break; + } - case TypePMem64: - BaseAddress = AllocateResource ( - TRUE, - RootBridge->ResAllocNode[Index].Length, - MIN (63, BitsOfAlignment), - TO_HOST_ADDRESS (ALIGN_VALUE (RootBridge->PMemAbove4G.Base, Alignment + 1), - RootBridge->PMemAbove4G.Translation), - TO_HOST_ADDRESS (RootBridge->PMemAbove4G.Limit, - RootBridge->PMemAbove4G.Translation) - ); + DEBUG (( + DEBUG_INFO, + " %s: Base/Length/Alignment = %lx/%lx/%lx - ", + mPciResourceTypeStr[Index], + BaseAddress, + RootBridge->ResAllocNode[Index].Length, + Alignment + )); if (BaseAddress != MAX_UINT64) { - break; + RootBridge->ResAllocNode[Index].Base = BaseAddress; + RootBridge->ResAllocNode[Index].Status = ResAllocated; + DEBUG ((DEBUG_INFO, "Success\n")); + } else { + ReturnStatus = EFI_OUT_OF_RESOURCES; + DEBUG ((DEBUG_ERROR, "Out Of Resource!\n")); } - // - // If memory above 4GB is not available, try memory below 4GB - // - case TypePMem32: - BaseAddress = AllocateResource ( - TRUE, - RootBridge->ResAllocNode[Index].Length, - MIN (31, BitsOfAlignment), - TO_HOST_ADDRESS (ALIGN_VALUE (RootBridge->PMem.Base, Alignment + 1), - RootBridge->PMem.Translation), - TO_HOST_ADDRESS (RootBridge->PMem.Limit, - RootBridge->PMem.Translation) - ); - break; - - default: - ASSERT (FALSE); - break; - } - - DEBUG ((DEBUG_INFO, " %s: Base/Length/Alignment = %lx/%lx/%lx - ", - mPciResourceTypeStr[Index], BaseAddress, RootBridge->ResAllocNode[Index].Length, Alignment)); - if (BaseAddress != MAX_UINT64) { - RootBridge->ResAllocNode[Index].Base = BaseAddress; - RootBridge->ResAllocNode[Index].Status = ResAllocated; - DEBUG ((DEBUG_INFO, "Success\n")); - } else { - ReturnStatus = EFI_OUT_OF_RESOURCES; - DEBUG ((DEBUG_ERROR, "Out Of Resource!\n")); } } } - } - if (ReturnStatus == EFI_OUT_OF_RESOURCES) { - ResourceConflict (HostBridge); - } + if (ReturnStatus == EFI_OUT_OF_RESOURCES) { + ResourceConflict (HostBridge); + } - // - // Set resource to zero for nodes where allocation fails - // - for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); - for (Index = TypeIo; Index < TypeBus; Index++) { - if (RootBridge->ResAllocNode[Index].Status != ResAllocated) { - RootBridge->ResAllocNode[Index].Length = 0; + // + // Set resource to zero for nodes where allocation fails + // + for (Link = GetFirstNode (&HostBridge->RootBridges) + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + for (Index = TypeIo; Index < TypeBus; Index++) { + if (RootBridge->ResAllocNode[Index].Status != ResAllocated) { + RootBridge->ResAllocNode[Index].Length = 0; + } } } - } - return ReturnStatus; - case EfiPciHostBridgeSetResources: - // - // HostBridgeInstance->CanRestarted = FALSE; - // - break; + return ReturnStatus; - case EfiPciHostBridgeFreeResources: - // - // HostBridgeInstance->CanRestarted = FALSE; - // - ReturnStatus = EFI_SUCCESS; - for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { - RootBridge = ROOT_BRIDGE_FROM_LINK (Link); - for (Index = TypeIo; Index < TypeBus; Index++) { - if (RootBridge->ResAllocNode[Index].Status == ResAllocated) { - switch (Index) { - case TypeIo: - Status = gDS->FreeIoSpace (RootBridge->ResAllocNode[Index].Base, RootBridge->ResAllocNode[Index].Length); - if (EFI_ERROR (Status)) { - ReturnStatus = Status; - } - break; + case EfiPciHostBridgeSetResources: + // + // HostBridgeInstance->CanRestarted = FALSE; + // + break; - case TypeMem32: - case TypePMem32: - case TypeMem64: - case TypePMem64: - Status = gDS->FreeMemorySpace (RootBridge->ResAllocNode[Index].Base, RootBridge->ResAllocNode[Index].Length); - if (EFI_ERROR (Status)) { - ReturnStatus = Status; + case EfiPciHostBridgeFreeResources: + // + // HostBridgeInstance->CanRestarted = FALSE; + // + ReturnStatus = EFI_SUCCESS; + for (Link = GetFirstNode (&HostBridge->RootBridges) + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { + RootBridge = ROOT_BRIDGE_FROM_LINK (Link); + for (Index = TypeIo; Index < TypeBus; Index++) { + if (RootBridge->ResAllocNode[Index].Status == ResAllocated) { + switch (Index) { + case TypeIo: + Status = gDS->FreeIoSpace (RootBridge->ResAllocNode[Index].Base, RootBridge->ResAllocNode[Index].Length); + if (EFI_ERROR (Status)) { + ReturnStatus = Status; + } + + break; + + case TypeMem32: + case TypePMem32: + case TypeMem64: + case TypePMem64: + Status = gDS->FreeMemorySpace (RootBridge->ResAllocNode[Index].Base, RootBridge->ResAllocNode[Index].Length); + if (EFI_ERROR (Status)) { + ReturnStatus = Status; + } + + break; + + default: + ASSERT (FALSE); + break; } - break; - default: - ASSERT (FALSE); - break; + RootBridge->ResAllocNode[Index].Type = Index; + RootBridge->ResAllocNode[Index].Base = 0; + RootBridge->ResAllocNode[Index].Length = 0; + RootBridge->ResAllocNode[Index].Status = ResNone; } - - RootBridge->ResAllocNode[Index].Type = Index; - RootBridge->ResAllocNode[Index].Base = 0; - RootBridge->ResAllocNode[Index].Length = 0; - RootBridge->ResAllocNode[Index].Status = ResNone; } - } - RootBridge->ResourceSubmitted = FALSE; - } + RootBridge->ResourceSubmitted = FALSE; + } - HostBridge->CanRestarted = TRUE; - return ReturnStatus; + HostBridge->CanRestarted = TRUE; + return ReturnStatus; - case EfiPciHostBridgeEndResourceAllocation: - // - // The resource allocation phase is completed. No specific action is required - // here. This notification can be used to perform any chipset specific programming. - // - break; + case EfiPciHostBridgeEndResourceAllocation: + // + // The resource allocation phase is completed. No specific action is required + // here. This notification can be used to perform any chipset specific programming. + // + break; - case EfiPciHostBridgeEndEnumeration: - // - // The Host Bridge Enumeration is completed. No specific action is required here. - // This notification can be used to perform any chipset specific programming. - // - break; + case EfiPciHostBridgeEndEnumeration: + // + // The Host Bridge Enumeration is completed. No specific action is required here. + // This notification can be used to perform any chipset specific programming. + // + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; @@ -1095,8 +1212,8 @@ NotifyPhase ( EFI_STATUS EFIAPI GetNextRootBridge ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN OUT EFI_HANDLE *RootBridgeHandle + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN OUT EFI_HANDLE *RootBridgeHandle ) { BOOLEAN ReturnNext; @@ -1109,19 +1226,20 @@ GetNextRootBridge ( } HostBridge = PCI_HOST_BRIDGE_FROM_THIS (This); - ReturnNext = (BOOLEAN) (*RootBridgeHandle == NULL); + ReturnNext = (BOOLEAN)(*RootBridgeHandle == NULL); for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (ReturnNext) { *RootBridgeHandle = RootBridge->Handle; return EFI_SUCCESS; } - ReturnNext = (BOOLEAN) (*RootBridgeHandle == RootBridge->Handle); + ReturnNext = (BOOLEAN)(*RootBridgeHandle == RootBridge->Handle); } if (ReturnNext) { @@ -1151,9 +1269,9 @@ GetNextRootBridge ( EFI_STATUS EFIAPI GetAttributes ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT UINT64 *Attributes + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT UINT64 *Attributes ) { LIST_ENTRY *Link; @@ -1166,9 +1284,10 @@ GetAttributes ( HostBridge = PCI_HOST_BRIDGE_FROM_THIS (This); for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { *Attributes = RootBridge->AllocationAttributes; @@ -1196,16 +1315,16 @@ GetAttributes ( EFI_STATUS EFIAPI StartBusEnumeration ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT VOID **Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT VOID **Configuration ) { - LIST_ENTRY *Link; - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; + LIST_ENTRY *Link; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; if (Configuration == NULL) { return EFI_INVALID_PARAMETER; @@ -1215,7 +1334,8 @@ StartBusEnumeration ( for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { *Configuration = AllocatePool (sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR)); @@ -1223,7 +1343,7 @@ StartBusEnumeration ( return EFI_OUT_OF_RESOURCES; } - Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) *Configuration; + Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)*Configuration; Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor->Len = sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_BUS; @@ -1235,8 +1355,8 @@ StartBusEnumeration ( Descriptor->AddrTranslationOffset = 0; Descriptor->AddrLen = RootBridge->Bus.Limit - RootBridge->Bus.Base + 1; - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) (Descriptor + 1); - End->Desc = ACPI_END_TAG_DESCRIPTOR; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)(Descriptor + 1); + End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0x0; return EFI_SUCCESS; @@ -1262,23 +1382,23 @@ StartBusEnumeration ( EFI_STATUS EFIAPI SetBusNumbers ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN VOID *Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN VOID *Configuration ) { - LIST_ENTRY *Link; - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; + LIST_ENTRY *Link; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; if (Configuration == NULL) { return EFI_INVALID_PARAMETER; } - Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) (Descriptor + 1); + Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)(Descriptor + 1); // // Check the Configuration is valid @@ -1286,7 +1406,8 @@ SetBusNumbers ( if ((Descriptor->Desc != ACPI_ADDRESS_SPACE_DESCRIPTOR) || (Descriptor->ResType != ACPI_ADDRESS_SPACE_TYPE_BUS) || (End->Desc != ACPI_END_TAG_DESCRIPTOR) - ) { + ) + { return EFI_INVALID_PARAMETER; } @@ -1294,25 +1415,27 @@ SetBusNumbers ( for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { - if (Descriptor->AddrLen == 0) { return EFI_INVALID_PARAMETER; } if ((Descriptor->AddrRangeMin < RootBridge->Bus.Base) || (Descriptor->AddrRangeMin + Descriptor->AddrLen - 1 > RootBridge->Bus.Limit) - ) { + ) + { return EFI_INVALID_PARAMETER; } + // // Update the Bus Range // - RootBridge->ResAllocNode[TypeBus].Base = Descriptor->AddrRangeMin; - RootBridge->ResAllocNode[TypeBus].Length = Descriptor->AddrLen; - RootBridge->ResAllocNode[TypeBus].Status = ResAllocated; + RootBridge->ResAllocNode[TypeBus].Base = Descriptor->AddrRangeMin; + RootBridge->ResAllocNode[TypeBus].Length = Descriptor->AddrLen; + RootBridge->ResAllocNode[TypeBus].Status = ResAllocated; return EFI_SUCCESS; } } @@ -1335,16 +1458,16 @@ SetBusNumbers ( EFI_STATUS EFIAPI SubmitResources ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN VOID *Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN VOID *Configuration ) { - LIST_ENTRY *Link; - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - PCI_RESOURCE_TYPE Type; + LIST_ENTRY *Link; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + PCI_RESOURCE_TYPE Type; // // Check the input parameter: Configuration @@ -1357,7 +1480,8 @@ SubmitResources ( for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { DEBUG ((DEBUG_INFO, "PciHostBridge: SubmitResources for %s\n", RootBridge->DevicePathStr)); @@ -1366,52 +1490,62 @@ SubmitResources ( // If the Configuration includes one or more invalid resource descriptors, all the resource // descriptors are ignored and the function returns EFI_INVALID_PARAMETER. // - for (Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { + for (Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { if (Descriptor->ResType > ACPI_ADDRESS_SPACE_TYPE_BUS) { return EFI_INVALID_PARAMETER; } - DEBUG ((DEBUG_INFO, " %s: Granularity/SpecificFlag = %ld / %02x%s\n", - mAcpiAddressSpaceTypeStr[Descriptor->ResType], Descriptor->AddrSpaceGranularity, Descriptor->SpecificFlag, - (Descriptor->SpecificFlag & EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0 ? L" (Prefetchable)" : L"" - )); + DEBUG (( + DEBUG_INFO, + " %s: Granularity/SpecificFlag = %ld / %02x%s\n", + mAcpiAddressSpaceTypeStr[Descriptor->ResType], + Descriptor->AddrSpaceGranularity, + Descriptor->SpecificFlag, + (Descriptor->SpecificFlag & EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0 ? L" (Prefetchable)" : L"" + )); DEBUG ((DEBUG_INFO, " Length/Alignment = 0x%lx / 0x%lx\n", Descriptor->AddrLen, Descriptor->AddrRangeMax)); switch (Descriptor->ResType) { - case ACPI_ADDRESS_SPACE_TYPE_MEM: - if (Descriptor->AddrSpaceGranularity != 32 && Descriptor->AddrSpaceGranularity != 64) { - return EFI_INVALID_PARAMETER; - } - if (Descriptor->AddrSpaceGranularity == 32 && Descriptor->AddrLen >= SIZE_4GB) { - return EFI_INVALID_PARAMETER; - } - // - // If the PCI root bridge does not support separate windows for nonprefetchable and - // prefetchable memory, then the PCI bus driver needs to include requests for - // prefetchable memory in the nonprefetchable memory pool. - // - if (((RootBridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM) != 0) && - ((Descriptor->SpecificFlag & EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0) - ) { - return EFI_INVALID_PARAMETER; - } - case ACPI_ADDRESS_SPACE_TYPE_IO: - // - // Check aligment, it should be of the form 2^n-1 - // - if (GetPowerOfTwo64 (Descriptor->AddrRangeMax + 1) != (Descriptor->AddrRangeMax + 1)) { - return EFI_INVALID_PARAMETER; - } - break; - default: - ASSERT (FALSE); - break; + case ACPI_ADDRESS_SPACE_TYPE_MEM: + if ((Descriptor->AddrSpaceGranularity != 32) && (Descriptor->AddrSpaceGranularity != 64)) { + return EFI_INVALID_PARAMETER; + } + + if ((Descriptor->AddrSpaceGranularity == 32) && (Descriptor->AddrLen >= SIZE_4GB)) { + return EFI_INVALID_PARAMETER; + } + + // + // If the PCI root bridge does not support separate windows for nonprefetchable and + // prefetchable memory, then the PCI bus driver needs to include requests for + // prefetchable memory in the nonprefetchable memory pool. + // + if (((RootBridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM) != 0) && + ((Descriptor->SpecificFlag & EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0) + ) + { + return EFI_INVALID_PARAMETER; + } + + case ACPI_ADDRESS_SPACE_TYPE_IO: + // + // Check aligment, it should be of the form 2^n-1 + // + if (GetPowerOfTwo64 (Descriptor->AddrRangeMax + 1) != (Descriptor->AddrRangeMax + 1)) { + return EFI_INVALID_PARAMETER; + } + + break; + default: + ASSERT (FALSE); + break; } } + if (Descriptor->Desc != ACPI_END_TAG_DESCRIPTOR) { return EFI_INVALID_PARAMETER; } - for (Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { + for (Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { if (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { if (Descriptor->AddrSpaceGranularity == 32) { if ((Descriptor->SpecificFlag & EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE) != 0) { @@ -1431,10 +1565,12 @@ SubmitResources ( ASSERT (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_IO); Type = TypeIo; } + RootBridge->ResAllocNode[Type].Length = Descriptor->AddrLen; RootBridge->ResAllocNode[Type].Alignment = Descriptor->AddrRangeMax; RootBridge->ResAllocNode[Type].Status = ResSubmitted; } + RootBridge->ResourceSubmitted = TRUE; return EFI_SUCCESS; } @@ -1461,26 +1597,27 @@ SubmitResources ( EFI_STATUS EFIAPI GetProposedResources ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT VOID **Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT VOID **Configuration ) { - LIST_ENTRY *Link; - PCI_HOST_BRIDGE_INSTANCE *HostBridge; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - UINTN Index; - UINTN Number; - VOID *Buffer; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; - UINT64 ResStatus; + LIST_ENTRY *Link; + PCI_HOST_BRIDGE_INSTANCE *HostBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + UINTN Index; + UINTN Number; + VOID *Buffer; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; + UINT64 ResStatus; HostBridge = PCI_HOST_BRIDGE_FROM_THIS (This); for (Link = GetFirstNode (&HostBridge->RootBridges) - ; !IsNull (&HostBridge->RootBridges, Link) - ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ; !IsNull (&HostBridge->RootBridges, Link) + ; Link = GetNextNode (&HostBridge->RootBridges, Link) + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { for (Index = 0, Number = 0; Index < TypeBus; Index++) { @@ -1494,52 +1631,54 @@ GetProposedResources ( return EFI_OUT_OF_RESOURCES; } - Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Buffer; + Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Buffer; for (Index = 0; Index < TypeBus; Index++) { ResStatus = RootBridge->ResAllocNode[Index].Status; if (ResStatus != ResNone) { - Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; - Descriptor->Len = sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3;; - Descriptor->GenFlag = 0; + Descriptor->Desc = ACPI_ADDRESS_SPACE_DESCRIPTOR; + Descriptor->Len = sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) - 3; + Descriptor->GenFlag = 0; // // AddrRangeMin in Resource Descriptor here should be device address // instead of host address, or else PCI bus driver cannot set correct // address into PCI BAR registers. // Base in ResAllocNode is a host address, so conversion is needed. // - Descriptor->AddrRangeMin = TO_DEVICE_ADDRESS (RootBridge->ResAllocNode[Index].Base, - GetTranslationByResourceType (RootBridge, Index)); + Descriptor->AddrRangeMin = TO_DEVICE_ADDRESS ( + RootBridge->ResAllocNode[Index].Base, + GetTranslationByResourceType (RootBridge, Index) + ); Descriptor->AddrRangeMax = 0; Descriptor->AddrTranslationOffset = (ResStatus == ResAllocated) ? EFI_RESOURCE_SATISFIED : PCI_RESOURCE_LESS; Descriptor->AddrLen = RootBridge->ResAllocNode[Index].Length; switch (Index) { + case TypeIo: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; + break; - case TypeIo: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; - break; - - case TypePMem32: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem32: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 32; - break; + case TypePMem32: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem32: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 32; + break; - case TypePMem64: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem64: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 64; - break; + case TypePMem64: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem64: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 64; + break; } Descriptor++; } } - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) Descriptor; - End->Desc = ACPI_END_TAG_DESCRIPTOR; - End->Checksum = 0; + + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor; + End->Desc = ACPI_END_TAG_DESCRIPTOR; + End->Checksum = 0; *Configuration = Buffer; @@ -1567,17 +1706,17 @@ GetProposedResources ( EFI_STATUS EFIAPI PreprocessController ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS PciAddress, - IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS PciAddress, + IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase ) { LIST_ENTRY *Link; PCI_HOST_BRIDGE_INSTANCE *HostBridge; PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - if ((UINT32) Phase > EfiPciBeforeResourceCollection) { + if ((UINT32)Phase > EfiPciBeforeResourceCollection) { return EFI_INVALID_PARAMETER; } @@ -1585,7 +1724,8 @@ PreprocessController ( for (Link = GetFirstNode (&HostBridge->RootBridges) ; !IsNull (&HostBridge->RootBridges, Link) ; Link = GetNextNode (&HostBridge->RootBridges, Link) - ) { + ) + { RootBridge = ROOT_BRIDGE_FROM_LINK (Link); if (RootBridgeHandle == RootBridge->Handle) { return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.h b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.h index 755ab75b19..e7a30fd909 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.h +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridge.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PCI_HOST_BRIDGE_H_ #define _PCI_HOST_BRIDGE_H_ - #include #include #include @@ -21,27 +20,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciRootBridge.h" -#define PCI_HOST_BRIDGE_SIGNATURE SIGNATURE_32 ('p', 'h', 'b', 'g') +#define PCI_HOST_BRIDGE_SIGNATURE SIGNATURE_32 ('p', 'h', 'b', 'g') typedef struct { - UINTN Signature; - EFI_HANDLE Handle; - LIST_ENTRY RootBridges; - BOOLEAN CanRestarted; - EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL ResAlloc; + UINTN Signature; + EFI_HANDLE Handle; + LIST_ENTRY RootBridges; + BOOLEAN CanRestarted; + EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL ResAlloc; } PCI_HOST_BRIDGE_INSTANCE; -#define PCI_HOST_BRIDGE_FROM_THIS(a) CR (a, PCI_HOST_BRIDGE_INSTANCE, ResAlloc, PCI_HOST_BRIDGE_SIGNATURE) +#define PCI_HOST_BRIDGE_FROM_THIS(a) CR (a, PCI_HOST_BRIDGE_INSTANCE, ResAlloc, PCI_HOST_BRIDGE_SIGNATURE) // // Macros to translate device address to host address and vice versa. According // to UEFI 2.7, device address = host address + translation offset. // -#define TO_HOST_ADDRESS(DeviceAddress,TranslationOffset) ((DeviceAddress) - (TranslationOffset)) -#define TO_DEVICE_ADDRESS(HostAddress,TranslationOffset) ((HostAddress) + (TranslationOffset)) +#define TO_HOST_ADDRESS(DeviceAddress, TranslationOffset) ((DeviceAddress) - (TranslationOffset)) +#define TO_DEVICE_ADDRESS(HostAddress, TranslationOffset) ((HostAddress) + (TranslationOffset)) // // Driver Entry Point // + /** Entry point of this driver. @@ -56,13 +56,14 @@ typedef struct { EFI_STATUS EFIAPI InitializePciHostBridge ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); // // HostBridge Resource Allocation interface // + /** Enter a certain phase of the PCI enumeration process. @@ -78,8 +79,8 @@ InitializePciHostBridge ( EFI_STATUS EFIAPI NotifyPhase ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PHASE Phase ); /** @@ -101,8 +102,8 @@ NotifyPhase ( EFI_STATUS EFIAPI GetNextRootBridge ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN OUT EFI_HANDLE *RootBridgeHandle + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN OUT EFI_HANDLE *RootBridgeHandle ); /** @@ -124,9 +125,9 @@ GetNextRootBridge ( EFI_STATUS EFIAPI GetAttributes ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT UINT64 *Attributes + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT UINT64 *Attributes ); /** @@ -146,9 +147,9 @@ GetAttributes ( EFI_STATUS EFIAPI StartBusEnumeration ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT VOID **Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT VOID **Configuration ); /** @@ -167,9 +168,9 @@ StartBusEnumeration ( EFI_STATUS EFIAPI SetBusNumbers ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN VOID *Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN VOID *Configuration ); /** @@ -188,9 +189,9 @@ SetBusNumbers ( EFI_STATUS EFIAPI SubmitResources ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN VOID *Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN VOID *Configuration ); /** @@ -211,9 +212,9 @@ SubmitResources ( EFI_STATUS EFIAPI GetProposedResources ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - OUT VOID **Configuration + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + OUT VOID **Configuration ); /** @@ -233,10 +234,10 @@ GetProposedResources ( EFI_STATUS EFIAPI PreprocessController ( - IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, - IN EFI_HANDLE RootBridgeHandle, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS PciAddress, - IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase + IN EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL *This, + IN EFI_HANDLE RootBridgeHandle, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS PciAddress, + IN EFI_PCI_CONTROLLER_RESOURCE_ALLOCATION_PHASE Phase ); /** @@ -246,7 +247,7 @@ PreprocessController ( **/ VOID ResourceConflict ( - IN PCI_HOST_BRIDGE_INSTANCE *HostBridge + IN PCI_HOST_BRIDGE_INSTANCE *HostBridge ); /** @@ -259,11 +260,11 @@ ResourceConflict ( **/ UINT64 GetTranslationByResourceType ( - IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, - IN PCI_RESOURCE_TYPE ResourceType + IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, + IN PCI_RESOURCE_TYPE ResourceType ); -extern EFI_CPU_IO2_PROTOCOL *mCpuIo; -extern EDKII_IOMMU_PROTOCOL *mIoMmu; +extern EFI_CPU_IO2_PROTOCOL *mCpuIo; +extern EDKII_IOMMU_PROTOCOL *mIoMmu; #endif diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostResource.h b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostResource.h index 0f5a17d55a..772f4b513f 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostResource.h +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostResource.h @@ -6,15 +6,16 @@ Copyright (c) 1999 - 2016, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef _PCI_HOST_RESOURCE_H_ #define _PCI_HOST_RESOURCE_H_ #include -#define PCI_RESOURCE_LESS 0xFFFFFFFFFFFFFFFEULL +#define PCI_RESOURCE_LESS 0xFFFFFFFFFFFFFFFEULL typedef enum { - TypeIo = 0, + TypeIo = 0, TypeMem32, TypePMem32, TypeMem64, @@ -31,14 +32,14 @@ typedef enum { } RES_STATUS; typedef struct { - PCI_RESOURCE_TYPE Type; + PCI_RESOURCE_TYPE Type; // // Base is a host address // - UINT64 Base; - UINT64 Length; - UINT64 Alignment; - RES_STATUS Status; + UINT64 Base; + UINT64 Length; + UINT64 Alignment; + RES_STATUS Status; } PCI_RES_NODE; #endif diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridge.h b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridge.h index caa3faf00a..10a6200719 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridge.h +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridge.h @@ -31,7 +31,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "PciHostResource.h" - typedef enum { IoOperation, MemOperation, @@ -40,46 +39,46 @@ typedef enum { #define MAP_INFO_SIGNATURE SIGNATURE_32 ('_', 'm', 'a', 'p') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_OPERATION Operation; - UINTN NumberOfBytes; - UINTN NumberOfPages; - EFI_PHYSICAL_ADDRESS HostAddress; - EFI_PHYSICAL_ADDRESS MappedHostAddress; + UINT32 Signature; + LIST_ENTRY Link; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_OPERATION Operation; + UINTN NumberOfBytes; + UINTN NumberOfPages; + EFI_PHYSICAL_ADDRESS HostAddress; + EFI_PHYSICAL_ADDRESS MappedHostAddress; } MAP_INFO; -#define MAP_INFO_FROM_LINK(a) CR (a, MAP_INFO, Link, MAP_INFO_SIGNATURE) +#define MAP_INFO_FROM_LINK(a) CR (a, MAP_INFO, Link, MAP_INFO_SIGNATURE) -#define PCI_ROOT_BRIDGE_SIGNATURE SIGNATURE_32 ('_', 'p', 'r', 'b') +#define PCI_ROOT_BRIDGE_SIGNATURE SIGNATURE_32 ('_', 'p', 'r', 'b') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_HANDLE Handle; - UINT64 AllocationAttributes; - UINT64 Attributes; - UINT64 Supports; - PCI_RES_NODE ResAllocNode[TypeMax]; - PCI_ROOT_BRIDGE_APERTURE Bus; - PCI_ROOT_BRIDGE_APERTURE Io; - PCI_ROOT_BRIDGE_APERTURE Mem; - PCI_ROOT_BRIDGE_APERTURE PMem; - PCI_ROOT_BRIDGE_APERTURE MemAbove4G; - PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; - BOOLEAN DmaAbove4G; - BOOLEAN NoExtendedConfigSpace; - VOID *ConfigBuffer; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - CHAR16 *DevicePathStr; - EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL RootBridgeIo; - - BOOLEAN ResourceSubmitted; - LIST_ENTRY Maps; + UINT32 Signature; + LIST_ENTRY Link; + EFI_HANDLE Handle; + UINT64 AllocationAttributes; + UINT64 Attributes; + UINT64 Supports; + PCI_RES_NODE ResAllocNode[TypeMax]; + PCI_ROOT_BRIDGE_APERTURE Bus; + PCI_ROOT_BRIDGE_APERTURE Io; + PCI_ROOT_BRIDGE_APERTURE Mem; + PCI_ROOT_BRIDGE_APERTURE PMem; + PCI_ROOT_BRIDGE_APERTURE MemAbove4G; + PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; + BOOLEAN DmaAbove4G; + BOOLEAN NoExtendedConfigSpace; + VOID *ConfigBuffer; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + CHAR16 *DevicePathStr; + EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL RootBridgeIo; + + BOOLEAN ResourceSubmitted; + LIST_ENTRY Maps; } PCI_ROOT_BRIDGE_INSTANCE; -#define ROOT_BRIDGE_FROM_THIS(a) CR (a, PCI_ROOT_BRIDGE_INSTANCE, RootBridgeIo, PCI_ROOT_BRIDGE_SIGNATURE) +#define ROOT_BRIDGE_FROM_THIS(a) CR (a, PCI_ROOT_BRIDGE_INSTANCE, RootBridgeIo, PCI_ROOT_BRIDGE_SIGNATURE) -#define ROOT_BRIDGE_FROM_LINK(a) CR (a, PCI_ROOT_BRIDGE_INSTANCE, Link, PCI_ROOT_BRIDGE_SIGNATURE) +#define ROOT_BRIDGE_FROM_LINK(a) CR (a, PCI_ROOT_BRIDGE_INSTANCE, Link, PCI_ROOT_BRIDGE_SIGNATURE) /** Construct the Pci Root Bridge instance. @@ -91,12 +90,13 @@ typedef struct { **/ PCI_ROOT_BRIDGE_INSTANCE * CreateRootBridge ( - IN PCI_ROOT_BRIDGE *Bridge + IN PCI_ROOT_BRIDGE *Bridge ); // // Protocol Member Function Prototypes // + /** Poll an address in memory mapped space until an exit condition is met @@ -286,11 +286,11 @@ RootBridgeIoIoWrite ( EFI_STATUS EFIAPI RootBridgeIoCopyMem ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 DestAddress, - IN UINT64 SrcAddress, - IN UINTN Count + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 DestAddress, + IN UINT64 SrcAddress, + IN UINTN Count ) ; @@ -567,5 +567,5 @@ RootBridgeIoConfiguration ( ) ; -extern EFI_CPU_IO2_PROTOCOL *mCpuIo; +extern EFI_CPU_IO2_PROTOCOL *mCpuIo; #endif diff --git a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c index 2f1bed853d..157a0ada80 100644 --- a/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c +++ b/MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciRootBridgeIo.c @@ -13,12 +13,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define NO_MAPPING (VOID *) (UINTN) -1 -#define RESOURCE_VALID(Resource) ((Resource)->Base <= (Resource)->Limit) +#define RESOURCE_VALID(Resource) ((Resource)->Base <= (Resource)->Limit) // // Lookup table for increment values based on transfer widths // -UINT8 mInStride[] = { +UINT8 mInStride[] = { 1, // EfiPciWidthUint8 2, // EfiPciWidthUint16 4, // EfiPciWidthUint32 @@ -36,7 +36,7 @@ UINT8 mInStride[] = { // // Lookup table for increment values based on transfer widths // -UINT8 mOutStride[] = { +UINT8 mOutStride[] = { 1, // EfiPciWidthUint8 2, // EfiPciWidthUint16 4, // EfiPciWidthUint32 @@ -61,13 +61,13 @@ UINT8 mOutStride[] = { **/ PCI_ROOT_BRIDGE_INSTANCE * CreateRootBridge ( - IN PCI_ROOT_BRIDGE *Bridge + IN PCI_ROOT_BRIDGE *Bridge ) { - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - PCI_RESOURCE_TYPE Index; - CHAR16 *DevicePathStr; - PCI_ROOT_BRIDGE_APERTURE *Aperture; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + PCI_RESOURCE_TYPE Index; + CHAR16 *DevicePathStr; + PCI_ROOT_BRIDGE_APERTURE *Aperture; DevicePathStr = NULL; @@ -76,13 +76,19 @@ CreateRootBridge ( DEBUG ((DEBUG_INFO, " Support/Attr: %lx / %lx\n", Bridge->Supports, Bridge->Attributes)); DEBUG ((DEBUG_INFO, " DmaAbove4G: %s\n", Bridge->DmaAbove4G ? L"Yes" : L"No")); DEBUG ((DEBUG_INFO, "NoExtConfSpace: %s\n", Bridge->NoExtendedConfigSpace ? L"Yes" : L"No")); - DEBUG ((DEBUG_INFO, " AllocAttr: %lx (%s%s)\n", Bridge->AllocationAttributes, - (Bridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM) != 0 ? L"CombineMemPMem " : L"", - (Bridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_MEM64_DECODE) != 0 ? L"Mem64Decode" : L"" - )); DEBUG (( - DEBUG_INFO, " Bus: %lx - %lx Translation=%lx\n", - Bridge->Bus.Base, Bridge->Bus.Limit, Bridge->Bus.Translation + DEBUG_INFO, + " AllocAttr: %lx (%s%s)\n", + Bridge->AllocationAttributes, + (Bridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM) != 0 ? L"CombineMemPMem " : L"", + (Bridge->AllocationAttributes & EFI_PCI_HOST_BRIDGE_MEM64_DECODE) != 0 ? L"Mem64Decode" : L"" + )); + DEBUG (( + DEBUG_INFO, + " Bus: %lx - %lx Translation=%lx\n", + Bridge->Bus.Base, + Bridge->Bus.Limit, + Bridge->Bus.Translation )); // // Translation for bus is not supported. @@ -93,24 +99,39 @@ CreateRootBridge ( } DEBUG (( - DEBUG_INFO, " Io: %lx - %lx Translation=%lx\n", - Bridge->Io.Base, Bridge->Io.Limit, Bridge->Io.Translation + DEBUG_INFO, + " Io: %lx - %lx Translation=%lx\n", + Bridge->Io.Base, + Bridge->Io.Limit, + Bridge->Io.Translation )); DEBUG (( - DEBUG_INFO, " Mem: %lx - %lx Translation=%lx\n", - Bridge->Mem.Base, Bridge->Mem.Limit, Bridge->Mem.Translation + DEBUG_INFO, + " Mem: %lx - %lx Translation=%lx\n", + Bridge->Mem.Base, + Bridge->Mem.Limit, + Bridge->Mem.Translation )); DEBUG (( - DEBUG_INFO, " MemAbove4G: %lx - %lx Translation=%lx\n", - Bridge->MemAbove4G.Base, Bridge->MemAbove4G.Limit, Bridge->MemAbove4G.Translation + DEBUG_INFO, + " MemAbove4G: %lx - %lx Translation=%lx\n", + Bridge->MemAbove4G.Base, + Bridge->MemAbove4G.Limit, + Bridge->MemAbove4G.Translation )); DEBUG (( - DEBUG_INFO, " PMem: %lx - %lx Translation=%lx\n", - Bridge->PMem.Base, Bridge->PMem.Limit, Bridge->PMem.Translation + DEBUG_INFO, + " PMem: %lx - %lx Translation=%lx\n", + Bridge->PMem.Base, + Bridge->PMem.Limit, + Bridge->PMem.Translation )); DEBUG (( - DEBUG_INFO, " PMemAbove4G: %lx - %lx Translation=%lx\n", - Bridge->PMemAbove4G.Base, Bridge->PMemAbove4G.Limit, Bridge->PMemAbove4G.Translation + DEBUG_INFO, + " PMemAbove4G: %lx - %lx Translation=%lx\n", + Bridge->PMemAbove4G.Base, + Bridge->PMemAbove4G.Limit, + Bridge->PMemAbove4G.Translation )); // @@ -122,18 +143,21 @@ CreateRootBridge ( return NULL; } } + if (RESOURCE_VALID (&Bridge->MemAbove4G)) { ASSERT (Bridge->MemAbove4G.Base >= SIZE_4GB); if (Bridge->MemAbove4G.Base < SIZE_4GB) { return NULL; } } + if (RESOURCE_VALID (&Bridge->PMem)) { ASSERT (Bridge->PMem.Limit < SIZE_4GB); if (Bridge->PMem.Limit >= SIZE_4GB) { return NULL; } } + if (RESOURCE_VALID (&Bridge->PMemAbove4G)) { ASSERT (Bridge->PMemAbove4G.Base >= SIZE_4GB); if (Bridge->PMemAbove4G.Base < SIZE_4GB) { @@ -174,17 +198,17 @@ CreateRootBridge ( RootBridge = AllocateZeroPool (sizeof (PCI_ROOT_BRIDGE_INSTANCE)); ASSERT (RootBridge != NULL); - RootBridge->Signature = PCI_ROOT_BRIDGE_SIGNATURE; - RootBridge->Supports = Bridge->Supports; - RootBridge->Attributes = Bridge->Attributes; - RootBridge->DmaAbove4G = Bridge->DmaAbove4G; + RootBridge->Signature = PCI_ROOT_BRIDGE_SIGNATURE; + RootBridge->Supports = Bridge->Supports; + RootBridge->Attributes = Bridge->Attributes; + RootBridge->DmaAbove4G = Bridge->DmaAbove4G; RootBridge->NoExtendedConfigSpace = Bridge->NoExtendedConfigSpace; - RootBridge->AllocationAttributes = Bridge->AllocationAttributes; - RootBridge->DevicePath = DuplicateDevicePath (Bridge->DevicePath); - RootBridge->DevicePathStr = DevicePathStr; - RootBridge->ConfigBuffer = AllocatePool ( - TypeMax * sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR) - ); + RootBridge->AllocationAttributes = Bridge->AllocationAttributes; + RootBridge->DevicePath = DuplicateDevicePath (Bridge->DevicePath); + RootBridge->DevicePathStr = DevicePathStr; + RootBridge->ConfigBuffer = AllocatePool ( + TypeMax * sizeof (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR) + sizeof (EFI_ACPI_END_TAG_DESCRIPTOR) + ); ASSERT (RootBridge->ConfigBuffer != NULL); InitializeListHead (&RootBridge->Maps); @@ -197,37 +221,40 @@ CreateRootBridge ( for (Index = TypeIo; Index < TypeMax; Index++) { switch (Index) { - case TypeBus: - Aperture = &RootBridge->Bus; - break; - case TypeIo: - Aperture = &RootBridge->Io; - break; - case TypeMem32: - Aperture = &RootBridge->Mem; - break; - case TypeMem64: - Aperture = &RootBridge->MemAbove4G; - break; - case TypePMem32: - Aperture = &RootBridge->PMem; - break; - case TypePMem64: - Aperture = &RootBridge->PMemAbove4G; - break; - default: - ASSERT (FALSE); - Aperture = NULL; - break; + case TypeBus: + Aperture = &RootBridge->Bus; + break; + case TypeIo: + Aperture = &RootBridge->Io; + break; + case TypeMem32: + Aperture = &RootBridge->Mem; + break; + case TypeMem64: + Aperture = &RootBridge->MemAbove4G; + break; + case TypePMem32: + Aperture = &RootBridge->PMem; + break; + case TypePMem64: + Aperture = &RootBridge->PMemAbove4G; + break; + default: + ASSERT (FALSE); + Aperture = NULL; + break; } - RootBridge->ResAllocNode[Index].Type = Index; + + RootBridge->ResAllocNode[Index].Type = Index; if (Bridge->ResourceAssigned && (Aperture->Limit >= Aperture->Base)) { // // Base in ResAllocNode is a host address, while Base in Aperture is a // device address. // - RootBridge->ResAllocNode[Index].Base = TO_HOST_ADDRESS (Aperture->Base, - Aperture->Translation); + RootBridge->ResAllocNode[Index].Base = TO_HOST_ADDRESS ( + Aperture->Base, + Aperture->Translation + ); RootBridge->ResAllocNode[Index].Length = Aperture->Limit - Aperture->Base + 1; RootBridge->ResAllocNode[Index].Status = ResAllocated; } else { @@ -325,7 +352,7 @@ RootBridgeIoCheckParameter ( // // Check to see if Width is in the valid range // - if ((UINT32) Width >= EfiPciWidthMaximum) { + if ((UINT32)Width >= EfiPciWidthMaximum) { return EFI_INVALID_PARAMETER; } @@ -333,11 +360,11 @@ RootBridgeIoCheckParameter ( // For FIFO type, the device address won't increase during the access, // so treat Count as 1 // - if (Width >= EfiPciWidthFifoUint8 && Width <= EfiPciWidthFifoUint64) { + if ((Width >= EfiPciWidthFifoUint8) && (Width <= EfiPciWidthFifoUint64)) { Count = 1; } - Width = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH) (Width & 0x03); + Width = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH)(Width & 0x03); Size = 1 << Width; // @@ -382,23 +409,26 @@ RootBridgeIoCheckParameter ( // if (Address + Length <= 0x1000) { if ((RootBridge->Attributes & ( - EFI_PCI_ATTRIBUTE_ISA_IO | EFI_PCI_ATTRIBUTE_VGA_PALETTE_IO | EFI_PCI_ATTRIBUTE_VGA_IO | - EFI_PCI_ATTRIBUTE_IDE_PRIMARY_IO | EFI_PCI_ATTRIBUTE_IDE_SECONDARY_IO | - EFI_PCI_ATTRIBUTE_ISA_IO_16 | EFI_PCI_ATTRIBUTE_VGA_PALETTE_IO_16 | EFI_PCI_ATTRIBUTE_VGA_IO_16)) != 0) { + EFI_PCI_ATTRIBUTE_ISA_IO | EFI_PCI_ATTRIBUTE_VGA_PALETTE_IO | EFI_PCI_ATTRIBUTE_VGA_IO | + EFI_PCI_ATTRIBUTE_IDE_PRIMARY_IO | EFI_PCI_ATTRIBUTE_IDE_SECONDARY_IO | + EFI_PCI_ATTRIBUTE_ISA_IO_16 | EFI_PCI_ATTRIBUTE_VGA_PALETTE_IO_16 | EFI_PCI_ATTRIBUTE_VGA_IO_16)) != 0) + { return EFI_SUCCESS; } } - Base = RootBridge->Io.Base; + + Base = RootBridge->Io.Base; Limit = RootBridge->Io.Limit; } else if (OperationType == MemOperation) { // // Allow Legacy MMIO access // - if ((Address >= 0xA0000) && (Address + Length) <= 0xC0000) { + if ((Address >= 0xA0000) && ((Address + Length) <= 0xC0000)) { if ((RootBridge->Attributes & EFI_PCI_ATTRIBUTE_VGA_MEMORY) != 0) { return EFI_SUCCESS; } } + // // By comparing the Address against Limit we know which range to be used // for checking @@ -417,14 +447,16 @@ RootBridgeIoCheckParameter ( Limit = RootBridge->PMemAbove4G.Limit; } } else { - PciRbAddr = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS*) &Address; - if (PciRbAddr->Bus < RootBridge->Bus.Base || - PciRbAddr->Bus > RootBridge->Bus.Limit) { + PciRbAddr = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_PCI_ADDRESS *)&Address; + if ((PciRbAddr->Bus < RootBridge->Bus.Base) || + (PciRbAddr->Bus > RootBridge->Bus.Limit)) + { return EFI_INVALID_PARAMETER; } - if (PciRbAddr->Device > PCI_MAX_DEVICE || - PciRbAddr->Function > PCI_MAX_FUNC) { + if ((PciRbAddr->Device > PCI_MAX_DEVICE) || + (PciRbAddr->Function > PCI_MAX_FUNC)) + { return EFI_INVALID_PARAMETER; } @@ -433,12 +465,13 @@ RootBridgeIoCheckParameter ( } else { Address = PciRbAddr->Register; } - Base = 0; + + Base = 0; Limit = RootBridge->NoExtendedConfigSpace ? 0xFF : 0xFFF; } if (Address < Base) { - return EFI_INVALID_PARAMETER; + return EFI_INVALID_PARAMETER; } if (Address + Length > Limit + 1) { @@ -462,18 +495,18 @@ RootBridgeIoCheckParameter ( **/ EFI_STATUS RootBridgeIoGetMemTranslationByAddress ( - IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, - IN UINT64 Address, - IN OUT UINT64 *Translation + IN PCI_ROOT_BRIDGE_INSTANCE *RootBridge, + IN UINT64 Address, + IN OUT UINT64 *Translation ) { - if (Address >= RootBridge->Mem.Base && Address <= RootBridge->Mem.Limit) { + if ((Address >= RootBridge->Mem.Base) && (Address <= RootBridge->Mem.Limit)) { *Translation = RootBridge->Mem.Translation; - } else if (Address >= RootBridge->PMem.Base && Address <= RootBridge->PMem.Limit) { + } else if ((Address >= RootBridge->PMem.Base) && (Address <= RootBridge->PMem.Limit)) { *Translation = RootBridge->PMem.Translation; - } else if (Address >= RootBridge->MemAbove4G.Base && Address <= RootBridge->MemAbove4G.Limit) { + } else if ((Address >= RootBridge->MemAbove4G.Base) && (Address <= RootBridge->MemAbove4G.Limit)) { *Translation = RootBridge->MemAbove4G.Translation; - } else if (Address >= RootBridge->PMemAbove4G.Base && Address <= RootBridge->PMemAbove4G.Limit) { + } else if ((Address >= RootBridge->PMemAbove4G.Base) && (Address <= RootBridge->PMemAbove4G.Limit)) { *Translation = RootBridge->PMemAbove4G.Translation; } else { return EFI_INVALID_PARAMETER; @@ -495,15 +528,16 @@ RootBridgeIoGetMemTranslationByAddress ( **/ UINT64 MultThenDivU64x64x32 ( - IN UINT64 Multiplicand, - IN UINT64 Multiplier, - IN UINT32 Divisor, - OUT UINT32 *Remainder OPTIONAL + IN UINT64 Multiplicand, + IN UINT64 Multiplier, + IN UINT32 Divisor, + OUT UINT32 *Remainder OPTIONAL ) { - UINT64 Uint64; - UINT32 LocalRemainder; - UINT32 Uint32; + UINT64 Uint64; + UINT32 LocalRemainder; + UINT32 Uint32; + if (Multiplicand > DivU64x64Remainder (MAX_UINT64, Multiplier, NULL)) { // // Make sure Multiplicand is the bigger one. @@ -513,6 +547,7 @@ MultThenDivU64x64x32 ( Multiplicand = Multiplier; Multiplier = Uint64; } + // // Because Multiplicand * Multiplier overflows, // Multiplicand * Multiplier / Divisor @@ -525,6 +560,7 @@ MultThenDivU64x64x32 ( if ((Multiplicand & 0x1) == 1) { Uint64 += DivU64x32Remainder (Multiplier, Divisor, &Uint32); } + return Uint64 + DivU64x32Remainder (Uint32 + LShiftU64 (LocalRemainder, 1), Divisor, Remainder); } else { return DivU64x32Remainder (MultU64x64 (Multiplicand, Multiplier), Divisor, Remainder); @@ -553,7 +589,7 @@ GetElapsedTick ( UINT64 PreviousTick; PreviousTick = *CurrentTick; - *CurrentTick = GetPerformanceCounter(); + *CurrentTick = GetPerformanceCounter (); if (StartTick < EndTick) { return *CurrentTick - PreviousTick; } else { @@ -638,20 +674,21 @@ RootBridgeIoPollMem ( if (Delay == 0) { return EFI_SUCCESS; - } else { // // NumberOfTicks = Frenquency * Delay / EFI_TIMER_PERIOD_SECONDS(1) // Frequency = GetPerformanceCounterProperties (&StartTick, &EndTick); - NumberOfTicks = MultThenDivU64x64x32 (Frequency, Delay, (UINT32)EFI_TIMER_PERIOD_SECONDS(1), &Remainder); - if (Remainder >= (UINTN)EFI_TIMER_PERIOD_SECONDS(1) / 2) { + NumberOfTicks = MultThenDivU64x64x32 (Frequency, Delay, (UINT32)EFI_TIMER_PERIOD_SECONDS (1), &Remainder); + if (Remainder >= (UINTN)EFI_TIMER_PERIOD_SECONDS (1) / 2) { NumberOfTicks++; } - for ( ElapsedTick = 0, CurrentTick = GetPerformanceCounter() - ; ElapsedTick <= NumberOfTicks - ; ElapsedTick += GetElapsedTick (&CurrentTick, StartTick, EndTick) - ) { + + for ( ElapsedTick = 0, CurrentTick = GetPerformanceCounter () + ; ElapsedTick <= NumberOfTicks + ; ElapsedTick += GetElapsedTick (&CurrentTick, StartTick, EndTick) + ) + { Status = This->Mem.Read (This, Width, Address, 1, Result); if (EFI_ERROR (Status)) { return Status; @@ -662,6 +699,7 @@ RootBridgeIoPollMem ( } } } + return EFI_TIMEOUT; } @@ -734,26 +772,28 @@ RootBridgeIoPollIo ( if (EFI_ERROR (Status)) { return Status; } + if ((*Result & Mask) == Value) { return EFI_SUCCESS; } if (Delay == 0) { return EFI_SUCCESS; - } else { // // NumberOfTicks = Frenquency * Delay / EFI_TIMER_PERIOD_SECONDS(1) // Frequency = GetPerformanceCounterProperties (&StartTick, &EndTick); - NumberOfTicks = MultThenDivU64x64x32 (Frequency, Delay, (UINT32)EFI_TIMER_PERIOD_SECONDS(1), &Remainder); - if (Remainder >= (UINTN)EFI_TIMER_PERIOD_SECONDS(1) / 2) { + NumberOfTicks = MultThenDivU64x64x32 (Frequency, Delay, (UINT32)EFI_TIMER_PERIOD_SECONDS (1), &Remainder); + if (Remainder >= (UINTN)EFI_TIMER_PERIOD_SECONDS (1) / 2) { NumberOfTicks++; } - for ( ElapsedTick = 0, CurrentTick = GetPerformanceCounter() - ; ElapsedTick <= NumberOfTicks - ; ElapsedTick += GetElapsedTick (&CurrentTick, StartTick, EndTick) - ) { + + for ( ElapsedTick = 0, CurrentTick = GetPerformanceCounter () + ; ElapsedTick <= NumberOfTicks + ; ElapsedTick += GetElapsedTick (&CurrentTick, StartTick, EndTick) + ) + { Status = This->Io.Read (This, Width, Address, 1, Result); if (EFI_ERROR (Status)) { return Status; @@ -764,6 +804,7 @@ RootBridgeIoPollIo ( } } } + return EFI_TIMEOUT; } @@ -804,26 +845,37 @@ RootBridgeIoMemRead ( OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - UINT64 Translation; + EFI_STATUS Status; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + UINT64 Translation; - Status = RootBridgeIoCheckParameter (This, MemOperation, Width, Address, - Count, Buffer); + Status = RootBridgeIoCheckParameter ( + This, + MemOperation, + Width, + Address, + Count, + Buffer + ); if (EFI_ERROR (Status)) { return Status; } RootBridge = ROOT_BRIDGE_FROM_THIS (This); - Status = RootBridgeIoGetMemTranslationByAddress (RootBridge, Address, &Translation); + Status = RootBridgeIoGetMemTranslationByAddress (RootBridge, Address, &Translation); if (EFI_ERROR (Status)) { return Status; } // Address passed to CpuIo->Mem.Read needs to be a host address instead of // device address. - return mCpuIo->Mem.Read (mCpuIo, (EFI_CPU_IO_PROTOCOL_WIDTH) Width, - TO_HOST_ADDRESS (Address, Translation), Count, Buffer); + return mCpuIo->Mem.Read ( + mCpuIo, + (EFI_CPU_IO_PROTOCOL_WIDTH)Width, + TO_HOST_ADDRESS (Address, Translation), + Count, + Buffer + ); } /** @@ -863,26 +915,37 @@ RootBridgeIoMemWrite ( IN VOID *Buffer ) { - EFI_STATUS Status; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - UINT64 Translation; + EFI_STATUS Status; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + UINT64 Translation; - Status = RootBridgeIoCheckParameter (This, MemOperation, Width, Address, - Count, Buffer); + Status = RootBridgeIoCheckParameter ( + This, + MemOperation, + Width, + Address, + Count, + Buffer + ); if (EFI_ERROR (Status)) { return Status; } RootBridge = ROOT_BRIDGE_FROM_THIS (This); - Status = RootBridgeIoGetMemTranslationByAddress (RootBridge, Address, &Translation); + Status = RootBridgeIoGetMemTranslationByAddress (RootBridge, Address, &Translation); if (EFI_ERROR (Status)) { return Status; } // Address passed to CpuIo->Mem.Write needs to be a host address instead of // device address. - return mCpuIo->Mem.Write (mCpuIo, (EFI_CPU_IO_PROTOCOL_WIDTH) Width, - TO_HOST_ADDRESS (Address, Translation), Count, Buffer); + return mCpuIo->Mem.Write ( + mCpuIo, + (EFI_CPU_IO_PROTOCOL_WIDTH)Width, + TO_HOST_ADDRESS (Address, Translation), + Count, + Buffer + ); } /** @@ -916,12 +979,16 @@ RootBridgeIoIoRead ( OUT VOID *Buffer ) { - EFI_STATUS Status; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_STATUS Status; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; Status = RootBridgeIoCheckParameter ( - This, IoOperation, Width, - Address, Count, Buffer + This, + IoOperation, + Width, + Address, + Count, + Buffer ); if (EFI_ERROR (Status)) { return Status; @@ -931,8 +998,13 @@ RootBridgeIoIoRead ( // Address passed to CpuIo->Io.Read needs to be a host address instead of // device address. - return mCpuIo->Io.Read (mCpuIo, (EFI_CPU_IO_PROTOCOL_WIDTH) Width, - TO_HOST_ADDRESS (Address, RootBridge->Io.Translation), Count, Buffer); + return mCpuIo->Io.Read ( + mCpuIo, + (EFI_CPU_IO_PROTOCOL_WIDTH)Width, + TO_HOST_ADDRESS (Address, RootBridge->Io.Translation), + Count, + Buffer + ); } /** @@ -959,19 +1031,23 @@ RootBridgeIoIoRead ( EFI_STATUS EFIAPI RootBridgeIoIoWrite ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { - EFI_STATUS Status; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_STATUS Status; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; Status = RootBridgeIoCheckParameter ( - This, IoOperation, Width, - Address, Count, Buffer + This, + IoOperation, + Width, + Address, + Count, + Buffer ); if (EFI_ERROR (Status)) { return Status; @@ -981,8 +1057,13 @@ RootBridgeIoIoWrite ( // Address passed to CpuIo->Io.Write needs to be a host address instead of // device address. - return mCpuIo->Io.Write (mCpuIo, (EFI_CPU_IO_PROTOCOL_WIDTH) Width, - TO_HOST_ADDRESS (Address, RootBridge->Io.Translation), Count, Buffer); + return mCpuIo->Io.Write ( + mCpuIo, + (EFI_CPU_IO_PROTOCOL_WIDTH)Width, + TO_HOST_ADDRESS (Address, RootBridge->Io.Translation), + Count, + Buffer + ); } /** @@ -1019,11 +1100,11 @@ RootBridgeIoIoWrite ( EFI_STATUS EFIAPI RootBridgeIoCopyMem ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 DestAddress, - IN UINT64 SrcAddress, - IN UINTN Count + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 DestAddress, + IN UINT64 SrcAddress, + IN UINTN Count ) { EFI_STATUS Status; @@ -1032,7 +1113,7 @@ RootBridgeIoCopyMem ( UINTN Index; UINT64 Result; - if ((UINT32) Width > EfiPciWidthUint64) { + if ((UINT32)Width > EfiPciWidthUint64) { return EFI_INVALID_PARAMETER; } @@ -1040,13 +1121,14 @@ RootBridgeIoCopyMem ( return EFI_SUCCESS; } - Stride = (UINTN) (1 << Width); + Stride = (UINTN)(1 << Width); Forward = TRUE; if ((DestAddress > SrcAddress) && - (DestAddress < (SrcAddress + Count * Stride))) { - Forward = FALSE; - SrcAddress = SrcAddress + (Count - 1) * Stride; + (DestAddress < (SrcAddress + Count * Stride))) + { + Forward = FALSE; + SrcAddress = SrcAddress + (Count - 1) * Stride; DestAddress = DestAddress + (Count - 1) * Stride; } @@ -1061,6 +1143,7 @@ RootBridgeIoCopyMem ( if (EFI_ERROR (Status)) { return Status; } + Status = RootBridgeIoMemWrite ( This, Width, @@ -1071,18 +1154,19 @@ RootBridgeIoCopyMem ( if (EFI_ERROR (Status)) { return Status; } + if (Forward) { - SrcAddress += Stride; + SrcAddress += Stride; DestAddress += Stride; } else { - SrcAddress -= Stride; + SrcAddress -= Stride; DestAddress -= Stride; } } + return EFI_SUCCESS; } - /** PCI configuration space access. @@ -1101,12 +1185,12 @@ RootBridgeIoCopyMem ( EFI_STATUS EFIAPI RootBridgeIoPciAccess ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN BOOLEAN Read, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN BOOLEAN Read, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { EFI_STATUS Status; @@ -1145,7 +1229,7 @@ RootBridgeIoPciAccess ( // InStride = mInStride[Width]; OutStride = mOutStride[Width]; - Size = (UINTN) (1 << (Width & 0x03)); + Size = (UINTN)(1 << (Width & 0x03)); for (Uint8Buffer = Buffer; Count > 0; Address += InStride, Uint8Buffer += OutStride, Count--) { if (Read) { PciSegmentReadBuffer (Address, Size, Uint8Buffer); @@ -1153,6 +1237,7 @@ RootBridgeIoPciAccess ( PciSegmentWriteBuffer (Address, Size, Uint8Buffer); } } + return EFI_SUCCESS; } @@ -1173,11 +1258,11 @@ RootBridgeIoPciAccess ( EFI_STATUS EFIAPI RootBridgeIoPciRead ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return RootBridgeIoPciAccess (This, TRUE, Width, Address, Count, Buffer); @@ -1200,11 +1285,11 @@ RootBridgeIoPciRead ( EFI_STATUS EFIAPI RootBridgeIoPciWrite ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return RootBridgeIoPciAccess (This, FALSE, Width, Address, Count, Buffer); @@ -1242,20 +1327,21 @@ RootBridgeIoMap ( OUT VOID **Mapping ) { - EFI_STATUS Status; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - EFI_PHYSICAL_ADDRESS PhysicalAddress; - MAP_INFO *MapInfo; + EFI_STATUS Status; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + MAP_INFO *MapInfo; - if (HostAddress == NULL || NumberOfBytes == NULL || DeviceAddress == NULL || - Mapping == NULL) { + if ((HostAddress == NULL) || (NumberOfBytes == NULL) || (DeviceAddress == NULL) || + (Mapping == NULL)) + { return EFI_INVALID_PARAMETER; } // // Make sure that Operation is valid // - if ((UINT32) Operation >= EfiPciOperationMaximum) { + if ((UINT32)Operation >= EfiPciOperationMaximum) { return EFI_INVALID_PARAMETER; } @@ -1267,12 +1353,13 @@ RootBridgeIoMap ( // Clear 64bit support // if (Operation > EfiPciOperationBusMasterCommonBuffer) { - Operation = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_OPERATION) (Operation - EfiPciOperationBusMasterRead64); + Operation = (EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL_OPERATION)(Operation - EfiPciOperationBusMasterRead64); } } + Status = mIoMmu->Map ( mIoMmu, - (EDKII_IOMMU_OPERATION) Operation, + (EDKII_IOMMU_OPERATION)Operation, HostAddress, NumberOfBytes, DeviceAddress, @@ -1281,21 +1368,22 @@ RootBridgeIoMap ( return Status; } - PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress; + PhysicalAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; if ((!RootBridge->DmaAbove4G || - (Operation != EfiPciOperationBusMasterRead64 && - Operation != EfiPciOperationBusMasterWrite64 && - Operation != EfiPciOperationBusMasterCommonBuffer64)) && - ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) { - + ((Operation != EfiPciOperationBusMasterRead64) && + (Operation != EfiPciOperationBusMasterWrite64) && + (Operation != EfiPciOperationBusMasterCommonBuffer64))) && + ((PhysicalAddress + *NumberOfBytes) > SIZE_4GB)) + { // // If the root bridge or the device cannot handle performing DMA above // 4GB but any part of the DMA transfer being mapped is above 4GB, then // map the DMA transfer to a buffer below 4GB. // - if (Operation == EfiPciOperationBusMasterCommonBuffer || - Operation == EfiPciOperationBusMasterCommonBuffer64) { + if ((Operation == EfiPciOperationBusMasterCommonBuffer) || + (Operation == EfiPciOperationBusMasterCommonBuffer64)) + { // // Common Buffer operations can not be remapped. If the common buffer // if above 4GB, then it is not possible to generate a mapping, so return @@ -1344,11 +1432,12 @@ RootBridgeIoMap ( // then copy the contents of the real buffer into the mapped buffer // so the Bus Master can read the contents of the real buffer. // - if (Operation == EfiPciOperationBusMasterRead || - Operation == EfiPciOperationBusMasterRead64) { + if ((Operation == EfiPciOperationBusMasterRead) || + (Operation == EfiPciOperationBusMasterRead64)) + { CopyMem ( - (VOID *) (UINTN) MapInfo->MappedHostAddress, - (VOID *) (UINTN) MapInfo->HostAddress, + (VOID *)(UINTN)MapInfo->MappedHostAddress, + (VOID *)(UINTN)MapInfo->HostAddress, MapInfo->NumberOfBytes ); } @@ -1362,7 +1451,7 @@ RootBridgeIoMap ( // // Return a pointer to the MAP_INFO structure in Mapping // - *Mapping = MapInfo; + *Mapping = MapInfo; } else { // // If the root bridge CAN handle performing DMA above 4GB or @@ -1400,9 +1489,9 @@ RootBridgeIoUnmap ( IN VOID *Mapping ) { - MAP_INFO *MapInfo; - LIST_ENTRY *Link; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + MAP_INFO *MapInfo; + LIST_ENTRY *Link; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; EFI_STATUS Status; if (mIoMmu != NULL) { @@ -1428,18 +1517,21 @@ RootBridgeIoUnmap ( for (Link = GetFirstNode (&RootBridge->Maps) ; !IsNull (&RootBridge->Maps, Link) ; Link = GetNextNode (&RootBridge->Maps, Link) - ) { + ) + { MapInfo = MAP_INFO_FROM_LINK (Link); if (MapInfo == Mapping) { break; } } + // // Mapping is not a valid value returned by Map() // if (MapInfo != Mapping) { return EFI_INVALID_PARAMETER; } + RemoveEntryList (&MapInfo->Link); // @@ -1447,11 +1539,12 @@ RootBridgeIoUnmap ( // then copy the contents of the mapped buffer into the real buffer // so the processor can read the contents of the real buffer. // - if (MapInfo->Operation == EfiPciOperationBusMasterWrite || - MapInfo->Operation == EfiPciOperationBusMasterWrite64) { + if ((MapInfo->Operation == EfiPciOperationBusMasterWrite) || + (MapInfo->Operation == EfiPciOperationBusMasterWrite64)) + { CopyMem ( - (VOID *) (UINTN) MapInfo->HostAddress, - (VOID *) (UINTN) MapInfo->MappedHostAddress, + (VOID *)(UINTN)MapInfo->HostAddress, + (VOID *)(UINTN)MapInfo->MappedHostAddress, MapInfo->NumberOfBytes ); } @@ -1524,8 +1617,9 @@ RootBridgeIoAllocateBuffer ( // The only valid memory types are EfiBootServicesData and // EfiRuntimeServicesData // - if (MemoryType != EfiBootServicesData && - MemoryType != EfiRuntimeServicesData) { + if ((MemoryType != EfiBootServicesData) && + (MemoryType != EfiRuntimeServicesData)) + { return EFI_INVALID_PARAMETER; } @@ -1536,8 +1630,9 @@ RootBridgeIoAllocateBuffer ( // // Clear DUAL_ADDRESS_CYCLE // - Attributes &= ~((UINT64) EFI_PCI_ATTRIBUTE_DUAL_ADDRESS_CYCLE); + Attributes &= ~((UINT64)EFI_PCI_ATTRIBUTE_DUAL_ADDRESS_CYCLE); } + Status = mIoMmu->AllocateBuffer ( mIoMmu, Type, @@ -1551,13 +1646,15 @@ RootBridgeIoAllocateBuffer ( AllocateType = AllocateAnyPages; if (!RootBridge->DmaAbove4G || - (Attributes & EFI_PCI_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0) { + ((Attributes & EFI_PCI_ATTRIBUTE_DUAL_ADDRESS_CYCLE) == 0)) + { // // Limit allocations to memory below 4GB // AllocateType = AllocateMaxAddress; - PhysicalAddress = (EFI_PHYSICAL_ADDRESS) (SIZE_4GB - 1); + PhysicalAddress = (EFI_PHYSICAL_ADDRESS)(SIZE_4GB - 1); } + Status = gBS->AllocatePages ( AllocateType, MemoryType, @@ -1565,7 +1662,7 @@ RootBridgeIoAllocateBuffer ( &PhysicalAddress ); if (!EFI_ERROR (Status)) { - *HostAddress = (VOID *) (UINTN) PhysicalAddress; + *HostAddress = (VOID *)(UINTN)PhysicalAddress; } return Status; @@ -1593,7 +1690,7 @@ RootBridgeIoFreeBuffer ( OUT VOID *HostAddress ) { - EFI_STATUS Status; + EFI_STATUS Status; if (mIoMmu != NULL) { Status = mIoMmu->FreeBuffer ( @@ -1604,7 +1701,7 @@ RootBridgeIoFreeBuffer ( return Status; } - return gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress, Pages); + return gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress, Pages); } /** @@ -1631,7 +1728,7 @@ RootBridgeIoFreeBuffer ( EFI_STATUS EFIAPI RootBridgeIoFlush ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This ) { return EFI_SUCCESS; @@ -1667,9 +1764,9 @@ RootBridgeIoGetAttributes ( OUT UINT64 *Attributes ) { - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - if (Attributes == NULL && Supported == NULL) { + if ((Attributes == NULL) && (Supported == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1678,7 +1775,7 @@ RootBridgeIoGetAttributes ( // Set the return value for Supported and Attributes // if (Supported != NULL) { - *Supported = RootBridge->Supports; + *Supported = RootBridge->Supports; } if (Attributes != NULL) { @@ -1733,7 +1830,7 @@ RootBridgeIoSetAttributes ( IN OUT UINT64 *ResourceLength ) { - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; RootBridge = ROOT_BRIDGE_FROM_THIS (This); @@ -1773,15 +1870,15 @@ RootBridgeIoSetAttributes ( EFI_STATUS EFIAPI RootBridgeIoConfiguration ( - IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, - OUT VOID **Resources + IN EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL *This, + OUT VOID **Resources ) { - PCI_RESOURCE_TYPE Index; - PCI_ROOT_BRIDGE_INSTANCE *RootBridge; - PCI_RES_NODE *ResAllocNode; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - EFI_ACPI_END_TAG_DESCRIPTOR *End; + PCI_RESOURCE_TYPE Index; + PCI_ROOT_BRIDGE_INSTANCE *RootBridge; + PCI_RES_NODE *ResAllocNode; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + EFI_ACPI_END_TAG_DESCRIPTOR *End; // // Get this instance of the Root Bridge. @@ -1793,7 +1890,6 @@ RootBridgeIoConfiguration ( ); Descriptor = RootBridge->ConfigBuffer; for (Index = TypeIo; Index < TypeMax; Index++) { - ResAllocNode = &RootBridge->ResAllocNode[Index]; if (ResAllocNode->Status != ResAllocated) { @@ -1805,48 +1901,48 @@ RootBridgeIoConfiguration ( // According to UEFI 2.7, RootBridgeIo->Configuration should return address // range in CPU view (host address), and ResAllocNode->Base is already a CPU // view address (host address). - Descriptor->AddrRangeMin = ResAllocNode->Base; - Descriptor->AddrRangeMax = ResAllocNode->Base + ResAllocNode->Length - 1; - Descriptor->AddrLen = ResAllocNode->Length; + Descriptor->AddrRangeMin = ResAllocNode->Base; + Descriptor->AddrRangeMax = ResAllocNode->Base + ResAllocNode->Length - 1; + Descriptor->AddrLen = ResAllocNode->Length; Descriptor->AddrTranslationOffset = GetTranslationByResourceType ( - RootBridge, - ResAllocNode->Type - ); + RootBridge, + ResAllocNode->Type + ); switch (ResAllocNode->Type) { - - case TypeIo: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; - break; - - case TypePMem32: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem32: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 32; - break; - - case TypePMem64: - Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; - case TypeMem64: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; - Descriptor->AddrSpaceGranularity = 64; - break; - - case TypeBus: - Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_BUS; - break; - - default: - break; + case TypeIo: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_IO; + break; + + case TypePMem32: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem32: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 32; + break; + + case TypePMem64: + Descriptor->SpecificFlag = EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE; + case TypeMem64: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_MEM; + Descriptor->AddrSpaceGranularity = 64; + break; + + case TypeBus: + Descriptor->ResType = ACPI_ADDRESS_SPACE_TYPE_BUS; + break; + + default: + break; } Descriptor++; } + // // Terminate the entries. // - End = (EFI_ACPI_END_TAG_DESCRIPTOR *) Descriptor; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor; End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0x0; diff --git a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/ComponentName.c index 68b0de8edb..eca2adb246 100644 --- a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/ComponentName.c @@ -20,14 +20,13 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gPciSioSerialComponen // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPciSioSerialComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) SerialComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) SerialComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gPciSioSerialComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)SerialComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)SerialComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSerialDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSerialDriverNameTable[] = { { "eng;en", L"PCI SIO Serial Driver" @@ -165,11 +164,11 @@ SerialComponentNameGetDriverName ( EFI_STATUS EFIAPI SerialComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { EFI_STATUS Status; @@ -182,18 +181,18 @@ SerialComponentNameGetControllerName ( // Make sure this driver is currently managing ControllerHandle // IoProtocolGuid = &gEfiSioProtocolGuid; - Status = EfiTestManagedDevice ( - ControllerHandle, - gSerialControllerDriver.DriverBindingHandle, - IoProtocolGuid - ); + Status = EfiTestManagedDevice ( + ControllerHandle, + gSerialControllerDriver.DriverBindingHandle, + IoProtocolGuid + ); if (EFI_ERROR (Status)) { IoProtocolGuid = &gEfiPciIoProtocolGuid; - Status = EfiTestManagedDevice ( - ControllerHandle, - gSerialControllerDriver.DriverBindingHandle, - IoProtocolGuid - ); + Status = EfiTestManagedDevice ( + ControllerHandle, + gSerialControllerDriver.DriverBindingHandle, + IoProtocolGuid + ); } if (EFI_ERROR (Status)) { @@ -217,7 +216,7 @@ SerialComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ChildHandle, &gEfiSerialIoProtocolGuid, - (VOID **) &SerialIo, + (VOID **)&SerialIo, gSerialControllerDriver.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -229,7 +228,7 @@ SerialComponentNameGetControllerName ( // // Get the Serial Controller's Device structure // - SerialDevice = SERIAL_DEV_FROM_THIS (SerialIo); + SerialDevice = SERIAL_DEV_FROM_THIS (SerialIo); ControllerNameTable = SerialDevice->ControllerNameTable; } @@ -250,11 +249,12 @@ SerialComponentNameGetControllerName ( **/ VOID AddName ( - IN SERIAL_DEV *SerialDevice, - IN UINT32 Instance + IN SERIAL_DEV *SerialDevice, + IN UINT32 Instance ) { - CHAR16 SerialPortName[SERIAL_PORT_NAME_LEN]; + CHAR16 SerialPortName[SERIAL_PORT_NAME_LEN]; + UnicodeSPrint ( SerialPortName, sizeof (SerialPortName), @@ -275,5 +275,4 @@ AddName ( SerialPortName, FALSE ); - } diff --git a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c index 7ce2e06afe..2b5ff0a37a 100644 --- a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c +++ b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.c @@ -12,7 +12,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // ISA Serial Driver Global Variables // -EFI_DRIVER_BINDING_PROTOCOL gSerialControllerDriver = { +EFI_DRIVER_BINDING_PROTOCOL gSerialControllerDriver = { SerialControllerDriverSupported, SerialControllerDriverStart, SerialControllerDriverStop, @@ -21,13 +21,13 @@ EFI_DRIVER_BINDING_PROTOCOL gSerialControllerDriver = { NULL }; -CONTROLLER_DEVICE_PATH mControllerDevicePathTemplate = { +CONTROLLER_DEVICE_PATH mControllerDevicePathTemplate = { { HARDWARE_DEVICE_PATH, HW_CONTROLLER_DP, { - (UINT8) (sizeof (CONTROLLER_DEVICE_PATH)), - (UINT8) ((sizeof (CONTROLLER_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (CONTROLLER_DEVICE_PATH)), + (UINT8)((sizeof (CONTROLLER_DEVICE_PATH)) >> 8) } }, 0 @@ -62,26 +62,26 @@ SERIAL_DEV gSerialDevTemplate = { MESSAGING_DEVICE_PATH, MSG_UART_DP, { - (UINT8) (sizeof (UART_DEVICE_PATH)), - (UINT8) ((sizeof (UART_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (UART_DEVICE_PATH)), + (UINT8)((sizeof (UART_DEVICE_PATH)) >> 8) } }, - 0, 0, 0, 0, 0 - }, // UartDevicePath - 0, // BaseAddress - FALSE, // MmioAccess - 1, // RegisterStride - 0, // ClockRate - 16, // ReceiveFifoDepth - { 0, 0 }, // Receive; - 16, // TransmitFifoDepth - { 0, 0 }, // Transmit; - FALSE, // SoftwareLoopbackEnable; - FALSE, // HardwareFlowControl; - NULL, // *ControllerNameTable; - FALSE, // ContainsControllerNode; - 0, // Instance; - NULL // *PciDeviceInfo; + 0, 0,0, 0, 0 + }, // UartDevicePath + 0, // BaseAddress + FALSE, // MmioAccess + 1, // RegisterStride + 0, // ClockRate + 16, // ReceiveFifoDepth + { 0, 0 }, // Receive; + 16, // TransmitFifoDepth + { 0, 0 }, // Transmit; + FALSE, // SoftwareLoopbackEnable; + FALSE, // HardwareFlowControl; + NULL, // *ControllerNameTable; + FALSE, // ContainsControllerNode; + 0, // Instance; + NULL // *PciDeviceInfo; }; /** @@ -95,14 +95,14 @@ SERIAL_DEV gSerialDevTemplate = { **/ BOOLEAN IsUartFlowControlDevicePathNode ( - IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl + IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl ) { - return (BOOLEAN) ( - (DevicePathType (FlowControl) == MESSAGING_DEVICE_PATH) && - (DevicePathSubType (FlowControl) == MSG_VENDOR_DP) && - (CompareGuid (&FlowControl->Guid, &gEfiUartDevicePathGuid)) - ); + return (BOOLEAN)( + (DevicePathType (FlowControl) == MESSAGING_DEVICE_PATH) && + (DevicePathSubType (FlowControl) == MSG_VENDOR_DP) && + (CompareGuid (&FlowControl->Guid, &gEfiUartDevicePathGuid)) + ); } /** @@ -118,11 +118,11 @@ IsUartFlowControlDevicePathNode ( EFI_STATUS EFIAPI InitializePciSioSerial ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -140,15 +140,15 @@ InitializePciSioSerial ( // // Initialize UART default setting in gSerialDevTempate // - gSerialDevTemplate.SerialMode.BaudRate = PcdGet64 (PcdUartDefaultBaudRate); - gSerialDevTemplate.SerialMode.DataBits = PcdGet8 (PcdUartDefaultDataBits); - gSerialDevTemplate.SerialMode.Parity = PcdGet8 (PcdUartDefaultParity); - gSerialDevTemplate.SerialMode.StopBits = PcdGet8 (PcdUartDefaultStopBits); + gSerialDevTemplate.SerialMode.BaudRate = PcdGet64 (PcdUartDefaultBaudRate); + gSerialDevTemplate.SerialMode.DataBits = PcdGet8 (PcdUartDefaultDataBits); + gSerialDevTemplate.SerialMode.Parity = PcdGet8 (PcdUartDefaultParity); + gSerialDevTemplate.SerialMode.StopBits = PcdGet8 (PcdUartDefaultStopBits); gSerialDevTemplate.UartDevicePath.BaudRate = PcdGet64 (PcdUartDefaultBaudRate); gSerialDevTemplate.UartDevicePath.DataBits = PcdGet8 (PcdUartDefaultDataBits); gSerialDevTemplate.UartDevicePath.Parity = PcdGet8 (PcdUartDefaultParity); gSerialDevTemplate.UartDevicePath.StopBits = PcdGet8 (PcdUartDefaultStopBits); - gSerialDevTemplate.ClockRate = PcdGet32 (PcdSerialClockRate); + gSerialDevTemplate.ClockRate = PcdGet32 (PcdSerialClockRate); return Status; } @@ -163,13 +163,13 @@ InitializePciSioSerial ( **/ EFI_STATUS IsSioSerialController ( - EFI_HANDLE Controller + EFI_HANDLE Controller ) { - EFI_STATUS Status; - EFI_SIO_PROTOCOL *Sio; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - ACPI_HID_DEVICE_PATH *Acpi; + EFI_STATUS Status; + EFI_SIO_PROTOCOL *Sio; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + ACPI_HID_DEVICE_PATH *Acpi; // // Open the IO Abstraction(s) needed to perform the supported test @@ -177,7 +177,7 @@ IsSioSerialController ( Status = gBS->OpenProtocol ( Controller, &gEfiSioProtocolGuid, - (VOID **) &Sio, + (VOID **)&Sio, gSerialControllerDriver.DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -198,25 +198,26 @@ IsSioSerialController ( ); Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, - gSerialControllerDriver.DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&DevicePath, + gSerialControllerDriver.DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); ASSERT (Status != EFI_ALREADY_STARTED); if (!EFI_ERROR (Status)) { do { - Acpi = (ACPI_HID_DEVICE_PATH *) DevicePath; + Acpi = (ACPI_HID_DEVICE_PATH *)DevicePath; DevicePath = NextDevicePathNode (DevicePath); } while (!IsDevicePathEnd (DevicePath)); - if (DevicePathType (Acpi) != ACPI_DEVICE_PATH || - (DevicePathSubType (Acpi) != ACPI_DP && DevicePathSubType (Acpi) != ACPI_EXTENDED_DP) || - Acpi->HID != EISA_PNP_ID (0x501) - ) { + if ((DevicePathType (Acpi) != ACPI_DEVICE_PATH) || + ((DevicePathSubType (Acpi) != ACPI_DP) && (DevicePathSubType (Acpi) != ACPI_EXTENDED_DP)) || + (Acpi->HID != EISA_PNP_ID (0x501)) + ) + { Status = EFI_UNSUPPORTED; } } @@ -225,12 +226,13 @@ IsSioSerialController ( // Close protocol, don't use device path protocol in the Support() function // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - gSerialControllerDriver.DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + gSerialControllerDriver.DriverBindingHandle, + Controller + ); } + return Status; } @@ -244,26 +246,26 @@ IsSioSerialController ( **/ EFI_STATUS IsPciSerialController ( - EFI_HANDLE Controller + EFI_HANDLE Controller ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - PCI_TYPE00 Pci; - PCI_SERIAL_PARAMETER *PciSerialParameter; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + PCI_TYPE00 Pci; + PCI_SERIAL_PARAMETER *PciSerialParameter; // // Open the IO Abstraction(s) needed to perform the supported test // Status = gBS->OpenProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, - gSerialControllerDriver.DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Controller, + &gEfiPciIoProtocolGuid, + (VOID **)&PciIo, + gSerialControllerDriver.DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (Status == EFI_ALREADY_STARTED) { return EFI_SUCCESS; } @@ -272,16 +274,19 @@ IsPciSerialController ( Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0, sizeof (Pci), &Pci); if (!EFI_ERROR (Status)) { if (!IS_PCI_16550_SERIAL (&Pci)) { - for (PciSerialParameter = (PCI_SERIAL_PARAMETER *) PcdGetPtr (PcdPciSerialParameters) + for (PciSerialParameter = (PCI_SERIAL_PARAMETER *)PcdGetPtr (PcdPciSerialParameters) ; PciSerialParameter->VendorId != 0xFFFF ; PciSerialParameter++ - ) { + ) + { if ((Pci.Hdr.VendorId == PciSerialParameter->VendorId) && (Pci.Hdr.DeviceId == PciSerialParameter->DeviceId) - ) { + ) + { break; } } + if (PciSerialParameter->VendorId == 0xFFFF) { Status = EFI_UNSUPPORTED; } else { @@ -294,12 +299,13 @@ IsPciSerialController ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - gSerialControllerDriver.DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + gSerialControllerDriver.DriverBindingHandle, + Controller + ); } + if (EFI_ERROR (Status)) { return Status; } @@ -308,24 +314,24 @@ IsPciSerialController ( // Open the EFI Device Path protocol needed to perform the supported test // Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, - gSerialControllerDriver.DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&DevicePath, + gSerialControllerDriver.DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); ASSERT (Status != EFI_ALREADY_STARTED); // // Close protocol, don't use device path protocol in the Support() function // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - gSerialControllerDriver.DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + gSerialControllerDriver.DriverBindingHandle, + Controller + ); return Status; } @@ -343,15 +349,15 @@ IsPciSerialController ( EFI_STATUS EFIAPI SerialControllerDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - UART_DEVICE_PATH *Uart; - UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; + EFI_STATUS Status; + UART_DEVICE_PATH *Uart; + UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; // // Test RemainingDevicePath @@ -360,10 +366,11 @@ SerialControllerDriverSupported ( Status = EFI_UNSUPPORTED; Uart = SkipControllerDevicePathNode (RemainingDevicePath, NULL, NULL); - if (DevicePathType (Uart) != MESSAGING_DEVICE_PATH || - DevicePathSubType (Uart) != MSG_UART_DP || - DevicePathNodeLength (Uart) != sizeof (UART_DEVICE_PATH) - ) { + if ((DevicePathType (Uart) != MESSAGING_DEVICE_PATH) || + (DevicePathSubType (Uart) != MSG_UART_DP) || + (DevicePathNodeLength (Uart) != sizeof (UART_DEVICE_PATH)) + ) + { return EFI_UNSUPPORTED; } @@ -374,7 +381,7 @@ SerialControllerDriverSupported ( return EFI_UNSUPPORTED; } - FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Uart); + FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *)NextDevicePathNode (Uart); if (IsUartFlowControlDevicePathNode (FlowControl)) { // // If the second node is Flow Control Node, @@ -390,6 +397,7 @@ SerialControllerDriverSupported ( if (EFI_ERROR (Status)) { Status = IsPciSerialController (Controller); } + return Status; } @@ -415,31 +423,31 @@ SerialControllerDriverSupported ( **/ EFI_STATUS CreateSerialDevice ( - IN EFI_HANDLE Controller, - IN UART_DEVICE_PATH *Uart, - IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, - IN BOOLEAN CreateControllerNode, - IN UINT32 Instance, - IN PARENT_IO_PROTOCOL_PTR ParentIo, - IN PCI_SERIAL_PARAMETER *PciSerialParameter OPTIONAL, - IN PCI_DEVICE_INFO *PciDeviceInfo OPTIONAL + IN EFI_HANDLE Controller, + IN UART_DEVICE_PATH *Uart, + IN EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath, + IN BOOLEAN CreateControllerNode, + IN UINT32 Instance, + IN PARENT_IO_PROTOCOL_PTR ParentIo, + IN PCI_SERIAL_PARAMETER *PciSerialParameter OPTIONAL, + IN PCI_DEVICE_INFO *PciDeviceInfo OPTIONAL ) { - EFI_STATUS Status; - SERIAL_DEV *SerialDevice; - UINT8 BarIndex; - UINT64 Offset; - UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; - UINT32 FlowControlMap; - ACPI_RESOURCE_HEADER_PTR Resources; - EFI_ACPI_IO_PORT_DESCRIPTOR *Io; - EFI_ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR *FixedIo; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *AddressSpace; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - - BarIndex = 0; - Offset = 0; - FlowControl = NULL; + EFI_STATUS Status; + SERIAL_DEV *SerialDevice; + UINT8 BarIndex; + UINT64 Offset; + UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; + UINT32 FlowControlMap; + ACPI_RESOURCE_HEADER_PTR Resources; + EFI_ACPI_IO_PORT_DESCRIPTOR *Io; + EFI_ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR *FixedIo; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *AddressSpace; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + + BarIndex = 0; + Offset = 0; + FlowControl = NULL; FlowControlMap = 0; // @@ -455,7 +463,7 @@ CreateSerialDevice ( if (Uart != NULL) { CopyMem (&SerialDevice->UartDevicePath, Uart, sizeof (UART_DEVICE_PATH)); - FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Uart); + FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *)NextDevicePathNode (Uart); if (IsUartFlowControlDevicePathNode (FlowControl)) { FlowControlMap = ReadUnaligned32 (&FlowControl->FlowControlMap); } else { @@ -468,16 +476,19 @@ CreateSerialDevice ( // if (PciSerialParameter != NULL) { BarIndex = (PciSerialParameter->BarIndex == MAX_UINT8) ? 0 : PciSerialParameter->BarIndex; - Offset = PciSerialParameter->Offset; + Offset = PciSerialParameter->Offset; if (PciSerialParameter->RegisterStride != 0) { SerialDevice->RegisterStride = PciSerialParameter->RegisterStride; } + if (PciSerialParameter->ClockRate != 0) { SerialDevice->ClockRate = PciSerialParameter->ClockRate; } + if (PciSerialParameter->ReceiveFifoDepth != 0) { SerialDevice->ReceiveFifoDepth = PciSerialParameter->ReceiveFifoDepth; } + if (PciSerialParameter->TransmitFifoDepth != 0) { SerialDevice->TransmitFifoDepth = PciSerialParameter->TransmitFifoDepth; } @@ -487,9 +498,16 @@ CreateSerialDevice ( // Pass NULL ActualBaudRate to VerifyUartParameters to disallow baudrate degrade. // DriverBindingStart() shouldn't create a handle with different UART device path. // - if (!VerifyUartParameters (SerialDevice->ClockRate, SerialDevice->UartDevicePath.BaudRate, SerialDevice->UartDevicePath.DataBits, - SerialDevice->UartDevicePath.Parity, SerialDevice->UartDevicePath.StopBits, NULL, NULL - )) { + if (!VerifyUartParameters ( + SerialDevice->ClockRate, + SerialDevice->UartDevicePath.BaudRate, + SerialDevice->UartDevicePath.DataBits, + SerialDevice->UartDevicePath.Parity, + SerialDevice->UartDevicePath.StopBits, + NULL, + NULL + )) + { Status = EFI_INVALID_PARAMETER; goto CreateError; } @@ -497,7 +515,7 @@ CreateSerialDevice ( if (PciSerialParameter == NULL) { Status = ParentIo.Sio->GetResources (ParentIo.Sio, &Resources); } else { - Status = ParentIo.PciIo->GetBarAttributes (ParentIo.PciIo, BarIndex, NULL, (VOID **) &Resources); + Status = ParentIo.PciIo->GetBarAttributes (ParentIo.PciIo, BarIndex, NULL, (VOID **)&Resources); } if (!EFI_ERROR (Status)) { @@ -508,39 +526,43 @@ CreateSerialDevice ( // while ((Resources.SmallHeader->Byte != ACPI_END_TAG_DESCRIPTOR) && (SerialDevice->BaseAddress == 0)) { switch (Resources.SmallHeader->Byte) { - case ACPI_IO_PORT_DESCRIPTOR: - Io = (EFI_ACPI_IO_PORT_DESCRIPTOR *) Resources.SmallHeader; - if (Io->Length != 0) { - SerialDevice->BaseAddress = Io->BaseAddressMin; - } - break; + case ACPI_IO_PORT_DESCRIPTOR: + Io = (EFI_ACPI_IO_PORT_DESCRIPTOR *)Resources.SmallHeader; + if (Io->Length != 0) { + SerialDevice->BaseAddress = Io->BaseAddressMin; + } - case ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR: - FixedIo = (EFI_ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR *) Resources.SmallHeader; - if (FixedIo->Length != 0) { - SerialDevice->BaseAddress = FixedIo->BaseAddress; - } - break; + break; - case ACPI_ADDRESS_SPACE_DESCRIPTOR: - AddressSpace = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Resources.SmallHeader; - if (AddressSpace->AddrLen != 0) { - if (AddressSpace->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { - SerialDevice->MmioAccess = TRUE; + case ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR: + FixedIo = (EFI_ACPI_FIXED_LOCATION_IO_PORT_DESCRIPTOR *)Resources.SmallHeader; + if (FixedIo->Length != 0) { + SerialDevice->BaseAddress = FixedIo->BaseAddress; } - SerialDevice->BaseAddress = AddressSpace->AddrRangeMin + Offset; - } - break; + + break; + + case ACPI_ADDRESS_SPACE_DESCRIPTOR: + AddressSpace = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Resources.SmallHeader; + if (AddressSpace->AddrLen != 0) { + if (AddressSpace->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { + SerialDevice->MmioAccess = TRUE; + } + + SerialDevice->BaseAddress = AddressSpace->AddrRangeMin + Offset; + } + + break; } if (Resources.SmallHeader->Bits.Type == 0) { - Resources.SmallHeader = (ACPI_SMALL_RESOURCE_HEADER *) ((UINT8 *) Resources.SmallHeader - + Resources.SmallHeader->Bits.Length - + sizeof (*Resources.SmallHeader)); + Resources.SmallHeader = (ACPI_SMALL_RESOURCE_HEADER *)((UINT8 *)Resources.SmallHeader + + Resources.SmallHeader->Bits.Length + + sizeof (*Resources.SmallHeader)); } else { - Resources.LargeHeader = (ACPI_LARGE_RESOURCE_HEADER *) ((UINT8 *) Resources.LargeHeader - + Resources.LargeHeader->Length - + sizeof (*Resources.LargeHeader)); + Resources.LargeHeader = (ACPI_LARGE_RESOURCE_HEADER *)((UINT8 *)Resources.LargeHeader + + Resources.LargeHeader->Length + + sizeof (*Resources.LargeHeader)); } } } @@ -550,7 +572,7 @@ CreateSerialDevice ( goto CreateError; } - SerialDevice->HardwareFlowControl = (BOOLEAN) (FlowControlMap == UART_FLOW_CONTROL_HARDWARE); + SerialDevice->HardwareFlowControl = (BOOLEAN)(FlowControlMap == UART_FLOW_CONTROL_HARDWARE); // // Report status code the serial present @@ -576,10 +598,10 @@ CreateSerialDevice ( // if (CreateControllerNode) { mControllerDevicePathTemplate.ControllerNumber = SerialDevice->Instance; - SerialDevice->DevicePath = AppendDevicePathNode ( - SerialDevice->ParentDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &mControllerDevicePathTemplate - ); + SerialDevice->DevicePath = AppendDevicePathNode ( + SerialDevice->ParentDevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&mControllerDevicePathTemplate + ); SerialDevice->ContainsControllerNode = TRUE; } @@ -592,15 +614,16 @@ CreateSerialDevice ( if (TempDevicePath != NULL) { SerialDevice->DevicePath = AppendDevicePathNode ( TempDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &SerialDevice->UartDevicePath + (EFI_DEVICE_PATH_PROTOCOL *)&SerialDevice->UartDevicePath ); FreePool (TempDevicePath); } else { SerialDevice->DevicePath = AppendDevicePathNode ( SerialDevice->ParentDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &SerialDevice->UartDevicePath + (EFI_DEVICE_PATH_PROTOCOL *)&SerialDevice->UartDevicePath ); } + // // 3. Append the Flow Control device path node. // Only produce the Flow Control node when remaining device path has it @@ -610,11 +633,12 @@ CreateSerialDevice ( if (TempDevicePath != NULL) { SerialDevice->DevicePath = AppendDevicePathNode ( TempDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) FlowControl + (EFI_DEVICE_PATH_PROTOCOL *)FlowControl ); FreePool (TempDevicePath); } } + ASSERT (SerialDevice->DevicePath != NULL); // @@ -644,20 +668,23 @@ CreateSerialDevice ( // Status = gBS->InstallMultipleProtocolInterfaces ( &SerialDevice->Handle, - &gEfiDevicePathProtocolGuid, SerialDevice->DevicePath, - &gEfiSerialIoProtocolGuid, &SerialDevice->SerialIo, + &gEfiDevicePathProtocolGuid, + SerialDevice->DevicePath, + &gEfiSerialIoProtocolGuid, + &SerialDevice->SerialIo, NULL ); if (EFI_ERROR (Status)) { goto CreateError; } + // // Open For Child Device // Status = gBS->OpenProtocol ( Controller, PciSerialParameter != NULL ? &gEfiPciIoProtocolGuid : &gEfiSioProtocolGuid, - (VOID **) &ParentIo, + (VOID **)&ParentIo, gSerialControllerDriver.DriverBindingHandle, SerialDevice->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -666,8 +693,10 @@ CreateSerialDevice ( if (EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( SerialDevice->Handle, - &gEfiDevicePathProtocolGuid, SerialDevice->DevicePath, - &gEfiSerialIoProtocolGuid, &SerialDevice->SerialIo, + &gEfiDevicePathProtocolGuid, + SerialDevice->DevicePath, + &gEfiSerialIoProtocolGuid, + &SerialDevice->SerialIo, NULL ); } @@ -677,11 +706,14 @@ CreateError: if (SerialDevice->DevicePath != NULL) { FreePool (SerialDevice->DevicePath); } + if (SerialDevice->ControllerNameTable != NULL) { FreeUnicodeStringTable (SerialDevice->ControllerNameTable); } + FreePool (SerialDevice); } + return Status; } @@ -697,18 +729,18 @@ CreateError: **/ SERIAL_DEV ** GetChildSerialDevices ( - IN EFI_HANDLE Controller, - IN EFI_GUID *IoProtocolGuid, - OUT UINTN *Count + IN EFI_HANDLE Controller, + IN EFI_GUID *IoProtocolGuid, + OUT UINTN *Count ) { - EFI_STATUS Status; - UINTN Index; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; - UINTN EntryCount; - SERIAL_DEV **SerialDevices; - EFI_SERIAL_IO_PROTOCOL *SerialIo; - BOOLEAN OpenByDriver; + EFI_STATUS Status; + UINTN Index; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; + UINTN EntryCount; + SERIAL_DEV **SerialDevices; + EFI_SERIAL_IO_PROTOCOL *SerialIo; + BOOLEAN OpenByDriver; *Count = 0; // @@ -716,11 +748,11 @@ GetChildSerialDevices ( // update the attributes/control. // Status = gBS->OpenProtocolInformation ( - Controller, - IoProtocolGuid, - &OpenInfoBuffer, - &EntryCount - ); + Controller, + IoProtocolGuid, + &OpenInfoBuffer, + &EntryCount + ); if (EFI_ERROR (Status)) { return NULL; } @@ -728,29 +760,29 @@ GetChildSerialDevices ( SerialDevices = AllocatePool (EntryCount * sizeof (SERIAL_DEV *)); ASSERT (SerialDevices != NULL); - *Count = 0; + *Count = 0; OpenByDriver = FALSE; for (Index = 0; Index < EntryCount; Index++) { if ((OpenInfoBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) { Status = gBS->OpenProtocol ( - OpenInfoBuffer[Index].ControllerHandle, - &gEfiSerialIoProtocolGuid, - (VOID **) &SerialIo, - gSerialControllerDriver.DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + OpenInfoBuffer[Index].ControllerHandle, + &gEfiSerialIoProtocolGuid, + (VOID **)&SerialIo, + gSerialControllerDriver.DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); if (!EFI_ERROR (Status)) { SerialDevices[(*Count)++] = SERIAL_DEV_FROM_THIS (SerialIo); } } - if ((OpenInfoBuffer[Index].Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { ASSERT (OpenInfoBuffer[Index].AgentHandle == gSerialControllerDriver.DriverBindingHandle); OpenByDriver = TRUE; } } + if (OpenInfoBuffer != NULL) { FreePool (OpenInfoBuffer); } @@ -772,32 +804,32 @@ GetChildSerialDevices ( EFI_STATUS EFIAPI SerialControllerDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_DEVICE_PATH_PROTOCOL *Node; - EFI_SERIAL_IO_PROTOCOL *SerialIo; - UINT32 ControllerNumber; - UART_DEVICE_PATH *Uart; - UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; - UINT32 Control; - PARENT_IO_PROTOCOL_PTR ParentIo; - ACPI_HID_DEVICE_PATH *Acpi; - EFI_GUID *IoProtocolGuid; - PCI_SERIAL_PARAMETER *PciSerialParameter; - PCI_SERIAL_PARAMETER DefaultPciSerialParameter; - PCI_TYPE00 Pci; - UINT32 PciSerialCount; - SERIAL_DEV **SerialDevices; - UINTN SerialDeviceCount; - PCI_DEVICE_INFO *PciDeviceInfo; - UINT64 Supports; - BOOLEAN ContainsControllerNode; + EFI_STATUS Status; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_SERIAL_IO_PROTOCOL *SerialIo; + UINT32 ControllerNumber; + UART_DEVICE_PATH *Uart; + UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; + UINT32 Control; + PARENT_IO_PROTOCOL_PTR ParentIo; + ACPI_HID_DEVICE_PATH *Acpi; + EFI_GUID *IoProtocolGuid; + PCI_SERIAL_PARAMETER *PciSerialParameter; + PCI_SERIAL_PARAMETER DefaultPciSerialParameter; + PCI_TYPE00 Pci; + UINT32 PciSerialCount; + SERIAL_DEV **SerialDevices; + UINTN SerialDeviceCount; + PCI_DEVICE_INFO *PciDeviceInfo; + UINT64 Supports; + BOOLEAN ContainsControllerNode; // // Get the Parent Device Path @@ -805,14 +837,15 @@ SerialControllerDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER ); - if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) { + if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { return Status; } + // // Report status code enable the serial // @@ -826,25 +859,26 @@ SerialControllerDriverStart ( // Grab the IO abstraction we need to get any work done // IoProtocolGuid = &gEfiSioProtocolGuid; - Status = gBS->OpenProtocol ( - Controller, - IoProtocolGuid, - (VOID **) &ParentIo, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); - if (EFI_ERROR (Status) && Status != EFI_ALREADY_STARTED) { + Status = gBS->OpenProtocol ( + Controller, + IoProtocolGuid, + (VOID **)&ParentIo, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); + if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { IoProtocolGuid = &gEfiPciIoProtocolGuid; - Status = gBS->OpenProtocol ( - Controller, - IoProtocolGuid, - (VOID **) &ParentIo, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Status = gBS->OpenProtocol ( + Controller, + IoProtocolGuid, + (VOID **)&ParentIo, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); } + ASSERT (!EFI_ERROR (Status) || Status == EFI_ALREADY_STARTED); // @@ -854,9 +888,9 @@ SerialControllerDriverStart ( return EFI_SUCCESS; } - ControllerNumber = 0; + ControllerNumber = 0; ContainsControllerNode = FALSE; - SerialDevices = GetChildSerialDevices (Controller, IoProtocolGuid, &SerialDeviceCount); + SerialDevices = GetChildSerialDevices (Controller, IoProtocolGuid, &SerialDeviceCount); if (SerialDeviceCount != 0) { if (RemainingDevicePath == NULL) { @@ -869,31 +903,41 @@ SerialControllerDriverStart ( // // Update the attributes/control of the SerialIo instance specified by RemainingDevicePath. // - Uart = (UART_DEVICE_PATH *) SkipControllerDevicePathNode (RemainingDevicePath, &ContainsControllerNode, &ControllerNumber); + Uart = (UART_DEVICE_PATH *)SkipControllerDevicePathNode (RemainingDevicePath, &ContainsControllerNode, &ControllerNumber); for (Index = 0; Index < SerialDeviceCount; Index++) { ASSERT ((SerialDevices != NULL) && (SerialDevices[Index] != NULL)); if ((!SerialDevices[Index]->ContainsControllerNode && !ContainsControllerNode) || - (SerialDevices[Index]->ContainsControllerNode && ContainsControllerNode && SerialDevices[Index]->Instance == ControllerNumber) - ) { + (SerialDevices[Index]->ContainsControllerNode && ContainsControllerNode && (SerialDevices[Index]->Instance == ControllerNumber)) + ) + { SerialIo = &SerialDevices[Index]->SerialIo; - Status = EFI_INVALID_PARAMETER; + Status = EFI_INVALID_PARAMETER; // // Pass NULL ActualBaudRate to VerifyUartParameters to disallow baudrate degrade. // DriverBindingStart() shouldn't create a handle with different UART device path. // - if (VerifyUartParameters (SerialDevices[Index]->ClockRate, Uart->BaudRate, Uart->DataBits, - (EFI_PARITY_TYPE) Uart->Parity, (EFI_STOP_BITS_TYPE) Uart->StopBits, NULL, NULL)) { + if (VerifyUartParameters ( + SerialDevices[Index]->ClockRate, + Uart->BaudRate, + Uart->DataBits, + (EFI_PARITY_TYPE)Uart->Parity, + (EFI_STOP_BITS_TYPE)Uart->StopBits, + NULL, + NULL + )) + { Status = SerialIo->SetAttributes ( SerialIo, Uart->BaudRate, SerialIo->Mode->ReceiveFifoDepth, SerialIo->Mode->Timeout, - (EFI_PARITY_TYPE) Uart->Parity, + (EFI_PARITY_TYPE)Uart->Parity, Uart->DataBits, - (EFI_STOP_BITS_TYPE) Uart->StopBits + (EFI_STOP_BITS_TYPE)Uart->StopBits ); } - FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) NextDevicePathNode (Uart); + + FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *)NextDevicePathNode (Uart); if (!EFI_ERROR (Status) && IsUartFlowControlDevicePathNode (FlowControl)) { Status = SerialIo->GetControl (SerialIo, &Control); if (!EFI_ERROR (Status)) { @@ -902,6 +946,7 @@ SerialControllerDriverStart ( } else { Control &= ~EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE; } + // // Clear the bits that are not allowed to pass to SetControl // @@ -911,9 +956,11 @@ SerialControllerDriverStart ( Status = SerialIo->SetControl (SerialIo, Control); } } + break; } } + if (Index != SerialDeviceCount) { // // Directly return if the SerialIo instance specified by RemainingDevicePath is found and updated. @@ -922,13 +969,14 @@ SerialControllerDriverStart ( if (SerialDevices != NULL) { FreePool (SerialDevices); } + return Status; } } } if (RemainingDevicePath != NULL) { - Uart = (UART_DEVICE_PATH *) SkipControllerDevicePathNode (RemainingDevicePath, &ContainsControllerNode, &ControllerNumber); + Uart = (UART_DEVICE_PATH *)SkipControllerDevicePathNode (RemainingDevicePath, &ContainsControllerNode, &ControllerNumber); } else { Uart = NULL; } @@ -936,12 +984,13 @@ SerialControllerDriverStart ( PciDeviceInfo = NULL; if (IoProtocolGuid == &gEfiSioProtocolGuid) { Status = EFI_NOT_FOUND; - if (RemainingDevicePath == NULL || !ContainsControllerNode) { + if ((RemainingDevicePath == NULL) || !ContainsControllerNode) { Node = ParentDevicePath; do { - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; Node = NextDevicePathNode (Node); } while (!IsDevicePathEnd (Node)); + Status = CreateSerialDevice (Controller, Uart, ParentDevicePath, FALSE, Acpi->UID, ParentIo, NULL, NULL); DEBUG ((DEBUG_INFO, "PciSioSerial: Create SIO child serial device - %r\n", Status)); } @@ -955,7 +1004,8 @@ SerialControllerDriverStart ( for (PciSerialParameter = PcdGetPtr (PcdPciSerialParameters); PciSerialParameter->VendorId != 0xFFFF; PciSerialParameter++) { if ((PciSerialParameter->VendorId == Pci.Hdr.VendorId) && (PciSerialParameter->DeviceId == Pci.Hdr.DeviceId) - ) { + ) + { PciSerialCount++; } } @@ -968,29 +1018,29 @@ SerialControllerDriverStart ( PciDeviceInfo = AllocatePool (sizeof (PCI_DEVICE_INFO)); ASSERT (PciDeviceInfo != NULL); PciDeviceInfo->ChildCount = 0; - PciDeviceInfo->PciIo = ParentIo.PciIo; - Status = ParentIo.PciIo->Attributes ( - ParentIo.PciIo, - EfiPciIoAttributeOperationGet, - 0, - &PciDeviceInfo->PciAttributes - ); + PciDeviceInfo->PciIo = ParentIo.PciIo; + Status = ParentIo.PciIo->Attributes ( + ParentIo.PciIo, + EfiPciIoAttributeOperationGet, + 0, + &PciDeviceInfo->PciAttributes + ); if (!EFI_ERROR (Status)) { Status = ParentIo.PciIo->Attributes ( - ParentIo.PciIo, - EfiPciIoAttributeOperationSupported, - 0, - &Supports - ); + ParentIo.PciIo, + EfiPciIoAttributeOperationSupported, + 0, + &Supports + ); if (!EFI_ERROR (Status)) { Supports &= (UINT64)(EFI_PCI_IO_ATTRIBUTE_IO | EFI_PCI_IO_ATTRIBUTE_MEMORY); - Status = ParentIo.PciIo->Attributes ( - ParentIo.PciIo, - EfiPciIoAttributeOperationEnable, - Supports, - NULL - ); + Status = ParentIo.PciIo->Attributes ( + ParentIo.PciIo, + EfiPciIoAttributeOperationEnable, + Supports, + NULL + ); } } } else { @@ -1007,18 +1057,18 @@ SerialControllerDriverStart ( // // PCI serial device contains only one UART // - if (RemainingDevicePath == NULL || !ContainsControllerNode) { + if ((RemainingDevicePath == NULL) || !ContainsControllerNode) { // // This PCI serial device is matched by class code in Supported() // if (PciSerialCount == 0) { - DefaultPciSerialParameter.VendorId = Pci.Hdr.VendorId; - DefaultPciSerialParameter.DeviceId = Pci.Hdr.DeviceId; - DefaultPciSerialParameter.BarIndex = 0; - DefaultPciSerialParameter.Offset = 0; + DefaultPciSerialParameter.VendorId = Pci.Hdr.VendorId; + DefaultPciSerialParameter.DeviceId = Pci.Hdr.DeviceId; + DefaultPciSerialParameter.BarIndex = 0; + DefaultPciSerialParameter.Offset = 0; DefaultPciSerialParameter.RegisterStride = 0; - DefaultPciSerialParameter.ClockRate = 0; - PciSerialParameter = &DefaultPciSerialParameter; + DefaultPciSerialParameter.ClockRate = 0; + PciSerialParameter = &DefaultPciSerialParameter; } else if (PciSerialCount == 1) { PciSerialParameter = PcdGetPtr (PcdPciSerialParameters); } @@ -1033,13 +1083,14 @@ SerialControllerDriverStart ( // // PCI serial device contains multiple UARTs // - if (RemainingDevicePath == NULL || ContainsControllerNode) { + if ((RemainingDevicePath == NULL) || ContainsControllerNode) { PciSerialCount = 0; for (PciSerialParameter = PcdGetPtr (PcdPciSerialParameters); PciSerialParameter->VendorId != 0xFFFF; PciSerialParameter++) { if ((PciSerialParameter->VendorId == Pci.Hdr.VendorId) && (PciSerialParameter->DeviceId == Pci.Hdr.DeviceId) && ((RemainingDevicePath == NULL) || (ControllerNumber == PciSerialCount)) - ) { + ) + { // // Create controller node when PCI serial device contains multiple UARTs // @@ -1070,14 +1121,15 @@ SerialControllerDriverStart ( if (EFI_ERROR (Status) && (SerialDeviceCount == 0)) { if (PciDeviceInfo != NULL) { Status = ParentIo.PciIo->Attributes ( - ParentIo.PciIo, - EfiPciIoAttributeOperationSet, - PciDeviceInfo->PciAttributes, - NULL - ); + ParentIo.PciIo, + EfiPciIoAttributeOperationSet, + PciDeviceInfo->PciAttributes, + NULL + ); ASSERT_EFI_ERROR (Status); FreePool (PciDeviceInfo); } + gBS->CloseProtocol ( Controller, &gEfiDevicePathProtocolGuid, @@ -1110,28 +1162,28 @@ SerialControllerDriverStart ( EFI_STATUS EFIAPI SerialControllerDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - UINTN Index; - BOOLEAN AllChildrenStopped; - EFI_SERIAL_IO_PROTOCOL *SerialIo; - SERIAL_DEV *SerialDevice; - VOID *IoProtocol; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - PCI_DEVICE_INFO *PciDeviceInfo; + EFI_STATUS Status; + UINTN Index; + BOOLEAN AllChildrenStopped; + EFI_SERIAL_IO_PROTOCOL *SerialIo; + SERIAL_DEV *SerialDevice; + VOID *IoProtocol; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + PCI_DEVICE_INFO *PciDeviceInfo; PciDeviceInfo = NULL; Status = gBS->HandleProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath + (VOID **)&DevicePath ); // @@ -1174,17 +1226,15 @@ SerialControllerDriverStop ( AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiSerialIoProtocolGuid, - (VOID **) &SerialIo, + (VOID **)&SerialIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR (Status)) { - SerialDevice = SERIAL_DEV_FROM_THIS (SerialIo); ASSERT ((PciDeviceInfo == NULL) || (PciDeviceInfo == SerialDevice->PciDeviceInfo)); PciDeviceInfo = SerialDevice->PciDeviceInfo; @@ -1198,8 +1248,10 @@ SerialControllerDriverStop ( Status = gBS->UninstallMultipleProtocolInterfaces ( ChildHandleBuffer[Index], - &gEfiDevicePathProtocolGuid, SerialDevice->DevicePath, - &gEfiSerialIoProtocolGuid, &SerialDevice->SerialIo, + &gEfiDevicePathProtocolGuid, + SerialDevice->DevicePath, + &gEfiSerialIoProtocolGuid, + &SerialDevice->SerialIo, NULL ); if (EFI_ERROR (Status)) { @@ -1237,14 +1289,15 @@ SerialControllerDriverStop ( if ((PciDeviceInfo != NULL) && (PciDeviceInfo->ChildCount == 0)) { ASSERT (PciDeviceInfo->PciIo != NULL); Status = PciDeviceInfo->PciIo->Attributes ( - PciDeviceInfo->PciIo, - EfiPciIoAttributeOperationSet, - PciDeviceInfo->PciAttributes, - NULL - ); + PciDeviceInfo->PciIo, + EfiPciIoAttributeOperationSet, + PciDeviceInfo->PciAttributes, + NULL + ); ASSERT_EFI_ERROR (Status); FreePool (PciDeviceInfo); } + return EFI_SUCCESS; } } diff --git a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.h b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.h index fa5aba07e1..5903ab5cd3 100644 --- a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.h +++ b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/Serial.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SERIAL_H_ #define _SERIAL_H_ - #include #include @@ -34,13 +33,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Driver Binding Externs // -extern EFI_DRIVER_BINDING_PROTOCOL gSerialControllerDriver; -extern EFI_COMPONENT_NAME_PROTOCOL gPciSioSerialComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gPciSioSerialComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gSerialControllerDriver; +extern EFI_COMPONENT_NAME_PROTOCOL gPciSioSerialComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gPciSioSerialComponentName2; -#define SIO_SERIAL_PORT_NAME L"SIO Serial Port #%d" -#define PCI_SERIAL_PORT_NAME L"PCI Serial Port #%d" -#define SERIAL_PORT_NAME_LEN (sizeof (SIO_SERIAL_PORT_NAME) / sizeof (CHAR16) + MAXIMUM_VALUE_CHARACTERS) +#define SIO_SERIAL_PORT_NAME L"SIO Serial Port #%d" +#define PCI_SERIAL_PORT_NAME L"PCI Serial Port #%d" +#define SERIAL_PORT_NAME_LEN (sizeof (SIO_SERIAL_PORT_NAME) / sizeof (CHAR16) + MAXIMUM_VALUE_CHARACTERS) // // Internal Data Structures @@ -61,73 +60,73 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gPciSioSerialComponentName2; /// RegisterStride equals to 4. /// typedef struct { - UINT16 VendorId; ///< Vendor ID to match the PCI device. The value 0xFFFF terminates the list of entries. - UINT16 DeviceId; ///< Device ID to match the PCI device - UINT32 ClockRate; ///< UART clock rate. Set to 0 for default clock rate of 1843200 Hz - UINT64 Offset; ///< The byte offset into to the BAR - UINT8 BarIndex; ///< Which BAR to get the UART base address - UINT8 RegisterStride; ///< UART register stride in bytes. Set to 0 for default register stride of 1 byte. - UINT16 ReceiveFifoDepth; ///< UART receive FIFO depth in bytes. Set to 0 for a default FIFO depth of 16 bytes. - UINT16 TransmitFifoDepth; ///< UART transmit FIFO depth in bytes. Set to 0 for a default FIFO depth of 16 bytes. - UINT8 Reserved[2]; + UINT16 VendorId; ///< Vendor ID to match the PCI device. The value 0xFFFF terminates the list of entries. + UINT16 DeviceId; ///< Device ID to match the PCI device + UINT32 ClockRate; ///< UART clock rate. Set to 0 for default clock rate of 1843200 Hz + UINT64 Offset; ///< The byte offset into to the BAR + UINT8 BarIndex; ///< Which BAR to get the UART base address + UINT8 RegisterStride; ///< UART register stride in bytes. Set to 0 for default register stride of 1 byte. + UINT16 ReceiveFifoDepth; ///< UART receive FIFO depth in bytes. Set to 0 for a default FIFO depth of 16 bytes. + UINT16 TransmitFifoDepth; ///< UART transmit FIFO depth in bytes. Set to 0 for a default FIFO depth of 16 bytes. + UINT8 Reserved[2]; } PCI_SERIAL_PARAMETER; #pragma pack() -#define SERIAL_MAX_FIFO_SIZE 17 ///< Actual FIFO size is 16. FIFO based on circular wastes one unit. +#define SERIAL_MAX_FIFO_SIZE 17 ///< Actual FIFO size is 16. FIFO based on circular wastes one unit. typedef struct { - UINT16 Head; ///< Head pointer of the FIFO. Empty when (Head == Tail). - UINT16 Tail; ///< Tail pointer of the FIFO. Full when ((Tail + 1) % SERIAL_MAX_FIFO_SIZE == Head). - UINT8 Data[SERIAL_MAX_FIFO_SIZE]; ///< Store the FIFO data. + UINT16 Head; ///< Head pointer of the FIFO. Empty when (Head == Tail). + UINT16 Tail; ///< Tail pointer of the FIFO. Full when ((Tail + 1) % SERIAL_MAX_FIFO_SIZE == Head). + UINT8 Data[SERIAL_MAX_FIFO_SIZE]; ///< Store the FIFO data. } SERIAL_DEV_FIFO; typedef union { - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_SIO_PROTOCOL *Sio; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_SIO_PROTOCOL *Sio; } PARENT_IO_PROTOCOL_PTR; typedef struct { - EFI_PCI_IO_PROTOCOL *PciIo; // Pointer to parent PciIo instance. - UINTN ChildCount; // Count of child SerialIo instance. - UINT64 PciAttributes; // Original PCI attributes. + EFI_PCI_IO_PROTOCOL *PciIo; // Pointer to parent PciIo instance. + UINTN ChildCount; // Count of child SerialIo instance. + UINT64 PciAttributes; // Original PCI attributes. } PCI_DEVICE_INFO; typedef struct { - UINT32 Signature; - EFI_HANDLE Handle; - EFI_SERIAL_IO_PROTOCOL SerialIo; - EFI_SERIAL_IO_MODE SerialMode; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - UART_DEVICE_PATH UartDevicePath; - - EFI_PHYSICAL_ADDRESS BaseAddress; ///< UART base address - BOOLEAN MmioAccess; ///< TRUE for MMIO, FALSE for IO - UINT8 RegisterStride; ///< UART Register Stride - UINT32 ClockRate; ///< UART clock rate - - UINT16 ReceiveFifoDepth; ///< UART receive FIFO depth in bytes. - SERIAL_DEV_FIFO Receive; ///< The FIFO used to store received data - - UINT16 TransmitFifoDepth; ///< UART transmit FIFO depth in bytes. - SERIAL_DEV_FIFO Transmit; ///< The FIFO used to store to-transmit data - - BOOLEAN SoftwareLoopbackEnable; - BOOLEAN HardwareFlowControl; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; - BOOLEAN ContainsControllerNode; ///< TRUE if the device produced contains Controller node - UINT32 Instance; - PCI_DEVICE_INFO *PciDeviceInfo; + UINT32 Signature; + EFI_HANDLE Handle; + EFI_SERIAL_IO_PROTOCOL SerialIo; + EFI_SERIAL_IO_MODE SerialMode; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + UART_DEVICE_PATH UartDevicePath; + + EFI_PHYSICAL_ADDRESS BaseAddress; ///< UART base address + BOOLEAN MmioAccess; ///< TRUE for MMIO, FALSE for IO + UINT8 RegisterStride; ///< UART Register Stride + UINT32 ClockRate; ///< UART clock rate + + UINT16 ReceiveFifoDepth; ///< UART receive FIFO depth in bytes. + SERIAL_DEV_FIFO Receive; ///< The FIFO used to store received data + + UINT16 TransmitFifoDepth; ///< UART transmit FIFO depth in bytes. + SERIAL_DEV_FIFO Transmit; ///< The FIFO used to store to-transmit data + + BOOLEAN SoftwareLoopbackEnable; + BOOLEAN HardwareFlowControl; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; + BOOLEAN ContainsControllerNode; ///< TRUE if the device produced contains Controller node + UINT32 Instance; + PCI_DEVICE_INFO *PciDeviceInfo; } SERIAL_DEV; -#define SERIAL_DEV_SIGNATURE SIGNATURE_32 ('s', 'e', 'r', 'd') -#define SERIAL_DEV_FROM_THIS(a) CR (a, SERIAL_DEV, SerialIo, SERIAL_DEV_SIGNATURE) +#define SERIAL_DEV_SIGNATURE SIGNATURE_32 ('s', 'e', 'r', 'd') +#define SERIAL_DEV_FROM_THIS(a) CR (a, SERIAL_DEV, SerialIo, SERIAL_DEV_SIGNATURE) // // Serial Driver Defaults // -#define SERIAL_PORT_DEFAULT_TIMEOUT 1000000 -#define SERIAL_PORT_SUPPORT_CONTROL_MASK (EFI_SERIAL_CLEAR_TO_SEND | \ +#define SERIAL_PORT_DEFAULT_TIMEOUT 1000000 +#define SERIAL_PORT_SUPPORT_CONTROL_MASK (EFI_SERIAL_CLEAR_TO_SEND | \ EFI_SERIAL_DATA_SET_READY | \ EFI_SERIAL_RING_INDICATE | \ EFI_SERIAL_CARRIER_DETECT | \ @@ -139,23 +138,23 @@ typedef struct { EFI_SERIAL_OUTPUT_BUFFER_EMPTY | \ EFI_SERIAL_INPUT_BUFFER_EMPTY) -#define SERIAL_PORT_MIN_TIMEOUT 1 // 1 uS -#define SERIAL_PORT_MAX_TIMEOUT 100000000 // 100 seconds +#define SERIAL_PORT_MIN_TIMEOUT 1 // 1 uS +#define SERIAL_PORT_MAX_TIMEOUT 100000000 // 100 seconds // // UART Registers // -#define SERIAL_REGISTER_THR 0 ///< WO Transmit Holding Register -#define SERIAL_REGISTER_RBR 0 ///< RO Receive Buffer Register -#define SERIAL_REGISTER_DLL 0 ///< R/W Divisor Latch LSB -#define SERIAL_REGISTER_DLM 1 ///< R/W Divisor Latch MSB -#define SERIAL_REGISTER_IER 1 ///< R/W Interrupt Enable Register -#define SERIAL_REGISTER_IIR 2 ///< RO Interrupt Identification Register -#define SERIAL_REGISTER_FCR 2 ///< WO FIFO Cotrol Register -#define SERIAL_REGISTER_LCR 3 ///< R/W Line Control Register -#define SERIAL_REGISTER_MCR 4 ///< R/W Modem Control Register -#define SERIAL_REGISTER_LSR 5 ///< R/W Line Status Register -#define SERIAL_REGISTER_MSR 6 ///< R/W Modem Status Register -#define SERIAL_REGISTER_SCR 7 ///< R/W Scratch Pad Register +#define SERIAL_REGISTER_THR 0 ///< WO Transmit Holding Register +#define SERIAL_REGISTER_RBR 0 ///< RO Receive Buffer Register +#define SERIAL_REGISTER_DLL 0 ///< R/W Divisor Latch LSB +#define SERIAL_REGISTER_DLM 1 ///< R/W Divisor Latch MSB +#define SERIAL_REGISTER_IER 1 ///< R/W Interrupt Enable Register +#define SERIAL_REGISTER_IIR 2 ///< RO Interrupt Identification Register +#define SERIAL_REGISTER_FCR 2 ///< WO FIFO Cotrol Register +#define SERIAL_REGISTER_LCR 3 ///< R/W Line Control Register +#define SERIAL_REGISTER_MCR 4 ///< R/W Modem Control Register +#define SERIAL_REGISTER_LSR 5 ///< R/W Line Status Register +#define SERIAL_REGISTER_MSR 6 ///< R/W Modem Status Register +#define SERIAL_REGISTER_SCR 7 ///< R/W Scratch Pad Register #pragma pack(1) /// @@ -163,13 +162,13 @@ typedef struct { /// typedef union { struct { - UINT8 Ravie : 1; ///< Receiver Data Available Interrupt Enable - UINT8 Theie : 1; ///< Transmistter Holding Register Empty Interrupt Enable - UINT8 Rie : 1; ///< Receiver Interrupt Enable - UINT8 Mie : 1; ///< Modem Interrupt Enable - UINT8 Reserved : 4; + UINT8 Ravie : 1; ///< Receiver Data Available Interrupt Enable + UINT8 Theie : 1; ///< Transmistter Holding Register Empty Interrupt Enable + UINT8 Rie : 1; ///< Receiver Interrupt Enable + UINT8 Mie : 1; ///< Modem Interrupt Enable + UINT8 Reserved : 4; } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_IER; /// @@ -177,15 +176,15 @@ typedef union { /// typedef union { struct { - UINT8 TrFIFOE : 1; ///< Transmit and Receive FIFO Enable - UINT8 ResetRF : 1; ///< Reset Reciever FIFO - UINT8 ResetTF : 1; ///< Reset Transmistter FIFO - UINT8 Dms : 1; ///< DMA Mode Select - UINT8 Reserved : 1; - UINT8 TrFIFO64 : 1; ///< Enable 64 byte FIFO - UINT8 Rtb : 2; ///< Receive Trigger Bits + UINT8 TrFIFOE : 1; ///< Transmit and Receive FIFO Enable + UINT8 ResetRF : 1; ///< Reset Reciever FIFO + UINT8 ResetTF : 1; ///< Reset Transmistter FIFO + UINT8 Dms : 1; ///< DMA Mode Select + UINT8 Reserved : 1; + UINT8 TrFIFO64 : 1; ///< Enable 64 byte FIFO + UINT8 Rtb : 2; ///< Receive Trigger Bits } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_FCR; /// @@ -193,15 +192,15 @@ typedef union { /// typedef union { struct { - UINT8 SerialDB : 2; ///< Number of Serial Data Bits - UINT8 StopB : 1; ///< Number of Stop Bits - UINT8 ParEn : 1; ///< Parity Enable - UINT8 EvenPar : 1; ///< Even Parity Select - UINT8 SticPar : 1; ///< Sticky Parity - UINT8 BrCon : 1; ///< Break Control - UINT8 DLab : 1; ///< Divisor Latch Access Bit + UINT8 SerialDB : 2; ///< Number of Serial Data Bits + UINT8 StopB : 1; ///< Number of Stop Bits + UINT8 ParEn : 1; ///< Parity Enable + UINT8 EvenPar : 1; ///< Even Parity Select + UINT8 SticPar : 1; ///< Sticky Parity + UINT8 BrCon : 1; ///< Break Control + UINT8 DLab : 1; ///< Divisor Latch Access Bit } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_LCR; /// @@ -209,14 +208,14 @@ typedef union { /// typedef union { struct { - UINT8 DtrC : 1; ///< Data Terminal Ready Control - UINT8 Rts : 1; ///< Request To Send Control - UINT8 Out1 : 1; ///< Output1 - UINT8 Out2 : 1; ///< Output2, used to disable interrupt - UINT8 Lme : 1; ///< Loopback Mode Enable - UINT8 Reserved : 3; + UINT8 DtrC : 1; ///< Data Terminal Ready Control + UINT8 Rts : 1; ///< Request To Send Control + UINT8 Out1 : 1; ///< Output1 + UINT8 Out2 : 1; ///< Output2, used to disable interrupt + UINT8 Lme : 1; ///< Loopback Mode Enable + UINT8 Reserved : 3; } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_MCR; /// @@ -224,16 +223,16 @@ typedef union { /// typedef union { struct { - UINT8 Dr : 1; ///< Receiver Data Ready Status - UINT8 Oe : 1; ///< Overrun Error Status - UINT8 Pe : 1; ///< Parity Error Status - UINT8 Fe : 1; ///< Framing Error Status - UINT8 Bi : 1; ///< Break Interrupt Status - UINT8 Thre : 1; ///< Transmistter Holding Register Status - UINT8 Temt : 1; ///< Transmitter Empty Status - UINT8 FIFOe : 1; ///< FIFO Error Status + UINT8 Dr : 1; ///< Receiver Data Ready Status + UINT8 Oe : 1; ///< Overrun Error Status + UINT8 Pe : 1; ///< Parity Error Status + UINT8 Fe : 1; ///< Framing Error Status + UINT8 Bi : 1; ///< Break Interrupt Status + UINT8 Thre : 1; ///< Transmistter Holding Register Status + UINT8 Temt : 1; ///< Transmitter Empty Status + UINT8 FIFOe : 1; ///< FIFO Error Status } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_LSR; /// @@ -241,48 +240,49 @@ typedef union { /// typedef union { struct { - UINT8 DeltaCTS : 1; ///< Delta Clear To Send Status - UINT8 DeltaDSR : 1; ///< Delta Data Set Ready Status - UINT8 TrailingEdgeRI : 1; ///< Trailing Edge of Ring Indicator Status - UINT8 DeltaDCD : 1; ///< Delta Data Carrier Detect Status - UINT8 Cts : 1; ///< Clear To Send Status - UINT8 Dsr : 1; ///< Data Set Ready Status - UINT8 Ri : 1; ///< Ring Indicator Status - UINT8 Dcd : 1; ///< Data Carrier Detect Status + UINT8 DeltaCTS : 1; ///< Delta Clear To Send Status + UINT8 DeltaDSR : 1; ///< Delta Data Set Ready Status + UINT8 TrailingEdgeRI : 1; ///< Trailing Edge of Ring Indicator Status + UINT8 DeltaDCD : 1; ///< Delta Data Carrier Detect Status + UINT8 Cts : 1; ///< Clear To Send Status + UINT8 Dsr : 1; ///< Data Set Ready Status + UINT8 Ri : 1; ///< Ring Indicator Status + UINT8 Dcd : 1; ///< Data Carrier Detect Status } Bits; - UINT8 Data; + UINT8 Data; } SERIAL_PORT_MSR; #pragma pack() // // Define serial register I/O macros // -#define READ_RBR(S) SerialReadRegister (S, SERIAL_REGISTER_RBR) -#define READ_DLL(S) SerialReadRegister (S, SERIAL_REGISTER_DLL) -#define READ_DLM(S) SerialReadRegister (S, SERIAL_REGISTER_DLM) -#define READ_IER(S) SerialReadRegister (S, SERIAL_REGISTER_IER) -#define READ_IIR(S) SerialReadRegister (S, SERIAL_REGISTER_IIR) -#define READ_LCR(S) SerialReadRegister (S, SERIAL_REGISTER_LCR) -#define READ_MCR(S) SerialReadRegister (S, SERIAL_REGISTER_MCR) -#define READ_LSR(S) SerialReadRegister (S, SERIAL_REGISTER_LSR) -#define READ_MSR(S) SerialReadRegister (S, SERIAL_REGISTER_MSR) -#define READ_SCR(S) SerialReadRegister (S, SERIAL_REGISTER_SCR) - -#define WRITE_THR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_THR, D) -#define WRITE_DLL(S, D) SerialWriteRegister (S, SERIAL_REGISTER_DLL, D) -#define WRITE_DLM(S, D) SerialWriteRegister (S, SERIAL_REGISTER_DLM, D) -#define WRITE_IER(S, D) SerialWriteRegister (S, SERIAL_REGISTER_IER, D) -#define WRITE_FCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_FCR, D) -#define WRITE_LCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_LCR, D) -#define WRITE_MCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_MCR, D) -#define WRITE_LSR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_LSR, D) -#define WRITE_MSR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_MSR, D) -#define WRITE_SCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_SCR, D) +#define READ_RBR(S) SerialReadRegister (S, SERIAL_REGISTER_RBR) +#define READ_DLL(S) SerialReadRegister (S, SERIAL_REGISTER_DLL) +#define READ_DLM(S) SerialReadRegister (S, SERIAL_REGISTER_DLM) +#define READ_IER(S) SerialReadRegister (S, SERIAL_REGISTER_IER) +#define READ_IIR(S) SerialReadRegister (S, SERIAL_REGISTER_IIR) +#define READ_LCR(S) SerialReadRegister (S, SERIAL_REGISTER_LCR) +#define READ_MCR(S) SerialReadRegister (S, SERIAL_REGISTER_MCR) +#define READ_LSR(S) SerialReadRegister (S, SERIAL_REGISTER_LSR) +#define READ_MSR(S) SerialReadRegister (S, SERIAL_REGISTER_MSR) +#define READ_SCR(S) SerialReadRegister (S, SERIAL_REGISTER_SCR) + +#define WRITE_THR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_THR, D) +#define WRITE_DLL(S, D) SerialWriteRegister (S, SERIAL_REGISTER_DLL, D) +#define WRITE_DLM(S, D) SerialWriteRegister (S, SERIAL_REGISTER_DLM, D) +#define WRITE_IER(S, D) SerialWriteRegister (S, SERIAL_REGISTER_IER, D) +#define WRITE_FCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_FCR, D) +#define WRITE_LCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_LCR, D) +#define WRITE_MCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_MCR, D) +#define WRITE_LSR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_LSR, D) +#define WRITE_MSR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_MSR, D) +#define WRITE_SCR(S, D) SerialWriteRegister (S, SERIAL_REGISTER_SCR, D) // // Prototypes // Driver model protocol interface // + /** Check to see if this driver supports the given controller @@ -296,9 +296,9 @@ typedef union { EFI_STATUS EFIAPI SerialControllerDriverSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -313,9 +313,9 @@ SerialControllerDriverSupported ( EFI_STATUS EFIAPI SerialControllerDriverStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -333,15 +333,16 @@ SerialControllerDriverStart ( EFI_STATUS EFIAPI SerialControllerDriverStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // Serial I/O Protocol Interface // + /** Reset serial device. @@ -354,7 +355,7 @@ SerialControllerDriverStop ( EFI_STATUS EFIAPI SerialReset ( - IN EFI_SERIAL_IO_PROTOCOL *This + IN EFI_SERIAL_IO_PROTOCOL *This ); /** @@ -377,13 +378,13 @@ SerialReset ( EFI_STATUS EFIAPI SerialSetAttributes ( - IN EFI_SERIAL_IO_PROTOCOL *This, - IN UINT64 BaudRate, - IN UINT32 ReceiveFifoDepth, - IN UINT32 Timeout, - IN EFI_PARITY_TYPE Parity, - IN UINT8 DataBits, - IN EFI_STOP_BITS_TYPE StopBits + IN EFI_SERIAL_IO_PROTOCOL *This, + IN UINT64 BaudRate, + IN UINT32 ReceiveFifoDepth, + IN UINT32 Timeout, + IN EFI_PARITY_TYPE Parity, + IN UINT8 DataBits, + IN EFI_STOP_BITS_TYPE StopBits ); /** @@ -399,8 +400,8 @@ SerialSetAttributes ( EFI_STATUS EFIAPI SerialSetControl ( - IN EFI_SERIAL_IO_PROTOCOL *This, - IN UINT32 Control + IN EFI_SERIAL_IO_PROTOCOL *This, + IN UINT32 Control ); /** @@ -415,8 +416,8 @@ SerialSetControl ( EFI_STATUS EFIAPI SerialGetControl ( - IN EFI_SERIAL_IO_PROTOCOL *This, - OUT UINT32 *Control + IN EFI_SERIAL_IO_PROTOCOL *This, + OUT UINT32 *Control ); /** @@ -435,9 +436,9 @@ SerialGetControl ( EFI_STATUS EFIAPI SerialWrite ( - IN EFI_SERIAL_IO_PROTOCOL *This, - IN OUT UINTN *BufferSize, - IN VOID *Buffer + IN EFI_SERIAL_IO_PROTOCOL *This, + IN OUT UINTN *BufferSize, + IN VOID *Buffer ); /** @@ -456,14 +457,15 @@ SerialWrite ( EFI_STATUS EFIAPI SerialRead ( - IN EFI_SERIAL_IO_PROTOCOL *This, - IN OUT UINTN *BufferSize, - OUT VOID *Buffer + IN EFI_SERIAL_IO_PROTOCOL *This, + IN OUT UINTN *BufferSize, + OUT VOID *Buffer ); // // Internal Functions // + /** Use scratchpad register to test if this serial port is present. @@ -473,7 +475,7 @@ SerialRead ( **/ BOOLEAN SerialPresent ( - IN SERIAL_DEV *SerialDevice + IN SERIAL_DEV *SerialDevice ); /** @@ -486,7 +488,7 @@ SerialPresent ( **/ BOOLEAN SerialFifoFull ( - IN SERIAL_DEV_FIFO *Fifo + IN SERIAL_DEV_FIFO *Fifo ); /** @@ -499,7 +501,7 @@ SerialFifoFull ( **/ BOOLEAN SerialFifoEmpty ( - IN SERIAL_DEV_FIFO *Fifo + IN SERIAL_DEV_FIFO *Fifo ); /** @@ -514,8 +516,8 @@ SerialFifoEmpty ( **/ EFI_STATUS SerialFifoAdd ( - IN SERIAL_DEV_FIFO *Fifo, - IN UINT8 Data + IN SERIAL_DEV_FIFO *Fifo, + IN UINT8 Data ); /** @@ -530,8 +532,8 @@ SerialFifoAdd ( **/ EFI_STATUS SerialFifoRemove ( - IN SERIAL_DEV_FIFO *Fifo, - OUT UINT8 *Data + IN SERIAL_DEV_FIFO *Fifo, + OUT UINT8 *Data ); /** @@ -546,7 +548,7 @@ SerialFifoRemove ( **/ EFI_STATUS SerialReceiveTransmit ( - IN SERIAL_DEV *SerialDevice + IN SERIAL_DEV *SerialDevice ); /** @@ -559,8 +561,8 @@ SerialReceiveTransmit ( **/ UINT8 SerialReadRegister ( - IN SERIAL_DEV *SerialDev, - IN UINT32 Offset + IN SERIAL_DEV *SerialDev, + IN UINT32 Offset ); /** @@ -572,15 +574,15 @@ SerialReadRegister ( **/ VOID SerialWriteRegister ( - IN SERIAL_DEV *SerialDev, - IN UINT32 Offset, - IN UINT8 Data + IN SERIAL_DEV *SerialDev, + IN UINT32 Offset, + IN UINT8 Data ); - // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -628,7 +630,6 @@ SerialComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -700,11 +701,11 @@ SerialComponentNameGetDriverName ( EFI_STATUS EFIAPI SerialComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -715,8 +716,8 @@ SerialComponentNameGetControllerName ( **/ VOID AddName ( - IN SERIAL_DEV *SerialDevice, - IN UINT32 Uid + IN SERIAL_DEV *SerialDevice, + IN UINT32 Uid ); /** @@ -741,13 +742,13 @@ AddName ( **/ BOOLEAN VerifyUartParameters ( - IN UINT32 ClockRate, - IN UINT64 BaudRate, - IN UINT8 DataBits, - IN EFI_PARITY_TYPE Parity, - IN EFI_STOP_BITS_TYPE StopBits, - OUT UINT64 *Divisor, - OUT UINT64 *ActualBaudRate + IN UINT32 ClockRate, + IN UINT64 BaudRate, + IN UINT8 DataBits, + IN EFI_PARITY_TYPE Parity, + IN EFI_STOP_BITS_TYPE StopBits, + OUT UINT64 *Divisor, + OUT UINT64 *ActualBaudRate ); /** @@ -762,9 +763,9 @@ VerifyUartParameters ( **/ UART_DEVICE_PATH * SkipControllerDevicePathNode ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath, - BOOLEAN *ContainsControllerNode, - UINT32 *ControllerNumber + EFI_DEVICE_PATH_PROTOCOL *DevicePath, + BOOLEAN *ContainsControllerNode, + UINT32 *ControllerNumber ); /** @@ -778,6 +779,7 @@ SkipControllerDevicePathNode ( **/ BOOLEAN IsUartFlowControlDevicePathNode ( - IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl + IN UART_FLOW_CONTROL_DEVICE_PATH *FlowControl ); + #endif diff --git a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/SerialIo.c b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/SerialIo.c index f8b9a0e3ee..8a85a6c3b8 100644 --- a/MdeModulePkg/Bus/Pci/PciSioSerialDxe/SerialIo.c +++ b/MdeModulePkg/Bus/Pci/PciSioSerialDxe/SerialIo.c @@ -20,27 +20,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UART_DEVICE_PATH * SkipControllerDevicePathNode ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath, - BOOLEAN *ContainsControllerNode, - UINT32 *ControllerNumber + EFI_DEVICE_PATH_PROTOCOL *DevicePath, + BOOLEAN *ContainsControllerNode, + UINT32 *ControllerNumber ) { if ((DevicePathType (DevicePath) == HARDWARE_DEVICE_PATH) && (DevicePathSubType (DevicePath) == HW_CONTROLLER_DP) - ) { + ) + { if (ContainsControllerNode != NULL) { *ContainsControllerNode = TRUE; } + if (ControllerNumber != NULL) { - *ControllerNumber = ((CONTROLLER_DEVICE_PATH *) DevicePath)->ControllerNumber; + *ControllerNumber = ((CONTROLLER_DEVICE_PATH *)DevicePath)->ControllerNumber; } + DevicePath = NextDevicePathNode (DevicePath); } else { if (ContainsControllerNode != NULL) { *ContainsControllerNode = FALSE; } } - return (UART_DEVICE_PATH *) DevicePath; + + return (UART_DEVICE_PATH *)DevicePath; } /** @@ -65,26 +69,27 @@ SkipControllerDevicePathNode ( **/ BOOLEAN VerifyUartParameters ( - IN UINT32 ClockRate, - IN UINT64 BaudRate, - IN UINT8 DataBits, - IN EFI_PARITY_TYPE Parity, - IN EFI_STOP_BITS_TYPE StopBits, - OUT UINT64 *Divisor, - OUT UINT64 *ActualBaudRate + IN UINT32 ClockRate, + IN UINT64 BaudRate, + IN UINT8 DataBits, + IN EFI_PARITY_TYPE Parity, + IN EFI_STOP_BITS_TYPE StopBits, + OUT UINT64 *Divisor, + OUT UINT64 *ActualBaudRate ) { - UINT64 Remainder; - UINT32 ComputedBaudRate; - UINT64 ComputedDivisor; - UINT64 Percent; + UINT64 Remainder; + UINT32 ComputedBaudRate; + UINT64 ComputedDivisor; + UINT64 Percent; if ((DataBits < 5) || (DataBits > 8) || (Parity < NoParity) || (Parity > SpaceParity) || (StopBits < OneStopBit) || (StopBits > TwoStopBits) || ((DataBits == 5) && (StopBits == TwoStopBits)) || ((DataBits >= 6) && (DataBits <= 8) && (StopBits == OneFiveStopBits)) - ) { + ) + { return FALSE; } @@ -108,6 +113,7 @@ VerifyUartParameters ( if (Remainder >= LShiftU64 (BaudRate, 3)) { ComputedDivisor++; } + // // If the computed divisor is larger than the maximum value that can be programmed // into the UART, then the requested baud rate can not be supported. @@ -128,13 +134,13 @@ VerifyUartParameters ( // Actual baud rate that the serial port will be programmed for // should be with in 4% of requested one. // - ComputedBaudRate = ClockRate / ((UINT16) ComputedDivisor << 4); + ComputedBaudRate = ClockRate / ((UINT16)ComputedDivisor << 4); if (ComputedBaudRate == 0) { return FALSE; } Percent = DivU64x32 (MultU64x32 (BaudRate, 100), ComputedBaudRate); - DEBUG ((DEBUG_INFO, "ClockRate = %d\n", ClockRate)); + DEBUG ((DEBUG_INFO, "ClockRate = %d\n", ClockRate)); DEBUG ((DEBUG_INFO, "Divisor = %ld\n", ComputedDivisor)); DEBUG ((DEBUG_INFO, "BaudRate/Actual (%ld/%d) = %d%%\n", BaudRate, ComputedBaudRate, Percent)); @@ -147,18 +153,23 @@ VerifyUartParameters ( if (ActualBaudRate != NULL) { *ActualBaudRate = BaudRate; } + if (Divisor != NULL) { *Divisor = ComputedDivisor; } + return TRUE; } + if (ComputedBaudRate < BaudRate) { if (ActualBaudRate != NULL) { *ActualBaudRate = ComputedBaudRate; } + if (Divisor != NULL) { *Divisor = ComputedDivisor; } + return TRUE; } @@ -170,22 +181,25 @@ VerifyUartParameters ( if (ComputedDivisor == MAX_UINT16) { return FALSE; } + ComputedDivisor++; - ComputedBaudRate = ClockRate / ((UINT16) ComputedDivisor << 4); + ComputedBaudRate = ClockRate / ((UINT16)ComputedDivisor << 4); if (ComputedBaudRate == 0) { return FALSE; } - DEBUG ((DEBUG_INFO, "ClockRate = %d\n", ClockRate)); + DEBUG ((DEBUG_INFO, "ClockRate = %d\n", ClockRate)); DEBUG ((DEBUG_INFO, "Divisor = %ld\n", ComputedDivisor)); DEBUG ((DEBUG_INFO, "BaudRate/Actual (%ld/%d) = %d%%\n", BaudRate, ComputedBaudRate, Percent)); if (ActualBaudRate != NULL) { *ActualBaudRate = ComputedBaudRate; } + if (Divisor != NULL) { *Divisor = ComputedDivisor; } + return TRUE; } @@ -198,10 +212,10 @@ VerifyUartParameters ( **/ BOOLEAN SerialFifoFull ( - IN SERIAL_DEV_FIFO *Fifo + IN SERIAL_DEV_FIFO *Fifo ) { - return (BOOLEAN) (((Fifo->Tail + 1) % SERIAL_MAX_FIFO_SIZE) == Fifo->Head); + return (BOOLEAN)(((Fifo->Tail + 1) % SERIAL_MAX_FIFO_SIZE) == Fifo->Head); } /** @@ -213,11 +227,11 @@ SerialFifoFull ( **/ BOOLEAN SerialFifoEmpty ( - IN SERIAL_DEV_FIFO *Fifo + IN SERIAL_DEV_FIFO *Fifo ) { - return (BOOLEAN) (Fifo->Head == Fifo->Tail); + return (BOOLEAN)(Fifo->Head == Fifo->Tail); } /** @@ -231,8 +245,8 @@ SerialFifoEmpty ( **/ EFI_STATUS SerialFifoAdd ( - IN OUT SERIAL_DEV_FIFO *Fifo, - IN UINT8 Data + IN OUT SERIAL_DEV_FIFO *Fifo, + IN UINT8 Data ) { // @@ -241,11 +255,12 @@ SerialFifoAdd ( if (SerialFifoFull (Fifo)) { return EFI_OUT_OF_RESOURCES; } + // // FIFO is not full can add data // Fifo->Data[Fifo->Tail] = Data; - Fifo->Tail = (Fifo->Tail + 1) % SERIAL_MAX_FIFO_SIZE; + Fifo->Tail = (Fifo->Tail + 1) % SERIAL_MAX_FIFO_SIZE; return EFI_SUCCESS; } @@ -261,8 +276,8 @@ SerialFifoAdd ( **/ EFI_STATUS SerialFifoRemove ( - IN OUT SERIAL_DEV_FIFO *Fifo, - OUT UINT8 *Data + IN OUT SERIAL_DEV_FIFO *Fifo, + OUT UINT8 *Data ) { // @@ -271,10 +286,11 @@ SerialFifoRemove ( if (SerialFifoEmpty (Fifo)) { return EFI_OUT_OF_RESOURCES; } + // // FIFO is not empty, can remove data // - *Data = Fifo->Data[Fifo->Head]; + *Data = Fifo->Data[Fifo->Head]; Fifo->Head = (Fifo->Head + 1) % SERIAL_MAX_FIFO_SIZE; return EFI_SUCCESS; } @@ -291,16 +307,16 @@ SerialFifoRemove ( **/ EFI_STATUS SerialReceiveTransmit ( - IN SERIAL_DEV *SerialDevice + IN SERIAL_DEV *SerialDevice ) { - SERIAL_PORT_LSR Lsr; - UINT8 Data; - BOOLEAN ReceiveFifoFull; - SERIAL_PORT_MSR Msr; - SERIAL_PORT_MCR Mcr; - UINTN TimeOut; + SERIAL_PORT_LSR Lsr; + UINT8 Data; + BOOLEAN ReceiveFifoFull; + SERIAL_PORT_MSR Msr; + SERIAL_PORT_MCR Mcr; + UINTN TimeOut; Data = 0; @@ -326,13 +342,15 @@ SerialReceiveTransmit ( // if receive buffer is available. // if (SerialDevice->HardwareFlowControl && - !FeaturePcdGet(PcdSerialUseHalfHandshake)&& + !FeaturePcdGet (PcdSerialUseHalfHandshake) && !ReceiveFifoFull - ) { + ) + { Mcr.Data = READ_MCR (SerialDevice); Mcr.Bits.Rts = 1; WRITE_MCR (SerialDevice, Mcr.Data); } + do { Lsr.Data = READ_LSR (SerialDevice); @@ -342,13 +360,13 @@ SerialReceiveTransmit ( if ((Lsr.Bits.Dr == 1) && !ReceiveFifoFull) { ReceiveFifoFull = SerialFifoFull (&SerialDevice->Receive); if (!ReceiveFifoFull) { - if (Lsr.Bits.FIFOe == 1 || Lsr.Bits.Oe == 1 || Lsr.Bits.Pe == 1 || Lsr.Bits.Fe == 1 || Lsr.Bits.Bi == 1) { + if ((Lsr.Bits.FIFOe == 1) || (Lsr.Bits.Oe == 1) || (Lsr.Bits.Pe == 1) || (Lsr.Bits.Fe == 1) || (Lsr.Bits.Bi == 1)) { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_ERROR_CODE, EFI_P_EC_INPUT_ERROR | EFI_PERIPHERAL_SERIAL_PORT, SerialDevice->DevicePath ); - if (Lsr.Bits.FIFOe == 1 || Lsr.Bits.Pe == 1|| Lsr.Bits.Fe == 1 || Lsr.Bits.Bi == 1) { + if ((Lsr.Bits.FIFOe == 1) || (Lsr.Bits.Pe == 1) || (Lsr.Bits.Fe == 1) || (Lsr.Bits.Bi == 1)) { Data = READ_RBR (SerialDevice); continue; } @@ -363,15 +381,15 @@ SerialReceiveTransmit ( // tell the peer to stop sending data. // if (SerialDevice->HardwareFlowControl && - !FeaturePcdGet(PcdSerialUseHalfHandshake) && + !FeaturePcdGet (PcdSerialUseHalfHandshake) && SerialFifoFull (&SerialDevice->Receive) - ) { + ) + { Mcr.Data = READ_MCR (SerialDevice); Mcr.Bits.Rts = 0; WRITE_MCR (SerialDevice, Mcr.Data); } - continue; } else { REPORT_STATUS_CODE_WITH_DEVICE_PATH ( @@ -381,10 +399,11 @@ SerialReceiveTransmit ( ); } } + // // Do the write // - if (Lsr.Bits.Thre == 1 && !SerialFifoEmpty (&SerialDevice->Transmit)) { + if ((Lsr.Bits.Thre == 1) && !SerialFifoEmpty (&SerialDevice->Transmit)) { // // Make sure the transmit data will not be missed // @@ -392,17 +411,18 @@ SerialReceiveTransmit ( // // For half handshake flow control assert RTS before sending. // - if (FeaturePcdGet(PcdSerialUseHalfHandshake)) { + if (FeaturePcdGet (PcdSerialUseHalfHandshake)) { Mcr.Data = READ_MCR (SerialDevice); - Mcr.Bits.Rts= 0; + Mcr.Bits.Rts = 0; WRITE_MCR (SerialDevice, Mcr.Data); } + // // Wait for CTS // - TimeOut = 0; - Msr.Data = READ_MSR (SerialDevice); - while ((Msr.Bits.Dcd == 1) && ((Msr.Bits.Cts == 0) ^ FeaturePcdGet(PcdSerialUseHalfHandshake))) { + TimeOut = 0; + Msr.Data = READ_MSR (SerialDevice); + while ((Msr.Bits.Dcd == 1) && ((Msr.Bits.Cts == 0) ^ FeaturePcdGet (PcdSerialUseHalfHandshake))) { gBS->Stall (TIMEOUT_STALL_INTERVAL); TimeOut++; if (TimeOut > 5) { @@ -412,7 +432,7 @@ SerialReceiveTransmit ( Msr.Data = READ_MSR (SerialDevice); } - if ((Msr.Bits.Dcd == 0) || ((Msr.Bits.Cts == 1) ^ FeaturePcdGet(PcdSerialUseHalfHandshake))) { + if ((Msr.Bits.Dcd == 0) || ((Msr.Bits.Cts == 1) ^ FeaturePcdGet (PcdSerialUseHalfHandshake))) { SerialFifoRemove (&SerialDevice->Transmit, &Data); WRITE_THR (SerialDevice, Data); } @@ -420,8 +440,8 @@ SerialReceiveTransmit ( // // For half handshake flow control, tell DCE we are done. // - if (FeaturePcdGet(PcdSerialUseHalfHandshake)) { - Mcr.Data = READ_MCR (SerialDevice); + if (FeaturePcdGet (PcdSerialUseHalfHandshake)) { + Mcr.Data = READ_MCR (SerialDevice); Mcr.Bits.Rts = 1; WRITE_MCR (SerialDevice, Mcr.Data); } @@ -484,12 +504,13 @@ SerialFlushTransmitFifo ( // in the rest of this function that may send additional characters to this // UART device invalidating the flush operation. // - Elapsed = 0; + Elapsed = 0; Lsr.Data = READ_LSR (SerialDevice); while (Lsr.Bits.Temt == 0 || Lsr.Bits.Thre == 0) { if (Elapsed >= Timeout) { return EFI_TIMEOUT; } + gBS->Stall (TIMEOUT_STALL_INTERVAL); Elapsed += TIMEOUT_STALL_INTERVAL; Lsr.Data = READ_LSR (SerialDevice); @@ -501,6 +522,7 @@ SerialFlushTransmitFifo ( // // Interface Functions // + /** Reset serial device. @@ -516,14 +538,14 @@ SerialReset ( IN EFI_SERIAL_IO_PROTOCOL *This ) { - EFI_STATUS Status; - SERIAL_DEV *SerialDevice; - SERIAL_PORT_LCR Lcr; - SERIAL_PORT_IER Ier; - SERIAL_PORT_MCR Mcr; - SERIAL_PORT_FCR Fcr; - EFI_TPL Tpl; - UINT32 Control; + EFI_STATUS Status; + SERIAL_DEV *SerialDevice; + SERIAL_PORT_LCR Lcr; + SERIAL_PORT_IER Ier; + SERIAL_PORT_MCR Mcr; + SERIAL_PORT_FCR Fcr; + EFI_TPL Tpl; + UINT32 Control; SerialDevice = SERIAL_DEV_FROM_THIS (This); @@ -557,17 +579,17 @@ SerialReset ( // // Turn off all interrupts // - Ier.Data = READ_IER (SerialDevice); - Ier.Bits.Ravie = 0; - Ier.Bits.Theie = 0; - Ier.Bits.Rie = 0; - Ier.Bits.Mie = 0; + Ier.Data = READ_IER (SerialDevice); + Ier.Bits.Ravie = 0; + Ier.Bits.Theie = 0; + Ier.Bits.Rie = 0; + Ier.Bits.Mie = 0; WRITE_IER (SerialDevice, Ier.Data); // // Reset the FIFO // - Fcr.Data = 0; + Fcr.Data = 0; Fcr.Bits.TrFIFOE = 0; WRITE_FCR (SerialDevice, Fcr.Data); @@ -588,12 +610,13 @@ SerialReset ( // // Enable FIFO // - Fcr.Bits.TrFIFOE = 1; + Fcr.Bits.TrFIFOE = 1; if (SerialDevice->ReceiveFifoDepth > 16) { Fcr.Bits.TrFIFO64 = 1; } - Fcr.Bits.ResetRF = 1; - Fcr.Bits.ResetTF = 1; + + Fcr.Bits.ResetRF = 1; + Fcr.Bits.ResetTF = 1; WRITE_FCR (SerialDevice, Fcr.Data); // @@ -604,15 +627,16 @@ SerialReset ( This->Mode->BaudRate, This->Mode->ReceiveFifoDepth, This->Mode->Timeout, - (EFI_PARITY_TYPE) This->Mode->Parity, - (UINT8) This->Mode->DataBits, - (EFI_STOP_BITS_TYPE) This->Mode->StopBits + (EFI_PARITY_TYPE)This->Mode->Parity, + (UINT8)This->Mode->DataBits, + (EFI_STOP_BITS_TYPE)This->Mode->StopBits ); if (EFI_ERROR (Status)) { gBS->RestoreTPL (Tpl); return EFI_DEVICE_ERROR; } + // // Go set the current control bits // @@ -620,9 +644,11 @@ SerialReset ( if (SerialDevice->HardwareFlowControl) { Control |= EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE; } + if (SerialDevice->SoftwareLoopbackEnable) { Control |= EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE; } + Status = This->SetControl ( This, Control @@ -636,7 +662,7 @@ SerialReset ( // // Reset the software FIFO // - SerialDevice->Receive.Head = SerialDevice->Receive.Tail = 0; + SerialDevice->Receive.Head = SerialDevice->Receive.Tail = 0; SerialDevice->Transmit.Head = SerialDevice->Transmit.Tail = 0; gBS->RestoreTPL (Tpl); @@ -675,12 +701,12 @@ SerialSetAttributes ( IN EFI_STOP_BITS_TYPE StopBits ) { - EFI_STATUS Status; - SERIAL_DEV *SerialDevice; - UINT64 Divisor; - SERIAL_PORT_LCR Lcr; - UART_DEVICE_PATH *Uart; - EFI_TPL Tpl; + EFI_STATUS Status; + SERIAL_DEV *SerialDevice; + UINT64 Divisor; + SERIAL_PORT_LCR Lcr; + UART_DEVICE_PATH *Uart; + EFI_TPL Tpl; SerialDevice = SERIAL_DEV_FROM_THIS (This); @@ -700,7 +726,7 @@ SerialSetAttributes ( } if (Parity == DefaultParity) { - Parity = (EFI_PARITY_TYPE) PcdGet8 (PcdUartDefaultParity); + Parity = (EFI_PARITY_TYPE)PcdGet8 (PcdUartDefaultParity); } if (DataBits == 0) { @@ -708,7 +734,7 @@ SerialSetAttributes ( } if (StopBits == DefaultStopBits) { - StopBits = (EFI_STOP_BITS_TYPE) PcdGet8 (PcdUartDefaultStopBits); + StopBits = (EFI_STOP_BITS_TYPE)PcdGet8 (PcdUartDefaultStopBits); } if (!VerifyUartParameters (SerialDevice->ClockRate, BaudRate, DataBits, Parity, StopBits, &Divisor, &BaudRate)) { @@ -744,8 +770,8 @@ SerialSetAttributes ( // // Write the divisor to the serial port // - WRITE_DLL (SerialDevice, (UINT8) Divisor); - WRITE_DLM (SerialDevice, (UINT8) ((UINT16) Divisor >> 8)); + WRITE_DLL (SerialDevice, (UINT8)Divisor); + WRITE_DLM (SerialDevice, (UINT8)((UINT16)Divisor >> 8)); // // Put serial port back in normal mode and set remaining attributes. @@ -753,98 +779,100 @@ SerialSetAttributes ( Lcr.Bits.DLab = 0; switch (Parity) { - case NoParity: - Lcr.Bits.ParEn = 0; - Lcr.Bits.EvenPar = 0; - Lcr.Bits.SticPar = 0; - break; - - case EvenParity: - Lcr.Bits.ParEn = 1; - Lcr.Bits.EvenPar = 1; - Lcr.Bits.SticPar = 0; - break; - - case OddParity: - Lcr.Bits.ParEn = 1; - Lcr.Bits.EvenPar = 0; - Lcr.Bits.SticPar = 0; - break; - - case SpaceParity: - Lcr.Bits.ParEn = 1; - Lcr.Bits.EvenPar = 1; - Lcr.Bits.SticPar = 1; - break; - - case MarkParity: - Lcr.Bits.ParEn = 1; - Lcr.Bits.EvenPar = 0; - Lcr.Bits.SticPar = 1; - break; - - default: - break; + case NoParity: + Lcr.Bits.ParEn = 0; + Lcr.Bits.EvenPar = 0; + Lcr.Bits.SticPar = 0; + break; + + case EvenParity: + Lcr.Bits.ParEn = 1; + Lcr.Bits.EvenPar = 1; + Lcr.Bits.SticPar = 0; + break; + + case OddParity: + Lcr.Bits.ParEn = 1; + Lcr.Bits.EvenPar = 0; + Lcr.Bits.SticPar = 0; + break; + + case SpaceParity: + Lcr.Bits.ParEn = 1; + Lcr.Bits.EvenPar = 1; + Lcr.Bits.SticPar = 1; + break; + + case MarkParity: + Lcr.Bits.ParEn = 1; + Lcr.Bits.EvenPar = 0; + Lcr.Bits.SticPar = 1; + break; + + default: + break; } switch (StopBits) { - case OneStopBit: - Lcr.Bits.StopB = 0; - break; + case OneStopBit: + Lcr.Bits.StopB = 0; + break; - case OneFiveStopBits: - case TwoStopBits: - Lcr.Bits.StopB = 1; - break; + case OneFiveStopBits: + case TwoStopBits: + Lcr.Bits.StopB = 1; + break; - default: - break; + default: + break; } + // // DataBits // - Lcr.Bits.SerialDB = (UINT8) ((DataBits - 5) & 0x03); + Lcr.Bits.SerialDB = (UINT8)((DataBits - 5) & 0x03); WRITE_LCR (SerialDevice, Lcr.Data); // // Set the Serial I/O mode // - This->Mode->BaudRate = BaudRate; - This->Mode->ReceiveFifoDepth = ReceiveFifoDepth; - This->Mode->Timeout = Timeout; - This->Mode->Parity = Parity; - This->Mode->DataBits = DataBits; - This->Mode->StopBits = StopBits; + This->Mode->BaudRate = BaudRate; + This->Mode->ReceiveFifoDepth = ReceiveFifoDepth; + This->Mode->Timeout = Timeout; + This->Mode->Parity = Parity; + This->Mode->DataBits = DataBits; + This->Mode->StopBits = StopBits; // // See if Device Path Node has actually changed // - if (SerialDevice->UartDevicePath.BaudRate == BaudRate && - SerialDevice->UartDevicePath.DataBits == DataBits && - SerialDevice->UartDevicePath.Parity == Parity && - SerialDevice->UartDevicePath.StopBits == StopBits - ) { + if ((SerialDevice->UartDevicePath.BaudRate == BaudRate) && + (SerialDevice->UartDevicePath.DataBits == DataBits) && + (SerialDevice->UartDevicePath.Parity == Parity) && + (SerialDevice->UartDevicePath.StopBits == StopBits) + ) + { gBS->RestoreTPL (Tpl); return EFI_SUCCESS; } + // // Update the device path // SerialDevice->UartDevicePath.BaudRate = BaudRate; SerialDevice->UartDevicePath.DataBits = DataBits; - SerialDevice->UartDevicePath.Parity = (UINT8) Parity; - SerialDevice->UartDevicePath.StopBits = (UINT8) StopBits; + SerialDevice->UartDevicePath.Parity = (UINT8)Parity; + SerialDevice->UartDevicePath.StopBits = (UINT8)StopBits; Status = EFI_SUCCESS; if (SerialDevice->Handle != NULL) { - // // Skip the optional Controller device path node // Uart = SkipControllerDevicePathNode ( - (EFI_DEVICE_PATH_PROTOCOL *) ( - (UINT8 *) SerialDevice->DevicePath + GetDevicePathSize (SerialDevice->ParentDevicePath) - END_DEVICE_PATH_LENGTH - ), + (EFI_DEVICE_PATH_PROTOCOL *)( + (UINT8 *)SerialDevice->DevicePath + GetDevicePathSize (SerialDevice->ParentDevicePath) - END_DEVICE_PATH_LENGTH + ), NULL, NULL ); @@ -879,11 +907,11 @@ SerialSetControl ( IN UINT32 Control ) { - SERIAL_DEV *SerialDevice; - SERIAL_PORT_MCR Mcr; - EFI_TPL Tpl; - UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; - EFI_STATUS Status; + SERIAL_DEV *SerialDevice; + SERIAL_PORT_MCR Mcr; + EFI_TPL Tpl; + UART_FLOW_CONTROL_DEVICE_PATH *FlowControl; + EFI_STATUS Status; // // The control bits that can be set are : @@ -900,7 +928,8 @@ SerialSetControl ( // if ((Control & (~(EFI_SERIAL_REQUEST_TO_SEND | EFI_SERIAL_DATA_TERMINAL_READY | EFI_SERIAL_HARDWARE_LOOPBACK_ENABLE | EFI_SERIAL_SOFTWARE_LOOPBACK_ENABLE | - EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0) { + EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0) + { return EFI_UNSUPPORTED; } @@ -915,12 +944,12 @@ SerialSetControl ( // SerialFlushTransmitFifo (SerialDevice); - Mcr.Data = READ_MCR (SerialDevice); - Mcr.Bits.DtrC = 0; - Mcr.Bits.Rts = 0; - Mcr.Bits.Lme = 0; + Mcr.Data = READ_MCR (SerialDevice); + Mcr.Bits.DtrC = 0; + Mcr.Bits.Rts = 0; + Mcr.Bits.Lme = 0; SerialDevice->SoftwareLoopbackEnable = FALSE; - SerialDevice->HardwareFlowControl = FALSE; + SerialDevice->HardwareFlowControl = FALSE; if ((Control & EFI_SERIAL_DATA_TERMINAL_READY) == EFI_SERIAL_DATA_TERMINAL_READY) { Mcr.Bits.DtrC = 1; @@ -946,14 +975,15 @@ SerialSetControl ( Status = EFI_SUCCESS; if (SerialDevice->Handle != NULL) { - FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *) ( - (UINTN) SerialDevice->DevicePath - + GetDevicePathSize (SerialDevice->ParentDevicePath) - - END_DEVICE_PATH_LENGTH - + sizeof (UART_DEVICE_PATH) - ); + FlowControl = (UART_FLOW_CONTROL_DEVICE_PATH *)( + (UINTN)SerialDevice->DevicePath + + GetDevicePathSize (SerialDevice->ParentDevicePath) + - END_DEVICE_PATH_LENGTH + + sizeof (UART_DEVICE_PATH) + ); if (IsUartFlowControlDevicePathNode (FlowControl) && - ((BOOLEAN) (ReadUnaligned32 (&FlowControl->FlowControlMap) == UART_FLOW_CONTROL_HARDWARE) != SerialDevice->HardwareFlowControl)) { + ((BOOLEAN)(ReadUnaligned32 (&FlowControl->FlowControlMap) == UART_FLOW_CONTROL_HARDWARE) != SerialDevice->HardwareFlowControl)) + { // // Flow Control setting is changed, need to reinstall device path protocol // @@ -988,16 +1018,16 @@ SerialGetControl ( OUT UINT32 *Control ) { - SERIAL_DEV *SerialDevice; - SERIAL_PORT_MSR Msr; - SERIAL_PORT_MCR Mcr; - EFI_TPL Tpl; + SERIAL_DEV *SerialDevice; + SERIAL_PORT_MSR Msr; + SERIAL_PORT_MCR Mcr; + EFI_TPL Tpl; - Tpl = gBS->RaiseTPL (TPL_NOTIFY); + Tpl = gBS->RaiseTPL (TPL_NOTIFY); - SerialDevice = SERIAL_DEV_FROM_THIS (This); + SerialDevice = SERIAL_DEV_FROM_THIS (This); - *Control = 0; + *Control = 0; // // Read the Modem Status Register @@ -1019,6 +1049,7 @@ SerialGetControl ( if (Msr.Bits.Dcd == 1) { *Control |= EFI_SERIAL_CARRIER_DETECT; } + // // Read the Modem Control Register // @@ -1039,6 +1070,7 @@ SerialGetControl ( if (SerialDevice->HardwareFlowControl) { *Control |= EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE; } + // // Update FIFO status // @@ -1097,9 +1129,9 @@ SerialWrite ( UINTN Timeout; UINTN BitsPerCharacter; - SerialDevice = SERIAL_DEV_FROM_THIS (This); - Elapsed = 0; - ActualWrite = 0; + SerialDevice = SERIAL_DEV_FROM_THIS (This); + Elapsed = 0; + ActualWrite = 0; if (*BufferSize == 0) { return EFI_SUCCESS; @@ -1115,9 +1147,9 @@ SerialWrite ( return EFI_DEVICE_ERROR; } - Tpl = gBS->RaiseTPL (TPL_NOTIFY); + Tpl = gBS->RaiseTPL (TPL_NOTIFY); - CharBuffer = (UINT8 *) Buffer; + CharBuffer = (UINT8 *)Buffer; // // Compute the number of bits in a single character. This is a start bit, @@ -1143,10 +1175,10 @@ SerialWrite ( Timeout = MAX ( This->Mode->Timeout, (UINTN)DivU64x64Remainder ( - BitsPerCharacter * (SerialDevice->TransmitFifoDepth + 1) * 1000000, - This->Mode->BaudRate, - NULL - ) + BitsPerCharacter * (SerialDevice->TransmitFifoDepth + 1) * 1000000, + This->Mode->BaudRate, + NULL + ) ); for (Index = 0; Index < *BufferSize; Index++) { @@ -1208,8 +1240,8 @@ SerialRead ( EFI_STATUS Status; EFI_TPL Tpl; - SerialDevice = SERIAL_DEV_FROM_THIS (This); - Elapsed = 0; + SerialDevice = SERIAL_DEV_FROM_THIS (This); + Elapsed = 0; if (*BufferSize == 0) { return EFI_SUCCESS; @@ -1219,9 +1251,9 @@ SerialRead ( return EFI_DEVICE_ERROR; } - Tpl = gBS->RaiseTPL (TPL_NOTIFY); + Tpl = gBS->RaiseTPL (TPL_NOTIFY); - Status = SerialReceiveTransmit (SerialDevice); + Status = SerialReceiveTransmit (SerialDevice); if (EFI_ERROR (Status)) { *BufferSize = 0; @@ -1237,7 +1269,7 @@ SerialRead ( return EFI_DEVICE_ERROR; } - CharBuffer = (UINT8 *) Buffer; + CharBuffer = (UINT8 *)Buffer; for (Index = 0; Index < *BufferSize; Index++) { while (SerialFifoRemove (&SerialDevice->Receive, &(CharBuffer[Index])) != EFI_SUCCESS) { // @@ -1261,6 +1293,7 @@ SerialRead ( return EFI_DEVICE_ERROR; } } + // // Successful read so reset timeout // @@ -1283,12 +1316,12 @@ SerialRead ( **/ BOOLEAN SerialPresent ( - IN SERIAL_DEV *SerialDevice + IN SERIAL_DEV *SerialDevice ) { - UINT8 Temp; - BOOLEAN Status; + UINT8 Temp; + BOOLEAN Status; Status = TRUE; @@ -1307,6 +1340,7 @@ SerialPresent ( if (READ_SCR (SerialDevice) != 0x55) { Status = FALSE; } + // // Restore SCR // @@ -1325,23 +1359,36 @@ SerialPresent ( **/ UINT8 SerialReadRegister ( - IN SERIAL_DEV *SerialDev, - IN UINT32 Offset + IN SERIAL_DEV *SerialDev, + IN UINT32 Offset ) { - UINT8 Data; - EFI_STATUS Status; + UINT8 Data; + EFI_STATUS Status; if (SerialDev->PciDeviceInfo == NULL) { - return IoRead8 ((UINTN) SerialDev->BaseAddress + Offset * SerialDev->RegisterStride); + return IoRead8 ((UINTN)SerialDev->BaseAddress + Offset * SerialDev->RegisterStride); } else { if (SerialDev->MmioAccess) { - Status = SerialDev->PciDeviceInfo->PciIo->Mem.Read (SerialDev->PciDeviceInfo->PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, 1, &Data); + Status = SerialDev->PciDeviceInfo->PciIo->Mem.Read ( + SerialDev->PciDeviceInfo->PciIo, + EfiPciIoWidthUint8, + EFI_PCI_IO_PASS_THROUGH_BAR, + SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, + 1, + &Data + ); } else { - Status = SerialDev->PciDeviceInfo->PciIo->Io.Read (SerialDev->PciDeviceInfo->PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, 1, &Data); + Status = SerialDev->PciDeviceInfo->PciIo->Io.Read ( + SerialDev->PciDeviceInfo->PciIo, + EfiPciIoWidthUint8, + EFI_PCI_IO_PASS_THROUGH_BAR, + SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, + 1, + &Data + ); } + ASSERT_EFI_ERROR (Status); return Data; } @@ -1356,23 +1403,36 @@ SerialReadRegister ( **/ VOID SerialWriteRegister ( - IN SERIAL_DEV *SerialDev, - IN UINT32 Offset, - IN UINT8 Data + IN SERIAL_DEV *SerialDev, + IN UINT32 Offset, + IN UINT8 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; if (SerialDev->PciDeviceInfo == NULL) { - IoWrite8 ((UINTN) SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, Data); + IoWrite8 ((UINTN)SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, Data); } else { if (SerialDev->MmioAccess) { - Status = SerialDev->PciDeviceInfo->PciIo->Mem.Write (SerialDev->PciDeviceInfo->PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, 1, &Data); + Status = SerialDev->PciDeviceInfo->PciIo->Mem.Write ( + SerialDev->PciDeviceInfo->PciIo, + EfiPciIoWidthUint8, + EFI_PCI_IO_PASS_THROUGH_BAR, + SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, + 1, + &Data + ); } else { - Status = SerialDev->PciDeviceInfo->PciIo->Io.Write (SerialDev->PciDeviceInfo->PciIo, EfiPciIoWidthUint8, EFI_PCI_IO_PASS_THROUGH_BAR, - SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, 1, &Data); + Status = SerialDev->PciDeviceInfo->PciIo->Io.Write ( + SerialDev->PciDeviceInfo->PciIo, + EfiPciIoWidthUint8, + EFI_PCI_IO_PASS_THROUGH_BAR, + SerialDev->BaseAddress + Offset * SerialDev->RegisterStride, + 1, + &Data + ); } + ASSERT_EFI_ERROR (Status); } } diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/SataControllerDxe/ComponentName.c index 5086d77474..9cc416fc1f 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/ComponentName.c @@ -20,16 +20,16 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gSataControllerCompon // /// EFI Component Name 2 Protocol /// -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSataControllerComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) SataControllerComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) SataControllerComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSataControllerComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)SataControllerComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)SataControllerComponentNameGetControllerName, "en" }; // /// Driver Name Strings /// -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerDriverNameTable[] = { { "eng;en", (CHAR16 *)L"Sata Controller Init Driver" @@ -43,7 +43,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerDriverName /// /// Controller Name Strings /// -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerControllerNameTable[] = { { "eng;en", (CHAR16 *)L"Sata Controller" @@ -78,9 +78,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSataControllerController EFI_STATUS EFIAPI SataControllerComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -135,14 +135,14 @@ SataControllerComponentNameGetDriverName ( EFI_STATUS EFIAPI SataControllerComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Make sure this driver is currently managing ControllHandle @@ -161,11 +161,10 @@ SataControllerComponentNameGetControllerName ( } return LookupUnicodeString2 ( - Language, - This->SupportedLanguages, - mSataControllerControllerNameTable, - ControllerName, - (BOOLEAN)(This == &gSataControllerComponentName) - ); + Language, + This->SupportedLanguages, + mSataControllerControllerNameTable, + ControllerName, + (BOOLEAN)(This == &gSataControllerComponentName) + ); } - diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c index 1133e1c935..f661efaec7 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.c @@ -12,7 +12,7 @@ /// /// EFI_DRIVER_BINDING_PROTOCOL instance /// -EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding = { SataControllerSupported, SataControllerStart, SataControllerStop, @@ -33,11 +33,11 @@ EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding = { UINT32 EFIAPI AhciReadReg ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; ASSERT (PciIo != NULL); @@ -47,7 +47,7 @@ AhciReadReg ( PciIo, EfiPciIoWidthUint32, AHCI_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); @@ -73,21 +73,20 @@ CalculateBestPioMode ( OUT UINT16 *SelectedMode ) { - UINT16 PioMode; - UINT16 AdvancedPioMode; - UINT16 Temp; - UINT16 Index; - UINT16 MinimumPioCycleTime; + UINT16 PioMode; + UINT16 AdvancedPioMode; + UINT16 Temp; + UINT16 Index; + UINT16 MinimumPioCycleTime; Temp = 0xff; - PioMode = (UINT8) (((ATA5_IDENTIFY_DATA *) (&(IdentifyData->AtaData)))->pio_cycle_timing >> 8); + PioMode = (UINT8)(((ATA5_IDENTIFY_DATA *)(&(IdentifyData->AtaData)))->pio_cycle_timing >> 8); // // See whether Identify Data word 64 - 70 are valid // if ((IdentifyData->AtaData.field_validity & 0x02) == 0x02) { - AdvancedPioMode = IdentifyData->AtaData.advanced_pio_modes; DEBUG ((DEBUG_INFO, "CalculateBestPioMode: AdvancedPioMode = %x\n", AdvancedPioMode)); @@ -105,7 +104,7 @@ CalculateBestPioMode ( // the best PIO Mode is the value in pio_cycle_timing. // if (Temp != 0xff) { - AdvancedPioMode = (UINT16) (Temp + 3); + AdvancedPioMode = (UINT16)(Temp + 3); } else { AdvancedPioMode = PioMode; } @@ -113,16 +112,16 @@ CalculateBestPioMode ( // // Limit the PIO mode to at most PIO4. // - PioMode = (UINT16) MIN (AdvancedPioMode, 4); + PioMode = (UINT16)MIN (AdvancedPioMode, 4); MinimumPioCycleTime = IdentifyData->AtaData.min_pio_cycle_time_with_flow_control; if (MinimumPioCycleTime <= 120) { - PioMode = (UINT16) MIN (4, PioMode); + PioMode = (UINT16)MIN (4, PioMode); } else if (MinimumPioCycleTime <= 180) { - PioMode = (UINT16) MIN (3, PioMode); + PioMode = (UINT16)MIN (3, PioMode); } else if (MinimumPioCycleTime <= 240) { - PioMode = (UINT16) MIN (2, PioMode); + PioMode = (UINT16)MIN (2, PioMode); } else { PioMode = 0; } @@ -136,7 +135,7 @@ CalculateBestPioMode ( } if (PioMode >= *DisPioMode) { - PioMode = (UINT16) (*DisPioMode - 1); + PioMode = (UINT16)(*DisPioMode - 1); } } @@ -145,7 +144,6 @@ CalculateBestPioMode ( } else { *SelectedMode = PioMode; // ATA_PIO_MODE_2 to ATA_PIO_MODE_4; } - } else { // // Identify Data word 64 - 70 are not valid @@ -166,7 +164,6 @@ CalculateBestPioMode ( } else { *SelectedMode = 2; // ATA_PIO_MODE_2; } - } return EFI_SUCCESS; @@ -190,8 +187,8 @@ CalculateBestUdmaMode ( OUT UINT16 *SelectedMode ) { - UINT16 TempMode; - UINT16 DeviceUDmaMode; + UINT16 TempMode; + UINT16 DeviceUDmaMode; DeviceUDmaMode = 0; @@ -205,7 +202,7 @@ CalculateBestUdmaMode ( DeviceUDmaMode = IdentifyData->AtaData.ultra_dma_mode; DEBUG ((DEBUG_INFO, "CalculateBestUdmaMode: DeviceUDmaMode = %x\n", DeviceUDmaMode)); DeviceUDmaMode &= 0x3f; - TempMode = 0; // initialize it to UDMA-0 + TempMode = 0; // initialize it to UDMA-0 while ((DeviceUDmaMode >>= 1) != 0) { TempMode++; @@ -221,7 +218,7 @@ CalculateBestUdmaMode ( } if (TempMode >= *DisUDmaMode) { - TempMode = (UINT16) (*DisUDmaMode - 1); + TempMode = (UINT16)(*DisUDmaMode - 1); } } @@ -246,11 +243,11 @@ CalculateBestUdmaMode ( EFI_STATUS EFIAPI InitializeSataControllerDriver ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -285,14 +282,14 @@ InitializeSataControllerDriver ( EFI_STATUS EFIAPI SataControllerSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - PCI_TYPE00 PciData; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + PCI_TYPE00 PciData; // // Attempt to open PCI I/O Protocol @@ -300,7 +297,7 @@ SataControllerSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -348,9 +345,9 @@ SataControllerSupported ( EFI_STATUS EFIAPI SataControllerStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; @@ -372,7 +369,7 @@ SataControllerStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -394,8 +391,8 @@ SataControllerStart ( // // Initialize Sata Private Data // - Private->Signature = SATA_CONTROLLER_SIGNATURE; - Private->PciIo = PciIo; + Private->Signature = SATA_CONTROLLER_SIGNATURE; + Private->PciIo = PciIo; Private->IdeInit.GetChannelInfo = IdeInitGetChannelInfo; Private->IdeInit.NotifyPhase = IdeInitNotifyPhase; Private->IdeInit.SubmitData = IdeInitSubmitData; @@ -415,7 +412,7 @@ SataControllerStart ( &Private->OriginalPciAttributes ); if (EFI_ERROR (Status)) { - goto Done; + goto Done; } DEBUG (( @@ -437,12 +434,12 @@ SataControllerStart ( DEBUG ((DEBUG_INFO, "Supported PCI Attributes = 0x%llx\n", Supports)); Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE; - Status = PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationEnable, - Supports, - NULL - ); + Status = PciIo->Attributes ( + PciIo, + EfiPciIoAttributeOperationEnable, + Supports, + NULL + ); if (EFI_ERROR (Status)) { goto Done; } @@ -475,13 +472,16 @@ SataControllerStart ( Status = EFI_UNSUPPORTED; goto Done; } + MaxPortNumber = 31; while (MaxPortNumber > 0) { if ((Data32 & ((UINT32)1 << MaxPortNumber)) != 0) { break; } + MaxPortNumber--; } + // // Make the ChannelCount equal to the max port number (0 based) plus 1. // @@ -492,13 +492,13 @@ SataControllerStart ( // Data32 = AhciReadReg (PciIo, R_AHCI_CAP); DEBUG ((DEBUG_INFO, "HBA Capabilities(CAP) = 0x%x\n", Data32)); - Private->DeviceCount = AHCI_MAX_DEVICES; + Private->DeviceCount = AHCI_MAX_DEVICES; if ((Data32 & B_AHCI_CAP_SPM) == B_AHCI_CAP_SPM) { Private->DeviceCount = AHCI_MULTI_MAX_DEVICES; } } - TotalCount = (UINTN) (Private->IdeInit.ChannelCount) * (UINTN) (Private->DeviceCount); + TotalCount = (UINTN)(Private->IdeInit.ChannelCount) * (UINTN)(Private->DeviceCount); Private->DisqualifiedModes = AllocateZeroPool ((sizeof (EFI_ATA_COLLECTIVE_MODE)) * TotalCount); if (Private->DisqualifiedModes == NULL) { Status = EFI_OUT_OF_RESOURCES; @@ -529,23 +529,25 @@ SataControllerStart ( Done: if (EFI_ERROR (Status)) { - gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); if (Private != NULL) { if (Private->DisqualifiedModes != NULL) { FreePool (Private->DisqualifiedModes); } + if (Private->IdentifyData != NULL) { FreePool (Private->IdentifyData); } + if (Private->IdentifyValid != NULL) { FreePool (Private->IdentifyValid); } + if (Private->PciAttributesChanged) { // // Restore original PCI attributes @@ -557,6 +559,7 @@ Done: NULL ); } + FreePool (Private); } } @@ -581,10 +584,10 @@ Done: EFI_STATUS EFIAPI SataControllerStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -597,7 +600,7 @@ SataControllerStop ( Status = gBS->OpenProtocol ( Controller, &gEfiIdeControllerInitProtocolGuid, - (VOID **) &IdeInit, + (VOID **)&IdeInit, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -626,12 +629,15 @@ SataControllerStop ( if (Private->DisqualifiedModes != NULL) { FreePool (Private->DisqualifiedModes); } + if (Private->IdentifyData != NULL) { FreePool (Private->IdentifyData); } + if (Private->IdentifyValid != NULL) { FreePool (Private->IdentifyValid); } + if (Private->PciAttributesChanged) { // // Restore original PCI attributes @@ -643,6 +649,7 @@ SataControllerStop ( NULL ); } + FreePool (Private); } @@ -691,6 +698,7 @@ FlatDeviceIndex ( // // Interface functions of IDE_CONTROLLER_INIT protocol // + /** Returns the information about the specified IDE channel. @@ -730,18 +738,19 @@ FlatDeviceIndex ( EFI_STATUS EFIAPI IdeInitGetChannelInfo ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - OUT BOOLEAN *Enabled, - OUT UINT8 *MaxDevices + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + OUT BOOLEAN *Enabled, + OUT UINT8 *MaxDevices ) { EFI_SATA_CONTROLLER_PRIVATE_DATA *Private; + Private = SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS (This); ASSERT (Private != NULL); if (Channel < This->ChannelCount) { - *Enabled = TRUE; + *Enabled = TRUE; *MaxDevices = Private->DeviceCount; return EFI_SUCCESS; } @@ -778,9 +787,9 @@ IdeInitGetChannelInfo ( EFI_STATUS EFIAPI IdeInitNotifyPhase ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN EFI_IDE_CONTROLLER_ENUM_PHASE Phase, - IN UINT8 Channel + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN EFI_IDE_CONTROLLER_ENUM_PHASE Phase, + IN UINT8 Channel ) { return EFI_SUCCESS; @@ -828,10 +837,10 @@ IdeInitNotifyPhase ( EFI_STATUS EFIAPI IdeInitSubmitData ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_IDENTIFY_DATA *IdentifyData + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_IDENTIFY_DATA *IdentifyData ) { EFI_SATA_CONTROLLER_PRIVATE_DATA *Private; @@ -907,10 +916,10 @@ IdeInitSubmitData ( EFI_STATUS EFIAPI IdeInitDisqualifyMode ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_ATA_COLLECTIVE_MODE *BadModes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_ATA_COLLECTIVE_MODE *BadModes ) { EFI_SATA_CONTROLLER_PRIVATE_DATA *Private; @@ -995,10 +1004,10 @@ IdeInitDisqualifyMode ( EFI_STATUS EFIAPI IdeInitCalculateMode ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - OUT EFI_ATA_COLLECTIVE_MODE **SupportedModes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + OUT EFI_ATA_COLLECTIVE_MODE **SupportedModes ) { EFI_SATA_CONTROLLER_PRIVATE_DATA *Private; @@ -1024,8 +1033,8 @@ IdeInitCalculateMode ( DeviceIndex = FlatDeviceIndex (Private, Channel, Device); - IdentifyData = &(Private->IdentifyData[DeviceIndex]); - IdentifyValid = Private->IdentifyValid[DeviceIndex]; + IdentifyData = &(Private->IdentifyData[DeviceIndex]); + IdentifyValid = Private->IdentifyValid[DeviceIndex]; DisqualifiedModes = &(Private->DisqualifiedModes[DeviceIndex]); // @@ -1037,32 +1046,32 @@ IdeInitCalculateMode ( } Status = CalculateBestPioMode ( - IdentifyData, - (DisqualifiedModes->PioMode.Valid ? ((UINT16 *) &(DisqualifiedModes->PioMode.Mode)) : NULL), - &SelectedMode - ); + IdentifyData, + (DisqualifiedModes->PioMode.Valid ? ((UINT16 *)&(DisqualifiedModes->PioMode.Mode)) : NULL), + &SelectedMode + ); if (!EFI_ERROR (Status)) { (*SupportedModes)->PioMode.Valid = TRUE; - (*SupportedModes)->PioMode.Mode = SelectedMode; - + (*SupportedModes)->PioMode.Mode = SelectedMode; } else { (*SupportedModes)->PioMode.Valid = FALSE; } + DEBUG ((DEBUG_INFO, "IdeInitCalculateMode: PioMode = %x\n", (*SupportedModes)->PioMode.Mode)); Status = CalculateBestUdmaMode ( - IdentifyData, - (DisqualifiedModes->UdmaMode.Valid ? ((UINT16 *) &(DisqualifiedModes->UdmaMode.Mode)) : NULL), - &SelectedMode - ); + IdentifyData, + (DisqualifiedModes->UdmaMode.Valid ? ((UINT16 *)&(DisqualifiedModes->UdmaMode.Mode)) : NULL), + &SelectedMode + ); if (!EFI_ERROR (Status)) { (*SupportedModes)->UdmaMode.Valid = TRUE; (*SupportedModes)->UdmaMode.Mode = SelectedMode; - } else { (*SupportedModes)->UdmaMode.Valid = FALSE; } + DEBUG ((DEBUG_INFO, "IdeInitCalculateMode: UdmaMode = %x\n", (*SupportedModes)->UdmaMode.Mode)); // @@ -1097,10 +1106,10 @@ IdeInitCalculateMode ( EFI_STATUS EFIAPI IdeInitSetTiming ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_ATA_COLLECTIVE_MODE *Modes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_ATA_COLLECTIVE_MODE *Modes ) { return EFI_SUCCESS; diff --git a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h index 7af3ad855f..4d545fb1f9 100644 --- a/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h +++ b/MdeModulePkg/Bus/Pci/SataControllerDxe/SataController.h @@ -30,94 +30,95 @@ // // Global Variables definitions // -extern EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gSataControllerComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gSataControllerComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gSataControllerDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gSataControllerComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gSataControllerComponentName2; -#define AHCI_BAR_INDEX 0x05 -#define R_AHCI_CAP 0x0 -#define B_AHCI_CAP_NPS (BIT4 | BIT3 | BIT2 | BIT1 | BIT0) // Number of Ports -#define B_AHCI_CAP_SPM BIT17 // Supports Port Multiplier -#define R_AHCI_PI 0xC +#define AHCI_BAR_INDEX 0x05 +#define R_AHCI_CAP 0x0 +#define B_AHCI_CAP_NPS (BIT4 | BIT3 | BIT2 | BIT1 | BIT0) // Number of Ports +#define B_AHCI_CAP_SPM BIT17 // Supports Port Multiplier +#define R_AHCI_PI 0xC /// /// AHCI each channel can have up to 1 device /// -#define AHCI_MAX_DEVICES 0x01 +#define AHCI_MAX_DEVICES 0x01 /// /// AHCI each channel can have 15 devices in the presence of a multiplier /// -#define AHCI_MULTI_MAX_DEVICES 0x0F +#define AHCI_MULTI_MAX_DEVICES 0x0F /// /// IDE supports 2 channel max /// -#define IDE_MAX_CHANNEL 0x02 +#define IDE_MAX_CHANNEL 0x02 /// /// IDE supports 2 devices max /// -#define IDE_MAX_DEVICES 0x02 +#define IDE_MAX_DEVICES 0x02 -#define SATA_ENUMER_ALL FALSE +#define SATA_ENUMER_ALL FALSE // // Sata Controller driver private data structure // -#define SATA_CONTROLLER_SIGNATURE SIGNATURE_32('S','A','T','A') +#define SATA_CONTROLLER_SIGNATURE SIGNATURE_32('S','A','T','A') typedef struct _EFI_SATA_CONTROLLER_PRIVATE_DATA { // // Standard signature used to identify Sata Controller private data // - UINT32 Signature; + UINT32 Signature; // // Protocol instance of IDE_CONTROLLER_INIT produced by this driver // - EFI_IDE_CONTROLLER_INIT_PROTOCOL IdeInit; + EFI_IDE_CONTROLLER_INIT_PROTOCOL IdeInit; // // Copy of protocol pointers used by this driver // - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; // // The number of devices that are supported by this channel // - UINT8 DeviceCount; + UINT8 DeviceCount; // // The highest disqulified mode for each attached device, // From ATA/ATAPI spec, if a mode is not supported, // the modes higher than it is also not supported // - EFI_ATA_COLLECTIVE_MODE *DisqualifiedModes; + EFI_ATA_COLLECTIVE_MODE *DisqualifiedModes; // // A copy of EFI_IDENTIFY_DATA data for each attached SATA device and its flag // - EFI_IDENTIFY_DATA *IdentifyData; - BOOLEAN *IdentifyValid; + EFI_IDENTIFY_DATA *IdentifyData; + BOOLEAN *IdentifyValid; // // Track the state so that the PCI attributes that were modified // can be restored to the original value later. // - BOOLEAN PciAttributesChanged; + BOOLEAN PciAttributesChanged; // // Copy of the original PCI Attributes // - UINT64 OriginalPciAttributes; + UINT64 OriginalPciAttributes; } EFI_SATA_CONTROLLER_PRIVATE_DATA; -#define SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS(a) CR(a, EFI_SATA_CONTROLLER_PRIVATE_DATA, IdeInit, SATA_CONTROLLER_SIGNATURE) +#define SATA_CONTROLLER_PRIVATE_DATA_FROM_THIS(a) CR(a, EFI_SATA_CONTROLLER_PRIVATE_DATA, IdeInit, SATA_CONTROLLER_SIGNATURE) // // Driver binding functions declaration // + /** Supported function of Driver Binding protocol for this driver. Test to see if this driver supports ControllerHandle. @@ -135,9 +136,9 @@ typedef struct _EFI_SATA_CONTROLLER_PRIVATE_DATA { EFI_STATUS EFIAPI SataControllerSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -157,9 +158,9 @@ SataControllerSupported ( EFI_STATUS EFIAPI SataControllerStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -177,15 +178,16 @@ SataControllerStart ( EFI_STATUS EFIAPI SataControllerStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // IDE controller init functions declaration // + /** Returns the information about the specified IDE channel. @@ -226,10 +228,10 @@ SataControllerStop ( EFI_STATUS EFIAPI IdeInitGetChannelInfo ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - OUT BOOLEAN *Enabled, - OUT UINT8 *MaxDevices + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + OUT BOOLEAN *Enabled, + OUT UINT8 *MaxDevices ); /** @@ -260,9 +262,9 @@ IdeInitGetChannelInfo ( EFI_STATUS EFIAPI IdeInitNotifyPhase ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN EFI_IDE_CONTROLLER_ENUM_PHASE Phase, - IN UINT8 Channel + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN EFI_IDE_CONTROLLER_ENUM_PHASE Phase, + IN UINT8 Channel ); /** @@ -307,10 +309,10 @@ IdeInitNotifyPhase ( EFI_STATUS EFIAPI IdeInitSubmitData ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_IDENTIFY_DATA *IdentifyData + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_IDENTIFY_DATA *IdentifyData ); /** @@ -356,10 +358,10 @@ IdeInitSubmitData ( EFI_STATUS EFIAPI IdeInitDisqualifyMode ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_ATA_COLLECTIVE_MODE *BadModes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_ATA_COLLECTIVE_MODE *BadModes ); /** @@ -419,10 +421,10 @@ IdeInitDisqualifyMode ( EFI_STATUS EFIAPI IdeInitCalculateMode ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - OUT EFI_ATA_COLLECTIVE_MODE **SupportedModes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + OUT EFI_ATA_COLLECTIVE_MODE **SupportedModes ); /** @@ -451,15 +453,16 @@ IdeInitCalculateMode ( EFI_STATUS EFIAPI IdeInitSetTiming ( - IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, - IN UINT8 Channel, - IN UINT8 Device, - IN EFI_ATA_COLLECTIVE_MODE *Modes + IN EFI_IDE_CONTROLLER_INIT_PROTOCOL *This, + IN UINT8 Channel, + IN UINT8 Device, + IN EFI_ATA_COLLECTIVE_MODE *Modes ); // // Forward reference declaration // + /** Retrieves a Unicode string that is the user readable name of the UEFI Driver. @@ -484,9 +487,9 @@ IdeInitSetTiming ( EFI_STATUS EFIAPI SataControllerComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ); /** @@ -532,12 +535,11 @@ SataControllerComponentNameGetDriverName ( EFI_STATUS EFIAPI SataControllerComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); #endif - diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/ComponentName.c index c915d37bf3..2301d4ab4d 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/ComponentName.c @@ -11,7 +11,7 @@ // // EFI Component Name Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gSdMmcPciHcComponentName = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gSdMmcPciHcComponentName = { SdMmcPciHcComponentNameGetDriverName, SdMmcPciHcComponentNameGetControllerName, "eng" @@ -20,20 +20,20 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gSdMmcPciHcComponentNa // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSdMmcPciHcComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) SdMmcPciHcComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) SdMmcPciHcComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSdMmcPciHcComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)SdMmcPciHcComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)SdMmcPciHcComponentNameGetControllerName, "en" }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdMmcPciHcDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdMmcPciHcDriverNameTable[] = { { "eng;en", L"Edkii Sd/Mmc Host Controller Driver" }, - { NULL , NULL } + { NULL, NULL } }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdMmcPciHcControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdMmcPciHcControllerNameTable[] = { { "eng;en", L"Edkii Sd/Mmc Host Controller" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -78,9 +78,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdMmcPciHcControllerName EFI_STATUS EFIAPI SdMmcPciHcComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -163,16 +163,16 @@ SdMmcPciHcComponentNameGetDriverName ( EFI_STATUS EFIAPI SdMmcPciHcComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; + EFI_STATUS Status; - if (Language == NULL || ControllerName == NULL) { + if ((Language == NULL) || (ControllerName == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c index 8b5f8e8ee7..a392a4e31a 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c @@ -24,14 +24,14 @@ **/ EFI_STATUS EmmcReset ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -41,9 +41,9 @@ EmmcReset ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_GO_IDLE_STATE; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeBc; - SdMmcCmdBlk.ResponseType = 0; + SdMmcCmdBlk.CommandIndex = EMMC_GO_IDLE_STATE; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeBc; + SdMmcCmdBlk.ResponseType = 0; SdMmcCmdBlk.CommandArgument = 0; gBS->Stall (1000); @@ -74,10 +74,10 @@ EmmcGetOcr ( IN OUT UINT32 *Argument ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -87,9 +87,9 @@ EmmcGetOcr ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_OP_COND; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR3; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_OP_COND; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR3; SdMmcCmdBlk.CommandArgument = *Argument; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -118,14 +118,14 @@ EmmcGetOcr ( **/ EFI_STATUS EmmcGetAllCid ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -135,9 +135,9 @@ EmmcGetAllCid ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_ALL_SEND_CID; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = EMMC_ALL_SEND_CID; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = 0; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -161,15 +161,15 @@ EmmcGetAllCid ( **/ EFI_STATUS EmmcSetRca ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -179,9 +179,9 @@ EmmcSetRca ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SET_RELATIVE_ADDR; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SET_RELATIVE_ADDR; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -211,13 +211,13 @@ EmmcGetCsd ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, IN UINT16 Rca, - OUT EMMC_CSD *Csd + OUT EMMC_CSD *Csd ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -227,9 +227,9 @@ EmmcGetCsd ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -237,7 +237,7 @@ EmmcGetCsd ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); + CopyMem (((UINT8 *)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); } return Status; @@ -258,15 +258,15 @@ EmmcGetCsd ( **/ EFI_STATUS EmmcSelect ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -276,9 +276,9 @@ EmmcSelect ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -303,13 +303,13 @@ EFI_STATUS EmmcGetExtCsd ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, - OUT EMMC_EXT_CSD *ExtCsd + OUT EMMC_EXT_CSD *ExtCsd ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -319,9 +319,9 @@ EmmcGetExtCsd ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = 0x00000000; Packet.InDataBuffer = ExtCsd; @@ -350,18 +350,18 @@ EmmcGetExtCsd ( **/ EFI_STATUS EmmcSwitch ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT8 Access, - IN UINT8 Index, - IN UINT8 Value, - IN UINT8 CmdSet + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT8 Access, + IN UINT8 Index, + IN UINT8 Value, + IN UINT8 CmdSet ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -371,9 +371,9 @@ EmmcSwitch ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SWITCH; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b; + SdMmcCmdBlk.CommandIndex = EMMC_SWITCH; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b; SdMmcCmdBlk.CommandArgument = (Access << 24) | (Index << 16) | (Value << 8) | CmdSet; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -400,13 +400,13 @@ EmmcSendStatus ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, IN UINT16 Rca, - OUT UINT32 *DevStatus + OUT UINT32 *DevStatus ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -416,9 +416,9 @@ EmmcSendStatus ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -447,16 +447,16 @@ EmmcSendStatus ( **/ EFI_STATUS EmmcSendTuningBlk ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT8 BusWidth + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT8 BusWidth ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 TuningBlock[128]; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 TuningBlock[128]; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -466,9 +466,9 @@ EmmcSendTuningBlk ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_TUNING_BLOCK; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_TUNING_BLOCK; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = 0; Packet.InDataBuffer = TuningBlock; @@ -503,24 +503,25 @@ EmmcSendTuningBlk ( **/ EFI_STATUS EmmcTuningClkForHs200 ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT8 BusWidth + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 HostCtrl2; - UINT8 Retry; + EFI_STATUS Status; + UINT8 HostCtrl2; + UINT8 Retry; // // Notify the host that the sampling clock tuning procedure starts. // HostCtrl2 = BIT6; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + // // Ask the device to send a sequence of tuning blocks till the tuning procedure is done. // @@ -550,11 +551,12 @@ EmmcTuningClkForHs200 ( // // Abort the tuning procedure and reset the tuning circuit. // - HostCtrl2 = (UINT8)~(BIT6 | BIT7); - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~(BIT6 | BIT7); + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + return EFI_DEVICE_ERROR; } @@ -615,19 +617,19 @@ EmmcCheckSwitchStatus ( **/ EFI_STATUS EmmcSwitchBusWidth ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN BOOLEAN IsDdr, - IN UINT8 BusWidth + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN BOOLEAN IsDdr, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 Access; - UINT8 Index; - UINT8 Value; - UINT8 CmdSet; + EFI_STATUS Status; + UINT8 Access; + UINT8 Index; + UINT8 Value; + UINT8 CmdSet; // // Write Byte, the Value field is written into the byte pointed by Index. @@ -683,23 +685,23 @@ EmmcSwitchBusWidth ( **/ EFI_STATUS EmmcSwitchBusTiming ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength, - IN SD_MMC_BUS_MODE BusTiming, - IN UINT32 ClockFreq + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength, + IN SD_MMC_BUS_MODE BusTiming, + IN UINT32 ClockFreq ) { - EFI_STATUS Status; - UINT8 Access; - UINT8 Index; - UINT8 Value; - UINT8 CmdSet; - SD_MMC_HC_PRIVATE_DATA *Private; - UINT8 HostCtrl1; - BOOLEAN DelaySendStatus; + EFI_STATUS Status; + UINT8 Access; + UINT8 Index; + UINT8 Value; + UINT8 CmdSet; + SD_MMC_HC_PRIVATE_DATA *Private; + UINT8 HostCtrl1; + BOOLEAN DelaySendStatus; Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru); // @@ -733,15 +735,15 @@ EmmcSwitchBusTiming ( return Status; } - if (BusTiming == SdMmcMmcHsSdr || BusTiming == SdMmcMmcHsDdr) { + if ((BusTiming == SdMmcMmcHsSdr) || (BusTiming == SdMmcMmcHsDdr)) { HostCtrl1 = BIT2; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } } else { - HostCtrl1 = (UINT8)~BIT2; - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 = (UINT8) ~BIT2; + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } @@ -767,6 +769,7 @@ EmmcSwitchBusTiming ( if (EFI_ERROR (Status)) { return Status; } + DelaySendStatus = FALSE; } else { DelaySendStatus = TRUE; @@ -808,18 +811,19 @@ EmmcSwitchBusTiming ( **/ EFI_STATUS EmmcSwitchToHighSpeed ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN SD_MMC_BUS_SETTINGS *BusMode + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN SD_MMC_BUS_SETTINGS *BusMode ) { EFI_STATUS Status; BOOLEAN IsDdr; - if ((BusMode->BusTiming != SdMmcMmcHsSdr && BusMode->BusTiming != SdMmcMmcHsDdr && BusMode->BusTiming != SdMmcMmcLegacy) || - BusMode->ClockFreq > 52) { + if (((BusMode->BusTiming != SdMmcMmcHsSdr) && (BusMode->BusTiming != SdMmcMmcHsDdr) && (BusMode->BusTiming != SdMmcMmcLegacy)) || + (BusMode->ClockFreq > 52)) + { return EFI_INVALID_PARAMETER; } @@ -855,17 +859,18 @@ EmmcSwitchToHighSpeed ( **/ EFI_STATUS EmmcSwitchToHS200 ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN SD_MMC_BUS_SETTINGS *BusMode + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN SD_MMC_BUS_SETTINGS *BusMode ) { EFI_STATUS Status; - if (BusMode->BusTiming != SdMmcMmcHs200 || - (BusMode->BusWidth != 4 && BusMode->BusWidth != 8)) { + if ((BusMode->BusTiming != SdMmcMmcHs200) || + ((BusMode->BusWidth != 4) && (BusMode->BusWidth != 8))) + { return EFI_INVALID_PARAMETER; } @@ -902,25 +907,26 @@ EmmcSwitchToHS200 ( **/ EFI_STATUS EmmcSwitchToHS400 ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN SD_MMC_BUS_SETTINGS *BusMode + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN SD_MMC_BUS_SETTINGS *BusMode ) { EFI_STATUS Status; SD_MMC_BUS_SETTINGS Hs200BusMode; UINT32 HsFreq; - if (BusMode->BusTiming != SdMmcMmcHs400 || - BusMode->BusWidth != 8) { + if ((BusMode->BusTiming != SdMmcMmcHs400) || + (BusMode->BusWidth != 8)) + { return EFI_INVALID_PARAMETER; } - Hs200BusMode.BusTiming = SdMmcMmcHs200; - Hs200BusMode.BusWidth = BusMode->BusWidth; - Hs200BusMode.ClockFreq = BusMode->ClockFreq; + Hs200BusMode.BusTiming = SdMmcMmcHs200; + Hs200BusMode.BusWidth = BusMode->BusWidth; + Hs200BusMode.ClockFreq = BusMode->ClockFreq; Hs200BusMode.DriverStrength = BusMode->DriverStrength; Status = EmmcSwitchToHS200 (PciIo, PassThru, Slot, Rca, &Hs200BusMode); @@ -973,29 +979,34 @@ EmmcIsBusTimingSupported ( Supported = FALSE; switch (BusTiming) { case SdMmcMmcHs400: - if ((((ExtCsd->DeviceType & (BIT6 | BIT7)) != 0) && (Capabilities->Hs400 != 0)) && Capabilities->BusWidth8 != 0) { + if ((((ExtCsd->DeviceType & (BIT6 | BIT7)) != 0) && (Capabilities->Hs400 != 0)) && (Capabilities->BusWidth8 != 0)) { Supported = TRUE; } + break; case SdMmcMmcHs200: if ((((ExtCsd->DeviceType & (BIT4 | BIT5)) != 0) && (Capabilities->Sdr104 != 0))) { Supported = TRUE; } + break; case SdMmcMmcHsDdr: if ((((ExtCsd->DeviceType & (BIT2 | BIT3)) != 0) && (Capabilities->Ddr50 != 0))) { Supported = TRUE; } + break; case SdMmcMmcHsSdr: if ((((ExtCsd->DeviceType & BIT1) != 0) && (Capabilities->HighSpeed != 0))) { Supported = TRUE; } + break; case SdMmcMmcLegacy: if ((ExtCsd->DeviceType & BIT0) != 0) { Supported = TRUE; } + break; default: ASSERT (FALSE); @@ -1018,8 +1029,8 @@ EmmcIsBusTimingSupported ( SD_MMC_BUS_MODE EmmcGetTargetBusTiming ( IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN EMMC_EXT_CSD *ExtCsd + IN UINT8 SlotIndex, + IN EMMC_EXT_CSD *ExtCsd ) { SD_MMC_BUS_MODE BusTiming; @@ -1033,6 +1044,7 @@ EmmcGetTargetBusTiming ( if (EmmcIsBusTimingSupported (Private, SlotIndex, ExtCsd, BusTiming)) { break; } + BusTiming--; } @@ -1052,17 +1064,17 @@ EmmcGetTargetBusTiming ( **/ BOOLEAN EmmcIsBusWidthSupported ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN SD_MMC_BUS_MODE BusTiming, - IN UINT16 BusWidth + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN SD_MMC_BUS_MODE BusTiming, + IN UINT16 BusWidth ) { - if (BusWidth == 8 && Private->Capability[SlotIndex].BusWidth8 != 0) { + if ((BusWidth == 8) && (Private->Capability[SlotIndex].BusWidth8 != 0)) { return TRUE; - } else if (BusWidth == 4 && BusTiming != SdMmcMmcHs400) { + } else if ((BusWidth == 4) && (BusTiming != SdMmcMmcHs400)) { return TRUE; - } else if (BusWidth == 1 && (BusTiming == SdMmcMmcHsSdr || BusTiming == SdMmcMmcLegacy)) { + } else if ((BusWidth == 1) && ((BusTiming == SdMmcMmcHsSdr) || (BusTiming == SdMmcMmcLegacy))) { return TRUE; } @@ -1081,10 +1093,10 @@ EmmcIsBusWidthSupported ( **/ UINT8 EmmcGetTargetBusWidth ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN EMMC_EXT_CSD *ExtCsd, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN EMMC_EXT_CSD *ExtCsd, + IN SD_MMC_BUS_MODE BusTiming ) { UINT8 BusWidth; @@ -1092,8 +1104,9 @@ EmmcGetTargetBusWidth ( PreferredBusWidth = Private->Slot[SlotIndex].OperatingParameters.BusWidth; - if (PreferredBusWidth != EDKII_SD_MMC_BUS_WIDTH_IGNORE && - EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, PreferredBusWidth)) { + if ((PreferredBusWidth != EDKII_SD_MMC_BUS_WIDTH_IGNORE) && + EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, PreferredBusWidth)) + { BusWidth = PreferredBusWidth; } else if (EmmcIsBusWidthSupported (Private, SlotIndex, BusTiming, 8)) { BusWidth = 8; @@ -1118,14 +1131,14 @@ EmmcGetTargetBusWidth ( **/ UINT32 EmmcGetTargetClockFreq ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN EMMC_EXT_CSD *ExtCsd, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN EMMC_EXT_CSD *ExtCsd, + IN SD_MMC_BUS_MODE BusTiming ) { - UINT32 PreferredClockFreq; - UINT32 MaxClockFreq; + UINT32 PreferredClockFreq; + UINT32 MaxClockFreq; PreferredClockFreq = Private->Slot[SlotIndex].OperatingParameters.ClockFreq; @@ -1143,7 +1156,7 @@ EmmcGetTargetClockFreq ( break; } - if (PreferredClockFreq != EDKII_SD_MMC_CLOCK_FREQ_IGNORE && PreferredClockFreq < MaxClockFreq) { + if ((PreferredClockFreq != EDKII_SD_MMC_CLOCK_FREQ_IGNORE) && (PreferredClockFreq < MaxClockFreq)) { return PreferredClockFreq; } else { return MaxClockFreq; @@ -1162,20 +1175,21 @@ EmmcGetTargetClockFreq ( **/ EDKII_SD_MMC_DRIVER_STRENGTH EmmcGetTargetDriverStrength ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN EMMC_EXT_CSD *ExtCsd, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN EMMC_EXT_CSD *ExtCsd, + IN SD_MMC_BUS_MODE BusTiming ) { EDKII_SD_MMC_DRIVER_STRENGTH PreferredDriverStrength; EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; PreferredDriverStrength = Private->Slot[SlotIndex].OperatingParameters.DriverStrength; - DriverStrength.Emmc = EmmcDriverStrengthType0; + DriverStrength.Emmc = EmmcDriverStrengthType0; - if (PreferredDriverStrength.Emmc != EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE && - (ExtCsd->DriverStrength & (BIT0 << PreferredDriverStrength.Emmc))) { + if ((PreferredDriverStrength.Emmc != EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE) && + (ExtCsd->DriverStrength & (BIT0 << PreferredDriverStrength.Emmc))) + { DriverStrength.Emmc = PreferredDriverStrength.Emmc; } @@ -1198,9 +1212,9 @@ EmmcGetTargetBusMode ( OUT SD_MMC_BUS_SETTINGS *BusMode ) { - BusMode->BusTiming = EmmcGetTargetBusTiming (Private, SlotIndex, ExtCsd); - BusMode->BusWidth = EmmcGetTargetBusWidth (Private, SlotIndex, ExtCsd, BusMode->BusTiming); - BusMode->ClockFreq = EmmcGetTargetClockFreq (Private, SlotIndex, ExtCsd, BusMode->BusTiming); + BusMode->BusTiming = EmmcGetTargetBusTiming (Private, SlotIndex, ExtCsd); + BusMode->BusWidth = EmmcGetTargetBusWidth (Private, SlotIndex, ExtCsd, BusMode->BusTiming); + BusMode->ClockFreq = EmmcGetTargetClockFreq (Private, SlotIndex, ExtCsd, BusMode->BusTiming); BusMode->DriverStrength = EmmcGetTargetDriverStrength (Private, SlotIndex, ExtCsd, BusMode->BusTiming); } @@ -1221,17 +1235,17 @@ EmmcGetTargetBusMode ( **/ EFI_STATUS EmmcSetBusMode ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca ) { - EFI_STATUS Status; - EMMC_CSD Csd; - EMMC_EXT_CSD ExtCsd; - SD_MMC_BUS_SETTINGS BusMode; - SD_MMC_HC_PRIVATE_DATA *Private; + EFI_STATUS Status; + EMMC_CSD Csd; + EMMC_EXT_CSD ExtCsd; + SD_MMC_BUS_SETTINGS BusMode; + SD_MMC_HC_PRIVATE_DATA *Private; Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru); @@ -1260,8 +1274,14 @@ EmmcSetBusMode ( EmmcGetTargetBusMode (Private, Slot, &ExtCsd, &BusMode); - DEBUG ((DEBUG_INFO, "EmmcSetBusMode: Target bus mode: timing = %d, width = %d, clock freq = %d, driver strength = %d\n", - BusMode.BusTiming, BusMode.BusWidth, BusMode.ClockFreq, BusMode.DriverStrength.Emmc)); + DEBUG (( + DEBUG_INFO, + "EmmcSetBusMode: Target bus mode: timing = %d, width = %d, clock freq = %d, driver strength = %d\n", + BusMode.BusTiming, + BusMode.BusWidth, + BusMode.ClockFreq, + BusMode.DriverStrength.Emmc + )); if (BusMode.BusTiming == SdMmcMmcHs400) { Status = EmmcSwitchToHS400 (PciIo, PassThru, Slot, Rca, &BusMode); @@ -1296,8 +1316,8 @@ EmmcSetBusMode ( **/ EFI_STATUS EmmcIdentification ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { EFI_STATUS Status; @@ -1324,13 +1344,15 @@ EmmcIdentification ( DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd1 fails with %r\n", Status)); return Status; } + Ocr |= BIT30; if (Retry++ == 100) { DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd1 fails too many times\n")); return EFI_DEVICE_ERROR; } - gBS->Stall(10 * 1000); + + gBS->Stall (10 * 1000); } while ((Ocr & BIT31) == 0); Status = EmmcGetAllCid (PassThru, Slot); @@ -1338,6 +1360,7 @@ EmmcIdentification ( DEBUG ((DEBUG_VERBOSE, "EmmcIdentification: Executing Cmd2 fails with %r\n", Status)); return Status; } + // // Slot starts from 0 and valid RCA starts from 1. // Here we takes a simple formula to calculate the RCA. @@ -1350,6 +1373,7 @@ EmmcIdentification ( DEBUG ((DEBUG_ERROR, "EmmcIdentification: Executing Cmd3 fails with %r\n", Status)); return Status; } + // // Enter Data Tranfer Mode. // @@ -1360,4 +1384,3 @@ EmmcIdentification ( return Status; } - diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c index b630daab76..662f9f483c 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c @@ -23,14 +23,14 @@ **/ EFI_STATUS SdCardReset ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -65,16 +65,16 @@ SdCardReset ( **/ EFI_STATUS SdCardVoltageCheck ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT8 SupplyVoltage, - IN UINT8 CheckPattern + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT8 SupplyVoltage, + IN UINT8 CheckPattern ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -84,9 +84,9 @@ SdCardVoltageCheck ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_IF_COND; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR7; + SdMmcCmdBlk.CommandIndex = SD_SEND_IF_COND; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeBcr; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR7; SdMmcCmdBlk.CommandArgument = (SupplyVoltage << 8) | CheckPattern; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -116,17 +116,17 @@ SdCardVoltageCheck ( **/ EFI_STATUS SdioSendOpCond ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT32 VoltageWindow, - IN BOOLEAN S18R + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT32 VoltageWindow, + IN BOOLEAN S18R ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 Switch; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 Switch; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -176,16 +176,16 @@ SdCardSendOpCond ( IN BOOLEAN S18R, IN BOOLEAN Xpc, IN BOOLEAN Hcs, - OUT UINT32 *Ocr + OUT UINT32 *Ocr ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 Switch; - UINT32 MaxPower; - UINT32 HostCapacity; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 Switch; + UINT32 MaxPower; + UINT32 HostCapacity; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -195,9 +195,9 @@ SdCardSendOpCond ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_APP_CMD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_APP_CMD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -241,14 +241,14 @@ SdCardSendOpCond ( **/ EFI_STATUS SdCardAllSendCid ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -285,13 +285,13 @@ EFI_STATUS SdCardSetRca ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, - OUT UINT16 *Rca + OUT UINT16 *Rca ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -328,15 +328,15 @@ SdCardSetRca ( **/ EFI_STATUS SdCardSelect ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -351,6 +351,7 @@ SdCardSelect ( if (Rca != 0) { SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b; } + SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -372,14 +373,14 @@ SdCardSelect ( **/ EFI_STATUS SdCardVoltageSwitch ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -389,9 +390,9 @@ SdCardVoltageSwitch ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_VOLTAGE_SWITCH; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_VOLTAGE_SWITCH; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = 0; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -415,17 +416,17 @@ SdCardVoltageSwitch ( **/ EFI_STATUS SdCardSetBusWidth ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN UINT8 BusWidth + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN UINT8 BusWidth ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 Value; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 Value; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -435,9 +436,9 @@ SdCardSetBusWidth ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_APP_CMD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_APP_CMD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -490,15 +491,15 @@ SdCardSwitch ( IN SD_DRIVER_STRENGTH_TYPE DriverStrength, IN UINT8 PowerLimit, IN BOOLEAN Mode, - OUT UINT8 *SwitchResp + OUT UINT8 *SwitchResp ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 ModeValue; - UINT8 AccessMode; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 ModeValue; + UINT8 AccessMode; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -552,7 +553,8 @@ SdCardSwitch ( if ((((AccessMode & 0xF) != 0xF) && ((SwitchResp[16] & 0xF) != AccessMode)) || (((CommandSystem & 0xF) != 0xF) && (((SwitchResp[16] >> 4) & 0xF) != CommandSystem)) || (((DriverStrength & 0xF) != 0xF) && ((SwitchResp[15] & 0xF) != DriverStrength)) || - (((PowerLimit & 0xF) != 0xF) && (((SwitchResp[15] >> 4) & 0xF) != PowerLimit))) { + (((PowerLimit & 0xF) != 0xF) && (((SwitchResp[15] >> 4) & 0xF) != PowerLimit))) + { return EFI_DEVICE_ERROR; } } @@ -579,13 +581,13 @@ SdCardSendStatus ( IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, IN UINT8 Slot, IN UINT16 Rca, - OUT UINT32 *DevStatus + OUT UINT32 *DevStatus ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -595,9 +597,9 @@ SdCardSendStatus ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_STATUS; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_SEND_STATUS; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdMmcPassThruPassThru (PassThru, Slot, &Packet, NULL); @@ -625,15 +627,15 @@ SdCardSendStatus ( **/ EFI_STATUS SdCardSendTuningBlk ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 TuningBlock[64]; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 TuningBlock[64]; ZeroMem (&SdMmcCmdBlk, sizeof (SdMmcCmdBlk)); ZeroMem (&SdMmcStatusBlk, sizeof (SdMmcStatusBlk)); @@ -643,9 +645,9 @@ SdCardSendTuningBlk ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_MMC_HC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_TUNING_BLOCK; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_SEND_TUNING_BLOCK; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = 0; Packet.InDataBuffer = TuningBlock; @@ -675,23 +677,24 @@ SdCardSendTuningBlk ( **/ EFI_STATUS SdCardTuningClock ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot ) { - EFI_STATUS Status; - UINT8 HostCtrl2; - UINT8 Retry; + EFI_STATUS Status; + UINT8 HostCtrl2; + UINT8 Retry; // // Notify the host that the sampling clock tuning procedure starts. // HostCtrl2 = BIT6; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + // // Ask the device to send a sequence of tuning blocks till the tuning procedure is done. // @@ -711,6 +714,7 @@ SdCardTuningClock ( if ((HostCtrl2 & (BIT6 | BIT7)) == 0) { break; } + if ((HostCtrl2 & (BIT6 | BIT7)) == BIT7) { return EFI_SUCCESS; } @@ -720,11 +724,12 @@ SdCardTuningClock ( // // Abort the tuning procedure and reset the tuning circuit. // - HostCtrl2 = (UINT8)~(BIT6 | BIT7); - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~(BIT6 | BIT7); + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + return EFI_DEVICE_ERROR; } @@ -746,15 +751,15 @@ SdCardTuningClock ( **/ EFI_STATUS SdCardSwitchBusWidth ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN UINT8 BusWidth + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT32 DevStatus; + EFI_STATUS Status; + UINT32 DevStatus; Status = SdCardSetBusWidth (PassThru, Slot, Rca, BusWidth); if (EFI_ERROR (Status)) { @@ -767,6 +772,7 @@ SdCardSwitchBusWidth ( DEBUG ((DEBUG_ERROR, "SdCardSwitchBusWidth: Send status fails with %r\n", Status)); return Status; } + // // Check the switch operation is really successful or not. // @@ -793,14 +799,14 @@ SdCardSwitchBusWidth ( **/ BOOLEAN SdIsBusTimingSupported ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN UINT8 CardSupportedBusTimings, - IN BOOLEAN IsInUhsI, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN UINT8 CardSupportedBusTimings, + IN BOOLEAN IsInUhsI, + IN SD_MMC_BUS_MODE BusTiming ) { - SD_MMC_HC_SLOT_CAP *Capability; + SD_MMC_HC_SLOT_CAP *Capability; Capability = &Private->Capability[SlotIndex]; @@ -810,26 +816,31 @@ SdIsBusTimingSupported ( if ((Capability->Sdr104 != 0) && ((CardSupportedBusTimings & BIT3) != 0)) { return TRUE; } + break; case SdMmcUhsDdr50: if ((Capability->Ddr50 != 0) && ((CardSupportedBusTimings & BIT4) != 0)) { return TRUE; } + break; case SdMmcUhsSdr50: if ((Capability->Sdr50 != 0) && ((CardSupportedBusTimings & BIT2) != 0)) { return TRUE; } + break; case SdMmcUhsSdr25: if ((CardSupportedBusTimings & BIT1) != 0) { return TRUE; } + break; case SdMmcUhsSdr12: if ((CardSupportedBusTimings & BIT0) != 0) { return TRUE; } + break; default: break; @@ -837,14 +848,16 @@ SdIsBusTimingSupported ( } else { switch (BusTiming) { case SdMmcSdHs: - if ((Capability->HighSpeed != 0) && (CardSupportedBusTimings & BIT1) != 0) { + if ((Capability->HighSpeed != 0) && ((CardSupportedBusTimings & BIT1) != 0)) { return TRUE; } + break; case SdMmcSdDs: if ((CardSupportedBusTimings & BIT0) != 0) { return TRUE; } + break; default: break; @@ -886,6 +899,7 @@ SdGetTargetBusTiming ( if (SdIsBusTimingSupported (Private, SlotIndex, CardSupportedBusTimings, IsInUhsI, BusTiming)) { break; } + BusTiming--; } @@ -903,9 +917,9 @@ SdGetTargetBusTiming ( **/ UINT8 SdGetTargetBusWidth ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN SD_MMC_BUS_MODE BusTiming ) { UINT8 BusWidth; @@ -913,9 +927,10 @@ SdGetTargetBusWidth ( PreferredBusWidth = Private->Slot[SlotIndex].OperatingParameters.BusWidth; - if (BusTiming == SdMmcSdDs || BusTiming == SdMmcSdHs) { - if (PreferredBusWidth != EDKII_SD_MMC_BUS_WIDTH_IGNORE && - (PreferredBusWidth == 1 || PreferredBusWidth == 4)) { + if ((BusTiming == SdMmcSdDs) || (BusTiming == SdMmcSdHs)) { + if ((PreferredBusWidth != EDKII_SD_MMC_BUS_WIDTH_IGNORE) && + ((PreferredBusWidth == 1) || (PreferredBusWidth == 4))) + { BusWidth = PreferredBusWidth; } else { BusWidth = 4; @@ -943,13 +958,13 @@ SdGetTargetBusWidth ( **/ UINT32 SdGetTargetBusClockFreq ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN SD_MMC_BUS_MODE BusTiming ) { - UINT32 PreferredClockFreq; - UINT32 MaxClockFreq; + UINT32 PreferredClockFreq; + UINT32 MaxClockFreq; PreferredClockFreq = Private->Slot[SlotIndex].OperatingParameters.ClockFreq; @@ -971,7 +986,7 @@ SdGetTargetBusClockFreq ( MaxClockFreq = 25; } - if (PreferredClockFreq != EDKII_SD_MMC_CLOCK_FREQ_IGNORE && PreferredClockFreq < MaxClockFreq) { + if ((PreferredClockFreq != EDKII_SD_MMC_CLOCK_FREQ_IGNORE) && (PreferredClockFreq < MaxClockFreq)) { return PreferredClockFreq; } else { return MaxClockFreq; @@ -990,32 +1005,33 @@ SdGetTargetBusClockFreq ( **/ EDKII_SD_MMC_DRIVER_STRENGTH SdGetTargetDriverStrength ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 SlotIndex, - IN UINT8 CardSupportedDriverStrengths, - IN SD_MMC_BUS_MODE BusTiming + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 SlotIndex, + IN UINT8 CardSupportedDriverStrengths, + IN SD_MMC_BUS_MODE BusTiming ) { EDKII_SD_MMC_DRIVER_STRENGTH PreferredDriverStrength; EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; - if (BusTiming == SdMmcSdDs || BusTiming == SdMmcSdHs) { + if ((BusTiming == SdMmcSdDs) || (BusTiming == SdMmcSdHs)) { DriverStrength.Sd = SdDriverStrengthIgnore; return DriverStrength; } PreferredDriverStrength = Private->Slot[SlotIndex].OperatingParameters.DriverStrength; - DriverStrength.Sd = SdDriverStrengthTypeB; - - if (PreferredDriverStrength.Sd != EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE && - (CardSupportedDriverStrengths & (BIT0 << PreferredDriverStrength.Sd))) { - - if ((PreferredDriverStrength.Sd == SdDriverStrengthTypeA && - (Private->Capability[SlotIndex].DriverTypeA != 0)) || - (PreferredDriverStrength.Sd == SdDriverStrengthTypeC && - (Private->Capability[SlotIndex].DriverTypeC != 0)) || - (PreferredDriverStrength.Sd == SdDriverStrengthTypeD && - (Private->Capability[SlotIndex].DriverTypeD != 0))) { + DriverStrength.Sd = SdDriverStrengthTypeB; + + if ((PreferredDriverStrength.Sd != EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE) && + (CardSupportedDriverStrengths & (BIT0 << PreferredDriverStrength.Sd))) + { + if (((PreferredDriverStrength.Sd == SdDriverStrengthTypeA) && + (Private->Capability[SlotIndex].DriverTypeA != 0)) || + ((PreferredDriverStrength.Sd == SdDriverStrengthTypeC) && + (Private->Capability[SlotIndex].DriverTypeC != 0)) || + ((PreferredDriverStrength.Sd == SdDriverStrengthTypeD) && + (Private->Capability[SlotIndex].DriverTypeD != 0))) + { DriverStrength.Sd = PreferredDriverStrength.Sd; } } @@ -1041,9 +1057,9 @@ SdGetTargetBusMode ( OUT SD_MMC_BUS_SETTINGS *BusMode ) { - BusMode->BusTiming = SdGetTargetBusTiming (Private, SlotIndex, SwitchQueryResp[13], IsInUhsI); - BusMode->BusWidth = SdGetTargetBusWidth (Private, SlotIndex, BusMode->BusTiming); - BusMode->ClockFreq = SdGetTargetBusClockFreq (Private, SlotIndex, BusMode->BusTiming); + BusMode->BusTiming = SdGetTargetBusTiming (Private, SlotIndex, SwitchQueryResp[13], IsInUhsI); + BusMode->BusWidth = SdGetTargetBusWidth (Private, SlotIndex, BusMode->BusTiming); + BusMode->ClockFreq = SdGetTargetBusClockFreq (Private, SlotIndex, BusMode->BusTiming); BusMode->DriverStrength = SdGetTargetDriverStrength (Private, SlotIndex, SwitchQueryResp[9], BusMode->BusTiming); } @@ -1065,19 +1081,19 @@ SdGetTargetBusMode ( **/ EFI_STATUS SdCardSetBusMode ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, - IN UINT8 Slot, - IN UINT16 Rca, - IN BOOLEAN S18A + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru, + IN UINT8 Slot, + IN UINT16 Rca, + IN BOOLEAN S18A ) { - EFI_STATUS Status; - SD_MMC_HC_SLOT_CAP *Capability; - UINT8 HostCtrl1; - UINT8 SwitchResp[64]; - SD_MMC_HC_PRIVATE_DATA *Private; - SD_MMC_BUS_SETTINGS BusMode; + EFI_STATUS Status; + SD_MMC_HC_SLOT_CAP *Capability; + UINT8 HostCtrl1; + UINT8 SwitchResp[64]; + SD_MMC_HC_PRIVATE_DATA *Private; + SD_MMC_BUS_SETTINGS BusMode; Private = SD_MMC_HC_PRIVATE_FROM_THIS (PassThru); @@ -1109,8 +1125,14 @@ SdCardSetBusMode ( SdGetTargetBusMode (Private, Slot, SwitchResp, S18A, &BusMode); - DEBUG ((DEBUG_INFO, "SdCardSetBusMode: Target bus mode: bus timing = %d, bus width = %d, clock freq[MHz] = %d, driver strength = %d\n", - BusMode.BusTiming, BusMode.BusWidth, BusMode.ClockFreq, BusMode.DriverStrength.Sd)); + DEBUG (( + DEBUG_INFO, + "SdCardSetBusMode: Target bus mode: bus timing = %d, bus width = %d, clock freq[MHz] = %d, driver strength = %d\n", + BusMode.BusTiming, + BusMode.BusWidth, + BusMode.ClockFreq, + BusMode.DriverStrength.Sd + )); if (!S18A) { Status = SdCardSwitchBusWidth (PciIo, PassThru, Slot, Rca, BusMode.BusWidth); @@ -1134,7 +1156,7 @@ SdCardSetBusMode ( // if (BusMode.BusTiming == SdMmcSdHs) { HostCtrl1 = BIT2; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } @@ -1174,8 +1196,8 @@ SdCardSetBusMode ( **/ EFI_STATUS SdCardIdentification ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { EFI_STATUS Status; @@ -1202,6 +1224,7 @@ SdCardIdentification ( DEBUG ((DEBUG_INFO, "SdCardIdentification: Executing Cmd0 fails with %r\n", Status)); return Status; } + // // 2. Send Cmd8 to the device // @@ -1210,6 +1233,7 @@ SdCardIdentification ( DEBUG ((DEBUG_INFO, "SdCardIdentification: Executing Cmd8 fails with %r\n", Status)); return Status; } + // // 3. Send SDIO Cmd5 to the device to the SDIO device OCR register. // @@ -1218,6 +1242,7 @@ SdCardIdentification ( DEBUG ((DEBUG_INFO, "SdCardIdentification: Found SDIO device, ignore it as we don't support\n")); return EFI_DEVICE_ERROR; } + // // 4. Send Acmd41 with voltage window 0 to the device // @@ -1259,7 +1284,8 @@ SdCardIdentification ( } if (((ControllerVer & 0xFF) >= SD_MMC_HC_CTRL_VER_300) && - ((ControllerVer & 0xFF) <= SD_MMC_HC_CTRL_VER_420)) { + ((ControllerVer & 0xFF) <= SD_MMC_HC_CTRL_VER_420)) + { S18r = TRUE; } else if (((ControllerVer & 0xFF) == SD_MMC_HC_CTRL_VER_100) || ((ControllerVer & 0xFF) == SD_MMC_HC_CTRL_VER_200)) { S18r = FALSE; @@ -1267,6 +1293,7 @@ SdCardIdentification ( ASSERT (FALSE); return EFI_UNSUPPORTED; } + // // 5. Repeatly send Acmd41 with supply voltage window to the device. // Note here we only support the cards complied with SD physical @@ -1285,7 +1312,8 @@ SdCardIdentification ( DEBUG ((DEBUG_ERROR, "SdCardIdentification: SdCardSendOpCond fails too many times\n")); return EFI_DEVICE_ERROR; } - gBS->Stall(10 * 1000); + + gBS->Stall (10 * 1000); } while ((Ocr & BIT31) == 0); // @@ -1293,10 +1321,11 @@ SdCardIdentification ( // (One of support bits is set to 1: SDR50, SDR104 or DDR50 in the // Capabilities register), switch its voltage to 1.8V. // - if ((Private->Capability[Slot].Sdr50 != 0 || - Private->Capability[Slot].Sdr104 != 0 || - Private->Capability[Slot].Ddr50 != 0) && - ((Ocr & BIT24) != 0)) { + if (((Private->Capability[Slot].Sdr50 != 0) || + (Private->Capability[Slot].Sdr104 != 0) || + (Private->Capability[Slot].Ddr50 != 0)) && + ((Ocr & BIT24) != 0)) + { Status = SdCardVoltageSwitch (PassThru, Slot); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SdCardIdentification: Executing SdCardVoltageSwitch fails with %r\n", Status)); @@ -1315,7 +1344,8 @@ SdCardIdentification ( Status = EFI_DEVICE_ERROR; goto Error; } - HostCtrl2 = BIT3; + + HostCtrl2 = BIT3; SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); gBS->Stall (5000); @@ -1341,6 +1371,7 @@ SdCardIdentification ( goto Error; } } + DEBUG ((DEBUG_INFO, "SdCardIdentification: Switch to 1.8v signal voltage success\n")); } @@ -1355,6 +1386,7 @@ SdCardIdentification ( DEBUG ((DEBUG_ERROR, "SdCardIdentification: Executing SdCardSetRca fails with %r\n", Status)); return Status; } + // // Enter Data Tranfer Mode. // @@ -1369,8 +1401,7 @@ Error: // // Set SD Bus Power = 0 // - PowerCtrl = (UINT8)~BIT0; - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, sizeof (PowerCtrl), &PowerCtrl); + PowerCtrl = (UINT8) ~BIT0; + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, sizeof (PowerCtrl), &PowerCtrl); return EFI_DEVICE_ERROR; } - diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c index 57f4cf329a..ab2becdd19 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.c @@ -14,12 +14,12 @@ #include "SdMmcPciHcDxe.h" -EDKII_SD_MMC_OVERRIDE *mOverride; +EDKII_SD_MMC_OVERRIDE *mOverride; // // Driver Global Variables // -EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding = { SdMmcPciHcDriverBindingSupported, SdMmcPciHcDriverBindingStart, SdMmcPciHcDriverBindingStop, @@ -28,7 +28,7 @@ EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding = { NULL }; -#define SLOT_INIT_TEMPLATE {0, UnknownSlot, 0, 0, 0, 0, \ +#define SLOT_INIT_TEMPLATE {0, UnknownSlot, 0, 0, 0, 0,\ {EDKII_SD_MMC_BUS_WIDTH_IGNORE,\ EDKII_SD_MMC_CLOCK_FREQ_IGNORE,\ {EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE}}} @@ -36,7 +36,7 @@ EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding = { // // Template for SD/MMC host controller private data. // -SD_MMC_HC_PRIVATE_DATA gSdMmcPciHcTemplate = { +SD_MMC_HC_PRIVATE_DATA gSdMmcPciHcTemplate = { SD_MMC_HC_PRIVATE_SIGNATURE, // Signature NULL, // ControllerHandle NULL, // PciIo @@ -63,7 +63,7 @@ SD_MMC_HC_PRIVATE_DATA gSdMmcPciHcTemplate = { SLOT_INIT_TEMPLATE }, { // Capability - {0}, + { 0 }, }, { // MaxCurrent 0, @@ -73,25 +73,25 @@ SD_MMC_HC_PRIVATE_DATA gSdMmcPciHcTemplate = { } }; -SD_DEVICE_PATH mSdDpTemplate = { +SD_DEVICE_PATH mSdDpTemplate = { { MESSAGING_DEVICE_PATH, MSG_SD_DP, { - (UINT8) (sizeof (SD_DEVICE_PATH)), - (UINT8) ((sizeof (SD_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (SD_DEVICE_PATH)), + (UINT8)((sizeof (SD_DEVICE_PATH)) >> 8) } }, 0 }; -EMMC_DEVICE_PATH mEmmcDpTemplate = { +EMMC_DEVICE_PATH mEmmcDpTemplate = { { MESSAGING_DEVICE_PATH, MSG_EMMC_DP, { - (UINT8) (sizeof (EMMC_DEVICE_PATH)), - (UINT8) ((sizeof (EMMC_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (EMMC_DEVICE_PATH)), + (UINT8)((sizeof (EMMC_DEVICE_PATH)) >> 8) } }, 0 @@ -101,7 +101,7 @@ EMMC_DEVICE_PATH mEmmcDpTemplate = { // Prioritized function list to detect card type. // User could add other card detection logic here. // -CARD_TYPE_DETECT_ROUTINE mCardTypeDetectRoutineTable[] = { +CARD_TYPE_DETECT_ROUTINE mCardTypeDetectRoutineTable[] = { EmmcIdentification, SdCardIdentification, NULL @@ -124,7 +124,7 @@ InitializeSdMmcPciHcDxe ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, @@ -150,19 +150,19 @@ InitializeSdMmcPciHcDxe ( VOID EFIAPI ProcessAsyncTaskList ( - IN EFI_EVENT Event, - IN VOID* Context + IN EFI_EVENT Event, + IN VOID *Context ) { - SD_MMC_HC_PRIVATE_DATA *Private; - LIST_ENTRY *Link; - SD_MMC_HC_TRB *Trb; - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - BOOLEAN InfiniteWait; - EFI_EVENT TrbEvent; + SD_MMC_HC_PRIVATE_DATA *Private; + LIST_ENTRY *Link; + SD_MMC_HC_TRB *Trb; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + BOOLEAN InfiniteWait; + EFI_EVENT TrbEvent; - Private = (SD_MMC_HC_PRIVATE_DATA*)Context; + Private = (SD_MMC_HC_PRIVATE_DATA *)Context; // // Check if the first entry in the async I/O queue is done or not. @@ -176,6 +176,7 @@ ProcessAsyncTaskList ( Status = EFI_NO_MEDIA; goto Done; } + if (!Trb->Started) { // // Check whether the cmd/data line is ready for transfer. @@ -183,7 +184,7 @@ ProcessAsyncTaskList ( Status = SdMmcCheckTrbEnv (Private, Trb); if (!EFI_ERROR (Status)) { Trb->Started = TRUE; - Status = SdMmcExecTrb (Private, Trb); + Status = SdMmcExecTrb (Private, Trb); if (EFI_ERROR (Status)) { goto Done; } @@ -191,6 +192,7 @@ ProcessAsyncTaskList ( goto Done; } } + Status = SdMmcCheckTrbResult (Private, Trb); } @@ -202,10 +204,11 @@ Done: } else { InfiniteWait = FALSE; } + if ((!InfiniteWait) && (Trb->Timeout-- == 0)) { RemoveEntryList (Link); Trb->Packet->TransactionStatus = EFI_TIMEOUT; - TrbEvent = Trb->Event; + TrbEvent = Trb->Event; SdMmcFreeTrb (Trb); DEBUG ((DEBUG_VERBOSE, "ProcessAsyncTaskList(): Signal Event %p EFI_TIMEOUT\n", TrbEvent)); gBS->SignalEvent (TrbEvent); @@ -217,11 +220,12 @@ Done: } else if ((Trb != NULL)) { RemoveEntryList (Link); Trb->Packet->TransactionStatus = Status; - TrbEvent = Trb->Event; + TrbEvent = Trb->Event; SdMmcFreeTrb (Trb); DEBUG ((DEBUG_VERBOSE, "ProcessAsyncTaskList(): Signal Event %p with %r\n", TrbEvent, Status)); gBS->SignalEvent (TrbEvent); } + return; } @@ -236,23 +240,23 @@ Done: VOID EFIAPI SdMmcPciHcEnumerateDevice ( - IN EFI_EVENT Event, - IN VOID* Context + IN EFI_EVENT Event, + IN VOID *Context ) { - SD_MMC_HC_PRIVATE_DATA *Private; - EFI_STATUS Status; - UINT8 Slot; - BOOLEAN MediaPresent; - UINT32 RoutineNum; - CARD_TYPE_DETECT_ROUTINE *Routine; - UINTN Index; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - SD_MMC_HC_TRB *Trb; - EFI_TPL OldTpl; - - Private = (SD_MMC_HC_PRIVATE_DATA*)Context; + SD_MMC_HC_PRIVATE_DATA *Private; + EFI_STATUS Status; + UINT8 Slot; + BOOLEAN MediaPresent; + UINT32 RoutineNum; + CARD_TYPE_DETECT_ROUTINE *Routine; + UINTN Index; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + SD_MMC_HC_TRB *Trb; + EFI_TPL OldTpl; + + Private = (SD_MMC_HC_PRIVATE_DATA *)Context; for (Slot = 0; Slot < SD_MMC_HC_MAX_SLOT; Slot++) { if ((Private->Slot[Slot].Enable) && (Private->Slot[Slot].SlotType == RemovableSlot)) { @@ -267,9 +271,10 @@ SdMmcPciHcEnumerateDevice ( OldTpl = gBS->RaiseTPL (TPL_NOTIFY); for (Link = GetFirstNode (&Private->Queue); !IsNull (&Private->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Private->Queue, Link); - Trb = SD_MMC_HC_TRB_FROM_THIS (Link); + Trb = SD_MMC_HC_TRB_FROM_THIS (Link); if (Trb->Slot == Slot) { RemoveEntryList (Link); Trb->Packet->TransactionStatus = EFI_NO_MEDIA; @@ -277,17 +282,19 @@ SdMmcPciHcEnumerateDevice ( SdMmcFreeTrb (Trb); } } + gBS->RestoreTPL (OldTpl); // // Notify the upper layer the connect state change through ReinstallProtocolInterface. // gBS->ReinstallProtocolInterface ( - Private->ControllerHandle, - &gEfiSdMmcPassThruProtocolGuid, - &Private->PassThru, - &Private->PassThru - ); + Private->ControllerHandle, + &gEfiSdMmcPassThruProtocolGuid, + &Private->PassThru, + &Private->PassThru + ); } + if ((Status == EFI_MEDIA_CHANGED) && MediaPresent) { DEBUG ((DEBUG_INFO, "SdMmcPciHcEnumerateDevice: device connected at slot %d of pci %p\n", Slot, Private->PciIo)); // @@ -297,6 +304,7 @@ SdMmcPciHcEnumerateDevice ( if (EFI_ERROR (Status)) { continue; } + // // Reinitialize slot and restart identification process for the new attached device // @@ -307,16 +315,17 @@ SdMmcPciHcEnumerateDevice ( Private->Slot[Slot].MediaPresent = TRUE; Private->Slot[Slot].Initialized = TRUE; - RoutineNum = sizeof (mCardTypeDetectRoutineTable) / sizeof (CARD_TYPE_DETECT_ROUTINE); + RoutineNum = sizeof (mCardTypeDetectRoutineTable) / sizeof (CARD_TYPE_DETECT_ROUTINE); for (Index = 0; Index < RoutineNum; Index++) { Routine = &mCardTypeDetectRoutineTable[Index]; if (*Routine != NULL) { - Status = (*Routine) (Private, Slot); + Status = (*Routine)(Private, Slot); if (!EFI_ERROR (Status)) { break; } } } + // // This card doesn't get initialized correctly. // @@ -385,9 +394,9 @@ SdMmcPciHcEnumerateDevice ( EFI_STATUS EFIAPI SdMmcPciHcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { EFI_STATUS Status; @@ -405,7 +414,7 @@ SdMmcPciHcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID *) &ParentDevicePath, + (VOID *)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -416,15 +425,16 @@ SdMmcPciHcDriverBindingSupported ( // return Status; } + // // Close the protocol because we don't use it here. // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Now test the EfiPciIoProtocol. @@ -432,7 +442,7 @@ SdMmcPciHcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -455,30 +465,32 @@ SdMmcPciHcDriverBindingSupported ( ); if (EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_UNSUPPORTED; } + // // Since we already got the PciData, we can close protocol to avoid to carry it // on for multiple exit points. // gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Examine SD PCI Host Controller PCI Configuration table fields. // if ((PciData.Hdr.ClassCode[2] == PCI_CLASS_SYSTEM_PERIPHERAL) && (PciData.Hdr.ClassCode[1] == PCI_SUBCLASS_SD_HOST_CONTROLLER) && - ((PciData.Hdr.ClassCode[0] == 0x00) || (PciData.Hdr.ClassCode[0] == 0x01))) { + ((PciData.Hdr.ClassCode[0] == 0x00) || (PciData.Hdr.ClassCode[0] == 0x01))) + { return EFI_SUCCESS; } @@ -523,24 +535,24 @@ SdMmcPciHcDriverBindingSupported ( EFI_STATUS EFIAPI SdMmcPciHcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - SD_MMC_HC_PRIVATE_DATA *Private; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Supports; - UINT64 PciAttributes; - UINT8 SlotNum; - UINT8 FirstBar; - UINT8 Slot; - UINT8 Index; - CARD_TYPE_DETECT_ROUTINE *Routine; - UINT32 RoutineNum; - BOOLEAN MediaPresent; - BOOLEAN Support64BitDma; + EFI_STATUS Status; + SD_MMC_HC_PRIVATE_DATA *Private; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Supports; + UINT64 PciAttributes; + UINT8 SlotNum; + UINT8 FirstBar; + UINT8 Slot; + UINT8 Index; + CARD_TYPE_DETECT_ROUTINE *Routine; + UINT32 RoutineNum; + BOOLEAN MediaPresent; + BOOLEAN Support64BitDma; DEBUG ((DEBUG_INFO, "SdMmcPciHcDriverBindingStart: Start\n")); @@ -552,7 +564,7 @@ SdMmcPciHcDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -620,11 +632,17 @@ SdMmcPciHcDriverBindingStart ( // implementations. // if (mOverride == NULL) { - Status = gBS->LocateProtocol (&gEdkiiSdMmcOverrideProtocolGuid, NULL, - (VOID **)&mOverride); + Status = gBS->LocateProtocol ( + &gEdkiiSdMmcOverrideProtocolGuid, + NULL, + (VOID **)&mOverride + ); if (!EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "%a: found SD/MMC override protocol\n", - __FUNCTION__)); + DEBUG (( + DEBUG_INFO, + "%a: found SD/MMC override protocol\n", + __FUNCTION__ + )); } } @@ -655,8 +673,12 @@ SdMmcPciHcDriverBindingStart ( &Private->BaseClkFreq[Slot] ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, "%a: Failed to override capability - %r\n", - __FUNCTION__, Status)); + DEBUG (( + DEBUG_WARN, + "%a: Failed to override capability - %r\n", + __FUNCTION__, + Status + )); continue; } } @@ -666,7 +688,7 @@ SdMmcPciHcDriverBindingStart ( Controller, Slot, EdkiiSdMmcGetOperatingParam, - (VOID*)&Private->Slot[Slot].OperatingParameters + (VOID *)&Private->Slot[Slot].OperatingParameters ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "%a: Failed to get operating parameters, using defaults\n", __FUNCTION__)); @@ -686,12 +708,13 @@ SdMmcPciHcDriverBindingStart ( // If any of the slots does not support 64b system bus // do not enable 64b DMA in the PCI layer. // - if ((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_300 && - Private->Capability[Slot].SysBus64V3 == 0) || - (Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_400 && - Private->Capability[Slot].SysBus64V3 == 0) || - (Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410 && - Private->Capability[Slot].SysBus64V4 == 0)) { + if (((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_300) && + (Private->Capability[Slot].SysBus64V3 == 0)) || + ((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_400) && + (Private->Capability[Slot].SysBus64V3 == 0)) || + ((Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410) && + (Private->Capability[Slot].SysBus64V4 == 0))) + { Support64BitDma = FALSE; } @@ -713,6 +736,7 @@ SdMmcPciHcDriverBindingStart ( if (EFI_ERROR (Status)) { continue; } + // // Check whether there is a SD/MMC card attached // @@ -737,16 +761,17 @@ SdMmcPciHcDriverBindingStart ( Private->Slot[Slot].MediaPresent = TRUE; Private->Slot[Slot].Initialized = TRUE; - RoutineNum = sizeof (mCardTypeDetectRoutineTable) / sizeof (CARD_TYPE_DETECT_ROUTINE); + RoutineNum = sizeof (mCardTypeDetectRoutineTable) / sizeof (CARD_TYPE_DETECT_ROUTINE); for (Index = 0; Index < RoutineNum; Index++) { Routine = &mCardTypeDetectRoutineTable[Index]; if (*Routine != NULL) { - Status = (*Routine) (Private, Slot); + Status = (*Routine)(Private, Slot); if (!EFI_ERROR (Status)) { break; } } } + // // This card doesn't get initialized correctly. // @@ -831,12 +856,13 @@ Done: NULL ); } + gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); if ((Private != NULL) && (Private->TimerEvent != NULL)) { gBS->CloseEvent (Private->TimerEvent); @@ -883,26 +909,26 @@ Done: EFI_STATUS EFIAPI SdMmcPciHcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - SD_MMC_HC_PRIVATE_DATA *Private; - EFI_PCI_IO_PROTOCOL *PciIo; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - SD_MMC_HC_TRB *Trb; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + SD_MMC_HC_PRIVATE_DATA *Private; + EFI_PCI_IO_PROTOCOL *PciIo; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + SD_MMC_HC_TRB *Trb; DEBUG ((DEBUG_INFO, "SdMmcPciHcDriverBindingStop: Start\n")); Status = gBS->OpenProtocol ( Controller, &gEfiSdMmcPassThruProtocolGuid, - (VOID**) &PassThru, + (VOID **)&PassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -919,20 +945,23 @@ SdMmcPciHcDriverBindingStop ( gBS->CloseEvent (Private->TimerEvent); Private->TimerEvent = NULL; } + if (Private->ConnectEvent != NULL) { gBS->CloseEvent (Private->ConnectEvent); Private->ConnectEvent = NULL; } + // // As the timer is closed, there is no needs to use TPL lock to // protect the critical region "queue". // for (Link = GetFirstNode (&Private->Queue); !IsNull (&Private->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Private->Queue, Link); RemoveEntryList (Link); - Trb = SD_MMC_HC_TRB_FROM_THIS (Link); + Trb = SD_MMC_HC_TRB_FROM_THIS (Link); Trb->Packet->TransactionStatus = EFI_ABORTED; gBS->SignalEvent (Trb->Event); SdMmcFreeTrb (Trb); @@ -1003,6 +1032,7 @@ SdMmcPassThruExecSyncTrb ( gBS->RestoreTPL (OldTpl); break; } + gBS->RestoreTPL (OldTpl); } @@ -1068,15 +1098,15 @@ SdMmcPassThruExecSyncTrb ( EFI_STATUS EFIAPI SdMmcPassThruPassThru ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot, - IN OUT EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot, + IN OUT EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { - EFI_STATUS Status; - SD_MMC_HC_PRIVATE_DATA *Private; - SD_MMC_HC_TRB *Trb; + EFI_STATUS Status; + SD_MMC_HC_PRIVATE_DATA *Private; + SD_MMC_HC_TRB *Trb; if ((This == NULL) || (Packet == NULL)) { return EFI_INVALID_PARAMETER; @@ -1112,6 +1142,7 @@ SdMmcPassThruPassThru ( if (Trb == NULL) { return EFI_OUT_OF_RESOURCES; } + // // Immediately return for async I/O. // @@ -1158,12 +1189,12 @@ SdMmcPassThruPassThru ( EFI_STATUS EFIAPI SdMmcPassThruGetNextSlot ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 *Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 *Slot ) { - SD_MMC_HC_PRIVATE_DATA *Private; - UINT8 Index; + SD_MMC_HC_PRIVATE_DATA *Private; + UINT8 Index; if ((This == NULL) || (Slot == NULL)) { return EFI_INVALID_PARAMETER; @@ -1174,20 +1205,22 @@ SdMmcPassThruGetNextSlot ( if (*Slot == 0xFF) { for (Index = 0; Index < SD_MMC_HC_MAX_SLOT; Index++) { if (Private->Slot[Index].Enable) { - *Slot = Index; + *Slot = Index; Private->PreviousSlot = Index; return EFI_SUCCESS; } } + return EFI_NOT_FOUND; } else if (*Slot == Private->PreviousSlot) { for (Index = *Slot + 1; Index < SD_MMC_HC_MAX_SLOT; Index++) { if (Private->Slot[Index].Enable) { - *Slot = Index; + *Slot = Index; Private->PreviousSlot = Index; return EFI_SUCCESS; } } + return EFI_NOT_FOUND; } else { return EFI_INVALID_PARAMETER; @@ -1231,14 +1264,14 @@ SdMmcPassThruGetNextSlot ( EFI_STATUS EFIAPI SdMmcPassThruBuildDevicePath ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - SD_MMC_HC_PRIVATE_DATA *Private; - SD_DEVICE_PATH *SdNode; - EMMC_DEVICE_PATH *EmmcNode; + SD_MMC_HC_PRIVATE_DATA *Private; + SD_DEVICE_PATH *SdNode; + EMMC_DEVICE_PATH *EmmcNode; if ((This == NULL) || (DevicePath == NULL) || (Slot >= SD_MMC_HC_MAX_SLOT)) { return EFI_INVALID_PARAMETER; @@ -1255,17 +1288,19 @@ SdMmcPassThruBuildDevicePath ( if (SdNode == NULL) { return EFI_OUT_OF_RESOURCES; } + SdNode->SlotNumber = Slot; - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) SdNode; + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)SdNode; } else if (Private->Slot[Slot].CardType == EmmcCardType) { EmmcNode = AllocateCopyPool (sizeof (EMMC_DEVICE_PATH), &mEmmcDpTemplate); if (EmmcNode == NULL) { return EFI_OUT_OF_RESOURCES; } + EmmcNode->SlotNumber = Slot; - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) EmmcNode; + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)EmmcNode; } else { // // Currently we only support SD and EMMC two device nodes. @@ -1300,15 +1335,15 @@ SdMmcPassThruBuildDevicePath ( EFI_STATUS EFIAPI SdMmcPassThruGetSlotNumber ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 *Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 *Slot ) { - SD_MMC_HC_PRIVATE_DATA *Private; - SD_DEVICE_PATH *SdNode; - EMMC_DEVICE_PATH *EmmcNode; - UINT8 SlotNumber; + SD_MMC_HC_PRIVATE_DATA *Private; + SD_DEVICE_PATH *SdNode; + EMMC_DEVICE_PATH *EmmcNode; + UINT8 SlotNumber; if ((This == NULL) || (DevicePath == NULL) || (Slot == NULL)) { return EFI_INVALID_PARAMETER; @@ -1322,16 +1357,17 @@ SdMmcPassThruGetSlotNumber ( if ((DevicePath->Type != MESSAGING_DEVICE_PATH) || ((DevicePath->SubType != MSG_SD_DP) && (DevicePath->SubType != MSG_EMMC_DP)) || - (DevicePathNodeLength(DevicePath) != sizeof(SD_DEVICE_PATH)) || - (DevicePathNodeLength(DevicePath) != sizeof(EMMC_DEVICE_PATH))) { + (DevicePathNodeLength (DevicePath) != sizeof (SD_DEVICE_PATH)) || + (DevicePathNodeLength (DevicePath) != sizeof (EMMC_DEVICE_PATH))) + { return EFI_UNSUPPORTED; } if (DevicePath->SubType == MSG_SD_DP) { - SdNode = (SD_DEVICE_PATH *) DevicePath; + SdNode = (SD_DEVICE_PATH *)DevicePath; SlotNumber = SdNode->SlotNumber; } else { - EmmcNode = (EMMC_DEVICE_PATH *) DevicePath; + EmmcNode = (EMMC_DEVICE_PATH *)DevicePath; SlotNumber = EmmcNode->SlotNumber; } @@ -1373,15 +1409,15 @@ SdMmcPassThruGetSlotNumber ( EFI_STATUS EFIAPI SdMmcPassThruResetDevice ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot ) { - SD_MMC_HC_PRIVATE_DATA *Private; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - SD_MMC_HC_TRB *Trb; - EFI_TPL OldTpl; + SD_MMC_HC_PRIVATE_DATA *Private; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + SD_MMC_HC_TRB *Trb; + EFI_TPL OldTpl; if (This == NULL) { return EFI_INVALID_PARAMETER; @@ -1400,6 +1436,7 @@ SdMmcPassThruResetDevice ( if (!Private->Slot[Slot].Initialized) { return EFI_DEVICE_ERROR; } + // // Free all async I/O requests in the queue // @@ -1407,10 +1444,11 @@ SdMmcPassThruResetDevice ( for (Link = GetFirstNode (&Private->Queue); !IsNull (&Private->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Private->Queue, Link); RemoveEntryList (Link); - Trb = SD_MMC_HC_TRB_FROM_THIS (Link); + Trb = SD_MMC_HC_TRB_FROM_THIS (Link); Trb->Packet->TransactionStatus = EFI_ABORTED; gBS->SignalEvent (Trb->Event); SdMmcFreeTrb (Trb); @@ -1420,4 +1458,3 @@ SdMmcPassThruResetDevice ( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h index fb69aa4baf..85e09cf114 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h @@ -35,11 +35,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "SdMmcPciHci.h" -extern EFI_COMPONENT_NAME_PROTOCOL gSdMmcPciHcComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gSdMmcPciHcComponentName2; -extern EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gSdMmcPciHcComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gSdMmcPciHcComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gSdMmcPciHcDriverBinding; -extern EDKII_SD_MMC_OVERRIDE *mOverride; +extern EDKII_SD_MMC_OVERRIDE *mOverride; #define SD_MMC_HC_PRIVATE_SIGNATURE SIGNATURE_32 ('s', 'd', 't', 'f') @@ -49,18 +49,18 @@ extern EDKII_SD_MMC_OVERRIDE *mOverride; // // Generic time out value, 1 microsecond as unit. // -#define SD_MMC_HC_GENERIC_TIMEOUT 1 * 1000 * 1000 +#define SD_MMC_HC_GENERIC_TIMEOUT 1 * 1000 * 1000 // // SD/MMC async transfer timer interval, set by experience. // The unit is 100us, takes 1ms as interval. // -#define SD_MMC_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS(1) +#define SD_MMC_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS(1) // // SD/MMC removable device enumeration timer interval, set by experience. // The unit is 100us, takes 100ms as interval. // -#define SD_MMC_HC_ENUM_TIMER EFI_TIMER_PERIOD_MILLISECONDS(100) +#define SD_MMC_HC_ENUM_TIMER EFI_TIMER_PERIOD_MILLISECONDS(100) typedef enum { UnknownCardType, @@ -78,97 +78,97 @@ typedef enum { } EFI_SD_MMC_SLOT_TYPE; typedef struct { - BOOLEAN Enable; - EFI_SD_MMC_SLOT_TYPE SlotType; - BOOLEAN MediaPresent; - BOOLEAN Initialized; - SD_MMC_CARD_TYPE CardType; - UINT64 CurrentFreq; - EDKII_SD_MMC_OPERATING_PARAMETERS OperatingParameters; + BOOLEAN Enable; + EFI_SD_MMC_SLOT_TYPE SlotType; + BOOLEAN MediaPresent; + BOOLEAN Initialized; + SD_MMC_CARD_TYPE CardType; + UINT64 CurrentFreq; + EDKII_SD_MMC_OPERATING_PARAMETERS OperatingParameters; } SD_MMC_HC_SLOT; typedef struct { - UINTN Signature; + UINTN Signature; - EFI_HANDLE ControllerHandle; - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_HANDLE ControllerHandle; + EFI_PCI_IO_PROTOCOL *PciIo; - EFI_SD_MMC_PASS_THRU_PROTOCOL PassThru; + EFI_SD_MMC_PASS_THRU_PROTOCOL PassThru; - UINT64 PciAttributes; + UINT64 PciAttributes; // // The field is used to record the previous slot in GetNextSlot(). // - UINT8 PreviousSlot; + UINT8 PreviousSlot; // // For Non-blocking operation. // - EFI_EVENT TimerEvent; + EFI_EVENT TimerEvent; // // For Sd removable device enumeration. // - EFI_EVENT ConnectEvent; - LIST_ENTRY Queue; + EFI_EVENT ConnectEvent; + LIST_ENTRY Queue; - SD_MMC_HC_SLOT Slot[SD_MMC_HC_MAX_SLOT]; - SD_MMC_HC_SLOT_CAP Capability[SD_MMC_HC_MAX_SLOT]; - UINT64 MaxCurrent[SD_MMC_HC_MAX_SLOT]; - UINT16 ControllerVersion[SD_MMC_HC_MAX_SLOT]; + SD_MMC_HC_SLOT Slot[SD_MMC_HC_MAX_SLOT]; + SD_MMC_HC_SLOT_CAP Capability[SD_MMC_HC_MAX_SLOT]; + UINT64 MaxCurrent[SD_MMC_HC_MAX_SLOT]; + UINT16 ControllerVersion[SD_MMC_HC_MAX_SLOT]; // // Some controllers may require to override base clock frequency // value stored in Capabilities Register 1. // - UINT32 BaseClkFreq[SD_MMC_HC_MAX_SLOT]; + UINT32 BaseClkFreq[SD_MMC_HC_MAX_SLOT]; } SD_MMC_HC_PRIVATE_DATA; typedef struct { - SD_MMC_BUS_MODE BusTiming; - UINT8 BusWidth; - UINT32 ClockFreq; - EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; + SD_MMC_BUS_MODE BusTiming; + UINT8 BusWidth; + UINT32 ClockFreq; + EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; } SD_MMC_BUS_SETTINGS; -#define SD_MMC_HC_TRB_SIG SIGNATURE_32 ('T', 'R', 'B', 'T') +#define SD_MMC_HC_TRB_SIG SIGNATURE_32 ('T', 'R', 'B', 'T') -#define SD_MMC_TRB_RETRIES 5 +#define SD_MMC_TRB_RETRIES 5 // // TRB (Transfer Request Block) contains information for the cmd request. // typedef struct { - UINT32 Signature; - LIST_ENTRY TrbList; - - UINT8 Slot; - UINT16 BlockSize; - - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - VOID *Data; - UINT32 DataLen; - BOOLEAN Read; - EFI_PHYSICAL_ADDRESS DataPhy; - VOID *DataMap; - SD_MMC_HC_TRANSFER_MODE Mode; - SD_MMC_HC_ADMA_LENGTH_MODE AdmaLengthMode; - - EFI_EVENT Event; - BOOLEAN Started; - BOOLEAN CommandComplete; - UINT64 Timeout; - UINT32 Retries; - - BOOLEAN PioModeTransferCompleted; - UINT32 PioBlockIndex; - - SD_MMC_HC_ADMA_32_DESC_LINE *Adma32Desc; - SD_MMC_HC_ADMA_64_V3_DESC_LINE *Adma64V3Desc; - SD_MMC_HC_ADMA_64_V4_DESC_LINE *Adma64V4Desc; - EFI_PHYSICAL_ADDRESS AdmaDescPhy; - VOID *AdmaMap; - UINT32 AdmaPages; - - SD_MMC_HC_PRIVATE_DATA *Private; + UINT32 Signature; + LIST_ENTRY TrbList; + + UINT8 Slot; + UINT16 BlockSize; + + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + VOID *Data; + UINT32 DataLen; + BOOLEAN Read; + EFI_PHYSICAL_ADDRESS DataPhy; + VOID *DataMap; + SD_MMC_HC_TRANSFER_MODE Mode; + SD_MMC_HC_ADMA_LENGTH_MODE AdmaLengthMode; + + EFI_EVENT Event; + BOOLEAN Started; + BOOLEAN CommandComplete; + UINT64 Timeout; + UINT32 Retries; + + BOOLEAN PioModeTransferCompleted; + UINT32 PioBlockIndex; + + SD_MMC_HC_ADMA_32_DESC_LINE *Adma32Desc; + SD_MMC_HC_ADMA_64_V3_DESC_LINE *Adma64V3Desc; + SD_MMC_HC_ADMA_64_V4_DESC_LINE *Adma64V4Desc; + EFI_PHYSICAL_ADDRESS AdmaDescPhy; + VOID *AdmaMap; + UINT32 AdmaPages; + + SD_MMC_HC_PRIVATE_DATA *Private; } SD_MMC_HC_TRB; #define SD_MMC_HC_TRB_FROM_THIS(a) \ @@ -178,22 +178,23 @@ typedef struct { // Task for Non-blocking mode. // typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - - UINT8 Slot; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - BOOLEAN IsStart; - EFI_EVENT Event; - UINT64 RetryTimes; - BOOLEAN InfiniteWait; - VOID *Map; - VOID *MapAddress; + UINT32 Signature; + LIST_ENTRY Link; + + UINT8 Slot; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + BOOLEAN IsStart; + EFI_EVENT Event; + UINT64 RetryTimes; + BOOLEAN InfiniteWait; + VOID *Map; + VOID *MapAddress; } SD_MMC_HC_QUEUE; // // Prototypes // + /** Execute card identification procedure. @@ -207,8 +208,8 @@ typedef struct { typedef EFI_STATUS (*CARD_TYPE_DETECT_ROUTINE) ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ); /** @@ -251,10 +252,10 @@ EFI_STATUS EFI_STATUS EFIAPI SdMmcPassThruPassThru ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot, - IN OUT EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot, + IN OUT EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ); /** @@ -289,8 +290,8 @@ SdMmcPassThruPassThru ( EFI_STATUS EFIAPI SdMmcPassThruGetNextSlot ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 *Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 *Slot ); /** @@ -330,9 +331,9 @@ SdMmcPassThruGetNextSlot ( EFI_STATUS EFIAPI SdMmcPassThruBuildDevicePath ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -359,9 +360,9 @@ SdMmcPassThruBuildDevicePath ( EFI_STATUS EFIAPI SdMmcPassThruGetSlotNumber ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 *Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 *Slot ); /** @@ -390,13 +391,14 @@ SdMmcPassThruGetSlotNumber ( EFI_STATUS EFIAPI SdMmcPassThruResetDevice ( - IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, - IN UINT8 Slot + IN EFI_SD_MMC_PASS_THRU_PROTOCOL *This, + IN UINT8 Slot ); // // Driver model protocol interfaces // + /** Tests to see if this driver supports a given controller. If a child device is provided, it further tests to see if this driver supports creating a handle for the specified child device. @@ -442,9 +444,9 @@ SdMmcPassThruResetDevice ( EFI_STATUS EFIAPI SdMmcPciHcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -485,9 +487,9 @@ SdMmcPciHcDriverBindingSupported ( EFI_STATUS EFIAPI SdMmcPciHcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -519,15 +521,16 @@ SdMmcPciHcDriverBindingStart ( EFI_STATUS EFIAPI SdMmcPciHcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -570,9 +573,9 @@ SdMmcPciHcDriverBindingStop ( EFI_STATUS EFIAPI SdMmcPciHcComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ); /** @@ -646,11 +649,11 @@ SdMmcPciHcComponentNameGetDriverName ( EFI_STATUS EFIAPI SdMmcPciHcComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -668,10 +671,10 @@ SdMmcPciHcComponentNameGetControllerName ( **/ SD_MMC_HC_TRB * SdMmcCreateTrb ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot, - IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot, + IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event ); /** @@ -682,7 +685,7 @@ SdMmcCreateTrb ( **/ VOID SdMmcFreeTrb ( - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_TRB *Trb ); /** @@ -698,8 +701,8 @@ SdMmcFreeTrb ( **/ EFI_STATUS SdMmcCheckTrbEnv ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ); /** @@ -715,8 +718,8 @@ SdMmcCheckTrbEnv ( **/ EFI_STATUS SdMmcWaitTrbEnv ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ); /** @@ -731,8 +734,8 @@ SdMmcWaitTrbEnv ( **/ EFI_STATUS SdMmcExecTrb ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ); /** @@ -748,8 +751,8 @@ SdMmcExecTrb ( **/ EFI_STATUS SdMmcCheckTrbResult ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ); /** @@ -764,8 +767,8 @@ SdMmcCheckTrbResult ( **/ EFI_STATUS SdMmcWaitTrbResult ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ); /** @@ -782,8 +785,8 @@ SdMmcWaitTrbResult ( **/ EFI_STATUS EmmcIdentification ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ); /** @@ -800,8 +803,8 @@ EmmcIdentification ( **/ EFI_STATUS SdCardIdentification ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ); /** @@ -840,8 +843,8 @@ SdMmcHcClockSupply ( **/ EFI_STATUS SdMmcHcReset ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ); /** @@ -857,8 +860,8 @@ SdMmcHcReset ( **/ EFI_STATUS SdMmcHcInitHost ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ); #endif diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index 6548ef71de..53b63ab52b 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -23,8 +23,8 @@ **/ VOID DumpCapabilityReg ( - IN UINT8 Slot, - IN SD_MMC_HC_SLOT_CAP *Capability + IN UINT8 Slot, + IN SD_MMC_HC_SLOT_CAP *Capability ) { // @@ -55,6 +55,7 @@ DumpCapabilityReg ( } else { DEBUG ((DEBUG_INFO, "%a\n", "Reserved")); } + DEBUG ((DEBUG_INFO, " SDR50 Support %a\n", Capability->Sdr50 ? "TRUE" : "FALSE")); DEBUG ((DEBUG_INFO, " SDR104 Support %a\n", Capability->Sdr104 ? "TRUE" : "FALSE")); DEBUG ((DEBUG_INFO, " DDR50 Support %a\n", Capability->Ddr50 ? "TRUE" : "FALSE")); @@ -67,6 +68,7 @@ DumpCapabilityReg ( } else { DEBUG ((DEBUG_INFO, " Retuning TimerCnt %dseconds\n", 2 * (Capability->TimerCount - 1))); } + DEBUG ((DEBUG_INFO, " SDR50 Tuning %a\n", Capability->TuningSDR50 ? "TRUE" : "FALSE")); DEBUG ((DEBUG_INFO, " Retuning Mode Mode %d\n", Capability->RetuningMod + 1)); DEBUG ((DEBUG_INFO, " Clock Multiplier M = %d\n", Capability->ClkMultiplier + 1)); @@ -88,13 +90,13 @@ DumpCapabilityReg ( EFI_STATUS EFIAPI SdMmcHcGetSlotInfo ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - OUT UINT8 *FirstBar, - OUT UINT8 *SlotNum + IN EFI_PCI_IO_PROTOCOL *PciIo, + OUT UINT8 *FirstBar, + OUT UINT8 *SlotNum ) { - EFI_STATUS Status; - SD_MMC_HC_SLOT_INFO SlotInfo; + EFI_STATUS Status; + SD_MMC_HC_SLOT_INFO SlotInfo; Status = PciIo->Pci.Read ( PciIo, @@ -139,18 +141,18 @@ SdMmcHcGetSlotInfo ( EFI_STATUS EFIAPI SdMmcHcRwMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN BOOLEAN Read, - IN UINT8 Count, - IN OUT VOID *Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN BOOLEAN Read, + IN UINT8 Count, + IN OUT VOID *Data ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL_WIDTH Width; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL_WIDTH Width; - if ((PciIo == NULL) || (Data == NULL)) { + if ((PciIo == NULL) || (Data == NULL)) { return EFI_INVALID_PARAMETER; } @@ -179,7 +181,7 @@ SdMmcHcRwMmio ( PciIo, Width, BarIndex, - (UINT64) Offset, + (UINT64)Offset, Count, Data ); @@ -188,7 +190,7 @@ SdMmcHcRwMmio ( PciIo, Width, BarIndex, - (UINT64) Offset, + (UINT64)Offset, Count, Data ); @@ -221,16 +223,16 @@ SdMmcHcRwMmio ( EFI_STATUS EFIAPI SdMmcHcOrMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN VOID *OrData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN VOID *OrData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 Or; + EFI_STATUS Status; + UINT64 Data; + UINT64 Or; Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -238,13 +240,13 @@ SdMmcHcOrMmio ( } if (Count == 1) { - Or = *(UINT8*) OrData; + Or = *(UINT8 *)OrData; } else if (Count == 2) { - Or = *(UINT16*) OrData; + Or = *(UINT16 *)OrData; } else if (Count == 4) { - Or = *(UINT32*) OrData; + Or = *(UINT32 *)OrData; } else if (Count == 8) { - Or = *(UINT64*) OrData; + Or = *(UINT64 *)OrData; } else { return EFI_INVALID_PARAMETER; } @@ -279,16 +281,16 @@ SdMmcHcOrMmio ( EFI_STATUS EFIAPI SdMmcHcAndMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN VOID *AndData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN VOID *AndData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 And; + EFI_STATUS Status; + UINT64 Data; + UINT64 And; Status = SdMmcHcRwMmio (PciIo, BarIndex, Offset, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -296,13 +298,13 @@ SdMmcHcAndMmio ( } if (Count == 1) { - And = *(UINT8*) AndData; + And = *(UINT8 *)AndData; } else if (Count == 2) { - And = *(UINT16*) AndData; + And = *(UINT16 *)AndData; } else if (Count == 4) { - And = *(UINT32*) AndData; + And = *(UINT32 *)AndData; } else if (Count == 8) { - And = *(UINT64*) AndData; + And = *(UINT64 *)AndData; } else { return EFI_INVALID_PARAMETER; } @@ -335,16 +337,16 @@ SdMmcHcAndMmio ( EFI_STATUS EFIAPI SdMmcHcCheckMmioSet ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue ) { - EFI_STATUS Status; - UINT64 Value; + EFI_STATUS Status; + UINT64 Value; // // Access PCI MMIO space to see if the value is the tested one. @@ -389,17 +391,17 @@ SdMmcHcCheckMmioSet ( EFI_STATUS EFIAPI SdMmcHcWaitMmioSet ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue, + IN UINT64 Timeout ) { - EFI_STATUS Status; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -449,7 +451,7 @@ SdMmcHcGetControllerVersion ( OUT UINT16 *Version ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CTRL_VER, TRUE, sizeof (UINT16), Version); if (EFI_ERROR (Status)) { @@ -473,28 +475,32 @@ SdMmcHcGetControllerVersion ( **/ EFI_STATUS SdMmcHcReset ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - EFI_STATUS Status; - UINT8 SwReset; - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT8 SwReset; + EFI_PCI_IO_PROTOCOL *PciIo; // // Notify the SD/MMC override protocol that we are about to reset // the SD/MMC host controller. // - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { + if ((mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( Private->ControllerHandle, Slot, EdkiiSdMmcResetPre, - NULL); + NULL + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: SD/MMC pre reset notifier callback failed - %r\n", - __FUNCTION__, Status)); + __FUNCTION__, + Status + )); return Status; } } @@ -527,8 +533,11 @@ SdMmcHcReset ( // Status = SdMmcHcEnableInterrupt (PciIo, Slot); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "SdMmcHcReset: SdMmcHcEnableInterrupt done with %r\n", - Status)); + DEBUG (( + DEBUG_INFO, + "SdMmcHcReset: SdMmcHcEnableInterrupt done with %r\n", + Status + )); return Status; } @@ -536,16 +545,20 @@ SdMmcHcReset ( // Notify the SD/MMC override protocol that we have just reset // the SD/MMC host controller. // - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { + if ((mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( Private->ControllerHandle, Slot, EdkiiSdMmcResetPost, - NULL); + NULL + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: SD/MMC post reset notifier callback failed - %r\n", - __FUNCTION__, Status)); + __FUNCTION__, + Status + )); } } @@ -565,26 +578,27 @@ SdMmcHcReset ( **/ EFI_STATUS SdMmcHcEnableInterrupt ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ) { - EFI_STATUS Status; - UINT16 IntStatus; + EFI_STATUS Status; + UINT16 IntStatus; // // Enable all bits in Error Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); if (EFI_ERROR (Status)) { return Status; } + // // Enable all bits in Normal Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); return Status; } @@ -604,11 +618,11 @@ EFI_STATUS SdMmcHcGetCapability ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN UINT8 Slot, - OUT SD_MMC_HC_SLOT_CAP *Capability + OUT SD_MMC_HC_SLOT_CAP *Capability ) { - EFI_STATUS Status; - UINT64 Cap; + EFI_STATUS Status; + UINT64 Cap; Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CAP, TRUE, sizeof (Cap), &Cap); if (EFI_ERROR (Status)) { @@ -635,10 +649,10 @@ EFI_STATUS SdMmcHcGetMaxCurrent ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN UINT8 Slot, - OUT UINT64 *MaxCurrent + OUT UINT64 *MaxCurrent ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_MAX_CURRENT_CAP, TRUE, sizeof (UINT64), MaxCurrent); @@ -662,14 +676,14 @@ SdMmcHcGetMaxCurrent ( **/ EFI_STATUS SdMmcHcCardDetect ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - OUT BOOLEAN *MediaPresent + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + OUT BOOLEAN *MediaPresent ) { - EFI_STATUS Status; - UINT16 Data; - UINT32 PresentState; + EFI_STATUS Status; + UINT16 Data; + UINT32 PresentState; // // Check Present State Register to see if there is a card presented. @@ -723,13 +737,13 @@ SdMmcHcCardDetect ( **/ EFI_STATUS SdMmcHcStopClock ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ) { - EFI_STATUS Status; - UINT32 PresentState; - UINT16 ClockCtrl; + EFI_STATUS Status; + UINT32 PresentState; + UINT16 ClockCtrl; // // Ensure no SD transactions are occurring on the SD Bus by @@ -752,8 +766,8 @@ SdMmcHcStopClock ( // // Set SD Clock Enable in the Clock Control register to 0 // - ClockCtrl = (UINT16)~BIT2; - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + ClockCtrl = (UINT16) ~BIT2; + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); return Status; } @@ -773,7 +787,7 @@ SdMmcHcStartSdClock ( IN UINT8 Slot ) { - UINT16 ClockCtrl; + UINT16 ClockCtrl; // // Set SD Clock Enable in the Clock Control register to 1 @@ -806,20 +820,20 @@ SdMmcHcClockSupply ( IN UINT64 ClockFreq ) { - EFI_STATUS Status; - UINT32 SettingFreq; - UINT32 Divisor; - UINT32 Remainder; - UINT16 ClockCtrl; - UINT32 BaseClkFreq; - UINT16 ControllerVer; - EFI_PCI_IO_PROTOCOL *PciIo; - - PciIo = Private->PciIo; - BaseClkFreq = Private->BaseClkFreq[Slot]; + EFI_STATUS Status; + UINT32 SettingFreq; + UINT32 Divisor; + UINT32 Remainder; + UINT16 ClockCtrl; + UINT32 BaseClkFreq; + UINT16 ControllerVer; + EFI_PCI_IO_PROTOCOL *PciIo; + + PciIo = Private->PciIo; + BaseClkFreq = Private->BaseClkFreq[Slot]; ControllerVer = Private->ControllerVersion[Slot]; - if (BaseClkFreq == 0 || ClockFreq == 0) { + if ((BaseClkFreq == 0) || (ClockFreq == 0)) { return EFI_INVALID_PARAMETER; } @@ -840,8 +854,9 @@ SdMmcHcClockSupply ( if ((ClockFreq == SettingFreq) && (Remainder == 0)) { break; } + if ((ClockFreq == SettingFreq) && (Remainder != 0)) { - SettingFreq ++; + SettingFreq++; } } @@ -851,17 +866,20 @@ SdMmcHcClockSupply ( // Set SDCLK Frequency Select and Internal Clock Enable fields in Clock Control register. // if ((ControllerVer >= SD_MMC_HC_CTRL_VER_300) && - (ControllerVer <= SD_MMC_HC_CTRL_VER_420)) { + (ControllerVer <= SD_MMC_HC_CTRL_VER_420)) + { ASSERT (Divisor <= 0x3FF); ClockCtrl = ((Divisor & 0xFF) << 8) | ((Divisor & 0x300) >> 2); } else if ((ControllerVer == SD_MMC_HC_CTRL_VER_100) || - (ControllerVer == SD_MMC_HC_CTRL_VER_200)) { + (ControllerVer == SD_MMC_HC_CTRL_VER_200)) + { // // Only the most significant bit can be used as divisor. // if (((Divisor - 1) & Divisor) != 0) { Divisor = 1 << (HighBitSet32 (Divisor) + 1); } + ASSERT (Divisor <= 0x80); ClockCtrl = (Divisor & 0xFF) << 8; } else { @@ -881,7 +899,7 @@ SdMmcHcClockSupply ( // Supply clock frequency with specified divisor // ClockCtrl |= BIT0; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Set SDCLK Frequency Select and Internal Clock Enable fields fails\n")); return Status; @@ -913,7 +931,7 @@ SdMmcHcClockSupply ( // legacy behavior. During first time setup we also don't know what type // of the card slot it is and which enum value of BusTiming applies. // - if (!FirstTimeSetup && mOverride != NULL && mOverride->NotifyPhase != NULL) { + if (!FirstTimeSetup && (mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( Private->ControllerHandle, Slot, @@ -951,18 +969,18 @@ SdMmcHcClockSupply ( **/ EFI_STATUS SdMmcHcPowerControl ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT8 PowerCtrl + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN UINT8 PowerCtrl ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Clr SD Bus Power // - PowerCtrl &= (UINT8)~BIT0; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + PowerCtrl &= (UINT8) ~BIT0; + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); if (EFI_ERROR (Status)) { return Status; } @@ -971,7 +989,7 @@ SdMmcHcPowerControl ( // Set SD Bus Voltage Select and SD Bus Power fields in Power Control Register // PowerCtrl |= BIT0; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); return Status; } @@ -991,33 +1009,35 @@ SdMmcHcPowerControl ( **/ EFI_STATUS SdMmcHcSetBusWidth ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT16 BusWidth + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN UINT16 BusWidth ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (BusWidth == 1) { - HostCtrl1 = (UINT8)~(BIT5 | BIT1); - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 = (UINT8) ~(BIT5 | BIT1); + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 4) { Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } + HostCtrl1 |= BIT1; - HostCtrl1 &= (UINT8)~BIT5; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 &= (UINT8) ~BIT5; + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 8) { Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } - HostCtrl1 &= (UINT8)~BIT1; + + HostCtrl1 &= (UINT8) ~BIT1; HostCtrl1 |= BIT5; - Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else { ASSERT (FALSE); return EFI_INVALID_PARAMETER; @@ -1039,14 +1059,14 @@ SdMmcHcSetBusWidth ( **/ EFI_STATUS SdMmcHcInitV4Enhancements ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN SD_MMC_HC_SLOT_CAP Capability, - IN UINT16 ControllerVer + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN SD_MMC_HC_SLOT_CAP Capability, + IN UINT16 ControllerVer ) { - EFI_STATUS Status; - UINT16 HostCtrl2; + EFI_STATUS Status; + UINT16 HostCtrl2; // // Check if controller version V4 or higher @@ -1076,9 +1096,11 @@ SdMmcHcInitV4Enhancements ( HostCtrl2 |= SD_MMC_HC_64_ADDR_EN; DEBUG ((DEBUG_INFO, "Enabled V4 64 bit system bus support\n")); } + HostCtrl2 |= SD_MMC_HC_26_DATA_LEN_ADMA_EN; DEBUG ((DEBUG_INFO, "Enabled V4 26 bit data length ADMA support\n")); } + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; @@ -1103,14 +1125,14 @@ SdMmcHcInitV4Enhancements ( **/ EFI_STATUS SdMmcHcInitPowerVoltage ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN SD_MMC_HC_SLOT_CAP Capability + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN SD_MMC_HC_SLOT_CAP Capability ) { - EFI_STATUS Status; - UINT8 MaxVoltage; - UINT8 HostCtrl2; + EFI_STATUS Status; + UINT8 MaxVoltage; + UINT8 HostCtrl2; // // Calculate supported maximum voltage according to SD Bus Voltage Select @@ -1131,7 +1153,7 @@ SdMmcHcInitPowerVoltage ( // MaxVoltage = 0x0A; HostCtrl2 = BIT3; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); gBS->Stall (5000); if (EFI_ERROR (Status)) { return Status; @@ -1163,12 +1185,12 @@ SdMmcHcInitPowerVoltage ( **/ EFI_STATUS SdMmcHcInitTimeoutCtrl ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ) { - EFI_STATUS Status; - UINT8 Timeout; + EFI_STATUS Status; + UINT8 Timeout; Timeout = 0x0E; Status = SdMmcHcRwMmio (PciIo, Slot, SD_MMC_HC_TIMEOUT_CTRL, FALSE, sizeof (Timeout), &Timeout); @@ -1189,33 +1211,37 @@ SdMmcHcInitTimeoutCtrl ( **/ EFI_STATUS SdMmcHcInitHost ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - SD_MMC_HC_SLOT_CAP Capability; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + SD_MMC_HC_SLOT_CAP Capability; // // Notify the SD/MMC override protocol that we are about to initialize // the SD/MMC host controller. // - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { + if ((mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( Private->ControllerHandle, Slot, EdkiiSdMmcInitHostPre, - NULL); + NULL + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: SD/MMC pre init notifier callback failed - %r\n", - __FUNCTION__, Status)); + __FUNCTION__, + Status + )); return Status; } } - PciIo = Private->PciIo; + PciIo = Private->PciIo; Capability = Private->Capability[Slot]; Status = SdMmcHcInitV4Enhancements (PciIo, Slot, Capability, Private->ControllerVersion[Slot]); @@ -1249,18 +1275,23 @@ SdMmcHcInitHost ( // Notify the SD/MMC override protocol that we are have just initialized // the SD/MMC host controller. // - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { + if ((mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( Private->ControllerHandle, Slot, EdkiiSdMmcInitHostPost, - NULL); + NULL + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: SD/MMC post init notifier callback failed - %r\n", - __FUNCTION__, Status)); + __FUNCTION__, + Status + )); } } + return Status; } @@ -1277,17 +1308,17 @@ SdMmcHcInitHost ( **/ EFI_STATUS SdMmcHcUhsSignaling ( - IN EFI_HANDLE ControllerHandle, - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN SD_MMC_BUS_MODE Timing + IN EFI_HANDLE ControllerHandle, + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN SD_MMC_BUS_MODE Timing ) { - EFI_STATUS Status; - UINT8 HostCtrl2; + EFI_STATUS Status; + UINT8 HostCtrl2; - HostCtrl2 = (UINT8)~SD_MMC_HC_CTRL_UHS_MASK; - Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~SD_MMC_HC_CTRL_UHS_MASK; + Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } @@ -1324,15 +1355,16 @@ SdMmcHcUhsSignaling ( HostCtrl2 = SD_MMC_HC_CTRL_MMC_HS400; break; default: - HostCtrl2 = 0; - break; + HostCtrl2 = 0; + break; } + Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { + if ((mOverride != NULL) && (mOverride->NotifyPhase != NULL)) { Status = mOverride->NotifyPhase ( ControllerHandle, Slot, @@ -1377,8 +1409,8 @@ SdMmcSetDriverStrength ( return EFI_SUCCESS; } - HostCtrl2 = (UINT16)~SD_MMC_HC_CTRL_DRIVER_STRENGTH_MASK; - Status = SdMmcHcAndMmio (PciIo, SlotIndex, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT16) ~SD_MMC_HC_CTRL_DRIVER_STRENGTH_MASK; + Status = SdMmcHcAndMmio (PciIo, SlotIndex, SD_MMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } @@ -1400,19 +1432,19 @@ SdMmcSetDriverStrength ( **/ EFI_STATUS SdMmcHcLedOnOff ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN BOOLEAN On + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN BOOLEAN On ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (On) { HostCtrl1 = BIT0; Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else { - HostCtrl1 = (UINT8)~BIT0; + HostCtrl1 = (UINT8) ~BIT0; Status = SdMmcHcAndMmio (PciIo, Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } @@ -1433,23 +1465,23 @@ SdMmcHcLedOnOff ( **/ EFI_STATUS BuildAdmaDescTable ( - IN SD_MMC_HC_TRB *Trb, - IN UINT16 ControllerVer + IN SD_MMC_HC_TRB *Trb, + IN UINT16 ControllerVer ) { - EFI_PHYSICAL_ADDRESS Data; - UINT64 DataLen; - UINT64 Entries; - UINT32 Index; - UINT64 Remaining; - UINT64 Address; - UINTN TableSize; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINTN Bytes; - UINT32 AdmaMaxDataPerLine; - UINT32 DescSize; - VOID *AdmaDesc; + EFI_PHYSICAL_ADDRESS Data; + UINT64 DataLen; + UINT64 Entries; + UINT32 Index; + UINT64 Remaining; + UINT64 Address; + UINTN TableSize; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINTN Bytes; + UINT32 AdmaMaxDataPerLine; + UINT32 DescSize; + VOID *AdmaDesc; AdmaMaxDataPerLine = ADMA_MAX_DATA_PER_LINE_16B; DescSize = sizeof (SD_MMC_HC_ADMA_32_DESC_LINE); @@ -1463,9 +1495,11 @@ BuildAdmaDescTable ( // Check for valid ranges in 32bit ADMA Descriptor Table // if ((Trb->Mode == SdMmcAdma32bMode) && - ((Data >= 0x100000000ul) || ((Data + DataLen) > 0x100000000ul))) { + ((Data >= 0x100000000ul) || ((Data + DataLen) > 0x100000000ul))) + { return EFI_INVALID_PARAMETER; } + // // Check address field alignment // @@ -1490,9 +1524,10 @@ BuildAdmaDescTable ( // if (Trb->Mode == SdMmcAdma64bV3Mode) { DescSize = sizeof (SD_MMC_HC_ADMA_64_V3_DESC_LINE); - }else if (Trb->Mode == SdMmcAdma64bV4Mode) { + } else if (Trb->Mode == SdMmcAdma64bV4Mode) { DescSize = sizeof (SD_MMC_HC_ADMA_64_V4_DESC_LINE); } + // // Configure 26b data length. // @@ -1500,20 +1535,21 @@ BuildAdmaDescTable ( AdmaMaxDataPerLine = ADMA_MAX_DATA_PER_LINE_26B; } - Entries = DivU64x32 ((DataLen + AdmaMaxDataPerLine - 1), AdmaMaxDataPerLine); - TableSize = (UINTN)MultU64x32 (Entries, DescSize); + Entries = DivU64x32 ((DataLen + AdmaMaxDataPerLine - 1), AdmaMaxDataPerLine); + TableSize = (UINTN)MultU64x32 (Entries, DescSize); Trb->AdmaPages = (UINT32)EFI_SIZE_TO_PAGES (TableSize); - Status = PciIo->AllocateBuffer ( - PciIo, - AllocateAnyPages, - EfiBootServicesData, - EFI_SIZE_TO_PAGES (TableSize), - (VOID **)&AdmaDesc, - 0 - ); + Status = PciIo->AllocateBuffer ( + PciIo, + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES (TableSize), + (VOID **)&AdmaDesc, + 0 + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + ZeroMem (AdmaDesc, TableSize); Bytes = TableSize; Status = PciIo->Map ( @@ -1538,21 +1574,22 @@ BuildAdmaDescTable ( } if ((Trb->Mode == SdMmcAdma32bMode) && - (UINT64)(UINTN)Trb->AdmaDescPhy > 0x100000000ul) { + ((UINT64)(UINTN)Trb->AdmaDescPhy > 0x100000000ul)) + { // // The ADMA doesn't support 64bit addressing. // PciIo->Unmap ( - PciIo, - Trb->AdmaMap - ); + PciIo, + Trb->AdmaMap + ); Trb->AdmaMap = NULL; PciIo->FreeBuffer ( - PciIo, - EFI_SIZE_TO_PAGES (TableSize), - AdmaDesc - ); + PciIo, + EFI_SIZE_TO_PAGES (TableSize), + AdmaDesc + ); return EFI_DEVICE_ERROR; } @@ -1574,25 +1611,28 @@ BuildAdmaDescTable ( if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { Trb->Adma32Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16); } + Trb->Adma32Desc[Index].LowerLength = (UINT16)(Remaining & MAX_UINT16); - Trb->Adma32Desc[Index].Address = (UINT32)Address; + Trb->Adma32Desc[Index].Address = (UINT32)Address; break; } else { Trb->Adma32Desc[Index].Valid = 1; Trb->Adma32Desc[Index].Act = 2; if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { - Trb->Adma32Desc[Index].UpperLength = 0; + Trb->Adma32Desc[Index].UpperLength = 0; } - Trb->Adma32Desc[Index].LowerLength = 0; - Trb->Adma32Desc[Index].Address = (UINT32)Address; + + Trb->Adma32Desc[Index].LowerLength = 0; + Trb->Adma32Desc[Index].Address = (UINT32)Address; } } else if (Trb->Mode == SdMmcAdma64bV3Mode) { if (Remaining <= AdmaMaxDataPerLine) { Trb->Adma64V3Desc[Index].Valid = 1; Trb->Adma64V3Desc[Index].Act = 2; if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { - Trb->Adma64V3Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16); + Trb->Adma64V3Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16); } + Trb->Adma64V3Desc[Index].LowerLength = (UINT16)(Remaining & MAX_UINT16); Trb->Adma64V3Desc[Index].LowerAddress = (UINT32)Address; Trb->Adma64V3Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32); @@ -1601,8 +1641,9 @@ BuildAdmaDescTable ( Trb->Adma64V3Desc[Index].Valid = 1; Trb->Adma64V3Desc[Index].Act = 2; if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { - Trb->Adma64V3Desc[Index].UpperLength = 0; + Trb->Adma64V3Desc[Index].UpperLength = 0; } + Trb->Adma64V3Desc[Index].LowerLength = 0; Trb->Adma64V3Desc[Index].LowerAddress = (UINT32)Address; Trb->Adma64V3Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32); @@ -1612,8 +1653,9 @@ BuildAdmaDescTable ( Trb->Adma64V4Desc[Index].Valid = 1; Trb->Adma64V4Desc[Index].Act = 2; if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { - Trb->Adma64V4Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16); + Trb->Adma64V4Desc[Index].UpperLength = (UINT16)RShiftU64 (Remaining, 16); } + Trb->Adma64V4Desc[Index].LowerLength = (UINT16)(Remaining & MAX_UINT16); Trb->Adma64V4Desc[Index].LowerAddress = (UINT32)Address; Trb->Adma64V4Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32); @@ -1622,8 +1664,9 @@ BuildAdmaDescTable ( Trb->Adma64V4Desc[Index].Valid = 1; Trb->Adma64V4Desc[Index].Act = 2; if (Trb->AdmaLengthMode == SdMmcAdmaLen26b) { - Trb->Adma64V4Desc[Index].UpperLength = 0; + Trb->Adma64V4Desc[Index].UpperLength = 0; } + Trb->Adma64V4Desc[Index].LowerLength = 0; Trb->Adma64V4Desc[Index].LowerAddress = (UINT32)Address; Trb->Adma64V4Desc[Index].UpperAddress = (UINT32)RShiftU64 (Address, 32); @@ -1644,6 +1687,7 @@ BuildAdmaDescTable ( } else { Trb->Adma64V4Desc[Index].End = 1; } + return EFI_SUCCESS; } @@ -1668,14 +1712,18 @@ SdMmcPrintPacket ( DEBUG ((DebugLevel, "Command index: %d, argument: %X\n", Packet->SdMmcCmdBlk->CommandIndex, Packet->SdMmcCmdBlk->CommandArgument)); DEBUG ((DebugLevel, "Command type: %d, response type: %d\n", Packet->SdMmcCmdBlk->CommandType, Packet->SdMmcCmdBlk->ResponseType)); } + if (Packet->SdMmcStatusBlk != NULL) { - DEBUG ((DebugLevel, "Response 0: %X, 1: %X, 2: %X, 3: %X\n", - Packet->SdMmcStatusBlk->Resp0, - Packet->SdMmcStatusBlk->Resp1, - Packet->SdMmcStatusBlk->Resp2, - Packet->SdMmcStatusBlk->Resp3 - )); + DEBUG (( + DebugLevel, + "Response 0: %X, 1: %X, 2: %X, 3: %X\n", + Packet->SdMmcStatusBlk->Resp0, + Packet->SdMmcStatusBlk->Resp1, + Packet->SdMmcStatusBlk->Resp2, + Packet->SdMmcStatusBlk->Resp3 + )); } + DEBUG ((DebugLevel, "Timeout: %ld\n", Packet->Timeout)); DEBUG ((DebugLevel, "InDataBuffer: %p\n", Packet->InDataBuffer)); DEBUG ((DebugLevel, "OutDataBuffer: %p\n", Packet->OutDataBuffer)); @@ -1743,10 +1791,10 @@ SdMmcSetupMemoryForDmaTransfer ( IN SD_MMC_HC_TRB *Trb ) { - EFI_PCI_IO_PROTOCOL_OPERATION Flag; - EFI_PCI_IO_PROTOCOL *PciIo; - UINTN MapLength; - EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL_OPERATION Flag; + EFI_PCI_IO_PROTOCOL *PciIo; + UINTN MapLength; + EFI_STATUS Status; if (Trb->Read) { Flag = EfiPciIoOperationBusMasterWrite; @@ -1755,24 +1803,25 @@ SdMmcSetupMemoryForDmaTransfer ( } PciIo = Private->PciIo; - if (Trb->Data != NULL && Trb->DataLen != 0) { + if ((Trb->Data != NULL) && (Trb->DataLen != 0)) { MapLength = Trb->DataLen; - Status = PciIo->Map ( - PciIo, - Flag, - Trb->Data, - &MapLength, - &Trb->DataPhy, - &Trb->DataMap - ); + Status = PciIo->Map ( + PciIo, + Flag, + Trb->Data, + &MapLength, + &Trb->DataPhy, + &Trb->DataMap + ); if (EFI_ERROR (Status) || (Trb->DataLen != MapLength)) { return EFI_BAD_BUFFER_SIZE; } } - if (Trb->Mode == SdMmcAdma32bMode || - Trb->Mode == SdMmcAdma64bV3Mode || - Trb->Mode == SdMmcAdma64bV4Mode) { + if ((Trb->Mode == SdMmcAdma32bMode) || + (Trb->Mode == SdMmcAdma64bV3Mode) || + (Trb->Mode == SdMmcAdma64bV4Mode)) + { Status = BuildAdmaDescTable (Trb, Private->ControllerVersion[Slot]); if (EFI_ERROR (Status)) { return Status; @@ -1797,33 +1846,33 @@ SdMmcSetupMemoryForDmaTransfer ( **/ SD_MMC_HC_TRB * SdMmcCreateTrb ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN UINT8 Slot, - IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, - IN EFI_EVENT Event + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot, + IN EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet, + IN EFI_EVENT Event ) { - SD_MMC_HC_TRB *Trb; - EFI_STATUS Status; - EFI_TPL OldTpl; + SD_MMC_HC_TRB *Trb; + EFI_STATUS Status; + EFI_TPL OldTpl; Trb = AllocateZeroPool (sizeof (SD_MMC_HC_TRB)); if (Trb == NULL) { return NULL; } - Trb->Signature = SD_MMC_HC_TRB_SIG; - Trb->Slot = Slot; - Trb->BlockSize = 0x200; - Trb->Packet = Packet; - Trb->Event = Event; - Trb->Started = FALSE; - Trb->CommandComplete = FALSE; - Trb->Timeout = Packet->Timeout; - Trb->Retries = SD_MMC_TRB_RETRIES; + Trb->Signature = SD_MMC_HC_TRB_SIG; + Trb->Slot = Slot; + Trb->BlockSize = 0x200; + Trb->Packet = Packet; + Trb->Event = Event; + Trb->Started = FALSE; + Trb->CommandComplete = FALSE; + Trb->Timeout = Packet->Timeout; + Trb->Retries = SD_MMC_TRB_RETRIES; Trb->PioModeTransferCompleted = FALSE; - Trb->PioBlockIndex = 0; - Trb->Private = Private; + Trb->PioBlockIndex = 0; + Trb->Private = Private; if ((Packet->InTransferLength != 0) && (Packet->InDataBuffer != NULL)) { Trb->Data = Packet->InDataBuffer; @@ -1847,33 +1896,38 @@ SdMmcCreateTrb ( if (((Private->Slot[Trb->Slot].CardType == EmmcCardType) && (Packet->SdMmcCmdBlk->CommandIndex == EMMC_SEND_TUNING_BLOCK)) || ((Private->Slot[Trb->Slot].CardType == SdCardType) && - (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) { + (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) + { Trb->Mode = SdMmcPioMode; } else { if (Trb->DataLen == 0) { Trb->Mode = SdMmcNoData; } else if (Private->Capability[Slot].Adma2 != 0) { - Trb->Mode = SdMmcAdma32bMode; + Trb->Mode = SdMmcAdma32bMode; Trb->AdmaLengthMode = SdMmcAdmaLen16b; if ((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_300) && - (Private->Capability[Slot].SysBus64V3 == 1)) { + (Private->Capability[Slot].SysBus64V3 == 1)) + { Trb->Mode = SdMmcAdma64bV3Mode; } else if (((Private->ControllerVersion[Slot] == SD_MMC_HC_CTRL_VER_400) && (Private->Capability[Slot].SysBus64V3 == 1)) || ((Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410) && - (Private->Capability[Slot].SysBus64V4 == 1))) { + (Private->Capability[Slot].SysBus64V4 == 1))) + { Trb->Mode = SdMmcAdma64bV4Mode; } + if (Private->ControllerVersion[Slot] >= SD_MMC_HC_CTRL_VER_410) { Trb->AdmaLengthMode = SdMmcAdmaLen26b; } + Status = SdMmcSetupMemoryForDmaTransfer (Private, Slot, Trb); if (EFI_ERROR (Status)) { goto Error; } } else if (Private->Capability[Slot].Sdma != 0) { Trb->Mode = SdMmcSdmaMode; - Status = SdMmcSetupMemoryForDmaTransfer (Private, Slot, Trb); + Status = SdMmcSetupMemoryForDmaTransfer (Private, Slot, Trb); if (EFI_ERROR (Status)) { goto Error; } @@ -1903,46 +1957,51 @@ Error: **/ VOID SdMmcFreeTrb ( - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_TRB *Trb ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; PciIo = Trb->Private->PciIo; if (Trb->AdmaMap != NULL) { PciIo->Unmap ( - PciIo, - Trb->AdmaMap - ); + PciIo, + Trb->AdmaMap + ); } + if (Trb->Adma32Desc != NULL) { PciIo->FreeBuffer ( - PciIo, - Trb->AdmaPages, - Trb->Adma32Desc - ); + PciIo, + Trb->AdmaPages, + Trb->Adma32Desc + ); } + if (Trb->Adma64V3Desc != NULL) { PciIo->FreeBuffer ( - PciIo, - Trb->AdmaPages, - Trb->Adma64V3Desc - ); + PciIo, + Trb->AdmaPages, + Trb->Adma64V3Desc + ); } + if (Trb->Adma64V4Desc != NULL) { PciIo->FreeBuffer ( - PciIo, - Trb->AdmaPages, - Trb->Adma64V4Desc - ); + PciIo, + Trb->AdmaPages, + Trb->Adma64V4Desc + ); } + if (Trb->DataMap != NULL) { PciIo->Unmap ( - PciIo, - Trb->DataMap - ); + PciIo, + Trb->DataMap + ); } + FreePool (Trb); return; } @@ -1960,20 +2019,21 @@ SdMmcFreeTrb ( **/ EFI_STATUS SdMmcCheckTrbEnv ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT32 PresentState; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT32 PresentState; Packet = Trb->Packet; if ((Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc) || (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR1b) || - (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b)) { + (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b)) + { // // Wait Command Inhibit (CMD) and Command Inhibit (DAT) in // the Present State register to be 0 @@ -2013,14 +2073,14 @@ SdMmcCheckTrbEnv ( **/ EFI_STATUS SdMmcWaitTrbEnv ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; // // Wait Command Complete Interrupt Status bit in Normal Interrupt Status Register @@ -2041,6 +2101,7 @@ SdMmcWaitTrbEnv ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -2064,23 +2125,23 @@ SdMmcWaitTrbEnv ( **/ EFI_STATUS SdMmcExecTrb ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT16 Cmd; - UINT16 IntStatus; - UINT32 Argument; - UINT32 BlkCount; - UINT16 BlkSize; - UINT16 TransMode; - UINT8 HostCtrl1; - UINT64 SdmaAddr; - UINT64 AdmaAddr; - BOOLEAN AddressingMode64; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 Cmd; + UINT16 IntStatus; + UINT32 Argument; + UINT32 BlkCount; + UINT16 BlkSize; + UINT16 TransMode; + UINT8 HostCtrl1; + UINT64 SdmaAddr; + UINT64 AdmaAddr; + BOOLEAN AddressingMode64; AddressingMode64 = FALSE; @@ -2094,6 +2155,7 @@ SdMmcExecTrb ( if (EFI_ERROR (Status)) { return Status; } + // // Clear all bits in Normal Interrupt Status Register excepts for Card Removal & Card Insertion bits. // @@ -2104,8 +2166,14 @@ SdMmcExecTrb ( } if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_400) { - Status = SdMmcHcCheckMmioSet(PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL2, sizeof(UINT16), - SD_MMC_HC_64_ADDR_EN, SD_MMC_HC_64_ADDR_EN); + Status = SdMmcHcCheckMmioSet ( + PciIo, + Trb->Slot, + SD_MMC_HC_HOST_CTRL2, + sizeof (UINT16), + SD_MMC_HC_64_ADDR_EN, + SD_MMC_HC_64_ADDR_EN + ); if (!EFI_ERROR (Status)) { AddressingMode64 = TRUE; } @@ -2115,15 +2183,16 @@ SdMmcExecTrb ( // Set Host Control 1 register DMA Select field // if ((Trb->Mode == SdMmcAdma32bMode) || - (Trb->Mode == SdMmcAdma64bV4Mode)) { + (Trb->Mode == SdMmcAdma64bV4Mode)) + { HostCtrl1 = BIT4; - Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } } else if (Trb->Mode == SdMmcAdma64bV3Mode) { HostCtrl1 = BIT4|BIT3; - Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdMmcHcOrMmio (PciIo, Trb->Slot, SD_MMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } @@ -2133,7 +2202,8 @@ SdMmcExecTrb ( if (Trb->Mode == SdMmcSdmaMode) { if ((!AddressingMode64) && - ((UINT64)(UINTN)Trb->DataPhy >= 0x100000000ul)) { + ((UINT64)(UINTN)Trb->DataPhy >= 0x100000000ul)) + { return EFI_INVALID_PARAMETER; } @@ -2150,7 +2220,8 @@ SdMmcExecTrb ( } } else if ((Trb->Mode == SdMmcAdma32bMode) || (Trb->Mode == SdMmcAdma64bV3Mode) || - (Trb->Mode == SdMmcAdma64bV4Mode)) { + (Trb->Mode == SdMmcAdma64bV4Mode)) + { AdmaAddr = (UINT64)(UINTN)Trb->AdmaDescPhy; Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_ADMA_SYS_ADDR, FALSE, sizeof (AdmaAddr), &AdmaAddr); if (EFI_ERROR (Status)) { @@ -2178,11 +2249,13 @@ SdMmcExecTrb ( // BlkCount = (Trb->DataLen / Trb->BlockSize); } + if (Private->ControllerVersion[Trb->Slot] >= SD_MMC_HC_CTRL_VER_410) { Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_SDMA_ADDR, FALSE, sizeof (UINT32), &BlkCount); } else { Status = SdMmcHcRwMmio (PciIo, Trb->Slot, SD_MMC_HC_BLK_COUNT, FALSE, sizeof (UINT16), &BlkCount); } + if (EFI_ERROR (Status)) { return Status; } @@ -2198,12 +2271,15 @@ SdMmcExecTrb ( if (Trb->Mode != SdMmcPioMode) { TransMode |= BIT0; } + if (Trb->Read) { TransMode |= BIT4; } + if (BlkCount > 1) { TransMode |= BIT5 | BIT1; } + // // Only SD memory card needs to use AUTO CMD12 feature. // @@ -2219,10 +2295,11 @@ SdMmcExecTrb ( return Status; } - Cmd = (UINT16)LShiftU64(Packet->SdMmcCmdBlk->CommandIndex, 8); + Cmd = (UINT16)LShiftU64 (Packet->SdMmcCmdBlk->CommandIndex, 8); if (Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc) { Cmd |= BIT5; } + // // Convert ResponseType to value // @@ -2236,7 +2313,7 @@ SdMmcExecTrb ( break; case SdMmcResponseTypeR2: Cmd |= (BIT0 | BIT3); - break; + break; case SdMmcResponseTypeR3: case SdMmcResponseTypeR4: Cmd |= BIT1; @@ -2250,6 +2327,7 @@ SdMmcExecTrb ( break; } } + // // Execute cmd // @@ -2281,18 +2359,19 @@ SdMmcSoftwareReset ( if ((ErrIntStatus & 0x0F) != 0) { SwReset |= BIT1; } + if ((ErrIntStatus & 0x70) != 0) { SwReset |= BIT2; } - Status = SdMmcHcRwMmio ( - Private->PciIo, - Slot, - SD_MMC_HC_SW_RST, - FALSE, - sizeof (SwReset), - &SwReset - ); + Status = SdMmcHcRwMmio ( + Private->PciIo, + Slot, + SD_MMC_HC_SW_RST, + FALSE, + sizeof (SwReset), + &SwReset + ); if (EFI_ERROR (Status)) { return Status; } @@ -2429,10 +2508,11 @@ SdMmcGetResponse ( sizeof (UINT32), &Response[Index] ); - if (EFI_ERROR (Status)) { - return Status; - } + if (EFI_ERROR (Status)) { + return Status; } + } + CopyMem (Packet->SdMmcStatusBlk, Response, sizeof (Response)); return EFI_SUCCESS; @@ -2474,10 +2554,12 @@ SdMmcCheckCommandComplete ( if (EFI_ERROR (Status)) { return Status; } + Status = SdMmcGetResponse (Private, Trb); if (EFI_ERROR (Status)) { return Status; } + Trb->CommandComplete = TRUE; return EFI_SUCCESS; } @@ -2503,11 +2585,11 @@ SdMmcTransferDataWithPio ( IN UINT16 IntStatus ) { - EFI_STATUS Status; - UINT16 Data16; - UINT32 BlockCount; + EFI_STATUS Status; + UINT16 Data16; + UINT32 BlockCount; EFI_PCI_IO_PROTOCOL_WIDTH Width; - UINTN Count; + UINTN Count; BlockCount = (Trb->DataLen / Trb->BlockSize); if (Trb->DataLen % Trb->BlockSize != 0) { @@ -2533,45 +2615,49 @@ SdMmcTransferDataWithPio ( Width = EfiPciIoWidthFifoUint8; Count = Trb->BlockSize; break; - } + } if (Trb->Read) { if ((IntStatus & BIT5) == 0) { return EFI_NOT_READY; } + Data16 = BIT5; SdMmcHcRwMmio (Private->PciIo, Trb->Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (Data16), &Data16); Status = Private->PciIo->Mem.Read ( - Private->PciIo, - Width, - Trb->Slot, - SD_MMC_HC_BUF_DAT_PORT, - Count, - (VOID*)((UINT8*)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex)) - ); + Private->PciIo, + Width, + Trb->Slot, + SD_MMC_HC_BUF_DAT_PORT, + Count, + (VOID *)((UINT8 *)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex)) + ); if (EFI_ERROR (Status)) { return Status; } + Trb->PioBlockIndex++; } else { if ((IntStatus & BIT4) == 0) { return EFI_NOT_READY; } + Data16 = BIT4; SdMmcHcRwMmio (Private->PciIo, Trb->Slot, SD_MMC_HC_NOR_INT_STS, FALSE, sizeof (Data16), &Data16); Status = Private->PciIo->Mem.Write ( - Private->PciIo, - Width, - Trb->Slot, - SD_MMC_HC_BUF_DAT_PORT, - Count, - (VOID*)((UINT8*)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex)) - ); + Private->PciIo, + Width, + Trb->Slot, + SD_MMC_HC_BUF_DAT_PORT, + Count, + (VOID *)((UINT8 *)Trb->Data + (Trb->BlockSize * Trb->PioBlockIndex)) + ); if (EFI_ERROR (Status)) { return Status; } + Trb->PioBlockIndex++; } @@ -2667,7 +2753,7 @@ SdMmcCheckDataTransfer ( return Status; } - if (Trb->Mode == SdMmcPioMode && !Trb->PioModeTransferCompleted) { + if ((Trb->Mode == SdMmcPioMode) && !Trb->PioModeTransferCompleted) { Status = SdMmcTransferDataWithPio (Private, Trb, IntStatus); if (EFI_ERROR (Status)) { return Status; @@ -2687,6 +2773,7 @@ SdMmcCheckDataTransfer ( if (EFI_ERROR (Status)) { return Status; } + Status = SdMmcUpdateSdmaAddress (Private, Trb); if (EFI_ERROR (Status)) { return Status; @@ -2709,15 +2796,15 @@ SdMmcCheckDataTransfer ( **/ EFI_STATUS SdMmcCheckTrbResult ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - UINT16 IntStatus; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + UINT16 IntStatus; - Packet = Trb->Packet; + Packet = Trb->Packet; // // Check Trb execution result by reading Normal Interrupt Status register. // @@ -2750,7 +2837,8 @@ SdMmcCheckTrbResult ( if (((Private->Slot[Trb->Slot].CardType == EmmcCardType) && (Packet->SdMmcCmdBlk->CommandIndex == EMMC_SEND_TUNING_BLOCK)) || ((Private->Slot[Trb->Slot].CardType == SdCardType) && - (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) { + (Packet->SdMmcCmdBlk->CommandIndex == SD_SEND_TUNING_BLOCK))) + { Status = SdMmcTransferDataWithPio (Private, Trb, IntStatus); goto Done; } @@ -2762,9 +2850,10 @@ SdMmcCheckTrbResult ( } } - if (Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc || - Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR1b || - Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b) { + if ((Packet->SdMmcCmdBlk->CommandType == SdMmcCommandTypeAdtc) || + (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR1b) || + (Packet->SdMmcCmdBlk->ResponseType == SdMmcResponseTypeR5b)) + { Status = SdMmcCheckDataTransfer (Private, Trb, IntStatus); } else { Status = EFI_SUCCESS; @@ -2797,14 +2886,14 @@ Done: **/ EFI_STATUS SdMmcWaitTrbResult ( - IN SD_MMC_HC_PRIVATE_DATA *Private, - IN SD_MMC_HC_TRB *Trb + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN SD_MMC_HC_TRB *Trb ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; Packet = Trb->Packet; // @@ -2825,6 +2914,7 @@ SdMmcWaitTrbResult ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -2835,4 +2925,3 @@ SdMmcWaitTrbResult ( return EFI_TIMEOUT; } - diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h index 16229a846c..91155770e0 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h @@ -14,9 +14,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // SD Host Controller SlotInfo Register Offset // -#define SD_MMC_HC_SLOT_OFFSET 0x40 +#define SD_MMC_HC_SLOT_OFFSET 0x40 -#define SD_MMC_HC_MAX_SLOT 6 +#define SD_MMC_HC_MAX_SLOT 6 // // SD Host Controller MMIO Register Offset @@ -60,17 +60,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // SD Host Controller bits to HOST_CTRL2 register // -#define SD_MMC_HC_CTRL_UHS_MASK 0x0007 -#define SD_MMC_HC_CTRL_UHS_SDR12 0x0000 -#define SD_MMC_HC_CTRL_UHS_SDR25 0x0001 -#define SD_MMC_HC_CTRL_UHS_SDR50 0x0002 -#define SD_MMC_HC_CTRL_UHS_SDR104 0x0003 -#define SD_MMC_HC_CTRL_UHS_DDR50 0x0004 -#define SD_MMC_HC_CTRL_MMC_LEGACY 0x0000 -#define SD_MMC_HC_CTRL_MMC_HS_SDR 0x0001 -#define SD_MMC_HC_CTRL_MMC_HS_DDR 0x0004 -#define SD_MMC_HC_CTRL_MMC_HS200 0x0003 -#define SD_MMC_HC_CTRL_MMC_HS400 0x0005 +#define SD_MMC_HC_CTRL_UHS_MASK 0x0007 +#define SD_MMC_HC_CTRL_UHS_SDR12 0x0000 +#define SD_MMC_HC_CTRL_UHS_SDR25 0x0001 +#define SD_MMC_HC_CTRL_UHS_SDR50 0x0002 +#define SD_MMC_HC_CTRL_UHS_SDR104 0x0003 +#define SD_MMC_HC_CTRL_UHS_DDR50 0x0004 +#define SD_MMC_HC_CTRL_MMC_LEGACY 0x0000 +#define SD_MMC_HC_CTRL_MMC_HS_SDR 0x0001 +#define SD_MMC_HC_CTRL_MMC_HS_DDR 0x0004 +#define SD_MMC_HC_CTRL_MMC_HS200 0x0003 +#define SD_MMC_HC_CTRL_MMC_HS400 0x0005 #define SD_MMC_HC_CTRL_DRIVER_STRENGTH_MASK 0x0030 @@ -97,113 +97,113 @@ typedef enum { // // The maximum data length of each descriptor line // -#define ADMA_MAX_DATA_PER_LINE_16B SIZE_64KB -#define ADMA_MAX_DATA_PER_LINE_26B SIZE_64MB +#define ADMA_MAX_DATA_PER_LINE_16B SIZE_64KB +#define ADMA_MAX_DATA_PER_LINE_26B SIZE_64MB // // ADMA descriptor for 32b addressing. // typedef struct { - UINT32 Valid:1; - UINT32 End:1; - UINT32 Int:1; - UINT32 Reserved:1; - UINT32 Act:2; - UINT32 UpperLength:10; - UINT32 LowerLength:16; - UINT32 Address; + UINT32 Valid : 1; + UINT32 End : 1; + UINT32 Int : 1; + UINT32 Reserved : 1; + UINT32 Act : 2; + UINT32 UpperLength : 10; + UINT32 LowerLength : 16; + UINT32 Address; } SD_MMC_HC_ADMA_32_DESC_LINE; // // ADMA descriptor for 64b addressing. // typedef struct { - UINT32 Valid:1; - UINT32 End:1; - UINT32 Int:1; - UINT32 Reserved:1; - UINT32 Act:2; - UINT32 UpperLength:10; - UINT32 LowerLength:16; - UINT32 LowerAddress; - UINT32 UpperAddress; + UINT32 Valid : 1; + UINT32 End : 1; + UINT32 Int : 1; + UINT32 Reserved : 1; + UINT32 Act : 2; + UINT32 UpperLength : 10; + UINT32 LowerLength : 16; + UINT32 LowerAddress; + UINT32 UpperAddress; } SD_MMC_HC_ADMA_64_V3_DESC_LINE; typedef struct { - UINT32 Valid:1; - UINT32 End:1; - UINT32 Int:1; - UINT32 Reserved:1; - UINT32 Act:2; - UINT32 UpperLength:10; - UINT32 LowerLength:16; - UINT32 LowerAddress; - UINT32 UpperAddress; - UINT32 Reserved1; + UINT32 Valid : 1; + UINT32 End : 1; + UINT32 Int : 1; + UINT32 Reserved : 1; + UINT32 Act : 2; + UINT32 UpperLength : 10; + UINT32 LowerLength : 16; + UINT32 LowerAddress; + UINT32 UpperAddress; + UINT32 Reserved1; } SD_MMC_HC_ADMA_64_V4_DESC_LINE; -#define SD_MMC_SDMA_BOUNDARY 512 * 1024 -#define SD_MMC_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) +#define SD_MMC_SDMA_BOUNDARY 512 * 1024 +#define SD_MMC_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) typedef struct { - UINT8 FirstBar:3; // bit 0:2 - UINT8 Reserved:1; // bit 3 - UINT8 SlotNum:3; // bit 4:6 - UINT8 Reserved1:1; // bit 7 + UINT8 FirstBar : 3; // bit 0:2 + UINT8 Reserved : 1; // bit 3 + UINT8 SlotNum : 3; // bit 4:6 + UINT8 Reserved1 : 1; // bit 7 } SD_MMC_HC_SLOT_INFO; typedef struct { - UINT32 TimeoutFreq:6; // bit 0:5 - UINT32 Reserved:1; // bit 6 - UINT32 TimeoutUnit:1; // bit 7 - UINT32 BaseClkFreq:8; // bit 8:15 - UINT32 MaxBlkLen:2; // bit 16:17 - UINT32 BusWidth8:1; // bit 18 - UINT32 Adma2:1; // bit 19 - UINT32 Reserved2:1; // bit 20 - UINT32 HighSpeed:1; // bit 21 - UINT32 Sdma:1; // bit 22 - UINT32 SuspRes:1; // bit 23 - UINT32 Voltage33:1; // bit 24 - UINT32 Voltage30:1; // bit 25 - UINT32 Voltage18:1; // bit 26 - UINT32 SysBus64V4:1; // bit 27 - UINT32 SysBus64V3:1; // bit 28 - UINT32 AsyncInt:1; // bit 29 - UINT32 SlotType:2; // bit 30:31 - UINT32 Sdr50:1; // bit 32 - UINT32 Sdr104:1; // bit 33 - UINT32 Ddr50:1; // bit 34 - UINT32 Reserved3:1; // bit 35 - UINT32 DriverTypeA:1; // bit 36 - UINT32 DriverTypeC:1; // bit 37 - UINT32 DriverTypeD:1; // bit 38 - UINT32 DriverType4:1; // bit 39 - UINT32 TimerCount:4; // bit 40:43 - UINT32 Reserved4:1; // bit 44 - UINT32 TuningSDR50:1; // bit 45 - UINT32 RetuningMod:2; // bit 46:47 - UINT32 ClkMultiplier:8; // bit 48:55 - UINT32 Reserved5:7; // bit 56:62 - UINT32 Hs400:1; // bit 63 + UINT32 TimeoutFreq : 6; // bit 0:5 + UINT32 Reserved : 1; // bit 6 + UINT32 TimeoutUnit : 1; // bit 7 + UINT32 BaseClkFreq : 8; // bit 8:15 + UINT32 MaxBlkLen : 2; // bit 16:17 + UINT32 BusWidth8 : 1; // bit 18 + UINT32 Adma2 : 1; // bit 19 + UINT32 Reserved2 : 1; // bit 20 + UINT32 HighSpeed : 1; // bit 21 + UINT32 Sdma : 1; // bit 22 + UINT32 SuspRes : 1; // bit 23 + UINT32 Voltage33 : 1; // bit 24 + UINT32 Voltage30 : 1; // bit 25 + UINT32 Voltage18 : 1; // bit 26 + UINT32 SysBus64V4 : 1; // bit 27 + UINT32 SysBus64V3 : 1; // bit 28 + UINT32 AsyncInt : 1; // bit 29 + UINT32 SlotType : 2; // bit 30:31 + UINT32 Sdr50 : 1; // bit 32 + UINT32 Sdr104 : 1; // bit 33 + UINT32 Ddr50 : 1; // bit 34 + UINT32 Reserved3 : 1; // bit 35 + UINT32 DriverTypeA : 1; // bit 36 + UINT32 DriverTypeC : 1; // bit 37 + UINT32 DriverTypeD : 1; // bit 38 + UINT32 DriverType4 : 1; // bit 39 + UINT32 TimerCount : 4; // bit 40:43 + UINT32 Reserved4 : 1; // bit 44 + UINT32 TuningSDR50 : 1; // bit 45 + UINT32 RetuningMod : 2; // bit 46:47 + UINT32 ClkMultiplier : 8; // bit 48:55 + UINT32 Reserved5 : 7; // bit 56:62 + UINT32 Hs400 : 1; // bit 63 } SD_MMC_HC_SLOT_CAP; // // SD Host controller version // -#define SD_MMC_HC_CTRL_VER_100 0x00 -#define SD_MMC_HC_CTRL_VER_200 0x01 -#define SD_MMC_HC_CTRL_VER_300 0x02 -#define SD_MMC_HC_CTRL_VER_400 0x03 -#define SD_MMC_HC_CTRL_VER_410 0x04 -#define SD_MMC_HC_CTRL_VER_420 0x05 +#define SD_MMC_HC_CTRL_VER_100 0x00 +#define SD_MMC_HC_CTRL_VER_200 0x01 +#define SD_MMC_HC_CTRL_VER_300 0x02 +#define SD_MMC_HC_CTRL_VER_400 0x03 +#define SD_MMC_HC_CTRL_VER_410 0x04 +#define SD_MMC_HC_CTRL_VER_420 0x05 // // SD Host controller V4 enhancements // -#define SD_MMC_HC_V4_EN BIT12 -#define SD_MMC_HC_64_ADDR_EN BIT13 -#define SD_MMC_HC_26_DATA_LEN_ADMA_EN BIT10 +#define SD_MMC_HC_V4_EN BIT12 +#define SD_MMC_HC_64_ADDR_EN BIT13 +#define SD_MMC_HC_26_DATA_LEN_ADMA_EN BIT10 /** Dump the content of SD/MMC host controller's Capability Register. @@ -214,8 +214,8 @@ typedef struct { **/ VOID DumpCapabilityReg ( - IN UINT8 Slot, - IN SD_MMC_HC_SLOT_CAP *Capability + IN UINT8 Slot, + IN SD_MMC_HC_SLOT_CAP *Capability ); /** @@ -232,9 +232,9 @@ DumpCapabilityReg ( EFI_STATUS EFIAPI SdMmcHcGetSlotInfo ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - OUT UINT8 *FirstBar, - OUT UINT8 *SlotNum + IN EFI_PCI_IO_PROTOCOL *PciIo, + OUT UINT8 *FirstBar, + OUT UINT8 *SlotNum ); /** @@ -263,12 +263,12 @@ SdMmcHcGetSlotInfo ( EFI_STATUS EFIAPI SdMmcHcRwMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN BOOLEAN Read, - IN UINT8 Count, - IN OUT VOID *Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN BOOLEAN Read, + IN UINT8 Count, + IN OUT VOID *Data ); /** @@ -295,11 +295,11 @@ SdMmcHcRwMmio ( EFI_STATUS EFIAPI SdMmcHcOrMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN VOID *OrData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN VOID *OrData ); /** @@ -326,11 +326,11 @@ SdMmcHcOrMmio ( EFI_STATUS EFIAPI SdMmcHcAndMmio ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN VOID *AndData + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN VOID *AndData ); /** @@ -358,13 +358,13 @@ SdMmcHcAndMmio ( EFI_STATUS EFIAPI SdMmcHcWaitMmioSet ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 BarIndex, - IN UINT32 Offset, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue, - IN UINT64 Timeout + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 BarIndex, + IN UINT32 Offset, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue, + IN UINT64 Timeout ); /** @@ -398,8 +398,8 @@ SdMmcHcGetControllerVersion ( **/ EFI_STATUS SdMmcHcEnableInterrupt ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ); /** @@ -417,7 +417,7 @@ EFI_STATUS SdMmcHcGetCapability ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN UINT8 Slot, - OUT SD_MMC_HC_SLOT_CAP *Capability + OUT SD_MMC_HC_SLOT_CAP *Capability ); /** @@ -435,7 +435,7 @@ EFI_STATUS SdMmcHcGetMaxCurrent ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN UINT8 Slot, - OUT UINT64 *MaxCurrent + OUT UINT64 *MaxCurrent ); /** @@ -455,9 +455,9 @@ SdMmcHcGetMaxCurrent ( **/ EFI_STATUS SdMmcHcCardDetect ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - OUT BOOLEAN *MediaPresent + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + OUT BOOLEAN *MediaPresent ); /** @@ -474,8 +474,8 @@ SdMmcHcCardDetect ( **/ EFI_STATUS SdMmcHcStopClock ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ); /** @@ -508,9 +508,9 @@ SdMmcHcStartSdClock ( **/ EFI_STATUS SdMmcHcPowerControl ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT8 PowerCtrl + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN UINT8 PowerCtrl ); /** @@ -528,9 +528,9 @@ SdMmcHcPowerControl ( **/ EFI_STATUS SdMmcHcSetBusWidth ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT16 BusWidth + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN UINT16 BusWidth ); /** @@ -548,9 +548,9 @@ SdMmcHcSetBusWidth ( **/ EFI_STATUS SdMmcHcInitPowerVoltage ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN SD_MMC_HC_SLOT_CAP Capability + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN SD_MMC_HC_SLOT_CAP Capability ); /** @@ -567,8 +567,8 @@ SdMmcHcInitPowerVoltage ( **/ EFI_STATUS SdMmcHcInitTimeoutCtrl ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot ); /** @@ -584,10 +584,10 @@ SdMmcHcInitTimeoutCtrl ( **/ EFI_STATUS SdMmcHcUhsSignaling ( - IN EFI_HANDLE ControllerHandle, - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN SD_MMC_BUS_MODE Timing + IN EFI_HANDLE ControllerHandle, + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot, + IN SD_MMC_BUS_MODE Timing ); /** diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.c index 9c18e6fddc..89e0a1b6a4 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.c @@ -11,7 +11,7 @@ EDKII_SD_MMC_HOST_CONTROLLER_PPI mSdMmcHostControllerPpi = { GetSdMmcHcMmioBar }; -EFI_PEI_PPI_DESCRIPTOR mPpiList = { +EFI_PEI_PPI_DESCRIPTOR mPpiList = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEdkiiPeiSdMmcHostControllerPpiGuid, &mSdMmcHostControllerPpi @@ -34,10 +34,10 @@ EFI_PEI_PPI_DESCRIPTOR mPpiList = { EFI_STATUS EFIAPI GetSdMmcHcMmioBar ( - IN EDKII_SD_MMC_HOST_CONTROLLER_PPI *This, - IN UINT8 ControllerId, - IN OUT UINTN **MmioBar, - OUT UINT8 *BarNum + IN EDKII_SD_MMC_HOST_CONTROLLER_PPI *This, + IN UINT8 ControllerId, + IN OUT UINTN **MmioBar, + OUT UINT8 *BarNum ) { SD_MMC_HC_PEI_PRIVATE_DATA *Private; @@ -70,26 +70,26 @@ GetSdMmcHcMmioBar ( EFI_STATUS EFIAPI InitializeSdMmcHcPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_BOOT_MODE BootMode; - EFI_STATUS Status; - UINT16 Bus; - UINT16 Device; - UINT16 Function; - UINT32 Size; - UINT64 MmioSize; - UINT8 SubClass; - UINT8 BaseClass; - UINT8 SlotInfo; - UINT8 SlotNum; - UINT8 FirstBar; - UINT8 Index; - UINT8 Slot; - UINT32 BarAddr; - SD_MMC_HC_PEI_PRIVATE_DATA *Private; + EFI_BOOT_MODE BootMode; + EFI_STATUS Status; + UINT16 Bus; + UINT16 Device; + UINT16 Function; + UINT32 Size; + UINT64 MmioSize; + UINT8 SubClass; + UINT8 BaseClass; + UINT8 SlotInfo; + UINT8 SlotNum; + UINT8 FirstBar; + UINT8 Index; + UINT8 Slot; + UINT32 BarAddr; + SD_MMC_HC_PEI_PRIVATE_DATA *Private; // // Shadow this PEIM to run from memory @@ -106,7 +106,7 @@ InitializeSdMmcHcPeim ( return EFI_SUCCESS; } - Private = (SD_MMC_HC_PEI_PRIVATE_DATA *) AllocateZeroPool (sizeof (SD_MMC_HC_PEI_PRIVATE_DATA)); + Private = (SD_MMC_HC_PEI_PRIVATE_DATA *)AllocateZeroPool (sizeof (SD_MMC_HC_PEI_PRIVATE_DATA)); if (Private == NULL) { DEBUG ((DEBUG_ERROR, "Failed to allocate memory for SD_MMC_HC_PEI_PRIVATE_DATA! \n")); return EFI_OUT_OF_RESOURCES; @@ -129,15 +129,15 @@ InitializeSdMmcHcPeim ( // Get the SD/MMC Pci host controller's Slot Info. // SlotInfo = PciRead8 (PCI_LIB_ADDRESS (Bus, Device, Function, SD_MMC_HC_PEI_SLOT_OFFSET)); - FirstBar = (*(SD_MMC_HC_PEI_SLOT_INFO*)&SlotInfo).FirstBar; - SlotNum = (*(SD_MMC_HC_PEI_SLOT_INFO*)&SlotInfo).SlotNum + 1; + FirstBar = (*(SD_MMC_HC_PEI_SLOT_INFO *)&SlotInfo).FirstBar; + SlotNum = (*(SD_MMC_HC_PEI_SLOT_INFO *)&SlotInfo).SlotNum + 1; ASSERT ((FirstBar + SlotNum) < MAX_SD_MMC_SLOTS); for (Index = 0, Slot = FirstBar; Slot < (FirstBar + SlotNum); Index++, Slot++) { // // Get the SD/MMC Pci host controller's MMIO region size. // - PciAnd16 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_COMMAND_OFFSET), (UINT16)~(EFI_PCI_COMMAND_BUS_MASTER | EFI_PCI_COMMAND_MEMORY_SPACE)); + PciAnd16 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_COMMAND_OFFSET), (UINT16) ~(EFI_PCI_COMMAND_BUS_MASTER | EFI_PCI_COMMAND_MEMORY_SPACE)); PciWrite32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4 * Slot), 0xFFFFFFFF); Size = PciRead32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4 * Slot)); @@ -153,8 +153,8 @@ InitializeSdMmcHcPeim ( // Memory space: anywhere in 64 bit address space // MmioSize = Size & 0xFFFFFFF0; - PciWrite32 (PCI_LIB_ADDRESS(Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4), 0xFFFFFFFF); - Size = PciRead32 (PCI_LIB_ADDRESS(Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4)); + PciWrite32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4), 0xFFFFFFFF); + Size = PciRead32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4)); // // Fix the length to support some spefic 64 bit BAR // @@ -162,7 +162,7 @@ InitializeSdMmcHcPeim ( // // Calculate the size of 64bit bar // - MmioSize |= LShiftU64 ((UINT64) Size, 32); + MmioSize |= LShiftU64 ((UINT64)Size, 32); MmioSize = (~(MmioSize)) + 1; // // Clean the high 32bits of this 64bit BAR to 0 as we only allow a 32bit BAR. @@ -175,7 +175,8 @@ InitializeSdMmcHcPeim ( // ASSERT (FALSE); continue; - }; + } + // // Assign resource to the SdMmc Pci host controller's MMIO BAR. // Enable the SdMmc Pci host controller by setting BME and MSE bits of PCI_CMD register. @@ -187,8 +188,9 @@ InitializeSdMmcHcPeim ( // Private->MmioBar[Private->TotalSdMmcHcs].SlotNum++; Private->MmioBar[Private->TotalSdMmcHcs].MmioBarAddr[Index] = BarAddr; - BarAddr += (UINT32)MmioSize; + BarAddr += (UINT32)MmioSize; } + Private->TotalSdMmcHcs++; ASSERT (Private->TotalSdMmcHcs < MAX_SD_MMC_HCS); } diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.h index ee04a6b897..ade59dd6e3 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcPei/SdMmcPciHcPei.h @@ -22,10 +22,10 @@ #include #include -#define SD_MMC_HC_PEI_SIGNATURE SIGNATURE_32 ('S', 'D', 'M', 'C') +#define SD_MMC_HC_PEI_SIGNATURE SIGNATURE_32 ('S', 'D', 'M', 'C') -#define MAX_SD_MMC_HCS 8 -#define MAX_SD_MMC_SLOTS 6 +#define MAX_SD_MMC_HCS 8 +#define MAX_SD_MMC_SLOTS 6 // // SD Host Controller SlotInfo Register Offset @@ -33,23 +33,23 @@ #define SD_MMC_HC_PEI_SLOT_OFFSET 0x40 typedef struct { - UINT8 FirstBar:3; // bit 0:2 - UINT8 Reserved:1; // bit 3 - UINT8 SlotNum:3; // bit 4:6 - UINT8 Reserved1:1; // bit 7 + UINT8 FirstBar : 3; // bit 0:2 + UINT8 Reserved : 1; // bit 3 + UINT8 SlotNum : 3; // bit 4:6 + UINT8 Reserved1 : 1; // bit 7 } SD_MMC_HC_PEI_SLOT_INFO; typedef struct { - UINTN SlotNum; - UINTN MmioBarAddr[MAX_SD_MMC_SLOTS]; + UINTN SlotNum; + UINTN MmioBarAddr[MAX_SD_MMC_SLOTS]; } SD_MMC_HC_PEI_BAR; typedef struct { - UINTN Signature; - EDKII_SD_MMC_HOST_CONTROLLER_PPI SdMmcHostControllerPpi; - EFI_PEI_PPI_DESCRIPTOR PpiList; - UINTN TotalSdMmcHcs; - SD_MMC_HC_PEI_BAR MmioBar[MAX_SD_MMC_HCS]; + UINTN Signature; + EDKII_SD_MMC_HOST_CONTROLLER_PPI SdMmcHostControllerPpi; + EFI_PEI_PPI_DESCRIPTOR PpiList; + UINTN TotalSdMmcHcs; + SD_MMC_HC_PEI_BAR MmioBar[MAX_SD_MMC_HCS]; } SD_MMC_HC_PEI_PRIVATE_DATA; #define SD_MMC_HC_PEI_PRIVATE_DATA_FROM_THIS(a) CR (a, SD_MMC_HC_PEI_PRIVATE_DATA, SdMmcHostControllerPpi, SD_MMC_HC_PEI_SIGNATURE) @@ -71,10 +71,10 @@ typedef struct { EFI_STATUS EFIAPI GetSdMmcHcMmioBar ( - IN EDKII_SD_MMC_HOST_CONTROLLER_PPI *This, - IN UINT8 ControllerId, - IN OUT UINTN **MmioBar, - OUT UINT8 *BarNum + IN EDKII_SD_MMC_HOST_CONTROLLER_PPI *This, + IN UINT8 ControllerId, + IN OUT UINTN **MmioBar, + OUT UINT8 *BarNum ); #endif diff --git a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/ComponentName.c index 5dc67e8905..cff05b4da5 100644 --- a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/ComponentName.c @@ -12,7 +12,7 @@ // // EFI Component Name Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUfsHcComponentName = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUfsHcComponentName = { UfsHcComponentNameGetDriverName, UfsHcComponentNameGetControllerName, "eng" @@ -21,13 +21,13 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUfsHcComponentName = // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUfsHcComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UfsHcComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UfsHcComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUfsHcComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UfsHcComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UfsHcComponentNameGetControllerName, "en" }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcDriverNameTable[] = { { "eng;en", L"Universal Flash Storage (UFS) Pci Host Controller Driver" @@ -38,7 +38,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcDriverNameTable[] = } }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcControllerNameTable[] = { { "eng;en", L"Universal Flash Storage (UFS) Pci Host Controller" @@ -91,9 +91,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsHcControllerNameTable EFI_STATUS EFIAPI UfsHcComponentNameGetDriverName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN CHAR8 *Language, - OUT CHAR16 **DriverName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN CHAR8 *Language, + OUT CHAR16 **DriverName ) { return LookupUnicodeString2 ( @@ -176,16 +176,16 @@ UfsHcComponentNameGetDriverName ( EFI_STATUS EFIAPI UfsHcComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; + EFI_STATUS Status; - if (Language == NULL || ControllerName == NULL) { + if ((Language == NULL) || (ControllerName == NULL)) { return EFI_INVALID_PARAMETER; } @@ -215,5 +215,4 @@ UfsHcComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gUfsHcComponentName) ); - } diff --git a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.c b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.c index 4be90d7a80..5756ef0791 100644 --- a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.c +++ b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.c @@ -12,7 +12,7 @@ // // NVM Express Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gUfsHcDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUfsHcDriverBinding = { UfsHcDriverBindingSupported, UfsHcDriverBindingStart, UfsHcDriverBindingStop, @@ -24,7 +24,7 @@ EFI_DRIVER_BINDING_PROTOCOL gUfsHcDriverBinding = { // // Template for Ufs host controller private data. // -UFS_HOST_CONTROLLER_PRIVATE_DATA gUfsHcTemplate = { +UFS_HOST_CONTROLLER_PRIVATE_DATA gUfsHcTemplate = { UFS_HC_PRIVATE_DATA_SIGNATURE, // Signature { // UfsHcProtocol UfsHcGetMmioBar, @@ -53,15 +53,15 @@ UFS_HOST_CONTROLLER_PRIVATE_DATA gUfsHcTemplate = { EFI_STATUS EFIAPI UfsHcGetMmioBar ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - OUT UINTN *MmioBar + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + OUT UINTN *MmioBar ) { - UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_STATUS Status; - UINT8 BarIndex; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; + UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_STATUS Status; + UINT8 BarIndex; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; if ((This == NULL) || (MmioBar == NULL)) { return EFI_INVALID_PARAMETER; @@ -76,7 +76,7 @@ UfsHcGetMmioBar ( PciIo, BarIndex, NULL, - (VOID**) &BarDesc + (VOID **)&BarDesc ); if (EFI_ERROR (Status)) { return Status; @@ -115,8 +115,8 @@ UfsHcMap ( IN EDKII_UFS_HOST_CONTROLLER_OPERATION Operation, IN VOID *HostAddress, IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; @@ -130,7 +130,7 @@ UfsHcMap ( Private = UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC (This); PciIo = Private->PciIo; - Status = PciIo->Map (PciIo, (EFI_PCI_IO_PROTOCOL_OPERATION)Operation, HostAddress, NumberOfBytes, DeviceAddress, Mapping); + Status = PciIo->Map (PciIo, (EFI_PCI_IO_PROTOCOL_OPERATION)Operation, HostAddress, NumberOfBytes, DeviceAddress, Mapping); return Status; } @@ -147,8 +147,8 @@ UfsHcMap ( EFI_STATUS EFIAPI UfsHcUnmap ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN VOID *Mapping + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN VOID *Mapping ) { UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; @@ -162,7 +162,7 @@ UfsHcUnmap ( Private = UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC (This); PciIo = Private->PciIo; - Status = PciIo->Unmap (PciIo, Mapping); + Status = PciIo->Unmap (PciIo, Mapping); return Status; } @@ -189,12 +189,12 @@ UfsHcUnmap ( EFI_STATUS EFIAPI UfsHcAllocateBuffer ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ) { UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; @@ -208,7 +208,7 @@ UfsHcAllocateBuffer ( Private = UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC (This); PciIo = Private->PciIo; - Status = PciIo->AllocateBuffer (PciIo, Type, MemoryType, Pages, HostAddress, Attributes); + Status = PciIo->AllocateBuffer (PciIo, Type, MemoryType, Pages, HostAddress, Attributes); return Status; } @@ -227,9 +227,9 @@ UfsHcAllocateBuffer ( EFI_STATUS EFIAPI UfsHcFreeBuffer ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ) { UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; @@ -243,7 +243,7 @@ UfsHcFreeBuffer ( Private = UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC (This); PciIo = Private->PciIo; - Status = PciIo->FreeBuffer (PciIo, Pages, HostAddress); + Status = PciIo->FreeBuffer (PciIo, Pages, HostAddress); return Status; } @@ -261,7 +261,7 @@ UfsHcFreeBuffer ( EFI_STATUS EFIAPI UfsHcFlush ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This ) { UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; @@ -271,7 +271,7 @@ UfsHcFlush ( Private = UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC (This); PciIo = Private->PciIo; - Status = PciIo->Flush (PciIo); + Status = PciIo->Flush (PciIo); return Status; } @@ -312,7 +312,7 @@ UfsHcMmioRead ( PciIo = Private->PciIo; BarIndex = Private->BarIndex; - Status = PciIo->Mem.Read (PciIo, (EFI_PCI_IO_PROTOCOL_WIDTH)Width, BarIndex, Offset, Count, Buffer); + Status = PciIo->Mem.Read (PciIo, (EFI_PCI_IO_PROTOCOL_WIDTH)Width, BarIndex, Offset, Count, Buffer); return Status; } @@ -354,7 +354,7 @@ UfsHcMmioWrite ( PciIo = Private->PciIo; BarIndex = Private->BarIndex; - Status = PciIo->Mem.Write (PciIo, (EFI_PCI_IO_PROTOCOL_WIDTH)Width, BarIndex, Offset, Count, Buffer); + Status = PciIo->Mem.Write (PciIo, (EFI_PCI_IO_PROTOCOL_WIDTH)Width, BarIndex, Offset, Count, Buffer); return Status; } @@ -426,7 +426,7 @@ UfsHcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID *) &ParentDevicePath, + (VOID *)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -437,15 +437,16 @@ UfsHcDriverBindingSupported ( // return Status; } + // // Close the protocol because we don't use it here // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Now test the EfiPciIoProtocol @@ -453,7 +454,7 @@ UfsHcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -461,6 +462,7 @@ UfsHcDriverBindingSupported ( if (EFI_ERROR (Status)) { return Status; } + // // Now further check the PCI header: Base class (offset 0x0B) and // Sub Class (offset 0x0A). This controller should be an UFS controller @@ -474,28 +476,30 @@ UfsHcDriverBindingSupported ( ); if (EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_UNSUPPORTED; } + // // Since we already got the PciData, we can close protocol to avoid to carry it on for multiple exit points. // gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); // // Examine UFS Host Controller PCI Configuration table fields // if (PciData.Hdr.ClassCode[2] == PCI_CLASS_MASS_STORAGE) { - if (PciData.Hdr.ClassCode[1] == 0x09 ) { //UFS Controller Subclass + if (PciData.Hdr.ClassCode[1] == 0x09 ) { + // UFS Controller Subclass UfsHcFound = TRUE; } } @@ -507,7 +511,6 @@ UfsHcDriverBindingSupported ( return Status; } - /** Starts a device controller or a bus controller. @@ -551,12 +554,12 @@ UfsHcDriverBindingStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; - UINT64 Supports; - UINT8 BarIndex; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UFS_HOST_CONTROLLER_PRIVATE_DATA *Private; + UINT64 Supports; + UINT8 BarIndex; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *BarDesc; PciIo = NULL; Private = NULL; @@ -569,7 +572,7 @@ UfsHcDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -602,7 +605,7 @@ UfsHcDriverBindingStart ( PciIo, BarIndex, NULL, - (VOID**) &BarDesc + (VOID **)&BarDesc ); if (Status == EFI_UNSUPPORTED) { continue; @@ -656,7 +659,7 @@ UfsHcDriverBindingStart ( &Controller, &gEdkiiUfsHostControllerProtocolGuid, EFI_NATIVE_INTERFACE, - (VOID*)&(Private->UfsHc) + (VOID *)&(Private->UfsHc) ); Done: @@ -672,12 +675,13 @@ Done: NULL ); } + gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); if (Private != NULL) { FreePool (Private); } @@ -686,7 +690,6 @@ Done: return Status; } - /** Stops a device controller or a bus controller. @@ -716,10 +719,10 @@ Done: EFI_STATUS EFIAPI UfsHcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -732,7 +735,7 @@ UfsHcDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEdkiiUfsHostControllerProtocolGuid, - (VOID **) &UfsHc, + (VOID **)&UfsHc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -794,7 +797,7 @@ UfsHcDriverEntry ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, diff --git a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h index 1cf1144675..0c329069c3 100644 --- a/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h +++ b/MdeModulePkg/Bus/Pci/UfsPciHcDxe/UfsPciHcDxe.h @@ -30,27 +30,27 @@ #include #include -extern EFI_DRIVER_BINDING_PROTOCOL gUfsHcDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gUfsHcComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gUfsHcComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gUfsHcDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gUfsHcComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gUfsHcComponentName2; // // Unique signature for private data structure. // -#define UFS_HC_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('U','F','S','H') +#define UFS_HC_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('U','F','S','H') -typedef struct _UFS_HOST_CONTROLLER_PRIVATE_DATA UFS_HOST_CONTROLLER_PRIVATE_DATA; +typedef struct _UFS_HOST_CONTROLLER_PRIVATE_DATA UFS_HOST_CONTROLLER_PRIVATE_DATA; // // Ufs host controller private data structure. // struct _UFS_HOST_CONTROLLER_PRIVATE_DATA { - UINT32 Signature; + UINT32 Signature; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL UfsHc; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT8 BarIndex; - UINT64 PciAttributes; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL UfsHc; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 BarIndex; + UINT64 PciAttributes; }; #define UFS_HOST_CONTROLLER_PRIVATE_DATA_FROM_UFSHC(a) \ @@ -178,11 +178,11 @@ UfsHcComponentNameGetDriverName ( EFI_STATUS EFIAPI UfsHcComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -307,10 +307,10 @@ UfsHcDriverBindingStart ( EFI_STATUS EFIAPI UfsHcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -325,8 +325,8 @@ UfsHcDriverBindingStop ( EFI_STATUS EFIAPI UfsHcGetMmioBar ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - OUT UINTN *MmioBar + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + OUT UINTN *MmioBar ); /** @@ -355,8 +355,8 @@ UfsHcMap ( IN EDKII_UFS_HOST_CONTROLLER_OPERATION Operation, IN VOID *HostAddress, IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -372,8 +372,8 @@ UfsHcMap ( EFI_STATUS EFIAPI UfsHcUnmap ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN VOID *Mapping + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN VOID *Mapping ); /** @@ -399,12 +399,12 @@ UfsHcUnmap ( EFI_STATUS EFIAPI UfsHcAllocateBuffer ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT VOID **HostAddress, - IN UINT64 Attributes + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT VOID **HostAddress, + IN UINT64 Attributes ); /** @@ -422,9 +422,9 @@ UfsHcAllocateBuffer ( EFI_STATUS EFIAPI UfsHcFreeBuffer ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - IN UINTN Pages, - IN VOID *HostAddress + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress ); /** @@ -441,7 +441,7 @@ UfsHcFreeBuffer ( EFI_STATUS EFIAPI UfsHcFlush ( - IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This + IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This ); /** diff --git a/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.c b/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.c index 68bfade9c2..ac42b1b796 100644 --- a/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.c +++ b/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.c @@ -11,7 +11,7 @@ EDKII_UFS_HOST_CONTROLLER_PPI mUfsHostControllerPpi = { GetUfsHcMmioBar }; -EFI_PEI_PPI_DESCRIPTOR mPpiList = { +EFI_PEI_PPI_DESCRIPTOR mPpiList = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEdkiiPeiUfsHostControllerPpiGuid, &mUfsHostControllerPpi @@ -31,9 +31,9 @@ EFI_PEI_PPI_DESCRIPTOR mPpiList = { EFI_STATUS EFIAPI GetUfsHcMmioBar ( - IN EDKII_UFS_HOST_CONTROLLER_PPI *This, - IN UINT8 ControllerId, - OUT UINTN *MmioBar + IN EDKII_UFS_HOST_CONTROLLER_PPI *This, + IN UINT8 ControllerId, + OUT UINTN *MmioBar ) { UFS_HC_PEI_PRIVATE_DATA *Private; @@ -66,8 +66,8 @@ GetUfsHcMmioBar ( EFI_STATUS EFIAPI InitializeUfsHcPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { EFI_BOOT_MODE BootMode; @@ -97,7 +97,7 @@ InitializeUfsHcPeim ( return EFI_SUCCESS; } - Private = (UFS_HC_PEI_PRIVATE_DATA *) AllocateZeroPool (sizeof (UFS_HC_PEI_PRIVATE_DATA)); + Private = (UFS_HC_PEI_PRIVATE_DATA *)AllocateZeroPool (sizeof (UFS_HC_PEI_PRIVATE_DATA)); if (Private == NULL) { DEBUG ((DEBUG_ERROR, "Failed to allocate memory for UFS_HC_PEI_PRIVATE_DATA! \n")); return EFI_OUT_OF_RESOURCES; @@ -119,7 +119,7 @@ InitializeUfsHcPeim ( // // Get the Ufs Pci host controller's MMIO region size. // - PciAnd16 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_COMMAND_OFFSET), (UINT16)~(EFI_PCI_COMMAND_BUS_MASTER | EFI_PCI_COMMAND_MEMORY_SPACE)); + PciAnd16 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_COMMAND_OFFSET), (UINT16) ~(EFI_PCI_COMMAND_BUS_MASTER | EFI_PCI_COMMAND_MEMORY_SPACE)); PciWrite32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET), 0xFFFFFFFF); Size = PciRead32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET)); @@ -135,8 +135,8 @@ InitializeUfsHcPeim ( // Memory space: anywhere in 64 bit address space // MmioSize = Size & 0xFFFFFFF0; - PciWrite32 (PCI_LIB_ADDRESS(Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4), 0xFFFFFFFF); - Size = PciRead32 (PCI_LIB_ADDRESS(Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4)); + PciWrite32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4), 0xFFFFFFFF); + Size = PciRead32 (PCI_LIB_ADDRESS (Bus, Device, Function, PCI_BASE_ADDRESSREG_OFFSET + 4)); // // Fix the length to support some specific 64 bit BAR @@ -146,7 +146,7 @@ InitializeUfsHcPeim ( // // Calculate the size of 64bit bar // - MmioSize |= LShiftU64 ((UINT64) Size, 32); + MmioSize |= LShiftU64 ((UINT64)Size, 32); MmioSize = (~(MmioSize)) + 1; // @@ -160,7 +160,8 @@ InitializeUfsHcPeim ( // ASSERT (FALSE); continue; - }; + } + // // Assign resource to the Ufs Pci host controller's MMIO BAR. // Enable the Ufs Pci host controller by setting BME and MSE bits of PCI_CMD register. diff --git a/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.h b/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.h index 48b42b8833..c04c84e524 100644 --- a/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.h +++ b/MdeModulePkg/Bus/Pci/UfsPciHcPei/UfsPciHcPei.h @@ -21,15 +21,15 @@ #include #include -#define UFS_HC_PEI_SIGNATURE SIGNATURE_32 ('U', 'F', 'S', 'P') -#define MAX_UFS_HCS 8 +#define UFS_HC_PEI_SIGNATURE SIGNATURE_32 ('U', 'F', 'S', 'P') +#define MAX_UFS_HCS 8 typedef struct { - UINTN Signature; - EDKII_UFS_HOST_CONTROLLER_PPI UfsHostControllerPpi; - EFI_PEI_PPI_DESCRIPTOR PpiList; - UINTN TotalUfsHcs; - UINTN UfsHcPciAddr[MAX_UFS_HCS]; + UINTN Signature; + EDKII_UFS_HOST_CONTROLLER_PPI UfsHostControllerPpi; + EFI_PEI_PPI_DESCRIPTOR PpiList; + UINTN TotalUfsHcs; + UINTN UfsHcPciAddr[MAX_UFS_HCS]; } UFS_HC_PEI_PRIVATE_DATA; #define UFS_HC_PEI_PRIVATE_DATA_FROM_THIS(a) CR (a, UFS_HC_PEI_PRIVATE_DATA, UfsHostControllerPpi, UFS_HC_PEI_SIGNATURE) @@ -48,9 +48,9 @@ typedef struct { EFI_STATUS EFIAPI GetUfsHcMmioBar ( - IN EDKII_UFS_HOST_CONTROLLER_PPI *This, - IN UINT8 ControllerId, - OUT UINTN *MmioBar + IN EDKII_UFS_HOST_CONTROLLER_PPI *This, + IN UINT8 ControllerId, + OUT UINTN *MmioBar ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.c index 572c11c287..7c398cb55a 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.c @@ -8,7 +8,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - // // EFI Component Name Protocol // @@ -22,19 +21,17 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUhciComponentName = // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUhciComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UhciComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UhciComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUhciComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UhciComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UhciComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUhciDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUhciDriverNameTable[] = { { "eng;en", L"Usb Uhci Driver" }, - { NULL, NULL } + { NULL, NULL } }; - // // EFI Component Name Functions // @@ -166,16 +163,16 @@ UhciComponentNameGetDriverName ( EFI_STATUS EFIAPI UhciComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - USB_HC_DEV *UhciDev; - EFI_USB2_HC_PROTOCOL *Usb2Hc; + EFI_STATUS Status; + USB_HC_DEV *UhciDev; + EFI_USB2_HC_PROTOCOL *Usb2Hc; // // This is a device driver, so ChildHandle must be NULL. @@ -202,7 +199,7 @@ UhciComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, gUhciDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -221,5 +218,4 @@ UhciComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gUhciComponentName) ); - } diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.h b/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.h index c3b5674e9e..7e6ee93869 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/ComponentName.h @@ -57,7 +57,6 @@ UhciComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -129,11 +128,11 @@ UhciComponentNameGetDriverName ( EFI_STATUS EFIAPI UhciComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c index 9f78f3dbd3..48741085e5 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.c @@ -9,8 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - -EFI_DRIVER_BINDING_PROTOCOL gUhciDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUhciDriverBinding = { UhciDriverBindingSupported, UhciDriverBindingStart, UhciDriverBindingStop, @@ -35,15 +34,16 @@ EFI_DRIVER_BINDING_PROTOCOL gUhciDriverBinding = { EFI_STATUS EFIAPI Uhci2Reset ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT16 Attributes + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT16 Attributes ) { - USB_HC_DEV *Uhc; - EFI_TPL OldTpl; + USB_HC_DEV *Uhc; + EFI_TPL OldTpl; if ((Attributes == EFI_USB_HC_RESET_GLOBAL_WITH_DEBUG) || - (Attributes == EFI_USB_HC_RESET_HOST_WITH_DEBUG)) { + (Attributes == EFI_USB_HC_RESET_HOST_WITH_DEBUG)) + { return EFI_UNSUPPORTED; } @@ -60,38 +60,38 @@ Uhci2Reset ( ); } - OldTpl = gBS->RaiseTPL (UHCI_TPL); + OldTpl = gBS->RaiseTPL (UHCI_TPL); switch (Attributes) { - case EFI_USB_HC_RESET_GLOBAL: - // - // Stop schedule and set the Global Reset bit in the command register - // - UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); - UhciSetRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_GRESET); + case EFI_USB_HC_RESET_GLOBAL: + // + // Stop schedule and set the Global Reset bit in the command register + // + UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); + UhciSetRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_GRESET); - gBS->Stall (UHC_ROOT_PORT_RESET_STALL); + gBS->Stall (UHC_ROOT_PORT_RESET_STALL); - // - // Clear the Global Reset bit to zero. - // - UhciClearRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_GRESET); + // + // Clear the Global Reset bit to zero. + // + UhciClearRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_GRESET); - gBS->Stall (UHC_ROOT_PORT_RECOVERY_STALL); - break; + gBS->Stall (UHC_ROOT_PORT_RECOVERY_STALL); + break; - case EFI_USB_HC_RESET_HOST_CONTROLLER: - // - // Stop schedule and set Host Controller Reset bit to 1 - // - UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); - UhciSetRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_HCRESET); + case EFI_USB_HC_RESET_HOST_CONTROLLER: + // + // Stop schedule and set Host Controller Reset bit to 1 + // + UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); + UhciSetRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_HCRESET); - gBS->Stall (UHC_ROOT_PORT_RECOVERY_STALL); - break; + gBS->Stall (UHC_ROOT_PORT_RECOVERY_STALL); + break; - default: - goto ON_INVAILD_PARAMETER; + default: + goto ON_INVAILD_PARAMETER; } // @@ -113,7 +113,6 @@ ON_INVAILD_PARAMETER: return EFI_INVALID_PARAMETER; } - /** Retrieves current state of the USB host controller according to UEFI 2.0 spec. @@ -128,29 +127,27 @@ ON_INVAILD_PARAMETER: EFI_STATUS EFIAPI Uhci2GetState ( - IN EFI_USB2_HC_PROTOCOL *This, - OUT EFI_USB_HC_STATE *State + IN EFI_USB2_HC_PROTOCOL *This, + OUT EFI_USB_HC_STATE *State ) { - USB_HC_DEV *Uhc; - UINT16 UsbSts; - UINT16 UsbCmd; + USB_HC_DEV *Uhc; + UINT16 UsbSts; + UINT16 UsbCmd; if (State == NULL) { return EFI_INVALID_PARAMETER; } - Uhc = UHC_FROM_USB2_HC_PROTO (This); + Uhc = UHC_FROM_USB2_HC_PROTO (This); - UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); - UsbSts = UhciReadReg (Uhc->PciIo, USBSTS_OFFSET); + UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); + UsbSts = UhciReadReg (Uhc->PciIo, USBSTS_OFFSET); - if ((UsbCmd & USBCMD_EGSM) !=0 ) { + if ((UsbCmd & USBCMD_EGSM) != 0 ) { *State = EfiUsbHcStateSuspend; - } else if ((UsbSts & USBSTS_HCH) != 0) { *State = EfiUsbHcStateHalt; - } else { *State = EfiUsbHcStateOperational; } @@ -158,7 +155,6 @@ Uhci2GetState ( return EFI_SUCCESS; } - /** Sets the USB host controller to a specific state according to UEFI 2.0 spec. @@ -174,18 +170,18 @@ Uhci2GetState ( EFI_STATUS EFIAPI Uhci2SetState ( - IN EFI_USB2_HC_PROTOCOL *This, - IN EFI_USB_HC_STATE State + IN EFI_USB2_HC_PROTOCOL *This, + IN EFI_USB_HC_STATE State ) { - EFI_USB_HC_STATE CurState; - USB_HC_DEV *Uhc; - EFI_TPL OldTpl; - EFI_STATUS Status; - UINT16 UsbCmd; + EFI_USB_HC_STATE CurState; + USB_HC_DEV *Uhc; + EFI_TPL OldTpl; + EFI_STATUS Status; + UINT16 UsbCmd; - Uhc = UHC_FROM_USB2_HC_PROTO (This); - Status = Uhci2GetState (This, &CurState); + Uhc = UHC_FROM_USB2_HC_PROTO (This); + Status = Uhci2GetState (This, &CurState); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -195,69 +191,68 @@ Uhci2SetState ( return EFI_SUCCESS; } - Status = EFI_SUCCESS; - OldTpl = gBS->RaiseTPL (UHCI_TPL); + Status = EFI_SUCCESS; + OldTpl = gBS->RaiseTPL (UHCI_TPL); switch (State) { - case EfiUsbHcStateHalt: - Status = UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); - break; - - case EfiUsbHcStateOperational: - UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); + case EfiUsbHcStateHalt: + Status = UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); + break; - if (CurState == EfiUsbHcStateHalt) { - // - // Set Run/Stop bit to 1, also set the bandwidht reclamation - // point to 64 bytes - // - UsbCmd |= USBCMD_RS | USBCMD_MAXP; - UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); + case EfiUsbHcStateOperational: + UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); - } else if (CurState == EfiUsbHcStateSuspend) { - // - // If FGR(Force Global Resume) bit is 0, set it - // - if ((UsbCmd & USBCMD_FGR) == 0) { - UsbCmd |= USBCMD_FGR; + if (CurState == EfiUsbHcStateHalt) { + // + // Set Run/Stop bit to 1, also set the bandwidht reclamation + // point to 64 bytes + // + UsbCmd |= USBCMD_RS | USBCMD_MAXP; + UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); + } else if (CurState == EfiUsbHcStateSuspend) { + // + // If FGR(Force Global Resume) bit is 0, set it + // + if ((UsbCmd & USBCMD_FGR) == 0) { + UsbCmd |= USBCMD_FGR; + UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); + } + + // + // wait 20ms to let resume complete (20ms is specified by UHCI spec) + // + gBS->Stall (UHC_FORCE_GLOBAL_RESUME_STALL); + + // + // Write FGR bit to 0 and EGSM(Enter Global Suspend Mode) bit to 0 + // + UsbCmd &= ~USBCMD_FGR; + UsbCmd &= ~USBCMD_EGSM; + UsbCmd |= USBCMD_RS; UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); } - // - // wait 20ms to let resume complete (20ms is specified by UHCI spec) - // - gBS->Stall (UHC_FORCE_GLOBAL_RESUME_STALL); + break; + + case EfiUsbHcStateSuspend: + Status = Uhci2SetState (This, EfiUsbHcStateHalt); + + if (EFI_ERROR (Status)) { + Status = EFI_DEVICE_ERROR; + goto ON_EXIT; + } // - // Write FGR bit to 0 and EGSM(Enter Global Suspend Mode) bit to 0 + // Set Enter Global Suspend Mode bit to 1. // - UsbCmd &= ~USBCMD_FGR; - UsbCmd &= ~USBCMD_EGSM; - UsbCmd |= USBCMD_RS; + UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); + UsbCmd |= USBCMD_EGSM; UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); - } - - break; - - case EfiUsbHcStateSuspend: - Status = Uhci2SetState (This, EfiUsbHcStateHalt); - - if (EFI_ERROR (Status)) { - Status = EFI_DEVICE_ERROR; - goto ON_EXIT; - } - - // - // Set Enter Global Suspend Mode bit to 1. - // - UsbCmd = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); - UsbCmd |= USBCMD_EGSM; - UhciWriteReg (Uhc->PciIo, USBCMD_OFFSET, UsbCmd); - break; + break; - default: - Status = EFI_INVALID_PARAMETER; - break; + default: + Status = EFI_INVALID_PARAMETER; + break; } ON_EXIT: @@ -289,10 +284,10 @@ Uhci2GetCapability ( OUT UINT8 *Is64BitCapable ) { - USB_HC_DEV *Uhc; - UINT32 Offset; - UINT16 PortSC; - UINT32 Index; + USB_HC_DEV *Uhc; + UINT32 Offset; + UINT16 PortSC; + UINT32 Index; Uhc = UHC_FROM_USB2_HC_PROTO (This); @@ -301,13 +296,13 @@ Uhci2GetCapability ( } *MaxSpeed = EFI_USB_SPEED_FULL; - *Is64BitCapable = (UINT8) FALSE; + *Is64BitCapable = (UINT8)FALSE; *PortNumber = 0; for (Index = 0; Index < USB_MAX_ROOTHUB_PORT; Index++) { - Offset = USBPORTSC_OFFSET + Index * 2; - PortSC = UhciReadReg (Uhc->PciIo, Offset); + Offset = USBPORTSC_OFFSET + Index * 2; + PortSC = UhciReadReg (Uhc->PciIo, Offset); // // Port status's bit 7 is reserved and always returns 1 if @@ -318,6 +313,7 @@ Uhci2GetCapability ( if (((PortSC & 0x80) == 0) || (PortSC == 0xFFFF)) { break; } + (*PortNumber)++; } @@ -327,7 +323,6 @@ Uhci2GetCapability ( return EFI_SUCCESS; } - /** Retrieves the current status of a USB root hub port according to UEFI 2.0 spec. @@ -344,14 +339,14 @@ Uhci2GetCapability ( EFI_STATUS EFIAPI Uhci2GetRootHubPortStatus ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 PortNumber, - OUT EFI_USB_PORT_STATUS *PortStatus + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 PortNumber, + OUT EFI_USB_PORT_STATUS *PortStatus ) { - USB_HC_DEV *Uhc; - UINT32 Offset; - UINT16 PortSC; + USB_HC_DEV *Uhc; + UINT32 Offset; + UINT16 PortSC; Uhc = UHC_FROM_USB2_HC_PROTO (This); @@ -363,11 +358,11 @@ Uhci2GetRootHubPortStatus ( return EFI_INVALID_PARAMETER; } - Offset = USBPORTSC_OFFSET + PortNumber * 2; - PortStatus->PortStatus = 0; - PortStatus->PortChangeStatus = 0; + Offset = USBPORTSC_OFFSET + PortNumber * 2; + PortStatus->PortStatus = 0; + PortStatus->PortChangeStatus = 0; - PortSC = UhciReadReg (Uhc->PciIo, Offset); + PortSC = UhciReadReg (Uhc->PciIo, Offset); if ((PortSC & USBPORTSC_CCS) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_CONNECTION; @@ -406,7 +401,6 @@ Uhci2GetRootHubPortStatus ( return EFI_SUCCESS; } - /** Sets a feature for the specified root hub port according to UEFI 2.0 spec. @@ -424,16 +418,16 @@ Uhci2GetRootHubPortStatus ( EFI_STATUS EFIAPI Uhci2SetRootHubPortFeature ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_HC_DEV *Uhc; - EFI_TPL OldTpl; - UINT32 Offset; - UINT16 PortSC; - UINT16 Command; + USB_HC_DEV *Uhc; + EFI_TPL OldTpl; + UINT32 Offset; + UINT16 PortSC; + UINT16 Command; Uhc = UHC_FROM_USB2_HC_PROTO (This); @@ -441,42 +435,43 @@ Uhci2SetRootHubPortFeature ( return EFI_INVALID_PARAMETER; } - Offset = USBPORTSC_OFFSET + PortNumber * 2; + Offset = USBPORTSC_OFFSET + PortNumber * 2; - OldTpl = gBS->RaiseTPL (UHCI_TPL); - PortSC = UhciReadReg (Uhc->PciIo, Offset); + OldTpl = gBS->RaiseTPL (UHCI_TPL); + PortSC = UhciReadReg (Uhc->PciIo, Offset); switch (PortFeature) { - case EfiUsbPortSuspend: - Command = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); - if ((Command & USBCMD_EGSM) == 0) { - // - // if global suspend is not active, can set port suspend - // - PortSC &= 0xfff5; - PortSC |= USBPORTSC_SUSP; - } - break; + case EfiUsbPortSuspend: + Command = UhciReadReg (Uhc->PciIo, USBCMD_OFFSET); + if ((Command & USBCMD_EGSM) == 0) { + // + // if global suspend is not active, can set port suspend + // + PortSC &= 0xfff5; + PortSC |= USBPORTSC_SUSP; + } - case EfiUsbPortReset: - PortSC &= 0xfff5; - PortSC |= USBPORTSC_PR; - break; + break; - case EfiUsbPortPower: - // - // No action - // - break; + case EfiUsbPortReset: + PortSC &= 0xfff5; + PortSC |= USBPORTSC_PR; + break; - case EfiUsbPortEnable: - PortSC &= 0xfff5; - PortSC |= USBPORTSC_PED; - break; + case EfiUsbPortPower: + // + // No action + // + break; - default: - gBS->RestoreTPL (OldTpl); - return EFI_INVALID_PARAMETER; + case EfiUsbPortEnable: + PortSC &= 0xfff5; + PortSC |= USBPORTSC_PED; + break; + + default: + gBS->RestoreTPL (OldTpl); + return EFI_INVALID_PARAMETER; } UhciWriteReg (Uhc->PciIo, Offset, PortSC); @@ -485,7 +480,6 @@ Uhci2SetRootHubPortFeature ( return EFI_SUCCESS; } - /** Clears a feature for the specified root hub port according to Uefi 2.0 spec. @@ -503,15 +497,15 @@ Uhci2SetRootHubPortFeature ( EFI_STATUS EFIAPI Uhci2ClearRootHubPortFeature ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_HC_DEV *Uhc; - EFI_TPL OldTpl; - UINT32 Offset; - UINT16 PortSC; + USB_HC_DEV *Uhc; + EFI_TPL OldTpl; + UINT32 Offset; + UINT16 PortSC; Uhc = UHC_FROM_USB2_HC_PROTO (This); @@ -519,67 +513,67 @@ Uhci2ClearRootHubPortFeature ( return EFI_INVALID_PARAMETER; } - Offset = USBPORTSC_OFFSET + PortNumber * 2; + Offset = USBPORTSC_OFFSET + PortNumber * 2; - OldTpl = gBS->RaiseTPL (UHCI_TPL); - PortSC = UhciReadReg (Uhc->PciIo, Offset); + OldTpl = gBS->RaiseTPL (UHCI_TPL); + PortSC = UhciReadReg (Uhc->PciIo, Offset); switch (PortFeature) { - case EfiUsbPortEnable: - PortSC &= 0xfff5; - PortSC &= ~USBPORTSC_PED; - break; + case EfiUsbPortEnable: + PortSC &= 0xfff5; + PortSC &= ~USBPORTSC_PED; + break; - case EfiUsbPortSuspend: - // - // Cause a resume on the specified port if in suspend mode. - // - PortSC &= 0xfff5; - PortSC &= ~USBPORTSC_SUSP; - break; + case EfiUsbPortSuspend: + // + // Cause a resume on the specified port if in suspend mode. + // + PortSC &= 0xfff5; + PortSC &= ~USBPORTSC_SUSP; + break; - case EfiUsbPortPower: - // - // No action - // - break; + case EfiUsbPortPower: + // + // No action + // + break; - case EfiUsbPortReset: - PortSC &= 0xfff5; - PortSC &= ~USBPORTSC_PR; - break; + case EfiUsbPortReset: + PortSC &= 0xfff5; + PortSC &= ~USBPORTSC_PR; + break; - case EfiUsbPortConnectChange: - PortSC &= 0xfff5; - PortSC |= USBPORTSC_CSC; - break; + case EfiUsbPortConnectChange: + PortSC &= 0xfff5; + PortSC |= USBPORTSC_CSC; + break; - case EfiUsbPortEnableChange: - PortSC &= 0xfff5; - PortSC |= USBPORTSC_PEDC; - break; + case EfiUsbPortEnableChange: + PortSC &= 0xfff5; + PortSC |= USBPORTSC_PEDC; + break; - case EfiUsbPortSuspendChange: - // - // Root hub does not support this - // - break; + case EfiUsbPortSuspendChange: + // + // Root hub does not support this + // + break; - case EfiUsbPortOverCurrentChange: - // - // Root hub does not support this - // - break; + case EfiUsbPortOverCurrentChange: + // + // Root hub does not support this + // + break; - case EfiUsbPortResetChange: - // - // Root hub does not support this - // - break; + case EfiUsbPortResetChange: + // + // Root hub does not support this + // + break; - default: - gBS->RestoreTPL (OldTpl); - return EFI_INVALID_PARAMETER; + default: + gBS->RestoreTPL (OldTpl); + return EFI_INVALID_PARAMETER; } UhciWriteReg (Uhc->PciIo, Offset, PortSC); @@ -588,7 +582,6 @@ Uhci2ClearRootHubPortFeature ( return EFI_SUCCESS; } - /** Submits control transfer to a target USB device according to UEFI 2.0 spec. @@ -614,45 +607,45 @@ Uhci2ClearRootHubPortFeature ( EFI_STATUS EFIAPI Uhci2ControlTransfer ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 DeviceAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN EFI_USB_DEVICE_REQUEST *Request, - IN EFI_USB_DATA_DIRECTION TransferDirection, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN TimeOut, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION TransferDirection, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN TimeOut, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { - USB_HC_DEV *Uhc; - UHCI_TD_SW *TDs; - EFI_TPL OldTpl; - EFI_STATUS Status; - UHCI_QH_RESULT QhResult; - UINT8 PktId; - UINT8 *RequestPhy; - VOID *RequestMap; - UINT8 *DataPhy; - VOID *DataMap; - BOOLEAN IsSlowDevice; - UINTN TransferDataLength; - - Uhc = UHC_FROM_USB2_HC_PROTO (This); - TDs = NULL; - DataPhy = NULL; - DataMap = NULL; - RequestPhy = NULL; - RequestMap = NULL; - - IsSlowDevice = (BOOLEAN) ((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); + USB_HC_DEV *Uhc; + UHCI_TD_SW *TDs; + EFI_TPL OldTpl; + EFI_STATUS Status; + UHCI_QH_RESULT QhResult; + UINT8 PktId; + UINT8 *RequestPhy; + VOID *RequestMap; + UINT8 *DataPhy; + VOID *DataMap; + BOOLEAN IsSlowDevice; + UINTN TransferDataLength; + + Uhc = UHC_FROM_USB2_HC_PROTO (This); + TDs = NULL; + DataPhy = NULL; + DataMap = NULL; + RequestPhy = NULL; + RequestMap = NULL; + + IsSlowDevice = (BOOLEAN)((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); // // Parameters Checking // - if (Request == NULL || TransferResult == NULL) { + if ((Request == NULL) || (TransferResult == NULL)) { return EFI_INVALID_PARAMETER; } @@ -661,12 +654,12 @@ Uhci2ControlTransfer ( } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && - (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) { - + (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) + { return EFI_INVALID_PARAMETER; } - if ((TransferDirection != EfiUsbNoData) && (Data == NULL || DataLength == NULL)) { + if ((TransferDirection != EfiUsbNoData) && ((Data == NULL) || (DataLength == NULL))) { return EFI_INVALID_PARAMETER; } @@ -712,12 +705,12 @@ Uhci2ControlTransfer ( Uhc, DeviceAddress, PktId, - (UINT8*)Request, + (UINT8 *)Request, RequestPhy, - (UINT8*)Data, + (UINT8 *)Data, DataPhy, TransferDataLength, - (UINT8) MaximumPacketLength, + (UINT8)MaximumPacketLength, IsSlowDevice ); @@ -754,7 +747,6 @@ ON_EXIT: return Status; } - /** Submits bulk transfer to a bulk endpoint of a USB device. @@ -782,18 +774,18 @@ ON_EXIT: EFI_STATUS EFIAPI Uhci2BulkTransfer ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN UINT8 DataBuffersNumber, - IN OUT VOID *Data[EFI_USB_MAX_BULK_BUFFER_NUM], - IN OUT UINTN *DataLength, - IN OUT UINT8 *DataToggle, - IN UINTN TimeOut, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN UINT8 DataBuffersNumber, + IN OUT VOID *Data[EFI_USB_MAX_BULK_BUFFER_NUM], + IN OUT UINTN *DataLength, + IN OUT UINT8 *DataToggle, + IN UINTN TimeOut, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { EFI_USB_DATA_DIRECTION Direction; @@ -824,7 +816,8 @@ Uhci2BulkTransfer ( } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && - (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) { + (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) + { return EFI_INVALID_PARAMETER; } @@ -869,7 +862,7 @@ Uhci2BulkTransfer ( DataPhy, *DataLength, DataToggle, - (UINT8) MaximumPacketLength, + (UINT8)MaximumPacketLength, FALSE ); @@ -878,7 +871,6 @@ Uhci2BulkTransfer ( goto ON_EXIT; } - // // Link the TDs to bulk queue head. According to the platfore // defintion of UHCI_NO_BW_RECLAMATION, BulkQh is either configured @@ -904,7 +896,6 @@ ON_EXIT: return Status; } - /** Submits an asynchronous interrupt transfer to an interrupt endpoint of a USB device according to UEFI 2.0 spec. @@ -932,37 +923,37 @@ ON_EXIT: EFI_STATUS EFIAPI Uhci2AsyncInterruptTransfer ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN BOOLEAN IsNewTransfer, - IN OUT UINT8 *DataToggle, - IN UINTN PollingInterval, - IN UINTN DataLength, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK CallBackFunction, - IN VOID *Context + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN BOOLEAN IsNewTransfer, + IN OUT UINT8 *DataToggle, + IN UINTN PollingInterval, + IN UINTN DataLength, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK CallBackFunction, + IN VOID *Context ) { - USB_HC_DEV *Uhc; - BOOLEAN IsSlowDevice; - UHCI_QH_SW *Qh; - UHCI_TD_SW *IntTds; - EFI_TPL OldTpl; - EFI_STATUS Status; - UINT8 *DataPtr; - UINT8 *DataPhy; - UINT8 PktId; - - Uhc = UHC_FROM_USB2_HC_PROTO (This); - Qh = NULL; - IntTds = NULL; - DataPtr = NULL; - DataPhy = NULL; - - IsSlowDevice = (BOOLEAN) ((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); + USB_HC_DEV *Uhc; + BOOLEAN IsSlowDevice; + UHCI_QH_SW *Qh; + UHCI_TD_SW *IntTds; + EFI_TPL OldTpl; + EFI_STATUS Status; + UINT8 *DataPtr; + UINT8 *DataPhy; + UINT8 PktId; + + Uhc = UHC_FROM_USB2_HC_PROTO (This); + Qh = NULL; + IntTds = NULL; + DataPtr = NULL; + DataPhy = NULL; + + IsSlowDevice = (BOOLEAN)((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); if ((EndPointAddress & 0x80) == 0) { return EFI_INVALID_PARAMETER; @@ -979,7 +970,7 @@ Uhci2AsyncInterruptTransfer ( return Status; } - if (PollingInterval < 1 || PollingInterval > 255) { + if ((PollingInterval < 1) || (PollingInterval > 255)) { return EFI_INVALID_PARAMETER; } @@ -1016,7 +1007,7 @@ Uhci2AsyncInterruptTransfer ( return EFI_OUT_OF_RESOURCES; } - DataPhy = (UINT8 *) (UINTN) UsbHcGetPciAddressForHostMem (Uhc->MemPool, DataPtr, DataLength); + DataPhy = (UINT8 *)(UINTN)UsbHcGetPciAddressForHostMem (Uhc->MemPool, DataPtr, DataLength); OldTpl = gBS->RaiseTPL (UHCI_TPL); @@ -1036,7 +1027,7 @@ Uhci2AsyncInterruptTransfer ( DataPhy, DataLength, DataToggle, - (UINT8) MaximumPacketLength, + (UINT8)MaximumPacketLength, IsSlowDevice ); @@ -1113,28 +1104,28 @@ FREE_DATA: EFI_STATUS EFIAPI Uhci2SyncInterruptTransfer ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN OUT UINT8 *DataToggle, - IN UINTN TimeOut, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN OUT UINT8 *DataToggle, + IN UINTN TimeOut, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { - EFI_STATUS Status; - USB_HC_DEV *Uhc; - UHCI_TD_SW *TDs; - UHCI_QH_RESULT QhResult; - EFI_TPL OldTpl; - UINT8 *DataPhy; - VOID *DataMap; - UINT8 PktId; - BOOLEAN IsSlowDevice; + EFI_STATUS Status; + USB_HC_DEV *Uhc; + UHCI_TD_SW *TDs; + UHCI_QH_RESULT QhResult; + EFI_TPL OldTpl; + UINT8 *DataPhy; + VOID *DataMap; + UINT8 PktId; + BOOLEAN IsSlowDevice; Uhc = UHC_FROM_USB2_HC_PROTO (This); DataPhy = NULL; @@ -1145,7 +1136,7 @@ Uhci2SyncInterruptTransfer ( return EFI_INVALID_PARAMETER; } - IsSlowDevice = (BOOLEAN) ((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); + IsSlowDevice = (BOOLEAN)((EFI_USB_SPEED_LOW == DeviceSpeed) ? TRUE : FALSE); if ((DataLength == NULL) || (Data == NULL) || (TransferResult == NULL)) { return EFI_INVALID_PARAMETER; @@ -1166,7 +1157,6 @@ Uhci2SyncInterruptTransfer ( *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; - UhciAckAllInterrupt (Uhc); if (!UhciIsHcWorking (Uhc->PciIo)) { @@ -1202,7 +1192,7 @@ Uhci2SyncInterruptTransfer ( DataPhy, *DataLength, DataToggle, - (UINT8) MaximumPacketLength, + (UINT8)MaximumPacketLength, IsSlowDevice ); @@ -1213,7 +1203,6 @@ Uhci2SyncInterruptTransfer ( goto ON_EXIT; } - UhciLinkTdToQh (Uhc, Uhc->SyncIntQh, TDs); Status = UhciExecuteTransfer (Uhc, Uhc->SyncIntQh, TDs, TimeOut, IsSlowDevice, &QhResult); @@ -1233,7 +1222,6 @@ ON_EXIT: return Status; } - /** Submits isochronous transfer to a target USB device according to UEFI 2.0 spec. @@ -1255,22 +1243,21 @@ ON_EXIT: EFI_STATUS EFIAPI Uhci2IsochronousTransfer ( - IN EFI_USB2_HC_PROTOCOL *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN UINT8 DataBuffersNumber, - IN OUT VOID *Data[EFI_USB_MAX_ISO_BUFFER_NUM], - IN UINTN DataLength, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_USB2_HC_PROTOCOL *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN UINT8 DataBuffersNumber, + IN OUT VOID *Data[EFI_USB_MAX_ISO_BUFFER_NUM], + IN UINTN DataLength, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { return EFI_UNSUPPORTED; } - /** Submits Async isochronous transfer to a target USB device according to UEFI 2.0 spec. @@ -1322,8 +1309,8 @@ Uhci2AsyncIsochronousTransfer ( EFI_STATUS EFIAPI UhciDriverEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return EfiLibInstallDriverBindingComponentName2 ( @@ -1336,7 +1323,6 @@ UhciDriverEntryPoint ( ); } - /** Test to see if this driver supports ControllerHandle. Any ControllerHandle that has UsbHcProtocol installed will be supported. @@ -1352,15 +1338,15 @@ UhciDriverEntryPoint ( EFI_STATUS EFIAPI UhciDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS OpenStatus; - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - USB_CLASSC UsbClassCReg; + EFI_STATUS OpenStatus; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + USB_CLASSC UsbClassCReg; // // Test whether there is PCI IO Protocol attached on the controller handle. @@ -1368,7 +1354,7 @@ UhciDriverBindingSupported ( OpenStatus = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1397,8 +1383,8 @@ UhciDriverBindingSupported ( if ((UsbClassCReg.BaseCode != PCI_CLASS_SERIAL) || (UsbClassCReg.SubClassCode != PCI_CLASS_SERIAL_USB) || (UsbClassCReg.ProgInterface != PCI_IF_UHCI) - ) { - + ) + { Status = EFI_UNSUPPORTED; } @@ -1411,10 +1397,8 @@ ON_EXIT: ); return Status; - } - /** Allocate and initialize the empty UHCI device. @@ -1445,22 +1429,22 @@ UhciAllocateDev ( // This driver supports both USB_HC_PROTOCOL and USB2_HC_PROTOCOL. // USB_HC_PROTOCOL is for EFI 1.1 backward compability. // - Uhc->Signature = USB_HC_DEV_SIGNATURE; - Uhc->Usb2Hc.GetCapability = Uhci2GetCapability; - Uhc->Usb2Hc.Reset = Uhci2Reset; - Uhc->Usb2Hc.GetState = Uhci2GetState; - Uhc->Usb2Hc.SetState = Uhci2SetState; - Uhc->Usb2Hc.ControlTransfer = Uhci2ControlTransfer; - Uhc->Usb2Hc.BulkTransfer = Uhci2BulkTransfer; - Uhc->Usb2Hc.AsyncInterruptTransfer = Uhci2AsyncInterruptTransfer; - Uhc->Usb2Hc.SyncInterruptTransfer = Uhci2SyncInterruptTransfer; - Uhc->Usb2Hc.IsochronousTransfer = Uhci2IsochronousTransfer; - Uhc->Usb2Hc.AsyncIsochronousTransfer = Uhci2AsyncIsochronousTransfer; - Uhc->Usb2Hc.GetRootHubPortStatus = Uhci2GetRootHubPortStatus; - Uhc->Usb2Hc.SetRootHubPortFeature = Uhci2SetRootHubPortFeature; - Uhc->Usb2Hc.ClearRootHubPortFeature = Uhci2ClearRootHubPortFeature; - Uhc->Usb2Hc.MajorRevision = 0x1; - Uhc->Usb2Hc.MinorRevision = 0x1; + Uhc->Signature = USB_HC_DEV_SIGNATURE; + Uhc->Usb2Hc.GetCapability = Uhci2GetCapability; + Uhc->Usb2Hc.Reset = Uhci2Reset; + Uhc->Usb2Hc.GetState = Uhci2GetState; + Uhc->Usb2Hc.SetState = Uhci2SetState; + Uhc->Usb2Hc.ControlTransfer = Uhci2ControlTransfer; + Uhc->Usb2Hc.BulkTransfer = Uhci2BulkTransfer; + Uhc->Usb2Hc.AsyncInterruptTransfer = Uhci2AsyncInterruptTransfer; + Uhc->Usb2Hc.SyncInterruptTransfer = Uhci2SyncInterruptTransfer; + Uhc->Usb2Hc.IsochronousTransfer = Uhci2IsochronousTransfer; + Uhc->Usb2Hc.AsyncIsochronousTransfer = Uhci2AsyncIsochronousTransfer; + Uhc->Usb2Hc.GetRootHubPortStatus = Uhci2GetRootHubPortStatus; + Uhc->Usb2Hc.SetRootHubPortFeature = Uhci2SetRootHubPortFeature; + Uhc->Usb2Hc.ClearRootHubPortFeature = Uhci2ClearRootHubPortFeature; + Uhc->Usb2Hc.MajorRevision = 0x1; + Uhc->Usb2Hc.MinorRevision = 0x1; Uhc->PciIo = PciIo; Uhc->DevicePath = DevicePath; @@ -1494,7 +1478,6 @@ ON_ERROR: return NULL; } - /** Free the UHCI device and release its associated resources. @@ -1503,7 +1486,7 @@ ON_ERROR: **/ VOID UhciFreeDev ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { if (Uhc->AsyncIntMonitor != NULL) { @@ -1525,7 +1508,6 @@ UhciFreeDev ( FreePool (Uhc); } - /** Uninstall all Uhci Interface. @@ -1535,26 +1517,25 @@ UhciFreeDev ( **/ VOID UhciCleanDevUp ( - IN EFI_HANDLE Controller, - IN EFI_USB2_HC_PROTOCOL *This + IN EFI_HANDLE Controller, + IN EFI_USB2_HC_PROTOCOL *This ) { - USB_HC_DEV *Uhc; - EFI_STATUS Status; + USB_HC_DEV *Uhc; + EFI_STATUS Status; // // Uninstall the USB_HC and USB_HC2 protocol, then disable the controller // Uhc = UHC_FROM_USB2_HC_PROTO (This); - Status = gBS->UninstallProtocolInterface ( Controller, &gEfiUsb2HcProtocolGuid, &Uhc->Usb2Hc ); if (EFI_ERROR (Status)) { - return ; + return; } UhciStopHc (Uhc, UHC_GENERIC_TIMEOUT); @@ -1565,11 +1546,11 @@ UhciCleanDevUp ( // Restore original PCI attributes // Uhc->PciIo->Attributes ( - Uhc->PciIo, - EfiPciIoAttributeOperationSet, - Uhc->OriginalPciAttributes, - NULL - ); + Uhc->PciIo, + EfiPciIoAttributeOperationSet, + Uhc->OriginalPciAttributes, + NULL + ); UhciFreeDev (Uhc); } @@ -1584,13 +1565,13 @@ UhciCleanDevUp ( VOID EFIAPI UhcExitBootService ( - EFI_EVENT Event, - VOID *Context + EFI_EVENT Event, + VOID *Context ) { - USB_HC_DEV *Uhc; + USB_HC_DEV *Uhc; - Uhc = (USB_HC_DEV *) Context; + Uhc = (USB_HC_DEV *)Context; // // Stop the Host Controller @@ -1620,27 +1601,27 @@ UhcExitBootService ( EFI_STATUS EFIAPI UhciDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - USB_HC_DEV *Uhc; - UINT64 Supports; - UINT64 OriginalPciAttributes; - BOOLEAN PciAttributesSaved; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + USB_HC_DEV *Uhc; + UINT64 Supports; + UINT64 OriginalPciAttributes; + BOOLEAN PciAttributesSaved; EFI_DEVICE_PATH_PROTOCOL *HcDevicePath; // // Open PCIIO, then enable the EHC device and turn off emulation // - Uhc = NULL; + Uhc = NULL; Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1654,14 +1635,14 @@ UhciDriverBindingStart ( // Open Device Path Protocol for on USB host controller // HcDevicePath = NULL; - Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &HcDevicePath, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&HcDevicePath, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); PciAttributesSaved = FALSE; // @@ -1677,6 +1658,7 @@ UhciDriverBindingStart ( if (EFI_ERROR (Status)) { goto CLOSE_PCIIO; } + PciAttributesSaved = TRUE; // @@ -1695,12 +1677,12 @@ UhciDriverBindingStart ( ); if (!EFI_ERROR (Status)) { Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE; - Status = PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationEnable, - Supports, - NULL - ); + Status = PciIo->Attributes ( + PciIo, + EfiPciIoAttributeOperationEnable, + Supports, + NULL + ); } if (EFI_ERROR (Status)) { @@ -1783,7 +1765,6 @@ UhciDriverBindingStart ( FALSE ); - // // Start the UHCI hardware, also set its reclamation point to 64 bytes // @@ -1808,24 +1789,23 @@ CLOSE_PCIIO: // Restore original PCI attributes // PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationSet, - OriginalPciAttributes, - NULL - ); + PciIo, + EfiPciIoAttributeOperationSet, + OriginalPciAttributes, + NULL + ); } gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return Status; } - /** Stop this driver on ControllerHandle. Support stopping any child handles created by this driver. @@ -1842,19 +1822,19 @@ CLOSE_PCIIO: EFI_STATUS EFIAPI UhciDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_USB2_HC_PROTOCOL *Usb2Hc; EFI_STATUS Status; - Status = gBS->OpenProtocol ( + Status = gBS->OpenProtocol ( Controller, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1872,11 +1852,11 @@ UhciDriverBindingStop ( UhciCleanDevUp (Controller, Usb2Hc); gBS->CloseProtocol ( - Controller, - &gEfiPciIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiPciIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_SUCCESS; } diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.h b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.h index 882f5e55ea..138623ed6b 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/Uhci.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_UHCI_H_ #define _EFI_UHCI_H_ - #include #include @@ -31,7 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -typedef struct _USB_HC_DEV USB_HC_DEV; +typedef struct _USB_HC_DEV USB_HC_DEV; #include "UsbHcMem.h" #include "UhciQueue.h" @@ -44,20 +43,20 @@ typedef struct _USB_HC_DEV USB_HC_DEV; // UHC timeout experience values // -#define UHC_1_MICROSECOND 1 -#define UHC_1_MILLISECOND (1000 * UHC_1_MICROSECOND) -#define UHC_1_SECOND (1000 * UHC_1_MILLISECOND) +#define UHC_1_MICROSECOND 1 +#define UHC_1_MILLISECOND (1000 * UHC_1_MICROSECOND) +#define UHC_1_SECOND (1000 * UHC_1_MILLISECOND) // // UHCI register operation timeout, set by experience // -#define UHC_GENERIC_TIMEOUT UHC_1_SECOND +#define UHC_GENERIC_TIMEOUT UHC_1_SECOND // // Wait for force global resume(FGR) complete, refers to // specification[UHCI11-2.1.1] // -#define UHC_FORCE_GLOBAL_RESUME_STALL (20 * UHC_1_MILLISECOND) +#define UHC_FORCE_GLOBAL_RESUME_STALL (20 * UHC_1_MILLISECOND) // // Wait for roothub port reset and recovery, reset stall @@ -71,22 +70,22 @@ typedef struct _USB_HC_DEV USB_HC_DEV; // Sync and Async transfer polling interval, set by experience, // and the unit of Async is 100us. // -#define UHC_SYNC_POLL_INTERVAL (1 * UHC_1_MILLISECOND) -#define UHC_ASYNC_POLL_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) +#define UHC_SYNC_POLL_INTERVAL (1 * UHC_1_MILLISECOND) +#define UHC_ASYNC_POLL_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) // // UHC raises TPL to TPL_NOTIFY to serialize all its operations // to protect shared data structures. // -#define UHCI_TPL TPL_NOTIFY +#define UHCI_TPL TPL_NOTIFY -#define USB_HC_DEV_SIGNATURE SIGNATURE_32 ('u', 'h', 'c', 'i') +#define USB_HC_DEV_SIGNATURE SIGNATURE_32 ('u', 'h', 'c', 'i') #pragma pack(1) typedef struct { - UINT8 ProgInterface; - UINT8 SubClassCode; - UINT8 BaseCode; + UINT8 ProgInterface; + UINT8 SubClassCode; + UINT8 BaseCode; } USB_CLASSC; #pragma pack() @@ -104,20 +103,20 @@ typedef struct { // device requires this bandwidth reclamation capability. // struct _USB_HC_DEV { - UINT32 Signature; - EFI_USB2_HC_PROTOCOL Usb2Hc; - EFI_PCI_IO_PROTOCOL *PciIo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINT64 OriginalPciAttributes; + UINT32 Signature; + EFI_USB2_HC_PROTOCOL Usb2Hc; + EFI_PCI_IO_PROTOCOL *PciIo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINT64 OriginalPciAttributes; // // Schedule data structures // - UINT32 *FrameBase; // the buffer pointed by this pointer is used to store pci bus address of the QH descriptor. - UINT32 *FrameBaseHostAddr; // the buffer pointed by this pointer is used to store host memory address of the QH descriptor. - UHCI_QH_SW *SyncIntQh; - UHCI_QH_SW *CtrlQh; - UHCI_QH_SW *BulkQh; + UINT32 *FrameBase; // the buffer pointed by this pointer is used to store pci bus address of the QH descriptor. + UINT32 *FrameBaseHostAddr; // the buffer pointed by this pointer is used to store host memory address of the QH descriptor. + UHCI_QH_SW *SyncIntQh; + UHCI_QH_SW *CtrlQh; + UHCI_QH_SW *BulkQh; // // Structures to maintain asynchronus interrupt transfers. @@ -127,22 +126,21 @@ struct _USB_HC_DEV { // released in two steps using Recycle and RecycleWait. // Check the asynchronous interrupt management routines. // - LIST_ENTRY AsyncIntList; - EFI_EVENT AsyncIntMonitor; - UHCI_ASYNC_REQUEST *Recycle; - UHCI_ASYNC_REQUEST *RecycleWait; - + LIST_ENTRY AsyncIntList; + EFI_EVENT AsyncIntMonitor; + UHCI_ASYNC_REQUEST *Recycle; + UHCI_ASYNC_REQUEST *RecycleWait; - UINTN RootPorts; - USBHC_MEM_POOL *MemPool; - EFI_UNICODE_STRING_TABLE *CtrlNameTable; - VOID *FrameMapping; + UINTN RootPorts; + USBHC_MEM_POOL *MemPool; + EFI_UNICODE_STRING_TABLE *CtrlNameTable; + VOID *FrameMapping; // // ExitBootServicesEvent is used to stop the EHC DMA operation // after exit boot service. // - EFI_EVENT ExitBootServiceEvent; + EFI_EVENT ExitBootServiceEvent; }; extern EFI_DRIVER_BINDING_PROTOCOL gUhciDriverBinding; @@ -164,9 +162,9 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gUhciComponentName2; EFI_STATUS EFIAPI UhciDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -185,9 +183,9 @@ UhciDriverBindingSupported ( EFI_STATUS EFIAPI UhciDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -206,10 +204,10 @@ UhciDriverBindingStart ( EFI_STATUS EFIAPI UhciDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.c b/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.c index 3d499c9baf..3dc27eff1a 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.c @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID UhciDumpQh ( - IN UHCI_QH_SW *QhSw + IN UHCI_QH_SW *QhSw ) { DEBUG ((DEBUG_VERBOSE, "&QhSw @ 0x%p\n", QhSw)); @@ -28,7 +28,6 @@ UhciDumpQh ( DEBUG ((DEBUG_VERBOSE, " Vertical Link - %x\n\n", QhSw->QhHw.VerticalLink)); } - /** Dump the content of TD structure. @@ -37,33 +36,33 @@ UhciDumpQh ( **/ VOID UhciDumpTds ( - IN UHCI_TD_SW *TdSw + IN UHCI_TD_SW *TdSw ) { - UHCI_TD_SW *CurTdSw; + UHCI_TD_SW *CurTdSw; CurTdSw = TdSw; while (CurTdSw != NULL) { - DEBUG ((DEBUG_VERBOSE, "TdSw @ 0x%p\n", CurTdSw)); - DEBUG ((DEBUG_VERBOSE, "TdSw.NextTd - 0x%p\n", CurTdSw->NextTd)); - DEBUG ((DEBUG_VERBOSE, "TdSw.DataLen - %d\n", CurTdSw->DataLen)); - DEBUG ((DEBUG_VERBOSE, "TdSw.Data - 0x%p\n", CurTdSw->Data)); + DEBUG ((DEBUG_VERBOSE, "TdSw @ 0x%p\n", CurTdSw)); + DEBUG ((DEBUG_VERBOSE, "TdSw.NextTd - 0x%p\n", CurTdSw->NextTd)); + DEBUG ((DEBUG_VERBOSE, "TdSw.DataLen - %d\n", CurTdSw->DataLen)); + DEBUG ((DEBUG_VERBOSE, "TdSw.Data - 0x%p\n", CurTdSw->Data)); DEBUG ((DEBUG_VERBOSE, "TdHw:\n")); - DEBUG ((DEBUG_VERBOSE, " NextLink - 0x%x\n", CurTdSw->TdHw.NextLink)); - DEBUG ((DEBUG_VERBOSE, " ActualLen - %d\n", CurTdSw->TdHw.ActualLen)); - DEBUG ((DEBUG_VERBOSE, " Status - 0x%x\n", CurTdSw->TdHw.Status)); - DEBUG ((DEBUG_VERBOSE, " IOC - %d\n", CurTdSw->TdHw.IntOnCpl)); - DEBUG ((DEBUG_VERBOSE, " IsIsoCh - %d\n", CurTdSw->TdHw.IsIsoch)); - DEBUG ((DEBUG_VERBOSE, " LowSpeed - %d\n", CurTdSw->TdHw.LowSpeed)); - DEBUG ((DEBUG_VERBOSE, " ErrorCount - %d\n", CurTdSw->TdHw.ErrorCount)); - DEBUG ((DEBUG_VERBOSE, " ShortPacket - %d\n", CurTdSw->TdHw.ShortPacket)); - DEBUG ((DEBUG_VERBOSE, " PidCode - 0x%x\n", CurTdSw->TdHw.PidCode)); - DEBUG ((DEBUG_VERBOSE, " DevAddr - %d\n", CurTdSw->TdHw.DeviceAddr)); - DEBUG ((DEBUG_VERBOSE, " EndPoint - %d\n", CurTdSw->TdHw.EndPoint)); - DEBUG ((DEBUG_VERBOSE, " DataToggle - %d\n", CurTdSw->TdHw.DataToggle)); - DEBUG ((DEBUG_VERBOSE, " MaxPacketLen - %d\n", CurTdSw->TdHw.MaxPacketLen)); - DEBUG ((DEBUG_VERBOSE, " DataBuffer - 0x%x\n\n",CurTdSw->TdHw.DataBuffer)); + DEBUG ((DEBUG_VERBOSE, " NextLink - 0x%x\n", CurTdSw->TdHw.NextLink)); + DEBUG ((DEBUG_VERBOSE, " ActualLen - %d\n", CurTdSw->TdHw.ActualLen)); + DEBUG ((DEBUG_VERBOSE, " Status - 0x%x\n", CurTdSw->TdHw.Status)); + DEBUG ((DEBUG_VERBOSE, " IOC - %d\n", CurTdSw->TdHw.IntOnCpl)); + DEBUG ((DEBUG_VERBOSE, " IsIsoCh - %d\n", CurTdSw->TdHw.IsIsoch)); + DEBUG ((DEBUG_VERBOSE, " LowSpeed - %d\n", CurTdSw->TdHw.LowSpeed)); + DEBUG ((DEBUG_VERBOSE, " ErrorCount - %d\n", CurTdSw->TdHw.ErrorCount)); + DEBUG ((DEBUG_VERBOSE, " ShortPacket - %d\n", CurTdSw->TdHw.ShortPacket)); + DEBUG ((DEBUG_VERBOSE, " PidCode - 0x%x\n", CurTdSw->TdHw.PidCode)); + DEBUG ((DEBUG_VERBOSE, " DevAddr - %d\n", CurTdSw->TdHw.DeviceAddr)); + DEBUG ((DEBUG_VERBOSE, " EndPoint - %d\n", CurTdSw->TdHw.EndPoint)); + DEBUG ((DEBUG_VERBOSE, " DataToggle - %d\n", CurTdSw->TdHw.DataToggle)); + DEBUG ((DEBUG_VERBOSE, " MaxPacketLen - %d\n", CurTdSw->TdHw.MaxPacketLen)); + DEBUG ((DEBUG_VERBOSE, " DataBuffer - 0x%x\n\n", CurTdSw->TdHw.DataBuffer)); CurTdSw = CurTdSw->NextTd; } diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.h b/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.h index 34f8ea1ff4..27a2ec51a0 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciDebug.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_UHCI_DEBUG_H_ #define _EFI_UHCI_DEBUG_H_ - /** Dump the content of QH structure. @@ -21,10 +20,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID UhciDumpQh ( - IN UHCI_QH_SW *QhSw + IN UHCI_QH_SW *QhSw ); - /** Dump the content of TD structure. @@ -35,7 +33,7 @@ UhciDumpQh ( **/ VOID UhciDumpTds ( - IN UHCI_TD_SW *TdSw + IN UHCI_TD_SW *TdSw ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.c b/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.c index fb97326dc0..bd9703dd13 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - /** Map address of request structure buffer. @@ -24,10 +23,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS UhciMapUserRequest ( - IN USB_HC_DEV *Uhc, - IN OUT VOID *Request, - OUT UINT8 **MappedAddr, - OUT VOID **Map + IN USB_HC_DEV *Uhc, + IN OUT VOID *Request, + OUT UINT8 **MappedAddr, + OUT VOID **Map ) { EFI_STATUS Status; @@ -45,13 +44,12 @@ UhciMapUserRequest ( ); if (!EFI_ERROR (Status)) { - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; } return Status; } - /** Map address of user data buffer. @@ -84,65 +82,64 @@ UhciMapUserData ( Status = EFI_SUCCESS; switch (Direction) { - case EfiUsbDataIn: - // - // BusMasterWrite means cpu read - // - *PktId = INPUT_PACKET_ID; - Status = Uhc->PciIo->Map ( - Uhc->PciIo, - EfiPciIoOperationBusMasterWrite, - Data, - Len, - &PhyAddr, - Map - ); - - if (EFI_ERROR (Status)) { - goto EXIT; - } - - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; - break; - - case EfiUsbDataOut: - *PktId = OUTPUT_PACKET_ID; - Status = Uhc->PciIo->Map ( - Uhc->PciIo, - EfiPciIoOperationBusMasterRead, - Data, - Len, - &PhyAddr, - Map - ); - - if (EFI_ERROR (Status)) { - goto EXIT; - } - - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; - break; - - case EfiUsbNoData: - if ((Len != NULL) && (*Len != 0)) { - Status = EFI_INVALID_PARAMETER; - goto EXIT; - } - - *PktId = OUTPUT_PACKET_ID; - *MappedAddr = NULL; - *Map = NULL; - break; - - default: - Status = EFI_INVALID_PARAMETER; + case EfiUsbDataIn: + // + // BusMasterWrite means cpu read + // + *PktId = INPUT_PACKET_ID; + Status = Uhc->PciIo->Map ( + Uhc->PciIo, + EfiPciIoOperationBusMasterWrite, + Data, + Len, + &PhyAddr, + Map + ); + + if (EFI_ERROR (Status)) { + goto EXIT; + } + + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; + break; + + case EfiUsbDataOut: + *PktId = OUTPUT_PACKET_ID; + Status = Uhc->PciIo->Map ( + Uhc->PciIo, + EfiPciIoOperationBusMasterRead, + Data, + Len, + &PhyAddr, + Map + ); + + if (EFI_ERROR (Status)) { + goto EXIT; + } + + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; + break; + + case EfiUsbNoData: + if ((Len != NULL) && (*Len != 0)) { + Status = EFI_INVALID_PARAMETER; + goto EXIT; + } + + *PktId = OUTPUT_PACKET_ID; + *MappedAddr = NULL; + *Map = NULL; + break; + + default: + Status = EFI_INVALID_PARAMETER; } EXIT: return Status; } - /** Link the TD To QH. @@ -153,9 +150,9 @@ EXIT: **/ VOID UhciLinkTdToQh ( - IN USB_HC_DEV *Uhc, - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td + IN USB_HC_DEV *Uhc, + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td ) { EFI_PHYSICAL_ADDRESS PhyAddr; @@ -165,10 +162,9 @@ UhciLinkTdToQh ( ASSERT ((Qh != NULL) && (Td != NULL)); Qh->QhHw.VerticalLink = QH_VLINK (PhyAddr, FALSE); - Qh->TDs = (VOID *) Td; + Qh->TDs = (VOID *)Td; } - /** Unlink TD from the QH. @@ -178,8 +174,8 @@ UhciLinkTdToQh ( **/ VOID UhciUnlinkTdFromQh ( - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td ) { ASSERT ((Qh != NULL) && (Td != NULL)); @@ -188,7 +184,6 @@ UhciUnlinkTdFromQh ( Qh->TDs = NULL; } - /** Append a new TD To the previous TD. @@ -199,9 +194,9 @@ UhciUnlinkTdFromQh ( **/ VOID UhciAppendTd ( - IN USB_HC_DEV *Uhc, - IN UHCI_TD_SW *PrevTd, - IN UHCI_TD_SW *ThisTd + IN USB_HC_DEV *Uhc, + IN UHCI_TD_SW *PrevTd, + IN UHCI_TD_SW *ThisTd ) { EFI_PHYSICAL_ADDRESS PhyAddr; @@ -211,10 +206,9 @@ UhciAppendTd ( ASSERT ((PrevTd != NULL) && (ThisTd != NULL)); PrevTd->TdHw.NextLink = TD_LINK (PhyAddr, TRUE, FALSE); - PrevTd->NextTd = (VOID *) ThisTd; + PrevTd->NextTd = (VOID *)ThisTd; } - /** Delete a list of TDs. @@ -226,23 +220,22 @@ UhciAppendTd ( **/ VOID UhciDestoryTds ( - IN USB_HC_DEV *Uhc, - IN UHCI_TD_SW *FirstTd + IN USB_HC_DEV *Uhc, + IN UHCI_TD_SW *FirstTd ) { - UHCI_TD_SW *NextTd; - UHCI_TD_SW *ThisTd; + UHCI_TD_SW *NextTd; + UHCI_TD_SW *ThisTd; NextTd = FirstTd; while (NextTd != NULL) { - ThisTd = NextTd; - NextTd = ThisTd->NextTd; + ThisTd = NextTd; + NextTd = ThisTd->NextTd; UsbHcFreeMem (Uhc->MemPool, ThisTd, sizeof (UHCI_TD_SW)); } } - /** Create an initialize a new queue head. @@ -254,11 +247,11 @@ UhciDestoryTds ( **/ UHCI_QH_SW * UhciCreateQh ( - IN USB_HC_DEV *Uhc, - IN UINTN Interval + IN USB_HC_DEV *Uhc, + IN UINTN Interval ) { - UHCI_QH_SW *Qh; + UHCI_QH_SW *Qh; Qh = UsbHcAllocateMem (Uhc->MemPool, sizeof (UHCI_QH_SW)); @@ -268,14 +261,13 @@ UhciCreateQh ( Qh->QhHw.HorizonLink = QH_HLINK (NULL, TRUE); Qh->QhHw.VerticalLink = QH_VLINK (NULL, TRUE); - Qh->Interval = UhciConvertPollRate(Interval); + Qh->Interval = UhciConvertPollRate (Interval); Qh->TDs = NULL; Qh->NextQh = NULL; return Qh; } - /** Create and intialize a TD. @@ -286,12 +278,12 @@ UhciCreateQh ( **/ UHCI_TD_SW * UhciCreateTd ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { - UHCI_TD_SW *Td; + UHCI_TD_SW *Td; - Td = UsbHcAllocateMem (Uhc->MemPool, sizeof (UHCI_TD_SW)); + Td = UsbHcAllocateMem (Uhc->MemPool, sizeof (UHCI_TD_SW)); if (Td == NULL) { return NULL; } @@ -304,7 +296,6 @@ UhciCreateTd ( return Td; } - /** Create and initialize a TD for Setup Stage of a control transfer. @@ -319,14 +310,14 @@ UhciCreateTd ( **/ UHCI_TD_SW * UhciCreateSetupTd ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 *Request, - IN UINT8 *RequestPhy, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 *Request, + IN UINT8 *RequestPhy, + IN BOOLEAN IsLow ) { - UHCI_TD_SW *Td; + UHCI_TD_SW *Td; Td = UhciCreateTd (Uhc); @@ -344,17 +335,16 @@ UhciCreateSetupTd ( Td->TdHw.EndPoint = 0; Td->TdHw.LowSpeed = IsLow ? 1 : 0; Td->TdHw.DeviceAddr = DevAddr & 0x7F; - Td->TdHw.MaxPacketLen = (UINT32) (sizeof (EFI_USB_DEVICE_REQUEST) - 1); + Td->TdHw.MaxPacketLen = (UINT32)(sizeof (EFI_USB_DEVICE_REQUEST) - 1); Td->TdHw.PidCode = SETUP_PACKET_ID; - Td->TdHw.DataBuffer = (UINT32) (UINTN) RequestPhy; + Td->TdHw.DataBuffer = (UINT32)(UINTN)RequestPhy; - Td->Data = Request; - Td->DataLen = (UINT16) sizeof (EFI_USB_DEVICE_REQUEST); + Td->Data = Request; + Td->DataLen = (UINT16)sizeof (EFI_USB_DEVICE_REQUEST); return Td; } - /** Create a TD for data. @@ -373,15 +363,15 @@ UhciCreateSetupTd ( **/ UHCI_TD_SW * UhciCreateDataTd ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 *DataPtr, - IN UINT8 *DataPhyPtr, - IN UINTN Len, - IN UINT8 PktId, - IN UINT8 Toggle, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 *DataPtr, + IN UINT8 *DataPhyPtr, + IN UINTN Len, + IN UINT8 PktId, + IN UINT8 Toggle, + IN BOOLEAN IsLow ) { UHCI_TD_SW *Td; @@ -391,7 +381,7 @@ UhciCreateDataTd ( // ASSERT (Len <= 0x500); - Td = UhciCreateTd (Uhc); + Td = UhciCreateTd (Uhc); if (Td == NULL) { return NULL; @@ -407,17 +397,16 @@ UhciCreateDataTd ( Td->TdHw.DataToggle = Toggle & 0x01; Td->TdHw.EndPoint = Endpoint & 0x0F; Td->TdHw.DeviceAddr = DevAddr & 0x7F; - Td->TdHw.MaxPacketLen = (UINT32) (Len - 1); - Td->TdHw.PidCode = (UINT8) PktId; - Td->TdHw.DataBuffer = (UINT32) (UINTN) DataPhyPtr; + Td->TdHw.MaxPacketLen = (UINT32)(Len - 1); + Td->TdHw.PidCode = (UINT8)PktId; + Td->TdHw.DataBuffer = (UINT32)(UINTN)DataPhyPtr; - Td->Data = DataPtr; - Td->DataLen = (UINT16) Len; + Td->Data = DataPtr; + Td->DataLen = (UINT16)Len; return Td; } - /** Create TD for the Status Stage of control transfer. @@ -431,13 +420,13 @@ UhciCreateDataTd ( **/ UHCI_TD_SW * UhciCreateStatusTd ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 PktId, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 PktId, + IN BOOLEAN IsLow ) { - UHCI_TD_SW *Td; + UHCI_TD_SW *Td; Td = UhciCreateTd (Uhc); @@ -451,21 +440,20 @@ UhciCreateStatusTd ( Td->TdHw.IntOnCpl = FALSE; Td->TdHw.ErrorCount = 0x03; Td->TdHw.Status |= USBTD_ACTIVE; - Td->TdHw.MaxPacketLen = 0x7FF; //0x7FF: there is no data (refer to UHCI spec) + Td->TdHw.MaxPacketLen = 0x7FF; // 0x7FF: there is no data (refer to UHCI spec) Td->TdHw.DataToggle = 1; Td->TdHw.EndPoint = 0; Td->TdHw.LowSpeed = IsLow ? 1 : 0; Td->TdHw.DeviceAddr = DevAddr & 0x7F; - Td->TdHw.PidCode = (UINT8) PktId; - Td->TdHw.DataBuffer = (UINT32) (UINTN) NULL; + Td->TdHw.PidCode = (UINT8)PktId; + Td->TdHw.DataBuffer = (UINT32)(UINTN)NULL; - Td->Data = NULL; - Td->DataLen = 0; + Td->Data = NULL; + Td->DataLen = 0; return Td; } - /** Create Tds list for Control Transfer. @@ -485,27 +473,26 @@ UhciCreateStatusTd ( **/ UHCI_TD_SW * UhciCreateCtrlTds ( - IN USB_HC_DEV *Uhc, - IN UINT8 DeviceAddr, - IN UINT8 DataPktId, - IN UINT8 *Request, - IN UINT8 *RequestPhy, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN UINT8 MaxPacket, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DeviceAddr, + IN UINT8 DataPktId, + IN UINT8 *Request, + IN UINT8 *RequestPhy, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN UINT8 MaxPacket, + IN BOOLEAN IsLow ) { - UHCI_TD_SW *SetupTd; - UHCI_TD_SW *FirstDataTd; - UHCI_TD_SW *DataTd; - UHCI_TD_SW *PrevDataTd; - UHCI_TD_SW *StatusTd; - UINT8 DataToggle; - UINT8 StatusPktId; - UINTN ThisTdLen; - + UHCI_TD_SW *SetupTd; + UHCI_TD_SW *FirstDataTd; + UHCI_TD_SW *DataTd; + UHCI_TD_SW *PrevDataTd; + UHCI_TD_SW *StatusTd; + UINT8 DataToggle; + UINT8 StatusPktId; + UINTN ThisTdLen; DataTd = NULL; SetupTd = NULL; @@ -537,8 +524,8 @@ UhciCreateCtrlTds ( Uhc, DeviceAddr, 0, - Data, //cpu memory address - DataPhy, //Pci memory address + Data, // cpu memory address + DataPhy, // Pci memory address ThisTdLen, DataPktId, DataToggle, @@ -557,10 +544,10 @@ UhciCreateCtrlTds ( } DataToggle ^= 1; - PrevDataTd = DataTd; - Data += ThisTdLen; - DataPhy += ThisTdLen; - DataLen -= ThisTdLen; + PrevDataTd = DataTd; + Data += ThisTdLen; + DataPhy += ThisTdLen; + DataLen -= ThisTdLen; } // @@ -602,7 +589,6 @@ FREE_TD: return NULL; } - /** Create Tds list for Bulk/Interrupt Transfer. @@ -622,22 +608,22 @@ FREE_TD: **/ UHCI_TD_SW * UhciCreateBulkOrIntTds ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 EndPoint, - IN UINT8 PktId, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN OUT UINT8 *DataToggle, - IN UINT8 MaxPacket, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 EndPoint, + IN UINT8 PktId, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN OUT UINT8 *DataToggle, + IN UINT8 MaxPacket, + IN BOOLEAN IsLow ) { - UHCI_TD_SW *DataTd; - UHCI_TD_SW *FirstDataTd; - UHCI_TD_SW *PrevDataTd; - UINTN ThisTdLen; + UHCI_TD_SW *DataTd; + UHCI_TD_SW *FirstDataTd; + UHCI_TD_SW *PrevDataTd; + UINTN ThisTdLen; DataTd = NULL; FirstDataTd = NULL; diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.h b/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.h index 594ea28ee8..a0f483de56 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciQueue.h @@ -30,9 +30,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent (((UINT32) ((UINTN) (Pointer)) & 0xFFFFFFF0) | \ ((VertFirst) ? 0x04 : 0) | ((Terminate) ? 0x01 : 0)) -#define LINK_TERMINATED(Link) (((Link) & 0x01) != 0) +#define LINK_TERMINATED(Link) (((Link) & 0x01) != 0) -#define UHCI_ADDR(QhOrTd) ((VOID *) (UINTN) ((QhOrTd) & 0xFFFFFFF0)) +#define UHCI_ADDR(QhOrTd) ((VOID *) (UINTN) ((QhOrTd) & 0xFFFFFFF0)) #pragma pack(1) // @@ -41,8 +41,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // This is the same as frame list entry. // typedef struct { - UINT32 HorizonLink; - UINT32 VerticalLink; + UINT32 HorizonLink; + UINT32 VerticalLink; } UHCI_QH_HW; // @@ -50,23 +50,23 @@ typedef struct { // Next pointer: 28, Reserved: 1, Vertical First: 1, NextIsQh: 1, Terminate: 1 // typedef struct { - UINT32 NextLink; - UINT32 ActualLen : 11; - UINT32 Reserved1 : 5; - UINT32 Status : 8; - UINT32 IntOnCpl : 1; - UINT32 IsIsoch : 1; - UINT32 LowSpeed : 1; - UINT32 ErrorCount : 2; - UINT32 ShortPacket : 1; - UINT32 Reserved2 : 2; - UINT32 PidCode : 8; - UINT32 DeviceAddr : 7; - UINT32 EndPoint : 4; - UINT32 DataToggle : 1; - UINT32 Reserved3 : 1; - UINT32 MaxPacketLen: 11; - UINT32 DataBuffer; + UINT32 NextLink; + UINT32 ActualLen : 11; + UINT32 Reserved1 : 5; + UINT32 Status : 8; + UINT32 IntOnCpl : 1; + UINT32 IsIsoch : 1; + UINT32 LowSpeed : 1; + UINT32 ErrorCount : 2; + UINT32 ShortPacket : 1; + UINT32 Reserved2 : 2; + UINT32 PidCode : 8; + UINT32 DeviceAddr : 7; + UINT32 EndPoint : 4; + UINT32 DataToggle : 1; + UINT32 Reserved3 : 1; + UINT32 MaxPacketLen : 11; + UINT32 DataBuffer; } UHCI_TD_HW; #pragma pack() @@ -74,20 +74,19 @@ typedef struct _UHCI_TD_SW UHCI_TD_SW; typedef struct _UHCI_QH_SW UHCI_QH_SW; struct _UHCI_QH_SW { - UHCI_QH_HW QhHw; - UHCI_QH_SW *NextQh; - UHCI_TD_SW *TDs; - UINTN Interval; + UHCI_QH_HW QhHw; + UHCI_QH_SW *NextQh; + UHCI_TD_SW *TDs; + UINTN Interval; }; struct _UHCI_TD_SW { - UHCI_TD_HW TdHw; - UHCI_TD_SW *NextTd; - UINT8 *Data; - UINT16 DataLen; + UHCI_TD_HW TdHw; + UHCI_TD_SW *NextTd; + UINT8 *Data; + UINT16 DataLen; }; - /** Link the TD To QH. @@ -98,12 +97,11 @@ struct _UHCI_TD_SW { **/ VOID UhciLinkTdToQh ( - IN USB_HC_DEV *Uhc, - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td + IN USB_HC_DEV *Uhc, + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td ); - /** Unlink TD from the QH. @@ -115,11 +113,10 @@ UhciLinkTdToQh ( **/ VOID UhciUnlinkTdFromQh ( - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td ); - /** Map address of request structure buffer. @@ -134,13 +131,12 @@ UhciUnlinkTdFromQh ( **/ EFI_STATUS UhciMapUserRequest ( - IN USB_HC_DEV *Uhc, - IN OUT VOID *Request, - OUT UINT8 **MappedAddr, - OUT VOID **Map + IN USB_HC_DEV *Uhc, + IN OUT VOID *Request, + OUT UINT8 **MappedAddr, + OUT VOID **Map ); - /** Map address of user data buffer. @@ -167,7 +163,6 @@ UhciMapUserData ( OUT VOID **Map ); - /** Delete a list of TDs. @@ -179,11 +174,10 @@ UhciMapUserData ( **/ VOID UhciDestoryTds ( - IN USB_HC_DEV *Uhc, - IN UHCI_TD_SW *FirstTd + IN USB_HC_DEV *Uhc, + IN UHCI_TD_SW *FirstTd ); - /** Create an initialize a new queue head. @@ -195,11 +189,10 @@ UhciDestoryTds ( **/ UHCI_QH_SW * UhciCreateQh ( - IN USB_HC_DEV *Uhc, - IN UINTN Interval + IN USB_HC_DEV *Uhc, + IN UINTN Interval ); - /** Create Tds list for Control Transfer. @@ -219,19 +212,18 @@ UhciCreateQh ( **/ UHCI_TD_SW * UhciCreateCtrlTds ( - IN USB_HC_DEV *Uhc, - IN UINT8 DeviceAddr, - IN UINT8 DataPktId, - IN UINT8 *Request, - IN UINT8 *RequestPhy, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN UINT8 MaxPacket, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DeviceAddr, + IN UINT8 DataPktId, + IN UINT8 *Request, + IN UINT8 *RequestPhy, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN UINT8 MaxPacket, + IN BOOLEAN IsLow ); - /** Create Tds list for Bulk/Interrupt Transfer. @@ -251,16 +243,16 @@ UhciCreateCtrlTds ( **/ UHCI_TD_SW * UhciCreateBulkOrIntTds ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 EndPoint, - IN UINT8 PktId, - IN UINT8 *Data, - IN UINT8 *DataPhy, - IN UINTN DataLen, - IN OUT UINT8 *DataToggle, - IN UINT8 MaxPacket, - IN BOOLEAN IsLow + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 EndPoint, + IN UINT8 PktId, + IN UINT8 *Data, + IN UINT8 *DataPhy, + IN UINTN DataLen, + IN OUT UINT8 *DataToggle, + IN UINT8 MaxPacket, + IN BOOLEAN IsLow ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.c b/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.c index 44bcde4c4e..9aa138fa46 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - /** Read a UHCI register. @@ -21,21 +20,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT16 UhciReadReg ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset ) { UINT16 Data; EFI_STATUS Status; Status = PciIo->Io.Read ( - PciIo, - EfiPciIoWidthUint16, - USB_BAR_INDEX, - Offset, - 1, - &Data - ); + PciIo, + EfiPciIoWidthUint16, + USB_BAR_INDEX, + Offset, + 1, + &Data + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UhciReadReg: PciIo Io.Read error: %r at offset %d\n", Status, Offset)); @@ -46,7 +45,6 @@ UhciReadReg ( return Data; } - /** Write data to UHCI register. @@ -57,28 +55,27 @@ UhciReadReg ( **/ VOID UhciWriteReg ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Data ) { EFI_STATUS Status; Status = PciIo->Io.Write ( - PciIo, - EfiPciIoWidthUint16, - USB_BAR_INDEX, - Offset, - 1, - &Data - ); + PciIo, + EfiPciIoWidthUint16, + USB_BAR_INDEX, + Offset, + 1, + &Data + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UhciWriteReg: PciIo Io.Write error: %r at offset %d\n", Status, Offset)); } } - /** Set a bit of the UHCI Register. @@ -89,19 +86,18 @@ UhciWriteReg ( **/ VOID UhciSetRegBit ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Bit + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Bit ) { UINT16 Data; Data = UhciReadReg (PciIo, Offset); - Data = (UINT16) (Data |Bit); + Data = (UINT16)(Data |Bit); UhciWriteReg (PciIo, Offset, Data); } - /** Clear a bit of the UHCI Register. @@ -112,19 +108,18 @@ UhciSetRegBit ( **/ VOID UhciClearRegBit ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Bit + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Bit ) { UINT16 Data; Data = UhciReadReg (PciIo, Offset); - Data = (UINT16) (Data & ~Bit); + Data = (UINT16)(Data & ~Bit); UhciWriteReg (PciIo, Offset, Data); } - /** Clear all the interrutp status bits, these bits are Write-Clean. @@ -134,7 +129,7 @@ UhciClearRegBit ( **/ VOID UhciAckAllInterrupt ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { UhciWriteReg (Uhc->PciIo, USBSTS_OFFSET, 0x3F); @@ -149,7 +144,6 @@ UhciAckAllInterrupt ( } } - /** Stop the host controller. @@ -162,12 +156,12 @@ UhciAckAllInterrupt ( **/ EFI_STATUS UhciStopHc ( - IN USB_HC_DEV *Uhc, - IN UINTN Timeout + IN USB_HC_DEV *Uhc, + IN UINTN Timeout ) { - UINT16 UsbSts; - UINTN Index; + UINT16 UsbSts; + UINTN Index; UhciClearRegBit (Uhc->PciIo, USBCMD_OFFSET, USBCMD_RS); @@ -188,7 +182,6 @@ UhciStopHc ( return EFI_TIMEOUT; } - /** Check whether the host controller operates well. @@ -200,10 +193,10 @@ UhciStopHc ( **/ BOOLEAN UhciIsHcWorking ( - IN EFI_PCI_IO_PROTOCOL *PciIo + IN EFI_PCI_IO_PROTOCOL *PciIo ) { - UINT16 UsbSts; + UINT16 UsbSts; UsbSts = UhciReadReg (PciIo, USBSTS_OFFSET); @@ -215,7 +208,6 @@ UhciIsHcWorking ( return TRUE; } - /** Set the UHCI frame list base address. It can't use UhciWriteReg which access memory in UINT16. @@ -226,20 +218,20 @@ UhciIsHcWorking ( **/ VOID UhciSetFrameListBaseAddr ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN VOID *Addr + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN VOID *Addr ) { - EFI_STATUS Status; - UINT32 Data; + EFI_STATUS Status; + UINT32 Data; - Data = (UINT32) ((UINTN) Addr & 0xFFFFF000); + Data = (UINT32)((UINTN)Addr & 0xFFFFF000); Status = PciIo->Io.Write ( PciIo, EfiPciIoWidthUint32, USB_BAR_INDEX, - (UINT64) USB_FRAME_BASE_OFFSET, + (UINT64)USB_FRAME_BASE_OFFSET, 1, &Data ); @@ -249,7 +241,6 @@ UhciSetFrameListBaseAddr ( } } - /** Disable USB Emulation. @@ -258,10 +249,10 @@ UhciSetFrameListBaseAddr ( **/ VOID UhciTurnOffUsbEmulation ( - IN EFI_PCI_IO_PROTOCOL *PciIo + IN EFI_PCI_IO_PROTOCOL *PciIo ) { - UINT16 Command; + UINT16 Command; Command = 0; diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.h b/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.h index b39dcbbbec..84e2d1bd2a 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciReg.h @@ -14,42 +14,42 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // UHCI register offset // -#define UHCI_FRAME_NUM 1024 +#define UHCI_FRAME_NUM 1024 // // Register offset and PCI related staff // -#define USB_BAR_INDEX 4 +#define USB_BAR_INDEX 4 -#define USBCMD_OFFSET 0 -#define USBSTS_OFFSET 2 -#define USBINTR_OFFSET 4 -#define USBPORTSC_OFFSET 0x10 -#define USB_FRAME_NO_OFFSET 6 -#define USB_FRAME_BASE_OFFSET 8 -#define USB_EMULATION_OFFSET 0xC0 +#define USBCMD_OFFSET 0 +#define USBSTS_OFFSET 2 +#define USBINTR_OFFSET 4 +#define USBPORTSC_OFFSET 0x10 +#define USB_FRAME_NO_OFFSET 6 +#define USB_FRAME_BASE_OFFSET 8 +#define USB_EMULATION_OFFSET 0xC0 // // Packet IDs // -#define SETUP_PACKET_ID 0x2D -#define INPUT_PACKET_ID 0x69 -#define OUTPUT_PACKET_ID 0xE1 -#define ERROR_PACKET_ID 0x55 +#define SETUP_PACKET_ID 0x2D +#define INPUT_PACKET_ID 0x69 +#define OUTPUT_PACKET_ID 0xE1 +#define ERROR_PACKET_ID 0x55 // // USB port status and control bit definition. // -#define USBPORTSC_CCS BIT0 // Current Connect Status -#define USBPORTSC_CSC BIT1 // Connect Status Change -#define USBPORTSC_PED BIT2 // Port Enable / Disable -#define USBPORTSC_PEDC BIT3 // Port Enable / Disable Change -#define USBPORTSC_LSL BIT4 // Line Status Low BIT -#define USBPORTSC_LSH BIT5 // Line Status High BIT -#define USBPORTSC_RD BIT6 // Resume Detect -#define USBPORTSC_LSDA BIT8 // Low Speed Device Attached -#define USBPORTSC_PR BIT9 // Port Reset -#define USBPORTSC_SUSP BIT12 // Suspend +#define USBPORTSC_CCS BIT0 // Current Connect Status +#define USBPORTSC_CSC BIT1 // Connect Status Change +#define USBPORTSC_PED BIT2 // Port Enable / Disable +#define USBPORTSC_PEDC BIT3 // Port Enable / Disable Change +#define USBPORTSC_LSL BIT4 // Line Status Low BIT +#define USBPORTSC_LSH BIT5 // Line Status High BIT +#define USBPORTSC_RD BIT6 // Resume Detect +#define USBPORTSC_LSDA BIT8 // Low Speed Device Attached +#define USBPORTSC_PR BIT9 // Port Reset +#define USBPORTSC_SUSP BIT12 // Suspend // // UHCI Spec said it must implement 2 ports each host at least, @@ -61,33 +61,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Command register bit definitions // -#define USBCMD_RS BIT0 // Run/Stop -#define USBCMD_HCRESET BIT1 // Host reset -#define USBCMD_GRESET BIT2 // Global reset -#define USBCMD_EGSM BIT3 // Global Suspend Mode -#define USBCMD_FGR BIT4 // Force Global Resume -#define USBCMD_SWDBG BIT5 // SW Debug mode -#define USBCMD_CF BIT6 // Config Flag (sw only) -#define USBCMD_MAXP BIT7 // Max Packet (0 = 32, 1 = 64) +#define USBCMD_RS BIT0 // Run/Stop +#define USBCMD_HCRESET BIT1 // Host reset +#define USBCMD_GRESET BIT2 // Global reset +#define USBCMD_EGSM BIT3 // Global Suspend Mode +#define USBCMD_FGR BIT4 // Force Global Resume +#define USBCMD_SWDBG BIT5 // SW Debug mode +#define USBCMD_CF BIT6 // Config Flag (sw only) +#define USBCMD_MAXP BIT7 // Max Packet (0 = 32, 1 = 64) // // USB Status register bit definitions // -#define USBSTS_USBINT BIT0 // Interrupt due to IOC -#define USBSTS_ERROR BIT1 // Interrupt due to error -#define USBSTS_RD BIT2 // Resume Detect -#define USBSTS_HSE BIT3 // Host System Error -#define USBSTS_HCPE BIT4 // Host Controller Process Error -#define USBSTS_HCH BIT5 // HC Halted - -#define USBTD_ACTIVE BIT7 // TD is still active -#define USBTD_STALLED BIT6 // TD is stalled -#define USBTD_BUFFERR BIT5 // Buffer underflow or overflow -#define USBTD_BABBLE BIT4 // Babble condition -#define USBTD_NAK BIT3 // NAK is received -#define USBTD_CRC BIT2 // CRC/Time out error -#define USBTD_BITSTUFF BIT1 // Bit stuff error - +#define USBSTS_USBINT BIT0 // Interrupt due to IOC +#define USBSTS_ERROR BIT1 // Interrupt due to error +#define USBSTS_RD BIT2 // Resume Detect +#define USBSTS_HSE BIT3 // Host System Error +#define USBSTS_HCPE BIT4 // Host Controller Process Error +#define USBSTS_HCH BIT5 // HC Halted + +#define USBTD_ACTIVE BIT7 // TD is still active +#define USBTD_STALLED BIT6 // TD is stalled +#define USBTD_BUFFERR BIT5 // Buffer underflow or overflow +#define USBTD_BABBLE BIT4 // Babble condition +#define USBTD_NAK BIT3 // NAK is received +#define USBTD_CRC BIT2 // CRC/Time out error +#define USBTD_BITSTUFF BIT1 // Bit stuff error /** Read a UHCI register. @@ -100,12 +99,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT16 UhciReadReg ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset ); - - /** Write data to UHCI register. @@ -118,13 +115,11 @@ UhciReadReg ( **/ VOID UhciWriteReg ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Data + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Data ); - - /** Set a bit of the UHCI Register. @@ -137,13 +132,11 @@ UhciWriteReg ( **/ VOID UhciSetRegBit ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Bit + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Bit ); - - /** Clear a bit of the UHCI Register. @@ -156,12 +149,11 @@ UhciSetRegBit ( **/ VOID UhciClearRegBit ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT32 Offset, - IN UINT16 Bit + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT32 Offset, + IN UINT16 Bit ); - /** Clear all the interrutp status bits, these bits are Write-Clean. @@ -173,10 +165,9 @@ UhciClearRegBit ( **/ VOID UhciAckAllInterrupt ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ); - /** Stop the host controller. @@ -189,12 +180,10 @@ UhciAckAllInterrupt ( **/ EFI_STATUS UhciStopHc ( - IN USB_HC_DEV *Uhc, - IN UINTN Timeout + IN USB_HC_DEV *Uhc, + IN UINTN Timeout ); - - /** Check whether the host controller operates well. @@ -206,10 +195,9 @@ UhciStopHc ( **/ BOOLEAN UhciIsHcWorking ( - IN EFI_PCI_IO_PROTOCOL *PciIo + IN EFI_PCI_IO_PROTOCOL *PciIo ); - /** Set the UHCI frame list base address. It can't use UhciWriteReg which access memory in UINT16. @@ -222,11 +210,10 @@ UhciIsHcWorking ( **/ VOID UhciSetFrameListBaseAddr ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN VOID *Addr + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN VOID *Addr ); - /** Disable USB Emulation. @@ -237,6 +224,7 @@ UhciSetFrameListBaseAddr ( **/ VOID UhciTurnOffUsbEmulation ( - IN EFI_PCI_IO_PROTOCOL *PciIo + IN EFI_PCI_IO_PROTOCOL *PciIo ); + #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c b/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c index 0829bc2a8c..c08f949696 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - /** Create Frame List Structure. @@ -22,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS UhciInitFrameList ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { EFI_PHYSICAL_ADDRESS MappedAddr; @@ -70,14 +69,14 @@ UhciInitFrameList ( goto ON_ERROR; } - Uhc->FrameBase = (UINT32 *) (UINTN) Buffer; - Uhc->FrameMapping = Mapping; + Uhc->FrameBase = (UINT32 *)(UINTN)Buffer; + Uhc->FrameMapping = Mapping; // // Tell the Host Controller where the Frame List lies, // by set the Frame List Base Address Register. // - UhciSetFrameListBaseAddr (Uhc->PciIo, (VOID *) (UINTN) MappedAddr); + UhciSetFrameListBaseAddr (Uhc->PciIo, (VOID *)(UINTN)MappedAddr); // // Allocate the QH used by sync interrupt/control/bulk transfer. @@ -85,9 +84,9 @@ UhciInitFrameList ( // can be reclaimed. Notice, LS don't support bulk transfer and // also doesn't support BW reclamation. // - Uhc->SyncIntQh = UhciCreateQh (Uhc, 1); - Uhc->CtrlQh = UhciCreateQh (Uhc, 1); - Uhc->BulkQh = UhciCreateQh (Uhc, 1); + Uhc->SyncIntQh = UhciCreateQh (Uhc, 1); + Uhc->CtrlQh = UhciCreateQh (Uhc, 1); + Uhc->BulkQh = UhciCreateQh (Uhc, 1); if ((Uhc->SyncIntQh == NULL) || (Uhc->CtrlQh == NULL) || (Uhc->BulkQh == NULL)) { Uhc->PciIo->Unmap (Uhc->PciIo, Mapping); @@ -102,22 +101,22 @@ UhciInitFrameList ( // Each frame entry is linked to this sequence of QH. These QH // will remain on the schedul, never got removed // - PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Uhc->CtrlQh, sizeof (UHCI_QH_HW)); - Uhc->SyncIntQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); - Uhc->SyncIntQh->NextQh = Uhc->CtrlQh; + PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Uhc->CtrlQh, sizeof (UHCI_QH_HW)); + Uhc->SyncIntQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); + Uhc->SyncIntQh->NextQh = Uhc->CtrlQh; - PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Uhc->BulkQh, sizeof (UHCI_QH_HW)); - Uhc->CtrlQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); - Uhc->CtrlQh->NextQh = Uhc->BulkQh; + PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Uhc->BulkQh, sizeof (UHCI_QH_HW)); + Uhc->CtrlQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); + Uhc->CtrlQh->NextQh = Uhc->BulkQh; // // Some old platform such as Intel's Tiger 4 has a difficult time // in supporting the full speed bandwidth reclamation in the previous // mentioned form. Most new platforms don't suffer it. // - Uhc->BulkQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); + Uhc->BulkQh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); - Uhc->BulkQh->NextQh = NULL; + Uhc->BulkQh->NextQh = NULL; Uhc->FrameBaseHostAddr = AllocateZeroPool (4096); if (Uhc->FrameBaseHostAddr == NULL) { @@ -127,7 +126,7 @@ UhciInitFrameList ( PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Uhc->SyncIntQh, sizeof (UHCI_QH_HW)); for (Index = 0; Index < UHCI_FRAME_NUM; Index++) { - Uhc->FrameBase[Index] = QH_HLINK (PhyAddr, FALSE); + Uhc->FrameBase[Index] = QH_HLINK (PhyAddr, FALSE); Uhc->FrameBaseHostAddr[Index] = (UINT32)(UINTN)Uhc->SyncIntQh; } @@ -150,7 +149,6 @@ ON_ERROR: return Status; } - /** Destory FrameList buffer. @@ -159,7 +157,7 @@ ON_ERROR: **/ VOID UhciDestoryFrameList ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { // @@ -172,7 +170,7 @@ UhciDestoryFrameList ( Uhc->PciIo->FreeBuffer ( Uhc->PciIo, EFI_SIZE_TO_PAGES (4096), - (VOID *) Uhc->FrameBase + (VOID *)Uhc->FrameBase ); if (Uhc->FrameBaseHostAddr != NULL) { @@ -191,14 +189,13 @@ UhciDestoryFrameList ( UsbHcFreeMem (Uhc->MemPool, Uhc->BulkQh, sizeof (UHCI_QH_SW)); } - Uhc->FrameBase = NULL; - Uhc->FrameBaseHostAddr = NULL; - Uhc->SyncIntQh = NULL; - Uhc->CtrlQh = NULL; - Uhc->BulkQh = NULL; + Uhc->FrameBase = NULL; + Uhc->FrameBaseHostAddr = NULL; + Uhc->SyncIntQh = NULL; + Uhc->CtrlQh = NULL; + Uhc->BulkQh = NULL; } - /** Convert the poll rate to the maxium 2^n that is smaller than Interval. @@ -210,10 +207,10 @@ UhciDestoryFrameList ( **/ UINTN UhciConvertPollRate ( - IN UINTN Interval + IN UINTN Interval ) { - UINTN BitCount; + UINTN BitCount; ASSERT (Interval != 0); @@ -230,7 +227,6 @@ UhciConvertPollRate ( return (UINTN)1 << (BitCount - 1); } - /** Link a queue head (for asynchronous interrupt transfer) to the frame list. @@ -241,15 +237,15 @@ UhciConvertPollRate ( **/ VOID UhciLinkQhToFrameList ( - USB_HC_DEV *Uhc, - UHCI_QH_SW *Qh + USB_HC_DEV *Uhc, + UHCI_QH_SW *Qh ) { - UINTN Index; - UHCI_QH_SW *Prev; - UHCI_QH_SW *Next; - EFI_PHYSICAL_ADDRESS PhyAddr; - EFI_PHYSICAL_ADDRESS QhPciAddr; + UINTN Index; + UHCI_QH_SW *Prev; + UHCI_QH_SW *Next; + EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_PHYSICAL_ADDRESS QhPciAddr; ASSERT ((Uhc->FrameBase != NULL) && (Qh != NULL)); @@ -261,8 +257,8 @@ UhciLinkQhToFrameList ( // heads on the frame list // ASSERT (!LINK_TERMINATED (Uhc->FrameBase[Index])); - Next = (UHCI_QH_SW*)(UINTN)Uhc->FrameBaseHostAddr[Index]; - Prev = NULL; + Next = (UHCI_QH_SW *)(UINTN)Uhc->FrameBaseHostAddr[Index]; + Prev = NULL; // // Now, insert the queue head (Qh) into this frame: @@ -279,8 +275,8 @@ UhciLinkQhToFrameList ( // rate is correct. // while (Next->Interval > Qh->Interval) { - Prev = Next; - Next = Next->NextQh; + Prev = Next; + Next = Next->NextQh; ASSERT (Next != NULL); } @@ -305,15 +301,15 @@ UhciLinkQhToFrameList ( // ASSERT ((Index == 0) && (Qh->NextQh == NULL)); - Prev = Next; - Next = Next->NextQh; + Prev = Next; + Next = Next->NextQh; - Qh->NextQh = Next; - Prev->NextQh = Qh; + Qh->NextQh = Next; + Prev->NextQh = Qh; - Qh->QhHw.HorizonLink = Prev->QhHw.HorizonLink; + Qh->QhHw.HorizonLink = Prev->QhHw.HorizonLink; - Prev->QhHw.HorizonLink = QH_HLINK (QhPciAddr, FALSE); + Prev->QhHw.HorizonLink = QH_HLINK (QhPciAddr, FALSE); break; } @@ -323,22 +319,21 @@ UhciLinkQhToFrameList ( // guarranted by 2^n polling interval. // if (Qh->NextQh == NULL) { - Qh->NextQh = Next; - PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Next, sizeof (UHCI_QH_HW)); - Qh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); + Qh->NextQh = Next; + PhyAddr = UsbHcGetPciAddressForHostMem (Uhc->MemPool, Next, sizeof (UHCI_QH_HW)); + Qh->QhHw.HorizonLink = QH_HLINK (PhyAddr, FALSE); } if (Prev == NULL) { - Uhc->FrameBase[Index] = QH_HLINK (QhPciAddr, FALSE); - Uhc->FrameBaseHostAddr[Index] = (UINT32)(UINTN)Qh; + Uhc->FrameBase[Index] = QH_HLINK (QhPciAddr, FALSE); + Uhc->FrameBaseHostAddr[Index] = (UINT32)(UINTN)Qh; } else { - Prev->NextQh = Qh; - Prev->QhHw.HorizonLink = QH_HLINK (QhPciAddr, FALSE); + Prev->NextQh = Qh; + Prev->QhHw.HorizonLink = QH_HLINK (QhPciAddr, FALSE); } } } - /** Unlink QH from the frame list is easier: find all the precedence node, and pointer there next to QhSw's @@ -350,13 +345,13 @@ UhciLinkQhToFrameList ( **/ VOID UhciUnlinkQhFromFrameList ( - USB_HC_DEV *Uhc, - UHCI_QH_SW *Qh + USB_HC_DEV *Uhc, + UHCI_QH_SW *Qh ) { - UINTN Index; - UHCI_QH_SW *Prev; - UHCI_QH_SW *This; + UINTN Index; + UHCI_QH_SW *Prev; + UHCI_QH_SW *This; ASSERT ((Uhc->FrameBase != NULL) && (Qh != NULL)); @@ -366,16 +361,16 @@ UhciUnlinkQhFromFrameList ( // queue heads on the frame list // ASSERT (!LINK_TERMINATED (Uhc->FrameBase[Index])); - This = (UHCI_QH_SW*)(UINTN)Uhc->FrameBaseHostAddr[Index]; - Prev = NULL; + This = (UHCI_QH_SW *)(UINTN)Uhc->FrameBaseHostAddr[Index]; + Prev = NULL; // // Walk through the frame's QH list to find the // queue head to remove // while ((This != NULL) && (This != Qh)) { - Prev = This; - This = This->NextQh; + Prev = This; + This = This->NextQh; } // @@ -390,16 +385,15 @@ UhciUnlinkQhFromFrameList ( // // Qh is the first entry in the frame // - Uhc->FrameBase[Index] = Qh->QhHw.HorizonLink; - Uhc->FrameBaseHostAddr[Index] = (UINT32)(UINTN)Qh->NextQh; + Uhc->FrameBase[Index] = Qh->QhHw.HorizonLink; + Uhc->FrameBaseHostAddr[Index] = (UINT32)(UINTN)Qh->NextQh; } else { - Prev->NextQh = Qh->NextQh; - Prev->QhHw.HorizonLink = Qh->QhHw.HorizonLink; + Prev->NextQh = Qh->NextQh; + Prev->QhHw.HorizonLink = Qh->QhHw.HorizonLink; } } } - /** Check TDs Results. @@ -413,18 +407,18 @@ UhciUnlinkQhFromFrameList ( **/ BOOLEAN UhciCheckTdStatus ( - IN USB_HC_DEV *Uhc, - IN UHCI_TD_SW *Td, - IN BOOLEAN IsLow, - OUT UHCI_QH_RESULT *QhResult + IN USB_HC_DEV *Uhc, + IN UHCI_TD_SW *Td, + IN BOOLEAN IsLow, + OUT UHCI_QH_RESULT *QhResult ) { - UINTN Len; - UINT8 State; - UHCI_TD_HW *TdHw; - BOOLEAN Finished; + UINTN Len; + UINT8 State; + UHCI_TD_HW *TdHw; + BOOLEAN Finished; - Finished = TRUE; + Finished = TRUE; // // Initialize the data toggle to that of the first @@ -457,7 +451,6 @@ UhciCheckTdStatus ( if ((State & USBTD_STALLED) != 0) { if ((State & USBTD_BABBLE) != 0) { QhResult->Result |= EFI_USB_ERR_BABBLE; - } else if (TdHw->ErrorCount != 0) { QhResult->Result |= EFI_USB_ERR_STALL; } @@ -480,7 +473,6 @@ UhciCheckTdStatus ( Finished = TRUE; goto ON_EXIT; - } else if ((State & USBTD_ACTIVE) != 0) { // // The TD is still active, no need to check further. @@ -489,14 +481,13 @@ UhciCheckTdStatus ( Finished = FALSE; goto ON_EXIT; - } else { // // Update the next data toggle, it is always the // next to the last known-good TD's data toggle if // any TD is executed OK // - QhResult->NextToggle = (UINT8) (1 - (UINT8)TdHw->DataToggle); + QhResult->NextToggle = (UINT8)(1 - (UINT8)TdHw->DataToggle); // // This TD is finished OK or met short packet read. Update the @@ -530,7 +521,7 @@ ON_EXIT: // if (!UhciIsHcWorking (Uhc->PciIo)) { QhResult->Result |= EFI_USB_ERR_SYSTEM; - Finished = TRUE; + Finished = TRUE; } if (Finished) { @@ -541,7 +532,6 @@ ON_EXIT: return Finished; } - /** Check the result of the transfer. @@ -558,19 +548,19 @@ ON_EXIT: **/ EFI_STATUS UhciExecuteTransfer ( - IN USB_HC_DEV *Uhc, - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td, - IN UINTN TimeOut, - IN BOOLEAN IsLow, - OUT UHCI_QH_RESULT *QhResult + IN USB_HC_DEV *Uhc, + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td, + IN UINTN TimeOut, + IN BOOLEAN IsLow, + OUT UHCI_QH_RESULT *QhResult ) { - UINTN Index; - UINTN Delay; - BOOLEAN Finished; - EFI_STATUS Status; - BOOLEAN InfiniteLoop; + UINTN Index; + UINTN Delay; + BOOLEAN Finished; + EFI_STATUS Status; + BOOLEAN InfiniteLoop; Finished = FALSE; Status = EFI_SUCCESS; @@ -605,7 +595,6 @@ UhciExecuteTransfer ( UhciDumpTds (Td); Status = EFI_TIMEOUT; - } else if (QhResult->Result != EFI_USB_NOERROR) { DEBUG ((DEBUG_ERROR, "UhciExecuteTransfer: execution failed with result %x\n", QhResult->Result)); UhciDumpQh (Qh); @@ -617,7 +606,6 @@ UhciExecuteTransfer ( return Status; } - /** Update Async Request, QH and TDs. @@ -635,12 +623,12 @@ UhciUpdateAsyncReq ( IN UINT32 NextToggle ) { - UHCI_QH_SW *Qh; - UHCI_TD_SW *FirstTd; - UHCI_TD_SW *Td; + UHCI_QH_SW *Qh; + UHCI_TD_SW *FirstTd; + UHCI_TD_SW *Td; - Qh = AsyncReq->QhSw; - FirstTd = AsyncReq->FirstTd; + Qh = AsyncReq->QhSw; + FirstTd = AsyncReq->FirstTd; if (Result == EFI_USB_NOERROR) { // @@ -659,11 +647,10 @@ UhciUpdateAsyncReq ( } UhciLinkTdToQh (Uhc, Qh, FirstTd); - return ; + return; } } - /** Create Async Request node, and Link to List. @@ -699,7 +686,7 @@ UhciCreateAsyncReq ( IN BOOLEAN IsLow ) { - UHCI_ASYNC_REQUEST *AsyncReq; + UHCI_ASYNC_REQUEST *AsyncReq; AsyncReq = AllocatePool (sizeof (UHCI_ASYNC_REQUEST)); @@ -710,17 +697,17 @@ UhciCreateAsyncReq ( // // Fill Request field. Data is allocated host memory, not mapped // - AsyncReq->Signature = UHCI_ASYNC_INT_SIGNATURE; - AsyncReq->DevAddr = DevAddr; - AsyncReq->EndPoint = EndPoint; - AsyncReq->DataLen = DataLen; - AsyncReq->Interval = UhciConvertPollRate(Interval); - AsyncReq->Data = Data; - AsyncReq->Callback = Callback; - AsyncReq->Context = Context; - AsyncReq->QhSw = Qh; - AsyncReq->FirstTd = FirstTd; - AsyncReq->IsLow = IsLow; + AsyncReq->Signature = UHCI_ASYNC_INT_SIGNATURE; + AsyncReq->DevAddr = DevAddr; + AsyncReq->EndPoint = EndPoint; + AsyncReq->DataLen = DataLen; + AsyncReq->Interval = UhciConvertPollRate (Interval); + AsyncReq->Data = Data; + AsyncReq->Callback = Callback; + AsyncReq->Context = Context; + AsyncReq->QhSw = Qh; + AsyncReq->FirstTd = FirstTd; + AsyncReq->IsLow = IsLow; // // Insert the new interrupt transfer to the head of the list. @@ -733,7 +720,6 @@ UhciCreateAsyncReq ( return EFI_SUCCESS; } - /** Free an asynchronous request's resource such as memory. @@ -743,8 +729,8 @@ UhciCreateAsyncReq ( **/ VOID UhciFreeAsyncReq ( - IN USB_HC_DEV *Uhc, - IN UHCI_ASYNC_REQUEST *AsyncReq + IN USB_HC_DEV *Uhc, + IN UHCI_ASYNC_REQUEST *AsyncReq ) { ASSERT ((Uhc != NULL) && (AsyncReq != NULL)); @@ -759,7 +745,6 @@ UhciFreeAsyncReq ( gBS->FreePool (AsyncReq); } - /** Unlink an asynchronous request's from UHC's asynchronus list. also remove the queue head from the frame list. If FreeNow, @@ -775,9 +760,9 @@ UhciFreeAsyncReq ( **/ VOID UhciUnlinkAsyncReq ( - IN USB_HC_DEV *Uhc, - IN UHCI_ASYNC_REQUEST *AsyncReq, - IN BOOLEAN FreeNow + IN USB_HC_DEV *Uhc, + IN UHCI_ASYNC_REQUEST *AsyncReq, + IN BOOLEAN FreeNow ) { ASSERT ((Uhc != NULL) && (AsyncReq != NULL)); @@ -793,12 +778,11 @@ UhciUnlinkAsyncReq ( // then add AsyncReq to UHC's recycle list // AsyncReq->QhSw->QhHw.VerticalLink = QH_VLINK (NULL, TRUE); - AsyncReq->Recycle = Uhc->RecycleWait; - Uhc->RecycleWait = AsyncReq; + AsyncReq->Recycle = Uhc->RecycleWait; + Uhc->RecycleWait = AsyncReq; } } - /** Delete Async Interrupt QH and TDs. @@ -814,10 +798,10 @@ UhciUnlinkAsyncReq ( **/ EFI_STATUS UhciRemoveAsyncReq ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 EndPoint, - OUT UINT8 *Toggle + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 EndPoint, + OUT UINT8 *Toggle ) { EFI_STATUS Status; @@ -842,14 +826,13 @@ UhciRemoveAsyncReq ( Link = Uhc->AsyncIntList.ForwardLink; do { - AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Link); - Link = Link->ForwardLink; + AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Link); + Link = Link->ForwardLink; if ((AsyncReq->DevAddr == DevAddr) && (AsyncReq->EndPoint == EndPoint)) { Found = TRUE; break; } - } while (Link != &(Uhc->AsyncIntList)); if (!Found) { @@ -870,7 +853,6 @@ UhciRemoveAsyncReq ( return Status; } - /** Recycle the asynchronouse request. When a queue head is unlinked from frame list, host controller hardware @@ -889,26 +871,24 @@ UhciRemoveAsyncReq ( **/ VOID UhciRecycleAsyncReq ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { - UHCI_ASYNC_REQUEST *Req; - UHCI_ASYNC_REQUEST *Next; + UHCI_ASYNC_REQUEST *Req; + UHCI_ASYNC_REQUEST *Next; Req = Uhc->Recycle; while (Req != NULL) { Next = Req->Recycle; UhciFreeAsyncReq (Uhc, Req); - Req = Next; + Req = Next; } Uhc->Recycle = Uhc->RecycleWait; Uhc->RecycleWait = NULL; } - - /** Release all the asynchronous transfers on the lsit. @@ -917,11 +897,11 @@ UhciRecycleAsyncReq ( **/ VOID UhciFreeAllAsyncReq ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ) { - LIST_ENTRY *Head; - UHCI_ASYNC_REQUEST *AsyncReq; + LIST_ENTRY *Head; + UHCI_ASYNC_REQUEST *AsyncReq; // // Call UhciRecycleAsyncReq twice. The requests on Recycle @@ -938,12 +918,11 @@ UhciFreeAllAsyncReq ( } while (!IsListEmpty (Head)) { - AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Head->ForwardLink); + AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Head->ForwardLink); UhciUnlinkAsyncReq (Uhc, AsyncReq, TRUE); } } - /** Interrupt transfer periodic check handler. @@ -954,18 +933,18 @@ UhciFreeAllAsyncReq ( VOID EFIAPI UhciMonitorAsyncReqList ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - UHCI_ASYNC_REQUEST *AsyncReq; - LIST_ENTRY *Link; - USB_HC_DEV *Uhc; - VOID *Data; - BOOLEAN Finished; - UHCI_QH_RESULT QhResult; + UHCI_ASYNC_REQUEST *AsyncReq; + LIST_ENTRY *Link; + USB_HC_DEV *Uhc; + VOID *Data; + BOOLEAN Finished; + UHCI_QH_RESULT QhResult; - Uhc = (USB_HC_DEV *) Context; + Uhc = (USB_HC_DEV *)Context; // // Recycle the asynchronous requests expired, and promote @@ -975,7 +954,7 @@ UhciMonitorAsyncReqList ( UhciRecycleAsyncReq (Uhc); if (IsListEmpty (&(Uhc->AsyncIntList))) { - return ; + return; } // @@ -984,8 +963,8 @@ UhciMonitorAsyncReqList ( Link = Uhc->AsyncIntList.ForwardLink; do { - AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Link); - Link = Link->ForwardLink; + AsyncReq = UHCI_ASYNC_INT_FROM_LINK (Link); + Link = Link->ForwardLink; Finished = UhciCheckTdStatus (Uhc, AsyncReq->FirstTd, AsyncReq->IsLow, &QhResult); @@ -1004,7 +983,7 @@ UhciMonitorAsyncReqList ( Data = AllocatePool (QhResult.Complete); if (Data == NULL) { - return ; + return; } CopyMem (Data, AsyncReq->FirstTd->Data, QhResult.Complete); diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.h b/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.h index 5bcfad5c6c..2112d13200 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_UHCI_SCHED_H_ #define _EFI_UHCI_SCHED_H_ - #define UHCI_ASYNC_INT_SIGNATURE SIGNATURE_32 ('u', 'h', 'c', 'a') // // The failure mask for USB transfer return status. If any of @@ -23,7 +22,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_USB_ERR_TIMEOUT | EFI_USB_ERR_BITSTUFF | \ EFI_USB_ERR_SYSTEM) - // // Structure to return the result of UHCI QH execution. // Result is the final result of the QH's QTD. NextToggle @@ -31,49 +29,48 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // length of data transferred. // typedef struct { - UINT32 Result; - UINT8 NextToggle; - UINTN Complete; + UINT32 Result; + UINT8 NextToggle; + UINTN Complete; } UHCI_QH_RESULT; -typedef struct _UHCI_ASYNC_REQUEST UHCI_ASYNC_REQUEST; +typedef struct _UHCI_ASYNC_REQUEST UHCI_ASYNC_REQUEST; // // Structure used to manager the asynchronous interrupt transfers. // -struct _UHCI_ASYNC_REQUEST{ - UINTN Signature; - LIST_ENTRY Link; - UHCI_ASYNC_REQUEST *Recycle; +struct _UHCI_ASYNC_REQUEST { + UINTN Signature; + LIST_ENTRY Link; + UHCI_ASYNC_REQUEST *Recycle; // // Endpoint attributes // - UINT8 DevAddr; - UINT8 EndPoint; - BOOLEAN IsLow; - UINTN Interval; + UINT8 DevAddr; + UINT8 EndPoint; + BOOLEAN IsLow; + UINTN Interval; // // Data and UHC structures // - UHCI_QH_SW *QhSw; - UHCI_TD_SW *FirstTd; - UINT8 *Data; // Allocated host memory, not mapped memory - UINTN DataLen; - VOID *Mapping; + UHCI_QH_SW *QhSw; + UHCI_TD_SW *FirstTd; + UINT8 *Data; // Allocated host memory, not mapped memory + UINTN DataLen; + VOID *Mapping; // // User callback and its context // - EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; - VOID *Context; + EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; + VOID *Context; }; #define UHCI_ASYNC_INT_FROM_LINK(a) \ CR (a, UHCI_ASYNC_REQUEST, Link, UHCI_ASYNC_INT_SIGNATURE) - /** Create Frame List Structure. @@ -86,7 +83,7 @@ struct _UHCI_ASYNC_REQUEST{ **/ EFI_STATUS UhciInitFrameList ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ); /** @@ -99,10 +96,9 @@ UhciInitFrameList ( **/ VOID UhciDestoryFrameList ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ); - /** Convert the poll rate to the maxium 2^n that is smaller than Interval. @@ -114,10 +110,9 @@ UhciDestoryFrameList ( **/ UINTN UhciConvertPollRate ( - IN UINTN Interval + IN UINTN Interval ); - /** Link a queue head (for asynchronous interrupt transfer) to the frame list. @@ -128,11 +123,10 @@ UhciConvertPollRate ( **/ VOID UhciLinkQhToFrameList ( - USB_HC_DEV *Uhc, - UHCI_QH_SW *Qh + USB_HC_DEV *Uhc, + UHCI_QH_SW *Qh ); - /** Unlink QH from the frame list is easier: find all the precedence node, and pointer there next to QhSw's @@ -144,11 +138,10 @@ UhciLinkQhToFrameList ( **/ VOID UhciUnlinkQhFromFrameList ( - USB_HC_DEV *Uhc, - UHCI_QH_SW *Qh + USB_HC_DEV *Uhc, + UHCI_QH_SW *Qh ); - /** Check the result of the transfer. @@ -165,15 +158,14 @@ UhciUnlinkQhFromFrameList ( **/ EFI_STATUS UhciExecuteTransfer ( - IN USB_HC_DEV *Uhc, - IN UHCI_QH_SW *Qh, - IN UHCI_TD_SW *Td, - IN UINTN TimeOut, - IN BOOLEAN IsLow, - OUT UHCI_QH_RESULT *QhResult + IN USB_HC_DEV *Uhc, + IN UHCI_QH_SW *Qh, + IN UHCI_TD_SW *Td, + IN UINTN TimeOut, + IN BOOLEAN IsLow, + OUT UHCI_QH_RESULT *QhResult ); - /** Create Async Request node, and Link to List. @@ -209,7 +201,6 @@ UhciCreateAsyncReq ( IN BOOLEAN IsLow ); - /** Delete Async Interrupt QH and TDs. @@ -225,13 +216,12 @@ UhciCreateAsyncReq ( **/ EFI_STATUS UhciRemoveAsyncReq ( - IN USB_HC_DEV *Uhc, - IN UINT8 DevAddr, - IN UINT8 EndPoint, - OUT UINT8 *Toggle + IN USB_HC_DEV *Uhc, + IN UINT8 DevAddr, + IN UINT8 EndPoint, + OUT UINT8 *Toggle ); - /** Release all the asynchronous transfers on the lsit. @@ -242,10 +232,9 @@ UhciRemoveAsyncReq ( **/ VOID UhciFreeAllAsyncReq ( - IN USB_HC_DEV *Uhc + IN USB_HC_DEV *Uhc ); - /** Interrupt transfer periodic check handler. @@ -258,8 +247,8 @@ UhciFreeAllAsyncReq ( VOID EFIAPI UhciMonitorAsyncReqList ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c b/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c index a8c098f9c3..d6b9615e49 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Uhci.h" - /** Allocate a block of memory to be used by the buffer pool. @@ -21,17 +20,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USBHC_MEM_BLOCK * UsbHcAllocMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Pages + IN USBHC_MEM_POOL *Pool, + IN UINTN Pages ) { - USBHC_MEM_BLOCK *Block; - EFI_PCI_IO_PROTOCOL *PciIo; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - UINTN Bytes; - EFI_STATUS Status; + USBHC_MEM_BLOCK *Block; + EFI_PCI_IO_PROTOCOL *PciIo; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + UINTN Bytes; + EFI_STATUS Status; PciIo = Pool->PciIo; @@ -46,9 +45,9 @@ UsbHcAllocMemBlock ( // ASSERT (USBHC_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); - Block->Bits = AllocateZeroPool (Block->BitsLen); + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); + Block->Bits = AllocateZeroPool (Block->BitsLen); if (Block->Bits == NULL) { gBS->FreePool (Block); @@ -72,7 +71,7 @@ UsbHcAllocMemBlock ( goto FREE_BITARRAY; } - Bytes = EFI_PAGES_TO_SIZE (Pages); + Bytes = EFI_PAGES_TO_SIZE (Pages); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, @@ -95,9 +94,9 @@ UsbHcAllocMemBlock ( goto FREE_BUFFER; } - Block->BufHost = BufHost; - Block->Buf = (UINT8 *) ((UINTN) MappedAddr); - Block->Mapping = Mapping; + Block->BufHost = BufHost; + Block->Buf = (UINT8 *)((UINTN)MappedAddr); + Block->Mapping = Mapping; return Block; @@ -110,7 +109,6 @@ FREE_BITARRAY: return NULL; } - /** Free the memory block from the memory pool. @@ -120,11 +118,11 @@ FREE_BITARRAY: **/ VOID UsbHcFreeMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_POOL *Pool, + IN USBHC_MEM_BLOCK *Block ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; ASSERT ((Pool != NULL) && (Block != NULL)); @@ -140,7 +138,6 @@ UsbHcFreeMemBlock ( gBS->FreePool (Block); } - /** Alloc some memory from the block. @@ -153,22 +150,22 @@ UsbHcFreeMemBlock ( **/ VOID * UsbHcAllocMemFromBlock ( - IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN USBHC_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -184,13 +181,12 @@ UsbHcAllocMemFromBlock ( } NEXT_BIT (Byte, Bit); - } else { NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -201,13 +197,13 @@ UsbHcAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -225,16 +221,16 @@ UsbHcAllocMemFromBlock ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINTN AllocSize; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINTN Offset; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINTN AllocSize; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINTN Offset; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); @@ -248,7 +244,7 @@ UsbHcGetPciAddressForHostMem ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->BufHost <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { + if ((Block->BufHost <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { break; } } @@ -257,8 +253,8 @@ UsbHcGetPciAddressForHostMem ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *)Mem - Block->BufHost; - PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN) (Block->Buf + Offset); + Offset = (UINT8 *)Mem - Block->BufHost; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->Buf + Offset); return PhyAddr; } @@ -271,8 +267,8 @@ UsbHcGetPciAddressForHostMem ( **/ VOID UsbHcInsertMemBlockToPool ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -280,7 +276,6 @@ UsbHcInsertMemBlockToPool ( Head->Next = Block; } - /** Is the memory block empty? @@ -292,10 +287,10 @@ UsbHcInsertMemBlockToPool ( **/ BOOLEAN UsbHcIsMemBlockEmpty ( - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Block ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -306,7 +301,6 @@ UsbHcIsMemBlockEmpty ( return TRUE; } - /** Unlink the memory block from the pool's list. @@ -316,11 +310,11 @@ UsbHcIsMemBlockEmpty ( **/ VOID UsbHcUnlinkMemBlock ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *BlockToUnlink + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *BlockToUnlink ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT ((Head != NULL) && (BlockToUnlink != NULL)); @@ -333,7 +327,6 @@ UsbHcUnlinkMemBlock ( } } - /** Initialize the memory management pool for the host controller. @@ -353,7 +346,7 @@ UsbHcInitMemPool ( IN UINT32 Which4G ) { - USBHC_MEM_POOL *Pool; + USBHC_MEM_POOL *Pool; Pool = AllocatePool (sizeof (USBHC_MEM_POOL)); @@ -374,7 +367,6 @@ UsbHcInitMemPool ( return Pool; } - /** Release the memory management pool. @@ -386,10 +378,10 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -408,7 +400,6 @@ UsbHcFreeMemPool ( return EFI_SUCCESS; } - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -421,16 +412,16 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - USBHC_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = USBHC_MEM_ROUND (Size); @@ -485,7 +476,6 @@ UsbHcAllocateMem ( return Mem; } - /** Free the allocated memory back to the memory pool. @@ -496,22 +486,22 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -522,8 +512,8 @@ UsbHcFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) / 8; - Bit = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) % 8; + Byte = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) / 8; + Bit = ((ToFree - Block->Buf) / USBHC_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -531,7 +521,7 @@ UsbHcFreeMem ( for (Count = 0; Count < (AllocSize / USBHC_MEM_UNIT); Count++) { ASSERT (USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -554,5 +544,5 @@ UsbHcFreeMem ( UsbHcFreeMemBlock (Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.h b/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.h index d202669c11..6644cc4d97 100644 --- a/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.h @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_EHCI_MEM_H_ #define _EFI_EHCI_MEM_H_ -#define USB_HC_BIT(a) ((UINTN)(1 << (a))) +#define USB_HC_BIT(a) ((UINTN)(1 << (a))) #define USB_HC_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & USB_HC_BIT(Bit)) == USB_HC_BIT(Bit))) @@ -18,16 +18,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USB_HC_HIGH_32BIT(Addr64) \ ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) - typedef struct _USBHC_MEM_BLOCK USBHC_MEM_BLOCK; struct _USBHC_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - USBHC_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + USBHC_MEM_BLOCK *Next; }; // @@ -36,16 +35,16 @@ struct _USBHC_MEM_BLOCK { // data to be on the same 4G memory. // typedef struct _USBHC_MEM_POOL { - EFI_PCI_IO_PROTOCOL *PciIo; - BOOLEAN Check4G; - UINT32 Which4G; - USBHC_MEM_BLOCK *Head; + EFI_PCI_IO_PROTOCOL *PciIo; + BOOLEAN Check4G; + UINT32 Which4G; + USBHC_MEM_BLOCK *Head; } USBHC_MEM_POOL; // // Memory allocation unit, must be 2^n, n>4 // -#define USBHC_MEM_UNIT 64 +#define USBHC_MEM_UNIT 64 #define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) #define USBHC_MEM_DEFAULT_PAGES 16 @@ -64,7 +63,6 @@ typedef struct _USBHC_MEM_POOL { } \ } while (0) - /** Initialize the memory management pool for the host controller. @@ -84,7 +82,6 @@ UsbHcInitMemPool ( IN UINT32 Which4G ); - /** Release the memory management pool. @@ -96,11 +93,9 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ); - - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -113,12 +108,10 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ); - - /** Free the allocated memory back to the memory pool. @@ -131,9 +124,9 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -147,9 +140,9 @@ UsbHcFreeMem ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddressForHostMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); #endif diff --git a/MdeModulePkg/Bus/Pci/UhciPei/DmaMem.c b/MdeModulePkg/Bus/Pci/UhciPei/DmaMem.c index 91e5bf5678..c6ef129235 100644 --- a/MdeModulePkg/Bus/Pci/UhciPei/DmaMem.c +++ b/MdeModulePkg/Bus/Pci/UhciPei/DmaMem.c @@ -39,8 +39,8 @@ IoMmuMap ( OUT VOID **Mapping ) { - EFI_STATUS Status; - UINT64 Attribute; + EFI_STATUS Status; + UINT64 Attribute; if (IoMmu != NULL) { Status = IoMmu->Map ( @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -82,10 +84,11 @@ IoMmuMap ( return Status; } } else { - *DeviceAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,8 +101,8 @@ IoMmuMap ( **/ VOID IoMmuUnmap ( - IN EDKII_IOMMU_PPI *IoMmu, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN VOID *Mapping ) { if (IoMmu != NULL) { @@ -140,9 +143,9 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; - *Mapping = NULL; + *Mapping = NULL; if (IoMmu != NULL) { Status = IoMmu->AllocateBuffer ( @@ -157,19 +160,20 @@ IoMmuAllocateBuffer ( } NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); - Status = IoMmu->Map ( - IoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + Status = IoMmu->Map ( + IoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { IoMmu->FreeBuffer (IoMmu, Pages, *HostAddress); *HostAddress = NULL; return EFI_OUT_OF_RESOURCES; } + Status = IoMmu->SetAttribute ( IoMmu, *Mapping, @@ -178,7 +182,7 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { IoMmu->Unmap (IoMmu, *Mapping); IoMmu->FreeBuffer (IoMmu, Pages, *HostAddress); - *Mapping = NULL; + *Mapping = NULL; *HostAddress = NULL; return Status; } @@ -191,15 +195,15 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *) (UINTN) HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } - - /** Initialize IOMMU. @@ -208,7 +212,7 @@ IoMmuAllocateBuffer ( **/ VOID IoMmuInit ( - OUT EDKII_IOMMU_PPI **IoMmu + OUT EDKII_IOMMU_PPI **IoMmu ) { *IoMmu = NULL; @@ -216,7 +220,6 @@ IoMmuInit ( &gEdkiiIoMmuPpiGuid, 0, NULL, - (VOID **) IoMmu + (VOID **)IoMmu ); } - diff --git a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c index a05834da3c..96abf3ab13 100644 --- a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c +++ b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c @@ -22,15 +22,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS UhciStopHc ( - IN USB_UHC_DEV *Uhc, - IN UINTN Timeout + IN USB_UHC_DEV *Uhc, + IN UINTN Timeout ) { - UINT16 CommandContent; - UINT16 UsbSts; - UINTN Index; + UINT16 CommandContent; + UINT16 UsbSts; + UINTN Index; - CommandContent = USBReadPortW (Uhc, Uhc->UsbHostControllerBaseAddress + USBCMD); + CommandContent = USBReadPortW (Uhc, Uhc->UsbHostControllerBaseAddress + USBCMD); CommandContent &= USBCMD_RS; USBWritePortW (Uhc, Uhc->UsbHostControllerBaseAddress + USBCMD, CommandContent); @@ -70,7 +70,7 @@ UhcEndOfPei ( IN VOID *Ppi ) { - USB_UHC_DEV *Uhc; + USB_UHC_DEV *Uhc; Uhc = PEI_RECOVERY_USB_UHC_DEV_FROM_THIS_NOTIFY (NotifyDescriptor); @@ -95,18 +95,18 @@ UhcEndOfPei ( EFI_STATUS EFIAPI UhcPeimEntry ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - PEI_USB_CONTROLLER_PPI *ChipSetUsbControllerPpi; - EFI_STATUS Status; - UINT8 Index; - UINTN ControllerType; - UINTN BaseAddress; - UINTN MemPages; - USB_UHC_DEV *UhcDev; - EFI_PHYSICAL_ADDRESS TempPtr; + PEI_USB_CONTROLLER_PPI *ChipSetUsbControllerPpi; + EFI_STATUS Status; + UINT8 Index; + UINTN ControllerType; + UINTN BaseAddress; + UINTN MemPages; + USB_UHC_DEV *UhcDev; + EFI_PHYSICAL_ADDRESS TempPtr; // // Shadow this PEIM to run from memory @@ -119,7 +119,7 @@ UhcPeimEntry ( &gPeiUsbControllerPpiGuid, 0, NULL, - (VOID **) &ChipSetUsbControllerPpi + (VOID **)&ChipSetUsbControllerPpi ); // // If failed to locate, it is a bug in dispather as depex has gPeiUsbControllerPpiGuid. @@ -129,7 +129,7 @@ UhcPeimEntry ( Index = 0; while (TRUE) { Status = ChipSetUsbControllerPpi->GetUsbController ( - (EFI_PEI_SERVICES **) PeiServices, + (EFI_PEI_SERVICES **)PeiServices, ChipSetUsbControllerPpi, Index, &ControllerType, @@ -161,10 +161,10 @@ UhcPeimEntry ( return EFI_OUT_OF_RESOURCES; } - UhcDev = (USB_UHC_DEV *) ((UINTN) TempPtr); - UhcDev->Signature = USB_UHC_DEV_SIGNATURE; + UhcDev = (USB_UHC_DEV *)((UINTN)TempPtr); + UhcDev->Signature = USB_UHC_DEV_SIGNATURE; IoMmuInit (&UhcDev->IoMmu); - UhcDev->UsbHostControllerBaseAddress = (UINT32) BaseAddress; + UhcDev->UsbHostControllerBaseAddress = (UINT32)BaseAddress; // // Init local memory management service @@ -182,12 +182,12 @@ UhcPeimEntry ( return Status; } - UhcDev->UsbHostControllerPpi.ControlTransfer = UhcControlTransfer; - UhcDev->UsbHostControllerPpi.BulkTransfer = UhcBulkTransfer; - UhcDev->UsbHostControllerPpi.GetRootHubPortNumber = UhcGetRootHubPortNumber; - UhcDev->UsbHostControllerPpi.GetRootHubPortStatus = UhcGetRootHubPortStatus; - UhcDev->UsbHostControllerPpi.SetRootHubPortFeature = UhcSetRootHubPortFeature; - UhcDev->UsbHostControllerPpi.ClearRootHubPortFeature = UhcClearRootHubPortFeature; + UhcDev->UsbHostControllerPpi.ControlTransfer = UhcControlTransfer; + UhcDev->UsbHostControllerPpi.BulkTransfer = UhcBulkTransfer; + UhcDev->UsbHostControllerPpi.GetRootHubPortNumber = UhcGetRootHubPortNumber; + UhcDev->UsbHostControllerPpi.GetRootHubPortStatus = UhcGetRootHubPortStatus; + UhcDev->UsbHostControllerPpi.SetRootHubPortFeature = UhcSetRootHubPortFeature; + UhcDev->UsbHostControllerPpi.ClearRootHubPortFeature = UhcClearRootHubPortFeature; UhcDev->PpiDescriptor.Flags = (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); UhcDev->PpiDescriptor.Guid = &gPeiUsbHostControllerPpiGuid; @@ -199,8 +199,8 @@ UhcPeimEntry ( continue; } - UhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - UhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; + UhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); + UhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; UhcDev->EndOfPeiNotifyList.Notify = UhcEndOfPei; PeiServicesNotifyPpi (&UhcDev->EndOfPeiNotifyList); @@ -239,46 +239,47 @@ UhcPeimEntry ( EFI_STATUS EFIAPI UhcControlTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 DeviceAddress, - IN UINT8 DeviceSpeed, - IN UINT8 MaximumPacketLength, - IN EFI_USB_DEVICE_REQUEST *Request, - IN EFI_USB_DATA_DIRECTION TransferDirection, - IN OUT VOID *Data OPTIONAL, - IN OUT UINTN *DataLength OPTIONAL, - IN UINTN TimeOut, - OUT UINT32 *TransferResult - ) -{ - USB_UHC_DEV *UhcDev; - UINT32 StatusReg; - UINT8 PktID; - QH_STRUCT *PtrQH; - TD_STRUCT *PtrTD; - TD_STRUCT *PtrPreTD; - TD_STRUCT *PtrSetupTD; - TD_STRUCT *PtrStatusTD; - EFI_STATUS Status; - UINT32 DataLen; - UINT8 DataToggle; - UINT8 *RequestPhy; - VOID *RequestMap; - UINT8 *DataPhy; - VOID *DataMap; + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 DeviceSpeed, + IN UINT8 MaximumPacketLength, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION TransferDirection, + IN OUT VOID *Data OPTIONAL, + IN OUT UINTN *DataLength OPTIONAL, + IN UINTN TimeOut, + OUT UINT32 *TransferResult + ) +{ + USB_UHC_DEV *UhcDev; + UINT32 StatusReg; + UINT8 PktID; + QH_STRUCT *PtrQH; + TD_STRUCT *PtrTD; + TD_STRUCT *PtrPreTD; + TD_STRUCT *PtrSetupTD; + TD_STRUCT *PtrStatusTD; + EFI_STATUS Status; + UINT32 DataLen; + UINT8 DataToggle; + UINT8 *RequestPhy; + VOID *RequestMap; + UINT8 *DataPhy; + VOID *DataMap; - UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); + UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); - StatusReg = UhcDev->UsbHostControllerBaseAddress + USBSTS; + StatusReg = UhcDev->UsbHostControllerBaseAddress + USBSTS; - PktID = INPUT_PACKET_ID; + PktID = INPUT_PACKET_ID; - RequestMap = NULL; + RequestMap = NULL; - if (Request == NULL || TransferResult == NULL) { + if ((Request == NULL) || (TransferResult == NULL)) { return EFI_INVALID_PARAMETER; } + // // if errors exist that cause host controller halt, // then return EFI_DEVICE_ERROR. @@ -307,6 +308,7 @@ UhcControlTransfer ( if (RequestMap != NULL) { IoMmuUnmap (UhcDev->IoMmu, RequestMap); } + return Status; } @@ -321,9 +323,9 @@ UhcControlTransfer ( DeviceAddress, 0, DeviceSpeed, - (UINT8 *) Request, + (UINT8 *)Request, RequestPhy, - (UINT8) sizeof (EFI_USB_DEVICE_REQUEST), + (UINT8)sizeof (EFI_USB_DEVICE_REQUEST), &PtrSetupTD ); @@ -341,22 +343,22 @@ UhcControlTransfer ( if (TransferDirection == EfiUsbNoData) { DataLen = 0; } else { - DataLen = (UINT32) *DataLength; + DataLen = (UINT32)*DataLength; } - DataToggle = 1; + DataToggle = 1; - PtrTD = PtrSetupTD; + PtrTD = PtrSetupTD; while (DataLen > 0) { // // create TD structures and link together // - UINT8 PacketSize; + UINT8 PacketSize; // // PacketSize is the data load size of each TD carries. // - PacketSize = (UINT8) DataLen; + PacketSize = (UINT8)DataLen; if (DataLen > MaximumPacketLength) { PacketSize = MaximumPacketLength; } @@ -381,9 +383,9 @@ UhcControlTransfer ( PtrPreTD = PtrTD; DataToggle ^= 1; - Data = (VOID *) ((UINT8 *) Data + PacketSize); - DataPhy += PacketSize; - DataLen -= PacketSize; + Data = (VOID *)((UINT8 *)Data + PacketSize); + DataPhy += PacketSize; + DataLen -= PacketSize; } // @@ -399,6 +401,7 @@ UhcControlTransfer ( } else { PktID = OUTPUT_PACKET_ID; } + // // create Status Stage TD structure // @@ -418,17 +421,17 @@ UhcControlTransfer ( // detail status is returned // Status = ExecuteControlTransfer ( - UhcDev, - PtrSetupTD, - DataLength, - TimeOut, - TransferResult - ); + UhcDev, + PtrSetupTD, + DataLength, + TimeOut, + TransferResult + ); // // TRUE means must search other framelistindex // - SetQHVerticalValidorInvalid(PtrQH, FALSE); + SetQHVerticalValidorInvalid (PtrQH, FALSE); DeleteQueuedTDs (UhcDev, PtrSetupTD); // @@ -436,7 +439,7 @@ UhcControlTransfer ( // if (!IsStatusOK (UhcDev, StatusReg)) { *TransferResult |= EFI_USB_ERR_SYSTEM; - Status = EFI_DEVICE_ERROR; + Status = EFI_DEVICE_ERROR; } ClearStatusReg (UhcDev, StatusReg); @@ -444,6 +447,7 @@ UhcControlTransfer ( if (DataMap != NULL) { IoMmuUnmap (UhcDev->IoMmu, DataMap); } + if (RequestMap != NULL) { IoMmuUnmap (UhcDev->IoMmu, RequestMap); } @@ -483,42 +487,42 @@ UhcControlTransfer ( EFI_STATUS EFIAPI UhcBulkTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 MaximumPacketLength, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN OUT UINT8 *DataToggle, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 MaximumPacketLength, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN OUT UINT8 *DataToggle, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ) { - USB_UHC_DEV *UhcDev; - UINT32 StatusReg; + USB_UHC_DEV *UhcDev; + UINT32 StatusReg; - UINT32 DataLen; + UINT32 DataLen; - QH_STRUCT *PtrQH; - TD_STRUCT *PtrFirstTD; - TD_STRUCT *PtrTD; - TD_STRUCT *PtrPreTD; + QH_STRUCT *PtrQH; + TD_STRUCT *PtrFirstTD; + TD_STRUCT *PtrTD; + TD_STRUCT *PtrPreTD; - UINT8 PktID; + UINT8 PktID; - BOOLEAN IsFirstTD; + BOOLEAN IsFirstTD; - EFI_STATUS Status; + EFI_STATUS Status; EFI_USB_DATA_DIRECTION TransferDirection; - BOOLEAN ShortPacketEnable; + BOOLEAN ShortPacketEnable; - UINT16 CommandContent; + UINT16 CommandContent; - UINT8 *DataPhy; - VOID *DataMap; + UINT8 *DataPhy; + VOID *DataMap; UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); @@ -533,16 +537,16 @@ UhcBulkTransfer ( USBWritePortW (UhcDev, UhcDev->UsbHostControllerBaseAddress + USBCMD, CommandContent); } - StatusReg = UhcDev->UsbHostControllerBaseAddress + USBSTS; + StatusReg = UhcDev->UsbHostControllerBaseAddress + USBSTS; // // these code lines are added here per complier's strict demand // - PktID = INPUT_PACKET_ID; - PtrTD = NULL; - PtrFirstTD = NULL; - PtrPreTD = NULL; - DataLen = 0; + PktID = INPUT_PACKET_ID; + PtrTD = NULL; + PtrFirstTD = NULL; + PtrPreTD = NULL; + DataLen = 0; ShortPacketEnable = FALSE; @@ -554,15 +558,16 @@ UhcBulkTransfer ( return EFI_INVALID_PARAMETER; } - if (MaximumPacketLength != 8 && MaximumPacketLength != 16 - && MaximumPacketLength != 32 && MaximumPacketLength != 64) { + if ( (MaximumPacketLength != 8) && (MaximumPacketLength != 16) + && (MaximumPacketLength != 32) && (MaximumPacketLength != 64)) + { return EFI_INVALID_PARAMETER; } + // // if has errors that cause host controller halt, then return EFI_DEVICE_ERROR directly. // if (!IsStatusOK (UhcDev, StatusReg)) { - ClearStatusReg (UhcDev, StatusReg); *TransferResult = EFI_USB_ERR_SYSTEM; return EFI_DEVICE_ERROR; @@ -586,7 +591,7 @@ UhcBulkTransfer ( return Status; } - DataLen = (UINT32) *DataLength; + DataLen = (UINT32)*DataLength; PtrQH = UhcDev->BulkQH; @@ -595,9 +600,9 @@ UhcBulkTransfer ( // // create TD structures and link together // - UINT8 PacketSize; + UINT8 PacketSize; - PacketSize = (UINT8) DataLen; + PacketSize = (UINT8)DataLen; if (DataLen > MaximumPacketLength) { PacketSize = MaximumPacketLength; } @@ -637,10 +642,11 @@ UhcBulkTransfer ( PtrPreTD = PtrTD; *DataToggle ^= 1; - Data = (VOID *) ((UINT8 *) Data + PacketSize); - DataPhy += PacketSize; - DataLen -= PacketSize; + Data = (VOID *)((UINT8 *)Data + PacketSize); + DataPhy += PacketSize; + DataLen -= PacketSize; } + // // link TD structures to QH structure // @@ -655,13 +661,13 @@ UhcBulkTransfer ( // of the last successful TD // Status = ExecBulkTransfer ( - UhcDev, - PtrFirstTD, - DataLength, - DataToggle, - TimeOut, - TransferResult - ); + UhcDev, + PtrFirstTD, + DataLength, + DataToggle, + TimeOut, + TransferResult + ); // // Delete Bulk transfer TD structure @@ -673,7 +679,7 @@ UhcBulkTransfer ( // if (!IsStatusOK (UhcDev, StatusReg)) { *TransferResult |= EFI_USB_ERR_SYSTEM; - Status = EFI_DEVICE_ERROR; + Status = EFI_DEVICE_ERROR; } ClearStatusReg (UhcDev, StatusReg); @@ -700,15 +706,15 @@ UhcBulkTransfer ( EFI_STATUS EFIAPI UhcGetRootHubPortNumber ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - OUT UINT8 *PortNumber + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + OUT UINT8 *PortNumber ) { - USB_UHC_DEV *UhcDev; - UINT32 PSAddr; - UINT16 RHPortControl; - UINT32 Index; + USB_UHC_DEV *UhcDev; + UINT32 PSAddr; + UINT16 RHPortControl; + UINT32 Index; UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); @@ -719,7 +725,7 @@ UhcGetRootHubPortNumber ( *PortNumber = 0; for (Index = 0; Index < 2; Index++) { - PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + Index * 2; + PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + Index * 2; RHPortControl = USBReadPortW (UhcDev, PSAddr); // // Port Register content is valid @@ -748,16 +754,16 @@ UhcGetRootHubPortNumber ( EFI_STATUS EFIAPI UhcGetRootHubPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - OUT EFI_USB_PORT_STATUS *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + OUT EFI_USB_PORT_STATUS *PortStatus ) { - USB_UHC_DEV *UhcDev; - UINT32 PSAddr; - UINT16 RHPortStatus; - UINT8 TotalPortNumber; + USB_UHC_DEV *UhcDev; + UINT32 PSAddr; + UINT16 RHPortStatus; + UINT8 TotalPortNumber; if (PortStatus == NULL) { return EFI_INVALID_PARAMETER; @@ -768,11 +774,11 @@ UhcGetRootHubPortStatus ( return EFI_INVALID_PARAMETER; } - UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); - PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; + UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); + PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; - PortStatus->PortStatus = 0; - PortStatus->PortChangeStatus = 0; + PortStatus->PortStatus = 0; + PortStatus->PortChangeStatus = 0; RHPortStatus = USBReadPortW (UhcDev, PSAddr); @@ -782,30 +788,35 @@ UhcGetRootHubPortStatus ( if ((RHPortStatus & USBPORTSC_CCS) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_CONNECTION; } + // // Port Enabled/Disabled // if ((RHPortStatus & USBPORTSC_PED) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_ENABLE; } + // // Port Suspend // if ((RHPortStatus & USBPORTSC_SUSP) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_SUSPEND; } + // // Port Reset // if ((RHPortStatus & USBPORTSC_PR) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_RESET; } + // // Low Speed Device Attached // if ((RHPortStatus & USBPORTSC_LSDA) != 0) { PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; } + // // Fill Port Status Change bits // @@ -815,6 +826,7 @@ UhcGetRootHubPortStatus ( if ((RHPortStatus & USBPORTSC_CSC) != 0) { PortStatus->PortChangeStatus |= USB_PORT_STAT_C_CONNECTION; } + // // Port Enabled/Disabled Change // @@ -841,59 +853,59 @@ UhcGetRootHubPortStatus ( EFI_STATUS EFIAPI UhcSetRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_UHC_DEV *UhcDev; - UINT32 PSAddr; - UINT32 CommandRegAddr; - UINT16 RHPortControl; - UINT8 TotalPortNumber; + USB_UHC_DEV *UhcDev; + UINT32 PSAddr; + UINT32 CommandRegAddr; + UINT16 RHPortControl; + UINT8 TotalPortNumber; UhcGetRootHubPortNumber (PeiServices, This, &TotalPortNumber); if (PortNumber > TotalPortNumber) { return EFI_INVALID_PARAMETER; } - UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); - PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; - CommandRegAddr = UhcDev->UsbHostControllerBaseAddress + USBCMD; + UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); + PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; + CommandRegAddr = UhcDev->UsbHostControllerBaseAddress + USBCMD; RHPortControl = USBReadPortW (UhcDev, PSAddr); switch (PortFeature) { + case EfiUsbPortSuspend: + if ((USBReadPortW (UhcDev, CommandRegAddr) & USBCMD_EGSM) == 0) { + // + // if global suspend is not active, can set port suspend + // + RHPortControl &= 0xfff5; + RHPortControl |= USBPORTSC_SUSP; + } - case EfiUsbPortSuspend: - if ((USBReadPortW (UhcDev, CommandRegAddr) & USBCMD_EGSM) == 0) { + break; + + case EfiUsbPortReset: + RHPortControl &= 0xfff5; + RHPortControl |= USBPORTSC_PR; // - // if global suspend is not active, can set port suspend + // Set the reset bit // - RHPortControl &= 0xfff5; - RHPortControl |= USBPORTSC_SUSP; - } - break; - - case EfiUsbPortReset: - RHPortControl &= 0xfff5; - RHPortControl |= USBPORTSC_PR; - // - // Set the reset bit - // - break; + break; - case EfiUsbPortPower: - break; + case EfiUsbPortPower: + break; - case EfiUsbPortEnable: - RHPortControl &= 0xfff5; - RHPortControl |= USBPORTSC_PED; - break; + case EfiUsbPortEnable: + RHPortControl &= 0xfff5; + RHPortControl |= USBPORTSC_PED; + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } USBWritePortW (UhcDev, PSAddr, RHPortControl); @@ -919,16 +931,16 @@ UhcSetRootHubPortFeature ( EFI_STATUS EFIAPI UhcClearRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_UHC_DEV *UhcDev; - UINT32 PSAddr; - UINT16 RHPortControl; - UINT8 TotalPortNumber; + USB_UHC_DEV *UhcDev; + UINT32 PSAddr; + UINT16 RHPortControl; + UINT8 TotalPortNumber; UhcGetRootHubPortNumber (PeiServices, This, &TotalPortNumber); @@ -936,79 +948,79 @@ UhcClearRootHubPortFeature ( return EFI_INVALID_PARAMETER; } - UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); - PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; + UhcDev = PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS (This); + PSAddr = UhcDev->UsbHostControllerBaseAddress + USBPORTSC1 + PortNumber * 2; RHPortControl = USBReadPortW (UhcDev, PSAddr); switch (PortFeature) { - // - // clear PORT_ENABLE feature means disable port. - // - case EfiUsbPortEnable: - RHPortControl &= 0xfff5; - RHPortControl &= ~USBPORTSC_PED; - break; + // + // clear PORT_ENABLE feature means disable port. + // + case EfiUsbPortEnable: + RHPortControl &= 0xfff5; + RHPortControl &= ~USBPORTSC_PED; + break; - // - // clear PORT_SUSPEND feature means resume the port. - // (cause a resume on the specified port if in suspend mode) - // - case EfiUsbPortSuspend: - RHPortControl &= 0xfff5; - RHPortControl &= ~USBPORTSC_SUSP; - break; + // + // clear PORT_SUSPEND feature means resume the port. + // (cause a resume on the specified port if in suspend mode) + // + case EfiUsbPortSuspend: + RHPortControl &= 0xfff5; + RHPortControl &= ~USBPORTSC_SUSP; + break; - // - // no operation - // - case EfiUsbPortPower: - break; + // + // no operation + // + case EfiUsbPortPower: + break; - // - // clear PORT_RESET means clear the reset signal. - // - case EfiUsbPortReset: - RHPortControl &= 0xfff5; - RHPortControl &= ~USBPORTSC_PR; - break; + // + // clear PORT_RESET means clear the reset signal. + // + case EfiUsbPortReset: + RHPortControl &= 0xfff5; + RHPortControl &= ~USBPORTSC_PR; + break; - // - // clear connect status change - // - case EfiUsbPortConnectChange: - RHPortControl &= 0xfff5; - RHPortControl |= USBPORTSC_CSC; - break; + // + // clear connect status change + // + case EfiUsbPortConnectChange: + RHPortControl &= 0xfff5; + RHPortControl |= USBPORTSC_CSC; + break; - // - // clear enable/disable status change - // - case EfiUsbPortEnableChange: - RHPortControl &= 0xfff5; - RHPortControl |= USBPORTSC_PEDC; - break; + // + // clear enable/disable status change + // + case EfiUsbPortEnableChange: + RHPortControl &= 0xfff5; + RHPortControl |= USBPORTSC_PEDC; + break; - // - // root hub does not support this request - // - case EfiUsbPortSuspendChange: - break; + // + // root hub does not support this request + // + case EfiUsbPortSuspendChange: + break; - // - // root hub does not support this request - // - case EfiUsbPortOverCurrentChange: - break; + // + // root hub does not support this request + // + case EfiUsbPortOverCurrentChange: + break; - // - // root hub does not support this request - // - case EfiUsbPortResetChange: - break; + // + // root hub does not support this request + // + case EfiUsbPortResetChange: + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } USBWritePortW (UhcDev, PSAddr, RHPortControl); @@ -1027,7 +1039,7 @@ UhcClearRootHubPortFeature ( **/ EFI_STATUS InitializeUsbHC ( - IN USB_UHC_DEV *UhcDev + IN USB_UHC_DEV *UhcDev ) { EFI_STATUS Status; @@ -1043,34 +1055,33 @@ InitializeUsbHC ( return Status; } - FrameListBaseAddrReg = UhcDev->UsbHostControllerBaseAddress + USBFLBASEADD; - CommandReg = UhcDev->UsbHostControllerBaseAddress + USBCMD; + FrameListBaseAddrReg = UhcDev->UsbHostControllerBaseAddress + USBFLBASEADD; + CommandReg = UhcDev->UsbHostControllerBaseAddress + USBCMD; // // Set Frame List Base Address to the specific register to inform the hardware. // - SetFrameListBaseAddress (UhcDev, FrameListBaseAddrReg, (UINT32) (UINTN) (UhcDev->FrameListEntry)); + SetFrameListBaseAddress (UhcDev, FrameListBaseAddrReg, (UINT32)(UINTN)(UhcDev->FrameListEntry)); - Command = USBReadPortW (UhcDev, CommandReg); + Command = USBReadPortW (UhcDev, CommandReg); Command |= USBCMD_GRESET; USBWritePortW (UhcDev, CommandReg, Command); MicroSecondDelay (50 * 1000); - Command &= ~USBCMD_GRESET; USBWritePortW (UhcDev, CommandReg, Command); // - //UHCI spec page120 reset recovery time + // UHCI spec page120 reset recovery time // MicroSecondDelay (20 * 1000); // // Set Run/Stop bit to 1. // - Command = USBReadPortW (UhcDev, CommandReg); + Command = USBReadPortW (UhcDev, CommandReg); Command |= USBCMD_RS | USBCMD_MAXP; USBWritePortW (UhcDev, CommandReg, Command); @@ -1088,7 +1099,7 @@ InitializeUsbHC ( **/ EFI_STATUS CreateFrameList ( - USB_UHC_DEV *UhcDev + USB_UHC_DEV *UhcDev ) { EFI_STATUS Status; @@ -1111,28 +1122,30 @@ CreateFrameList ( } // - //Create Control QH and Bulk QH and link them into Framelist Entry + // Create Control QH and Bulk QH and link them into Framelist Entry // - Status = CreateQH(UhcDev, &UhcDev->ConfigQH); + Status = CreateQH (UhcDev, &UhcDev->ConfigQH); if (Status != EFI_SUCCESS) { return EFI_OUT_OF_RESOURCES; } + ASSERT (UhcDev->ConfigQH != NULL); - Status = CreateQH(UhcDev, &UhcDev->BulkQH); + Status = CreateQH (UhcDev, &UhcDev->BulkQH); if (Status != EFI_SUCCESS) { return EFI_OUT_OF_RESOURCES; } + ASSERT (UhcDev->BulkQH != NULL); // - //Set the corresponding QH pointer + // Set the corresponding QH pointer // - SetQHHorizontalLinkPtr(UhcDev->ConfigQH, UhcDev->BulkQH); + SetQHHorizontalLinkPtr (UhcDev->ConfigQH, UhcDev->BulkQH); SetQHHorizontalQHorTDSelect (UhcDev->ConfigQH, TRUE); SetQHHorizontalValidorInvalid (UhcDev->ConfigQH, TRUE); - UhcDev->FrameListEntry = (FRAMELIST_ENTRY *) ((UINTN) FrameListBaseAddr); + UhcDev->FrameListEntry = (FRAMELIST_ENTRY *)((UINTN)FrameListBaseAddr); FrameListPtr = UhcDev->FrameListEntry; @@ -1141,7 +1154,7 @@ CreateFrameList ( FrameListPtr->FrameListPtr = (UINT32)(UINTN)UhcDev->ConfigQH >> 4; FrameListPtr->FrameListPtrQSelect = 1; FrameListPtr->FrameListRsvd = 0; - FrameListPtr ++; + FrameListPtr++; } return EFI_SUCCESS; @@ -1158,8 +1171,8 @@ CreateFrameList ( **/ UINT16 USBReadPortW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port ) { return IoRead16 (Port); @@ -1175,9 +1188,9 @@ USBReadPortW ( **/ VOID USBWritePortW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port, - IN UINT16 Data + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port, + IN UINT16 Data ) { IoWrite16 (Port, Data); @@ -1193,9 +1206,9 @@ USBWritePortW ( **/ VOID USBWritePortDW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port, - IN UINT32 Data + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port, + IN UINT32 Data ) { IoWrite32 (Port, Data); @@ -1210,8 +1223,8 @@ USBWritePortDW ( **/ VOID ClearStatusReg ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 StatusAddr + IN USB_UHC_DEV *UhcDev, + IN UINT32 StatusAddr ) { // @@ -1232,8 +1245,8 @@ ClearStatusReg ( **/ BOOLEAN IsStatusOK ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 StatusRegAddr + IN USB_UHC_DEV *UhcDev, + IN UINT32 StatusRegAddr ) { UINT16 StatusValue; @@ -1247,8 +1260,6 @@ IsStatusOK ( } } - - /** Set Frame List Base Address. @@ -1259,15 +1270,15 @@ IsStatusOK ( **/ VOID SetFrameListBaseAddress ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 FrameListRegAddr, - IN UINT32 Addr + IN USB_UHC_DEV *UhcDev, + IN UINT32 FrameListRegAddr, + IN UINT32 Addr ) { // // Sets value in the USB Frame List Base Address register. // - USBWritePortDW (UhcDev, FrameListRegAddr, (UINT32) (Addr & 0xFFFFF000)); + USBWritePortDW (UhcDev, FrameListRegAddr, (UINT32)(Addr & 0xFFFFF000)); } /** @@ -1282,8 +1293,8 @@ SetFrameListBaseAddress ( **/ EFI_STATUS CreateQH ( - IN USB_UHC_DEV *UhcDev, - OUT QH_STRUCT **PtrQH + IN USB_UHC_DEV *UhcDev, + OUT QH_STRUCT **PtrQH ) { EFI_STATUS Status; @@ -1291,10 +1302,11 @@ CreateQH ( // // allocate align memory for QH_STRUCT // - Status = AllocateTDorQHStruct (UhcDev, sizeof(QH_STRUCT), (void **)PtrQH); + Status = AllocateTDorQHStruct (UhcDev, sizeof (QH_STRUCT), (void **)PtrQH); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + // // init each field of the QH_STRUCT // @@ -1322,11 +1334,9 @@ SetQHHorizontalLinkPtr ( // Only the highest 28bit of the address is valid // (take 32bit address as an example). // - PtrQH->QueueHead.QHHorizontalPtr = (UINT32) (UINTN) PtrNext >> 4; + PtrQH->QueueHead.QHHorizontalPtr = (UINT32)(UINTN)PtrNext >> 4; } - - /** Set a QH or TD horizontally to be connected with a specific QH. @@ -1385,7 +1395,7 @@ SetQHVerticalLinkPtr ( // Only the highest 28bit of the address is valid // (take 32bit address as an example). // - PtrQH->QueueHead.QHVerticalPtr = (UINT32) (UINTN) PtrNext >> 4; + PtrQH->QueueHead.QHVerticalPtr = (UINT32)(UINTN)PtrNext >> 4; } /** @@ -1428,8 +1438,6 @@ SetQHVerticalValidorInvalid ( PtrQH->QueueHead.QHVerticalTerminate = IsValid ? 0 : 1; } - - /** Allocate TD or QH Struct. @@ -1443,21 +1451,21 @@ SetQHVerticalValidorInvalid ( **/ EFI_STATUS AllocateTDorQHStruct ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Size, - OUT VOID **PtrStruct + IN USB_UHC_DEV *UhcDev, + IN UINT32 Size, + OUT VOID **PtrStruct ) { EFI_STATUS Status; - Status = EFI_SUCCESS; - *PtrStruct = NULL; + Status = EFI_SUCCESS; + *PtrStruct = NULL; Status = UhcAllocatePool ( - UhcDev, - (UINT8 **) PtrStruct, - Size - ); + UhcDev, + (UINT8 **)PtrStruct, + Size + ); if (EFI_ERROR (Status)) { return Status; } @@ -1479,15 +1487,16 @@ AllocateTDorQHStruct ( **/ EFI_STATUS CreateTD ( - IN USB_UHC_DEV *UhcDev, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + OUT TD_STRUCT **PtrTD ) { EFI_STATUS Status; + // // create memory for TD_STRUCT, and align the memory. // - Status = AllocateTDorQHStruct (UhcDev, sizeof(TD_STRUCT), (void **)PtrTD); + Status = AllocateTDorQHStruct (UhcDev, sizeof (TD_STRUCT), (void **)PtrTD); if (EFI_ERROR (Status)) { return Status; } @@ -1518,14 +1527,14 @@ CreateTD ( **/ EFI_STATUS GenSetupStageTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 DeviceSpeed, - IN UINT8 *DevRequest, - IN UINT8 *RequestPhy, - IN UINT8 RequestLen, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 DeviceSpeed, + IN UINT8 *DevRequest, + IN UINT8 *RequestPhy, + IN UINT8 RequestLen, + OUT TD_STRUCT **PtrTD ) { TD_STRUCT *TdStruct; @@ -1564,14 +1573,15 @@ GenSetupStageTD ( // (TRUE - Slow Device; FALSE - Full Speed Device) // switch (DeviceSpeed) { - case USB_SLOW_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (TdStruct, TRUE); - break; + case USB_SLOW_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (TdStruct, TRUE); + break; - case USB_FULL_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (TdStruct, FALSE); - break; + case USB_FULL_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (TdStruct, FALSE); + break; } + // // Non isochronous transfer TD // @@ -1598,13 +1608,13 @@ GenSetupStageTD ( SetTDTokenPacketID (TdStruct, SETUP_PACKET_ID); - TdStruct->PtrTDBuffer = (UINT8 *) DevRequest; + TdStruct->PtrTDBuffer = (UINT8 *)DevRequest; TdStruct->TDBufferLength = RequestLen; // // Set the beginning address of the buffer that will be used // during the transaction. // - TdStruct->TDData.TDBufferPtr = (UINT32) (UINTN) RequestPhy; + TdStruct->TDData.TDBufferPtr = (UINT32)(UINTN)RequestPhy; *PtrTD = TdStruct; @@ -1631,16 +1641,16 @@ GenSetupStageTD ( **/ EFI_STATUS GenDataTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 *PtrData, - IN UINT8 *DataPhy, - IN UINT8 Len, - IN UINT8 PktID, - IN UINT8 Toggle, - IN UINT8 DeviceSpeed, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 *PtrData, + IN UINT8 *DataPhy, + IN UINT8 Len, + IN UINT8 PktID, + IN UINT8 Toggle, + IN UINT8 DeviceSpeed, + OUT TD_STRUCT **PtrTD ) { TD_STRUCT *TdStruct; @@ -1683,14 +1693,15 @@ GenDataTD ( // (TRUE - Slow Device; FALSE - Full Speed Device) // switch (DeviceSpeed) { - case USB_SLOW_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (TdStruct, TRUE); - break; + case USB_SLOW_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (TdStruct, TRUE); + break; - case USB_FULL_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (TdStruct, FALSE); - break; + case USB_FULL_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (TdStruct, FALSE); + break; } + // // Non isochronous transfer TD // @@ -1721,13 +1732,13 @@ GenDataTD ( SetTDTokenPacketID (TdStruct, PktID); - TdStruct->PtrTDBuffer = (UINT8 *) PtrData; + TdStruct->PtrTDBuffer = (UINT8 *)PtrData; TdStruct->TDBufferLength = Len; // // Set the beginning address of the buffer that will be used // during the transaction. // - TdStruct->TDData.TDBufferPtr = (UINT32) (UINTN) DataPhy; + TdStruct->TDData.TDBufferPtr = (UINT32)(UINTN)DataPhy; *PtrTD = TdStruct; @@ -1750,12 +1761,12 @@ GenDataTD ( **/ EFI_STATUS CreateStatusTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 PktID, - IN UINT8 DeviceSpeed, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 PktID, + IN UINT8 DeviceSpeed, + OUT TD_STRUCT **PtrTD ) { TD_STRUCT *PtrTDStruct; @@ -1794,14 +1805,15 @@ CreateStatusTD ( // (TRUE - Slow Device; FALSE - Full Speed Device) // switch (DeviceSpeed) { - case USB_SLOW_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (PtrTDStruct, TRUE); - break; + case USB_SLOW_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (PtrTDStruct, TRUE); + break; - case USB_FULL_SPEED_DEVICE: - SetTDLoworFullSpeedDevice (PtrTDStruct, FALSE); - break; + case USB_FULL_SPEED_DEVICE: + SetTDLoworFullSpeedDevice (PtrTDStruct, FALSE); + break; } + // // Non isochronous transfer TD // @@ -1828,7 +1840,7 @@ CreateStatusTD ( SetTDTokenPacketID (PtrTDStruct, PktID); - PtrTDStruct->PtrTDBuffer = NULL; + PtrTDStruct->PtrTDBuffer = NULL; PtrTDStruct->TDBufferLength = 0; // // Set the beginning address of the buffer that will be used @@ -1850,8 +1862,8 @@ CreateStatusTD ( **/ VOID SetTDLinkPtrValidorInvalid ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsValid + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsValid ) { // @@ -1870,8 +1882,8 @@ SetTDLinkPtrValidorInvalid ( **/ VOID SetTDLinkPtrQHorTDSelect ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsQH + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsQH ) { // @@ -1889,8 +1901,8 @@ SetTDLinkPtrQHorTDSelect ( **/ VOID SetTDLinkPtrDepthorBreadth ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsDepth + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsDepth ) { // @@ -1909,15 +1921,15 @@ SetTDLinkPtrDepthorBreadth ( **/ VOID SetTDLinkPtr ( - IN TD_STRUCT *PtrTDStruct, - IN VOID *PtrNext + IN TD_STRUCT *PtrTDStruct, + IN VOID *PtrNext ) { // // Set TD Link Pointer. Since QH,TD align on 16-byte boundaries, // only the highest 28 bits are valid. (if take 32bit address as an example) // - PtrTDStruct->TDData.TDLinkPtr = (UINT32) (UINTN) PtrNext >> 4; + PtrTDStruct->TDData.TDLinkPtr = (UINT32)(UINTN)PtrNext >> 4; } /** @@ -1930,18 +1942,16 @@ SetTDLinkPtr ( **/ VOID * GetTDLinkPtr ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { // // Get TD Link Pointer. Restore it back to 32bit // (if take 32bit address as an example) // - return (VOID *) (UINTN) ((PtrTDStruct->TDData.TDLinkPtr) << 4); + return (VOID *)(UINTN)((PtrTDStruct->TDData.TDLinkPtr) << 4); } - - /** Enable/Disable short packet detection mechanism. @@ -1951,8 +1961,8 @@ GetTDLinkPtr ( **/ VOID EnableorDisableTDShortPacket ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsEnable + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsEnable ) { // @@ -1970,8 +1980,8 @@ EnableorDisableTDShortPacket ( **/ VOID SetTDControlErrorCounter ( - IN TD_STRUCT *PtrTDStruct, - IN UINT8 MaxErrors + IN TD_STRUCT *PtrTDStruct, + IN UINT8 MaxErrors ) { // @@ -1993,8 +2003,8 @@ SetTDControlErrorCounter ( **/ VOID SetTDLoworFullSpeedDevice ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsLowSpeedDevice + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsLowSpeedDevice ) { // @@ -2012,8 +2022,8 @@ SetTDLoworFullSpeedDevice ( **/ VOID SetTDControlIsochronousorNot ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsIsochronous + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsIsochronous ) { // @@ -2032,8 +2042,8 @@ SetTDControlIsochronousorNot ( **/ VOID SetorClearTDControlIOC ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsSet + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsSet ) { // @@ -2052,8 +2062,8 @@ SetorClearTDControlIOC ( **/ VOID SetTDStatusActiveorInactive ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsActive + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsActive ) { // @@ -2077,8 +2087,8 @@ SetTDStatusActiveorInactive ( **/ UINT16 SetTDTokenMaxLength ( - IN TD_STRUCT *PtrTDStruct, - IN UINT16 MaxLen + IN TD_STRUCT *PtrTDStruct, + IN UINT16 MaxLen ) { // @@ -2102,7 +2112,7 @@ SetTDTokenMaxLength ( **/ VOID SetTDTokenDataToggle1 ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { // @@ -2119,7 +2129,7 @@ SetTDTokenDataToggle1 ( **/ VOID SetTDTokenDataToggle0 ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { // @@ -2137,14 +2147,14 @@ SetTDTokenDataToggle0 ( **/ VOID SetTDTokenEndPoint ( - IN TD_STRUCT *PtrTDStruct, - IN UINTN EndPoint + IN TD_STRUCT *PtrTDStruct, + IN UINTN EndPoint ) { // // Set EndPoint Number the TD is targeting at. // - PtrTDStruct->TDData.TDTokenEndPt = (UINT8) EndPoint; + PtrTDStruct->TDData.TDTokenEndPt = (UINT8)EndPoint; } /** @@ -2156,14 +2166,14 @@ SetTDTokenEndPoint ( **/ VOID SetTDTokenDeviceAddress ( - IN TD_STRUCT *PtrTDStruct, - IN UINTN DevAddr + IN TD_STRUCT *PtrTDStruct, + IN UINTN DevAddr ) { // // Set Device Address the TD is targeting at. // - PtrTDStruct->TDData.TDTokenDevAddr = (UINT8) DevAddr; + PtrTDStruct->TDData.TDTokenDevAddr = (UINT8)DevAddr; } /** @@ -2175,8 +2185,8 @@ SetTDTokenDeviceAddress ( **/ VOID SetTDTokenPacketID ( - IN TD_STRUCT *PtrTDStruct, - IN UINT8 PacketID + IN TD_STRUCT *PtrTDStruct, + IN UINT8 PacketID ) { // @@ -2195,16 +2205,16 @@ SetTDTokenPacketID ( **/ BOOLEAN IsTDStatusActive ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether the TD is active. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x80); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x80); } /** @@ -2217,16 +2227,16 @@ IsTDStatusActive ( **/ BOOLEAN IsTDStatusStalled ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether the device/endpoint addressed by this TD is stalled. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x40); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x40); } /** @@ -2239,16 +2249,16 @@ IsTDStatusStalled ( **/ BOOLEAN IsTDStatusBufferError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether Data Buffer Error is happened. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x20); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x20); } /** @@ -2261,16 +2271,16 @@ IsTDStatusBufferError ( **/ BOOLEAN IsTDStatusBabbleError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether Babble Error is happened. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x10); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x10); } /** @@ -2283,16 +2293,16 @@ IsTDStatusBabbleError ( **/ BOOLEAN IsTDStatusNAKReceived ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether NAK is received. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x08); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x08); } /** @@ -2305,16 +2315,16 @@ IsTDStatusNAKReceived ( **/ BOOLEAN IsTDStatusCRCTimeOutError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether CRC/Time Out Error is encountered. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x04); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x04); } /** @@ -2327,16 +2337,16 @@ IsTDStatusCRCTimeOutError ( **/ BOOLEAN IsTDStatusBitStuffError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { - UINT8 TDStatus; + UINT8 TDStatus; // // Detect whether Bitstuff Error is received. // - TDStatus = (UINT8) (PtrTDStruct->TDData.TDStatus); - return (BOOLEAN) (TDStatus & 0x02); + TDStatus = (UINT8)(PtrTDStruct->TDData.TDStatus); + return (BOOLEAN)(TDStatus & 0x02); } /** @@ -2349,14 +2359,14 @@ IsTDStatusBitStuffError ( **/ UINT16 GetTDStatusActualLength ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { // // Retrieve the actual number of bytes that were tansferred. // the value is encoded as n-1. so return the decoded value. // - return (UINT16) ((PtrTDStruct->TDData.TDStatusActualLength) + 1); + return (UINT16)((PtrTDStruct->TDData.TDStatusActualLength) + 1); } /** @@ -2369,7 +2379,7 @@ GetTDStatusActualLength ( **/ BOOLEAN GetTDLinkPtrValidorInvalid ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ) { // @@ -2381,7 +2391,6 @@ GetTDLinkPtrValidorInvalid ( } else { return TRUE; } - } /** @@ -2394,19 +2403,19 @@ GetTDLinkPtrValidorInvalid ( **/ UINTN CountTDsNumber ( - IN TD_STRUCT *PtrFirstTD + IN TD_STRUCT *PtrFirstTD ) { - UINTN Number; - TD_STRUCT *Ptr; + UINTN Number; + TD_STRUCT *Ptr; // // Count the queued TDs number. // - Number = 0; - Ptr = PtrFirstTD; + Number = 0; + Ptr = PtrFirstTD; while (Ptr != 0) { - Ptr = (TD_STRUCT *) Ptr->PtrNextTD; + Ptr = (TD_STRUCT *)Ptr->PtrNextTD; Number++; } @@ -2422,13 +2431,14 @@ CountTDsNumber ( **/ VOID LinkTDToQH ( - IN QH_STRUCT *PtrQH, - IN TD_STRUCT *PtrTD + IN QH_STRUCT *PtrQH, + IN TD_STRUCT *PtrTD ) { - if (PtrQH == NULL || PtrTD == NULL) { - return ; + if ((PtrQH == NULL) || (PtrTD == NULL)) { + return; } + // // Validate QH Vertical Ptr field // @@ -2439,9 +2449,9 @@ LinkTDToQH ( // SetQHVerticalQHorTDSelect (PtrQH, FALSE); - SetQHVerticalLinkPtr (PtrQH, (VOID *) PtrTD); + SetQHVerticalLinkPtr (PtrQH, (VOID *)PtrTD); - PtrQH->PtrDown = (VOID *) PtrTD; + PtrQH->PtrDown = (VOID *)PtrTD; } /** @@ -2453,13 +2463,14 @@ LinkTDToQH ( **/ VOID LinkTDToTD ( - IN TD_STRUCT *PtrPreTD, - IN TD_STRUCT *PtrTD + IN TD_STRUCT *PtrPreTD, + IN TD_STRUCT *PtrTD ) { - if (PtrPreTD == NULL || PtrTD == NULL) { - return ; + if ((PtrPreTD == NULL) || (PtrTD == NULL)) { + return; } + // // Depth first fashion // @@ -2477,9 +2488,9 @@ LinkTDToTD ( SetTDLinkPtr (PtrPreTD, PtrTD); - PtrPreTD->PtrNextTD = (VOID *) PtrTD; + PtrPreTD->PtrNextTD = (VOID *)PtrTD; - PtrTD->PtrNextTD = NULL; + PtrTD->PtrNextTD = NULL; } /** @@ -2498,21 +2509,21 @@ LinkTDToTD ( **/ EFI_STATUS ExecuteControlTransfer ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrTD, - OUT UINTN *ActualLen, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrTD, + OUT UINTN *ActualLen, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ) { - UINTN ErrTDPos; - UINTN Delay; - BOOLEAN InfiniteLoop; + UINTN ErrTDPos; + UINTN Delay; + BOOLEAN InfiniteLoop; - ErrTDPos = 0; - *TransferResult = EFI_USB_NOERROR; - *ActualLen = 0; - InfiniteLoop = FALSE; + ErrTDPos = 0; + *TransferResult = EFI_USB_NOERROR; + *ActualLen = 0; + InfiniteLoop = FALSE; Delay = TimeOut * STALL_1_MILLI_SECOND; // @@ -2524,7 +2535,6 @@ ExecuteControlTransfer ( } do { - CheckTDsResults (PtrTD, TransferResult, &ErrTDPos, ActualLen); // @@ -2533,9 +2543,9 @@ ExecuteControlTransfer ( if ((*TransferResult & EFI_USB_ERR_NOTEXECUTE) != EFI_USB_ERR_NOTEXECUTE) { break; } + MicroSecondDelay (STALL_1_MICRO_SECOND); Delay--; - } while (InfiniteLoop || (Delay != 0)); if (*TransferResult != EFI_USB_NOERROR) { @@ -2562,23 +2572,23 @@ ExecuteControlTransfer ( **/ EFI_STATUS ExecBulkTransfer ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrTD, - IN OUT UINTN *ActualLen, - IN UINT8 *DataToggle, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrTD, + IN OUT UINTN *ActualLen, + IN UINT8 *DataToggle, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ) { - UINTN ErrTDPos; - UINTN ScrollNum; - UINTN Delay; - BOOLEAN InfiniteLoop; + UINTN ErrTDPos; + UINTN ScrollNum; + UINTN Delay; + BOOLEAN InfiniteLoop; - ErrTDPos = 0; - *TransferResult = EFI_USB_NOERROR; - *ActualLen = 0; - InfiniteLoop = FALSE; + ErrTDPos = 0; + *TransferResult = EFI_USB_NOERROR; + *ActualLen = 0; + InfiniteLoop = FALSE; Delay = TimeOut * STALL_1_MILLI_SECOND; // @@ -2590,7 +2600,6 @@ ExecBulkTransfer ( } do { - CheckTDsResults (PtrTD, TransferResult, &ErrTDPos, ActualLen); // // TD is inactive, thus meaning bulk transfer's end. @@ -2598,9 +2607,9 @@ ExecBulkTransfer ( if ((*TransferResult & EFI_USB_ERR_NOTEXECUTE) != EFI_USB_ERR_NOTEXECUTE) { break; } + MicroSecondDelay (STALL_1_MICRO_SECOND); Delay--; - } while (InfiniteLoop || (Delay != 0)); // @@ -2615,9 +2624,9 @@ ExecBulkTransfer ( *DataToggle ^= 1; } - // - // If error, wait 100ms to retry by upper layer - // + // + // If error, wait 100ms to retry by upper layer + // MicroSecondDelay (100 * 1000); return EFI_DEVICE_ERROR; } @@ -2634,20 +2643,19 @@ ExecBulkTransfer ( **/ VOID DeleteQueuedTDs ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrFirstTD + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrFirstTD ) { - TD_STRUCT *Tptr1; + TD_STRUCT *Tptr1; - TD_STRUCT *Tptr2; + TD_STRUCT *Tptr2; Tptr1 = PtrFirstTD; // // Delete all the TDs in a queue. // while (Tptr1 != NULL) { - Tptr2 = Tptr1; if (!GetTDLinkPtrValidorInvalid (Tptr2)) { @@ -2659,10 +2667,10 @@ DeleteQueuedTDs ( Tptr1 = GetTDLinkPtr (Tptr2); } - UhcFreePool (UhcDev, (UINT8 *) Tptr2, sizeof (TD_STRUCT)); + UhcFreePool (UhcDev, (UINT8 *)Tptr2, sizeof (TD_STRUCT)); } - return ; + return; } /** @@ -2678,13 +2686,13 @@ DeleteQueuedTDs ( **/ BOOLEAN CheckTDsResults ( - IN TD_STRUCT *PtrTD, - OUT UINT32 *Result, - OUT UINTN *ErrTDPos, - OUT UINTN *ActualTransferSize + IN TD_STRUCT *PtrTD, + OUT UINT32 *Result, + OUT UINTN *ErrTDPos, + OUT UINTN *ActualTransferSize ) { - UINTN Len; + UINTN Len; *Result = EFI_USB_NOERROR; *ErrTDPos = 0; @@ -2695,7 +2703,6 @@ CheckTDsResults ( *ActualTransferSize = 0; while (PtrTD != NULL) { - if (IsTDStatusActive (PtrTD)) { *Result |= EFI_USB_ERR_NOTEXECUTE; } @@ -2723,10 +2730,11 @@ CheckTDsResults ( if (IsTDStatusBitStuffError (PtrTD)) { *Result |= EFI_USB_ERR_BITSTUFF; } + // // Accumulate actual transferred data length in each TD. // - Len = GetTDStatusActualLength (PtrTD) & 0x7FF; + Len = GetTDStatusActualLength (PtrTD) & 0x7FF; *ActualTransferSize += Len; // @@ -2736,7 +2744,7 @@ CheckTDsResults ( return FALSE; } - PtrTD = (TD_STRUCT *) (PtrTD->PtrNextTD); + PtrTD = (TD_STRUCT *)(PtrTD->PtrNextTD); // // Record the first Error TD's position in the queue, // this value is zero-based. @@ -2777,13 +2785,13 @@ CreateMemoryBlock ( // memory management header and bit array use 1 page // MemPages = MemoryBlockSizeInPages + 1; - Status = IoMmuAllocateBuffer ( - UhcDev->IoMmu, - MemPages, - (VOID **) &TempPtr, - &MappedAddr, - &Mapping - ); + Status = IoMmuAllocateBuffer ( + UhcDev->IoMmu, + MemPages, + (VOID **)&TempPtr, + &MappedAddr, + &Mapping + ); if (EFI_ERROR (Status) || (TempPtr == NULL)) { return EFI_OUT_OF_RESOURCES; } @@ -2792,7 +2800,7 @@ CreateMemoryBlock ( ZeroMem (Ptr, MemPages * EFI_PAGE_SIZE); - *MemoryHeader = (MEMORY_MANAGE_HEADER *) Ptr; + *MemoryHeader = (MEMORY_MANAGE_HEADER *)Ptr; // // adjust Ptr pointer to the next empty memory // @@ -2800,15 +2808,15 @@ CreateMemoryBlock ( // // Set Bit Array initial address // - (*MemoryHeader)->BitArrayPtr = Ptr; + (*MemoryHeader)->BitArrayPtr = Ptr; - (*MemoryHeader)->Next = NULL; + (*MemoryHeader)->Next = NULL; // // Memory block initial address // - Ptr = TempPtr; - Ptr += EFI_PAGE_SIZE; + Ptr = TempPtr; + Ptr += EFI_PAGE_SIZE; (*MemoryHeader)->MemoryBlockPtr = Ptr; // // set Memory block size @@ -2833,15 +2841,15 @@ CreateMemoryBlock ( **/ EFI_STATUS InitializeMemoryManagement ( - IN USB_UHC_DEV *UhcDev + IN USB_UHC_DEV *UhcDev ) { MEMORY_MANAGE_HEADER *MemoryHeader; EFI_STATUS Status; UINTN MemPages; - MemPages = NORMAL_MEMORY_BLOCK_UNIT_IN_PAGES; - Status = CreateMemoryBlock (UhcDev, &MemoryHeader, MemPages); + MemPages = NORMAL_MEMORY_BLOCK_UNIT_IN_PAGES; + Status = CreateMemoryBlock (UhcDev, &MemoryHeader, MemPages); if (EFI_ERROR (Status)) { return Status; } @@ -2864,9 +2872,9 @@ InitializeMemoryManagement ( **/ EFI_STATUS UhcAllocatePool ( - IN USB_UHC_DEV *UhcDev, - OUT UINT8 **Pool, - IN UINTN AllocSize + IN USB_UHC_DEV *UhcDev, + OUT UINT8 **Pool, + IN UINTN AllocSize ) { MEMORY_MANAGE_HEADER *MemoryHeader; @@ -2891,16 +2899,16 @@ UhcAllocatePool ( Status = EFI_NOT_FOUND; for (TempHeaderPtr = MemoryHeader; TempHeaderPtr != NULL; TempHeaderPtr = TempHeaderPtr->Next) { - Status = AllocMemInMemoryBlock ( - TempHeaderPtr, - (VOID **) Pool, - RealAllocSize / 32 - ); + TempHeaderPtr, + (VOID **)Pool, + RealAllocSize / 32 + ); if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } } + // // There is no enough memory, // Create a new Memory Block @@ -2919,16 +2927,17 @@ UhcAllocatePool ( if (EFI_ERROR (Status)) { return Status; } + // // Link the new Memory Block to the Memory Header list // InsertMemoryHeaderToList (MemoryHeader, NewMemoryHeader); Status = AllocMemInMemoryBlock ( - NewMemoryHeader, - (VOID **) Pool, - RealAllocSize / 32 - ); + NewMemoryHeader, + (VOID **)Pool, + RealAllocSize / 32 + ); return Status; } @@ -2950,21 +2959,21 @@ AllocMemInMemoryBlock ( IN UINTN NumberOfMemoryUnit ) { - UINTN TempBytePos; - UINTN FoundBytePos; - UINT8 Index; - UINT8 FoundBitPos; - UINT8 ByteValue; - UINT8 BitValue; - UINTN NumberOfZeros; - UINTN Count; + UINTN TempBytePos; + UINTN FoundBytePos; + UINT8 Index; + UINT8 FoundBitPos; + UINT8 ByteValue; + UINT8 BitValue; + UINTN NumberOfZeros; + UINTN Count; - FoundBytePos = 0; - FoundBitPos = 0; + FoundBytePos = 0; + FoundBitPos = 0; ByteValue = MemoryHeader->BitArrayPtr[0]; NumberOfZeros = 0; - Index = 0; + Index = 0; for (TempBytePos = 0; TempBytePos < MemoryHeader->BitArraySizeInBytes;) { // // Pop out BitValue from a byte in TempBytePos. @@ -3001,10 +3010,11 @@ AllocMemInMemoryBlock ( // // reset the (FoundBytePos,FoundBitPos) to the position of '1' // - FoundBytePos = TempBytePos; - FoundBitPos = Index; + FoundBytePos = TempBytePos; + FoundBitPos = Index; } } + // // right shift the byte // @@ -3020,14 +3030,15 @@ AllocMemInMemoryBlock ( // and reset the bit pos. // TempBytePos += 1; - ByteValue = MemoryHeader->BitArrayPtr[TempBytePos]; - Index = 0; + ByteValue = MemoryHeader->BitArrayPtr[TempBytePos]; + Index = 0; } } if (NumberOfZeros < NumberOfMemoryUnit) { return EFI_NOT_FOUND; } + // // Found enough free space. // @@ -3042,23 +3053,24 @@ AllocMemInMemoryBlock ( if ((MemoryHeader->BitArrayPtr[0] & BIT0) != 0) { FoundBitPos += 1; } + // // Have the (FoundBytePos,FoundBitPos) make sense. // if (FoundBitPos > 7) { FoundBytePos += 1; - FoundBitPos -= 8; + FoundBitPos -= 8; } + // // Set the memory as allocated // for (TempBytePos = FoundBytePos, Index = FoundBitPos, Count = 0; Count < NumberOfMemoryUnit; Count++) { - - MemoryHeader->BitArrayPtr[TempBytePos] = (UINT8) (MemoryHeader->BitArrayPtr[TempBytePos] | (1 << Index)); + MemoryHeader->BitArrayPtr[TempBytePos] = (UINT8)(MemoryHeader->BitArrayPtr[TempBytePos] | (1 << Index)); Index++; if (Index == 8) { TempBytePos += 1; - Index = 0; + Index = 0; } } @@ -3077,9 +3089,9 @@ AllocMemInMemoryBlock ( **/ VOID UhcFreePool ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 *Pool, - IN UINTN AllocSize + IN USB_UHC_DEV *UhcDev, + IN UINT8 *Pool, + IN UINTN AllocSize ) { MEMORY_MANAGE_HEADER *MemoryHeader; @@ -3103,38 +3115,37 @@ UhcFreePool ( } for (TempHeaderPtr = MemoryHeader; TempHeaderPtr != NULL; - TempHeaderPtr = TempHeaderPtr->Next) { - + TempHeaderPtr = TempHeaderPtr->Next) + { if ((Pool >= TempHeaderPtr->MemoryBlockPtr) && ((Pool + RealAllocSize) <= (TempHeaderPtr->MemoryBlockPtr + - TempHeaderPtr->MemoryBlockSizeInBytes))) { - + TempHeaderPtr->MemoryBlockSizeInBytes))) + { // // Pool is in the Memory Block area, // find the start byte and bit in the bit array // - StartBytePos = ((Pool - TempHeaderPtr->MemoryBlockPtr) / 32) / 8; - StartBitPos = (UINT8) (((Pool - TempHeaderPtr->MemoryBlockPtr) / 32) % 8); + StartBytePos = ((Pool - TempHeaderPtr->MemoryBlockPtr) / 32) / 8; + StartBitPos = (UINT8)(((Pool - TempHeaderPtr->MemoryBlockPtr) / 32) % 8); // // reset associated bits in bit array // for (Index = StartBytePos, Index2 = StartBitPos, Count = 0; Count < (RealAllocSize / 32); Count++) { - - TempHeaderPtr->BitArrayPtr[Index] = (UINT8) (TempHeaderPtr->BitArrayPtr[Index] ^ (1 << Index2)); + TempHeaderPtr->BitArrayPtr[Index] = (UINT8)(TempHeaderPtr->BitArrayPtr[Index] ^ (1 << Index2)); Index2++; if (Index2 == 8) { Index += 1; Index2 = 0; } } + // // break the loop // break; } } - } /** @@ -3160,10 +3171,6 @@ InsertMemoryHeaderToList ( } } - - - - /** Map address of request structure buffer. @@ -3178,10 +3185,10 @@ InsertMemoryHeaderToList ( **/ EFI_STATUS UhciMapUserRequest ( - IN USB_UHC_DEV *Uhc, - IN OUT VOID *Request, - OUT UINT8 **MappedAddr, - OUT VOID **Map + IN USB_UHC_DEV *Uhc, + IN OUT VOID *Request, + OUT UINT8 **MappedAddr, + OUT VOID **Map ) { EFI_STATUS Status; @@ -3199,7 +3206,7 @@ UhciMapUserRequest ( ); if (!EFI_ERROR (Status)) { - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; } return Status; @@ -3237,61 +3244,60 @@ UhciMapUserData ( Status = EFI_SUCCESS; switch (Direction) { - case EfiUsbDataIn: - // - // BusMasterWrite means cpu read - // - *PktId = INPUT_PACKET_ID; - Status = IoMmuMap ( - Uhc->IoMmu, - EdkiiIoMmuOperationBusMasterWrite, - Data, - Len, - &PhyAddr, - Map - ); - - if (EFI_ERROR (Status)) { - goto EXIT; - } + case EfiUsbDataIn: + // + // BusMasterWrite means cpu read + // + *PktId = INPUT_PACKET_ID; + Status = IoMmuMap ( + Uhc->IoMmu, + EdkiiIoMmuOperationBusMasterWrite, + Data, + Len, + &PhyAddr, + Map + ); + + if (EFI_ERROR (Status)) { + goto EXIT; + } - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; - break; - - case EfiUsbDataOut: - *PktId = OUTPUT_PACKET_ID; - Status = IoMmuMap ( - Uhc->IoMmu, - EdkiiIoMmuOperationBusMasterRead, - Data, - Len, - &PhyAddr, - Map - ); + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; + break; - if (EFI_ERROR (Status)) { - goto EXIT; - } + case EfiUsbDataOut: + *PktId = OUTPUT_PACKET_ID; + Status = IoMmuMap ( + Uhc->IoMmu, + EdkiiIoMmuOperationBusMasterRead, + Data, + Len, + &PhyAddr, + Map + ); + + if (EFI_ERROR (Status)) { + goto EXIT; + } - *MappedAddr = (UINT8 *) (UINTN) PhyAddr; - break; + *MappedAddr = (UINT8 *)(UINTN)PhyAddr; + break; - case EfiUsbNoData: - if ((Len != NULL) && (*Len != 0)) { - Status = EFI_INVALID_PARAMETER; - goto EXIT; - } + case EfiUsbNoData: + if ((Len != NULL) && (*Len != 0)) { + Status = EFI_INVALID_PARAMETER; + goto EXIT; + } - *PktId = OUTPUT_PACKET_ID; - *MappedAddr = NULL; - *Map = NULL; - break; + *PktId = OUTPUT_PACKET_ID; + *MappedAddr = NULL; + *Map = NULL; + break; - default: - Status = EFI_INVALID_PARAMETER; + default: + Status = EFI_INVALID_PARAMETER; } EXIT: return Status; } - diff --git a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.h b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.h index 9100cbeabd..5b135f2558 100644 --- a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.h +++ b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _RECOVERY_UHC_H_ #define _RECOVERY_UHC_H_ - #include #include @@ -26,39 +25,39 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define USB_SLOW_SPEED_DEVICE 0x01 -#define USB_FULL_SPEED_DEVICE 0x02 +#define USB_SLOW_SPEED_DEVICE 0x01 +#define USB_FULL_SPEED_DEVICE 0x02 // // One memory block uses 16 page // -#define NORMAL_MEMORY_BLOCK_UNIT_IN_PAGES 16 - -#define USBCMD 0 /* Command Register Offset 00-01h */ -#define USBCMD_RS BIT0 /* Run/Stop */ -#define USBCMD_HCRESET BIT1 /* Host reset */ -#define USBCMD_GRESET BIT2 /* Global reset */ -#define USBCMD_EGSM BIT3 /* Global Suspend Mode */ -#define USBCMD_FGR BIT4 /* Force Global Resume */ -#define USBCMD_SWDBG BIT5 /* SW Debug mode */ -#define USBCMD_CF BIT6 /* Config Flag (sw only) */ -#define USBCMD_MAXP BIT7 /* Max Packet (0 = 32, 1 = 64) */ +#define NORMAL_MEMORY_BLOCK_UNIT_IN_PAGES 16 + +#define USBCMD 0 /* Command Register Offset 00-01h */ +#define USBCMD_RS BIT0 /* Run/Stop */ +#define USBCMD_HCRESET BIT1 /* Host reset */ +#define USBCMD_GRESET BIT2 /* Global reset */ +#define USBCMD_EGSM BIT3 /* Global Suspend Mode */ +#define USBCMD_FGR BIT4 /* Force Global Resume */ +#define USBCMD_SWDBG BIT5 /* SW Debug mode */ +#define USBCMD_CF BIT6 /* Config Flag (sw only) */ +#define USBCMD_MAXP BIT7 /* Max Packet (0 = 32, 1 = 64) */ /* Status register */ -#define USBSTS 2 /* Status Register Offset 02-03h */ -#define USBSTS_USBINT BIT0 /* Interrupt due to IOC */ -#define USBSTS_ERROR BIT1 /* Interrupt due to error */ -#define USBSTS_RD BIT2 /* Resume Detect */ -#define USBSTS_HSE BIT3 /* Host System Error - basically PCI problems */ -#define USBSTS_HCPE BIT4 /* Host Controller Process Error - the scripts were buggy */ -#define USBSTS_HCH BIT5 /* HC Halted */ +#define USBSTS 2 /* Status Register Offset 02-03h */ +#define USBSTS_USBINT BIT0 /* Interrupt due to IOC */ +#define USBSTS_ERROR BIT1 /* Interrupt due to error */ +#define USBSTS_RD BIT2 /* Resume Detect */ +#define USBSTS_HSE BIT3 /* Host System Error - basically PCI problems */ +#define USBSTS_HCPE BIT4 /* Host Controller Process Error - the scripts were buggy */ +#define USBSTS_HCH BIT5 /* HC Halted */ /* Interrupt enable register */ -#define USBINTR 4 /* Interrupt Enable Register 04-05h */ -#define USBINTR_TIMEOUT BIT0 /* Timeout/CRC error enable */ -#define USBINTR_RESUME BIT1 /* Resume interrupt enable */ -#define USBINTR_IOC BIT2 /* Interrupt On Complete enable */ -#define USBINTR_SP BIT3 /* Short packet interrupt enable */ +#define USBINTR 4 /* Interrupt Enable Register 04-05h */ +#define USBINTR_TIMEOUT BIT0 /* Timeout/CRC error enable */ +#define USBINTR_RESUME BIT1 /* Resume interrupt enable */ +#define USBINTR_IOC BIT2 /* Interrupt On Complete enable */ +#define USBINTR_SP BIT3 /* Short packet interrupt enable */ /* Frame Number Register Offset 06-08h */ #define USBFRNUM 6 @@ -70,90 +69,89 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USBSOF 0x0c /* USB port status and control registers */ -#define USBPORTSC1 0x10 /*Port 1 offset 10-11h */ -#define USBPORTSC2 0x12 /*Port 2 offset 12-13h */ - -#define USBPORTSC_CCS BIT0 /* Current Connect Status ("device present") */ -#define USBPORTSC_CSC BIT1 /* Connect Status Change */ -#define USBPORTSC_PED BIT2 /* Port Enable / Disable */ -#define USBPORTSC_PEDC BIT3 /* Port Enable / Disable Change */ -#define USBPORTSC_LSL BIT4 /* Line Status Low bit*/ -#define USBPORTSC_LSH BIT5 /* Line Status High bit*/ -#define USBPORTSC_RD BIT6 /* Resume Detect */ -#define USBPORTSC_LSDA BIT8 /* Low Speed Device Attached */ -#define USBPORTSC_PR BIT9 /* Port Reset */ -#define USBPORTSC_SUSP BIT12 /* Suspend */ - -#define SETUP_PACKET_ID 0x2D -#define INPUT_PACKET_ID 0x69 -#define OUTPUT_PACKET_ID 0xE1 -#define ERROR_PACKET_ID 0x55 +#define USBPORTSC1 0x10 /*Port 1 offset 10-11h */ +#define USBPORTSC2 0x12 /*Port 2 offset 12-13h */ + +#define USBPORTSC_CCS BIT0 /* Current Connect Status ("device present") */ +#define USBPORTSC_CSC BIT1 /* Connect Status Change */ +#define USBPORTSC_PED BIT2 /* Port Enable / Disable */ +#define USBPORTSC_PEDC BIT3 /* Port Enable / Disable Change */ +#define USBPORTSC_LSL BIT4 /* Line Status Low bit*/ +#define USBPORTSC_LSH BIT5 /* Line Status High bit*/ +#define USBPORTSC_RD BIT6 /* Resume Detect */ +#define USBPORTSC_LSDA BIT8 /* Low Speed Device Attached */ +#define USBPORTSC_PR BIT9 /* Port Reset */ +#define USBPORTSC_SUSP BIT12 /* Suspend */ + +#define SETUP_PACKET_ID 0x2D +#define INPUT_PACKET_ID 0x69 +#define OUTPUT_PACKET_ID 0xE1 +#define ERROR_PACKET_ID 0x55 #define STALL_1_MICRO_SECOND 1 #define STALL_1_MILLI_SECOND 1000 - #pragma pack(1) typedef struct { - UINT32 FrameListPtrTerminate : 1; - UINT32 FrameListPtrQSelect : 1; - UINT32 FrameListRsvd : 2; - UINT32 FrameListPtr : 28; + UINT32 FrameListPtrTerminate : 1; + UINT32 FrameListPtrQSelect : 1; + UINT32 FrameListRsvd : 2; + UINT32 FrameListPtr : 28; } FRAMELIST_ENTRY; typedef struct { - UINT32 QHHorizontalTerminate : 1; - UINT32 QHHorizontalQSelect : 1; - UINT32 QHHorizontalRsvd : 2; - UINT32 QHHorizontalPtr : 28; - UINT32 QHVerticalTerminate : 1; - UINT32 QHVerticalQSelect : 1; - UINT32 QHVerticalRsvd : 2; - UINT32 QHVerticalPtr : 28; + UINT32 QHHorizontalTerminate : 1; + UINT32 QHHorizontalQSelect : 1; + UINT32 QHHorizontalRsvd : 2; + UINT32 QHHorizontalPtr : 28; + UINT32 QHVerticalTerminate : 1; + UINT32 QHVerticalQSelect : 1; + UINT32 QHVerticalRsvd : 2; + UINT32 QHVerticalPtr : 28; } QUEUE_HEAD; typedef struct { - QUEUE_HEAD QueueHead; - UINT32 Reserved1; - UINT32 Reserved2; - VOID *PtrNext; - VOID *PtrDown; - VOID *Reserved3; - UINT32 Reserved4; + QUEUE_HEAD QueueHead; + UINT32 Reserved1; + UINT32 Reserved2; + VOID *PtrNext; + VOID *PtrDown; + VOID *Reserved3; + UINT32 Reserved4; } QH_STRUCT; typedef struct { - UINT32 TDLinkPtrTerminate : 1; - UINT32 TDLinkPtrQSelect : 1; - UINT32 TDLinkPtrDepthSelect : 1; - UINT32 TDLinkPtrRsvd : 1; - UINT32 TDLinkPtr : 28; - UINT32 TDStatusActualLength : 11; - UINT32 TDStatusRsvd : 5; - UINT32 TDStatus : 8; - UINT32 TDStatusIOC : 1; - UINT32 TDStatusIOS : 1; - UINT32 TDStatusLS : 1; - UINT32 TDStatusErr : 2; - UINT32 TDStatusSPD : 1; - UINT32 TDStatusRsvd2 : 2; - UINT32 TDTokenPID : 8; - UINT32 TDTokenDevAddr : 7; - UINT32 TDTokenEndPt : 4; - UINT32 TDTokenDataToggle : 1; - UINT32 TDTokenRsvd : 1; - UINT32 TDTokenMaxLen : 11; - UINT32 TDBufferPtr; + UINT32 TDLinkPtrTerminate : 1; + UINT32 TDLinkPtrQSelect : 1; + UINT32 TDLinkPtrDepthSelect : 1; + UINT32 TDLinkPtrRsvd : 1; + UINT32 TDLinkPtr : 28; + UINT32 TDStatusActualLength : 11; + UINT32 TDStatusRsvd : 5; + UINT32 TDStatus : 8; + UINT32 TDStatusIOC : 1; + UINT32 TDStatusIOS : 1; + UINT32 TDStatusLS : 1; + UINT32 TDStatusErr : 2; + UINT32 TDStatusSPD : 1; + UINT32 TDStatusRsvd2 : 2; + UINT32 TDTokenPID : 8; + UINT32 TDTokenDevAddr : 7; + UINT32 TDTokenEndPt : 4; + UINT32 TDTokenDataToggle : 1; + UINT32 TDTokenRsvd : 1; + UINT32 TDTokenMaxLen : 11; + UINT32 TDBufferPtr; } TD; typedef struct { - TD TDData; - UINT8 *PtrTDBuffer; - VOID *PtrNextTD; - VOID *PtrNextQH; - UINT16 TDBufferLength; - UINT16 Reserved; + TD TDData; + UINT8 *PtrTDBuffer; + VOID *PtrNextTD; + VOID *PtrNextQH; + UINT16 TDBufferLength; + UINT16 Reserved; } TD_STRUCT; #pragma pack() @@ -161,38 +159,37 @@ typedef struct { typedef struct _MEMORY_MANAGE_HEADER MEMORY_MANAGE_HEADER; struct _MEMORY_MANAGE_HEADER { - UINT8 *BitArrayPtr; - UINTN BitArraySizeInBytes; - UINT8 *MemoryBlockPtr; - UINTN MemoryBlockSizeInBytes; - MEMORY_MANAGE_HEADER *Next; + UINT8 *BitArrayPtr; + UINTN BitArraySizeInBytes; + UINT8 *MemoryBlockPtr; + UINTN MemoryBlockSizeInBytes; + MEMORY_MANAGE_HEADER *Next; }; -#define USB_UHC_DEV_SIGNATURE SIGNATURE_32 ('p', 'u', 'h', 'c') +#define USB_UHC_DEV_SIGNATURE SIGNATURE_32 ('p', 'u', 'h', 'c') typedef struct { - UINTN Signature; - PEI_USB_HOST_CONTROLLER_PPI UsbHostControllerPpi; - EDKII_IOMMU_PPI *IoMmu; - EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; + UINTN Signature; + PEI_USB_HOST_CONTROLLER_PPI UsbHostControllerPpi; + EDKII_IOMMU_PPI *IoMmu; + EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; // // EndOfPei callback is used to stop the UHC DMA operation // after exit PEI phase. // - EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; + EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; - UINT32 UsbHostControllerBaseAddress; - FRAMELIST_ENTRY *FrameListEntry; - QH_STRUCT *ConfigQH; - QH_STRUCT *BulkQH; + UINT32 UsbHostControllerBaseAddress; + FRAMELIST_ENTRY *FrameListEntry; + QH_STRUCT *ConfigQH; + QH_STRUCT *BulkQH; // // Header1 used for QH,TD memory blocks management // - MEMORY_MANAGE_HEADER *Header1; - + MEMORY_MANAGE_HEADER *Header1; } USB_UHC_DEV; -#define PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS(a) CR (a, USB_UHC_DEV, UsbHostControllerPpi, USB_UHC_DEV_SIGNATURE) -#define PEI_RECOVERY_USB_UHC_DEV_FROM_THIS_NOTIFY(a) CR (a, USB_UHC_DEV, EndOfPeiNotifyList, USB_UHC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_UHC_DEV_FROM_UHCI_THIS(a) CR (a, USB_UHC_DEV, UsbHostControllerPpi, USB_UHC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_UHC_DEV_FROM_THIS_NOTIFY(a) CR (a, USB_UHC_DEV, EndOfPeiNotifyList, USB_UHC_DEV_SIGNATURE) /** Submits control transfer to a target USB device. @@ -220,17 +217,17 @@ typedef struct { EFI_STATUS EFIAPI UhcControlTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI * This, - IN UINT8 DeviceAddress, - IN UINT8 DeviceSpeed, - IN UINT8 MaximumPacketLength, - IN EFI_USB_DEVICE_REQUEST * Request, - IN EFI_USB_DATA_DIRECTION TransferDirection, - IN OUT VOID *Data OPTIONAL, - IN OUT UINTN *DataLength OPTIONAL, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 DeviceSpeed, + IN UINT8 MaximumPacketLength, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION TransferDirection, + IN OUT VOID *Data OPTIONAL, + IN OUT UINTN *DataLength OPTIONAL, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ); /** @@ -263,16 +260,16 @@ UhcControlTransfer ( EFI_STATUS EFIAPI UhcBulkTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 MaximumPacketLength, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN OUT UINT8 *DataToggle, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 MaximumPacketLength, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN OUT UINT8 *DataToggle, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ); /** @@ -290,9 +287,9 @@ UhcBulkTransfer ( EFI_STATUS EFIAPI UhcGetRootHubPortNumber ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - OUT UINT8 *PortNumber + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + OUT UINT8 *PortNumber ); /** @@ -311,10 +308,10 @@ UhcGetRootHubPortNumber ( EFI_STATUS EFIAPI UhcGetRootHubPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - OUT EFI_USB_PORT_STATUS *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + OUT EFI_USB_PORT_STATUS *PortStatus ); /** @@ -333,10 +330,10 @@ UhcGetRootHubPortStatus ( EFI_STATUS EFIAPI UhcSetRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ); /** @@ -357,10 +354,10 @@ UhcSetRootHubPortFeature ( EFI_STATUS EFIAPI UhcClearRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ); /** @@ -374,7 +371,7 @@ UhcClearRootHubPortFeature ( **/ EFI_STATUS InitializeUsbHC ( - IN USB_UHC_DEV *UhcDev + IN USB_UHC_DEV *UhcDev ); /** @@ -388,7 +385,7 @@ InitializeUsbHC ( **/ EFI_STATUS CreateFrameList ( - USB_UHC_DEV *UhcDev + USB_UHC_DEV *UhcDev ); /** @@ -402,8 +399,8 @@ CreateFrameList ( **/ UINT16 USBReadPortW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port ); /** @@ -416,9 +413,9 @@ USBReadPortW ( **/ VOID USBWritePortW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port, - IN UINT16 Data + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port, + IN UINT16 Data ); /** @@ -431,9 +428,9 @@ USBWritePortW ( **/ VOID USBWritePortDW ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Port, - IN UINT32 Data + IN USB_UHC_DEV *UhcDev, + IN UINT32 Port, + IN UINT32 Data ); /** @@ -445,8 +442,8 @@ USBWritePortDW ( **/ VOID ClearStatusReg ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 StatusAddr + IN USB_UHC_DEV *UhcDev, + IN UINT32 StatusAddr ); /** @@ -461,8 +458,8 @@ ClearStatusReg ( **/ BOOLEAN IsStatusOK ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 StatusRegAddr + IN USB_UHC_DEV *UhcDev, + IN UINT32 StatusRegAddr ); /** @@ -475,9 +472,9 @@ IsStatusOK ( **/ VOID SetFrameListBaseAddress ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 FrameListRegAddr, - IN UINT32 Addr + IN USB_UHC_DEV *UhcDev, + IN UINT32 FrameListRegAddr, + IN UINT32 Addr ); /** @@ -574,7 +571,6 @@ SetQHVerticalValidorInvalid ( IN BOOLEAN IsValid ); - /** Allocate TD or QH Struct. @@ -588,9 +584,9 @@ SetQHVerticalValidorInvalid ( **/ EFI_STATUS AllocateTDorQHStruct ( - IN USB_UHC_DEV *UhcDev, - IN UINT32 Size, - OUT VOID **PtrStruct + IN USB_UHC_DEV *UhcDev, + IN UINT32 Size, + OUT VOID **PtrStruct ); /** @@ -605,8 +601,8 @@ AllocateTDorQHStruct ( **/ EFI_STATUS CreateTD ( - IN USB_UHC_DEV *UhcDev, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + OUT TD_STRUCT **PtrTD ); /** @@ -627,14 +623,14 @@ CreateTD ( **/ EFI_STATUS GenSetupStageTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 DeviceSpeed, - IN UINT8 *DevRequest, - IN UINT8 *RequestPhy, - IN UINT8 RequestLen, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 DeviceSpeed, + IN UINT8 *DevRequest, + IN UINT8 *RequestPhy, + IN UINT8 RequestLen, + OUT TD_STRUCT **PtrTD ); /** @@ -657,16 +653,16 @@ GenSetupStageTD ( **/ EFI_STATUS GenDataTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 *PtrData, - IN UINT8 *DataPhy, - IN UINT8 Len, - IN UINT8 PktID, - IN UINT8 Toggle, - IN UINT8 DeviceSpeed, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 *PtrData, + IN UINT8 *DataPhy, + IN UINT8 Len, + IN UINT8 PktID, + IN UINT8 Toggle, + IN UINT8 DeviceSpeed, + OUT TD_STRUCT **PtrTD ); /** @@ -685,12 +681,12 @@ GenDataTD ( **/ EFI_STATUS CreateStatusTD ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 DevAddr, - IN UINT8 Endpoint, - IN UINT8 PktID, - IN UINT8 DeviceSpeed, - OUT TD_STRUCT **PtrTD + IN USB_UHC_DEV *UhcDev, + IN UINT8 DevAddr, + IN UINT8 Endpoint, + IN UINT8 PktID, + IN UINT8 DeviceSpeed, + OUT TD_STRUCT **PtrTD ); /** @@ -702,8 +698,8 @@ CreateStatusTD ( **/ VOID SetTDLinkPtrValidorInvalid ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsValid + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsValid ); /** @@ -715,8 +711,8 @@ SetTDLinkPtrValidorInvalid ( **/ VOID SetTDLinkPtrQHorTDSelect ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsQH + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsQH ); /** @@ -728,8 +724,8 @@ SetTDLinkPtrQHorTDSelect ( **/ VOID SetTDLinkPtrDepthorBreadth ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsDepth + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsDepth ); /** @@ -741,8 +737,8 @@ SetTDLinkPtrDepthorBreadth ( **/ VOID SetTDLinkPtr ( - IN TD_STRUCT *PtrTDStruct, - IN VOID *PtrNext + IN TD_STRUCT *PtrTDStruct, + IN VOID *PtrNext ); /** @@ -753,12 +749,11 @@ SetTDLinkPtr ( @retval Get TD Link Pointer in TD. **/ -VOID* +VOID * GetTDLinkPtr ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); - /** Enable/Disable short packet detection mechanism. @@ -768,8 +763,8 @@ GetTDLinkPtr ( **/ VOID EnableorDisableTDShortPacket ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsEnable + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsEnable ); /** @@ -781,8 +776,8 @@ EnableorDisableTDShortPacket ( **/ VOID SetTDControlErrorCounter ( - IN TD_STRUCT *PtrTDStruct, - IN UINT8 MaxErrors + IN TD_STRUCT *PtrTDStruct, + IN UINT8 MaxErrors ); /** @@ -794,8 +789,8 @@ SetTDControlErrorCounter ( **/ VOID SetTDLoworFullSpeedDevice ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsLowSpeedDevice + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsLowSpeedDevice ); /** @@ -807,8 +802,8 @@ SetTDLoworFullSpeedDevice ( **/ VOID SetTDControlIsochronousorNot ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsIsochronous + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsIsochronous ); /** @@ -821,8 +816,8 @@ SetTDControlIsochronousorNot ( **/ VOID SetorClearTDControlIOC ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsSet + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsSet ); /** @@ -834,8 +829,8 @@ SetorClearTDControlIOC ( **/ VOID SetTDStatusActiveorInactive ( - IN TD_STRUCT *PtrTDStruct, - IN BOOLEAN IsActive + IN TD_STRUCT *PtrTDStruct, + IN BOOLEAN IsActive ); /** @@ -848,8 +843,8 @@ SetTDStatusActiveorInactive ( **/ UINT16 SetTDTokenMaxLength ( - IN TD_STRUCT *PtrTDStruct, - IN UINT16 MaxLen + IN TD_STRUCT *PtrTDStruct, + IN UINT16 MaxLen ); /** @@ -860,7 +855,7 @@ SetTDTokenMaxLength ( **/ VOID SetTDTokenDataToggle1 ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -871,7 +866,7 @@ SetTDTokenDataToggle1 ( **/ VOID SetTDTokenDataToggle0 ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -883,8 +878,8 @@ SetTDTokenDataToggle0 ( **/ VOID SetTDTokenEndPoint ( - IN TD_STRUCT *PtrTDStruct, - IN UINTN EndPoint + IN TD_STRUCT *PtrTDStruct, + IN UINTN EndPoint ); /** @@ -896,8 +891,8 @@ SetTDTokenEndPoint ( **/ VOID SetTDTokenDeviceAddress ( - IN TD_STRUCT *PtrTDStruct, - IN UINTN DevAddr + IN TD_STRUCT *PtrTDStruct, + IN UINTN DevAddr ); /** @@ -909,8 +904,8 @@ SetTDTokenDeviceAddress ( **/ VOID SetTDTokenPacketID ( - IN TD_STRUCT *PtrTDStruct, - IN UINT8 PacketID + IN TD_STRUCT *PtrTDStruct, + IN UINT8 PacketID ); /** @@ -922,7 +917,7 @@ SetTDTokenPacketID ( **/ VOID SetTDDataBuffer ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -935,7 +930,7 @@ SetTDDataBuffer ( **/ BOOLEAN IsTDStatusActive ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -948,7 +943,7 @@ IsTDStatusActive ( **/ BOOLEAN IsTDStatusStalled ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -961,7 +956,7 @@ IsTDStatusStalled ( **/ BOOLEAN IsTDStatusBufferError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -974,7 +969,7 @@ IsTDStatusBufferError ( **/ BOOLEAN IsTDStatusBabbleError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -987,7 +982,7 @@ IsTDStatusBabbleError ( **/ BOOLEAN IsTDStatusNAKReceived ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -1000,7 +995,7 @@ IsTDStatusNAKReceived ( **/ BOOLEAN IsTDStatusCRCTimeOutError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -1013,7 +1008,7 @@ IsTDStatusCRCTimeOutError ( **/ BOOLEAN IsTDStatusBitStuffError ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -1026,7 +1021,7 @@ IsTDStatusBitStuffError ( **/ UINT16 GetTDStatusActualLength ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -1039,7 +1034,7 @@ GetTDStatusActualLength ( **/ BOOLEAN GetTDLinkPtrValidorInvalid ( - IN TD_STRUCT *PtrTDStruct + IN TD_STRUCT *PtrTDStruct ); /** @@ -1052,7 +1047,7 @@ GetTDLinkPtrValidorInvalid ( **/ UINTN CountTDsNumber ( - IN TD_STRUCT *PtrFirstTD + IN TD_STRUCT *PtrFirstTD ); /** @@ -1064,8 +1059,8 @@ CountTDsNumber ( **/ VOID LinkTDToQH ( - IN QH_STRUCT *PtrQH, - IN TD_STRUCT *PtrTD + IN QH_STRUCT *PtrQH, + IN TD_STRUCT *PtrTD ); /** @@ -1077,8 +1072,8 @@ LinkTDToQH ( **/ VOID LinkTDToTD ( - IN TD_STRUCT *PtrPreTD, - IN TD_STRUCT *PtrTD + IN TD_STRUCT *PtrPreTD, + IN TD_STRUCT *PtrTD ); /** @@ -1097,11 +1092,11 @@ LinkTDToTD ( **/ EFI_STATUS ExecuteControlTransfer ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrTD, - OUT UINTN *ActualLen, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrTD, + OUT UINTN *ActualLen, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ); /** @@ -1121,12 +1116,12 @@ ExecuteControlTransfer ( **/ EFI_STATUS ExecBulkTransfer ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrTD, - IN OUT UINTN *ActualLen, - IN UINT8 *DataToggle, - IN UINTN TimeOut, - OUT UINT32 *TransferResult + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrTD, + IN OUT UINTN *ActualLen, + IN UINT8 *DataToggle, + IN UINTN TimeOut, + OUT UINT32 *TransferResult ); /** @@ -1138,8 +1133,8 @@ ExecBulkTransfer ( **/ VOID DeleteQueuedTDs ( - IN USB_UHC_DEV *UhcDev, - IN TD_STRUCT *PtrFirstTD + IN USB_UHC_DEV *UhcDev, + IN TD_STRUCT *PtrFirstTD ); /** @@ -1155,10 +1150,10 @@ DeleteQueuedTDs ( **/ BOOLEAN CheckTDsResults ( - IN TD_STRUCT *PtrTD, - OUT UINT32 *Result, - OUT UINTN *ErrTDPos, - OUT UINTN *ActualTransferSize + IN TD_STRUCT *PtrTD, + OUT UINT32 *Result, + OUT UINTN *ErrTDPos, + OUT UINTN *ActualTransferSize ); /** @@ -1190,7 +1185,7 @@ CreateMemoryBlock ( **/ EFI_STATUS InitializeMemoryManagement ( - IN USB_UHC_DEV *UhcDev + IN USB_UHC_DEV *UhcDev ); /** @@ -1206,9 +1201,9 @@ InitializeMemoryManagement ( **/ EFI_STATUS UhcAllocatePool ( - IN USB_UHC_DEV *UhcDev, - OUT UINT8 **Pool, - IN UINTN AllocSize + IN USB_UHC_DEV *UhcDev, + OUT UINT8 **Pool, + IN UINTN AllocSize ); /** @@ -1239,9 +1234,9 @@ AllocMemInMemoryBlock ( **/ VOID UhcFreePool ( - IN USB_UHC_DEV *UhcDev, - IN UINT8 *Pool, - IN UINTN AllocSize + IN USB_UHC_DEV *UhcDev, + IN UINT8 *Pool, + IN UINTN AllocSize ); /** @@ -1257,7 +1252,6 @@ InsertMemoryHeaderToList ( IN MEMORY_MANAGE_HEADER *NewMemoryHeader ); - /** Map address of request structure buffer. @@ -1272,10 +1266,10 @@ InsertMemoryHeaderToList ( **/ EFI_STATUS UhciMapUserRequest ( - IN USB_UHC_DEV *Uhc, - IN OUT VOID *Request, - OUT UINT8 **MappedAddr, - OUT VOID **Map + IN USB_UHC_DEV *Uhc, + IN OUT VOID *Request, + OUT UINT8 **MappedAddr, + OUT VOID **Map ); /** @@ -1343,8 +1337,8 @@ IoMmuMap ( **/ VOID IoMmuUnmap ( - IN EDKII_IOMMU_PPI *IoMmu, - IN VOID *Mapping + IN EDKII_IOMMU_PPI *IoMmu, + IN VOID *Mapping ); /** @@ -1375,7 +1369,6 @@ IoMmuAllocateBuffer ( OUT VOID **Mapping ); - /** Initialize IOMMU. @@ -1384,7 +1377,7 @@ IoMmuAllocateBuffer ( **/ VOID IoMmuInit ( - OUT EDKII_IOMMU_PPI **IoMmu + OUT EDKII_IOMMU_PPI **IoMmu ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.c b/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.c index 9e2697b822..e3af49c8c9 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.c @@ -21,15 +21,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gXhciComponentName = // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gXhciComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) XhciComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) XhciComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gXhciComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)XhciComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)XhciComponentNameGetControllerName, "en" }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mXhciDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mXhciDriverNameTable[] = { { "eng;en", L"Usb Xhci Driver" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -166,9 +166,9 @@ XhciComponentNameGetControllerName ( OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - EFI_USB2_HC_PROTOCOL *Usb2Hc; - USB_XHCI_INSTANCE *XhciDev; + EFI_STATUS Status; + EFI_USB2_HC_PROTOCOL *Usb2Hc; + USB_XHCI_INSTANCE *XhciDev; // // This is a device driver, so ChildHandle must be NULL. @@ -195,7 +195,7 @@ XhciComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, gXhciDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -213,5 +213,4 @@ XhciComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gXhciComponentName) ); - } diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.h b/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.h index 13fbde1658..103ad60575 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/ComponentName.h @@ -57,7 +57,6 @@ XhciComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -137,4 +136,3 @@ XhciComponentNameGetControllerName ( ); #endif - diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c index 005820e011..99fb3521d5 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c @@ -7,10 +7,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "Xhci.h" - /** Allocate a block of memory to be used by the buffer pool. @@ -22,17 +20,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USBHC_MEM_BLOCK * UsbHcAllocMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Pages + IN USBHC_MEM_POOL *Pool, + IN UINTN Pages ) { - USBHC_MEM_BLOCK *Block; - EFI_PCI_IO_PROTOCOL *PciIo; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - UINTN Bytes; - EFI_STATUS Status; + USBHC_MEM_BLOCK *Block; + EFI_PCI_IO_PROTOCOL *PciIo; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + UINTN Bytes; + EFI_STATUS Status; PciIo = Pool->PciIo; @@ -47,9 +45,9 @@ UsbHcAllocMemBlock ( // ASSERT (USBHC_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); - Block->Bits = AllocateZeroPool (Block->BitsLen); + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); + Block->Bits = AllocateZeroPool (Block->BitsLen); if (Block->Bits == NULL) { gBS->FreePool (Block); @@ -73,7 +71,7 @@ UsbHcAllocMemBlock ( goto FREE_BITARRAY; } - Bytes = EFI_PAGES_TO_SIZE (Pages); + Bytes = EFI_PAGES_TO_SIZE (Pages); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, @@ -87,9 +85,9 @@ UsbHcAllocMemBlock ( goto FREE_BUFFER; } - Block->BufHost = BufHost; - Block->Buf = (UINT8 *) ((UINTN) MappedAddr); - Block->Mapping = Mapping; + Block->BufHost = BufHost; + Block->Buf = (UINT8 *)((UINTN)MappedAddr); + Block->Mapping = Mapping; return Block; @@ -102,7 +100,6 @@ FREE_BITARRAY: return NULL; } - /** Free the memory block from the memory pool. @@ -112,11 +109,11 @@ FREE_BITARRAY: **/ VOID UsbHcFreeMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_POOL *Pool, + IN USBHC_MEM_BLOCK *Block ) { - EFI_PCI_IO_PROTOCOL *PciIo; + EFI_PCI_IO_PROTOCOL *PciIo; ASSERT ((Pool != NULL) && (Block != NULL)); @@ -132,7 +129,6 @@ UsbHcFreeMemBlock ( gBS->FreePool (Block); } - /** Alloc some memory from the block. @@ -145,22 +141,22 @@ UsbHcFreeMemBlock ( **/ VOID * UsbHcAllocMemFromBlock ( - IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN USBHC_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -176,13 +172,12 @@ UsbHcAllocMemFromBlock ( } NEXT_BIT (Byte, Bit); - } else { NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -193,13 +188,13 @@ UsbHcAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -218,16 +213,16 @@ UsbHcAllocMemFromBlock ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddrForHostAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINTN AllocSize; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINTN Offset; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINTN AllocSize; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINTN Offset; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); @@ -241,7 +236,7 @@ UsbHcGetPciAddrForHostAddr ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->BufHost <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { + if ((Block->BufHost <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { break; } } @@ -250,8 +245,8 @@ UsbHcGetPciAddrForHostAddr ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *)Mem - Block->BufHost; - PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN) (Block->Buf + Offset); + Offset = (UINT8 *)Mem - Block->BufHost; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->Buf + Offset); return PhyAddr; } @@ -267,16 +262,16 @@ UsbHcGetPciAddrForHostAddr ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetHostAddrForPciAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINTN AllocSize; - EFI_PHYSICAL_ADDRESS HostAddr; - UINTN Offset; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINTN AllocSize; + EFI_PHYSICAL_ADDRESS HostAddr; + UINTN Offset; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); @@ -290,7 +285,7 @@ UsbHcGetHostAddrForPciAddr ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->Buf <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->Buf + Block->BufLen))) { + if ((Block->Buf <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->Buf + Block->BufLen))) { break; } } @@ -299,8 +294,8 @@ UsbHcGetHostAddrForPciAddr ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *)Mem - Block->Buf; - HostAddr = (EFI_PHYSICAL_ADDRESS)(UINTN) (Block->BufHost + Offset); + Offset = (UINT8 *)Mem - Block->Buf; + HostAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->BufHost + Offset); return HostAddr; } @@ -313,8 +308,8 @@ UsbHcGetHostAddrForPciAddr ( **/ VOID UsbHcInsertMemBlockToPool ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -322,7 +317,6 @@ UsbHcInsertMemBlockToPool ( Head->Next = Block; } - /** Is the memory block empty? @@ -334,10 +328,10 @@ UsbHcInsertMemBlockToPool ( **/ BOOLEAN UsbHcIsMemBlockEmpty ( - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Block ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -348,7 +342,6 @@ UsbHcIsMemBlockEmpty ( return TRUE; } - /** Unlink the memory block from the pool's list. @@ -358,11 +351,11 @@ UsbHcIsMemBlockEmpty ( **/ VOID UsbHcUnlinkMemBlock ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *BlockToUnlink + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *BlockToUnlink ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT ((Head != NULL) && (BlockToUnlink != NULL)); @@ -375,7 +368,6 @@ UsbHcUnlinkMemBlock ( } } - /** Initialize the memory management pool for the host controller. @@ -390,7 +382,7 @@ UsbHcInitMemPool ( IN EFI_PCI_IO_PROTOCOL *PciIo ) { - USBHC_MEM_POOL *Pool; + USBHC_MEM_POOL *Pool; Pool = AllocatePool (sizeof (USBHC_MEM_POOL)); @@ -398,8 +390,8 @@ UsbHcInitMemPool ( return Pool; } - Pool->PciIo = PciIo; - Pool->Head = UsbHcAllocMemBlock (Pool, USBHC_MEM_DEFAULT_PAGES); + Pool->PciIo = PciIo; + Pool->Head = UsbHcAllocMemBlock (Pool, USBHC_MEM_DEFAULT_PAGES); if (Pool->Head == NULL) { gBS->FreePool (Pool); @@ -409,7 +401,6 @@ UsbHcInitMemPool ( return Pool; } - /** Release the memory management pool. @@ -421,10 +412,10 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -443,7 +434,6 @@ UsbHcFreeMemPool ( return EFI_SUCCESS; } - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -456,16 +446,16 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - USBHC_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = USBHC_MEM_ROUND (Size); @@ -520,7 +510,6 @@ UsbHcAllocateMem ( return Mem; } - /** Free the allocated memory back to the memory pool. @@ -531,22 +520,22 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -557,8 +546,8 @@ UsbHcFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; - Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; + Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; + Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -566,7 +555,7 @@ UsbHcFreeMem ( for (Count = 0; Count < (AllocSize / USBHC_MEM_UNIT); Count++) { ASSERT (USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -589,7 +578,7 @@ UsbHcFreeMem ( UsbHcFreeMemBlock (Pool, Block); } - return ; + return; } /** @@ -621,13 +610,13 @@ UsbHcAllocateAlignedPages ( OUT VOID **Mapping ) { - EFI_STATUS Status; - VOID *Memory; - UINTN AlignedMemory; - UINTN AlignmentMask; - UINTN UnalignedPages; - UINTN RealPages; - UINTN Bytes; + EFI_STATUS Status; + VOID *Memory; + UINTN AlignedMemory; + UINTN AlignmentMask; + UINTN UnalignedPages; + UINTN RealPages; + UINTN Bytes; // // Alignment must be a power of two or zero. @@ -641,12 +630,13 @@ UsbHcAllocateAlignedPages ( if (Pages == 0) { return EFI_INVALID_PARAMETER; } + if (Alignment > EFI_PAGE_SIZE) { // // Calculate the total number of pages since alignment is larger than page size. // - AlignmentMask = Alignment - 1; - RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); + AlignmentMask = Alignment - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); // // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow. // @@ -663,8 +653,9 @@ UsbHcAllocateAlignedPages ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; - UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); + + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). @@ -672,6 +663,7 @@ UsbHcAllocateAlignedPages ( Status = PciIo->FreeBuffer (PciIo, UnalignedPages, Memory); ASSERT_EFI_ERROR (Status); } + Memory = (VOID *)(UINTN)(AlignedMemory + EFI_PAGES_TO_SIZE (Pages)); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -696,25 +688,26 @@ UsbHcAllocateAlignedPages ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - AlignedMemory = (UINTN) Memory; + + AlignedMemory = (UINTN)Memory; } - Bytes = EFI_PAGES_TO_SIZE (Pages); + Bytes = EFI_PAGES_TO_SIZE (Pages); Status = PciIo->Map ( PciIo, EfiPciIoOperationBusMasterCommonBuffer, - (VOID *) AlignedMemory, + (VOID *)AlignedMemory, &Bytes, DeviceAddress, Mapping ); if (EFI_ERROR (Status) || (Bytes != EFI_PAGES_TO_SIZE (Pages))) { - Status = PciIo->FreeBuffer (PciIo, Pages, (VOID *) AlignedMemory); + Status = PciIo->FreeBuffer (PciIo, Pages, (VOID *)AlignedMemory); return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *) AlignedMemory; + *HostAddress = (VOID *)AlignedMemory; return EFI_SUCCESS; } @@ -730,13 +723,13 @@ UsbHcAllocateAlignedPages ( **/ VOID UsbHcFreeAlignedPages ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN VOID *HostAddress, - IN UINTN Pages, - VOID *Mapping + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN VOID *HostAddress, + IN UINTN Pages, + VOID *Mapping ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Pages != 0); diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h index 319110da3a..48ae86141c 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h @@ -10,20 +10,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_XHCI_MEM_H_ #define _EFI_XHCI_MEM_H_ -#define USB_HC_BIT(a) ((UINTN)(1 << (a))) +#define USB_HC_BIT(a) ((UINTN)(1 << (a))) #define USB_HC_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & USB_HC_BIT(Bit)) == USB_HC_BIT(Bit))) typedef struct _USBHC_MEM_BLOCK USBHC_MEM_BLOCK; struct _USBHC_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - USBHC_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + USBHC_MEM_BLOCK *Next; }; // @@ -32,16 +32,16 @@ struct _USBHC_MEM_BLOCK { // data to be on the same 4G memory. // typedef struct _USBHC_MEM_POOL { - EFI_PCI_IO_PROTOCOL *PciIo; - BOOLEAN Check4G; - UINT32 Which4G; - USBHC_MEM_BLOCK *Head; + EFI_PCI_IO_PROTOCOL *PciIo; + BOOLEAN Check4G; + UINT32 Which4G; + USBHC_MEM_BLOCK *Head; } USBHC_MEM_POOL; // // Memory allocation unit, must be 2^n, n>4 // -#define USBHC_MEM_UNIT 64 +#define USBHC_MEM_UNIT 64 #define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) #define USBHC_MEM_DEFAULT_PAGES 16 @@ -60,8 +60,6 @@ typedef struct _USBHC_MEM_POOL { } \ } while (0) - - /** Initialize the memory management pool for the host controller. @@ -76,7 +74,6 @@ UsbHcInitMemPool ( IN EFI_PCI_IO_PROTOCOL *PciIo ); - /** Release the memory management pool. @@ -88,10 +85,9 @@ UsbHcInitMemPool ( **/ EFI_STATUS UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ); - /** Allocate some memory from the host controller's memory pool which can be used to communicate with host controller. @@ -104,11 +100,10 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ); - /** Free the allocated memory back to the memory pool. @@ -119,9 +114,9 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -136,9 +131,9 @@ UsbHcFreeMem ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddrForHostAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -153,9 +148,9 @@ UsbHcGetPciAddrForHostAddr ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetHostAddrForPciAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -198,10 +193,10 @@ UsbHcAllocateAlignedPages ( **/ VOID UsbHcFreeAlignedPages ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN VOID *HostAddress, - IN UINTN Pages, - VOID *Mapping + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN VOID *HostAddress, + IN UINTN Pages, + VOID *Mapping ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c index 5a1f907ff0..b79499e225 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c @@ -13,46 +13,46 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // to the UEFI protocol's port state (change). // USB_PORT_STATE_MAP mUsbPortStateMap[] = { - {XHC_PORTSC_CCS, USB_PORT_STAT_CONNECTION}, - {XHC_PORTSC_PED, USB_PORT_STAT_ENABLE}, - {XHC_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT}, - {XHC_PORTSC_RESET, USB_PORT_STAT_RESET} + { XHC_PORTSC_CCS, USB_PORT_STAT_CONNECTION }, + { XHC_PORTSC_PED, USB_PORT_STAT_ENABLE }, + { XHC_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT }, + { XHC_PORTSC_RESET, USB_PORT_STAT_RESET } }; USB_PORT_STATE_MAP mUsbPortChangeMap[] = { - {XHC_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION}, - {XHC_PORTSC_PEC, USB_PORT_STAT_C_ENABLE}, - {XHC_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT}, - {XHC_PORTSC_PRC, USB_PORT_STAT_C_RESET} + { XHC_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION }, + { XHC_PORTSC_PEC, USB_PORT_STAT_C_ENABLE }, + { XHC_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT }, + { XHC_PORTSC_PRC, USB_PORT_STAT_C_RESET } }; -USB_CLEAR_PORT_MAP mUsbClearPortChangeMap[] = { - {XHC_PORTSC_CSC, EfiUsbPortConnectChange}, - {XHC_PORTSC_PEC, EfiUsbPortEnableChange}, - {XHC_PORTSC_OCC, EfiUsbPortOverCurrentChange}, - {XHC_PORTSC_PRC, EfiUsbPortResetChange} +USB_CLEAR_PORT_MAP mUsbClearPortChangeMap[] = { + { XHC_PORTSC_CSC, EfiUsbPortConnectChange }, + { XHC_PORTSC_PEC, EfiUsbPortEnableChange }, + { XHC_PORTSC_OCC, EfiUsbPortOverCurrentChange }, + { XHC_PORTSC_PRC, EfiUsbPortResetChange } }; USB_PORT_STATE_MAP mUsbHubPortStateMap[] = { - {XHC_HUB_PORTSC_CCS, USB_PORT_STAT_CONNECTION}, - {XHC_HUB_PORTSC_PED, USB_PORT_STAT_ENABLE}, - {XHC_HUB_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT}, - {XHC_HUB_PORTSC_RESET, USB_PORT_STAT_RESET} + { XHC_HUB_PORTSC_CCS, USB_PORT_STAT_CONNECTION }, + { XHC_HUB_PORTSC_PED, USB_PORT_STAT_ENABLE }, + { XHC_HUB_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT }, + { XHC_HUB_PORTSC_RESET, USB_PORT_STAT_RESET } }; USB_PORT_STATE_MAP mUsbHubPortChangeMap[] = { - {XHC_HUB_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION}, - {XHC_HUB_PORTSC_PEC, USB_PORT_STAT_C_ENABLE}, - {XHC_HUB_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT}, - {XHC_HUB_PORTSC_PRC, USB_PORT_STAT_C_RESET} + { XHC_HUB_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION }, + { XHC_HUB_PORTSC_PEC, USB_PORT_STAT_C_ENABLE }, + { XHC_HUB_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT }, + { XHC_HUB_PORTSC_PRC, USB_PORT_STAT_C_RESET } }; -USB_CLEAR_PORT_MAP mUsbHubClearPortChangeMap[] = { - {XHC_HUB_PORTSC_CSC, EfiUsbPortConnectChange}, - {XHC_HUB_PORTSC_PEC, EfiUsbPortEnableChange}, - {XHC_HUB_PORTSC_OCC, EfiUsbPortOverCurrentChange}, - {XHC_HUB_PORTSC_PRC, EfiUsbPortResetChange}, - {XHC_HUB_PORTSC_BHRC, Usb3PortBHPortResetChange} +USB_CLEAR_PORT_MAP mUsbHubClearPortChangeMap[] = { + { XHC_HUB_PORTSC_CSC, EfiUsbPortConnectChange }, + { XHC_HUB_PORTSC_PEC, EfiUsbPortEnableChange }, + { XHC_HUB_PORTSC_OCC, EfiUsbPortOverCurrentChange }, + { XHC_HUB_PORTSC_PRC, EfiUsbPortResetChange }, + { XHC_HUB_PORTSC_BHRC, Usb3PortBHPortResetChange } }; EFI_DRIVER_BINDING_PROTOCOL gXhciDriverBinding = { @@ -67,7 +67,7 @@ EFI_DRIVER_BINDING_PROTOCOL gXhciDriverBinding = { // // Template for Xhci's Usb2 Host Controller Protocol Instance. // -EFI_USB2_HC_PROTOCOL gXhciUsb2HcTemplate = { +EFI_USB2_HC_PROTOCOL gXhciUsb2HcTemplate = { XhcGetCapability, XhcReset, XhcGetState, @@ -114,12 +114,12 @@ XhcGetCapability ( return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (XHC_TPL); + OldTpl = gBS->RaiseTPL (XHC_TPL); Xhc = XHC_FROM_THIS (This); *MaxSpeed = EFI_USB_SPEED_SUPER; - *PortNumber = (UINT8) (Xhc->HcSParams1.Data.MaxPorts); - *Is64BitCapable = (UINT8) Xhc->Support64BitDma; + *PortNumber = (UINT8)(Xhc->HcSParams1.Data.MaxPorts); + *Is64BitCapable = (UINT8)Xhc->Support64BitDma; DEBUG ((DEBUG_INFO, "XhcGetCapability: %d ports, 64 bit %d\n", *PortNumber, *Is64BitCapable)); gBS->RestoreTPL (OldTpl); @@ -127,7 +127,6 @@ XhcGetCapability ( return EFI_SUCCESS; } - /** Provides software reset for the USB host controller. @@ -168,51 +167,54 @@ XhcReset ( OldTpl = gBS->RaiseTPL (XHC_TPL); switch (Attributes) { - case EFI_USB_HC_RESET_GLOBAL: - // - // Flow through, same behavior as Host Controller Reset - // - case EFI_USB_HC_RESET_HOST_CONTROLLER: - if ((Xhc->DebugCapSupOffset != 0xFFFFFFFF) && ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset) & 0xFF) == XHC_CAP_USB_DEBUG) && - ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset + XHC_DC_DCCTRL) & BIT0) != 0)) { - Status = EFI_SUCCESS; - goto ON_EXIT; - } + case EFI_USB_HC_RESET_GLOBAL: // - // Host Controller must be Halt when Reset it + // Flow through, same behavior as Host Controller Reset // - if (!XhcIsHalt (Xhc)) { - Status = XhcHaltHC (Xhc, XHC_GENERIC_TIMEOUT); + case EFI_USB_HC_RESET_HOST_CONTROLLER: + if ((Xhc->DebugCapSupOffset != 0xFFFFFFFF) && ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset) & 0xFF) == XHC_CAP_USB_DEBUG) && + ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset + XHC_DC_DCCTRL) & BIT0) != 0)) + { + Status = EFI_SUCCESS; + goto ON_EXIT; + } + + // + // Host Controller must be Halt when Reset it + // + if (!XhcIsHalt (Xhc)) { + Status = XhcHaltHC (Xhc, XHC_GENERIC_TIMEOUT); + + if (EFI_ERROR (Status)) { + Status = EFI_DEVICE_ERROR; + goto ON_EXIT; + } + } + + Status = XhcResetHC (Xhc, XHC_RESET_TIMEOUT); + ASSERT (!(XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_CNR))); if (EFI_ERROR (Status)) { - Status = EFI_DEVICE_ERROR; goto ON_EXIT; } - } - - Status = XhcResetHC (Xhc, XHC_RESET_TIMEOUT); - ASSERT (!(XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_CNR))); - if (EFI_ERROR (Status)) { - goto ON_EXIT; - } - // - // Clean up the asynchronous transfers, currently only - // interrupt supports asynchronous operation. - // - XhciDelAllAsyncIntTransfers (Xhc); - XhcFreeSched (Xhc); + // + // Clean up the asynchronous transfers, currently only + // interrupt supports asynchronous operation. + // + XhciDelAllAsyncIntTransfers (Xhc); + XhcFreeSched (Xhc); - XhcInitSched (Xhc); - break; + XhcInitSched (Xhc); + break; - case EFI_USB_HC_RESET_GLOBAL_WITH_DEBUG: - case EFI_USB_HC_RESET_HOST_WITH_DEBUG: - Status = EFI_UNSUPPORTED; - break; + case EFI_USB_HC_RESET_GLOBAL_WITH_DEBUG: + case EFI_USB_HC_RESET_HOST_WITH_DEBUG: + Status = EFI_UNSUPPORTED; + break; - default: - Status = EFI_INVALID_PARAMETER; + default: + Status = EFI_INVALID_PARAMETER; } ON_EXIT: @@ -222,7 +224,6 @@ ON_EXIT: return Status; } - /** Retrieve the current state of the USB host controller. @@ -252,7 +253,7 @@ XhcGetState ( OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); if (XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT)) { *State = EfiUsbHcStateHalt; @@ -285,10 +286,10 @@ XhcSetState ( IN EFI_USB_HC_STATE State ) { - USB_XHCI_INSTANCE *Xhc; - EFI_STATUS Status; - EFI_USB_HC_STATE CurState; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + EFI_STATUS Status; + EFI_USB_HC_STATE CurState; + EFI_TPL OldTpl; Status = XhcGetState (This, &CurState); @@ -302,38 +303,38 @@ XhcSetState ( OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); switch (State) { - case EfiUsbHcStateHalt: - Status = XhcHaltHC (Xhc, XHC_GENERIC_TIMEOUT); - break; - - case EfiUsbHcStateOperational: - if (XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HSE)) { - Status = EFI_DEVICE_ERROR; + case EfiUsbHcStateHalt: + Status = XhcHaltHC (Xhc, XHC_GENERIC_TIMEOUT); break; - } - // - // Software must not write a one to this field unless the host controller - // is in the Halted state. Doing so will yield undefined results. - // refers to Spec[XHCI1.0-2.3.1] - // - if (!XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT)) { - Status = EFI_DEVICE_ERROR; - break; - } + case EfiUsbHcStateOperational: + if (XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HSE)) { + Status = EFI_DEVICE_ERROR; + break; + } - Status = XhcRunHC (Xhc, XHC_GENERIC_TIMEOUT); - break; + // + // Software must not write a one to this field unless the host controller + // is in the Halted state. Doing so will yield undefined results. + // refers to Spec[XHCI1.0-2.3.1] + // + if (!XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT)) { + Status = EFI_DEVICE_ERROR; + break; + } - case EfiUsbHcStateSuspend: - Status = EFI_UNSUPPORTED; - break; + Status = XhcRunHC (Xhc, XHC_GENERIC_TIMEOUT); + break; - default: - Status = EFI_INVALID_PARAMETER; + case EfiUsbHcStateSuspend: + Status = EFI_UNSUPPORTED; + break; + + default: + Status = EFI_INVALID_PARAMETER; } DEBUG ((DEBUG_INFO, "XhcSetState: status %r\n", Status)); @@ -364,15 +365,15 @@ XhcGetRootHubPortStatus ( OUT EFI_USB_PORT_STATUS *PortStatus ) { - USB_XHCI_INSTANCE *Xhc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - UINTN Index; - UINTN MapSize; - EFI_STATUS Status; - USB_DEV_ROUTE ParentRouteChart; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + UINTN Index; + UINTN MapSize; + EFI_STATUS Status; + USB_DEV_ROUTE ParentRouteChart; + EFI_TPL OldTpl; if (PortStatus == NULL) { return EFI_INVALID_PARAMETER; @@ -380,8 +381,8 @@ XhcGetRootHubPortStatus ( OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); - Status = EFI_SUCCESS; + Xhc = XHC_FROM_THIS (This); + Status = EFI_SUCCESS; TotalPort = Xhc->HcSParams1.Data.MaxPorts; @@ -390,7 +391,7 @@ XhcGetRootHubPortStatus ( goto ON_EXIT; } - Offset = (UINT32) (XHC_PORTSC_OFFSET + (0x10 * PortNumber)); + Offset = (UINT32)(XHC_PORTSC_OFFSET + (0x10 * PortNumber)); PortStatus->PortStatus = 0; PortStatus->PortChangeStatus = 0; @@ -401,21 +402,21 @@ XhcGetRootHubPortStatus ( // bit 10~13 of the root port status register identifies the speed of the attached device. // switch ((State & XHC_PORTSC_PS) >> 10) { - case 2: - PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; - break; + case 2: + PortStatus->PortStatus |= USB_PORT_STAT_LOW_SPEED; + break; - case 3: - PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; - break; + case 3: + PortStatus->PortStatus |= USB_PORT_STAT_HIGH_SPEED; + break; - case 4: - case 5: - PortStatus->PortStatus |= USB_PORT_STAT_SUPER_SPEED; - break; + case 4: + case 5: + PortStatus->PortStatus |= USB_PORT_STAT_SUPER_SPEED; + break; - default: - break; + default: + break; } // @@ -425,9 +426,10 @@ XhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbPortStateMap[Index].HwState)) { - PortStatus->PortStatus = (UINT16) (PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); + PortStatus->PortStatus = (UINT16)(PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); } } + // // Bit5~8 reflects its current link state. // @@ -439,7 +441,7 @@ XhcGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbPortChangeMap[Index].HwState)) { - PortStatus->PortChangeStatus = (UINT16) (PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); + PortStatus->PortChangeStatus = (UINT16)(PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); } } @@ -463,7 +465,6 @@ ON_EXIT: return Status; } - /** Sets a feature for the specified root hub port. @@ -484,12 +485,12 @@ XhcSetRootHubPortFeature ( IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_XHCI_INSTANCE *Xhc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (XHC_TPL); @@ -503,71 +504,71 @@ XhcSetRootHubPortFeature ( goto ON_EXIT; } - Offset = (UINT32) (XHC_PORTSC_OFFSET + (0x10 * PortNumber)); + Offset = (UINT32)(XHC_PORTSC_OFFSET + (0x10 * PortNumber)); State = XhcReadOpReg (Xhc, Offset); // // Mask off the port status change bits, these bits are // write clean bit // - State &= ~ (BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); + State &= ~(BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); switch (PortFeature) { - case EfiUsbPortEnable: - // - // Ports may only be enabled by the xHC. Software cannot enable a port by writing a '1' to this flag. - // A port may be disabled by software writing a '1' to this flag. - // - Status = EFI_SUCCESS; - break; - - case EfiUsbPortSuspend: - State |= XHC_PORTSC_LWS; - XhcWriteOpReg (Xhc, Offset, State); - State &= ~XHC_PORTSC_PLS; - State |= (3 << 5) ; - XhcWriteOpReg (Xhc, Offset, State); - break; - - case EfiUsbPortReset: - DEBUG ((DEBUG_INFO, "XhcUsbPortReset!\n")); - // - // Make sure Host Controller not halt before reset it - // - if (XhcIsHalt (Xhc)) { - Status = XhcRunHC (Xhc, XHC_GENERIC_TIMEOUT); + case EfiUsbPortEnable: + // + // Ports may only be enabled by the xHC. Software cannot enable a port by writing a '1' to this flag. + // A port may be disabled by software writing a '1' to this flag. + // + Status = EFI_SUCCESS; + break; - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_INFO, "XhcSetRootHubPortFeature :failed to start HC - %r\n", Status)); - break; + case EfiUsbPortSuspend: + State |= XHC_PORTSC_LWS; + XhcWriteOpReg (Xhc, Offset, State); + State &= ~XHC_PORTSC_PLS; + State |= (3 << 5); + XhcWriteOpReg (Xhc, Offset, State); + break; + + case EfiUsbPortReset: + DEBUG ((DEBUG_INFO, "XhcUsbPortReset!\n")); + // + // Make sure Host Controller not halt before reset it + // + if (XhcIsHalt (Xhc)) { + Status = XhcRunHC (Xhc, XHC_GENERIC_TIMEOUT); + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_INFO, "XhcSetRootHubPortFeature :failed to start HC - %r\n", Status)); + break; + } } - } - // - // 4.3.1 Resetting a Root Hub Port - // 1) Write the PORTSC register with the Port Reset (PR) bit set to '1'. - // - State |= XHC_PORTSC_RESET; - XhcWriteOpReg (Xhc, Offset, State); - XhcWaitOpRegBit(Xhc, Offset, XHC_PORTSC_PRC, TRUE, XHC_GENERIC_TIMEOUT); - break; + // + // 4.3.1 Resetting a Root Hub Port + // 1) Write the PORTSC register with the Port Reset (PR) bit set to '1'. + // + State |= XHC_PORTSC_RESET; + XhcWriteOpReg (Xhc, Offset, State); + XhcWaitOpRegBit (Xhc, Offset, XHC_PORTSC_PRC, TRUE, XHC_GENERIC_TIMEOUT); + break; - case EfiUsbPortPower: - // - // Not supported, ignore the operation - // - Status = EFI_SUCCESS; - break; + case EfiUsbPortPower: + // + // Not supported, ignore the operation + // + Status = EFI_SUCCESS; + break; - case EfiUsbPortOwner: - // - // XHCI root hub port don't has the owner bit, ignore the operation - // - Status = EFI_SUCCESS; - break; + case EfiUsbPortOwner: + // + // XHCI root hub port don't has the owner bit, ignore the operation + // + Status = EFI_SUCCESS; + break; - default: - Status = EFI_INVALID_PARAMETER; + default: + Status = EFI_INVALID_PARAMETER; } ON_EXIT: @@ -577,7 +578,6 @@ ON_EXIT: return Status; } - /** Clears a feature for the specified root hub port. @@ -601,17 +601,17 @@ XhcClearRootHubPortFeature ( IN EFI_USB_PORT_FEATURE PortFeature ) { - USB_XHCI_INSTANCE *Xhc; - UINT32 Offset; - UINT32 State; - UINT32 TotalPort; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + UINT32 Offset; + UINT32 State; + UINT32 TotalPort; + EFI_STATUS Status; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); - Status = EFI_SUCCESS; + Xhc = XHC_FROM_THIS (This); + Status = EFI_SUCCESS; TotalPort = (Xhc->HcSParams1.Data.MaxPorts); @@ -627,82 +627,82 @@ XhcClearRootHubPortFeature ( // write clean bit // State = XhcReadOpReg (Xhc, Offset); - State &= ~ (BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); + State &= ~(BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); switch (PortFeature) { - case EfiUsbPortEnable: - // - // Ports may only be enabled by the xHC. Software cannot enable a port by writing a '1' to this flag. - // A port may be disabled by software writing a '1' to this flag. - // - State |= XHC_PORTSC_PED; - State &= ~XHC_PORTSC_RESET; - XhcWriteOpReg (Xhc, Offset, State); - break; - - case EfiUsbPortSuspend: - State |= XHC_PORTSC_LWS; - XhcWriteOpReg (Xhc, Offset, State); - State &= ~XHC_PORTSC_PLS; - XhcWriteOpReg (Xhc, Offset, State); - break; - - case EfiUsbPortReset: - // - // PORTSC_RESET BIT(4) bit is RW1S attribute, which means Write-1-to-set status: - // Register bits indicate status when read, a clear bit may be set by - // writing a '1'. Writing a '0' to RW1S bits has no effect. - // - break; + case EfiUsbPortEnable: + // + // Ports may only be enabled by the xHC. Software cannot enable a port by writing a '1' to this flag. + // A port may be disabled by software writing a '1' to this flag. + // + State |= XHC_PORTSC_PED; + State &= ~XHC_PORTSC_RESET; + XhcWriteOpReg (Xhc, Offset, State); + break; - case EfiUsbPortOwner: - // - // XHCI root hub port don't has the owner bit, ignore the operation - // - break; + case EfiUsbPortSuspend: + State |= XHC_PORTSC_LWS; + XhcWriteOpReg (Xhc, Offset, State); + State &= ~XHC_PORTSC_PLS; + XhcWriteOpReg (Xhc, Offset, State); + break; - case EfiUsbPortConnectChange: - // - // Clear connect status change - // - State |= XHC_PORTSC_CSC; - XhcWriteOpReg (Xhc, Offset, State); - break; + case EfiUsbPortReset: + // + // PORTSC_RESET BIT(4) bit is RW1S attribute, which means Write-1-to-set status: + // Register bits indicate status when read, a clear bit may be set by + // writing a '1'. Writing a '0' to RW1S bits has no effect. + // + break; - case EfiUsbPortEnableChange: - // - // Clear enable status change - // - State |= XHC_PORTSC_PEC; - XhcWriteOpReg (Xhc, Offset, State); - break; + case EfiUsbPortOwner: + // + // XHCI root hub port don't has the owner bit, ignore the operation + // + break; - case EfiUsbPortOverCurrentChange: - // - // Clear PortOverCurrent change - // - State |= XHC_PORTSC_OCC; - XhcWriteOpReg (Xhc, Offset, State); - break; + case EfiUsbPortConnectChange: + // + // Clear connect status change + // + State |= XHC_PORTSC_CSC; + XhcWriteOpReg (Xhc, Offset, State); + break; - case EfiUsbPortResetChange: - // - // Clear Port Reset change - // - State |= XHC_PORTSC_PRC; - XhcWriteOpReg (Xhc, Offset, State); - break; + case EfiUsbPortEnableChange: + // + // Clear enable status change + // + State |= XHC_PORTSC_PEC; + XhcWriteOpReg (Xhc, Offset, State); + break; - case EfiUsbPortPower: - case EfiUsbPortSuspendChange: - // - // Not supported or not related operation - // - break; + case EfiUsbPortOverCurrentChange: + // + // Clear PortOverCurrent change + // + State |= XHC_PORTSC_OCC; + XhcWriteOpReg (Xhc, Offset, State); + break; - default: - Status = EFI_INVALID_PARAMETER; - break; + case EfiUsbPortResetChange: + // + // Clear Port Reset change + // + State |= XHC_PORTSC_PRC; + XhcWriteOpReg (Xhc, Offset, State); + break; + + case EfiUsbPortPower: + case EfiUsbPortSuspendChange: + // + // Not supported or not related operation + // + break; + + default: + Status = EFI_INVALID_PARAMETER; + break; } ON_EXIT: @@ -737,22 +737,22 @@ ON_EXIT: **/ EFI_STATUS XhcTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout, - OUT UINT32 *TransferResult + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout, + OUT UINT32 *TransferResult ) { - EFI_STATUS Status; - EFI_STATUS RecoveryStatus; - URB *Urb; + EFI_STATUS Status; + EFI_STATUS RecoveryStatus; + URB *Urb; ASSERT ((Type == XHC_CTRL_TRANSFER) || (Type == XHC_BULK_TRANSFER) || (Type == XHC_INT_TRANSFER_SYNC)); Urb = XhcCreateUrb ( @@ -780,7 +780,7 @@ XhcTransfer ( // // The transfer timed out. Abort the transfer by dequeueing of the TD. // - RecoveryStatus = XhcDequeueTrbFromEndpoint(Xhc, Urb); + RecoveryStatus = XhcDequeueTrbFromEndpoint (Xhc, Urb); if (RecoveryStatus == EFI_ALREADY_STARTED) { // // The URB is finished just before stopping endpoint. @@ -789,8 +789,8 @@ XhcTransfer ( ASSERT (Urb->Result == EFI_USB_NOERROR); Status = EFI_SUCCESS; DEBUG ((DEBUG_ERROR, "XhcTransfer[Type=%d]: pending URB is finished, Length = %d.\n", Type, Urb->Completed)); - } else if (EFI_ERROR(RecoveryStatus)) { - DEBUG((DEBUG_ERROR, "XhcTransfer[Type=%d]: XhcDequeueTrbFromEndpoint failed!\n", Type)); + } else if (EFI_ERROR (RecoveryStatus)) { + DEBUG ((DEBUG_ERROR, "XhcTransfer[Type=%d]: XhcDequeueTrbFromEndpoint failed!\n", Type)); } } @@ -799,7 +799,7 @@ XhcTransfer ( if ((*TransferResult == EFI_USB_ERR_STALL) || (*TransferResult == EFI_USB_ERR_BABBLE)) { ASSERT (Status == EFI_DEVICE_ERROR); - RecoveryStatus = XhcRecoverHaltedEndpoint(Xhc, Urb); + RecoveryStatus = XhcRecoverHaltedEndpoint (Xhc, Urb); if (EFI_ERROR (RecoveryStatus)) { DEBUG ((DEBUG_ERROR, "XhcTransfer[Type=%d]: XhcRecoverHaltedEndpoint failed!\n", Type)); } @@ -876,24 +876,28 @@ XhcControlTransfer ( if ((TransferDirection != EfiUsbDataIn) && (TransferDirection != EfiUsbDataOut) && - (TransferDirection != EfiUsbNoData)) { + (TransferDirection != EfiUsbNoData)) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection == EfiUsbNoData) && - ((Data != NULL) || (*DataLength != 0))) { + ((Data != NULL) || (*DataLength != 0))) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection != EfiUsbNoData) && - ((Data == NULL) || (*DataLength == 0))) { + ((Data == NULL) || (*DataLength == 0))) + { return EFI_INVALID_PARAMETER; } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && (MaximumPacketLength != 32) && (MaximumPacketLength != 64) && (MaximumPacketLength != 512) - ) { + ) + { return EFI_INVALID_PARAMETER; } @@ -907,7 +911,7 @@ XhcControlTransfer ( OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); Status = EFI_DEVICE_ERROR; *TransferResult = EFI_USB_ERR_SYSTEM; @@ -931,7 +935,8 @@ XhcControlTransfer ( // According to XHCI 1.0 spec, the Set_Address request is replaced by XHCI's Address_Device cmd. // if ((Request->Request == USB_REQ_SET_ADDRESS) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) + { // // Reset the BusDevAddr field of all disabled entries in UsbDevContext array firstly. // This way is used to clean the history to avoid using wrong device address by XhcAsyncInterruptTransfer(). @@ -939,7 +944,8 @@ XhcControlTransfer ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId == 0) && - (Xhc->UsbDevContext[Index + 1].BusDevAddr == (UINT8)Request->Value)) { + (Xhc->UsbDevContext[Index + 1].BusDevAddr == (UINT8)Request->Value)) + { Xhc->UsbDevContext[Index + 1].BusDevAddr = 0; } } @@ -948,6 +954,7 @@ XhcControlTransfer ( Status = EFI_DEVICE_ERROR; goto ON_EXIT; } + // // The actual device address has been assigned by XHCI during initializing the device slot. // So we just need establish the mapping relationship between the device address requested from UsbBus @@ -955,7 +962,7 @@ XhcControlTransfer ( // can find out the actual device address by it. // Xhc->UsbDevContext[SlotId].BusDevAddr = (UINT8)Request->Value; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; goto ON_EXIT; } @@ -966,20 +973,20 @@ XhcControlTransfer ( // endpoint is bidirectional. XhcCreateUrb expects this // combination of Ep addr and its direction. // - Endpoint = (UINT8) (0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); - Status = XhcTransfer ( - Xhc, - DeviceAddress, - Endpoint, - DeviceSpeed, - MaximumPacketLength, - XHC_CTRL_TRANSFER, - Request, - Data, - DataLength, - Timeout, - TransferResult - ); + Endpoint = (UINT8)(0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); + Status = XhcTransfer ( + Xhc, + DeviceAddress, + Endpoint, + DeviceSpeed, + MaximumPacketLength, + XHC_CTRL_TRANSFER, + Request, + Data, + DataLength, + Timeout, + TransferResult + ); if (EFI_ERROR (Status)) { goto ON_EXIT; @@ -992,28 +999,30 @@ XhcControlTransfer ( // if ((Request->Request == USB_REQ_GET_DESCRIPTOR) && ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE)) || - ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_DEVICE))))) { + ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_DEVICE))))) + { DescriptorType = (UINT8)(Request->Value >> 8); if ((DescriptorType == USB_DESC_TYPE_DEVICE) && ((*DataLength == sizeof (EFI_USB_DEVICE_DESCRIPTOR)) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (*DataLength == 8)))) { - ASSERT (Data != NULL); + ASSERT (Data != NULL); + // + // Store a copy of device scriptor as hub device need this info to configure endpoint. + // + CopyMem (&Xhc->UsbDevContext[SlotId].DevDesc, Data, *DataLength); + if (Xhc->UsbDevContext[SlotId].DevDesc.BcdUSB >= 0x0300) { // - // Store a copy of device scriptor as hub device need this info to configure endpoint. + // If it's a usb3.0 device, then its max packet size is a 2^n. // - CopyMem (&Xhc->UsbDevContext[SlotId].DevDesc, Data, *DataLength); - if (Xhc->UsbDevContext[SlotId].DevDesc.BcdUSB >= 0x0300) { - // - // If it's a usb3.0 device, then its max packet size is a 2^n. - // - MaxPacket0 = 1 << Xhc->UsbDevContext[SlotId].DevDesc.MaxPacketSize0; - } else { - MaxPacket0 = Xhc->UsbDevContext[SlotId].DevDesc.MaxPacketSize0; - } - Xhc->UsbDevContext[SlotId].ConfDesc = AllocateZeroPool (Xhc->UsbDevContext[SlotId].DevDesc.NumConfigurations * sizeof (EFI_USB_CONFIG_DESCRIPTOR *)); - if (Xhc->HcCParams.Data.Csz == 0) { - Status = XhcEvaluateContext (Xhc, SlotId, MaxPacket0); - } else { - Status = XhcEvaluateContext64 (Xhc, SlotId, MaxPacket0); - } + MaxPacket0 = 1 << Xhc->UsbDevContext[SlotId].DevDesc.MaxPacketSize0; + } else { + MaxPacket0 = Xhc->UsbDevContext[SlotId].DevDesc.MaxPacketSize0; + } + + Xhc->UsbDevContext[SlotId].ConfDesc = AllocateZeroPool (Xhc->UsbDevContext[SlotId].DevDesc.NumConfigurations * sizeof (EFI_USB_CONFIG_DESCRIPTOR *)); + if (Xhc->HcCParams.Data.Csz == 0) { + Status = XhcEvaluateContext (Xhc, SlotId, MaxPacket0); + } else { + Status = XhcEvaluateContext64 (Xhc, SlotId, MaxPacket0); + } } else if (DescriptorType == USB_DESC_TYPE_CONFIG) { ASSERT (Data != NULL); if (*DataLength == ((UINT16 *)Data)[1]) { @@ -1022,7 +1031,7 @@ XhcControlTransfer ( // Index = (UINT8)Request->Value; ASSERT (Index < Xhc->UsbDevContext[SlotId].DevDesc.NumConfigurations); - Xhc->UsbDevContext[SlotId].ConfDesc[Index] = AllocateZeroPool(*DataLength); + Xhc->UsbDevContext[SlotId].ConfDesc[Index] = AllocateZeroPool (*DataLength); CopyMem (Xhc->UsbDevContext[SlotId].ConfDesc[Index], Data, *DataLength); // // Default to use AlternateSetting 0 for all interfaces. @@ -1030,7 +1039,8 @@ XhcControlTransfer ( Xhc->UsbDevContext[SlotId].ActiveAlternateSetting = AllocateZeroPool (Xhc->UsbDevContext[SlotId].ConfDesc[Index]->NumInterfaces * sizeof (UINT8)); } } else if (((DescriptorType == USB_DESC_TYPE_HUB) || - (DescriptorType == USB_DESC_TYPE_HUB_SUPER_SPEED)) && (*DataLength > 2)) { + (DescriptorType == USB_DESC_TYPE_HUB_SUPER_SPEED)) && (*DataLength > 2)) + { ASSERT (Data != NULL); HubDesc = (EFI_USB_HUB_DESCRIPTOR *)Data; ASSERT (HubDesc->NumPorts <= 15); @@ -1055,7 +1065,8 @@ XhcControlTransfer ( } } } else if ((Request->Request == USB_REQ_SET_CONFIG) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) + { // // Hook Set_Config request from UsbBus as we need configure device endpoint. // @@ -1066,17 +1077,19 @@ XhcControlTransfer ( } else { Status = XhcSetConfigCmd64 (Xhc, SlotId, DeviceSpeed, Xhc->UsbDevContext[SlotId].ConfDesc[Index]); } + break; } } } else if ((Request->Request == USB_REQ_SET_INTERFACE) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_INTERFACE))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_INTERFACE))) + { // // Hook Set_Interface request from UsbBus as we need configure interface setting. // Request->Value indicates AlterlateSetting to set // Request->Index indicates Interface to set // - if (Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8) Request->Index] != (UINT8) Request->Value) { + if (Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8)Request->Index] != (UINT8)Request->Value) { if (Xhc->HcCParams.Data.Csz == 0) { Status = XhcSetInterface (Xhc, SlotId, DeviceSpeed, Xhc->UsbDevContext[SlotId].ConfDesc[Xhc->UsbDevContext[SlotId].ActiveConfiguration - 1], Request); } else { @@ -1084,7 +1097,8 @@ XhcControlTransfer ( } } } else if ((Request->Request == USB_REQ_GET_STATUS) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER))) + { ASSERT (Data != NULL); // // Hook Get_Status request from UsbBus to keep track of the port status change. @@ -1117,14 +1131,14 @@ XhcControlTransfer ( MapSize = sizeof (mUsbHubPortStateMap) / sizeof (USB_PORT_STATE_MAP); for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubPortStateMap[Index].HwState)) { - PortStatus.PortStatus = (UINT16) (PortStatus.PortStatus | mUsbHubPortStateMap[Index].UefiState); + PortStatus.PortStatus = (UINT16)(PortStatus.PortStatus | mUsbHubPortStateMap[Index].UefiState); } } MapSize = sizeof (mUsbHubPortChangeMap) / sizeof (USB_PORT_STATE_MAP); for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubPortChangeMap[Index].HwState)) { - PortStatus.PortChangeStatus = (UINT16) (PortStatus.PortChangeStatus | mUsbHubPortChangeMap[Index].UefiState); + PortStatus.PortChangeStatus = (UINT16)(PortStatus.PortChangeStatus | mUsbHubPortChangeMap[Index].UefiState); } } @@ -1133,11 +1147,11 @@ XhcControlTransfer ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubClearPortChangeMap[Index].HwState)) { ZeroMem (&ClearPortRequest, sizeof (EFI_USB_DEVICE_REQUEST)); - ClearPortRequest.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER); - ClearPortRequest.Request = (UINT8) USB_REQ_CLEAR_FEATURE; - ClearPortRequest.Value = mUsbHubClearPortChangeMap[Index].Selector; - ClearPortRequest.Index = Request->Index; - ClearPortRequest.Length = 0; + ClearPortRequest.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER); + ClearPortRequest.Request = (UINT8)USB_REQ_CLEAR_FEATURE; + ClearPortRequest.Value = mUsbHubClearPortChangeMap[Index].Selector; + ClearPortRequest.Index = Request->Index; + ClearPortRequest.Length = 0; XhcControlTransfer ( This, @@ -1157,7 +1171,7 @@ XhcControlTransfer ( XhcPollPortStatusChange (Xhc, Xhc->UsbDevContext[SlotId].RouteString, (UINT8)Request->Index, &PortStatus); - *(UINT32 *)Data = *(UINT32*)&PortStatus; + *(UINT32 *)Data = *(UINT32 *)&PortStatus; } ON_EXIT: @@ -1170,7 +1184,6 @@ ON_EXIT: return Status; } - /** Submits bulk transfer to a bulk endpoint of a USB device. @@ -1218,16 +1231,17 @@ XhcBulkTransfer ( OUT UINT32 *TransferResult ) { - USB_XHCI_INSTANCE *Xhc; - UINT8 SlotId; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + UINT8 SlotId; + EFI_STATUS Status; + EFI_TPL OldTpl; // // Validate the parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -1238,13 +1252,14 @@ XhcBulkTransfer ( if ((DeviceSpeed == EFI_USB_SPEED_LOW) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || ((EFI_USB_SPEED_HIGH == DeviceSpeed) && (MaximumPacketLength > 512)) || - ((EFI_USB_SPEED_SUPER == DeviceSpeed) && (MaximumPacketLength > 1024))) { + ((EFI_USB_SPEED_SUPER == DeviceSpeed) && (MaximumPacketLength > 1024))) + { return EFI_INVALID_PARAMETER; } OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -1284,6 +1299,7 @@ ON_EXIT: if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcBulkTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); } + gBS->RestoreTPL (OldTpl); return Status; @@ -1335,12 +1351,12 @@ XhcAsyncInterruptTransfer ( IN VOID *Context OPTIONAL ) { - USB_XHCI_INSTANCE *Xhc; - URB *Urb; - EFI_STATUS Status; - UINT8 SlotId; - UINT8 Index; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + URB *Urb; + EFI_STATUS Status; + UINT8 SlotId; + UINT8 Index; + EFI_TPL OldTpl; // // Validate parameters @@ -1365,7 +1381,7 @@ XhcAsyncInterruptTransfer ( OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); // // Delete Async interrupt transfer request. @@ -1433,7 +1449,6 @@ ON_EXIT: return Status; } - /** Submits synchronous interrupt transfer to an interrupt endpoint of a USB device. @@ -1477,16 +1492,17 @@ XhcSyncInterruptTransfer ( OUT UINT32 *TransferResult ) { - USB_XHCI_INSTANCE *Xhc; - UINT8 SlotId; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + UINT8 SlotId; + EFI_STATUS Status; + EFI_TPL OldTpl; // // Validates parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -1496,13 +1512,14 @@ XhcSyncInterruptTransfer ( if (((DeviceSpeed == EFI_USB_SPEED_LOW) && (MaximumPacketLength != 8)) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || - ((DeviceSpeed == EFI_USB_SPEED_HIGH) && (MaximumPacketLength > 3072))) { + ((DeviceSpeed == EFI_USB_SPEED_HIGH) && (MaximumPacketLength > 3072))) + { return EFI_INVALID_PARAMETER; } OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = XHC_FROM_THIS (This); + Xhc = XHC_FROM_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -1538,12 +1555,12 @@ ON_EXIT: if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSyncInterruptTransfer: error - %r, transfer - %x\n", Status, *TransferResult)); } + gBS->RestoreTPL (OldTpl); return Status; } - /** Submits isochronous transfer to a target USB device. @@ -1583,7 +1600,6 @@ XhcIsochronousTransfer ( return EFI_UNSUPPORTED; } - /** Submits Async isochronous transfer to a target USB device. @@ -1639,8 +1655,8 @@ XhcAsyncIsochronousTransfer ( EFI_STATUS EFIAPI XhcDriverEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return EfiLibInstallDriverBindingComponentName2 ( @@ -1653,7 +1669,6 @@ XhcDriverEntryPoint ( ); } - /** Test to see if this driver supports ControllerHandle. Any ControllerHandle that has Usb2HcProtocol installed will @@ -1670,14 +1685,14 @@ XhcDriverEntryPoint ( EFI_STATUS EFIAPI XhcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - USB_CLASSC UsbClassCReg; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + USB_CLASSC UsbClassCReg; // // Test whether there is PCI IO Protocol attached on the controller handle. @@ -1685,7 +1700,7 @@ XhcDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1713,7 +1728,8 @@ XhcDriverBindingSupported ( // if ((UsbClassCReg.BaseCode != PCI_CLASS_SERIAL) || (UsbClassCReg.SubClassCode != PCI_CLASS_SERIAL_USB) || - (UsbClassCReg.ProgInterface != PCI_IF_XHCI)) { + (UsbClassCReg.ProgInterface != PCI_IF_XHCI)) + { Status = EFI_UNSUPPORTED; } @@ -1739,18 +1755,18 @@ ON_EXIT: otherwise NULL. **/ -USB_XHCI_INSTANCE* +USB_XHCI_INSTANCE * XhcCreateUsbHc ( IN EFI_PCI_IO_PROTOCOL *PciIo, IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, IN UINT64 OriginalPciAttributes ) { - USB_XHCI_INSTANCE *Xhc; - EFI_STATUS Status; - UINT32 PageSize; - UINT16 ExtCapReg; - UINT8 ReleaseNumber; + USB_XHCI_INSTANCE *Xhc; + EFI_STATUS Status; + UINT32 PageSize; + UINT16 ExtCapReg; + UINT8 ReleaseNumber; Xhc = AllocateZeroPool (sizeof (USB_XHCI_INSTANCE)); @@ -1797,12 +1813,12 @@ XhcCreateUsbHc ( // This xHC supports a page size of 2^(n+12) if bit n is Set. For example, // if bit 0 is Set, the xHC supports 4k byte page sizes. // - PageSize = XhcReadOpReg(Xhc, XHC_PAGESIZE_OFFSET) & XHC_PAGESIZE_MASK; - Xhc->PageSize = 1 << (HighBitSet32(PageSize) + 12); + PageSize = XhcReadOpReg (Xhc, XHC_PAGESIZE_OFFSET) & XHC_PAGESIZE_MASK; + Xhc->PageSize = 1 << (HighBitSet32 (PageSize) + 12); - ExtCapReg = (UINT16) (Xhc->HcCParams.Data.ExtCapReg); - Xhc->ExtCapRegBase = ExtCapReg << 2; - Xhc->UsbLegSupOffset = XhcGetCapabilityAddr (Xhc, XHC_CAP_USB_LEGACY); + ExtCapReg = (UINT16)(Xhc->HcCParams.Data.ExtCapReg); + Xhc->ExtCapRegBase = ExtCapReg << 2; + Xhc->UsbLegSupOffset = XhcGetCapabilityAddr (Xhc, XHC_CAP_USB_LEGACY); Xhc->DebugCapSupOffset = XhcGetCapabilityAddr (Xhc, XHC_CAP_USB_DEBUG); DEBUG ((DEBUG_INFO, "XhcCreateUsb3Hc: Capability length 0x%x\n", Xhc->CapLength)); @@ -1854,7 +1870,7 @@ XhcExitBootService ( USB_XHCI_INSTANCE *Xhc; EFI_PCI_IO_PROTOCOL *PciIo; - Xhc = (USB_XHCI_INSTANCE*) Context; + Xhc = (USB_XHCI_INSTANCE *)Context; PciIo = Xhc->PciIo; // @@ -1874,11 +1890,11 @@ XhcExitBootService ( // Restore original PCI attributes // PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationSet, - Xhc->OriginalPciAttributes, - NULL - ); + PciIo, + EfiPciIoAttributeOperationSet, + Xhc->OriginalPciAttributes, + NULL + ); } /** @@ -1897,17 +1913,17 @@ XhcExitBootService ( EFI_STATUS EFIAPI XhcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 Supports; - UINT64 OriginalPciAttributes; - BOOLEAN PciAttributesSaved; - USB_XHCI_INSTANCE *Xhc; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 Supports; + UINT64 OriginalPciAttributes; + BOOLEAN PciAttributesSaved; + USB_XHCI_INSTANCE *Xhc; EFI_DEVICE_PATH_PROTOCOL *HcDevicePath; // @@ -1916,7 +1932,7 @@ XhcDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiPciIoProtocolGuid, - (VOID **) &PciIo, + (VOID **)&PciIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1930,14 +1946,14 @@ XhcDriverBindingStart ( // Open Device Path Protocol for on USB host controller // HcDevicePath = NULL; - Status = gBS->OpenProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - (VOID **) &HcDevicePath, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiDevicePathProtocolGuid, + (VOID **)&HcDevicePath, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); PciAttributesSaved = FALSE; // @@ -1953,6 +1969,7 @@ XhcDriverBindingStart ( if (EFI_ERROR (Status)) { goto CLOSE_PCIIO; } + PciAttributesSaved = TRUE; Status = PciIo->Attributes ( @@ -1963,12 +1980,12 @@ XhcDriverBindingStart ( ); if (!EFI_ERROR (Status)) { Supports &= (UINT64)EFI_PCI_DEVICE_ENABLE; - Status = PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationEnable, - Supports, - NULL - ); + Status = PciIo->Attributes ( + PciIo, + EfiPciIoAttributeOperationEnable, + Supports, + NULL + ); } if (EFI_ERROR (Status)) { @@ -2000,9 +2017,13 @@ XhcDriverBindingStart ( if (!EFI_ERROR (Status)) { Xhc->Support64BitDma = TRUE; } else { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: failed to enable 64-bit DMA on 64-bit capable controller @ %p (%r)\n", - __FUNCTION__, Controller, Status)); + __FUNCTION__, + Controller, + Status + )); } } @@ -2025,7 +2046,7 @@ XhcDriverBindingStart ( // // Start the Host Controller // - XhcRunHC(Xhc, XHC_GENERIC_TIMEOUT); + XhcRunHC (Xhc, XHC_GENERIC_TIMEOUT); // // Start the asynchronous interrupt monitor @@ -2096,11 +2117,11 @@ CLOSE_PCIIO: // Restore original PCI attributes // PciIo->Attributes ( - PciIo, - EfiPciIoAttributeOperationSet, - OriginalPciAttributes, - NULL - ); + PciIo, + EfiPciIoAttributeOperationSet, + OriginalPciAttributes, + NULL + ); } gBS->CloseProtocol ( @@ -2113,7 +2134,6 @@ CLOSE_PCIIO: return Status; } - /** Stop this driver on ControllerHandle. Support stopping any child handles created by this driver. @@ -2130,10 +2150,10 @@ CLOSE_PCIIO: EFI_STATUS EFIAPI XhcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -2150,7 +2170,7 @@ XhcDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -2185,9 +2205,11 @@ XhcDriverBindingStop ( // for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled || - (Xhc->UsbDevContext[Index + 1].SlotId == 0)) { + (Xhc->UsbDevContext[Index + 1].SlotId == 0)) + { continue; } + if (Xhc->HcCParams.Data.Csz == 0) { XhcDisableSlotCmd (Xhc, Xhc->UsbDevContext[Index + 1].SlotId); } else { diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h index 3285eb8798..5054d796b1 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h @@ -29,8 +29,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -typedef struct _USB_XHCI_INSTANCE USB_XHCI_INSTANCE; -typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; +typedef struct _USB_XHCI_INSTANCE USB_XHCI_INSTANCE; +typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; #include "XhciReg.h" #include "XhciSched.h" @@ -40,62 +40,62 @@ typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; // // The unit is microsecond, setting it as 1us. // -#define XHC_1_MICROSECOND (1) +#define XHC_1_MICROSECOND (1) // // The unit is microsecond, setting it as 1ms. // -#define XHC_1_MILLISECOND (1000) +#define XHC_1_MILLISECOND (1000) // // XHC generic timeout experience values. // The unit is millisecond, setting it as 10s. // -#define XHC_GENERIC_TIMEOUT (10 * 1000) +#define XHC_GENERIC_TIMEOUT (10 * 1000) // // XHC reset timeout experience values. // The unit is millisecond, setting it as 1s. // -#define XHC_RESET_TIMEOUT (1000) +#define XHC_RESET_TIMEOUT (1000) // // TRSTRCY delay requirement in usb 2.0 spec chapter 7.1.7.5. // The unit is microsecond, setting it as 10ms. // -#define XHC_RESET_RECOVERY_DELAY (10 * 1000) +#define XHC_RESET_RECOVERY_DELAY (10 * 1000) // // XHC async transfer timer interval, set by experience. // The unit is 100us, takes 1ms as interval. // -#define XHC_ASYNC_TIMER_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) +#define XHC_ASYNC_TIMER_INTERVAL EFI_TIMER_PERIOD_MILLISECONDS(1) // // XHC raises TPL to TPL_NOTIFY to serialize all its operations // to protect shared data structures. // -#define XHC_TPL TPL_NOTIFY +#define XHC_TPL TPL_NOTIFY -#define CMD_RING_TRB_NUMBER 0x100 -#define TR_RING_TRB_NUMBER 0x100 -#define ERST_NUMBER 0x01 -#define EVENT_RING_TRB_NUMBER 0x200 +#define CMD_RING_TRB_NUMBER 0x100 +#define TR_RING_TRB_NUMBER 0x100 +#define ERST_NUMBER 0x01 +#define EVENT_RING_TRB_NUMBER 0x200 -#define CMD_INTER 0 -#define CTRL_INTER 1 -#define BULK_INTER 2 -#define INT_INTER 3 -#define INT_INTER_ASYNC 4 +#define CMD_INTER 0 +#define CTRL_INTER 1 +#define BULK_INTER 2 +#define INT_INTER 3 +#define INT_INTER_ASYNC 4 -#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) +#define EFI_LIST_CONTAINER(Entry, Type, Field) BASE_CR(Entry, Type, Field) -#define XHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0xFFFFFFFF)) -#define XHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINT64)(UINTN)(Addr64), 32) & 0xFFFFFFFF)) -#define XHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define XHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0xFFFFFFFF)) +#define XHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINT64)(UINTN)(Addr64), 32) & 0xFFFFFFFF)) +#define XHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) #define XHC_REG_BIT_IS_SET(Xhc, Offset, Bit) \ (XHC_BIT_IS_SET(XhcReadOpReg ((Xhc), (Offset)), (Bit))) -#define XHCI_IS_DATAIN(EndpointAddr) XHC_BIT_IS_SET((EndpointAddr), 0x80) +#define XHCI_IS_DATAIN(EndpointAddr) XHC_BIT_IS_SET((EndpointAddr), 0x80) -#define XHCI_INSTANCE_SIG SIGNATURE_32 ('x', 'h', 'c', 'i') -#define XHC_FROM_THIS(a) CR(a, USB_XHCI_INSTANCE, Usb2Hc, XHCI_INSTANCE_SIG) +#define XHCI_INSTANCE_SIG SIGNATURE_32 ('x', 'h', 'c', 'i') +#define XHC_FROM_THIS(a) CR(a, USB_XHCI_INSTANCE, Usb2Hc, XHCI_INSTANCE_SIG) #define USB_DESC_TYPE_HUB 0x29 #define USB_DESC_TYPE_HUB_SUPER_SPEED 0x2a @@ -113,19 +113,19 @@ typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; // #pragma pack(1) typedef struct { - UINT8 ProgInterface; - UINT8 SubClassCode; - UINT8 BaseCode; + UINT8 ProgInterface; + UINT8 SubClassCode; + UINT8 BaseCode; } USB_CLASSC; typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 NumPorts; - UINT16 HubCharacter; - UINT8 PwrOn2PwrGood; - UINT8 HubContrCurrent; - UINT8 Filler[16]; + UINT8 Length; + UINT8 DescType; + UINT8 NumPorts; + UINT16 HubCharacter; + UINT8 PwrOn2PwrGood; + UINT8 HubContrCurrent; + UINT8 Filler[16]; } EFI_USB_HUB_DESCRIPTOR; #pragma pack() @@ -133,23 +133,23 @@ struct _USB_DEV_CONTEXT { // // Whether this entry in UsbDevContext array is used or not. // - BOOLEAN Enabled; + BOOLEAN Enabled; // // The slot id assigned to the new device through XHCI's Enable_Slot cmd. // - UINT8 SlotId; + UINT8 SlotId; // // The route string presented an attached usb device. // - USB_DEV_ROUTE RouteString; + USB_DEV_ROUTE RouteString; // // The route string of parent device if it exists. Otherwise it's zero. // - USB_DEV_ROUTE ParentRouteString; + USB_DEV_ROUTE ParentRouteString; // // The actual device address assigned by XHCI through Address_Device command. // - UINT8 XhciDevAddr; + UINT8 XhciDevAddr; // // The requested device address from UsbBus driver through Set_Address standard usb request. // As XHCI spec replaces this request with Address_Device command, we have to record the @@ -158,23 +158,23 @@ struct _USB_DEV_CONTEXT { // through EFI_USB2_HC_PROTOCOL. Xhci driver would be responsible for translating it to actual // device address and access the actual device. // - UINT8 BusDevAddr; + UINT8 BusDevAddr; // // The pointer to the input device context. // - VOID *InputContext; + VOID *InputContext; // // The pointer to the output device context. // - VOID *OutputContext; + VOID *OutputContext; // // The transfer queue for every endpoint. // - VOID *EndpointTransferRing[31]; + VOID *EndpointTransferRing[31]; // // The device descriptor which is stored to support XHCI's Evaluate_Context cmd. // - EFI_USB_DEVICE_DESCRIPTOR DevDesc; + EFI_USB_DEVICE_DESCRIPTOR DevDesc; // // As a usb device may include multiple configuration descriptors, we dynamically allocate an array // to store them. @@ -182,81 +182,80 @@ struct _USB_DEV_CONTEXT { // such as Interface descriptor, Endpoint descriptor, and so on. // These information is used to support XHCI's Config_Endpoint cmd. // - EFI_USB_CONFIG_DESCRIPTOR **ConfDesc; + EFI_USB_CONFIG_DESCRIPTOR **ConfDesc; // // A device has an active Configuration. // - UINT8 ActiveConfiguration; + UINT8 ActiveConfiguration; // // Every interface has an active AlternateSetting. // - UINT8 *ActiveAlternateSetting; + UINT8 *ActiveAlternateSetting; }; struct _USB_XHCI_INSTANCE { - UINT32 Signature; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT64 OriginalPciAttributes; - USBHC_MEM_POOL *MemPool; + UINT32 Signature; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT64 OriginalPciAttributes; + USBHC_MEM_POOL *MemPool; - EFI_USB2_HC_PROTOCOL Usb2Hc; + EFI_USB2_HC_PROTOCOL Usb2Hc; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; // // ExitBootServicesEvent is used to set OS semaphore and // stop the XHC DMA operation after exit boot service. // - EFI_EVENT ExitBootServiceEvent; - EFI_EVENT PollTimer; - LIST_ENTRY AsyncIntTransfers; - - UINT8 CapLength; ///< Capability Register Length - XHC_HCSPARAMS1 HcSParams1; ///< Structural Parameters 1 - XHC_HCSPARAMS2 HcSParams2; ///< Structural Parameters 2 - XHC_HCCPARAMS HcCParams; ///< Capability Parameters - UINT32 DBOff; ///< Doorbell Offset - UINT32 RTSOff; ///< Runtime Register Space Offset - UINT16 MaxInterrupt; - UINT32 PageSize; - UINT64 *ScratchBuf; - VOID *ScratchMap; - UINT32 MaxScratchpadBufs; - UINT64 *ScratchEntry; - UINTN *ScratchEntryMap; - UINT32 ExtCapRegBase; - UINT32 UsbLegSupOffset; - UINT32 DebugCapSupOffset; - UINT64 *DCBAA; - VOID *DCBAAMap; - UINT32 MaxSlotsEn; - URB *PendingUrb; + EFI_EVENT ExitBootServiceEvent; + EFI_EVENT PollTimer; + LIST_ENTRY AsyncIntTransfers; + + UINT8 CapLength; ///< Capability Register Length + XHC_HCSPARAMS1 HcSParams1; ///< Structural Parameters 1 + XHC_HCSPARAMS2 HcSParams2; ///< Structural Parameters 2 + XHC_HCCPARAMS HcCParams; ///< Capability Parameters + UINT32 DBOff; ///< Doorbell Offset + UINT32 RTSOff; ///< Runtime Register Space Offset + UINT16 MaxInterrupt; + UINT32 PageSize; + UINT64 *ScratchBuf; + VOID *ScratchMap; + UINT32 MaxScratchpadBufs; + UINT64 *ScratchEntry; + UINTN *ScratchEntryMap; + UINT32 ExtCapRegBase; + UINT32 UsbLegSupOffset; + UINT32 DebugCapSupOffset; + UINT64 *DCBAA; + VOID *DCBAAMap; + UINT32 MaxSlotsEn; + URB *PendingUrb; // // Cmd Transfer Ring // - TRANSFER_RING CmdRing; + TRANSFER_RING CmdRing; // // EventRing // - EVENT_RING EventRing; + EVENT_RING EventRing; // // Misc // - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; // // Store device contexts managed by XHCI instance // The array supports up to 255 devices, entry 0 is reserved and should not be used. // - USB_DEV_CONTEXT UsbDevContext[256]; + USB_DEV_CONTEXT UsbDevContext[256]; - BOOLEAN Support64BitDma; // Whether 64 bit DMA may be used with this device + BOOLEAN Support64BitDma; // Whether 64 bit DMA may be used with this device }; - -extern EFI_DRIVER_BINDING_PROTOCOL gXhciDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gXhciComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gXhciComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gXhciDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gXhciComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gXhciComponentName2; /** Test to see if this driver supports ControllerHandle. Any @@ -274,9 +273,9 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gXhciComponentName2; EFI_STATUS EFIAPI XhcDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -295,9 +294,9 @@ XhcDriverBindingSupported ( EFI_STATUS EFIAPI XhcDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -316,10 +315,10 @@ XhcDriverBindingStart ( EFI_STATUS EFIAPI XhcDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c index 70102a7fcf..80be3311d4 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c @@ -21,18 +21,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT8 XhcReadCapReg8 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ) { - UINT8 Data; - EFI_STATUS Status; + UINT8 Data; + EFI_STATUS Status; Status = Xhc->PciIo->Mem.Read ( Xhc->PciIo, EfiPciIoWidthUint8, XHC_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); @@ -57,18 +57,18 @@ XhcReadCapReg8 ( **/ UINT32 XhcReadCapReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; Status = Xhc->PciIo->Mem.Read ( Xhc->PciIo, EfiPciIoWidthUint32, XHC_BAR_INDEX, - (UINT64) Offset, + (UINT64)Offset, 1, &Data ); @@ -93,12 +93,12 @@ XhcReadCapReg ( **/ UINT32 XhcReadOpReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; ASSERT (Xhc->CapLength != 0); @@ -129,12 +129,12 @@ XhcReadOpReg ( **/ VOID XhcWriteOpReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Xhc->CapLength != 0); @@ -152,10 +152,6 @@ XhcWriteOpReg ( } } - - - - /** Write the data to the XHCI door bell register. @@ -166,12 +162,12 @@ XhcWriteOpReg ( **/ VOID XhcWriteDoorBellReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Xhc->DBOff != 0); @@ -200,12 +196,12 @@ XhcWriteDoorBellReg ( **/ UINT32 XhcReadRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; ASSERT (Xhc->RTSOff != 0); @@ -236,12 +232,12 @@ XhcReadRuntimeReg ( **/ VOID XhcWriteRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Xhc->RTSOff != 0); @@ -270,12 +266,12 @@ XhcWriteRuntimeReg ( **/ UINT32 XhcReadExtCapReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; ASSERT (Xhc->ExtCapRegBase != 0); @@ -306,12 +302,12 @@ XhcReadExtCapReg ( **/ VOID XhcWriteExtCapReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (Xhc->ExtCapRegBase != 0); @@ -329,7 +325,6 @@ XhcWriteExtCapReg ( } } - /** Set one bit of the runtime register while keeping other bits. @@ -340,12 +335,12 @@ XhcWriteExtCapReg ( **/ VOID XhcSetRuntimeRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcReadRuntimeReg (Xhc, Offset); Data |= Bit; @@ -362,12 +357,12 @@ XhcSetRuntimeRegBit ( **/ VOID XhcClearRuntimeRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcReadRuntimeReg (Xhc, Offset); Data &= ~Bit; @@ -384,19 +379,18 @@ XhcClearRuntimeRegBit ( **/ VOID XhcSetOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcReadOpReg (Xhc, Offset); Data |= Bit; XhcWriteOpReg (Xhc, Offset, Data); } - /** Clear one bit of the operational register while keeping other bits. @@ -407,12 +401,12 @@ XhcSetOpRegBit ( **/ VOID XhcClearOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcReadOpReg (Xhc, Offset); Data &= ~Bit; @@ -436,15 +430,15 @@ XhcClearOpRegBit ( **/ EFI_STATUS XhcWaitOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ) { - EFI_STATUS Status; - EFI_EVENT TimeoutEvent; + EFI_STATUS Status; + EFI_EVENT TimeoutEvent; TimeoutEvent = NULL; @@ -460,15 +454,17 @@ XhcWaitOpRegBit ( &TimeoutEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto DONE; } - Status = gBS->SetTimer (TimeoutEvent, - TimerRelative, - EFI_TIMER_PERIOD_MILLISECONDS(Timeout)); + Status = gBS->SetTimer ( + TimeoutEvent, + TimerRelative, + EFI_TIMER_PERIOD_MILLISECONDS (Timeout) + ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto DONE; } @@ -479,7 +475,7 @@ XhcWaitOpRegBit ( } gBS->Stall (XHC_1_MICROSECOND); - } while (EFI_ERROR(gBS->CheckEvent (TimeoutEvent))); + } while (EFI_ERROR (gBS->CheckEvent (TimeoutEvent))); Status = EFI_TIMEOUT; @@ -499,10 +495,10 @@ DONE: **/ VOID XhcSetBiosOwnership ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { - UINT32 Buffer; + UINT32 Buffer; if (Xhc->UsbLegSupOffset == 0xFFFFFFFF) { return; @@ -523,10 +519,10 @@ XhcSetBiosOwnership ( **/ VOID XhcClearBiosOwnership ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { - UINT32 Buffer; + UINT32 Buffer; if (Xhc->UsbLegSupOffset == 0xFFFFFFFF) { return; @@ -550,13 +546,13 @@ XhcClearBiosOwnership ( **/ UINT32 XhcGetCapabilityAddr ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 CapId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 CapId ) { - UINT32 ExtCapOffset; - UINT8 NextExtCapReg; - UINT32 Data; + UINT32 ExtCapOffset; + UINT8 NextExtCapReg; + UINT32 Data; ExtCapOffset = 0; @@ -568,6 +564,7 @@ XhcGetCapabilityAddr ( if ((Data & 0xFF) == CapId) { return ExtCapOffset; } + // // If not, then traverse all of the ext capability registers till finding out it. // @@ -589,13 +586,12 @@ XhcGetCapabilityAddr ( **/ BOOLEAN XhcIsHalt ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { return XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT); } - /** Whether system error occurred. @@ -607,7 +603,7 @@ XhcIsHalt ( **/ BOOLEAN XhcIsSysError ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { return XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HSE); @@ -627,11 +623,11 @@ XhcSetHsee ( IN USB_XHCI_INSTANCE *Xhc ) { - EFI_STATUS Status; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT16 XhciCmd; + EFI_STATUS Status; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT16 XhciCmd; - PciIo = Xhc->PciIo; + PciIo = Xhc->PciIo; Status = PciIo->Pci.Read ( PciIo, EfiPciIoWidthUint16, @@ -658,11 +654,11 @@ XhcSetHsee ( **/ EFI_STATUS XhcResetHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EFI_SUCCESS; @@ -679,7 +675,8 @@ XhcResetHC ( } if ((Xhc->DebugCapSupOffset == 0xFFFFFFFF) || ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset) & 0xFF) != XHC_CAP_USB_DEBUG) || - ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset + XHC_DC_DCCTRL) & BIT0) == 0)) { + ((XhcReadExtCapReg (Xhc, Xhc->DebugCapSupOffset + XHC_DC_DCCTRL) & BIT0) == 0)) + { XhcSetOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RESET); // // Some XHCI host controllers require to have extra 1ms delay before accessing any MMIO register during reset. @@ -701,7 +698,6 @@ XhcResetHC ( return Status; } - /** Halt the XHCI host controller. @@ -714,18 +710,17 @@ XhcResetHC ( **/ EFI_STATUS XhcHaltHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; XhcClearOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RUN); Status = XhcWaitOpRegBit (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT, TRUE, Timeout); return Status; } - /** Set the XHCI host controller to run. @@ -738,11 +733,11 @@ XhcHaltHC ( **/ EFI_STATUS XhcRunHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; XhcSetOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RUN); Status = XhcWaitOpRegBit (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT, FALSE, Timeout); diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h index cc5c1bf09a..4950eed272 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.h @@ -10,124 +10,124 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_XHCI_REG_H_ #define _EFI_XHCI_REG_H_ -#define PCI_IF_XHCI 0x30 +#define PCI_IF_XHCI 0x30 // // PCI Configuration Registers // -#define XHC_BAR_INDEX 0x00 +#define XHC_BAR_INDEX 0x00 -#define XHC_PCI_BAR_OFFSET 0x10 // Memory Bar Register Offset -#define XHC_PCI_BAR_MASK 0xFFFF // Memory Base Address Mask +#define XHC_PCI_BAR_OFFSET 0x10 // Memory Bar Register Offset +#define XHC_PCI_BAR_MASK 0xFFFF // Memory Base Address Mask -#define XHC_PCI_SBRN_OFFSET 0x60 // Serial Bus Release Number Register Offset +#define XHC_PCI_SBRN_OFFSET 0x60 // Serial Bus Release Number Register Offset -#define USB_HUB_CLASS_CODE 0x09 -#define USB_HUB_SUBCLASS_CODE 0x00 +#define USB_HUB_CLASS_CODE 0x09 +#define USB_HUB_SUBCLASS_CODE 0x00 -#define XHC_CAP_USB_LEGACY 0x01 -#define XHC_CAP_USB_DEBUG 0x0A +#define XHC_CAP_USB_LEGACY 0x01 +#define XHC_CAP_USB_DEBUG 0x0A -//============================================// +// ============================================// // XHCI register offset // -//============================================// +// ============================================// // // Capability registers offset // -#define XHC_CAPLENGTH_OFFSET 0x00 // Capability register length offset -#define XHC_HCIVERSION_OFFSET 0x02 // Interface Version Number 02-03h -#define XHC_HCSPARAMS1_OFFSET 0x04 // Structural Parameters 1 -#define XHC_HCSPARAMS2_OFFSET 0x08 // Structural Parameters 2 -#define XHC_HCSPARAMS3_OFFSET 0x0c // Structural Parameters 3 -#define XHC_HCCPARAMS_OFFSET 0x10 // Capability Parameters -#define XHC_DBOFF_OFFSET 0x14 // Doorbell Offset -#define XHC_RTSOFF_OFFSET 0x18 // Runtime Register Space Offset +#define XHC_CAPLENGTH_OFFSET 0x00 // Capability register length offset +#define XHC_HCIVERSION_OFFSET 0x02 // Interface Version Number 02-03h +#define XHC_HCSPARAMS1_OFFSET 0x04 // Structural Parameters 1 +#define XHC_HCSPARAMS2_OFFSET 0x08 // Structural Parameters 2 +#define XHC_HCSPARAMS3_OFFSET 0x0c // Structural Parameters 3 +#define XHC_HCCPARAMS_OFFSET 0x10 // Capability Parameters +#define XHC_DBOFF_OFFSET 0x14 // Doorbell Offset +#define XHC_RTSOFF_OFFSET 0x18 // Runtime Register Space Offset // // Operational registers offset // -#define XHC_USBCMD_OFFSET 0x0000 // USB Command Register Offset -#define XHC_USBSTS_OFFSET 0x0004 // USB Status Register Offset -#define XHC_PAGESIZE_OFFSET 0x0008 // USB Page Size Register Offset -#define XHC_DNCTRL_OFFSET 0x0014 // Device Notification Control Register Offset -#define XHC_CRCR_OFFSET 0x0018 // Command Ring Control Register Offset -#define XHC_DCBAAP_OFFSET 0x0030 // Device Context Base Address Array Pointer Register Offset -#define XHC_CONFIG_OFFSET 0x0038 // Configure Register Offset -#define XHC_PORTSC_OFFSET 0x0400 // Port Status and Control Register Offset +#define XHC_USBCMD_OFFSET 0x0000 // USB Command Register Offset +#define XHC_USBSTS_OFFSET 0x0004 // USB Status Register Offset +#define XHC_PAGESIZE_OFFSET 0x0008 // USB Page Size Register Offset +#define XHC_DNCTRL_OFFSET 0x0014 // Device Notification Control Register Offset +#define XHC_CRCR_OFFSET 0x0018 // Command Ring Control Register Offset +#define XHC_DCBAAP_OFFSET 0x0030 // Device Context Base Address Array Pointer Register Offset +#define XHC_CONFIG_OFFSET 0x0038 // Configure Register Offset +#define XHC_PORTSC_OFFSET 0x0400 // Port Status and Control Register Offset // // Runtime registers offset // -#define XHC_MFINDEX_OFFSET 0x00 // Microframe Index Register Offset -#define XHC_IMAN_OFFSET 0x20 // Interrupter X Management Register Offset -#define XHC_IMOD_OFFSET 0x24 // Interrupter X Moderation Register Offset -#define XHC_ERSTSZ_OFFSET 0x28 // Event Ring Segment Table Size Register Offset -#define XHC_ERSTBA_OFFSET 0x30 // Event Ring Segment Table Base Address Register Offset -#define XHC_ERDP_OFFSET 0x38 // Event Ring Dequeue Pointer Register Offset +#define XHC_MFINDEX_OFFSET 0x00 // Microframe Index Register Offset +#define XHC_IMAN_OFFSET 0x20 // Interrupter X Management Register Offset +#define XHC_IMOD_OFFSET 0x24 // Interrupter X Moderation Register Offset +#define XHC_ERSTSZ_OFFSET 0x28 // Event Ring Segment Table Size Register Offset +#define XHC_ERSTBA_OFFSET 0x30 // Event Ring Segment Table Base Address Register Offset +#define XHC_ERDP_OFFSET 0x38 // Event Ring Dequeue Pointer Register Offset // // Debug registers offset // -#define XHC_DC_DCCTRL 0x20 +#define XHC_DC_DCCTRL 0x20 -#define USBLEGSP_BIOS_SEMAPHORE BIT16 // HC BIOS Owned Semaphore -#define USBLEGSP_OS_SEMAPHORE BIT24 // HC OS Owned Semaphore +#define USBLEGSP_BIOS_SEMAPHORE BIT16 // HC BIOS Owned Semaphore +#define USBLEGSP_OS_SEMAPHORE BIT24 // HC OS Owned Semaphore #pragma pack (1) typedef struct { - UINT8 MaxSlots; // Number of Device Slots - UINT16 MaxIntrs:11; // Number of Interrupters - UINT16 Rsvd:5; - UINT8 MaxPorts; // Number of Ports + UINT8 MaxSlots; // Number of Device Slots + UINT16 MaxIntrs : 11; // Number of Interrupters + UINT16 Rsvd : 5; + UINT8 MaxPorts; // Number of Ports } HCSPARAMS1; // // Structural Parameters 1 Register Bitmap Definition // typedef union { - UINT32 Dword; - HCSPARAMS1 Data; + UINT32 Dword; + HCSPARAMS1 Data; } XHC_HCSPARAMS1; typedef struct { - UINT32 Ist:4; // Isochronous Scheduling Threshold - UINT32 Erst:4; // Event Ring Segment Table Max - UINT32 Rsvd:13; - UINT32 ScratchBufHi:5; // Max Scratchpad Buffers Hi - UINT32 Spr:1; // Scratchpad Restore - UINT32 ScratchBufLo:5; // Max Scratchpad Buffers Lo + UINT32 Ist : 4; // Isochronous Scheduling Threshold + UINT32 Erst : 4; // Event Ring Segment Table Max + UINT32 Rsvd : 13; + UINT32 ScratchBufHi : 5; // Max Scratchpad Buffers Hi + UINT32 Spr : 1; // Scratchpad Restore + UINT32 ScratchBufLo : 5; // Max Scratchpad Buffers Lo } HCSPARAMS2; // // Structural Parameters 2 Register Bitmap Definition // typedef union { - UINT32 Dword; - HCSPARAMS2 Data; + UINT32 Dword; + HCSPARAMS2 Data; } XHC_HCSPARAMS2; typedef struct { - UINT16 Ac64:1; // 64-bit Addressing Capability - UINT16 Bnc:1; // BW Negotiation Capability - UINT16 Csz:1; // Context Size - UINT16 Ppc:1; // Port Power Control - UINT16 Pind:1; // Port Indicators - UINT16 Lhrc:1; // Light HC Reset Capability - UINT16 Ltc:1; // Latency Tolerance Messaging Capability - UINT16 Nss:1; // No Secondary SID Support - UINT16 Pae:1; // Parse All Event Data - UINT16 Rsvd:3; - UINT16 MaxPsaSize:4; // Maximum Primary Stream Array Size - UINT16 ExtCapReg; // xHCI Extended Capabilities Pointer + UINT16 Ac64 : 1; // 64-bit Addressing Capability + UINT16 Bnc : 1; // BW Negotiation Capability + UINT16 Csz : 1; // Context Size + UINT16 Ppc : 1; // Port Power Control + UINT16 Pind : 1; // Port Indicators + UINT16 Lhrc : 1; // Light HC Reset Capability + UINT16 Ltc : 1; // Latency Tolerance Messaging Capability + UINT16 Nss : 1; // No Secondary SID Support + UINT16 Pae : 1; // Parse All Event Data + UINT16 Rsvd : 3; + UINT16 MaxPsaSize : 4; // Maximum Primary Stream Array Size + UINT16 ExtCapReg; // xHCI Extended Capabilities Pointer } HCCPARAMS; // // Capability Parameters Register Bitmap Definition // typedef union { - UINT32 Dword; - HCCPARAMS Data; + UINT32 Dword; + HCCPARAMS Data; } XHC_HCCPARAMS; #pragma pack () @@ -135,62 +135,62 @@ typedef union { // // Register Bit Definition // -#define XHC_USBCMD_RUN BIT0 // Run/Stop -#define XHC_USBCMD_RESET BIT1 // Host Controller Reset -#define XHC_USBCMD_INTE BIT2 // Interrupter Enable -#define XHC_USBCMD_HSEE BIT3 // Host System Error Enable - -#define XHC_USBSTS_HALT BIT0 // Host Controller Halted -#define XHC_USBSTS_HSE BIT2 // Host System Error -#define XHC_USBSTS_EINT BIT3 // Event Interrupt -#define XHC_USBSTS_PCD BIT4 // Port Change Detect -#define XHC_USBSTS_SSS BIT8 // Save State Status -#define XHC_USBSTS_RSS BIT9 // Restore State Status -#define XHC_USBSTS_SRE BIT10 // Save/Restore Error -#define XHC_USBSTS_CNR BIT11 // Host Controller Not Ready -#define XHC_USBSTS_HCE BIT12 // Host Controller Error - -#define XHC_PAGESIZE_MASK 0xFFFF // Page Size - -#define XHC_CRCR_RCS BIT0 // Ring Cycle State -#define XHC_CRCR_CS BIT1 // Command Stop -#define XHC_CRCR_CA BIT2 // Command Abort -#define XHC_CRCR_CRR BIT3 // Command Ring Running - -#define XHC_CONFIG_MASK 0xFF // Command Ring Running - -#define XHC_PORTSC_CCS BIT0 // Current Connect Status -#define XHC_PORTSC_PED BIT1 // Port Enabled/Disabled -#define XHC_PORTSC_OCA BIT3 // Over-current Active -#define XHC_PORTSC_RESET BIT4 // Port Reset -#define XHC_PORTSC_PLS (BIT5|BIT6|BIT7|BIT8) // Port Link State -#define XHC_PORTSC_PP BIT9 // Port Power -#define XHC_PORTSC_PS (BIT10|BIT11|BIT12|BIT13) // Port Speed -#define XHC_PORTSC_LWS BIT16 // Port Link State Write Strobe -#define XHC_PORTSC_CSC BIT17 // Connect Status Change -#define XHC_PORTSC_PEC BIT18 // Port Enabled/Disabled Change -#define XHC_PORTSC_WRC BIT19 // Warm Port Reset Change -#define XHC_PORTSC_OCC BIT20 // Over-Current Change -#define XHC_PORTSC_PRC BIT21 // Port Reset Change -#define XHC_PORTSC_PLC BIT22 // Port Link State Change -#define XHC_PORTSC_CEC BIT23 // Port Config Error Change -#define XHC_PORTSC_CAS BIT24 // Cold Attach Status - -#define XHC_HUB_PORTSC_CCS BIT0 // Hub's Current Connect Status -#define XHC_HUB_PORTSC_PED BIT1 // Hub's Port Enabled/Disabled -#define XHC_HUB_PORTSC_OCA BIT3 // Hub's Over-current Active -#define XHC_HUB_PORTSC_RESET BIT4 // Hub's Port Reset -#define XHC_HUB_PORTSC_PP BIT9 // Hub's Port Power -#define XHC_HUB_PORTSC_CSC BIT16 // Hub's Connect Status Change -#define XHC_HUB_PORTSC_PEC BIT17 // Hub's Port Enabled/Disabled Change -#define XHC_HUB_PORTSC_OCC BIT19 // Hub's Over-Current Change -#define XHC_HUB_PORTSC_PRC BIT20 // Hub's Port Reset Change -#define XHC_HUB_PORTSC_BHRC BIT21 // Hub's Port Warm Reset Change -#define XHC_IMAN_IP BIT0 // Interrupt Pending -#define XHC_IMAN_IE BIT1 // Interrupt Enable - -#define XHC_IMODI_MASK 0x0000FFFF // Interrupt Moderation Interval -#define XHC_IMODC_MASK 0xFFFF0000 // Interrupt Moderation Counter +#define XHC_USBCMD_RUN BIT0 // Run/Stop +#define XHC_USBCMD_RESET BIT1 // Host Controller Reset +#define XHC_USBCMD_INTE BIT2 // Interrupter Enable +#define XHC_USBCMD_HSEE BIT3 // Host System Error Enable + +#define XHC_USBSTS_HALT BIT0 // Host Controller Halted +#define XHC_USBSTS_HSE BIT2 // Host System Error +#define XHC_USBSTS_EINT BIT3 // Event Interrupt +#define XHC_USBSTS_PCD BIT4 // Port Change Detect +#define XHC_USBSTS_SSS BIT8 // Save State Status +#define XHC_USBSTS_RSS BIT9 // Restore State Status +#define XHC_USBSTS_SRE BIT10 // Save/Restore Error +#define XHC_USBSTS_CNR BIT11 // Host Controller Not Ready +#define XHC_USBSTS_HCE BIT12 // Host Controller Error + +#define XHC_PAGESIZE_MASK 0xFFFF // Page Size + +#define XHC_CRCR_RCS BIT0 // Ring Cycle State +#define XHC_CRCR_CS BIT1 // Command Stop +#define XHC_CRCR_CA BIT2 // Command Abort +#define XHC_CRCR_CRR BIT3 // Command Ring Running + +#define XHC_CONFIG_MASK 0xFF // Command Ring Running + +#define XHC_PORTSC_CCS BIT0 // Current Connect Status +#define XHC_PORTSC_PED BIT1 // Port Enabled/Disabled +#define XHC_PORTSC_OCA BIT3 // Over-current Active +#define XHC_PORTSC_RESET BIT4 // Port Reset +#define XHC_PORTSC_PLS (BIT5|BIT6|BIT7|BIT8) // Port Link State +#define XHC_PORTSC_PP BIT9 // Port Power +#define XHC_PORTSC_PS (BIT10|BIT11|BIT12|BIT13) // Port Speed +#define XHC_PORTSC_LWS BIT16 // Port Link State Write Strobe +#define XHC_PORTSC_CSC BIT17 // Connect Status Change +#define XHC_PORTSC_PEC BIT18 // Port Enabled/Disabled Change +#define XHC_PORTSC_WRC BIT19 // Warm Port Reset Change +#define XHC_PORTSC_OCC BIT20 // Over-Current Change +#define XHC_PORTSC_PRC BIT21 // Port Reset Change +#define XHC_PORTSC_PLC BIT22 // Port Link State Change +#define XHC_PORTSC_CEC BIT23 // Port Config Error Change +#define XHC_PORTSC_CAS BIT24 // Cold Attach Status + +#define XHC_HUB_PORTSC_CCS BIT0 // Hub's Current Connect Status +#define XHC_HUB_PORTSC_PED BIT1 // Hub's Port Enabled/Disabled +#define XHC_HUB_PORTSC_OCA BIT3 // Hub's Over-current Active +#define XHC_HUB_PORTSC_RESET BIT4 // Hub's Port Reset +#define XHC_HUB_PORTSC_PP BIT9 // Hub's Port Power +#define XHC_HUB_PORTSC_CSC BIT16 // Hub's Connect Status Change +#define XHC_HUB_PORTSC_PEC BIT17 // Hub's Port Enabled/Disabled Change +#define XHC_HUB_PORTSC_OCC BIT19 // Hub's Over-Current Change +#define XHC_HUB_PORTSC_PRC BIT20 // Hub's Port Reset Change +#define XHC_HUB_PORTSC_BHRC BIT21 // Hub's Port Warm Reset Change +#define XHC_IMAN_IP BIT0 // Interrupt Pending +#define XHC_IMAN_IE BIT1 // Interrupt Enable + +#define XHC_IMODI_MASK 0x0000FFFF // Interrupt Moderation Interval +#define XHC_IMODC_MASK 0xFFFF0000 // Interrupt Moderation Counter // // Hub Class Feature Selector for Clear Port Feature Request @@ -198,8 +198,8 @@ typedef union { // For more details, Please refer to USB 3.0 Spec Table 10-7. // typedef enum { - Usb3PortBHPortReset = 28, - Usb3PortBHPortResetChange = 29 + Usb3PortBHPortReset = 28, + Usb3PortBHPortResetChange = 29 } XHC_PORT_FEATURE; // @@ -207,16 +207,16 @@ typedef enum { // UEFI's port states. // typedef struct { - UINT32 HwState; - UINT16 UefiState; + UINT32 HwState; + UINT16 UefiState; } USB_PORT_STATE_MAP; // // Structure to map the hardware port states to feature selector for clear port feature request. // typedef struct { - UINT32 HwState; - UINT16 Selector; + UINT32 HwState; + UINT16 Selector; } USB_CLEAR_PORT_MAP; /** @@ -231,8 +231,8 @@ typedef struct { **/ UINT8 XhcReadCapReg8 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -247,8 +247,8 @@ XhcReadCapReg8 ( **/ UINT32 XhcReadCapReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -263,8 +263,8 @@ XhcReadCapReg ( **/ UINT32 XhcReadOpReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -277,12 +277,11 @@ XhcReadOpReg ( **/ VOID XhcWriteOpReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); - /** Read XHCI runtime register. @@ -294,8 +293,8 @@ XhcWriteOpReg ( **/ UINT32 XhcReadRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -308,12 +307,11 @@ XhcReadRuntimeReg ( **/ VOID XhcWriteRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); - /** Write the data to the XHCI door bell register. @@ -324,9 +322,9 @@ XhcWriteRuntimeReg ( **/ VOID XhcWriteDoorBellReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -339,9 +337,9 @@ XhcWriteDoorBellReg ( **/ VOID XhcSetOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -354,9 +352,9 @@ XhcSetOpRegBit ( **/ VOID XhcClearOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -375,11 +373,11 @@ XhcClearOpRegBit ( **/ EFI_STATUS XhcWaitOpRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ); /** @@ -393,8 +391,8 @@ XhcWaitOpRegBit ( **/ UINT32 XhcReadRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -407,9 +405,9 @@ XhcReadRuntimeReg ( **/ VOID XhcWriteRuntimeReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -422,9 +420,9 @@ XhcWriteRuntimeReg ( **/ VOID XhcSetRuntimeRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -437,9 +435,9 @@ XhcSetRuntimeRegBit ( **/ VOID XhcClearRuntimeRegBit ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -453,8 +451,8 @@ XhcClearRuntimeRegBit ( **/ UINT32 XhcReadExtCapReg ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Offset + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Offset ); /** @@ -468,7 +466,7 @@ XhcReadExtCapReg ( **/ BOOLEAN XhcIsHalt ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -482,7 +480,7 @@ XhcIsHalt ( **/ BOOLEAN XhcIsSysError ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -497,8 +495,8 @@ XhcIsSysError ( **/ EFI_STATUS XhcResetHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ); /** @@ -513,8 +511,8 @@ XhcResetHC ( **/ EFI_STATUS XhcHaltHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ); /** @@ -529,8 +527,8 @@ XhcHaltHC ( **/ EFI_STATUS XhcRunHC ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT32 Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN UINT32 Timeout ); /** @@ -544,8 +542,8 @@ XhcRunHC ( **/ UINT32 XhcGetCapabilityAddr ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 CapId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 CapId ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c index 92f63c29fc..c2906e06fd 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c @@ -19,25 +19,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @return Created URB or NULL. **/ -URB* +URB * XhcCreateCmdTrb ( IN USB_XHCI_INSTANCE *Xhc, IN TRB_TEMPLATE *CmdTrb ) { - URB *Urb; + URB *Urb; Urb = AllocateZeroPool (sizeof (URB)); if (Urb == NULL) { return NULL; } - Urb->Signature = XHC_URB_SIG; + Urb->Signature = XHC_URB_SIG; - Urb->Ring = &Xhc->CmdRing; + Urb->Ring = &Xhc->CmdRing; XhcSyncTrsRing (Xhc, Urb->Ring); - Urb->TrbNum = 1; - Urb->TrbStart = Urb->Ring->RingEnqueue; + Urb->TrbNum = 1; + Urb->TrbStart = Urb->Ring->RingEnqueue; CopyMem (Urb->TrbStart, CmdTrb, sizeof (TRB_TEMPLATE)); Urb->TrbStart->CycleBit = Urb->Ring->RingPCS & BIT0; Urb->TrbEnd = Urb->TrbStart; @@ -63,14 +63,14 @@ XhcCreateCmdTrb ( EFI_STATUS EFIAPI XhcCmdTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN TRB_TEMPLATE *CmdTrb, - IN UINTN Timeout, - OUT TRB_TEMPLATE **EvtTrb + IN USB_XHCI_INSTANCE *Xhc, + IN TRB_TEMPLATE *CmdTrb, + IN UINTN Timeout, + OUT TRB_TEMPLATE **EvtTrb ) { - EFI_STATUS Status; - URB *Urb; + EFI_STATUS Status; + URB *Urb; // // Validate the parameters @@ -128,24 +128,24 @@ ON_EXIT: @return Created URB or NULL **/ -URB* +URB * XhcCreateUrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ) { - USB_ENDPOINT *Ep; - EFI_STATUS Status; - URB *Urb; + USB_ENDPOINT *Ep; + EFI_STATUS Status; + URB *Urb; Urb = AllocateZeroPool (sizeof (URB)); if (Urb == NULL) { @@ -189,8 +189,8 @@ XhcCreateUrb ( **/ VOID XhcFreeUrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { if ((Xhc == NULL) || (Urb == NULL)) { @@ -215,23 +215,23 @@ XhcFreeUrb ( **/ EFI_STATUS XhcCreateTransferTrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - VOID *OutputContext; - TRANSFER_RING *EPRing; - UINT8 EPType; - UINT8 SlotId; - UINT8 Dci; - TRB *TrbStart; - UINTN TotalLen; - UINTN Len; - UINTN TrbNum; - EFI_PCI_IO_PROTOCOL_OPERATION MapOp; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *Map; - EFI_STATUS Status; + VOID *OutputContext; + TRANSFER_RING *EPRing; + UINT8 EPType; + UINT8 SlotId; + UINT8 Dci; + TRB *TrbStart; + UINTN TotalLen; + UINTN Len; + UINTN TrbNum; + EFI_PCI_IO_PROTOCOL_OPERATION MapOp; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *Map; + EFI_STATUS Status; SlotId = XhcBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { @@ -244,37 +244,37 @@ XhcCreateTransferTrb ( Urb->Completed = 0; Urb->Result = EFI_USB_NOERROR; - Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); + Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); ASSERT (Dci < 32); - EPRing = (TRANSFER_RING *)(UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]; - Urb->Ring = EPRing; + EPRing = (TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]; + Urb->Ring = EPRing; OutputContext = Xhc->UsbDevContext[SlotId].OutputContext; if (Xhc->HcCParams.Data.Csz == 0) { - EPType = (UINT8) ((DEVICE_CONTEXT *)OutputContext)->EP[Dci-1].EPType; + EPType = (UINT8)((DEVICE_CONTEXT *)OutputContext)->EP[Dci-1].EPType; } else { - EPType = (UINT8) ((DEVICE_CONTEXT_64 *)OutputContext)->EP[Dci-1].EPType; + EPType = (UINT8)((DEVICE_CONTEXT_64 *)OutputContext)->EP[Dci-1].EPType; } // // No need to remap. // if ((Urb->Data != NULL) && (Urb->DataMap == NULL)) { - if (((UINT8) (Urb->Ep.Direction)) == EfiUsbDataIn) { + if (((UINT8)(Urb->Ep.Direction)) == EfiUsbDataIn) { MapOp = EfiPciIoOperationBusMasterWrite; } else { MapOp = EfiPciIoOperationBusMasterRead; } - Len = Urb->DataLen; - Status = Xhc->PciIo->Map (Xhc->PciIo, MapOp, Urb->Data, &Len, &PhyAddr, &Map); + Len = Urb->DataLen; + Status = Xhc->PciIo->Map (Xhc->PciIo, MapOp, Urb->Data, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != Urb->DataLen)) { DEBUG ((DEBUG_ERROR, "XhcCreateTransferTrb: Fail to map Urb->Data.\n")); return EFI_OUT_OF_RESOURCES; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; } // @@ -287,7 +287,7 @@ XhcCreateTransferTrb ( // // For control transfer, create SETUP_STAGE_TRB first. // - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; TrbStart->TrbCtrSetup.bmRequestType = Urb->Request->RequestType; TrbStart->TrbCtrSetup.bRequest = Urb->Request->Request; TrbStart->TrbCtrSetup.wValue = Urb->Request->Value; @@ -310,6 +310,7 @@ XhcCreateTransferTrb ( } else { TrbStart->TrbCtrSetup.TRT = 0; } + // // Update the cycle bit // @@ -321,10 +322,10 @@ XhcCreateTransferTrb ( // if (Urb->DataLen > 0) { XhcSyncTrsRing (Xhc, EPRing); - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; - TrbStart->TrbCtrData.TRBPtrLo = XHC_LOW_32BIT(Urb->DataPhy); - TrbStart->TrbCtrData.TRBPtrHi = XHC_HIGH_32BIT(Urb->DataPhy); - TrbStart->TrbCtrData.Length = (UINT32) Urb->DataLen; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart->TrbCtrData.TRBPtrLo = XHC_LOW_32BIT (Urb->DataPhy); + TrbStart->TrbCtrData.TRBPtrHi = XHC_HIGH_32BIT (Urb->DataPhy); + TrbStart->TrbCtrData.Length = (UINT32)Urb->DataLen; TrbStart->TrbCtrData.TDSize = 0; TrbStart->TrbCtrData.IntTarget = 0; TrbStart->TrbCtrData.ISP = 1; @@ -339,18 +340,20 @@ XhcCreateTransferTrb ( } else { TrbStart->TrbCtrData.DIR = 0; } + // // Update the cycle bit // TrbStart->TrbCtrData.CycleBit = EPRing->RingPCS & BIT0; Urb->TrbNum++; } + // // For control transfer, create STATUS_STAGE_TRB. // Get the pointer to next TRB for status stage use // XhcSyncTrsRing (Xhc, EPRing); - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; TrbStart->TrbCtrStatus.IntTarget = 0; TrbStart->TrbCtrStatus.IOC = 1; TrbStart->TrbCtrStatus.CH = 0; @@ -362,6 +365,7 @@ XhcCreateTransferTrb ( } else { TrbStart->TrbCtrStatus.DIR = 0; } + // // Update the cycle bit // @@ -387,10 +391,11 @@ XhcCreateTransferTrb ( } else { Len = 0x10000; } - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; - TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.Length = (UINT32) Len; + + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.Length = (UINT32)Len; TrbStart->TrbNormal.TDSize = 0; TrbStart->TrbNormal.IntTarget = 0; TrbStart->TrbNormal.ISP = 1; @@ -422,10 +427,11 @@ XhcCreateTransferTrb ( } else { Len = 0x10000; } - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; - TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.Length = (UINT32) Len; + + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.Length = (UINT32)Len; TrbStart->TrbNormal.TDSize = 0; TrbStart->TrbNormal.IntTarget = 0; TrbStart->TrbNormal.ISP = 1; @@ -446,7 +452,7 @@ XhcCreateTransferTrb ( break; default: - DEBUG ((DEBUG_INFO, "Not supported EPType 0x%x!\n",EPType)); + DEBUG ((DEBUG_INFO, "Not supported EPType 0x%x!\n", EPType)); ASSERT (FALSE); break; } @@ -454,7 +460,6 @@ XhcCreateTransferTrb ( return EFI_SUCCESS; } - /** Initialize the XHCI host controller for schedule. @@ -463,7 +468,7 @@ XhcCreateTransferTrb ( **/ VOID XhcInitSched ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { VOID *Dcbaa; @@ -500,8 +505,8 @@ XhcInitSched ( // The Device Context Base Address Array shall contain MaxSlotsEn + 1 entries. // Software shall set Device Context Base Address Array entries for unallocated Device Slots to '0'. // - Entries = (Xhc->MaxSlotsEn + 1) * sizeof(UINT64); - Dcbaa = UsbHcAllocateMem (Xhc->MemPool, Entries); + Entries = (Xhc->MaxSlotsEn + 1) * sizeof (UINT64); + Dcbaa = UsbHcAllocateMem (Xhc->MemPool, Entries); ASSERT (Dcbaa != NULL); ZeroMem (Dcbaa, Entries); @@ -529,14 +534,14 @@ XhcInitSched ( Xhc->ScratchEntry = ScratchEntry; ScratchPhy = 0; - Status = UsbHcAllocateAlignedPages ( - Xhc->PciIo, - EFI_SIZE_TO_PAGES (MaxScratchpadBufs * sizeof (UINT64)), - Xhc->PageSize, - (VOID **) &ScratchBuf, - &ScratchPhy, - &Xhc->ScratchMap - ); + Status = UsbHcAllocateAlignedPages ( + Xhc->PciIo, + EFI_SIZE_TO_PAGES (MaxScratchpadBufs * sizeof (UINT64)), + Xhc->PageSize, + (VOID **)&ScratchBuf, + &ScratchPhy, + &Xhc->ScratchMap + ); ASSERT_EFI_ERROR (Status); ZeroMem (ScratchBuf, MaxScratchpadBufs * sizeof (UINT64)); @@ -547,14 +552,14 @@ XhcInitSched ( // for (Index = 0; Index < MaxScratchpadBufs; Index++) { ScratchEntryPhy = 0; - Status = UsbHcAllocateAlignedPages ( - Xhc->PciIo, - EFI_SIZE_TO_PAGES (Xhc->PageSize), - Xhc->PageSize, - (VOID **) &ScratchEntry[Index], - &ScratchEntryPhy, - (VOID **) &ScratchEntryMap[Index] - ); + Status = UsbHcAllocateAlignedPages ( + Xhc->PciIo, + EFI_SIZE_TO_PAGES (Xhc->PageSize), + Xhc->PageSize, + (VOID **)&ScratchEntry[Index], + &ScratchEntryPhy, + (VOID **)&ScratchEntryMap[Index] + ); ASSERT_EFI_ERROR (Status); ZeroMem ((VOID *)(UINTN)ScratchEntry[Index], Xhc->PageSize); // @@ -562,11 +567,12 @@ XhcInitSched ( // *ScratchBuf++ = ScratchEntryPhy; } + // // The Scratchpad Buffer Array contains pointers to the Scratchpad Buffers. Entry 0 of the // Device Context Base Address Array points to the Scratchpad Buffer Array. // - *(UINT64 *)Dcbaa = (UINT64)(UINTN) ScratchPhy; + *(UINT64 *)Dcbaa = (UINT64)(UINTN)ScratchPhy; } // @@ -579,7 +585,7 @@ XhcInitSched ( // So divide it to two 32-bytes width register access. // DcbaaPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Dcbaa, Entries); - XhcWriteOpReg (Xhc, XHC_DCBAAP_OFFSET, XHC_LOW_32BIT(DcbaaPhy)); + XhcWriteOpReg (Xhc, XHC_DCBAAP_OFFSET, XHC_LOW_32BIT (DcbaaPhy)); XhcWriteOpReg (Xhc, XHC_DCBAAP_OFFSET + 4, XHC_HIGH_32BIT (DcbaaPhy)); DEBUG ((DEBUG_INFO, "XhcInitSched:DCBAA=0x%x\n", (UINT64)(UINTN)Xhc->DCBAA)); @@ -596,15 +602,15 @@ XhcInitSched ( // Transfer Ring it checks for a Cycle bit transition. If a transition detected, the ring is empty. // So we set RCS as inverted PCS init value to let Command Ring empty // - CmdRing = (UINT64)(UINTN)Xhc->CmdRing.RingSeg0; - CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, (VOID *)(UINTN) CmdRing, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER); + CmdRing = (UINT64)(UINTN)Xhc->CmdRing.RingSeg0; + CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, (VOID *)(UINTN)CmdRing, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER); ASSERT ((CmdRingPhy & 0x3F) == 0); CmdRingPhy |= XHC_CRCR_RCS; // // Some 3rd party XHCI external cards don't support single 64-bytes width register access, // So divide it to two 32-bytes width register access. // - XhcWriteOpReg (Xhc, XHC_CRCR_OFFSET, XHC_LOW_32BIT(CmdRingPhy)); + XhcWriteOpReg (Xhc, XHC_CRCR_OFFSET, XHC_LOW_32BIT (CmdRingPhy)); XhcWriteOpReg (Xhc, XHC_CRCR_OFFSET + 4, XHC_HIGH_32BIT (CmdRingPhy)); // @@ -621,9 +627,13 @@ XhcInitSched ( // Allocate EventRing for Cmd, Ctrl, Bulk, Interrupt, AsynInterrupt transfer // CreateEventRing (Xhc, &Xhc->EventRing); - DEBUG ((DEBUG_INFO, "XhcInitSched: Created CMD ring [%p~%p) EVENT ring [%p~%p)\n", - Xhc->CmdRing.RingSeg0, (UINTN)Xhc->CmdRing.RingSeg0 + sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER, - Xhc->EventRing.EventRingSeg0, (UINTN)Xhc->EventRing.EventRingSeg0 + sizeof (TRB_TEMPLATE) * EVENT_RING_TRB_NUMBER + DEBUG (( + DEBUG_INFO, + "XhcInitSched: Created CMD ring [%p~%p) EVENT ring [%p~%p)\n", + Xhc->CmdRing.RingSeg0, + (UINTN)Xhc->CmdRing.RingSeg0 + sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER, + Xhc->EventRing.EventRingSeg0, + (UINTN)Xhc->EventRing.EventRingSeg0 + sizeof (TRB_TEMPLATE) * EVENT_RING_TRB_NUMBER )); } @@ -644,19 +654,20 @@ XhcInitSched ( EFI_STATUS EFIAPI XhcRecoverHaltedEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; - UINT8 Dci; - UINT8 SlotId; + EFI_STATUS Status; + UINT8 Dci; + UINT8 SlotId; Status = EFI_SUCCESS; SlotId = XhcBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { return EFI_DEVICE_ERROR; } + Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); ASSERT (Dci < 32); @@ -665,8 +676,8 @@ XhcRecoverHaltedEndpoint ( // // 1) Send Reset endpoint command to transit from halt to stop state // - Status = XhcResetEndpoint(Xhc, SlotId, Dci); - if (EFI_ERROR(Status)) { + Status = XhcResetEndpoint (Xhc, SlotId, Dci); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcRecoverHaltedEndpoint: Reset Endpoint Failed, Status = %r\n", Status)); goto Done; } @@ -674,8 +685,8 @@ XhcRecoverHaltedEndpoint ( // // 2)Set dequeue pointer // - Status = XhcSetTrDequeuePointer(Xhc, SlotId, Dci, Urb); - if (EFI_ERROR(Status)) { + Status = XhcSetTrDequeuePointer (Xhc, SlotId, Dci, Urb); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcRecoverHaltedEndpoint: Set Transfer Ring Dequeue Pointer Failed, Status = %r\n", Status)); goto Done; } @@ -706,19 +717,20 @@ Done: EFI_STATUS EFIAPI XhcDequeueTrbFromEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; - UINT8 Dci; - UINT8 SlotId; + EFI_STATUS Status; + UINT8 Dci; + UINT8 SlotId; Status = EFI_SUCCESS; SlotId = XhcBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { return EFI_DEVICE_ERROR; } + Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); ASSERT (Dci < 32); @@ -727,8 +739,8 @@ XhcDequeueTrbFromEndpoint ( // // 1) Send Stop endpoint command to stop xHC from executing of the TDs on the endpoint // - Status = XhcStopEndpoint(Xhc, SlotId, Dci, Urb); - if (EFI_ERROR(Status)) { + Status = XhcStopEndpoint (Xhc, SlotId, Dci, Urb); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcDequeueTrbFromEndpoint: Stop Endpoint Failed, Status = %r\n", Status)); goto Done; } @@ -736,7 +748,7 @@ XhcDequeueTrbFromEndpoint ( // // 2)Set dequeue pointer // - if (Urb->Finished && Urb->Result == EFI_USB_NOERROR) { + if (Urb->Finished && (Urb->Result == EFI_USB_NOERROR)) { // // Return Already Started to indicate the pending URB is finished. // This fixes BULK data loss when transfer is detected as timeout @@ -745,7 +757,7 @@ XhcDequeueTrbFromEndpoint ( Status = EFI_ALREADY_STARTED; DEBUG ((DEBUG_INFO, "XhcDequeueTrbFromEndpoint: Pending URB is finished: Length Actual/Expect = %d/%d!\n", Urb->Completed, Urb->DataLen)); } else { - Status = XhcSetTrDequeuePointer(Xhc, SlotId, Dci, Urb); + Status = XhcSetTrDequeuePointer (Xhc, SlotId, Dci, Urb); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcDequeueTrbFromEndpoint: Set Transfer Ring Dequeue Pointer Failed, Status = %r\n", Status)); goto Done; @@ -770,8 +782,8 @@ Done: **/ VOID CreateEventRing ( - IN USB_XHCI_INSTANCE *Xhc, - OUT EVENT_RING *EventRing + IN USB_XHCI_INSTANCE *Xhc, + OUT EVENT_RING *EventRing ) { VOID *Buf; @@ -783,15 +795,15 @@ CreateEventRing ( ASSERT (EventRing != NULL); Size = sizeof (TRB_TEMPLATE) * EVENT_RING_TRB_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); EventRing->EventRingSeg0 = Buf; EventRing->TrbNumber = EVENT_RING_TRB_NUMBER; - EventRing->EventRingDequeue = (TRB_TEMPLATE *) EventRing->EventRingSeg0; - EventRing->EventRingEnqueue = (TRB_TEMPLATE *) EventRing->EventRingSeg0; + EventRing->EventRingDequeue = (TRB_TEMPLATE *)EventRing->EventRingSeg0; + EventRing->EventRingEnqueue = (TRB_TEMPLATE *)EventRing->EventRingSeg0; DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size); @@ -802,12 +814,12 @@ CreateEventRing ( EventRing->EventRingCCS = 1; Size = sizeof (EVENT_RING_SEG_TABLE_ENTRY) * ERST_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); - ERSTBase = (EVENT_RING_SEG_TABLE_ENTRY *) Buf; + ERSTBase = (EVENT_RING_SEG_TABLE_ENTRY *)Buf; EventRing->ERSTBase = ERSTBase; ERSTBase->PtrLo = XHC_LOW_32BIT (DequeuePhy); ERSTBase->PtrHi = XHC_HIGH_32BIT (DequeuePhy); @@ -832,12 +844,12 @@ CreateEventRing ( XhcWriteRuntimeReg ( Xhc, XHC_ERDP_OFFSET, - XHC_LOW_32BIT((UINT64)(UINTN)DequeuePhy) + XHC_LOW_32BIT ((UINT64)(UINTN)DequeuePhy) ); XhcWriteRuntimeReg ( Xhc, XHC_ERDP_OFFSET + 4, - XHC_HIGH_32BIT((UINT64)(UINTN)DequeuePhy) + XHC_HIGH_32BIT ((UINT64)(UINTN)DequeuePhy) ); // // Program the Interrupter Event Ring Segment Table Base Address (ERSTBA) register(5.5.2.3.2) @@ -848,12 +860,12 @@ CreateEventRing ( XhcWriteRuntimeReg ( Xhc, XHC_ERSTBA_OFFSET, - XHC_LOW_32BIT((UINT64)(UINTN)ERSTPhy) + XHC_LOW_32BIT ((UINT64)(UINTN)ERSTPhy) ); XhcWriteRuntimeReg ( Xhc, XHC_ERSTBA_OFFSET + 4, - XHC_HIGH_32BIT((UINT64)(UINTN)ERSTPhy) + XHC_HIGH_32BIT ((UINT64)(UINTN)ERSTPhy) ); // // Need set IMAN IE bit to enble the ring interrupt @@ -871,9 +883,9 @@ CreateEventRing ( **/ VOID CreateTransferRing ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINTN TrbNum, - OUT TRANSFER_RING *TransferRing + IN USB_XHCI_INSTANCE *Xhc, + IN UINTN TrbNum, + OUT TRANSFER_RING *TransferRing ) { VOID *Buf; @@ -882,28 +894,28 @@ CreateTransferRing ( Buf = UsbHcAllocateMem (Xhc->MemPool, sizeof (TRB_TEMPLATE) * TrbNum); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, sizeof (TRB_TEMPLATE) * TrbNum); - TransferRing->RingSeg0 = Buf; - TransferRing->TrbNumber = TrbNum; - TransferRing->RingEnqueue = (TRB_TEMPLATE *) TransferRing->RingSeg0; - TransferRing->RingDequeue = (TRB_TEMPLATE *) TransferRing->RingSeg0; - TransferRing->RingPCS = 1; + TransferRing->RingSeg0 = Buf; + TransferRing->TrbNumber = TrbNum; + TransferRing->RingEnqueue = (TRB_TEMPLATE *)TransferRing->RingSeg0; + TransferRing->RingDequeue = (TRB_TEMPLATE *)TransferRing->RingSeg0; + TransferRing->RingPCS = 1; // // 4.9.2 Transfer Ring Management // To form a ring (or circular queue) a Link TRB may be inserted at the end of a ring to // point to the first TRB in the ring. // - EndTrb = (LINK_TRB *) ((UINTN)Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1)); + EndTrb = (LINK_TRB *)((UINTN)Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1)); EndTrb->Type = TRB_TYPE_LINK; - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum); EndTrb->PtrLo = XHC_LOW_32BIT (PhyAddr); EndTrb->PtrHi = XHC_HIGH_32BIT (PhyAddr); // // Toggle Cycle (TC). When set to '1', the xHC shall toggle its interpretation of the Cycle bit. // - EndTrb->TC = 1; + EndTrb->TC = 1; // // Set Cycle bit as other TRB PCS init value // @@ -920,11 +932,11 @@ CreateTransferRing ( EFI_STATUS EFIAPI XhcFreeEventRing ( - IN USB_XHCI_INSTANCE *Xhc, - IN EVENT_RING *EventRing -) + IN USB_XHCI_INSTANCE *Xhc, + IN EVENT_RING *EventRing + ) { - if(EventRing->EventRingSeg0 == NULL) { + if (EventRing->EventRingSeg0 == NULL) { return EFI_SUCCESS; } @@ -948,11 +960,11 @@ XhcFreeEventRing ( **/ VOID XhcFreeSched ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { - UINT32 Index; - UINT64 *ScratchEntry; + UINT32 Index; + UINT64 *ScratchEntry; if (Xhc->ScratchBuf != NULL) { ScratchEntry = Xhc->ScratchEntry; @@ -960,8 +972,9 @@ XhcFreeSched ( // // Free Scratchpad Buffers // - UsbHcFreeAlignedPages (Xhc->PciIo, (VOID*)(UINTN)ScratchEntry[Index], EFI_SIZE_TO_PAGES (Xhc->PageSize), (VOID *) Xhc->ScratchEntryMap[Index]); + UsbHcFreeAlignedPages (Xhc->PciIo, (VOID *)(UINTN)ScratchEntry[Index], EFI_SIZE_TO_PAGES (Xhc->PageSize), (VOID *)Xhc->ScratchEntryMap[Index]); } + // // Free Scratchpad Buffer Array // @@ -975,10 +988,10 @@ XhcFreeSched ( Xhc->CmdRing.RingSeg0 = NULL; } - XhcFreeEventRing (Xhc,&Xhc->EventRing); + XhcFreeEventRing (Xhc, &Xhc->EventRing); if (Xhc->DCBAA != NULL) { - UsbHcFreeMem (Xhc->MemPool, Xhc->DCBAA, (Xhc->MaxSlotsEn + 1) * sizeof(UINT64)); + UsbHcFreeMem (Xhc->MemPool, Xhc->DCBAA, (Xhc->MaxSlotsEn + 1) * sizeof (UINT64)); Xhc->DCBAA = NULL; } @@ -1004,30 +1017,31 @@ XhcFreeSched ( **/ BOOLEAN IsTransferRingTrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN TRB_TEMPLATE *Trb, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN TRB_TEMPLATE *Trb, + IN URB *Urb ) { - LINK_TRB *LinkTrb; - TRB_TEMPLATE *CheckedTrb; - UINTN Index; - EFI_PHYSICAL_ADDRESS PhyAddr; + LINK_TRB *LinkTrb; + TRB_TEMPLATE *CheckedTrb; + UINTN Index; + EFI_PHYSICAL_ADDRESS PhyAddr; CheckedTrb = Urb->TrbStart; for (Index = 0; Index < Urb->TrbNum; Index++) { if (Trb == CheckedTrb) { return TRUE; } + CheckedTrb++; // // If the checked TRB is the link TRB at the end of the transfer ring, // recircle it to the head of the ring. // if (CheckedTrb->Type == TRB_TYPE_LINK) { - LinkTrb = (LINK_TRB *) CheckedTrb; - PhyAddr = (EFI_PHYSICAL_ADDRESS)(LinkTrb->PtrLo | LShiftU64 ((UINT64) LinkTrb->PtrHi, 32)); - CheckedTrb = (TRB_TEMPLATE *)(UINTN) UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN) PhyAddr, sizeof (TRB_TEMPLATE)); + LinkTrb = (LINK_TRB *)CheckedTrb; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(LinkTrb->PtrLo | LShiftU64 ((UINT64)LinkTrb->PtrHi, 32)); + CheckedTrb = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE)); ASSERT (CheckedTrb == Urb->Ring->RingSeg0); } } @@ -1048,14 +1062,14 @@ IsTransferRingTrb ( **/ BOOLEAN IsAsyncIntTrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN TRB_TEMPLATE *Trb, - OUT URB **Urb + IN USB_XHCI_INSTANCE *Xhc, + IN TRB_TEMPLATE *Trb, + OUT URB **Urb ) { - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - URB *CheckedUrb; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + URB *CheckedUrb; BASE_LIST_FOR_EACH_SAFE (Entry, Next, &Xhc->AsyncIntTransfers) { CheckedUrb = EFI_LIST_CONTAINER (Entry, URB, UrbList); @@ -1068,7 +1082,6 @@ IsAsyncIntTrb ( return FALSE; } - /** Check the URB's execution result and update the URB's result accordingly. @@ -1081,21 +1094,21 @@ IsAsyncIntTrb ( **/ BOOLEAN XhcCheckUrbResult ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - EVT_TRB_TRANSFER *EvtTrb; - TRB_TEMPLATE *TRBPtr; - UINTN Index; - UINT8 TRBType; - EFI_STATUS Status; - URB *AsyncUrb; - URB *CheckedUrb; - UINT64 XhcDequeue; - UINT32 High; - UINT32 Low; - EFI_PHYSICAL_ADDRESS PhyAddr; + EVT_TRB_TRANSFER *EvtTrb; + TRB_TEMPLATE *TRBPtr; + UINTN Index; + UINT8 TRBType; + EFI_STATUS Status; + URB *AsyncUrb; + URB *CheckedUrb; + UINT64 XhcDequeue; + UINT32 High; + UINT32 Low; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT ((Xhc != NULL) && (Urb != NULL)); @@ -1136,8 +1149,8 @@ XhcCheckUrbResult ( // // Need convert pci device address to host address // - PhyAddr = (EFI_PHYSICAL_ADDRESS)(EvtTrb->TRBPtrLo | LShiftU64 ((UINT64) EvtTrb->TRBPtrHi, 32)); - TRBPtr = (TRB_TEMPLATE *)(UINTN) UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN) PhyAddr, sizeof (TRB_TEMPLATE)); + PhyAddr = (EFI_PHYSICAL_ADDRESS)(EvtTrb->TRBPtrLo | LShiftU64 ((UINT64)EvtTrb->TRBPtrHi, 32)); + TRBPtr = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE)); // // Update the status of URB including the pending URB, the URB that is currently checked, @@ -1145,7 +1158,7 @@ XhcCheckUrbResult ( // This way is used to avoid that those completed async transfer events don't get // handled in time and are flushed by newer coming events. // - if (Xhc->PendingUrb != NULL && IsTransferRingTrb (Xhc, TRBPtr, Xhc->PendingUrb)) { + if ((Xhc->PendingUrb != NULL) && IsTransferRingTrb (Xhc, TRBPtr, Xhc->PendingUrb)) { CheckedUrb = Xhc->PendingUrb; } else if (IsTransferRingTrb (Xhc, TRBPtr, Urb)) { CheckedUrb = Urb; @@ -1159,25 +1172,25 @@ XhcCheckUrbResult ( case TRB_COMPLETION_STALL_ERROR: CheckedUrb->Result |= EFI_USB_ERR_STALL; CheckedUrb->Finished = TRUE; - DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: STALL_ERROR! Completecode = %x\n",EvtTrb->Completecode)); + DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: STALL_ERROR! Completecode = %x\n", EvtTrb->Completecode)); goto EXIT; case TRB_COMPLETION_BABBLE_ERROR: CheckedUrb->Result |= EFI_USB_ERR_BABBLE; CheckedUrb->Finished = TRUE; - DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: BABBLE_ERROR! Completecode = %x\n",EvtTrb->Completecode)); + DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: BABBLE_ERROR! Completecode = %x\n", EvtTrb->Completecode)); goto EXIT; case TRB_COMPLETION_DATA_BUFFER_ERROR: CheckedUrb->Result |= EFI_USB_ERR_BUFFER; CheckedUrb->Finished = TRUE; - DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: ERR_BUFFER! Completecode = %x\n",EvtTrb->Completecode)); + DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: ERR_BUFFER! Completecode = %x\n", EvtTrb->Completecode)); goto EXIT; case TRB_COMPLETION_USB_TRANSACTION_ERROR: CheckedUrb->Result |= EFI_USB_ERR_TIMEOUT; CheckedUrb->Finished = TRUE; - DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: TRANSACTION_ERROR! Completecode = %x\n",EvtTrb->Completecode)); + DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: TRANSACTION_ERROR! Completecode = %x\n", EvtTrb->Completecode)); goto EXIT; case TRB_COMPLETION_STOPPED: @@ -1196,17 +1209,18 @@ XhcCheckUrbResult ( DEBUG ((DEBUG_VERBOSE, "XhcCheckUrbResult: short packet happens!\n")); } - TRBType = (UINT8) (TRBPtr->Type); + TRBType = (UINT8)(TRBPtr->Type); if ((TRBType == TRB_TYPE_DATA_STAGE) || (TRBType == TRB_TYPE_NORMAL) || - (TRBType == TRB_TYPE_ISOCH)) { - CheckedUrb->Completed += (((TRANSFER_TRB_NORMAL*)TRBPtr)->Length - EvtTrb->Length); + (TRBType == TRB_TYPE_ISOCH)) + { + CheckedUrb->Completed += (((TRANSFER_TRB_NORMAL *)TRBPtr)->Length - EvtTrb->Length); } break; default: - DEBUG ((DEBUG_ERROR, "Transfer Default Error Occur! Completecode = 0x%x!\n",EvtTrb->Completecode)); + DEBUG ((DEBUG_ERROR, "Transfer Default Error Occur! Completecode = 0x%x!\n", EvtTrb->Completecode)); CheckedUrb->Result |= EFI_USB_ERR_TIMEOUT; CheckedUrb->Finished = TRUE; goto EXIT; @@ -1237,9 +1251,9 @@ EXIT: // Some 3rd party XHCI external cards don't support single 64-bytes width register access, // So divide it to two 32-bytes width register access. // - Low = XhcReadRuntimeReg (Xhc, XHC_ERDP_OFFSET); - High = XhcReadRuntimeReg (Xhc, XHC_ERDP_OFFSET + 4); - XhcDequeue = (UINT64)(LShiftU64((UINT64)High, 32) | Low); + Low = XhcReadRuntimeReg (Xhc, XHC_ERDP_OFFSET); + High = XhcReadRuntimeReg (Xhc, XHC_ERDP_OFFSET + 4); + XhcDequeue = (UINT64)(LShiftU64 ((UINT64)High, 32) | Low); PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE)); @@ -1255,7 +1269,6 @@ EXIT: return Urb->Finished; } - /** Execute the transfer by polling the URB. This is a synchronous operation. @@ -1272,18 +1285,18 @@ EXIT: **/ EFI_STATUS XhcExecTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN BOOLEAN CmdTransfer, - IN URB *Urb, - IN UINTN Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN BOOLEAN CmdTransfer, + IN URB *Urb, + IN UINTN Timeout ) { - EFI_STATUS Status; - UINT8 SlotId; - UINT8 Dci; - BOOLEAN Finished; - EFI_EVENT TimeoutEvent; - BOOLEAN IndefiniteTimeout; + EFI_STATUS Status; + UINT8 SlotId; + UINT8 Dci; + BOOLEAN Finished; + EFI_EVENT TimeoutEvent; + BOOLEAN IndefiniteTimeout; Status = EFI_SUCCESS; Finished = FALSE; @@ -1298,7 +1311,8 @@ XhcExecTransfer ( if (SlotId == 0) { return EFI_DEVICE_ERROR; } - Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); + + Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); ASSERT (Dci < 32); } @@ -1319,9 +1333,11 @@ XhcExecTransfer ( goto DONE; } - Status = gBS->SetTimer (TimeoutEvent, - TimerRelative, - EFI_TIMER_PERIOD_MILLISECONDS(Timeout)); + Status = gBS->SetTimer ( + TimeoutEvent, + TimerRelative, + EFI_TIMER_PERIOD_MILLISECONDS (Timeout) + ); if (EFI_ERROR (Status)) { goto DONE; @@ -1335,17 +1351,18 @@ RINGDOORBELL: if (Finished) { break; } + gBS->Stall (XHC_1_MICROSECOND); - } while (IndefiniteTimeout || EFI_ERROR(gBS->CheckEvent (TimeoutEvent))); + } while (IndefiniteTimeout || EFI_ERROR (gBS->CheckEvent (TimeoutEvent))); DONE: - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { Urb->Result = EFI_USB_ERR_NOTEXECUTE; } else if (!Finished) { Urb->Result = EFI_USB_ERR_TIMEOUT; Status = EFI_TIMEOUT; } else if (Urb->Result != EFI_USB_NOERROR) { - Status = EFI_DEVICE_ERROR; + Status = EFI_DEVICE_ERROR; } if (TimeoutEvent != NULL) { @@ -1369,9 +1386,9 @@ DONE: **/ EFI_STATUS XhciDelAsyncIntTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpNum + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpNum ) { LIST_ENTRY *Entry; @@ -1389,7 +1406,8 @@ XhciDelAsyncIntTransfer ( Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); if ((Urb->Ep.BusAddr == BusAddr) && (Urb->Ep.EpAddr == EpNum) && - (Urb->Ep.Direction == Direction)) { + (Urb->Ep.Direction == Direction)) + { // // Device doesn't finish the IntTransfer until real data comes // So the TRB should be removed as well. @@ -1417,13 +1435,13 @@ XhciDelAsyncIntTransfer ( **/ VOID XhciDelAllAsyncIntTransfers ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ) { - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - URB *Urb; - EFI_STATUS Status; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + URB *Urb; + EFI_STATUS Status; BASE_LIST_FOR_EACH_SAFE (Entry, Next, &Xhc->AsyncIntTransfers) { Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); @@ -1461,18 +1479,18 @@ XhciDelAllAsyncIntTransfers ( **/ URB * XhciInsertAsyncIntTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ) { - VOID *Data; - URB *Urb; + VOID *Data; + URB *Urb; Data = AllocateZeroPool (DataLen); if (Data == NULL) { @@ -1517,17 +1535,18 @@ XhciInsertAsyncIntTransfer ( **/ VOID XhcUpdateAsyncRequest ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; + EFI_STATUS Status; if (Urb->Result == EFI_USB_NOERROR) { Status = XhcCreateTransferTrb (Xhc, Urb); if (EFI_ERROR (Status)) { return; } + Status = RingIntTransferDoorBell (Xhc, Urb); if (EFI_ERROR (Status)) { return; @@ -1548,16 +1567,16 @@ XhcUpdateAsyncRequest ( **/ EFI_STATUS XhcFlushAsyncIntMap ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS PhyAddr; - EFI_PCI_IO_PROTOCOL_OPERATION MapOp; - EFI_PCI_IO_PROTOCOL *PciIo; - UINTN Len; - VOID *Map; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_PCI_IO_PROTOCOL_OPERATION MapOp; + EFI_PCI_IO_PROTOCOL *PciIo; + UINTN Len; + VOID *Map; PciIo = Xhc->PciIo; Len = Urb->DataLen; @@ -1582,8 +1601,8 @@ XhcFlushAsyncIntMap ( goto ON_ERROR; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; return EFI_SUCCESS; ON_ERROR: @@ -1600,22 +1619,22 @@ ON_ERROR: VOID EFIAPI XhcMonitorAsyncRequests ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_XHCI_INSTANCE *Xhc; - LIST_ENTRY *Entry; - LIST_ENTRY *Next; - UINT8 *ProcBuf; - URB *Urb; - UINT8 SlotId; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_XHCI_INSTANCE *Xhc; + LIST_ENTRY *Entry; + LIST_ENTRY *Next; + UINT8 *ProcBuf; + URB *Urb; + UINT8 SlotId; + EFI_STATUS Status; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (XHC_TPL); - Xhc = (USB_XHCI_INSTANCE*) Context; + Xhc = (USB_XHCI_INSTANCE *)Context; BASE_LIST_FOR_EACH_SAFE (Entry, Next, &Xhc->AsyncIntTransfers) { Urb = EFI_LIST_CONTAINER (Entry, URB, UrbList); @@ -1685,7 +1704,7 @@ XhcMonitorAsyncRequests ( // his callback. Some drivers may has a lower TPL restriction. // gBS->RestoreTPL (OldTpl); - (Urb->Callback) (ProcBuf, Urb->Completed, Urb->Context, Urb->Result); + (Urb->Callback)(ProcBuf, Urb->Completed, Urb->Context, Urb->Result); OldTpl = gBS->RaiseTPL (XHC_TPL); } @@ -1713,19 +1732,19 @@ XhcMonitorAsyncRequests ( EFI_STATUS EFIAPI XhcPollPortStatusChange ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT8 Port, - IN EFI_USB_PORT_STATUS *PortState + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT8 Port, + IN EFI_USB_PORT_STATUS *PortState ) { - EFI_STATUS Status; - UINT8 Speed; - UINT8 SlotId; - UINT8 Retries; - USB_DEV_ROUTE RouteChart; + EFI_STATUS Status; + UINT8 Speed; + UINT8 SlotId; + UINT8 Retries; + USB_DEV_ROUTE RouteChart; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; Retries = XHC_INIT_DEVICE_SLOT_RETRIES; if ((PortState->PortChangeStatus & (USB_PORT_STAT_C_CONNECTION | USB_PORT_STAT_C_ENABLE | USB_PORT_STAT_C_OVERCURRENT | USB_PORT_STAT_C_RESET)) == 0) { @@ -1737,13 +1756,14 @@ XhcPollPortStatusChange ( RouteChart.Route.RootPortNum = Port + 1; RouteChart.Route.TierNum = 1; } else { - if(Port < 14) { + if (Port < 14) { RouteChart.Route.RouteString = ParentRouteChart.Route.RouteString | (Port << (4 * (ParentRouteChart.Route.TierNum - 1))); } else { RouteChart.Route.RouteString = ParentRouteChart.Route.RouteString | (15 << (4 * (ParentRouteChart.Route.TierNum - 1))); } - RouteChart.Route.RootPortNum = ParentRouteChart.Route.RootPortNum; - RouteChart.Route.TierNum = ParentRouteChart.Route.TierNum + 1; + + RouteChart.Route.RootPortNum = ParentRouteChart.Route.RootPortNum; + RouteChart.Route.TierNum = ParentRouteChart.Route.TierNum + 1; } SlotId = XhcRouteStringToSlotId (Xhc, RouteChart); @@ -1756,7 +1776,8 @@ XhcPollPortStatusChange ( } if (((PortState->PortStatus & USB_PORT_STAT_ENABLE) != 0) && - ((PortState->PortStatus & USB_PORT_STAT_CONNECTION) != 0)) { + ((PortState->PortStatus & USB_PORT_STAT_CONNECTION) != 0)) + { // // Has a device attached, Identify device speed after port is enabled. // @@ -1796,7 +1817,6 @@ XhcPollPortStatusChange ( return Status; } - /** Calculate the device context index by endpoint address and direction. @@ -1808,19 +1828,20 @@ XhcPollPortStatusChange ( **/ UINT8 XhcEndpointToDci ( - IN UINT8 EpAddr, - IN UINT8 Direction + IN UINT8 EpAddr, + IN UINT8 Direction ) { - UINT8 Index; + UINT8 Index; if (EpAddr == 0) { return 1; } else { - Index = (UINT8) (2 * EpAddr); + Index = (UINT8)(2 * EpAddr); if (Direction == EfiUsbDataIn) { Index += 1; } + return Index; } } @@ -1846,7 +1867,8 @@ XhcBusDevAddrToSlotId ( for (Index = 0; Index < 255; Index++) { if (Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId != 0) && - (Xhc->UsbDevContext[Index + 1].BusDevAddr == BusDevAddr)) { + (Xhc->UsbDevContext[Index + 1].BusDevAddr == BusDevAddr)) + { break; } } @@ -1879,7 +1901,8 @@ XhcRouteStringToSlotId ( for (Index = 0; Index < 255; Index++) { if (Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId != 0) && - (Xhc->UsbDevContext[Index + 1].RouteString.Dword == RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].RouteString.Dword == RouteString.Dword)) + { break; } } @@ -1903,12 +1926,12 @@ XhcRouteStringToSlotId ( EFI_STATUS EFIAPI XhcSyncEventRing ( - IN USB_XHCI_INSTANCE *Xhc, - IN EVENT_RING *EvtRing + IN USB_XHCI_INSTANCE *Xhc, + IN EVENT_RING *EvtRing ) { - UINTN Index; - TRB_TEMPLATE *EvtTrb1; + UINTN Index; + TRB_TEMPLATE *EvtTrb1; ASSERT (EvtRing != NULL); @@ -1925,8 +1948,8 @@ XhcSyncEventRing ( EvtTrb1++; - if ((UINTN)EvtTrb1 >= ((UINTN) EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { - EvtTrb1 = EvtRing->EventRingSeg0; + if ((UINTN)EvtTrb1 >= ((UINTN)EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { + EvtTrb1 = EvtRing->EventRingSeg0; EvtRing->EventRingCCS = (EvtRing->EventRingCCS) ? 0 : 1; } } @@ -1952,12 +1975,12 @@ XhcSyncEventRing ( EFI_STATUS EFIAPI XhcSyncTrsRing ( - IN USB_XHCI_INSTANCE *Xhc, - IN TRANSFER_RING *TrsRing + IN USB_XHCI_INSTANCE *Xhc, + IN TRANSFER_RING *TrsRing ) { - UINTN Index; - TRB_TEMPLATE *TrsTrb; + UINTN Index; + TRB_TEMPLATE *TrsTrb; ASSERT (TrsRing != NULL); // @@ -1970,18 +1993,19 @@ XhcSyncTrsRing ( if (TrsTrb->CycleBit != (TrsRing->RingPCS & BIT0)) { break; } + TrsTrb++; - if ((UINT8) TrsTrb->Type == TRB_TYPE_LINK) { - ASSERT (((LINK_TRB*)TrsTrb)->TC != 0); + if ((UINT8)TrsTrb->Type == TRB_TYPE_LINK) { + ASSERT (((LINK_TRB *)TrsTrb)->TC != 0); // // set cycle bit in Link TRB as normal // - ((LINK_TRB*)TrsTrb)->CycleBit = TrsRing->RingPCS & BIT0; + ((LINK_TRB *)TrsTrb)->CycleBit = TrsRing->RingPCS & BIT0; // // Toggle PCS maintained by software // TrsRing->RingPCS = (TrsRing->RingPCS & BIT0) ? 0 : 1; - TrsTrb = (TRB_TEMPLATE *) TrsRing->RingSeg0; // Use host address + TrsTrb = (TRB_TEMPLATE *)TrsRing->RingSeg0; // Use host address } } @@ -2018,9 +2042,9 @@ XhcSyncTrsRing ( EFI_STATUS EFIAPI XhcCheckNewEvent ( - IN USB_XHCI_INSTANCE *Xhc, - IN EVENT_RING *EvtRing, - OUT TRB_TEMPLATE **NewEvtTrb + IN USB_XHCI_INSTANCE *Xhc, + IN EVENT_RING *EvtRing, + OUT TRB_TEMPLATE **NewEvtTrb ) { ASSERT (EvtRing != NULL); @@ -2035,7 +2059,7 @@ XhcCheckNewEvent ( // // If the dequeue pointer is beyond the ring, then roll-back it to the begining of the ring. // - if ((UINTN)EvtRing->EventRingDequeue >= ((UINTN) EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { + if ((UINTN)EvtRing->EventRingDequeue >= ((UINTN)EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { EvtRing->EventRingDequeue = EvtRing->EventRingSeg0; } @@ -2055,9 +2079,9 @@ XhcCheckNewEvent ( EFI_STATUS EFIAPI XhcRingDoorBell ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ) { if (SlotId == 0) { @@ -2080,12 +2104,12 @@ XhcRingDoorBell ( **/ EFI_STATUS RingIntTransferDoorBell ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ) { - UINT8 SlotId; - UINT8 Dci; + UINT8 SlotId; + UINT8 Dci; SlotId = XhcBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); Dci = XhcEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); @@ -2108,11 +2132,11 @@ RingIntTransferDoorBell ( EFI_STATUS EFIAPI XhcInitializeDeviceSlot ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ) { EFI_STATUS Status; @@ -2133,15 +2157,16 @@ XhcInitializeDeviceSlot ( CmdTrb.Type = TRB_TYPE_EN_SLOT; Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrb, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrb, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcInitializeDeviceSlot: Enable Slot Failed, Status = %r\n", Status)); return Status; } + ASSERT (EvtTrb->SlotId <= Xhc->MaxSlotsEn); DEBUG ((DEBUG_INFO, "Enable Slot Successfully, The Slot ID = 0x%x\n", EvtTrb->SlotId)); SlotId = (UINT8)EvtTrb->SlotId; @@ -2159,10 +2184,10 @@ XhcInitializeDeviceSlot ( // InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT)); ASSERT (InputContext != NULL); - ASSERT (((UINTN) InputContext & 0x3F) == 0); + ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT)); - Xhc->UsbDevContext[SlotId].InputContext = (VOID *) InputContext; + Xhc->UsbDevContext[SlotId].InputContext = (VOID *)InputContext; // // 2) Initialize the Input Control Context (6.2.5.1) of the Input Context by setting the A0 and A1 @@ -2183,14 +2208,15 @@ XhcInitializeDeviceSlot ( // // The device is behind of hub device. // - ParentSlotId = XhcRouteStringToSlotId(Xhc, ParentRouteChart); + ParentSlotId = XhcRouteStringToSlotId (Xhc, ParentRouteChart); ASSERT (ParentSlotId != 0); // - //if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context + // if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context // ParentDeviceContext = (DEVICE_CONTEXT *)Xhc->UsbDevContext[ParentSlotId].OutputContext; if ((ParentDeviceContext->Slot.TTPortNum == 0) && - (ParentDeviceContext->Slot.TTHubSlotId == 0)) { + (ParentDeviceContext->Slot.TTHubSlotId == 0)) + { if ((ParentDeviceContext->Slot.Speed == (EFI_USB_SPEED_HIGH + 1)) && (DeviceSpeed < EFI_USB_SPEED_HIGH)) { // // Full/Low device attached to High speed hub port that isolates the high speed signaling @@ -2217,9 +2243,9 @@ XhcInitializeDeviceSlot ( // // 4) Allocate and initialize the Transfer Ring for the Default Control Endpoint. // - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); Xhc->UsbDevContext[SlotId].EndpointTransferRing[0] = EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); // // 5) Initialize the Input default control Endpoint 0 Context (6.2.3). // @@ -2232,6 +2258,7 @@ XhcInitializeDeviceSlot ( } else { InputContext->EP[0].MaxPacketSize = 8; } + // // Initial value of Average TRB Length for Control endpoints would be 8B, Interrupt endpoints // 1KB, and Bulk and Isoch endpoints 3KB. @@ -2259,7 +2286,7 @@ XhcInitializeDeviceSlot ( // OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT)); ASSERT (OutputContext != NULL); - ASSERT (((UINTN) OutputContext & 0x3F) == 0); + ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT)); Xhc->UsbDevContext[SlotId].OutputContext = OutputContext; @@ -2271,7 +2298,7 @@ XhcInitializeDeviceSlot ( // // Fill DCBAA with PCI device address // - Xhc->DCBAA[SlotId] = (UINT64) (UINTN) PhyAddr; + Xhc->DCBAA[SlotId] = (UINT64)(UINTN)PhyAddr; // // 8) Issue an Address Device Command for the Device Slot, where the command points to the Input @@ -2282,20 +2309,20 @@ XhcInitializeDeviceSlot ( // gBS->Stall (XHC_RESET_RECOVERY_DELAY); ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT)); CmdTrbAddr.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbAddr.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbAddr.CycleBit = 1; CmdTrbAddr.Type = TRB_TYPE_ADDRESS_DEV; CmdTrbAddr.SlotId = Xhc->UsbDevContext[SlotId].SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbAddr, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbAddr, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (!EFI_ERROR (Status)) { - DeviceAddress = (UINT8) ((DEVICE_CONTEXT *) OutputContext)->Slot.DeviceAddress; + DeviceAddress = (UINT8)((DEVICE_CONTEXT *)OutputContext)->Slot.DeviceAddress; DEBUG ((DEBUG_INFO, " Address %d assigned successfully\n", DeviceAddress)); Xhc->UsbDevContext[SlotId].XhciDevAddr = DeviceAddress; } else { @@ -2321,11 +2348,11 @@ XhcInitializeDeviceSlot ( EFI_STATUS EFIAPI XhcInitializeDeviceSlot64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ) { EFI_STATUS Status; @@ -2346,15 +2373,16 @@ XhcInitializeDeviceSlot64 ( CmdTrb.Type = TRB_TYPE_EN_SLOT; Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrb, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrb, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcInitializeDeviceSlot64: Enable Slot Failed, Status = %r\n", Status)); return Status; } + ASSERT (EvtTrb->SlotId <= Xhc->MaxSlotsEn); DEBUG ((DEBUG_INFO, "Enable Slot Successfully, The Slot ID = 0x%x\n", EvtTrb->SlotId)); SlotId = (UINT8)EvtTrb->SlotId; @@ -2372,10 +2400,10 @@ XhcInitializeDeviceSlot64 ( // InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT_64)); ASSERT (InputContext != NULL); - ASSERT (((UINTN) InputContext & 0x3F) == 0); + ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT_64)); - Xhc->UsbDevContext[SlotId].InputContext = (VOID *) InputContext; + Xhc->UsbDevContext[SlotId].InputContext = (VOID *)InputContext; // // 2) Initialize the Input Control Context (6.2.5.1) of the Input Context by setting the A0 and A1 @@ -2396,14 +2424,15 @@ XhcInitializeDeviceSlot64 ( // // The device is behind of hub device. // - ParentSlotId = XhcRouteStringToSlotId(Xhc, ParentRouteChart); + ParentSlotId = XhcRouteStringToSlotId (Xhc, ParentRouteChart); ASSERT (ParentSlotId != 0); // - //if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context + // if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context // ParentDeviceContext = (DEVICE_CONTEXT_64 *)Xhc->UsbDevContext[ParentSlotId].OutputContext; if ((ParentDeviceContext->Slot.TTPortNum == 0) && - (ParentDeviceContext->Slot.TTHubSlotId == 0)) { + (ParentDeviceContext->Slot.TTHubSlotId == 0)) + { if ((ParentDeviceContext->Slot.Speed == (EFI_USB_SPEED_HIGH + 1)) && (DeviceSpeed < EFI_USB_SPEED_HIGH)) { // // Full/Low device attached to High speed hub port that isolates the high speed signaling @@ -2430,9 +2459,9 @@ XhcInitializeDeviceSlot64 ( // // 4) Allocate and initialize the Transfer Ring for the Default Control Endpoint. // - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); Xhc->UsbDevContext[SlotId].EndpointTransferRing[0] = EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); // // 5) Initialize the Input default control Endpoint 0 Context (6.2.3). // @@ -2445,6 +2474,7 @@ XhcInitializeDeviceSlot64 ( } else { InputContext->EP[0].MaxPacketSize = 8; } + // // Initial value of Average TRB Length for Control endpoints would be 8B, Interrupt endpoints // 1KB, and Bulk and Isoch endpoints 3KB. @@ -2472,7 +2502,7 @@ XhcInitializeDeviceSlot64 ( // OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT_64)); ASSERT (OutputContext != NULL); - ASSERT (((UINTN) OutputContext & 0x3F) == 0); + ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT_64)); Xhc->UsbDevContext[SlotId].OutputContext = OutputContext; @@ -2484,7 +2514,7 @@ XhcInitializeDeviceSlot64 ( // // Fill DCBAA with PCI device address // - Xhc->DCBAA[SlotId] = (UINT64) (UINTN) PhyAddr; + Xhc->DCBAA[SlotId] = (UINT64)(UINTN)PhyAddr; // // 8) Issue an Address Device Command for the Device Slot, where the command points to the Input @@ -2495,20 +2525,20 @@ XhcInitializeDeviceSlot64 ( // gBS->Stall (XHC_RESET_RECOVERY_DELAY); ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbAddr.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbAddr.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbAddr.CycleBit = 1; CmdTrbAddr.Type = TRB_TYPE_ADDRESS_DEV; CmdTrbAddr.SlotId = Xhc->UsbDevContext[SlotId].SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbAddr, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbAddr, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (!EFI_ERROR (Status)) { - DeviceAddress = (UINT8) ((DEVICE_CONTEXT_64 *) OutputContext)->Slot.DeviceAddress; + DeviceAddress = (UINT8)((DEVICE_CONTEXT_64 *)OutputContext)->Slot.DeviceAddress; DEBUG ((DEBUG_INFO, " Address %d assigned successfully\n", DeviceAddress)); Xhc->UsbDevContext[SlotId].XhciDevAddr = DeviceAddress; } else { @@ -2519,7 +2549,6 @@ XhcInitializeDeviceSlot64 ( return Status; } - /** Disable the specified device slot. @@ -2532,8 +2561,8 @@ XhcInitializeDeviceSlot64 ( EFI_STATUS EFIAPI XhcDisableSlotCmd ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId ) { EFI_STATUS Status; @@ -2549,7 +2578,8 @@ XhcDisableSlotCmd ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled || (Xhc->UsbDevContext[Index + 1].SlotId == 0) || - (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) + { continue; } @@ -2570,16 +2600,17 @@ XhcDisableSlotCmd ( CmdTrbDisSlot.CycleBit = 1; CmdTrbDisSlot.Type = TRB_TYPE_DIS_SLOT; CmdTrbDisSlot.SlotId = SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbDisSlot, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbDisSlot, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcDisableSlotCmd: Disable Slot Command Failed, Status = %r\n", Status)); return Status; } + // // Free the slot's device context entry // @@ -2594,6 +2625,7 @@ XhcDisableSlotCmd ( if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] = NULL; } @@ -2616,6 +2648,7 @@ XhcDisableSlotCmd ( if (Xhc->UsbDevContext[SlotId].OutputContext != NULL) { UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT)); } + // // Doesn't zero the entry because XhcAsyncInterruptTransfer() may be invoked to remove the established // asynchronous interrupt pipe after the device is disabled. It needs the device address mapping info to @@ -2639,8 +2672,8 @@ XhcDisableSlotCmd ( EFI_STATUS EFIAPI XhcDisableSlotCmd64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId ) { EFI_STATUS Status; @@ -2656,7 +2689,8 @@ XhcDisableSlotCmd64 ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled || (Xhc->UsbDevContext[Index + 1].SlotId == 0) || - (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) + { continue; } @@ -2677,16 +2711,17 @@ XhcDisableSlotCmd64 ( CmdTrbDisSlot.CycleBit = 1; CmdTrbDisSlot.Type = TRB_TYPE_DIS_SLOT; CmdTrbDisSlot.SlotId = SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbDisSlot, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbDisSlot, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcDisableSlotCmd: Disable Slot Command Failed, Status = %r\n", Status)); return Status; } + // // Free the slot's device context entry // @@ -2701,6 +2736,7 @@ XhcDisableSlotCmd64 ( if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] = NULL; } @@ -2721,8 +2757,9 @@ XhcDisableSlotCmd64 ( } if (Xhc->UsbDevContext[SlotId].OutputContext != NULL) { - UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT_64)); + UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT_64)); } + // // Doesn't zero the entry because XhcAsyncInterruptTransfer() may be invoked to remove the established // asynchronous interrupt pipe after the device is disabled. It needs the device address mapping info to @@ -2749,23 +2786,23 @@ XhcDisableSlotCmd64 ( UINT8 EFIAPI XhcInitializeEndpointContext ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN INPUT_CONTEXT *InputContext, - IN USB_INTERFACE_DESCRIPTOR *IfDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN INPUT_CONTEXT *InputContext, + IN USB_INTERFACE_DESCRIPTOR *IfDesc ) { - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - UINT8 Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINT8 Interval; - TRANSFER_RING *EndpointTransferRing; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + UINT8 Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINT8 Interval; + TRANSFER_RING *EndpointTransferRing; MaxDci = 0; @@ -2815,14 +2852,16 @@ XhcInitializeEndpointContext ( InputContext->EP[Dci-1].AverageTRBLength = 0x1000; if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool(sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); - DEBUG ((DEBUG_INFO, "Endpoint[%x]: Created BULK ring [%p~%p)\n", - EpDesc->EndpointAddress, - EndpointTransferRing->RingSeg0, - (UINTN) EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) - )); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + DEBUG (( + DEBUG_INFO, + "Endpoint[%x]: Created BULK ring [%p~%p)\n", + EpDesc->EndpointAddress, + EndpointTransferRing->RingSeg0, + (UINTN)EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) + )); } break; @@ -2834,6 +2873,7 @@ XhcInitializeEndpointContext ( InputContext->EP[Dci-1].CErr = 0; InputContext->EP[Dci-1].EPType = ED_ISOCH_OUT; } + // // Get the bInterval from descriptor and init the the interval field of endpoint context. // Refer to XHCI 1.1 spec section 6.2.3.6. @@ -2862,6 +2902,7 @@ XhcInitializeEndpointContext ( InputContext->EP[Dci-1].CErr = 3; InputContext->EP[Dci-1].EPType = ED_INTERRUPT_OUT; } + InputContext->EP[Dci-1].AverageTRBLength = 0x1000; InputContext->EP[Dci-1].MaxESITPayload = EpDesc->MaxPacketSize; // @@ -2873,7 +2914,7 @@ XhcInitializeEndpointContext ( // Calculate through the bInterval field of Endpoint descriptor. // ASSERT (Interval != 0); - InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32((UINT32)Interval) + 3; + InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32 ((UINT32)Interval) + 3; } else if ((DeviceSpeed == EFI_USB_SPEED_HIGH) || (DeviceSpeed == EFI_USB_SPEED_SUPER)) { Interval = EpDesc->Interval; ASSERT (Interval >= 1 && Interval <= 16); @@ -2888,15 +2929,18 @@ XhcInitializeEndpointContext ( } if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool(sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); - DEBUG ((DEBUG_INFO, "Endpoint[%x]: Created INT ring [%p~%p)\n", - EpDesc->EndpointAddress, - EndpointTransferRing->RingSeg0, - (UINTN) EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) - )); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + DEBUG (( + DEBUG_INFO, + "Endpoint[%x]: Created INT ring [%p~%p)\n", + EpDesc->EndpointAddress, + EndpointTransferRing->RingSeg0, + (UINTN)EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) + )); } + break; case USB_ENDPOINT_CONTROL: @@ -2915,8 +2959,8 @@ XhcInitializeEndpointContext ( ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); - PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); - PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; + PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); + PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; InputContext->EP[Dci-1].PtrLo = XHC_LOW_32BIT (PhyAddr); InputContext->EP[Dci-1].PtrHi = XHC_HIGH_32BIT (PhyAddr); @@ -2941,23 +2985,23 @@ XhcInitializeEndpointContext ( UINT8 EFIAPI XhcInitializeEndpointContext64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN INPUT_CONTEXT_64 *InputContext, - IN USB_INTERFACE_DESCRIPTOR *IfDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN INPUT_CONTEXT_64 *InputContext, + IN USB_INTERFACE_DESCRIPTOR *IfDesc ) { - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - UINT8 Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINT8 Interval; - TRANSFER_RING *EndpointTransferRing; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + UINT8 Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINT8 Interval; + TRANSFER_RING *EndpointTransferRing; MaxDci = 0; @@ -3007,14 +3051,16 @@ XhcInitializeEndpointContext64 ( InputContext->EP[Dci-1].AverageTRBLength = 0x1000; if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool(sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); - DEBUG ((DEBUG_INFO, "Endpoint64[%x]: Created BULK ring [%p~%p)\n", - EpDesc->EndpointAddress, - EndpointTransferRing->RingSeg0, - (UINTN) EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) - )); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + DEBUG (( + DEBUG_INFO, + "Endpoint64[%x]: Created BULK ring [%p~%p)\n", + EpDesc->EndpointAddress, + EndpointTransferRing->RingSeg0, + (UINTN)EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) + )); } break; @@ -3026,6 +3072,7 @@ XhcInitializeEndpointContext64 ( InputContext->EP[Dci-1].CErr = 0; InputContext->EP[Dci-1].EPType = ED_ISOCH_OUT; } + // // Get the bInterval from descriptor and init the the interval field of endpoint context. // Refer to XHCI 1.1 spec section 6.2.3.6. @@ -3054,6 +3101,7 @@ XhcInitializeEndpointContext64 ( InputContext->EP[Dci-1].CErr = 3; InputContext->EP[Dci-1].EPType = ED_INTERRUPT_OUT; } + InputContext->EP[Dci-1].AverageTRBLength = 0x1000; InputContext->EP[Dci-1].MaxESITPayload = EpDesc->MaxPacketSize; // @@ -3065,7 +3113,7 @@ XhcInitializeEndpointContext64 ( // Calculate through the bInterval field of Endpoint descriptor. // ASSERT (Interval != 0); - InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32((UINT32)Interval) + 3; + InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32 ((UINT32)Interval) + 3; } else if ((DeviceSpeed == EFI_USB_SPEED_HIGH) || (DeviceSpeed == EFI_USB_SPEED_SUPER)) { Interval = EpDesc->Interval; ASSERT (Interval >= 1 && Interval <= 16); @@ -3080,15 +3128,18 @@ XhcInitializeEndpointContext64 ( } if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool(sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - CreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); - DEBUG ((DEBUG_INFO, "Endpoint64[%x]: Created INT ring [%p~%p)\n", - EpDesc->EndpointAddress, - EndpointTransferRing->RingSeg0, - (UINTN) EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) - )); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + CreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + DEBUG (( + DEBUG_INFO, + "Endpoint64[%x]: Created INT ring [%p~%p)\n", + EpDesc->EndpointAddress, + EndpointTransferRing->RingSeg0, + (UINTN)EndpointTransferRing->RingSeg0 + TR_RING_TRB_NUMBER * sizeof (TRB_TEMPLATE) + )); } + break; case USB_ENDPOINT_CONTROL: @@ -3107,8 +3158,8 @@ XhcInitializeEndpointContext64 ( ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); - PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); - PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; + PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); + PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; InputContext->EP[Dci-1].PtrLo = XHC_LOW_32BIT (PhyAddr); InputContext->EP[Dci-1].PtrHi = XHC_HIGH_32BIT (PhyAddr); @@ -3132,23 +3183,24 @@ XhcInitializeEndpointContext64 ( EFI_STATUS EFIAPI XhcSetConfigCmd ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDesc; - UINT8 Index; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDesc; + UINT8 Index; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; INPUT_CONTEXT *InputContext; DEVICE_CONTEXT *OutputContext; EVT_TRB_COMMAND_COMPLETION *EvtTrb; + // // 4.6.6 Configure Endpoint // @@ -3186,7 +3238,7 @@ XhcSetConfigCmd ( // configure endpoint // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -3195,9 +3247,9 @@ XhcSetConfigCmd ( DEBUG ((DEBUG_INFO, "Configure Endpoint\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSetConfigCmd: Config Endpoint Failed, Status = %r\n", Status)); @@ -3222,23 +3274,24 @@ XhcSetConfigCmd ( EFI_STATUS EFIAPI XhcSetConfigCmd64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDesc; - UINT8 Index; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDesc; + UINT8 Index; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; INPUT_CONTEXT_64 *InputContext; DEVICE_CONTEXT_64 *OutputContext; EVT_TRB_COMMAND_COMPLETION *EvtTrb; + // // 4.6.6 Configure Endpoint // @@ -3276,7 +3329,7 @@ XhcSetConfigCmd64 ( // configure endpoint // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -3285,9 +3338,9 @@ XhcSetConfigCmd64 ( DEBUG ((DEBUG_INFO, "Configure Endpoint\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSetConfigCmd64: Config Endpoint Failed, Status = %r\n", Status)); @@ -3313,15 +3366,15 @@ XhcSetConfigCmd64 ( EFI_STATUS EFIAPI XhcStopEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *PendingUrb OPTIONAL + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *PendingUrb OPTIONAL ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - CMD_TRB_STOP_ENDPOINT CmdTrbStopED; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + CMD_TRB_STOP_ENDPOINT CmdTrbStopED; DEBUG ((DEBUG_INFO, "XhcStopEndpoint: Slot = 0x%x, Dci = 0x%x\n", SlotId, Dci)); @@ -3356,13 +3409,13 @@ XhcStopEndpoint ( CmdTrbStopED.Type = TRB_TYPE_STOP_ENDPOINT; CmdTrbStopED.EDID = Dci; CmdTrbStopED.SlotId = SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbStopED, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbStopED, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcStopEndpoint: Stop Endpoint Failed, Status = %r\n", Status)); } @@ -3385,9 +3438,9 @@ XhcStopEndpoint ( EFI_STATUS EFIAPI XhcResetEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ) { EFI_STATUS Status; @@ -3404,13 +3457,13 @@ XhcResetEndpoint ( CmdTrbResetED.Type = TRB_TYPE_RESET_ENDPOINT; CmdTrbResetED.EDID = Dci; CmdTrbResetED.SlotId = SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbResetED, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbResetED, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcResetEndpoint: Reset Endpoint Failed, Status = %r\n", Status)); } @@ -3433,10 +3486,10 @@ XhcResetEndpoint ( EFI_STATUS EFIAPI XhcSetTrDequeuePointer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *Urb ) { EFI_STATUS Status; @@ -3450,20 +3503,20 @@ XhcSetTrDequeuePointer ( // Send stop endpoint command to transit Endpoint from running to stop state // ZeroMem (&CmdSetTRDeq, sizeof (CmdSetTRDeq)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER)); CmdSetTRDeq.PtrLo = XHC_LOW_32BIT (PhyAddr) | Urb->Ring->RingPCS; CmdSetTRDeq.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdSetTRDeq.CycleBit = 1; CmdSetTRDeq.Type = TRB_TYPE_SET_TR_DEQUE; CmdSetTRDeq.Endpoint = Dci; CmdSetTRDeq.SlotId = SlotId; - Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdSetTRDeq, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdSetTRDeq, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSetTrDequeuePointer: Set TR Dequeue Pointer Failed, Status = %r\n", Status)); } @@ -3485,26 +3538,26 @@ XhcSetTrDequeuePointer ( EFI_STATUS EFIAPI XhcSetInterface ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc, - IN EFI_USB_DEVICE_REQUEST *Request + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc, + IN EFI_USB_DEVICE_REQUEST *Request ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDescActive; - USB_INTERFACE_DESCRIPTOR *IfDescSet; - USB_INTERFACE_DESCRIPTOR *IfDesc; - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - UINT8 Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *RingSeg; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDescActive; + USB_INTERFACE_DESCRIPTOR *IfDescSet; + USB_INTERFACE_DESCRIPTOR *IfDesc; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + UINT8 Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *RingSeg; CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; INPUT_CONTEXT *InputContext; @@ -3533,18 +3586,18 @@ XhcSetInterface ( MaxDci = 0; IfDescActive = NULL; - IfDescSet = NULL; + IfDescSet = NULL; IfDesc = (USB_INTERFACE_DESCRIPTOR *)(ConfigDesc + 1); - while ((UINTN) IfDesc < ((UINTN) ConfigDesc + ConfigDesc->TotalLength)) { + while ((UINTN)IfDesc < ((UINTN)ConfigDesc + ConfigDesc->TotalLength)) { if ((IfDesc->DescriptorType == USB_DESC_TYPE_INTERFACE) && (IfDesc->Length >= sizeof (USB_INTERFACE_DESCRIPTOR))) { - if (IfDesc->InterfaceNumber == (UINT8) Request->Index) { + if (IfDesc->InterfaceNumber == (UINT8)Request->Index) { if (IfDesc->AlternateSetting == Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[IfDesc->InterfaceNumber]) { // // Find out the active interface descriptor. // IfDescActive = IfDesc; - } else if (IfDesc->AlternateSetting == (UINT8) Request->Value) { + } else if (IfDesc->AlternateSetting == (UINT8)Request->Value) { // // Find out the interface descriptor to set. // @@ -3552,6 +3605,7 @@ XhcSetInterface ( } } } + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } @@ -3570,8 +3624,8 @@ XhcSetInterface ( // if ((IfDescActive != NULL) && (IfDescSet != NULL)) { - NumEp = IfDescActive->NumEndpoints; - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) (IfDescActive + 1); + NumEp = IfDescActive->NumEndpoints; + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDescActive + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { while (EpDesc->DescriptorType != USB_DESC_TYPE_ENDPOINT) { EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); @@ -3582,14 +3636,15 @@ XhcSetInterface ( continue; } - EpAddr = (UINT8) (EpDesc->EndpointAddress & 0x0F); - Direction = (UINT8) ((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); + EpAddr = (UINT8)(EpDesc->EndpointAddress & 0x0F); + Direction = (UINT8)((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); Dci = XhcEndpointToDci (EpAddr, Direction); ASSERT (Dci < 32); if (Dci > MaxDci) { MaxDci = Dci; } + // // XHCI 4.3.6 - Setting Alternate Interfaces // 1) Stop any Running Transfer Rings affected by the Alternate Interface setting. @@ -3598,6 +3653,7 @@ XhcSetInterface ( if (EFI_ERROR (Status)) { return Status; } + // // XHCI 4.3.6 - Setting Alternate Interfaces // 2) Free Transfer Rings of all endpoints that will be affected by the Alternate Interface setting. @@ -3607,6 +3663,7 @@ XhcSetInterface ( if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci - 1]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci - 1] = NULL; } @@ -3646,7 +3703,7 @@ XhcSetInterface ( // 5) Issue and successfully complete a Configure Endpoint Command. // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -3655,9 +3712,9 @@ XhcSetInterface ( DEBUG ((DEBUG_INFO, "SetInterface: Configure Endpoint\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SetInterface: Config Endpoint Failed, Status = %r\n", Status)); @@ -3665,7 +3722,7 @@ XhcSetInterface ( // // Update the active AlternateSetting. // - Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8) Request->Index] = (UINT8) Request->Value; + Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8)Request->Index] = (UINT8)Request->Value; } } @@ -3687,26 +3744,26 @@ XhcSetInterface ( EFI_STATUS EFIAPI XhcSetInterface64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc, - IN EFI_USB_DEVICE_REQUEST *Request + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc, + IN EFI_USB_DEVICE_REQUEST *Request ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDescActive; - USB_INTERFACE_DESCRIPTOR *IfDescSet; - USB_INTERFACE_DESCRIPTOR *IfDesc; - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - UINT8 Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *RingSeg; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDescActive; + USB_INTERFACE_DESCRIPTOR *IfDescSet; + USB_INTERFACE_DESCRIPTOR *IfDesc; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + UINT8 Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *RingSeg; CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; INPUT_CONTEXT_64 *InputContext; @@ -3735,18 +3792,18 @@ XhcSetInterface64 ( MaxDci = 0; IfDescActive = NULL; - IfDescSet = NULL; + IfDescSet = NULL; IfDesc = (USB_INTERFACE_DESCRIPTOR *)(ConfigDesc + 1); - while ((UINTN) IfDesc < ((UINTN) ConfigDesc + ConfigDesc->TotalLength)) { + while ((UINTN)IfDesc < ((UINTN)ConfigDesc + ConfigDesc->TotalLength)) { if ((IfDesc->DescriptorType == USB_DESC_TYPE_INTERFACE) && (IfDesc->Length >= sizeof (USB_INTERFACE_DESCRIPTOR))) { - if (IfDesc->InterfaceNumber == (UINT8) Request->Index) { + if (IfDesc->InterfaceNumber == (UINT8)Request->Index) { if (IfDesc->AlternateSetting == Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[IfDesc->InterfaceNumber]) { // // Find out the active interface descriptor. // IfDescActive = IfDesc; - } else if (IfDesc->AlternateSetting == (UINT8) Request->Value) { + } else if (IfDesc->AlternateSetting == (UINT8)Request->Value) { // // Find out the interface descriptor to set. // @@ -3754,6 +3811,7 @@ XhcSetInterface64 ( } } } + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } @@ -3772,8 +3830,8 @@ XhcSetInterface64 ( // if ((IfDescActive != NULL) && (IfDescSet != NULL)) { - NumEp = IfDescActive->NumEndpoints; - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) (IfDescActive + 1); + NumEp = IfDescActive->NumEndpoints; + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDescActive + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { while (EpDesc->DescriptorType != USB_DESC_TYPE_ENDPOINT) { EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); @@ -3784,14 +3842,15 @@ XhcSetInterface64 ( continue; } - EpAddr = (UINT8) (EpDesc->EndpointAddress & 0x0F); - Direction = (UINT8) ((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); + EpAddr = (UINT8)(EpDesc->EndpointAddress & 0x0F); + Direction = (UINT8)((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); Dci = XhcEndpointToDci (EpAddr, Direction); ASSERT (Dci < 32); if (Dci > MaxDci) { MaxDci = Dci; } + // // XHCI 4.3.6 - Setting Alternate Interfaces // 1) Stop any Running Transfer Rings affected by the Alternate Interface setting. @@ -3800,6 +3859,7 @@ XhcSetInterface64 ( if (EFI_ERROR (Status)) { return Status; } + // // XHCI 4.3.6 - Setting Alternate Interfaces // 2) Free Transfer Rings of all endpoints that will be affected by the Alternate Interface setting. @@ -3809,6 +3869,7 @@ XhcSetInterface64 ( if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci - 1]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci - 1] = NULL; } @@ -3848,7 +3909,7 @@ XhcSetInterface64 ( // 5) Issue and successfully complete a Configure Endpoint Command. // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -3857,9 +3918,9 @@ XhcSetInterface64 ( DEBUG ((DEBUG_INFO, "SetInterface64: Configure Endpoint\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SetInterface64: Config Endpoint Failed, Status = %r\n", Status)); @@ -3867,7 +3928,7 @@ XhcSetInterface64 ( // // Update the active AlternateSetting. // - Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8) Request->Index] = (UINT8) Request->Value; + Xhc->UsbDevContext[SlotId].ActiveAlternateSetting[(UINT8)Request->Index] = (UINT8)Request->Value; } } @@ -3887,9 +3948,9 @@ XhcSetInterface64 ( EFI_STATUS EFIAPI XhcEvaluateContext ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ) { EFI_STATUS Status; @@ -3910,7 +3971,7 @@ XhcEvaluateContext ( InputContext->EP[0].MaxPacketSize = MaxPacketSize; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbEvalu.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbEvalu.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbEvalu.CycleBit = 1; @@ -3919,13 +3980,14 @@ XhcEvaluateContext ( DEBUG ((DEBUG_INFO, "Evaluate context\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbEvalu, + (TRB_TEMPLATE *)(UINTN)&CmdTrbEvalu, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcEvaluateContext: Evaluate Context Failed, Status = %r\n", Status)); } + return Status; } @@ -3942,9 +4004,9 @@ XhcEvaluateContext ( EFI_STATUS EFIAPI XhcEvaluateContext64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ) { EFI_STATUS Status; @@ -3965,7 +4027,7 @@ XhcEvaluateContext64 ( InputContext->EP[0].MaxPacketSize = MaxPacketSize; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbEvalu.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbEvalu.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbEvalu.CycleBit = 1; @@ -3974,17 +4036,17 @@ XhcEvaluateContext64 ( DEBUG ((DEBUG_INFO, "Evaluate context\n")); Status = XhcCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbEvalu, + (TRB_TEMPLATE *)(UINTN)&CmdTrbEvalu, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcEvaluateContext64: Evaluate Context Failed, Status = %r\n", Status)); } + return Status; } - /** Evaluate the slot context for hub device through XHCI's Configure_Endpoint cmd. @@ -3999,11 +4061,11 @@ XhcEvaluateContext64 ( **/ EFI_STATUS XhcConfigHubContext ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ) { EFI_STATUS Status; @@ -4027,14 +4089,14 @@ XhcConfigHubContext ( // // Copy the slot context from OutputContext to Input context // - CopyMem(&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT)); + CopyMem (&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT)); InputContext->Slot.Hub = 1; InputContext->Slot.PortNum = PortNum; InputContext->Slot.TTT = TTT; InputContext->Slot.MTT = MTT; ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -4042,14 +4104,15 @@ XhcConfigHubContext ( CmdTrbCfgEP.SlotId = Xhc->UsbDevContext[SlotId].SlotId; DEBUG ((DEBUG_INFO, "Configure Hub Slot Context\n")); Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcConfigHubContext: Config Endpoint Failed, Status = %r\n", Status)); } + return Status; } @@ -4067,11 +4130,11 @@ XhcConfigHubContext ( **/ EFI_STATUS XhcConfigHubContext64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ) { EFI_STATUS Status; @@ -4095,14 +4158,14 @@ XhcConfigHubContext64 ( // // Copy the slot context from OutputContext to Input context // - CopyMem(&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT_64)); + CopyMem (&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT_64)); InputContext->Slot.Hub = 1; InputContext->Slot.PortNum = PortNum; InputContext->Slot.TTT = TTT; InputContext->Slot.MTT = MTT; ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -4110,13 +4173,14 @@ XhcConfigHubContext64 ( CmdTrbCfgEP.SlotId = Xhc->UsbDevContext[SlotId].SlotId; DEBUG ((DEBUG_INFO, "Configure Hub Slot Context\n")); Status = XhcCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcConfigHubContext64: Config Endpoint Failed, Status = %r\n", Status)); } + return Status; } diff --git a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h index 3f9cdb1c36..7c85f7993b 100644 --- a/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h +++ b/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h @@ -10,73 +10,73 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_XHCI_SCHED_H_ #define _EFI_XHCI_SCHED_H_ -#define XHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') -#define XHC_INIT_DEVICE_SLOT_RETRIES 1 +#define XHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') +#define XHC_INIT_DEVICE_SLOT_RETRIES 1 // // Transfer types, used in URB to identify the transfer type // -#define XHC_CTRL_TRANSFER 0x01 -#define XHC_BULK_TRANSFER 0x02 -#define XHC_INT_TRANSFER_SYNC 0x04 -#define XHC_INT_TRANSFER_ASYNC 0x08 -#define XHC_INT_ONLY_TRANSFER_ASYNC 0x10 +#define XHC_CTRL_TRANSFER 0x01 +#define XHC_BULK_TRANSFER 0x02 +#define XHC_INT_TRANSFER_SYNC 0x04 +#define XHC_INT_TRANSFER_ASYNC 0x08 +#define XHC_INT_ONLY_TRANSFER_ASYNC 0x10 // // 6.4.6 TRB Types // -#define TRB_TYPE_NORMAL 1 -#define TRB_TYPE_SETUP_STAGE 2 -#define TRB_TYPE_DATA_STAGE 3 -#define TRB_TYPE_STATUS_STAGE 4 -#define TRB_TYPE_ISOCH 5 -#define TRB_TYPE_LINK 6 -#define TRB_TYPE_EVENT_DATA 7 -#define TRB_TYPE_NO_OP 8 -#define TRB_TYPE_EN_SLOT 9 -#define TRB_TYPE_DIS_SLOT 10 -#define TRB_TYPE_ADDRESS_DEV 11 -#define TRB_TYPE_CON_ENDPOINT 12 -#define TRB_TYPE_EVALU_CONTXT 13 -#define TRB_TYPE_RESET_ENDPOINT 14 -#define TRB_TYPE_STOP_ENDPOINT 15 -#define TRB_TYPE_SET_TR_DEQUE 16 -#define TRB_TYPE_RESET_DEV 17 -#define TRB_TYPE_GET_PORT_BANW 21 -#define TRB_TYPE_FORCE_HEADER 22 -#define TRB_TYPE_NO_OP_COMMAND 23 -#define TRB_TYPE_TRANS_EVENT 32 -#define TRB_TYPE_COMMAND_COMPLT_EVENT 33 -#define TRB_TYPE_PORT_STATUS_CHANGE_EVENT 34 -#define TRB_TYPE_HOST_CONTROLLER_EVENT 37 -#define TRB_TYPE_DEVICE_NOTIFI_EVENT 38 -#define TRB_TYPE_MFINDEX_WRAP_EVENT 39 +#define TRB_TYPE_NORMAL 1 +#define TRB_TYPE_SETUP_STAGE 2 +#define TRB_TYPE_DATA_STAGE 3 +#define TRB_TYPE_STATUS_STAGE 4 +#define TRB_TYPE_ISOCH 5 +#define TRB_TYPE_LINK 6 +#define TRB_TYPE_EVENT_DATA 7 +#define TRB_TYPE_NO_OP 8 +#define TRB_TYPE_EN_SLOT 9 +#define TRB_TYPE_DIS_SLOT 10 +#define TRB_TYPE_ADDRESS_DEV 11 +#define TRB_TYPE_CON_ENDPOINT 12 +#define TRB_TYPE_EVALU_CONTXT 13 +#define TRB_TYPE_RESET_ENDPOINT 14 +#define TRB_TYPE_STOP_ENDPOINT 15 +#define TRB_TYPE_SET_TR_DEQUE 16 +#define TRB_TYPE_RESET_DEV 17 +#define TRB_TYPE_GET_PORT_BANW 21 +#define TRB_TYPE_FORCE_HEADER 22 +#define TRB_TYPE_NO_OP_COMMAND 23 +#define TRB_TYPE_TRANS_EVENT 32 +#define TRB_TYPE_COMMAND_COMPLT_EVENT 33 +#define TRB_TYPE_PORT_STATUS_CHANGE_EVENT 34 +#define TRB_TYPE_HOST_CONTROLLER_EVENT 37 +#define TRB_TYPE_DEVICE_NOTIFI_EVENT 38 +#define TRB_TYPE_MFINDEX_WRAP_EVENT 39 // // Endpoint Type (EP Type). // -#define ED_NOT_VALID 0 -#define ED_ISOCH_OUT 1 -#define ED_BULK_OUT 2 -#define ED_INTERRUPT_OUT 3 -#define ED_CONTROL_BIDIR 4 -#define ED_ISOCH_IN 5 -#define ED_BULK_IN 6 -#define ED_INTERRUPT_IN 7 +#define ED_NOT_VALID 0 +#define ED_ISOCH_OUT 1 +#define ED_BULK_OUT 2 +#define ED_INTERRUPT_OUT 3 +#define ED_CONTROL_BIDIR 4 +#define ED_ISOCH_IN 5 +#define ED_BULK_IN 6 +#define ED_INTERRUPT_IN 7 // // 6.4.5 TRB Completion Codes // -#define TRB_COMPLETION_INVALID 0 -#define TRB_COMPLETION_SUCCESS 1 -#define TRB_COMPLETION_DATA_BUFFER_ERROR 2 -#define TRB_COMPLETION_BABBLE_ERROR 3 -#define TRB_COMPLETION_USB_TRANSACTION_ERROR 4 -#define TRB_COMPLETION_TRB_ERROR 5 -#define TRB_COMPLETION_STALL_ERROR 6 -#define TRB_COMPLETION_SHORT_PACKET 13 -#define TRB_COMPLETION_STOPPED 26 -#define TRB_COMPLETION_STOPPED_LENGTH_INVALID 27 +#define TRB_COMPLETION_INVALID 0 +#define TRB_COMPLETION_SUCCESS 1 +#define TRB_COMPLETION_DATA_BUFFER_ERROR 2 +#define TRB_COMPLETION_BABBLE_ERROR 3 +#define TRB_COMPLETION_USB_TRANSACTION_ERROR 4 +#define TRB_COMPLETION_TRB_ERROR 5 +#define TRB_COMPLETION_STALL_ERROR 6 +#define TRB_COMPLETION_SHORT_PACKET 13 +#define TRB_COMPLETION_STOPPED 26 +#define TRB_COMPLETION_STOPPED_LENGTH_INVALID 27 // // The topology string used to present usb device location @@ -85,15 +85,15 @@ typedef struct _USB_DEV_TOPOLOGY { // // The tier concatenation of down stream port. // - UINT32 RouteString:20; + UINT32 RouteString : 20; // // The root port number of the chain. // - UINT32 RootPortNum:8; + UINT32 RootPortNum : 8; // // The Tier the device reside. // - UINT32 TierNum:4; + UINT32 TierNum : 4; } USB_DEV_TOPOLOGY; // @@ -126,33 +126,33 @@ typedef struct _USB_ENDPOINT { // TRB Template // typedef struct _TRB_TEMPLATE { - UINT32 Parameter1; + UINT32 Parameter1; - UINT32 Parameter2; + UINT32 Parameter2; - UINT32 Status; + UINT32 Status; - UINT32 CycleBit:1; - UINT32 RsvdZ1:9; - UINT32 Type:6; - UINT32 Control:16; + UINT32 CycleBit : 1; + UINT32 RsvdZ1 : 9; + UINT32 Type : 6; + UINT32 Control : 16; } TRB_TEMPLATE; typedef struct _TRANSFER_RING { - VOID *RingSeg0; - UINTN TrbNumber; - TRB_TEMPLATE *RingEnqueue; - TRB_TEMPLATE *RingDequeue; - UINT32 RingPCS; + VOID *RingSeg0; + UINTN TrbNumber; + TRB_TEMPLATE *RingEnqueue; + TRB_TEMPLATE *RingDequeue; + UINT32 RingPCS; } TRANSFER_RING; typedef struct _EVENT_RING { - VOID *ERSTBase; - VOID *EventRingSeg0; - UINTN TrbNumber; - TRB_TEMPLATE *EventRingEnqueue; - TRB_TEMPLATE *EventRingDequeue; - UINT32 EventRingCCS; + VOID *ERSTBase; + VOID *EventRingSeg0; + UINTN TrbNumber; + TRB_TEMPLATE *EventRingEnqueue; + TRB_TEMPLATE *EventRingDequeue; + UINT32 EventRingCCS; } EVENT_RING; // @@ -160,39 +160,39 @@ typedef struct _EVENT_RING { // usb requests. // typedef struct _URB { - UINT32 Signature; - LIST_ENTRY UrbList; + UINT32 Signature; + LIST_ENTRY UrbList; // // Usb Device URB related information // - USB_ENDPOINT Ep; - EFI_USB_DEVICE_REQUEST *Request; - VOID *Data; - UINTN DataLen; - VOID *DataPhy; - VOID *DataMap; - EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; - VOID *Context; + USB_ENDPOINT Ep; + EFI_USB_DEVICE_REQUEST *Request; + VOID *Data; + UINTN DataLen; + VOID *DataPhy; + VOID *DataMap; + EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; + VOID *Context; // // Execute result // - UINT32 Result; + UINT32 Result; // // completed data length // - UINTN Completed; + UINTN Completed; // // Command/Tranfer Ring info // - TRANSFER_RING *Ring; - TRB_TEMPLATE *TrbStart; - TRB_TEMPLATE *TrbEnd; - UINTN TrbNum; - BOOLEAN StartDone; - BOOLEAN EndDone; - BOOLEAN Finished; - - TRB_TEMPLATE *EvtTrb; + TRANSFER_RING *Ring; + TRB_TEMPLATE *TrbStart; + TRB_TEMPLATE *TrbEnd; + UINTN TrbNum; + BOOLEAN StartDone; + BOOLEAN EndDone; + BOOLEAN Finished; + + TRB_TEMPLATE *EvtTrb; } URB; // @@ -203,11 +203,11 @@ typedef struct _URB { // is defined by the Event Ring Segment Table Base Size Register (5.5.2.3.1). // typedef struct _EVENT_RING_SEG_TABLE_ENTRY { - UINT32 PtrLo; - UINT32 PtrHi; - UINT32 RingTrbSize:16; - UINT32 RsvdZ1:16; - UINT32 RsvdZ2; + UINT32 PtrLo; + UINT32 PtrHi; + UINT32 RingTrbSize : 16; + UINT32 RsvdZ1 : 16; + UINT32 RsvdZ2; } EVENT_RING_SEG_TABLE_ENTRY; // @@ -217,25 +217,25 @@ typedef struct _EVENT_RING_SEG_TABLE_ENTRY { // Rings, and to define the Data stage information for Control Transfer Rings. // typedef struct _TRANSFER_TRB_NORMAL { - UINT32 TRBPtrLo; - - UINT32 TRBPtrHi; - - UINT32 Length:17; - UINT32 TDSize:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 ISP:1; - UINT32 NS:1; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ1:2; - UINT32 BEI:1; - UINT32 Type:6; - UINT32 RsvdZ2:16; + UINT32 TRBPtrLo; + + UINT32 TRBPtrHi; + + UINT32 Length : 17; + UINT32 TDSize : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 ISP : 1; + UINT32 NS : 1; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ1 : 2; + UINT32 BEI : 1; + UINT32 Type : 6; + UINT32 RsvdZ2 : 16; } TRANSFER_TRB_NORMAL; // @@ -243,25 +243,25 @@ typedef struct _TRANSFER_TRB_NORMAL { // A Setup Stage TRB is created by system software to initiate a USB Setup packet on a control endpoint. // typedef struct _TRANSFER_TRB_CONTROL_SETUP { - UINT32 bmRequestType:8; - UINT32 bRequest:8; - UINT32 wValue:16; - - UINT32 wIndex:16; - UINT32 wLength:16; - - UINT32 Length:17; - UINT32 RsvdZ1:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 RsvdZ2:4; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ3:3; - UINT32 Type:6; - UINT32 TRT:2; - UINT32 RsvdZ4:14; + UINT32 bmRequestType : 8; + UINT32 bRequest : 8; + UINT32 wValue : 16; + + UINT32 wIndex : 16; + UINT32 wLength : 16; + + UINT32 Length : 17; + UINT32 RsvdZ1 : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 4; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ3 : 3; + UINT32 Type : 6; + UINT32 TRT : 2; + UINT32 RsvdZ4 : 14; } TRANSFER_TRB_CONTROL_SETUP; // @@ -269,25 +269,25 @@ typedef struct _TRANSFER_TRB_CONTROL_SETUP { // A Data Stage TRB is used generate the Data stage transaction of a USB Control transfer. // typedef struct _TRANSFER_TRB_CONTROL_DATA { - UINT32 TRBPtrLo; - - UINT32 TRBPtrHi; - - UINT32 Length:17; - UINT32 TDSize:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 ISP:1; - UINT32 NS:1; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ1:3; - UINT32 Type:6; - UINT32 DIR:1; - UINT32 RsvdZ2:15; + UINT32 TRBPtrLo; + + UINT32 TRBPtrHi; + + UINT32 Length : 17; + UINT32 TDSize : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 ISP : 1; + UINT32 NS : 1; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ1 : 3; + UINT32 Type : 6; + UINT32 DIR : 1; + UINT32 RsvdZ2 : 15; } TRANSFER_TRB_CONTROL_DATA; // @@ -295,21 +295,21 @@ typedef struct _TRANSFER_TRB_CONTROL_DATA { // A Data Stage TRB is used generate the Data stage transaction of a USB Control transfer. // typedef struct _TRANSFER_TRB_CONTROL_STATUS { - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 RsvdZ3:22; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 RsvdZ4:2; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 RsvdZ5:4; - UINT32 Type:6; - UINT32 DIR:1; - UINT32 RsvdZ6:15; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 RsvdZ3 : 22; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 RsvdZ4 : 2; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 RsvdZ5 : 4; + UINT32 Type : 6; + UINT32 DIR : 1; + UINT32 RsvdZ6 : 15; } TRANSFER_TRB_CONTROL_STATUS; // @@ -318,21 +318,21 @@ typedef struct _TRANSFER_TRB_CONTROL_STATUS { // for more information on the use and operation of Transfer Events. // typedef struct _EVT_TRB_TRANSFER { - UINT32 TRBPtrLo; + UINT32 TRBPtrLo; - UINT32 TRBPtrHi; + UINT32 TRBPtrHi; - UINT32 Length:24; - UINT32 Completecode:8; + UINT32 Length : 24; + UINT32 Completecode : 8; - UINT32 CycleBit:1; - UINT32 RsvdZ1:1; - UINT32 ED:1; - UINT32 RsvdZ2:7; - UINT32 Type:6; - UINT32 EndpointId:5; - UINT32 RsvdZ3:3; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ1 : 1; + UINT32 ED : 1; + UINT32 RsvdZ2 : 7; + UINT32 Type : 6; + UINT32 EndpointId : 5; + UINT32 RsvdZ3 : 3; + UINT32 SlotId : 8; } EVT_TRB_TRANSFER; // @@ -341,26 +341,26 @@ typedef struct _EVT_TRB_TRANSFER { // Command Ring. Refer to section 4.11.4 for more information on the use of Command Completion Events. // typedef struct _EVT_TRB_COMMAND_COMPLETION { - UINT32 TRBPtrLo; + UINT32 TRBPtrLo; - UINT32 TRBPtrHi; + UINT32 TRBPtrHi; - UINT32 RsvdZ2:24; - UINT32 Completecode:8; + UINT32 RsvdZ2 : 24; + UINT32 Completecode : 8; - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 VFID:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 VFID : 8; + UINT32 SlotId : 8; } EVT_TRB_COMMAND_COMPLETION; typedef union _TRB { - TRB_TEMPLATE TrbTemplate; - TRANSFER_TRB_NORMAL TrbNormal; - TRANSFER_TRB_CONTROL_SETUP TrbCtrSetup; - TRANSFER_TRB_CONTROL_DATA TrbCtrData; - TRANSFER_TRB_CONTROL_STATUS TrbCtrStatus; + TRB_TEMPLATE TrbTemplate; + TRANSFER_TRB_NORMAL TrbNormal; + TRANSFER_TRB_CONTROL_SETUP TrbCtrSetup; + TRANSFER_TRB_CONTROL_DATA TrbCtrData; + TRANSFER_TRB_CONTROL_STATUS TrbCtrStatus; } TRB; // @@ -369,14 +369,14 @@ typedef union _TRB { // mechanisms offered by the xHCI. // typedef struct _CMD_TRB_NO_OP { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } CMD_TRB_NO_OP; // @@ -385,14 +385,14 @@ typedef struct _CMD_TRB_NO_OP { // selected slot to the host in a Command Completion Event. // typedef struct _CMD_TRB_ENABLE_SLOT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } CMD_TRB_ENABLE_SLOT; // @@ -401,15 +401,15 @@ typedef struct _CMD_TRB_ENABLE_SLOT { // internal xHC resources assigned to the slot. // typedef struct _CMD_TRB_DISABLE_SLOT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:8; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 8; + UINT32 SlotId : 8; } CMD_TRB_DISABLE_SLOT; // @@ -419,18 +419,18 @@ typedef struct _CMD_TRB_DISABLE_SLOT { // issue a SET_ADDRESS request to the USB device. // typedef struct _CMD_TRB_ADDRESS_DEVICE { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:8; - UINT32 BSR:1; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 8; + UINT32 BSR : 1; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_ADDRESS_DEVICE; // @@ -439,18 +439,18 @@ typedef struct _CMD_TRB_ADDRESS_DEVICE { // endpoints selected by the command. // typedef struct _CMD_TRB_CONFIG_ENDPOINT { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:8; - UINT32 DC:1; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 8; + UINT32 DC : 1; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_CONFIG_ENDPOINT; // @@ -460,17 +460,17 @@ typedef struct _CMD_TRB_CONFIG_ENDPOINT { // shall evaluate any changes // typedef struct _CMD_TRB_EVALUATE_CONTEXT { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:9; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 9; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_EVALUATE_CONTEXT; // @@ -478,17 +478,17 @@ typedef struct _CMD_TRB_EVALUATE_CONTEXT { // The Reset Endpoint Command TRB is used by system software to reset a specified Transfer Ring // typedef struct _CMD_TRB_RESET_ENDPOINT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:8; - UINT32 TSP:1; - UINT32 Type:6; - UINT32 EDID:5; - UINT32 RsvdZ4:3; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 8; + UINT32 TSP : 1; + UINT32 Type : 6; + UINT32 EDID : 5; + UINT32 RsvdZ4 : 3; + UINT32 SlotId : 8; } CMD_TRB_RESET_ENDPOINT; // @@ -497,17 +497,17 @@ typedef struct _CMD_TRB_RESET_ENDPOINT { // Transfer Ring and temporarily take ownership of TDs that had previously been passed to the xHC. // typedef struct _CMD_TRB_STOP_ENDPOINT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 EDID:5; - UINT32 RsvdZ4:2; - UINT32 SP:1; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 EDID : 5; + UINT32 RsvdZ4 : 2; + UINT32 SP : 1; + UINT32 SlotId : 8; } CMD_TRB_STOP_ENDPOINT; // @@ -516,19 +516,19 @@ typedef struct _CMD_TRB_STOP_ENDPOINT { // Pointer and DCS fields of an Endpoint or Stream Context. // typedef struct _CMD_SET_TR_DEQ_POINTER { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1:16; - UINT32 StreamID:16; + UINT32 RsvdZ1 : 16; + UINT32 StreamID : 16; - UINT32 CycleBit:1; - UINT32 RsvdZ2:9; - UINT32 Type:6; - UINT32 Endpoint:5; - UINT32 RsvdZ3:3; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 9; + UINT32 Type : 6; + UINT32 Endpoint : 5; + UINT32 RsvdZ3 : 3; + UINT32 SlotId : 8; } CMD_SET_TR_DEQ_POINTER; // @@ -536,211 +536,207 @@ typedef struct _CMD_SET_TR_DEQ_POINTER { // A Link TRB provides support for non-contiguous TRB Rings. // typedef struct _LINK_TRB { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1:22; - UINT32 InterTarget:10; + UINT32 RsvdZ1 : 22; + UINT32 InterTarget : 10; - UINT32 CycleBit:1; - UINT32 TC:1; - UINT32 RsvdZ2:2; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 RsvdZ3:4; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 CycleBit : 1; + UINT32 TC : 1; + UINT32 RsvdZ2 : 2; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 RsvdZ3 : 4; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } LINK_TRB; // // 6.2.2 Slot Context // typedef struct _SLOT_CONTEXT { - UINT32 RouteString:20; - UINT32 Speed:4; - UINT32 RsvdZ1:1; - UINT32 MTT:1; - UINT32 Hub:1; - UINT32 ContextEntries:5; - - UINT32 MaxExitLatency:16; - UINT32 RootHubPortNum:8; - UINT32 PortNum:8; - - UINT32 TTHubSlotId:8; - UINT32 TTPortNum:8; - UINT32 TTT:2; - UINT32 RsvdZ2:4; - UINT32 InterTarget:10; - - UINT32 DeviceAddress:8; - UINT32 RsvdZ3:19; - UINT32 SlotState:5; - - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; + UINT32 RouteString : 20; + UINT32 Speed : 4; + UINT32 RsvdZ1 : 1; + UINT32 MTT : 1; + UINT32 Hub : 1; + UINT32 ContextEntries : 5; + + UINT32 MaxExitLatency : 16; + UINT32 RootHubPortNum : 8; + UINT32 PortNum : 8; + + UINT32 TTHubSlotId : 8; + UINT32 TTPortNum : 8; + UINT32 TTT : 2; + UINT32 RsvdZ2 : 4; + UINT32 InterTarget : 10; + + UINT32 DeviceAddress : 8; + UINT32 RsvdZ3 : 19; + UINT32 SlotState : 5; + + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; } SLOT_CONTEXT; typedef struct _SLOT_CONTEXT_64 { - UINT32 RouteString:20; - UINT32 Speed:4; - UINT32 RsvdZ1:1; - UINT32 MTT:1; - UINT32 Hub:1; - UINT32 ContextEntries:5; - - UINT32 MaxExitLatency:16; - UINT32 RootHubPortNum:8; - UINT32 PortNum:8; - - UINT32 TTHubSlotId:8; - UINT32 TTPortNum:8; - UINT32 TTT:2; - UINT32 RsvdZ2:4; - UINT32 InterTarget:10; - - UINT32 DeviceAddress:8; - UINT32 RsvdZ3:19; - UINT32 SlotState:5; - - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; - UINT32 RsvdZ15; - + UINT32 RouteString : 20; + UINT32 Speed : 4; + UINT32 RsvdZ1 : 1; + UINT32 MTT : 1; + UINT32 Hub : 1; + UINT32 ContextEntries : 5; + + UINT32 MaxExitLatency : 16; + UINT32 RootHubPortNum : 8; + UINT32 PortNum : 8; + + UINT32 TTHubSlotId : 8; + UINT32 TTPortNum : 8; + UINT32 TTT : 2; + UINT32 RsvdZ2 : 4; + UINT32 InterTarget : 10; + + UINT32 DeviceAddress : 8; + UINT32 RsvdZ3 : 19; + UINT32 SlotState : 5; + + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; + UINT32 RsvdZ15; } SLOT_CONTEXT_64; - // // 6.2.3 Endpoint Context // typedef struct _ENDPOINT_CONTEXT { - UINT32 EPState:3; - UINT32 RsvdZ1:5; - UINT32 Mult:2; - UINT32 MaxPStreams:5; - UINT32 LSA:1; - UINT32 Interval:8; - UINT32 RsvdZ2:8; - - UINT32 RsvdZ3:1; - UINT32 CErr:2; - UINT32 EPType:3; - UINT32 RsvdZ4:1; - UINT32 HID:1; - UINT32 MaxBurstSize:8; - UINT32 MaxPacketSize:16; - - UINT32 PtrLo; - - UINT32 PtrHi; - - UINT32 AverageTRBLength:16; - UINT32 MaxESITPayload:16; - - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; + UINT32 EPState : 3; + UINT32 RsvdZ1 : 5; + UINT32 Mult : 2; + UINT32 MaxPStreams : 5; + UINT32 LSA : 1; + UINT32 Interval : 8; + UINT32 RsvdZ2 : 8; + + UINT32 RsvdZ3 : 1; + UINT32 CErr : 2; + UINT32 EPType : 3; + UINT32 RsvdZ4 : 1; + UINT32 HID : 1; + UINT32 MaxBurstSize : 8; + UINT32 MaxPacketSize : 16; + + UINT32 PtrLo; + + UINT32 PtrHi; + + UINT32 AverageTRBLength : 16; + UINT32 MaxESITPayload : 16; + + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; } ENDPOINT_CONTEXT; typedef struct _ENDPOINT_CONTEXT_64 { - UINT32 EPState:3; - UINT32 RsvdZ1:5; - UINT32 Mult:2; - UINT32 MaxPStreams:5; - UINT32 LSA:1; - UINT32 Interval:8; - UINT32 RsvdZ2:8; - - UINT32 RsvdZ3:1; - UINT32 CErr:2; - UINT32 EPType:3; - UINT32 RsvdZ4:1; - UINT32 HID:1; - UINT32 MaxBurstSize:8; - UINT32 MaxPacketSize:16; - - UINT32 PtrLo; - - UINT32 PtrHi; - - UINT32 AverageTRBLength:16; - UINT32 MaxESITPayload:16; - - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; - UINT32 RsvdZ15; - + UINT32 EPState : 3; + UINT32 RsvdZ1 : 5; + UINT32 Mult : 2; + UINT32 MaxPStreams : 5; + UINT32 LSA : 1; + UINT32 Interval : 8; + UINT32 RsvdZ2 : 8; + + UINT32 RsvdZ3 : 1; + UINT32 CErr : 2; + UINT32 EPType : 3; + UINT32 RsvdZ4 : 1; + UINT32 HID : 1; + UINT32 MaxBurstSize : 8; + UINT32 MaxPacketSize : 16; + + UINT32 PtrLo; + + UINT32 PtrHi; + + UINT32 AverageTRBLength : 16; + UINT32 MaxESITPayload : 16; + + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; + UINT32 RsvdZ15; } ENDPOINT_CONTEXT_64; - // // 6.2.5.1 Input Control Context // typedef struct _INPUT_CONTRL_CONTEXT { - UINT32 Dword1; - UINT32 Dword2; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - UINT32 RsvdZ3; - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; + UINT32 Dword1; + UINT32 Dword2; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + UINT32 RsvdZ3; + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; } INPUT_CONTRL_CONTEXT; typedef struct _INPUT_CONTRL_CONTEXT_64 { - UINT32 Dword1; - UINT32 Dword2; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - UINT32 RsvdZ3; - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; + UINT32 Dword1; + UINT32 Dword2; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + UINT32 RsvdZ3; + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; } INPUT_CONTRL_CONTEXT_64; // // 6.2.1 Device Context // typedef struct _DEVICE_CONTEXT { - SLOT_CONTEXT Slot; - ENDPOINT_CONTEXT EP[31]; + SLOT_CONTEXT Slot; + ENDPOINT_CONTEXT EP[31]; } DEVICE_CONTEXT; typedef struct _DEVICE_CONTEXT_64 { - SLOT_CONTEXT_64 Slot; - ENDPOINT_CONTEXT_64 EP[31]; + SLOT_CONTEXT_64 Slot; + ENDPOINT_CONTEXT_64 EP[31]; } DEVICE_CONTEXT_64; // @@ -753,12 +749,11 @@ typedef struct _INPUT_CONTEXT { } INPUT_CONTEXT; typedef struct _INPUT_CONTEXT_64 { - INPUT_CONTRL_CONTEXT_64 InputControlContext; - SLOT_CONTEXT_64 Slot; - ENDPOINT_CONTEXT_64 EP[31]; + INPUT_CONTRL_CONTEXT_64 InputControlContext; + SLOT_CONTEXT_64 Slot; + ENDPOINT_CONTEXT_64 EP[31]; } INPUT_CONTEXT_64; - /** Initialize the XHCI host controller for schedule. @@ -767,7 +762,7 @@ typedef struct _INPUT_CONTEXT_64 { **/ VOID XhcInitSched ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -778,7 +773,7 @@ XhcInitSched ( **/ VOID XhcFreeSched ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -792,8 +787,8 @@ XhcFreeSched ( **/ EFI_STATUS RingIntTransferDoorBell ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ); /** @@ -811,10 +806,10 @@ RingIntTransferDoorBell ( **/ EFI_STATUS XhcExecTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN BOOLEAN CmdTransfer, - IN URB *Urb, - IN UINTN Timeout + IN USB_XHCI_INSTANCE *Xhc, + IN BOOLEAN CmdTransfer, + IN URB *Urb, + IN UINTN Timeout ); /** @@ -831,9 +826,9 @@ XhcExecTransfer ( **/ EFI_STATUS XhciDelAsyncIntTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpNum + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpNum ); /** @@ -844,7 +839,7 @@ XhciDelAsyncIntTransfer ( **/ VOID XhciDelAllAsyncIntTransfers ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -865,14 +860,14 @@ XhciDelAllAsyncIntTransfers ( **/ URB * XhciInsertAsyncIntTransfer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ); /** @@ -883,7 +878,7 @@ XhciInsertAsyncIntTransfer ( **/ VOID XhcSetBiosOwnership ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -894,7 +889,7 @@ XhcSetBiosOwnership ( **/ VOID XhcClearBiosOwnership ( - IN USB_XHCI_INSTANCE *Xhc + IN USB_XHCI_INSTANCE *Xhc ); /** @@ -924,8 +919,8 @@ XhcRouteStringToSlotId ( **/ UINT8 XhcEndpointToDci ( - IN UINT8 EpAddr, - IN UINT8 Direction + IN UINT8 EpAddr, + IN UINT8 Direction ); /** @@ -941,9 +936,9 @@ XhcEndpointToDci ( EFI_STATUS EFIAPI XhcRingDoorBell ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ); /** @@ -956,8 +951,8 @@ XhcRingDoorBell ( VOID EFIAPI XhcMonitorAsyncRequests ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -975,10 +970,10 @@ XhcMonitorAsyncRequests ( EFI_STATUS EFIAPI XhcPollPortStatusChange ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT8 Port, - IN EFI_USB_PORT_STATUS *PortState + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT8 Port, + IN EFI_USB_PORT_STATUS *PortState ); /** @@ -995,14 +990,13 @@ XhcPollPortStatusChange ( **/ EFI_STATUS XhcConfigHubContext ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ); - /** Evaluate the slot context for hub device through XHCI's Configure_Endpoint cmd. @@ -1017,14 +1011,13 @@ XhcConfigHubContext ( **/ EFI_STATUS XhcConfigHubContext64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ); - /** Configure all the device endpoints through XHCI's Configure_Endpoint cmd. @@ -1039,13 +1032,12 @@ XhcConfigHubContext64 ( EFI_STATUS EFIAPI XhcSetConfigCmd ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ); - /** Configure all the device endpoints through XHCI's Configure_Endpoint cmd. @@ -1060,10 +1052,10 @@ XhcSetConfigCmd ( EFI_STATUS EFIAPI XhcSetConfigCmd64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ); /** @@ -1081,11 +1073,11 @@ XhcSetConfigCmd64 ( EFI_STATUS EFIAPI XhcSetInterface ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc, - IN EFI_USB_DEVICE_REQUEST *Request + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc, + IN EFI_USB_DEVICE_REQUEST *Request ); /** @@ -1103,11 +1095,11 @@ XhcSetInterface ( EFI_STATUS EFIAPI XhcSetInterface64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc, - IN EFI_USB_DEVICE_REQUEST *Request + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc, + IN EFI_USB_DEVICE_REQUEST *Request ); /** @@ -1141,11 +1133,11 @@ XhcBusDevAddrToSlotId ( EFI_STATUS EFIAPI XhcInitializeDeviceSlot ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ); /** @@ -1163,11 +1155,11 @@ XhcInitializeDeviceSlot ( EFI_STATUS EFIAPI XhcInitializeDeviceSlot64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN USB_XHCI_INSTANCE *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ); /** @@ -1183,12 +1175,11 @@ XhcInitializeDeviceSlot64 ( EFI_STATUS EFIAPI XhcEvaluateContext ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ); - /** Evaluate the endpoint 0 context through XHCI's Evaluate_Context cmd. @@ -1202,12 +1193,11 @@ XhcEvaluateContext ( EFI_STATUS EFIAPI XhcEvaluateContext64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ); - /** Disable the specified device slot. @@ -1220,11 +1210,10 @@ XhcEvaluateContext64 ( EFI_STATUS EFIAPI XhcDisableSlotCmd ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId ); - /** Disable the specified device slot. @@ -1237,11 +1226,10 @@ XhcDisableSlotCmd ( EFI_STATUS EFIAPI XhcDisableSlotCmd64 ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId ); - /** Synchronize the specified transfer ring to update the enqueue and dequeue pointer. @@ -1254,8 +1242,8 @@ XhcDisableSlotCmd64 ( EFI_STATUS EFIAPI XhcSyncTrsRing ( - IN USB_XHCI_INSTANCE *Xhc, - TRANSFER_RING *TrsRing + IN USB_XHCI_INSTANCE *Xhc, + TRANSFER_RING *TrsRing ); /** @@ -1270,8 +1258,8 @@ XhcSyncTrsRing ( EFI_STATUS EFIAPI XhcSyncEventRing ( - IN USB_XHCI_INSTANCE *Xhc, - EVENT_RING *EvtRing + IN USB_XHCI_INSTANCE *Xhc, + EVENT_RING *EvtRing ); /** @@ -1288,9 +1276,9 @@ XhcSyncEventRing ( EFI_STATUS EFIAPI XhcCheckNewEvent ( - IN USB_XHCI_INSTANCE *Xhc, - IN EVENT_RING *EvtRing, - OUT TRB_TEMPLATE **NewEvtTrb + IN USB_XHCI_INSTANCE *Xhc, + IN EVENT_RING *EvtRing, + OUT TRB_TEMPLATE **NewEvtTrb ); /** @@ -1303,9 +1291,9 @@ XhcCheckNewEvent ( **/ VOID CreateTransferRing ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINTN TrbNum, - OUT TRANSFER_RING *TransferRing + IN USB_XHCI_INSTANCE *Xhc, + IN UINTN TrbNum, + OUT TRANSFER_RING *TransferRing ); /** @@ -1317,8 +1305,8 @@ CreateTransferRing ( **/ VOID CreateEventRing ( - IN USB_XHCI_INSTANCE *Xhc, - OUT EVENT_RING *EventRing + IN USB_XHCI_INSTANCE *Xhc, + OUT EVENT_RING *EventRing ); /** @@ -1338,8 +1326,8 @@ CreateEventRing ( EFI_STATUS EFIAPI XhcRecoverHaltedEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ); /** @@ -1358,8 +1346,8 @@ XhcRecoverHaltedEndpoint ( EFI_STATUS EFIAPI XhcDequeueTrbFromEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ); /** @@ -1377,10 +1365,10 @@ XhcDequeueTrbFromEndpoint ( EFI_STATUS EFIAPI XhcStopEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *PendingUrb OPTIONAL + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *PendingUrb OPTIONAL ); /** @@ -1397,9 +1385,9 @@ XhcStopEndpoint ( EFI_STATUS EFIAPI XhcResetEndpoint ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ); /** @@ -1418,10 +1406,10 @@ XhcResetEndpoint ( EFI_STATUS EFIAPI XhcSetTrDequeuePointer ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *Urb ); /** @@ -1442,19 +1430,19 @@ XhcSetTrDequeuePointer ( @return Created URB or NULL **/ -URB* +URB * XhcCreateUrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN USB_XHCI_INSTANCE *Xhc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ); /** @@ -1466,8 +1454,8 @@ XhcCreateUrb ( **/ VOID XhcFreeUrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ); /** @@ -1481,8 +1469,8 @@ XhcFreeUrb ( **/ EFI_STATUS XhcCreateTransferTrb ( - IN USB_XHCI_INSTANCE *Xhc, - IN URB *Urb + IN USB_XHCI_INSTANCE *Xhc, + IN URB *Urb ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciPei/DmaMem.c b/MdeModulePkg/Bus/Pci/XhciPei/DmaMem.c index c4d93aea25..c8e49e1864 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/DmaMem.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/DmaMem.c @@ -32,11 +32,11 @@ EDKII_IOMMU_PPI *mIoMmu; **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { EFI_STATUS Status; @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -81,9 +83,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,7 +101,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { EFI_STATUS Status; @@ -109,6 +112,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -142,7 +146,7 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; if (mIoMmu != NULL) { @@ -157,18 +161,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = mIoMmu->Map ( - mIoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = mIoMmu->Map ( + mIoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -186,10 +191,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -207,9 +214,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { EFI_STATUS Status; @@ -221,6 +228,7 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -286,9 +294,10 @@ IoMmuAllocateAlignedBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Memory = *HostAddress; - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; - UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). @@ -296,11 +305,13 @@ IoMmuAllocateAlignedBuffer ( Status = mIoMmu->FreeBuffer ( mIoMmu, UnalignedPages, - Memory); + Memory + ); if (EFI_ERROR (Status)) { return Status; } } + Memory = (VOID *)(UINTN)(AlignedMemory + EFI_PAGES_TO_SIZE (Pages)); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -310,24 +321,27 @@ IoMmuAllocateAlignedBuffer ( Status = mIoMmu->FreeBuffer ( mIoMmu, UnalignedPages, - Memory); + Memory + ); if (EFI_ERROR (Status)) { return Status; } } - *HostAddress = (VOID *) AlignedMemory; - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = mIoMmu->Map ( - mIoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + + *HostAddress = (VOID *)AlignedMemory; + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = mIoMmu->Map ( + mIoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -345,10 +359,12 @@ IoMmuAllocateAlignedBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(((UINTN) HostPhyAddress + AlignmentMask) & ~AlignmentMask); - *DeviceAddress = ((UINTN) HostPhyAddress + AlignmentMask) & ~AlignmentMask; - *Mapping = NULL; + + *HostAddress = (VOID *)(((UINTN)HostPhyAddress + AlignmentMask) & ~AlignmentMask); + *DeviceAddress = ((UINTN)HostPhyAddress + AlignmentMask) & ~AlignmentMask; + *Mapping = NULL; } + return Status; } @@ -367,4 +383,3 @@ IoMmuInit ( (VOID **)&mIoMmu ); } - diff --git a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c index 01f4228537..c64b38fcfc 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c @@ -20,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USBHC_MEM_BLOCK * UsbHcAllocMemBlock ( - IN UINTN Pages + IN UINTN Pages ) { USBHC_MEM_BLOCK *Block; @@ -32,16 +32,17 @@ UsbHcAllocMemBlock ( EFI_PHYSICAL_ADDRESS TempPtr; PageNumber = EFI_SIZE_TO_PAGES (sizeof (USBHC_MEM_BLOCK)); - Status = PeiServicesAllocatePages ( - EfiBootServicesData, - PageNumber, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + PageNumber, + &TempPtr + ); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID *) (UINTN) TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); + + ZeroMem ((VOID *)(UINTN)TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); // // each bit in the bit array represents USBHC_MEM_UNIT @@ -49,23 +50,24 @@ UsbHcAllocMemBlock ( // ASSERT (USBHC_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block = (USBHC_MEM_BLOCK *) (UINTN) TempPtr; - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block = (USBHC_MEM_BLOCK *)(UINTN)TempPtr; + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); Block->BitsLen = Block->BufLen / (USBHC_MEM_UNIT * 8); PageNumber = EFI_SIZE_TO_PAGES (Block->BitsLen); - Status = PeiServicesAllocatePages ( - EfiBootServicesData, - PageNumber, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + PageNumber, + &TempPtr + ); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID *) (UINTN) TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); - Block->Bits = (UINT8 *) (UINTN) TempPtr; + ZeroMem ((VOID *)(UINTN)TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); + + Block->Bits = (UINT8 *)(UINTN)TempPtr; Status = IoMmuAllocateBuffer ( Pages, @@ -76,12 +78,13 @@ UsbHcAllocMemBlock ( if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID *) (UINTN) BufHost, EFI_PAGES_TO_SIZE (Pages)); - Block->BufHost = (UINT8 *) (UINTN) BufHost; - Block->Buf = (UINT8 *) (UINTN) MappedAddr; - Block->Mapping = Mapping; - Block->Next = NULL; + ZeroMem ((VOID *)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); + + Block->BufHost = (UINT8 *)(UINTN)BufHost; + Block->Buf = (UINT8 *)(UINTN)MappedAddr; + Block->Mapping = Mapping; + Block->Next = NULL; return Block; } @@ -95,8 +98,8 @@ UsbHcAllocMemBlock ( **/ VOID UsbHcFreeMemBlock ( - IN USBHC_MEM_POOL *Pool, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_POOL *Pool, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Pool != NULL) && (Block != NULL)); @@ -120,22 +123,22 @@ UsbHcFreeMemBlock ( **/ VOID * UsbHcAllocMemFromBlock ( - IN USBHC_MEM_BLOCK *Block, - IN UINTN Units + IN USBHC_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -154,9 +157,9 @@ UsbHcAllocMemFromBlock ( } else { NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -167,13 +170,13 @@ UsbHcAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -192,9 +195,9 @@ UsbHcAllocMemFromBlock ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddrForHostAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { USBHC_MEM_BLOCK *Head; @@ -215,7 +218,7 @@ UsbHcGetPciAddrForHostAddr ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->BufHost <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { + if ((Block->BufHost <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->BufHost + Block->BufLen))) { break; } } @@ -224,8 +227,8 @@ UsbHcGetPciAddrForHostAddr ( // // calculate the pci memory address for host memory address. // - Offset = (UINT8 *) Mem - Block->BufHost; - PhyAddr = (EFI_PHYSICAL_ADDRESS) (UINTN) (Block->Buf + Offset); + Offset = (UINT8 *)Mem - Block->BufHost; + PhyAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->Buf + Offset); return PhyAddr; } @@ -241,9 +244,9 @@ UsbHcGetPciAddrForHostAddr ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetHostAddrForPciAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { USBHC_MEM_BLOCK *Head; @@ -264,7 +267,7 @@ UsbHcGetHostAddrForPciAddr ( // scan the memory block list for the memory block that // completely contains the allocated memory. // - if ((Block->Buf <= (UINT8 *) Mem) && (((UINT8 *) Mem + AllocSize) <= (Block->Buf + Block->BufLen))) { + if ((Block->Buf <= (UINT8 *)Mem) && (((UINT8 *)Mem + AllocSize) <= (Block->Buf + Block->BufLen))) { break; } } @@ -273,8 +276,8 @@ UsbHcGetHostAddrForPciAddr ( // // calculate the host memory address for pci memory address. // - Offset = (UINT8 *) Mem - Block->Buf; - HostAddr = (EFI_PHYSICAL_ADDRESS) (UINTN) (Block->BufHost + Offset); + Offset = (UINT8 *)Mem - Block->Buf; + HostAddr = (EFI_PHYSICAL_ADDRESS)(UINTN)(Block->BufHost + Offset); return HostAddr; } @@ -287,8 +290,8 @@ UsbHcGetHostAddrForPciAddr ( **/ VOID UsbHcInsertMemBlockToPool ( - IN USBHC_MEM_BLOCK *Head, - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Head, + IN USBHC_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -307,10 +310,10 @@ UsbHcInsertMemBlockToPool ( **/ BOOLEAN UsbHcIsMemBlockEmpty ( - IN USBHC_MEM_BLOCK *Block + IN USBHC_MEM_BLOCK *Block ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -321,8 +324,6 @@ UsbHcIsMemBlockEmpty ( return TRUE; } - - /** Initialize the memory management pool for the host controller. @@ -340,17 +341,18 @@ UsbHcInitMemPool ( EFI_PHYSICAL_ADDRESS TempPtr; PageNumber = EFI_SIZE_TO_PAGES (sizeof (USBHC_MEM_POOL)); - Status = PeiServicesAllocatePages ( - EfiBootServicesData, - PageNumber, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + PageNumber, + &TempPtr + ); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID *) (UINTN) TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); - Pool = (USBHC_MEM_POOL *) ((UINTN) TempPtr); + ZeroMem ((VOID *)(UINTN)TempPtr, EFI_PAGES_TO_SIZE (PageNumber)); + + Pool = (USBHC_MEM_POOL *)((UINTN)TempPtr); Pool->Head = UsbHcAllocMemBlock (USBHC_MEM_DEFAULT_PAGES); if (Pool->Head == NULL) { @@ -371,10 +373,10 @@ UsbHcInitMemPool ( **/ VOID UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ) { - USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -384,7 +386,7 @@ UsbHcFreeMemPool ( // first block. // for (Block = Pool->Head->Next; Block != NULL; Block = Pool->Head->Next) { - //UsbHcUnlinkMemBlock (Pool->Head, Block); + // UsbHcUnlinkMemBlock (Pool->Head, Block); UsbHcFreeMemBlock (Pool, Block); } @@ -403,16 +405,16 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - USBHC_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + USBHC_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = USBHC_MEM_ROUND (Size); @@ -446,6 +448,7 @@ UsbHcAllocateMem ( } else { Pages = USBHC_MEM_DEFAULT_PAGES; } + NewBlock = UsbHcAllocMemBlock (Pages); if (NewBlock == NULL) { @@ -475,22 +478,22 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - USBHC_MEM_BLOCK *Head; - USBHC_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + USBHC_MEM_BLOCK *Head; + USBHC_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = USBHC_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -501,8 +504,8 @@ UsbHcFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; - Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; + Byte = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) / 8; + Bit = ((ToFree - Block->BufHost) / USBHC_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -510,7 +513,7 @@ UsbHcFreeMem ( for (Count = 0; Count < (AllocSize / USBHC_MEM_UNIT); Count++) { ASSERT (USB_HC_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ USB_HC_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ USB_HC_BIT (Bit)); NEXT_BIT (Byte, Bit); } @@ -529,7 +532,7 @@ UsbHcFreeMem ( // Release the current memory block if it is empty and not the head // if ((Block != Head) && UsbHcIsMemBlockEmpty (Block)) { - //UsbHcUnlinkMemBlock (Head, Block); + // UsbHcUnlinkMemBlock (Head, Block); UsbHcFreeMemBlock (Pool, Block); } } @@ -553,11 +556,11 @@ UsbHcFreeMem ( **/ EFI_STATUS UsbHcAllocateAlignedPages ( - IN UINTN Pages, - IN UINTN Alignment, - OUT VOID **HostAddress, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN UINTN Pages, + IN UINTN Alignment, + OUT VOID **HostAddress, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { EFI_STATUS Status; @@ -603,7 +606,7 @@ UsbHcAllocateAlignedPages ( } } - *HostAddress = Memory; + *HostAddress = Memory; *DeviceAddress = DeviceMemory; return EFI_SUCCESS; @@ -619,13 +622,12 @@ UsbHcAllocateAlignedPages ( **/ VOID UsbHcFreeAlignedPages ( - IN VOID *HostAddress, - IN UINTN Pages, - IN VOID *Mapping + IN VOID *HostAddress, + IN UINTN Pages, + IN VOID *Mapping ) { ASSERT (Pages != 0); IoMmuFreeBuffer (Pages, HostAddress, Mapping); } - diff --git a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h index 5aa41397f3..2b4c8b19fc 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h +++ b/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h @@ -12,29 +12,29 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define USBHC_MEM_DEFAULT_PAGES 16 +#define USBHC_MEM_DEFAULT_PAGES 16 typedef struct _USBHC_MEM_BLOCK USBHC_MEM_BLOCK; struct _USBHC_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - USBHC_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + USBHC_MEM_BLOCK *Next; }; // // Memory allocation unit, must be 2^n, n>4 // -#define USBHC_MEM_UNIT 64 +#define USBHC_MEM_UNIT 64 -#define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) -#define USBHC_MEM_ROUND(Len) (((Len) + USBHC_MEM_UNIT_MASK) & (~USBHC_MEM_UNIT_MASK)) +#define USBHC_MEM_UNIT_MASK (USBHC_MEM_UNIT - 1) +#define USBHC_MEM_ROUND(Len) (((Len) + USBHC_MEM_UNIT_MASK) & (~USBHC_MEM_UNIT_MASK)) -#define USB_HC_BIT(a) ((UINTN)(1 << (a))) +#define USB_HC_BIT(a) ((UINTN)(1 << (a))) #define USB_HC_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & USB_HC_BIT(Bit)) == USB_HC_BIT(Bit))) @@ -57,9 +57,9 @@ struct _USBHC_MEM_BLOCK { // data to be on the same 4G memory. // typedef struct _USBHC_MEM_POOL { - BOOLEAN Check4G; - UINT32 Which4G; - USBHC_MEM_BLOCK *Head; + BOOLEAN Check4G; + UINT32 Which4G; + USBHC_MEM_BLOCK *Head; } USBHC_MEM_POOL; /** @@ -74,9 +74,9 @@ typedef struct _USBHC_MEM_POOL { **/ EFI_PHYSICAL_ADDRESS UsbHcGetPciAddrForHostAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -91,9 +91,9 @@ UsbHcGetPciAddrForHostAddr ( **/ EFI_PHYSICAL_ADDRESS UsbHcGetHostAddrForPciAddr ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -115,11 +115,11 @@ UsbHcGetHostAddrForPciAddr ( **/ EFI_STATUS UsbHcAllocateAlignedPages ( - IN UINTN Pages, - IN UINTN Alignment, - OUT VOID **HostAddress, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN UINTN Pages, + IN UINTN Alignment, + OUT VOID **HostAddress, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -132,9 +132,9 @@ UsbHcAllocateAlignedPages ( **/ VOID UsbHcFreeAlignedPages ( - IN VOID *HostAddress, - IN UINTN Pages, - IN VOID *Mapping + IN VOID *HostAddress, + IN UINTN Pages, + IN VOID *Mapping ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.c b/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.c index 6bdf488413..301f376b04 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.c @@ -15,48 +15,48 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // to the UEFI protocol's port state (change). // USB_PORT_STATE_MAP mUsbPortStateMap[] = { - {XHC_PORTSC_CCS, USB_PORT_STAT_CONNECTION}, - {XHC_PORTSC_PED, USB_PORT_STAT_ENABLE}, - {XHC_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT}, - {XHC_PORTSC_PP, USB_PORT_STAT_POWER}, - {XHC_PORTSC_RESET, USB_PORT_STAT_RESET} + { XHC_PORTSC_CCS, USB_PORT_STAT_CONNECTION }, + { XHC_PORTSC_PED, USB_PORT_STAT_ENABLE }, + { XHC_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT }, + { XHC_PORTSC_PP, USB_PORT_STAT_POWER }, + { XHC_PORTSC_RESET, USB_PORT_STAT_RESET } }; USB_PORT_STATE_MAP mUsbPortChangeMap[] = { - {XHC_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION}, - {XHC_PORTSC_PEC, USB_PORT_STAT_C_ENABLE}, - {XHC_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT}, - {XHC_PORTSC_PRC, USB_PORT_STAT_C_RESET} + { XHC_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION }, + { XHC_PORTSC_PEC, USB_PORT_STAT_C_ENABLE }, + { XHC_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT }, + { XHC_PORTSC_PRC, USB_PORT_STAT_C_RESET } }; -USB_CLEAR_PORT_MAP mUsbClearPortChangeMap[] = { - {XHC_PORTSC_CSC, EfiUsbPortConnectChange}, - {XHC_PORTSC_PEC, EfiUsbPortEnableChange}, - {XHC_PORTSC_OCC, EfiUsbPortOverCurrentChange}, - {XHC_PORTSC_PRC, EfiUsbPortResetChange} +USB_CLEAR_PORT_MAP mUsbClearPortChangeMap[] = { + { XHC_PORTSC_CSC, EfiUsbPortConnectChange }, + { XHC_PORTSC_PEC, EfiUsbPortEnableChange }, + { XHC_PORTSC_OCC, EfiUsbPortOverCurrentChange }, + { XHC_PORTSC_PRC, EfiUsbPortResetChange } }; USB_PORT_STATE_MAP mUsbHubPortStateMap[] = { - {XHC_HUB_PORTSC_CCS, USB_PORT_STAT_CONNECTION}, - {XHC_HUB_PORTSC_PED, USB_PORT_STAT_ENABLE}, - {XHC_HUB_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT}, - {XHC_HUB_PORTSC_PP, USB_PORT_STAT_POWER}, - {XHC_HUB_PORTSC_RESET, USB_PORT_STAT_RESET} + { XHC_HUB_PORTSC_CCS, USB_PORT_STAT_CONNECTION }, + { XHC_HUB_PORTSC_PED, USB_PORT_STAT_ENABLE }, + { XHC_HUB_PORTSC_OCA, USB_PORT_STAT_OVERCURRENT }, + { XHC_HUB_PORTSC_PP, USB_PORT_STAT_POWER }, + { XHC_HUB_PORTSC_RESET, USB_PORT_STAT_RESET } }; USB_PORT_STATE_MAP mUsbHubPortChangeMap[] = { - {XHC_HUB_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION}, - {XHC_HUB_PORTSC_PEC, USB_PORT_STAT_C_ENABLE}, - {XHC_HUB_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT}, - {XHC_HUB_PORTSC_PRC, USB_PORT_STAT_C_RESET} + { XHC_HUB_PORTSC_CSC, USB_PORT_STAT_C_CONNECTION }, + { XHC_HUB_PORTSC_PEC, USB_PORT_STAT_C_ENABLE }, + { XHC_HUB_PORTSC_OCC, USB_PORT_STAT_C_OVERCURRENT }, + { XHC_HUB_PORTSC_PRC, USB_PORT_STAT_C_RESET } }; -USB_CLEAR_PORT_MAP mUsbHubClearPortChangeMap[] = { - {XHC_HUB_PORTSC_CSC, EfiUsbPortConnectChange}, - {XHC_HUB_PORTSC_PEC, EfiUsbPortEnableChange}, - {XHC_HUB_PORTSC_OCC, EfiUsbPortOverCurrentChange}, - {XHC_HUB_PORTSC_PRC, EfiUsbPortResetChange}, - {XHC_HUB_PORTSC_BHRC, Usb3PortBHPortResetChange} +USB_CLEAR_PORT_MAP mUsbHubClearPortChangeMap[] = { + { XHC_HUB_PORTSC_CSC, EfiUsbPortConnectChange }, + { XHC_HUB_PORTSC_PEC, EfiUsbPortEnableChange }, + { XHC_HUB_PORTSC_OCC, EfiUsbPortOverCurrentChange }, + { XHC_HUB_PORTSC_PRC, EfiUsbPortResetChange }, + { XHC_HUB_PORTSC_BHRC, Usb3PortBHPortResetChange } }; /** @@ -70,11 +70,11 @@ USB_CLEAR_PORT_MAP mUsbHubClearPortChangeMap[] = { **/ UINT32 XhcPeiReadOpReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; ASSERT (Xhc->CapLength != 0); @@ -92,9 +92,9 @@ XhcPeiReadOpReg ( **/ VOID XhcPeiWriteOpReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { ASSERT (Xhc->CapLength != 0); @@ -112,12 +112,12 @@ XhcPeiWriteOpReg ( **/ VOID XhcPeiSetOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcPeiReadOpReg (Xhc, Offset); Data |= Bit; @@ -134,12 +134,12 @@ XhcPeiSetOpRegBit ( **/ VOID XhcPeiClearOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcPeiReadOpReg (Xhc, Offset); Data &= ~Bit; @@ -162,14 +162,14 @@ XhcPeiClearOpRegBit ( **/ EFI_STATUS XhcPeiWaitOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ) { - UINT64 Index; + UINT64 Index; for (Index = 0; Index < Timeout * XHC_1_MILLISECOND; Index++) { if (XHC_REG_BIT_IS_SET (Xhc, Offset, Bit) == WaitToSet) { @@ -193,19 +193,17 @@ XhcPeiWaitOpRegBit ( **/ UINT32 XhcPeiReadCapRegister ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; Data = MmioRead32 (Xhc->UsbHostControllerBaseAddress + Offset); return Data; } - - /** Write the data to the XHCI door bell register. @@ -216,9 +214,9 @@ XhcPeiReadCapRegister ( **/ VOID XhcPeiWriteDoorBellReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { ASSERT (Xhc->DBOff != 0); @@ -237,11 +235,11 @@ XhcPeiWriteDoorBellReg ( **/ UINT32 XhcPeiReadRuntimeReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset ) { - UINT32 Data; + UINT32 Data; ASSERT (Xhc->RTSOff != 0); @@ -260,9 +258,9 @@ XhcPeiReadRuntimeReg ( **/ VOID XhcPeiWriteRuntimeReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ) { ASSERT (Xhc->RTSOff != 0); @@ -280,12 +278,12 @@ XhcPeiWriteRuntimeReg ( **/ VOID XhcPeiSetRuntimeRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcPeiReadRuntimeReg (Xhc, Offset); Data |= Bit; @@ -302,12 +300,12 @@ XhcPeiSetRuntimeRegBit ( **/ VOID XhcPeiClearRuntimeRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ) { - UINT32 Data; + UINT32 Data; Data = XhcPeiReadRuntimeReg (Xhc, Offset); Data &= ~Bit; @@ -325,7 +323,7 @@ XhcPeiClearRuntimeRegBit ( **/ BOOLEAN XhcPeiIsHalt ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ) { return XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT); @@ -342,7 +340,7 @@ XhcPeiIsHalt ( **/ BOOLEAN XhcPeiIsSysError ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ) { return XHC_REG_BIT_IS_SET (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HSE); @@ -360,11 +358,11 @@ XhcPeiIsSysError ( **/ EFI_STATUS XhcPeiResetHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Host can only be reset when it is halt. If not so, halt it @@ -402,11 +400,11 @@ ON_EXIT: **/ EFI_STATUS XhcPeiHaltHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; XhcPeiClearOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RUN); Status = XhcPeiWaitOpRegBit (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT, TRUE, Timeout); @@ -426,11 +424,11 @@ XhcPeiHaltHC ( **/ EFI_STATUS XhcPeiRunHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ) { - EFI_STATUS Status; + EFI_STATUS Status; XhcPeiSetOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RUN); Status = XhcPeiWaitOpRegBit (Xhc, XHC_USBSTS_OFFSET, XHC_USBSTS_HALT, FALSE, Timeout); @@ -467,37 +465,37 @@ XhcPeiRunHC ( EFI_STATUS EFIAPI XhcPeiControlTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 DeviceAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN EFI_USB_DEVICE_REQUEST *Request, - IN EFI_USB_DATA_DIRECTION TransferDirection, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN TimeOut, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION TransferDirection, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN TimeOut, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { - PEI_XHC_DEV *Xhc; - URB *Urb; - UINT8 Endpoint; - UINT8 Index; - UINT8 DescriptorType; - UINT8 SlotId; - UINT8 TTT; - UINT8 MTT; - UINT32 MaxPacket0; - EFI_USB_HUB_DESCRIPTOR *HubDesc; - EFI_STATUS Status; - EFI_STATUS RecoveryStatus; - UINTN MapSize; - EFI_USB_PORT_STATUS PortStatus; - UINT32 State; - EFI_USB_DEVICE_REQUEST ClearPortRequest; - UINTN Len; + PEI_XHC_DEV *Xhc; + URB *Urb; + UINT8 Endpoint; + UINT8 Index; + UINT8 DescriptorType; + UINT8 SlotId; + UINT8 TTT; + UINT8 MTT; + UINT32 MaxPacket0; + EFI_USB_HUB_DESCRIPTOR *HubDesc; + EFI_STATUS Status; + EFI_STATUS RecoveryStatus; + UINTN MapSize; + EFI_USB_PORT_STATUS PortStatus; + UINT32 State; + EFI_USB_DEVICE_REQUEST ClearPortRequest; + UINTN Len; // // Validate parameters @@ -508,24 +506,28 @@ XhcPeiControlTransfer ( if ((TransferDirection != EfiUsbDataIn) && (TransferDirection != EfiUsbDataOut) && - (TransferDirection != EfiUsbNoData)) { + (TransferDirection != EfiUsbNoData)) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection == EfiUsbNoData) && - ((Data != NULL) || (*DataLength != 0))) { + ((Data != NULL) || (*DataLength != 0))) + { return EFI_INVALID_PARAMETER; } if ((TransferDirection != EfiUsbNoData) && - ((Data == NULL) || (*DataLength == 0))) { + ((Data == NULL) || (*DataLength == 0))) + { return EFI_INVALID_PARAMETER; } if ((MaximumPacketLength != 8) && (MaximumPacketLength != 16) && (MaximumPacketLength != 32) && (MaximumPacketLength != 64) && (MaximumPacketLength != 512) - ) { + ) + { return EFI_INVALID_PARAMETER; } @@ -537,7 +539,7 @@ XhcPeiControlTransfer ( return EFI_INVALID_PARAMETER; } - Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); + Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); Status = EFI_DEVICE_ERROR; *TransferResult = EFI_USB_ERR_SYSTEM; @@ -561,7 +563,8 @@ XhcPeiControlTransfer ( // According to XHCI 1.0 spec, the Set_Address request is replaced by XHCI's Address_Device cmd. // if ((Request->Request == USB_REQ_SET_ADDRESS) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) + { // // Reset the BusDevAddr field of all disabled entries in UsbDevContext array firstly. // This way is used to clean the history to avoid using wrong device address afterwards. @@ -569,7 +572,8 @@ XhcPeiControlTransfer ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId == 0) && - (Xhc->UsbDevContext[Index + 1].BusDevAddr == (UINT8) Request->Value)) { + (Xhc->UsbDevContext[Index + 1].BusDevAddr == (UINT8)Request->Value)) + { Xhc->UsbDevContext[Index + 1].BusDevAddr = 0; } } @@ -577,14 +581,15 @@ XhcPeiControlTransfer ( if (Xhc->UsbDevContext[SlotId].XhciDevAddr == 0) { goto ON_EXIT; } + // // The actual device address has been assigned by XHCI during initializing the device slot. // So we just need establish the mapping relationship between the device address requested from UsbBus // and the actual device address assigned by XHCI. The following invocations through EFI_USB2_HC_PROTOCOL interface // can find out the actual device address by it. // - Xhc->UsbDevContext[SlotId].BusDevAddr = (UINT8) Request->Value; - Status = EFI_SUCCESS; + Xhc->UsbDevContext[SlotId].BusDevAddr = (UINT8)Request->Value; + Status = EFI_SUCCESS; goto ON_EXIT; } @@ -595,20 +600,20 @@ XhcPeiControlTransfer ( // endpoint is bidirectional. XhcPeiCreateUrb expects this // combination of Ep addr and its direction. // - Endpoint = (UINT8) (0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); - Urb = XhcPeiCreateUrb ( - Xhc, - DeviceAddress, - Endpoint, - DeviceSpeed, - MaximumPacketLength, - XHC_CTRL_TRANSFER, - Request, - Data, - *DataLength, - NULL, - NULL - ); + Endpoint = (UINT8)(0 | ((TransferDirection == EfiUsbDataIn) ? 0x80 : 0)); + Urb = XhcPeiCreateUrb ( + Xhc, + DeviceAddress, + Endpoint, + DeviceSpeed, + MaximumPacketLength, + XHC_CTRL_TRANSFER, + Request, + Data, + *DataLength, + NULL, + NULL + ); if (Urb == NULL) { DEBUG ((DEBUG_ERROR, "XhcPeiControlTransfer: failed to create URB")); @@ -629,20 +634,22 @@ XhcPeiControlTransfer ( // // The transfer timed out. Abort the transfer by dequeueing of the TD. // - RecoveryStatus = XhcPeiDequeueTrbFromEndpoint(Xhc, Urb); - if (EFI_ERROR(RecoveryStatus)) { - DEBUG((DEBUG_ERROR, "XhcPeiControlTransfer: XhcPeiDequeueTrbFromEndpoint failed\n")); + RecoveryStatus = XhcPeiDequeueTrbFromEndpoint (Xhc, Urb); + if (EFI_ERROR (RecoveryStatus)) { + DEBUG ((DEBUG_ERROR, "XhcPeiControlTransfer: XhcPeiDequeueTrbFromEndpoint failed\n")); } + XhcPeiFreeUrb (Xhc, Urb); goto ON_EXIT; } else { if (*TransferResult == EFI_USB_NOERROR) { Status = EFI_SUCCESS; } else if ((*TransferResult == EFI_USB_ERR_STALL) || (*TransferResult == EFI_USB_ERR_BABBLE)) { - RecoveryStatus = XhcPeiRecoverHaltedEndpoint(Xhc, Urb); + RecoveryStatus = XhcPeiRecoverHaltedEndpoint (Xhc, Urb); if (EFI_ERROR (RecoveryStatus)) { DEBUG ((DEBUG_ERROR, "XhcPeiControlTransfer: XhcPeiRecoverHaltedEndpoint failed\n")); } + Status = EFI_DEVICE_ERROR; XhcPeiFreeUrb (Xhc, Urb); goto ON_EXIT; @@ -651,6 +658,7 @@ XhcPeiControlTransfer ( goto ON_EXIT; } } + // // Unmap data before consume. // @@ -663,8 +671,9 @@ XhcPeiControlTransfer ( // if ((Request->Request == USB_REQ_GET_DESCRIPTOR) && ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE)) || - ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_DEVICE))))) { - DescriptorType = (UINT8) (Request->Value >> 8); + ((Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_DEVICE))))) + { + DescriptorType = (UINT8)(Request->Value >> 8); if ((DescriptorType == USB_DESC_TYPE_DEVICE) && ((*DataLength == sizeof (EFI_USB_DEVICE_DESCRIPTOR)) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (*DataLength == 8)))) { ASSERT (Data != NULL); // @@ -679,11 +688,13 @@ XhcPeiControlTransfer ( } else { MaxPacket0 = Xhc->UsbDevContext[SlotId].DevDesc.MaxPacketSize0; } + Xhc->UsbDevContext[SlotId].ConfDesc = AllocateZeroPool (Xhc->UsbDevContext[SlotId].DevDesc.NumConfigurations * sizeof (EFI_USB_CONFIG_DESCRIPTOR *)); if (Xhc->UsbDevContext[SlotId].ConfDesc == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } + if (Xhc->HcCParams.Data.Csz == 0) { Status = XhcPeiEvaluateContext (Xhc, SlotId, MaxPacket0); } else { @@ -691,28 +702,30 @@ XhcPeiControlTransfer ( } } else if (DescriptorType == USB_DESC_TYPE_CONFIG) { ASSERT (Data != NULL); - if (*DataLength == ((UINT16 *) Data)[1]) { + if (*DataLength == ((UINT16 *)Data)[1]) { // // Get configuration value from request, store the configuration descriptor for Configure_Endpoint cmd. // - Index = (UINT8) Request->Value; + Index = (UINT8)Request->Value; ASSERT (Index < Xhc->UsbDevContext[SlotId].DevDesc.NumConfigurations); Xhc->UsbDevContext[SlotId].ConfDesc[Index] = AllocateZeroPool (*DataLength); if (Xhc->UsbDevContext[SlotId].ConfDesc[Index] == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ON_EXIT; } + CopyMem (Xhc->UsbDevContext[SlotId].ConfDesc[Index], Data, *DataLength); } } else if (((DescriptorType == USB_DESC_TYPE_HUB) || - (DescriptorType == USB_DESC_TYPE_HUB_SUPER_SPEED)) && (*DataLength > 2)) { + (DescriptorType == USB_DESC_TYPE_HUB_SUPER_SPEED)) && (*DataLength > 2)) + { ASSERT (Data != NULL); - HubDesc = (EFI_USB_HUB_DESCRIPTOR *) Data; + HubDesc = (EFI_USB_HUB_DESCRIPTOR *)Data; ASSERT (HubDesc->NumPorts <= 15); // // The bit 5,6 of HubCharacter field of Hub Descriptor is TTT. // - TTT = (UINT8) ((HubDesc->HubCharacter & (BIT5 | BIT6)) >> 5); + TTT = (UINT8)((HubDesc->HubCharacter & (BIT5 | BIT6)) >> 5); if (Xhc->UsbDevContext[SlotId].DevDesc.DeviceProtocol == 2) { // // Don't support multi-TT feature for super speed hub now. @@ -730,7 +743,8 @@ XhcPeiControlTransfer ( } } } else if ((Request->Request == USB_REQ_SET_CONFIG) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE))) + { // // Hook Set_Config request from UsbBus as we need configure device endpoint. // @@ -741,16 +755,18 @@ XhcPeiControlTransfer ( } else { Status = XhcPeiSetConfigCmd64 (Xhc, SlotId, DeviceSpeed, Xhc->UsbDevContext[SlotId].ConfDesc[Index]); } + break; } } } else if ((Request->Request == USB_REQ_GET_STATUS) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER))) { + (Request->RequestType == USB_REQUEST_TYPE (EfiUsbDataIn, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER))) + { ASSERT (Data != NULL); // // Hook Get_Status request from UsbBus to keep track of the port status change. // - State = *(UINT32 *) Data; + State = *(UINT32 *)Data; PortStatus.PortStatus = 0; PortStatus.PortChangeStatus = 0; @@ -778,14 +794,14 @@ XhcPeiControlTransfer ( MapSize = sizeof (mUsbHubPortStateMap) / sizeof (USB_PORT_STATE_MAP); for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubPortStateMap[Index].HwState)) { - PortStatus.PortStatus = (UINT16) (PortStatus.PortStatus | mUsbHubPortStateMap[Index].UefiState); + PortStatus.PortStatus = (UINT16)(PortStatus.PortStatus | mUsbHubPortStateMap[Index].UefiState); } } MapSize = sizeof (mUsbHubPortChangeMap) / sizeof (USB_PORT_STATE_MAP); for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubPortChangeMap[Index].HwState)) { - PortStatus.PortChangeStatus = (UINT16) (PortStatus.PortChangeStatus | mUsbHubPortChangeMap[Index].UefiState); + PortStatus.PortChangeStatus = (UINT16)(PortStatus.PortChangeStatus | mUsbHubPortChangeMap[Index].UefiState); } } @@ -794,11 +810,11 @@ XhcPeiControlTransfer ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbHubClearPortChangeMap[Index].HwState)) { ZeroMem (&ClearPortRequest, sizeof (EFI_USB_DEVICE_REQUEST)); - ClearPortRequest.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER); - ClearPortRequest.Request = (UINT8) USB_REQ_CLEAR_FEATURE; - ClearPortRequest.Value = mUsbHubClearPortChangeMap[Index].Selector; - ClearPortRequest.Index = Request->Index; - ClearPortRequest.Length = 0; + ClearPortRequest.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_CLASS, USB_TARGET_OTHER); + ClearPortRequest.Request = (UINT8)USB_REQ_CLEAR_FEATURE; + ClearPortRequest.Value = mUsbHubClearPortChangeMap[Index].Selector; + ClearPortRequest.Index = Request->Index; + ClearPortRequest.Length = 0; XhcPeiControlTransfer ( PeiServices, @@ -819,7 +835,7 @@ XhcPeiControlTransfer ( XhcPeiPollPortStatusChange (Xhc, Xhc->UsbDevContext[SlotId].RouteString, (UINT8)Request->Index, &PortStatus); - *(UINT32 *) Data = *(UINT32 *) &PortStatus; + *(UINT32 *)Data = *(UINT32 *)&PortStatus; } ON_EXIT: @@ -866,31 +882,32 @@ ON_EXIT: EFI_STATUS EFIAPI XhcPeiBulkTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 DeviceAddress, - IN UINT8 EndPointAddress, - IN UINT8 DeviceSpeed, - IN UINTN MaximumPacketLength, - IN OUT VOID *Data[EFI_USB_MAX_BULK_BUFFER_NUM], - IN OUT UINTN *DataLength, - IN OUT UINT8 *DataToggle, - IN UINTN TimeOut, - IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, - OUT UINT32 *TransferResult + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 DeviceAddress, + IN UINT8 EndPointAddress, + IN UINT8 DeviceSpeed, + IN UINTN MaximumPacketLength, + IN OUT VOID *Data[EFI_USB_MAX_BULK_BUFFER_NUM], + IN OUT UINTN *DataLength, + IN OUT UINT8 *DataToggle, + IN UINTN TimeOut, + IN EFI_USB2_HC_TRANSACTION_TRANSLATOR *Translator, + OUT UINT32 *TransferResult ) { - PEI_XHC_DEV *Xhc; - URB *Urb; - UINT8 SlotId; - EFI_STATUS Status; - EFI_STATUS RecoveryStatus; + PEI_XHC_DEV *Xhc; + URB *Urb; + UINT8 SlotId; + EFI_STATUS Status; + EFI_STATUS RecoveryStatus; // // Validate the parameters // if ((DataLength == NULL) || (*DataLength == 0) || - (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) { + (Data == NULL) || (Data[0] == NULL) || (TransferResult == NULL)) + { return EFI_INVALID_PARAMETER; } @@ -901,11 +918,12 @@ XhcPeiBulkTransfer ( if ((DeviceSpeed == EFI_USB_SPEED_LOW) || ((DeviceSpeed == EFI_USB_SPEED_FULL) && (MaximumPacketLength > 64)) || ((DeviceSpeed == EFI_USB_SPEED_HIGH) && (MaximumPacketLength > 512)) || - ((DeviceSpeed == EFI_USB_SPEED_SUPER) && (MaximumPacketLength > 1024))) { + ((DeviceSpeed == EFI_USB_SPEED_SUPER) && (MaximumPacketLength > 1024))) + { return EFI_INVALID_PARAMETER; } - Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); + Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); *TransferResult = EFI_USB_ERR_SYSTEM; Status = EFI_DEVICE_ERROR; @@ -956,18 +974,19 @@ XhcPeiBulkTransfer ( // // The transfer timed out. Abort the transfer by dequeueing of the TD. // - RecoveryStatus = XhcPeiDequeueTrbFromEndpoint(Xhc, Urb); - if (EFI_ERROR(RecoveryStatus)) { - DEBUG((DEBUG_ERROR, "XhcPeiBulkTransfer: XhcPeiDequeueTrbFromEndpoint failed\n")); + RecoveryStatus = XhcPeiDequeueTrbFromEndpoint (Xhc, Urb); + if (EFI_ERROR (RecoveryStatus)) { + DEBUG ((DEBUG_ERROR, "XhcPeiBulkTransfer: XhcPeiDequeueTrbFromEndpoint failed\n")); } } else { if (*TransferResult == EFI_USB_NOERROR) { Status = EFI_SUCCESS; } else if ((*TransferResult == EFI_USB_ERR_STALL) || (*TransferResult == EFI_USB_ERR_BABBLE)) { - RecoveryStatus = XhcPeiRecoverHaltedEndpoint(Xhc, Urb); + RecoveryStatus = XhcPeiRecoverHaltedEndpoint (Xhc, Urb); if (EFI_ERROR (RecoveryStatus)) { DEBUG ((DEBUG_ERROR, "XhcPeiBulkTransfer: XhcPeiRecoverHaltedEndpoint failed\n")); } + Status = EFI_DEVICE_ERROR; } } @@ -998,12 +1017,13 @@ ON_EXIT: EFI_STATUS EFIAPI XhcPeiGetRootHubPortNumber ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - OUT UINT8 *PortNumber + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + OUT UINT8 *PortNumber ) { - PEI_XHC_DEV *XhcDev; + PEI_XHC_DEV *XhcDev; + XhcDev = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); if (PortNumber == NULL) { @@ -1033,18 +1053,18 @@ XhcPeiGetRootHubPortNumber ( EFI_STATUS EFIAPI XhcPeiClearRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - PEI_XHC_DEV *Xhc; - UINT32 Offset; - UINT32 State; - EFI_STATUS Status; + PEI_XHC_DEV *Xhc; + UINT32 Offset; + UINT32 State; + EFI_STATUS Status; - Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); + Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); Status = EFI_SUCCESS; if (PortNumber >= Xhc->HcSParams1.Data.MaxPorts) { @@ -1052,15 +1072,15 @@ XhcPeiClearRootHubPortFeature ( goto ON_EXIT; } - Offset = (UINT32) (XHC_PORTSC_OFFSET + (0x10 * PortNumber)); - State = XhcPeiReadOpReg (Xhc, Offset); + Offset = (UINT32)(XHC_PORTSC_OFFSET + (0x10 * PortNumber)); + State = XhcPeiReadOpReg (Xhc, Offset); DEBUG ((DEBUG_INFO, "XhcPeiClearRootHubPortFeature: Port: %x State: %x\n", PortNumber, State)); // // Mask off the port status change bits, these bits are // write clean bits // - State &= ~ (BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); + State &= ~(BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); switch (PortFeature) { case EfiUsbPortEnable: @@ -1096,6 +1116,7 @@ XhcPeiClearRootHubPortFeature ( State &= ~XHC_PORTSC_PP; XhcPeiWriteOpReg (Xhc, Offset, State); } + break; case EfiUsbPortOwner: @@ -1168,18 +1189,18 @@ ON_EXIT: EFI_STATUS EFIAPI XhcPeiSetRootHubPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - IN EFI_USB_PORT_FEATURE PortFeature + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + IN EFI_USB_PORT_FEATURE PortFeature ) { - PEI_XHC_DEV *Xhc; - UINT32 Offset; - UINT32 State; - EFI_STATUS Status; + PEI_XHC_DEV *Xhc; + UINT32 Offset; + UINT32 State; + EFI_STATUS Status; - Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); + Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS (This); Status = EFI_SUCCESS; if (PortNumber >= Xhc->HcSParams1.Data.MaxPorts) { @@ -1187,15 +1208,15 @@ XhcPeiSetRootHubPortFeature ( goto ON_EXIT; } - Offset = (UINT32) (XHC_PORTSC_OFFSET + (0x10 * PortNumber)); - State = XhcPeiReadOpReg (Xhc, Offset); + Offset = (UINT32)(XHC_PORTSC_OFFSET + (0x10 * PortNumber)); + State = XhcPeiReadOpReg (Xhc, Offset); DEBUG ((DEBUG_INFO, "XhcPeiSetRootHubPortFeature: Port: %x State: %x\n", PortNumber, State)); // // Mask off the port status change bits, these bits are // write clean bits // - State &= ~ (BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); + State &= ~(BIT1 | BIT17 | BIT18 | BIT19 | BIT20 | BIT21 | BIT22 | BIT23); switch (PortFeature) { case EfiUsbPortEnable: @@ -1209,7 +1230,7 @@ XhcPeiSetRootHubPortFeature ( State |= XHC_PORTSC_LWS; XhcPeiWriteOpReg (Xhc, Offset, State); State &= ~XHC_PORTSC_PLS; - State |= (3 << 5) ; + State |= (3 << 5); XhcPeiWriteOpReg (Xhc, Offset, State); break; @@ -1232,7 +1253,7 @@ XhcPeiSetRootHubPortFeature ( // State |= XHC_PORTSC_RESET; XhcPeiWriteOpReg (Xhc, Offset, State); - XhcPeiWaitOpRegBit(Xhc, Offset, XHC_PORTSC_PRC, TRUE, XHC_GENERIC_TIMEOUT); + XhcPeiWaitOpRegBit (Xhc, Offset, XHC_PORTSC_PRC, TRUE, XHC_GENERIC_TIMEOUT); break; case EfiUsbPortPower: @@ -1243,6 +1264,7 @@ XhcPeiSetRootHubPortFeature ( State |= XHC_PORTSC_PP; XhcPeiWriteOpReg (Xhc, Offset, State); } + break; case EfiUsbPortOwner: @@ -1276,18 +1298,18 @@ ON_EXIT: EFI_STATUS EFIAPI XhcPeiGetRootHubPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB2_HOST_CONTROLLER_PPI *This, - IN UINT8 PortNumber, - OUT EFI_USB_PORT_STATUS *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB2_HOST_CONTROLLER_PPI *This, + IN UINT8 PortNumber, + OUT EFI_USB_PORT_STATUS *PortStatus ) { - PEI_XHC_DEV *Xhc; - UINT32 Offset; - UINT32 State; - UINTN Index; - UINTN MapSize; - USB_DEV_ROUTE ParentRouteChart; + PEI_XHC_DEV *Xhc; + UINT32 Offset; + UINT32 State; + UINTN Index; + UINTN MapSize; + USB_DEV_ROUTE ParentRouteChart; if (PortStatus == NULL) { return EFI_INVALID_PARAMETER; @@ -1302,11 +1324,11 @@ XhcPeiGetRootHubPortStatus ( // // Clear port status. // - PortStatus->PortStatus = 0; - PortStatus->PortChangeStatus = 0; + PortStatus->PortStatus = 0; + PortStatus->PortChangeStatus = 0; - Offset = (UINT32) (XHC_PORTSC_OFFSET + (0x10 * PortNumber)); - State = XhcPeiReadOpReg (Xhc, Offset); + Offset = (UINT32)(XHC_PORTSC_OFFSET + (0x10 * PortNumber)); + State = XhcPeiReadOpReg (Xhc, Offset); DEBUG ((DEBUG_INFO, "XhcPeiGetRootHubPortStatus: Port: %x State: %x\n", PortNumber, State)); // @@ -1338,9 +1360,10 @@ XhcPeiGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbPortStateMap[Index].HwState)) { - PortStatus->PortStatus = (UINT16) (PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); + PortStatus->PortStatus = (UINT16)(PortStatus->PortStatus | mUsbPortStateMap[Index].UefiState); } } + // // Bit5~8 reflects its current link state. // @@ -1352,7 +1375,7 @@ XhcPeiGetRootHubPortStatus ( for (Index = 0; Index < MapSize; Index++) { if (XHC_BIT_IS_SET (State, mUsbPortChangeMap[Index].HwState)) { - PortStatus->PortChangeStatus = (UINT16) (PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); + PortStatus->PortChangeStatus = (UINT16)(PortStatus->PortChangeStatus | mUsbPortChangeMap[Index].UefiState); } } @@ -1394,9 +1417,9 @@ XhcEndOfPei ( IN VOID *Ppi ) { - PEI_XHC_DEV *Xhc; + PEI_XHC_DEV *Xhc; - Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS_NOTIFY(NotifyDescriptor); + Xhc = PEI_RECOVERY_USB_XHC_DEV_FROM_THIS_NOTIFY (NotifyDescriptor); XhcPeiHaltHC (Xhc, XHC_GENERIC_TIMEOUT); @@ -1415,19 +1438,19 @@ XhcEndOfPei ( EFI_STATUS EFIAPI XhcPeimEntry ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - PEI_USB_CONTROLLER_PPI *UsbControllerPpi; - EFI_STATUS Status; - UINT8 Index; - UINTN ControllerType; - UINTN BaseAddress; - UINTN MemPages; - PEI_XHC_DEV *XhcDev; - EFI_PHYSICAL_ADDRESS TempPtr; - UINT32 PageSize; + PEI_USB_CONTROLLER_PPI *UsbControllerPpi; + EFI_STATUS Status; + UINT8 Index; + UINTN ControllerType; + UINTN BaseAddress; + UINTN MemPages; + PEI_XHC_DEV *XhcDev; + EFI_PHYSICAL_ADDRESS TempPtr; + UINT32 PageSize; // // Shadow this PEIM to run from memory. @@ -1440,7 +1463,7 @@ XhcPeimEntry ( &gPeiUsbControllerPpiGuid, 0, NULL, - (VOID **) &UsbControllerPpi + (VOID **)&UsbControllerPpi ); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; @@ -1451,7 +1474,7 @@ XhcPeimEntry ( Index = 0; while (TRUE) { Status = UsbControllerPpi->GetUsbController ( - (EFI_PEI_SERVICES **) PeiServices, + (EFI_PEI_SERVICES **)PeiServices, UsbControllerPpi, Index, &ControllerType, @@ -1473,25 +1496,26 @@ XhcPeimEntry ( } MemPages = EFI_SIZE_TO_PAGES (sizeof (PEI_XHC_DEV)); - Status = PeiServicesAllocatePages ( - EfiBootServicesData, - MemPages, - &TempPtr - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesData, + MemPages, + &TempPtr + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - ZeroMem ((VOID *) (UINTN) TempPtr, EFI_PAGES_TO_SIZE (MemPages)); - XhcDev = (PEI_XHC_DEV *) ((UINTN) TempPtr); - - XhcDev->Signature = USB_XHC_DEV_SIGNATURE; - XhcDev->UsbHostControllerBaseAddress = (UINT32) BaseAddress; - XhcDev->CapLength = (UINT8) (XhcPeiReadCapRegister (XhcDev, XHC_CAPLENGTH_OFFSET) & 0x0FF); - XhcDev->HcSParams1.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCSPARAMS1_OFFSET); - XhcDev->HcSParams2.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCSPARAMS2_OFFSET); - XhcDev->HcCParams.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCCPARAMS_OFFSET); - XhcDev->DBOff = XhcPeiReadCapRegister (XhcDev, XHC_DBOFF_OFFSET); - XhcDev->RTSOff = XhcPeiReadCapRegister (XhcDev, XHC_RTSOFF_OFFSET); + + ZeroMem ((VOID *)(UINTN)TempPtr, EFI_PAGES_TO_SIZE (MemPages)); + XhcDev = (PEI_XHC_DEV *)((UINTN)TempPtr); + + XhcDev->Signature = USB_XHC_DEV_SIGNATURE; + XhcDev->UsbHostControllerBaseAddress = (UINT32)BaseAddress; + XhcDev->CapLength = (UINT8)(XhcPeiReadCapRegister (XhcDev, XHC_CAPLENGTH_OFFSET) & 0x0FF); + XhcDev->HcSParams1.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCSPARAMS1_OFFSET); + XhcDev->HcSParams2.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCSPARAMS2_OFFSET); + XhcDev->HcCParams.Dword = XhcPeiReadCapRegister (XhcDev, XHC_HCCPARAMS_OFFSET); + XhcDev->DBOff = XhcPeiReadCapRegister (XhcDev, XHC_DBOFF_OFFSET); + XhcDev->RTSOff = XhcPeiReadCapRegister (XhcDev, XHC_RTSOFF_OFFSET); // // This PageSize field defines the page size supported by the xHC implementation. @@ -1528,19 +1552,19 @@ XhcPeimEntry ( // MicroSecondDelay (XHC_ROOT_PORT_STATE_STABLE); - XhcDev->Usb2HostControllerPpi.ControlTransfer = XhcPeiControlTransfer; - XhcDev->Usb2HostControllerPpi.BulkTransfer = XhcPeiBulkTransfer; - XhcDev->Usb2HostControllerPpi.GetRootHubPortNumber = XhcPeiGetRootHubPortNumber; - XhcDev->Usb2HostControllerPpi.GetRootHubPortStatus = XhcPeiGetRootHubPortStatus; - XhcDev->Usb2HostControllerPpi.SetRootHubPortFeature = XhcPeiSetRootHubPortFeature; - XhcDev->Usb2HostControllerPpi.ClearRootHubPortFeature = XhcPeiClearRootHubPortFeature; + XhcDev->Usb2HostControllerPpi.ControlTransfer = XhcPeiControlTransfer; + XhcDev->Usb2HostControllerPpi.BulkTransfer = XhcPeiBulkTransfer; + XhcDev->Usb2HostControllerPpi.GetRootHubPortNumber = XhcPeiGetRootHubPortNumber; + XhcDev->Usb2HostControllerPpi.GetRootHubPortStatus = XhcPeiGetRootHubPortStatus; + XhcDev->Usb2HostControllerPpi.SetRootHubPortFeature = XhcPeiSetRootHubPortFeature; + XhcDev->Usb2HostControllerPpi.ClearRootHubPortFeature = XhcPeiClearRootHubPortFeature; XhcDev->PpiDescriptor.Flags = (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - XhcDev->PpiDescriptor.Guid = &gPeiUsb2HostControllerPpiGuid; - XhcDev->PpiDescriptor.Ppi = &XhcDev->Usb2HostControllerPpi; + XhcDev->PpiDescriptor.Guid = &gPeiUsb2HostControllerPpiGuid; + XhcDev->PpiDescriptor.Ppi = &XhcDev->Usb2HostControllerPpi; - XhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); - XhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; + XhcDev->EndOfPeiNotifyList.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); + XhcDev->EndOfPeiNotifyList.Guid = &gEfiEndOfPeiSignalPpiGuid; XhcDev->EndOfPeiNotifyList.Notify = XhcEndOfPei; PeiServicesInstallPpi (&XhcDev->PpiDescriptor); diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.h b/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.h index 03a55f3eb6..0800b15c72 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.h +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhcPeim.h @@ -25,33 +25,33 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -typedef struct _PEI_XHC_DEV PEI_XHC_DEV; -typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; +typedef struct _PEI_XHC_DEV PEI_XHC_DEV; +typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; #include "UsbHcMem.h" #include "XhciReg.h" #include "XhciSched.h" -#define CMD_RING_TRB_NUMBER 0x100 -#define TR_RING_TRB_NUMBER 0x100 -#define ERST_NUMBER 0x01 -#define EVENT_RING_TRB_NUMBER 0x200 +#define CMD_RING_TRB_NUMBER 0x100 +#define TR_RING_TRB_NUMBER 0x100 +#define ERST_NUMBER 0x01 +#define EVENT_RING_TRB_NUMBER 0x200 -#define XHC_1_MICROSECOND 1 -#define XHC_1_MILLISECOND (1000 * XHC_1_MICROSECOND) -#define XHC_1_SECOND (1000 * XHC_1_MILLISECOND) +#define XHC_1_MICROSECOND 1 +#define XHC_1_MILLISECOND (1000 * XHC_1_MICROSECOND) +#define XHC_1_SECOND (1000 * XHC_1_MILLISECOND) // // XHC reset timeout experience values. // The unit is millisecond, setting it as 1s. // -#define XHC_RESET_TIMEOUT (1000) +#define XHC_RESET_TIMEOUT (1000) // // TRSTRCY delay requirement in usb 2.0 spec chapter 7.1.7.5. // The unit is microsecond, setting it as 10ms. // -#define XHC_RESET_RECOVERY_DELAY (10 * 1000) +#define XHC_RESET_RECOVERY_DELAY (10 * 1000) // // Wait for root port state stable. @@ -62,11 +62,11 @@ typedef struct _USB_DEV_CONTEXT USB_DEV_CONTEXT; // XHC generic timeout experience values. // The unit is millisecond, setting it as 10s. // -#define XHC_GENERIC_TIMEOUT (10 * 1000) +#define XHC_GENERIC_TIMEOUT (10 * 1000) -#define XHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) -#define XHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) -#define XHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define XHC_LOW_32BIT(Addr64) ((UINT32)(((UINTN)(Addr64)) & 0XFFFFFFFF)) +#define XHC_HIGH_32BIT(Addr64) ((UINT32)(RShiftU64((UINTN)(Addr64), 32) & 0XFFFFFFFF)) +#define XHC_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) #define XHC_REG_BIT_IS_SET(XHC, Offset, Bit) \ (XHC_BIT_IS_SET(XhcPeiReadOpReg ((XHC), (Offset)), (Bit))) @@ -86,23 +86,23 @@ struct _USB_DEV_CONTEXT { // // Whether this entry in UsbDevContext array is used or not. // - BOOLEAN Enabled; + BOOLEAN Enabled; // // The slot id assigned to the new device through XHCI's Enable_Slot cmd. // - UINT8 SlotId; + UINT8 SlotId; // // The route string presented an attached usb device. // - USB_DEV_ROUTE RouteString; + USB_DEV_ROUTE RouteString; // // The route string of parent device if it exists. Otherwise it's zero. // - USB_DEV_ROUTE ParentRouteString; + USB_DEV_ROUTE ParentRouteString; // // The actual device address assigned by XHCI through Address_Device command. // - UINT8 XhciDevAddr; + UINT8 XhciDevAddr; // // The requested device address from UsbBus driver through Set_Address standard usb request. // As XHCI spec replaces this request with Address_Device command, we have to record the @@ -111,23 +111,23 @@ struct _USB_DEV_CONTEXT { // through EFI_USB2_HC_PROTOCOL. Xhci driver would be responsible for translating it to actual // device address and access the actual device. // - UINT8 BusDevAddr; + UINT8 BusDevAddr; // // The pointer to the input device context. // - VOID *InputContext; + VOID *InputContext; // // The pointer to the output device context. // - VOID *OutputContext; + VOID *OutputContext; // // The transfer queue for every endpoint. // - VOID *EndpointTransferRing[31]; + VOID *EndpointTransferRing[31]; // // The device descriptor which is stored to support XHCI's Evaluate_Context cmd. // - EFI_USB_DEVICE_DESCRIPTOR DevDesc; + EFI_USB_DEVICE_DESCRIPTOR DevDesc; // // As a usb device may include multiple configuration descriptors, we dynamically allocate an array // to store them. @@ -135,59 +135,59 @@ struct _USB_DEV_CONTEXT { // such as Interface descriptor, Endpoint descriptor, and so on. // These information is used to support XHCI's Config_Endpoint cmd. // - EFI_USB_CONFIG_DESCRIPTOR **ConfDesc; + EFI_USB_CONFIG_DESCRIPTOR **ConfDesc; }; -#define USB_XHC_DEV_SIGNATURE SIGNATURE_32 ('x', 'h', 'c', 'i') +#define USB_XHC_DEV_SIGNATURE SIGNATURE_32 ('x', 'h', 'c', 'i') struct _PEI_XHC_DEV { - UINTN Signature; - PEI_USB2_HOST_CONTROLLER_PPI Usb2HostControllerPpi; - EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; - UINT32 UsbHostControllerBaseAddress; - USBHC_MEM_POOL *MemPool; + UINTN Signature; + PEI_USB2_HOST_CONTROLLER_PPI Usb2HostControllerPpi; + EFI_PEI_PPI_DESCRIPTOR PpiDescriptor; + UINT32 UsbHostControllerBaseAddress; + USBHC_MEM_POOL *MemPool; // // EndOfPei callback is used to stop the XHC DMA operation // after exit PEI phase. // - EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; + EFI_PEI_NOTIFY_DESCRIPTOR EndOfPeiNotifyList; // // XHCI configuration data // - UINT8 CapLength; ///< Capability Register Length - XHC_HCSPARAMS1 HcSParams1; ///< Structural Parameters 1 - XHC_HCSPARAMS2 HcSParams2; ///< Structural Parameters 2 - XHC_HCCPARAMS HcCParams; ///< Capability Parameters - UINT32 DBOff; ///< Doorbell Offset - UINT32 RTSOff; ///< Runtime Register Space Offset - UINT32 PageSize; - UINT32 MaxScratchpadBufs; - UINT64 *ScratchBuf; - VOID *ScratchMap; - UINT64 *ScratchEntry; - UINTN *ScratchEntryMap; - UINT64 *DCBAA; - UINT32 MaxSlotsEn; + UINT8 CapLength; ///< Capability Register Length + XHC_HCSPARAMS1 HcSParams1; ///< Structural Parameters 1 + XHC_HCSPARAMS2 HcSParams2; ///< Structural Parameters 2 + XHC_HCCPARAMS HcCParams; ///< Capability Parameters + UINT32 DBOff; ///< Doorbell Offset + UINT32 RTSOff; ///< Runtime Register Space Offset + UINT32 PageSize; + UINT32 MaxScratchpadBufs; + UINT64 *ScratchBuf; + VOID *ScratchMap; + UINT64 *ScratchEntry; + UINTN *ScratchEntryMap; + UINT64 *DCBAA; + UINT32 MaxSlotsEn; // // Cmd Transfer Ring // - TRANSFER_RING CmdRing; + TRANSFER_RING CmdRing; // // EventRing // - EVENT_RING EventRing; + EVENT_RING EventRing; // // Store device contexts managed by XHCI device // The array supports up to 255 devices, entry 0 is reserved and should not be used. // - USB_DEV_CONTEXT UsbDevContext[256]; + USB_DEV_CONTEXT UsbDevContext[256]; }; -#define PEI_RECOVERY_USB_XHC_DEV_FROM_THIS(a) CR (a, PEI_XHC_DEV, Usb2HostControllerPpi, USB_XHC_DEV_SIGNATURE) -#define PEI_RECOVERY_USB_XHC_DEV_FROM_THIS_NOTIFY(a) CR (a, PEI_XHC_DEV, EndOfPeiNotifyList, USB_XHC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_XHC_DEV_FROM_THIS(a) CR (a, PEI_XHC_DEV, Usb2HostControllerPpi, USB_XHC_DEV_SIGNATURE) +#define PEI_RECOVERY_USB_XHC_DEV_FROM_THIS_NOTIFY(a) CR (a, PEI_XHC_DEV, EndOfPeiNotifyList, USB_XHC_DEV_SIGNATURE) /** Initialize the memory management pool for the host controller. @@ -209,7 +209,7 @@ UsbHcInitMemPool ( **/ VOID UsbHcFreeMemPool ( - IN USBHC_MEM_POOL *Pool + IN USBHC_MEM_POOL *Pool ) ; @@ -225,8 +225,8 @@ UsbHcFreeMemPool ( **/ VOID * UsbHcAllocateMem ( - IN USBHC_MEM_POOL *Pool, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN UINTN Size ) ; @@ -240,13 +240,12 @@ UsbHcAllocateMem ( **/ VOID UsbHcFreeMem ( - IN USBHC_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN USBHC_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) ; - /** Initialize IOMMU. **/ @@ -276,11 +275,11 @@ IoMmuInit ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -294,7 +293,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -337,9 +336,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhciReg.h b/MdeModulePkg/Bus/Pci/XhciPei/XhciReg.h index e98b451a96..bfbb608526 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhciReg.h +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhciReg.h @@ -13,153 +13,152 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Capability registers offset // -#define XHC_CAPLENGTH_OFFSET 0x00 // Capability register length offset -#define XHC_HCIVERSION_OFFSET 0x02 // Interface Version Number 02-03h -#define XHC_HCSPARAMS1_OFFSET 0x04 // Structural Parameters 1 -#define XHC_HCSPARAMS2_OFFSET 0x08 // Structural Parameters 2 -#define XHC_HCSPARAMS3_OFFSET 0x0c // Structural Parameters 3 -#define XHC_HCCPARAMS_OFFSET 0x10 // Capability Parameters -#define XHC_DBOFF_OFFSET 0x14 // Doorbell Offset -#define XHC_RTSOFF_OFFSET 0x18 // Runtime Register Space Offset +#define XHC_CAPLENGTH_OFFSET 0x00 // Capability register length offset +#define XHC_HCIVERSION_OFFSET 0x02 // Interface Version Number 02-03h +#define XHC_HCSPARAMS1_OFFSET 0x04 // Structural Parameters 1 +#define XHC_HCSPARAMS2_OFFSET 0x08 // Structural Parameters 2 +#define XHC_HCSPARAMS3_OFFSET 0x0c // Structural Parameters 3 +#define XHC_HCCPARAMS_OFFSET 0x10 // Capability Parameters +#define XHC_DBOFF_OFFSET 0x14 // Doorbell Offset +#define XHC_RTSOFF_OFFSET 0x18 // Runtime Register Space Offset // // Operational registers offset // -#define XHC_USBCMD_OFFSET 0x0000 // USB Command Register Offset -#define XHC_USBSTS_OFFSET 0x0004 // USB Status Register Offset -#define XHC_PAGESIZE_OFFSET 0x0008 // USB Page Size Register Offset -#define XHC_DNCTRL_OFFSET 0x0014 // Device Notification Control Register Offset -#define XHC_CRCR_OFFSET 0x0018 // Command Ring Control Register Offset -#define XHC_DCBAAP_OFFSET 0x0030 // Device Context Base Address Array Pointer Register Offset -#define XHC_CONFIG_OFFSET 0x0038 // Configure Register Offset -#define XHC_PORTSC_OFFSET 0x0400 // Port Status and Control Register Offset +#define XHC_USBCMD_OFFSET 0x0000 // USB Command Register Offset +#define XHC_USBSTS_OFFSET 0x0004 // USB Status Register Offset +#define XHC_PAGESIZE_OFFSET 0x0008 // USB Page Size Register Offset +#define XHC_DNCTRL_OFFSET 0x0014 // Device Notification Control Register Offset +#define XHC_CRCR_OFFSET 0x0018 // Command Ring Control Register Offset +#define XHC_DCBAAP_OFFSET 0x0030 // Device Context Base Address Array Pointer Register Offset +#define XHC_CONFIG_OFFSET 0x0038 // Configure Register Offset +#define XHC_PORTSC_OFFSET 0x0400 // Port Status and Control Register Offset // // Runtime registers offset // -#define XHC_MFINDEX_OFFSET 0x00 // Microframe Index Register Offset -#define XHC_IMAN_OFFSET 0x20 // Interrupter X Management Register Offset -#define XHC_IMOD_OFFSET 0x24 // Interrupter X Moderation Register Offset -#define XHC_ERSTSZ_OFFSET 0x28 // Event Ring Segment Table Size Register Offset -#define XHC_ERSTBA_OFFSET 0x30 // Event Ring Segment Table Base Address Register Offset -#define XHC_ERDP_OFFSET 0x38 // Event Ring Dequeue Pointer Register Offset +#define XHC_MFINDEX_OFFSET 0x00 // Microframe Index Register Offset +#define XHC_IMAN_OFFSET 0x20 // Interrupter X Management Register Offset +#define XHC_IMOD_OFFSET 0x24 // Interrupter X Moderation Register Offset +#define XHC_ERSTSZ_OFFSET 0x28 // Event Ring Segment Table Size Register Offset +#define XHC_ERSTBA_OFFSET 0x30 // Event Ring Segment Table Base Address Register Offset +#define XHC_ERDP_OFFSET 0x38 // Event Ring Dequeue Pointer Register Offset // // Register Bit Definition // -#define XHC_USBCMD_RUN BIT0 // Run/Stop -#define XHC_USBCMD_RESET BIT1 // Host Controller Reset -#define XHC_USBCMD_INTE BIT2 // Interrupter Enable -#define XHC_USBCMD_HSEE BIT3 // Host System Error Enable - -#define XHC_USBSTS_HALT BIT0 // Host Controller Halted -#define XHC_USBSTS_HSE BIT2 // Host System Error -#define XHC_USBSTS_EINT BIT3 // Event Interrupt -#define XHC_USBSTS_PCD BIT4 // Port Change Detect -#define XHC_USBSTS_SSS BIT8 // Save State Status -#define XHC_USBSTS_RSS BIT9 // Restore State Status -#define XHC_USBSTS_SRE BIT10 // Save/Restore Error -#define XHC_USBSTS_CNR BIT11 // Host Controller Not Ready -#define XHC_USBSTS_HCE BIT12 // Host Controller Error - -#define XHC_PAGESIZE_MASK 0xFFFF // Page Size - -#define XHC_CRCR_RCS BIT0 // Ring Cycle State -#define XHC_CRCR_CS BIT1 // Command Stop -#define XHC_CRCR_CA BIT2 // Command Abort -#define XHC_CRCR_CRR BIT3 // Command Ring Running - -#define XHC_CONFIG_MASK 0xFF // Max Device Slots Enabled - -#define XHC_PORTSC_CCS BIT0 // Current Connect Status -#define XHC_PORTSC_PED BIT1 // Port Enabled/Disabled -#define XHC_PORTSC_OCA BIT3 // Over-current Active -#define XHC_PORTSC_RESET BIT4 // Port Reset -#define XHC_PORTSC_PLS (BIT5|BIT6|BIT7|BIT8) // Port Link State -#define XHC_PORTSC_PP BIT9 // Port Power -#define XHC_PORTSC_PS (BIT10|BIT11|BIT12|BIT13) // Port Speed -#define XHC_PORTSC_LWS BIT16 // Port Link State Write Strobe -#define XHC_PORTSC_CSC BIT17 // Connect Status Change -#define XHC_PORTSC_PEC BIT18 // Port Enabled/Disabled Change -#define XHC_PORTSC_WRC BIT19 // Warm Port Reset Change -#define XHC_PORTSC_OCC BIT20 // Over-Current Change -#define XHC_PORTSC_PRC BIT21 // Port Reset Change -#define XHC_PORTSC_PLC BIT22 // Port Link State Change -#define XHC_PORTSC_CEC BIT23 // Port Config Error Change -#define XHC_PORTSC_CAS BIT24 // Cold Attach Status - -#define XHC_HUB_PORTSC_CCS BIT0 // Hub's Current Connect Status -#define XHC_HUB_PORTSC_PED BIT1 // Hub's Port Enabled/Disabled -#define XHC_HUB_PORTSC_OCA BIT3 // Hub's Over-current Active -#define XHC_HUB_PORTSC_RESET BIT4 // Hub's Port Reset -#define XHC_HUB_PORTSC_PP BIT9 // Hub's Port Power -#define XHC_HUB_PORTSC_CSC BIT16 // Hub's Connect Status Change -#define XHC_HUB_PORTSC_PEC BIT17 // Hub's Port Enabled/Disabled Change -#define XHC_HUB_PORTSC_OCC BIT19 // Hub's Over-Current Change -#define XHC_HUB_PORTSC_PRC BIT20 // Hub's Port Reset Change -#define XHC_HUB_PORTSC_BHRC BIT21 // Hub's Port Warm Reset Change - -#define XHC_IMAN_IP BIT0 // Interrupt Pending -#define XHC_IMAN_IE BIT1 // Interrupt Enable - -#define XHC_IMODI_MASK 0x0000FFFF // Interrupt Moderation Interval -#define XHC_IMODC_MASK 0xFFFF0000 // Interrupt Moderation Counter - +#define XHC_USBCMD_RUN BIT0 // Run/Stop +#define XHC_USBCMD_RESET BIT1 // Host Controller Reset +#define XHC_USBCMD_INTE BIT2 // Interrupter Enable +#define XHC_USBCMD_HSEE BIT3 // Host System Error Enable + +#define XHC_USBSTS_HALT BIT0 // Host Controller Halted +#define XHC_USBSTS_HSE BIT2 // Host System Error +#define XHC_USBSTS_EINT BIT3 // Event Interrupt +#define XHC_USBSTS_PCD BIT4 // Port Change Detect +#define XHC_USBSTS_SSS BIT8 // Save State Status +#define XHC_USBSTS_RSS BIT9 // Restore State Status +#define XHC_USBSTS_SRE BIT10 // Save/Restore Error +#define XHC_USBSTS_CNR BIT11 // Host Controller Not Ready +#define XHC_USBSTS_HCE BIT12 // Host Controller Error + +#define XHC_PAGESIZE_MASK 0xFFFF // Page Size + +#define XHC_CRCR_RCS BIT0 // Ring Cycle State +#define XHC_CRCR_CS BIT1 // Command Stop +#define XHC_CRCR_CA BIT2 // Command Abort +#define XHC_CRCR_CRR BIT3 // Command Ring Running + +#define XHC_CONFIG_MASK 0xFF // Max Device Slots Enabled + +#define XHC_PORTSC_CCS BIT0 // Current Connect Status +#define XHC_PORTSC_PED BIT1 // Port Enabled/Disabled +#define XHC_PORTSC_OCA BIT3 // Over-current Active +#define XHC_PORTSC_RESET BIT4 // Port Reset +#define XHC_PORTSC_PLS (BIT5|BIT6|BIT7|BIT8) // Port Link State +#define XHC_PORTSC_PP BIT9 // Port Power +#define XHC_PORTSC_PS (BIT10|BIT11|BIT12|BIT13) // Port Speed +#define XHC_PORTSC_LWS BIT16 // Port Link State Write Strobe +#define XHC_PORTSC_CSC BIT17 // Connect Status Change +#define XHC_PORTSC_PEC BIT18 // Port Enabled/Disabled Change +#define XHC_PORTSC_WRC BIT19 // Warm Port Reset Change +#define XHC_PORTSC_OCC BIT20 // Over-Current Change +#define XHC_PORTSC_PRC BIT21 // Port Reset Change +#define XHC_PORTSC_PLC BIT22 // Port Link State Change +#define XHC_PORTSC_CEC BIT23 // Port Config Error Change +#define XHC_PORTSC_CAS BIT24 // Cold Attach Status + +#define XHC_HUB_PORTSC_CCS BIT0 // Hub's Current Connect Status +#define XHC_HUB_PORTSC_PED BIT1 // Hub's Port Enabled/Disabled +#define XHC_HUB_PORTSC_OCA BIT3 // Hub's Over-current Active +#define XHC_HUB_PORTSC_RESET BIT4 // Hub's Port Reset +#define XHC_HUB_PORTSC_PP BIT9 // Hub's Port Power +#define XHC_HUB_PORTSC_CSC BIT16 // Hub's Connect Status Change +#define XHC_HUB_PORTSC_PEC BIT17 // Hub's Port Enabled/Disabled Change +#define XHC_HUB_PORTSC_OCC BIT19 // Hub's Over-Current Change +#define XHC_HUB_PORTSC_PRC BIT20 // Hub's Port Reset Change +#define XHC_HUB_PORTSC_BHRC BIT21 // Hub's Port Warm Reset Change + +#define XHC_IMAN_IP BIT0 // Interrupt Pending +#define XHC_IMAN_IE BIT1 // Interrupt Enable + +#define XHC_IMODI_MASK 0x0000FFFF // Interrupt Moderation Interval +#define XHC_IMODC_MASK 0xFFFF0000 // Interrupt Moderation Counter #pragma pack (1) typedef struct { - UINT8 MaxSlots; // Number of Device Slots - UINT16 MaxIntrs:11; // Number of Interrupters - UINT16 Rsvd:5; - UINT8 MaxPorts; // Number of Ports + UINT8 MaxSlots; // Number of Device Slots + UINT16 MaxIntrs : 11; // Number of Interrupters + UINT16 Rsvd : 5; + UINT8 MaxPorts; // Number of Ports } HCSPARAMS1; // // Structural Parameters 1 Register Bitmap Definition // typedef union { - UINT32 Dword; - HCSPARAMS1 Data; + UINT32 Dword; + HCSPARAMS1 Data; } XHC_HCSPARAMS1; typedef struct { - UINT32 Ist:4; // Isochronous Scheduling Threshold - UINT32 Erst:4; // Event Ring Segment Table Max - UINT32 Rsvd:13; - UINT32 ScratchBufHi:5; // Max Scratchpad Buffers Hi - UINT32 Spr:1; // Scratchpad Restore - UINT32 ScratchBufLo:5; // Max Scratchpad Buffers Lo + UINT32 Ist : 4; // Isochronous Scheduling Threshold + UINT32 Erst : 4; // Event Ring Segment Table Max + UINT32 Rsvd : 13; + UINT32 ScratchBufHi : 5; // Max Scratchpad Buffers Hi + UINT32 Spr : 1; // Scratchpad Restore + UINT32 ScratchBufLo : 5; // Max Scratchpad Buffers Lo } HCSPARAMS2; // // Structural Parameters 2 Register Bitmap Definition // typedef union { - UINT32 Dword; - HCSPARAMS2 Data; + UINT32 Dword; + HCSPARAMS2 Data; } XHC_HCSPARAMS2; typedef struct { - UINT16 Ac64:1; // 64-bit Addressing Capability - UINT16 Bnc:1; // BW Negotiation Capability - UINT16 Csz:1; // Context Size - UINT16 Ppc:1; // Port Power Control - UINT16 Pind:1; // Port Indicators - UINT16 Lhrc:1; // Light HC Reset Capability - UINT16 Ltc:1; // Latency Tolerance Messaging Capability - UINT16 Nss:1; // No Secondary SID Support - UINT16 Pae:1; // Parse All Event Data - UINT16 Rsvd:3; - UINT16 MaxPsaSize:4; // Maximum Primary Stream Array Size - UINT16 ExtCapReg; // xHCI Extended Capabilities Pointer + UINT16 Ac64 : 1; // 64-bit Addressing Capability + UINT16 Bnc : 1; // BW Negotiation Capability + UINT16 Csz : 1; // Context Size + UINT16 Ppc : 1; // Port Power Control + UINT16 Pind : 1; // Port Indicators + UINT16 Lhrc : 1; // Light HC Reset Capability + UINT16 Ltc : 1; // Latency Tolerance Messaging Capability + UINT16 Nss : 1; // No Secondary SID Support + UINT16 Pae : 1; // Parse All Event Data + UINT16 Rsvd : 3; + UINT16 MaxPsaSize : 4; // Maximum Primary Stream Array Size + UINT16 ExtCapReg; // xHCI Extended Capabilities Pointer } HCCPARAMS; // // Capability Parameters Register Bitmap Definition // typedef union { - UINT32 Dword; - HCCPARAMS Data; + UINT32 Dword; + HCCPARAMS Data; } XHC_HCCPARAMS; #pragma pack () @@ -169,19 +168,19 @@ typedef union { // #pragma pack(1) typedef struct { - UINT8 Pi; - UINT8 SubClassCode; - UINT8 BaseCode; + UINT8 Pi; + UINT8 SubClassCode; + UINT8 BaseCode; } USB_CLASSC; typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 NumPorts; - UINT16 HubCharacter; - UINT8 PwrOn2PwrGood; - UINT8 HubContrCurrent; - UINT8 Filler[16]; + UINT8 Length; + UINT8 DescType; + UINT8 NumPorts; + UINT16 HubCharacter; + UINT8 PwrOn2PwrGood; + UINT8 HubContrCurrent; + UINT8 Filler[16]; } EFI_USB_HUB_DESCRIPTOR; #pragma pack() @@ -191,8 +190,8 @@ typedef struct { // For more details, Please refer to USB 3.0 Spec Table 10-7. // typedef enum { - Usb3PortBHPortReset = 28, - Usb3PortBHPortResetChange = 29 + Usb3PortBHPortReset = 28, + Usb3PortBHPortResetChange = 29 } XHC_PORT_FEATURE; // @@ -200,16 +199,16 @@ typedef enum { // UEFI's port states. // typedef struct { - UINT32 HwState; - UINT16 UefiState; + UINT32 HwState; + UINT16 UefiState; } USB_PORT_STATE_MAP; // // Structure to map the hardware port states to feature selector for clear port feature request. // typedef struct { - UINT32 HwState; - UINT16 Selector; + UINT32 HwState; + UINT16 Selector; } USB_CLEAR_PORT_MAP; /** @@ -223,8 +222,8 @@ typedef struct { **/ UINT32 XhcPeiReadOpReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset ); /** @@ -237,9 +236,9 @@ XhcPeiReadOpReg ( **/ VOID XhcPeiWriteOpReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -252,9 +251,9 @@ XhcPeiWriteOpReg ( **/ VOID XhcPeiSetOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -267,9 +266,9 @@ XhcPeiSetOpRegBit ( **/ VOID XhcPeiClearOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -288,14 +287,13 @@ XhcPeiClearOpRegBit ( **/ EFI_STATUS XhcPeiWaitOpRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit, - IN BOOLEAN WaitToSet, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit, + IN BOOLEAN WaitToSet, + IN UINT32 Timeout ); - /** Write the data to the XHCI door bell register. @@ -306,9 +304,9 @@ XhcPeiWaitOpRegBit ( **/ VOID XhcPeiWriteDoorBellReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -322,8 +320,8 @@ XhcPeiWriteDoorBellReg ( **/ UINT32 XhcPeiReadRuntimeReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset ); /** @@ -336,9 +334,9 @@ XhcPeiReadRuntimeReg ( **/ VOID XhcPeiWriteRuntimeReg ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Data + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Data ); /** @@ -351,9 +349,9 @@ XhcPeiWriteRuntimeReg ( **/ VOID XhcPeiSetRuntimeRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -366,9 +364,9 @@ XhcPeiSetRuntimeRegBit ( **/ VOID XhcPeiClearRuntimeRegBit ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Offset, - IN UINT32 Bit + IN PEI_XHC_DEV *Xhc, + IN UINT32 Offset, + IN UINT32 Bit ); /** @@ -382,7 +380,7 @@ XhcPeiClearRuntimeRegBit ( **/ BOOLEAN XhcPeiIsHalt ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ); /** @@ -396,7 +394,7 @@ XhcPeiIsHalt ( **/ BOOLEAN XhcPeiIsSysError ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ); /** @@ -411,8 +409,8 @@ XhcPeiIsSysError ( **/ EFI_STATUS XhcPeiResetHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ); /** @@ -427,8 +425,8 @@ XhcPeiResetHC ( **/ EFI_STATUS XhcPeiHaltHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ); /** @@ -443,8 +441,8 @@ XhcPeiHaltHC ( **/ EFI_STATUS XhcPeiRunHC ( - IN PEI_XHC_DEV *Xhc, - IN UINT32 Timeout + IN PEI_XHC_DEV *Xhc, + IN UINT32 Timeout ); #endif diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c index 1fc06aaa61..cc597a4371 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c @@ -19,25 +19,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @return Created URB or NULL. **/ -URB* +URB * XhcPeiCreateCmdTrb ( - IN PEI_XHC_DEV *Xhc, - IN TRB_TEMPLATE *CmdTrb + IN PEI_XHC_DEV *Xhc, + IN TRB_TEMPLATE *CmdTrb ) { - URB *Urb; + URB *Urb; Urb = AllocateZeroPool (sizeof (URB)); if (Urb == NULL) { return NULL; } - Urb->Signature = XHC_URB_SIG; + Urb->Signature = XHC_URB_SIG; - Urb->Ring = &Xhc->CmdRing; + Urb->Ring = &Xhc->CmdRing; XhcPeiSyncTrsRing (Xhc, Urb->Ring); - Urb->TrbNum = 1; - Urb->TrbStart = Urb->Ring->RingEnqueue; + Urb->TrbNum = 1; + Urb->TrbStart = Urb->Ring->RingEnqueue; CopyMem (Urb->TrbStart, CmdTrb, sizeof (TRB_TEMPLATE)); Urb->TrbStart->CycleBit = Urb->Ring->RingPCS & BIT0; Urb->TrbEnd = Urb->TrbStart; @@ -62,14 +62,14 @@ XhcPeiCreateCmdTrb ( **/ EFI_STATUS XhcPeiCmdTransfer ( - IN PEI_XHC_DEV *Xhc, - IN TRB_TEMPLATE *CmdTrb, - IN UINTN Timeout, - OUT TRB_TEMPLATE **EvtTrb + IN PEI_XHC_DEV *Xhc, + IN TRB_TEMPLATE *CmdTrb, + IN UINTN Timeout, + OUT TRB_TEMPLATE **EvtTrb ) { - EFI_STATUS Status; - URB *Urb; + EFI_STATUS Status; + URB *Urb; // // Validate the parameters @@ -126,24 +126,24 @@ ON_EXIT: @return Created URB or NULL **/ -URB* +URB * XhcPeiCreateUrb ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 BusAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN PEI_XHC_DEV *Xhc, + IN UINT8 BusAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ) { - USB_ENDPOINT *Ep; - EFI_STATUS Status; - URB *Urb; + USB_ENDPOINT *Ep; + EFI_STATUS Status; + URB *Urb; Urb = AllocateZeroPool (sizeof (URB)); if (Urb == NULL) { @@ -154,7 +154,7 @@ XhcPeiCreateUrb ( Ep = &Urb->Ep; Ep->BusAddr = BusAddr; - Ep->EpAddr = (UINT8) (EpAddr & 0x0F); + Ep->EpAddr = (UINT8)(EpAddr & 0x0F); Ep->Direction = ((EpAddr & 0x80) != 0) ? EfiUsbDataIn : EfiUsbDataOut; Ep->DevSpeed = DevSpeed; Ep->MaxPacket = MaxPacket; @@ -185,8 +185,8 @@ XhcPeiCreateUrb ( **/ VOID XhcPeiFreeUrb ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ) { if ((Xhc == NULL) || (Urb == NULL)) { @@ -209,23 +209,23 @@ XhcPeiFreeUrb ( **/ EFI_STATUS XhcPeiCreateTransferTrb ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ) { - VOID *OutputContext; - TRANSFER_RING *EPRing; - UINT8 EPType; - UINT8 SlotId; - UINT8 Dci; - TRB *TrbStart; - UINTN TotalLen; - UINTN Len; - UINTN TrbNum; - EDKII_IOMMU_OPERATION MapOp; - EFI_PHYSICAL_ADDRESS PhyAddr; - VOID *Map; - EFI_STATUS Status; + VOID *OutputContext; + TRANSFER_RING *EPRing; + UINT8 EPType; + UINT8 SlotId; + UINT8 Dci; + TRB *TrbStart; + UINTN TotalLen; + UINTN Len; + UINTN TrbNum; + EDKII_IOMMU_OPERATION MapOp; + EFI_PHYSICAL_ADDRESS PhyAddr; + VOID *Map; + EFI_STATUS Status; SlotId = XhcPeiBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { @@ -238,27 +238,27 @@ XhcPeiCreateTransferTrb ( Urb->Completed = 0; Urb->Result = EFI_USB_NOERROR; - Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); - EPRing = (TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]; - Urb->Ring = EPRing; + Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); + EPRing = (TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]; + Urb->Ring = EPRing; OutputContext = Xhc->UsbDevContext[SlotId].OutputContext; if (Xhc->HcCParams.Data.Csz == 0) { - EPType = (UINT8) ((DEVICE_CONTEXT *)OutputContext)->EP[Dci-1].EPType; + EPType = (UINT8)((DEVICE_CONTEXT *)OutputContext)->EP[Dci-1].EPType; } else { - EPType = (UINT8) ((DEVICE_CONTEXT_64 *)OutputContext)->EP[Dci-1].EPType; + EPType = (UINT8)((DEVICE_CONTEXT_64 *)OutputContext)->EP[Dci-1].EPType; } // // No need to remap. // if ((Urb->Data != NULL) && (Urb->DataMap == NULL)) { - if (((UINT8) (Urb->Ep.Direction)) == EfiUsbDataIn) { + if (((UINT8)(Urb->Ep.Direction)) == EfiUsbDataIn) { MapOp = EdkiiIoMmuOperationBusMasterWrite; } else { MapOp = EdkiiIoMmuOperationBusMasterRead; } - Len = Urb->DataLen; + Len = Urb->DataLen; Status = IoMmuMap (MapOp, Urb->Data, &Len, &PhyAddr, &Map); if (EFI_ERROR (Status) || (Len != Urb->DataLen)) { @@ -266,8 +266,8 @@ XhcPeiCreateTransferTrb ( return EFI_OUT_OF_RESOURCES; } - Urb->DataPhy = (VOID *) ((UINTN) PhyAddr); - Urb->DataMap = Map; + Urb->DataPhy = (VOID *)((UINTN)PhyAddr); + Urb->DataMap = Map; } // @@ -280,7 +280,7 @@ XhcPeiCreateTransferTrb ( // // For control transfer, create SETUP_STAGE_TRB first. // - TrbStart = (TRB *) (UINTN) EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; TrbStart->TrbCtrSetup.bmRequestType = Urb->Request->RequestType; TrbStart->TrbCtrSetup.bRequest = Urb->Request->Request; TrbStart->TrbCtrSetup.wValue = Urb->Request->Value; @@ -303,6 +303,7 @@ XhcPeiCreateTransferTrb ( } else { TrbStart->TrbCtrSetup.TRT = 0; } + // // Update the cycle bit // @@ -314,10 +315,10 @@ XhcPeiCreateTransferTrb ( // if (Urb->DataLen > 0) { XhcPeiSyncTrsRing (Xhc, EPRing); - TrbStart = (TRB *) (UINTN) EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; TrbStart->TrbCtrData.TRBPtrLo = XHC_LOW_32BIT (Urb->DataPhy); TrbStart->TrbCtrData.TRBPtrHi = XHC_HIGH_32BIT (Urb->DataPhy); - TrbStart->TrbCtrData.Length = (UINT32) Urb->DataLen; + TrbStart->TrbCtrData.Length = (UINT32)Urb->DataLen; TrbStart->TrbCtrData.TDSize = 0; TrbStart->TrbCtrData.IntTarget = 0; TrbStart->TrbCtrData.ISP = 1; @@ -332,18 +333,20 @@ XhcPeiCreateTransferTrb ( } else { TrbStart->TrbCtrData.DIR = 0; } + // // Update the cycle bit // TrbStart->TrbCtrData.CycleBit = EPRing->RingPCS & BIT0; Urb->TrbNum++; } + // // For control transfer, create STATUS_STAGE_TRB. // Get the pointer to next TRB for status stage use // XhcPeiSyncTrsRing (Xhc, EPRing); - TrbStart = (TRB *) (UINTN) EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; TrbStart->TrbCtrStatus.IntTarget = 0; TrbStart->TrbCtrStatus.IOC = 1; TrbStart->TrbCtrStatus.CH = 0; @@ -355,6 +358,7 @@ XhcPeiCreateTransferTrb ( } else { TrbStart->TrbCtrStatus.DIR = 0; } + // // Update the cycle bit // @@ -364,7 +368,7 @@ XhcPeiCreateTransferTrb ( // XhcPeiSyncTrsRing (Xhc, EPRing); Urb->TrbNum++; - Urb->TrbEnd = (TRB_TEMPLATE *) (UINTN) TrbStart; + Urb->TrbEnd = (TRB_TEMPLATE *)(UINTN)TrbStart; break; @@ -373,17 +377,18 @@ XhcPeiCreateTransferTrb ( TotalLen = 0; Len = 0; TrbNum = 0; - TrbStart = (TRB *) (UINTN) EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; while (TotalLen < Urb->DataLen) { if ((TotalLen + 0x10000) >= Urb->DataLen) { Len = Urb->DataLen - TotalLen; } else { Len = 0x10000; } - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; - TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.Length = (UINT32) Len; + + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.Length = (UINT32)Len; TrbStart->TrbNormal.TDSize = 0; TrbStart->TrbNormal.IntTarget = 0; TrbStart->TrbNormal.ISP = 1; @@ -408,17 +413,18 @@ XhcPeiCreateTransferTrb ( TotalLen = 0; Len = 0; TrbNum = 0; - TrbStart = (TRB *) (UINTN) EPRing->RingEnqueue; + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; while (TotalLen < Urb->DataLen) { if ((TotalLen + 0x10000) >= Urb->DataLen) { Len = Urb->DataLen - TotalLen; } else { Len = 0x10000; } - TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; - TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT((UINT8 *) Urb->DataPhy + TotalLen); - TrbStart->TrbNormal.Length = (UINT32) Len; + + TrbStart = (TRB *)(UINTN)EPRing->RingEnqueue; + TrbStart->TrbNormal.TRBPtrLo = XHC_LOW_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.TRBPtrHi = XHC_HIGH_32BIT ((UINT8 *)Urb->DataPhy + TotalLen); + TrbStart->TrbNormal.Length = (UINT32)Len; TrbStart->TrbNormal.TDSize = 0; TrbStart->TrbNormal.IntTarget = 0; TrbStart->TrbNormal.ISP = 1; @@ -439,7 +445,7 @@ XhcPeiCreateTransferTrb ( break; default: - DEBUG ((DEBUG_INFO, "Not supported EPType 0x%x!\n",EPType)); + DEBUG ((DEBUG_INFO, "Not supported EPType 0x%x!\n", EPType)); ASSERT (FALSE); break; } @@ -463,20 +469,21 @@ XhcPeiCreateTransferTrb ( **/ EFI_STATUS XhcPeiRecoverHaltedEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; - UINT8 Dci; - UINT8 SlotId; + EFI_STATUS Status; + UINT8 Dci; + UINT8 SlotId; Status = EFI_SUCCESS; SlotId = XhcPeiBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { return EFI_DEVICE_ERROR; } - Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8) (Urb->Ep.Direction)); + + Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); DEBUG ((DEBUG_INFO, "XhcPeiRecoverHaltedEndpoint: Recovery Halted Slot = %x, Dci = %x\n", SlotId, Dci)); @@ -484,7 +491,7 @@ XhcPeiRecoverHaltedEndpoint ( // 1) Send Reset endpoint command to transit from halt to stop state // Status = XhcPeiResetEndpoint (Xhc, SlotId, Dci); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiRecoverHaltedEndpoint: Reset Endpoint Failed, Status = %r\n", Status)); goto Done; } @@ -493,7 +500,7 @@ XhcPeiRecoverHaltedEndpoint ( // 2) Set dequeue pointer // Status = XhcPeiSetTrDequeuePointer (Xhc, SlotId, Dci, Urb); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiRecoverHaltedEndpoint: Set Dequeue Pointer Failed, Status = %r\n", Status)); goto Done; } @@ -522,20 +529,21 @@ Done: **/ EFI_STATUS XhcPeiDequeueTrbFromEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ) { - EFI_STATUS Status; - UINT8 Dci; - UINT8 SlotId; + EFI_STATUS Status; + UINT8 Dci; + UINT8 SlotId; Status = EFI_SUCCESS; SlotId = XhcPeiBusDevAddrToSlotId (Xhc, Urb->Ep.BusAddr); if (SlotId == 0) { return EFI_DEVICE_ERROR; } - Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8) (Urb->Ep.Direction)); + + Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); DEBUG ((DEBUG_INFO, "XhcPeiDequeueTrbFromEndpoint: Stop Slot = %x, Dci = %x\n", SlotId, Dci)); @@ -543,7 +551,7 @@ XhcPeiDequeueTrbFromEndpoint ( // 1) Send Stop endpoint command to stop endpoint. // Status = XhcPeiStopEndpoint (Xhc, SlotId, Dci); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiDequeueTrbFromEndpoint: Stop Endpoint Failed, Status = %r\n", Status)); goto Done; } @@ -552,7 +560,7 @@ XhcPeiDequeueTrbFromEndpoint ( // 2) Set dequeue pointer // Status = XhcPeiSetTrDequeuePointer (Xhc, SlotId, Dci, Urb); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiDequeueTrbFromEndpoint: Set Dequeue Pointer Failed, Status = %r\n", Status)); goto Done; } @@ -578,8 +586,8 @@ Done: **/ BOOLEAN XhcPeiIsTransferRingTrb ( - IN TRB_TEMPLATE *Trb, - IN URB *Urb + IN TRB_TEMPLATE *Trb, + IN URB *Urb ) { TRB_TEMPLATE *CheckedTrb; @@ -593,6 +601,7 @@ XhcPeiIsTransferRingTrb ( if (Trb == CheckedTrb) { return TRUE; } + CheckedTrb++; } @@ -611,20 +620,20 @@ XhcPeiIsTransferRingTrb ( **/ BOOLEAN XhcPeiCheckUrbResult ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ) { - EVT_TRB_TRANSFER *EvtTrb; - TRB_TEMPLATE *TRBPtr; - UINTN Index; - UINT8 TRBType; - EFI_STATUS Status; - URB *CheckedUrb; - UINT64 XhcDequeue; - UINT32 High; - UINT32 Low; - EFI_PHYSICAL_ADDRESS PhyAddr; + EVT_TRB_TRANSFER *EvtTrb; + TRB_TEMPLATE *TRBPtr; + UINTN Index; + UINT8 TRBType; + EFI_STATUS Status; + URB *CheckedUrb; + UINT64 XhcDequeue; + UINT32 High; + UINT32 Low; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT ((Xhc != NULL) && (Urb != NULL)); @@ -646,7 +655,7 @@ XhcPeiCheckUrbResult ( // XhcPeiSyncEventRing (Xhc, &Xhc->EventRing); for (Index = 0; Index < Xhc->EventRing.TrbNumber; Index++) { - Status = XhcPeiCheckNewEvent (Xhc, &Xhc->EventRing, ((TRB_TEMPLATE **) &EvtTrb)); + Status = XhcPeiCheckNewEvent (Xhc, &Xhc->EventRing, ((TRB_TEMPLATE **)&EvtTrb)); if (Status == EFI_NOT_READY) { // // All new events are handled, return directly. @@ -664,8 +673,8 @@ XhcPeiCheckUrbResult ( // // Need convert pci device address to host address // - PhyAddr = (EFI_PHYSICAL_ADDRESS) (EvtTrb->TRBPtrLo | LShiftU64 ((UINT64) EvtTrb->TRBPtrHi, 32)); - TRBPtr = (TRB_TEMPLATE *) (UINTN) UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *) (UINTN) PhyAddr, sizeof (TRB_TEMPLATE)); + PhyAddr = (EFI_PHYSICAL_ADDRESS)(EvtTrb->TRBPtrLo | LShiftU64 ((UINT64)EvtTrb->TRBPtrHi, 32)); + TRBPtr = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE)); // // Update the status of Urb according to the finished event regardless of whether @@ -710,11 +719,12 @@ XhcPeiCheckUrbResult ( DEBUG ((DEBUG_VERBOSE, "XhcPeiCheckUrbResult: short packet happens!\n")); } - TRBType = (UINT8) (TRBPtr->Type); + TRBType = (UINT8)(TRBPtr->Type); if ((TRBType == TRB_TYPE_DATA_STAGE) || (TRBType == TRB_TYPE_NORMAL) || - (TRBType == TRB_TYPE_ISOCH)) { - CheckedUrb->Completed += (((TRANSFER_TRB_NORMAL*)TRBPtr)->Length - EvtTrb->Length); + (TRBType == TRB_TYPE_ISOCH)) + { + CheckedUrb->Completed += (((TRANSFER_TRB_NORMAL *)TRBPtr)->Length - EvtTrb->Length); } break; @@ -739,7 +749,7 @@ XhcPeiCheckUrbResult ( if (CheckedUrb->StartDone && CheckedUrb->EndDone) { CheckedUrb->Finished = TRUE; - CheckedUrb->EvtTrb = (TRB_TEMPLATE *) EvtTrb; + CheckedUrb->EvtTrb = (TRB_TEMPLATE *)EvtTrb; } } @@ -751,9 +761,9 @@ EXIT: // Some 3rd party XHCI external cards don't support single 64-bytes width register access, // So divide it to two 32-bytes width register access. // - Low = XhcPeiReadRuntimeReg (Xhc, XHC_ERDP_OFFSET); - High = XhcPeiReadRuntimeReg (Xhc, XHC_ERDP_OFFSET + 4); - XhcDequeue = (UINT64) (LShiftU64((UINT64) High, 32) | Low); + Low = XhcPeiReadRuntimeReg (Xhc, XHC_ERDP_OFFSET); + High = XhcPeiReadRuntimeReg (Xhc, XHC_ERDP_OFFSET + 4); + XhcDequeue = (UINT64)(LShiftU64 ((UINT64)High, 32) | Low); PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE)); @@ -784,18 +794,18 @@ EXIT: **/ EFI_STATUS XhcPeiExecTransfer ( - IN PEI_XHC_DEV *Xhc, - IN BOOLEAN CmdTransfer, - IN URB *Urb, - IN UINTN Timeout + IN PEI_XHC_DEV *Xhc, + IN BOOLEAN CmdTransfer, + IN URB *Urb, + IN UINTN Timeout ) { - EFI_STATUS Status; - UINTN Index; - UINT64 Loop; - UINT8 SlotId; - UINT8 Dci; - BOOLEAN Finished; + EFI_STATUS Status; + UINTN Index; + UINT64 Loop; + UINT8 SlotId; + UINT8 Dci; + BOOLEAN Finished; if (CmdTransfer) { SlotId = 0; @@ -805,7 +815,8 @@ XhcPeiExecTransfer ( if (SlotId == 0) { return EFI_DEVICE_ERROR; } - Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); + + Dci = XhcPeiEndpointToDci (Urb->Ep.EpAddr, (UINT8)(Urb->Ep.Direction)); } Status = EFI_SUCCESS; @@ -821,6 +832,7 @@ XhcPeiExecTransfer ( if (Finished) { break; } + MicroSecondDelay (XHC_1_MICROSECOND); } @@ -828,7 +840,7 @@ XhcPeiExecTransfer ( Urb->Result = EFI_USB_ERR_TIMEOUT; Status = EFI_TIMEOUT; } else if (Urb->Result != EFI_USB_NOERROR) { - Status = EFI_DEVICE_ERROR; + Status = EFI_DEVICE_ERROR; } return Status; @@ -848,16 +860,16 @@ XhcPeiExecTransfer ( **/ EFI_STATUS XhcPeiPollPortStatusChange ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT8 Port, - IN EFI_USB_PORT_STATUS *PortState + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT8 Port, + IN EFI_USB_PORT_STATUS *PortState ) { - EFI_STATUS Status; - UINT8 Speed; - UINT8 SlotId; - USB_DEV_ROUTE RouteChart; + EFI_STATUS Status; + UINT8 Speed; + UINT8 SlotId; + USB_DEV_ROUTE RouteChart; DEBUG ((DEBUG_INFO, "XhcPeiPollPortStatusChange: PortChangeStatus: %x PortStatus: %x\n", PortState->PortChangeStatus, PortState->PortStatus)); @@ -872,13 +884,14 @@ XhcPeiPollPortStatusChange ( RouteChart.Route.RootPortNum = Port + 1; RouteChart.Route.TierNum = 1; } else { - if(Port < 14) { + if (Port < 14) { RouteChart.Route.RouteString = ParentRouteChart.Route.RouteString | (Port << (4 * (ParentRouteChart.Route.TierNum - 1))); } else { RouteChart.Route.RouteString = ParentRouteChart.Route.RouteString | (15 << (4 * (ParentRouteChart.Route.TierNum - 1))); } - RouteChart.Route.RootPortNum = ParentRouteChart.Route.RootPortNum; - RouteChart.Route.TierNum = ParentRouteChart.Route.TierNum + 1; + + RouteChart.Route.RootPortNum = ParentRouteChart.Route.RootPortNum; + RouteChart.Route.TierNum = ParentRouteChart.Route.TierNum + 1; } SlotId = XhcPeiRouteStringToSlotId (Xhc, RouteChart); @@ -891,7 +904,8 @@ XhcPeiPollPortStatusChange ( } if (((PortState->PortStatus & USB_PORT_STAT_ENABLE) != 0) && - ((PortState->PortStatus & USB_PORT_STAT_CONNECTION) != 0)) { + ((PortState->PortStatus & USB_PORT_STAT_CONNECTION) != 0)) + { // // Has a device attached, Identify device speed after port is enabled. // @@ -903,6 +917,7 @@ XhcPeiPollPortStatusChange ( } else if ((PortState->PortStatus & USB_PORT_STAT_SUPER_SPEED) != 0) { Speed = EFI_USB_SPEED_SUPER; } + // // Execute Enable_Slot cmd for attached device, initialize device context and assign device address. // @@ -930,21 +945,22 @@ XhcPeiPollPortStatusChange ( **/ UINT8 XhcPeiEndpointToDci ( - IN UINT8 EpAddr, - IN EFI_USB_DATA_DIRECTION Direction + IN UINT8 EpAddr, + IN EFI_USB_DATA_DIRECTION Direction ) { - UINT8 Index; + UINT8 Index; ASSERT (EpAddr <= 15); if (EpAddr == 0) { return 1; } else { - Index = (UINT8) (2 * EpAddr); + Index = (UINT8)(2 * EpAddr); if (Direction == EfiUsbDataIn) { Index += 1; } + return Index; } } @@ -960,16 +976,17 @@ XhcPeiEndpointToDci ( **/ UINT8 XhcPeiBusDevAddrToSlotId ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 BusDevAddr + IN PEI_XHC_DEV *Xhc, + IN UINT8 BusDevAddr ) { - UINT8 Index; + UINT8 Index; for (Index = 0; Index < 255; Index++) { if (Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId != 0) && - (Xhc->UsbDevContext[Index + 1].BusDevAddr == BusDevAddr)) { + (Xhc->UsbDevContext[Index + 1].BusDevAddr == BusDevAddr)) + { break; } } @@ -992,16 +1009,17 @@ XhcPeiBusDevAddrToSlotId ( **/ UINT8 XhcPeiRouteStringToSlotId ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE RouteString + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE RouteString ) { - UINT8 Index; + UINT8 Index; for (Index = 0; Index < 255; Index++) { if (Xhc->UsbDevContext[Index + 1].Enabled && (Xhc->UsbDevContext[Index + 1].SlotId != 0) && - (Xhc->UsbDevContext[Index + 1].RouteString.Dword == RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].RouteString.Dword == RouteString.Dword)) + { break; } } @@ -1023,9 +1041,9 @@ XhcPeiRouteStringToSlotId ( **/ VOID XhcPeiRingDoorBell ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ) { if (SlotId == 0) { @@ -1050,25 +1068,25 @@ XhcPeiRingDoorBell ( **/ EFI_STATUS XhcPeiInitializeDeviceSlot ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT *InputContext; - DEVICE_CONTEXT *OutputContext; - TRANSFER_RING *EndpointTransferRing; - CMD_TRB_ADDRESS_DEVICE CmdTrbAddr; - UINT8 DeviceAddress; - CMD_TRB_ENABLE_SLOT CmdTrb; - UINT8 SlotId; - UINT8 ParentSlotId; - DEVICE_CONTEXT *ParentDeviceContext; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT *InputContext; + DEVICE_CONTEXT *OutputContext; + TRANSFER_RING *EndpointTransferRing; + CMD_TRB_ADDRESS_DEVICE CmdTrbAddr; + UINT8 DeviceAddress; + CMD_TRB_ENABLE_SLOT CmdTrb; + UINT8 SlotId; + UINT8 ParentSlotId; + DEVICE_CONTEXT *ParentDeviceContext; + EFI_PHYSICAL_ADDRESS PhyAddr; ZeroMem (&CmdTrb, sizeof (CMD_TRB_ENABLE_SLOT)); CmdTrb.CycleBit = 1; @@ -1076,17 +1094,18 @@ XhcPeiInitializeDeviceSlot ( Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrb, + (TRB_TEMPLATE *)(UINTN)&CmdTrb, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiInitializeDeviceSlot: Enable Slot Failed, Status = %r\n", Status)); return Status; } + ASSERT (EvtTrb->SlotId <= Xhc->MaxSlotsEn); DEBUG ((DEBUG_INFO, "XhcPeiInitializeDeviceSlot: Enable Slot Successfully, The Slot ID = 0x%x\n", EvtTrb->SlotId)); - SlotId = (UINT8) EvtTrb->SlotId; + SlotId = (UINT8)EvtTrb->SlotId; ASSERT (SlotId != 0); ZeroMem (&Xhc->UsbDevContext[SlotId], sizeof (USB_DEV_CONTEXT)); @@ -1101,10 +1120,10 @@ XhcPeiInitializeDeviceSlot ( // InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT)); ASSERT (InputContext != NULL); - ASSERT (((UINTN) InputContext & 0x3F) == 0); + ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT)); - Xhc->UsbDevContext[SlotId].InputContext = (VOID *) InputContext; + Xhc->UsbDevContext[SlotId].InputContext = (VOID *)InputContext; // // 2) Initialize the Input Control Context (6.2.5.1) of the Input Context by setting the A0 and A1 @@ -1130,9 +1149,10 @@ XhcPeiInitializeDeviceSlot ( // // If the Full/Low device attached to a High Speed Hub, init the TTPortNum and TTHubSlotId field of slot context // - ParentDeviceContext = (DEVICE_CONTEXT *) Xhc->UsbDevContext[ParentSlotId].OutputContext; + ParentDeviceContext = (DEVICE_CONTEXT *)Xhc->UsbDevContext[ParentSlotId].OutputContext; if ((ParentDeviceContext->Slot.TTPortNum == 0) && - (ParentDeviceContext->Slot.TTHubSlotId == 0)) { + (ParentDeviceContext->Slot.TTHubSlotId == 0)) + { if ((ParentDeviceContext->Slot.Speed == (EFI_USB_SPEED_HIGH + 1)) && (DeviceSpeed < EFI_USB_SPEED_HIGH)) { // // Full/Low device attached to High speed hub port that isolates the high speed signaling @@ -1159,9 +1179,9 @@ XhcPeiInitializeDeviceSlot ( // // 4) Allocate and initialize the Transfer Ring for the Default Control Endpoint. // - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); Xhc->UsbDevContext[SlotId].EndpointTransferRing[0] = EndpointTransferRing; - XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); // // 5) Initialize the Input default control Endpoint 0 Context (6.2.3). // @@ -1174,6 +1194,7 @@ XhcPeiInitializeDeviceSlot ( } else { InputContext->EP[0].MaxPacketSize = 8; } + // // Initial value of Average TRB Length for Control endpoints would be 8B, Interrupt endpoints // 1KB, and Bulk and Isoch endpoints 3KB. @@ -1190,7 +1211,7 @@ XhcPeiInitializeDeviceSlot ( // PhyAddr = UsbHcGetPciAddrForHostAddr ( Xhc->MemPool, - ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0, + ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0; @@ -1201,7 +1222,7 @@ XhcPeiInitializeDeviceSlot ( // OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT)); ASSERT (OutputContext != NULL); - ASSERT (((UINTN) OutputContext & 0x3F) == 0); + ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT)); Xhc->UsbDevContext[SlotId].OutputContext = OutputContext; @@ -1213,7 +1234,7 @@ XhcPeiInitializeDeviceSlot ( // // Fill DCBAA with PCI device address // - Xhc->DCBAA[SlotId] = (UINT64) (UINTN) PhyAddr; + Xhc->DCBAA[SlotId] = (UINT64)(UINTN)PhyAddr; // // 8) Issue an Address Device Command for the Device Slot, where the command points to the Input @@ -1224,20 +1245,20 @@ XhcPeiInitializeDeviceSlot ( // MicroSecondDelay (XHC_RESET_RECOVERY_DELAY); ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT)); CmdTrbAddr.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbAddr.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbAddr.CycleBit = 1; CmdTrbAddr.Type = TRB_TYPE_ADDRESS_DEV; CmdTrbAddr.SlotId = Xhc->UsbDevContext[SlotId].SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbAddr, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbAddr, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (!EFI_ERROR (Status)) { - DeviceAddress = (UINT8) OutputContext->Slot.DeviceAddress; + DeviceAddress = (UINT8)OutputContext->Slot.DeviceAddress; DEBUG ((DEBUG_INFO, "XhcPeiInitializeDeviceSlot: Address %d assigned successfully\n", DeviceAddress)); Xhc->UsbDevContext[SlotId].XhciDevAddr = DeviceAddress; } @@ -1261,25 +1282,25 @@ XhcPeiInitializeDeviceSlot ( **/ EFI_STATUS XhcPeiInitializeDeviceSlot64 ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT_64 *InputContext; - DEVICE_CONTEXT_64 *OutputContext; - TRANSFER_RING *EndpointTransferRing; - CMD_TRB_ADDRESS_DEVICE CmdTrbAddr; - UINT8 DeviceAddress; - CMD_TRB_ENABLE_SLOT CmdTrb; - UINT8 SlotId; - UINT8 ParentSlotId; - DEVICE_CONTEXT_64 *ParentDeviceContext; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT_64 *InputContext; + DEVICE_CONTEXT_64 *OutputContext; + TRANSFER_RING *EndpointTransferRing; + CMD_TRB_ADDRESS_DEVICE CmdTrbAddr; + UINT8 DeviceAddress; + CMD_TRB_ENABLE_SLOT CmdTrb; + UINT8 SlotId; + UINT8 ParentSlotId; + DEVICE_CONTEXT_64 *ParentDeviceContext; + EFI_PHYSICAL_ADDRESS PhyAddr; ZeroMem (&CmdTrb, sizeof (CMD_TRB_ENABLE_SLOT)); CmdTrb.CycleBit = 1; @@ -1287,14 +1308,15 @@ XhcPeiInitializeDeviceSlot64 ( Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrb, + (TRB_TEMPLATE *)(UINTN)&CmdTrb, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiInitializeDeviceSlot64: Enable Slot Failed, Status = %r\n", Status)); return Status; } + ASSERT (EvtTrb->SlotId <= Xhc->MaxSlotsEn); DEBUG ((DEBUG_INFO, "XhcPeiInitializeDeviceSlot64: Enable Slot Successfully, The Slot ID = 0x%x\n", EvtTrb->SlotId)); SlotId = (UINT8)EvtTrb->SlotId; @@ -1312,10 +1334,10 @@ XhcPeiInitializeDeviceSlot64 ( // InputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (INPUT_CONTEXT_64)); ASSERT (InputContext != NULL); - ASSERT (((UINTN) InputContext & 0x3F) == 0); + ASSERT (((UINTN)InputContext & 0x3F) == 0); ZeroMem (InputContext, sizeof (INPUT_CONTEXT_64)); - Xhc->UsbDevContext[SlotId].InputContext = (VOID *) InputContext; + Xhc->UsbDevContext[SlotId].InputContext = (VOID *)InputContext; // // 2) Initialize the Input Control Context (6.2.5.1) of the Input Context by setting the A0 and A1 @@ -1339,11 +1361,12 @@ XhcPeiInitializeDeviceSlot64 ( ParentSlotId = XhcPeiRouteStringToSlotId (Xhc, ParentRouteChart); ASSERT (ParentSlotId != 0); // - //if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context + // if the Full/Low device attached to a High Speed Hub, Init the TTPortNum and TTHubSlotId field of slot context // - ParentDeviceContext = (DEVICE_CONTEXT_64 *) Xhc->UsbDevContext[ParentSlotId].OutputContext; + ParentDeviceContext = (DEVICE_CONTEXT_64 *)Xhc->UsbDevContext[ParentSlotId].OutputContext; if ((ParentDeviceContext->Slot.TTPortNum == 0) && - (ParentDeviceContext->Slot.TTHubSlotId == 0)) { + (ParentDeviceContext->Slot.TTHubSlotId == 0)) + { if ((ParentDeviceContext->Slot.Speed == (EFI_USB_SPEED_HIGH + 1)) && (DeviceSpeed < EFI_USB_SPEED_HIGH)) { // // Full/Low device attached to High speed hub port that isolates the high speed signaling @@ -1370,9 +1393,9 @@ XhcPeiInitializeDeviceSlot64 ( // // 4) Allocate and initialize the Transfer Ring for the Default Control Endpoint. // - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); Xhc->UsbDevContext[SlotId].EndpointTransferRing[0] = EndpointTransferRing; - XhcPeiCreateTransferRing(Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0]); // // 5) Initialize the Input default control Endpoint 0 Context (6.2.3). // @@ -1385,6 +1408,7 @@ XhcPeiInitializeDeviceSlot64 ( } else { InputContext->EP[0].MaxPacketSize = 8; } + // // Initial value of Average TRB Length for Control endpoints would be 8B, Interrupt endpoints // 1KB, and Bulk and Isoch endpoints 3KB. @@ -1401,7 +1425,7 @@ XhcPeiInitializeDeviceSlot64 ( // PhyAddr = UsbHcGetPciAddrForHostAddr ( Xhc->MemPool, - ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0, + ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0; @@ -1412,7 +1436,7 @@ XhcPeiInitializeDeviceSlot64 ( // OutputContext = UsbHcAllocateMem (Xhc->MemPool, sizeof (DEVICE_CONTEXT_64)); ASSERT (OutputContext != NULL); - ASSERT (((UINTN) OutputContext & 0x3F) == 0); + ASSERT (((UINTN)OutputContext & 0x3F) == 0); ZeroMem (OutputContext, sizeof (DEVICE_CONTEXT_64)); Xhc->UsbDevContext[SlotId].OutputContext = OutputContext; @@ -1424,7 +1448,7 @@ XhcPeiInitializeDeviceSlot64 ( // // Fill DCBAA with PCI device address // - Xhc->DCBAA[SlotId] = (UINT64) (UINTN) PhyAddr; + Xhc->DCBAA[SlotId] = (UINT64)(UINTN)PhyAddr; // // 8) Issue an Address Device Command for the Device Slot, where the command points to the Input @@ -1435,20 +1459,20 @@ XhcPeiInitializeDeviceSlot64 ( // MicroSecondDelay (XHC_RESET_RECOVERY_DELAY); ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbAddr.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbAddr.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbAddr.CycleBit = 1; CmdTrbAddr.Type = TRB_TYPE_ADDRESS_DEV; CmdTrbAddr.SlotId = Xhc->UsbDevContext[SlotId].SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbAddr, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbAddr, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (!EFI_ERROR (Status)) { - DeviceAddress = (UINT8) OutputContext->Slot.DeviceAddress; + DeviceAddress = (UINT8)OutputContext->Slot.DeviceAddress; DEBUG ((DEBUG_INFO, "XhcPeiInitializeDeviceSlot64: Address %d assigned successfully\n", DeviceAddress)); Xhc->UsbDevContext[SlotId].XhciDevAddr = DeviceAddress; } @@ -1457,7 +1481,6 @@ XhcPeiInitializeDeviceSlot64 ( return Status; } - /** Disable the specified device slot. @@ -1469,8 +1492,8 @@ XhcPeiInitializeDeviceSlot64 ( **/ EFI_STATUS XhcPeiDisableSlotCmd ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId ) { EFI_STATUS Status; @@ -1486,7 +1509,8 @@ XhcPeiDisableSlotCmd ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled || (Xhc->UsbDevContext[Index + 1].SlotId == 0) || - (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) + { continue; } @@ -1507,16 +1531,17 @@ XhcPeiDisableSlotCmd ( CmdTrbDisSlot.CycleBit = 1; CmdTrbDisSlot.Type = TRB_TYPE_DIS_SLOT; CmdTrbDisSlot.SlotId = SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbDisSlot, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbDisSlot, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiDisableSlotCmd: Disable Slot Command Failed, Status = %r\n", Status)); return Status; } + // // Free the slot's device context entry // @@ -1527,10 +1552,11 @@ XhcPeiDisableSlotCmd ( // for (Index = 0; Index < 31; Index++) { if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] != NULL) { - RingSeg = ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index])->RingSeg0; + RingSeg = ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index])->RingSeg0; if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] = NULL; } @@ -1549,6 +1575,7 @@ XhcPeiDisableSlotCmd ( if (Xhc->UsbDevContext[SlotId].OutputContext != NULL) { UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT)); } + // // Doesn't zero the entry because XhcAsyncInterruptTransfer() may be invoked to remove the established // asynchronous interrupt pipe after the device is disabled. It needs the device address mapping info to @@ -1572,8 +1599,8 @@ XhcPeiDisableSlotCmd ( **/ EFI_STATUS XhcPeiDisableSlotCmd64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId ) { EFI_STATUS Status; @@ -1589,7 +1616,8 @@ XhcPeiDisableSlotCmd64 ( for (Index = 0; Index < 255; Index++) { if (!Xhc->UsbDevContext[Index + 1].Enabled || (Xhc->UsbDevContext[Index + 1].SlotId == 0) || - (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) { + (Xhc->UsbDevContext[Index + 1].ParentRouteString.Dword != Xhc->UsbDevContext[SlotId].RouteString.Dword)) + { continue; } @@ -1610,16 +1638,17 @@ XhcPeiDisableSlotCmd64 ( CmdTrbDisSlot.CycleBit = 1; CmdTrbDisSlot.Type = TRB_TYPE_DIS_SLOT; CmdTrbDisSlot.SlotId = SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbDisSlot, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbDisSlot, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiDisableSlotCmd64: Disable Slot Command Failed, Status = %r\n", Status)); return Status; } + // // Free the slot's device context entry // @@ -1630,10 +1659,11 @@ XhcPeiDisableSlotCmd64 ( // for (Index = 0; Index < 31; Index++) { if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] != NULL) { - RingSeg = ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index])->RingSeg0; + RingSeg = ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index])->RingSeg0; if (RingSeg != NULL) { UsbHcFreeMem (Xhc->MemPool, RingSeg, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER); } + FreePool (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index]); Xhc->UsbDevContext[SlotId].EndpointTransferRing[Index] = NULL; } @@ -1650,8 +1680,9 @@ XhcPeiDisableSlotCmd64 ( } if (Xhc->UsbDevContext[SlotId].OutputContext != NULL) { - UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT_64)); + UsbHcFreeMem (Xhc->MemPool, Xhc->UsbDevContext[SlotId].OutputContext, sizeof (DEVICE_CONTEXT_64)); } + // // Doesn't zero the entry because XhcAsyncInterruptTransfer() may be invoked to remove the established // asynchronous interrupt pipe after the device is disabled. It needs the device address mapping info to @@ -1677,30 +1708,31 @@ XhcPeiDisableSlotCmd64 ( **/ EFI_STATUS XhcPeiSetConfigCmd ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDesc; - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINT8 Index; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - EFI_USB_DATA_DIRECTION Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINT8 Interval; - - TRANSFER_RING *EndpointTransferRing; - CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; - INPUT_CONTEXT *InputContext; - DEVICE_CONTEXT *OutputContext; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDesc; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINT8 Index; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + EFI_USB_DATA_DIRECTION Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINT8 Interval; + + TRANSFER_RING *EndpointTransferRing; + CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; + INPUT_CONTEXT *InputContext; + DEVICE_CONTEXT *OutputContext; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + // // 4.6.6 Configure Endpoint // @@ -1713,22 +1745,22 @@ XhcPeiSetConfigCmd ( MaxDci = 0; - IfDesc = (USB_INTERFACE_DESCRIPTOR *) (ConfigDesc + 1); + IfDesc = (USB_INTERFACE_DESCRIPTOR *)(ConfigDesc + 1); for (Index = 0; Index < ConfigDesc->NumInterfaces; Index++) { while ((IfDesc->DescriptorType != USB_DESC_TYPE_INTERFACE) || (IfDesc->AlternateSetting != 0)) { - IfDesc = (USB_INTERFACE_DESCRIPTOR *) ((UINTN) IfDesc + IfDesc->Length); + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } NumEp = IfDesc->NumEndpoints; - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) (IfDesc + 1); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { while (EpDesc->DescriptorType != USB_DESC_TYPE_ENDPOINT) { - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) ((UINTN) EpDesc + EpDesc->Length); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); } - EpAddr = (UINT8) (EpDesc->EndpointAddress & 0x0F); - Direction = (UINT8) ((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); + EpAddr = (UINT8)(EpDesc->EndpointAddress & 0x0F); + Direction = (UINT8)((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); Dci = XhcPeiEndpointToDci (EpAddr, Direction); if (Dci > MaxDci) { @@ -1759,9 +1791,9 @@ XhcPeiSetConfigCmd ( InputContext->EP[Dci-1].AverageTRBLength = 0x1000; if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); } break; @@ -1773,6 +1805,7 @@ XhcPeiSetConfigCmd ( InputContext->EP[Dci-1].CErr = 0; InputContext->EP[Dci-1].EPType = ED_ISOCH_OUT; } + // // Get the bInterval from descriptor and init the the interval field of endpoint context. // Refer to XHCI 1.1 spec section 6.2.3.6. @@ -1801,6 +1834,7 @@ XhcPeiSetConfigCmd ( InputContext->EP[Dci-1].CErr = 3; InputContext->EP[Dci-1].EPType = ED_INTERRUPT_OUT; } + InputContext->EP[Dci-1].AverageTRBLength = 0x1000; InputContext->EP[Dci-1].MaxESITPayload = EpDesc->MaxPacketSize; // @@ -1812,7 +1846,7 @@ XhcPeiSetConfigCmd ( // Calculate through the bInterval field of Endpoint descriptor. // ASSERT (Interval != 0); - InputContext->EP[Dci-1].Interval = (UINT32) HighBitSet32 ((UINT32) Interval) + 3; + InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32 ((UINT32)Interval) + 3; } else if ((DeviceSpeed == EFI_USB_SPEED_HIGH) || (DeviceSpeed == EFI_USB_SPEED_SUPER)) { Interval = EpDesc->Interval; ASSERT (Interval >= 1 && Interval <= 16); @@ -1823,10 +1857,11 @@ XhcPeiSetConfigCmd ( } if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); } + break; case USB_ENDPOINT_CONTROL: @@ -1842,17 +1877,18 @@ XhcPeiSetConfigCmd ( PhyAddr = UsbHcGetPciAddrForHostAddr ( Xhc->MemPool, - ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, + ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); - PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); - PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; + PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); + PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; InputContext->EP[Dci-1].PtrLo = XHC_LOW_32BIT (PhyAddr); InputContext->EP[Dci-1].PtrHi = XHC_HIGH_32BIT (PhyAddr); - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) ((UINTN) EpDesc + EpDesc->Length); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); } - IfDesc = (USB_INTERFACE_DESCRIPTOR *) ((UINTN) IfDesc + IfDesc->Length); + + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } InputContext->InputControlContext.Dword2 |= BIT0; @@ -1861,7 +1897,7 @@ XhcPeiSetConfigCmd ( // configure endpoint // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -1870,13 +1906,14 @@ XhcPeiSetConfigCmd ( DEBUG ((DEBUG_INFO, "XhcSetConfigCmd: Configure Endpoint\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSetConfigCmd: Config Endpoint Failed, Status = %r\n", Status)); } + return Status; } @@ -1893,30 +1930,31 @@ XhcPeiSetConfigCmd ( **/ EFI_STATUS XhcPeiSetConfigCmd64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ) { - EFI_STATUS Status; - USB_INTERFACE_DESCRIPTOR *IfDesc; - USB_ENDPOINT_DESCRIPTOR *EpDesc; - UINT8 Index; - UINTN NumEp; - UINTN EpIndex; - UINT8 EpAddr; - EFI_USB_DATA_DIRECTION Direction; - UINT8 Dci; - UINT8 MaxDci; - EFI_PHYSICAL_ADDRESS PhyAddr; - UINT8 Interval; - - TRANSFER_RING *EndpointTransferRing; - CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; - INPUT_CONTEXT_64 *InputContext; - DEVICE_CONTEXT_64 *OutputContext; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; + EFI_STATUS Status; + USB_INTERFACE_DESCRIPTOR *IfDesc; + USB_ENDPOINT_DESCRIPTOR *EpDesc; + UINT8 Index; + UINTN NumEp; + UINTN EpIndex; + UINT8 EpAddr; + EFI_USB_DATA_DIRECTION Direction; + UINT8 Dci; + UINT8 MaxDci; + EFI_PHYSICAL_ADDRESS PhyAddr; + UINT8 Interval; + + TRANSFER_RING *EndpointTransferRing; + CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; + INPUT_CONTEXT_64 *InputContext; + DEVICE_CONTEXT_64 *OutputContext; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + // // 4.6.6 Configure Endpoint // @@ -1929,22 +1967,22 @@ XhcPeiSetConfigCmd64 ( MaxDci = 0; - IfDesc = (USB_INTERFACE_DESCRIPTOR *) (ConfigDesc + 1); + IfDesc = (USB_INTERFACE_DESCRIPTOR *)(ConfigDesc + 1); for (Index = 0; Index < ConfigDesc->NumInterfaces; Index++) { while ((IfDesc->DescriptorType != USB_DESC_TYPE_INTERFACE) || (IfDesc->AlternateSetting != 0)) { - IfDesc = (USB_INTERFACE_DESCRIPTOR *) ((UINTN) IfDesc + IfDesc->Length); + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } NumEp = IfDesc->NumEndpoints; - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) (IfDesc + 1); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)(IfDesc + 1); for (EpIndex = 0; EpIndex < NumEp; EpIndex++) { while (EpDesc->DescriptorType != USB_DESC_TYPE_ENDPOINT) { - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) ((UINTN) EpDesc + EpDesc->Length); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); } - EpAddr = (UINT8) (EpDesc->EndpointAddress & 0x0F); - Direction = (UINT8) ((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); + EpAddr = (UINT8)(EpDesc->EndpointAddress & 0x0F); + Direction = (UINT8)((EpDesc->EndpointAddress & 0x80) ? EfiUsbDataIn : EfiUsbDataOut); Dci = XhcPeiEndpointToDci (EpAddr, Direction); ASSERT (Dci < 32); @@ -1976,9 +2014,9 @@ XhcPeiSetConfigCmd64 ( InputContext->EP[Dci-1].AverageTRBLength = 0x1000; if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); } break; @@ -1990,6 +2028,7 @@ XhcPeiSetConfigCmd64 ( InputContext->EP[Dci-1].CErr = 0; InputContext->EP[Dci-1].EPType = ED_ISOCH_OUT; } + // // Get the bInterval from descriptor and init the the interval field of endpoint context. // Refer to XHCI 1.1 spec section 6.2.3.6. @@ -2018,6 +2057,7 @@ XhcPeiSetConfigCmd64 ( InputContext->EP[Dci-1].CErr = 3; InputContext->EP[Dci-1].EPType = ED_INTERRUPT_OUT; } + InputContext->EP[Dci-1].AverageTRBLength = 0x1000; InputContext->EP[Dci-1].MaxESITPayload = EpDesc->MaxPacketSize; // @@ -2029,7 +2069,7 @@ XhcPeiSetConfigCmd64 ( // Calculate through the bInterval field of Endpoint descriptor. // ASSERT (Interval != 0); - InputContext->EP[Dci-1].Interval = (UINT32) HighBitSet32( (UINT32) Interval) + 3; + InputContext->EP[Dci-1].Interval = (UINT32)HighBitSet32 ((UINT32)Interval) + 3; } else if ((DeviceSpeed == EFI_USB_SPEED_HIGH) || (DeviceSpeed == EFI_USB_SPEED_SUPER)) { Interval = EpDesc->Interval; ASSERT (Interval >= 1 && Interval <= 16); @@ -2040,10 +2080,11 @@ XhcPeiSetConfigCmd64 ( } if (Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] == NULL) { - EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); - Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *) EndpointTransferRing; - XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); + EndpointTransferRing = AllocateZeroPool (sizeof (TRANSFER_RING)); + Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1] = (VOID *)EndpointTransferRing; + XhcPeiCreateTransferRing (Xhc, TR_RING_TRB_NUMBER, (TRANSFER_RING *)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1]); } + break; case USB_ENDPOINT_CONTROL: @@ -2059,19 +2100,20 @@ XhcPeiSetConfigCmd64 ( PhyAddr = UsbHcGetPciAddrForHostAddr ( Xhc->MemPool, - ((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, + ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0, sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER ); PhyAddr &= ~((EFI_PHYSICAL_ADDRESS)0x0F); - PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *) (UINTN) Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; + PhyAddr |= (EFI_PHYSICAL_ADDRESS)((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingPCS; InputContext->EP[Dci-1].PtrLo = XHC_LOW_32BIT (PhyAddr); InputContext->EP[Dci-1].PtrHi = XHC_HIGH_32BIT (PhyAddr); - EpDesc = (USB_ENDPOINT_DESCRIPTOR *) ((UINTN)EpDesc + EpDesc->Length); + EpDesc = (USB_ENDPOINT_DESCRIPTOR *)((UINTN)EpDesc + EpDesc->Length); } - IfDesc = (USB_INTERFACE_DESCRIPTOR *) ((UINTN)IfDesc + IfDesc->Length); + + IfDesc = (USB_INTERFACE_DESCRIPTOR *)((UINTN)IfDesc + IfDesc->Length); } InputContext->InputControlContext.Dword2 |= BIT0; @@ -2080,7 +2122,7 @@ XhcPeiSetConfigCmd64 ( // configure endpoint // ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -2089,9 +2131,9 @@ XhcPeiSetConfigCmd64 ( DEBUG ((DEBUG_INFO, "XhcSetConfigCmd64: Configure Endpoint\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcSetConfigCmd64: Config Endpoint Failed, Status = %r\n", Status)); @@ -2100,7 +2142,6 @@ XhcPeiSetConfigCmd64 ( return Status; } - /** Evaluate the endpoint 0 context through XHCI's Evaluate_Context cmd. @@ -2113,16 +2154,16 @@ XhcPeiSetConfigCmd64 ( **/ EFI_STATUS XhcPeiEvaluateContext ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ) { - EFI_STATUS Status; - CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT *InputContext; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT *InputContext; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); @@ -2136,7 +2177,7 @@ XhcPeiEvaluateContext ( InputContext->EP[0].MaxPacketSize = MaxPacketSize; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbEvalu.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbEvalu.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbEvalu.CycleBit = 1; @@ -2145,13 +2186,14 @@ XhcPeiEvaluateContext ( DEBUG ((DEBUG_INFO, "XhcEvaluateContext: Evaluate context\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbEvalu, + (TRB_TEMPLATE *)(UINTN)&CmdTrbEvalu, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcEvaluateContext: Evaluate Context Failed, Status = %r\n", Status)); } + return Status; } @@ -2167,16 +2209,16 @@ XhcPeiEvaluateContext ( **/ EFI_STATUS XhcPeiEvaluateContext64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ) { - EFI_STATUS Status; - CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT_64 *InputContext; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + CMD_TRB_EVALUATE_CONTEXT CmdTrbEvalu; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT_64 *InputContext; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); @@ -2190,7 +2232,7 @@ XhcPeiEvaluateContext64 ( InputContext->EP[0].MaxPacketSize = MaxPacketSize; ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbEvalu.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbEvalu.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbEvalu.CycleBit = 1; @@ -2199,13 +2241,14 @@ XhcPeiEvaluateContext64 ( DEBUG ((DEBUG_INFO, "XhcEvaluateContext64: Evaluate context 64\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbEvalu, + (TRB_TEMPLATE *)(UINTN)&CmdTrbEvalu, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcEvaluateContext64: Evaluate Context Failed, Status = %r\n", Status)); } + return Status; } @@ -2223,19 +2266,19 @@ XhcPeiEvaluateContext64 ( **/ EFI_STATUS XhcPeiConfigHubContext ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT *InputContext; - DEVICE_CONTEXT *OutputContext; - CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT *InputContext; + DEVICE_CONTEXT *OutputContext; + CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); InputContext = Xhc->UsbDevContext[SlotId].InputContext; @@ -2251,14 +2294,14 @@ XhcPeiConfigHubContext ( // // Copy the slot context from OutputContext to Input context // - CopyMem(&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT)); + CopyMem (&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT)); InputContext->Slot.Hub = 1; InputContext->Slot.PortNum = PortNum; InputContext->Slot.TTT = TTT; InputContext->Slot.MTT = MTT; ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -2267,13 +2310,14 @@ XhcPeiConfigHubContext ( DEBUG ((DEBUG_INFO, "Configure Hub Slot Context\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcConfigHubContext: Config Endpoint Failed, Status = %r\n", Status)); } + return Status; } @@ -2291,19 +2335,19 @@ XhcPeiConfigHubContext ( **/ EFI_STATUS XhcPeiConfigHubContext64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - INPUT_CONTEXT_64 *InputContext; - DEVICE_CONTEXT_64 *OutputContext; - CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; - EFI_PHYSICAL_ADDRESS PhyAddr; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + INPUT_CONTEXT_64 *InputContext; + DEVICE_CONTEXT_64 *OutputContext; + CMD_TRB_CONFIG_ENDPOINT CmdTrbCfgEP; + EFI_PHYSICAL_ADDRESS PhyAddr; ASSERT (Xhc->UsbDevContext[SlotId].SlotId != 0); InputContext = Xhc->UsbDevContext[SlotId].InputContext; @@ -2319,14 +2363,14 @@ XhcPeiConfigHubContext64 ( // // Copy the slot context from OutputContext to Input context // - CopyMem(&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT_64)); + CopyMem (&(InputContext->Slot), &(OutputContext->Slot), sizeof (SLOT_CONTEXT_64)); InputContext->Slot.Hub = 1; InputContext->Slot.PortNum = PortNum; InputContext->Slot.TTT = TTT; InputContext->Slot.MTT = MTT; ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64)); CmdTrbCfgEP.PtrLo = XHC_LOW_32BIT (PhyAddr); CmdTrbCfgEP.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdTrbCfgEP.CycleBit = 1; @@ -2335,13 +2379,14 @@ XhcPeiConfigHubContext64 ( DEBUG ((DEBUG_INFO, "Configure Hub Slot Context 64\n")); Status = XhcPeiCmdTransfer ( Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbCfgEP, + (TRB_TEMPLATE *)(UINTN)&CmdTrbCfgEP, XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb + (TRB_TEMPLATE **)(UINTN)&EvtTrb ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcConfigHubContext64: Config Endpoint Failed, Status = %r\n", Status)); } + return Status; } @@ -2359,14 +2404,14 @@ XhcPeiConfigHubContext64 ( EFI_STATUS EFIAPI XhcPeiStopEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ) { - EFI_STATUS Status; - EVT_TRB_COMMAND_COMPLETION *EvtTrb; - CMD_TRB_STOP_ENDPOINT CmdTrbStopED; + EFI_STATUS Status; + EVT_TRB_COMMAND_COMPLETION *EvtTrb; + CMD_TRB_STOP_ENDPOINT CmdTrbStopED; DEBUG ((DEBUG_INFO, "XhcPeiStopEndpoint: Slot = 0x%x, Dci = 0x%x\n", SlotId, Dci)); @@ -2378,13 +2423,13 @@ XhcPeiStopEndpoint ( CmdTrbStopED.Type = TRB_TYPE_STOP_ENDPOINT; CmdTrbStopED.EDID = Dci; CmdTrbStopED.SlotId = SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbStopED, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbStopED, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiStopEndpoint: Stop Endpoint Failed, Status = %r\n", Status)); } @@ -2405,9 +2450,9 @@ XhcPeiStopEndpoint ( EFI_STATUS EFIAPI XhcPeiResetEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ) { EFI_STATUS Status; @@ -2424,13 +2469,13 @@ XhcPeiResetEndpoint ( CmdTrbResetED.Type = TRB_TYPE_RESET_ENDPOINT; CmdTrbResetED.EDID = Dci; CmdTrbResetED.SlotId = SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdTrbResetED, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdTrbResetED, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiResetEndpoint: Reset Endpoint Failed, Status = %r\n", Status)); } @@ -2453,10 +2498,10 @@ XhcPeiResetEndpoint ( EFI_STATUS EFIAPI XhcPeiSetTrDequeuePointer ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *Urb ) { EFI_STATUS Status; @@ -2470,20 +2515,20 @@ XhcPeiSetTrDequeuePointer ( // Send stop endpoint command to transit Endpoint from running to stop state // ZeroMem (&CmdSetTRDeq, sizeof (CmdSetTRDeq)); - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER)); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER)); CmdSetTRDeq.PtrLo = XHC_LOW_32BIT (PhyAddr) | Urb->Ring->RingPCS; CmdSetTRDeq.PtrHi = XHC_HIGH_32BIT (PhyAddr); CmdSetTRDeq.CycleBit = 1; CmdSetTRDeq.Type = TRB_TYPE_SET_TR_DEQUE; CmdSetTRDeq.Endpoint = Dci; CmdSetTRDeq.SlotId = SlotId; - Status = XhcPeiCmdTransfer ( - Xhc, - (TRB_TEMPLATE *) (UINTN) &CmdSetTRDeq, - XHC_GENERIC_TIMEOUT, - (TRB_TEMPLATE **) (UINTN) &EvtTrb - ); - if (EFI_ERROR(Status)) { + Status = XhcPeiCmdTransfer ( + Xhc, + (TRB_TEMPLATE *)(UINTN)&CmdSetTRDeq, + XHC_GENERIC_TIMEOUT, + (TRB_TEMPLATE **)(UINTN)&EvtTrb + ); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "XhcPeiSetTrDequeuePointer: Set TR Dequeue Pointer Failed, Status = %r\n", Status)); } @@ -2503,9 +2548,9 @@ XhcPeiSetTrDequeuePointer ( **/ EFI_STATUS XhcPeiCheckNewEvent ( - IN PEI_XHC_DEV *Xhc, - IN EVENT_RING *EvtRing, - OUT TRB_TEMPLATE **NewEvtTrb + IN PEI_XHC_DEV *Xhc, + IN EVENT_RING *EvtRing, + OUT TRB_TEMPLATE **NewEvtTrb ) { ASSERT (EvtRing != NULL); @@ -2520,7 +2565,7 @@ XhcPeiCheckNewEvent ( // // If the dequeue pointer is beyond the ring, then roll-back it to the begining of the ring. // - if ((UINTN) EvtRing->EventRingDequeue >= ((UINTN) EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { + if ((UINTN)EvtRing->EventRingDequeue >= ((UINTN)EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { EvtRing->EventRingDequeue = EvtRing->EventRingSeg0; } @@ -2538,12 +2583,12 @@ XhcPeiCheckNewEvent ( **/ EFI_STATUS XhcPeiSyncEventRing ( - IN PEI_XHC_DEV *Xhc, - IN EVENT_RING *EvtRing + IN PEI_XHC_DEV *Xhc, + IN EVENT_RING *EvtRing ) { - UINTN Index; - TRB_TEMPLATE *EvtTrb; + UINTN Index; + TRB_TEMPLATE *EvtTrb; ASSERT (EvtRing != NULL); @@ -2560,8 +2605,8 @@ XhcPeiSyncEventRing ( EvtTrb++; - if ((UINTN) EvtTrb >= ((UINTN) EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { - EvtTrb = EvtRing->EventRingSeg0; + if ((UINTN)EvtTrb >= ((UINTN)EvtRing->EventRingSeg0 + sizeof (TRB_TEMPLATE) * EvtRing->TrbNumber)) { + EvtTrb = EvtRing->EventRingSeg0; EvtRing->EventRingCCS = (EvtRing->EventRingCCS) ? 0 : 1; } } @@ -2584,11 +2629,11 @@ XhcPeiSyncEventRing ( **/ VOID XhcPeiFreeEventRing ( - IN PEI_XHC_DEV *Xhc, - IN EVENT_RING *EventRing + IN PEI_XHC_DEV *Xhc, + IN EVENT_RING *EventRing ) { - if(EventRing->EventRingSeg0 == NULL) { + if (EventRing->EventRingSeg0 == NULL) { return; } @@ -2612,30 +2657,30 @@ XhcPeiFreeEventRing ( **/ VOID XhcPeiCreateEventRing ( - IN PEI_XHC_DEV *Xhc, - OUT EVENT_RING *EventRing + IN PEI_XHC_DEV *Xhc, + OUT EVENT_RING *EventRing ) { - VOID *Buf; - EVENT_RING_SEG_TABLE_ENTRY *ERSTBase; - UINTN Size; - EFI_PHYSICAL_ADDRESS ERSTPhy; - EFI_PHYSICAL_ADDRESS DequeuePhy; + VOID *Buf; + EVENT_RING_SEG_TABLE_ENTRY *ERSTBase; + UINTN Size; + EFI_PHYSICAL_ADDRESS ERSTPhy; + EFI_PHYSICAL_ADDRESS DequeuePhy; ASSERT (EventRing != NULL); Size = sizeof (TRB_TEMPLATE) * EVENT_RING_TRB_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size); - EventRing->EventRingSeg0 = Buf; - EventRing->TrbNumber = EVENT_RING_TRB_NUMBER; - EventRing->EventRingDequeue = (TRB_TEMPLATE *) EventRing->EventRingSeg0; - EventRing->EventRingEnqueue = (TRB_TEMPLATE *) EventRing->EventRingSeg0; + EventRing->EventRingSeg0 = Buf; + EventRing->TrbNumber = EVENT_RING_TRB_NUMBER; + EventRing->EventRingDequeue = (TRB_TEMPLATE *)EventRing->EventRingSeg0; + EventRing->EventRingEnqueue = (TRB_TEMPLATE *)EventRing->EventRingSeg0; // // Software maintains an Event Ring Consumer Cycle State (CCS) bit, initializing it to '1' @@ -2644,12 +2689,12 @@ XhcPeiCreateEventRing ( EventRing->EventRingCCS = 1; Size = sizeof (EVENT_RING_SEG_TABLE_ENTRY) * ERST_NUMBER; - Buf = UsbHcAllocateMem (Xhc->MemPool, Size); + Buf = UsbHcAllocateMem (Xhc->MemPool, Size); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, Size); - ERSTBase = (EVENT_RING_SEG_TABLE_ENTRY *) Buf; + ERSTBase = (EVENT_RING_SEG_TABLE_ENTRY *)Buf; EventRing->ERSTBase = ERSTBase; ERSTBase->PtrLo = XHC_LOW_32BIT (DequeuePhy); ERSTBase->PtrHi = XHC_HIGH_32BIT (DequeuePhy); @@ -2674,12 +2719,12 @@ XhcPeiCreateEventRing ( XhcPeiWriteRuntimeReg ( Xhc, XHC_ERDP_OFFSET, - XHC_LOW_32BIT ((UINT64) (UINTN) DequeuePhy) + XHC_LOW_32BIT ((UINT64)(UINTN)DequeuePhy) ); XhcPeiWriteRuntimeReg ( Xhc, XHC_ERDP_OFFSET + 4, - XHC_HIGH_32BIT ((UINT64) (UINTN) DequeuePhy) + XHC_HIGH_32BIT ((UINT64)(UINTN)DequeuePhy) ); // // Program the Interrupter Event Ring Segment Table Base Address (ERSTBA) register (5.5.2.3.2) @@ -2690,12 +2735,12 @@ XhcPeiCreateEventRing ( XhcPeiWriteRuntimeReg ( Xhc, XHC_ERSTBA_OFFSET, - XHC_LOW_32BIT ((UINT64) (UINTN) ERSTPhy) + XHC_LOW_32BIT ((UINT64)(UINTN)ERSTPhy) ); XhcPeiWriteRuntimeReg ( Xhc, XHC_ERSTBA_OFFSET + 4, - XHC_HIGH_32BIT ((UINT64) (UINTN) ERSTPhy) + XHC_HIGH_32BIT ((UINT64)(UINTN)ERSTPhy) ); // // Need set IMAN IE bit to enable the ring interrupt @@ -2718,8 +2763,8 @@ XhcPeiSyncTrsRing ( IN TRANSFER_RING *TrsRing ) { - UINTN Index; - TRB_TEMPLATE *TrsTrb; + UINTN Index; + TRB_TEMPLATE *TrsTrb; ASSERT (TrsRing != NULL); // @@ -2732,18 +2777,19 @@ XhcPeiSyncTrsRing ( if (TrsTrb->CycleBit != (TrsRing->RingPCS & BIT0)) { break; } + TrsTrb++; - if ((UINT8) TrsTrb->Type == TRB_TYPE_LINK) { - ASSERT (((LINK_TRB *) TrsTrb)->TC != 0); + if ((UINT8)TrsTrb->Type == TRB_TYPE_LINK) { + ASSERT (((LINK_TRB *)TrsTrb)->TC != 0); // // set cycle bit in Link TRB as normal // - ((LINK_TRB*)TrsTrb)->CycleBit = TrsRing->RingPCS & BIT0; + ((LINK_TRB *)TrsTrb)->CycleBit = TrsRing->RingPCS & BIT0; // // Toggle PCS maintained by software // TrsRing->RingPCS = (TrsRing->RingPCS & BIT0) ? 0 : 1; - TrsTrb = (TRB_TEMPLATE *) TrsRing->RingSeg0; // Use host address + TrsTrb = (TRB_TEMPLATE *)TrsRing->RingSeg0; // Use host address } } @@ -2776,9 +2822,9 @@ XhcPeiSyncTrsRing ( **/ VOID XhcPeiCreateTransferRing ( - IN PEI_XHC_DEV *Xhc, - IN UINTN TrbNum, - OUT TRANSFER_RING *TransferRing + IN PEI_XHC_DEV *Xhc, + IN UINTN TrbNum, + OUT TRANSFER_RING *TransferRing ) { VOID *Buf; @@ -2787,28 +2833,28 @@ XhcPeiCreateTransferRing ( Buf = UsbHcAllocateMem (Xhc->MemPool, sizeof (TRB_TEMPLATE) * TrbNum); ASSERT (Buf != NULL); - ASSERT (((UINTN) Buf & 0x3F) == 0); + ASSERT (((UINTN)Buf & 0x3F) == 0); ZeroMem (Buf, sizeof (TRB_TEMPLATE) * TrbNum); - TransferRing->RingSeg0 = Buf; - TransferRing->TrbNumber = TrbNum; - TransferRing->RingEnqueue = (TRB_TEMPLATE *) TransferRing->RingSeg0; - TransferRing->RingDequeue = (TRB_TEMPLATE *) TransferRing->RingSeg0; - TransferRing->RingPCS = 1; + TransferRing->RingSeg0 = Buf; + TransferRing->TrbNumber = TrbNum; + TransferRing->RingEnqueue = (TRB_TEMPLATE *)TransferRing->RingSeg0; + TransferRing->RingDequeue = (TRB_TEMPLATE *)TransferRing->RingSeg0; + TransferRing->RingPCS = 1; // // 4.9.2 Transfer Ring Management // To form a ring (or circular queue) a Link TRB may be inserted at the end of a ring to // point to the first TRB in the ring. // - EndTrb = (LINK_TRB *) ((UINTN) Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1)); + EndTrb = (LINK_TRB *)((UINTN)Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1)); EndTrb->Type = TRB_TYPE_LINK; - PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum); + PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum); EndTrb->PtrLo = XHC_LOW_32BIT (PhyAddr); EndTrb->PtrHi = XHC_HIGH_32BIT (PhyAddr); // // Toggle Cycle (TC). When set to '1', the xHC shall toggle its interpretation of the Cycle bit. // - EndTrb->TC = 1; + EndTrb->TC = 1; // // Set Cycle bit as other TRB PCS init value // @@ -2823,7 +2869,7 @@ XhcPeiCreateTransferRing ( **/ VOID XhcPeiInitSched ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ) { VOID *Dcbaa; @@ -2859,7 +2905,7 @@ XhcPeiInitSched ( // The Device Context Base Address Array shall contain MaxSlotsEn + 1 entries. // Software shall set Device Context Base Address Array entries for unallocated Device Slots to '0'. // - Size = (Xhc->MaxSlotsEn + 1) * sizeof (UINT64); + Size = (Xhc->MaxSlotsEn + 1) * sizeof (UINT64); Dcbaa = UsbHcAllocateMem (Xhc->MemPool, Size); ASSERT (Dcbaa != NULL); @@ -2887,13 +2933,13 @@ XhcPeiInitSched ( Xhc->ScratchEntry = ScratchEntry; ScratchPhy = 0; - Status = UsbHcAllocateAlignedPages ( - EFI_SIZE_TO_PAGES (MaxScratchpadBufs * sizeof (UINT64)), - Xhc->PageSize, - (VOID **) &ScratchBuf, - &ScratchPhy, - &Xhc->ScratchMap - ); + Status = UsbHcAllocateAlignedPages ( + EFI_SIZE_TO_PAGES (MaxScratchpadBufs * sizeof (UINT64)), + Xhc->PageSize, + (VOID **)&ScratchBuf, + &ScratchPhy, + &Xhc->ScratchMap + ); ASSERT_EFI_ERROR (Status); ZeroMem (ScratchBuf, MaxScratchpadBufs * sizeof (UINT64)); @@ -2904,32 +2950,33 @@ XhcPeiInitSched ( // for (Index = 0; Index < MaxScratchpadBufs; Index++) { ScratchEntryPhy = 0; - Status = UsbHcAllocateAlignedPages ( - EFI_SIZE_TO_PAGES (Xhc->PageSize), - Xhc->PageSize, - (VOID **) &ScratchEntry[Index], - &ScratchEntryPhy, - (VOID **) &ScratchEntryMap[Index] - ); + Status = UsbHcAllocateAlignedPages ( + EFI_SIZE_TO_PAGES (Xhc->PageSize), + Xhc->PageSize, + (VOID **)&ScratchEntry[Index], + &ScratchEntryPhy, + (VOID **)&ScratchEntryMap[Index] + ); ASSERT_EFI_ERROR (Status); - ZeroMem ((VOID *) (UINTN) ScratchEntry[Index], Xhc->PageSize); + ZeroMem ((VOID *)(UINTN)ScratchEntry[Index], Xhc->PageSize); // // Fill with the PCI device address // *ScratchBuf++ = ScratchEntryPhy; } + // // The Scratchpad Buffer Array contains pointers to the Scratchpad Buffers. Entry 0 of the // Device Context Base Address Array points to the Scratchpad Buffer Array. // - *(UINT64 *) Dcbaa = (UINT64) (UINTN) ScratchPhy; + *(UINT64 *)Dcbaa = (UINT64)(UINTN)ScratchPhy; } // // Program the Device Context Base Address Array Pointer (DCBAAP) register (5.4.6) with // a 64-bit address pointing to where the Device Context Base Address Array is located. // - Xhc->DCBAA = (UINT64 *) (UINTN) Dcbaa; + Xhc->DCBAA = (UINT64 *)(UINTN)Dcbaa; // // Some 3rd party XHCI external cards don't support single 64-bytes width register access, // So divide it to two 32-bytes width register access. @@ -2989,11 +3036,11 @@ XhcPeiInitSched ( **/ VOID XhcPeiFreeSched ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ) { - UINT32 Index; - UINT64 *ScratchEntry; + UINT32 Index; + UINT64 *ScratchEntry; if (Xhc->ScratchBuf != NULL) { ScratchEntry = Xhc->ScratchEntry; @@ -3001,8 +3048,9 @@ XhcPeiFreeSched ( // // Free Scratchpad Buffers // - UsbHcFreeAlignedPages ((VOID*) (UINTN) ScratchEntry[Index], EFI_SIZE_TO_PAGES (Xhc->PageSize), (VOID *) Xhc->ScratchEntryMap[Index]); + UsbHcFreeAlignedPages ((VOID *)(UINTN)ScratchEntry[Index], EFI_SIZE_TO_PAGES (Xhc->PageSize), (VOID *)Xhc->ScratchEntryMap[Index]); } + // // Free Scratchpad Buffer Array // @@ -3016,7 +3064,7 @@ XhcPeiFreeSched ( Xhc->CmdRing.RingSeg0 = NULL; } - XhcPeiFreeEventRing (Xhc,&Xhc->EventRing); + XhcPeiFreeEventRing (Xhc, &Xhc->EventRing); if (Xhc->DCBAA != NULL) { UsbHcFreeMem (Xhc->MemPool, Xhc->DCBAA, (Xhc->MaxSlotsEn + 1) * sizeof (UINT64)); diff --git a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.h b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.h index badc57a51b..bbe6232797 100644 --- a/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.h +++ b/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.h @@ -13,62 +13,62 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Transfer types, used in URB to identify the transfer type // -#define XHC_CTRL_TRANSFER 0x01 -#define XHC_BULK_TRANSFER 0x02 +#define XHC_CTRL_TRANSFER 0x01 +#define XHC_BULK_TRANSFER 0x02 // // 6.4.6 TRB Types // -#define TRB_TYPE_NORMAL 1 -#define TRB_TYPE_SETUP_STAGE 2 -#define TRB_TYPE_DATA_STAGE 3 -#define TRB_TYPE_STATUS_STAGE 4 -#define TRB_TYPE_ISOCH 5 -#define TRB_TYPE_LINK 6 -#define TRB_TYPE_EVENT_DATA 7 -#define TRB_TYPE_NO_OP 8 -#define TRB_TYPE_EN_SLOT 9 -#define TRB_TYPE_DIS_SLOT 10 -#define TRB_TYPE_ADDRESS_DEV 11 -#define TRB_TYPE_CON_ENDPOINT 12 -#define TRB_TYPE_EVALU_CONTXT 13 -#define TRB_TYPE_RESET_ENDPOINT 14 -#define TRB_TYPE_STOP_ENDPOINT 15 -#define TRB_TYPE_SET_TR_DEQUE 16 -#define TRB_TYPE_RESET_DEV 17 -#define TRB_TYPE_GET_PORT_BANW 21 -#define TRB_TYPE_FORCE_HEADER 22 -#define TRB_TYPE_NO_OP_COMMAND 23 -#define TRB_TYPE_TRANS_EVENT 32 -#define TRB_TYPE_COMMAND_COMPLT_EVENT 33 -#define TRB_TYPE_PORT_STATUS_CHANGE_EVENT 34 -#define TRB_TYPE_HOST_CONTROLLER_EVENT 37 -#define TRB_TYPE_DEVICE_NOTIFI_EVENT 38 -#define TRB_TYPE_MFINDEX_WRAP_EVENT 39 +#define TRB_TYPE_NORMAL 1 +#define TRB_TYPE_SETUP_STAGE 2 +#define TRB_TYPE_DATA_STAGE 3 +#define TRB_TYPE_STATUS_STAGE 4 +#define TRB_TYPE_ISOCH 5 +#define TRB_TYPE_LINK 6 +#define TRB_TYPE_EVENT_DATA 7 +#define TRB_TYPE_NO_OP 8 +#define TRB_TYPE_EN_SLOT 9 +#define TRB_TYPE_DIS_SLOT 10 +#define TRB_TYPE_ADDRESS_DEV 11 +#define TRB_TYPE_CON_ENDPOINT 12 +#define TRB_TYPE_EVALU_CONTXT 13 +#define TRB_TYPE_RESET_ENDPOINT 14 +#define TRB_TYPE_STOP_ENDPOINT 15 +#define TRB_TYPE_SET_TR_DEQUE 16 +#define TRB_TYPE_RESET_DEV 17 +#define TRB_TYPE_GET_PORT_BANW 21 +#define TRB_TYPE_FORCE_HEADER 22 +#define TRB_TYPE_NO_OP_COMMAND 23 +#define TRB_TYPE_TRANS_EVENT 32 +#define TRB_TYPE_COMMAND_COMPLT_EVENT 33 +#define TRB_TYPE_PORT_STATUS_CHANGE_EVENT 34 +#define TRB_TYPE_HOST_CONTROLLER_EVENT 37 +#define TRB_TYPE_DEVICE_NOTIFI_EVENT 38 +#define TRB_TYPE_MFINDEX_WRAP_EVENT 39 // // Endpoint Type (EP Type). // -#define ED_NOT_VALID 0 -#define ED_ISOCH_OUT 1 -#define ED_BULK_OUT 2 -#define ED_INTERRUPT_OUT 3 -#define ED_CONTROL_BIDIR 4 -#define ED_ISOCH_IN 5 -#define ED_BULK_IN 6 -#define ED_INTERRUPT_IN 7 +#define ED_NOT_VALID 0 +#define ED_ISOCH_OUT 1 +#define ED_BULK_OUT 2 +#define ED_INTERRUPT_OUT 3 +#define ED_CONTROL_BIDIR 4 +#define ED_ISOCH_IN 5 +#define ED_BULK_IN 6 +#define ED_INTERRUPT_IN 7 // // 6.4.5 TRB Completion Codes // -#define TRB_COMPLETION_INVALID 0 -#define TRB_COMPLETION_SUCCESS 1 -#define TRB_COMPLETION_DATA_BUFFER_ERROR 2 -#define TRB_COMPLETION_BABBLE_ERROR 3 -#define TRB_COMPLETION_USB_TRANSACTION_ERROR 4 -#define TRB_COMPLETION_TRB_ERROR 5 -#define TRB_COMPLETION_STALL_ERROR 6 -#define TRB_COMPLETION_SHORT_PACKET 13 +#define TRB_COMPLETION_INVALID 0 +#define TRB_COMPLETION_SUCCESS 1 +#define TRB_COMPLETION_DATA_BUFFER_ERROR 2 +#define TRB_COMPLETION_BABBLE_ERROR 3 +#define TRB_COMPLETION_USB_TRANSACTION_ERROR 4 +#define TRB_COMPLETION_TRB_ERROR 5 +#define TRB_COMPLETION_STALL_ERROR 6 +#define TRB_COMPLETION_SHORT_PACKET 13 // // The topology string used to present usb device location @@ -77,23 +77,23 @@ typedef struct _USB_DEV_TOPOLOGY { // // The tier concatenation of down stream port. // - UINT32 RouteString:20; + UINT32 RouteString : 20; // // The root port number of the chain. // - UINT32 RootPortNum:8; + UINT32 RootPortNum : 8; // // The Tier the device reside. // - UINT32 TierNum:4; + UINT32 TierNum : 4; } USB_DEV_TOPOLOGY; // // USB Device's RouteChart // typedef union _USB_DEV_ROUTE { - UINT32 Dword; - USB_DEV_TOPOLOGY Route; + UINT32 Dword; + USB_DEV_TOPOLOGY Route; } USB_DEV_ROUTE; // @@ -118,74 +118,74 @@ typedef struct _USB_ENDPOINT { // TRB Template // typedef struct _TRB_TEMPLATE { - UINT32 Parameter1; + UINT32 Parameter1; - UINT32 Parameter2; + UINT32 Parameter2; - UINT32 Status; + UINT32 Status; - UINT32 CycleBit:1; - UINT32 RsvdZ1:9; - UINT32 Type:6; - UINT32 Control:16; + UINT32 CycleBit : 1; + UINT32 RsvdZ1 : 9; + UINT32 Type : 6; + UINT32 Control : 16; } TRB_TEMPLATE; typedef struct _TRANSFER_RING { - VOID *RingSeg0; - UINTN TrbNumber; - TRB_TEMPLATE *RingEnqueue; - TRB_TEMPLATE *RingDequeue; - UINT32 RingPCS; + VOID *RingSeg0; + UINTN TrbNumber; + TRB_TEMPLATE *RingEnqueue; + TRB_TEMPLATE *RingDequeue; + UINT32 RingPCS; } TRANSFER_RING; typedef struct _EVENT_RING { - VOID *ERSTBase; - VOID *EventRingSeg0; - UINTN TrbNumber; - TRB_TEMPLATE *EventRingEnqueue; - TRB_TEMPLATE *EventRingDequeue; - UINT32 EventRingCCS; + VOID *ERSTBase; + VOID *EventRingSeg0; + UINTN TrbNumber; + TRB_TEMPLATE *EventRingEnqueue; + TRB_TEMPLATE *EventRingDequeue; + UINT32 EventRingCCS; } EVENT_RING; -#define XHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') +#define XHC_URB_SIG SIGNATURE_32 ('U', 'S', 'B', 'R') // // URB (Usb Request Block) contains information for all kinds of // usb requests. // typedef struct _URB { - UINT32 Signature; + UINT32 Signature; // // Usb Device URB related information // - USB_ENDPOINT Ep; - EFI_USB_DEVICE_REQUEST *Request; - VOID *Data; - UINTN DataLen; - VOID *DataPhy; - VOID *DataMap; - EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; - VOID *Context; + USB_ENDPOINT Ep; + EFI_USB_DEVICE_REQUEST *Request; + VOID *Data; + UINTN DataLen; + VOID *DataPhy; + VOID *DataMap; + EFI_ASYNC_USB_TRANSFER_CALLBACK Callback; + VOID *Context; // // Execute result // - UINT32 Result; + UINT32 Result; // // completed data length // - UINTN Completed; + UINTN Completed; // // Command/Tranfer Ring info // - TRANSFER_RING *Ring; - TRB_TEMPLATE *TrbStart; - TRB_TEMPLATE *TrbEnd; - UINTN TrbNum; - BOOLEAN StartDone; - BOOLEAN EndDone; - BOOLEAN Finished; - - TRB_TEMPLATE *EvtTrb; + TRANSFER_RING *Ring; + TRB_TEMPLATE *TrbStart; + TRB_TEMPLATE *TrbEnd; + UINTN TrbNum; + BOOLEAN StartDone; + BOOLEAN EndDone; + BOOLEAN Finished; + + TRB_TEMPLATE *EvtTrb; } URB; // @@ -196,11 +196,11 @@ typedef struct _URB { // is defined by the Event Ring Segment Table Base Size Register (5.5.2.3.1). // typedef struct _EVENT_RING_SEG_TABLE_ENTRY { - UINT32 PtrLo; - UINT32 PtrHi; - UINT32 RingTrbSize:16; - UINT32 RsvdZ1:16; - UINT32 RsvdZ2; + UINT32 PtrLo; + UINT32 PtrHi; + UINT32 RingTrbSize : 16; + UINT32 RsvdZ1 : 16; + UINT32 RsvdZ2; } EVENT_RING_SEG_TABLE_ENTRY; // @@ -210,25 +210,25 @@ typedef struct _EVENT_RING_SEG_TABLE_ENTRY { // Rings, and to define the Data stage information for Control Transfer Rings. // typedef struct _TRANSFER_TRB_NORMAL { - UINT32 TRBPtrLo; - - UINT32 TRBPtrHi; - - UINT32 Length:17; - UINT32 TDSize:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 ISP:1; - UINT32 NS:1; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ1:2; - UINT32 BEI:1; - UINT32 Type:6; - UINT32 RsvdZ2:16; + UINT32 TRBPtrLo; + + UINT32 TRBPtrHi; + + UINT32 Length : 17; + UINT32 TDSize : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 ISP : 1; + UINT32 NS : 1; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ1 : 2; + UINT32 BEI : 1; + UINT32 Type : 6; + UINT32 RsvdZ2 : 16; } TRANSFER_TRB_NORMAL; // @@ -236,25 +236,25 @@ typedef struct _TRANSFER_TRB_NORMAL { // A Setup Stage TRB is created by system software to initiate a USB Setup packet on a control endpoint. // typedef struct _TRANSFER_TRB_CONTROL_SETUP { - UINT32 bmRequestType:8; - UINT32 bRequest:8; - UINT32 wValue:16; - - UINT32 wIndex:16; - UINT32 wLength:16; - - UINT32 Length:17; - UINT32 RsvdZ1:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 RsvdZ2:4; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ3:3; - UINT32 Type:6; - UINT32 TRT:2; - UINT32 RsvdZ4:14; + UINT32 bmRequestType : 8; + UINT32 bRequest : 8; + UINT32 wValue : 16; + + UINT32 wIndex : 16; + UINT32 wLength : 16; + + UINT32 Length : 17; + UINT32 RsvdZ1 : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 4; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ3 : 3; + UINT32 Type : 6; + UINT32 TRT : 2; + UINT32 RsvdZ4 : 14; } TRANSFER_TRB_CONTROL_SETUP; // @@ -262,25 +262,25 @@ typedef struct _TRANSFER_TRB_CONTROL_SETUP { // A Data Stage TRB is used generate the Data stage transaction of a USB Control transfer. // typedef struct _TRANSFER_TRB_CONTROL_DATA { - UINT32 TRBPtrLo; - - UINT32 TRBPtrHi; - - UINT32 Length:17; - UINT32 TDSize:5; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 ISP:1; - UINT32 NS:1; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 IDT:1; - UINT32 RsvdZ1:3; - UINT32 Type:6; - UINT32 DIR:1; - UINT32 RsvdZ2:15; + UINT32 TRBPtrLo; + + UINT32 TRBPtrHi; + + UINT32 Length : 17; + UINT32 TDSize : 5; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 ISP : 1; + UINT32 NS : 1; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 IDT : 1; + UINT32 RsvdZ1 : 3; + UINT32 Type : 6; + UINT32 DIR : 1; + UINT32 RsvdZ2 : 15; } TRANSFER_TRB_CONTROL_DATA; // @@ -288,21 +288,21 @@ typedef struct _TRANSFER_TRB_CONTROL_DATA { // A Data Stage TRB is used generate the Data stage transaction of a USB Control transfer. // typedef struct _TRANSFER_TRB_CONTROL_STATUS { - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 RsvdZ3:22; - UINT32 IntTarget:10; - - UINT32 CycleBit:1; - UINT32 ENT:1; - UINT32 RsvdZ4:2; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 RsvdZ5:4; - UINT32 Type:6; - UINT32 DIR:1; - UINT32 RsvdZ6:15; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 RsvdZ3 : 22; + UINT32 IntTarget : 10; + + UINT32 CycleBit : 1; + UINT32 ENT : 1; + UINT32 RsvdZ4 : 2; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 RsvdZ5 : 4; + UINT32 Type : 6; + UINT32 DIR : 1; + UINT32 RsvdZ6 : 15; } TRANSFER_TRB_CONTROL_STATUS; // @@ -311,21 +311,21 @@ typedef struct _TRANSFER_TRB_CONTROL_STATUS { // for more information on the use and operation of Transfer Events. // typedef struct _EVT_TRB_TRANSFER { - UINT32 TRBPtrLo; + UINT32 TRBPtrLo; - UINT32 TRBPtrHi; + UINT32 TRBPtrHi; - UINT32 Length:24; - UINT32 Completecode:8; + UINT32 Length : 24; + UINT32 Completecode : 8; - UINT32 CycleBit:1; - UINT32 RsvdZ1:1; - UINT32 ED:1; - UINT32 RsvdZ2:7; - UINT32 Type:6; - UINT32 EndpointId:5; - UINT32 RsvdZ3:3; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ1 : 1; + UINT32 ED : 1; + UINT32 RsvdZ2 : 7; + UINT32 Type : 6; + UINT32 EndpointId : 5; + UINT32 RsvdZ3 : 3; + UINT32 SlotId : 8; } EVT_TRB_TRANSFER; // @@ -334,26 +334,26 @@ typedef struct _EVT_TRB_TRANSFER { // Command Ring. Refer to section 4.11.4 for more information on the use of Command Completion Events. // typedef struct _EVT_TRB_COMMAND_COMPLETION { - UINT32 TRBPtrLo; + UINT32 TRBPtrLo; - UINT32 TRBPtrHi; + UINT32 TRBPtrHi; - UINT32 RsvdZ2:24; - UINT32 Completecode:8; + UINT32 RsvdZ2 : 24; + UINT32 Completecode : 8; - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 VFID:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 VFID : 8; + UINT32 SlotId : 8; } EVT_TRB_COMMAND_COMPLETION; typedef union _TRB { - TRB_TEMPLATE TrbTemplate; - TRANSFER_TRB_NORMAL TrbNormal; - TRANSFER_TRB_CONTROL_SETUP TrbCtrSetup; - TRANSFER_TRB_CONTROL_DATA TrbCtrData; - TRANSFER_TRB_CONTROL_STATUS TrbCtrStatus; + TRB_TEMPLATE TrbTemplate; + TRANSFER_TRB_NORMAL TrbNormal; + TRANSFER_TRB_CONTROL_SETUP TrbCtrSetup; + TRANSFER_TRB_CONTROL_DATA TrbCtrData; + TRANSFER_TRB_CONTROL_STATUS TrbCtrStatus; } TRB; // @@ -362,14 +362,14 @@ typedef union _TRB { // mechanisms offered by the xHCI. // typedef struct _CMD_TRB_NO_OP { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } CMD_TRB_NO_OP; // @@ -378,14 +378,14 @@ typedef struct _CMD_TRB_NO_OP { // selected slot to the host in a Command Completion Event. // typedef struct _CMD_TRB_ENABLE_SLOT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } CMD_TRB_ENABLE_SLOT; // @@ -394,15 +394,15 @@ typedef struct _CMD_TRB_ENABLE_SLOT { // internal xHC resources assigned to the slot. // typedef struct _CMD_TRB_DISABLE_SLOT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 RsvdZ4:8; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 RsvdZ4 : 8; + UINT32 SlotId : 8; } CMD_TRB_DISABLE_SLOT; // @@ -412,18 +412,18 @@ typedef struct _CMD_TRB_DISABLE_SLOT { // issue a SET_ADDRESS request to the USB device. // typedef struct _CMD_TRB_ADDRESS_DEVICE { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:8; - UINT32 BSR:1; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 8; + UINT32 BSR : 1; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_ADDRESS_DEVICE; // @@ -432,18 +432,18 @@ typedef struct _CMD_TRB_ADDRESS_DEVICE { // endpoints selected by the command. // typedef struct _CMD_TRB_CONFIG_ENDPOINT { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:8; - UINT32 DC:1; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 8; + UINT32 DC : 1; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_CONFIG_ENDPOINT; // @@ -453,17 +453,17 @@ typedef struct _CMD_TRB_CONFIG_ENDPOINT { // shall evaluate any changes // typedef struct _CMD_TRB_EVALUATE_CONTEXT { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1; + UINT32 RsvdZ1; - UINT32 CycleBit:1; - UINT32 RsvdZ2:9; - UINT32 Type:6; - UINT32 RsvdZ3:8; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 9; + UINT32 Type : 6; + UINT32 RsvdZ3 : 8; + UINT32 SlotId : 8; } CMD_TRB_EVALUATE_CONTEXT; // @@ -471,17 +471,17 @@ typedef struct _CMD_TRB_EVALUATE_CONTEXT { // The Reset Endpoint Command TRB is used by system software to reset a specified Transfer Ring // typedef struct _CMD_TRB_RESET_ENDPOINT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:8; - UINT32 TSP:1; - UINT32 Type:6; - UINT32 EDID:5; - UINT32 RsvdZ4:3; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 8; + UINT32 TSP : 1; + UINT32 Type : 6; + UINT32 EDID : 5; + UINT32 RsvdZ4 : 3; + UINT32 SlotId : 8; } CMD_TRB_RESET_ENDPOINT; // @@ -490,17 +490,17 @@ typedef struct _CMD_TRB_RESET_ENDPOINT { // Transfer Ring and temporarily take ownership of TDs that had previously been passed to the xHC. // typedef struct _CMD_TRB_STOP_ENDPOINT { - UINT32 RsvdZ0; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - - UINT32 CycleBit:1; - UINT32 RsvdZ3:9; - UINT32 Type:6; - UINT32 EDID:5; - UINT32 RsvdZ4:2; - UINT32 SP:1; - UINT32 SlotId:8; + UINT32 RsvdZ0; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + + UINT32 CycleBit : 1; + UINT32 RsvdZ3 : 9; + UINT32 Type : 6; + UINT32 EDID : 5; + UINT32 RsvdZ4 : 2; + UINT32 SP : 1; + UINT32 SlotId : 8; } CMD_TRB_STOP_ENDPOINT; // @@ -509,19 +509,19 @@ typedef struct _CMD_TRB_STOP_ENDPOINT { // Pointer and DCS fields of an Endpoint or Stream Context. // typedef struct _CMD_SET_TR_DEQ_POINTER { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1:16; - UINT32 StreamID:16; + UINT32 RsvdZ1 : 16; + UINT32 StreamID : 16; - UINT32 CycleBit:1; - UINT32 RsvdZ2:9; - UINT32 Type:6; - UINT32 Endpoint:5; - UINT32 RsvdZ3:3; - UINT32 SlotId:8; + UINT32 CycleBit : 1; + UINT32 RsvdZ2 : 9; + UINT32 Type : 6; + UINT32 Endpoint : 5; + UINT32 RsvdZ3 : 3; + UINT32 SlotId : 8; } CMD_SET_TR_DEQ_POINTER; // @@ -529,226 +529,222 @@ typedef struct _CMD_SET_TR_DEQ_POINTER { // A Link TRB provides support for non-contiguous TRB Rings. // typedef struct _LINK_TRB { - UINT32 PtrLo; + UINT32 PtrLo; - UINT32 PtrHi; + UINT32 PtrHi; - UINT32 RsvdZ1:22; - UINT32 InterTarget:10; + UINT32 RsvdZ1 : 22; + UINT32 InterTarget : 10; - UINT32 CycleBit:1; - UINT32 TC:1; - UINT32 RsvdZ2:2; - UINT32 CH:1; - UINT32 IOC:1; - UINT32 RsvdZ3:4; - UINT32 Type:6; - UINT32 RsvdZ4:16; + UINT32 CycleBit : 1; + UINT32 TC : 1; + UINT32 RsvdZ2 : 2; + UINT32 CH : 1; + UINT32 IOC : 1; + UINT32 RsvdZ3 : 4; + UINT32 Type : 6; + UINT32 RsvdZ4 : 16; } LINK_TRB; // // 6.2.2 Slot Context // typedef struct _SLOT_CONTEXT { - UINT32 RouteString:20; - UINT32 Speed:4; - UINT32 RsvdZ1:1; - UINT32 MTT:1; - UINT32 Hub:1; - UINT32 ContextEntries:5; - - UINT32 MaxExitLatency:16; - UINT32 RootHubPortNum:8; - UINT32 PortNum:8; - - UINT32 TTHubSlotId:8; - UINT32 TTPortNum:8; - UINT32 TTT:2; - UINT32 RsvdZ2:4; - UINT32 InterTarget:10; - - UINT32 DeviceAddress:8; - UINT32 RsvdZ3:19; - UINT32 SlotState:5; - - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; + UINT32 RouteString : 20; + UINT32 Speed : 4; + UINT32 RsvdZ1 : 1; + UINT32 MTT : 1; + UINT32 Hub : 1; + UINT32 ContextEntries : 5; + + UINT32 MaxExitLatency : 16; + UINT32 RootHubPortNum : 8; + UINT32 PortNum : 8; + + UINT32 TTHubSlotId : 8; + UINT32 TTPortNum : 8; + UINT32 TTT : 2; + UINT32 RsvdZ2 : 4; + UINT32 InterTarget : 10; + + UINT32 DeviceAddress : 8; + UINT32 RsvdZ3 : 19; + UINT32 SlotState : 5; + + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; } SLOT_CONTEXT; typedef struct _SLOT_CONTEXT_64 { - UINT32 RouteString:20; - UINT32 Speed:4; - UINT32 RsvdZ1:1; - UINT32 MTT:1; - UINT32 Hub:1; - UINT32 ContextEntries:5; - - UINT32 MaxExitLatency:16; - UINT32 RootHubPortNum:8; - UINT32 PortNum:8; - - UINT32 TTHubSlotId:8; - UINT32 TTPortNum:8; - UINT32 TTT:2; - UINT32 RsvdZ2:4; - UINT32 InterTarget:10; - - UINT32 DeviceAddress:8; - UINT32 RsvdZ3:19; - UINT32 SlotState:5; - - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; - UINT32 RsvdZ15; - + UINT32 RouteString : 20; + UINT32 Speed : 4; + UINT32 RsvdZ1 : 1; + UINT32 MTT : 1; + UINT32 Hub : 1; + UINT32 ContextEntries : 5; + + UINT32 MaxExitLatency : 16; + UINT32 RootHubPortNum : 8; + UINT32 PortNum : 8; + + UINT32 TTHubSlotId : 8; + UINT32 TTPortNum : 8; + UINT32 TTT : 2; + UINT32 RsvdZ2 : 4; + UINT32 InterTarget : 10; + + UINT32 DeviceAddress : 8; + UINT32 RsvdZ3 : 19; + UINT32 SlotState : 5; + + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; + UINT32 RsvdZ15; } SLOT_CONTEXT_64; - // // 6.2.3 Endpoint Context // typedef struct _ENDPOINT_CONTEXT { - UINT32 EPState:3; - UINT32 RsvdZ1:5; - UINT32 Mult:2; - UINT32 MaxPStreams:5; - UINT32 LSA:1; - UINT32 Interval:8; - UINT32 RsvdZ2:8; - - UINT32 RsvdZ3:1; - UINT32 CErr:2; - UINT32 EPType:3; - UINT32 RsvdZ4:1; - UINT32 HID:1; - UINT32 MaxBurstSize:8; - UINT32 MaxPacketSize:16; - - UINT32 PtrLo; - - UINT32 PtrHi; - - UINT32 AverageTRBLength:16; - UINT32 MaxESITPayload:16; - - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; + UINT32 EPState : 3; + UINT32 RsvdZ1 : 5; + UINT32 Mult : 2; + UINT32 MaxPStreams : 5; + UINT32 LSA : 1; + UINT32 Interval : 8; + UINT32 RsvdZ2 : 8; + + UINT32 RsvdZ3 : 1; + UINT32 CErr : 2; + UINT32 EPType : 3; + UINT32 RsvdZ4 : 1; + UINT32 HID : 1; + UINT32 MaxBurstSize : 8; + UINT32 MaxPacketSize : 16; + + UINT32 PtrLo; + + UINT32 PtrHi; + + UINT32 AverageTRBLength : 16; + UINT32 MaxESITPayload : 16; + + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; } ENDPOINT_CONTEXT; typedef struct _ENDPOINT_CONTEXT_64 { - UINT32 EPState:3; - UINT32 RsvdZ1:5; - UINT32 Mult:2; - UINT32 MaxPStreams:5; - UINT32 LSA:1; - UINT32 Interval:8; - UINT32 RsvdZ2:8; - - UINT32 RsvdZ3:1; - UINT32 CErr:2; - UINT32 EPType:3; - UINT32 RsvdZ4:1; - UINT32 HID:1; - UINT32 MaxBurstSize:8; - UINT32 MaxPacketSize:16; - - UINT32 PtrLo; - - UINT32 PtrHi; - - UINT32 AverageTRBLength:16; - UINT32 MaxESITPayload:16; - - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; - UINT32 RsvdZ15; - + UINT32 EPState : 3; + UINT32 RsvdZ1 : 5; + UINT32 Mult : 2; + UINT32 MaxPStreams : 5; + UINT32 LSA : 1; + UINT32 Interval : 8; + UINT32 RsvdZ2 : 8; + + UINT32 RsvdZ3 : 1; + UINT32 CErr : 2; + UINT32 EPType : 3; + UINT32 RsvdZ4 : 1; + UINT32 HID : 1; + UINT32 MaxBurstSize : 8; + UINT32 MaxPacketSize : 16; + + UINT32 PtrLo; + + UINT32 PtrHi; + + UINT32 AverageTRBLength : 16; + UINT32 MaxESITPayload : 16; + + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; + UINT32 RsvdZ15; } ENDPOINT_CONTEXT_64; - // // 6.2.5.1 Input Control Context // typedef struct _INPUT_CONTRL_CONTEXT { - UINT32 Dword1; - UINT32 Dword2; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - UINT32 RsvdZ3; - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; + UINT32 Dword1; + UINT32 Dword2; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + UINT32 RsvdZ3; + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; } INPUT_CONTRL_CONTEXT; typedef struct _INPUT_CONTRL_CONTEXT_64 { - UINT32 Dword1; - UINT32 Dword2; - UINT32 RsvdZ1; - UINT32 RsvdZ2; - UINT32 RsvdZ3; - UINT32 RsvdZ4; - UINT32 RsvdZ5; - UINT32 RsvdZ6; - UINT32 RsvdZ7; - UINT32 RsvdZ8; - UINT32 RsvdZ9; - UINT32 RsvdZ10; - UINT32 RsvdZ11; - UINT32 RsvdZ12; - UINT32 RsvdZ13; - UINT32 RsvdZ14; + UINT32 Dword1; + UINT32 Dword2; + UINT32 RsvdZ1; + UINT32 RsvdZ2; + UINT32 RsvdZ3; + UINT32 RsvdZ4; + UINT32 RsvdZ5; + UINT32 RsvdZ6; + UINT32 RsvdZ7; + UINT32 RsvdZ8; + UINT32 RsvdZ9; + UINT32 RsvdZ10; + UINT32 RsvdZ11; + UINT32 RsvdZ12; + UINT32 RsvdZ13; + UINT32 RsvdZ14; } INPUT_CONTRL_CONTEXT_64; // // 6.2.1 Device Context // typedef struct _DEVICE_CONTEXT { - SLOT_CONTEXT Slot; - ENDPOINT_CONTEXT EP[31]; + SLOT_CONTEXT Slot; + ENDPOINT_CONTEXT EP[31]; } DEVICE_CONTEXT; typedef struct _DEVICE_CONTEXT_64 { - SLOT_CONTEXT_64 Slot; - ENDPOINT_CONTEXT_64 EP[31]; + SLOT_CONTEXT_64 Slot; + ENDPOINT_CONTEXT_64 EP[31]; } DEVICE_CONTEXT_64; // // 6.2.5 Input Context // typedef struct _INPUT_CONTEXT { - INPUT_CONTRL_CONTEXT InputControlContext; - SLOT_CONTEXT Slot; - ENDPOINT_CONTEXT EP[31]; + INPUT_CONTRL_CONTEXT InputControlContext; + SLOT_CONTEXT Slot; + ENDPOINT_CONTEXT EP[31]; } INPUT_CONTEXT; typedef struct _INPUT_CONTEXT_64 { - INPUT_CONTRL_CONTEXT_64 InputControlContext; - SLOT_CONTEXT_64 Slot; - ENDPOINT_CONTEXT_64 EP[31]; + INPUT_CONTRL_CONTEXT_64 InputControlContext; + SLOT_CONTEXT_64 Slot; + ENDPOINT_CONTEXT_64 EP[31]; } INPUT_CONTEXT_64; /** @@ -766,10 +762,10 @@ typedef struct _INPUT_CONTEXT_64 { **/ EFI_STATUS XhcPeiExecTransfer ( - IN PEI_XHC_DEV *Xhc, - IN BOOLEAN CmdTransfer, - IN URB *Urb, - IN UINTN Timeout + IN PEI_XHC_DEV *Xhc, + IN BOOLEAN CmdTransfer, + IN URB *Urb, + IN UINTN Timeout ); /** @@ -783,8 +779,8 @@ XhcPeiExecTransfer ( **/ UINT8 XhcPeiBusDevAddrToSlotId ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 BusDevAddr + IN PEI_XHC_DEV *Xhc, + IN UINT8 BusDevAddr ); /** @@ -798,8 +794,8 @@ XhcPeiBusDevAddrToSlotId ( **/ UINT8 XhcPeiRouteStringToSlotId ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE RouteString + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE RouteString ); /** @@ -813,8 +809,8 @@ XhcPeiRouteStringToSlotId ( **/ UINT8 XhcPeiEndpointToDci ( - IN UINT8 EpAddr, - IN EFI_USB_DATA_DIRECTION Direction + IN UINT8 EpAddr, + IN EFI_USB_DATA_DIRECTION Direction ); /** @@ -827,9 +823,9 @@ XhcPeiEndpointToDci ( **/ VOID XhcPeiRingDoorBell ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ); /** @@ -846,10 +842,10 @@ XhcPeiRingDoorBell ( **/ EFI_STATUS XhcPeiPollPortStatusChange ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT8 Port, - IN EFI_USB_PORT_STATUS *PortState + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT8 Port, + IN EFI_USB_PORT_STATUS *PortState ); /** @@ -866,11 +862,11 @@ XhcPeiPollPortStatusChange ( **/ EFI_STATUS XhcPeiConfigHubContext ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ); /** @@ -887,11 +883,11 @@ XhcPeiConfigHubContext ( **/ EFI_STATUS XhcPeiConfigHubContext64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 PortNum, - IN UINT8 TTT, - IN UINT8 MTT + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 PortNum, + IN UINT8 TTT, + IN UINT8 MTT ); /** @@ -907,10 +903,10 @@ XhcPeiConfigHubContext64 ( **/ EFI_STATUS XhcPeiSetConfigCmd ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ); /** @@ -926,10 +922,10 @@ XhcPeiSetConfigCmd ( **/ EFI_STATUS XhcPeiSetConfigCmd64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 DeviceSpeed, - IN USB_CONFIG_DESCRIPTOR *ConfigDesc + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 DeviceSpeed, + IN USB_CONFIG_DESCRIPTOR *ConfigDesc ); /** @@ -946,9 +942,9 @@ XhcPeiSetConfigCmd64 ( EFI_STATUS EFIAPI XhcPeiStopEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ); /** @@ -965,9 +961,9 @@ XhcPeiStopEndpoint ( EFI_STATUS EFIAPI XhcPeiResetEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci ); /** @@ -986,10 +982,10 @@ XhcPeiResetEndpoint ( EFI_STATUS EFIAPI XhcPeiSetTrDequeuePointer ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT8 Dci, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT8 Dci, + IN URB *Urb ); /** @@ -1007,11 +1003,11 @@ XhcPeiSetTrDequeuePointer ( **/ EFI_STATUS XhcPeiInitializeDeviceSlot ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ); /** @@ -1029,11 +1025,11 @@ XhcPeiInitializeDeviceSlot ( **/ EFI_STATUS XhcPeiInitializeDeviceSlot64 ( - IN PEI_XHC_DEV *Xhc, - IN USB_DEV_ROUTE ParentRouteChart, - IN UINT16 ParentPort, - IN USB_DEV_ROUTE RouteChart, - IN UINT8 DeviceSpeed + IN PEI_XHC_DEV *Xhc, + IN USB_DEV_ROUTE ParentRouteChart, + IN UINT16 ParentPort, + IN USB_DEV_ROUTE RouteChart, + IN UINT8 DeviceSpeed ); /** @@ -1048,9 +1044,9 @@ XhcPeiInitializeDeviceSlot64 ( **/ EFI_STATUS XhcPeiEvaluateContext ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ); /** @@ -1065,9 +1061,9 @@ XhcPeiEvaluateContext ( **/ EFI_STATUS XhcPeiEvaluateContext64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId, - IN UINT32 MaxPacketSize + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId, + IN UINT32 MaxPacketSize ); /** @@ -1081,8 +1077,8 @@ XhcPeiEvaluateContext64 ( **/ EFI_STATUS XhcPeiDisableSlotCmd ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId ); /** @@ -1096,8 +1092,8 @@ XhcPeiDisableSlotCmd ( **/ EFI_STATUS XhcPeiDisableSlotCmd64 ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 SlotId + IN PEI_XHC_DEV *Xhc, + IN UINT8 SlotId ); /** @@ -1116,8 +1112,8 @@ XhcPeiDisableSlotCmd64 ( **/ EFI_STATUS XhcPeiRecoverHaltedEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ); /** @@ -1135,8 +1131,8 @@ XhcPeiRecoverHaltedEndpoint ( **/ EFI_STATUS XhcPeiDequeueTrbFromEndpoint ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ); /** @@ -1157,19 +1153,19 @@ XhcPeiDequeueTrbFromEndpoint ( @return Created URB or NULL **/ -URB* +URB * XhcPeiCreateUrb ( - IN PEI_XHC_DEV *Xhc, - IN UINT8 DevAddr, - IN UINT8 EpAddr, - IN UINT8 DevSpeed, - IN UINTN MaxPacket, - IN UINTN Type, - IN EFI_USB_DEVICE_REQUEST *Request, - IN VOID *Data, - IN UINTN DataLen, - IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, - IN VOID *Context + IN PEI_XHC_DEV *Xhc, + IN UINT8 DevAddr, + IN UINT8 EpAddr, + IN UINT8 DevSpeed, + IN UINTN MaxPacket, + IN UINTN Type, + IN EFI_USB_DEVICE_REQUEST *Request, + IN VOID *Data, + IN UINTN DataLen, + IN EFI_ASYNC_USB_TRANSFER_CALLBACK Callback, + IN VOID *Context ); /** @@ -1181,8 +1177,8 @@ XhcPeiCreateUrb ( **/ VOID XhcPeiFreeUrb ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ); /** @@ -1196,8 +1192,8 @@ XhcPeiFreeUrb ( **/ EFI_STATUS XhcPeiCreateTransferTrb ( - IN PEI_XHC_DEV *Xhc, - IN URB *Urb + IN PEI_XHC_DEV *Xhc, + IN URB *Urb ); /** @@ -1225,9 +1221,9 @@ XhcPeiSyncTrsRing ( **/ VOID XhcPeiCreateTransferRing ( - IN PEI_XHC_DEV *Xhc, - IN UINTN TrbNum, - OUT TRANSFER_RING *TransferRing + IN PEI_XHC_DEV *Xhc, + IN UINTN TrbNum, + OUT TRANSFER_RING *TransferRing ); /** @@ -1243,9 +1239,9 @@ XhcPeiCreateTransferRing ( **/ EFI_STATUS XhcPeiCheckNewEvent ( - IN PEI_XHC_DEV *Xhc, - IN EVENT_RING *EvtRing, - OUT TRB_TEMPLATE **NewEvtTrb + IN PEI_XHC_DEV *Xhc, + IN EVENT_RING *EvtRing, + OUT TRB_TEMPLATE **NewEvtTrb ); /** @@ -1259,8 +1255,8 @@ XhcPeiCheckNewEvent ( **/ EFI_STATUS XhcPeiSyncEventRing ( - IN PEI_XHC_DEV *Xhc, - IN EVENT_RING *EvtRing + IN PEI_XHC_DEV *Xhc, + IN EVENT_RING *EvtRing ); /** @@ -1272,8 +1268,8 @@ XhcPeiSyncEventRing ( **/ VOID XhcPeiCreateEventRing ( - IN PEI_XHC_DEV *Xhc, - OUT EVENT_RING *EventRing + IN PEI_XHC_DEV *Xhc, + OUT EVENT_RING *EventRing ); /** @@ -1284,7 +1280,7 @@ XhcPeiCreateEventRing ( **/ VOID XhcPeiInitSched ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ); /** @@ -1295,7 +1291,7 @@ XhcPeiInitSched ( **/ VOID XhcPeiFreeSched ( - IN PEI_XHC_DEV *Xhc + IN PEI_XHC_DEV *Xhc ); #endif diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ComponentName.c b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ComponentName.c index e56eefee3a..9ff4542471 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ComponentName.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "ScsiBus.h" // @@ -21,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gScsiBusComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gScsiBusComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) ScsiBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) ScsiBusComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gScsiBusComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)ScsiBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)ScsiBusComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mScsiBusDriverNameTable[] = { - { "eng;en", (CHAR16 *) L"SCSI Bus Driver" }, - { NULL , NULL } +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mScsiBusDriverNameTable[] = { + { "eng;en", (CHAR16 *)L"SCSI Bus Driver" }, + { NULL, NULL } }; /** @@ -160,11 +158,11 @@ ScsiBusComponentNameGetDriverName ( EFI_STATUS EFIAPI ScsiBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c index 27b554ad3e..9ea69ee740 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.c @@ -7,11 +7,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "ScsiBus.h" - -EFI_DRIVER_BINDING_PROTOCOL gSCSIBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gSCSIBusDriverBinding = { SCSIBusDriverBindingSupported, SCSIBusDriverBindingStart, SCSIBusDriverBindingStop, @@ -80,8 +78,8 @@ NotifyFunction ( **/ VOID * AllocateAlignedBuffer ( - IN SCSI_IO_DEV *ScsiIoDevice, - IN UINTN BufferSize + IN SCSI_IO_DEV *ScsiIoDevice, + IN UINTN BufferSize ) { return AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), ScsiIoDevice->ScsiIo.IoAlign); @@ -99,8 +97,8 @@ AllocateAlignedBuffer ( **/ VOID FreeAlignedBuffer ( - IN VOID *Buffer, - IN UINTN BufferSize + IN VOID *Buffer, + IN UINTN BufferSize ) { if (Buffer != NULL) { @@ -120,12 +118,12 @@ FreeAlignedBuffer ( **/ EFI_STATUS EFIAPI -InitializeScsiBus( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeScsiBus ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -143,7 +141,6 @@ InitializeScsiBus( return Status; } - /** Test to see if this driver supports ControllerHandle. @@ -171,12 +168,12 @@ SCSIBusDriverBindingSupported ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_SCSI_PASS_THRU_PROTOCOL *PassThru; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtPassThru; - UINT64 Lun; - UINT8 *TargetId; - SCSI_TARGET_ID ScsiTargetId; + EFI_STATUS Status; + EFI_SCSI_PASS_THRU_PROTOCOL *PassThru; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtPassThru; + UINT64 Lun; + UINT8 *TargetId; + SCSI_TARGET_ID ScsiTargetId; TargetId = &ScsiTargetId.ScsiId.ExtScsi[0]; SetMem (TargetId, TARGET_MAX_BYTES, 0xFF); @@ -197,7 +194,7 @@ SCSIBusDriverBindingSupported ( if (Status == EFI_ALREADY_STARTED) { return EFI_SUCCESS; - } else if (!EFI_ERROR(Status)) { + } else if (!EFI_ERROR (Status)) { // // Check if RemainingDevicePath is NULL or the End of Device Path Node, // if yes, return EFI_SUCCESS. @@ -227,7 +224,7 @@ SCSIBusDriverBindingSupported ( This->DriverBindingHandle, Controller ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } } @@ -271,7 +268,6 @@ SCSIBusDriverBindingSupported ( return Status; } - /** Start this driver on ControllerHandle. @@ -299,20 +295,20 @@ SCSIBusDriverBindingStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - UINT64 Lun; - UINT8 *TargetId; - BOOLEAN ScanOtherPuns; - BOOLEAN FromFirstTarget; - BOOLEAN ExtScsiSupport; - EFI_STATUS Status; - EFI_STATUS DevicePathStatus; - EFI_STATUS PassThruStatus; - SCSI_BUS_DEVICE *ScsiBusDev; - SCSI_TARGET_ID ScsiTargetId; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_SCSI_PASS_THRU_PROTOCOL *ScsiInterface; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiInterface; - EFI_SCSI_BUS_PROTOCOL *BusIdentify; + UINT64 Lun; + UINT8 *TargetId; + BOOLEAN ScanOtherPuns; + BOOLEAN FromFirstTarget; + BOOLEAN ExtScsiSupport; + EFI_STATUS Status; + EFI_STATUS DevicePathStatus; + EFI_STATUS PassThruStatus; + SCSI_BUS_DEVICE *ScsiBusDev; + SCSI_TARGET_ID ScsiTargetId; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_SCSI_PASS_THRU_PROTOCOL *ScsiInterface; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiInterface; + EFI_SCSI_BUS_PROTOCOL *BusIdentify; TargetId = NULL; ScanOtherPuns = TRUE; @@ -326,7 +322,7 @@ SCSIBusDriverBindingStart ( DevicePathStatus = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -352,7 +348,7 @@ SCSIBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiExtScsiPassThruProtocolGuid, - (VOID **) &ExtScsiInterface, + (VOID **)&ExtScsiInterface, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -360,11 +356,11 @@ SCSIBusDriverBindingStart ( // // Fail to open UEFI ExtendPassThru Protocol, then try to open EFI PassThru Protocol instead. // - if (EFI_ERROR(Status) && (Status != EFI_ALREADY_STARTED)) { + if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { Status = gBS->OpenProtocol ( Controller, &gEfiScsiPassThruProtocolGuid, - (VOID **) &ScsiInterface, + (VOID **)&ScsiInterface, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -373,7 +369,7 @@ SCSIBusDriverBindingStart ( // Fail to open EFI PassThru Protocol, Close the DevicePathProtocol if it is opened by this time. // if (EFI_ERROR (Status) && (Status != EFI_ALREADY_STARTED)) { - if (!EFI_ERROR(DevicePathStatus)) { + if (!EFI_ERROR (DevicePathStatus)) { gBS->CloseProtocol ( Controller, &gEfiDevicePathProtocolGuid, @@ -381,6 +377,7 @@ SCSIBusDriverBindingStart ( Controller ); } + return Status; } } else { @@ -393,7 +390,7 @@ SCSIBusDriverBindingStart ( PassThruStatus = gBS->OpenProtocol ( Controller, &gEfiScsiPassThruProtocolGuid, - (VOID **) &ScsiInterface, + (VOID **)&ScsiInterface, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -406,18 +403,19 @@ SCSIBusDriverBindingStart ( // on this handle for this time. Then construct Host controller private data. // ScsiBusDev = NULL; - ScsiBusDev = AllocateZeroPool(sizeof(SCSI_BUS_DEVICE)); + ScsiBusDev = AllocateZeroPool (sizeof (SCSI_BUS_DEVICE)); if (ScsiBusDev == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - ScsiBusDev->Signature = SCSI_BUS_DEVICE_SIGNATURE; - ScsiBusDev->ExtScsiSupport = ExtScsiSupport; - ScsiBusDev->DevicePath = ParentDevicePath; + + ScsiBusDev->Signature = SCSI_BUS_DEVICE_SIGNATURE; + ScsiBusDev->ExtScsiSupport = ExtScsiSupport; + ScsiBusDev->DevicePath = ParentDevicePath; if (ScsiBusDev->ExtScsiSupport) { ScsiBusDev->ExtScsiInterface = ExtScsiInterface; } else { - ScsiBusDev->ScsiInterface = ScsiInterface; + ScsiBusDev->ScsiInterface = ScsiInterface; } // @@ -442,7 +440,7 @@ SCSIBusDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &BusIdentify, + (VOID **)&BusIdentify, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -451,6 +449,7 @@ SCSIBusDriverBindingStart ( if (EFI_ERROR (Status)) { return Status; } + ScsiBusDev = SCSI_BUS_CONTROLLER_DEVICE_FROM_THIS (BusIdentify); } @@ -463,7 +462,7 @@ SCSIBusDriverBindingStart ( ParentDevicePath ); - Lun = 0; + Lun = 0; if (RemainingDevicePath == NULL) { // // If RemainingDevicePath is NULL, @@ -492,7 +491,7 @@ SCSIBusDriverBindingStart ( ScanOtherPuns = FALSE; } - while(ScanOtherPuns) { + while (ScanOtherPuns) { if (FromFirstTarget) { // // Remaining Device Path is NULL, scan all the possible Puns in the @@ -503,6 +502,7 @@ SCSIBusDriverBindingStart ( } else { Status = ScsiBusDev->ScsiInterface->GetNextDevice (ScsiBusDev->ScsiInterface, &ScsiTargetId.ScsiId.Scsi, &Lun); } + if (EFI_ERROR (Status)) { // // no legal Pun and Lun found any more @@ -512,6 +512,7 @@ SCSIBusDriverBindingStart ( } else { ScanOtherPuns = FALSE; } + // // Avoid creating handle for the host adapter. // @@ -524,12 +525,14 @@ SCSIBusDriverBindingStart ( continue; } } + // // Scan for the scsi device, if it attaches to the scsi bus, // then create handle and install scsi i/o protocol. // Status = ScsiScanCreateDevice (This, Controller, &ScsiTargetId, Lun, ScsiBusDev); } + return EFI_SUCCESS; ErrorExit: @@ -561,6 +564,7 @@ ErrorExit: Controller ); } + return Status; } @@ -586,20 +590,20 @@ ErrorExit: EFI_STATUS EFIAPI SCSIBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - BOOLEAN AllChildrenStopped; - UINTN Index; - EFI_SCSI_IO_PROTOCOL *ScsiIo; - SCSI_IO_DEV *ScsiIoDevice; - VOID *ScsiPassThru; - EFI_SCSI_BUS_PROTOCOL *Scsidentifier; - SCSI_BUS_DEVICE *ScsiBusDev; + EFI_STATUS Status; + BOOLEAN AllChildrenStopped; + UINTN Index; + EFI_SCSI_IO_PROTOCOL *ScsiIo; + SCSI_IO_DEV *ScsiIoDevice; + VOID *ScsiPassThru; + EFI_SCSI_BUS_PROTOCOL *Scsidentifier; + SCSI_BUS_DEVICE *ScsiBusDev; if (NumberOfChildren == 0) { // @@ -608,7 +612,7 @@ SCSIBusDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &Scsidentifier, + (VOID **)&Scsidentifier, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -675,11 +679,10 @@ SCSIBusDriverBindingStop ( AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiScsiIoProtocolGuid, - (VOID **) &ScsiIo, + (VOID **)&ScsiIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -700,7 +703,6 @@ SCSIBusDriverBindingStop ( This->DriverBindingHandle, ChildHandleBuffer[Index] ); - } else { Status = gBS->CloseProtocol ( Controller, @@ -751,7 +753,6 @@ SCSIBusDriverBindingStop ( return EFI_SUCCESS; } - /** Retrieves the device type information of the SCSI Controller. @@ -766,22 +767,21 @@ SCSIBusDriverBindingStop ( EFI_STATUS EFIAPI ScsiGetDeviceType ( - IN EFI_SCSI_IO_PROTOCOL *This, - OUT UINT8 *DeviceType + IN EFI_SCSI_IO_PROTOCOL *This, + OUT UINT8 *DeviceType ) { - SCSI_IO_DEV *ScsiIoDevice; + SCSI_IO_DEV *ScsiIoDevice; if (DeviceType == NULL) { return EFI_INVALID_PARAMETER; } - ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); - *DeviceType = ScsiIoDevice->ScsiDeviceType; + ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); + *DeviceType = ScsiIoDevice->ScsiDeviceType; return EFI_SUCCESS; } - /** Retrieves the device location in the SCSI channel. @@ -798,22 +798,22 @@ ScsiGetDeviceType ( EFI_STATUS EFIAPI ScsiGetDeviceLocation ( - IN EFI_SCSI_IO_PROTOCOL *This, - IN OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_SCSI_IO_PROTOCOL *This, + IN OUT UINT8 **Target, + OUT UINT64 *Lun ) { - SCSI_IO_DEV *ScsiIoDevice; + SCSI_IO_DEV *ScsiIoDevice; - if (Target == NULL || Lun == NULL) { + if ((Target == NULL) || (Lun == NULL)) { return EFI_INVALID_PARAMETER; } ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); - CopyMem (*Target,&ScsiIoDevice->Pun, TARGET_MAX_BYTES); + CopyMem (*Target, &ScsiIoDevice->Pun, TARGET_MAX_BYTES); - *Lun = ScsiIoDevice->Lun; + *Lun = ScsiIoDevice->Lun; return EFI_SUCCESS; } @@ -833,10 +833,10 @@ ScsiGetDeviceLocation ( EFI_STATUS EFIAPI ScsiResetBus ( - IN EFI_SCSI_IO_PROTOCOL *This + IN EFI_SCSI_IO_PROTOCOL *This ) { - SCSI_IO_DEV *ScsiIoDevice; + SCSI_IO_DEV *ScsiIoDevice; ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); @@ -849,14 +849,13 @@ ScsiResetBus ( ScsiIoDevice->ScsiBusDeviceData->DevicePath ); - if (ScsiIoDevice->ExtScsiSupport){ + if (ScsiIoDevice->ExtScsiSupport) { return ScsiIoDevice->ExtScsiPassThru->ResetChannel (ScsiIoDevice->ExtScsiPassThru); } else { return ScsiIoDevice->ScsiPassThru->ResetChannel (ScsiIoDevice->ScsiPassThru); } } - /** Resets the SCSI Controller that the device handle specifies. @@ -871,7 +870,7 @@ ScsiResetBus ( EFI_STATUS EFIAPI ScsiResetDevice ( - IN EFI_SCSI_IO_PROTOCOL *This + IN EFI_SCSI_IO_PROTOCOL *This ) { SCSI_IO_DEV *ScsiIoDevice; @@ -888,25 +887,23 @@ ScsiResetDevice ( ScsiIoDevice->ScsiBusDeviceData->DevicePath ); - CopyMem (Target,&ScsiIoDevice->Pun, TARGET_MAX_BYTES); - + CopyMem (Target, &ScsiIoDevice->Pun, TARGET_MAX_BYTES); if (ScsiIoDevice->ExtScsiSupport) { return ScsiIoDevice->ExtScsiPassThru->ResetTargetLun ( - ScsiIoDevice->ExtScsiPassThru, - Target, - ScsiIoDevice->Lun - ); + ScsiIoDevice->ExtScsiPassThru, + Target, + ScsiIoDevice->Lun + ); } else { return ScsiIoDevice->ScsiPassThru->ResetTarget ( - ScsiIoDevice->ScsiPassThru, - ScsiIoDevice->Pun.ScsiId.Scsi, - ScsiIoDevice->Lun - ); + ScsiIoDevice->ScsiPassThru, + ScsiIoDevice->Pun.ScsiId.Scsi, + ScsiIoDevice->Lun + ); } } - /** Sends a SCSI Request Packet to the SCSI Controller for execution. @@ -957,9 +954,9 @@ ScsiResetDevice ( EFI_STATUS EFIAPI ScsiExecuteSCSICommand ( - IN EFI_SCSI_IO_PROTOCOL *This, - IN OUT EFI_SCSI_IO_SCSI_REQUEST_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_SCSI_IO_PROTOCOL *This, + IN OUT EFI_SCSI_IO_SCSI_REQUEST_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { SCSI_IO_DEV *ScsiIoDevice; @@ -975,11 +972,11 @@ ScsiExecuteSCSICommand ( return EFI_INVALID_PARAMETER; } - ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); - CopyMem (Target,&ScsiIoDevice->Pun, TARGET_MAX_BYTES); + ScsiIoDevice = SCSI_IO_DEV_FROM_THIS (This); + CopyMem (Target, &ScsiIoDevice->Pun, TARGET_MAX_BYTES); if (ScsiIoDevice->ExtScsiSupport) { - ExtRequestPacket = (EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *) Packet; + ExtRequestPacket = (EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *)Packet; if (((ScsiIoDevice->ExtScsiPassThru->Mode->Attributes & EFI_SCSI_PASS_THRU_ATTRIBUTES_NONBLOCKIO) != 0) && (Event != NULL)) { Status = ScsiIoDevice->ExtScsiPassThru->PassThru ( @@ -1001,7 +998,7 @@ ScsiExecuteSCSICommand ( ExtRequestPacket, NULL ); - if ((!EFI_ERROR(Status)) && (Event != NULL)) { + if ((!EFI_ERROR (Status)) && (Event != NULL)) { // // Signal Event to tell caller to pick up the SCSI IO packet if the // PassThru() succeeds. @@ -1010,8 +1007,7 @@ ScsiExecuteSCSICommand ( } } } else { - - mWorkingBuffer = AllocatePool (sizeof(EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET)); + mWorkingBuffer = AllocatePool (sizeof (EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET)); if (mWorkingBuffer == NULL) { return EFI_DEVICE_ERROR; @@ -1020,67 +1016,66 @@ ScsiExecuteSCSICommand ( // // Convert package into EFI1.0, EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET. // - Status = ScsiioToPassThruPacket(Packet, (EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET*)mWorkingBuffer); - if (EFI_ERROR(Status)) { - FreePool(mWorkingBuffer); + Status = ScsiioToPassThruPacket (Packet, (EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *)mWorkingBuffer); + if (EFI_ERROR (Status)) { + FreePool (mWorkingBuffer); return Status; } if (((ScsiIoDevice->ScsiPassThru->Mode->Attributes & EFI_SCSI_PASS_THRU_ATTRIBUTES_NONBLOCKIO) != 0) && (Event != NULL)) { - EventData.Data1 = (VOID*)Packet; + EventData.Data1 = (VOID *)Packet; EventData.Data2 = Event; // // Create Event // Status = gBS->CreateEvent ( - EVT_NOTIFY_SIGNAL, - TPL_NOTIFY, - NotifyFunction, - &EventData, - &PacketEvent - ); - if (EFI_ERROR(Status)) { - FreePool(mWorkingBuffer); + EVT_NOTIFY_SIGNAL, + TPL_NOTIFY, + NotifyFunction, + &EventData, + &PacketEvent + ); + if (EFI_ERROR (Status)) { + FreePool (mWorkingBuffer); return Status; } Status = ScsiIoDevice->ScsiPassThru->PassThru ( - ScsiIoDevice->ScsiPassThru, - ScsiIoDevice->Pun.ScsiId.Scsi, - ScsiIoDevice->Lun, - mWorkingBuffer, - PacketEvent - ); + ScsiIoDevice->ScsiPassThru, + ScsiIoDevice->Pun.ScsiId.Scsi, + ScsiIoDevice->Lun, + mWorkingBuffer, + PacketEvent + ); - if (EFI_ERROR(Status)) { - FreePool(mWorkingBuffer); - gBS->CloseEvent(PacketEvent); + if (EFI_ERROR (Status)) { + FreePool (mWorkingBuffer); + gBS->CloseEvent (PacketEvent); return Status; } - } else { // // If there's no event or SCSI Device doesn't support NON-BLOCKING, just convert // EFI1.0 PassThru packet back to UEFI2.0 SCSI IO Packet. // Status = ScsiIoDevice->ScsiPassThru->PassThru ( - ScsiIoDevice->ScsiPassThru, - ScsiIoDevice->Pun.ScsiId.Scsi, - ScsiIoDevice->Lun, - mWorkingBuffer, - NULL - ); - if (EFI_ERROR(Status)) { - FreePool(mWorkingBuffer); + ScsiIoDevice->ScsiPassThru, + ScsiIoDevice->Pun.ScsiId.Scsi, + ScsiIoDevice->Lun, + mWorkingBuffer, + NULL + ); + if (EFI_ERROR (Status)) { + FreePool (mWorkingBuffer); return Status; } - PassThruToScsiioPacket((EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET*)mWorkingBuffer,Packet); + PassThruToScsiioPacket ((EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *)mWorkingBuffer, Packet); // // After converting EFI1.0 PassThru Packet back to UEFI2.0 SCSI IO Packet, // free mWorkingBuffer. // - FreePool(mWorkingBuffer); + FreePool (mWorkingBuffer); // // Signal Event to tell caller to pick up the SCSI IO Packet. @@ -1090,10 +1085,10 @@ ScsiExecuteSCSICommand ( } } } + return Status; } - /** Scan SCSI Bus to discover the device, and attach ScsiIoProtocol to it. @@ -1111,11 +1106,11 @@ ScsiExecuteSCSICommand ( EFI_STATUS EFIAPI ScsiScanCreateDevice ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN SCSI_TARGET_ID *TargetId, - IN UINT64 Lun, - IN OUT SCSI_BUS_DEVICE *ScsiBusDev + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN SCSI_TARGET_ID *TargetId, + IN UINT64 Lun, + IN OUT SCSI_BUS_DEVICE *ScsiBusDev ) { EFI_STATUS Status; @@ -1123,7 +1118,7 @@ ScsiScanCreateDevice ( EFI_DEVICE_PATH_PROTOCOL *ScsiDevicePath; EFI_DEVICE_PATH_PROTOCOL *DevicePath; EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - EFI_HANDLE DeviceHandle; + EFI_HANDLE DeviceHandle; DevicePath = NULL; RemainingDevicePath = NULL; @@ -1133,7 +1128,7 @@ ScsiScanCreateDevice ( // // Build Device Path // - if (ScsiBusDev->ExtScsiSupport){ + if (ScsiBusDev->ExtScsiSupport) { Status = ScsiBusDev->ExtScsiInterface->BuildDevicePath ( ScsiBusDev->ExtScsiInterface, &TargetId->ScsiId.ExtScsi[0], @@ -1149,7 +1144,7 @@ ScsiScanCreateDevice ( ); } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -1163,10 +1158,10 @@ ScsiScanCreateDevice ( goto ErrorExit; } - DeviceHandle = NULL; + DeviceHandle = NULL; RemainingDevicePath = DevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) { + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (RemainingDevicePath)) { // // The device has been started, directly return to fast boot. // @@ -1180,20 +1175,19 @@ ScsiScanCreateDevice ( goto ErrorExit; } - ScsiIoDevice->Signature = SCSI_IO_DEV_SIGNATURE; - ScsiIoDevice->ScsiBusDeviceData = ScsiBusDev; - CopyMem(&ScsiIoDevice->Pun, TargetId, TARGET_MAX_BYTES); - ScsiIoDevice->Lun = Lun; + ScsiIoDevice->Signature = SCSI_IO_DEV_SIGNATURE; + ScsiIoDevice->ScsiBusDeviceData = ScsiBusDev; + CopyMem (&ScsiIoDevice->Pun, TargetId, TARGET_MAX_BYTES); + ScsiIoDevice->Lun = Lun; if (ScsiBusDev->ExtScsiSupport) { - ScsiIoDevice->ExtScsiPassThru = ScsiBusDev->ExtScsiInterface; - ScsiIoDevice->ExtScsiSupport = TRUE; - ScsiIoDevice->ScsiIo.IoAlign = ScsiIoDevice->ExtScsiPassThru->Mode->IoAlign; - + ScsiIoDevice->ExtScsiPassThru = ScsiBusDev->ExtScsiInterface; + ScsiIoDevice->ExtScsiSupport = TRUE; + ScsiIoDevice->ScsiIo.IoAlign = ScsiIoDevice->ExtScsiPassThru->Mode->IoAlign; } else { - ScsiIoDevice->ScsiPassThru = ScsiBusDev->ScsiInterface; - ScsiIoDevice->ExtScsiSupport = FALSE; - ScsiIoDevice->ScsiIo.IoAlign = ScsiIoDevice->ScsiPassThru->Mode->IoAlign; + ScsiIoDevice->ScsiPassThru = ScsiBusDev->ScsiInterface; + ScsiIoDevice->ExtScsiSupport = FALSE; + ScsiIoDevice->ScsiIo.IoAlign = ScsiIoDevice->ScsiPassThru->Mode->IoAlign; } ScsiIoDevice->ScsiIo.GetDeviceType = ScsiGetDeviceType; @@ -1233,22 +1227,23 @@ ScsiScanCreateDevice ( gBS->OpenProtocol ( Controller, &gEfiExtScsiPassThruProtocolGuid, - (VOID **) &(ScsiBusDev->ExtScsiInterface), + (VOID **)&(ScsiBusDev->ExtScsiInterface), This->DriverBindingHandle, ScsiIoDevice->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); - } else { + } else { gBS->OpenProtocol ( Controller, &gEfiScsiPassThruProtocolGuid, - (VOID **) &(ScsiBusDev->ScsiInterface), + (VOID **)&(ScsiBusDev->ScsiInterface), This->DriverBindingHandle, ScsiIoDevice->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); - } + } } + return EFI_SUCCESS; ErrorExit: @@ -1271,7 +1266,6 @@ ErrorExit: return Status; } - /** Discovery SCSI Device @@ -1283,19 +1277,19 @@ ErrorExit: **/ BOOLEAN DiscoverScsiDevice ( - IN OUT SCSI_IO_DEV *ScsiIoDevice + IN OUT SCSI_IO_DEV *ScsiIoDevice ) { - EFI_STATUS Status; - UINT32 InquiryDataLength; - UINT8 SenseDataLength; - UINT8 HostAdapterStatus; - UINT8 TargetStatus; - EFI_SCSI_INQUIRY_DATA *InquiryData; - EFI_SCSI_SENSE_DATA *SenseData; - UINT8 MaxRetry; - UINT8 Index; - BOOLEAN ScsiDeviceFound; + EFI_STATUS Status; + UINT32 InquiryDataLength; + UINT8 SenseDataLength; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; + EFI_SCSI_INQUIRY_DATA *InquiryData; + EFI_SCSI_SENSE_DATA *SenseData; + UINT8 MaxRetry; + UINT8 Index; + BOOLEAN ScsiDeviceFound; HostAdapterStatus = 0; TargetStatus = 0; @@ -1327,29 +1321,33 @@ DiscoverScsiDevice ( MaxRetry = 2; for (Index = 0; Index < MaxRetry; Index++) { Status = ScsiInquiryCommand ( - &ScsiIoDevice->ScsiIo, - SCSI_BUS_TIMEOUT, - SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - (VOID *) InquiryData, - &InquiryDataLength, - FALSE - ); + &ScsiIoDevice->ScsiIo, + SCSI_BUS_TIMEOUT, + SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + (VOID *)InquiryData, + &InquiryDataLength, + FALSE + ); if (!EFI_ERROR (Status)) { if ((HostAdapterStatus == EFI_SCSI_IO_STATUS_HOST_ADAPTER_OK) && (TargetStatus == EFI_SCSI_IO_STATUS_TARGET_CHECK_CONDITION) && (SenseData->Error_Code == 0x70) && - (SenseData->Sense_Key == EFI_SCSI_SK_ILLEGAL_REQUEST)) { + (SenseData->Sense_Key == EFI_SCSI_SK_ILLEGAL_REQUEST)) + { ScsiDeviceFound = FALSE; goto Done; } + break; } + if ((Status == EFI_BAD_BUFFER_SIZE) || (Status == EFI_INVALID_PARAMETER) || - (Status == EFI_UNSUPPORTED)) { + (Status == EFI_UNSUPPORTED)) + { ScsiDeviceFound = FALSE; goto Done; } @@ -1369,7 +1367,8 @@ DiscoverScsiDevice ( } if ((InquiryData->Peripheral_Type >= EFI_SCSI_TYPE_RESERVED_LOW) && - (InquiryData->Peripheral_Type <= EFI_SCSI_TYPE_RESERVED_HIGH)) { + (InquiryData->Peripheral_Type <= EFI_SCSI_TYPE_RESERVED_HIGH)) + { ScsiDeviceFound = FALSE; goto Done; } @@ -1385,7 +1384,7 @@ DiscoverScsiDevice ( // // ANSI-approved version // - ScsiIoDevice->ScsiVersion = (UINT8) (InquiryData->Version & 0x07); + ScsiIoDevice->ScsiVersion = (UINT8)(InquiryData->Version & 0x07); } ScsiDeviceFound = TRUE; @@ -1397,7 +1396,6 @@ Done: return ScsiDeviceFound; } - /** Convert EFI_SCSI_IO_SCSI_REQUEST_PACKET packet to EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET packet. @@ -1413,7 +1411,7 @@ ScsiioToPassThruPacket ( ) { // - //EFI 1.10 doesn't support Bi-Direction Command. + // EFI 1.10 doesn't support Bi-Direction Command. // if (Packet->DataDirection == EFI_SCSI_IO_DATA_DIRECTION_BIDIRECTIONAL) { return EFI_UNSUPPORTED; @@ -1431,16 +1429,16 @@ ScsiioToPassThruPacket ( CommandPacket->SenseDataLength = Packet->SenseDataLength; if (Packet->DataDirection == EFI_SCSI_IO_DATA_DIRECTION_READ) { - CommandPacket->DataBuffer = Packet->InDataBuffer; + CommandPacket->DataBuffer = Packet->InDataBuffer; CommandPacket->TransferLength = Packet->InTransferLength; } else if (Packet->DataDirection == EFI_SCSI_IO_DATA_DIRECTION_WRITE) { - CommandPacket->DataBuffer = Packet->OutDataBuffer; + CommandPacket->DataBuffer = Packet->OutDataBuffer; CommandPacket->TransferLength = Packet->OutTransferLength; } + return EFI_SUCCESS; } - /** Convert EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET packet to EFI_SCSI_IO_SCSI_REQUEST_PACKET packet. @@ -1465,10 +1463,10 @@ PassThruToScsiioPacket ( Packet->SenseDataLength = ScsiPacket->SenseDataLength; if (ScsiPacket->DataDirection == EFI_SCSI_IO_DATA_DIRECTION_READ) { - Packet->InDataBuffer = ScsiPacket->DataBuffer; + Packet->InDataBuffer = ScsiPacket->DataBuffer; Packet->InTransferLength = ScsiPacket->TransferLength; } else if (Packet->DataDirection == EFI_SCSI_IO_DATA_DIRECTION_WRITE) { - Packet->OutDataBuffer = ScsiPacket->DataBuffer; + Packet->OutDataBuffer = ScsiPacket->DataBuffer; Packet->OutTransferLength = ScsiPacket->TransferLength; } @@ -1490,31 +1488,30 @@ NotifyFunction ( IN VOID *Context ) { - EFI_SCSI_IO_SCSI_REQUEST_PACKET *Packet; - EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *ScsiPacket; - EFI_EVENT CallerEvent; - SCSI_EVENT_DATA *PassData; + EFI_SCSI_IO_SCSI_REQUEST_PACKET *Packet; + EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *ScsiPacket; + EFI_EVENT CallerEvent; + SCSI_EVENT_DATA *PassData; - PassData = (SCSI_EVENT_DATA*)Context; - Packet = (EFI_SCSI_IO_SCSI_REQUEST_PACKET *)PassData->Data1; - ScsiPacket = (EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET*)mWorkingBuffer; + PassData = (SCSI_EVENT_DATA *)Context; + Packet = (EFI_SCSI_IO_SCSI_REQUEST_PACKET *)PassData->Data1; + ScsiPacket = (EFI_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *)mWorkingBuffer; // // Convert EFI1.0 PassThru packet to UEFI2.0 SCSI IO Packet. // - PassThruToScsiioPacket(ScsiPacket, Packet); + PassThruToScsiioPacket (ScsiPacket, Packet); // // After converting EFI1.0 PassThru Packet back to UEFI2.0 SCSI IO Packet, // free mWorkingBuffer. // - gBS->FreePool(mWorkingBuffer); + gBS->FreePool (mWorkingBuffer); // // Signal Event to tell caller to pick up UEFI2.0 SCSI IO Packet. // CallerEvent = PassData->Data2; - gBS->CloseEvent(Event); - gBS->SignalEvent(CallerEvent); + gBS->CloseEvent (Event); + gBS->SignalEvent (CallerEvent); } - diff --git a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h index 97581866b6..68c5c02a91 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h +++ b/MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBus.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SCSI_BUS_H_ #define _SCSI_BUS_H_ - #include #include @@ -31,22 +30,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define SCSI_IO_DEV_SIGNATURE SIGNATURE_32 ('s', 'c', 'i', 'o') +#define SCSI_IO_DEV_SIGNATURE SIGNATURE_32 ('s', 'c', 'i', 'o') typedef union { - UINT32 Scsi; - UINT8 ExtScsi[4]; + UINT32 Scsi; + UINT8 ExtScsi[4]; } SCSI_ID; typedef struct _SCSI_TARGET_ID { - SCSI_ID ScsiId; - UINT8 ExtScsiId[12]; -}SCSI_TARGET_ID; - + SCSI_ID ScsiId; + UINT8 ExtScsiId[12]; +} SCSI_TARGET_ID; typedef struct { - VOID *Data1; - VOID *Data2; + VOID *Data1; + VOID *Data2; } SCSI_EVENT_DATA; // @@ -57,7 +55,7 @@ typedef struct { // // SCSI Bus Timeout Experience Value // -#define SCSI_BUS_TIMEOUT EFI_TIMER_PERIOD_SECONDS (3) +#define SCSI_BUS_TIMEOUT EFI_TIMER_PERIOD_SECONDS (3) // // The ScsiBusProtocol is just used to locate ScsiBusDev @@ -67,16 +65,16 @@ typedef struct { // gEfiCallerIdGuid will be used as its protocol guid. // typedef struct _EFI_SCSI_BUS_PROTOCOL { - UINT64 Reserved; + UINT64 Reserved; } EFI_SCSI_BUS_PROTOCOL; typedef struct _SCSI_BUS_DEVICE { - UINTN Signature; - EFI_SCSI_BUS_PROTOCOL BusIdentify; - BOOLEAN ExtScsiSupport; - EFI_SCSI_PASS_THRU_PROTOCOL *ScsiInterface; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiInterface; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINTN Signature; + EFI_SCSI_BUS_PROTOCOL BusIdentify; + BOOLEAN ExtScsiSupport; + EFI_SCSI_PASS_THRU_PROTOCOL *ScsiInterface; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiInterface; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } SCSI_BUS_DEVICE; #define SCSI_BUS_CONTROLLER_DEVICE_FROM_THIS(a) CR (a, SCSI_BUS_DEVICE, BusIdentify, SCSI_BUS_DEVICE_SIGNATURE) @@ -182,15 +180,16 @@ SCSIBusDriverBindingStart ( EFI_STATUS EFIAPI SCSIBusDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -309,11 +308,11 @@ ScsiBusComponentNameGetDriverName ( EFI_STATUS EFIAPI ScsiBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -330,8 +329,8 @@ ScsiBusComponentNameGetControllerName ( EFI_STATUS EFIAPI ScsiGetDeviceType ( - IN EFI_SCSI_IO_PROTOCOL *This, - OUT UINT8 *DeviceType + IN EFI_SCSI_IO_PROTOCOL *This, + OUT UINT8 *DeviceType ); /** @@ -350,9 +349,9 @@ ScsiGetDeviceType ( EFI_STATUS EFIAPI ScsiGetDeviceLocation ( - IN EFI_SCSI_IO_PROTOCOL *This, - IN OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_SCSI_IO_PROTOCOL *This, + IN OUT UINT8 **Target, + OUT UINT64 *Lun ); /** @@ -370,7 +369,7 @@ ScsiGetDeviceLocation ( EFI_STATUS EFIAPI ScsiResetBus ( - IN EFI_SCSI_IO_PROTOCOL *This + IN EFI_SCSI_IO_PROTOCOL *This ); /** @@ -387,7 +386,7 @@ ScsiResetBus ( EFI_STATUS EFIAPI ScsiResetDevice ( - IN EFI_SCSI_IO_PROTOCOL *This + IN EFI_SCSI_IO_PROTOCOL *This ); /** @@ -462,11 +461,11 @@ ScsiExecuteSCSICommand ( EFI_STATUS EFIAPI ScsiScanCreateDevice ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN SCSI_TARGET_ID *TargetId, - IN UINT64 Lun, - IN OUT SCSI_BUS_DEVICE *ScsiBusDev + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN SCSI_TARGET_ID *TargetId, + IN UINT64 Lun, + IN OUT SCSI_BUS_DEVICE *ScsiBusDev ); /** @@ -480,7 +479,7 @@ ScsiScanCreateDevice ( **/ BOOLEAN DiscoverScsiDevice ( - IN OUT SCSI_IO_DEV *ScsiIoDevice + IN OUT SCSI_IO_DEV *ScsiIoDevice ); #endif diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ComponentName.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ComponentName.c index b193de9ed9..212d26bf88 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ComponentName.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "ScsiDisk.h" // @@ -21,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gScsiDiskComponentNam // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gScsiDiskComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) ScsiDiskComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) ScsiDiskComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gScsiDiskComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)ScsiDiskComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)ScsiDiskComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mScsiDiskDriverNameTable[] = { - { "eng;en", (CHAR16 *) L"Scsi Disk Driver" }, - { NULL , NULL } +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mScsiDiskDriverNameTable[] = { + { "eng;en", (CHAR16 *)L"Scsi Disk Driver" }, + { NULL, NULL } }; /** @@ -160,16 +158,16 @@ ScsiDiskComponentNameGetDriverName ( EFI_STATUS EFIAPI ScsiDiskComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - SCSI_DISK_DEV *ScsiDiskDevice; - EFI_BLOCK_IO_PROTOCOL *BlockIo; + EFI_STATUS Status; + SCSI_DISK_DEV *ScsiDiskDevice; + EFI_BLOCK_IO_PROTOCOL *BlockIo; // // This is a device driver, so ChildHandle must be NULL. @@ -189,13 +187,14 @@ ScsiDiskComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, gScsiDiskDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,5 +213,4 @@ ScsiDiskComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gScsiDiskComponentName) ); - } diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c index b35d92fcd7..98e84b4ea8 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c @@ -6,10 +6,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "ScsiDisk.h" -EFI_DRIVER_BINDING_PROTOCOL gScsiDiskDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gScsiDiskDriverBinding = { ScsiDiskDriverBindingSupported, ScsiDiskDriverBindingStart, ScsiDiskDriverBindingStop, @@ -18,7 +17,7 @@ EFI_DRIVER_BINDING_PROTOCOL gScsiDiskDriverBinding = { NULL }; -EFI_DISK_INFO_PROTOCOL gScsiDiskInfoProtocolTemplate = { +EFI_DISK_INFO_PROTOCOL gScsiDiskInfoProtocolTemplate = { EFI_DISK_INFO_SCSI_INTERFACE_GUID, ScsiDiskInfoInquiry, ScsiDiskInfoIdentify, @@ -40,8 +39,8 @@ EFI_DISK_INFO_PROTOCOL gScsiDiskInfoProtocolTemplate = { **/ VOID * AllocateAlignedBuffer ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINTN BufferSize + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINTN BufferSize ) { return AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), ScsiDiskDevice->ScsiIo->IoAlign); @@ -59,8 +58,8 @@ AllocateAlignedBuffer ( **/ VOID FreeAlignedBuffer ( - IN VOID *Buffer, - IN UINTN BufferSize + IN VOID *Buffer, + IN UINTN BufferSize ) { if (Buffer != NULL) { @@ -82,12 +81,12 @@ FreeAlignedBuffer ( **/ EFI_STATUS EFIAPI -InitializeScsiDisk( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +InitializeScsiDisk ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). @@ -102,7 +101,6 @@ InitializeScsiDisk( ); ASSERT_EFI_ERROR (Status); - return Status; } @@ -140,7 +138,7 @@ ScsiDiskDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiScsiIoProtocolGuid, - (VOID **) &ScsiIo, + (VOID **)&ScsiIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -153,7 +151,8 @@ ScsiDiskDriverBindingSupported ( if (!EFI_ERROR (Status)) { if ((DeviceType == EFI_SCSI_TYPE_DISK) || (DeviceType == EFI_SCSI_TYPE_CDROM) || - (DeviceType == EFI_SCSI_TYPE_WLUN)) { + (DeviceType == EFI_SCSI_TYPE_WLUN)) + { Status = EFI_SUCCESS; } else { Status = EFI_UNSUPPORTED; @@ -169,7 +168,6 @@ ScsiDiskDriverBindingSupported ( return Status; } - /** Start this driver on ControllerHandle. @@ -208,7 +206,7 @@ ScsiDiskDriverBindingStart ( MustReadCapacity = TRUE; - ScsiDiskDevice = (SCSI_DISK_DEV *) AllocateZeroPool (sizeof (SCSI_DISK_DEV)); + ScsiDiskDevice = (SCSI_DISK_DEV *)AllocateZeroPool (sizeof (SCSI_DISK_DEV)); if (ScsiDiskDevice == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -216,7 +214,7 @@ ScsiDiskDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiScsiIoProtocolGuid, - (VOID **) &ScsiIo, + (VOID **)&ScsiIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -252,35 +250,36 @@ ScsiDiskDriverBindingStart ( ScsiIo->GetDeviceType (ScsiIo, &(ScsiDiskDevice->DeviceType)); switch (ScsiDiskDevice->DeviceType) { - case EFI_SCSI_TYPE_DISK: - ScsiDiskDevice->BlkIo.Media->BlockSize = 0x200; - MustReadCapacity = TRUE; - break; + case EFI_SCSI_TYPE_DISK: + ScsiDiskDevice->BlkIo.Media->BlockSize = 0x200; + MustReadCapacity = TRUE; + break; - case EFI_SCSI_TYPE_CDROM: - ScsiDiskDevice->BlkIo.Media->BlockSize = 0x800; - ScsiDiskDevice->BlkIo.Media->ReadOnly = TRUE; - MustReadCapacity = FALSE; - break; + case EFI_SCSI_TYPE_CDROM: + ScsiDiskDevice->BlkIo.Media->BlockSize = 0x800; + ScsiDiskDevice->BlkIo.Media->ReadOnly = TRUE; + MustReadCapacity = FALSE; + break; - case EFI_SCSI_TYPE_WLUN: - MustReadCapacity = FALSE; - break; + case EFI_SCSI_TYPE_WLUN: + MustReadCapacity = FALSE; + break; } + // // The Sense Data Array's initial size is 6 // ScsiDiskDevice->SenseDataNumber = 6; - ScsiDiskDevice->SenseData = (EFI_SCSI_SENSE_DATA *) AllocateZeroPool ( - sizeof (EFI_SCSI_SENSE_DATA) * ScsiDiskDevice->SenseDataNumber - ); + ScsiDiskDevice->SenseData = (EFI_SCSI_SENSE_DATA *)AllocateZeroPool ( + sizeof (EFI_SCSI_SENSE_DATA) * ScsiDiskDevice->SenseDataNumber + ); if (ScsiDiskDevice->SenseData == NULL) { gBS->CloseProtocol ( - Controller, - &gEfiScsiIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiScsiIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); FreePool (ScsiDiskDevice); return EFI_OUT_OF_RESOURCES; } @@ -307,6 +306,7 @@ ScsiDiskDriverBindingStart ( return EFI_DEVICE_ERROR; } } + // // The second parameter "TRUE" means must // retrieve media capacity @@ -341,6 +341,7 @@ ScsiDiskDriverBindingStart ( DEBUG ((DEBUG_ERROR, "ScsiDisk: Failed to install the Erase Block Protocol! Status = %r\n", Status)); } } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, Controller)) { Status = gBS->InstallProtocolInterface ( &Controller, @@ -352,6 +353,7 @@ ScsiDiskDriverBindingStart ( DEBUG ((DEBUG_ERROR, "ScsiDisk: Failed to install the Storage Security Command Protocol! Status = %r\n", Status)); } } + ScsiDiskDevice->ControllerNameTable = NULL; AddUnicodeString2 ( "eng", @@ -381,10 +383,8 @@ ScsiDiskDriverBindingStart ( Controller ); return Status; - } - /** Stop this driver on ControllerHandle. @@ -407,21 +407,21 @@ ScsiDiskDriverBindingStart ( EFI_STATUS EFIAPI ScsiDiskDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer OPTIONAL + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer OPTIONAL ) { - EFI_BLOCK_IO_PROTOCOL *BlkIo; - EFI_ERASE_BLOCK_PROTOCOL *EraseBlock; - SCSI_DISK_DEV *ScsiDiskDevice; - EFI_STATUS Status; + EFI_BLOCK_IO_PROTOCOL *BlkIo; + EFI_ERASE_BLOCK_PROTOCOL *EraseBlock; + SCSI_DISK_DEV *ScsiDiskDevice; + EFI_STATUS Status; Status = gBS->OpenProtocol ( Controller, &gEfiBlockIoProtocolGuid, - (VOID **) &BlkIo, + (VOID **)&BlkIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -435,7 +435,8 @@ ScsiDiskDriverBindingStop ( // // Wait for the BlockIo2 requests queue to become empty // - while (!IsListEmpty (&ScsiDiskDevice->AsyncTaskQueue)); + while (!IsListEmpty (&ScsiDiskDevice->AsyncTaskQueue)) { + } // // If Erase Block Protocol is installed, then uninstall this protocol. @@ -443,7 +444,7 @@ ScsiDiskDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiEraseBlockProtocolGuid, - (VOID **) &EraseBlock, + (VOID **)&EraseBlock, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -482,6 +483,7 @@ ScsiDiskDriverBindingStop ( return EFI_SUCCESS; } + // // errors met // @@ -504,19 +506,19 @@ ScsiDiskDriverBindingStop ( EFI_STATUS EFIAPI ScsiDiskReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_TPL OldTpl; - SCSI_DISK_DEV *ScsiDiskDevice; - EFI_STATUS Status; + EFI_TPL OldTpl; + SCSI_DISK_DEV *ScsiDiskDevice; + EFI_STATUS Status; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO (This); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO (This); - Status = ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); + Status = ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); if (EFI_ERROR (Status)) { if (Status == EFI_UNSUPPORTED) { @@ -563,11 +565,11 @@ Done: EFI_STATUS EFIAPI ScsiDiskReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -583,8 +585,7 @@ ScsiDiskReadBlocks ( ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO (This); Media = ScsiDiskDevice->BlkIo.Media; - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { - + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -593,11 +594,11 @@ ScsiDiskReadBlocks ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -612,33 +613,37 @@ ScsiDiskReadBlocks ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } + // // Get the intrinsic block size // - BlockSize = Media->BlockSize; + BlockSize = Media->BlockSize; if (BlockSize == 0) { Status = EFI_DEVICE_ERROR; goto Done; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if (!(Media->MediaPresent)) { Status = EFI_NO_MEDIA; @@ -675,7 +680,7 @@ ScsiDiskReadBlocks ( goto Done; } - if ((Media->IoAlign > 1) && (((UINTN) Buffer & (Media->IoAlign - 1)) != 0)) { + if ((Media->IoAlign > 1) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { Status = EFI_INVALID_PARAMETER; goto Done; } @@ -712,11 +717,11 @@ Done: EFI_STATUS EFIAPI ScsiDiskWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -732,8 +737,7 @@ ScsiDiskWriteBlocks ( ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO (This); Media = ScsiDiskDevice->BlkIo.Media; - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { - + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -742,11 +746,11 @@ ScsiDiskWriteBlocks ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -761,33 +765,37 @@ ScsiDiskWriteBlocks ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } + // // Get the intrinsic block size // - BlockSize = Media->BlockSize; + BlockSize = Media->BlockSize; if (BlockSize == 0) { Status = EFI_DEVICE_ERROR; goto Done; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if (!(Media->MediaPresent)) { Status = EFI_NO_MEDIA; @@ -829,10 +837,11 @@ ScsiDiskWriteBlocks ( goto Done; } - if ((Media->IoAlign > 1) && (((UINTN) Buffer & (Media->IoAlign - 1)) != 0)) { + if ((Media->IoAlign > 1) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { Status = EFI_INVALID_PARAMETER; goto Done; } + // // if all the parameters are valid, then perform read sectors command // to transfer data from device to host. @@ -857,7 +866,7 @@ Done: EFI_STATUS EFIAPI ScsiDiskFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ) { // @@ -866,7 +875,6 @@ ScsiDiskFlushBlocks ( return EFI_SUCCESS; } - /** Reset SCSI Disk. @@ -886,15 +894,15 @@ ScsiDiskResetEx ( IN BOOLEAN ExtendedVerification ) { - EFI_TPL OldTpl; - SCSI_DISK_DEV *ScsiDiskDevice; - EFI_STATUS Status; + EFI_TPL OldTpl; + SCSI_DISK_DEV *ScsiDiskDevice; + EFI_STATUS Status; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO2 (This); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO2 (This); - Status = ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); + Status = ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); if (EFI_ERROR (Status)) { if (Status == EFI_UNSUPPORTED) { @@ -950,12 +958,12 @@ Done: EFI_STATUS EFIAPI ScsiDiskReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -971,8 +979,7 @@ ScsiDiskReadBlocksEx ( ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO2 (This); Media = ScsiDiskDevice->BlkIo.Media; - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { - + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -981,11 +988,11 @@ ScsiDiskReadBlocksEx ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -1000,33 +1007,37 @@ ScsiDiskReadBlocksEx ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } + // // Get the intrinsic block size // - BlockSize = Media->BlockSize; + BlockSize = Media->BlockSize; if (BlockSize == 0) { Status = EFI_DEVICE_ERROR; goto Done; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if (!(Media->MediaPresent)) { Status = EFI_NO_MEDIA; @@ -1068,7 +1079,7 @@ ScsiDiskReadBlocksEx ( goto Done; } - if ((Media->IoAlign > 1) && (((UINTN) Buffer & (Media->IoAlign - 1)) != 0)) { + if ((Media->IoAlign > 1) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { Status = EFI_INVALID_PARAMETER; goto Done; } @@ -1079,13 +1090,13 @@ ScsiDiskReadBlocksEx ( // if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; - Status = ScsiDiskAsyncReadSectors ( - ScsiDiskDevice, - Buffer, - Lba, - NumberOfBlocks, - Token - ); + Status = ScsiDiskAsyncReadSectors ( + ScsiDiskDevice, + Buffer, + Lba, + NumberOfBlocks, + Token + ); } else { Status = ScsiDiskReadSectors ( ScsiDiskDevice, @@ -1126,12 +1137,12 @@ Done: EFI_STATUS EFIAPI ScsiDiskWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -1147,8 +1158,7 @@ ScsiDiskWriteBlocksEx ( ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO2 (This); Media = ScsiDiskDevice->BlkIo.Media; - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { - + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -1157,11 +1167,11 @@ ScsiDiskWriteBlocksEx ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -1176,33 +1186,37 @@ ScsiDiskWriteBlocksEx ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } + // // Get the intrinsic block size // - BlockSize = Media->BlockSize; + BlockSize = Media->BlockSize; if (BlockSize == 0) { Status = EFI_DEVICE_ERROR; goto Done; } - NumberOfBlocks = BufferSize / BlockSize; + NumberOfBlocks = BufferSize / BlockSize; if (!(Media->MediaPresent)) { Status = EFI_NO_MEDIA; @@ -1249,7 +1263,7 @@ ScsiDiskWriteBlocksEx ( goto Done; } - if ((Media->IoAlign > 1) && (((UINTN) Buffer & (Media->IoAlign - 1)) != 0)) { + if ((Media->IoAlign > 1) && (((UINTN)Buffer & (Media->IoAlign - 1)) != 0)) { Status = EFI_INVALID_PARAMETER; goto Done; } @@ -1260,13 +1274,13 @@ ScsiDiskWriteBlocksEx ( // if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; - Status = ScsiDiskAsyncWriteSectors ( - ScsiDiskDevice, - Buffer, - Lba, - NumberOfBlocks, - Token - ); + Status = ScsiDiskAsyncWriteSectors ( + ScsiDiskDevice, + Buffer, + Lba, + NumberOfBlocks, + Token + ); } else { Status = ScsiDiskWriteSectors ( ScsiDiskDevice, @@ -1313,8 +1327,7 @@ ScsiDiskFlushBlocksEx ( ScsiDiskDevice = SCSI_DISK_DEV_FROM_BLKIO2 (This); Media = ScsiDiskDevice->BlkIo.Media; - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { - + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -1323,11 +1336,11 @@ ScsiDiskFlushBlocksEx ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -1342,19 +1355,22 @@ ScsiDiskFlushBlocksEx ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } @@ -1372,7 +1388,8 @@ ScsiDiskFlushBlocksEx ( // // Wait for the BlockIo2 requests queue to become empty // - while (!IsListEmpty (&ScsiDiskDevice->AsyncTaskQueue)); + while (!IsListEmpty (&ScsiDiskDevice->AsyncTaskQueue)) { + } Status = EFI_SUCCESS; @@ -1389,7 +1406,6 @@ Done: return Status; } - /** Internal helper notify function which process the result of an asynchronous SCSI UNMAP Command and signal the event passed from EraseBlocks. @@ -1412,13 +1428,13 @@ ScsiDiskAsyncUnmapNotify ( gBS->CloseEvent (Event); - EraseBlkReq = (SCSI_ERASEBLK_REQUEST *) Context; + EraseBlkReq = (SCSI_ERASEBLK_REQUEST *)Context; CommandPacket = &EraseBlkReq->CommandPacket; Token = EraseBlkReq->Token; Token->TransactionStatus = EFI_SUCCESS; Status = CheckHostAdapterStatus (CommandPacket->HostAdapterStatus); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "ScsiDiskAsyncUnmapNotify: Host adapter indicating error status 0x%x.\n", @@ -1430,7 +1446,7 @@ ScsiDiskAsyncUnmapNotify ( } Status = CheckTargetStatus (CommandPacket->TargetStatus); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "ScsiDiskAsyncUnmapNotify: Target indicating error status 0x%x.\n", @@ -1465,10 +1481,10 @@ Done: **/ EFI_STATUS ScsiDiskUnmap ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Lba, - IN UINTN Blocks, - IN EFI_ERASE_BLOCK_TOKEN *Token OPTIONAL + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Lba, + IN UINTN Blocks, + IN EFI_ERASE_BLOCK_TOKEN *Token OPTIONAL ) { EFI_SCSI_IO_PROTOCOL *ScsiIo; @@ -1494,7 +1510,7 @@ ScsiDiskUnmap ( AsyncUnmapEvent = NULL; ReturnStatus = EFI_SUCCESS; - if (Blocks / (UINTN) MaxLbaCnt > MaxBlkDespCnt) { + if (Blocks / (UINTN)MaxLbaCnt > MaxBlkDespCnt) { ReturnStatus = EFI_DEVICE_ERROR; goto Done; } @@ -1511,10 +1527,10 @@ ScsiDiskUnmap ( goto Done; } - BlkDespCnt = (UINT32) ((Blocks - 1) / MaxLbaCnt + 1); - UnmapParamListLen = (UINT16) (sizeof (EFI_SCSI_DISK_UNMAP_PARAM_LIST_HEADER) - + BlkDespCnt * sizeof (EFI_SCSI_DISK_UNMAP_BLOCK_DESP)); - UnmapParamList = AllocateZeroPool (UnmapParamListLen); + BlkDespCnt = (UINT32)((Blocks - 1) / MaxLbaCnt + 1); + UnmapParamListLen = (UINT16)(sizeof (EFI_SCSI_DISK_UNMAP_PARAM_LIST_HEADER) + + BlkDespCnt * sizeof (EFI_SCSI_DISK_UNMAP_BLOCK_DESP)); + UnmapParamList = AllocateZeroPool (UnmapParamListLen); if (UnmapParamList == NULL) { ReturnStatus = EFI_DEVICE_ERROR; goto Done; @@ -1528,12 +1544,12 @@ ScsiDiskUnmap ( if (Blocks > MaxLbaCnt) { *(UINT64 *)(&BlkDespPtr->Lba) = SwapBytes64 (Lba); *(UINT32 *)(&BlkDespPtr->BlockNum) = SwapBytes32 (MaxLbaCnt); - Blocks -= MaxLbaCnt; - Lba += MaxLbaCnt; + Blocks -= MaxLbaCnt; + Lba += MaxLbaCnt; } else { *(UINT64 *)(&BlkDespPtr->Lba) = SwapBytes64 (Lba); - *(UINT32 *)(&BlkDespPtr->BlockNum) = SwapBytes32 ((UINT32) Blocks); - Blocks = 0; + *(UINT32 *)(&BlkDespPtr->BlockNum) = SwapBytes32 ((UINT32)Blocks); + Blocks = 0; } BlkDespPtr++; @@ -1563,7 +1579,7 @@ ScsiDiskUnmap ( EraseBlkReq, &AsyncUnmapEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { ReturnStatus = EFI_DEVICE_ERROR; goto Done; } @@ -1579,7 +1595,7 @@ ScsiDiskUnmap ( CommandPacket, AsyncUnmapEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { ReturnStatus = EFI_DEVICE_ERROR; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); @@ -1602,7 +1618,7 @@ ScsiDiskUnmap ( CommandPacket, NULL ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { ReturnStatus = EFI_DEVICE_ERROR; goto Done; } @@ -1612,7 +1628,7 @@ ScsiDiskUnmap ( // Only blocking UNMAP request will reach here. // Status = CheckHostAdapterStatus (CommandPacket->HostAdapterStatus); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "ScsiDiskUnmap: Host adapter indicating error status 0x%x.\n", @@ -1624,7 +1640,7 @@ ScsiDiskUnmap ( } Status = CheckTargetStatus (CommandPacket->TargetStatus); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "ScsiDiskUnmap: Target indicating error status 0x%x.\n", @@ -1640,6 +1656,7 @@ Done: if (EraseBlkReq->CommandPacket.Cdb != NULL) { FreePool (EraseBlkReq->CommandPacket.Cdb); } + FreePool (EraseBlkReq); } @@ -1684,11 +1701,11 @@ Done: EFI_STATUS EFIAPI ScsiDiskEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -1703,7 +1720,7 @@ ScsiDiskEraseBlocks ( OldTpl = gBS->RaiseTPL (TPL_CALLBACK); ScsiDiskDevice = SCSI_DISK_DEV_FROM_ERASEBLK (This); - if (!IS_DEVICE_FIXED(ScsiDiskDevice)) { + if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); if (EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; @@ -1712,11 +1729,11 @@ ScsiDiskEraseBlocks ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -1731,18 +1748,21 @@ ScsiDiskEraseBlocks ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + Status = EFI_MEDIA_CHANGED; goto Done; } } + // // Get the intrinsic block size // @@ -1768,6 +1788,7 @@ ScsiDiskEraseBlocks ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + Status = EFI_SUCCESS; goto Done; } @@ -1862,14 +1883,14 @@ Done: EFI_STATUS EFIAPI ScsiDiskReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId OPTIONAL, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId OPTIONAL, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -1883,14 +1904,14 @@ ScsiDiskReceiveData ( VOID *AlignedBuffer; BOOLEAN AlignedBufferAllocated; - AlignedBuffer = NULL; - MediaChange = FALSE; - AlignedBufferAllocated = FALSE; - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - ScsiDiskDevice = SCSI_DISK_DEV_FROM_STORSEC (This); - Media = ScsiDiskDevice->BlkIo.Media; + AlignedBuffer = NULL; + MediaChange = FALSE; + AlignedBufferAllocated = FALSE; + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_STORSEC (This); + Media = ScsiDiskDevice->BlkIo.Media; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); @@ -1901,11 +1922,11 @@ ScsiDiskReceiveData ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -1920,19 +1941,22 @@ ScsiDiskReceiveData ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } @@ -1962,6 +1986,7 @@ ScsiDiskReceiveData ( Status = EFI_OUT_OF_RESOURCES; goto Done; } + ZeroMem (AlignedBuffer, PayloadBufferSize); AlignedBufferAllocated = TRUE; } else { @@ -1970,19 +1995,19 @@ ScsiDiskReceiveData ( } Status = ScsiSecurityProtocolInCommand ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - SecurityProtocolId, - SecurityProtocolSpecificData, - FALSE, - PayloadBufferSize, - AlignedBuffer, - PayloadTransferSize - ); + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + SecurityProtocolId, + SecurityProtocolSpecificData, + FALSE, + PayloadBufferSize, + AlignedBuffer, + PayloadTransferSize + ); if (EFI_ERROR (Status)) { goto Done; } @@ -2011,6 +2036,7 @@ Done: ZeroMem (AlignedBuffer, PayloadBufferSize); FreeAlignedBuffer (AlignedBuffer, PayloadBufferSize); } + gBS->RestoreTPL (OldTpl); return Status; } @@ -2073,13 +2099,13 @@ Done: EFI_STATUS EFIAPI ScsiDiskSendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId OPTIONAL, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId OPTIONAL, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer ) { SCSI_DISK_DEV *ScsiDiskDevice; @@ -2093,14 +2119,14 @@ ScsiDiskSendData ( VOID *AlignedBuffer; BOOLEAN AlignedBufferAllocated; - AlignedBuffer = NULL; - MediaChange = FALSE; - AlignedBufferAllocated = FALSE; - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); - ScsiDiskDevice = SCSI_DISK_DEV_FROM_STORSEC (This); - Media = ScsiDiskDevice->BlkIo.Media; + AlignedBuffer = NULL; + MediaChange = FALSE; + AlignedBufferAllocated = FALSE; + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_STORSEC (This); + Media = ScsiDiskDevice->BlkIo.Media; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); if (!IS_DEVICE_FIXED (ScsiDiskDevice)) { Status = ScsiDiskDetectMedia (ScsiDiskDevice, FALSE, &MediaChange); @@ -2111,11 +2137,11 @@ ScsiDiskSendData ( if (MediaChange) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiBlockIoProtocolGuid, - &ScsiDiskDevice->BlkIo, - &ScsiDiskDevice->BlkIo - ); + ScsiDiskDevice->Handle, + &gEfiBlockIoProtocolGuid, + &ScsiDiskDevice->BlkIo, + &ScsiDiskDevice->BlkIo + ); gBS->ReinstallProtocolInterface ( ScsiDiskDevice->Handle, &gEfiBlockIo2ProtocolGuid, @@ -2130,19 +2156,22 @@ ScsiDiskSendData ( &ScsiDiskDevice->EraseBlock ); } + if (DetermineInstallStorageSecurity (ScsiDiskDevice, ScsiDiskDevice->Handle)) { gBS->ReinstallProtocolInterface ( - ScsiDiskDevice->Handle, - &gEfiStorageSecurityCommandProtocolGuid, - &ScsiDiskDevice->StorageSecurity, - &ScsiDiskDevice->StorageSecurity - ); + ScsiDiskDevice->Handle, + &gEfiStorageSecurityCommandProtocolGuid, + &ScsiDiskDevice->StorageSecurity, + &ScsiDiskDevice->StorageSecurity + ); } + if (Media->MediaPresent) { Status = EFI_MEDIA_CHANGED; } else { Status = EFI_NO_MEDIA; } + goto Done; } } @@ -2177,6 +2206,7 @@ ScsiDiskSendData ( Status = EFI_OUT_OF_RESOURCES; goto Done; } + CopyMem (AlignedBuffer, PayloadBuffer, PayloadBufferSize); AlignedBufferAllocated = TRUE; } else { @@ -2185,18 +2215,18 @@ ScsiDiskSendData ( } Status = ScsiSecurityProtocolOutCommand ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - SecurityProtocolId, - SecurityProtocolSpecificData, - FALSE, - PayloadBufferSize, - AlignedBuffer - ); + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + SecurityProtocolId, + SecurityProtocolSpecificData, + FALSE, + PayloadBufferSize, + AlignedBuffer + ); if (EFI_ERROR (Status)) { goto Done; } @@ -2216,11 +2246,11 @@ Done: ZeroMem (AlignedBuffer, PayloadBufferSize); FreeAlignedBuffer (AlignedBuffer, PayloadBufferSize); } + gBS->RestoreTPL (OldTpl); return Status; } - /** Detect Device and read out capacity ,if error occurs, parse the sense key. @@ -2234,31 +2264,31 @@ Done: **/ EFI_STATUS ScsiDiskDetectMedia ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN BOOLEAN MustReadCapacity, - OUT BOOLEAN *MediaChange + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN BOOLEAN MustReadCapacity, + OUT BOOLEAN *MediaChange ) { - EFI_STATUS Status; - EFI_SCSI_SENSE_DATA *SenseData; - UINTN NumberOfSenseKeys; - BOOLEAN NeedRetry; - BOOLEAN NeedReadCapacity; - UINT8 Retry; - UINT8 MaxRetry; - EFI_BLOCK_IO_MEDIA OldMedia; - UINTN Action; - EFI_EVENT TimeoutEvt; - - Status = EFI_SUCCESS; - SenseData = NULL; - NumberOfSenseKeys = 0; - Retry = 0; - MaxRetry = 3; - Action = ACTION_NO_ACTION; - NeedReadCapacity = FALSE; - *MediaChange = FALSE; - TimeoutEvt = NULL; + EFI_STATUS Status; + EFI_SCSI_SENSE_DATA *SenseData; + UINTN NumberOfSenseKeys; + BOOLEAN NeedRetry; + BOOLEAN NeedReadCapacity; + UINT8 Retry; + UINT8 MaxRetry; + EFI_BLOCK_IO_MEDIA OldMedia; + UINTN Action; + EFI_EVENT TimeoutEvt; + + Status = EFI_SUCCESS; + SenseData = NULL; + NumberOfSenseKeys = 0; + Retry = 0; + MaxRetry = 3; + Action = ACTION_NO_ACTION; + NeedReadCapacity = FALSE; + *MediaChange = FALSE; + TimeoutEvt = NULL; CopyMem (&OldMedia, ScsiDiskDevice->BlkIo.Media, sizeof (OldMedia)); @@ -2273,7 +2303,7 @@ ScsiDiskDetectMedia ( return Status; } - Status = gBS->SetTimer (TimeoutEvt, TimerRelative, EFI_TIMER_PERIOD_SECONDS(120)); + Status = gBS->SetTimer (TimeoutEvt, TimerRelative, EFI_TIMER_PERIOD_SECONDS (120)); if (EFI_ERROR (Status)) { goto EXIT; } @@ -2285,11 +2315,11 @@ ScsiDiskDetectMedia ( // while (EFI_ERROR (gBS->CheckEvent (TimeoutEvt))) { Status = ScsiDiskTestUnitReady ( - ScsiDiskDevice, - &NeedRetry, - &SenseData, - &NumberOfSenseKeys - ); + ScsiDiskDevice, + &NeedRetry, + &SenseData, + &NumberOfSenseKeys + ); if (!EFI_ERROR (Status)) { Status = DetectMediaParsingSenseKeys ( ScsiDiskDevice, @@ -2328,8 +2358,8 @@ ScsiDiskDetectMedia ( // READ_CAPACITY command is not supported by any of the UFS WLUNs. // if (ScsiDiskDevice->DeviceType == EFI_SCSI_TYPE_WLUN) { - NeedReadCapacity = FALSE; - MustReadCapacity = FALSE; + NeedReadCapacity = FALSE; + MustReadCapacity = FALSE; ScsiDiskDevice->BlkIo.Media->MediaPresent = TRUE; } @@ -2391,17 +2421,17 @@ ScsiDiskDetectMedia ( } if (ScsiDiskDevice->BlkIo.Media->ReadOnly != OldMedia.ReadOnly) { - *MediaChange = TRUE; + *MediaChange = TRUE; ScsiDiskDevice->BlkIo.Media->MediaId += 1; } if (ScsiDiskDevice->BlkIo.Media->BlockSize != OldMedia.BlockSize) { - *MediaChange = TRUE; + *MediaChange = TRUE; ScsiDiskDevice->BlkIo.Media->MediaId += 1; } if (ScsiDiskDevice->BlkIo.Media->LastBlock != OldMedia.LastBlock) { - *MediaChange = TRUE; + *MediaChange = TRUE; ScsiDiskDevice->BlkIo.Media->MediaId += 1; } @@ -2425,10 +2455,10 @@ EXIT: if (TimeoutEvt != NULL) { gBS->CloseEvent (TimeoutEvt); } + return Status; } - /** Send out Inquiry command to Device. @@ -2441,40 +2471,40 @@ EXIT: **/ EFI_STATUS ScsiDiskInquiryDevice ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry ) { - UINT32 InquiryDataLength; - UINT8 SenseDataLength; - UINT8 HostAdapterStatus; - UINT8 TargetStatus; - EFI_SCSI_SENSE_DATA *SenseDataArray; - UINTN NumberOfSenseKeys; - EFI_STATUS Status; - UINT8 MaxRetry; - UINT8 Index; - EFI_SCSI_SUPPORTED_VPD_PAGES_VPD_PAGE *SupportedVpdPages; - EFI_SCSI_BLOCK_LIMITS_VPD_PAGE *BlockLimits; - UINTN PageLength; + UINT32 InquiryDataLength; + UINT8 SenseDataLength; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; + EFI_SCSI_SENSE_DATA *SenseDataArray; + UINTN NumberOfSenseKeys; + EFI_STATUS Status; + UINT8 MaxRetry; + UINT8 Index; + EFI_SCSI_SUPPORTED_VPD_PAGES_VPD_PAGE *SupportedVpdPages; + EFI_SCSI_BLOCK_LIMITS_VPD_PAGE *BlockLimits; + UINTN PageLength; InquiryDataLength = sizeof (EFI_SCSI_INQUIRY_DATA); SenseDataLength = 0; Status = ScsiInquiryCommand ( - ScsiDiskDevice->ScsiIo, - SCSI_DISK_TIMEOUT, - NULL, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - (VOID *) &(ScsiDiskDevice->InquiryData), - &InquiryDataLength, - FALSE - ); - // - // no need to check HostAdapterStatus and TargetStatus - // + ScsiDiskDevice->ScsiIo, + SCSI_DISK_TIMEOUT, + NULL, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + (VOID *)&(ScsiDiskDevice->InquiryData), + &InquiryDataLength, + FALSE + ); + // + // no need to check HostAdapterStatus and TargetStatus + // if ((Status == EFI_SUCCESS) || (Status == EFI_WARN_BUFFER_TOO_SMALL)) { ParseInquiryData (ScsiDiskDevice); @@ -2487,41 +2517,49 @@ ScsiDiskInquiryDevice ( *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + ZeroMem (SupportedVpdPages, sizeof (EFI_SCSI_SUPPORTED_VPD_PAGES_VPD_PAGE)); InquiryDataLength = sizeof (EFI_SCSI_SUPPORTED_VPD_PAGES_VPD_PAGE); SenseDataLength = 0; - Status = ScsiInquiryCommandEx ( - ScsiDiskDevice->ScsiIo, - SCSI_DISK_TIMEOUT, - NULL, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - (VOID *) SupportedVpdPages, - &InquiryDataLength, - TRUE, - EFI_SCSI_PAGE_CODE_SUPPORTED_VPD - ); + Status = ScsiInquiryCommandEx ( + ScsiDiskDevice->ScsiIo, + SCSI_DISK_TIMEOUT, + NULL, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + (VOID *)SupportedVpdPages, + &InquiryDataLength, + TRUE, + EFI_SCSI_PAGE_CODE_SUPPORTED_VPD + ); if (!EFI_ERROR (Status)) { PageLength = (SupportedVpdPages->PageLength2 << 8) - | SupportedVpdPages->PageLength1; + | SupportedVpdPages->PageLength1; // // Sanity checks for coping with broken devices // if (PageLength > sizeof SupportedVpdPages->SupportedVpdPageList) { - DEBUG ((DEBUG_WARN, + DEBUG (( + DEBUG_WARN, "%a: invalid PageLength (%u) in Supported VPD Pages page\n", - __FUNCTION__, (UINT32)PageLength)); + __FUNCTION__, + (UINT32)PageLength + )); PageLength = 0; } if ((PageLength > 0) && (SupportedVpdPages->SupportedVpdPageList[0] != - EFI_SCSI_PAGE_CODE_SUPPORTED_VPD)) { - DEBUG ((DEBUG_WARN, + EFI_SCSI_PAGE_CODE_SUPPORTED_VPD)) + { + DEBUG (( + DEBUG_WARN, "%a: Supported VPD Pages page doesn't start with code 0x%02x\n", - __FUNCTION__, EFI_SCSI_PAGE_CODE_SUPPORTED_VPD)); + __FUNCTION__, + EFI_SCSI_PAGE_CODE_SUPPORTED_VPD + )); PageLength = 0; } @@ -2534,11 +2572,15 @@ ScsiDiskInquiryDevice ( // if ((Index > 0) && (SupportedVpdPages->SupportedVpdPageList[Index] <= - SupportedVpdPages->SupportedVpdPageList[Index - 1])) { - DEBUG ((DEBUG_WARN, + SupportedVpdPages->SupportedVpdPageList[Index - 1])) + { + DEBUG (( + DEBUG_WARN, "%a: non-ascending code in Supported VPD Pages page @ %u\n", - __FUNCTION__, Index)); - Index = 0; + __FUNCTION__, + Index + )); + Index = 0; PageLength = 0; break; } @@ -2558,25 +2600,26 @@ ScsiDiskInquiryDevice ( *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + ZeroMem (BlockLimits, sizeof (EFI_SCSI_BLOCK_LIMITS_VPD_PAGE)); InquiryDataLength = sizeof (EFI_SCSI_BLOCK_LIMITS_VPD_PAGE); SenseDataLength = 0; - Status = ScsiInquiryCommandEx ( - ScsiDiskDevice->ScsiIo, - SCSI_DISK_TIMEOUT, - NULL, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - (VOID *) BlockLimits, - &InquiryDataLength, - TRUE, - EFI_SCSI_PAGE_CODE_BLOCK_LIMITS_VPD - ); + Status = ScsiInquiryCommandEx ( + ScsiDiskDevice->ScsiIo, + SCSI_DISK_TIMEOUT, + NULL, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + (VOID *)BlockLimits, + &InquiryDataLength, + TRUE, + EFI_SCSI_PAGE_CODE_BLOCK_LIMITS_VPD + ); if (!EFI_ERROR (Status)) { ScsiDiskDevice->BlkIo.Media->OptimalTransferLengthGranularity = (BlockLimits->OptimalTransferLengthGranularity2 << 8) | - BlockLimits->OptimalTransferLengthGranularity1; + BlockLimits->OptimalTransferLengthGranularity1; ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (BlockLimits->MaximumUnmapLbaCount4 << 24) | @@ -2622,15 +2665,14 @@ ScsiDiskInquiryDevice ( if (!EFI_ERROR (Status)) { return EFI_SUCCESS; - } else if (Status == EFI_NOT_READY) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if ((Status == EFI_INVALID_PARAMETER) || (Status == EFI_UNSUPPORTED)) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // go ahead to check HostAdapterStatus and TargetStatus // (EFI_TIMEOUT, EFI_DEVICE_ERROR) @@ -2641,9 +2683,9 @@ ScsiDiskInquiryDevice ( *NeedRetry = TRUE; return EFI_DEVICE_ERROR; } else if (Status == EFI_DEVICE_ERROR) { - // - // reset the scsi channel - // + // + // reset the scsi channel + // ScsiDiskDevice->ScsiIo->ResetBus (ScsiDiskDevice->ScsiIo); *NeedRetry = FALSE; return EFI_DEVICE_ERROR; @@ -2657,7 +2699,6 @@ ScsiDiskInquiryDevice ( ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if (Status == EFI_DEVICE_ERROR) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; @@ -2671,12 +2712,12 @@ ScsiDiskInquiryDevice ( MaxRetry = 3; for (Index = 0; Index < MaxRetry; Index++) { Status = ScsiDiskRequestSenseKeys ( - ScsiDiskDevice, - NeedRetry, - &SenseDataArray, - &NumberOfSenseKeys, - TRUE - ); + ScsiDiskDevice, + NeedRetry, + &SenseDataArray, + &NumberOfSenseKeys, + TRUE + ); if (!EFI_ERROR (Status)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; @@ -2686,6 +2727,7 @@ ScsiDiskInquiryDevice ( return EFI_DEVICE_ERROR; } } + // // ScsiDiskRequestSenseKeys() failed after several rounds of retry. // set *NeedRetry = FALSE to avoid the outside caller try again. @@ -2712,10 +2754,10 @@ ScsiDiskInquiryDevice ( **/ EFI_STATUS ScsiDiskTestUnitReady ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys ) { EFI_STATUS Status; @@ -2725,31 +2767,31 @@ ScsiDiskTestUnitReady ( UINT8 Index; UINT8 MaxRetry; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); - *NumberOfSenseKeys = 0; + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + *NumberOfSenseKeys = 0; // // Parameter 3 and 4: do not require sense data, retrieve it when needed. // Status = ScsiTestUnitReadyCommand ( - ScsiDiskDevice->ScsiIo, - SCSI_DISK_TIMEOUT, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus - ); + ScsiDiskDevice->ScsiIo, + SCSI_DISK_TIMEOUT, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus + ); // // no need to check HostAdapterStatus and TargetStatus // if (Status == EFI_NOT_READY) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if ((Status == EFI_INVALID_PARAMETER) || (Status == EFI_UNSUPPORTED)) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // go ahead to check HostAdapterStatus and TargetStatus(in case of EFI_DEVICE_ERROR) // @@ -2758,7 +2800,6 @@ ScsiDiskTestUnitReady ( if ((Status == EFI_TIMEOUT) || (Status == EFI_NOT_READY)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if (Status == EFI_DEVICE_ERROR) { // // reset the scsi channel @@ -2776,7 +2817,6 @@ ScsiDiskTestUnitReady ( ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if (Status == EFI_DEVICE_ERROR) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; @@ -2791,12 +2831,12 @@ ScsiDiskTestUnitReady ( MaxRetry = 3; for (Index = 0; Index < MaxRetry; Index++) { Status = ScsiDiskRequestSenseKeys ( - ScsiDiskDevice, - NeedRetry, - SenseDataArray, - NumberOfSenseKeys, - FALSE - ); + ScsiDiskDevice, + NeedRetry, + SenseDataArray, + NumberOfSenseKeys, + FALSE + ); if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } @@ -2805,6 +2845,7 @@ ScsiDiskTestUnitReady ( return EFI_DEVICE_ERROR; } } + // // ScsiDiskRequestSenseKeys() failed after several rounds of retry. // set *NeedRetry = FALSE to avoid the outside caller try again. @@ -2827,13 +2868,13 @@ ScsiDiskTestUnitReady ( **/ EFI_STATUS DetectMediaParsingSenseKeys ( - OUT SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN NumberOfSenseKeys, - OUT UINTN *Action + OUT SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN NumberOfSenseKeys, + OUT UINTN *Action ) { - BOOLEAN RetryLater; + BOOLEAN RetryLater; // // Default is to read capacity, unless.. @@ -2844,6 +2885,7 @@ DetectMediaParsingSenseKeys ( if (ScsiDiskDevice->BlkIo.Media->MediaPresent == TRUE) { *Action = ACTION_NO_ACTION; } + return EFI_SUCCESS; } @@ -2854,13 +2896,14 @@ DetectMediaParsingSenseKeys ( if (ScsiDiskDevice->BlkIo.Media->MediaPresent == TRUE) { *Action = ACTION_NO_ACTION; } + return EFI_SUCCESS; } if (ScsiDiskIsNoMedia (SenseData, NumberOfSenseKeys)) { ScsiDiskDevice->BlkIo.Media->MediaPresent = FALSE; ScsiDiskDevice->BlkIo.Media->LastBlock = 0; - *Action = ACTION_NO_ACTION; + *Action = ACTION_NO_ACTION; DEBUG ((DEBUG_VERBOSE, "ScsiDisk: ScsiDiskIsNoMedia\n")); return EFI_SUCCESS; } @@ -2895,6 +2938,7 @@ DetectMediaParsingSenseKeys ( DEBUG ((DEBUG_VERBOSE, "ScsiDisk: ScsiDiskDriveNotReady!\n")); return EFI_SUCCESS; } + *Action = ACTION_NO_ACTION; return EFI_DEVICE_ERROR; } @@ -2904,7 +2948,6 @@ DetectMediaParsingSenseKeys ( return EFI_SUCCESS; } - /** Send read capacity command to device and get the device parameter. @@ -2919,29 +2962,30 @@ DetectMediaParsingSenseKeys ( **/ EFI_STATUS ScsiDiskReadCapacity ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys ) { - UINT8 HostAdapterStatus; - UINT8 TargetStatus; - EFI_STATUS CommandStatus; - EFI_STATUS Status; - UINT8 Index; - UINT8 MaxRetry; - UINT8 SenseDataLength; - UINT32 DataLength10; - UINT32 DataLength16; - EFI_SCSI_DISK_CAPACITY_DATA *CapacityData10; - EFI_SCSI_DISK_CAPACITY_DATA16 *CapacityData16; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; + EFI_STATUS CommandStatus; + EFI_STATUS Status; + UINT8 Index; + UINT8 MaxRetry; + UINT8 SenseDataLength; + UINT32 DataLength10; + UINT32 DataLength16; + EFI_SCSI_DISK_CAPACITY_DATA *CapacityData10; + EFI_SCSI_DISK_CAPACITY_DATA16 *CapacityData16; CapacityData10 = AllocateAlignedBuffer (ScsiDiskDevice, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); if (CapacityData10 == NULL) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + CapacityData16 = AllocateAlignedBuffer (ScsiDiskDevice, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); if (CapacityData16 == NULL) { FreeAlignedBuffer (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); @@ -2949,14 +2993,14 @@ ScsiDiskReadCapacity ( return EFI_DEVICE_ERROR; } - SenseDataLength = 0; - DataLength10 = sizeof (EFI_SCSI_DISK_CAPACITY_DATA); - DataLength16 = sizeof (EFI_SCSI_DISK_CAPACITY_DATA16); + SenseDataLength = 0; + DataLength10 = sizeof (EFI_SCSI_DISK_CAPACITY_DATA); + DataLength16 = sizeof (EFI_SCSI_DISK_CAPACITY_DATA16); ZeroMem (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); ZeroMem (CapacityData16, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); - *NumberOfSenseKeys = 0; - *NeedRetry = FALSE; + *NumberOfSenseKeys = 0; + *NeedRetry = FALSE; // // submit Read Capacity(10) Command. If it returns capacity of FFFFFFFFh, @@ -2969,14 +3013,15 @@ ScsiDiskReadCapacity ( &SenseDataLength, &HostAdapterStatus, &TargetStatus, - (VOID *) CapacityData10, + (VOID *)CapacityData10, &DataLength10, FALSE ); ScsiDiskDevice->Cdb16Byte = FALSE; if ((!EFI_ERROR (CommandStatus)) && (CapacityData10->LastLba3 == 0xff) && (CapacityData10->LastLba2 == 0xff) && - (CapacityData10->LastLba1 == 0xff) && (CapacityData10->LastLba0 == 0xff)) { + (CapacityData10->LastLba1 == 0xff) && (CapacityData10->LastLba0 == 0xff)) + { // // use Read Capacity (16), Read (16) and Write (16) next when hard disk size > 2TB // @@ -2992,44 +3037,43 @@ ScsiDiskReadCapacity ( &SenseDataLength, &HostAdapterStatus, &TargetStatus, - (VOID *) CapacityData16, + (VOID *)CapacityData16, &DataLength16, FALSE ); } - // - // no need to check HostAdapterStatus and TargetStatus - // - if (CommandStatus == EFI_SUCCESS) { - GetMediaInfo (ScsiDiskDevice, CapacityData10, CapacityData16); - FreeAlignedBuffer (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); - FreeAlignedBuffer (CapacityData16, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); - return EFI_SUCCESS; - } - - FreeAlignedBuffer (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); - FreeAlignedBuffer (CapacityData16, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); - - if (CommandStatus == EFI_NOT_READY) { - *NeedRetry = TRUE; - return EFI_DEVICE_ERROR; - } else if ((CommandStatus == EFI_INVALID_PARAMETER) || (CommandStatus == EFI_UNSUPPORTED)) { - *NeedRetry = FALSE; - return EFI_DEVICE_ERROR; - } - - // - // go ahead to check HostAdapterStatus and TargetStatus - // (EFI_TIMEOUT, EFI_DEVICE_ERROR, EFI_WARN_BUFFER_TOO_SMALL) - // - - Status = CheckHostAdapterStatus (HostAdapterStatus); - if ((Status == EFI_TIMEOUT) || (Status == EFI_NOT_READY)) { - *NeedRetry = TRUE; - return EFI_DEVICE_ERROR; - - } else if (Status == EFI_DEVICE_ERROR) { + // + // no need to check HostAdapterStatus and TargetStatus + // + if (CommandStatus == EFI_SUCCESS) { + GetMediaInfo (ScsiDiskDevice, CapacityData10, CapacityData16); + FreeAlignedBuffer (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); + FreeAlignedBuffer (CapacityData16, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); + return EFI_SUCCESS; + } + + FreeAlignedBuffer (CapacityData10, sizeof (EFI_SCSI_DISK_CAPACITY_DATA)); + FreeAlignedBuffer (CapacityData16, sizeof (EFI_SCSI_DISK_CAPACITY_DATA16)); + + if (CommandStatus == EFI_NOT_READY) { + *NeedRetry = TRUE; + return EFI_DEVICE_ERROR; + } else if ((CommandStatus == EFI_INVALID_PARAMETER) || (CommandStatus == EFI_UNSUPPORTED)) { + *NeedRetry = FALSE; + return EFI_DEVICE_ERROR; + } + + // + // go ahead to check HostAdapterStatus and TargetStatus + // (EFI_TIMEOUT, EFI_DEVICE_ERROR, EFI_WARN_BUFFER_TOO_SMALL) + // + + Status = CheckHostAdapterStatus (HostAdapterStatus); + if ((Status == EFI_TIMEOUT) || (Status == EFI_NOT_READY)) { + *NeedRetry = TRUE; + return EFI_DEVICE_ERROR; + } else if (Status == EFI_DEVICE_ERROR) { // // reset the scsi channel // @@ -3046,7 +3090,6 @@ ScsiDiskReadCapacity ( ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); *NeedRetry = TRUE; return EFI_DEVICE_ERROR; - } else if (Status == EFI_DEVICE_ERROR) { *NeedRetry = FALSE; return EFI_DEVICE_ERROR; @@ -3059,14 +3102,13 @@ ScsiDiskReadCapacity ( // MaxRetry = 3; for (Index = 0; Index < MaxRetry; Index++) { - Status = ScsiDiskRequestSenseKeys ( - ScsiDiskDevice, - NeedRetry, - SenseDataArray, - NumberOfSenseKeys, - TRUE - ); + ScsiDiskDevice, + NeedRetry, + SenseDataArray, + NumberOfSenseKeys, + TRUE + ); if (!EFI_ERROR (Status)) { return EFI_SUCCESS; } @@ -3075,6 +3117,7 @@ ScsiDiskReadCapacity ( return EFI_DEVICE_ERROR; } } + // // ScsiDiskRequestSenseKeys() failed after several rounds of retry. // set *NeedRetry = FALSE to avoid the outside caller try again. @@ -3096,35 +3139,34 @@ ScsiDiskReadCapacity ( **/ EFI_STATUS CheckHostAdapterStatus ( - IN UINT8 HostAdapterStatus + IN UINT8 HostAdapterStatus ) { switch (HostAdapterStatus) { - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OK: - return EFI_SUCCESS; + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_OK: + return EFI_SUCCESS; - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_SELECTION_TIMEOUT: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_TIMEOUT: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_TIMEOUT_COMMAND: - return EFI_TIMEOUT; + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_SELECTION_TIMEOUT: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_TIMEOUT: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_TIMEOUT_COMMAND: + return EFI_TIMEOUT; - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_MESSAGE_REJECT: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_PARITY_ERROR: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_REQUEST_SENSE_FAILED: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_DATA_OVERRUN_UNDERRUN: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_BUS_RESET: - return EFI_NOT_READY; + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_MESSAGE_REJECT: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_PARITY_ERROR: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_REQUEST_SENSE_FAILED: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_DATA_OVERRUN_UNDERRUN: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_BUS_RESET: + return EFI_NOT_READY; - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_BUS_FREE: - case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_PHASE_ERROR: - return EFI_DEVICE_ERROR; + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_BUS_FREE: + case EFI_EXT_SCSI_STATUS_HOST_ADAPTER_PHASE_ERROR: + return EFI_DEVICE_ERROR; - default: - return EFI_SUCCESS; + default: + return EFI_SUCCESS; } } - /** Check the target status and re-interpret it in EFI_STATUS. @@ -3137,30 +3179,29 @@ CheckHostAdapterStatus ( **/ EFI_STATUS CheckTargetStatus ( - IN UINT8 TargetStatus + IN UINT8 TargetStatus ) { switch (TargetStatus) { - case EFI_EXT_SCSI_STATUS_TARGET_GOOD: - case EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION: - case EFI_EXT_SCSI_STATUS_TARGET_CONDITION_MET: - return EFI_SUCCESS; + case EFI_EXT_SCSI_STATUS_TARGET_GOOD: + case EFI_EXT_SCSI_STATUS_TARGET_CHECK_CONDITION: + case EFI_EXT_SCSI_STATUS_TARGET_CONDITION_MET: + return EFI_SUCCESS; - case EFI_EXT_SCSI_STATUS_TARGET_INTERMEDIATE: - case EFI_EXT_SCSI_STATUS_TARGET_INTERMEDIATE_CONDITION_MET: - case EFI_EXT_SCSI_STATUS_TARGET_BUSY: - case EFI_EXT_SCSI_STATUS_TARGET_TASK_SET_FULL: - return EFI_NOT_READY; + case EFI_EXT_SCSI_STATUS_TARGET_INTERMEDIATE: + case EFI_EXT_SCSI_STATUS_TARGET_INTERMEDIATE_CONDITION_MET: + case EFI_EXT_SCSI_STATUS_TARGET_BUSY: + case EFI_EXT_SCSI_STATUS_TARGET_TASK_SET_FULL: + return EFI_NOT_READY; - case EFI_EXT_SCSI_STATUS_TARGET_RESERVATION_CONFLICT: - return EFI_DEVICE_ERROR; + case EFI_EXT_SCSI_STATUS_TARGET_RESERVATION_CONFLICT: + return EFI_DEVICE_ERROR; - default: - return EFI_SUCCESS; + default: + return EFI_SUCCESS; } } - /** Retrieve all sense keys from the device. @@ -3180,33 +3221,33 @@ CheckTargetStatus ( **/ EFI_STATUS ScsiDiskRequestSenseKeys ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys, - IN BOOLEAN AskResetIfError + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys, + IN BOOLEAN AskResetIfError ) { - EFI_SCSI_SENSE_DATA *PtrSenseData; - UINT8 SenseDataLength; - BOOLEAN SenseReq; - EFI_STATUS Status; - EFI_STATUS FallStatus; - UINT8 HostAdapterStatus; - UINT8 TargetStatus; + EFI_SCSI_SENSE_DATA *PtrSenseData; + UINT8 SenseDataLength; + BOOLEAN SenseReq; + EFI_STATUS Status; + EFI_STATUS FallStatus; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; FallStatus = EFI_SUCCESS; - SenseDataLength = (UINT8) sizeof (EFI_SCSI_SENSE_DATA); + SenseDataLength = (UINT8)sizeof (EFI_SCSI_SENSE_DATA); ZeroMem ( ScsiDiskDevice->SenseData, sizeof (EFI_SCSI_SENSE_DATA) * (ScsiDiskDevice->SenseDataNumber) ); - *NumberOfSenseKeys = 0; - *SenseDataArray = ScsiDiskDevice->SenseData; - Status = EFI_SUCCESS; - PtrSenseData = AllocateAlignedBuffer (ScsiDiskDevice, sizeof (EFI_SCSI_SENSE_DATA)); + *NumberOfSenseKeys = 0; + *SenseDataArray = ScsiDiskDevice->SenseData; + Status = EFI_SUCCESS; + PtrSenseData = AllocateAlignedBuffer (ScsiDiskDevice, sizeof (EFI_SCSI_SENSE_DATA)); if (PtrSenseData == NULL) { return EFI_DEVICE_ERROR; } @@ -3214,36 +3255,33 @@ ScsiDiskRequestSenseKeys ( for (SenseReq = TRUE; SenseReq;) { ZeroMem (PtrSenseData, sizeof (EFI_SCSI_SENSE_DATA)); Status = ScsiRequestSenseCommand ( - ScsiDiskDevice->ScsiIo, - SCSI_DISK_TIMEOUT, - PtrSenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus - ); - if ((Status == EFI_SUCCESS) || (Status == EFI_WARN_BUFFER_TOO_SMALL)) { - FallStatus = EFI_SUCCESS; - - } else if ((Status == EFI_TIMEOUT) || (Status == EFI_NOT_READY)) { - *NeedRetry = TRUE; - FallStatus = EFI_DEVICE_ERROR; - - } else if ((Status == EFI_INVALID_PARAMETER) || (Status == EFI_UNSUPPORTED)) { - *NeedRetry = FALSE; - FallStatus = EFI_DEVICE_ERROR; - - } else if (Status == EFI_DEVICE_ERROR) { - if (AskResetIfError) { - ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); - } + ScsiDiskDevice->ScsiIo, + SCSI_DISK_TIMEOUT, + PtrSenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus + ); + if ((Status == EFI_SUCCESS) || (Status == EFI_WARN_BUFFER_TOO_SMALL)) { + FallStatus = EFI_SUCCESS; + } else if ((Status == EFI_TIMEOUT) || (Status == EFI_NOT_READY)) { + *NeedRetry = TRUE; + FallStatus = EFI_DEVICE_ERROR; + } else if ((Status == EFI_INVALID_PARAMETER) || (Status == EFI_UNSUPPORTED)) { + *NeedRetry = FALSE; + FallStatus = EFI_DEVICE_ERROR; + } else if (Status == EFI_DEVICE_ERROR) { + if (AskResetIfError) { + ScsiDiskDevice->ScsiIo->ResetDevice (ScsiDiskDevice->ScsiIo); + } - FallStatus = EFI_DEVICE_ERROR; + FallStatus = EFI_DEVICE_ERROR; } if (EFI_ERROR (FallStatus)) { if (*NumberOfSenseKeys != 0) { *NeedRetry = FALSE; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; goto EXIT; } else { Status = EFI_DEVICE_ERROR; @@ -3259,7 +3297,8 @@ ScsiDiskRequestSenseKeys ( // skip the loop. // if ((PtrSenseData->Sense_Key == EFI_SCSI_SK_NO_SENSE) || - (*NumberOfSenseKeys == ScsiDiskDevice->SenseDataNumber)) { + (*NumberOfSenseKeys == ScsiDiskDevice->SenseDataNumber)) + { SenseReq = FALSE; } } @@ -3269,7 +3308,6 @@ EXIT: return Status; } - /** Get information from media read capacity command. @@ -3285,25 +3323,25 @@ GetMediaInfo ( IN EFI_SCSI_DISK_CAPACITY_DATA16 *Capacity16 ) { - UINT8 *Ptr; + UINT8 *Ptr; if (!ScsiDiskDevice->Cdb16Byte) { - ScsiDiskDevice->BlkIo.Media->LastBlock = ((UINT32) Capacity10->LastLba3 << 24) | - (Capacity10->LastLba2 << 16) | - (Capacity10->LastLba1 << 8) | - Capacity10->LastLba0; + ScsiDiskDevice->BlkIo.Media->LastBlock = ((UINT32)Capacity10->LastLba3 << 24) | + (Capacity10->LastLba2 << 16) | + (Capacity10->LastLba1 << 8) | + Capacity10->LastLba0; ScsiDiskDevice->BlkIo.Media->BlockSize = (Capacity10->BlockSize3 << 24) | (Capacity10->BlockSize2 << 16) | (Capacity10->BlockSize1 << 8) | - Capacity10->BlockSize0; - ScsiDiskDevice->BlkIo.Media->LowestAlignedLba = 0; - ScsiDiskDevice->BlkIo.Media->LogicalBlocksPerPhysicalBlock = 0; + Capacity10->BlockSize0; + ScsiDiskDevice->BlkIo.Media->LowestAlignedLba = 0; + ScsiDiskDevice->BlkIo.Media->LogicalBlocksPerPhysicalBlock = 0; if (!ScsiDiskDevice->BlockLimitsVpdSupported) { - ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32) ScsiDiskDevice->BlkIo.Media->LastBlock; + ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32)ScsiDiskDevice->BlkIo.Media->LastBlock; } } else { - Ptr = (UINT8*)&ScsiDiskDevice->BlkIo.Media->LastBlock; + Ptr = (UINT8 *)&ScsiDiskDevice->BlkIo.Media->LastBlock; *Ptr++ = Capacity16->LastLba0; *Ptr++ = Capacity16->LastLba1; *Ptr++ = Capacity16->LastLba2; @@ -3316,16 +3354,16 @@ GetMediaInfo ( ScsiDiskDevice->BlkIo.Media->BlockSize = (Capacity16->BlockSize3 << 24) | (Capacity16->BlockSize2 << 16) | (Capacity16->BlockSize1 << 8) | - Capacity16->BlockSize0; + Capacity16->BlockSize0; ScsiDiskDevice->BlkIo.Media->LowestAlignedLba = (Capacity16->LowestAlignLogic2 << 8) | - Capacity16->LowestAlignLogic1; - ScsiDiskDevice->BlkIo.Media->LogicalBlocksPerPhysicalBlock = (1 << Capacity16->LogicPerPhysical); + Capacity16->LowestAlignLogic1; + ScsiDiskDevice->BlkIo.Media->LogicalBlocksPerPhysicalBlock = (1 << Capacity16->LogicPerPhysical); if (!ScsiDiskDevice->BlockLimitsVpdSupported) { - if (ScsiDiskDevice->BlkIo.Media->LastBlock > (UINT32) -1) { - ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32) -1; + if (ScsiDiskDevice->BlkIo.Media->LastBlock > (UINT32)-1) { + ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32)-1; } else { - ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32) ScsiDiskDevice->BlkIo.Media->LastBlock; + ScsiDiskDevice->UnmapInfo.MaxLbaCnt = (UINT32)ScsiDiskDevice->BlkIo.Media->LastBlock; } } } @@ -3341,11 +3379,11 @@ GetMediaInfo ( **/ VOID ParseInquiryData ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice + IN OUT SCSI_DISK_DEV *ScsiDiskDevice ) { - ScsiDiskDevice->FixedDevice = (BOOLEAN) ((ScsiDiskDevice->InquiryData.Rmb == 1) ? 0 : 1); - ScsiDiskDevice->BlkIoMedia.RemovableMedia = (BOOLEAN) (!ScsiDiskDevice->FixedDevice); + ScsiDiskDevice->FixedDevice = (BOOLEAN)((ScsiDiskDevice->InquiryData.Rmb == 1) ? 0 : 1); + ScsiDiskDevice->BlkIoMedia.RemovableMedia = (BOOLEAN)(!ScsiDiskDevice->FixedDevice); } /** @@ -3362,48 +3400,47 @@ ParseInquiryData ( **/ EFI_STATUS ScsiDiskReadSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks ) { - UINTN BlocksRemaining; - UINT8 *PtrBuffer; - UINT32 BlockSize; - UINT32 ByteCount; - UINT32 MaxBlock; - UINT32 SectorCount; - UINT32 NextSectorCount; - UINT64 Timeout; - EFI_STATUS Status; - UINT8 Index; - UINT8 MaxRetry; - BOOLEAN NeedRetry; + UINTN BlocksRemaining; + UINT8 *PtrBuffer; + UINT32 BlockSize; + UINT32 ByteCount; + UINT32 MaxBlock; + UINT32 SectorCount; + UINT32 NextSectorCount; + UINT64 Timeout; + EFI_STATUS Status; + UINT8 Index; + UINT8 MaxRetry; + BOOLEAN NeedRetry; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; - BlocksRemaining = NumberOfBlocks; - BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; + BlocksRemaining = NumberOfBlocks; + BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; // // limit the data bytes that can be transferred by one Read(10) or Read(16) Command // if (!ScsiDiskDevice->Cdb16Byte) { - MaxBlock = 0xFFFF; + MaxBlock = 0xFFFF; } else { - MaxBlock = 0xFFFFFFFF; + MaxBlock = 0xFFFFFFFF; } PtrBuffer = Buffer; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { if (!ScsiDiskDevice->Cdb16Byte) { - SectorCount = (UINT16) BlocksRemaining; + SectorCount = (UINT16)BlocksRemaining; } else { - SectorCount = (UINT32) BlocksRemaining; + SectorCount = (UINT32)BlocksRemaining; } } else { SectorCount = MaxBlock; @@ -3442,31 +3479,32 @@ ScsiDiskReadSectors ( // to follow ATA spec in which it mentioned that the device may take up to 30s to respond // commands in the Standby/Idle mode. // - Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); + Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); - MaxRetry = 2; + MaxRetry = 2; for (Index = 0; Index < MaxRetry; Index++) { if (!ScsiDiskDevice->Cdb16Byte) { Status = ScsiDiskRead10 ( - ScsiDiskDevice, - &NeedRetry, - Timeout, - PtrBuffer, - &ByteCount, - (UINT32) Lba, - SectorCount - ); + ScsiDiskDevice, + &NeedRetry, + Timeout, + PtrBuffer, + &ByteCount, + (UINT32)Lba, + SectorCount + ); } else { Status = ScsiDiskRead16 ( - ScsiDiskDevice, - &NeedRetry, - Timeout, - PtrBuffer, - &ByteCount, - Lba, - SectorCount - ); + ScsiDiskDevice, + &NeedRetry, + Timeout, + PtrBuffer, + &ByteCount, + Lba, + SectorCount + ); } + if (!EFI_ERROR (Status)) { break; } @@ -3505,8 +3543,8 @@ ScsiDiskReadSectors ( // SectorCount = ByteCount / BlockSize; - Lba += SectorCount; - PtrBuffer = PtrBuffer + SectorCount * BlockSize; + Lba += SectorCount; + PtrBuffer = PtrBuffer + SectorCount * BlockSize; BlocksRemaining -= SectorCount; } @@ -3527,48 +3565,47 @@ ScsiDiskReadSectors ( **/ EFI_STATUS ScsiDiskWriteSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks ) { - UINTN BlocksRemaining; - UINT8 *PtrBuffer; - UINT32 BlockSize; - UINT32 ByteCount; - UINT32 MaxBlock; - UINT32 SectorCount; - UINT32 NextSectorCount; - UINT64 Timeout; - EFI_STATUS Status; - UINT8 Index; - UINT8 MaxRetry; - BOOLEAN NeedRetry; + UINTN BlocksRemaining; + UINT8 *PtrBuffer; + UINT32 BlockSize; + UINT32 ByteCount; + UINT32 MaxBlock; + UINT32 SectorCount; + UINT32 NextSectorCount; + UINT64 Timeout; + EFI_STATUS Status; + UINT8 Index; + UINT8 MaxRetry; + BOOLEAN NeedRetry; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; - BlocksRemaining = NumberOfBlocks; - BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; + BlocksRemaining = NumberOfBlocks; + BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; // // limit the data bytes that can be transferred by one Read(10) or Read(16) Command // if (!ScsiDiskDevice->Cdb16Byte) { - MaxBlock = 0xFFFF; + MaxBlock = 0xFFFF; } else { - MaxBlock = 0xFFFFFFFF; + MaxBlock = 0xFFFFFFFF; } PtrBuffer = Buffer; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { if (!ScsiDiskDevice->Cdb16Byte) { - SectorCount = (UINT16) BlocksRemaining; + SectorCount = (UINT16)BlocksRemaining; } else { - SectorCount = (UINT32) BlocksRemaining; + SectorCount = (UINT32)BlocksRemaining; } } else { SectorCount = MaxBlock; @@ -3607,30 +3644,31 @@ ScsiDiskWriteSectors ( // to follow ATA spec in which it mentioned that the device may take up to 30s to respond // commands in the Standby/Idle mode. // - Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); - MaxRetry = 2; + Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); + MaxRetry = 2; for (Index = 0; Index < MaxRetry; Index++) { if (!ScsiDiskDevice->Cdb16Byte) { Status = ScsiDiskWrite10 ( - ScsiDiskDevice, - &NeedRetry, - Timeout, - PtrBuffer, - &ByteCount, - (UINT32) Lba, - SectorCount - ); + ScsiDiskDevice, + &NeedRetry, + Timeout, + PtrBuffer, + &ByteCount, + (UINT32)Lba, + SectorCount + ); } else { Status = ScsiDiskWrite16 ( - ScsiDiskDevice, - &NeedRetry, - Timeout, - PtrBuffer, - &ByteCount, - Lba, - SectorCount - ); - } + ScsiDiskDevice, + &NeedRetry, + Timeout, + PtrBuffer, + &ByteCount, + Lba, + SectorCount + ); + } + if (!EFI_ERROR (Status)) { break; } @@ -3663,13 +3701,14 @@ ScsiDiskWriteSectors ( if ((Index == MaxRetry) && (Status != EFI_SUCCESS)) { return EFI_DEVICE_ERROR; } + // // actual transferred sectors // SectorCount = ByteCount / BlockSize; - Lba += SectorCount; - PtrBuffer = PtrBuffer + SectorCount * BlockSize; + Lba += SectorCount; + PtrBuffer = PtrBuffer + SectorCount * BlockSize; BlocksRemaining -= SectorCount; } @@ -3693,23 +3732,23 @@ ScsiDiskWriteSectors ( **/ EFI_STATUS ScsiDiskAsyncReadSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - UINTN BlocksRemaining; - UINT8 *PtrBuffer; - UINT32 BlockSize; - UINT32 ByteCount; - UINT32 MaxBlock; - UINT32 SectorCount; - UINT64 Timeout; - SCSI_BLKIO2_REQUEST *BlkIo2Req; - EFI_STATUS Status; - EFI_TPL OldTpl; + UINTN BlocksRemaining; + UINT8 *PtrBuffer; + UINT32 BlockSize; + UINT32 ByteCount; + UINT32 MaxBlock; + UINT32 SectorCount; + UINT64 Timeout; + SCSI_BLKIO2_REQUEST *BlkIo2Req; + EFI_STATUS Status; + EFI_TPL OldTpl; if ((Token == NULL) || (Token->Event == NULL)) { return EFI_INVALID_PARAMETER; @@ -3720,7 +3759,7 @@ ScsiDiskAsyncReadSectors ( return EFI_OUT_OF_RESOURCES; } - BlkIo2Req->Token = Token; + BlkIo2Req->Token = Token; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&ScsiDiskDevice->AsyncTaskQueue, &BlkIo2Req->Link); @@ -3728,30 +3767,29 @@ ScsiDiskAsyncReadSectors ( InitializeListHead (&BlkIo2Req->ScsiRWQueue); - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; - BlocksRemaining = NumberOfBlocks; - BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; + BlocksRemaining = NumberOfBlocks; + BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; // // Limit the data bytes that can be transferred by one Read(10) or Read(16) // Command // if (!ScsiDiskDevice->Cdb16Byte) { - MaxBlock = 0xFFFF; + MaxBlock = 0xFFFF; } else { - MaxBlock = 0xFFFFFFFF; + MaxBlock = 0xFFFFFFFF; } PtrBuffer = Buffer; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { if (!ScsiDiskDevice->Cdb16Byte) { - SectorCount = (UINT16) BlocksRemaining; + SectorCount = (UINT16)BlocksRemaining; } else { - SectorCount = (UINT32) BlocksRemaining; + SectorCount = (UINT32)BlocksRemaining; } } else { SectorCount = MaxBlock; @@ -3791,7 +3829,7 @@ ScsiDiskAsyncReadSectors ( // 30s is added to follow ATA spec in which it mentioned that the device // may take up to 30s to respond commands in the Standby/Idle mode. // - Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); + Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); if (!ScsiDiskDevice->Cdb16Byte) { Status = ScsiDiskAsyncRead10 ( @@ -3800,7 +3838,7 @@ ScsiDiskAsyncReadSectors ( 0, PtrBuffer, ByteCount, - (UINT32) Lba, + (UINT32)Lba, SectorCount, BlkIo2Req, Token @@ -3818,6 +3856,7 @@ ScsiDiskAsyncReadSectors ( Token ); } + if (EFI_ERROR (Status)) { // // Some devices will return EFI_DEVICE_ERROR or EFI_TIMEOUT when the data @@ -3868,8 +3907,8 @@ ScsiDiskAsyncReadSectors ( // SectorCount = ByteCount / BlockSize; - Lba += SectorCount; - PtrBuffer = PtrBuffer + SectorCount * BlockSize; + Lba += SectorCount; + PtrBuffer = PtrBuffer + SectorCount * BlockSize; BlocksRemaining -= SectorCount; } @@ -3887,6 +3926,7 @@ Done: gBS->SignalEvent (Token->Event); } + gBS->RestoreTPL (OldTpl); } @@ -3910,23 +3950,23 @@ Done: **/ EFI_STATUS ScsiDiskAsyncWriteSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - UINTN BlocksRemaining; - UINT8 *PtrBuffer; - UINT32 BlockSize; - UINT32 ByteCount; - UINT32 MaxBlock; - UINT32 SectorCount; - UINT64 Timeout; - SCSI_BLKIO2_REQUEST *BlkIo2Req; - EFI_STATUS Status; - EFI_TPL OldTpl; + UINTN BlocksRemaining; + UINT8 *PtrBuffer; + UINT32 BlockSize; + UINT32 ByteCount; + UINT32 MaxBlock; + UINT32 SectorCount; + UINT64 Timeout; + SCSI_BLKIO2_REQUEST *BlkIo2Req; + EFI_STATUS Status; + EFI_TPL OldTpl; if ((Token == NULL) || (Token->Event == NULL)) { return EFI_INVALID_PARAMETER; @@ -3937,7 +3977,7 @@ ScsiDiskAsyncWriteSectors ( return EFI_OUT_OF_RESOURCES; } - BlkIo2Req->Token = Token; + BlkIo2Req->Token = Token; OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&ScsiDiskDevice->AsyncTaskQueue, &BlkIo2Req->Link); @@ -3945,30 +3985,29 @@ ScsiDiskAsyncWriteSectors ( InitializeListHead (&BlkIo2Req->ScsiRWQueue); - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; - BlocksRemaining = NumberOfBlocks; - BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; + BlocksRemaining = NumberOfBlocks; + BlockSize = ScsiDiskDevice->BlkIo.Media->BlockSize; // // Limit the data bytes that can be transferred by one Read(10) or Read(16) // Command // if (!ScsiDiskDevice->Cdb16Byte) { - MaxBlock = 0xFFFF; + MaxBlock = 0xFFFF; } else { - MaxBlock = 0xFFFFFFFF; + MaxBlock = 0xFFFFFFFF; } PtrBuffer = Buffer; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { if (!ScsiDiskDevice->Cdb16Byte) { - SectorCount = (UINT16) BlocksRemaining; + SectorCount = (UINT16)BlocksRemaining; } else { - SectorCount = (UINT32) BlocksRemaining; + SectorCount = (UINT32)BlocksRemaining; } } else { SectorCount = MaxBlock; @@ -4008,7 +4047,7 @@ ScsiDiskAsyncWriteSectors ( // 30s is added to follow ATA spec in which it mentioned that the device // may take up to 30s to respond commands in the Standby/Idle mode. // - Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); + Timeout = EFI_TIMER_PERIOD_SECONDS (ByteCount / 2100000 + 31); if (!ScsiDiskDevice->Cdb16Byte) { Status = ScsiDiskAsyncWrite10 ( @@ -4017,7 +4056,7 @@ ScsiDiskAsyncWriteSectors ( 0, PtrBuffer, ByteCount, - (UINT32) Lba, + (UINT32)Lba, SectorCount, BlkIo2Req, Token @@ -4035,6 +4074,7 @@ ScsiDiskAsyncWriteSectors ( Token ); } + if (EFI_ERROR (Status)) { // // Some devices will return EFI_DEVICE_ERROR or EFI_TIMEOUT when the data @@ -4085,8 +4125,8 @@ ScsiDiskAsyncWriteSectors ( // SectorCount = ByteCount / BlockSize; - Lba += SectorCount; - PtrBuffer = PtrBuffer + SectorCount * BlockSize; + Lba += SectorCount; + PtrBuffer = PtrBuffer + SectorCount * BlockSize; BlocksRemaining -= SectorCount; } @@ -4104,13 +4144,13 @@ Done: gBS->SignalEvent (Token->Event); } + gBS->RestoreTPL (OldTpl); } return Status; } - /** Submit Read(10) command. @@ -4126,13 +4166,13 @@ Done: **/ EFI_STATUS ScsiDiskRead10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - OUT UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + OUT UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount ) { UINT8 SenseDataLength; @@ -4151,23 +4191,23 @@ ScsiDiskRead10 ( // try again till the operation succeeds or fails with one sector transfer length. // BackOff: - *NeedRetry = FALSE; - Action = ACTION_NO_ACTION; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); - ReturnStatus = ScsiRead10Command ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - DataBuffer, - DataLength, - StartLba, - SectorCount - ); + *NeedRetry = FALSE; + Action = ACTION_NO_ACTION; + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + ReturnStatus = ScsiRead10Command ( + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + DataBuffer, + DataLength, + StartLba, + SectorCount + ); - if (ReturnStatus == EFI_NOT_READY || ReturnStatus == EFI_BAD_BUFFER_SIZE) { + if ((ReturnStatus == EFI_NOT_READY) || (ReturnStatus == EFI_BAD_BUFFER_SIZE)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; } else if ((ReturnStatus == EFI_INVALID_PARAMETER) || (ReturnStatus == EFI_UNSUPPORTED)) { @@ -4219,11 +4259,12 @@ BackOff: *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // Try again with half length if the sense data shows we need to retry. // SectorCount >>= 1; - *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; + *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; goto BackOff; } else { *NeedRetry = FALSE; @@ -4234,7 +4275,6 @@ BackOff: return ReturnStatus; } - /** Submit Write(10) Command. @@ -4251,13 +4291,13 @@ BackOff: **/ EFI_STATUS ScsiDiskWrite10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - IN UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + IN UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount ) { EFI_STATUS Status; @@ -4276,22 +4316,22 @@ ScsiDiskWrite10 ( // try again till the operation succeeds or fails with one sector transfer length. // BackOff: - *NeedRetry = FALSE; - Action = ACTION_NO_ACTION; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); - ReturnStatus = ScsiWrite10Command ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - DataBuffer, - DataLength, - StartLba, - SectorCount - ); - if (ReturnStatus == EFI_NOT_READY || ReturnStatus == EFI_BAD_BUFFER_SIZE) { + *NeedRetry = FALSE; + Action = ACTION_NO_ACTION; + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + ReturnStatus = ScsiWrite10Command ( + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + DataBuffer, + DataLength, + StartLba, + SectorCount + ); + if ((ReturnStatus == EFI_NOT_READY) || (ReturnStatus == EFI_BAD_BUFFER_SIZE)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; } else if ((ReturnStatus == EFI_INVALID_PARAMETER) || (ReturnStatus == EFI_UNSUPPORTED)) { @@ -4343,11 +4383,12 @@ BackOff: *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // Try again with half length if the sense data shows we need to retry. // SectorCount >>= 1; - *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; + *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; goto BackOff; } else { *NeedRetry = FALSE; @@ -4358,7 +4399,6 @@ BackOff: return ReturnStatus; } - /** Submit Read(16) command. @@ -4374,13 +4414,13 @@ BackOff: **/ EFI_STATUS ScsiDiskRead16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - OUT UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + OUT UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount ) { UINT8 SenseDataLength; @@ -4399,22 +4439,22 @@ ScsiDiskRead16 ( // try again till the operation succeeds or fails with one sector transfer length. // BackOff: - *NeedRetry = FALSE; - Action = ACTION_NO_ACTION; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); - ReturnStatus = ScsiRead16Command ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - DataBuffer, - DataLength, - StartLba, - SectorCount - ); - if (ReturnStatus == EFI_NOT_READY || ReturnStatus == EFI_BAD_BUFFER_SIZE) { + *NeedRetry = FALSE; + Action = ACTION_NO_ACTION; + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + ReturnStatus = ScsiRead16Command ( + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + DataBuffer, + DataLength, + StartLba, + SectorCount + ); + if ((ReturnStatus == EFI_NOT_READY) || (ReturnStatus == EFI_BAD_BUFFER_SIZE)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; } else if ((ReturnStatus == EFI_INVALID_PARAMETER) || (ReturnStatus == EFI_UNSUPPORTED)) { @@ -4466,11 +4506,12 @@ BackOff: *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // Try again with half length if the sense data shows we need to retry. // SectorCount >>= 1; - *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; + *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; goto BackOff; } else { *NeedRetry = FALSE; @@ -4481,7 +4522,6 @@ BackOff: return ReturnStatus; } - /** Submit Write(16) Command. @@ -4498,13 +4538,13 @@ BackOff: **/ EFI_STATUS ScsiDiskWrite16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - IN UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + IN UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount ) { EFI_STATUS Status; @@ -4523,22 +4563,22 @@ ScsiDiskWrite16 ( // try again till the operation succeeds or fails with one sector transfer length. // BackOff: - *NeedRetry = FALSE; - Action = ACTION_NO_ACTION; - SenseDataLength = (UINT8) (ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); - ReturnStatus = ScsiWrite16Command ( - ScsiDiskDevice->ScsiIo, - Timeout, - ScsiDiskDevice->SenseData, - &SenseDataLength, - &HostAdapterStatus, - &TargetStatus, - DataBuffer, - DataLength, - StartLba, - SectorCount - ); - if (ReturnStatus == EFI_NOT_READY || ReturnStatus == EFI_BAD_BUFFER_SIZE) { + *NeedRetry = FALSE; + Action = ACTION_NO_ACTION; + SenseDataLength = (UINT8)(ScsiDiskDevice->SenseDataNumber * sizeof (EFI_SCSI_SENSE_DATA)); + ReturnStatus = ScsiWrite16Command ( + ScsiDiskDevice->ScsiIo, + Timeout, + ScsiDiskDevice->SenseData, + &SenseDataLength, + &HostAdapterStatus, + &TargetStatus, + DataBuffer, + DataLength, + StartLba, + SectorCount + ); + if ((ReturnStatus == EFI_NOT_READY) || (ReturnStatus == EFI_BAD_BUFFER_SIZE)) { *NeedRetry = TRUE; return EFI_DEVICE_ERROR; } else if ((ReturnStatus == EFI_INVALID_PARAMETER) || (ReturnStatus == EFI_UNSUPPORTED)) { @@ -4590,11 +4630,12 @@ BackOff: *NeedRetry = FALSE; return EFI_DEVICE_ERROR; } + // // Try again with half length if the sense data shows we need to retry. // SectorCount >>= 1; - *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; + *DataLength = SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; goto BackOff; } else { *NeedRetry = FALSE; @@ -4605,7 +4646,6 @@ BackOff: return ReturnStatus; } - /** Internal helper notify function in which determine whether retry of a SCSI Read/Write command is needed and signal the event passed from Block I/O(2) if @@ -4622,23 +4662,23 @@ ScsiDiskNotify ( IN VOID *Context ) { - EFI_STATUS Status; - SCSI_ASYNC_RW_REQUEST *Request; - SCSI_DISK_DEV *ScsiDiskDevice; - EFI_BLOCK_IO2_TOKEN *Token; - UINTN Action; - UINT32 OldDataLength; - UINT32 OldSectorCount; - UINT8 MaxRetry; + EFI_STATUS Status; + SCSI_ASYNC_RW_REQUEST *Request; + SCSI_DISK_DEV *ScsiDiskDevice; + EFI_BLOCK_IO2_TOKEN *Token; + UINTN Action; + UINT32 OldDataLength; + UINT32 OldSectorCount; + UINT8 MaxRetry; gBS->CloseEvent (Event); - Request = (SCSI_ASYNC_RW_REQUEST *) Context; - ScsiDiskDevice = Request->ScsiDiskDevice; - Token = Request->BlkIo2Req->Token; - OldDataLength = Request->DataLength; - OldSectorCount = Request->SectorCount; - MaxRetry = 2; + Request = (SCSI_ASYNC_RW_REQUEST *)Context; + ScsiDiskDevice = Request->ScsiDiskDevice; + Token = Request->BlkIo2Req->Token; + OldDataLength = Request->DataLength; + OldSectorCount = Request->SectorCount; + MaxRetry = 2; // // If previous sub-tasks already fails, no need to process this sub-task. @@ -4710,13 +4750,14 @@ ScsiDiskNotify ( Token->TransactionStatus = EFI_DEVICE_ERROR; goto Exit; } + // // Try again with two half length request if the sense data shows we need // to retry. // Request->SectorCount >>= 1; - Request->DataLength = Request->SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; - Request->TimesRetry = 0; + Request->DataLength = Request->SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize; + Request->TimesRetry = 0; goto Retry; } else { @@ -4742,7 +4783,7 @@ Retry: Request->TimesRetry, Request->InBuffer, Request->DataLength, - (UINT32) Request->StartLba, + (UINT32)Request->StartLba, Request->SectorCount, Request->BlkIo2Req, Token @@ -4776,7 +4817,7 @@ Retry: 0, Request->InBuffer + Request->SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize, OldDataLength - Request->DataLength, - (UINT32) Request->StartLba + Request->SectorCount, + (UINT32)Request->StartLba + Request->SectorCount, OldSectorCount - Request->SectorCount, Request->BlkIo2Req, Token @@ -4794,6 +4835,7 @@ Retry: Token ); } + if (EFI_ERROR (Status)) { Token->TransactionStatus = EFI_DEVICE_ERROR; goto Exit; @@ -4810,7 +4852,7 @@ Retry: Request->TimesRetry, Request->OutBuffer, Request->DataLength, - (UINT32) Request->StartLba, + (UINT32)Request->StartLba, Request->SectorCount, Request->BlkIo2Req, Token @@ -4844,7 +4886,7 @@ Retry: 0, Request->OutBuffer + Request->SectorCount * ScsiDiskDevice->BlkIo.Media->BlockSize, OldDataLength - Request->DataLength, - (UINT32) Request->StartLba + Request->SectorCount, + (UINT32)Request->StartLba + Request->SectorCount, OldSectorCount - Request->SectorCount, Request->BlkIo2Req, Token @@ -4862,6 +4904,7 @@ Retry: Token ); } + if (EFI_ERROR (Status)) { Token->TransactionStatus = EFI_DEVICE_ERROR; goto Exit; @@ -4872,7 +4915,8 @@ Retry: Exit: RemoveEntryList (&Request->Link); if ((IsListEmpty (&Request->BlkIo2Req->ScsiRWQueue)) && - (Request->BlkIo2Req->LastScsiRW)) { + (Request->BlkIo2Req->LastScsiRW)) + { // // The last SCSI R/W command of a BlockIo2 request completes // @@ -4885,7 +4929,6 @@ Exit: FreePool (Request); } - /** Submit Async Read(10) command. @@ -4908,21 +4951,21 @@ Exit: **/ EFI_STATUS ScsiDiskAsyncRead10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - OUT UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + OUT UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - SCSI_ASYNC_RW_REQUEST *Request; - EFI_EVENT AsyncIoEvent; - EFI_TPL OldTpl; + EFI_STATUS Status; + SCSI_ASYNC_RW_REQUEST *Request; + EFI_EVENT AsyncIoEvent; + EFI_TPL OldTpl; AsyncIoEvent = NULL; @@ -4935,21 +4978,21 @@ ScsiDiskAsyncRead10 ( InsertTailList (&BlkIo2Req->ScsiRWQueue, &Request->Link); gBS->RestoreTPL (OldTpl); - Request->SenseDataLength = (UINT8) (6 * sizeof (EFI_SCSI_SENSE_DATA)); + Request->SenseDataLength = (UINT8)(6 * sizeof (EFI_SCSI_SENSE_DATA)); Request->SenseData = AllocateZeroPool (Request->SenseDataLength); if (Request->SenseData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - Request->ScsiDiskDevice = ScsiDiskDevice; - Request->Timeout = Timeout; - Request->TimesRetry = TimesRetry; - Request->InBuffer = DataBuffer; - Request->DataLength = DataLength; - Request->StartLba = StartLba; - Request->SectorCount = SectorCount; - Request->BlkIo2Req = BlkIo2Req; + Request->ScsiDiskDevice = ScsiDiskDevice; + Request->Timeout = Timeout; + Request->TimesRetry = TimesRetry; + Request->InBuffer = DataBuffer; + Request->DataLength = DataLength; + Request->StartLba = StartLba; + Request->SectorCount = SectorCount; + Request->BlkIo2Req = BlkIo2Req; // // Create Event @@ -4961,7 +5004,7 @@ ScsiDiskAsyncRead10 ( Request, &AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -4974,11 +5017,11 @@ ScsiDiskAsyncRead10 ( &Request->TargetStatus, Request->InBuffer, &Request->DataLength, - (UINT32) Request->StartLba, + (UINT32)Request->StartLba, Request->SectorCount, AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5004,7 +5047,6 @@ ErrorExit: return Status; } - /** Submit Async Write(10) command. @@ -5027,21 +5069,21 @@ ErrorExit: **/ EFI_STATUS ScsiDiskAsyncWrite10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - IN UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + IN UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - SCSI_ASYNC_RW_REQUEST *Request; - EFI_EVENT AsyncIoEvent; - EFI_TPL OldTpl; + EFI_STATUS Status; + SCSI_ASYNC_RW_REQUEST *Request; + EFI_EVENT AsyncIoEvent; + EFI_TPL OldTpl; AsyncIoEvent = NULL; @@ -5054,21 +5096,21 @@ ScsiDiskAsyncWrite10 ( InsertTailList (&BlkIo2Req->ScsiRWQueue, &Request->Link); gBS->RestoreTPL (OldTpl); - Request->SenseDataLength = (UINT8) (6 * sizeof (EFI_SCSI_SENSE_DATA)); + Request->SenseDataLength = (UINT8)(6 * sizeof (EFI_SCSI_SENSE_DATA)); Request->SenseData = AllocateZeroPool (Request->SenseDataLength); if (Request->SenseData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - Request->ScsiDiskDevice = ScsiDiskDevice; - Request->Timeout = Timeout; - Request->TimesRetry = TimesRetry; - Request->OutBuffer = DataBuffer; - Request->DataLength = DataLength; - Request->StartLba = StartLba; - Request->SectorCount = SectorCount; - Request->BlkIo2Req = BlkIo2Req; + Request->ScsiDiskDevice = ScsiDiskDevice; + Request->Timeout = Timeout; + Request->TimesRetry = TimesRetry; + Request->OutBuffer = DataBuffer; + Request->DataLength = DataLength; + Request->StartLba = StartLba; + Request->SectorCount = SectorCount; + Request->BlkIo2Req = BlkIo2Req; // // Create Event @@ -5080,7 +5122,7 @@ ScsiDiskAsyncWrite10 ( Request, &AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5093,11 +5135,11 @@ ScsiDiskAsyncWrite10 ( &Request->TargetStatus, Request->OutBuffer, &Request->DataLength, - (UINT32) Request->StartLba, + (UINT32)Request->StartLba, Request->SectorCount, AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5123,7 +5165,6 @@ ErrorExit: return Status; } - /** Submit Async Read(16) command. @@ -5146,21 +5187,21 @@ ErrorExit: **/ EFI_STATUS ScsiDiskAsyncRead16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - OUT UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + OUT UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - SCSI_ASYNC_RW_REQUEST *Request; - EFI_EVENT AsyncIoEvent; - EFI_TPL OldTpl; + EFI_STATUS Status; + SCSI_ASYNC_RW_REQUEST *Request; + EFI_EVENT AsyncIoEvent; + EFI_TPL OldTpl; AsyncIoEvent = NULL; @@ -5173,21 +5214,21 @@ ScsiDiskAsyncRead16 ( InsertTailList (&BlkIo2Req->ScsiRWQueue, &Request->Link); gBS->RestoreTPL (OldTpl); - Request->SenseDataLength = (UINT8) (6 * sizeof (EFI_SCSI_SENSE_DATA)); + Request->SenseDataLength = (UINT8)(6 * sizeof (EFI_SCSI_SENSE_DATA)); Request->SenseData = AllocateZeroPool (Request->SenseDataLength); if (Request->SenseData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - Request->ScsiDiskDevice = ScsiDiskDevice; - Request->Timeout = Timeout; - Request->TimesRetry = TimesRetry; - Request->InBuffer = DataBuffer; - Request->DataLength = DataLength; - Request->StartLba = StartLba; - Request->SectorCount = SectorCount; - Request->BlkIo2Req = BlkIo2Req; + Request->ScsiDiskDevice = ScsiDiskDevice; + Request->Timeout = Timeout; + Request->TimesRetry = TimesRetry; + Request->InBuffer = DataBuffer; + Request->DataLength = DataLength; + Request->StartLba = StartLba; + Request->SectorCount = SectorCount; + Request->BlkIo2Req = BlkIo2Req; // // Create Event @@ -5199,7 +5240,7 @@ ScsiDiskAsyncRead16 ( Request, &AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5216,7 +5257,7 @@ ScsiDiskAsyncRead16 ( Request->SectorCount, AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5242,7 +5283,6 @@ ErrorExit: return Status; } - /** Submit Async Write(16) command. @@ -5265,21 +5305,21 @@ ErrorExit: **/ EFI_STATUS ScsiDiskAsyncWrite16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - IN UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + IN UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - SCSI_ASYNC_RW_REQUEST *Request; - EFI_EVENT AsyncIoEvent; - EFI_TPL OldTpl; + EFI_STATUS Status; + SCSI_ASYNC_RW_REQUEST *Request; + EFI_EVENT AsyncIoEvent; + EFI_TPL OldTpl; AsyncIoEvent = NULL; @@ -5292,21 +5332,21 @@ ScsiDiskAsyncWrite16 ( InsertTailList (&BlkIo2Req->ScsiRWQueue, &Request->Link); gBS->RestoreTPL (OldTpl); - Request->SenseDataLength = (UINT8) (6 * sizeof (EFI_SCSI_SENSE_DATA)); + Request->SenseDataLength = (UINT8)(6 * sizeof (EFI_SCSI_SENSE_DATA)); Request->SenseData = AllocateZeroPool (Request->SenseDataLength); if (Request->SenseData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto ErrorExit; } - Request->ScsiDiskDevice = ScsiDiskDevice; - Request->Timeout = Timeout; - Request->TimesRetry = TimesRetry; - Request->OutBuffer = DataBuffer; - Request->DataLength = DataLength; - Request->StartLba = StartLba; - Request->SectorCount = SectorCount; - Request->BlkIo2Req = BlkIo2Req; + Request->ScsiDiskDevice = ScsiDiskDevice; + Request->Timeout = Timeout; + Request->TimesRetry = TimesRetry; + Request->OutBuffer = DataBuffer; + Request->DataLength = DataLength; + Request->StartLba = StartLba; + Request->SectorCount = SectorCount; + Request->BlkIo2Req = BlkIo2Req; // // Create Event @@ -5318,7 +5358,7 @@ ScsiDiskAsyncWrite16 ( Request, &AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5335,7 +5375,7 @@ ScsiDiskAsyncWrite16 ( Request->SectorCount, AsyncIoEvent ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -5361,7 +5401,6 @@ ErrorExit: return Status; } - /** Check sense key to find if media presents. @@ -5373,13 +5412,13 @@ ErrorExit: **/ BOOLEAN ScsiDiskIsNoMedia ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsNoMedia; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsNoMedia; IsNoMedia = FALSE; SensePtr = SenseData; @@ -5390,16 +5429,17 @@ ScsiDiskIsNoMedia ( // Additional Sense Code is ASC_NO_MEDIA (0x3A) // if ((SensePtr->Sense_Key == EFI_SCSI_SK_NOT_READY) && - (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_NO_MEDIA)) { + (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_NO_MEDIA)) + { IsNoMedia = TRUE; } + SensePtr++; } return IsNoMedia; } - /** Parse sense key. @@ -5412,70 +5452,68 @@ ScsiDiskIsNoMedia ( **/ BOOLEAN ScsiDiskIsMediaError ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsError; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsError; - IsError = FALSE; - SensePtr = SenseData; + IsError = FALSE; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->Sense_Key) { + case EFI_SCSI_SK_MEDIUM_ERROR: + // + // Sense Key is EFI_SCSI_SK_MEDIUM_ERROR (0x3) + // + switch (SensePtr->Addnl_Sense_Code) { + // + // fall through + // + case EFI_SCSI_ASC_MEDIA_ERR1: - case EFI_SCSI_SK_MEDIUM_ERROR: - // - // Sense Key is EFI_SCSI_SK_MEDIUM_ERROR (0x3) - // - switch (SensePtr->Addnl_Sense_Code) { + // + // fall through + // + case EFI_SCSI_ASC_MEDIA_ERR2: - // - // fall through - // - case EFI_SCSI_ASC_MEDIA_ERR1: + // + // fall through + // + case EFI_SCSI_ASC_MEDIA_ERR3: + case EFI_SCSI_ASC_MEDIA_ERR4: + IsError = TRUE; + break; - // - // fall through - // - case EFI_SCSI_ASC_MEDIA_ERR2: + default: + break; + } - // - // fall through - // - case EFI_SCSI_ASC_MEDIA_ERR3: - case EFI_SCSI_ASC_MEDIA_ERR4: - IsError = TRUE; break; - default: - break; - } + case EFI_SCSI_SK_NOT_READY: + // + // Sense Key is EFI_SCSI_SK_NOT_READY (0x2) + // + switch (SensePtr->Addnl_Sense_Code) { + // + // Additional Sense Code is ASC_MEDIA_UPSIDE_DOWN (0x6) + // + case EFI_SCSI_ASC_MEDIA_UPSIDE_DOWN: + IsError = TRUE; + break; - break; + default: + break; + } - case EFI_SCSI_SK_NOT_READY: - // - // Sense Key is EFI_SCSI_SK_NOT_READY (0x2) - // - switch (SensePtr->Addnl_Sense_Code) { - // - // Additional Sense Code is ASC_MEDIA_UPSIDE_DOWN (0x6) - // - case EFI_SCSI_ASC_MEDIA_UPSIDE_DOWN: - IsError = TRUE; break; default: break; - } - break; - - default: - break; } SensePtr++; @@ -5484,7 +5522,6 @@ ScsiDiskIsMediaError ( return IsError; } - /** Check sense key to find if hardware error happens. @@ -5497,19 +5534,18 @@ ScsiDiskIsMediaError ( **/ BOOLEAN ScsiDiskIsHardwareError ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsError; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsError; - IsError = FALSE; - SensePtr = SenseData; + IsError = FALSE; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - // // Sense Key is EFI_SCSI_SK_HARDWARE_ERROR (0x4) // @@ -5523,7 +5559,6 @@ ScsiDiskIsHardwareError ( return IsError; } - /** Check sense key to find if media has changed. @@ -5535,16 +5570,16 @@ ScsiDiskIsHardwareError ( **/ BOOLEAN ScsiDiskIsMediaChange ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsMediaChanged; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsMediaChanged; - IsMediaChanged = FALSE; - SensePtr = SenseData; + IsMediaChanged = FALSE; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { // @@ -5552,7 +5587,8 @@ ScsiDiskIsMediaChange ( // Additional sense code is EFI_SCSI_ASC_MEDIA_CHANGE (0x28) // if ((SensePtr->Sense_Key == EFI_SCSI_SK_UNIT_ATTENTION) && - (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_CHANGE)) { + (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_CHANGE)) + { IsMediaChanged = TRUE; } @@ -5574,25 +5610,25 @@ ScsiDiskIsMediaChange ( **/ BOOLEAN ScsiDiskIsResetBefore ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsResetBefore; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsResetBefore; IsResetBefore = FALSE; SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - // // Sense Key is EFI_SCSI_SK_UNIT_ATTENTION (0x6) // Additional Sense Code is EFI_SCSI_ASC_RESET (0x29) // if ((SensePtr->Sense_Key == EFI_SCSI_SK_UNIT_ATTENTION) && - (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_RESET)) { + (SensePtr->Addnl_Sense_Code == EFI_SCSI_ASC_RESET)) + { IsResetBefore = TRUE; } @@ -5615,56 +5651,56 @@ ScsiDiskIsResetBefore ( **/ BOOLEAN ScsiDiskIsDriveReady ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts, - OUT BOOLEAN *RetryLater + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts, + OUT BOOLEAN *RetryLater ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN IsReady; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN IsReady; IsReady = TRUE; *RetryLater = FALSE; SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->Sense_Key) { - - case EFI_SCSI_SK_NOT_READY: - // - // Sense Key is EFI_SCSI_SK_NOT_READY (0x2) - // - switch (SensePtr->Addnl_Sense_Code) { - case EFI_SCSI_ASC_NOT_READY: + case EFI_SCSI_SK_NOT_READY: // - // Additional Sense Code is EFI_SCSI_ASC_NOT_READY (0x4) + // Sense Key is EFI_SCSI_SK_NOT_READY (0x2) // - switch (SensePtr->Addnl_Sense_Code_Qualifier) { - case EFI_SCSI_ASCQ_IN_PROGRESS: - // - // Additional Sense Code Qualifier is - // EFI_SCSI_ASCQ_IN_PROGRESS (0x1) - // - IsReady = FALSE; - *RetryLater = TRUE; - break; + switch (SensePtr->Addnl_Sense_Code) { + case EFI_SCSI_ASC_NOT_READY: + // + // Additional Sense Code is EFI_SCSI_ASC_NOT_READY (0x4) + // + switch (SensePtr->Addnl_Sense_Code_Qualifier) { + case EFI_SCSI_ASCQ_IN_PROGRESS: + // + // Additional Sense Code Qualifier is + // EFI_SCSI_ASCQ_IN_PROGRESS (0x1) + // + IsReady = FALSE; + *RetryLater = TRUE; + break; + + default: + IsReady = FALSE; + *RetryLater = FALSE; + break; + } - default: - IsReady = FALSE; - *RetryLater = FALSE; - break; + break; + + default: + break; } + break; default: break; - } - break; - - default: - break; } SensePtr++; @@ -5685,13 +5721,13 @@ ScsiDiskIsDriveReady ( **/ BOOLEAN ScsiDiskHaveSenseKey ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { - EFI_SCSI_SENSE_DATA *SensePtr; - UINTN Index; - BOOLEAN HaveSenseKey; + EFI_SCSI_SENSE_DATA *SensePtr; + UINTN Index; + BOOLEAN HaveSenseKey; if (SenseCounts == 0) { HaveSenseKey = FALSE; @@ -5702,12 +5738,12 @@ ScsiDiskHaveSenseKey ( SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - // // Sense Key is SK_NO_SENSE (0x0) // if ((SensePtr->Sense_Key == EFI_SCSI_SK_NO_SENSE) && - (Index == 0)) { + (Index == 0)) + { HaveSenseKey = FALSE; } @@ -5725,11 +5761,11 @@ ScsiDiskHaveSenseKey ( **/ VOID ReleaseScsiDiskDeviceResources ( - IN SCSI_DISK_DEV *ScsiDiskDevice + IN SCSI_DISK_DEV *ScsiDiskDevice ) { if (ScsiDiskDevice == NULL) { - return ; + return; } if (ScsiDiskDevice->SenseData != NULL) { @@ -5759,11 +5795,11 @@ ReleaseScsiDiskDeviceResources ( **/ BOOLEAN DetermineInstallBlockIo ( - IN EFI_HANDLE ChildHandle + IN EFI_HANDLE ChildHandle ) { - EFI_SCSI_PASS_THRU_PROTOCOL *ScsiPassThru; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiPassThru; + EFI_SCSI_PASS_THRU_PROTOCOL *ScsiPassThru; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiPassThru; // // Firstly, check if ExtScsiPassThru Protocol parent handle exists. If existence, @@ -5805,15 +5841,15 @@ DetermineInstallBlockIo ( VOID * EFIAPI GetParentProtocol ( - IN EFI_GUID *ProtocolGuid, - IN EFI_HANDLE ChildHandle + IN EFI_GUID *ProtocolGuid, + IN EFI_HANDLE ChildHandle ) { - UINTN Index; - UINTN HandleCount; - VOID *Interface; - EFI_STATUS Status; - EFI_HANDLE *HandleBuffer; + UINTN Index; + UINTN HandleCount; + VOID *Interface; + EFI_STATUS Status; + EFI_HANDLE *HandleBuffer; // // Retrieve the list of all handles from the handle database @@ -5860,20 +5896,20 @@ GetParentProtocol ( **/ BOOLEAN DetermineInstallEraseBlock ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ) { - UINT8 HostAdapterStatus; - UINT8 TargetStatus; - EFI_STATUS CommandStatus; - EFI_STATUS Status; - BOOLEAN UfsDevice; - BOOLEAN RetVal; - EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; - UINT8 SenseDataLength; - UINT32 DataLength16; - EFI_SCSI_DISK_CAPACITY_DATA16 *CapacityData16; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; + EFI_STATUS CommandStatus; + EFI_STATUS Status; + BOOLEAN UfsDevice; + BOOLEAN RetVal; + EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; + UINT8 SenseDataLength; + UINT32 DataLength16; + EFI_SCSI_DISK_CAPACITY_DATA16 *CapacityData16; UfsDevice = FALSE; RetVal = TRUE; @@ -5890,7 +5926,7 @@ DetermineInstallEraseBlock ( Status = gBS->HandleProtocol ( ChildHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePathNode + (VOID **)&DevicePathNode ); // // Device Path protocol must be installed on the device handle. @@ -5902,13 +5938,15 @@ DetermineInstallEraseBlock ( // For now, only support Erase Block Protocol on UFS devices. // if ((DevicePathNode->Type == MESSAGING_DEVICE_PATH) && - (DevicePathNode->SubType == MSG_UFS_DP)) { + (DevicePathNode->SubType == MSG_UFS_DP)) + { UfsDevice = TRUE; break; } DevicePathNode = NextDevicePathNode (DevicePathNode); } + if (!UfsDevice) { RetVal = FALSE; goto Done; @@ -5934,7 +5972,7 @@ DetermineInstallEraseBlock ( &SenseDataLength, &HostAdapterStatus, &TargetStatus, - (VOID *) CapacityData16, + (VOID *)CapacityData16, &DataLength16, FALSE ); @@ -5946,7 +5984,8 @@ DetermineInstallEraseBlock ( // Bits TPE and TPRZ should both be set to enable the erase feature on UFS. // if (((CapacityData16->LowestAlignLogic2 & BIT7) == 0) || - ((CapacityData16->LowestAlignLogic2 & BIT6) == 0)) { + ((CapacityData16->LowestAlignLogic2 & BIT6) == 0)) + { DEBUG (( DEBUG_VERBOSE, "ScsiDisk EraseBlock: Either TPE or TPRZ is not set: 0x%x.\n", @@ -5971,7 +6010,8 @@ DetermineInstallEraseBlock ( // Check whether the UFS device server implements the UNMAP command. // if ((ScsiDiskDevice->UnmapInfo.MaxLbaCnt == 0) || - (ScsiDiskDevice->UnmapInfo.MaxBlkDespCnt == 0)) { + (ScsiDiskDevice->UnmapInfo.MaxBlkDespCnt == 0)) + { DEBUG (( DEBUG_VERBOSE, "ScsiDisk EraseBlock: The device server does not implement the UNMAP command.\n" @@ -6001,22 +6041,22 @@ Done: **/ BOOLEAN DetermineInstallStorageSecurity ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ) { - EFI_STATUS Status; - UFS_DEVICE_PATH *UfsDevice; - BOOLEAN RetVal; - EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; + EFI_STATUS Status; + UFS_DEVICE_PATH *UfsDevice; + BOOLEAN RetVal; + EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; - UfsDevice = NULL; - RetVal = TRUE; + UfsDevice = NULL; + RetVal = TRUE; Status = gBS->HandleProtocol ( ChildHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePathNode + (VOID **)&DevicePathNode ); // // Device Path protocol must be installed on the device handle. @@ -6028,13 +6068,15 @@ DetermineInstallStorageSecurity ( // For now, only support Storage Security Command Protocol on UFS devices. // if ((DevicePathNode->Type == MESSAGING_DEVICE_PATH) && - (DevicePathNode->SubType == MSG_UFS_DP)) { - UfsDevice = (UFS_DEVICE_PATH *) DevicePathNode; + (DevicePathNode->SubType == MSG_UFS_DP)) + { + UfsDevice = (UFS_DEVICE_PATH *)DevicePathNode; break; } DevicePathNode = NextDevicePathNode (DevicePathNode); } + if (UfsDevice == NULL) { RetVal = FALSE; goto Done; @@ -6067,26 +6109,26 @@ Done: EFI_STATUS EFIAPI ScsiDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ) { - EFI_STATUS Status; - SCSI_DISK_DEV *ScsiDiskDevice; + EFI_STATUS Status; + SCSI_DISK_DEV *ScsiDiskDevice; - ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); Status = EFI_BUFFER_TOO_SMALL; if (*InquiryDataSize >= sizeof (ScsiDiskDevice->InquiryData)) { Status = EFI_SUCCESS; CopyMem (InquiryData, &ScsiDiskDevice->InquiryData, sizeof (ScsiDiskDevice->InquiryData)); } + *InquiryDataSize = sizeof (ScsiDiskDevice->InquiryData); return Status; } - /** Provides identify information for the controller type. @@ -6108,13 +6150,13 @@ ScsiDiskInfoInquiry ( EFI_STATUS EFIAPI ScsiDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ) { - EFI_STATUS Status; - SCSI_DISK_DEV *ScsiDiskDevice; + EFI_STATUS Status; + SCSI_DISK_DEV *ScsiDiskDevice; if (CompareGuid (&This->Interface, &gEfiDiskInfoScsiInterfaceGuid) || CompareGuid (&This->Interface, &gEfiDiskInfoUfsInterfaceGuid)) { // @@ -6123,13 +6165,14 @@ ScsiDiskInfoIdentify ( return EFI_NOT_FOUND; } - ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); + ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); Status = EFI_BUFFER_TOO_SMALL; if (*IdentifyDataSize >= sizeof (ScsiDiskDevice->IdentifyData)) { Status = EFI_SUCCESS; CopyMem (IdentifyData, &ScsiDiskDevice->IdentifyData, sizeof (ScsiDiskDevice->IdentifyData)); } + *IdentifyDataSize = sizeof (ScsiDiskDevice->IdentifyData); return Status; } @@ -6154,16 +6197,15 @@ ScsiDiskInfoIdentify ( EFI_STATUS EFIAPI ScsiDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ) { return EFI_NOT_FOUND; } - /** This function is used by the IDE bus driver to get controller information. @@ -6178,12 +6220,12 @@ ScsiDiskInfoSenseData ( EFI_STATUS EFIAPI ScsiDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ) { - SCSI_DISK_DEV *ScsiDiskDevice; + SCSI_DISK_DEV *ScsiDiskDevice; if (CompareGuid (&This->Interface, &gEfiDiskInfoScsiInterfaceGuid) || CompareGuid (&This->Interface, &gEfiDiskInfoUfsInterfaceGuid)) { // @@ -6192,14 +6234,13 @@ ScsiDiskInfoWhichIde ( return EFI_UNSUPPORTED; } - ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); - *IdeChannel = ScsiDiskDevice->Channel; - *IdeDevice = ScsiDiskDevice->Device; + ScsiDiskDevice = SCSI_DISK_DEV_FROM_DISKINFO (This); + *IdeChannel = ScsiDiskDevice->Channel; + *IdeDevice = ScsiDiskDevice->Device; return EFI_SUCCESS; } - /** Issues ATA IDENTIFY DEVICE command to identify ATAPI device. @@ -6215,11 +6256,11 @@ ScsiDiskInfoWhichIde ( **/ EFI_STATUS AtapiIdentifyDevice ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice + IN OUT SCSI_DISK_DEV *ScsiDiskDevice ) { - EFI_SCSI_IO_SCSI_REQUEST_PACKET CommandPacket; - UINT8 Cdb[6]; + EFI_SCSI_IO_SCSI_REQUEST_PACKET CommandPacket; + UINT8 Cdb[6]; // // Initialize SCSI REQUEST_PACKET and 6-byte Cdb @@ -6227,17 +6268,16 @@ AtapiIdentifyDevice ( ZeroMem (&CommandPacket, sizeof (CommandPacket)); ZeroMem (Cdb, sizeof (Cdb)); - Cdb[0] = ATA_CMD_IDENTIFY_DEVICE; - CommandPacket.Timeout = SCSI_DISK_TIMEOUT; - CommandPacket.Cdb = Cdb; - CommandPacket.CdbLength = (UINT8) sizeof (Cdb); - CommandPacket.InDataBuffer = &ScsiDiskDevice->IdentifyData; + Cdb[0] = ATA_CMD_IDENTIFY_DEVICE; + CommandPacket.Timeout = SCSI_DISK_TIMEOUT; + CommandPacket.Cdb = Cdb; + CommandPacket.CdbLength = (UINT8)sizeof (Cdb); + CommandPacket.InDataBuffer = &ScsiDiskDevice->IdentifyData; CommandPacket.InTransferLength = sizeof (ScsiDiskDevice->IdentifyData); return ScsiDiskDevice->ScsiIo->ExecuteScsiCommand (ScsiDiskDevice->ScsiIo, &CommandPacket, NULL); } - /** Initialize the installation of DiskInfo protocol. @@ -6252,8 +6292,8 @@ AtapiIdentifyDevice ( **/ VOID InitializeInstallDiskInfo ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ) { EFI_STATUS Status; @@ -6263,7 +6303,7 @@ InitializeInstallDiskInfo ( SATA_DEVICE_PATH *SataDevicePath; UINTN IdentifyRetry; - Status = gBS->HandleProtocol (ChildHandle, &gEfiDevicePathProtocolGuid, (VOID **) &DevicePathNode); + Status = gBS->HandleProtocol (ChildHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePathNode); // // Device Path protocol must be installed on the device handle. // @@ -6278,9 +6318,9 @@ InitializeInstallDiskInfo ( if ((DevicePathType (DevicePathNode) == HARDWARE_DEVICE_PATH) && (DevicePathSubType (DevicePathNode) == HW_PCI_DP) && (DevicePathType (ChildDevicePathNode) == MESSAGING_DEVICE_PATH) && - ((DevicePathSubType (ChildDevicePathNode) == MSG_ATAPI_DP) || - (DevicePathSubType (ChildDevicePathNode) == MSG_SATA_DP))) { - + ((DevicePathSubType (ChildDevicePathNode) == MSG_ATAPI_DP) || + (DevicePathSubType (ChildDevicePathNode) == MSG_SATA_DP))) + { IdentifyRetry = 3; do { // @@ -6289,13 +6329,13 @@ InitializeInstallDiskInfo ( // Status = AtapiIdentifyDevice (ScsiDiskDevice); if (!EFI_ERROR (Status)) { - if (DevicePathSubType(ChildDevicePathNode) == MSG_ATAPI_DP) { + if (DevicePathSubType (ChildDevicePathNode) == MSG_ATAPI_DP) { // // We find the valid ATAPI device path // - AtapiDevicePath = (ATAPI_DEVICE_PATH *) ChildDevicePathNode; + AtapiDevicePath = (ATAPI_DEVICE_PATH *)ChildDevicePathNode; ScsiDiskDevice->Channel = AtapiDevicePath->PrimarySecondary; - ScsiDiskDevice->Device = AtapiDevicePath->SlaveMaster; + ScsiDiskDevice->Device = AtapiDevicePath->SlaveMaster; // // Update the DiskInfo.Interface to IDE interface GUID for the physical ATAPI device. // @@ -6304,22 +6344,25 @@ InitializeInstallDiskInfo ( // // We find the valid SATA device path // - SataDevicePath = (SATA_DEVICE_PATH *) ChildDevicePathNode; + SataDevicePath = (SATA_DEVICE_PATH *)ChildDevicePathNode; ScsiDiskDevice->Channel = SataDevicePath->HBAPortNumber; - ScsiDiskDevice->Device = SataDevicePath->PortMultiplierPortNumber; + ScsiDiskDevice->Device = SataDevicePath->PortMultiplierPortNumber; // // Update the DiskInfo.Interface to AHCI interface GUID for the physical AHCI device. // CopyGuid (&ScsiDiskDevice->DiskInfo.Interface, &gEfiDiskInfoAhciInterfaceGuid); } + return; } } while (--IdentifyRetry > 0); } else if ((DevicePathType (ChildDevicePathNode) == MESSAGING_DEVICE_PATH) && - (DevicePathSubType (ChildDevicePathNode) == MSG_UFS_DP)) { + (DevicePathSubType (ChildDevicePathNode) == MSG_UFS_DP)) + { CopyGuid (&ScsiDiskDevice->DiskInfo.Interface, &gEfiDiskInfoUfsInterfaceGuid); break; } + DevicePathNode = ChildDevicePathNode; } diff --git a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h index ed9bbd6f8b..d54282df5f 100644 --- a/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h +++ b/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h @@ -9,10 +9,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SCSI_DISK_H_ #define _SCSI_DISK_H_ - #include - #include #include #include @@ -24,7 +22,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - #include #include #include @@ -37,74 +34,74 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define IS_DEVICE_FIXED(a) (a)->FixedDevice ? 1 : 0 +#define IS_DEVICE_FIXED(a) (a)->FixedDevice ? 1 : 0 -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) -#define UFS_WLUN_RPMB 0xC4 +#define UFS_WLUN_RPMB 0xC4 typedef struct { - UINT32 MaxLbaCnt; - UINT32 MaxBlkDespCnt; - UINT32 GranularityAlignment; + UINT32 MaxLbaCnt; + UINT32 MaxBlkDespCnt; + UINT32 GranularityAlignment; } SCSI_UNMAP_PARAM_INFO; -#define SCSI_DISK_DEV_SIGNATURE SIGNATURE_32 ('s', 'c', 'd', 'k') +#define SCSI_DISK_DEV_SIGNATURE SIGNATURE_32 ('s', 'c', 'd', 'k') typedef struct { - UINT32 Signature; + UINT32 Signature; - EFI_HANDLE Handle; + EFI_HANDLE Handle; - EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; + EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; - EFI_BLOCK_IO_PROTOCOL BlkIo; - EFI_BLOCK_IO2_PROTOCOL BlkIo2; - EFI_BLOCK_IO_MEDIA BlkIoMedia; - EFI_ERASE_BLOCK_PROTOCOL EraseBlock; - EFI_SCSI_IO_PROTOCOL *ScsiIo; - UINT8 DeviceType; - BOOLEAN FixedDevice; - UINT16 Reserved; + EFI_BLOCK_IO_PROTOCOL BlkIo; + EFI_BLOCK_IO2_PROTOCOL BlkIo2; + EFI_BLOCK_IO_MEDIA BlkIoMedia; + EFI_ERASE_BLOCK_PROTOCOL EraseBlock; + EFI_SCSI_IO_PROTOCOL *ScsiIo; + UINT8 DeviceType; + BOOLEAN FixedDevice; + UINT16 Reserved; - EFI_SCSI_SENSE_DATA *SenseData; - UINTN SenseDataNumber; - EFI_SCSI_INQUIRY_DATA InquiryData; + EFI_SCSI_SENSE_DATA *SenseData; + UINTN SenseDataNumber; + EFI_SCSI_INQUIRY_DATA InquiryData; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; - EFI_DISK_INFO_PROTOCOL DiskInfo; + EFI_DISK_INFO_PROTOCOL DiskInfo; // // The following fields are only valid for ATAPI/SATA device // - UINT32 Channel; - UINT32 Device; - ATAPI_IDENTIFY_DATA IdentifyData; + UINT32 Channel; + UINT32 Device; + ATAPI_IDENTIFY_DATA IdentifyData; // // Scsi UNMAP command parameters information // - SCSI_UNMAP_PARAM_INFO UnmapInfo; - BOOLEAN BlockLimitsVpdSupported; + SCSI_UNMAP_PARAM_INFO UnmapInfo; + BOOLEAN BlockLimitsVpdSupported; // // The flag indicates if 16-byte command can be used // - BOOLEAN Cdb16Byte; + BOOLEAN Cdb16Byte; // // The queue for asynchronous task requests // - LIST_ENTRY AsyncTaskQueue; + LIST_ENTRY AsyncTaskQueue; } SCSI_DISK_DEV; -#define SCSI_DISK_DEV_FROM_BLKIO(a) CR (a, SCSI_DISK_DEV, BlkIo, SCSI_DISK_DEV_SIGNATURE) -#define SCSI_DISK_DEV_FROM_BLKIO2(a) CR (a, SCSI_DISK_DEV, BlkIo2, SCSI_DISK_DEV_SIGNATURE) +#define SCSI_DISK_DEV_FROM_BLKIO(a) CR (a, SCSI_DISK_DEV, BlkIo, SCSI_DISK_DEV_SIGNATURE) +#define SCSI_DISK_DEV_FROM_BLKIO2(a) CR (a, SCSI_DISK_DEV, BlkIo2, SCSI_DISK_DEV_SIGNATURE) #define SCSI_DISK_DEV_FROM_ERASEBLK(a) CR (a, SCSI_DISK_DEV, EraseBlock, SCSI_DISK_DEV_SIGNATURE) -#define SCSI_DISK_DEV_FROM_STORSEC(a) CR (a, SCSI_DISK_DEV, StorageSecurity, SCSI_DISK_DEV_SIGNATURE) +#define SCSI_DISK_DEV_FROM_STORSEC(a) CR (a, SCSI_DISK_DEV, StorageSecurity, SCSI_DISK_DEV_SIGNATURE) -#define SCSI_DISK_DEV_FROM_DISKINFO(a) CR (a, SCSI_DISK_DEV, DiskInfo, SCSI_DISK_DEV_SIGNATURE) +#define SCSI_DISK_DEV_FROM_DISKINFO(a) CR (a, SCSI_DISK_DEV, DiskInfo, SCSI_DISK_DEV_SIGNATURE) // // Asynchronous I/O request @@ -113,55 +110,55 @@ typedef struct { // Private data structure for a BlockIo2 request // typedef struct { - EFI_BLOCK_IO2_TOKEN *Token; + EFI_BLOCK_IO2_TOKEN *Token; // // The flag indicates if the last Scsi Read/Write sub-task for a BlockIo2 // request is sent to device // - BOOLEAN LastScsiRW; + BOOLEAN LastScsiRW; // // The queue for Scsi Read/Write sub-tasks of a BlockIo2 request // - LIST_ENTRY ScsiRWQueue; + LIST_ENTRY ScsiRWQueue; - LIST_ENTRY Link; + LIST_ENTRY Link; } SCSI_BLKIO2_REQUEST; // // Private data structure for a SCSI Read/Write request // typedef struct { - SCSI_DISK_DEV *ScsiDiskDevice; - UINT64 Timeout; - EFI_SCSI_SENSE_DATA *SenseData; - UINT8 SenseDataLength; - UINT8 HostAdapterStatus; - UINT8 TargetStatus; - UINT8 *InBuffer; - UINT8 *OutBuffer; - UINT32 DataLength; - UINT64 StartLba; - UINT32 SectorCount; - UINT8 TimesRetry; + SCSI_DISK_DEV *ScsiDiskDevice; + UINT64 Timeout; + EFI_SCSI_SENSE_DATA *SenseData; + UINT8 SenseDataLength; + UINT8 HostAdapterStatus; + UINT8 TargetStatus; + UINT8 *InBuffer; + UINT8 *OutBuffer; + UINT32 DataLength; + UINT64 StartLba; + UINT32 SectorCount; + UINT8 TimesRetry; // // The BlockIo2 request this SCSI command belongs to // - SCSI_BLKIO2_REQUEST *BlkIo2Req; + SCSI_BLKIO2_REQUEST *BlkIo2Req; - LIST_ENTRY Link; + LIST_ENTRY Link; } SCSI_ASYNC_RW_REQUEST; // // Private data structure for an EraseBlock request // typedef struct { - EFI_ERASE_BLOCK_TOKEN *Token; + EFI_ERASE_BLOCK_TOKEN *Token; - EFI_SCSI_IO_SCSI_REQUEST_PACKET CommandPacket; + EFI_SCSI_IO_SCSI_REQUEST_PACKET CommandPacket; - LIST_ENTRY Link; + LIST_ENTRY Link; } SCSI_ERASEBLK_REQUEST; // @@ -173,14 +170,14 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gScsiDiskComponentName2; // // action code used in detect media process // -#define ACTION_NO_ACTION 0x00 -#define ACTION_READ_CAPACITY 0x01 -#define ACTION_RETRY_COMMAND_LATER 0x02 -#define ACTION_RETRY_WITH_BACKOFF_ALGO 0x03 +#define ACTION_NO_ACTION 0x00 +#define ACTION_READ_CAPACITY 0x01 +#define ACTION_RETRY_COMMAND_LATER 0x02 +#define ACTION_RETRY_WITH_BACKOFF_ALGO 0x03 -#define SCSI_COMMAND_VERSION_1 0x01 -#define SCSI_COMMAND_VERSION_2 0x02 -#define SCSI_COMMAND_VERSION_3 0x03 +#define SCSI_COMMAND_VERSION_1 0x01 +#define SCSI_COMMAND_VERSION_2 0x02 +#define SCSI_COMMAND_VERSION_3 0x03 // // SCSI Disk Timeout Experience Value @@ -189,7 +186,7 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gScsiDiskComponentName2; // value is updated to 30s to follow ATA/ATAPI spec in which the device may take up to 30s // to respond command. // -#define SCSI_DISK_TIMEOUT EFI_TIMER_PERIOD_SECONDS (30) +#define SCSI_DISK_TIMEOUT EFI_TIMER_PERIOD_SECONDS (30) /** Test to see if this driver supports ControllerHandle. @@ -267,15 +264,16 @@ ScsiDiskDriverBindingStart ( EFI_STATUS EFIAPI ScsiDiskDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer OPTIONAL + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer OPTIONAL ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -323,7 +321,6 @@ ScsiDiskComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -395,11 +392,11 @@ ScsiDiskComponentNameGetDriverName ( EFI_STATUS EFIAPI ScsiDiskComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -418,11 +415,10 @@ ScsiDiskComponentNameGetControllerName ( EFI_STATUS EFIAPI ScsiDiskReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); - /** The function is to Read Block from SCSI Disk. @@ -443,14 +439,13 @@ ScsiDiskReset ( EFI_STATUS EFIAPI ScsiDiskReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ); - /** The function is to Write Block to SCSI Disk. @@ -472,14 +467,13 @@ ScsiDiskReadBlocks ( EFI_STATUS EFIAPI ScsiDiskWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); - /** Flush Block to Disk. @@ -493,10 +487,9 @@ ScsiDiskWriteBlocks ( EFI_STATUS EFIAPI ScsiDiskFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ); - /** Reset SCSI Disk. @@ -545,12 +538,12 @@ ScsiDiskResetEx ( EFI_STATUS EFIAPI ScsiDiskReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -579,12 +572,12 @@ ScsiDiskReadBlocksEx ( EFI_STATUS EFIAPI ScsiDiskWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -638,14 +631,13 @@ ScsiDiskFlushBlocksEx ( EFI_STATUS EFIAPI ScsiDiskEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ); - /** Send a security protocol command to a device that receives data and/or the result of one or more commands sent by SendData. @@ -713,14 +705,14 @@ ScsiDiskEraseBlocks ( EFI_STATUS EFIAPI ScsiDiskReceiveData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId OPTIONAL, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId OPTIONAL, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ); /** @@ -781,16 +773,15 @@ ScsiDiskReceiveData ( EFI_STATUS EFIAPI ScsiDiskSendData ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId OPTIONAL, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId OPTIONAL, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer ); - /** Provides inquiry information for the controller type. @@ -810,12 +801,11 @@ ScsiDiskSendData ( EFI_STATUS EFIAPI ScsiDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ); - /** Provides identify information for the controller type. @@ -837,12 +827,11 @@ ScsiDiskInfoInquiry ( EFI_STATUS EFIAPI ScsiDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ); - /** Provides sense data information for the controller type. @@ -863,10 +852,10 @@ ScsiDiskInfoIdentify ( EFI_STATUS EFIAPI ScsiDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ); /** @@ -883,12 +872,11 @@ ScsiDiskInfoSenseData ( EFI_STATUS EFIAPI ScsiDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ); - /** Detect Device and read out capacity ,if error occurs, parse the sense key. @@ -902,9 +890,9 @@ ScsiDiskInfoWhichIde ( **/ EFI_STATUS ScsiDiskDetectMedia ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN BOOLEAN MustReadCapacity, - OUT BOOLEAN *MediaChange + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN BOOLEAN MustReadCapacity, + OUT BOOLEAN *MediaChange ); /** @@ -925,13 +913,12 @@ ScsiDiskDetectMedia ( **/ EFI_STATUS ScsiDiskTestUnitReady ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys ); - /** Parsing Sense Keys which got from request sense command. @@ -946,13 +933,12 @@ ScsiDiskTestUnitReady ( **/ EFI_STATUS DetectMediaParsingSenseKeys ( - OUT SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN NumberOfSenseKeys, - OUT UINTN *Action + OUT SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN NumberOfSenseKeys, + OUT UINTN *Action ); - /** Send read capacity command to device and get the device parameter. @@ -967,10 +953,10 @@ DetectMediaParsingSenseKeys ( **/ EFI_STATUS ScsiDiskReadCapacity ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys ); /** @@ -986,10 +972,9 @@ ScsiDiskReadCapacity ( **/ EFI_STATUS CheckHostAdapterStatus ( - IN UINT8 HostAdapterStatus + IN UINT8 HostAdapterStatus ); - /** Check the target status and re-interpret it in EFI_STATUS. @@ -1002,7 +987,7 @@ CheckHostAdapterStatus ( **/ EFI_STATUS CheckTargetStatus ( - IN UINT8 TargetStatus + IN UINT8 TargetStatus ); /** @@ -1024,11 +1009,11 @@ CheckTargetStatus ( **/ EFI_STATUS ScsiDiskRequestSenseKeys ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - OUT EFI_SCSI_SENSE_DATA **SenseDataArray, - OUT UINTN *NumberOfSenseKeys, - IN BOOLEAN AskResetIfError + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + OUT EFI_SCSI_SENSE_DATA **SenseDataArray, + OUT UINTN *NumberOfSenseKeys, + IN BOOLEAN AskResetIfError ); /** @@ -1043,8 +1028,8 @@ ScsiDiskRequestSenseKeys ( **/ EFI_STATUS ScsiDiskInquiryDevice ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry + IN OUT SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry ); /** @@ -1055,7 +1040,7 @@ ScsiDiskInquiryDevice ( **/ VOID ParseInquiryData ( - IN OUT SCSI_DISK_DEV *ScsiDiskDevice + IN OUT SCSI_DISK_DEV *ScsiDiskDevice ); /** @@ -1072,10 +1057,10 @@ ParseInquiryData ( **/ EFI_STATUS ScsiDiskReadSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks ); /** @@ -1092,10 +1077,10 @@ ScsiDiskReadSectors ( **/ EFI_STATUS ScsiDiskWriteSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks ); /** @@ -1115,11 +1100,11 @@ ScsiDiskWriteSectors ( **/ EFI_STATUS ScsiDiskAsyncReadSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1139,11 +1124,11 @@ ScsiDiskAsyncReadSectors ( **/ EFI_STATUS ScsiDiskAsyncWriteSectors ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN VOID *Buffer, - IN EFI_LBA Lba, - IN UINTN NumberOfBlocks, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN VOID *Buffer, + IN EFI_LBA Lba, + IN UINTN NumberOfBlocks, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1161,13 +1146,13 @@ ScsiDiskAsyncWriteSectors ( **/ EFI_STATUS ScsiDiskRead10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - OUT UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + OUT UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount ); /** @@ -1186,13 +1171,13 @@ ScsiDiskRead10 ( **/ EFI_STATUS ScsiDiskWrite10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - IN UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + IN UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount ); /** @@ -1210,13 +1195,13 @@ ScsiDiskWrite10 ( **/ EFI_STATUS ScsiDiskRead16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - OUT UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + OUT UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount ); /** @@ -1235,13 +1220,13 @@ ScsiDiskRead16 ( **/ EFI_STATUS ScsiDiskWrite16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - OUT BOOLEAN *NeedRetry, - IN UINT64 Timeout, - IN UINT8 *DataBuffer, - IN OUT UINT32 *DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount + IN SCSI_DISK_DEV *ScsiDiskDevice, + OUT BOOLEAN *NeedRetry, + IN UINT64 Timeout, + IN UINT8 *DataBuffer, + IN OUT UINT32 *DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount ); /** @@ -1266,15 +1251,15 @@ ScsiDiskWrite16 ( **/ EFI_STATUS ScsiDiskAsyncRead10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - OUT UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + OUT UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1299,15 +1284,15 @@ ScsiDiskAsyncRead10 ( **/ EFI_STATUS ScsiDiskAsyncWrite10 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - IN UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT32 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + IN UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT32 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1332,15 +1317,15 @@ ScsiDiskAsyncWrite10 ( **/ EFI_STATUS ScsiDiskAsyncRead16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - OUT UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + OUT UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1365,15 +1350,15 @@ ScsiDiskAsyncRead16 ( **/ EFI_STATUS ScsiDiskAsyncWrite16 ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN UINT64 Timeout, - IN UINT8 TimesRetry, - IN UINT8 *DataBuffer, - IN UINT32 DataLength, - IN UINT64 StartLba, - IN UINT32 SectorCount, - IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, - IN EFI_BLOCK_IO2_TOKEN *Token + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN UINT64 Timeout, + IN UINT8 TimesRetry, + IN UINT8 *DataBuffer, + IN UINT32 DataLength, + IN UINT64 StartLba, + IN UINT32 SectorCount, + IN OUT SCSI_BLKIO2_REQUEST *BlkIo2Req, + IN EFI_BLOCK_IO2_TOKEN *Token ); /** @@ -1401,8 +1386,8 @@ GetMediaInfo ( **/ BOOLEAN ScsiDiskIsNoMedia ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1417,8 +1402,8 @@ ScsiDiskIsNoMedia ( **/ BOOLEAN ScsiDiskIsMediaError ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1433,8 +1418,8 @@ ScsiDiskIsMediaError ( **/ BOOLEAN ScsiDiskIsHardwareError ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1448,8 +1433,8 @@ ScsiDiskIsHardwareError ( **/ BOOLEAN ScsiDiskIsMediaChange ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1464,8 +1449,8 @@ ScsiDiskIsMediaChange ( **/ BOOLEAN ScsiDiskIsResetBefore ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1481,9 +1466,9 @@ ScsiDiskIsResetBefore ( **/ BOOLEAN ScsiDiskIsDriveReady ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts, - OUT BOOLEAN *RetryLater + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts, + OUT BOOLEAN *RetryLater ); /** @@ -1498,8 +1483,8 @@ ScsiDiskIsDriveReady ( **/ BOOLEAN ScsiDiskHaveSenseKey ( - IN EFI_SCSI_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN EFI_SCSI_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -1510,7 +1495,7 @@ ScsiDiskHaveSenseKey ( **/ VOID ReleaseScsiDiskDeviceResources ( - IN SCSI_DISK_DEV *ScsiDiskDevice + IN SCSI_DISK_DEV *ScsiDiskDevice ); /** @@ -1525,7 +1510,7 @@ ReleaseScsiDiskDeviceResources ( **/ BOOLEAN DetermineInstallBlockIo ( - IN EFI_HANDLE ChildHandle + IN EFI_HANDLE ChildHandle ); /** @@ -1542,8 +1527,8 @@ DetermineInstallBlockIo ( **/ VOID InitializeInstallDiskInfo ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ); /** @@ -1561,8 +1546,8 @@ InitializeInstallDiskInfo ( VOID * EFIAPI GetParentProtocol ( - IN EFI_GUID *ProtocolGuid, - IN EFI_HANDLE ChildHandle + IN EFI_GUID *ProtocolGuid, + IN EFI_HANDLE ChildHandle ); /** @@ -1577,8 +1562,8 @@ GetParentProtocol ( **/ BOOLEAN DetermineInstallEraseBlock ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ); /** @@ -1593,8 +1578,8 @@ DetermineInstallEraseBlock ( **/ BOOLEAN DetermineInstallStorageSecurity ( - IN SCSI_DISK_DEV *ScsiDiskDevice, - IN EFI_HANDLE ChildHandle + IN SCSI_DISK_DEV *ScsiDiskDevice, + IN EFI_HANDLE ChildHandle ); #endif diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/DmaMem.c b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/DmaMem.c index 2d8bfa1b00..df2f18024e 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/DmaMem.c +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/DmaMem.c @@ -32,11 +32,11 @@ EDKII_IOMMU_PPI *mIoMmu; **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { EFI_STATUS Status; @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -81,9 +83,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,7 +101,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { EFI_STATUS Status; @@ -109,6 +112,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -142,7 +146,7 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; if (mIoMmu != NULL) { @@ -157,18 +161,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = mIoMmu->Map ( - mIoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = mIoMmu->Map ( + mIoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -186,10 +191,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -207,9 +214,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { EFI_STATUS Status; @@ -221,6 +228,7 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -239,4 +247,3 @@ IoMmuInit ( (VOID **)&mIoMmu ); } - diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.c b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.c index bf4498df55..a87eb2092f 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.c +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.c @@ -10,7 +10,7 @@ // // Template for EMMC HC Slot Data. // -EMMC_PEIM_HC_SLOT gEmmcHcSlotTemplate = { +EMMC_PEIM_HC_SLOT gEmmcHcSlotTemplate = { EMMC_PEIM_SLOT_SIG, // Signature { // Media { @@ -97,7 +97,7 @@ EMMC_PEIM_HC_SLOT gEmmcHcSlotTemplate = { 0, }, { // ExtCsd - {0}, + { 0 }, }, TRUE, // SectorAddressing NULL // Private @@ -106,7 +106,7 @@ EMMC_PEIM_HC_SLOT gEmmcHcSlotTemplate = { // // Template for EMMC HC Private Data. // -EMMC_PEIM_HC_PRIVATE_DATA gEmmcHcPrivateTemplate = { +EMMC_PEIM_HC_PRIVATE_DATA gEmmcHcPrivateTemplate = { EMMC_PEIM_SIG, // Signature NULL, // Pool { // BlkIoPpi @@ -158,6 +158,7 @@ EMMC_PEIM_HC_PRIVATE_DATA gEmmcHcPrivateTemplate = { 0, // SlotNum 0 // TotalBlkIoDevices }; + /** Gets the count of block I/O devices that one specific block driver detects. @@ -185,9 +186,9 @@ EmmcBlockIoPeimGetDeviceNo ( OUT UINTN *NumberBlockDevices ) { - EMMC_PEIM_HC_PRIVATE_DATA *Private; + EMMC_PEIM_HC_PRIVATE_DATA *Private; - Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); + Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); *NumberBlockDevices = Private->TotalBlkIoDevices; return EFI_SUCCESS; } @@ -242,11 +243,11 @@ EmmcBlockIoPeimGetMediaInfo ( OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { - EMMC_PEIM_HC_PRIVATE_DATA *Private; - UINT8 SlotNum; - UINT8 MediaNum; - UINT8 Location; - BOOLEAN Found; + EMMC_PEIM_HC_PRIVATE_DATA *Private; + UINT8 SlotNum; + UINT8 MediaNum; + UINT8 Location; + BOOLEAN Found; Found = FALSE; Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); @@ -259,12 +260,13 @@ EmmcBlockIoPeimGetMediaInfo ( MediaNum = 0; for (SlotNum = 0; SlotNum < Private->SlotNum; SlotNum++) { for (MediaNum = 0; MediaNum < Private->Slot[SlotNum].MediaNum; MediaNum++) { - Location ++; + Location++; if (Location == DeviceIndex) { Found = TRUE; break; } } + if (Found) { break; } @@ -323,17 +325,17 @@ EmmcBlockIoPeimReadBlocks ( OUT VOID *Buffer ) { - EFI_STATUS Status; - UINT32 BlockSize; - UINTN NumberOfBlocks; - EMMC_PEIM_HC_PRIVATE_DATA *Private; - UINT8 SlotNum; - UINT8 MediaNum; - UINT8 Location; - UINT8 PartitionConfig; - UINTN Remaining; - UINT32 MaxBlock; - BOOLEAN Found; + EFI_STATUS Status; + UINT32 BlockSize; + UINTN NumberOfBlocks; + EMMC_PEIM_HC_PRIVATE_DATA *Private; + UINT8 SlotNum; + UINT8 MediaNum; + UINT8 Location; + UINT8 PartitionConfig; + UINTN Remaining; + UINT32 MaxBlock; + BOOLEAN Found; Status = EFI_SUCCESS; Found = FALSE; @@ -358,12 +360,13 @@ EmmcBlockIoPeimReadBlocks ( MediaNum = 0; for (SlotNum = 0; SlotNum < Private->SlotNum; SlotNum++) { for (MediaNum = 0; MediaNum < Private->Slot[SlotNum].MediaNum; MediaNum++) { - Location ++; + Location++; if (Location == DeviceIndex) { Found = TRUE; break; } } + if (Found) { break; } @@ -385,20 +388,22 @@ EmmcBlockIoPeimReadBlocks ( // PartitionConfig = Private->Slot[SlotNum].ExtCsd.PartitionConfig; if ((PartitionConfig & 0x7) != Private->Slot[SlotNum].PartitionType[MediaNum]) { - PartitionConfig &= (UINT8)~0x7; + PartitionConfig &= (UINT8) ~0x7; PartitionConfig |= Private->Slot[SlotNum].PartitionType[MediaNum]; - Status = EmmcPeimSwitch ( - &Private->Slot[SlotNum], - 0x3, - OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), - PartitionConfig, - 0x0 - ); + Status = EmmcPeimSwitch ( + &Private->Slot[SlotNum], + 0x3, + OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), + PartitionConfig, + 0x0 + ); if (EFI_ERROR (Status)) { return Status; } + Private->Slot[SlotNum].ExtCsd.PartitionConfig = PartitionConfig; } + // // Start to execute data transfer. The max block number in single cmd is 65535 blocks. // @@ -418,15 +423,16 @@ EmmcBlockIoPeimReadBlocks ( } BufferSize = NumberOfBlocks * BlockSize; - Status = EmmcPeimRwMultiBlocks (&Private->Slot[SlotNum], StartLBA, BlockSize, Buffer, BufferSize, TRUE); + Status = EmmcPeimRwMultiBlocks (&Private->Slot[SlotNum], StartLBA, BlockSize, Buffer, BufferSize, TRUE); if (EFI_ERROR (Status)) { return Status; } StartLBA += NumberOfBlocks; - Buffer = (UINT8*)Buffer + BufferSize; + Buffer = (UINT8 *)Buffer + BufferSize; Remaining -= NumberOfBlocks; } + return Status; } @@ -452,14 +458,14 @@ EmmcBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI EmmcBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ) { - EMMC_PEIM_HC_PRIVATE_DATA *Private; + EMMC_PEIM_HC_PRIVATE_DATA *Private; - Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); *NumberBlockDevices = Private->TotalBlkIoDevices; return EFI_SUCCESS; @@ -509,29 +515,29 @@ EmmcBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI EmmcBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - EFI_STATUS Status; - EMMC_PEIM_HC_PRIVATE_DATA *Private; - EFI_PEI_BLOCK_IO_MEDIA Media; - UINT8 SlotNum; - UINT8 MediaNum; - UINT8 Location; - BOOLEAN Found; + EFI_STATUS Status; + EMMC_PEIM_HC_PRIVATE_DATA *Private; + EFI_PEI_BLOCK_IO_MEDIA Media; + UINT8 SlotNum; + UINT8 MediaNum; + UINT8 Location; + BOOLEAN Found; Found = FALSE; Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - Status = EmmcBlockIoPeimGetMediaInfo ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - &Media - ); + Status = EmmcBlockIoPeimGetMediaInfo ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + &Media + ); if (EFI_ERROR (Status)) { return Status; } @@ -540,12 +546,13 @@ EmmcBlockIoPeimGetMediaInfo2 ( MediaNum = 0; for (SlotNum = 0; SlotNum < Private->SlotNum; SlotNum++) { for (MediaNum = 0; MediaNum < Private->Slot[SlotNum].MediaNum; MediaNum++) { - Location ++; + Location++; if (Location == DeviceIndex) { Found = TRUE; break; } } + if (Found) { break; } @@ -592,28 +599,28 @@ EmmcBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI EmmcBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - EMMC_PEIM_HC_PRIVATE_DATA *Private; - - Status = EFI_SUCCESS; - Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - - Status = EmmcBlockIoPeimReadBlocks ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - StartLBA, - BufferSize, - Buffer - ); + EFI_STATUS Status; + EMMC_PEIM_HC_PRIVATE_DATA *Private; + + Status = EFI_SUCCESS; + Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + + Status = EmmcBlockIoPeimReadBlocks ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + StartLBA, + BufferSize, + Buffer + ); return Status; } @@ -636,7 +643,7 @@ EmmcBlockIoPeimEndOfPei ( IN VOID *Ppi ) { - EMMC_PEIM_HC_PRIVATE_DATA *Private; + EMMC_PEIM_HC_PRIVATE_DATA *Private; Private = GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY (NotifyDescriptor); @@ -660,26 +667,26 @@ EmmcBlockIoPeimEndOfPei ( EFI_STATUS EFIAPI InitializeEmmcBlockIoPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - EMMC_PEIM_HC_PRIVATE_DATA *Private; - EDKII_SD_MMC_HOST_CONTROLLER_PPI *SdMmcHcPpi; - UINT32 Index; - UINT32 PartitionIndex; - UINTN *MmioBase; - UINT8 BarNum; - UINT8 SlotNum; - UINT8 MediaNum; - UINT8 Controller; - UINT64 Capacity; - EMMC_EXT_CSD *ExtCsd; - EMMC_HC_SLOT_CAP Capability; - EMMC_PEIM_HC_SLOT *Slot; - UINT32 SecCount; - UINT32 GpSizeMult; + EFI_STATUS Status; + EMMC_PEIM_HC_PRIVATE_DATA *Private; + EDKII_SD_MMC_HOST_CONTROLLER_PPI *SdMmcHcPpi; + UINT32 Index; + UINT32 PartitionIndex; + UINTN *MmioBase; + UINT8 BarNum; + UINT8 SlotNum; + UINT8 MediaNum; + UINT8 Controller; + UINT64 Capacity; + EMMC_EXT_CSD *ExtCsd; + EMMC_HC_SLOT_CAP Capability; + EMMC_PEIM_HC_SLOT *Slot; + UINT32 SecCount; + UINT32 GpSizeMult; // // Shadow this PEIM to run from memory @@ -695,7 +702,7 @@ InitializeEmmcBlockIoPeim ( &gEdkiiPeiSdMmcHostControllerPpiGuid, 0, NULL, - (VOID **) &SdMmcHcPpi + (VOID **)&SdMmcHcPpi ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -724,8 +731,9 @@ InitializeEmmcBlockIoPeim ( Status = EFI_OUT_OF_RESOURCES; break; } - Private->BlkIoPpiList.Ppi = (VOID*)&Private->BlkIoPpi; - Private->BlkIo2PpiList.Ppi = (VOID*)&Private->BlkIo2Ppi; + + Private->BlkIoPpiList.Ppi = (VOID *)&Private->BlkIoPpi; + Private->BlkIo2PpiList.Ppi = (VOID *)&Private->BlkIo2Ppi; // // Initialize the memory pool which will be used in all transactions. // @@ -740,6 +748,7 @@ InitializeEmmcBlockIoPeim ( if (EFI_ERROR (Status)) { continue; } + if (Capability.SlotType != 0x1) { DEBUG ((DEBUG_INFO, "The slot at 0x%x is not embedded slot type\n", MmioBase[Index])); Status = EFI_UNSUPPORTED; @@ -750,10 +759,12 @@ InitializeEmmcBlockIoPeim ( if (EFI_ERROR (Status)) { continue; } + Status = EmmcPeimHcCardDetect (MmioBase[Index]); if (EFI_ERROR (Status)) { continue; } + Status = EmmcPeimHcInitHost (MmioBase[Index]); if (EFI_ERROR (Status)) { continue; @@ -777,6 +788,7 @@ InitializeEmmcBlockIoPeim ( Status = EFI_UNSUPPORTED; continue; } + if ((ExtCsd->PartitioningSupport & BIT0) != BIT0) { DEBUG ((DEBUG_ERROR, "The EMMC device doesn't support Partition Feature!!!\n")); Status = EFI_UNSUPPORTED; @@ -786,7 +798,7 @@ InitializeEmmcBlockIoPeim ( for (PartitionIndex = 0; PartitionIndex < EMMC_PEIM_MAX_PARTITIONS; PartitionIndex++) { switch (PartitionIndex) { case EmmcPartitionUserData: - SecCount = *(UINT32*)&ExtCsd->SecCount; + SecCount = *(UINT32 *)&ExtCsd->SecCount; Capacity = MultU64x32 ((UINT64)SecCount, 0x200); break; case EmmcPartitionBoot1: @@ -798,19 +810,19 @@ InitializeEmmcBlockIoPeim ( break; case EmmcPartitionGP1: GpSizeMult = (ExtCsd->GpSizeMult[0] | (ExtCsd->GpSizeMult[1] << 8) | (ExtCsd->GpSizeMult[2] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP2: GpSizeMult = (ExtCsd->GpSizeMult[3] | (ExtCsd->GpSizeMult[4] << 8) | (ExtCsd->GpSizeMult[5] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP3: GpSizeMult = (ExtCsd->GpSizeMult[6] | (ExtCsd->GpSizeMult[7] << 8) | (ExtCsd->GpSizeMult[8] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP4: GpSizeMult = (ExtCsd->GpSizeMult[9] | (ExtCsd->GpSizeMult[10] << 8) | (ExtCsd->GpSizeMult[11] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; default: ASSERT (FALSE); @@ -820,13 +832,15 @@ InitializeEmmcBlockIoPeim ( MediaNum = Slot->MediaNum; if (Capacity != 0) { Slot->Media[MediaNum].LastBlock = DivU64x32 (Capacity, Slot->Media[MediaNum].BlockSize) - 1; - Slot->PartitionType[MediaNum] = PartitionIndex; + Slot->PartitionType[MediaNum] = PartitionIndex; Private->TotalBlkIoDevices++; Slot->MediaNum++; } } + Private->SlotNum++; } + Controller++; if (!EFI_ERROR (Status)) { diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.h b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.h index 774274e484..f8108c3082 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.h +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcBlockIoPei.h @@ -26,31 +26,31 @@ #include -typedef struct _EMMC_PEIM_HC_PRIVATE_DATA EMMC_PEIM_HC_PRIVATE_DATA; -typedef struct _EMMC_PEIM_HC_SLOT EMMC_PEIM_HC_SLOT; -typedef struct _EMMC_TRB EMMC_TRB; +typedef struct _EMMC_PEIM_HC_PRIVATE_DATA EMMC_PEIM_HC_PRIVATE_DATA; +typedef struct _EMMC_PEIM_HC_SLOT EMMC_PEIM_HC_SLOT; +typedef struct _EMMC_TRB EMMC_TRB; #include "EmmcHci.h" #include "EmmcHcMem.h" -#define EMMC_PEIM_SIG SIGNATURE_32 ('E', 'M', 'C', 'P') -#define EMMC_PEIM_SLOT_SIG SIGNATURE_32 ('E', 'M', 'C', 'S') +#define EMMC_PEIM_SIG SIGNATURE_32 ('E', 'M', 'C', 'P') +#define EMMC_PEIM_SLOT_SIG SIGNATURE_32 ('E', 'M', 'C', 'S') -#define EMMC_PEIM_MAX_SLOTS 6 -#define EMMC_PEIM_MAX_PARTITIONS 8 +#define EMMC_PEIM_MAX_SLOTS 6 +#define EMMC_PEIM_MAX_PARTITIONS 8 struct _EMMC_PEIM_HC_SLOT { - UINT32 Signature; - EFI_PEI_BLOCK_IO2_MEDIA Media[EMMC_PEIM_MAX_PARTITIONS]; - UINT8 MediaNum; - EMMC_PARTITION_TYPE PartitionType[EMMC_PEIM_MAX_PARTITIONS]; - - UINTN EmmcHcBase; - EMMC_HC_SLOT_CAP Capability; - EMMC_CSD Csd; - EMMC_EXT_CSD ExtCsd; - BOOLEAN SectorAddressing; - EMMC_PEIM_HC_PRIVATE_DATA *Private; + UINT32 Signature; + EFI_PEI_BLOCK_IO2_MEDIA Media[EMMC_PEIM_MAX_PARTITIONS]; + UINT8 MediaNum; + EMMC_PARTITION_TYPE PartitionType[EMMC_PEIM_MAX_PARTITIONS]; + + UINTN EmmcHcBase; + EMMC_HC_SLOT_CAP Capability; + EMMC_CSD Csd; + EMMC_EXT_CSD ExtCsd; + BOOLEAN SectorAddressing; + EMMC_PEIM_HC_PRIVATE_DATA *Private; }; struct _EMMC_PEIM_HC_PRIVATE_DATA { @@ -71,27 +71,27 @@ struct _EMMC_PEIM_HC_PRIVATE_DATA { UINT8 TotalBlkIoDevices; }; -#define EMMC_TIMEOUT MultU64x32((UINT64)(3), 1000000) -#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, BlkIoPpi, EMMC_PEIM_SIG) -#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, EMMC_PEIM_SIG) -#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, EMMC_PEIM_SIG) +#define EMMC_TIMEOUT MultU64x32((UINT64)(3), 1000000) +#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, BlkIoPpi, EMMC_PEIM_SIG) +#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, EMMC_PEIM_SIG) +#define GET_EMMC_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, EMMC_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, EMMC_PEIM_SIG) struct _EMMC_TRB { - EMMC_PEIM_HC_SLOT *Slot; - UINT16 BlockSize; + EMMC_PEIM_HC_SLOT *Slot; + UINT16 BlockSize; - EMMC_COMMAND_PACKET *Packet; - VOID *Data; - UINT32 DataLen; - BOOLEAN Read; - EFI_PHYSICAL_ADDRESS DataPhy; - VOID *DataMap; - EMMC_HC_TRANSFER_MODE Mode; + EMMC_COMMAND_PACKET *Packet; + VOID *Data; + UINT32 DataLen; + BOOLEAN Read; + EFI_PHYSICAL_ADDRESS DataPhy; + VOID *DataMap; + EMMC_HC_TRANSFER_MODE Mode; - UINT64 Timeout; + UINT64 Timeout; - EMMC_HC_ADMA_DESC_LINE *AdmaDesc; - UINTN AdmaDescSize; + EMMC_HC_ADMA_DESC_LINE *AdmaDesc; + UINTN AdmaDescSize; }; /** @@ -238,9 +238,9 @@ EmmcBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI EmmcBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -287,10 +287,10 @@ EmmcBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI EmmcBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ); /** @@ -330,12 +330,12 @@ EmmcBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI EmmcBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -349,7 +349,7 @@ EmmcBlockIoPeimReadBlocks2 ( **/ EFI_STATUS EmmcPeimInitMemPool ( - IN EMMC_PEIM_HC_PRIVATE_DATA *Private + IN EMMC_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -363,7 +363,7 @@ EmmcPeimInitMemPool ( **/ EFI_STATUS EmmcPeimFreeMemPool ( - IN EMMC_PEIM_MEM_POOL *Pool + IN EMMC_PEIM_MEM_POOL *Pool ); /** @@ -378,8 +378,8 @@ EmmcPeimFreeMemPool ( **/ VOID * EmmcPeimAllocateMem ( - IN EMMC_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN EMMC_PEIM_MEM_POOL *Pool, + IN UINTN Size ); /** @@ -392,9 +392,9 @@ EmmcPeimAllocateMem ( **/ VOID EmmcPeimFreeMem ( - IN EMMC_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN EMMC_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -426,11 +426,11 @@ IoMmuInit ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -444,7 +444,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -487,9 +487,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.c b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.c index 19a0afcb6d..6778254b61 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.c +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.c @@ -18,25 +18,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EMMC_PEIM_MEM_BLOCK * EmmcPeimAllocMemBlock ( - IN UINTN Pages + IN UINTN Pages ) { - EMMC_PEIM_MEM_BLOCK *Block; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - EFI_STATUS Status; - VOID *TempPtr; + EMMC_PEIM_MEM_BLOCK *Block; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Block = NULL; - Status = PeiServicesAllocatePool (sizeof(EMMC_PEIM_MEM_BLOCK), &TempPtr); + Status = PeiServicesAllocatePool (sizeof (EMMC_PEIM_MEM_BLOCK), &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof(EMMC_PEIM_MEM_BLOCK)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (EMMC_PEIM_MEM_BLOCK)); // // each bit in the bit array represents EMMC_PEIM_MEM_UNIT @@ -44,18 +44,18 @@ EmmcPeimAllocMemBlock ( // ASSERT (EMMC_PEIM_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block = (EMMC_PEIM_MEM_BLOCK*)(UINTN)TempPtr; - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (EMMC_PEIM_MEM_UNIT * 8); + Block = (EMMC_PEIM_MEM_BLOCK *)(UINTN)TempPtr; + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (EMMC_PEIM_MEM_UNIT * 8); Status = PeiServicesAllocatePool (Block->BitsLen, &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, Block->BitsLen); + ZeroMem ((VOID *)(UINTN)TempPtr, Block->BitsLen); - Block->Bits = (UINT8*)(UINTN)TempPtr; + Block->Bits = (UINT8 *)(UINTN)TempPtr; Status = IoMmuAllocateBuffer ( Pages, @@ -67,10 +67,10 @@ EmmcPeimAllocMemBlock ( return NULL; } - ZeroMem ((VOID*)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); + ZeroMem ((VOID *)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); - Block->BufHost = (UINT8 *) (UINTN) BufHost; - Block->Buf = (UINT8 *) (UINTN) MappedAddr; + Block->BufHost = (UINT8 *)(UINTN)BufHost; + Block->Buf = (UINT8 *)(UINTN)MappedAddr; Block->Mapping = Mapping; Block->Next = NULL; @@ -86,8 +86,8 @@ EmmcPeimAllocMemBlock ( **/ VOID EmmcPeimFreeMemBlock ( - IN EMMC_PEIM_MEM_POOL *Pool, - IN EMMC_PEIM_MEM_BLOCK *Block + IN EMMC_PEIM_MEM_POOL *Pool, + IN EMMC_PEIM_MEM_BLOCK *Block ) { ASSERT ((Pool != NULL) && (Block != NULL)); @@ -107,22 +107,22 @@ EmmcPeimFreeMemBlock ( **/ VOID * EmmcPeimAllocMemFromBlock ( - IN EMMC_PEIM_MEM_BLOCK *Block, - IN UINTN Units + IN EMMC_PEIM_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -138,13 +138,12 @@ EmmcPeimAllocMemFromBlock ( } EMMC_PEIM_NEXT_BIT (Byte, Bit); - } else { EMMC_PEIM_NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -155,13 +154,13 @@ EmmcPeimAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!EMMC_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) EMMC_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)EMMC_PEIM_MEM_BIT (Bit)); EMMC_PEIM_NEXT_BIT (Byte, Bit); } @@ -177,8 +176,8 @@ EmmcPeimAllocMemFromBlock ( **/ VOID EmmcPeimInsertMemBlockToPool ( - IN EMMC_PEIM_MEM_BLOCK *Head, - IN EMMC_PEIM_MEM_BLOCK *Block + IN EMMC_PEIM_MEM_BLOCK *Head, + IN EMMC_PEIM_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -197,11 +196,10 @@ EmmcPeimInsertMemBlockToPool ( **/ BOOLEAN EmmcPeimIsMemBlockEmpty ( - IN EMMC_PEIM_MEM_BLOCK *Block + IN EMMC_PEIM_MEM_BLOCK *Block ) { - UINTN Index; - + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -212,8 +210,6 @@ EmmcPeimIsMemBlockEmpty ( return TRUE; } - - /** Initialize the memory management pool for the host controller. @@ -228,9 +224,9 @@ EmmcPeimInitMemPool ( IN EMMC_PEIM_HC_PRIVATE_DATA *Private ) { - EMMC_PEIM_MEM_POOL *Pool; - EFI_STATUS Status; - VOID *TempPtr; + EMMC_PEIM_MEM_POOL *Pool; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Pool = NULL; @@ -240,7 +236,7 @@ EmmcPeimInitMemPool ( return EFI_OUT_OF_RESOURCES; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof (EMMC_PEIM_MEM_POOL)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (EMMC_PEIM_MEM_POOL)); Pool = (EMMC_PEIM_MEM_POOL *)((UINTN)TempPtr); @@ -265,10 +261,10 @@ EmmcPeimInitMemPool ( **/ EFI_STATUS EmmcPeimFreeMemPool ( - IN EMMC_PEIM_MEM_POOL *Pool + IN EMMC_PEIM_MEM_POOL *Pool ) { - EMMC_PEIM_MEM_BLOCK *Block; + EMMC_PEIM_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -296,16 +292,16 @@ EmmcPeimFreeMemPool ( **/ VOID * EmmcPeimAllocateMem ( - IN EMMC_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN EMMC_PEIM_MEM_POOL *Pool, + IN UINTN Size ) { - EMMC_PEIM_MEM_BLOCK *Head; - EMMC_PEIM_MEM_BLOCK *Block; - EMMC_PEIM_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + EMMC_PEIM_MEM_BLOCK *Head; + EMMC_PEIM_MEM_BLOCK *Block; + EMMC_PEIM_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = EMMC_PEIM_MEM_ROUND (Size); @@ -368,22 +364,22 @@ EmmcPeimAllocateMem ( **/ VOID EmmcPeimFreeMem ( - IN EMMC_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN EMMC_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - EMMC_PEIM_MEM_BLOCK *Head; - EMMC_PEIM_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + EMMC_PEIM_MEM_BLOCK *Head; + EMMC_PEIM_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = EMMC_PEIM_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -394,8 +390,8 @@ EmmcPeimFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->Buf) / EMMC_PEIM_MEM_UNIT) / 8; - Bit = ((ToFree - Block->Buf) / EMMC_PEIM_MEM_UNIT) % 8; + Byte = ((ToFree - Block->Buf) / EMMC_PEIM_MEM_UNIT) / 8; + Bit = ((ToFree - Block->Buf) / EMMC_PEIM_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -403,7 +399,7 @@ EmmcPeimFreeMem ( for (Count = 0; Count < (AllocSize / EMMC_PEIM_MEM_UNIT); Count++) { ASSERT (EMMC_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ EMMC_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ EMMC_PEIM_MEM_BIT (Bit)); EMMC_PEIM_NEXT_BIT (Byte, Bit); } @@ -425,5 +421,5 @@ EmmcPeimFreeMem ( EmmcPeimFreeMemBlock (Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.h b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.h index 255ad345d1..d3b6ec545a 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.h +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHcMem.h @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EMMC_PEIM_MEM_H_ #define _EMMC_PEIM_MEM_H_ -#define EMMC_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) +#define EMMC_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) #define EMMC_PEIM_MEM_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & EMMC_PEIM_MEM_BIT(Bit)) == EMMC_PEIM_MEM_BIT(Bit))) @@ -17,28 +17,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _EMMC_PEIM_MEM_BLOCK EMMC_PEIM_MEM_BLOCK; struct _EMMC_PEIM_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - EMMC_PEIM_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + EMMC_PEIM_MEM_BLOCK *Next; }; typedef struct _EMMC_PEIM_MEM_POOL { - EMMC_PEIM_MEM_BLOCK *Head; + EMMC_PEIM_MEM_BLOCK *Head; } EMMC_PEIM_MEM_POOL; // // Memory allocation unit, note that the value must meet EMMC spec alignment requirement. // -#define EMMC_PEIM_MEM_UNIT 128 +#define EMMC_PEIM_MEM_UNIT 128 #define EMMC_PEIM_MEM_UNIT_MASK (EMMC_PEIM_MEM_UNIT - 1) #define EMMC_PEIM_MEM_DEFAULT_PAGES 16 -#define EMMC_PEIM_MEM_ROUND(Len) (((Len) + EMMC_PEIM_MEM_UNIT_MASK) & (~EMMC_PEIM_MEM_UNIT_MASK)) +#define EMMC_PEIM_MEM_ROUND(Len) (((Len) + EMMC_PEIM_MEM_UNIT_MASK) & (~EMMC_PEIM_MEM_UNIT_MASK)) // // Advance the byte and bit to the next bit, adjust byte accordingly. @@ -53,4 +53,3 @@ typedef struct _EMMC_PEIM_MEM_POOL { } while (0) #endif - diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.c b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.c index d7f9e107c4..bafd71e9b5 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.c +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.c @@ -28,13 +28,13 @@ EFI_STATUS EFIAPI EmmcPeimHcRwMmio ( - IN UINTN Address, - IN BOOLEAN Read, - IN UINT8 Count, - IN OUT VOID *Data + IN UINTN Address, + IN BOOLEAN Read, + IN UINT8 Count, + IN OUT VOID *Data ) { - if ((Address == 0) || (Data == NULL)) { + if ((Address == 0) || (Data == NULL)) { return EFI_INVALID_PARAMETER; } @@ -45,31 +45,35 @@ EmmcPeimHcRwMmio ( switch (Count) { case 1: if (Read) { - *(UINT8*)Data = MmioRead8 (Address); + *(UINT8 *)Data = MmioRead8 (Address); } else { - MmioWrite8 (Address, *(UINT8*)Data); + MmioWrite8 (Address, *(UINT8 *)Data); } + break; case 2: if (Read) { - *(UINT16*)Data = MmioRead16 (Address); + *(UINT16 *)Data = MmioRead16 (Address); } else { - MmioWrite16 (Address, *(UINT16*)Data); + MmioWrite16 (Address, *(UINT16 *)Data); } + break; case 4: if (Read) { - *(UINT32*)Data = MmioRead32 (Address); + *(UINT32 *)Data = MmioRead32 (Address); } else { - MmioWrite32 (Address, *(UINT32*)Data); + MmioWrite32 (Address, *(UINT32 *)Data); } + break; case 8: if (Read) { - *(UINT64*)Data = MmioRead64 (Address); + *(UINT64 *)Data = MmioRead64 (Address); } else { - MmioWrite64 (Address, *(UINT64*)Data); + MmioWrite64 (Address, *(UINT64 *)Data); } + break; default: ASSERT (FALSE); @@ -98,14 +102,14 @@ EmmcPeimHcRwMmio ( EFI_STATUS EFIAPI EmmcPeimHcOrMmio ( - IN UINTN Address, - IN UINT8 Count, - IN VOID *OrData + IN UINTN Address, + IN UINT8 Count, + IN VOID *OrData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 Or; + EFI_STATUS Status; + UINT64 Data; + UINT64 Or; Status = EmmcPeimHcRwMmio (Address, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -113,13 +117,13 @@ EmmcPeimHcOrMmio ( } if (Count == 1) { - Or = *(UINT8*) OrData; + Or = *(UINT8 *)OrData; } else if (Count == 2) { - Or = *(UINT16*) OrData; + Or = *(UINT16 *)OrData; } else if (Count == 4) { - Or = *(UINT32*) OrData; + Or = *(UINT32 *)OrData; } else if (Count == 8) { - Or = *(UINT64*) OrData; + Or = *(UINT64 *)OrData; } else { return EFI_INVALID_PARAMETER; } @@ -149,14 +153,14 @@ EmmcPeimHcOrMmio ( EFI_STATUS EFIAPI EmmcPeimHcAndMmio ( - IN UINTN Address, - IN UINT8 Count, - IN VOID *AndData + IN UINTN Address, + IN UINT8 Count, + IN VOID *AndData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 And; + EFI_STATUS Status; + UINT64 Data; + UINT64 And; Status = EmmcPeimHcRwMmio (Address, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -164,13 +168,13 @@ EmmcPeimHcAndMmio ( } if (Count == 1) { - And = *(UINT8*) AndData; + And = *(UINT8 *)AndData; } else if (Count == 2) { - And = *(UINT16*) AndData; + And = *(UINT16 *)AndData; } else if (Count == 4) { - And = *(UINT32*) AndData; + And = *(UINT32 *)AndData; } else if (Count == 8) { - And = *(UINT64*) AndData; + And = *(UINT64 *)AndData; } else { return EFI_INVALID_PARAMETER; } @@ -198,14 +202,14 @@ EmmcPeimHcAndMmio ( EFI_STATUS EFIAPI EmmcPeimHcCheckMmioSet ( - IN UINTN Address, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue + IN UINTN Address, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue ) { - EFI_STATUS Status; - UINT64 Value; + EFI_STATUS Status; + UINT64 Value; // // Access PCI MMIO space to see if the value is the tested one. @@ -245,15 +249,15 @@ EmmcPeimHcCheckMmioSet ( EFI_STATUS EFIAPI EmmcPeimHcWaitMmioSet ( - IN UINTN Address, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue, - IN UINT64 Timeout + IN UINTN Address, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue, + IN UINT64 Timeout ) { - EFI_STATUS Status; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -294,11 +298,11 @@ EmmcPeimHcWaitMmioSet ( **/ EFI_STATUS EmmcPeimHcReset ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT8 SwReset; + EFI_STATUS Status; + UINT8 SwReset; SwReset = 0xFF; Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_SW_RST, FALSE, sizeof (SwReset), &SwReset); @@ -319,6 +323,7 @@ EmmcPeimHcReset ( DEBUG ((DEBUG_INFO, "EmmcPeimHcReset: reset done with %r\n", Status)); return Status; } + // // Enable all interrupt after reset all. // @@ -339,25 +344,26 @@ EmmcPeimHcReset ( **/ EFI_STATUS EmmcPeimHcEnableInterrupt ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT16 IntStatus; + EFI_STATUS Status; + UINT16 IntStatus; // // Enable all bits in Error Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); if (EFI_ERROR (Status)) { return Status; } + // // Enable all bits in Normal Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); return Status; } @@ -374,12 +380,12 @@ EmmcPeimHcEnableInterrupt ( **/ EFI_STATUS EmmcPeimHcGetCapability ( - IN UINTN Bar, - OUT EMMC_HC_SLOT_CAP *Capability + IN UINTN Bar, + OUT EMMC_HC_SLOT_CAP *Capability ) { - EFI_STATUS Status; - UINT64 Cap; + EFI_STATUS Status; + UINT64 Cap; Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_CAP, TRUE, sizeof (Cap), &Cap); if (EFI_ERROR (Status)) { @@ -406,12 +412,12 @@ EmmcPeimHcGetCapability ( **/ EFI_STATUS EmmcPeimHcCardDetect ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT16 Data; - UINT32 PresentState; + EFI_STATUS Status; + UINT16 Data; + UINT32 PresentState; // // Check Normal Interrupt Status Register @@ -460,12 +466,12 @@ EmmcPeimHcCardDetect ( **/ EFI_STATUS EmmcPeimHcStopClock ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT32 PresentState; - UINT16 ClockCtrl; + EFI_STATUS Status; + UINT32 PresentState; + UINT16 ClockCtrl; // // Ensure no SD transactions are occurring on the SD Bus by @@ -486,8 +492,8 @@ EmmcPeimHcStopClock ( // // Set SD Clock Enable in the Clock Control register to 0 // - ClockCtrl = (UINT16)~BIT2; - Status = EmmcPeimHcAndMmio (Bar + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + ClockCtrl = (UINT16) ~BIT2; + Status = EmmcPeimHcAndMmio (Bar + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); return Status; } @@ -506,18 +512,18 @@ EmmcPeimHcStopClock ( **/ EFI_STATUS EmmcPeimHcClockSupply ( - IN UINTN Bar, - IN UINT64 ClockFreq + IN UINTN Bar, + IN UINT64 ClockFreq ) { - EFI_STATUS Status; - EMMC_HC_SLOT_CAP Capability; - UINT32 BaseClkFreq; - UINT32 SettingFreq; - UINT32 Divisor; - UINT32 Remainder; - UINT16 ControllerVer; - UINT16 ClockCtrl; + EFI_STATUS Status; + EMMC_HC_SLOT_CAP Capability; + UINT32 BaseClkFreq; + UINT32 SettingFreq; + UINT32 Divisor; + UINT32 Remainder; + UINT16 ControllerVer; + UINT16 ClockCtrl; // // Calculate a divisor for SD clock frequency @@ -526,6 +532,7 @@ EmmcPeimHcClockSupply ( if (EFI_ERROR (Status)) { return Status; } + ASSERT (Capability.BaseClkFreq != 0); BaseClkFreq = Capability.BaseClkFreq; @@ -551,8 +558,9 @@ EmmcPeimHcClockSupply ( if ((ClockFreq == SettingFreq) && (Remainder == 0)) { break; } + if ((ClockFreq == SettingFreq) && (Remainder != 0)) { - SettingFreq ++; + SettingFreq++; } } @@ -562,6 +570,7 @@ EmmcPeimHcClockSupply ( if (EFI_ERROR (Status)) { return Status; } + // // Set SDCLK Frequency Select and Internal Clock Enable fields in Clock Control register. // @@ -575,6 +584,7 @@ EmmcPeimHcClockSupply ( if (((Divisor - 1) & Divisor) != 0) { Divisor = 1 << (HighBitSet32 (Divisor) + 1); } + ASSERT (Divisor <= 0x80); ClockCtrl = (Divisor & 0xFF) << 8; } else { @@ -594,7 +604,7 @@ EmmcPeimHcClockSupply ( // Supply clock frequency with specified divisor // ClockCtrl |= BIT0; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Set SDCLK Frequency Select and Internal Clock Enable fields fails\n")); return Status; @@ -618,7 +628,7 @@ EmmcPeimHcClockSupply ( // Set SD Clock Enable in the Clock Control register to 1 // ClockCtrl = BIT2; - Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); return Status; } @@ -637,17 +647,17 @@ EmmcPeimHcClockSupply ( **/ EFI_STATUS EmmcPeimHcPowerControl ( - IN UINTN Bar, - IN UINT8 PowerCtrl + IN UINTN Bar, + IN UINT8 PowerCtrl ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Clr SD Bus Power // - PowerCtrl &= (UINT8)~BIT0; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + PowerCtrl &= (UINT8) ~BIT0; + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); if (EFI_ERROR (Status)) { return Status; } @@ -656,7 +666,7 @@ EmmcPeimHcPowerControl ( // Set SD Bus Voltage Select and SD Bus Power fields in Power Control Register // PowerCtrl |= BIT0; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); return Status; } @@ -675,32 +685,34 @@ EmmcPeimHcPowerControl ( **/ EFI_STATUS EmmcPeimHcSetBusWidth ( - IN UINTN Bar, - IN UINT16 BusWidth + IN UINTN Bar, + IN UINT16 BusWidth ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (BusWidth == 1) { - HostCtrl1 = (UINT8)~(BIT5 | BIT1); - Status = EmmcPeimHcAndMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 = (UINT8) ~(BIT5 | BIT1); + Status = EmmcPeimHcAndMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 4) { Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } + HostCtrl1 |= BIT1; - HostCtrl1 &= (UINT8)~BIT5; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 &= (UINT8) ~BIT5; + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 8) { Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } - HostCtrl1 &= (UINT8)~BIT1; + + HostCtrl1 &= (UINT8) ~BIT1; HostCtrl1 |= BIT5; - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else { ASSERT (FALSE); return EFI_INVALID_PARAMETER; @@ -720,12 +732,12 @@ EmmcPeimHcSetBusWidth ( **/ EFI_STATUS EmmcPeimHcInitClockFreq ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - EMMC_HC_SLOT_CAP Capability; - UINT32 InitFreq; + EFI_STATUS Status; + EMMC_HC_SLOT_CAP Capability; + UINT32 InitFreq; // // Calculate a divisor for SD clock frequency @@ -741,11 +753,12 @@ EmmcPeimHcInitClockFreq ( // return EFI_UNSUPPORTED; } + // // Supply 400KHz clock frequency at initialization phase. // InitFreq = 400; - Status = EmmcPeimHcClockSupply (Bar, InitFreq); + Status = EmmcPeimHcClockSupply (Bar, InitFreq); return Status; } @@ -762,13 +775,13 @@ EmmcPeimHcInitClockFreq ( **/ EFI_STATUS EmmcPeimHcInitPowerVoltage ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - EMMC_HC_SLOT_CAP Capability; - UINT8 MaxVoltage; - UINT8 HostCtrl2; + EFI_STATUS Status; + EMMC_HC_SLOT_CAP Capability; + UINT8 MaxVoltage; + UINT8 HostCtrl2; // // Get the support voltage of the Host Controller @@ -777,6 +790,7 @@ EmmcPeimHcInitPowerVoltage ( if (EFI_ERROR (Status)) { return Status; } + // // Calculate supported maximum voltage according to SD Bus Voltage Select // @@ -796,10 +810,11 @@ EmmcPeimHcInitPowerVoltage ( // MaxVoltage = 0x0A; HostCtrl2 = BIT3; - Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + MicroSecondDelay (5000); } else { ASSERT (FALSE); @@ -827,11 +842,11 @@ EmmcPeimHcInitPowerVoltage ( **/ EFI_STATUS EmmcPeimHcInitTimeoutCtrl ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT8 Timeout; + EFI_STATUS Status; + UINT8 Timeout; Timeout = 0x0E; Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_TIMEOUT_CTRL, FALSE, sizeof (Timeout), &Timeout); @@ -851,10 +866,10 @@ EmmcPeimHcInitTimeoutCtrl ( **/ EFI_STATUS EmmcPeimHcInitHost ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EmmcPeimHcInitClockFreq (Bar); if (EFI_ERROR (Status)) { @@ -882,18 +897,18 @@ EmmcPeimHcInitHost ( **/ EFI_STATUS EmmcPeimHcLedOnOff ( - IN UINTN Bar, - IN BOOLEAN On + IN UINTN Bar, + IN BOOLEAN On ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (On) { HostCtrl1 = BIT0; Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else { - HostCtrl1 = (UINT8)~BIT0; + HostCtrl1 = (UINT8) ~BIT0; Status = EmmcPeimHcAndMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } @@ -913,15 +928,15 @@ EmmcPeimHcLedOnOff ( **/ EFI_STATUS BuildAdmaDescTable ( - IN EMMC_TRB *Trb + IN EMMC_TRB *Trb ) { - EFI_PHYSICAL_ADDRESS Data; - UINT64 DataLen; - UINT64 Entries; - UINT32 Index; - UINT64 Remaining; - UINT32 Address; + EFI_PHYSICAL_ADDRESS Data; + UINT64 DataLen; + UINT64 Entries; + UINT32 Index; + UINT64 Remaining; + UINT32 Address; Data = Trb->DataPhy; DataLen = Trb->DataLen; @@ -931,6 +946,7 @@ BuildAdmaDescTable ( if ((Data >= 0x100000000ul) || ((Data + DataLen) > 0x100000000ul)) { return EFI_INVALID_PARAMETER; } + // // Address field shall be set on 32-bit boundary (Lower 2-bit is always set to 0) // for 32-bit address descriptor table. @@ -951,14 +967,14 @@ BuildAdmaDescTable ( Address = (UINT32)Data; for (Index = 0; Index < Entries; Index++) { if (Remaining <= ADMA_MAX_DATA_PER_LINE) { - Trb->AdmaDesc[Index].Valid = 1; - Trb->AdmaDesc[Index].Act = 2; + Trb->AdmaDesc[Index].Valid = 1; + Trb->AdmaDesc[Index].Act = 2; Trb->AdmaDesc[Index].Length = (UINT16)Remaining; Trb->AdmaDesc[Index].Address = Address; break; } else { - Trb->AdmaDesc[Index].Valid = 1; - Trb->AdmaDesc[Index].Act = 2; + Trb->AdmaDesc[Index].Valid = 1; + Trb->AdmaDesc[Index].Act = 2; Trb->AdmaDesc[Index].Length = 0; Trb->AdmaDesc[Index].Address = Address; } @@ -985,15 +1001,15 @@ BuildAdmaDescTable ( **/ EMMC_TRB * EmmcPeimCreateTrb ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN EMMC_COMMAND_PACKET *Packet + IN EMMC_PEIM_HC_SLOT *Slot, + IN EMMC_COMMAND_PACKET *Packet ) { - EMMC_TRB *Trb; - EFI_STATUS Status; - EMMC_HC_SLOT_CAP Capability; - EDKII_IOMMU_OPERATION MapOp; - UINTN MapLength; + EMMC_TRB *Trb; + EFI_STATUS Status; + EMMC_HC_SLOT_CAP Capability; + EDKII_IOMMU_OPERATION MapOp; + UINTN MapLength; // // Calculate a divisor for SD clock frequency @@ -1043,7 +1059,7 @@ EmmcPeimCreateTrb ( if (Trb->DataLen != 0) { MapLength = Trb->DataLen; - Status = IoMmuMap (MapOp, Trb->Data, &MapLength, &Trb->DataPhy, &Trb->DataMap); + Status = IoMmuMap (MapOp, Trb->Data, &MapLength, &Trb->DataPhy, &Trb->DataMap); if (EFI_ERROR (Status) || (MapLength != Trb->DataLen)) { DEBUG ((DEBUG_ERROR, "EmmcPeimCreateTrb: Fail to map data buffer.\n")); @@ -1055,7 +1071,7 @@ EmmcPeimCreateTrb ( Trb->Mode = EmmcNoData; } else if (Capability.Adma2 != 0) { Trb->Mode = EmmcAdmaMode; - Status = BuildAdmaDescTable (Trb); + Status = BuildAdmaDescTable (Trb); if (EFI_ERROR (Status)) { goto Error; } @@ -1065,6 +1081,7 @@ EmmcPeimCreateTrb ( Trb->Mode = EmmcPioMode; } } + return Trb; Error: @@ -1080,7 +1097,7 @@ Error: **/ VOID EmmcPeimFreeTrb ( - IN EMMC_TRB *Trb + IN EMMC_TRB *Trb ) { if ((Trb != NULL) && (Trb->DataMap != NULL)) { @@ -1094,6 +1111,7 @@ EmmcPeimFreeTrb ( if (Trb != NULL) { FreePool (Trb); } + return; } @@ -1110,19 +1128,20 @@ EmmcPeimFreeTrb ( **/ EFI_STATUS EmmcPeimCheckTrbEnv ( - IN UINTN Bar, - IN EMMC_TRB *Trb + IN UINTN Bar, + IN EMMC_TRB *Trb ) { - EFI_STATUS Status; - EMMC_COMMAND_PACKET *Packet; - UINT32 PresentState; + EFI_STATUS Status; + EMMC_COMMAND_PACKET *Packet; + UINT32 PresentState; Packet = Trb->Packet; if ((Packet->EmmcCmdBlk->CommandType == EmmcCommandTypeAdtc) || (Packet->EmmcCmdBlk->ResponseType == EmmcResponceTypeR1b) || - (Packet->EmmcCmdBlk->ResponseType == EmmcResponceTypeR5b)) { + (Packet->EmmcCmdBlk->ResponseType == EmmcResponceTypeR5b)) + { // // Wait Command Inhibit (CMD) and Command Inhibit (DAT) in // the Present State register to be 0 @@ -1159,14 +1178,14 @@ EmmcPeimCheckTrbEnv ( **/ EFI_STATUS EmmcPeimWaitTrbEnv ( - IN UINTN Bar, - IN EMMC_TRB *Trb + IN UINTN Bar, + IN EMMC_TRB *Trb ) { - EFI_STATUS Status; - EMMC_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + EMMC_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; // // Wait Command Complete Interrupt Status bit in Normal Interrupt Status Register @@ -1187,6 +1206,7 @@ EmmcPeimWaitTrbEnv ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -1210,21 +1230,21 @@ EmmcPeimWaitTrbEnv ( **/ EFI_STATUS EmmcPeimExecTrb ( - IN UINTN Bar, - IN EMMC_TRB *Trb + IN UINTN Bar, + IN EMMC_TRB *Trb ) { - EFI_STATUS Status; - EMMC_COMMAND_PACKET *Packet; - UINT16 Cmd; - UINT16 IntStatus; - UINT32 Argument; - UINT16 BlkCount; - UINT16 BlkSize; - UINT16 TransMode; - UINT8 HostCtrl1; - UINT32 SdmaAddr; - UINT64 AdmaAddr; + EFI_STATUS Status; + EMMC_COMMAND_PACKET *Packet; + UINT16 Cmd; + UINT16 IntStatus; + UINT32 Argument; + UINT16 BlkCount; + UINT16 BlkSize; + UINT16 TransMode; + UINT8 HostCtrl1; + UINT32 SdmaAddr; + UINT64 AdmaAddr; Packet = Trb->Packet; // @@ -1235,6 +1255,7 @@ EmmcPeimExecTrb ( if (EFI_ERROR (Status)) { return Status; } + // // Clear all bits in Normal Interrupt Status Register // @@ -1243,12 +1264,13 @@ EmmcPeimExecTrb ( if (EFI_ERROR (Status)) { return Status; } + // // Set Host Control 1 register DMA Select field // if (Trb->Mode == EmmcAdmaMode) { HostCtrl1 = BIT4; - Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = EmmcPeimHcOrMmio (Bar + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } @@ -1295,7 +1317,7 @@ EmmcPeimExecTrb ( BlkCount = (UINT16)(Trb->DataLen / Trb->BlockSize); } - Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_BLK_COUNT, FALSE, sizeof (BlkCount), &BlkCount); + Status = EmmcPeimHcRwMmio (Bar + EMMC_HC_BLK_COUNT, FALSE, sizeof (BlkCount), &BlkCount); if (EFI_ERROR (Status)) { return Status; } @@ -1311,9 +1333,11 @@ EmmcPeimExecTrb ( if (Trb->Mode != EmmcPioMode) { TransMode |= BIT0; } + if (Trb->Read) { TransMode |= BIT4; } + if (BlkCount > 1) { TransMode |= BIT5 | BIT1; } @@ -1324,10 +1348,11 @@ EmmcPeimExecTrb ( return Status; } - Cmd = (UINT16)LShiftU64(Packet->EmmcCmdBlk->CommandIndex, 8); + Cmd = (UINT16)LShiftU64 (Packet->EmmcCmdBlk->CommandIndex, 8); if (Packet->EmmcCmdBlk->CommandType == EmmcCommandTypeAdtc) { Cmd |= BIT5; } + // // Convert ResponseType to value // @@ -1341,7 +1366,7 @@ EmmcPeimExecTrb ( break; case EmmcResponceTypeR2: Cmd |= (BIT0 | BIT3); - break; + break; case EmmcResponceTypeR3: case EmmcResponceTypeR4: Cmd |= BIT1; @@ -1355,6 +1380,7 @@ EmmcPeimExecTrb ( break; } } + // // Execute cmd // @@ -1375,18 +1401,18 @@ EmmcPeimExecTrb ( **/ EFI_STATUS EmmcPeimCheckTrbResult ( - IN UINTN Bar, - IN EMMC_TRB *Trb + IN UINTN Bar, + IN EMMC_TRB *Trb ) { - EFI_STATUS Status; - EMMC_COMMAND_PACKET *Packet; - UINT16 IntStatus; - UINT32 Response[4]; - UINT32 SdmaAddr; - UINT8 Index; - UINT8 SwReset; - UINT32 PioLength; + EFI_STATUS Status; + EMMC_COMMAND_PACKET *Packet; + UINT16 IntStatus; + UINT32 Response[4]; + UINT32 SdmaAddr; + UINT8 Index; + UINT8 SwReset; + UINT32 PioLength; SwReset = 0; Packet = Trb->Packet; @@ -1402,6 +1428,7 @@ EmmcPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + // // Check Transfer Complete bit is set or not. // @@ -1430,6 +1457,7 @@ EmmcPeimCheckTrbResult ( goto Done; } + // // Check if there is a error happened during cmd execution. // If yes, then do error recovery procedure to follow SD Host Controller @@ -1449,6 +1477,7 @@ EmmcPeimCheckTrbResult ( if ((IntStatus & 0x0F) != 0) { SwReset |= BIT1; } + if ((IntStatus & 0xF0) != 0) { SwReset |= BIT2; } @@ -1462,6 +1491,7 @@ EmmcPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + Status = EmmcPeimHcWaitMmioSet ( Bar + EMMC_HC_SW_RST, sizeof (SwReset), @@ -1476,6 +1506,7 @@ EmmcPeimCheckTrbResult ( Status = EFI_DEVICE_ERROR; goto Done; } + // // Check if DMA interrupt is signalled for the SDMA transfer. // @@ -1493,6 +1524,7 @@ EmmcPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + // // Update SDMA Address register. // @@ -1506,12 +1538,14 @@ EmmcPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + Trb->DataPhy = (UINT32)(UINTN)SdmaAddr; } if ((Packet->EmmcCmdBlk->CommandType != EmmcCommandTypeAdtc) && (Packet->EmmcCmdBlk->ResponseType != EmmcResponceTypeR1b) && - (Packet->EmmcCmdBlk->ResponseType != EmmcResponceTypeR5b)) { + (Packet->EmmcCmdBlk->ResponseType != EmmcResponceTypeR5b)) + { if ((IntStatus & BIT0) == BIT0) { Status = EFI_SUCCESS; goto Done; @@ -1534,8 +1568,9 @@ EmmcPeimCheckTrbResult ( // Read data out from Buffer Port register // for (PioLength = 0; PioLength < Trb->DataLen; PioLength += 4) { - EmmcPeimHcRwMmio (Bar + EMMC_HC_BUF_DAT_PORT, TRUE, 4, (UINT8*)Trb->Data + PioLength); + EmmcPeimHcRwMmio (Bar + EMMC_HC_BUF_DAT_PORT, TRUE, 4, (UINT8 *)Trb->Data + PioLength); } + Status = EFI_SUCCESS; goto Done; } @@ -1560,6 +1595,7 @@ Done: return Status; } } + CopyMem (Packet->EmmcStatusBlk, Response, sizeof (Response)); } } @@ -1583,14 +1619,14 @@ Done: **/ EFI_STATUS EmmcPeimWaitTrbResult ( - IN UINTN Bar, - IN EMMC_TRB *Trb + IN UINTN Bar, + IN EMMC_TRB *Trb ) { - EFI_STATUS Status; - EMMC_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + EMMC_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; Packet = Trb->Packet; // @@ -1611,6 +1647,7 @@ EmmcPeimWaitTrbResult ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -1655,12 +1692,12 @@ EmmcPeimWaitTrbResult ( EFI_STATUS EFIAPI EmmcPeimExecCmd ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN OUT EMMC_COMMAND_PACKET *Packet + IN EMMC_PEIM_HC_SLOT *Slot, + IN OUT EMMC_COMMAND_PACKET *Packet ) { - EFI_STATUS Status; - EMMC_TRB *Trb; + EFI_STATUS Status; + EMMC_TRB *Trb; if (Packet == NULL) { return EFI_INVALID_PARAMETER; @@ -1718,13 +1755,13 @@ Done: **/ EFI_STATUS EmmcPeimReset ( - IN EMMC_PEIM_HC_SLOT *Slot + IN EMMC_PEIM_HC_SLOT *Slot ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1732,11 +1769,11 @@ EmmcPeimReset ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_GO_IDLE_STATE; - EmmcCmdBlk.CommandType = EmmcCommandTypeBc; - EmmcCmdBlk.ResponseType = 0; + EmmcCmdBlk.CommandIndex = EMMC_GO_IDLE_STATE; + EmmcCmdBlk.CommandType = EmmcCommandTypeBc; + EmmcCmdBlk.ResponseType = 0; EmmcCmdBlk.CommandArgument = 0; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1759,14 +1796,14 @@ EmmcPeimReset ( **/ EFI_STATUS EmmcPeimGetOcr ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN OUT UINT32 *Argument + IN EMMC_PEIM_HC_SLOT *Slot, + IN OUT UINT32 *Argument ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1774,11 +1811,11 @@ EmmcPeimGetOcr ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SEND_OP_COND; - EmmcCmdBlk.CommandType = EmmcCommandTypeBcr; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR3; + EmmcCmdBlk.CommandIndex = EMMC_SEND_OP_COND; + EmmcCmdBlk.CommandType = EmmcCommandTypeBcr; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR3; EmmcCmdBlk.CommandArgument = *Argument; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1806,13 +1843,13 @@ EmmcPeimGetOcr ( **/ EFI_STATUS EmmcPeimGetAllCid ( - IN EMMC_PEIM_HC_SLOT *Slot + IN EMMC_PEIM_HC_SLOT *Slot ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1820,11 +1857,11 @@ EmmcPeimGetAllCid ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_ALL_SEND_CID; - EmmcCmdBlk.CommandType = EmmcCommandTypeBcr; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR2; + EmmcCmdBlk.CommandIndex = EMMC_ALL_SEND_CID; + EmmcCmdBlk.CommandType = EmmcCommandTypeBcr; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR2; EmmcCmdBlk.CommandArgument = 0; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1847,14 +1884,14 @@ EmmcPeimGetAllCid ( **/ EFI_STATUS EmmcPeimSetRca ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1862,11 +1899,11 @@ EmmcPeimSetRca ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SET_RELATIVE_ADDR; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SET_RELATIVE_ADDR; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = Rca << 16; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1892,15 +1929,15 @@ EmmcPeimSetRca ( **/ EFI_STATUS EmmcPeimGetCsd ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - OUT EMMC_CSD *Csd + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + OUT EMMC_CSD *Csd ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1908,11 +1945,11 @@ EmmcPeimGetCsd ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SEND_CSD; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR2; + EmmcCmdBlk.CommandIndex = EMMC_SEND_CSD; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR2; EmmcCmdBlk.CommandArgument = Rca << 16; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1920,7 +1957,7 @@ EmmcPeimGetCsd ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Csd) + 1, &EmmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); + CopyMem (((UINT8 *)Csd) + 1, &EmmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); } return Status; @@ -1940,14 +1977,14 @@ EmmcPeimGetCsd ( **/ EFI_STATUS EmmcPeimSelect ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1955,11 +1992,11 @@ EmmcPeimSelect ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = Rca << 16; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -1981,14 +2018,14 @@ EmmcPeimSelect ( **/ EFI_STATUS EmmcPeimGetExtCsd ( - IN EMMC_PEIM_HC_SLOT *Slot, - OUT EMMC_EXT_CSD *ExtCsd + IN EMMC_PEIM_HC_SLOT *Slot, + OUT EMMC_EXT_CSD *ExtCsd ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -1996,11 +2033,11 @@ EmmcPeimGetExtCsd ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; - EmmcCmdBlk.CommandType = EmmcCommandTypeAdtc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; + EmmcCmdBlk.CommandType = EmmcCommandTypeAdtc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = 0x00000000; Packet.InDataBuffer = ExtCsd; @@ -2028,17 +2065,17 @@ EmmcPeimGetExtCsd ( **/ EFI_STATUS EmmcPeimSwitch ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT8 Access, - IN UINT8 Index, - IN UINT8 Value, - IN UINT8 CmdSet + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT8 Access, + IN UINT8 Index, + IN UINT8 Value, + IN UINT8 CmdSet ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -2046,11 +2083,11 @@ EmmcPeimSwitch ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SWITCH; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1b; + EmmcCmdBlk.CommandIndex = EMMC_SWITCH; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1b; EmmcCmdBlk.CommandArgument = (Access << 24) | (Index << 16) | (Value << 8) | CmdSet; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -2073,15 +2110,15 @@ EmmcPeimSwitch ( **/ EFI_STATUS EmmcPeimSendStatus ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - OUT UINT32 *DevStatus + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + OUT UINT32 *DevStatus ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -2089,11 +2126,11 @@ EmmcPeimSendStatus ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = Rca << 16; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -2119,14 +2156,14 @@ EmmcPeimSendStatus ( **/ EFI_STATUS EmmcPeimSetBlkCount ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT16 BlockCount + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT16 BlockCount ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -2136,9 +2173,9 @@ EmmcPeimSetBlkCount ( Packet.EmmcStatusBlk = &EmmcStatusBlk; Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SET_BLOCK_COUNT; - EmmcCmdBlk.CommandType = EmmcCommandTypeAc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SET_BLOCK_COUNT; + EmmcCmdBlk.CommandType = EmmcCommandTypeAc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = BlockCount; Status = EmmcPeimExecCmd (Slot, &Packet); @@ -2165,18 +2202,18 @@ EmmcPeimSetBlkCount ( **/ EFI_STATUS EmmcPeimRwMultiBlocks ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN EMMC_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -2191,7 +2228,7 @@ EmmcPeimRwMultiBlocks ( // transfer speed (2.4MB/s). // Refer to eMMC 5.0 spec section 6.9.1 for details. // - Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000;; + Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000; if (IsRead) { Packet.InDataBuffer = Buffer; @@ -2237,15 +2274,15 @@ EmmcPeimRwMultiBlocks ( **/ EFI_STATUS EmmcPeimSendTuningBlk ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT8 BusWidth + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT8 BusWidth ) { - EMMC_COMMAND_BLOCK EmmcCmdBlk; - EMMC_STATUS_BLOCK EmmcStatusBlk; - EMMC_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 TuningBlock[128]; + EMMC_COMMAND_BLOCK EmmcCmdBlk; + EMMC_STATUS_BLOCK EmmcStatusBlk; + EMMC_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 TuningBlock[128]; ZeroMem (&EmmcCmdBlk, sizeof (EmmcCmdBlk)); ZeroMem (&EmmcStatusBlk, sizeof (EmmcStatusBlk)); @@ -2253,11 +2290,11 @@ EmmcPeimSendTuningBlk ( Packet.EmmcCmdBlk = &EmmcCmdBlk; Packet.EmmcStatusBlk = &EmmcStatusBlk; - Packet.Timeout = EMMC_TIMEOUT; + Packet.Timeout = EMMC_TIMEOUT; - EmmcCmdBlk.CommandIndex = EMMC_SEND_TUNING_BLOCK; - EmmcCmdBlk.CommandType = EmmcCommandTypeAdtc; - EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; + EmmcCmdBlk.CommandIndex = EMMC_SEND_TUNING_BLOCK; + EmmcCmdBlk.CommandType = EmmcCommandTypeAdtc; + EmmcCmdBlk.ResponseType = EmmcResponceTypeR1; EmmcCmdBlk.CommandArgument = 0; Packet.InDataBuffer = TuningBlock; @@ -2290,22 +2327,23 @@ EmmcPeimSendTuningBlk ( **/ EFI_STATUS EmmcPeimTuningClkForHs200 ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT8 BusWidth + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 HostCtrl2; - UINT8 Retry; + EFI_STATUS Status; + UINT8 HostCtrl2; + UINT8 Retry; // // Notify the host that the sampling clock tuning procedure starts. // HostCtrl2 = BIT6; - Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + // // Ask the device to send a sequence of tuning blocks till the tuning procedure is done. // @@ -2334,11 +2372,12 @@ EmmcPeimTuningClkForHs200 ( // // Abort the tuning procedure and reset the tuning circuit. // - HostCtrl2 = (UINT8)~(BIT6 | BIT7); - Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~(BIT6 | BIT7); + Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + return EFI_DEVICE_ERROR; } @@ -2360,18 +2399,18 @@ EmmcPeimTuningClkForHs200 ( **/ EFI_STATUS EmmcPeimSwitchBusWidth ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - IN BOOLEAN IsDdr, - IN UINT8 BusWidth + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + IN BOOLEAN IsDdr, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 Access; - UINT8 Index; - UINT8 Value; - UINT8 CmdSet; - UINT32 DevStatus; + EFI_STATUS Status; + UINT8 Access; + UINT8 Index; + UINT8 Value; + UINT8 CmdSet; + UINT32 DevStatus; // // Write Byte, the Value field is written into the byte pointed by Index. @@ -2400,6 +2439,7 @@ EmmcPeimSwitchBusWidth ( if (EFI_ERROR (Status)) { return Status; } + // // Check the switch operation is really successful or not. // @@ -2429,18 +2469,18 @@ EmmcPeimSwitchBusWidth ( **/ EFI_STATUS EmmcPeimSwitchClockFreq ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - IN UINT8 HsTiming, - IN UINT32 ClockFreq + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + IN UINT8 HsTiming, + IN UINT32 ClockFreq ) { - EFI_STATUS Status; - UINT8 Access; - UINT8 Index; - UINT8 Value; - UINT8 CmdSet; - UINT32 DevStatus; + EFI_STATUS Status; + UINT8 Access; + UINT8 Index; + UINT8 Value; + UINT8 CmdSet; + UINT32 DevStatus; // // Write Byte, the Value field is written into the byte pointed by Index. @@ -2459,12 +2499,14 @@ EmmcPeimSwitchClockFreq ( if (EFI_ERROR (Status)) { return Status; } + // // Check the switch operation is really successful or not. // if ((DevStatus & BIT7) != 0) { return EFI_DEVICE_ERROR; } + // // Convert the clock freq unit from MHz to KHz. // @@ -2492,36 +2534,38 @@ EmmcPeimSwitchClockFreq ( **/ EFI_STATUS EmmcPeimSwitchToHighSpeed ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - IN UINT32 ClockFreq, - IN BOOLEAN IsDdr, - IN UINT8 BusWidth + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + IN UINT32 ClockFreq, + IN BOOLEAN IsDdr, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 HsTiming; - UINT8 HostCtrl1; - UINT8 HostCtrl2; + EFI_STATUS Status; + UINT8 HsTiming; + UINT8 HostCtrl1; + UINT8 HostCtrl2; Status = EmmcPeimSwitchBusWidth (Slot, Rca, IsDdr, BusWidth); if (EFI_ERROR (Status)) { return Status; } + // // Set to High Speed timing // HostCtrl1 = BIT2; - Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } - HostCtrl2 = (UINT8)~0x7; - Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~0x7; + Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + if (IsDdr) { HostCtrl2 = BIT2; } else if (ClockFreq == 52) { @@ -2529,13 +2573,14 @@ EmmcPeimSwitchToHighSpeed ( } else { HostCtrl2 = 0; } + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } HsTiming = 1; - Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); + Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); return Status; } @@ -2557,16 +2602,16 @@ EmmcPeimSwitchToHighSpeed ( **/ EFI_STATUS EmmcPeimSwitchToHS200 ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - IN UINT32 ClockFreq, - IN UINT8 BusWidth + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + IN UINT32 ClockFreq, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT8 HsTiming; - UINT8 HostCtrl2; - UINT16 ClockCtrl; + EFI_STATUS Status; + UINT8 HsTiming; + UINT8 HostCtrl2; + UINT16 ClockCtrl; if ((BusWidth != 4) && (BusWidth != 8)) { return EFI_INVALID_PARAMETER; @@ -2576,6 +2621,7 @@ EmmcPeimSwitchToHS200 ( if (EFI_ERROR (Status)) { return Status; } + // // Set to HS200/SDR104 timing // @@ -2587,13 +2633,14 @@ EmmcPeimSwitchToHS200 ( return Status; } - HostCtrl2 = (UINT8)~0x7; - Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~0x7; + Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + HostCtrl2 = BIT0 | BIT1; - Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } @@ -2611,14 +2658,15 @@ EmmcPeimSwitchToHS200 ( if (EFI_ERROR (Status)) { return Status; } + // // Set SD Clock Enable in the Clock Control register to 1 // ClockCtrl = BIT2; - Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); HsTiming = 2; - Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); + Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); if (EFI_ERROR (Status)) { return Status; } @@ -2644,27 +2692,29 @@ EmmcPeimSwitchToHS200 ( **/ EFI_STATUS EmmcPeimSwitchToHS400 ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca, - IN UINT32 ClockFreq + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca, + IN UINT32 ClockFreq ) { - EFI_STATUS Status; - UINT8 HsTiming; - UINT8 HostCtrl2; + EFI_STATUS Status; + UINT8 HsTiming; + UINT8 HostCtrl2; Status = EmmcPeimSwitchToHS200 (Slot, Rca, ClockFreq, 8); if (EFI_ERROR (Status)) { return Status; } + // // Set to High Speed timing and set the clock frequency to a value less than 52MHz. // HsTiming = 1; - Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, 52); + Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, 52); if (EFI_ERROR (Status)) { return Status; } + // // HS400 mode must use 8 data lines. // @@ -2672,22 +2722,24 @@ EmmcPeimSwitchToHS400 ( if (EFI_ERROR (Status)) { return Status; } + // // Set to HS400 timing // - HostCtrl2 = (UINT8)~0x7; - Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~0x7; + Status = EmmcPeimHcAndMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + HostCtrl2 = BIT0 | BIT2; - Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = EmmcPeimHcOrMmio (Slot->EmmcHcBase + EMMC_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } HsTiming = 3; - Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); + Status = EmmcPeimSwitchClockFreq (Slot, Rca, HsTiming, ClockFreq); return Status; } @@ -2707,16 +2759,16 @@ EmmcPeimSwitchToHS400 ( **/ EFI_STATUS EmmcPeimSetBusMode ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT32 Rca + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT32 Rca ) { - EFI_STATUS Status; - EMMC_HC_SLOT_CAP Capability; - UINT8 HsTiming; - BOOLEAN IsDdr; - UINT32 ClockFreq; - UINT8 BusWidth; + EFI_STATUS Status; + EMMC_HC_SLOT_CAP Capability; + UINT8 HsTiming; + BOOLEAN IsDdr; + UINT32 ClockFreq; + UINT8 BusWidth; Status = EmmcPeimGetCsd (Slot, Rca, &Slot->Csd); if (EFI_ERROR (Status)) { @@ -2751,6 +2803,7 @@ EmmcPeimSetBusMode ( } else { BusWidth = 4; } + // // Get Device_Type from EXT_CSD register. // @@ -2759,6 +2812,7 @@ EmmcPeimSetBusMode ( DEBUG ((DEBUG_ERROR, "EmmcPeimSetBusMode: EmmcPeimGetExtCsd fails with %r\n", Status)); return Status; } + // // Calculate supported bus speed/bus width/clock frequency. // @@ -2782,6 +2836,7 @@ EmmcPeimSetBusMode ( IsDdr = FALSE; ClockFreq = 26; } + // // Check if both of the device and the host controller support HS400 DDR mode. // @@ -2802,7 +2857,7 @@ EmmcPeimSetBusMode ( return EFI_SUCCESS; } - DEBUG ((DEBUG_INFO, "HsTiming %d ClockFreq %d BusWidth %d Ddr %a\n", HsTiming, ClockFreq, BusWidth, IsDdr ? "TRUE":"FALSE")); + DEBUG ((DEBUG_INFO, "HsTiming %d ClockFreq %d BusWidth %d Ddr %a\n", HsTiming, ClockFreq, BusWidth, IsDdr ? "TRUE" : "FALSE")); if (HsTiming == 3) { // @@ -2837,13 +2892,13 @@ EmmcPeimSetBusMode ( **/ EFI_STATUS EmmcPeimIdentification ( - IN EMMC_PEIM_HC_SLOT *Slot + IN EMMC_PEIM_HC_SLOT *Slot ) { - EFI_STATUS Status; - UINT32 Ocr; - UINT32 Rca; - UINTN Retry; + EFI_STATUS Status; + UINT32 Ocr; + UINT32 Rca; + UINTN Retry; Status = EmmcPeimReset (Slot); if (EFI_ERROR (Status)) { @@ -2864,6 +2919,7 @@ EmmcPeimIdentification ( DEBUG ((DEBUG_ERROR, "EmmcPeimIdentification: EmmcPeimGetOcr fails too many times\n")); return EFI_DEVICE_ERROR; } + MicroSecondDelay (10 * 1000); } while ((Ocr & BIT31) == 0); @@ -2872,6 +2928,7 @@ EmmcPeimIdentification ( DEBUG ((DEBUG_ERROR, "EmmcPeimIdentification: EmmcPeimGetAllCid fails with %r\n", Status)); return Status; } + // // Don't support multiple devices on the slot, that is // shared bus slot feature. @@ -2882,6 +2939,7 @@ EmmcPeimIdentification ( DEBUG ((DEBUG_ERROR, "EmmcPeimIdentification: EmmcPeimSetRca fails with %r\n", Status)); return Status; } + // // Enter Data Tranfer Mode. // diff --git a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.h b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.h index 4e3e51d144..6c6108b028 100644 --- a/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.h +++ b/MdeModulePkg/Bus/Sd/EmmcBlockIoPei/EmmcHci.h @@ -61,9 +61,9 @@ typedef enum { // // The maximum data length of each descriptor line // -#define ADMA_MAX_DATA_PER_LINE 0x10000 -#define EMMC_SDMA_BOUNDARY 512 * 1024 -#define EMMC_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) +#define ADMA_MAX_DATA_PER_LINE 0x10000 +#define EMMC_SDMA_BOUNDARY 512 * 1024 +#define EMMC_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) typedef enum { EmmcCommandTypeBc, // Broadcast commands, no response @@ -85,76 +85,76 @@ typedef enum { } EMMC_RESPONSE_TYPE; typedef struct _EMMC_COMMAND_BLOCK { - UINT16 CommandIndex; - UINT32 CommandArgument; - UINT32 CommandType; // One of the EMMC_COMMAND_TYPE values - UINT32 ResponseType; // One of the EMMC_RESPONSE_TYPE values + UINT16 CommandIndex; + UINT32 CommandArgument; + UINT32 CommandType; // One of the EMMC_COMMAND_TYPE values + UINT32 ResponseType; // One of the EMMC_RESPONSE_TYPE values } EMMC_COMMAND_BLOCK; typedef struct _EMMC_STATUS_BLOCK { - UINT32 Resp0; - UINT32 Resp1; - UINT32 Resp2; - UINT32 Resp3; + UINT32 Resp0; + UINT32 Resp1; + UINT32 Resp2; + UINT32 Resp3; } EMMC_STATUS_BLOCK; typedef struct _EMMC_COMMAND_PACKET { - UINT64 Timeout; - EMMC_COMMAND_BLOCK *EmmcCmdBlk; - EMMC_STATUS_BLOCK *EmmcStatusBlk; - VOID *InDataBuffer; - VOID *OutDataBuffer; - UINT32 InTransferLength; - UINT32 OutTransferLength; + UINT64 Timeout; + EMMC_COMMAND_BLOCK *EmmcCmdBlk; + EMMC_STATUS_BLOCK *EmmcStatusBlk; + VOID *InDataBuffer; + VOID *OutDataBuffer; + UINT32 InTransferLength; + UINT32 OutTransferLength; } EMMC_COMMAND_PACKET; #pragma pack(1) typedef struct { - UINT32 Valid:1; - UINT32 End:1; - UINT32 Int:1; - UINT32 Reserved:1; - UINT32 Act:2; - UINT32 Reserved1:10; - UINT32 Length:16; - UINT32 Address; + UINT32 Valid : 1; + UINT32 End : 1; + UINT32 Int : 1; + UINT32 Reserved : 1; + UINT32 Act : 2; + UINT32 Reserved1 : 10; + UINT32 Length : 16; + UINT32 Address; } EMMC_HC_ADMA_DESC_LINE; typedef struct { - UINT32 TimeoutFreq:6; // bit 0:5 - UINT32 Reserved:1; // bit 6 - UINT32 TimeoutUnit:1; // bit 7 - UINT32 BaseClkFreq:8; // bit 8:15 - UINT32 MaxBlkLen:2; // bit 16:17 - UINT32 BusWidth8:1; // bit 18 - UINT32 Adma2:1; // bit 19 - UINT32 Reserved2:1; // bit 20 - UINT32 HighSpeed:1; // bit 21 - UINT32 Sdma:1; // bit 22 - UINT32 SuspRes:1; // bit 23 - UINT32 Voltage33:1; // bit 24 - UINT32 Voltage30:1; // bit 25 - UINT32 Voltage18:1; // bit 26 - UINT32 Reserved3:1; // bit 27 - UINT32 SysBus64:1; // bit 28 - UINT32 AsyncInt:1; // bit 29 - UINT32 SlotType:2; // bit 30:31 - UINT32 Sdr50:1; // bit 32 - UINT32 Sdr104:1; // bit 33 - UINT32 Ddr50:1; // bit 34 - UINT32 Reserved4:1; // bit 35 - UINT32 DriverTypeA:1; // bit 36 - UINT32 DriverTypeC:1; // bit 37 - UINT32 DriverTypeD:1; // bit 38 - UINT32 DriverType4:1; // bit 39 - UINT32 TimerCount:4; // bit 40:43 - UINT32 Reserved5:1; // bit 44 - UINT32 TuningSDR50:1; // bit 45 - UINT32 RetuningMod:2; // bit 46:47 - UINT32 ClkMultiplier:8; // bit 48:55 - UINT32 Reserved6:7; // bit 56:62 - UINT32 Hs400:1; // bit 63 + UINT32 TimeoutFreq : 6; // bit 0:5 + UINT32 Reserved : 1; // bit 6 + UINT32 TimeoutUnit : 1; // bit 7 + UINT32 BaseClkFreq : 8; // bit 8:15 + UINT32 MaxBlkLen : 2; // bit 16:17 + UINT32 BusWidth8 : 1; // bit 18 + UINT32 Adma2 : 1; // bit 19 + UINT32 Reserved2 : 1; // bit 20 + UINT32 HighSpeed : 1; // bit 21 + UINT32 Sdma : 1; // bit 22 + UINT32 SuspRes : 1; // bit 23 + UINT32 Voltage33 : 1; // bit 24 + UINT32 Voltage30 : 1; // bit 25 + UINT32 Voltage18 : 1; // bit 26 + UINT32 Reserved3 : 1; // bit 27 + UINT32 SysBus64 : 1; // bit 28 + UINT32 AsyncInt : 1; // bit 29 + UINT32 SlotType : 2; // bit 30:31 + UINT32 Sdr50 : 1; // bit 32 + UINT32 Sdr104 : 1; // bit 33 + UINT32 Ddr50 : 1; // bit 34 + UINT32 Reserved4 : 1; // bit 35 + UINT32 DriverTypeA : 1; // bit 36 + UINT32 DriverTypeC : 1; // bit 37 + UINT32 DriverTypeD : 1; // bit 38 + UINT32 DriverType4 : 1; // bit 39 + UINT32 TimerCount : 4; // bit 40:43 + UINT32 Reserved5 : 1; // bit 44 + UINT32 TuningSDR50 : 1; // bit 45 + UINT32 RetuningMod : 2; // bit 46:47 + UINT32 ClkMultiplier : 8; // bit 48:55 + UINT32 Reserved6 : 7; // bit 56:62 + UINT32 Hs400 : 1; // bit 63 } EMMC_HC_SLOT_CAP; #pragma pack() @@ -170,7 +170,7 @@ typedef struct { **/ EFI_STATUS EmmcPeimHcReset ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -185,7 +185,7 @@ EmmcPeimHcReset ( **/ EFI_STATUS EmmcPeimHcEnableInterrupt ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -200,8 +200,8 @@ EmmcPeimHcEnableInterrupt ( **/ EFI_STATUS EmmcPeimHcGetCapability ( - IN UINTN Bar, - OUT EMMC_HC_SLOT_CAP *Capability + IN UINTN Bar, + OUT EMMC_HC_SLOT_CAP *Capability ); /** @@ -219,7 +219,7 @@ EmmcPeimHcGetCapability ( **/ EFI_STATUS EmmcPeimHcCardDetect ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -234,7 +234,7 @@ EmmcPeimHcCardDetect ( **/ EFI_STATUS EmmcPeimHcInitHost ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -255,11 +255,11 @@ EmmcPeimHcInitHost ( **/ EFI_STATUS EmmcPeimSwitch ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT8 Access, - IN UINT8 Index, - IN UINT8 Value, - IN UINT8 CmdSet + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT8 Access, + IN UINT8 Index, + IN UINT8 Value, + IN UINT8 CmdSet ); /** @@ -277,8 +277,8 @@ EmmcPeimSwitch ( **/ EFI_STATUS EmmcPeimSetBlkCount ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN UINT16 BlockCount + IN EMMC_PEIM_HC_SLOT *Slot, + IN UINT16 BlockCount ); /** @@ -300,12 +300,12 @@ EmmcPeimSetBlkCount ( **/ EFI_STATUS EmmcPeimRwMultiBlocks ( - IN EMMC_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN EMMC_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ); /** @@ -321,7 +321,7 @@ EmmcPeimRwMultiBlocks ( **/ EFI_STATUS EmmcPeimIdentification ( - IN EMMC_PEIM_HC_SLOT *Slot + IN EMMC_PEIM_HC_SLOT *Slot ); /** @@ -332,8 +332,7 @@ EmmcPeimIdentification ( **/ VOID EmmcPeimFreeTrb ( - IN EMMC_TRB *Trb + IN EMMC_TRB *Trb ); #endif - diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/ComponentName.c b/MdeModulePkg/Bus/Sd/EmmcDxe/ComponentName.c index 6a4d18d4d6..b66bbff824 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/ComponentName.c @@ -11,17 +11,17 @@ // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEmmcDxeDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEmmcDxeDriverNameTable[] = { { "eng;en", L"Edkii Emmc Device Driver" }, - { NULL , NULL } + { NULL, NULL } }; // // Controller name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEmmcDxeControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mEmmcDxeControllerNameTable[] = { { "eng;en", L"Edkii Emmc Host Controller" }, - { NULL , NULL } + { NULL, NULL } }; // @@ -36,9 +36,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gEmmcDxeComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gEmmcDxeComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) EmmcDxeComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) EmmcDxeComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gEmmcDxeComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)EmmcDxeComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)EmmcDxeComponentNameGetControllerName, "en" }; @@ -96,7 +96,6 @@ EmmcDxeComponentNameGetDriverName ( DriverName, (BOOLEAN)(This == &gEmmcDxeComponentName) ); - } /** @@ -170,11 +169,11 @@ EmmcDxeComponentNameGetDriverName ( EFI_STATUS EFIAPI EmmcDxeComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { EFI_STATUS Status; @@ -205,13 +204,14 @@ EmmcDxeComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the child context // Status = gBS->OpenProtocol ( ChildHandle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, gEmmcDxeDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -220,8 +220,8 @@ EmmcDxeComponentNameGetControllerName ( return EFI_UNSUPPORTED; } - Partition = EMMC_PARTITION_DATA_FROM_BLKIO (BlockIo); - Device = Partition->Device; + Partition = EMMC_PARTITION_DATA_FROM_BLKIO (BlockIo); + Device = Partition->Device; ControllerNameTable = Device->ControllerNameTable; } @@ -233,4 +233,3 @@ EmmcDxeComponentNameGetControllerName ( (BOOLEAN)(This == &gEmmcDxeComponentName) ); } - diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c index 63d77a22fe..39b7c7ce6e 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c @@ -19,24 +19,28 @@ VOID EFIAPI AsyncIoCallback ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EMMC_REQUEST *Request; - EFI_STATUS Status; + EMMC_REQUEST *Request; + EFI_STATUS Status; Status = gBS->CloseEvent (Event); if (EFI_ERROR (Status)) { return; } - Request = (EMMC_REQUEST *) Context; + Request = (EMMC_REQUEST *)Context; DEBUG_CODE_BEGIN (); - DEBUG ((DEBUG_INFO, "Emmc Async Request: CmdIndex[%d] Arg[%08x] %r\n", - Request->SdMmcCmdBlk.CommandIndex, Request->SdMmcCmdBlk.CommandArgument, - Request->Packet.TransactionStatus)); + DEBUG (( + DEBUG_INFO, + "Emmc Async Request: CmdIndex[%d] Arg[%08x] %r\n", + Request->SdMmcCmdBlk.CommandIndex, + Request->SdMmcCmdBlk.CommandArgument, + Request->Packet.TransactionStatus + )); DEBUG_CODE_END (); if (EFI_ERROR (Request->Packet.TransactionStatus)) { @@ -65,15 +69,15 @@ AsyncIoCallback ( **/ EFI_STATUS EmmcSelect ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca + IN EMMC_DEVICE *Device, + IN UINT16 Rca ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; PassThru = Device->Private->PassThru; @@ -84,9 +88,9 @@ EmmcSelect ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SELECT_DESELECT_CARD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -108,16 +112,16 @@ EmmcSelect ( **/ EFI_STATUS EmmcSendStatus ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT UINT32 *DevStatus + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT UINT32 *DevStatus ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; PassThru = Device->Private->PassThru; @@ -128,9 +132,9 @@ EmmcSendStatus ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_STATUS; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -155,16 +159,16 @@ EmmcSendStatus ( **/ EFI_STATUS EmmcGetCsd ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT EMMC_CSD *Csd + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT EMMC_CSD *Csd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; PassThru = Device->Private->PassThru; @@ -177,9 +181,9 @@ EmmcGetCsd ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_CSD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -187,7 +191,7 @@ EmmcGetCsd ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); + CopyMem (((UINT8 *)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CSD) - 1); } return Status; @@ -207,16 +211,16 @@ EmmcGetCsd ( **/ EFI_STATUS EmmcGetCid ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT EMMC_CID *Cid + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT EMMC_CID *Cid ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; PassThru = Device->Private->PassThru; @@ -229,9 +233,9 @@ EmmcGetCid ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_CID; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_CID; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -239,7 +243,7 @@ EmmcGetCid ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Cid) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CID) - 1); + CopyMem (((UINT8 *)Cid) + 1, &SdMmcStatusBlk.Resp0, sizeof (EMMC_CID) - 1); } return Status; @@ -258,15 +262,15 @@ EmmcGetCid ( **/ EFI_STATUS EmmcGetExtCsd ( - IN EMMC_DEVICE *Device, - OUT EMMC_EXT_CSD *ExtCsd + IN EMMC_DEVICE *Device, + OUT EMMC_EXT_CSD *ExtCsd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; PassThru = Device->Private->PassThru; @@ -278,12 +282,12 @@ EmmcGetExtCsd ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = EMMC_SEND_EXT_CSD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAdtc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = 0x00000000; - Packet.InDataBuffer = ExtCsd; - Packet.InTransferLength = sizeof (EMMC_EXT_CSD); + Packet.InDataBuffer = ExtCsd; + Packet.InTransferLength = sizeof (EMMC_EXT_CSD); Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -307,19 +311,19 @@ EmmcGetExtCsd ( **/ EFI_STATUS EmmcSetExtCsd ( - IN EMMC_PARTITION *Partition, - IN UINT8 Offset, - IN UINT8 Value, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN UINT8 Offset, + IN UINT8 Value, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EMMC_REQUEST *SetExtCsdReq; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - UINT32 CommandArgument; - EFI_TPL OldTpl; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EMMC_REQUEST *SetExtCsdReq; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + UINT32 CommandArgument; + EFI_TPL OldTpl; SetExtCsdReq = NULL; @@ -333,7 +337,7 @@ EmmcSetExtCsd ( } SetExtCsdReq->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &SetExtCsdReq->Link); gBS->RestoreTPL (OldTpl); SetExtCsdReq->Packet.SdMmcCmdBlk = &SetExtCsdReq->SdMmcCmdBlk; @@ -346,7 +350,7 @@ EmmcSetExtCsd ( // // Write the Value to the field specified by Offset. // - CommandArgument = (Value << 8) | (Offset << 16) | BIT24 | BIT25; + CommandArgument = (Value << 8) | (Offset << 16) | BIT24 | BIT25; SetExtCsdReq->SdMmcCmdBlk.CommandArgument = CommandArgument; SetExtCsdReq->IsEnd = IsEnd; @@ -382,6 +386,7 @@ Error: if (SetExtCsdReq->Event != NULL) { gBS->CloseEvent (SetExtCsdReq->Event); } + FreePool (SetExtCsdReq); } } else { @@ -415,17 +420,17 @@ Error: **/ EFI_STATUS EmmcSetBlkCount ( - IN EMMC_PARTITION *Partition, - IN UINT16 BlockNum, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN UINT16 BlockNum, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EMMC_REQUEST *SetBlkCntReq; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_TPL OldTpl; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EMMC_REQUEST *SetBlkCntReq; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_TPL OldTpl; SetBlkCntReq = NULL; @@ -439,16 +444,16 @@ EmmcSetBlkCount ( } SetBlkCntReq->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &SetBlkCntReq->Link); gBS->RestoreTPL (OldTpl); SetBlkCntReq->Packet.SdMmcCmdBlk = &SetBlkCntReq->SdMmcCmdBlk; SetBlkCntReq->Packet.SdMmcStatusBlk = &SetBlkCntReq->SdMmcStatusBlk; SetBlkCntReq->Packet.Timeout = EMMC_GENERIC_TIMEOUT; - SetBlkCntReq->SdMmcCmdBlk.CommandIndex = EMMC_SET_BLOCK_COUNT; - SetBlkCntReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SetBlkCntReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SetBlkCntReq->SdMmcCmdBlk.CommandIndex = EMMC_SET_BLOCK_COUNT; + SetBlkCntReq->SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SetBlkCntReq->SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SetBlkCntReq->SdMmcCmdBlk.CommandArgument = BlockNum; SetBlkCntReq->IsEnd = IsEnd; @@ -484,6 +489,7 @@ Error: if (SetBlkCntReq->Event != NULL) { gBS->CloseEvent (SetBlkCntReq->Event); } + FreePool (SetBlkCntReq); } } else { @@ -527,22 +533,22 @@ Error: **/ EFI_STATUS EmmcProtocolInOut ( - IN EMMC_PARTITION *Partition, - IN UINT8 SecurityProtocol, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - IN BOOLEAN IsRead, - IN UINT64 Timeout, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN UINT8 SecurityProtocol, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + IN BOOLEAN IsRead, + IN UINT64 Timeout, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EMMC_REQUEST *ProtocolReq; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_TPL OldTpl; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EMMC_REQUEST *ProtocolReq; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_TPL OldTpl; ProtocolReq = NULL; @@ -556,7 +562,7 @@ EmmcProtocolInOut ( } ProtocolReq->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &ProtocolReq->Link); gBS->RestoreTPL (OldTpl); ProtocolReq->Packet.SdMmcCmdBlk = &ProtocolReq->SdMmcCmdBlk; @@ -617,6 +623,7 @@ Error: if (ProtocolReq->Event != NULL) { gBS->CloseEvent (ProtocolReq->Event); } + FreePool (ProtocolReq); } } else { @@ -655,20 +662,20 @@ Error: **/ EFI_STATUS EmmcRwMultiBlocks ( - IN EMMC_PARTITION *Partition, - IN EFI_LBA Lba, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN EFI_LBA Lba, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EMMC_REQUEST *RwMultiBlkReq; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_TPL OldTpl; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EMMC_REQUEST *RwMultiBlkReq; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_TPL OldTpl; RwMultiBlkReq = NULL; @@ -682,7 +689,7 @@ EmmcRwMultiBlocks ( } RwMultiBlkReq->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &RwMultiBlkReq->Link); gBS->RestoreTPL (OldTpl); RwMultiBlkReq->Packet.SdMmcCmdBlk = &RwMultiBlkReq->SdMmcCmdBlk; @@ -751,6 +758,7 @@ Error: if (RwMultiBlkReq->Event != NULL) { gBS->CloseEvent (RwMultiBlkReq->Event); } + FreePool (RwMultiBlkReq); } } else { @@ -793,25 +801,25 @@ Error: **/ EFI_STATUS EmmcReadWrite ( - IN EMMC_PARTITION *Partition, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead, - IN OUT EFI_BLOCK_IO2_TOKEN *Token + IN EMMC_PARTITION *Partition, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN BlockNum; - UINTN IoAlign; - UINT8 PartitionConfig; - UINTN Remaining; - UINT32 MaxBlock; - BOOLEAN LastRw; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN BlockNum; + UINTN IoAlign; + UINT8 PartitionConfig; + UINTN Remaining; + UINT32 MaxBlock; + BOOLEAN LastRw; Status = EFI_SUCCESS; Device = Partition->Device; @@ -838,6 +846,7 @@ EmmcReadWrite ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -846,32 +855,35 @@ EmmcReadWrite ( return EFI_BAD_BUFFER_SIZE; } - BlockNum = BufferSize / BlockSize; + BlockNum = BufferSize / BlockSize; if ((Lba + BlockNum - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; } + // // Check if needs to switch partition access. // PartitionConfig = Device->ExtCsd.PartitionConfig; if ((PartitionConfig & 0x7) != Partition->PartitionType) { - PartitionConfig &= (UINT8)~0x7; + PartitionConfig &= (UINT8) ~0x7; PartitionConfig |= Partition->PartitionType; - Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, Token, FALSE); + Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, Token, FALSE); if (EFI_ERROR (Status)) { return Status; } + Device->ExtCsd.PartitionConfig = PartitionConfig; } + // // Start to execute data transfer. The max block number in single cmd is 65535 blocks. // @@ -885,23 +897,31 @@ EmmcReadWrite ( } else { BlockNum = MaxBlock; } + Status = EmmcSetBlkCount (Partition, (UINT16)BlockNum, Token, FALSE); if (EFI_ERROR (Status)) { return Status; } BufferSize = BlockNum * BlockSize; - Status = EmmcRwMultiBlocks (Partition, Lba, Buffer, BufferSize, IsRead, Token, LastRw); + Status = EmmcRwMultiBlocks (Partition, Lba, Buffer, BufferSize, IsRead, Token, LastRw); if (EFI_ERROR (Status)) { return Status; } - DEBUG ((DEBUG_BLKIO, - "Emmc%a(): Part %d Lba 0x%x BlkNo 0x%x Event %p with %r\n", - IsRead ? "Read " : "Write", Partition->PartitionType, Lba, BlockNum, - (Token != NULL) ? Token->Event : NULL, Status)); - Lba += BlockNum; - Buffer = (UINT8*)Buffer + BufferSize; + DEBUG (( + DEBUG_BLKIO, + "Emmc%a(): Part %d Lba 0x%x BlkNo 0x%x Event %p with %r\n", + IsRead ? "Read " : "Write", + Partition->PartitionType, + Lba, + BlockNum, + (Token != NULL) ? Token->Event : NULL, + Status + )); + + Lba += BlockNum; + Buffer = (UINT8 *)Buffer + BufferSize; Remaining -= BlockNum; } @@ -922,13 +942,13 @@ EmmcReadWrite ( EFI_STATUS EFIAPI EmmcReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_STATUS Status; + EMMC_PARTITION *Partition; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This); @@ -967,11 +987,11 @@ EmmcReadBlocks ( IN UINT32 MediaId, IN EFI_LBA Lba, IN UINTN BufferSize, - OUT VOID *Buffer + OUT VOID *Buffer ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; + EFI_STATUS Status; + EMMC_PARTITION *Partition; Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This); @@ -1002,15 +1022,15 @@ EmmcReadBlocks ( EFI_STATUS EFIAPI EmmcWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; + EFI_STATUS Status; + EMMC_PARTITION *Partition; Partition = EMMC_PARTITION_DATA_FROM_BLKIO (This); @@ -1031,7 +1051,7 @@ EmmcWriteBlocks ( EFI_STATUS EFIAPI EmmcFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ) { // @@ -1058,18 +1078,19 @@ EmmcResetEx ( IN BOOLEAN ExtendedVerification ) { - EMMC_PARTITION *Partition; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - EMMC_REQUEST *Request; - EFI_TPL OldTpl; + EMMC_PARTITION *Partition; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + EMMC_REQUEST *Request; + EFI_TPL OldTpl; Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This); OldTpl = gBS->RaiseTPL (TPL_NOTIFY); for (Link = GetFirstNode (&Partition->Queue); !IsNull (&Partition->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Partition->Queue, Link); RemoveEntryList (Link); @@ -1084,6 +1105,7 @@ EmmcResetEx ( FreePool (Request); } + gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; @@ -1118,16 +1140,16 @@ EmmcResetEx ( EFI_STATUS EFIAPI EmmcReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; + EFI_STATUS Status; + EMMC_PARTITION *Partition; Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This); @@ -1160,16 +1182,16 @@ EmmcReadBlocksEx ( EFI_STATUS EFIAPI EmmcWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; + EFI_STATUS Status; + EMMC_PARTITION *Partition; Partition = EMMC_PARTITION_DATA_FROM_BLKIO2 (This); @@ -1198,7 +1220,7 @@ EmmcFlushBlocksEx ( // // Signal event and return directly. // - if (Token != NULL && Token->Event != NULL) { + if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } @@ -1282,27 +1304,27 @@ EmmcFlushBlocksEx ( EFI_STATUS EFIAPI EmmcSecurityProtocolInOut ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize, - IN BOOLEAN IsRead + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize, + IN BOOLEAN IsRead ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; - EMMC_DEVICE *Device; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN BlockNum; - UINTN IoAlign; - UINTN Remaining; - UINT32 MaxBlock; - UINT8 PartitionConfig; + EFI_STATUS Status; + EMMC_PARTITION *Partition; + EMMC_DEVICE *Device; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN BlockNum; + UINTN IoAlign; + UINTN Remaining; + UINT32 MaxBlock; + UINT8 PartitionConfig; Status = EFI_SUCCESS; Partition = EMMC_PARTITION_DATA_FROM_SSP (This); @@ -1330,10 +1352,10 @@ EmmcSecurityProtocolInOut ( return EFI_BAD_BUFFER_SIZE; } - BlockNum = PayloadBufferSize / BlockSize; + BlockNum = PayloadBufferSize / BlockSize; IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) PayloadBuffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)PayloadBuffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -1341,21 +1363,24 @@ EmmcSecurityProtocolInOut ( // Security protocol interface is synchronous transfer. // Waiting for async I/O list to be empty before any operation. // - while (!IsListEmpty (&Partition->Queue)); + while (!IsListEmpty (&Partition->Queue)) { + } // // Check if needs to switch partition access. // PartitionConfig = Device->ExtCsd.PartitionConfig; if ((PartitionConfig & 0x7) != Partition->PartitionType) { - PartitionConfig &= (UINT8)~0x7; + PartitionConfig &= (UINT8) ~0x7; PartitionConfig |= Partition->PartitionType; - Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, NULL, FALSE); + Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, NULL, FALSE); if (EFI_ERROR (Status)) { return Status; } + Device->ExtCsd.PartitionConfig = PartitionConfig; } + // // Start to execute data transfer. The max block number in single cmd is 65535 blocks. // @@ -1375,12 +1400,12 @@ EmmcSecurityProtocolInOut ( } PayloadBufferSize = BlockNum * BlockSize; - Status = EmmcProtocolInOut (Partition, SecurityProtocolId, SecurityProtocolSpecificData, PayloadBufferSize, PayloadBuffer, IsRead, Timeout, NULL, FALSE); + Status = EmmcProtocolInOut (Partition, SecurityProtocolId, SecurityProtocolSpecificData, PayloadBufferSize, PayloadBuffer, IsRead, Timeout, NULL, FALSE); if (EFI_ERROR (Status)) { return Status; } - PayloadBuffer = (UINT8*)PayloadBuffer + PayloadBufferSize; + PayloadBuffer = (UINT8 *)PayloadBuffer + PayloadBufferSize; Remaining -= BlockNum; if (PayloadTransferSize != NULL) { *PayloadTransferSize += PayloadBufferSize; @@ -1465,19 +1490,19 @@ EmmcSecurityProtocolInOut ( EFI_STATUS EFIAPI EmmcSecurityProtocolIn ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ) { - EFI_STATUS Status; + EFI_STATUS Status; - if ((PayloadTransferSize == NULL) && PayloadBufferSize != 0) { + if ((PayloadTransferSize == NULL) && (PayloadBufferSize != 0)) { return EFI_INVALID_PARAMETER; } @@ -1560,16 +1585,16 @@ EmmcSecurityProtocolIn ( EFI_STATUS EFIAPI EmmcSecurityProtocolOut ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EmmcSecurityProtocolInOut ( This, @@ -1602,17 +1627,17 @@ EmmcSecurityProtocolOut ( **/ EFI_STATUS EmmcEraseBlockStart ( - IN EMMC_PARTITION *Partition, - IN EFI_LBA StartLba, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN EFI_LBA StartLba, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EMMC_DEVICE *Device; - EMMC_REQUEST *EraseBlockStart; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EMMC_DEVICE *Device; + EMMC_REQUEST *EraseBlockStart; + EFI_TPL OldTpl; EraseBlockStart = NULL; @@ -1626,7 +1651,7 @@ EmmcEraseBlockStart ( } EraseBlockStart->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &EraseBlockStart->Link); gBS->RestoreTPL (OldTpl); EraseBlockStart->Packet.SdMmcCmdBlk = &EraseBlockStart->SdMmcCmdBlk; @@ -1676,6 +1701,7 @@ Error: if (EraseBlockStart->Event != NULL) { gBS->CloseEvent (EraseBlockStart->Event); } + FreePool (EraseBlockStart); } } else { @@ -1709,17 +1735,17 @@ Error: **/ EFI_STATUS EmmcEraseBlockEnd ( - IN EMMC_PARTITION *Partition, - IN EFI_LBA EndLba, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN EFI_LBA EndLba, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EMMC_DEVICE *Device; - EMMC_REQUEST *EraseBlockEnd; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EMMC_DEVICE *Device; + EMMC_REQUEST *EraseBlockEnd; + EFI_TPL OldTpl; EraseBlockEnd = NULL; @@ -1733,7 +1759,7 @@ EmmcEraseBlockEnd ( } EraseBlockEnd->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &EraseBlockEnd->Link); gBS->RestoreTPL (OldTpl); EraseBlockEnd->Packet.SdMmcCmdBlk = &EraseBlockEnd->SdMmcCmdBlk; @@ -1783,6 +1809,7 @@ Error: if (EraseBlockEnd->Event != NULL) { gBS->CloseEvent (EraseBlockEnd->Event); } + FreePool (EraseBlockEnd); } } else { @@ -1815,16 +1842,16 @@ Error: **/ EFI_STATUS EmmcEraseBlock ( - IN EMMC_PARTITION *Partition, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN EMMC_PARTITION *Partition, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EMMC_DEVICE *Device; - EMMC_REQUEST *EraseBlock; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EMMC_DEVICE *Device; + EMMC_REQUEST *EraseBlock; + EFI_TPL OldTpl; EraseBlock = NULL; @@ -1838,7 +1865,7 @@ EmmcEraseBlock ( } EraseBlock->Signature = EMMC_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Partition->Queue, &EraseBlock->Link); gBS->RestoreTPL (OldTpl); EraseBlock->Packet.SdMmcCmdBlk = &EraseBlock->SdMmcCmdBlk; @@ -1890,6 +1917,7 @@ Error: if (EraseBlock->Event != NULL) { gBS->CloseEvent (EraseBlock->Event); } + FreePool (EraseBlock); } } else { @@ -1922,14 +1950,14 @@ Error: **/ EFI_STATUS EmmcWriteZeros ( - IN EMMC_PARTITION *Partition, - IN EFI_LBA StartLba, - IN UINTN Size + IN EMMC_PARTITION *Partition, + IN EFI_LBA StartLba, + IN UINTN Size ) { - EFI_STATUS Status; - UINT8 *Buffer; - UINT32 MediaId; + EFI_STATUS Status; + UINT8 *Buffer; + UINT32 MediaId; Buffer = AllocateZeroPool (Size); if (Buffer == NULL) { @@ -1974,27 +2002,27 @@ EmmcWriteZeros ( EFI_STATUS EFIAPI EmmcEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ) { - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN BlockNum; - EFI_LBA FirstLba; - EFI_LBA LastLba; - EFI_LBA StartGroupLba; - EFI_LBA EndGroupLba; - UINT32 EraseGroupSize; - UINT32 Remainder; - UINTN WriteZeroSize; - UINT8 PartitionConfig; - EMMC_PARTITION *Partition; - EMMC_DEVICE *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN BlockNum; + EFI_LBA FirstLba; + EFI_LBA LastLba; + EFI_LBA StartGroupLba; + EFI_LBA EndGroupLba; + UINT32 EraseGroupSize; + UINT32 Remainder; + UINTN WriteZeroSize; + UINT8 PartitionConfig; + EMMC_PARTITION *Partition; + EMMC_DEVICE *Device; Status = EFI_SUCCESS; Partition = EMMC_PARTITION_DATA_FROM_ERASEBLK (This); @@ -2017,7 +2045,7 @@ EmmcEraseBlocks ( return EFI_INVALID_PARAMETER; } - BlockNum = Size / BlockSize; + BlockNum = Size / BlockSize; if ((Lba + BlockNum - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } @@ -2034,12 +2062,13 @@ EmmcEraseBlocks ( // PartitionConfig = Device->ExtCsd.PartitionConfig; if ((PartitionConfig & 0x7) != Partition->PartitionType) { - PartitionConfig &= (UINT8)~0x7; + PartitionConfig &= (UINT8) ~0x7; PartitionConfig |= Partition->PartitionType; - Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE); + Status = EmmcSetExtCsd (Partition, OFFSET_OF (EMMC_EXT_CSD, PartitionConfig), PartitionConfig, (EFI_BLOCK_IO2_TOKEN *)Token, FALSE); if (EFI_ERROR (Status)) { return Status; } + Device->ExtCsd.PartitionConfig = PartitionConfig; } @@ -2079,6 +2108,7 @@ EmmcEraseBlocks ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -2089,7 +2119,7 @@ EmmcEraseBlocks ( // if (StartGroupLba > FirstLba) { WriteZeroSize = (UINTN)(StartGroupLba - FirstLba) * BlockSize; - Status = EmmcWriteZeros (Partition, FirstLba, WriteZeroSize); + Status = EmmcWriteZeros (Partition, FirstLba, WriteZeroSize); if (EFI_ERROR (Status)) { return Status; } @@ -2102,7 +2132,7 @@ EmmcEraseBlocks ( // if (EndGroupLba <= LastLba) { WriteZeroSize = (UINTN)(LastLba + 1 - EndGroupLba) * BlockSize; - Status = EmmcWriteZeros (Partition, EndGroupLba, WriteZeroSize); + Status = EmmcWriteZeros (Partition, EndGroupLba, WriteZeroSize); if (EFI_ERROR (Status)) { return Status; } @@ -2125,6 +2155,7 @@ EmmcEraseBlocks ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -2132,17 +2163,17 @@ EmmcEraseBlocks ( LastLba = EndGroupLba - 1; } - Status = EmmcEraseBlockStart (Partition, FirstLba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE); + Status = EmmcEraseBlockStart (Partition, FirstLba, (EFI_BLOCK_IO2_TOKEN *)Token, FALSE); if (EFI_ERROR (Status)) { return Status; } - Status = EmmcEraseBlockEnd (Partition, LastLba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE); + Status = EmmcEraseBlockEnd (Partition, LastLba, (EFI_BLOCK_IO2_TOKEN *)Token, FALSE); if (EFI_ERROR (Status)) { return Status; } - Status = EmmcEraseBlock (Partition, (EFI_BLOCK_IO2_TOKEN*)Token, TRUE); + Status = EmmcEraseBlock (Partition, (EFI_BLOCK_IO2_TOKEN *)Token, TRUE); if (EFI_ERROR (Status)) { return Status; } diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h index 62e70ae912..2568f0359d 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h @@ -26,8 +26,8 @@ EFI_STATUS EFIAPI EmmcReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -56,7 +56,7 @@ EmmcReadBlocks ( IN UINT32 MediaId, IN EFI_LBA Lba, IN UINTN BufferSize, - OUT VOID *Buffer + OUT VOID *Buffer ); /** @@ -82,11 +82,11 @@ EmmcReadBlocks ( EFI_STATUS EFIAPI EmmcWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -102,7 +102,7 @@ EmmcWriteBlocks ( EFI_STATUS EFIAPI EmmcFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ); /** @@ -152,12 +152,12 @@ EmmcResetEx ( EFI_STATUS EFIAPI EmmcReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -185,12 +185,12 @@ EmmcReadBlocksEx ( EFI_STATUS EFIAPI EmmcWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -287,15 +287,15 @@ EmmcFlushBlocksEx ( EFI_STATUS EFIAPI EmmcSecurityProtocolInOut ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize, - IN BOOLEAN IsRead + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize, + IN BOOLEAN IsRead ); /** @@ -373,14 +373,14 @@ EmmcSecurityProtocolInOut ( EFI_STATUS EFIAPI EmmcSecurityProtocolIn ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - OUT VOID *PayloadBuffer, - OUT UINTN *PayloadTransferSize + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + OUT VOID *PayloadBuffer, + OUT UINTN *PayloadTransferSize ); /** @@ -447,13 +447,13 @@ EmmcSecurityProtocolIn ( EFI_STATUS EFIAPI EmmcSecurityProtocolOut ( - IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, - IN UINT32 MediaId, - IN UINT64 Timeout, - IN UINT8 SecurityProtocolId, - IN UINT16 SecurityProtocolSpecificData, - IN UINTN PayloadBufferSize, - IN VOID *PayloadBuffer + IN EFI_STORAGE_SECURITY_COMMAND_PROTOCOL *This, + IN UINT32 MediaId, + IN UINT64 Timeout, + IN UINT8 SecurityProtocolId, + IN UINT16 SecurityProtocolSpecificData, + IN UINTN PayloadBufferSize, + IN VOID *PayloadBuffer ); /** @@ -486,12 +486,11 @@ EmmcSecurityProtocolOut ( EFI_STATUS EFIAPI EmmcEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ); #endif - diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDiskInfo.c b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDiskInfo.c index e9e31aa2c1..1f3ab05db9 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDiskInfo.c +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDiskInfo.c @@ -32,9 +32,9 @@ EmmcDiskInfoInquiry ( IN OUT UINT32 *InquiryDataSize ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; - EMMC_DEVICE *Device; + EFI_STATUS Status; + EMMC_PARTITION *Partition; + EMMC_DEVICE *Device; Partition = EMMC_PARTITION_DATA_FROM_DISKINFO (This); Device = Partition->Device; diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.c b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.c index 8dca9a6ee1..c780c396e1 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.c +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.c @@ -14,7 +14,7 @@ // // EmmcDxe Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gEmmcDxeDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gEmmcDxeDriverBinding = { EmmcDxeDriverBindingSupported, EmmcDxeDriverBindingStart, EmmcDxeDriverBindingStop, @@ -26,7 +26,7 @@ EFI_DRIVER_BINDING_PROTOCOL gEmmcDxeDriverBinding = { // // Template for Emmc Partitions. // -EMMC_PARTITION mEmmcPartitionTemplate = { +EMMC_PARTITION mEmmcPartitionTemplate = { EMMC_PARTITION_SIGNATURE, // Signature FALSE, // Enable EmmcPartitionUnknown, // PartitionType @@ -93,39 +93,39 @@ DumpCsd ( IN EMMC_CSD *Csd ) { - DEBUG((DEBUG_INFO, "== Dump Emmc Csd Register==\n")); - DEBUG((DEBUG_INFO, " CSD structure 0x%x\n", Csd->CsdStructure)); - DEBUG((DEBUG_INFO, " System specification version 0x%x\n", Csd->SpecVers)); - DEBUG((DEBUG_INFO, " Data read access-time 1 0x%x\n", Csd->Taac)); - DEBUG((DEBUG_INFO, " Data read access-time 2 0x%x\n", Csd->Nsac)); - DEBUG((DEBUG_INFO, " Max. bus clock frequency 0x%x\n", Csd->TranSpeed)); - DEBUG((DEBUG_INFO, " Device command classes 0x%x\n", Csd->Ccc)); - DEBUG((DEBUG_INFO, " Max. read data block length 0x%x\n", Csd->ReadBlLen)); - DEBUG((DEBUG_INFO, " Partial blocks for read allowed 0x%x\n", Csd->ReadBlPartial)); - DEBUG((DEBUG_INFO, " Write block misalignment 0x%x\n", Csd->WriteBlkMisalign)); - DEBUG((DEBUG_INFO, " Read block misalignment 0x%x\n", Csd->ReadBlkMisalign)); - DEBUG((DEBUG_INFO, " DSR implemented 0x%x\n", Csd->DsrImp)); - DEBUG((DEBUG_INFO, " Device size 0x%x\n", Csd->CSizeLow | (Csd->CSizeHigh << 2))); - DEBUG((DEBUG_INFO, " Max. read current @ VDD min 0x%x\n", Csd->VddRCurrMin)); - DEBUG((DEBUG_INFO, " Max. read current @ VDD max 0x%x\n", Csd->VddRCurrMax)); - DEBUG((DEBUG_INFO, " Max. write current @ VDD min 0x%x\n", Csd->VddWCurrMin)); - DEBUG((DEBUG_INFO, " Max. write current @ VDD max 0x%x\n", Csd->VddWCurrMax)); - DEBUG((DEBUG_INFO, " Device size multiplier 0x%x\n", Csd->CSizeMult)); - DEBUG((DEBUG_INFO, " Erase group size 0x%x\n", Csd->EraseGrpSize)); - DEBUG((DEBUG_INFO, " Erase group size multiplier 0x%x\n", Csd->EraseGrpMult)); - DEBUG((DEBUG_INFO, " Write protect group size 0x%x\n", Csd->WpGrpSize)); - DEBUG((DEBUG_INFO, " Write protect group enable 0x%x\n", Csd->WpGrpEnable)); - DEBUG((DEBUG_INFO, " Manufacturer default ECC 0x%x\n", Csd->DefaultEcc)); - DEBUG((DEBUG_INFO, " Write speed factor 0x%x\n", Csd->R2WFactor)); - DEBUG((DEBUG_INFO, " Max. write data block length 0x%x\n", Csd->WriteBlLen)); - DEBUG((DEBUG_INFO, " Partial blocks for write allowed 0x%x\n", Csd->WriteBlPartial)); - DEBUG((DEBUG_INFO, " Content protection application 0x%x\n", Csd->ContentProtApp)); - DEBUG((DEBUG_INFO, " File format group 0x%x\n", Csd->FileFormatGrp)); - DEBUG((DEBUG_INFO, " Copy flag (OTP) 0x%x\n", Csd->Copy)); - DEBUG((DEBUG_INFO, " Permanent write protection 0x%x\n", Csd->PermWriteProtect)); - DEBUG((DEBUG_INFO, " Temporary write protection 0x%x\n", Csd->TmpWriteProtect)); - DEBUG((DEBUG_INFO, " File format 0x%x\n", Csd->FileFormat)); - DEBUG((DEBUG_INFO, " ECC code 0x%x\n", Csd->Ecc)); + DEBUG ((DEBUG_INFO, "== Dump Emmc Csd Register==\n")); + DEBUG ((DEBUG_INFO, " CSD structure 0x%x\n", Csd->CsdStructure)); + DEBUG ((DEBUG_INFO, " System specification version 0x%x\n", Csd->SpecVers)); + DEBUG ((DEBUG_INFO, " Data read access-time 1 0x%x\n", Csd->Taac)); + DEBUG ((DEBUG_INFO, " Data read access-time 2 0x%x\n", Csd->Nsac)); + DEBUG ((DEBUG_INFO, " Max. bus clock frequency 0x%x\n", Csd->TranSpeed)); + DEBUG ((DEBUG_INFO, " Device command classes 0x%x\n", Csd->Ccc)); + DEBUG ((DEBUG_INFO, " Max. read data block length 0x%x\n", Csd->ReadBlLen)); + DEBUG ((DEBUG_INFO, " Partial blocks for read allowed 0x%x\n", Csd->ReadBlPartial)); + DEBUG ((DEBUG_INFO, " Write block misalignment 0x%x\n", Csd->WriteBlkMisalign)); + DEBUG ((DEBUG_INFO, " Read block misalignment 0x%x\n", Csd->ReadBlkMisalign)); + DEBUG ((DEBUG_INFO, " DSR implemented 0x%x\n", Csd->DsrImp)); + DEBUG ((DEBUG_INFO, " Device size 0x%x\n", Csd->CSizeLow | (Csd->CSizeHigh << 2))); + DEBUG ((DEBUG_INFO, " Max. read current @ VDD min 0x%x\n", Csd->VddRCurrMin)); + DEBUG ((DEBUG_INFO, " Max. read current @ VDD max 0x%x\n", Csd->VddRCurrMax)); + DEBUG ((DEBUG_INFO, " Max. write current @ VDD min 0x%x\n", Csd->VddWCurrMin)); + DEBUG ((DEBUG_INFO, " Max. write current @ VDD max 0x%x\n", Csd->VddWCurrMax)); + DEBUG ((DEBUG_INFO, " Device size multiplier 0x%x\n", Csd->CSizeMult)); + DEBUG ((DEBUG_INFO, " Erase group size 0x%x\n", Csd->EraseGrpSize)); + DEBUG ((DEBUG_INFO, " Erase group size multiplier 0x%x\n", Csd->EraseGrpMult)); + DEBUG ((DEBUG_INFO, " Write protect group size 0x%x\n", Csd->WpGrpSize)); + DEBUG ((DEBUG_INFO, " Write protect group enable 0x%x\n", Csd->WpGrpEnable)); + DEBUG ((DEBUG_INFO, " Manufacturer default ECC 0x%x\n", Csd->DefaultEcc)); + DEBUG ((DEBUG_INFO, " Write speed factor 0x%x\n", Csd->R2WFactor)); + DEBUG ((DEBUG_INFO, " Max. write data block length 0x%x\n", Csd->WriteBlLen)); + DEBUG ((DEBUG_INFO, " Partial blocks for write allowed 0x%x\n", Csd->WriteBlPartial)); + DEBUG ((DEBUG_INFO, " Content protection application 0x%x\n", Csd->ContentProtApp)); + DEBUG ((DEBUG_INFO, " File format group 0x%x\n", Csd->FileFormatGrp)); + DEBUG ((DEBUG_INFO, " Copy flag (OTP) 0x%x\n", Csd->Copy)); + DEBUG ((DEBUG_INFO, " Permanent write protection 0x%x\n", Csd->PermWriteProtect)); + DEBUG ((DEBUG_INFO, " Temporary write protection 0x%x\n", Csd->TmpWriteProtect)); + DEBUG ((DEBUG_INFO, " File format 0x%x\n", Csd->FileFormat)); + DEBUG ((DEBUG_INFO, " ECC code 0x%x\n", Csd->Ecc)); return EFI_SUCCESS; } @@ -142,68 +142,98 @@ DumpExtCsd ( IN EMMC_EXT_CSD *ExtCsd ) { - DEBUG((DEBUG_INFO, "==Dump Emmc ExtCsd Register==\n")); - DEBUG((DEBUG_INFO, " Supported Command Sets 0x%x\n", ExtCsd->CmdSet)); - DEBUG((DEBUG_INFO, " HPI features 0x%x\n", ExtCsd->HpiFeatures)); - DEBUG((DEBUG_INFO, " Background operations support 0x%x\n", ExtCsd->BkOpsSupport)); - DEBUG((DEBUG_INFO, " Background operations status 0x%x\n", ExtCsd->BkopsStatus)); - DEBUG((DEBUG_INFO, " Number of correctly programmed sectors 0x%x\n", *((UINT32*)&ExtCsd->CorrectlyPrgSectorsNum[0]))); - DEBUG((DEBUG_INFO, " Initialization time after partitioning 0x%x\n", ExtCsd->IniTimeoutAp)); - DEBUG((DEBUG_INFO, " TRIM Multiplier 0x%x\n", ExtCsd->TrimMult)); - DEBUG((DEBUG_INFO, " Secure Feature support 0x%x\n", ExtCsd->SecFeatureSupport)); - DEBUG((DEBUG_INFO, " Secure Erase Multiplier 0x%x\n", ExtCsd->SecEraseMult)); - DEBUG((DEBUG_INFO, " Secure TRIM Multiplier 0x%x\n", ExtCsd->SecTrimMult)); - DEBUG((DEBUG_INFO, " Boot information 0x%x\n", ExtCsd->BootInfo)); - DEBUG((DEBUG_INFO, " Boot partition size 0x%x\n", ExtCsd->BootSizeMult)); - DEBUG((DEBUG_INFO, " Access size 0x%x\n", ExtCsd->AccSize)); - DEBUG((DEBUG_INFO, " High-capacity erase unit size 0x%x\n", ExtCsd->HcEraseGrpSize)); - DEBUG((DEBUG_INFO, " High-capacity erase timeout 0x%x\n", ExtCsd->EraseTimeoutMult)); - DEBUG((DEBUG_INFO, " Reliable write sector count 0x%x\n", ExtCsd->RelWrSecC)); - DEBUG((DEBUG_INFO, " High-capacity write protect group size 0x%x\n", ExtCsd->HcWpGrpSize)); - DEBUG((DEBUG_INFO, " Sleep/awake timeout 0x%x\n", ExtCsd->SATimeout)); - DEBUG((DEBUG_INFO, " Sector Count 0x%x\n", *((UINT32*)&ExtCsd->SecCount[0]))); - DEBUG((DEBUG_INFO, " Partition switching timing 0x%x\n", ExtCsd->PartitionSwitchTime)); - DEBUG((DEBUG_INFO, " Out-of-interrupt busy timing 0x%x\n", ExtCsd->OutOfInterruptTime)); - DEBUG((DEBUG_INFO, " I/O Driver Strength 0x%x\n", ExtCsd->DriverStrength)); - DEBUG((DEBUG_INFO, " Device type 0x%x\n", ExtCsd->DeviceType)); - DEBUG((DEBUG_INFO, " CSD STRUCTURE 0x%x\n", ExtCsd->CsdStructure)); - DEBUG((DEBUG_INFO, " Extended CSD revision 0x%x\n", ExtCsd->ExtCsdRev)); - DEBUG((DEBUG_INFO, " Command set 0x%x\n", ExtCsd->CmdSet)); - DEBUG((DEBUG_INFO, " Command set revision 0x%x\n", ExtCsd->CmdSetRev)); - DEBUG((DEBUG_INFO, " Power class 0x%x\n", ExtCsd->PowerClass)); - DEBUG((DEBUG_INFO, " High-speed interface timing 0x%x\n", ExtCsd->HsTiming)); - DEBUG((DEBUG_INFO, " Bus width mode 0x%x\n", ExtCsd->BusWidth)); - DEBUG((DEBUG_INFO, " Erased memory content 0x%x\n", ExtCsd->ErasedMemCont)); - DEBUG((DEBUG_INFO, " Partition configuration 0x%x\n", ExtCsd->PartitionConfig)); - DEBUG((DEBUG_INFO, " Boot config protection 0x%x\n", ExtCsd->BootConfigProt)); - DEBUG((DEBUG_INFO, " Boot bus Conditions 0x%x\n", ExtCsd->BootBusConditions)); - DEBUG((DEBUG_INFO, " High-density erase group definition 0x%x\n", ExtCsd->EraseGroupDef)); - DEBUG((DEBUG_INFO, " Boot write protection status register 0x%x\n", ExtCsd->BootWpStatus)); - DEBUG((DEBUG_INFO, " Boot area write protection register 0x%x\n", ExtCsd->BootWp)); - DEBUG((DEBUG_INFO, " User area write protection register 0x%x\n", ExtCsd->UserWp)); - DEBUG((DEBUG_INFO, " FW configuration 0x%x\n", ExtCsd->FwConfig)); - DEBUG((DEBUG_INFO, " RPMB Size 0x%x\n", ExtCsd->RpmbSizeMult)); - DEBUG((DEBUG_INFO, " H/W reset function 0x%x\n", ExtCsd->RstFunction)); - DEBUG((DEBUG_INFO, " Partitioning Support 0x%x\n", ExtCsd->PartitioningSupport)); - DEBUG((DEBUG_INFO, " Max Enhanced Area Size 0x%02x%02x%02x\n", \ - ExtCsd->MaxEnhSizeMult[2], ExtCsd->MaxEnhSizeMult[1], ExtCsd->MaxEnhSizeMult[0])); - DEBUG((DEBUG_INFO, " Partitions attribute 0x%x\n", ExtCsd->PartitionsAttribute)); - DEBUG((DEBUG_INFO, " Partitioning Setting 0x%x\n", ExtCsd->PartitionSettingCompleted)); - DEBUG((DEBUG_INFO, " General Purpose Partition 1 Size 0x%02x%02x%02x\n", \ - ExtCsd->GpSizeMult[2], ExtCsd->GpSizeMult[1], ExtCsd->GpSizeMult[0])); - DEBUG((DEBUG_INFO, " General Purpose Partition 2 Size 0x%02x%02x%02x\n", \ - ExtCsd->GpSizeMult[5], ExtCsd->GpSizeMult[4], ExtCsd->GpSizeMult[3])); - DEBUG((DEBUG_INFO, " General Purpose Partition 3 Size 0x%02x%02x%02x\n", \ - ExtCsd->GpSizeMult[8], ExtCsd->GpSizeMult[7], ExtCsd->GpSizeMult[6])); - DEBUG((DEBUG_INFO, " General Purpose Partition 4 Size 0x%02x%02x%02x\n", \ - ExtCsd->GpSizeMult[11], ExtCsd->GpSizeMult[10], ExtCsd->GpSizeMult[9])); - DEBUG((DEBUG_INFO, " Enhanced User Data Area Size 0x%02x%02x%02x\n", \ - ExtCsd->EnhSizeMult[2], ExtCsd->EnhSizeMult[1], ExtCsd->EnhSizeMult[0])); - DEBUG((DEBUG_INFO, " Enhanced User Data Start Address 0x%x\n", *((UINT32*)&ExtCsd->EnhStartAddr[0]))); - DEBUG((DEBUG_INFO, " Bad Block Management mode 0x%x\n", ExtCsd->SecBadBlkMgmnt)); - DEBUG((DEBUG_INFO, " Native sector size 0x%x\n", ExtCsd->NativeSectorSize)); - DEBUG((DEBUG_INFO, " Sector size emulation 0x%x\n", ExtCsd->UseNativeSector)); - DEBUG((DEBUG_INFO, " Sector size 0x%x\n", ExtCsd->DataSectorSize)); + DEBUG ((DEBUG_INFO, "==Dump Emmc ExtCsd Register==\n")); + DEBUG ((DEBUG_INFO, " Supported Command Sets 0x%x\n", ExtCsd->CmdSet)); + DEBUG ((DEBUG_INFO, " HPI features 0x%x\n", ExtCsd->HpiFeatures)); + DEBUG ((DEBUG_INFO, " Background operations support 0x%x\n", ExtCsd->BkOpsSupport)); + DEBUG ((DEBUG_INFO, " Background operations status 0x%x\n", ExtCsd->BkopsStatus)); + DEBUG ((DEBUG_INFO, " Number of correctly programmed sectors 0x%x\n", *((UINT32 *)&ExtCsd->CorrectlyPrgSectorsNum[0]))); + DEBUG ((DEBUG_INFO, " Initialization time after partitioning 0x%x\n", ExtCsd->IniTimeoutAp)); + DEBUG ((DEBUG_INFO, " TRIM Multiplier 0x%x\n", ExtCsd->TrimMult)); + DEBUG ((DEBUG_INFO, " Secure Feature support 0x%x\n", ExtCsd->SecFeatureSupport)); + DEBUG ((DEBUG_INFO, " Secure Erase Multiplier 0x%x\n", ExtCsd->SecEraseMult)); + DEBUG ((DEBUG_INFO, " Secure TRIM Multiplier 0x%x\n", ExtCsd->SecTrimMult)); + DEBUG ((DEBUG_INFO, " Boot information 0x%x\n", ExtCsd->BootInfo)); + DEBUG ((DEBUG_INFO, " Boot partition size 0x%x\n", ExtCsd->BootSizeMult)); + DEBUG ((DEBUG_INFO, " Access size 0x%x\n", ExtCsd->AccSize)); + DEBUG ((DEBUG_INFO, " High-capacity erase unit size 0x%x\n", ExtCsd->HcEraseGrpSize)); + DEBUG ((DEBUG_INFO, " High-capacity erase timeout 0x%x\n", ExtCsd->EraseTimeoutMult)); + DEBUG ((DEBUG_INFO, " Reliable write sector count 0x%x\n", ExtCsd->RelWrSecC)); + DEBUG ((DEBUG_INFO, " High-capacity write protect group size 0x%x\n", ExtCsd->HcWpGrpSize)); + DEBUG ((DEBUG_INFO, " Sleep/awake timeout 0x%x\n", ExtCsd->SATimeout)); + DEBUG ((DEBUG_INFO, " Sector Count 0x%x\n", *((UINT32 *)&ExtCsd->SecCount[0]))); + DEBUG ((DEBUG_INFO, " Partition switching timing 0x%x\n", ExtCsd->PartitionSwitchTime)); + DEBUG ((DEBUG_INFO, " Out-of-interrupt busy timing 0x%x\n", ExtCsd->OutOfInterruptTime)); + DEBUG ((DEBUG_INFO, " I/O Driver Strength 0x%x\n", ExtCsd->DriverStrength)); + DEBUG ((DEBUG_INFO, " Device type 0x%x\n", ExtCsd->DeviceType)); + DEBUG ((DEBUG_INFO, " CSD STRUCTURE 0x%x\n", ExtCsd->CsdStructure)); + DEBUG ((DEBUG_INFO, " Extended CSD revision 0x%x\n", ExtCsd->ExtCsdRev)); + DEBUG ((DEBUG_INFO, " Command set 0x%x\n", ExtCsd->CmdSet)); + DEBUG ((DEBUG_INFO, " Command set revision 0x%x\n", ExtCsd->CmdSetRev)); + DEBUG ((DEBUG_INFO, " Power class 0x%x\n", ExtCsd->PowerClass)); + DEBUG ((DEBUG_INFO, " High-speed interface timing 0x%x\n", ExtCsd->HsTiming)); + DEBUG ((DEBUG_INFO, " Bus width mode 0x%x\n", ExtCsd->BusWidth)); + DEBUG ((DEBUG_INFO, " Erased memory content 0x%x\n", ExtCsd->ErasedMemCont)); + DEBUG ((DEBUG_INFO, " Partition configuration 0x%x\n", ExtCsd->PartitionConfig)); + DEBUG ((DEBUG_INFO, " Boot config protection 0x%x\n", ExtCsd->BootConfigProt)); + DEBUG ((DEBUG_INFO, " Boot bus Conditions 0x%x\n", ExtCsd->BootBusConditions)); + DEBUG ((DEBUG_INFO, " High-density erase group definition 0x%x\n", ExtCsd->EraseGroupDef)); + DEBUG ((DEBUG_INFO, " Boot write protection status register 0x%x\n", ExtCsd->BootWpStatus)); + DEBUG ((DEBUG_INFO, " Boot area write protection register 0x%x\n", ExtCsd->BootWp)); + DEBUG ((DEBUG_INFO, " User area write protection register 0x%x\n", ExtCsd->UserWp)); + DEBUG ((DEBUG_INFO, " FW configuration 0x%x\n", ExtCsd->FwConfig)); + DEBUG ((DEBUG_INFO, " RPMB Size 0x%x\n", ExtCsd->RpmbSizeMult)); + DEBUG ((DEBUG_INFO, " H/W reset function 0x%x\n", ExtCsd->RstFunction)); + DEBUG ((DEBUG_INFO, " Partitioning Support 0x%x\n", ExtCsd->PartitioningSupport)); + DEBUG (( + DEBUG_INFO, + " Max Enhanced Area Size 0x%02x%02x%02x\n", \ + ExtCsd->MaxEnhSizeMult[2], + ExtCsd->MaxEnhSizeMult[1], + ExtCsd->MaxEnhSizeMult[0] + )); + DEBUG ((DEBUG_INFO, " Partitions attribute 0x%x\n", ExtCsd->PartitionsAttribute)); + DEBUG ((DEBUG_INFO, " Partitioning Setting 0x%x\n", ExtCsd->PartitionSettingCompleted)); + DEBUG (( + DEBUG_INFO, + " General Purpose Partition 1 Size 0x%02x%02x%02x\n", \ + ExtCsd->GpSizeMult[2], + ExtCsd->GpSizeMult[1], + ExtCsd->GpSizeMult[0] + )); + DEBUG (( + DEBUG_INFO, + " General Purpose Partition 2 Size 0x%02x%02x%02x\n", \ + ExtCsd->GpSizeMult[5], + ExtCsd->GpSizeMult[4], + ExtCsd->GpSizeMult[3] + )); + DEBUG (( + DEBUG_INFO, + " General Purpose Partition 3 Size 0x%02x%02x%02x\n", \ + ExtCsd->GpSizeMult[8], + ExtCsd->GpSizeMult[7], + ExtCsd->GpSizeMult[6] + )); + DEBUG (( + DEBUG_INFO, + " General Purpose Partition 4 Size 0x%02x%02x%02x\n", \ + ExtCsd->GpSizeMult[11], + ExtCsd->GpSizeMult[10], + ExtCsd->GpSizeMult[9] + )); + DEBUG (( + DEBUG_INFO, + " Enhanced User Data Area Size 0x%02x%02x%02x\n", \ + ExtCsd->EnhSizeMult[2], + ExtCsd->EnhSizeMult[1], + ExtCsd->EnhSizeMult[0] + )); + DEBUG ((DEBUG_INFO, " Enhanced User Data Start Address 0x%x\n", *((UINT32 *)&ExtCsd->EnhStartAddr[0]))); + DEBUG ((DEBUG_INFO, " Bad Block Management mode 0x%x\n", ExtCsd->SecBadBlkMgmnt)); + DEBUG ((DEBUG_INFO, " Native sector size 0x%x\n", ExtCsd->NativeSectorSize)); + DEBUG ((DEBUG_INFO, " Sector size emulation 0x%x\n", ExtCsd->UseNativeSector)); + DEBUG ((DEBUG_INFO, " Sector size 0x%x\n", ExtCsd->DataSectorSize)); return EFI_SUCCESS; } @@ -219,8 +249,8 @@ DumpExtCsd ( **/ EFI_STATUS GetEmmcModelName ( - IN OUT EMMC_DEVICE *Device, - IN EMMC_CID *Cid + IN OUT EMMC_DEVICE *Device, + IN EMMC_CID *Cid ) { CHAR8 String[EMMC_MODEL_NAME_MAX_LEN]; @@ -248,27 +278,28 @@ GetEmmcModelName ( **/ EFI_STATUS DiscoverAllPartitions ( - IN EMMC_DEVICE *Device + IN EMMC_DEVICE *Device ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; - EMMC_CSD *Csd; - EMMC_CID *Cid; - EMMC_EXT_CSD *ExtCsd; - UINT8 Slot; - UINT64 Capacity; - UINT32 DevStatus; - UINT8 Index; - UINT32 SecCount; - UINT32 GpSizeMult; - - Slot = Device->Slot; + EFI_STATUS Status; + EMMC_PARTITION *Partition; + EMMC_CSD *Csd; + EMMC_CID *Cid; + EMMC_EXT_CSD *ExtCsd; + UINT8 Slot; + UINT64 Capacity; + UINT32 DevStatus; + UINT8 Index; + UINT32 SecCount; + UINT32 GpSizeMult; + + Slot = Device->Slot; Status = EmmcSendStatus (Device, Slot + 1, &DevStatus); if (EFI_ERROR (Status)) { return Status; } + // // Deselect the device to force it enter stby mode before getting CSD // register content. @@ -287,6 +318,7 @@ DiscoverAllPartitions ( if (EFI_ERROR (Status)) { return Status; } + DumpCsd (Csd); if ((Csd->CSizeLow | Csd->CSizeHigh << 2) == 0xFFF) { @@ -311,6 +343,7 @@ DiscoverAllPartitions ( if (EFI_ERROR (Status)) { return Status; } + DumpExtCsd (ExtCsd); if (ExtCsd->ExtCsdRev < 5) { @@ -326,22 +359,22 @@ DiscoverAllPartitions ( for (Index = 0; Index < EMMC_MAX_PARTITIONS; Index++) { Partition = &Device->Partition[Index]; CopyMem (Partition, &mEmmcPartitionTemplate, sizeof (EMMC_PARTITION)); - Partition->Device = Device; + Partition->Device = Device; InitializeListHead (&Partition->Queue); - Partition->BlockIo.Media = &Partition->BlockMedia; - Partition->BlockIo2.Media = &Partition->BlockMedia; - Partition->PartitionType = Index; - Partition->BlockMedia.IoAlign = Device->Private->PassThru->IoAlign; - Partition->BlockMedia.BlockSize = 0x200; - Partition->BlockMedia.LastBlock = 0x00; - Partition->BlockMedia.RemovableMedia = FALSE; + Partition->BlockIo.Media = &Partition->BlockMedia; + Partition->BlockIo2.Media = &Partition->BlockMedia; + Partition->PartitionType = Index; + Partition->BlockMedia.IoAlign = Device->Private->PassThru->IoAlign; + Partition->BlockMedia.BlockSize = 0x200; + Partition->BlockMedia.LastBlock = 0x00; + Partition->BlockMedia.RemovableMedia = FALSE; Partition->BlockMedia.MediaPresent = TRUE; Partition->BlockMedia.LogicalPartition = FALSE; switch (Index) { case EmmcPartitionUserData: - SecCount = *(UINT32*)&ExtCsd->SecCount; - Capacity = MultU64x32 ((UINT64) SecCount, 0x200); + SecCount = *(UINT32 *)&ExtCsd->SecCount; + Capacity = MultU64x32 ((UINT64)SecCount, 0x200); break; case EmmcPartitionBoot1: case EmmcPartitionBoot2: @@ -352,19 +385,19 @@ DiscoverAllPartitions ( break; case EmmcPartitionGP1: GpSizeMult = (UINT32)(ExtCsd->GpSizeMult[0] | (ExtCsd->GpSizeMult[1] << 8) | (ExtCsd->GpSizeMult[2] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP2: GpSizeMult = (UINT32)(ExtCsd->GpSizeMult[3] | (ExtCsd->GpSizeMult[4] << 8) | (ExtCsd->GpSizeMult[5] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP3: GpSizeMult = (UINT32)(ExtCsd->GpSizeMult[6] | (ExtCsd->GpSizeMult[7] << 8) | (ExtCsd->GpSizeMult[8] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; case EmmcPartitionGP4: GpSizeMult = (UINT32)(ExtCsd->GpSizeMult[9] | (ExtCsd->GpSizeMult[10] << 8) | (ExtCsd->GpSizeMult[11] << 16)); - Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); + Capacity = MultU64x32 (MultU64x32 (MultU64x32 ((UINT64)GpSizeMult, ExtCsd->HcWpGrpSize), ExtCsd->HcEraseGrpSize), SIZE_512KB); break; default: ASSERT (FALSE); @@ -372,7 +405,7 @@ DiscoverAllPartitions ( } if (Capacity != 0) { - Partition->Enable = TRUE; + Partition->Enable = TRUE; Partition->BlockMedia.LastBlock = DivU64x32 (Capacity, Partition->BlockMedia.BlockSize) - 1; } @@ -402,17 +435,17 @@ DiscoverAllPartitions ( **/ EFI_STATUS InstallProtocolOnPartition ( - IN EMMC_DEVICE *Device, - IN UINT8 Index + IN EMMC_DEVICE *Device, + IN UINT8 Index ) { - EFI_STATUS Status; - EMMC_PARTITION *Partition; - CONTROLLER_DEVICE_PATH ControlNode; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - EFI_HANDLE DeviceHandle; + EFI_STATUS Status; + EMMC_PARTITION *Partition; + CONTROLLER_DEVICE_PATH ControlNode; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + EFI_HANDLE DeviceHandle; // // Build device path @@ -424,21 +457,21 @@ InstallProtocolOnPartition ( SetDevicePathNodeLength (&ControlNode.Header, sizeof (CONTROLLER_DEVICE_PATH)); ControlNode.ControllerNumber = Index; - DevicePath = AppendDevicePathNode (ParentDevicePath, (EFI_DEVICE_PATH_PROTOCOL*)&ControlNode); + DevicePath = AppendDevicePathNode (ParentDevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&ControlNode); if (DevicePath == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Error; } - DeviceHandle = NULL; + DeviceHandle = NULL; RemainingDevicePath = DevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) { + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (RemainingDevicePath)) { Status = EFI_ALREADY_STARTED; goto Error; } - Partition = &Device->Partition[Index]; + Partition = &Device->Partition[Index]; Partition->DevicePath = DevicePath; if (Partition->Enable) { // @@ -464,9 +497,10 @@ InstallProtocolOnPartition ( } if (((Partition->PartitionType == EmmcPartitionUserData) || - (Partition->PartitionType == EmmcPartitionBoot1) || - (Partition->PartitionType == EmmcPartitionBoot2)) && - ((Device->Csd.Ccc & BIT10) != 0)) { + (Partition->PartitionType == EmmcPartitionBoot1) || + (Partition->PartitionType == EmmcPartitionBoot2)) && + ((Device->Csd.Ccc & BIT10) != 0)) + { Status = gBS->InstallProtocolInterface ( &Partition->Handle, &gEfiStorageSecurityCommandProtocolGuid, @@ -495,13 +529,12 @@ InstallProtocolOnPartition ( gBS->OpenProtocol ( Device->Private->Controller, &gEfiSdMmcPassThruProtocolGuid, - (VOID **) &(Device->Private->PassThru), + (VOID **)&(Device->Private->PassThru), Device->Private->DriverBindingHandle, Partition->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); } - } else { Status = EFI_INVALID_PARAMETER; } @@ -532,27 +565,27 @@ Error: EFI_STATUS EFIAPI DiscoverEmmcDevice ( - IN EMMC_DRIVER_PRIVATE_DATA *Private, - IN UINT8 Slot, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EMMC_DRIVER_PRIVATE_DATA *Private, + IN UINT8 Slot, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EMMC_DEVICE *Device; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; - EFI_DEVICE_PATH_PROTOCOL *RemainingEmmcDevPath; - EFI_DEV_PATH *Node; - EFI_HANDLE DeviceHandle; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - UINT8 Index; + EFI_STATUS Status; + EMMC_DEVICE *Device; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; + EFI_DEVICE_PATH_PROTOCOL *RemainingEmmcDevPath; + EFI_DEV_PATH *Node; + EFI_HANDLE DeviceHandle; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + UINT8 Index; Device = NULL; DevicePath = NULL; NewDevicePath = NULL; RemainingDevicePath = NULL; - PassThru = Private->PassThru; - Device = &Private->Device[Slot]; + PassThru = Private->PassThru; + Device = &Private->Device[Slot]; // // Build Device Path to check if the EMMC device present at the slot. @@ -562,7 +595,7 @@ DiscoverEmmcDevice ( Slot, &DevicePath ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -582,7 +615,7 @@ DiscoverEmmcDevice ( DeviceHandle = NULL; RemainingEmmcDevPath = NewDevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingEmmcDevPath, &DeviceHandle); + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingEmmcDevPath, &DeviceHandle); // // The device path to the EMMC device doesn't exist. It means the corresponding device private data hasn't been initialized. // @@ -594,7 +627,7 @@ DiscoverEmmcDevice ( // Expose user area in the Sd memory card to upper layer. // Status = DiscoverAllPartitions (Device); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { FreePool (NewDevicePath); goto Error; } @@ -605,7 +638,7 @@ DiscoverEmmcDevice ( EFI_NATIVE_INTERFACE, Device->DevicePath ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { FreePool (NewDevicePath); goto Error; } @@ -639,10 +672,11 @@ DiscoverEmmcDevice ( // // Enumerate the specified partition // - Node = (EFI_DEV_PATH *) RemainingDevicePath; + Node = (EFI_DEV_PATH *)RemainingDevicePath; if ((DevicePathType (&Node->DevPath) != HARDWARE_DEVICE_PATH) || (DevicePathSubType (&Node->DevPath) != HW_CONTROLLER_DP) || - (DevicePathNodeLength (&Node->DevPath) != sizeof (CONTROLLER_DEVICE_PATH))) { + (DevicePathNodeLength (&Node->DevPath) != sizeof (CONTROLLER_DEVICE_PATH))) + { Status = EFI_INVALID_PARAMETER; goto Error; } @@ -707,15 +741,15 @@ Error: EFI_STATUS EFIAPI EmmcDxeDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - UINT8 Slot; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + UINT8 Slot; // // Test EFI_SD_MMC_PASS_THRU_PROTOCOL on the controller handle. @@ -723,7 +757,7 @@ EmmcDxeDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiSdMmcPassThruProtocolGuid, - (VOID**) &PassThru, + (VOID **)&PassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -772,7 +806,7 @@ EmmcDxeDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -818,27 +852,27 @@ EmmcDxeDriverBindingSupported ( EFI_STATUS EFIAPI EmmcDxeDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EMMC_DRIVER_PRIVATE_DATA *Private; - UINT8 Slot; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EMMC_DRIVER_PRIVATE_DATA *Private; + UINT8 Slot; Private = NULL; PassThru = NULL; - Status = gBS->OpenProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - (VOID **) &PassThru, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiSdMmcPassThruProtocolGuid, + (VOID **)&PassThru, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if ((EFI_ERROR (Status)) && (Status != EFI_ALREADY_STARTED)) { return Status; } @@ -856,7 +890,7 @@ EmmcDxeDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -880,7 +914,7 @@ EmmcDxeDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &Private, + (VOID **)&Private, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -933,6 +967,7 @@ Error: FreePool (Private); } } + return Status; } @@ -965,10 +1000,10 @@ Error: EFI_STATUS EFIAPI EmmcDxeDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -991,7 +1026,7 @@ EmmcDxeDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &Private, + (VOID **)&Private, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1005,7 +1040,7 @@ EmmcDxeDriverBindingStop ( Status = gBS->OpenProtocol ( Device->Handle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1013,6 +1048,7 @@ EmmcDxeDriverBindingStop ( if (EFI_ERROR (Status)) { continue; } + ASSERT (DevicePath == Device->DevicePath); gBS->UninstallProtocolInterface ( Device->Handle, @@ -1023,16 +1059,16 @@ EmmcDxeDriverBindingStop ( } gBS->UninstallProtocolInterface ( - Controller, - &gEfiCallerIdGuid, - Private - ); + Controller, + &gEfiCallerIdGuid, + Private + ); gBS->CloseProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiSdMmcPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); FreePool (Private); return EFI_SUCCESS; @@ -1044,7 +1080,7 @@ EmmcDxeDriverBindingStop ( Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1053,7 +1089,7 @@ EmmcDxeDriverBindingStop ( Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiBlockIo2ProtocolGuid, - (VOID **) &BlockIo2, + (VOID **)&BlockIo2, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1073,7 +1109,8 @@ EmmcDxeDriverBindingStop ( for (Link = GetFirstNode (&Partition->Queue); !IsNull (&Partition->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Partition->Queue, Link); RemoveEntryList (Link); @@ -1132,7 +1169,7 @@ EmmcDxeDriverBindingStop ( Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiStorageSecurityCommandProtocolGuid, - (VOID **) &StorageSecurity, + (VOID **)&StorageSecurity, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1146,13 +1183,13 @@ EmmcDxeDriverBindingStop ( ); if (EFI_ERROR (Status)) { gBS->OpenProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - (VOID **) &Partition->Device->Private->PassThru, - This->DriverBindingHandle, - ChildHandleBuffer[Index], - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + Controller, + &gEfiSdMmcPassThruProtocolGuid, + (VOID **)&Partition->Device->Private->PassThru, + This->DriverBindingHandle, + ChildHandleBuffer[Index], + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); AllChildrenStopped = FALSE; continue; } @@ -1181,11 +1218,11 @@ EmmcDxeDriverBindingStop ( EFI_STATUS EFIAPI InitializeEmmcDxe ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). diff --git a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.h b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.h index 5ecce41dee..a83d4ec1df 100644 --- a/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.h +++ b/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcDxe.h @@ -40,11 +40,11 @@ // // Global Variables // -extern EFI_DRIVER_BINDING_PROTOCOL gEmmcDxeDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gEmmcDxeComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gEmmcDxeComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gEmmcDxeDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gEmmcDxeComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gEmmcDxeComponentName2; -#define EMMC_PARTITION_SIGNATURE SIGNATURE_32 ('E', 'm', 'm', 'P') +#define EMMC_PARTITION_SIGNATURE SIGNATURE_32 ('E', 'm', 'm', 'P') #define EMMC_PARTITION_DATA_FROM_BLKIO(a) \ CR(a, EMMC_PARTITION, BlockIo, EMMC_PARTITION_SIGNATURE) @@ -64,72 +64,72 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gEmmcDxeComponentName2; // // Take 2.5 seconds as generic time out value, 1 microsecond as unit. // -#define EMMC_GENERIC_TIMEOUT 2500 * 1000 +#define EMMC_GENERIC_TIMEOUT 2500 * 1000 -#define EMMC_REQUEST_SIGNATURE SIGNATURE_32 ('E', 'm', 'R', 'e') +#define EMMC_REQUEST_SIGNATURE SIGNATURE_32 ('E', 'm', 'R', 'e') -typedef struct _EMMC_DEVICE EMMC_DEVICE; -typedef struct _EMMC_DRIVER_PRIVATE_DATA EMMC_DRIVER_PRIVATE_DATA; +typedef struct _EMMC_DEVICE EMMC_DEVICE; +typedef struct _EMMC_DRIVER_PRIVATE_DATA EMMC_DRIVER_PRIVATE_DATA; // // Asynchronous I/O request. // typedef struct { - UINT32 Signature; - LIST_ENTRY Link; + UINT32 Signature; + LIST_ENTRY Link; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - BOOLEAN IsEnd; + BOOLEAN IsEnd; - EFI_BLOCK_IO2_TOKEN *Token; - EFI_EVENT Event; + EFI_BLOCK_IO2_TOKEN *Token; + EFI_EVENT Event; } EMMC_REQUEST; #define EMMC_REQUEST_FROM_LINK(a) \ CR(a, EMMC_REQUEST, Link, EMMC_REQUEST_SIGNATURE) typedef struct { - UINT32 Signature; - BOOLEAN Enable; - EMMC_PARTITION_TYPE PartitionType; - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_BLOCK_IO_PROTOCOL BlockIo; - EFI_BLOCK_IO2_PROTOCOL BlockIo2; - EFI_BLOCK_IO_MEDIA BlockMedia; - EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; - EFI_ERASE_BLOCK_PROTOCOL EraseBlock; - EFI_DISK_INFO_PROTOCOL DiskInfo; - - LIST_ENTRY Queue; - - EMMC_DEVICE *Device; + UINT32 Signature; + BOOLEAN Enable; + EMMC_PARTITION_TYPE PartitionType; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_BLOCK_IO_PROTOCOL BlockIo; + EFI_BLOCK_IO2_PROTOCOL BlockIo2; + EFI_BLOCK_IO_MEDIA BlockMedia; + EFI_STORAGE_SECURITY_COMMAND_PROTOCOL StorageSecurity; + EFI_ERASE_BLOCK_PROTOCOL EraseBlock; + EFI_DISK_INFO_PROTOCOL DiskInfo; + + LIST_ENTRY Queue; + + EMMC_DEVICE *Device; } EMMC_PARTITION; // // Up to 6 slots per EMMC PCI host controller // -#define EMMC_MAX_DEVICES 6 +#define EMMC_MAX_DEVICES 6 // // Up to 8 partitions per EMMC device. // -#define EMMC_MAX_PARTITIONS 8 -#define EMMC_MODEL_NAME_MAX_LEN 32 +#define EMMC_MAX_PARTITIONS 8 +#define EMMC_MODEL_NAME_MAX_LEN 32 struct _EMMC_DEVICE { - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINT8 Slot; - BOOLEAN SectorAddressing; - - EMMC_PARTITION Partition[EMMC_MAX_PARTITIONS]; - EMMC_CSD Csd; - EMMC_CID Cid; - EMMC_EXT_CSD ExtCsd; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINT8 Slot; + BOOLEAN SectorAddressing; + + EMMC_PARTITION Partition[EMMC_MAX_PARTITIONS]; + EMMC_CSD Csd; + EMMC_CID Cid; + EMMC_EXT_CSD ExtCsd; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; // // The model name consists of three fields in CID register // 1) OEM/Application ID (2 bytes) @@ -137,21 +137,21 @@ struct _EMMC_DEVICE { // 3) Product Serial Number (4 bytes) // The delimiters of these fields are whitespace. // - CHAR16 ModelName[EMMC_MODEL_NAME_MAX_LEN]; - EMMC_DRIVER_PRIVATE_DATA *Private; -} ; + CHAR16 ModelName[EMMC_MODEL_NAME_MAX_LEN]; + EMMC_DRIVER_PRIVATE_DATA *Private; +}; // // EMMC DXE driver private data structure // struct _EMMC_DRIVER_PRIVATE_DATA { - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_HANDLE Controller; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_HANDLE DriverBindingHandle; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_HANDLE Controller; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_HANDLE DriverBindingHandle; - EMMC_DEVICE Device[EMMC_MAX_DEVICES]; -} ; + EMMC_DEVICE Device[EMMC_MAX_DEVICES]; +}; /** Tests to see if this driver supports a given controller. If a child device is provided, @@ -198,9 +198,9 @@ struct _EMMC_DRIVER_PRIVATE_DATA { EFI_STATUS EFIAPI EmmcDxeDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -241,9 +241,9 @@ EmmcDxeDriverBindingSupported ( EFI_STATUS EFIAPI EmmcDxeDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -275,10 +275,10 @@ EmmcDxeDriverBindingStart ( EFI_STATUS EFIAPI EmmcDxeDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -399,11 +399,11 @@ EmmcDxeComponentNameGetDriverName ( EFI_STATUS EFIAPI EmmcDxeComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -419,8 +419,8 @@ EmmcDxeComponentNameGetControllerName ( **/ EFI_STATUS EmmcSelect ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca + IN EMMC_DEVICE *Device, + IN UINT16 Rca ); /** @@ -437,9 +437,9 @@ EmmcSelect ( **/ EFI_STATUS EmmcSendStatus ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT UINT32 *DevStatus + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT UINT32 *DevStatus ); /** @@ -456,9 +456,9 @@ EmmcSendStatus ( **/ EFI_STATUS EmmcGetCsd ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT EMMC_CSD *Csd + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT EMMC_CSD *Csd ); /** @@ -475,9 +475,9 @@ EmmcGetCsd ( **/ EFI_STATUS EmmcGetCid ( - IN EMMC_DEVICE *Device, - IN UINT16 Rca, - OUT EMMC_CID *Cid + IN EMMC_DEVICE *Device, + IN UINT16 Rca, + OUT EMMC_CID *Cid ); /** @@ -493,9 +493,8 @@ EmmcGetCid ( **/ EFI_STATUS EmmcGetExtCsd ( - IN EMMC_DEVICE *Device, - OUT EMMC_EXT_CSD *ExtCsd + IN EMMC_DEVICE *Device, + OUT EMMC_EXT_CSD *ExtCsd ); #endif - diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/DmaMem.c b/MdeModulePkg/Bus/Sd/SdBlockIoPei/DmaMem.c index 63ad6ce46a..3954e2a5d1 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/DmaMem.c +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/DmaMem.c @@ -32,11 +32,11 @@ EDKII_IOMMU_PPI *mIoMmu; **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { EFI_STATUS Status; @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -81,9 +83,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,7 +101,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { EFI_STATUS Status; @@ -109,6 +112,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -142,7 +146,7 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; if (mIoMmu != NULL) { @@ -157,18 +161,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = mIoMmu->Map ( - mIoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = mIoMmu->Map ( + mIoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -186,10 +191,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -207,9 +214,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { EFI_STATUS Status; @@ -221,6 +228,7 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -239,4 +247,3 @@ IoMmuInit ( (VOID **)&mIoMmu ); } - diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c index ddcd68bef7..06058e9ea0 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c @@ -10,7 +10,7 @@ // // Template for SD HC Slot Data. // -SD_PEIM_HC_SLOT gSdHcSlotTemplate = { +SD_PEIM_HC_SLOT gSdHcSlotTemplate = { SD_PEIM_SLOT_SIG, // Signature { // Media MSG_SD_DP, @@ -34,7 +34,7 @@ SD_PEIM_HC_SLOT gSdHcSlotTemplate = { // // Template for SD HC Private Data. // -SD_PEIM_HC_PRIVATE_DATA gSdHcPrivateTemplate = { +SD_PEIM_HC_PRIVATE_DATA gSdHcPrivateTemplate = { SD_PEIM_SIG, // Signature NULL, // Pool { // BlkIoPpi @@ -86,6 +86,7 @@ SD_PEIM_HC_PRIVATE_DATA gSdHcPrivateTemplate = { 0, // SlotNum 0 // TotalBlkIoDevices }; + /** Gets the count of block I/O devices that one specific block driver detects. @@ -113,9 +114,9 @@ SdBlockIoPeimGetDeviceNo ( OUT UINTN *NumberBlockDevices ) { - SD_PEIM_HC_PRIVATE_DATA *Private; + SD_PEIM_HC_PRIVATE_DATA *Private; - Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); + Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); *NumberBlockDevices = Private->TotalBlkIoDevices; return EFI_SUCCESS; } @@ -170,9 +171,9 @@ SdBlockIoPeimGetMediaInfo ( OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { - SD_PEIM_HC_PRIVATE_DATA *Private; + SD_PEIM_HC_PRIVATE_DATA *Private; - Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); + Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); if ((DeviceIndex == 0) || (DeviceIndex > Private->TotalBlkIoDevices) || (DeviceIndex > SD_PEIM_MAX_SLOTS)) { return EFI_INVALID_PARAMETER; @@ -231,12 +232,12 @@ SdBlockIoPeimReadBlocks ( OUT VOID *Buffer ) { - EFI_STATUS Status; - UINT32 BlockSize; - UINTN NumberOfBlocks; - SD_PEIM_HC_PRIVATE_DATA *Private; - UINTN Remaining; - UINT32 MaxBlock; + EFI_STATUS Status; + UINT32 BlockSize; + UINTN NumberOfBlocks; + SD_PEIM_HC_PRIVATE_DATA *Private; + UINTN Remaining; + UINT32 MaxBlock; Status = EFI_SUCCESS; Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); @@ -286,14 +287,16 @@ SdBlockIoPeimReadBlocks ( } else { Status = SdPeimRwSingleBlock (&Private->Slot[DeviceIndex - 1], StartLBA, BlockSize, Buffer, BufferSize, TRUE); } + if (EFI_ERROR (Status)) { return Status; } StartLBA += NumberOfBlocks; - Buffer = (UINT8*)Buffer + BufferSize; + Buffer = (UINT8 *)Buffer + BufferSize; Remaining -= NumberOfBlocks; } + return Status; } @@ -319,14 +322,14 @@ SdBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI SdBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ) { - SD_PEIM_HC_PRIVATE_DATA *Private; + SD_PEIM_HC_PRIVATE_DATA *Private; - Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); *NumberBlockDevices = Private->TotalBlkIoDevices; return EFI_SUCCESS; @@ -376,24 +379,24 @@ SdBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI SdBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - EFI_STATUS Status; - SD_PEIM_HC_PRIVATE_DATA *Private; - EFI_PEI_BLOCK_IO_MEDIA Media; + EFI_STATUS Status; + SD_PEIM_HC_PRIVATE_DATA *Private; + EFI_PEI_BLOCK_IO_MEDIA Media; Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - Status = SdBlockIoPeimGetMediaInfo ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - &Media - ); + Status = SdBlockIoPeimGetMediaInfo ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + &Media + ); if (EFI_ERROR (Status)) { return Status; } @@ -439,28 +442,28 @@ SdBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI SdBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - SD_PEIM_HC_PRIVATE_DATA *Private; - - Status = EFI_SUCCESS; - Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - - Status = SdBlockIoPeimReadBlocks ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - StartLBA, - BufferSize, - Buffer - ); + EFI_STATUS Status; + SD_PEIM_HC_PRIVATE_DATA *Private; + + Status = EFI_SUCCESS; + Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + + Status = SdBlockIoPeimReadBlocks ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + StartLBA, + BufferSize, + Buffer + ); return Status; } @@ -483,7 +486,7 @@ SdBlockIoPeimEndOfPei ( IN VOID *Ppi ) { - SD_PEIM_HC_PRIVATE_DATA *Private; + SD_PEIM_HC_PRIVATE_DATA *Private; Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY (NotifyDescriptor); @@ -507,26 +510,26 @@ SdBlockIoPeimEndOfPei ( EFI_STATUS EFIAPI InitializeSdBlockIoPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - SD_PEIM_HC_PRIVATE_DATA *Private; - EDKII_SD_MMC_HOST_CONTROLLER_PPI *SdMmcHcPpi; - UINT32 Index; - UINTN *MmioBase; - UINT8 BarNum; - UINT8 SlotNum; - UINT8 Controller; - UINT64 Capacity; - SD_HC_SLOT_CAP Capability; - SD_PEIM_HC_SLOT *Slot; - SD_CSD *Csd; - SD_CSD2 *Csd2; - UINT32 CSize; - UINT32 CSizeMul; - UINT32 ReadBlLen; + EFI_STATUS Status; + SD_PEIM_HC_PRIVATE_DATA *Private; + EDKII_SD_MMC_HOST_CONTROLLER_PPI *SdMmcHcPpi; + UINT32 Index; + UINTN *MmioBase; + UINT8 BarNum; + UINT8 SlotNum; + UINT8 Controller; + UINT64 Capacity; + SD_HC_SLOT_CAP Capability; + SD_PEIM_HC_SLOT *Slot; + SD_CSD *Csd; + SD_CSD2 *Csd2; + UINT32 CSize; + UINT32 CSizeMul; + UINT32 ReadBlLen; // // Shadow this PEIM to run from memory @@ -542,7 +545,7 @@ InitializeSdBlockIoPeim ( &gEdkiiPeiSdMmcHostControllerPpiGuid, 0, NULL, - (VOID **) &SdMmcHcPpi + (VOID **)&SdMmcHcPpi ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -571,8 +574,9 @@ InitializeSdBlockIoPeim ( Status = EFI_OUT_OF_RESOURCES; break; } - Private->BlkIoPpiList.Ppi = (VOID*)&Private->BlkIoPpi; - Private->BlkIo2PpiList.Ppi = (VOID*)&Private->BlkIo2Ppi; + + Private->BlkIoPpiList.Ppi = (VOID *)&Private->BlkIoPpi; + Private->BlkIo2PpiList.Ppi = (VOID *)&Private->BlkIo2Ppi; // // Initialize the memory pool which will be used in all transactions. // @@ -587,6 +591,7 @@ InitializeSdBlockIoPeim ( if (EFI_ERROR (Status)) { continue; } + if (Capability.SlotType != 0x1) { DEBUG ((DEBUG_INFO, "The slot at 0x%x is not embedded slot type\n", MmioBase[Index])); Status = EFI_UNSUPPORTED; @@ -597,10 +602,12 @@ InitializeSdBlockIoPeim ( if (EFI_ERROR (Status)) { continue; } + Status = SdPeimHcCardDetect (MmioBase[Index]); if (EFI_ERROR (Status)) { continue; } + Status = SdPeimHcInitHost (MmioBase[Index]); if (EFI_ERROR (Status)) { continue; @@ -621,15 +628,15 @@ InitializeSdBlockIoPeim ( Csd = &Slot->Csd; if (Csd->CsdStructure == 0) { Slot->SectorAddressing = FALSE; - CSize = (Csd->CSizeHigh << 2 | Csd->CSizeLow) + 1; - CSizeMul = (1 << (Csd->CSizeMul + 2)); - ReadBlLen = (1 << (Csd->ReadBlLen)); - Capacity = MultU64x32 (MultU64x32 ((UINT64)CSize, CSizeMul), ReadBlLen); + CSize = (Csd->CSizeHigh << 2 | Csd->CSizeLow) + 1; + CSizeMul = (1 << (Csd->CSizeMul + 2)); + ReadBlLen = (1 << (Csd->ReadBlLen)); + Capacity = MultU64x32 (MultU64x32 ((UINT64)CSize, CSizeMul), ReadBlLen); } else { Slot->SectorAddressing = TRUE; - Csd2 = (SD_CSD2*)(VOID*)Csd; - CSize = (Csd2->CSizeHigh << 16 | Csd2->CSizeLow) + 1; - Capacity = MultU64x32 ((UINT64)CSize, SIZE_512KB); + Csd2 = (SD_CSD2 *)(VOID *)Csd; + CSize = (Csd2->CSizeHigh << 16 | Csd2->CSizeLow) + 1; + Capacity = MultU64x32 ((UINT64)CSize, SIZE_512KB); } Slot->Media.LastBlock = DivU64x32 (Capacity, Slot->Media.BlockSize) - 1; diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.h b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.h index 7fd6dba92e..2261d8c798 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.h +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.h @@ -26,27 +26,27 @@ #include -typedef struct _SD_PEIM_HC_PRIVATE_DATA SD_PEIM_HC_PRIVATE_DATA; -typedef struct _SD_PEIM_HC_SLOT SD_PEIM_HC_SLOT; -typedef struct _SD_TRB SD_TRB; +typedef struct _SD_PEIM_HC_PRIVATE_DATA SD_PEIM_HC_PRIVATE_DATA; +typedef struct _SD_PEIM_HC_SLOT SD_PEIM_HC_SLOT; +typedef struct _SD_TRB SD_TRB; #include "SdHci.h" #include "SdHcMem.h" -#define SD_PEIM_SIG SIGNATURE_32 ('S', 'D', 'C', 'P') -#define SD_PEIM_SLOT_SIG SIGNATURE_32 ('S', 'D', 'C', 'S') +#define SD_PEIM_SIG SIGNATURE_32 ('S', 'D', 'C', 'P') +#define SD_PEIM_SLOT_SIG SIGNATURE_32 ('S', 'D', 'C', 'S') -#define SD_PEIM_MAX_SLOTS 6 +#define SD_PEIM_MAX_SLOTS 6 struct _SD_PEIM_HC_SLOT { - UINT32 Signature; - EFI_PEI_BLOCK_IO2_MEDIA Media; - - UINTN SdHcBase; - SD_HC_SLOT_CAP Capability; - SD_CSD Csd; - BOOLEAN SectorAddressing; - SD_PEIM_HC_PRIVATE_DATA *Private; + UINT32 Signature; + EFI_PEI_BLOCK_IO2_MEDIA Media; + + UINTN SdHcBase; + SD_HC_SLOT_CAP Capability; + SD_CSD Csd; + BOOLEAN SectorAddressing; + SD_PEIM_HC_PRIVATE_DATA *Private; }; struct _SD_PEIM_HC_PRIVATE_DATA { @@ -67,27 +67,27 @@ struct _SD_PEIM_HC_PRIVATE_DATA { UINT8 TotalBlkIoDevices; }; -#define SD_TIMEOUT MultU64x32((UINT64)(3), 1000000) -#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, BlkIoPpi, SD_PEIM_SIG) -#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, SD_PEIM_SIG) -#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, SD_PEIM_SIG) +#define SD_TIMEOUT MultU64x32((UINT64)(3), 1000000) +#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, BlkIoPpi, SD_PEIM_SIG) +#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, SD_PEIM_SIG) +#define GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, SD_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, SD_PEIM_SIG) struct _SD_TRB { - SD_PEIM_HC_SLOT *Slot; - UINT16 BlockSize; + SD_PEIM_HC_SLOT *Slot; + UINT16 BlockSize; - SD_COMMAND_PACKET *Packet; - VOID *Data; - UINT32 DataLen; - BOOLEAN Read; - EFI_PHYSICAL_ADDRESS DataPhy; - VOID *DataMap; - SD_HC_TRANSFER_MODE Mode; + SD_COMMAND_PACKET *Packet; + VOID *Data; + UINT32 DataLen; + BOOLEAN Read; + EFI_PHYSICAL_ADDRESS DataPhy; + VOID *DataMap; + SD_HC_TRANSFER_MODE Mode; - UINT64 Timeout; + UINT64 Timeout; - SD_HC_ADMA_DESC_LINE *AdmaDesc; - UINTN AdmaDescSize; + SD_HC_ADMA_DESC_LINE *AdmaDesc; + UINTN AdmaDescSize; }; /** @@ -234,9 +234,9 @@ SdBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI SdBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -283,10 +283,10 @@ SdBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI SdBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ); /** @@ -326,12 +326,12 @@ SdBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI SdBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -345,7 +345,7 @@ SdBlockIoPeimReadBlocks2 ( **/ EFI_STATUS SdPeimInitMemPool ( - IN SD_PEIM_HC_PRIVATE_DATA *Private + IN SD_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -359,7 +359,7 @@ SdPeimInitMemPool ( **/ EFI_STATUS SdPeimFreeMemPool ( - IN SD_PEIM_MEM_POOL *Pool + IN SD_PEIM_MEM_POOL *Pool ); /** @@ -374,8 +374,8 @@ SdPeimFreeMemPool ( **/ VOID * SdPeimAllocateMem ( - IN SD_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN SD_PEIM_MEM_POOL *Pool, + IN UINTN Size ); /** @@ -388,9 +388,9 @@ SdPeimAllocateMem ( **/ VOID SdPeimFreeMem ( - IN SD_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN SD_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -422,11 +422,11 @@ IoMmuInit ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -440,7 +440,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -483,9 +483,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.c b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.c index fb043c19ff..27aec1fbf3 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.c +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.c @@ -18,25 +18,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ SD_PEIM_MEM_BLOCK * SdPeimAllocMemBlock ( - IN UINTN Pages + IN UINTN Pages ) { - SD_PEIM_MEM_BLOCK *Block; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - EFI_STATUS Status; - VOID *TempPtr; + SD_PEIM_MEM_BLOCK *Block; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Block = NULL; - Status = PeiServicesAllocatePool (sizeof(SD_PEIM_MEM_BLOCK), &TempPtr); + Status = PeiServicesAllocatePool (sizeof (SD_PEIM_MEM_BLOCK), &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof(SD_PEIM_MEM_BLOCK)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (SD_PEIM_MEM_BLOCK)); // // each bit in the bit array represents SD_PEIM_MEM_UNIT @@ -44,18 +44,18 @@ SdPeimAllocMemBlock ( // ASSERT (SD_PEIM_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block = (SD_PEIM_MEM_BLOCK*)(UINTN)TempPtr; - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (SD_PEIM_MEM_UNIT * 8); + Block = (SD_PEIM_MEM_BLOCK *)(UINTN)TempPtr; + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (SD_PEIM_MEM_UNIT * 8); Status = PeiServicesAllocatePool (Block->BitsLen, &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, Block->BitsLen); + ZeroMem ((VOID *)(UINTN)TempPtr, Block->BitsLen); - Block->Bits = (UINT8*)(UINTN)TempPtr; + Block->Bits = (UINT8 *)(UINTN)TempPtr; Status = IoMmuAllocateBuffer ( Pages, @@ -67,10 +67,10 @@ SdPeimAllocMemBlock ( return NULL; } - ZeroMem ((VOID*)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); + ZeroMem ((VOID *)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); - Block->BufHost = (UINT8 *) (UINTN) BufHost; - Block->Buf = (UINT8 *) (UINTN) MappedAddr; + Block->BufHost = (UINT8 *)(UINTN)BufHost; + Block->Buf = (UINT8 *)(UINTN)MappedAddr; Block->Mapping = Mapping; Block->Next = NULL; @@ -86,8 +86,8 @@ SdPeimAllocMemBlock ( **/ VOID SdPeimFreeMemBlock ( - IN SD_PEIM_MEM_POOL *Pool, - IN SD_PEIM_MEM_BLOCK *Block + IN SD_PEIM_MEM_POOL *Pool, + IN SD_PEIM_MEM_BLOCK *Block ) { ASSERT ((Pool != NULL) && (Block != NULL)); @@ -107,22 +107,22 @@ SdPeimFreeMemBlock ( **/ VOID * SdPeimAllocMemFromBlock ( - IN SD_PEIM_MEM_BLOCK *Block, - IN UINTN Units + IN SD_PEIM_MEM_BLOCK *Block, + IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -138,13 +138,12 @@ SdPeimAllocMemFromBlock ( } SD_PEIM_NEXT_BIT (Byte, Bit); - } else { SD_PEIM_NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -155,13 +154,13 @@ SdPeimAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!SD_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) SD_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)SD_PEIM_MEM_BIT (Bit)); SD_PEIM_NEXT_BIT (Byte, Bit); } @@ -177,8 +176,8 @@ SdPeimAllocMemFromBlock ( **/ VOID SdPeimInsertMemBlockToPool ( - IN SD_PEIM_MEM_BLOCK *Head, - IN SD_PEIM_MEM_BLOCK *Block + IN SD_PEIM_MEM_BLOCK *Head, + IN SD_PEIM_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -197,11 +196,10 @@ SdPeimInsertMemBlockToPool ( **/ BOOLEAN SdPeimIsMemBlockEmpty ( - IN SD_PEIM_MEM_BLOCK *Block + IN SD_PEIM_MEM_BLOCK *Block ) { - UINTN Index; - + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -212,8 +210,6 @@ SdPeimIsMemBlockEmpty ( return TRUE; } - - /** Initialize the memory management pool for the host controller. @@ -228,9 +224,9 @@ SdPeimInitMemPool ( IN SD_PEIM_HC_PRIVATE_DATA *Private ) { - SD_PEIM_MEM_POOL *Pool; - EFI_STATUS Status; - VOID *TempPtr; + SD_PEIM_MEM_POOL *Pool; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Pool = NULL; @@ -240,7 +236,7 @@ SdPeimInitMemPool ( return EFI_OUT_OF_RESOURCES; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof (SD_PEIM_MEM_POOL)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (SD_PEIM_MEM_POOL)); Pool = (SD_PEIM_MEM_POOL *)((UINTN)TempPtr); @@ -265,10 +261,10 @@ SdPeimInitMemPool ( **/ EFI_STATUS SdPeimFreeMemPool ( - IN SD_PEIM_MEM_POOL *Pool + IN SD_PEIM_MEM_POOL *Pool ) { - SD_PEIM_MEM_BLOCK *Block; + SD_PEIM_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -296,16 +292,16 @@ SdPeimFreeMemPool ( **/ VOID * SdPeimAllocateMem ( - IN SD_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN SD_PEIM_MEM_POOL *Pool, + IN UINTN Size ) { - SD_PEIM_MEM_BLOCK *Head; - SD_PEIM_MEM_BLOCK *Block; - SD_PEIM_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + SD_PEIM_MEM_BLOCK *Head; + SD_PEIM_MEM_BLOCK *Block; + SD_PEIM_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = SD_PEIM_MEM_ROUND (Size); @@ -368,22 +364,22 @@ SdPeimAllocateMem ( **/ VOID SdPeimFreeMem ( - IN SD_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN SD_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - SD_PEIM_MEM_BLOCK *Head; - SD_PEIM_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + SD_PEIM_MEM_BLOCK *Head; + SD_PEIM_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = SD_PEIM_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -394,8 +390,8 @@ SdPeimFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->Buf) / SD_PEIM_MEM_UNIT) / 8; - Bit = ((ToFree - Block->Buf) / SD_PEIM_MEM_UNIT) % 8; + Byte = ((ToFree - Block->Buf) / SD_PEIM_MEM_UNIT) / 8; + Bit = ((ToFree - Block->Buf) / SD_PEIM_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -403,7 +399,7 @@ SdPeimFreeMem ( for (Count = 0; Count < (AllocSize / SD_PEIM_MEM_UNIT); Count++) { ASSERT (SD_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ SD_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ SD_PEIM_MEM_BIT (Bit)); SD_PEIM_NEXT_BIT (Byte, Bit); } @@ -425,5 +421,5 @@ SdPeimFreeMem ( SdPeimFreeMemBlock (Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.h b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.h index c6bda2d1e0..70620a5f81 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.h +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHcMem.h @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SD_PEIM_MEM_H_ #define _SD_PEIM_MEM_H_ -#define SD_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) +#define SD_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) #define SD_PEIM_MEM_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & SD_PEIM_MEM_BIT(Bit)) == SD_PEIM_MEM_BIT(Bit))) @@ -17,28 +17,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _SD_PEIM_MEM_BLOCK SD_PEIM_MEM_BLOCK; struct _SD_PEIM_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - SD_PEIM_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + SD_PEIM_MEM_BLOCK *Next; }; typedef struct _SD_PEIM_MEM_POOL { - SD_PEIM_MEM_BLOCK *Head; + SD_PEIM_MEM_BLOCK *Head; } SD_PEIM_MEM_POOL; // // Memory allocation unit, note that the value must meet SD spec alignment requirement. // -#define SD_PEIM_MEM_UNIT 128 +#define SD_PEIM_MEM_UNIT 128 #define SD_PEIM_MEM_UNIT_MASK (SD_PEIM_MEM_UNIT - 1) #define SD_PEIM_MEM_DEFAULT_PAGES 16 -#define SD_PEIM_MEM_ROUND(Len) (((Len) + SD_PEIM_MEM_UNIT_MASK) & (~SD_PEIM_MEM_UNIT_MASK)) +#define SD_PEIM_MEM_ROUND(Len) (((Len) + SD_PEIM_MEM_UNIT_MASK) & (~SD_PEIM_MEM_UNIT_MASK)) // // Advance the byte and bit to the next bit, adjust byte accordingly. @@ -53,4 +53,3 @@ typedef struct _SD_PEIM_MEM_POOL { } while (0) #endif - diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.c b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.c index 7c8b548b9e..774cae35f2 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.c +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.c @@ -28,13 +28,13 @@ EFI_STATUS EFIAPI SdPeimHcRwMmio ( - IN UINTN Address, - IN BOOLEAN Read, - IN UINT8 Count, - IN OUT VOID *Data + IN UINTN Address, + IN BOOLEAN Read, + IN UINT8 Count, + IN OUT VOID *Data ) { - if ((Address == 0) || (Data == NULL)) { + if ((Address == 0) || (Data == NULL)) { return EFI_INVALID_PARAMETER; } @@ -45,31 +45,35 @@ SdPeimHcRwMmio ( switch (Count) { case 1: if (Read) { - *(UINT8*)Data = MmioRead8 (Address); + *(UINT8 *)Data = MmioRead8 (Address); } else { - MmioWrite8 (Address, *(UINT8*)Data); + MmioWrite8 (Address, *(UINT8 *)Data); } + break; case 2: if (Read) { - *(UINT16*)Data = MmioRead16 (Address); + *(UINT16 *)Data = MmioRead16 (Address); } else { - MmioWrite16 (Address, *(UINT16*)Data); + MmioWrite16 (Address, *(UINT16 *)Data); } + break; case 4: if (Read) { - *(UINT32*)Data = MmioRead32 (Address); + *(UINT32 *)Data = MmioRead32 (Address); } else { - MmioWrite32 (Address, *(UINT32*)Data); + MmioWrite32 (Address, *(UINT32 *)Data); } + break; case 8: if (Read) { - *(UINT64*)Data = MmioRead64 (Address); + *(UINT64 *)Data = MmioRead64 (Address); } else { - MmioWrite64 (Address, *(UINT64*)Data); + MmioWrite64 (Address, *(UINT64 *)Data); } + break; default: ASSERT (FALSE); @@ -98,14 +102,14 @@ SdPeimHcRwMmio ( EFI_STATUS EFIAPI SdPeimHcOrMmio ( - IN UINTN Address, - IN UINT8 Count, - IN VOID *OrData + IN UINTN Address, + IN UINT8 Count, + IN VOID *OrData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 Or; + EFI_STATUS Status; + UINT64 Data; + UINT64 Or; Status = SdPeimHcRwMmio (Address, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -113,13 +117,13 @@ SdPeimHcOrMmio ( } if (Count == 1) { - Or = *(UINT8*) OrData; + Or = *(UINT8 *)OrData; } else if (Count == 2) { - Or = *(UINT16*) OrData; + Or = *(UINT16 *)OrData; } else if (Count == 4) { - Or = *(UINT32*) OrData; + Or = *(UINT32 *)OrData; } else if (Count == 8) { - Or = *(UINT64*) OrData; + Or = *(UINT64 *)OrData; } else { return EFI_INVALID_PARAMETER; } @@ -149,14 +153,14 @@ SdPeimHcOrMmio ( EFI_STATUS EFIAPI SdPeimHcAndMmio ( - IN UINTN Address, - IN UINT8 Count, - IN VOID *AndData + IN UINTN Address, + IN UINT8 Count, + IN VOID *AndData ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 And; + EFI_STATUS Status; + UINT64 Data; + UINT64 And; Status = SdPeimHcRwMmio (Address, TRUE, Count, &Data); if (EFI_ERROR (Status)) { @@ -164,13 +168,13 @@ SdPeimHcAndMmio ( } if (Count == 1) { - And = *(UINT8*) AndData; + And = *(UINT8 *)AndData; } else if (Count == 2) { - And = *(UINT16*) AndData; + And = *(UINT16 *)AndData; } else if (Count == 4) { - And = *(UINT32*) AndData; + And = *(UINT32 *)AndData; } else if (Count == 8) { - And = *(UINT64*) AndData; + And = *(UINT64 *)AndData; } else { return EFI_INVALID_PARAMETER; } @@ -198,14 +202,14 @@ SdPeimHcAndMmio ( EFI_STATUS EFIAPI SdPeimHcCheckMmioSet ( - IN UINTN Address, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue + IN UINTN Address, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue ) { - EFI_STATUS Status; - UINT64 Value; + EFI_STATUS Status; + UINT64 Value; // // Access PCI MMIO space to see if the value is the tested one. @@ -245,15 +249,15 @@ SdPeimHcCheckMmioSet ( EFI_STATUS EFIAPI SdPeimHcWaitMmioSet ( - IN UINTN Address, - IN UINT8 Count, - IN UINT64 MaskValue, - IN UINT64 TestValue, - IN UINT64 Timeout + IN UINTN Address, + IN UINT8 Count, + IN UINT64 MaskValue, + IN UINT64 TestValue, + IN UINT64 Timeout ) { - EFI_STATUS Status; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -294,11 +298,11 @@ SdPeimHcWaitMmioSet ( **/ EFI_STATUS SdPeimHcReset ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT8 SwReset; + EFI_STATUS Status; + UINT8 SwReset; SwReset = 0xFF; Status = SdPeimHcRwMmio (Bar + SD_HC_SW_RST, FALSE, sizeof (SwReset), &SwReset); @@ -319,6 +323,7 @@ SdPeimHcReset ( DEBUG ((DEBUG_INFO, "SdPeimHcReset: reset done with %r\n", Status)); return Status; } + // // Enable all interrupt after reset all. // @@ -339,25 +344,26 @@ SdPeimHcReset ( **/ EFI_STATUS SdPeimHcEnableInterrupt ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT16 IntStatus; + EFI_STATUS Status; + UINT16 IntStatus; // // Enable all bits in Error Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = SdPeimHcRwMmio (Bar + SD_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = SdPeimHcRwMmio (Bar + SD_HC_ERR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); if (EFI_ERROR (Status)) { return Status; } + // // Enable all bits in Normal Interrupt Status Enable Register // IntStatus = 0xFFFF; - Status = SdPeimHcRwMmio (Bar + SD_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); + Status = SdPeimHcRwMmio (Bar + SD_HC_NOR_INT_STS_EN, FALSE, sizeof (IntStatus), &IntStatus); return Status; } @@ -374,12 +380,12 @@ SdPeimHcEnableInterrupt ( **/ EFI_STATUS SdPeimHcGetCapability ( - IN UINTN Bar, - OUT SD_HC_SLOT_CAP *Capability + IN UINTN Bar, + OUT SD_HC_SLOT_CAP *Capability ) { - EFI_STATUS Status; - UINT64 Cap; + EFI_STATUS Status; + UINT64 Cap; Status = SdPeimHcRwMmio (Bar + SD_HC_CAP, TRUE, sizeof (Cap), &Cap); if (EFI_ERROR (Status)) { @@ -406,12 +412,12 @@ SdPeimHcGetCapability ( **/ EFI_STATUS SdPeimHcCardDetect ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT16 Data; - UINT32 PresentState; + EFI_STATUS Status; + UINT16 Data; + UINT32 PresentState; // // Check Normal Interrupt Status Register @@ -460,12 +466,12 @@ SdPeimHcCardDetect ( **/ EFI_STATUS SdPeimHcStopClock ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT32 PresentState; - UINT16 ClockCtrl; + EFI_STATUS Status; + UINT32 PresentState; + UINT16 ClockCtrl; // // Ensure no SD transactions are occurring on the SD Bus by @@ -486,8 +492,8 @@ SdPeimHcStopClock ( // // Set SD Clock Enable in the Clock Control register to 0 // - ClockCtrl = (UINT16)~BIT2; - Status = SdPeimHcAndMmio (Bar + SD_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + ClockCtrl = (UINT16) ~BIT2; + Status = SdPeimHcAndMmio (Bar + SD_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); return Status; } @@ -506,18 +512,18 @@ SdPeimHcStopClock ( **/ EFI_STATUS SdPeimHcClockSupply ( - IN UINTN Bar, - IN UINT64 ClockFreq + IN UINTN Bar, + IN UINT64 ClockFreq ) { - EFI_STATUS Status; - SD_HC_SLOT_CAP Capability; - UINT32 BaseClkFreq; - UINT32 SettingFreq; - UINT32 Divisor; - UINT32 Remainder; - UINT16 ControllerVer; - UINT16 ClockCtrl; + EFI_STATUS Status; + SD_HC_SLOT_CAP Capability; + UINT32 BaseClkFreq; + UINT32 SettingFreq; + UINT32 Divisor; + UINT32 Remainder; + UINT16 ControllerVer; + UINT16 ClockCtrl; // // Calculate a divisor for SD clock frequency @@ -526,6 +532,7 @@ SdPeimHcClockSupply ( if (EFI_ERROR (Status)) { return Status; } + ASSERT (Capability.BaseClkFreq != 0); BaseClkFreq = Capability.BaseClkFreq; @@ -551,8 +558,9 @@ SdPeimHcClockSupply ( if ((ClockFreq == SettingFreq) && (Remainder == 0)) { break; } + if ((ClockFreq == SettingFreq) && (Remainder != 0)) { - SettingFreq ++; + SettingFreq++; } } @@ -562,6 +570,7 @@ SdPeimHcClockSupply ( if (EFI_ERROR (Status)) { return Status; } + // // Set SDCLK Frequency Select and Internal Clock Enable fields in Clock Control register. // @@ -575,6 +584,7 @@ SdPeimHcClockSupply ( if (((Divisor - 1) & Divisor) != 0) { Divisor = 1 << (HighBitSet32 (Divisor) + 1); } + ASSERT (Divisor <= 0x80); ClockCtrl = (Divisor & 0xFF) << 8; } else { @@ -594,7 +604,7 @@ SdPeimHcClockSupply ( // Supply clock frequency with specified divisor // ClockCtrl |= BIT0; - Status = SdPeimHcRwMmio (Bar + SD_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); + Status = SdPeimHcRwMmio (Bar + SD_HC_CLOCK_CTRL, FALSE, sizeof (ClockCtrl), &ClockCtrl); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Set SDCLK Frequency Select and Internal Clock Enable fields fails\n")); return Status; @@ -618,7 +628,7 @@ SdPeimHcClockSupply ( // Set SD Clock Enable in the Clock Control register to 1 // ClockCtrl = BIT2; - Status = SdPeimHcOrMmio (Bar + SD_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + Status = SdPeimHcOrMmio (Bar + SD_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); return Status; } @@ -637,17 +647,17 @@ SdPeimHcClockSupply ( **/ EFI_STATUS SdPeimHcPowerControl ( - IN UINTN Bar, - IN UINT8 PowerCtrl + IN UINTN Bar, + IN UINT8 PowerCtrl ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Clr SD Bus Power // - PowerCtrl &= (UINT8)~BIT0; - Status = SdPeimHcRwMmio (Bar + SD_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + PowerCtrl &= (UINT8) ~BIT0; + Status = SdPeimHcRwMmio (Bar + SD_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); if (EFI_ERROR (Status)) { return Status; } @@ -656,7 +666,7 @@ SdPeimHcPowerControl ( // Set SD Bus Voltage Select and SD Bus Power fields in Power Control Register // PowerCtrl |= BIT0; - Status = SdPeimHcRwMmio (Bar + SD_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); + Status = SdPeimHcRwMmio (Bar + SD_HC_POWER_CTRL, FALSE, sizeof (PowerCtrl), &PowerCtrl); return Status; } @@ -675,32 +685,34 @@ SdPeimHcPowerControl ( **/ EFI_STATUS SdPeimHcSetBusWidth ( - IN UINTN Bar, - IN UINT16 BusWidth + IN UINTN Bar, + IN UINT16 BusWidth ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (BusWidth == 1) { - HostCtrl1 = (UINT8)~(BIT5 | BIT1); - Status = SdPeimHcAndMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 = (UINT8) ~(BIT5 | BIT1); + Status = SdPeimHcAndMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 4) { Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } + HostCtrl1 |= BIT1; - HostCtrl1 &= (UINT8)~BIT5; - Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + HostCtrl1 &= (UINT8) ~BIT5; + Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else if (BusWidth == 8) { Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, TRUE, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } - HostCtrl1 &= (UINT8)~BIT1; + + HostCtrl1 &= (UINT8) ~BIT1; HostCtrl1 |= BIT5; - Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); + Status = SdPeimHcRwMmio (Bar + SD_HC_HOST_CTRL1, FALSE, sizeof (HostCtrl1), &HostCtrl1); } else { ASSERT (FALSE); return EFI_INVALID_PARAMETER; @@ -720,12 +732,12 @@ SdPeimHcSetBusWidth ( **/ EFI_STATUS SdPeimHcInitClockFreq ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - SD_HC_SLOT_CAP Capability; - UINT32 InitFreq; + EFI_STATUS Status; + SD_HC_SLOT_CAP Capability; + UINT32 InitFreq; // // Calculate a divisor for SD clock frequency @@ -741,11 +753,12 @@ SdPeimHcInitClockFreq ( // return EFI_UNSUPPORTED; } + // // Supply 400KHz clock frequency at initialization phase. // InitFreq = 400; - Status = SdPeimHcClockSupply (Bar, InitFreq); + Status = SdPeimHcClockSupply (Bar, InitFreq); return Status; } @@ -762,13 +775,13 @@ SdPeimHcInitClockFreq ( **/ EFI_STATUS SdPeimHcInitPowerVoltage ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - SD_HC_SLOT_CAP Capability; - UINT8 MaxVoltage; - UINT8 HostCtrl2; + EFI_STATUS Status; + SD_HC_SLOT_CAP Capability; + UINT8 MaxVoltage; + UINT8 HostCtrl2; // // Get the support voltage of the Host Controller @@ -777,6 +790,7 @@ SdPeimHcInitPowerVoltage ( if (EFI_ERROR (Status)) { return Status; } + // // Calculate supported maximum voltage according to SD Bus Voltage Select // @@ -796,10 +810,11 @@ SdPeimHcInitPowerVoltage ( // MaxVoltage = 0x0A; HostCtrl2 = BIT3; - Status = SdPeimHcOrMmio (Bar + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdPeimHcOrMmio (Bar + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + MicroSecondDelay (5000); } else { ASSERT (FALSE); @@ -827,11 +842,11 @@ SdPeimHcInitPowerVoltage ( **/ EFI_STATUS SdPeimHcInitTimeoutCtrl ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; - UINT8 Timeout; + EFI_STATUS Status; + UINT8 Timeout; Timeout = 0x0E; Status = SdPeimHcRwMmio (Bar + SD_HC_TIMEOUT_CTRL, FALSE, sizeof (Timeout), &Timeout); @@ -851,10 +866,10 @@ SdPeimHcInitTimeoutCtrl ( **/ EFI_STATUS SdPeimHcInitHost ( - IN UINTN Bar + IN UINTN Bar ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = SdPeimHcInitClockFreq (Bar); if (EFI_ERROR (Status)) { @@ -882,18 +897,18 @@ SdPeimHcInitHost ( **/ EFI_STATUS SdPeimHcLedOnOff ( - IN UINTN Bar, - IN BOOLEAN On + IN UINTN Bar, + IN BOOLEAN On ) { - EFI_STATUS Status; - UINT8 HostCtrl1; + EFI_STATUS Status; + UINT8 HostCtrl1; if (On) { HostCtrl1 = BIT0; Status = SdPeimHcOrMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } else { - HostCtrl1 = (UINT8)~BIT0; + HostCtrl1 = (UINT8) ~BIT0; Status = SdPeimHcAndMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); } @@ -913,15 +928,15 @@ SdPeimHcLedOnOff ( **/ EFI_STATUS BuildAdmaDescTable ( - IN SD_TRB *Trb + IN SD_TRB *Trb ) { - EFI_PHYSICAL_ADDRESS Data; - UINT64 DataLen; - UINT64 Entries; - UINT32 Index; - UINT64 Remaining; - UINT32 Address; + EFI_PHYSICAL_ADDRESS Data; + UINT64 DataLen; + UINT64 Entries; + UINT32 Index; + UINT64 Remaining; + UINT32 Address; Data = Trb->DataPhy; DataLen = Trb->DataLen; @@ -931,6 +946,7 @@ BuildAdmaDescTable ( if ((Data >= 0x100000000ul) || ((Data + DataLen) > 0x100000000ul)) { return EFI_INVALID_PARAMETER; } + // // Address field shall be set on 32-bit boundary (Lower 2-bit is always set to 0) // for 32-bit address descriptor table. @@ -951,14 +967,14 @@ BuildAdmaDescTable ( Address = (UINT32)Data; for (Index = 0; Index < Entries; Index++) { if (Remaining <= ADMA_MAX_DATA_PER_LINE) { - Trb->AdmaDesc[Index].Valid = 1; - Trb->AdmaDesc[Index].Act = 2; + Trb->AdmaDesc[Index].Valid = 1; + Trb->AdmaDesc[Index].Act = 2; Trb->AdmaDesc[Index].Length = (UINT16)Remaining; Trb->AdmaDesc[Index].Address = Address; break; } else { - Trb->AdmaDesc[Index].Valid = 1; - Trb->AdmaDesc[Index].Act = 2; + Trb->AdmaDesc[Index].Valid = 1; + Trb->AdmaDesc[Index].Act = 2; Trb->AdmaDesc[Index].Length = 0; Trb->AdmaDesc[Index].Address = Address; } @@ -985,15 +1001,15 @@ BuildAdmaDescTable ( **/ SD_TRB * SdPeimCreateTrb ( - IN SD_PEIM_HC_SLOT *Slot, - IN SD_COMMAND_PACKET *Packet + IN SD_PEIM_HC_SLOT *Slot, + IN SD_COMMAND_PACKET *Packet ) { - SD_TRB *Trb; - EFI_STATUS Status; - SD_HC_SLOT_CAP Capability; - EDKII_IOMMU_OPERATION MapOp; - UINTN MapLength; + SD_TRB *Trb; + EFI_STATUS Status; + SD_HC_SLOT_CAP Capability; + EDKII_IOMMU_OPERATION MapOp; + UINTN MapLength; // // Calculate a divisor for SD clock frequency @@ -1043,7 +1059,7 @@ SdPeimCreateTrb ( if (Trb->DataLen != 0) { MapLength = Trb->DataLen; - Status = IoMmuMap (MapOp, Trb->Data, &MapLength, &Trb->DataPhy, &Trb->DataMap); + Status = IoMmuMap (MapOp, Trb->Data, &MapLength, &Trb->DataPhy, &Trb->DataMap); if (EFI_ERROR (Status) || (MapLength != Trb->DataLen)) { DEBUG ((DEBUG_ERROR, "SdPeimCreateTrb: Fail to map data buffer.\n")); @@ -1055,7 +1071,7 @@ SdPeimCreateTrb ( Trb->Mode = SdNoData; } else if (Capability.Adma2 != 0) { Trb->Mode = SdAdmaMode; - Status = BuildAdmaDescTable (Trb); + Status = BuildAdmaDescTable (Trb); if (EFI_ERROR (Status)) { goto Error; } @@ -1065,6 +1081,7 @@ SdPeimCreateTrb ( Trb->Mode = SdPioMode; } } + return Trb; Error: @@ -1080,7 +1097,7 @@ Error: **/ VOID SdPeimFreeTrb ( - IN SD_TRB *Trb + IN SD_TRB *Trb ) { if ((Trb != NULL) && (Trb->DataMap != NULL)) { @@ -1094,6 +1111,7 @@ SdPeimFreeTrb ( if (Trb != NULL) { FreePool (Trb); } + return; } @@ -1110,19 +1128,20 @@ SdPeimFreeTrb ( **/ EFI_STATUS SdPeimCheckTrbEnv ( - IN UINTN Bar, - IN SD_TRB *Trb + IN UINTN Bar, + IN SD_TRB *Trb ) { - EFI_STATUS Status; - SD_COMMAND_PACKET *Packet; - UINT32 PresentState; + EFI_STATUS Status; + SD_COMMAND_PACKET *Packet; + UINT32 PresentState; Packet = Trb->Packet; if ((Packet->SdCmdBlk->CommandType == SdCommandTypeAdtc) || (Packet->SdCmdBlk->ResponseType == SdResponseTypeR1b) || - (Packet->SdCmdBlk->ResponseType == SdResponseTypeR5b)) { + (Packet->SdCmdBlk->ResponseType == SdResponseTypeR5b)) + { // // Wait Command Inhibit (CMD) and Command Inhibit (DAT) in // the Present State register to be 0 @@ -1159,14 +1178,14 @@ SdPeimCheckTrbEnv ( **/ EFI_STATUS SdPeimWaitTrbEnv ( - IN UINTN Bar, - IN SD_TRB *Trb + IN UINTN Bar, + IN SD_TRB *Trb ) { - EFI_STATUS Status; - SD_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + SD_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; // // Wait Command Complete Interrupt Status bit in Normal Interrupt Status Register @@ -1187,6 +1206,7 @@ SdPeimWaitTrbEnv ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -1210,21 +1230,21 @@ SdPeimWaitTrbEnv ( **/ EFI_STATUS SdPeimExecTrb ( - IN UINTN Bar, - IN SD_TRB *Trb + IN UINTN Bar, + IN SD_TRB *Trb ) { - EFI_STATUS Status; - SD_COMMAND_PACKET *Packet; - UINT16 Cmd; - UINT16 IntStatus; - UINT32 Argument; - UINT16 BlkCount; - UINT16 BlkSize; - UINT16 TransMode; - UINT8 HostCtrl1; - UINT32 SdmaAddr; - UINT64 AdmaAddr; + EFI_STATUS Status; + SD_COMMAND_PACKET *Packet; + UINT16 Cmd; + UINT16 IntStatus; + UINT32 Argument; + UINT16 BlkCount; + UINT16 BlkSize; + UINT16 TransMode; + UINT8 HostCtrl1; + UINT32 SdmaAddr; + UINT64 AdmaAddr; Packet = Trb->Packet; // @@ -1235,6 +1255,7 @@ SdPeimExecTrb ( if (EFI_ERROR (Status)) { return Status; } + // // Clear all bits in Normal Interrupt Status Register // @@ -1243,12 +1264,13 @@ SdPeimExecTrb ( if (EFI_ERROR (Status)) { return Status; } + // // Set Host Control 1 register DMA Select field // if (Trb->Mode == SdAdmaMode) { HostCtrl1 = BIT4; - Status = SdPeimHcOrMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdPeimHcOrMmio (Bar + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } @@ -1294,7 +1316,8 @@ SdPeimExecTrb ( // BlkCount = (UINT16)(Trb->DataLen / Trb->BlockSize); } - Status = SdPeimHcRwMmio (Bar + SD_HC_BLK_COUNT, FALSE, sizeof (BlkCount), &BlkCount); + + Status = SdPeimHcRwMmio (Bar + SD_HC_BLK_COUNT, FALSE, sizeof (BlkCount), &BlkCount); if (EFI_ERROR (Status)) { return Status; } @@ -1310,12 +1333,15 @@ SdPeimExecTrb ( if (Trb->Mode != SdPioMode) { TransMode |= BIT0; } + if (Trb->Read) { TransMode |= BIT4; } + if (BlkCount > 1) { TransMode |= BIT5 | BIT1; } + // // SD memory card needs to use AUTO CMD12 feature. // @@ -1329,10 +1355,11 @@ SdPeimExecTrb ( return Status; } - Cmd = (UINT16)LShiftU64(Packet->SdCmdBlk->CommandIndex, 8); + Cmd = (UINT16)LShiftU64 (Packet->SdCmdBlk->CommandIndex, 8); if (Packet->SdCmdBlk->CommandType == SdCommandTypeAdtc) { Cmd |= BIT5; } + // // Convert ResponseType to value // @@ -1346,7 +1373,7 @@ SdPeimExecTrb ( break; case SdResponseTypeR2: Cmd |= (BIT0 | BIT3); - break; + break; case SdResponseTypeR3: case SdResponseTypeR4: Cmd |= BIT1; @@ -1360,6 +1387,7 @@ SdPeimExecTrb ( break; } } + // // Execute cmd // @@ -1380,18 +1408,18 @@ SdPeimExecTrb ( **/ EFI_STATUS SdPeimCheckTrbResult ( - IN UINTN Bar, - IN SD_TRB *Trb + IN UINTN Bar, + IN SD_TRB *Trb ) { - EFI_STATUS Status; - SD_COMMAND_PACKET *Packet; - UINT16 IntStatus; - UINT32 Response[4]; - UINT32 SdmaAddr; - UINT8 Index; - UINT8 SwReset; - UINT32 PioLength; + EFI_STATUS Status; + SD_COMMAND_PACKET *Packet; + UINT16 IntStatus; + UINT32 Response[4]; + UINT32 SdmaAddr; + UINT8 Index; + UINT8 SwReset; + UINT32 PioLength; SwReset = 0; Packet = Trb->Packet; @@ -1407,6 +1435,7 @@ SdPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + // // Check Transfer Complete bit is set or not. // @@ -1435,6 +1464,7 @@ SdPeimCheckTrbResult ( goto Done; } + // // Check if there is a error happened during cmd execution. // If yes, then do error recovery procedure to follow SD Host Controller @@ -1454,6 +1484,7 @@ SdPeimCheckTrbResult ( if ((IntStatus & 0x0F) != 0) { SwReset |= BIT1; } + if ((IntStatus & 0xF0) != 0) { SwReset |= BIT2; } @@ -1467,6 +1498,7 @@ SdPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + Status = SdPeimHcWaitMmioSet ( Bar + SD_HC_SW_RST, sizeof (SwReset), @@ -1481,6 +1513,7 @@ SdPeimCheckTrbResult ( Status = EFI_DEVICE_ERROR; goto Done; } + // // Check if DMA interrupt is signalled for the SDMA transfer. // @@ -1498,6 +1531,7 @@ SdPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + // // Update SDMA Address register. // @@ -1511,12 +1545,14 @@ SdPeimCheckTrbResult ( if (EFI_ERROR (Status)) { goto Done; } + Trb->DataPhy = (UINT32)(UINTN)SdmaAddr; } if ((Packet->SdCmdBlk->CommandType != SdCommandTypeAdtc) && (Packet->SdCmdBlk->ResponseType != SdResponseTypeR1b) && - (Packet->SdCmdBlk->ResponseType != SdResponseTypeR5b)) { + (Packet->SdCmdBlk->ResponseType != SdResponseTypeR5b)) + { if ((IntStatus & BIT0) == BIT0) { Status = EFI_SUCCESS; goto Done; @@ -1539,8 +1575,9 @@ SdPeimCheckTrbResult ( // Read data out from Buffer Port register // for (PioLength = 0; PioLength < Trb->DataLen; PioLength += 4) { - SdPeimHcRwMmio (Bar + SD_HC_BUF_DAT_PORT, TRUE, 4, (UINT8*)Trb->Data + PioLength); + SdPeimHcRwMmio (Bar + SD_HC_BUF_DAT_PORT, TRUE, 4, (UINT8 *)Trb->Data + PioLength); } + Status = EFI_SUCCESS; goto Done; } @@ -1565,6 +1602,7 @@ Done: return Status; } } + CopyMem (Packet->SdStatusBlk, Response, sizeof (Response)); } } @@ -1588,14 +1626,14 @@ Done: **/ EFI_STATUS SdPeimWaitTrbResult ( - IN UINTN Bar, - IN SD_TRB *Trb + IN UINTN Bar, + IN SD_TRB *Trb ) { - EFI_STATUS Status; - SD_COMMAND_PACKET *Packet; - UINT64 Timeout; - BOOLEAN InfiniteWait; + EFI_STATUS Status; + SD_COMMAND_PACKET *Packet; + UINT64 Timeout; + BOOLEAN InfiniteWait; Packet = Trb->Packet; // @@ -1616,6 +1654,7 @@ SdPeimWaitTrbResult ( if (Status != EFI_NOT_READY) { return Status; } + // // Stall for 1 microsecond. // @@ -1660,12 +1699,12 @@ SdPeimWaitTrbResult ( EFI_STATUS EFIAPI SdPeimExecCmd ( - IN SD_PEIM_HC_SLOT *Slot, - IN OUT SD_COMMAND_PACKET *Packet + IN SD_PEIM_HC_SLOT *Slot, + IN OUT SD_COMMAND_PACKET *Packet ) { - EFI_STATUS Status; - SD_TRB *Trb; + EFI_STATUS Status; + SD_TRB *Trb; if (Packet == NULL) { return EFI_INVALID_PARAMETER; @@ -1722,13 +1761,13 @@ Done: **/ EFI_STATUS SdPeimReset ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1738,9 +1777,9 @@ SdPeimReset ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_GO_IDLE_STATE; - SdCmdBlk.CommandType = SdCommandTypeBc; - SdCmdBlk.ResponseType = 0; + SdCmdBlk.CommandIndex = SD_GO_IDLE_STATE; + SdCmdBlk.CommandType = SdCommandTypeBc; + SdCmdBlk.ResponseType = 0; SdCmdBlk.CommandArgument = 0; Status = SdPeimExecCmd (Slot, &Packet); @@ -1764,15 +1803,15 @@ SdPeimReset ( **/ EFI_STATUS SdPeimVoltageCheck ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT8 SupplyVoltage, - IN UINT8 CheckPattern + IN SD_PEIM_HC_SLOT *Slot, + IN UINT8 SupplyVoltage, + IN UINT8 CheckPattern ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1782,9 +1821,9 @@ SdPeimVoltageCheck ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_SEND_IF_COND; - SdCmdBlk.CommandType = SdCommandTypeBcr; - SdCmdBlk.ResponseType = SdResponseTypeR7; + SdCmdBlk.CommandIndex = SD_SEND_IF_COND; + SdCmdBlk.CommandType = SdCommandTypeBcr; + SdCmdBlk.ResponseType = SdResponseTypeR7; SdCmdBlk.CommandArgument = (SupplyVoltage << 8) | CheckPattern; Status = SdPeimExecCmd (Slot, &Packet); @@ -1812,16 +1851,16 @@ SdPeimVoltageCheck ( **/ EFI_STATUS SdioSendOpCond ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT32 VoltageWindow, - IN BOOLEAN S18r + IN SD_PEIM_HC_SLOT *Slot, + IN UINT32 VoltageWindow, + IN BOOLEAN S18r ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 Switch; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 Switch; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1864,22 +1903,22 @@ SdioSendOpCond ( **/ EFI_STATUS SdPeimSendOpCond ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - IN UINT32 VoltageWindow, - IN BOOLEAN S18r, - IN BOOLEAN Xpc, - IN BOOLEAN Hcs, - OUT UINT32 *Ocr + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + IN UINT32 VoltageWindow, + IN BOOLEAN S18r, + IN BOOLEAN Xpc, + IN BOOLEAN Hcs, + OUT UINT32 *Ocr ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 Switch; - UINT32 MaxPower; - UINT32 HostCapacity; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 Switch; + UINT32 MaxPower; + UINT32 HostCapacity; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1889,9 +1928,9 @@ SdPeimSendOpCond ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_APP_CMD; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR1; + SdCmdBlk.CommandIndex = SD_APP_CMD; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR1; SdCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdPeimExecCmd (Slot, &Packet); @@ -1903,9 +1942,9 @@ SdPeimSendOpCond ( SdCmdBlk.CommandType = SdCommandTypeBcr; SdCmdBlk.ResponseType = SdResponseTypeR3; - Switch = S18r ? BIT24 : 0; - MaxPower = Xpc ? BIT28 : 0; - HostCapacity = Hcs ? BIT30 : 0; + Switch = S18r ? BIT24 : 0; + MaxPower = Xpc ? BIT28 : 0; + HostCapacity = Hcs ? BIT30 : 0; SdCmdBlk.CommandArgument = (VoltageWindow & 0xFFFFFF) | Switch | MaxPower | HostCapacity; Status = SdPeimExecCmd (Slot, &Packet); @@ -1933,13 +1972,13 @@ SdPeimSendOpCond ( **/ EFI_STATUS SdPeimAllSendCid ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1947,11 +1986,11 @@ SdPeimAllSendCid ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_ALL_SEND_CID; - SdCmdBlk.CommandType = SdCommandTypeBcr; - SdCmdBlk.ResponseType = SdResponseTypeR2; + SdCmdBlk.CommandIndex = SD_ALL_SEND_CID; + SdCmdBlk.CommandType = SdCommandTypeBcr; + SdCmdBlk.ResponseType = SdResponseTypeR2; SdCmdBlk.CommandArgument = 0; Status = SdPeimExecCmd (Slot, &Packet); @@ -1974,14 +2013,14 @@ SdPeimAllSendCid ( **/ EFI_STATUS SdPeimSetRca ( - IN SD_PEIM_HC_SLOT *Slot, - OUT UINT16 *Rca + IN SD_PEIM_HC_SLOT *Slot, + OUT UINT16 *Rca ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -1989,7 +2028,7 @@ SdPeimSetRca ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; SdCmdBlk.CommandIndex = SD_SET_RELATIVE_ADDR; SdCmdBlk.CommandType = SdCommandTypeBcr; @@ -2021,15 +2060,15 @@ SdPeimSetRca ( **/ EFI_STATUS SdPeimGetCsd ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - OUT SD_CSD *Csd + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + OUT SD_CSD *Csd ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2037,11 +2076,11 @@ SdPeimGetCsd ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_SEND_CSD; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR2; + SdCmdBlk.CommandIndex = SD_SEND_CSD; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR2; SdCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdPeimExecCmd (Slot, &Packet); @@ -2049,7 +2088,7 @@ SdPeimGetCsd ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Csd) + 1, &SdStatusBlk.Resp0, sizeof (SD_CSD) - 1); + CopyMem (((UINT8 *)Csd) + 1, &SdStatusBlk.Resp0, sizeof (SD_CSD) - 1); } return Status; @@ -2069,14 +2108,14 @@ SdPeimGetCsd ( **/ EFI_STATUS SdPeimSelect ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2084,11 +2123,11 @@ SdPeimSelect ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_SELECT_DESELECT_CARD; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR1b; + SdCmdBlk.CommandIndex = SD_SELECT_DESELECT_CARD; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR1b; SdCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdPeimExecCmd (Slot, &Packet); @@ -2109,13 +2148,13 @@ SdPeimSelect ( **/ EFI_STATUS SdPeimVoltageSwitch ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2123,11 +2162,11 @@ SdPeimVoltageSwitch ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_VOLTAGE_SWITCH; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR1; + SdCmdBlk.CommandIndex = SD_VOLTAGE_SWITCH; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR1; SdCmdBlk.CommandArgument = 0; Status = SdPeimExecCmd (Slot, &Packet); @@ -2150,16 +2189,16 @@ SdPeimVoltageSwitch ( **/ EFI_STATUS SdPeimSetBusWidth ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - IN UINT8 BusWidth + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + IN UINT8 BusWidth ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 Value; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 Value; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2169,9 +2208,9 @@ SdPeimSetBusWidth ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_APP_CMD; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR1; + SdCmdBlk.CommandIndex = SD_APP_CMD; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR1; SdCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdPeimExecCmd (Slot, &Packet); @@ -2190,6 +2229,7 @@ SdPeimSetBusWidth ( } else { return EFI_INVALID_PARAMETER; } + SdCmdBlk.CommandArgument = Value & 0x3; Status = SdPeimExecCmd (Slot, &Packet); @@ -2216,20 +2256,20 @@ SdPeimSetBusWidth ( **/ EFI_STATUS SdPeimSwitch ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT8 AccessMode, - IN UINT8 CommandSystem, - IN UINT8 DriveStrength, - IN UINT8 PowerLimit, - IN BOOLEAN Mode, - OUT UINT8 *SwitchResp + IN SD_PEIM_HC_SLOT *Slot, + IN UINT8 AccessMode, + IN UINT8 CommandSystem, + IN UINT8 DriveStrength, + IN UINT8 PowerLimit, + IN BOOLEAN Mode, + OUT UINT8 *SwitchResp ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT32 ModeValue; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT32 ModeValue; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2237,13 +2277,13 @@ SdPeimSwitch ( Packet.SdCmdBlk = &SdCmdBlk; Packet.SdStatusBlk = &SdStatusBlk; - Packet.Timeout = SD_TIMEOUT; + Packet.Timeout = SD_TIMEOUT; SdCmdBlk.CommandIndex = SD_SWITCH_FUNC; SdCmdBlk.CommandType = SdCommandTypeAdtc; SdCmdBlk.ResponseType = SdResponseTypeR1; - ModeValue = Mode ? BIT31 : 0; + ModeValue = Mode ? BIT31 : 0; SdCmdBlk.CommandArgument = (AccessMode & 0xF) | ((PowerLimit & 0xF) << 4) | \ ((DriveStrength & 0xF) << 8) | ((DriveStrength & 0xF) << 12) | \ ModeValue; @@ -2270,15 +2310,15 @@ SdPeimSwitch ( **/ EFI_STATUS SdPeimSendStatus ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - OUT UINT32 *DevStatus + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + OUT UINT32 *DevStatus ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2288,9 +2328,9 @@ SdPeimSendStatus ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_SEND_STATUS; - SdCmdBlk.CommandType = SdCommandTypeAc; - SdCmdBlk.ResponseType = SdResponseTypeR1; + SdCmdBlk.CommandIndex = SD_SEND_STATUS; + SdCmdBlk.CommandType = SdCommandTypeAc; + SdCmdBlk.ResponseType = SdResponseTypeR1; SdCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = SdPeimExecCmd (Slot, &Packet); @@ -2320,18 +2360,18 @@ SdPeimSendStatus ( **/ EFI_STATUS SdPeimRwSingleBlock ( - IN SD_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN SD_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2345,7 +2385,7 @@ SdPeimRwSingleBlock ( // Taking 2MB/s as divisor is because it's the lowest // transfer speed of class 2. // - Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000;; + Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000; if (IsRead) { Packet.InDataBuffer = Buffer; @@ -2393,18 +2433,18 @@ SdPeimRwSingleBlock ( **/ EFI_STATUS SdPeimRwMultiBlocks ( - IN SD_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN SD_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2418,7 +2458,7 @@ SdPeimRwMultiBlocks ( // Taking 2MB/s as divisor is because it's the lowest // transfer speed of class 2. // - Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000;; + Packet.Timeout = (BufferSize / (2 * 1024 * 1024) + 1) * 1000 * 1000; if (IsRead) { Packet.InDataBuffer = Buffer; @@ -2463,14 +2503,14 @@ SdPeimRwMultiBlocks ( **/ EFI_STATUS SdPeimSendTuningBlk ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - SD_COMMAND_BLOCK SdCmdBlk; - SD_STATUS_BLOCK SdStatusBlk; - SD_COMMAND_PACKET Packet; - EFI_STATUS Status; - UINT8 TuningBlock[64]; + SD_COMMAND_BLOCK SdCmdBlk; + SD_STATUS_BLOCK SdStatusBlk; + SD_COMMAND_PACKET Packet; + EFI_STATUS Status; + UINT8 TuningBlock[64]; ZeroMem (&SdCmdBlk, sizeof (SdCmdBlk)); ZeroMem (&SdStatusBlk, sizeof (SdStatusBlk)); @@ -2480,9 +2520,9 @@ SdPeimSendTuningBlk ( Packet.SdStatusBlk = &SdStatusBlk; Packet.Timeout = SD_TIMEOUT; - SdCmdBlk.CommandIndex = SD_SEND_TUNING_BLOCK; - SdCmdBlk.CommandType = SdCommandTypeAdtc; - SdCmdBlk.ResponseType = SdResponseTypeR1; + SdCmdBlk.CommandIndex = SD_SEND_TUNING_BLOCK; + SdCmdBlk.CommandType = SdCommandTypeAdtc; + SdCmdBlk.ResponseType = SdResponseTypeR1; SdCmdBlk.CommandArgument = 0; Packet.InDataBuffer = TuningBlock; @@ -2510,21 +2550,22 @@ SdPeimSendTuningBlk ( **/ EFI_STATUS SdPeimTuningClock ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - EFI_STATUS Status; - UINT8 HostCtrl2; - UINT8 Retry; + EFI_STATUS Status; + UINT8 HostCtrl2; + UINT8 Retry; // // Notify the host that the sampling clock tuning procedure starts. // HostCtrl2 = BIT6; - Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + // // Ask the device to send a sequence of tuning blocks till the tuning procedure is done. // @@ -2553,11 +2594,12 @@ SdPeimTuningClock ( // // Abort the tuning procedure and reset the tuning circuit. // - HostCtrl2 = (UINT8)~(BIT6 | BIT7); - Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~(BIT6 | BIT7); + Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + return EFI_DEVICE_ERROR; } @@ -2577,13 +2619,13 @@ SdPeimTuningClock ( **/ EFI_STATUS SdPeimSwitchBusWidth ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - IN UINT8 BusWidth + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + IN UINT8 BusWidth ) { - EFI_STATUS Status; - UINT32 DevStatus; + EFI_STATUS Status; + UINT32 DevStatus; Status = SdPeimSetBusWidth (Slot, Rca, BusWidth); if (EFI_ERROR (Status)) { @@ -2594,6 +2636,7 @@ SdPeimSwitchBusWidth ( if (EFI_ERROR (Status)) { return Status; } + // // Check the switch operation is really successful or not. // @@ -2622,19 +2665,19 @@ SdPeimSwitchBusWidth ( **/ EFI_STATUS SdPeimSetBusMode ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT16 Rca, - IN BOOLEAN S18a + IN SD_PEIM_HC_SLOT *Slot, + IN UINT16 Rca, + IN BOOLEAN S18a ) { - EFI_STATUS Status; - SD_HC_SLOT_CAP Capability; - UINT32 ClockFreq; - UINT8 BusWidth; - UINT8 AccessMode; - UINT8 HostCtrl1; - UINT8 HostCtrl2; - UINT8 SwitchResp[64]; + EFI_STATUS Status; + SD_HC_SLOT_CAP Capability; + UINT32 ClockFreq; + UINT8 BusWidth; + UINT8 AccessMode; + UINT8 HostCtrl1; + UINT8 HostCtrl2; + UINT8 SwitchResp[64]; Status = SdPeimGetCsd (Slot, Rca, &Slot->Csd); if (EFI_ERROR (Status)) { @@ -2654,7 +2697,7 @@ SdPeimSetBusMode ( } BusWidth = 4; - Status = SdPeimSwitchBusWidth (Slot, Rca, BusWidth); + Status = SdPeimSwitchBusWidth (Slot, Rca, BusWidth); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SdPeimSetBusMode: SdPeimSwitchBusWidth fails with %r\n", Status)); return Status; @@ -2668,24 +2711,25 @@ SdPeimSetBusMode ( if (EFI_ERROR (Status)) { return Status; } + // // Calculate supported bus speed/bus width/clock frequency by host and device capability. // ClockFreq = 0; if (S18a && (Capability.Sdr104 != 0) && ((SwitchResp[13] & BIT3) != 0)) { - ClockFreq = 208; + ClockFreq = 208; AccessMode = 3; } else if (S18a && (Capability.Sdr50 != 0) && ((SwitchResp[13] & BIT2) != 0)) { - ClockFreq = 100; + ClockFreq = 100; AccessMode = 2; } else if (S18a && (Capability.Ddr50 != 0) && ((SwitchResp[13] & BIT4) != 0)) { - ClockFreq = 50; + ClockFreq = 50; AccessMode = 4; } else if ((SwitchResp[13] & BIT1) != 0) { - ClockFreq = 50; + ClockFreq = 50; AccessMode = 1; } else { - ClockFreq = 25; + ClockFreq = 25; AccessMode = 0; } @@ -2701,24 +2745,26 @@ SdPeimSetBusMode ( DEBUG ((DEBUG_ERROR, "SdPeimSetBusMode: SdPeimSwitch to AccessMode %d ClockFreq %d BusWidth %d fails! The Switch response is 0x%1x\n", AccessMode, ClockFreq, BusWidth, SwitchResp[16] & 0xF)); return EFI_DEVICE_ERROR; } + // // Set to High Speed timing // if (AccessMode == 1) { HostCtrl1 = BIT2; - Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); + Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL1, sizeof (HostCtrl1), &HostCtrl1); if (EFI_ERROR (Status)) { return Status; } } - HostCtrl2 = (UINT8)~0x7; - Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + HostCtrl2 = (UINT8) ~0x7; + Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } + HostCtrl2 = AccessMode; - Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); + Status = SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); if (EFI_ERROR (Status)) { return Status; } @@ -2755,22 +2801,23 @@ SdPeimSetBusMode ( **/ EFI_STATUS SdPeimIdentification ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ) { - EFI_STATUS Status; - UINT32 Ocr; - UINT16 Rca; - BOOLEAN Xpc; - BOOLEAN S18r; - UINT64 MaxCurrent; - UINT64 Current; - UINT16 ControllerVer; - UINT8 PowerCtrl; - UINT32 PresentState; - UINT8 HostCtrl2; - SD_HC_SLOT_CAP Capability; - UINTN Retry; + EFI_STATUS Status; + UINT32 Ocr; + UINT16 Rca; + BOOLEAN Xpc; + BOOLEAN S18r; + UINT64 MaxCurrent; + UINT64 Current; + UINT16 ControllerVer; + UINT8 PowerCtrl; + UINT32 PresentState; + UINT8 HostCtrl2; + SD_HC_SLOT_CAP Capability; + UINTN Retry; + // // 1. Send Cmd0 to the device // @@ -2779,6 +2826,7 @@ SdPeimIdentification ( DEBUG ((DEBUG_ERROR, "SdPeimIdentification: Executing Cmd0 fails with %r\n", Status)); return Status; } + // // 2. Send Cmd8 to the device // @@ -2787,6 +2835,7 @@ SdPeimIdentification ( DEBUG ((DEBUG_ERROR, "SdPeimIdentification: Executing Cmd8 fails with %r\n", Status)); return Status; } + // // 3. Send SDIO Cmd5 to the device to the SDIO device OCR register. // @@ -2795,6 +2844,7 @@ SdPeimIdentification ( DEBUG ((DEBUG_ERROR, "SdPeimIdentification: Found SDIO device, ignore it as we don't support\n")); return EFI_DEVICE_ERROR; } + // // 4. Send Acmd41 with voltage window 0 to the device // @@ -2853,6 +2903,7 @@ SdPeimIdentification ( ASSERT (FALSE); return EFI_UNSUPPORTED; } + // // 5. Repeatly send Acmd41 with supply voltage window to the device. // Note here we only support the cards complied with SD physical @@ -2871,6 +2922,7 @@ SdPeimIdentification ( DEBUG ((DEBUG_ERROR, "SdPeimIdentification: SdPeimSendOpCond fails too many times\n")); return EFI_DEVICE_ERROR; } + MicroSecondDelay (10 * 1000); } while ((Ocr & BIT31) == 0); @@ -2879,10 +2931,11 @@ SdPeimIdentification ( // (One of support bits is set to 1: SDR50, SDR104 or DDR50 in the // Capabilities register), switch its voltage to 1.8V. // - if ((Capability.Sdr50 != 0 || - Capability.Sdr104 != 0 || - Capability.Ddr50 != 0) && - ((Ocr & BIT24) != 0)) { + if (((Capability.Sdr50 != 0) || + (Capability.Sdr104 != 0) || + (Capability.Ddr50 != 0)) && + ((Ocr & BIT24) != 0)) + { Status = SdPeimVoltageSwitch (Slot); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SdPeimIdentification: Executing SdPeimVoltageSwitch fails with %r\n", Status)); @@ -2901,7 +2954,8 @@ SdPeimIdentification ( Status = EFI_DEVICE_ERROR; goto Error; } - HostCtrl2 = BIT3; + + HostCtrl2 = BIT3; SdPeimHcOrMmio (Slot->SdHcBase + SD_HC_HOST_CTRL2, sizeof (HostCtrl2), &HostCtrl2); MicroSecondDelay (5000); @@ -2924,6 +2978,7 @@ SdPeimIdentification ( goto Error; } } + DEBUG ((DEBUG_INFO, "SdPeimIdentification: Switch to 1.8v signal voltage success\n")); } @@ -2938,6 +2993,7 @@ SdPeimIdentification ( DEBUG ((DEBUG_ERROR, "SdPeimIdentification: Executing SdPeimSetRca fails with %r\n", Status)); return Status; } + // // Enter Data Tranfer Mode. // @@ -2951,7 +3007,7 @@ Error: // // Set SD Bus Power = 0 // - PowerCtrl = (UINT8)~BIT0; - Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_POWER_CTRL, sizeof (PowerCtrl), &PowerCtrl); + PowerCtrl = (UINT8) ~BIT0; + Status = SdPeimHcAndMmio (Slot->SdHcBase + SD_HC_POWER_CTRL, sizeof (PowerCtrl), &PowerCtrl); return EFI_DEVICE_ERROR; } diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.h b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.h index c31297521c..5619e2e473 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.h +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdHci.h @@ -61,9 +61,9 @@ typedef enum { // // The maximum data length of each descriptor line // -#define ADMA_MAX_DATA_PER_LINE 0x10000 -#define SD_SDMA_BOUNDARY 512 * 1024 -#define SD_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) +#define ADMA_MAX_DATA_PER_LINE 0x10000 +#define SD_SDMA_BOUNDARY 512 * 1024 +#define SD_SDMA_ROUND_UP(x, n) (((x) + n) & ~(n - 1)) typedef enum { SdCommandTypeBc, // Broadcast commands, no response @@ -85,76 +85,76 @@ typedef enum { } SD_RESPONSE_TYPE; typedef struct _SD_COMMAND_BLOCK { - UINT16 CommandIndex; - UINT32 CommandArgument; - UINT32 CommandType; // One of the SD_COMMAND_TYPE values - UINT32 ResponseType; // One of the SD_RESPONSE_TYPE values + UINT16 CommandIndex; + UINT32 CommandArgument; + UINT32 CommandType; // One of the SD_COMMAND_TYPE values + UINT32 ResponseType; // One of the SD_RESPONSE_TYPE values } SD_COMMAND_BLOCK; typedef struct _SD_STATUS_BLOCK { - UINT32 Resp0; - UINT32 Resp1; - UINT32 Resp2; - UINT32 Resp3; + UINT32 Resp0; + UINT32 Resp1; + UINT32 Resp2; + UINT32 Resp3; } SD_STATUS_BLOCK; typedef struct _SD_COMMAND_PACKET { - UINT64 Timeout; - SD_COMMAND_BLOCK *SdCmdBlk; - SD_STATUS_BLOCK *SdStatusBlk; - VOID *InDataBuffer; - VOID *OutDataBuffer; - UINT32 InTransferLength; - UINT32 OutTransferLength; + UINT64 Timeout; + SD_COMMAND_BLOCK *SdCmdBlk; + SD_STATUS_BLOCK *SdStatusBlk; + VOID *InDataBuffer; + VOID *OutDataBuffer; + UINT32 InTransferLength; + UINT32 OutTransferLength; } SD_COMMAND_PACKET; #pragma pack(1) typedef struct { - UINT32 Valid:1; - UINT32 End:1; - UINT32 Int:1; - UINT32 Reserved:1; - UINT32 Act:2; - UINT32 Reserved1:10; - UINT32 Length:16; - UINT32 Address; + UINT32 Valid : 1; + UINT32 End : 1; + UINT32 Int : 1; + UINT32 Reserved : 1; + UINT32 Act : 2; + UINT32 Reserved1 : 10; + UINT32 Length : 16; + UINT32 Address; } SD_HC_ADMA_DESC_LINE; typedef struct { - UINT32 TimeoutFreq:6; // bit 0:5 - UINT32 Reserved:1; // bit 6 - UINT32 TimeoutUnit:1; // bit 7 - UINT32 BaseClkFreq:8; // bit 8:15 - UINT32 MaxBlkLen:2; // bit 16:17 - UINT32 BusWidth8:1; // bit 18 - UINT32 Adma2:1; // bit 19 - UINT32 Reserved2:1; // bit 20 - UINT32 HighSpeed:1; // bit 21 - UINT32 Sdma:1; // bit 22 - UINT32 SuspRes:1; // bit 23 - UINT32 Voltage33:1; // bit 24 - UINT32 Voltage30:1; // bit 25 - UINT32 Voltage18:1; // bit 26 - UINT32 Reserved3:1; // bit 27 - UINT32 SysBus64:1; // bit 28 - UINT32 AsyncInt:1; // bit 29 - UINT32 SlotType:2; // bit 30:31 - UINT32 Sdr50:1; // bit 32 - UINT32 Sdr104:1; // bit 33 - UINT32 Ddr50:1; // bit 34 - UINT32 Reserved4:1; // bit 35 - UINT32 DriverTypeA:1; // bit 36 - UINT32 DriverTypeC:1; // bit 37 - UINT32 DriverTypeD:1; // bit 38 - UINT32 DriverType4:1; // bit 39 - UINT32 TimerCount:4; // bit 40:43 - UINT32 Reserved5:1; // bit 44 - UINT32 TuningSDR50:1; // bit 45 - UINT32 RetuningMod:2; // bit 46:47 - UINT32 ClkMultiplier:8; // bit 48:55 - UINT32 Reserved6:7; // bit 56:62 - UINT32 Hs400:1; // bit 63 + UINT32 TimeoutFreq : 6; // bit 0:5 + UINT32 Reserved : 1; // bit 6 + UINT32 TimeoutUnit : 1; // bit 7 + UINT32 BaseClkFreq : 8; // bit 8:15 + UINT32 MaxBlkLen : 2; // bit 16:17 + UINT32 BusWidth8 : 1; // bit 18 + UINT32 Adma2 : 1; // bit 19 + UINT32 Reserved2 : 1; // bit 20 + UINT32 HighSpeed : 1; // bit 21 + UINT32 Sdma : 1; // bit 22 + UINT32 SuspRes : 1; // bit 23 + UINT32 Voltage33 : 1; // bit 24 + UINT32 Voltage30 : 1; // bit 25 + UINT32 Voltage18 : 1; // bit 26 + UINT32 Reserved3 : 1; // bit 27 + UINT32 SysBus64 : 1; // bit 28 + UINT32 AsyncInt : 1; // bit 29 + UINT32 SlotType : 2; // bit 30:31 + UINT32 Sdr50 : 1; // bit 32 + UINT32 Sdr104 : 1; // bit 33 + UINT32 Ddr50 : 1; // bit 34 + UINT32 Reserved4 : 1; // bit 35 + UINT32 DriverTypeA : 1; // bit 36 + UINT32 DriverTypeC : 1; // bit 37 + UINT32 DriverTypeD : 1; // bit 38 + UINT32 DriverType4 : 1; // bit 39 + UINT32 TimerCount : 4; // bit 40:43 + UINT32 Reserved5 : 1; // bit 44 + UINT32 TuningSDR50 : 1; // bit 45 + UINT32 RetuningMod : 2; // bit 46:47 + UINT32 ClkMultiplier : 8; // bit 48:55 + UINT32 Reserved6 : 7; // bit 56:62 + UINT32 Hs400 : 1; // bit 63 } SD_HC_SLOT_CAP; #pragma pack() @@ -170,7 +170,7 @@ typedef struct { **/ EFI_STATUS SdPeimHcReset ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -185,7 +185,7 @@ SdPeimHcReset ( **/ EFI_STATUS SdPeimHcEnableInterrupt ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -200,8 +200,8 @@ SdPeimHcEnableInterrupt ( **/ EFI_STATUS SdPeimHcGetCapability ( - IN UINTN Bar, - OUT SD_HC_SLOT_CAP *Capability + IN UINTN Bar, + OUT SD_HC_SLOT_CAP *Capability ); /** @@ -219,7 +219,7 @@ SdPeimHcGetCapability ( **/ EFI_STATUS SdPeimHcCardDetect ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -234,7 +234,7 @@ SdPeimHcCardDetect ( **/ EFI_STATUS SdPeimHcInitHost ( - IN UINTN Bar + IN UINTN Bar ); /** @@ -256,13 +256,13 @@ SdPeimHcInitHost ( **/ EFI_STATUS SdPeimSwitch ( - IN SD_PEIM_HC_SLOT *Slot, - IN UINT8 AccessMode, - IN UINT8 CommandSystem, - IN UINT8 DriveStrength, - IN UINT8 PowerLimit, - IN BOOLEAN Mode, - OUT UINT8 *SwitchResp + IN SD_PEIM_HC_SLOT *Slot, + IN UINT8 AccessMode, + IN UINT8 CommandSystem, + IN UINT8 DriveStrength, + IN UINT8 PowerLimit, + IN BOOLEAN Mode, + OUT UINT8 *SwitchResp ); /** @@ -284,12 +284,12 @@ SdPeimSwitch ( **/ EFI_STATUS SdPeimRwSingleBlock ( - IN SD_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN SD_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ); /** @@ -311,12 +311,12 @@ SdPeimRwSingleBlock ( **/ EFI_STATUS SdPeimRwMultiBlocks ( - IN SD_PEIM_HC_SLOT *Slot, - IN EFI_LBA Lba, - IN UINT32 BlockSize, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead + IN SD_PEIM_HC_SLOT *Slot, + IN EFI_LBA Lba, + IN UINT32 BlockSize, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead ); /** @@ -332,7 +332,7 @@ SdPeimRwMultiBlocks ( **/ EFI_STATUS SdPeimIdentification ( - IN SD_PEIM_HC_SLOT *Slot + IN SD_PEIM_HC_SLOT *Slot ); /** @@ -343,8 +343,7 @@ SdPeimIdentification ( **/ VOID SdPeimFreeTrb ( - IN SD_TRB *Trb + IN SD_TRB *Trb ); #endif - diff --git a/MdeModulePkg/Bus/Sd/SdDxe/ComponentName.c b/MdeModulePkg/Bus/Sd/SdDxe/ComponentName.c index acd29d72cf..405a3d3ffe 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Sd/SdDxe/ComponentName.c @@ -11,17 +11,17 @@ // // Driver name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdDxeDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdDxeDriverNameTable[] = { { "eng;en", L"Edkii Sd Memory Card Device Driver" }, - { NULL , NULL } + { NULL, NULL } }; // // Controller name table // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdDxeControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mSdDxeControllerNameTable[] = { { "eng;en", L"Edkii Sd Host Controller" }, - { NULL , NULL } + { NULL, NULL } }; // @@ -36,9 +36,9 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gSdDxeComponentName = // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSdDxeComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) SdDxeComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) SdDxeComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gSdDxeComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)SdDxeComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)SdDxeComponentNameGetControllerName, "en" }; @@ -96,7 +96,6 @@ SdDxeComponentNameGetDriverName ( DriverName, (BOOLEAN)(This == &gSdDxeComponentName) ); - } /** @@ -170,11 +169,11 @@ SdDxeComponentNameGetDriverName ( EFI_STATUS EFIAPI SdDxeComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { EFI_STATUS Status; @@ -204,13 +203,14 @@ SdDxeComponentNameGetControllerName ( if (EFI_ERROR (Status)) { return Status; } + // // Get the child context // Status = gBS->OpenProtocol ( ChildHandle, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, gSdDxeDriverBinding.DriverBindingHandle, ChildHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -219,7 +219,7 @@ SdDxeComponentNameGetControllerName ( return EFI_UNSUPPORTED; } - Device = SD_DEVICE_DATA_FROM_BLKIO (BlockIo); + Device = SD_DEVICE_DATA_FROM_BLKIO (BlockIo); ControllerNameTable = Device->ControllerNameTable; } @@ -231,4 +231,3 @@ SdDxeComponentNameGetControllerName ( (BOOLEAN)(This == &gSdDxeComponentName) ); } - diff --git a/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.c b/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.c index 5a041d3618..45df48ff72 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.c +++ b/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.c @@ -19,20 +19,24 @@ VOID EFIAPI AsyncIoCallback ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - SD_REQUEST *Request; + SD_REQUEST *Request; gBS->CloseEvent (Event); - Request = (SD_REQUEST *) Context; + Request = (SD_REQUEST *)Context; DEBUG_CODE_BEGIN (); - DEBUG ((DEBUG_INFO, "Sd Async Request: CmdIndex[%d] Arg[%08x] %r\n", - Request->SdMmcCmdBlk.CommandIndex, Request->SdMmcCmdBlk.CommandArgument, - Request->Packet.TransactionStatus)); + DEBUG (( + DEBUG_INFO, + "Sd Async Request: CmdIndex[%d] Arg[%08x] %r\n", + Request->SdMmcCmdBlk.CommandIndex, + Request->SdMmcCmdBlk.CommandArgument, + Request->Packet.TransactionStatus + )); DEBUG_CODE_END (); if (EFI_ERROR (Request->Packet.TransactionStatus)) { @@ -61,8 +65,8 @@ AsyncIoCallback ( **/ EFI_STATUS SdSetRca ( - IN SD_DEVICE *Device, - OUT UINT16 *Rca + IN SD_DEVICE *Device, + OUT UINT16 *Rca ) { EFI_STATUS Status; @@ -106,8 +110,8 @@ SdSetRca ( **/ EFI_STATUS SdSelect ( - IN SD_DEVICE *Device, - IN UINT16 Rca + IN SD_DEVICE *Device, + IN UINT16 Rca ) { EFI_STATUS Status; @@ -130,6 +134,7 @@ SdSelect ( if (Rca != 0) { SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1b; } + SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -151,9 +156,9 @@ SdSelect ( **/ EFI_STATUS SdSendStatus ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT UINT32 *DevStatus + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT UINT32 *DevStatus ) { EFI_STATUS Status; @@ -171,15 +176,16 @@ SdSendStatus ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_STATUS; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; + SdMmcCmdBlk.CommandIndex = SD_SEND_STATUS; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR1; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); if (!EFI_ERROR (Status)) { CopyMem (DevStatus, &SdMmcStatusBlk.Resp0, sizeof (UINT32)); } + return Status; } @@ -197,9 +203,9 @@ SdSendStatus ( **/ EFI_STATUS SdGetCsd ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT SD_CSD *Csd + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT SD_CSD *Csd ) { EFI_STATUS Status; @@ -219,9 +225,9 @@ SdGetCsd ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_CSD; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = SD_SEND_CSD; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -230,7 +236,7 @@ SdGetCsd ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (SD_CSD) - 1); + CopyMem (((UINT8 *)Csd) + 1, &SdMmcStatusBlk.Resp0, sizeof (SD_CSD) - 1); } return Status; @@ -250,9 +256,9 @@ SdGetCsd ( **/ EFI_STATUS SdGetCid ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT SD_CID *Cid + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT SD_CID *Cid ) { EFI_STATUS Status; @@ -272,9 +278,9 @@ SdGetCid ( Packet.SdMmcStatusBlk = &SdMmcStatusBlk; Packet.Timeout = SD_GENERIC_TIMEOUT; - SdMmcCmdBlk.CommandIndex = SD_SEND_CID; - SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; - SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; + SdMmcCmdBlk.CommandIndex = SD_SEND_CID; + SdMmcCmdBlk.CommandType = SdMmcCommandTypeAc; + SdMmcCmdBlk.ResponseType = SdMmcResponseTypeR2; SdMmcCmdBlk.CommandArgument = (UINT32)Rca << 16; Status = PassThru->PassThru (PassThru, Device->Slot, &Packet, NULL); @@ -283,7 +289,7 @@ SdGetCid ( // // For details, refer to SD Host Controller Simplified Spec 3.0 Table 2-12. // - CopyMem (((UINT8*)Cid) + 1, &SdMmcStatusBlk.Resp0, sizeof (SD_CID) - 1); + CopyMem (((UINT8 *)Cid) + 1, &SdMmcStatusBlk.Resp0, sizeof (SD_CID) - 1); } return Status; @@ -310,19 +316,19 @@ SdGetCid ( **/ EFI_STATUS SdRwSingleBlock ( - IN SD_DEVICE *Device, - IN EFI_LBA Lba, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN SD_DEVICE *Device, + IN EFI_LBA Lba, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - SD_REQUEST *RwSingleBlkReq; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + SD_REQUEST *RwSingleBlkReq; + EFI_TPL OldTpl; RwSingleBlkReq = NULL; PassThru = Device->Private->PassThru; @@ -334,7 +340,7 @@ SdRwSingleBlock ( } RwSingleBlkReq->Signature = SD_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Device->Queue, &RwSingleBlkReq->Link); gBS->RestoreTPL (OldTpl); RwSingleBlkReq->Packet.SdMmcCmdBlk = &RwSingleBlkReq->SdMmcCmdBlk; @@ -403,6 +409,7 @@ Error: if (RwSingleBlkReq->Event != NULL) { gBS->CloseEvent (RwSingleBlkReq->Event); } + FreePool (RwSingleBlkReq); } } else { @@ -441,19 +448,19 @@ Error: **/ EFI_STATUS SdRwMultiBlocks ( - IN SD_DEVICE *Device, - IN EFI_LBA Lba, - IN VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN SD_DEVICE *Device, + IN EFI_LBA Lba, + IN VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - SD_REQUEST *RwMultiBlkReq; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_TPL OldTpl; + EFI_STATUS Status; + SD_REQUEST *RwMultiBlkReq; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_TPL OldTpl; RwMultiBlkReq = NULL; @@ -466,7 +473,7 @@ SdRwMultiBlocks ( } RwMultiBlkReq->Signature = SD_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Device->Queue, &RwMultiBlkReq->Link); gBS->RestoreTPL (OldTpl); RwMultiBlkReq->Packet.SdMmcCmdBlk = &RwMultiBlkReq->SdMmcCmdBlk; @@ -535,6 +542,7 @@ Error: if (RwMultiBlkReq->Event != NULL) { gBS->CloseEvent (RwMultiBlkReq->Event); } + FreePool (RwMultiBlkReq); } } else { @@ -577,23 +585,23 @@ Error: **/ EFI_STATUS SdReadWrite ( - IN SD_DEVICE *Device, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT VOID *Buffer, - IN UINTN BufferSize, - IN BOOLEAN IsRead, - IN OUT EFI_BLOCK_IO2_TOKEN *Token + IN SD_DEVICE *Device, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT VOID *Buffer, + IN UINTN BufferSize, + IN BOOLEAN IsRead, + IN OUT EFI_BLOCK_IO2_TOKEN *Token ) { - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN BlockNum; - UINTN IoAlign; - UINTN Remaining; - UINT32 MaxBlock; - BOOLEAN LastRw; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN BlockNum; + UINTN IoAlign; + UINTN Remaining; + UINT32 MaxBlock; + BOOLEAN LastRw; Status = EFI_SUCCESS; Media = &Device->BlockMedia; @@ -619,6 +627,7 @@ SdReadWrite ( Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } + return EFI_SUCCESS; } @@ -627,13 +636,13 @@ SdReadWrite ( return EFI_BAD_BUFFER_SIZE; } - BlockNum = BufferSize / BlockSize; + BlockNum = BufferSize / BlockSize; if ((Lba + BlockNum - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } IoAlign = Media->IoAlign; - if (IoAlign > 0 && (((UINTN) Buffer & (IoAlign - 1)) != 0)) { + if ((IoAlign > 0) && (((UINTN)Buffer & (IoAlign - 1)) != 0)) { return EFI_INVALID_PARAMETER; } @@ -661,14 +670,22 @@ SdReadWrite ( } else { Status = SdRwMultiBlocks (Device, Lba, Buffer, BufferSize, IsRead, Token, LastRw); } + if (EFI_ERROR (Status)) { return Status; } - DEBUG ((DEBUG_BLKIO, "Sd%a(): Lba 0x%x BlkNo 0x%x Event %p with %r\n", - IsRead ? "Read" : "Write", Lba, BlockNum, - (Token != NULL) ? Token->Event : NULL, Status)); - Lba += BlockNum; - Buffer = (UINT8*)Buffer + BufferSize; + + DEBUG (( + DEBUG_BLKIO, + "Sd%a(): Lba 0x%x BlkNo 0x%x Event %p with %r\n", + IsRead ? "Read" : "Write", + Lba, + BlockNum, + (Token != NULL) ? Token->Event : NULL, + Status + )); + Lba += BlockNum; + Buffer = (UINT8 *)Buffer + BufferSize; Remaining -= BlockNum; } @@ -689,13 +706,13 @@ SdReadWrite ( EFI_STATUS EFIAPI SdReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - SD_DEVICE *Device; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_STATUS Status; + SD_DEVICE *Device; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; Device = SD_DEVICE_DATA_FROM_BLKIO (This); @@ -734,11 +751,11 @@ SdReadBlocks ( IN UINT32 MediaId, IN EFI_LBA Lba, IN UINTN BufferSize, - OUT VOID *Buffer + OUT VOID *Buffer ) { - EFI_STATUS Status; - SD_DEVICE *Device; + EFI_STATUS Status; + SD_DEVICE *Device; Device = SD_DEVICE_DATA_FROM_BLKIO (This); @@ -769,15 +786,15 @@ SdReadBlocks ( EFI_STATUS EFIAPI SdWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { - EFI_STATUS Status; - SD_DEVICE *Device; + EFI_STATUS Status; + SD_DEVICE *Device; Device = SD_DEVICE_DATA_FROM_BLKIO (This); @@ -798,7 +815,7 @@ SdWriteBlocks ( EFI_STATUS EFIAPI SdFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ) { // @@ -825,18 +842,19 @@ SdResetEx ( IN BOOLEAN ExtendedVerification ) { - SD_DEVICE *Device; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - SD_REQUEST *Request; - EFI_TPL OldTpl; + SD_DEVICE *Device; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + SD_REQUEST *Request; + EFI_TPL OldTpl; Device = SD_DEVICE_DATA_FROM_BLKIO2 (This); OldTpl = gBS->RaiseTPL (TPL_NOTIFY); for (Link = GetFirstNode (&Device->Queue); !IsNull (&Device->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Device->Queue, Link); RemoveEntryList (Link); @@ -851,6 +869,7 @@ SdResetEx ( FreePool (Request); } + gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; @@ -885,16 +904,16 @@ SdResetEx ( EFI_STATUS EFIAPI SdReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - SD_DEVICE *Device; + EFI_STATUS Status; + SD_DEVICE *Device; Device = SD_DEVICE_DATA_FROM_BLKIO2 (This); @@ -927,16 +946,16 @@ SdReadBlocksEx ( EFI_STATUS EFIAPI SdWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ) { - EFI_STATUS Status; - SD_DEVICE *Device; + EFI_STATUS Status; + SD_DEVICE *Device; Device = SD_DEVICE_DATA_FROM_BLKIO2 (This); @@ -965,7 +984,7 @@ SdFlushBlocksEx ( // // Signal event and return directly. // - if (Token != NULL && Token->Event != NULL) { + if ((Token != NULL) && (Token->Event != NULL)) { Token->TransactionStatus = EFI_SUCCESS; gBS->SignalEvent (Token->Event); } @@ -989,16 +1008,16 @@ SdFlushBlocksEx ( **/ EFI_STATUS SdEraseBlockStart ( - IN SD_DEVICE *Device, - IN EFI_LBA StartLba, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN SD_DEVICE *Device, + IN EFI_LBA StartLba, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - SD_REQUEST *EraseBlockStart; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + SD_REQUEST *EraseBlockStart; + EFI_TPL OldTpl; EraseBlockStart = NULL; PassThru = Device->Private->PassThru; @@ -1010,7 +1029,7 @@ SdEraseBlockStart ( } EraseBlockStart->Signature = SD_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Device->Queue, &EraseBlockStart->Link); gBS->RestoreTPL (OldTpl); EraseBlockStart->Packet.SdMmcCmdBlk = &EraseBlockStart->SdMmcCmdBlk; @@ -1060,6 +1079,7 @@ Error: if (EraseBlockStart->Event != NULL) { gBS->CloseEvent (EraseBlockStart->Event); } + FreePool (EraseBlockStart); } } else { @@ -1093,16 +1113,16 @@ Error: **/ EFI_STATUS SdEraseBlockEnd ( - IN SD_DEVICE *Device, - IN EFI_LBA EndLba, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN SD_DEVICE *Device, + IN EFI_LBA EndLba, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - SD_REQUEST *EraseBlockEnd; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + SD_REQUEST *EraseBlockEnd; + EFI_TPL OldTpl; EraseBlockEnd = NULL; PassThru = Device->Private->PassThru; @@ -1114,7 +1134,7 @@ SdEraseBlockEnd ( } EraseBlockEnd->Signature = SD_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Device->Queue, &EraseBlockEnd->Link); gBS->RestoreTPL (OldTpl); EraseBlockEnd->Packet.SdMmcCmdBlk = &EraseBlockEnd->SdMmcCmdBlk; @@ -1164,6 +1184,7 @@ Error: if (EraseBlockEnd->Event != NULL) { gBS->CloseEvent (EraseBlockEnd->Event); } + FreePool (EraseBlockEnd); } } else { @@ -1196,15 +1217,15 @@ Error: **/ EFI_STATUS SdEraseBlock ( - IN SD_DEVICE *Device, - IN EFI_BLOCK_IO2_TOKEN *Token, - IN BOOLEAN IsEnd + IN SD_DEVICE *Device, + IN EFI_BLOCK_IO2_TOKEN *Token, + IN BOOLEAN IsEnd ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - SD_REQUEST *EraseBlock; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + SD_REQUEST *EraseBlock; + EFI_TPL OldTpl; EraseBlock = NULL; PassThru = Device->Private->PassThru; @@ -1216,7 +1237,7 @@ SdEraseBlock ( } EraseBlock->Signature = SD_REQUEST_SIGNATURE; - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); InsertTailList (&Device->Queue, &EraseBlock->Link); gBS->RestoreTPL (OldTpl); EraseBlock->Packet.SdMmcCmdBlk = &EraseBlock->SdMmcCmdBlk; @@ -1260,6 +1281,7 @@ Error: if (EraseBlock->Event != NULL) { gBS->CloseEvent (EraseBlock->Event); } + FreePool (EraseBlock); } } else { @@ -1307,19 +1329,19 @@ Error: EFI_STATUS EFIAPI SdEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ) { - EFI_STATUS Status; - EFI_BLOCK_IO_MEDIA *Media; - UINTN BlockSize; - UINTN BlockNum; - EFI_LBA LastLba; - SD_DEVICE *Device; + EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + UINTN BlockSize; + UINTN BlockNum; + EFI_LBA LastLba; + SD_DEVICE *Device; Status = EFI_SUCCESS; Device = SD_DEVICE_DATA_FROM_ERASEBLK (This); @@ -1341,7 +1363,7 @@ SdEraseBlocks ( return EFI_INVALID_PARAMETER; } - BlockNum = Size / BlockSize; + BlockNum = Size / BlockSize; if ((Lba + BlockNum - 1) > Media->LastBlock) { return EFI_INVALID_PARAMETER; } @@ -1352,17 +1374,17 @@ SdEraseBlocks ( LastLba = Lba + BlockNum - 1; - Status = SdEraseBlockStart (Device, Lba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE); + Status = SdEraseBlockStart (Device, Lba, (EFI_BLOCK_IO2_TOKEN *)Token, FALSE); if (EFI_ERROR (Status)) { return Status; } - Status = SdEraseBlockEnd (Device, LastLba, (EFI_BLOCK_IO2_TOKEN*)Token, FALSE); + Status = SdEraseBlockEnd (Device, LastLba, (EFI_BLOCK_IO2_TOKEN *)Token, FALSE); if (EFI_ERROR (Status)) { return Status; } - Status = SdEraseBlock (Device, (EFI_BLOCK_IO2_TOKEN*)Token, TRUE); + Status = SdEraseBlock (Device, (EFI_BLOCK_IO2_TOKEN *)Token, TRUE); if (EFI_ERROR (Status)) { return Status; } diff --git a/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.h b/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.h index b6b4c45f1f..b456ea31e8 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.h +++ b/MdeModulePkg/Bus/Sd/SdDxe/SdBlockIo.h @@ -26,8 +26,8 @@ EFI_STATUS EFIAPI SdReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -56,7 +56,7 @@ SdReadBlocks ( IN UINT32 MediaId, IN EFI_LBA Lba, IN UINTN BufferSize, - OUT VOID *Buffer + OUT VOID *Buffer ); /** @@ -82,11 +82,11 @@ SdReadBlocks ( EFI_STATUS EFIAPI SdWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -102,7 +102,7 @@ SdWriteBlocks ( EFI_STATUS EFIAPI SdFlushBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This + IN EFI_BLOCK_IO_PROTOCOL *This ); /** @@ -152,12 +152,12 @@ SdResetEx ( EFI_STATUS EFIAPI SdReadBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -185,12 +185,12 @@ SdReadBlocksEx ( EFI_STATUS EFIAPI SdWriteBlocksEx ( - IN EFI_BLOCK_IO2_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_BLOCK_IO2_TOKEN *Token, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO2_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_BLOCK_IO2_TOKEN *Token, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -241,12 +241,11 @@ SdFlushBlocksEx ( EFI_STATUS EFIAPI SdEraseBlocks ( - IN EFI_ERASE_BLOCK_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN OUT EFI_ERASE_BLOCK_TOKEN *Token, - IN UINTN Size + IN EFI_ERASE_BLOCK_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN OUT EFI_ERASE_BLOCK_TOKEN *Token, + IN UINTN Size ); #endif - diff --git a/MdeModulePkg/Bus/Sd/SdDxe/SdDiskInfo.c b/MdeModulePkg/Bus/Sd/SdDxe/SdDiskInfo.c index 6563f7232a..8bc82b9be7 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/SdDiskInfo.c +++ b/MdeModulePkg/Bus/Sd/SdDxe/SdDiskInfo.c @@ -32,8 +32,8 @@ SdDiskInfoInquiry ( IN OUT UINT32 *InquiryDataSize ) { - EFI_STATUS Status; - SD_DEVICE *Device; + EFI_STATUS Status; + SD_DEVICE *Device; Device = SD_DEVICE_DATA_FROM_DISKINFO (This); diff --git a/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.c b/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.c index 4ca374990d..a7b2515b14 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.c +++ b/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.c @@ -14,7 +14,7 @@ // // SdDxe Driver Binding Protocol Instance // -EFI_DRIVER_BINDING_PROTOCOL gSdDxeDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gSdDxeDriverBinding = { SdDxeDriverBindingSupported, SdDxeDriverBindingStart, SdDxeDriverBindingStop, @@ -26,7 +26,7 @@ EFI_DRIVER_BINDING_PROTOCOL gSdDxeDriverBinding = { // // Template for SD_DEVICE data structure. // -SD_DEVICE mSdDeviceTemplate = { +SD_DEVICE mSdDeviceTemplate = { SD_DEVICE_SIGNATURE, // Signature NULL, // Handle NULL, // DevicePath @@ -99,41 +99,42 @@ DumpCsd ( IN SD_CSD *Csd ) { - SD_CSD2 *Csd2; - - DEBUG((DEBUG_INFO, "== Dump Sd Csd Register==\n")); - DEBUG((DEBUG_INFO, " CSD structure 0x%x\n", Csd->CsdStructure)); - DEBUG((DEBUG_INFO, " Data read access-time 1 0x%x\n", Csd->Taac)); - DEBUG((DEBUG_INFO, " Data read access-time 2 0x%x\n", Csd->Nsac)); - DEBUG((DEBUG_INFO, " Max. bus clock frequency 0x%x\n", Csd->TranSpeed)); - DEBUG((DEBUG_INFO, " Device command classes 0x%x\n", Csd->Ccc)); - DEBUG((DEBUG_INFO, " Max. read data block length 0x%x\n", Csd->ReadBlLen)); - DEBUG((DEBUG_INFO, " Partial blocks for read allowed 0x%x\n", Csd->ReadBlPartial)); - DEBUG((DEBUG_INFO, " Write block misalignment 0x%x\n", Csd->WriteBlkMisalign)); - DEBUG((DEBUG_INFO, " Read block misalignment 0x%x\n", Csd->ReadBlkMisalign)); - DEBUG((DEBUG_INFO, " DSR implemented 0x%x\n", Csd->DsrImp)); + SD_CSD2 *Csd2; + + DEBUG ((DEBUG_INFO, "== Dump Sd Csd Register==\n")); + DEBUG ((DEBUG_INFO, " CSD structure 0x%x\n", Csd->CsdStructure)); + DEBUG ((DEBUG_INFO, " Data read access-time 1 0x%x\n", Csd->Taac)); + DEBUG ((DEBUG_INFO, " Data read access-time 2 0x%x\n", Csd->Nsac)); + DEBUG ((DEBUG_INFO, " Max. bus clock frequency 0x%x\n", Csd->TranSpeed)); + DEBUG ((DEBUG_INFO, " Device command classes 0x%x\n", Csd->Ccc)); + DEBUG ((DEBUG_INFO, " Max. read data block length 0x%x\n", Csd->ReadBlLen)); + DEBUG ((DEBUG_INFO, " Partial blocks for read allowed 0x%x\n", Csd->ReadBlPartial)); + DEBUG ((DEBUG_INFO, " Write block misalignment 0x%x\n", Csd->WriteBlkMisalign)); + DEBUG ((DEBUG_INFO, " Read block misalignment 0x%x\n", Csd->ReadBlkMisalign)); + DEBUG ((DEBUG_INFO, " DSR implemented 0x%x\n", Csd->DsrImp)); if (Csd->CsdStructure == 0) { - DEBUG((DEBUG_INFO, " Device size 0x%x\n", Csd->CSizeLow | (Csd->CSizeHigh << 2))); - DEBUG((DEBUG_INFO, " Max. read current @ VDD min 0x%x\n", Csd->VddRCurrMin)); - DEBUG((DEBUG_INFO, " Max. read current @ VDD max 0x%x\n", Csd->VddRCurrMax)); - DEBUG((DEBUG_INFO, " Max. write current @ VDD min 0x%x\n", Csd->VddWCurrMin)); - DEBUG((DEBUG_INFO, " Max. write current @ VDD max 0x%x\n", Csd->VddWCurrMax)); + DEBUG ((DEBUG_INFO, " Device size 0x%x\n", Csd->CSizeLow | (Csd->CSizeHigh << 2))); + DEBUG ((DEBUG_INFO, " Max. read current @ VDD min 0x%x\n", Csd->VddRCurrMin)); + DEBUG ((DEBUG_INFO, " Max. read current @ VDD max 0x%x\n", Csd->VddRCurrMax)); + DEBUG ((DEBUG_INFO, " Max. write current @ VDD min 0x%x\n", Csd->VddWCurrMin)); + DEBUG ((DEBUG_INFO, " Max. write current @ VDD max 0x%x\n", Csd->VddWCurrMax)); } else { - Csd2 = (SD_CSD2*)(VOID*)Csd; - DEBUG((DEBUG_INFO, " Device size 0x%x\n", Csd2->CSizeLow | (Csd->CSizeHigh << 16))); + Csd2 = (SD_CSD2 *)(VOID *)Csd; + DEBUG ((DEBUG_INFO, " Device size 0x%x\n", Csd2->CSizeLow | (Csd->CSizeHigh << 16))); } - DEBUG((DEBUG_INFO, " Erase sector size 0x%x\n", Csd->SectorSize)); - DEBUG((DEBUG_INFO, " Erase single block enable 0x%x\n", Csd->EraseBlkEn)); - DEBUG((DEBUG_INFO, " Write protect group size 0x%x\n", Csd->WpGrpSize)); - DEBUG((DEBUG_INFO, " Write protect group enable 0x%x\n", Csd->WpGrpEnable)); - DEBUG((DEBUG_INFO, " Write speed factor 0x%x\n", Csd->R2WFactor)); - DEBUG((DEBUG_INFO, " Max. write data block length 0x%x\n", Csd->WriteBlLen)); - DEBUG((DEBUG_INFO, " Partial blocks for write allowed 0x%x\n", Csd->WriteBlPartial)); - DEBUG((DEBUG_INFO, " File format group 0x%x\n", Csd->FileFormatGrp)); - DEBUG((DEBUG_INFO, " Copy flag (OTP) 0x%x\n", Csd->Copy)); - DEBUG((DEBUG_INFO, " Permanent write protection 0x%x\n", Csd->PermWriteProtect)); - DEBUG((DEBUG_INFO, " Temporary write protection 0x%x\n", Csd->TmpWriteProtect)); - DEBUG((DEBUG_INFO, " File format 0x%x\n", Csd->FileFormat)); + + DEBUG ((DEBUG_INFO, " Erase sector size 0x%x\n", Csd->SectorSize)); + DEBUG ((DEBUG_INFO, " Erase single block enable 0x%x\n", Csd->EraseBlkEn)); + DEBUG ((DEBUG_INFO, " Write protect group size 0x%x\n", Csd->WpGrpSize)); + DEBUG ((DEBUG_INFO, " Write protect group enable 0x%x\n", Csd->WpGrpEnable)); + DEBUG ((DEBUG_INFO, " Write speed factor 0x%x\n", Csd->R2WFactor)); + DEBUG ((DEBUG_INFO, " Max. write data block length 0x%x\n", Csd->WriteBlLen)); + DEBUG ((DEBUG_INFO, " Partial blocks for write allowed 0x%x\n", Csd->WriteBlPartial)); + DEBUG ((DEBUG_INFO, " File format group 0x%x\n", Csd->FileFormatGrp)); + DEBUG ((DEBUG_INFO, " Copy flag (OTP) 0x%x\n", Csd->Copy)); + DEBUG ((DEBUG_INFO, " Permanent write protection 0x%x\n", Csd->PermWriteProtect)); + DEBUG ((DEBUG_INFO, " Temporary write protection 0x%x\n", Csd->TmpWriteProtect)); + DEBUG ((DEBUG_INFO, " File format 0x%x\n", Csd->FileFormat)); return EFI_SUCCESS; } @@ -149,8 +150,8 @@ DumpCsd ( **/ EFI_STATUS GetSdModelName ( - IN OUT SD_DEVICE *Device, - IN SD_CID *Cid + IN OUT SD_DEVICE *Device, + IN SD_CID *Cid ) { CHAR8 String[SD_MODEL_NAME_MAX_LEN]; @@ -178,19 +179,19 @@ GetSdModelName ( **/ EFI_STATUS DiscoverUserArea ( - IN SD_DEVICE *Device + IN SD_DEVICE *Device ) { - EFI_STATUS Status; - SD_CSD *Csd; - SD_CSD2 *Csd2; - SD_CID *Cid; - UINT64 Capacity; - UINT32 DevStatus; - UINT16 Rca; - UINT32 CSize; - UINT32 CSizeMul; - UINT32 ReadBlLen; + EFI_STATUS Status; + SD_CSD *Csd; + SD_CSD2 *Csd2; + SD_CID *Cid; + UINT64 Capacity; + UINT32 DevStatus; + UINT16 Rca; + UINT32 CSize; + UINT32 CSizeMul; + UINT32 ReadBlLen; // // Deselect the device to force it enter stby mode. @@ -210,6 +211,7 @@ DiscoverUserArea ( if (EFI_ERROR (Status)) { return Status; } + DumpCsd (Csd); Cid = &Device->Cid; @@ -217,6 +219,7 @@ DiscoverUserArea ( if (EFI_ERROR (Status)) { return Status; } + GetSdModelName (Device, Cid); Status = SdSelect (Device, Rca); @@ -232,15 +235,15 @@ DiscoverUserArea ( if (Csd->CsdStructure == 0) { Device->SectorAddressing = FALSE; - CSize = (Csd->CSizeHigh << 2 | Csd->CSizeLow) + 1; - CSizeMul = (1 << (Csd->CSizeMul + 2)); - ReadBlLen = (1 << (Csd->ReadBlLen)); - Capacity = MultU64x32 (MultU64x32 ((UINT64)CSize, CSizeMul), ReadBlLen); + CSize = (Csd->CSizeHigh << 2 | Csd->CSizeLow) + 1; + CSizeMul = (1 << (Csd->CSizeMul + 2)); + ReadBlLen = (1 << (Csd->ReadBlLen)); + Capacity = MultU64x32 (MultU64x32 ((UINT64)CSize, CSizeMul), ReadBlLen); } else { Device->SectorAddressing = TRUE; - Csd2 = (SD_CSD2*)(VOID*)Csd; - CSize = (Csd2->CSizeHigh << 16 | Csd2->CSizeLow) + 1; - Capacity = MultU64x32 ((UINT64)CSize, SIZE_512KB); + Csd2 = (SD_CSD2 *)(VOID *)Csd; + CSize = (Csd2->CSizeHigh << 16 | Csd2->CSizeLow) + 1; + Capacity = MultU64x32 ((UINT64)CSize, SIZE_512KB); } Device->BlockIo.Media = &Device->BlockMedia; @@ -279,23 +282,23 @@ DiscoverUserArea ( EFI_STATUS EFIAPI DiscoverSdDevice ( - IN SD_DRIVER_PRIVATE_DATA *Private, - IN UINT8 Slot + IN SD_DRIVER_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - EFI_STATUS Status; - SD_DEVICE *Device; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; - EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - EFI_HANDLE DeviceHandle; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_STATUS Status; + SD_DEVICE *Device; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + EFI_HANDLE DeviceHandle; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; Device = NULL; DevicePath = NULL; NewDevicePath = NULL; RemainingDevicePath = NULL; - PassThru = Private->PassThru; + PassThru = Private->PassThru; // // Build Device Path @@ -305,7 +308,7 @@ DiscoverSdDevice ( Slot, &DevicePath ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -324,10 +327,10 @@ DiscoverSdDevice ( goto Error; } - DeviceHandle = NULL; + DeviceHandle = NULL; RemainingDevicePath = NewDevicePath; - Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(RemainingDevicePath)) { + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &RemainingDevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (RemainingDevicePath)) { // // The device has been started, directly return to fast boot. // @@ -353,7 +356,7 @@ DiscoverSdDevice ( // Expose user area in the Sd memory card to upper layer. // Status = DiscoverUserArea (Device); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto Error; } @@ -392,7 +395,7 @@ DiscoverSdDevice ( gBS->OpenProtocol ( Private->Controller, &gEfiSdMmcPassThruProtocolGuid, - (VOID **) &(Private->PassThru), + (VOID **)&(Private->PassThru), Private->DriverBindingHandle, Device->Handle, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -458,15 +461,15 @@ Error: EFI_STATUS EFIAPI SdDxeDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - UINT8 Slot; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + UINT8 Slot; // // Test EFI_SD_MMC_PASS_THRU_PROTOCOL on the controller handle. @@ -474,7 +477,7 @@ SdDxeDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiSdMmcPassThruProtocolGuid, - (VOID**) &PassThru, + (VOID **)&PassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -523,7 +526,7 @@ SdDxeDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -569,27 +572,27 @@ SdDxeDriverBindingSupported ( EFI_STATUS EFIAPI SdDxeDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - SD_DRIVER_PRIVATE_DATA *Private; - UINT8 Slot; + EFI_STATUS Status; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + SD_DRIVER_PRIVATE_DATA *Private; + UINT8 Slot; Private = NULL; PassThru = NULL; - Status = gBS->OpenProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - (VOID **) &PassThru, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Status = gBS->OpenProtocol ( + Controller, + &gEfiSdMmcPassThruProtocolGuid, + (VOID **)&PassThru, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if ((EFI_ERROR (Status)) && (Status != EFI_ALREADY_STARTED)) { return Status; } @@ -607,7 +610,7 @@ SdDxeDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -631,7 +634,7 @@ SdDxeDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &Private, + (VOID **)&Private, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -676,14 +679,15 @@ Error: if (Private != NULL) { gBS->UninstallMultipleProtocolInterfaces ( - Controller, - &gEfiCallerIdGuid, - Private, - NULL - ); + Controller, + &gEfiCallerIdGuid, + Private, + NULL + ); FreePool (Private); } } + return Status; } @@ -716,30 +720,30 @@ Error: EFI_STATUS EFIAPI SdDxeDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - BOOLEAN AllChildrenStopped; - UINTN Index; - SD_DRIVER_PRIVATE_DATA *Private; - SD_DEVICE *Device; - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_BLOCK_IO2_PROTOCOL *BlockIo2; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - LIST_ENTRY *Link; - LIST_ENTRY *NextLink; - SD_REQUEST *Request; - EFI_TPL OldTpl; + EFI_STATUS Status; + BOOLEAN AllChildrenStopped; + UINTN Index; + SD_DRIVER_PRIVATE_DATA *Private; + SD_DEVICE *Device; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_BLOCK_IO2_PROTOCOL *BlockIo2; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + LIST_ENTRY *Link; + LIST_ENTRY *NextLink; + SD_REQUEST *Request; + EFI_TPL OldTpl; if (NumberOfChildren == 0) { Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &Private, + (VOID **)&Private, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -749,16 +753,16 @@ SdDxeDriverBindingStop ( } gBS->UninstallProtocolInterface ( - Controller, - &gEfiCallerIdGuid, - Private - ); + Controller, + &gEfiCallerIdGuid, + Private + ); gBS->CloseProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiSdMmcPassThruProtocolGuid, + This->DriverBindingHandle, + Controller + ); FreePool (Private); @@ -770,19 +774,19 @@ SdDxeDriverBindingStop ( for (Index = 0; Index < NumberOfChildren; Index++) { BlockIo = NULL; BlockIo2 = NULL; - Status = gBS->OpenProtocol ( - ChildHandleBuffer[Index], - &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Status = gBS->OpenProtocol ( + ChildHandleBuffer[Index], + &gEfiBlockIoProtocolGuid, + (VOID **)&BlockIo, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); if (EFI_ERROR (Status)) { Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiBlockIo2ProtocolGuid, - (VOID **) &BlockIo2, + (VOID **)&BlockIo2, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -806,7 +810,8 @@ SdDxeDriverBindingStop ( OldTpl = gBS->RaiseTPL (TPL_NOTIFY); for (Link = GetFirstNode (&Device->Queue); !IsNull (&Device->Queue, Link); - Link = NextLink) { + Link = NextLink) + { NextLink = GetNextNode (&Device->Queue, Link); RemoveEntryList (Link); @@ -821,6 +826,7 @@ SdDxeDriverBindingStop ( FreePool (Request); } + gBS->RestoreTPL (OldTpl); // @@ -849,14 +855,14 @@ SdDxeDriverBindingStop ( ); if (EFI_ERROR (Status)) { AllChildrenStopped = FALSE; - gBS->OpenProtocol ( - Controller, - &gEfiSdMmcPassThruProtocolGuid, - (VOID **)&PassThru, - This->DriverBindingHandle, - ChildHandleBuffer[Index], - EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER - ); + gBS->OpenProtocol ( + Controller, + &gEfiSdMmcPassThruProtocolGuid, + (VOID **)&PassThru, + This->DriverBindingHandle, + ChildHandleBuffer[Index], + EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER + ); } else { FreePool (Device->DevicePath); FreeUnicodeStringTable (Device->ControllerNameTable); @@ -884,11 +890,11 @@ SdDxeDriverBindingStop ( EFI_STATUS EFIAPI InitializeSdDxe ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). diff --git a/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.h b/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.h index ff740a5218..8d95f278cd 100644 --- a/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.h +++ b/MdeModulePkg/Bus/Sd/SdDxe/SdDxe.h @@ -39,11 +39,11 @@ // // Global Variables // -extern EFI_DRIVER_BINDING_PROTOCOL gSdDxeDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL gSdDxeComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gSdDxeComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gSdDxeDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gSdDxeComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gSdDxeComponentName2; -#define SD_DEVICE_SIGNATURE SIGNATURE_32 ('S', 'D', 't', 'f') +#define SD_DEVICE_SIGNATURE SIGNATURE_32 ('S', 'D', 't', 'f') #define SD_DEVICE_DATA_FROM_BLKIO(a) \ CR(a, SD_DEVICE, BlockIo, SD_DEVICE_SIGNATURE) @@ -60,11 +60,11 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gSdDxeComponentName2; // // Take 2.5 seconds as generic time out value, 1 microsecond as unit. // -#define SD_GENERIC_TIMEOUT 2500 * 1000 +#define SD_GENERIC_TIMEOUT 2500 * 1000 -#define SD_REQUEST_SIGNATURE SIGNATURE_32 ('S', 'D', 'R', 'E') +#define SD_REQUEST_SIGNATURE SIGNATURE_32 ('S', 'D', 'R', 'E') -#define SD_MODEL_NAME_MAX_LEN 32 +#define SD_MODEL_NAME_MAX_LEN 32 typedef struct _SD_DEVICE SD_DEVICE; typedef struct _SD_DRIVER_PRIVATE_DATA SD_DRIVER_PRIVATE_DATA; @@ -73,40 +73,40 @@ typedef struct _SD_DRIVER_PRIVATE_DATA SD_DRIVER_PRIVATE_DATA; // Asynchronous I/O request. // typedef struct { - UINT32 Signature; - LIST_ENTRY Link; + UINT32 Signature; + LIST_ENTRY Link; - EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; - EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; - EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; + EFI_SD_MMC_COMMAND_BLOCK SdMmcCmdBlk; + EFI_SD_MMC_STATUS_BLOCK SdMmcStatusBlk; + EFI_SD_MMC_PASS_THRU_COMMAND_PACKET Packet; - BOOLEAN IsEnd; + BOOLEAN IsEnd; - EFI_BLOCK_IO2_TOKEN *Token; + EFI_BLOCK_IO2_TOKEN *Token; - EFI_EVENT Event; + EFI_EVENT Event; } SD_REQUEST; #define SD_REQUEST_FROM_LINK(a) \ CR(a, SD_REQUEST, Link, SD_REQUEST_SIGNATURE) struct _SD_DEVICE { - UINT32 Signature; - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINT8 Slot; - BOOLEAN SectorAddressing; - EFI_BLOCK_IO_PROTOCOL BlockIo; - EFI_BLOCK_IO2_PROTOCOL BlockIo2; - EFI_BLOCK_IO_MEDIA BlockMedia; - EFI_ERASE_BLOCK_PROTOCOL EraseBlock; - EFI_DISK_INFO_PROTOCOL DiskInfo; - - LIST_ENTRY Queue; - - SD_CSD Csd; - SD_CID Cid; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + UINT32 Signature; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINT8 Slot; + BOOLEAN SectorAddressing; + EFI_BLOCK_IO_PROTOCOL BlockIo; + EFI_BLOCK_IO2_PROTOCOL BlockIo2; + EFI_BLOCK_IO_MEDIA BlockMedia; + EFI_ERASE_BLOCK_PROTOCOL EraseBlock; + EFI_DISK_INFO_PROTOCOL DiskInfo; + + LIST_ENTRY Queue; + + SD_CSD Csd; + SD_CID Cid; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; // // The model name consists of three fields in CID register // 1) OEM/Application ID (2 bytes) @@ -114,19 +114,19 @@ struct _SD_DEVICE { // 3) Product Serial Number (4 bytes) // The delimiters of these fields are whitespace. // - CHAR16 ModelName[SD_MODEL_NAME_MAX_LEN]; - SD_DRIVER_PRIVATE_DATA *Private; -} ; + CHAR16 ModelName[SD_MODEL_NAME_MAX_LEN]; + SD_DRIVER_PRIVATE_DATA *Private; +}; // // SD DXE driver private data structure // struct _SD_DRIVER_PRIVATE_DATA { - EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; - EFI_HANDLE Controller; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EFI_HANDLE DriverBindingHandle; -} ; + EFI_SD_MMC_PASS_THRU_PROTOCOL *PassThru; + EFI_HANDLE Controller; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_HANDLE DriverBindingHandle; +}; /** Tests to see if this driver supports a given controller. If a child device is provided, @@ -173,9 +173,9 @@ struct _SD_DRIVER_PRIVATE_DATA { EFI_STATUS EFIAPI SdDxeDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -216,9 +216,9 @@ SdDxeDriverBindingSupported ( EFI_STATUS EFIAPI SdDxeDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -250,10 +250,10 @@ SdDxeDriverBindingStart ( EFI_STATUS EFIAPI SdDxeDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); /** @@ -374,11 +374,11 @@ SdDxeComponentNameGetDriverName ( EFI_STATUS EFIAPI SdDxeComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -394,8 +394,8 @@ SdDxeComponentNameGetControllerName ( **/ EFI_STATUS SdSetRca ( - IN SD_DEVICE *Device, - OUT UINT16 *Rca + IN SD_DEVICE *Device, + OUT UINT16 *Rca ); /** @@ -411,8 +411,8 @@ SdSetRca ( **/ EFI_STATUS SdSelect ( - IN SD_DEVICE *Device, - IN UINT16 Rca + IN SD_DEVICE *Device, + IN UINT16 Rca ); /** @@ -428,9 +428,9 @@ SdSelect ( **/ EFI_STATUS SdSendStatus ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT UINT32 *DevStatus + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT UINT32 *DevStatus ); /** @@ -447,9 +447,9 @@ SdSendStatus ( **/ EFI_STATUS SdGetCsd ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT SD_CSD *Csd + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT SD_CSD *Csd ); /** @@ -466,10 +466,9 @@ SdGetCsd ( **/ EFI_STATUS SdGetCid ( - IN SD_DEVICE *Device, - IN UINT16 Rca, - OUT SD_CID *Cid + IN SD_DEVICE *Device, + IN UINT16 Rca, + OUT SD_CID *Cid ); #endif - diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c index 61378a63cd..62aeaf86c8 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/DmaMem.c @@ -32,11 +32,11 @@ EDKII_IOMMU_PPI *mIoMmu; **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ) { EFI_STATUS Status; @@ -54,23 +54,25 @@ IoMmuMap ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + switch (Operation) { - case EdkiiIoMmuOperationBusMasterRead: - case EdkiiIoMmuOperationBusMasterRead64: - Attribute = EDKII_IOMMU_ACCESS_READ; - break; - case EdkiiIoMmuOperationBusMasterWrite: - case EdkiiIoMmuOperationBusMasterWrite64: - Attribute = EDKII_IOMMU_ACCESS_WRITE; - break; - case EdkiiIoMmuOperationBusMasterCommonBuffer: - case EdkiiIoMmuOperationBusMasterCommonBuffer64: - Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; - break; - default: - ASSERT(FALSE); - return EFI_INVALID_PARAMETER; + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + Attribute = EDKII_IOMMU_ACCESS_READ; + break; + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + Attribute = EDKII_IOMMU_ACCESS_WRITE; + break; + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + Attribute = EDKII_IOMMU_ACCESS_READ | EDKII_IOMMU_ACCESS_WRITE; + break; + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -81,9 +83,10 @@ IoMmuMap ( } } else { *DeviceAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)HostAddress; - *Mapping = NULL; - Status = EFI_SUCCESS; + *Mapping = NULL; + Status = EFI_SUCCESS; } + return Status; } @@ -98,7 +101,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ) { EFI_STATUS Status; @@ -109,6 +112,7 @@ IoMmuUnmap ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -142,7 +146,7 @@ IoMmuAllocateBuffer ( UINTN NumberOfBytes; EFI_PHYSICAL_ADDRESS HostPhyAddress; - *HostAddress = NULL; + *HostAddress = NULL; *DeviceAddress = 0; if (mIoMmu != NULL) { @@ -157,18 +161,19 @@ IoMmuAllocateBuffer ( return EFI_OUT_OF_RESOURCES; } - NumberOfBytes = EFI_PAGES_TO_SIZE(Pages); - Status = mIoMmu->Map ( - mIoMmu, - EdkiiIoMmuOperationBusMasterCommonBuffer, - *HostAddress, - &NumberOfBytes, - DeviceAddress, - Mapping - ); + NumberOfBytes = EFI_PAGES_TO_SIZE (Pages); + Status = mIoMmu->Map ( + mIoMmu, + EdkiiIoMmuOperationBusMasterCommonBuffer, + *HostAddress, + &NumberOfBytes, + DeviceAddress, + Mapping + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + Status = mIoMmu->SetAttribute ( mIoMmu, *Mapping, @@ -186,10 +191,12 @@ IoMmuAllocateBuffer ( if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - *HostAddress = (VOID *)(UINTN)HostPhyAddress; + + *HostAddress = (VOID *)(UINTN)HostPhyAddress; *DeviceAddress = HostPhyAddress; - *Mapping = NULL; + *Mapping = NULL; } + return Status; } @@ -207,9 +214,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ) { EFI_STATUS Status; @@ -221,6 +228,7 @@ IoMmuFreeBuffer ( } else { Status = EFI_SUCCESS; } + return Status; } @@ -239,4 +247,3 @@ IoMmuInit ( (VOID **)&mIoMmu ); } - diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c index 4664187291..b331c0f3e3 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.c @@ -10,7 +10,7 @@ // // Template for UFS HC Peim Private Data. // -UFS_PEIM_HC_PRIVATE_DATA gUfsHcPeimTemplate = { +UFS_PEIM_HC_PRIVATE_DATA gUfsHcPeimTemplate = { UFS_PEIM_HC_SIG, // Signature NULL, // Controller NULL, // Pool @@ -131,8 +131,6 @@ UFS_PEIM_HC_PRIVATE_DATA gUfsHcPeimTemplate = { } }; - - /** Execute TEST UNITY READY SCSI command on a specific UFS device. @@ -148,20 +146,20 @@ UFS_PEIM_HC_PRIVATE_DATA gUfsHcPeimTemplate = { **/ EFI_STATUS UfsPeimTestUnitReady ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINTN Lun, - OUT VOID *SenseData OPTIONAL, - OUT UINT8 *SenseDataLength + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINTN Lun, + OUT VOID *SenseData OPTIONAL, + OUT UINT8 *SenseDataLength ) { - UFS_SCSI_REQUEST_PACKET Packet; - UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIX]; - EFI_STATUS Status; + UFS_SCSI_REQUEST_PACKET Packet; + UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIX]; + EFI_STATUS Status; ZeroMem (&Packet, sizeof (UFS_SCSI_REQUEST_PACKET)); ZeroMem (Cdb, sizeof (Cdb)); - Cdb[0] = EFI_SCSI_OP_TEST_UNIT_READY; + Cdb[0] = EFI_SCSI_OP_TEST_UNIT_READY; Packet.Timeout = UFS_TIMEOUT; Packet.Cdb = Cdb; @@ -170,7 +168,7 @@ UfsPeimTestUnitReady ( Packet.SenseData = SenseData; Packet.SenseDataLength = *SenseDataLength; - Status = UfsExecScsiCmds (Private,(UINT8)Lun, &Packet); + Status = UfsExecScsiCmds (Private, (UINT8)Lun, &Packet); if (*SenseDataLength != 0) { *SenseDataLength = Packet.SenseDataLength; @@ -179,8 +177,6 @@ UfsPeimTestUnitReady ( return Status; } - - /** Execute READ CAPACITY(10) SCSI command on a specific UFS device. @@ -198,17 +194,17 @@ UfsPeimTestUnitReady ( **/ EFI_STATUS UfsPeimReadCapacity ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINTN Lun, - OUT VOID *DataBuffer, - OUT UINT32 *DataLength, - OUT VOID *SenseData OPTIONAL, - OUT UINT8 *SenseDataLength + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINTN Lun, + OUT VOID *DataBuffer, + OUT UINT32 *DataLength, + OUT VOID *SenseData OPTIONAL, + OUT UINT8 *SenseDataLength ) { - UFS_SCSI_REQUEST_PACKET Packet; - UINT8 Cdb[UFS_SCSI_OP_LENGTH_TEN]; - EFI_STATUS Status; + UFS_SCSI_REQUEST_PACKET Packet; + UINT8 Cdb[UFS_SCSI_OP_LENGTH_TEN]; + EFI_STATUS Status; ZeroMem (&Packet, sizeof (UFS_SCSI_REQUEST_PACKET)); ZeroMem (Cdb, sizeof (Cdb)); @@ -254,17 +250,17 @@ UfsPeimReadCapacity ( **/ EFI_STATUS UfsPeimReadCapacity16 ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINTN Lun, - OUT VOID *DataBuffer, - OUT UINT32 *DataLength, - OUT VOID *SenseData OPTIONAL, - OUT UINT8 *SenseDataLength + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINTN Lun, + OUT VOID *DataBuffer, + OUT UINT32 *DataLength, + OUT VOID *SenseData OPTIONAL, + OUT UINT8 *SenseDataLength ) { - UFS_SCSI_REQUEST_PACKET Packet; - UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIXTEEN]; - EFI_STATUS Status; + UFS_SCSI_REQUEST_PACKET Packet; + UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIXTEEN]; + EFI_STATUS Status; ZeroMem (&Packet, sizeof (UFS_SCSI_REQUEST_PACKET)); ZeroMem (Cdb, sizeof (Cdb)); @@ -314,26 +310,26 @@ UfsPeimReadCapacity16 ( **/ EFI_STATUS UfsPeimRead10 ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINTN Lun, - IN UINTN StartLba, - IN UINT32 SectorNum, - OUT VOID *DataBuffer, - OUT UINT32 *DataLength, - OUT VOID *SenseData OPTIONAL, - OUT UINT8 *SenseDataLength + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINTN Lun, + IN UINTN StartLba, + IN UINT32 SectorNum, + OUT VOID *DataBuffer, + OUT UINT32 *DataLength, + OUT VOID *SenseData OPTIONAL, + OUT UINT8 *SenseDataLength ) { - UFS_SCSI_REQUEST_PACKET Packet; - UINT8 Cdb[UFS_SCSI_OP_LENGTH_TEN]; - EFI_STATUS Status; + UFS_SCSI_REQUEST_PACKET Packet; + UINT8 Cdb[UFS_SCSI_OP_LENGTH_TEN]; + EFI_STATUS Status; ZeroMem (&Packet, sizeof (UFS_SCSI_REQUEST_PACKET)); ZeroMem (Cdb, sizeof (Cdb)); Cdb[0] = EFI_SCSI_OP_READ10; - WriteUnaligned32 ((UINT32 *)&Cdb[2], SwapBytes32 ((UINT32) StartLba)); - WriteUnaligned16 ((UINT16 *)&Cdb[7], SwapBytes16 ((UINT16) SectorNum)); + WriteUnaligned32 ((UINT32 *)&Cdb[2], SwapBytes32 ((UINT32)StartLba)); + WriteUnaligned16 ((UINT16 *)&Cdb[7], SwapBytes16 ((UINT16)SectorNum)); Packet.Timeout = UFS_TIMEOUT; Packet.Cdb = Cdb; @@ -376,19 +372,19 @@ UfsPeimRead10 ( **/ EFI_STATUS UfsPeimRead16 ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINTN Lun, - IN UINTN StartLba, - IN UINT32 SectorNum, - OUT VOID *DataBuffer, - OUT UINT32 *DataLength, - OUT VOID *SenseData OPTIONAL, - OUT UINT8 *SenseDataLength + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINTN Lun, + IN UINTN StartLba, + IN UINT32 SectorNum, + OUT VOID *DataBuffer, + OUT UINT32 *DataLength, + OUT VOID *SenseData OPTIONAL, + OUT UINT8 *SenseDataLength ) { - UFS_SCSI_REQUEST_PACKET Packet; - UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIXTEEN]; - EFI_STATUS Status; + UFS_SCSI_REQUEST_PACKET Packet; + UINT8 Cdb[UFS_SCSI_OP_LENGTH_SIXTEEN]; + EFI_STATUS Status; ZeroMem (&Packet, sizeof (UFS_SCSI_REQUEST_PACKET)); ZeroMem (Cdb, sizeof (Cdb)); @@ -432,28 +428,31 @@ UfsPeimRead16 ( **/ EFI_STATUS UfsPeimParsingSenseKeys ( - IN EFI_PEI_BLOCK_IO2_MEDIA *Media, - IN EFI_SCSI_SENSE_DATA *SenseData, - OUT BOOLEAN *NeedRetry + IN EFI_PEI_BLOCK_IO2_MEDIA *Media, + IN EFI_SCSI_SENSE_DATA *SenseData, + OUT BOOLEAN *NeedRetry ) { if ((SenseData->Sense_Key == EFI_SCSI_SK_NOT_READY) && - (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_NO_MEDIA)) { + (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_NO_MEDIA)) + { Media->MediaPresent = FALSE; - *NeedRetry = FALSE; + *NeedRetry = FALSE; DEBUG ((DEBUG_VERBOSE, "UfsBlockIoPei: Is No Media\n")); return EFI_DEVICE_ERROR; } if ((SenseData->Sense_Key == EFI_SCSI_SK_UNIT_ATTENTION) && - (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_CHANGE)) { + (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_CHANGE)) + { *NeedRetry = TRUE; DEBUG ((DEBUG_VERBOSE, "UfsBlockIoPei: Is Media Change\n")); return EFI_SUCCESS; } if ((SenseData->Sense_Key == EFI_SCSI_SK_UNIT_ATTENTION) && - (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_RESET)) { + (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_RESET)) + { *NeedRetry = TRUE; DEBUG ((DEBUG_VERBOSE, "UfsBlockIoPei: Was Reset Before\n")); return EFI_SUCCESS; @@ -461,7 +460,8 @@ UfsPeimParsingSenseKeys ( if ((SenseData->Sense_Key == EFI_SCSI_SK_MEDIUM_ERROR) || ((SenseData->Sense_Key == EFI_SCSI_SK_NOT_READY) && - (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_UPSIDE_DOWN))) { + (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_MEDIA_UPSIDE_DOWN))) + { *NeedRetry = FALSE; DEBUG ((DEBUG_VERBOSE, "UfsBlockIoPei: Media Error\n")); return EFI_DEVICE_ERROR; @@ -475,7 +475,8 @@ UfsPeimParsingSenseKeys ( if ((SenseData->Sense_Key == EFI_SCSI_SK_NOT_READY) && (SenseData->Addnl_Sense_Code == EFI_SCSI_ASC_NOT_READY) && - (SenseData->Addnl_Sense_Code_Qualifier == EFI_SCSI_ASCQ_IN_PROGRESS)) { + (SenseData->Addnl_Sense_Code_Qualifier == EFI_SCSI_ASCQ_IN_PROGRESS)) + { *NeedRetry = TRUE; DEBUG ((DEBUG_VERBOSE, "UfsBlockIoPei: Was Reset Before\n")); return EFI_SUCCESS; @@ -486,7 +487,6 @@ UfsPeimParsingSenseKeys ( return EFI_DEVICE_ERROR; } - /** Gets the count of block I/O devices that one specific block driver detects. @@ -573,15 +573,15 @@ UfsBlockIoPeimGetMediaInfo ( OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { - EFI_STATUS Status; - UFS_PEIM_HC_PRIVATE_DATA *Private; - EFI_SCSI_SENSE_DATA SenseData; - UINT8 SenseDataLength; - EFI_SCSI_DISK_CAPACITY_DATA Capacity; - EFI_SCSI_DISK_CAPACITY_DATA16 Capacity16; - UINTN DataLength; - BOOLEAN NeedRetry; - UINTN Lun; + EFI_STATUS Status; + UFS_PEIM_HC_PRIVATE_DATA *Private; + EFI_SCSI_SENSE_DATA SenseData; + UINT8 SenseDataLength; + EFI_SCSI_DISK_CAPACITY_DATA Capacity; + EFI_SCSI_DISK_CAPACITY_DATA16 Capacity16; + UINTN DataLength; + BOOLEAN NeedRetry; + UINTN Lun; Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); NeedRetry = TRUE; @@ -621,30 +621,31 @@ UfsBlockIoPeimGetMediaInfo ( if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } - } while (NeedRetry); DataLength = sizeof (EFI_SCSI_DISK_CAPACITY_DATA); SenseDataLength = 0; - Status = UfsPeimReadCapacity (Private, Lun, &Capacity, (UINT32 *)&DataLength, NULL, &SenseDataLength); + Status = UfsPeimReadCapacity (Private, Lun, &Capacity, (UINT32 *)&DataLength, NULL, &SenseDataLength); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } if ((Capacity.LastLba3 == 0xff) && (Capacity.LastLba2 == 0xff) && - (Capacity.LastLba1 == 0xff) && (Capacity.LastLba0 == 0xff)) { + (Capacity.LastLba1 == 0xff) && (Capacity.LastLba0 == 0xff)) + { DataLength = sizeof (EFI_SCSI_DISK_CAPACITY_DATA16); SenseDataLength = 0; - Status = UfsPeimReadCapacity16 (Private, Lun, &Capacity16, (UINT32 *)&DataLength, NULL, &SenseDataLength); + Status = UfsPeimReadCapacity16 (Private, Lun, &Capacity16, (UINT32 *)&DataLength, NULL, &SenseDataLength); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } + Private->Media[Lun].LastBlock = ((UINT32)Capacity16.LastLba3 << 24) | (Capacity16.LastLba2 << 16) | (Capacity16.LastLba1 << 8) | Capacity16.LastLba0; - Private->Media[Lun].LastBlock |= LShiftU64 ((UINT64)Capacity16.LastLba7, 56) | LShiftU64((UINT64)Capacity16.LastLba6, 48) | LShiftU64 ((UINT64)Capacity16.LastLba5, 40) | LShiftU64 ((UINT64)Capacity16.LastLba4, 32); + Private->Media[Lun].LastBlock |= LShiftU64 ((UINT64)Capacity16.LastLba7, 56) | LShiftU64 ((UINT64)Capacity16.LastLba6, 48) | LShiftU64 ((UINT64)Capacity16.LastLba5, 40) | LShiftU64 ((UINT64)Capacity16.LastLba4, 32); Private->Media[Lun].BlockSize = (Capacity16.BlockSize3 << 24) | (Capacity16.BlockSize2 << 16) | (Capacity16.BlockSize1 << 8) | Capacity16.BlockSize0; } else { - Private->Media[Lun].LastBlock = ((UINT32)Capacity.LastLba3 << 24) | (Capacity.LastLba2 << 16) | (Capacity.LastLba1 << 8) | Capacity.LastLba0; - Private->Media[Lun].BlockSize = (Capacity.BlockSize3 << 24) | (Capacity.BlockSize2 << 16) | (Capacity.BlockSize1 << 8) | Capacity.BlockSize0; + Private->Media[Lun].LastBlock = ((UINT32)Capacity.LastLba3 << 24) | (Capacity.LastLba2 << 16) | (Capacity.LastLba1 << 8) | Capacity.LastLba0; + Private->Media[Lun].BlockSize = (Capacity.BlockSize3 << 24) | (Capacity.BlockSize2 << 16) | (Capacity.BlockSize1 << 8) | Capacity.BlockSize0; } MediaInfo->DeviceType = UfsDevice; @@ -700,14 +701,14 @@ UfsBlockIoPeimReadBlocks ( OUT VOID *Buffer ) { - EFI_STATUS Status; - UINTN BlockSize; - UINTN NumberOfBlocks; - UFS_PEIM_HC_PRIVATE_DATA *Private; - EFI_SCSI_SENSE_DATA SenseData; - UINT8 SenseDataLength; - BOOLEAN NeedRetry; - UINTN Lun; + EFI_STATUS Status; + UINTN BlockSize; + UINTN NumberOfBlocks; + UFS_PEIM_HC_PRIVATE_DATA *Private; + EFI_SCSI_SENSE_DATA SenseData; + UINT8 SenseDataLength; + BOOLEAN NeedRetry; + UINTN Lun; Status = EFI_SUCCESS; NeedRetry = TRUE; @@ -767,7 +768,6 @@ UfsBlockIoPeimReadBlocks ( if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } - } while (NeedRetry); SenseDataLength = 0; @@ -794,6 +794,7 @@ UfsBlockIoPeimReadBlocks ( &SenseDataLength ); } + return Status; } @@ -819,9 +820,9 @@ UfsBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI UfsBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ) { // @@ -877,25 +878,25 @@ UfsBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI UfsBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { - EFI_STATUS Status; - UFS_PEIM_HC_PRIVATE_DATA *Private; - EFI_PEI_BLOCK_IO_MEDIA Media; - UINTN Lun; - - Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - - Status = UfsBlockIoPeimGetMediaInfo ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - &Media - ); + EFI_STATUS Status; + UFS_PEIM_HC_PRIVATE_DATA *Private; + EFI_PEI_BLOCK_IO_MEDIA Media; + UINTN Lun; + + Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + + Status = UfsBlockIoPeimGetMediaInfo ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + &Media + ); if (EFI_ERROR (Status)) { return Status; } @@ -942,28 +943,28 @@ UfsBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI UfsBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { - EFI_STATUS Status; - UFS_PEIM_HC_PRIVATE_DATA *Private; - - Status = EFI_SUCCESS; - Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); - - Status = UfsBlockIoPeimReadBlocks ( - PeiServices, - &Private->BlkIoPpi, - DeviceIndex, - StartLBA, - BufferSize, - Buffer - ); + EFI_STATUS Status; + UFS_PEIM_HC_PRIVATE_DATA *Private; + + Status = EFI_SUCCESS; + Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2 (This); + + Status = UfsBlockIoPeimReadBlocks ( + PeiServices, + &Private->BlkIoPpi, + DeviceIndex, + StartLBA, + BufferSize, + Buffer + ); return Status; } @@ -986,7 +987,7 @@ UfsEndOfPei ( IN VOID *Ppi ) { - UFS_PEIM_HC_PRIVATE_DATA *Private; + UFS_PEIM_HC_PRIVATE_DATA *Private; Private = GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY (NotifyDescriptor); @@ -1028,17 +1029,17 @@ UfsEndOfPei ( EFI_STATUS EFIAPI InitializeUfsBlockIoPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - UFS_PEIM_HC_PRIVATE_DATA *Private; - EDKII_UFS_HOST_CONTROLLER_PPI *UfsHcPpi; - UINT32 Index; - UFS_CONFIG_DESC Config; - UINTN MmioBase; - UINT8 Controller; + EFI_STATUS Status; + UFS_PEIM_HC_PRIVATE_DATA *Private; + EDKII_UFS_HOST_CONTROLLER_PPI *UfsHcPpi; + UINT32 Index; + UFS_CONFIG_DESC Config; + UINTN MmioBase; + UINT8 Controller; // // Shadow this PEIM to run from memory @@ -1054,7 +1055,7 @@ InitializeUfsBlockIoPeim ( &gEdkiiPeiUfsHostControllerPpiGuid, 0, NULL, - (VOID **) &UfsHcPpi + (VOID **)&UfsHcPpi ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h index 6e2305aa2b..a0b615b7ea 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsBlockIoPei.h @@ -29,14 +29,14 @@ #include "UfsHci.h" #include "UfsHcMem.h" -#define UFS_PEIM_HC_SIG SIGNATURE_32 ('U', 'F', 'S', 'H') +#define UFS_PEIM_HC_SIG SIGNATURE_32 ('U', 'F', 'S', 'H') -#define UFS_PEIM_MAX_LUNS 8 +#define UFS_PEIM_MAX_LUNS 8 typedef struct { - UINT8 Lun[UFS_PEIM_MAX_LUNS]; - UINT16 BitMask:12; // Bit 0~7 is for common luns. Bit 8~11 is reserved for those well known luns - UINT16 Rsvd:4; + UINT8 Lun[UFS_PEIM_MAX_LUNS]; + UINT16 BitMask : 12; // Bit 0~7 is for common luns. Bit 8~11 is reserved for those well known luns + UINT16 Rsvd : 4; } UFS_PEIM_EXPOSED_LUNS; typedef struct { @@ -48,52 +48,52 @@ typedef struct { /// EFI_TIMEOUT if the time required to execute the SCSI /// Request Packet is greater than Timeout. /// - UINT64 Timeout; + UINT64 Timeout; /// /// A pointer to the data buffer to transfer between the SCSI /// controller and the SCSI device for read and bidirectional commands. /// - VOID *InDataBuffer; + VOID *InDataBuffer; /// /// A pointer to the data buffer to transfer between the SCSI /// controller and the SCSI device for write or bidirectional commands. /// - VOID *OutDataBuffer; + VOID *OutDataBuffer; /// /// A pointer to the sense data that was generated by the execution of /// the SCSI Request Packet. /// - VOID *SenseData; + VOID *SenseData; /// /// A pointer to buffer that contains the Command Data Block to /// send to the SCSI device specified by Target and Lun. /// - VOID *Cdb; + VOID *Cdb; /// /// On Input, the size, in bytes, of InDataBuffer. On output, the /// number of bytes transferred between the SCSI controller and the SCSI device. /// - UINT32 InTransferLength; + UINT32 InTransferLength; /// /// On Input, the size, in bytes of OutDataBuffer. On Output, the /// Number of bytes transferred between SCSI Controller and the SCSI device. /// - UINT32 OutTransferLength; + UINT32 OutTransferLength; /// /// The length, in bytes, of the buffer Cdb. The standard values are 6, /// 10, 12, and 16, but other values are possible if a variable length CDB is used. /// - UINT8 CdbLength; + UINT8 CdbLength; /// /// The direction of the data transfer. 0 for reads, 1 for writes. A /// value of 2 is Reserved for Bi-Directional SCSI commands. /// - UINT8 DataDirection; + UINT8 DataDirection; /// /// On input, the length in bytes of the SenseData buffer. On /// output, the number of bytes written to the SenseData buffer. /// - UINT8 SenseDataLength; + UINT8 SenseDataLength; } UFS_SCSI_REQUEST_PACKET; typedef struct _UFS_PEIM_HC_PRIVATE_DATA { @@ -129,32 +129,32 @@ typedef struct _UFS_PEIM_HC_PRIVATE_DATA { UFS_PEIM_EXPOSED_LUNS Luns; } UFS_PEIM_HC_PRIVATE_DATA; -#define UFS_TIMEOUT MultU64x32((UINT64)(3), 10000000) +#define UFS_TIMEOUT MultU64x32((UINT64)(3), 10000000) -#define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) +#define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) -#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIoPpi, UFS_PEIM_HC_SIG) -#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, UFS_PEIM_HC_SIG) -#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, UFS_PEIM_HC_SIG) +#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIoPpi, UFS_PEIM_HC_SIG) +#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS2(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, BlkIo2Ppi, UFS_PEIM_HC_SIG) +#define GET_UFS_PEIM_HC_PRIVATE_DATA_FROM_THIS_NOTIFY(a) CR (a, UFS_PEIM_HC_PRIVATE_DATA, EndOfPeiNotifyList, UFS_PEIM_HC_SIG) #define UFS_SCSI_OP_LENGTH_SIX 0x6 #define UFS_SCSI_OP_LENGTH_TEN 0xa #define UFS_SCSI_OP_LENGTH_SIXTEEN 0x10 typedef struct _UFS_DEVICE_MANAGEMENT_REQUEST_PACKET { - UINT64 Timeout; - VOID *InDataBuffer; - VOID *OutDataBuffer; - UINT8 Opcode; - UINT8 DescId; - UINT8 Index; - UINT8 Selector; - UINT32 InTransferLength; - UINT32 OutTransferLength; - UINT8 DataDirection; - UINT8 Ocs; + UINT64 Timeout; + VOID *InDataBuffer; + VOID *OutDataBuffer; + UINT8 Opcode; + UINT8 DescId; + UINT8 Index; + UINT8 Selector; + UINT32 InTransferLength; + UINT32 OutTransferLength; + UINT8 DataDirection; + UINT8 Ocs; } UFS_DEVICE_MANAGEMENT_REQUEST_PACKET; /** @@ -178,9 +178,9 @@ typedef struct _UFS_DEVICE_MANAGEMENT_REQUEST_PACKET { **/ EFI_STATUS UfsExecScsiCmds ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 Lun, - IN OUT UFS_SCSI_REQUEST_PACKET *Packet + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 Lun, + IN OUT UFS_SCSI_REQUEST_PACKET *Packet ); /** @@ -194,7 +194,7 @@ UfsExecScsiCmds ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -208,7 +208,7 @@ UfsControllerInit ( **/ EFI_STATUS UfsControllerStop ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -224,8 +224,8 @@ UfsControllerStop ( **/ EFI_STATUS UfsSetFlag ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 FlagId + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 FlagId ); /** @@ -246,13 +246,13 @@ UfsSetFlag ( **/ EFI_STATUS UfsRwDeviceDesc ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT VOID *Descriptor, - IN UINT32 DescSize + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT VOID *Descriptor, + IN UINT32 DescSize ); /** @@ -270,7 +270,7 @@ UfsRwDeviceDesc ( **/ EFI_STATUS UfsExecNopCmds ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -417,9 +417,9 @@ UfsBlockIoPeimReadBlocks ( EFI_STATUS EFIAPI UfsBlockIoPeimGetDeviceNo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -466,10 +466,10 @@ UfsBlockIoPeimGetDeviceNo2 ( EFI_STATUS EFIAPI UfsBlockIoPeimGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ); /** @@ -509,12 +509,12 @@ UfsBlockIoPeimGetMediaInfo2 ( EFI_STATUS EFIAPI UfsBlockIoPeimReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -528,7 +528,7 @@ UfsBlockIoPeimReadBlocks2 ( **/ EFI_STATUS UfsPeimInitMemPool ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ); /** @@ -542,7 +542,7 @@ UfsPeimInitMemPool ( **/ EFI_STATUS UfsPeimFreeMemPool ( - IN UFS_PEIM_MEM_POOL *Pool + IN UFS_PEIM_MEM_POOL *Pool ); /** @@ -557,8 +557,8 @@ UfsPeimFreeMemPool ( **/ VOID * UfsPeimAllocateMem ( - IN UFS_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN UFS_PEIM_MEM_POOL *Pool, + IN UINTN Size ); /** @@ -571,9 +571,9 @@ UfsPeimAllocateMem ( **/ VOID UfsPeimFreeMem ( - IN UFS_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN UFS_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ); /** @@ -605,11 +605,11 @@ IoMmuInit ( **/ EFI_STATUS IoMmuMap ( - IN EDKII_IOMMU_OPERATION Operation, - IN VOID *HostAddress, - IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -623,7 +623,7 @@ IoMmuMap ( **/ EFI_STATUS IoMmuUnmap ( - IN VOID *Mapping + IN VOID *Mapping ); /** @@ -666,9 +666,9 @@ IoMmuAllocateBuffer ( **/ EFI_STATUS IoMmuFreeBuffer ( - IN UINTN Pages, - IN VOID *HostAddress, - IN VOID *Mapping + IN UINTN Pages, + IN VOID *HostAddress, + IN VOID *Mapping ); /** diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c index a4e731640d..b7dd9b6acd 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.c @@ -18,25 +18,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UFS_PEIM_MEM_BLOCK * UfsPeimAllocMemBlock ( - IN UINTN Pages + IN UINTN Pages ) { - UFS_PEIM_MEM_BLOCK *Block; - VOID *BufHost; - VOID *Mapping; - EFI_PHYSICAL_ADDRESS MappedAddr; - EFI_STATUS Status; - VOID *TempPtr; + UFS_PEIM_MEM_BLOCK *Block; + VOID *BufHost; + VOID *Mapping; + EFI_PHYSICAL_ADDRESS MappedAddr; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Block = NULL; - Status = PeiServicesAllocatePool (sizeof(UFS_PEIM_MEM_BLOCK), &TempPtr); + Status = PeiServicesAllocatePool (sizeof (UFS_PEIM_MEM_BLOCK), &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof(UFS_PEIM_MEM_BLOCK)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (UFS_PEIM_MEM_BLOCK)); // // each bit in the bit array represents UFS_PEIM_MEM_UNIT @@ -44,18 +44,18 @@ UfsPeimAllocMemBlock ( // ASSERT (UFS_PEIM_MEM_UNIT * 8 <= EFI_PAGE_SIZE); - Block = (UFS_PEIM_MEM_BLOCK*)(UINTN)TempPtr; - Block->BufLen = EFI_PAGES_TO_SIZE (Pages); - Block->BitsLen = Block->BufLen / (UFS_PEIM_MEM_UNIT * 8); + Block = (UFS_PEIM_MEM_BLOCK *)(UINTN)TempPtr; + Block->BufLen = EFI_PAGES_TO_SIZE (Pages); + Block->BitsLen = Block->BufLen / (UFS_PEIM_MEM_UNIT * 8); Status = PeiServicesAllocatePool (Block->BitsLen, &TempPtr); if (EFI_ERROR (Status)) { return NULL; } - ZeroMem ((VOID*)(UINTN)TempPtr, Block->BitsLen); + ZeroMem ((VOID *)(UINTN)TempPtr, Block->BitsLen); - Block->Bits = (UINT8*)(UINTN)TempPtr; + Block->Bits = (UINT8 *)(UINTN)TempPtr; Status = IoMmuAllocateBuffer ( Pages, @@ -67,10 +67,10 @@ UfsPeimAllocMemBlock ( return NULL; } - ZeroMem ((VOID*)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); + ZeroMem ((VOID *)(UINTN)BufHost, EFI_PAGES_TO_SIZE (Pages)); - Block->BufHost = (UINT8 *) (UINTN) BufHost; - Block->Buf = (UINT8 *) (UINTN) MappedAddr; + Block->BufHost = (UINT8 *)(UINTN)BufHost; + Block->Buf = (UINT8 *)(UINTN)MappedAddr; Block->Mapping = Mapping; Block->Next = NULL; @@ -86,8 +86,8 @@ UfsPeimAllocMemBlock ( **/ VOID UfsPeimFreeMemBlock ( - IN UFS_PEIM_MEM_POOL *Pool, - IN UFS_PEIM_MEM_BLOCK *Block + IN UFS_PEIM_MEM_POOL *Pool, + IN UFS_PEIM_MEM_BLOCK *Block ) { ASSERT ((Pool != NULL) && (Block != NULL)); @@ -111,18 +111,18 @@ UfsPeimAllocMemFromBlock ( IN UINTN Units ) { - UINTN Byte; - UINT8 Bit; - UINTN StartByte; - UINT8 StartBit; - UINTN Available; - UINTN Count; + UINTN Byte; + UINT8 Bit; + UINTN StartByte; + UINT8 StartBit; + UINTN Available; + UINTN Count; ASSERT ((Block != 0) && (Units != 0)); - StartByte = 0; - StartBit = 0; - Available = 0; + StartByte = 0; + StartBit = 0; + Available = 0; for (Byte = 0, Bit = 0; Byte < Block->BitsLen;) { // @@ -138,13 +138,12 @@ UfsPeimAllocMemFromBlock ( } UFS_PEIM_NEXT_BIT (Byte, Bit); - } else { UFS_PEIM_NEXT_BIT (Byte, Bit); - Available = 0; - StartByte = Byte; - StartBit = Bit; + Available = 0; + StartByte = Byte; + StartBit = Bit; } } @@ -155,13 +154,13 @@ UfsPeimAllocMemFromBlock ( // // Mark the memory as allocated // - Byte = StartByte; - Bit = StartBit; + Byte = StartByte; + Bit = StartBit; for (Count = 0; Count < Units; Count++) { ASSERT (!UFS_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] | (UINT8) UFS_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] | (UINT8)UFS_PEIM_MEM_BIT (Bit)); UFS_PEIM_NEXT_BIT (Byte, Bit); } @@ -177,8 +176,8 @@ UfsPeimAllocMemFromBlock ( **/ VOID UfsPeimInsertMemBlockToPool ( - IN UFS_PEIM_MEM_BLOCK *Head, - IN UFS_PEIM_MEM_BLOCK *Block + IN UFS_PEIM_MEM_BLOCK *Head, + IN UFS_PEIM_MEM_BLOCK *Block ) { ASSERT ((Head != NULL) && (Block != NULL)); @@ -197,11 +196,10 @@ UfsPeimInsertMemBlockToPool ( **/ BOOLEAN UfsPeimIsMemBlockEmpty ( - IN UFS_PEIM_MEM_BLOCK *Block + IN UFS_PEIM_MEM_BLOCK *Block ) { - UINTN Index; - + UINTN Index; for (Index = 0; Index < Block->BitsLen; Index++) { if (Block->Bits[Index] != 0) { @@ -212,8 +210,6 @@ UfsPeimIsMemBlockEmpty ( return TRUE; } - - /** Initialize the memory management pool for the host controller. @@ -228,9 +224,9 @@ UfsPeimInitMemPool ( IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - UFS_PEIM_MEM_POOL *Pool; - EFI_STATUS Status; - VOID *TempPtr; + UFS_PEIM_MEM_POOL *Pool; + EFI_STATUS Status; + VOID *TempPtr; TempPtr = NULL; Pool = NULL; @@ -240,7 +236,7 @@ UfsPeimInitMemPool ( return EFI_OUT_OF_RESOURCES; } - ZeroMem ((VOID*)(UINTN)TempPtr, sizeof (UFS_PEIM_MEM_POOL)); + ZeroMem ((VOID *)(UINTN)TempPtr, sizeof (UFS_PEIM_MEM_POOL)); Pool = (UFS_PEIM_MEM_POOL *)((UINTN)TempPtr); @@ -265,10 +261,10 @@ UfsPeimInitMemPool ( **/ EFI_STATUS UfsPeimFreeMemPool ( - IN UFS_PEIM_MEM_POOL *Pool + IN UFS_PEIM_MEM_POOL *Pool ) { - UFS_PEIM_MEM_BLOCK *Block; + UFS_PEIM_MEM_BLOCK *Block; ASSERT (Pool->Head != NULL); @@ -296,16 +292,16 @@ UfsPeimFreeMemPool ( **/ VOID * UfsPeimAllocateMem ( - IN UFS_PEIM_MEM_POOL *Pool, - IN UINTN Size + IN UFS_PEIM_MEM_POOL *Pool, + IN UINTN Size ) { - UFS_PEIM_MEM_BLOCK *Head; - UFS_PEIM_MEM_BLOCK *Block; - UFS_PEIM_MEM_BLOCK *NewBlock; - VOID *Mem; - UINTN AllocSize; - UINTN Pages; + UFS_PEIM_MEM_BLOCK *Head; + UFS_PEIM_MEM_BLOCK *Block; + UFS_PEIM_MEM_BLOCK *NewBlock; + VOID *Mem; + UINTN AllocSize; + UINTN Pages; Mem = NULL; AllocSize = UFS_PEIM_MEM_ROUND (Size); @@ -368,22 +364,22 @@ UfsPeimAllocateMem ( **/ VOID UfsPeimFreeMem ( - IN UFS_PEIM_MEM_POOL *Pool, - IN VOID *Mem, - IN UINTN Size + IN UFS_PEIM_MEM_POOL *Pool, + IN VOID *Mem, + IN UINTN Size ) { - UFS_PEIM_MEM_BLOCK *Head; - UFS_PEIM_MEM_BLOCK *Block; - UINT8 *ToFree; - UINTN AllocSize; - UINTN Byte; - UINTN Bit; - UINTN Count; + UFS_PEIM_MEM_BLOCK *Head; + UFS_PEIM_MEM_BLOCK *Block; + UINT8 *ToFree; + UINTN AllocSize; + UINTN Byte; + UINTN Bit; + UINTN Count; Head = Pool->Head; AllocSize = UFS_PEIM_MEM_ROUND (Size); - ToFree = (UINT8 *) Mem; + ToFree = (UINT8 *)Mem; for (Block = Head; Block != NULL; Block = Block->Next) { // @@ -394,8 +390,8 @@ UfsPeimFreeMem ( // // compute the start byte and bit in the bit array // - Byte = ((ToFree - Block->Buf) / UFS_PEIM_MEM_UNIT) / 8; - Bit = ((ToFree - Block->Buf) / UFS_PEIM_MEM_UNIT) % 8; + Byte = ((ToFree - Block->Buf) / UFS_PEIM_MEM_UNIT) / 8; + Bit = ((ToFree - Block->Buf) / UFS_PEIM_MEM_UNIT) % 8; // // reset associated bits in bit array @@ -403,7 +399,7 @@ UfsPeimFreeMem ( for (Count = 0; Count < (AllocSize / UFS_PEIM_MEM_UNIT); Count++) { ASSERT (UFS_PEIM_MEM_BIT_IS_SET (Block->Bits[Byte], Bit)); - Block->Bits[Byte] = (UINT8) (Block->Bits[Byte] ^ UFS_PEIM_MEM_BIT (Bit)); + Block->Bits[Byte] = (UINT8)(Block->Bits[Byte] ^ UFS_PEIM_MEM_BIT (Bit)); UFS_PEIM_NEXT_BIT (Byte, Bit); } @@ -425,5 +421,5 @@ UfsPeimFreeMem ( UfsPeimFreeMemBlock (Pool, Block); } - return ; + return; } diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.h index b47d05a1a5..6bde93765d 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHcMem.h @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _UFS_PEIM_MEM_H_ #define _UFS_PEIM_MEM_H_ -#define UFS_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) +#define UFS_PEIM_MEM_BIT(a) ((UINTN)(1 << (a))) #define UFS_PEIM_MEM_BIT_IS_SET(Data, Bit) \ ((BOOLEAN)(((Data) & UFS_PEIM_MEM_BIT(Bit)) == UFS_PEIM_MEM_BIT(Bit))) @@ -17,23 +17,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef struct _UFS_PEIM_MEM_BLOCK UFS_PEIM_MEM_BLOCK; struct _UFS_PEIM_MEM_BLOCK { - UINT8 *Bits; // Bit array to record which unit is allocated - UINTN BitsLen; - UINT8 *Buf; - UINT8 *BufHost; - UINTN BufLen; // Memory size in bytes - VOID *Mapping; - UFS_PEIM_MEM_BLOCK *Next; + UINT8 *Bits; // Bit array to record which unit is allocated + UINTN BitsLen; + UINT8 *Buf; + UINT8 *BufHost; + UINTN BufLen; // Memory size in bytes + VOID *Mapping; + UFS_PEIM_MEM_BLOCK *Next; }; typedef struct _UFS_PEIM_MEM_POOL { - UFS_PEIM_MEM_BLOCK *Head; + UFS_PEIM_MEM_BLOCK *Head; } UFS_PEIM_MEM_POOL; // // Memory allocation unit, note that the value must meet UFS spec alignment requirement. // -#define UFS_PEIM_MEM_UNIT 128 +#define UFS_PEIM_MEM_UNIT 128 #define UFS_PEIM_MEM_UNIT_MASK (UFS_PEIM_MEM_UNIT - 1) #define UFS_PEIM_MEM_DEFAULT_PAGES 16 @@ -53,4 +53,3 @@ typedef struct _UFS_PEIM_MEM_POOL { } while (0) #endif - diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c index 1e47eb7eaa..2baa57593e 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.c @@ -22,15 +22,15 @@ EFI_STATUS EFIAPI UfsWaitMemSet ( - IN UINTN Address, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN UINTN Address, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT64 Delay; - BOOLEAN InfiniteWait; + UINT32 Value; + UINT64 Delay; + BOOLEAN InfiniteWait; if (Timeout == 0) { InfiniteWait = TRUE; @@ -56,7 +56,6 @@ UfsWaitMemSet ( MicroSecondDelay (1); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -71,8 +70,8 @@ UfsWaitMemSet ( **/ VOID DumpUicCmdExecResult ( - IN UINT8 UicOpcode, - IN UINT8 Result + IN UINT8 UicOpcode, + IN UINT8 Result ) { if (UicOpcode <= UfsUicDmePeerSet) { @@ -109,7 +108,7 @@ DumpUicCmdExecResult ( case 0x0A: DEBUG ((DEBUG_VERBOSE, "UIC configuration command fails - DME_FAILURE\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -120,7 +119,7 @@ DumpUicCmdExecResult ( case 0x01: DEBUG ((DEBUG_VERBOSE, "UIC control command fails - FAILURE\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -135,7 +134,7 @@ DumpUicCmdExecResult ( **/ VOID DumpQueryResponseResult ( - IN UINT8 Result + IN UINT8 Result ) { switch (Result) { @@ -169,7 +168,7 @@ DumpQueryResponseResult ( case 0xFF: DEBUG ((DEBUG_VERBOSE, "Query Response with General Failure\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -185,18 +184,18 @@ DumpQueryResponseResult ( **/ VOID SwapLittleEndianToBigEndian ( - IN OUT UINT8 *Buffer, - IN UINT32 BufferSize + IN OUT UINT8 *Buffer, + IN UINT32 BufferSize ) { - UINT32 Index; - UINT8 Temp; - UINT32 SwapCount; + UINT32 Index; + UINT8 Temp; + UINT32 SwapCount; SwapCount = BufferSize / 2; for (Index = 0; Index < SwapCount; Index++) { - Temp = Buffer[Index]; - Buffer[Index] = Buffer[BufferSize - 1 - Index]; + Temp = Buffer[Index]; + Buffer[Index] = Buffer[BufferSize - 1 - Index]; Buffer[BufferSize - 1 - Index] = Temp; } } @@ -215,32 +214,32 @@ SwapLittleEndianToBigEndian ( **/ VOID UfsFillTsfOfQueryReqUpiu ( - IN OUT UTP_UPIU_TSF *TsfBase, - IN UINT8 Opcode, - IN UINT8 DescId OPTIONAL, - IN UINT8 Index OPTIONAL, - IN UINT8 Selector OPTIONAL, - IN UINT16 Length OPTIONAL, - IN UINT32 Value OPTIONAL + IN OUT UTP_UPIU_TSF *TsfBase, + IN UINT8 Opcode, + IN UINT8 DescId OPTIONAL, + IN UINT8 Index OPTIONAL, + IN UINT8 Selector OPTIONAL, + IN UINT16 Length OPTIONAL, + IN UINT32 Value OPTIONAL ) { ASSERT (TsfBase != NULL); ASSERT (Opcode <= UtpQueryFuncOpcodeTogFlag); - TsfBase->Opcode = Opcode; + TsfBase->Opcode = Opcode; if (Opcode != UtpQueryFuncOpcodeNop) { TsfBase->DescId = DescId; TsfBase->Index = Index; TsfBase->Selector = Selector; if ((Opcode == UtpQueryFuncOpcodeRdDesc) || (Opcode == UtpQueryFuncOpcodeWrDesc)) { - SwapLittleEndianToBigEndian ((UINT8*)&Length, sizeof (Length)); + SwapLittleEndianToBigEndian ((UINT8 *)&Length, sizeof (Length)); TsfBase->Length = Length; } if (Opcode == UtpQueryFuncOpcodeWrAttr) { - SwapLittleEndianToBigEndian ((UINT8*)&Value, sizeof (Value)); - TsfBase->Value = Value; + SwapLittleEndianToBigEndian ((UINT8 *)&Value, sizeof (Value)); + TsfBase->Value = Value; } } } @@ -261,16 +260,16 @@ UfsFillTsfOfQueryReqUpiu ( **/ EFI_STATUS UfsInitCommandUpiu ( - IN OUT UTP_COMMAND_UPIU *Command, - IN UINT8 Lun, - IN UINT8 TaskTag, - IN UINT8 *Cdb, - IN UINT8 CdbLength, - IN UFS_DATA_DIRECTION DataDirection, - IN UINT32 ExpDataTranLen + IN OUT UTP_COMMAND_UPIU *Command, + IN UINT8 Lun, + IN UINT8 TaskTag, + IN UINT8 *Cdb, + IN UINT8 CdbLength, + IN UFS_DATA_DIRECTION DataDirection, + IN UINT32 ExpDataTranLen ) { - UINT8 Flags; + UINT8 Flags; ASSERT ((Command != NULL) && (Cdb != NULL)); @@ -293,7 +292,7 @@ UfsInitCommandUpiu ( Command->Lun = Lun; Command->TaskTag = TaskTag; Command->CmdSet = 0x00; - SwapLittleEndianToBigEndian ((UINT8*)&ExpDataTranLen, sizeof (ExpDataTranLen)); + SwapLittleEndianToBigEndian ((UINT8 *)&ExpDataTranLen, sizeof (ExpDataTranLen)); Command->ExpDataTranLen = ExpDataTranLen; CopyMem (Command->Cdb, Cdb, CdbLength); @@ -313,15 +312,15 @@ UfsInitCommandUpiu ( **/ EFI_STATUS UfsInitUtpPrdt ( - IN UTP_TR_PRD *Prdt, - IN VOID *Buffer, - IN UINT32 BufferSize + IN UTP_TR_PRD *Prdt, + IN VOID *Buffer, + IN UINT32 BufferSize ) { - UINT32 PrdtIndex; - UINT32 RemainingLen; - UINT8 *Remaining; - UINTN PrdtNumber; + UINT32 PrdtIndex; + UINT32 RemainingLen; + UINT8 *Remaining; + UINTN PrdtNumber; if ((BufferSize & (BIT0 | BIT1)) != 0) { BufferSize &= ~(BIT0 | BIT1); @@ -347,8 +346,8 @@ UfsInitUtpPrdt ( Prdt[PrdtIndex].DbAddr = (UINT32)RShiftU64 ((UINT64)(UINTN)Remaining, 2); Prdt[PrdtIndex].DbAddrU = (UINT32)RShiftU64 ((UINT64)(UINTN)Remaining, 32); - RemainingLen -= UFS_MAX_DATA_LEN_PER_PRD; - Remaining += UFS_MAX_DATA_LEN_PER_PRD; + RemainingLen -= UFS_MAX_DATA_LEN_PER_PRD; + Remaining += UFS_MAX_DATA_LEN_PER_PRD; } return EFI_SUCCESS; @@ -371,14 +370,14 @@ UfsInitUtpPrdt ( **/ EFI_STATUS UfsInitQueryRequestUpiu ( - IN OUT UTP_QUERY_REQ_UPIU *QueryReq, - IN UINT8 TaskTag, - IN UINT8 Opcode, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN UINTN DataSize OPTIONAL, - IN UINT8 *Data OPTIONAL + IN OUT UTP_QUERY_REQ_UPIU *QueryReq, + IN UINT8 TaskTag, + IN UINT8 Opcode, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN UINTN DataSize OPTIONAL, + IN UINT8 *Data OPTIONAL ) { ASSERT (QueryReq != NULL); @@ -392,7 +391,7 @@ UfsInitQueryRequestUpiu ( } if (Opcode == UtpQueryFuncOpcodeWrAttr) { - UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, 0, *(UINT32*)Data); + UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, 0, *(UINT32 *)Data); } else if ((Opcode == UtpQueryFuncOpcodeRdDesc) || (Opcode == UtpQueryFuncOpcodeWrDesc)) { UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, (UINT16)DataSize, 0); } else { @@ -402,7 +401,7 @@ UfsInitQueryRequestUpiu ( if (Opcode == UtpQueryFuncOpcodeWrDesc) { CopyMem (QueryReq + 1, Data, DataSize); - SwapLittleEndianToBigEndian ((UINT8*)&DataSize, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&DataSize, sizeof (UINT16)); QueryReq->DataSegLen = (UINT16)DataSize; } @@ -425,25 +424,25 @@ UfsInitQueryRequestUpiu ( **/ EFI_STATUS UfsCreateScsiCommandDesc ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 Lun, - IN UFS_SCSI_REQUEST_PACKET *Packet, - IN UTP_TRD *Trd, - OUT VOID **BufferMap + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 Lun, + IN UFS_SCSI_REQUEST_PACKET *Packet, + IN UTP_TRD *Trd, + OUT VOID **BufferMap ) { - UINT8 *CommandDesc; - UINTN TotalLen; - UINTN PrdtNumber; - VOID *Buffer; - UINT32 Length; - UTP_COMMAND_UPIU *CommandUpiu; - UTP_TR_PRD *PrdtBase; - UFS_DATA_DIRECTION DataDirection; - EFI_STATUS Status; - EDKII_IOMMU_OPERATION MapOp; - UINTN MapLength; - EFI_PHYSICAL_ADDRESS BufferPhyAddr; + UINT8 *CommandDesc; + UINTN TotalLen; + UINTN PrdtNumber; + VOID *Buffer; + UINT32 Length; + UTP_COMMAND_UPIU *CommandUpiu; + UTP_TR_PRD *PrdtBase; + UFS_DATA_DIRECTION DataDirection; + EFI_STATUS Status; + EDKII_IOMMU_OPERATION MapOp; + UINTN MapLength; + EFI_PHYSICAL_ADDRESS BufferPhyAddr; ASSERT ((Private != NULL) && (Packet != NULL) && (Trd != NULL)); @@ -455,8 +454,8 @@ UfsCreateScsiCommandDesc ( DataDirection = UfsDataIn; MapOp = EdkiiIoMmuOperationBusMasterWrite; } else { - Buffer = Packet->OutDataBuffer; - Length = Packet->OutTransferLength; + Buffer = Packet->OutDataBuffer; + Length = Packet->OutTransferLength; DataDirection = UfsDataOut; MapOp = EdkiiIoMmuOperationBusMasterRead; } @@ -465,7 +464,7 @@ UfsCreateScsiCommandDesc ( DataDirection = UfsNoData; } else { MapLength = Length; - Status = IoMmuMap (MapOp, Buffer, &MapLength, &BufferPhyAddr, BufferMap); + Status = IoMmuMap (MapOp, Buffer, &MapLength, &BufferPhyAddr, BufferMap); if (EFI_ERROR (Status) || (MapLength != Length)) { DEBUG ((DEBUG_ERROR, "UfsCreateScsiCommandDesc: Fail to map data buffer.\n")); @@ -481,11 +480,11 @@ UfsCreateScsiCommandDesc ( return EFI_OUT_OF_RESOURCES; } - CommandUpiu = (UTP_COMMAND_UPIU*)CommandDesc; - PrdtBase = (UTP_TR_PRD*)(CommandDesc + ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU))); + CommandUpiu = (UTP_COMMAND_UPIU *)CommandDesc; + PrdtBase = (UTP_TR_PRD *)(CommandDesc + ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU))); UfsInitCommandUpiu (CommandUpiu, Lun, Private->TaskTag++, Packet->Cdb, Packet->CdbLength, DataDirection, Length); - UfsInitUtpPrdt (PrdtBase, (VOID*)(UINTN)BufferPhyAddr, Length); + UfsInitUtpPrdt (PrdtBase, (VOID *)(UINTN)BufferPhyAddr, Length); // // Fill UTP_TRD associated fields @@ -525,13 +524,13 @@ UfsCreateDMCommandDesc ( IN UTP_TRD *Trd ) { - UINT8 *CommandDesc; - UINTN TotalLen; - UTP_QUERY_REQ_UPIU *QueryReqUpiu; - UINT8 Opcode; - UINT32 DataSize; - UINT8 *Data; - UINT8 DataDirection; + UINT8 *CommandDesc; + UINTN TotalLen; + UTP_QUERY_REQ_UPIU *QueryReqUpiu; + UINT8 Opcode; + UINT32 DataSize; + UINT8 *Data; + UINT8 DataDirection; ASSERT ((Private != NULL) && (Packet != NULL) && (Trd != NULL)); @@ -552,13 +551,15 @@ UfsCreateDMCommandDesc ( Data = NULL; } - if (((Opcode != UtpQueryFuncOpcodeSetFlag) && (Opcode != UtpQueryFuncOpcodeClrFlag) && (Opcode != UtpQueryFuncOpcodeTogFlag)) - && ((DataSize == 0) || (Data == NULL))) { + if ( ((Opcode != UtpQueryFuncOpcodeSetFlag) && (Opcode != UtpQueryFuncOpcodeClrFlag) && (Opcode != UtpQueryFuncOpcodeTogFlag)) + && ((DataSize == 0) || (Data == NULL))) + { return EFI_INVALID_PARAMETER; } - if (((Opcode == UtpQueryFuncOpcodeSetFlag) || (Opcode == UtpQueryFuncOpcodeClrFlag) || (Opcode == UtpQueryFuncOpcodeTogFlag)) - && ((DataSize != 0) || (Data != NULL))) { + if ( ((Opcode == UtpQueryFuncOpcodeSetFlag) || (Opcode == UtpQueryFuncOpcodeClrFlag) || (Opcode == UtpQueryFuncOpcodeTogFlag)) + && ((DataSize != 0) || (Data != NULL))) + { return EFI_INVALID_PARAMETER; } @@ -580,7 +581,7 @@ UfsCreateDMCommandDesc ( // // Initialize UTP QUERY REQUEST UPIU // - QueryReqUpiu = (UTP_QUERY_REQ_UPIU*)CommandDesc; + QueryReqUpiu = (UTP_QUERY_REQ_UPIU *)CommandDesc; UfsInitQueryRequestUpiu ( QueryReqUpiu, Private->TaskTag++, @@ -603,11 +604,11 @@ UfsCreateDMCommandDesc ( Trd->UcdBa = (UINT32)RShiftU64 ((UINT64)(UINTN)QueryReqUpiu, 7); Trd->UcdBaU = (UINT32)RShiftU64 ((UINT64)(UINTN)QueryReqUpiu, 32); if (Opcode == UtpQueryFuncOpcodeWrDesc) { - Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)), sizeof (UINT32)); - Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); + Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)), sizeof (UINT32)); + Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); } else { - Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); - Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)), sizeof (UINT32)); + Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); + Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)), sizeof (UINT32)); } return EFI_SUCCESS; @@ -626,13 +627,13 @@ UfsCreateDMCommandDesc ( **/ EFI_STATUS UfsCreateNopCommandDesc ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UTP_TRD *Trd + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UTP_TRD *Trd ) { - UINT8 *CommandDesc; - UINTN TotalLen; - UTP_NOP_OUT_UPIU *NopOutUpiu; + UINT8 *CommandDesc; + UINTN TotalLen; + UTP_NOP_OUT_UPIU *NopOutUpiu; ASSERT ((Private != NULL) && (Trd != NULL)); @@ -642,7 +643,7 @@ UfsCreateNopCommandDesc ( return EFI_OUT_OF_RESOURCES; } - NopOutUpiu = (UTP_NOP_OUT_UPIU*)CommandDesc; + NopOutUpiu = (UTP_NOP_OUT_UPIU *)CommandDesc; NopOutUpiu->TaskTag = Private->TaskTag++; @@ -673,8 +674,8 @@ UfsCreateNopCommandDesc ( **/ EFI_STATUS UfsFindAvailableSlotInTrl ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - OUT UINT8 *Slot + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + OUT UINT8 *Slot ) { ASSERT ((Private != NULL) && (Slot != NULL)); @@ -688,8 +689,6 @@ UfsFindAvailableSlotInTrl ( return EFI_SUCCESS; } - - /** Start specified slot in transfer list of a UFS device. @@ -699,13 +698,13 @@ UfsFindAvailableSlotInTrl ( **/ VOID UfsStartExecCmd ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - UINTN UfsHcBase; - UINTN Address; - UINT32 Data; + UINTN UfsHcBase; + UINTN Address; + UINT32 Data; UfsHcBase = Private->UfsHcBase; @@ -728,13 +727,13 @@ UfsStartExecCmd ( **/ VOID UfsStopExecCmd ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 Slot + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - UINTN UfsHcBase; - UINTN Address; - UINT32 Data; + UINTN UfsHcBase; + UINTN Address; + UINT32 Data; UfsHcBase = Private->UfsHcBase; @@ -765,42 +764,43 @@ UfsStopExecCmd ( **/ EFI_STATUS UfsRwDeviceDesc ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT VOID *Descriptor, - IN UINT32 DescSize + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT VOID *Descriptor, + IN UINT32 DescSize ) { - EFI_STATUS Status; - UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; - UINT8 Slot; - UTP_TRD *Trd; - UINTN Address; - UTP_QUERY_RESP_UPIU *QueryResp; - UINT8 *CmdDescBase; - UINT32 CmdDescSize; - UINT16 ReturnDataSize; + EFI_STATUS Status; + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + UINT8 Slot; + UTP_TRD *Trd; + UINTN Address; + UTP_QUERY_RESP_UPIU *QueryResp; + UINT8 *CmdDescBase; + UINT32 CmdDescSize; + UINT16 ReturnDataSize; ZeroMem (&Packet, sizeof (UFS_DEVICE_MANAGEMENT_REQUEST_PACKET)); if (Read) { - Packet.DataDirection = UfsDataIn; - Packet.InDataBuffer = Descriptor; - Packet.InTransferLength = DescSize; - Packet.Opcode = UtpQueryFuncOpcodeRdDesc; + Packet.DataDirection = UfsDataIn; + Packet.InDataBuffer = Descriptor; + Packet.InTransferLength = DescSize; + Packet.Opcode = UtpQueryFuncOpcodeRdDesc; } else { Packet.DataDirection = UfsDataOut; Packet.OutDataBuffer = Descriptor; Packet.OutTransferLength = DescSize; Packet.Opcode = UtpQueryFuncOpcodeWrDesc; } - Packet.DescId = DescId; - Packet.Index = Index; - Packet.Selector = Selector; - Packet.Timeout = UFS_TIMEOUT; + + Packet.DescId = DescId; + Packet.Index = Index; + Packet.Selector = Selector; + Packet.Timeout = UFS_TIMEOUT; // // Find out which slot of transfer request list is available. @@ -810,7 +810,7 @@ UfsRwDeviceDesc ( return Status; } - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; // // Fill transfer request descriptor to this slot. // @@ -823,7 +823,7 @@ UfsRwDeviceDesc ( // Check the transfer request result. // CmdDescBase = (UINT8 *)(UINTN)(LShiftU64 ((UINT64)Trd->UcdBaU, 32) | LShiftU64 ((UINT64)Trd->UcdBa, 7)); - QueryResp = (UTP_QUERY_RESP_UPIU*)(CmdDescBase + Trd->RuO * sizeof (UINT32)); + QueryResp = (UTP_QUERY_RESP_UPIU *)(CmdDescBase + Trd->RuO * sizeof (UINT32)); CmdDescSize = Trd->RuO * sizeof (UINT32) + Trd->RuL * sizeof (UINT32); // @@ -835,7 +835,7 @@ UfsRwDeviceDesc ( // Wait for the completion of the transfer request. // Address = Private->UfsHcBase + UFS_HC_UTRLDBR_OFFSET; - Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet.Timeout); + Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet.Timeout); if (EFI_ERROR (Status)) { goto Exit; } @@ -848,7 +848,7 @@ UfsRwDeviceDesc ( if (Trd->Ocs == 0) { ReturnDataSize = QueryResp->Tsf.Length; - SwapLittleEndianToBigEndian ((UINT8*)&ReturnDataSize, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnDataSize, sizeof (UINT16)); if (Read) { // @@ -875,8 +875,6 @@ Exit: return Status; } - - /** Read or write specified flag of a UFS device. @@ -892,20 +890,20 @@ Exit: **/ EFI_STATUS UfsRwFlags ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 FlagId, - IN OUT UINT8 *Value + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 FlagId, + IN OUT UINT8 *Value ) { - EFI_STATUS Status; - UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; - UINT8 Slot; - UTP_TRD *Trd; - UINTN Address; - UTP_QUERY_RESP_UPIU *QueryResp; - UINT8 *CmdDescBase; - UINT32 CmdDescSize; + EFI_STATUS Status; + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + UINT8 Slot; + UTP_TRD *Trd; + UINTN Address; + UTP_QUERY_RESP_UPIU *QueryResp; + UINT8 *CmdDescBase; + UINT32 CmdDescSize; if (Value == NULL) { return EFI_INVALID_PARAMETER; @@ -915,22 +913,23 @@ UfsRwFlags ( if (Read) { ASSERT (Value != NULL); - Packet.DataDirection = UfsDataIn; - Packet.Opcode = UtpQueryFuncOpcodeRdFlag; + Packet.DataDirection = UfsDataIn; + Packet.Opcode = UtpQueryFuncOpcodeRdFlag; } else { - Packet.DataDirection = UfsDataOut; + Packet.DataDirection = UfsDataOut; if (*Value == 1) { - Packet.Opcode = UtpQueryFuncOpcodeSetFlag; + Packet.Opcode = UtpQueryFuncOpcodeSetFlag; } else if (*Value == 0) { - Packet.Opcode = UtpQueryFuncOpcodeClrFlag; + Packet.Opcode = UtpQueryFuncOpcodeClrFlag; } else { return EFI_INVALID_PARAMETER; } } - Packet.DescId = FlagId; - Packet.Index = 0; - Packet.Selector = 0; - Packet.Timeout = UFS_TIMEOUT; + + Packet.DescId = FlagId; + Packet.Index = 0; + Packet.Selector = 0; + Packet.Timeout = UFS_TIMEOUT; // // Find out which slot of transfer request list is available. @@ -943,7 +942,7 @@ UfsRwFlags ( // // Fill transfer request descriptor to this slot. // - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; Status = UfsCreateDMCommandDesc (Private, &Packet, Trd); if (EFI_ERROR (Status)) { return Status; @@ -953,7 +952,7 @@ UfsRwFlags ( // Check the transfer request result. // CmdDescBase = (UINT8 *)(UINTN)(LShiftU64 ((UINT64)Trd->UcdBaU, 32) | LShiftU64 ((UINT64)Trd->UcdBa, 7)); - QueryResp = (UTP_QUERY_RESP_UPIU*)(CmdDescBase + Trd->RuO * sizeof (UINT32)); + QueryResp = (UTP_QUERY_RESP_UPIU *)(CmdDescBase + Trd->RuO * sizeof (UINT32)); CmdDescSize = Trd->RuO * sizeof (UINT32) + Trd->RuL * sizeof (UINT32); // @@ -965,7 +964,7 @@ UfsRwFlags ( // Wait for the completion of the transfer request. // Address = Private->UfsHcBase + UFS_HC_UTRLDBR_OFFSET; - Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet.Timeout); + Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet.Timeout); if (EFI_ERROR (Status)) { goto Exit; } @@ -980,7 +979,7 @@ UfsRwFlags ( // // The 'FLAG VALUE' field is at byte offset 3 of QueryResp->Tsf.Value // - *Value = *((UINT8*)&(QueryResp->Tsf.Value) + 3); + *Value = *((UINT8 *)&(QueryResp->Tsf.Value) + 3); } else { Status = EFI_DEVICE_ERROR; } @@ -1005,12 +1004,12 @@ Exit: **/ EFI_STATUS UfsSetFlag ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 FlagId + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 FlagId ) { - EFI_STATUS Status; - UINT8 Value; + EFI_STATUS Status; + UINT8 Value; Value = 1; Status = UfsRwFlags (Private, FALSE, FlagId, &Value); @@ -1018,8 +1017,6 @@ UfsSetFlag ( return Status; } - - /** Sends NOP IN cmd to a UFS device for initialization process request. For more details, please refer to UFS 2.0 spec Figure 13.3. @@ -1035,16 +1032,16 @@ UfsSetFlag ( **/ EFI_STATUS UfsExecNopCmds ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINT8 Slot; - UTP_TRD *Trd; - UTP_NOP_IN_UPIU *NopInUpiu; - UINT8 *CmdDescBase; - UINT32 CmdDescSize; - UINTN Address; + EFI_STATUS Status; + UINT8 Slot; + UTP_TRD *Trd; + UTP_NOP_IN_UPIU *NopInUpiu; + UINT8 *CmdDescBase; + UINT32 CmdDescSize; + UINTN Address; // // Find out which slot of transfer request list is available. @@ -1054,7 +1051,7 @@ UfsExecNopCmds ( return Status; } - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; Status = UfsCreateNopCommandDesc (Private, Trd); if (EFI_ERROR (Status)) { return Status; @@ -1064,7 +1061,7 @@ UfsExecNopCmds ( // Check the transfer request result. // CmdDescBase = (UINT8 *)(UINTN)(LShiftU64 ((UINT64)Trd->UcdBaU, 32) | LShiftU64 ((UINT64)Trd->UcdBa, 7)); - NopInUpiu = (UTP_NOP_IN_UPIU*)(CmdDescBase + Trd->RuO * sizeof (UINT32)); + NopInUpiu = (UTP_NOP_IN_UPIU *)(CmdDescBase + Trd->RuO * sizeof (UINT32)); CmdDescSize = Trd->RuO * sizeof (UINT32) + Trd->RuL * sizeof (UINT32); // @@ -1076,7 +1073,7 @@ UfsExecNopCmds ( // Wait for the completion of the transfer request. // Address = Private->UfsHcBase + UFS_HC_UTRLDBR_OFFSET; - Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, UFS_TIMEOUT); + Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, UFS_TIMEOUT); if (EFI_ERROR (Status)) { goto Exit; } @@ -1115,21 +1112,21 @@ Exit: **/ EFI_STATUS UfsExecScsiCmds ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 Lun, - IN OUT UFS_SCSI_REQUEST_PACKET *Packet + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 Lun, + IN OUT UFS_SCSI_REQUEST_PACKET *Packet ) { - EFI_STATUS Status; - UINT8 Slot; - UTP_TRD *Trd; - UINTN Address; - UINT8 *CmdDescBase; - UINT32 CmdDescSize; - UTP_RESPONSE_UPIU *Response; - UINT16 SenseDataLen; - UINT32 ResTranCount; - VOID *PacketBufferMap; + EFI_STATUS Status; + UINT8 Slot; + UTP_TRD *Trd; + UINTN Address; + UINT8 *CmdDescBase; + UINT32 CmdDescSize; + UTP_RESPONSE_UPIU *Response; + UINT16 SenseDataLen; + UINT32 ResTranCount; + VOID *PacketBufferMap; // // Find out which slot of transfer request list is available. @@ -1139,7 +1136,7 @@ UfsExecScsiCmds ( return Status; } - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; PacketBufferMap = NULL; // @@ -1150,7 +1147,7 @@ UfsExecScsiCmds ( return Status; } - CmdDescBase = (UINT8*)(UINTN)(LShiftU64 ((UINT64)Trd->UcdBaU, 32) | LShiftU64 ((UINT64)Trd->UcdBa, 7)); + CmdDescBase = (UINT8 *)(UINTN)(LShiftU64 ((UINT64)Trd->UcdBaU, 32) | LShiftU64 ((UINT64)Trd->UcdBa, 7)); CmdDescSize = Trd->PrdtO * sizeof (UINT32) + Trd->PrdtL * sizeof (UTP_TR_PRD); // @@ -1162,7 +1159,7 @@ UfsExecScsiCmds ( // Wait for the completion of the transfer request. // Address = Private->UfsHcBase + UFS_HC_UTRLDBR_OFFSET; - Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet->Timeout); + Status = UfsWaitMemSet (Address, BIT0 << Slot, 0, Packet->Timeout); if (EFI_ERROR (Status)) { goto Exit; } @@ -1170,9 +1167,9 @@ UfsExecScsiCmds ( // // Get sense data if exists // - Response = (UTP_RESPONSE_UPIU*)(CmdDescBase + Trd->RuO * sizeof (UINT32)); + Response = (UTP_RESPONSE_UPIU *)(CmdDescBase + Trd->RuO * sizeof (UINT32)); SenseDataLen = Response->SenseDataLen; - SwapLittleEndianToBigEndian ((UINT8*)&SenseDataLen, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&SenseDataLen, sizeof (UINT16)); if ((Packet->SenseDataLength != 0) && (Packet->SenseData != NULL)) { // @@ -1199,13 +1196,13 @@ UfsExecScsiCmds ( if (Packet->DataDirection == UfsDataIn) { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->InTransferLength -= ResTranCount; } } else if (Packet->DataDirection == UfsDataOut) { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->OutTransferLength -= ResTranCount; } } @@ -1217,13 +1214,13 @@ Exit: if (PacketBufferMap != NULL) { IoMmuUnmap (PacketBufferMap); } + UfsStopExecCmd (Private, Slot); UfsPeimFreeMem (Private->Pool, CmdDescBase, CmdDescSize); return Status; } - /** Sent UIC DME_LINKSTARTUP command to start the link startup procedure. @@ -1240,11 +1237,11 @@ Exit: **/ EFI_STATUS UfsExecUicCommands ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private, - IN UINT8 UicOpcode, - IN UINT32 Arg1, - IN UINT32 Arg2, - IN UINT32 Arg3 + IN UFS_PEIM_HC_PRIVATE_DATA *Private, + IN UINT8 UicOpcode, + IN UINT32 Arg1, + IN UINT32 Arg2, + IN UINT32 Arg3 ) { EFI_STATUS Status; @@ -1280,7 +1277,7 @@ UfsExecUicCommands ( // Host software shall only set the UICCMD if HCS.UCRDY is set to 1. // Address = Private->UfsHcBase + UFS_HC_STATUS_OFFSET; - Status = UfsWaitMemSet (Address, UFS_HC_HCS_UCRDY, UFS_HC_HCS_UCRDY, UFS_TIMEOUT); + Status = UfsWaitMemSet (Address, UFS_HC_HCS_UCRDY, UFS_HC_HCS_UCRDY, UFS_TIMEOUT); if (EFI_ERROR (Status)) { return Status; } @@ -1303,9 +1300,9 @@ UfsExecUicCommands ( Address = UfsHcBase + UFS_HC_UCMD_ARG2_OFFSET; Data = MmioRead32 (Address); if ((Data & 0xFF) != 0) { - DEBUG_CODE_BEGIN(); - DumpUicCmdExecResult (UicOpcode, (UINT8)(Data & 0xFF)); - DEBUG_CODE_END(); + DEBUG_CODE_BEGIN (); + DumpUicCmdExecResult (UicOpcode, (UINT8)(Data & 0xFF)); + DEBUG_CODE_END (); return EFI_DEVICE_ERROR; } } @@ -1321,6 +1318,7 @@ UfsExecUicCommands ( if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } + return EFI_NOT_FOUND; } @@ -1340,12 +1338,12 @@ UfsExecUicCommands ( **/ EFI_STATUS UfsEnableHostController ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINTN Address; - UINT32 Data; + EFI_STATUS Status; + UINTN Address; + UINT32 Data; // // UFS 2.0 spec section 7.1.1 - Host Controller Initialization @@ -1395,11 +1393,11 @@ UfsEnableHostController ( **/ EFI_STATUS UfsDeviceDetection ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - UINTN Retry; - EFI_STATUS Status; + UINTN Retry; + EFI_STATUS Status; // // Start UFS device detection. @@ -1436,28 +1434,28 @@ UfsDeviceDetection ( **/ EFI_STATUS UfsInitTaskManagementRequestList ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - UINTN Address; - UINT32 Data; - UINT8 Nutmrs; - VOID *CmdDescHost; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - VOID *CmdDescMapping; - EFI_STATUS Status; + UINTN Address; + UINT32 Data; + UINT8 Nutmrs; + VOID *CmdDescHost; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + VOID *CmdDescMapping; + EFI_STATUS Status; // // Initial h/w and s/w context for future operations. // - Address = Private->UfsHcBase + UFS_HC_CAP_OFFSET; - Data = MmioRead32 (Address); + Address = Private->UfsHcBase + UFS_HC_CAP_OFFSET; + Data = MmioRead32 (Address); Private->Capabilities = Data; // // Allocate and initialize UTP Task Management Request List. // - Nutmrs = (UINT8) (RShiftU64 ((Private->Capabilities & UFS_HC_CAP_NUTMRS), 16) + 1); + Nutmrs = (UINT8)(RShiftU64 ((Private->Capabilities & UFS_HC_CAP_NUTMRS), 16) + 1); Status = IoMmuAllocateBuffer ( EFI_SIZE_TO_PAGES (Nutmrs * sizeof (UTP_TMRD)), &CmdDescHost, @@ -1478,7 +1476,7 @@ UfsInitTaskManagementRequestList ( MmioWrite32 (Address, (UINT32)(UINTN)CmdDescPhyAddr); Address = Private->UfsHcBase + UFS_HC_UTMRLBAU_OFFSET; MmioWrite32 (Address, (UINT32)RShiftU64 ((UINT64)CmdDescPhyAddr, 32)); - Private->UtpTmrlBase = (VOID*)(UINTN)CmdDescHost; + Private->UtpTmrlBase = (VOID *)(UINTN)CmdDescHost; Private->Nutmrs = Nutmrs; Private->TmrlMapping = CmdDescMapping; @@ -1503,22 +1501,22 @@ UfsInitTaskManagementRequestList ( **/ EFI_STATUS UfsInitTransferRequestList ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - UINTN Address; - UINT32 Data; - UINT8 Nutrs; - VOID *CmdDescHost; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - VOID *CmdDescMapping; - EFI_STATUS Status; + UINTN Address; + UINT32 Data; + UINT8 Nutrs; + VOID *CmdDescHost; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + VOID *CmdDescMapping; + EFI_STATUS Status; // // Initial h/w and s/w context for future operations. // - Address = Private->UfsHcBase + UFS_HC_CAP_OFFSET; - Data = MmioRead32 (Address); + Address = Private->UfsHcBase + UFS_HC_CAP_OFFSET; + Data = MmioRead32 (Address); Private->Capabilities = Data; // @@ -1545,7 +1543,7 @@ UfsInitTransferRequestList ( MmioWrite32 (Address, (UINT32)(UINTN)CmdDescPhyAddr); Address = Private->UfsHcBase + UFS_HC_UTRLBAU_OFFSET; MmioWrite32 (Address, (UINT32)RShiftU64 ((UINT64)CmdDescPhyAddr, 32)); - Private->UtpTrlBase = (VOID*)(UINTN)CmdDescHost; + Private->UtpTrlBase = (VOID *)(UINTN)CmdDescHost; Private->Nutrs = Nutrs; Private->TrlMapping = CmdDescMapping; @@ -1570,10 +1568,10 @@ UfsInitTransferRequestList ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UfsEnableHostController (Private); if (EFI_ERROR (Status)) { @@ -1624,12 +1622,12 @@ UfsControllerInit ( **/ EFI_STATUS UfsControllerStop ( - IN UFS_PEIM_HC_PRIVATE_DATA *Private + IN UFS_PEIM_HC_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINTN Address; - UINT32 Data; + EFI_STATUS Status; + UINTN Address; + UINT32 Data; // // Enable the UTP Task Management Request List by setting the UTP Task Management diff --git a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.h b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.h index e8b5aae702..f19b6535a1 100644 --- a/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.h +++ b/MdeModulePkg/Bus/Ufs/UfsBlockIoPei/UfsHci.h @@ -13,62 +13,62 @@ // // Host Capabilities Register Offsets // -#define UFS_HC_CAP_OFFSET 0x0000 // Controller Capabilities -#define UFS_HC_VER_OFFSET 0x0008 // Version -#define UFS_HC_DDID_OFFSET 0x0010 // Device ID and Device Class -#define UFS_HC_PMID_OFFSET 0x0014 // Product ID and Manufacturer ID -#define UFS_HC_AHIT_OFFSET 0x0018 // Auto-Hibernate Idle Timer +#define UFS_HC_CAP_OFFSET 0x0000 // Controller Capabilities +#define UFS_HC_VER_OFFSET 0x0008 // Version +#define UFS_HC_DDID_OFFSET 0x0010 // Device ID and Device Class +#define UFS_HC_PMID_OFFSET 0x0014 // Product ID and Manufacturer ID +#define UFS_HC_AHIT_OFFSET 0x0018 // Auto-Hibernate Idle Timer // // Operation and Runtime Register Offsets // -#define UFS_HC_IS_OFFSET 0x0020 // Interrupt Status -#define UFS_HC_IE_OFFSET 0x0024 // Interrupt Enable -#define UFS_HC_STATUS_OFFSET 0x0030 // Host Controller Status -#define UFS_HC_ENABLE_OFFSET 0x0034 // Host Controller Enable -#define UFS_HC_UECPA_OFFSET 0x0038 // Host UIC Error Code PHY Adapter Layer -#define UFS_HC_UECDL_OFFSET 0x003c // Host UIC Error Code Data Link Layer -#define UFS_HC_UECN_OFFSET 0x0040 // Host UIC Error Code Network Layer -#define UFS_HC_UECT_OFFSET 0x0044 // Host UIC Error Code Transport Layer -#define UFS_HC_UECDME_OFFSET 0x0048 // Host UIC Error Code DME -#define UFS_HC_UTRIACR_OFFSET 0x004c // UTP Transfer Request Interrupt Aggregation Control Register +#define UFS_HC_IS_OFFSET 0x0020 // Interrupt Status +#define UFS_HC_IE_OFFSET 0x0024 // Interrupt Enable +#define UFS_HC_STATUS_OFFSET 0x0030 // Host Controller Status +#define UFS_HC_ENABLE_OFFSET 0x0034 // Host Controller Enable +#define UFS_HC_UECPA_OFFSET 0x0038 // Host UIC Error Code PHY Adapter Layer +#define UFS_HC_UECDL_OFFSET 0x003c // Host UIC Error Code Data Link Layer +#define UFS_HC_UECN_OFFSET 0x0040 // Host UIC Error Code Network Layer +#define UFS_HC_UECT_OFFSET 0x0044 // Host UIC Error Code Transport Layer +#define UFS_HC_UECDME_OFFSET 0x0048 // Host UIC Error Code DME +#define UFS_HC_UTRIACR_OFFSET 0x004c // UTP Transfer Request Interrupt Aggregation Control Register // // UTP Transfer Register Offsets // -#define UFS_HC_UTRLBA_OFFSET 0x0050 // UTP Transfer Request List Base Address -#define UFS_HC_UTRLBAU_OFFSET 0x0054 // UTP Transfer Request List Base Address Upper 32-Bits -#define UFS_HC_UTRLDBR_OFFSET 0x0058 // UTP Transfer Request List Door Bell Register -#define UFS_HC_UTRLCLR_OFFSET 0x005c // UTP Transfer Request List CLear Register -#define UFS_HC_UTRLRSR_OFFSET 0x0060 // UTP Transfer Request Run-Stop Register +#define UFS_HC_UTRLBA_OFFSET 0x0050 // UTP Transfer Request List Base Address +#define UFS_HC_UTRLBAU_OFFSET 0x0054 // UTP Transfer Request List Base Address Upper 32-Bits +#define UFS_HC_UTRLDBR_OFFSET 0x0058 // UTP Transfer Request List Door Bell Register +#define UFS_HC_UTRLCLR_OFFSET 0x005c // UTP Transfer Request List CLear Register +#define UFS_HC_UTRLRSR_OFFSET 0x0060 // UTP Transfer Request Run-Stop Register // // UTP Task Management Register Offsets // -#define UFS_HC_UTMRLBA_OFFSET 0x0070 // UTP Task Management Request List Base Address -#define UFS_HC_UTMRLBAU_OFFSET 0x0074 // UTP Task Management Request List Base Address Upper 32-Bits -#define UFS_HC_UTMRLDBR_OFFSET 0x0078 // UTP Task Management Request List Door Bell Register -#define UFS_HC_UTMRLCLR_OFFSET 0x007c // UTP Task Management Request List CLear Register -#define UFS_HC_UTMRLRSR_OFFSET 0x0080 // UTP Task Management Run-Stop Register +#define UFS_HC_UTMRLBA_OFFSET 0x0070 // UTP Task Management Request List Base Address +#define UFS_HC_UTMRLBAU_OFFSET 0x0074 // UTP Task Management Request List Base Address Upper 32-Bits +#define UFS_HC_UTMRLDBR_OFFSET 0x0078 // UTP Task Management Request List Door Bell Register +#define UFS_HC_UTMRLCLR_OFFSET 0x007c // UTP Task Management Request List CLear Register +#define UFS_HC_UTMRLRSR_OFFSET 0x0080 // UTP Task Management Run-Stop Register // // UIC Command Register Offsets // -#define UFS_HC_UIC_CMD_OFFSET 0x0090 // UIC Command Register -#define UFS_HC_UCMD_ARG1_OFFSET 0x0094 // UIC Command Argument 1 -#define UFS_HC_UCMD_ARG2_OFFSET 0x0098 // UIC Command Argument 2 -#define UFS_HC_UCMD_ARG3_OFFSET 0x009c // UIC Command Argument 3 +#define UFS_HC_UIC_CMD_OFFSET 0x0090 // UIC Command Register +#define UFS_HC_UCMD_ARG1_OFFSET 0x0094 // UIC Command Argument 1 +#define UFS_HC_UCMD_ARG2_OFFSET 0x0098 // UIC Command Argument 2 +#define UFS_HC_UCMD_ARG3_OFFSET 0x009c // UIC Command Argument 3 // // UMA Register Offsets // -#define UFS_HC_UMA_OFFSET 0x00b0 // Reserved for Unified Memory Extension +#define UFS_HC_UMA_OFFSET 0x00b0 // Reserved for Unified Memory Extension -#define UFS_HC_HCE_EN BIT0 -#define UFS_HC_HCS_DP BIT0 -#define UFS_HC_HCS_UCRDY BIT3 -#define UFS_HC_IS_ULSS BIT8 -#define UFS_HC_IS_UCCS BIT10 -#define UFS_HC_CAP_64ADDR BIT24 -#define UFS_HC_CAP_NUTMRS (BIT16 | BIT17 | BIT18) -#define UFS_HC_CAP_NUTRS (BIT0 | BIT1 | BIT2 | BIT3 | BIT4) -#define UFS_HC_UTMRLRSR BIT0 -#define UFS_HC_UTRLRSR BIT0 +#define UFS_HC_HCE_EN BIT0 +#define UFS_HC_HCS_DP BIT0 +#define UFS_HC_HCS_UCRDY BIT3 +#define UFS_HC_IS_ULSS BIT8 +#define UFS_HC_IS_UCCS BIT10 +#define UFS_HC_CAP_64ADDR BIT24 +#define UFS_HC_CAP_NUTMRS (BIT16 | BIT17 | BIT18) +#define UFS_HC_CAP_NUTRS (BIT0 | BIT1 | BIT2 | BIT3 | BIT4) +#define UFS_HC_UTMRLRSR BIT0 +#define UFS_HC_UTRLRSR BIT0 // // The initial value of the OCS field of UTP TRD or TMRD descriptor @@ -79,25 +79,25 @@ // // A maximum of length of 256KB is supported by PRDT entry // -#define UFS_MAX_DATA_LEN_PER_PRD 0x40000 +#define UFS_MAX_DATA_LEN_PER_PRD 0x40000 -#define UFS_STORAGE_COMMAND_TYPE 0x01 +#define UFS_STORAGE_COMMAND_TYPE 0x01 -#define UFS_REGULAR_COMMAND 0x00 -#define UFS_INTERRUPT_COMMAND 0x01 +#define UFS_REGULAR_COMMAND 0x00 +#define UFS_INTERRUPT_COMMAND 0x01 -#define UFS_LUN_0 0x00 -#define UFS_LUN_1 0x01 -#define UFS_LUN_2 0x02 -#define UFS_LUN_3 0x03 -#define UFS_LUN_4 0x04 -#define UFS_LUN_5 0x05 -#define UFS_LUN_6 0x06 -#define UFS_LUN_7 0x07 -#define UFS_WLUN_REPORT_LUNS 0x81 -#define UFS_WLUN_UFS_DEV 0xD0 -#define UFS_WLUN_BOOT 0xB0 -#define UFS_WLUN_RPMB 0xC4 +#define UFS_LUN_0 0x00 +#define UFS_LUN_1 0x01 +#define UFS_LUN_2 0x02 +#define UFS_LUN_3 0x03 +#define UFS_LUN_4 0x04 +#define UFS_LUN_5 0x05 +#define UFS_LUN_6 0x06 +#define UFS_LUN_7 0x07 +#define UFS_WLUN_REPORT_LUNS 0x81 +#define UFS_WLUN_UFS_DEV 0xD0 +#define UFS_WLUN_BOOT 0xB0 +#define UFS_WLUN_RPMB 0xC4 #pragma pack(1) @@ -105,227 +105,227 @@ // UFSHCI 2.0 Spec Section 5.2.1 Offset 00h: CAP - Controller Capabilities // typedef struct { - UINT8 Nutrs:4; // Number of UTP Transfer Request Slots - UINT8 Rsvd1:4; + UINT8 Nutrs : 4; // Number of UTP Transfer Request Slots + UINT8 Rsvd1 : 4; - UINT8 NoRtt; // Number of outstanding READY TO TRANSFER (RTT) requests supported + UINT8 NoRtt; // Number of outstanding READY TO TRANSFER (RTT) requests supported - UINT8 Nutmrs:3; // Number of UTP Task Management Request Slots - UINT8 Rsvd2:4; - UINT8 AutoHs:1; // Auto-Hibernation Support + UINT8 Nutmrs : 3; // Number of UTP Task Management Request Slots + UINT8 Rsvd2 : 4; + UINT8 AutoHs : 1; // Auto-Hibernation Support - UINT8 As64:1; // 64-bit addressing supported - UINT8 Oodds:1; // Out of order data delivery supported - UINT8 UicDmetms:1; // UIC DME_TEST_MODE command supported - UINT8 Ume:1; // Reserved for Unified Memory Extension - UINT8 Rsvd4:4; + UINT8 As64 : 1; // 64-bit addressing supported + UINT8 Oodds : 1; // Out of order data delivery supported + UINT8 UicDmetms : 1; // UIC DME_TEST_MODE command supported + UINT8 Ume : 1; // Reserved for Unified Memory Extension + UINT8 Rsvd4 : 4; } UFS_HC_CAP; // // UFSHCI 2.0 Spec Section 5.2.2 Offset 08h: VER - UFS Version // typedef struct { - UINT8 Vs:4; // Version Suffix - UINT8 Mnr:4; // Minor version number + UINT8 Vs : 4; // Version Suffix + UINT8 Mnr : 4; // Minor version number - UINT8 Mjr; // Major version number + UINT8 Mjr; // Major version number - UINT16 Rsvd1; + UINT16 Rsvd1; } UFS_HC_VER; // // UFSHCI 2.0 Spec Section 5.2.3 Offset 10h: HCPID - Host Controller Product ID // -#define UFS_HC_PID UINT32 +#define UFS_HC_PID UINT32 // // UFSHCI 2.0 Spec Section 5.2.4 Offset 14h: HCMID - Host Controller Manufacturer ID // -#define UFS_HC_MID UINT32 +#define UFS_HC_MID UINT32 // // UFSHCI 2.0 Spec Section 5.2.5 Offset 18h: AHIT - Auto-Hibernate Idle Timer // typedef struct { - UINT32 Ahitv:10; // Auto-Hibernate Idle Timer Value - UINT32 Ts:3; // Timer scale - UINT32 Rsvd1:19; + UINT32 Ahitv : 10; // Auto-Hibernate Idle Timer Value + UINT32 Ts : 3; // Timer scale + UINT32 Rsvd1 : 19; } UFS_HC_AHIT; // // UFSHCI 2.0 Spec Section 5.3.1 Offset 20h: IS - Interrupt Status // typedef struct { - UINT16 Utrcs:1; // UTP Transfer Request Completion Status - UINT16 Udepri:1; // UIC DME_ENDPOINT_RESET Indication - UINT16 Ue:1; // UIC Error - UINT16 Utms:1; // UIC Test Mode Status - - UINT16 Upms:1; // UIC Power Mode Status - UINT16 Uhxs:1; // UIC Hibernate Exit Status - UINT16 Uhes:1; // UIC Hibernate Enter Status - UINT16 Ulls:1; // UIC Link Lost Status - - UINT16 Ulss:1; // UIC Link Startup Status - UINT16 Utmrcs:1; // UTP Task Management Request Completion Status - UINT16 Uccs:1; // UIC Command Completion Status - UINT16 Dfes:1; // Device Fatal Error Status - - UINT16 Utpes:1; // UTP Error Status - UINT16 Rsvd1:3; - - UINT16 Hcfes:1; // Host Controller Fatal Error Status - UINT16 Sbfes:1; // System Bus Fatal Error Status - UINT16 Rsvd2:14; + UINT16 Utrcs : 1; // UTP Transfer Request Completion Status + UINT16 Udepri : 1; // UIC DME_ENDPOINT_RESET Indication + UINT16 Ue : 1; // UIC Error + UINT16 Utms : 1; // UIC Test Mode Status + + UINT16 Upms : 1; // UIC Power Mode Status + UINT16 Uhxs : 1; // UIC Hibernate Exit Status + UINT16 Uhes : 1; // UIC Hibernate Enter Status + UINT16 Ulls : 1; // UIC Link Lost Status + + UINT16 Ulss : 1; // UIC Link Startup Status + UINT16 Utmrcs : 1; // UTP Task Management Request Completion Status + UINT16 Uccs : 1; // UIC Command Completion Status + UINT16 Dfes : 1; // Device Fatal Error Status + + UINT16 Utpes : 1; // UTP Error Status + UINT16 Rsvd1 : 3; + + UINT16 Hcfes : 1; // Host Controller Fatal Error Status + UINT16 Sbfes : 1; // System Bus Fatal Error Status + UINT16 Rsvd2 : 14; } UFS_HC_IS; // // UFSHCI 2.0 Spec Section 5.3.2 Offset 24h: IE - Interrupt Enable // typedef struct { - UINT16 Utrce:1; // UTP Transfer Request Completion Enable - UINT16 Udeprie:1; // UIC DME_ENDPOINT_RESET Enable - UINT16 Uee:1; // UIC Error Enable - UINT16 Utmse:1; // UIC Test Mode Status Enable - - UINT16 Upmse:1; // UIC Power Mode Status Enable - UINT16 Uhxse:1; // UIC Hibernate Exit Status Enable - UINT16 Uhese:1; // UIC Hibernate Enter Status Enable - UINT16 Ullse:1; // UIC Link Lost Status Enable - - UINT16 Ulsse:1; // UIC Link Startup Status Enable - UINT16 Utmrce:1; // UTP Task Management Request Completion Enable - UINT16 Ucce:1; // UIC Command Completion Enable - UINT16 Dfee:1; // Device Fatal Error Enable - - UINT16 Utpee:1; // UTP Error Enable - UINT16 Rsvd1:3; - - UINT16 Hcfee:1; // Host Controller Fatal Error Enable - UINT16 Sbfee:1; // System Bus Fatal Error Enable - UINT16 Rsvd2:14; + UINT16 Utrce : 1; // UTP Transfer Request Completion Enable + UINT16 Udeprie : 1; // UIC DME_ENDPOINT_RESET Enable + UINT16 Uee : 1; // UIC Error Enable + UINT16 Utmse : 1; // UIC Test Mode Status Enable + + UINT16 Upmse : 1; // UIC Power Mode Status Enable + UINT16 Uhxse : 1; // UIC Hibernate Exit Status Enable + UINT16 Uhese : 1; // UIC Hibernate Enter Status Enable + UINT16 Ullse : 1; // UIC Link Lost Status Enable + + UINT16 Ulsse : 1; // UIC Link Startup Status Enable + UINT16 Utmrce : 1; // UTP Task Management Request Completion Enable + UINT16 Ucce : 1; // UIC Command Completion Enable + UINT16 Dfee : 1; // Device Fatal Error Enable + + UINT16 Utpee : 1; // UTP Error Enable + UINT16 Rsvd1 : 3; + + UINT16 Hcfee : 1; // Host Controller Fatal Error Enable + UINT16 Sbfee : 1; // System Bus Fatal Error Enable + UINT16 Rsvd2 : 14; } UFS_HC_IE; // // UFSHCI 2.0 Spec Section 5.3.3 Offset 30h: HCS - Host Controller Status // typedef struct { - UINT8 Dp:1; // Device Present - UINT8 UtrlRdy:1; // UTP Transfer Request List Ready - UINT8 UtmrlRdy:1; // UTP Task Management Request List Ready - UINT8 UcRdy:1; // UIC COMMAND Ready - UINT8 Rsvd1:4; - - UINT8 Upmcrs:3; // UIC Power Mode Change Request Status - UINT8 Rsvd2:1; // UIC Hibernate Exit Status Enable - UINT8 Utpec:4; // UTP Error Code - - UINT8 TtagUtpE; // Task Tag of UTP error - UINT8 TlunUtpE; // Target LUN of UTP error + UINT8 Dp : 1; // Device Present + UINT8 UtrlRdy : 1; // UTP Transfer Request List Ready + UINT8 UtmrlRdy : 1; // UTP Task Management Request List Ready + UINT8 UcRdy : 1; // UIC COMMAND Ready + UINT8 Rsvd1 : 4; + + UINT8 Upmcrs : 3; // UIC Power Mode Change Request Status + UINT8 Rsvd2 : 1; // UIC Hibernate Exit Status Enable + UINT8 Utpec : 4; // UTP Error Code + + UINT8 TtagUtpE; // Task Tag of UTP error + UINT8 TlunUtpE; // Target LUN of UTP error } UFS_HC_STATUS; // // UFSHCI 2.0 Spec Section 5.3.4 Offset 34h: HCE - Host Controller Enable // typedef struct { - UINT32 Hce:1; // Host Controller Enable - UINT32 Rsvd1:31; + UINT32 Hce : 1; // Host Controller Enable + UINT32 Rsvd1 : 31; } UFS_HC_ENABLE; // // UFSHCI 2.0 Spec Section 5.3.5 Offset 38h: UECPA - Host UIC Error Code PHY Adapter Layer // typedef struct { - UINT32 Ec:5; // UIC PHY Adapter Layer Error Code - UINT32 Rsvd1:26; - UINT32 Err:1; // UIC PHY Adapter Layer Error + UINT32 Ec : 5; // UIC PHY Adapter Layer Error Code + UINT32 Rsvd1 : 26; + UINT32 Err : 1; // UIC PHY Adapter Layer Error } UFS_HC_UECPA; // // UFSHCI 2.0 Spec Section 5.3.6 Offset 3ch: UECDL - Host UIC Error Code Data Link Layer // typedef struct { - UINT32 Ec:15; // UIC Data Link Layer Error Code - UINT32 Rsvd1:16; - UINT32 Err:1; // UIC Data Link Layer Error + UINT32 Ec : 15; // UIC Data Link Layer Error Code + UINT32 Rsvd1 : 16; + UINT32 Err : 1; // UIC Data Link Layer Error } UFS_HC_UECDL; // // UFSHCI 2.0 Spec Section 5.3.7 Offset 40h: UECN - Host UIC Error Code Network Layer // typedef struct { - UINT32 Ec:3; // UIC Network Layer Error Code - UINT32 Rsvd1:28; - UINT32 Err:1; // UIC Network Layer Error + UINT32 Ec : 3; // UIC Network Layer Error Code + UINT32 Rsvd1 : 28; + UINT32 Err : 1; // UIC Network Layer Error } UFS_HC_UECN; // // UFSHCI 2.0 Spec Section 5.3.8 Offset 44h: UECT - Host UIC Error Code Transport Layer // typedef struct { - UINT32 Ec:7; // UIC Transport Layer Error Code - UINT32 Rsvd1:24; - UINT32 Err:1; // UIC Transport Layer Error + UINT32 Ec : 7; // UIC Transport Layer Error Code + UINT32 Rsvd1 : 24; + UINT32 Err : 1; // UIC Transport Layer Error } UFS_HC_UECT; // // UFSHCI 2.0 Spec Section 5.3.9 Offset 48h: UECDME - Host UIC Error Code // typedef struct { - UINT32 Ec:1; // UIC DME Error Code - UINT32 Rsvd1:30; - UINT32 Err:1; // UIC DME Error + UINT32 Ec : 1; // UIC DME Error Code + UINT32 Rsvd1 : 30; + UINT32 Err : 1; // UIC DME Error } UFS_HC_UECDME; // // UFSHCI 2.0 Spec Section 5.3.10 Offset 4Ch: UTRIACR - UTP Transfer Request Interrupt Aggregation Control Register // typedef struct { - UINT8 IaToVal; // Interrupt aggregation timeout value + UINT8 IaToVal; // Interrupt aggregation timeout value - UINT8 IacTh:5; // Interrupt aggregation counter threshold - UINT8 Rsvd1:3; + UINT8 IacTh : 5; // Interrupt aggregation counter threshold + UINT8 Rsvd1 : 3; - UINT8 Ctr:1; // Counter and Timer Reset - UINT8 Rsvd2:3; - UINT8 Iasb:1; // Interrupt aggregation status bit - UINT8 Rsvd3:3; + UINT8 Ctr : 1; // Counter and Timer Reset + UINT8 Rsvd2 : 3; + UINT8 Iasb : 1; // Interrupt aggregation status bit + UINT8 Rsvd3 : 3; - UINT8 IapwEn:1; // Interrupt aggregation parameter write enable - UINT8 Rsvd4:6; - UINT8 IaEn:1; // Interrupt Aggregation Enable/Disable + UINT8 IapwEn : 1; // Interrupt aggregation parameter write enable + UINT8 Rsvd4 : 6; + UINT8 IaEn : 1; // Interrupt Aggregation Enable/Disable } UFS_HC_UTRIACR; // // UFSHCI 2.0 Spec Section 5.4.1 Offset 50h: UTRLBA - UTP Transfer Request List Base Address // typedef struct { - UINT32 Rsvd1:10; - UINT32 UtrlBa:22; // UTP Transfer Request List Base Address + UINT32 Rsvd1 : 10; + UINT32 UtrlBa : 22; // UTP Transfer Request List Base Address } UFS_HC_UTRLBA; // // UFSHCI 2.0 Spec Section 5.4.2 Offset 54h: UTRLBAU - UTP Transfer Request List Base Address Upper 32-bits // -#define UFS_HC_UTRLBAU UINT32 +#define UFS_HC_UTRLBAU UINT32 // // UFSHCI 2.0 Spec Section 5.4.3 Offset 58h: UTRLDBR - UTP Transfer Request List Door Bell Register // -#define UFS_HC_UTRLDBR UINT32 +#define UFS_HC_UTRLDBR UINT32 // // UFSHCI 2.0 Spec Section 5.4.4 Offset 5Ch: UTRLCLR - UTP Transfer Request List CLear Register // -#define UFS_HC_UTRLCLR UINT32 +#define UFS_HC_UTRLCLR UINT32 #if 0 // // UFSHCI 2.0 Spec Section 5.4.5 Offset 60h: UTRLRSR - UTP Transfer Request List Run Stop Register // typedef struct { - UINT32 UtrlRsr:1; // UTP Transfer Request List Run-Stop Register - UINT32 Rsvd1:31; + UINT32 UtrlRsr : 1; // UTP Transfer Request List Run-Stop Register + UINT32 Rsvd1 : 31; } UFS_HC_UTRLRSR; #endif @@ -333,29 +333,29 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.5.1 Offset 70h: UTMRLBA - UTP Task Management Request List Base Address // typedef struct { - UINT32 Rsvd1:10; - UINT32 UtmrlBa:22; // UTP Task Management Request List Base Address + UINT32 Rsvd1 : 10; + UINT32 UtmrlBa : 22; // UTP Task Management Request List Base Address } UFS_HC_UTMRLBA; // // UFSHCI 2.0 Spec Section 5.5.2 Offset 74h: UTMRLBAU - UTP Task Management Request List Base Address Upper 32-bits // -#define UFS_HC_UTMRLBAU UINT32 +#define UFS_HC_UTMRLBAU UINT32 // // UFSHCI 2.0 Spec Section 5.5.3 Offset 78h: UTMRLDBR - UTP Task Management Request List Door Bell Register // typedef struct { - UINT32 UtmrlDbr:8; // UTP Task Management Request List Door bell Register - UINT32 Rsvd1:24; + UINT32 UtmrlDbr : 8; // UTP Task Management Request List Door bell Register + UINT32 Rsvd1 : 24; } UFS_HC_UTMRLDBR; // // UFSHCI 2.0 Spec Section 5.5.4 Offset 7Ch: UTMRLCLR - UTP Task Management Request List CLear Register // typedef struct { - UINT32 UtmrlClr:8; // UTP Task Management List Clear Register - UINT32 Rsvd1:24; + UINT32 UtmrlClr : 8; // UTP Task Management List Clear Register + UINT32 Rsvd1 : 24; } UFS_HC_UTMRLCLR; #if 0 @@ -363,8 +363,8 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.5.5 Offset 80h: UTMRLRSR - UTP Task Management Request List Run Stop Register // typedef struct { - UINT32 UtmrlRsr:1; // UTP Task Management Request List Run-Stop Register - UINT32 Rsvd1:31; + UINT32 UtmrlRsr : 1; // UTP Task Management Request List Run-Stop Register + UINT32 Rsvd1 : 31; } UFS_HC_UTMRLRSR; #endif @@ -372,24 +372,24 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.6.1 Offset 90h: UICCMD - UIC Command // typedef struct { - UINT32 CmdOp:8; // Command Opcode - UINT32 Rsvd1:24; + UINT32 CmdOp : 8; // Command Opcode + UINT32 Rsvd1 : 24; } UFS_HC_UICCMD; // // UFSHCI 2.0 Spec Section 5.6.2 Offset 94h: UICCMDARG1 - UIC Command Argument 1 // -#define UFS_HC_UICCMD_ARG1 UINT32 +#define UFS_HC_UICCMD_ARG1 UINT32 // // UFSHCI 2.0 Spec Section 5.6.2 Offset 98h: UICCMDARG2 - UIC Command Argument 2 // -#define UFS_HC_UICCMD_ARG2 UINT32 +#define UFS_HC_UICCMD_ARG2 UINT32 // // UFSHCI 2.0 Spec Section 5.6.2 Offset 9ch: UICCMDARG3 - UIC Command Argument 3 // -#define UFS_HC_UICCMD_ARG3 UINT32 +#define UFS_HC_UICCMD_ARG3 UINT32 // // UIC command opcodes @@ -417,74 +417,74 @@ typedef struct { // // DW0 // - UINT32 Rsvd1:24; - UINT32 Int:1; /* Interrupt */ - UINT32 Dd:2; /* Data Direction */ - UINT32 Rsvd2:1; - UINT32 Ct:4; /* Command Type */ + UINT32 Rsvd1 : 24; + UINT32 Int : 1; /* Interrupt */ + UINT32 Dd : 2; /* Data Direction */ + UINT32 Rsvd2 : 1; + UINT32 Ct : 4; /* Command Type */ // // DW1 // - UINT32 Rsvd3; + UINT32 Rsvd3; // // DW2 // - UINT32 Ocs:8; /* Overall Command Status */ - UINT32 Rsvd4:24; + UINT32 Ocs : 8; /* Overall Command Status */ + UINT32 Rsvd4 : 24; // // DW3 // - UINT32 Rsvd5; + UINT32 Rsvd5; // // DW4 // - UINT32 Rsvd6:7; - UINT32 UcdBa:25; /* UTP Command Descriptor Base Address */ + UINT32 Rsvd6 : 7; + UINT32 UcdBa : 25; /* UTP Command Descriptor Base Address */ // // DW5 // - UINT32 UcdBaU; /* UTP Command Descriptor Base Address Upper 32-bits */ + UINT32 UcdBaU; /* UTP Command Descriptor Base Address Upper 32-bits */ // // DW6 // - UINT16 RuL; /* Response UPIU Length */ - UINT16 RuO; /* Response UPIU Offset */ + UINT16 RuL; /* Response UPIU Length */ + UINT16 RuO; /* Response UPIU Offset */ // // DW7 // - UINT16 PrdtL; /* PRDT Length */ - UINT16 PrdtO; /* PRDT Offset */ + UINT16 PrdtL; /* PRDT Length */ + UINT16 PrdtO; /* PRDT Offset */ } UTP_TRD; typedef struct { // // DW0 // - UINT32 Rsvd1:2; - UINT32 DbAddr:30; /* Data Base Address */ + UINT32 Rsvd1 : 2; + UINT32 DbAddr : 30; /* Data Base Address */ // // DW1 // - UINT32 DbAddrU; /* Data Base Address Upper 32-bits */ + UINT32 DbAddrU; /* Data Base Address Upper 32-bits */ // // DW2 // - UINT32 Rsvd2; + UINT32 Rsvd2; // // DW3 // - UINT32 DbCount:18; /* Data Byte Count */ - UINT32 Rsvd3:14; + UINT32 DbCount : 18; /* Data Byte Count */ + UINT32 Rsvd3 : 14; } UTP_TR_PRD; // @@ -494,38 +494,38 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x01*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x01*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 CmdSet:4; /* Command Set Type */ - UINT8 Rsvd1:4; - UINT8 Rsvd2; - UINT8 Rsvd3; - UINT8 Rsvd4; + UINT8 CmdSet : 4; /* Command Set Type */ + UINT8 Rsvd1 : 4; + UINT8 Rsvd2; + UINT8 Rsvd3; + UINT8 Rsvd4; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd5; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd5; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 ExpDataTranLen; /* Expected Data Transfer Length - Big Endian */ + UINT32 ExpDataTranLen; /* Expected Data Transfer Length - Big Endian */ // // DW4 - DW7 // - UINT8 Cdb[16]; + UINT8 Cdb[16]; } UTP_COMMAND_UPIU; // @@ -535,44 +535,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x21*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x21*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 CmdSet:4; /* Command Set Type */ - UINT8 Rsvd1:4; - UINT8 Rsvd2; - UINT8 Response; /* Response */ - UINT8 Status; /* Status */ + UINT8 CmdSet : 4; /* Command Set Type */ + UINT8 Rsvd1 : 4; + UINT8 Rsvd2; + UINT8 Response; /* Response */ + UINT8 Status; /* Status */ // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 ResTranCount; /* Residual Transfer Count - Big Endian */ + UINT32 ResTranCount; /* Residual Transfer Count - Big Endian */ // // DW4 - DW7 // - UINT8 Rsvd3[16]; + UINT8 Rsvd3[16]; // // Data Segment - Sense Data // - UINT16 SenseDataLen; /* Sense Data Length - Big Endian */ - UINT8 SenseData[18]; /* Sense Data */ + UINT16 SenseDataLen; /* Sense Data Length - Big Endian */ + UINT8 SenseData[18]; /* Sense Data */ } UTP_RESPONSE_UPIU; // @@ -582,44 +582,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x02*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x02*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be sent out // - //UINT8 Data[]; /* Data to be sent out, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be sent out, maximum is 65535 bytes */ } UTP_DATA_OUT_UPIU; // @@ -629,44 +629,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x22*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x22*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be read // - //UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ } UTP_DATA_IN_UPIU; // @@ -676,44 +676,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x31*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x31*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be read // - //UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ } UTP_RDY_TO_TRAN_UPIU; // @@ -723,46 +723,46 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x04*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x04*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1; - UINT8 TskManFunc; /* Task Management Function */ - UINT8 Rsvd2[2]; + UINT8 Rsvd1; + UINT8 TskManFunc; /* Task Management Function */ + UINT8 Rsvd2[2]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 InputParam1; /* Input Parameter 1 - Big Endian */ + UINT32 InputParam1; /* Input Parameter 1 - Big Endian */ // // DW4 // - UINT32 InputParam2; /* Input Parameter 2 - Big Endian */ + UINT32 InputParam2; /* Input Parameter 2 - Big Endian */ // // DW5 // - UINT32 InputParam3; /* Input Parameter 3 - Big Endian */ + UINT32 InputParam3; /* Input Parameter 3 - Big Endian */ // // DW6 - DW7 // - UINT8 Rsvd4[8]; + UINT8 Rsvd4[8]; } UTP_TM_REQ_UPIU; // @@ -772,41 +772,41 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x24*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x24*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[2]; - UINT8 Resp; /* Response */ - UINT8 Rsvd2; + UINT8 Rsvd1[2]; + UINT8 Resp; /* Response */ + UINT8 Rsvd2; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 OutputParam1; /* Output Parameter 1 - Big Endian */ + UINT32 OutputParam1; /* Output Parameter 1 - Big Endian */ // // DW4 // - UINT32 OutputParam2; /* Output Parameter 2 - Big Endian */ + UINT32 OutputParam2; /* Output Parameter 2 - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd4[12]; + UINT8 Rsvd4[12]; } UTP_TM_RESP_UPIU; // @@ -816,47 +816,46 @@ typedef struct { // // DW0 // - UINT32 Rsvd1:24; - UINT32 Int:1; /* Interrupt */ - UINT32 Rsvd2:7; + UINT32 Rsvd1 : 24; + UINT32 Int : 1; /* Interrupt */ + UINT32 Rsvd2 : 7; // // DW1 // - UINT32 Rsvd3; + UINT32 Rsvd3; // // DW2 // - UINT32 Ocs:8; /* Overall Command Status */ - UINT32 Rsvd4:24; + UINT32 Ocs : 8; /* Overall Command Status */ + UINT32 Rsvd4 : 24; // // DW3 // - UINT32 Rsvd5; + UINT32 Rsvd5; // // DW4 - DW11 // - UTP_TM_REQ_UPIU TmReq; /* Task Management Request UPIU */ + UTP_TM_REQ_UPIU TmReq; /* Task Management Request UPIU */ // // DW12 - DW19 // - UTP_TM_RESP_UPIU TmResp; /* Task Management Response UPIU */ + UTP_TM_RESP_UPIU TmResp; /* Task Management Response UPIU */ } UTP_TMRD; - typedef struct { - UINT8 Opcode; - UINT8 DescId; - UINT8 Index; - UINT8 Selector; - UINT16 Rsvd1; - UINT16 Length; - UINT32 Value; - UINT32 Rsvd2; + UINT8 Opcode; + UINT8 DescId; + UINT8 Index; + UINT8 Selector; + UINT16 Rsvd1; + UINT16 Length; + UINT32 Value; + UINT32 Rsvd2; } UTP_UPIU_TSF; // @@ -866,56 +865,56 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x16*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x16*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2; - UINT8 QueryFunc; /* Query Function */ - UINT8 Rsvd3[2]; + UINT8 Rsvd2; + UINT8 QueryFunc; /* Query Function */ + UINT8 Rsvd3[2]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd4; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd4; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 - 6 // - UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ + UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ // // DW7 // - UINT8 Rsvd5[4]; + UINT8 Rsvd5[4]; // // Data Segment - Data to be transferred // - //UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ } UTP_QUERY_REQ_UPIU; -#define QUERY_FUNC_STD_READ_REQ 0x01 -#define QUERY_FUNC_STD_WRITE_REQ 0x81 +#define QUERY_FUNC_STD_READ_REQ 0x01 +#define QUERY_FUNC_STD_WRITE_REQ 0x81 typedef enum { - UtpQueryFuncOpcodeNop = 0x00, - UtpQueryFuncOpcodeRdDesc = 0x01, - UtpQueryFuncOpcodeWrDesc = 0x02, - UtpQueryFuncOpcodeRdAttr = 0x03, - UtpQueryFuncOpcodeWrAttr = 0x04, - UtpQueryFuncOpcodeRdFlag = 0x05, - UtpQueryFuncOpcodeSetFlag = 0x06, - UtpQueryFuncOpcodeClrFlag = 0x07, - UtpQueryFuncOpcodeTogFlag = 0x08 + UtpQueryFuncOpcodeNop = 0x00, + UtpQueryFuncOpcodeRdDesc = 0x01, + UtpQueryFuncOpcodeWrDesc = 0x02, + UtpQueryFuncOpcodeRdAttr = 0x03, + UtpQueryFuncOpcodeWrAttr = 0x04, + UtpQueryFuncOpcodeRdFlag = 0x05, + UtpQueryFuncOpcodeSetFlag = 0x06, + UtpQueryFuncOpcodeClrFlag = 0x07, + UtpQueryFuncOpcodeTogFlag = 0x08 } UTP_QUERY_FUNC_OPCODE; // @@ -925,42 +924,42 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x36*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x36*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2; - UINT8 QueryFunc; /* Query Function */ - UINT8 QueryResp; /* Query Response */ - UINT8 Rsvd3; + UINT8 Rsvd2; + UINT8 QueryFunc; /* Query Function */ + UINT8 QueryResp; /* Query Response */ + UINT8 Rsvd3; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 - 6 // - UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ + UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ // // DW7 // - UINT8 Rsvd4[4]; + UINT8 Rsvd4[4]; // // Data Segment - Data to be transferred // - //UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ } UTP_QUERY_RESP_UPIU; typedef enum { @@ -984,39 +983,39 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x3F*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x3F*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[2]; - UINT8 Response; /* Response - 0x01 */ - UINT8 Rsvd2; + UINT8 Rsvd1[2]; + UINT8 Response; /* Response - 0x01 */ + UINT8 Rsvd2; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information - 0x00 */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information - 0x00 */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT8 HdrSts; /* Basic Header Status */ - UINT8 Rsvd3; - UINT8 E2ESts; /* End-to-End Status */ - UINT8 Rsvd4; + UINT8 HdrSts; /* Basic Header Status */ + UINT8 Rsvd3; + UINT8 E2ESts; /* End-to-End Status */ + UINT8 Rsvd4; // // DW4 - DW7 // - UINT8 Rsvd5[16]; + UINT8 Rsvd5[16]; } UTP_REJ_UPIU; // @@ -1026,29 +1025,29 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x00*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x00*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2[4]; + UINT8 Rsvd2[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 - DW7 // - UINT8 Rsvd4[20]; + UINT8 Rsvd4[20]; } UTP_NOP_OUT_UPIU; // @@ -1058,234 +1057,234 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x20*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x20*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2[2]; - UINT8 Resp; /* Response - 0x00 */ - UINT8 Rsvd3; + UINT8 Rsvd2[2]; + UINT8 Resp; /* Response - 0x00 */ + UINT8 Rsvd3; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information - 0x00 */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information - 0x00 */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 - DW7 // - UINT8 Rsvd4[20]; + UINT8 Rsvd4[20]; } UTP_NOP_IN_UPIU; // // UFS Descriptors // typedef enum { - UfsDeviceDesc = 0x00, - UfsConfigDesc = 0x01, - UfsUnitDesc = 0x02, - UfsInterConnDesc = 0x04, - UfsStringDesc = 0x05, - UfsGeometryDesc = 0x07, - UfsPowerDesc = 0x08 + UfsDeviceDesc = 0x00, + UfsConfigDesc = 0x01, + UfsUnitDesc = 0x02, + UfsInterConnDesc = 0x04, + UfsStringDesc = 0x05, + UfsGeometryDesc = 0x07, + UfsPowerDesc = 0x08 } UFS_DESC_IDN; // // UFS 2.0 Spec Section 14.1.6.2 - Device Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 Device; - UINT8 DevClass; - UINT8 DevSubClass; - UINT8 Protocol; - UINT8 NumLun; - UINT8 NumWLun; - UINT8 BootEn; - UINT8 DescAccessEn; - UINT8 InitPowerMode; - UINT8 HighPriorityLun; - UINT8 SecureRemovalType; - UINT8 SecurityLun; - UINT8 BgOpsTermLat; - UINT8 InitActiveIccLevel; - UINT16 SpecVersion; - UINT16 ManufactureDate; - UINT8 ManufacturerName; - UINT8 ProductName; - UINT8 SerialName; - UINT8 OemId; - UINT16 ManufacturerId; - UINT8 Ud0BaseOffset; - UINT8 Ud0ConfParamLen; - UINT8 DevRttCap; - UINT16 PeriodicRtcUpdate; - UINT8 Rsvd1[17]; - UINT8 Rsvd2[16]; + UINT8 Length; + UINT8 DescType; + UINT8 Device; + UINT8 DevClass; + UINT8 DevSubClass; + UINT8 Protocol; + UINT8 NumLun; + UINT8 NumWLun; + UINT8 BootEn; + UINT8 DescAccessEn; + UINT8 InitPowerMode; + UINT8 HighPriorityLun; + UINT8 SecureRemovalType; + UINT8 SecurityLun; + UINT8 BgOpsTermLat; + UINT8 InitActiveIccLevel; + UINT16 SpecVersion; + UINT16 ManufactureDate; + UINT8 ManufacturerName; + UINT8 ProductName; + UINT8 SerialName; + UINT8 OemId; + UINT16 ManufacturerId; + UINT8 Ud0BaseOffset; + UINT8 Ud0ConfParamLen; + UINT8 DevRttCap; + UINT16 PeriodicRtcUpdate; + UINT8 Rsvd1[17]; + UINT8 Rsvd2[16]; } UFS_DEV_DESC; typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 Rsvd1; - UINT8 BootEn; - UINT8 DescAccessEn; - UINT8 InitPowerMode; - UINT8 HighPriorityLun; - UINT8 SecureRemovalType; - UINT8 InitActiveIccLevel; - UINT16 PeriodicRtcUpdate; - UINT8 Rsvd2[5]; + UINT8 Length; + UINT8 DescType; + UINT8 Rsvd1; + UINT8 BootEn; + UINT8 DescAccessEn; + UINT8 InitPowerMode; + UINT8 HighPriorityLun; + UINT8 SecureRemovalType; + UINT8 InitActiveIccLevel; + UINT16 PeriodicRtcUpdate; + UINT8 Rsvd2[5]; } UFS_CONFIG_DESC_GEN_HEADER; typedef struct { - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 MemType; - UINT32 NumAllocUnits; - UINT8 DataReliability; - UINT8 LogicBlkSize; - UINT8 ProvisionType; - UINT16 CtxCap; - UINT8 Rsvd1[3]; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 MemType; + UINT32 NumAllocUnits; + UINT8 DataReliability; + UINT8 LogicBlkSize; + UINT8 ProvisionType; + UINT16 CtxCap; + UINT8 Rsvd1[3]; } UFS_UNIT_DESC_CONFIG_PARAMS; // // UFS 2.0 Spec Section 14.1.6.3 - Configuration Descriptor // typedef struct { - UFS_CONFIG_DESC_GEN_HEADER Header; - UFS_UNIT_DESC_CONFIG_PARAMS UnitDescConfParams[8]; + UFS_CONFIG_DESC_GEN_HEADER Header; + UFS_UNIT_DESC_CONFIG_PARAMS UnitDescConfParams[8]; } UFS_CONFIG_DESC; // // UFS 2.0 Spec Section 14.1.6.4 - Geometry Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 MediaTech; - UINT8 Rsvd1; - UINT64 TotalRawDevCapacity; - UINT8 Rsvd2; - UINT32 SegSize; - UINT8 AllocUnitSize; - UINT8 MinAddrBlkSize; - UINT8 OptReadBlkSize; - UINT8 OptWriteBlkSize; - UINT8 MaxInBufSize; - UINT8 MaxOutBufSize; - UINT8 RpmbRwSize; - UINT8 Rsvd3; - UINT8 DataOrder; - UINT8 MaxCtxIdNum; - UINT8 SysDataTagUnitSize; - UINT8 SysDataResUnitSize; - UINT8 SupSecRemovalTypes; - UINT16 SupMemTypes; - UINT32 SysCodeMaxNumAllocUnits; - UINT16 SupCodeCapAdjFac; - UINT32 NonPersMaxNumAllocUnits; - UINT16 NonPersCapAdjFac; - UINT32 Enhance1MaxNumAllocUnits; - UINT16 Enhance1CapAdjFac; - UINT32 Enhance2MaxNumAllocUnits; - UINT16 Enhance2CapAdjFac; - UINT32 Enhance3MaxNumAllocUnits; - UINT16 Enhance3CapAdjFac; - UINT32 Enhance4MaxNumAllocUnits; - UINT16 Enhance4CapAdjFac; + UINT8 Length; + UINT8 DescType; + UINT8 MediaTech; + UINT8 Rsvd1; + UINT64 TotalRawDevCapacity; + UINT8 Rsvd2; + UINT32 SegSize; + UINT8 AllocUnitSize; + UINT8 MinAddrBlkSize; + UINT8 OptReadBlkSize; + UINT8 OptWriteBlkSize; + UINT8 MaxInBufSize; + UINT8 MaxOutBufSize; + UINT8 RpmbRwSize; + UINT8 Rsvd3; + UINT8 DataOrder; + UINT8 MaxCtxIdNum; + UINT8 SysDataTagUnitSize; + UINT8 SysDataResUnitSize; + UINT8 SupSecRemovalTypes; + UINT16 SupMemTypes; + UINT32 SysCodeMaxNumAllocUnits; + UINT16 SupCodeCapAdjFac; + UINT32 NonPersMaxNumAllocUnits; + UINT16 NonPersCapAdjFac; + UINT32 Enhance1MaxNumAllocUnits; + UINT16 Enhance1CapAdjFac; + UINT32 Enhance2MaxNumAllocUnits; + UINT16 Enhance2CapAdjFac; + UINT32 Enhance3MaxNumAllocUnits; + UINT16 Enhance3CapAdjFac; + UINT32 Enhance4MaxNumAllocUnits; + UINT16 Enhance4CapAdjFac; } UFS_GEOMETRY_DESC; // // UFS 2.0 Spec Section 14.1.6.5 - Unit Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 UnitIdx; - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 LunQueueDep; - UINT8 Rsvd1; - UINT8 MemType; - UINT8 DataReliability; - UINT8 LogicBlkSize; - UINT64 LogicBlkCount; - UINT32 EraseBlkSize; - UINT8 ProvisionType; - UINT64 PhyMemResCount; - UINT16 CtxCap; - UINT8 LargeUnitGranularity; + UINT8 Length; + UINT8 DescType; + UINT8 UnitIdx; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 LunQueueDep; + UINT8 Rsvd1; + UINT8 MemType; + UINT8 DataReliability; + UINT8 LogicBlkSize; + UINT64 LogicBlkCount; + UINT32 EraseBlkSize; + UINT8 ProvisionType; + UINT64 PhyMemResCount; + UINT16 CtxCap; + UINT8 LargeUnitGranularity; } UFS_UNIT_DESC; // // UFS 2.0 Spec Section 14.1.6.6 - RPMB Unit Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 UnitIdx; - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 LunQueueDep; - UINT8 Rsvd1; - UINT8 MemType; - UINT8 Rsvd2; - UINT8 LogicBlkSize; - UINT64 LogicBlkCount; - UINT32 EraseBlkSize; - UINT8 ProvisionType; - UINT64 PhyMemResCount; - UINT8 Rsvd3[3]; + UINT8 Length; + UINT8 DescType; + UINT8 UnitIdx; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 LunQueueDep; + UINT8 Rsvd1; + UINT8 MemType; + UINT8 Rsvd2; + UINT8 LogicBlkSize; + UINT64 LogicBlkCount; + UINT32 EraseBlkSize; + UINT8 ProvisionType; + UINT64 PhyMemResCount; + UINT8 Rsvd3[3]; } UFS_RPMB_UNIT_DESC; typedef struct { - UINT16 Value:10; - UINT16 Rsvd1:4; - UINT16 Unit:2; + UINT16 Value : 10; + UINT16 Rsvd1 : 4; + UINT16 Unit : 2; } UFS_POWER_PARAM_ELEMENT; // // UFS 2.0 Spec Section 14.1.6.7 - Power Parameter Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVcc[16]; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ[16]; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ2[16]; + UINT8 Length; + UINT8 DescType; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVcc[16]; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ[16]; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ2[16]; } UFS_POWER_DESC; // // UFS 2.0 Spec Section 14.1.6.8 - InterConnect Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT16 UniProVer; - UINT16 MphyVer; + UINT8 Length; + UINT8 DescType; + UINT16 UniProVer; + UINT16 MphyVer; } UFS_INTER_CONNECT_DESC; // // UFS 2.0 Spec Section 14.1.6.9 - 14.1.6.12 - String Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - CHAR16 Unicode[126]; + UINT8 Length; + UINT8 DescType; + CHAR16 Unicode[126]; } UFS_STRING_DESC; // @@ -1306,34 +1305,32 @@ typedef enum { // UFS 2.0 Spec Section 14.2 - Attributes // typedef enum { - UfsAttrBootLunEn = 0x00, - UfsAttrCurPowerMode = 0x02, - UfsAttrActiveIccLevel = 0x03, - UfsAttrOutOfOrderDataEn = 0x04, - UfsAttrBgOpStatus = 0x05, - UfsAttrPurgeStatus = 0x06, - UfsAttrMaxDataInSize = 0x07, - UfsAttrMaxDataOutSize = 0x08, - UfsAttrDynCapNeeded = 0x09, - UfsAttrRefClkFreq = 0x0a, - UfsAttrConfigDescLock = 0x0b, - UfsAttrMaxNumOfRtt = 0x0c, - UfsAttrExceptionEvtCtrl = 0x0d, - UfsAttrExceptionEvtSts = 0x0e, - UfsAttrSecondsPassed = 0x0f, - UfsAttrContextConf = 0x10, - UfsAttrCorrPrgBlkNum = 0x11 + UfsAttrBootLunEn = 0x00, + UfsAttrCurPowerMode = 0x02, + UfsAttrActiveIccLevel = 0x03, + UfsAttrOutOfOrderDataEn = 0x04, + UfsAttrBgOpStatus = 0x05, + UfsAttrPurgeStatus = 0x06, + UfsAttrMaxDataInSize = 0x07, + UfsAttrMaxDataOutSize = 0x08, + UfsAttrDynCapNeeded = 0x09, + UfsAttrRefClkFreq = 0x0a, + UfsAttrConfigDescLock = 0x0b, + UfsAttrMaxNumOfRtt = 0x0c, + UfsAttrExceptionEvtCtrl = 0x0d, + UfsAttrExceptionEvtSts = 0x0e, + UfsAttrSecondsPassed = 0x0f, + UfsAttrContextConf = 0x10, + UfsAttrCorrPrgBlkNum = 0x11 } UFS_ATTR_IDN; typedef enum { - UfsNoData = 0, - UfsDataOut = 1, - UfsDataIn = 2, + UfsNoData = 0, + UfsDataOut = 1, + UfsDataIn = 2, UfsDdReserved } UFS_DATA_DIRECTION; - #pragma pack() #endif - diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/ComponentName.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/ComponentName.c index aced63b491..43584f4749 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/ComponentName.c @@ -18,14 +18,13 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUfsPassThruComponent // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUfsPassThruComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UfsPassThruComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UfsPassThruComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUfsPassThruComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UfsPassThruComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UfsPassThruComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsPassThruDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsPassThruDriverNameTable[] = { { "eng;en", L"Universal Flash Storage (UFS) Pass Thru Driver" @@ -36,7 +35,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsPassThruDriverNameTab } }; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsPassThruControllerNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUfsPassThruControllerNameTable[] = { { "eng;en", L"Universal Flash Storage (UFS) Host Controller" @@ -174,16 +173,16 @@ UfsPassThruComponentNameGetDriverName ( EFI_STATUS EFIAPI UfsPassThruComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; + EFI_STATUS Status; - if (Language == NULL || ControllerName == NULL) { + if ((Language == NULL) || (ControllerName == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsDevConfigProtocol.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsDevConfigProtocol.c index 4730ecd90b..07ec590edc 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsDevConfigProtocol.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsDevConfigProtocol.c @@ -34,17 +34,17 @@ EFI_STATUS EFIAPI UfsRwUfsDescriptor ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT8 *Descriptor, - IN OUT UINT32 *DescSize + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT8 *Descriptor, + IN OUT UINT32 *DescSize ) { - EFI_STATUS Status; - UFS_PASS_THRU_PRIVATE_DATA *Private; + EFI_STATUS Status; + UFS_PASS_THRU_PRIVATE_DATA *Private; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_DEV_CONFIG (This); @@ -64,6 +64,7 @@ UfsRwUfsDescriptor ( if (Status == EFI_TIMEOUT) { Status = EFI_DEVICE_ERROR; } + return Status; } @@ -88,14 +89,14 @@ UfsRwUfsDescriptor ( EFI_STATUS EFIAPI UfsRwUfsFlag ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 FlagId, - IN OUT UINT8 *Flag + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 FlagId, + IN OUT UINT8 *Flag ) { - EFI_STATUS Status; - UFS_PASS_THRU_PRIVATE_DATA *Private; + EFI_STATUS Status; + UFS_PASS_THRU_PRIVATE_DATA *Private; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_DEV_CONFIG (This); @@ -107,6 +108,7 @@ UfsRwUfsFlag ( if (Status == EFI_TIMEOUT) { Status = EFI_DEVICE_ERROR; } + return Status; } @@ -136,20 +138,20 @@ UfsRwUfsFlag ( EFI_STATUS EFIAPI UfsRwUfsAttribute ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 AttrId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT8 *Attribute, - IN OUT UINT32 *AttrSize + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT8 *Attribute, + IN OUT UINT32 *AttrSize ) { - EFI_STATUS Status; - UFS_PASS_THRU_PRIVATE_DATA *Private; - UINT32 Attribute32; + EFI_STATUS Status; + UFS_PASS_THRU_PRIVATE_DATA *Private; + UINT32 Attribute32; - Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_DEV_CONFIG (This); + Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_DEV_CONFIG (This); Attribute32 = 0; if ((This == NULL) || (Attribute == NULL) || (AttrSize == NULL)) { @@ -186,5 +188,6 @@ UfsRwUfsAttribute ( Status = EFI_DEVICE_ERROR; } } + return Status; } diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c index 92ff958f16..4c2d6ae27f 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.c @@ -11,9 +11,9 @@ // // Template for Ufs Pass Thru private data. // -UFS_PASS_THRU_PRIVATE_DATA gUfsPassThruTemplate = { - UFS_PASS_THRU_SIG, // Signature - NULL, // Handle +UFS_PASS_THRU_PRIVATE_DATA gUfsPassThruTemplate = { + UFS_PASS_THRU_SIG, // Signature + NULL, // Handle { // ExtScsiPassThruMode 0xFFFFFFFF, EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_PHYSICAL | EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_LOGICAL | EFI_EXT_SCSI_PASS_THRU_ATTRIBUTES_NONBLOCKIO, @@ -34,17 +34,17 @@ UFS_PASS_THRU_PRIVATE_DATA gUfsPassThruTemplate = { UfsRwUfsFlag, UfsRwUfsAttribute }, - 0, // UfsHostController - 0, // UfsHcBase - {0, 0}, // UfsHcInfo - {NULL, NULL}, // UfsHcDriverInterface - 0, // TaskTag - 0, // UtpTrlBase - 0, // Nutrs - 0, // TrlMapping - 0, // UtpTmrlBase - 0, // Nutmrs - 0, // TmrlMapping + 0, // UfsHostController + 0, // UfsHcBase + { 0, 0 }, // UfsHcInfo + { NULL, NULL }, // UfsHcDriverInterface + 0, // TaskTag + 0, // UtpTrlBase + 0, // Nutrs + 0, // TrlMapping + 0, // UtpTmrlBase + 0, // Nutmrs + 0, // TmrlMapping { // Luns { UFS_LUN_0, // Ufs Common Lun 0 @@ -60,17 +60,17 @@ UFS_PASS_THRU_PRIVATE_DATA gUfsPassThruTemplate = { UFS_WLUN_BOOT, // Ufs Boot Well Known Lun UFS_WLUN_RPMB // RPMB Well Known Lun }, - 0x0000, // By default don't expose any Luns. + 0x0000, // By default don't expose any Luns. 0x0 }, - NULL, // TimerEvent + NULL, // TimerEvent { // Queue NULL, NULL } }; -EFI_DRIVER_BINDING_PROTOCOL gUfsPassThruDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUfsPassThruDriverBinding = { UfsPassThruDriverBindingSupported, UfsPassThruDriverBindingStart, UfsPassThruDriverBindingStop, @@ -79,20 +79,20 @@ EFI_DRIVER_BINDING_PROTOCOL gUfsPassThruDriverBinding = { NULL }; -UFS_DEVICE_PATH mUfsDevicePathTemplate = { +UFS_DEVICE_PATH mUfsDevicePathTemplate = { { MESSAGING_DEVICE_PATH, MSG_UFS_DP, { - (UINT8) (sizeof (UFS_DEVICE_PATH)), - (UINT8) ((sizeof (UFS_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (UFS_DEVICE_PATH)), + (UINT8)((sizeof (UFS_DEVICE_PATH)) >> 8) } }, 0, 0 }; -UINT8 mUfsTargetId[TARGET_MAX_BYTES]; +UINT8 mUfsTargetId[TARGET_MAX_BYTES]; GLOBAL_REMOVE_IF_UNREFERENCED EDKII_UFS_HC_PLATFORM_PROTOCOL *mUfsHcPlatform; @@ -140,17 +140,17 @@ GLOBAL_REMOVE_IF_UNREFERENCED EDKII_UFS_HC_PLATFORM_PROTOCOL *mUfsHcPlatform; EFI_STATUS EFIAPI UfsPassThruPassThru ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ) { - EFI_STATUS Status; - UFS_PASS_THRU_PRIVATE_DATA *Private; - UINT8 UfsLun; - UINT16 Index; + EFI_STATUS Status; + UFS_PASS_THRU_PRIVATE_DATA *Private; + UINT8 UfsLun; + UINT16 Index; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -162,7 +162,8 @@ UfsPassThruPassThru ( // Don't support variable length CDB // if ((Packet->CdbLength != 6) && (Packet->CdbLength != 10) && - (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) { + (Packet->CdbLength != 12) && (Packet->CdbLength != 16)) + { return EFI_INVALID_PARAMETER; } @@ -170,15 +171,15 @@ UfsPassThruPassThru ( return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->InDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->InDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->OutDataBuffer, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->OutDataBuffer, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } - if ((This->Mode->IoAlign > 1) && !IS_ALIGNED(Packet->SenseData, This->Mode->IoAlign)) { + if ((This->Mode->IoAlign > 1) && !IS_ALIGNED (Packet->SenseData, This->Mode->IoAlign)) { return EFI_INVALID_PARAMETER; } @@ -186,7 +187,7 @@ UfsPassThruPassThru ( // For UFS 2.0 compatible device, 0 is always used to represent the location of the UFS device. // SetMem (mUfsTargetId, TARGET_MAX_BYTES, 0x00); - if ((Target == NULL) || (CompareMem(Target, mUfsTargetId, TARGET_MAX_BYTES) != 0)) { + if ((Target == NULL) || (CompareMem (Target, mUfsTargetId, TARGET_MAX_BYTES) != 0)) { return EFI_INVALID_PARAMETER; } @@ -196,9 +197,9 @@ UfsPassThruPassThru ( // The second 8 bits of the 64-bit address saves the corresponding 8-bit UFS LUN. // if ((UINT8)Lun == UFS_WLUN_PREFIX) { - UfsLun = BIT7 | (((UINT8*)&Lun)[1] & 0xFF); + UfsLun = BIT7 | (((UINT8 *)&Lun)[1] & 0xFF); } else if ((UINT8)Lun == 0) { - UfsLun = ((UINT8*)&Lun)[1] & 0xFF; + UfsLun = ((UINT8 *)&Lun)[1] & 0xFF; } else { return EFI_INVALID_PARAMETER; } @@ -251,19 +252,19 @@ UfsPassThruPassThru ( EFI_STATUS EFIAPI UfsPassThruGetNextTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target, - IN OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target, + IN OUT UINT64 *Lun ) { - UFS_PASS_THRU_PRIVATE_DATA *Private; - UINT8 UfsLun; - UINT16 Index; - UINT16 Next; + UFS_PASS_THRU_PRIVATE_DATA *Private; + UINT8 UfsLun; + UINT16 Index; + UINT16 Next; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); - if (Target == NULL || Lun == NULL) { + if ((Target == NULL) || (Lun == NULL)) { return EFI_INVALID_PARAMETER; } @@ -284,14 +285,16 @@ UfsPassThruGetNextTargetLun ( break; } } + if (Index != UFS_MAX_LUNS) { *Lun = 0; if ((UfsLun & BIT7) == BIT7) { - ((UINT8*)Lun)[0] = UFS_WLUN_PREFIX; - ((UINT8*)Lun)[1] = UfsLun & ~BIT7; + ((UINT8 *)Lun)[0] = UFS_WLUN_PREFIX; + ((UINT8 *)Lun)[1] = UfsLun & ~BIT7; } else { - ((UINT8*)Lun)[1] = UfsLun; + ((UINT8 *)Lun)[1] = UfsLun; } + return EFI_SUCCESS; } else { return EFI_NOT_FOUND; @@ -300,10 +303,10 @@ UfsPassThruGetNextTargetLun ( SetMem (mUfsTargetId, TARGET_MAX_BYTES, 0x00); if (CompareMem (*Target, mUfsTargetId, TARGET_MAX_BYTES) == 0) { - if (((UINT8*)Lun)[0] == UFS_WLUN_PREFIX) { - UfsLun = BIT7 | (((UINT8*)Lun)[1] & 0xFF); - } else if (((UINT8*)Lun)[0] == 0) { - UfsLun = ((UINT8*)Lun)[1] & 0xFF; + if (((UINT8 *)Lun)[0] == UFS_WLUN_PREFIX) { + UfsLun = BIT7 | (((UINT8 *)Lun)[1] & 0xFF); + } else if (((UINT8 *)Lun)[0] == 0) { + UfsLun = ((UINT8 *)Lun)[1] & 0xFF; } else { return EFI_NOT_FOUND; } @@ -334,11 +337,12 @@ UfsPassThruGetNextTargetLun ( if (Index != UFS_MAX_LUNS) { *Lun = 0; if ((UfsLun & BIT7) == BIT7) { - ((UINT8*)Lun)[0] = UFS_WLUN_PREFIX; - ((UINT8*)Lun)[1] = UfsLun & ~BIT7; + ((UINT8 *)Lun)[0] = UFS_WLUN_PREFIX; + ((UINT8 *)Lun)[1] = UfsLun & ~BIT7; } else { - ((UINT8*)Lun)[1] = UfsLun; + ((UINT8 *)Lun)[1] = UfsLun; } + return EFI_SUCCESS; } else { return EFI_NOT_FOUND; @@ -378,16 +382,16 @@ UfsPassThruGetNextTargetLun ( EFI_STATUS EFIAPI UfsPassThruBuildDevicePath ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ) { - UFS_PASS_THRU_PRIVATE_DATA *Private; - EFI_DEV_PATH *DevicePathNode; - UINT8 UfsLun; - UINT16 Index; + UFS_PASS_THRU_PRIVATE_DATA *Private; + EFI_DEV_PATH *DevicePathNode; + UINT8 UfsLun; + UINT16 Index; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); @@ -400,9 +404,9 @@ UfsPassThruBuildDevicePath ( } if ((UINT8)Lun == UFS_WLUN_PREFIX) { - UfsLun = BIT7 | (((UINT8*)&Lun)[1] & 0xFF); + UfsLun = BIT7 | (((UINT8 *)&Lun)[1] & 0xFF); } else if ((UINT8)Lun == 0) { - UfsLun = ((UINT8*)&Lun)[1] & 0xFF; + UfsLun = ((UINT8 *)&Lun)[1] & 0xFF; } else { return EFI_NOT_FOUND; } @@ -429,7 +433,7 @@ UfsPassThruBuildDevicePath ( DevicePathNode->Ufs.Pun = 0; DevicePathNode->Ufs.Lun = UfsLun; - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) DevicePathNode; + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)DevicePathNode; return EFI_SUCCESS; } @@ -456,24 +460,24 @@ UfsPassThruBuildDevicePath ( EFI_STATUS EFIAPI UfsPassThruGetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 **Target, + OUT UINT64 *Lun ) { - UFS_PASS_THRU_PRIVATE_DATA *Private; - EFI_DEV_PATH *DevicePathNode; - UINT8 Pun; - UINT8 UfsLun; - UINT16 Index; + UFS_PASS_THRU_PRIVATE_DATA *Private; + EFI_DEV_PATH *DevicePathNode; + UINT8 Pun; + UINT8 UfsLun; + UINT16 Index; Private = UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS (This); // // Validate parameters passed in. // - if (DevicePath == NULL || Target == NULL || Lun == NULL) { + if ((DevicePath == NULL) || (Target == NULL) || (Lun == NULL)) { return EFI_INVALID_PARAMETER; } @@ -485,14 +489,15 @@ UfsPassThruGetTargetLun ( // Check whether the DevicePath belongs to UFS_DEVICE_PATH // if ((DevicePath->Type != MESSAGING_DEVICE_PATH) || (DevicePath->SubType != MSG_UFS_DP) || - (DevicePathNodeLength(DevicePath) != sizeof(UFS_DEVICE_PATH))) { + (DevicePathNodeLength (DevicePath) != sizeof (UFS_DEVICE_PATH))) + { return EFI_UNSUPPORTED; } - DevicePathNode = (EFI_DEV_PATH *) DevicePath; + DevicePathNode = (EFI_DEV_PATH *)DevicePath; - Pun = (UINT8) DevicePathNode->Ufs.Pun; - UfsLun = (UINT8) DevicePathNode->Ufs.Lun; + Pun = (UINT8)DevicePathNode->Ufs.Pun; + UfsLun = (UINT8)DevicePathNode->Ufs.Lun; if (Pun != 0) { return EFI_NOT_FOUND; @@ -515,11 +520,12 @@ UfsPassThruGetTargetLun ( SetMem (*Target, TARGET_MAX_BYTES, 0x00); *Lun = 0; if ((UfsLun & BIT7) == BIT7) { - ((UINT8*)Lun)[0] = UFS_WLUN_PREFIX; - ((UINT8*)Lun)[1] = UfsLun & ~BIT7; + ((UINT8 *)Lun)[0] = UFS_WLUN_PREFIX; + ((UINT8 *)Lun)[1] = UfsLun & ~BIT7; } else { - ((UINT8*)Lun)[1] = UfsLun; + ((UINT8 *)Lun)[1] = UfsLun; } + return EFI_SUCCESS; } @@ -537,7 +543,7 @@ UfsPassThruGetTargetLun ( EFI_STATUS EFIAPI UfsPassThruResetChannel ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This ) { // @@ -568,9 +574,9 @@ UfsPassThruResetChannel ( EFI_STATUS EFIAPI UfsPassThruResetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun ) { // @@ -604,16 +610,16 @@ UfsPassThruResetTargetLun ( EFI_STATUS EFIAPI UfsPassThruGetNextTarget ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target ) { - if (Target == NULL || *Target == NULL) { + if ((Target == NULL) || (*Target == NULL)) { return EFI_INVALID_PARAMETER; } SetMem (mUfsTargetId, TARGET_MAX_BYTES, 0xFF); - if (CompareMem(*Target, mUfsTargetId, TARGET_MAX_BYTES) == 0) { + if (CompareMem (*Target, mUfsTargetId, TARGET_MAX_BYTES) == 0) { SetMem (*Target, TARGET_MAX_BYTES, 0x00); return EFI_SUCCESS; } @@ -666,14 +672,14 @@ UfsPassThruGetNextTarget ( EFI_STATUS EFIAPI UfsPassThruDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHostController; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHostController; // // Ufs Pass Thru driver is a device driver, and should ingore the @@ -682,7 +688,7 @@ UfsPassThruDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID *) &ParentDevicePath, + (VOID *)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -693,20 +699,21 @@ UfsPassThruDriverBindingSupported ( // return Status; } + // // Close the protocol because we don't use it here // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); Status = gBS->OpenProtocol ( Controller, &gEdkiiUfsHostControllerProtocolGuid, - (VOID **) &UfsHostController, + (VOID **)&UfsHostController, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -723,11 +730,11 @@ UfsPassThruDriverBindingSupported ( // Close the I/O Abstraction(s) used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEdkiiUfsHostControllerProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEdkiiUfsHostControllerProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_SUCCESS; } @@ -748,8 +755,8 @@ UfsFinishDeviceInitialization ( ) { EFI_STATUS Status; - UINT8 DeviceInitStatus; - UINT32 Timeout; + UINT8 DeviceInitStatus; + UINT32 Timeout; DeviceInitStatus = 0xFF; @@ -770,6 +777,7 @@ UfsFinishDeviceInitialization ( if (EFI_ERROR (Status)) { return Status; } + MicroSecondDelay (1); Timeout--; } while (DeviceInitStatus != 0 && Timeout != 0); @@ -821,20 +829,20 @@ UfsFinishDeviceInitialization ( EFI_STATUS EFIAPI UfsPassThruDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; - UFS_PASS_THRU_PRIVATE_DATA *Private; - UINTN UfsHcBase; - UINT32 Index; - UFS_UNIT_DESC UnitDescriptor; - UFS_DEV_DESC DeviceDescriptor; - UINT32 UnitDescriptorSize; - UINT32 DeviceDescriptorSize; + EFI_STATUS Status; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + UFS_PASS_THRU_PRIVATE_DATA *Private; + UINTN UfsHcBase; + UINT32 Index; + UFS_UNIT_DESC UnitDescriptor; + UFS_DEV_DESC DeviceDescriptor; + UINT32 UnitDescriptorSize; + UINT32 DeviceDescriptorSize; Status = EFI_SUCCESS; UfsHc = NULL; @@ -843,14 +851,14 @@ UfsPassThruDriverBindingStart ( DEBUG ((DEBUG_INFO, "==UfsPassThru Start== Controller = %x\n", Controller)); - Status = gBS->OpenProtocol ( - Controller, - &gEdkiiUfsHostControllerProtocolGuid, - (VOID **) &UfsHc, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); + Status = gBS->OpenProtocol ( + Controller, + &gEdkiiUfsHostControllerProtocolGuid, + (VOID **)&UfsHc, + This->DriverBindingHandle, + Controller, + EFI_OPEN_PROTOCOL_BY_DRIVER + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Open Ufs Host Controller Protocol Error, Status = %r\n", Status)); @@ -876,11 +884,11 @@ UfsPassThruDriverBindingStart ( goto Error; } - Private->ExtScsiPassThru.Mode = &Private->ExtScsiPassThruMode; - Private->UfsHostController = UfsHc; - Private->UfsHcBase = UfsHcBase; - Private->Handle = Controller; - Private->UfsHcDriverInterface.UfsHcProtocol = UfsHc; + Private->ExtScsiPassThru.Mode = &Private->ExtScsiPassThruMode; + Private->UfsHostController = UfsHc; + Private->UfsHcBase = UfsHcBase; + Private->Handle = Controller; + Private->UfsHcDriverInterface.UfsHcProtocol = UfsHc; Private->UfsHcDriverInterface.UfsExecUicCommand = UfsHcDriverInterfaceExecUicCommand; InitializeListHead (&Private->Queue); @@ -888,7 +896,7 @@ UfsPassThruDriverBindingStart ( // This has to be done before initializing UfsHcInfo or calling the UfsControllerInit // if (mUfsHcPlatform == NULL) { - Status = gBS->LocateProtocol (&gEdkiiUfsHcPlatformProtocolGuid, NULL, (VOID**)&mUfsHcPlatform); + Status = gBS->LocateProtocol (&gEdkiiUfsHcPlatformProtocolGuid, NULL, (VOID **)&mUfsHcPlatform); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "No UfsHcPlatformProtocol present\n")); } @@ -931,11 +939,12 @@ UfsPassThruDriverBindingStart ( // UnitDescriptorSize = sizeof (UFS_UNIT_DESC); for (Index = 0; Index < 8; Index++) { - Status = UfsRwDeviceDesc (Private, TRUE, UfsUnitDesc, (UINT8) Index, 0, &UnitDescriptor, &UnitDescriptorSize); + Status = UfsRwDeviceDesc (Private, TRUE, UfsUnitDesc, (UINT8)Index, 0, &UnitDescriptor, &UnitDescriptorSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to read unit descriptor, index = %X, status = %r\n", Index, Status)); continue; } + if (UnitDescriptor.LunEn == 0x1) { DEBUG ((DEBUG_INFO, "UFS LUN %X is enabled\n", Index)); Private->Luns.BitMask |= (BIT0 << Index); @@ -946,7 +955,7 @@ UfsPassThruDriverBindingStart ( // Check if RPMB WLUN is supported and set corresponding bit mask. // DeviceDescriptorSize = sizeof (UFS_DEV_DESC); - Status = UfsRwDeviceDesc (Private, TRUE, UfsDeviceDesc, 0, 0, &DeviceDescriptor, &DeviceDescriptorSize); + Status = UfsRwDeviceDesc (Private, TRUE, UfsDeviceDesc, 0, 0, &DeviceDescriptor, &DeviceDescriptorSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failed to read device descriptor, status = %r\n", Status)); } else { @@ -998,6 +1007,7 @@ Error: if (Private->TmrlMapping != NULL) { UfsHc->Unmap (UfsHc, Private->TmrlMapping); } + if (Private->UtpTmrlBase != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (Private->Nutmrs * sizeof (UTP_TMRD)), Private->UtpTmrlBase); } @@ -1005,6 +1015,7 @@ Error: if (Private->TrlMapping != NULL) { UfsHc->Unmap (UfsHc, Private->TrlMapping); } + if (Private->UtpTrlBase != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (Private->Nutrs * sizeof (UTP_TMRD)), Private->UtpTrlBase); } @@ -1057,26 +1068,26 @@ Error: EFI_STATUS EFIAPI UfsPassThruDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - UFS_PASS_THRU_PRIVATE_DATA *Private; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiPassThru; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; - UFS_PASS_THRU_TRANS_REQ *TransReq; - LIST_ENTRY *Entry; - LIST_ENTRY *NextEntry; + EFI_STATUS Status; + UFS_PASS_THRU_PRIVATE_DATA *Private; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL *ExtScsiPassThru; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + UFS_PASS_THRU_TRANS_REQ *TransReq; + LIST_ENTRY *Entry; + LIST_ENTRY *NextEntry; DEBUG ((DEBUG_INFO, "==UfsPassThru Stop== Controller Controller = %x\n", Controller)); Status = gBS->OpenProtocol ( Controller, &gEfiExtScsiPassThruProtocolGuid, - (VOID **) &ExtScsiPassThru, + (VOID **)&ExtScsiPassThru, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1092,9 +1103,9 @@ UfsPassThruDriverBindingStop ( // // Cleanup the resources of I/O requests in the async I/O queue // - if (!IsListEmpty(&Private->Queue)) { + if (!IsListEmpty (&Private->Queue)) { BASE_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Private->Queue) { - TransReq = UFS_PASS_THRU_TRANS_REQ_FROM_THIS (Entry); + TransReq = UFS_PASS_THRU_TRANS_REQ_FROM_THIS (Entry); // // TODO: Should find/add a proper host adapter return status for this @@ -1129,6 +1140,7 @@ UfsPassThruDriverBindingStop ( if (Private->TmrlMapping != NULL) { UfsHc->Unmap (UfsHc, Private->TmrlMapping); } + if (Private->UtpTmrlBase != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (Private->Nutmrs * sizeof (UTP_TMRD)), Private->UtpTmrlBase); } @@ -1136,6 +1148,7 @@ UfsPassThruDriverBindingStop ( if (Private->TrlMapping != NULL) { UfsHc->Unmap (UfsHc, Private->TrlMapping); } + if (Private->UtpTrlBase != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (Private->Nutrs * sizeof (UTP_TMRD)), Private->UtpTrlBase); } @@ -1159,7 +1172,6 @@ UfsPassThruDriverBindingStop ( return Status; } - /** The user Entry Point for module UfsPassThru. The user code starts with this function. @@ -1173,11 +1185,11 @@ UfsPassThruDriverBindingStop ( EFI_STATUS EFIAPI InitializeUfsPassThru ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install driver model protocol(s). diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h index 79b86f7e6b..2b4f5d32d9 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThru.h @@ -28,7 +28,7 @@ #include "UfsPassThruHci.h" -#define UFS_PASS_THRU_SIG SIGNATURE_32 ('U', 'F', 'S', 'P') +#define UFS_PASS_THRU_SIG SIGNATURE_32 ('U', 'F', 'S', 'P') // // Lun 0~7 is for 8 common luns. @@ -38,46 +38,46 @@ // Lun 10: BOOT // Lun 11: RPMB // -#define UFS_MAX_LUNS 12 -#define UFS_WLUN_PREFIX 0xC1 -#define UFS_INIT_COMPLETION_TIMEOUT 600000 +#define UFS_MAX_LUNS 12 +#define UFS_WLUN_PREFIX 0xC1 +#define UFS_INIT_COMPLETION_TIMEOUT 600000 typedef struct { - UINT8 Lun[UFS_MAX_LUNS]; - UINT16 BitMask:12; // Bit 0~7 is 1/1 mapping to common luns. Bit 8~11 is 1/1 mapping to well-known luns. - UINT16 Rsvd:4; + UINT8 Lun[UFS_MAX_LUNS]; + UINT16 BitMask : 12; // Bit 0~7 is 1/1 mapping to common luns. Bit 8~11 is 1/1 mapping to well-known luns. + UINT16 Rsvd : 4; } UFS_EXPOSED_LUNS; typedef struct _UFS_PASS_THRU_PRIVATE_DATA { - UINT32 Signature; - EFI_HANDLE Handle; - EFI_EXT_SCSI_PASS_THRU_MODE ExtScsiPassThruMode; - EFI_EXT_SCSI_PASS_THRU_PROTOCOL ExtScsiPassThru; - EFI_UFS_DEVICE_CONFIG_PROTOCOL UfsDevConfig; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHostController; - UINTN UfsHcBase; - EDKII_UFS_HC_INFO UfsHcInfo; - EDKII_UFS_HC_DRIVER_INTERFACE UfsHcDriverInterface; - - UINT8 TaskTag; - - VOID *UtpTrlBase; - UINT8 Nutrs; - VOID *TrlMapping; - VOID *UtpTmrlBase; - UINT8 Nutmrs; - VOID *TmrlMapping; - - UFS_EXPOSED_LUNS Luns; + UINT32 Signature; + EFI_HANDLE Handle; + EFI_EXT_SCSI_PASS_THRU_MODE ExtScsiPassThruMode; + EFI_EXT_SCSI_PASS_THRU_PROTOCOL ExtScsiPassThru; + EFI_UFS_DEVICE_CONFIG_PROTOCOL UfsDevConfig; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHostController; + UINTN UfsHcBase; + EDKII_UFS_HC_INFO UfsHcInfo; + EDKII_UFS_HC_DRIVER_INTERFACE UfsHcDriverInterface; + + UINT8 TaskTag; + + VOID *UtpTrlBase; + UINT8 Nutrs; + VOID *TrlMapping; + VOID *UtpTmrlBase; + UINT8 Nutmrs; + VOID *TmrlMapping; + + UFS_EXPOSED_LUNS Luns; // // For Non-blocking operation. // - EFI_EVENT TimerEvent; - LIST_ENTRY Queue; + EFI_EVENT TimerEvent; + LIST_ENTRY Queue; } UFS_PASS_THRU_PRIVATE_DATA; -#define UFS_PASS_THRU_TRANS_REQ_SIG SIGNATURE_32 ('U', 'F', 'S', 'T') +#define UFS_PASS_THRU_TRANS_REQ_SIG SIGNATURE_32 ('U', 'F', 'S', 'T') typedef struct { UINT32 Signature; @@ -100,12 +100,12 @@ typedef struct { #define UFS_PASS_THRU_TRANS_REQ_FROM_THIS(a) \ CR(a, UFS_PASS_THRU_TRANS_REQ, TransferList, UFS_PASS_THRU_TRANS_REQ_SIG) -#define UFS_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) -#define UFS_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS(1) +#define UFS_TIMEOUT EFI_TIMER_PERIOD_SECONDS(3) +#define UFS_HC_ASYNC_TIMER EFI_TIMER_PERIOD_MILLISECONDS(1) -#define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) +#define ROUNDUP8(x) (((x) % 8 == 0) ? (x) : ((x) / 8 + 1) * 8) -#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) +#define IS_ALIGNED(addr, size) (((UINTN) (addr) & (size - 1)) == 0) #define UFS_PASS_THRU_PRIVATE_DATA_FROM_THIS(a) \ CR (a, \ @@ -129,19 +129,20 @@ typedef struct { ) typedef struct _UFS_DEVICE_MANAGEMENT_REQUEST_PACKET { - UINT64 Timeout; - VOID *DataBuffer; - UINT8 Opcode; - UINT8 DescId; - UINT8 Index; - UINT8 Selector; - UINT32 TransferLength; - UINT8 DataDirection; + UINT64 Timeout; + VOID *DataBuffer; + UINT8 Opcode; + UINT8 DescId; + UINT8 Index; + UINT8 Selector; + UINT32 TransferLength; + UINT8 DataDirection; } UFS_DEVICE_MANAGEMENT_REQUEST_PACKET; // // function prototype // + /** Tests to see if this driver supports a given controller. If a child device is provided, it further tests to see if this driver supports creating a handle for the specified child device. @@ -264,15 +265,16 @@ UfsPassThruDriverBindingStart ( EFI_STATUS EFIAPI UfsPassThruDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -320,7 +322,6 @@ UfsPassThruComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -392,11 +393,11 @@ UfsPassThruComponentNameGetDriverName ( EFI_STATUS EFIAPI UfsPassThruComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); /** @@ -443,11 +444,11 @@ UfsPassThruComponentNameGetControllerName ( EFI_STATUS EFIAPI UfsPassThruPassThru ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, - IN EFI_EVENT Event OPTIONAL + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, + IN EFI_EVENT Event OPTIONAL ); /** @@ -479,9 +480,9 @@ UfsPassThruPassThru ( EFI_STATUS EFIAPI UfsPassThruGetNextTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target, - IN OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target, + IN OUT UINT64 *Lun ); /** @@ -514,10 +515,10 @@ UfsPassThruGetNextTargetLun ( EFI_STATUS EFIAPI UfsPassThruBuildDevicePath ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath ); /** @@ -542,10 +543,10 @@ UfsPassThruBuildDevicePath ( EFI_STATUS EFIAPI UfsPassThruGetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT UINT8 **Target, - OUT UINT64 *Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT UINT8 **Target, + OUT UINT64 *Lun ); /** @@ -562,7 +563,7 @@ UfsPassThruGetTargetLun ( EFI_STATUS EFIAPI UfsPassThruResetChannel ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This ); /** @@ -587,9 +588,9 @@ UfsPassThruResetChannel ( EFI_STATUS EFIAPI UfsPassThruResetTargetLun ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN UINT8 *Target, - IN UINT64 Lun + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN UINT8 *Target, + IN UINT64 Lun ); /** @@ -617,8 +618,8 @@ UfsPassThruResetTargetLun ( EFI_STATUS EFIAPI UfsPassThruGetNextTarget ( - IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, - IN OUT UINT8 **Target + IN EFI_EXT_SCSI_PASS_THRU_PROTOCOL *This, + IN OUT UINT8 **Target ); /** @@ -664,7 +665,7 @@ UfsExecScsiCmds ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ); /** @@ -678,7 +679,7 @@ UfsControllerInit ( **/ EFI_STATUS UfsControllerStop ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ); /** @@ -697,11 +698,11 @@ UfsControllerStop ( **/ EFI_STATUS UfsAllocateAlignCommonBuffer ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINTN Size, - OUT VOID **CmdDescHost, - OUT EFI_PHYSICAL_ADDRESS *CmdDescPhyAddr, - OUT VOID **CmdDescMapping + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINTN Size, + OUT VOID **CmdDescHost, + OUT EFI_PHYSICAL_ADDRESS *CmdDescPhyAddr, + OUT VOID **CmdDescMapping ); /** @@ -717,8 +718,8 @@ UfsAllocateAlignCommonBuffer ( **/ EFI_STATUS UfsSetFlag ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 FlagId + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 FlagId ); /** @@ -735,9 +736,9 @@ UfsSetFlag ( **/ EFI_STATUS UfsReadFlag ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 FlagId, - OUT UINT8 *Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 FlagId, + OUT UINT8 *Value ); /** @@ -755,10 +756,10 @@ UfsReadFlag ( **/ EFI_STATUS UfsRwFlags ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 FlagId, - IN OUT UINT8 *Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 FlagId, + IN OUT UINT8 *Value ); /** @@ -781,13 +782,13 @@ UfsRwFlags ( **/ EFI_STATUS UfsRwDeviceDesc ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT VOID *Descriptor, - IN OUT UINT32 *DescSize + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT VOID *Descriptor, + IN OUT UINT32 *DescSize ); /** @@ -807,12 +808,12 @@ UfsRwDeviceDesc ( **/ EFI_STATUS UfsRwAttributes ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 AttrId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT32 *Attributes + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT32 *Attributes ); /** @@ -830,7 +831,7 @@ UfsRwAttributes ( **/ EFI_STATUS UfsExecNopCmds ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ); /** @@ -843,8 +844,8 @@ UfsExecNopCmds ( VOID EFIAPI ProcessAsyncTaskList ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -860,8 +861,8 @@ ProcessAsyncTaskList ( VOID EFIAPI SignalCallerEvent ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UFS_PASS_THRU_TRANS_REQ *TransReq + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UFS_PASS_THRU_TRANS_REQ *TransReq ); /** @@ -890,13 +891,13 @@ SignalCallerEvent ( EFI_STATUS EFIAPI UfsRwUfsDescriptor ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT8 *Descriptor, - IN OUT UINT32 *DescSize + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT8 *Descriptor, + IN OUT UINT32 *DescSize ); /** @@ -920,10 +921,10 @@ UfsRwUfsDescriptor ( EFI_STATUS EFIAPI UfsRwUfsFlag ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 FlagId, - IN OUT UINT8 *Flag + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 FlagId, + IN OUT UINT8 *Flag ); /** @@ -952,13 +953,13 @@ UfsRwUfsFlag ( EFI_STATUS EFIAPI UfsRwUfsAttribute ( - IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, - IN BOOLEAN Read, - IN UINT8 AttrId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT8 *Attribute, - IN OUT UINT32 *AttrSize + IN EFI_UFS_DEVICE_CONFIG_PROTOCOL *This, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT8 *Attribute, + IN OUT UINT32 *AttrSize ); /** @@ -991,9 +992,9 @@ GetUfsHcInfo ( IN UFS_PASS_THRU_PRIVATE_DATA *Private ); -extern EFI_COMPONENT_NAME_PROTOCOL gUfsPassThruComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL gUfsPassThruComponentName2; -extern EFI_DRIVER_BINDING_PROTOCOL gUfsPassThruDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL gUfsPassThruComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL gUfsPassThruComponentName2; +extern EFI_DRIVER_BINDING_PROTOCOL gUfsPassThruDriverBinding; extern EDKII_UFS_HC_PLATFORM_PROTOCOL *mUfsHcPlatform; #endif diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.c b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.c index 0b1030ab47..eba35cc669 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.c +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.c @@ -25,9 +25,9 @@ **/ EFI_STATUS UfsMmioRead32 ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINTN Offset, - OUT UINT32 *Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINTN Offset, + OUT UINT32 *Value ) { EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; @@ -55,9 +55,9 @@ UfsMmioRead32 ( **/ EFI_STATUS UfsMmioWrite32 ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINTN Offset, - IN UINT32 Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINTN Offset, + IN UINT32 Value ) { EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; @@ -87,17 +87,17 @@ UfsMmioWrite32 ( **/ EFI_STATUS UfsWaitMemSet ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINTN Offset, - IN UINT32 MaskValue, - IN UINT32 TestValue, - IN UINT64 Timeout + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINTN Offset, + IN UINT32 MaskValue, + IN UINT32 TestValue, + IN UINT64 Timeout ) { - UINT32 Value; - UINT64 Delay; - BOOLEAN InfiniteWait; - EFI_STATUS Status; + UINT32 Value; + UINT64 Delay; + BOOLEAN InfiniteWait; + EFI_STATUS Status; if (Timeout == 0) { InfiniteWait = TRUE; @@ -128,7 +128,6 @@ UfsWaitMemSet ( MicroSecondDelay (1); Delay--; - } while (InfiniteWait || (Delay > 0)); return EFI_TIMEOUT; @@ -143,8 +142,8 @@ UfsWaitMemSet ( **/ VOID DumpUicCmdExecResult ( - IN UINT8 UicOpcode, - IN UINT8 Result + IN UINT8 UicOpcode, + IN UINT8 Result ) { if (UicOpcode <= UfsUicDmePeerSet) { @@ -181,7 +180,7 @@ DumpUicCmdExecResult ( case 0x0A: DEBUG ((DEBUG_VERBOSE, "UIC configuration command fails - DME_FAILURE\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -192,7 +191,7 @@ DumpUicCmdExecResult ( case 0x01: DEBUG ((DEBUG_VERBOSE, "UIC control command fails - FAILURE\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -207,7 +206,7 @@ DumpUicCmdExecResult ( **/ VOID DumpQueryResponseResult ( - IN UINT8 Result + IN UINT8 Result ) { switch (Result) { @@ -241,7 +240,7 @@ DumpQueryResponseResult ( case 0xFF: DEBUG ((DEBUG_VERBOSE, "Query Response with General Failure\n")); break; - default : + default: ASSERT (FALSE); break; } @@ -257,18 +256,18 @@ DumpQueryResponseResult ( **/ VOID SwapLittleEndianToBigEndian ( - IN OUT UINT8 *Buffer, - IN UINT32 BufferSize + IN OUT UINT8 *Buffer, + IN UINT32 BufferSize ) { - UINT32 Index; - UINT8 Temp; - UINT32 SwapCount; + UINT32 Index; + UINT8 Temp; + UINT32 SwapCount; SwapCount = BufferSize / 2; for (Index = 0; Index < SwapCount; Index++) { - Temp = Buffer[Index]; - Buffer[Index] = Buffer[BufferSize - 1 - Index]; + Temp = Buffer[Index]; + Buffer[Index] = Buffer[BufferSize - 1 - Index]; Buffer[BufferSize - 1 - Index] = Temp; } } @@ -287,32 +286,32 @@ SwapLittleEndianToBigEndian ( **/ VOID UfsFillTsfOfQueryReqUpiu ( - IN OUT UTP_UPIU_TSF *TsfBase, - IN UINT8 Opcode, - IN UINT8 DescId OPTIONAL, - IN UINT8 Index OPTIONAL, - IN UINT8 Selector OPTIONAL, - IN UINT16 Length OPTIONAL, - IN UINT32 Value OPTIONAL + IN OUT UTP_UPIU_TSF *TsfBase, + IN UINT8 Opcode, + IN UINT8 DescId OPTIONAL, + IN UINT8 Index OPTIONAL, + IN UINT8 Selector OPTIONAL, + IN UINT16 Length OPTIONAL, + IN UINT32 Value OPTIONAL ) { ASSERT (TsfBase != NULL); ASSERT (Opcode <= UtpQueryFuncOpcodeTogFlag); - TsfBase->Opcode = Opcode; + TsfBase->Opcode = Opcode; if (Opcode != UtpQueryFuncOpcodeNop) { TsfBase->DescId = DescId; TsfBase->Index = Index; TsfBase->Selector = Selector; if ((Opcode == UtpQueryFuncOpcodeRdDesc) || (Opcode == UtpQueryFuncOpcodeWrDesc)) { - SwapLittleEndianToBigEndian ((UINT8*)&Length, sizeof (Length)); + SwapLittleEndianToBigEndian ((UINT8 *)&Length, sizeof (Length)); TsfBase->Length = Length; } if (Opcode == UtpQueryFuncOpcodeWrAttr) { - SwapLittleEndianToBigEndian ((UINT8*)&Value, sizeof (Value)); - TsfBase->Value = Value; + SwapLittleEndianToBigEndian ((UINT8 *)&Value, sizeof (Value)); + TsfBase->Value = Value; } } } @@ -333,16 +332,16 @@ UfsFillTsfOfQueryReqUpiu ( **/ EFI_STATUS UfsInitCommandUpiu ( - IN OUT UTP_COMMAND_UPIU *Command, - IN UINT8 Lun, - IN UINT8 TaskTag, - IN UINT8 *Cdb, - IN UINT8 CdbLength, - IN UFS_DATA_DIRECTION DataDirection, - IN UINT32 ExpDataTranLen + IN OUT UTP_COMMAND_UPIU *Command, + IN UINT8 Lun, + IN UINT8 TaskTag, + IN UINT8 *Cdb, + IN UINT8 CdbLength, + IN UFS_DATA_DIRECTION DataDirection, + IN UINT32 ExpDataTranLen ) { - UINT8 Flags; + UINT8 Flags; ASSERT ((Command != NULL) && (Cdb != NULL)); @@ -365,7 +364,7 @@ UfsInitCommandUpiu ( Command->Lun = Lun; Command->TaskTag = TaskTag; Command->CmdSet = 0x00; - SwapLittleEndianToBigEndian ((UINT8*)&ExpDataTranLen, sizeof (ExpDataTranLen)); + SwapLittleEndianToBigEndian ((UINT8 *)&ExpDataTranLen, sizeof (ExpDataTranLen)); Command->ExpDataTranLen = ExpDataTranLen; CopyMem (Command->Cdb, Cdb, CdbLength); @@ -385,15 +384,15 @@ UfsInitCommandUpiu ( **/ EFI_STATUS UfsInitUtpPrdt ( - IN UTP_TR_PRD *Prdt, - IN VOID *Buffer, - IN UINT32 BufferSize + IN UTP_TR_PRD *Prdt, + IN VOID *Buffer, + IN UINT32 BufferSize ) { - UINT32 PrdtIndex; - UINT32 RemainingLen; - UINT8 *Remaining; - UINTN PrdtNumber; + UINT32 PrdtIndex; + UINT32 RemainingLen; + UINT8 *Remaining; + UINTN PrdtNumber; ASSERT (((UINTN)Buffer & (BIT0 | BIT1)) == 0); ASSERT ((BufferSize & (BIT1 | BIT0)) == 0); @@ -415,8 +414,8 @@ UfsInitUtpPrdt ( Prdt[PrdtIndex].DbAddr = (UINT32)RShiftU64 ((UINT64)(UINTN)Remaining, 2); Prdt[PrdtIndex].DbAddrU = (UINT32)RShiftU64 ((UINT64)(UINTN)Remaining, 32); - RemainingLen -= UFS_MAX_DATA_LEN_PER_PRD; - Remaining += UFS_MAX_DATA_LEN_PER_PRD; + RemainingLen -= UFS_MAX_DATA_LEN_PER_PRD; + Remaining += UFS_MAX_DATA_LEN_PER_PRD; } return EFI_SUCCESS; @@ -439,14 +438,14 @@ UfsInitUtpPrdt ( **/ EFI_STATUS UfsInitQueryRequestUpiu ( - IN OUT UTP_QUERY_REQ_UPIU *QueryReq, - IN UINT8 TaskTag, - IN UINT8 Opcode, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN UINTN DataSize OPTIONAL, - IN UINT8 *Data OPTIONAL + IN OUT UTP_QUERY_REQ_UPIU *QueryReq, + IN UINT8 TaskTag, + IN UINT8 Opcode, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN UINTN DataSize OPTIONAL, + IN UINT8 *Data OPTIONAL ) { ASSERT (QueryReq != NULL); @@ -460,7 +459,7 @@ UfsInitQueryRequestUpiu ( } if (Opcode == UtpQueryFuncOpcodeWrAttr) { - UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, 0, *(UINT32*)Data); + UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, 0, *(UINT32 *)Data); } else if ((Opcode == UtpQueryFuncOpcodeRdDesc) || (Opcode == UtpQueryFuncOpcodeWrDesc)) { UfsFillTsfOfQueryReqUpiu (&QueryReq->Tsf, Opcode, DescId, Index, Selector, (UINT16)DataSize, 0); } else { @@ -470,7 +469,7 @@ UfsInitQueryRequestUpiu ( if (Opcode == UtpQueryFuncOpcodeWrDesc) { CopyMem (QueryReq + 1, Data, DataSize); - SwapLittleEndianToBigEndian ((UINT8*)&DataSize, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&DataSize, sizeof (UINT16)); QueryReq->DataSegLen = (UINT16)DataSize; } @@ -498,17 +497,17 @@ UfsCreateScsiCommandDesc ( IN UINT8 Lun, IN EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet, IN UTP_TRD *Trd, - OUT VOID **CmdDescHost, - OUT VOID **CmdDescMapping + OUT VOID **CmdDescHost, + OUT VOID **CmdDescMapping ) { - UINTN TotalLen; - UINTN PrdtNumber; - UTP_COMMAND_UPIU *CommandUpiu; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - EFI_STATUS Status; - UINT32 DataLen; - UFS_DATA_DIRECTION DataDirection; + UINTN TotalLen; + UINTN PrdtNumber; + UTP_COMMAND_UPIU *CommandUpiu; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + EFI_STATUS Status; + UINT32 DataLen; + UFS_DATA_DIRECTION DataDirection; ASSERT ((Private != NULL) && (Packet != NULL) && (Trd != NULL)); @@ -526,14 +525,14 @@ UfsCreateScsiCommandDesc ( PrdtNumber = (UINTN)DivU64x32 ((UINT64)DataLen + UFS_MAX_DATA_LEN_PER_PRD - 1, UFS_MAX_DATA_LEN_PER_PRD); - TotalLen = ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU)) + PrdtNumber * sizeof (UTP_TR_PRD); + TotalLen = ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU)) + PrdtNumber * sizeof (UTP_TR_PRD); Status = UfsAllocateAlignCommonBuffer (Private, TotalLen, CmdDescHost, &CmdDescPhyAddr, CmdDescMapping); if (EFI_ERROR (Status)) { return Status; } - CommandUpiu = (UTP_COMMAND_UPIU*)*CmdDescHost; + CommandUpiu = (UTP_COMMAND_UPIU *)*CmdDescHost; UfsInitCommandUpiu (CommandUpiu, Lun, Private->TaskTag++, Packet->Cdb, Packet->CdbLength, DataDirection, DataLen); @@ -575,18 +574,18 @@ UfsCreateDMCommandDesc ( IN UFS_PASS_THRU_PRIVATE_DATA *Private, IN UFS_DEVICE_MANAGEMENT_REQUEST_PACKET *Packet, IN UTP_TRD *Trd, - OUT VOID **CmdDescHost, - OUT VOID **CmdDescMapping + OUT VOID **CmdDescHost, + OUT VOID **CmdDescMapping ) { - UINTN TotalLen; - UTP_QUERY_REQ_UPIU *QueryReqUpiu; - UINT8 Opcode; - UINT32 DataSize; - UINT8 *Data; - UINT8 DataDirection; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - EFI_STATUS Status; + UINTN TotalLen; + UTP_QUERY_REQ_UPIU *QueryReqUpiu; + UINT8 Opcode; + UINT32 DataSize; + UINT8 *Data; + UINT8 DataDirection; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + EFI_STATUS Status; ASSERT ((Private != NULL) && (Packet != NULL) && (Trd != NULL)); @@ -600,9 +599,10 @@ UfsCreateDMCommandDesc ( Data = Packet->DataBuffer; if ((Opcode == UtpQueryFuncOpcodeWrDesc) || (Opcode == UtpQueryFuncOpcodeRdDesc)) { - if (DataSize == 0 || Data == NULL) { + if ((DataSize == 0) || (Data == NULL)) { return EFI_INVALID_PARAMETER; } + TotalLen = ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)) + ROUNDUP8 (DataSize); } else { TotalLen = ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)); @@ -616,7 +616,7 @@ UfsCreateDMCommandDesc ( // // Initialize UTP QUERY REQUEST UPIU // - QueryReqUpiu = (UTP_QUERY_REQ_UPIU*)*CmdDescHost; + QueryReqUpiu = (UTP_QUERY_REQ_UPIU *)*CmdDescHost; ASSERT (QueryReqUpiu != NULL); UfsInitQueryRequestUpiu ( QueryReqUpiu, @@ -640,11 +640,11 @@ UfsCreateDMCommandDesc ( Trd->UcdBa = (UINT32)RShiftU64 ((UINT64)CmdDescPhyAddr, 7); Trd->UcdBaU = (UINT32)RShiftU64 ((UINT64)CmdDescPhyAddr, 32); if (Opcode == UtpQueryFuncOpcodeWrDesc) { - Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)), sizeof (UINT32)); - Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); + Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)), sizeof (UINT32)); + Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); } else { - Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); - Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)), sizeof (UINT32)); + Trd->RuL = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_RESP_UPIU)) + ROUNDUP8 (DataSize), sizeof (UINT32)); + Trd->RuO = (UINT16)DivU64x32 ((UINT64)ROUNDUP8 (sizeof (UTP_QUERY_REQ_UPIU)), sizeof (UINT32)); } return EFI_SUCCESS; @@ -665,16 +665,16 @@ UfsCreateDMCommandDesc ( **/ EFI_STATUS UfsCreateNopCommandDesc ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UTP_TRD *Trd, - OUT VOID **CmdDescHost, - OUT VOID **CmdDescMapping + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UTP_TRD *Trd, + OUT VOID **CmdDescHost, + OUT VOID **CmdDescMapping ) { - UINTN TotalLen; - UTP_NOP_OUT_UPIU *NopOutUpiu; - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + UINTN TotalLen; + UTP_NOP_OUT_UPIU *NopOutUpiu; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; ASSERT ((Private != NULL) && (Trd != NULL)); @@ -684,7 +684,7 @@ UfsCreateNopCommandDesc ( return Status; } - NopOutUpiu = (UTP_NOP_OUT_UPIU*)*CmdDescHost; + NopOutUpiu = (UTP_NOP_OUT_UPIU *)*CmdDescHost; ASSERT (NopOutUpiu != NULL); NopOutUpiu->TaskTag = Private->TaskTag++; @@ -716,23 +716,23 @@ UfsCreateNopCommandDesc ( **/ EFI_STATUS UfsFindAvailableSlotInTrl ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - OUT UINT8 *Slot + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + OUT UINT8 *Slot ) { - UINT8 Nutrs; - UINT8 Index; - UINT32 Data; - EFI_STATUS Status; + UINT8 Nutrs; + UINT8 Index; + UINT32 Data; + EFI_STATUS Status; ASSERT ((Private != NULL) && (Slot != NULL)); - Status = UfsMmioRead32 (Private, UFS_HC_UTRLDBR_OFFSET, &Data); + Status = UfsMmioRead32 (Private, UFS_HC_UTRLDBR_OFFSET, &Data); if (EFI_ERROR (Status)) { return Status; } - Nutrs = (UINT8)((Private->UfsHcInfo.Capabilities & UFS_HC_CAP_NUTRS) + 1); + Nutrs = (UINT8)((Private->UfsHcInfo.Capabilities & UFS_HC_CAP_NUTRS) + 1); for (Index = 0; Index < Nutrs; Index++) { if ((Data & (BIT0 << Index)) == 0) { @@ -744,7 +744,6 @@ UfsFindAvailableSlotInTrl ( return EFI_NOT_READY; } - /** Start specified slot in transfer list of a UFS device. @@ -754,12 +753,12 @@ UfsFindAvailableSlotInTrl ( **/ EFI_STATUS UfsStartExecCmd ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 Slot + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; Status = UfsMmioRead32 (Private, UFS_HC_UTRLRSR_OFFSET, &Data); if (EFI_ERROR (Status)) { @@ -790,12 +789,12 @@ UfsStartExecCmd ( **/ EFI_STATUS UfsStopExecCmd ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 Slot + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 Slot ) { - UINT32 Data; - EFI_STATUS Status; + UINT32 Data; + EFI_STATUS Status; Status = UfsMmioRead32 (Private, UFS_HC_UTRLDBR_OFFSET, &Data); if (EFI_ERROR (Status)) { @@ -837,14 +836,14 @@ UfsGetReturnDataFromQueryResponse ( UINT16 ReturnDataSize; UINT32 ReturnData; - if (Packet == NULL || QueryResp == NULL) { + if ((Packet == NULL) || (QueryResp == NULL)) { return EFI_INVALID_PARAMETER; } switch (Packet->Opcode) { case UtpQueryFuncOpcodeRdDesc: ReturnDataSize = QueryResp->Tsf.Length; - SwapLittleEndianToBigEndian ((UINT8*)&ReturnDataSize, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnDataSize, sizeof (UINT16)); // // Make sure the hardware device does not return more data than expected. // @@ -857,7 +856,7 @@ UfsGetReturnDataFromQueryResponse ( break; case UtpQueryFuncOpcodeWrDesc: ReturnDataSize = QueryResp->Tsf.Length; - SwapLittleEndianToBigEndian ((UINT8*)&ReturnDataSize, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnDataSize, sizeof (UINT16)); Packet->TransferLength = ReturnDataSize; break; case UtpQueryFuncOpcodeRdFlag: @@ -867,12 +866,12 @@ UfsGetReturnDataFromQueryResponse ( // // The 'FLAG VALUE' field is at byte offset 3 of QueryResp->Tsf.Value // - *((UINT8*)(Packet->DataBuffer)) = *((UINT8*)&(QueryResp->Tsf.Value) + 3); + *((UINT8 *)(Packet->DataBuffer)) = *((UINT8 *)&(QueryResp->Tsf.Value) + 3); break; case UtpQueryFuncOpcodeRdAttr: case UtpQueryFuncOpcodeWrAttr: ReturnData = QueryResp->Tsf.Value; - SwapLittleEndianToBigEndian ((UINT8*) &ReturnData, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ReturnData, sizeof (UINT32)); CopyMem (Packet->DataBuffer, &ReturnData, sizeof (UINT32)); break; default: @@ -918,7 +917,7 @@ UfsSendDmRequestRetry ( return Status; } - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; // // Fill transfer request descriptor to this slot. // @@ -928,8 +927,8 @@ UfsSendDmRequestRetry ( return Status; } - UfsHc = Private->UfsHostController; - QueryResp = (UTP_QUERY_RESP_UPIU*)((UINT8*)CmdDescHost + Trd->RuO * sizeof (UINT32)); + UfsHc = Private->UfsHostController; + QueryResp = (UTP_QUERY_RESP_UPIU *)((UINT8 *)CmdDescHost + Trd->RuO * sizeof (UINT32)); ASSERT (QueryResp != NULL); CmdDescSize = Trd->RuO * sizeof (UINT32) + Trd->RuL * sizeof (UINT32); @@ -946,17 +945,19 @@ UfsSendDmRequestRetry ( goto Exit; } - if (Trd->Ocs != 0 || QueryResp->QueryResp != UfsUtpQueryResponseSuccess) { + if ((Trd->Ocs != 0) || (QueryResp->QueryResp != UfsUtpQueryResponseSuccess)) { DEBUG ((DEBUG_ERROR, "Failed to send query request, OCS = %X, QueryResp = %X\n", Trd->Ocs, QueryResp->QueryResp)); DumpQueryResponseResult (QueryResp->QueryResp); if ((QueryResp->QueryResp == UfsUtpQueryResponseInvalidSelector) || (QueryResp->QueryResp == UfsUtpQueryResponseInvalidIndex) || - (QueryResp->QueryResp == UfsUtpQueryResponseInvalidIdn)) { + (QueryResp->QueryResp == UfsUtpQueryResponseInvalidIdn)) + { Status = EFI_INVALID_PARAMETER; } else { Status = EFI_DEVICE_ERROR; } + goto Exit; } @@ -974,6 +975,7 @@ Exit: if (CmdDescMapping != NULL) { UfsHc->Unmap (UfsHc, CmdDescMapping); } + if (CmdDescHost != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (CmdDescSize), CmdDescHost); } @@ -1005,7 +1007,7 @@ UfsSendDmRequest ( Status = EFI_SUCCESS; - for (Retry = 0; Retry < 5; Retry ++) { + for (Retry = 0; Retry < 5; Retry++) { Status = UfsSendDmRequestRetry (Private, Packet); if (!EFI_ERROR (Status)) { return EFI_SUCCESS; @@ -1038,17 +1040,17 @@ UfsSendDmRequest ( **/ EFI_STATUS UfsRwDeviceDesc ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 DescId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT VOID *Descriptor, - IN OUT UINT32 *DescSize + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 DescId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT VOID *Descriptor, + IN OUT UINT32 *DescSize ) { - UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; - EFI_STATUS Status; + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + EFI_STATUS Status; if (DescSize == NULL) { return EFI_INVALID_PARAMETER; @@ -1057,18 +1059,19 @@ UfsRwDeviceDesc ( ZeroMem (&Packet, sizeof (UFS_DEVICE_MANAGEMENT_REQUEST_PACKET)); if (Read) { - Packet.DataDirection = UfsDataIn; - Packet.Opcode = UtpQueryFuncOpcodeRdDesc; + Packet.DataDirection = UfsDataIn; + Packet.Opcode = UtpQueryFuncOpcodeRdDesc; } else { - Packet.DataDirection = UfsDataOut; - Packet.Opcode = UtpQueryFuncOpcodeWrDesc; + Packet.DataDirection = UfsDataOut; + Packet.Opcode = UtpQueryFuncOpcodeWrDesc; } - Packet.DataBuffer = Descriptor; - Packet.TransferLength = *DescSize; - Packet.DescId = DescId; - Packet.Index = Index; - Packet.Selector = Selector; - Packet.Timeout = UFS_TIMEOUT; + + Packet.DataBuffer = Descriptor; + Packet.TransferLength = *DescSize; + Packet.DescId = DescId; + Packet.Index = Index; + Packet.Selector = Selector; + Packet.Timeout = UFS_TIMEOUT; Status = UfsSendDmRequest (Private, &Packet); if (EFI_ERROR (Status)) { @@ -1099,30 +1102,31 @@ UfsRwDeviceDesc ( **/ EFI_STATUS UfsRwAttributes ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 AttrId, - IN UINT8 Index, - IN UINT8 Selector, - IN OUT UINT32 *Attributes + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 AttrId, + IN UINT8 Index, + IN UINT8 Selector, + IN OUT UINT32 *Attributes ) { - UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; ZeroMem (&Packet, sizeof (UFS_DEVICE_MANAGEMENT_REQUEST_PACKET)); if (Read) { - Packet.DataDirection = UfsDataIn; - Packet.Opcode = UtpQueryFuncOpcodeRdAttr; + Packet.DataDirection = UfsDataIn; + Packet.Opcode = UtpQueryFuncOpcodeRdAttr; } else { - Packet.DataDirection = UfsDataOut; - Packet.Opcode = UtpQueryFuncOpcodeWrAttr; + Packet.DataDirection = UfsDataOut; + Packet.Opcode = UtpQueryFuncOpcodeWrAttr; } - Packet.DataBuffer = Attributes; - Packet.DescId = AttrId; - Packet.Index = Index; - Packet.Selector = Selector; - Packet.Timeout = UFS_TIMEOUT; + + Packet.DataBuffer = Attributes; + Packet.DescId = AttrId; + Packet.Index = Index; + Packet.Selector = Selector; + Packet.Timeout = UFS_TIMEOUT; return UfsSendDmRequest (Private, &Packet); } @@ -1143,13 +1147,13 @@ UfsRwAttributes ( **/ EFI_STATUS UfsRwFlags ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN BOOLEAN Read, - IN UINT8 FlagId, - IN OUT UINT8 *Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN BOOLEAN Read, + IN UINT8 FlagId, + IN OUT UINT8 *Value ) { - UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; + UFS_DEVICE_MANAGEMENT_REQUEST_PACKET Packet; if (Value == NULL) { return EFI_INVALID_PARAMETER; @@ -1159,23 +1163,24 @@ UfsRwFlags ( if (Read) { ASSERT (Value != NULL); - Packet.DataDirection = UfsDataIn; - Packet.Opcode = UtpQueryFuncOpcodeRdFlag; + Packet.DataDirection = UfsDataIn; + Packet.Opcode = UtpQueryFuncOpcodeRdFlag; } else { - Packet.DataDirection = UfsDataOut; + Packet.DataDirection = UfsDataOut; if (*Value == 1) { - Packet.Opcode = UtpQueryFuncOpcodeSetFlag; + Packet.Opcode = UtpQueryFuncOpcodeSetFlag; } else if (*Value == 0) { - Packet.Opcode = UtpQueryFuncOpcodeClrFlag; + Packet.Opcode = UtpQueryFuncOpcodeClrFlag; } else { return EFI_INVALID_PARAMETER; } } - Packet.DataBuffer = Value; - Packet.DescId = FlagId; - Packet.Index = 0; - Packet.Selector = 0; - Packet.Timeout = UFS_TIMEOUT; + + Packet.DataBuffer = Value; + Packet.DescId = FlagId; + Packet.Index = 0; + Packet.Selector = 0; + Packet.Timeout = UFS_TIMEOUT; return UfsSendDmRequest (Private, &Packet); } @@ -1193,12 +1198,12 @@ UfsRwFlags ( **/ EFI_STATUS UfsSetFlag ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 FlagId + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 FlagId ) { - EFI_STATUS Status; - UINT8 Value; + EFI_STATUS Status; + UINT8 Value; Value = 1; Status = UfsRwFlags (Private, FALSE, FlagId, &Value); @@ -1220,12 +1225,12 @@ UfsSetFlag ( **/ EFI_STATUS UfsReadFlag ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINT8 FlagId, - OUT UINT8 *Value + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINT8 FlagId, + OUT UINT8 *Value ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UfsRwFlags (Private, TRUE, FlagId, Value); @@ -1247,17 +1252,17 @@ UfsReadFlag ( **/ EFI_STATUS UfsExecNopCmds ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINT8 Slot; - UTP_TRD *Trd; - UTP_NOP_IN_UPIU *NopInUpiu; - UINT32 CmdDescSize; - VOID *CmdDescHost; - VOID *CmdDescMapping; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + EFI_STATUS Status; + UINT8 Slot; + UTP_TRD *Trd; + UTP_NOP_IN_UPIU *NopInUpiu; + UINT32 CmdDescSize; + VOID *CmdDescHost; + VOID *CmdDescMapping; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; // // Find out which slot of transfer request list is available. @@ -1267,7 +1272,7 @@ UfsExecNopCmds ( return Status; } - Trd = ((UTP_TRD*)Private->UtpTrlBase) + Slot; + Trd = ((UTP_TRD *)Private->UtpTrlBase) + Slot; Status = UfsCreateNopCommandDesc (Private, Trd, &CmdDescHost, &CmdDescMapping); if (EFI_ERROR (Status)) { return Status; @@ -1276,8 +1281,8 @@ UfsExecNopCmds ( // // Check the transfer request result. // - UfsHc = Private->UfsHostController; - NopInUpiu = (UTP_NOP_IN_UPIU*)((UINT8*)CmdDescHost + Trd->RuO * sizeof (UINT32)); + UfsHc = Private->UfsHostController; + NopInUpiu = (UTP_NOP_IN_UPIU *)((UINT8 *)CmdDescHost + Trd->RuO * sizeof (UINT32)); ASSERT (NopInUpiu != NULL); CmdDescSize = Trd->RuO * sizeof (UINT32) + Trd->RuL * sizeof (UINT32); @@ -1308,6 +1313,7 @@ Exit: if (CmdDescMapping != NULL) { UfsHc->Unmap (UfsHc, CmdDescMapping); } + if (CmdDescHost != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (CmdDescSize), CmdDescHost); } @@ -1346,6 +1352,7 @@ UfsReconcileDataTransferBuffer ( if (TransReq->Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ) { CopyMem (TransReq->Packet->InDataBuffer, TransReq->AlignedDataBuf, TransReq->Packet->InTransferLength); } + // // Wipe out the transfer buffer in case it contains sensitive data. // @@ -1393,14 +1400,16 @@ UfsPrepareDataTransferBuffer ( if (DataBuf == NULL) { return EFI_DEVICE_ERROR; } + ZeroMem (DataBuf, DataLen); - TransReq->AlignedDataBuf = DataBuf; + TransReq->AlignedDataBuf = DataBuf; TransReq->AlignedDataBufSize = DataLen; } else { - DataLen = TransReq->Packet->InTransferLength; - DataBuf = TransReq->Packet->InDataBuffer; + DataLen = TransReq->Packet->InTransferLength; + DataBuf = TransReq->Packet->InDataBuffer; } - Flag = EdkiiUfsHcOperationBusMasterWrite; + + Flag = EdkiiUfsHcOperationBusMasterWrite; } else { if (((UINTN)TransReq->Packet->OutDataBuffer % 4 != 0) || (TransReq->Packet->OutTransferLength % 4 != 0)) { DataLen = TransReq->Packet->OutTransferLength + (4 - (TransReq->Packet->OutTransferLength % 4)); @@ -1408,14 +1417,16 @@ UfsPrepareDataTransferBuffer ( if (DataBuf == NULL) { return EFI_DEVICE_ERROR; } + CopyMem (DataBuf, TransReq->Packet->OutDataBuffer, TransReq->Packet->OutTransferLength); - TransReq->AlignedDataBuf = DataBuf; + TransReq->AlignedDataBuf = DataBuf; TransReq->AlignedDataBufSize = DataLen; } else { - DataLen = TransReq->Packet->OutTransferLength; - DataBuf = TransReq->Packet->OutDataBuffer; + DataLen = TransReq->Packet->OutTransferLength; + DataBuf = TransReq->Packet->OutDataBuffer; } - Flag = EdkiiUfsHcOperationBusMasterRead; + + Flag = EdkiiUfsHcOperationBusMasterRead; } if (DataLen != 0) { @@ -1438,6 +1449,7 @@ UfsPrepareDataTransferBuffer ( FreeAlignedPages (TransReq->AlignedDataBuf, EFI_SIZE_TO_PAGES (TransReq->AlignedDataBufSize)); TransReq->AlignedDataBuf = NULL; } + return EFI_DEVICE_ERROR; } } @@ -1445,9 +1457,9 @@ UfsPrepareDataTransferBuffer ( // // Fill PRDT table of Command UPIU for executed SCSI cmd. // - PrdtBase = (UTP_TR_PRD*)((UINT8*)TransReq->CmdDescHost + ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU))); + PrdtBase = (UTP_TR_PRD *)((UINT8 *)TransReq->CmdDescHost + ROUNDUP8 (sizeof (UTP_COMMAND_UPIU)) + ROUNDUP8 (sizeof (UTP_RESPONSE_UPIU))); ASSERT (PrdtBase != NULL); - UfsInitUtpPrdt (PrdtBase, (VOID*)(UINTN)DataBufPhyAddr, DataLen); + UfsInitUtpPrdt (PrdtBase, (VOID *)(UINTN)DataBufPhyAddr, DataLen); return EFI_SUCCESS; } @@ -1484,13 +1496,13 @@ UfsExecScsiCmds ( IN EFI_EVENT Event OPTIONAL ) { - EFI_STATUS Status; - UTP_RESPONSE_UPIU *Response; - UINT16 SenseDataLen; - UINT32 ResTranCount; - EFI_TPL OldTpl; - UFS_PASS_THRU_TRANS_REQ *TransReq; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + EFI_STATUS Status; + UTP_RESPONSE_UPIU *Response; + UINT16 SenseDataLen; + UINT32 ResTranCount; + EFI_TPL OldTpl; + UFS_PASS_THRU_TRANS_REQ *TransReq; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; TransReq = AllocateZeroPool (sizeof (UFS_PASS_THRU_TRANS_REQ)); if (TransReq == NULL) { @@ -1501,7 +1513,7 @@ UfsExecScsiCmds ( TransReq->TimeoutRemain = Packet->Timeout; TransReq->Packet = Packet; - UfsHc = Private->UfsHostController; + UfsHc = Private->UfsHostController; // // Find out which slot of transfer request list is available. // @@ -1510,7 +1522,7 @@ UfsExecScsiCmds ( return Status; } - TransReq->Trd = ((UTP_TRD*)Private->UtpTrlBase) + TransReq->Slot; + TransReq->Trd = ((UTP_TRD *)Private->UtpTrlBase) + TransReq->Slot; // // Fill transfer request descriptor to this slot. @@ -1538,7 +1550,7 @@ UfsExecScsiCmds ( // Insert the async SCSI cmd to the Async I/O list // if (Event != NULL) { - OldTpl = gBS->RaiseTPL (TPL_NOTIFY); + OldTpl = gBS->RaiseTPL (TPL_NOTIFY); TransReq->CallerEvent = Event; InsertTailList (&Private->Queue, &TransReq->TransferList); gBS->RestoreTPL (OldTpl); @@ -1567,10 +1579,10 @@ UfsExecScsiCmds ( // // Get sense data if exists // - Response = (UTP_RESPONSE_UPIU*)((UINT8*)TransReq->CmdDescHost + TransReq->Trd->RuO * sizeof (UINT32)); + Response = (UTP_RESPONSE_UPIU *)((UINT8 *)TransReq->CmdDescHost + TransReq->Trd->RuO * sizeof (UINT32)); ASSERT (Response != NULL); SenseDataLen = Response->SenseDataLen; - SwapLittleEndianToBigEndian ((UINT8*)&SenseDataLen, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&SenseDataLen, sizeof (UINT16)); if ((Packet->SenseDataLength != 0) && (Packet->SenseData != NULL)) { // @@ -1598,13 +1610,13 @@ UfsExecScsiCmds ( if (Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ) { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->InTransferLength -= ResTranCount; } } else { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->OutTransferLength -= ResTranCount; } } @@ -1623,12 +1635,15 @@ Exit1: if (TransReq->CmdDescMapping != NULL) { UfsHc->Unmap (UfsHc, TransReq->CmdDescMapping); } + if (TransReq->CmdDescHost != NULL) { UfsHc->FreeBuffer (UfsHc, EFI_SIZE_TO_PAGES (TransReq->CmdDescSize), TransReq->CmdDescHost); } + if (TransReq != NULL) { FreePool (TransReq); } + return Status; } @@ -1644,8 +1659,8 @@ Exit1: **/ EFI_STATUS UfsExecUicCommands ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN OUT EDKII_UIC_COMMAND *UicCommand + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN OUT EDKII_UIC_COMMAND *UicCommand ) { EFI_STATUS Status; @@ -1703,7 +1718,7 @@ UfsExecUicCommands ( // UFS 2.0 spec section 5.3.1 Offset:0x20 IS.Bit10 UIC Command Completion Status (UCCS) // This bit is set to '1' by the host controller upon completion of a UIC command. // - Status = UfsWaitMemSet (Private, UFS_HC_IS_OFFSET, UFS_HC_IS_UCCS, UFS_HC_IS_UCCS, UFS_TIMEOUT); + Status = UfsWaitMemSet (Private, UFS_HC_IS_OFFSET, UFS_HC_IS_UCCS, UFS_HC_IS_UCCS, UFS_TIMEOUT); if (EFI_ERROR (Status)) { return Status; } @@ -1713,14 +1728,16 @@ UfsExecUicCommands ( if (EFI_ERROR (Status)) { return Status; } + Status = UfsMmioRead32 (Private, UFS_HC_UCMD_ARG3_OFFSET, &UicCommand->Arg3); if (EFI_ERROR (Status)) { return Status; } + if ((UicCommand->Arg2 & 0xFF) != 0) { - DEBUG_CODE_BEGIN(); - DumpUicCmdExecResult ((UINT8)UicCommand->Opcode, (UINT8)(UicCommand->Arg2 & 0xFF)); - DEBUG_CODE_END(); + DEBUG_CODE_BEGIN (); + DumpUicCmdExecResult ((UINT8)UicCommand->Opcode, (UINT8)(UicCommand->Arg2 & 0xFF)); + DEBUG_CODE_END (); return EFI_DEVICE_ERROR; } } @@ -1744,17 +1761,17 @@ UfsExecUicCommands ( **/ EFI_STATUS UfsAllocateAlignCommonBuffer ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UINTN Size, - OUT VOID **CmdDescHost, - OUT EFI_PHYSICAL_ADDRESS *CmdDescPhyAddr, - OUT VOID **CmdDescMapping + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UINTN Size, + OUT VOID **CmdDescHost, + OUT EFI_PHYSICAL_ADDRESS *CmdDescPhyAddr, + OUT VOID **CmdDescMapping ) { - EFI_STATUS Status; - UINTN Bytes; - BOOLEAN Is32BitAddr; - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + EFI_STATUS Status; + UINTN Bytes; + BOOLEAN Is32BitAddr; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; if ((Private->UfsHcInfo.Capabilities & UFS_HC_CAP_64ADDR) == UFS_HC_CAP_64ADDR) { Is32BitAddr = FALSE; @@ -1831,13 +1848,13 @@ UfsAllocateAlignCommonBuffer ( **/ EFI_STATUS UfsEnableHostController ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINT32 Data; + EFI_STATUS Status; + UINT32 Data; - if (mUfsHcPlatform != NULL && mUfsHcPlatform->Callback != NULL) { + if ((mUfsHcPlatform != NULL) && (mUfsHcPlatform->Callback != NULL)) { Status = mUfsHcPlatform->Callback (Private->Handle, EdkiiUfsHcPreHce, &Private->UfsHcDriverInterface); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPreHce, Status = %r\n", Status)); @@ -1863,6 +1880,7 @@ UfsEnableHostController ( if (EFI_ERROR (Status)) { return Status; } + // // Wait until HCE is read as '0' before continuing. // @@ -1888,7 +1906,7 @@ UfsEnableHostController ( return EFI_DEVICE_ERROR; } - if (mUfsHcPlatform != NULL && mUfsHcPlatform->Callback != NULL) { + if ((mUfsHcPlatform != NULL) && (mUfsHcPlatform->Callback != NULL)) { Status = mUfsHcPlatform->Callback (Private->Handle, EdkiiUfsHcPostHce, &Private->UfsHcDriverInterface); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPostHce, Status = %r\n", Status)); @@ -1911,7 +1929,7 @@ UfsEnableHostController ( **/ EFI_STATUS UfsDeviceDetection ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { UINTN Retry; @@ -1919,7 +1937,7 @@ UfsDeviceDetection ( UINT32 Data; EDKII_UIC_COMMAND LinkStartupCommand; - if (mUfsHcPlatform != NULL && mUfsHcPlatform->Callback != NULL) { + if ((mUfsHcPlatform != NULL) && (mUfsHcPlatform->Callback != NULL)) { Status = mUfsHcPlatform->Callback (Private->Handle, EdkiiUfsHcPreLinkStartup, &Private->UfsHcDriverInterface); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPreLinkStartup, Status = %r\n", Status)); @@ -1933,10 +1951,10 @@ UfsDeviceDetection ( // for (Retry = 0; Retry < 3; Retry++) { LinkStartupCommand.Opcode = UfsUicDmeLinkStartup; - LinkStartupCommand.Arg1 = 0; - LinkStartupCommand.Arg2 = 0; - LinkStartupCommand.Arg3 = 0; - Status = UfsExecUicCommands (Private, &LinkStartupCommand); + LinkStartupCommand.Arg1 = 0; + LinkStartupCommand.Arg2 = 0; + LinkStartupCommand.Arg3 = 0; + Status = UfsExecUicCommands (Private, &LinkStartupCommand); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } @@ -1952,13 +1970,14 @@ UfsDeviceDetection ( return EFI_DEVICE_ERROR; } } else { - if (mUfsHcPlatform != NULL && mUfsHcPlatform->Callback != NULL) { + if ((mUfsHcPlatform != NULL) && (mUfsHcPlatform->Callback != NULL)) { Status = mUfsHcPlatform->Callback (Private->Handle, EdkiiUfsHcPostLinkStartup, &Private->UfsHcDriverInterface); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failure from platform driver during EdkiiUfsHcPostLinkStartup, Status = %r\n", Status)); return Status; } } + return EFI_SUCCESS; } } @@ -1977,14 +1996,14 @@ UfsDeviceDetection ( **/ EFI_STATUS UfsInitTaskManagementRequestList ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - UINT8 Nutmrs; - VOID *CmdDescHost; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - VOID *CmdDescMapping; - EFI_STATUS Status; + UINT8 Nutmrs; + VOID *CmdDescHost; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + VOID *CmdDescMapping; + EFI_STATUS Status; // // Initial h/w and s/w context for future operations. @@ -1996,7 +2015,7 @@ UfsInitTaskManagementRequestList ( // // Allocate and initialize UTP Task Management Request List. // - Nutmrs = (UINT8) (RShiftU64 ((Private->UfsHcInfo.Capabilities & UFS_HC_CAP_NUTMRS), 16) + 1); + Nutmrs = (UINT8)(RShiftU64 ((Private->UfsHcInfo.Capabilities & UFS_HC_CAP_NUTMRS), 16) + 1); Status = UfsAllocateAlignCommonBuffer (Private, Nutmrs * sizeof (UTP_TMRD), &CmdDescHost, &CmdDescPhyAddr, &CmdDescMapping); if (EFI_ERROR (Status)) { return Status; @@ -2015,6 +2034,7 @@ UfsInitTaskManagementRequestList ( if (EFI_ERROR (Status)) { return Status; } + Private->UtpTmrlBase = CmdDescHost; Private->Nutmrs = Nutmrs; Private->TmrlMapping = CmdDescMapping; @@ -2042,14 +2062,14 @@ UfsInitTaskManagementRequestList ( **/ EFI_STATUS UfsInitTransferRequestList ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - UINT8 Nutrs; - VOID *CmdDescHost; - EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; - VOID *CmdDescMapping; - EFI_STATUS Status; + UINT8 Nutrs; + VOID *CmdDescHost; + EFI_PHYSICAL_ADDRESS CmdDescPhyAddr; + VOID *CmdDescMapping; + EFI_STATUS Status; // // Initial h/w and s/w context for future operations. @@ -2108,10 +2128,10 @@ UfsInitTransferRequestList ( **/ EFI_STATUS UfsControllerInit ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UfsEnableHostController (Private); if (EFI_ERROR (Status)) { @@ -2152,11 +2172,11 @@ UfsControllerInit ( **/ EFI_STATUS UfsControllerStop ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private + IN UFS_PASS_THRU_PRIVATE_DATA *Private ) { - EFI_STATUS Status; - UINT32 Data; + EFI_STATUS Status; + UINT32 Data; // // Enable the UTP Task Management Request List by setting the UTP Task Management @@ -2183,6 +2203,7 @@ UfsControllerStop ( if (EFI_ERROR (Status)) { return Status; } + ASSERT ((Data & UFS_HC_HCE_EN) == UFS_HC_HCE_EN); Status = UfsMmioWrite32 (Private, UFS_HC_ENABLE_OFFSET, 0); @@ -2216,17 +2237,17 @@ UfsControllerStop ( VOID EFIAPI SignalCallerEvent ( - IN UFS_PASS_THRU_PRIVATE_DATA *Private, - IN UFS_PASS_THRU_TRANS_REQ *TransReq + IN UFS_PASS_THRU_PRIVATE_DATA *Private, + IN UFS_PASS_THRU_TRANS_REQ *TransReq ) { - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; - EFI_EVENT CallerEvent; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHc; + EFI_EVENT CallerEvent; ASSERT ((Private != NULL) && (TransReq != NULL)); - UfsHc = Private->UfsHostController; - CallerEvent = TransReq->CallerEvent; + UfsHc = Private->UfsHostController; + CallerEvent = TransReq->CallerEvent; RemoveEntryList (&TransReq->TransferList); @@ -2239,6 +2260,7 @@ SignalCallerEvent ( if (TransReq->CmdDescMapping != NULL) { UfsHc->Unmap (UfsHc, TransReq->CmdDescMapping); } + if (TransReq->CmdDescHost != NULL) { UfsHc->FreeBuffer ( UfsHc, @@ -2263,36 +2285,37 @@ SignalCallerEvent ( VOID EFIAPI ProcessAsyncTaskList ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - UFS_PASS_THRU_PRIVATE_DATA *Private; - LIST_ENTRY *Entry; - LIST_ENTRY *NextEntry; - UFS_PASS_THRU_TRANS_REQ *TransReq; - EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet; - UTP_RESPONSE_UPIU *Response; - UINT16 SenseDataLen; - UINT32 ResTranCount; - UINT32 SlotsMap; - UINT32 Value; - EFI_STATUS Status; - - Private = (UFS_PASS_THRU_PRIVATE_DATA*) Context; - SlotsMap = 0; + UFS_PASS_THRU_PRIVATE_DATA *Private; + LIST_ENTRY *Entry; + LIST_ENTRY *NextEntry; + UFS_PASS_THRU_TRANS_REQ *TransReq; + EFI_EXT_SCSI_PASS_THRU_SCSI_REQUEST_PACKET *Packet; + UTP_RESPONSE_UPIU *Response; + UINT16 SenseDataLen; + UINT32 ResTranCount; + UINT32 SlotsMap; + UINT32 Value; + EFI_STATUS Status; + + Private = (UFS_PASS_THRU_PRIVATE_DATA *)Context; + SlotsMap = 0; // // Check the entries in the async I/O queue are done or not. // - if (!IsListEmpty(&Private->Queue)) { + if (!IsListEmpty (&Private->Queue)) { BASE_LIST_FOR_EACH_SAFE (Entry, NextEntry, &Private->Queue) { - TransReq = UFS_PASS_THRU_TRANS_REQ_FROM_THIS (Entry); - Packet = TransReq->Packet; + TransReq = UFS_PASS_THRU_TRANS_REQ_FROM_THIS (Entry); + Packet = TransReq->Packet; if ((SlotsMap & (BIT0 << TransReq->Slot)) != 0) { return; } + SlotsMap |= BIT0 << TransReq->Slot; Status = UfsMmioRead32 (Private, UFS_HC_UTRLDBR_OFFSET, &Value); @@ -2329,10 +2352,10 @@ ProcessAsyncTaskList ( // // Get sense data if exists // - Response = (UTP_RESPONSE_UPIU*)((UINT8*)TransReq->CmdDescHost + TransReq->Trd->RuO * sizeof (UINT32)); + Response = (UTP_RESPONSE_UPIU *)((UINT8 *)TransReq->CmdDescHost + TransReq->Trd->RuO * sizeof (UINT32)); ASSERT (Response != NULL); SenseDataLen = Response->SenseDataLen; - SwapLittleEndianToBigEndian ((UINT8*)&SenseDataLen, sizeof (UINT16)); + SwapLittleEndianToBigEndian ((UINT8 *)&SenseDataLen, sizeof (UINT16)); if ((Packet->SenseDataLength != 0) && (Packet->SenseData != NULL)) { // @@ -2360,13 +2383,13 @@ ProcessAsyncTaskList ( if (Packet->DataDirection == EFI_EXT_SCSI_DATA_DIRECTION_READ) { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->InTransferLength -= ResTranCount; } } else { if ((Response->Flags & BIT5) == BIT5) { ResTranCount = Response->ResTranCount; - SwapLittleEndianToBigEndian ((UINT8*)&ResTranCount, sizeof (UINT32)); + SwapLittleEndianToBigEndian ((UINT8 *)&ResTranCount, sizeof (UINT32)); Packet->OutTransferLength -= ResTranCount; } } @@ -2400,9 +2423,9 @@ UfsHcDriverInterfaceExecUicCommand ( IN OUT EDKII_UIC_COMMAND *UicCommand ) { - UFS_PASS_THRU_PRIVATE_DATA *Private; + UFS_PASS_THRU_PRIVATE_DATA *Private; - if (This == NULL || UicCommand == NULL) { + if ((This == NULL) || (UicCommand == NULL)) { return EFI_INVALID_PARAMETER; } @@ -2441,7 +2464,7 @@ GetUfsHcInfo ( Private->UfsHcInfo.Capabilities = Data; - if (mUfsHcPlatform != NULL && mUfsHcPlatform->OverrideHcInfo != NULL) { + if ((mUfsHcPlatform != NULL) && (mUfsHcPlatform->OverrideHcInfo != NULL)) { Status = mUfsHcPlatform->OverrideHcInfo (Private->Handle, &Private->UfsHcInfo); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Failure from platform on OverrideHcInfo, Status = %r\n", Status)); @@ -2451,4 +2474,3 @@ GetUfsHcInfo ( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.h b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.h index e8b5aae702..f19b6535a1 100644 --- a/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.h +++ b/MdeModulePkg/Bus/Ufs/UfsPassThruDxe/UfsPassThruHci.h @@ -13,62 +13,62 @@ // // Host Capabilities Register Offsets // -#define UFS_HC_CAP_OFFSET 0x0000 // Controller Capabilities -#define UFS_HC_VER_OFFSET 0x0008 // Version -#define UFS_HC_DDID_OFFSET 0x0010 // Device ID and Device Class -#define UFS_HC_PMID_OFFSET 0x0014 // Product ID and Manufacturer ID -#define UFS_HC_AHIT_OFFSET 0x0018 // Auto-Hibernate Idle Timer +#define UFS_HC_CAP_OFFSET 0x0000 // Controller Capabilities +#define UFS_HC_VER_OFFSET 0x0008 // Version +#define UFS_HC_DDID_OFFSET 0x0010 // Device ID and Device Class +#define UFS_HC_PMID_OFFSET 0x0014 // Product ID and Manufacturer ID +#define UFS_HC_AHIT_OFFSET 0x0018 // Auto-Hibernate Idle Timer // // Operation and Runtime Register Offsets // -#define UFS_HC_IS_OFFSET 0x0020 // Interrupt Status -#define UFS_HC_IE_OFFSET 0x0024 // Interrupt Enable -#define UFS_HC_STATUS_OFFSET 0x0030 // Host Controller Status -#define UFS_HC_ENABLE_OFFSET 0x0034 // Host Controller Enable -#define UFS_HC_UECPA_OFFSET 0x0038 // Host UIC Error Code PHY Adapter Layer -#define UFS_HC_UECDL_OFFSET 0x003c // Host UIC Error Code Data Link Layer -#define UFS_HC_UECN_OFFSET 0x0040 // Host UIC Error Code Network Layer -#define UFS_HC_UECT_OFFSET 0x0044 // Host UIC Error Code Transport Layer -#define UFS_HC_UECDME_OFFSET 0x0048 // Host UIC Error Code DME -#define UFS_HC_UTRIACR_OFFSET 0x004c // UTP Transfer Request Interrupt Aggregation Control Register +#define UFS_HC_IS_OFFSET 0x0020 // Interrupt Status +#define UFS_HC_IE_OFFSET 0x0024 // Interrupt Enable +#define UFS_HC_STATUS_OFFSET 0x0030 // Host Controller Status +#define UFS_HC_ENABLE_OFFSET 0x0034 // Host Controller Enable +#define UFS_HC_UECPA_OFFSET 0x0038 // Host UIC Error Code PHY Adapter Layer +#define UFS_HC_UECDL_OFFSET 0x003c // Host UIC Error Code Data Link Layer +#define UFS_HC_UECN_OFFSET 0x0040 // Host UIC Error Code Network Layer +#define UFS_HC_UECT_OFFSET 0x0044 // Host UIC Error Code Transport Layer +#define UFS_HC_UECDME_OFFSET 0x0048 // Host UIC Error Code DME +#define UFS_HC_UTRIACR_OFFSET 0x004c // UTP Transfer Request Interrupt Aggregation Control Register // // UTP Transfer Register Offsets // -#define UFS_HC_UTRLBA_OFFSET 0x0050 // UTP Transfer Request List Base Address -#define UFS_HC_UTRLBAU_OFFSET 0x0054 // UTP Transfer Request List Base Address Upper 32-Bits -#define UFS_HC_UTRLDBR_OFFSET 0x0058 // UTP Transfer Request List Door Bell Register -#define UFS_HC_UTRLCLR_OFFSET 0x005c // UTP Transfer Request List CLear Register -#define UFS_HC_UTRLRSR_OFFSET 0x0060 // UTP Transfer Request Run-Stop Register +#define UFS_HC_UTRLBA_OFFSET 0x0050 // UTP Transfer Request List Base Address +#define UFS_HC_UTRLBAU_OFFSET 0x0054 // UTP Transfer Request List Base Address Upper 32-Bits +#define UFS_HC_UTRLDBR_OFFSET 0x0058 // UTP Transfer Request List Door Bell Register +#define UFS_HC_UTRLCLR_OFFSET 0x005c // UTP Transfer Request List CLear Register +#define UFS_HC_UTRLRSR_OFFSET 0x0060 // UTP Transfer Request Run-Stop Register // // UTP Task Management Register Offsets // -#define UFS_HC_UTMRLBA_OFFSET 0x0070 // UTP Task Management Request List Base Address -#define UFS_HC_UTMRLBAU_OFFSET 0x0074 // UTP Task Management Request List Base Address Upper 32-Bits -#define UFS_HC_UTMRLDBR_OFFSET 0x0078 // UTP Task Management Request List Door Bell Register -#define UFS_HC_UTMRLCLR_OFFSET 0x007c // UTP Task Management Request List CLear Register -#define UFS_HC_UTMRLRSR_OFFSET 0x0080 // UTP Task Management Run-Stop Register +#define UFS_HC_UTMRLBA_OFFSET 0x0070 // UTP Task Management Request List Base Address +#define UFS_HC_UTMRLBAU_OFFSET 0x0074 // UTP Task Management Request List Base Address Upper 32-Bits +#define UFS_HC_UTMRLDBR_OFFSET 0x0078 // UTP Task Management Request List Door Bell Register +#define UFS_HC_UTMRLCLR_OFFSET 0x007c // UTP Task Management Request List CLear Register +#define UFS_HC_UTMRLRSR_OFFSET 0x0080 // UTP Task Management Run-Stop Register // // UIC Command Register Offsets // -#define UFS_HC_UIC_CMD_OFFSET 0x0090 // UIC Command Register -#define UFS_HC_UCMD_ARG1_OFFSET 0x0094 // UIC Command Argument 1 -#define UFS_HC_UCMD_ARG2_OFFSET 0x0098 // UIC Command Argument 2 -#define UFS_HC_UCMD_ARG3_OFFSET 0x009c // UIC Command Argument 3 +#define UFS_HC_UIC_CMD_OFFSET 0x0090 // UIC Command Register +#define UFS_HC_UCMD_ARG1_OFFSET 0x0094 // UIC Command Argument 1 +#define UFS_HC_UCMD_ARG2_OFFSET 0x0098 // UIC Command Argument 2 +#define UFS_HC_UCMD_ARG3_OFFSET 0x009c // UIC Command Argument 3 // // UMA Register Offsets // -#define UFS_HC_UMA_OFFSET 0x00b0 // Reserved for Unified Memory Extension +#define UFS_HC_UMA_OFFSET 0x00b0 // Reserved for Unified Memory Extension -#define UFS_HC_HCE_EN BIT0 -#define UFS_HC_HCS_DP BIT0 -#define UFS_HC_HCS_UCRDY BIT3 -#define UFS_HC_IS_ULSS BIT8 -#define UFS_HC_IS_UCCS BIT10 -#define UFS_HC_CAP_64ADDR BIT24 -#define UFS_HC_CAP_NUTMRS (BIT16 | BIT17 | BIT18) -#define UFS_HC_CAP_NUTRS (BIT0 | BIT1 | BIT2 | BIT3 | BIT4) -#define UFS_HC_UTMRLRSR BIT0 -#define UFS_HC_UTRLRSR BIT0 +#define UFS_HC_HCE_EN BIT0 +#define UFS_HC_HCS_DP BIT0 +#define UFS_HC_HCS_UCRDY BIT3 +#define UFS_HC_IS_ULSS BIT8 +#define UFS_HC_IS_UCCS BIT10 +#define UFS_HC_CAP_64ADDR BIT24 +#define UFS_HC_CAP_NUTMRS (BIT16 | BIT17 | BIT18) +#define UFS_HC_CAP_NUTRS (BIT0 | BIT1 | BIT2 | BIT3 | BIT4) +#define UFS_HC_UTMRLRSR BIT0 +#define UFS_HC_UTRLRSR BIT0 // // The initial value of the OCS field of UTP TRD or TMRD descriptor @@ -79,25 +79,25 @@ // // A maximum of length of 256KB is supported by PRDT entry // -#define UFS_MAX_DATA_LEN_PER_PRD 0x40000 +#define UFS_MAX_DATA_LEN_PER_PRD 0x40000 -#define UFS_STORAGE_COMMAND_TYPE 0x01 +#define UFS_STORAGE_COMMAND_TYPE 0x01 -#define UFS_REGULAR_COMMAND 0x00 -#define UFS_INTERRUPT_COMMAND 0x01 +#define UFS_REGULAR_COMMAND 0x00 +#define UFS_INTERRUPT_COMMAND 0x01 -#define UFS_LUN_0 0x00 -#define UFS_LUN_1 0x01 -#define UFS_LUN_2 0x02 -#define UFS_LUN_3 0x03 -#define UFS_LUN_4 0x04 -#define UFS_LUN_5 0x05 -#define UFS_LUN_6 0x06 -#define UFS_LUN_7 0x07 -#define UFS_WLUN_REPORT_LUNS 0x81 -#define UFS_WLUN_UFS_DEV 0xD0 -#define UFS_WLUN_BOOT 0xB0 -#define UFS_WLUN_RPMB 0xC4 +#define UFS_LUN_0 0x00 +#define UFS_LUN_1 0x01 +#define UFS_LUN_2 0x02 +#define UFS_LUN_3 0x03 +#define UFS_LUN_4 0x04 +#define UFS_LUN_5 0x05 +#define UFS_LUN_6 0x06 +#define UFS_LUN_7 0x07 +#define UFS_WLUN_REPORT_LUNS 0x81 +#define UFS_WLUN_UFS_DEV 0xD0 +#define UFS_WLUN_BOOT 0xB0 +#define UFS_WLUN_RPMB 0xC4 #pragma pack(1) @@ -105,227 +105,227 @@ // UFSHCI 2.0 Spec Section 5.2.1 Offset 00h: CAP - Controller Capabilities // typedef struct { - UINT8 Nutrs:4; // Number of UTP Transfer Request Slots - UINT8 Rsvd1:4; + UINT8 Nutrs : 4; // Number of UTP Transfer Request Slots + UINT8 Rsvd1 : 4; - UINT8 NoRtt; // Number of outstanding READY TO TRANSFER (RTT) requests supported + UINT8 NoRtt; // Number of outstanding READY TO TRANSFER (RTT) requests supported - UINT8 Nutmrs:3; // Number of UTP Task Management Request Slots - UINT8 Rsvd2:4; - UINT8 AutoHs:1; // Auto-Hibernation Support + UINT8 Nutmrs : 3; // Number of UTP Task Management Request Slots + UINT8 Rsvd2 : 4; + UINT8 AutoHs : 1; // Auto-Hibernation Support - UINT8 As64:1; // 64-bit addressing supported - UINT8 Oodds:1; // Out of order data delivery supported - UINT8 UicDmetms:1; // UIC DME_TEST_MODE command supported - UINT8 Ume:1; // Reserved for Unified Memory Extension - UINT8 Rsvd4:4; + UINT8 As64 : 1; // 64-bit addressing supported + UINT8 Oodds : 1; // Out of order data delivery supported + UINT8 UicDmetms : 1; // UIC DME_TEST_MODE command supported + UINT8 Ume : 1; // Reserved for Unified Memory Extension + UINT8 Rsvd4 : 4; } UFS_HC_CAP; // // UFSHCI 2.0 Spec Section 5.2.2 Offset 08h: VER - UFS Version // typedef struct { - UINT8 Vs:4; // Version Suffix - UINT8 Mnr:4; // Minor version number + UINT8 Vs : 4; // Version Suffix + UINT8 Mnr : 4; // Minor version number - UINT8 Mjr; // Major version number + UINT8 Mjr; // Major version number - UINT16 Rsvd1; + UINT16 Rsvd1; } UFS_HC_VER; // // UFSHCI 2.0 Spec Section 5.2.3 Offset 10h: HCPID - Host Controller Product ID // -#define UFS_HC_PID UINT32 +#define UFS_HC_PID UINT32 // // UFSHCI 2.0 Spec Section 5.2.4 Offset 14h: HCMID - Host Controller Manufacturer ID // -#define UFS_HC_MID UINT32 +#define UFS_HC_MID UINT32 // // UFSHCI 2.0 Spec Section 5.2.5 Offset 18h: AHIT - Auto-Hibernate Idle Timer // typedef struct { - UINT32 Ahitv:10; // Auto-Hibernate Idle Timer Value - UINT32 Ts:3; // Timer scale - UINT32 Rsvd1:19; + UINT32 Ahitv : 10; // Auto-Hibernate Idle Timer Value + UINT32 Ts : 3; // Timer scale + UINT32 Rsvd1 : 19; } UFS_HC_AHIT; // // UFSHCI 2.0 Spec Section 5.3.1 Offset 20h: IS - Interrupt Status // typedef struct { - UINT16 Utrcs:1; // UTP Transfer Request Completion Status - UINT16 Udepri:1; // UIC DME_ENDPOINT_RESET Indication - UINT16 Ue:1; // UIC Error - UINT16 Utms:1; // UIC Test Mode Status - - UINT16 Upms:1; // UIC Power Mode Status - UINT16 Uhxs:1; // UIC Hibernate Exit Status - UINT16 Uhes:1; // UIC Hibernate Enter Status - UINT16 Ulls:1; // UIC Link Lost Status - - UINT16 Ulss:1; // UIC Link Startup Status - UINT16 Utmrcs:1; // UTP Task Management Request Completion Status - UINT16 Uccs:1; // UIC Command Completion Status - UINT16 Dfes:1; // Device Fatal Error Status - - UINT16 Utpes:1; // UTP Error Status - UINT16 Rsvd1:3; - - UINT16 Hcfes:1; // Host Controller Fatal Error Status - UINT16 Sbfes:1; // System Bus Fatal Error Status - UINT16 Rsvd2:14; + UINT16 Utrcs : 1; // UTP Transfer Request Completion Status + UINT16 Udepri : 1; // UIC DME_ENDPOINT_RESET Indication + UINT16 Ue : 1; // UIC Error + UINT16 Utms : 1; // UIC Test Mode Status + + UINT16 Upms : 1; // UIC Power Mode Status + UINT16 Uhxs : 1; // UIC Hibernate Exit Status + UINT16 Uhes : 1; // UIC Hibernate Enter Status + UINT16 Ulls : 1; // UIC Link Lost Status + + UINT16 Ulss : 1; // UIC Link Startup Status + UINT16 Utmrcs : 1; // UTP Task Management Request Completion Status + UINT16 Uccs : 1; // UIC Command Completion Status + UINT16 Dfes : 1; // Device Fatal Error Status + + UINT16 Utpes : 1; // UTP Error Status + UINT16 Rsvd1 : 3; + + UINT16 Hcfes : 1; // Host Controller Fatal Error Status + UINT16 Sbfes : 1; // System Bus Fatal Error Status + UINT16 Rsvd2 : 14; } UFS_HC_IS; // // UFSHCI 2.0 Spec Section 5.3.2 Offset 24h: IE - Interrupt Enable // typedef struct { - UINT16 Utrce:1; // UTP Transfer Request Completion Enable - UINT16 Udeprie:1; // UIC DME_ENDPOINT_RESET Enable - UINT16 Uee:1; // UIC Error Enable - UINT16 Utmse:1; // UIC Test Mode Status Enable - - UINT16 Upmse:1; // UIC Power Mode Status Enable - UINT16 Uhxse:1; // UIC Hibernate Exit Status Enable - UINT16 Uhese:1; // UIC Hibernate Enter Status Enable - UINT16 Ullse:1; // UIC Link Lost Status Enable - - UINT16 Ulsse:1; // UIC Link Startup Status Enable - UINT16 Utmrce:1; // UTP Task Management Request Completion Enable - UINT16 Ucce:1; // UIC Command Completion Enable - UINT16 Dfee:1; // Device Fatal Error Enable - - UINT16 Utpee:1; // UTP Error Enable - UINT16 Rsvd1:3; - - UINT16 Hcfee:1; // Host Controller Fatal Error Enable - UINT16 Sbfee:1; // System Bus Fatal Error Enable - UINT16 Rsvd2:14; + UINT16 Utrce : 1; // UTP Transfer Request Completion Enable + UINT16 Udeprie : 1; // UIC DME_ENDPOINT_RESET Enable + UINT16 Uee : 1; // UIC Error Enable + UINT16 Utmse : 1; // UIC Test Mode Status Enable + + UINT16 Upmse : 1; // UIC Power Mode Status Enable + UINT16 Uhxse : 1; // UIC Hibernate Exit Status Enable + UINT16 Uhese : 1; // UIC Hibernate Enter Status Enable + UINT16 Ullse : 1; // UIC Link Lost Status Enable + + UINT16 Ulsse : 1; // UIC Link Startup Status Enable + UINT16 Utmrce : 1; // UTP Task Management Request Completion Enable + UINT16 Ucce : 1; // UIC Command Completion Enable + UINT16 Dfee : 1; // Device Fatal Error Enable + + UINT16 Utpee : 1; // UTP Error Enable + UINT16 Rsvd1 : 3; + + UINT16 Hcfee : 1; // Host Controller Fatal Error Enable + UINT16 Sbfee : 1; // System Bus Fatal Error Enable + UINT16 Rsvd2 : 14; } UFS_HC_IE; // // UFSHCI 2.0 Spec Section 5.3.3 Offset 30h: HCS - Host Controller Status // typedef struct { - UINT8 Dp:1; // Device Present - UINT8 UtrlRdy:1; // UTP Transfer Request List Ready - UINT8 UtmrlRdy:1; // UTP Task Management Request List Ready - UINT8 UcRdy:1; // UIC COMMAND Ready - UINT8 Rsvd1:4; - - UINT8 Upmcrs:3; // UIC Power Mode Change Request Status - UINT8 Rsvd2:1; // UIC Hibernate Exit Status Enable - UINT8 Utpec:4; // UTP Error Code - - UINT8 TtagUtpE; // Task Tag of UTP error - UINT8 TlunUtpE; // Target LUN of UTP error + UINT8 Dp : 1; // Device Present + UINT8 UtrlRdy : 1; // UTP Transfer Request List Ready + UINT8 UtmrlRdy : 1; // UTP Task Management Request List Ready + UINT8 UcRdy : 1; // UIC COMMAND Ready + UINT8 Rsvd1 : 4; + + UINT8 Upmcrs : 3; // UIC Power Mode Change Request Status + UINT8 Rsvd2 : 1; // UIC Hibernate Exit Status Enable + UINT8 Utpec : 4; // UTP Error Code + + UINT8 TtagUtpE; // Task Tag of UTP error + UINT8 TlunUtpE; // Target LUN of UTP error } UFS_HC_STATUS; // // UFSHCI 2.0 Spec Section 5.3.4 Offset 34h: HCE - Host Controller Enable // typedef struct { - UINT32 Hce:1; // Host Controller Enable - UINT32 Rsvd1:31; + UINT32 Hce : 1; // Host Controller Enable + UINT32 Rsvd1 : 31; } UFS_HC_ENABLE; // // UFSHCI 2.0 Spec Section 5.3.5 Offset 38h: UECPA - Host UIC Error Code PHY Adapter Layer // typedef struct { - UINT32 Ec:5; // UIC PHY Adapter Layer Error Code - UINT32 Rsvd1:26; - UINT32 Err:1; // UIC PHY Adapter Layer Error + UINT32 Ec : 5; // UIC PHY Adapter Layer Error Code + UINT32 Rsvd1 : 26; + UINT32 Err : 1; // UIC PHY Adapter Layer Error } UFS_HC_UECPA; // // UFSHCI 2.0 Spec Section 5.3.6 Offset 3ch: UECDL - Host UIC Error Code Data Link Layer // typedef struct { - UINT32 Ec:15; // UIC Data Link Layer Error Code - UINT32 Rsvd1:16; - UINT32 Err:1; // UIC Data Link Layer Error + UINT32 Ec : 15; // UIC Data Link Layer Error Code + UINT32 Rsvd1 : 16; + UINT32 Err : 1; // UIC Data Link Layer Error } UFS_HC_UECDL; // // UFSHCI 2.0 Spec Section 5.3.7 Offset 40h: UECN - Host UIC Error Code Network Layer // typedef struct { - UINT32 Ec:3; // UIC Network Layer Error Code - UINT32 Rsvd1:28; - UINT32 Err:1; // UIC Network Layer Error + UINT32 Ec : 3; // UIC Network Layer Error Code + UINT32 Rsvd1 : 28; + UINT32 Err : 1; // UIC Network Layer Error } UFS_HC_UECN; // // UFSHCI 2.0 Spec Section 5.3.8 Offset 44h: UECT - Host UIC Error Code Transport Layer // typedef struct { - UINT32 Ec:7; // UIC Transport Layer Error Code - UINT32 Rsvd1:24; - UINT32 Err:1; // UIC Transport Layer Error + UINT32 Ec : 7; // UIC Transport Layer Error Code + UINT32 Rsvd1 : 24; + UINT32 Err : 1; // UIC Transport Layer Error } UFS_HC_UECT; // // UFSHCI 2.0 Spec Section 5.3.9 Offset 48h: UECDME - Host UIC Error Code // typedef struct { - UINT32 Ec:1; // UIC DME Error Code - UINT32 Rsvd1:30; - UINT32 Err:1; // UIC DME Error + UINT32 Ec : 1; // UIC DME Error Code + UINT32 Rsvd1 : 30; + UINT32 Err : 1; // UIC DME Error } UFS_HC_UECDME; // // UFSHCI 2.0 Spec Section 5.3.10 Offset 4Ch: UTRIACR - UTP Transfer Request Interrupt Aggregation Control Register // typedef struct { - UINT8 IaToVal; // Interrupt aggregation timeout value + UINT8 IaToVal; // Interrupt aggregation timeout value - UINT8 IacTh:5; // Interrupt aggregation counter threshold - UINT8 Rsvd1:3; + UINT8 IacTh : 5; // Interrupt aggregation counter threshold + UINT8 Rsvd1 : 3; - UINT8 Ctr:1; // Counter and Timer Reset - UINT8 Rsvd2:3; - UINT8 Iasb:1; // Interrupt aggregation status bit - UINT8 Rsvd3:3; + UINT8 Ctr : 1; // Counter and Timer Reset + UINT8 Rsvd2 : 3; + UINT8 Iasb : 1; // Interrupt aggregation status bit + UINT8 Rsvd3 : 3; - UINT8 IapwEn:1; // Interrupt aggregation parameter write enable - UINT8 Rsvd4:6; - UINT8 IaEn:1; // Interrupt Aggregation Enable/Disable + UINT8 IapwEn : 1; // Interrupt aggregation parameter write enable + UINT8 Rsvd4 : 6; + UINT8 IaEn : 1; // Interrupt Aggregation Enable/Disable } UFS_HC_UTRIACR; // // UFSHCI 2.0 Spec Section 5.4.1 Offset 50h: UTRLBA - UTP Transfer Request List Base Address // typedef struct { - UINT32 Rsvd1:10; - UINT32 UtrlBa:22; // UTP Transfer Request List Base Address + UINT32 Rsvd1 : 10; + UINT32 UtrlBa : 22; // UTP Transfer Request List Base Address } UFS_HC_UTRLBA; // // UFSHCI 2.0 Spec Section 5.4.2 Offset 54h: UTRLBAU - UTP Transfer Request List Base Address Upper 32-bits // -#define UFS_HC_UTRLBAU UINT32 +#define UFS_HC_UTRLBAU UINT32 // // UFSHCI 2.0 Spec Section 5.4.3 Offset 58h: UTRLDBR - UTP Transfer Request List Door Bell Register // -#define UFS_HC_UTRLDBR UINT32 +#define UFS_HC_UTRLDBR UINT32 // // UFSHCI 2.0 Spec Section 5.4.4 Offset 5Ch: UTRLCLR - UTP Transfer Request List CLear Register // -#define UFS_HC_UTRLCLR UINT32 +#define UFS_HC_UTRLCLR UINT32 #if 0 // // UFSHCI 2.0 Spec Section 5.4.5 Offset 60h: UTRLRSR - UTP Transfer Request List Run Stop Register // typedef struct { - UINT32 UtrlRsr:1; // UTP Transfer Request List Run-Stop Register - UINT32 Rsvd1:31; + UINT32 UtrlRsr : 1; // UTP Transfer Request List Run-Stop Register + UINT32 Rsvd1 : 31; } UFS_HC_UTRLRSR; #endif @@ -333,29 +333,29 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.5.1 Offset 70h: UTMRLBA - UTP Task Management Request List Base Address // typedef struct { - UINT32 Rsvd1:10; - UINT32 UtmrlBa:22; // UTP Task Management Request List Base Address + UINT32 Rsvd1 : 10; + UINT32 UtmrlBa : 22; // UTP Task Management Request List Base Address } UFS_HC_UTMRLBA; // // UFSHCI 2.0 Spec Section 5.5.2 Offset 74h: UTMRLBAU - UTP Task Management Request List Base Address Upper 32-bits // -#define UFS_HC_UTMRLBAU UINT32 +#define UFS_HC_UTMRLBAU UINT32 // // UFSHCI 2.0 Spec Section 5.5.3 Offset 78h: UTMRLDBR - UTP Task Management Request List Door Bell Register // typedef struct { - UINT32 UtmrlDbr:8; // UTP Task Management Request List Door bell Register - UINT32 Rsvd1:24; + UINT32 UtmrlDbr : 8; // UTP Task Management Request List Door bell Register + UINT32 Rsvd1 : 24; } UFS_HC_UTMRLDBR; // // UFSHCI 2.0 Spec Section 5.5.4 Offset 7Ch: UTMRLCLR - UTP Task Management Request List CLear Register // typedef struct { - UINT32 UtmrlClr:8; // UTP Task Management List Clear Register - UINT32 Rsvd1:24; + UINT32 UtmrlClr : 8; // UTP Task Management List Clear Register + UINT32 Rsvd1 : 24; } UFS_HC_UTMRLCLR; #if 0 @@ -363,8 +363,8 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.5.5 Offset 80h: UTMRLRSR - UTP Task Management Request List Run Stop Register // typedef struct { - UINT32 UtmrlRsr:1; // UTP Task Management Request List Run-Stop Register - UINT32 Rsvd1:31; + UINT32 UtmrlRsr : 1; // UTP Task Management Request List Run-Stop Register + UINT32 Rsvd1 : 31; } UFS_HC_UTMRLRSR; #endif @@ -372,24 +372,24 @@ typedef struct { // UFSHCI 2.0 Spec Section 5.6.1 Offset 90h: UICCMD - UIC Command // typedef struct { - UINT32 CmdOp:8; // Command Opcode - UINT32 Rsvd1:24; + UINT32 CmdOp : 8; // Command Opcode + UINT32 Rsvd1 : 24; } UFS_HC_UICCMD; // // UFSHCI 2.0 Spec Section 5.6.2 Offset 94h: UICCMDARG1 - UIC Command Argument 1 // -#define UFS_HC_UICCMD_ARG1 UINT32 +#define UFS_HC_UICCMD_ARG1 UINT32 // // UFSHCI 2.0 Spec Section 5.6.2 Offset 98h: UICCMDARG2 - UIC Command Argument 2 // -#define UFS_HC_UICCMD_ARG2 UINT32 +#define UFS_HC_UICCMD_ARG2 UINT32 // // UFSHCI 2.0 Spec Section 5.6.2 Offset 9ch: UICCMDARG3 - UIC Command Argument 3 // -#define UFS_HC_UICCMD_ARG3 UINT32 +#define UFS_HC_UICCMD_ARG3 UINT32 // // UIC command opcodes @@ -417,74 +417,74 @@ typedef struct { // // DW0 // - UINT32 Rsvd1:24; - UINT32 Int:1; /* Interrupt */ - UINT32 Dd:2; /* Data Direction */ - UINT32 Rsvd2:1; - UINT32 Ct:4; /* Command Type */ + UINT32 Rsvd1 : 24; + UINT32 Int : 1; /* Interrupt */ + UINT32 Dd : 2; /* Data Direction */ + UINT32 Rsvd2 : 1; + UINT32 Ct : 4; /* Command Type */ // // DW1 // - UINT32 Rsvd3; + UINT32 Rsvd3; // // DW2 // - UINT32 Ocs:8; /* Overall Command Status */ - UINT32 Rsvd4:24; + UINT32 Ocs : 8; /* Overall Command Status */ + UINT32 Rsvd4 : 24; // // DW3 // - UINT32 Rsvd5; + UINT32 Rsvd5; // // DW4 // - UINT32 Rsvd6:7; - UINT32 UcdBa:25; /* UTP Command Descriptor Base Address */ + UINT32 Rsvd6 : 7; + UINT32 UcdBa : 25; /* UTP Command Descriptor Base Address */ // // DW5 // - UINT32 UcdBaU; /* UTP Command Descriptor Base Address Upper 32-bits */ + UINT32 UcdBaU; /* UTP Command Descriptor Base Address Upper 32-bits */ // // DW6 // - UINT16 RuL; /* Response UPIU Length */ - UINT16 RuO; /* Response UPIU Offset */ + UINT16 RuL; /* Response UPIU Length */ + UINT16 RuO; /* Response UPIU Offset */ // // DW7 // - UINT16 PrdtL; /* PRDT Length */ - UINT16 PrdtO; /* PRDT Offset */ + UINT16 PrdtL; /* PRDT Length */ + UINT16 PrdtO; /* PRDT Offset */ } UTP_TRD; typedef struct { // // DW0 // - UINT32 Rsvd1:2; - UINT32 DbAddr:30; /* Data Base Address */ + UINT32 Rsvd1 : 2; + UINT32 DbAddr : 30; /* Data Base Address */ // // DW1 // - UINT32 DbAddrU; /* Data Base Address Upper 32-bits */ + UINT32 DbAddrU; /* Data Base Address Upper 32-bits */ // // DW2 // - UINT32 Rsvd2; + UINT32 Rsvd2; // // DW3 // - UINT32 DbCount:18; /* Data Byte Count */ - UINT32 Rsvd3:14; + UINT32 DbCount : 18; /* Data Byte Count */ + UINT32 Rsvd3 : 14; } UTP_TR_PRD; // @@ -494,38 +494,38 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x01*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x01*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 CmdSet:4; /* Command Set Type */ - UINT8 Rsvd1:4; - UINT8 Rsvd2; - UINT8 Rsvd3; - UINT8 Rsvd4; + UINT8 CmdSet : 4; /* Command Set Type */ + UINT8 Rsvd1 : 4; + UINT8 Rsvd2; + UINT8 Rsvd3; + UINT8 Rsvd4; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd5; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd5; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 ExpDataTranLen; /* Expected Data Transfer Length - Big Endian */ + UINT32 ExpDataTranLen; /* Expected Data Transfer Length - Big Endian */ // // DW4 - DW7 // - UINT8 Cdb[16]; + UINT8 Cdb[16]; } UTP_COMMAND_UPIU; // @@ -535,44 +535,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x21*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x21*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 CmdSet:4; /* Command Set Type */ - UINT8 Rsvd1:4; - UINT8 Rsvd2; - UINT8 Response; /* Response */ - UINT8 Status; /* Status */ + UINT8 CmdSet : 4; /* Command Set Type */ + UINT8 Rsvd1 : 4; + UINT8 Rsvd2; + UINT8 Response; /* Response */ + UINT8 Status; /* Status */ // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 ResTranCount; /* Residual Transfer Count - Big Endian */ + UINT32 ResTranCount; /* Residual Transfer Count - Big Endian */ // // DW4 - DW7 // - UINT8 Rsvd3[16]; + UINT8 Rsvd3[16]; // // Data Segment - Sense Data // - UINT16 SenseDataLen; /* Sense Data Length - Big Endian */ - UINT8 SenseData[18]; /* Sense Data */ + UINT16 SenseDataLen; /* Sense Data Length - Big Endian */ + UINT8 SenseData[18]; /* Sense Data */ } UTP_RESPONSE_UPIU; // @@ -582,44 +582,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x02*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x02*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be sent out // - //UINT8 Data[]; /* Data to be sent out, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be sent out, maximum is 65535 bytes */ } UTP_DATA_OUT_UPIU; // @@ -629,44 +629,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x22*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x22*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be read // - //UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ } UTP_DATA_IN_UPIU; // @@ -676,44 +676,44 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x31*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x31*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[4]; + UINT8 Rsvd1[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd2; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd2; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ + UINT32 DataBufOffset; /* Data Buffer Offset - Big Endian */ // // DW4 // - UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ + UINT32 DataTranCount; /* Data Transfer Count - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd3[12]; + UINT8 Rsvd3[12]; // // Data Segment - Data to be read // - //UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be read, maximum is 65535 bytes */ } UTP_RDY_TO_TRAN_UPIU; // @@ -723,46 +723,46 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x04*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x04*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1; - UINT8 TskManFunc; /* Task Management Function */ - UINT8 Rsvd2[2]; + UINT8 Rsvd1; + UINT8 TskManFunc; /* Task Management Function */ + UINT8 Rsvd2[2]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 InputParam1; /* Input Parameter 1 - Big Endian */ + UINT32 InputParam1; /* Input Parameter 1 - Big Endian */ // // DW4 // - UINT32 InputParam2; /* Input Parameter 2 - Big Endian */ + UINT32 InputParam2; /* Input Parameter 2 - Big Endian */ // // DW5 // - UINT32 InputParam3; /* Input Parameter 3 - Big Endian */ + UINT32 InputParam3; /* Input Parameter 3 - Big Endian */ // // DW6 - DW7 // - UINT8 Rsvd4[8]; + UINT8 Rsvd4[8]; } UTP_TM_REQ_UPIU; // @@ -772,41 +772,41 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x24*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x24*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[2]; - UINT8 Resp; /* Response */ - UINT8 Rsvd2; + UINT8 Rsvd1[2]; + UINT8 Resp; /* Response */ + UINT8 Rsvd2; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT32 OutputParam1; /* Output Parameter 1 - Big Endian */ + UINT32 OutputParam1; /* Output Parameter 1 - Big Endian */ // // DW4 // - UINT32 OutputParam2; /* Output Parameter 2 - Big Endian */ + UINT32 OutputParam2; /* Output Parameter 2 - Big Endian */ // // DW5 - DW7 // - UINT8 Rsvd4[12]; + UINT8 Rsvd4[12]; } UTP_TM_RESP_UPIU; // @@ -816,47 +816,46 @@ typedef struct { // // DW0 // - UINT32 Rsvd1:24; - UINT32 Int:1; /* Interrupt */ - UINT32 Rsvd2:7; + UINT32 Rsvd1 : 24; + UINT32 Int : 1; /* Interrupt */ + UINT32 Rsvd2 : 7; // // DW1 // - UINT32 Rsvd3; + UINT32 Rsvd3; // // DW2 // - UINT32 Ocs:8; /* Overall Command Status */ - UINT32 Rsvd4:24; + UINT32 Ocs : 8; /* Overall Command Status */ + UINT32 Rsvd4 : 24; // // DW3 // - UINT32 Rsvd5; + UINT32 Rsvd5; // // DW4 - DW11 // - UTP_TM_REQ_UPIU TmReq; /* Task Management Request UPIU */ + UTP_TM_REQ_UPIU TmReq; /* Task Management Request UPIU */ // // DW12 - DW19 // - UTP_TM_RESP_UPIU TmResp; /* Task Management Response UPIU */ + UTP_TM_RESP_UPIU TmResp; /* Task Management Response UPIU */ } UTP_TMRD; - typedef struct { - UINT8 Opcode; - UINT8 DescId; - UINT8 Index; - UINT8 Selector; - UINT16 Rsvd1; - UINT16 Length; - UINT32 Value; - UINT32 Rsvd2; + UINT8 Opcode; + UINT8 DescId; + UINT8 Index; + UINT8 Selector; + UINT16 Rsvd1; + UINT16 Length; + UINT32 Value; + UINT32 Rsvd2; } UTP_UPIU_TSF; // @@ -866,56 +865,56 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x16*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x16*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2; - UINT8 QueryFunc; /* Query Function */ - UINT8 Rsvd3[2]; + UINT8 Rsvd2; + UINT8 QueryFunc; /* Query Function */ + UINT8 Rsvd3[2]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd4; - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd4; + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 - 6 // - UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ + UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ // // DW7 // - UINT8 Rsvd5[4]; + UINT8 Rsvd5[4]; // // Data Segment - Data to be transferred // - //UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ } UTP_QUERY_REQ_UPIU; -#define QUERY_FUNC_STD_READ_REQ 0x01 -#define QUERY_FUNC_STD_WRITE_REQ 0x81 +#define QUERY_FUNC_STD_READ_REQ 0x01 +#define QUERY_FUNC_STD_WRITE_REQ 0x81 typedef enum { - UtpQueryFuncOpcodeNop = 0x00, - UtpQueryFuncOpcodeRdDesc = 0x01, - UtpQueryFuncOpcodeWrDesc = 0x02, - UtpQueryFuncOpcodeRdAttr = 0x03, - UtpQueryFuncOpcodeWrAttr = 0x04, - UtpQueryFuncOpcodeRdFlag = 0x05, - UtpQueryFuncOpcodeSetFlag = 0x06, - UtpQueryFuncOpcodeClrFlag = 0x07, - UtpQueryFuncOpcodeTogFlag = 0x08 + UtpQueryFuncOpcodeNop = 0x00, + UtpQueryFuncOpcodeRdDesc = 0x01, + UtpQueryFuncOpcodeWrDesc = 0x02, + UtpQueryFuncOpcodeRdAttr = 0x03, + UtpQueryFuncOpcodeWrAttr = 0x04, + UtpQueryFuncOpcodeRdFlag = 0x05, + UtpQueryFuncOpcodeSetFlag = 0x06, + UtpQueryFuncOpcodeClrFlag = 0x07, + UtpQueryFuncOpcodeTogFlag = 0x08 } UTP_QUERY_FUNC_OPCODE; // @@ -925,42 +924,42 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x36*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x36*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2; - UINT8 QueryFunc; /* Query Function */ - UINT8 QueryResp; /* Query Response */ - UINT8 Rsvd3; + UINT8 Rsvd2; + UINT8 QueryFunc; /* Query Function */ + UINT8 QueryResp; /* Query Response */ + UINT8 Rsvd3; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian */ // // DW3 - 6 // - UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ + UTP_UPIU_TSF Tsf; /* Transaction Specific Fields */ // // DW7 // - UINT8 Rsvd4[4]; + UINT8 Rsvd4[4]; // // Data Segment - Data to be transferred // - //UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ + // UINT8 Data[]; /* Data to be transferred, maximum is 65535 bytes */ } UTP_QUERY_RESP_UPIU; typedef enum { @@ -984,39 +983,39 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x3F*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Lun; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x3F*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Lun; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd1[2]; - UINT8 Response; /* Response - 0x01 */ - UINT8 Rsvd2; + UINT8 Rsvd1[2]; + UINT8 Response; /* Response - 0x01 */ + UINT8 Rsvd2; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information - 0x00 */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information - 0x00 */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 // - UINT8 HdrSts; /* Basic Header Status */ - UINT8 Rsvd3; - UINT8 E2ESts; /* End-to-End Status */ - UINT8 Rsvd4; + UINT8 HdrSts; /* Basic Header Status */ + UINT8 Rsvd3; + UINT8 E2ESts; /* End-to-End Status */ + UINT8 Rsvd4; // // DW4 - DW7 // - UINT8 Rsvd5[16]; + UINT8 Rsvd5[16]; } UTP_REJ_UPIU; // @@ -1026,29 +1025,29 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x00*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x00*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2[4]; + UINT8 Rsvd2[4]; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 Rsvd3; - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 Rsvd3; + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 - DW7 // - UINT8 Rsvd4[20]; + UINT8 Rsvd4[20]; } UTP_NOP_OUT_UPIU; // @@ -1058,234 +1057,234 @@ typedef struct { // // DW0 // - UINT8 TransCode:6; /* Transaction Type - 0x20*/ - UINT8 Dd:1; - UINT8 Hd:1; - UINT8 Flags; - UINT8 Rsvd1; - UINT8 TaskTag; /* Task Tag */ + UINT8 TransCode : 6; /* Transaction Type - 0x20*/ + UINT8 Dd : 1; + UINT8 Hd : 1; + UINT8 Flags; + UINT8 Rsvd1; + UINT8 TaskTag; /* Task Tag */ // // DW1 // - UINT8 Rsvd2[2]; - UINT8 Resp; /* Response - 0x00 */ - UINT8 Rsvd3; + UINT8 Rsvd2[2]; + UINT8 Resp; /* Response - 0x00 */ + UINT8 Rsvd3; // // DW2 // - UINT8 EhsLen; /* Total EHS Length - 0x00 */ - UINT8 DevInfo; /* Device Information - 0x00 */ - UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ + UINT8 EhsLen; /* Total EHS Length - 0x00 */ + UINT8 DevInfo; /* Device Information - 0x00 */ + UINT16 DataSegLen; /* Data Segment Length - Big Endian - 0x0000 */ // // DW3 - DW7 // - UINT8 Rsvd4[20]; + UINT8 Rsvd4[20]; } UTP_NOP_IN_UPIU; // // UFS Descriptors // typedef enum { - UfsDeviceDesc = 0x00, - UfsConfigDesc = 0x01, - UfsUnitDesc = 0x02, - UfsInterConnDesc = 0x04, - UfsStringDesc = 0x05, - UfsGeometryDesc = 0x07, - UfsPowerDesc = 0x08 + UfsDeviceDesc = 0x00, + UfsConfigDesc = 0x01, + UfsUnitDesc = 0x02, + UfsInterConnDesc = 0x04, + UfsStringDesc = 0x05, + UfsGeometryDesc = 0x07, + UfsPowerDesc = 0x08 } UFS_DESC_IDN; // // UFS 2.0 Spec Section 14.1.6.2 - Device Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 Device; - UINT8 DevClass; - UINT8 DevSubClass; - UINT8 Protocol; - UINT8 NumLun; - UINT8 NumWLun; - UINT8 BootEn; - UINT8 DescAccessEn; - UINT8 InitPowerMode; - UINT8 HighPriorityLun; - UINT8 SecureRemovalType; - UINT8 SecurityLun; - UINT8 BgOpsTermLat; - UINT8 InitActiveIccLevel; - UINT16 SpecVersion; - UINT16 ManufactureDate; - UINT8 ManufacturerName; - UINT8 ProductName; - UINT8 SerialName; - UINT8 OemId; - UINT16 ManufacturerId; - UINT8 Ud0BaseOffset; - UINT8 Ud0ConfParamLen; - UINT8 DevRttCap; - UINT16 PeriodicRtcUpdate; - UINT8 Rsvd1[17]; - UINT8 Rsvd2[16]; + UINT8 Length; + UINT8 DescType; + UINT8 Device; + UINT8 DevClass; + UINT8 DevSubClass; + UINT8 Protocol; + UINT8 NumLun; + UINT8 NumWLun; + UINT8 BootEn; + UINT8 DescAccessEn; + UINT8 InitPowerMode; + UINT8 HighPriorityLun; + UINT8 SecureRemovalType; + UINT8 SecurityLun; + UINT8 BgOpsTermLat; + UINT8 InitActiveIccLevel; + UINT16 SpecVersion; + UINT16 ManufactureDate; + UINT8 ManufacturerName; + UINT8 ProductName; + UINT8 SerialName; + UINT8 OemId; + UINT16 ManufacturerId; + UINT8 Ud0BaseOffset; + UINT8 Ud0ConfParamLen; + UINT8 DevRttCap; + UINT16 PeriodicRtcUpdate; + UINT8 Rsvd1[17]; + UINT8 Rsvd2[16]; } UFS_DEV_DESC; typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 Rsvd1; - UINT8 BootEn; - UINT8 DescAccessEn; - UINT8 InitPowerMode; - UINT8 HighPriorityLun; - UINT8 SecureRemovalType; - UINT8 InitActiveIccLevel; - UINT16 PeriodicRtcUpdate; - UINT8 Rsvd2[5]; + UINT8 Length; + UINT8 DescType; + UINT8 Rsvd1; + UINT8 BootEn; + UINT8 DescAccessEn; + UINT8 InitPowerMode; + UINT8 HighPriorityLun; + UINT8 SecureRemovalType; + UINT8 InitActiveIccLevel; + UINT16 PeriodicRtcUpdate; + UINT8 Rsvd2[5]; } UFS_CONFIG_DESC_GEN_HEADER; typedef struct { - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 MemType; - UINT32 NumAllocUnits; - UINT8 DataReliability; - UINT8 LogicBlkSize; - UINT8 ProvisionType; - UINT16 CtxCap; - UINT8 Rsvd1[3]; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 MemType; + UINT32 NumAllocUnits; + UINT8 DataReliability; + UINT8 LogicBlkSize; + UINT8 ProvisionType; + UINT16 CtxCap; + UINT8 Rsvd1[3]; } UFS_UNIT_DESC_CONFIG_PARAMS; // // UFS 2.0 Spec Section 14.1.6.3 - Configuration Descriptor // typedef struct { - UFS_CONFIG_DESC_GEN_HEADER Header; - UFS_UNIT_DESC_CONFIG_PARAMS UnitDescConfParams[8]; + UFS_CONFIG_DESC_GEN_HEADER Header; + UFS_UNIT_DESC_CONFIG_PARAMS UnitDescConfParams[8]; } UFS_CONFIG_DESC; // // UFS 2.0 Spec Section 14.1.6.4 - Geometry Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 MediaTech; - UINT8 Rsvd1; - UINT64 TotalRawDevCapacity; - UINT8 Rsvd2; - UINT32 SegSize; - UINT8 AllocUnitSize; - UINT8 MinAddrBlkSize; - UINT8 OptReadBlkSize; - UINT8 OptWriteBlkSize; - UINT8 MaxInBufSize; - UINT8 MaxOutBufSize; - UINT8 RpmbRwSize; - UINT8 Rsvd3; - UINT8 DataOrder; - UINT8 MaxCtxIdNum; - UINT8 SysDataTagUnitSize; - UINT8 SysDataResUnitSize; - UINT8 SupSecRemovalTypes; - UINT16 SupMemTypes; - UINT32 SysCodeMaxNumAllocUnits; - UINT16 SupCodeCapAdjFac; - UINT32 NonPersMaxNumAllocUnits; - UINT16 NonPersCapAdjFac; - UINT32 Enhance1MaxNumAllocUnits; - UINT16 Enhance1CapAdjFac; - UINT32 Enhance2MaxNumAllocUnits; - UINT16 Enhance2CapAdjFac; - UINT32 Enhance3MaxNumAllocUnits; - UINT16 Enhance3CapAdjFac; - UINT32 Enhance4MaxNumAllocUnits; - UINT16 Enhance4CapAdjFac; + UINT8 Length; + UINT8 DescType; + UINT8 MediaTech; + UINT8 Rsvd1; + UINT64 TotalRawDevCapacity; + UINT8 Rsvd2; + UINT32 SegSize; + UINT8 AllocUnitSize; + UINT8 MinAddrBlkSize; + UINT8 OptReadBlkSize; + UINT8 OptWriteBlkSize; + UINT8 MaxInBufSize; + UINT8 MaxOutBufSize; + UINT8 RpmbRwSize; + UINT8 Rsvd3; + UINT8 DataOrder; + UINT8 MaxCtxIdNum; + UINT8 SysDataTagUnitSize; + UINT8 SysDataResUnitSize; + UINT8 SupSecRemovalTypes; + UINT16 SupMemTypes; + UINT32 SysCodeMaxNumAllocUnits; + UINT16 SupCodeCapAdjFac; + UINT32 NonPersMaxNumAllocUnits; + UINT16 NonPersCapAdjFac; + UINT32 Enhance1MaxNumAllocUnits; + UINT16 Enhance1CapAdjFac; + UINT32 Enhance2MaxNumAllocUnits; + UINT16 Enhance2CapAdjFac; + UINT32 Enhance3MaxNumAllocUnits; + UINT16 Enhance3CapAdjFac; + UINT32 Enhance4MaxNumAllocUnits; + UINT16 Enhance4CapAdjFac; } UFS_GEOMETRY_DESC; // // UFS 2.0 Spec Section 14.1.6.5 - Unit Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 UnitIdx; - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 LunQueueDep; - UINT8 Rsvd1; - UINT8 MemType; - UINT8 DataReliability; - UINT8 LogicBlkSize; - UINT64 LogicBlkCount; - UINT32 EraseBlkSize; - UINT8 ProvisionType; - UINT64 PhyMemResCount; - UINT16 CtxCap; - UINT8 LargeUnitGranularity; + UINT8 Length; + UINT8 DescType; + UINT8 UnitIdx; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 LunQueueDep; + UINT8 Rsvd1; + UINT8 MemType; + UINT8 DataReliability; + UINT8 LogicBlkSize; + UINT64 LogicBlkCount; + UINT32 EraseBlkSize; + UINT8 ProvisionType; + UINT64 PhyMemResCount; + UINT16 CtxCap; + UINT8 LargeUnitGranularity; } UFS_UNIT_DESC; // // UFS 2.0 Spec Section 14.1.6.6 - RPMB Unit Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 UnitIdx; - UINT8 LunEn; - UINT8 BootLunId; - UINT8 LunWriteProt; - UINT8 LunQueueDep; - UINT8 Rsvd1; - UINT8 MemType; - UINT8 Rsvd2; - UINT8 LogicBlkSize; - UINT64 LogicBlkCount; - UINT32 EraseBlkSize; - UINT8 ProvisionType; - UINT64 PhyMemResCount; - UINT8 Rsvd3[3]; + UINT8 Length; + UINT8 DescType; + UINT8 UnitIdx; + UINT8 LunEn; + UINT8 BootLunId; + UINT8 LunWriteProt; + UINT8 LunQueueDep; + UINT8 Rsvd1; + UINT8 MemType; + UINT8 Rsvd2; + UINT8 LogicBlkSize; + UINT64 LogicBlkCount; + UINT32 EraseBlkSize; + UINT8 ProvisionType; + UINT64 PhyMemResCount; + UINT8 Rsvd3[3]; } UFS_RPMB_UNIT_DESC; typedef struct { - UINT16 Value:10; - UINT16 Rsvd1:4; - UINT16 Unit:2; + UINT16 Value : 10; + UINT16 Rsvd1 : 4; + UINT16 Unit : 2; } UFS_POWER_PARAM_ELEMENT; // // UFS 2.0 Spec Section 14.1.6.7 - Power Parameter Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVcc[16]; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ[16]; - UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ2[16]; + UINT8 Length; + UINT8 DescType; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVcc[16]; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ[16]; + UFS_POWER_PARAM_ELEMENT ActiveIccLevelVccQ2[16]; } UFS_POWER_DESC; // // UFS 2.0 Spec Section 14.1.6.8 - InterConnect Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT16 UniProVer; - UINT16 MphyVer; + UINT8 Length; + UINT8 DescType; + UINT16 UniProVer; + UINT16 MphyVer; } UFS_INTER_CONNECT_DESC; // // UFS 2.0 Spec Section 14.1.6.9 - 14.1.6.12 - String Descriptor // typedef struct { - UINT8 Length; - UINT8 DescType; - CHAR16 Unicode[126]; + UINT8 Length; + UINT8 DescType; + CHAR16 Unicode[126]; } UFS_STRING_DESC; // @@ -1306,34 +1305,32 @@ typedef enum { // UFS 2.0 Spec Section 14.2 - Attributes // typedef enum { - UfsAttrBootLunEn = 0x00, - UfsAttrCurPowerMode = 0x02, - UfsAttrActiveIccLevel = 0x03, - UfsAttrOutOfOrderDataEn = 0x04, - UfsAttrBgOpStatus = 0x05, - UfsAttrPurgeStatus = 0x06, - UfsAttrMaxDataInSize = 0x07, - UfsAttrMaxDataOutSize = 0x08, - UfsAttrDynCapNeeded = 0x09, - UfsAttrRefClkFreq = 0x0a, - UfsAttrConfigDescLock = 0x0b, - UfsAttrMaxNumOfRtt = 0x0c, - UfsAttrExceptionEvtCtrl = 0x0d, - UfsAttrExceptionEvtSts = 0x0e, - UfsAttrSecondsPassed = 0x0f, - UfsAttrContextConf = 0x10, - UfsAttrCorrPrgBlkNum = 0x11 + UfsAttrBootLunEn = 0x00, + UfsAttrCurPowerMode = 0x02, + UfsAttrActiveIccLevel = 0x03, + UfsAttrOutOfOrderDataEn = 0x04, + UfsAttrBgOpStatus = 0x05, + UfsAttrPurgeStatus = 0x06, + UfsAttrMaxDataInSize = 0x07, + UfsAttrMaxDataOutSize = 0x08, + UfsAttrDynCapNeeded = 0x09, + UfsAttrRefClkFreq = 0x0a, + UfsAttrConfigDescLock = 0x0b, + UfsAttrMaxNumOfRtt = 0x0c, + UfsAttrExceptionEvtCtrl = 0x0d, + UfsAttrExceptionEvtSts = 0x0e, + UfsAttrSecondsPassed = 0x0f, + UfsAttrContextConf = 0x10, + UfsAttrCorrPrgBlkNum = 0x11 } UFS_ATTR_IDN; typedef enum { - UfsNoData = 0, - UfsDataOut = 1, - UfsDataIn = 2, + UfsNoData = 0, + UfsDataOut = 1, + UfsDataIn = 2, UfsDdReserved } UFS_DATA_DIRECTION; - #pragma pack() #endif - diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.c b/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.c index 2b1ca20a63..1df799e71b 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.c +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.c @@ -23,8 +23,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS BotRecoveryReset ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev ) { EFI_USB_DEVICE_REQUEST DevReq; @@ -41,23 +41,23 @@ BotRecoveryReset ( ZeroMem (&DevReq, sizeof (EFI_USB_DEVICE_REQUEST)); - DevReq.RequestType = 0x21; - DevReq.Request = 0xFF; - DevReq.Value = 0; - DevReq.Index = 0; - DevReq.Length = 0; + DevReq.RequestType = 0x21; + DevReq.Request = 0xFF; + DevReq.Value = 0; + DevReq.Index = 0; + DevReq.Length = 0; - Timeout = 3000; + Timeout = 3000; Status = UsbIoPpi->UsbControlTransfer ( - PeiServices, - UsbIoPpi, - &DevReq, - EfiUsbNoData, - Timeout, - NULL, - 0 - ); + PeiServices, + UsbIoPpi, + &DevReq, + EfiUsbNoData, + Timeout, + NULL, + 0 + ); // // clear bulk in endpoint stall feature @@ -96,13 +96,13 @@ BotRecoveryReset ( **/ EFI_STATUS BotCommandPhase ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev, - IN VOID *Command, - IN UINT8 CommandSize, - IN UINT32 DataTransferLength, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT16 Timeout + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev, + IN VOID *Command, + IN UINT8 CommandSize, + IN UINT32 DataTransferLength, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT16 Timeout ) { CBW Cbw; @@ -117,25 +117,25 @@ BotCommandPhase ( // // Fill the command block, detailed see BOT spec // - Cbw.Signature = CBWSIG; - Cbw.Tag = 0x01; - Cbw.DataTransferLength = DataTransferLength; - Cbw.Flags = (UINT8) ((Direction == EfiUsbDataIn) ? 0x80 : 0); - Cbw.Lun = 0; - Cbw.CmdLen = CommandSize; + Cbw.Signature = CBWSIG; + Cbw.Tag = 0x01; + Cbw.DataTransferLength = DataTransferLength; + Cbw.Flags = (UINT8)((Direction == EfiUsbDataIn) ? 0x80 : 0); + Cbw.Lun = 0; + Cbw.CmdLen = CommandSize; CopyMem (Cbw.CmdBlock, Command, CommandSize); DataSize = sizeof (CBW); Status = UsbIoPpi->UsbBulkTransfer ( - PeiServices, - UsbIoPpi, - (PeiBotDev->BulkOutEndpoint)->EndpointAddress, - (UINT8 *) &Cbw, - &DataSize, - Timeout - ); + PeiServices, + UsbIoPpi, + (PeiBotDev->BulkOutEndpoint)->EndpointAddress, + (UINT8 *)&Cbw, + &DataSize, + Timeout + ); if (EFI_ERROR (Status)) { // // Command phase fail, we need to recovery reset this device @@ -168,12 +168,12 @@ BotCommandPhase ( **/ EFI_STATUS BotDataPhase ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev, - IN UINT32 *DataSize, - IN OUT VOID *DataBuffer, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT16 Timeout + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev, + IN UINT32 *DataSize, + IN OUT VOID *DataBuffer, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT16 Timeout ) { EFI_STATUS Status; @@ -185,21 +185,21 @@ BotDataPhase ( UINT8 *BufferPtr; UINTN TransferredSize; - UsbIoPpi = PeiBotDev->UsbIoPpi; + UsbIoPpi = PeiBotDev->UsbIoPpi; Remain = *DataSize; - BufferPtr = (UINT8 *) DataBuffer; + BufferPtr = (UINT8 *)DataBuffer; TransferredSize = 0; // // retrieve the max packet length of the given endpoint // if (Direction == EfiUsbDataIn) { - MaxPacketLen = (PeiBotDev->BulkInEndpoint)->MaxPacketSize; - EndpointAddr = (PeiBotDev->BulkInEndpoint)->EndpointAddress; + MaxPacketLen = (PeiBotDev->BulkInEndpoint)->MaxPacketSize; + EndpointAddr = (PeiBotDev->BulkInEndpoint)->EndpointAddress; } else { - MaxPacketLen = (PeiBotDev->BulkOutEndpoint)->MaxPacketSize; - EndpointAddr = (PeiBotDev->BulkOutEndpoint)->EndpointAddress; + MaxPacketLen = (PeiBotDev->BulkOutEndpoint)->MaxPacketSize; + EndpointAddr = (PeiBotDev->BulkOutEndpoint)->EndpointAddress; } while (Remain > 0) { @@ -213,13 +213,13 @@ BotDataPhase ( } Status = UsbIoPpi->UsbBulkTransfer ( - PeiServices, - UsbIoPpi, - EndpointAddr, - BufferPtr, - &Increment, - Timeout - ); + PeiServices, + UsbIoPpi, + EndpointAddr, + BufferPtr, + &Increment, + Timeout + ); TransferredSize += Increment; @@ -229,10 +229,10 @@ BotDataPhase ( } BufferPtr += Increment; - Remain -= Increment; + Remain -= Increment; } - *DataSize = (UINT32) TransferredSize; + *DataSize = (UINT32)TransferredSize; return EFI_SUCCESS; } @@ -256,10 +256,10 @@ BotDataPhase ( **/ EFI_STATUS BotStatusPhase ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev, - OUT UINT8 *TransferStatus, - IN UINT16 Timeout + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev, + OUT UINT8 *TransferStatus, + IN UINT16 Timeout ) { CSW Csw; @@ -272,21 +272,21 @@ BotStatusPhase ( ZeroMem (&Csw, sizeof (CSW)); - EndpointAddr = (PeiBotDev->BulkInEndpoint)->EndpointAddress; + EndpointAddr = (PeiBotDev->BulkInEndpoint)->EndpointAddress; - DataSize = sizeof (CSW); + DataSize = sizeof (CSW); // // Get the status field from bulk transfer // Status = UsbIoPpi->UsbBulkTransfer ( - PeiServices, - UsbIoPpi, - EndpointAddr, - &Csw, - &DataSize, - Timeout - ); + PeiServices, + UsbIoPpi, + EndpointAddr, + &Csw, + &DataSize, + Timeout + ); if (EFI_ERROR (Status)) { return Status; } @@ -319,14 +319,14 @@ BotStatusPhase ( **/ EFI_STATUS PeiAtapiCommand ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev, - IN VOID *Command, - IN UINT8 CommandSize, - IN VOID *DataBuffer, - IN UINT32 BufferLength, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT16 TimeOutInMilliSeconds + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev, + IN VOID *Command, + IN UINT8 CommandSize, + IN VOID *DataBuffer, + IN UINT32 BufferLength, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT16 TimeOutInMilliSeconds ) { EFI_STATUS Status; @@ -339,48 +339,50 @@ PeiAtapiCommand ( // First send ATAPI command through Bot // Status = BotCommandPhase ( - PeiServices, - PeiBotDev, - Command, - CommandSize, - BufferLength, - Direction, - TimeOutInMilliSeconds - ); + PeiServices, + PeiBotDev, + Command, + CommandSize, + BufferLength, + Direction, + TimeOutInMilliSeconds + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } + // // Send/Get Data if there is a Data Stage // switch (Direction) { - case EfiUsbDataIn: - case EfiUsbDataOut: - BufferSize = BufferLength; - - BotDataStatus = BotDataPhase ( - PeiServices, - PeiBotDev, - &BufferSize, - DataBuffer, - Direction, - TimeOutInMilliSeconds - ); - break; - - case EfiUsbNoData: - break; + case EfiUsbDataIn: + case EfiUsbDataOut: + BufferSize = BufferLength; + + BotDataStatus = BotDataPhase ( + PeiServices, + PeiBotDev, + &BufferSize, + DataBuffer, + Direction, + TimeOutInMilliSeconds + ); + break; + + case EfiUsbNoData: + break; } + // // Status Phase // Status = BotStatusPhase ( - PeiServices, - PeiBotDev, - &TransferStatus, - TimeOutInMilliSeconds - ); + PeiServices, + PeiBotDev, + &TransferStatus, + TimeOutInMilliSeconds + ); if (EFI_ERROR (Status)) { BotRecoveryReset (PeiServices, PeiBotDev); return EFI_DEVICE_ERROR; diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.h b/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.h index a4ad759b0b..54d149e45b 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.h +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/BotPeim.h @@ -10,14 +10,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_BOT_PEIM_H_ #define _PEI_BOT_PEIM_H_ - #include #include #include #include -//#include +// #include #include #include #include @@ -29,20 +28,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Bulk Only device protocol // typedef struct { - UINT32 Signature; - UINT32 Tag; - UINT32 DataTransferLength; - UINT8 Flags; - UINT8 Lun; - UINT8 CmdLen; - UINT8 CmdBlock[16]; + UINT32 Signature; + UINT32 Tag; + UINT32 DataTransferLength; + UINT8 Flags; + UINT8 Lun; + UINT8 CmdLen; + UINT8 CmdBlock[16]; } CBW; typedef struct { - UINT32 Signature; - UINT32 Tag; - UINT32 DataResidue; - UINT8 Status; + UINT32 Signature; + UINT32 Tag; + UINT32 DataResidue; + UINT8 Status; } CSW; #pragma pack() @@ -178,8 +177,8 @@ PeiUsbRead10 ( **/ BOOLEAN IsNoMedia ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -194,8 +193,8 @@ IsNoMedia ( **/ BOOLEAN IsMediaError ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); /** @@ -210,8 +209,8 @@ IsMediaError ( **/ BOOLEAN IsMediaChange ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c index c5ba307e75..422ac5fec9 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiAtapi.c @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbBotPeim.h" #include "BotPeim.h" -#define MAXSENSEKEY 5 +#define MAXSENSEKEY 5 /** Sends out ATAPI Inquiry Packet Command to the specified device. This command will @@ -31,7 +31,7 @@ PeiUsbInquiry ( { ATAPI_PACKET_COMMAND Packet; EFI_STATUS Status; - ATAPI_INQUIRY_DATA Idata; + ATAPI_INQUIRY_DATA Idata; // // fill command packet @@ -39,9 +39,9 @@ PeiUsbInquiry ( ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); ZeroMem (&Idata, sizeof (ATAPI_INQUIRY_DATA)); - Packet.Inquiry.opcode = ATA_CMD_INQUIRY; - Packet.Inquiry.page_code = 0; - Packet.Inquiry.allocation_length = 36; + Packet.Inquiry.opcode = ATA_CMD_INQUIRY; + Packet.Inquiry.page_code = 0; + Packet.Inquiry.allocation_length = 36; // // Send scsi INQUIRY command packet. @@ -49,29 +49,29 @@ PeiUsbInquiry ( // retrieve the first 36 bytes for standard INQUIRY data. // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - &Idata, - 36, - EfiUsbDataIn, - 2000 - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + &Idata, + 36, + EfiUsbDataIn, + 2000 + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } if ((Idata.peripheral_type & 0x1f) == 0x05) { - PeiBotDevice->DeviceType = USBCDROM; - PeiBotDevice->Media.BlockSize = 0x800; + PeiBotDevice->DeviceType = USBCDROM; + PeiBotDevice->Media.BlockSize = 0x800; PeiBotDevice->Media2.ReadOnly = TRUE; PeiBotDevice->Media2.RemovableMedia = TRUE; PeiBotDevice->Media2.BlockSize = 0x800; } else { - PeiBotDevice->DeviceType = USBFLOPPY; - PeiBotDevice->Media.BlockSize = 0x200; + PeiBotDevice->DeviceType = USBFLOPPY; + PeiBotDevice->Media.BlockSize = 0x200; PeiBotDevice->Media2.ReadOnly = FALSE; PeiBotDevice->Media2.RemovableMedia = TRUE; PeiBotDevice->Media2.BlockSize = 0x200; @@ -110,15 +110,15 @@ PeiUsbTestUnitReady ( // send command packet // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - NULL, - 0, - EfiUsbNoData, - 2000 - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + NULL, + 0, + EfiUsbNoData, + 2000 + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -147,11 +147,11 @@ PeiUsbRequestSense ( IN UINT8 *SenseKeyBuffer ) { - EFI_STATUS Status; - ATAPI_PACKET_COMMAND Packet; - UINT8 *Ptr; - BOOLEAN SenseReq; - ATAPI_REQUEST_SENSE_DATA *Sense; + EFI_STATUS Status; + ATAPI_PACKET_COMMAND Packet; + UINT8 *Ptr; + BOOLEAN SenseReq; + ATAPI_REQUEST_SENSE_DATA *Sense; *SenseCounts = 0; @@ -160,7 +160,7 @@ PeiUsbRequestSense ( // ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); Packet.RequestSence.opcode = ATA_CMD_REQUEST_SENSE; - Packet.RequestSence.allocation_length = (UINT8) sizeof (ATAPI_REQUEST_SENSE_DATA); + Packet.RequestSence.allocation_length = (UINT8)sizeof (ATAPI_REQUEST_SENSE_DATA); Ptr = SenseKeyBuffer; @@ -171,22 +171,22 @@ PeiUsbRequestSense ( // until no sense data exists in the device. // while (SenseReq) { - Sense = (ATAPI_REQUEST_SENSE_DATA *) Ptr; + Sense = (ATAPI_REQUEST_SENSE_DATA *)Ptr; // // send out Request Sense Packet Command and get one Sense // data form device. // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - (VOID *) Ptr, - sizeof (ATAPI_REQUEST_SENSE_DATA), - EfiUsbDataIn, - 2000 - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + (VOID *)Ptr, + sizeof (ATAPI_REQUEST_SENSE_DATA), + EfiUsbDataIn, + 2000 + ); // // failed to get Sense data @@ -200,7 +200,6 @@ PeiUsbRequestSense ( } if (Sense->sense_key != ATA_SK_NO_SENSE) { - Ptr += sizeof (ATAPI_REQUEST_SENSE_DATA); // // Ptr is byte based pointer @@ -210,7 +209,6 @@ PeiUsbRequestSense ( if (*SenseCounts == MAXSENSEKEY) { break; } - } else { // // when no sense key, skip out the loop @@ -240,10 +238,10 @@ PeiUsbReadCapacity ( IN PEI_BOT_DEVICE *PeiBotDevice ) { - EFI_STATUS Status; - ATAPI_PACKET_COMMAND Packet; - ATAPI_READ_CAPACITY_DATA Data; - UINT32 LastBlock; + EFI_STATUS Status; + ATAPI_PACKET_COMMAND Packet; + ATAPI_READ_CAPACITY_DATA Data; + UINT32 LastBlock; ZeroMem (&Data, sizeof (ATAPI_READ_CAPACITY_DATA)); ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); @@ -254,20 +252,21 @@ PeiUsbReadCapacity ( // send command packet // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - (VOID *) &Data, - sizeof (ATAPI_READ_CAPACITY_DATA), - EfiUsbDataIn, - 2000 - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + (VOID *)&Data, + sizeof (ATAPI_READ_CAPACITY_DATA), + EfiUsbDataIn, + 2000 + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } - LastBlock = ((UINT32) Data.LastLba3 << 24) | (Data.LastLba2 << 16) | (Data.LastLba1 << 8) | Data.LastLba0; + + LastBlock = ((UINT32)Data.LastLba3 << 24) | (Data.LastLba2 << 16) | (Data.LastLba1 << 8) | Data.LastLba0; if (LastBlock == 0xFFFFFFFF) { DEBUG ((DEBUG_INFO, "The usb device LBA count is larger than 0xFFFFFFFF!\n")); @@ -300,30 +299,30 @@ PeiUsbReadFormattedCapacity ( IN PEI_BOT_DEVICE *PeiBotDevice ) { - EFI_STATUS Status; - ATAPI_PACKET_COMMAND Packet; - ATAPI_READ_FORMAT_CAPACITY_DATA FormatData; - UINT32 LastBlock; + EFI_STATUS Status; + ATAPI_PACKET_COMMAND Packet; + ATAPI_READ_FORMAT_CAPACITY_DATA FormatData; + UINT32 LastBlock; ZeroMem (&FormatData, sizeof (ATAPI_READ_FORMAT_CAPACITY_DATA)); ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); - Packet.ReadFormatCapacity.opcode = ATA_CMD_READ_FORMAT_CAPACITY; - Packet.ReadFormatCapacity.allocation_length_lo = 12; + Packet.ReadFormatCapacity.opcode = ATA_CMD_READ_FORMAT_CAPACITY; + Packet.ReadFormatCapacity.allocation_length_lo = 12; // // send command packet // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - (VOID *) &FormatData, - sizeof (ATAPI_READ_FORMAT_CAPACITY_DATA), - EfiUsbDataIn, - 2000 - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + (VOID *)&FormatData, + sizeof (ATAPI_READ_FORMAT_CAPACITY_DATA), + EfiUsbDataIn, + 2000 + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -335,11 +334,10 @@ PeiUsbReadFormattedCapacity ( // PeiBotDevice->Media.MediaPresent = FALSE; PeiBotDevice->Media.LastBlock = 0; - PeiBotDevice->Media2.MediaPresent = FALSE; - PeiBotDevice->Media2.LastBlock = 0; - + PeiBotDevice->Media2.MediaPresent = FALSE; + PeiBotDevice->Media2.LastBlock = 0; } else { - LastBlock = ((UINT32) FormatData.LastLba3 << 24) | (FormatData.LastLba2 << 16) | (FormatData.LastLba1 << 8) | FormatData.LastLba0; + LastBlock = ((UINT32)FormatData.LastLba3 << 24) | (FormatData.LastLba2 << 16) | (FormatData.LastLba1 << 8) | FormatData.LastLba0; if (LastBlock == 0xFFFFFFFF) { DEBUG ((DEBUG_INFO, "The usb device LBA count is larger than 0xFFFFFFFF!\n")); } @@ -397,26 +395,23 @@ PeiUsbRead10 ( // prepare command packet for the Inquiry Packet Command. // ZeroMem (&Packet, sizeof (ATAPI_PACKET_COMMAND)); - Read10Packet = &Packet.Read10; - Lba32 = (UINT32) Lba; - PtrBuffer = Buffer; + Read10Packet = &Packet.Read10; + Lba32 = (UINT32)Lba; + PtrBuffer = Buffer; - BlockSize = (UINT32) PeiBotDevice->Media.BlockSize; + BlockSize = (UINT32)PeiBotDevice->Media.BlockSize; - MaxBlock = (UINT16) (65535 / BlockSize); - BlocksRemaining = (UINT16) NumberOfBlocks; + MaxBlock = (UINT16)(65535 / BlockSize); + BlocksRemaining = (UINT16)NumberOfBlocks; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; while (BlocksRemaining > 0) { - if (BlocksRemaining <= MaxBlock) { - SectorCount = BlocksRemaining; - } else { - SectorCount = MaxBlock; } + // // fill the Packet data structure // @@ -426,43 +421,43 @@ PeiUsbRead10 ( // Lba0 ~ Lba3 specify the start logical block address of the data transfer. // Lba0 is MSB, Lba3 is LSB // - Read10Packet->Lba3 = (UINT8) (Lba32 & 0xff); - Read10Packet->Lba2 = (UINT8) (Lba32 >> 8); - Read10Packet->Lba1 = (UINT8) (Lba32 >> 16); - Read10Packet->Lba0 = (UINT8) (Lba32 >> 24); + Read10Packet->Lba3 = (UINT8)(Lba32 & 0xff); + Read10Packet->Lba2 = (UINT8)(Lba32 >> 8); + Read10Packet->Lba1 = (UINT8)(Lba32 >> 16); + Read10Packet->Lba0 = (UINT8)(Lba32 >> 24); // // TranLen0 ~ TranLen1 specify the transfer length in block unit. // TranLen0 is MSB, TranLen is LSB // - Read10Packet->TranLen1 = (UINT8) (SectorCount & 0xff); - Read10Packet->TranLen0 = (UINT8) (SectorCount >> 8); + Read10Packet->TranLen1 = (UINT8)(SectorCount & 0xff); + Read10Packet->TranLen0 = (UINT8)(SectorCount >> 8); - ByteCount = SectorCount * BlockSize; + ByteCount = SectorCount * BlockSize; - TimeOut = (UINT16) (SectorCount * 2000); + TimeOut = (UINT16)(SectorCount * 2000); // // send command packet // Status = PeiAtapiCommand ( - PeiServices, - PeiBotDevice, - &Packet, - (UINT8) sizeof (ATAPI_PACKET_COMMAND), - (VOID *) PtrBuffer, - ByteCount, - EfiUsbDataIn, - TimeOut - ); + PeiServices, + PeiBotDevice, + &Packet, + (UINT8)sizeof (ATAPI_PACKET_COMMAND), + (VOID *)PtrBuffer, + ByteCount, + EfiUsbDataIn, + TimeOut + ); if (Status != EFI_SUCCESS) { return Status; } - Lba32 += SectorCount; - PtrBuffer = (UINT8 *) PtrBuffer + SectorCount * BlockSize; - BlocksRemaining = (UINT16) (BlocksRemaining - SectorCount); + Lba32 += SectorCount; + PtrBuffer = (UINT8 *)PtrBuffer + SectorCount * BlockSize; + BlocksRemaining = (UINT16)(BlocksRemaining - SectorCount); } return Status; @@ -480,37 +475,36 @@ PeiUsbRead10 ( **/ BOOLEAN IsNoMedia ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { ATAPI_REQUEST_SENSE_DATA *SensePtr; UINTN Index; BOOLEAN NoMedia; - NoMedia = FALSE; - SensePtr = SenseData; + NoMedia = FALSE; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->sense_key) { + case ATA_SK_NOT_READY: + switch (SensePtr->addnl_sense_code) { + // + // if no media, fill IdeDev parameter with specific info. + // + case ATA_ASC_NO_MEDIA: + NoMedia = TRUE; + break; + + default: + break; + } - case ATA_SK_NOT_READY: - switch (SensePtr->addnl_sense_code) { - // - // if no media, fill IdeDev parameter with specific info. - // - case ATA_ASC_NO_MEDIA: - NoMedia = TRUE; break; default: break; - } - break; - - default: - break; } SensePtr++; @@ -531,63 +525,63 @@ IsNoMedia ( **/ BOOLEAN IsMediaError ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { ATAPI_REQUEST_SENSE_DATA *SensePtr; UINTN Index; BOOLEAN Error; - SensePtr = SenseData; - Error = FALSE; + SensePtr = SenseData; + Error = FALSE; for (Index = 0; Index < SenseCounts; Index++) { - switch (SensePtr->sense_key) { - // - // Medium error case - // - case ATA_SK_MEDIUM_ERROR: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_MEDIA_ERR1: - // - // fall through - // - case ATA_ASC_MEDIA_ERR2: - // - // fall through - // - case ATA_ASC_MEDIA_ERR3: - // - // fall through - // - case ATA_ASC_MEDIA_ERR4: - Error = TRUE; - break; + // + // Medium error case + // + case ATA_SK_MEDIUM_ERROR: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_MEDIA_ERR1: + // + // fall through + // + case ATA_ASC_MEDIA_ERR2: + // + // fall through + // + case ATA_ASC_MEDIA_ERR3: + // + // fall through + // + case ATA_ASC_MEDIA_ERR4: + Error = TRUE; + break; + + default: + break; + } - default: break; - } - break; + // + // Medium upside-down case + // + case ATA_SK_NOT_READY: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_MEDIA_UPSIDE_DOWN: + Error = TRUE; + break; + + default: + break; + } - // - // Medium upside-down case - // - case ATA_SK_NOT_READY: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_MEDIA_UPSIDE_DOWN: - Error = TRUE; break; default: break; - } - break; - - default: - break; } SensePtr++; @@ -608,8 +602,8 @@ IsMediaError ( **/ BOOLEAN IsMediaChange ( - IN ATAPI_REQUEST_SENSE_DATA *SenseData, - IN UINTN SenseCounts + IN ATAPI_REQUEST_SENSE_DATA *SenseData, + IN UINTN SenseCounts ) { ATAPI_REQUEST_SENSE_DATA *SensePtr; @@ -618,26 +612,27 @@ IsMediaChange ( MediaChange = FALSE; - SensePtr = SenseData; + SensePtr = SenseData; for (Index = 0; Index < SenseCounts; Index++) { // // catch media change sense key and addition sense data // switch (SensePtr->sense_key) { - case ATA_SK_UNIT_ATTENTION: - switch (SensePtr->addnl_sense_code) { - case ATA_ASC_MEDIA_CHANGE: - MediaChange = TRUE; + case ATA_SK_UNIT_ATTENTION: + switch (SensePtr->addnl_sense_code) { + case ATA_ASC_MEDIA_CHANGE: + MediaChange = TRUE; + break; + + default: + break; + } + break; default: break; - } - break; - - default: - break; } SensePtr++; diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c index 292682a2e4..dfc4e40698 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.c @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbPeim.h" #include "PeiUsbLib.h" - /** Clear a given usb feature. @@ -27,11 +26,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PeiUsbClearDeviceFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN EFI_USB_RECIPIENT Recipient, - IN UINT16 Value, - IN UINT16 Target + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN EFI_USB_RECIPIENT Recipient, + IN UINT16 Value, + IN UINT16 Target ) { EFI_USB_DEVICE_REQUEST DevReq; @@ -39,23 +38,23 @@ PeiUsbClearDeviceFeature ( ASSERT (UsbIoPpi != NULL); switch (Recipient) { - case EfiUsbDevice: - DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_D; - break; + case EfiUsbDevice: + DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_D; + break; - case EfiUsbInterface: - DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_I; - break; + case EfiUsbInterface: + DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_I; + break; - case EfiUsbEndpoint: - DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_E; - break; + case EfiUsbEndpoint: + DevReq.RequestType = USB_DEV_CLEAR_FEATURE_REQ_TYPE_E; + break; } - DevReq.Request = USB_DEV_CLEAR_FEATURE; - DevReq.Value = Value; - DevReq.Index = Target; - DevReq.Length = 0; + DevReq.Request = USB_DEV_CLEAR_FEATURE; + DevReq.Value = Value; + DevReq.Index = Target; + DevReq.Length = 0; return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -68,7 +67,6 @@ PeiUsbClearDeviceFeature ( ); } - /** Clear Endpoint Halt. @@ -83,9 +81,9 @@ PeiUsbClearDeviceFeature ( **/ EFI_STATUS PeiUsbClearEndpointHalt ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 EndpointAddress + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 EndpointAddress ) { EFI_STATUS Status; @@ -93,18 +91,18 @@ PeiUsbClearEndpointHalt ( EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor; UINT8 EndpointIndex; - // // Check its interface // Status = UsbIoPpi->UsbGetInterfaceDescriptor ( - PeiServices, - UsbIoPpi, - &InterfaceDesc - ); + PeiServices, + UsbIoPpi, + &InterfaceDesc + ); if (EFI_ERROR (Status)) { return Status; } + for (EndpointIndex = 0; EndpointIndex < InterfaceDesc->NumEndpoints; EndpointIndex++) { Status = UsbIoPpi->UsbGetEndpointDescriptor (PeiServices, UsbIoPpi, EndpointIndex, &EndpointDescriptor); if (EFI_ERROR (Status)) { @@ -121,14 +119,12 @@ PeiUsbClearEndpointHalt ( } Status = PeiUsbClearDeviceFeature ( - PeiServices, - UsbIoPpi, - EfiUsbEndpoint, - EfiUsbEndpointHalt, - EndpointAddress - ); + PeiServices, + UsbIoPpi, + EfiUsbEndpoint, + EfiUsbEndpointHalt, + EndpointAddress + ); return Status; } - - diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.h b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.h index e06e2533a7..41894610a2 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.h +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/PeiUsbLib.h @@ -13,29 +13,29 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Standard device request and request type // By [Spec-USB20/Chapter-9.4] // -#define USB_DEV_GET_STATUS 0x00 -#define USB_DEV_GET_STATUS_REQ_TYPE_D 0x80 // Receiver : Device -#define USB_DEV_GET_STATUS_REQ_TYPE_I 0x81 // Receiver : Interface -#define USB_DEV_GET_STATUS_REQ_TYPE_E 0x82 // Receiver : Endpoint +#define USB_DEV_GET_STATUS 0x00 +#define USB_DEV_GET_STATUS_REQ_TYPE_D 0x80 // Receiver : Device +#define USB_DEV_GET_STATUS_REQ_TYPE_I 0x81 // Receiver : Interface +#define USB_DEV_GET_STATUS_REQ_TYPE_E 0x82 // Receiver : Endpoint -#define USB_DEV_CLEAR_FEATURE 0x01 -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint +#define USB_DEV_CLEAR_FEATURE 0x01 +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint -#define USB_DEV_SET_FEATURE 0x03 -#define USB_DEV_SET_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device -#define USB_DEV_SET_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface -#define USB_DEV_SET_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint +#define USB_DEV_SET_FEATURE 0x03 +#define USB_DEV_SET_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device +#define USB_DEV_SET_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface +#define USB_DEV_SET_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint -#define USB_DEV_SET_ADDRESS 0x05 -#define USB_DEV_SET_ADDRESS_REQ_TYPE 0x00 +#define USB_DEV_SET_ADDRESS 0x05 +#define USB_DEV_SET_ADDRESS_REQ_TYPE 0x00 -#define USB_DEV_GET_DESCRIPTOR 0x06 -#define USB_DEV_GET_DESCRIPTOR_REQ_TYPE 0x80 +#define USB_DEV_GET_DESCRIPTOR 0x06 +#define USB_DEV_GET_DESCRIPTOR_REQ_TYPE 0x80 -#define USB_DEV_SET_DESCRIPTOR 0x07 -#define USB_DEV_SET_DESCRIPTOR_REQ_TYPE 0x00 +#define USB_DEV_SET_DESCRIPTOR 0x07 +#define USB_DEV_SET_DESCRIPTOR_REQ_TYPE 0x00 #define USB_DEV_GET_CONFIGURATION 0x08 #define USB_DEV_GET_CONFIGURATION_REQ_TYPE 0x80 @@ -43,14 +43,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USB_DEV_SET_CONFIGURATION 0x09 #define USB_DEV_SET_CONFIGURATION_REQ_TYPE 0x00 -#define USB_DEV_GET_INTERFACE 0x0A -#define USB_DEV_GET_INTERFACE_REQ_TYPE 0x81 +#define USB_DEV_GET_INTERFACE 0x0A +#define USB_DEV_GET_INTERFACE_REQ_TYPE 0x81 -#define USB_DEV_SET_INTERFACE 0x0B -#define USB_DEV_SET_INTERFACE_REQ_TYPE 0x01 +#define USB_DEV_SET_INTERFACE 0x0B +#define USB_DEV_SET_INTERFACE_REQ_TYPE 0x01 -#define USB_DEV_SYNCH_FRAME 0x0C -#define USB_DEV_SYNCH_FRAME_REQ_TYPE 0x82 +#define USB_DEV_SYNCH_FRAME 0x0C +#define USB_DEV_SYNCH_FRAME_REQ_TYPE 0x82 // // USB Descriptor types @@ -66,18 +66,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // USB request type // -#define USB_TYPE_STANDARD (0x00 << 5) -#define USB_TYPE_CLASS (0x01 << 5) -#define USB_TYPE_VENDOR (0x02 << 5) -#define USB_TYPE_RESERVED (0x03 << 5) +#define USB_TYPE_STANDARD (0x00 << 5) +#define USB_TYPE_CLASS (0x01 << 5) +#define USB_TYPE_VENDOR (0x02 << 5) +#define USB_TYPE_RESERVED (0x03 << 5) // // USB request targer device // -#define USB_RECIP_DEVICE 0x00 -#define USB_RECIP_INTERFACE 0x01 -#define USB_RECIP_ENDPOINT 0x02 -#define USB_RECIP_OTHER 0x03 +#define USB_RECIP_DEVICE 0x00 +#define USB_RECIP_INTERFACE 0x01 +#define USB_RECIP_ENDPOINT 0x02 +#define USB_RECIP_OTHER 0x03 typedef enum { EfiUsbEndpointHalt, @@ -93,7 +93,6 @@ typedef enum { EfiUsbEndpoint } EFI_USB_RECIPIENT; - /** Clear a given usb feature. @@ -110,14 +109,13 @@ typedef enum { **/ EFI_STATUS PeiUsbClearDeviceFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN EFI_USB_RECIPIENT Recipient, - IN UINT16 Value, - IN UINT16 Target + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN EFI_USB_RECIPIENT Recipient, + IN UINT16 Value, + IN UINT16 Target ); - /** Clear Endpoint Halt. @@ -132,12 +130,9 @@ PeiUsbClearDeviceFeature ( **/ EFI_STATUS PeiUsbClearEndpointHalt ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 EndpointAddress + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 EndpointAddress ); - - - #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.c b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.c index e110626886..ef62f441e3 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.c +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.c @@ -12,26 +12,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Global function // -EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { +EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { EFI_PEI_PPI_DESCRIPTOR_NOTIFY_DISPATCH | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, &gPeiUsbIoPpiGuid, NotifyOnUsbIoPpi }; -EFI_PEI_RECOVERY_BLOCK_IO_PPI mRecoveryBlkIoPpi = { +EFI_PEI_RECOVERY_BLOCK_IO_PPI mRecoveryBlkIoPpi = { BotGetNumberOfBlockDevices, BotGetMediaInfo, BotReadBlocks }; -EFI_PEI_RECOVERY_BLOCK_IO2_PPI mRecoveryBlkIo2Ppi = { +EFI_PEI_RECOVERY_BLOCK_IO2_PPI mRecoveryBlkIo2Ppi = { EFI_PEI_RECOVERY_BLOCK_IO2_PPI_REVISION, BotGetNumberOfBlockDevices2, BotGetMediaInfo2, BotReadBlocks2 }; -EFI_PEI_PPI_DESCRIPTOR mPpiList[2] = { +EFI_PEI_PPI_DESCRIPTOR mPpiList[2] = { { EFI_PEI_PPI_DESCRIPTOR_PPI, &gEfiPeiVirtualBlockIoPpiGuid, @@ -57,8 +57,8 @@ EFI_PEI_PPI_DESCRIPTOR mPpiList[2] = { **/ EFI_STATUS PeiBotDetectMedia ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev ); /** @@ -74,14 +74,14 @@ PeiBotDetectMedia ( EFI_STATUS EFIAPI PeimInitializeUsbBot ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - UINTN UsbIoPpiInstance; - EFI_PEI_PPI_DESCRIPTOR *TempPpiDescriptor; - PEI_USB_IO_PPI *UsbIoPpi; + EFI_STATUS Status; + UINTN UsbIoPpiInstance; + EFI_PEI_PPI_DESCRIPTOR *TempPpiDescriptor; + PEI_USB_IO_PPI *UsbIoPpi; // // Shadow this PEIM to run from memory @@ -94,17 +94,17 @@ PeimInitializeUsbBot ( // locate all usb io PPIs // for (UsbIoPpiInstance = 0; UsbIoPpiInstance < PEI_FAT_MAX_USB_IO_PPI; UsbIoPpiInstance++) { - Status = PeiServicesLocatePpi ( - &gPeiUsbIoPpiGuid, - UsbIoPpiInstance, - &TempPpiDescriptor, - (VOID **) &UsbIoPpi - ); + &gPeiUsbIoPpiGuid, + UsbIoPpiInstance, + &TempPpiDescriptor, + (VOID **)&UsbIoPpi + ); if (EFI_ERROR (Status)) { break; } } + // // Register a notify function // @@ -127,14 +127,14 @@ PeimInitializeUsbBot ( EFI_STATUS EFIAPI NotifyOnUsbIoPpi ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, - IN VOID *InvokePpi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, + IN VOID *InvokePpi ) { PEI_USB_IO_PPI *UsbIoPpi; - UsbIoPpi = (PEI_USB_IO_PPI *) InvokePpi; + UsbIoPpi = (PEI_USB_IO_PPI *)InvokePpi; InitUsbBot (PeiServices, UsbIoPpi); @@ -154,8 +154,8 @@ NotifyOnUsbIoPpi ( **/ EFI_STATUS InitUsbBot ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi ) { PEI_BOT_DEVICE *PeiBotDevice; @@ -170,45 +170,45 @@ InitUsbBot ( // Check its interface // Status = UsbIoPpi->UsbGetInterfaceDescriptor ( - PeiServices, - UsbIoPpi, - &InterfaceDesc - ); + PeiServices, + UsbIoPpi, + &InterfaceDesc + ); if (EFI_ERROR (Status)) { return Status; } + // // Check if it is the BOT device we support // if ((InterfaceDesc->InterfaceClass != 0x08) || (InterfaceDesc->InterfaceProtocol != 0x50)) { - return EFI_NOT_FOUND; } MemPages = sizeof (PEI_BOT_DEVICE) / EFI_PAGE_SIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &AllocateAddress - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &AllocateAddress + ); if (EFI_ERROR (Status)) { return Status; } - PeiBotDevice = (PEI_BOT_DEVICE *) ((UINTN) AllocateAddress); + PeiBotDevice = (PEI_BOT_DEVICE *)((UINTN)AllocateAddress); PeiBotDevice->Signature = PEI_BOT_DEVICE_SIGNATURE; PeiBotDevice->UsbIoPpi = UsbIoPpi; - PeiBotDevice->AllocateAddress = (UINTN) AllocateAddress; + PeiBotDevice->AllocateAddress = (UINTN)AllocateAddress; PeiBotDevice->BotInterface = InterfaceDesc; // // Default value // - PeiBotDevice->Media.DeviceType = UsbMassStorage; - PeiBotDevice->Media.BlockSize = 0x200; - PeiBotDevice->Media2.InterfaceType = MSG_USB_DP; - PeiBotDevice->Media2.BlockSize = 0x200; + PeiBotDevice->Media.DeviceType = UsbMassStorage; + PeiBotDevice->Media.BlockSize = 0x200; + PeiBotDevice->Media2.InterfaceType = MSG_USB_DP; + PeiBotDevice->Media2.BlockSize = 0x200; PeiBotDevice->Media2.RemovableMedia = FALSE; PeiBotDevice->Media2.ReadOnly = FALSE; @@ -217,11 +217,11 @@ InitUsbBot ( // for (Index = 0; Index < 2; Index++) { Status = UsbIoPpi->UsbGetEndpointDescriptor ( - PeiServices, - UsbIoPpi, - Index, - &EndpointDesc - ); + PeiServices, + UsbIoPpi, + Index, + &EndpointDesc + ); if (EFI_ERROR (Status)) { return Status; @@ -257,7 +257,7 @@ InitUsbBot ( PeiBotDevice->BlkIoPpiList.Ppi = &PeiBotDevice->BlkIoPpi; PeiBotDevice->BlkIo2PpiList.Ppi = &PeiBotDevice->BlkIo2Ppi; - Status = PeiUsbInquiry (PeiServices, PeiBotDevice); + Status = PeiUsbInquiry (PeiServices, PeiBotDevice); if (EFI_ERROR (Status)) { return Status; } @@ -271,7 +271,7 @@ InitUsbBot ( return Status; } - PeiBotDevice->SensePtr = (ATAPI_REQUEST_SENSE_DATA *) ((UINTN) AllocateAddress); + PeiBotDevice->SensePtr = (ATAPI_REQUEST_SENSE_DATA *)((UINTN)AllocateAddress); Status = PeiServicesInstallPpi (&PeiBotDevice->BlkIoPpiList); @@ -304,9 +304,9 @@ InitUsbBot ( EFI_STATUS EFIAPI BotGetNumberOfBlockDevices ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + OUT UINTN *NumberBlockDevices ) { // @@ -346,10 +346,10 @@ BotGetNumberOfBlockDevices ( EFI_STATUS EFIAPI BotGetMediaInfo ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ) { PEI_BOT_DEVICE *PeiBotDev; @@ -366,9 +366,9 @@ BotGetMediaInfo ( ); Status = PeiBotDetectMedia ( - PeiServices, - PeiBotDev - ); + PeiServices, + PeiBotDev + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; @@ -420,12 +420,12 @@ BotGetMediaInfo ( EFI_STATUS EFIAPI BotReadBlocks ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { PEI_BOT_DEVICE *PeiBotDev; @@ -464,19 +464,18 @@ BotReadBlocks ( NumberOfBlocks = BufferSize / (PeiBotDev->Media.BlockSize); if (Status == EFI_SUCCESS) { - Status = PeiUsbTestUnitReady ( - PeiServices, - PeiBotDev - ); + PeiServices, + PeiBotDev + ); if (Status == EFI_SUCCESS) { Status = PeiUsbRead10 ( - PeiServices, - PeiBotDev, - Buffer, - StartLBA, - 1 - ); + PeiServices, + PeiBotDev, + Buffer, + StartLBA, + 1 + ); } } else { // @@ -494,9 +493,9 @@ BotReadBlocks ( // update the media info accordingly. // Status = PeiBotDetectMedia ( - PeiServices, - PeiBotDev - ); + PeiServices, + PeiBotDev + ); if (Status != EFI_SUCCESS) { return EFI_DEVICE_ERROR; } @@ -520,45 +519,42 @@ BotReadBlocks ( } Status = PeiUsbRead10 ( - PeiServices, - PeiBotDev, - Buffer, - StartLBA, - NumberOfBlocks - ); + PeiServices, + PeiBotDev, + Buffer, + StartLBA, + NumberOfBlocks + ); switch (Status) { + case EFI_SUCCESS: + return EFI_SUCCESS; - case EFI_SUCCESS: - return EFI_SUCCESS; - - default: - return EFI_DEVICE_ERROR; + default: + return EFI_DEVICE_ERROR; } } else { - StartLBA += 1; + StartLBA += 1; NumberOfBlocks -= 1; - Buffer = (UINT8 *) Buffer + PeiBotDev->Media.BlockSize; + Buffer = (UINT8 *)Buffer + PeiBotDev->Media.BlockSize; if (NumberOfBlocks == 0) { return EFI_SUCCESS; } Status = PeiUsbRead10 ( - PeiServices, - PeiBotDev, - Buffer, - StartLBA, - NumberOfBlocks - ); + PeiServices, + PeiBotDev, + Buffer, + StartLBA, + NumberOfBlocks + ); switch (Status) { + case EFI_SUCCESS: + return EFI_SUCCESS; - case EFI_SUCCESS: - return EFI_SUCCESS; - - default: - return EFI_DEVICE_ERROR; - + default: + return EFI_DEVICE_ERROR; } } } @@ -585,9 +581,9 @@ BotReadBlocks ( EFI_STATUS EFIAPI BotGetNumberOfBlockDevices2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ) { // @@ -627,10 +623,10 @@ BotGetNumberOfBlockDevices2 ( EFI_STATUS EFIAPI BotGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ) { PEI_BOT_DEVICE *PeiBotDev; @@ -695,12 +691,12 @@ BotGetMediaInfo2 ( EFI_STATUS EFIAPI BotReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ) { PEI_BOT_DEVICE *PeiBotDev; @@ -738,25 +734,25 @@ BotReadBlocks2 ( **/ EFI_STATUS PeiBotDetectMedia ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev ) { - EFI_STATUS Status; - EFI_STATUS FloppyStatus; - UINTN SenseCounts; - BOOLEAN NeedReadCapacity; - EFI_PHYSICAL_ADDRESS AllocateAddress; - ATAPI_REQUEST_SENSE_DATA *SensePtr; - UINTN Retry; + EFI_STATUS Status; + EFI_STATUS FloppyStatus; + UINTN SenseCounts; + BOOLEAN NeedReadCapacity; + EFI_PHYSICAL_ADDRESS AllocateAddress; + ATAPI_REQUEST_SENSE_DATA *SensePtr; + UINTN Retry; // // if there is no media present,or media not changed, // the request sense command will detect faster than read capacity command. // read capacity command can be bypassed, thus improve performance. // - SenseCounts = 0; - NeedReadCapacity = TRUE; + SenseCounts = 0; + NeedReadCapacity = TRUE; Status = PeiServicesAllocatePages ( EfiBootServicesCode, @@ -771,20 +767,20 @@ PeiBotDetectMedia ( ZeroMem (SensePtr, EFI_PAGE_SIZE); Status = PeiUsbRequestSense ( - PeiServices, - PeiBotDev, - &SenseCounts, - (UINT8 *) SensePtr - ); + PeiServices, + PeiBotDev, + &SenseCounts, + (UINT8 *)SensePtr + ); if (Status == EFI_SUCCESS) { // // No Media // if (IsNoMedia (SensePtr, SenseCounts)) { - NeedReadCapacity = FALSE; - PeiBotDev->Media.MediaPresent = FALSE; - PeiBotDev->Media.LastBlock = 0; + NeedReadCapacity = FALSE; + PeiBotDev->Media.MediaPresent = FALSE; + PeiBotDev->Media.LastBlock = 0; PeiBotDev->Media2.MediaPresent = FALSE; PeiBotDev->Media2.LastBlock = 0; } else { @@ -795,6 +791,7 @@ PeiBotDetectMedia ( PeiBotDev->Media.MediaPresent = TRUE; PeiBotDev->Media2.MediaPresent = TRUE; } + // // Media Error // @@ -802,14 +799,12 @@ PeiBotDetectMedia ( // // if media error encountered, make it look like no media present. // - PeiBotDev->Media.MediaPresent = FALSE; - PeiBotDev->Media.LastBlock = 0; + PeiBotDev->Media.MediaPresent = FALSE; + PeiBotDev->Media.LastBlock = 0; PeiBotDev->Media2.MediaPresent = FALSE; PeiBotDev->Media2.LastBlock = 0; } - } - } if (NeedReadCapacity) { @@ -818,43 +813,46 @@ PeiBotDetectMedia ( // for (Retry = 0; Retry < 4; Retry++) { switch (PeiBotDev->DeviceType) { - case USBCDROM: - Status = PeiUsbReadCapacity ( - PeiServices, - PeiBotDev - ); - break; - - case USBFLOPPY2: - Status = PeiUsbReadFormattedCapacity ( - PeiServices, - PeiBotDev - ); - if (EFI_ERROR(Status)|| - !PeiBotDev->Media.MediaPresent) { - // - // retry the ReadCapacity command - // - PeiBotDev->DeviceType = USBFLOPPY; - Status = EFI_DEVICE_ERROR; - } - break; - - case USBFLOPPY: - Status = PeiUsbReadCapacity ( - PeiServices, - PeiBotDev - ); - if (EFI_ERROR (Status)) { - // - // retry the ReadFormatCapacity command - // - PeiBotDev->DeviceType = USBFLOPPY2; - } - break; - - default: - return EFI_INVALID_PARAMETER; + case USBCDROM: + Status = PeiUsbReadCapacity ( + PeiServices, + PeiBotDev + ); + break; + + case USBFLOPPY2: + Status = PeiUsbReadFormattedCapacity ( + PeiServices, + PeiBotDev + ); + if (EFI_ERROR (Status) || + !PeiBotDev->Media.MediaPresent) + { + // + // retry the ReadCapacity command + // + PeiBotDev->DeviceType = USBFLOPPY; + Status = EFI_DEVICE_ERROR; + } + + break; + + case USBFLOPPY: + Status = PeiUsbReadCapacity ( + PeiServices, + PeiBotDev + ); + if (EFI_ERROR (Status)) { + // + // retry the ReadFormatCapacity command + // + PeiBotDev->DeviceType = USBFLOPPY2; + } + + break; + + default: + return EFI_INVALID_PARAMETER; } SenseCounts = 0; @@ -865,11 +863,11 @@ PeiBotDetectMedia ( } FloppyStatus = PeiUsbRequestSense ( - PeiServices, - PeiBotDev, - &SenseCounts, - (UINT8 *) SensePtr - ); + PeiServices, + PeiBotDev, + &SenseCounts, + (UINT8 *)SensePtr + ); // // If Request Sense data failed,retry. @@ -877,12 +875,13 @@ PeiBotDetectMedia ( if (EFI_ERROR (FloppyStatus)) { continue; } + // // No Media // if (IsNoMedia (SensePtr, SenseCounts)) { - PeiBotDev->Media.MediaPresent = FALSE; - PeiBotDev->Media.LastBlock = 0; + PeiBotDev->Media.MediaPresent = FALSE; + PeiBotDev->Media.LastBlock = 0; PeiBotDev->Media2.MediaPresent = FALSE; PeiBotDev->Media2.LastBlock = 0; break; @@ -892,13 +891,14 @@ PeiBotDetectMedia ( // // if media error encountered, make it look like no media present. // - PeiBotDev->Media.MediaPresent = FALSE; - PeiBotDev->Media.LastBlock = 0; + PeiBotDev->Media.MediaPresent = FALSE; + PeiBotDev->Media.LastBlock = 0; PeiBotDev->Media2.MediaPresent = FALSE; PeiBotDev->Media2.LastBlock = 0; break; } } + // // ENDFOR // diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.h b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.h index 81ca4a2d07..1819784981 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.h +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbBotPeim.h @@ -46,9 +46,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI BotGetNumberOfBlockDevices ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -81,10 +81,10 @@ BotGetNumberOfBlockDevices ( EFI_STATUS EFIAPI BotGetMediaInfo ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO_MEDIA *MediaInfo ); /** @@ -124,12 +124,12 @@ BotGetMediaInfo ( EFI_STATUS EFIAPI BotReadBlocks ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -154,9 +154,9 @@ BotReadBlocks ( EFI_STATUS EFIAPI BotGetNumberOfBlockDevices2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - OUT UINTN *NumberBlockDevices + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + OUT UINTN *NumberBlockDevices ); /** @@ -189,10 +189,10 @@ BotGetNumberOfBlockDevices2 ( EFI_STATUS EFIAPI BotGetMediaInfo2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + OUT EFI_PEI_BLOCK_IO2_MEDIA *MediaInfo ); /** @@ -232,12 +232,12 @@ BotGetMediaInfo2 ( EFI_STATUS EFIAPI BotReadBlocks2 ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, - IN UINTN DeviceIndex, - IN EFI_PEI_LBA StartLBA, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_RECOVERY_BLOCK_IO2_PPI *This, + IN UINTN DeviceIndex, + IN EFI_PEI_LBA StartLBA, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -256,9 +256,9 @@ BotReadBlocks2 ( EFI_STATUS EFIAPI NotifyOnUsbIoPpi ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, - IN VOID *InvokePpi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDesc, + IN VOID *InvokePpi ); /** @@ -274,11 +274,11 @@ NotifyOnUsbIoPpi ( **/ EFI_STATUS InitUsbBot ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi ); -#define USBCDROM 1 // let the device type value equal to USBCDROM, which is defined by PI spec. +#define USBCDROM 1 // let the device type value equal to USBCDROM, which is defined by PI spec. // Therefore the CdExpressPei module can do recovery on UsbCdrom. #define USBFLOPPY 2 // for those that use ReadCapacity(0x25) command to retrieve media capacity #define USBFLOPPY2 3 // for those that use ReadFormatCapacity(0x23) command to retrieve media capacity @@ -288,24 +288,24 @@ InitUsbBot ( // #define PEI_BOT_DEVICE_SIGNATURE SIGNATURE_32 ('U', 'B', 'O', 'T') typedef struct { - UINTN Signature; - EFI_PEI_RECOVERY_BLOCK_IO_PPI BlkIoPpi; - EFI_PEI_RECOVERY_BLOCK_IO2_PPI BlkIo2Ppi; - EFI_PEI_PPI_DESCRIPTOR BlkIoPpiList; - EFI_PEI_PPI_DESCRIPTOR BlkIo2PpiList; - EFI_PEI_BLOCK_IO_MEDIA Media; - EFI_PEI_BLOCK_IO2_MEDIA Media2; - PEI_USB_IO_PPI *UsbIoPpi; - EFI_USB_INTERFACE_DESCRIPTOR *BotInterface; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; - UINTN AllocateAddress; - UINTN DeviceType; - ATAPI_REQUEST_SENSE_DATA *SensePtr; + UINTN Signature; + EFI_PEI_RECOVERY_BLOCK_IO_PPI BlkIoPpi; + EFI_PEI_RECOVERY_BLOCK_IO2_PPI BlkIo2Ppi; + EFI_PEI_PPI_DESCRIPTOR BlkIoPpiList; + EFI_PEI_PPI_DESCRIPTOR BlkIo2PpiList; + EFI_PEI_BLOCK_IO_MEDIA Media; + EFI_PEI_BLOCK_IO2_MEDIA Media2; + PEI_USB_IO_PPI *UsbIoPpi; + EFI_USB_INTERFACE_DESCRIPTOR *BotInterface; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; + UINTN AllocateAddress; + UINTN DeviceType; + ATAPI_REQUEST_SENSE_DATA *SensePtr; } PEI_BOT_DEVICE; -#define PEI_BOT_DEVICE_FROM_THIS(a) CR (a, PEI_BOT_DEVICE, BlkIoPpi, PEI_BOT_DEVICE_SIGNATURE) -#define PEI_BOT_DEVICE2_FROM_THIS(a) CR (a, PEI_BOT_DEVICE, BlkIo2Ppi, PEI_BOT_DEVICE_SIGNATURE) +#define PEI_BOT_DEVICE_FROM_THIS(a) CR (a, PEI_BOT_DEVICE, BlkIoPpi, PEI_BOT_DEVICE_SIGNATURE) +#define PEI_BOT_DEVICE2_FROM_THIS(a) CR (a, PEI_BOT_DEVICE, BlkIo2Ppi, PEI_BOT_DEVICE_SIGNATURE) /** Send ATAPI command using BOT protocol. @@ -326,14 +326,14 @@ typedef struct { **/ EFI_STATUS PeiAtapiCommand ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_BOT_DEVICE *PeiBotDev, - IN VOID *Command, - IN UINT8 CommandSize, - IN VOID *DataBuffer, - IN UINT32 BufferLength, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT16 TimeOutInMilliSeconds + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_BOT_DEVICE *PeiBotDev, + IN VOID *Command, + IN UINT8 CommandSize, + IN VOID *DataBuffer, + IN UINT32 BufferLength, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT16 TimeOutInMilliSeconds ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbPeim.h b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbPeim.h index cb93d72291..225b6cb370 100644 --- a/MdeModulePkg/Bus/Usb/UsbBotPei/UsbPeim.h +++ b/MdeModulePkg/Bus/Usb/UsbBotPei/UsbPeim.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_USB_PEIM_H_ #define _PEI_USB_PEIM_H_ - #include #include diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/ComponentName.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/ComponentName.c index 642f936412..c644b42a81 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/ComponentName.c @@ -7,13 +7,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include - #include - /** Retrieves a Unicode string that is the user readable name of the driver. @@ -61,7 +58,6 @@ UsbBusComponentNameGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -133,14 +129,13 @@ UsbBusComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); - // // EFI Component Name Protocol // @@ -153,16 +148,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL mUsbBusComponentName // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL mUsbBusComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UsbBusComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UsbBusComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL mUsbBusComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UsbBusComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UsbBusComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbBusDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbBusDriverNameTable[] = { { "eng;en", L"Usb Bus Driver" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -292,11 +286,11 @@ UsbBusComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbBusComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c index 7e48a2882c..6a3ac63c3a 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.c @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbBus.h" -EFI_USB_IO_PROTOCOL mUsbIoProtocol = { +EFI_USB_IO_PROTOCOL mUsbIoProtocol = { UsbIoControlTransfer, UsbIoBulkTransfer, UsbIoAsyncInterruptTransfer, @@ -25,7 +25,7 @@ EFI_USB_IO_PROTOCOL mUsbIoProtocol = { UsbIoPortReset }; -EFI_DRIVER_BINDING_PROTOCOL mUsbBusDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL mUsbBusDriverBinding = { UsbBusControllerDriverSupported, UsbBusControllerDriverStart, UsbBusControllerDriverStop, @@ -65,12 +65,12 @@ UsbIoControlTransfer ( OUT UINT32 *UsbStatus ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - USB_ENDPOINT_DESC *EpDesc; - EFI_TPL OldTpl; - EFI_STATUS Status; - UINTN RequestedDataLength; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + USB_ENDPOINT_DESC *EpDesc; + EFI_TPL OldTpl; + EFI_STATUS Status; + UINTN RequestedDataLength; if (UsbStatus == NULL) { return EFI_INVALID_PARAMETER; @@ -78,23 +78,23 @@ UsbIoControlTransfer ( OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; RequestedDataLength = DataLength; - Status = UsbHcControlTransfer ( - Dev->Bus, - Dev->Address, - Dev->Speed, - Dev->MaxPacket0, - Request, - Direction, - Data, - &DataLength, - (UINTN) Timeout, - &Dev->Translator, - UsbStatus - ); + Status = UsbHcControlTransfer ( + Dev->Bus, + Dev->Address, + Dev->Speed, + Dev->MaxPacket0, + Request, + Direction, + Data, + &DataLength, + (UINTN)Timeout, + &Dev->Translator, + UsbStatus + ); // // If the request completed successfully and the Direction of the request is // EfiUsbDataIn or EfiUsbDataOut, then make sure the actual number of bytes @@ -102,7 +102,7 @@ UsbIoControlTransfer ( // number of bytes were transferred, then return EFI_DEVICE_ERROR. // if (!EFI_ERROR (Status)) { - if (Direction != EfiUsbNoData && DataLength != RequestedDataLength) { + if ((Direction != EfiUsbNoData) && (DataLength != RequestedDataLength)) { Status = EFI_DEVICE_ERROR; goto ON_EXIT; } @@ -139,11 +139,14 @@ UsbIoControlTransfer ( // Reset the endpoint toggle when endpoint stall is cleared // if ((Request->Request == USB_REQ_CLEAR_FEATURE) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, - USB_TARGET_ENDPOINT)) && - (Request->Value == USB_FEATURE_ENDPOINT_HALT)) { - - EpDesc = UsbGetEndpointDesc (UsbIf, (UINT8) Request->Index); + (Request->RequestType == USB_REQUEST_TYPE ( + EfiUsbNoData, + USB_REQ_TYPE_STANDARD, + USB_TARGET_ENDPOINT + )) && + (Request->Value == USB_FEATURE_ENDPOINT_HALT)) + { + EpDesc = UsbGetEndpointDesc (UsbIf, (UINT8)Request->Index); if (EpDesc != NULL) { EpDesc->Toggle = 0; @@ -158,16 +161,21 @@ UsbIoControlTransfer ( // completely irrelevant. // if ((Request->Request == USB_REQ_SET_CONFIG) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, - USB_TARGET_DEVICE))) { + (Request->RequestType == USB_REQUEST_TYPE ( + EfiUsbNoData, + USB_REQ_TYPE_STANDARD, + USB_TARGET_DEVICE + ))) + { // // Don't re-create the USB interfaces if configuration isn't changed. // if ((Dev->ActiveConfig != NULL) && - (Request->Value == Dev->ActiveConfig->Desc.ConfigurationValue)) { - + (Request->Value == Dev->ActiveConfig->Desc.ConfigurationValue)) + { goto ON_EXIT; } + DEBUG ((DEBUG_INFO, "UsbIoControlTransfer: configure changed!!! Do NOT use old UsbIo!!!\n")); if (Dev->ActiveConfig != NULL) { @@ -175,7 +183,7 @@ UsbIoControlTransfer ( } if (Request->Value != 0) { - Status = UsbSelectConfig (Dev, (UINT8) Request->Value); + Status = UsbSelectConfig (Dev, (UINT8)Request->Value); } // @@ -191,11 +199,14 @@ UsbIoControlTransfer ( // should remains the same. // if ((Request->Request == USB_REQ_SET_INTERFACE) && - (Request->RequestType == USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, - USB_TARGET_INTERFACE)) && - (Request->Index == UsbIf->IfSetting->Desc.InterfaceNumber)) { - - Status = UsbSelectSetting (UsbIf->IfDesc, (UINT8) Request->Value); + (Request->RequestType == USB_REQUEST_TYPE ( + EfiUsbNoData, + USB_REQ_TYPE_STANDARD, + USB_TARGET_INTERFACE + )) && + (Request->Index == UsbIf->IfSetting->Desc.InterfaceNumber)) + { + Status = UsbSelectSetting (UsbIf->IfDesc, (UINT8)Request->Value); if (!EFI_ERROR (Status)) { ASSERT (UsbIf->IfDesc->ActiveIndex < USB_MAX_INTERFACE_SETTING); @@ -208,7 +219,6 @@ ON_EXIT: return Status; } - /** Execute a bulk transfer to the device endpoint. @@ -228,56 +238,56 @@ ON_EXIT: EFI_STATUS EFIAPI UsbIoBulkTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Endpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout, - OUT UINT32 *UsbStatus + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Endpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout, + OUT UINT32 *UsbStatus ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - USB_ENDPOINT_DESC *EpDesc; - UINT8 BufNum; - UINT8 Toggle; - EFI_TPL OldTpl; - EFI_STATUS Status; - - if ((USB_ENDPOINT_ADDR (Endpoint) == 0) || (USB_ENDPOINT_ADDR(Endpoint) > 15) || - (UsbStatus == NULL)) { - + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + USB_ENDPOINT_DESC *EpDesc; + UINT8 BufNum; + UINT8 Toggle; + EFI_TPL OldTpl; + EFI_STATUS Status; + + if ((USB_ENDPOINT_ADDR (Endpoint) == 0) || (USB_ENDPOINT_ADDR (Endpoint) > 15) || + (UsbStatus == NULL)) + { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (USB_BUS_TPL); + OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; - EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); + EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); if ((EpDesc == NULL) || (USB_ENDPOINT_TYPE (&EpDesc->Desc) != USB_ENDPOINT_BULK)) { Status = EFI_INVALID_PARAMETER; goto ON_EXIT; } - BufNum = 1; - Toggle = EpDesc->Toggle; - Status = UsbHcBulkTransfer ( - Dev->Bus, - Dev->Address, - Endpoint, - Dev->Speed, - EpDesc->Desc.MaxPacketSize, - BufNum, - &Data, - DataLength, - &Toggle, - Timeout, - &Dev->Translator, - UsbStatus - ); + BufNum = 1; + Toggle = EpDesc->Toggle; + Status = UsbHcBulkTransfer ( + Dev->Bus, + Dev->Address, + Endpoint, + Dev->Speed, + EpDesc->Desc.MaxPacketSize, + BufNum, + &Data, + DataLength, + &Toggle, + Timeout, + &Dev->Translator, + UsbStatus + ); EpDesc->Toggle = Toggle; @@ -303,7 +313,6 @@ ON_EXIT: return Status; } - /** Execute a synchronous interrupt transfer. @@ -323,33 +332,33 @@ ON_EXIT: EFI_STATUS EFIAPI UsbIoSyncInterruptTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Endpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout, - OUT UINT32 *UsbStatus + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Endpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout, + OUT UINT32 *UsbStatus ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - USB_ENDPOINT_DESC *EpDesc; - EFI_TPL OldTpl; - UINT8 Toggle; - EFI_STATUS Status; - - if ((USB_ENDPOINT_ADDR (Endpoint) == 0) || (USB_ENDPOINT_ADDR(Endpoint) > 15) || - (UsbStatus == NULL)) { - + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + USB_ENDPOINT_DESC *EpDesc; + EFI_TPL OldTpl; + UINT8 Toggle; + EFI_STATUS Status; + + if ((USB_ENDPOINT_ADDR (Endpoint) == 0) || (USB_ENDPOINT_ADDR (Endpoint) > 15) || + (UsbStatus == NULL)) + { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (USB_BUS_TPL); + OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; - EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); + EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); if ((EpDesc == NULL) || (USB_ENDPOINT_TYPE (&EpDesc->Desc) != USB_ENDPOINT_INTERRUPT)) { Status = EFI_INVALID_PARAMETER; @@ -378,7 +387,6 @@ ON_EXIT: return Status; } - /** Queue a new asynchronous interrupt transfer, or remove the old request if (IsNewTransfer == FALSE). @@ -411,43 +419,43 @@ UsbIoAsyncInterruptTransfer ( IN VOID *Context OPTIONAL ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - USB_ENDPOINT_DESC *EpDesc; - EFI_TPL OldTpl; - UINT8 Toggle; - EFI_STATUS Status; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + USB_ENDPOINT_DESC *EpDesc; + EFI_TPL OldTpl; + UINT8 Toggle; + EFI_STATUS Status; if ((USB_ENDPOINT_ADDR (Endpoint) == 0) || (USB_ENDPOINT_ADDR (Endpoint) > 15)) { return EFI_INVALID_PARAMETER; } - OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + OldTpl = gBS->RaiseTPL (USB_BUS_TPL); + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; - EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); + EpDesc = UsbGetEndpointDesc (UsbIf, Endpoint); if ((EpDesc == NULL) || (USB_ENDPOINT_TYPE (&EpDesc->Desc) != USB_ENDPOINT_INTERRUPT)) { Status = EFI_INVALID_PARAMETER; goto ON_EXIT; } - Toggle = EpDesc->Toggle; - Status = UsbHcAsyncInterruptTransfer ( - Dev->Bus, - Dev->Address, - Endpoint, - Dev->Speed, - EpDesc->Desc.MaxPacketSize, - IsNewTransfer, - &Toggle, - PollInterval, - DataLength, - &Dev->Translator, - Callback, - Context - ); + Toggle = EpDesc->Toggle; + Status = UsbHcAsyncInterruptTransfer ( + Dev->Bus, + Dev->Address, + Endpoint, + Dev->Speed, + EpDesc->Desc.MaxPacketSize, + IsNewTransfer, + &Toggle, + PollInterval, + DataLength, + &Dev->Translator, + Callback, + Context + ); EpDesc->Toggle = Toggle; @@ -456,7 +464,6 @@ ON_EXIT: return Status; } - /** Execute a synchronous isochronous transfer. @@ -472,17 +479,16 @@ ON_EXIT: EFI_STATUS EFIAPI UsbIoIsochronousTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 DeviceEndpoint, - IN OUT VOID *Data, - IN UINTN DataLength, - OUT UINT32 *Status + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 DeviceEndpoint, + IN OUT VOID *Data, + IN UINTN DataLength, + OUT UINT32 *Status ) { return EFI_UNSUPPORTED; } - /** Queue an asynchronous isochronous transfer. @@ -511,7 +517,6 @@ UsbIoAsyncIsochronousTransfer ( return EFI_UNSUPPORTED; } - /** Retrieve the device descriptor of the device. @@ -525,13 +530,13 @@ UsbIoAsyncIsochronousTransfer ( EFI_STATUS EFIAPI UsbIoGetDeviceDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - OUT EFI_USB_DEVICE_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + OUT EFI_USB_DEVICE_DESCRIPTOR *Descriptor ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - EFI_TPL OldTpl; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + EFI_TPL OldTpl; if (Descriptor == NULL) { return EFI_INVALID_PARAMETER; @@ -539,8 +544,8 @@ UsbIoGetDeviceDescriptor ( OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; CopyMem (Descriptor, &Dev->DevDesc->Desc, sizeof (EFI_USB_DEVICE_DESCRIPTOR)); @@ -548,7 +553,6 @@ UsbIoGetDeviceDescriptor ( return EFI_SUCCESS; } - /** Return the configuration descriptor of the current active configuration. @@ -563,14 +567,14 @@ UsbIoGetDeviceDescriptor ( EFI_STATUS EFIAPI UsbIoGetActiveConfigDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - OUT EFI_USB_CONFIG_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + OUT EFI_USB_CONFIG_DESCRIPTOR *Descriptor ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - EFI_STATUS Status; - EFI_TPL OldTpl; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + EFI_STATUS Status; + EFI_TPL OldTpl; if (Descriptor == NULL) { return EFI_INVALID_PARAMETER; @@ -579,8 +583,8 @@ UsbIoGetActiveConfigDescriptor ( Status = EFI_SUCCESS; OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; if (Dev->ActiveConfig == NULL) { Status = EFI_NOT_FOUND; @@ -594,7 +598,6 @@ ON_EXIT: return Status; } - /** Retrieve the active interface setting descriptor for this USB IO instance. @@ -612,8 +615,8 @@ UsbIoGetInterfaceDescriptor ( OUT EFI_USB_INTERFACE_DESCRIPTOR *Descriptor ) { - USB_INTERFACE *UsbIf; - EFI_TPL OldTpl; + USB_INTERFACE *UsbIf; + EFI_TPL OldTpl; if (Descriptor == NULL) { return EFI_INVALID_PARAMETER; @@ -621,14 +624,13 @@ UsbIoGetInterfaceDescriptor ( OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); + UsbIf = USB_INTERFACE_FROM_USBIO (This); CopyMem (Descriptor, &(UsbIf->IfSetting->Desc), sizeof (EFI_USB_INTERFACE_DESCRIPTOR)); gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; } - /** Retrieve the endpoint descriptor from this interface setting. @@ -644,17 +646,17 @@ UsbIoGetInterfaceDescriptor ( EFI_STATUS EFIAPI UsbIoGetEndpointDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Index, - OUT EFI_USB_ENDPOINT_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Index, + OUT EFI_USB_ENDPOINT_DESCRIPTOR *Descriptor ) { - USB_INTERFACE *UsbIf; - EFI_TPL OldTpl; + USB_INTERFACE *UsbIf; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); + UsbIf = USB_INTERFACE_FROM_USBIO (This); if ((Descriptor == NULL) || (Index > 15)) { gBS->RestoreTPL (OldTpl); @@ -676,7 +678,6 @@ UsbIoGetEndpointDescriptor ( return EFI_SUCCESS; } - /** Retrieve the supported language ID table from the device. @@ -690,28 +691,27 @@ UsbIoGetEndpointDescriptor ( EFI_STATUS EFIAPI UsbIoGetSupportedLanguages ( - IN EFI_USB_IO_PROTOCOL *This, - OUT UINT16 **LangIDTable, - OUT UINT16 *TableSize + IN EFI_USB_IO_PROTOCOL *This, + OUT UINT16 **LangIDTable, + OUT UINT16 *TableSize ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - EFI_TPL OldTpl; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + EFI_TPL OldTpl; - OldTpl = gBS->RaiseTPL (USB_BUS_TPL); + OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; - *LangIDTable = Dev->LangId; - *TableSize = (UINT16) (Dev->TotalLangId * sizeof (UINT16)); + *LangIDTable = Dev->LangId; + *TableSize = (UINT16)(Dev->TotalLangId * sizeof (UINT16)); gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; } - /** Retrieve an indexed string in the language of LangID. @@ -727,19 +727,19 @@ UsbIoGetSupportedLanguages ( EFI_STATUS EFIAPI UsbIoGetStringDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT16 LangID, - IN UINT8 StringIndex, - OUT CHAR16 **String + IN EFI_USB_IO_PROTOCOL *This, + IN UINT16 LangID, + IN UINT8 StringIndex, + OUT CHAR16 **String ) { - USB_DEVICE *Dev; - USB_INTERFACE *UsbIf; - EFI_USB_STRING_DESCRIPTOR *StrDesc; - EFI_TPL OldTpl; - UINT8 *Buf; - UINT8 Index; - EFI_STATUS Status; + USB_DEVICE *Dev; + USB_INTERFACE *UsbIf; + EFI_USB_STRING_DESCRIPTOR *StrDesc; + EFI_TPL OldTpl; + UINT8 *Buf; + UINT8 Index; + EFI_STATUS Status; if ((StringIndex == 0) || (LangID == 0)) { return EFI_NOT_FOUND; @@ -747,8 +747,8 @@ UsbIoGetStringDescriptor ( OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; // // Check whether language ID is supported @@ -788,7 +788,7 @@ UsbIoGetStringDescriptor ( } CopyMem (Buf, StrDesc->String, StrDesc->Length - 2); - *String = (CHAR16 *) Buf; + *String = (CHAR16 *)Buf; Status = EFI_SUCCESS; FREE_STR: @@ -799,7 +799,6 @@ ON_EXIT: return Status; } - /** Reset the device, then if that succeeds, reconfigure the device with its address and current active configuration. @@ -816,17 +815,17 @@ UsbIoPortReset ( IN EFI_USB_IO_PROTOCOL *This ) { - USB_INTERFACE *UsbIf; - USB_INTERFACE *HubIf; - USB_DEVICE *Dev; - EFI_TPL OldTpl; - EFI_STATUS Status; - UINT8 DevAddress; + USB_INTERFACE *UsbIf; + USB_INTERFACE *HubIf; + USB_DEVICE *Dev; + EFI_TPL OldTpl; + EFI_STATUS Status; + UINT8 DevAddress; OldTpl = gBS->RaiseTPL (USB_BUS_TPL); - UsbIf = USB_INTERFACE_FROM_USBIO (This); - Dev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (This); + Dev = UsbIf->Device; if (UsbIf->IsHub) { Status = EFI_INVALID_PARAMETER; @@ -837,8 +836,13 @@ UsbIoPortReset ( Status = HubIf->HubApi->ResetPort (HubIf, Dev->ParentPort); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbIoPortReset: failed to reset hub port %d@hub %d, %r \n", - Dev->ParentPort, Dev->ParentAddr, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbIoPortReset: failed to reset hub port %d@hub %d, %r \n", + Dev->ParentPort, + Dev->ParentAddr, + Status + )); goto ON_EXIT; } @@ -852,7 +856,7 @@ UsbIoPortReset ( // DevAddress = Dev->Address; Dev->Address = 0; - Status = UsbSetAddress (Dev, DevAddress); + Status = UsbSetAddress (Dev, DevAddress); Dev->Address = DevAddress; gBS->Stall (USB_SET_DEVICE_ADDRESS_STALL); @@ -861,13 +865,17 @@ UsbIoPortReset ( // // It may fail due to device disconnection or other reasons. // - DEBUG (( DEBUG_ERROR, "UsbIoPortReset: failed to set address for device %d - %r\n", - Dev->Address, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbIoPortReset: failed to set address for device %d - %r\n", + Dev->Address, + Status + )); goto ON_EXIT; } - DEBUG (( DEBUG_INFO, "UsbIoPortReset: device is now ADDRESSED at %d\n", Dev->Address)); + DEBUG ((DEBUG_INFO, "UsbIoPortReset: device is now ADDRESSED at %d\n", Dev->Address)); // // Reset the current active configure, after this device @@ -877,8 +885,12 @@ UsbIoPortReset ( Status = UsbSetConfig (Dev, Dev->ActiveConfig->Desc.ConfigurationValue); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbIoPortReset: failed to set configure for device %d - %r\n", - Dev->Address, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbIoPortReset: failed to set configure for device %d - %r\n", + Dev->Address, + Status + )); } } @@ -887,7 +899,6 @@ ON_EXIT: return Status; } - /** Install Usb Bus Protocol on host controller, and start the Usb bus. @@ -908,11 +919,11 @@ UsbBusBuildProtocol ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - USB_BUS *UsbBus; - USB_DEVICE *RootHub; - USB_INTERFACE *RootIf; - EFI_STATUS Status; - EFI_STATUS Status2; + USB_BUS *UsbBus; + USB_DEVICE *RootHub; + USB_INTERFACE *RootIf; + EFI_STATUS Status; + EFI_STATUS Status2; UsbBus = AllocateZeroPool (sizeof (USB_BUS)); @@ -927,7 +938,7 @@ UsbBusBuildProtocol ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &UsbBus->DevicePath, + (VOID **)&UsbBus->DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -951,7 +962,7 @@ UsbBusBuildProtocol ( Status = gBS->OpenProtocol ( Controller, &gEfiUsb2HcProtocolGuid, - (VOID **) &(UsbBus->Usb2Hc), + (VOID **)&(UsbBus->Usb2Hc), This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -960,7 +971,7 @@ UsbBusBuildProtocol ( Status2 = gBS->OpenProtocol ( Controller, &gEfiUsbHcProtocolGuid, - (VOID **) &(UsbBus->UsbHc), + (VOID **)&(UsbBus->UsbHc), This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1040,7 +1051,7 @@ UsbBusBuildProtocol ( UsbBus->DevicePath ); - Status = mUsbRootHubApi.Init (RootIf); + Status = mUsbRootHubApi.Init (RootIf); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "UsbBusStart: Failed to init root hub %r\n", Status)); @@ -1056,6 +1067,7 @@ FREE_ROOTHUB: if (RootIf != NULL) { FreePool (RootIf); } + if (RootHub != NULL) { FreePool (RootHub); } @@ -1066,20 +1078,22 @@ UNINSTALL_USBBUS: CLOSE_HC: if (UsbBus->Usb2Hc != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiUsb2HcProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsb2HcProtocolGuid, + This->DriverBindingHandle, + Controller + ); } + if (UsbBus->UsbHc != NULL) { gBS->CloseProtocol ( - Controller, - &gEfiUsbHcProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbHcProtocolGuid, + This->DriverBindingHandle, + Controller + ); } + gBS->CloseProtocol ( Controller, &gEfiDevicePathProtocolGuid, @@ -1092,7 +1106,6 @@ CLOSE_HC: return Status; } - /** The USB bus driver entry pointer. @@ -1106,8 +1119,8 @@ CLOSE_HC: EFI_STATUS EFIAPI UsbBusDriverEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return EfiLibInstallDriverBindingComponentName2 ( @@ -1120,7 +1133,6 @@ UsbBusDriverEntryPoint ( ); } - /** Check whether USB bus driver support this device. @@ -1162,11 +1174,11 @@ UsbBusControllerDriverSupported ( DevicePathNode.DevPath = RemainingDevicePath; if ((DevicePathNode.DevPath->Type != MESSAGING_DEVICE_PATH) || - (DevicePathNode.DevPath->SubType != MSG_USB_DP && - DevicePathNode.DevPath->SubType != MSG_USB_CLASS_DP - && DevicePathNode.DevPath->SubType != MSG_USB_WWID_DP - )) { - + ( (DevicePathNode.DevPath->SubType != MSG_USB_DP) && + (DevicePathNode.DevPath->SubType != MSG_USB_CLASS_DP) + && (DevicePathNode.DevPath->SubType != MSG_USB_WWID_DP) + )) + { return EFI_UNSUPPORTED; } } @@ -1178,7 +1190,7 @@ UsbBusControllerDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1194,7 +1206,7 @@ UsbBusControllerDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbHcProtocolGuid, - (VOID **) &UsbHc, + (VOID **)&UsbHc, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1211,14 +1223,12 @@ UsbBusControllerDriverSupported ( // Close the USB_HC used to perform the supported test // gBS->CloseProtocol ( - Controller, - &gEfiUsbHcProtocolGuid, - This->DriverBindingHandle, - Controller - ); - + Controller, + &gEfiUsbHcProtocolGuid, + This->DriverBindingHandle, + Controller + ); } else { - // // Close the USB_HC2 used to perform the supported test // @@ -1236,7 +1246,7 @@ UsbBusControllerDriverSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -1250,11 +1260,11 @@ UsbBusControllerDriverSupported ( // Close protocol, don't use device path protocol in the Support() function // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); return EFI_SUCCESS; } @@ -1262,7 +1272,6 @@ UsbBusControllerDriverSupported ( return Status; } - /** Start to process the controller. @@ -1284,14 +1293,14 @@ UsbBusControllerDriverStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_USB_BUS_PROTOCOL *UsbBusId; - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; + EFI_USB_BUS_PROTOCOL *UsbBusId; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *ParentDevicePath; Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &ParentDevicePath, + (VOID **)&ParentDevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1314,7 +1323,7 @@ UsbBusControllerDriverStart ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &UsbBusId, + (VOID **)&UsbBusId, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1329,13 +1338,14 @@ UsbBusControllerDriverStart ( if (EFI_ERROR (Status)) { return Status; } + // // Try get the Usb Bus protocol interface again // Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &UsbBusId, + (VOID **)&UsbBusId, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1370,11 +1380,9 @@ UsbBusControllerDriverStart ( ASSERT (!EFI_ERROR (Status)); } - return EFI_SUCCESS; } - /** Stop handle the controller by this USB bus driver. @@ -1409,20 +1417,20 @@ UsbBusControllerDriverStop ( EFI_STATUS Status; EFI_STATUS ReturnStatus; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; if (NumberOfChildren > 0) { // // BugBug: Raise TPL to callback level instead of USB_BUS_TPL to avoid TPL conflict // - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); ReturnStatus = EFI_SUCCESS; for (Index = 0; Index < NumberOfChildren; Index++) { Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1438,8 +1446,8 @@ UsbBusControllerDriverStop ( continue; } - UsbIf = USB_INTERFACE_FROM_USBIO (UsbIo); - UsbDev = UsbIf->Device; + UsbIf = USB_INTERFACE_FROM_USBIO (UsbIo); + UsbDev = UsbIf->Device; ReturnStatus = UsbRemoveDevice (UsbDev); } @@ -1448,7 +1456,7 @@ UsbBusControllerDriverStop ( return ReturnStatus; } - DEBUG (( DEBUG_INFO, "UsbBusStop: usb bus stopped on %p\n", Controller)); + DEBUG ((DEBUG_INFO, "UsbBusStop: usb bus stopped on %p\n", Controller)); // // Locate USB_BUS for the current host controller @@ -1456,7 +1464,7 @@ UsbBusControllerDriverStop ( Status = gBS->OpenProtocol ( Controller, &gEfiCallerIdGuid, - (VOID **) &BusId, + (VOID **)&BusId, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1473,7 +1481,7 @@ UsbBusControllerDriverStop ( // // BugBug: Raise TPL to callback level instead of USB_BUS_TPL to avoid TPL conflict // - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); RootHub = Bus->Devices[0]; RootIf = RootHub->Interfaces[0]; @@ -1493,8 +1501,8 @@ UsbBusControllerDriverStop ( if (!EFI_ERROR (ReturnStatus)) { mUsbRootHubApi.Release (RootIf); - gBS->FreePool (RootIf); - gBS->FreePool (RootHub); + gBS->FreePool (RootIf); + gBS->FreePool (RootHub); Status = UsbBusFreeUsbDPList (&Bus->WantedUsbIoDPList); ASSERT (!EFI_ERROR (Status)); @@ -1533,5 +1541,6 @@ UsbBusControllerDriverStop ( gBS->FreePool (Bus); } } + return Status; } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.h b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.h index 40bc5f130e..21a24218fc 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.h +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBus.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USB_BUS_H_ #define _EFI_USB_BUS_H_ - #include #include @@ -28,7 +27,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - #include typedef struct _USB_DEVICE USB_DEVICE; @@ -36,7 +34,6 @@ typedef struct _USB_INTERFACE USB_INTERFACE; typedef struct _USB_BUS USB_BUS; typedef struct _USB_HUB_API USB_HUB_API; - #include "UsbUtility.h" #include "UsbDesc.h" #include "UsbHub.h" @@ -46,19 +43,19 @@ typedef struct _USB_HUB_API USB_HUB_API; // USB bus timeout experience values // -#define USB_MAX_LANG_ID 16 -#define USB_MAX_INTERFACE 16 -#define USB_MAX_DEVICES 128 +#define USB_MAX_LANG_ID 16 +#define USB_MAX_INTERFACE 16 +#define USB_MAX_DEVICES 128 -#define USB_BUS_1_MILLISECOND 1000 +#define USB_BUS_1_MILLISECOND 1000 // // Roothub and hub's polling interval, set by experience, // The unit of roothub is 100us, means 100ms as interval, and // the unit of hub is 1ms, means 64ms as interval. // -#define USB_ROOTHUB_POLL_INTERVAL (100 * 10000U) -#define USB_HUB_POLL_INTERVAL 64 +#define USB_ROOTHUB_POLL_INTERVAL (100 * 10000U) +#define USB_HUB_POLL_INTERVAL 64 // // Wait for port stable to work, refers to specification @@ -69,13 +66,13 @@ typedef struct _USB_HUB_API USB_HUB_API; // // Wait for port statue reg change, set by experience // -#define USB_WAIT_PORT_STS_CHANGE_STALL (100) +#define USB_WAIT_PORT_STS_CHANGE_STALL (100) // // Wait for set device address, refers to specification // [USB20-9.2.6.3, it says 2ms] // -#define USB_SET_DEVICE_ADDRESS_STALL (2 * USB_BUS_1_MILLISECOND) +#define USB_SET_DEVICE_ADDRESS_STALL (2 * USB_BUS_1_MILLISECOND) // // Wait for retry max packet size, set by experience @@ -86,7 +83,7 @@ typedef struct _USB_HUB_API USB_HUB_API; // Wait for hub port power-on, refers to specification // [USB20-11.23.2] // -#define USB_SET_PORT_POWER_STALL (2 * USB_BUS_1_MILLISECOND) +#define USB_SET_PORT_POWER_STALL (2 * USB_BUS_1_MILLISECOND) // // Wait for port reset, refers to specification @@ -103,7 +100,7 @@ typedef struct _USB_HUB_API USB_HUB_API; // Wait for port recovery to accept SetAddress, refers to specification // [USB20-7.1.7.5, it says 10 ms for TRSTRCY] // -#define USB_SET_PORT_RECOVERY_STALL (10 * USB_BUS_1_MILLISECOND) +#define USB_SET_PORT_RECOVERY_STALL (10 * USB_BUS_1_MILLISECOND) // // Wait for clear roothub port reset, set by experience @@ -113,7 +110,7 @@ typedef struct _USB_HUB_API USB_HUB_API; // // Wait for set roothub port enable, set by experience // -#define USB_SET_ROOT_PORT_ENABLE_STALL (20 * USB_BUS_1_MILLISECOND) +#define USB_SET_ROOT_PORT_ENABLE_STALL (20 * USB_BUS_1_MILLISECOND) // // Send general device request timeout. @@ -122,7 +119,7 @@ typedef struct _USB_HUB_API USB_HUB_API; // 50 milliseconds. We use a value of 500 milliseconds to work // around slower hubs and devices. // -#define USB_GENERAL_DEVICE_REQUEST_TIMEOUT 500 +#define USB_GENERAL_DEVICE_REQUEST_TIMEOUT 500 // // Send clear feature request timeout, set by experience @@ -133,13 +130,13 @@ typedef struct _USB_HUB_API USB_HUB_API; // Bus raises TPL to TPL_NOTIFY to serialize all its operations // to protect shared data structures. // -#define USB_BUS_TPL TPL_NOTIFY +#define USB_BUS_TPL TPL_NOTIFY -#define USB_INTERFACE_SIGNATURE SIGNATURE_32 ('U', 'S', 'B', 'I') -#define USB_BUS_SIGNATURE SIGNATURE_32 ('U', 'S', 'B', 'B') +#define USB_INTERFACE_SIGNATURE SIGNATURE_32 ('U', 'S', 'B', 'I') +#define USB_BUS_SIGNATURE SIGNATURE_32 ('U', 'S', 'B', 'B') -#define USB_BIT(a) ((UINTN)(1 << (a))) -#define USB_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define USB_BIT(a) ((UINTN)(1 << (a))) +#define USB_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) #define USB_INTERFACE_FROM_USBIO(a) \ CR(a, USB_INTERFACE, UsbIo, USB_INTERFACE_SIGNATURE) @@ -153,113 +150,112 @@ typedef struct _USB_HUB_API USB_HUB_API; // gEfiCallerIdGuid will be used as its protocol guid. // typedef struct _EFI_USB_BUS_PROTOCOL { - UINT64 Reserved; + UINT64 Reserved; } EFI_USB_BUS_PROTOCOL; - // // Stands for the real USB device. Each device may // has several separately working interfaces. // struct _USB_DEVICE { - USB_BUS *Bus; + USB_BUS *Bus; // // Configuration information // - UINT8 Speed; - UINT8 Address; - UINT32 MaxPacket0; + UINT8 Speed; + UINT8 Address; + UINT32 MaxPacket0; // // The device's descriptors and its configuration // - USB_DEVICE_DESC *DevDesc; - USB_CONFIG_DESC *ActiveConfig; + USB_DEVICE_DESC *DevDesc; + USB_CONFIG_DESC *ActiveConfig; - UINT16 LangId [USB_MAX_LANG_ID]; - UINT16 TotalLangId; + UINT16 LangId[USB_MAX_LANG_ID]; + UINT16 TotalLangId; - UINT8 NumOfInterface; - USB_INTERFACE *Interfaces [USB_MAX_INTERFACE]; + UINT8 NumOfInterface; + USB_INTERFACE *Interfaces[USB_MAX_INTERFACE]; // // Parent child relationship // - EFI_USB2_HC_TRANSACTION_TRANSLATOR Translator; + EFI_USB2_HC_TRANSACTION_TRANSLATOR Translator; - UINT8 ParentAddr; - USB_INTERFACE *ParentIf; - UINT8 ParentPort; // Start at 0 - UINT8 Tier; - BOOLEAN DisconnectFail; + UINT8 ParentAddr; + USB_INTERFACE *ParentIf; + UINT8 ParentPort; // Start at 0 + UINT8 Tier; + BOOLEAN DisconnectFail; }; // // Stands for different functions of USB device // struct _USB_INTERFACE { - UINTN Signature; - USB_DEVICE *Device; - USB_INTERFACE_DESC *IfDesc; - USB_INTERFACE_SETTING *IfSetting; + UINTN Signature; + USB_DEVICE *Device; + USB_INTERFACE_DESC *IfDesc; + USB_INTERFACE_SETTING *IfSetting; // // Handles and protocols // - EFI_HANDLE Handle; - EFI_USB_IO_PROTOCOL UsbIo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - BOOLEAN IsManaged; + EFI_HANDLE Handle; + EFI_USB_IO_PROTOCOL UsbIo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + BOOLEAN IsManaged; // // Hub device special data // - BOOLEAN IsHub; - USB_HUB_API *HubApi; - UINT8 NumOfPort; - EFI_EVENT HubNotify; + BOOLEAN IsHub; + USB_HUB_API *HubApi; + UINT8 NumOfPort; + EFI_EVENT HubNotify; // // Data used only by normal hub devices // - USB_ENDPOINT_DESC *HubEp; - UINT8 *ChangeMap; + USB_ENDPOINT_DESC *HubEp; + UINT8 *ChangeMap; // // Data used only by root hub to hand over device to // companion UHCI driver if low/full speed devices are // connected to EHCI. // - UINT8 MaxSpeed; + UINT8 MaxSpeed; }; // // Stands for the current USB Bus // struct _USB_BUS { - UINTN Signature; - EFI_USB_BUS_PROTOCOL BusId; + UINTN Signature; + EFI_USB_BUS_PROTOCOL BusId; // // Managed USB host controller // - EFI_HANDLE HostHandle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_USB2_HC_PROTOCOL *Usb2Hc; - EFI_USB_HC_PROTOCOL *UsbHc; + EFI_HANDLE HostHandle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_USB2_HC_PROTOCOL *Usb2Hc; + EFI_USB_HC_PROTOCOL *UsbHc; // // Recorded the max supported usb devices. // XHCI can support up to 255 devices. // EHCI/UHCI/OHCI supports up to 127 devices. // - UINT32 MaxDevices; + UINT32 MaxDevices; // // An array of device that is on the bus. Devices[0] is // for root hub. Device with address i is at Devices[i]. // - USB_DEVICE *Devices[256]; + USB_DEVICE *Devices[256]; // // USB Bus driver need to control the recursive connect policy of the bus, only those wanted @@ -269,35 +265,34 @@ struct _USB_BUS { // every wanted child device is stored in a item of the WantedUsbIoDPList, whose structure is // DEVICE_PATH_LIST_ITEM // - LIST_ENTRY WantedUsbIoDPList; - + LIST_ENTRY WantedUsbIoDPList; }; // // USB Hub Api // -struct _USB_HUB_API{ - USB_HUB_INIT Init; - USB_HUB_GET_PORT_STATUS GetPortStatus; - USB_HUB_CLEAR_PORT_CHANGE ClearPortChange; - USB_HUB_SET_PORT_FEATURE SetPortFeature; - USB_HUB_CLEAR_PORT_FEATURE ClearPortFeature; - USB_HUB_RESET_PORT ResetPort; - USB_HUB_RELEASE Release; +struct _USB_HUB_API { + USB_HUB_INIT Init; + USB_HUB_GET_PORT_STATUS GetPortStatus; + USB_HUB_CLEAR_PORT_CHANGE ClearPortChange; + USB_HUB_SET_PORT_FEATURE SetPortFeature; + USB_HUB_CLEAR_PORT_FEATURE ClearPortFeature; + USB_HUB_RESET_PORT ResetPort; + USB_HUB_RELEASE Release; }; -#define USB_US_LAND_ID 0x0409 +#define USB_US_LAND_ID 0x0409 -#define DEVICE_PATH_LIST_ITEM_SIGNATURE SIGNATURE_32('d','p','l','i') -typedef struct _DEVICE_PATH_LIST_ITEM{ - UINTN Signature; - LIST_ENTRY Link; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; +#define DEVICE_PATH_LIST_ITEM_SIGNATURE SIGNATURE_32('d','p','l','i') +typedef struct _DEVICE_PATH_LIST_ITEM { + UINTN Signature; + LIST_ENTRY Link; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } DEVICE_PATH_LIST_ITEM; typedef struct { - USB_CLASS_DEVICE_PATH UsbClass; - EFI_DEVICE_PATH_PROTOCOL End; + USB_CLASS_DEVICE_PATH UsbClass; + EFI_DEVICE_PATH_PROTOCOL End; } USB_CLASS_FORMAT_DEVICE_PATH; /** @@ -312,7 +307,7 @@ typedef struct { EFI_STATUS EFIAPI UsbBusFreeUsbDPList ( - IN LIST_ENTRY *UsbIoDPList + IN LIST_ENTRY *UsbIoDPList ); /** @@ -329,8 +324,8 @@ UsbBusFreeUsbDPList ( EFI_STATUS EFIAPI UsbBusAddWantedUsbIoDP ( - IN EFI_USB_BUS_PROTOCOL *UsbBusId, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_USB_BUS_PROTOCOL *UsbBusId, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -346,8 +341,8 @@ UsbBusAddWantedUsbIoDP ( BOOLEAN EFIAPI UsbBusIsWantedUsbIO ( - IN USB_BUS *Bus, - IN USB_INTERFACE *UsbIf + IN USB_BUS *Bus, + IN USB_INTERFACE *UsbIf ); /** @@ -363,7 +358,7 @@ UsbBusIsWantedUsbIO ( EFI_STATUS EFIAPI UsbBusRecursivelyConnectWantedUsbIo ( - IN EFI_USB_BUS_PROTOCOL *UsbBusId + IN EFI_USB_BUS_PROTOCOL *UsbBusId ); /** @@ -416,12 +411,12 @@ UsbIoControlTransfer ( EFI_STATUS EFIAPI UsbIoBulkTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Endpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout, - OUT UINT32 *UsbStatus + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Endpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout, + OUT UINT32 *UsbStatus ); /** @@ -443,12 +438,12 @@ UsbIoBulkTransfer ( EFI_STATUS EFIAPI UsbIoSyncInterruptTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Endpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout, - OUT UINT32 *UsbStatus + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Endpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout, + OUT UINT32 *UsbStatus ); /** @@ -498,11 +493,11 @@ UsbIoAsyncInterruptTransfer ( EFI_STATUS EFIAPI UsbIoIsochronousTransfer ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 DeviceEndpoint, - IN OUT VOID *Data, - IN UINTN DataLength, - OUT UINT32 *Status + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 DeviceEndpoint, + IN OUT VOID *Data, + IN UINTN DataLength, + OUT UINT32 *Status ); /** @@ -543,8 +538,8 @@ UsbIoAsyncIsochronousTransfer ( EFI_STATUS EFIAPI UsbIoGetDeviceDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - OUT EFI_USB_DEVICE_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + OUT EFI_USB_DEVICE_DESCRIPTOR *Descriptor ); /** @@ -561,8 +556,8 @@ UsbIoGetDeviceDescriptor ( EFI_STATUS EFIAPI UsbIoGetActiveConfigDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - OUT EFI_USB_CONFIG_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + OUT EFI_USB_CONFIG_DESCRIPTOR *Descriptor ); /** @@ -597,9 +592,9 @@ UsbIoGetInterfaceDescriptor ( EFI_STATUS EFIAPI UsbIoGetEndpointDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT8 Index, - OUT EFI_USB_ENDPOINT_DESCRIPTOR *Descriptor + IN EFI_USB_IO_PROTOCOL *This, + IN UINT8 Index, + OUT EFI_USB_ENDPOINT_DESCRIPTOR *Descriptor ); /** @@ -615,9 +610,9 @@ UsbIoGetEndpointDescriptor ( EFI_STATUS EFIAPI UsbIoGetSupportedLanguages ( - IN EFI_USB_IO_PROTOCOL *This, - OUT UINT16 **LangIDTable, - OUT UINT16 *TableSize + IN EFI_USB_IO_PROTOCOL *This, + OUT UINT16 **LangIDTable, + OUT UINT16 *TableSize ); /** @@ -635,10 +630,10 @@ UsbIoGetSupportedLanguages ( EFI_STATUS EFIAPI UsbIoGetStringDescriptor ( - IN EFI_USB_IO_PROTOCOL *This, - IN UINT16 LangID, - IN UINT8 StringIndex, - OUT CHAR16 **String + IN EFI_USB_IO_PROTOCOL *This, + IN UINT16 LangID, + IN UINT8 StringIndex, + OUT CHAR16 **String ); /** @@ -690,8 +685,8 @@ UsbBusBuildProtocol ( EFI_STATUS EFIAPI UsbBusDriverEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); /** @@ -756,9 +751,9 @@ UsbBusControllerDriverStop ( IN EFI_HANDLE *ChildHandleBuffer ); -extern EFI_USB_IO_PROTOCOL mUsbIoProtocol; -extern EFI_DRIVER_BINDING_PROTOCOL mUsbBusDriverBinding; -extern EFI_COMPONENT_NAME_PROTOCOL mUsbBusComponentName; -extern EFI_COMPONENT_NAME2_PROTOCOL mUsbBusComponentName2; +extern EFI_USB_IO_PROTOCOL mUsbIoProtocol; +extern EFI_DRIVER_BINDING_PROTOCOL mUsbBusDriverBinding; +extern EFI_COMPONENT_NAME_PROTOCOL mUsbBusComponentName; +extern EFI_COMPONENT_NAME2_PROTOCOL mUsbBusComponentName2; #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c index 4e602228fb..a620a67074 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbBus.h" - /** Free the interface setting descriptor. @@ -21,8 +20,8 @@ UsbFreeInterfaceDesc ( IN USB_INTERFACE_SETTING *Setting ) { - USB_ENDPOINT_DESC *Ep; - UINTN Index; + USB_ENDPOINT_DESC *Ep; + UINTN Index; if (Setting->Endpoints != NULL) { // @@ -47,7 +46,6 @@ UsbFreeInterfaceDesc ( FreePool (Setting); } - /** Free a configuration descriptor with its interface descriptors. It may be initialized partially. @@ -57,12 +55,12 @@ UsbFreeInterfaceDesc ( **/ VOID UsbFreeConfigDesc ( - IN USB_CONFIG_DESC *Config + IN USB_CONFIG_DESC *Config ) { - USB_INTERFACE_DESC *Interface; - UINTN Index; - UINTN SetIndex; + USB_INTERFACE_DESC *Interface; + UINTN Index; + UINTN SetIndex; if (Config->Interfaces != NULL) { // @@ -91,10 +89,8 @@ UsbFreeConfigDesc ( } FreePool (Config); - } - /** Free a device descriptor with its configurations. @@ -103,10 +99,10 @@ UsbFreeConfigDesc ( **/ VOID UsbFreeDevDesc ( - IN USB_DEVICE_DESC *DevDesc + IN USB_DEVICE_DESC *DevDesc ) { - UINTN Index; + UINTN Index; if (DevDesc->Configs != NULL) { for (Index = 0; Index < DevDesc->Desc.NumConfigurations; Index++) { @@ -121,7 +117,6 @@ UsbFreeDevDesc ( FreePool (DevDesc); } - /** Create a descriptor. @@ -135,46 +130,46 @@ UsbFreeDevDesc ( **/ VOID * UsbCreateDesc ( - IN UINT8 *DescBuf, - IN UINTN Len, - IN UINT8 Type, - OUT UINTN *Consumed + IN UINT8 *DescBuf, + IN UINTN Len, + IN UINT8 Type, + OUT UINTN *Consumed ) { - USB_DESC_HEAD *Head; - UINTN DescLen; - UINTN CtrlLen; - UINTN Offset; - VOID *Desc; + USB_DESC_HEAD *Head; + UINTN DescLen; + UINTN CtrlLen; + UINTN Offset; + VOID *Desc; DescLen = 0; CtrlLen = 0; *Consumed = 0; switch (Type) { - case USB_DESC_TYPE_DEVICE: - DescLen = sizeof (EFI_USB_DEVICE_DESCRIPTOR); - CtrlLen = sizeof (USB_DEVICE_DESC); - break; - - case USB_DESC_TYPE_CONFIG: - DescLen = sizeof (EFI_USB_CONFIG_DESCRIPTOR); - CtrlLen = sizeof (USB_CONFIG_DESC); - break; - - case USB_DESC_TYPE_INTERFACE: - DescLen = sizeof (EFI_USB_INTERFACE_DESCRIPTOR); - CtrlLen = sizeof (USB_INTERFACE_SETTING); - break; - - case USB_DESC_TYPE_ENDPOINT: - DescLen = sizeof (EFI_USB_ENDPOINT_DESCRIPTOR); - CtrlLen = sizeof (USB_ENDPOINT_DESC); - break; - - default: - ASSERT (FALSE); - return NULL; + case USB_DESC_TYPE_DEVICE: + DescLen = sizeof (EFI_USB_DEVICE_DESCRIPTOR); + CtrlLen = sizeof (USB_DEVICE_DESC); + break; + + case USB_DESC_TYPE_CONFIG: + DescLen = sizeof (EFI_USB_CONFIG_DESCRIPTOR); + CtrlLen = sizeof (USB_CONFIG_DESC); + break; + + case USB_DESC_TYPE_INTERFACE: + DescLen = sizeof (EFI_USB_INTERFACE_DESCRIPTOR); + CtrlLen = sizeof (USB_INTERFACE_SETTING); + break; + + case USB_DESC_TYPE_ENDPOINT: + DescLen = sizeof (EFI_USB_ENDPOINT_DESCRIPTOR); + CtrlLen = sizeof (USB_ENDPOINT_DESC); + break; + + default: + ASSERT (FALSE); + return NULL; } // @@ -231,19 +226,18 @@ UsbCreateDesc ( return NULL; } - Desc = AllocateZeroPool ((UINTN) CtrlLen); + Desc = AllocateZeroPool ((UINTN)CtrlLen); if (Desc == NULL) { return NULL; } - CopyMem (Desc, Head, (UINTN) DescLen); + CopyMem (Desc, Head, (UINTN)DescLen); *Consumed = Offset; return Desc; } - /** Parse an interface descriptor and its endpoints. @@ -256,23 +250,23 @@ UsbCreateDesc ( **/ USB_INTERFACE_SETTING * UsbParseInterfaceDesc ( - IN UINT8 *DescBuf, - IN UINTN Len, - OUT UINTN *Consumed + IN UINT8 *DescBuf, + IN UINTN Len, + OUT UINTN *Consumed ) { - USB_INTERFACE_SETTING *Setting; - USB_ENDPOINT_DESC *Ep; - UINTN Index; - UINTN NumEp; - UINTN Used; - UINTN Offset; + USB_INTERFACE_SETTING *Setting; + USB_ENDPOINT_DESC *Ep; + UINTN Index; + UINTN NumEp; + UINTN Used; + UINTN Offset; *Consumed = 0; Setting = UsbCreateDesc (DescBuf, Len, USB_DESC_TYPE_INTERFACE, &Used); if (Setting == NULL) { - DEBUG (( DEBUG_ERROR, "UsbParseInterfaceDesc: failed to create interface descriptor\n")); + DEBUG ((DEBUG_ERROR, "UsbParseInterfaceDesc: failed to create interface descriptor\n")); return NULL; } @@ -281,16 +275,21 @@ UsbParseInterfaceDesc ( // // Create an array to hold the interface's endpoints // - NumEp = Setting->Desc.NumEndpoints; + NumEp = Setting->Desc.NumEndpoints; - DEBUG (( DEBUG_INFO, "UsbParseInterfaceDesc: interface %d(setting %d) has %d endpoints\n", - Setting->Desc.InterfaceNumber, Setting->Desc.AlternateSetting, (UINT32)NumEp)); + DEBUG (( + DEBUG_INFO, + "UsbParseInterfaceDesc: interface %d(setting %d) has %d endpoints\n", + Setting->Desc.InterfaceNumber, + Setting->Desc.AlternateSetting, + (UINT32)NumEp + )); if (NumEp == 0) { goto ON_EXIT; } - Setting->Endpoints = AllocateZeroPool (sizeof (USB_ENDPOINT_DESC *) * NumEp); + Setting->Endpoints = AllocateZeroPool (sizeof (USB_ENDPOINT_DESC *) * NumEp); if (Setting->Endpoints == NULL) { goto ON_ERROR; @@ -303,15 +302,14 @@ UsbParseInterfaceDesc ( Ep = UsbCreateDesc (DescBuf + Offset, Len - Offset, USB_DESC_TYPE_ENDPOINT, &Used); if (Ep == NULL) { - DEBUG (( DEBUG_ERROR, "UsbParseInterfaceDesc: failed to create endpoint(index %d)\n", (UINT32)Index)); + DEBUG ((DEBUG_ERROR, "UsbParseInterfaceDesc: failed to create endpoint(index %d)\n", (UINT32)Index)); goto ON_ERROR; } - Setting->Endpoints[Index] = Ep; - Offset += Used; + Setting->Endpoints[Index] = Ep; + Offset += Used; } - ON_EXIT: *Consumed = Offset; return Setting; @@ -321,7 +319,6 @@ ON_ERROR: return NULL; } - /** Parse the configuration descriptor and its interfaces. @@ -333,16 +330,16 @@ ON_ERROR: **/ USB_CONFIG_DESC * UsbParseConfigDesc ( - IN UINT8 *DescBuf, - IN UINTN Len + IN UINT8 *DescBuf, + IN UINTN Len ) { - USB_CONFIG_DESC *Config; - USB_INTERFACE_SETTING *Setting; - USB_INTERFACE_DESC *Interface; - UINTN Index; - UINTN NumIf; - UINTN Consumed; + USB_CONFIG_DESC *Config; + USB_INTERFACE_SETTING *Setting; + USB_INTERFACE_DESC *Interface; + UINTN Index; + UINTN NumIf; + UINTN Consumed; ASSERT (DescBuf != NULL); @@ -355,15 +352,19 @@ UsbParseConfigDesc ( // // Initialize an array of setting for the configuration's interfaces. // - NumIf = Config->Desc.NumInterfaces; - Config->Interfaces = AllocateZeroPool (sizeof (USB_INTERFACE_DESC *) * NumIf); + NumIf = Config->Desc.NumInterfaces; + Config->Interfaces = AllocateZeroPool (sizeof (USB_INTERFACE_DESC *) * NumIf); if (Config->Interfaces == NULL) { goto ON_ERROR; } - DEBUG (( DEBUG_INFO, "UsbParseConfigDesc: config %d has %d interfaces\n", - Config->Desc.ConfigurationValue, (UINT32)NumIf)); + DEBUG (( + DEBUG_INFO, + "UsbParseConfigDesc: config %d has %d interfaces\n", + Config->Desc.ConfigurationValue, + (UINT32)NumIf + )); for (Index = 0; Index < NumIf; Index++) { Interface = AllocateZeroPool (sizeof (USB_INTERFACE_DESC)); @@ -394,11 +395,10 @@ UsbParseConfigDesc ( Setting = UsbParseInterfaceDesc (DescBuf, Len, &Consumed); if (Setting == NULL) { - DEBUG (( DEBUG_ERROR, "UsbParseConfigDesc: warning: failed to get interface setting, stop parsing now.\n")); + DEBUG ((DEBUG_ERROR, "UsbParseConfigDesc: warning: failed to get interface setting, stop parsing now.\n")); break; - } else if (Setting->Desc.InterfaceNumber >= NumIf) { - DEBUG (( DEBUG_ERROR, "UsbParseConfigDesc: malformatted interface descriptor\n")); + DEBUG ((DEBUG_ERROR, "UsbParseConfigDesc: malformatted interface descriptor\n")); UsbFreeInterfaceDesc (Setting); goto ON_ERROR; @@ -427,7 +427,6 @@ ON_ERROR: return NULL; } - /** USB standard control transfer support routine. This function is used by USB device. It is possible that @@ -450,15 +449,15 @@ ON_ERROR: **/ EFI_STATUS UsbCtrlRequest ( - IN USB_DEVICE *UsbDev, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINTN Type, - IN UINTN Target, - IN UINTN Request, - IN UINT16 Value, - IN UINT16 Index, - IN OUT VOID *Buf, - IN UINTN Length + IN USB_DEVICE *UsbDev, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINTN Type, + IN UINTN Target, + IN UINTN Request, + IN UINT16 Value, + IN UINT16 Index, + IN OUT VOID *Buf, + IN UINTN Length ) { EFI_USB_DEVICE_REQUEST DevReq; @@ -468,13 +467,13 @@ UsbCtrlRequest ( ASSERT ((UsbDev != NULL) && (UsbDev->Bus != NULL)); - DevReq.RequestType = USB_REQUEST_TYPE (Direction, Type, Target); - DevReq.Request = (UINT8) Request; - DevReq.Value = Value; - DevReq.Index = Index; - DevReq.Length = (UINT16) Length; + DevReq.RequestType = USB_REQUEST_TYPE (Direction, Type, Target); + DevReq.Request = (UINT8)Request; + DevReq.Value = Value; + DevReq.Index = Index; + DevReq.Length = (UINT16)Length; - Len = Length; + Len = Length; Status = UsbHcControlTransfer ( UsbDev->Bus, UsbDev->Address, @@ -492,7 +491,6 @@ UsbCtrlRequest ( return Status; } - /** Get the standard descriptors. @@ -510,15 +508,15 @@ UsbCtrlRequest ( **/ EFI_STATUS UsbCtrlGetDesc ( - IN USB_DEVICE *UsbDev, - IN UINTN DescType, - IN UINTN DescIndex, - IN UINT16 LangId, - OUT VOID *Buf, - IN UINTN Length + IN USB_DEVICE *UsbDev, + IN UINTN DescType, + IN UINTN DescIndex, + IN UINT16 LangId, + OUT VOID *Buf, + IN UINTN Length ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( UsbDev, @@ -526,7 +524,7 @@ UsbCtrlGetDesc ( USB_REQ_TYPE_STANDARD, USB_TARGET_DEVICE, USB_REQ_GET_DESCRIPTOR, - (UINT16) ((DescType << 8) | DescIndex), + (UINT16)((DescType << 8) | DescIndex), LangId, Buf, Length @@ -535,7 +533,6 @@ UsbCtrlGetDesc ( return Status; } - /** Return the max packet size for endpoint zero. This function is the first function called to get descriptors during bus @@ -549,13 +546,12 @@ UsbCtrlGetDesc ( **/ EFI_STATUS UsbGetMaxPacketSize0 ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ) { - EFI_USB_DEVICE_DESCRIPTOR DevDesc; - EFI_STATUS Status; - UINTN Index; - + EFI_USB_DEVICE_DESCRIPTOR DevDesc; + EFI_STATUS Status; + UINTN Index; // // Get the first 8 bytes of the device descriptor which contains @@ -569,6 +565,7 @@ UsbGetMaxPacketSize0 ( UsbDev->MaxPacket0 = 1 << 9; return EFI_SUCCESS; } + UsbDev->MaxPacket0 = DevDesc.MaxPacketSize0; return EFI_SUCCESS; } @@ -579,7 +576,6 @@ UsbGetMaxPacketSize0 ( return EFI_DEVICE_ERROR; } - /** Get the device descriptor for the device. @@ -591,11 +587,11 @@ UsbGetMaxPacketSize0 ( **/ EFI_STATUS UsbGetDevDesc ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ) { - USB_DEVICE_DESC *DevDesc; - EFI_STATUS Status; + USB_DEVICE_DESC *DevDesc; + EFI_STATUS Status; DevDesc = AllocateZeroPool (sizeof (USB_DEVICE_DESC)); @@ -603,14 +599,14 @@ UsbGetDevDesc ( return EFI_OUT_OF_RESOURCES; } - Status = UsbCtrlGetDesc ( - UsbDev, - USB_DESC_TYPE_DEVICE, - 0, - 0, - DevDesc, - sizeof (EFI_USB_DEVICE_DESCRIPTOR) - ); + Status = UsbCtrlGetDesc ( + UsbDev, + USB_DESC_TYPE_DEVICE, + 0, + 0, + DevDesc, + sizeof (EFI_USB_DEVICE_DESCRIPTOR) + ); if (EFI_ERROR (Status)) { gBS->FreePool (DevDesc); @@ -621,7 +617,6 @@ UsbGetDevDesc ( return Status; } - /** Retrieve the indexed string for the language. It requires two steps to get a string, first to get the string's length. Then @@ -636,14 +631,14 @@ UsbGetDevDesc ( **/ EFI_USB_STRING_DESCRIPTOR * UsbGetOneString ( - IN USB_DEVICE *UsbDev, - IN UINT8 Index, - IN UINT16 LangId + IN USB_DEVICE *UsbDev, + IN UINT8 Index, + IN UINT16 LangId ) { - EFI_USB_STRING_DESCRIPTOR Desc; - EFI_STATUS Status; - UINT8 *Buf; + EFI_USB_STRING_DESCRIPTOR Desc; + EFI_STATUS Status; + UINT8 *Buf; // // First get two bytes which contains the string length. @@ -656,7 +651,8 @@ UsbGetOneString ( if (EFI_ERROR (Status) || (Desc.Length < OFFSET_OF (EFI_USB_STRING_DESCRIPTOR, Length) + sizeof (Desc.Length)) || (Desc.Length % 2 != 0) - ) { + ) + { return NULL; } @@ -680,10 +676,9 @@ UsbGetOneString ( return NULL; } - return (EFI_USB_STRING_DESCRIPTOR *) Buf; + return (EFI_USB_STRING_DESCRIPTOR *)Buf; } - /** Build the language ID table for string descriptors. @@ -694,14 +689,14 @@ UsbGetOneString ( **/ EFI_STATUS UsbBuildLangTable ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ) { - EFI_USB_STRING_DESCRIPTOR *Desc; - EFI_STATUS Status; - UINTN Index; - UINTN Max; - UINT16 *Point; + EFI_USB_STRING_DESCRIPTOR *Desc; + EFI_STATUS Status; + UINTN Index; + UINTN Max; + UINT16 *Point; // // The string of language ID zero returns the supported languages @@ -719,8 +714,8 @@ UsbBuildLangTable ( Status = EFI_SUCCESS; - Max = (Desc->Length - 2) / 2; - Max = MIN(Max, USB_MAX_LANG_ID); + Max = (Desc->Length - 2) / 2; + Max = MIN (Max, USB_MAX_LANG_ID); Point = Desc->String; for (Index = 0; Index < Max; Index++) { @@ -735,7 +730,6 @@ ON_EXIT: return Status; } - /** Retrieve the indexed configure for the device. USB device returns the configuration together with the interfaces for @@ -750,13 +744,13 @@ ON_EXIT: **/ EFI_USB_CONFIG_DESCRIPTOR * UsbGetOneConfig ( - IN USB_DEVICE *UsbDev, - IN UINT8 Index + IN USB_DEVICE *UsbDev, + IN UINT8 Index ) { - EFI_USB_CONFIG_DESCRIPTOR Desc; - EFI_STATUS Status; - VOID *Buf; + EFI_USB_CONFIG_DESCRIPTOR Desc; + EFI_STATUS Status; + VOID *Buf; // // First get four bytes which contains the total length @@ -765,13 +759,17 @@ UsbGetOneConfig ( Status = UsbCtrlGetDesc (UsbDev, USB_DESC_TYPE_CONFIG, Index, 0, &Desc, 8); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbGetOneConfig: failed to get descript length(%d) %r\n", - Desc.TotalLength, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbGetOneConfig: failed to get descript length(%d) %r\n", + Desc.TotalLength, + Status + )); return NULL; } - DEBUG (( DEBUG_INFO, "UsbGetOneConfig: total length is %d\n", Desc.TotalLength)); + DEBUG ((DEBUG_INFO, "UsbGetOneConfig: total length is %d\n", Desc.TotalLength)); // // Reject if TotalLength even cannot cover itself. @@ -789,7 +787,7 @@ UsbGetOneConfig ( Status = UsbCtrlGetDesc (UsbDev, USB_DESC_TYPE_CONFIG, Index, 0, Buf, Desc.TotalLength); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbGetOneConfig: failed to get full descript %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbGetOneConfig: failed to get full descript %r\n", Status)); FreePool (Buf); return NULL; @@ -798,7 +796,6 @@ UsbGetOneConfig ( return Buf; } - /** Build the whole array of descriptors. This function must be called after UsbGetMaxPacketSize0 returns the max packet @@ -812,15 +809,15 @@ UsbGetOneConfig ( **/ EFI_STATUS UsbBuildDescTable ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ) { - EFI_USB_CONFIG_DESCRIPTOR *Config; - USB_DEVICE_DESC *DevDesc; - USB_CONFIG_DESC *ConfigDesc; - UINT8 NumConfig; - EFI_STATUS Status; - UINT8 Index; + EFI_USB_CONFIG_DESCRIPTOR *Config; + USB_DEVICE_DESC *DevDesc; + USB_CONFIG_DESC *ConfigDesc; + UINT8 NumConfig; + EFI_STATUS Status; + UINT8 Index; // // Get the device descriptor, then allocate the configure @@ -829,7 +826,7 @@ UsbBuildDescTable ( Status = UsbGetDevDesc (UsbDev); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbBuildDescTable: failed to get device descriptor - %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbBuildDescTable: failed to get device descriptor - %r\n", Status)); return Status; } @@ -844,7 +841,7 @@ UsbBuildDescTable ( return EFI_OUT_OF_RESOURCES; } - DEBUG (( DEBUG_INFO, "UsbBuildDescTable: device has %d configures\n", NumConfig)); + DEBUG ((DEBUG_INFO, "UsbBuildDescTable: device has %d configures\n", NumConfig)); // // Read each configurations, then parse them @@ -853,7 +850,7 @@ UsbBuildDescTable ( Config = UsbGetOneConfig (UsbDev, Index); if (Config == NULL) { - DEBUG (( DEBUG_ERROR, "UsbBuildDescTable: failed to get configure (index %d)\n", Index)); + DEBUG ((DEBUG_ERROR, "UsbBuildDescTable: failed to get configure (index %d)\n", Index)); // // If we can get the default descriptor, it is likely that the @@ -866,12 +863,12 @@ UsbBuildDescTable ( break; } - ConfigDesc = UsbParseConfigDesc ((UINT8 *) Config, Config->TotalLength); + ConfigDesc = UsbParseConfigDesc ((UINT8 *)Config, Config->TotalLength); FreePool (Config); if (ConfigDesc == NULL) { - DEBUG (( DEBUG_ERROR, "UsbBuildDescTable: failed to parse configure (index %d)\n", Index)); + DEBUG ((DEBUG_ERROR, "UsbBuildDescTable: failed to parse configure (index %d)\n", Index)); // // If we can get the default descriptor, it is likely that the @@ -894,13 +891,12 @@ UsbBuildDescTable ( Status = UsbBuildLangTable (UsbDev); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_INFO, "UsbBuildDescTable: get language ID table %r\n", Status)); + DEBUG ((DEBUG_INFO, "UsbBuildDescTable: get language ID table %r\n", Status)); } return EFI_SUCCESS; } - /** Set the device's address. @@ -913,11 +909,11 @@ UsbBuildDescTable ( **/ EFI_STATUS UsbSetAddress ( - IN USB_DEVICE *UsbDev, - IN UINT8 Address + IN USB_DEVICE *UsbDev, + IN UINT8 Address ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( UsbDev, @@ -934,7 +930,6 @@ UsbSetAddress ( return Status; } - /** Set the device's configuration. This function changes the device's internal state. UsbSelectConfig changes @@ -949,11 +944,11 @@ UsbSetAddress ( **/ EFI_STATUS UsbSetConfig ( - IN USB_DEVICE *UsbDev, - IN UINT8 ConfigIndex + IN USB_DEVICE *UsbDev, + IN UINT8 ConfigIndex ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( UsbDev, @@ -965,12 +960,11 @@ UsbSetConfig ( 0, NULL, 0 - ); + ); return Status; } - /** Usb UsbIo interface to clear the feature. This is should only be used by HUB which is considered a device driver @@ -987,21 +981,21 @@ UsbSetConfig ( **/ EFI_STATUS UsbIoClearFeature ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN UINTN Target, - IN UINT16 Feature, - IN UINT16 Index + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN UINTN Target, + IN UINT16 Feature, + IN UINT16 Index ) { EFI_USB_DEVICE_REQUEST DevReq; UINT32 UsbResult; EFI_STATUS Status; - DevReq.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, Target); - DevReq.Request = USB_REQ_CLEAR_FEATURE; - DevReq.Value = Feature; - DevReq.Index = Index; - DevReq.Length = 0; + DevReq.RequestType = USB_REQUEST_TYPE (EfiUsbNoData, USB_REQ_TYPE_STANDARD, Target); + DevReq.Request = USB_REQ_CLEAR_FEATURE; + DevReq.Value = Feature; + DevReq.Index = Index; + DevReq.Length = 0; Status = UsbIo->UsbControlTransfer ( UsbIo, diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.h b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.h index 7b0c77fdc7..ce205e706d 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.h +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbDesc.h @@ -26,12 +26,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #pragma pack(1) typedef struct { - UINT8 Len; - UINT8 Type; + UINT8 Len; + UINT8 Type; } USB_DESC_HEAD; #pragma pack() - // // Each USB device has a device descriptor. Each device may // have several configures. Each configure contains several @@ -42,13 +41,13 @@ typedef struct { // structure. // typedef struct { - EFI_USB_ENDPOINT_DESCRIPTOR Desc; - UINT8 Toggle; + EFI_USB_ENDPOINT_DESCRIPTOR Desc; + UINT8 Toggle; } USB_ENDPOINT_DESC; typedef struct { - EFI_USB_INTERFACE_DESCRIPTOR Desc; - USB_ENDPOINT_DESC **Endpoints; + EFI_USB_INTERFACE_DESCRIPTOR Desc; + USB_ENDPOINT_DESC **Endpoints; } USB_INTERFACE_SETTING; // @@ -57,19 +56,19 @@ typedef struct { // It should sufice in most environments. // typedef struct { - USB_INTERFACE_SETTING* Settings[USB_MAX_INTERFACE_SETTING]; - UINTN NumOfSetting; - UINTN ActiveIndex; // Index of active setting + USB_INTERFACE_SETTING *Settings[USB_MAX_INTERFACE_SETTING]; + UINTN NumOfSetting; + UINTN ActiveIndex; // Index of active setting } USB_INTERFACE_DESC; typedef struct { - EFI_USB_CONFIG_DESCRIPTOR Desc; - USB_INTERFACE_DESC **Interfaces; + EFI_USB_CONFIG_DESCRIPTOR Desc; + USB_INTERFACE_DESC **Interfaces; } USB_CONFIG_DESC; typedef struct { - EFI_USB_DEVICE_DESCRIPTOR Desc; - USB_CONFIG_DESC **Configs; + EFI_USB_DEVICE_DESCRIPTOR Desc; + USB_CONFIG_DESC **Configs; } USB_DEVICE_DESC; /** @@ -94,15 +93,15 @@ typedef struct { **/ EFI_STATUS UsbCtrlRequest ( - IN USB_DEVICE *UsbDev, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINTN Type, - IN UINTN Target, - IN UINTN Request, - IN UINT16 Value, - IN UINT16 Index, - IN OUT VOID *Buf, - IN UINTN Length + IN USB_DEVICE *UsbDev, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINTN Type, + IN UINTN Target, + IN UINTN Request, + IN UINT16 Value, + IN UINT16 Index, + IN OUT VOID *Buf, + IN UINTN Length ); /** @@ -118,7 +117,7 @@ UsbCtrlRequest ( **/ EFI_STATUS UsbGetMaxPacketSize0 ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ); /** @@ -131,7 +130,7 @@ UsbGetMaxPacketSize0 ( **/ VOID UsbFreeDevDesc ( - IN USB_DEVICE_DESC *DevDesc + IN USB_DEVICE_DESC *DevDesc ); /** @@ -146,11 +145,11 @@ UsbFreeDevDesc ( @return The created string descriptor or NULL. **/ -EFI_USB_STRING_DESCRIPTOR* +EFI_USB_STRING_DESCRIPTOR * UsbGetOneString ( - IN USB_DEVICE *UsbDev, - IN UINT8 StringIndex, - IN UINT16 LangId + IN USB_DEVICE *UsbDev, + IN UINT8 StringIndex, + IN UINT16 LangId ); /** @@ -166,7 +165,7 @@ UsbGetOneString ( **/ EFI_STATUS UsbBuildDescTable ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ); /** @@ -181,8 +180,8 @@ UsbBuildDescTable ( **/ EFI_STATUS UsbSetAddress ( - IN USB_DEVICE *UsbDev, - IN UINT8 Address + IN USB_DEVICE *UsbDev, + IN UINT8 Address ); /** @@ -199,8 +198,8 @@ UsbSetAddress ( **/ EFI_STATUS UsbSetConfig ( - IN USB_DEVICE *UsbDev, - IN UINT8 ConfigIndex + IN USB_DEVICE *UsbDev, + IN UINT8 ConfigIndex ); /** @@ -219,9 +218,10 @@ UsbSetConfig ( **/ EFI_STATUS UsbIoClearFeature ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN UINTN Target, - IN UINT16 Feature, - IN UINT16 Index + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN UINTN Target, + IN UINT16 Feature, + IN UINT16 Index ); + #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c index 500978a9de..5495b324b3 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.c @@ -20,13 +20,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ USB_ENDPOINT_DESC * UsbGetEndpointDesc ( - IN USB_INTERFACE *UsbIf, - IN UINT8 EpAddr + IN USB_INTERFACE *UsbIf, + IN UINT8 EpAddr ) { - USB_ENDPOINT_DESC *EpDesc; - UINT8 Index; - UINT8 NumEndpoints; + USB_ENDPOINT_DESC *EpDesc; + UINT8 Index; + UINT8 NumEndpoints; NumEndpoints = UsbIf->IfSetting->Desc.NumEndpoints; @@ -41,7 +41,6 @@ UsbGetEndpointDesc ( return NULL; } - /** Free the resource used by USB interface. @@ -52,31 +51,34 @@ UsbGetEndpointDesc ( **/ EFI_STATUS UsbFreeInterface ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ) { - EFI_STATUS Status; + EFI_STATUS Status; UsbCloseHostProtoByChild (UsbIf->Device->Bus, UsbIf->Handle); Status = gBS->UninstallMultipleProtocolInterfaces ( UsbIf->Handle, - &gEfiDevicePathProtocolGuid, UsbIf->DevicePath, - &gEfiUsbIoProtocolGuid, &UsbIf->UsbIo, + &gEfiDevicePathProtocolGuid, + UsbIf->DevicePath, + &gEfiUsbIoProtocolGuid, + &UsbIf->UsbIo, NULL ); if (!EFI_ERROR (Status)) { if (UsbIf->DevicePath != NULL) { FreePool (UsbIf->DevicePath); } + FreePool (UsbIf); } else { UsbOpenHostProtoByChild (UsbIf->Device->Bus, UsbIf->Handle); } + return Status; } - /** Create an interface for the descriptor IfDesc. Each device's configuration can have several interfaces. @@ -89,14 +91,14 @@ UsbFreeInterface ( **/ USB_INTERFACE * UsbCreateInterface ( - IN USB_DEVICE *Device, - IN USB_INTERFACE_DESC *IfDesc + IN USB_DEVICE *Device, + IN USB_INTERFACE_DESC *IfDesc ) { - USB_DEVICE_PATH UsbNode; - USB_INTERFACE *UsbIf; - USB_INTERFACE *HubIf; - EFI_STATUS Status; + USB_DEVICE_PATH UsbNode; + USB_INTERFACE *UsbIf; + USB_INTERFACE *HubIf; + EFI_STATUS Status; UsbIf = AllocateZeroPool (sizeof (USB_INTERFACE)); @@ -104,11 +106,11 @@ UsbCreateInterface ( return NULL; } - UsbIf->Signature = USB_INTERFACE_SIGNATURE; - UsbIf->Device = Device; - UsbIf->IfDesc = IfDesc; + UsbIf->Signature = USB_INTERFACE_SIGNATURE; + UsbIf->Device = Device; + UsbIf->IfDesc = IfDesc; ASSERT (IfDesc->ActiveIndex < USB_MAX_INTERFACE_SETTING); - UsbIf->IfSetting = IfDesc->Settings[IfDesc->ActiveIndex]; + UsbIf->IfSetting = IfDesc->Settings[IfDesc->ActiveIndex]; CopyMem ( &(UsbIf->UsbIo), @@ -119,10 +121,10 @@ UsbCreateInterface ( // // Install protocols for USBIO and device path // - UsbNode.Header.Type = MESSAGING_DEVICE_PATH; - UsbNode.Header.SubType = MSG_USB_DP; - UsbNode.ParentPortNumber = Device->ParentPort; - UsbNode.InterfaceNumber = UsbIf->IfSetting->Desc.InterfaceNumber; + UsbNode.Header.Type = MESSAGING_DEVICE_PATH; + UsbNode.Header.SubType = MSG_USB_DP; + UsbNode.ParentPortNumber = Device->ParentPort; + UsbNode.InterfaceNumber = UsbIf->IfSetting->Desc.InterfaceNumber; SetDevicePathNodeLength (&UsbNode.Header, sizeof (UsbNode)); @@ -182,7 +184,6 @@ ON_ERROR: return NULL; } - /** Free the resource used by this USB device. @@ -191,7 +192,7 @@ ON_ERROR: **/ VOID UsbFreeDevice ( - IN USB_DEVICE *Device + IN USB_DEVICE *Device ) { if (Device->DevDesc != NULL) { @@ -201,7 +202,6 @@ UsbFreeDevice ( gBS->FreePool (Device); } - /** Create a device which is on the parent's ParentPort port. @@ -213,11 +213,11 @@ UsbFreeDevice ( **/ USB_DEVICE * UsbCreateDevice ( - IN USB_INTERFACE *ParentIf, - IN UINT8 ParentPort + IN USB_INTERFACE *ParentIf, + IN UINT8 ParentPort ) { - USB_DEVICE *Device; + USB_DEVICE *Device; ASSERT (ParentIf != NULL); @@ -227,16 +227,15 @@ UsbCreateDevice ( return NULL; } - Device->Bus = ParentIf->Device->Bus; - Device->MaxPacket0 = 8; - Device->ParentAddr = ParentIf->Device->Address; - Device->ParentIf = ParentIf; - Device->ParentPort = ParentPort; - Device->Tier = (UINT8)(ParentIf->Device->Tier + 1); + Device->Bus = ParentIf->Device->Bus; + Device->MaxPacket0 = 8; + Device->ParentAddr = ParentIf->Device->Address; + Device->ParentIf = ParentIf; + Device->ParentPort = ParentPort; + Device->Tier = (UINT8)(ParentIf->Device->Tier + 1); return Device; } - /** Connect the USB interface with its driver. EFI USB bus will create a USB interface for each separate interface descriptor. @@ -249,11 +248,11 @@ UsbCreateDevice ( **/ EFI_STATUS UsbConnectDriver ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ) { - EFI_STATUS Status; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_TPL OldTpl; Status = EFI_SUCCESS; @@ -264,7 +263,6 @@ UsbConnectDriver ( if (UsbIsHubInterface (UsbIf)) { DEBUG ((DEBUG_INFO, "UsbConnectDriver: found a hub device\n")); Status = mUsbHubApi.Init (UsbIf); - } else { // // This function is called in both UsbIoControlTransfer and @@ -278,15 +276,15 @@ UsbConnectDriver ( // Only recursively wanted usb child device // if (UsbBusIsWantedUsbIO (UsbIf->Device->Bus, UsbIf)) { - OldTpl = UsbGetCurrentTpl (); + OldTpl = UsbGetCurrentTpl (); DEBUG ((DEBUG_INFO, "UsbConnectDriver: TPL before connect is %d, %p\n", (UINT32)OldTpl, UsbIf->Handle)); gBS->RestoreTPL (TPL_CALLBACK); - Status = gBS->ConnectController (UsbIf->Handle, NULL, NULL, TRUE); - UsbIf->IsManaged = (BOOLEAN)!EFI_ERROR (Status); + Status = gBS->ConnectController (UsbIf->Handle, NULL, NULL, TRUE); + UsbIf->IsManaged = (BOOLEAN) !EFI_ERROR (Status); - DEBUG ((DEBUG_INFO, "UsbConnectDriver: TPL after connect is %d\n", (UINT32)UsbGetCurrentTpl())); + DEBUG ((DEBUG_INFO, "UsbConnectDriver: TPL after connect is %d\n", (UINT32)UsbGetCurrentTpl ())); ASSERT (UsbGetCurrentTpl () == TPL_CALLBACK); gBS->RaiseTPL (OldTpl); @@ -296,7 +294,6 @@ UsbConnectDriver ( return Status; } - /** Select an alternate setting for the interface. Each interface can have several mutually exclusive @@ -312,12 +309,12 @@ UsbConnectDriver ( **/ EFI_STATUS UsbSelectSetting ( - IN USB_INTERFACE_DESC *IfDesc, - IN UINT8 Alternate + IN USB_INTERFACE_DESC *IfDesc, + IN UINT8 Alternate ) { - USB_INTERFACE_SETTING *Setting; - UINTN Index; + USB_INTERFACE_SETTING *Setting; + UINTN Index; // // Locate the active alternate setting @@ -340,8 +337,12 @@ UsbSelectSetting ( IfDesc->ActiveIndex = Index; ASSERT (Setting != NULL); - DEBUG ((DEBUG_INFO, "UsbSelectSetting: setting %d selected for interface %d\n", - Alternate, Setting->Desc.InterfaceNumber)); + DEBUG (( + DEBUG_INFO, + "UsbSelectSetting: setting %d selected for interface %d\n", + Alternate, + Setting->Desc.InterfaceNumber + )); // // Reset the endpoint toggle to zero @@ -353,7 +354,6 @@ UsbSelectSetting ( return EFI_SUCCESS; } - /** Select a new configuration for the device. Each device may support several configurations. @@ -368,22 +368,22 @@ UsbSelectSetting ( **/ EFI_STATUS UsbSelectConfig ( - IN USB_DEVICE *Device, - IN UINT8 ConfigValue + IN USB_DEVICE *Device, + IN UINT8 ConfigValue ) { - USB_DEVICE_DESC *DevDesc; - USB_CONFIG_DESC *ConfigDesc; - USB_INTERFACE_DESC *IfDesc; - USB_INTERFACE *UsbIf; - EFI_STATUS Status; - UINT8 Index; + USB_DEVICE_DESC *DevDesc; + USB_CONFIG_DESC *ConfigDesc; + USB_INTERFACE_DESC *IfDesc; + USB_INTERFACE *UsbIf; + EFI_STATUS Status; + UINT8 Index; // // Locate the active config, then set the device's pointer // - DevDesc = Device->DevDesc; - ConfigDesc = NULL; + DevDesc = Device->DevDesc; + ConfigDesc = NULL; for (Index = 0; Index < DevDesc->Desc.NumConfigurations; Index++) { ConfigDesc = DevDesc->Configs[Index]; @@ -399,8 +399,12 @@ UsbSelectConfig ( Device->ActiveConfig = ConfigDesc; - DEBUG ((DEBUG_INFO, "UsbSelectConfig: config %d selected for device %d\n", - ConfigValue, Device->Address)); + DEBUG (( + DEBUG_INFO, + "UsbSelectConfig: config %d selected for device %d\n", + ConfigValue, + Device->Address + )); // // Create interfaces for each USB interface descriptor. @@ -447,7 +451,6 @@ UsbSelectConfig ( return EFI_SUCCESS; } - /** Disconnect the USB interface with its driver. @@ -456,11 +459,11 @@ UsbSelectConfig ( **/ EFI_STATUS UsbDisconnectDriver ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ) { - EFI_TPL OldTpl; - EFI_STATUS Status; + EFI_TPL OldTpl; + EFI_STATUS Status; // // Release the hub if it's a hub controller, otherwise @@ -469,7 +472,6 @@ UsbDisconnectDriver ( Status = EFI_SUCCESS; if (UsbIf->IsHub) { Status = UsbIf->HubApi->Release (UsbIf); - } else if (UsbIf->IsManaged) { // // This function is called in both UsbIoControlTransfer and @@ -478,7 +480,7 @@ UsbDisconnectDriver ( // twisted TPL used. It should be no problem for us to connect // or disconnect at CALLBACK. // - OldTpl = UsbGetCurrentTpl (); + OldTpl = UsbGetCurrentTpl (); DEBUG ((DEBUG_INFO, "UsbDisconnectDriver: old TPL is %d, %p\n", (UINT32)OldTpl, UsbIf->Handle)); gBS->RestoreTPL (TPL_CALLBACK); @@ -488,7 +490,7 @@ UsbDisconnectDriver ( UsbIf->IsManaged = FALSE; } - DEBUG (( DEBUG_INFO, "UsbDisconnectDriver: TPL after disconnect is %d, %d\n", (UINT32)UsbGetCurrentTpl(), Status)); + DEBUG ((DEBUG_INFO, "UsbDisconnectDriver: TPL after disconnect is %d, %d\n", (UINT32)UsbGetCurrentTpl (), Status)); ASSERT (UsbGetCurrentTpl () == TPL_CALLBACK); gBS->RaiseTPL (OldTpl); @@ -497,7 +499,6 @@ UsbDisconnectDriver ( return Status; } - /** Remove the current device configuration. @@ -506,13 +507,13 @@ UsbDisconnectDriver ( **/ EFI_STATUS UsbRemoveConfig ( - IN USB_DEVICE *Device + IN USB_DEVICE *Device ) { - USB_INTERFACE *UsbIf; - UINTN Index; - EFI_STATUS Status; - EFI_STATUS ReturnStatus; + USB_INTERFACE *UsbIf; + UINTN Index; + EFI_STATUS Status; + EFI_STATUS ReturnStatus; // // Remove each interface of the device @@ -541,11 +542,10 @@ UsbRemoveConfig ( } } - Device->ActiveConfig = NULL; + Device->ActiveConfig = NULL; return ReturnStatus; } - /** Remove the device and all its children from the bus. @@ -556,14 +556,14 @@ UsbRemoveConfig ( **/ EFI_STATUS UsbRemoveDevice ( - IN USB_DEVICE *Device + IN USB_DEVICE *Device ) { - USB_BUS *Bus; - USB_DEVICE *Child; - EFI_STATUS Status; - EFI_STATUS ReturnStatus; - UINTN Index; + USB_BUS *Bus; + USB_DEVICE *Child; + EFI_STATUS Status; + EFI_STATUS ReturnStatus; + UINTN Index; Bus = Device->Bus; @@ -585,7 +585,7 @@ UsbRemoveDevice ( Bus->Devices[Index] = NULL; } else { Bus->Devices[Index]->DisconnectFail = TRUE; - ReturnStatus = Status; + ReturnStatus = Status; DEBUG ((DEBUG_INFO, "UsbRemoveDevice: failed to remove child %p at parent %p\n", Child, Device)); } } @@ -597,7 +597,7 @@ UsbRemoveDevice ( Status = UsbRemoveConfig (Device); if (!EFI_ERROR (Status)) { - DEBUG (( DEBUG_INFO, "UsbRemoveDevice: device %d removed\n", Device->Address)); + DEBUG ((DEBUG_INFO, "UsbRemoveDevice: device %d removed\n", Device->Address)); ASSERT (Device->Address < Bus->MaxDevices); Bus->Devices[Device->Address] = NULL; @@ -605,10 +605,10 @@ UsbRemoveDevice ( } else { Bus->Devices[Device->Address]->DisconnectFail = TRUE; } + return Status; } - /** Find the child device on the hub's port. @@ -620,13 +620,13 @@ UsbRemoveDevice ( **/ USB_DEVICE * UsbFindChild ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ) { - USB_DEVICE *Device; - USB_BUS *Bus; - UINTN Index; + USB_DEVICE *Device; + USB_BUS *Bus; + UINTN Index; Bus = HubIf->Device->Bus; @@ -637,8 +637,8 @@ UsbFindChild ( Device = Bus->Devices[Index]; if ((Device != NULL) && (Device->ParentAddr == HubIf->Device->Address) && - (Device->ParentPort == Port)) { - + (Device->ParentPort == Port)) + { return Device; } } @@ -646,7 +646,6 @@ UsbFindChild ( return NULL; } - /** Enumerate and configure the new device on the port of this HUB interface. @@ -661,19 +660,19 @@ UsbFindChild ( **/ EFI_STATUS UsbEnumerateNewDev ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - IN BOOLEAN ResetIsNeeded + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + IN BOOLEAN ResetIsNeeded ) { - USB_BUS *Bus; - USB_HUB_API *HubApi; - USB_DEVICE *Child; - USB_DEVICE *Parent; - EFI_USB_PORT_STATUS PortState; - UINTN Address; - UINT8 Config; - EFI_STATUS Status; + USB_BUS *Bus; + USB_HUB_API *HubApi; + USB_DEVICE *Child; + USB_DEVICE *Parent; + EFI_USB_PORT_STATUS PortState; + UINTN Address; + UINT8 Config; + EFI_STATUS Status; Parent = HubIf->Device; Bus = Parent->Bus; @@ -695,9 +694,10 @@ UsbEnumerateNewDev ( return Status; } - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: hub port %d is reset\n", Port)); + + DEBUG ((DEBUG_INFO, "UsbEnumerateNewDev: hub port %d is reset\n", Port)); } else { - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: hub port %d reset is skipped\n", Port)); + DEBUG ((DEBUG_INFO, "UsbEnumerateNewDev: hub port %d reset is skipped\n", Port)); } Child = UsbCreateDevice (HubIf, Port); @@ -721,7 +721,7 @@ UsbEnumerateNewDev ( DEBUG ((DEBUG_ERROR, "UsbEnumerateNewDev: No device present at port %d\n", Port)); Status = EFI_NOT_FOUND; goto ON_ERROR; - } else if (USB_BIT_IS_SET (PortState.PortStatus, USB_PORT_STAT_SUPER_SPEED)){ + } else if (USB_BIT_IS_SET (PortState.PortStatus, USB_PORT_STAT_SUPER_SPEED)) { Child->Speed = EFI_USB_SPEED_SUPER; Child->MaxPacket0 = 512; } else if (USB_BIT_IS_SET (PortState.PortStatus, USB_PORT_STAT_HIGH_SPEED)) { @@ -735,10 +735,11 @@ UsbEnumerateNewDev ( Child->MaxPacket0 = 8; } - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: device is of %d speed\n", Child->Speed)); + DEBUG ((DEBUG_INFO, "UsbEnumerateNewDev: device is of %d speed\n", Child->Speed)); if (((Child->Speed == EFI_USB_SPEED_LOW) || (Child->Speed == EFI_USB_SPEED_FULL)) && - (Parent->Speed == EFI_USB_SPEED_HIGH)) { + (Parent->Speed == EFI_USB_SPEED_HIGH)) + { // // If the child is a low or full speed device, it is necessary to // set the transaction translator. Port TT is 1-based. @@ -746,14 +747,18 @@ UsbEnumerateNewDev ( // 1. if parent is of high speed, then parent is our translator // 2. otherwise use parent's translator. // - Child->Translator.TranslatorHubAddress = Parent->Address; - Child->Translator.TranslatorPortNumber = (UINT8) (Port + 1); + Child->Translator.TranslatorHubAddress = Parent->Address; + Child->Translator.TranslatorPortNumber = (UINT8)(Port + 1); } else { Child->Translator = Parent->Translator; } - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: device uses translator (%d, %d)\n", - Child->Translator.TranslatorHubAddress, - Child->Translator.TranslatorPortNumber)); + + DEBUG (( + DEBUG_INFO, + "UsbEnumerateNewDev: device uses translator (%d, %d)\n", + Child->Translator.TranslatorHubAddress, + Child->Translator.TranslatorPortNumber + )); // // After port is reset, hub establishes a signal path between @@ -805,7 +810,7 @@ UsbEnumerateNewDev ( goto ON_ERROR; } - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: max packet size for EP 0 is %d\n", Child->MaxPacket0)); + DEBUG ((DEBUG_INFO, "UsbEnumerateNewDev: max packet size for EP 0 is %d\n", Child->MaxPacket0)); // // Host learns about the device's abilities by requesting device's @@ -830,7 +835,7 @@ UsbEnumerateNewDev ( goto ON_ERROR; } - DEBUG (( DEBUG_INFO, "UsbEnumerateNewDev: device %d is now in CONFIGED state\n", Address)); + DEBUG ((DEBUG_INFO, "UsbEnumerateNewDev: device %d is now in CONFIGED state\n", Address)); // // Host assigns and loads a device driver. @@ -870,7 +875,6 @@ ON_ERROR: return Status; } - /** Process the events on the port. @@ -884,17 +888,17 @@ ON_ERROR: **/ EFI_STATUS UsbEnumeratePort ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ) { - USB_HUB_API *HubApi; - USB_DEVICE *Child; - EFI_USB_PORT_STATUS PortState; - EFI_STATUS Status; + USB_HUB_API *HubApi; + USB_DEVICE *Child; + EFI_USB_PORT_STATUS PortState; + EFI_STATUS Status; - Child = NULL; - HubApi = HubIf->HubApi; + Child = NULL; + HubApi = HubIf->HubApi; // // Host learns of the new device by polling the hub for port changes. @@ -914,8 +918,14 @@ UsbEnumeratePort ( return EFI_SUCCESS; } - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: port %d state - %02x, change - %02x on %p\n", - Port, PortState.PortStatus, PortState.PortChangeStatus, HubIf)); + DEBUG (( + DEBUG_INFO, + "UsbEnumeratePort: port %d state - %02x, change - %02x on %p\n", + Port, + PortState.PortStatus, + PortState.PortChangeStatus, + HubIf + )); // // This driver only process two kinds of events now: over current and @@ -924,7 +934,6 @@ UsbEnumeratePort ( // if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_OVERCURRENT)) { - if (USB_BIT_IS_SET (PortState.PortStatus, USB_PORT_STAT_OVERCURRENT)) { // // Case1: @@ -932,17 +941,17 @@ UsbEnumeratePort ( // which probably is caused by short circuit. It has to wait system hardware // to perform recovery. // - DEBUG (( DEBUG_ERROR, "UsbEnumeratePort: Critical Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: Critical Over Current\n", Port)); return EFI_DEVICE_ERROR; - } + // // Case2: // Only OverCurrentChange set, means system has been recoveried from // over current. As a result, all ports are nearly power-off, so // it's necessary to detach and enumerate all ports again. // - DEBUG (( DEBUG_ERROR, "UsbEnumeratePort: 2.0 device Recovery Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 2.0 device Recovery Over Current\n", Port)); } if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_ENABLE)) { @@ -952,7 +961,7 @@ UsbEnumeratePort ( // on 2.0 roothub does. When over-current has influence on 1.1 device, the port // would be disabled, so it's also necessary to detach and enumerate again. // - DEBUG (( DEBUG_ERROR, "UsbEnumeratePort: 1.1 device Recovery Over Current\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbEnumeratePort: 1.1 device Recovery Over Current\n", Port)); } if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_CONNECTION)) { @@ -969,7 +978,7 @@ UsbEnumeratePort ( Child = UsbFindChild (HubIf, Port); if (Child != NULL) { - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: device at port %d removed from root hub %p\n", Port, HubIf)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: device at port %d removed from root hub %p\n", Port, HubIf)); UsbRemoveDevice (Child); } @@ -977,22 +986,20 @@ UsbEnumeratePort ( // // Now, new device connected, enumerate and configure the device // - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: new device connected at port %d\n", Port)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: new device connected at port %d\n", Port)); if (USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_RESET)) { Status = UsbEnumerateNewDev (HubIf, Port, FALSE); } else { Status = UsbEnumerateNewDev (HubIf, Port, TRUE); } - } else { - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: device disconnected event on port %d\n", Port)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: device disconnected event on port %d\n", Port)); } HubApi->ClearPortChange (HubIf, Port); return Status; } - /** Enumerate all the changed hub ports. @@ -1003,37 +1010,37 @@ UsbEnumeratePort ( VOID EFIAPI UsbHubEnumeration ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_INTERFACE *HubIf; - UINT8 Byte; - UINT8 Bit; - UINT8 Index; - USB_DEVICE *Child; + USB_INTERFACE *HubIf; + UINT8 Byte; + UINT8 Bit; + UINT8 Index; + USB_DEVICE *Child; ASSERT (Context != NULL); - HubIf = (USB_INTERFACE *) Context; + HubIf = (USB_INTERFACE *)Context; for (Index = 0; Index < HubIf->NumOfPort; Index++) { Child = UsbFindChild (HubIf, Index); if ((Child != NULL) && (Child->DisconnectFail == TRUE)) { - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: The device disconnect fails at port %d from hub %p, try again\n", Index, HubIf)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: The device disconnect fails at port %d from hub %p, try again\n", Index, HubIf)); UsbRemoveDevice (Child); } } if (HubIf->ChangeMap == NULL) { - return ; + return; } // // HUB starts its port index with 1. // - Byte = 0; - Bit = 1; + Byte = 0; + Bit = 1; for (Index = 0; Index < HubIf->NumOfPort; Index++) { if (USB_BIT_IS_SET (HubIf->ChangeMap[Byte], USB_BIT (Bit))) { @@ -1047,10 +1054,9 @@ UsbHubEnumeration ( gBS->FreePool (HubIf->ChangeMap); HubIf->ChangeMap = NULL; - return ; + return; } - /** Enumerate all the changed hub ports. @@ -1061,20 +1067,20 @@ UsbHubEnumeration ( VOID EFIAPI UsbRootHubEnumeration ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_INTERFACE *RootHub; - UINT8 Index; - USB_DEVICE *Child; + USB_INTERFACE *RootHub; + UINT8 Index; + USB_DEVICE *Child; - RootHub = (USB_INTERFACE *) Context; + RootHub = (USB_INTERFACE *)Context; for (Index = 0; Index < RootHub->NumOfPort; Index++) { Child = UsbFindChild (RootHub, Index); if ((Child != NULL) && (Child->DisconnectFail == TRUE)) { - DEBUG (( DEBUG_INFO, "UsbEnumeratePort: The device disconnect fails at port %d from root hub %p, try again\n", Index, RootHub)); + DEBUG ((DEBUG_INFO, "UsbEnumeratePort: The device disconnect fails at port %d from root hub %p, try again\n", Index, RootHub)); UsbRemoveDevice (Child); } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.h b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.h index eaba243ed5..51c204be28 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.h +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbEnumer.h @@ -22,7 +22,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent } \ } while (0) - // // Common interface used by usb bus enumeration process. // This interface is defined to mask the difference between @@ -32,7 +31,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef EFI_STATUS (*USB_HUB_INIT) ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ); // @@ -44,45 +43,45 @@ EFI_STATUS typedef EFI_STATUS (*USB_HUB_GET_PORT_STATUS) ( - IN USB_INTERFACE *UsbIf, - IN UINT8 Port, - OUT EFI_USB_PORT_STATUS *PortState + IN USB_INTERFACE *UsbIf, + IN UINT8 Port, + OUT EFI_USB_PORT_STATUS *PortState ); typedef VOID (*USB_HUB_CLEAR_PORT_CHANGE) ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ); typedef EFI_STATUS (*USB_HUB_SET_PORT_FEATURE) ( - IN USB_INTERFACE *UsbIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *UsbIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ); typedef EFI_STATUS (*USB_HUB_CLEAR_PORT_FEATURE) ( - IN USB_INTERFACE *UsbIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *UsbIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ); typedef EFI_STATUS (*USB_HUB_RESET_PORT) ( - IN USB_INTERFACE *UsbIf, - IN UINT8 Port + IN USB_INTERFACE *UsbIf, + IN UINT8 Port ); typedef EFI_STATUS (*USB_HUB_RELEASE) ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ); /** @@ -94,10 +93,10 @@ EFI_STATUS @return The endpoint descriptor or NULL. **/ -USB_ENDPOINT_DESC* +USB_ENDPOINT_DESC * UsbGetEndpointDesc ( - IN USB_INTERFACE *UsbIf, - IN UINT8 EpAddr + IN USB_INTERFACE *UsbIf, + IN UINT8 EpAddr ); /** @@ -115,8 +114,8 @@ UsbGetEndpointDesc ( **/ EFI_STATUS UsbSelectSetting ( - IN USB_INTERFACE_DESC *IfDesc, - IN UINT8 Alternate + IN USB_INTERFACE_DESC *IfDesc, + IN UINT8 Alternate ); /** @@ -133,8 +132,8 @@ UsbSelectSetting ( **/ EFI_STATUS UsbSelectConfig ( - IN USB_DEVICE *Device, - IN UINT8 ConfigIndex + IN USB_DEVICE *Device, + IN UINT8 ConfigIndex ); /** @@ -147,7 +146,7 @@ UsbSelectConfig ( **/ EFI_STATUS UsbRemoveConfig ( - IN USB_DEVICE *Device + IN USB_DEVICE *Device ); /** @@ -160,7 +159,7 @@ UsbRemoveConfig ( **/ EFI_STATUS UsbRemoveDevice ( - IN USB_DEVICE *Device + IN USB_DEVICE *Device ); /** @@ -175,8 +174,8 @@ UsbRemoveDevice ( VOID EFIAPI UsbHubEnumeration ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -191,7 +190,8 @@ UsbHubEnumeration ( VOID EFIAPI UsbRootHubEnumeration ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); + #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c index 022bab5fc1..0497a73f44 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.c @@ -17,19 +17,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // bit maps. // USB_CHANGE_FEATURE_MAP mHubFeatureMap[] = { - {USB_PORT_STAT_C_CONNECTION, EfiUsbPortConnectChange}, - {USB_PORT_STAT_C_ENABLE, EfiUsbPortEnableChange}, - {USB_PORT_STAT_C_SUSPEND, EfiUsbPortSuspendChange}, - {USB_PORT_STAT_C_OVERCURRENT, EfiUsbPortOverCurrentChange}, - {USB_PORT_STAT_C_RESET, EfiUsbPortResetChange} + { USB_PORT_STAT_C_CONNECTION, EfiUsbPortConnectChange }, + { USB_PORT_STAT_C_ENABLE, EfiUsbPortEnableChange }, + { USB_PORT_STAT_C_SUSPEND, EfiUsbPortSuspendChange }, + { USB_PORT_STAT_C_OVERCURRENT, EfiUsbPortOverCurrentChange }, + { USB_PORT_STAT_C_RESET, EfiUsbPortResetChange } }; USB_CHANGE_FEATURE_MAP mRootHubFeatureMap[] = { - {USB_PORT_STAT_C_CONNECTION, EfiUsbPortConnectChange}, - {USB_PORT_STAT_C_ENABLE, EfiUsbPortEnableChange}, - {USB_PORT_STAT_C_SUSPEND, EfiUsbPortSuspendChange}, - {USB_PORT_STAT_C_OVERCURRENT, EfiUsbPortOverCurrentChange}, - {USB_PORT_STAT_C_RESET, EfiUsbPortResetChange}, + { USB_PORT_STAT_C_CONNECTION, EfiUsbPortConnectChange }, + { USB_PORT_STAT_C_ENABLE, EfiUsbPortEnableChange }, + { USB_PORT_STAT_C_SUSPEND, EfiUsbPortSuspendChange }, + { USB_PORT_STAT_C_OVERCURRENT, EfiUsbPortOverCurrentChange }, + { USB_PORT_STAT_C_RESET, EfiUsbPortResetChange }, }; // @@ -37,6 +37,7 @@ USB_CHANGE_FEATURE_MAP mRootHubFeatureMap[] = { // is related to an interface, these requests are sent // to the control endpoint of the device. // + /** USB hub control transfer to set the hub depth. @@ -49,11 +50,11 @@ USB_CHANGE_FEATURE_MAP mRootHubFeatureMap[] = { **/ EFI_STATUS UsbHubCtrlSetHubDepth ( - IN USB_DEVICE *HubDev, - IN UINT16 Depth + IN USB_DEVICE *HubDev, + IN UINT16 Depth ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( HubDev, @@ -82,11 +83,11 @@ UsbHubCtrlSetHubDepth ( **/ EFI_STATUS UsbHubCtrlClearHubFeature ( - IN USB_DEVICE *HubDev, - IN UINT16 Feature + IN USB_DEVICE *HubDev, + IN UINT16 Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( HubDev, @@ -103,7 +104,6 @@ UsbHubCtrlClearHubFeature ( return Status; } - /** Clear the feature of the device's port. @@ -117,12 +117,12 @@ UsbHubCtrlClearHubFeature ( **/ EFI_STATUS UsbHubCtrlClearPortFeature ( - IN USB_DEVICE *HubDev, - IN UINT8 Port, - IN UINT16 Feature + IN USB_DEVICE *HubDev, + IN UINT8 Port, + IN UINT16 Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; // // In USB bus, all the port index starts from 0. But HUB @@ -135,7 +135,7 @@ UsbHubCtrlClearPortFeature ( USB_HUB_TARGET_PORT, USB_HUB_REQ_CLEAR_FEATURE, Feature, - (UINT16) (Port + 1), + (UINT16)(Port + 1), NULL, 0 ); @@ -143,7 +143,6 @@ UsbHubCtrlClearPortFeature ( return Status; } - /** Clear the transaction translate buffer if full/low speed control/bulk transfer failed and the transfer @@ -163,21 +162,21 @@ UsbHubCtrlClearPortFeature ( **/ EFI_STATUS UsbHubCtrlClearTTBuffer ( - IN USB_DEVICE *HubDev, - IN UINT8 Port, - IN UINT16 DevAddr, - IN UINT16 EpNum, - IN UINT16 EpType + IN USB_DEVICE *HubDev, + IN UINT8 Port, + IN UINT16 DevAddr, + IN UINT16 EpNum, + IN UINT16 EpType ) { - EFI_STATUS Status; - UINT16 Value; + EFI_STATUS Status; + UINT16 Value; // // Check USB2.0 spec page 424 for wValue's encoding // - Value = (UINT16) ((EpNum & 0x0F) | (DevAddr << 4) | - ((EpType & 0x03) << 11) | ((EpNum & 0x80) << 15)); + Value = (UINT16)((EpNum & 0x0F) | (DevAddr << 4) | + ((EpType & 0x03) << 11) | ((EpNum & 0x80) << 15)); Status = UsbCtrlRequest ( HubDev, @@ -186,7 +185,7 @@ UsbHubCtrlClearTTBuffer ( USB_HUB_TARGET_PORT, USB_HUB_REQ_CLEAR_TT, Value, - (UINT16) (Port + 1), + (UINT16)(Port + 1), NULL, 0 ); @@ -207,13 +206,13 @@ UsbHubCtrlClearTTBuffer ( **/ EFI_STATUS UsbHubCtrlGetHubDesc ( - IN USB_DEVICE *HubDev, - OUT VOID *Buf, - IN UINTN Len + IN USB_DEVICE *HubDev, + OUT VOID *Buf, + IN UINTN Len ) { - EFI_STATUS Status; - UINT8 DescType; + EFI_STATUS Status; + UINT8 DescType; DescType = (HubDev->Speed == EFI_USB_SPEED_SUPER) ? USB_DESC_TYPE_HUB_SUPER_SPEED : @@ -225,7 +224,7 @@ UsbHubCtrlGetHubDesc ( USB_REQ_TYPE_CLASS, USB_HUB_TARGET_HUB, USB_HUB_REQ_GET_DESC, - (UINT16) (DescType << 8), + (UINT16)(DescType << 8), 0, Buf, Len @@ -234,7 +233,6 @@ UsbHubCtrlGetHubDesc ( return Status; } - /** Usb hub control transfer to get the hub status. @@ -247,11 +245,11 @@ UsbHubCtrlGetHubDesc ( **/ EFI_STATUS UsbHubCtrlGetHubStatus ( - IN USB_DEVICE *HubDev, - OUT UINT32 *State + IN USB_DEVICE *HubDev, + OUT UINT32 *State ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = UsbCtrlRequest ( HubDev, @@ -268,7 +266,6 @@ UsbHubCtrlGetHubStatus ( return Status; } - /** Usb hub control transfer to get the port status. @@ -282,12 +279,12 @@ UsbHubCtrlGetHubStatus ( **/ EFI_STATUS UsbHubCtrlGetPortStatus ( - IN USB_DEVICE *HubDev, - IN UINT8 Port, - OUT VOID *State + IN USB_DEVICE *HubDev, + IN UINT8 Port, + OUT VOID *State ) { - EFI_STATUS Status; + EFI_STATUS Status; // // In USB bus, all the port index starts from 0. But HUB @@ -302,7 +299,7 @@ UsbHubCtrlGetPortStatus ( USB_HUB_TARGET_PORT, USB_HUB_REQ_GET_STATUS, 0, - (UINT16) (Port + 1), + (UINT16)(Port + 1), State, 4 ); @@ -310,7 +307,6 @@ UsbHubCtrlGetPortStatus ( return Status; } - /** Usb hub control transfer to set the port feature. @@ -324,12 +320,12 @@ UsbHubCtrlGetPortStatus ( **/ EFI_STATUS UsbHubCtrlSetPortFeature ( - IN USB_DEVICE *HubDev, - IN UINT8 Port, - IN UINT8 Feature + IN USB_DEVICE *HubDev, + IN UINT8 Port, + IN UINT8 Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; // // In USB bus, all the port index starts from 0. But HUB @@ -342,7 +338,7 @@ UsbHubCtrlSetPortFeature ( USB_HUB_TARGET_PORT, USB_HUB_REQ_SET_FEATURE, Feature, - (UINT16) (Port + 1), + (UINT16)(Port + 1), NULL, 0 ); @@ -350,7 +346,6 @@ UsbHubCtrlSetPortFeature ( return Status; } - /** Read the whole usb hub descriptor. It is necessary to do it in two steps because hub descriptor is of @@ -369,7 +364,7 @@ UsbHubReadDesc ( OUT EFI_USB_HUB_DESCRIPTOR *HubDesc ) { - EFI_STATUS Status; + EFI_STATUS Status; // // First get the hub descriptor length @@ -386,8 +381,6 @@ UsbHubReadDesc ( return UsbHubCtrlGetHubDesc (HubDev, HubDesc, HubDesc->Length); } - - /** Ack the hub change bits. If these bits are not ACKed, Hub will always return changed bit map from its interrupt endpoint. @@ -400,13 +393,13 @@ UsbHubReadDesc ( **/ EFI_STATUS UsbHubAckHubStatus ( - IN USB_DEVICE *HubDev + IN USB_DEVICE *HubDev ) { - EFI_USB_PORT_STATUS HubState; - EFI_STATUS Status; + EFI_USB_PORT_STATUS HubState; + EFI_STATUS Status; - Status = UsbHubCtrlGetHubStatus (HubDev, (UINT32 *) &HubState); + Status = UsbHubCtrlGetHubStatus (HubDev, (UINT32 *)&HubState); if (EFI_ERROR (Status)) { return Status; @@ -423,7 +416,6 @@ UsbHubAckHubStatus ( return EFI_SUCCESS; } - /** Test whether the interface is a hub interface. @@ -435,7 +427,7 @@ UsbHubAckHubStatus ( **/ BOOLEAN UsbIsHubInterface ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ) { EFI_USB_INTERFACE_DESCRIPTOR *Setting; @@ -447,15 +439,14 @@ UsbIsHubInterface ( Setting = &UsbIf->IfSetting->Desc; if ((Setting->InterfaceClass == USB_HUB_CLASS_CODE) && - (Setting->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) { - + (Setting->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) + { return TRUE; } return FALSE; } - /** The callback function to the USB hub status change interrupt endpoint. It is called periodically by @@ -473,20 +464,20 @@ UsbIsHubInterface ( EFI_STATUS EFIAPI UsbOnHubInterrupt ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ) { - USB_INTERFACE *HubIf; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_USB_ENDPOINT_DESCRIPTOR *EpDesc; - EFI_STATUS Status; + USB_INTERFACE *HubIf; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_USB_ENDPOINT_DESCRIPTOR *EpDesc; + EFI_STATUS Status; - HubIf = (USB_INTERFACE *) Context; - UsbIo = &(HubIf->UsbIo); - EpDesc = &(HubIf->HubEp->Desc); + HubIf = (USB_INTERFACE *)Context; + UsbIo = &(HubIf->UsbIo); + EpDesc = &(HubIf->HubEp->Desc); if (Result != EFI_USB_NOERROR) { // @@ -516,7 +507,7 @@ UsbOnHubInterrupt ( ); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbOnHubInterrupt: failed to remove async transfer - %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbOnHubInterrupt: failed to remove async transfer - %r\n", Status)); return Status; } @@ -531,7 +522,7 @@ UsbOnHubInterrupt ( ); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbOnHubInterrupt: failed to submit new async transfer - %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbOnHubInterrupt: failed to submit new async transfer - %r\n", Status)); } return Status; @@ -559,9 +550,6 @@ UsbOnHubInterrupt ( return EFI_SUCCESS; } - - - /** Initialize the device for a non-root hub. @@ -573,7 +561,7 @@ UsbOnHubInterrupt ( **/ EFI_STATUS UsbHubInit ( - IN USB_INTERFACE *HubIf + IN USB_INTERFACE *HubIf ) { UINT8 HubDescBuffer[256]; @@ -590,11 +578,11 @@ UsbHubInit ( // // Locate the interrupt endpoint for port change map // - HubIf->IsHub = FALSE; - Setting = HubIf->IfSetting; - HubDev = HubIf->Device; - EpDesc = NULL; - NumEndpoints = Setting->Desc.NumEndpoints; + HubIf->IsHub = FALSE; + Setting = HubIf->IfSetting; + HubDev = HubIf->Device; + EpDesc = NULL; + NumEndpoints = Setting->Desc.NumEndpoints; for (Index = 0; Index < NumEndpoints; Index++) { ASSERT ((Setting->Endpoints != NULL) && (Setting->Endpoints[Index] != NULL)); @@ -602,13 +590,14 @@ UsbHubInit ( EpDesc = Setting->Endpoints[Index]; if (USB_BIT_IS_SET (EpDesc->Desc.EndpointAddress, USB_ENDPOINT_DIR_IN) && - (USB_ENDPOINT_TYPE (&EpDesc->Desc) == USB_ENDPOINT_INTERRUPT)) { + (USB_ENDPOINT_TYPE (&EpDesc->Desc) == USB_ENDPOINT_INTERRUPT)) + { break; } } if (Index == NumEndpoints) { - DEBUG (( DEBUG_ERROR, "UsbHubInit: no interrupt endpoint found for hub %d\n", HubDev->Address)); + DEBUG ((DEBUG_ERROR, "UsbHubInit: no interrupt endpoint found for hub %d\n", HubDev->Address)); return EFI_DEVICE_ERROR; } @@ -616,17 +605,17 @@ UsbHubInit ( // The length field of descriptor is UINT8 type, so the buffer // with 256 bytes is enough to hold the descriptor data. // - HubDesc = (EFI_USB_HUB_DESCRIPTOR *) HubDescBuffer; - Status = UsbHubReadDesc (HubDev, HubDesc); + HubDesc = (EFI_USB_HUB_DESCRIPTOR *)HubDescBuffer; + Status = UsbHubReadDesc (HubDev, HubDesc); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbHubInit: failed to read HUB descriptor %r\n", Status)); + DEBUG ((DEBUG_ERROR, "UsbHubInit: failed to read HUB descriptor %r\n", Status)); return Status; } HubIf->NumOfPort = HubDesc->NumPorts; - DEBUG (( DEBUG_INFO, "UsbHubInit: hub %d has %d ports\n", HubDev->Address,HubIf->NumOfPort)); + DEBUG ((DEBUG_INFO, "UsbHubInit: hub %d has %d ports\n", HubDev->Address, HubIf->NumOfPort)); // // OK, set IsHub to TRUE. Now usb bus can handle this device @@ -652,7 +641,7 @@ UsbHubInit ( // for both gang/individual powered hubs. // for (Index = 0; Index < HubDesc->NumPorts; Index++) { - UsbHubCtrlSetPortFeature (HubIf->Device, Index, (EFI_USB_PORT_FEATURE) USB_HUB_PORT_POWER); + UsbHubCtrlSetPortFeature (HubIf->Device, Index, (EFI_USB_PORT_FEATURE)USB_HUB_PORT_POWER); } // @@ -661,6 +650,7 @@ UsbHubInit ( if (HubDesc->PwrOn2PwrGood > 0) { gBS->Stall (HubDesc->PwrOn2PwrGood * USB_SET_PORT_POWER_STALL); } + UsbHubAckHubStatus (HubIf->Device); } @@ -676,8 +666,12 @@ UsbHubInit ( ); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbHubInit: failed to create signal for hub %d - %r\n", - HubDev->Address, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbHubInit: failed to create signal for hub %d - %r\n", + HubDev->Address, + Status + )); return Status; } @@ -701,8 +695,12 @@ UsbHubInit ( ); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbHubInit: failed to queue interrupt transfer for hub %d - %r\n", - HubDev->Address, Status)); + DEBUG (( + DEBUG_ERROR, + "UsbHubInit: failed to queue interrupt transfer for hub %d - %r\n", + HubDev->Address, + Status + )); gBS->CloseEvent (HubIf->HubNotify); HubIf->HubNotify = NULL; @@ -710,12 +708,10 @@ UsbHubInit ( return Status; } - DEBUG (( DEBUG_INFO, "UsbHubInit: hub %d initialized\n", HubDev->Address)); + DEBUG ((DEBUG_INFO, "UsbHubInit: hub %d initialized\n", HubDev->Address)); return Status; } - - /** Get the port status. This function is required to ACK the port change bits although it will return @@ -732,20 +728,18 @@ UsbHubInit ( **/ EFI_STATUS UsbHubGetPortStatus ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - OUT EFI_USB_PORT_STATUS *PortState + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + OUT EFI_USB_PORT_STATUS *PortState ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = UsbHubCtrlGetPortStatus (HubIf->Device, Port, PortState); + Status = UsbHubCtrlGetPortStatus (HubIf->Device, Port, PortState); return Status; } - - /** Clear the port change status. @@ -755,8 +749,8 @@ UsbHubGetPortStatus ( **/ VOID UsbHubClearPortChange ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ) { EFI_USB_PORT_STATUS PortState; @@ -780,13 +774,11 @@ UsbHubClearPortChange ( Map = &mHubFeatureMap[Index]; if (USB_BIT_IS_SET (PortState.PortChangeStatus, Map->ChangedBit)) { - UsbHubCtrlClearPortFeature (HubIf->Device, Port, (UINT16) Map->Feature); + UsbHubCtrlClearPortFeature (HubIf->Device, Port, (UINT16)Map->Feature); } } } - - /** Function to set the port feature for non-root hub. @@ -800,19 +792,18 @@ UsbHubClearPortChange ( **/ EFI_STATUS UsbHubSetPortFeature ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = UsbHubCtrlSetPortFeature (HubIf->Device, Port, (UINT8) Feature); + Status = UsbHubCtrlSetPortFeature (HubIf->Device, Port, (UINT8)Feature); return Status; } - /** Interface function to clear the port feature for non-root hub. @@ -826,19 +817,18 @@ UsbHubSetPortFeature ( **/ EFI_STATUS UsbHubClearPortFeature ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = UsbHubCtrlClearPortFeature (HubIf->Device, Port, (UINT8) Feature); + Status = UsbHubCtrlClearPortFeature (HubIf->Device, Port, (UINT8)Feature); return Status; } - /** Interface function to reset the port. @@ -852,15 +842,15 @@ UsbHubClearPortFeature ( **/ EFI_STATUS UsbHubResetPort ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ) { - EFI_USB_PORT_STATUS PortState; - UINTN Index; - EFI_STATUS Status; + EFI_USB_PORT_STATUS PortState; + UINTN Index; + EFI_STATUS Status; - Status = UsbHubSetPortFeature (HubIf, Port, (EFI_USB_PORT_FEATURE) USB_HUB_PORT_RESET); + Status = UsbHubSetPortFeature (HubIf, Port, (EFI_USB_PORT_FEATURE)USB_HUB_PORT_RESET); if (EFI_ERROR (Status)) { return Status; @@ -885,7 +875,8 @@ UsbHubResetPort ( } if (!EFI_ERROR (Status) && - USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_RESET)) { + USB_BIT_IS_SET (PortState.PortChangeStatus, USB_PORT_STAT_C_RESET)) + { gBS->Stall (USB_SET_PORT_RECOVERY_STALL); return EFI_SUCCESS; } @@ -896,7 +887,6 @@ UsbHubResetPort ( return EFI_TIMEOUT; } - /** Release the hub's control of the interface. @@ -907,11 +897,11 @@ UsbHubResetPort ( **/ EFI_STATUS UsbHubRelease ( - IN USB_INTERFACE *HubIf + IN USB_INTERFACE *HubIf ) { - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; UsbIo = &HubIf->UsbIo; Status = UsbIo->UsbAsyncInterruptTransfer ( @@ -930,17 +920,15 @@ UsbHubRelease ( gBS->CloseEvent (HubIf->HubNotify); - HubIf->IsHub = FALSE; - HubIf->HubApi = NULL; - HubIf->HubEp = NULL; - HubIf->HubNotify = NULL; + HubIf->IsHub = FALSE; + HubIf->HubApi = NULL; + HubIf->HubEp = NULL; + HubIf->HubNotify = NULL; - DEBUG (( DEBUG_INFO, "UsbHubRelease: hub device %d released\n", HubIf->Device->Address)); + DEBUG ((DEBUG_INFO, "UsbHubRelease: hub device %d released\n", HubIf->Device->Address)); return EFI_SUCCESS; } - - /** Initialize the interface for root hub. @@ -952,13 +940,13 @@ UsbHubRelease ( **/ EFI_STATUS UsbRootHubInit ( - IN USB_INTERFACE *HubIf + IN USB_INTERFACE *HubIf ) { - EFI_STATUS Status; - UINT8 MaxSpeed; - UINT8 NumOfPort; - UINT8 Support64; + EFI_STATUS Status; + UINT8 MaxSpeed; + UINT8 NumOfPort; + UINT8 Support64; Status = UsbHcGetCapability (HubIf->Device->Bus, &MaxSpeed, &NumOfPort, &Support64); @@ -966,15 +954,20 @@ UsbRootHubInit ( return Status; } - DEBUG (( DEBUG_INFO, "UsbRootHubInit: root hub %p - max speed %d, %d ports\n", - HubIf, MaxSpeed, NumOfPort)); - - HubIf->IsHub = TRUE; - HubIf->HubApi = &mUsbRootHubApi; - HubIf->HubEp = NULL; - HubIf->MaxSpeed = MaxSpeed; - HubIf->NumOfPort = NumOfPort; - HubIf->HubNotify = NULL; + DEBUG (( + DEBUG_INFO, + "UsbRootHubInit: root hub %p - max speed %d, %d ports\n", + HubIf, + MaxSpeed, + NumOfPort + )); + + HubIf->IsHub = TRUE; + HubIf->HubApi = &mUsbRootHubApi; + HubIf->HubEp = NULL; + HubIf->MaxSpeed = MaxSpeed; + HubIf->NumOfPort = NumOfPort; + HubIf->HubNotify = NULL; // // Create a timer to poll root hub ports periodically @@ -1010,7 +1003,6 @@ UsbRootHubInit ( return Status; } - /** Get the port status. This function is required to ACK the port change bits although it will return @@ -1027,21 +1019,20 @@ UsbRootHubInit ( **/ EFI_STATUS UsbRootHubGetPortStatus ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - OUT EFI_USB_PORT_STATUS *PortState + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + OUT EFI_USB_PORT_STATUS *PortState ) { - USB_BUS *Bus; - EFI_STATUS Status; + USB_BUS *Bus; + EFI_STATUS Status; - Bus = HubIf->Device->Bus; - Status = UsbHcGetRootHubPortStatus (Bus, Port, PortState); + Bus = HubIf->Device->Bus; + Status = UsbHcGetRootHubPortStatus (Bus, Port, PortState); return Status; } - /** Clear the port change status. @@ -1051,8 +1042,8 @@ UsbRootHubGetPortStatus ( **/ VOID UsbRootHubClearPortChange ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port + IN USB_INTERFACE *HubIf, + IN UINT8 Port ) { EFI_USB_PORT_STATUS PortState; @@ -1076,12 +1067,11 @@ UsbRootHubClearPortChange ( Map = &mRootHubFeatureMap[Index]; if (USB_BIT_IS_SET (PortState.PortChangeStatus, Map->ChangedBit)) { - UsbHcClearRootHubPortFeature (HubIf->Device->Bus, Port, (EFI_USB_PORT_FEATURE) Map->Feature); + UsbHcClearRootHubPortFeature (HubIf->Device->Bus, Port, (EFI_USB_PORT_FEATURE)Map->Feature); } } } - /** Set the root hub port feature. @@ -1095,19 +1085,18 @@ UsbRootHubClearPortChange ( **/ EFI_STATUS UsbRootHubSetPortFeature ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = UsbHcSetRootHubPortFeature (HubIf->Device->Bus, Port, Feature); + Status = UsbHcSetRootHubPortFeature (HubIf->Device->Bus, Port, Feature); return Status; } - /** Clear the root hub port feature. @@ -1121,19 +1110,18 @@ UsbRootHubSetPortFeature ( **/ EFI_STATUS UsbRootHubClearPortFeature ( - IN USB_INTERFACE *HubIf, - IN UINT8 Port, - IN EFI_USB_PORT_FEATURE Feature + IN USB_INTERFACE *HubIf, + IN UINT8 Port, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = UsbHcClearRootHubPortFeature (HubIf->Device->Bus, Port, Feature); + Status = UsbHcClearRootHubPortFeature (HubIf->Device->Bus, Port, Feature); return Status; } - /** Interface function to reset the root hub port. @@ -1149,26 +1137,26 @@ UsbRootHubClearPortFeature ( **/ EFI_STATUS UsbRootHubResetPort ( - IN USB_INTERFACE *RootIf, - IN UINT8 Port + IN USB_INTERFACE *RootIf, + IN UINT8 Port ) { - USB_BUS *Bus; - EFI_STATUS Status; - EFI_USB_PORT_STATUS PortState; - UINTN Index; + USB_BUS *Bus; + EFI_STATUS Status; + EFI_USB_PORT_STATUS PortState; + UINTN Index; // // Notice: although EHCI requires that ENABLED bit be cleared // when reset the port, we don't need to care that here. It // should be handled in the EHCI driver. // - Bus = RootIf->Device->Bus; + Bus = RootIf->Device->Bus; - Status = UsbHcSetRootHubPortFeature (Bus, Port, EfiUsbPortReset); + Status = UsbHcSetRootHubPortFeature (Bus, Port, EfiUsbPortReset); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbRootHubResetPort: failed to start reset on port %d\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbRootHubResetPort: failed to start reset on port %d\n", Port)); return Status; } @@ -1181,7 +1169,7 @@ UsbRootHubResetPort ( Status = UsbHcClearRootHubPortFeature (Bus, Port, EfiUsbPortReset); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbRootHubResetPort: failed to clear reset on port %d\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbRootHubResetPort: failed to clear reset on port %d\n", Port)); return Status; } @@ -1220,17 +1208,15 @@ UsbRootHubResetPort ( // automatically enable the port, we need to enable it manually. // if (RootIf->MaxSpeed == EFI_USB_SPEED_HIGH) { - DEBUG (( DEBUG_ERROR, "UsbRootHubResetPort: release low/full speed device (%d) to UHCI\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbRootHubResetPort: release low/full speed device (%d) to UHCI\n", Port)); UsbRootHubSetPortFeature (RootIf, Port, EfiUsbPortOwner); return EFI_NOT_FOUND; - } else { - Status = UsbRootHubSetPortFeature (RootIf, Port, EfiUsbPortEnable); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "UsbRootHubResetPort: failed to enable port %d for UHCI\n", Port)); + DEBUG ((DEBUG_ERROR, "UsbRootHubResetPort: failed to enable port %d for UHCI\n", Port)); return Status; } @@ -1241,7 +1227,6 @@ UsbRootHubResetPort ( return EFI_SUCCESS; } - /** Release the root hub's control of the interface. @@ -1253,10 +1238,10 @@ UsbRootHubResetPort ( **/ EFI_STATUS UsbRootHubRelease ( - IN USB_INTERFACE *HubIf + IN USB_INTERFACE *HubIf ) { - DEBUG (( DEBUG_INFO, "UsbRootHubRelease: root hub released for hub %p\n", HubIf)); + DEBUG ((DEBUG_INFO, "UsbRootHubRelease: root hub released for hub %p\n", HubIf)); gBS->SetTimer (HubIf->HubNotify, TimerCancel, USB_ROOTHUB_POLL_INTERVAL); gBS->CloseEvent (HubIf->HubNotify); @@ -1264,7 +1249,7 @@ UsbRootHubRelease ( return EFI_SUCCESS; } -USB_HUB_API mUsbHubApi = { +USB_HUB_API mUsbHubApi = { UsbHubInit, UsbHubGetPortStatus, UsbHubClearPortChange, @@ -1274,7 +1259,7 @@ USB_HUB_API mUsbHubApi = { UsbHubRelease }; -USB_HUB_API mUsbRootHubApi = { +USB_HUB_API mUsbRootHubApi = { UsbRootHubInit, UsbRootHubGetPortStatus, UsbRootHubClearPortChange, diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.h b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.h index 6043b5b2cd..8c8583a697 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.h +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbHub.h @@ -12,33 +12,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define USB_ENDPOINT_ADDR(EpAddr) ((EpAddr) & 0x7F) -#define USB_ENDPOINT_TYPE(Desc) ((Desc)->Attributes & USB_ENDPOINT_TYPE_MASK) +#define USB_ENDPOINT_ADDR(EpAddr) ((EpAddr) & 0x7F) +#define USB_ENDPOINT_TYPE(Desc) ((Desc)->Attributes & USB_ENDPOINT_TYPE_MASK) - -#define USB_DESC_TYPE_HUB 0x29 +#define USB_DESC_TYPE_HUB 0x29 #define USB_DESC_TYPE_HUB_SUPER_SPEED 0x2a // // Hub class control transfer target // -#define USB_HUB_TARGET_HUB 0 -#define USB_HUB_TARGET_PORT 3 +#define USB_HUB_TARGET_HUB 0 +#define USB_HUB_TARGET_PORT 3 // // HUB class specific contrl transfer request type // -#define USB_HUB_REQ_GET_STATUS 0 -#define USB_HUB_REQ_CLEAR_FEATURE 1 -#define USB_HUB_REQ_SET_FEATURE 3 -#define USB_HUB_REQ_GET_DESC 6 -#define USB_HUB_REQ_SET_DESC 7 -#define USB_HUB_REQ_CLEAR_TT 8 -#define USB_HUB_REQ_RESET_TT 9 -#define USB_HUB_REQ_GET_TT_STATE 10 -#define USB_HUB_REQ_STOP_TT 11 +#define USB_HUB_REQ_GET_STATUS 0 +#define USB_HUB_REQ_CLEAR_FEATURE 1 +#define USB_HUB_REQ_SET_FEATURE 3 +#define USB_HUB_REQ_GET_DESC 6 +#define USB_HUB_REQ_SET_DESC 7 +#define USB_HUB_REQ_CLEAR_TT 8 +#define USB_HUB_REQ_RESET_TT 9 +#define USB_HUB_REQ_GET_TT_STATE 10 +#define USB_HUB_REQ_STOP_TT 11 -#define USB_HUB_REQ_SET_DEPTH 12 +#define USB_HUB_REQ_SET_DEPTH 12 // // USB hub class feature selector @@ -51,22 +50,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USB_HUB_PORT_OVER_CURRENT 3 #define USB_HUB_PORT_RESET 4 -#define USB_HUB_PORT_LINK_STATE 5 +#define USB_HUB_PORT_LINK_STATE 5 -#define USB_HUB_PORT_POWER 8 -#define USB_HUB_PORT_LOW_SPEED 9 -#define USB_HUB_C_PORT_CONNECT 16 -#define USB_HUB_C_PORT_ENABLE 17 -#define USB_HUB_C_PORT_SUSPEND 18 -#define USB_HUB_C_PORT_OVER_CURRENT 19 -#define USB_HUB_C_PORT_RESET 20 -#define USB_HUB_PORT_TEST 21 -#define USB_HUB_PORT_INDICATOR 22 +#define USB_HUB_PORT_POWER 8 +#define USB_HUB_PORT_LOW_SPEED 9 +#define USB_HUB_C_PORT_CONNECT 16 +#define USB_HUB_C_PORT_ENABLE 17 +#define USB_HUB_C_PORT_SUSPEND 18 +#define USB_HUB_C_PORT_OVER_CURRENT 19 +#define USB_HUB_C_PORT_RESET 20 +#define USB_HUB_PORT_TEST 21 +#define USB_HUB_PORT_INDICATOR 22 -#define USB_HUB_C_PORT_LINK_STATE 25 -#define USB_HUB_PORT_REMOTE_WAKE_MASK 27 -#define USB_HUB_BH_PORT_RESET 28 -#define USB_HUB_C_BH_PORT_RESET 29 +#define USB_HUB_C_PORT_LINK_STATE 25 +#define USB_HUB_PORT_REMOTE_WAKE_MASK 27 +#define USB_HUB_BH_PORT_RESET 28 +#define USB_HUB_C_BH_PORT_RESET 29 // // Constant value for Port Status & Port Change Status of SuperSpeed port @@ -76,18 +75,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // USB hub power control method. In gang power control // -#define USB_HUB_GANG_POWER_CTRL 0 -#define USB_HUB_PORT_POWER_CTRL 0x01 +#define USB_HUB_GANG_POWER_CTRL 0 +#define USB_HUB_PORT_POWER_CTRL 0x01 // // USB hub status bits // -#define USB_HUB_STAT_LOCAL_POWER 0x01 -#define USB_HUB_STAT_OVER_CURRENT 0x02 -#define USB_HUB_STAT_C_LOCAL_POWER 0x01 -#define USB_HUB_STAT_C_OVER_CURRENT 0x02 +#define USB_HUB_STAT_LOCAL_POWER 0x01 +#define USB_HUB_STAT_OVER_CURRENT 0x02 +#define USB_HUB_STAT_C_LOCAL_POWER 0x01 +#define USB_HUB_STAT_C_OVER_CURRENT 0x02 -#define USB_HUB_CLASS_CODE 0x09 -#define USB_HUB_SUBCLASS_CODE 0x00 +#define USB_HUB_CLASS_CODE 0x09 +#define USB_HUB_SUBCLASS_CODE 0x00 // // Host software return timeout if port status doesn't change @@ -100,24 +99,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Hub descriptor, the last two fields are of variable length. // typedef struct { - UINT8 Length; - UINT8 DescType; - UINT8 NumPorts; - UINT16 HubCharacter; - UINT8 PwrOn2PwrGood; - UINT8 HubContrCurrent; - UINT8 Filler[16]; + UINT8 Length; + UINT8 DescType; + UINT8 NumPorts; + UINT16 HubCharacter; + UINT8 PwrOn2PwrGood; + UINT8 HubContrCurrent; + UINT8 Filler[16]; } EFI_USB_HUB_DESCRIPTOR; #pragma pack() - typedef struct { - UINT16 ChangedBit; - EFI_USB_PORT_FEATURE Feature; + UINT16 ChangedBit; + EFI_USB_PORT_FEATURE Feature; } USB_CHANGE_FEATURE_MAP; - /** Clear the transaction translate buffer if full/low speed control/bulk transfer failed and the transfer @@ -137,14 +134,13 @@ typedef struct { **/ EFI_STATUS UsbHubCtrlClearTTBuffer ( - IN USB_DEVICE *UsbDev, - IN UINT8 Port, - IN UINT16 DevAddr, - IN UINT16 EpNum, - IN UINT16 EpType + IN USB_DEVICE *UsbDev, + IN UINT8 Port, + IN UINT16 DevAddr, + IN UINT16 EpNum, + IN UINT16 EpType ); - /** Test whether the interface is a hub interface. @@ -156,10 +152,9 @@ UsbHubCtrlClearTTBuffer ( **/ BOOLEAN UsbIsHubInterface ( - IN USB_INTERFACE *UsbIf + IN USB_INTERFACE *UsbIf ); - /** Ack the hub change bits. If these bits are not ACKed, Hub will always return changed bit map from its interrupt endpoint. @@ -172,10 +167,9 @@ UsbIsHubInterface ( **/ EFI_STATUS UsbHubAckHubStatus ( - IN USB_DEVICE *UsbDev + IN USB_DEVICE *UsbDev ); -extern USB_HUB_API mUsbHubApi; -extern USB_HUB_API mUsbRootHubApi; +extern USB_HUB_API mUsbHubApi; +extern USB_HUB_API mUsbRootHubApi; #endif - diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.c b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.c index 4441466d80..12d08c0b74 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.c +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.c @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "UsbBus.h" // @@ -15,14 +14,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Use a shor form Usb class Device Path, which could match any usb device, in WantedUsbIoDPList to indicate all Usb devices // are wanted Usb devices // -USB_CLASS_FORMAT_DEVICE_PATH mAllUsbClassDevicePath = { +USB_CLASS_FORMAT_DEVICE_PATH mAllUsbClassDevicePath = { { { MESSAGING_DEVICE_PATH, MSG_USB_CLASS_DP, { - (UINT8) (sizeof (USB_CLASS_DEVICE_PATH)), - (UINT8) ((sizeof (USB_CLASS_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (USB_CLASS_DEVICE_PATH)), + (UINT8)((sizeof (USB_CLASS_DEVICE_PATH)) >> 8) } }, 0xffff, // VendorId @@ -42,7 +41,6 @@ USB_CLASS_FORMAT_DEVICE_PATH mAllUsbClassDevicePath = { } }; - /** Get the capability of the host controller. @@ -57,41 +55,31 @@ USB_CLASS_FORMAT_DEVICE_PATH mAllUsbClassDevicePath = { **/ EFI_STATUS UsbHcGetCapability ( - IN USB_BUS *UsbBus, - OUT UINT8 *MaxSpeed, - OUT UINT8 *NumOfPort, - OUT UINT8 *Is64BitCapable + IN USB_BUS *UsbBus, + OUT UINT8 *MaxSpeed, + OUT UINT8 *NumOfPort, + OUT UINT8 *Is64BitCapable ) { - EFI_STATUS Status; + EFI_STATUS Status; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->GetCapability ( - UsbBus->Usb2Hc, - MaxSpeed, - NumOfPort, - Is64BitCapable - ); - + UsbBus->Usb2Hc, + MaxSpeed, + NumOfPort, + Is64BitCapable + ); } else { Status = UsbBus->UsbHc->GetRootHubPortNumber (UsbBus->UsbHc, NumOfPort); *MaxSpeed = EFI_USB_SPEED_FULL; - *Is64BitCapable = (UINT8) FALSE; + *Is64BitCapable = (UINT8)FALSE; } return Status; } - - - - - - - - - /** Get the root hub port state. @@ -105,12 +93,12 @@ UsbHcGetCapability ( **/ EFI_STATUS UsbHcGetRootHubPortStatus ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - OUT EFI_USB_PORT_STATUS *PortStatus + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + OUT EFI_USB_PORT_STATUS *PortStatus ) { - EFI_STATUS Status; + EFI_STATUS Status; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->GetRootHubPortStatus (UsbBus->Usb2Hc, PortIndex, PortStatus); @@ -121,7 +109,6 @@ UsbHcGetRootHubPortStatus ( return Status; } - /** Set the root hub port feature. @@ -135,13 +122,12 @@ UsbHcGetRootHubPortStatus ( **/ EFI_STATUS UsbHcSetRootHubPortFeature ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - IN EFI_USB_PORT_FEATURE Feature + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; - + EFI_STATUS Status; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->SetRootHubPortFeature (UsbBus->Usb2Hc, PortIndex, Feature); @@ -152,7 +138,6 @@ UsbHcSetRootHubPortFeature ( return Status; } - /** Clear the root hub port feature. @@ -166,12 +151,12 @@ UsbHcSetRootHubPortFeature ( **/ EFI_STATUS UsbHcClearRootHubPortFeature ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - IN EFI_USB_PORT_FEATURE Feature + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + IN EFI_USB_PORT_FEATURE Feature ) { - EFI_STATUS Status; + EFI_STATUS Status; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->ClearRootHubPortFeature (UsbBus->Usb2Hc, PortIndex, Feature); @@ -182,7 +167,6 @@ UsbHcClearRootHubPortFeature ( return Status; } - /** Execute a control transfer to the device. @@ -217,8 +201,8 @@ UsbHcControlTransfer ( OUT UINT32 *UsbResult ) { - EFI_STATUS Status; - BOOLEAN IsSlowDevice; + EFI_STATUS Status; + BOOLEAN IsSlowDevice; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->ControlTransfer ( @@ -234,27 +218,25 @@ UsbHcControlTransfer ( Translator, UsbResult ); - } else { IsSlowDevice = (BOOLEAN)(EFI_USB_SPEED_LOW == DevSpeed); - Status = UsbBus->UsbHc->ControlTransfer ( - UsbBus->UsbHc, - DevAddr, - IsSlowDevice, - (UINT8) MaxPacket, - Request, - Direction, - Data, - DataLength, - TimeOut, - UsbResult - ); + Status = UsbBus->UsbHc->ControlTransfer ( + UsbBus->UsbHc, + DevAddr, + IsSlowDevice, + (UINT8)MaxPacket, + Request, + Direction, + Data, + DataLength, + TimeOut, + UsbResult + ); } return Status; } - /** Execute a bulk transfer to the device's endpoint. @@ -293,7 +275,7 @@ UsbHcBulkTransfer ( OUT UINT32 *UsbResult ) { - EFI_STATUS Status; + EFI_STATUS Status; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->BulkTransfer ( @@ -315,7 +297,7 @@ UsbHcBulkTransfer ( UsbBus->UsbHc, DevAddr, EpAddr, - (UINT8) MaxPacket, + (UINT8)MaxPacket, *Data, DataLength, DataToggle, @@ -327,7 +309,6 @@ UsbHcBulkTransfer ( return Status; } - /** Queue or cancel an asynchronous interrupt transfer. @@ -366,8 +347,8 @@ UsbHcAsyncInterruptTransfer ( IN VOID *Context OPTIONAL ) { - EFI_STATUS Status; - BOOLEAN IsSlowDevice; + EFI_STATUS Status; + BOOLEAN IsSlowDevice; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->AsyncInterruptTransfer ( @@ -392,7 +373,7 @@ UsbHcAsyncInterruptTransfer ( DevAddr, EpAddr, IsSlowDevice, - (UINT8) MaxPacket, + (UINT8)MaxPacket, IsNewTransfer, DataToggle, PollingInterval, @@ -405,7 +386,6 @@ UsbHcAsyncInterruptTransfer ( return Status; } - /** Execute a synchronous interrupt transfer to the target endpoint. @@ -442,8 +422,8 @@ UsbHcSyncInterruptTransfer ( OUT UINT32 *UsbResult ) { - EFI_STATUS Status; - BOOLEAN IsSlowDevice; + EFI_STATUS Status; + BOOLEAN IsSlowDevice; if (UsbBus->Usb2Hc != NULL) { Status = UsbBus->Usb2Hc->SyncInterruptTransfer ( @@ -460,31 +440,24 @@ UsbHcSyncInterruptTransfer ( UsbResult ); } else { - IsSlowDevice = (BOOLEAN) ((EFI_USB_SPEED_LOW == DevSpeed) ? TRUE : FALSE); - Status = UsbBus->UsbHc->SyncInterruptTransfer ( - UsbBus->UsbHc, - DevAddr, - EpAddr, - IsSlowDevice, - (UINT8) MaxPacket, - Data, - DataLength, - DataToggle, - TimeOut, - UsbResult - ); + IsSlowDevice = (BOOLEAN)((EFI_USB_SPEED_LOW == DevSpeed) ? TRUE : FALSE); + Status = UsbBus->UsbHc->SyncInterruptTransfer ( + UsbBus->UsbHc, + DevAddr, + EpAddr, + IsSlowDevice, + (UINT8)MaxPacket, + Data, + DataLength, + DataToggle, + TimeOut, + UsbResult + ); } return Status; } - - - - - - - /** Open the USB host controller protocol BY_CHILD. @@ -496,29 +469,28 @@ UsbHcSyncInterruptTransfer ( **/ EFI_STATUS UsbOpenHostProtoByChild ( - IN USB_BUS *Bus, - IN EFI_HANDLE Child + IN USB_BUS *Bus, + IN EFI_HANDLE Child ) { - EFI_USB_HC_PROTOCOL *UsbHc; - EFI_USB2_HC_PROTOCOL *Usb2Hc; - EFI_STATUS Status; + EFI_USB_HC_PROTOCOL *UsbHc; + EFI_USB2_HC_PROTOCOL *Usb2Hc; + EFI_STATUS Status; if (Bus->Usb2Hc != NULL) { Status = gBS->OpenProtocol ( Bus->HostHandle, &gEfiUsb2HcProtocolGuid, - (VOID **) &Usb2Hc, + (VOID **)&Usb2Hc, mUsbBusDriverBinding.DriverBindingHandle, Child, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER ); - } else { Status = gBS->OpenProtocol ( Bus->HostHandle, &gEfiUsbHcProtocolGuid, - (VOID **) &UsbHc, + (VOID **)&UsbHc, mUsbBusDriverBinding.DriverBindingHandle, Child, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -528,7 +500,6 @@ UsbOpenHostProtoByChild ( return Status; } - /** Close the USB host controller protocol BY_CHILD. @@ -538,8 +509,8 @@ UsbOpenHostProtoByChild ( **/ VOID UsbCloseHostProtoByChild ( - IN USB_BUS *Bus, - IN EFI_HANDLE Child + IN USB_BUS *Bus, + IN EFI_HANDLE Child ) { if (Bus->Usb2Hc != NULL) { @@ -549,7 +520,6 @@ UsbCloseHostProtoByChild ( mUsbBusDriverBinding.DriverBindingHandle, Child ); - } else { gBS->CloseProtocol ( Bus->HostHandle, @@ -560,7 +530,6 @@ UsbCloseHostProtoByChild ( } } - /** return the current TPL, copied from the EDKII glue lib. @@ -574,7 +543,7 @@ UsbGetCurrentTpl ( VOID ) { - EFI_TPL Tpl; + EFI_TPL Tpl; Tpl = gBS->RaiseTPL (TPL_HIGH_LEVEL); gBS->RestoreTPL (Tpl); @@ -593,45 +562,45 @@ UsbGetCurrentTpl ( EFI_DEVICE_PATH_PROTOCOL * EFIAPI GetUsbDPFromFullDP ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathPtr; - EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathBeginPtr; - EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathEndPtr; - UINTN Size; + EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathPtr; + EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathBeginPtr; + EFI_DEVICE_PATH_PROTOCOL *UsbDevicePathEndPtr; + UINTN Size; // // Get the Usb part first Begin node in full device path // UsbDevicePathBeginPtr = DevicePath; - while ( (!IsDevicePathEnd (UsbDevicePathBeginPtr))&& + while ((!IsDevicePathEnd (UsbDevicePathBeginPtr)) && ((UsbDevicePathBeginPtr->Type != MESSAGING_DEVICE_PATH) || - (UsbDevicePathBeginPtr->SubType != MSG_USB_DP && - UsbDevicePathBeginPtr->SubType != MSG_USB_CLASS_DP + ( UsbDevicePathBeginPtr->SubType != MSG_USB_DP && + UsbDevicePathBeginPtr->SubType != MSG_USB_CLASS_DP && UsbDevicePathBeginPtr->SubType != MSG_USB_WWID_DP - ))) { - - UsbDevicePathBeginPtr = NextDevicePathNode(UsbDevicePathBeginPtr); + ))) + { + UsbDevicePathBeginPtr = NextDevicePathNode (UsbDevicePathBeginPtr); } // // Get the Usb part first End node in full device path // UsbDevicePathEndPtr = UsbDevicePathBeginPtr; - while ((!IsDevicePathEnd (UsbDevicePathEndPtr))&& + while ((!IsDevicePathEnd (UsbDevicePathEndPtr)) && (UsbDevicePathEndPtr->Type == MESSAGING_DEVICE_PATH) && - (UsbDevicePathEndPtr->SubType == MSG_USB_DP || - UsbDevicePathEndPtr->SubType == MSG_USB_CLASS_DP - || UsbDevicePathEndPtr->SubType == MSG_USB_WWID_DP - )) { - - UsbDevicePathEndPtr = NextDevicePathNode(UsbDevicePathEndPtr); + ( UsbDevicePathEndPtr->SubType == MSG_USB_DP || + UsbDevicePathEndPtr->SubType == MSG_USB_CLASS_DP + || UsbDevicePathEndPtr->SubType == MSG_USB_WWID_DP + )) + { + UsbDevicePathEndPtr = NextDevicePathNode (UsbDevicePathEndPtr); } Size = GetDevicePathSize (UsbDevicePathBeginPtr); Size -= GetDevicePathSize (UsbDevicePathEndPtr); - if (Size ==0){ + if (Size == 0) { // // The passed in DevicePath does not contain the usb nodes // @@ -647,7 +616,7 @@ GetUsbDPFromFullDP ( // // Append end device path node // - UsbDevicePathEndPtr = (EFI_DEVICE_PATH_PROTOCOL *) ((UINTN) UsbDevicePathPtr + Size); + UsbDevicePathEndPtr = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)UsbDevicePathPtr + Size); SetDevicePathEndNode (UsbDevicePathEndPtr); return UsbDevicePathPtr; } @@ -665,14 +634,14 @@ GetUsbDPFromFullDP ( BOOLEAN EFIAPI SearchUsbDPInList ( - IN EFI_DEVICE_PATH_PROTOCOL *UsbDP, - IN LIST_ENTRY *UsbIoDPList + IN EFI_DEVICE_PATH_PROTOCOL *UsbDP, + IN LIST_ENTRY *UsbIoDPList ) { - LIST_ENTRY *ListIndex; - DEVICE_PATH_LIST_ITEM *ListItem; - BOOLEAN Found; - UINTN UsbDpDevicePathSize; + LIST_ENTRY *ListIndex; + DEVICE_PATH_LIST_ITEM *ListItem; + BOOLEAN Found; + UINTN UsbDpDevicePathSize; // // Check that UsbDP and UsbIoDPList are valid @@ -681,22 +650,23 @@ SearchUsbDPInList ( return FALSE; } - Found = FALSE; + Found = FALSE; ListIndex = UsbIoDPList->ForwardLink; - while (ListIndex != UsbIoDPList){ - ListItem = CR(ListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); + while (ListIndex != UsbIoDPList) { + ListItem = CR (ListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); // // Compare DEVICE_PATH_LIST_ITEM.DevicePath[] // ASSERT (ListItem->DevicePath != NULL); - UsbDpDevicePathSize = GetDevicePathSize (UsbDP); + UsbDpDevicePathSize = GetDevicePathSize (UsbDP); if (UsbDpDevicePathSize == GetDevicePathSize (ListItem->DevicePath)) { if ((CompareMem (UsbDP, ListItem->DevicePath, UsbDpDevicePathSize)) == 0) { Found = TRUE; break; } } + ListIndex = ListIndex->ForwardLink; } @@ -716,11 +686,11 @@ SearchUsbDPInList ( EFI_STATUS EFIAPI AddUsbDPToList ( - IN EFI_DEVICE_PATH_PROTOCOL *UsbDP, - IN LIST_ENTRY *UsbIoDPList + IN EFI_DEVICE_PATH_PROTOCOL *UsbDP, + IN LIST_ENTRY *UsbIoDPList ) { - DEVICE_PATH_LIST_ITEM *ListItem; + DEVICE_PATH_LIST_ITEM *ListItem; // // Check that UsbDP and UsbIoDPList are valid @@ -729,7 +699,7 @@ AddUsbDPToList ( return EFI_INVALID_PARAMETER; } - if (SearchUsbDPInList (UsbDP, UsbIoDPList)){ + if (SearchUsbDPInList (UsbDP, UsbIoDPList)) { return EFI_SUCCESS; } @@ -738,7 +708,7 @@ AddUsbDPToList ( // ListItem = AllocateZeroPool (sizeof (DEVICE_PATH_LIST_ITEM)); ASSERT (ListItem != NULL); - ListItem->Signature = DEVICE_PATH_LIST_ITEM_SIGNATURE; + ListItem->Signature = DEVICE_PATH_LIST_ITEM_SIGNATURE; ListItem->DevicePath = DuplicateDevicePath (UsbDP); InsertTailList (UsbIoDPList, &ListItem->Link); @@ -760,25 +730,25 @@ AddUsbDPToList ( BOOLEAN EFIAPI MatchUsbClass ( - IN USB_CLASS_DEVICE_PATH *UsbClassDevicePathPtr, - IN USB_INTERFACE *UsbIf + IN USB_CLASS_DEVICE_PATH *UsbClassDevicePathPtr, + IN USB_INTERFACE *UsbIf ) { USB_INTERFACE_DESC *IfDesc; EFI_USB_INTERFACE_DESCRIPTOR *ActIfDesc; EFI_USB_DEVICE_DESCRIPTOR *DevDesc; - if ((UsbClassDevicePathPtr->Header.Type != MESSAGING_DEVICE_PATH) || - (UsbClassDevicePathPtr->Header.SubType != MSG_USB_CLASS_DP)){ + (UsbClassDevicePathPtr->Header.SubType != MSG_USB_CLASS_DP)) + { ASSERT (0); return FALSE; } - IfDesc = UsbIf->IfDesc; + IfDesc = UsbIf->IfDesc; ASSERT (IfDesc->ActiveIndex < USB_MAX_INTERFACE_SETTING); - ActIfDesc = &(IfDesc->Settings[IfDesc->ActiveIndex]->Desc); - DevDesc = &(UsbIf->Device->DevDesc->Desc); + ActIfDesc = &(IfDesc->Settings[IfDesc->ActiveIndex]->Desc); + DevDesc = &(UsbIf->Device->DevDesc->Desc); // // If connect class policy, determine whether to create device handle by the five fields @@ -787,36 +757,37 @@ MatchUsbClass ( // In addition, hub interface is always matched for this policy. // if ((ActIfDesc->InterfaceClass == USB_HUB_CLASS_CODE) && - (ActIfDesc->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) { + (ActIfDesc->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) + { return TRUE; } // // If vendor id or product id is 0xffff, they will be ignored. // - if ((UsbClassDevicePathPtr->VendorId == 0xffff || UsbClassDevicePathPtr->VendorId == DevDesc->IdVendor) && - (UsbClassDevicePathPtr->ProductId == 0xffff || UsbClassDevicePathPtr->ProductId == DevDesc->IdProduct)) { - + if (((UsbClassDevicePathPtr->VendorId == 0xffff) || (UsbClassDevicePathPtr->VendorId == DevDesc->IdVendor)) && + ((UsbClassDevicePathPtr->ProductId == 0xffff) || (UsbClassDevicePathPtr->ProductId == DevDesc->IdProduct))) + { // // If Class in Device Descriptor is set to 0, the counterparts in interface should be checked. // if (DevDesc->DeviceClass == 0) { - if ((UsbClassDevicePathPtr->DeviceClass == ActIfDesc->InterfaceClass || - UsbClassDevicePathPtr->DeviceClass == 0xff) && - (UsbClassDevicePathPtr->DeviceSubClass == ActIfDesc->InterfaceSubClass || - UsbClassDevicePathPtr->DeviceSubClass == 0xff) && - (UsbClassDevicePathPtr->DeviceProtocol == ActIfDesc->InterfaceProtocol || - UsbClassDevicePathPtr->DeviceProtocol == 0xff)) { + if (((UsbClassDevicePathPtr->DeviceClass == ActIfDesc->InterfaceClass) || + (UsbClassDevicePathPtr->DeviceClass == 0xff)) && + ((UsbClassDevicePathPtr->DeviceSubClass == ActIfDesc->InterfaceSubClass) || + (UsbClassDevicePathPtr->DeviceSubClass == 0xff)) && + ((UsbClassDevicePathPtr->DeviceProtocol == ActIfDesc->InterfaceProtocol) || + (UsbClassDevicePathPtr->DeviceProtocol == 0xff))) + { return TRUE; } - - } else if ((UsbClassDevicePathPtr->DeviceClass == DevDesc->DeviceClass || - UsbClassDevicePathPtr->DeviceClass == 0xff) && - (UsbClassDevicePathPtr->DeviceSubClass == DevDesc->DeviceSubClass || - UsbClassDevicePathPtr->DeviceSubClass == 0xff) && - (UsbClassDevicePathPtr->DeviceProtocol == DevDesc->DeviceProtocol || - UsbClassDevicePathPtr->DeviceProtocol == 0xff)) { - + } else if (((UsbClassDevicePathPtr->DeviceClass == DevDesc->DeviceClass) || + (UsbClassDevicePathPtr->DeviceClass == 0xff)) && + ((UsbClassDevicePathPtr->DeviceSubClass == DevDesc->DeviceSubClass) || + (UsbClassDevicePathPtr->DeviceSubClass == 0xff)) && + ((UsbClassDevicePathPtr->DeviceProtocol == DevDesc->DeviceProtocol) || + (UsbClassDevicePathPtr->DeviceProtocol == 0xff))) + { return TRUE; } } @@ -837,8 +808,8 @@ MatchUsbClass ( **/ BOOLEAN MatchUsbWwid ( - IN USB_WWID_DEVICE_PATH *UsbWWIDDevicePathPtr, - IN USB_INTERFACE *UsbIf + IN USB_WWID_DEVICE_PATH *UsbWWIDDevicePathPtr, + IN USB_INTERFACE *UsbIf ) { USB_INTERFACE_DESC *IfDesc; @@ -851,21 +822,23 @@ MatchUsbWwid ( UINTN Length; if ((UsbWWIDDevicePathPtr->Header.Type != MESSAGING_DEVICE_PATH) || - (UsbWWIDDevicePathPtr->Header.SubType != MSG_USB_WWID_DP )){ + (UsbWWIDDevicePathPtr->Header.SubType != MSG_USB_WWID_DP)) + { ASSERT (0); return FALSE; } - IfDesc = UsbIf->IfDesc; + IfDesc = UsbIf->IfDesc; ASSERT (IfDesc->ActiveIndex < USB_MAX_INTERFACE_SETTING); - ActIfDesc = &(IfDesc->Settings[IfDesc->ActiveIndex]->Desc); - DevDesc = &(UsbIf->Device->DevDesc->Desc); + ActIfDesc = &(IfDesc->Settings[IfDesc->ActiveIndex]->Desc); + DevDesc = &(UsbIf->Device->DevDesc->Desc); // // In addition, Hub interface is always matched for this policy. // if ((ActIfDesc->InterfaceClass == USB_HUB_CLASS_CODE) && - (ActIfDesc->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) { + (ActIfDesc->InterfaceSubClass == USB_HUB_SUBCLASS_CODE)) + { return TRUE; } @@ -874,7 +847,8 @@ MatchUsbWwid ( // if ((DevDesc->IdVendor != UsbWWIDDevicePathPtr->VendorId) || (DevDesc->IdProduct != UsbWWIDDevicePathPtr->ProductId) || - (ActIfDesc->InterfaceNumber != UsbWWIDDevicePathPtr->InterfaceNumber)) { + (ActIfDesc->InterfaceNumber != UsbWWIDDevicePathPtr->InterfaceNumber)) + { return FALSE; } @@ -888,7 +862,7 @@ MatchUsbWwid ( // // Serial number in USB WWID device path is the last 64-or-less UTF-16 characters. // - CompareStr = (CHAR16 *) (UINTN) (UsbWWIDDevicePathPtr + 1); + CompareStr = (CHAR16 *)(UINTN)(UsbWWIDDevicePathPtr + 1); CompareLen = (DevicePathNodeLength (UsbWWIDDevicePathPtr) - sizeof (USB_WWID_DEVICE_PATH)) / sizeof (CHAR16); if (CompareStr[CompareLen - 1] == L'\0') { CompareLen--; @@ -905,7 +879,8 @@ MatchUsbWwid ( Length = (StrDesc->Length - 2) / sizeof (CHAR16); if ((Length >= CompareLen) && - (CompareMem (StrDesc->String + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) { + (CompareMem (StrDesc->String + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) + { return TRUE; } } @@ -925,11 +900,11 @@ MatchUsbWwid ( EFI_STATUS EFIAPI UsbBusFreeUsbDPList ( - IN LIST_ENTRY *UsbIoDPList + IN LIST_ENTRY *UsbIoDPList ) { - LIST_ENTRY *ListIndex; - DEVICE_PATH_LIST_ITEM *ListItem; + LIST_ENTRY *ListIndex; + DEVICE_PATH_LIST_ITEM *ListItem; // // Check that ControllerHandle is a valid handle @@ -939,14 +914,15 @@ UsbBusFreeUsbDPList ( } ListIndex = UsbIoDPList->ForwardLink; - while (ListIndex != UsbIoDPList){ - ListItem = CR(ListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); + while (ListIndex != UsbIoDPList) { + ListItem = CR (ListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); // // Free DEVICE_PATH_LIST_ITEM.DevicePath[] // - if (ListItem->DevicePath != NULL){ - FreePool(ListItem->DevicePath); + if (ListItem->DevicePath != NULL) { + FreePool (ListItem->DevicePath); } + // // Free DEVICE_PATH_LIST_ITEM itself // @@ -973,28 +949,29 @@ UsbBusFreeUsbDPList ( EFI_STATUS EFIAPI UsbBusAddWantedUsbIoDP ( - IN EFI_USB_BUS_PROTOCOL *UsbBusId, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_USB_BUS_PROTOCOL *UsbBusId, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - USB_BUS *Bus; - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *DevicePathPtr; + USB_BUS *Bus; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *DevicePathPtr; // // Check whether remaining device path is valid // - if (RemainingDevicePath != NULL && !IsDevicePathEnd (RemainingDevicePath)) { + if ((RemainingDevicePath != NULL) && !IsDevicePathEnd (RemainingDevicePath)) { if ((RemainingDevicePath->Type != MESSAGING_DEVICE_PATH) || - (RemainingDevicePath->SubType != MSG_USB_DP && - RemainingDevicePath->SubType != MSG_USB_CLASS_DP - && RemainingDevicePath->SubType != MSG_USB_WWID_DP - )) { + ( (RemainingDevicePath->SubType != MSG_USB_DP) && + (RemainingDevicePath->SubType != MSG_USB_CLASS_DP) + && (RemainingDevicePath->SubType != MSG_USB_WWID_DP) + )) + { return EFI_INVALID_PARAMETER; } } - if (UsbBusId == NULL){ + if (UsbBusId == NULL) { return EFI_INVALID_PARAMETER; } @@ -1008,7 +985,7 @@ UsbBusAddWantedUsbIoDP ( // Status = UsbBusFreeUsbDPList (&Bus->WantedUsbIoDPList); ASSERT (!EFI_ERROR (Status)); - DevicePathPtr = DuplicateDevicePath ((EFI_DEVICE_PATH_PROTOCOL *) &mAllUsbClassDevicePath); + DevicePathPtr = DuplicateDevicePath ((EFI_DEVICE_PATH_PROTOCOL *)&mAllUsbClassDevicePath); } else if (!IsDevicePathEnd (RemainingDevicePath)) { // // If RemainingDevicePath isn't the End of Device Path Node, @@ -1043,16 +1020,16 @@ UsbBusAddWantedUsbIoDP ( BOOLEAN EFIAPI UsbBusIsWantedUsbIO ( - IN USB_BUS *Bus, - IN USB_INTERFACE *UsbIf + IN USB_BUS *Bus, + IN USB_INTERFACE *UsbIf ) { - EFI_DEVICE_PATH_PROTOCOL *DevicePathPtr; - LIST_ENTRY *WantedUsbIoDPListPtr; - LIST_ENTRY *WantedListIndex; - DEVICE_PATH_LIST_ITEM *WantedListItem; - BOOLEAN DoConvert; - UINTN FirstDevicePathSize; + EFI_DEVICE_PATH_PROTOCOL *DevicePathPtr; + LIST_ENTRY *WantedUsbIoDPListPtr; + LIST_ENTRY *WantedListIndex; + DEVICE_PATH_LIST_ITEM *WantedListItem; + BOOLEAN DoConvert; + UINTN FirstDevicePathSize; // // Check whether passed in parameters are valid @@ -1060,6 +1037,7 @@ UsbBusIsWantedUsbIO ( if ((UsbIf == NULL) || (Bus == NULL)) { return FALSE; } + // // Check whether UsbIf is Hub // @@ -1070,7 +1048,7 @@ UsbBusIsWantedUsbIO ( // // Check whether all Usb devices in this bus are wanted // - if (SearchUsbDPInList ((EFI_DEVICE_PATH_PROTOCOL *)&mAllUsbClassDevicePath, &Bus->WantedUsbIoDPList)){ + if (SearchUsbDPInList ((EFI_DEVICE_PATH_PROTOCOL *)&mAllUsbClassDevicePath, &Bus->WantedUsbIoDPList)) { return TRUE; } @@ -1084,37 +1062,42 @@ UsbBusIsWantedUsbIO ( DevicePathPtr = GetUsbDPFromFullDP (UsbIf->DevicePath); ASSERT (DevicePathPtr != NULL); - DoConvert = FALSE; + DoConvert = FALSE; WantedListIndex = WantedUsbIoDPListPtr->ForwardLink; - while (WantedListIndex != WantedUsbIoDPListPtr){ - WantedListItem = CR(WantedListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); + while (WantedListIndex != WantedUsbIoDPListPtr) { + WantedListItem = CR (WantedListIndex, DEVICE_PATH_LIST_ITEM, Link, DEVICE_PATH_LIST_ITEM_SIGNATURE); ASSERT (WantedListItem->DevicePath->Type == MESSAGING_DEVICE_PATH); switch (WantedListItem->DevicePath->SubType) { - case MSG_USB_DP: - FirstDevicePathSize = GetDevicePathSize (WantedListItem->DevicePath); - if (FirstDevicePathSize == GetDevicePathSize (DevicePathPtr)) { - if (CompareMem ( - WantedListItem->DevicePath, - DevicePathPtr, - GetDevicePathSize (DevicePathPtr)) == 0 - ) { + case MSG_USB_DP: + FirstDevicePathSize = GetDevicePathSize (WantedListItem->DevicePath); + if (FirstDevicePathSize == GetDevicePathSize (DevicePathPtr)) { + if (CompareMem ( + WantedListItem->DevicePath, + DevicePathPtr, + GetDevicePathSize (DevicePathPtr) + ) == 0 + ) + { + DoConvert = TRUE; + } + } + + break; + case MSG_USB_CLASS_DP: + if (MatchUsbClass ((USB_CLASS_DEVICE_PATH *)WantedListItem->DevicePath, UsbIf)) { DoConvert = TRUE; } - } - break; - case MSG_USB_CLASS_DP: - if (MatchUsbClass((USB_CLASS_DEVICE_PATH *)WantedListItem->DevicePath, UsbIf)) { - DoConvert = TRUE; - } - break; - case MSG_USB_WWID_DP: - if (MatchUsbWwid((USB_WWID_DEVICE_PATH *)WantedListItem->DevicePath, UsbIf)) { - DoConvert = TRUE; - } - break; - default: - ASSERT (0); - break; + + break; + case MSG_USB_WWID_DP: + if (MatchUsbWwid ((USB_WWID_DEVICE_PATH *)WantedListItem->DevicePath, UsbIf)) { + DoConvert = TRUE; + } + + break; + default: + ASSERT (0); + break; } if (DoConvert) { @@ -1123,12 +1106,13 @@ UsbBusIsWantedUsbIO ( WantedListIndex = WantedListIndex->ForwardLink; } + gBS->FreePool (DevicePathPtr); // // Check whether the new Usb device path is wanted // - if (DoConvert){ + if (DoConvert) { return TRUE; } else { return FALSE; @@ -1148,19 +1132,19 @@ UsbBusIsWantedUsbIO ( EFI_STATUS EFIAPI UsbBusRecursivelyConnectWantedUsbIo ( - IN EFI_USB_BUS_PROTOCOL *UsbBusId + IN EFI_USB_BUS_PROTOCOL *UsbBusId ) { - USB_BUS *Bus; - EFI_STATUS Status; - UINTN Index; - EFI_USB_IO_PROTOCOL *UsbIo; - USB_INTERFACE *UsbIf; - UINTN UsbIoHandleCount; - EFI_HANDLE *UsbIoBuffer; - EFI_DEVICE_PATH_PROTOCOL *UsbIoDevicePath; - - if (UsbBusId == NULL){ + USB_BUS *Bus; + EFI_STATUS Status; + UINTN Index; + EFI_USB_IO_PROTOCOL *UsbIo; + USB_INTERFACE *UsbIf; + UINTN UsbIoHandleCount; + EFI_HANDLE *UsbIoBuffer; + EFI_DEVICE_PATH_PROTOCOL *UsbIoDevicePath; + + if (UsbBusId == NULL) { return EFI_INVALID_PARAMETER; } @@ -1170,10 +1154,11 @@ UsbBusRecursivelyConnectWantedUsbIo ( // Get all Usb IO handles in system // UsbIoHandleCount = 0; - Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiUsbIoProtocolGuid, NULL, &UsbIoHandleCount, &UsbIoBuffer); - if (Status == EFI_NOT_FOUND || UsbIoHandleCount == 0) { + Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiUsbIoProtocolGuid, NULL, &UsbIoHandleCount, &UsbIoBuffer); + if ((Status == EFI_NOT_FOUND) || (UsbIoHandleCount == 0)) { return EFI_SUCCESS; } + ASSERT (!EFI_ERROR (Status)); for (Index = 0; Index < UsbIoHandleCount; Index++) { @@ -1182,30 +1167,33 @@ UsbBusRecursivelyConnectWantedUsbIo ( // Note: The usb child handle maybe invalid because of hot plugged out during the loop // UsbIoDevicePath = NULL; - Status = gBS->HandleProtocol (UsbIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *) &UsbIoDevicePath); - if (EFI_ERROR (Status) || UsbIoDevicePath == NULL) { + Status = gBS->HandleProtocol (UsbIoBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID *)&UsbIoDevicePath); + if (EFI_ERROR (Status) || (UsbIoDevicePath == NULL)) { continue; } + if (CompareMem ( - UsbIoDevicePath, - Bus->DevicePath, - (GetDevicePathSize (Bus->DevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL)) - ) != 0) { + UsbIoDevicePath, + Bus->DevicePath, + (GetDevicePathSize (Bus->DevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL)) + ) != 0) + { continue; } // // Get the child Usb IO interface // - Status = gBS->HandleProtocol( - UsbIoBuffer[Index], - &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo - ); + Status = gBS->HandleProtocol ( + UsbIoBuffer[Index], + &gEfiUsbIoProtocolGuid, + (VOID **)&UsbIo + ); if (EFI_ERROR (Status)) { continue; } - UsbIf = USB_INTERFACE_FROM_USBIO (UsbIo); + + UsbIf = USB_INTERFACE_FROM_USBIO (UsbIo); if (UsbBusIsWantedUsbIO (Bus, UsbIf)) { if (!UsbIf->IsManaged) { @@ -1213,9 +1201,9 @@ UsbBusRecursivelyConnectWantedUsbIo ( // Recursively connect the wanted Usb Io handle // DEBUG ((DEBUG_INFO, "UsbBusRecursivelyConnectWantedUsbIo: TPL before connect is %d\n", (UINT32)UsbGetCurrentTpl ())); - Status = gBS->ConnectController (UsbIf->Handle, NULL, NULL, TRUE); - UsbIf->IsManaged = (BOOLEAN)!EFI_ERROR (Status); - DEBUG ((DEBUG_INFO, "UsbBusRecursivelyConnectWantedUsbIo: TPL after connect is %d\n", (UINT32)UsbGetCurrentTpl())); + Status = gBS->ConnectController (UsbIf->Handle, NULL, NULL, TRUE); + UsbIf->IsManaged = (BOOLEAN) !EFI_ERROR (Status); + DEBUG ((DEBUG_INFO, "UsbBusRecursivelyConnectWantedUsbIo: TPL after connect is %d\n", (UINT32)UsbGetCurrentTpl ())); } } } diff --git a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.h b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.h index 1d2b8a6174..04cf36d3c8 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.h +++ b/MdeModulePkg/Bus/Usb/UsbBusDxe/UsbUtility.h @@ -24,13 +24,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS UsbHcGetCapability ( - IN USB_BUS *UsbBus, - OUT UINT8 *MaxSpeed, - OUT UINT8 *NumOfPort, - OUT UINT8 *Is64BitCapable + IN USB_BUS *UsbBus, + OUT UINT8 *MaxSpeed, + OUT UINT8 *NumOfPort, + OUT UINT8 *Is64BitCapable ); - /** Get the root hub port state. @@ -44,9 +43,9 @@ UsbHcGetCapability ( **/ EFI_STATUS UsbHcGetRootHubPortStatus ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - OUT EFI_USB_PORT_STATUS *PortStatus + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + OUT EFI_USB_PORT_STATUS *PortStatus ); /** @@ -62,9 +61,9 @@ UsbHcGetRootHubPortStatus ( **/ EFI_STATUS UsbHcSetRootHubPortFeature ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - IN EFI_USB_PORT_FEATURE Feature + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + IN EFI_USB_PORT_FEATURE Feature ); /** @@ -80,9 +79,9 @@ UsbHcSetRootHubPortFeature ( **/ EFI_STATUS UsbHcClearRootHubPortFeature ( - IN USB_BUS *UsbBus, - IN UINT8 PortIndex, - IN EFI_USB_PORT_FEATURE Feature + IN USB_BUS *UsbBus, + IN UINT8 PortIndex, + IN EFI_USB_PORT_FEATURE Feature ); /** @@ -231,7 +230,6 @@ UsbHcSyncInterruptTransfer ( OUT UINT32 *UsbResult ); - /** Open the USB host controller protocol BY_CHILD. @@ -243,8 +241,8 @@ UsbHcSyncInterruptTransfer ( **/ EFI_STATUS UsbOpenHostProtoByChild ( - IN USB_BUS *Bus, - IN EFI_HANDLE Child + IN USB_BUS *Bus, + IN EFI_HANDLE Child ); /** @@ -258,8 +256,8 @@ UsbOpenHostProtoByChild ( **/ VOID UsbCloseHostProtoByChild ( - IN USB_BUS *Bus, - IN EFI_HANDLE Child + IN USB_BUS *Bus, + IN EFI_HANDLE Child ); /** diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.c b/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.c index ce6db0b048..df38227eed 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.c +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.c @@ -26,10 +26,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PeiHubGetPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - OUT UINT32 *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + OUT UINT32 *PortStatus ) { EFI_USB_DEVICE_REQUEST DeviceRequest; @@ -42,8 +42,7 @@ PeiHubGetPortStatus ( DeviceRequest.RequestType = USB_HUB_GET_PORT_STATUS_REQ_TYPE; DeviceRequest.Request = USB_HUB_GET_PORT_STATUS; DeviceRequest.Index = Port; - DeviceRequest.Length = (UINT16) sizeof (UINT32); - + DeviceRequest.Length = (UINT16)sizeof (UINT32); return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -54,7 +53,6 @@ PeiHubGetPortStatus ( PortStatus, sizeof (UINT32) ); - } /** @@ -72,13 +70,13 @@ PeiHubGetPortStatus ( **/ EFI_STATUS PeiHubSetPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + IN UINT8 Value ) { - EFI_USB_DEVICE_REQUEST DeviceRequest; + EFI_USB_DEVICE_REQUEST DeviceRequest; ZeroMem (&DeviceRequest, sizeof (EFI_USB_DEVICE_REQUEST)); @@ -116,13 +114,13 @@ PeiHubSetPortFeature ( **/ EFI_STATUS PeiHubClearPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + IN UINT8 Value ) { - EFI_USB_DEVICE_REQUEST DeviceRequest; + EFI_USB_DEVICE_REQUEST DeviceRequest; ZeroMem (&DeviceRequest, sizeof (EFI_USB_DEVICE_REQUEST)); @@ -159,9 +157,9 @@ PeiHubClearPortFeature ( **/ EFI_STATUS PeiHubGetHubStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - OUT UINT32 *HubStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + OUT UINT32 *HubStatus ) { EFI_USB_DEVICE_REQUEST DeviceRequest; @@ -173,7 +171,7 @@ PeiHubGetHubStatus ( // DeviceRequest.RequestType = USB_HUB_GET_HUB_STATUS_REQ_TYPE; DeviceRequest.Request = USB_HUB_GET_HUB_STATUS; - DeviceRequest.Length = (UINT16) sizeof (UINT32); + DeviceRequest.Length = (UINT16)sizeof (UINT32); return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -186,8 +184,6 @@ PeiHubGetHubStatus ( ); } - - /** Clear specified feature on a given hub. @@ -202,12 +198,12 @@ PeiHubGetHubStatus ( **/ EFI_STATUS PeiHubClearHubFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Value ) { - EFI_USB_DEVICE_REQUEST DeviceRequest; + EFI_USB_DEVICE_REQUEST DeviceRequest; ZeroMem (&DeviceRequest, sizeof (EFI_USB_DEVICE_REQUEST)); @@ -218,15 +214,15 @@ PeiHubClearHubFeature ( DeviceRequest.Request = USB_HUB_CLEAR_FEATURE; DeviceRequest.Value = Value; - return UsbIoPpi->UsbControlTransfer ( - PeiServices, - UsbIoPpi, - &DeviceRequest, - EfiUsbNoData, - PcdGet32 (PcdUsbTransferTimeoutValue), - NULL, - 0 - ); + return UsbIoPpi->UsbControlTransfer ( + PeiServices, + UsbIoPpi, + &DeviceRequest, + EfiUsbNoData, + PcdGet32 (PcdUsbTransferTimeoutValue), + NULL, + 0 + ); } /** @@ -246,15 +242,15 @@ PeiHubClearHubFeature ( **/ EFI_STATUS PeiGetHubDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINTN DescriptorSize, - OUT EFI_USB_HUB_DESCRIPTOR *HubDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINTN DescriptorSize, + OUT EFI_USB_HUB_DESCRIPTOR *HubDescriptor ) { - EFI_USB_DEVICE_REQUEST DevReq; - UINT8 DescType; + EFI_USB_DEVICE_REQUEST DevReq; + UINT8 DescType; ZeroMem (&DevReq, sizeof (EFI_USB_DEVICE_REQUEST)); @@ -267,18 +263,18 @@ PeiGetHubDescriptor ( // DevReq.RequestType = USB_RT_HUB | 0x80; DevReq.Request = USB_HUB_GET_DESCRIPTOR; - DevReq.Value = (UINT16) (DescType << 8); - DevReq.Length = (UINT16) DescriptorSize; - - return UsbIoPpi->UsbControlTransfer ( - PeiServices, - UsbIoPpi, - &DevReq, - EfiUsbDataIn, - PcdGet32 (PcdUsbTransferTimeoutValue), - HubDescriptor, - (UINT16)DescriptorSize - ); + DevReq.Value = (UINT16)(DescType << 8); + DevReq.Length = (UINT16)DescriptorSize; + + return UsbIoPpi->UsbControlTransfer ( + PeiServices, + UsbIoPpi, + &DevReq, + EfiUsbDataIn, + PcdGet32 (PcdUsbTransferTimeoutValue), + HubDescriptor, + (UINT16)DescriptorSize + ); } /** @@ -299,13 +295,13 @@ PeiGetHubDescriptor ( **/ EFI_STATUS PeiUsbHubReadDesc ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN PEI_USB_IO_PPI *UsbIoPpi, - OUT EFI_USB_HUB_DESCRIPTOR *HubDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN PEI_USB_IO_PPI *UsbIoPpi, + OUT EFI_USB_HUB_DESCRIPTOR *HubDescriptor ) { - EFI_STATUS Status; + EFI_STATUS Status; // // First get the hub descriptor length @@ -335,12 +331,13 @@ PeiUsbHubReadDesc ( **/ EFI_STATUS PeiUsbHubCtrlSetHubDepth ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN PEI_USB_IO_PPI *UsbIoPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN PEI_USB_IO_PPI *UsbIoPpi ) { - EFI_USB_DEVICE_REQUEST DevReq; + EFI_USB_DEVICE_REQUEST DevReq; + ZeroMem (&DevReq, sizeof (EFI_USB_DEVICE_REQUEST)); // @@ -351,15 +348,15 @@ PeiUsbHubCtrlSetHubDepth ( DevReq.Value = PeiUsbDevice->Tier; DevReq.Length = 0; - return UsbIoPpi->UsbControlTransfer ( - PeiServices, - UsbIoPpi, - &DevReq, - EfiUsbNoData, - PcdGet32 (PcdUsbTransferTimeoutValue), - NULL, - 0 - ); + return UsbIoPpi->UsbControlTransfer ( + PeiServices, + UsbIoPpi, + &DevReq, + EfiUsbNoData, + PcdGet32 (PcdUsbTransferTimeoutValue), + NULL, + 0 + ); } /** @@ -374,8 +371,8 @@ PeiUsbHubCtrlSetHubDepth ( **/ EFI_STATUS PeiDoHubConfig ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice ) { UINT8 HubDescBuffer[256]; @@ -391,17 +388,17 @@ PeiDoHubConfig ( // The length field of descriptor is UINT8 type, so the buffer // with 256 bytes is enough to hold the descriptor data. // - HubDescriptor = (EFI_USB_HUB_DESCRIPTOR *) HubDescBuffer; + HubDescriptor = (EFI_USB_HUB_DESCRIPTOR *)HubDescBuffer; // // Get the hub descriptor // Status = PeiUsbHubReadDesc ( - PeiServices, - PeiUsbDevice, - UsbIoPpi, - HubDescriptor - ); + PeiServices, + PeiUsbDevice, + UsbIoPpi, + HubDescriptor + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } @@ -421,18 +418,18 @@ PeiDoHubConfig ( // for (Index = 0; Index < PeiUsbDevice->DownStreamPortNo; Index++) { Status = PeiHubSetPortFeature ( - PeiServices, - UsbIoPpi, - (UINT8) (Index + 1), - EfiUsbPortPower - ); + PeiServices, + UsbIoPpi, + (UINT8)(Index + 1), + EfiUsbPortPower + ); if (EFI_ERROR (Status)) { - DEBUG (( DEBUG_ERROR, "PeiDoHubConfig: PeiHubSetPortFeature EfiUsbPortPower failed %x\n", Index)); + DEBUG ((DEBUG_ERROR, "PeiDoHubConfig: PeiHubSetPortFeature EfiUsbPortPower failed %x\n", Index)); continue; } } - DEBUG (( DEBUG_INFO, "PeiDoHubConfig: HubDescriptor.PwrOn2PwrGood: 0x%x\n", HubDescriptor->PwrOn2PwrGood)); + DEBUG ((DEBUG_INFO, "PeiDoHubConfig: HubDescriptor.PwrOn2PwrGood: 0x%x\n", HubDescriptor->PwrOn2PwrGood)); if (HubDescriptor->PwrOn2PwrGood > 0) { MicroSecondDelay (HubDescriptor->PwrOn2PwrGood * USB_SET_PORT_POWER_STALL); } @@ -441,10 +438,10 @@ PeiDoHubConfig ( // Clear Hub Status Change // Status = PeiHubGetHubStatus ( - PeiServices, - UsbIoPpi, - (UINT32 *) &HubStatus - ); + PeiServices, + UsbIoPpi, + (UINT32 *)&HubStatus + ); if (EFI_ERROR (Status)) { return EFI_DEVICE_ERROR; } else { @@ -458,6 +455,7 @@ PeiDoHubConfig ( C_HUB_LOCAL_POWER ); } + // // Hub change overcurrent happens // @@ -484,14 +482,14 @@ PeiDoHubConfig ( **/ VOID PeiResetHubPort ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 PortNum + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 PortNum ) { - EFI_STATUS Status; - UINTN Index; - EFI_USB_PORT_STATUS HubPortStatus; + EFI_STATUS Status; + UINTN Index; + EFI_USB_PORT_STATUS HubPortStatus; MicroSecondDelay (100 * 1000); @@ -521,7 +519,7 @@ PeiResetHubPort ( PeiServices, UsbIoPpi, PortNum, - (UINT32 *) &HubPortStatus + (UINT32 *)&HubPortStatus ); if (EFI_ERROR (Status)) { diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.h b/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.h index 2a6d911a06..abf5ba7142 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.h +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/HubPeim.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_HUB_PEIM_H_ #define _PEI_HUB_PEIM_H_ - // // Hub feature numbers // @@ -35,45 +34,45 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Hub Characteristics // -#define HUB_CHAR_LPSM 0x0003 -#define HUB_CHAR_COMPOUND 0x0004 -#define HUB_CHAR_OCPM 0x0018 +#define HUB_CHAR_LPSM 0x0003 +#define HUB_CHAR_COMPOUND 0x0004 +#define HUB_CHAR_OCPM 0x0018 // // Standard hub request and request type // By [Spec-USB20/Chapter-11.24] // -#define USB_HUB_CLEAR_FEATURE 0x01 -#define USB_HUB_CLEAR_FEATURE_REQ_TYPE 0x20 +#define USB_HUB_CLEAR_FEATURE 0x01 +#define USB_HUB_CLEAR_FEATURE_REQ_TYPE 0x20 -#define USB_HUB_CLEAR_FEATURE_PORT 0x01 -#define USB_HUB_CLEAR_FEATURE_PORT_REQ_TYPE 0x23 +#define USB_HUB_CLEAR_FEATURE_PORT 0x01 +#define USB_HUB_CLEAR_FEATURE_PORT_REQ_TYPE 0x23 -#define USB_HUB_GET_BUS_STATE 0x02 -#define USB_HUB_GET_BUS_STATE_REQ_TYPE 0xA3 +#define USB_HUB_GET_BUS_STATE 0x02 +#define USB_HUB_GET_BUS_STATE_REQ_TYPE 0xA3 -#define USB_HUB_GET_DESCRIPTOR 0x06 -#define USB_HUB_GET_DESCRIPTOR_REQ_TYPE 0xA0 +#define USB_HUB_GET_DESCRIPTOR 0x06 +#define USB_HUB_GET_DESCRIPTOR_REQ_TYPE 0xA0 -#define USB_HUB_GET_HUB_STATUS 0x00 -#define USB_HUB_GET_HUB_STATUS_REQ_TYPE 0xA0 +#define USB_HUB_GET_HUB_STATUS 0x00 +#define USB_HUB_GET_HUB_STATUS_REQ_TYPE 0xA0 -#define USB_HUB_GET_PORT_STATUS 0x00 -#define USB_HUB_GET_PORT_STATUS_REQ_TYPE 0xA3 +#define USB_HUB_GET_PORT_STATUS 0x00 +#define USB_HUB_GET_PORT_STATUS_REQ_TYPE 0xA3 -#define USB_HUB_SET_DESCRIPTOR 0x07 -#define USB_HUB_SET_DESCRIPTOR_REQ_TYPE 0x20 +#define USB_HUB_SET_DESCRIPTOR 0x07 +#define USB_HUB_SET_DESCRIPTOR_REQ_TYPE 0x20 -#define USB_HUB_SET_HUB_FEATURE 0x03 -#define USB_HUB_SET_HUB_FEATURE_REQ_TYPE 0x20 +#define USB_HUB_SET_HUB_FEATURE 0x03 +#define USB_HUB_SET_HUB_FEATURE_REQ_TYPE 0x20 -#define USB_HUB_SET_PORT_FEATURE 0x03 -#define USB_HUB_SET_PORT_FEATURE_REQ_TYPE 0x23 +#define USB_HUB_SET_PORT_FEATURE 0x03 +#define USB_HUB_SET_PORT_FEATURE_REQ_TYPE 0x23 -#define USB_RT_HUB (USB_TYPE_CLASS | USB_RECIP_DEVICE) -#define USB_RT_PORT (USB_TYPE_CLASS | USB_RECIP_OTHER) +#define USB_RT_HUB (USB_TYPE_CLASS | USB_RECIP_DEVICE) +#define USB_RT_PORT (USB_TYPE_CLASS | USB_RECIP_OTHER) -#define USB_HUB_REQ_SET_DEPTH 12 +#define USB_HUB_REQ_SET_DEPTH 12 #define MAXBYTES 8 #pragma pack(1) @@ -81,21 +80,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Hub descriptor, the last two fields are of variable length. // typedef struct { - UINT8 Length; - UINT8 DescriptorType; - UINT8 NbrPorts; - UINT8 HubCharacteristics[2]; - UINT8 PwrOn2PwrGood; - UINT8 HubContrCurrent; - UINT8 Filler[MAXBYTES]; + UINT8 Length; + UINT8 DescriptorType; + UINT8 NbrPorts; + UINT8 HubCharacteristics[2]; + UINT8 PwrOn2PwrGood; + UINT8 HubContrCurrent; + UINT8 Filler[MAXBYTES]; } EFI_USB_HUB_DESCRIPTOR; typedef struct { - UINT16 HubStatus; - UINT16 HubChangeStatus; + UINT16 HubStatus; + UINT16 HubChangeStatus; } EFI_USB_HUB_STATUS; #pragma pack() + /** Get a given hub port status. @@ -111,10 +111,10 @@ typedef struct { **/ EFI_STATUS PeiHubGetPortStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - OUT UINT32 *PortStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + OUT UINT32 *PortStatus ); /** @@ -132,13 +132,12 @@ PeiHubGetPortStatus ( **/ EFI_STATUS PeiHubSetPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + IN UINT8 Value ); - /** Get a given hub status. @@ -153,9 +152,9 @@ PeiHubSetPortFeature ( **/ EFI_STATUS PeiHubGetHubStatus ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - OUT UINT32 *HubStatus + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + OUT UINT32 *HubStatus ); /** @@ -173,10 +172,10 @@ PeiHubGetHubStatus ( **/ EFI_STATUS PeiHubClearPortFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Port, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Port, + IN UINT8 Value ); /** @@ -193,9 +192,9 @@ PeiHubClearPortFeature ( **/ EFI_STATUS PeiHubClearHubFeature ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 Value + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 Value ); /** @@ -234,8 +233,8 @@ PeiGetHubDescriptor ( **/ EFI_STATUS PeiDoHubConfig ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice ); /** @@ -248,11 +247,9 @@ PeiDoHubConfig ( **/ VOID PeiResetHubPort ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT8 PortNum + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT8 PortNum ); #endif - - diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.c b/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.c index 1385b0ab59..8cb205e58a 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.c +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.c @@ -28,23 +28,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS PeiUsbGetDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT16 Value, - IN UINT16 Index, - IN UINT16 DescriptorLength, - OUT VOID *Descriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT16 Value, + IN UINT16 Index, + IN UINT16 DescriptorLength, + OUT VOID *Descriptor ) { EFI_USB_DEVICE_REQUEST DevReq; ASSERT (UsbIoPpi != NULL); - DevReq.RequestType = USB_DEV_GET_DESCRIPTOR_REQ_TYPE; - DevReq.Request = USB_DEV_GET_DESCRIPTOR; - DevReq.Value = Value; - DevReq.Index = Index; - DevReq.Length = DescriptorLength; + DevReq.RequestType = USB_DEV_GET_DESCRIPTOR_REQ_TYPE; + DevReq.Request = USB_DEV_GET_DESCRIPTOR; + DevReq.Value = Value; + DevReq.Index = Index; + DevReq.Length = DescriptorLength; return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -71,20 +71,20 @@ PeiUsbGetDescriptor ( **/ EFI_STATUS PeiUsbSetDeviceAddress ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT16 AddressValue + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT16 AddressValue ) { EFI_USB_DEVICE_REQUEST DevReq; ASSERT (UsbIoPpi != NULL); - DevReq.RequestType = USB_DEV_SET_ADDRESS_REQ_TYPE; - DevReq.Request = USB_DEV_SET_ADDRESS; - DevReq.Value = AddressValue; - DevReq.Index = 0; - DevReq.Length = 0; + DevReq.RequestType = USB_DEV_SET_ADDRESS_REQ_TYPE; + DevReq.Request = USB_DEV_SET_ADDRESS; + DevReq.Value = AddressValue; + DevReq.Index = 0; + DevReq.Length = 0; return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -97,8 +97,6 @@ PeiUsbSetDeviceAddress ( ); } - - /** Configure a usb device to Configuration 1. @@ -112,16 +110,17 @@ PeiUsbSetDeviceAddress ( **/ EFI_STATUS PeiUsbSetConfiguration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi ) { EFI_USB_DEVICE_REQUEST DevReq; + ZeroMem (&DevReq, sizeof (EFI_USB_DEVICE_REQUEST)); - DevReq.RequestType = USB_DEV_SET_CONFIGURATION_REQ_TYPE; - DevReq.Request = USB_DEV_SET_CONFIGURATION; - DevReq.Value = 1; + DevReq.RequestType = USB_DEV_SET_CONFIGURATION_REQ_TYPE; + DevReq.Request = USB_DEV_SET_CONFIGURATION; + DevReq.Value = 1; return UsbIoPpi->UsbControlTransfer ( PeiServices, @@ -168,12 +167,12 @@ IsPortConnect ( **/ UINTN PeiUsbGetDeviceSpeed ( - IN UINT16 PortStatus + IN UINT16 PortStatus ) { if ((PortStatus & USB_PORT_STAT_LOW_SPEED) != 0) { return EFI_USB_SPEED_LOW; - } else if ((PortStatus & USB_PORT_STAT_HIGH_SPEED) != 0){ + } else if ((PortStatus & USB_PORT_STAT_HIGH_SPEED) != 0) { return EFI_USB_SPEED_HIGH; } else if ((PortStatus & USB_PORT_STAT_SUPER_SPEED) != 0) { return EFI_USB_SPEED_SUPER; @@ -181,5 +180,3 @@ PeiUsbGetDeviceSpeed ( return EFI_USB_SPEED_FULL; } } - - diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.h b/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.h index 48b8e594b2..23f531e8bc 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.h +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/PeiUsbLib.h @@ -10,34 +10,33 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_USB_LIB_H_ #define _PEI_USB_LIB_H_ - // // Standard device request and request type // By [Spec-USB20/Chapter-9.4] // -#define USB_DEV_GET_STATUS 0x00 -#define USB_DEV_GET_STATUS_REQ_TYPE_D 0x80 // Receiver : Device -#define USB_DEV_GET_STATUS_REQ_TYPE_I 0x81 // Receiver : Interface -#define USB_DEV_GET_STATUS_REQ_TYPE_E 0x82 // Receiver : Endpoint +#define USB_DEV_GET_STATUS 0x00 +#define USB_DEV_GET_STATUS_REQ_TYPE_D 0x80 // Receiver : Device +#define USB_DEV_GET_STATUS_REQ_TYPE_I 0x81 // Receiver : Interface +#define USB_DEV_GET_STATUS_REQ_TYPE_E 0x82 // Receiver : Endpoint -#define USB_DEV_CLEAR_FEATURE 0x01 -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface -#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint +#define USB_DEV_CLEAR_FEATURE 0x01 +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface +#define USB_DEV_CLEAR_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint -#define USB_DEV_SET_FEATURE 0x03 -#define USB_DEV_SET_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device -#define USB_DEV_SET_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface -#define USB_DEV_SET_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint +#define USB_DEV_SET_FEATURE 0x03 +#define USB_DEV_SET_FEATURE_REQ_TYPE_D 0x00 // Receiver : Device +#define USB_DEV_SET_FEATURE_REQ_TYPE_I 0x01 // Receiver : Interface +#define USB_DEV_SET_FEATURE_REQ_TYPE_E 0x02 // Receiver : Endpoint -#define USB_DEV_SET_ADDRESS 0x05 -#define USB_DEV_SET_ADDRESS_REQ_TYPE 0x00 +#define USB_DEV_SET_ADDRESS 0x05 +#define USB_DEV_SET_ADDRESS_REQ_TYPE 0x00 -#define USB_DEV_GET_DESCRIPTOR 0x06 -#define USB_DEV_GET_DESCRIPTOR_REQ_TYPE 0x80 +#define USB_DEV_GET_DESCRIPTOR 0x06 +#define USB_DEV_GET_DESCRIPTOR_REQ_TYPE 0x80 -#define USB_DEV_SET_DESCRIPTOR 0x07 -#define USB_DEV_SET_DESCRIPTOR_REQ_TYPE 0x00 +#define USB_DEV_SET_DESCRIPTOR 0x07 +#define USB_DEV_SET_DESCRIPTOR_REQ_TYPE 0x00 #define USB_DEV_GET_CONFIGURATION 0x08 #define USB_DEV_GET_CONFIGURATION_REQ_TYPE 0x80 @@ -45,42 +44,42 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USB_DEV_SET_CONFIGURATION 0x09 #define USB_DEV_SET_CONFIGURATION_REQ_TYPE 0x00 -#define USB_DEV_GET_INTERFACE 0x0A -#define USB_DEV_GET_INTERFACE_REQ_TYPE 0x81 +#define USB_DEV_GET_INTERFACE 0x0A +#define USB_DEV_GET_INTERFACE_REQ_TYPE 0x81 -#define USB_DEV_SET_INTERFACE 0x0B -#define USB_DEV_SET_INTERFACE_REQ_TYPE 0x01 +#define USB_DEV_SET_INTERFACE 0x0B +#define USB_DEV_SET_INTERFACE_REQ_TYPE 0x01 -#define USB_DEV_SYNCH_FRAME 0x0C -#define USB_DEV_SYNCH_FRAME_REQ_TYPE 0x82 +#define USB_DEV_SYNCH_FRAME 0x0C +#define USB_DEV_SYNCH_FRAME_REQ_TYPE 0x82 // // USB Descriptor types // -#define USB_DT_DEVICE 0x01 -#define USB_DT_CONFIG 0x02 -#define USB_DT_STRING 0x03 -#define USB_DT_INTERFACE 0x04 -#define USB_DT_ENDPOINT 0x05 -#define USB_DT_HUB 0x29 -#define USB_DT_SUPERSPEED_HUB 0x2A -#define USB_DT_HID 0x21 +#define USB_DT_DEVICE 0x01 +#define USB_DT_CONFIG 0x02 +#define USB_DT_STRING 0x03 +#define USB_DT_INTERFACE 0x04 +#define USB_DT_ENDPOINT 0x05 +#define USB_DT_HUB 0x29 +#define USB_DT_SUPERSPEED_HUB 0x2A +#define USB_DT_HID 0x21 // // USB request type // -#define USB_TYPE_STANDARD (0x00 << 5) -#define USB_TYPE_CLASS (0x01 << 5) -#define USB_TYPE_VENDOR (0x02 << 5) -#define USB_TYPE_RESERVED (0x03 << 5) +#define USB_TYPE_STANDARD (0x00 << 5) +#define USB_TYPE_CLASS (0x01 << 5) +#define USB_TYPE_VENDOR (0x02 << 5) +#define USB_TYPE_RESERVED (0x03 << 5) // // USB request targer device // -#define USB_RECIP_DEVICE 0x00 -#define USB_RECIP_INTERFACE 0x01 -#define USB_RECIP_ENDPOINT 0x02 -#define USB_RECIP_OTHER 0x03 +#define USB_RECIP_DEVICE 0x00 +#define USB_RECIP_INTERFACE 0x01 +#define USB_RECIP_ENDPOINT 0x02 +#define USB_RECIP_OTHER 0x03 typedef enum { EfiUsbEndpointHalt, @@ -114,12 +113,12 @@ typedef enum { **/ EFI_STATUS PeiUsbGetDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT16 Value, - IN UINT16 Index, - IN UINT16 DescriptorLength, - OUT VOID *Descriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT16 Value, + IN UINT16 Index, + IN UINT16 DescriptorLength, + OUT VOID *Descriptor ); /** @@ -136,12 +135,11 @@ PeiUsbGetDescriptor ( **/ EFI_STATUS PeiUsbSetDeviceAddress ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi, - IN UINT16 AddressValue + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi, + IN UINT16 AddressValue ); - /** Configure a usb device to Configuration 1. @@ -155,8 +153,8 @@ PeiUsbSetDeviceAddress ( **/ EFI_STATUS PeiUsbSetConfiguration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *UsbIoPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *UsbIoPpi ); /** @@ -183,7 +181,7 @@ IsPortConnect ( **/ UINTN PeiUsbGetDeviceSpeed ( - IN UINT16 PortStatus + IN UINT16 PortStatus ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbIoPeim.c b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbIoPeim.c index 4b292b7feb..c4283521ff 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbIoPeim.c +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbIoPeim.c @@ -33,29 +33,30 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI PeiUsbControlTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN EFI_USB_DEVICE_REQUEST *Request, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT32 Timeout, - IN OUT VOID *Data OPTIONAL, - IN UINTN DataLength OPTIONAL + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT32 Timeout, + IN OUT VOID *Data OPTIONAL, + IN UINTN DataLength OPTIONAL ) { - EFI_STATUS Status; - PEI_USB_DEVICE *PeiUsbDev; - UINT32 TransferResult; - EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor; - UINT8 EndpointIndex; + EFI_STATUS Status; + PEI_USB_DEVICE *PeiUsbDev; + UINT32 TransferResult; + EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor; + UINT8 EndpointIndex; PeiUsbDev = PEI_USB_DEVICE_FROM_THIS (This); EndpointDescriptor = NULL; - EndpointIndex = 0; + EndpointIndex = 0; if ((Request->Request == USB_REQ_CLEAR_FEATURE) && (Request->RequestType == USB_DEV_CLEAR_FEATURE_REQ_TYPE_E) && - (Request->Value == USB_FEATURE_ENDPOINT_HALT)) { + (Request->Value == USB_FEATURE_ENDPOINT_HALT)) + { // // Request->Index is the Endpoint Address, use it to get the Endpoint Index. // @@ -79,33 +80,33 @@ PeiUsbControlTransfer ( if (PeiUsbDev->Usb2HcPpi != NULL) { Status = PeiUsbDev->Usb2HcPpi->ControlTransfer ( - PeiServices, - PeiUsbDev->Usb2HcPpi, - PeiUsbDev->DeviceAddress, - PeiUsbDev->DeviceSpeed, - PeiUsbDev->MaxPacketSize0, - Request, - Direction, - Data, - &DataLength, - Timeout, - &(PeiUsbDev->Translator), - &TransferResult - ); + PeiServices, + PeiUsbDev->Usb2HcPpi, + PeiUsbDev->DeviceAddress, + PeiUsbDev->DeviceSpeed, + PeiUsbDev->MaxPacketSize0, + Request, + Direction, + Data, + &DataLength, + Timeout, + &(PeiUsbDev->Translator), + &TransferResult + ); } else { Status = PeiUsbDev->UsbHcPpi->ControlTransfer ( - PeiServices, - PeiUsbDev->UsbHcPpi, - PeiUsbDev->DeviceAddress, - PeiUsbDev->DeviceSpeed, - (UINT8) PeiUsbDev->MaxPacketSize0, - Request, - Direction, - Data, - &DataLength, - Timeout, - &TransferResult - ); + PeiServices, + PeiUsbDev->UsbHcPpi, + PeiUsbDev->DeviceAddress, + PeiUsbDev->DeviceSpeed, + (UINT8)PeiUsbDev->MaxPacketSize0, + Request, + Direction, + Data, + &DataLength, + Timeout, + &TransferResult + ); } // @@ -113,9 +114,10 @@ PeiUsbControlTransfer ( // if ((Request->Request == USB_REQ_CLEAR_FEATURE) && (Request->RequestType == USB_DEV_CLEAR_FEATURE_REQ_TYPE_E) && - (Request->Value == USB_FEATURE_ENDPOINT_HALT)) { + (Request->Value == USB_FEATURE_ENDPOINT_HALT)) + { if ((PeiUsbDev->DataToggle & (1 << EndpointIndex)) != 0) { - PeiUsbDev->DataToggle = (UINT16) (PeiUsbDev->DataToggle ^ (1 << EndpointIndex)); + PeiUsbDev->DataToggle = (UINT16)(PeiUsbDev->DataToggle ^ (1 << EndpointIndex)); } } @@ -147,30 +149,30 @@ PeiUsbControlTransfer ( EFI_STATUS EFIAPI PeiUsbBulkTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN UINT8 DeviceEndpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN UINT8 DeviceEndpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout ) { - EFI_STATUS Status; - PEI_USB_DEVICE *PeiUsbDev; - UINT32 TransferResult; - UINTN MaxPacketLength; - UINT8 DataToggle; - UINT8 OldToggle; - EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor; - UINT8 EndpointIndex; - VOID *Data2[EFI_USB_MAX_BULK_BUFFER_NUM]; - - PeiUsbDev = PEI_USB_DEVICE_FROM_THIS (This); + EFI_STATUS Status; + PEI_USB_DEVICE *PeiUsbDev; + UINT32 TransferResult; + UINTN MaxPacketLength; + UINT8 DataToggle; + UINT8 OldToggle; + EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescriptor; + UINT8 EndpointIndex; + VOID *Data2[EFI_USB_MAX_BULK_BUFFER_NUM]; + + PeiUsbDev = PEI_USB_DEVICE_FROM_THIS (This); EndpointDescriptor = NULL; - EndpointIndex = 0; - Data2[0] = Data; - Data2[1] = NULL; + EndpointIndex = 0; + Data2[0] = Data; + Data2[1] = NULL; while (EndpointIndex < MAX_ENDPOINT) { Status = PeiUsbGetEndpointDescriptor (PeiServices, This, EndpointIndex, &EndpointDescriptor); @@ -200,36 +202,36 @@ PeiUsbBulkTransfer ( if (PeiUsbDev->Usb2HcPpi != NULL) { Status = PeiUsbDev->Usb2HcPpi->BulkTransfer ( - PeiServices, - PeiUsbDev->Usb2HcPpi, - PeiUsbDev->DeviceAddress, - DeviceEndpoint, - PeiUsbDev->DeviceSpeed, - MaxPacketLength, - Data2, - DataLength, - &DataToggle, - Timeout, - &(PeiUsbDev->Translator), - &TransferResult - ); + PeiServices, + PeiUsbDev->Usb2HcPpi, + PeiUsbDev->DeviceAddress, + DeviceEndpoint, + PeiUsbDev->DeviceSpeed, + MaxPacketLength, + Data2, + DataLength, + &DataToggle, + Timeout, + &(PeiUsbDev->Translator), + &TransferResult + ); } else { Status = PeiUsbDev->UsbHcPpi->BulkTransfer ( - PeiServices, - PeiUsbDev->UsbHcPpi, - PeiUsbDev->DeviceAddress, - DeviceEndpoint, - (UINT8) MaxPacketLength, - Data, - DataLength, - &DataToggle, - Timeout, - &TransferResult - ); + PeiServices, + PeiUsbDev->UsbHcPpi, + PeiUsbDev->DeviceAddress, + DeviceEndpoint, + (UINT8)MaxPacketLength, + Data, + DataLength, + &DataToggle, + Timeout, + &TransferResult + ); } if (OldToggle != DataToggle) { - PeiUsbDev->DataToggle = (UINT16) (PeiUsbDev->DataToggle ^ (1 << EndpointIndex)); + PeiUsbDev->DataToggle = (UINT16)(PeiUsbDev->DataToggle ^ (1 << EndpointIndex)); } DEBUG ((DEBUG_INFO, "PeiUsbBulkTransfer: %r\n", Status)); @@ -250,14 +252,15 @@ PeiUsbBulkTransfer ( EFI_STATUS EFIAPI PeiUsbGetInterfaceDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - OUT EFI_USB_INTERFACE_DESCRIPTOR **InterfaceDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + OUT EFI_USB_INTERFACE_DESCRIPTOR **InterfaceDescriptor ) { PEI_USB_DEVICE *PeiUsbDev; - PeiUsbDev = PEI_USB_DEVICE_FROM_THIS (This); - *InterfaceDescriptor = PeiUsbDev->InterfaceDesc; + + PeiUsbDev = PEI_USB_DEVICE_FROM_THIS (This); + *InterfaceDescriptor = PeiUsbDev->InterfaceDesc; return EFI_SUCCESS; } @@ -276,10 +279,10 @@ PeiUsbGetInterfaceDescriptor ( EFI_STATUS EFIAPI PeiUsbGetEndpointDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN UINT8 EndpointIndex, - OUT EFI_USB_ENDPOINT_DESCRIPTOR **EndpointDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN UINT8 EndpointIndex, + OUT EFI_USB_ENDPOINT_DESCRIPTOR **EndpointDescriptor ) { PEI_USB_DEVICE *PeiUsbDev; @@ -317,8 +320,8 @@ PeiUsbGetEndpointDescriptor ( EFI_STATUS EFIAPI PeiUsbPortReset ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This ) { PEI_USB_DEVICE *PeiUsbDev; @@ -338,14 +341,14 @@ PeiUsbPortReset ( // // Set address // - Address = PeiUsbDev->DeviceAddress; - PeiUsbDev->DeviceAddress = 0; + Address = PeiUsbDev->DeviceAddress; + PeiUsbDev->DeviceAddress = 0; Status = PeiUsbSetDeviceAddress ( - PeiServices, - This, - Address - ); + PeiServices, + This, + Address + ); if (EFI_ERROR (Status)) { return Status; @@ -357,9 +360,9 @@ PeiUsbPortReset ( // Set default configuration // Status = PeiUsbSetConfiguration ( - PeiServices, - This - ); + PeiServices, + This + ); return Status; } diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.c b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.c index 12dc975e88..6ea4495162 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.c +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.c @@ -14,7 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // UsbIo PPI interface function // -PEI_USB_IO_PPI mUsbIoPpi = { +PEI_USB_IO_PPI mUsbIoPpi = { PeiUsbControlTransfer, PeiUsbBulkTransfer, PeiUsbGetInterfaceDescriptor, @@ -22,7 +22,7 @@ PEI_USB_IO_PPI mUsbIoPpi = { PeiUsbPortReset }; -EFI_PEI_PPI_DESCRIPTOR mUsbIoPpiList = { +EFI_PEI_PPI_DESCRIPTOR mUsbIoPpiList = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gPeiUsbIoPpiGuid, NULL @@ -42,9 +42,9 @@ EFI_PEI_PPI_DESCRIPTOR mUsbIoPpiList = { **/ EFI_STATUS PeiUsbEnumeration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, - IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, + IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi ); /** @@ -62,10 +62,10 @@ PeiUsbEnumeration ( **/ EFI_STATUS PeiConfigureUsbDevice ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN UINT8 Port, - IN OUT UINT8 *DeviceAddress + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN UINT8 Port, + IN OUT UINT8 *DeviceAddress ); /** @@ -81,8 +81,8 @@ PeiConfigureUsbDevice ( **/ EFI_STATUS PeiUsbGetAllConfiguration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice ); /** @@ -100,11 +100,11 @@ PeiUsbGetAllConfiguration ( **/ EFI_STATUS GetExpectedDescriptor ( - IN UINT8 *Buffer, - IN UINTN Length, - IN UINT8 DescType, - IN UINT8 DescLength, - OUT UINTN *ParsedBytes + IN UINT8 *Buffer, + IN UINTN Length, + IN UINT8 DescType, + IN UINT8 DescLength, + OUT UINTN *ParsedBytes ); /** @@ -121,14 +121,14 @@ GetExpectedDescriptor ( EFI_STATUS EFIAPI PeimInitializeUsb ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - UINTN Index; - PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi; - PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi; + EFI_STATUS Status; + UINTN Index; + PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi; + PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi; if (!EFI_ERROR (PeiServicesRegisterForShadow (FileHandle))) { return EFI_SUCCESS; @@ -147,7 +147,7 @@ PeimInitializeUsb ( &gPeiUsbHostControllerPpiGuid, Index, NULL, - (VOID **) &UsbHcPpi + (VOID **)&UsbHcPpi ); if (EFI_ERROR (Status)) { // @@ -155,7 +155,8 @@ PeimInitializeUsb ( // break; } - PeiUsbEnumeration ((EFI_PEI_SERVICES **) PeiServices, UsbHcPpi, NULL); + + PeiUsbEnumeration ((EFI_PEI_SERVICES **)PeiServices, UsbHcPpi, NULL); Index++; } @@ -168,7 +169,7 @@ PeimInitializeUsb ( &gPeiUsb2HostControllerPpiGuid, Index, NULL, - (VOID **) &Usb2HcPpi + (VOID **)&Usb2HcPpi ); if (EFI_ERROR (Status)) { // @@ -176,7 +177,8 @@ PeimInitializeUsb ( // break; } - PeiUsbEnumeration ((EFI_PEI_SERVICES **) PeiServices, NULL, Usb2HcPpi); + + PeiUsbEnumeration ((EFI_PEI_SERVICES **)PeiServices, NULL, Usb2HcPpi); Index++; } } @@ -203,9 +205,9 @@ PeimInitializeUsb ( **/ EFI_STATUS PeiHubEnumeration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN UINT8 *CurrentAddress + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN UINT8 *CurrentAddress ) { UINTN Index; @@ -218,19 +220,17 @@ PeiHubEnumeration ( UINTN InterfaceIndex; UINTN EndpointIndex; - - UsbIoPpi = &PeiUsbDevice->UsbIoPpi; + UsbIoPpi = &PeiUsbDevice->UsbIoPpi; DEBUG ((DEBUG_INFO, "PeiHubEnumeration: DownStreamPortNo: %x\n", PeiUsbDevice->DownStreamPortNo)); for (Index = 0; Index < PeiUsbDevice->DownStreamPortNo; Index++) { - Status = PeiHubGetPortStatus ( - PeiServices, - UsbIoPpi, - (UINT8) (Index + 1), - (UINT32 *) &PortStatus - ); + PeiServices, + UsbIoPpi, + (UINT8)(Index + 1), + (UINT32 *)&PortStatus + ); if (EFI_ERROR (Status)) { continue; @@ -248,22 +248,22 @@ PeiHubEnumeration ( // Begin to deal with the new device // MemPages = sizeof (PEI_USB_DEVICE) / EFI_PAGE_SIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &AllocateAddress - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &AllocateAddress + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - NewPeiUsbDevice = (PEI_USB_DEVICE *) ((UINTN) AllocateAddress); + NewPeiUsbDevice = (PEI_USB_DEVICE *)((UINTN)AllocateAddress); ZeroMem (NewPeiUsbDevice, sizeof (PEI_USB_DEVICE)); - NewPeiUsbDevice->Signature = PEI_USB_DEVICE_SIGNATURE; - NewPeiUsbDevice->DeviceAddress = 0; - NewPeiUsbDevice->MaxPacketSize0 = 8; - NewPeiUsbDevice->DataToggle = 0; + NewPeiUsbDevice->Signature = PEI_USB_DEVICE_SIGNATURE; + NewPeiUsbDevice->DeviceAddress = 0; + NewPeiUsbDevice->MaxPacketSize0 = 8; + NewPeiUsbDevice->DataToggle = 0; CopyMem ( &(NewPeiUsbDevice->UsbIoPpi), &mUsbIoPpi, @@ -275,39 +275,40 @@ PeiHubEnumeration ( sizeof (EFI_PEI_PPI_DESCRIPTOR) ); NewPeiUsbDevice->UsbIoPpiList.Ppi = &NewPeiUsbDevice->UsbIoPpi; - NewPeiUsbDevice->AllocateAddress = (UINTN) AllocateAddress; + NewPeiUsbDevice->AllocateAddress = (UINTN)AllocateAddress; NewPeiUsbDevice->UsbHcPpi = PeiUsbDevice->UsbHcPpi; NewPeiUsbDevice->Usb2HcPpi = PeiUsbDevice->Usb2HcPpi; - NewPeiUsbDevice->Tier = (UINT8) (PeiUsbDevice->Tier + 1); + NewPeiUsbDevice->Tier = (UINT8)(PeiUsbDevice->Tier + 1); NewPeiUsbDevice->IsHub = 0x0; NewPeiUsbDevice->DownStreamPortNo = 0x0; if (((PortStatus.PortChangeStatus & USB_PORT_STAT_C_RESET) == 0) || - ((PortStatus.PortStatus & (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE)) == 0)) { + ((PortStatus.PortStatus & (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE)) == 0)) + { // // If the port already has reset change flag and is connected and enabled, skip the port reset logic. // PeiResetHubPort (PeiServices, UsbIoPpi, (UINT8)(Index + 1)); PeiHubGetPortStatus ( - PeiServices, - UsbIoPpi, - (UINT8) (Index + 1), - (UINT32 *) &PortStatus - ); + PeiServices, + UsbIoPpi, + (UINT8)(Index + 1), + (UINT32 *)&PortStatus + ); } else { PeiHubClearPortFeature ( PeiServices, UsbIoPpi, - (UINT8) (Index + 1), + (UINT8)(Index + 1), EfiUsbPortResetChange ); } - NewPeiUsbDevice->DeviceSpeed = (UINT8) PeiUsbGetDeviceSpeed (PortStatus.PortStatus); + NewPeiUsbDevice->DeviceSpeed = (UINT8)PeiUsbGetDeviceSpeed (PortStatus.PortStatus); DEBUG ((DEBUG_INFO, "Device Speed =%d\n", PeiUsbDevice->DeviceSpeed)); - if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_SUPER_SPEED)){ + if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_SUPER_SPEED)) { NewPeiUsbDevice->MaxPacketSize0 = 512; } else if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_HIGH_SPEED)) { NewPeiUsbDevice->MaxPacketSize0 = 64; @@ -317,12 +318,12 @@ PeiHubEnumeration ( NewPeiUsbDevice->MaxPacketSize0 = 8; } - if(NewPeiUsbDevice->DeviceSpeed != EFI_USB_SPEED_HIGH) { + if (NewPeiUsbDevice->DeviceSpeed != EFI_USB_SPEED_HIGH) { if (PeiUsbDevice->DeviceSpeed == EFI_USB_SPEED_HIGH) { NewPeiUsbDevice->Translator.TranslatorPortNumber = (UINT8)Index; NewPeiUsbDevice->Translator.TranslatorHubAddress = *CurrentAddress; } else { - CopyMem(&(NewPeiUsbDevice->Translator), &(PeiUsbDevice->Translator), sizeof(EFI_USB2_HC_TRANSACTION_TRANSLATOR)); + CopyMem (&(NewPeiUsbDevice->Translator), &(PeiUsbDevice->Translator), sizeof (EFI_USB2_HC_TRANSACTION_TRANSLATOR)); } } @@ -330,21 +331,22 @@ PeiHubEnumeration ( // Configure that Usb Device // Status = PeiConfigureUsbDevice ( - PeiServices, - NewPeiUsbDevice, - (UINT8) (Index + 1), - CurrentAddress - ); + PeiServices, + NewPeiUsbDevice, + (UINT8)(Index + 1), + CurrentAddress + ); if (EFI_ERROR (Status)) { continue; } + DEBUG ((DEBUG_INFO, "PeiHubEnumeration: PeiConfigureUsbDevice Success\n")); Status = PeiServicesInstallPpi (&NewPeiUsbDevice->UsbIoPpiList); if (NewPeiUsbDevice->InterfaceDesc->InterfaceClass == 0x09) { - NewPeiUsbDevice->IsHub = 0x1; + NewPeiUsbDevice->IsHub = 0x1; Status = PeiDoHubConfig (PeiServices, NewPeiUsbDevice); if (EFI_ERROR (Status)) { @@ -359,19 +361,20 @@ PeiHubEnumeration ( // Begin to deal with the new device // MemPages = sizeof (PEI_USB_DEVICE) / EFI_PAGE_SIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &AllocateAddress - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &AllocateAddress + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + CopyMem ((VOID *)(UINTN)AllocateAddress, NewPeiUsbDevice, sizeof (PEI_USB_DEVICE)); - NewPeiUsbDevice = (PEI_USB_DEVICE *) ((UINTN) AllocateAddress); - NewPeiUsbDevice->AllocateAddress = (UINTN) AllocateAddress; + NewPeiUsbDevice = (PEI_USB_DEVICE *)((UINTN)AllocateAddress); + NewPeiUsbDevice->AllocateAddress = (UINTN)AllocateAddress; NewPeiUsbDevice->UsbIoPpiList.Ppi = &NewPeiUsbDevice->UsbIoPpi; - NewPeiUsbDevice->InterfaceDesc = NewPeiUsbDevice->InterfaceDescList[InterfaceIndex]; + NewPeiUsbDevice->InterfaceDesc = NewPeiUsbDevice->InterfaceDescList[InterfaceIndex]; for (EndpointIndex = 0; EndpointIndex < NewPeiUsbDevice->InterfaceDesc->NumEndpoints; EndpointIndex++) { NewPeiUsbDevice->EndpointDesc[EndpointIndex] = NewPeiUsbDevice->EndpointDescList[InterfaceIndex][EndpointIndex]; } @@ -379,7 +382,7 @@ PeiHubEnumeration ( Status = PeiServicesInstallPpi (&NewPeiUsbDevice->UsbIoPpiList); if (NewPeiUsbDevice->InterfaceDesc->InterfaceClass == 0x09) { - NewPeiUsbDevice->IsHub = 0x1; + NewPeiUsbDevice->IsHub = 0x1; Status = PeiDoHubConfig (PeiServices, NewPeiUsbDevice); if (EFI_ERROR (Status)) { @@ -393,7 +396,6 @@ PeiHubEnumeration ( } } - return EFI_SUCCESS; } @@ -411,9 +413,9 @@ PeiHubEnumeration ( **/ EFI_STATUS PeiUsbEnumeration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, - IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, + IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi ) { UINT8 NumOfRootPort; @@ -430,15 +432,15 @@ PeiUsbEnumeration ( CurrentAddress = 0; if (Usb2HcPpi != NULL) { Usb2HcPpi->GetRootHubPortNumber ( - PeiServices, - Usb2HcPpi, - (UINT8 *) &NumOfRootPort - ); + PeiServices, + Usb2HcPpi, + (UINT8 *)&NumOfRootPort + ); } else if (UsbHcPpi != NULL) { UsbHcPpi->GetRootHubPortNumber ( PeiServices, UsbHcPpi, - (UINT8 *) &NumOfRootPort + (UINT8 *)&NumOfRootPort ); } else { ASSERT (FALSE); @@ -453,19 +455,20 @@ PeiUsbEnumeration ( // if (Usb2HcPpi != NULL) { Usb2HcPpi->GetRootHubPortStatus ( - PeiServices, - Usb2HcPpi, - (UINT8) Index, - &PortStatus - ); + PeiServices, + Usb2HcPpi, + (UINT8)Index, + &PortStatus + ); } else { UsbHcPpi->GetRootHubPortStatus ( PeiServices, UsbHcPpi, - (UINT8) Index, + (UINT8)Index, &PortStatus ); } + DEBUG ((DEBUG_INFO, "USB Status --- Port: %x ConnectChange[%04x] Status[%04x]\n", Index, PortStatus.PortChangeStatus, PortStatus.PortStatus)); // // Only handle connection/enable/overcurrent/reset change. @@ -475,22 +478,22 @@ PeiUsbEnumeration ( } else { if (IsPortConnect (PortStatus.PortStatus)) { MemPages = sizeof (PEI_USB_DEVICE) / EFI_PAGE_SIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &AllocateAddress - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &AllocateAddress + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - PeiUsbDevice = (PEI_USB_DEVICE *) ((UINTN) AllocateAddress); + PeiUsbDevice = (PEI_USB_DEVICE *)((UINTN)AllocateAddress); ZeroMem (PeiUsbDevice, sizeof (PEI_USB_DEVICE)); - PeiUsbDevice->Signature = PEI_USB_DEVICE_SIGNATURE; - PeiUsbDevice->DeviceAddress = 0; - PeiUsbDevice->MaxPacketSize0 = 8; - PeiUsbDevice->DataToggle = 0; + PeiUsbDevice->Signature = PEI_USB_DEVICE_SIGNATURE; + PeiUsbDevice->DeviceAddress = 0; + PeiUsbDevice->MaxPacketSize0 = 8; + PeiUsbDevice->DataToggle = 0; CopyMem ( &(PeiUsbDevice->UsbIoPpi), &mUsbIoPpi, @@ -501,15 +504,16 @@ PeiUsbEnumeration ( &mUsbIoPpiList, sizeof (EFI_PEI_PPI_DESCRIPTOR) ); - PeiUsbDevice->UsbIoPpiList.Ppi = &PeiUsbDevice->UsbIoPpi; - PeiUsbDevice->AllocateAddress = (UINTN) AllocateAddress; - PeiUsbDevice->UsbHcPpi = UsbHcPpi; - PeiUsbDevice->Usb2HcPpi = Usb2HcPpi; - PeiUsbDevice->IsHub = 0x0; - PeiUsbDevice->DownStreamPortNo = 0x0; + PeiUsbDevice->UsbIoPpiList.Ppi = &PeiUsbDevice->UsbIoPpi; + PeiUsbDevice->AllocateAddress = (UINTN)AllocateAddress; + PeiUsbDevice->UsbHcPpi = UsbHcPpi; + PeiUsbDevice->Usb2HcPpi = Usb2HcPpi; + PeiUsbDevice->IsHub = 0x0; + PeiUsbDevice->DownStreamPortNo = 0x0; if (((PortStatus.PortChangeStatus & USB_PORT_STAT_C_RESET) == 0) || - ((PortStatus.PortStatus & (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE)) == 0)) { + ((PortStatus.PortStatus & (USB_PORT_STAT_CONNECTION | USB_PORT_STAT_ENABLE)) == 0)) + { // // If the port already has reset change flag and is connected and enabled, skip the port reset logic. // @@ -525,39 +529,39 @@ PeiUsbEnumeration ( Usb2HcPpi->GetRootHubPortStatus ( PeiServices, Usb2HcPpi, - (UINT8) Index, + (UINT8)Index, &PortStatus ); } else { UsbHcPpi->GetRootHubPortStatus ( PeiServices, UsbHcPpi, - (UINT8) Index, + (UINT8)Index, &PortStatus ); } } else { if (Usb2HcPpi != NULL) { Usb2HcPpi->ClearRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - (UINT8) Index, - EfiUsbPortResetChange - ); + PeiServices, + Usb2HcPpi, + (UINT8)Index, + EfiUsbPortResetChange + ); } else { UsbHcPpi->ClearRootHubPortFeature ( PeiServices, UsbHcPpi, - (UINT8) Index, + (UINT8)Index, EfiUsbPortResetChange ); } } - PeiUsbDevice->DeviceSpeed = (UINT8) PeiUsbGetDeviceSpeed (PortStatus.PortStatus); + PeiUsbDevice->DeviceSpeed = (UINT8)PeiUsbGetDeviceSpeed (PortStatus.PortStatus); DEBUG ((DEBUG_INFO, "Device Speed =%d\n", PeiUsbDevice->DeviceSpeed)); - if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_SUPER_SPEED)){ + if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_SUPER_SPEED)) { PeiUsbDevice->MaxPacketSize0 = 512; } else if (USB_BIT_IS_SET (PortStatus.PortStatus, USB_PORT_STAT_HIGH_SPEED)) { PeiUsbDevice->MaxPacketSize0 = 64; @@ -571,15 +575,16 @@ PeiUsbEnumeration ( // Configure that Usb Device // Status = PeiConfigureUsbDevice ( - PeiServices, - PeiUsbDevice, - Index, - &CurrentAddress - ); + PeiServices, + PeiUsbDevice, + Index, + &CurrentAddress + ); if (EFI_ERROR (Status)) { continue; } + DEBUG ((DEBUG_INFO, "PeiUsbEnumeration: PeiConfigureUsbDevice Success\n")); Status = PeiServicesInstallPpi (&PeiUsbDevice->UsbIoPpiList); @@ -600,19 +605,20 @@ PeiUsbEnumeration ( // Begin to deal with the new device // MemPages = sizeof (PEI_USB_DEVICE) / EFI_PAGE_SIZE + 1; - Status = PeiServicesAllocatePages ( - EfiBootServicesCode, - MemPages, - &AllocateAddress - ); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + MemPages, + &AllocateAddress + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + CopyMem ((VOID *)(UINTN)AllocateAddress, PeiUsbDevice, sizeof (PEI_USB_DEVICE)); - PeiUsbDevice = (PEI_USB_DEVICE *) ((UINTN) AllocateAddress); - PeiUsbDevice->AllocateAddress = (UINTN) AllocateAddress; + PeiUsbDevice = (PEI_USB_DEVICE *)((UINTN)AllocateAddress); + PeiUsbDevice->AllocateAddress = (UINTN)AllocateAddress; PeiUsbDevice->UsbIoPpiList.Ppi = &PeiUsbDevice->UsbIoPpi; - PeiUsbDevice->InterfaceDesc = PeiUsbDevice->InterfaceDescList[InterfaceIndex]; + PeiUsbDevice->InterfaceDesc = PeiUsbDevice->InterfaceDescList[InterfaceIndex]; for (EndpointIndex = 0; EndpointIndex < PeiUsbDevice->InterfaceDesc->NumEndpoints; EndpointIndex++) { PeiUsbDevice->EndpointDesc[EndpointIndex] = PeiUsbDevice->EndpointDescList[InterfaceIndex][EndpointIndex]; } @@ -656,16 +662,16 @@ PeiUsbEnumeration ( **/ EFI_STATUS PeiConfigureUsbDevice ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice, - IN UINT8 Port, - IN OUT UINT8 *DeviceAddress + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice, + IN UINT8 Port, + IN OUT UINT8 *DeviceAddress ) { - EFI_USB_DEVICE_DESCRIPTOR DeviceDescriptor; - EFI_STATUS Status; - PEI_USB_IO_PPI *UsbIoPpi; - UINT8 Retry; + EFI_USB_DEVICE_DESCRIPTOR DeviceDescriptor; + EFI_STATUS Status; + PEI_USB_IO_PPI *UsbIoPpi; + UINT8 Retry; UsbIoPpi = &PeiUsbDevice->UsbIoPpi; Status = EFI_SUCCESS; @@ -674,7 +680,7 @@ PeiConfigureUsbDevice ( // Get USB device descriptor // - for (Retry = 0; Retry < 3; Retry ++) { + for (Retry = 0; Retry < 3; Retry++) { Status = PeiUsbGetDescriptor ( PeiServices, UsbIoPpi, @@ -701,18 +707,19 @@ PeiConfigureUsbDevice ( PeiUsbDevice->MaxPacketSize0 = DeviceDescriptor.MaxPacketSize0; } - (*DeviceAddress) ++; + (*DeviceAddress)++; Status = PeiUsbSetDeviceAddress ( - PeiServices, - UsbIoPpi, - *DeviceAddress - ); + PeiServices, + UsbIoPpi, + *DeviceAddress + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "PeiUsbSetDeviceAddress Failed: %r\n", Status)); return Status; } + MicroSecondDelay (USB_SET_DEVICE_ADDRESS_STALL); PeiUsbDevice->DeviceAddress = *DeviceAddress; @@ -721,13 +728,13 @@ PeiConfigureUsbDevice ( // Get whole USB device descriptor // Status = PeiUsbGetDescriptor ( - PeiServices, - UsbIoPpi, - (USB_DT_DEVICE << 8), - 0, - (UINT16) sizeof (EFI_USB_DEVICE_DESCRIPTOR), - &DeviceDescriptor - ); + PeiServices, + UsbIoPpi, + (USB_DT_DEVICE << 8), + 0, + (UINT16)sizeof (EFI_USB_DEVICE_DESCRIPTOR), + &DeviceDescriptor + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "PeiUsbGetDescriptor First Failed\n")); @@ -738,18 +745,19 @@ PeiConfigureUsbDevice ( // Get its default configuration and its first interface // Status = PeiUsbGetAllConfiguration ( - PeiServices, - PeiUsbDevice - ); + PeiServices, + PeiUsbDevice + ); if (EFI_ERROR (Status)) { return Status; } + MicroSecondDelay (USB_GET_CONFIG_DESCRIPTOR_STALL); Status = PeiUsbSetConfiguration ( - PeiServices, - UsbIoPpi - ); + PeiServices, + UsbIoPpi + ); if (EFI_ERROR (Status)) { return Status; @@ -771,20 +779,20 @@ PeiConfigureUsbDevice ( **/ EFI_STATUS PeiUsbGetAllConfiguration ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_DEVICE *PeiUsbDevice + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_DEVICE *PeiUsbDevice ) { - EFI_STATUS Status; - EFI_USB_CONFIG_DESCRIPTOR *ConfigDesc; - PEI_USB_IO_PPI *UsbIoPpi; - UINT16 ConfigDescLength; - UINT8 *Ptr; - UINTN SkipBytes; - UINTN LengthLeft; - UINTN InterfaceIndex; - UINTN Index; - UINTN NumOfEndpoint; + EFI_STATUS Status; + EFI_USB_CONFIG_DESCRIPTOR *ConfigDesc; + PEI_USB_IO_PPI *UsbIoPpi; + UINT16 ConfigDescLength; + UINT8 *Ptr; + UINTN SkipBytes; + UINTN LengthLeft; + UINTN InterfaceIndex; + UINTN Index; + UINTN NumOfEndpoint; UsbIoPpi = &PeiUsbDevice->UsbIoPpi; @@ -792,22 +800,23 @@ PeiUsbGetAllConfiguration ( // First get its 4-byte configuration descriptor // Status = PeiUsbGetDescriptor ( - PeiServices, - UsbIoPpi, - (USB_DT_CONFIG << 8), // Value - 0, // Index - 4, // Length - PeiUsbDevice->ConfigurationData - ); + PeiServices, + UsbIoPpi, + (USB_DT_CONFIG << 8), // Value + 0, // Index + 4, // Length + PeiUsbDevice->ConfigurationData + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "PeiUsbGet Config Descriptor First Failed\n")); return Status; } + MicroSecondDelay (USB_GET_CONFIG_DESCRIPTOR_STALL); - ConfigDesc = (EFI_USB_CONFIG_DESCRIPTOR *) PeiUsbDevice->ConfigurationData; - ConfigDescLength = ConfigDesc->TotalLength; + ConfigDesc = (EFI_USB_CONFIG_DESCRIPTOR *)PeiUsbDevice->ConfigurationData; + ConfigDescLength = ConfigDesc->TotalLength; // // Reject if TotalLength even cannot cover itself. @@ -827,52 +836,52 @@ PeiUsbGetAllConfiguration ( // Then we get the total descriptors for this configuration // Status = PeiUsbGetDescriptor ( - PeiServices, - UsbIoPpi, - (USB_DT_CONFIG << 8), - 0, - ConfigDescLength, - PeiUsbDevice->ConfigurationData - ); + PeiServices, + UsbIoPpi, + (USB_DT_CONFIG << 8), + 0, + ConfigDescLength, + PeiUsbDevice->ConfigurationData + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "PeiUsbGet Config Descriptor all Failed\n")); return Status; } + // // Parse this configuration descriptor // First get the current config descriptor; // Status = GetExpectedDescriptor ( - PeiUsbDevice->ConfigurationData, - ConfigDescLength, - USB_DT_CONFIG, - (UINT8) sizeof (EFI_USB_CONFIG_DESCRIPTOR), - &SkipBytes - ); + PeiUsbDevice->ConfigurationData, + ConfigDescLength, + USB_DT_CONFIG, + (UINT8)sizeof (EFI_USB_CONFIG_DESCRIPTOR), + &SkipBytes + ); if (EFI_ERROR (Status)) { return Status; } - Ptr = PeiUsbDevice->ConfigurationData + SkipBytes; - PeiUsbDevice->ConfigDesc = (EFI_USB_CONFIG_DESCRIPTOR *) Ptr; + Ptr = PeiUsbDevice->ConfigurationData + SkipBytes; + PeiUsbDevice->ConfigDesc = (EFI_USB_CONFIG_DESCRIPTOR *)Ptr; - Ptr += sizeof (EFI_USB_CONFIG_DESCRIPTOR); + Ptr += sizeof (EFI_USB_CONFIG_DESCRIPTOR); LengthLeft = ConfigDescLength - SkipBytes - sizeof (EFI_USB_CONFIG_DESCRIPTOR); for (InterfaceIndex = 0; InterfaceIndex < PeiUsbDevice->ConfigDesc->NumInterfaces; InterfaceIndex++) { - // // Get the interface descriptor // Status = GetExpectedDescriptor ( - Ptr, - LengthLeft, - USB_DT_INTERFACE, - (UINT8) sizeof (EFI_USB_INTERFACE_DESCRIPTOR), - &SkipBytes - ); + Ptr, + LengthLeft, + USB_DT_INTERFACE, + (UINT8)sizeof (EFI_USB_INTERFACE_DESCRIPTOR), + &SkipBytes + ); if (EFI_ERROR (Status)) { return Status; @@ -880,11 +889,12 @@ PeiUsbGetAllConfiguration ( Ptr += SkipBytes; if (InterfaceIndex == 0) { - PeiUsbDevice->InterfaceDesc = (EFI_USB_INTERFACE_DESCRIPTOR *) Ptr; + PeiUsbDevice->InterfaceDesc = (EFI_USB_INTERFACE_DESCRIPTOR *)Ptr; } - PeiUsbDevice->InterfaceDescList[InterfaceIndex] = (EFI_USB_INTERFACE_DESCRIPTOR *) Ptr; - Ptr += sizeof (EFI_USB_INTERFACE_DESCRIPTOR); + PeiUsbDevice->InterfaceDescList[InterfaceIndex] = (EFI_USB_INTERFACE_DESCRIPTOR *)Ptr; + + Ptr += sizeof (EFI_USB_INTERFACE_DESCRIPTOR); LengthLeft -= SkipBytes; LengthLeft -= sizeof (EFI_USB_INTERFACE_DESCRIPTOR); @@ -899,12 +909,12 @@ PeiUsbGetAllConfiguration ( // Get the endpoint descriptor // Status = GetExpectedDescriptor ( - Ptr, - LengthLeft, - USB_DT_ENDPOINT, - (UINT8) sizeof (EFI_USB_ENDPOINT_DESCRIPTOR), - &SkipBytes - ); + Ptr, + LengthLeft, + USB_DT_ENDPOINT, + (UINT8)sizeof (EFI_USB_ENDPOINT_DESCRIPTOR), + &SkipBytes + ); if (EFI_ERROR (Status)) { return Status; @@ -912,11 +922,12 @@ PeiUsbGetAllConfiguration ( Ptr += SkipBytes; if (InterfaceIndex == 0) { - PeiUsbDevice->EndpointDesc[Index] = (EFI_USB_ENDPOINT_DESCRIPTOR *) Ptr; + PeiUsbDevice->EndpointDesc[Index] = (EFI_USB_ENDPOINT_DESCRIPTOR *)Ptr; } - PeiUsbDevice->EndpointDescList[InterfaceIndex][Index] = (EFI_USB_ENDPOINT_DESCRIPTOR *) Ptr; - Ptr += sizeof (EFI_USB_ENDPOINT_DESCRIPTOR); + PeiUsbDevice->EndpointDescList[InterfaceIndex][Index] = (EFI_USB_ENDPOINT_DESCRIPTOR *)Ptr; + + Ptr += sizeof (EFI_USB_ENDPOINT_DESCRIPTOR); LengthLeft -= SkipBytes; LengthLeft -= sizeof (EFI_USB_ENDPOINT_DESCRIPTOR); } @@ -940,15 +951,15 @@ PeiUsbGetAllConfiguration ( **/ EFI_STATUS GetExpectedDescriptor ( - IN UINT8 *Buffer, - IN UINTN Length, - IN UINT8 DescType, - IN UINT8 DescLength, - OUT UINTN *ParsedBytes + IN UINT8 *Buffer, + IN UINTN Length, + IN UINT8 DescType, + IN UINT8 DescLength, + OUT UINTN *ParsedBytes ) { - USB_DESC_HEAD *Head; - UINTN Offset; + USB_DESC_HEAD *Head; + UINTN Offset; // // Total length is too small that cannot hold the single descriptor header plus data. @@ -1020,17 +1031,16 @@ GetExpectedDescriptor ( **/ VOID ResetRootPort ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, - IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi, - IN UINT8 PortNum, - IN UINT8 RetryIndex + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, + IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi, + IN UINT8 PortNum, + IN UINT8 RetryIndex ) { - EFI_STATUS Status; - UINTN Index; - EFI_USB_PORT_STATUS PortStatus; - + EFI_STATUS Status; + UINTN Index; + EFI_USB_PORT_STATUS PortStatus; if (Usb2HcPpi != NULL) { MicroSecondDelay (200 * 1000); @@ -1039,11 +1049,11 @@ ResetRootPort ( // reset root port // Status = Usb2HcPpi->SetRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortReset - ); + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortReset + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "SetRootHubPortFeature EfiUsbPortReset Failed\n")); @@ -1060,11 +1070,11 @@ ResetRootPort ( // clear reset root port // Status = Usb2HcPpi->ClearRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortReset - ); + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortReset + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "ClearRootHubPortFeature EfiUsbPortReset Failed\n")); @@ -1103,35 +1113,35 @@ ResetRootPort ( } Usb2HcPpi->ClearRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortResetChange - ); + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortResetChange + ); Usb2HcPpi->ClearRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortConnectChange - ); + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortConnectChange + ); // // Set port enable // - Usb2HcPpi->SetRootHubPortFeature( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortEnable - ); + Usb2HcPpi->SetRootHubPortFeature ( + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortEnable + ); Usb2HcPpi->ClearRootHubPortFeature ( - PeiServices, - Usb2HcPpi, - PortNum, - EfiUsbPortEnableChange - ); + PeiServices, + Usb2HcPpi, + PortNum, + EfiUsbPortEnableChange + ); MicroSecondDelay ((RetryIndex + 1) * 50 * 1000); } else { @@ -1221,7 +1231,7 @@ ResetRootPort ( // // Set port enable // - UsbHcPpi->SetRootHubPortFeature( + UsbHcPpi->SetRootHubPortFeature ( PeiServices, UsbHcPpi, PortNum, @@ -1237,5 +1247,6 @@ ResetRootPort ( MicroSecondDelay ((RetryIndex + 1) * 50 * 1000); } + return; } diff --git a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.h b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.h index 776edba6bb..69d1126da0 100644 --- a/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.h +++ b/MdeModulePkg/Bus/Usb/UsbBusPei/UsbPeim.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_USB_PEIM_H_ #define _PEI_USB_PEIM_H_ - #include #include @@ -32,43 +31,43 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #pragma pack(1) typedef struct { - UINT8 Len; - UINT8 Type; + UINT8 Len; + UINT8 Type; } USB_DESC_HEAD; #pragma pack() -#define MAX_INTERFACE 8 -#define MAX_ENDPOINT 16 +#define MAX_INTERFACE 8 +#define MAX_ENDPOINT 16 #define PEI_USB_DEVICE_SIGNATURE SIGNATURE_32 ('U', 's', 'b', 'D') typedef struct { - UINTN Signature; - PEI_USB_IO_PPI UsbIoPpi; - EFI_PEI_PPI_DESCRIPTOR UsbIoPpiList; - UINT16 MaxPacketSize0; - UINT16 DataToggle; - UINT8 DeviceAddress; - UINT8 DeviceSpeed; - UINT8 IsHub; - UINT8 DownStreamPortNo; - UINTN AllocateAddress; - PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi; - PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi; - UINT8 ConfigurationData[1024]; - EFI_USB_CONFIG_DESCRIPTOR *ConfigDesc; - EFI_USB_INTERFACE_DESCRIPTOR *InterfaceDesc; - EFI_USB_INTERFACE_DESCRIPTOR *InterfaceDescList[MAX_INTERFACE]; - EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDesc[MAX_ENDPOINT]; - EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescList[MAX_INTERFACE][MAX_ENDPOINT]; - EFI_USB2_HC_TRANSACTION_TRANSLATOR Translator; - UINT8 Tier; + UINTN Signature; + PEI_USB_IO_PPI UsbIoPpi; + EFI_PEI_PPI_DESCRIPTOR UsbIoPpiList; + UINT16 MaxPacketSize0; + UINT16 DataToggle; + UINT8 DeviceAddress; + UINT8 DeviceSpeed; + UINT8 IsHub; + UINT8 DownStreamPortNo; + UINTN AllocateAddress; + PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi; + PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi; + UINT8 ConfigurationData[1024]; + EFI_USB_CONFIG_DESCRIPTOR *ConfigDesc; + EFI_USB_INTERFACE_DESCRIPTOR *InterfaceDesc; + EFI_USB_INTERFACE_DESCRIPTOR *InterfaceDescList[MAX_INTERFACE]; + EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDesc[MAX_ENDPOINT]; + EFI_USB_ENDPOINT_DESCRIPTOR *EndpointDescList[MAX_INTERFACE][MAX_ENDPOINT]; + EFI_USB2_HC_TRANSACTION_TRANSLATOR Translator; + UINT8 Tier; } PEI_USB_DEVICE; -#define PEI_USB_DEVICE_FROM_THIS(a) CR (a, PEI_USB_DEVICE, UsbIoPpi, PEI_USB_DEVICE_SIGNATURE) +#define PEI_USB_DEVICE_FROM_THIS(a) CR (a, PEI_USB_DEVICE, UsbIoPpi, PEI_USB_DEVICE_SIGNATURE) -#define USB_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) +#define USB_BIT_IS_SET(Data, Bit) ((BOOLEAN)(((Data) & (Bit)) == (Bit))) -#define USB_BUS_1_MILLISECOND 1000 +#define USB_BUS_1_MILLISECOND 1000 // // Wait for port reset, refers to specification @@ -78,13 +77,13 @@ typedef struct { // According to USB2.0, Chapter 11.5.1.5 Resetting, // the worst case for TDRST is 20ms // -#define USB_SET_PORT_RESET_STALL (20 * USB_BUS_1_MILLISECOND) -#define USB_SET_ROOT_PORT_RESET_STALL (50 * USB_BUS_1_MILLISECOND) +#define USB_SET_PORT_RESET_STALL (20 * USB_BUS_1_MILLISECOND) +#define USB_SET_ROOT_PORT_RESET_STALL (50 * USB_BUS_1_MILLISECOND) // // Wait for clear roothub port reset, set by experience // -#define USB_CLR_ROOT_PORT_RESET_STALL (20 * USB_BUS_1_MILLISECOND) +#define USB_CLR_ROOT_PORT_RESET_STALL (20 * USB_BUS_1_MILLISECOND) // // Wait for port statue reg change, set by experience @@ -95,24 +94,24 @@ typedef struct { // Host software return timeout if port status doesn't change // after 500ms(LOOP * STALL = 5000 * 0.1ms), set by experience // -#define USB_WAIT_PORT_STS_CHANGE_LOOP 5000 +#define USB_WAIT_PORT_STS_CHANGE_LOOP 5000 // // Wait for hub port power-on, refers to specification // [USB20-11.23.2] // -#define USB_SET_PORT_POWER_STALL (2 * USB_BUS_1_MILLISECOND) +#define USB_SET_PORT_POWER_STALL (2 * USB_BUS_1_MILLISECOND) // // Wait for set device address, refers to specification // [USB20-9.2.6.3, it says 2ms] // -#define USB_SET_DEVICE_ADDRESS_STALL (2 * USB_BUS_1_MILLISECOND) +#define USB_SET_DEVICE_ADDRESS_STALL (2 * USB_BUS_1_MILLISECOND) // // Wait for get configuration descriptor, set by experience // -#define USB_GET_CONFIG_DESCRIPTOR_STALL (1 * USB_BUS_1_MILLISECOND) +#define USB_GET_CONFIG_DESCRIPTOR_STALL (1 * USB_BUS_1_MILLISECOND) /** Submits control transfer to a target USB device. @@ -137,13 +136,13 @@ typedef struct { EFI_STATUS EFIAPI PeiUsbControlTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN EFI_USB_DEVICE_REQUEST *Request, - IN EFI_USB_DATA_DIRECTION Direction, - IN UINT32 Timeout, - IN OUT VOID *Data OPTIONAL, - IN UINTN DataLength OPTIONAL + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN EFI_USB_DEVICE_REQUEST *Request, + IN EFI_USB_DATA_DIRECTION Direction, + IN UINT32 Timeout, + IN OUT VOID *Data OPTIONAL, + IN UINTN DataLength OPTIONAL ); /** @@ -170,12 +169,12 @@ PeiUsbControlTransfer ( EFI_STATUS EFIAPI PeiUsbBulkTransfer ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN UINT8 DeviceEndpoint, - IN OUT VOID *Data, - IN OUT UINTN *DataLength, - IN UINTN Timeout + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN UINT8 DeviceEndpoint, + IN OUT VOID *Data, + IN OUT UINTN *DataLength, + IN UINTN Timeout ); /** @@ -192,9 +191,9 @@ PeiUsbBulkTransfer ( EFI_STATUS EFIAPI PeiUsbGetInterfaceDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - OUT EFI_USB_INTERFACE_DESCRIPTOR **InterfaceDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + OUT EFI_USB_INTERFACE_DESCRIPTOR **InterfaceDescriptor ); /** @@ -212,10 +211,10 @@ PeiUsbGetInterfaceDescriptor ( EFI_STATUS EFIAPI PeiUsbGetEndpointDescriptor ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This, - IN UINT8 EndpointIndex, - OUT EFI_USB_ENDPOINT_DESCRIPTOR **EndpointDescriptor + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This, + IN UINT8 EndpointIndex, + OUT EFI_USB_ENDPOINT_DESCRIPTOR **EndpointDescriptor ); /** @@ -231,8 +230,8 @@ PeiUsbGetEndpointDescriptor ( EFI_STATUS EFIAPI PeiUsbPortReset ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_IO_PPI *This + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_IO_PPI *This ); /** @@ -247,11 +246,11 @@ PeiUsbPortReset ( **/ VOID ResetRootPort ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, - IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi, - IN UINT8 PortNum, - IN UINT8 RetryIndex + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_USB_HOST_CONTROLLER_PPI *UsbHcPpi, + IN PEI_USB2_HOST_CONTROLLER_PPI *Usb2HcPpi, + IN UINT8 PortNum, + IN UINT8 RetryIndex ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/ComponentName.c b/MdeModulePkg/Bus/Usb/UsbKbDxe/ComponentName.c index 6af1d7809f..536a11bb00 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/ComponentName.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "KeyBoard.h" // @@ -21,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUsbKeyboardComponent // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbKeyboardComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UsbKeyboardComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UsbKeyboardComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbKeyboardComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UsbKeyboardComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UsbKeyboardComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbKeyboardDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbKeyboardDriverNameTable[] = { { "eng;en", L"Usb Keyboard Driver" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -145,17 +143,18 @@ UsbKeyboardComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbKeyboardComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - USB_KB_DEV *UsbKbDev; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL *SimpleTxtIn; - EFI_USB_IO_PROTOCOL *UsbIoProtocol; + EFI_STATUS Status; + USB_KB_DEV *UsbKbDev; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *SimpleTxtIn; + EFI_USB_IO_PROTOCOL *UsbIoProtocol; + // // This is a device driver, so ChildHandle must be NULL. // @@ -169,7 +168,7 @@ UsbKeyboardComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIoProtocol, + (VOID **)&UsbIoProtocol, gUsbKeyboardDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -188,13 +187,14 @@ UsbKeyboardComponentNameGetControllerName ( if (Status != EFI_ALREADY_STARTED) { return EFI_UNSUPPORTED; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, &gEfiSimpleTextInProtocolGuid, - (VOID **) &SimpleTxtIn, + (VOID **)&SimpleTxtIn, gUsbKeyboardDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -213,5 +213,4 @@ UsbKeyboardComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gUsbKeyboardComponentName) ); - } diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c index 9d1798278e..e889f422bb 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c @@ -13,7 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // USB Keyboard Driver Global Variables // -EFI_DRIVER_BINDING_PROTOCOL gUsbKeyboardDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUsbKeyboardDriverBinding = { USBKeyboardDriverBindingSupported, USBKeyboardDriverBindingStart, USBKeyboardDriverBindingStop, @@ -37,11 +37,11 @@ EFI_DRIVER_BINDING_PROTOCOL gUsbKeyboardDriverBinding = { EFI_STATUS EFIAPI USBKeyboardDriverBindingEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, @@ -70,13 +70,13 @@ USBKeyboardDriverBindingEntryPoint ( EFI_STATUS EFIAPI USBKeyboardDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; // // Check if USB I/O Protocol is attached on the controller handle. @@ -84,7 +84,7 @@ USBKeyboardDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -133,22 +133,22 @@ USBKeyboardDriverBindingSupported ( EFI_STATUS EFIAPI USBKeyboardDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; - USB_KB_DEV *UsbKeyboardDevice; - UINT8 EndpointNumber; - EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; - UINT8 Index; - UINT8 EndpointAddr; - UINT8 PollingInterval; - UINT8 PacketSize; - BOOLEAN Found; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + USB_KB_DEV *UsbKeyboardDevice; + UINT8 EndpointNumber; + EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; + UINT8 Index; + UINT8 EndpointAddr; + UINT8 PollingInterval; + UINT8 PacketSize; + BOOLEAN Found; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); // @@ -157,7 +157,7 @@ USBKeyboardDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -175,7 +175,7 @@ USBKeyboardDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &UsbKeyboardDevice->DevicePath, + (VOID **)&UsbKeyboardDevice->DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -184,6 +184,7 @@ USBKeyboardDriverBindingStart ( if (EFI_ERROR (Status)) { goto ErrorExit; } + // // Report that the USB keyboard is being enabled // @@ -219,7 +220,6 @@ USBKeyboardDriverBindingStart ( // Found = FALSE; for (Index = 0; Index < EndpointNumber; Index++) { - UsbIo->UsbGetEndpointDescriptor ( UsbIo, Index, @@ -227,11 +227,12 @@ USBKeyboardDriverBindingStart ( ); if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && - ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) + { // // We only care interrupt endpoint here // - CopyMem(&UsbKeyboardDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof(EndpointDescriptor)); + CopyMem (&UsbKeyboardDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof (EndpointDescriptor)); Found = TRUE; break; } @@ -258,9 +259,9 @@ USBKeyboardDriverBindingStart ( UsbKeyboardDevice->DevicePath ); - UsbKeyboardDevice->Signature = USB_KB_DEV_SIGNATURE; - UsbKeyboardDevice->SimpleInput.Reset = USBKeyboardReset; - UsbKeyboardDevice->SimpleInput.ReadKeyStroke = USBKeyboardReadKeyStroke; + UsbKeyboardDevice->Signature = USB_KB_DEV_SIGNATURE; + UsbKeyboardDevice->SimpleInput.Reset = USBKeyboardReset; + UsbKeyboardDevice->SimpleInput.ReadKeyStroke = USBKeyboardReadKeyStroke; UsbKeyboardDevice->SimpleInputEx.Reset = USBKeyboardResetEx; UsbKeyboardDevice->SimpleInputEx.ReadKeyStrokeEx = USBKeyboardReadKeyStrokeEx; @@ -280,6 +281,7 @@ USBKeyboardDriverBindingStart ( if (!EFI_ERROR (Status)) { Status = gBS->SetTimer (UsbKeyboardDevice->TimerEvent, TimerPeriodic, KEYBOARD_TIMER_INTERVAL); } + if (EFI_ERROR (Status)) { goto ErrorExit; } @@ -338,27 +340,26 @@ USBKeyboardDriverBindingStart ( } UsbKeyboardDevice->ControllerHandle = Controller; - Status = InitKeyboardLayout (UsbKeyboardDevice); + Status = InitKeyboardLayout (UsbKeyboardDevice); if (EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( - Controller, - &gEfiSimpleTextInProtocolGuid, - &UsbKeyboardDevice->SimpleInput, - &gEfiSimpleTextInputExProtocolGuid, - &UsbKeyboardDevice->SimpleInputEx, - NULL - ); + Controller, + &gEfiSimpleTextInProtocolGuid, + &UsbKeyboardDevice->SimpleInput, + &gEfiSimpleTextInputExProtocolGuid, + &UsbKeyboardDevice->SimpleInputEx, + NULL + ); goto ErrorExit; } - // // Reset USB Keyboard Device exhaustively. // Status = UsbKeyboardDevice->SimpleInputEx.Reset ( - &UsbKeyboardDevice->SimpleInputEx, - TRUE - ); + &UsbKeyboardDevice->SimpleInputEx, + TRUE + ); if (EFI_ERROR (Status)) { gBS->UninstallMultipleProtocolInterfaces ( Controller, @@ -376,7 +377,7 @@ USBKeyboardDriverBindingStart ( // EndpointAddr = UsbKeyboardDevice->IntEndpointDescriptor.EndpointAddress; PollingInterval = UsbKeyboardDevice->IntEndpointDescriptor.Interval; - PacketSize = (UINT8) (UsbKeyboardDevice->IntEndpointDescriptor.MaxPacketSize); + PacketSize = (UINT8)(UsbKeyboardDevice->IntEndpointDescriptor.MaxPacketSize); Status = UsbIo->UsbAsyncInterruptTransfer ( UsbIo, @@ -419,30 +420,36 @@ USBKeyboardDriverBindingStart ( gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; -// -// Error handler -// + // + // Error handler + // ErrorExit: if (UsbKeyboardDevice != NULL) { if (UsbKeyboardDevice->TimerEvent != NULL) { gBS->CloseEvent (UsbKeyboardDevice->TimerEvent); } + if (UsbKeyboardDevice->SimpleInput.WaitForKey != NULL) { gBS->CloseEvent (UsbKeyboardDevice->SimpleInput.WaitForKey); } + if (UsbKeyboardDevice->SimpleInputEx.WaitForKeyEx != NULL) { gBS->CloseEvent (UsbKeyboardDevice->SimpleInputEx.WaitForKeyEx); } + if (UsbKeyboardDevice->KeyNotifyProcessEvent != NULL) { gBS->CloseEvent (UsbKeyboardDevice->KeyNotifyProcessEvent); } + if (UsbKeyboardDevice->KeyboardLayoutEvent != NULL) { ReleaseKeyboardLayoutResources (UsbKeyboardDevice); gBS->CloseEvent (UsbKeyboardDevice->KeyboardLayoutEvent); } + FreePool (UsbKeyboardDevice); UsbKeyboardDevice = NULL; } + gBS->CloseProtocol ( Controller, &gEfiUsbIoProtocolGuid, @@ -454,10 +461,8 @@ ErrorExit1: gBS->RestoreTPL (OldTpl); return Status; - } - /** Stop the USB keyboard device handled by this driver. @@ -476,20 +481,20 @@ ErrorExit1: EFI_STATUS EFIAPI USBKeyboardDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL *SimpleInput; - USB_KB_DEV *UsbKeyboardDevice; + EFI_STATUS Status; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL *SimpleInput; + USB_KB_DEV *UsbKeyboardDevice; Status = gBS->OpenProtocol ( Controller, &gEfiSimpleTextInProtocolGuid, - (VOID **) &SimpleInput, + (VOID **)&SimpleInput, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -593,8 +598,8 @@ USBKeyboardDriverBindingStop ( **/ EFI_STATUS USBKeyboardReadKeyStrokeWorker ( - IN OUT USB_KB_DEV *UsbKeyboardDevice, - OUT EFI_KEY_DATA *KeyData + IN OUT USB_KB_DEV *UsbKeyboardDevice, + OUT EFI_KEY_DATA *KeyData ) { if (KeyData == NULL) { @@ -630,12 +635,12 @@ USBKeyboardReadKeyStrokeWorker ( EFI_STATUS EFIAPI USBKeyboardReset ( - IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - USB_KB_DEV *UsbKeyboardDevice; + EFI_STATUS Status; + USB_KB_DEV *UsbKeyboardDevice; UsbKeyboardDevice = USB_KB_DEV_FROM_THIS (This); @@ -676,7 +681,6 @@ USBKeyboardReset ( return EFI_SUCCESS; } - /** Reads the next keystroke from the input device. @@ -693,13 +697,13 @@ USBKeyboardReset ( EFI_STATUS EFIAPI USBKeyboardReadKeyStroke ( - IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, - OUT EFI_INPUT_KEY *Key + IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, + OUT EFI_INPUT_KEY *Key ) { - USB_KB_DEV *UsbKeyboardDevice; - EFI_STATUS Status; - EFI_KEY_DATA KeyData; + USB_KB_DEV *UsbKeyboardDevice; + EFI_STATUS Status; + EFI_KEY_DATA KeyData; UsbKeyboardDevice = USB_KB_DEV_FROM_THIS (This); @@ -713,21 +717,23 @@ USBKeyboardReadKeyStroke ( if (EFI_ERROR (Status)) { return Status; } + // // SimpleTextIn Protocol doesn't support partial keystroke; // - if (KeyData.Key.ScanCode == CHAR_NULL && KeyData.Key.UnicodeChar == SCAN_NULL) { + if ((KeyData.Key.ScanCode == CHAR_NULL) && (KeyData.Key.UnicodeChar == SCAN_NULL)) { continue; } + // // Translate the CTRL-Alpha characters to their corresponding control value // (ctrl-a = 0x0001 through ctrl-Z = 0x001A) // if ((KeyData.KeyState.KeyShiftState & (EFI_LEFT_CONTROL_PRESSED | EFI_RIGHT_CONTROL_PRESSED)) != 0) { - if (KeyData.Key.UnicodeChar >= L'a' && KeyData.Key.UnicodeChar <= L'z') { - KeyData.Key.UnicodeChar = (CHAR16) (KeyData.Key.UnicodeChar - L'a' + 1); - } else if (KeyData.Key.UnicodeChar >= L'A' && KeyData.Key.UnicodeChar <= L'Z') { - KeyData.Key.UnicodeChar = (CHAR16) (KeyData.Key.UnicodeChar - L'A' + 1); + if ((KeyData.Key.UnicodeChar >= L'a') && (KeyData.Key.UnicodeChar <= L'z')) { + KeyData.Key.UnicodeChar = (CHAR16)(KeyData.Key.UnicodeChar - L'a' + 1); + } else if ((KeyData.Key.UnicodeChar >= L'A') && (KeyData.Key.UnicodeChar <= L'Z')) { + KeyData.Key.UnicodeChar = (CHAR16)(KeyData.Key.UnicodeChar - L'A' + 1); } } @@ -736,7 +742,6 @@ USBKeyboardReadKeyStroke ( } } - /** Event notification function registered for EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL.WaitForKeyEx and EFI_SIMPLE_TEXT_INPUT_PROTOCOL.WaitForKey. @@ -748,15 +753,15 @@ USBKeyboardReadKeyStroke ( VOID EFIAPI USBKeyboardWaitForKey ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_KB_DEV *UsbKeyboardDevice; - EFI_KEY_DATA KeyData; - EFI_TPL OldTpl; + USB_KB_DEV *UsbKeyboardDevice; + EFI_KEY_DATA KeyData; + EFI_TPL OldTpl; - UsbKeyboardDevice = (USB_KB_DEV *) Context; + UsbKeyboardDevice = (USB_KB_DEV *)Context; // // Enter critical section @@ -778,13 +783,15 @@ USBKeyboardWaitForKey ( UsbKeyboardDevice->EfiKeyQueue.Buffer[UsbKeyboardDevice->EfiKeyQueue.Head], sizeof (EFI_KEY_DATA) ); - if (KeyData.Key.ScanCode == SCAN_NULL && KeyData.Key.UnicodeChar == CHAR_NULL) { + if ((KeyData.Key.ScanCode == SCAN_NULL) && (KeyData.Key.UnicodeChar == CHAR_NULL)) { Dequeue (&UsbKeyboardDevice->EfiKeyQueue, &KeyData, sizeof (EFI_KEY_DATA)); continue; } + gBS->SignalEvent (Event); break; } + // // Leave critical section and return // @@ -800,16 +807,16 @@ USBKeyboardWaitForKey ( VOID EFIAPI USBKeyboardTimerHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - USB_KB_DEV *UsbKeyboardDevice; - UINT8 KeyCode; - EFI_KEY_DATA KeyData; + EFI_STATUS Status; + USB_KB_DEV *UsbKeyboardDevice; + UINT8 KeyCode; + EFI_KEY_DATA KeyData; - UsbKeyboardDevice = (USB_KB_DEV *) Context; + UsbKeyboardDevice = (USB_KB_DEV *)Context; // // Fetch raw data from the USB keyboard buffer, @@ -817,7 +824,7 @@ USBKeyboardTimerHandler ( // Status = USBParseKey (UsbKeyboardDevice, &KeyCode); if (EFI_ERROR (Status)) { - return ; + return; } // @@ -825,7 +832,7 @@ USBKeyboardTimerHandler ( // Status = UsbKeyCodeToEfiInputKey (UsbKeyboardDevice, KeyCode, &KeyData); if (EFI_ERROR (Status)) { - return ; + return; } // @@ -845,17 +852,18 @@ USBKeyboardTimerHandler ( **/ EFI_STATUS KbdFreeNotifyList ( - IN OUT LIST_ENTRY *NotifyList + IN OUT LIST_ENTRY *NotifyList ) { - KEYBOARD_CONSOLE_IN_EX_NOTIFY *NotifyNode; - LIST_ENTRY *Link; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *NotifyNode; + LIST_ENTRY *Link; if (NotifyList == NULL) { return EFI_INVALID_PARAMETER; } + while (!IsListEmpty (NotifyList)) { - Link = GetFirstNode (NotifyList); + Link = GetFirstNode (NotifyList); NotifyNode = CR (Link, KEYBOARD_CONSOLE_IN_EX_NOTIFY, NotifyEntry, USB_KB_CONSOLE_IN_EX_NOTIFY_SIGNATURE); RemoveEntryList (Link); FreePool (NotifyNode); @@ -883,19 +891,23 @@ IsKeyRegistered ( ASSERT (RegsiteredData != NULL && InputData != NULL); if ((RegsiteredData->Key.ScanCode != InputData->Key.ScanCode) || - (RegsiteredData->Key.UnicodeChar != InputData->Key.UnicodeChar)) { + (RegsiteredData->Key.UnicodeChar != InputData->Key.UnicodeChar)) + { return FALSE; } // // Assume KeyShiftState/KeyToggleState = 0 in Registered key data means these state could be ignored. // - if (RegsiteredData->KeyState.KeyShiftState != 0 && - RegsiteredData->KeyState.KeyShiftState != InputData->KeyState.KeyShiftState) { + if ((RegsiteredData->KeyState.KeyShiftState != 0) && + (RegsiteredData->KeyState.KeyShiftState != InputData->KeyState.KeyShiftState)) + { return FALSE; } - if (RegsiteredData->KeyState.KeyToggleState != 0 && - RegsiteredData->KeyState.KeyToggleState != InputData->KeyState.KeyToggleState) { + + if ((RegsiteredData->KeyState.KeyToggleState != 0) && + (RegsiteredData->KeyState.KeyToggleState != InputData->KeyState.KeyToggleState)) + { return FALSE; } @@ -905,6 +917,7 @@ IsKeyRegistered ( // // Simple Text Input Ex protocol functions // + /** Resets the input device hardware. @@ -934,8 +947,8 @@ USBKeyboardResetEx ( IN BOOLEAN ExtendedVerification ) { - EFI_STATUS Status; - USB_KB_DEV *UsbKeyboardDevice; + EFI_STATUS Status; + USB_KB_DEV *UsbKeyboardDevice; UsbKeyboardDevice = TEXT_INPUT_EX_USB_KB_DEV_FROM_THIS (This); @@ -948,7 +961,6 @@ USBKeyboardResetEx ( UsbKeyboardDevice->KeyState.KeyToggleState = EFI_TOGGLE_STATE_VALID; return EFI_SUCCESS; - } /** @@ -968,11 +980,11 @@ USBKeyboardResetEx ( EFI_STATUS EFIAPI USBKeyboardReadKeyStrokeEx ( - IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, - OUT EFI_KEY_DATA *KeyData + IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, + OUT EFI_KEY_DATA *KeyData ) { - USB_KB_DEV *UsbKeyboardDevice; + USB_KB_DEV *UsbKeyboardDevice; if (KeyData == NULL) { return EFI_INVALID_PARAMETER; @@ -981,7 +993,6 @@ USBKeyboardReadKeyStrokeEx ( UsbKeyboardDevice = TEXT_INPUT_EX_USB_KB_DEV_FROM_THIS (This); return USBKeyboardReadKeyStrokeWorker (UsbKeyboardDevice, KeyData); - } /** @@ -1005,7 +1016,7 @@ USBKeyboardSetState ( IN EFI_KEY_TOGGLE_STATE *KeyToggleState ) { - USB_KB_DEV *UsbKeyboardDevice; + USB_KB_DEV *UsbKeyboardDevice; if (KeyToggleState == NULL) { return EFI_INVALID_PARAMETER; @@ -1014,7 +1025,8 @@ USBKeyboardSetState ( UsbKeyboardDevice = TEXT_INPUT_EX_USB_KB_DEV_FROM_THIS (This); if (((UsbKeyboardDevice->KeyState.KeyToggleState & EFI_TOGGLE_STATE_VALID) != EFI_TOGGLE_STATE_VALID) || - ((*KeyToggleState & EFI_TOGGLE_STATE_VALID) != EFI_TOGGLE_STATE_VALID)) { + ((*KeyToggleState & EFI_TOGGLE_STATE_VALID) != EFI_TOGGLE_STATE_VALID)) + { return EFI_UNSUPPORTED; } @@ -1022,20 +1034,23 @@ USBKeyboardSetState ( // Update the status light // - UsbKeyboardDevice->ScrollOn = FALSE; - UsbKeyboardDevice->NumLockOn = FALSE; - UsbKeyboardDevice->CapsOn = FALSE; + UsbKeyboardDevice->ScrollOn = FALSE; + UsbKeyboardDevice->NumLockOn = FALSE; + UsbKeyboardDevice->CapsOn = FALSE; UsbKeyboardDevice->IsSupportPartialKey = FALSE; if ((*KeyToggleState & EFI_SCROLL_LOCK_ACTIVE) == EFI_SCROLL_LOCK_ACTIVE) { UsbKeyboardDevice->ScrollOn = TRUE; } + if ((*KeyToggleState & EFI_NUM_LOCK_ACTIVE) == EFI_NUM_LOCK_ACTIVE) { UsbKeyboardDevice->NumLockOn = TRUE; } + if ((*KeyToggleState & EFI_CAPS_LOCK_ACTIVE) == EFI_CAPS_LOCK_ACTIVE) { UsbKeyboardDevice->CapsOn = TRUE; } + if ((*KeyToggleState & EFI_KEY_STATE_EXPOSED) == EFI_KEY_STATE_EXPOSED) { UsbKeyboardDevice->IsSupportPartialKey = TRUE; } @@ -1045,7 +1060,6 @@ USBKeyboardSetState ( UsbKeyboardDevice->KeyState.KeyToggleState = *KeyToggleState; return EFI_SUCCESS; - } /** @@ -1076,13 +1090,13 @@ USBKeyboardRegisterKeyNotify ( OUT VOID **NotifyHandle ) { - USB_KB_DEV *UsbKeyboardDevice; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *NewNotify; - LIST_ENTRY *Link; - LIST_ENTRY *NotifyList; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + USB_KB_DEV *UsbKeyboardDevice; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *NewNotify; + LIST_ENTRY *Link; + LIST_ENTRY *NotifyList; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; - if (KeyData == NULL || NotifyHandle == NULL || KeyNotificationFunction == NULL) { + if ((KeyData == NULL) || (NotifyHandle == NULL) || (KeyNotificationFunction == NULL)) { return EFI_INVALID_PARAMETER; } @@ -1095,7 +1109,8 @@ USBKeyboardRegisterKeyNotify ( for (Link = GetFirstNode (NotifyList); !IsNull (NotifyList, Link); - Link = GetNextNode (NotifyList, Link)) { + Link = GetNextNode (NotifyList, Link)) + { CurrentNotify = CR ( Link, KEYBOARD_CONSOLE_IN_EX_NOTIFY, @@ -1113,7 +1128,7 @@ USBKeyboardRegisterKeyNotify ( // // Allocate resource to save the notification function // - NewNotify = (KEYBOARD_CONSOLE_IN_EX_NOTIFY *) AllocateZeroPool (sizeof (KEYBOARD_CONSOLE_IN_EX_NOTIFY)); + NewNotify = (KEYBOARD_CONSOLE_IN_EX_NOTIFY *)AllocateZeroPool (sizeof (KEYBOARD_CONSOLE_IN_EX_NOTIFY)); if (NewNotify == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -1123,11 +1138,9 @@ USBKeyboardRegisterKeyNotify ( CopyMem (&NewNotify->KeyData, KeyData, sizeof (EFI_KEY_DATA)); InsertTailList (&UsbKeyboardDevice->NotifyList, &NewNotify->NotifyEntry); - *NotifyHandle = NewNotify; return EFI_SUCCESS; - } /** @@ -1147,10 +1160,10 @@ USBKeyboardUnregisterKeyNotify ( IN VOID *NotificationHandle ) { - USB_KB_DEV *UsbKeyboardDevice; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; - LIST_ENTRY *Link; - LIST_ENTRY *NotifyList; + USB_KB_DEV *UsbKeyboardDevice; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + LIST_ENTRY *Link; + LIST_ENTRY *NotifyList; if (NotificationHandle == NULL) { return EFI_INVALID_PARAMETER; @@ -1164,7 +1177,8 @@ USBKeyboardUnregisterKeyNotify ( NotifyList = &UsbKeyboardDevice->NotifyList; for (Link = GetFirstNode (NotifyList); !IsNull (NotifyList, Link); - Link = GetNextNode (NotifyList, Link)) { + Link = GetNextNode (NotifyList, Link)) + { CurrentNotify = CR ( Link, KEYBOARD_CONSOLE_IN_EX_NOTIFY, @@ -1197,19 +1211,19 @@ USBKeyboardUnregisterKeyNotify ( VOID EFIAPI KeyNotifyProcessHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - USB_KB_DEV *UsbKeyboardDevice; - EFI_KEY_DATA KeyData; - LIST_ENTRY *Link; - LIST_ENTRY *NotifyList; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; - EFI_TPL OldTpl; + EFI_STATUS Status; + USB_KB_DEV *UsbKeyboardDevice; + EFI_KEY_DATA KeyData; + LIST_ENTRY *Link; + LIST_ENTRY *NotifyList; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + EFI_TPL OldTpl; - UsbKeyboardDevice = (USB_KB_DEV *) Context; + UsbKeyboardDevice = (USB_KB_DEV *)Context; // // Invoke notification functions. @@ -1228,6 +1242,7 @@ KeyNotifyProcessHandler ( if (EFI_ERROR (Status)) { break; } + for (Link = GetFirstNode (NotifyList); !IsNull (NotifyList, Link); Link = GetNextNode (NotifyList, Link)) { CurrentNotify = CR (Link, KEYBOARD_CONSOLE_IN_EX_NOTIFY, NotifyEntry, USB_KB_CONSOLE_IN_EX_NOTIFY_SIGNATURE); if (IsKeyRegistered (&CurrentNotify->KeyData, &KeyData)) { @@ -1236,4 +1251,3 @@ KeyNotifyProcessHandler ( } } } - diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h index 852e43390d..a9dfeafd6f 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h @@ -5,10 +5,10 @@ Copyright (c) 2004 - 2017, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef _EFI_USB_KB_H_ #define _EFI_USB_KB_H_ - #include #include @@ -34,59 +34,59 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define KEYBOARD_TIMER_INTERVAL 200000 // 0.02s +#define KEYBOARD_TIMER_INTERVAL 200000 // 0.02s -#define MAX_KEY_ALLOWED 32 +#define MAX_KEY_ALLOWED 32 -#define HZ 1000 * 1000 * 10 -#define USBKBD_REPEAT_DELAY ((HZ) / 2) -#define USBKBD_REPEAT_RATE ((HZ) / 50) +#define HZ 1000 * 1000 * 10 +#define USBKBD_REPEAT_DELAY ((HZ) / 2) +#define USBKBD_REPEAT_RATE ((HZ) / 50) -#define CLASS_HID 3 -#define SUBCLASS_BOOT 1 -#define PROTOCOL_KEYBOARD 1 +#define CLASS_HID 3 +#define SUBCLASS_BOOT 1 +#define PROTOCOL_KEYBOARD 1 -#define BOOT_PROTOCOL 0 -#define REPORT_PROTOCOL 1 +#define BOOT_PROTOCOL 0 +#define REPORT_PROTOCOL 1 typedef struct { - BOOLEAN Down; - UINT8 KeyCode; + BOOLEAN Down; + UINT8 KeyCode; } USB_KEY; typedef struct { - VOID *Buffer[MAX_KEY_ALLOWED + 1]; - UINTN Head; - UINTN Tail; - UINTN ItemSize; + VOID *Buffer[MAX_KEY_ALLOWED + 1]; + UINTN Head; + UINTN Tail; + UINTN ItemSize; } USB_SIMPLE_QUEUE; -#define USB_KB_DEV_SIGNATURE SIGNATURE_32 ('u', 'k', 'b', 'd') -#define USB_KB_CONSOLE_IN_EX_NOTIFY_SIGNATURE SIGNATURE_32 ('u', 'k', 'b', 'x') +#define USB_KB_DEV_SIGNATURE SIGNATURE_32 ('u', 'k', 'b', 'd') +#define USB_KB_CONSOLE_IN_EX_NOTIFY_SIGNATURE SIGNATURE_32 ('u', 'k', 'b', 'x') typedef struct _KEYBOARD_CONSOLE_IN_EX_NOTIFY { - UINTN Signature; - EFI_KEY_DATA KeyData; - EFI_KEY_NOTIFY_FUNCTION KeyNotificationFn; - LIST_ENTRY NotifyEntry; + UINTN Signature; + EFI_KEY_DATA KeyData; + EFI_KEY_NOTIFY_FUNCTION KeyNotificationFn; + LIST_ENTRY NotifyEntry; } KEYBOARD_CONSOLE_IN_EX_NOTIFY; #define USB_NS_KEY_SIGNATURE SIGNATURE_32 ('u', 'n', 's', 'k') typedef struct { - UINTN Signature; - LIST_ENTRY Link; + UINTN Signature; + LIST_ENTRY Link; // // The number of EFI_NS_KEY_MODIFIER children definitions // - UINTN KeyCount; + UINTN KeyCount; // // NsKey[0] : Non-spacing key // NsKey[1] ~ NsKey[KeyCount] : Physical keys // - EFI_KEY_DESCRIPTOR *NsKey; + EFI_KEY_DESCRIPTOR *NsKey; } USB_NS_KEY; #define USB_NS_KEY_FORM_FROM_LINK(a) CR (a, USB_NS_KEY, Link, USB_NS_KEY_SIGNATURE) @@ -95,64 +95,64 @@ typedef struct { /// Structure to describe USB keyboard device /// typedef struct { - UINTN Signature; - EFI_HANDLE ControllerHandle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_EVENT DelayedRecoveryEvent; - EFI_SIMPLE_TEXT_INPUT_PROTOCOL SimpleInput; - EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL SimpleInputEx; - EFI_USB_IO_PROTOCOL *UsbIo; - - EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; - EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; - - USB_SIMPLE_QUEUE UsbKeyQueue; - USB_SIMPLE_QUEUE EfiKeyQueue; - USB_SIMPLE_QUEUE EfiKeyQueueForNotify; - BOOLEAN CtrlOn; - BOOLEAN AltOn; - BOOLEAN ShiftOn; - BOOLEAN NumLockOn; - BOOLEAN CapsOn; - BOOLEAN ScrollOn; - UINT8 LastKeyCodeArray[8]; - UINT8 CurKeyCode; - - EFI_EVENT TimerEvent; - - UINT8 RepeatKey; - EFI_EVENT RepeatTimer; - - EFI_UNICODE_STRING_TABLE *ControllerNameTable; - - BOOLEAN LeftCtrlOn; - BOOLEAN LeftAltOn; - BOOLEAN LeftShiftOn; - BOOLEAN LeftLogoOn; - BOOLEAN RightCtrlOn; - BOOLEAN RightAltOn; - BOOLEAN RightShiftOn; - BOOLEAN RightLogoOn; - BOOLEAN MenuKeyOn; - BOOLEAN SysReqOn; - BOOLEAN AltGrOn; - - BOOLEAN IsSupportPartialKey; - - EFI_KEY_STATE KeyState; + UINTN Signature; + EFI_HANDLE ControllerHandle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_EVENT DelayedRecoveryEvent; + EFI_SIMPLE_TEXT_INPUT_PROTOCOL SimpleInput; + EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL SimpleInputEx; + EFI_USB_IO_PROTOCOL *UsbIo; + + EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; + EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; + + USB_SIMPLE_QUEUE UsbKeyQueue; + USB_SIMPLE_QUEUE EfiKeyQueue; + USB_SIMPLE_QUEUE EfiKeyQueueForNotify; + BOOLEAN CtrlOn; + BOOLEAN AltOn; + BOOLEAN ShiftOn; + BOOLEAN NumLockOn; + BOOLEAN CapsOn; + BOOLEAN ScrollOn; + UINT8 LastKeyCodeArray[8]; + UINT8 CurKeyCode; + + EFI_EVENT TimerEvent; + + UINT8 RepeatKey; + EFI_EVENT RepeatTimer; + + EFI_UNICODE_STRING_TABLE *ControllerNameTable; + + BOOLEAN LeftCtrlOn; + BOOLEAN LeftAltOn; + BOOLEAN LeftShiftOn; + BOOLEAN LeftLogoOn; + BOOLEAN RightCtrlOn; + BOOLEAN RightAltOn; + BOOLEAN RightShiftOn; + BOOLEAN RightLogoOn; + BOOLEAN MenuKeyOn; + BOOLEAN SysReqOn; + BOOLEAN AltGrOn; + + BOOLEAN IsSupportPartialKey; + + EFI_KEY_STATE KeyState; // // Notification function list // - LIST_ENTRY NotifyList; - EFI_EVENT KeyNotifyProcessEvent; + LIST_ENTRY NotifyList; + EFI_EVENT KeyNotifyProcessEvent; // // Non-spacing key list // - LIST_ENTRY NsKeyList; - USB_NS_KEY *CurrentNsKey; - EFI_KEY_DESCRIPTOR *KeyConvertionTable; - EFI_EVENT KeyboardLayoutEvent; + LIST_ENTRY NsKeyList; + USB_NS_KEY *CurrentNsKey; + EFI_KEY_DESCRIPTOR *KeyConvertionTable; + EFI_EVENT KeyboardLayoutEvent; } USB_KB_DEV; // @@ -175,23 +175,24 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gUsbKeyboardComponentName2; // So the number of valid non-modifier USB keycodes is 0x62, and the number of // valid keycodes is 0x6A. // -#define NUMBER_OF_VALID_NON_MODIFIER_USB_KEYCODE 0x62 -#define NUMBER_OF_VALID_USB_KEYCODE 0x6A +#define NUMBER_OF_VALID_NON_MODIFIER_USB_KEYCODE 0x62 +#define NUMBER_OF_VALID_USB_KEYCODE 0x6A // // 0x0 to 0x3 are reserved for typical keyboard status or keyboard errors. // -#define USBKBD_VALID_KEYCODE(Key) ((UINT8) (Key) > 3) +#define USBKBD_VALID_KEYCODE(Key) ((UINT8) (Key) > 3) typedef struct { - UINT8 NumLock : 1; - UINT8 CapsLock : 1; - UINT8 ScrollLock : 1; - UINT8 Resrvd : 5; + UINT8 NumLock : 1; + UINT8 CapsLock : 1; + UINT8 ScrollLock : 1; + UINT8 Resrvd : 5; } LED_MAP; // // Functions of Driver Binding Protocol // + /** Check whether USB keyboard driver supports this device. @@ -206,9 +207,9 @@ typedef struct { EFI_STATUS EFIAPI USBKeyboardDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -231,9 +232,9 @@ USBKeyboardDriverBindingSupported ( EFI_STATUS EFIAPI USBKeyboardDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -254,15 +255,16 @@ USBKeyboardDriverBindingStart ( EFI_STATUS EFIAPI USBKeyboardDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // // EFI Component Name Functions // + /** Retrieves a Unicode string that is the user readable name of the driver. @@ -366,16 +368,17 @@ UsbKeyboardComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbKeyboardComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); // // Functions of Simple Text Input Protocol // + /** Reset the input device and optionally run diagnostics @@ -394,8 +397,8 @@ UsbKeyboardComponentNameGetControllerName ( EFI_STATUS EFIAPI USBKeyboardReset ( - IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -414,13 +417,14 @@ USBKeyboardReset ( EFI_STATUS EFIAPI USBKeyboardReadKeyStroke ( - IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, - OUT EFI_INPUT_KEY *Key + IN EFI_SIMPLE_TEXT_INPUT_PROTOCOL *This, + OUT EFI_INPUT_KEY *Key ); // // Simple Text Input Ex protocol functions // + /** Resets the input device hardware. @@ -467,8 +471,8 @@ USBKeyboardResetEx ( EFI_STATUS EFIAPI USBKeyboardReadKeyStrokeEx ( - IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, - OUT EFI_KEY_DATA *KeyData + IN EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *This, + OUT EFI_KEY_DATA *KeyData ); /** @@ -549,8 +553,8 @@ USBKeyboardUnregisterKeyNotify ( VOID EFIAPI USBKeyboardWaitForKey ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -564,7 +568,7 @@ USBKeyboardWaitForKey ( **/ EFI_STATUS KbdFreeNotifyList ( - IN OUT LIST_ENTRY *NotifyList + IN OUT LIST_ENTRY *NotifyList ); /** @@ -592,8 +596,8 @@ IsKeyRegistered ( VOID EFIAPI USBKeyboardTimerHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -605,9 +609,8 @@ USBKeyboardTimerHandler ( VOID EFIAPI KeyNotifyProcessHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); #endif - diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.c b/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.c index 5faf82ea57..5a94a4dda7 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.c +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.c @@ -18,125 +18,125 @@ USB_KEYBOARD_LAYOUT_PACK_BIN mUsbKeyboardLayoutBin = { sizeof (USB_KEYBOARD_LAYOUT_PACK_BIN) - sizeof (UINT32), EFI_HII_PACKAGE_KEYBOARD_LAYOUT }, - 1, // LayoutCount - sizeof (USB_KEYBOARD_LAYOUT_PACK_BIN) - sizeof (UINT32) - sizeof (EFI_HII_PACKAGE_HEADER) - sizeof (UINT16), // LayoutLength - USB_KEYBOARD_LAYOUT_KEY_GUID, // KeyGuid + 1, // LayoutCount + sizeof (USB_KEYBOARD_LAYOUT_PACK_BIN) - sizeof (UINT32) - sizeof (EFI_HII_PACKAGE_HEADER) - sizeof (UINT16), // LayoutLength + USB_KEYBOARD_LAYOUT_KEY_GUID, // KeyGuid sizeof (UINT16) + sizeof (EFI_GUID) + sizeof (UINT32) + sizeof (UINT8) + (USB_KEYBOARD_KEY_COUNT * sizeof (EFI_KEY_DESCRIPTOR)), // LayoutDescriptorStringOffset - USB_KEYBOARD_KEY_COUNT, // DescriptorCount + USB_KEYBOARD_KEY_COUNT, // DescriptorCount { // // EFI_KEY_DESCRIPTOR (total number is USB_KEYBOARD_KEY_COUNT) // - {EfiKeyC1, 'a', 'A', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB5, 'b', 'B', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB3, 'c', 'C', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC3, 'd', 'D', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD3, 'e', 'E', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC4, 'f', 'F', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC5, 'g', 'G', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC6, 'h', 'H', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD8, 'i', 'I', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC7, 'j', 'J', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC8, 'k', 'K', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC9, 'l', 'L', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB7, 'm', 'M', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB6, 'n', 'N', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD9, 'o', 'O', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD10, 'p', 'P', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD1, 'q', 'Q', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD4, 'r', 'R', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyC2, 's', 'S', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD5, 't', 'T', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD7, 'u', 'U', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB4, 'v', 'V', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD2, 'w', 'W', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB2, 'x', 'X', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyD6, 'y', 'Y', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyB1, 'z', 'Z', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK}, - {EfiKeyE1, '1', '!', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE2, '2', '@', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE3, '3', '#', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE4, '4', '$', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE5, '5', '%', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE6, '6', '^', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE7, '7', '&', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE8, '8', '*', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE9, '9', '(', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE10, '0', ')', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyEnter, 0x0d, 0x0d, 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyEsc, 0x1b, 0x1b, 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyBackSpace, 0x08, 0x08, 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyTab, 0x09, 0x09, 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeySpaceBar, ' ', ' ', 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyE11, '-', '_', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE12, '=', '+', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyD11, '[', '{', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyD12, ']', '}', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyD13, '\\', '|', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyC12, '\\', '|', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyC10, ';', ':', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyC11, '\'', '"', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyE0, '`', '~', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyB8, ',', '<', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyB9, '.', '>', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyB10, '/', '?', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT}, - {EfiKeyCapsLock, 0x00, 0x00, 0, 0, EFI_CAPS_LOCK_MODIFIER, 0}, - {EfiKeyF1, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_ONE_MODIFIER, 0}, - {EfiKeyF2, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TWO_MODIFIER, 0}, - {EfiKeyF3, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_THREE_MODIFIER, 0}, - {EfiKeyF4, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_FOUR_MODIFIER, 0}, - {EfiKeyF5, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_FIVE_MODIFIER, 0}, - {EfiKeyF6, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_SIX_MODIFIER, 0}, - {EfiKeyF7, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_SEVEN_MODIFIER, 0}, - {EfiKeyF8, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_EIGHT_MODIFIER, 0}, - {EfiKeyF9, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_NINE_MODIFIER, 0}, - {EfiKeyF10, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TEN_MODIFIER, 0}, - {EfiKeyF11, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_ELEVEN_MODIFIER, 0}, - {EfiKeyF12, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TWELVE_MODIFIER, 0}, - {EfiKeyPrint, 0x00, 0x00, 0, 0, EFI_PRINT_MODIFIER, 0}, - {EfiKeySLck, 0x00, 0x00, 0, 0, EFI_SCROLL_LOCK_MODIFIER, 0}, - {EfiKeyPause, 0x00, 0x00, 0, 0, EFI_PAUSE_MODIFIER, 0}, - {EfiKeyIns, 0x00, 0x00, 0, 0, EFI_INSERT_MODIFIER, 0}, - {EfiKeyHome, 0x00, 0x00, 0, 0, EFI_HOME_MODIFIER, 0}, - {EfiKeyPgUp, 0x00, 0x00, 0, 0, EFI_PAGE_UP_MODIFIER, 0}, - {EfiKeyDel, 0x00, 0x00, 0, 0, EFI_DELETE_MODIFIER, 0}, - {EfiKeyEnd, 0x00, 0x00, 0, 0, EFI_END_MODIFIER, 0}, - {EfiKeyPgDn, 0x00, 0x00, 0, 0, EFI_PAGE_DOWN_MODIFIER, 0}, - {EfiKeyRightArrow, 0x00, 0x00, 0, 0, EFI_RIGHT_ARROW_MODIFIER, 0}, - {EfiKeyLeftArrow, 0x00, 0x00, 0, 0, EFI_LEFT_ARROW_MODIFIER, 0}, - {EfiKeyDownArrow, 0x00, 0x00, 0, 0, EFI_DOWN_ARROW_MODIFIER, 0}, - {EfiKeyUpArrow, 0x00, 0x00, 0, 0, EFI_UP_ARROW_MODIFIER, 0}, - {EfiKeyNLck, 0x00, 0x00, 0, 0, EFI_NUM_LOCK_MODIFIER, 0}, - {EfiKeySlash, '/', '/', 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyAsterisk, '*', '*', 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyMinus, '-', '-', 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyPlus, '+', '+', 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyEnter, 0x0d, 0x0d, 0, 0, EFI_NULL_MODIFIER, 0}, - {EfiKeyOne, '1', '1', 0, 0, EFI_END_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyTwo, '2', '2', 0, 0, EFI_DOWN_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyThree, '3', '3', 0, 0, EFI_PAGE_DOWN_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyFour, '4', '4', 0, 0, EFI_LEFT_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyFive, '5', '5', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeySix, '6', '6', 0, 0, EFI_RIGHT_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeySeven, '7', '7', 0, 0, EFI_HOME_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyEight, '8', '8', 0, 0, EFI_UP_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyNine, '9', '9', 0, 0, EFI_PAGE_UP_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyZero, '0', '0', 0, 0, EFI_INSERT_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyPeriod, '.', '.', 0, 0, EFI_DELETE_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK}, - {EfiKeyA4, 0x00, 0x00, 0, 0, EFI_MENU_MODIFIER, 0}, - {EfiKeyLCtrl, 0, 0, 0, 0, EFI_LEFT_CONTROL_MODIFIER, 0}, - {EfiKeyLShift, 0, 0, 0, 0, EFI_LEFT_SHIFT_MODIFIER, 0}, - {EfiKeyLAlt, 0, 0, 0, 0, EFI_LEFT_ALT_MODIFIER, 0}, - {EfiKeyA0, 0, 0, 0, 0, EFI_LEFT_LOGO_MODIFIER, 0}, - {EfiKeyRCtrl, 0, 0, 0, 0, EFI_RIGHT_CONTROL_MODIFIER, 0}, - {EfiKeyRShift, 0, 0, 0, 0, EFI_RIGHT_SHIFT_MODIFIER, 0}, - {EfiKeyA2, 0, 0, 0, 0, EFI_RIGHT_ALT_MODIFIER, 0}, - {EfiKeyA3, 0, 0, 0, 0, EFI_RIGHT_LOGO_MODIFIER, 0}, + { EfiKeyC1, 'a', 'A', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB5, 'b', 'B', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB3, 'c', 'C', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC3, 'd', 'D', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD3, 'e', 'E', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC4, 'f', 'F', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC5, 'g', 'G', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC6, 'h', 'H', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD8, 'i', 'I', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC7, 'j', 'J', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC8, 'k', 'K', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC9, 'l', 'L', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB7, 'm', 'M', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB6, 'n', 'N', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD9, 'o', 'O', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD10, 'p', 'P', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD1, 'q', 'Q', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD4, 'r', 'R', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyC2, 's', 'S', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD5, 't', 'T', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD7, 'u', 'U', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB4, 'v', 'V', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD2, 'w', 'W', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB2, 'x', 'X', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyD6, 'y', 'Y', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyB1, 'z', 'Z', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_CAPS_LOCK }, + { EfiKeyE1, '1', '!', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE2, '2', '@', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE3, '3', '#', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE4, '4', '$', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE5, '5', '%', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE6, '6', '^', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE7, '7', '&', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE8, '8', '*', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE9, '9', '(', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE10, '0', ')', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyEnter, 0x0d, 0x0d, 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyEsc, 0x1b, 0x1b, 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyBackSpace, 0x08, 0x08, 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyTab, 0x09, 0x09, 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeySpaceBar, ' ', ' ', 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyE11, '-', '_', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE12, '=', '+', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyD11, '[', '{', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyD12, ']', '}', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyD13, '\\', '|', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyC12, '\\', '|', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyC10, ';', ':', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyC11, '\'', '"', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyE0, '`', '~', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyB8, ',', '<', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyB9, '.', '>', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyB10, '/', '?', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT }, + { EfiKeyCapsLock, 0x00, 0x00, 0, 0, EFI_CAPS_LOCK_MODIFIER, 0 }, + { EfiKeyF1, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_ONE_MODIFIER, 0 }, + { EfiKeyF2, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TWO_MODIFIER, 0 }, + { EfiKeyF3, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_THREE_MODIFIER, 0 }, + { EfiKeyF4, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_FOUR_MODIFIER, 0 }, + { EfiKeyF5, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_FIVE_MODIFIER, 0 }, + { EfiKeyF6, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_SIX_MODIFIER, 0 }, + { EfiKeyF7, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_SEVEN_MODIFIER, 0 }, + { EfiKeyF8, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_EIGHT_MODIFIER, 0 }, + { EfiKeyF9, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_NINE_MODIFIER, 0 }, + { EfiKeyF10, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TEN_MODIFIER, 0 }, + { EfiKeyF11, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_ELEVEN_MODIFIER, 0 }, + { EfiKeyF12, 0x00, 0x00, 0, 0, EFI_FUNCTION_KEY_TWELVE_MODIFIER, 0 }, + { EfiKeyPrint, 0x00, 0x00, 0, 0, EFI_PRINT_MODIFIER, 0 }, + { EfiKeySLck, 0x00, 0x00, 0, 0, EFI_SCROLL_LOCK_MODIFIER, 0 }, + { EfiKeyPause, 0x00, 0x00, 0, 0, EFI_PAUSE_MODIFIER, 0 }, + { EfiKeyIns, 0x00, 0x00, 0, 0, EFI_INSERT_MODIFIER, 0 }, + { EfiKeyHome, 0x00, 0x00, 0, 0, EFI_HOME_MODIFIER, 0 }, + { EfiKeyPgUp, 0x00, 0x00, 0, 0, EFI_PAGE_UP_MODIFIER, 0 }, + { EfiKeyDel, 0x00, 0x00, 0, 0, EFI_DELETE_MODIFIER, 0 }, + { EfiKeyEnd, 0x00, 0x00, 0, 0, EFI_END_MODIFIER, 0 }, + { EfiKeyPgDn, 0x00, 0x00, 0, 0, EFI_PAGE_DOWN_MODIFIER, 0 }, + { EfiKeyRightArrow, 0x00, 0x00, 0, 0, EFI_RIGHT_ARROW_MODIFIER, 0 }, + { EfiKeyLeftArrow, 0x00, 0x00, 0, 0, EFI_LEFT_ARROW_MODIFIER, 0 }, + { EfiKeyDownArrow, 0x00, 0x00, 0, 0, EFI_DOWN_ARROW_MODIFIER, 0 }, + { EfiKeyUpArrow, 0x00, 0x00, 0, 0, EFI_UP_ARROW_MODIFIER, 0 }, + { EfiKeyNLck, 0x00, 0x00, 0, 0, EFI_NUM_LOCK_MODIFIER, 0 }, + { EfiKeySlash, '/', '/', 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyAsterisk, '*', '*', 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyMinus, '-', '-', 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyPlus, '+', '+', 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyEnter, 0x0d, 0x0d, 0, 0, EFI_NULL_MODIFIER, 0 }, + { EfiKeyOne, '1', '1', 0, 0, EFI_END_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyTwo, '2', '2', 0, 0, EFI_DOWN_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyThree, '3', '3', 0, 0, EFI_PAGE_DOWN_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyFour, '4', '4', 0, 0, EFI_LEFT_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyFive, '5', '5', 0, 0, EFI_NULL_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeySix, '6', '6', 0, 0, EFI_RIGHT_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeySeven, '7', '7', 0, 0, EFI_HOME_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyEight, '8', '8', 0, 0, EFI_UP_ARROW_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyNine, '9', '9', 0, 0, EFI_PAGE_UP_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyZero, '0', '0', 0, 0, EFI_INSERT_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyPeriod, '.', '.', 0, 0, EFI_DELETE_MODIFIER, EFI_AFFECTED_BY_STANDARD_SHIFT | EFI_AFFECTED_BY_NUM_LOCK }, + { EfiKeyA4, 0x00, 0x00, 0, 0, EFI_MENU_MODIFIER, 0 }, + { EfiKeyLCtrl, 0, 0, 0, 0, EFI_LEFT_CONTROL_MODIFIER, 0 }, + { EfiKeyLShift, 0, 0, 0, 0, EFI_LEFT_SHIFT_MODIFIER, 0 }, + { EfiKeyLAlt, 0, 0, 0, 0, EFI_LEFT_ALT_MODIFIER, 0 }, + { EfiKeyA0, 0, 0, 0, 0, EFI_LEFT_LOGO_MODIFIER, 0 }, + { EfiKeyRCtrl, 0, 0, 0, 0, EFI_RIGHT_CONTROL_MODIFIER, 0 }, + { EfiKeyRShift, 0, 0, 0, 0, EFI_RIGHT_SHIFT_MODIFIER, 0 }, + { EfiKeyA2, 0, 0, 0, 0, EFI_RIGHT_ALT_MODIFIER, 0 }, + { EfiKeyA3, 0, 0, 0, 0, EFI_RIGHT_LOGO_MODIFIER, 0 }, }, - 1, // DescriptionCount - {'e', 'n', '-', 'U', 'S'}, // RFC4646 language code - ' ', // Space - {'E', 'n', 'g', 'l', 'i', 's', 'h', ' ', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd', '\0'}, // DescriptionString[] + 1, // DescriptionCount + { 'e', 'n', '-', 'U', 'S' }, // RFC4646 language code + ' ', // Space + { 'E', 'n', 'g', 'l', 'i', 's', 'h', ' ', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd', '\0' }, // DescriptionString[] }; // @@ -144,7 +144,7 @@ USB_KEYBOARD_LAYOUT_PACK_BIN mUsbKeyboardLayoutBin = { // EFI_KEY is defined in UEFI spec. // USB Keycode is defined in USB HID Firmware spec. // -UINT8 EfiKeyToUsbKeyCodeConvertionTable[] = { +UINT8 EfiKeyToUsbKeyCodeConvertionTable[] = { 0xe0, // EfiKeyLCtrl 0xe3, // EfiKeyA0 0xe2, // EfiKeyLAlt @@ -256,7 +256,7 @@ UINT8 EfiKeyToUsbKeyCodeConvertionTable[] = { // Keyboard modifier value to EFI Scan Code conversion table // EFI Scan Code and the modifier values are defined in UEFI spec. // -UINT8 ModifierValueToEfiScanCodeConvertionTable[] = { +UINT8 ModifierValueToEfiScanCodeConvertionTable[] = { SCAN_NULL, // EFI_NULL_MODIFIER SCAN_NULL, // EFI_LEFT_CONTROL_MODIFIER SCAN_NULL, // EFI_RIGHT_CONTROL_MODIFIER @@ -314,12 +314,12 @@ UINT8 ModifierValueToEfiScanCodeConvertionTable[] = { **/ EFI_STATUS InstallDefaultKeyboardLayout ( - IN OUT USB_KB_DEV *UsbKeyboardDevice + IN OUT USB_KB_DEV *UsbKeyboardDevice ) { - EFI_STATUS Status; - EFI_HII_DATABASE_PROTOCOL *HiiDatabase; - EFI_HII_HANDLE HiiHandle; + EFI_STATUS Status; + EFI_HII_DATABASE_PROTOCOL *HiiDatabase; + EFI_HII_HANDLE HiiHandle; // // Locate Hii database protocol @@ -327,7 +327,7 @@ InstallDefaultKeyboardLayout ( Status = gBS->LocateProtocol ( &gEfiHiiDatabaseProtocolGuid, NULL, - (VOID **) &HiiDatabase + (VOID **)&HiiDatabase ); if (EFI_ERROR (Status)) { return Status; @@ -354,7 +354,6 @@ InstallDefaultKeyboardLayout ( return Status; } - /** Uses USB I/O to check whether the device is a USB keyboard device. @@ -366,7 +365,7 @@ InstallDefaultKeyboardLayout ( **/ BOOLEAN IsUSBKeyboard ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ) { EFI_STATUS Status; @@ -384,10 +383,11 @@ IsUSBKeyboard ( return FALSE; } - if (InterfaceDescriptor.InterfaceClass == CLASS_HID && - InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT && - InterfaceDescriptor.InterfaceProtocol == PROTOCOL_KEYBOARD - ) { + if ((InterfaceDescriptor.InterfaceClass == CLASS_HID) && + (InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT) && + (InterfaceDescriptor.InterfaceProtocol == PROTOCOL_KEYBOARD) + ) + { return TRUE; } @@ -406,10 +406,10 @@ GetCurrentKeyboardLayout ( VOID ) { - EFI_STATUS Status; - EFI_HII_DATABASE_PROTOCOL *HiiDatabase; - EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; - UINT16 Length; + EFI_STATUS Status; + EFI_HII_DATABASE_PROTOCOL *HiiDatabase; + EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; + UINT16 Length; // // Locate HII Database Protocol @@ -417,7 +417,7 @@ GetCurrentKeyboardLayout ( Status = gBS->LocateProtocol ( &gEfiHiiDatabaseProtocolGuid, NULL, - (VOID **) &HiiDatabase + (VOID **)&HiiDatabase ); if (EFI_ERROR (Status)) { return NULL; @@ -426,14 +426,14 @@ GetCurrentKeyboardLayout ( // // Get current keyboard layout from HII database // - Length = 0; + Length = 0; KeyboardLayout = NULL; - Status = HiiDatabase->GetKeyboardLayout ( - HiiDatabase, - NULL, - &Length, - KeyboardLayout - ); + Status = HiiDatabase->GetKeyboardLayout ( + HiiDatabase, + NULL, + &Length, + KeyboardLayout + ); if (Status == EFI_BUFFER_TOO_SMALL) { KeyboardLayout = AllocatePool (Length); ASSERT (KeyboardLayout != NULL); @@ -465,8 +465,8 @@ GetCurrentKeyboardLayout ( **/ EFI_KEY_DESCRIPTOR * GetKeyDescriptor ( - IN USB_KB_DEV *UsbKeyboardDevice, - IN UINT8 KeyCode + IN USB_KB_DEV *UsbKeyboardDevice, + IN UINT8 KeyCode ) { UINT8 Index; @@ -482,9 +482,9 @@ GetKeyDescriptor ( // Calculate the index of Key Descriptor in Key Convertion Table // if (KeyCode <= 0x65) { - Index = (UINT8) (KeyCode - 4); + Index = (UINT8)(KeyCode - 4); } else { - Index = (UINT8) (KeyCode - 0xe0 + NUMBER_OF_VALID_NON_MODIFIER_USB_KEYCODE); + Index = (UINT8)(KeyCode - 0xe0 + NUMBER_OF_VALID_NON_MODIFIER_USB_KEYCODE); } return &UsbKeyboardDevice->KeyConvertionTable[Index]; @@ -506,12 +506,12 @@ FindUsbNsKey ( IN EFI_KEY_DESCRIPTOR *KeyDescriptor ) { - LIST_ENTRY *Link; - LIST_ENTRY *NsKeyList; - USB_NS_KEY *UsbNsKey; + LIST_ENTRY *Link; + LIST_ENTRY *NsKeyList; + USB_NS_KEY *UsbNsKey; NsKeyList = &UsbKeyboardDevice->NsKeyList; - Link = GetFirstNode (NsKeyList); + Link = GetFirstNode (NsKeyList); while (!IsNull (NsKeyList, Link)) { UsbNsKey = USB_NS_KEY_FORM_FROM_LINK (Link); @@ -578,23 +578,23 @@ FindPhysicalKey ( VOID EFIAPI SetKeyboardLayoutEvent ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_KB_DEV *UsbKeyboardDevice; - EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; - EFI_KEY_DESCRIPTOR TempKey; - EFI_KEY_DESCRIPTOR *KeyDescriptor; - EFI_KEY_DESCRIPTOR *TableEntry; - EFI_KEY_DESCRIPTOR *NsKey; - USB_NS_KEY *UsbNsKey; - UINTN Index; - UINTN Index2; - UINTN KeyCount; - UINT8 KeyCode; - - UsbKeyboardDevice = (USB_KB_DEV *) Context; + USB_KB_DEV *UsbKeyboardDevice; + EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; + EFI_KEY_DESCRIPTOR TempKey; + EFI_KEY_DESCRIPTOR *KeyDescriptor; + EFI_KEY_DESCRIPTOR *TableEntry; + EFI_KEY_DESCRIPTOR *NsKey; + USB_NS_KEY *UsbNsKey; + UINTN Index; + UINTN Index2; + UINTN KeyCount; + UINT8 KeyCode; + + UsbKeyboardDevice = (USB_KB_DEV *)Context; if (UsbKeyboardDevice->Signature != USB_KB_DEV_SIGNATURE) { return; } @@ -611,13 +611,13 @@ SetKeyboardLayoutEvent ( // Re-allocate resource for KeyConvertionTable // ReleaseKeyboardLayoutResources (UsbKeyboardDevice); - UsbKeyboardDevice->KeyConvertionTable = AllocateZeroPool ((NUMBER_OF_VALID_USB_KEYCODE) * sizeof (EFI_KEY_DESCRIPTOR)); + UsbKeyboardDevice->KeyConvertionTable = AllocateZeroPool ((NUMBER_OF_VALID_USB_KEYCODE)*sizeof (EFI_KEY_DESCRIPTOR)); ASSERT (UsbKeyboardDevice->KeyConvertionTable != NULL); // // Traverse the list of key descriptors following the header of EFI_HII_KEYBOARD_LAYOUT // - KeyDescriptor = (EFI_KEY_DESCRIPTOR *) (((UINT8 *) KeyboardLayout) + sizeof (EFI_HII_KEYBOARD_LAYOUT)); + KeyDescriptor = (EFI_KEY_DESCRIPTOR *)(((UINT8 *)KeyboardLayout) + sizeof (EFI_HII_KEYBOARD_LAYOUT)); for (Index = 0; Index < KeyboardLayout->DescriptorCount; Index++) { // // Copy from HII keyboard layout package binary for alignment @@ -627,13 +627,14 @@ SetKeyboardLayoutEvent ( // // Fill the key into KeyConvertionTable, whose index is calculated from USB keycode. // - KeyCode = EfiKeyToUsbKeyCodeConvertionTable [(UINT8) (TempKey.Key)]; + KeyCode = EfiKeyToUsbKeyCodeConvertionTable[(UINT8)(TempKey.Key)]; TableEntry = GetKeyDescriptor (UsbKeyboardDevice, KeyCode); if (TableEntry == NULL) { ReleaseKeyboardLayoutResources (UsbKeyboardDevice); FreePool (KeyboardLayout); return; } + CopyMem (TableEntry, KeyDescriptor, sizeof (EFI_KEY_DESCRIPTOR)); // @@ -647,29 +648,30 @@ SetKeyboardLayoutEvent ( // Search for sequential children physical key definitions // KeyCount = 0; - NsKey = KeyDescriptor + 1; - for (Index2 = (UINT8) Index + 1; Index2 < KeyboardLayout->DescriptorCount; Index2++) { + NsKey = KeyDescriptor + 1; + for (Index2 = (UINT8)Index + 1; Index2 < KeyboardLayout->DescriptorCount; Index2++) { CopyMem (&TempKey, NsKey, sizeof (EFI_KEY_DESCRIPTOR)); if (TempKey.Modifier == EFI_NS_KEY_DEPENDENCY_MODIFIER) { KeyCount++; } else { break; } + NsKey++; } UsbNsKey->Signature = USB_NS_KEY_SIGNATURE; - UsbNsKey->KeyCount = KeyCount; - UsbNsKey->NsKey = AllocateCopyPool ( - (KeyCount + 1) * sizeof (EFI_KEY_DESCRIPTOR), - KeyDescriptor - ); + UsbNsKey->KeyCount = KeyCount; + UsbNsKey->NsKey = AllocateCopyPool ( + (KeyCount + 1) * sizeof (EFI_KEY_DESCRIPTOR), + KeyDescriptor + ); InsertTailList (&UsbKeyboardDevice->NsKeyList, &UsbNsKey->Link); // // Skip over the child physical keys // - Index += KeyCount; + Index += KeyCount; KeyDescriptor += KeyCount; } @@ -679,7 +681,7 @@ SetKeyboardLayoutEvent ( // // There are two EfiKeyEnter, duplicate its key descriptor // - TableEntry = GetKeyDescriptor (UsbKeyboardDevice, 0x58); + TableEntry = GetKeyDescriptor (UsbKeyboardDevice, 0x58); KeyDescriptor = GetKeyDescriptor (UsbKeyboardDevice, 0x28); CopyMem (TableEntry, KeyDescriptor, sizeof (EFI_KEY_DESCRIPTOR)); @@ -694,19 +696,20 @@ SetKeyboardLayoutEvent ( **/ VOID ReleaseKeyboardLayoutResources ( - IN OUT USB_KB_DEV *UsbKeyboardDevice + IN OUT USB_KB_DEV *UsbKeyboardDevice ) { - USB_NS_KEY *UsbNsKey; - LIST_ENTRY *Link; + USB_NS_KEY *UsbNsKey; + LIST_ENTRY *Link; if (UsbKeyboardDevice->KeyConvertionTable != NULL) { FreePool (UsbKeyboardDevice->KeyConvertionTable); } + UsbKeyboardDevice->KeyConvertionTable = NULL; while (!IsListEmpty (&UsbKeyboardDevice->NsKeyList)) { - Link = GetFirstNode (&UsbKeyboardDevice->NsKeyList); + Link = GetFirstNode (&UsbKeyboardDevice->NsKeyList); UsbNsKey = USB_NS_KEY_FORM_FROM_LINK (Link); RemoveEntryList (&UsbNsKey->Link); @@ -732,17 +735,17 @@ ReleaseKeyboardLayoutResources ( **/ EFI_STATUS InitKeyboardLayout ( - OUT USB_KB_DEV *UsbKeyboardDevice + OUT USB_KB_DEV *UsbKeyboardDevice ) { - EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; - EFI_STATUS Status; + EFI_HII_KEYBOARD_LAYOUT *KeyboardLayout; + EFI_STATUS Status; - UsbKeyboardDevice->KeyConvertionTable = AllocateZeroPool ((NUMBER_OF_VALID_USB_KEYCODE) * sizeof (EFI_KEY_DESCRIPTOR)); + UsbKeyboardDevice->KeyConvertionTable = AllocateZeroPool ((NUMBER_OF_VALID_USB_KEYCODE)*sizeof (EFI_KEY_DESCRIPTOR)); ASSERT (UsbKeyboardDevice->KeyConvertionTable != NULL); InitializeListHead (&UsbKeyboardDevice->NsKeyList); - UsbKeyboardDevice->CurrentNsKey = NULL; + UsbKeyboardDevice->CurrentNsKey = NULL; UsbKeyboardDevice->KeyboardLayoutEvent = NULL; // @@ -776,6 +779,7 @@ InitKeyboardLayout ( // return EFI_NOT_READY; } + // // If no keyboard layout can be retrieved from HII database, and default layout // is enabled, then load the default keyboard layout. @@ -786,7 +790,6 @@ InitKeyboardLayout ( return EFI_SUCCESS; } - /** Initialize USB keyboard device and all private data structures. @@ -798,13 +801,13 @@ InitKeyboardLayout ( **/ EFI_STATUS InitUSBKeyboard ( - IN OUT USB_KB_DEV *UsbKeyboardDevice + IN OUT USB_KB_DEV *UsbKeyboardDevice ) { - UINT16 ConfigValue; - UINT8 Protocol; - EFI_STATUS Status; - UINT32 TransferResult; + UINT16 ConfigValue; + UINT8 Protocol; + EFI_STATUS Status; + UINT32 TransferResult; REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, @@ -868,12 +871,12 @@ InitUSBKeyboard ( ); } - UsbKeyboardDevice->CtrlOn = FALSE; - UsbKeyboardDevice->AltOn = FALSE; - UsbKeyboardDevice->ShiftOn = FALSE; - UsbKeyboardDevice->NumLockOn = FALSE; - UsbKeyboardDevice->CapsOn = FALSE; - UsbKeyboardDevice->ScrollOn = FALSE; + UsbKeyboardDevice->CtrlOn = FALSE; + UsbKeyboardDevice->AltOn = FALSE; + UsbKeyboardDevice->ShiftOn = FALSE; + UsbKeyboardDevice->NumLockOn = FALSE; + UsbKeyboardDevice->CapsOn = FALSE; + UsbKeyboardDevice->ScrollOn = FALSE; UsbKeyboardDevice->LeftCtrlOn = FALSE; UsbKeyboardDevice->LeftAltOn = FALSE; @@ -886,7 +889,7 @@ InitUSBKeyboard ( UsbKeyboardDevice->MenuKeyOn = FALSE; UsbKeyboardDevice->SysReqOn = FALSE; - UsbKeyboardDevice->AltGrOn = FALSE; + UsbKeyboardDevice->AltGrOn = FALSE; UsbKeyboardDevice->CurrentNsKey = NULL; @@ -932,7 +935,6 @@ InitUSBKeyboard ( return EFI_SUCCESS; } - /** Handler function for USB keyboard's asynchronous interrupt transfer. @@ -954,32 +956,32 @@ InitUSBKeyboard ( EFI_STATUS EFIAPI KeyboardHandler ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ) { - USB_KB_DEV *UsbKeyboardDevice; - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 *CurKeyCodeBuffer; - UINT8 *OldKeyCodeBuffer; - UINT8 CurModifierMap; - UINT8 OldModifierMap; - UINT8 Mask; - UINTN Index; - UINT8 Index2; - BOOLEAN KeyRelease; - BOOLEAN KeyPress; - USB_KEY UsbKey; - UINT8 NewRepeatKey; - UINT32 UsbStatus; - EFI_KEY_DESCRIPTOR *KeyDescriptor; + USB_KB_DEV *UsbKeyboardDevice; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 *CurKeyCodeBuffer; + UINT8 *OldKeyCodeBuffer; + UINT8 CurModifierMap; + UINT8 OldModifierMap; + UINT8 Mask; + UINTN Index; + UINT8 Index2; + BOOLEAN KeyRelease; + BOOLEAN KeyPress; + USB_KEY UsbKey; + UINT8 NewRepeatKey; + UINT32 UsbStatus; + EFI_KEY_DESCRIPTOR *KeyDescriptor; ASSERT (Context != NULL); NewRepeatKey = 0; - UsbKeyboardDevice = (USB_KB_DEV *) Context; + UsbKeyboardDevice = (USB_KB_DEV *)Context; UsbIo = UsbKeyboardDevice->UsbIo; // @@ -1001,10 +1003,10 @@ KeyboardHandler ( UsbKeyboardDevice->RepeatKey = 0; gBS->SetTimer ( - UsbKeyboardDevice->RepeatTimer, - TimerCancel, - USBKBD_REPEAT_RATE - ); + UsbKeyboardDevice->RepeatTimer, + TimerCancel, + USBKBD_REPEAT_RATE + ); if ((Result & EFI_USB_ERR_STALL) == EFI_USB_ERR_STALL) { UsbClearEndpointHalt ( @@ -1042,7 +1044,7 @@ KeyboardHandler ( // // If no error and no data, just return EFI_SUCCESS. // - if (DataLength == 0 || Data == NULL) { + if ((DataLength == 0) || (Data == NULL)) { return EFI_SUCCESS; } @@ -1057,8 +1059,8 @@ KeyboardHandler ( return EFI_DEVICE_ERROR; } - CurKeyCodeBuffer = (UINT8 *) Data; - OldKeyCodeBuffer = UsbKeyboardDevice->LastKeyCodeArray; + CurKeyCodeBuffer = (UINT8 *)Data; + OldKeyCodeBuffer = UsbKeyboardDevice->LastKeyCodeArray; // // Checks for new key stroke. @@ -1079,8 +1081,8 @@ KeyboardHandler ( // // Parse the modifier key, which is the first byte of keyboard input report. // - CurModifierMap = CurKeyCodeBuffer[0]; - OldModifierMap = OldKeyCodeBuffer[0]; + CurModifierMap = CurKeyCodeBuffer[0]; + OldModifierMap = OldKeyCodeBuffer[0]; // // Handle modifier key's pressing or releasing situation. @@ -1095,15 +1097,15 @@ KeyboardHandler ( // Bit7: Right GUI, Keycode: 0xe7 // for (Index = 0; Index < 8; Index++) { - Mask = (UINT8) (1 << Index); + Mask = (UINT8)(1 << Index); if ((CurModifierMap & Mask) != (OldModifierMap & Mask)) { // // If current modifier key is up, then CurModifierMap & Mask = 0; // otherwise it is a non-zero value. // Insert the changed modifier key into key buffer. // - UsbKey.KeyCode = (UINT8) (0xe0 + Index); - UsbKey.Down = (BOOLEAN) ((CurModifierMap & Mask) != 0); + UsbKey.KeyCode = (UINT8)(0xe0 + Index); + UsbKey.Down = (BOOLEAN)((CurModifierMap & Mask) != 0); Enqueue (&UsbKeyboardDevice->UsbKeyQueue, &UsbKey, sizeof (UsbKey)); } } @@ -1114,17 +1116,16 @@ KeyboardHandler ( // KeyRelease = FALSE; for (Index = 2; Index < 8; Index++) { - if (!USBKBD_VALID_KEYCODE (OldKeyCodeBuffer[Index])) { continue; } + // // For any key in old keycode buffer, if it is not in current keycode buffer, // then it is released. Otherwise, it is not released. // KeyRelease = TRUE; for (Index2 = 2; Index2 < 8; Index2++) { - if (!USBKBD_VALID_KEYCODE (CurKeyCodeBuffer[Index2])) { continue; } @@ -1164,17 +1165,16 @@ KeyboardHandler ( // KeyPress = FALSE; for (Index = 2; Index < 8; Index++) { - if (!USBKBD_VALID_KEYCODE (CurKeyCodeBuffer[Index])) { continue; } + // // For any key in current keycode buffer, if it is not in old keycode buffer, // then it is pressed. Otherwise, it is not pressed. // KeyPress = TRUE; for (Index2 = 2; Index2 < 8; Index2++) { - if (!USBKBD_VALID_KEYCODE (OldKeyCodeBuffer[Index2])) { continue; } @@ -1198,7 +1198,7 @@ KeyboardHandler ( continue; } - if (KeyDescriptor->Modifier == EFI_NUM_LOCK_MODIFIER || KeyDescriptor->Modifier == EFI_CAPS_LOCK_MODIFIER) { + if ((KeyDescriptor->Modifier == EFI_NUM_LOCK_MODIFIER) || (KeyDescriptor->Modifier == EFI_CAPS_LOCK_MODIFIER)) { // // For NumLock or CapsLock pressed, there is no need to handle repeat key for them. // @@ -1207,7 +1207,7 @@ KeyboardHandler ( // // Prepare new repeat key, and clear the original one. // - NewRepeatKey = CurKeyCodeBuffer[Index]; + NewRepeatKey = CurKeyCodeBuffer[Index]; UsbKeyboardDevice->RepeatKey = 0; } } @@ -1241,7 +1241,6 @@ KeyboardHandler ( return EFI_SUCCESS; } - /** Retrieves a USB keycode after parsing the raw data in keyboard buffer. @@ -1258,7 +1257,7 @@ KeyboardHandler ( EFI_STATUS USBParseKey ( IN OUT USB_KB_DEV *UsbKeyboardDevice, - OUT UINT8 *KeyCode + OUT UINT8 *KeyCode ) { USB_KEY UsbKey; @@ -1276,194 +1275,193 @@ USBParseKey ( if (KeyDescriptor == NULL) { continue; } + if (!UsbKey.Down) { // // Key is released. // switch (KeyDescriptor->Modifier) { + // + // Ctrl release + // + case EFI_LEFT_CONTROL_MODIFIER: + UsbKeyboardDevice->LeftCtrlOn = FALSE; + UsbKeyboardDevice->CtrlOn = FALSE; + break; + case EFI_RIGHT_CONTROL_MODIFIER: + UsbKeyboardDevice->RightCtrlOn = FALSE; + UsbKeyboardDevice->CtrlOn = FALSE; + break; + + // + // Shift release + // + case EFI_LEFT_SHIFT_MODIFIER: + UsbKeyboardDevice->LeftShiftOn = FALSE; + UsbKeyboardDevice->ShiftOn = FALSE; + break; + case EFI_RIGHT_SHIFT_MODIFIER: + UsbKeyboardDevice->RightShiftOn = FALSE; + UsbKeyboardDevice->ShiftOn = FALSE; + break; + + // + // Alt release + // + case EFI_LEFT_ALT_MODIFIER: + UsbKeyboardDevice->LeftAltOn = FALSE; + UsbKeyboardDevice->AltOn = FALSE; + break; + case EFI_RIGHT_ALT_MODIFIER: + UsbKeyboardDevice->RightAltOn = FALSE; + UsbKeyboardDevice->AltOn = FALSE; + break; + // + // Left Logo release + // + case EFI_LEFT_LOGO_MODIFIER: + UsbKeyboardDevice->LeftLogoOn = FALSE; + break; + + // + // Right Logo release + // + case EFI_RIGHT_LOGO_MODIFIER: + UsbKeyboardDevice->RightLogoOn = FALSE; + break; + + // + // Menu key release + // + case EFI_MENU_MODIFIER: + UsbKeyboardDevice->MenuKeyOn = FALSE; + break; + + // + // SysReq release + // + case EFI_PRINT_MODIFIER: + case EFI_SYS_REQUEST_MODIFIER: + UsbKeyboardDevice->SysReqOn = FALSE; + break; + + // + // AltGr release + // + case EFI_ALT_GR_MODIFIER: + UsbKeyboardDevice->AltGrOn = FALSE; + break; + + default: + break; + } + + continue; + } + + // + // Analyzes key pressing situation + // + switch (KeyDescriptor->Modifier) { // - // Ctrl release + // Ctrl press // case EFI_LEFT_CONTROL_MODIFIER: - UsbKeyboardDevice->LeftCtrlOn = FALSE; - UsbKeyboardDevice->CtrlOn = FALSE; + UsbKeyboardDevice->LeftCtrlOn = TRUE; + UsbKeyboardDevice->CtrlOn = TRUE; break; case EFI_RIGHT_CONTROL_MODIFIER: - UsbKeyboardDevice->RightCtrlOn = FALSE; - UsbKeyboardDevice->CtrlOn = FALSE; + UsbKeyboardDevice->RightCtrlOn = TRUE; + UsbKeyboardDevice->CtrlOn = TRUE; break; // - // Shift release + // Shift press // case EFI_LEFT_SHIFT_MODIFIER: - UsbKeyboardDevice->LeftShiftOn = FALSE; - UsbKeyboardDevice->ShiftOn = FALSE; + UsbKeyboardDevice->LeftShiftOn = TRUE; + UsbKeyboardDevice->ShiftOn = TRUE; break; case EFI_RIGHT_SHIFT_MODIFIER: - UsbKeyboardDevice->RightShiftOn = FALSE; - UsbKeyboardDevice->ShiftOn = FALSE; + UsbKeyboardDevice->RightShiftOn = TRUE; + UsbKeyboardDevice->ShiftOn = TRUE; break; // - // Alt release + // Alt press // case EFI_LEFT_ALT_MODIFIER: - UsbKeyboardDevice->LeftAltOn = FALSE; - UsbKeyboardDevice->AltOn = FALSE; + UsbKeyboardDevice->LeftAltOn = TRUE; + UsbKeyboardDevice->AltOn = TRUE; break; case EFI_RIGHT_ALT_MODIFIER: - UsbKeyboardDevice->RightAltOn = FALSE; - UsbKeyboardDevice->AltOn = FALSE; + UsbKeyboardDevice->RightAltOn = TRUE; + UsbKeyboardDevice->AltOn = TRUE; break; // - // Left Logo release + // Left Logo press // case EFI_LEFT_LOGO_MODIFIER: - UsbKeyboardDevice->LeftLogoOn = FALSE; + UsbKeyboardDevice->LeftLogoOn = TRUE; break; // - // Right Logo release + // Right Logo press // case EFI_RIGHT_LOGO_MODIFIER: - UsbKeyboardDevice->RightLogoOn = FALSE; + UsbKeyboardDevice->RightLogoOn = TRUE; break; // - // Menu key release + // Menu key press // case EFI_MENU_MODIFIER: - UsbKeyboardDevice->MenuKeyOn = FALSE; + UsbKeyboardDevice->MenuKeyOn = TRUE; break; // - // SysReq release + // SysReq press // case EFI_PRINT_MODIFIER: case EFI_SYS_REQUEST_MODIFIER: - UsbKeyboardDevice->SysReqOn = FALSE; + UsbKeyboardDevice->SysReqOn = TRUE; break; // - // AltGr release + // AltGr press // case EFI_ALT_GR_MODIFIER: - UsbKeyboardDevice->AltGrOn = FALSE; + UsbKeyboardDevice->AltGrOn = TRUE; break; - default: + case EFI_NUM_LOCK_MODIFIER: + // + // Toggle NumLock + // + UsbKeyboardDevice->NumLockOn = (BOOLEAN)(!(UsbKeyboardDevice->NumLockOn)); + SetKeyLED (UsbKeyboardDevice); break; - } - - continue; - } - - // - // Analyzes key pressing situation - // - switch (KeyDescriptor->Modifier) { - - // - // Ctrl press - // - case EFI_LEFT_CONTROL_MODIFIER: - UsbKeyboardDevice->LeftCtrlOn = TRUE; - UsbKeyboardDevice->CtrlOn = TRUE; - break; - case EFI_RIGHT_CONTROL_MODIFIER: - UsbKeyboardDevice->RightCtrlOn = TRUE; - UsbKeyboardDevice->CtrlOn = TRUE; - break; - - // - // Shift press - // - case EFI_LEFT_SHIFT_MODIFIER: - UsbKeyboardDevice->LeftShiftOn = TRUE; - UsbKeyboardDevice->ShiftOn = TRUE; - break; - case EFI_RIGHT_SHIFT_MODIFIER: - UsbKeyboardDevice->RightShiftOn = TRUE; - UsbKeyboardDevice->ShiftOn = TRUE; - break; - - // - // Alt press - // - case EFI_LEFT_ALT_MODIFIER: - UsbKeyboardDevice->LeftAltOn = TRUE; - UsbKeyboardDevice->AltOn = TRUE; - break; - case EFI_RIGHT_ALT_MODIFIER: - UsbKeyboardDevice->RightAltOn = TRUE; - UsbKeyboardDevice->AltOn = TRUE; - break; - - // - // Left Logo press - // - case EFI_LEFT_LOGO_MODIFIER: - UsbKeyboardDevice->LeftLogoOn = TRUE; - break; - - // - // Right Logo press - // - case EFI_RIGHT_LOGO_MODIFIER: - UsbKeyboardDevice->RightLogoOn = TRUE; - break; - - // - // Menu key press - // - case EFI_MENU_MODIFIER: - UsbKeyboardDevice->MenuKeyOn = TRUE; - break; - - // - // SysReq press - // - case EFI_PRINT_MODIFIER: - case EFI_SYS_REQUEST_MODIFIER: - UsbKeyboardDevice->SysReqOn = TRUE; - break; - - // - // AltGr press - // - case EFI_ALT_GR_MODIFIER: - UsbKeyboardDevice->AltGrOn = TRUE; - break; - case EFI_NUM_LOCK_MODIFIER: - // - // Toggle NumLock - // - UsbKeyboardDevice->NumLockOn = (BOOLEAN) (!(UsbKeyboardDevice->NumLockOn)); - SetKeyLED (UsbKeyboardDevice); - break; - - case EFI_CAPS_LOCK_MODIFIER: - // - // Toggle CapsLock - // - UsbKeyboardDevice->CapsOn = (BOOLEAN) (!(UsbKeyboardDevice->CapsOn)); - SetKeyLED (UsbKeyboardDevice); - break; + case EFI_CAPS_LOCK_MODIFIER: + // + // Toggle CapsLock + // + UsbKeyboardDevice->CapsOn = (BOOLEAN)(!(UsbKeyboardDevice->CapsOn)); + SetKeyLED (UsbKeyboardDevice); + break; - case EFI_SCROLL_LOCK_MODIFIER: - // - // Toggle ScrollLock - // - UsbKeyboardDevice->ScrollOn = (BOOLEAN) (!(UsbKeyboardDevice->ScrollOn)); - SetKeyLED (UsbKeyboardDevice); - break; + case EFI_SCROLL_LOCK_MODIFIER: + // + // Toggle ScrollLock + // + UsbKeyboardDevice->ScrollOn = (BOOLEAN)(!(UsbKeyboardDevice->ScrollOn)); + SetKeyLED (UsbKeyboardDevice); + break; - default: - break; + default: + break; } // @@ -1490,8 +1488,8 @@ USBParseKey ( **/ VOID InitializeKeyState ( - IN USB_KB_DEV *UsbKeyboardDevice, - OUT EFI_KEY_STATE *KeyState + IN USB_KB_DEV *UsbKeyboardDevice, + OUT EFI_KEY_STATE *KeyState ) { KeyState->KeyShiftState = EFI_SHIFT_STATE_VALID; @@ -1500,30 +1498,39 @@ InitializeKeyState ( if (UsbKeyboardDevice->LeftCtrlOn) { KeyState->KeyShiftState |= EFI_LEFT_CONTROL_PRESSED; } + if (UsbKeyboardDevice->RightCtrlOn) { KeyState->KeyShiftState |= EFI_RIGHT_CONTROL_PRESSED; } + if (UsbKeyboardDevice->LeftAltOn) { KeyState->KeyShiftState |= EFI_LEFT_ALT_PRESSED; } + if (UsbKeyboardDevice->RightAltOn) { KeyState->KeyShiftState |= EFI_RIGHT_ALT_PRESSED; } + if (UsbKeyboardDevice->LeftShiftOn) { KeyState->KeyShiftState |= EFI_LEFT_SHIFT_PRESSED; } + if (UsbKeyboardDevice->RightShiftOn) { KeyState->KeyShiftState |= EFI_RIGHT_SHIFT_PRESSED; } + if (UsbKeyboardDevice->LeftLogoOn) { KeyState->KeyShiftState |= EFI_LEFT_LOGO_PRESSED; } + if (UsbKeyboardDevice->RightLogoOn) { KeyState->KeyShiftState |= EFI_RIGHT_LOGO_PRESSED; } + if (UsbKeyboardDevice->MenuKeyOn) { KeyState->KeyShiftState |= EFI_MENU_KEY_PRESSED; } + if (UsbKeyboardDevice->SysReqOn) { KeyState->KeyShiftState |= EFI_SYS_REQ_PRESSED; } @@ -1531,12 +1538,15 @@ InitializeKeyState ( if (UsbKeyboardDevice->ScrollOn) { KeyState->KeyToggleState |= EFI_SCROLL_LOCK_ACTIVE; } + if (UsbKeyboardDevice->NumLockOn) { KeyState->KeyToggleState |= EFI_NUM_LOCK_ACTIVE; } + if (UsbKeyboardDevice->CapsOn) { KeyState->KeyToggleState |= EFI_CAPS_LOCK_ACTIVE; } + if (UsbKeyboardDevice->IsSupportPartialKey) { KeyState->KeyToggleState |= EFI_KEY_STATE_EXPOSED; } @@ -1560,15 +1570,15 @@ InitializeKeyState ( **/ EFI_STATUS UsbKeyCodeToEfiInputKey ( - IN USB_KB_DEV *UsbKeyboardDevice, - IN UINT8 KeyCode, - OUT EFI_KEY_DATA *KeyData + IN USB_KB_DEV *UsbKeyboardDevice, + IN UINT8 KeyCode, + OUT EFI_KEY_DATA *KeyData ) { - EFI_KEY_DESCRIPTOR *KeyDescriptor; - LIST_ENTRY *Link; - LIST_ENTRY *NotifyList; - KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; + EFI_KEY_DESCRIPTOR *KeyDescriptor; + LIST_ENTRY *Link; + LIST_ENTRY *NotifyList; + KEYBOARD_CONSOLE_IN_EX_NOTIFY *CurrentNotify; // // KeyCode must in the range of [0x4, 0x65] or [0xe0, 0xe7]. @@ -1591,7 +1601,7 @@ UsbKeyCodeToEfiInputKey ( // If this keystroke follows a non-spacing key, then find the descriptor for corresponding // physical key. // - KeyDescriptor = FindPhysicalKey (UsbKeyboardDevice->CurrentNsKey, KeyDescriptor); + KeyDescriptor = FindPhysicalKey (UsbKeyboardDevice->CurrentNsKey, KeyDescriptor); UsbKeyboardDevice->CurrentNsKey = NULL; } @@ -1605,7 +1615,7 @@ UsbKeyCodeToEfiInputKey ( KeyData->Key.ScanCode = ModifierValueToEfiScanCodeConvertionTable[KeyDescriptor->Modifier]; KeyData->Key.UnicodeChar = KeyDescriptor->Unicode; - if ((KeyDescriptor->AffectedAttribute & EFI_AFFECTED_BY_STANDARD_SHIFT)!= 0) { + if ((KeyDescriptor->AffectedAttribute & EFI_AFFECTED_BY_STANDARD_SHIFT) != 0) { if (UsbKeyboardDevice->ShiftOn) { KeyData->Key.UnicodeChar = KeyDescriptor->ShiftedUnicode; @@ -1614,8 +1624,9 @@ UsbKeyCodeToEfiInputKey ( // are normally adjusted by shift modifiers. e.g. Shift Key + 'f' key = 'F' // if ((KeyDescriptor->Unicode != CHAR_NULL) && (KeyDescriptor->ShiftedUnicode != CHAR_NULL) && - (KeyDescriptor->Unicode != KeyDescriptor->ShiftedUnicode)) { - UsbKeyboardDevice->LeftShiftOn = FALSE; + (KeyDescriptor->Unicode != KeyDescriptor->ShiftedUnicode)) + { + UsbKeyboardDevice->LeftShiftOn = FALSE; UsbKeyboardDevice->RightShiftOn = FALSE; } @@ -1660,17 +1671,17 @@ UsbKeyCodeToEfiInputKey ( // // Translate Unicode 0x1B (ESC) to EFI Scan Code // - if (KeyData->Key.UnicodeChar == 0x1B && KeyData->Key.ScanCode == SCAN_NULL) { - KeyData->Key.ScanCode = SCAN_ESC; + if ((KeyData->Key.UnicodeChar == 0x1B) && (KeyData->Key.ScanCode == SCAN_NULL)) { + KeyData->Key.ScanCode = SCAN_ESC; KeyData->Key.UnicodeChar = CHAR_NULL; } // // Not valid for key without both unicode key code and EFI Scan Code. // - if (KeyData->Key.UnicodeChar == 0 && KeyData->Key.ScanCode == SCAN_NULL) { + if ((KeyData->Key.UnicodeChar == 0) && (KeyData->Key.ScanCode == SCAN_NULL)) { if (!UsbKeyboardDevice->IsSupportPartialKey) { - return EFI_NOT_READY; + return EFI_NOT_READY; } } @@ -1709,15 +1720,15 @@ UsbKeyCodeToEfiInputKey ( **/ VOID InitQueue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + IN UINTN ItemSize ) { - UINTN Index; + UINTN Index; - Queue->ItemSize = ItemSize; - Queue->Head = 0; - Queue->Tail = 0; + Queue->ItemSize = ItemSize; + Queue->Head = 0; + Queue->Tail = 0; if (Queue->Buffer[0] != NULL) { FreePool (Queue->Buffer[0]); @@ -1727,7 +1738,7 @@ InitQueue ( ASSERT (Queue->Buffer[0] != NULL); for (Index = 1; Index < sizeof (Queue->Buffer) / sizeof (Queue->Buffer[0]); Index++) { - Queue->Buffer[Index] = ((UINT8 *) Queue->Buffer[Index - 1]) + ItemSize; + Queue->Buffer[Index] = ((UINT8 *)Queue->Buffer[Index - 1]) + ItemSize; } } @@ -1738,13 +1749,12 @@ InitQueue ( **/ VOID DestroyQueue ( - IN OUT USB_SIMPLE_QUEUE *Queue + IN OUT USB_SIMPLE_QUEUE *Queue ) { FreePool (Queue->Buffer[0]); } - /** Check whether the queue is empty. @@ -1756,16 +1766,15 @@ DestroyQueue ( **/ BOOLEAN IsQueueEmpty ( - IN USB_SIMPLE_QUEUE *Queue + IN USB_SIMPLE_QUEUE *Queue ) { // // Meet FIFO empty condition // - return (BOOLEAN) (Queue->Head == Queue->Tail); + return (BOOLEAN)(Queue->Head == Queue->Tail); } - /** Check whether the queue is full. @@ -1777,13 +1786,12 @@ IsQueueEmpty ( **/ BOOLEAN IsQueueFull ( - IN USB_SIMPLE_QUEUE *Queue + IN USB_SIMPLE_QUEUE *Queue ) { - return (BOOLEAN) (((Queue->Tail + 1) % (MAX_KEY_ALLOWED + 1)) == Queue->Head); + return (BOOLEAN)(((Queue->Tail + 1) % (MAX_KEY_ALLOWED + 1)) == Queue->Head); } - /** Enqueue the item to the queue. @@ -1793,9 +1801,9 @@ IsQueueFull ( **/ VOID Enqueue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - IN VOID *Item, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + IN VOID *Item, + IN UINTN ItemSize ) { ASSERT (ItemSize == Queue->ItemSize); @@ -1815,7 +1823,6 @@ Enqueue ( Queue->Tail = (Queue->Tail + 1) % (MAX_KEY_ALLOWED + 1); } - /** Dequeue a item from the queue. @@ -1829,9 +1836,9 @@ Enqueue ( **/ EFI_STATUS Dequeue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - OUT VOID *Item, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + OUT VOID *Item, + IN UINTN ItemSize ) { ASSERT (Queue->ItemSize == ItemSize); @@ -1850,7 +1857,6 @@ Dequeue ( return EFI_SUCCESS; } - /** Sets USB keyboard LED state. @@ -1859,21 +1865,21 @@ Dequeue ( **/ VOID SetKeyLED ( - IN USB_KB_DEV *UsbKeyboardDevice + IN USB_KB_DEV *UsbKeyboardDevice ) { - LED_MAP Led; - UINT8 ReportId; + LED_MAP Led; + UINT8 ReportId; // // Set each field in Led map. // - Led.NumLock = (UINT8) ((UsbKeyboardDevice->NumLockOn) ? 1 : 0); - Led.CapsLock = (UINT8) ((UsbKeyboardDevice->CapsOn) ? 1 : 0); - Led.ScrollLock = (UINT8) ((UsbKeyboardDevice->ScrollOn) ? 1 : 0); + Led.NumLock = (UINT8)((UsbKeyboardDevice->NumLockOn) ? 1 : 0); + Led.CapsLock = (UINT8)((UsbKeyboardDevice->CapsOn) ? 1 : 0); + Led.ScrollLock = (UINT8)((UsbKeyboardDevice->ScrollOn) ? 1 : 0); Led.Resrvd = 0; - ReportId = 0; + ReportId = 0; // // Call Set_Report Request to lighten the LED. // @@ -1883,11 +1889,10 @@ SetKeyLED ( ReportId, HID_OUTPUT_REPORT, 1, - (UINT8 *) &Led + (UINT8 *)&Led ); } - /** Handler for Repeat Key event. @@ -1904,14 +1909,14 @@ SetKeyLED ( VOID EFIAPI USBKeyboardRepeatHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { USB_KB_DEV *UsbKeyboardDevice; USB_KEY UsbKey; - UsbKeyboardDevice = (USB_KB_DEV *) Context; + UsbKeyboardDevice = (USB_KB_DEV *)Context; // // Do nothing when there is no repeat key. @@ -1935,7 +1940,6 @@ USBKeyboardRepeatHandler ( } } - /** Handler for Delayed Recovery event. @@ -1952,20 +1956,19 @@ USBKeyboardRepeatHandler ( VOID EFIAPI USBKeyboardRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { + USB_KB_DEV *UsbKeyboardDevice; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 PacketSize; - USB_KB_DEV *UsbKeyboardDevice; - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 PacketSize; + UsbKeyboardDevice = (USB_KB_DEV *)Context; - UsbKeyboardDevice = (USB_KB_DEV *) Context; - - UsbIo = UsbKeyboardDevice->UsbIo; + UsbIo = UsbKeyboardDevice->UsbIo; - PacketSize = (UINT8) (UsbKeyboardDevice->IntEndpointDescriptor.MaxPacketSize); + PacketSize = (UINT8)(UsbKeyboardDevice->IntEndpointDescriptor.MaxPacketSize); // // Re-submit Asynchronous Interrupt Transfer for recovery. diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.h b/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.h index 811f136b65..05189444fc 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.h +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/KeyBoard.h @@ -9,10 +9,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_KEYBOARD_H_ #define _EFI_KEYBOARD_H_ - #include "EfiKey.h" -#define USB_KEYBOARD_KEY_COUNT 105 +#define USB_KEYBOARD_KEY_COUNT 105 #define USB_KEYBOARD_LANGUAGE_STR_LEN 5 // RFC4646 Language Code: "en-US" #define USB_KEYBOARD_DESCRIPTION_STR_LEN (16 + 1) // Description: "English Keyboard" @@ -22,28 +21,29 @@ typedef struct { // // This 4-bytes total array length is required by PreparePackageList() // - UINT32 Length; + UINT32 Length; // // Keyboard Layout package definition // - EFI_HII_PACKAGE_HEADER PackageHeader; - UINT16 LayoutCount; + EFI_HII_PACKAGE_HEADER PackageHeader; + UINT16 LayoutCount; // // EFI_HII_KEYBOARD_LAYOUT // - UINT16 LayoutLength; - EFI_GUID Guid; - UINT32 LayoutDescriptorStringOffset; - UINT8 DescriptorCount; - EFI_KEY_DESCRIPTOR KeyDescriptor[USB_KEYBOARD_KEY_COUNT]; - UINT16 DescriptionCount; - CHAR16 Language[USB_KEYBOARD_LANGUAGE_STR_LEN]; - CHAR16 Space; - CHAR16 DescriptionString[USB_KEYBOARD_DESCRIPTION_STR_LEN]; + UINT16 LayoutLength; + EFI_GUID Guid; + UINT32 LayoutDescriptorStringOffset; + UINT8 DescriptorCount; + EFI_KEY_DESCRIPTOR KeyDescriptor[USB_KEYBOARD_KEY_COUNT]; + UINT16 DescriptionCount; + CHAR16 Language[USB_KEYBOARD_LANGUAGE_STR_LEN]; + CHAR16 Space; + CHAR16 DescriptionString[USB_KEYBOARD_DESCRIPTION_STR_LEN]; } USB_KEYBOARD_LAYOUT_PACK_BIN; #pragma pack() + /** Uses USB I/O to check whether the device is a USB keyboard device. @@ -55,7 +55,7 @@ typedef struct { **/ BOOLEAN IsUSBKeyboard ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ); /** @@ -69,7 +69,7 @@ IsUSBKeyboard ( **/ EFI_STATUS InitUSBKeyboard ( - IN OUT USB_KB_DEV *UsbKeyboardDevice + IN OUT USB_KB_DEV *UsbKeyboardDevice ); /** @@ -89,7 +89,7 @@ InitUSBKeyboard ( **/ EFI_STATUS InitKeyboardLayout ( - OUT USB_KB_DEV *UsbKeyboardDevice + OUT USB_KB_DEV *UsbKeyboardDevice ); /** @@ -100,7 +100,7 @@ InitKeyboardLayout ( **/ VOID ReleaseKeyboardLayoutResources ( - IN OUT USB_KB_DEV *UsbKeyboardDevice + IN OUT USB_KB_DEV *UsbKeyboardDevice ); /** @@ -124,10 +124,10 @@ ReleaseKeyboardLayoutResources ( EFI_STATUS EFIAPI KeyboardHandler ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ); /** @@ -146,8 +146,8 @@ KeyboardHandler ( VOID EFIAPI USBKeyboardRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -187,12 +187,11 @@ USBParseKey ( **/ EFI_STATUS UsbKeyCodeToEfiInputKey ( - IN USB_KB_DEV *UsbKeyboardDevice, - IN UINT8 KeyCode, - OUT EFI_KEY_DATA *KeyData + IN USB_KB_DEV *UsbKeyboardDevice, + IN UINT8 KeyCode, + OUT EFI_KEY_DATA *KeyData ); - /** Create the queue. @@ -202,8 +201,8 @@ UsbKeyCodeToEfiInputKey ( **/ VOID InitQueue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + IN UINTN ItemSize ); /** @@ -213,10 +212,9 @@ InitQueue ( **/ VOID DestroyQueue ( - IN OUT USB_SIMPLE_QUEUE *Queue + IN OUT USB_SIMPLE_QUEUE *Queue ); - /** Check whether the queue is empty. @@ -228,10 +226,9 @@ DestroyQueue ( **/ BOOLEAN IsQueueEmpty ( - IN USB_SIMPLE_QUEUE *Queue + IN USB_SIMPLE_QUEUE *Queue ); - /** Check whether the queue is full. @@ -243,10 +240,9 @@ IsQueueEmpty ( **/ BOOLEAN IsQueueFull ( - IN USB_SIMPLE_QUEUE *Queue + IN USB_SIMPLE_QUEUE *Queue ); - /** Enqueue the item to the queue. @@ -256,12 +252,11 @@ IsQueueFull ( **/ VOID Enqueue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - IN VOID *Item, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + IN VOID *Item, + IN UINTN ItemSize ); - /** Dequeue a item from the queue. @@ -275,9 +270,9 @@ Enqueue ( **/ EFI_STATUS Dequeue ( - IN OUT USB_SIMPLE_QUEUE *Queue, - OUT VOID *Item, - IN UINTN ItemSize + IN OUT USB_SIMPLE_QUEUE *Queue, + OUT VOID *Item, + IN UINTN ItemSize ); /** @@ -296,8 +291,8 @@ Dequeue ( VOID EFIAPI USBKeyboardRepeatHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -308,7 +303,7 @@ USBKeyboardRepeatHandler ( **/ VOID SetKeyLED ( - IN USB_KB_DEV *UsbKeyboardDevice + IN USB_KB_DEV *UsbKeyboardDevice ); /** @@ -319,8 +314,8 @@ SetKeyLED ( **/ VOID InitializeKeyState ( - IN USB_KB_DEV *UsbKeyboardDevice, - OUT EFI_KEY_STATE *KeyState + IN USB_KB_DEV *UsbKeyboardDevice, + OUT EFI_KEY_STATE *KeyState ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/ComponentName.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/ComponentName.c index dff3d3a7b0..69cf36a985 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/ComponentName.c @@ -20,17 +20,16 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUsbMassStorageCompon // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMassStorageComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UsbMassStorageGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UsbMassStorageGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMassStorageComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UsbMassStorageGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UsbMassStorageGetControllerName, "en" }; - GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE -mUsbMassStorageDriverNameTable[] = { - {"eng;en", L"Usb Mass Storage Driver"}, - {NULL, NULL} + mUsbMassStorageDriverNameTable[] = { + { "eng;en", L"Usb Mass Storage Driver" }, + { NULL, NULL } }; /** @@ -145,11 +144,11 @@ UsbMassStorageGetDriverName ( EFI_STATUS EFIAPI UsbMassStorageGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMass.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMass.h index fccb203a3b..2ac9803011 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMass.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMass.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USBMASS_H_ #define _EFI_USBMASS_H_ - #include #include #include @@ -26,8 +25,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -typedef struct _USB_MASS_TRANSPORT USB_MASS_TRANSPORT; -typedef struct _USB_MASS_DEVICE USB_MASS_DEVICE; +typedef struct _USB_MASS_TRANSPORT USB_MASS_TRANSPORT; +typedef struct _USB_MASS_DEVICE USB_MASS_DEVICE; #include "UsbMassBot.h" #include "UsbMassCbi.h" @@ -44,9 +43,9 @@ typedef struct _USB_MASS_DEVICE USB_MASS_DEVICE; #define USB_MASS_1_MILLISECOND 1000 #define USB_MASS_1_SECOND (1000 * USB_MASS_1_MILLISECOND) -#define USB_MASS_CMD_SUCCESS 0 -#define USB_MASS_CMD_FAIL 1 -#define USB_MASS_CMD_PERSISTENT 2 +#define USB_MASS_CMD_SUCCESS 0 +#define USB_MASS_CMD_FAIL 1 +#define USB_MASS_CMD_PERSISTENT 2 /** Initializes USB transport protocol. @@ -65,8 +64,8 @@ typedef struct _USB_MASS_DEVICE USB_MASS_DEVICE; typedef EFI_STATUS (*USB_MASS_INIT_TRANSPORT) ( - IN EFI_USB_IO_PROTOCOL *Usb, - OUT VOID **Context OPTIONAL + IN EFI_USB_IO_PROTOCOL *Usb, + OUT VOID **Context OPTIONAL ); /** @@ -114,8 +113,8 @@ EFI_STATUS typedef EFI_STATUS (*USB_MASS_RESET) ( - IN VOID *Context, - IN BOOLEAN ExtendedVerification + IN VOID *Context, + IN BOOLEAN ExtendedVerification ); /** @@ -132,8 +131,8 @@ EFI_STATUS typedef EFI_STATUS (*USB_MASS_GET_MAX_LUN) ( - IN VOID *Context, - IN UINT8 *MaxLun + IN VOID *Context, + IN UINT8 *MaxLun ); /** @@ -147,7 +146,7 @@ EFI_STATUS typedef EFI_STATUS (*USB_MASS_CLEAN_UP) ( - IN VOID *Context + IN VOID *Context ); /// @@ -159,29 +158,29 @@ EFI_STATUS /// it is no longer necessary. /// struct _USB_MASS_TRANSPORT { - UINT8 Protocol; - USB_MASS_INIT_TRANSPORT Init; ///< Initialize the mass storage transport protocol - USB_MASS_EXEC_COMMAND ExecCommand; ///< Transport command to the device then get result - USB_MASS_RESET Reset; ///< Reset the device - USB_MASS_GET_MAX_LUN GetMaxLun; ///< Get max lun, only for bot - USB_MASS_CLEAN_UP CleanUp; ///< Clean up the resources. + UINT8 Protocol; + USB_MASS_INIT_TRANSPORT Init; ///< Initialize the mass storage transport protocol + USB_MASS_EXEC_COMMAND ExecCommand; ///< Transport command to the device then get result + USB_MASS_RESET Reset; ///< Reset the device + USB_MASS_GET_MAX_LUN GetMaxLun; ///< Get max lun, only for bot + USB_MASS_CLEAN_UP CleanUp; ///< Clean up the resources. }; struct _USB_MASS_DEVICE { - UINT32 Signature; - EFI_HANDLE Controller; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_BLOCK_IO_PROTOCOL BlockIo; - EFI_BLOCK_IO_MEDIA BlockIoMedia; - BOOLEAN OpticalStorage; - UINT8 Lun; ///< Logical Unit Number - UINT8 Pdt; ///< Peripheral Device Type - USB_MASS_TRANSPORT *Transport; ///< USB mass storage transport protocol - VOID *Context; - EFI_DISK_INFO_PROTOCOL DiskInfo; - USB_BOOT_INQUIRY_DATA InquiryData; - BOOLEAN Cdb16Byte; + UINT32 Signature; + EFI_HANDLE Controller; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_BLOCK_IO_PROTOCOL BlockIo; + EFI_BLOCK_IO_MEDIA BlockIoMedia; + BOOLEAN OpticalStorage; + UINT8 Lun; ///< Logical Unit Number + UINT8 Pdt; ///< Peripheral Device Type + USB_MASS_TRANSPORT *Transport; ///< USB mass storage transport protocol + VOID *Context; + EFI_DISK_INFO_PROTOCOL DiskInfo; + USB_BOOT_INQUIRY_DATA InquiryData; + BOOLEAN Cdb16Byte; }; #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.c index 7b29bc81fe..f648187a01 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.c @@ -24,15 +24,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS UsbBootRequestSense ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - USB_BOOT_REQUEST_SENSE_CMD SenseCmd; - USB_BOOT_REQUEST_SENSE_DATA SenseData; - EFI_BLOCK_IO_MEDIA *Media; - USB_MASS_TRANSPORT *Transport; - EFI_STATUS Status; - UINT32 CmdResult; + USB_BOOT_REQUEST_SENSE_CMD SenseCmd; + USB_BOOT_REQUEST_SENSE_DATA SenseData; + EFI_BLOCK_IO_MEDIA *Media; + USB_MASS_TRANSPORT *Transport; + EFI_STATUS Status; + UINT32 CmdResult; Transport = UsbMass->Transport; @@ -43,8 +43,8 @@ UsbBootRequestSense ( ZeroMem (&SenseData, sizeof (USB_BOOT_REQUEST_SENSE_DATA)); SenseCmd.OpCode = USB_BOOT_REQUEST_SENSE_OPCODE; - SenseCmd.Lun = (UINT8) (USB_BOOT_LUN (UsbMass->Lun)); - SenseCmd.AllocLen = (UINT8) sizeof (USB_BOOT_REQUEST_SENSE_DATA); + SenseCmd.Lun = (UINT8)(USB_BOOT_LUN (UsbMass->Lun)); + SenseCmd.AllocLen = (UINT8)sizeof (USB_BOOT_REQUEST_SENSE_DATA); Status = Transport->ExecCommand ( UsbMass->Context, @@ -57,11 +57,12 @@ UsbBootRequestSense ( USB_BOOT_GENERAL_CMD_TIMEOUT, &CmdResult ); - if (EFI_ERROR (Status) || CmdResult != USB_MASS_CMD_SUCCESS) { + if (EFI_ERROR (Status) || (CmdResult != USB_MASS_CMD_SUCCESS)) { DEBUG ((DEBUG_ERROR, "UsbBootRequestSense: (%r) CmdResult=0x%x\n", Status, CmdResult)); if (!EFI_ERROR (Status)) { Status = EFI_DEVICE_ERROR; } + return Status; } @@ -72,77 +73,80 @@ UsbBootRequestSense ( Media = &UsbMass->BlockIoMedia; switch (USB_BOOT_SENSE_KEY (SenseData.SenseKey)) { + case USB_BOOT_SENSE_NO_SENSE: + if (SenseData.Asc == USB_BOOT_ASC_NO_ADDITIONAL_SENSE_INFORMATION) { + // + // It is not an error if a device does not have additional sense information + // + Status = EFI_SUCCESS; + } else { + Status = EFI_NO_RESPONSE; + } - case USB_BOOT_SENSE_NO_SENSE: - if (SenseData.Asc == USB_BOOT_ASC_NO_ADDITIONAL_SENSE_INFORMATION) { + break; + + case USB_BOOT_SENSE_RECOVERED: // - // It is not an error if a device does not have additional sense information + // Suppose hardware can handle this case, and recover later by itself // - Status = EFI_SUCCESS; - } else { - Status = EFI_NO_RESPONSE; - } - break; - - case USB_BOOT_SENSE_RECOVERED: - // - // Suppose hardware can handle this case, and recover later by itself - // - Status = EFI_NOT_READY; - break; - - case USB_BOOT_SENSE_NOT_READY: - Status = EFI_DEVICE_ERROR; - if (SenseData.Asc == USB_BOOT_ASC_NO_MEDIA) { - Media->MediaPresent = FALSE; - Status = EFI_NO_MEDIA; - } else if (SenseData.Asc == USB_BOOT_ASC_NOT_READY) { Status = EFI_NOT_READY; - } - break; + break; - case USB_BOOT_SENSE_ILLEGAL_REQUEST: - Status = EFI_INVALID_PARAMETER; - break; + case USB_BOOT_SENSE_NOT_READY: + Status = EFI_DEVICE_ERROR; + if (SenseData.Asc == USB_BOOT_ASC_NO_MEDIA) { + Media->MediaPresent = FALSE; + Status = EFI_NO_MEDIA; + } else if (SenseData.Asc == USB_BOOT_ASC_NOT_READY) { + Status = EFI_NOT_READY; + } - case USB_BOOT_SENSE_UNIT_ATTENTION: - Status = EFI_DEVICE_ERROR; - if (SenseData.Asc == USB_BOOT_ASC_MEDIA_CHANGE) { - // - // If MediaChange, reset ReadOnly and new MediaId - // - Status = EFI_MEDIA_CHANGED; - Media->ReadOnly = FALSE; - Media->MediaId++; - } else if (SenseData.Asc == USB_BOOT_ASC_NOT_READY) { - Status = EFI_NOT_READY; - } else if (SenseData.Asc == USB_BOOT_ASC_NO_MEDIA) { - Status = EFI_NOT_READY; - } - break; + break; + + case USB_BOOT_SENSE_ILLEGAL_REQUEST: + Status = EFI_INVALID_PARAMETER; + break; + + case USB_BOOT_SENSE_UNIT_ATTENTION: + Status = EFI_DEVICE_ERROR; + if (SenseData.Asc == USB_BOOT_ASC_MEDIA_CHANGE) { + // + // If MediaChange, reset ReadOnly and new MediaId + // + Status = EFI_MEDIA_CHANGED; + Media->ReadOnly = FALSE; + Media->MediaId++; + } else if (SenseData.Asc == USB_BOOT_ASC_NOT_READY) { + Status = EFI_NOT_READY; + } else if (SenseData.Asc == USB_BOOT_ASC_NO_MEDIA) { + Status = EFI_NOT_READY; + } - case USB_BOOT_SENSE_DATA_PROTECT: - Status = EFI_WRITE_PROTECTED; - Media->ReadOnly = TRUE; - break; + break; + + case USB_BOOT_SENSE_DATA_PROTECT: + Status = EFI_WRITE_PROTECTED; + Media->ReadOnly = TRUE; + break; - default: - Status = EFI_DEVICE_ERROR; - break; + default: + Status = EFI_DEVICE_ERROR; + break; } - DEBUG ((DEBUG_INFO, "UsbBootRequestSense: (%r) with error code (%x) sense key %x/%x/%x\n", - Status, - SenseData.ErrorCode, - USB_BOOT_SENSE_KEY (SenseData.SenseKey), - SenseData.Asc, - SenseData.Ascq - )); + DEBUG (( + DEBUG_INFO, + "UsbBootRequestSense: (%r) with error code (%x) sense key %x/%x/%x\n", + Status, + SenseData.ErrorCode, + USB_BOOT_SENSE_KEY (SenseData.SenseKey), + SenseData.Asc, + SenseData.Ascq + )); return Status; } - /** Execute the USB mass storage bootability commands. @@ -164,18 +168,18 @@ UsbBootRequestSense ( **/ EFI_STATUS UsbBootExecCmd ( - IN USB_MASS_DEVICE *UsbMass, - IN VOID *Cmd, - IN UINT8 CmdLen, - IN EFI_USB_DATA_DIRECTION DataDir, - IN VOID *Data, - IN UINT32 DataLen, - IN UINT32 Timeout + IN USB_MASS_DEVICE *UsbMass, + IN VOID *Cmd, + IN UINT8 CmdLen, + IN EFI_USB_DATA_DIRECTION DataDir, + IN VOID *Data, + IN UINT32 DataLen, + IN UINT32 Timeout ) { - USB_MASS_TRANSPORT *Transport; - EFI_STATUS Status; - UINT32 CmdResult; + USB_MASS_TRANSPORT *Transport; + EFI_STATUS Status; + UINT32 CmdResult; Transport = UsbMass->Transport; Status = Transport->ExecCommand ( @@ -210,7 +214,6 @@ UsbBootExecCmd ( return UsbBootRequestSense (UsbMass); } - /** Execute the USB mass storage bootability commands with retrial. @@ -234,18 +237,18 @@ UsbBootExecCmd ( **/ EFI_STATUS UsbBootExecCmdWithRetry ( - IN USB_MASS_DEVICE *UsbMass, - IN VOID *Cmd, - IN UINT8 CmdLen, - IN EFI_USB_DATA_DIRECTION DataDir, - IN VOID *Data, - IN UINT32 DataLen, - IN UINT32 Timeout + IN USB_MASS_DEVICE *UsbMass, + IN VOID *Cmd, + IN UINT8 CmdLen, + IN EFI_USB_DATA_DIRECTION DataDir, + IN VOID *Data, + IN UINT32 DataLen, + IN UINT32 Timeout ) { - EFI_STATUS Status; - UINTN Retry; - EFI_EVENT TimeoutEvt; + EFI_STATUS Status; + UINTN Retry; + EFI_EVENT TimeoutEvt; Retry = 0; Status = EFI_SUCCESS; @@ -260,7 +263,7 @@ UsbBootExecCmdWithRetry ( return Status; } - Status = gBS->SetTimer (TimeoutEvt, TimerRelative, EFI_TIMER_PERIOD_SECONDS(60)); + Status = gBS->SetTimer (TimeoutEvt, TimerRelative, EFI_TIMER_PERIOD_SECONDS (60)); if (EFI_ERROR (Status)) { goto EXIT; } @@ -278,9 +281,10 @@ UsbBootExecCmdWithRetry ( DataLen, Timeout ); - if (Status == EFI_SUCCESS || Status == EFI_NO_MEDIA) { + if ((Status == EFI_SUCCESS) || (Status == EFI_NO_MEDIA)) { break; } + // // If the sense data shows the drive is not ready, we need execute the cmd again. // We limit the upper boundary to 60 seconds. @@ -288,6 +292,7 @@ UsbBootExecCmdWithRetry ( if (Status == EFI_NOT_READY) { continue; } + // // If the status is other error, then just retry 5 times. // @@ -304,7 +309,6 @@ EXIT: return Status; } - /** Execute TEST UNIT READY command to check if the device is ready. @@ -316,20 +320,20 @@ EXIT: **/ EFI_STATUS UsbBootIsUnitReady ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { USB_BOOT_TEST_UNIT_READY_CMD TestCmd; ZeroMem (&TestCmd, sizeof (USB_BOOT_TEST_UNIT_READY_CMD)); - TestCmd.OpCode = USB_BOOT_TEST_UNIT_READY_OPCODE; - TestCmd.Lun = (UINT8) (USB_BOOT_LUN (UsbMass->Lun)); + TestCmd.OpCode = USB_BOOT_TEST_UNIT_READY_OPCODE; + TestCmd.Lun = (UINT8)(USB_BOOT_LUN (UsbMass->Lun)); return UsbBootExecCmdWithRetry ( UsbMass, &TestCmd, - (UINT8) sizeof (USB_BOOT_TEST_UNIT_READY_CMD), + (UINT8)sizeof (USB_BOOT_TEST_UNIT_READY_CMD), EfiUsbNoData, NULL, 0, @@ -337,7 +341,6 @@ UsbBootIsUnitReady ( ); } - /** Execute INQUIRY Command to request information regarding parameters of the device be sent to the host computer. @@ -350,12 +353,12 @@ UsbBootIsUnitReady ( **/ EFI_STATUS UsbBootInquiry ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - USB_BOOT_INQUIRY_CMD InquiryCmd; - EFI_BLOCK_IO_MEDIA *Media; - EFI_STATUS Status; + USB_BOOT_INQUIRY_CMD InquiryCmd; + EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; Media = &(UsbMass->BlockIoMedia); @@ -363,13 +366,13 @@ UsbBootInquiry ( ZeroMem (&UsbMass->InquiryData, sizeof (USB_BOOT_INQUIRY_DATA)); InquiryCmd.OpCode = USB_BOOT_INQUIRY_OPCODE; - InquiryCmd.Lun = (UINT8) (USB_BOOT_LUN (UsbMass->Lun)); - InquiryCmd.AllocLen = (UINT8) sizeof (USB_BOOT_INQUIRY_DATA); + InquiryCmd.Lun = (UINT8)(USB_BOOT_LUN (UsbMass->Lun)); + InquiryCmd.AllocLen = (UINT8)sizeof (USB_BOOT_INQUIRY_DATA); Status = UsbBootExecCmdWithRetry ( UsbMass, &InquiryCmd, - (UINT8) sizeof (USB_BOOT_INQUIRY_CMD), + (UINT8)sizeof (USB_BOOT_INQUIRY_CMD), EfiUsbDataIn, &UsbMass->InquiryData, sizeof (USB_BOOT_INQUIRY_DATA), @@ -383,12 +386,12 @@ UsbBootInquiry ( // Get information from PDT (Peripheral Device Type) field and Removable Medium Bit // from the inquiry data. // - UsbMass->Pdt = (UINT8) (USB_BOOT_PDT (UsbMass->InquiryData.Pdt)); - Media->RemovableMedia = (BOOLEAN) (USB_BOOT_REMOVABLE (UsbMass->InquiryData.Removable)); + UsbMass->Pdt = (UINT8)(USB_BOOT_PDT (UsbMass->InquiryData.Pdt)); + Media->RemovableMedia = (BOOLEAN)(USB_BOOT_REMOVABLE (UsbMass->InquiryData.Removable)); // // Set block size to the default value of 512 Bytes, in case no media is present at first time. // - Media->BlockSize = 0x0200; + Media->BlockSize = 0x0200; return Status; } @@ -410,16 +413,16 @@ UsbBootInquiry ( **/ EFI_STATUS UsbBootReadCapacity16 ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - UINT8 CapacityCmd[16]; - EFI_SCSI_DISK_CAPACITY_DATA16 CapacityData; - EFI_BLOCK_IO_MEDIA *Media; - EFI_STATUS Status; - UINT32 BlockSize; + UINT8 CapacityCmd[16]; + EFI_SCSI_DISK_CAPACITY_DATA16 CapacityData; + EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; + UINT32 BlockSize; - Media = &UsbMass->BlockIoMedia; + Media = &UsbMass->BlockIoMedia; Media->MediaPresent = FALSE; Media->LastBlock = 0; @@ -428,8 +431,8 @@ UsbBootReadCapacity16 ( ZeroMem (CapacityCmd, sizeof (CapacityCmd)); ZeroMem (&CapacityData, sizeof (CapacityData)); - CapacityCmd[0] = EFI_SCSI_OP_READ_CAPACITY16; - CapacityCmd[1] = 0x10; + CapacityCmd[0] = EFI_SCSI_OP_READ_CAPACITY16; + CapacityCmd[1] = 0x10; // // Partial medium indicator, set the bytes 2 ~ 9 of the Cdb as ZERO. // @@ -440,7 +443,7 @@ UsbBootReadCapacity16 ( Status = UsbBootExecCmdWithRetry ( UsbMass, CapacityCmd, - (UINT8) sizeof (CapacityCmd), + (UINT8)sizeof (CapacityCmd), EfiUsbDataIn, &CapacityData, sizeof (CapacityData), @@ -455,13 +458,13 @@ UsbBootReadCapacity16 ( // from READ CAPACITY data. // Media->MediaPresent = TRUE; - Media->LastBlock = SwapBytes64 (ReadUnaligned64 ((CONST UINT64 *) &(CapacityData.LastLba7))); + Media->LastBlock = SwapBytes64 (ReadUnaligned64 ((CONST UINT64 *)&(CapacityData.LastLba7))); - BlockSize = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *) &(CapacityData.BlockSize3))); + BlockSize = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *)&(CapacityData.BlockSize3))); Media->LowestAlignedLba = (CapacityData.LowestAlignLogic2 << 8) | - CapacityData.LowestAlignLogic1; - Media->LogicalBlocksPerPhysicalBlock = (1 << CapacityData.LogicPerPhysical); + CapacityData.LowestAlignLogic1; + Media->LogicalBlocksPerPhysicalBlock = (1 << CapacityData.LogicPerPhysical); if (BlockSize == 0) { // // Get sense data @@ -474,7 +477,6 @@ UsbBootReadCapacity16 ( return Status; } - /** Execute READ CAPACITY command to request information regarding the capacity of the installed medium of the device. @@ -492,27 +494,27 @@ UsbBootReadCapacity16 ( **/ EFI_STATUS UsbBootReadCapacity ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - USB_BOOT_READ_CAPACITY_CMD CapacityCmd; - USB_BOOT_READ_CAPACITY_DATA CapacityData; - EFI_BLOCK_IO_MEDIA *Media; - EFI_STATUS Status; - UINT32 BlockSize; + USB_BOOT_READ_CAPACITY_CMD CapacityCmd; + USB_BOOT_READ_CAPACITY_DATA CapacityData; + EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; + UINT32 BlockSize; - Media = &UsbMass->BlockIoMedia; + Media = &UsbMass->BlockIoMedia; ZeroMem (&CapacityCmd, sizeof (USB_BOOT_READ_CAPACITY_CMD)); ZeroMem (&CapacityData, sizeof (USB_BOOT_READ_CAPACITY_DATA)); CapacityCmd.OpCode = USB_BOOT_READ_CAPACITY_OPCODE; - CapacityCmd.Lun = (UINT8) (USB_BOOT_LUN (UsbMass->Lun)); + CapacityCmd.Lun = (UINT8)(USB_BOOT_LUN (UsbMass->Lun)); Status = UsbBootExecCmdWithRetry ( UsbMass, &CapacityCmd, - (UINT8) sizeof (USB_BOOT_READ_CAPACITY_CMD), + (UINT8)sizeof (USB_BOOT_READ_CAPACITY_CMD), EfiUsbDataIn, &CapacityData, sizeof (USB_BOOT_READ_CAPACITY_DATA), @@ -527,9 +529,9 @@ UsbBootReadCapacity ( // from READ CAPACITY data. // Media->MediaPresent = TRUE; - Media->LastBlock = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *) CapacityData.LastLba)); + Media->LastBlock = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *)CapacityData.LastLba)); - BlockSize = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *) CapacityData.BlockLen)); + BlockSize = SwapBytes32 (ReadUnaligned32 ((CONST UINT32 *)CapacityData.BlockLen)); if (BlockSize == 0) { // // Get sense data @@ -560,15 +562,15 @@ UsbBootReadCapacity ( **/ EFI_STATUS UsbScsiModeSense ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - EFI_STATUS Status; - USB_SCSI_MODE_SENSE6_CMD ModeSenseCmd; - USB_SCSI_MODE_SENSE6_PARA_HEADER ModeParaHeader; - EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; + USB_SCSI_MODE_SENSE6_CMD ModeSenseCmd; + USB_SCSI_MODE_SENSE6_PARA_HEADER ModeParaHeader; + EFI_BLOCK_IO_MEDIA *Media; - Media = &UsbMass->BlockIoMedia; + Media = &UsbMass->BlockIoMedia; ZeroMem (&ModeSenseCmd, sizeof (USB_SCSI_MODE_SENSE6_CMD)); ZeroMem (&ModeParaHeader, sizeof (USB_SCSI_MODE_SENSE6_PARA_HEADER)); @@ -576,15 +578,15 @@ UsbScsiModeSense ( // // MODE SENSE(6) command is defined in Section 8.2.10 of SCSI-2 Spec // - ModeSenseCmd.OpCode = USB_SCSI_MODE_SENSE6_OPCODE; - ModeSenseCmd.Lun = (UINT8) USB_BOOT_LUN (UsbMass->Lun); - ModeSenseCmd.PageCode = 0x3F; - ModeSenseCmd.AllocateLen = (UINT8) sizeof (USB_SCSI_MODE_SENSE6_PARA_HEADER); + ModeSenseCmd.OpCode = USB_SCSI_MODE_SENSE6_OPCODE; + ModeSenseCmd.Lun = (UINT8)USB_BOOT_LUN (UsbMass->Lun); + ModeSenseCmd.PageCode = 0x3F; + ModeSenseCmd.AllocateLen = (UINT8)sizeof (USB_SCSI_MODE_SENSE6_PARA_HEADER); Status = UsbBootExecCmdWithRetry ( UsbMass, &ModeSenseCmd, - (UINT8) sizeof (USB_SCSI_MODE_SENSE6_CMD), + (UINT8)sizeof (USB_SCSI_MODE_SENSE6_CMD), EfiUsbDataIn, &ModeParaHeader, sizeof (USB_SCSI_MODE_SENSE6_PARA_HEADER), @@ -597,13 +599,12 @@ UsbScsiModeSense ( // BIT7 of this byte is indicates whether the medium is write protected. // if (!EFI_ERROR (Status)) { - Media->ReadOnly = (BOOLEAN) ((ModeParaHeader.DevicePara & BIT7) != 0); + Media->ReadOnly = (BOOLEAN)((ModeParaHeader.DevicePara & BIT7) != 0); } return Status; } - /** Get the parameters for the USB mass storage media. @@ -621,13 +622,13 @@ UsbScsiModeSense ( **/ EFI_STATUS UsbBootGetParams ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - EFI_BLOCK_IO_MEDIA *Media; - EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; - Media = &(UsbMass->BlockIoMedia); + Media = &(UsbMass->BlockIoMedia); Status = UsbBootInquiry (UsbMass); if (EFI_ERROR (Status)) { @@ -640,9 +641,10 @@ UsbBootGetParams ( // 4 Peripheral Device Types are in spec. // if ((UsbMass->Pdt != USB_PDT_DIRECT_ACCESS) && - (UsbMass->Pdt != USB_PDT_CDROM) && - (UsbMass->Pdt != USB_PDT_OPTICAL) && - (UsbMass->Pdt != USB_PDT_SIMPLE_DIRECT)) { + (UsbMass->Pdt != USB_PDT_CDROM) && + (UsbMass->Pdt != USB_PDT_OPTICAL) && + (UsbMass->Pdt != USB_PDT_SIMPLE_DIRECT)) + { DEBUG ((DEBUG_ERROR, "UsbBootGetParams: Found an unsupported peripheral type[%d]\n", UsbMass->Pdt)); return EFI_UNSUPPORTED; } @@ -659,7 +661,7 @@ UsbBootGetParams ( // // Default value 2048 Bytes, in case no media present at first time // - Media->BlockSize = 0x0800; + Media->BlockSize = 0x0800; } Status = UsbBootDetectMedia (UsbMass); @@ -667,7 +669,6 @@ UsbBootGetParams ( return Status; } - /** Detect whether the removable media is present and whether it has changed. @@ -679,19 +680,19 @@ UsbBootGetParams ( **/ EFI_STATUS UsbBootDetectMedia ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - EFI_BLOCK_IO_MEDIA OldMedia; - EFI_BLOCK_IO_MEDIA *Media; - UINT8 CmdSet; - EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA OldMedia; + EFI_BLOCK_IO_MEDIA *Media; + UINT8 CmdSet; + EFI_STATUS Status; - Media = &UsbMass->BlockIoMedia; + Media = &UsbMass->BlockIoMedia; CopyMem (&OldMedia, &(UsbMass->BlockIoMedia), sizeof (EFI_BLOCK_IO_MEDIA)); - CmdSet = ((EFI_USB_INTERFACE_DESCRIPTOR *) (UsbMass->Context))->InterfaceSubClass; + CmdSet = ((EFI_USB_INTERFACE_DESCRIPTOR *)(UsbMass->Context))->InterfaceSubClass; Status = UsbBootIsUnitReady (UsbMass); if (EFI_ERROR (Status)) { @@ -723,7 +724,7 @@ UsbBootDetectMedia ( } } - if (EFI_ERROR (Status) && Status != EFI_NO_MEDIA) { + if (EFI_ERROR (Status) && (Status != EFI_NO_MEDIA)) { // // For NoMedia, BlockIo is still needed. // @@ -749,8 +750,8 @@ UsbBootDetectMedia ( (Media->MediaPresent != OldMedia.MediaPresent) || (Media->ReadOnly != OldMedia.ReadOnly) || (Media->BlockSize != OldMedia.BlockSize) || - (Media->LastBlock != OldMedia.LastBlock)) { - + (Media->LastBlock != OldMedia.LastBlock)) + { // // This function is called from: // Block I/O Protocol APIs, which run at TPL_CALLBACK. @@ -781,7 +782,8 @@ UsbBootDetectMedia ( if ((Media->ReadOnly != OldMedia.ReadOnly) || (Media->BlockSize != OldMedia.BlockSize) || - (Media->LastBlock != OldMedia.LastBlock)) { + (Media->LastBlock != OldMedia.LastBlock)) + { Media->MediaId++; } @@ -791,7 +793,6 @@ UsbBootDetectMedia ( return Status; } - /** Read or write some blocks from the device. @@ -807,20 +808,20 @@ UsbBootDetectMedia ( **/ EFI_STATUS UsbBootReadWriteBlocks ( - IN USB_MASS_DEVICE *UsbMass, - IN BOOLEAN Write, - IN UINT32 Lba, - IN UINTN TotalBlock, - IN OUT UINT8 *Buffer + IN USB_MASS_DEVICE *UsbMass, + IN BOOLEAN Write, + IN UINT32 Lba, + IN UINTN TotalBlock, + IN OUT UINT8 *Buffer ) { - USB_BOOT_READ_WRITE_10_CMD Cmd; - EFI_STATUS Status; - UINT32 Count; - UINT32 CountMax; - UINT32 BlockSize; - UINT32 ByteSize; - UINT32 Timeout; + USB_BOOT_READ_WRITE_10_CMD Cmd; + EFI_STATUS Status; + UINT32 Count; + UINT32 CountMax; + UINT32 BlockSize; + UINT32 ByteSize; + UINT32 Timeout; BlockSize = UsbMass->BlockIoMedia.BlockSize; CountMax = USB_BOOT_MAX_CARRY_SIZE / BlockSize; @@ -839,22 +840,22 @@ UsbBootReadWriteBlocks ( // // USB command's upper limit timeout is 5s. [USB2.0-9.2.6.1] // - Timeout = (UINT32) USB_BOOT_GENERAL_CMD_TIMEOUT; + Timeout = (UINT32)USB_BOOT_GENERAL_CMD_TIMEOUT; // // Fill in the command then execute // ZeroMem (&Cmd, sizeof (USB_BOOT_READ_WRITE_10_CMD)); - Cmd.OpCode = Write ? USB_BOOT_WRITE10_OPCODE : USB_BOOT_READ10_OPCODE; - Cmd.Lun = (UINT8) (USB_BOOT_LUN (UsbMass->Lun)); - WriteUnaligned32 ((UINT32 *) Cmd.Lba, SwapBytes32 (Lba)); - WriteUnaligned16 ((UINT16 *) Cmd.TransferLen, SwapBytes16 ((UINT16)Count)); + Cmd.OpCode = Write ? USB_BOOT_WRITE10_OPCODE : USB_BOOT_READ10_OPCODE; + Cmd.Lun = (UINT8)(USB_BOOT_LUN (UsbMass->Lun)); + WriteUnaligned32 ((UINT32 *)Cmd.Lba, SwapBytes32 (Lba)); + WriteUnaligned16 ((UINT16 *)Cmd.TransferLen, SwapBytes16 ((UINT16)Count)); Status = UsbBootExecCmdWithRetry ( UsbMass, &Cmd, - (UINT8) sizeof (USB_BOOT_READ_WRITE_10_CMD), + (UINT8)sizeof (USB_BOOT_READ_WRITE_10_CMD), Write ? EfiUsbDataOut : EfiUsbDataIn, Buffer, ByteSize, @@ -863,10 +864,13 @@ UsbBootReadWriteBlocks ( if (EFI_ERROR (Status)) { return Status; } + DEBUG (( - DEBUG_BLKIO, "UsbBoot%sBlocks: LBA (0x%lx), Blk (0x%x)\n", + DEBUG_BLKIO, + "UsbBoot%sBlocks: LBA (0x%lx), Blk (0x%x)\n", Write ? L"Write" : L"Read", - Lba, Count + Lba, + Count )); Lba += Count; Buffer += ByteSize; @@ -890,20 +894,20 @@ UsbBootReadWriteBlocks ( **/ EFI_STATUS UsbBootReadWriteBlocks16 ( - IN USB_MASS_DEVICE *UsbMass, - IN BOOLEAN Write, - IN UINT64 Lba, - IN UINTN TotalBlock, - IN OUT UINT8 *Buffer + IN USB_MASS_DEVICE *UsbMass, + IN BOOLEAN Write, + IN UINT64 Lba, + IN UINTN TotalBlock, + IN OUT UINT8 *Buffer ) { - UINT8 Cmd[16]; - EFI_STATUS Status; - UINT32 Count; - UINT32 CountMax; - UINT32 BlockSize; - UINT32 ByteSize; - UINT32 Timeout; + UINT8 Cmd[16]; + EFI_STATUS Status; + UINT32 Count; + UINT32 CountMax; + UINT32 BlockSize; + UINT32 ByteSize; + UINT32 Timeout; BlockSize = UsbMass->BlockIoMedia.BlockSize; CountMax = USB_BOOT_MAX_CARRY_SIZE / BlockSize; @@ -919,22 +923,22 @@ UsbBootReadWriteBlocks16 ( // // USB command's upper limit timeout is 5s. [USB2.0-9.2.6.1] // - Timeout = (UINT32) USB_BOOT_GENERAL_CMD_TIMEOUT; + Timeout = (UINT32)USB_BOOT_GENERAL_CMD_TIMEOUT; // // Fill in the command then execute // ZeroMem (Cmd, sizeof (Cmd)); - Cmd[0] = Write ? EFI_SCSI_OP_WRITE16 : EFI_SCSI_OP_READ16; - Cmd[1] = (UINT8) ((USB_BOOT_LUN (UsbMass->Lun) & 0xE0)); - WriteUnaligned64 ((UINT64 *) &Cmd[2], SwapBytes64 (Lba)); - WriteUnaligned32 ((UINT32 *) &Cmd[10], SwapBytes32 (Count)); + Cmd[0] = Write ? EFI_SCSI_OP_WRITE16 : EFI_SCSI_OP_READ16; + Cmd[1] = (UINT8)((USB_BOOT_LUN (UsbMass->Lun) & 0xE0)); + WriteUnaligned64 ((UINT64 *)&Cmd[2], SwapBytes64 (Lba)); + WriteUnaligned32 ((UINT32 *)&Cmd[10], SwapBytes32 (Count)); Status = UsbBootExecCmdWithRetry ( UsbMass, Cmd, - (UINT8) sizeof (Cmd), + (UINT8)sizeof (Cmd), Write ? EfiUsbDataOut : EfiUsbDataIn, Buffer, ByteSize, @@ -943,10 +947,13 @@ UsbBootReadWriteBlocks16 ( if (EFI_ERROR (Status)) { return Status; } + DEBUG (( - DEBUG_BLKIO, "UsbBoot%sBlocks16: LBA (0x%lx), Blk (0x%x)\n", + DEBUG_BLKIO, + "UsbBoot%sBlocks16: LBA (0x%lx), Blk (0x%x)\n", Write ? L"Write" : L"Read", - Lba, Count + Lba, + Count )); Lba += Count; Buffer += ByteSize; @@ -968,14 +975,14 @@ UsbBootReadWriteBlocks16 ( **/ EFI_STATUS UsbClearEndpointStall ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN UINT8 EndpointAddr + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN UINT8 EndpointAddr ) { - EFI_USB_DEVICE_REQUEST Request; - EFI_STATUS Status; - UINT32 CmdResult; - UINT32 Timeout; + EFI_USB_DEVICE_REQUEST Request; + EFI_STATUS Status; + UINT32 CmdResult; + UINT32 Timeout; Request.RequestType = 0x02; Request.Request = USB_REQ_CLEAR_FEATURE; diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.h index f34a41284e..6722c3b003 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBoot.h @@ -17,15 +17,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Others are "Group 1 Timeout Commands". That is, // they should be retried if driver is ready. // -#define USB_BOOT_INQUIRY_OPCODE 0x12 -#define USB_BOOT_REQUEST_SENSE_OPCODE 0x03 -#define USB_BOOT_MODE_SENSE10_OPCODE 0x5A -#define USB_BOOT_READ_CAPACITY_OPCODE 0x25 -#define USB_BOOT_TEST_UNIT_READY_OPCODE 0x00 -#define USB_BOOT_READ10_OPCODE 0x28 -#define USB_BOOT_WRITE10_OPCODE 0x2A +#define USB_BOOT_INQUIRY_OPCODE 0x12 +#define USB_BOOT_REQUEST_SENSE_OPCODE 0x03 +#define USB_BOOT_MODE_SENSE10_OPCODE 0x5A +#define USB_BOOT_READ_CAPACITY_OPCODE 0x25 +#define USB_BOOT_TEST_UNIT_READY_OPCODE 0x00 +#define USB_BOOT_READ10_OPCODE 0x28 +#define USB_BOOT_WRITE10_OPCODE 0x2A -#define USB_SCSI_MODE_SENSE6_OPCODE 0x1A +#define USB_SCSI_MODE_SENSE6_OPCODE 0x1A // // The Sense Key part of the sense data. Sense data has three levels: @@ -53,25 +53,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Supported PDT codes, or Peripheral Device Type // -#define USB_PDT_DIRECT_ACCESS 0x00 ///< Direct access device -#define USB_PDT_CDROM 0x05 ///< CDROM -#define USB_PDT_OPTICAL 0x07 ///< Non-CD optical disks -#define USB_PDT_SIMPLE_DIRECT 0x0E ///< Simplified direct access device +#define USB_PDT_DIRECT_ACCESS 0x00 ///< Direct access device +#define USB_PDT_CDROM 0x05 ///< CDROM +#define USB_PDT_OPTICAL 0x07 ///< Non-CD optical disks +#define USB_PDT_SIMPLE_DIRECT 0x0E ///< Simplified direct access device // // Other parameters, Max carried size is 64KB. // -#define USB_BOOT_MAX_CARRY_SIZE SIZE_64KB +#define USB_BOOT_MAX_CARRY_SIZE SIZE_64KB // // Retry mass command times, set by experience // -#define USB_BOOT_COMMAND_RETRY 5 +#define USB_BOOT_COMMAND_RETRY 5 // // Wait for unit ready command, set by experience // -#define USB_BOOT_RETRY_UNIT_READY_STALL (500 * USB_MASS_1_MILLISECOND) +#define USB_BOOT_RETRY_UNIT_READY_STALL (500 * USB_MASS_1_MILLISECOND) // // Mass command timeout, refers to specification[USB20-9.2.6.1] @@ -80,7 +80,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // USB CD-Rom and iPod devices are much slower than USB key when response // most of commands, So we set 5s as timeout here. // -#define USB_BOOT_GENERAL_CMD_TIMEOUT (5 * USB_MASS_1_SECOND) +#define USB_BOOT_GENERAL_CMD_TIMEOUT (5 * USB_MASS_1_SECOND) // // The required commands are INQUIRY, READ CAPACITY, TEST UNIT READY, @@ -90,122 +90,122 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #pragma pack(1) typedef struct { - UINT8 OpCode; - UINT8 Lun; ///< Lun (high 3 bits) - UINT8 Reserved0[2]; - UINT8 AllocLen; - UINT8 Reserved1; - UINT8 Pad[6]; + UINT8 OpCode; + UINT8 Lun; ///< Lun (high 3 bits) + UINT8 Reserved0[2]; + UINT8 AllocLen; + UINT8 Reserved1; + UINT8 Pad[6]; } USB_BOOT_INQUIRY_CMD; typedef struct { - UINT8 Pdt; ///< Peripheral Device Type (low 5 bits) - UINT8 Removable; ///< Removable Media (highest bit) - UINT8 Reserved0[2]; - UINT8 AddLen; ///< Additional length - UINT8 Reserved1[3]; - UINT8 VendorID[8]; - UINT8 ProductID[16]; - UINT8 ProductRevision[4]; + UINT8 Pdt; ///< Peripheral Device Type (low 5 bits) + UINT8 Removable; ///< Removable Media (highest bit) + UINT8 Reserved0[2]; + UINT8 AddLen; ///< Additional length + UINT8 Reserved1[3]; + UINT8 VendorID[8]; + UINT8 ProductID[16]; + UINT8 ProductRevision[4]; } USB_BOOT_INQUIRY_DATA; typedef struct { - UINT8 OpCode; - UINT8 Lun; - UINT8 Reserved0[8]; - UINT8 Pad[2]; + UINT8 OpCode; + UINT8 Lun; + UINT8 Reserved0[8]; + UINT8 Pad[2]; } USB_BOOT_READ_CAPACITY_CMD; typedef struct { - UINT8 LastLba[4]; - UINT8 BlockLen[4]; + UINT8 LastLba[4]; + UINT8 BlockLen[4]; } USB_BOOT_READ_CAPACITY_DATA; typedef struct { - UINT8 OpCode; - UINT8 Lun; - UINT8 Reserved[4]; - UINT8 Pad[6]; + UINT8 OpCode; + UINT8 Lun; + UINT8 Reserved[4]; + UINT8 Pad[6]; } USB_BOOT_TEST_UNIT_READY_CMD; typedef struct { - UINT8 OpCode; - UINT8 Lun; - UINT8 PageCode; - UINT8 Reserved0[4]; - UINT8 ParaListLenMsb; - UINT8 ParaListLenLsb; - UINT8 Reserved1; - UINT8 Pad[2]; + UINT8 OpCode; + UINT8 Lun; + UINT8 PageCode; + UINT8 Reserved0[4]; + UINT8 ParaListLenMsb; + UINT8 ParaListLenLsb; + UINT8 Reserved1; + UINT8 Pad[2]; } USB_BOOT_MODE_SENSE10_CMD; typedef struct { - UINT8 ModeDataLenMsb; - UINT8 ModeDataLenLsb; - UINT8 Reserved0[4]; - UINT8 BlkDesLenMsb; - UINT8 BlkDesLenLsb; + UINT8 ModeDataLenMsb; + UINT8 ModeDataLenLsb; + UINT8 Reserved0[4]; + UINT8 BlkDesLenMsb; + UINT8 BlkDesLenLsb; } USB_BOOT_MODE_SENSE10_PARA_HEADER; typedef struct { - UINT8 OpCode; - UINT8 Lun; ///< Lun (High 3 bits) - UINT8 Lba[4]; ///< Logical block address - UINT8 Reserved0; - UINT8 TransferLen[2]; ///< Transfer length - UINT8 Reserverd1; - UINT8 Pad[2]; + UINT8 OpCode; + UINT8 Lun; ///< Lun (High 3 bits) + UINT8 Lba[4]; ///< Logical block address + UINT8 Reserved0; + UINT8 TransferLen[2]; ///< Transfer length + UINT8 Reserverd1; + UINT8 Pad[2]; } USB_BOOT_READ_WRITE_10_CMD; typedef struct { - UINT8 OpCode; - UINT8 Lun; ///< Lun (High 3 bits) - UINT8 Reserved0[2]; - UINT8 AllocLen; ///< Allocation length - UINT8 Reserved1; - UINT8 Pad[6]; + UINT8 OpCode; + UINT8 Lun; ///< Lun (High 3 bits) + UINT8 Reserved0[2]; + UINT8 AllocLen; ///< Allocation length + UINT8 Reserved1; + UINT8 Pad[6]; } USB_BOOT_REQUEST_SENSE_CMD; typedef struct { - UINT8 ErrorCode; - UINT8 Reserved0; - UINT8 SenseKey; ///< Sense key (low 4 bits) - UINT8 Infor[4]; - UINT8 AddLen; ///< Additional Sense length, 10 - UINT8 Reserved1[4]; - UINT8 Asc; ///< Additional Sense Code - UINT8 Ascq; ///< Additional Sense Code Qualifier - UINT8 Reserverd2[4]; + UINT8 ErrorCode; + UINT8 Reserved0; + UINT8 SenseKey; ///< Sense key (low 4 bits) + UINT8 Infor[4]; + UINT8 AddLen; ///< Additional Sense length, 10 + UINT8 Reserved1[4]; + UINT8 Asc; ///< Additional Sense Code + UINT8 Ascq; ///< Additional Sense Code Qualifier + UINT8 Reserverd2[4]; } USB_BOOT_REQUEST_SENSE_DATA; typedef struct { - UINT8 OpCode; - UINT8 Lun; - UINT8 PageCode; - UINT8 Reserved0; - UINT8 AllocateLen; - UINT8 Control; + UINT8 OpCode; + UINT8 Lun; + UINT8 PageCode; + UINT8 Reserved0; + UINT8 AllocateLen; + UINT8 Control; } USB_SCSI_MODE_SENSE6_CMD; typedef struct { - UINT8 ModeDataLen; - UINT8 MediumType; - UINT8 DevicePara; - UINT8 BlkDesLen; + UINT8 ModeDataLen; + UINT8 MediumType; + UINT8 DevicePara; + UINT8 BlkDesLen; } USB_SCSI_MODE_SENSE6_PARA_HEADER; #pragma pack() // // Convert a LUN number to that in the command // -#define USB_BOOT_LUN(Lun) ((Lun) << 5) +#define USB_BOOT_LUN(Lun) ((Lun) << 5) // // Get the removable, PDT, and sense key bits from the command data // -#define USB_BOOT_REMOVABLE(RmbByte) (((RmbByte) & BIT7) != 0) -#define USB_BOOT_PDT(Pdt) ((Pdt) & 0x1f) -#define USB_BOOT_SENSE_KEY(Key) ((Key) & 0x0f) +#define USB_BOOT_REMOVABLE(RmbByte) (((RmbByte) & BIT7) != 0) +#define USB_BOOT_PDT(Pdt) ((Pdt) & 0x1f) +#define USB_BOOT_SENSE_KEY(Key) ((Key) & 0x0f) /** Get the parameters for the USB mass storage media. @@ -224,7 +224,7 @@ typedef struct { **/ EFI_STATUS UsbBootGetParams ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ); /** @@ -238,7 +238,7 @@ UsbBootGetParams ( **/ EFI_STATUS UsbBootIsUnitReady ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ); /** @@ -252,7 +252,7 @@ UsbBootIsUnitReady ( **/ EFI_STATUS UsbBootDetectMedia ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ); /** @@ -269,10 +269,10 @@ UsbBootDetectMedia ( **/ EFI_STATUS UsbBootReadBlocks ( - IN USB_MASS_DEVICE *UsbMass, - IN UINT32 Lba, - IN UINTN TotalBlock, - OUT UINT8 *Buffer + IN USB_MASS_DEVICE *UsbMass, + IN UINT32 Lba, + IN UINTN TotalBlock, + OUT UINT8 *Buffer ); /** @@ -290,11 +290,11 @@ UsbBootReadBlocks ( **/ EFI_STATUS UsbBootReadWriteBlocks ( - IN USB_MASS_DEVICE *UsbMass, - IN BOOLEAN Write, - IN UINT32 Lba, - IN UINTN TotalBlock, - IN OUT UINT8 *Buffer + IN USB_MASS_DEVICE *UsbMass, + IN BOOLEAN Write, + IN UINT32 Lba, + IN UINTN TotalBlock, + IN OUT UINT8 *Buffer ); /** @@ -311,11 +311,11 @@ UsbBootReadWriteBlocks ( **/ EFI_STATUS UsbBootReadWriteBlocks16 ( - IN USB_MASS_DEVICE *UsbMass, - IN BOOLEAN Write, - IN UINT64 Lba, - IN UINTN TotalBlock, - IN OUT UINT8 *Buffer + IN USB_MASS_DEVICE *UsbMass, + IN BOOLEAN Write, + IN UINT64 Lba, + IN UINTN TotalBlock, + IN OUT UINT8 *Buffer ); /** @@ -330,9 +330,8 @@ UsbBootReadWriteBlocks16 ( **/ EFI_STATUS UsbClearEndpointStall ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN UINT8 EndpointAddr + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN UINT8 EndpointAddr ); #endif - diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.c index ce252e60fc..55c239d33e 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.c @@ -12,7 +12,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Definition of USB BOT Transport Protocol // -USB_MASS_TRANSPORT mUsbBotTransport = { +USB_MASS_TRANSPORT mUsbBotTransport = { USB_MASS_STORE_BOT, UsbBotInit, UsbBotExecCommand, @@ -38,8 +38,8 @@ USB_MASS_TRANSPORT mUsbBotTransport = { **/ EFI_STATUS UsbBotInit ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - OUT VOID **Context OPTIONAL + IN EFI_USB_IO_PROTOCOL *UsbIo, + OUT VOID **Context OPTIONAL ) { USB_BOT_PROTOCOL *UsbBot; @@ -84,17 +84,17 @@ UsbBotInit ( } if (USB_IS_IN_ENDPOINT (EndPoint.EndpointAddress) && - (UsbBot->BulkInEndpoint == NULL)) { - - UsbBot->BulkInEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *) (UsbBot + 1); - CopyMem(UsbBot->BulkInEndpoint, &EndPoint, sizeof (EndPoint)); + (UsbBot->BulkInEndpoint == NULL)) + { + UsbBot->BulkInEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *)(UsbBot + 1); + CopyMem (UsbBot->BulkInEndpoint, &EndPoint, sizeof (EndPoint)); } if (USB_IS_OUT_ENDPOINT (EndPoint.EndpointAddress) && - (UsbBot->BulkOutEndpoint == NULL)) { - - UsbBot->BulkOutEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *) (UsbBot + 1) + 1; - CopyMem (UsbBot->BulkOutEndpoint, &EndPoint, sizeof(EndPoint)); + (UsbBot->BulkOutEndpoint == NULL)) + { + UsbBot->BulkOutEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *)(UsbBot + 1) + 1; + CopyMem (UsbBot->BulkOutEndpoint, &EndPoint, sizeof (EndPoint)); } } @@ -145,19 +145,19 @@ ON_ERROR: **/ EFI_STATUS UsbBotSendCommand ( - IN USB_BOT_PROTOCOL *UsbBot, - IN UINT8 *Cmd, - IN UINT8 CmdLen, - IN EFI_USB_DATA_DIRECTION DataDir, - IN UINT32 TransLen, - IN UINT8 Lun + IN USB_BOT_PROTOCOL *UsbBot, + IN UINT8 *Cmd, + IN UINT8 CmdLen, + IN EFI_USB_DATA_DIRECTION DataDir, + IN UINT32 TransLen, + IN UINT8 Lun ) { - USB_BOT_CBW Cbw; - EFI_STATUS Status; - UINT32 Result; - UINTN DataLen; - UINTN Timeout; + USB_BOT_CBW Cbw; + EFI_STATUS Status; + UINT32 Result; + UINTN DataLen; + UINTN Timeout; ASSERT ((CmdLen > 0) && (CmdLen <= USB_BOT_MAX_CMDLEN)); @@ -167,7 +167,7 @@ UsbBotSendCommand ( Cbw.Signature = USB_BOT_CBW_SIGNATURE; Cbw.Tag = UsbBot->CbwTag; Cbw.DataLen = TransLen; - Cbw.Flag = (UINT8) ((DataDir == EfiUsbDataIn) ? BIT7 : 0); + Cbw.Flag = (UINT8)((DataDir == EfiUsbDataIn) ? BIT7 : 0); Cbw.Lun = Lun; Cbw.CmdLen = CmdLen; @@ -190,7 +190,7 @@ UsbBotSendCommand ( &Result ); if (EFI_ERROR (Status)) { - if (USB_IS_ERROR (Result, EFI_USB_ERR_STALL) && DataDir == EfiUsbDataOut) { + if (USB_IS_ERROR (Result, EFI_USB_ERR_STALL) && (DataDir == EfiUsbDataOut)) { // // Respond to Bulk-Out endpoint stall with a Reset Recovery, // according to section 5.3.1 of USB Mass Storage Class Bulk-Only Transport Spec, v1.0. @@ -204,7 +204,6 @@ UsbBotSendCommand ( return Status; } - /** Transfer the data between the device and host. @@ -226,16 +225,16 @@ UsbBotSendCommand ( **/ EFI_STATUS UsbBotDataTransfer ( - IN USB_BOT_PROTOCOL *UsbBot, - IN EFI_USB_DATA_DIRECTION DataDir, - IN OUT UINT8 *Data, - IN OUT UINTN *TransLen, - IN UINT32 Timeout + IN USB_BOT_PROTOCOL *UsbBot, + IN EFI_USB_DATA_DIRECTION DataDir, + IN OUT UINT8 *Data, + IN OUT UINTN *TransLen, + IN UINT32 Timeout ) { - EFI_USB_ENDPOINT_DESCRIPTOR *Endpoint; - EFI_STATUS Status; - UINT32 Result; + EFI_USB_ENDPOINT_DESCRIPTOR *Endpoint; + EFI_STATUS Status; + UINT32 Result; // // If no data to transfer, just return EFI_SUCCESS. @@ -274,15 +273,15 @@ UsbBotDataTransfer ( } else { DEBUG ((DEBUG_ERROR, "UsbBotDataTransfer: (%r)\n", Status)); } - if(Status == EFI_TIMEOUT){ - UsbBotResetDevice(UsbBot, FALSE); + + if (Status == EFI_TIMEOUT) { + UsbBotResetDevice (UsbBot, FALSE); } } return Status; } - /** Get the command execution status from device. @@ -304,19 +303,19 @@ UsbBotDataTransfer ( **/ EFI_STATUS UsbBotGetStatus ( - IN USB_BOT_PROTOCOL *UsbBot, - IN UINT32 TransLen, - OUT UINT8 *CmdStatus + IN USB_BOT_PROTOCOL *UsbBot, + IN UINT32 TransLen, + OUT UINT8 *CmdStatus ) { - USB_BOT_CSW Csw; - UINTN Len; - UINT8 Endpoint; - EFI_STATUS Status; - UINT32 Result; - EFI_USB_IO_PROTOCOL *UsbIo; - UINT32 Index; - UINTN Timeout; + USB_BOT_CSW Csw; + UINTN Len; + UINT8 Endpoint; + EFI_STATUS Status; + UINT32 Result; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT32 Index; + UINTN Timeout; *CmdStatus = USB_BOT_COMMAND_ERROR; Status = EFI_DEVICE_ERROR; @@ -339,10 +338,11 @@ UsbBotGetStatus ( Timeout, &Result ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { if (USB_IS_ERROR (Result, EFI_USB_ERR_STALL)) { UsbClearEndpointStall (UsbIo, Endpoint); } + continue; } @@ -361,15 +361,15 @@ UsbBotGetStatus ( break; } } + // - //The tag is increased even if there is an error. + // The tag is increased even if there is an error. // UsbBot->CbwTag++; return Status; } - /** Call the USB Mass Storage Class BOT protocol to issue the command/data/status circle to execute the commands. @@ -402,13 +402,13 @@ UsbBotExecCommand ( OUT UINT32 *CmdStatus ) { - USB_BOT_PROTOCOL *UsbBot; - EFI_STATUS Status; - UINTN TransLen; - UINT8 Result; + USB_BOT_PROTOCOL *UsbBot; + EFI_STATUS Status; + UINTN TransLen; + UINT8 Result; - *CmdStatus = USB_MASS_CMD_FAIL; - UsbBot = (USB_BOT_PROTOCOL *) Context; + *CmdStatus = USB_MASS_CMD_FAIL; + UsbBot = (USB_BOT_PROTOCOL *)Context; // // Send the command to the device. Return immediately if device @@ -425,7 +425,7 @@ UsbBotExecCommand ( // failed. The host should attempt to receive the CSW no matter // whether it succeeds or fails. // - TransLen = (UINTN) DataLen; + TransLen = (UINTN)DataLen; UsbBotDataTransfer (UsbBot, DataDir, Data, &TransLen, Timeout); // @@ -444,7 +444,6 @@ UsbBotExecCommand ( return EFI_SUCCESS; } - /** Reset the USB mass storage device by BOT protocol. @@ -459,8 +458,8 @@ UsbBotExecCommand ( **/ EFI_STATUS UsbBotResetDevice ( - IN VOID *Context, - IN BOOLEAN ExtendedVerification + IN VOID *Context, + IN BOOLEAN ExtendedVerification ) { USB_BOT_PROTOCOL *UsbBot; @@ -469,7 +468,7 @@ UsbBotResetDevice ( UINT32 Result; UINT32 Timeout; - UsbBot = (USB_BOT_PROTOCOL *) Context; + UsbBot = (USB_BOT_PROTOCOL *)Context; if (ExtendedVerification) { // @@ -522,7 +521,6 @@ UsbBotResetDevice ( return Status; } - /** Get the max LUN (Logical Unit Number) of USB mass storage device. @@ -536,8 +534,8 @@ UsbBotResetDevice ( **/ EFI_STATUS UsbBotGetMaxLun ( - IN VOID *Context, - OUT UINT8 *MaxLun + IN VOID *Context, + OUT UINT8 *MaxLun ) { USB_BOT_PROTOCOL *UsbBot; @@ -546,11 +544,11 @@ UsbBotGetMaxLun ( UINT32 Result; UINT32 Timeout; - if (Context == NULL || MaxLun == NULL) { + if ((Context == NULL) || (MaxLun == NULL)) { return EFI_INVALID_PARAMETER; } - UsbBot = (USB_BOT_PROTOCOL *) Context; + UsbBot = (USB_BOT_PROTOCOL *)Context; // // Issue a class specific Bulk-Only Mass Storage get max lun request. @@ -568,11 +566,11 @@ UsbBotGetMaxLun ( &Request, EfiUsbDataIn, Timeout, - (VOID *) MaxLun, + (VOID *)MaxLun, 1, &Result ); - if (EFI_ERROR (Status) || *MaxLun > USB_BOT_MAX_LUN) { + if (EFI_ERROR (Status) || (*MaxLun > USB_BOT_MAX_LUN)) { // // If the Get LUN request returns an error or the MaxLun is larger than // the maximum LUN value (0x0f) supported by the USB Mass Storage Class @@ -598,7 +596,7 @@ UsbBotGetMaxLun ( **/ EFI_STATUS UsbBotCleanUp ( - IN VOID *Context + IN VOID *Context ) { FreePool (Context); diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.h index 3ef8f240a2..cf8e9a3bdd 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassBot.h @@ -11,29 +11,29 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USBMASS_BOT_H_ #define _EFI_USBMASS_BOT_H_ -extern USB_MASS_TRANSPORT mUsbBotTransport; +extern USB_MASS_TRANSPORT mUsbBotTransport; // // Usb Bulk-Only class specific request // -#define USB_BOT_RESET_REQUEST 0xFF ///< Bulk-Only Mass Storage Reset -#define USB_BOT_GETLUN_REQUEST 0xFE ///< Get Max Lun -#define USB_BOT_CBW_SIGNATURE 0x43425355 ///< dCBWSignature, tag the packet as CBW -#define USB_BOT_CSW_SIGNATURE 0x53425355 ///< dCSWSignature, tag the packet as CSW -#define USB_BOT_MAX_LUN 0x0F ///< Lun number is from 0 to 15 -#define USB_BOT_MAX_CMDLEN 16 ///< Maximum number of command from command set +#define USB_BOT_RESET_REQUEST 0xFF ///< Bulk-Only Mass Storage Reset +#define USB_BOT_GETLUN_REQUEST 0xFE ///< Get Max Lun +#define USB_BOT_CBW_SIGNATURE 0x43425355 ///< dCBWSignature, tag the packet as CBW +#define USB_BOT_CSW_SIGNATURE 0x53425355 ///< dCSWSignature, tag the packet as CSW +#define USB_BOT_MAX_LUN 0x0F ///< Lun number is from 0 to 15 +#define USB_BOT_MAX_CMDLEN 16 ///< Maximum number of command from command set // // Usb BOT command block status values // -#define USB_BOT_COMMAND_OK 0x00 ///< Command passed, good status -#define USB_BOT_COMMAND_FAILED 0x01 ///< Command failed -#define USB_BOT_COMMAND_ERROR 0x02 ///< Phase error, need to reset the device +#define USB_BOT_COMMAND_OK 0x00 ///< Command passed, good status +#define USB_BOT_COMMAND_FAILED 0x01 ///< Command failed +#define USB_BOT_COMMAND_ERROR 0x02 ///< Phase error, need to reset the device // // Usb Bot retry to get CSW, refers to specification[BOT10-5.3, it says 2 times] // -#define USB_BOT_RECV_CSW_RETRY 3 +#define USB_BOT_RECV_CSW_RETRY 3 // // Usb Bot wait device reset complete, set by experience @@ -43,32 +43,32 @@ extern USB_MASS_TRANSPORT mUsbBotTransport; // // Usb Bot transport timeout, set by experience // -#define USB_BOT_SEND_CBW_TIMEOUT (3 * USB_MASS_1_SECOND) -#define USB_BOT_RECV_CSW_TIMEOUT (3 * USB_MASS_1_SECOND) -#define USB_BOT_RESET_DEVICE_TIMEOUT (3 * USB_MASS_1_SECOND) +#define USB_BOT_SEND_CBW_TIMEOUT (3 * USB_MASS_1_SECOND) +#define USB_BOT_RECV_CSW_TIMEOUT (3 * USB_MASS_1_SECOND) +#define USB_BOT_RESET_DEVICE_TIMEOUT (3 * USB_MASS_1_SECOND) #pragma pack(1) /// /// The CBW (Command Block Wrapper) structures used by the USB BOT protocol. /// typedef struct { - UINT32 Signature; - UINT32 Tag; - UINT32 DataLen; ///< Length of data between CBW and CSW - UINT8 Flag; ///< Bit 7, 0 ~ Data-Out, 1 ~ Data-In - UINT8 Lun; ///< Lun number. Bits 0~3 are used - UINT8 CmdLen; ///< Length of the command. Bits 0~4 are used - UINT8 CmdBlock[USB_BOT_MAX_CMDLEN]; + UINT32 Signature; + UINT32 Tag; + UINT32 DataLen; ///< Length of data between CBW and CSW + UINT8 Flag; ///< Bit 7, 0 ~ Data-Out, 1 ~ Data-In + UINT8 Lun; ///< Lun number. Bits 0~3 are used + UINT8 CmdLen; ///< Length of the command. Bits 0~4 are used + UINT8 CmdBlock[USB_BOT_MAX_CMDLEN]; } USB_BOT_CBW; /// /// The and CSW (Command Status Wrapper) structures used by the USB BOT protocol. /// typedef struct { - UINT32 Signature; - UINT32 Tag; - UINT32 DataResidue; - UINT8 CmdStatus; + UINT32 Signature; + UINT32 Tag; + UINT32 DataResidue; + UINT8 CmdStatus; } USB_BOT_CSW; #pragma pack() @@ -76,11 +76,11 @@ typedef struct { // // Put Interface at the first field to make it easy to distinguish BOT/CBI Protocol instance // - EFI_USB_INTERFACE_DESCRIPTOR Interface; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; - UINT32 CbwTag; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_USB_INTERFACE_DESCRIPTOR Interface; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; + UINT32 CbwTag; + EFI_USB_IO_PROTOCOL *UsbIo; } USB_BOT_PROTOCOL; /** @@ -100,8 +100,8 @@ typedef struct { **/ EFI_STATUS UsbBotInit ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - OUT VOID **Context OPTIONAL + IN EFI_USB_IO_PROTOCOL *UsbIo, + OUT VOID **Context OPTIONAL ); /** @@ -150,8 +150,8 @@ UsbBotExecCommand ( **/ EFI_STATUS UsbBotResetDevice ( - IN VOID *Context, - IN BOOLEAN ExtendedVerification + IN VOID *Context, + IN BOOLEAN ExtendedVerification ); /** @@ -167,8 +167,8 @@ UsbBotResetDevice ( **/ EFI_STATUS UsbBotGetMaxLun ( - IN VOID *Context, - OUT UINT8 *MaxLun + IN VOID *Context, + OUT UINT8 *MaxLun ); /** @@ -181,7 +181,7 @@ UsbBotGetMaxLun ( **/ EFI_STATUS UsbBotCleanUp ( - IN VOID *Context + IN VOID *Context ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.c index 423104f504..05903a5e74 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.c @@ -14,7 +14,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Definition of USB CBI0 Transport Protocol // -USB_MASS_TRANSPORT mUsbCbi0Transport = { +USB_MASS_TRANSPORT mUsbCbi0Transport = { USB_MASS_STORE_CBI0, UsbCbiInit, UsbCbiExecCommand, @@ -26,7 +26,7 @@ USB_MASS_TRANSPORT mUsbCbi0Transport = { // // Definition of USB CBI1 Transport Protocol // -USB_MASS_TRANSPORT mUsbCbi1Transport = { +USB_MASS_TRANSPORT mUsbCbi1Transport = { USB_MASS_STORE_CBI1, UsbCbiInit, UsbCbiExecCommand, @@ -52,8 +52,8 @@ USB_MASS_TRANSPORT mUsbCbi1Transport = { **/ EFI_STATUS UsbCbiInit ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - OUT VOID **Context OPTIONAL + IN EFI_USB_IO_PROTOCOL *UsbIo, + OUT VOID **Context OPTIONAL ) { USB_CBI_PROTOCOL *UsbCbi; @@ -82,8 +82,9 @@ UsbCbiInit ( } Interface = &UsbCbi->Interface; - if ((Interface->InterfaceProtocol != USB_MASS_STORE_CBI0) - && (Interface->InterfaceProtocol != USB_MASS_STORE_CBI1)) { + if ( (Interface->InterfaceProtocol != USB_MASS_STORE_CBI0) + && (Interface->InterfaceProtocol != USB_MASS_STORE_CBI1)) + { Status = EFI_UNSUPPORTED; goto ON_ERROR; } @@ -102,27 +103,27 @@ UsbCbiInit ( // Use the first Bulk-In and Bulk-Out endpoints // if (USB_IS_IN_ENDPOINT (EndPoint.EndpointAddress) && - (UsbCbi->BulkInEndpoint == NULL)) { - - UsbCbi->BulkInEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *) (UsbCbi + 1); - CopyMem(UsbCbi->BulkInEndpoint, &EndPoint, sizeof (EndPoint));; + (UsbCbi->BulkInEndpoint == NULL)) + { + UsbCbi->BulkInEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *)(UsbCbi + 1); + CopyMem (UsbCbi->BulkInEndpoint, &EndPoint, sizeof (EndPoint)); } if (USB_IS_OUT_ENDPOINT (EndPoint.EndpointAddress) && - (UsbCbi->BulkOutEndpoint == NULL)) { - - UsbCbi->BulkOutEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *) (UsbCbi + 1) + 1; - CopyMem(UsbCbi->BulkOutEndpoint, &EndPoint, sizeof (EndPoint)); + (UsbCbi->BulkOutEndpoint == NULL)) + { + UsbCbi->BulkOutEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *)(UsbCbi + 1) + 1; + CopyMem (UsbCbi->BulkOutEndpoint, &EndPoint, sizeof (EndPoint)); } } else if (USB_IS_INTERRUPT_ENDPOINT (EndPoint.Attributes)) { // // Use the first interrupt endpoint if it is CBI0 // if ((Interface->InterfaceProtocol == USB_MASS_STORE_CBI0) && - (UsbCbi->InterruptEndpoint == NULL)) { - - UsbCbi->InterruptEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *) (UsbCbi + 1) + 2; - CopyMem(UsbCbi->InterruptEndpoint, &EndPoint, sizeof (EndPoint)); + (UsbCbi->InterruptEndpoint == NULL)) + { + UsbCbi->InterruptEndpoint = (EFI_USB_ENDPOINT_DESCRIPTOR *)(UsbCbi + 1) + 2; + CopyMem (UsbCbi->InterruptEndpoint, &EndPoint, sizeof (EndPoint)); } } } @@ -131,6 +132,7 @@ UsbCbiInit ( Status = EFI_UNSUPPORTED; goto ON_ERROR; } + if ((Interface->InterfaceProtocol == USB_MASS_STORE_CBI0) && (UsbCbi->InterruptEndpoint == NULL)) { Status = EFI_UNSUPPORTED; goto ON_ERROR; @@ -166,10 +168,10 @@ ON_ERROR: **/ EFI_STATUS UsbCbiSendCommand ( - IN USB_CBI_PROTOCOL *UsbCbi, - IN UINT8 *Cmd, - IN UINT8 CmdLen, - IN UINT32 Timeout + IN USB_CBI_PROTOCOL *UsbCbi, + IN UINT8 *Cmd, + IN UINT8 CmdLen, + IN UINT32 Timeout ) { EFI_USB_DEVICE_REQUEST Request; @@ -188,8 +190,8 @@ UsbCbiSendCommand ( Request.Index = UsbCbi->Interface.InterfaceNumber; Request.Length = CmdLen; - Status = EFI_SUCCESS; - Timeout = Timeout / USB_MASS_1_MILLISECOND; + Status = EFI_SUCCESS; + Timeout = Timeout / USB_MASS_1_MILLISECOND; for (Retry = 0; Retry < USB_CBI_MAX_RETRY; Retry++) { // @@ -223,7 +225,6 @@ UsbCbiSendCommand ( return Status; } - /** Transfer data between the device and host. @@ -244,20 +245,20 @@ UsbCbiSendCommand ( **/ EFI_STATUS UsbCbiDataTransfer ( - IN USB_CBI_PROTOCOL *UsbCbi, - IN EFI_USB_DATA_DIRECTION DataDir, - IN OUT UINT8 *Data, - IN OUT UINTN *TransLen, - IN UINT32 Timeout + IN USB_CBI_PROTOCOL *UsbCbi, + IN EFI_USB_DATA_DIRECTION DataDir, + IN OUT UINT8 *Data, + IN OUT UINTN *TransLen, + IN UINT32 Timeout ) { - EFI_USB_ENDPOINT_DESCRIPTOR *Endpoint; - EFI_STATUS Status; - UINT32 TransStatus; - UINTN Remain; - UINTN Increment; - UINT8 *Next; - UINTN Retry; + EFI_USB_ENDPOINT_DESCRIPTOR *Endpoint; + EFI_STATUS Status; + UINT32 TransStatus; + UINTN Remain; + UINTN Increment; + UINT8 *Next; + UINTN Retry; // // If no data to transfer, just return EFI_SUCCESS. @@ -287,7 +288,7 @@ UsbCbiDataTransfer ( while (Remain > 0) { TransStatus = 0; - if (Remain > (UINTN) USB_CBI_MAX_PACKET_NUM * Endpoint->MaxPacketSize) { + if (Remain > (UINTN)USB_CBI_MAX_PACKET_NUM * Endpoint->MaxPacketSize) { Increment = USB_CBI_MAX_PACKET_NUM * Endpoint->MaxPacketSize; } else { Increment = Remain; @@ -334,7 +335,7 @@ UsbCbiDataTransfer ( goto ON_EXIT; } - Next += Increment; + Next += Increment; Remain -= Increment; } @@ -343,7 +344,6 @@ ON_EXIT: return Status; } - /** Gets the result of high level command execution from interrupt endpoint. @@ -362,20 +362,20 @@ ON_EXIT: **/ EFI_STATUS UsbCbiGetStatus ( - IN USB_CBI_PROTOCOL *UsbCbi, - IN UINT32 Timeout, - OUT USB_CBI_STATUS *Result + IN USB_CBI_PROTOCOL *UsbCbi, + IN UINT32 Timeout, + OUT USB_CBI_STATUS *Result ) { - UINTN Len; - UINT8 Endpoint; - EFI_STATUS Status; - UINT32 TransStatus; - INTN Retry; + UINTN Len; + UINT8 Endpoint; + EFI_STATUS Status; + UINT32 TransStatus; + INTN Retry; - Endpoint = UsbCbi->InterruptEndpoint->EndpointAddress; - Status = EFI_SUCCESS; - Timeout = Timeout / USB_MASS_1_MILLISECOND; + Endpoint = UsbCbi->InterruptEndpoint->EndpointAddress; + Status = EFI_SUCCESS; + Timeout = Timeout / USB_MASS_1_MILLISECOND; // // Attempt to the read the result from interrupt endpoint @@ -405,7 +405,6 @@ UsbCbiGetStatus ( return Status; } - /** Execute USB mass storage command through the CBI0/CBI1 transport protocol. @@ -436,13 +435,13 @@ UsbCbiExecCommand ( OUT UINT32 *CmdStatus ) { - USB_CBI_PROTOCOL *UsbCbi; - USB_CBI_STATUS Result; - EFI_STATUS Status; - UINTN TransLen; + USB_CBI_PROTOCOL *UsbCbi; + USB_CBI_STATUS Result; + EFI_STATUS Status; + UINTN TransLen; - *CmdStatus = USB_MASS_CMD_SUCCESS; - UsbCbi = (USB_CBI_PROTOCOL *) Context; + *CmdStatus = USB_MASS_CMD_SUCCESS; + UsbCbi = (USB_CBI_PROTOCOL *)Context; // // Send the command to the device. Return immediately if device @@ -450,8 +449,8 @@ UsbCbiExecCommand ( // Status = UsbCbiSendCommand (UsbCbi, Cmd, CmdLen, Timeout); if (EFI_ERROR (Status)) { - gBS->Stall(10 * USB_MASS_1_MILLISECOND); - DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiSendCommand (%r)\n",Status)); + gBS->Stall (10 * USB_MASS_1_MILLISECOND); + DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiSendCommand (%r)\n", Status)); return Status; } @@ -459,11 +458,11 @@ UsbCbiExecCommand ( // Transfer the data. Return this status if no interrupt endpoint // is used to report the transfer status. // - TransLen = (UINTN) DataLen; + TransLen = (UINTN)DataLen; - Status = UsbCbiDataTransfer (UsbCbi, DataDir, Data, &TransLen, Timeout); + Status = UsbCbiDataTransfer (UsbCbi, DataDir, Data, &TransLen, Timeout); if (UsbCbi->InterruptEndpoint == NULL) { - DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiDataTransfer (%r)\n",Status)); + DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiDataTransfer (%r)\n", Status)); return Status; } @@ -472,7 +471,7 @@ UsbCbiExecCommand ( // Status = UsbCbiGetStatus (UsbCbi, Timeout, &Result); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiGetStatus (%r)\n",Status)); + DEBUG ((DEBUG_ERROR, "UsbCbiExecCommand: UsbCbiGetStatus (%r)\n", Status)); return Status; } @@ -483,7 +482,7 @@ UsbCbiExecCommand ( // Do not set the USB_MASS_CMD_FAIL for a request sense command // as a bad result type doesn't mean a cmd failure // - if (Result.Type != 0 && *(UINT8*)Cmd != 0x03) { + if ((Result.Type != 0) && (*(UINT8 *)Cmd != 0x03)) { *CmdStatus = USB_MASS_CMD_FAIL; } } else { @@ -491,40 +490,39 @@ UsbCbiExecCommand ( // Check page 27, CBI spec 1.1 for vaious reture status. // switch (Result.Value & 0x03) { - case 0x00: - // - // Pass - // - *CmdStatus = USB_MASS_CMD_SUCCESS; - break; + case 0x00: + // + // Pass + // + *CmdStatus = USB_MASS_CMD_SUCCESS; + break; - case 0x02: - // - // Phase Error, response with reset. - // No break here to fall through to "Fail". - // - UsbCbiResetDevice (UsbCbi, FALSE); + case 0x02: + // + // Phase Error, response with reset. + // No break here to fall through to "Fail". + // + UsbCbiResetDevice (UsbCbi, FALSE); - case 0x01: - // - // Fail - // - *CmdStatus = USB_MASS_CMD_FAIL; - break; + case 0x01: + // + // Fail + // + *CmdStatus = USB_MASS_CMD_FAIL; + break; - case 0x03: - // - // Persistent Fail. Need to send REQUEST SENSE. - // - *CmdStatus = USB_MASS_CMD_PERSISTENT; - break; + case 0x03: + // + // Persistent Fail. Need to send REQUEST SENSE. + // + *CmdStatus = USB_MASS_CMD_PERSISTENT; + break; } } return EFI_SUCCESS; } - /** Reset the USB mass storage device by CBI protocol. @@ -542,17 +540,17 @@ UsbCbiExecCommand ( **/ EFI_STATUS UsbCbiResetDevice ( - IN VOID *Context, - IN BOOLEAN ExtendedVerification + IN VOID *Context, + IN BOOLEAN ExtendedVerification ) { - UINT8 ResetCmd[USB_CBI_RESET_CMD_LEN]; - USB_CBI_PROTOCOL *UsbCbi; - USB_CBI_STATUS Result; - EFI_STATUS Status; - UINT32 Timeout; + UINT8 ResetCmd[USB_CBI_RESET_CMD_LEN]; + USB_CBI_PROTOCOL *UsbCbi; + USB_CBI_STATUS Result; + EFI_STATUS Status; + UINT32 Timeout; - UsbCbi = (USB_CBI_PROTOCOL *) Context; + UsbCbi = (USB_CBI_PROTOCOL *)Context; // // Fill in the reset command. @@ -587,7 +585,6 @@ UsbCbiResetDevice ( return Status; } - /** Clean up the CBI protocol's resource. @@ -598,7 +595,7 @@ UsbCbiResetDevice ( **/ EFI_STATUS UsbCbiCleanUp ( - IN VOID *Context + IN VOID *Context ) { FreePool (Context); diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.h index b79b9c2436..8aca9132c8 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassCbi.h @@ -10,19 +10,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USBMASS_CBI_H_ #define _EFI_USBMASS_CBI_H_ -extern USB_MASS_TRANSPORT mUsbCbi0Transport; -extern USB_MASS_TRANSPORT mUsbCbi1Transport; +extern USB_MASS_TRANSPORT mUsbCbi0Transport; +extern USB_MASS_TRANSPORT mUsbCbi1Transport; -#define USB_CBI_MAX_PACKET_NUM 16 -#define USB_CBI_RESET_CMD_LEN 12 +#define USB_CBI_MAX_PACKET_NUM 16 +#define USB_CBI_RESET_CMD_LEN 12 // // USB CBI retry C/B/I transport times, set by experience // -#define USB_CBI_MAX_RETRY 3 +#define USB_CBI_MAX_RETRY 3 // // Time to wait for USB CBI reset to complete, set by experience // -#define USB_CBI_RESET_DEVICE_STALL (50 * USB_MASS_1_MILLISECOND) +#define USB_CBI_RESET_DEVICE_STALL (50 * USB_MASS_1_MILLISECOND) // // USB CBI transport timeout, set by experience // @@ -32,17 +32,17 @@ typedef struct { // // Put Interface at the first field to make it easy to distinguish BOT/CBI Protocol instance // - EFI_USB_INTERFACE_DESCRIPTOR Interface; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; - EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; - EFI_USB_ENDPOINT_DESCRIPTOR *InterruptEndpoint; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_USB_INTERFACE_DESCRIPTOR Interface; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkInEndpoint; + EFI_USB_ENDPOINT_DESCRIPTOR *BulkOutEndpoint; + EFI_USB_ENDPOINT_DESCRIPTOR *InterruptEndpoint; + EFI_USB_IO_PROTOCOL *UsbIo; } USB_CBI_PROTOCOL; #pragma pack(1) typedef struct { - UINT8 Type; - UINT8 Value; + UINT8 Type; + UINT8 Value; } USB_CBI_STATUS; #pragma pack() @@ -63,8 +63,8 @@ typedef struct { **/ EFI_STATUS UsbCbiInit ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - OUT VOID **Context OPTIONAL + IN EFI_USB_IO_PROTOCOL *UsbIo, + OUT VOID **Context OPTIONAL ); /** @@ -114,8 +114,8 @@ UsbCbiExecCommand ( **/ EFI_STATUS UsbCbiResetDevice ( - IN VOID *Context, - IN BOOLEAN ExtendedVerification + IN VOID *Context, + IN BOOLEAN ExtendedVerification ); /** @@ -128,7 +128,7 @@ UsbCbiResetDevice ( **/ EFI_STATUS UsbCbiCleanUp ( - IN VOID *Context + IN VOID *Context ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.c index 44e1d0c01d..5620608b40 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMass.h" -EFI_DISK_INFO_PROTOCOL gUsbDiskInfoProtocolTemplate = { +EFI_DISK_INFO_PROTOCOL gUsbDiskInfoProtocolTemplate = { EFI_DISK_INFO_USB_INTERFACE_GUID, UsbDiskInfoInquiry, UsbDiskInfoIdentify, @@ -27,13 +27,12 @@ EFI_DISK_INFO_PROTOCOL gUsbDiskInfoProtocolTemplate = { **/ VOID InitializeDiskInfo ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { CopyMem (&UsbMass->DiskInfo, &gUsbDiskInfoProtocolTemplate, sizeof (gUsbDiskInfoProtocolTemplate)); } - /** Provides inquiry information for the controller type. @@ -53,26 +52,26 @@ InitializeDiskInfo ( EFI_STATUS EFIAPI UsbDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ) { - EFI_STATUS Status; - USB_MASS_DEVICE *UsbMass; + EFI_STATUS Status; + USB_MASS_DEVICE *UsbMass; - UsbMass = USB_MASS_DEVICE_FROM_DISK_INFO (This); + UsbMass = USB_MASS_DEVICE_FROM_DISK_INFO (This); Status = EFI_BUFFER_TOO_SMALL; if (*InquiryDataSize >= sizeof (UsbMass->InquiryData)) { Status = EFI_SUCCESS; CopyMem (InquiryData, &UsbMass->InquiryData, sizeof (UsbMass->InquiryData)); } + *InquiryDataSize = sizeof (UsbMass->InquiryData); return Status; } - /** Provides identify information for the controller type. @@ -94,9 +93,9 @@ UsbDiskInfoInquiry ( EFI_STATUS EFIAPI UsbDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ) { return EFI_NOT_FOUND; @@ -122,16 +121,15 @@ UsbDiskInfoIdentify ( EFI_STATUS EFIAPI UsbDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ) { return EFI_NOT_FOUND; } - /** This function is used to get controller information. @@ -146,11 +144,10 @@ UsbDiskInfoSenseData ( EFI_STATUS EFIAPI UsbDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ) { return EFI_UNSUPPORTED; } - diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.h index 2571cc5419..4ada890827 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassDiskInfo.h @@ -20,10 +20,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID InitializeDiskInfo ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ); - /** Provides inquiry information for the controller type. @@ -43,9 +42,9 @@ InitializeDiskInfo ( EFI_STATUS EFIAPI UsbDiskInfoInquiry ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *InquiryData, - IN OUT UINT32 *InquiryDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *InquiryData, + IN OUT UINT32 *InquiryDataSize ); /** @@ -69,9 +68,9 @@ UsbDiskInfoInquiry ( EFI_STATUS EFIAPI UsbDiskInfoIdentify ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *IdentifyData, - IN OUT UINT32 *IdentifyDataSize + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *IdentifyData, + IN OUT UINT32 *IdentifyDataSize ); /** @@ -94,13 +93,12 @@ UsbDiskInfoIdentify ( EFI_STATUS EFIAPI UsbDiskInfoSenseData ( - IN EFI_DISK_INFO_PROTOCOL *This, - IN OUT VOID *SenseData, - IN OUT UINT32 *SenseDataSize, - OUT UINT8 *SenseDataNumber + IN EFI_DISK_INFO_PROTOCOL *This, + IN OUT VOID *SenseData, + IN OUT UINT32 *SenseDataSize, + OUT UINT8 *SenseDataNumber ); - /** This function is used to get controller information. @@ -115,9 +113,9 @@ UsbDiskInfoSenseData ( EFI_STATUS EFIAPI UsbDiskInfoWhichIde ( - IN EFI_DISK_INFO_PROTOCOL *This, - OUT UINT32 *IdeChannel, - OUT UINT32 *IdeDevice + IN EFI_DISK_INFO_PROTOCOL *This, + OUT UINT32 *IdeChannel, + OUT UINT32 *IdeDevice ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.c b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.c index de9c5f0632..9c5fd4e16b 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.c +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.c @@ -8,17 +8,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMass.h" -#define USB_MASS_TRANSPORT_COUNT 3 +#define USB_MASS_TRANSPORT_COUNT 3 // // Array of USB transport interfaces. // -USB_MASS_TRANSPORT *mUsbMassTransport[USB_MASS_TRANSPORT_COUNT] = { +USB_MASS_TRANSPORT *mUsbMassTransport[USB_MASS_TRANSPORT_COUNT] = { &mUsbCbi0Transport, &mUsbCbi1Transport, &mUsbBotTransport, }; -EFI_DRIVER_BINDING_PROTOCOL gUSBMassDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUSBMassDriverBinding = { USBMassDriverBindingSupported, USBMassDriverBindingStart, USBMassDriverBindingStop, @@ -45,19 +45,19 @@ EFI_DRIVER_BINDING_PROTOCOL gUSBMassDriverBinding = { EFI_STATUS EFIAPI UsbMassReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - USB_MASS_DEVICE *UsbMass; - EFI_TPL OldTpl; - EFI_STATUS Status; + USB_MASS_DEVICE *UsbMass; + EFI_TPL OldTpl; + EFI_STATUS Status; // // Raise TPL to TPL_CALLBACK to serialize all its operations // to protect shared data structures. // - OldTpl = gBS->RaiseTPL (TPL_CALLBACK); + OldTpl = gBS->RaiseTPL (TPL_CALLBACK); UsbMass = USB_MASS_DEVICE_FROM_BLOCK_IO (This); Status = UsbMass->Transport->Reset (UsbMass->Context, ExtendedVerification); @@ -94,11 +94,11 @@ UsbMassReset ( EFI_STATUS EFIAPI UsbMassReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ) { USB_MASS_DEVICE *UsbMass; @@ -168,7 +168,7 @@ UsbMassReadBlocks ( if (UsbMass->Cdb16Byte) { Status = UsbBootReadWriteBlocks16 (UsbMass, FALSE, Lba, TotalBlock, Buffer); } else { - Status = UsbBootReadWriteBlocks (UsbMass, FALSE, (UINT32) Lba, TotalBlock, Buffer); + Status = UsbBootReadWriteBlocks (UsbMass, FALSE, (UINT32)Lba, TotalBlock, Buffer); } if (EFI_ERROR (Status)) { @@ -181,7 +181,6 @@ ON_EXIT: return Status; } - /** Writes a specified number of blocks to the device. @@ -210,11 +209,11 @@ ON_EXIT: EFI_STATUS EFIAPI UsbMassWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ) { USB_MASS_DEVICE *UsbMass; @@ -288,7 +287,7 @@ UsbMassWriteBlocks ( if (UsbMass->Cdb16Byte) { Status = UsbBootReadWriteBlocks16 (UsbMass, TRUE, Lba, TotalBlock, Buffer); } else { - Status = UsbBootReadWriteBlocks (UsbMass, TRUE, (UINT32) Lba, TotalBlock, Buffer); + Status = UsbBootReadWriteBlocks (UsbMass, TRUE, (UINT32)Lba, TotalBlock, Buffer); } if (EFI_ERROR (Status)) { @@ -335,11 +334,11 @@ UsbMassFlushBlocks ( **/ EFI_STATUS UsbMassInitMedia ( - IN USB_MASS_DEVICE *UsbMass + IN USB_MASS_DEVICE *UsbMass ) { - EFI_BLOCK_IO_MEDIA *Media; - EFI_STATUS Status; + EFI_BLOCK_IO_MEDIA *Media; + EFI_STATUS Status; Media = &UsbMass->BlockIoMedia; @@ -363,6 +362,7 @@ UsbMassInitMedia ( // Status = EFI_SUCCESS; } + return Status; } @@ -400,7 +400,7 @@ UsbMassInitTransport ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -427,7 +427,7 @@ UsbMassInitTransport ( *Transport = mUsbMassTransport[Index]; if (Interface.InterfaceProtocol == (*Transport)->Protocol) { - Status = (*Transport)->Init (UsbIo, Context); + Status = (*Transport)->Init (UsbIo, Context); break; } } @@ -471,12 +471,12 @@ ON_EXIT: **/ EFI_STATUS UsbMassInitMultiLun ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN USB_MASS_TRANSPORT *Transport, - IN VOID *Context, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN UINT8 MaxLun + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN USB_MASS_TRANSPORT *Transport, + IN VOID *Context, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN UINT8 MaxLun ) { USB_MASS_DEVICE *UsbMass; @@ -490,24 +490,23 @@ UsbMassInitMultiLun ( ReturnStatus = EFI_NOT_FOUND; for (Index = 0; Index <= MaxLun; Index++) { - DEBUG ((DEBUG_INFO, "UsbMassInitMultiLun: Start to initialize No.%d logic unit\n", Index)); UsbIo = NULL; UsbMass = AllocateZeroPool (sizeof (USB_MASS_DEVICE)); ASSERT (UsbMass != NULL); - UsbMass->Signature = USB_MASS_SIGNATURE; - UsbMass->UsbIo = UsbIo; - UsbMass->BlockIo.Media = &UsbMass->BlockIoMedia; - UsbMass->BlockIo.Reset = UsbMassReset; - UsbMass->BlockIo.ReadBlocks = UsbMassReadBlocks; - UsbMass->BlockIo.WriteBlocks = UsbMassWriteBlocks; - UsbMass->BlockIo.FlushBlocks = UsbMassFlushBlocks; - UsbMass->OpticalStorage = FALSE; - UsbMass->Transport = Transport; - UsbMass->Context = Context; - UsbMass->Lun = Index; + UsbMass->Signature = USB_MASS_SIGNATURE; + UsbMass->UsbIo = UsbIo; + UsbMass->BlockIo.Media = &UsbMass->BlockIoMedia; + UsbMass->BlockIo.Reset = UsbMassReset; + UsbMass->BlockIo.ReadBlocks = UsbMassReadBlocks; + UsbMass->BlockIo.WriteBlocks = UsbMassWriteBlocks; + UsbMass->BlockIo.FlushBlocks = UsbMassFlushBlocks; + UsbMass->OpticalStorage = FALSE; + UsbMass->Transport = Transport; + UsbMass->Context = Context; + UsbMass->Lun = Index; // // Initialize the media parameter data for EFI_BLOCK_IO_MEDIA of Block I/O Protocol. @@ -566,7 +565,7 @@ UsbMassInitMultiLun ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, UsbMass->Controller, EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -588,6 +587,7 @@ UsbMassInitMultiLun ( FreePool (UsbMass); continue; } + ReturnStatus = EFI_SUCCESS; DEBUG ((DEBUG_INFO, "UsbMassInitMultiLun: Success to initialize No.%d logic unit\n", Index)); } @@ -609,15 +609,15 @@ UsbMassInitMultiLun ( **/ EFI_STATUS UsbMassInitNonLun ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN USB_MASS_TRANSPORT *Transport, - IN VOID *Context + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN USB_MASS_TRANSPORT *Transport, + IN VOID *Context ) { - USB_MASS_DEVICE *UsbMass; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_STATUS Status; + USB_MASS_DEVICE *UsbMass; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; UsbIo = NULL; UsbMass = AllocateZeroPool (sizeof (USB_MASS_DEVICE)); @@ -626,7 +626,7 @@ UsbMassInitNonLun ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -637,17 +637,17 @@ UsbMassInitNonLun ( goto ON_ERROR; } - UsbMass->Signature = USB_MASS_SIGNATURE; - UsbMass->Controller = Controller; - UsbMass->UsbIo = UsbIo; - UsbMass->BlockIo.Media = &UsbMass->BlockIoMedia; - UsbMass->BlockIo.Reset = UsbMassReset; - UsbMass->BlockIo.ReadBlocks = UsbMassReadBlocks; - UsbMass->BlockIo.WriteBlocks = UsbMassWriteBlocks; - UsbMass->BlockIo.FlushBlocks = UsbMassFlushBlocks; - UsbMass->OpticalStorage = FALSE; - UsbMass->Transport = Transport; - UsbMass->Context = Context; + UsbMass->Signature = USB_MASS_SIGNATURE; + UsbMass->Controller = Controller; + UsbMass->UsbIo = UsbIo; + UsbMass->BlockIo.Media = &UsbMass->BlockIoMedia; + UsbMass->BlockIo.Reset = UsbMassReset; + UsbMass->BlockIo.ReadBlocks = UsbMassReadBlocks; + UsbMass->BlockIo.WriteBlocks = UsbMassWriteBlocks; + UsbMass->BlockIo.FlushBlocks = UsbMassFlushBlocks; + UsbMass->OpticalStorage = FALSE; + UsbMass->Transport = Transport; + UsbMass->Context = Context; // // Initialize the media parameter data for EFI_BLOCK_IO_MEDIA of Block I/O Protocol. @@ -678,6 +678,7 @@ ON_ERROR: if (UsbMass != NULL) { FreePool (UsbMass); } + if (UsbIo != NULL) { gBS->CloseProtocol ( Controller, @@ -686,10 +687,10 @@ ON_ERROR: Controller ); } + return Status; } - /** Check whether the controller is a supported USB mass storage. @@ -718,7 +719,7 @@ USBMassDriverBindingSupported ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -793,13 +794,13 @@ USBMassDriverBindingStart ( IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - USB_MASS_TRANSPORT *Transport; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - VOID *Context; - UINT8 MaxLun; - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_TPL OldTpl; + USB_MASS_TRANSPORT *Transport; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + VOID *Context; + UINT8 MaxLun; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); @@ -813,6 +814,7 @@ USBMassDriverBindingStart ( DEBUG ((DEBUG_ERROR, "USBMassDriverBindingStart: UsbMassInitTransport (%r)\n", Status)); goto Exit; } + if (MaxLun == 0) { // // Initialize data for device that does not support multiple LUNSs. @@ -828,7 +830,7 @@ USBMassDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -842,7 +844,7 @@ USBMassDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -866,26 +868,26 @@ USBMassDriverBindingStart ( Status = UsbMassInitMultiLun (This, Controller, Transport, Context, DevicePath, MaxLun); if (EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); DEBUG ((DEBUG_ERROR, "USBMassDriverBindingStart: UsbMassInitMultiLun (%r) with Maxlun=%d\n", Status, MaxLun)); } } + Exit: gBS->RestoreTPL (OldTpl); return Status; } - /** Stop controlling the device. @@ -903,18 +905,18 @@ Exit: EFI_STATUS EFIAPI USBMassDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - USB_MASS_DEVICE *UsbMass; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - UINTN Index; - BOOLEAN AllChildrenStopped; + EFI_STATUS Status; + USB_MASS_DEVICE *UsbMass; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + UINTN Index; + BOOLEAN AllChildrenStopped; // // This is a bus driver stop function since multi-lun is supported. @@ -930,29 +932,29 @@ USBMassDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { // // This is a 2nd type handle(multi-lun root), it needs to close devicepath // and usbio protocol. // gBS->CloseProtocol ( - Controller, - &gEfiDevicePathProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiDevicePathProtocolGuid, + This->DriverBindingHandle, + Controller + ); gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); DEBUG ((DEBUG_INFO, "Success to stop multi-lun root handle\n")); return EFI_SUCCESS; } @@ -980,11 +982,11 @@ USBMassDriverBindingStop ( } gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); UsbMass->Transport->CleanUp (UsbMass->Context); FreePool (UsbMass); @@ -1001,11 +1003,10 @@ USBMassDriverBindingStop ( AllChildrenStopped = TRUE; for (Index = 0; Index < NumberOfChildren; Index++) { - Status = gBS->OpenProtocol ( ChildHandleBuffer[Index], &gEfiBlockIoProtocolGuid, - (VOID **) &BlockIo, + (VOID **)&BlockIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1046,7 +1047,7 @@ USBMassDriverBindingStop ( gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, ChildHandleBuffer[Index], EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER @@ -1058,6 +1059,7 @@ USBMassDriverBindingStop ( if (((Index + 1) == NumberOfChildren) && AllChildrenStopped) { UsbMass->Transport->CleanUp (UsbMass->Context); } + FreePool (UsbMass); } } @@ -1066,7 +1068,7 @@ USBMassDriverBindingStop ( return EFI_DEVICE_ERROR; } - DEBUG ((DEBUG_INFO, "Success to stop all %d multi-lun children handles\n", (UINT32) NumberOfChildren)); + DEBUG ((DEBUG_INFO, "Success to stop all %d multi-lun children handles\n", (UINT32)NumberOfChildren)); return EFI_SUCCESS; } @@ -1085,8 +1087,8 @@ USBMassDriverBindingStop ( EFI_STATUS EFIAPI USBMassStorageEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; diff --git a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.h b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.h index 283bed7055..045659855d 100644 --- a/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.h +++ b/MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassImpl.h @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USBMASS_IMPL_H_ #define _EFI_USBMASS_IMPL_H_ -#define USB_MASS_SIGNATURE SIGNATURE_32 ('U', 's', 'b', 'M') +#define USB_MASS_SIGNATURE SIGNATURE_32 ('U', 's', 'b', 'M') #define USB_MASS_DEVICE_FROM_BLOCK_IO(a) \ CR (a, USB_MASS_DEVICE, BlockIo, USB_MASS_SIGNATURE) @@ -18,7 +18,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define USB_MASS_DEVICE_FROM_DISK_INFO(a) \ CR (a, USB_MASS_DEVICE, DiskInfo, USB_MASS_SIGNATURE) - extern EFI_COMPONENT_NAME_PROTOCOL gUsbMassStorageComponentName; extern EFI_COMPONENT_NAME2_PROTOCOL gUsbMassStorageComponentName2; @@ -88,10 +87,10 @@ USBMassDriverBindingStart ( EFI_STATUS EFIAPI USBMassDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // @@ -116,8 +115,8 @@ USBMassDriverBindingStop ( EFI_STATUS EFIAPI UsbMassReset ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_BLOCK_IO_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -147,11 +146,11 @@ UsbMassReset ( EFI_STATUS EFIAPI UsbMassReadBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - OUT VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + OUT VOID *Buffer ); /** @@ -182,11 +181,11 @@ UsbMassReadBlocks ( EFI_STATUS EFIAPI UsbMassWriteBlocks ( - IN EFI_BLOCK_IO_PROTOCOL *This, - IN UINT32 MediaId, - IN EFI_LBA Lba, - IN UINTN BufferSize, - IN VOID *Buffer + IN EFI_BLOCK_IO_PROTOCOL *This, + IN UINT32 MediaId, + IN EFI_LBA Lba, + IN UINTN BufferSize, + IN VOID *Buffer ); /** @@ -255,7 +254,6 @@ UsbMassStorageGetDriverName ( OUT CHAR16 **DriverName ); - /** Retrieves a Unicode string that is the user readable name of the controller that is being managed by a driver. @@ -317,11 +315,11 @@ UsbMassStorageGetDriverName ( EFI_STATUS EFIAPI UsbMassStorageGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/ComponentName.c b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/ComponentName.c index efad274fd9..6c861d5257 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/ComponentName.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "UsbMouseAbsolutePointer.h" // @@ -21,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUsbMouseAbsolutePoin // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseAbsolutePointerComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UsbMouseAbsolutePointerComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UsbMouseAbsolutePointerComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseAbsolutePointerComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UsbMouseAbsolutePointerComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UsbMouseAbsolutePointerComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbMouseAbsolutePointerDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbMouseAbsolutePointerDriverNameTable[] = { { "eng;en", L"Usb Mouse Absolute Pointer Driver" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -145,17 +143,17 @@ UsbMouseAbsolutePointerComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbMouseAbsolutePointerComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; - EFI_ABSOLUTE_POINTER_PROTOCOL *AbsolutePointerProtocol; - EFI_USB_IO_PROTOCOL *UsbIoProtocol; + EFI_STATUS Status; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; + EFI_ABSOLUTE_POINTER_PROTOCOL *AbsolutePointerProtocol; + EFI_USB_IO_PROTOCOL *UsbIoProtocol; // // This is a device driver, so ChildHandle must be NULL. @@ -170,7 +168,7 @@ UsbMouseAbsolutePointerComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIoProtocol, + (VOID **)&UsbIoProtocol, gUsbMouseAbsolutePointerDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -189,13 +187,14 @@ UsbMouseAbsolutePointerComponentNameGetControllerName ( if (Status != EFI_ALREADY_STARTED) { return EFI_UNSUPPORTED; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, - &gEfiAbsolutePointerProtocolGuid, - (VOID **) &AbsolutePointerProtocol, + &gEfiAbsolutePointerProtocolGuid, + (VOID **)&AbsolutePointerProtocol, gUsbMouseAbsolutePointerDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,5 +213,4 @@ UsbMouseAbsolutePointerComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gUsbMouseAbsolutePointerComponentName) ); - } diff --git a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/MouseHid.c b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/MouseHid.c index 10e18e58ab..96e3e5c1f7 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/MouseHid.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/MouseHid.c @@ -8,7 +8,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMouseAbsolutePointer.h" - /** Get next HID item from report descriptor. @@ -31,12 +30,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT8 * GetNextHidItem ( - IN UINT8 *StartPos, - IN UINT8 *EndPos, - OUT HID_ITEM *HidItem + IN UINT8 *StartPos, + IN UINT8 *EndPos, + OUT HID_ITEM *HidItem ) { - UINT8 Temp; + UINT8 Temp; if (EndPos <= StartPos) { return NULL; @@ -66,7 +65,7 @@ GetNextHidItem ( if ((EndPos - StartPos) >= HidItem->Size) { HidItem->Data.LongData = StartPos; - StartPos += HidItem->Size; + StartPos += HidItem->Size; return StartPos; } } @@ -75,48 +74,47 @@ GetNextHidItem ( HidItem->Size = BitFieldRead8 (Temp, 0, 1); switch (HidItem->Size) { - case 0: - // - // No data - // - return StartPos; - - case 1: - // - // 1-byte data - // - if ((EndPos - StartPos) >= 1) { - HidItem->Data.Uint8 = *StartPos++; + case 0: + // + // No data + // return StartPos; - } - case 2: - // - // 2-byte data - // - if ((EndPos - StartPos) >= 2) { - CopyMem (&HidItem->Data.Uint16, StartPos, sizeof (UINT16)); - StartPos += 2; - return StartPos; - } + case 1: + // + // 1-byte data + // + if ((EndPos - StartPos) >= 1) { + HidItem->Data.Uint8 = *StartPos++; + return StartPos; + } - case 3: - // - // 4-byte data, adjust size - // - HidItem->Size = 4; - if ((EndPos - StartPos) >= 4) { - CopyMem (&HidItem->Data.Uint32, StartPos, sizeof (UINT32)); - StartPos += 4; - return StartPos; - } + case 2: + // + // 2-byte data + // + if ((EndPos - StartPos) >= 2) { + CopyMem (&HidItem->Data.Uint16, StartPos, sizeof (UINT16)); + StartPos += 2; + return StartPos; + } + + case 3: + // + // 4-byte data, adjust size + // + HidItem->Size = 4; + if ((EndPos - StartPos) >= 4) { + CopyMem (&HidItem->Data.Uint32, StartPos, sizeof (UINT32)); + StartPos += 4; + return StartPos; + } } } return NULL; } - /** Get data from HID item. @@ -131,20 +129,21 @@ GetNextHidItem ( **/ UINT32 GetItemData ( - IN HID_ITEM *HidItem + IN HID_ITEM *HidItem ) { // // Get data from HID item. // switch (HidItem->Size) { - case 1: - return HidItem->Data.Uint8; - case 2: - return HidItem->Data.Uint16; - case 4: - return HidItem->Data.Uint32; + case 1: + return HidItem->Data.Uint8; + case 2: + return HidItem->Data.Uint16; + case 4: + return HidItem->Data.Uint32; } + return 0; } @@ -161,67 +160,68 @@ GetItemData ( **/ VOID ParseHidItem ( - IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouse, - IN HID_ITEM *HidItem + IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouse, + IN HID_ITEM *HidItem ) { UINT8 Data; switch (HidItem->Type) { + case HID_ITEM_TYPE_MAIN: + // + // we don't care any main items, just skip + // + return; - case HID_ITEM_TYPE_MAIN: - // - // we don't care any main items, just skip - // - return ; + case HID_ITEM_TYPE_GLOBAL: + // + // For global items, we only care Usage Page tag for Button Page here + // + if (HidItem->Tag == HID_GLOBAL_ITEM_TAG_USAGE_PAGE) { + Data = (UINT8)GetItemData (HidItem); + if (Data == 0x09) { + // + // Button Page + // + UsbMouse->PrivateData.ButtonDetected = TRUE; + } + } - case HID_ITEM_TYPE_GLOBAL: - // - // For global items, we only care Usage Page tag for Button Page here - // - if (HidItem->Tag == HID_GLOBAL_ITEM_TAG_USAGE_PAGE) { - Data = (UINT8) GetItemData (HidItem); - if (Data == 0x09) { + return; + + case HID_ITEM_TYPE_LOCAL: + if (HidItem->Size == 0) { // - // Button Page + // No expected data for local item // - UsbMouse->PrivateData.ButtonDetected = TRUE; + return; } - } - return; - case HID_ITEM_TYPE_LOCAL: - if (HidItem->Size == 0) { - // - // No expected data for local item - // - return ; - } + Data = (UINT8)GetItemData (HidItem); - Data = (UINT8) GetItemData (HidItem); + switch (HidItem->Tag) { + case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: + if (UsbMouse->PrivateData.ButtonDetected) { + UsbMouse->PrivateData.ButtonMinIndex = Data; + } - switch (HidItem->Tag) { - case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: - if (UsbMouse->PrivateData.ButtonDetected) { - UsbMouse->PrivateData.ButtonMinIndex = Data; - } - return ; + return; - case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: - { - if (UsbMouse->PrivateData.ButtonDetected) { - UsbMouse->PrivateData.ButtonMaxIndex = Data; - } - return ; - } + case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: + { + if (UsbMouse->PrivateData.ButtonDetected) { + UsbMouse->PrivateData.ButtonMaxIndex = Data; + } + + return; + } - default: - return ; + default: + return; } } } - /** Parse Mouse Report Descriptor. @@ -240,9 +240,9 @@ ParseHidItem ( **/ EFI_STATUS ParseMouseReportDescriptor ( - OUT USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointer, - IN UINT8 *ReportDescriptor, - IN UINTN ReportSize + OUT USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointer, + IN UINT8 *ReportDescriptor, + IN UINTN ReportSize ) { UINT8 *DescriptorEnd; @@ -265,11 +265,11 @@ ParseMouseReportDescriptor ( Ptr = GetNextHidItem (Ptr, DescriptorEnd, &HidItem); } - UsbMouseAbsolutePointer->NumberOfButtons = (UINT8) (UsbMouseAbsolutePointer->PrivateData.ButtonMaxIndex - UsbMouseAbsolutePointer->PrivateData.ButtonMinIndex + 1); - UsbMouseAbsolutePointer->XLogicMax = 1023; - UsbMouseAbsolutePointer->YLogicMax = 1023; - UsbMouseAbsolutePointer->XLogicMin = -1023; - UsbMouseAbsolutePointer->YLogicMin = -1023; + UsbMouseAbsolutePointer->NumberOfButtons = (UINT8)(UsbMouseAbsolutePointer->PrivateData.ButtonMaxIndex - UsbMouseAbsolutePointer->PrivateData.ButtonMinIndex + 1); + UsbMouseAbsolutePointer->XLogicMax = 1023; + UsbMouseAbsolutePointer->YLogicMax = 1023; + UsbMouseAbsolutePointer->XLogicMin = -1023; + UsbMouseAbsolutePointer->YLogicMin = -1023; return EFI_SUCCESS; } diff --git a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c index 926e03f9cb..ad5f066ec9 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMouseAbsolutePointer.h" -EFI_DRIVER_BINDING_PROTOCOL gUsbMouseAbsolutePointerDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUsbMouseAbsolutePointerDriverBinding = { USBMouseAbsolutePointerDriverBindingSupported, USBMouseAbsolutePointerDriverBindingStart, USBMouseAbsolutePointerDriverBindingStop, @@ -32,11 +32,11 @@ EFI_DRIVER_BINDING_PROTOCOL gUsbMouseAbsolutePointerDriverBinding = { EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, @@ -51,7 +51,6 @@ USBMouseAbsolutePointerDriverBindingEntryPoint ( return EFI_SUCCESS; } - /** Check whether USB Mouse Absolute Pointer Driver supports this device. @@ -66,18 +65,18 @@ USBMouseAbsolutePointerDriverBindingEntryPoint ( EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -96,16 +95,15 @@ USBMouseAbsolutePointerDriverBindingSupported ( } gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return Status; } - /** Starts the mouse device with this driver. @@ -128,22 +126,22 @@ USBMouseAbsolutePointerDriverBindingSupported ( EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; - UINT8 EndpointNumber; - EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; - UINT8 Index; - UINT8 EndpointAddr; - UINT8 PollingInterval; - UINT8 PacketSize; - BOOLEAN Found; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; + UINT8 EndpointNumber; + EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; + UINT8 Index; + UINT8 EndpointAddr; + UINT8 PollingInterval; + UINT8 PacketSize; + BOOLEAN Found; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); // @@ -152,7 +150,7 @@ USBMouseAbsolutePointerDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -173,7 +171,7 @@ USBMouseAbsolutePointerDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &UsbMouseAbsolutePointerDevice->DevicePath, + (VOID **)&UsbMouseAbsolutePointerDevice->DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,11 +212,12 @@ USBMouseAbsolutePointerDriverBindingStart ( ); if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && - ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) + { // // We only care interrupt endpoint here // - CopyMem (&UsbMouseAbsolutePointerDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof(EndpointDescriptor)); + CopyMem (&UsbMouseAbsolutePointerDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof (EndpointDescriptor)); Found = TRUE; break; } @@ -267,7 +266,7 @@ USBMouseAbsolutePointerDriverBindingStart ( // UsbMouseAbsolutePointerDevice->AbsolutePointerProtocol.GetState = GetMouseAbsolutePointerState; UsbMouseAbsolutePointerDevice->AbsolutePointerProtocol.Reset = UsbMouseAbsolutePointerReset; - UsbMouseAbsolutePointerDevice->AbsolutePointerProtocol.Mode = &UsbMouseAbsolutePointerDevice->Mode; + UsbMouseAbsolutePointerDevice->AbsolutePointerProtocol.Mode = &UsbMouseAbsolutePointerDevice->Mode; Status = gBS->CreateEvent ( EVT_NOTIFY_WAIT, @@ -307,7 +306,7 @@ USBMouseAbsolutePointerDriverBindingStart ( // EndpointAddr = UsbMouseAbsolutePointerDevice->IntEndpointDescriptor.EndpointAddress; PollingInterval = UsbMouseAbsolutePointerDevice->IntEndpointDescriptor.Interval; - PacketSize = (UINT8) (UsbMouseAbsolutePointerDevice->IntEndpointDescriptor.MaxPacketSize); + PacketSize = (UINT8)(UsbMouseAbsolutePointerDevice->IntEndpointDescriptor.MaxPacketSize); Status = UsbIo->UsbAsyncInterruptTransfer ( UsbIo, @@ -337,8 +336,8 @@ USBMouseAbsolutePointerDriverBindingStart ( gUsbMouseAbsolutePointerComponentName.SupportedLanguages, &UsbMouseAbsolutePointerDevice->ControllerNameTable, L"Generic Usb Mouse Absolute Pointer", - TRUE - ); + TRUE + ); AddUnicodeString2 ( "en", gUsbMouseAbsolutePointerComponentName2.SupportedLanguages, @@ -350,17 +349,17 @@ USBMouseAbsolutePointerDriverBindingStart ( gBS->RestoreTPL (OldTpl); return EFI_SUCCESS; -// -// Error handler -// + // + // Error handler + // ErrorExit: if (EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); if (UsbMouseAbsolutePointerDevice != NULL) { if ((UsbMouseAbsolutePointerDevice->AbsolutePointerProtocol).WaitForInput != NULL) { @@ -378,7 +377,6 @@ ErrorExit1: return Status; } - /** Stop the USB mouse device handled by this driver. @@ -395,10 +393,10 @@ ErrorExit1: EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { EFI_STATUS Status; @@ -409,7 +407,7 @@ USBMouseAbsolutePointerDriverBindingStop ( Status = gBS->OpenProtocol ( Controller, &gEfiAbsolutePointerProtocolGuid, - (VOID **) &AbsolutePointerProtocol, + (VOID **)&AbsolutePointerProtocol, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -478,10 +476,8 @@ USBMouseAbsolutePointerDriverBindingStop ( FreePool (UsbMouseAbsolutePointerDevice); return EFI_SUCCESS; - } - /** Uses USB I/O to check whether the device is a USB mouse device. @@ -493,7 +489,7 @@ USBMouseAbsolutePointerDriverBindingStop ( **/ BOOLEAN IsUsbMouse ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ) { EFI_STATUS Status; @@ -514,14 +510,14 @@ IsUsbMouse ( if ((InterfaceDescriptor.InterfaceClass == CLASS_HID) && (InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT) && (InterfaceDescriptor.InterfaceProtocol == PROTOCOL_MOUSE) - ) { + ) + { return TRUE; } return FALSE; } - /** Initialize the USB mouse device. @@ -539,20 +535,20 @@ IsUsbMouse ( **/ EFI_STATUS InitializeUsbMouseDevice ( - IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev + IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev ) { - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 Protocol; - EFI_STATUS Status; - EFI_USB_HID_DESCRIPTOR *MouseHidDesc; - UINT8 *ReportDesc; - EFI_USB_CONFIG_DESCRIPTOR ConfigDesc; - VOID *Buf; - UINT32 TransferResult; - UINT16 Total; - USB_DESC_HEAD *Head; - BOOLEAN Start; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 Protocol; + EFI_STATUS Status; + EFI_USB_HID_DESCRIPTOR *MouseHidDesc; + UINT8 *ReportDesc; + EFI_USB_CONFIG_DESCRIPTOR ConfigDesc; + VOID *Buf; + UINT32 TransferResult; + UINT16 Total; + USB_DESC_HEAD *Head; + BOOLEAN Start; UsbIo = UsbMouseAbsolutePointerDev->UsbIo; @@ -589,9 +585,9 @@ InitializeUsbMouseDevice ( return Status; } - Total = 0; - Start = FALSE; - Head = (USB_DESC_HEAD *)Buf; + Total = 0; + Start = FALSE; + Head = (USB_DESC_HEAD *)Buf; MouseHidDesc = NULL; // @@ -602,19 +598,23 @@ InitializeUsbMouseDevice ( while (Total < ConfigDesc.TotalLength) { if (Head->Type == USB_DESC_TYPE_INTERFACE) { if ((((USB_INTERFACE_DESCRIPTOR *)Head)->InterfaceNumber == UsbMouseAbsolutePointerDev->InterfaceDescriptor.InterfaceNumber) && - (((USB_INTERFACE_DESCRIPTOR *)Head)->AlternateSetting == UsbMouseAbsolutePointerDev->InterfaceDescriptor.AlternateSetting)) { + (((USB_INTERFACE_DESCRIPTOR *)Head)->AlternateSetting == UsbMouseAbsolutePointerDev->InterfaceDescriptor.AlternateSetting)) + { Start = TRUE; } } + if (Start && (Head->Type == USB_DESC_TYPE_ENDPOINT)) { break; } + if (Start && (Head->Type == USB_DESC_TYPE_HID)) { MouseHidDesc = (EFI_USB_HID_DESCRIPTOR *)Head; break; } + Total = Total + (UINT16)Head->Len; - Head = (USB_DESC_HEAD*)((UINT8 *)Buf + Total); + Head = (USB_DESC_HEAD *)((UINT8 *)Buf + Total); } if (MouseHidDesc == NULL) { @@ -722,7 +722,6 @@ InitializeUsbMouseDevice ( return EFI_SUCCESS; } - /** Handler function for USB mouse's asynchronous interrupt transfer. @@ -743,19 +742,19 @@ InitializeUsbMouseDevice ( EFI_STATUS EFIAPI OnMouseInterruptComplete ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ) { - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 EndpointAddr; - UINT32 UsbResult; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 EndpointAddr; + UINT32 UsbResult; - UsbMouseAbsolutePointerDevice = (USB_MOUSE_ABSOLUTE_POINTER_DEV *) Context; - UsbIo = UsbMouseAbsolutePointerDevice->UsbIo; + UsbMouseAbsolutePointerDevice = (USB_MOUSE_ABSOLUTE_POINTER_DEV *)Context; + UsbIo = UsbMouseAbsolutePointerDevice->UsbIo; if (Result != EFI_USB_NOERROR) { // @@ -804,7 +803,7 @@ OnMouseInterruptComplete ( // // If no error and no data, just return EFI_SUCCESS. // - if (DataLength == 0 || Data == NULL) { + if ((DataLength == 0) || (Data == NULL)) { return EFI_SUCCESS; } @@ -826,26 +825,32 @@ OnMouseInterruptComplete ( UsbMouseAbsolutePointerDevice->StateChanged = TRUE; - UsbMouseAbsolutePointerDevice->State.ActiveButtons = *(UINT8 *) Data & (BIT0 | BIT1 | BIT2); + UsbMouseAbsolutePointerDevice->State.ActiveButtons = *(UINT8 *)Data & (BIT0 | BIT1 | BIT2); UsbMouseAbsolutePointerDevice->State.CurrentX = MIN ( - MAX ((INT64) UsbMouseAbsolutePointerDevice->State.CurrentX + *((INT8 *) Data + 1), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinX), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxX + MAX ( + (INT64)UsbMouseAbsolutePointerDevice->State.CurrentX + *((INT8 *)Data + 1), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinX + ), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxX ); UsbMouseAbsolutePointerDevice->State.CurrentY = MIN ( - MAX ((INT64) UsbMouseAbsolutePointerDevice->State.CurrentY + *((INT8 *) Data + 2), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinY), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxY + MAX ( + (INT64)UsbMouseAbsolutePointerDevice->State.CurrentY + *((INT8 *)Data + 2), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinY + ), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxY ); if (DataLength > 3) { UsbMouseAbsolutePointerDevice->State.CurrentZ = MIN ( - MAX ((INT64) UsbMouseAbsolutePointerDevice->State.CurrentZ + *((INT8 *) Data + 1), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinZ), - (INT64) UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxZ + MAX ( + (INT64)UsbMouseAbsolutePointerDevice->State.CurrentZ + *((INT8 *)Data + 1), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMinZ + ), + (INT64)UsbMouseAbsolutePointerDevice->Mode.AbsoluteMaxZ ); } @@ -873,7 +878,7 @@ GetMouseAbsolutePointerState ( OUT EFI_ABSOLUTE_POINTER_STATE *State ) { - USB_MOUSE_ABSOLUTE_POINTER_DEV *MouseAbsolutePointerDev; + USB_MOUSE_ABSOLUTE_POINTER_DEV *MouseAbsolutePointerDev; if (State == NULL) { return EFI_INVALID_PARAMETER; @@ -900,7 +905,6 @@ GetMouseAbsolutePointerState ( return EFI_SUCCESS; } - /** Resets the pointer device hardware. @@ -919,9 +923,9 @@ UsbMouseAbsolutePointerReset ( IN BOOLEAN ExtendedVerification ) { - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDevice; - UsbMouseAbsolutePointerDevice = USB_MOUSE_ABSOLUTE_POINTER_DEV_FROM_MOUSE_PROTOCOL (This); + UsbMouseAbsolutePointerDevice = USB_MOUSE_ABSOLUTE_POINTER_DEV_FROM_MOUSE_PROTOCOL (This); REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, @@ -960,13 +964,13 @@ UsbMouseAbsolutePointerReset ( VOID EFIAPI UsbMouseAbsolutePointerWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; - UsbMouseAbsolutePointerDev = (USB_MOUSE_ABSOLUTE_POINTER_DEV *) Context; + UsbMouseAbsolutePointerDev = (USB_MOUSE_ABSOLUTE_POINTER_DEV *)Context; // // If there's input from mouse, signal the event. @@ -992,16 +996,16 @@ UsbMouseAbsolutePointerWaitForInput ( VOID EFIAPI USBMouseRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; - EFI_USB_IO_PROTOCOL *UsbIo; + USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev; + EFI_USB_IO_PROTOCOL *UsbIo; - UsbMouseAbsolutePointerDev = (USB_MOUSE_ABSOLUTE_POINTER_DEV *) Context; + UsbMouseAbsolutePointerDev = (USB_MOUSE_ABSOLUTE_POINTER_DEV *)Context; - UsbIo = UsbMouseAbsolutePointerDev->UsbIo; + UsbIo = UsbMouseAbsolutePointerDev->UsbIo; // // Re-submit Asynchronous Interrupt Transfer for recovery. diff --git a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.h b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.h index c9edc45e38..d5f92d2ed9 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.h +++ b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _USB_MOUSE_ABSOLUTE_POINTER_H_ #define _USB_MOUSE_ABSOLUTE_POINTER_H_ - #include #include @@ -27,14 +26,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define CLASS_HID 3 -#define SUBCLASS_BOOT 1 -#define PROTOCOL_MOUSE 2 +#define CLASS_HID 3 +#define SUBCLASS_BOOT 1 +#define PROTOCOL_MOUSE 2 -#define BOOT_PROTOCOL 0 -#define REPORT_PROTOCOL 1 +#define BOOT_PROTOCOL 0 +#define REPORT_PROTOCOL 1 -#define USB_MOUSE_ABSOLUTE_POINTER_DEV_SIGNATURE SIGNATURE_32 ('u', 'm', 's', 't') +#define USB_MOUSE_ABSOLUTE_POINTER_DEV_SIGNATURE SIGNATURE_32 ('u', 'm', 's', 't') // // A common header for usb standard descriptor. @@ -42,8 +41,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #pragma pack(1) typedef struct { - UINT8 Len; - UINT8 Type; + UINT8 Len; + UINT8 Type; } USB_DESC_HEAD; #pragma pack() @@ -51,33 +50,33 @@ typedef struct { /// Button range and status /// typedef struct { - BOOLEAN ButtonDetected; - UINT8 ButtonMinIndex; - UINT8 ButtonMaxIndex; - UINT8 Reserved; + BOOLEAN ButtonDetected; + UINT8 ButtonMinIndex; + UINT8 ButtonMaxIndex; + UINT8 Reserved; } USB_MOUSE_BUTTON_DATA; /// /// Device instance of USB mouse. /// typedef struct { - UINTN Signature; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_EVENT DelayedRecoveryEvent; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; - EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; - UINT8 NumberOfButtons; - INT32 XLogicMax; - INT32 XLogicMin; - INT32 YLogicMax; - INT32 YLogicMin; - EFI_ABSOLUTE_POINTER_PROTOCOL AbsolutePointerProtocol; - EFI_ABSOLUTE_POINTER_STATE State; - EFI_ABSOLUTE_POINTER_MODE Mode; - BOOLEAN StateChanged; - USB_MOUSE_BUTTON_DATA PrivateData; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + UINTN Signature; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_EVENT DelayedRecoveryEvent; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; + EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; + UINT8 NumberOfButtons; + INT32 XLogicMax; + INT32 XLogicMin; + INT32 YLogicMax; + INT32 YLogicMin; + EFI_ABSOLUTE_POINTER_PROTOCOL AbsolutePointerProtocol; + EFI_ABSOLUTE_POINTER_STATE State; + EFI_ABSOLUTE_POINTER_MODE Mode; + BOOLEAN StateChanged; + USB_MOUSE_BUTTON_DATA PrivateData; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; } USB_MOUSE_ABSOLUTE_POINTER_DEV; /// @@ -85,21 +84,21 @@ typedef struct { /// typedef union { - UINT8 Uint8; - UINT16 Uint16; - UINT32 Uint32; - INT8 Int8; - INT16 Int16; - INT32 Int32; - UINT8 *LongData; + UINT8 Uint8; + UINT16 Uint16; + UINT32 Uint32; + INT8 Int8; + INT16 Int16; + INT32 Int32; + UINT8 *LongData; } HID_DATA; typedef struct { - UINT16 Format; - UINT8 Size; - UINT8 Type; - UINT8 Tag; - HID_DATA Data; + UINT16 Format; + UINT8 Size; + UINT8 Type; + UINT8 Tag; + HID_DATA Data; } HID_ITEM; #define USB_MOUSE_ABSOLUTE_POINTER_DEV_FROM_MOUSE_PROTOCOL(a) \ @@ -130,9 +129,9 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseAbsolutePointerComponentName2; EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -157,9 +156,9 @@ USBMouseAbsolutePointerDriverBindingSupported ( EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -178,10 +177,10 @@ USBMouseAbsolutePointerDriverBindingStart ( EFI_STATUS EFIAPI USBMouseAbsolutePointerDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // @@ -291,11 +290,11 @@ UsbMouseAbsolutePointerComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbMouseAbsolutePointerComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); // @@ -351,8 +350,8 @@ UsbMouseAbsolutePointerReset ( VOID EFIAPI UsbMouseAbsolutePointerWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); // @@ -370,7 +369,7 @@ UsbMouseAbsolutePointerWaitForInput ( **/ BOOLEAN IsUsbMouse ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ); /** @@ -390,7 +389,7 @@ IsUsbMouse ( **/ EFI_STATUS InitializeUsbMouseDevice ( - IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev + IN USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointerDev ); /** @@ -413,10 +412,10 @@ InitializeUsbMouseDevice ( EFI_STATUS EFIAPI OnMouseInterruptComplete ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ); /** @@ -435,8 +434,8 @@ OnMouseInterruptComplete ( VOID EFIAPI USBMouseRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -457,9 +456,9 @@ USBMouseRecoveryHandler ( **/ EFI_STATUS ParseMouseReportDescriptor ( - OUT USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointer, - IN UINT8 *ReportDescriptor, - IN UINTN ReportSize + OUT USB_MOUSE_ABSOLUTE_POINTER_DEV *UsbMouseAbsolutePointer, + IN UINT8 *ReportDescriptor, + IN UINTN ReportSize ); #endif diff --git a/MdeModulePkg/Bus/Usb/UsbMouseDxe/ComponentName.c b/MdeModulePkg/Bus/Usb/UsbMouseDxe/ComponentName.c index 7f4b3e821e..0b5adb1e12 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseDxe/ComponentName.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseDxe/ComponentName.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "UsbMouse.h" // @@ -21,16 +20,15 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME_PROTOCOL gUsbMouseComponentNam // // EFI Component Name 2 Protocol // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseComponentName2 = { - (EFI_COMPONENT_NAME2_GET_DRIVER_NAME) UsbMouseComponentNameGetDriverName, - (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME) UsbMouseComponentNameGetControllerName, +GLOBAL_REMOVE_IF_UNREFERENCED EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseComponentName2 = { + (EFI_COMPONENT_NAME2_GET_DRIVER_NAME)UsbMouseComponentNameGetDriverName, + (EFI_COMPONENT_NAME2_GET_CONTROLLER_NAME)UsbMouseComponentNameGetControllerName, "en" }; - -GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbMouseDriverNameTable[] = { +GLOBAL_REMOVE_IF_UNREFERENCED EFI_UNICODE_STRING_TABLE mUsbMouseDriverNameTable[] = { { "eng;en", L"Usb Mouse Driver" }, - { NULL , NULL } + { NULL, NULL } }; /** @@ -145,17 +143,17 @@ UsbMouseComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbMouseComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ) { - EFI_STATUS Status; - USB_MOUSE_DEV *UsbMouseDev; - EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; - EFI_USB_IO_PROTOCOL *UsbIoProtocol; + EFI_STATUS Status; + USB_MOUSE_DEV *UsbMouseDev; + EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; + EFI_USB_IO_PROTOCOL *UsbIoProtocol; // // This is a device driver, so ChildHandle must be NULL. @@ -170,7 +168,7 @@ UsbMouseComponentNameGetControllerName ( Status = gBS->OpenProtocol ( ControllerHandle, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIoProtocol, + (VOID **)&UsbIoProtocol, gUsbMouseDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -189,13 +187,14 @@ UsbMouseComponentNameGetControllerName ( if (Status != EFI_ALREADY_STARTED) { return EFI_UNSUPPORTED; } + // // Get the device context // Status = gBS->OpenProtocol ( ControllerHandle, - &gEfiSimplePointerProtocolGuid, - (VOID **) &SimplePointerProtocol, + &gEfiSimplePointerProtocolGuid, + (VOID **)&SimplePointerProtocol, gUsbMouseDriverBinding.DriverBindingHandle, ControllerHandle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,5 +213,4 @@ UsbMouseComponentNameGetControllerName ( ControllerName, (BOOLEAN)(This == &gUsbMouseComponentName) ); - } diff --git a/MdeModulePkg/Bus/Usb/UsbMouseDxe/MouseHid.c b/MdeModulePkg/Bus/Usb/UsbMouseDxe/MouseHid.c index 2b6d86030b..acc19acd98 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseDxe/MouseHid.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseDxe/MouseHid.c @@ -8,7 +8,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMouse.h" - /** Get next HID item from report descriptor. @@ -31,12 +30,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ UINT8 * GetNextHidItem ( - IN UINT8 *StartPos, - IN UINT8 *EndPos, - OUT HID_ITEM *HidItem + IN UINT8 *StartPos, + IN UINT8 *EndPos, + OUT HID_ITEM *HidItem ) { - UINT8 Temp; + UINT8 Temp; if (EndPos <= StartPos) { return NULL; @@ -66,7 +65,7 @@ GetNextHidItem ( if ((EndPos - StartPos) >= HidItem->Size) { HidItem->Data.LongData = StartPos; - StartPos += HidItem->Size; + StartPos += HidItem->Size; return StartPos; } } @@ -75,48 +74,47 @@ GetNextHidItem ( HidItem->Size = BitFieldRead8 (Temp, 0, 1); switch (HidItem->Size) { - case 0: - // - // No data - // - return StartPos; - - case 1: - // - // 1-byte data - // - if ((EndPos - StartPos) >= 1) { - HidItem->Data.Uint8 = *StartPos++; + case 0: + // + // No data + // return StartPos; - } - case 2: - // - // 2-byte data - // - if ((EndPos - StartPos) >= 2) { - CopyMem (&HidItem->Data.Uint16, StartPos, sizeof (UINT16)); - StartPos += 2; - return StartPos; - } + case 1: + // + // 1-byte data + // + if ((EndPos - StartPos) >= 1) { + HidItem->Data.Uint8 = *StartPos++; + return StartPos; + } - case 3: - // - // 4-byte data, adjust size - // - HidItem->Size = 4; - if ((EndPos - StartPos) >= 4) { - CopyMem (&HidItem->Data.Uint32, StartPos, sizeof (UINT32)); - StartPos += 4; - return StartPos; - } + case 2: + // + // 2-byte data + // + if ((EndPos - StartPos) >= 2) { + CopyMem (&HidItem->Data.Uint16, StartPos, sizeof (UINT16)); + StartPos += 2; + return StartPos; + } + + case 3: + // + // 4-byte data, adjust size + // + HidItem->Size = 4; + if ((EndPos - StartPos) >= 4) { + CopyMem (&HidItem->Data.Uint32, StartPos, sizeof (UINT32)); + StartPos += 4; + return StartPos; + } } } return NULL; } - /** Get data from HID item. @@ -131,20 +129,21 @@ GetNextHidItem ( **/ UINT32 GetItemData ( - IN HID_ITEM *HidItem + IN HID_ITEM *HidItem ) { // // Get data from HID item. // switch (HidItem->Size) { - case 1: - return HidItem->Data.Uint8; - case 2: - return HidItem->Data.Uint16; - case 4: - return HidItem->Data.Uint32; + case 1: + return HidItem->Data.Uint8; + case 2: + return HidItem->Data.Uint16; + case 4: + return HidItem->Data.Uint32; } + return 0; } @@ -161,67 +160,68 @@ GetItemData ( **/ VOID ParseHidItem ( - IN USB_MOUSE_DEV *UsbMouse, - IN HID_ITEM *HidItem + IN USB_MOUSE_DEV *UsbMouse, + IN HID_ITEM *HidItem ) { UINT8 Data; switch (HidItem->Type) { + case HID_ITEM_TYPE_MAIN: + // + // we don't care any main items, just skip + // + return; - case HID_ITEM_TYPE_MAIN: - // - // we don't care any main items, just skip - // - return; + case HID_ITEM_TYPE_GLOBAL: + // + // For global items, we only care Usage Page tag for Button Page here + // + if (HidItem->Tag == HID_GLOBAL_ITEM_TAG_USAGE_PAGE) { + Data = (UINT8)GetItemData (HidItem); + if (Data == 0x09) { + // + // Button Page + // + UsbMouse->PrivateData.ButtonDetected = TRUE; + } + } - case HID_ITEM_TYPE_GLOBAL: - // - // For global items, we only care Usage Page tag for Button Page here - // - if (HidItem->Tag == HID_GLOBAL_ITEM_TAG_USAGE_PAGE) { - Data = (UINT8) GetItemData (HidItem); - if (Data == 0x09) { + return; + + case HID_ITEM_TYPE_LOCAL: + if (HidItem->Size == 0) { // - // Button Page + // No expected data for local item // - UsbMouse->PrivateData.ButtonDetected = TRUE; + return; } - } - return; - case HID_ITEM_TYPE_LOCAL: - if (HidItem->Size == 0) { - // - // No expected data for local item - // - return ; - } + Data = (UINT8)GetItemData (HidItem); - Data = (UINT8) GetItemData (HidItem); + switch (HidItem->Tag) { + case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: + if (UsbMouse->PrivateData.ButtonDetected) { + UsbMouse->PrivateData.ButtonMinIndex = Data; + } - switch (HidItem->Tag) { - case HID_LOCAL_ITEM_TAG_USAGE_MINIMUM: - if (UsbMouse->PrivateData.ButtonDetected) { - UsbMouse->PrivateData.ButtonMinIndex = Data; - } - return ; + return; - case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: - { - if (UsbMouse->PrivateData.ButtonDetected) { - UsbMouse->PrivateData.ButtonMaxIndex = Data; - } - return ; - } + case HID_LOCAL_ITEM_TAG_USAGE_MAXIMUM: + { + if (UsbMouse->PrivateData.ButtonDetected) { + UsbMouse->PrivateData.ButtonMaxIndex = Data; + } - default: - return; - } + return; + } + + default: + return; + } } } - /** Parse Mouse Report Descriptor. @@ -240,9 +240,9 @@ ParseHidItem ( **/ EFI_STATUS ParseMouseReportDescriptor ( - OUT USB_MOUSE_DEV *UsbMouse, - IN UINT8 *ReportDescriptor, - IN UINTN ReportSize + OUT USB_MOUSE_DEV *UsbMouse, + IN UINT8 *ReportDescriptor, + IN UINTN ReportSize ) { UINT8 *DescriptorEnd; @@ -265,11 +265,11 @@ ParseMouseReportDescriptor ( Ptr = GetNextHidItem (Ptr, DescriptorEnd, &HidItem); } - UsbMouse->NumberOfButtons = (UINT8) (UsbMouse->PrivateData.ButtonMaxIndex - UsbMouse->PrivateData.ButtonMinIndex + 1); - UsbMouse->XLogicMax = 127; - UsbMouse->YLogicMax = 127; - UsbMouse->XLogicMin = -127; - UsbMouse->YLogicMin = -127; + UsbMouse->NumberOfButtons = (UINT8)(UsbMouse->PrivateData.ButtonMaxIndex - UsbMouse->PrivateData.ButtonMinIndex + 1); + UsbMouse->XLogicMax = 127; + UsbMouse->YLogicMax = 127; + UsbMouse->XLogicMin = -127; + UsbMouse->YLogicMin = -127; return EFI_SUCCESS; } diff --git a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c index 9861c32d49..451d4b934f 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "UsbMouse.h" -EFI_DRIVER_BINDING_PROTOCOL gUsbMouseDriverBinding = { +EFI_DRIVER_BINDING_PROTOCOL gUsbMouseDriverBinding = { USBMouseDriverBindingSupported, USBMouseDriverBindingStart, USBMouseDriverBindingStop, @@ -32,11 +32,11 @@ EFI_DRIVER_BINDING_PROTOCOL gUsbMouseDriverBinding = { EFI_STATUS EFIAPI USBMouseDriverBindingEntryPoint ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EfiLibInstallDriverBindingComponentName2 ( ImageHandle, @@ -51,7 +51,6 @@ USBMouseDriverBindingEntryPoint ( return EFI_SUCCESS; } - /** Check whether USB mouse driver supports this device. @@ -66,18 +65,18 @@ USBMouseDriverBindingEntryPoint ( EFI_STATUS EFIAPI USBMouseDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -96,16 +95,15 @@ USBMouseDriverBindingSupported ( } gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); return Status; } - /** Starts the mouse device with this driver. @@ -128,22 +126,22 @@ USBMouseDriverBindingSupported ( EFI_STATUS EFIAPI USBMouseDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; - USB_MOUSE_DEV *UsbMouseDevice; - UINT8 EndpointNumber; - EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; - UINT8 Index; - UINT8 EndpointAddr; - UINT8 PollingInterval; - UINT8 PacketSize; - BOOLEAN Found; - EFI_TPL OldTpl; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + USB_MOUSE_DEV *UsbMouseDevice; + UINT8 EndpointNumber; + EFI_USB_ENDPOINT_DESCRIPTOR EndpointDescriptor; + UINT8 Index; + UINT8 EndpointAddr; + UINT8 PollingInterval; + UINT8 PacketSize; + BOOLEAN Found; + EFI_TPL OldTpl; OldTpl = gBS->RaiseTPL (TPL_CALLBACK); // @@ -152,7 +150,7 @@ USBMouseDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo, + (VOID **)&UsbIo, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_BY_DRIVER @@ -173,7 +171,7 @@ USBMouseDriverBindingStart ( Status = gBS->OpenProtocol ( Controller, &gEfiDevicePathProtocolGuid, - (VOID **) &UsbMouseDevice->DevicePath, + (VOID **)&UsbMouseDevice->DevicePath, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -214,11 +212,12 @@ USBMouseDriverBindingStart ( ); if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && - ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) + { // // We only care interrupt endpoint here // - CopyMem(&UsbMouseDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof(EndpointDescriptor)); + CopyMem (&UsbMouseDevice->IntEndpointDescriptor, &EndpointDescriptor, sizeof (EndpointDescriptor)); Found = TRUE; break; } @@ -265,9 +264,9 @@ USBMouseDriverBindingStart ( // // Initialize and install EFI Simple Pointer Protocol. // - UsbMouseDevice->SimplePointerProtocol.GetState = GetMouseState; - UsbMouseDevice->SimplePointerProtocol.Reset = UsbMouseReset; - UsbMouseDevice->SimplePointerProtocol.Mode = &UsbMouseDevice->Mode; + UsbMouseDevice->SimplePointerProtocol.GetState = GetMouseState; + UsbMouseDevice->SimplePointerProtocol.Reset = UsbMouseReset; + UsbMouseDevice->SimplePointerProtocol.Mode = &UsbMouseDevice->Mode; Status = gBS->CreateEvent ( EVT_NOTIFY_WAIT, @@ -307,7 +306,7 @@ USBMouseDriverBindingStart ( // EndpointAddr = UsbMouseDevice->IntEndpointDescriptor.EndpointAddress; PollingInterval = UsbMouseDevice->IntEndpointDescriptor.Interval; - PacketSize = (UINT8) (UsbMouseDevice->IntEndpointDescriptor.MaxPacketSize); + PacketSize = (UINT8)(UsbMouseDevice->IntEndpointDescriptor.MaxPacketSize); Status = UsbIo->UsbAsyncInterruptTransfer ( UsbIo, @@ -351,17 +350,17 @@ USBMouseDriverBindingStart ( return EFI_SUCCESS; -// -// Error handler -// + // + // Error handler + // ErrorExit: if (EFI_ERROR (Status)) { gBS->CloseProtocol ( - Controller, - &gEfiUsbIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); + Controller, + &gEfiUsbIoProtocolGuid, + This->DriverBindingHandle, + Controller + ); if (UsbMouseDevice != NULL) { if ((UsbMouseDevice->SimplePointerProtocol).WaitForInput != NULL) { @@ -378,7 +377,6 @@ ErrorExit1: return Status; } - /** Stop the USB mouse device handled by this driver. @@ -395,21 +393,21 @@ ErrorExit1: EFI_STATUS EFIAPI USBMouseDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ) { - EFI_STATUS Status; - USB_MOUSE_DEV *UsbMouseDevice; - EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; - EFI_USB_IO_PROTOCOL *UsbIo; + EFI_STATUS Status; + USB_MOUSE_DEV *UsbMouseDevice; + EFI_SIMPLE_POINTER_PROTOCOL *SimplePointerProtocol; + EFI_USB_IO_PROTOCOL *UsbIo; Status = gBS->OpenProtocol ( Controller, &gEfiSimplePointerProtocolGuid, - (VOID **) &SimplePointerProtocol, + (VOID **)&SimplePointerProtocol, This->DriverBindingHandle, Controller, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -478,10 +476,8 @@ USBMouseDriverBindingStop ( FreePool (UsbMouseDevice); return EFI_SUCCESS; - } - /** Uses USB I/O to check whether the device is a USB mouse device. @@ -493,7 +489,7 @@ USBMouseDriverBindingStop ( **/ BOOLEAN IsUsbMouse ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ) { EFI_STATUS Status; @@ -514,14 +510,14 @@ IsUsbMouse ( if ((InterfaceDescriptor.InterfaceClass == CLASS_HID) && (InterfaceDescriptor.InterfaceSubClass == SUBCLASS_BOOT) && (InterfaceDescriptor.InterfaceProtocol == PROTOCOL_MOUSE) - ) { + ) + { return TRUE; } return FALSE; } - /** Initialize the USB mouse device. @@ -539,20 +535,20 @@ IsUsbMouse ( **/ EFI_STATUS InitializeUsbMouseDevice ( - IN OUT USB_MOUSE_DEV *UsbMouseDev + IN OUT USB_MOUSE_DEV *UsbMouseDev ) { - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 Protocol; - EFI_STATUS Status; - EFI_USB_HID_DESCRIPTOR *MouseHidDesc; - UINT8 *ReportDesc; - EFI_USB_CONFIG_DESCRIPTOR ConfigDesc; - VOID *Buf; - UINT32 TransferResult; - UINT16 Total; - USB_DESC_HEAD *Head; - BOOLEAN Start; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 Protocol; + EFI_STATUS Status; + EFI_USB_HID_DESCRIPTOR *MouseHidDesc; + UINT8 *ReportDesc; + EFI_USB_CONFIG_DESCRIPTOR ConfigDesc; + VOID *Buf; + UINT32 TransferResult; + UINT16 Total; + USB_DESC_HEAD *Head; + BOOLEAN Start; UsbIo = UsbMouseDev->UsbIo; @@ -589,9 +585,9 @@ InitializeUsbMouseDevice ( return Status; } - Total = 0; - Start = FALSE; - Head = (USB_DESC_HEAD *)Buf; + Total = 0; + Start = FALSE; + Head = (USB_DESC_HEAD *)Buf; MouseHidDesc = NULL; // @@ -602,19 +598,23 @@ InitializeUsbMouseDevice ( while (Total < ConfigDesc.TotalLength) { if (Head->Type == USB_DESC_TYPE_INTERFACE) { if ((((USB_INTERFACE_DESCRIPTOR *)Head)->InterfaceNumber == UsbMouseDev->InterfaceDescriptor.InterfaceNumber) && - (((USB_INTERFACE_DESCRIPTOR *)Head)->AlternateSetting == UsbMouseDev->InterfaceDescriptor.AlternateSetting)) { + (((USB_INTERFACE_DESCRIPTOR *)Head)->AlternateSetting == UsbMouseDev->InterfaceDescriptor.AlternateSetting)) + { Start = TRUE; } } + if (Start && (Head->Type == USB_DESC_TYPE_ENDPOINT)) { break; } + if (Start && (Head->Type == USB_DESC_TYPE_HID)) { MouseHidDesc = (EFI_USB_HID_DESCRIPTOR *)Head; break; } + Total = Total + (UINT16)Head->Len; - Head = (USB_DESC_HEAD*)((UINT8 *)Buf + Total); + Head = (USB_DESC_HEAD *)((UINT8 *)Buf + Total); } if (MouseHidDesc == NULL) { @@ -668,9 +668,11 @@ InitializeUsbMouseDevice ( if (UsbMouseDev->NumberOfButtons >= 1) { UsbMouseDev->Mode.LeftButton = TRUE; } + if (UsbMouseDev->NumberOfButtons > 1) { UsbMouseDev->Mode.RightButton = TRUE; } + UsbMouseDev->Mode.ResolutionX = 8; UsbMouseDev->Mode.ResolutionY = 8; UsbMouseDev->Mode.ResolutionZ = 0; @@ -720,7 +722,6 @@ InitializeUsbMouseDevice ( return EFI_SUCCESS; } - /** Handler function for USB mouse's asynchronous interrupt transfer. @@ -741,19 +742,19 @@ InitializeUsbMouseDevice ( EFI_STATUS EFIAPI OnMouseInterruptComplete ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ) { - USB_MOUSE_DEV *UsbMouseDevice; - EFI_USB_IO_PROTOCOL *UsbIo; - UINT8 EndpointAddr; - UINT32 UsbResult; + USB_MOUSE_DEV *UsbMouseDevice; + EFI_USB_IO_PROTOCOL *UsbIo; + UINT8 EndpointAddr; + UINT32 UsbResult; - UsbMouseDevice = (USB_MOUSE_DEV *) Context; - UsbIo = UsbMouseDevice->UsbIo; + UsbMouseDevice = (USB_MOUSE_DEV *)Context; + UsbIo = UsbMouseDevice->UsbIo; if (Result != EFI_USB_NOERROR) { // @@ -802,7 +803,7 @@ OnMouseInterruptComplete ( // // If no error and no data, just return EFI_SUCCESS. // - if (DataLength == 0 || Data == NULL) { + if ((DataLength == 0) || (Data == NULL)) { return EFI_SUCCESS; } @@ -824,13 +825,13 @@ OnMouseInterruptComplete ( UsbMouseDevice->StateChanged = TRUE; - UsbMouseDevice->State.LeftButton = (BOOLEAN) ((*(UINT8 *) Data & BIT0) != 0); - UsbMouseDevice->State.RightButton = (BOOLEAN) ((*(UINT8 *) Data & BIT1) != 0); - UsbMouseDevice->State.RelativeMovementX += *((INT8 *) Data + 1); - UsbMouseDevice->State.RelativeMovementY += *((INT8 *) Data + 2); + UsbMouseDevice->State.LeftButton = (BOOLEAN)((*(UINT8 *)Data & BIT0) != 0); + UsbMouseDevice->State.RightButton = (BOOLEAN)((*(UINT8 *)Data & BIT1) != 0); + UsbMouseDevice->State.RelativeMovementX += *((INT8 *)Data + 1); + UsbMouseDevice->State.RelativeMovementY += *((INT8 *)Data + 2); if (DataLength > 3) { - UsbMouseDevice->State.RelativeMovementZ += *((INT8 *) Data + 3); + UsbMouseDevice->State.RelativeMovementZ += *((INT8 *)Data + 3); } return EFI_SUCCESS; @@ -857,7 +858,7 @@ GetMouseState ( OUT EFI_SIMPLE_POINTER_STATE *MouseState ) { - USB_MOUSE_DEV *MouseDev; + USB_MOUSE_DEV *MouseDev; if (MouseState == NULL) { return EFI_INVALID_PARAMETER; @@ -885,12 +886,11 @@ GetMouseState ( MouseDev->State.RelativeMovementY = 0; MouseDev->State.RelativeMovementZ = 0; - MouseDev->StateChanged = FALSE; + MouseDev->StateChanged = FALSE; return EFI_SUCCESS; } - /** Resets the pointer device hardware. @@ -905,13 +905,13 @@ GetMouseState ( EFI_STATUS EFIAPI UsbMouseReset ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ) { - USB_MOUSE_DEV *UsbMouseDevice; + USB_MOUSE_DEV *UsbMouseDevice; - UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This); + UsbMouseDevice = USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL (This); REPORT_STATUS_CODE_WITH_DEVICE_PATH ( EFI_PROGRESS_CODE, @@ -941,13 +941,13 @@ UsbMouseReset ( VOID EFIAPI UsbMouseWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_MOUSE_DEV *UsbMouseDev; + USB_MOUSE_DEV *UsbMouseDev; - UsbMouseDev = (USB_MOUSE_DEV *) Context; + UsbMouseDev = (USB_MOUSE_DEV *)Context; // // If there's input from mouse, signal the event. @@ -973,16 +973,16 @@ UsbMouseWaitForInput ( VOID EFIAPI USBMouseRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - USB_MOUSE_DEV *UsbMouseDev; - EFI_USB_IO_PROTOCOL *UsbIo; + USB_MOUSE_DEV *UsbMouseDev; + EFI_USB_IO_PROTOCOL *UsbIo; - UsbMouseDev = (USB_MOUSE_DEV *) Context; + UsbMouseDev = (USB_MOUSE_DEV *)Context; - UsbIo = UsbMouseDev->UsbIo; + UsbIo = UsbMouseDev->UsbIo; // // Re-submit Asynchronous Interrupt Transfer for recovery. diff --git a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.h b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.h index f46069602f..3ddd765c45 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.h +++ b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _EFI_USB_MOUSE_H_ #define _EFI_USB_MOUSE_H_ - #include #include @@ -27,14 +26,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define CLASS_HID 3 -#define SUBCLASS_BOOT 1 -#define PROTOCOL_MOUSE 2 +#define CLASS_HID 3 +#define SUBCLASS_BOOT 1 +#define PROTOCOL_MOUSE 2 -#define BOOT_PROTOCOL 0 -#define REPORT_PROTOCOL 1 +#define BOOT_PROTOCOL 0 +#define REPORT_PROTOCOL 1 -#define USB_MOUSE_DEV_SIGNATURE SIGNATURE_32 ('u', 'm', 'o', 'u') +#define USB_MOUSE_DEV_SIGNATURE SIGNATURE_32 ('u', 'm', 'o', 'u') // // A common header for usb standard descriptor. @@ -42,8 +41,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #pragma pack(1) typedef struct { - UINT8 Len; - UINT8 Type; + UINT8 Len; + UINT8 Type; } USB_DESC_HEAD; #pragma pack() @@ -51,33 +50,33 @@ typedef struct { /// Button range and status /// typedef struct { - BOOLEAN ButtonDetected; - UINT8 ButtonMinIndex; - UINT8 ButtonMaxIndex; - UINT8 Reserved; + BOOLEAN ButtonDetected; + UINT8 ButtonMinIndex; + UINT8 ButtonMaxIndex; + UINT8 Reserved; } USB_MOUSE_BUTTON_DATA; /// /// Device instance of USB mouse. /// typedef struct { - UINTN Signature; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_EVENT DelayedRecoveryEvent; - EFI_USB_IO_PROTOCOL *UsbIo; - EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; - EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; - UINT8 NumberOfButtons; - INT32 XLogicMax; - INT32 XLogicMin; - INT32 YLogicMax; - INT32 YLogicMin; - EFI_SIMPLE_POINTER_PROTOCOL SimplePointerProtocol; - EFI_SIMPLE_POINTER_STATE State; - EFI_SIMPLE_POINTER_MODE Mode; - BOOLEAN StateChanged; - USB_MOUSE_BUTTON_DATA PrivateData; - EFI_UNICODE_STRING_TABLE *ControllerNameTable; + UINTN Signature; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_EVENT DelayedRecoveryEvent; + EFI_USB_IO_PROTOCOL *UsbIo; + EFI_USB_INTERFACE_DESCRIPTOR InterfaceDescriptor; + EFI_USB_ENDPOINT_DESCRIPTOR IntEndpointDescriptor; + UINT8 NumberOfButtons; + INT32 XLogicMax; + INT32 XLogicMin; + INT32 YLogicMax; + INT32 YLogicMin; + EFI_SIMPLE_POINTER_PROTOCOL SimplePointerProtocol; + EFI_SIMPLE_POINTER_STATE State; + EFI_SIMPLE_POINTER_MODE Mode; + BOOLEAN StateChanged; + USB_MOUSE_BUTTON_DATA PrivateData; + EFI_UNICODE_STRING_TABLE *ControllerNameTable; } USB_MOUSE_DEV; /// @@ -85,21 +84,21 @@ typedef struct { /// typedef union { - UINT8 Uint8; - UINT16 Uint16; - UINT32 Uint32; - INT8 Int8; - INT16 Int16; - INT32 Int32; - UINT8 *LongData; + UINT8 Uint8; + UINT16 Uint16; + UINT32 Uint32; + INT8 Int8; + INT16 Int16; + INT32 Int32; + UINT8 *LongData; } HID_DATA; typedef struct { - UINT16 Format; - UINT8 Size; - UINT8 Type; - UINT8 Tag; - HID_DATA Data; + UINT16 Format; + UINT8 Size; + UINT8 Type; + UINT8 Tag; + HID_DATA Data; } HID_ITEM; #define USB_MOUSE_DEV_FROM_MOUSE_PROTOCOL(a) \ @@ -130,9 +129,9 @@ extern EFI_COMPONENT_NAME2_PROTOCOL gUsbMouseComponentName2; EFI_STATUS EFIAPI USBMouseDriverBindingSupported ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -157,9 +156,9 @@ USBMouseDriverBindingSupported ( EFI_STATUS EFIAPI USBMouseDriverBindingStart ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath ); /** @@ -178,10 +177,10 @@ USBMouseDriverBindingStart ( EFI_STATUS EFIAPI USBMouseDriverBindingStop ( - IN EFI_DRIVER_BINDING_PROTOCOL *This, - IN EFI_HANDLE Controller, - IN UINTN NumberOfChildren, - IN EFI_HANDLE *ChildHandleBuffer + IN EFI_DRIVER_BINDING_PROTOCOL *This, + IN EFI_HANDLE Controller, + IN UINTN NumberOfChildren, + IN EFI_HANDLE *ChildHandleBuffer ); // @@ -291,11 +290,11 @@ UsbMouseComponentNameGetDriverName ( EFI_STATUS EFIAPI UsbMouseComponentNameGetControllerName ( - IN EFI_COMPONENT_NAME_PROTOCOL *This, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle OPTIONAL, - IN CHAR8 *Language, - OUT CHAR16 **ControllerName + IN EFI_COMPONENT_NAME_PROTOCOL *This, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle OPTIONAL, + IN CHAR8 *Language, + OUT CHAR16 **ControllerName ); // @@ -337,8 +336,8 @@ GetMouseState ( EFI_STATUS EFIAPI UsbMouseReset ( - IN EFI_SIMPLE_POINTER_PROTOCOL *This, - IN BOOLEAN ExtendedVerification + IN EFI_SIMPLE_POINTER_PROTOCOL *This, + IN BOOLEAN ExtendedVerification ); /** @@ -351,8 +350,8 @@ UsbMouseReset ( VOID EFIAPI UsbMouseWaitForInput ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); // @@ -370,7 +369,7 @@ UsbMouseWaitForInput ( **/ BOOLEAN IsUsbMouse ( - IN EFI_USB_IO_PROTOCOL *UsbIo + IN EFI_USB_IO_PROTOCOL *UsbIo ); /** @@ -390,7 +389,7 @@ IsUsbMouse ( **/ EFI_STATUS InitializeUsbMouseDevice ( - IN OUT USB_MOUSE_DEV *UsbMouseDev + IN OUT USB_MOUSE_DEV *UsbMouseDev ); /** @@ -413,10 +412,10 @@ InitializeUsbMouseDevice ( EFI_STATUS EFIAPI OnMouseInterruptComplete ( - IN VOID *Data, - IN UINTN DataLength, - IN VOID *Context, - IN UINT32 Result + IN VOID *Data, + IN UINTN DataLength, + IN VOID *Context, + IN UINT32 Result ); /** @@ -435,8 +434,8 @@ OnMouseInterruptComplete ( VOID EFIAPI USBMouseRecoveryHandler ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -457,9 +456,9 @@ USBMouseRecoveryHandler ( **/ EFI_STATUS ParseMouseReportDescriptor ( - OUT USB_MOUSE_DEV *UsbMouse, - IN UINT8 *ReportDescriptor, - IN UINTN ReportSize + OUT USB_MOUSE_DEV *UsbMouse, + IN UINT8 *ReportDescriptor, + IN UINTN ReportSize ); #endif diff --git a/MdeModulePkg/Core/Dxe/Dispatcher/Dependency.c b/MdeModulePkg/Core/Dxe/Dispatcher/Dependency.c index 89e540ba75..acbf68b700 100644 --- a/MdeModulePkg/Core/Dxe/Dispatcher/Dependency.c +++ b/MdeModulePkg/Core/Dxe/Dispatcher/Dependency.c @@ -15,15 +15,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Global stack used to evaluate dependency expressions // -BOOLEAN *mDepexEvaluationStack = NULL; -BOOLEAN *mDepexEvaluationStackEnd = NULL; -BOOLEAN *mDepexEvaluationStackPointer = NULL; +BOOLEAN *mDepexEvaluationStack = NULL; +BOOLEAN *mDepexEvaluationStackEnd = NULL; +BOOLEAN *mDepexEvaluationStackPointer = NULL; // // Worker functions // - /** Grow size of the Depex stack @@ -36,8 +35,8 @@ GrowDepexStack ( VOID ) { - BOOLEAN *NewStack; - UINTN Size; + BOOLEAN *NewStack; + UINTN Size; Size = DEPEX_STACK_SIZE_INCREMENT; if (mDepexEvaluationStack != NULL) { @@ -75,8 +74,6 @@ GrowDepexStack ( return EFI_SUCCESS; } - - /** Push an element onto the Boolean Stack. @@ -115,8 +112,6 @@ PushBool ( return EFI_SUCCESS; } - - /** Pop an element from the Boolean stack. @@ -146,8 +141,6 @@ PopBool ( return EFI_SUCCESS; } - - /** Preprocess dependency expression and update DriverEntry to reflect the state of Before, After, and SOR dependencies. If DriverEntry->Before @@ -162,7 +155,7 @@ PopBool ( **/ EFI_STATUS CorePreProcessDepex ( - IN EFI_CORE_DRIVER_ENTRY *DriverEntry + IN EFI_CORE_DRIVER_ENTRY *DriverEntry ) { UINT8 *Iterator; @@ -187,8 +180,6 @@ CorePreProcessDepex ( return EFI_SUCCESS; } - - /** This is the POSTFIX version of the dependency evaluator. This code does not need to handle Before or After, as it is not valid to call this @@ -204,7 +195,7 @@ CorePreProcessDepex ( **/ BOOLEAN CoreIsSchedulable ( - IN EFI_CORE_DRIVER_ENTRY *DriverEntry + IN EFI_CORE_DRIVER_ENTRY *DriverEntry ) { EFI_STATUS Status; @@ -214,7 +205,7 @@ CoreIsSchedulable ( EFI_GUID DriverGuid; VOID *Interface; - Operator = FALSE; + Operator = FALSE; Operator2 = FALSE; if (DriverEntry->After || DriverEntry->Before) { @@ -237,6 +228,7 @@ CoreIsSchedulable ( DEBUG ((DEBUG_DISPATCH, "FALSE\n RESULT = FALSE\n")); return FALSE; } + DEBUG ((DEBUG_DISPATCH, "TRUE\n RESULT = TRUE\n")); return TRUE; } @@ -247,7 +239,6 @@ CoreIsSchedulable ( // mDepexEvaluationStackPointer = mDepexEvaluationStack; - Iterator = DriverEntry->Depex; while (TRUE) { @@ -264,158 +255,166 @@ CoreIsSchedulable ( // Look at the opcode of the dependency expression instruction. // switch (*Iterator) { - case EFI_DEP_BEFORE: - case EFI_DEP_AFTER: - // - // For a well-formed Dependency Expression, the code should never get here. - // The BEFORE and AFTER are processed prior to this routine's invocation. - // If the code flow arrives at this point, there was a BEFORE or AFTER - // that were not the first opcodes. - // - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected BEFORE or AFTER opcode)\n")); - ASSERT (FALSE); - case EFI_DEP_SOR: - // - // These opcodes can only appear once as the first opcode. If it is found - // at any other location, then the dependency expression evaluates to FALSE - // - if (Iterator != DriverEntry->Depex) { - DEBUG ((DEBUG_DISPATCH, " SOR\n")); - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected SOR opcode)\n")); - return FALSE; - } - DEBUG ((DEBUG_DISPATCH, " SOR = Requested\n")); - // - // Otherwise, it is the first opcode and should be treated as a NOP. - // - break; - - case EFI_DEP_PUSH: - // - // Push operator is followed by a GUID. Test to see if the GUID protocol - // is installed and push the boolean result on the stack. - // - CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); - - Status = CoreLocateProtocol (&DriverGuid, NULL, &Interface); - - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = FALSE\n", &DriverGuid)); + case EFI_DEP_BEFORE: + case EFI_DEP_AFTER: + // + // For a well-formed Dependency Expression, the code should never get here. + // The BEFORE and AFTER are processed prior to this routine's invocation. + // If the code flow arrives at this point, there was a BEFORE or AFTER + // that were not the first opcodes. + // + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected BEFORE or AFTER opcode)\n")); + ASSERT (FALSE); + case EFI_DEP_SOR: + // + // These opcodes can only appear once as the first opcode. If it is found + // at any other location, then the dependency expression evaluates to FALSE + // + if (Iterator != DriverEntry->Depex) { + DEBUG ((DEBUG_DISPATCH, " SOR\n")); + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected SOR opcode)\n")); + return FALSE; + } + + DEBUG ((DEBUG_DISPATCH, " SOR = Requested\n")); + // + // Otherwise, it is the first opcode and should be treated as a NOP. + // + break; + + case EFI_DEP_PUSH: + // + // Push operator is followed by a GUID. Test to see if the GUID protocol + // is installed and push the boolean result on the stack. + // + CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); + + Status = CoreLocateProtocol (&DriverGuid, NULL, &Interface); + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = FALSE\n", &DriverGuid)); + Status = PushBool (FALSE); + } else { + DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); + *Iterator = EFI_DEP_REPLACE_TRUE; + Status = PushBool (TRUE); + } + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Iterator += sizeof (EFI_GUID); + break; + + case EFI_DEP_AND: + DEBUG ((DEBUG_DISPATCH, " AND\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PopBool (&Operator2); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(Operator && Operator2)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_OR: + DEBUG ((DEBUG_DISPATCH, " OR\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PopBool (&Operator2); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(Operator || Operator2)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_NOT: + DEBUG ((DEBUG_DISPATCH, " NOT\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(!Operator)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_TRUE: + DEBUG ((DEBUG_DISPATCH, " TRUE\n")); + Status = PushBool (TRUE); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_FALSE: + DEBUG ((DEBUG_DISPATCH, " FALSE\n")); Status = PushBool (FALSE); - } else { + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_END: + DEBUG ((DEBUG_DISPATCH, " END\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + DEBUG ((DEBUG_DISPATCH, " RESULT = %a\n", Operator ? "TRUE" : "FALSE")); + return Operator; + + case EFI_DEP_REPLACE_TRUE: + CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); - *Iterator = EFI_DEP_REPLACE_TRUE; + Status = PushBool (TRUE); - } - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Iterator += sizeof (EFI_GUID); - break; - - case EFI_DEP_AND: - DEBUG ((DEBUG_DISPATCH, " AND\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PopBool (&Operator2); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(Operator && Operator2)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_OR: - DEBUG ((DEBUG_DISPATCH, " OR\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PopBool (&Operator2); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(Operator || Operator2)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_NOT: - DEBUG ((DEBUG_DISPATCH, " NOT\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(!Operator)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_TRUE: - DEBUG ((DEBUG_DISPATCH, " TRUE\n")); - Status = PushBool (TRUE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_FALSE: - DEBUG ((DEBUG_DISPATCH, " FALSE\n")); - Status = PushBool (FALSE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_END: - DEBUG ((DEBUG_DISPATCH, " END\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - DEBUG ((DEBUG_DISPATCH, " RESULT = %a\n", Operator ? "TRUE" : "FALSE")); - return Operator; - - case EFI_DEP_REPLACE_TRUE: - CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); - DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); - - Status = PushBool (TRUE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Iterator += sizeof (EFI_GUID); - break; - - default: - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unknown opcode)\n")); - goto Done; + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Iterator += sizeof (EFI_GUID); + break; + + default: + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unknown opcode)\n")); + goto Done; } // @@ -432,5 +431,3 @@ CoreIsSchedulable ( Done: return FALSE; } - - diff --git a/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c index 3605605e91..fb9ae3ce78 100644 --- a/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Dxe/Dispatcher/Dispatcher.c @@ -55,7 +55,6 @@ LIST_ENTRY mFvHandleList = INITIALIZE_LIST_HEAD_VARIABLE (mFvHandleList); // EFI_LOCK mDispatcherLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL); - // // Flag for the DXE Dispacher. TRUE if dispatcher is execuing. // @@ -64,13 +63,13 @@ BOOLEAN gDispatcherRunning = FALSE; // // Module globals to manage the FwVol registration notification event // -EFI_EVENT mFwVolEvent; -VOID *mFwVolEventRegistration; +EFI_EVENT mFwVolEvent; +VOID *mFwVolEventRegistration; // // List of file types supported by dispatcher // -EFI_FV_FILETYPE mDxeFileTypes[] = { +EFI_FV_FILETYPE mDxeFileTypes[] = { EFI_FV_FILETYPE_DRIVER, EFI_FV_FILETYPE_COMBINED_SMM_DXE, EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER, @@ -79,15 +78,16 @@ EFI_FV_FILETYPE mDxeFileTypes[] = { }; typedef struct { - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH File; - EFI_DEVICE_PATH_PROTOCOL End; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH File; + EFI_DEVICE_PATH_PROTOCOL End; } FV_FILEPATH_DEVICE_PATH; -FV_FILEPATH_DEVICE_PATH mFvDevicePath; +FV_FILEPATH_DEVICE_PATH mFvDevicePath; // // Function Prototypes // + /** Insert InsertedDriverEntry onto the mScheduledQueue. To do this you must add any driver with a before dependency on InsertedDriverEntry first. @@ -101,7 +101,7 @@ FV_FILEPATH_DEVICE_PATH mFvDevicePath; **/ VOID CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( - IN EFI_CORE_DRIVER_ENTRY *InsertedDriverEntry + IN EFI_CORE_DRIVER_ENTRY *InsertedDriverEntry ); /** @@ -124,8 +124,8 @@ CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( VOID EFIAPI CoreFwVolEventProtocolNotify ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -143,9 +143,9 @@ CoreFwVolEventProtocolNotify ( **/ EFI_DEVICE_PATH_PROTOCOL * CoreFvToDevicePath ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *DriverName + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *DriverName ); /** @@ -171,10 +171,10 @@ CoreFvToDevicePath ( **/ EFI_STATUS CoreAddToDriverList ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *DriverName, - IN EFI_FV_FILETYPE Type + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *DriverName, + IN EFI_FV_FILETYPE Type ); /** @@ -190,12 +190,11 @@ CoreAddToDriverList ( **/ EFI_STATUS CoreProcessFvImageFile ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *FileName + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *FileName ); - /** Enter critical section by gaining lock on mDispatcherLock. @@ -208,7 +207,6 @@ CoreAcquireDispatcherLock ( CoreAcquireLock (&mDispatcherLock); } - /** Exit critical section by releasing lock on mDispatcherLock. @@ -221,7 +219,6 @@ CoreReleaseDispatcherLock ( CoreReleaseLock (&mDispatcherLock); } - /** Read Depex and pre-process the Depex for Before and After. If Section Extraction protocol returns an error via ReadSection defer the reading of the Depex. @@ -236,30 +233,29 @@ CoreReleaseDispatcherLock ( **/ EFI_STATUS CoreGetDepexSectionAndPreProccess ( - IN EFI_CORE_DRIVER_ENTRY *DriverEntry + IN EFI_CORE_DRIVER_ENTRY *DriverEntry ) { - EFI_STATUS Status; - EFI_SECTION_TYPE SectionType; - UINT32 AuthenticationStatus; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - + EFI_STATUS Status; + EFI_SECTION_TYPE SectionType; + UINT32 AuthenticationStatus; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; Fv = DriverEntry->Fv; // // Grab Depex info, it will never be free'ed. // - SectionType = EFI_SECTION_DXE_DEPEX; - Status = Fv->ReadSection ( - DriverEntry->Fv, - &DriverEntry->FileName, - SectionType, - 0, - &DriverEntry->Depex, - (UINTN *)&DriverEntry->DepexSize, - &AuthenticationStatus - ); + SectionType = EFI_SECTION_DXE_DEPEX; + Status = Fv->ReadSection ( + DriverEntry->Fv, + &DriverEntry->FileName, + SectionType, + 0, + &DriverEntry->Depex, + (UINTN *)&DriverEntry->DepexSize, + &AuthenticationStatus + ); if (EFI_ERROR (Status)) { if (Status == EFI_PROTOCOL_ERROR) { // @@ -270,8 +266,8 @@ CoreGetDepexSectionAndPreProccess ( // // If no Depex assume UEFI 2.0 driver model // - DriverEntry->Depex = NULL; - DriverEntry->Dependent = TRUE; + DriverEntry->Depex = NULL; + DriverEntry->Dependent = TRUE; DriverEntry->DepexProtocolError = FALSE; } } else { @@ -286,7 +282,6 @@ CoreGetDepexSectionAndPreProccess ( return Status; } - /** Check every driver and locate a matching one. If the driver is found, the Unrequested state flag is cleared. @@ -308,23 +303,24 @@ CoreSchedule ( IN EFI_GUID *DriverName ) { - LIST_ENTRY *Link; - EFI_CORE_DRIVER_ENTRY *DriverEntry; + LIST_ENTRY *Link; + EFI_CORE_DRIVER_ENTRY *DriverEntry; // // Check every driver // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->FvHandle == FirmwareVolumeHandle && + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + if ((DriverEntry->FvHandle == FirmwareVolumeHandle) && DriverEntry->Unrequested && - CompareGuid (DriverName, &DriverEntry->FileName)) { + CompareGuid (DriverName, &DriverEntry->FileName)) + { // // Move the driver from the Unrequested to the Dependent state // CoreAcquireDispatcherLock (); - DriverEntry->Unrequested = FALSE; - DriverEntry->Dependent = TRUE; + DriverEntry->Unrequested = FALSE; + DriverEntry->Dependent = TRUE; CoreReleaseDispatcherLock (); DEBUG ((DEBUG_DISPATCH, "Schedule FFS(%g) - EFI_SUCCESS\n", DriverName)); @@ -338,8 +334,6 @@ CoreSchedule ( return EFI_NOT_FOUND; } - - /** Convert a driver from the Untrused back to the Scheduled state. @@ -359,17 +353,18 @@ CoreTrust ( IN EFI_GUID *DriverName ) { - LIST_ENTRY *Link; - EFI_CORE_DRIVER_ENTRY *DriverEntry; + LIST_ENTRY *Link; + EFI_CORE_DRIVER_ENTRY *DriverEntry; // // Check every driver // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->FvHandle == FirmwareVolumeHandle && + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + if ((DriverEntry->FvHandle == FirmwareVolumeHandle) && DriverEntry->Untrusted && - CompareGuid (DriverName, &DriverEntry->FileName)) { + CompareGuid (DriverName, &DriverEntry->FileName)) + { // // Transition driver from Untrusted to Scheduled state. // @@ -382,6 +377,7 @@ CoreTrust ( return EFI_SUCCESS; } } + return EFI_NOT_FOUND; } @@ -405,12 +401,12 @@ CoreDispatcher ( VOID ) { - EFI_STATUS Status; - EFI_STATUS ReturnStatus; - LIST_ENTRY *Link; - EFI_CORE_DRIVER_ENTRY *DriverEntry; - BOOLEAN ReadyToRun; - EFI_EVENT DxeDispatchEvent; + EFI_STATUS Status; + EFI_STATUS ReturnStatus; + LIST_ENTRY *Link; + EFI_CORE_DRIVER_ENTRY *DriverEntry; + BOOLEAN ReadyToRun; + EFI_EVENT DxeDispatchEvent; PERF_FUNCTION_BEGIN (); @@ -453,16 +449,16 @@ CoreDispatcher ( // Untrused to Scheduled it would have already been loaded so we may need to // skip the LoadImage // - if (DriverEntry->ImageHandle == NULL && !DriverEntry->IsFvImage) { + if ((DriverEntry->ImageHandle == NULL) && !DriverEntry->IsFvImage) { DEBUG ((DEBUG_INFO, "Loading driver %g\n", &DriverEntry->FileName)); Status = CoreLoadImage ( - FALSE, - gDxeCoreImageHandle, - DriverEntry->FvFileDevicePath, - NULL, - 0, - &DriverEntry->ImageHandle - ); + FALSE, + gDxeCoreImageHandle, + DriverEntry->FvFileDevicePath, + NULL, + 0, + &DriverEntry->ImageHandle + ); // // Update the driver state to reflect that it's been loaded @@ -482,7 +478,7 @@ CoreDispatcher ( // // This case include the Never Trusted state if EFI_ACCESS_DENIED is returned // - DriverEntry->Initialized = TRUE; + DriverEntry->Initialized = TRUE; } DriverEntry->Scheduled = FALSE; @@ -499,13 +495,12 @@ CoreDispatcher ( CoreAcquireDispatcherLock (); - DriverEntry->Scheduled = FALSE; - DriverEntry->Initialized = TRUE; + DriverEntry->Scheduled = FALSE; + DriverEntry->Initialized = TRUE; RemoveEntryList (&DriverEntry->ScheduledLink); CoreReleaseDispatcherLock (); - if (DriverEntry->IsFvImage) { // // Produce a firmware volume block protocol for FvImage so it gets dispatched from. @@ -549,7 +544,7 @@ CoreDispatcher ( for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->DepexProtocolError){ + if (DriverEntry->DepexProtocolError) { // // If Section Extraction Protocol did not let the Depex be read before retry the read // @@ -583,7 +578,6 @@ CoreDispatcher ( return ReturnStatus; } - /** Insert InsertedDriverEntry onto the mScheduledQueue. To do this you must add any driver with a before dependency on InsertedDriverEntry first. @@ -597,18 +591,18 @@ CoreDispatcher ( **/ VOID CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( - IN EFI_CORE_DRIVER_ENTRY *InsertedDriverEntry + IN EFI_CORE_DRIVER_ENTRY *InsertedDriverEntry ) { - LIST_ENTRY *Link; - EFI_CORE_DRIVER_ENTRY *DriverEntry; + LIST_ENTRY *Link; + EFI_CORE_DRIVER_ENTRY *DriverEntry; // // Process Before Dependency // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) { + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + if (DriverEntry->Before && DriverEntry->Dependent && (DriverEntry != InsertedDriverEntry)) { DEBUG ((DEBUG_DISPATCH, "Evaluate DXE DEPEX for FFS(%g)\n", &DriverEntry->FileName)); DEBUG ((DEBUG_DISPATCH, " BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid)); if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) { @@ -638,8 +632,8 @@ CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( // Process After Dependency // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) { + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + if (DriverEntry->After && DriverEntry->Dependent && (DriverEntry != InsertedDriverEntry)) { DEBUG ((DEBUG_DISPATCH, "Evaluate DXE DEPEX for FFS(%g)\n", &DriverEntry->FileName)); DEBUG ((DEBUG_DISPATCH, " AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid)); if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) { @@ -655,7 +649,6 @@ CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( } } - /** Return TRUE if the Fv has been processed, FALSE if not. @@ -667,22 +660,22 @@ CoreInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( **/ BOOLEAN FvHasBeenProcessed ( - IN EFI_HANDLE FvHandle + IN EFI_HANDLE FvHandle ) { - LIST_ENTRY *Link; - KNOWN_HANDLE *KnownHandle; + LIST_ENTRY *Link; + KNOWN_HANDLE *KnownHandle; for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) { - KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); + KnownHandle = CR (Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); if (KnownHandle->Handle == FvHandle) { return TRUE; } } + return FALSE; } - /** Remember that Fv protocol on FvHandle has had it's drivers placed on the mDiscoveredList. This fucntion adds entries on the mFvHandleList if new @@ -697,21 +690,21 @@ FvHasBeenProcessed ( **/ KNOWN_HANDLE * FvIsBeingProcessed ( - IN EFI_HANDLE FvHandle + IN EFI_HANDLE FvHandle ) { - EFI_STATUS Status; - EFI_GUID FvNameGuid; - BOOLEAN FvNameGuidIsFound; - UINT32 ExtHeaderOffset; - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - EFI_FV_BLOCK_MAP_ENTRY *BlockMap; - UINTN LbaOffset; - UINTN Index; - EFI_LBA LbaIndex; - LIST_ENTRY *Link; - KNOWN_HANDLE *KnownHandle; + EFI_STATUS Status; + EFI_GUID FvNameGuid; + BOOLEAN FvNameGuidIsFound; + UINT32 ExtHeaderOffset; + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_FV_BLOCK_MAP_ENTRY *BlockMap; + UINTN LbaOffset; + UINTN Index; + EFI_LBA LbaIndex; + LIST_ENTRY *Link; + KNOWN_HANDLE *KnownHandle; FwVolHeader = NULL; @@ -719,7 +712,7 @@ FvIsBeingProcessed ( // Get the FirmwareVolumeBlock protocol on that handle // FvNameGuidIsFound = FALSE; - Status = CoreHandleProtocol (FvHandle, &gEfiFirmwareVolumeBlockProtocolGuid, (VOID **)&Fvb); + Status = CoreHandleProtocol (FvHandle, &gEfiFirmwareVolumeBlockProtocolGuid, (VOID **)&Fvb); if (!EFI_ERROR (Status)) { // // Get the full FV header based on FVB protocol. @@ -728,19 +721,20 @@ FvIsBeingProcessed ( Status = GetFwVolHeader (Fvb, &FwVolHeader); if (!EFI_ERROR (Status)) { ASSERT (FwVolHeader != NULL); - if (VerifyFvHeaderChecksum (FwVolHeader) && FwVolHeader->ExtHeaderOffset != 0) { - ExtHeaderOffset = (UINT32) FwVolHeader->ExtHeaderOffset; - BlockMap = FwVolHeader->BlockMap; - LbaIndex = 0; - LbaOffset = 0; + if (VerifyFvHeaderChecksum (FwVolHeader) && (FwVolHeader->ExtHeaderOffset != 0)) { + ExtHeaderOffset = (UINT32)FwVolHeader->ExtHeaderOffset; + BlockMap = FwVolHeader->BlockMap; + LbaIndex = 0; + LbaOffset = 0; // // Find LbaIndex and LbaOffset for FV extension header based on BlockMap. // while ((BlockMap->NumBlocks != 0) || (BlockMap->Length != 0)) { - for (Index = 0; Index < BlockMap->NumBlocks && ExtHeaderOffset >= BlockMap->Length; Index ++) { + for (Index = 0; Index < BlockMap->NumBlocks && ExtHeaderOffset >= BlockMap->Length; Index++) { ExtHeaderOffset -= BlockMap->Length; - LbaIndex ++; + LbaIndex++; } + // // Check whether FvExtHeader is crossing the multi block range. // @@ -748,16 +742,19 @@ FvIsBeingProcessed ( LbaOffset = ExtHeaderOffset; break; } + BlockMap++; } + // // Read FvNameGuid from FV extension header. // - Status = ReadFvbData (Fvb, &LbaIndex, &LbaOffset, sizeof (FvNameGuid), (UINT8 *) &FvNameGuid); + Status = ReadFvbData (Fvb, &LbaIndex, &LbaOffset, sizeof (FvNameGuid), (UINT8 *)&FvNameGuid); if (!EFI_ERROR (Status)) { FvNameGuidIsFound = TRUE; } } + CoreFreePool (FwVolHeader); } } @@ -767,7 +764,7 @@ FvIsBeingProcessed ( // Check whether the FV image with the found FvNameGuid has been processed. // for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) { - KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); + KnownHandle = CR (Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); if (CompareGuid (&FvNameGuid, &KnownHandle->FvNameGuid)) { DEBUG ((DEBUG_ERROR, "FvImage on FvHandle %p and %p has the same FvNameGuid %g.\n", FvHandle, KnownHandle->Handle, &FvNameGuid)); return NULL; @@ -779,17 +776,15 @@ FvIsBeingProcessed ( ASSERT (KnownHandle != NULL); KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE; - KnownHandle->Handle = FvHandle; + KnownHandle->Handle = FvHandle; if (FvNameGuidIsFound) { CopyGuid (&KnownHandle->FvNameGuid, &FvNameGuid); } + InsertTailList (&mFvHandleList, &KnownHandle->Link); return KnownHandle; } - - - /** Convert FvHandle and DriverName into an EFI device path @@ -805,14 +800,14 @@ FvIsBeingProcessed ( **/ EFI_DEVICE_PATH_PROTOCOL * CoreFvToDevicePath ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *DriverName + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *DriverName ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; - EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; + EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath; // // Remember the device path of the FV @@ -828,16 +823,14 @@ CoreFvToDevicePath ( SetDevicePathEndNode (&mFvDevicePath.End); FileNameDevicePath = AppendDevicePath ( - FvDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath - ); + FvDevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath + ); } return FileNameDevicePath; } - - /** Add an entry to the mDiscoveredList. Allocate memory to store the DriverEntry, and initilize any state variables. Read the Depex from the FV and store it @@ -861,14 +854,13 @@ CoreFvToDevicePath ( **/ EFI_STATUS CoreAddToDriverList ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *DriverName, - IN EFI_FV_FILETYPE Type + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *DriverName, + IN EFI_FV_FILETYPE Type ) { - EFI_CORE_DRIVER_ENTRY *DriverEntry; - + EFI_CORE_DRIVER_ENTRY *DriverEntry; // // Create the Driver Entry for the list. ZeroPool initializes lots of variables to @@ -880,7 +872,7 @@ CoreAddToDriverList ( DriverEntry->IsFvImage = TRUE; } - DriverEntry->Signature = EFI_CORE_DRIVER_ENTRY_SIGNATURE; + DriverEntry->Signature = EFI_CORE_DRIVER_ENTRY_SIGNATURE; CopyGuid (&DriverEntry->FileName, DriverName); DriverEntry->FvHandle = FvHandle; DriverEntry->Fv = Fv; @@ -897,7 +889,6 @@ CoreAddToDriverList ( return EFI_SUCCESS; } - /** Check if a FV Image type file (EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) is described by a EFI_HOB_FIRMWARE_VOLUME2 Hob. @@ -912,11 +903,11 @@ CoreAddToDriverList ( **/ BOOLEAN FvFoundInHobFv2 ( - IN CONST EFI_GUID *FvNameGuid, - IN CONST EFI_GUID *DriverName + IN CONST EFI_GUID *FvNameGuid, + IN CONST EFI_GUID *DriverName ) { - EFI_PEI_HOB_POINTERS HobFv2; + EFI_PEI_HOB_POINTERS HobFv2; HobFv2.Raw = GetHobList (); @@ -925,9 +916,11 @@ FvFoundInHobFv2 ( // Compare parent FvNameGuid and FileGuid both. // if (CompareGuid (DriverName, &HobFv2.FirmwareVolume2->FileName) && - CompareGuid (FvNameGuid, &HobFv2.FirmwareVolume2->FvName)) { + CompareGuid (FvNameGuid, &HobFv2.FirmwareVolume2->FvName)) + { return TRUE; } + HobFv2.Raw = GET_NEXT_HOB (HobFv2); } @@ -950,9 +943,9 @@ FvFoundInHobFv2 ( **/ BOOLEAN GetFvUsedSize ( - IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader, - OUT UINT32 *FvUsedSize, - OUT UINT8 *EraseByte + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader, + OUT UINT32 *FvUsedSize, + OUT UINT8 *EraseByte ) { UINT16 ExtHeaderOffset; @@ -962,20 +955,21 @@ GetFvUsedSize ( ExtHeaderOffset = ReadUnaligned16 (&FvHeader->ExtHeaderOffset); if (ExtHeaderOffset != 0) { - ExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) ((UINT8 *) FvHeader + ExtHeaderOffset); - ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *) (ExtHeader + 1); - while ((UINTN) ExtEntryList < ((UINTN) ExtHeader + ReadUnaligned32 (&ExtHeader->ExtHeaderSize))) { + ExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)((UINT8 *)FvHeader + ExtHeaderOffset); + ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *)(ExtHeader + 1); + while ((UINTN)ExtEntryList < ((UINTN)ExtHeader + ReadUnaligned32 (&ExtHeader->ExtHeaderSize))) { if (ReadUnaligned16 (&ExtEntryList->ExtEntryType) == EFI_FV_EXT_TYPE_USED_SIZE_TYPE) { // // USED_SIZE FV_EXT_TYPE entry is found. // - ExtEntryUsedSize = (EFI_FIRMWARE_VOLUME_EXT_ENTRY_USED_SIZE_TYPE *) ExtEntryList; - *FvUsedSize = ReadUnaligned32 (&ExtEntryUsedSize->UsedSize); + ExtEntryUsedSize = (EFI_FIRMWARE_VOLUME_EXT_ENTRY_USED_SIZE_TYPE *)ExtEntryList; + *FvUsedSize = ReadUnaligned32 (&ExtEntryUsedSize->UsedSize); if ((ReadUnaligned32 (&FvHeader->Attributes) & EFI_FVB2_ERASE_POLARITY) != 0) { *EraseByte = 0xFF; } else { *EraseByte = 0; } + DEBUG (( DEBUG_INFO, "FV at 0x%x has 0x%x used size, and erase byte is 0x%02x\n", @@ -985,8 +979,9 @@ GetFvUsedSize ( )); return TRUE; } + ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *) - ((UINT8 *) ExtEntryList + ReadUnaligned16 (&ExtEntryList->ExtEntrySize)); + ((UINT8 *)ExtEntryList + ReadUnaligned16 (&ExtEntryList->ExtEntrySize)); } } @@ -1009,28 +1004,28 @@ GetFvUsedSize ( **/ EFI_STATUS CoreProcessFvImageFile ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *FileName + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *FileName ) { - EFI_STATUS Status; - EFI_SECTION_TYPE SectionType; - UINT32 AuthenticationStatus; - VOID *Buffer; - VOID *AlignedBuffer; - UINTN BufferSize; - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - UINT32 FvAlignment; - EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; - UINT32 FvUsedSize; - UINT8 EraseByte; - UINTN Index; + EFI_STATUS Status; + EFI_SECTION_TYPE SectionType; + UINT32 AuthenticationStatus; + VOID *Buffer; + VOID *AlignedBuffer; + UINTN BufferSize; + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + UINT32 FvAlignment; + EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; + UINT32 FvUsedSize; + UINT8 EraseByte; + UINTN Index; // // Read firmware volume section(s) // - SectionType = EFI_SECTION_FIRMWARE_VOLUME_IMAGE; + SectionType = EFI_SECTION_FIRMWARE_VOLUME_IMAGE; Index = 0; do { @@ -1039,27 +1034,27 @@ CoreProcessFvImageFile ( Buffer = NULL; BufferSize = 0; AlignedBuffer = NULL; - Status = Fv->ReadSection ( - Fv, - FileName, - SectionType, - Index, - &Buffer, - &BufferSize, - &AuthenticationStatus - ); + Status = Fv->ReadSection ( + Fv, + FileName, + SectionType, + Index, + &Buffer, + &BufferSize, + &AuthenticationStatus + ); if (!EFI_ERROR (Status)) { - // + // // Evaluate the authentication status of the Firmware Volume through // Security Architectural Protocol // if (gSecurity != NULL) { FvFileDevicePath = CoreFvToDevicePath (Fv, FvHandle, FileName); - Status = gSecurity->FileAuthenticationState ( - gSecurity, - AuthenticationStatus, - FvFileDevicePath - ); + Status = gSecurity->FileAuthenticationState ( + gSecurity, + AuthenticationStatus, + FvFileDevicePath + ); if (FvFileDevicePath != NULL) { FreePool (FvFileDevicePath); } @@ -1071,6 +1066,7 @@ CoreProcessFvImageFile ( if (Buffer != NULL) { FreePool (Buffer); } + break; } } @@ -1078,7 +1074,7 @@ CoreProcessFvImageFile ( // // FvImage should be at its required alignment. // - FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) Buffer; + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)Buffer; // // If EFI_FVB2_WEAK_ALIGNMENT is set in the volume header then the first byte of the volume // can be aligned on any power-of-two boundary. A weakly aligned volume can not be moved from @@ -1107,11 +1103,11 @@ CoreProcessFvImageFile ( // // Check FvImage alignment. // - if ((UINTN) FvHeader % FvAlignment != 0) { + if ((UINTN)FvHeader % FvAlignment != 0) { // // Allocate the aligned buffer for the FvImage. // - AlignedBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), (UINTN) FvAlignment); + AlignedBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES (BufferSize), (UINTN)FvAlignment); if (AlignedBuffer == NULL) { FreePool (Buffer); Status = EFI_OUT_OF_RESOURCES; @@ -1124,31 +1120,33 @@ CoreProcessFvImageFile ( // // Copy the used bytes and fill the rest with the erase value. // - CopyMem (AlignedBuffer, FvHeader, (UINTN) FvUsedSize); + CopyMem (AlignedBuffer, FvHeader, (UINTN)FvUsedSize); SetMem ( - (UINT8 *) AlignedBuffer + FvUsedSize, - (UINTN) (BufferSize - FvUsedSize), + (UINT8 *)AlignedBuffer + FvUsedSize, + (UINTN)(BufferSize - FvUsedSize), EraseByte ); } else { CopyMem (AlignedBuffer, Buffer, BufferSize); } - FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) AlignedBuffer; + + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)AlignedBuffer; FreePool (Buffer); Buffer = NULL; } } } + // // Produce a FVB protocol for the file // Status = ProduceFVBProtocolOnBuffer ( - (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, - (UINT64)BufferSize, - FvHandle, - AuthenticationStatus, - NULL - ); + (EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader, + (UINT64)BufferSize, + FvHandle, + AuthenticationStatus, + NULL + ); } if (EFI_ERROR (Status)) { @@ -1179,7 +1177,6 @@ CoreProcessFvImageFile ( } } - /** Event notification that is fired every time a FV dispatch protocol is added. More than one protocol may have been added when this event is fired, so you @@ -1200,42 +1197,42 @@ CoreProcessFvImageFile ( VOID EFIAPI CoreFwVolEventProtocolNotify ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - EFI_STATUS GetNextFileStatus; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; - EFI_HANDLE FvHandle; - UINTN BufferSize; - EFI_GUID NameGuid; - UINTN Key; - EFI_FV_FILETYPE Type; - EFI_FV_FILE_ATTRIBUTES Attributes; - UINTN Size; - EFI_CORE_DRIVER_ENTRY *DriverEntry; - EFI_GUID *AprioriFile; - UINTN AprioriEntryCount; - UINTN Index; - LIST_ENTRY *Link; - UINT32 AuthenticationStatus; - UINTN SizeOfBuffer; - VOID *DepexBuffer; - KNOWN_HANDLE *KnownHandle; + EFI_STATUS Status; + EFI_STATUS GetNextFileStatus; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; + EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; + EFI_HANDLE FvHandle; + UINTN BufferSize; + EFI_GUID NameGuid; + UINTN Key; + EFI_FV_FILETYPE Type; + EFI_FV_FILE_ATTRIBUTES Attributes; + UINTN Size; + EFI_CORE_DRIVER_ENTRY *DriverEntry; + EFI_GUID *AprioriFile; + UINTN AprioriEntryCount; + UINTN Index; + LIST_ENTRY *Link; + UINT32 AuthenticationStatus; + UINTN SizeOfBuffer; + VOID *DepexBuffer; + KNOWN_HANDLE *KnownHandle; FvHandle = NULL; while (TRUE) { BufferSize = sizeof (EFI_HANDLE); - Status = CoreLocateHandle ( - ByRegisterNotify, - NULL, - mFwVolEventRegistration, - &BufferSize, - &FvHandle - ); + Status = CoreLocateHandle ( + ByRegisterNotify, + NULL, + mFwVolEventRegistration, + &BufferSize, + &FvHandle + ); if (EFI_ERROR (Status)) { // // If no more notification events exit @@ -1263,7 +1260,7 @@ CoreFwVolEventProtocolNotify ( } Status = CoreHandleProtocol (FvHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&Fv); - if (EFI_ERROR (Status) || Fv == NULL) { + if (EFI_ERROR (Status) || (Fv == NULL)) { // // FvHandle must have Firmware Volume2 protocol thus we should never get here. // @@ -1291,7 +1288,7 @@ CoreFwVolEventProtocolNotify ( // Key = 0; do { - Type = mDxeFileTypes[Index]; + Type = mDxeFileTypes[Index]; GetNextFileStatus = Fv->GetNextFile ( Fv, &Key, @@ -1334,15 +1331,15 @@ CoreFwVolEventProtocolNotify ( // DepexBuffer = NULL; SizeOfBuffer = 0; - Status = Fv->ReadSection ( - Fv, - &NameGuid, - EFI_SECTION_SMM_DEPEX, - 0, - &DepexBuffer, - &SizeOfBuffer, - &AuthenticationStatus - ); + Status = Fv->ReadSection ( + Fv, + &NameGuid, + EFI_SECTION_SMM_DEPEX, + 0, + &DepexBuffer, + &SizeOfBuffer, + &AuthenticationStatus + ); if (!EFI_ERROR (Status)) { // // If SMM depex section is found, this FV image is invalid to be supported. @@ -1357,15 +1354,15 @@ CoreFwVolEventProtocolNotify ( // DepexBuffer = NULL; SizeOfBuffer = 0; - Status = Fv->ReadSection ( - Fv, - &NameGuid, - EFI_SECTION_DXE_DEPEX, - 0, - &DepexBuffer, - &SizeOfBuffer, - &AuthenticationStatus - ); + Status = Fv->ReadSection ( + Fv, + &NameGuid, + EFI_SECTION_DXE_DEPEX, + 0, + &DepexBuffer, + &SizeOfBuffer, + &AuthenticationStatus + ); if (EFI_ERROR (Status)) { // // If no depex section, produce a firmware volume block protocol for it so it gets dispatched from. @@ -1392,15 +1389,15 @@ CoreFwVolEventProtocolNotify ( // Read the array of GUIDs from the Apriori file if it is present in the firmware volume // AprioriFile = NULL; - Status = Fv->ReadSection ( - Fv, - &gAprioriGuid, - EFI_SECTION_RAW, - 0, - (VOID **)&AprioriFile, - &SizeOfBuffer, - &AuthenticationStatus - ); + Status = Fv->ReadSection ( + Fv, + &gAprioriGuid, + EFI_SECTION_RAW, + 0, + (VOID **)&AprioriFile, + &SizeOfBuffer, + &AuthenticationStatus + ); if (!EFI_ERROR (Status)) { AprioriEntryCount = SizeOfBuffer / sizeof (EFI_GUID); } else { @@ -1415,9 +1412,10 @@ CoreFwVolEventProtocolNotify ( for (Index = 0; Index < AprioriEntryCount; Index++) { for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); if (CompareGuid (&DriverEntry->FileName, &AprioriFile[Index]) && - (FvHandle == DriverEntry->FvHandle)) { + (FvHandle == DriverEntry->FvHandle)) + { CoreAcquireDispatcherLock (); DriverEntry->Dependent = FALSE; DriverEntry->Scheduled = TRUE; @@ -1437,8 +1435,6 @@ CoreFwVolEventProtocolNotify ( } } - - /** Initialize the dispatcher. Initialize the notification function that runs when an FV2 protocol is added to the system. @@ -1476,11 +1472,11 @@ CoreDisplayDiscoveredNotDispatched ( VOID ) { - LIST_ENTRY *Link; - EFI_CORE_DRIVER_ENTRY *DriverEntry; + LIST_ENTRY *Link; + EFI_CORE_DRIVER_ENTRY *DriverEntry; - for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); + for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { + DriverEntry = CR (Link, EFI_CORE_DRIVER_ENTRY, Link, EFI_CORE_DRIVER_ENTRY_SIGNATURE); if (DriverEntry->Dependent) { DEBUG ((DEBUG_LOAD, "Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName)); } diff --git a/MdeModulePkg/Core/Dxe/DxeMain.h b/MdeModulePkg/Core/Dxe/DxeMain.h index 7779e2d4e3..815a6b4bd8 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain.h +++ b/MdeModulePkg/Core/Dxe/DxeMain.h @@ -10,8 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _DXE_MAIN_H_ #define _DXE_MAIN_H_ - - #include #include @@ -87,7 +85,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - // // attributes for reserved memory before it is promoted to system memory // @@ -100,7 +97,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // #define EFI_MEMORY_PORT_IO 0x4000000000000000ULL - /// /// EFI_DEP_REPLACE_TRUE - Used to dynamically patch the dependency expression /// to save time. A EFI_DEP_PUSH is evaluated one an @@ -117,11 +113,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define DEPEX_STACK_SIZE_INCREMENT 0x1000 typedef struct { - EFI_GUID *ProtocolGuid; - VOID **Protocol; - EFI_EVENT Event; - VOID *Registration; - BOOLEAN Present; + EFI_GUID *ProtocolGuid; + VOID **Protocol; + EFI_EVENT Event; + VOID *Registration; + BOOLEAN Present; } EFI_CORE_PROTOCOL_NOTIFY_ENTRY; // @@ -130,171 +126,166 @@ typedef struct { #define KNOWN_HANDLE_SIGNATURE SIGNATURE_32('k','n','o','w') typedef struct { - UINTN Signature; - LIST_ENTRY Link; // mFvHandleList - EFI_HANDLE Handle; - EFI_GUID FvNameGuid; + UINTN Signature; + LIST_ENTRY Link; // mFvHandleList + EFI_HANDLE Handle; + EFI_GUID FvNameGuid; } KNOWN_HANDLE; - -#define EFI_CORE_DRIVER_ENTRY_SIGNATURE SIGNATURE_32('d','r','v','r') +#define EFI_CORE_DRIVER_ENTRY_SIGNATURE SIGNATURE_32('d','r','v','r') typedef struct { - UINTN Signature; - LIST_ENTRY Link; // mDriverList + UINTN Signature; + LIST_ENTRY Link; // mDriverList - LIST_ENTRY ScheduledLink; // mScheduledQueue + LIST_ENTRY ScheduledLink; // mScheduledQueue - EFI_HANDLE FvHandle; - EFI_GUID FileName; - EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; + EFI_HANDLE FvHandle; + EFI_GUID FileName; + EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - VOID *Depex; - UINTN DepexSize; + VOID *Depex; + UINTN DepexSize; - BOOLEAN Before; - BOOLEAN After; - EFI_GUID BeforeAfterGuid; + BOOLEAN Before; + BOOLEAN After; + EFI_GUID BeforeAfterGuid; - BOOLEAN Dependent; - BOOLEAN Unrequested; - BOOLEAN Scheduled; - BOOLEAN Untrusted; - BOOLEAN Initialized; - BOOLEAN DepexProtocolError; - - EFI_HANDLE ImageHandle; - BOOLEAN IsFvImage; + BOOLEAN Dependent; + BOOLEAN Unrequested; + BOOLEAN Scheduled; + BOOLEAN Untrusted; + BOOLEAN Initialized; + BOOLEAN DepexProtocolError; + EFI_HANDLE ImageHandle; + BOOLEAN IsFvImage; } EFI_CORE_DRIVER_ENTRY; // -//The data structure of GCD memory map entry +// The data structure of GCD memory map entry // #define EFI_GCD_MAP_SIGNATURE SIGNATURE_32('g','c','d','m') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - EFI_PHYSICAL_ADDRESS BaseAddress; - UINT64 EndAddress; - UINT64 Capabilities; - UINT64 Attributes; - EFI_GCD_MEMORY_TYPE GcdMemoryType; - EFI_GCD_IO_TYPE GcdIoType; - EFI_HANDLE ImageHandle; - EFI_HANDLE DeviceHandle; + UINTN Signature; + LIST_ENTRY Link; + EFI_PHYSICAL_ADDRESS BaseAddress; + UINT64 EndAddress; + UINT64 Capabilities; + UINT64 Attributes; + EFI_GCD_MEMORY_TYPE GcdMemoryType; + EFI_GCD_IO_TYPE GcdIoType; + EFI_HANDLE ImageHandle; + EFI_HANDLE DeviceHandle; } EFI_GCD_MAP_ENTRY; - -#define LOADED_IMAGE_PRIVATE_DATA_SIGNATURE SIGNATURE_32('l','d','r','i') +#define LOADED_IMAGE_PRIVATE_DATA_SIGNATURE SIGNATURE_32('l','d','r','i') typedef struct { - UINTN Signature; + UINTN Signature; /// Image handle - EFI_HANDLE Handle; + EFI_HANDLE Handle; /// Image type - UINTN Type; + UINTN Type; /// If entrypoint has been called - BOOLEAN Started; + BOOLEAN Started; /// The image's entry point - EFI_IMAGE_ENTRY_POINT EntryPoint; + EFI_IMAGE_ENTRY_POINT EntryPoint; /// loaded image protocol - EFI_LOADED_IMAGE_PROTOCOL Info; + EFI_LOADED_IMAGE_PROTOCOL Info; /// Location in memory - EFI_PHYSICAL_ADDRESS ImageBasePage; + EFI_PHYSICAL_ADDRESS ImageBasePage; /// Number of pages - UINTN NumberOfPages; + UINTN NumberOfPages; /// Original fixup data - CHAR8 *FixupData; + CHAR8 *FixupData; /// Tpl of started image - EFI_TPL Tpl; + EFI_TPL Tpl; /// Status returned by started image - EFI_STATUS Status; + EFI_STATUS Status; /// Size of ExitData from started image - UINTN ExitDataSize; + UINTN ExitDataSize; /// Pointer to exit data from started image - VOID *ExitData; + VOID *ExitData; /// Pointer to pool allocation for context save/restore - VOID *JumpBuffer; + VOID *JumpBuffer; /// Pointer to buffer for context save/restore - BASE_LIBRARY_JUMP_BUFFER *JumpContext; + BASE_LIBRARY_JUMP_BUFFER *JumpContext; /// Machine type from PE image - UINT16 Machine; + UINT16 Machine; /// PE/COFF Image Emulator Protocol pointer - EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *PeCoffEmu; + EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *PeCoffEmu; /// Runtime image list - EFI_RUNTIME_IMAGE_ENTRY *RuntimeData; + EFI_RUNTIME_IMAGE_ENTRY *RuntimeData; /// Pointer to Loaded Image Device Path Protocol - EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath; + EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath; /// PeCoffLoader ImageContext - PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; + PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; /// Status returned by LoadImage() service. - EFI_STATUS LoadImageStatus; + EFI_STATUS LoadImageStatus; } LOADED_IMAGE_PRIVATE_DATA; #define LOADED_IMAGE_PRIVATE_DATA_FROM_THIS(a) \ CR(a, LOADED_IMAGE_PRIVATE_DATA, Info, LOADED_IMAGE_PRIVATE_DATA_SIGNATURE) -#define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE SIGNATURE_32 ('I','P','R','C') +#define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE SIGNATURE_32 ('I','P','R','C') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_PHYSICAL_ADDRESS CodeSegmentBase; - UINT64 CodeSegmentSize; + UINT32 Signature; + LIST_ENTRY Link; + EFI_PHYSICAL_ADDRESS CodeSegmentBase; + UINT64 CodeSegmentSize; } IMAGE_PROPERTIES_RECORD_CODE_SECTION; -#define IMAGE_PROPERTIES_RECORD_SIGNATURE SIGNATURE_32 ('I','P','R','D') +#define IMAGE_PROPERTIES_RECORD_SIGNATURE SIGNATURE_32 ('I','P','R','D') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_PHYSICAL_ADDRESS ImageBase; - UINT64 ImageSize; - UINTN CodeSegmentCount; - LIST_ENTRY CodeSegmentList; + UINT32 Signature; + LIST_ENTRY Link; + EFI_PHYSICAL_ADDRESS ImageBase; + UINT64 ImageSize; + UINTN CodeSegmentCount; + LIST_ENTRY CodeSegmentList; } IMAGE_PROPERTIES_RECORD; // // DXE Core Global Variables // -extern EFI_SYSTEM_TABLE *gDxeCoreST; -extern EFI_RUNTIME_SERVICES *gDxeCoreRT; -extern EFI_DXE_SERVICES *gDxeCoreDS; -extern EFI_HANDLE gDxeCoreImageHandle; +extern EFI_SYSTEM_TABLE *gDxeCoreST; +extern EFI_RUNTIME_SERVICES *gDxeCoreRT; +extern EFI_DXE_SERVICES *gDxeCoreDS; +extern EFI_HANDLE gDxeCoreImageHandle; -extern BOOLEAN gMemoryMapTerminated; +extern BOOLEAN gMemoryMapTerminated; -extern EFI_DECOMPRESS_PROTOCOL gEfiDecompress; +extern EFI_DECOMPRESS_PROTOCOL gEfiDecompress; -extern EFI_RUNTIME_ARCH_PROTOCOL *gRuntime; -extern EFI_CPU_ARCH_PROTOCOL *gCpu; -extern EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *gWatchdogTimer; -extern EFI_METRONOME_ARCH_PROTOCOL *gMetronome; -extern EFI_TIMER_ARCH_PROTOCOL *gTimer; -extern EFI_SECURITY_ARCH_PROTOCOL *gSecurity; -extern EFI_SECURITY2_ARCH_PROTOCOL *gSecurity2; -extern EFI_BDS_ARCH_PROTOCOL *gBds; -extern EFI_SMM_BASE2_PROTOCOL *gSmmBase2; +extern EFI_RUNTIME_ARCH_PROTOCOL *gRuntime; +extern EFI_CPU_ARCH_PROTOCOL *gCpu; +extern EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *gWatchdogTimer; +extern EFI_METRONOME_ARCH_PROTOCOL *gMetronome; +extern EFI_TIMER_ARCH_PROTOCOL *gTimer; +extern EFI_SECURITY_ARCH_PROTOCOL *gSecurity; +extern EFI_SECURITY2_ARCH_PROTOCOL *gSecurity2; +extern EFI_BDS_ARCH_PROTOCOL *gBds; +extern EFI_SMM_BASE2_PROTOCOL *gSmmBase2; -extern EFI_TPL gEfiCurrentTpl; +extern EFI_TPL gEfiCurrentTpl; -extern EFI_GUID *gDxeCoreFileName; -extern EFI_LOADED_IMAGE_PROTOCOL *gDxeCoreLoadedImage; +extern EFI_GUID *gDxeCoreFileName; +extern EFI_LOADED_IMAGE_PROTOCOL *gDxeCoreLoadedImage; -extern EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1]; +extern EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1]; -extern BOOLEAN gDispatcherRunning; -extern EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate; +extern BOOLEAN gDispatcherRunning; +extern EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate; -extern EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable; -extern BOOLEAN gLoadFixedAddressCodeMemoryReady; +extern EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable; +extern BOOLEAN gLoadFixedAddressCodeMemoryReady; // // Service Initialization Functions // - - /** Called to initialize the pool. @@ -304,7 +295,6 @@ CoreInitializePool ( VOID ); - /** Called to initialize the memory map and add descriptors to the current descriptor list. @@ -328,7 +318,6 @@ CoreAddMemoryDescriptor ( IN UINT64 Attribute ); - /** Release memory lock on mGcdMemorySpaceLock. @@ -338,7 +327,6 @@ CoreReleaseGcdMemoryLock ( VOID ); - /** Acquire memory lock on mGcdMemorySpaceLock. @@ -348,7 +336,6 @@ CoreAcquireGcdMemoryLock ( VOID ); - /** External function. Initializes memory services based on the memory descriptor HOBs. This function is responsible for priming the memory @@ -371,8 +358,6 @@ CoreInitializeMemoryServices ( OUT UINT64 *MemoryLength ); - - /** External function. Initializes the GCD and memory services based on the memory descriptor HOBs. This function is responsible for priming the GCD map and the @@ -394,7 +379,6 @@ CoreInitializeGcdServices ( IN UINT64 MemoryLength ); - /** Initializes "event" support. @@ -406,7 +390,6 @@ CoreInitializeEventServices ( VOID ); - /** Add the Image Services to EFI Boot Services Table and install the protocol interfaces for this image. @@ -418,10 +401,9 @@ CoreInitializeEventServices ( **/ EFI_STATUS CoreInitializeImageServices ( - IN VOID *HobStart + IN VOID *HobStart ); - /** Creates an event that is fired everytime a Protocol of a specific type is installed. @@ -431,7 +413,6 @@ CoreNotifyOnProtocolInstallation ( VOID ); - /** Return TRUE if all AP services are available. @@ -444,7 +425,6 @@ CoreAllEfiServicesAvailable ( VOID ); - /** Calcualte the 32-bit CRC in a EFI table using the service provided by the gRuntime service. @@ -454,10 +434,9 @@ CoreAllEfiServicesAvailable ( **/ VOID CalculateEfiHdrCrc ( - IN OUT EFI_TABLE_HEADER *Hdr + IN OUT EFI_TABLE_HEADER *Hdr ); - /** Called by the platform code to process a tick. @@ -468,10 +447,9 @@ CalculateEfiHdrCrc ( VOID EFIAPI CoreTimerTick ( - IN UINT64 Duration + IN UINT64 Duration ); - /** Initialize the dispatcher. Initialize the notification function that runs when an FV2 protocol is added to the system. @@ -482,7 +460,6 @@ CoreInitializeDispatcher ( VOID ); - /** This is the POSTFIX version of the dependency evaluator. This code does not need to handle Before or After, as it is not valid to call this @@ -498,10 +475,9 @@ CoreInitializeDispatcher ( **/ BOOLEAN CoreIsSchedulable ( - IN EFI_CORE_DRIVER_ENTRY *DriverEntry + IN EFI_CORE_DRIVER_ENTRY *DriverEntry ); - /** Preprocess dependency expression and update DriverEntry to reflect the state of Before, After, and SOR dependencies. If DriverEntry->Before @@ -516,11 +492,9 @@ CoreIsSchedulable ( **/ EFI_STATUS CorePreProcessDepex ( - IN EFI_CORE_DRIVER_ENTRY *DriverEntry + IN EFI_CORE_DRIVER_ENTRY *DriverEntry ); - - /** Terminates all boot services. @@ -534,11 +508,10 @@ CorePreProcessDepex ( EFI_STATUS EFIAPI CoreExitBootServices ( - IN EFI_HANDLE ImageHandle, - IN UINTN MapKey + IN EFI_HANDLE ImageHandle, + IN UINTN MapKey ); - /** Make sure the memory map is following all the construction rules, it is the last time to check memory map error before exit boot services. @@ -552,10 +525,9 @@ CoreExitBootServices ( **/ EFI_STATUS CoreTerminateMemoryMap ( - IN UINTN MapKey + IN UINTN MapKey ); - /** Signals all events in the EventGroup. @@ -564,11 +536,9 @@ CoreTerminateMemoryMap ( **/ VOID CoreNotifySignalList ( - IN EFI_GUID *EventGroup + IN EFI_GUID *EventGroup ); - - /** Boot Service called to add, modify, or remove a system configuration table from the EFI System Table. @@ -587,12 +557,10 @@ CoreNotifySignalList ( EFI_STATUS EFIAPI CoreInstallConfigurationTable ( - IN EFI_GUID *Guid, - IN VOID *Table + IN EFI_GUID *Guid, + IN VOID *Table ); - - /** Raise the task priority level to the new level. High level is implemented by disabling processor interrupts. @@ -605,11 +573,9 @@ CoreInstallConfigurationTable ( EFI_TPL EFIAPI CoreRaiseTpl ( - IN EFI_TPL NewTpl + IN EFI_TPL NewTpl ); - - /** Lowers the task priority to the previous value. If the new priority unmasks events at a higher priority, they are dispatched. @@ -620,11 +586,9 @@ CoreRaiseTpl ( VOID EFIAPI CoreRestoreTpl ( - IN EFI_TPL NewTpl + IN EFI_TPL NewTpl ); - - /** Introduces a fine-grained stall. @@ -638,11 +602,9 @@ CoreRestoreTpl ( EFI_STATUS EFIAPI CoreStall ( - IN UINTN Microseconds + IN UINTN Microseconds ); - - /** Sets the system's watchdog timer. @@ -668,14 +630,12 @@ CoreStall ( EFI_STATUS EFIAPI CoreSetWatchdogTimer ( - IN UINTN Timeout, - IN UINT64 WatchdogCode, - IN UINTN DataSize, - IN CHAR16 *WatchdogData OPTIONAL + IN UINTN Timeout, + IN UINT64 WatchdogCode, + IN UINTN DataSize, + IN CHAR16 *WatchdogData OPTIONAL ); - - /** Wrapper function to CoreInstallProtocolInterfaceNotify. This is the public API which Calls the private one which contains a BOOLEAN parameter for notifications @@ -693,13 +653,12 @@ CoreSetWatchdogTimer ( EFI_STATUS EFIAPI CoreInstallProtocolInterface ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface ); - /** Installs a protocol interface into the boot services environment. @@ -719,15 +678,13 @@ CoreInstallProtocolInterface ( **/ EFI_STATUS CoreInstallProtocolInterfaceNotify ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface, - IN BOOLEAN Notify + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface, + IN BOOLEAN Notify ); - - /** Installs a list of protocol interface into the boot services environment. This function calls InstallProtocolInterface() in a loop. If any error @@ -752,12 +709,10 @@ CoreInstallProtocolInterfaceNotify ( EFI_STATUS EFIAPI CoreInstallMultipleProtocolInterfaces ( - IN OUT EFI_HANDLE *Handle, + IN OUT EFI_HANDLE *Handle, ... ); - - /** Uninstalls a list of protocol interface in the boot services environment. This function calls UnisatllProtocolInterface() in a loop. This is @@ -775,12 +730,10 @@ CoreInstallMultipleProtocolInterfaces ( EFI_STATUS EFIAPI CoreUninstallMultipleProtocolInterfaces ( - IN EFI_HANDLE Handle, + IN EFI_HANDLE Handle, ... ); - - /** Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. @@ -798,14 +751,12 @@ CoreUninstallMultipleProtocolInterfaces ( EFI_STATUS EFIAPI CoreReinstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *OldInterface, - IN VOID *NewInterface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *OldInterface, + IN VOID *NewInterface ); - - /** Uninstalls all instances of a protocol:interfacer from a handle. If the last protocol interface is remove from the handle, the @@ -822,13 +773,11 @@ CoreReinstallProtocolInterface ( EFI_STATUS EFIAPI CoreUninstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); - - /** Queries a handle to determine if it supports a specified protocol. @@ -843,13 +792,11 @@ CoreUninstallProtocolInterface ( EFI_STATUS EFIAPI CoreHandleProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface ); - - /** Locates the installed protocol handler for the handle, and invokes it to obtain the protocol interface. Usage information @@ -873,16 +820,14 @@ CoreHandleProtocol ( EFI_STATUS EFIAPI CoreOpenProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface OPTIONAL, - IN EFI_HANDLE ImageHandle, - IN EFI_HANDLE ControllerHandle, - IN UINT32 Attributes + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface OPTIONAL, + IN EFI_HANDLE ImageHandle, + IN EFI_HANDLE ControllerHandle, + IN UINT32 Attributes ); - - /** Return information about Opened protocols in the system @@ -897,14 +842,12 @@ CoreOpenProtocol ( EFI_STATUS EFIAPI CoreOpenProtocolInformation ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, - OUT UINTN *EntryCount + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, + OUT UINTN *EntryCount ); - - /** Closes a protocol on a handle that was opened using OpenProtocol(). @@ -933,14 +876,12 @@ CoreOpenProtocolInformation ( EFI_STATUS EFIAPI CoreCloseProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN EFI_HANDLE AgentHandle, - IN EFI_HANDLE ControllerHandle + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN EFI_HANDLE AgentHandle, + IN EFI_HANDLE ControllerHandle ); - - /** Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated from pool. @@ -967,13 +908,11 @@ CoreCloseProtocol ( EFI_STATUS EFIAPI CoreProtocolsPerHandle ( - IN EFI_HANDLE UserHandle, - OUT EFI_GUID ***ProtocolBuffer, - OUT UINTN *ProtocolBufferCount + IN EFI_HANDLE UserHandle, + OUT EFI_GUID ***ProtocolBuffer, + OUT UINTN *ProtocolBufferCount ); - - /** Add a new protocol notification record for the request protocol. @@ -990,12 +929,11 @@ CoreProtocolsPerHandle ( EFI_STATUS EFIAPI CoreRegisterProtocolNotify ( - IN EFI_GUID *Protocol, - IN EFI_EVENT Event, - OUT VOID **Registration + IN EFI_GUID *Protocol, + IN EFI_EVENT Event, + OUT VOID **Registration ); - /** Removes all the events in the protocol database that match Event. @@ -1007,10 +945,9 @@ CoreRegisterProtocolNotify ( **/ EFI_STATUS CoreUnregisterProtocolNotify ( - IN EFI_EVENT Event + IN EFI_EVENT Event ); - /** Locates the requested handle(s) and returns them in Buffer. @@ -1032,15 +969,13 @@ CoreUnregisterProtocolNotify ( EFI_STATUS EFIAPI CoreLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer ); - - /** Locates the handle to a device on the device path that best matches the specified protocol. @@ -1059,13 +994,11 @@ CoreLocateHandle ( EFI_STATUS EFIAPI CoreLocateDevicePath ( - IN EFI_GUID *Protocol, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, - OUT EFI_HANDLE *Device + IN EFI_GUID *Protocol, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, + OUT EFI_HANDLE *Device ); - - /** Function returns an array of handles that support the requested protocol in a buffer allocated from pool. This is a version of CoreLocateHandle() @@ -1091,15 +1024,13 @@ CoreLocateDevicePath ( EFI_STATUS EFIAPI CoreLocateHandleBuffer ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *NumberHandles, - OUT EFI_HANDLE **Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *NumberHandles, + OUT EFI_HANDLE **Buffer ); - - /** Return the first Protocol Interface that matches the Protocol GUID. If Registration is passed in, return a Protocol Instance that was just add @@ -1124,7 +1055,6 @@ CoreLocateProtocol ( OUT VOID **Interface ); - /** return handle database key. @@ -1137,7 +1067,6 @@ CoreGetHandleDatabaseKey ( VOID ); - /** Go connect any handles that were created or modified while a image executed. @@ -1150,8 +1079,6 @@ CoreConnectHandlesByKey ( UINT64 Key ); - - /** Connects one or more drivers to a controller. @@ -1187,8 +1114,6 @@ CoreConnectController ( IN BOOLEAN Recursive ); - - /** Disonnects a controller from a driver @@ -1229,8 +1154,6 @@ CoreDisconnectController ( IN EFI_HANDLE ChildHandle OPTIONAL ); - - /** Allocates pages from the memory map. @@ -1252,9 +1175,9 @@ CoreDisconnectController ( EFI_STATUS EFIAPI CoreAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, IN OUT EFI_PHYSICAL_ADDRESS *Memory ); @@ -1272,8 +1195,8 @@ CoreAllocatePages ( EFI_STATUS EFIAPI CoreFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -1316,8 +1239,6 @@ CoreGetMemoryMap ( OUT UINT32 *DescriptorVersion ); - - /** Allocate pool of a particular type. @@ -1372,7 +1293,7 @@ CoreInternalAllocatePool ( EFI_STATUS EFIAPI CoreFreePool ( - IN VOID *Buffer + IN VOID *Buffer ); /** @@ -1388,8 +1309,8 @@ CoreFreePool ( EFI_STATUS EFIAPI CoreInternalFreePool ( - IN VOID *Buffer, - OUT EFI_MEMORY_TYPE *PoolType OPTIONAL + IN VOID *Buffer, + OUT EFI_MEMORY_TYPE *PoolType OPTIONAL ); /** @@ -1429,16 +1350,14 @@ CoreInternalFreePool ( EFI_STATUS EFIAPI CoreLoadImage ( - IN BOOLEAN BootPolicy, - IN EFI_HANDLE ParentImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN VOID *SourceBuffer OPTIONAL, - IN UINTN SourceSize, - OUT EFI_HANDLE *ImageHandle + IN BOOLEAN BootPolicy, + IN EFI_HANDLE ParentImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN VOID *SourceBuffer OPTIONAL, + IN UINTN SourceSize, + OUT EFI_HANDLE *ImageHandle ); - - /** Unloads an image. @@ -1457,8 +1376,6 @@ CoreUnloadImage ( IN EFI_HANDLE ImageHandle ); - - /** Transfer control to a loaded image's entry point. @@ -1486,8 +1403,6 @@ CoreStartImage ( OUT CHAR16 **ExitData OPTIONAL ); - - /** Terminates the currently loaded EFI image and returns control to boot services. @@ -1520,8 +1435,6 @@ CoreExit ( IN CHAR16 *ExitData OPTIONAL ); - - /** Creates an event. @@ -1543,15 +1456,13 @@ CoreExit ( EFI_STATUS EFIAPI CoreCreateEvent ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN VOID *NotifyContext OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN VOID *NotifyContext OPTIONAL, + OUT EFI_EVENT *Event ); - - /** Creates an event in a group. @@ -1575,12 +1486,12 @@ CoreCreateEvent ( EFI_STATUS EFIAPI CoreCreateEventEx ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN CONST VOID *NotifyContext OPTIONAL, - IN CONST EFI_GUID *EventGroup OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN CONST VOID *NotifyContext OPTIONAL, + IN CONST EFI_GUID *EventGroup OPTIONAL, + OUT EFI_EVENT *Event ); /** @@ -1606,12 +1517,12 @@ CoreCreateEventEx ( EFI_STATUS EFIAPI CoreCreateEventInternal ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN CONST VOID *NotifyContext OPTIONAL, - IN CONST EFI_GUID *EventGroup OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN CONST VOID *NotifyContext OPTIONAL, + IN CONST EFI_GUID *EventGroup OPTIONAL, + OUT EFI_EVENT *Event ); /** @@ -1632,13 +1543,11 @@ CoreCreateEventInternal ( EFI_STATUS EFIAPI CoreSetTimer ( - IN EFI_EVENT UserEvent, - IN EFI_TIMER_DELAY Type, - IN UINT64 TriggerTime + IN EFI_EVENT UserEvent, + IN EFI_TIMER_DELAY Type, + IN UINT64 TriggerTime ); - - /** Signals the event. Queues the event to be notified if needed. @@ -1651,11 +1560,9 @@ CoreSetTimer ( EFI_STATUS EFIAPI CoreSignalEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ); - - /** Stops execution until an event is signaled. @@ -1673,13 +1580,11 @@ CoreSignalEvent ( EFI_STATUS EFIAPI CoreWaitForEvent ( - IN UINTN NumberOfEvents, - IN EFI_EVENT *UserEvents, - OUT UINTN *UserIndex + IN UINTN NumberOfEvents, + IN EFI_EVENT *UserEvents, + OUT UINTN *UserIndex ); - - /** Closes an event and frees the event structure. @@ -1692,11 +1597,9 @@ CoreWaitForEvent ( EFI_STATUS EFIAPI CoreCloseEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ); - - /** Check the status of an event. @@ -1710,10 +1613,9 @@ CoreCloseEvent ( EFI_STATUS EFIAPI CoreCheckEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ); - /** Adds reserved memory, system memory, or memory-mapped I/O resources to the global coherency domain of the processor. @@ -1735,7 +1637,6 @@ CoreAddMemorySpace ( IN UINT64 Capabilities ); - /** Allocates nonexistent memory, reserved memory, system memory, or memorymapped I/O resources from the global coherency domain of the processor. @@ -1765,7 +1666,6 @@ CoreAllocateMemorySpace ( IN EFI_HANDLE DeviceHandle OPTIONAL ); - /** Frees nonexistent memory, reserved memory, system memory, or memory-mapped I/O resources from the global coherency domain of the processor. @@ -1783,7 +1683,6 @@ CoreFreeMemorySpace ( IN UINT64 Length ); - /** Removes reserved memory, system memory, or memory-mapped I/O resources from the global coherency domain of the processor. @@ -1801,7 +1700,6 @@ CoreRemoveMemorySpace ( IN UINT64 Length ); - /** Retrieves the descriptor for a memory region containing a specified address. @@ -1819,7 +1717,6 @@ CoreGetMemorySpaceDescriptor ( OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Descriptor ); - /** Modifies the attributes for a memory region in the global coherency domain of the processor. @@ -1850,7 +1747,6 @@ CoreSetMemorySpaceAttributes ( IN UINT64 Attributes ); - /** Modifies the capabilities for a memory region in the global coherency domain of the processor. @@ -1876,7 +1772,6 @@ CoreSetMemorySpaceCapabilities ( IN UINT64 Capabilities ); - /** Returns a map of the memory resources in the global coherency domain of the processor. @@ -1896,7 +1791,6 @@ CoreGetMemorySpaceMap ( OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR **MemorySpaceMap ); - /** Adds reserved I/O or I/O resources to the global coherency domain of the processor. @@ -1916,7 +1810,6 @@ CoreAddIoSpace ( IN UINT64 Length ); - /** Allocates nonexistent I/O, reserved I/O, or I/O resources from the global coherency domain of the processor. @@ -1946,7 +1839,6 @@ CoreAllocateIoSpace ( IN EFI_HANDLE DeviceHandle OPTIONAL ); - /** Frees nonexistent I/O, reserved I/O, or I/O resources from the global coherency domain of the processor. @@ -1964,7 +1856,6 @@ CoreFreeIoSpace ( IN UINT64 Length ); - /** Removes reserved I/O or I/O resources from the global coherency domain of the processor. @@ -1982,7 +1873,6 @@ CoreRemoveIoSpace ( IN UINT64 Length ); - /** Retrieves the descriptor for an I/O region containing a specified address. @@ -2000,7 +1890,6 @@ CoreGetIoSpaceDescriptor ( OUT EFI_GCD_IO_SPACE_DESCRIPTOR *Descriptor ); - /** Returns a map of the I/O resources in the global coherency domain of the processor. @@ -2019,7 +1908,6 @@ CoreGetIoSpaceMap ( OUT EFI_GCD_IO_SPACE_DESCRIPTOR **IoSpaceMap ); - /** This is the main Dispatcher for DXE and it exits when there are no more drivers to run. Drain the mScheduledQueue and load and start a PE @@ -2061,7 +1949,6 @@ CoreSchedule ( IN EFI_GUID *DriverName ); - /** Convert a driver from the Untrused back to the Scheduled state. @@ -2081,7 +1968,6 @@ CoreTrust ( IN EFI_GUID *DriverName ); - /** This routine is the driver initialization entry point. It initializes the libraries, and registers two notification functions. These notification @@ -2096,11 +1982,10 @@ CoreTrust ( EFI_STATUS EFIAPI FwVolDriverInit ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); - /** Entry point of the section extraction code. Initializes an instance of the section extraction interface and installs it on a new handle. @@ -2115,11 +2000,10 @@ FwVolDriverInit ( EFI_STATUS EFIAPI InitializeSectionExtraction ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); - /** This DXE service routine is used to process a firmware volume. In particular, it can be called by BDS to process a single firmware @@ -2140,13 +2024,13 @@ InitializeSectionExtraction ( EFI_STATUS EFIAPI CoreProcessFirmwareVolume ( - IN VOID *FvHeader, - IN UINTN Size, - OUT EFI_HANDLE *FVProtocolHandle + IN VOID *FvHeader, + IN UINTN Size, + OUT EFI_HANDLE *FVProtocolHandle ); // -//Functions used during debug buils +// Functions used during debug buils // /** @@ -2159,7 +2043,6 @@ CoreDisplayMissingArchProtocols ( VOID ); - /** Traverse the discovered list for any drivers that were discovered but not loaded because the dependency experessions evaluated to false. @@ -2170,8 +2053,6 @@ CoreDisplayDiscoveredNotDispatched ( VOID ); - - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -2184,10 +2065,9 @@ CoreDisplayDiscoveredNotDispatched ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg1 ( - UINTN Arg1 + UINTN Arg1 ); - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -2200,11 +2080,10 @@ CoreEfiNotAvailableYetArg1 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg2 ( - UINTN Arg1, - UINTN Arg2 + UINTN Arg1, + UINTN Arg2 ); - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -2218,12 +2097,11 @@ CoreEfiNotAvailableYetArg2 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg3 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3 ); - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -2238,13 +2116,12 @@ CoreEfiNotAvailableYetArg3 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg4 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4 ); - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -2260,14 +2137,13 @@ CoreEfiNotAvailableYetArg4 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg5 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4, - UINTN Arg5 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4, + UINTN Arg5 ); - /** Given a compressed source buffer, this function retrieves the size of the uncompressed buffer and the size of the scratch buffer required to decompress @@ -2310,14 +2186,13 @@ CoreEfiNotAvailableYetArg5 ( EFI_STATUS EFIAPI DxeMainUefiDecompressGetInfo ( - IN EFI_DECOMPRESS_PROTOCOL *This, - IN VOID *Source, - IN UINT32 SourceSize, - OUT UINT32 *DestinationSize, - OUT UINT32 *ScratchSize + IN EFI_DECOMPRESS_PROTOCOL *This, + IN VOID *Source, + IN UINT32 SourceSize, + OUT UINT32 *DestinationSize, + OUT UINT32 *ScratchSize ); - /** Decompresses a compressed source buffer. @@ -2355,13 +2230,13 @@ DxeMainUefiDecompressGetInfo ( EFI_STATUS EFIAPI DxeMainUefiDecompress ( - IN EFI_DECOMPRESS_PROTOCOL *This, - IN VOID *Source, - IN UINT32 SourceSize, - IN OUT VOID *Destination, - IN UINT32 DestinationSize, - IN OUT VOID *Scratch, - IN UINT32 ScratchSize + IN EFI_DECOMPRESS_PROTOCOL *This, + IN VOID *Source, + IN UINT32 SourceSize, + IN OUT VOID *Destination, + IN UINT32 DestinationSize, + IN OUT VOID *Scratch, + IN UINT32 ScratchSize ); /** @@ -2382,13 +2257,11 @@ DxeMainUefiDecompress ( EFI_STATUS EFIAPI OpenSectionStream ( - IN UINTN SectionStreamLength, - IN VOID *SectionStream, - OUT UINTN *SectionStreamHandle + IN UINTN SectionStreamLength, + IN VOID *SectionStream, + OUT UINTN *SectionStreamHandle ); - - /** SEP member function. Retrieves requested section from section stream. @@ -2450,17 +2323,16 @@ OpenSectionStream ( EFI_STATUS EFIAPI GetSection ( - IN UINTN SectionStreamHandle, - IN EFI_SECTION_TYPE *SectionType, - IN EFI_GUID *SectionDefinitionGuid, - IN UINTN SectionInstance, - IN VOID **Buffer, - IN OUT UINTN *BufferSize, - OUT UINT32 *AuthenticationStatus, - IN BOOLEAN IsFfs3Fv + IN UINTN SectionStreamHandle, + IN EFI_SECTION_TYPE *SectionType, + IN EFI_GUID *SectionDefinitionGuid, + IN UINTN SectionInstance, + IN VOID **Buffer, + IN OUT UINTN *BufferSize, + OUT UINT32 *AuthenticationStatus, + IN BOOLEAN IsFfs3Fv ); - /** SEP member function. Deletes an existing section stream @@ -2477,8 +2349,8 @@ GetSection ( EFI_STATUS EFIAPI CloseSectionStream ( - IN UINTN StreamHandleToClose, - IN BOOLEAN FreeStreamBuffer + IN UINTN StreamHandleToClose, + IN BOOLEAN FreeStreamBuffer ); /** @@ -2497,7 +2369,6 @@ CoreInitializeDebugImageInfoTable ( VOID ); - /** Update the CRC32 in the Debug Table. Since the CRC32 service is made available by the Runtime driver, we have to @@ -2511,7 +2382,6 @@ CoreUpdateDebugTableCrc32 ( VOID ); - /** Adds a new DebugImageInfo structure to the DebugImageInfo Table. Re-Allocates the table if it's not large enough to accomidate another entry. @@ -2524,12 +2394,11 @@ CoreUpdateDebugTableCrc32 ( **/ VOID CoreNewDebugImageInfoEntry ( - IN UINT32 ImageInfoType, - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_HANDLE ImageHandle + IN UINT32 ImageInfoType, + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_HANDLE ImageHandle ); - /** Removes and frees an entry from the DebugImageInfo Table. @@ -2538,10 +2407,9 @@ CoreNewDebugImageInfoEntry ( **/ VOID CoreRemoveDebugImageInfoEntry ( - EFI_HANDLE ImageHandle + EFI_HANDLE ImageHandle ); - /** This routine consumes FV hobs and produces instances of FW_VOL_BLOCK_PROTOCOL as appropriate. @@ -2555,8 +2423,8 @@ CoreRemoveDebugImageInfoEntry ( EFI_STATUS EFIAPI FwVolBlockDriverInit ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); /** @@ -2570,7 +2438,7 @@ FwVolBlockDriverInit ( **/ UINT32 GetFvbAuthenticationStatus ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol ); /** @@ -2594,14 +2462,13 @@ GetFvbAuthenticationStatus ( **/ EFI_STATUS ProduceFVBProtocolOnBuffer ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN EFI_HANDLE ParentHandle, - IN UINT32 AuthenticationStatus, - OUT EFI_HANDLE *FvProtocol OPTIONAL + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN EFI_HANDLE ParentHandle, + IN UINT32 AuthenticationStatus, + OUT EFI_HANDLE *FvProtocol OPTIONAL ); - /** Raising to the task priority level of the mutual exclusion lock, and then acquires ownership of the lock. @@ -2616,7 +2483,6 @@ CoreAcquireLock ( IN EFI_LOCK *Lock ); - /** Initialize a basic mutual exclusion lock. Each lock provides mutual exclusion access at it's task priority @@ -2635,7 +2501,6 @@ CoreAcquireLockOrFail ( IN EFI_LOCK *Lock ); - /** Releases ownership of the mutual exclusion lock, and restores the previous task priority level. @@ -2669,11 +2534,11 @@ CoreReleaseLock ( **/ EFI_STATUS ReadFvbData ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, - IN OUT EFI_LBA *StartLba, - IN OUT UINTN *Offset, - IN UINTN DataSize, - OUT UINT8 *Data + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, + IN OUT EFI_LBA *StartLba, + IN OUT UINTN *Offset, + IN UINTN DataSize, + OUT UINT8 *Data ); /** @@ -2694,8 +2559,8 @@ ReadFvbData ( **/ EFI_STATUS GetFwVolHeader ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, - OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, + OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader ); /** @@ -2709,7 +2574,7 @@ GetFwVolHeader ( **/ BOOLEAN VerifyFvHeaderChecksum ( - IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader ); /** @@ -2720,7 +2585,7 @@ VerifyFvHeaderChecksum ( **/ VOID MemoryProfileInit ( - IN VOID *HobStart + IN VOID *HobStart ); /** @@ -2840,7 +2705,7 @@ CoreInitializeMemoryProtection ( **/ VOID InstallMemoryAttributesTableOnMemoryAllocation ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ); /** @@ -2871,8 +2736,8 @@ RemoveImageRecord ( **/ VOID ProtectUefiImage ( - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath ); /** @@ -2883,8 +2748,8 @@ ProtectUefiImage ( **/ VOID UnprotectUefiImage ( - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath ); /** diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c index db21311f93..2c27fc0695 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c +++ b/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c @@ -11,7 +11,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // DXE Core Global Variables for Protocols from PEI // -EFI_HANDLE mDecompressHandle = NULL; +EFI_HANDLE mDecompressHandle = NULL; // // DXE Core globals for Architecture Protocols @@ -27,18 +27,18 @@ EFI_WATCHDOG_TIMER_ARCH_PROTOCOL *gWatchdogTimer = NULL; // // DXE Core globals for optional protocol dependencies // -EFI_SMM_BASE2_PROTOCOL *gSmmBase2 = NULL; +EFI_SMM_BASE2_PROTOCOL *gSmmBase2 = NULL; // // DXE Core Global used to update core loaded image protocol handle // -EFI_GUID *gDxeCoreFileName; -EFI_LOADED_IMAGE_PROTOCOL *gDxeCoreLoadedImage; +EFI_GUID *gDxeCoreFileName; +EFI_LOADED_IMAGE_PROTOCOL *gDxeCoreLoadedImage; // // DXE Core Module Variables // -EFI_BOOT_SERVICES mBootServices = { +EFI_BOOT_SERVICES mBootServices = { { EFI_BOOT_SERVICES_SIGNATURE, // Signature EFI_BOOT_SERVICES_REVISION, // Revision @@ -46,81 +46,81 @@ EFI_BOOT_SERVICES mBootServices = { 0, // CRC32 0 // Reserved }, - (EFI_RAISE_TPL) CoreRaiseTpl, // RaiseTPL - (EFI_RESTORE_TPL) CoreRestoreTpl, // RestoreTPL - (EFI_ALLOCATE_PAGES) CoreAllocatePages, // AllocatePages - (EFI_FREE_PAGES) CoreFreePages, // FreePages - (EFI_GET_MEMORY_MAP) CoreGetMemoryMap, // GetMemoryMap - (EFI_ALLOCATE_POOL) CoreAllocatePool, // AllocatePool - (EFI_FREE_POOL) CoreFreePool, // FreePool - (EFI_CREATE_EVENT) CoreCreateEvent, // CreateEvent - (EFI_SET_TIMER) CoreSetTimer, // SetTimer - (EFI_WAIT_FOR_EVENT) CoreWaitForEvent, // WaitForEvent - (EFI_SIGNAL_EVENT) CoreSignalEvent, // SignalEvent - (EFI_CLOSE_EVENT) CoreCloseEvent, // CloseEvent - (EFI_CHECK_EVENT) CoreCheckEvent, // CheckEvent - (EFI_INSTALL_PROTOCOL_INTERFACE) CoreInstallProtocolInterface, // InstallProtocolInterface - (EFI_REINSTALL_PROTOCOL_INTERFACE) CoreReinstallProtocolInterface, // ReinstallProtocolInterface - (EFI_UNINSTALL_PROTOCOL_INTERFACE) CoreUninstallProtocolInterface, // UninstallProtocolInterface - (EFI_HANDLE_PROTOCOL) CoreHandleProtocol, // HandleProtocol - (VOID *) NULL, // Reserved - (EFI_REGISTER_PROTOCOL_NOTIFY) CoreRegisterProtocolNotify, // RegisterProtocolNotify - (EFI_LOCATE_HANDLE) CoreLocateHandle, // LocateHandle - (EFI_LOCATE_DEVICE_PATH) CoreLocateDevicePath, // LocateDevicePath - (EFI_INSTALL_CONFIGURATION_TABLE) CoreInstallConfigurationTable, // InstallConfigurationTable - (EFI_IMAGE_LOAD) CoreLoadImage, // LoadImage - (EFI_IMAGE_START) CoreStartImage, // StartImage - (EFI_EXIT) CoreExit, // Exit - (EFI_IMAGE_UNLOAD) CoreUnloadImage, // UnloadImage - (EFI_EXIT_BOOT_SERVICES) CoreExitBootServices, // ExitBootServices - (EFI_GET_NEXT_MONOTONIC_COUNT) CoreEfiNotAvailableYetArg1, // GetNextMonotonicCount - (EFI_STALL) CoreStall, // Stall - (EFI_SET_WATCHDOG_TIMER) CoreSetWatchdogTimer, // SetWatchdogTimer - (EFI_CONNECT_CONTROLLER) CoreConnectController, // ConnectController - (EFI_DISCONNECT_CONTROLLER) CoreDisconnectController, // DisconnectController - (EFI_OPEN_PROTOCOL) CoreOpenProtocol, // OpenProtocol - (EFI_CLOSE_PROTOCOL) CoreCloseProtocol, // CloseProtocol - (EFI_OPEN_PROTOCOL_INFORMATION) CoreOpenProtocolInformation, // OpenProtocolInformation - (EFI_PROTOCOLS_PER_HANDLE) CoreProtocolsPerHandle, // ProtocolsPerHandle - (EFI_LOCATE_HANDLE_BUFFER) CoreLocateHandleBuffer, // LocateHandleBuffer - (EFI_LOCATE_PROTOCOL) CoreLocateProtocol, // LocateProtocol - (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES) CoreInstallMultipleProtocolInterfaces, // InstallMultipleProtocolInterfaces - (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES) CoreUninstallMultipleProtocolInterfaces, // UninstallMultipleProtocolInterfaces - (EFI_CALCULATE_CRC32) CoreEfiNotAvailableYetArg3, // CalculateCrc32 - (EFI_COPY_MEM) CopyMem, // CopyMem - (EFI_SET_MEM) SetMem, // SetMem - (EFI_CREATE_EVENT_EX) CoreCreateEventEx // CreateEventEx + (EFI_RAISE_TPL)CoreRaiseTpl, // RaiseTPL + (EFI_RESTORE_TPL)CoreRestoreTpl, // RestoreTPL + (EFI_ALLOCATE_PAGES)CoreAllocatePages, // AllocatePages + (EFI_FREE_PAGES)CoreFreePages, // FreePages + (EFI_GET_MEMORY_MAP)CoreGetMemoryMap, // GetMemoryMap + (EFI_ALLOCATE_POOL)CoreAllocatePool, // AllocatePool + (EFI_FREE_POOL)CoreFreePool, // FreePool + (EFI_CREATE_EVENT)CoreCreateEvent, // CreateEvent + (EFI_SET_TIMER)CoreSetTimer, // SetTimer + (EFI_WAIT_FOR_EVENT)CoreWaitForEvent, // WaitForEvent + (EFI_SIGNAL_EVENT)CoreSignalEvent, // SignalEvent + (EFI_CLOSE_EVENT)CoreCloseEvent, // CloseEvent + (EFI_CHECK_EVENT)CoreCheckEvent, // CheckEvent + (EFI_INSTALL_PROTOCOL_INTERFACE)CoreInstallProtocolInterface, // InstallProtocolInterface + (EFI_REINSTALL_PROTOCOL_INTERFACE)CoreReinstallProtocolInterface, // ReinstallProtocolInterface + (EFI_UNINSTALL_PROTOCOL_INTERFACE)CoreUninstallProtocolInterface, // UninstallProtocolInterface + (EFI_HANDLE_PROTOCOL)CoreHandleProtocol, // HandleProtocol + (VOID *)NULL, // Reserved + (EFI_REGISTER_PROTOCOL_NOTIFY)CoreRegisterProtocolNotify, // RegisterProtocolNotify + (EFI_LOCATE_HANDLE)CoreLocateHandle, // LocateHandle + (EFI_LOCATE_DEVICE_PATH)CoreLocateDevicePath, // LocateDevicePath + (EFI_INSTALL_CONFIGURATION_TABLE)CoreInstallConfigurationTable, // InstallConfigurationTable + (EFI_IMAGE_LOAD)CoreLoadImage, // LoadImage + (EFI_IMAGE_START)CoreStartImage, // StartImage + (EFI_EXIT)CoreExit, // Exit + (EFI_IMAGE_UNLOAD)CoreUnloadImage, // UnloadImage + (EFI_EXIT_BOOT_SERVICES)CoreExitBootServices, // ExitBootServices + (EFI_GET_NEXT_MONOTONIC_COUNT)CoreEfiNotAvailableYetArg1, // GetNextMonotonicCount + (EFI_STALL)CoreStall, // Stall + (EFI_SET_WATCHDOG_TIMER)CoreSetWatchdogTimer, // SetWatchdogTimer + (EFI_CONNECT_CONTROLLER)CoreConnectController, // ConnectController + (EFI_DISCONNECT_CONTROLLER)CoreDisconnectController, // DisconnectController + (EFI_OPEN_PROTOCOL)CoreOpenProtocol, // OpenProtocol + (EFI_CLOSE_PROTOCOL)CoreCloseProtocol, // CloseProtocol + (EFI_OPEN_PROTOCOL_INFORMATION)CoreOpenProtocolInformation, // OpenProtocolInformation + (EFI_PROTOCOLS_PER_HANDLE)CoreProtocolsPerHandle, // ProtocolsPerHandle + (EFI_LOCATE_HANDLE_BUFFER)CoreLocateHandleBuffer, // LocateHandleBuffer + (EFI_LOCATE_PROTOCOL)CoreLocateProtocol, // LocateProtocol + (EFI_INSTALL_MULTIPLE_PROTOCOL_INTERFACES)CoreInstallMultipleProtocolInterfaces, // InstallMultipleProtocolInterfaces + (EFI_UNINSTALL_MULTIPLE_PROTOCOL_INTERFACES)CoreUninstallMultipleProtocolInterfaces, // UninstallMultipleProtocolInterfaces + (EFI_CALCULATE_CRC32)CoreEfiNotAvailableYetArg3, // CalculateCrc32 + (EFI_COPY_MEM)CopyMem, // CopyMem + (EFI_SET_MEM)SetMem, // SetMem + (EFI_CREATE_EVENT_EX)CoreCreateEventEx // CreateEventEx }; -EFI_DXE_SERVICES mDxeServices = { +EFI_DXE_SERVICES mDxeServices = { { DXE_SERVICES_SIGNATURE, // Signature DXE_SERVICES_REVISION, // Revision sizeof (DXE_SERVICES), // HeaderSize - 0, // CRC32 - 0 // Reserved + 0, // CRC32 + 0 // Reserved }, - (EFI_ADD_MEMORY_SPACE) CoreAddMemorySpace, // AddMemorySpace - (EFI_ALLOCATE_MEMORY_SPACE) CoreAllocateMemorySpace, // AllocateMemorySpace - (EFI_FREE_MEMORY_SPACE) CoreFreeMemorySpace, // FreeMemorySpace - (EFI_REMOVE_MEMORY_SPACE) CoreRemoveMemorySpace, // RemoveMemorySpace - (EFI_GET_MEMORY_SPACE_DESCRIPTOR) CoreGetMemorySpaceDescriptor, // GetMemorySpaceDescriptor - (EFI_SET_MEMORY_SPACE_ATTRIBUTES) CoreSetMemorySpaceAttributes, // SetMemorySpaceAttributes - (EFI_GET_MEMORY_SPACE_MAP) CoreGetMemorySpaceMap, // GetMemorySpaceMap - (EFI_ADD_IO_SPACE) CoreAddIoSpace, // AddIoSpace - (EFI_ALLOCATE_IO_SPACE) CoreAllocateIoSpace, // AllocateIoSpace - (EFI_FREE_IO_SPACE) CoreFreeIoSpace, // FreeIoSpace - (EFI_REMOVE_IO_SPACE) CoreRemoveIoSpace, // RemoveIoSpace - (EFI_GET_IO_SPACE_DESCRIPTOR) CoreGetIoSpaceDescriptor, // GetIoSpaceDescriptor - (EFI_GET_IO_SPACE_MAP) CoreGetIoSpaceMap, // GetIoSpaceMap - (EFI_DISPATCH) CoreDispatcher, // Dispatch - (EFI_SCHEDULE) CoreSchedule, // Schedule - (EFI_TRUST) CoreTrust, // Trust - (EFI_PROCESS_FIRMWARE_VOLUME) CoreProcessFirmwareVolume, // ProcessFirmwareVolume + (EFI_ADD_MEMORY_SPACE)CoreAddMemorySpace, // AddMemorySpace + (EFI_ALLOCATE_MEMORY_SPACE)CoreAllocateMemorySpace, // AllocateMemorySpace + (EFI_FREE_MEMORY_SPACE)CoreFreeMemorySpace, // FreeMemorySpace + (EFI_REMOVE_MEMORY_SPACE)CoreRemoveMemorySpace, // RemoveMemorySpace + (EFI_GET_MEMORY_SPACE_DESCRIPTOR)CoreGetMemorySpaceDescriptor, // GetMemorySpaceDescriptor + (EFI_SET_MEMORY_SPACE_ATTRIBUTES)CoreSetMemorySpaceAttributes, // SetMemorySpaceAttributes + (EFI_GET_MEMORY_SPACE_MAP)CoreGetMemorySpaceMap, // GetMemorySpaceMap + (EFI_ADD_IO_SPACE)CoreAddIoSpace, // AddIoSpace + (EFI_ALLOCATE_IO_SPACE)CoreAllocateIoSpace, // AllocateIoSpace + (EFI_FREE_IO_SPACE)CoreFreeIoSpace, // FreeIoSpace + (EFI_REMOVE_IO_SPACE)CoreRemoveIoSpace, // RemoveIoSpace + (EFI_GET_IO_SPACE_DESCRIPTOR)CoreGetIoSpaceDescriptor, // GetIoSpaceDescriptor + (EFI_GET_IO_SPACE_MAP)CoreGetIoSpaceMap, // GetIoSpaceMap + (EFI_DISPATCH)CoreDispatcher, // Dispatch + (EFI_SCHEDULE)CoreSchedule, // Schedule + (EFI_TRUST)CoreTrust, // Trust + (EFI_PROCESS_FIRMWARE_VOLUME)CoreProcessFirmwareVolume, // ProcessFirmwareVolume (EFI_SET_MEMORY_SPACE_CAPABILITIES)CoreSetMemorySpaceCapabilities, // SetMemorySpaceCapabilities }; -EFI_SYSTEM_TABLE mEfiSystemTableTemplate = { +EFI_SYSTEM_TABLE mEfiSystemTableTemplate = { { EFI_SYSTEM_TABLE_SIGNATURE, // Signature EFI_SYSTEM_TABLE_REVISION, // Revision @@ -142,7 +142,7 @@ EFI_SYSTEM_TABLE mEfiSystemTableTemplate = { NULL // ConfigurationTable }; -EFI_RUNTIME_SERVICES mEfiRuntimeServicesTableTemplate = { +EFI_RUNTIME_SERVICES mEfiRuntimeServicesTableTemplate = { { EFI_RUNTIME_SERVICES_SIGNATURE, // Signature EFI_RUNTIME_SERVICES_REVISION, // Revision @@ -150,23 +150,23 @@ EFI_RUNTIME_SERVICES mEfiRuntimeServicesTableTemplate = { 0, // CRC32 0 // Reserved }, - (EFI_GET_TIME) CoreEfiNotAvailableYetArg2, // GetTime - (EFI_SET_TIME) CoreEfiNotAvailableYetArg1, // SetTime - (EFI_GET_WAKEUP_TIME) CoreEfiNotAvailableYetArg3, // GetWakeupTime - (EFI_SET_WAKEUP_TIME) CoreEfiNotAvailableYetArg2, // SetWakeupTime - (EFI_SET_VIRTUAL_ADDRESS_MAP) CoreEfiNotAvailableYetArg4, // SetVirtualAddressMap - (EFI_CONVERT_POINTER) CoreEfiNotAvailableYetArg2, // ConvertPointer - (EFI_GET_VARIABLE) CoreEfiNotAvailableYetArg5, // GetVariable - (EFI_GET_NEXT_VARIABLE_NAME) CoreEfiNotAvailableYetArg3, // GetNextVariableName - (EFI_SET_VARIABLE) CoreEfiNotAvailableYetArg5, // SetVariable - (EFI_GET_NEXT_HIGH_MONO_COUNT) CoreEfiNotAvailableYetArg1, // GetNextHighMonotonicCount - (EFI_RESET_SYSTEM) CoreEfiNotAvailableYetArg4, // ResetSystem - (EFI_UPDATE_CAPSULE) CoreEfiNotAvailableYetArg3, // UpdateCapsule - (EFI_QUERY_CAPSULE_CAPABILITIES) CoreEfiNotAvailableYetArg4, // QueryCapsuleCapabilities - (EFI_QUERY_VARIABLE_INFO) CoreEfiNotAvailableYetArg4 // QueryVariableInfo + (EFI_GET_TIME)CoreEfiNotAvailableYetArg2, // GetTime + (EFI_SET_TIME)CoreEfiNotAvailableYetArg1, // SetTime + (EFI_GET_WAKEUP_TIME)CoreEfiNotAvailableYetArg3, // GetWakeupTime + (EFI_SET_WAKEUP_TIME)CoreEfiNotAvailableYetArg2, // SetWakeupTime + (EFI_SET_VIRTUAL_ADDRESS_MAP)CoreEfiNotAvailableYetArg4, // SetVirtualAddressMap + (EFI_CONVERT_POINTER)CoreEfiNotAvailableYetArg2, // ConvertPointer + (EFI_GET_VARIABLE)CoreEfiNotAvailableYetArg5, // GetVariable + (EFI_GET_NEXT_VARIABLE_NAME)CoreEfiNotAvailableYetArg3, // GetNextVariableName + (EFI_SET_VARIABLE)CoreEfiNotAvailableYetArg5, // SetVariable + (EFI_GET_NEXT_HIGH_MONO_COUNT)CoreEfiNotAvailableYetArg1, // GetNextHighMonotonicCount + (EFI_RESET_SYSTEM)CoreEfiNotAvailableYetArg4, // ResetSystem + (EFI_UPDATE_CAPSULE)CoreEfiNotAvailableYetArg3, // UpdateCapsule + (EFI_QUERY_CAPSULE_CAPABILITIES)CoreEfiNotAvailableYetArg4, // QueryCapsuleCapabilities + (EFI_QUERY_VARIABLE_INFO)CoreEfiNotAvailableYetArg4 // QueryVariableInfo }; -EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate = { +EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate = { INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.ImageHead), INITIALIZE_LIST_HEAD_VARIABLE (gRuntimeTemplate.EventHead), @@ -184,24 +184,24 @@ EFI_RUNTIME_ARCH_PROTOCOL gRuntimeTemplate = { FALSE }; -EFI_RUNTIME_ARCH_PROTOCOL *gRuntime = &gRuntimeTemplate; +EFI_RUNTIME_ARCH_PROTOCOL *gRuntime = &gRuntimeTemplate; // // DXE Core Global Variables for the EFI System Table, Boot Services Table, // DXE Services Table, and Runtime Services Table // -EFI_DXE_SERVICES *gDxeCoreDS = &mDxeServices; -EFI_SYSTEM_TABLE *gDxeCoreST = NULL; +EFI_DXE_SERVICES *gDxeCoreDS = &mDxeServices; +EFI_SYSTEM_TABLE *gDxeCoreST = NULL; // // For debug initialize gDxeCoreRT to template. gDxeCoreRT must be allocated from RT memory // but gDxeCoreRT is used for ASSERT () and DEBUG () type macros so lets give it // a value that will not cause debug infrastructure to crash early on. // -EFI_RUNTIME_SERVICES *gDxeCoreRT = &mEfiRuntimeServicesTableTemplate; +EFI_RUNTIME_SERVICES *gDxeCoreRT = &mEfiRuntimeServicesTableTemplate; EFI_HANDLE gDxeCoreImageHandle = NULL; -BOOLEAN gMemoryMapTerminated = FALSE; +BOOLEAN gMemoryMapTerminated = FALSE; // // EFI Decompress Protocol @@ -215,7 +215,7 @@ EFI_DECOMPRESS_PROTOCOL gEfiDecompress = { // For Loading modules at fixed address feature, the configuration table is to cache the top address below which to load // Runtime code&boot time code // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable = {0, 0}; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoadModuleAtFixAddressConfigurationTable = { 0, 0 }; // Main entry point to the DXE Core // @@ -231,7 +231,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE gLoa VOID EFIAPI DxeMain ( - IN VOID *HobStart + IN VOID *HobStart ) { EFI_STATUS Status; @@ -248,10 +248,11 @@ DxeMain ( // Setup the default exception handlers // VectorInfoList = NULL; - GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); + GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { - VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *) (GET_GUID_HOB_DATA(GuidHob)); + VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *)(GET_GUID_HOB_DATA (GuidHob)); } + Status = InitializeCpuExceptionHandlersEx (VectorInfoList, NULL); ASSERT_EFI_ERROR (Status); @@ -295,7 +296,7 @@ DxeMain ( // Call constructor for all libraries // ProcessLibraryConstructorList (gDxeCoreImageHandle, gDxeCoreST); - PERF_CROSSMODULE_END ("PEI"); + PERF_CROSSMODULE_END ("PEI"); PERF_CROSSMODULE_BEGIN ("DXE"); // @@ -303,22 +304,28 @@ DxeMain ( // CoreInitializeMemoryServices()), now that library constructors have // executed. // - DEBUG ((DEBUG_INFO, "%a: MemoryBaseAddress=0x%Lx MemoryLength=0x%Lx\n", - __FUNCTION__, MemoryBaseAddress, MemoryLength)); + DEBUG (( + DEBUG_INFO, + "%a: MemoryBaseAddress=0x%Lx MemoryLength=0x%Lx\n", + __FUNCTION__, + MemoryBaseAddress, + MemoryLength + )); // // Report DXE Core image information to the PE/COFF Extra Action Library // ZeroMem (&ImageContext, sizeof (ImageContext)); - ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)gDxeCoreLoadedImage->ImageBase; - ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*)(UINTN)ImageContext.ImageAddress); - ImageContext.SizeOfHeaders = PeCoffGetSizeOfHeaders ((VOID*)(UINTN)ImageContext.ImageAddress); - Status = PeCoffLoaderGetEntryPoint ((VOID*)(UINTN)ImageContext.ImageAddress, &EntryPoint); + ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)gDxeCoreLoadedImage->ImageBase; + ImageContext.PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageContext.ImageAddress); + ImageContext.SizeOfHeaders = PeCoffGetSizeOfHeaders ((VOID *)(UINTN)ImageContext.ImageAddress); + Status = PeCoffLoaderGetEntryPoint ((VOID *)(UINTN)ImageContext.ImageAddress, &EntryPoint); if (Status == EFI_SUCCESS) { ImageContext.EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)EntryPoint; } - ImageContext.Handle = (VOID *)(UINTN)gDxeCoreLoadedImage->ImageBase; - ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; + + ImageContext.Handle = (VOID *)(UINTN)gDxeCoreLoadedImage->ImageBase; + ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; PeCoffLoaderRelocateImageExtraAction (&ImageContext); // @@ -344,10 +351,11 @@ DxeMain ( // Configuration Table so that user could easily to retrieve the top address to load Dxe and PEI // Code and Tseg base to load SMM driver. // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { Status = CoreInstallConfigurationTable (&gLoadFixedAddressConfigurationTableGuid, &gLoadModuleAtFixAddressConfigurationTable); ASSERT_EFI_ERROR (Status); } + // // Report Status Code here for DXE_ENTRY_POINT once it is available // @@ -371,56 +379,61 @@ DxeMain ( DEBUG ((DEBUG_INFO | DEBUG_LOAD, "HOBLIST address in DXE = 0x%p\n", HobStart)); DEBUG_CODE_BEGIN (); - EFI_PEI_HOB_POINTERS Hob; - - for (Hob.Raw = HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { - if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ - Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ - Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ - Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1)); - } + EFI_PEI_HOB_POINTERS Hob; + + for (Hob.Raw = HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { + if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ + Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ + Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ + Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1 + )); } - for (Hob.Raw = HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { - if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) { - DEBUG (( - DEBUG_INFO | DEBUG_LOAD, - "FV Hob 0x%0lx - 0x%0lx\n", - Hob.FirmwareVolume->BaseAddress, - Hob.FirmwareVolume->BaseAddress + Hob.FirmwareVolume->Length - 1 - )); - } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) { - DEBUG (( - DEBUG_INFO | DEBUG_LOAD, - "FV2 Hob 0x%0lx - 0x%0lx\n", - Hob.FirmwareVolume2->BaseAddress, - Hob.FirmwareVolume2->BaseAddress + Hob.FirmwareVolume2->Length - 1 - )); + } + + for (Hob.Raw = HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { + if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) { + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "FV Hob 0x%0lx - 0x%0lx\n", + Hob.FirmwareVolume->BaseAddress, + Hob.FirmwareVolume->BaseAddress + Hob.FirmwareVolume->Length - 1 + )); + } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) { + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "FV2 Hob 0x%0lx - 0x%0lx\n", + Hob.FirmwareVolume2->BaseAddress, + Hob.FirmwareVolume2->BaseAddress + Hob.FirmwareVolume2->Length - 1 + )); + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + " %g - %g\n", + &Hob.FirmwareVolume2->FvName, + &Hob.FirmwareVolume2->FileName + )); + } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3) { + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "FV3 Hob 0x%0lx - 0x%0lx - 0x%x - 0x%x\n", + Hob.FirmwareVolume3->BaseAddress, + Hob.FirmwareVolume3->BaseAddress + Hob.FirmwareVolume3->Length - 1, + Hob.FirmwareVolume3->AuthenticationStatus, + Hob.FirmwareVolume3->ExtractedFv + )); + if (Hob.FirmwareVolume3->ExtractedFv) { DEBUG (( DEBUG_INFO | DEBUG_LOAD, " %g - %g\n", - &Hob.FirmwareVolume2->FvName, - &Hob.FirmwareVolume2->FileName - )); - } else if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3) { - DEBUG (( - DEBUG_INFO | DEBUG_LOAD, - "FV3 Hob 0x%0lx - 0x%0lx - 0x%x - 0x%x\n", - Hob.FirmwareVolume3->BaseAddress, - Hob.FirmwareVolume3->BaseAddress + Hob.FirmwareVolume3->Length - 1, - Hob.FirmwareVolume3->AuthenticationStatus, - Hob.FirmwareVolume3->ExtractedFv + &Hob.FirmwareVolume3->FvName, + &Hob.FirmwareVolume3->FileName )); - if (Hob.FirmwareVolume3->ExtractedFv) { - DEBUG (( - DEBUG_INFO | DEBUG_LOAD, - " %g - %g\n", - &Hob.FirmwareVolume3->FvName, - &Hob.FirmwareVolume3->FileName - )); - } } } + } + DEBUG_CODE_END (); // @@ -440,16 +453,17 @@ DxeMain ( // GuidHob = GetNextGuidHob (&gEfiVectorHandoffInfoPpiGuid, HobStart); if (GuidHob != NULL) { - VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *) (GET_GUID_HOB_DATA(GuidHob)); - VectorInfo = VectorInfoList; - Index = 1; + VectorInfoList = (EFI_VECTOR_HANDOFF_INFO *)(GET_GUID_HOB_DATA (GuidHob)); + VectorInfo = VectorInfoList; + Index = 1; while (VectorInfo->Attribute != EFI_VECTOR_HANDOFF_LAST_ENTRY) { - VectorInfo ++; - Index ++; + VectorInfo++; + Index++; } - VectorInfo = AllocateCopyPool (sizeof (EFI_VECTOR_HANDOFF_INFO) * Index, (VOID *) VectorInfoList); + + VectorInfo = AllocateCopyPool (sizeof (EFI_VECTOR_HANDOFF_INFO) * Index, (VOID *)VectorInfoList); ASSERT (VectorInfo != NULL); - Status = CoreInstallConfigurationTable (&gEfiVectorHandoffTableGuid, (VOID *) VectorInfo); + Status = CoreInstallConfigurationTable (&gEfiVectorHandoffTableGuid, (VOID *)VectorInfo); ASSERT_EFI_ERROR (Status); } @@ -470,7 +484,8 @@ DxeMain ( // Status = CoreInstallMultipleProtocolInterfaces ( &mDecompressHandle, - &gEfiDecompressProtocolGuid, &gEfiDecompress, + &gEfiDecompressProtocolGuid, + &gEfiDecompress, NULL ); ASSERT_EFI_ERROR (Status); @@ -511,7 +526,7 @@ DxeMain ( // Display Architectural protocols that were not loaded if this is DEBUG build // DEBUG_CODE_BEGIN (); - CoreDisplayMissingArchProtocols (); + CoreDisplayMissingArchProtocols (); DEBUG_CODE_END (); // @@ -519,14 +534,14 @@ DxeMain ( // evaluated to false if this is a debug build // DEBUG_CODE_BEGIN (); - CoreDisplayDiscoveredNotDispatched (); + CoreDisplayDiscoveredNotDispatched (); DEBUG_CODE_END (); // // Assert if the Architectural Protocols are not present. // Status = CoreAllEfiServicesAvailable (); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { // // Report Status code that some Architectural Protocols are not present. // @@ -535,6 +550,7 @@ DxeMain ( (EFI_SOFTWARE_DXE_CORE | EFI_SW_DXE_CORE_EC_NO_ARCH) ); } + ASSERT_EFI_ERROR (Status); // @@ -559,9 +575,6 @@ DxeMain ( UNREACHABLE (); } - - - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -574,7 +587,7 @@ DxeMain ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg1 ( - UINTN Arg1 + UINTN Arg1 ) { // @@ -586,7 +599,6 @@ CoreEfiNotAvailableYetArg1 ( return EFI_NOT_AVAILABLE_YET; } - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -599,8 +611,8 @@ CoreEfiNotAvailableYetArg1 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg2 ( - UINTN Arg1, - UINTN Arg2 + UINTN Arg1, + UINTN Arg2 ) { // @@ -612,7 +624,6 @@ CoreEfiNotAvailableYetArg2 ( return EFI_NOT_AVAILABLE_YET; } - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -626,9 +637,9 @@ CoreEfiNotAvailableYetArg2 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg3 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3 ) { // @@ -640,7 +651,6 @@ CoreEfiNotAvailableYetArg3 ( return EFI_NOT_AVAILABLE_YET; } - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -655,10 +665,10 @@ CoreEfiNotAvailableYetArg3 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg4 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4 ) { // @@ -670,7 +680,6 @@ CoreEfiNotAvailableYetArg4 ( return EFI_NOT_AVAILABLE_YET; } - /** Place holder function until all the Boot Services and Runtime Services are available. @@ -686,11 +695,11 @@ CoreEfiNotAvailableYetArg4 ( EFI_STATUS EFIAPI CoreEfiNotAvailableYetArg5 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4, - UINTN Arg5 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4, + UINTN Arg5 ) { // @@ -702,7 +711,6 @@ CoreEfiNotAvailableYetArg5 ( return EFI_NOT_AVAILABLE_YET; } - /** Calcualte the 32-bit CRC in a EFI table using the service provided by the gRuntime service. @@ -712,10 +720,10 @@ CoreEfiNotAvailableYetArg5 ( **/ VOID CalculateEfiHdrCrc ( - IN OUT EFI_TABLE_HEADER *Hdr + IN OUT EFI_TABLE_HEADER *Hdr ) { - UINT32 Crc; + UINT32 Crc; Hdr->CRC32 = 0; @@ -728,7 +736,6 @@ CalculateEfiHdrCrc ( Hdr->CRC32 = Crc; } - /** Terminates all boot services. @@ -742,11 +749,11 @@ CalculateEfiHdrCrc ( EFI_STATUS EFIAPI CoreExitBootServices ( - IN EFI_HANDLE ImageHandle, - IN UINTN MapKey + IN EFI_HANDLE ImageHandle, + IN UINTN MapKey ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Disable Timer @@ -780,7 +787,7 @@ CoreExitBootServices ( (EFI_SOFTWARE_EFI_BOOT_SERVICE | EFI_SW_BS_PC_EXIT_BOOT_SERVICES) ); - MemoryProtectionExitBootServicesCallback(); + MemoryProtectionExitBootServicesCallback (); // // Disable interrupt of Debug timer. @@ -822,7 +829,6 @@ CoreExitBootServices ( return Status; } - /** Given a compressed source buffer, this function retrieves the size of the uncompressed buffer and the size of the scratch buffer required to decompress @@ -865,20 +871,20 @@ CoreExitBootServices ( EFI_STATUS EFIAPI DxeMainUefiDecompressGetInfo ( - IN EFI_DECOMPRESS_PROTOCOL *This, - IN VOID *Source, - IN UINT32 SourceSize, - OUT UINT32 *DestinationSize, - OUT UINT32 *ScratchSize + IN EFI_DECOMPRESS_PROTOCOL *This, + IN VOID *Source, + IN UINT32 SourceSize, + OUT UINT32 *DestinationSize, + OUT UINT32 *ScratchSize ) { - if (Source == NULL || DestinationSize == NULL || ScratchSize == NULL) { + if ((Source == NULL) || (DestinationSize == NULL) || (ScratchSize == NULL)) { return EFI_INVALID_PARAMETER; } + return UefiDecompressGetInfo (Source, SourceSize, DestinationSize, ScratchSize); } - /** Decompresses a compressed source buffer. @@ -916,20 +922,20 @@ DxeMainUefiDecompressGetInfo ( EFI_STATUS EFIAPI DxeMainUefiDecompress ( - IN EFI_DECOMPRESS_PROTOCOL *This, - IN VOID *Source, - IN UINT32 SourceSize, - IN OUT VOID *Destination, - IN UINT32 DestinationSize, - IN OUT VOID *Scratch, - IN UINT32 ScratchSize + IN EFI_DECOMPRESS_PROTOCOL *This, + IN VOID *Source, + IN UINT32 SourceSize, + IN OUT VOID *Destination, + IN UINT32 DestinationSize, + IN OUT VOID *Scratch, + IN UINT32 ScratchSize ) { EFI_STATUS Status; UINT32 TestDestinationSize; UINT32 TestScratchSize; - if (Source == NULL || Destination== NULL || Scratch == NULL) { + if ((Source == NULL) || (Destination == NULL) || (Scratch == NULL)) { return EFI_INVALID_PARAMETER; } @@ -938,7 +944,7 @@ DxeMainUefiDecompress ( return Status; } - if (ScratchSize < TestScratchSize || DestinationSize < TestDestinationSize) { + if ((ScratchSize < TestScratchSize) || (DestinationSize < TestDestinationSize)) { return RETURN_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c b/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c index 29a55d02e6..3fe02940ed 100644 --- a/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c +++ b/MdeModulePkg/Core/Dxe/DxeMain/DxeProtocolNotify.c @@ -39,34 +39,34 @@ EFI_CORE_PROTOCOL_NOTIFY_ENTRY mArchProtocols[] = { // Optional protocols that the DXE Core will use if they are present // EFI_CORE_PROTOCOL_NOTIFY_ENTRY mOptionalProtocols[] = { - { &gEfiSecurity2ArchProtocolGuid, (VOID **)&gSecurity2, NULL, NULL, FALSE }, - { &gEfiSmmBase2ProtocolGuid, (VOID **)&gSmmBase2, NULL, NULL, FALSE }, - { NULL, (VOID **)NULL, NULL, NULL, FALSE } + { &gEfiSecurity2ArchProtocolGuid, (VOID **)&gSecurity2, NULL, NULL, FALSE }, + { &gEfiSmmBase2ProtocolGuid, (VOID **)&gSmmBase2, NULL, NULL, FALSE }, + { NULL, (VOID **)NULL, NULL, NULL, FALSE } }; // // Following is needed to display missing architectural protocols in debug builds // typedef struct { - EFI_GUID *ProtocolGuid; - CHAR8 *GuidString; + EFI_GUID *ProtocolGuid; + CHAR8 *GuidString; } GUID_TO_STRING_PROTOCOL_ENTRY; -GLOBAL_REMOVE_IF_UNREFERENCED CONST GUID_TO_STRING_PROTOCOL_ENTRY mMissingProtocols[] = { - { &gEfiSecurityArchProtocolGuid, "Security" }, - { &gEfiCpuArchProtocolGuid, "CPU" }, - { &gEfiMetronomeArchProtocolGuid, "Metronome" }, - { &gEfiTimerArchProtocolGuid, "Timer" }, - { &gEfiBdsArchProtocolGuid, "Bds" }, - { &gEfiWatchdogTimerArchProtocolGuid, "Watchdog Timer" }, - { &gEfiRuntimeArchProtocolGuid, "Runtime" }, - { &gEfiVariableArchProtocolGuid, "Variable" }, - { &gEfiVariableWriteArchProtocolGuid, "Variable Write" }, - { &gEfiCapsuleArchProtocolGuid, "Capsule" }, - { &gEfiMonotonicCounterArchProtocolGuid, "Monotonic Counter" }, - { &gEfiResetArchProtocolGuid, "Reset" }, - { &gEfiRealTimeClockArchProtocolGuid, "Real Time Clock" }, - { NULL, "" } +GLOBAL_REMOVE_IF_UNREFERENCED CONST GUID_TO_STRING_PROTOCOL_ENTRY mMissingProtocols[] = { + { &gEfiSecurityArchProtocolGuid, "Security" }, + { &gEfiCpuArchProtocolGuid, "CPU" }, + { &gEfiMetronomeArchProtocolGuid, "Metronome" }, + { &gEfiTimerArchProtocolGuid, "Timer" }, + { &gEfiBdsArchProtocolGuid, "Bds" }, + { &gEfiWatchdogTimerArchProtocolGuid, "Watchdog Timer" }, + { &gEfiRuntimeArchProtocolGuid, "Runtime" }, + { &gEfiVariableArchProtocolGuid, "Variable" }, + { &gEfiVariableWriteArchProtocolGuid, "Variable Write" }, + { &gEfiCapsuleArchProtocolGuid, "Capsule" }, + { &gEfiMonotonicCounterArchProtocolGuid, "Monotonic Counter" }, + { &gEfiResetArchProtocolGuid, "Reset" }, + { &gEfiRealTimeClockArchProtocolGuid, "Real Time Clock" }, + { NULL, "" } }; /** @@ -88,10 +88,10 @@ CoreAllEfiServicesAvailable ( return EFI_NOT_FOUND; } } + return EFI_SUCCESS; } - /** Notification event handler registered by CoreNotifyOnArchProtocolInstallation (). This notify function is registered for every architectural protocol. This handler @@ -170,14 +170,15 @@ GenericProtocolNotify ( // Copy all the registered Image to new gRuntime protocol // for (Link = gRuntimeTemplate.ImageHead.ForwardLink; Link != &gRuntimeTemplate.ImageHead; Link = TempLinkNode.ForwardLink) { - CopyMem (&TempLinkNode, Link, sizeof(LIST_ENTRY)); + CopyMem (&TempLinkNode, Link, sizeof (LIST_ENTRY)); InsertTailList (&gRuntime->ImageHead, Link); } + // // Copy all the registered Event to new gRuntime protocol // for (Link = gRuntimeTemplate.EventHead.ForwardLink; Link != &gRuntimeTemplate.EventHead; Link = TempLinkNode.ForwardLink) { - CopyMem (&TempLinkNode, Link, sizeof(LIST_ENTRY)); + CopyMem (&TempLinkNode, Link, sizeof (LIST_ENTRY)); InsertTailList (&gRuntime->EventHead, Link); } @@ -213,28 +214,28 @@ CoreNotifyOnProtocolEntryTable ( { EFI_STATUS Status; - for (; Entry->ProtocolGuid != NULL; Entry++) { + for ( ; Entry->ProtocolGuid != NULL; Entry++) { // // Create the event // Status = CoreCreateEvent ( - EVT_NOTIFY_SIGNAL, - TPL_CALLBACK, - GenericProtocolNotify, - Entry, - &Entry->Event - ); - ASSERT_EFI_ERROR(Status); + EVT_NOTIFY_SIGNAL, + TPL_CALLBACK, + GenericProtocolNotify, + Entry, + &Entry->Event + ); + ASSERT_EFI_ERROR (Status); // // Register for protocol notifactions on this event // Status = CoreRegisterProtocolNotify ( - Entry->ProtocolGuid, - Entry->Event, - &Entry->Registration - ); - ASSERT_EFI_ERROR(Status); + Entry->ProtocolGuid, + Entry->Event, + &Entry->Registration + ); + ASSERT_EFI_ERROR (Status); } } @@ -252,7 +253,6 @@ CoreNotifyOnProtocolInstallation ( CoreNotifyOnProtocolEntryTable (mOptionalProtocols); } - /** Displays Architectural protocols that were not loaded and are required for DXE core to function. Only used in Debug Builds. diff --git a/MdeModulePkg/Core/Dxe/Event/Event.c b/MdeModulePkg/Core/Dxe/Event/Event.c index 6f96e12815..dc82abb021 100644 --- a/MdeModulePkg/Core/Dxe/Event/Event.c +++ b/MdeModulePkg/Core/Dxe/Event/Event.c @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "DxeMain.h" #include "Event.h" @@ -19,27 +18,27 @@ EFI_TPL gEfiCurrentTpl = TPL_APPLICATION; /// /// gEventQueueLock - Protects the event queues /// -EFI_LOCK gEventQueueLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL); +EFI_LOCK gEventQueueLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL); /// /// gEventQueue - A list of event's to notify for each priority level /// -LIST_ENTRY gEventQueue[TPL_HIGH_LEVEL + 1]; +LIST_ENTRY gEventQueue[TPL_HIGH_LEVEL + 1]; /// /// gEventPending - A bitmask of the EventQueues that are pending /// -UINTN gEventPending = 0; +UINTN gEventPending = 0; /// /// gEventSignalQueue - A list of events to signal based on EventGroup type /// -LIST_ENTRY gEventSignalQueue = INITIALIZE_LIST_HEAD_VARIABLE (gEventSignalQueue); +LIST_ENTRY gEventSignalQueue = INITIALIZE_LIST_HEAD_VARIABLE (gEventSignalQueue); /// /// Enumerate the valid types /// -UINT32 mEventTable[] = { +UINT32 mEventTable[] = { /// /// 0x80000200 Timer event with a notification function that is /// queue when the event is signaled with SignalEvent() @@ -85,8 +84,7 @@ UINT32 mEventTable[] = { /// /// gIdleLoopEvent - Event which is signalled when the core is idle /// -EFI_EVENT gIdleLoopEvent = NULL; - +EFI_EVENT gIdleLoopEvent = NULL; /** Enter critical section by acquiring the lock on gEventQueueLock. @@ -100,7 +98,6 @@ CoreAcquireEventLock ( CoreAcquireLock (&gEventQueueLock); } - /** Exit critical section by releasing the lock on gEventQueueLock. @@ -113,8 +110,6 @@ CoreReleaseEventLock ( CoreReleaseLock (&gEventQueueLock); } - - /** Initializes "event" support. @@ -126,9 +121,9 @@ CoreInitializeEventServices ( VOID ) { - UINTN Index; + UINTN Index; - for (Index=0; Index <= TPL_HIGH_LEVEL; Index++) { + for (Index = 0; Index <= TPL_HIGH_LEVEL; Index++) { InitializeListHead (&gEventQueue[Index]); } @@ -146,8 +141,6 @@ CoreInitializeEventServices ( return EFI_SUCCESS; } - - /** Dispatches all pending events. @@ -157,11 +150,11 @@ CoreInitializeEventServices ( **/ VOID CoreDispatchEventNotifies ( - IN EFI_TPL Priority + IN EFI_TPL Priority ) { - IEVENT *Event; - LIST_ENTRY *Head; + IEVENT *Event; + LIST_ENTRY *Head; CoreAcquireEventLock (); ASSERT (gEventQueueLock.OwnerTpl == Priority); @@ -171,7 +164,6 @@ CoreDispatchEventNotifies ( // Dispatch all the pending notifications // while (!IsListEmpty (Head)) { - Event = CR (Head->ForwardLink, IEVENT, NotifyLink, EVENT_SIGNATURE); RemoveEntryList (&Event->NotifyLink); @@ -203,8 +195,6 @@ CoreDispatchEventNotifies ( CoreReleaseEventLock (); } - - /** Queues the event's notification function to fire. @@ -213,10 +203,9 @@ CoreDispatchEventNotifies ( **/ VOID CoreNotifyEvent ( - IN IEVENT *Event + IN IEVENT *Event ) { - // // Event database must be locked // @@ -239,9 +228,6 @@ CoreNotifyEvent ( gEventPending |= (UINTN)(1 << Event->NotifyTpl); } - - - /** Signals all events in the EventGroup. @@ -250,12 +236,12 @@ CoreNotifyEvent ( **/ VOID CoreNotifySignalList ( - IN EFI_GUID *EventGroup + IN EFI_GUID *EventGroup ) { - LIST_ENTRY *Link; - LIST_ENTRY *Head; - IEVENT *Event; + LIST_ENTRY *Link; + LIST_ENTRY *Head; + IEVENT *Event; CoreAcquireEventLock (); @@ -270,7 +256,6 @@ CoreNotifySignalList ( CoreReleaseEventLock (); } - /** Creates an event. @@ -292,18 +277,16 @@ CoreNotifySignalList ( EFI_STATUS EFIAPI CoreCreateEvent ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN VOID *NotifyContext OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN VOID *NotifyContext OPTIONAL, + OUT EFI_EVENT *Event ) { return CoreCreateEventEx (Type, NotifyTpl, NotifyFunction, NotifyContext, NULL, Event); } - - /** Creates an event in a group. @@ -327,21 +310,22 @@ CoreCreateEvent ( EFI_STATUS EFIAPI CoreCreateEventEx ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN CONST VOID *NotifyContext OPTIONAL, - IN CONST EFI_GUID *EventGroup OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN CONST VOID *NotifyContext OPTIONAL, + IN CONST EFI_GUID *EventGroup OPTIONAL, + OUT EFI_EVENT *Event ) { // // If it's a notify type of event, check for invalid NotifyTpl // if ((Type & (EVT_NOTIFY_WAIT | EVT_NOTIFY_SIGNAL)) != 0) { - if (NotifyTpl != TPL_APPLICATION && - NotifyTpl != TPL_CALLBACK && - NotifyTpl != TPL_NOTIFY) { + if ((NotifyTpl != TPL_APPLICATION) && + (NotifyTpl != TPL_CALLBACK) && + (NotifyTpl != TPL_NOTIFY)) + { return EFI_INVALID_PARAMETER; } } @@ -372,18 +356,17 @@ CoreCreateEventEx ( EFI_STATUS EFIAPI CoreCreateEventInternal ( - IN UINT32 Type, - IN EFI_TPL NotifyTpl, - IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, - IN CONST VOID *NotifyContext OPTIONAL, - IN CONST EFI_GUID *EventGroup OPTIONAL, - OUT EFI_EVENT *Event + IN UINT32 Type, + IN EFI_TPL NotifyTpl, + IN EFI_EVENT_NOTIFY NotifyFunction OPTIONAL, + IN CONST VOID *NotifyContext OPTIONAL, + IN CONST EFI_GUID *EventGroup OPTIONAL, + OUT EFI_EVENT *Event ) { - EFI_STATUS Status; - IEVENT *IEvent; - INTN Index; - + EFI_STATUS Status; + IEVENT *IEvent; + INTN Index; if (Event == NULL) { return EFI_INVALID_PARAMETER; @@ -394,12 +377,13 @@ CoreCreateEventInternal ( // Status = EFI_INVALID_PARAMETER; for (Index = 0; Index < (sizeof (mEventTable) / sizeof (UINT32)); Index++) { - if (Type == mEventTable[Index]) { - Status = EFI_SUCCESS; - break; - } + if (Type == mEventTable[Index]) { + Status = EFI_SUCCESS; + break; + } } - if(EFI_ERROR (Status)) { + + if (EFI_ERROR (Status)) { return EFI_INVALID_PARAMETER; } @@ -414,6 +398,7 @@ CoreCreateEventInternal ( if ((Type == EVT_SIGNAL_EXIT_BOOT_SERVICES) || (Type == EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE)) { return EFI_INVALID_PARAMETER; } + if (CompareGuid (EventGroup, &gEfiEventExitBootServicesGuid)) { Type = EVT_SIGNAL_EXIT_BOOT_SERVICES; } else if (CompareGuid (EventGroup, &gEfiEventVirtualAddressChangeGuid)) { @@ -439,17 +424,17 @@ CoreCreateEventInternal ( // if ((NotifyFunction == NULL) || (NotifyTpl <= TPL_APPLICATION) || - (NotifyTpl >= TPL_HIGH_LEVEL)) { + (NotifyTpl >= TPL_HIGH_LEVEL)) + { return EFI_INVALID_PARAMETER; } - } else { // // No notification needed, zero ignored values // - NotifyTpl = 0; + NotifyTpl = 0; NotifyFunction = NULL; - NotifyContext = NULL; + NotifyContext = NULL; } // @@ -460,12 +445,13 @@ CoreCreateEventInternal ( } else { IEvent = AllocateZeroPool (sizeof (IEVENT)); } + if (IEvent == NULL) { return EFI_OUT_OF_RESOURCES; } IEvent->Signature = EVENT_SIGNATURE; - IEvent->Type = Type; + IEvent->Type = Type; IEvent->NotifyTpl = NotifyTpl; IEvent->NotifyFunction = NotifyFunction; @@ -484,7 +470,7 @@ CoreCreateEventInternal ( IEvent->RuntimeData.Type = Type; IEvent->RuntimeData.NotifyTpl = NotifyTpl; IEvent->RuntimeData.NotifyFunction = NotifyFunction; - IEvent->RuntimeData.NotifyContext = (VOID *) NotifyContext; + IEvent->RuntimeData.NotifyContext = (VOID *)NotifyContext; // // Work around the bug in the Platform Init specification (v1.7), reported // as Mantis#2017: "EFI_RUNTIME_EVENT_ENTRY.Event" should have type @@ -493,7 +479,7 @@ CoreCreateEventInternal ( // doesn't match the natural language description. Therefore we need an // explicit cast here. // - IEvent->RuntimeData.Event = (EFI_EVENT *) IEvent; + IEvent->RuntimeData.Event = (EFI_EVENT *)IEvent; InsertTailList (&gRuntime->EventHead, &IEvent->RuntimeData.Link); } @@ -514,9 +500,6 @@ CoreCreateEventInternal ( return EFI_SUCCESS; } - - - /** Signals the event. Queues the event to be notified if needed. @@ -529,10 +512,10 @@ CoreCreateEventInternal ( EFI_STATUS EFIAPI CoreSignalEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ) { - IEVENT *Event; + IEVENT *Event; Event = UserEvent; @@ -565,7 +548,7 @@ CoreSignalEvent ( CoreReleaseEventLock (); CoreNotifySignalList (&Event->EventGroup); CoreAcquireEventLock (); - } else { + } else { CoreNotifyEvent (Event); } } @@ -575,8 +558,6 @@ CoreSignalEvent ( return EFI_SUCCESS; } - - /** Check the status of an event. @@ -590,7 +571,7 @@ CoreSignalEvent ( EFI_STATUS EFIAPI CoreCheckEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ) { IEVENT *Event; @@ -613,7 +594,6 @@ CoreCheckEvent ( Status = EFI_NOT_READY; if ((Event->SignalCount == 0) && ((Event->Type & EVT_NOTIFY_WAIT) != 0)) { - // // Queue the wait notify function // @@ -621,6 +601,7 @@ CoreCheckEvent ( if (Event->SignalCount == 0) { CoreNotifyEvent (Event); } + CoreReleaseEventLock (); } @@ -633,7 +614,7 @@ CoreCheckEvent ( if (Event->SignalCount != 0) { Event->SignalCount = 0; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } CoreReleaseEventLock (); @@ -642,8 +623,6 @@ CoreCheckEvent ( return Status; } - - /** Stops execution until an event is signaled. @@ -661,13 +640,13 @@ CoreCheckEvent ( EFI_STATUS EFIAPI CoreWaitForEvent ( - IN UINTN NumberOfEvents, - IN EFI_EVENT *UserEvents, - OUT UINTN *UserIndex + IN UINTN NumberOfEvents, + IN EFI_EVENT *UserEvents, + OUT UINTN *UserIndex ) { - EFI_STATUS Status; - UINTN Index; + EFI_STATUS Status; + UINTN Index; // // Can only WaitForEvent at TPL_APPLICATION @@ -684,10 +663,8 @@ CoreWaitForEvent ( return EFI_INVALID_PARAMETER; } - for(;;) { - - for(Index = 0; Index < NumberOfEvents; Index++) { - + for ( ; ;) { + for (Index = 0; Index < NumberOfEvents; Index++) { Status = CoreCheckEvent (UserEvents[Index]); // @@ -697,6 +674,7 @@ CoreWaitForEvent ( if (UserIndex != NULL) { *UserIndex = Index; } + return Status; } } @@ -708,7 +686,6 @@ CoreWaitForEvent ( } } - /** Closes an event and frees the event structure. @@ -721,7 +698,7 @@ CoreWaitForEvent ( EFI_STATUS EFIAPI CoreCloseEvent ( - IN EFI_EVENT UserEvent + IN EFI_EVENT UserEvent ) { EFI_STATUS Status; @@ -776,7 +753,7 @@ CoreCloseEvent ( // clear the Signature of Event before free pool. // Event->Signature = 0; - Status = CoreFreePool (Event); + Status = CoreFreePool (Event); ASSERT_EFI_ERROR (Status); return Status; diff --git a/MdeModulePkg/Core/Dxe/Event/Event.h b/MdeModulePkg/Core/Dxe/Event/Event.h index 8141c5003e..201b90b301 100644 --- a/MdeModulePkg/Core/Dxe/Event/Event.h +++ b/MdeModulePkg/Core/Dxe/Event/Event.h @@ -10,18 +10,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __EVENT_H__ #define __EVENT_H__ - -#define VALID_TPL(a) ((a) <= TPL_HIGH_LEVEL) -extern UINTN gEventPending; +#define VALID_TPL(a) ((a) <= TPL_HIGH_LEVEL) +extern UINTN gEventPending; /// /// Set if Event is part of an event group /// -#define EVT_EXFLAG_EVENT_GROUP 0x01 +#define EVT_EXFLAG_EVENT_GROUP 0x01 /// /// Set if Event is registered on a protocol notify /// -#define EVT_EXFLAG_EVENT_PROTOCOL_NOTIFICATION 0x02 +#define EVT_EXFLAG_EVENT_PROTOCOL_NOTIFICATION 0x02 // // EFI_EVENT @@ -31,41 +30,40 @@ extern UINTN gEventPending; /// Timer event information /// typedef struct { - LIST_ENTRY Link; - UINT64 TriggerTime; - UINT64 Period; + LIST_ENTRY Link; + UINT64 TriggerTime; + UINT64 Period; } TIMER_EVENT_INFO; -#define EVENT_SIGNATURE SIGNATURE_32('e','v','n','t') +#define EVENT_SIGNATURE SIGNATURE_32('e','v','n','t') typedef struct { - UINTN Signature; - UINT32 Type; - UINT32 SignalCount; + UINTN Signature; + UINT32 Type; + UINT32 SignalCount; /// /// Entry if the event is registered to be signalled /// - LIST_ENTRY SignalLink; + LIST_ENTRY SignalLink; /// /// Notification information for this event /// - EFI_TPL NotifyTpl; - EFI_EVENT_NOTIFY NotifyFunction; - VOID *NotifyContext; - EFI_GUID EventGroup; - LIST_ENTRY NotifyLink; - UINT8 ExFlag; + EFI_TPL NotifyTpl; + EFI_EVENT_NOTIFY NotifyFunction; + VOID *NotifyContext; + EFI_GUID EventGroup; + LIST_ENTRY NotifyLink; + UINT8 ExFlag; /// /// A list of all runtime events /// - EFI_RUNTIME_EVENT_ENTRY RuntimeData; - TIMER_EVENT_INFO Timer; + EFI_RUNTIME_EVENT_ENTRY RuntimeData; + TIMER_EVENT_INFO Timer; } IEVENT; // // Internal prototypes // - /** Dispatches all pending events. @@ -75,10 +73,9 @@ typedef struct { **/ VOID CoreDispatchEventNotifies ( - IN EFI_TPL Priority + IN EFI_TPL Priority ); - /** Initializes timer support. diff --git a/MdeModulePkg/Core/Dxe/Event/Timer.c b/MdeModulePkg/Core/Dxe/Event/Timer.c index 7a94712d81..29e507c67c 100644 --- a/MdeModulePkg/Core/Dxe/Event/Timer.c +++ b/MdeModulePkg/Core/Dxe/Event/Timer.c @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "DxeMain.h" #include "Event.h" @@ -14,16 +13,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Internal data // -LIST_ENTRY mEfiTimerList = INITIALIZE_LIST_HEAD_VARIABLE (mEfiTimerList); -EFI_LOCK mEfiTimerLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL - 1); -EFI_EVENT mEfiCheckTimerEvent = NULL; +LIST_ENTRY mEfiTimerList = INITIALIZE_LIST_HEAD_VARIABLE (mEfiTimerList); +EFI_LOCK mEfiTimerLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL - 1); +EFI_EVENT mEfiCheckTimerEvent = NULL; -EFI_LOCK mEfiSystemTimeLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL); -UINT64 mEfiSystemTime = 0; +EFI_LOCK mEfiSystemTimeLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_HIGH_LEVEL); +UINT64 mEfiSystemTime = 0; // // Timer functions // + /** Inserts the timer event. @@ -33,12 +33,12 @@ UINT64 mEfiSystemTime = 0; **/ VOID CoreInsertEventTimer ( - IN IEVENT *Event + IN IEVENT *Event ) { - UINT64 TriggerTime; - LIST_ENTRY *Link; - IEVENT *Event2; + UINT64 TriggerTime; + LIST_ENTRY *Link; + IEVENT *Event2; ASSERT_LOCKED (&mEfiTimerLock); @@ -72,7 +72,7 @@ CoreCurrentSystemTime ( VOID ) { - UINT64 SystemTime; + UINT64 SystemTime; CoreAcquireLock (&mEfiSystemTimeLock); SystemTime = mEfiSystemTime; @@ -92,12 +92,12 @@ CoreCurrentSystemTime ( VOID EFIAPI CoreCheckTimers ( - IN EFI_EVENT CheckEvent, - IN VOID *Context + IN EFI_EVENT CheckEvent, + IN VOID *Context ) { - UINT64 SystemTime; - IEVENT *Event; + UINT64 SystemTime; + IEVENT *Event; // // Check the timer database for expired timers @@ -154,7 +154,6 @@ CoreCheckTimers ( CoreReleaseLock (&mEfiTimerLock); } - /** Initializes timer support. @@ -177,7 +176,6 @@ CoreInitializeTimer ( ASSERT_EFI_ERROR (Status); } - /** Called by the platform code to process a tick. @@ -188,10 +186,10 @@ CoreInitializeTimer ( VOID EFIAPI CoreTimerTick ( - IN UINT64 Duration + IN UINT64 Duration ) { - IEVENT *Event; + IEVENT *Event; // // Check runtiem flag in case there are ticks while exiting boot services @@ -218,8 +216,6 @@ CoreTimerTick ( CoreReleaseLock (&mEfiSystemTimeLock); } - - /** Sets the type of timer and the trigger time for a timer event. @@ -238,12 +234,12 @@ CoreTimerTick ( EFI_STATUS EFIAPI CoreSetTimer ( - IN EFI_EVENT UserEvent, - IN EFI_TIMER_DELAY Type, - IN UINT64 TriggerTime + IN EFI_EVENT UserEvent, + IN EFI_TIMER_DELAY Type, + IN UINT64 TriggerTime ) { - IEVENT *Event; + IEVENT *Event; Event = UserEvent; @@ -255,7 +251,7 @@ CoreSetTimer ( return EFI_INVALID_PARAMETER; } - if ((UINT32)Type > TimerRelative || (Event->Type & EVT_TIMER) == 0) { + if (((UINT32)Type > TimerRelative) || ((Event->Type & EVT_TIMER) == 0)) { return EFI_INVALID_PARAMETER; } @@ -270,14 +266,14 @@ CoreSetTimer ( } Event->Timer.TriggerTime = 0; - Event->Timer.Period = 0; + Event->Timer.Period = 0; if (Type != TimerCancel) { - if (Type == TimerPeriodic) { if (TriggerTime == 0) { gTimer->GetTimerPeriod (gTimer, &TriggerTime); } + Event->Timer.Period = TriggerTime; } diff --git a/MdeModulePkg/Core/Dxe/Event/Tpl.c b/MdeModulePkg/Core/Dxe/Event/Tpl.c index 8b5928df00..b33f80573c 100644 --- a/MdeModulePkg/Core/Dxe/Event/Tpl.c +++ b/MdeModulePkg/Core/Dxe/Event/Tpl.c @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID CoreSetInterruptState ( - IN BOOLEAN Enable + IN BOOLEAN Enable ) { EFI_STATUS Status; @@ -26,21 +26,23 @@ CoreSetInterruptState ( if (gCpu == NULL) { return; } + if (!Enable) { gCpu->DisableInterrupt (gCpu); return; } + if (gSmmBase2 == NULL) { gCpu->EnableInterrupt (gCpu); return; } + Status = gSmmBase2->InSmm (gSmmBase2, &InSmm); if (!EFI_ERROR (Status) && !InSmm) { - gCpu->EnableInterrupt(gCpu); + gCpu->EnableInterrupt (gCpu); } } - /** Raise the task priority level to the new level. High level is implemented by disabling processor interrupts. @@ -53,22 +55,23 @@ CoreSetInterruptState ( EFI_TPL EFIAPI CoreRaiseTpl ( - IN EFI_TPL NewTpl + IN EFI_TPL NewTpl ) { - EFI_TPL OldTpl; + EFI_TPL OldTpl; OldTpl = gEfiCurrentTpl; if (OldTpl > NewTpl) { DEBUG ((DEBUG_ERROR, "FATAL ERROR - RaiseTpl with OldTpl(0x%x) > NewTpl(0x%x)\n", OldTpl, NewTpl)); ASSERT (FALSE); } + ASSERT (VALID_TPL (NewTpl)); // // If raising to high level, disable interrupts // - if (NewTpl >= TPL_HIGH_LEVEL && OldTpl < TPL_HIGH_LEVEL) { + if ((NewTpl >= TPL_HIGH_LEVEL) && (OldTpl < TPL_HIGH_LEVEL)) { CoreSetInterruptState (FALSE); } @@ -80,9 +83,6 @@ CoreRaiseTpl ( return OldTpl; } - - - /** Lowers the task priority to the previous value. If the new priority unmasks events at a higher priority, they are dispatched. @@ -93,17 +93,18 @@ CoreRaiseTpl ( VOID EFIAPI CoreRestoreTpl ( - IN EFI_TPL NewTpl + IN EFI_TPL NewTpl ) { - EFI_TPL OldTpl; - EFI_TPL PendingTpl; + EFI_TPL OldTpl; + EFI_TPL PendingTpl; OldTpl = gEfiCurrentTpl; if (NewTpl > OldTpl) { DEBUG ((DEBUG_ERROR, "FATAL ERROR - RestoreTpl with NewTpl(0x%x) > OldTpl(0x%x)\n", NewTpl, OldTpl)); ASSERT (FALSE); } + ASSERT (VALID_TPL (NewTpl)); // @@ -111,7 +112,7 @@ CoreRestoreTpl ( // interrupts are enabled // - if (OldTpl >= TPL_HIGH_LEVEL && NewTpl < TPL_HIGH_LEVEL) { + if ((OldTpl >= TPL_HIGH_LEVEL) && (NewTpl < TPL_HIGH_LEVEL)) { gEfiCurrentTpl = TPL_HIGH_LEVEL; } @@ -119,7 +120,7 @@ CoreRestoreTpl ( // Dispatch any pending events // while (gEventPending != 0) { - PendingTpl = (UINTN) HighBitSet64 (gEventPending); + PendingTpl = (UINTN)HighBitSet64 (gEventPending); if (PendingTpl <= NewTpl) { break; } @@ -128,6 +129,7 @@ CoreRestoreTpl ( if (gEfiCurrentTpl < TPL_HIGH_LEVEL) { CoreSetInterruptState (TRUE); } + CoreDispatchEventNotifies (gEfiCurrentTpl); } @@ -144,5 +146,4 @@ CoreRestoreTpl ( if (gEfiCurrentTpl < TPL_HIGH_LEVEL) { CoreSetInterruptState (TRUE); } - } diff --git a/MdeModulePkg/Core/Dxe/FwVol/Ffs.c b/MdeModulePkg/Core/Dxe/FwVol/Ffs.c index 199c7f821b..17e599cc15 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/Ffs.c +++ b/MdeModulePkg/Core/Dxe/FwVol/Ffs.c @@ -6,11 +6,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "DxeMain.h" #include "FwVolDriver.h" - /** Get the FFS file state by checking the highest bit set in the header's state field. @@ -26,13 +24,13 @@ GetFileState ( IN EFI_FFS_FILE_HEADER *FfsHeader ) { - EFI_FFS_FILE_STATE FileState; - UINT8 HighestBit; + EFI_FFS_FILE_STATE FileState; + UINT8 HighestBit; FileState = FfsHeader->State; if (ErasePolarity != 0) { - FileState = (EFI_FFS_FILE_STATE)~FileState; + FileState = (EFI_FFS_FILE_STATE) ~FileState; } HighestBit = 0x80; @@ -40,11 +38,9 @@ GetFileState ( HighestBit >>= 1; } - return (EFI_FFS_FILE_STATE) HighestBit; + return (EFI_FFS_FILE_STATE)HighestBit; } - - /** Check if a block of buffer is erased. @@ -58,16 +54,16 @@ GetFileState ( **/ BOOLEAN IsBufferErased ( - IN UINT8 ErasePolarity, - IN VOID *InBuffer, - IN UINTN BufferSize + IN UINT8 ErasePolarity, + IN VOID *InBuffer, + IN UINTN BufferSize ) { - UINTN Count; - UINT8 EraseByte; - UINT8 *Buffer; + UINTN Count; + UINT8 EraseByte; + UINT8 *Buffer; - if(ErasePolarity == 1) { + if (ErasePolarity == 1) { EraseByte = 0xFF; } else { EraseByte = 0; @@ -83,8 +79,6 @@ IsBufferErased ( return TRUE; } - - /** Verify checksum of the firmware volume header. @@ -96,12 +90,12 @@ IsBufferErased ( **/ BOOLEAN VerifyFvHeaderChecksum ( - IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader ) { UINT16 Checksum; - Checksum = CalculateSum16 ((UINT16 *) FvHeader, FvHeader->HeaderLength); + Checksum = CalculateSum16 ((UINT16 *)FvHeader, FvHeader->HeaderLength); if (Checksum == 0) { return TRUE; @@ -110,7 +104,6 @@ VerifyFvHeaderChecksum ( } } - /** Verify checksum of the FFS file header. @@ -125,14 +118,15 @@ VerifyHeaderChecksum ( IN EFI_FFS_FILE_HEADER *FfsHeader ) { - UINT8 HeaderChecksum; + UINT8 HeaderChecksum; if (IS_FFS_FILE2 (FfsHeader)) { - HeaderChecksum = CalculateSum8 ((UINT8 *) FfsHeader, sizeof (EFI_FFS_FILE_HEADER2)); + HeaderChecksum = CalculateSum8 ((UINT8 *)FfsHeader, sizeof (EFI_FFS_FILE_HEADER2)); } else { - HeaderChecksum = CalculateSum8 ((UINT8 *) FfsHeader, sizeof (EFI_FFS_FILE_HEADER)); + HeaderChecksum = CalculateSum8 ((UINT8 *)FfsHeader, sizeof (EFI_FFS_FILE_HEADER)); } - HeaderChecksum = (UINT8) (HeaderChecksum - FfsHeader->State - FfsHeader->IntegrityCheck.Checksum.File); + + HeaderChecksum = (UINT8)(HeaderChecksum - FfsHeader->State - FfsHeader->IntegrityCheck.Checksum.File); if (HeaderChecksum == 0) { return TRUE; @@ -141,8 +135,6 @@ VerifyHeaderChecksum ( } } - - /** Check if it's a valid FFS file header. @@ -164,23 +156,22 @@ IsValidFfsHeader ( *FileState = GetFileState (ErasePolarity, FfsHeader); switch (*FileState) { - case EFI_FILE_HEADER_VALID: - case EFI_FILE_DATA_VALID: - case EFI_FILE_MARKED_FOR_UPDATE: - case EFI_FILE_DELETED: - // - // Here we need to verify header checksum - // - return VerifyHeaderChecksum (FfsHeader); - - case EFI_FILE_HEADER_CONSTRUCTION: - case EFI_FILE_HEADER_INVALID: - default: - return FALSE; + case EFI_FILE_HEADER_VALID: + case EFI_FILE_DATA_VALID: + case EFI_FILE_MARKED_FOR_UPDATE: + case EFI_FILE_DELETED: + // + // Here we need to verify header checksum + // + return VerifyHeaderChecksum (FfsHeader); + + case EFI_FILE_HEADER_CONSTRUCTION: + case EFI_FILE_HEADER_INVALID: + default: + return FALSE; } } - /** Check if it's a valid FFS file. Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first. @@ -203,25 +194,23 @@ IsValidFfsFile ( FileState = GetFileState (ErasePolarity, FfsHeader); switch (FileState) { + case EFI_FILE_DELETED: + case EFI_FILE_DATA_VALID: + case EFI_FILE_MARKED_FOR_UPDATE: + DataCheckSum = FFS_FIXED_CHECKSUM; + if ((FfsHeader->Attributes & FFS_ATTRIB_CHECKSUM) == FFS_ATTRIB_CHECKSUM) { + if (IS_FFS_FILE2 (FfsHeader)) { + DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *)FfsHeader + sizeof (EFI_FFS_FILE_HEADER2), FFS_FILE2_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER2)); + } else { + DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *)FfsHeader + sizeof (EFI_FFS_FILE_HEADER), FFS_FILE_SIZE (FfsHeader) - sizeof (EFI_FFS_FILE_HEADER)); + } + } - case EFI_FILE_DELETED: - case EFI_FILE_DATA_VALID: - case EFI_FILE_MARKED_FOR_UPDATE: - DataCheckSum = FFS_FIXED_CHECKSUM; - if ((FfsHeader->Attributes & FFS_ATTRIB_CHECKSUM) == FFS_ATTRIB_CHECKSUM) { - if (IS_FFS_FILE2 (FfsHeader)) { - DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER2), FFS_FILE2_SIZE (FfsHeader) - sizeof(EFI_FFS_FILE_HEADER2)); - } else { - DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER), FFS_FILE_SIZE (FfsHeader) - sizeof(EFI_FFS_FILE_HEADER)); + if (FfsHeader->IntegrityCheck.Checksum.File == DataCheckSum) { + return TRUE; } - } - if (FfsHeader->IntegrityCheck.Checksum.File == DataCheckSum) { - return TRUE; - } - default: - return FALSE; + default: + return FALSE; } } - - diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVol.c b/MdeModulePkg/Core/Dxe/FwVol/FwVol.c index 0059b0f2d9..153bfecafa 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/FwVol.c +++ b/MdeModulePkg/Core/Dxe/FwVol/FwVol.c @@ -11,14 +11,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "FwVolDriver.h" - // // Protocol notify related globals // -VOID *gEfiFwVolBlockNotifyReg; -EFI_EVENT gEfiFwVolBlockEvent; +VOID *gEfiFwVolBlockNotifyReg; +EFI_EVENT gEfiFwVolBlockEvent; -FV_DEVICE mFvDevice = { +FV_DEVICE mFvDevice = { FV2_DEVICE_SIGNATURE, NULL, NULL, @@ -29,7 +28,7 @@ FV_DEVICE mFvDevice = { FvReadFileSection, FvWriteFile, FvGetNextFile, - sizeof (UINTN), + sizeof (UINTN), NULL, FvGetVolumeInfo, FvSetVolumeInfo @@ -38,17 +37,17 @@ FV_DEVICE mFvDevice = { NULL, NULL, NULL, - { NULL, NULL }, + { NULL, NULL}, 0, 0, FALSE, FALSE }; - // // FFS helper functions // + /** Read data from Firmware Block by FVB protocol Read. The data may cross the multi block ranges. @@ -68,27 +67,27 @@ FV_DEVICE mFvDevice = { **/ EFI_STATUS ReadFvbData ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, - IN OUT EFI_LBA *StartLba, - IN OUT UINTN *Offset, - IN UINTN DataSize, - OUT UINT8 *Data + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, + IN OUT EFI_LBA *StartLba, + IN OUT UINTN *Offset, + IN UINTN DataSize, + OUT UINT8 *Data ) { - UINTN BlockSize; - UINTN NumberOfBlocks; - UINTN BlockIndex; - UINTN ReadDataSize; - EFI_STATUS Status; + UINTN BlockSize; + UINTN NumberOfBlocks; + UINTN BlockIndex; + UINTN ReadDataSize; + EFI_STATUS Status; // // Try read data in current block // BlockIndex = 0; ReadDataSize = DataSize; - Status = Fvb->Read (Fvb, *StartLba, *Offset, &ReadDataSize, Data); + Status = Fvb->Read (Fvb, *StartLba, *Offset, &ReadDataSize, Data); if (Status == EFI_SUCCESS) { - *Offset += DataSize; + *Offset += DataSize; return EFI_SUCCESS; } else if (Status != EFI_BAD_BUFFER_SIZE) { // @@ -118,9 +117,10 @@ ReadFvbData ( if (EFI_ERROR (Status)) { return Status; } - Data += BlockSize; + + Data += BlockSize; DataSize -= BlockSize; - BlockIndex ++; + BlockIndex++; } // @@ -150,7 +150,7 @@ ReadFvbData ( // Update Lba and Offset used by the following read. // *StartLba += BlockIndex; - *Offset = DataSize; + *Offset = DataSize; return EFI_SUCCESS; } @@ -173,8 +173,8 @@ ReadFvbData ( **/ EFI_STATUS GetFwVolHeader ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, - OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb, + OUT EFI_FIRMWARE_VOLUME_HEADER **FwVolHeader ) { EFI_STATUS Status; @@ -187,10 +187,10 @@ GetFwVolHeader ( // // Read the standard FV header // - StartLba = 0; - Offset = 0; + StartLba = 0; + Offset = 0; FvhLength = sizeof (EFI_FIRMWARE_VOLUME_HEADER); - Status = ReadFvbData (Fvb, &StartLba, &Offset, FvhLength, (UINT8 *)&TempFvh); + Status = ReadFvbData (Fvb, &StartLba, &Offset, FvhLength, (UINT8 *)&TempFvh); if (EFI_ERROR (Status)) { return Status; } @@ -207,7 +207,8 @@ GetFwVolHeader ( // understand it... // if ((!CompareGuid (&TempFvh.FileSystemGuid, &gEfiFirmwareFileSystem2Guid)) && - (!CompareGuid (&TempFvh.FileSystemGuid, &gEfiFirmwareFileSystem3Guid))) { + (!CompareGuid (&TempFvh.FileSystemGuid, &gEfiFirmwareFileSystem3Guid))) + { return EFI_INVALID_PARAMETER; } @@ -228,8 +229,8 @@ GetFwVolHeader ( // Read the rest of the header // FvhLength = TempFvh.HeaderLength - sizeof (EFI_FIRMWARE_VOLUME_HEADER); - Buffer = (UINT8 *)*FwVolHeader + sizeof (EFI_FIRMWARE_VOLUME_HEADER); - Status = ReadFvbData (Fvb, &StartLba, &Offset, FvhLength, Buffer); + Buffer = (UINT8 *)*FwVolHeader + sizeof (EFI_FIRMWARE_VOLUME_HEADER); + Status = ReadFvbData (Fvb, &StartLba, &Offset, FvhLength, Buffer); if (EFI_ERROR (Status)) { // // Read failed so free buffer @@ -240,8 +241,6 @@ GetFwVolHeader ( return Status; } - - /** Free FvDevice resource when error happens @@ -253,8 +252,8 @@ FreeFvDeviceResource ( IN FV_DEVICE *FvDevice ) { - FFS_FILE_LIST_ENTRY *FfsFileEntry; - LIST_ENTRY *NextEntry; + FFS_FILE_LIST_ENTRY *FfsFileEntry; + LIST_ENTRY *NextEntry; // // Free File List Entry @@ -279,7 +278,7 @@ FreeFvDeviceResource ( CoreFreePool (FfsFileEntry); - FfsFileEntry = (FFS_FILE_LIST_ENTRY *) NextEntry; + FfsFileEntry = (FFS_FILE_LIST_ENTRY *)NextEntry; } if (!FvDevice->IsMemoryMapped) { @@ -297,8 +296,6 @@ FreeFvDeviceResource ( return; } - - /** Check if an FV is consistent and allocate cache for it. @@ -314,30 +311,30 @@ FvCheck ( IN OUT FV_DEVICE *FvDevice ) { - EFI_STATUS Status; - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader; - EFI_FVB_ATTRIBUTES_2 FvbAttributes; - EFI_FV_BLOCK_MAP_ENTRY *BlockMap; - FFS_FILE_LIST_ENTRY *FfsFileEntry; - EFI_FFS_FILE_HEADER *FfsHeader; - UINT8 *CacheLocation; - UINTN Index; - EFI_LBA LbaIndex; - UINTN Size; - EFI_FFS_FILE_STATE FileState; - UINT8 *TopFvAddress; - UINTN TestLength; - EFI_PHYSICAL_ADDRESS PhysicalAddress; - BOOLEAN FileCached; - UINTN WholeFileSize; - EFI_FFS_FILE_HEADER *CacheFfsHeader; - - FileCached = FALSE; + EFI_STATUS Status; + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader; + EFI_FVB_ATTRIBUTES_2 FvbAttributes; + EFI_FV_BLOCK_MAP_ENTRY *BlockMap; + FFS_FILE_LIST_ENTRY *FfsFileEntry; + EFI_FFS_FILE_HEADER *FfsHeader; + UINT8 *CacheLocation; + UINTN Index; + EFI_LBA LbaIndex; + UINTN Size; + EFI_FFS_FILE_STATE FileState; + UINT8 *TopFvAddress; + UINTN TestLength; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + BOOLEAN FileCached; + UINTN WholeFileSize; + EFI_FFS_FILE_HEADER *CacheFfsHeader; + + FileCached = FALSE; CacheFfsHeader = NULL; - Fvb = FvDevice->Fvb; + Fvb = FvDevice->Fvb; FwVolHeader = FvDevice->FwVolHeader; Status = Fvb->GetAttributes (Fvb, &FvbAttributes); @@ -345,7 +342,7 @@ FvCheck ( return Status; } - Size = (UINTN) FwVolHeader->FvLength; + Size = (UINTN)FwVolHeader->FvLength; if ((FvbAttributes & EFI_FVB2_MEMORY_MAPPED) != 0) { FvDevice->IsMemoryMapped = TRUE; @@ -357,10 +354,10 @@ FvCheck ( // // Don't cache memory mapped FV really. // - FvDevice->CachedFv = (UINT8 *) (UINTN) PhysicalAddress; + FvDevice->CachedFv = (UINT8 *)(UINTN)PhysicalAddress; } else { FvDevice->IsMemoryMapped = FALSE; - FvDevice->CachedFv = AllocatePool (Size); + FvDevice->CachedFv = AllocatePool (Size); if (FvDevice->CachedFv == NULL) { return EFI_OUT_OF_RESOURCES; @@ -376,9 +373,9 @@ FvCheck ( // // Copy FV into memory using the block map. // - BlockMap = FwVolHeader->BlockMap; + BlockMap = FwVolHeader->BlockMap; CacheLocation = FvDevice->CachedFv; - LbaIndex = 0; + LbaIndex = 0; while ((BlockMap->NumBlocks != 0) || (BlockMap->Length != 0)) { // // read the FV data @@ -417,7 +414,6 @@ FvCheck ( FvDevice->ErasePolarity = 0; } - // // go through the whole FV cache, check the consistence of the FV. // Make a linked list of all the Ffs file headers @@ -432,21 +428,21 @@ FvCheck ( // // Searching for files starts on an 8 byte aligned boundary after the end of the Extended Header if it exists. // - FwVolExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) (FvDevice->CachedFv + FwVolHeader->ExtHeaderOffset); - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FwVolExtHeader + FwVolExtHeader->ExtHeaderSize); + FwVolExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(FvDevice->CachedFv + FwVolHeader->ExtHeaderOffset); + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FwVolExtHeader + FwVolExtHeader->ExtHeaderSize); } else { - FfsHeader = (EFI_FFS_FILE_HEADER *) (FvDevice->CachedFv + FwVolHeader->HeaderLength); + FfsHeader = (EFI_FFS_FILE_HEADER *)(FvDevice->CachedFv + FwVolHeader->HeaderLength); } - FfsHeader = (EFI_FFS_FILE_HEADER *) ALIGN_POINTER (FfsHeader, 8); - TopFvAddress = FvDevice->EndOfCachedFv; - while (((UINTN) FfsHeader >= (UINTN) FvDevice->CachedFv) && ((UINTN) FfsHeader <= (UINTN) ((UINTN) TopFvAddress - sizeof (EFI_FFS_FILE_HEADER)))) { + FfsHeader = (EFI_FFS_FILE_HEADER *)ALIGN_POINTER (FfsHeader, 8); + TopFvAddress = FvDevice->EndOfCachedFv; + while (((UINTN)FfsHeader >= (UINTN)FvDevice->CachedFv) && ((UINTN)FfsHeader <= (UINTN)((UINTN)TopFvAddress - sizeof (EFI_FFS_FILE_HEADER)))) { if (FileCached) { CoreFreePool (CacheFfsHeader); FileCached = FALSE; } - TestLength = TopFvAddress - ((UINT8 *) FfsHeader); + TestLength = TopFvAddress - ((UINT8 *)FfsHeader); if (TestLength > sizeof (EFI_FFS_FILE_HEADER)) { TestLength = sizeof (EFI_FFS_FILE_HEADER); } @@ -460,15 +456,18 @@ FvCheck ( if (!IsValidFfsHeader (FvDevice->ErasePolarity, FfsHeader, &FileState)) { if ((FileState == EFI_FILE_HEADER_INVALID) || - (FileState == EFI_FILE_HEADER_CONSTRUCTION)) { + (FileState == EFI_FILE_HEADER_CONSTRUCTION)) + { if (IS_FFS_FILE2 (FfsHeader)) { if (!FvDevice->IsFfs3Fv) { DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsHeader->Name)); } - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER2)); + + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsHeader + sizeof (EFI_FFS_FILE_HEADER2)); } else { - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsHeader + sizeof (EFI_FFS_FILE_HEADER)); + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsHeader + sizeof (EFI_FFS_FILE_HEADER)); } + continue; } else { // @@ -487,12 +486,13 @@ FvCheck ( // Here is to cache FFS file to memory buffer for following checksum calculating. // And then, the cached file buffer can be also used for FvReadFile. // - WholeFileSize = IS_FFS_FILE2 (CacheFfsHeader) ? FFS_FILE2_SIZE (CacheFfsHeader): FFS_FILE_SIZE (CacheFfsHeader); + WholeFileSize = IS_FFS_FILE2 (CacheFfsHeader) ? FFS_FILE2_SIZE (CacheFfsHeader) : FFS_FILE_SIZE (CacheFfsHeader); CacheFfsHeader = AllocateCopyPool (WholeFileSize, CacheFfsHeader); if (CacheFfsHeader == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } + FileCached = TRUE; } } @@ -509,11 +509,11 @@ FvCheck ( ASSERT (FFS_FILE2_SIZE (CacheFfsHeader) > 0x00FFFFFF); if (!FvDevice->IsFfs3Fv) { DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &CacheFfsHeader->Name)); - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsHeader + FFS_FILE2_SIZE (CacheFfsHeader)); + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsHeader + FFS_FILE2_SIZE (CacheFfsHeader)); // // Adjust pointer to the next 8-byte aligned boundary. // - FfsHeader = (EFI_FFS_FILE_HEADER *) (((UINTN) FfsHeader + 7) & ~0x07); + FfsHeader = (EFI_FFS_FILE_HEADER *)(((UINTN)FfsHeader + 7) & ~0x07); continue; } } @@ -533,23 +533,22 @@ FvCheck ( goto Done; } - FfsFileEntry->FfsHeader = CacheFfsHeader; + FfsFileEntry->FfsHeader = CacheFfsHeader; FfsFileEntry->FileCached = FileCached; - FileCached = FALSE; + FileCached = FALSE; InsertTailList (&FvDevice->FfsFileListHeader, &FfsFileEntry->Link); } if (IS_FFS_FILE2 (CacheFfsHeader)) { - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsHeader + FFS_FILE2_SIZE (CacheFfsHeader)); + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsHeader + FFS_FILE2_SIZE (CacheFfsHeader)); } else { - FfsHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsHeader + FFS_FILE_SIZE (CacheFfsHeader)); + FfsHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsHeader + FFS_FILE_SIZE (CacheFfsHeader)); } // // Adjust pointer to the next 8-byte aligned boundary. // FfsHeader = (EFI_FFS_FILE_HEADER *)(((UINTN)FfsHeader + 7) & ~0x07); - } Done: @@ -558,14 +557,13 @@ Done: CoreFreePool (CacheFfsHeader); FileCached = FALSE; } + FreeFvDeviceResource (FvDevice); } return Status; } - - /** This notification function is invoked when an instance of the EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL is produced. It layers an instance of the @@ -579,32 +577,33 @@ Done: VOID EFIAPI NotifyFwVolBlock ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_HANDLE Handle; - EFI_STATUS Status; - UINTN BufferSize; - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - FV_DEVICE *FvDevice; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_HANDLE Handle; + EFI_STATUS Status; + UINTN BufferSize; + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; + FV_DEVICE *FvDevice; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + // // Examine all new handles // - for (;;) { + for ( ; ;) { // // Get the next handle // BufferSize = sizeof (Handle); - Status = CoreLocateHandle ( - ByRegisterNotify, - NULL, - gEfiFwVolBlockNotifyReg, - &BufferSize, - &Handle - ); + Status = CoreLocateHandle ( + ByRegisterNotify, + NULL, + gEfiFwVolBlockNotifyReg, + &BufferSize, + &Handle + ); // // If not found, we're done @@ -631,6 +630,7 @@ NotifyFwVolBlock ( if (EFI_ERROR (Status)) { continue; } + ASSERT (FwVolHeader != NULL); if (!VerifyFvHeaderChecksum (FwVolHeader)) { @@ -653,7 +653,6 @@ NotifyFwVolBlock ( // FvDevice->Fvb = Fvb; } - } else { // // No FwVol protocol on the handle so create a new one @@ -678,11 +677,11 @@ NotifyFwVolBlock ( // Install an New FV protocol on the existing handle // Status = CoreInstallProtocolInterface ( - &Handle, - &gEfiFirmwareVolume2ProtocolGuid, - EFI_NATIVE_INTERFACE, - &FvDevice->Fv - ); + &Handle, + &gEfiFirmwareVolume2ProtocolGuid, + EFI_NATIVE_INTERFACE, + &FvDevice->Fv + ); ASSERT_EFI_ERROR (Status); } else { // @@ -696,8 +695,6 @@ NotifyFwVolBlock ( return; } - - /** This routine is the driver initialization entry point. It registers a notification function. This notification function are responsible @@ -712,8 +709,8 @@ NotifyFwVolBlock ( EFI_STATUS EFIAPI FwVolDriverInit ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { gEfiFwVolBlockEvent = EfiCreateProtocolNotifyEvent ( diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c index ab7b3feff3..eed9f86305 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c +++ b/MdeModulePkg/Core/Dxe/FwVol/FwVolAttrib.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "FwVolDriver.h" - /** Retrieves attributes, insures positive polarity of attribute bits, returns resulting attributes in output parameter. @@ -23,17 +22,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI FvGetVolumeAttributes ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - OUT EFI_FV_ATTRIBUTES *Attributes + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + OUT EFI_FV_ATTRIBUTES *Attributes ) { - EFI_STATUS Status; - FV_DEVICE *FvDevice; - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; - EFI_FVB_ATTRIBUTES_2 FvbAttributes; + EFI_STATUS Status; + FV_DEVICE *FvDevice; + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; + EFI_FVB_ATTRIBUTES_2 FvbAttributes; FvDevice = FV_DEVICE_FROM_THIS (This); - Fvb = FvDevice->Fvb; + Fvb = FvDevice->Fvb; // // First get the Firmware Volume Block Attributes @@ -50,8 +49,6 @@ FvGetVolumeAttributes ( return Status; } - - /** Sets current attributes for volume @@ -72,7 +69,6 @@ FvSetVolumeAttributes ( return EFI_UNSUPPORTED; } - /** Return information of type InformationType for the requested firmware volume. @@ -89,17 +85,15 @@ FvSetVolumeAttributes ( EFI_STATUS EFIAPI FvGetVolumeInfo ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *InformationType, - IN OUT UINTN *BufferSize, - OUT VOID *Buffer + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *InformationType, + IN OUT UINTN *BufferSize, + OUT VOID *Buffer ) { return EFI_UNSUPPORTED; } - - /** Set information of type InformationType for the requested firmware volume. @@ -116,14 +110,11 @@ FvGetVolumeInfo ( EFI_STATUS EFIAPI FvSetVolumeInfo ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *InformationType, - IN UINTN BufferSize, - IN CONST VOID *Buffer + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *InformationType, + IN UINTN BufferSize, + IN CONST VOID *Buffer ) { return EFI_UNSUPPORTED; } - - - diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolDriver.h b/MdeModulePkg/Core/Dxe/FwVol/FwVolDriver.h index 19ad39871e..3403c812b2 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/FwVolDriver.h +++ b/MdeModulePkg/Core/Dxe/FwVol/FwVolDriver.h @@ -10,40 +10,39 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __FW_VOL_DRIVER_H_ #define __FW_VOL_DRIVER_H_ - -#define FV2_DEVICE_SIGNATURE SIGNATURE_32 ('_', 'F', 'V', '2') +#define FV2_DEVICE_SIGNATURE SIGNATURE_32 ('_', 'F', 'V', '2') // // Used to track all non-deleted files // typedef struct { - LIST_ENTRY Link; - EFI_FFS_FILE_HEADER *FfsHeader; - UINTN StreamHandle; - BOOLEAN FileCached; + LIST_ENTRY Link; + EFI_FFS_FILE_HEADER *FfsHeader; + UINTN StreamHandle; + BOOLEAN FileCached; } FFS_FILE_LIST_ENTRY; typedef struct { - UINTN Signature; - EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; - EFI_HANDLE Handle; - EFI_FIRMWARE_VOLUME2_PROTOCOL Fv; + UINTN Signature; + EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *Fvb; + EFI_HANDLE Handle; + EFI_FIRMWARE_VOLUME2_PROTOCOL Fv; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - UINT8 *CachedFv; - UINT8 *EndOfCachedFv; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + UINT8 *CachedFv; + UINT8 *EndOfCachedFv; - FFS_FILE_LIST_ENTRY *LastKey; + FFS_FILE_LIST_ENTRY *LastKey; - LIST_ENTRY FfsFileListHeader; + LIST_ENTRY FfsFileListHeader; - UINT32 AuthenticationStatus; - UINT8 ErasePolarity; - BOOLEAN IsFfs3Fv; - BOOLEAN IsMemoryMapped; + UINT32 AuthenticationStatus; + UINT8 ErasePolarity; + BOOLEAN IsFfs3Fv; + BOOLEAN IsMemoryMapped; } FV_DEVICE; -#define FV_DEVICE_FROM_THIS(a) CR(a, FV_DEVICE, Fv, FV2_DEVICE_SIGNATURE) +#define FV_DEVICE_FROM_THIS(a) CR(a, FV_DEVICE, Fv, FV2_DEVICE_SIGNATURE) /** Retrieves attributes, insures positive polarity of attribute bits, returns @@ -58,11 +57,10 @@ typedef struct { EFI_STATUS EFIAPI FvGetVolumeAttributes ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - OUT EFI_FV_ATTRIBUTES *Attributes + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + OUT EFI_FV_ATTRIBUTES *Attributes ); - /** Sets current attributes for volume @@ -80,7 +78,6 @@ FvSetVolumeAttributes ( IN OUT EFI_FV_ATTRIBUTES *Attributes ); - /** Given the input key, search for the next matching file in the volume. @@ -130,16 +127,14 @@ FvSetVolumeAttributes ( EFI_STATUS EFIAPI FvGetNextFile ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN OUT VOID *Key, - IN OUT EFI_FV_FILETYPE *FileType, - OUT EFI_GUID *NameGuid, - OUT EFI_FV_FILE_ATTRIBUTES *Attributes, - OUT UINTN *Size + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN OUT VOID *Key, + IN OUT EFI_FV_FILETYPE *FileType, + OUT EFI_GUID *NameGuid, + OUT EFI_FV_FILE_ATTRIBUTES *Attributes, + OUT UINTN *Size ); - - /** Locates a file in the firmware volume and copies it to the supplied buffer. @@ -183,16 +178,15 @@ FvGetNextFile ( EFI_STATUS EFIAPI FvReadFile ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *NameGuid, - IN OUT VOID **Buffer, - IN OUT UINTN *BufferSize, - OUT EFI_FV_FILETYPE *FoundType, - OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *NameGuid, + IN OUT VOID **Buffer, + IN OUT UINTN *BufferSize, + OUT EFI_FV_FILETYPE *FoundType, + OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes, + OUT UINT32 *AuthenticationStatus ); - /** Locates a section in a given FFS File and copies it to the supplied buffer (not including section header). @@ -233,7 +227,6 @@ FvReadFileSection ( OUT UINT32 *AuthenticationStatus ); - /** Writes one or more files to the firmware volume. @@ -264,7 +257,6 @@ FvWriteFile ( IN EFI_FV_WRITE_FILE_DATA *FileData ); - /** Return information of type InformationType for the requested firmware volume. @@ -281,14 +273,12 @@ FvWriteFile ( EFI_STATUS EFIAPI FvGetVolumeInfo ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *InformationType, - IN OUT UINTN *BufferSize, - OUT VOID *Buffer + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *InformationType, + IN OUT UINTN *BufferSize, + OUT VOID *Buffer ); - - /** Set information of type InformationType for the requested firmware volume. @@ -305,14 +295,12 @@ FvGetVolumeInfo ( EFI_STATUS EFIAPI FvSetVolumeInfo ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *InformationType, - IN UINTN BufferSize, - IN CONST VOID *Buffer + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *InformationType, + IN UINTN BufferSize, + IN CONST VOID *Buffer ); - - /** Check if a block of buffer is erased. @@ -326,12 +314,11 @@ FvSetVolumeInfo ( **/ BOOLEAN IsBufferErased ( - IN UINT8 ErasePolarity, - IN VOID *InBuffer, - IN UINTN BufferSize + IN UINT8 ErasePolarity, + IN VOID *InBuffer, + IN UINTN BufferSize ); - /** Get the FFS file state by checking the highest bit set in the header's state field. @@ -347,7 +334,6 @@ GetFileState ( IN EFI_FFS_FILE_HEADER *FfsHeader ); - /** Set the FFS file state. @@ -381,7 +367,6 @@ IsValidFfsHeader ( OUT EFI_FFS_FILE_STATE *FileState ); - /** Check if it's a valid FFS file. Here we are sure that it has a valid FFS file header since we must call IsValidFfsHeader() first. diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c index 8dcbbeb5ee..2ff22c93aa 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c +++ b/MdeModulePkg/Core/Dxe/FwVol/FwVolRead.c @@ -29,8 +29,8 @@ Required Alignment Alignment Value in FFS FFS_ATTRIB_DATA_ALIGNMENT2 Align 8 MB 6 1 23 16 MB 7 1 24 **/ -UINT8 mFvAttributes[] = {0, 4, 7, 9, 10, 12, 15, 16}; -UINT8 mFvAttributes2[] = {17, 18, 19, 20, 21, 22, 23, 24}; +UINT8 mFvAttributes[] = { 0, 4, 7, 9, 10, 12, 15, 16 }; +UINT8 mFvAttributes2[] = { 17, 18, 19, 20, 21, 22, 23, 24 }; /** Convert the FFS File Attributes to FV File Attributes @@ -42,19 +42,19 @@ UINT8 mFvAttributes2[] = {17, 18, 19, 20, 21, 22, 23, 24}; **/ EFI_FV_FILE_ATTRIBUTES FfsAttributes2FvFileAttributes ( - IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes + IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes ) { - UINT8 DataAlignment; - EFI_FV_FILE_ATTRIBUTES FileAttribute; + UINT8 DataAlignment; + EFI_FV_FILE_ATTRIBUTES FileAttribute; - DataAlignment = (UINT8) ((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3); + DataAlignment = (UINT8)((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3); ASSERT (DataAlignment < 8); if ((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT_2) != 0) { - FileAttribute = (EFI_FV_FILE_ATTRIBUTES) mFvAttributes2[DataAlignment]; + FileAttribute = (EFI_FV_FILE_ATTRIBUTES)mFvAttributes2[DataAlignment]; } else { - FileAttribute = (EFI_FV_FILE_ATTRIBUTES) mFvAttributes[DataAlignment]; + FileAttribute = (EFI_FV_FILE_ATTRIBUTES)mFvAttributes[DataAlignment]; } if ((FfsAttributes & FFS_ATTRIB_FIXED) == FFS_ATTRIB_FIXED) { @@ -113,26 +113,26 @@ FfsAttributes2FvFileAttributes ( EFI_STATUS EFIAPI FvGetNextFile ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN OUT VOID *Key, - IN OUT EFI_FV_FILETYPE *FileType, - OUT EFI_GUID *NameGuid, - OUT EFI_FV_FILE_ATTRIBUTES *Attributes, - OUT UINTN *Size + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN OUT VOID *Key, + IN OUT EFI_FV_FILETYPE *FileType, + OUT EFI_GUID *NameGuid, + OUT EFI_FV_FILE_ATTRIBUTES *Attributes, + OUT UINTN *Size ) { - EFI_STATUS Status; - FV_DEVICE *FvDevice; - EFI_FV_ATTRIBUTES FvAttributes; - EFI_FFS_FILE_HEADER *FfsFileHeader; - UINTN *KeyValue; - LIST_ENTRY *Link; - FFS_FILE_LIST_ENTRY *FfsFileEntry; + EFI_STATUS Status; + FV_DEVICE *FvDevice; + EFI_FV_ATTRIBUTES FvAttributes; + EFI_FFS_FILE_HEADER *FfsFileHeader; + UINTN *KeyValue; + LIST_ENTRY *Link; + FFS_FILE_LIST_ENTRY *FfsFileEntry; FvDevice = FV_DEVICE_FROM_THIS (This); Status = FvGetVolumeAttributes (This, &FvAttributes); - if (EFI_ERROR (Status)){ + if (EFI_ERROR (Status)) { return Status; } @@ -151,7 +151,7 @@ FvGetNextFile ( } KeyValue = (UINTN *)Key; - for (;;) { + for ( ; ;) { if (*KeyValue == 0) { // // Search for 1st matching file @@ -171,7 +171,7 @@ FvGetNextFile ( return EFI_NOT_FOUND; } - FfsFileEntry = (FFS_FILE_LIST_ENTRY *)Link->ForwardLink; + FfsFileEntry = (FFS_FILE_LIST_ENTRY *)Link->ForwardLink; FfsFileHeader = (EFI_FFS_FILE_HEADER *)FfsFileEntry->FfsHeader; // @@ -199,7 +199,6 @@ FvGetNextFile ( // break; } - } // @@ -224,8 +223,6 @@ FvGetNextFile ( return EFI_SUCCESS; } - - /** Locates a file in the firmware volume and copies it to the supplied buffer. @@ -269,25 +266,25 @@ FvGetNextFile ( EFI_STATUS EFIAPI FvReadFile ( - IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, - IN CONST EFI_GUID *NameGuid, - IN OUT VOID **Buffer, - IN OUT UINTN *BufferSize, - OUT EFI_FV_FILETYPE *FoundType, - OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_FIRMWARE_VOLUME2_PROTOCOL *This, + IN CONST EFI_GUID *NameGuid, + IN OUT VOID **Buffer, + IN OUT UINTN *BufferSize, + OUT EFI_FV_FILETYPE *FoundType, + OUT EFI_FV_FILE_ATTRIBUTES *FileAttributes, + OUT UINT32 *AuthenticationStatus ) { - EFI_STATUS Status; - FV_DEVICE *FvDevice; - EFI_GUID SearchNameGuid; - EFI_FV_FILETYPE LocalFoundType; - EFI_FV_FILE_ATTRIBUTES LocalAttributes; - UINTN FileSize; - UINT8 *SrcPtr; - EFI_FFS_FILE_HEADER *FfsHeader; - UINTN InputBufferSize; - UINTN WholeFileSize; + EFI_STATUS Status; + FV_DEVICE *FvDevice; + EFI_GUID SearchNameGuid; + EFI_FV_FILETYPE LocalFoundType; + EFI_FV_FILE_ATTRIBUTES LocalAttributes; + UINTN FileSize; + UINT8 *SrcPtr; + EFI_FFS_FILE_HEADER *FfsHeader; + UINTN InputBufferSize; + UINTN WholeFileSize; if (NameGuid == NULL) { return EFI_INVALID_PARAMETER; @@ -295,7 +292,6 @@ FvReadFile ( FvDevice = FV_DEVICE_FROM_THIS (This); - // // Keep looking until we find the matching NameGuid. // The Key is really a FfsFileEntry @@ -303,14 +299,14 @@ FvReadFile ( FvDevice->LastKey = 0; do { LocalFoundType = 0; - Status = FvGetNextFile ( - This, - &FvDevice->LastKey, - &LocalFoundType, - &SearchNameGuid, - &LocalAttributes, - &FileSize - ); + Status = FvGetNextFile ( + This, + &FvDevice->LastKey, + &LocalFoundType, + &SearchNameGuid, + &LocalAttributes, + &FileSize + ); if (EFI_ERROR (Status)) { return EFI_NOT_FOUND; } @@ -328,15 +324,16 @@ FvReadFile ( // // Cache FFS file to memory buffer. // - WholeFileSize = IS_FFS_FILE2 (FfsHeader) ? FFS_FILE2_SIZE (FfsHeader): FFS_FILE_SIZE (FfsHeader); - FfsHeader = AllocateCopyPool (WholeFileSize, FfsHeader); + WholeFileSize = IS_FFS_FILE2 (FfsHeader) ? FFS_FILE2_SIZE (FfsHeader) : FFS_FILE_SIZE (FfsHeader); + FfsHeader = AllocateCopyPool (WholeFileSize, FfsHeader); if (FfsHeader == NULL) { return EFI_OUT_OF_RESOURCES; } + // // Let FfsHeader in FfsFileEntry point to the cached file buffer. // - FvDevice->LastKey->FfsHeader = FfsHeader; + FvDevice->LastKey->FfsHeader = FfsHeader; FvDevice->LastKey->FileCached = TRUE; } } @@ -349,16 +346,17 @@ FvReadFile ( // // Calculate return values // - *FoundType = FfsHeader->Type; + *FoundType = FfsHeader->Type; *FileAttributes = FfsAttributes2FvFileAttributes (FfsHeader->Attributes); - if ((FvDevice->FwVolHeader->Attributes & EFI_FVB2_MEMORY_MAPPED) == EFI_FVB2_MEMORY_MAPPED) { - *FileAttributes |= EFI_FV_FILE_ATTRIB_MEMORY_MAPPED; - } + if ((FvDevice->FwVolHeader->Attributes & EFI_FVB2_MEMORY_MAPPED) == EFI_FVB2_MEMORY_MAPPED) { + *FileAttributes |= EFI_FV_FILE_ATTRIB_MEMORY_MAPPED; + } + // // Inherit the authentication status. // *AuthenticationStatus = FvDevice->AuthenticationStatus; - *BufferSize = FileSize; + *BufferSize = FileSize; if (Buffer == NULL) { // @@ -371,9 +369,9 @@ FvReadFile ( // Skip over file header // if (IS_FFS_FILE2 (FfsHeader)) { - SrcPtr = ((UINT8 *) FfsHeader) + sizeof (EFI_FFS_FILE_HEADER2); + SrcPtr = ((UINT8 *)FfsHeader) + sizeof (EFI_FFS_FILE_HEADER2); } else { - SrcPtr = ((UINT8 *) FfsHeader) + sizeof (EFI_FFS_FILE_HEADER); + SrcPtr = ((UINT8 *)FfsHeader) + sizeof (EFI_FFS_FILE_HEADER); } Status = EFI_SUCCESS; @@ -389,7 +387,7 @@ FvReadFile ( // // Callers buffer was not big enough // - Status = EFI_WARN_BUFFER_TOO_SMALL; + Status = EFI_WARN_BUFFER_TOO_SMALL; FileSize = InputBufferSize; } @@ -401,8 +399,6 @@ FvReadFile ( return Status; } - - /** Locates a section in a given FFS File and copies it to the supplied buffer (not including section header). @@ -443,15 +439,15 @@ FvReadFileSection ( OUT UINT32 *AuthenticationStatus ) { - EFI_STATUS Status; - FV_DEVICE *FvDevice; - EFI_FV_FILETYPE FileType; - EFI_FV_FILE_ATTRIBUTES FileAttributes; - UINTN FileSize; - UINT8 *FileBuffer; - FFS_FILE_LIST_ENTRY *FfsEntry; - - if (NameGuid == NULL || Buffer == NULL) { + EFI_STATUS Status; + FV_DEVICE *FvDevice; + EFI_FV_FILETYPE FileType; + EFI_FV_FILE_ATTRIBUTES FileAttributes; + UINTN FileSize; + UINT8 *FileBuffer; + FFS_FILE_LIST_ENTRY *FfsEntry; + + if ((NameGuid == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -461,27 +457,29 @@ FvReadFileSection ( // Read the file // Status = FvReadFile ( - This, - NameGuid, - NULL, - &FileSize, - &FileType, - &FileAttributes, - AuthenticationStatus - ); + This, + NameGuid, + NULL, + &FileSize, + &FileType, + &FileAttributes, + AuthenticationStatus + ); // // Get the last key used by our call to FvReadFile as it is the FfsEntry for this file. // - FfsEntry = (FFS_FILE_LIST_ENTRY *) FvDevice->LastKey; + FfsEntry = (FFS_FILE_LIST_ENTRY *)FvDevice->LastKey; if (EFI_ERROR (Status)) { return Status; } + if (IS_FFS_FILE2 (FfsEntry->FfsHeader)) { - FileBuffer = ((UINT8 *) FfsEntry->FfsHeader) + sizeof (EFI_FFS_FILE_HEADER2); + FileBuffer = ((UINT8 *)FfsEntry->FfsHeader) + sizeof (EFI_FFS_FILE_HEADER2); } else { - FileBuffer = ((UINT8 *) FfsEntry->FfsHeader) + sizeof (EFI_FFS_FILE_HEADER); + FileBuffer = ((UINT8 *)FfsEntry->FfsHeader) + sizeof (EFI_FFS_FILE_HEADER); } + // // Check to see that the file actually HAS sections before we go any further. // @@ -532,5 +530,3 @@ FvReadFileSection ( Done: return Status; } - - diff --git a/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c b/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c index 3a3b569b74..6e3a59bc4c 100644 --- a/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c +++ b/MdeModulePkg/Core/Dxe/FwVol/FwVolWrite.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "FwVolDriver.h" - /** Writes one or more files to the firmware volume. @@ -42,5 +41,3 @@ FvWriteFile ( { return EFI_UNSUPPORTED; } - - diff --git a/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c b/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c index 95174c1e46..d81334ce24 100644 --- a/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c +++ b/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c @@ -12,7 +12,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "FwVolBlock.h" -FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = { +FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = { { { HARDWARE_DEVICE_PATH, @@ -23,8 +23,8 @@ FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = { } }, EfiMemoryMappedIO, - (EFI_PHYSICAL_ADDRESS) 0, - (EFI_PHYSICAL_ADDRESS) 0, + (EFI_PHYSICAL_ADDRESS)0, + (EFI_PHYSICAL_ADDRESS)0, }, { END_DEVICE_PATH_TYPE, @@ -36,7 +36,7 @@ FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = { } }; -FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = { +FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = { { { MEDIA_DEVICE_PATH, @@ -79,8 +79,6 @@ EFI_FW_VOL_BLOCK_DEVICE mFwVolBlock = { 0 }; - - /** Retrieves Volume attributes. No polarity translations are done. @@ -97,7 +95,7 @@ FwVolBlockGetAttributes ( OUT EFI_FVB_ATTRIBUTES_2 *Attributes ) { - EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; + EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; FvbDevice = FVB_DEVICE_FROM_THIS (This); @@ -109,8 +107,6 @@ FwVolBlockGetAttributes ( return EFI_SUCCESS; } - - /** Modifies the current settings of the firmware volume according to the input parameter. @@ -134,8 +130,6 @@ FwVolBlockSetAttributes ( return EFI_UNSUPPORTED; } - - /** The EraseBlock() function erases one or more blocks as denoted by the variable argument list. The entire parameter list of blocks must be verified @@ -162,15 +156,13 @@ FwVolBlockSetAttributes ( EFI_STATUS EFIAPI FwVolBlockEraseBlock ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, ... ) { return EFI_UNSUPPORTED; } - - /** Read the specified number of bytes from the block to the input buffer. @@ -194,19 +186,19 @@ FwVolBlockEraseBlock ( EFI_STATUS EFIAPI FwVolBlockReadBlock ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, - IN CONST EFI_LBA Lba, - IN CONST UINTN Offset, - IN OUT UINTN *NumBytes, - IN OUT UINT8 *Buffer + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN CONST EFI_LBA Lba, + IN CONST UINTN Offset, + IN OUT UINTN *NumBytes, + IN OUT UINT8 *Buffer ) { - EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - UINT8 *LbaOffset; - UINTN LbaStart; - UINTN NumOfBytesRead; - UINTN LbaIndex; + EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + UINT8 *LbaOffset; + UINTN LbaStart; + UINTN NumOfBytesRead; + UINTN LbaIndex; FvbDevice = FVB_DEVICE_FROM_THIS (This); @@ -217,7 +209,7 @@ FwVolBlockReadBlock ( return EFI_ACCESS_DENIED; } - LbaIndex = (UINTN) Lba; + LbaIndex = (UINTN)Lba; if (LbaIndex >= FvbDevice->NumBlocks) { // // Invalid Lba, read nothing. @@ -242,9 +234,9 @@ FwVolBlockReadBlock ( NumOfBytesRead = FvbDevice->LbaCache[LbaIndex].Length - Offset; } - LbaStart = FvbDevice->LbaCache[LbaIndex].Base; - FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINTN) FvbDevice->BaseAddress); - LbaOffset = (UINT8 *) FwVolHeader + LbaStart + Offset; + LbaStart = FvbDevice->LbaCache[LbaIndex].Base; + FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINTN)FvbDevice->BaseAddress); + LbaOffset = (UINT8 *)FwVolHeader + LbaStart + Offset; // // Perform read operation @@ -259,8 +251,6 @@ FwVolBlockReadBlock ( return EFI_BAD_BUFFER_SIZE; } - - /** Writes the specified number of bytes from the input buffer to the block. @@ -288,18 +278,16 @@ FwVolBlockReadBlock ( EFI_STATUS EFIAPI FwVolBlockWriteBlock ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer ) { return EFI_UNSUPPORTED; } - - /** Get Fvb's base address. @@ -317,7 +305,7 @@ FwVolBlockGetPhysicalAddress ( OUT EFI_PHYSICAL_ADDRESS *Address ) { - EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; + EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; FvbDevice = FVB_DEVICE_FROM_THIS (This); @@ -329,8 +317,6 @@ FwVolBlockGetPhysicalAddress ( return EFI_UNSUPPORTED; } - - /** Retrieves the size in bytes of a specific block within a firmware volume. @@ -357,10 +343,10 @@ FwVolBlockGetBlockSize ( IN OUT UINTN *NumberOfBlocks ) { - UINTN TotalBlocks; - EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; - EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + UINTN TotalBlocks; + EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; + EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; FvbDevice = FVB_DEVICE_FROM_THIS (This); @@ -379,7 +365,7 @@ FwVolBlockGetBlockSize ( // Search the block map for the given block // TotalBlocks = 0; - while ((PtrBlockMapEntry->NumBlocks != 0) || (PtrBlockMapEntry->Length !=0 )) { + while ((PtrBlockMapEntry->NumBlocks != 0) || (PtrBlockMapEntry->Length != 0)) { TotalBlocks += PtrBlockMapEntry->NumBlocks; if (Lba < TotalBlocks) { // @@ -391,7 +377,7 @@ FwVolBlockGetBlockSize ( PtrBlockMapEntry++; } - *BlockSize = PtrBlockMapEntry->Length; + *BlockSize = PtrBlockMapEntry->Length; *NumberOfBlocks = TotalBlocks - (UINTN)Lba; return EFI_SUCCESS; @@ -408,14 +394,14 @@ FwVolBlockGetBlockSize ( **/ UINT32 GetFvbAuthenticationStatus ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *FvbProtocol ) { - EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; - UINT32 AuthenticationStatus; + EFI_FW_VOL_BLOCK_DEVICE *FvbDevice; + UINT32 AuthenticationStatus; AuthenticationStatus = 0; - FvbDevice = BASE_CR (FvbProtocol, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance); + FvbDevice = BASE_CR (FvbProtocol, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance); if (FvbDevice->Signature == FVB_DEVICE_SIGNATURE) { AuthenticationStatus = FvbDevice->AuthenticationStatus; } @@ -444,24 +430,24 @@ GetFvbAuthenticationStatus ( **/ EFI_STATUS ProduceFVBProtocolOnBuffer ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN EFI_HANDLE ParentHandle, - IN UINT32 AuthenticationStatus, - OUT EFI_HANDLE *FvProtocol OPTIONAL + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN EFI_HANDLE ParentHandle, + IN UINT32 AuthenticationStatus, + OUT EFI_HANDLE *FvProtocol OPTIONAL ) { - EFI_STATUS Status; - EFI_FW_VOL_BLOCK_DEVICE *FvbDev; - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - UINTN BlockIndex; - UINTN BlockIndex2; - UINTN LinearOffset; - UINT32 FvAlignment; - EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry; + EFI_STATUS Status; + EFI_FW_VOL_BLOCK_DEVICE *FvbDev; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + UINTN BlockIndex; + UINTN BlockIndex2; + UINTN LinearOffset; + UINT32 FvAlignment; + EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry; FvAlignment = 0; - FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN) BaseAddress; + FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)BaseAddress; // // Validate FV Header, if not as expected, return // @@ -485,6 +471,7 @@ ProduceFVBProtocolOnBuffer ( if (FvAlignment < 8) { FvAlignment = 8; } + if ((UINTN)BaseAddress % FvAlignment != 0) { // // FvImage buffer is not at its required alignment. @@ -508,10 +495,10 @@ ProduceFVBProtocolOnBuffer ( return EFI_OUT_OF_RESOURCES; } - FvbDev->BaseAddress = BaseAddress; - FvbDev->FvbAttributes = FwVolHeader->Attributes; + FvbDev->BaseAddress = BaseAddress; + FvbDev->FvbAttributes = FwVolHeader->Attributes; FvbDev->FwVolBlockInstance.ParentHandle = ParentHandle; - FvbDev->AuthenticationStatus = AuthenticationStatus; + FvbDev->AuthenticationStatus = AuthenticationStatus; // // Init the block caching fields of the device @@ -520,7 +507,8 @@ ProduceFVBProtocolOnBuffer ( FvbDev->NumBlocks = 0; for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; - PtrBlockMapEntry++) { + PtrBlockMapEntry++) + { FvbDev->NumBlocks += PtrBlockMapEntry->NumBlocks; } @@ -531,6 +519,7 @@ ProduceFVBProtocolOnBuffer ( CoreFreePool (FvbDev); return EFI_OUT_OF_RESOURCES; } + FvbDev->LbaCache = AllocatePool (FvbDev->NumBlocks * sizeof (LBA_CACHE)); if (FvbDev->LbaCache == NULL) { CoreFreePool (FvbDev); @@ -540,14 +529,15 @@ ProduceFVBProtocolOnBuffer ( // // Last, fill in the cache with the linear address of the blocks // - BlockIndex = 0; + BlockIndex = 0; LinearOffset = 0; for (PtrBlockMapEntry = FwVolHeader->BlockMap; - PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) { + PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) + { for (BlockIndex2 = 0; BlockIndex2 < PtrBlockMapEntry->NumBlocks; BlockIndex2++) { - FvbDev->LbaCache[BlockIndex].Base = LinearOffset; + FvbDev->LbaCache[BlockIndex].Base = LinearOffset; FvbDev->LbaCache[BlockIndex].Length = PtrBlockMapEntry->Length; - LinearOffset += PtrBlockMapEntry->Length; + LinearOffset += PtrBlockMapEntry->Length; BlockIndex++; } } @@ -559,22 +549,24 @@ ProduceFVBProtocolOnBuffer ( // // FV does not contains extension header, then produce MEMMAP_DEVICE_PATH // - FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) AllocateCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate); + FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)AllocateCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate); if (FvbDev->DevicePath == NULL) { FreePool (FvbDev); return EFI_OUT_OF_RESOURCES; } - ((FV_MEMMAP_DEVICE_PATH *) FvbDev->DevicePath)->MemMapDevPath.StartingAddress = BaseAddress; - ((FV_MEMMAP_DEVICE_PATH *) FvbDev->DevicePath)->MemMapDevPath.EndingAddress = BaseAddress + FwVolHeader->FvLength - 1; + + ((FV_MEMMAP_DEVICE_PATH *)FvbDev->DevicePath)->MemMapDevPath.StartingAddress = BaseAddress; + ((FV_MEMMAP_DEVICE_PATH *)FvbDev->DevicePath)->MemMapDevPath.EndingAddress = BaseAddress + FwVolHeader->FvLength - 1; } else { // // FV contains extension header, then produce MEDIA_FW_VOL_DEVICE_PATH // - FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) AllocateCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate); + FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)AllocateCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate); if (FvbDev->DevicePath == NULL) { FreePool (FvbDev); return EFI_OUT_OF_RESOURCES; } + CopyGuid ( &((FV_PIWG_DEVICE_PATH *)FvbDev->DevicePath)->FvDevPath.FvName, (GUID *)(UINTN)(BaseAddress + FwVolHeader->ExtHeaderOffset) @@ -587,8 +579,10 @@ ProduceFVBProtocolOnBuffer ( // Status = CoreInstallMultipleProtocolInterfaces ( &FvbDev->Handle, - &gEfiFirmwareVolumeBlockProtocolGuid, &FvbDev->FwVolBlockInstance, - &gEfiDevicePathProtocolGuid, FvbDev->DevicePath, + &gEfiFirmwareVolumeBlockProtocolGuid, + &FvbDev->FwVolBlockInstance, + &gEfiDevicePathProtocolGuid, + FvbDev->DevicePath, NULL ); @@ -602,8 +596,6 @@ ProduceFVBProtocolOnBuffer ( return Status; } - - /** This routine consumes FV hobs and produces instances of FW_VOL_BLOCK_PROTOCOL as appropriate. @@ -617,13 +609,13 @@ ProduceFVBProtocolOnBuffer ( EFI_STATUS EFIAPI FwVolBlockDriverInit ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_PEI_HOB_POINTERS FvHob; - EFI_PEI_HOB_POINTERS Fv3Hob; - UINT32 AuthenticationStatus; + EFI_PEI_HOB_POINTERS FvHob; + EFI_PEI_HOB_POINTERS Fv3Hob; + UINT32 AuthenticationStatus; // // Core Needs Firmware Volumes to function @@ -637,12 +629,15 @@ FwVolBlockDriverInit ( Fv3Hob.Raw = GetHobList (); while ((Fv3Hob.Raw = GetNextHob (EFI_HOB_TYPE_FV3, Fv3Hob.Raw)) != NULL) { if ((Fv3Hob.FirmwareVolume3->BaseAddress == FvHob.FirmwareVolume->BaseAddress) && - (Fv3Hob.FirmwareVolume3->Length == FvHob.FirmwareVolume->Length)) { + (Fv3Hob.FirmwareVolume3->Length == FvHob.FirmwareVolume->Length)) + { AuthenticationStatus = Fv3Hob.FirmwareVolume3->AuthenticationStatus; break; } + Fv3Hob.Raw = GET_NEXT_HOB (Fv3Hob); } + // // Produce an FVB protocol for it // @@ -653,8 +648,6 @@ FwVolBlockDriverInit ( return EFI_SUCCESS; } - - /** This DXE service routine is used to process a firmware volume. In particular, it can be called by BDS to process a single firmware @@ -679,22 +672,22 @@ FwVolBlockDriverInit ( EFI_STATUS EFIAPI CoreProcessFirmwareVolume ( - IN VOID *FvHeader, - IN UINTN Size, - OUT EFI_HANDLE *FVProtocolHandle + IN VOID *FvHeader, + IN UINTN Size, + OUT EFI_HANDLE *FVProtocolHandle ) { VOID *Ptr; EFI_STATUS Status; *FVProtocolHandle = NULL; - Status = ProduceFVBProtocolOnBuffer ( - (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, - (UINT64)Size, - NULL, - 0, - FVProtocolHandle - ); + Status = ProduceFVBProtocolOnBuffer ( + (EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader, + (UINT64)Size, + NULL, + 0, + FVProtocolHandle + ); // // Since in our implementation we use register-protocol-notify to put a // FV protocol on the FVB protocol handle, we can't directly verify that @@ -703,17 +696,16 @@ CoreProcessFirmwareVolume ( // well. Otherwise we have to assume that the volume was corrupted // somehow. // - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { ASSERT (*FVProtocolHandle != NULL); - Ptr = NULL; - Status = CoreHandleProtocol (*FVProtocolHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **) &Ptr); - if (EFI_ERROR(Status) || (Ptr == NULL)) { + Ptr = NULL; + Status = CoreHandleProtocol (*FVProtocolHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&Ptr); + if (EFI_ERROR (Status) || (Ptr == NULL)) { return EFI_VOLUME_CORRUPTED; } + return EFI_SUCCESS; } + return Status; } - - - diff --git a/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.h b/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.h index 2205e9e77d..aa2ab7f7c2 100644 --- a/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.h +++ b/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.h @@ -10,13 +10,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _FWVOL_BLOCK_H_ #define _FWVOL_BLOCK_H_ - -#define FVB_DEVICE_SIGNATURE SIGNATURE_32('_','F','V','B') - +#define FVB_DEVICE_SIGNATURE SIGNATURE_32('_','F','V','B') typedef struct { - UINTN Base; - UINTN Length; + UINTN Base; + UINTN Length; } LBA_CACHE; typedef struct { @@ -44,11 +42,9 @@ typedef struct { UINT32 AuthenticationStatus; } EFI_FW_VOL_BLOCK_DEVICE; - #define FVB_DEVICE_FROM_THIS(a) \ CR(a, EFI_FW_VOL_BLOCK_DEVICE, FwVolBlockInstance, FVB_DEVICE_SIGNATURE) - /** Retrieves Volume attributes. No polarity translations are done. @@ -65,8 +61,6 @@ FwVolBlockGetAttributes ( OUT EFI_FVB_ATTRIBUTES_2 *Attributes ); - - /** Modifies the current settings of the firmware volume according to the input parameter. @@ -87,8 +81,6 @@ FwVolBlockSetAttributes ( IN CONST EFI_FVB_ATTRIBUTES_2 *Attributes ); - - /** The EraseBlock() function erases one or more blocks as denoted by the variable argument list. The entire parameter list of blocks must be verified @@ -115,12 +107,10 @@ FwVolBlockSetAttributes ( EFI_STATUS EFIAPI FwVolBlockEraseBlock ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, ... ); - - /** Read the specified number of bytes from the block to the input buffer. @@ -144,15 +134,13 @@ FwVolBlockEraseBlock ( EFI_STATUS EFIAPI FwVolBlockReadBlock ( - IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, - IN CONST EFI_LBA Lba, - IN CONST UINTN Offset, - IN OUT UINTN *NumBytes, - IN OUT UINT8 *Buffer + IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN CONST EFI_LBA Lba, + IN CONST UINTN Offset, + IN OUT UINTN *NumBytes, + IN OUT UINT8 *Buffer ); - - /** Writes the specified number of bytes from the input buffer to the block. @@ -180,15 +168,13 @@ FwVolBlockReadBlock ( EFI_STATUS EFIAPI FwVolBlockWriteBlock ( - IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, - IN EFI_LBA Lba, - IN UINTN Offset, - IN OUT UINTN *NumBytes, - IN UINT8 *Buffer + IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This, + IN EFI_LBA Lba, + IN UINTN Offset, + IN OUT UINTN *NumBytes, + IN UINT8 *Buffer ); - - /** Get Fvb's base address. @@ -206,8 +192,6 @@ FwVolBlockGetPhysicalAddress ( OUT EFI_PHYSICAL_ADDRESS *Address ); - - /** Retrieves the size in bytes of a specific block within a firmware volume. @@ -234,5 +218,4 @@ FwVolBlockGetBlockSize ( IN OUT UINTN *NumberOfBlocks ); - #endif diff --git a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c index 2224aae281..3763467bdb 100644 --- a/MdeModulePkg/Core/Dxe/Gcd/Gcd.c +++ b/MdeModulePkg/Core/Dxe/Gcd/Gcd.c @@ -12,9 +12,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Gcd.h" #include "Mem/HeapGuard.h" -#define MINIMUM_INITIAL_MEMORY_SIZE 0x10000 +#define MINIMUM_INITIAL_MEMORY_SIZE 0x10000 -#define MEMORY_ATTRIBUTE_MASK (EFI_RESOURCE_ATTRIBUTE_PRESENT | \ +#define MEMORY_ATTRIBUTE_MASK (EFI_RESOURCE_ATTRIBUTE_PRESENT | \ EFI_RESOURCE_ATTRIBUTE_INITIALIZED | \ EFI_RESOURCE_ATTRIBUTE_TESTED | \ EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED | \ @@ -26,24 +26,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_RESOURCE_ATTRIBUTE_64_BIT_IO | \ EFI_RESOURCE_ATTRIBUTE_PERSISTENT ) -#define TESTED_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT | \ +#define TESTED_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT | \ EFI_RESOURCE_ATTRIBUTE_INITIALIZED | \ EFI_RESOURCE_ATTRIBUTE_TESTED ) -#define INITIALIZED_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT | \ +#define INITIALIZED_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT |\ EFI_RESOURCE_ATTRIBUTE_INITIALIZED ) -#define PRESENT_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT) +#define PRESENT_MEMORY_ATTRIBUTES (EFI_RESOURCE_ATTRIBUTE_PRESENT) // // Module Variables // -EFI_LOCK mGcdMemorySpaceLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -EFI_LOCK mGcdIoSpaceLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -LIST_ENTRY mGcdMemorySpaceMap = INITIALIZE_LIST_HEAD_VARIABLE (mGcdMemorySpaceMap); -LIST_ENTRY mGcdIoSpaceMap = INITIALIZE_LIST_HEAD_VARIABLE (mGcdIoSpaceMap); +EFI_LOCK mGcdMemorySpaceLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +EFI_LOCK mGcdIoSpaceLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +LIST_ENTRY mGcdMemorySpaceMap = INITIALIZE_LIST_HEAD_VARIABLE (mGcdMemorySpaceMap); +LIST_ENTRY mGcdIoSpaceMap = INITIALIZE_LIST_HEAD_VARIABLE (mGcdIoSpaceMap); -EFI_GCD_MAP_ENTRY mGcdMemorySpaceMapEntryTemplate = { +EFI_GCD_MAP_ENTRY mGcdMemorySpaceMapEntryTemplate = { EFI_GCD_MAP_SIGNATURE, { NULL, @@ -54,12 +54,12 @@ EFI_GCD_MAP_ENTRY mGcdMemorySpaceMapEntryTemplate = { 0, 0, EfiGcdMemoryTypeNonExistent, - (EFI_GCD_IO_TYPE) 0, + (EFI_GCD_IO_TYPE)0, NULL, NULL }; -EFI_GCD_MAP_ENTRY mGcdIoSpaceMapEntryTemplate = { +EFI_GCD_MAP_ENTRY mGcdIoSpaceMapEntryTemplate = { EFI_GCD_MAP_SIGNATURE, { NULL, @@ -69,34 +69,34 @@ EFI_GCD_MAP_ENTRY mGcdIoSpaceMapEntryTemplate = { 0, 0, 0, - (EFI_GCD_MEMORY_TYPE) 0, + (EFI_GCD_MEMORY_TYPE)0, EfiGcdIoTypeNonExistent, NULL, NULL }; -GCD_ATTRIBUTE_CONVERSION_ENTRY mAttributeConversionTable[] = { - { EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE, EFI_MEMORY_UC, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_UNCACHED_EXPORTED, EFI_MEMORY_UCE, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE, EFI_MEMORY_WC, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE, EFI_MEMORY_WT, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE, EFI_MEMORY_WB, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE, EFI_MEMORY_RP, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE, EFI_MEMORY_WP, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE, EFI_MEMORY_XP, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE, EFI_MEMORY_RO, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_PRESENT, EFI_MEMORY_PRESENT, FALSE }, - { EFI_RESOURCE_ATTRIBUTE_INITIALIZED, EFI_MEMORY_INITIALIZED, FALSE }, - { EFI_RESOURCE_ATTRIBUTE_TESTED, EFI_MEMORY_TESTED, FALSE }, - { EFI_RESOURCE_ATTRIBUTE_PERSISTABLE, EFI_MEMORY_NV, TRUE }, - { EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE, EFI_MEMORY_MORE_RELIABLE, TRUE }, - { 0, 0, FALSE } +GCD_ATTRIBUTE_CONVERSION_ENTRY mAttributeConversionTable[] = { + { EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE, EFI_MEMORY_UC, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_UNCACHED_EXPORTED, EFI_MEMORY_UCE, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE, EFI_MEMORY_WC, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE, EFI_MEMORY_WT, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE, EFI_MEMORY_WB, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE, EFI_MEMORY_RP, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE, EFI_MEMORY_WP, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE, EFI_MEMORY_XP, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE, EFI_MEMORY_RO, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_PRESENT, EFI_MEMORY_PRESENT, FALSE }, + { EFI_RESOURCE_ATTRIBUTE_INITIALIZED, EFI_MEMORY_INITIALIZED, FALSE }, + { EFI_RESOURCE_ATTRIBUTE_TESTED, EFI_MEMORY_TESTED, FALSE }, + { EFI_RESOURCE_ATTRIBUTE_PERSISTABLE, EFI_MEMORY_NV, TRUE }, + { EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE, EFI_MEMORY_MORE_RELIABLE, TRUE }, + { 0, 0, FALSE } }; /// /// Lookup table used to print GCD Memory Space Map /// -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdMemoryTypeNames[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdMemoryTypeNames[] = { "NonExist ", // EfiGcdMemoryTypeNonExistent "Reserved ", // EfiGcdMemoryTypeReserved "SystemMem", // EfiGcdMemoryTypeSystemMemory @@ -109,7 +109,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdMemoryTypeNames[] = { /// /// Lookup table used to print GCD I/O Space Map /// -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdIoTypeNames[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdIoTypeNames[] = { "NonExist", // EfiGcdIoTypeNonExistent "Reserved", // EfiGcdIoTypeReserved "I/O ", // EfiGcdIoTypeIo @@ -119,7 +119,7 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdIoTypeNames[] = { /// /// Lookup table used to print GCD Allocation Types /// -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdAllocationTypeNames[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *mGcdAllocationTypeNames[] = { "AnySearchBottomUp ", // EfiGcdAllocateAnySearchBottomUp "MaxAddressSearchBottomUp ", // EfiGcdAllocateMaxAddressSearchBottomUp "AtAddress ", // EfiGcdAllocateAddress @@ -141,33 +141,37 @@ CoreDumpGcdMemorySpaceMap ( BOOLEAN InitialMap ) { - DEBUG_CODE_BEGIN (); - EFI_STATUS Status; - UINTN NumberOfDescriptors; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; - UINTN Index; + DEBUG_CODE_BEGIN (); + EFI_STATUS Status; + UINTN NumberOfDescriptors; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; + UINTN Index; - Status = CoreGetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap); - ASSERT (Status == EFI_SUCCESS && MemorySpaceMap != NULL); + Status = CoreGetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap); + ASSERT (Status == EFI_SUCCESS && MemorySpaceMap != NULL); - if (InitialMap) { - DEBUG ((DEBUG_GCD, "GCD:Initial GCD Memory Space Map\n")); - } - DEBUG ((DEBUG_GCD, "GCDMemType Range Capabilities Attributes \n")); - DEBUG ((DEBUG_GCD, "========== ================================= ================ ================\n")); - for (Index = 0; Index < NumberOfDescriptors; Index++) { - DEBUG ((DEBUG_GCD, "%a %016lx-%016lx %016lx %016lx%c\n", - mGcdMemoryTypeNames[MIN (MemorySpaceMap[Index].GcdMemoryType, EfiGcdMemoryTypeMaximum)], - MemorySpaceMap[Index].BaseAddress, - MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - 1, - MemorySpaceMap[Index].Capabilities, - MemorySpaceMap[Index].Attributes, - MemorySpaceMap[Index].ImageHandle == NULL ? ' ' : '*' - )); - } - DEBUG ((DEBUG_GCD, "\n")); - FreePool (MemorySpaceMap); - DEBUG_CODE_END (); + if (InitialMap) { + DEBUG ((DEBUG_GCD, "GCD:Initial GCD Memory Space Map\n")); + } + + DEBUG ((DEBUG_GCD, "GCDMemType Range Capabilities Attributes \n")); + DEBUG ((DEBUG_GCD, "========== ================================= ================ ================\n")); + for (Index = 0; Index < NumberOfDescriptors; Index++) { + DEBUG (( + DEBUG_GCD, + "%a %016lx-%016lx %016lx %016lx%c\n", + mGcdMemoryTypeNames[MIN (MemorySpaceMap[Index].GcdMemoryType, EfiGcdMemoryTypeMaximum)], + MemorySpaceMap[Index].BaseAddress, + MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - 1, + MemorySpaceMap[Index].Capabilities, + MemorySpaceMap[Index].Attributes, + MemorySpaceMap[Index].ImageHandle == NULL ? ' ' : '*' + )); + } + + DEBUG ((DEBUG_GCD, "\n")); + FreePool (MemorySpaceMap); + DEBUG_CODE_END (); } /** @@ -183,32 +187,35 @@ CoreDumpGcdIoSpaceMap ( BOOLEAN InitialMap ) { - DEBUG_CODE_BEGIN (); - EFI_STATUS Status; - UINTN NumberOfDescriptors; - EFI_GCD_IO_SPACE_DESCRIPTOR *IoSpaceMap; - UINTN Index; + DEBUG_CODE_BEGIN (); + EFI_STATUS Status; + UINTN NumberOfDescriptors; + EFI_GCD_IO_SPACE_DESCRIPTOR *IoSpaceMap; + UINTN Index; - Status = CoreGetIoSpaceMap (&NumberOfDescriptors, &IoSpaceMap); - ASSERT (Status == EFI_SUCCESS && IoSpaceMap != NULL); + Status = CoreGetIoSpaceMap (&NumberOfDescriptors, &IoSpaceMap); + ASSERT (Status == EFI_SUCCESS && IoSpaceMap != NULL); - if (InitialMap) { - DEBUG ((DEBUG_GCD, "GCD:Initial GCD I/O Space Map\n")); - } + if (InitialMap) { + DEBUG ((DEBUG_GCD, "GCD:Initial GCD I/O Space Map\n")); + } - DEBUG ((DEBUG_GCD, "GCDIoType Range \n")); - DEBUG ((DEBUG_GCD, "========== =================================\n")); - for (Index = 0; Index < NumberOfDescriptors; Index++) { - DEBUG ((DEBUG_GCD, "%a %016lx-%016lx%c\n", - mGcdIoTypeNames[MIN (IoSpaceMap[Index].GcdIoType, EfiGcdIoTypeMaximum)], - IoSpaceMap[Index].BaseAddress, - IoSpaceMap[Index].BaseAddress + IoSpaceMap[Index].Length - 1, - IoSpaceMap[Index].ImageHandle == NULL ? ' ' : '*' - )); - } - DEBUG ((DEBUG_GCD, "\n")); - FreePool (IoSpaceMap); - DEBUG_CODE_END (); + DEBUG ((DEBUG_GCD, "GCDIoType Range \n")); + DEBUG ((DEBUG_GCD, "========== =================================\n")); + for (Index = 0; Index < NumberOfDescriptors; Index++) { + DEBUG (( + DEBUG_GCD, + "%a %016lx-%016lx%c\n", + mGcdIoTypeNames[MIN (IoSpaceMap[Index].GcdIoType, EfiGcdIoTypeMaximum)], + IoSpaceMap[Index].BaseAddress, + IoSpaceMap[Index].BaseAddress + IoSpaceMap[Index].Length - 1, + IoSpaceMap[Index].ImageHandle == NULL ? ' ' : '*' + )); + } + + DEBUG ((DEBUG_GCD, "\n")); + FreePool (IoSpaceMap); + DEBUG_CODE_END (); } /** @@ -225,16 +232,26 @@ CoreValidateResourceDescriptorHobAttributes ( IN UINT64 Attributes ) { - ASSERT (((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED) == 0) || - ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE) != 0)); - ASSERT (((Attributes & EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED) == 0) || - ((Attributes & EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE) != 0)); - ASSERT (((Attributes & EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED) == 0) || - ((Attributes & EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE) != 0)); - ASSERT (((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTED) == 0) || - ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE) != 0)); - ASSERT (((Attributes & EFI_RESOURCE_ATTRIBUTE_PERSISTENT) == 0) || - ((Attributes & EFI_RESOURCE_ATTRIBUTE_PERSISTABLE) != 0)); + ASSERT ( + ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_PROTECTED) == 0) || + ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_PROTECTABLE) != 0) + ); + ASSERT ( + ((Attributes & EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTED) == 0) || + ((Attributes & EFI_RESOURCE_ATTRIBUTE_WRITE_PROTECTABLE) != 0) + ); + ASSERT ( + ((Attributes & EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTED) == 0) || + ((Attributes & EFI_RESOURCE_ATTRIBUTE_EXECUTION_PROTECTABLE) != 0) + ); + ASSERT ( + ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTED) == 0) || + ((Attributes & EFI_RESOURCE_ATTRIBUTE_READ_ONLY_PROTECTABLE) != 0) + ); + ASSERT ( + ((Attributes & EFI_RESOURCE_ATTRIBUTE_PERSISTENT) == 0) || + ((Attributes & EFI_RESOURCE_ATTRIBUTE_PERSISTABLE) != 0) + ); } /** @@ -249,8 +266,6 @@ CoreAcquireGcdMemoryLock ( CoreAcquireLock (&mGcdMemorySpaceLock); } - - /** Release memory lock on mGcdMemorySpaceLock. @@ -263,8 +278,6 @@ CoreReleaseGcdMemoryLock ( CoreReleaseLock (&mGcdMemorySpaceLock); } - - /** Acquire memory lock on mGcdIoSpaceLock. @@ -277,7 +290,6 @@ CoreAcquireGcdIoLock ( CoreAcquireLock (&mGcdIoSpaceLock); } - /** Release memory lock on mGcdIoSpaceLock. @@ -290,11 +302,10 @@ CoreReleaseGcdIoLock ( CoreReleaseLock (&mGcdIoSpaceLock); } - - // // GCD Initialization Worker Functions // + /** Aligns a value to the specified boundary. @@ -320,10 +331,10 @@ AlignValue ( if (RoundUp) { Value += AlignmentMask; } + return Value & (~AlignmentMask); } - /** Aligns address to the page boundary. @@ -334,13 +345,12 @@ AlignValue ( **/ UINT64 PageAlignAddress ( - IN UINT64 Value + IN UINT64 Value ) { return AlignValue (Value, EFI_PAGE_SHIFT, TRUE); } - /** Aligns length to the page boundary. @@ -351,7 +361,7 @@ PageAlignAddress ( **/ UINT64 PageAlignLength ( - IN UINT64 Value + IN UINT64 Value ) { return AlignValue (Value, EFI_PAGE_SHIFT, FALSE); @@ -383,15 +393,15 @@ CoreAllocateGcdMapEntry ( // cause problem when it's freed (if HeapGuard is enabled). // mOnGuarding = TRUE; - *TopEntry = AllocateZeroPool (sizeof (EFI_GCD_MAP_ENTRY)); + *TopEntry = AllocateZeroPool (sizeof (EFI_GCD_MAP_ENTRY)); mOnGuarding = FALSE; if (*TopEntry == NULL) { return EFI_OUT_OF_RESOURCES; } - mOnGuarding = TRUE; + mOnGuarding = TRUE; *BottomEntry = AllocateZeroPool (sizeof (EFI_GCD_MAP_ENTRY)); - mOnGuarding = FALSE; + mOnGuarding = FALSE; if (*BottomEntry == NULL) { CoreFreePool (*TopEntry); return EFI_OUT_OF_RESOURCES; @@ -400,7 +410,6 @@ CoreAllocateGcdMapEntry ( return EFI_SUCCESS; } - /** Internal function. Inserts a new descriptor into a sorted list @@ -417,7 +426,7 @@ CoreAllocateGcdMapEntry ( **/ EFI_STATUS CoreInsertGcdMapEntry ( - IN LIST_ENTRY *Link, + IN LIST_ENTRY *Link, IN EFI_GCD_MAP_ENTRY *Entry, IN EFI_PHYSICAL_ADDRESS BaseAddress, IN UINT64 Length, @@ -448,7 +457,6 @@ CoreInsertGcdMapEntry ( return EFI_SUCCESS; } - /** Merge the Gcd region specified by Link and its adjacent entry. @@ -463,9 +471,9 @@ CoreInsertGcdMapEntry ( **/ EFI_STATUS CoreMergeGcdMapEntry ( - IN LIST_ENTRY *Link, - IN BOOLEAN Forward, - IN LIST_ENTRY *Map + IN LIST_ENTRY *Link, + IN BOOLEAN Forward, + IN LIST_ENTRY *Map ) { LIST_ENTRY *AdjacentLink; @@ -494,34 +502,39 @@ CoreMergeGcdMapEntry ( if (Entry->Capabilities != AdjacentEntry->Capabilities) { return EFI_UNSUPPORTED; } + if (Entry->Attributes != AdjacentEntry->Attributes) { return EFI_UNSUPPORTED; } + if (Entry->GcdMemoryType != AdjacentEntry->GcdMemoryType) { return EFI_UNSUPPORTED; } + if (Entry->GcdIoType != AdjacentEntry->GcdIoType) { return EFI_UNSUPPORTED; } + if (Entry->ImageHandle != AdjacentEntry->ImageHandle) { return EFI_UNSUPPORTED; } + if (Entry->DeviceHandle != AdjacentEntry->DeviceHandle) { return EFI_UNSUPPORTED; } if (Forward) { - Entry->EndAddress = AdjacentEntry->EndAddress; + Entry->EndAddress = AdjacentEntry->EndAddress; } else { Entry->BaseAddress = AdjacentEntry->BaseAddress; } + RemoveEntryList (AdjacentLink); CoreFreePool (AdjacentEntry); return EFI_SUCCESS; } - /** Merge adjacent entries on total chain. @@ -548,6 +561,7 @@ CoreCleanupGcdMapEntry ( if (TopEntry->Signature == 0) { CoreFreePool (TopEntry); } + if (BottomEntry->Signature == 0) { CoreFreePool (BottomEntry); } @@ -557,12 +571,12 @@ CoreCleanupGcdMapEntry ( CoreMergeGcdMapEntry (Link, FALSE, Map); Link = Link->ForwardLink; } + CoreMergeGcdMapEntry (EndLink, TRUE, Map); return EFI_SUCCESS; } - /** Search a segment of memory space in GCD map. The result is a range of GCD entry list. @@ -598,23 +612,25 @@ CoreSearchGcdMapEntry ( Link = Map->ForwardLink; while (Link != Map) { Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); - if (BaseAddress >= Entry->BaseAddress && BaseAddress <= Entry->EndAddress) { + if ((BaseAddress >= Entry->BaseAddress) && (BaseAddress <= Entry->EndAddress)) { *StartLink = Link; } + if (*StartLink != NULL) { - if ((BaseAddress + Length - 1) >= Entry->BaseAddress && - (BaseAddress + Length - 1) <= Entry->EndAddress ) { + if (((BaseAddress + Length - 1) >= Entry->BaseAddress) && + ((BaseAddress + Length - 1) <= Entry->EndAddress)) + { *EndLink = Link; return EFI_SUCCESS; } } + Link = Link->ForwardLink; } return EFI_NOT_FOUND; } - /** Count the amount of GCD map entries. @@ -628,11 +644,11 @@ CoreCountGcdMapEntry ( IN LIST_ENTRY *Map ) { - UINTN Count; - LIST_ENTRY *Link; + UINTN Count; + LIST_ENTRY *Link; Count = 0; - Link = Map->ForwardLink; + Link = Map->ForwardLink; while (Link != Map) { Count++; Link = Link->ForwardLink; @@ -641,8 +657,6 @@ CoreCountGcdMapEntry ( return Count; } - - /** Return the memory attribute specified by Attributes @@ -653,31 +667,30 @@ CoreCountGcdMapEntry ( **/ UINT64 ConverToCpuArchAttributes ( - UINT64 Attributes + UINT64 Attributes ) { - UINT64 CpuArchAttributes; + UINT64 CpuArchAttributes; CpuArchAttributes = Attributes & EFI_MEMORY_ATTRIBUTE_MASK; - if ( (Attributes & EFI_MEMORY_UC) == EFI_MEMORY_UC) { + if ((Attributes & EFI_MEMORY_UC) == EFI_MEMORY_UC) { CpuArchAttributes |= EFI_MEMORY_UC; - } else if ( (Attributes & EFI_MEMORY_WC ) == EFI_MEMORY_WC) { + } else if ((Attributes & EFI_MEMORY_WC) == EFI_MEMORY_WC) { CpuArchAttributes |= EFI_MEMORY_WC; - } else if ( (Attributes & EFI_MEMORY_WT ) == EFI_MEMORY_WT) { + } else if ((Attributes & EFI_MEMORY_WT) == EFI_MEMORY_WT) { CpuArchAttributes |= EFI_MEMORY_WT; - } else if ( (Attributes & EFI_MEMORY_WB) == EFI_MEMORY_WB) { + } else if ((Attributes & EFI_MEMORY_WB) == EFI_MEMORY_WB) { CpuArchAttributes |= EFI_MEMORY_WB; - } else if ( (Attributes & EFI_MEMORY_UCE) == EFI_MEMORY_UCE) { + } else if ((Attributes & EFI_MEMORY_UCE) == EFI_MEMORY_UCE) { CpuArchAttributes |= EFI_MEMORY_UCE; - } else if ( (Attributes & EFI_MEMORY_WP) == EFI_MEMORY_WP) { + } else if ((Attributes & EFI_MEMORY_WP) == EFI_MEMORY_WP) { CpuArchAttributes |= EFI_MEMORY_WP; } return CpuArchAttributes; } - /** Do operation on a segment of memory space specified (add, free, remove, change attribute ...). @@ -748,6 +761,7 @@ CoreConvertSpace ( goto Done; } + ASSERT (StartLink != NULL && EndLink != NULL); // @@ -757,89 +771,103 @@ CoreConvertSpace ( while (Link != EndLink->ForwardLink) { Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); switch (Operation) { - // - // Add operations - // - case GCD_ADD_MEMORY_OPERATION: - if (Entry->GcdMemoryType != EfiGcdMemoryTypeNonExistent || - Entry->ImageHandle != NULL ) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - break; - case GCD_ADD_IO_OPERATION: - if (Entry->GcdIoType != EfiGcdIoTypeNonExistent || - Entry->ImageHandle != NULL ) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - break; - // - // Free operations - // - case GCD_FREE_MEMORY_OPERATION: - case GCD_FREE_IO_OPERATION: - if (Entry->ImageHandle == NULL) { - Status = EFI_NOT_FOUND; - goto Done; - } - break; - // - // Remove operations - // - case GCD_REMOVE_MEMORY_OPERATION: - if (Entry->GcdMemoryType == EfiGcdMemoryTypeNonExistent) { - Status = EFI_NOT_FOUND; - goto Done; - } - if (Entry->ImageHandle != NULL) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - break; - case GCD_REMOVE_IO_OPERATION: - if (Entry->GcdIoType == EfiGcdIoTypeNonExistent) { - Status = EFI_NOT_FOUND; - goto Done; - } - if (Entry->ImageHandle != NULL) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - break; - // - // Set attributes operation - // - case GCD_SET_ATTRIBUTES_MEMORY_OPERATION: - if ((Attributes & EFI_MEMORY_RUNTIME) != 0) { - if ((BaseAddress & EFI_PAGE_MASK) != 0 || (Length & EFI_PAGE_MASK) != 0) { - Status = EFI_INVALID_PARAMETER; + // + // Add operations + // + case GCD_ADD_MEMORY_OPERATION: + if ((Entry->GcdMemoryType != EfiGcdMemoryTypeNonExistent) || + (Entry->ImageHandle != NULL)) + { + Status = EFI_ACCESS_DENIED; goto Done; } - } - if ((Entry->Capabilities & Attributes) != Attributes) { - Status = EFI_UNSUPPORTED; - goto Done; - } - break; - // - // Set capabilities operation - // - case GCD_SET_CAPABILITIES_MEMORY_OPERATION: - if ((BaseAddress & EFI_PAGE_MASK) != 0 || (Length & EFI_PAGE_MASK) != 0) { - Status = EFI_INVALID_PARAMETER; - goto Done; - } + break; + case GCD_ADD_IO_OPERATION: + if ((Entry->GcdIoType != EfiGcdIoTypeNonExistent) || + (Entry->ImageHandle != NULL)) + { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + break; // - // Current attributes must still be supported with new capabilities + // Free operations // - if ((Capabilities & Entry->Attributes) != Entry->Attributes) { - Status = EFI_UNSUPPORTED; - goto Done; - } - break; + case GCD_FREE_MEMORY_OPERATION: + case GCD_FREE_IO_OPERATION: + if (Entry->ImageHandle == NULL) { + Status = EFI_NOT_FOUND; + goto Done; + } + + break; + // + // Remove operations + // + case GCD_REMOVE_MEMORY_OPERATION: + if (Entry->GcdMemoryType == EfiGcdMemoryTypeNonExistent) { + Status = EFI_NOT_FOUND; + goto Done; + } + + if (Entry->ImageHandle != NULL) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + break; + case GCD_REMOVE_IO_OPERATION: + if (Entry->GcdIoType == EfiGcdIoTypeNonExistent) { + Status = EFI_NOT_FOUND; + goto Done; + } + + if (Entry->ImageHandle != NULL) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + break; + // + // Set attributes operation + // + case GCD_SET_ATTRIBUTES_MEMORY_OPERATION: + if ((Attributes & EFI_MEMORY_RUNTIME) != 0) { + if (((BaseAddress & EFI_PAGE_MASK) != 0) || ((Length & EFI_PAGE_MASK) != 0)) { + Status = EFI_INVALID_PARAMETER; + goto Done; + } + } + + if ((Entry->Capabilities & Attributes) != Attributes) { + Status = EFI_UNSUPPORTED; + goto Done; + } + + break; + // + // Set capabilities operation + // + case GCD_SET_CAPABILITIES_MEMORY_OPERATION: + if (((BaseAddress & EFI_PAGE_MASK) != 0) || ((Length & EFI_PAGE_MASK) != 0)) { + Status = EFI_INVALID_PARAMETER; + + goto Done; + } + + // + // Current attributes must still be supported with new capabilities + // + if ((Capabilities & Entry->Attributes) != Entry->Attributes) { + Status = EFI_UNSUPPORTED; + goto Done; + } + + break; } + Link = Link->ForwardLink; } @@ -851,6 +879,7 @@ CoreConvertSpace ( Status = EFI_OUT_OF_RESOURCES; goto Done; } + ASSERT (TopEntry != NULL && BottomEntry != NULL); // @@ -887,6 +916,7 @@ CoreConvertSpace ( CpuArchAttributes ); } + if (EFI_ERROR (Status)) { CoreFreePool (TopEntry); CoreFreePool (BottomEntry); @@ -903,58 +933,61 @@ CoreConvertSpace ( Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); CoreInsertGcdMapEntry (Link, Entry, BaseAddress, Length, TopEntry, BottomEntry); switch (Operation) { - // - // Add operations - // - case GCD_ADD_MEMORY_OPERATION: - Entry->GcdMemoryType = GcdMemoryType; - if (GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) { - Entry->Capabilities = Capabilities | EFI_MEMORY_RUNTIME | EFI_MEMORY_PORT_IO; - } else { - Entry->Capabilities = Capabilities | EFI_MEMORY_RUNTIME; - } - break; - case GCD_ADD_IO_OPERATION: - Entry->GcdIoType = GcdIoType; - break; - // - // Free operations - // - case GCD_FREE_MEMORY_OPERATION: - case GCD_FREE_IO_OPERATION: - Entry->ImageHandle = NULL; - Entry->DeviceHandle = NULL; - break; - // - // Remove operations - // - case GCD_REMOVE_MEMORY_OPERATION: - Entry->GcdMemoryType = EfiGcdMemoryTypeNonExistent; - Entry->Capabilities = 0; - break; - case GCD_REMOVE_IO_OPERATION: - Entry->GcdIoType = EfiGcdIoTypeNonExistent; - break; - // - // Set attributes operation - // - case GCD_SET_ATTRIBUTES_MEMORY_OPERATION: - if (CpuArchAttributes == 0) { - // - // Keep original CPU arch attributes when caller just calls - // SetMemorySpaceAttributes() with none CPU arch attributes (for example, RUNTIME). - // - Attributes |= (Entry->Attributes & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); - } - Entry->Attributes = Attributes; - break; - // - // Set capabilities operation - // - case GCD_SET_CAPABILITIES_MEMORY_OPERATION: - Entry->Capabilities = Capabilities; - break; + // + // Add operations + // + case GCD_ADD_MEMORY_OPERATION: + Entry->GcdMemoryType = GcdMemoryType; + if (GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) { + Entry->Capabilities = Capabilities | EFI_MEMORY_RUNTIME | EFI_MEMORY_PORT_IO; + } else { + Entry->Capabilities = Capabilities | EFI_MEMORY_RUNTIME; + } + + break; + case GCD_ADD_IO_OPERATION: + Entry->GcdIoType = GcdIoType; + break; + // + // Free operations + // + case GCD_FREE_MEMORY_OPERATION: + case GCD_FREE_IO_OPERATION: + Entry->ImageHandle = NULL; + Entry->DeviceHandle = NULL; + break; + // + // Remove operations + // + case GCD_REMOVE_MEMORY_OPERATION: + Entry->GcdMemoryType = EfiGcdMemoryTypeNonExistent; + Entry->Capabilities = 0; + break; + case GCD_REMOVE_IO_OPERATION: + Entry->GcdIoType = EfiGcdIoTypeNonExistent; + break; + // + // Set attributes operation + // + case GCD_SET_ATTRIBUTES_MEMORY_OPERATION: + if (CpuArchAttributes == 0) { + // + // Keep original CPU arch attributes when caller just calls + // SetMemorySpaceAttributes() with none CPU arch attributes (for example, RUNTIME). + // + Attributes |= (Entry->Attributes & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); + } + + Entry->Attributes = Attributes; + break; + // + // Set capabilities operation + // + case GCD_SET_CAPABILITIES_MEMORY_OPERATION: + Entry->Capabilities = Capabilities; + break; } + Link = Link->ForwardLink; } @@ -970,6 +1003,7 @@ Done: CoreReleaseGcdMemoryLock (); CoreDumpGcdMemorySpaceMap (FALSE); } + if ((Operation & GCD_IO_SPACE_OPERATION) != 0) { CoreReleaseGcdIoLock (); CoreDumpGcdIoSpaceMap (FALSE); @@ -978,7 +1012,6 @@ Done: return Status; } - /** Check whether an entry could be used to allocate space. @@ -1005,24 +1038,27 @@ CoreAllocateSpaceCheckEntry ( if (Entry->ImageHandle != NULL) { return EFI_NOT_FOUND; } + switch (Operation) { - case GCD_ALLOCATE_MEMORY_OPERATION: - if (Entry->GcdMemoryType != GcdMemoryType) { - return EFI_NOT_FOUND; - } - break; - case GCD_ALLOCATE_IO_OPERATION: - if (Entry->GcdIoType != GcdIoType) { - return EFI_NOT_FOUND; - } - break; - default: - return EFI_UNSUPPORTED; + case GCD_ALLOCATE_MEMORY_OPERATION: + if (Entry->GcdMemoryType != GcdMemoryType) { + return EFI_NOT_FOUND; + } + + break; + case GCD_ALLOCATE_IO_OPERATION: + if (Entry->GcdIoType != GcdIoType) { + return EFI_NOT_FOUND; + } + + break; + default: + return EFI_UNSUPPORTED; } + return EFI_SUCCESS; } - /** Allocate space on specified address and length. @@ -1074,26 +1110,32 @@ CoreAllocateSpace ( DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } + if ((UINT32)GcdMemoryType >= EfiGcdMemoryTypeMaximum) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } + if ((UINT32)GcdIoType >= EfiGcdIoTypeMaximum) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } + if (BaseAddress == NULL) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } + if (ImageHandle == NULL) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } + if (Alignment >= 64) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_NOT_FOUND)); return EFI_NOT_FOUND; } + if (Length == 0) { DEBUG ((DEBUG_GCD, " Status = %r\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; @@ -1135,6 +1177,7 @@ CoreAllocateSpace ( Status = EFI_NOT_FOUND; goto Done; } + ASSERT (StartLink != NULL && EndLink != NULL); // @@ -1142,23 +1185,24 @@ CoreAllocateSpace ( // Link = StartLink; while (Link != EndLink->ForwardLink) { - Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); - Link = Link->ForwardLink; + Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); + Link = Link->ForwardLink; Status = CoreAllocateSpaceCheckEntry (Operation, Entry, GcdMemoryType, GcdIoType); if (EFI_ERROR (Status)) { goto Done; } } + Found = TRUE; } else { - Entry = CR (Map->BackLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); // // Compute the maximum address to use in the search algorithm // - if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchBottomUp || - GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown ) { + if ((GcdAllocateType == EfiGcdAllocateMaxAddressSearchBottomUp) || + (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown)) + { MaxAddress = *BaseAddress; } else { MaxAddress = Entry->EndAddress; @@ -1167,17 +1211,20 @@ CoreAllocateSpace ( // // Verify that the list of descriptors are unallocated memory matching GcdMemoryType. // - if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown || - GcdAllocateType == EfiGcdAllocateAnySearchTopDown ) { + if ((GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown) || + (GcdAllocateType == EfiGcdAllocateAnySearchTopDown)) + { Link = Map->BackLink; } else { Link = Map->ForwardLink; } + while (Link != Map) { Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); - if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown || - GcdAllocateType == EfiGcdAllocateAnySearchTopDown ) { + if ((GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown) || + (GcdAllocateType == EfiGcdAllocateAnySearchTopDown)) + { Link = Link->BackLink; } else { Link = Link->ForwardLink; @@ -1188,20 +1235,24 @@ CoreAllocateSpace ( continue; } - if (GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown || - GcdAllocateType == EfiGcdAllocateAnySearchTopDown) { + if ((GcdAllocateType == EfiGcdAllocateMaxAddressSearchTopDown) || + (GcdAllocateType == EfiGcdAllocateAnySearchTopDown)) + { if ((Entry->BaseAddress + Length) > MaxAddress) { continue; } + if (Length > (Entry->EndAddress + 1)) { Status = EFI_NOT_FOUND; goto Done; } + if (Entry->EndAddress > MaxAddress) { *BaseAddress = MaxAddress; } else { *BaseAddress = Entry->EndAddress; } + *BaseAddress = (*BaseAddress + 1 - Length) & (~AlignmentMask); } else { *BaseAddress = (Entry->BaseAddress + AlignmentMask) & (~AlignmentMask); @@ -1219,29 +1270,33 @@ CoreAllocateSpace ( Status = EFI_NOT_FOUND; goto Done; } + ASSERT (StartLink != NULL && EndLink != NULL); Link = StartLink; // // Verify that the list of descriptors are unallocated memory matching GcdMemoryType. // - Found = TRUE; + Found = TRUE; SubLink = StartLink; while (SubLink != EndLink->ForwardLink) { - Entry = CR (SubLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); + Entry = CR (SubLink, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); Status = CoreAllocateSpaceCheckEntry (Operation, Entry, GcdMemoryType, GcdIoType); if (EFI_ERROR (Status)) { - Link = SubLink; + Link = SubLink; Found = FALSE; break; } + SubLink = SubLink->ForwardLink; } + if (Found) { break; } } } + if (!Found) { Status = EFI_NOT_FOUND; goto Done; @@ -1255,6 +1310,7 @@ CoreAllocateSpace ( Status = EFI_OUT_OF_RESOURCES; goto Done; } + ASSERT (TopEntry != NULL && BottomEntry != NULL); // @@ -1266,7 +1322,7 @@ CoreAllocateSpace ( CoreInsertGcdMapEntry (Link, Entry, *BaseAddress, Length, TopEntry, BottomEntry); Entry->ImageHandle = ImageHandle; Entry->DeviceHandle = DeviceHandle; - Link = Link->ForwardLink; + Link = Link->ForwardLink; } // @@ -1279,13 +1335,15 @@ Done: if (!EFI_ERROR (Status)) { DEBUG ((DEBUG_GCD, " (BaseAddress = %016lx)", *BaseAddress)); } + DEBUG ((DEBUG_GCD, "\n")); if ((Operation & GCD_MEMORY_SPACE_OPERATION) != 0) { CoreReleaseGcdMemoryLock (); CoreDumpGcdMemorySpaceMap (FALSE); } - if ((Operation & GCD_IO_SPACE_OPERATION) !=0) { + + if ((Operation & GCD_IO_SPACE_OPERATION) != 0) { CoreReleaseGcdIoLock (); CoreDumpGcdIoSpaceMap (FALSE); } @@ -1293,7 +1351,6 @@ Done: return Status; } - /** Add a segment of memory to GCD map. @@ -1321,11 +1378,11 @@ CoreInternalAddMemorySpace ( // // Make sure parameters are valid // - if (GcdMemoryType <= EfiGcdMemoryTypeNonExistent || GcdMemoryType >= EfiGcdMemoryTypeMaximum) { + if ((GcdMemoryType <= EfiGcdMemoryTypeNonExistent) || (GcdMemoryType >= EfiGcdMemoryTypeMaximum)) { return EFI_INVALID_PARAMETER; } - return CoreConvertSpace (GCD_ADD_MEMORY_OPERATION, GcdMemoryType, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, Capabilities, 0); + return CoreConvertSpace (GCD_ADD_MEMORY_OPERATION, GcdMemoryType, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, Capabilities, 0); } // @@ -1366,6 +1423,7 @@ CoreAllocateMemorySpace ( } else { DEBUG ((DEBUG_GCD, "GCD:AllocateMemorySpace(Base=,Length=%016lx)\n", Length)); } + DEBUG ((DEBUG_GCD, " GcdAllocateType = %a\n", mGcdAllocationTypeNames[MIN (GcdAllocateType, EfiGcdMaxAllocateType)])); DEBUG ((DEBUG_GCD, " GcdMemoryType = %a\n", mGcdMemoryTypeNames[MIN (GcdMemoryType, EfiGcdMemoryTypeMaximum)])); DEBUG ((DEBUG_GCD, " Alignment = %016lx\n", LShiftU64 (1, Alignment))); @@ -1376,7 +1434,7 @@ CoreAllocateMemorySpace ( GCD_ALLOCATE_MEMORY_OPERATION, GcdAllocateType, GcdMemoryType, - (EFI_GCD_IO_TYPE) 0, + (EFI_GCD_IO_TYPE)0, Alignment, Length, BaseAddress, @@ -1385,7 +1443,6 @@ CoreAllocateMemorySpace ( ); } - /** Adds reserved memory, system memory, or memory-mapped I/O resources to the global coherency domain of the processor. @@ -1414,7 +1471,6 @@ CoreAddMemorySpace ( Status = CoreInternalAddMemorySpace (GcdMemoryType, BaseAddress, Length, Capabilities); if (!EFI_ERROR (Status) && ((GcdMemoryType == EfiGcdMemoryTypeSystemMemory) || (GcdMemoryType == EfiGcdMemoryTypeMoreReliable))) { - PageBaseAddress = PageAlignAddress (BaseAddress); PageLength = PageAlignLength (BaseAddress + Length - PageBaseAddress); @@ -1436,7 +1492,7 @@ CoreAddMemorySpace ( Capabilities ); } else { - for (; PageLength != 0; PageLength -= EFI_PAGE_SIZE, PageBaseAddress += EFI_PAGE_SIZE) { + for ( ; PageLength != 0; PageLength -= EFI_PAGE_SIZE, PageBaseAddress += EFI_PAGE_SIZE) { Status = CoreAllocateMemorySpace ( EfiGcdAllocateAddress, GcdMemoryType, @@ -1458,10 +1514,10 @@ CoreAddMemorySpace ( } } } + return Status; } - /** Frees nonexistent memory, reserved memory, system memory, or memory-mapped I/O resources from the global coherency domain of the processor. @@ -1481,10 +1537,9 @@ CoreFreeMemorySpace ( { DEBUG ((DEBUG_GCD, "GCD:FreeMemorySpace(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); - return CoreConvertSpace (GCD_FREE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0); + return CoreConvertSpace (GCD_FREE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, 0, 0); } - /** Removes reserved memory, system memory, or memory-mapped I/O resources from the global coherency domain of the processor. @@ -1504,10 +1559,9 @@ CoreRemoveMemorySpace ( { DEBUG ((DEBUG_GCD, "GCD:RemoveMemorySpace(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); - return CoreConvertSpace (GCD_REMOVE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0); + return CoreConvertSpace (GCD_REMOVE_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, 0, 0); } - /** Build a memory descriptor according to an entry. @@ -1518,7 +1572,7 @@ CoreRemoveMemorySpace ( VOID BuildMemoryDescriptor ( IN OUT EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Descriptor, - IN EFI_GCD_MAP_ENTRY *Entry + IN EFI_GCD_MAP_ENTRY *Entry ) { Descriptor->BaseAddress = Entry->BaseAddress; @@ -1530,7 +1584,6 @@ BuildMemoryDescriptor ( Descriptor->DeviceHandle = Entry->DeviceHandle; } - /** Retrieves the descriptor for a memory region containing a specified address. @@ -1582,7 +1635,6 @@ CoreGetMemorySpaceDescriptor ( return Status; } - /** Modifies the attributes for a memory region in the global coherency domain of the processor. @@ -1616,10 +1668,9 @@ CoreSetMemorySpaceAttributes ( DEBUG ((DEBUG_GCD, "GCD:SetMemorySpaceAttributes(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); DEBUG ((DEBUG_GCD, " Attributes = %016lx\n", Attributes)); - return CoreConvertSpace (GCD_SET_ATTRIBUTES_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, Attributes); + return CoreConvertSpace (GCD_SET_ATTRIBUTES_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, 0, Attributes); } - /** Modifies the capabilities for a memory region in the global coherency domain of the processor. @@ -1645,20 +1696,19 @@ CoreSetMemorySpaceCapabilities ( IN UINT64 Capabilities ) { - EFI_STATUS Status; + EFI_STATUS Status; DEBUG ((DEBUG_GCD, "GCD:CoreSetMemorySpaceCapabilities(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); DEBUG ((DEBUG_GCD, " Capabilities = %016lx\n", Capabilities)); - Status = CoreConvertSpace (GCD_SET_CAPABILITIES_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, Capabilities, 0); - if (!EFI_ERROR(Status)) { - CoreUpdateMemoryAttributes(BaseAddress, RShiftU64(Length, EFI_PAGE_SHIFT), Capabilities & (~EFI_MEMORY_RUNTIME)); + Status = CoreConvertSpace (GCD_SET_CAPABILITIES_MEMORY_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, Capabilities, 0); + if (!EFI_ERROR (Status)) { + CoreUpdateMemoryAttributes (BaseAddress, RShiftU64 (Length, EFI_PAGE_SHIFT), Capabilities & (~EFI_MEMORY_RUNTIME)); } return Status; } - /** Returns a map of the memory resources in the global coherency domain of the processor. @@ -1689,12 +1739,13 @@ CoreGetMemorySpaceMap ( if (NumberOfDescriptors == NULL) { return EFI_INVALID_PARAMETER; } + if (MemorySpaceMap == NULL) { return EFI_INVALID_PARAMETER; } - *NumberOfDescriptors = 0; - *MemorySpaceMap = NULL; + *NumberOfDescriptors = 0; + *MemorySpaceMap = NULL; // // Take the lock, for entering the loop with the lock held. @@ -1706,18 +1757,19 @@ CoreGetMemorySpaceMap ( // AllocatePool() called below has to be running outside the GCD lock. // DescriptorCount = CoreCountGcdMapEntry (&mGcdMemorySpaceMap); - if (DescriptorCount == *NumberOfDescriptors && *MemorySpaceMap != NULL) { + if ((DescriptorCount == *NumberOfDescriptors) && (*MemorySpaceMap != NULL)) { // // Fill in the MemorySpaceMap if no memory space map change. // Descriptor = *MemorySpaceMap; - Link = mGcdMemorySpaceMap.ForwardLink; + Link = mGcdMemorySpaceMap.ForwardLink; while (Link != &mGcdMemorySpaceMap) { Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); BuildMemoryDescriptor (Descriptor, Entry); Descriptor++; Link = Link->ForwardLink; } + // // We're done; exit the loop with the lock held. // @@ -1739,8 +1791,10 @@ CoreGetMemorySpaceMap ( FreePool (*MemorySpaceMap); } - *MemorySpaceMap = AllocatePool (DescriptorCount * - sizeof (EFI_GCD_MEMORY_SPACE_DESCRIPTOR)); + *MemorySpaceMap = AllocatePool ( + DescriptorCount * + sizeof (EFI_GCD_MEMORY_SPACE_DESCRIPTOR) + ); if (*MemorySpaceMap == NULL) { *NumberOfDescriptors = 0; return EFI_OUT_OF_RESOURCES; @@ -1756,6 +1810,7 @@ CoreGetMemorySpaceMap ( // CoreAcquireGcdMemoryLock (); } + // // We exited the loop with the lock held, release it. // @@ -1764,7 +1819,6 @@ CoreGetMemorySpaceMap ( return EFI_SUCCESS; } - /** Adds reserved I/O or I/O resources to the global coherency domain of the processor. @@ -1790,12 +1844,12 @@ CoreAddIoSpace ( // // Make sure parameters are valid // - if (GcdIoType <= EfiGcdIoTypeNonExistent || GcdIoType >= EfiGcdIoTypeMaximum) { + if ((GcdIoType <= EfiGcdIoTypeNonExistent) || (GcdIoType >= EfiGcdIoTypeMaximum)) { return EFI_INVALID_PARAMETER; } - return CoreConvertSpace (GCD_ADD_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, GcdIoType, BaseAddress, Length, 0, 0); -} + return CoreConvertSpace (GCD_ADD_IO_OPERATION, (EFI_GCD_MEMORY_TYPE)0, GcdIoType, BaseAddress, Length, 0, 0); +} /** Allocates nonexistent I/O, reserved I/O, or I/O resources from the global coherency @@ -1831,6 +1885,7 @@ CoreAllocateIoSpace ( } else { DEBUG ((DEBUG_GCD, "GCD:AllocateIoSpace(Base=,Length=%016lx)\n", Length)); } + DEBUG ((DEBUG_GCD, " GcdAllocateType = %a\n", mGcdAllocationTypeNames[MIN (GcdAllocateType, EfiGcdMaxAllocateType)])); DEBUG ((DEBUG_GCD, " GcdIoType = %a\n", mGcdIoTypeNames[MIN (GcdIoType, EfiGcdIoTypeMaximum)])); DEBUG ((DEBUG_GCD, " Alignment = %016lx\n", LShiftU64 (1, Alignment))); @@ -1840,7 +1895,7 @@ CoreAllocateIoSpace ( return CoreAllocateSpace ( GCD_ALLOCATE_IO_OPERATION, GcdAllocateType, - (EFI_GCD_MEMORY_TYPE) 0, + (EFI_GCD_MEMORY_TYPE)0, GcdIoType, Alignment, Length, @@ -1850,7 +1905,6 @@ CoreAllocateIoSpace ( ); } - /** Frees nonexistent I/O, reserved I/O, or I/O resources from the global coherency domain of the processor. @@ -1870,10 +1924,9 @@ CoreFreeIoSpace ( { DEBUG ((DEBUG_GCD, "GCD:FreeIoSpace(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); - return CoreConvertSpace (GCD_FREE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0); + return CoreConvertSpace (GCD_FREE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, 0, 0); } - /** Removes reserved I/O or I/O resources from the global coherency domain of the processor. @@ -1893,10 +1946,9 @@ CoreRemoveIoSpace ( { DEBUG ((DEBUG_GCD, "GCD:RemoveIoSpace(Base=%016lx,Length=%016lx)\n", BaseAddress, Length)); - return CoreConvertSpace (GCD_REMOVE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE) 0, (EFI_GCD_IO_TYPE) 0, BaseAddress, Length, 0, 0); + return CoreConvertSpace (GCD_REMOVE_IO_OPERATION, (EFI_GCD_MEMORY_TYPE)0, (EFI_GCD_IO_TYPE)0, BaseAddress, Length, 0, 0); } - /** Build a IO descriptor according to an entry. @@ -1917,7 +1969,6 @@ BuildIoDescriptor ( Descriptor->DeviceHandle = Entry->DeviceHandle; } - /** Retrieves the descriptor for an I/O region containing a specified address. @@ -1969,7 +2020,6 @@ CoreGetIoSpaceDescriptor ( return Status; } - /** Returns a map of the I/O resources in the global coherency domain of the processor. @@ -1999,6 +2049,7 @@ CoreGetIoSpaceMap ( if (NumberOfDescriptors == NULL) { return EFI_INVALID_PARAMETER; } + if (IoSpaceMap == NULL) { return EFI_INVALID_PARAMETER; } @@ -2023,13 +2074,14 @@ CoreGetIoSpaceMap ( // Fill in the IoSpaceMap // Descriptor = *IoSpaceMap; - Link = mGcdIoSpaceMap.ForwardLink; + Link = mGcdIoSpaceMap.ForwardLink; while (Link != &mGcdIoSpaceMap) { Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); BuildIoDescriptor (Descriptor, Entry); Descriptor++; Link = Link->ForwardLink; } + Status = EFI_SUCCESS; Done: @@ -2037,7 +2089,6 @@ Done: return Status; } - /** Converts a Resource Descriptor HOB attributes mask to an EFI Memory Descriptor capabilities mask @@ -2083,8 +2134,8 @@ CalculateTotalMemoryBinSizeNeeded ( VOID ) { - UINTN Index; - UINT64 TotalSize; + UINTN Index; + UINT64 TotalSize; // // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array @@ -2108,45 +2159,49 @@ CalculateTotalMemoryBinSizeNeeded ( **/ VOID FindLargestFreeRegion ( - IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress, - IN OUT UINT64 *Length, - IN EFI_HOB_MEMORY_ALLOCATION *MemoryHob - ) + IN OUT EFI_PHYSICAL_ADDRESS *BaseAddress, + IN OUT UINT64 *Length, + IN EFI_HOB_MEMORY_ALLOCATION *MemoryHob + ) { - EFI_PHYSICAL_ADDRESS TopAddress; - EFI_PHYSICAL_ADDRESS AllocatedTop; - EFI_PHYSICAL_ADDRESS LowerBase; - UINT64 LowerSize; - EFI_PHYSICAL_ADDRESS UpperBase; - UINT64 UpperSize; + EFI_PHYSICAL_ADDRESS TopAddress; + EFI_PHYSICAL_ADDRESS AllocatedTop; + EFI_PHYSICAL_ADDRESS LowerBase; + UINT64 LowerSize; + EFI_PHYSICAL_ADDRESS UpperBase; + UINT64 UpperSize; TopAddress = *BaseAddress + *Length; while (MemoryHob != NULL) { AllocatedTop = MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength; if ((MemoryHob->AllocDescriptor.MemoryBaseAddress >= *BaseAddress) && - (AllocatedTop <= TopAddress)) { + (AllocatedTop <= TopAddress)) + { LowerBase = *BaseAddress; LowerSize = MemoryHob->AllocDescriptor.MemoryBaseAddress - *BaseAddress; UpperBase = AllocatedTop; UpperSize = TopAddress - AllocatedTop; if (LowerSize != 0) { - FindLargestFreeRegion (&LowerBase, &LowerSize, (EFI_HOB_MEMORY_ALLOCATION *) GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (MemoryHob))); + FindLargestFreeRegion (&LowerBase, &LowerSize, (EFI_HOB_MEMORY_ALLOCATION *)GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (MemoryHob))); } + if (UpperSize != 0) { - FindLargestFreeRegion (&UpperBase, &UpperSize, (EFI_HOB_MEMORY_ALLOCATION *) GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (MemoryHob))); + FindLargestFreeRegion (&UpperBase, &UpperSize, (EFI_HOB_MEMORY_ALLOCATION *)GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (MemoryHob))); } if (UpperSize >= LowerSize) { - *Length = UpperSize; + *Length = UpperSize; *BaseAddress = UpperBase; } else { - *Length = LowerSize; + *Length = LowerSize; *BaseAddress = LowerBase; } + return; } + MemoryHob = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, GET_NEXT_HOB (MemoryHob)); } } @@ -2173,23 +2228,23 @@ CoreInitializeMemoryServices ( OUT UINT64 *MemoryLength ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_MEMORY_TYPE_INFORMATION *EfiMemoryTypeInformation; - UINTN DataSize; - BOOLEAN Found; - EFI_HOB_HANDOFF_INFO_TABLE *PhitHob; - EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; - EFI_HOB_RESOURCE_DESCRIPTOR *PhitResourceHob; - EFI_PHYSICAL_ADDRESS BaseAddress; - UINT64 Length; - UINT64 Attributes; - UINT64 Capabilities; - EFI_PHYSICAL_ADDRESS TestedMemoryBaseAddress; - UINT64 TestedMemoryLength; - EFI_PHYSICAL_ADDRESS HighAddress; - EFI_HOB_GUID_TYPE *GuidHob; - UINT32 ReservedCodePageNumber; - UINT64 MinimalMemorySizeNeeded; + EFI_PEI_HOB_POINTERS Hob; + EFI_MEMORY_TYPE_INFORMATION *EfiMemoryTypeInformation; + UINTN DataSize; + BOOLEAN Found; + EFI_HOB_HANDOFF_INFO_TABLE *PhitHob; + EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; + EFI_HOB_RESOURCE_DESCRIPTOR *PhitResourceHob; + EFI_PHYSICAL_ADDRESS BaseAddress; + UINT64 Length; + UINT64 Attributes; + UINT64 Capabilities; + EFI_PHYSICAL_ADDRESS TestedMemoryBaseAddress; + UINT64 TestedMemoryLength; + EFI_PHYSICAL_ADDRESS HighAddress; + EFI_HOB_GUID_TYPE *GuidHob; + UINT32 ReservedCodePageNumber; + UINT64 MinimalMemorySizeNeeded; // // Point at the first HOB. This must be the PHIT HOB. @@ -2206,27 +2261,28 @@ CoreInitializeMemoryServices ( // // Initialize Local Variables // - PhitResourceHob = NULL; - ResourceHob = NULL; - BaseAddress = 0; - Length = 0; - Attributes = 0; + PhitResourceHob = NULL; + ResourceHob = NULL; + BaseAddress = 0; + Length = 0; + Attributes = 0; // // Cache the PHIT HOB for later use // PhitHob = Hob.HandoffInformationTable; - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { - ReservedCodePageNumber = PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber); - ReservedCodePageNumber += PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber); + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { + ReservedCodePageNumber = PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber); + ReservedCodePageNumber += PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber); // // cache the Top address for loading modules at Fixed Address // gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress = PhitHob->EfiMemoryTop - + EFI_PAGES_TO_SIZE(ReservedCodePageNumber); + + EFI_PAGES_TO_SIZE (ReservedCodePageNumber); } + // // See if a Memory Type Information HOB is available // @@ -2234,7 +2290,7 @@ CoreInitializeMemoryServices ( if (GuidHob != NULL) { EfiMemoryTypeInformation = GET_GUID_HOB_DATA (GuidHob); DataSize = GET_GUID_HOB_DATA_SIZE (GuidHob); - if (EfiMemoryTypeInformation != NULL && DataSize > 0 && DataSize <= (EfiMaxMemoryType + 1) * sizeof (EFI_MEMORY_TYPE_INFORMATION)) { + if ((EfiMemoryTypeInformation != NULL) && (DataSize > 0) && (DataSize <= (EfiMaxMemoryType + 1) * sizeof (EFI_MEMORY_TYPE_INFORMATION))) { CopyMem (&gMemoryTypeInformation, EfiMemoryTypeInformation, DataSize); } } @@ -2247,8 +2303,8 @@ CoreInitializeMemoryServices ( // // Find the Resource Descriptor HOB that contains PHIT range EfiFreeMemoryBottom..EfiFreeMemoryTop // - Found = FALSE; - for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + Found = FALSE; + for (Hob.Raw = *HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // Skip all HOBs except Resource Descriptor HOBs // @@ -2263,6 +2319,7 @@ CoreInitializeMemoryServices ( if (ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY) { continue; } + if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) != TESTED_MEMORY_ATTRIBUTES) { continue; } @@ -2273,6 +2330,7 @@ CoreInitializeMemoryServices ( if (PhitHob->EfiFreeMemoryBottom < ResourceHob->PhysicalStart) { continue; } + if (PhitHob->EfiFreeMemoryTop > (ResourceHob->PhysicalStart + ResourceHob->ResourceLength)) { continue; } @@ -2281,14 +2339,14 @@ CoreInitializeMemoryServices ( // Cache the resource descriptor HOB for the memory region described by the PHIT HOB // PhitResourceHob = ResourceHob; - Found = TRUE; + Found = TRUE; // // Compute range between PHIT EfiMemoryTop and the end of the Resource Descriptor HOB // Attributes = PhitResourceHob->ResourceAttribute; BaseAddress = PageAlignAddress (PhitHob->EfiMemoryTop); - Length = PageAlignLength (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - BaseAddress); + Length = PageAlignLength (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - BaseAddress); FindLargestFreeRegion (&BaseAddress, &Length, (EFI_HOB_MEMORY_ALLOCATION *)GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION)); if (Length < MinimalMemorySizeNeeded) { // @@ -2296,18 +2354,19 @@ CoreInitializeMemoryServices ( // Compute range between PHIT EfiFreeMemoryBottom and PHIT EfiFreeMemoryTop // BaseAddress = PageAlignAddress (PhitHob->EfiFreeMemoryBottom); - Length = PageAlignLength (PhitHob->EfiFreeMemoryTop - BaseAddress); - //This region is required to have no memory allocation inside it, skip check for entries in HOB List + Length = PageAlignLength (PhitHob->EfiFreeMemoryTop - BaseAddress); + // This region is required to have no memory allocation inside it, skip check for entries in HOB List if (Length < MinimalMemorySizeNeeded) { // // If that range is not large enough to intialize the DXE Core, then // Compute range between the start of the Resource Descriptor HOB and the start of the HOB List // BaseAddress = PageAlignAddress (ResourceHob->PhysicalStart); - Length = PageAlignLength ((UINT64)((UINTN)*HobStart - BaseAddress)); + Length = PageAlignLength ((UINT64)((UINTN)*HobStart - BaseAddress)); FindLargestFreeRegion (&BaseAddress, &Length, (EFI_HOB_MEMORY_ALLOCATION *)GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION)); } } + break; } @@ -2329,13 +2388,14 @@ CoreInitializeMemoryServices ( // The max address must be within the physically addressible range for the processor. // HighAddress = MAX_ALLOC_ADDRESS; - for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = *HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // Skip the Resource Descriptor HOB that contains the PHIT // if (Hob.ResourceDescriptor == PhitResourceHob) { continue; } + // // Skip all HOBs except Resource Descriptor HOBs // @@ -2350,9 +2410,11 @@ CoreInitializeMemoryServices ( if (ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY) { continue; } + if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) != TESTED_MEMORY_ATTRIBUTES) { continue; } + if ((ResourceHob->PhysicalStart + ResourceHob->ResourceLength) > (EFI_PHYSICAL_ADDRESS)MAX_ALLOC_ADDRESS) { continue; } @@ -2360,7 +2422,7 @@ CoreInitializeMemoryServices ( // // Skip Resource Descriptor HOBs that are below a previously found Resource Descriptor HOB // - if (HighAddress != (EFI_PHYSICAL_ADDRESS)MAX_ALLOC_ADDRESS && ResourceHob->PhysicalStart <= HighAddress) { + if ((HighAddress != (EFI_PHYSICAL_ADDRESS)MAX_ALLOC_ADDRESS) && (ResourceHob->PhysicalStart <= HighAddress)) { continue; } @@ -2368,7 +2430,7 @@ CoreInitializeMemoryServices ( // Skip Resource Descriptor HOBs that are not large enough to initilize the DXE Core // TestedMemoryBaseAddress = PageAlignAddress (ResourceHob->PhysicalStart); - TestedMemoryLength = PageAlignLength (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - TestedMemoryBaseAddress); + TestedMemoryLength = PageAlignLength (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - TestedMemoryBaseAddress); FindLargestFreeRegion (&TestedMemoryBaseAddress, &TestedMemoryLength, (EFI_HOB_MEMORY_ALLOCATION *)GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION)); if (TestedMemoryLength < MinimalMemorySizeNeeded) { continue; @@ -2417,7 +2479,6 @@ CoreInitializeMemoryServices ( return EFI_SUCCESS; } - /** External function. Initializes the GCD and memory services based on the memory descriptor HOBs. This function is responsible for priming the GCD map and the @@ -2439,27 +2500,27 @@ CoreInitializeGcdServices ( IN UINT64 MemoryLength ) { - EFI_PEI_HOB_POINTERS Hob; - VOID *NewHobList; - EFI_HOB_HANDOFF_INFO_TABLE *PhitHob; - UINT8 SizeOfMemorySpace; - UINT8 SizeOfIoSpace; - EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; - EFI_PHYSICAL_ADDRESS BaseAddress; - UINT64 Length; - EFI_STATUS Status; - EFI_GCD_MAP_ENTRY *Entry; - EFI_GCD_MEMORY_TYPE GcdMemoryType; - EFI_GCD_IO_TYPE GcdIoType; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; - EFI_HOB_MEMORY_ALLOCATION *MemoryHob; - EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; - UINTN NumberOfDescriptors; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; - UINTN Index; - UINT64 Capabilities; - EFI_HOB_CPU * CpuHob; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMapHobList; + EFI_PEI_HOB_POINTERS Hob; + VOID *NewHobList; + EFI_HOB_HANDOFF_INFO_TABLE *PhitHob; + UINT8 SizeOfMemorySpace; + UINT8 SizeOfIoSpace; + EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; + EFI_PHYSICAL_ADDRESS BaseAddress; + UINT64 Length; + EFI_STATUS Status; + EFI_GCD_MAP_ENTRY *Entry; + EFI_GCD_MEMORY_TYPE GcdMemoryType; + EFI_GCD_IO_TYPE GcdIoType; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; + UINTN NumberOfDescriptors; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap; + UINTN Index; + UINT64 Capabilities; + EFI_HOB_CPU *CpuHob; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMapHobList; // // Cache the PHIT HOB for later use @@ -2501,48 +2562,50 @@ CoreInitializeGcdServices ( // // Walk the HOB list and add all resource descriptors to the GCD // - for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { - + for (Hob.Raw = *HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { GcdMemoryType = EfiGcdMemoryTypeNonExistent; GcdIoType = EfiGcdIoTypeNonExistent; if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - ResourceHob = Hob.ResourceDescriptor; switch (ResourceHob->ResourceType) { - case EFI_RESOURCE_SYSTEM_MEMORY: - if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == TESTED_MEMORY_ATTRIBUTES) { - if ((ResourceHob->ResourceAttribute & EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE) == EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE) { - GcdMemoryType = EfiGcdMemoryTypeMoreReliable; - } else { - GcdMemoryType = EfiGcdMemoryTypeSystemMemory; + case EFI_RESOURCE_SYSTEM_MEMORY: + if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == TESTED_MEMORY_ATTRIBUTES) { + if ((ResourceHob->ResourceAttribute & EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE) == EFI_RESOURCE_ATTRIBUTE_MORE_RELIABLE) { + GcdMemoryType = EfiGcdMemoryTypeMoreReliable; + } else { + GcdMemoryType = EfiGcdMemoryTypeSystemMemory; + } } - } - if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == INITIALIZED_MEMORY_ATTRIBUTES) { - GcdMemoryType = EfiGcdMemoryTypeReserved; - } - if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == PRESENT_MEMORY_ATTRIBUTES) { + + if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == INITIALIZED_MEMORY_ATTRIBUTES) { + GcdMemoryType = EfiGcdMemoryTypeReserved; + } + + if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) == PRESENT_MEMORY_ATTRIBUTES) { + GcdMemoryType = EfiGcdMemoryTypeReserved; + } + + if ((ResourceHob->ResourceAttribute & EFI_RESOURCE_ATTRIBUTE_PERSISTENT) == EFI_RESOURCE_ATTRIBUTE_PERSISTENT) { + GcdMemoryType = EfiGcdMemoryTypePersistent; + } + + break; + case EFI_RESOURCE_MEMORY_MAPPED_IO: + case EFI_RESOURCE_FIRMWARE_DEVICE: + GcdMemoryType = EfiGcdMemoryTypeMemoryMappedIo; + break; + case EFI_RESOURCE_MEMORY_MAPPED_IO_PORT: + case EFI_RESOURCE_MEMORY_RESERVED: GcdMemoryType = EfiGcdMemoryTypeReserved; - } - if ((ResourceHob->ResourceAttribute & EFI_RESOURCE_ATTRIBUTE_PERSISTENT) == EFI_RESOURCE_ATTRIBUTE_PERSISTENT) { - GcdMemoryType = EfiGcdMemoryTypePersistent; - } - break; - case EFI_RESOURCE_MEMORY_MAPPED_IO: - case EFI_RESOURCE_FIRMWARE_DEVICE: - GcdMemoryType = EfiGcdMemoryTypeMemoryMappedIo; - break; - case EFI_RESOURCE_MEMORY_MAPPED_IO_PORT: - case EFI_RESOURCE_MEMORY_RESERVED: - GcdMemoryType = EfiGcdMemoryTypeReserved; - break; - case EFI_RESOURCE_IO: - GcdIoType = EfiGcdIoTypeIo; - break; - case EFI_RESOURCE_IO_RESERVED: - GcdIoType = EfiGcdIoTypeReserved; - break; + break; + case EFI_RESOURCE_IO: + GcdIoType = EfiGcdIoTypeIo; + break; + case EFI_RESOURCE_IO_RESERVED: + GcdIoType = EfiGcdIoTypeReserved; + break; } if (GcdMemoryType != EfiGcdMemoryTypeNonExistent) { @@ -2582,8 +2645,10 @@ CoreInitializeGcdServices ( // Status = CoreGetMemorySpaceDescriptor (MemoryBaseAddress, &Descriptor); if (!EFI_ERROR (Status)) { - ASSERT ((Descriptor.GcdMemoryType == EfiGcdMemoryTypeSystemMemory) || - (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMoreReliable)); + ASSERT ( + (Descriptor.GcdMemoryType == EfiGcdMemoryTypeSystemMemory) || + (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMoreReliable) + ); Status = CoreAllocateMemorySpace ( EfiGcdAllocateAddress, Descriptor.GcdMemoryType, @@ -2599,11 +2664,11 @@ CoreInitializeGcdServices ( // Walk the HOB list and allocate all memory space that is consumed by memory allocation HOBs, // and Firmware Volume HOBs. Also update the EFI Memory Map with the memory allocation HOBs. // - for (Hob.Raw = *HobStart; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = *HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { - MemoryHob = Hob.MemoryAllocation; + MemoryHob = Hob.MemoryAllocation; BaseAddress = MemoryHob->AllocDescriptor.MemoryBaseAddress; - Status = CoreGetMemorySpaceDescriptor (BaseAddress, &Descriptor); + Status = CoreGetMemorySpaceDescriptor (BaseAddress, &Descriptor); if (!EFI_ERROR (Status)) { Status = CoreAllocateMemorySpace ( EfiGcdAllocateAddress, @@ -2616,7 +2681,8 @@ CoreInitializeGcdServices ( ); if (!EFI_ERROR (Status) && ((Descriptor.GcdMemoryType == EfiGcdMemoryTypeSystemMemory) || - (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMoreReliable))) { + (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMoreReliable))) + { CoreAddMemoryDescriptor ( MemoryHob->AllocDescriptor.MemoryType, MemoryHob->AllocDescriptor.MemoryBaseAddress, @@ -2629,16 +2695,16 @@ CoreInitializeGcdServices ( if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) { FirmwareVolumeHob = Hob.FirmwareVolume; - BaseAddress = FirmwareVolumeHob->BaseAddress; - Status = CoreAllocateMemorySpace ( - EfiGcdAllocateAddress, - EfiGcdMemoryTypeMemoryMappedIo, - 0, - FirmwareVolumeHob->Length, - &BaseAddress, - gDxeCoreImageHandle, - NULL - ); + BaseAddress = FirmwareVolumeHob->BaseAddress; + Status = CoreAllocateMemorySpace ( + EfiGcdAllocateAddress, + EfiGcdMemoryTypeMemoryMappedIo, + 0, + FirmwareVolumeHob->Length, + &BaseAddress, + gDxeCoreImageHandle, + NULL + ); } } @@ -2651,15 +2717,18 @@ CoreInitializeGcdServices ( MemorySpaceMapHobList = NULL; for (Index = 0; Index < NumberOfDescriptors; Index++) { if ((MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeSystemMemory) || - (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMoreReliable)) { + (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeMoreReliable)) + { if (MemorySpaceMap[Index].ImageHandle == NULL) { - BaseAddress = PageAlignAddress (MemorySpaceMap[Index].BaseAddress); - Length = PageAlignLength (MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - BaseAddress); - if (Length == 0 || MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length < BaseAddress) { + BaseAddress = PageAlignAddress (MemorySpaceMap[Index].BaseAddress); + Length = PageAlignLength (MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - BaseAddress); + if ((Length == 0) || (MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length < BaseAddress)) { continue; } - if (((UINTN) MemorySpaceMap[Index].BaseAddress <= (UINTN) (*HobStart)) && - ((UINTN) (MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length) >= (UINTN) PhitHob->EfiFreeMemoryBottom)) { + + if (((UINTN)MemorySpaceMap[Index].BaseAddress <= (UINTN)(*HobStart)) && + ((UINTN)(MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length) >= (UINTN)PhitHob->EfiFreeMemoryBottom)) + { // // Skip the memory space that covers HOB List, it should be processed // after HOB List relocation to avoid the resources allocated by others @@ -2668,6 +2737,7 @@ CoreInitializeGcdServices ( MemorySpaceMapHobList = &MemorySpaceMap[Index]; continue; } + CoreAddMemoryDescriptor ( EfiConventionalMemory, BaseAddress, @@ -2695,7 +2765,7 @@ CoreInitializeGcdServices ( // may have not enough remaining resource for HOB List. // NewHobList = AllocateCopyPool ( - (UINTN) PhitHob->EfiFreeMemoryBottom - (UINTN) (*HobStart), + (UINTN)PhitHob->EfiFreeMemoryBottom - (UINTN)(*HobStart), *HobStart ); ASSERT (NewHobList != NULL); @@ -2709,7 +2779,7 @@ CoreInitializeGcdServices ( // after HOB List relocation. // BaseAddress = PageAlignAddress (MemorySpaceMapHobList->BaseAddress); - Length = PageAlignLength (MemorySpaceMapHobList->BaseAddress + MemorySpaceMapHobList->Length - BaseAddress); + Length = PageAlignLength (MemorySpaceMapHobList->BaseAddress + MemorySpaceMapHobList->Length - BaseAddress); CoreAddMemoryDescriptor ( EfiConventionalMemory, BaseAddress, diff --git a/MdeModulePkg/Core/Dxe/Gcd/Gcd.h b/MdeModulePkg/Core/Dxe/Gcd/Gcd.h index 715687b928..d4a4dd7c1b 100644 --- a/MdeModulePkg/Core/Dxe/Gcd/Gcd.h +++ b/MdeModulePkg/Core/Dxe/Gcd/Gcd.h @@ -13,8 +13,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // GCD Operations // -#define GCD_MEMORY_SPACE_OPERATION 0x20 -#define GCD_IO_SPACE_OPERATION 0x40 +#define GCD_MEMORY_SPACE_OPERATION 0x20 +#define GCD_IO_SPACE_OPERATION 0x40 #define GCD_ADD_MEMORY_OPERATION (GCD_MEMORY_SPACE_OPERATION | 0) #define GCD_ALLOCATE_MEMORY_OPERATION (GCD_MEMORY_SPACE_OPERATION | 1) @@ -23,18 +23,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define GCD_SET_ATTRIBUTES_MEMORY_OPERATION (GCD_MEMORY_SPACE_OPERATION | 4) #define GCD_SET_CAPABILITIES_MEMORY_OPERATION (GCD_MEMORY_SPACE_OPERATION | 5) -#define GCD_ADD_IO_OPERATION (GCD_IO_SPACE_OPERATION | 0) -#define GCD_ALLOCATE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 1) -#define GCD_FREE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 2) -#define GCD_REMOVE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 3) +#define GCD_ADD_IO_OPERATION (GCD_IO_SPACE_OPERATION | 0) +#define GCD_ALLOCATE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 1) +#define GCD_FREE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 2) +#define GCD_REMOVE_IO_OPERATION (GCD_IO_SPACE_OPERATION | 3) // // The data structure used to convert from GCD attributes to EFI Memory Map attributes // typedef struct { - UINT64 Attribute; - UINT64 Capability; - BOOLEAN Memory; + UINT64 Attribute; + UINT64 Capability; + BOOLEAN Memory; } GCD_ATTRIBUTE_CONVERSION_ENTRY; #endif diff --git a/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c b/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c index 12a202417c..0b824c62b7 100644 --- a/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c +++ b/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c @@ -9,10 +9,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "Handle.h" - // // Driver Support Functions // + /** Connects one or more drivers to a controller. @@ -48,22 +48,22 @@ CoreConnectController ( IN BOOLEAN Recursive ) { - EFI_STATUS Status; - EFI_STATUS ReturnStatus; - IHANDLE *Handle; - PROTOCOL_INTERFACE *Prot; - LIST_ENTRY *Link; - LIST_ENTRY *ProtLink; - OPEN_PROTOCOL_DATA *OpenData; - EFI_DEVICE_PATH_PROTOCOL *AlignedRemainingDevicePath; - EFI_HANDLE *ChildHandleBuffer; - UINTN ChildHandleCount; - UINTN Index; - UINTN HandleFilePathSize; - UINTN RemainingDevicePathSize; - EFI_DEVICE_PATH_PROTOCOL *HandleFilePath; - EFI_DEVICE_PATH_PROTOCOL *FilePath; - EFI_DEVICE_PATH_PROTOCOL *TempFilePath; + EFI_STATUS Status; + EFI_STATUS ReturnStatus; + IHANDLE *Handle; + PROTOCOL_INTERFACE *Prot; + LIST_ENTRY *Link; + LIST_ENTRY *ProtLink; + OPEN_PROTOCOL_DATA *OpenData; + EFI_DEVICE_PATH_PROTOCOL *AlignedRemainingDevicePath; + EFI_HANDLE *ChildHandleBuffer; + UINTN ChildHandleCount; + UINTN Index; + UINTN HandleFilePathSize; + UINTN RemainingDevicePathSize; + EFI_DEVICE_PATH_PROTOCOL *HandleFilePath; + EFI_DEVICE_PATH_PROTOCOL *FilePath; + EFI_DEVICE_PATH_PROTOCOL *TempFilePath; // // Make sure ControllerHandle is valid @@ -87,25 +87,27 @@ CoreConnectController ( ASSERT (HandleFilePath != NULL); FilePath = HandleFilePath; TempFilePath = NULL; - if (RemainingDevicePath != NULL && !Recursive) { + if ((RemainingDevicePath != NULL) && !Recursive) { HandleFilePathSize = GetDevicePathSize (HandleFilePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); RemainingDevicePathSize = GetDevicePathSize (RemainingDevicePath); - TempFilePath = AllocateZeroPool (HandleFilePathSize + RemainingDevicePathSize); + TempFilePath = AllocateZeroPool (HandleFilePathSize + RemainingDevicePathSize); ASSERT (TempFilePath != NULL); CopyMem (TempFilePath, HandleFilePath, HandleFilePathSize); - CopyMem ((UINT8 *) TempFilePath + HandleFilePathSize, RemainingDevicePath, RemainingDevicePathSize); + CopyMem ((UINT8 *)TempFilePath + HandleFilePathSize, RemainingDevicePath, RemainingDevicePathSize); FilePath = TempFilePath; } + Status = gSecurity2->FileAuthentication ( - gSecurity2, - FilePath, - NULL, - 0, - FALSE - ); + gSecurity2, + FilePath, + NULL, + 0, + FALSE + ); if (TempFilePath != NULL) { FreePool (TempFilePath); } + if (EFI_ERROR (Status)) { return Status; } @@ -169,15 +171,15 @@ CoreConnectController ( return ReturnStatus; } - // // Count ControllerHandle's children // for (Link = Handle->Protocols.ForwardLink, ChildHandleCount = 0; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; - ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink != &Prot->OpenList; + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) { ChildHandleCount++; @@ -188,7 +190,7 @@ CoreConnectController ( // // Allocate a handle buffer for ControllerHandle's children // - ChildHandleBuffer = AllocatePool (ChildHandleCount * sizeof(EFI_HANDLE)); + ChildHandleBuffer = AllocatePool (ChildHandleCount * sizeof (EFI_HANDLE)); if (ChildHandleBuffer == NULL) { CoreReleaseProtocolLock (); return EFI_OUT_OF_RESOURCES; @@ -198,10 +200,11 @@ CoreConnectController ( // Fill in a handle buffer with ControllerHandle's children // for (Link = Handle->Protocols.ForwardLink, ChildHandleCount = 0; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; - ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink != &Prot->OpenList; + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) { ChildHandleBuffer[ChildHandleCount] = OpenData->ControllerHandle; @@ -236,7 +239,6 @@ CoreConnectController ( return ReturnStatus; } - /** Add Driver Binding Protocols from Context Driver Image Handles to sorted Driver Binding Protocol list. @@ -296,11 +298,11 @@ AddSortedDriverBindingProtocol ( // Retrieve the Driver Binding Protocol associated with each Driver Binding Handle // Status = CoreHandleProtocol ( - DriverBindingHandleBuffer[Index], - &gEfiDriverBindingProtocolGuid, - (VOID **) &DriverBinding - ); - if (EFI_ERROR (Status) || DriverBinding == NULL) { + DriverBindingHandleBuffer[Index], + &gEfiDriverBindingProtocolGuid, + (VOID **)&DriverBinding + ); + if (EFI_ERROR (Status) || (DriverBinding == NULL)) { continue; } @@ -319,21 +321,22 @@ AddSortedDriverBindingProtocol ( ); } } + return; } // // Retrieve the Driver Binding Protocol from DriverBindingHandle // - Status = CoreHandleProtocol( + Status = CoreHandleProtocol ( DriverBindingHandle, &gEfiDriverBindingProtocolGuid, - (VOID **) &DriverBinding + (VOID **)&DriverBinding ); // // If DriverBindingHandle does not support the Driver Binding Protocol then return // - if (EFI_ERROR (Status) || DriverBinding == NULL) { + if (EFI_ERROR (Status) || (DriverBinding == NULL)) { return; } @@ -352,6 +355,7 @@ AddSortedDriverBindingProtocol ( if (*NumberOfSortedDriverBindingProtocols < DriverBindingHandleCount) { SortedDriverBindingProtocols[*NumberOfSortedDriverBindingProtocols] = DriverBinding; } + *NumberOfSortedDriverBindingProtocols = *NumberOfSortedDriverBindingProtocols + 1; // @@ -364,7 +368,6 @@ AddSortedDriverBindingProtocol ( } } - /** Connects a controller to a driver. @@ -416,12 +419,12 @@ CoreConnectSingleController ( // // Initialize local variables // - DriverBindingHandleCount = 0; - DriverBindingHandleBuffer = NULL; - NumberOfSortedDriverBindingProtocols = 0; - SortedDriverBindingProtocols = NULL; - PlatformDriverOverride = NULL; - NewDriverBindingHandleBuffer = NULL; + DriverBindingHandleCount = 0; + DriverBindingHandleBuffer = NULL; + NumberOfSortedDriverBindingProtocols = 0; + SortedDriverBindingProtocols = NULL; + PlatformDriverOverride = NULL; + NewDriverBindingHandleBuffer = NULL; // // Get list of all Driver Binding Protocol Instances @@ -468,7 +471,7 @@ CoreConnectSingleController ( Status = CoreLocateProtocol ( &gEfiPlatformDriverOverrideProtocolGuid, NULL, - (VOID **) &PlatformDriverOverride + (VOID **)&PlatformDriverOverride ); if (!EFI_ERROR (Status) && (PlatformDriverOverride != NULL)) { DriverImageHandle = NULL; @@ -501,7 +504,7 @@ CoreConnectSingleController ( Status = CoreHandleProtocol ( DriverBindingHandleBuffer[Index], &gEfiDriverFamilyOverrideProtocolGuid, - (VOID **) &DriverFamilyOverride + (VOID **)&DriverFamilyOverride ); if (!EFI_ERROR (Status) && (DriverFamilyOverride != NULL)) { DriverFamilyOverrideVersion = DriverFamilyOverride->GetVersion (DriverFamilyOverride); @@ -532,7 +535,7 @@ CoreConnectSingleController ( Status = CoreHandleProtocol ( ControllerHandle, &gEfiBusSpecificDriverOverrideProtocolGuid, - (VOID **) &BusSpecificDriverOverride + (VOID **)&BusSpecificDriverOverride ); if (!EFI_ERROR (Status) && (BusSpecificDriverOverride != NULL)) { DriverImageHandle = NULL; @@ -608,9 +611,10 @@ CoreConnectSingleController ( HighestIndex = Index; } } + if (SortIndex != HighestIndex) { - DriverBinding = SortedDriverBindingProtocols[SortIndex]; - SortedDriverBindingProtocols[SortIndex] = SortedDriverBindingProtocols[HighestIndex]; + DriverBinding = SortedDriverBindingProtocols[SortIndex]; + SortedDriverBindingProtocols[SortIndex] = SortedDriverBindingProtocols[HighestIndex]; SortedDriverBindingProtocols[HighestIndex] = DriverBinding; } } @@ -620,19 +624,18 @@ CoreConnectSingleController ( // OneStarted = FALSE; do { - // // Loop through the sorted Driver Binding Protocol Instances in order, and see if // any of the Driver Binding Protocols support the controller specified by // ControllerHandle. // DriverBinding = NULL; - DriverFound = FALSE; + DriverFound = FALSE; for (Index = 0; (Index < NumberOfSortedDriverBindingProtocols) && !DriverFound; Index++) { if (SortedDriverBindingProtocols[Index] != NULL) { DriverBinding = SortedDriverBindingProtocols[Index]; PERF_DRIVER_BINDING_SUPPORT_BEGIN (DriverBinding->DriverBindingHandle, ControllerHandle); - Status = DriverBinding->Supported( + Status = DriverBinding->Supported ( DriverBinding, ControllerHandle, RemainingDevicePath @@ -640,7 +643,7 @@ CoreConnectSingleController ( PERF_DRIVER_BINDING_SUPPORT_END (DriverBinding->DriverBindingHandle, ControllerHandle); if (!EFI_ERROR (Status)) { SortedDriverBindingProtocols[Index] = NULL; - DriverFound = TRUE; + DriverFound = TRUE; // // A driver was found that supports ControllerHandle, so attempt to start the driver @@ -692,8 +695,6 @@ CoreConnectSingleController ( return EFI_NOT_FOUND; } - - /** Disonnects a controller from a driver @@ -734,24 +735,24 @@ CoreDisconnectController ( IN EFI_HANDLE ChildHandle OPTIONAL ) { - EFI_STATUS Status; - IHANDLE *Handle; - EFI_HANDLE *DriverImageHandleBuffer; - EFI_HANDLE *ChildBuffer; - UINTN Index; - UINTN HandleIndex; - UINTN DriverImageHandleCount; - UINTN ChildrenToStop; - UINTN ChildBufferCount; - UINTN StopCount; - BOOLEAN Duplicate; - BOOLEAN ChildHandleValid; - BOOLEAN DriverImageHandleValid; - LIST_ENTRY *Link; - LIST_ENTRY *ProtLink; - OPEN_PROTOCOL_DATA *OpenData; - PROTOCOL_INTERFACE *Prot; - EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; + EFI_STATUS Status; + IHANDLE *Handle; + EFI_HANDLE *DriverImageHandleBuffer; + EFI_HANDLE *ChildBuffer; + UINTN Index; + UINTN HandleIndex; + UINTN DriverImageHandleCount; + UINTN ChildrenToStop; + UINTN ChildBufferCount; + UINTN StopCount; + BOOLEAN Duplicate; + BOOLEAN ChildHandleValid; + BOOLEAN DriverImageHandleValid; + LIST_ENTRY *Link; + LIST_ENTRY *ProtLink; + OPEN_PROTOCOL_DATA *OpenData; + PROTOCOL_INTERFACE *Prot; + EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; // // Make sure ControllerHandle is valid @@ -793,16 +794,18 @@ CoreDisconnectController ( CoreAcquireProtocolLock (); for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { DriverImageHandleCount++; } } } + CoreReleaseProtocolLock (); // @@ -823,19 +826,21 @@ CoreDisconnectController ( CoreAcquireProtocolLock (); for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { Duplicate = FALSE; - for (Index = 0; Index< DriverImageHandleCount; Index++) { + for (Index = 0; Index < DriverImageHandleCount; Index++) { if (DriverImageHandleBuffer[Index] == OpenData->AgentHandle) { Duplicate = TRUE; break; } } + if (!Duplicate) { DriverImageHandleBuffer[DriverImageHandleCount] = OpenData->AgentHandle; DriverImageHandleCount++; @@ -843,12 +848,12 @@ CoreDisconnectController ( } } } + CoreReleaseProtocolLock (); } StopCount = 0; for (HandleIndex = 0; HandleIndex < DriverImageHandleCount; HandleIndex++) { - if (DriverImageHandleBuffer != NULL) { DriverImageHandle = DriverImageHandleBuffer[HandleIndex]; } @@ -861,7 +866,7 @@ CoreDisconnectController ( &gEfiDriverBindingProtocolGuid, (VOID **)&DriverBinding ); - if (EFI_ERROR (Status) || DriverBinding == NULL) { + if (EFI_ERROR (Status) || (DriverBinding == NULL)) { Status = EFI_INVALID_PARAMETER; goto Done; } @@ -870,30 +875,33 @@ CoreDisconnectController ( // Look at each protocol interface for a match // DriverImageHandleValid = FALSE; - ChildBufferCount = 0; + ChildBufferCount = 0; CoreAcquireProtocolLock (); for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if (OpenData->AgentHandle == DriverImageHandle) { if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0) { ChildBufferCount++; } + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { DriverImageHandleValid = TRUE; } } } } + CoreReleaseProtocolLock (); if (DriverImageHandleValid) { ChildHandleValid = FALSE; - ChildBuffer = NULL; + ChildBuffer = NULL; if (ChildBufferCount != 0) { ChildBuffer = AllocatePool (sizeof (EFI_HANDLE) * ChildBufferCount); if (ChildBuffer == NULL) { @@ -905,13 +913,15 @@ CoreDisconnectController ( CoreAcquireProtocolLock (); for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); for (ProtLink = Prot->OpenList.ForwardLink; ProtLink != &Prot->OpenList; - ProtLink = ProtLink->ForwardLink) { + ProtLink = ProtLink->ForwardLink) + { OpenData = CR (ProtLink, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->AgentHandle == DriverImageHandle) && - ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0)) { + ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER) != 0)) + { Duplicate = FALSE; for (Index = 0; Index < ChildBufferCount; Index++) { if (ChildBuffer[Index] == OpenData->ControllerHandle) { @@ -919,34 +929,39 @@ CoreDisconnectController ( break; } } + if (!Duplicate) { ChildBuffer[ChildBufferCount] = OpenData->ControllerHandle; if (ChildHandle == ChildBuffer[ChildBufferCount]) { ChildHandleValid = TRUE; } + ChildBufferCount++; } } } } + CoreReleaseProtocolLock (); } - if (ChildHandle == NULL || ChildHandleValid) { + if ((ChildHandle == NULL) || ChildHandleValid) { ChildrenToStop = 0; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; if (ChildBufferCount > 0) { if (ChildHandle != NULL) { ChildrenToStop = 1; - Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, &ChildHandle); + Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, &ChildHandle); } else { ChildrenToStop = ChildBufferCount; - Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, ChildBuffer); + Status = DriverBinding->Stop (DriverBinding, ControllerHandle, ChildrenToStop, ChildBuffer); } } + if (!EFI_ERROR (Status) && ((ChildHandle == NULL) || (ChildBufferCount == ChildrenToStop))) { Status = DriverBinding->Stop (DriverBinding, ControllerHandle, 0, NULL); } + if (!EFI_ERROR (Status)) { StopCount++; } diff --git a/MdeModulePkg/Core/Dxe/Hand/Handle.c b/MdeModulePkg/Core/Dxe/Hand/Handle.c index 92979281b7..bd6c57843e 100644 --- a/MdeModulePkg/Core/Dxe/Hand/Handle.c +++ b/MdeModulePkg/Core/Dxe/Hand/Handle.c @@ -9,19 +9,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" #include "Handle.h" - // // mProtocolDatabase - A list of all protocols in the system. (simple list for now) // gHandleList - A list of all the handles in the system // gProtocolDatabaseLock - Lock to protect the mProtocolDatabase // gHandleDatabaseKey - The Key to show that the handle has been created/modified // -LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); -LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); -EFI_LOCK gProtocolDatabaseLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -UINT64 gHandleDatabaseKey = 0; - - +LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); +LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); +EFI_LOCK gProtocolDatabaseLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +UINT64 gHandleDatabaseKey = 0; /** Acquire lock on gProtocolDatabaseLock. @@ -35,8 +32,6 @@ CoreAcquireProtocolLock ( CoreAcquireLock (&gProtocolDatabaseLock); } - - /** Release lock on gProtocolDatabaseLock. @@ -49,8 +44,6 @@ CoreReleaseProtocolLock ( CoreReleaseLock (&gProtocolDatabaseLock); } - - /** Check whether a handle is a valid EFI_HANDLE The gProtocolDatabaseLock must be owned @@ -63,21 +56,21 @@ CoreReleaseProtocolLock ( **/ EFI_STATUS CoreValidateHandle ( - IN EFI_HANDLE UserHandle + IN EFI_HANDLE UserHandle ) { - IHANDLE *Handle; - LIST_ENTRY *Link; + IHANDLE *Handle; + LIST_ENTRY *Link; if (UserHandle == NULL) { return EFI_INVALID_PARAMETER; } - ASSERT_LOCKED(&gProtocolDatabaseLock); + ASSERT_LOCKED (&gProtocolDatabaseLock); for (Link = gHandleList.BackLink; Link != &gHandleList; Link = Link->BackLink) { Handle = CR (Link, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); - if (Handle == (IHANDLE *) UserHandle) { + if (Handle == (IHANDLE *)UserHandle) { return EFI_SUCCESS; } } @@ -85,8 +78,6 @@ CoreValidateHandle ( return EFI_INVALID_PARAMETER; } - - /** Finds the protocol entry for the requested protocol. The gProtocolDatabaseLock must be owned @@ -99,15 +90,15 @@ CoreValidateHandle ( **/ PROTOCOL_ENTRY * CoreFindProtocolEntry ( - IN EFI_GUID *Protocol, - IN BOOLEAN Create + IN EFI_GUID *Protocol, + IN BOOLEAN Create ) { - LIST_ENTRY *Link; - PROTOCOL_ENTRY *Item; - PROTOCOL_ENTRY *ProtEntry; + LIST_ENTRY *Link; + PROTOCOL_ENTRY *Item; + PROTOCOL_ENTRY *ProtEntry; - ASSERT_LOCKED(&gProtocolDatabaseLock); + ASSERT_LOCKED (&gProtocolDatabaseLock); // // Search the database for the matching GUID @@ -116,11 +107,10 @@ CoreFindProtocolEntry ( ProtEntry = NULL; for (Link = mProtocolDatabase.ForwardLink; Link != &mProtocolDatabase; - Link = Link->ForwardLink) { - - Item = CR(Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); + Link = Link->ForwardLink) + { + Item = CR (Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); if (CompareGuid (&Item->ProtocolID, Protocol)) { - // // This is the protocol entry // @@ -135,7 +125,7 @@ CoreFindProtocolEntry ( // allocate a new entry // if ((ProtEntry == NULL) && Create) { - ProtEntry = AllocatePool (sizeof(PROTOCOL_ENTRY)); + ProtEntry = AllocatePool (sizeof (PROTOCOL_ENTRY)); if (ProtEntry != NULL) { // @@ -156,8 +146,6 @@ CoreFindProtocolEntry ( return ProtEntry; } - - /** Finds the protocol instance for the requested handle and protocol. Note: This function doesn't do parameters checking, it's caller's responsibility @@ -172,16 +160,16 @@ CoreFindProtocolEntry ( **/ PROTOCOL_INTERFACE * CoreFindProtocolInterface ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ) { PROTOCOL_INTERFACE *Prot; PROTOCOL_ENTRY *ProtEntry; LIST_ENTRY *Link; - ASSERT_LOCKED(&gProtocolDatabaseLock); + ASSERT_LOCKED (&gProtocolDatabaseLock); Prot = NULL; // @@ -190,17 +178,15 @@ CoreFindProtocolInterface ( ProtEntry = CoreFindProtocolEntry (Protocol, FALSE); if (ProtEntry != NULL) { - // // Look at each protocol interface for any matches // - for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link=Link->ForwardLink) { - + for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { // // If this protocol interface matches, remove it // - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); - if (Prot->Interface == Interface && Prot->Protocol == ProtEntry) { + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + if ((Prot->Interface == Interface) && (Prot->Protocol == ProtEntry)) { break; } @@ -211,7 +197,6 @@ CoreFindProtocolInterface ( return Prot; } - /** Removes an event from a register protocol notify list on a protocol. @@ -224,31 +209,31 @@ CoreFindProtocolInterface ( **/ EFI_STATUS CoreUnregisterProtocolNotifyEvent ( - IN EFI_EVENT Event + IN EFI_EVENT Event ) { - LIST_ENTRY *Link; - PROTOCOL_ENTRY *ProtEntry; - LIST_ENTRY *NotifyLink; - PROTOCOL_NOTIFY *ProtNotify; + LIST_ENTRY *Link; + PROTOCOL_ENTRY *ProtEntry; + LIST_ENTRY *NotifyLink; + PROTOCOL_NOTIFY *ProtNotify; CoreAcquireProtocolLock (); for ( Link = mProtocolDatabase.ForwardLink; Link != &mProtocolDatabase; - Link = Link->ForwardLink) { - - ProtEntry = CR(Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); + Link = Link->ForwardLink) + { + ProtEntry = CR (Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); for ( NotifyLink = ProtEntry->Notify.ForwardLink; NotifyLink != &ProtEntry->Notify; - NotifyLink = NotifyLink->ForwardLink) { - - ProtNotify = CR(NotifyLink, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + NotifyLink = NotifyLink->ForwardLink) + { + ProtNotify = CR (NotifyLink, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); if (ProtNotify->Event == Event) { - RemoveEntryList(&ProtNotify->Link); - CoreFreePool(ProtNotify); + RemoveEntryList (&ProtNotify->Link); + CoreFreePool (ProtNotify); CoreReleaseProtocolLock (); return EFI_SUCCESS; } @@ -259,8 +244,6 @@ CoreUnregisterProtocolNotifyEvent ( return EFI_NOT_FOUND; } - - /** Removes all the events in the protocol database that match Event. @@ -272,10 +255,10 @@ CoreUnregisterProtocolNotifyEvent ( **/ EFI_STATUS CoreUnregisterProtocolNotify ( - IN EFI_EVENT Event + IN EFI_EVENT Event ) { - EFI_STATUS Status; + EFI_STATUS Status; do { Status = CoreUnregisterProtocolNotifyEvent (Event); @@ -284,9 +267,6 @@ CoreUnregisterProtocolNotify ( return EFI_SUCCESS; } - - - /** Wrapper function to CoreInstallProtocolInterfaceNotify. This is the public API which Calls the private one which contains a BOOLEAN parameter for notifications @@ -304,22 +284,21 @@ CoreUnregisterProtocolNotify ( EFI_STATUS EFIAPI CoreInstallProtocolInterface ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface ) { return CoreInstallProtocolInterfaceNotify ( - UserHandle, - Protocol, - InterfaceType, - Interface, - TRUE - ); + UserHandle, + Protocol, + InterfaceType, + Interface, + TRUE + ); } - /** Installs a protocol interface into the boot services environment. @@ -339,11 +318,11 @@ CoreInstallProtocolInterface ( **/ EFI_STATUS CoreInstallProtocolInterfaceNotify ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface, - IN BOOLEAN Notify + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface, + IN BOOLEAN Notify ) { PROTOCOL_INTERFACE *Prot; @@ -356,7 +335,7 @@ CoreInstallProtocolInterfaceNotify ( // returns EFI_INVALID_PARAMETER if InterfaceType is invalid. // Also added check for invalid UserHandle and Protocol pointers. // - if (UserHandle == NULL || Protocol == NULL) { + if ((UserHandle == NULL) || (Protocol == NULL)) { return EFI_INVALID_PARAMETER; } @@ -367,10 +346,10 @@ CoreInstallProtocolInterfaceNotify ( // // Print debug message // - DEBUG((DEBUG_INFO, "InstallProtocolInterface: %g %p\n", Protocol, Interface)); + DEBUG ((DEBUG_INFO, "InstallProtocolInterface: %g %p\n", Protocol, Interface)); Status = EFI_OUT_OF_RESOURCES; - Prot = NULL; + Prot = NULL; Handle = NULL; if (*UserHandle != NULL) { @@ -396,7 +375,7 @@ CoreInstallProtocolInterfaceNotify ( // // Allocate a new protocol interface structure // - Prot = AllocateZeroPool (sizeof(PROTOCOL_INTERFACE)); + Prot = AllocateZeroPool (sizeof (PROTOCOL_INTERFACE)); if (Prot == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -407,7 +386,7 @@ CoreInstallProtocolInterfaceNotify ( // Handle = (IHANDLE *)*UserHandle; if (Handle == NULL) { - Handle = AllocateZeroPool (sizeof(IHANDLE)); + Handle = AllocateZeroPool (sizeof (IHANDLE)); if (Handle == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -433,7 +412,7 @@ CoreInstallProtocolInterfaceNotify ( } else { Status = CoreValidateHandle (Handle); if (EFI_ERROR (Status)) { - DEBUG((DEBUG_ERROR, "InstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); + DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); goto Done; } } @@ -447,8 +426,8 @@ CoreInstallProtocolInterfaceNotify ( // Initialize the protocol interface structure // Prot->Signature = PROTOCOL_INTERFACE_SIGNATURE; - Prot->Handle = Handle; - Prot->Protocol = ProtEntry; + Prot->Handle = Handle; + Prot->Protocol = ProtEntry; Prot->Interface = Interface; // @@ -475,6 +454,7 @@ CoreInstallProtocolInterfaceNotify ( if (Notify) { CoreNotifyProtocolEntry (ProtEntry); } + Status = EFI_SUCCESS; Done: @@ -494,15 +474,13 @@ Done: if (Prot != NULL) { CoreFreePool (Prot); } - DEBUG((DEBUG_ERROR, "InstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); + + DEBUG ((DEBUG_ERROR, "InstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); } return Status; } - - - /** Installs a list of protocol interface into the boot services environment. This function calls InstallProtocolInterface() in a loop. If any error @@ -528,7 +506,7 @@ Done: EFI_STATUS EFIAPI CoreInstallMultipleProtocolInterfaces ( - IN OUT EFI_HANDLE *Handle, + IN OUT EFI_HANDLE *Handle, ... ) { @@ -549,7 +527,7 @@ CoreInstallMultipleProtocolInterfaces ( // // Syncronize with notifcations. // - OldTpl = CoreRaiseTpl (TPL_NOTIFY); + OldTpl = CoreRaiseTpl (TPL_NOTIFY); OldHandle = *Handle; // @@ -573,8 +551,8 @@ CoreInstallMultipleProtocolInterfaces ( if (CompareGuid (Protocol, &gEfiDevicePathProtocolGuid)) { DeviceHandle = NULL; DevicePath = Interface; - Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &DevicePath, &DeviceHandle); - if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd(DevicePath)) { + Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &DevicePath, &DeviceHandle); + if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (DevicePath)) { Status = EFI_ALREADY_STARTED; continue; } @@ -585,6 +563,7 @@ CoreInstallMultipleProtocolInterfaces ( // Status = CoreInstallProtocolInterface (Handle, Protocol, EFI_NATIVE_INTERFACE, Interface); } + VA_END (Args); // @@ -595,11 +574,12 @@ CoreInstallMultipleProtocolInterfaces ( // Reset the va_arg back to the first argument. // VA_START (Args, Handle); - for (; Index > 1; Index--) { - Protocol = VA_ARG (Args, EFI_GUID *); + for ( ; Index > 1; Index--) { + Protocol = VA_ARG (Args, EFI_GUID *); Interface = VA_ARG (Args, VOID *); CoreUninstallProtocolInterface (*Handle, Protocol, Interface); } + VA_END (Args); *Handle = OldHandle; @@ -612,7 +592,6 @@ CoreInstallMultipleProtocolInterfaces ( return Status; } - /** Attempts to disconnect all drivers that are using the protocol interface being queried. If failed, reconnect all drivers disconnected. @@ -629,14 +608,14 @@ CoreInstallMultipleProtocolInterfaces ( **/ EFI_STATUS CoreDisconnectControllersUsingProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN PROTOCOL_INTERFACE *Prot + IN EFI_HANDLE UserHandle, + IN PROTOCOL_INTERFACE *Prot ) { - EFI_STATUS Status; - BOOLEAN ItemFound; - LIST_ENTRY *Link; - OPEN_PROTOCOL_DATA *OpenData; + EFI_STATUS Status; + BOOLEAN ItemFound; + LIST_ENTRY *Link; + OPEN_PROTOCOL_DATA *OpenData; Status = EFI_SUCCESS; @@ -654,6 +633,7 @@ CoreDisconnectControllersUsingProtocolInterface ( if (!EFI_ERROR (Status)) { ItemFound = TRUE; } + break; } } @@ -666,7 +646,8 @@ CoreDisconnectControllersUsingProtocolInterface ( for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList;) { OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); if ((OpenData->Attributes & - (EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL | EFI_OPEN_PROTOCOL_GET_PROTOCOL | EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) != 0) { + (EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL | EFI_OPEN_PROTOCOL_GET_PROTOCOL | EFI_OPEN_PROTOCOL_TEST_PROTOCOL)) != 0) + { Link = RemoveEntryList (&OpenData->Link); Prot->OpenListCount--; CoreFreePool (OpenData); @@ -689,8 +670,6 @@ CoreDisconnectControllersUsingProtocolInterface ( return Status; } - - /** Uninstalls all instances of a protocol:interfacer from a handle. If the last protocol interface is remove from the handle, the @@ -707,14 +686,14 @@ CoreDisconnectControllersUsingProtocolInterface ( EFI_STATUS EFIAPI CoreUninstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *Interface ) { - EFI_STATUS Status; - IHANDLE *Handle; - PROTOCOL_INTERFACE *Prot; + EFI_STATUS Status; + IHANDLE *Handle; + PROTOCOL_INTERFACE *Prot; // // Check that Protocol is valid @@ -803,8 +782,6 @@ Done: return Status; } - - /** Uninstalls a list of protocol interface in the boot services environment. This function calls UninstallProtocolInterface() in a loop. This is @@ -830,15 +807,15 @@ Done: EFI_STATUS EFIAPI CoreUninstallMultipleProtocolInterfaces ( - IN EFI_HANDLE Handle, + IN EFI_HANDLE Handle, ... ) { - EFI_STATUS Status; - VA_LIST Args; - EFI_GUID *Protocol; - VOID *Interface; - UINTN Index; + EFI_STATUS Status; + VA_LIST Args; + EFI_GUID *Protocol; + VOID *Interface; + UINTN Index; VA_START (Args, Handle); for (Index = 0, Status = EFI_SUCCESS; !EFI_ERROR (Status); Index++) { @@ -857,6 +834,7 @@ CoreUninstallMultipleProtocolInterfaces ( // Status = CoreUninstallProtocolInterface (Handle, Protocol, Interface); } + VA_END (Args); // @@ -868,11 +846,12 @@ CoreUninstallMultipleProtocolInterfaces ( // Reset the va_arg back to the first argument. // VA_START (Args, Handle); - for (; Index > 1; Index--) { - Protocol = VA_ARG(Args, EFI_GUID *); - Interface = VA_ARG(Args, VOID *); + for ( ; Index > 1; Index--) { + Protocol = VA_ARG (Args, EFI_GUID *); + Interface = VA_ARG (Args, VOID *); CoreInstallProtocolInterface (&Handle, Protocol, EFI_NATIVE_INTERFACE, Interface); } + VA_END (Args); Status = EFI_INVALID_PARAMETER; } @@ -880,7 +859,6 @@ CoreUninstallMultipleProtocolInterfaces ( return Status; } - /** Locate a certain GUID protocol interface in a Handle's protocols. @@ -892,8 +870,8 @@ CoreUninstallMultipleProtocolInterfaces ( **/ PROTOCOL_INTERFACE * CoreGetProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol ) { EFI_STATUS Status; @@ -913,17 +891,16 @@ CoreGetProtocolInterface ( // Look at each protocol interface for a match // for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); ProtEntry = Prot->Protocol; if (CompareGuid (&ProtEntry->ProtocolID, Protocol)) { return Prot; } } + return NULL; } - - /** Queries a handle to determine if it supports a specified protocol. @@ -942,23 +919,21 @@ CoreGetProtocolInterface ( EFI_STATUS EFIAPI CoreHandleProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface ) { return CoreOpenProtocol ( - UserHandle, - Protocol, - Interface, - gDxeCoreImageHandle, - NULL, - EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL - ); + UserHandle, + Protocol, + Interface, + gDxeCoreImageHandle, + NULL, + EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL + ); } - - /** Locates the installed protocol handler for the handle, and invokes it to obtain the protocol interface. Usage information @@ -982,12 +957,12 @@ CoreHandleProtocol ( EFI_STATUS EFIAPI CoreOpenProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface OPTIONAL, - IN EFI_HANDLE ImageHandle, - IN EFI_HANDLE ControllerHandle, - IN UINT32 Attributes + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface OPTIONAL, + IN EFI_HANDLE ImageHandle, + IN EFI_HANDLE ControllerHandle, + IN UINT32 Attributes ) { EFI_STATUS Status; @@ -1030,47 +1005,52 @@ CoreOpenProtocol ( // Check for invalid Attributes // switch (Attributes) { - case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER : - Status = CoreValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - goto Done; - } - Status = CoreValidateHandle (ControllerHandle); - if (EFI_ERROR (Status)) { - goto Done; - } - if (UserHandle == ControllerHandle) { + case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: + Status = CoreValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + goto Done; + } + + Status = CoreValidateHandle (ControllerHandle); + if (EFI_ERROR (Status)) { + goto Done; + } + + if (UserHandle == ControllerHandle) { + Status = EFI_INVALID_PARAMETER; + goto Done; + } + + break; + case EFI_OPEN_PROTOCOL_BY_DRIVER: + case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: + Status = CoreValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + goto Done; + } + + Status = CoreValidateHandle (ControllerHandle); + if (EFI_ERROR (Status)) { + goto Done; + } + + break; + case EFI_OPEN_PROTOCOL_EXCLUSIVE: + Status = CoreValidateHandle (ImageHandle); + if (EFI_ERROR (Status)) { + goto Done; + } + + break; + case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: + case EFI_OPEN_PROTOCOL_GET_PROTOCOL: + case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: + break; + default: Status = EFI_INVALID_PARAMETER; goto Done; - } - break; - case EFI_OPEN_PROTOCOL_BY_DRIVER : - case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE : - Status = CoreValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - goto Done; - } - Status = CoreValidateHandle (ControllerHandle); - if (EFI_ERROR (Status)) { - goto Done; - } - break; - case EFI_OPEN_PROTOCOL_EXCLUSIVE : - Status = CoreValidateHandle (ImageHandle); - if (EFI_ERROR (Status)) { - goto Done; - } - break; - case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL : - case EFI_OPEN_PROTOCOL_GET_PROTOCOL : - case EFI_OPEN_PROTOCOL_TEST_PROTOCOL : - break; - default: - Status = EFI_INVALID_PARAMETER; - goto Done; } - // // Look at each protocol interface for a match // @@ -1082,10 +1062,10 @@ CoreOpenProtocol ( Status = EFI_SUCCESS; - ByDriver = FALSE; - Exclusive = FALSE; + ByDriver = FALSE; + Exclusive = FALSE; for ( Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); ExactMatch = (BOOLEAN)((OpenData->AgentHandle == ImageHandle) && (OpenData->Attributes == Attributes) && (OpenData->ControllerHandle == ControllerHandle)); @@ -1096,6 +1076,7 @@ CoreOpenProtocol ( goto Done; } } + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_EXCLUSIVE) != 0) { Exclusive = TRUE; } else if (ExactMatch) { @@ -1113,62 +1094,66 @@ CoreOpenProtocol ( // switch (Attributes) { - case EFI_OPEN_PROTOCOL_BY_DRIVER : - if (Exclusive || ByDriver) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - break; - case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE : - case EFI_OPEN_PROTOCOL_EXCLUSIVE : - if (Exclusive) { - Status = EFI_ACCESS_DENIED; - goto Done; - } - if (ByDriver) { - do { - Disconnect = FALSE; - for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { - OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { - Disconnect = TRUE; - CoreReleaseProtocolLock (); - Status = CoreDisconnectController (UserHandle, OpenData->AgentHandle, NULL); - CoreAcquireProtocolLock (); - if (EFI_ERROR (Status)) { - Status = EFI_ACCESS_DENIED; - goto Done; - } else { - break; + case EFI_OPEN_PROTOCOL_BY_DRIVER: + if (Exclusive || ByDriver) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + break; + case EFI_OPEN_PROTOCOL_BY_DRIVER | EFI_OPEN_PROTOCOL_EXCLUSIVE: + case EFI_OPEN_PROTOCOL_EXCLUSIVE: + if (Exclusive) { + Status = EFI_ACCESS_DENIED; + goto Done; + } + + if (ByDriver) { + do { + Disconnect = FALSE; + for (Link = Prot->OpenList.ForwardLink; Link != &Prot->OpenList; Link = Link->ForwardLink) { + OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); + if ((OpenData->Attributes & EFI_OPEN_PROTOCOL_BY_DRIVER) != 0) { + Disconnect = TRUE; + CoreReleaseProtocolLock (); + Status = CoreDisconnectController (UserHandle, OpenData->AgentHandle, NULL); + CoreAcquireProtocolLock (); + if (EFI_ERROR (Status)) { + Status = EFI_ACCESS_DENIED; + goto Done; + } else { + break; + } } } - } - } while (Disconnect); - } - break; - case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER : - case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL : - case EFI_OPEN_PROTOCOL_GET_PROTOCOL : - case EFI_OPEN_PROTOCOL_TEST_PROTOCOL : - break; + } while (Disconnect); + } + + break; + case EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER: + case EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL: + case EFI_OPEN_PROTOCOL_GET_PROTOCOL: + case EFI_OPEN_PROTOCOL_TEST_PROTOCOL: + break; } if (ImageHandle == NULL) { Status = EFI_SUCCESS; goto Done; } + // // Create new entry // - OpenData = AllocatePool (sizeof(OPEN_PROTOCOL_DATA)); + OpenData = AllocatePool (sizeof (OPEN_PROTOCOL_DATA)); if (OpenData == NULL) { Status = EFI_OUT_OF_RESOURCES; } else { - OpenData->Signature = OPEN_PROTOCOL_DATA_SIGNATURE; - OpenData->AgentHandle = ImageHandle; - OpenData->ControllerHandle = ControllerHandle; - OpenData->Attributes = Attributes; - OpenData->OpenCount = 1; + OpenData->Signature = OPEN_PROTOCOL_DATA_SIGNATURE; + OpenData->AgentHandle = ImageHandle; + OpenData->ControllerHandle = ControllerHandle; + OpenData->Attributes = Attributes; + OpenData->OpenCount = 1; InsertTailList (&Prot->OpenList, &OpenData->Link); Prot->OpenListCount++; Status = EFI_SUCCESS; @@ -1181,7 +1166,7 @@ Done: // Keep Interface unmodified in case of any Error // except EFI_ALREADY_STARTED and EFI_UNSUPPORTED. // - if (!EFI_ERROR (Status) || Status == EFI_ALREADY_STARTED) { + if (!EFI_ERROR (Status) || (Status == EFI_ALREADY_STARTED)) { // // According to above logic, if 'Prot' is NULL, then the 'Status' must be // EFI_UNSUPPORTED. Here the 'Status' is not EFI_UNSUPPORTED, so 'Prot' @@ -1211,8 +1196,6 @@ Done: return Status; } - - /** Closes a protocol on a handle that was opened using OpenProtocol(). @@ -1241,10 +1224,10 @@ Done: EFI_STATUS EFIAPI CoreCloseProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN EFI_HANDLE AgentHandle, - IN EFI_HANDLE ControllerHandle + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN EFI_HANDLE AgentHandle, + IN EFI_HANDLE ControllerHandle ) { EFI_STATUS Status; @@ -1264,16 +1247,19 @@ CoreCloseProtocol ( if (EFI_ERROR (Status)) { goto Done; } + Status = CoreValidateHandle (AgentHandle); if (EFI_ERROR (Status)) { goto Done; } + if (ControllerHandle != NULL) { Status = CoreValidateHandle (ControllerHandle); if (EFI_ERROR (Status)) { goto Done; } } + if (Protocol == NULL) { Status = EFI_INVALID_PARAMETER; goto Done; @@ -1282,7 +1268,7 @@ CoreCloseProtocol ( // // Look at each protocol interface for a match // - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; ProtocolInterface = CoreGetProtocolInterface (UserHandle, Protocol); if (ProtocolInterface == NULL) { goto Done; @@ -1294,12 +1280,12 @@ CoreCloseProtocol ( Link = ProtocolInterface->OpenList.ForwardLink; while (Link != &ProtocolInterface->OpenList) { OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); - Link = Link->ForwardLink; + Link = Link->ForwardLink; if ((OpenData->AgentHandle == AgentHandle) && (OpenData->ControllerHandle == ControllerHandle)) { - RemoveEntryList (&OpenData->Link); - ProtocolInterface->OpenListCount--; - CoreFreePool (OpenData); - Status = EFI_SUCCESS; + RemoveEntryList (&OpenData->Link); + ProtocolInterface->OpenListCount--; + CoreFreePool (OpenData); + Status = EFI_SUCCESS; } } @@ -1311,9 +1297,6 @@ Done: return Status; } - - - /** Return information about Opened protocols in the system @@ -1332,22 +1315,22 @@ Done: EFI_STATUS EFIAPI CoreOpenProtocolInformation ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, - OUT UINTN *EntryCount + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT EFI_OPEN_PROTOCOL_INFORMATION_ENTRY **EntryBuffer, + OUT UINTN *EntryCount ) { - EFI_STATUS Status; - PROTOCOL_INTERFACE *ProtocolInterface; - LIST_ENTRY *Link; - OPEN_PROTOCOL_DATA *OpenData; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *Buffer; - UINTN Count; - UINTN Size; + EFI_STATUS Status; + PROTOCOL_INTERFACE *ProtocolInterface; + LIST_ENTRY *Link; + OPEN_PROTOCOL_DATA *OpenData; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *Buffer; + UINTN Count; + UINTN Size; *EntryBuffer = NULL; - *EntryCount = 0; + *EntryCount = 0; // // Lock the protocol database @@ -1357,7 +1340,7 @@ CoreOpenProtocolInformation ( // // Look at each protocol interface for a match // - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; ProtocolInterface = CoreGetProtocolInterface (UserHandle, Protocol); if (ProtocolInterface == NULL) { goto Done; @@ -1367,17 +1350,18 @@ CoreOpenProtocolInformation ( // Count the number of Open Entries // for ( Link = ProtocolInterface->OpenList.ForwardLink, Count = 0; - (Link != &ProtocolInterface->OpenList) ; - Link = Link->ForwardLink ) { + (Link != &ProtocolInterface->OpenList); + Link = Link->ForwardLink ) + { Count++; } ASSERT (Count == ProtocolInterface->OpenListCount); if (Count == 0) { - Size = sizeof(EFI_OPEN_PROTOCOL_INFORMATION_ENTRY); + Size = sizeof (EFI_OPEN_PROTOCOL_INFORMATION_ENTRY); } else { - Size = Count * sizeof(EFI_OPEN_PROTOCOL_INFORMATION_ENTRY); + Size = Count * sizeof (EFI_OPEN_PROTOCOL_INFORMATION_ENTRY); } Buffer = AllocatePool (Size); @@ -1389,7 +1373,8 @@ CoreOpenProtocolInformation ( Status = EFI_SUCCESS; for ( Link = ProtocolInterface->OpenList.ForwardLink, Count = 0; (Link != &ProtocolInterface->OpenList); - Link = Link->ForwardLink, Count++ ) { + Link = Link->ForwardLink, Count++ ) + { OpenData = CR (Link, OPEN_PROTOCOL_DATA, Link, OPEN_PROTOCOL_DATA_SIGNATURE); Buffer[Count].AgentHandle = OpenData->AgentHandle; @@ -1399,7 +1384,7 @@ CoreOpenProtocolInformation ( } *EntryBuffer = Buffer; - *EntryCount = Count; + *EntryCount = Count; Done: // @@ -1409,9 +1394,6 @@ Done: return Status; } - - - /** Retrieves the list of protocol interface GUIDs that are installed on a handle in a buffer allocated from pool. @@ -1438,17 +1420,17 @@ Done: EFI_STATUS EFIAPI CoreProtocolsPerHandle ( - IN EFI_HANDLE UserHandle, - OUT EFI_GUID ***ProtocolBuffer, - OUT UINTN *ProtocolBufferCount + IN EFI_HANDLE UserHandle, + OUT EFI_GUID ***ProtocolBuffer, + OUT UINTN *ProtocolBufferCount ) { - EFI_STATUS Status; - IHANDLE *Handle; - PROTOCOL_INTERFACE *Prot; - LIST_ENTRY *Link; - UINTN ProtocolCount; - EFI_GUID **Buffer; + EFI_STATUS Status; + IHANDLE *Handle; + PROTOCOL_INTERFACE *Prot; + LIST_ENTRY *Link; + UINTN ProtocolCount; + EFI_GUID **Buffer; if (ProtocolBuffer == NULL) { return EFI_INVALID_PARAMETER; @@ -1489,15 +1471,17 @@ CoreProtocolsPerHandle ( goto Done; } - *ProtocolBuffer = Buffer; + *ProtocolBuffer = Buffer; *ProtocolBufferCount = ProtocolCount; for ( Link = Handle->Protocols.ForwardLink, ProtocolCount = 0; Link != &Handle->Protocols; - Link = Link->ForwardLink, ProtocolCount++) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Link = Link->ForwardLink, ProtocolCount++) + { + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); Buffer[ProtocolCount] = &(Prot->Protocol->ProtocolID); } + Status = EFI_SUCCESS; Done: @@ -1505,8 +1489,6 @@ Done: return Status; } - - /** return handle database key. @@ -1522,8 +1504,6 @@ CoreGetHandleDatabaseKey ( return gHandleDatabaseKey; } - - /** Go connect any handles that were created or modified while a image executed. @@ -1536,11 +1516,11 @@ CoreConnectHandlesByKey ( UINT64 Key ) { - UINTN Count; - LIST_ENTRY *Link; - EFI_HANDLE *HandleBuffer; - IHANDLE *Handle; - UINTN Index; + UINTN Count; + LIST_ENTRY *Link; + EFI_HANDLE *HandleBuffer; + IHANDLE *Handle; + UINTN Index; // // Lock the protocol database @@ -1579,5 +1559,5 @@ CoreConnectHandlesByKey ( CoreConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } - CoreFreePool(HandleBuffer); + CoreFreePool (HandleBuffer); } diff --git a/MdeModulePkg/Core/Dxe/Hand/Handle.h b/MdeModulePkg/Core/Dxe/Hand/Handle.h index 3f83e3af15..5c66e4da66 100644 --- a/MdeModulePkg/Core/Dxe/Hand/Handle.h +++ b/MdeModulePkg/Core/Dxe/Hand/Handle.h @@ -9,26 +9,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _HAND_H_ #define _HAND_H_ - -#define EFI_HANDLE_SIGNATURE SIGNATURE_32('h','n','d','l') +#define EFI_HANDLE_SIGNATURE SIGNATURE_32('h','n','d','l') /// /// IHANDLE - contains a list of protocol handles /// typedef struct { - UINTN Signature; + UINTN Signature; /// All handles list of IHANDLE - LIST_ENTRY AllHandles; + LIST_ENTRY AllHandles; /// List of PROTOCOL_INTERFACE's for this handle - LIST_ENTRY Protocols; - UINTN LocateRequest; + LIST_ENTRY Protocols; + UINTN LocateRequest; /// The Handle Database Key value when this handle was last created or modified - UINT64 Key; + UINT64 Key; } IHANDLE; #define ASSERT_IS_HANDLE(a) ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE) -#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('p','r','t','e') +#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('p','r','t','e') /// /// PROTOCOL_ENTRY - each different protocol has 1 entry in the protocol @@ -36,18 +35,17 @@ typedef struct { /// with a list of registered notifies. /// typedef struct { - UINTN Signature; + UINTN Signature; /// Link Entry inserted to mProtocolDatabase - LIST_ENTRY AllEntries; + LIST_ENTRY AllEntries; /// ID of the protocol - EFI_GUID ProtocolID; + EFI_GUID ProtocolID; /// All protocol interfaces - LIST_ENTRY Protocols; + LIST_ENTRY Protocols; /// Registerd notification handlers - LIST_ENTRY Notify; + LIST_ENTRY Notify; } PROTOCOL_ENTRY; - #define PROTOCOL_INTERFACE_SIGNATURE SIGNATURE_32('p','i','f','c') /// @@ -55,55 +53,51 @@ typedef struct { /// with a protocol interface structure /// typedef struct { - UINTN Signature; + UINTN Signature; /// Link on IHANDLE.Protocols - LIST_ENTRY Link; + LIST_ENTRY Link; /// Back pointer - IHANDLE *Handle; + IHANDLE *Handle; /// Link on PROTOCOL_ENTRY.Protocols - LIST_ENTRY ByProtocol; + LIST_ENTRY ByProtocol; /// The protocol ID - PROTOCOL_ENTRY *Protocol; + PROTOCOL_ENTRY *Protocol; /// The interface value - VOID *Interface; + VOID *Interface; /// OPEN_PROTOCOL_DATA list - LIST_ENTRY OpenList; - UINTN OpenListCount; - + LIST_ENTRY OpenList; + UINTN OpenListCount; } PROTOCOL_INTERFACE; #define OPEN_PROTOCOL_DATA_SIGNATURE SIGNATURE_32('p','o','d','l') typedef struct { - UINTN Signature; - ///Link on PROTOCOL_INTERFACE.OpenList - LIST_ENTRY Link; - - EFI_HANDLE AgentHandle; - EFI_HANDLE ControllerHandle; - UINT32 Attributes; - UINT32 OpenCount; + UINTN Signature; + /// Link on PROTOCOL_INTERFACE.OpenList + LIST_ENTRY Link; + + EFI_HANDLE AgentHandle; + EFI_HANDLE ControllerHandle; + UINT32 Attributes; + UINT32 OpenCount; } OPEN_PROTOCOL_DATA; - -#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('p','r','t','n') +#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('p','r','t','n') /// /// PROTOCOL_NOTIFY - used for each register notification for a protocol /// typedef struct { - UINTN Signature; - PROTOCOL_ENTRY *Protocol; + UINTN Signature; + PROTOCOL_ENTRY *Protocol; /// All notifications for this protocol - LIST_ENTRY Link; + LIST_ENTRY Link; /// Event to notify - EFI_EVENT Event; + EFI_EVENT Event; /// Last position notified - LIST_ENTRY *Position; + LIST_ENTRY *Position; } PROTOCOL_NOTIFY; - - /** Finds the protocol entry for the requested protocol. The gProtocolDatabaseLock must be owned @@ -116,11 +110,10 @@ typedef struct { **/ PROTOCOL_ENTRY * CoreFindProtocolEntry ( - IN EFI_GUID *Protocol, - IN BOOLEAN Create + IN EFI_GUID *Protocol, + IN BOOLEAN Create ); - /** Signal event for every protocol in protocol entry. @@ -129,10 +122,9 @@ CoreFindProtocolEntry ( **/ VOID CoreNotifyProtocolEntry ( - IN PROTOCOL_ENTRY *ProtEntry + IN PROTOCOL_ENTRY *ProtEntry ); - /** Finds the protocol instance for the requested handle and protocol. Note: This function doesn't do parameters checking, it's caller's responsibility @@ -147,12 +139,11 @@ CoreNotifyProtocolEntry ( **/ PROTOCOL_INTERFACE * CoreFindProtocolInterface ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); - /** Removes Protocol from the protocol list (but not the handle list). @@ -165,12 +156,11 @@ CoreFindProtocolInterface ( **/ PROTOCOL_INTERFACE * CoreRemoveInterfaceFromProtocol ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); - /** Connects a controller to a driver. @@ -215,11 +205,10 @@ CoreConnectSingleController ( **/ EFI_STATUS CoreDisconnectControllersUsingProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN PROTOCOL_INTERFACE *Prot + IN EFI_HANDLE UserHandle, + IN PROTOCOL_INTERFACE *Prot ); - /** Acquire lock on gProtocolDatabaseLock. @@ -229,7 +218,6 @@ CoreAcquireProtocolLock ( VOID ); - /** Release lock on gProtocolDatabaseLock. @@ -239,7 +227,6 @@ CoreReleaseProtocolLock ( VOID ); - /** Check whether a handle is a valid EFI_HANDLE The gProtocolDatabaseLock must be owned @@ -252,14 +239,14 @@ CoreReleaseProtocolLock ( **/ EFI_STATUS CoreValidateHandle ( - IN EFI_HANDLE UserHandle + IN EFI_HANDLE UserHandle ); // // Externs // -extern EFI_LOCK gProtocolDatabaseLock; -extern LIST_ENTRY gHandleList; -extern UINT64 gHandleDatabaseKey; +extern EFI_LOCK gProtocolDatabaseLock; +extern LIST_ENTRY gHandleList; +extern UINT64 gHandleDatabaseKey; #endif diff --git a/MdeModulePkg/Core/Dxe/Hand/Locate.c b/MdeModulePkg/Core/Dxe/Hand/Locate.c index 4987c046c6..a29010a545 100644 --- a/MdeModulePkg/Core/Dxe/Hand/Locate.c +++ b/MdeModulePkg/Core/Dxe/Hand/Locate.c @@ -12,24 +12,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // ProtocolRequest - Last LocateHandle request ID // -UINTN mEfiLocateHandleRequest = 0; +UINTN mEfiLocateHandleRequest = 0; // // Internal prototypes // typedef struct { - EFI_GUID *Protocol; - VOID *SearchKey; - LIST_ENTRY *Position; - PROTOCOL_ENTRY *ProtEntry; + EFI_GUID *Protocol; + VOID *SearchKey; + LIST_ENTRY *Position; + PROTOCOL_ENTRY *ProtEntry; } LOCATE_POSITION; typedef IHANDLE * -(* CORE_GET_NEXT) ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface +(*CORE_GET_NEXT) ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ); /** @@ -45,8 +45,8 @@ IHANDLE * **/ IHANDLE * CoreGetNextLocateAllHandles ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ); /** @@ -63,8 +63,8 @@ CoreGetNextLocateAllHandles ( **/ IHANDLE * CoreGetNextLocateByRegisterNotify ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ); /** @@ -80,11 +80,10 @@ CoreGetNextLocateByRegisterNotify ( **/ IHANDLE * CoreGetNextLocateByProtocol ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ); - /** Internal function for locating the requested handle(s) and returns them in Buffer. The caller should already have acquired the ProtocolLock. @@ -106,21 +105,21 @@ CoreGetNextLocateByProtocol ( **/ EFI_STATUS InternalCoreLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer ) { - EFI_STATUS Status; - LOCATE_POSITION Position; - PROTOCOL_NOTIFY *ProtNotify; - CORE_GET_NEXT GetNext; - UINTN ResultSize; - IHANDLE *Handle; - IHANDLE **ResultBuffer; - VOID *Interface; + EFI_STATUS Status; + LOCATE_POSITION Position; + PROTOCOL_NOTIFY *ProtNotify; + CORE_GET_NEXT GetNext; + UINTN ResultSize; + IHANDLE *Handle; + IHANDLE **ResultBuffer; + VOID *Interface; if (BufferSize == NULL) { return EFI_INVALID_PARAMETER; @@ -139,52 +138,55 @@ InternalCoreLocateHandle ( Position.SearchKey = SearchKey; Position.Position = &gHandleList; - ResultSize = 0; - ResultBuffer = (IHANDLE **) Buffer; - Status = EFI_SUCCESS; + ResultSize = 0; + ResultBuffer = (IHANDLE **)Buffer; + Status = EFI_SUCCESS; // // Get the search function based on type // switch (SearchType) { - case AllHandles: - GetNext = CoreGetNextLocateAllHandles; - break; - - case ByRegisterNotify: - // - // Must have SearchKey for locate ByRegisterNotify - // - if (SearchKey == NULL) { - Status = EFI_INVALID_PARAMETER; + case AllHandles: + GetNext = CoreGetNextLocateAllHandles; break; - } - GetNext = CoreGetNextLocateByRegisterNotify; - break; - case ByProtocol: - GetNext = CoreGetNextLocateByProtocol; - if (Protocol == NULL) { - Status = EFI_INVALID_PARAMETER; + case ByRegisterNotify: + // + // Must have SearchKey for locate ByRegisterNotify + // + if (SearchKey == NULL) { + Status = EFI_INVALID_PARAMETER; + break; + } + + GetNext = CoreGetNextLocateByRegisterNotify; break; - } - // - // Look up the protocol entry and set the head pointer - // - Position.ProtEntry = CoreFindProtocolEntry (Protocol, FALSE); - if (Position.ProtEntry == NULL) { - Status = EFI_NOT_FOUND; + + case ByProtocol: + GetNext = CoreGetNextLocateByProtocol; + if (Protocol == NULL) { + Status = EFI_INVALID_PARAMETER; + break; + } + + // + // Look up the protocol entry and set the head pointer + // + Position.ProtEntry = CoreFindProtocolEntry (Protocol, FALSE); + if (Position.ProtEntry == NULL) { + Status = EFI_NOT_FOUND; + break; + } + + Position.Position = &Position.ProtEntry->Protocols; break; - } - Position.Position = &Position.ProtEntry->Protocols; - break; - default: - Status = EFI_INVALID_PARAMETER; - break; + default: + Status = EFI_INVALID_PARAMETER; + break; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -193,7 +195,7 @@ InternalCoreLocateHandle ( // Enumerate out the matching handles // mEfiLocateHandleRequest += 1; - for (; ;) { + for ( ; ;) { // // Get the next handle. If no more handles, stop // @@ -206,10 +208,10 @@ InternalCoreLocateHandle ( // Increase the resulting buffer size, and if this handle // fits return it // - ResultSize += sizeof(Handle); + ResultSize += sizeof (Handle); if (ResultSize <= *BufferSize) { - *ResultBuffer = Handle; - ResultBuffer += 1; + *ResultBuffer = Handle; + ResultBuffer += 1; } } @@ -230,13 +232,13 @@ InternalCoreLocateHandle ( *BufferSize = ResultSize; - if (SearchType == ByRegisterNotify && !EFI_ERROR(Status)) { + if ((SearchType == ByRegisterNotify) && !EFI_ERROR (Status)) { // // If this is a search by register notify and a handle was // returned, update the register notification position // ASSERT (SearchKey != NULL); - ProtNotify = SearchKey; + ProtNotify = SearchKey; ProtNotify->Position = ProtNotify->Position->ForwardLink; } } @@ -265,25 +267,24 @@ InternalCoreLocateHandle ( EFI_STATUS EFIAPI CoreLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Lock the protocol database // CoreAcquireProtocolLock (); - Status = InternalCoreLocateHandle(SearchType, Protocol, SearchKey, BufferSize, Buffer); + Status = InternalCoreLocateHandle (SearchType, Protocol, SearchKey, BufferSize, Buffer); CoreReleaseProtocolLock (); return Status; } - /** Routine to get the next Handle, when you are searching for all handles. @@ -297,11 +298,11 @@ CoreLocateHandle ( **/ IHANDLE * CoreGetNextLocateAllHandles ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ) { - IHANDLE *Handle; + IHANDLE *Handle; // // Next handle @@ -311,8 +312,8 @@ CoreGetNextLocateAllHandles ( // // If not at the end of the list, get the handle // - Handle = NULL; - *Interface = NULL; + Handle = NULL; + *Interface = NULL; if (Position->Position != &gHandleList) { Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); } @@ -320,8 +321,6 @@ CoreGetNextLocateAllHandles ( return Handle; } - - /** Routine to get the next Handle, when you are searching for register protocol notifies. @@ -336,8 +335,8 @@ CoreGetNextLocateAllHandles ( **/ IHANDLE * CoreGetNextLocateByRegisterNotify ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ) { IHANDLE *Handle; @@ -345,15 +344,15 @@ CoreGetNextLocateByRegisterNotify ( PROTOCOL_INTERFACE *Prot; LIST_ENTRY *Link; - Handle = NULL; - *Interface = NULL; + Handle = NULL; + *Interface = NULL; ProtNotify = Position->SearchKey; // // If this is the first request, get the next handle // if (ProtNotify != NULL) { - ASSERT(ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); + ASSERT (ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); Position->SearchKey = NULL; // @@ -361,8 +360,8 @@ CoreGetNextLocateByRegisterNotify ( // Link = ProtNotify->Position->ForwardLink; if (Link != &ProtNotify->Protocol->Protocols) { - Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; *Interface = Prot->Interface; } } @@ -370,7 +369,6 @@ CoreGetNextLocateByRegisterNotify ( return Handle; } - /** Routine to get the next Handle, when you are searching for a given protocol. @@ -384,21 +382,21 @@ CoreGetNextLocateByRegisterNotify ( **/ IHANDLE * CoreGetNextLocateByProtocol ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ) { IHANDLE *Handle; LIST_ENTRY *Link; PROTOCOL_INTERFACE *Prot; - Handle = NULL; - *Interface = NULL; - for (; ;) { + Handle = NULL; + *Interface = NULL; + for ( ; ;) { // // Next entry // - Link = Position->Position->ForwardLink; + Link = Position->Position->ForwardLink; Position->Position = Link; // @@ -412,8 +410,8 @@ CoreGetNextLocateByProtocol ( // // Get the handle // - Prot = CR(Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; *Interface = Prot->Interface; // @@ -429,7 +427,6 @@ CoreGetNextLocateByProtocol ( return Handle; } - /** Locates the handle to a device on the device path that supports the specified protocol. @@ -449,22 +446,22 @@ CoreGetNextLocateByProtocol ( EFI_STATUS EFIAPI CoreLocateDevicePath ( - IN EFI_GUID *Protocol, - IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, - OUT EFI_HANDLE *Device + IN EFI_GUID *Protocol, + IN OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath, + OUT EFI_HANDLE *Device ) { - INTN SourceSize; - INTN Size; - INTN BestMatch; - UINTN HandleCount; - UINTN Index; - EFI_STATUS Status; - EFI_HANDLE *Handles; - EFI_HANDLE Handle; - EFI_HANDLE BestDevice; - EFI_DEVICE_PATH_PROTOCOL *SourcePath; - EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; + INTN SourceSize; + INTN Size; + INTN BestMatch; + UINTN HandleCount; + UINTN Index; + EFI_STATUS Status; + EFI_HANDLE *Handles; + EFI_HANDLE Handle; + EFI_HANDLE BestDevice; + EFI_DEVICE_PATH_PROTOCOL *SourcePath; + EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; if (Protocol == NULL) { return EFI_INVALID_PARAMETER; @@ -474,9 +471,9 @@ CoreLocateDevicePath ( return EFI_INVALID_PARAMETER; } - Handles = NULL; - BestDevice = NULL; - SourcePath = *DevicePath; + Handles = NULL; + BestDevice = NULL; + SourcePath = *DevicePath; TmpDevicePath = SourcePath; while (!IsDevicePathEnd (TmpDevicePath)) { if (IsDevicePathEndInstance (TmpDevicePath)) { @@ -486,21 +483,22 @@ CoreLocateDevicePath ( // break; } + TmpDevicePath = NextDevicePathNode (TmpDevicePath); } - SourceSize = (UINTN) TmpDevicePath - (UINTN) SourcePath; + SourceSize = (UINTN)TmpDevicePath - (UINTN)SourcePath; // // Get a list of all handles that support the requested protocol // Status = CoreLocateHandleBuffer (ByProtocol, Protocol, NULL, &HandleCount, &Handles); - if (EFI_ERROR (Status) || HandleCount == 0) { + if (EFI_ERROR (Status) || (HandleCount == 0)) { return EFI_NOT_FOUND; } BestMatch = -1; - for(Index = 0; Index < HandleCount; Index += 1) { + for (Index = 0; Index < HandleCount; Index += 1) { Handle = Handles[Index]; Status = CoreHandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&TmpDevicePath); if (EFI_ERROR (Status)) { @@ -513,9 +511,9 @@ CoreLocateDevicePath ( // // Check if DevicePath is first part of SourcePath // - Size = GetDevicePathSize (TmpDevicePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL); + Size = GetDevicePathSize (TmpDevicePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); ASSERT (Size >= 0); - if ((Size <= SourceSize) && CompareMem (SourcePath, TmpDevicePath, (UINTN) Size) == 0) { + if ((Size <= SourceSize) && (CompareMem (SourcePath, TmpDevicePath, (UINTN)Size) == 0)) { // // If the size is equal to the best match, then we // have a duplicate device path for 2 different device @@ -527,7 +525,7 @@ CoreLocateDevicePath ( // We've got a match, see if it's the best match so far // if (Size > BestMatch) { - BestMatch = Size; + BestMatch = Size; BestDevice = Handle; } } @@ -544,18 +542,18 @@ CoreLocateDevicePath ( } if (Device == NULL) { - return EFI_INVALID_PARAMETER; + return EFI_INVALID_PARAMETER; } + *Device = BestDevice; // // Return the remaining part of the device path // - *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *) SourcePath) + BestMatch); + *DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)(((UINT8 *)SourcePath) + BestMatch); return EFI_SUCCESS; } - /** Return the first Protocol Interface that matches the Protocol GUID. If Registration is passed in, return a Protocol Instance that was just add @@ -580,17 +578,17 @@ CoreLocateProtocol ( OUT VOID **Interface ) { - EFI_STATUS Status; - LOCATE_POSITION Position; - PROTOCOL_NOTIFY *ProtNotify; - IHANDLE *Handle; + EFI_STATUS Status; + LOCATE_POSITION Position; + PROTOCOL_NOTIFY *ProtNotify; + IHANDLE *Handle; if ((Interface == NULL) || (Protocol == NULL)) { return EFI_INVALID_PARAMETER; } *Interface = NULL; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; // // Set initial position @@ -618,6 +616,7 @@ CoreLocateProtocol ( Status = EFI_NOT_FOUND; goto Done; } + Position.Position = &Position.ProtEntry->Protocols; Handle = CoreGetNextLocateByProtocol (&Position, Interface); @@ -632,7 +631,7 @@ CoreLocateProtocol ( // If this is a search by register notify and a handle was // returned, update the register notification position // - ProtNotify = Registration; + ProtNotify = Registration; ProtNotify->Position = ProtNotify->Position->ForwardLink; } @@ -666,15 +665,15 @@ Done: EFI_STATUS EFIAPI CoreLocateHandleBuffer ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *NumberHandles, - OUT EFI_HANDLE **Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *NumberHandles, + OUT EFI_HANDLE **Buffer ) { - EFI_STATUS Status; - UINTN BufferSize; + EFI_STATUS Status; + UINTN BufferSize; if (NumberHandles == NULL) { return EFI_INVALID_PARAMETER; @@ -684,14 +683,14 @@ CoreLocateHandleBuffer ( return EFI_INVALID_PARAMETER; } - BufferSize = 0; + BufferSize = 0; *NumberHandles = 0; - *Buffer = NULL; + *Buffer = NULL; // // Lock the protocol database // - CoreAcquireProtocolLock(); + CoreAcquireProtocolLock (); Status = InternalCoreLocateHandle ( SearchType, Protocol, @@ -705,10 +704,11 @@ CoreLocateHandleBuffer ( // // Add code to correctly handle expected errors from CoreLocateHandle(). // - if (EFI_ERROR(Status) && Status != EFI_BUFFER_TOO_SMALL) { + if (EFI_ERROR (Status) && (Status != EFI_BUFFER_TOO_SMALL)) { if (Status != EFI_INVALID_PARAMETER) { Status = EFI_NOT_FOUND; } + CoreReleaseProtocolLock (); return Status; } @@ -727,14 +727,11 @@ CoreLocateHandleBuffer ( *Buffer ); - *NumberHandles = BufferSize / sizeof(EFI_HANDLE); - if (EFI_ERROR(Status)) { + *NumberHandles = BufferSize / sizeof (EFI_HANDLE); + if (EFI_ERROR (Status)) { *NumberHandles = 0; } CoreReleaseProtocolLock (); return Status; } - - - diff --git a/MdeModulePkg/Core/Dxe/Hand/Notify.c b/MdeModulePkg/Core/Dxe/Hand/Notify.c index d05f95207f..a6e20cad23 100644 --- a/MdeModulePkg/Core/Dxe/Hand/Notify.c +++ b/MdeModulePkg/Core/Dxe/Hand/Notify.c @@ -19,22 +19,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID CoreNotifyProtocolEntry ( - IN PROTOCOL_ENTRY *ProtEntry + IN PROTOCOL_ENTRY *ProtEntry ) { - PROTOCOL_NOTIFY *ProtNotify; - LIST_ENTRY *Link; + PROTOCOL_NOTIFY *ProtNotify; + LIST_ENTRY *Link; ASSERT_LOCKED (&gProtocolDatabaseLock); - for (Link=ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) { - ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); CoreSignalEvent (ProtNotify->Event); } } - - /** Removes Protocol from the protocol list (but not the handle list). @@ -47,9 +45,9 @@ CoreNotifyProtocolEntry ( **/ PROTOCOL_INTERFACE * CoreRemoveInterfaceFromProtocol ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ) { PROTOCOL_INTERFACE *Prot; @@ -61,14 +59,13 @@ CoreRemoveInterfaceFromProtocol ( Prot = CoreFindProtocolInterface (Handle, Protocol, Interface); if (Prot != NULL) { - ProtEntry = Prot->Protocol; // // If there's a protocol notify location pointing to this entry, back it up one // - for(Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) { - ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); if (ProtNotify->Position == &Prot->ByProtocol) { ProtNotify->Position = Prot->ByProtocol.BackLink; @@ -84,7 +81,6 @@ CoreRemoveInterfaceFromProtocol ( return Prot; } - /** Add a new protocol notification record for the request protocol. @@ -101,16 +97,16 @@ CoreRemoveInterfaceFromProtocol ( EFI_STATUS EFIAPI CoreRegisterProtocolNotify ( - IN EFI_GUID *Protocol, - IN EFI_EVENT Event, - OUT VOID **Registration + IN EFI_GUID *Protocol, + IN EFI_EVENT Event, + OUT VOID **Registration ) { - PROTOCOL_ENTRY *ProtEntry; - PROTOCOL_NOTIFY *ProtNotify; - EFI_STATUS Status; + PROTOCOL_ENTRY *ProtEntry; + PROTOCOL_NOTIFY *ProtNotify; + EFI_STATUS Status; - if ((Protocol == NULL) || (Event == NULL) || (Registration == NULL)) { + if ((Protocol == NULL) || (Event == NULL) || (Registration == NULL)) { return EFI_INVALID_PARAMETER; } @@ -124,16 +120,15 @@ CoreRegisterProtocolNotify ( ProtEntry = CoreFindProtocolEntry (Protocol, TRUE); if (ProtEntry != NULL) { - // // Allocate a new notification record // - ProtNotify = AllocatePool (sizeof(PROTOCOL_NOTIFY)); + ProtNotify = AllocatePool (sizeof (PROTOCOL_NOTIFY)); if (ProtNotify != NULL) { ((IEVENT *)Event)->ExFlag |= EVT_EXFLAG_EVENT_PROTOCOL_NOTIFICATION; - ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE; - ProtNotify->Protocol = ProtEntry; - ProtNotify->Event = Event; + ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE; + ProtNotify->Protocol = ProtEntry; + ProtNotify->Event = Event; // // start at the begining // @@ -153,13 +148,12 @@ CoreRegisterProtocolNotify ( Status = EFI_OUT_OF_RESOURCES; if (ProtNotify != NULL) { *Registration = ProtNotify; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } return Status; } - /** Reinstall a protocol interface on a device handle. The OldInterface for Protocol is replaced by the NewInterface. @@ -177,16 +171,16 @@ CoreRegisterProtocolNotify ( EFI_STATUS EFIAPI CoreReinstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *OldInterface, - IN VOID *NewInterface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *OldInterface, + IN VOID *NewInterface ) { - EFI_STATUS Status; - IHANDLE *Handle; - PROTOCOL_INTERFACE *Prot; - PROTOCOL_ENTRY *ProtEntry; + EFI_STATUS Status; + IHANDLE *Handle; + PROTOCOL_INTERFACE *Prot; + PROTOCOL_ENTRY *ProtEntry; if (Protocol == NULL) { return EFI_INVALID_PARAMETER; @@ -202,7 +196,7 @@ CoreReinstallProtocolInterface ( goto Done; } - Handle = (IHANDLE *) UserHandle; + Handle = (IHANDLE *)UserHandle; // // Check that Protocol exists on UserHandle, and Interface matches the interface in the database // diff --git a/MdeModulePkg/Core/Dxe/Image/Image.c b/MdeModulePkg/Core/Dxe/Image/Image.c index 44b7f105a2..68bde5c15c 100644 --- a/MdeModulePkg/Core/Dxe/Image/Image.c +++ b/MdeModulePkg/Core/Dxe/Image/Image.c @@ -15,24 +15,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent LOADED_IMAGE_PRIVATE_DATA *mCurrentImage = NULL; typedef struct { - LIST_ENTRY Link; - EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *Emulator; - UINT16 MachineType; + LIST_ENTRY Link; + EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *Emulator; + UINT16 MachineType; } EMULATOR_ENTRY; -STATIC LIST_ENTRY mAvailableEmulators; -STATIC EFI_EVENT mPeCoffEmuProtocolRegistrationEvent; -STATIC VOID *mPeCoffEmuProtocolNotifyRegistration; +STATIC LIST_ENTRY mAvailableEmulators; +STATIC EFI_EVENT mPeCoffEmuProtocolRegistrationEvent; +STATIC VOID *mPeCoffEmuProtocolNotifyRegistration; // // This code is needed to build the Image handle for the DXE Core // -LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage = { - LOADED_IMAGE_PRIVATE_DATA_SIGNATURE, // Signature - NULL, // Image handle - EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, // Image type - TRUE, // If entrypoint has been called - NULL, // EntryPoint +LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage = { + LOADED_IMAGE_PRIVATE_DATA_SIGNATURE, // Signature + NULL, // Image handle + EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, // Image type + TRUE, // If entrypoint has been called + NULL, // EntryPoint { EFI_LOADED_IMAGE_INFORMATION_REVISION, // Revision NULL, // Parent handle @@ -69,22 +69,22 @@ LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage = { // memory range usage. It is a bit mapped array in which every bit indicates the correspoding memory page // available or not. // -GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mDxeCodeMemoryRangeUsageBitMap=NULL; +GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mDxeCodeMemoryRangeUsageBitMap = NULL; typedef struct { - UINT16 MachineType; - CHAR16 *MachineTypeName; + UINT16 MachineType; + CHAR16 *MachineTypeName; } MACHINE_TYPE_INFO; GLOBAL_REMOVE_IF_UNREFERENCED MACHINE_TYPE_INFO mMachineTypeInfo[] = { - {EFI_IMAGE_MACHINE_IA32, L"IA32"}, - {EFI_IMAGE_MACHINE_IA64, L"IA64"}, - {EFI_IMAGE_MACHINE_X64, L"X64"}, - {EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM"}, - {EFI_IMAGE_MACHINE_AARCH64, L"AARCH64"} + { EFI_IMAGE_MACHINE_IA32, L"IA32" }, + { EFI_IMAGE_MACHINE_IA64, L"IA64" }, + { EFI_IMAGE_MACHINE_X64, L"X64" }, + { EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM" }, + { EFI_IMAGE_MACHINE_AARCH64, L"AARCH64" } }; -UINT16 mDxeCoreImageMachineType = 0; +UINT16 mDxeCoreImageMachineType = 0; /** Return machine type name. @@ -95,12 +95,12 @@ UINT16 mDxeCoreImageMachineType = 0; **/ CHAR16 * GetMachineTypeName ( - UINT16 MachineType + UINT16 MachineType ) { UINTN Index; - for (Index = 0; Index < sizeof(mMachineTypeInfo)/sizeof(mMachineTypeInfo[0]); Index++) { + for (Index = 0; Index < sizeof (mMachineTypeInfo)/sizeof (mMachineTypeInfo[0]); Index++) { if (mMachineTypeInfo[Index].MachineType == MachineType) { return mMachineTypeInfo[Index].MachineTypeName; } @@ -121,8 +121,8 @@ STATIC VOID EFIAPI PeCoffEmuProtocolNotify ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { EFI_STATUS Status; @@ -136,13 +136,13 @@ PeCoffEmuProtocolNotify ( while (TRUE) { BufferSize = sizeof (EmuHandle); - Status = CoreLocateHandle ( - ByRegisterNotify, - NULL, - mPeCoffEmuProtocolNotifyRegistration, - &BufferSize, - &EmuHandle - ); + Status = CoreLocateHandle ( + ByRegisterNotify, + NULL, + mPeCoffEmuProtocolNotifyRegistration, + &BufferSize, + &EmuHandle + ); if (EFI_ERROR (Status)) { // // If no more notification events exit @@ -155,7 +155,7 @@ PeCoffEmuProtocolNotify ( &gEdkiiPeCoffImageEmulatorProtocolGuid, (VOID **)&Emulator ); - if (EFI_ERROR (Status) || Emulator == NULL) { + if (EFI_ERROR (Status) || (Emulator == NULL)) { continue; } @@ -180,20 +180,20 @@ PeCoffEmuProtocolNotify ( **/ EFI_STATUS CoreInitializeImageServices ( - IN VOID *HobStart + IN VOID *HobStart ) { - EFI_STATUS Status; - LOADED_IMAGE_PRIVATE_DATA *Image; - EFI_PHYSICAL_ADDRESS DxeCoreImageBaseAddress; - UINT64 DxeCoreImageLength; - VOID *DxeCoreEntryPoint; - EFI_PEI_HOB_POINTERS DxeCoreHob; + EFI_STATUS Status; + LOADED_IMAGE_PRIVATE_DATA *Image; + EFI_PHYSICAL_ADDRESS DxeCoreImageBaseAddress; + UINT64 DxeCoreImageLength; + VOID *DxeCoreEntryPoint; + EFI_PEI_HOB_POINTERS DxeCoreHob; // // Searching for image hob // - DxeCoreHob.Raw = HobStart; + DxeCoreHob.Raw = HobStart; while ((DxeCoreHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, DxeCoreHob.Raw)) != NULL) { if (CompareGuid (&DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.Name, &gEfiHobMemoryAllocModuleGuid)) { // @@ -201,13 +201,15 @@ CoreInitializeImageServices ( // break; } + DxeCoreHob.Raw = GET_NEXT_HOB (DxeCoreHob); } + ASSERT (DxeCoreHob.Raw != NULL); DxeCoreImageBaseAddress = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress; DxeCoreImageLength = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength; - DxeCoreEntryPoint = (VOID *) (UINTN) DxeCoreHob.MemoryAllocationModule->EntryPoint; + DxeCoreEntryPoint = (VOID *)(UINTN)DxeCoreHob.MemoryAllocationModule->EntryPoint; gDxeCoreFileName = &DxeCoreHob.MemoryAllocationModule->ModuleName; // @@ -215,13 +217,13 @@ CoreInitializeImageServices ( // Image = &mCorePrivateImage; - Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint; - Image->ImageBasePage = DxeCoreImageBaseAddress; - Image->NumberOfPages = (UINTN)(EFI_SIZE_TO_PAGES((UINTN)(DxeCoreImageLength))); - Image->Tpl = gEfiCurrentTpl; - Image->Info.SystemTable = gDxeCoreST; - Image->Info.ImageBase = (VOID *)(UINTN)DxeCoreImageBaseAddress; - Image->Info.ImageSize = DxeCoreImageLength; + Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint; + Image->ImageBasePage = DxeCoreImageBaseAddress; + Image->NumberOfPages = (UINTN)(EFI_SIZE_TO_PAGES ((UINTN)(DxeCoreImageLength))); + Image->Tpl = gEfiCurrentTpl; + Image->Info.SystemTable = gDxeCoreST; + Image->Info.ImageBase = (VOID *)(UINTN)DxeCoreImageBaseAddress; + Image->Info.ImageSize = DxeCoreImageLength; // // Install the protocol interfaces for this image @@ -240,8 +242,8 @@ CoreInitializeImageServices ( // Fill in DXE globals // mDxeCoreImageMachineType = PeCoffLoaderGetMachineType (Image->Info.ImageBase); - gDxeCoreImageHandle = Image->Handle; - gDxeCoreLoadedImage = &Image->Info; + gDxeCoreImageHandle = Image->Handle; + gDxeCoreLoadedImage = &Image->Info; // // Create the PE/COFF emulator protocol registration event @@ -253,7 +255,7 @@ CoreInitializeImageServices ( NULL, &mPeCoffEmuProtocolRegistrationEvent ); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); // // Register for protocol notifications on this event @@ -263,7 +265,7 @@ CoreInitializeImageServices ( mPeCoffEmuProtocolRegistrationEvent, &mPeCoffEmuProtocolNotifyRegistration ); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); InitializeListHead (&mAvailableEmulators); @@ -289,16 +291,16 @@ CoreInitializeImageServices ( EFI_STATUS EFIAPI CoreReadImageFile ( - IN VOID *UserHandle, - IN UINTN Offset, - IN OUT UINTN *ReadSize, - OUT VOID *Buffer + IN VOID *UserHandle, + IN UINTN Offset, + IN OUT UINTN *ReadSize, + OUT VOID *Buffer ) { - UINTN EndPosition; + UINTN EndPosition; IMAGE_FILE_HANDLE *FHand; - if (UserHandle == NULL || ReadSize == NULL || Buffer == NULL) { + if ((UserHandle == NULL) || (ReadSize == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -316,13 +318,15 @@ CoreReadImageFile ( if (EndPosition > FHand->SourceSize) { *ReadSize = (UINT32)(FHand->SourceSize - Offset); } + if (Offset >= FHand->SourceSize) { - *ReadSize = 0; + *ReadSize = 0; } CopyMem (Buffer, (CHAR8 *)FHand->Source + Offset, *ReadSize); return EFI_SUCCESS; } + /** To check memory usage bit map array to figure out if the memory range the image will be loaded in is available or not. If memory range is available, the function will mark the corresponding bits to 1 which indicates the memory range is used. @@ -336,66 +340,73 @@ CoreReadImageFile ( **/ EFI_STATUS CheckAndMarkFixLoadingMemoryUsageBitMap ( - IN EFI_PHYSICAL_ADDRESS ImageBase, - IN UINTN ImageSize + IN EFI_PHYSICAL_ADDRESS ImageBase, + IN UINTN ImageSize ) { - UINT32 DxeCodePageNumber; - UINT64 DxeCodeSize; - EFI_PHYSICAL_ADDRESS DxeCodeBase; - UINTN BaseOffsetPageNumber; - UINTN TopOffsetPageNumber; - UINTN Index; - // - // The DXE code range includes RuntimeCodePage range and Boot time code range. - // - DxeCodePageNumber = PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber); - DxeCodePageNumber += PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber); - DxeCodeSize = EFI_PAGES_TO_SIZE(DxeCodePageNumber); - DxeCodeBase = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - DxeCodeSize; - - // - // If the memory usage bit map is not initialized, do it. Every bit in the array - // indicate the status of the corresponding memory page, available or not - // - if (mDxeCodeMemoryRangeUsageBitMap == NULL) { - mDxeCodeMemoryRangeUsageBitMap = AllocateZeroPool(((DxeCodePageNumber/64) + 1)*sizeof(UINT64)); - } - // - // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND - // - if (!gLoadFixedAddressCodeMemoryReady || mDxeCodeMemoryRangeUsageBitMap == NULL) { - return EFI_NOT_FOUND; - } - // - // Test the memory range for loading the image in the DXE code range. - // - if (gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress < ImageBase + ImageSize || - DxeCodeBase > ImageBase) { - return EFI_NOT_FOUND; - } - // - // Test if the memory is avalaible or not. - // - BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - DxeCodeBase)); - TopOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - DxeCodeBase)); - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - if ((mDxeCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) { - // - // This page is already used. - // - return EFI_NOT_FOUND; - } - } - - // - // Being here means the memory range is available. So mark the bits for the memory range - // - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - mDxeCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64)); - } - return EFI_SUCCESS; + UINT32 DxeCodePageNumber; + UINT64 DxeCodeSize; + EFI_PHYSICAL_ADDRESS DxeCodeBase; + UINTN BaseOffsetPageNumber; + UINTN TopOffsetPageNumber; + UINTN Index; + + // + // The DXE code range includes RuntimeCodePage range and Boot time code range. + // + DxeCodePageNumber = PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber); + DxeCodePageNumber += PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber); + DxeCodeSize = EFI_PAGES_TO_SIZE (DxeCodePageNumber); + DxeCodeBase = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - DxeCodeSize; + + // + // If the memory usage bit map is not initialized, do it. Every bit in the array + // indicate the status of the corresponding memory page, available or not + // + if (mDxeCodeMemoryRangeUsageBitMap == NULL) { + mDxeCodeMemoryRangeUsageBitMap = AllocateZeroPool (((DxeCodePageNumber/64) + 1)*sizeof (UINT64)); + } + + // + // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND + // + if (!gLoadFixedAddressCodeMemoryReady || (mDxeCodeMemoryRangeUsageBitMap == NULL)) { + return EFI_NOT_FOUND; + } + + // + // Test the memory range for loading the image in the DXE code range. + // + if ((gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress < ImageBase + ImageSize) || + (DxeCodeBase > ImageBase)) + { + return EFI_NOT_FOUND; + } + + // + // Test if the memory is avalaible or not. + // + BaseOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase - DxeCodeBase)); + TopOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase + ImageSize - DxeCodeBase)); + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + if ((mDxeCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64 (1, (Index % 64))) != 0) { + // + // This page is already used. + // + return EFI_NOT_FOUND; + } + } + + // + // Being here means the memory range is available. So mark the bits for the memory range + // + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + mDxeCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64 (1, (Index % 64)); + } + + return EFI_SUCCESS; } + /** Get the fixed loading address from image header assigned by build tool. This function only be called @@ -408,85 +419,89 @@ CheckAndMarkFixLoadingMemoryUsageBitMap ( **/ EFI_STATUS -GetPeCoffImageFixLoadingAssignedAddress( +GetPeCoffImageFixLoadingAssignedAddress ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) { - UINTN SectionHeaderOffset; - EFI_STATUS Status; - EFI_IMAGE_SECTION_HEADER SectionHeader; - EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; - UINT16 Index; - UINTN Size; - UINT16 NumberOfSections; - IMAGE_FILE_HANDLE *Handle; - UINT64 ValueInSectionHeader; - - - Status = EFI_NOT_FOUND; - - // - // Get PeHeader pointer - // - Handle = (IMAGE_FILE_HANDLE*)ImageContext->Handle; - ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )Handle->Source + ImageContext->PeCoffHeaderOffset); - SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + - sizeof (UINT32) + - sizeof (EFI_IMAGE_FILE_HEADER) + - ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; - NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; - - // - // Get base address from the first section header that doesn't point to code section. - // - for (Index = 0; Index < NumberOfSections; Index++) { - // - // Read section header from file - // - Size = sizeof (EFI_IMAGE_SECTION_HEADER); - Status = ImageContext->ImageRead ( - ImageContext->Handle, - SectionHeaderOffset, - &Size, - &SectionHeader - ); - if (EFI_ERROR (Status)) { - return Status; - } - if (Size != sizeof (EFI_IMAGE_SECTION_HEADER)) { - return EFI_NOT_FOUND; - } - - Status = EFI_NOT_FOUND; - - if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { - // - // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header - // that doesn't point to code section in image header, as well as ImageBase field of image header. And there is an - // assumption that when the feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations - // & PointerToLineNumbers fields should NOT be Zero, or else, these 2 fields should be set to Zero - // - ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations); - if (ValueInSectionHeader != 0) { - // - // When the feature is configured as load module at fixed absolute address, the ImageAddress field of ImageContext - // hold the specified address. If the feature is configured as load module at fixed offset, ImageAddress hold an offset - // relative to top address - // - if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) < 0) { - ImageContext->ImageAddress = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress + (INT64)(INTN)ImageContext->ImageAddress; - } - // - // Check if the memory range is available. - // - Status = CheckAndMarkFixLoadingMemoryUsageBitMap (ImageContext->ImageAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment)); - } - break; - } - SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); - } - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status = %r \n", (VOID *)(UINTN)(ImageContext->ImageAddress), Status)); - return Status; + UINTN SectionHeaderOffset; + EFI_STATUS Status; + EFI_IMAGE_SECTION_HEADER SectionHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + UINT16 Index; + UINTN Size; + UINT16 NumberOfSections; + IMAGE_FILE_HANDLE *Handle; + UINT64 ValueInSectionHeader; + + Status = EFI_NOT_FOUND; + + // + // Get PeHeader pointer + // + Handle = (IMAGE_FILE_HANDLE *)ImageContext->Handle; + ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8 *)Handle->Source + ImageContext->PeCoffHeaderOffset); + SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; + NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; + + // + // Get base address from the first section header that doesn't point to code section. + // + for (Index = 0; Index < NumberOfSections; Index++) { + // + // Read section header from file + // + Size = sizeof (EFI_IMAGE_SECTION_HEADER); + Status = ImageContext->ImageRead ( + ImageContext->Handle, + SectionHeaderOffset, + &Size, + &SectionHeader + ); + if (EFI_ERROR (Status)) { + return Status; + } + + if (Size != sizeof (EFI_IMAGE_SECTION_HEADER)) { + return EFI_NOT_FOUND; + } + + Status = EFI_NOT_FOUND; + + if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { + // + // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header + // that doesn't point to code section in image header, as well as ImageBase field of image header. And there is an + // assumption that when the feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations + // & PointerToLineNumbers fields should NOT be Zero, or else, these 2 fields should be set to Zero + // + ValueInSectionHeader = ReadUnaligned64 ((UINT64 *)&SectionHeader.PointerToRelocations); + if (ValueInSectionHeader != 0) { + // + // When the feature is configured as load module at fixed absolute address, the ImageAddress field of ImageContext + // hold the specified address. If the feature is configured as load module at fixed offset, ImageAddress hold an offset + // relative to top address + // + if ((INT64)PcdGet64 (PcdLoadModuleAtFixAddressEnable) < 0) { + ImageContext->ImageAddress = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress + (INT64)(INTN)ImageContext->ImageAddress; + } + + // + // Check if the memory range is available. + // + Status = CheckAndMarkFixLoadingMemoryUsageBitMap (ImageContext->ImageAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment)); + } + + break; + } + + SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); + } + + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status = %r \n", (VOID *)(UINTN)(ImageContext->ImageAddress), Status)); + return Status; } /** @@ -507,21 +522,24 @@ CoreIsImageTypeSupported ( IN OUT LOADED_IMAGE_PRIVATE_DATA *Image ) { - LIST_ENTRY *Link; - EMULATOR_ENTRY *Entry; + LIST_ENTRY *Link; + EMULATOR_ENTRY *Entry; for (Link = GetFirstNode (&mAvailableEmulators); !IsNull (&mAvailableEmulators, Link); - Link = GetNextNode (&mAvailableEmulators, Link)) { - + Link = GetNextNode (&mAvailableEmulators, Link)) + { Entry = BASE_CR (Link, EMULATOR_ENTRY, Link); if (Entry->MachineType != Image->ImageContext.Machine) { continue; } - if (Entry->Emulator->IsImageSupported (Entry->Emulator, + if (Entry->Emulator->IsImageSupported ( + Entry->Emulator, Image->ImageContext.ImageType, - Image->Info.FilePath)) { + Image->Info.FilePath + )) + { Image->PeCoffEmu = Entry->Emulator; return TRUE; } @@ -554,17 +572,17 @@ CoreIsImageTypeSupported ( **/ EFI_STATUS CoreLoadPeImage ( - IN BOOLEAN BootPolicy, - IN VOID *Pe32Handle, - IN LOADED_IMAGE_PRIVATE_DATA *Image, - IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL, - IN UINT32 Attribute + IN BOOLEAN BootPolicy, + IN VOID *Pe32Handle, + IN LOADED_IMAGE_PRIVATE_DATA *Image, + IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL, + IN UINT32 Attribute ) { - EFI_STATUS Status; - BOOLEAN DstBufAlocated; - UINTN Size; + EFI_STATUS Status; + BOOLEAN DstBufAlocated; + UINTN Size; ZeroMem (&Image->ImageContext, sizeof (Image->ImageContext)); @@ -584,9 +602,12 @@ CoreLoadPeImage ( // The PE/COFF loader can support loading image types that can be executed. // If we loaded an image type that we can not execute return EFI_UNSUPPORTED. // - DEBUG ((DEBUG_ERROR, "Image type %s can't be loaded on %s UEFI system.\n", + DEBUG (( + DEBUG_ERROR, + "Image type %s can't be loaded on %s UEFI system.\n", GetMachineTypeName (Image->ImageContext.Machine), - GetMachineTypeName (mDxeCoreImageMachineType))); + GetMachineTypeName (mDxeCoreImageMachineType) + )); return EFI_UNSUPPORTED; } @@ -594,22 +615,22 @@ CoreLoadPeImage ( // Set EFI memory type based on ImageType // switch (Image->ImageContext.ImageType) { - case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION: - Image->ImageContext.ImageCodeMemoryType = EfiLoaderCode; - Image->ImageContext.ImageDataMemoryType = EfiLoaderData; - break; - case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: - Image->ImageContext.ImageCodeMemoryType = EfiBootServicesCode; - Image->ImageContext.ImageDataMemoryType = EfiBootServicesData; - break; - case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: - case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER: - Image->ImageContext.ImageCodeMemoryType = EfiRuntimeServicesCode; - Image->ImageContext.ImageDataMemoryType = EfiRuntimeServicesData; - break; - default: - Image->ImageContext.ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM; - return EFI_UNSUPPORTED; + case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION: + Image->ImageContext.ImageCodeMemoryType = EfiLoaderCode; + Image->ImageContext.ImageDataMemoryType = EfiLoaderData; + break; + case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER: + Image->ImageContext.ImageCodeMemoryType = EfiBootServicesCode; + Image->ImageContext.ImageDataMemoryType = EfiBootServicesData; + break; + case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER: + case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER: + Image->ImageContext.ImageCodeMemoryType = EfiRuntimeServicesCode; + Image->ImageContext.ImageDataMemoryType = EfiRuntimeServicesData; + break; + default: + Image->ImageContext.ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM; + return EFI_UNSUPPORTED; } // @@ -641,43 +662,46 @@ CoreLoadPeImage ( // If Loading Module At Fixed Address feature is enabled, the module should be loaded to // a specified address. // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 ) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0 ) { Status = GetPeCoffImageFixLoadingAssignedAddress (&(Image->ImageContext)); - if (EFI_ERROR (Status)) { - // - // If the code memory is not ready, invoke CoreAllocatePage with AllocateAnyPages to load the driver. - // - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Loading module at fixed address failed since specified memory is not available.\n")); - - Status = CoreAllocatePages ( - AllocateAnyPages, - (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType), - Image->NumberOfPages, - &Image->ImageContext.ImageAddress - ); + if (EFI_ERROR (Status)) { + // + // If the code memory is not ready, invoke CoreAllocatePage with AllocateAnyPages to load the driver. + // + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Loading module at fixed address failed since specified memory is not available.\n")); + + Status = CoreAllocatePages ( + AllocateAnyPages, + (EFI_MEMORY_TYPE)(Image->ImageContext.ImageCodeMemoryType), + Image->NumberOfPages, + &Image->ImageContext.ImageAddress + ); } } else { - if (Image->ImageContext.ImageAddress >= 0x100000 || Image->ImageContext.RelocationsStripped) { + if ((Image->ImageContext.ImageAddress >= 0x100000) || Image->ImageContext.RelocationsStripped) { Status = CoreAllocatePages ( AllocateAddress, - (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType), + (EFI_MEMORY_TYPE)(Image->ImageContext.ImageCodeMemoryType), Image->NumberOfPages, &Image->ImageContext.ImageAddress ); } + if (EFI_ERROR (Status) && !Image->ImageContext.RelocationsStripped) { Status = CoreAllocatePages ( AllocateAnyPages, - (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType), + (EFI_MEMORY_TYPE)(Image->ImageContext.ImageCodeMemoryType), Image->NumberOfPages, &Image->ImageContext.ImageAddress ); } } + if (EFI_ERROR (Status)) { return Status; } + DstBufAlocated = TRUE; } else { // @@ -693,22 +717,23 @@ CoreLoadPeImage ( return EFI_INVALID_PARAMETER; } - if (Image->NumberOfPages != 0 && - Image->NumberOfPages < - (EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment))) { + if ((Image->NumberOfPages != 0) && + (Image->NumberOfPages < + (EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment)))) + { Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment); return EFI_BUFFER_TOO_SMALL; } - Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment); + Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment); Image->ImageContext.ImageAddress = DstBuffer; } Image->ImageBasePage = Image->ImageContext.ImageAddress; if (!Image->ImageContext.IsTeImage) { Image->ImageContext.ImageAddress = - (Image->ImageContext.ImageAddress + Image->ImageContext.SectionAlignment - 1) & - ~((UINTN)Image->ImageContext.SectionAlignment - 1); + (Image->ImageContext.ImageAddress + Image->ImageContext.SectionAlignment - 1) & + ~((UINTN)Image->ImageContext.SectionAlignment - 1); } // @@ -755,7 +780,7 @@ CoreLoadPeImage ( // // Get the image entry point. // - Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)Image->ImageContext.EntryPoint; + Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)Image->ImageContext.EntryPoint; // // Fill in the image information for the Loaded Image Protocol @@ -763,19 +788,20 @@ CoreLoadPeImage ( Image->Type = Image->ImageContext.ImageType; Image->Info.ImageBase = (VOID *)(UINTN)Image->ImageContext.ImageAddress; Image->Info.ImageSize = Image->ImageContext.ImageSize; - Image->Info.ImageCodeType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType); - Image->Info.ImageDataType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageDataMemoryType); + Image->Info.ImageCodeType = (EFI_MEMORY_TYPE)(Image->ImageContext.ImageCodeMemoryType); + Image->Info.ImageDataType = (EFI_MEMORY_TYPE)(Image->ImageContext.ImageDataMemoryType); if ((Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) != 0) { if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) { // // Make a list off all the RT images so we can let the RT AP know about them. // - Image->RuntimeData = AllocateRuntimePool (sizeof(EFI_RUNTIME_IMAGE_ENTRY)); + Image->RuntimeData = AllocateRuntimePool (sizeof (EFI_RUNTIME_IMAGE_ENTRY)); if (Image->RuntimeData == NULL) { goto Done; } + Image->RuntimeData->ImageBase = Image->Info.ImageBase; - Image->RuntimeData->ImageSize = (UINT64) (Image->Info.ImageSize); + Image->RuntimeData->ImageSize = (UINT64)(Image->Info.ImageSize); Image->RuntimeData->RelocationData = Image->ImageContext.FixupData; Image->RuntimeData->Handle = Image->Handle; InsertTailList (&gRuntime->ImageHead, &Image->RuntimeData->Link); @@ -796,53 +822,57 @@ CoreLoadPeImage ( DEBUG_CODE_BEGIN (); - UINTN Index; - UINTN StartIndex; - CHAR8 EfiFileName[256]; - + UINTN Index; + UINTN StartIndex; + CHAR8 EfiFileName[256]; - DEBUG ((DEBUG_INFO | DEBUG_LOAD, - "Loading driver at 0x%11p EntryPoint=0x%11p ", - (VOID *)(UINTN) Image->ImageContext.ImageAddress, - FUNCTION_ENTRY_POINT (Image->ImageContext.EntryPoint))); + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "Loading driver at 0x%11p EntryPoint=0x%11p ", + (VOID *)(UINTN)Image->ImageContext.ImageAddress, + FUNCTION_ENTRY_POINT (Image->ImageContext.EntryPoint) + )); + // + // Print Module Name by Pdb file path. + // Windows and Unix style file path are all trimmed correctly. + // + if (Image->ImageContext.PdbPointer != NULL) { + StartIndex = 0; + for (Index = 0; Image->ImageContext.PdbPointer[Index] != 0; Index++) { + if ((Image->ImageContext.PdbPointer[Index] == '\\') || (Image->ImageContext.PdbPointer[Index] == '/')) { + StartIndex = Index + 1; + } + } // - // Print Module Name by Pdb file path. - // Windows and Unix style file path are all trimmed correctly. + // Copy the PDB file name to our temporary string, and replace .pdb with .efi + // The PDB file name is limited in the range of 0~255. + // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary. // - if (Image->ImageContext.PdbPointer != NULL) { - StartIndex = 0; - for (Index = 0; Image->ImageContext.PdbPointer[Index] != 0; Index++) { - if ((Image->ImageContext.PdbPointer[Index] == '\\') || (Image->ImageContext.PdbPointer[Index] == '/')) { - StartIndex = Index + 1; - } - } - // - // Copy the PDB file name to our temporary string, and replace .pdb with .efi - // The PDB file name is limited in the range of 0~255. - // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary. - // - for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { - EfiFileName[Index] = Image->ImageContext.PdbPointer[Index + StartIndex]; - if (EfiFileName[Index] == 0) { - EfiFileName[Index] = '.'; - } - if (EfiFileName[Index] == '.') { - EfiFileName[Index + 1] = 'e'; - EfiFileName[Index + 2] = 'f'; - EfiFileName[Index + 3] = 'i'; - EfiFileName[Index + 4] = 0; - break; - } + for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { + EfiFileName[Index] = Image->ImageContext.PdbPointer[Index + StartIndex]; + if (EfiFileName[Index] == 0) { + EfiFileName[Index] = '.'; } - if (Index == sizeof (EfiFileName) - 4) { - EfiFileName[Index] = 0; + if (EfiFileName[Index] == '.') { + EfiFileName[Index + 1] = 'e'; + EfiFileName[Index + 2] = 'f'; + EfiFileName[Index + 3] = 'i'; + EfiFileName[Index + 4] = 0; + break; } - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex])); } - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n")); + + if (Index == sizeof (EfiFileName) - 4) { + EfiFileName[Index] = 0; + } + + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex])); + } + + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n")); DEBUG_CODE_END (); @@ -857,7 +887,7 @@ Done: if (DstBufAlocated) { CoreFreePages (Image->ImageContext.ImageAddress, Image->NumberOfPages); Image->ImageContext.ImageAddress = 0; - Image->ImageBasePage = 0; + Image->ImageBasePage = 0; } if (Image->ImageContext.FixupData != NULL) { @@ -867,8 +897,6 @@ Done: return Status; } - - /** Get the image's private data from its handle. @@ -901,7 +929,6 @@ CoreLoadedImageInfo ( return Image; } - /** Unloads EFI image from memory. @@ -915,18 +942,18 @@ CoreUnloadAndCloseImage ( IN BOOLEAN FreePage ) { - EFI_STATUS Status; - UINTN HandleCount; - EFI_HANDLE *HandleBuffer; - UINTN HandleIndex; - EFI_GUID **ProtocolGuidArray; - UINTN ArrayCount; - UINTN ProtocolIndex; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo; - UINTN OpenInfoCount; - UINTN OpenInfoIndex; - - HandleBuffer = NULL; + EFI_STATUS Status; + UINTN HandleCount; + EFI_HANDLE *HandleBuffer; + UINTN HandleIndex; + EFI_GUID **ProtocolGuidArray; + UINTN ArrayCount; + UINTN ProtocolIndex; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo; + UINTN OpenInfoCount; + UINTN OpenInfoIndex; + + HandleBuffer = NULL; ProtocolGuidArray = NULL; if (Image->Started) { @@ -951,7 +978,6 @@ CoreUnloadAndCloseImage ( // Free our references to the image handle // if (Image->Handle != NULL) { - Status = CoreLocateHandleBuffer ( AllHandles, NULL, @@ -985,16 +1011,19 @@ CoreUnloadAndCloseImage ( ); } } + if (OpenInfo != NULL) { - CoreFreePool(OpenInfo); + CoreFreePool (OpenInfo); } } } + if (ProtocolGuidArray != NULL) { - CoreFreePool(ProtocolGuidArray); + CoreFreePool (ProtocolGuidArray); } } } + if (HandleBuffer != NULL) { CoreFreePool (HandleBuffer); } @@ -1018,10 +1047,9 @@ CoreUnloadAndCloseImage ( Status = CoreUninstallProtocolInterface ( Image->Handle, &gEfiHiiPackageListProtocolGuid, - (VOID *) (UINTN) Image->ImageContext.HiiResourceData + (VOID *)(UINTN)Image->ImageContext.HiiResourceData ); } - } if (Image->RuntimeData != NULL) { @@ -1032,6 +1060,7 @@ CoreUnloadAndCloseImage ( RemoveEntryList (&Image->RuntimeData->Link); RemoveImageRecord (Image->RuntimeData); } + CoreFreePool (Image->RuntimeData); } @@ -1060,7 +1089,6 @@ CoreUnloadAndCloseImage ( CoreFreePool (Image); } - /** Loads an EFI image into memory and returns a handle to the image. @@ -1107,16 +1135,16 @@ CoreUnloadAndCloseImage ( **/ EFI_STATUS CoreLoadImageCommon ( - IN BOOLEAN BootPolicy, - IN EFI_HANDLE ParentImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN VOID *SourceBuffer OPTIONAL, - IN UINTN SourceSize, - IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL, - IN OUT UINTN *NumberOfPages OPTIONAL, - OUT EFI_HANDLE *ImageHandle, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL, - IN UINT32 Attribute + IN BOOLEAN BootPolicy, + IN EFI_HANDLE ParentImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN VOID *SourceBuffer OPTIONAL, + IN UINTN SourceSize, + IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL, + IN OUT UINTN *NumberOfPages OPTIONAL, + OUT EFI_HANDLE *ImageHandle, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL, + IN UINT32 Attribute ) { LOADED_IMAGE_PRIVATE_DATA *Image; @@ -1142,23 +1170,23 @@ CoreLoadImageCommon ( // // The caller must pass in a valid ParentImageHandle // - if (ImageHandle == NULL || ParentImageHandle == NULL) { + if ((ImageHandle == NULL) || (ParentImageHandle == NULL)) { return EFI_INVALID_PARAMETER; } ParentImage = CoreLoadedImageInfo (ParentImageHandle); if (ParentImage == NULL) { - DEBUG((DEBUG_LOAD|DEBUG_ERROR, "LoadImageEx: Parent handle not an image handle\n")); + DEBUG ((DEBUG_LOAD|DEBUG_ERROR, "LoadImageEx: Parent handle not an image handle\n")); return EFI_INVALID_PARAMETER; } ZeroMem (&FHand, sizeof (IMAGE_FILE_HANDLE)); - FHand.Signature = IMAGE_FILE_HANDLE_SIGNATURE; - OriginalFilePath = FilePath; - InputFilePath = FilePath; - HandleFilePath = FilePath; - DeviceHandle = NULL; - Status = EFI_SUCCESS; + FHand.Signature = IMAGE_FILE_HANDLE_SIGNATURE; + OriginalFilePath = FilePath; + InputFilePath = FilePath; + HandleFilePath = FilePath; + DeviceHandle = NULL; + Status = EFI_SUCCESS; AuthenticationStatus = 0; ImageIsFromFv = FALSE; ImageIsFromLoadFile = FALSE; @@ -1169,10 +1197,11 @@ CoreLoadImageCommon ( if (SourceBuffer != NULL) { FHand.Source = SourceBuffer; FHand.SourceSize = SourceSize; - Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &HandleFilePath, &DeviceHandle); + Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &HandleFilePath, &DeviceHandle); if (EFI_ERROR (Status)) { DeviceHandle = NULL; } + if (SourceSize > 0) { Status = EFI_SUCCESS; } else { @@ -1192,18 +1221,19 @@ CoreLoadImageCommon ( ImageIsFromFv = TRUE; } else { HandleFilePath = FilePath; - Status = CoreLocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &HandleFilePath, &DeviceHandle); + Status = CoreLocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &HandleFilePath, &DeviceHandle); if (EFI_ERROR (Status)) { if (!BootPolicy) { HandleFilePath = FilePath; - Status = CoreLocateDevicePath (&gEfiLoadFile2ProtocolGuid, &HandleFilePath, &DeviceHandle); + Status = CoreLocateDevicePath (&gEfiLoadFile2ProtocolGuid, &HandleFilePath, &DeviceHandle); } + if (EFI_ERROR (Status)) { HandleFilePath = FilePath; - Status = CoreLocateDevicePath (&gEfiLoadFileProtocolGuid, &HandleFilePath, &DeviceHandle); + Status = CoreLocateDevicePath (&gEfiLoadFileProtocolGuid, &HandleFilePath, &DeviceHandle); if (!EFI_ERROR (Status)) { ImageIsFromLoadFile = TRUE; - Node = HandleFilePath; + Node = HandleFilePath; } } } @@ -1213,11 +1243,11 @@ CoreLoadImageCommon ( // Get the source file buffer by its device path. // FHand.Source = GetFileBufferByFilePath ( - BootPolicy, - FilePath, - &FHand.SourceSize, - &AuthenticationStatus - ); + BootPolicy, + FilePath, + &FHand.SourceSize, + &AuthenticationStatus + ); if (FHand.Source == NULL) { Status = EFI_NOT_FOUND; } else { @@ -1241,12 +1271,12 @@ CoreLoadImageCommon ( // Verify File Authentication through the Security2 Architectural Protocol // SecurityStatus = gSecurity2->FileAuthentication ( - gSecurity2, - OriginalFilePath, - FHand.Source, - FHand.SourceSize, - BootPolicy - ); + gSecurity2, + OriginalFilePath, + FHand.Source, + FHand.SourceSize, + BootPolicy + ); if (!EFI_ERROR (SecurityStatus) && ImageIsFromFv) { // // When Security2 is installed, Security Architectural Protocol must be published. @@ -1277,7 +1307,7 @@ CoreLoadImageCommon ( // // Check Security Status. // - if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) { + if (EFI_ERROR (SecurityStatus) && (SecurityStatus != EFI_SECURITY_VIOLATION)) { if (SecurityStatus == EFI_ACCESS_DENIED) { // // Image was not loaded because the platform policy prohibits the image from being loaded. @@ -1285,15 +1315,16 @@ CoreLoadImageCommon ( // *ImageHandle = NULL; } + Status = SecurityStatus; - Image = NULL; + Image = NULL; goto Done; } // // Allocate a new image structure // - Image = AllocateZeroPool (sizeof(LOADED_IMAGE_PRIVATE_DATA)); + Image = AllocateZeroPool (sizeof (LOADED_IMAGE_PRIVATE_DATA)); if (Image == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -1306,10 +1337,11 @@ CoreLoadImageCommon ( if (DeviceHandle != NULL) { Status = CoreHandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath); if (!EFI_ERROR (Status)) { - FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL); - FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize ); + FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); + FilePath = (EFI_DEVICE_PATH_PROTOCOL *)(((UINT8 *)FilePath) + FilePathSize); } } + // // Initialize the fields for an internal driver // @@ -1320,11 +1352,10 @@ CoreLoadImageCommon ( Image->Info.FilePath = DuplicateDevicePath (FilePath); Image->Info.ParentHandle = ParentImageHandle; - if (NumberOfPages != NULL) { - Image->NumberOfPages = *NumberOfPages ; + Image->NumberOfPages = *NumberOfPages; } else { - Image->NumberOfPages = 0 ; + Image->NumberOfPages = 0; } // @@ -1352,6 +1383,7 @@ CoreLoadImageCommon ( *NumberOfPages = Image->NumberOfPages; } } + goto Done; } @@ -1367,7 +1399,7 @@ CoreLoadImageCommon ( } // - //Reinstall loaded image protocol to fire any notifications + // Reinstall loaded image protocol to fire any notifications // Status = CoreReinstallProtocolInterface ( Image->Handle, @@ -1391,11 +1423,11 @@ CoreLoadImageCommon ( // Install Loaded Image Device Path Protocol onto the image handle of a PE/COFE image // Status = CoreInstallProtocolInterface ( - &Image->Handle, - &gEfiLoadedImageDevicePathProtocolGuid, - EFI_NATIVE_INTERFACE, - Image->LoadedImageDevicePath - ); + &Image->Handle, + &gEfiLoadedImageDevicePathProtocolGuid, + EFI_NATIVE_INTERFACE, + Image->LoadedImageDevicePath + ); if (EFI_ERROR (Status)) { goto Done; } @@ -1408,12 +1440,13 @@ CoreLoadImageCommon ( &Image->Handle, &gEfiHiiPackageListProtocolGuid, EFI_NATIVE_INTERFACE, - (VOID *) (UINTN) Image->ImageContext.HiiResourceData + (VOID *)(UINTN)Image->ImageContext.HiiResourceData ); if (EFI_ERROR (Status)) { goto Done; } } + ProtectUefiImage (&Image->Info, Image->LoadedImageDevicePath); // @@ -1429,6 +1462,7 @@ Done: if (FHand.FreeBuffer) { CoreFreePool (FHand.Source); } + if (OriginalFilePath != InputFilePath) { CoreFreePool (OriginalFilePath); } @@ -1455,9 +1489,6 @@ Done: return Status; } - - - /** Loads an EFI image into memory and returns a handle to the image. @@ -1495,16 +1526,16 @@ Done: EFI_STATUS EFIAPI CoreLoadImage ( - IN BOOLEAN BootPolicy, - IN EFI_HANDLE ParentImageHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN VOID *SourceBuffer OPTIONAL, - IN UINTN SourceSize, - OUT EFI_HANDLE *ImageHandle + IN BOOLEAN BootPolicy, + IN EFI_HANDLE ParentImageHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN VOID *SourceBuffer OPTIONAL, + IN UINTN SourceSize, + OUT EFI_HANDLE *ImageHandle ) { - EFI_STATUS Status; - EFI_HANDLE Handle; + EFI_STATUS Status; + EFI_HANDLE Handle; PERF_LOAD_IMAGE_BEGIN (NULL); @@ -1514,7 +1545,7 @@ CoreLoadImage ( FilePath, SourceBuffer, SourceSize, - (EFI_PHYSICAL_ADDRESS) (UINTN) NULL, + (EFI_PHYSICAL_ADDRESS)(UINTN)NULL, NULL, ImageHandle, NULL, @@ -1561,19 +1592,20 @@ CoreStartImage ( OUT CHAR16 **ExitData OPTIONAL ) { - EFI_STATUS Status; - LOADED_IMAGE_PRIVATE_DATA *Image; - LOADED_IMAGE_PRIVATE_DATA *LastImage; - UINT64 HandleDatabaseKey; - UINTN SetJumpFlag; - EFI_HANDLE Handle; + EFI_STATUS Status; + LOADED_IMAGE_PRIVATE_DATA *Image; + LOADED_IMAGE_PRIVATE_DATA *LastImage; + UINT64 HandleDatabaseKey; + UINTN SetJumpFlag; + EFI_HANDLE Handle; Handle = ImageHandle; Image = CoreLoadedImageInfo (ImageHandle); - if (Image == NULL || Image->Started) { + if ((Image == NULL) || Image->Started) { return EFI_INVALID_PARAMETER; } + if (EFI_ERROR (Image->LoadImageStatus)) { return Image->LoadImageStatus; } @@ -1582,32 +1614,36 @@ CoreStartImage ( // The image to be started must have the machine type supported by DxeCore. // if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->Machine) && - Image->PeCoffEmu == NULL) { + (Image->PeCoffEmu == NULL)) + { // // Do not ASSERT here, because image might be loaded via EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED // But it can not be started. // - DEBUG ((DEBUG_ERROR, "Image type %s can't be started ", GetMachineTypeName(Image->Machine))); - DEBUG ((DEBUG_ERROR, "on %s UEFI system.\n", GetMachineTypeName(mDxeCoreImageMachineType))); + DEBUG ((DEBUG_ERROR, "Image type %s can't be started ", GetMachineTypeName (Image->Machine))); + DEBUG ((DEBUG_ERROR, "on %s UEFI system.\n", GetMachineTypeName (mDxeCoreImageMachineType))); return EFI_UNSUPPORTED; } if (Image->PeCoffEmu != NULL) { - Status = Image->PeCoffEmu->RegisterImage (Image->PeCoffEmu, + Status = Image->PeCoffEmu->RegisterImage ( + Image->PeCoffEmu, Image->ImageBasePage, EFI_PAGES_TO_SIZE (Image->NumberOfPages), - &Image->EntryPoint); + &Image->EntryPoint + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_LOAD | DEBUG_ERROR, + DEBUG (( + DEBUG_LOAD | DEBUG_ERROR, "CoreLoadPeImage: Failed to register foreign image with emulator - %r\n", - Status)); + Status + )); return Status; } } PERF_START_IMAGE_BEGIN (Handle); - // // Push the current start image context, and // link the current image to the head. This is the @@ -1638,6 +1674,7 @@ CoreStartImage ( return EFI_OUT_OF_RESOURCES; } + Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT); SetJumpFlag = SetJump (Image->JumpContext); @@ -1651,7 +1688,7 @@ CoreStartImage ( // Call the image's entry point // Image->Started = TRUE; - Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable); + Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable); // // Add some debug information if the image returned with error. @@ -1659,9 +1696,10 @@ CoreStartImage ( // all the resource in this situation. // DEBUG_CODE_BEGIN (); - if (EFI_ERROR (Image->Status)) { - DEBUG ((DEBUG_ERROR, "Error: Image at %11p start failed: %r\n", Image->Info.ImageBase, Image->Status)); - } + if (EFI_ERROR (Image->Status)) { + DEBUG ((DEBUG_ERROR, "Error: Image at %11p start failed: %r\n", Image->Info.ImageBase, Image->Status)); + } + DEBUG_CODE_END (); // @@ -1700,20 +1738,21 @@ CoreStartImage ( // Handle the image's returned ExitData // DEBUG_CODE_BEGIN (); - if (Image->ExitDataSize != 0 || Image->ExitData != NULL) { - - DEBUG ((DEBUG_LOAD, "StartImage: ExitDataSize %d, ExitData %p", (UINT32)Image->ExitDataSize, Image->ExitData)); - if (Image->ExitData != NULL) { - DEBUG ((DEBUG_LOAD, " (%hs)", Image->ExitData)); - } - DEBUG ((DEBUG_LOAD, "\n")); + if ((Image->ExitDataSize != 0) || (Image->ExitData != NULL)) { + DEBUG ((DEBUG_LOAD, "StartImage: ExitDataSize %d, ExitData %p", (UINT32)Image->ExitDataSize, Image->ExitData)); + if (Image->ExitData != NULL) { + DEBUG ((DEBUG_LOAD, " (%hs)", Image->ExitData)); } + + DEBUG ((DEBUG_LOAD, "\n")); + } + DEBUG_CODE_END (); // // Return the exit data to the caller // - if (ExitData != NULL && ExitDataSize != NULL) { + if ((ExitData != NULL) && (ExitDataSize != NULL)) { *ExitDataSize = Image->ExitDataSize; *ExitData = Image->ExitData; } else { @@ -1733,7 +1772,7 @@ CoreStartImage ( // If the image returned an error, or if the image is an application // unload it // - if (EFI_ERROR (Image->Status) || Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) { + if (EFI_ERROR (Image->Status) || (Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) { CoreUnloadAndCloseImage (Image, TRUE); // // ImageHandle may be invalid after the image is unloaded, so use NULL handle to record perf log. @@ -1823,11 +1862,12 @@ CoreExit ( // if (ExitData != NULL) { Image->ExitDataSize = ExitDataSize; - Image->ExitData = AllocatePool (Image->ExitDataSize); + Image->ExitData = AllocatePool (Image->ExitDataSize); if (Image->ExitData == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } + CopyMem (Image->ExitData, ExitData, Image->ExitDataSize); } @@ -1847,9 +1887,6 @@ Done: return Status; } - - - /** Unloads an image. @@ -1888,7 +1925,6 @@ CoreUnloadImage ( if (Image->Info.Unload != NULL) { Status = Image->Info.Unload (ImageHandle); } - } else { // // This Image hasn't been started, thus it can be unloaded @@ -1896,7 +1932,6 @@ CoreUnloadImage ( Status = EFI_SUCCESS; } - if (!EFI_ERROR (Status)) { // // if the Image was not started or Unloaded O.K. then clean up diff --git a/MdeModulePkg/Core/Dxe/Image/Image.h b/MdeModulePkg/Core/Dxe/Image/Image.h index e9c44ab2a7..7e4175e562 100644 --- a/MdeModulePkg/Core/Dxe/Image/Image.h +++ b/MdeModulePkg/Core/Dxe/Image/Image.h @@ -6,19 +6,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _IMAGE_H_ #define _IMAGE_H_ // // Private Data Types // -#define IMAGE_FILE_HANDLE_SIGNATURE SIGNATURE_32('i','m','g','f') +#define IMAGE_FILE_HANDLE_SIGNATURE SIGNATURE_32('i','m','g','f') typedef struct { - UINTN Signature; - BOOLEAN FreeBuffer; - VOID *Source; - UINTN SourceSize; + UINTN Signature; + BOOLEAN FreeBuffer; + VOID *Source; + UINTN SourceSize; } IMAGE_FILE_HANDLE; #endif diff --git a/MdeModulePkg/Core/Dxe/Library/Library.c b/MdeModulePkg/Core/Dxe/Library/Library.c index b7f0781ed7..63cef1daca 100644 --- a/MdeModulePkg/Core/Dxe/Library/Library.c +++ b/MdeModulePkg/Core/Dxe/Library/Library.c @@ -11,6 +11,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Lock Stuff // + /** Initialize a basic mutual exclusion lock. Each lock provides mutual exclusion access at it's task priority @@ -45,8 +46,6 @@ CoreAcquireLockOrFail ( return EFI_SUCCESS; } - - /** Raising to the task priority level of the mutual exclusion lock, and then acquires ownership of the lock. @@ -68,8 +67,6 @@ CoreAcquireLock ( Lock->Lock = EfiLockAcquired; } - - /** Releases ownership of the mutual exclusion lock, and restores the previous task priority level. @@ -84,7 +81,7 @@ CoreReleaseLock ( IN EFI_LOCK *Lock ) { - EFI_TPL Tpl; + EFI_TPL Tpl; ASSERT (Lock != NULL); ASSERT (Lock->Lock == EfiLockAcquired); @@ -95,6 +92,3 @@ CoreReleaseLock ( CoreRestoreTpl (Tpl); } - - - diff --git a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c index b4cb48843f..9377f620c5 100644 --- a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c +++ b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c @@ -14,34 +14,34 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Global to avoid infinite reentrance of memory allocation when updating // page table attributes, which may need allocate pages for new PDE/PTE. // -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE; // // Pointer to table tracking the Guarded memory with bitmap, in which '1' // is used to indicate memory guarded. '0' might be free memory or Guard // page itself, depending on status of memory adjacent to it. // -GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0; +GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0; // // Current depth level of map table pointed by mGuardedMemoryMap. // mMapLevel must be initialized at least by 1. It will be automatically // updated according to the address of memory just tracked. // -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1; // // Shift and mask for each level of map table // -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH] - = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS; -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH] - = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH] + = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH] + = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS; // // Used for promoting freed but not used pages. // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS mLastPromotedPage = BASE_4GB; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS mLastPromotedPage = BASE_4GB; /** Set corresponding bits in bitmap table to 1 according to the address. @@ -55,29 +55,29 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS mLastPromotedPage = BASE_4GB; STATIC VOID SetBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN Lsbs; - UINTN Qwords; - UINTN Msbs; - UINTN StartBit; - UINTN EndBit; + UINTN Lsbs; + UINTN Qwords; + UINTN Msbs; + UINTN StartBit; + UINTN EndBit; - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) >= GUARDED_HEAP_MAP_ENTRY_BITS) { - Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % - GUARDED_HEAP_MAP_ENTRY_BITS; - Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; - Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; + Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % + GUARDED_HEAP_MAP_ENTRY_BITS; + Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; } else { - Msbs = BitNumber; - Lsbs = 0; - Qwords = 0; + Msbs = BitNumber; + Lsbs = 0; + Qwords = 0; } if (Msbs > 0) { @@ -86,8 +86,11 @@ SetBits ( } if (Qwords > 0) { - SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, - (UINT64)-1); + SetMem64 ( + (VOID *)BitMap, + Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, + (UINT64)-1 + ); BitMap += Qwords; } @@ -108,29 +111,29 @@ SetBits ( STATIC VOID ClearBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN Lsbs; - UINTN Qwords; - UINTN Msbs; - UINTN StartBit; - UINTN EndBit; + UINTN Lsbs; + UINTN Qwords; + UINTN Msbs; + UINTN StartBit; + UINTN EndBit; - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) >= GUARDED_HEAP_MAP_ENTRY_BITS) { - Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % - GUARDED_HEAP_MAP_ENTRY_BITS; - Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; - Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; + Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % + GUARDED_HEAP_MAP_ENTRY_BITS; + Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; } else { - Msbs = BitNumber; - Lsbs = 0; - Qwords = 0; + Msbs = BitNumber; + Lsbs = 0; + Qwords = 0; } if (Msbs > 0) { @@ -163,21 +166,21 @@ ClearBits ( STATIC UINT64 GetBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN StartBit; - UINTN EndBit; - UINTN Lsbs; - UINTN Msbs; - UINT64 Result; + UINTN StartBit; + UINTN EndBit; + UINTN Lsbs; + UINTN Msbs; + UINT64 Result; ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS); - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) { Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit; @@ -187,13 +190,13 @@ GetBits ( Lsbs = 0; } - if (StartBit == 0 && BitNumber == GUARDED_HEAP_MAP_ENTRY_BITS) { + if ((StartBit == 0) && (BitNumber == GUARDED_HEAP_MAP_ENTRY_BITS)) { Result = *BitMap; } else { - Result = RShiftU64((*BitMap), StartBit) & (LShiftU64(1, Msbs) - 1); + Result = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1); if (Lsbs > 0) { - BitMap += 1; - Result |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs); + BitMap += 1; + Result |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs); } } @@ -212,18 +215,18 @@ GetBits ( **/ UINTN FindGuardedMemoryMap ( - IN EFI_PHYSICAL_ADDRESS Address, - IN BOOLEAN AllocMapUnit, - OUT UINT64 **BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN BOOLEAN AllocMapUnit, + OUT UINT64 **BitMap ) { - UINTN Level; - UINT64 *GuardMap; - UINT64 MapMemory; - UINTN Index; - UINTN Size; - UINTN BitsToUnitEnd; - EFI_STATUS Status; + UINTN Level; + UINT64 *GuardMap; + UINT64 MapMemory; + UINTN Index; + UINTN Size; + UINTN BitsToUnitEnd; + EFI_STATUS Status; MapMemory = 0; @@ -235,50 +238,49 @@ FindGuardedMemoryMap ( RShiftU64 ( Address, mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] - ) != 0) { - + ) != 0) + { if (mGuardedMemoryMap != 0) { Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; Status = CoreInternalAllocatePages ( - AllocateAnyPages, - EfiBootServicesData, - EFI_SIZE_TO_PAGES (Size), - &MapMemory, - FALSE - ); + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES (Size), + &MapMemory, + FALSE + ); ASSERT_EFI_ERROR (Status); ASSERT (MapMemory != 0); SetMem ((VOID *)(UINTN)MapMemory, Size, 0); *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap; - mGuardedMemoryMap = MapMemory; + mGuardedMemoryMap = MapMemory; } mMapLevel++; - } GuardMap = &mGuardedMemoryMap; for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Level < GUARDED_HEAP_MAP_TABLE_DEPTH; - ++Level) { - + ++Level) + { if (*GuardMap == 0) { if (!AllocMapUnit) { GuardMap = NULL; break; } - Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; + Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; Status = CoreInternalAllocatePages ( - AllocateAnyPages, - EfiBootServicesData, - EFI_SIZE_TO_PAGES (Size), - &MapMemory, - FALSE - ); + AllocateAnyPages, + EfiBootServicesData, + EFI_SIZE_TO_PAGES (Size), + &MapMemory, + FALSE + ); ASSERT_EFI_ERROR (Status); ASSERT (MapMemory != 0); @@ -286,10 +288,9 @@ FindGuardedMemoryMap ( *GuardMap = MapMemory; } - Index = (UINTN)RShiftU64 (Address, mLevelShift[Level]); - Index &= mLevelMask[Level]; - GuardMap = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64)); - + Index = (UINTN)RShiftU64 (Address, mLevelShift[Level]); + Index &= mLevelMask[Level]; + GuardMap = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64)); } BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address); @@ -309,13 +310,13 @@ FindGuardedMemoryMap ( VOID EFIAPI SetGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINTN BitsToUnitEnd; while (NumberOfPages > 0) { BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap); @@ -325,7 +326,7 @@ SetGuardedMemoryBits ( // Cross map unit Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } SetBits (Address, Bits, BitMap); @@ -346,13 +347,13 @@ SetGuardedMemoryBits ( VOID EFIAPI ClearGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINTN BitsToUnitEnd; while (NumberOfPages > 0) { BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap); @@ -362,7 +363,7 @@ ClearGuardedMemoryBits ( // Cross map unit Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } ClearBits (Address, Bits, BitMap); @@ -382,15 +383,15 @@ ClearGuardedMemoryBits ( **/ UINT64 GetGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINT64 Result; - UINTN Shift; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINT64 Result; + UINTN Shift; + UINTN BitsToUnitEnd; ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS); @@ -401,9 +402,9 @@ GetGuardedMemoryBits ( if (NumberOfPages > BitsToUnitEnd) { // Cross map unit - Bits = BitsToUnitEnd; + Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } if (BitMap != NULL) { @@ -428,15 +429,18 @@ GetGuardedMemoryBits ( UINTN EFIAPI GetGuardMapBit ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ) { - UINT64 *GuardMap; + UINT64 *GuardMap; FindGuardedMemoryMap (Address, FALSE, &GuardMap); if (GuardMap != NULL) { - if (RShiftU64 (*GuardMap, - GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) { + if (RShiftU64 ( + *GuardMap, + GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address) + ) & 1) + { return 1; } } @@ -444,7 +448,6 @@ GetGuardMapBit ( return 0; } - /** Check to see if the page at the given address is a Guard page or not. @@ -456,10 +459,10 @@ GetGuardMapBit ( BOOLEAN EFIAPI IsGuardPage ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ) { - UINT64 BitMap; + UINT64 BitMap; // // There must be at least one guarded page before and/or after given @@ -470,7 +473,6 @@ IsGuardPage ( return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0))); } - /** Check to see if the page at the given address is guarded or not. @@ -482,7 +484,7 @@ IsGuardPage ( BOOLEAN EFIAPI IsMemoryGuarded ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ) { return (GetGuardMapBit (Address) == 1); @@ -500,10 +502,10 @@ IsMemoryGuarded ( VOID EFIAPI SetGuardPage ( - IN EFI_PHYSICAL_ADDRESS BaseAddress + IN EFI_PHYSICAL_ADDRESS BaseAddress ) { - EFI_STATUS Status; + EFI_STATUS Status; if (gCpu == NULL) { return; @@ -535,11 +537,11 @@ SetGuardPage ( VOID EFIAPI UnsetGuardPage ( - IN EFI_PHYSICAL_ADDRESS BaseAddress + IN EFI_PHYSICAL_ADDRESS BaseAddress ) { - UINT64 Attributes; - EFI_STATUS Status; + UINT64 Attributes; + EFI_STATUS Status; if (gCpu == NULL) { return; @@ -583,13 +585,13 @@ UnsetGuardPage ( **/ BOOLEAN IsMemoryTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType, - IN UINT8 PageOrPool + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType, + IN UINT8 PageOrPool ) { - UINT64 TestBit; - UINT64 ConfigBit; + UINT64 TestBit; + UINT64 ConfigBit; if (AllocateType == AllocateAddress) { return FALSE; @@ -609,7 +611,7 @@ IsMemoryTypeToGuard ( if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { TestBit = BIT63; - } else if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { + } else if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { TestBit = BIT62; } else if (MemoryType < EfiMaxMemoryType) { TestBit = LShiftU64 (1, MemoryType); @@ -633,11 +635,14 @@ IsMemoryTypeToGuard ( **/ BOOLEAN IsPoolTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages, - GUARD_HEAP_TYPE_POOL); + return IsMemoryTypeToGuard ( + MemoryType, + AllocateAnyPages, + GUARD_HEAP_TYPE_POOL + ); } /** @@ -651,8 +656,8 @@ IsPoolTypeToGuard ( **/ BOOLEAN IsPageTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType ) { return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE); @@ -667,7 +672,7 @@ IsPageTypeToGuard ( **/ BOOLEAN IsHeapGuardEnabled ( - UINT8 GuardType + UINT8 GuardType ) { return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages, GuardType); @@ -683,11 +688,11 @@ IsHeapGuardEnabled ( **/ VOID SetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ) { - EFI_PHYSICAL_ADDRESS GuardPage; + EFI_PHYSICAL_ADDRESS GuardPage; // // Set tail Guard @@ -719,8 +724,8 @@ SetGuardForMemory ( **/ VOID UnsetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ) { EFI_PHYSICAL_ADDRESS GuardPage; @@ -742,7 +747,7 @@ UnsetGuardForMemory ( // ------------------- // Start -> -1 -2 // - GuardPage = Memory - EFI_PAGES_TO_SIZE (1); + GuardPage = Memory - EFI_PAGES_TO_SIZE (1); GuardBitmap = GetGuardedMemoryBits (Memory - EFI_PAGES_TO_SIZE (2), 2); if ((GuardBitmap & BIT1) == 0) { // @@ -775,7 +780,7 @@ UnsetGuardForMemory ( // -------------------- // +1 +0 <- End // - GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages); + GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages); GuardBitmap = GetGuardedMemoryBits (GuardPage, 2); if ((GuardBitmap & BIT0) == 0) { // @@ -799,7 +804,7 @@ UnsetGuardForMemory ( // // No matter what, we just clear the mark of the Guarded memory. // - ClearGuardedMemoryBits(Memory, NumberOfPages); + ClearGuardedMemoryBits (Memory, NumberOfPages); } /** @@ -818,9 +823,9 @@ UnsetGuardForMemory ( **/ UINT64 AdjustMemoryS ( - IN UINT64 Start, - IN UINT64 Size, - IN UINT64 SizeRequested + IN UINT64 Start, + IN UINT64 Size, + IN UINT64 SizeRequested ) { UINT64 Target; @@ -831,7 +836,7 @@ AdjustMemoryS ( // make sure alignment of the returned pool address. // if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0) { - SizeRequested = ALIGN_VALUE(SizeRequested, 8); + SizeRequested = ALIGN_VALUE (SizeRequested, 8); } Target = Start + Size - SizeRequested; @@ -877,8 +882,8 @@ AdjustMemoryS ( **/ VOID AdjustMemoryF ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ) { EFI_PHYSICAL_ADDRESS Start; @@ -886,11 +891,11 @@ AdjustMemoryF ( UINTN PagesToFree; UINT64 GuardBitmap; - if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) { + if ((Memory == NULL) || (NumberOfPages == NULL) || (*NumberOfPages == 0)) { return; } - Start = *Memory; + Start = *Memory; PagesToFree = *NumberOfPages; // @@ -906,7 +911,7 @@ AdjustMemoryF ( // Start -> -1 -2 // MemoryToTest = Start - EFI_PAGES_TO_SIZE (2); - GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); + GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); if ((GuardBitmap & BIT1) == 0) { // // Head Guard exists. @@ -941,7 +946,7 @@ AdjustMemoryF ( // +1 +0 <- End // MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree); - GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); + GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); if ((GuardBitmap & BIT0) == 0) { // // Tail Guard exists. @@ -961,8 +966,8 @@ AdjustMemoryF ( PagesToFree -= 1; } - *Memory = Start; - *NumberOfPages = PagesToFree; + *Memory = Start; + *NumberOfPages = PagesToFree; } /** @@ -975,8 +980,8 @@ AdjustMemoryF ( **/ VOID AdjustMemoryA ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ) { // @@ -1009,12 +1014,12 @@ AdjustMemoryA ( **/ VOID * AdjustPoolHeadA ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages, - IN UINTN Size + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages, + IN UINTN Size ) { - if (Memory == 0 || (PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) { + if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) { // // Pool head is put near the head Guard // @@ -1037,10 +1042,10 @@ AdjustPoolHeadA ( **/ VOID * AdjustPoolHeadF ( - IN EFI_PHYSICAL_ADDRESS Memory + IN EFI_PHYSICAL_ADDRESS Memory ) { - if (Memory == 0 || (PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) { + if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) { // // Pool head is put near the head Guard // @@ -1103,30 +1108,31 @@ SetAllGuardPages ( VOID ) { - UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 TableEntry; - UINT64 Address; - UINT64 GuardPage; - INTN Level; - UINTN Index; - BOOLEAN OnGuarding; - - if (mGuardedMemoryMap == 0 || - mMapLevel == 0 || - mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) { + UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 TableEntry; + UINT64 Address; + UINT64 GuardPage; + INTN Level; + UINTN Index; + BOOLEAN OnGuarding; + + if ((mGuardedMemoryMap == 0) || + (mMapLevel == 0) || + (mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH)) + { return; } CopyMem (Entries, mLevelMask, sizeof (Entries)); CopyMem (Shifts, mLevelShift, sizeof (Shifts)); - SetMem (Tables, sizeof(Tables), 0); - SetMem (Addresses, sizeof(Addresses), 0); - SetMem (Indices, sizeof(Indices), 0); + SetMem (Tables, sizeof (Tables), 0); + SetMem (Addresses, sizeof (Addresses), 0); + SetMem (Indices, sizeof (Indices), 0); Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Tables[Level] = mGuardedMemoryMap; @@ -1135,32 +1141,26 @@ SetAllGuardPages ( DEBUG_CODE ( DumpGuardedMemoryBitmap (); - ); + ); while (TRUE) { if (Indices[Level] > Entries[Level]) { Tables[Level] = 0; Level -= 1; } else { - - TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; - Address = Addresses[Level]; + TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; + Address = Addresses[Level]; if (TableEntry == 0) { - OnGuarding = FALSE; - } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { - - Level += 1; - Tables[Level] = TableEntry; - Addresses[Level] = Address; - Indices[Level] = 0; + Level += 1; + Tables[Level] = TableEntry; + Addresses[Level] = Address; + Indices[Level] = 0; continue; - } else { - Index = 0; while (Index < GUARDED_HEAP_MAP_ENTRY_BITS) { if ((TableEntry & 1) == 1) { @@ -1169,6 +1169,7 @@ SetAllGuardPages ( } else { GuardPage = Address - EFI_PAGE_SIZE; } + OnGuarding = TRUE; } else { if (OnGuarding) { @@ -1176,6 +1177,7 @@ SetAllGuardPages ( } else { GuardPage = 0; } + OnGuarding = FALSE; } @@ -1198,10 +1200,9 @@ SetAllGuardPages ( break; } - Indices[Level] += 1; - Address = (Level == 0) ? 0 : Addresses[Level - 1]; - Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]); - + Indices[Level] += 1; + Address = (Level == 0) ? 0 : Addresses[Level - 1]; + Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]); } } @@ -1214,31 +1215,32 @@ SetAllGuardPages ( **/ VOID GetLastGuardedFreePageAddress ( - OUT EFI_PHYSICAL_ADDRESS *Address + OUT EFI_PHYSICAL_ADDRESS *Address ) { - EFI_PHYSICAL_ADDRESS AddressGranularity; - EFI_PHYSICAL_ADDRESS BaseAddress; - UINTN Level; - UINT64 Map; - INTN Index; + EFI_PHYSICAL_ADDRESS AddressGranularity; + EFI_PHYSICAL_ADDRESS BaseAddress; + UINTN Level; + UINT64 Map; + INTN Index; ASSERT (mMapLevel >= 1); BaseAddress = 0; - Map = mGuardedMemoryMap; + Map = mGuardedMemoryMap; for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Level < GUARDED_HEAP_MAP_TABLE_DEPTH; - ++Level) { + ++Level) + { AddressGranularity = LShiftU64 (1, mLevelShift[Level]); // // Find the non-NULL entry at largest index. // - for (Index = (INTN)mLevelMask[Level]; Index >= 0 ; --Index) { + for (Index = (INTN)mLevelMask[Level]; Index >= 0; --Index) { if (((UINT64 *)(UINTN)Map)[Index] != 0) { BaseAddress += MultU64x32 (AddressGranularity, (UINT32)Index); - Map = ((UINT64 *)(UINTN)Map)[Index]; + Map = ((UINT64 *)(UINTN)Map)[Index]; break; } } @@ -1248,7 +1250,7 @@ GetLastGuardedFreePageAddress ( // Find the non-zero MSB then get the page address. // while (Map != 0) { - Map = RShiftU64 (Map, 1); + Map = RShiftU64 (Map, 1); BaseAddress += EFI_PAGES_TO_SIZE (1); } @@ -1265,8 +1267,8 @@ GetLastGuardedFreePageAddress ( **/ VOID MarkFreedPages ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN Pages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN Pages ) { SetGuardedMemoryBits (BaseAddress, Pages); @@ -1283,11 +1285,11 @@ MarkFreedPages ( VOID EFIAPI GuardFreedPages ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN Pages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN Pages ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Legacy memory lower than 1MB might be accessed with no allocation. Leave @@ -1322,6 +1324,7 @@ GuardFreedPages ( if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "Failed to guard freed pages: %p (%lu)\n", BaseAddress, (UINT64)Pages)); } + mOnGuarding = FALSE; } } @@ -1337,8 +1340,8 @@ GuardFreedPages ( VOID EFIAPI GuardFreedPagesChecked ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN Pages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN Pages ) { if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) { @@ -1355,30 +1358,31 @@ GuardAllFreedPages ( VOID ) { - UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 TableEntry; - UINT64 Address; - UINT64 GuardPage; - INTN Level; - UINT64 BitIndex; - UINTN GuardPageNumber; - - if (mGuardedMemoryMap == 0 || - mMapLevel == 0 || - mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) { + UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 TableEntry; + UINT64 Address; + UINT64 GuardPage; + INTN Level; + UINT64 BitIndex; + UINTN GuardPageNumber; + + if ((mGuardedMemoryMap == 0) || + (mMapLevel == 0) || + (mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH)) + { return; } CopyMem (Entries, mLevelMask, sizeof (Entries)); CopyMem (Shifts, mLevelShift, sizeof (Shifts)); - SetMem (Tables, sizeof(Tables), 0); - SetMem (Addresses, sizeof(Addresses), 0); - SetMem (Indices, sizeof(Indices), 0); + SetMem (Tables, sizeof (Tables), 0); + SetMem (Addresses, sizeof (Addresses), 0); + SetMem (Indices, sizeof (Indices), 0); Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Tables[Level] = mGuardedMemoryMap; @@ -1391,14 +1395,14 @@ GuardAllFreedPages ( Tables[Level] = 0; Level -= 1; } else { - TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; - Address = Addresses[Level]; + TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; + Address = Addresses[Level]; if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { - Level += 1; - Tables[Level] = TableEntry; - Addresses[Level] = Address; - Indices[Level] = 0; + Level += 1; + Tables[Level] = TableEntry; + Addresses[Level] = Address; + Indices[Level] = 0; continue; } else { @@ -1408,6 +1412,7 @@ GuardAllFreedPages ( if (GuardPage == (UINT64)-1) { GuardPage = Address; } + ++GuardPageNumber; } else if (GuardPageNumber > 0) { GuardFreedPages (GuardPage, GuardPageNumber); @@ -1429,10 +1434,9 @@ GuardAllFreedPages ( break; } - Indices[Level] += 1; - Address = (Level == 0) ? 0 : Addresses[Level - 1]; + Indices[Level] += 1; + Address = (Level == 0) ? 0 : Addresses[Level - 1]; Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]); - } // @@ -1457,16 +1461,17 @@ GuardAllFreedPages ( **/ VOID MergeGuardPages ( - IN EFI_MEMORY_DESCRIPTOR *MemoryMapEntry, - IN EFI_PHYSICAL_ADDRESS MaxAddress + IN EFI_MEMORY_DESCRIPTOR *MemoryMapEntry, + IN EFI_PHYSICAL_ADDRESS MaxAddress ) { - EFI_PHYSICAL_ADDRESS EndAddress; - UINT64 Bitmap; - INTN Pages; + EFI_PHYSICAL_ADDRESS EndAddress; + UINT64 Bitmap; + INTN Pages; if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) || - MemoryMapEntry->Type >= EfiMemoryMappedIO) { + (MemoryMapEntry->Type >= EfiMemoryMappedIO)) + { return; } @@ -1511,14 +1516,14 @@ MergeGuardPages ( **/ BOOLEAN PromoteGuardedFreePages ( - OUT EFI_PHYSICAL_ADDRESS *StartAddress, - OUT EFI_PHYSICAL_ADDRESS *EndAddress + OUT EFI_PHYSICAL_ADDRESS *StartAddress, + OUT EFI_PHYSICAL_ADDRESS *EndAddress ) { - EFI_STATUS Status; - UINTN AvailablePages; - UINT64 Bitmap; - EFI_PHYSICAL_ADDRESS Start; + EFI_STATUS Status; + UINTN AvailablePages; + UINT64 Bitmap; + EFI_PHYSICAL_ADDRESS Start; if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) { return FALSE; @@ -1528,8 +1533,8 @@ PromoteGuardedFreePages ( // Similar to memory allocation service, always search the freed pages in // descending direction. // - Start = mLastPromotedPage; - AvailablePages = 0; + Start = mLastPromotedPage; + AvailablePages = 0; while (AvailablePages == 0) { Start -= EFI_PAGES_TO_SIZE (GUARDED_HEAP_MAP_ENTRY_BITS); // @@ -1565,7 +1570,7 @@ PromoteGuardedFreePages ( // operation; otherwise infinite loops could be caused. // mOnGuarding = TRUE; - Status = gCpu->SetMemoryAttributes (gCpu, Start, EFI_PAGES_TO_SIZE(AvailablePages), 0); + Status = gCpu->SetMemoryAttributes (gCpu, Start, EFI_PAGES_TO_SIZE (AvailablePages), 0); ASSERT_EFI_ERROR (Status); mOnGuarding = FALSE; } @@ -1590,7 +1595,8 @@ HeapGuardCpuArchProtocolNotify ( ASSERT (gCpu != NULL); if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL) && - IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) { + IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) + { DEBUG ((DEBUG_ERROR, "Heap guard and freed memory guard cannot be enabled at the same time.\n")); CpuDeadLoop (); } @@ -1614,11 +1620,11 @@ HeapGuardCpuArchProtocolNotify ( **/ VOID Uint64ToBinString ( - IN UINT64 Value, - OUT CHAR8 *BinString + IN UINT64 Value, + OUT CHAR8 *BinString ) { - UINTN Index; + UINTN Index; if (BinString == NULL) { return; @@ -1626,8 +1632,9 @@ Uint64ToBinString ( for (Index = 64; Index > 0; --Index) { BinString[Index - 1] = '0' + (Value & 1); - Value = RShiftU64 (Value, 1); + Value = RShiftU64 (Value, 1); } + BinString[64] = '\0'; } @@ -1640,44 +1647,48 @@ DumpGuardedMemoryBitmap ( VOID ) { - UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 TableEntry; - UINT64 Address; - INTN Level; - UINTN RepeatZero; - CHAR8 String[GUARDED_HEAP_MAP_ENTRY_BITS + 1]; - CHAR8 *Ruler1; - CHAR8 *Ruler2; + UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 TableEntry; + UINT64 Address; + INTN Level; + UINTN RepeatZero; + CHAR8 String[GUARDED_HEAP_MAP_ENTRY_BITS + 1]; + CHAR8 *Ruler1; + CHAR8 *Ruler2; if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_ALL)) { return; } - if (mGuardedMemoryMap == 0 || - mMapLevel == 0 || - mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) { + if ((mGuardedMemoryMap == 0) || + (mMapLevel == 0) || + (mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH)) + { return; } Ruler1 = " 3 2 1 0"; Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210"; - DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "=============================" - " Guarded Memory Bitmap " - "==============================\r\n")); + DEBUG (( + HEAP_GUARD_DEBUG_LEVEL, + "=============================" + " Guarded Memory Bitmap " + "==============================\r\n" + )); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, " %a\r\n", Ruler1)); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, " %a\r\n", Ruler2)); CopyMem (Entries, mLevelMask, sizeof (Entries)); CopyMem (Shifts, mLevelShift, sizeof (Shifts)); - SetMem (Indices, sizeof(Indices), 0); - SetMem (Tables, sizeof(Tables), 0); - SetMem (Addresses, sizeof(Addresses), 0); + SetMem (Indices, sizeof (Indices), 0); + SetMem (Tables, sizeof (Tables), 0); + SetMem (Addresses, sizeof (Addresses), 0); Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Tables[Level] = mGuardedMemoryMap; @@ -1686,7 +1697,6 @@ DumpGuardedMemoryBitmap ( while (TRUE) { if (Indices[Level] > Entries[Level]) { - Tables[Level] = 0; Level -= 1; RepeatZero = 0; @@ -1696,40 +1706,33 @@ DumpGuardedMemoryBitmap ( "=========================================" "=========================================\r\n" )); - } else { - - TableEntry = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]]; - Address = Addresses[Level]; + TableEntry = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]]; + Address = Addresses[Level]; if (TableEntry == 0) { - if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { if (RepeatZero == 0) { - Uint64ToBinString(TableEntry, String); + Uint64ToBinString (TableEntry, String); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String)); } else if (RepeatZero == 1) { DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "... : ...\r\n")); } + RepeatZero += 1; } - } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { - - Level += 1; - Tables[Level] = TableEntry; - Addresses[Level] = Address; - Indices[Level] = 0; - RepeatZero = 0; + Level += 1; + Tables[Level] = TableEntry; + Addresses[Level] = Address; + Indices[Level] = 0; + RepeatZero = 0; continue; - } else { - RepeatZero = 0; - Uint64ToBinString(TableEntry, String); + Uint64ToBinString (TableEntry, String); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String)); - } } @@ -1737,10 +1740,8 @@ DumpGuardedMemoryBitmap ( break; } - Indices[Level] += 1; - Address = (Level == 0) ? 0 : Addresses[Level - 1]; - Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]); - + Indices[Level] += 1; + Address = (Level == 0) ? 0 : Addresses[Level - 1]; + Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]); } } - diff --git a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.h b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.h index d6e4ed39dd..9a32b4dd51 100644 --- a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.h +++ b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.h @@ -51,15 +51,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9 // bits in address. (512 = 1 << 9) // -#define BYTE_LENGTH_SHIFT 3 // (8 = 1 << 3) +#define BYTE_LENGTH_SHIFT 3 // (8 = 1 << 3) #define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT \ (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT) -#define GUARDED_HEAP_MAP_TABLE_DEPTH 5 +#define GUARDED_HEAP_MAP_TABLE_DEPTH 5 // Use UINT64_index + bit_index_of_UINT64 to locate the bit in may -#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT 6 // (64 = 1 << 6) +#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT 6 // (64 = 1 << 6) #define GUARDED_HEAP_MAP_ENTRY_BITS \ (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) @@ -152,9 +152,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Memory type to guard (matching the related PCD definition) // -#define GUARD_HEAP_TYPE_PAGE BIT0 -#define GUARD_HEAP_TYPE_POOL BIT1 -#define GUARD_HEAP_TYPE_FREED BIT4 +#define GUARD_HEAP_TYPE_PAGE BIT0 +#define GUARD_HEAP_TYPE_POOL BIT1 +#define GUARD_HEAP_TYPE_FREED BIT4 #define GUARD_HEAP_TYPE_ALL \ (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_FREED) @@ -164,10 +164,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define HEAP_GUARD_DEBUG_LEVEL (DEBUG_POOL|DEBUG_PAGE) typedef struct { - UINT32 TailMark; - UINT32 HeadMark; - EFI_PHYSICAL_ADDRESS Address; - LIST_ENTRY Link; + UINT32 TailMark; + UINT32 HeadMark; + EFI_PHYSICAL_ADDRESS Address; + LIST_ENTRY Link; } HEAP_GUARD_NODE; /** @@ -219,8 +219,8 @@ CoreConvertPagesWithGuard ( **/ VOID SetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -233,8 +233,8 @@ SetGuardForMemory ( **/ VOID UnsetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -247,8 +247,8 @@ UnsetGuardForMemory ( **/ VOID AdjustMemoryA ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ); /** @@ -265,8 +265,8 @@ AdjustMemoryA ( **/ VOID AdjustMemoryF ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ); /** @@ -285,9 +285,9 @@ AdjustMemoryF ( **/ UINT64 AdjustMemoryS ( - IN UINT64 Start, - IN UINT64 Size, - IN UINT64 SizeRequested + IN UINT64 Start, + IN UINT64 Size, + IN UINT64 SizeRequested ); /** @@ -301,7 +301,7 @@ AdjustMemoryS ( **/ BOOLEAN IsPoolTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ); /** @@ -315,8 +315,8 @@ IsPoolTypeToGuard ( **/ BOOLEAN IsPageTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType ); /** @@ -330,7 +330,7 @@ IsPageTypeToGuard ( BOOLEAN EFIAPI IsMemoryGuarded ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ); /** @@ -344,7 +344,7 @@ IsMemoryGuarded ( BOOLEAN EFIAPI IsGuardPage ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ); /** @@ -369,9 +369,9 @@ DumpGuardedMemoryBitmap ( **/ VOID * AdjustPoolHeadA ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages, - IN UINTN Size + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages, + IN UINTN Size ); /** @@ -383,7 +383,7 @@ AdjustPoolHeadA ( **/ VOID * AdjustPoolHeadF ( - IN EFI_PHYSICAL_ADDRESS Memory + IN EFI_PHYSICAL_ADDRESS Memory ); /** @@ -395,7 +395,7 @@ AdjustPoolHeadF ( **/ BOOLEAN IsHeapGuardEnabled ( - UINT8 GuardType + UINT8 GuardType ); /** @@ -418,8 +418,8 @@ HeapGuardCpuArchProtocolNotify ( **/ VOID MergeGuardPages ( - IN EFI_MEMORY_DESCRIPTOR *MemoryMapEntry, - IN EFI_PHYSICAL_ADDRESS MaxAddress + IN EFI_MEMORY_DESCRIPTOR *MemoryMapEntry, + IN EFI_PHYSICAL_ADDRESS MaxAddress ); /** @@ -433,8 +433,8 @@ MergeGuardPages ( VOID EFIAPI GuardFreedPagesChecked ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN Pages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN Pages ); /** @@ -458,10 +458,10 @@ GuardFreedPagesChecked ( **/ BOOLEAN PromoteGuardedFreePages ( - OUT EFI_PHYSICAL_ADDRESS *StartAddress, - OUT EFI_PHYSICAL_ADDRESS *EndAddress + OUT EFI_PHYSICAL_ADDRESS *StartAddress, + OUT EFI_PHYSICAL_ADDRESS *EndAddress ); -extern BOOLEAN mOnGuarding; +extern BOOLEAN mOnGuarding; #endif diff --git a/MdeModulePkg/Core/Dxe/Mem/Imem.h b/MdeModulePkg/Core/Dxe/Mem/Imem.h index 090f3f089f..2f0bf2bf63 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Imem.h +++ b/MdeModulePkg/Core/Dxe/Mem/Imem.h @@ -20,34 +20,33 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // | 0x80000000..0xFFFFFFFF - OS reserved | // +---------------------------------------------------+ // -#define MEMORY_TYPE_OS_RESERVED_MIN 0x80000000 -#define MEMORY_TYPE_OS_RESERVED_MAX 0xFFFFFFFF -#define MEMORY_TYPE_OEM_RESERVED_MIN 0x70000000 -#define MEMORY_TYPE_OEM_RESERVED_MAX 0x7FFFFFFF +#define MEMORY_TYPE_OS_RESERVED_MIN 0x80000000 +#define MEMORY_TYPE_OS_RESERVED_MAX 0xFFFFFFFF +#define MEMORY_TYPE_OEM_RESERVED_MIN 0x70000000 +#define MEMORY_TYPE_OEM_RESERVED_MAX 0x7FFFFFFF // // MEMORY_MAP_ENTRY // -#define MEMORY_MAP_SIGNATURE SIGNATURE_32('m','m','a','p') +#define MEMORY_MAP_SIGNATURE SIGNATURE_32('m','m','a','p') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - BOOLEAN FromPages; + UINTN Signature; + LIST_ENTRY Link; + BOOLEAN FromPages; - EFI_MEMORY_TYPE Type; - UINT64 Start; - UINT64 End; + EFI_MEMORY_TYPE Type; + UINT64 Start; + UINT64 End; - UINT64 VirtualStart; - UINT64 Attribute; + UINT64 VirtualStart; + UINT64 Attribute; } MEMORY_MAP; // // Internal prototypes // - /** Internal function. Used by the pool functions to allocate pages to back pool allocation requests. @@ -62,14 +61,12 @@ typedef struct { **/ VOID * CoreAllocatePoolPages ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN NumberOfPages, - IN UINTN Alignment, - IN BOOLEAN NeedGuard + IN EFI_MEMORY_TYPE PoolType, + IN UINTN NumberOfPages, + IN UINTN Alignment, + IN BOOLEAN NeedGuard ); - - /** Internal function. Frees pool pages allocated via AllocatePoolPages () @@ -79,12 +76,10 @@ CoreAllocatePoolPages ( **/ VOID CoreFreePoolPages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); - - /** Internal function to allocate pool of a particular type. Caller must have the memory lock held @@ -103,8 +98,6 @@ CoreAllocatePoolI ( IN BOOLEAN NeedGuard ); - - /** Internal function to free a pool entry. Caller must have the memory lock held @@ -118,12 +111,10 @@ CoreAllocatePoolI ( **/ EFI_STATUS CoreFreePoolI ( - IN VOID *Buffer, - OUT EFI_MEMORY_TYPE *PoolType OPTIONAL + IN VOID *Buffer, + OUT EFI_MEMORY_TYPE *PoolType OPTIONAL ); - - /** Enter critical section by gaining lock on gMemoryLock. @@ -133,7 +124,6 @@ CoreAcquireMemoryLock ( VOID ); - /** Exit critical section by releasing lock on gMemoryLock. @@ -165,18 +155,18 @@ CoreReleaseMemoryLock ( EFI_STATUS EFIAPI CoreInternalAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN BOOLEAN NeedGuard + IN BOOLEAN NeedGuard ); // // Internal Global data // -extern EFI_LOCK gMemoryLock; -extern LIST_ENTRY gMemoryMap; -extern LIST_ENTRY mGcdMemorySpaceMap; +extern EFI_LOCK gMemoryLock; +extern LIST_ENTRY gMemoryMap; +extern LIST_ENTRY mGcdMemorySpaceMap; #endif diff --git a/MdeModulePkg/Core/Dxe/Mem/MemData.c b/MdeModulePkg/Core/Dxe/Mem/MemData.c index 67d8868322..8f138b703e 100644 --- a/MdeModulePkg/Core/Dxe/Mem/MemData.c +++ b/MdeModulePkg/Core/Dxe/Mem/MemData.c @@ -8,13 +8,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" - // // MemoryLock - synchronizes access to the memory map and pool lists // -EFI_LOCK gMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +EFI_LOCK gMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); // // MemoryMap - the current memory map // -LIST_ENTRY gMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (gMemoryMap); +LIST_ENTRY gMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (gMemoryMap); diff --git a/MdeModulePkg/Core/Dxe/Mem/MemoryProfileRecord.c b/MdeModulePkg/Core/Dxe/Mem/MemoryProfileRecord.c index 62bbe3cdc8..00e33b707d 100644 --- a/MdeModulePkg/Core/Dxe/Mem/MemoryProfileRecord.c +++ b/MdeModulePkg/Core/Dxe/Mem/MemoryProfileRecord.c @@ -9,15 +9,15 @@ #include "DxeMain.h" #include "Imem.h" -#define IS_UEFI_MEMORY_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT0) != 0) +#define IS_UEFI_MEMORY_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT0) != 0) #define GET_OCCUPIED_SIZE(ActualSize, Alignment) \ ((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))) typedef struct { - UINT32 Signature; - MEMORY_PROFILE_CONTEXT Context; - LIST_ENTRY *DriverInfoList; + UINT32 Signature; + MEMORY_PROFILE_CONTEXT Context; + LIST_ENTRY *DriverInfoList; } MEMORY_PROFILE_CONTEXT_DATA; typedef struct { @@ -29,15 +29,14 @@ typedef struct { } MEMORY_PROFILE_DRIVER_INFO_DATA; typedef struct { - UINT32 Signature; - MEMORY_PROFILE_ALLOC_INFO AllocInfo; - CHAR8 *ActionString; - LIST_ENTRY Link; + UINT32 Signature; + MEMORY_PROFILE_ALLOC_INFO AllocInfo; + CHAR8 *ActionString; + LIST_ENTRY Link; } MEMORY_PROFILE_ALLOC_INFO_DATA; - -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mImageQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageQueue); -GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mMemoryProfileContext = { +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mImageQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageQueue); +GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mMemoryProfileContext = { MEMORY_PROFILE_CONTEXT_SIGNATURE, { { @@ -47,21 +46,21 @@ GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mMemoryProfileContext }, 0, 0, - {0}, - {0}, + { 0 }, + { 0 }, 0, 0, 0 }, &mImageQueue, }; -GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA *mMemoryProfileContextPtr = NULL; +GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA *mMemoryProfileContextPtr = NULL; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOCK mMemoryProfileLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mMemoryProfileGettingStatus = FALSE; -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mMemoryProfileRecordingEnable = MEMORY_PROFILE_RECORDING_DISABLE; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_DEVICE_PATH_PROTOCOL *mMemoryProfileDriverPath; -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMemoryProfileDriverPathSize; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_LOCK mMemoryProfileLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mMemoryProfileGettingStatus = FALSE; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mMemoryProfileRecordingEnable = MEMORY_PROFILE_RECORDING_DISABLE; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_DEVICE_PATH_PROTOCOL *mMemoryProfileDriverPath; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMemoryProfileDriverPathSize; /** Get memory profile data. @@ -82,7 +81,7 @@ EFIAPI ProfileProtocolGetData ( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, IN OUT UINT64 *ProfileSize, - OUT VOID *ProfileBuffer + OUT VOID *ProfileBuffer ); /** @@ -103,11 +102,11 @@ ProfileProtocolGetData ( EFI_STATUS EFIAPI ProfileProtocolRegisterImage ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize, - IN EFI_FV_FILETYPE FileType + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize, + IN EFI_FV_FILETYPE FileType ); /** @@ -127,10 +126,10 @@ ProfileProtocolRegisterImage ( EFI_STATUS EFIAPI ProfileProtocolUnregisterImage ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize ); /** @@ -147,8 +146,8 @@ ProfileProtocolUnregisterImage ( EFI_STATUS EFIAPI ProfileProtocolGetRecordingState ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - OUT BOOLEAN *RecordingState + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + OUT BOOLEAN *RecordingState ); /** @@ -164,8 +163,8 @@ ProfileProtocolGetRecordingState ( EFI_STATUS EFIAPI ProfileProtocolSetRecordingState ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN BOOLEAN RecordingState + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN BOOLEAN RecordingState ); /** @@ -194,16 +193,16 @@ ProfileProtocolSetRecordingState ( EFI_STATUS EFIAPI ProfileProtocolRecord ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ); -GLOBAL_REMOVE_IF_UNREFERENCED EDKII_MEMORY_PROFILE_PROTOCOL mProfileProtocol = { +GLOBAL_REMOVE_IF_UNREFERENCED EDKII_MEMORY_PROFILE_PROTOCOL mProfileProtocol = { ProfileProtocolGetData, ProfileProtocolRegisterImage, ProfileProtocolUnregisterImage, @@ -268,22 +267,22 @@ InternalPeCoffGetSubsystem ( ASSERT (Pe32Data != NULL); - DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data; + DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, so read the PE header after the DOS image header. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) ((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff)); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff)); } else { // // DOS image header is not present, so PE header is at the image base. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) Pe32Data; + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data; } if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) { return Hdr.Te->Subsystem; - } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { + } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { Magic = Hdr.Pe32->OptionalHeader.Magic; if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return Hdr.Pe32->OptionalHeader.Subsystem; @@ -318,23 +317,23 @@ InternalPeCoffGetEntryPoint ( OUT VOID **EntryPoint ) { - EFI_IMAGE_DOS_HEADER *DosHdr; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; + EFI_IMAGE_DOS_HEADER *DosHdr; + EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; ASSERT (Pe32Data != NULL); ASSERT (EntryPoint != NULL); - DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data; + DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, so read the PE header after the DOS image header. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) ((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff)); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff)); } else { // // DOS image header is not present, so PE header is at the image base. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) Pe32Data; + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data; } // @@ -342,10 +341,10 @@ InternalPeCoffGetEntryPoint ( // AddressOfEntryPoint is common for PE32 & PE32+ // if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) { - *EntryPoint = (VOID *) ((UINTN) Pe32Data + (UINTN) (Hdr.Te->AddressOfEntryPoint & 0x0ffffffff) + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize); + *EntryPoint = (VOID *)((UINTN)Pe32Data + (UINTN)(Hdr.Te->AddressOfEntryPoint & 0x0ffffffff) + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize); return RETURN_SUCCESS; } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { - *EntryPoint = (VOID *) ((UINTN) Pe32Data + (UINTN) (Hdr.Pe32->OptionalHeader.AddressOfEntryPoint & 0x0ffffffff)); + *EntryPoint = (VOID *)((UINTN)Pe32Data + (UINTN)(Hdr.Pe32->OptionalHeader.AddressOfEntryPoint & 0x0ffffffff)); return RETURN_SUCCESS; } @@ -368,30 +367,30 @@ InternalPeCoffGetEntryPoint ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * BuildDriverInfo ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize, - IN PHYSICAL_ADDRESS EntryPoint, - IN UINT16 ImageSubsystem, - IN EFI_FV_FILETYPE FileType + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize, + IN PHYSICAL_ADDRESS EntryPoint, + IN UINT16 ImageSubsystem, + IN EFI_FV_FILETYPE FileType ) { - EFI_STATUS Status; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - VOID *EntryPointInImage; - CHAR8 *PdbString; - UINTN PdbSize; - UINTN PdbOccupiedSize; - - PdbSize = 0; + EFI_STATUS Status; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + VOID *EntryPointInImage; + CHAR8 *PdbString; + UINTN PdbSize; + UINTN PdbOccupiedSize; + + PdbSize = 0; PdbOccupiedSize = 0; - PdbString = NULL; + PdbString = NULL; if (ImageBase != 0) { - PdbString = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageBase); + PdbString = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageBase); if (PdbString != NULL) { - PdbSize = AsciiStrSize (PdbString); + PdbSize = AsciiStrSize (PdbString); PdbOccupiedSize = GET_OCCUPIED_SIZE (PdbSize, sizeof (UINT64)); } } @@ -402,53 +401,56 @@ BuildDriverInfo ( Status = CoreInternalAllocatePool ( EfiBootServicesData, sizeof (*DriverInfoData) + sizeof (LIST_ENTRY) + PdbSize, - (VOID **) &DriverInfoData + (VOID **)&DriverInfoData ); if (EFI_ERROR (Status)) { return NULL; } + ASSERT (DriverInfoData != NULL); ZeroMem (DriverInfoData, sizeof (*DriverInfoData)); - DriverInfo = &DriverInfoData->DriverInfo; - DriverInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; + DriverInfo = &DriverInfoData->DriverInfo; + DriverInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; DriverInfo->Header.Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; - DriverInfo->Header.Length = (UINT16) (sizeof (MEMORY_PROFILE_DRIVER_INFO) + PdbOccupiedSize); - DriverInfo->Header.Revision = MEMORY_PROFILE_DRIVER_INFO_REVISION; + DriverInfo->Header.Length = (UINT16)(sizeof (MEMORY_PROFILE_DRIVER_INFO) + PdbOccupiedSize); + DriverInfo->Header.Revision = MEMORY_PROFILE_DRIVER_INFO_REVISION; if (FileName != NULL) { CopyMem (&DriverInfo->FileName, FileName, sizeof (EFI_GUID)); } - DriverInfo->ImageBase = ImageBase; - DriverInfo->ImageSize = ImageSize; - DriverInfo->EntryPoint = EntryPoint; + + DriverInfo->ImageBase = ImageBase; + DriverInfo->ImageSize = ImageSize; + DriverInfo->EntryPoint = EntryPoint; DriverInfo->ImageSubsystem = ImageSubsystem; if ((EntryPoint != 0) && ((EntryPoint < ImageBase) || (EntryPoint >= (ImageBase + ImageSize)))) { // // If the EntryPoint is not in the range of image buffer, it should come from emulation environment. // So patch ImageBuffer here to align the EntryPoint. // - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageBase, &EntryPointInImage); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageBase, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverInfo->ImageBase = ImageBase + EntryPoint - (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; + DriverInfo->ImageBase = ImageBase + EntryPoint - (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; } - DriverInfo->FileType = FileType; - DriverInfoData->AllocInfoList = (LIST_ENTRY *) (DriverInfoData + 1); + + DriverInfo->FileType = FileType; + DriverInfoData->AllocInfoList = (LIST_ENTRY *)(DriverInfoData + 1); InitializeListHead (DriverInfoData->AllocInfoList); - DriverInfo->CurrentUsage = 0; - DriverInfo->PeakUsage = 0; + DriverInfo->CurrentUsage = 0; + DriverInfo->PeakUsage = 0; DriverInfo->AllocRecordCount = 0; if (PdbSize != 0) { - DriverInfo->PdbStringOffset = (UINT16) sizeof (MEMORY_PROFILE_DRIVER_INFO); - DriverInfoData->PdbString = (CHAR8 *) (DriverInfoData->AllocInfoList + 1); + DriverInfo->PdbStringOffset = (UINT16)sizeof (MEMORY_PROFILE_DRIVER_INFO); + DriverInfoData->PdbString = (CHAR8 *)(DriverInfoData->AllocInfoList + 1); CopyMem (DriverInfoData->PdbString, PdbString, PdbSize); } else { DriverInfo->PdbStringOffset = 0; - DriverInfoData->PdbString = NULL; + DriverInfoData->PdbString = NULL; } InsertTailList (ContextData->DriverInfoList, &DriverInfoData->Link); - ContextData->Context.ImageCount ++; + ContextData->Context.ImageCount++; ContextData->Context.TotalImageSize += DriverInfo->ImageSize; return DriverInfoData; @@ -465,13 +467,13 @@ BuildDriverInfo ( **/ BOOLEAN NeedRecordThisDriver ( - IN EFI_DEVICE_PATH_PROTOCOL *DriverFilePath + IN EFI_DEVICE_PATH_PROTOCOL *DriverFilePath ) { - EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; - EFI_DEVICE_PATH_PROTOCOL *DevicePathInstance; - UINTN DevicePathSize; - UINTN FilePathSize; + EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePathInstance; + UINTN DevicePathSize; + UINTN FilePathSize; if (!IsDevicePathValid (mMemoryProfileDriverPath, mMemoryProfileDriverPathSize)) { // @@ -483,7 +485,7 @@ NeedRecordThisDriver ( // // Record FilePath without END node. // - FilePathSize = GetDevicePathSize (DriverFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL); + FilePathSize = GetDevicePathSize (DriverFilePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); DevicePathInstance = mMemoryProfileDriverPath; do { @@ -500,14 +502,15 @@ NeedRecordThisDriver ( // DevicePathSize = (UINTN)TmpDevicePath - (UINTN)DevicePathInstance; if ((FilePathSize == DevicePathSize) && - (CompareMem (DriverFilePath, DevicePathInstance, DevicePathSize) == 0)) { + (CompareMem (DriverFilePath, DevicePathInstance, DevicePathSize) == 0)) + { return TRUE; } // // Get next instance. // - DevicePathInstance = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)DevicePathInstance + DevicePathSize + DevicePathNodeLength(TmpDevicePath)); + DevicePathInstance = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)DevicePathInstance + DevicePathSize + DevicePathNodeLength (TmpDevicePath)); } while (DevicePathSubType (TmpDevicePath) != END_ENTIRE_DEVICE_PATH_SUBTYPE); return FALSE; @@ -525,22 +528,22 @@ NeedRecordThisDriver ( **/ BOOLEAN RegisterDxeCore ( - IN VOID *HobStart, - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData + IN VOID *HobStart, + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData ) { - EFI_PEI_HOB_POINTERS DxeCoreHob; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - PHYSICAL_ADDRESS ImageBase; - UINT8 TempBuffer[sizeof(MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof(EFI_DEVICE_PATH_PROTOCOL)]; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + EFI_PEI_HOB_POINTERS DxeCoreHob; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + PHYSICAL_ADDRESS ImageBase; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; ASSERT (ContextData != NULL); // // Searching for image hob // - DxeCoreHob.Raw = HobStart; + DxeCoreHob.Raw = HobStart; while ((DxeCoreHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, DxeCoreHob.Raw)) != NULL) { if (CompareGuid (&DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.Name, &gEfiHobMemoryAllocModuleGuid)) { // @@ -548,26 +551,28 @@ RegisterDxeCore ( // break; } + DxeCoreHob.Raw = GET_NEXT_HOB (DxeCoreHob); } + ASSERT (DxeCoreHob.Raw != NULL); - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) TempBuffer; + FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; EfiInitializeFwVolDevicepathNode (FilePath, &DxeCoreHob.MemoryAllocationModule->ModuleName); SetDevicePathEndNode (FilePath + 1); - if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *) FilePath)) { + if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *)FilePath)) { return FALSE; } - ImageBase = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress; + ImageBase = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress; DriverInfoData = BuildDriverInfo ( ContextData, &DxeCoreHob.MemoryAllocationModule->ModuleName, ImageBase, DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength, DxeCoreHob.MemoryAllocationModule->EntryPoint, - InternalPeCoffGetSubsystem ((VOID *) (UINTN) ImageBase), + InternalPeCoffGetSubsystem ((VOID *)(UINTN)ImageBase), EFI_FV_FILETYPE_DXE_CORE ); if (DriverInfoData == NULL) { @@ -585,10 +590,10 @@ RegisterDxeCore ( **/ VOID MemoryProfileInit ( - IN VOID *HobStart + IN VOID *HobStart ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; if (!IS_UEFI_MEMORY_PROFILE_ENABLED) { return; @@ -605,9 +610,10 @@ MemoryProfileInit ( } else { mMemoryProfileRecordingEnable = MEMORY_PROFILE_RECORDING_ENABLE; } + mMemoryProfileDriverPathSize = PcdGetSize (PcdMemoryProfileDriverPath); - mMemoryProfileDriverPath = AllocateCopyPool (mMemoryProfileDriverPathSize, PcdGetPtr (PcdMemoryProfileDriverPath)); - mMemoryProfileContextPtr = &mMemoryProfileContext; + mMemoryProfileDriverPath = AllocateCopyPool (mMemoryProfileDriverPathSize, PcdGetPtr (PcdMemoryProfileDriverPath)); + mMemoryProfileContextPtr = &mMemoryProfileContext; RegisterDxeCore (HobStart, &mMemoryProfileContext); @@ -623,8 +629,8 @@ MemoryProfileInstallProtocol ( VOID ) { - EFI_HANDLE Handle; - EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_STATUS Status; if (!IS_UEFI_MEMORY_PROFILE_ENABLED) { return; @@ -650,21 +656,22 @@ MemoryProfileInstallProtocol ( **/ EFI_GUID * GetFileNameFromFilePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *ThisFilePath; - EFI_GUID *FileName; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *ThisFilePath; + EFI_GUID *FileName; FileName = NULL; if (FilePath != NULL) { - ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) FilePath; + ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)FilePath; while (!IsDevicePathEnd (ThisFilePath)) { FileName = EfiGetNameGuidFromFwVolDevicePathNode (ThisFilePath); if (FileName != NULL) { break; } - ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) NextDevicePathNode (ThisFilePath); + + ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)NextDevicePathNode (ThisFilePath); } } @@ -689,8 +696,8 @@ RegisterMemoryProfileImage ( IN EFI_FV_FILETYPE FileType ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; if (!IS_UEFI_MEMORY_PROFILE_ENABLED) { return EFI_UNSUPPORTED; @@ -733,21 +740,22 @@ RegisterMemoryProfileImage ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * GetMemoryProfileDriverInfoByFileNameAndAddress ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS Address + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS Address ) { - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - LIST_ENTRY *DriverLink; - LIST_ENTRY *DriverInfoList; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + LIST_ENTRY *DriverLink; + LIST_ENTRY *DriverInfoList; DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -757,7 +765,8 @@ GetMemoryProfileDriverInfoByFileNameAndAddress ( DriverInfo = &DriverInfoData->DriverInfo; if ((CompareGuid (&DriverInfo->FileName, FileName)) && (Address >= DriverInfo->ImageBase) && - (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) { + (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) + { return DriverInfoData; } } @@ -777,20 +786,21 @@ GetMemoryProfileDriverInfoByFileNameAndAddress ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * GetMemoryProfileDriverInfoFromAddress ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN PHYSICAL_ADDRESS Address + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN PHYSICAL_ADDRESS Address ) { - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - LIST_ENTRY *DriverLink; - LIST_ENTRY *DriverInfoList; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + LIST_ENTRY *DriverLink; + LIST_ENTRY *DriverInfoList; DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -799,7 +809,8 @@ GetMemoryProfileDriverInfoFromAddress ( ); DriverInfo = &DriverInfoData->DriverInfo; if ((Address >= DriverInfo->ImageBase) && - (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) { + (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) + { return DriverInfoData; } } @@ -820,15 +831,15 @@ GetMemoryProfileDriverInfoFromAddress ( **/ EFI_STATUS UnregisterMemoryProfileImage ( - IN LOADED_IMAGE_PRIVATE_DATA *DriverEntry + IN LOADED_IMAGE_PRIVATE_DATA *DriverEntry ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - EFI_GUID *FileName; - PHYSICAL_ADDRESS ImageAddress; - VOID *EntryPointInImage; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + EFI_GUID *FileName; + PHYSICAL_ADDRESS ImageAddress; + VOID *EntryPointInImage; if (!IS_UEFI_MEMORY_PROFILE_ENABLED) { return EFI_UNSUPPORTED; @@ -844,23 +855,26 @@ UnregisterMemoryProfileImage ( } DriverInfoData = NULL; - FileName = GetFileNameFromFilePath (DriverEntry->Info.FilePath); - ImageAddress = DriverEntry->ImageContext.ImageAddress; + FileName = GetFileNameFromFilePath (DriverEntry->Info.FilePath); + ImageAddress = DriverEntry->ImageContext.ImageAddress; if ((DriverEntry->ImageContext.EntryPoint < ImageAddress) || (DriverEntry->ImageContext.EntryPoint >= (ImageAddress + DriverEntry->ImageContext.ImageSize))) { // // If the EntryPoint is not in the range of image buffer, it should come from emulation environment. // So patch ImageAddress here to align the EntryPoint. // - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageAddress, &EntryPointInImage); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageAddress, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - ImageAddress = ImageAddress + (UINTN) DriverEntry->ImageContext.EntryPoint - (UINTN) EntryPointInImage; + ImageAddress = ImageAddress + (UINTN)DriverEntry->ImageContext.EntryPoint - (UINTN)EntryPointInImage; } + if (FileName != NULL) { DriverInfoData = GetMemoryProfileDriverInfoByFileNameAndAddress (ContextData, FileName, ImageAddress); } + if (DriverInfoData == NULL) { DriverInfoData = GetMemoryProfileDriverInfoFromAddress (ContextData, ImageAddress); } + if (DriverInfoData == NULL) { return EFI_NOT_FOUND; } @@ -868,11 +882,11 @@ UnregisterMemoryProfileImage ( ContextData->Context.TotalImageSize -= DriverInfoData->DriverInfo.ImageSize; // Keep the ImageBase for RVA calculation in Application. - //DriverInfoData->DriverInfo.ImageBase = 0; + // DriverInfoData->DriverInfo.ImageBase = 0; DriverInfoData->DriverInfo.ImageSize = 0; if (DriverInfoData->DriverInfo.PeakUsage == 0) { - ContextData->Context.ImageCount --; + ContextData->Context.ImageCount--; RemoveEntryList (&DriverInfoData->Link); // // Use CoreInternalFreePool() that will not update profile for this FreePool action. @@ -897,14 +911,14 @@ UnregisterMemoryProfileImage ( **/ BOOLEAN CoreNeedRecordProfile ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - UINT64 TestBit; + UINT64 TestBit; - if ((UINT32) MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { + if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { TestBit = BIT63; - } else if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { + } else if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { TestBit = BIT62; } else { TestBit = LShiftU64 (1, MemoryType); @@ -930,12 +944,12 @@ CoreNeedRecordProfile ( **/ UINTN GetProfileMemoryIndex ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - if ((UINT32) MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { + if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { return EfiMaxMemoryType; - } else if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { + } else if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { return EfiMaxMemoryType + 1; } else { return MemoryType; @@ -968,17 +982,17 @@ CoreUpdateProfileAllocate ( IN CHAR8 *ActionString OPTIONAL ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - UINTN ProfileMemoryIndex; - MEMORY_PROFILE_ACTION BasicAction; - UINTN ActionStringSize; - UINTN ActionStringOccupiedSize; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + UINTN ProfileMemoryIndex; + MEMORY_PROFILE_ACTION BasicAction; + UINTN ActionStringSize; + UINTN ActionStringOccupiedSize; BasicAction = Action & MEMORY_PROFILE_ACTION_BASIC_MASK; @@ -992,10 +1006,10 @@ CoreUpdateProfileAllocate ( return EFI_UNSUPPORTED; } - ActionStringSize = 0; + ActionStringSize = 0; ActionStringOccupiedSize = 0; if (ActionString != NULL) { - ActionStringSize = AsciiStrSize (ActionString); + ActionStringSize = AsciiStrSize (ActionString); ActionStringOccupiedSize = GET_OCCUPIED_SIZE (ActionStringSize, sizeof (UINT64)); } @@ -1003,48 +1017,49 @@ CoreUpdateProfileAllocate ( // Use CoreInternalAllocatePool() that will not update profile for this AllocatePool action. // AllocInfoData = NULL; - Status = CoreInternalAllocatePool ( - EfiBootServicesData, - sizeof (*AllocInfoData) + ActionStringSize, - (VOID **) &AllocInfoData - ); + Status = CoreInternalAllocatePool ( + EfiBootServicesData, + sizeof (*AllocInfoData) + ActionStringSize, + (VOID **)&AllocInfoData + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + ASSERT (AllocInfoData != NULL); // // Only update SequenceCount if and only if it is basic action. // if (Action == BasicAction) { - ContextData->Context.SequenceCount ++; + ContextData->Context.SequenceCount++; } - AllocInfo = &AllocInfoData->AllocInfo; - AllocInfoData->Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; - AllocInfo->Header.Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; - AllocInfo->Header.Length = (UINT16) (sizeof (MEMORY_PROFILE_ALLOC_INFO) + ActionStringOccupiedSize); - AllocInfo->Header.Revision = MEMORY_PROFILE_ALLOC_INFO_REVISION; - AllocInfo->CallerAddress = CallerAddress; - AllocInfo->SequenceId = ContextData->Context.SequenceCount; - AllocInfo->Action = Action; - AllocInfo->MemoryType = MemoryType; - AllocInfo->Buffer = (PHYSICAL_ADDRESS) (UINTN) Buffer; - AllocInfo->Size = Size; + AllocInfo = &AllocInfoData->AllocInfo; + AllocInfoData->Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; + AllocInfo->Header.Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; + AllocInfo->Header.Length = (UINT16)(sizeof (MEMORY_PROFILE_ALLOC_INFO) + ActionStringOccupiedSize); + AllocInfo->Header.Revision = MEMORY_PROFILE_ALLOC_INFO_REVISION; + AllocInfo->CallerAddress = CallerAddress; + AllocInfo->SequenceId = ContextData->Context.SequenceCount; + AllocInfo->Action = Action; + AllocInfo->MemoryType = MemoryType; + AllocInfo->Buffer = (PHYSICAL_ADDRESS)(UINTN)Buffer; + AllocInfo->Size = Size; if (ActionString != NULL) { - AllocInfo->ActionStringOffset = (UINT16) sizeof (MEMORY_PROFILE_ALLOC_INFO); - AllocInfoData->ActionString = (CHAR8 *) (AllocInfoData + 1); + AllocInfo->ActionStringOffset = (UINT16)sizeof (MEMORY_PROFILE_ALLOC_INFO); + AllocInfoData->ActionString = (CHAR8 *)(AllocInfoData + 1); CopyMem (AllocInfoData->ActionString, ActionString, ActionStringSize); } else { AllocInfo->ActionStringOffset = 0; - AllocInfoData->ActionString = NULL; + AllocInfoData->ActionString = NULL; } InsertTailList (DriverInfoData->AllocInfoList, &AllocInfoData->Link); - Context = &ContextData->Context; + Context = &ContextData->Context; DriverInfo = &DriverInfoData->DriverInfo; - DriverInfo->AllocRecordCount ++; + DriverInfo->AllocRecordCount++; // // Update summary if and only if it is basic action. @@ -1056,6 +1071,7 @@ CoreUpdateProfileAllocate ( if (DriverInfo->PeakUsage < DriverInfo->CurrentUsage) { DriverInfo->PeakUsage = DriverInfo->CurrentUsage; } + DriverInfo->CurrentUsageByType[ProfileMemoryIndex] += Size; if (DriverInfo->PeakUsageByType[ProfileMemoryIndex] < DriverInfo->CurrentUsageByType[ProfileMemoryIndex]) { DriverInfo->PeakUsageByType[ProfileMemoryIndex] = DriverInfo->CurrentUsageByType[ProfileMemoryIndex]; @@ -1065,6 +1081,7 @@ CoreUpdateProfileAllocate ( if (Context->PeakTotalUsage < Context->CurrentTotalUsage) { Context->PeakTotalUsage = Context->CurrentTotalUsage; } + Context->CurrentTotalUsageByType[ProfileMemoryIndex] += Size; if (Context->PeakTotalUsageByType[ProfileMemoryIndex] < Context->CurrentTotalUsageByType[ProfileMemoryIndex]) { Context->PeakTotalUsageByType[ProfileMemoryIndex] = Context->CurrentTotalUsageByType[ProfileMemoryIndex]; @@ -1087,22 +1104,23 @@ CoreUpdateProfileAllocate ( **/ MEMORY_PROFILE_ALLOC_INFO_DATA * GetMemoryProfileAllocInfoFromAddress ( - IN MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData, - IN MEMORY_PROFILE_ACTION BasicAction, - IN UINTN Size, - IN VOID *Buffer + IN MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData, + IN MEMORY_PROFILE_ACTION BasicAction, + IN UINTN Size, + IN VOID *Buffer ) { - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1113,17 +1131,21 @@ GetMemoryProfileAllocInfoFromAddress ( if ((AllocInfo->Action & MEMORY_PROFILE_ACTION_BASIC_MASK) != BasicAction) { continue; } + switch (BasicAction) { case MemoryProfileActionAllocatePages: - if ((AllocInfo->Buffer <= (PHYSICAL_ADDRESS) (UINTN) Buffer) && - ((AllocInfo->Buffer + AllocInfo->Size) >= ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size))) { + if ((AllocInfo->Buffer <= (PHYSICAL_ADDRESS)(UINTN)Buffer) && + ((AllocInfo->Buffer + AllocInfo->Size) >= ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size))) + { return AllocInfoData; } + break; case MemoryProfileActionAllocatePool: - if (AllocInfo->Buffer == (PHYSICAL_ADDRESS) (UINTN) Buffer) { + if (AllocInfo->Buffer == (PHYSICAL_ADDRESS)(UINTN)Buffer) { return AllocInfoData; } + break; default: ASSERT (FALSE); @@ -1186,7 +1208,7 @@ CoreUpdateProfileFree ( // Need use do-while loop to find all possible records, // because one address might be recorded multiple times. // - Found = FALSE; + Found = FALSE; AllocInfoData = NULL; do { if (DriverInfoData != NULL) { @@ -1203,6 +1225,7 @@ CoreUpdateProfileFree ( break; } } + if (AllocInfoData == NULL) { // // Legal case, because driver A might free memory allocated by driver B, by some protocol. @@ -1211,7 +1234,8 @@ CoreUpdateProfileFree ( for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { ThisDriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -1230,6 +1254,7 @@ CoreUpdateProfileFree ( AllocInfoData = NULL; break; } + if (AllocInfoData != NULL) { DriverInfoData = ThisDriverInfoData; break; @@ -1254,44 +1279,45 @@ CoreUpdateProfileFree ( Found = TRUE; - Context = &ContextData->Context; + Context = &ContextData->Context; DriverInfo = &DriverInfoData->DriverInfo; - AllocInfo = &AllocInfoData->AllocInfo; + AllocInfo = &AllocInfoData->AllocInfo; - DriverInfo->AllocRecordCount --; + DriverInfo->AllocRecordCount--; // // Update summary if and only if it is basic action. // if (AllocInfo->Action == (AllocInfo->Action & MEMORY_PROFILE_ACTION_BASIC_MASK)) { ProfileMemoryIndex = GetProfileMemoryIndex (AllocInfo->MemoryType); - Context->CurrentTotalUsage -= AllocInfo->Size; + Context->CurrentTotalUsage -= AllocInfo->Size; Context->CurrentTotalUsageByType[ProfileMemoryIndex] -= AllocInfo->Size; - DriverInfo->CurrentUsage -= AllocInfo->Size; + DriverInfo->CurrentUsage -= AllocInfo->Size; DriverInfo->CurrentUsageByType[ProfileMemoryIndex] -= AllocInfo->Size; } RemoveEntryList (&AllocInfoData->Link); if (BasicAction == MemoryProfileActionFreePages) { - if (AllocInfo->Buffer != (PHYSICAL_ADDRESS) (UINTN) Buffer) { + if (AllocInfo->Buffer != (PHYSICAL_ADDRESS)(UINTN)Buffer) { CoreUpdateProfileAllocate ( AllocInfo->CallerAddress, AllocInfo->Action, AllocInfo->MemoryType, - (UINTN) ((PHYSICAL_ADDRESS) (UINTN) Buffer - AllocInfo->Buffer), - (VOID *) (UINTN) AllocInfo->Buffer, + (UINTN)((PHYSICAL_ADDRESS)(UINTN)Buffer - AllocInfo->Buffer), + (VOID *)(UINTN)AllocInfo->Buffer, AllocInfoData->ActionString ); } - if (AllocInfo->Buffer + AllocInfo->Size != ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size)) { + + if (AllocInfo->Buffer + AllocInfo->Size != ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size)) { CoreUpdateProfileAllocate ( AllocInfo->CallerAddress, AllocInfo->Action, AllocInfo->MemoryType, - (UINTN) ((AllocInfo->Buffer + AllocInfo->Size) - ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size)), - (VOID *) ((UINTN) Buffer + Size), + (UINTN)((AllocInfo->Buffer + AllocInfo->Size) - ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size)), + (VOID *)((UINTN)Buffer + Size), AllocInfoData->ActionString ); } @@ -1337,9 +1363,9 @@ CoreUpdateProfile ( IN CHAR8 *ActionString OPTIONAL ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_ACTION BasicAction; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_ACTION BasicAction; if (!IS_UEFI_MEMORY_PROFILE_ENABLED) { return EFI_UNSUPPORTED; @@ -1394,6 +1420,7 @@ CoreUpdateProfile ( Status = EFI_UNSUPPORTED; break; } + CoreReleaseMemoryProfileLock (); return Status; @@ -1412,15 +1439,14 @@ MemoryProfileGetDataSize ( VOID ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - LIST_ENTRY *DriverInfoList; - LIST_ENTRY *DriverLink; - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - UINTN TotalSize; - + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *DriverInfoList; + LIST_ENTRY *DriverLink; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + UINTN TotalSize; ContextData = GetMemoryProfileContext (); if (ContextData == NULL) { @@ -1432,7 +1458,8 @@ MemoryProfileGetDataSize ( DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -1444,7 +1471,8 @@ MemoryProfileGetDataSize ( AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1466,35 +1494,36 @@ MemoryProfileGetDataSize ( **/ VOID MemoryProfileCopyData ( - IN VOID *ProfileBuffer + IN VOID *ProfileBuffer ) { - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - LIST_ENTRY *DriverInfoList; - LIST_ENTRY *DriverLink; - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - UINTN PdbSize; - UINTN ActionStringSize; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *DriverInfoList; + LIST_ENTRY *DriverLink; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + UINTN PdbSize; + UINTN ActionStringSize; ContextData = GetMemoryProfileContext (); if (ContextData == NULL) { - return ; + return; } Context = ProfileBuffer; CopyMem (Context, &ContextData->Context, sizeof (MEMORY_PROFILE_CONTEXT)); - DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *) (Context + 1); + DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *)(Context + 1); DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -1504,14 +1533,16 @@ MemoryProfileCopyData ( CopyMem (DriverInfo, &DriverInfoData->DriverInfo, sizeof (MEMORY_PROFILE_DRIVER_INFO)); if (DriverInfo->PdbStringOffset != 0) { PdbSize = AsciiStrSize (DriverInfoData->PdbString); - CopyMem ((VOID *) ((UINTN) DriverInfo + DriverInfo->PdbStringOffset), DriverInfoData->PdbString, PdbSize); + CopyMem ((VOID *)((UINTN)DriverInfo + DriverInfo->PdbStringOffset), DriverInfoData->PdbString, PdbSize); } - AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) DriverInfo + DriverInfo->Header.Length); + + AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)DriverInfo + DriverInfo->Header.Length); AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1521,12 +1552,13 @@ MemoryProfileCopyData ( CopyMem (AllocInfo, &AllocInfoData->AllocInfo, sizeof (MEMORY_PROFILE_ALLOC_INFO)); if (AllocInfo->ActionStringOffset != 0) { ActionStringSize = AsciiStrSize (AllocInfoData->ActionString); - CopyMem ((VOID *) ((UINTN) AllocInfo + AllocInfo->ActionStringOffset), AllocInfoData->ActionString, ActionStringSize); + CopyMem ((VOID *)((UINTN)AllocInfo + AllocInfo->ActionStringOffset), AllocInfoData->ActionString, ActionStringSize); } - AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *) ((UINTN) AllocInfo + AllocInfo->Header.Length); + + AllocInfo = (MEMORY_PROFILE_ALLOC_INFO *)((UINTN)AllocInfo + AllocInfo->Header.Length); } - DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *) AllocInfo; + DriverInfo = (MEMORY_PROFILE_DRIVER_INFO *)AllocInfo; } } @@ -1549,25 +1581,25 @@ EFIAPI ProfileProtocolGetData ( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, IN OUT UINT64 *ProfileSize, - OUT VOID *ProfileBuffer + OUT VOID *ProfileBuffer ) { - UINTN Size; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN MemoryProfileGettingStatus; + UINTN Size; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN MemoryProfileGettingStatus; ContextData = GetMemoryProfileContext (); if (ContextData == NULL) { return EFI_UNSUPPORTED; } - MemoryProfileGettingStatus = mMemoryProfileGettingStatus; + MemoryProfileGettingStatus = mMemoryProfileGettingStatus; mMemoryProfileGettingStatus = TRUE; Size = MemoryProfileGetDataSize (); if (*ProfileSize < Size) { - *ProfileSize = Size; + *ProfileSize = Size; mMemoryProfileGettingStatus = MemoryProfileGettingStatus; return EFI_BUFFER_TOO_SMALL; } @@ -1604,18 +1636,18 @@ ProfileProtocolRegisterImage ( IN EFI_FV_FILETYPE FileType ) { - EFI_STATUS Status; - LOADED_IMAGE_PRIVATE_DATA DriverEntry; - VOID *EntryPointInImage; + EFI_STATUS Status; + LOADED_IMAGE_PRIVATE_DATA DriverEntry; + VOID *EntryPointInImage; ZeroMem (&DriverEntry, sizeof (DriverEntry)); - DriverEntry.Info.FilePath = FilePath; + DriverEntry.Info.FilePath = FilePath; DriverEntry.ImageContext.ImageAddress = ImageBase; - DriverEntry.ImageContext.ImageSize = ImageSize; - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageBase, &EntryPointInImage); + DriverEntry.ImageContext.ImageSize = ImageSize; + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageBase, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverEntry.ImageContext.EntryPoint = (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; - DriverEntry.ImageContext.ImageType = InternalPeCoffGetSubsystem ((VOID *) (UINTN) ImageBase); + DriverEntry.ImageContext.EntryPoint = (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; + DriverEntry.ImageContext.ImageType = InternalPeCoffGetSubsystem ((VOID *)(UINTN)ImageBase); return RegisterMemoryProfileImage (&DriverEntry, FileType); } @@ -1643,17 +1675,17 @@ ProfileProtocolUnregisterImage ( IN UINT64 ImageSize ) { - EFI_STATUS Status; - LOADED_IMAGE_PRIVATE_DATA DriverEntry; - VOID *EntryPointInImage; + EFI_STATUS Status; + LOADED_IMAGE_PRIVATE_DATA DriverEntry; + VOID *EntryPointInImage; ZeroMem (&DriverEntry, sizeof (DriverEntry)); - DriverEntry.Info.FilePath = FilePath; + DriverEntry.Info.FilePath = FilePath; DriverEntry.ImageContext.ImageAddress = ImageBase; - DriverEntry.ImageContext.ImageSize = ImageSize; - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageBase, &EntryPointInImage); + DriverEntry.ImageContext.ImageSize = ImageSize; + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageBase, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverEntry.ImageContext.EntryPoint = (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; + DriverEntry.ImageContext.EntryPoint = (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; return UnregisterMemoryProfileImage (&DriverEntry); } @@ -1672,11 +1704,11 @@ ProfileProtocolUnregisterImage ( EFI_STATUS EFIAPI ProfileProtocolGetRecordingState ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - OUT BOOLEAN *RecordingState + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + OUT BOOLEAN *RecordingState ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; ContextData = GetMemoryProfileContext (); if (ContextData == NULL) { @@ -1686,6 +1718,7 @@ ProfileProtocolGetRecordingState ( if (RecordingState == NULL) { return EFI_INVALID_PARAMETER; } + *RecordingState = mMemoryProfileRecordingEnable; return EFI_SUCCESS; } @@ -1703,11 +1736,11 @@ ProfileProtocolGetRecordingState ( EFI_STATUS EFIAPI ProfileProtocolSetRecordingState ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN BOOLEAN RecordingState + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN BOOLEAN RecordingState ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; ContextData = GetMemoryProfileContext (); if (ContextData == NULL) { @@ -1744,13 +1777,13 @@ ProfileProtocolSetRecordingState ( EFI_STATUS EFIAPI ProfileProtocolRecord ( - IN EDKII_MEMORY_PROFILE_PROTOCOL *This, - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN EDKII_MEMORY_PROFILE_PROTOCOL *This, + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { return CoreUpdateProfile (CallerAddress, Action, MemoryType, Size, Buffer, ActionString); diff --git a/MdeModulePkg/Core/Dxe/Mem/Page.c b/MdeModulePkg/Core/Dxe/Mem/Page.c index 731bf08bc9..47d4c5d92e 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Page.c +++ b/MdeModulePkg/Core/Dxe/Mem/Page.c @@ -14,38 +14,38 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Entry for tracking the memory regions for each memory type to coalesce similar memory types // typedef struct { - EFI_PHYSICAL_ADDRESS BaseAddress; - EFI_PHYSICAL_ADDRESS MaximumAddress; - UINT64 CurrentNumberOfPages; - UINT64 NumberOfPages; - UINTN InformationIndex; - BOOLEAN Special; - BOOLEAN Runtime; + EFI_PHYSICAL_ADDRESS BaseAddress; + EFI_PHYSICAL_ADDRESS MaximumAddress; + UINT64 CurrentNumberOfPages; + UINT64 NumberOfPages; + UINTN InformationIndex; + BOOLEAN Special; + BOOLEAN Runtime; } EFI_MEMORY_TYPE_STATISTICS; // // MemoryMap - The current memory map // -UINTN mMemoryMapKey = 0; +UINTN mMemoryMapKey = 0; -#define MAX_MAP_DEPTH 6 +#define MAX_MAP_DEPTH 6 /// /// mMapDepth - depth of new descriptor stack /// -UINTN mMapDepth = 0; +UINTN mMapDepth = 0; /// /// mMapStack - space to use as temp storage to build new map descriptors /// -MEMORY_MAP mMapStack[MAX_MAP_DEPTH]; -UINTN mFreeMapStack = 0; +MEMORY_MAP mMapStack[MAX_MAP_DEPTH]; +UINTN mFreeMapStack = 0; /// /// This list maintain the free memory map list /// -LIST_ENTRY mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList); -BOOLEAN mMemoryTypeInformationInitialized = FALSE; +LIST_ENTRY mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList); +BOOLEAN mMemoryTypeInformationInitialized = FALSE; -EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = { +EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = { { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, TRUE, FALSE }, // EfiReservedMemoryType { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }, // EfiLoaderCode { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE }, // EfiLoaderData @@ -64,10 +64,10 @@ EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics[EfiMaxMemoryType + 1] = { { 0, MAX_ALLOC_ADDRESS, 0, 0, EfiMaxMemoryType, FALSE, FALSE } // EfiMaxMemoryType }; -EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = MAX_ALLOC_ADDRESS; -EFI_PHYSICAL_ADDRESS mDefaultBaseAddress = MAX_ALLOC_ADDRESS; +EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress = MAX_ALLOC_ADDRESS; +EFI_PHYSICAL_ADDRESS mDefaultBaseAddress = MAX_ALLOC_ADDRESS; -EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = { +EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = { { EfiReservedMemoryType, 0 }, { EfiLoaderCode, 0 }, { EfiLoaderData, 0 }, @@ -90,7 +90,7 @@ EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation[EfiMaxMemoryType + 1] = { // and ready to load the module in to specified address.or else, the memory is not ready and module will be loaded at a // address assigned by DXE core. // -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN gLoadFixedAddressCodeMemoryReady = FALSE; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN gLoadFixedAddressCodeMemoryReady = FALSE; /** Enter critical section by gaining lock on gMemoryLock. @@ -104,8 +104,6 @@ CoreAcquireMemoryLock ( CoreAcquireLock (&gMemoryLock); } - - /** Exit critical section by releasing lock on gMemoryLock. @@ -118,9 +116,6 @@ CoreReleaseMemoryLock ( CoreReleaseLock (&gMemoryLock); } - - - /** Internal function. Removes a descriptor entry. @@ -129,7 +124,7 @@ CoreReleaseMemoryLock ( **/ VOID RemoveMemoryMapEntry ( - IN OUT MEMORY_MAP *Entry + IN OUT MEMORY_MAP *Entry ) { RemoveEntryList (&Entry->Link); @@ -157,17 +152,17 @@ RemoveMemoryMapEntry ( **/ VOID CoreAddRange ( - IN EFI_MEMORY_TYPE Type, - IN EFI_PHYSICAL_ADDRESS Start, - IN EFI_PHYSICAL_ADDRESS End, - IN UINT64 Attribute + IN EFI_MEMORY_TYPE Type, + IN EFI_PHYSICAL_ADDRESS Start, + IN EFI_PHYSICAL_ADDRESS End, + IN UINT64 Attribute ) { - LIST_ENTRY *Link; - MEMORY_MAP *Entry; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; ASSERT ((Start & EFI_PAGE_MASK) == 0); - ASSERT (End > Start) ; + ASSERT (End > Start); ASSERT_LOCKED (&gMemoryLock); @@ -182,7 +177,7 @@ CoreAddRange ( // at address 0, then do not zero the page at address 0 because the page is being // used for other purposes. // - if (Type == EfiConventionalMemory && Start == 0 && (End >= EFI_PAGE_SIZE - 1)) { + if ((Type == EfiConventionalMemory) && (Start == 0) && (End >= EFI_PAGE_SIZE - 1)) { if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT0) == 0) { SetMem ((VOID *)(UINTN)Start, EFI_PAGE_SIZE, 0); } @@ -226,12 +221,9 @@ CoreAddRange ( } if (Entry->End + 1 == Start) { - Start = Entry->Start; RemoveMemoryMapEntry (Entry); - } else if (Entry->Start == End + 1) { - End = Entry->End; RemoveMemoryMapEntry (Entry); } @@ -241,19 +233,19 @@ CoreAddRange ( // Add descriptor // - mMapStack[mMapDepth].Signature = MEMORY_MAP_SIGNATURE; - mMapStack[mMapDepth].FromPages = FALSE; - mMapStack[mMapDepth].Type = Type; - mMapStack[mMapDepth].Start = Start; - mMapStack[mMapDepth].End = End; - mMapStack[mMapDepth].VirtualStart = 0; - mMapStack[mMapDepth].Attribute = Attribute; + mMapStack[mMapDepth].Signature = MEMORY_MAP_SIGNATURE; + mMapStack[mMapDepth].FromPages = FALSE; + mMapStack[mMapDepth].Type = Type; + mMapStack[mMapDepth].Start = Start; + mMapStack[mMapDepth].End = End; + mMapStack[mMapDepth].VirtualStart = 0; + mMapStack[mMapDepth].Attribute = Attribute; InsertTailList (&gMemoryMap, &mMapStack[mMapDepth].Link); mMapDepth += 1; ASSERT (mMapDepth < MAX_MAP_DEPTH); - return ; + return; } /** @@ -274,9 +266,9 @@ AllocateMemoryMapEntry ( VOID ) { - MEMORY_MAP* FreeDescriptorEntries; - MEMORY_MAP* Entry; - UINTN Index; + MEMORY_MAP *FreeDescriptorEntries; + MEMORY_MAP *Entry; + UINTN Index; if (IsListEmpty (&mFreeMemoryMapEntryList)) { // @@ -292,7 +284,7 @@ AllocateMemoryMapEntry ( // // Enque the free memmory map entries into the list // - for (Index = 0; Index < DEFAULT_PAGE_ALLOCATION_GRANULARITY / sizeof(MEMORY_MAP); Index++) { + for (Index = 0; Index < DEFAULT_PAGE_ALLOCATION_GRANULARITY / sizeof (MEMORY_MAP); Index++) { FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE; InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link); } @@ -300,6 +292,7 @@ AllocateMemoryMapEntry ( return NULL; } } + // // dequeue the first descriptor from the list // @@ -309,7 +302,6 @@ AllocateMemoryMapEntry ( return Entry; } - /** Internal function. Moves any memory descriptors that are on the temporary descriptor stack to heap. @@ -320,9 +312,9 @@ CoreFreeMemoryMapStack ( VOID ) { - MEMORY_MAP *Entry; - MEMORY_MAP *Entry2; - LIST_ENTRY *Link2; + MEMORY_MAP *Entry; + MEMORY_MAP *Entry2; + LIST_ENTRY *Link2; ASSERT_LOCKED (&gMemoryLock); @@ -330,7 +322,7 @@ CoreFreeMemoryMapStack ( // If already freeing the map stack, then return // if (mFreeMapStack != 0) { - return ; + return; } // @@ -352,14 +344,13 @@ CoreFreeMemoryMapStack ( mMapDepth -= 1; if (mMapStack[mMapDepth].Link.ForwardLink != NULL) { - // // Move this entry to general memory // RemoveEntryList (&mMapStack[mMapDepth].Link); mMapStack[mMapDepth].Link.ForwardLink = NULL; - CopyMem (Entry , &mMapStack[mMapDepth], sizeof (MEMORY_MAP)); + CopyMem (Entry, &mMapStack[mMapDepth], sizeof (MEMORY_MAP)); Entry->FromPages = TRUE; // @@ -367,13 +358,12 @@ CoreFreeMemoryMapStack ( // for (Link2 = gMemoryMap.ForwardLink; Link2 != &gMemoryMap; Link2 = Link2->ForwardLink) { Entry2 = CR (Link2, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); - if (Entry2->FromPages && Entry2->Start > Entry->Start) { + if (Entry2->FromPages && (Entry2->Start > Entry->Start)) { break; } } InsertTailList (Link2, &Entry->Link); - } else { // // This item of mMapStack[mMapDepth] has already been dequeued from gMemoryMap list, @@ -395,27 +385,27 @@ PromoteMemoryResource ( VOID ) { - LIST_ENTRY *Link; - EFI_GCD_MAP_ENTRY *Entry; - BOOLEAN Promoted; - EFI_PHYSICAL_ADDRESS StartAddress; - EFI_PHYSICAL_ADDRESS EndAddress; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; + LIST_ENTRY *Link; + EFI_GCD_MAP_ENTRY *Entry; + BOOLEAN Promoted; + EFI_PHYSICAL_ADDRESS StartAddress; + EFI_PHYSICAL_ADDRESS EndAddress; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; DEBUG ((DEBUG_PAGE, "Promote the memory resource\n")); CoreAcquireGcdMemoryLock (); Promoted = FALSE; - Link = mGcdMemorySpaceMap.ForwardLink; + Link = mGcdMemorySpaceMap.ForwardLink; while (Link != &mGcdMemorySpaceMap) { - Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); - if (Entry->GcdMemoryType == EfiGcdMemoryTypeReserved && - Entry->EndAddress < MAX_ALLOC_ADDRESS && - (Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) == - (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)) { + if ((Entry->GcdMemoryType == EfiGcdMemoryTypeReserved) && + (Entry->EndAddress < MAX_ALLOC_ADDRESS) && + ((Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) == + (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED))) + { // // Update the GCD map // @@ -424,9 +414,10 @@ PromoteMemoryResource ( } else { Entry->GcdMemoryType = EfiGcdMemoryTypeSystemMemory; } + Entry->Capabilities |= EFI_MEMORY_TESTED; - Entry->ImageHandle = gDxeCoreImageHandle; - Entry->DeviceHandle = NULL; + Entry->ImageHandle = gDxeCoreImageHandle; + Entry->DeviceHandle = NULL; // // Add to allocable system memory resource @@ -468,6 +459,7 @@ PromoteMemoryResource ( return Promoted; } + /** This function try to allocate Runtime code & Boot time code memory range. If LMFA enabled, 2 patchable PCD PcdLoadFixAddressRuntimeCodePageNumber & PcdLoadFixAddressBootTimeCodePageNumber which are set by tools will record the @@ -479,58 +471,61 @@ CoreLoadingFixedAddressHook ( VOID ) { - UINT32 RuntimeCodePageNumber; - UINT32 BootTimeCodePageNumber; - EFI_PHYSICAL_ADDRESS RuntimeCodeBase; - EFI_PHYSICAL_ADDRESS BootTimeCodeBase; - EFI_STATUS Status; - - // - // Make sure these 2 areas are not initialzied. - // - if (!gLoadFixedAddressCodeMemoryReady) { - RuntimeCodePageNumber = PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber); - BootTimeCodePageNumber= PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber); - RuntimeCodeBase = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - EFI_PAGES_TO_SIZE (RuntimeCodePageNumber)); - BootTimeCodeBase = (EFI_PHYSICAL_ADDRESS)(RuntimeCodeBase - EFI_PAGES_TO_SIZE (BootTimeCodePageNumber)); - // - // Try to allocate runtime memory. - // - Status = CoreAllocatePages ( - AllocateAddress, - EfiRuntimeServicesCode, - RuntimeCodePageNumber, - &RuntimeCodeBase - ); - if (EFI_ERROR(Status)) { - // - // Runtime memory allocation failed - // - return; - } - // - // Try to allocate boot memory. - // - Status = CoreAllocatePages ( - AllocateAddress, - EfiBootServicesCode, - BootTimeCodePageNumber, - &BootTimeCodeBase - ); - if (EFI_ERROR(Status)) { - // - // boot memory allocation failed. Free Runtime code range and will try the allocation again when - // new memory range is installed. - // - CoreFreePages ( - RuntimeCodeBase, - RuntimeCodePageNumber - ); - return; - } - gLoadFixedAddressCodeMemoryReady = TRUE; - } - return; + UINT32 RuntimeCodePageNumber; + UINT32 BootTimeCodePageNumber; + EFI_PHYSICAL_ADDRESS RuntimeCodeBase; + EFI_PHYSICAL_ADDRESS BootTimeCodeBase; + EFI_STATUS Status; + + // + // Make sure these 2 areas are not initialzied. + // + if (!gLoadFixedAddressCodeMemoryReady) { + RuntimeCodePageNumber = PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber); + BootTimeCodePageNumber = PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber); + RuntimeCodeBase = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - EFI_PAGES_TO_SIZE (RuntimeCodePageNumber)); + BootTimeCodeBase = (EFI_PHYSICAL_ADDRESS)(RuntimeCodeBase - EFI_PAGES_TO_SIZE (BootTimeCodePageNumber)); + // + // Try to allocate runtime memory. + // + Status = CoreAllocatePages ( + AllocateAddress, + EfiRuntimeServicesCode, + RuntimeCodePageNumber, + &RuntimeCodeBase + ); + if (EFI_ERROR (Status)) { + // + // Runtime memory allocation failed + // + return; + } + + // + // Try to allocate boot memory. + // + Status = CoreAllocatePages ( + AllocateAddress, + EfiBootServicesCode, + BootTimeCodePageNumber, + &BootTimeCodeBase + ); + if (EFI_ERROR (Status)) { + // + // boot memory allocation failed. Free Runtime code range and will try the allocation again when + // new memory range is installed. + // + CoreFreePages ( + RuntimeCodeBase, + RuntimeCodePageNumber + ); + return; + } + + gLoadFixedAddressCodeMemoryReady = TRUE; + } + + return; } /** @@ -556,32 +551,37 @@ CoreAddMemoryDescriptor ( IN UINT64 Attribute ) { - EFI_PHYSICAL_ADDRESS End; - EFI_STATUS Status; - UINTN Index; - UINTN FreeIndex; + EFI_PHYSICAL_ADDRESS End; + EFI_STATUS Status; + UINTN Index; + UINTN FreeIndex; if ((Start & EFI_PAGE_MASK) != 0) { return; } - if (Type >= EfiMaxMemoryType && Type < MEMORY_TYPE_OEM_RESERVED_MIN) { + if ((Type >= EfiMaxMemoryType) && (Type < MEMORY_TYPE_OEM_RESERVED_MIN)) { return; } + CoreAcquireMemoryLock (); End = Start + LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT) - 1; CoreAddRange (Type, Start, End, Attribute); CoreFreeMemoryMapStack (); CoreReleaseMemoryLock (); - ApplyMemoryProtectionPolicy (EfiMaxMemoryType, Type, Start, - LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT)); + ApplyMemoryProtectionPolicy ( + EfiMaxMemoryType, + Type, + Start, + LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT) + ); // // If Loading Module At Fixed Address feature is enabled. try to allocate memory with Runtime code & Boot time code type // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { - CoreLoadingFixedAddressHook(); + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { + CoreLoadingFixedAddressHook (); } // @@ -591,7 +591,6 @@ CoreAddMemoryDescriptor ( return; } - // // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array // @@ -599,10 +598,11 @@ CoreAddMemoryDescriptor ( // // Make sure the memory type in the gMemoryTypeInformation[] array is valid // - Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type); + Type = (EFI_MEMORY_TYPE)(gMemoryTypeInformation[Index].Type); if ((UINT32)Type > EfiMaxMemoryType) { continue; } + if (gMemoryTypeInformation[Index].NumberOfPages != 0) { // // Allocate pages for the current memory type from the top of available memory @@ -623,7 +623,7 @@ CoreAddMemoryDescriptor ( // // Make sure the memory type in the gMemoryTypeInformation[] array is valid // - Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[FreeIndex].Type); + Type = (EFI_MEMORY_TYPE)(gMemoryTypeInformation[FreeIndex].Type); if ((UINT32)Type > EfiMaxMemoryType) { continue; } @@ -637,6 +637,7 @@ CoreAddMemoryDescriptor ( mMemoryTypeStatistics[Type].MaximumAddress = MAX_ALLOC_ADDRESS; } } + return; } @@ -666,10 +667,11 @@ CoreAddMemoryDescriptor ( // // Make sure the memory type in the gMemoryTypeInformation[] array is valid // - Type = (EFI_MEMORY_TYPE) (gMemoryTypeInformation[Index].Type); + Type = (EFI_MEMORY_TYPE)(gMemoryTypeInformation[Index].Type); if ((UINT32)Type > EfiMaxMemoryType) { continue; } + if (gMemoryTypeInformation[Index].NumberOfPages != 0) { CoreFreePages ( mMemoryTypeStatistics[Type].BaseAddress, @@ -684,12 +686,13 @@ CoreAddMemoryDescriptor ( // If the number of pages reserved for a memory type is 0, then all allocations for that type // should be in the default range. // - for (Type = (EFI_MEMORY_TYPE) 0; Type < EfiMaxMemoryType; Type++) { + for (Type = (EFI_MEMORY_TYPE)0; Type < EfiMaxMemoryType; Type++) { for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) { if (Type == (EFI_MEMORY_TYPE)gMemoryTypeInformation[Index].Type) { mMemoryTypeStatistics[Type].InformationIndex = Index; } } + mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0; if (mMemoryTypeStatistics[Type].MaximumAddress == MAX_ALLOC_ADDRESS) { mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress; @@ -699,7 +702,6 @@ CoreAddMemoryDescriptor ( mMemoryTypeInformationInitialized = TRUE; } - /** Internal function. Converts a memory range to the specified type or attributes. The range must exist in the memory map. Either ChangingType or @@ -730,26 +732,25 @@ CoreConvertPagesEx ( IN UINT64 NewAttributes ) { + UINT64 NumberOfBytes; + UINT64 End; + UINT64 RangeEnd; + UINT64 Attribute; + EFI_MEMORY_TYPE MemType; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; - UINT64 NumberOfBytes; - UINT64 End; - UINT64 RangeEnd; - UINT64 Attribute; - EFI_MEMORY_TYPE MemType; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - - Entry = NULL; + Entry = NULL; NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT); - End = Start + NumberOfBytes - 1; + End = Start + NumberOfBytes - 1; ASSERT (NumberOfPages); ASSERT ((Start & EFI_PAGE_MASK) == 0); - ASSERT (End > Start) ; + ASSERT (End > Start); ASSERT_LOCKED (&gMemoryLock); - ASSERT ( (ChangingType == FALSE) || (ChangingAttributes == FALSE) ); + ASSERT ((ChangingType == FALSE) || (ChangingAttributes == FALSE)); - if (NumberOfPages == 0 || ((Start & EFI_PAGE_MASK) != 0) || (Start >= End)) { + if ((NumberOfPages == 0) || ((Start & EFI_PAGE_MASK) != 0) || (Start >= End)) { return EFI_INVALID_PARAMETER; } @@ -758,14 +759,13 @@ CoreConvertPagesEx ( // while (Start < End) { - // // Find the entry that the covers the range // for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) { Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); - if (Entry->Start <= Start && Entry->End > Start) { + if ((Entry->Start <= Start) && (Entry->End > Start)) { break; } } @@ -786,6 +786,7 @@ CoreConvertPagesEx ( return EFI_NOT_FOUND; } } + // // Convert range to the end, or to the end of the descriptor // if that's all we've got @@ -800,6 +801,7 @@ CoreConvertPagesEx ( if (ChangingType) { DEBUG ((DEBUG_PAGE, "ConvertRange: %lx-%lx to type %d\n", Start, RangeEnd, NewType)); } + if (ChangingAttributes) { DEBUG ((DEBUG_PAGE, "ConvertRange: %lx-%lx to attr %lx\n", Start, RangeEnd, NewAttributes)); } @@ -808,13 +810,14 @@ CoreConvertPagesEx ( // // Debug code - verify conversion is allowed // - if (!(NewType == EfiConventionalMemory ? 1 : 0) ^ (Entry->Type == EfiConventionalMemory ? 1 : 0)) { + if (!((NewType == EfiConventionalMemory) ? 1 : 0) ^ ((Entry->Type == EfiConventionalMemory) ? 1 : 0)) { DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ConvertPages: Incompatible memory types, ")); if (Entry->Type == EfiConventionalMemory) { DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "the pages to free have been freed\n")); } else { DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "the pages to allocate have been allocated\n")); } + return EFI_NOT_FOUND; } @@ -822,8 +825,9 @@ CoreConvertPagesEx ( // Update counters for the number of pages allocated to each memory type // if ((UINT32)Entry->Type < EfiMaxMemoryType) { - if ((Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress && Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress) || - (Start >= mDefaultBaseAddress && Start <= mDefaultMaximumAddress) ) { + if (((Start >= mMemoryTypeStatistics[Entry->Type].BaseAddress) && (Start <= mMemoryTypeStatistics[Entry->Type].MaximumAddress)) || + ((Start >= mDefaultBaseAddress) && (Start <= mDefaultMaximumAddress))) + { if (NumberOfPages > mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages) { mMemoryTypeStatistics[Entry->Type].CurrentNumberOfPages = 0; } else { @@ -833,8 +837,9 @@ CoreConvertPagesEx ( } if ((UINT32)NewType < EfiMaxMemoryType) { - if ((Start >= mMemoryTypeStatistics[NewType].BaseAddress && Start <= mMemoryTypeStatistics[NewType].MaximumAddress) || - (Start >= mDefaultBaseAddress && Start <= mDefaultMaximumAddress) ) { + if (((Start >= mMemoryTypeStatistics[NewType].BaseAddress) && (Start <= mMemoryTypeStatistics[NewType].MaximumAddress)) || + ((Start >= mDefaultBaseAddress) && (Start <= mDefaultMaximumAddress))) + { mMemoryTypeStatistics[NewType].CurrentNumberOfPages += NumberOfPages; if (mMemoryTypeStatistics[NewType].CurrentNumberOfPages > gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages) { gMemoryTypeInformation[mMemoryTypeStatistics[NewType].InformationIndex].NumberOfPages = (UINT32)mMemoryTypeStatistics[NewType].CurrentNumberOfPages; @@ -847,21 +852,16 @@ CoreConvertPagesEx ( // Pull range out of descriptor // if (Entry->Start == Start) { - // // Clip start // Entry->Start = RangeEnd + 1; - } else if (Entry->End == RangeEnd) { - // // Clip end // Entry->End = Start - 1; - } else { - // // Pull it out of the center, clip current // @@ -870,7 +870,7 @@ CoreConvertPagesEx ( // Add a new one // mMapStack[mMapDepth].Signature = MEMORY_MAP_SIGNATURE; - mMapStack[mMapDepth].FromPages = FALSE; + mMapStack[mMapDepth].FromPages = FALSE; mMapStack[mMapDepth].Type = Entry->Type; mMapStack[mMapDepth].Start = RangeEnd+1; mMapStack[mMapDepth].End = Entry->End; @@ -896,10 +896,10 @@ CoreConvertPagesEx ( // if (ChangingType) { Attribute = Entry->Attribute; - MemType = NewType; + MemType = NewType; } else { Attribute = NewAttributes; - MemType = Entry->Type; + MemType = Entry->Type; } // @@ -916,7 +916,8 @@ CoreConvertPagesEx ( // if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) || !ChangingType || - MemType != EfiConventionalMemory) { + (MemType != EfiConventionalMemory)) + { CoreAddRange (MemType, Start, RangeEnd, Attribute); } @@ -928,10 +929,10 @@ CoreConvertPagesEx ( // if (Start == 0) { if (RangeEnd > EFI_PAGE_SIZE) { - DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) EFI_PAGE_SIZE, (UINTN) (RangeEnd - EFI_PAGE_SIZE + 1)); + DEBUG_CLEAR_MEMORY ((VOID *)(UINTN)EFI_PAGE_SIZE, (UINTN)(RangeEnd - EFI_PAGE_SIZE + 1)); } } else { - DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) Start, (UINTN) (RangeEnd - Start + 1)); + DEBUG_CLEAR_MEMORY ((VOID *)(UINTN)Start, (UINTN)(RangeEnd - Start + 1)); } } @@ -953,7 +954,6 @@ CoreConvertPagesEx ( return EFI_SUCCESS; } - /** Internal function. Converts a memory range to the specified type. The range must exist in the memory map. @@ -977,10 +977,9 @@ CoreConvertPages ( IN EFI_MEMORY_TYPE NewType ) { - return CoreConvertPagesEx(Start, NumberOfPages, TRUE, NewType, FALSE, 0); + return CoreConvertPagesEx (Start, NumberOfPages, TRUE, NewType, FALSE, 0); } - /** Internal function. Converts a memory range to use new attributes. @@ -1002,12 +1001,11 @@ CoreUpdateMemoryAttributes ( // // Update the attributes to the new value // - CoreConvertPagesEx(Start, NumberOfPages, FALSE, (EFI_MEMORY_TYPE)0, TRUE, NewAttributes); + CoreConvertPagesEx (Start, NumberOfPages, FALSE, (EFI_MEMORY_TYPE)0, TRUE, NewAttributes); CoreReleaseMemoryLock (); } - /** Internal function. Finds a consecutive free page range below the requested address. @@ -1033,20 +1031,19 @@ CoreFindFreePagesI ( IN BOOLEAN NeedGuard ) { - UINT64 NumberOfBytes; - UINT64 Target; - UINT64 DescStart; - UINT64 DescEnd; - UINT64 DescNumberOfBytes; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - - if ((MaxAddress < EFI_PAGE_MASK) ||(NumberOfPages == 0)) { + UINT64 NumberOfBytes; + UINT64 Target; + UINT64 DescStart; + UINT64 DescEnd; + UINT64 DescNumberOfBytes; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + + if ((MaxAddress < EFI_PAGE_MASK) || (NumberOfPages == 0)) { return 0; } if ((MaxAddress & EFI_PAGE_MASK) != EFI_PAGE_MASK) { - // // If MaxAddress is not aligned to the end of a page // @@ -1068,7 +1065,7 @@ CoreFindFreePagesI ( } NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT); - Target = 0; + Target = 0; for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) { Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); @@ -1081,7 +1078,7 @@ CoreFindFreePagesI ( } DescStart = Entry->Start; - DescEnd = Entry->End; + DescEnd = Entry->End; // // If desc is past max allowed address or below min allowed address, skip it @@ -1153,7 +1150,6 @@ CoreFindFreePagesI ( return Target; } - /** Internal function. Finds a consecutive free page range below the requested address @@ -1170,19 +1166,19 @@ CoreFindFreePagesI ( **/ UINT64 FindFreePages ( - IN UINT64 MaxAddress, - IN UINT64 NoPages, - IN EFI_MEMORY_TYPE NewType, - IN UINTN Alignment, - IN BOOLEAN NeedGuard - ) + IN UINT64 MaxAddress, + IN UINT64 NoPages, + IN EFI_MEMORY_TYPE NewType, + IN UINTN Alignment, + IN BOOLEAN NeedGuard + ) { - UINT64 Start; + UINT64 Start; // // Attempt to find free pages in the preferred bin based on the requested memory type // - if ((UINT32)NewType < EfiMaxMemoryType && MaxAddress >= mMemoryTypeStatistics[NewType].MaximumAddress) { + if (((UINT32)NewType < EfiMaxMemoryType) && (MaxAddress >= mMemoryTypeStatistics[NewType].MaximumAddress)) { Start = CoreFindFreePagesI ( mMemoryTypeStatistics[NewType].MaximumAddress, mMemoryTypeStatistics[NewType].BaseAddress, @@ -1200,12 +1196,19 @@ FindFreePages ( // Attempt to find free pages in the default allocation bin // if (MaxAddress >= mDefaultMaximumAddress) { - Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType, - Alignment, NeedGuard); + Start = CoreFindFreePagesI ( + mDefaultMaximumAddress, + 0, + NoPages, + NewType, + Alignment, + NeedGuard + ); if (Start != 0) { if (Start < mDefaultBaseAddress) { mDefaultBaseAddress = Start; } + return Start; } } @@ -1216,8 +1219,14 @@ FindFreePages ( // address range. If this allocation fails, then there are not enough // resources anywhere to satisfy the request. // - Start = CoreFindFreePagesI (MaxAddress, 0, NoPages, NewType, Alignment, - NeedGuard); + Start = CoreFindFreePagesI ( + MaxAddress, + 0, + NoPages, + NewType, + Alignment, + NeedGuard + ); if (Start != 0) { return Start; } @@ -1235,7 +1244,6 @@ FindFreePages ( return FindFreePages (MaxAddress, NoPages, NewType, Alignment, NeedGuard); } - /** Allocates pages from the memory map. @@ -1258,11 +1266,11 @@ FindFreePages ( EFI_STATUS EFIAPI CoreInternalAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN BOOLEAN NeedGuard + IN BOOLEAN NeedGuard ) { EFI_STATUS Status; @@ -1277,8 +1285,9 @@ CoreInternalAllocatePages ( return EFI_INVALID_PARAMETER; } - if ((MemoryType >= EfiMaxMemoryType && MemoryType < MEMORY_TYPE_OEM_RESERVED_MIN) || - (MemoryType == EfiConventionalMemory) || (MemoryType == EfiPersistentMemory)) { + if (((MemoryType >= EfiMaxMemoryType) && (MemoryType < MEMORY_TYPE_OEM_RESERVED_MIN)) || + (MemoryType == EfiConventionalMemory) || (MemoryType == EfiPersistentMemory)) + { return EFI_INVALID_PARAMETER; } @@ -1288,11 +1297,11 @@ CoreInternalAllocatePages ( Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY; - if (MemoryType == EfiACPIReclaimMemory || - MemoryType == EfiACPIMemoryNVS || - MemoryType == EfiRuntimeServicesCode || - MemoryType == EfiRuntimeServicesData) { - + if ((MemoryType == EfiACPIReclaimMemory) || + (MemoryType == EfiACPIMemoryNVS) || + (MemoryType == EfiRuntimeServicesCode) || + (MemoryType == EfiRuntimeServicesData)) + { Alignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; } @@ -1327,15 +1336,18 @@ CoreInternalAllocatePages ( // if (Type == AllocateAddress) { if ((NumberOfPages == 0) || - (NumberOfPages > RShiftU64 (MaxAddress, EFI_PAGE_SHIFT))) { + (NumberOfPages > RShiftU64 (MaxAddress, EFI_PAGE_SHIFT))) + { return EFI_NOT_FOUND; } + NumberOfBytes = LShiftU64 (NumberOfPages, EFI_PAGE_SHIFT); - End = Start + NumberOfBytes - 1; + End = Start + NumberOfBytes - 1; if ((Start >= End) || (Start > MaxAddress) || - (End > MaxAddress)) { + (End > MaxAddress)) + { return EFI_NOT_FOUND; } @@ -1347,20 +1359,26 @@ CoreInternalAllocatePages ( // fragmented. // - for (CheckType = (EFI_MEMORY_TYPE) 0; CheckType < EfiMaxMemoryType; CheckType++) { - if (MemoryType != CheckType && + for (CheckType = (EFI_MEMORY_TYPE)0; CheckType < EfiMaxMemoryType; CheckType++) { + if ((MemoryType != CheckType) && mMemoryTypeStatistics[CheckType].Special && - mMemoryTypeStatistics[CheckType].NumberOfPages > 0) { - if (Start >= mMemoryTypeStatistics[CheckType].BaseAddress && - Start <= mMemoryTypeStatistics[CheckType].MaximumAddress) { + (mMemoryTypeStatistics[CheckType].NumberOfPages > 0)) + { + if ((Start >= mMemoryTypeStatistics[CheckType].BaseAddress) && + (Start <= mMemoryTypeStatistics[CheckType].MaximumAddress)) + { return EFI_NOT_FOUND; } - if (End >= mMemoryTypeStatistics[CheckType].BaseAddress && - End <= mMemoryTypeStatistics[CheckType].MaximumAddress) { + + if ((End >= mMemoryTypeStatistics[CheckType].BaseAddress) && + (End <= mMemoryTypeStatistics[CheckType].MaximumAddress)) + { return EFI_NOT_FOUND; } - if (Start < mMemoryTypeStatistics[CheckType].BaseAddress && - End > mMemoryTypeStatistics[CheckType].MaximumAddress) { + + if ((Start < mMemoryTypeStatistics[CheckType].BaseAddress) && + (End > mMemoryTypeStatistics[CheckType].MaximumAddress)) + { return EFI_NOT_FOUND; } } @@ -1377,8 +1395,13 @@ CoreInternalAllocatePages ( // If not a specific address, then find an address to allocate // if (Type != AllocateAddress) { - Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment, - NeedGuard); + Start = FindFreePages ( + MaxAddress, + NumberOfPages, + MemoryType, + Alignment, + NeedGuard + ); if (Start == 0) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -1389,9 +1412,9 @@ CoreInternalAllocatePages ( // Convert pages from FreeMemory to the requested type // if (NeedGuard) { - Status = CoreConvertPagesWithGuard(Start, NumberOfPages, MemoryType); + Status = CoreConvertPagesWithGuard (Start, NumberOfPages, MemoryType); } else { - Status = CoreConvertPages(Start, NumberOfPages, MemoryType); + Status = CoreConvertPages (Start, NumberOfPages, MemoryType); } Done: @@ -1401,6 +1424,7 @@ Done: if (NeedGuard) { SetGuardForMemory (Start, NumberOfPages); } + *Memory = Start; } @@ -1438,21 +1462,31 @@ CoreAllocatePages ( BOOLEAN NeedGuard; NeedGuard = IsPageTypeToGuard (MemoryType, Type) && !mOnGuarding; - Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory, - NeedGuard); + Status = CoreInternalAllocatePages ( + Type, + MemoryType, + NumberOfPages, + Memory, + NeedGuard + ); if (!EFI_ERROR (Status)) { CoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionAllocatePages, MemoryType, EFI_PAGES_TO_SIZE (NumberOfPages), - (VOID *) (UINTN) *Memory, + (VOID *)(UINTN)*Memory, NULL ); InstallMemoryAttributesTableOnMemoryAllocation (MemoryType); - ApplyMemoryProtectionPolicy (EfiConventionalMemory, MemoryType, *Memory, - EFI_PAGES_TO_SIZE (NumberOfPages)); + ApplyMemoryProtectionPolicy ( + EfiConventionalMemory, + MemoryType, + *Memory, + EFI_PAGES_TO_SIZE (NumberOfPages) + ); } + return Status; } @@ -1471,16 +1505,16 @@ CoreAllocatePages ( EFI_STATUS EFIAPI CoreInternalFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages, - OUT EFI_MEMORY_TYPE *MemoryType OPTIONAL + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages, + OUT EFI_MEMORY_TYPE *MemoryType OPTIONAL ) { - EFI_STATUS Status; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - UINTN Alignment; - BOOLEAN IsGuarded; + EFI_STATUS Status; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + UINTN Alignment; + BOOLEAN IsGuarded; // // Free the range @@ -1491,13 +1525,14 @@ CoreInternalFreePages ( // Find the entry that the covers the range // IsGuarded = FALSE; - Entry = NULL; + Entry = NULL; for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) { - Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); - if (Entry->Start <= Memory && Entry->End > Memory) { - break; + Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); + if ((Entry->Start <= Memory) && (Entry->End > Memory)) { + break; } } + if (Link == &gMemoryMap) { Status = EFI_NOT_FOUND; goto Done; @@ -1506,13 +1541,12 @@ CoreInternalFreePages ( Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY; ASSERT (Entry != NULL); - if (Entry->Type == EfiACPIReclaimMemory || - Entry->Type == EfiACPIMemoryNVS || - Entry->Type == EfiRuntimeServicesCode || - Entry->Type == EfiRuntimeServicesData) { - + if ((Entry->Type == EfiACPIReclaimMemory) || + (Entry->Type == EfiACPIMemoryNVS) || + (Entry->Type == EfiRuntimeServicesCode) || + (Entry->Type == EfiRuntimeServicesData)) + { Alignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; - } if ((Memory & (Alignment - 1)) != 0) { @@ -1530,8 +1564,11 @@ CoreInternalFreePages ( IsGuarded = IsPageTypeToGuard (Entry->Type, AllocateAnyPages) && IsMemoryGuarded (Memory); if (IsGuarded) { - Status = CoreConvertPagesWithGuard (Memory, NumberOfPages, - EfiConventionalMemory); + Status = CoreConvertPagesWithGuard ( + Memory, + NumberOfPages, + EfiConventionalMemory + ); } else { Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory); } @@ -1559,24 +1596,29 @@ CoreFreePages ( IN UINTN NumberOfPages ) { - EFI_STATUS Status; - EFI_MEMORY_TYPE MemoryType; + EFI_STATUS Status; + EFI_MEMORY_TYPE MemoryType; Status = CoreInternalFreePages (Memory, NumberOfPages, &MemoryType); if (!EFI_ERROR (Status)) { GuardFreedPagesChecked (Memory, NumberOfPages); CoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionFreePages, MemoryType, EFI_PAGES_TO_SIZE (NumberOfPages), - (VOID *) (UINTN) Memory, + (VOID *)(UINTN)Memory, NULL ); InstallMemoryAttributesTableOnMemoryAllocation (MemoryType); - ApplyMemoryProtectionPolicy (MemoryType, EfiConventionalMemory, Memory, - EFI_PAGES_TO_SIZE (NumberOfPages)); + ApplyMemoryProtectionPolicy ( + MemoryType, + EfiConventionalMemory, + Memory, + EFI_PAGES_TO_SIZE (NumberOfPages) + ); } + return Status; } @@ -1604,7 +1646,7 @@ MergeMemoryMapDescriptor ( // // Traverse the array of descriptors in MemoryMap // - for (; MemoryMap != MemoryMapDescriptor; MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize)) { + for ( ; MemoryMap != MemoryMapDescriptor; MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize)) { // // Check to see if the Type fields are identical. // @@ -1701,17 +1743,17 @@ CoreGetMemoryMap ( OUT UINT32 *DescriptorVersion ) { - EFI_STATUS Status; - UINTN Size; - UINTN BufferSize; - UINTN NumberOfEntries; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - EFI_GCD_MAP_ENTRY *GcdMapEntry; - EFI_GCD_MAP_ENTRY MergeGcdMapEntry; - EFI_MEMORY_TYPE Type; - EFI_MEMORY_DESCRIPTOR *MemoryMapStart; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_STATUS Status; + UINTN Size; + UINTN BufferSize; + UINTN NumberOfEntries; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + EFI_GCD_MAP_ENTRY *GcdMapEntry; + EFI_GCD_MAP_ENTRY MergeGcdMapEntry; + EFI_MEMORY_TYPE Type; + EFI_MEMORY_DESCRIPTOR *MemoryMapStart; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; // // Make sure the parameters are valid @@ -1732,8 +1774,9 @@ CoreGetMemoryMap ( if ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypePersistent) || (GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeReserved) || ((GcdMapEntry->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) && - ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) { - NumberOfEntries ++; + ((GcdMapEntry->Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) + { + NumberOfEntries++; } } @@ -1744,7 +1787,7 @@ CoreGetMemoryMap ( // prevent people from having pointer math bugs in their code. // now you have to use *DescriptorSize to make things work. // - Size += sizeof(UINT64) - (Size % sizeof (UINT64)); + Size += sizeof (UINT64) - (Size % sizeof (UINT64)); if (DescriptorSize != NULL) { *DescriptorSize = Size; @@ -1786,10 +1829,10 @@ CoreGetMemoryMap ( // // Convert internal map into an EFI_MEMORY_DESCRIPTOR // - MemoryMap->Type = Entry->Type; - MemoryMap->PhysicalStart = Entry->Start; - MemoryMap->VirtualStart = Entry->VirtualStart; - MemoryMap->NumberOfPages = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT); + MemoryMap->Type = Entry->Type; + MemoryMap->PhysicalStart = Entry->Start; + MemoryMap->VirtualStart = Entry->VirtualStart; + MemoryMap->NumberOfPages = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT); // // If the memory type is EfiConventionalMemory, then determine if the range is part of a // memory type bin and needs to be converted to the same memory type as the rest of the @@ -1798,15 +1841,17 @@ CoreGetMemoryMap ( // differences across reboots. // if (MemoryMap->Type == EfiConventionalMemory) { - for (Type = (EFI_MEMORY_TYPE) 0; Type < EfiMaxMemoryType; Type++) { + for (Type = (EFI_MEMORY_TYPE)0; Type < EfiMaxMemoryType; Type++) { if (mMemoryTypeStatistics[Type].Special && - mMemoryTypeStatistics[Type].NumberOfPages > 0 && - Entry->Start >= mMemoryTypeStatistics[Type].BaseAddress && - Entry->End <= mMemoryTypeStatistics[Type].MaximumAddress) { + (mMemoryTypeStatistics[Type].NumberOfPages > 0) && + (Entry->Start >= mMemoryTypeStatistics[Type].BaseAddress) && + (Entry->End <= mMemoryTypeStatistics[Type].MaximumAddress)) + { MemoryMap->Type = Type; } } } + MemoryMap->Attribute = Entry->Attribute; if (MemoryMap->Type < EfiMaxMemoryType) { if (mMemoryTypeStatistics[MemoryMap->Type].Runtime) { @@ -1821,7 +1866,6 @@ CoreGetMemoryMap ( MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size); } - ZeroMem (&MergeGcdMapEntry, sizeof (MergeGcdMapEntry)); GcdMapEntry = NULL; for (Link = mGcdMemorySpaceMap.ForwardLink; ; Link = Link->ForwardLink) { @@ -1834,15 +1878,17 @@ CoreGetMemoryMap ( if ((MergeGcdMapEntry.Capabilities == GcdMapEntry->Capabilities) && (MergeGcdMapEntry.Attributes == GcdMapEntry->Attributes) && (MergeGcdMapEntry.GcdMemoryType == GcdMapEntry->GcdMemoryType) && - (MergeGcdMapEntry.GcdIoType == GcdMapEntry->GcdIoType)) { - MergeGcdMapEntry.EndAddress = GcdMapEntry->EndAddress; + (MergeGcdMapEntry.GcdIoType == GcdMapEntry->GcdIoType)) + { + MergeGcdMapEntry.EndAddress = GcdMapEntry->EndAddress; continue; } } if ((MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeReserved) || ((MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo) && - ((MergeGcdMapEntry.Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) { + ((MergeGcdMapEntry.Attributes & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME))) + { // // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR, // it will be recorded as page PhysicalStart and NumberOfPages. @@ -1857,7 +1903,7 @@ CoreGetMemoryMap ( MemoryMap->VirtualStart = 0; MemoryMap->NumberOfPages = RShiftU64 ((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1), EFI_PAGE_SHIFT); MemoryMap->Attribute = (MergeGcdMapEntry.Attributes & ~EFI_MEMORY_PORT_IO) | - (MergeGcdMapEntry.Capabilities & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); + (MergeGcdMapEntry.Capabilities & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); if (MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeReserved) { MemoryMap->Type = EfiReservedMemoryType; @@ -1891,8 +1937,8 @@ CoreGetMemoryMap ( MemoryMap->VirtualStart = 0; MemoryMap->NumberOfPages = RShiftU64 ((MergeGcdMapEntry.EndAddress - MergeGcdMapEntry.BaseAddress + 1), EFI_PAGE_SHIFT); MemoryMap->Attribute = MergeGcdMapEntry.Attributes | EFI_MEMORY_NV | - (MergeGcdMapEntry.Capabilities & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); - MemoryMap->Type = EfiPersistentMemory; + (MergeGcdMapEntry.Capabilities & (EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK)); + MemoryMap->Type = EfiPersistentMemory; // // Check to see if the new Memory Map Descriptor can be merged with an @@ -1900,12 +1946,14 @@ CoreGetMemoryMap ( // MemoryMap = MergeMemoryMapDescriptor (MemoryMapStart, MemoryMap, Size); } + if (Link == &mGcdMemorySpaceMap) { // // break loop when arrive at head. // break; } + if (GcdMapEntry != NULL) { // // Copy new GCD map entry for the following GCD range merge @@ -1931,11 +1979,12 @@ CoreGetMemoryMap ( // all supported OSs. // MemoryMapEnd = MemoryMap; - MemoryMap = MemoryMapStart; + MemoryMap = MemoryMapStart; while (MemoryMap < MemoryMapEnd) { MemoryMap->Attribute &= ~(UINT64)EFI_MEMORY_ACCESS_MASK; - MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size); + MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size); } + MergeMemoryMap (MemoryMapStart, &BufferSize, Size); MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMapStart + BufferSize); @@ -1957,12 +2006,11 @@ Done: DEBUG_CODE ( DumpGuardedMemoryBitmap (); - ); + ); return Status; } - /** Internal function. Used by the pool functions to allocate pages to back pool allocation requests. @@ -1977,19 +2025,24 @@ Done: **/ VOID * CoreAllocatePoolPages ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN NumberOfPages, - IN UINTN Alignment, - IN BOOLEAN NeedGuard + IN EFI_MEMORY_TYPE PoolType, + IN UINTN NumberOfPages, + IN UINTN Alignment, + IN BOOLEAN NeedGuard ) { - UINT64 Start; + UINT64 Start; // // Find the pages to convert // - Start = FindFreePages (MAX_ALLOC_ADDRESS, NumberOfPages, PoolType, Alignment, - NeedGuard); + Start = FindFreePages ( + MAX_ALLOC_ADDRESS, + NumberOfPages, + PoolType, + Alignment, + NeedGuard + ); // // Convert it to boot services data @@ -2004,10 +2057,9 @@ CoreAllocatePoolPages ( } } - return (VOID *)(UINTN) Start; + return (VOID *)(UINTN)Start; } - /** Internal function. Frees pool pages allocated via AllocatePoolPages () @@ -2017,15 +2069,13 @@ CoreAllocatePoolPages ( **/ VOID CoreFreePoolPages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ) { CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory); } - - /** Make sure the memory map is following all the construction rules, it is the last time to check memory map error before exit boot services. @@ -2039,19 +2089,18 @@ CoreFreePoolPages ( **/ EFI_STATUS CoreTerminateMemoryMap ( - IN UINTN MapKey + IN UINTN MapKey ) { - EFI_STATUS Status; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; + EFI_STATUS Status; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; Status = EFI_SUCCESS; CoreAcquireMemoryLock (); if (MapKey == mMemoryMapKey) { - // // Make sure the memory map is following all the construction rules // This is the last chance we will be able to display any messages on @@ -2059,18 +2108,19 @@ CoreTerminateMemoryMap ( // for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) { - Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); + Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); if (Entry->Type < EfiMaxMemoryType) { if (mMemoryTypeStatistics[Entry->Type].Runtime) { ASSERT (Entry->Type != EfiACPIReclaimMemory); ASSERT (Entry->Type != EfiACPIMemoryNVS); if ((Entry->Start & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) { - DEBUG((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n")); + DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n")); Status = EFI_INVALID_PARAMETER; goto Done; } + if (((Entry->End + 1) & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) { - DEBUG((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n")); + DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n")); Status = EFI_INVALID_PARAMETER; goto Done; } @@ -2094,12 +2144,3 @@ Done: return Status; } - - - - - - - - - diff --git a/MdeModulePkg/Core/Dxe/Mem/Pool.c b/MdeModulePkg/Core/Dxe/Mem/Pool.c index 734fc94bf6..7aaf501600 100644 --- a/MdeModulePkg/Core/Dxe/Mem/Pool.c +++ b/MdeModulePkg/Core/Dxe/Mem/Pool.c @@ -10,36 +10,35 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Imem.h" #include "HeapGuard.h" -STATIC EFI_LOCK mPoolMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +STATIC EFI_LOCK mPoolMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -#define POOL_FREE_SIGNATURE SIGNATURE_32('p','f','r','0') +#define POOL_FREE_SIGNATURE SIGNATURE_32('p','f','r','0') typedef struct { - UINT32 Signature; - UINT32 Index; - LIST_ENTRY Link; + UINT32 Signature; + UINT32 Index; + LIST_ENTRY Link; } POOL_FREE; - -#define POOL_HEAD_SIGNATURE SIGNATURE_32('p','h','d','0') -#define POOLPAGE_HEAD_SIGNATURE SIGNATURE_32('p','h','d','1') +#define POOL_HEAD_SIGNATURE SIGNATURE_32('p','h','d','0') +#define POOLPAGE_HEAD_SIGNATURE SIGNATURE_32('p','h','d','1') typedef struct { - UINT32 Signature; - UINT32 Reserved; - EFI_MEMORY_TYPE Type; - UINTN Size; - CHAR8 Data[1]; + UINT32 Signature; + UINT32 Reserved; + EFI_MEMORY_TYPE Type; + UINTN Size; + CHAR8 Data[1]; } POOL_HEAD; -#define SIZE_OF_POOL_HEAD OFFSET_OF(POOL_HEAD,Data) +#define SIZE_OF_POOL_HEAD OFFSET_OF(POOL_HEAD,Data) -#define POOL_TAIL_SIGNATURE SIGNATURE_32('p','t','a','l') +#define POOL_TAIL_SIGNATURE SIGNATURE_32('p','t','a','l') typedef struct { - UINT32 Signature; - UINT32 Reserved; - UINTN Size; + UINT32 Signature; + UINT32 Reserved; + UINTN Size; } POOL_TAIL; -#define POOL_OVERHEAD (SIZE_OF_POOL_HEAD + sizeof(POOL_TAIL)) +#define POOL_OVERHEAD (SIZE_OF_POOL_HEAD + sizeof(POOL_TAIL)) #define HEAD_TO_TAIL(a) \ ((POOL_TAIL *) (((CHAR8 *) (a)) + (a)->Size - sizeof(POOL_TAIL))); @@ -49,16 +48,16 @@ typedef struct { // blocks between bins by splitting them up, while not wasting too much memory // as we would in a strict power-of-2 sequence // -STATIC CONST UINT16 mPoolSizeTable[] = { +STATIC CONST UINT16 mPoolSizeTable[] = { 128, 256, 384, 640, 1024, 1664, 2688, 4352, 7040, 11392, 18432, 29824 }; -#define SIZE_TO_LIST(a) (GetPoolIndexFromSize (a)) -#define LIST_TO_SIZE(a) (mPoolSizeTable [a]) +#define SIZE_TO_LIST(a) (GetPoolIndexFromSize (a)) +#define LIST_TO_SIZE(a) (mPoolSizeTable [a]) -#define MAX_POOL_LIST (ARRAY_SIZE (mPoolSizeTable)) +#define MAX_POOL_LIST (ARRAY_SIZE (mPoolSizeTable)) -#define MAX_POOL_SIZE (MAX_ADDRESS - POOL_OVERHEAD) +#define MAX_POOL_SIZE (MAX_ADDRESS - POOL_OVERHEAD) // // Globals @@ -66,22 +65,22 @@ STATIC CONST UINT16 mPoolSizeTable[] = { #define POOL_SIGNATURE SIGNATURE_32('p','l','s','t') typedef struct { - INTN Signature; - UINTN Used; - EFI_MEMORY_TYPE MemoryType; - LIST_ENTRY FreeList[MAX_POOL_LIST]; - LIST_ENTRY Link; + INTN Signature; + UINTN Used; + EFI_MEMORY_TYPE MemoryType; + LIST_ENTRY FreeList[MAX_POOL_LIST]; + LIST_ENTRY Link; } POOL; // // Pool header for each memory type. // -POOL mPoolHead[EfiMaxMemoryType]; +POOL mPoolHead[EfiMaxMemoryType]; // // List of pool header to search for the appropriate memory type. // -LIST_ENTRY mPoolHeadList = INITIALIZE_LIST_HEAD_VARIABLE (mPoolHeadList); +LIST_ENTRY mPoolHeadList = INITIALIZE_LIST_HEAD_VARIABLE (mPoolHeadList); /** Get pool size table index from the specified size. @@ -94,16 +93,17 @@ LIST_ENTRY mPoolHeadList = INITIALIZE_LIST_HEAD_VARIABLE (mPoolHeadList); STATIC UINTN GetPoolIndexFromSize ( - UINTN Size + UINTN Size ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < MAX_POOL_LIST; Index++) { - if (mPoolSizeTable [Index] >= Size) { + if (mPoolSizeTable[Index] >= Size) { return Index; } } + return MAX_POOL_LIST; } @@ -119,17 +119,16 @@ CoreInitializePool ( UINTN Type; UINTN Index; - for (Type=0; Type < EfiMaxMemoryType; Type++) { + for (Type = 0; Type < EfiMaxMemoryType; Type++) { mPoolHead[Type].Signature = 0; mPoolHead[Type].Used = 0; - mPoolHead[Type].MemoryType = (EFI_MEMORY_TYPE) Type; - for (Index=0; Index < MAX_POOL_LIST; Index++) { + mPoolHead[Type].MemoryType = (EFI_MEMORY_TYPE)Type; + for (Index = 0; Index < MAX_POOL_LIST; Index++) { InitializeListHead (&mPoolHead[Type].FreeList[Index]); } } } - /** Look up pool head for specified memory type. @@ -143,9 +142,9 @@ LookupPoolHead ( IN EFI_MEMORY_TYPE MemoryType ) { - LIST_ENTRY *Link; - POOL *Pool; - UINTN Index; + LIST_ENTRY *Link; + POOL *Pool; + UINTN Index; if ((UINT32)MemoryType < EfiMaxMemoryType) { return &mPoolHead[MemoryType]; @@ -156,10 +155,9 @@ LookupPoolHead ( // OS loaders that are provided by operating system vendors. // MemoryType values in the range 0x70000000..0x7FFFFFFF are reserved for OEM use. // - if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { - + if ((UINT32)MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) { for (Link = mPoolHeadList.ForwardLink; Link != &mPoolHeadList; Link = Link->ForwardLink) { - Pool = CR(Link, POOL, Link, POOL_SIGNATURE); + Pool = CR (Link, POOL, Link, POOL_SIGNATURE); if (Pool->MemoryType == MemoryType) { return Pool; } @@ -170,10 +168,10 @@ LookupPoolHead ( return NULL; } - Pool->Signature = POOL_SIGNATURE; - Pool->Used = 0; + Pool->Signature = POOL_SIGNATURE; + Pool->Used = 0; Pool->MemoryType = MemoryType; - for (Index=0; Index < MAX_POOL_LIST; Index++) { + for (Index = 0; Index < MAX_POOL_LIST; Index++) { InitializeListHead (&Pool->FreeList[Index]); } @@ -185,8 +183,6 @@ LookupPoolHead ( return NULL; } - - /** Allocate pool of a particular type. @@ -210,14 +206,15 @@ CoreInternalAllocatePool ( OUT VOID **Buffer ) { - EFI_STATUS Status; - BOOLEAN NeedGuard; + EFI_STATUS Status; + BOOLEAN NeedGuard; // // If it's not a valid type, fail it // - if ((PoolType >= EfiMaxMemoryType && PoolType < MEMORY_TYPE_OEM_RESERVED_MIN) || - (PoolType == EfiConventionalMemory) || (PoolType == EfiPersistentMemory)) { + if (((PoolType >= EfiMaxMemoryType) && (PoolType < MEMORY_TYPE_OEM_RESERVED_MIN)) || + (PoolType == EfiConventionalMemory) || (PoolType == EfiPersistentMemory)) + { return EFI_INVALID_PARAMETER; } @@ -278,7 +275,7 @@ CoreAllocatePool ( Status = CoreInternalAllocatePool (PoolType, Size, Buffer); if (!EFI_ERROR (Status)) { CoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionAllocatePool, PoolType, Size, @@ -287,6 +284,7 @@ CoreAllocatePool ( ); InstallMemoryAttributesTableOnMemoryAllocation (PoolType); } + return Status; } @@ -305,10 +303,10 @@ CoreAllocatePool ( STATIC VOID * CoreAllocatePoolPagesI ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN NoPages, - IN UINTN Granularity, - IN BOOLEAN NeedGuard + IN EFI_MEMORY_TYPE PoolType, + IN UINTN NoPages, + IN UINTN Granularity, + IN BOOLEAN NeedGuard ) { VOID *Buffer; @@ -326,9 +324,15 @@ CoreAllocatePoolPagesI ( if (NeedGuard) { SetGuardForMemory ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, NoPages); } - ApplyMemoryProtectionPolicy(EfiConventionalMemory, PoolType, - (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_PAGES_TO_SIZE (NoPages)); + + ApplyMemoryProtectionPolicy ( + EfiConventionalMemory, + PoolType, + (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, + EFI_PAGES_TO_SIZE (NoPages) + ); } + return Buffer; } @@ -350,27 +354,27 @@ CoreAllocatePoolI ( IN BOOLEAN NeedGuard ) { - POOL *Pool; - POOL_FREE *Free; - POOL_HEAD *Head; - POOL_TAIL *Tail; - CHAR8 *NewPage; - VOID *Buffer; - UINTN Index; - UINTN FSize; - UINTN Offset, MaxOffset; - UINTN NoPages; - UINTN Granularity; - BOOLEAN HasPoolTail; - BOOLEAN PageAsPool; + POOL *Pool; + POOL_FREE *Free; + POOL_HEAD *Head; + POOL_TAIL *Tail; + CHAR8 *NewPage; + VOID *Buffer; + UINTN Index; + UINTN FSize; + UINTN Offset, MaxOffset; + UINTN NoPages; + UINTN Granularity; + BOOLEAN HasPoolTail; + BOOLEAN PageAsPool; ASSERT_LOCKED (&mPoolMemoryLock); - if (PoolType == EfiACPIReclaimMemory || - PoolType == EfiACPIMemoryNVS || - PoolType == EfiRuntimeServicesCode || - PoolType == EfiRuntimeServicesData) { - + if ((PoolType == EfiACPIReclaimMemory) || + (PoolType == EfiACPIMemoryNVS) || + (PoolType == EfiRuntimeServicesCode) || + (PoolType == EfiRuntimeServicesData)) + { Granularity = RUNTIME_PAGE_ALLOCATION_GRANULARITY; } else { Granularity = DEFAULT_PAGE_ALLOCATION_GRANULARITY; @@ -380,8 +384,8 @@ CoreAllocatePoolI ( // Adjust the size by the pool header & tail overhead // - HasPoolTail = !(NeedGuard && - ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)); + HasPoolTail = !(NeedGuard && + ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)); PageAsPool = (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) && !mOnGuarding); // @@ -392,27 +396,30 @@ CoreAllocatePoolI ( Size = ALIGN_VARIABLE (Size); Size += POOL_OVERHEAD; - Index = SIZE_TO_LIST(Size); - Pool = LookupPoolHead (PoolType); - if (Pool== NULL) { + Index = SIZE_TO_LIST (Size); + Pool = LookupPoolHead (PoolType); + if (Pool == NULL) { return NULL; } + Head = NULL; // // If allocation is over max size, just allocate pages for the request // (slow) // - if (Index >= SIZE_TO_LIST (Granularity) || NeedGuard || PageAsPool) { + if ((Index >= SIZE_TO_LIST (Granularity)) || NeedGuard || PageAsPool) { if (!HasPoolTail) { Size -= sizeof (POOL_TAIL); } - NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1; + + NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1; NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1); - Head = CoreAllocatePoolPagesI (PoolType, NoPages, Granularity, NeedGuard); + Head = CoreAllocatePoolPagesI (PoolType, NoPages, Granularity, NeedGuard); if (NeedGuard) { Head = AdjustPoolHeadA ((EFI_PHYSICAL_ADDRESS)(UINTN)Head, NoPages, Size); } + goto Done; } @@ -420,8 +427,7 @@ CoreAllocatePoolI ( // If there's no free pool in the proper list size, go get some more pages // if (IsListEmpty (&Pool->FreeList[Index])) { - - Offset = LIST_TO_SIZE (Index); + Offset = LIST_TO_SIZE (Index); MaxOffset = Granularity; // @@ -431,7 +437,7 @@ CoreAllocatePoolI ( if (!IsListEmpty (&Pool->FreeList[Index])) { Free = CR (Pool->FreeList[Index].ForwardLink, POOL_FREE, Link, POOL_FREE_SIGNATURE); RemoveEntryList (&Free->Link); - NewPage = (VOID *) Free; + NewPage = (VOID *)Free; MaxOffset = LIST_TO_SIZE (Index); goto Carve; } @@ -440,8 +446,12 @@ CoreAllocatePoolI ( // // Get another page // - NewPage = CoreAllocatePoolPagesI (PoolType, EFI_SIZE_TO_PAGES (Granularity), - Granularity, NeedGuard); + NewPage = CoreAllocatePoolPagesI ( + PoolType, + EFI_SIZE_TO_PAGES (Granularity), + Granularity, + NeedGuard + ); if (NewPage == NULL) { goto Done; } @@ -450,7 +460,7 @@ CoreAllocatePoolI ( // Serve the allocation request from the head of the allocated block // Carve: - Head = (POOL_HEAD *) NewPage; + Head = (POOL_HEAD *)NewPage; // // Carve up remaining space into free pool blocks @@ -458,15 +468,16 @@ Carve: Index--; while (Offset < MaxOffset) { ASSERT (Index < MAX_POOL_LIST); - FSize = LIST_TO_SIZE(Index); + FSize = LIST_TO_SIZE (Index); while (Offset + FSize <= MaxOffset) { - Free = (POOL_FREE *) &NewPage[Offset]; + Free = (POOL_FREE *)&NewPage[Offset]; Free->Signature = POOL_FREE_SIGNATURE; Free->Index = (UINT32)Index; InsertHeadList (&Pool->FreeList[Index], &Free->Link); Offset += FSize; } + Index -= 1; } @@ -480,13 +491,12 @@ Carve: Free = CR (Pool->FreeList[Index].ForwardLink, POOL_FREE, Link, POOL_FREE_SIGNATURE); RemoveEntryList (&Free->Link); - Head = (POOL_HEAD *) Free; + Head = (POOL_HEAD *)Free; Done: Buffer = NULL; if (Head != NULL) { - // // Account the allocation // @@ -497,7 +507,7 @@ Done: // Head->Signature = (PageAsPool) ? POOLPAGE_HEAD_SIGNATURE : POOL_HEAD_SIGNATURE; Head->Size = Size; - Head->Type = (EFI_MEMORY_TYPE) PoolType; + Head->Type = (EFI_MEMORY_TYPE)PoolType; Buffer = Head->Data; if (HasPoolTail) { @@ -514,22 +524,19 @@ Done: DEBUG (( DEBUG_POOL, - "AllocatePoolI: Type %x, Addr %p (len %lx) %,ld\n", PoolType, + "AllocatePoolI: Type %x, Addr %p (len %lx) %,ld\n", + PoolType, Buffer, (UINT64)Size, - (UINT64) Pool->Used + (UINT64)Pool->Used )); - - } else { - DEBUG ((DEBUG_ERROR | DEBUG_POOL, "AllocatePool: failed to allocate %ld bytes\n", (UINT64) Size)); + DEBUG ((DEBUG_ERROR | DEBUG_POOL, "AllocatePool: failed to allocate %ld bytes\n", (UINT64)Size)); } return Buffer; } - - /** Frees pool. @@ -543,11 +550,11 @@ Done: EFI_STATUS EFIAPI CoreInternalFreePool ( - IN VOID *Buffer, - OUT EFI_MEMORY_TYPE *PoolType OPTIONAL + IN VOID *Buffer, + OUT EFI_MEMORY_TYPE *PoolType OPTIONAL ) { - EFI_STATUS Status; + EFI_STATUS Status; if (Buffer == NULL) { return EFI_INVALID_PARAMETER; @@ -574,13 +581,13 @@ CoreFreePool ( IN VOID *Buffer ) { - EFI_STATUS Status; - EFI_MEMORY_TYPE PoolType; + EFI_STATUS Status; + EFI_MEMORY_TYPE PoolType; Status = CoreInternalFreePool (Buffer, &PoolType); if (!EFI_ERROR (Status)) { CoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionFreePool, PoolType, 0, @@ -589,6 +596,7 @@ CoreFreePool ( ); InstallMemoryAttributesTableOnMemoryAllocation (PoolType); } + return Status; } @@ -603,9 +611,9 @@ CoreFreePool ( STATIC VOID CoreFreePoolPagesI ( - IN EFI_MEMORY_TYPE PoolType, - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages + IN EFI_MEMORY_TYPE PoolType, + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages ) { CoreAcquireMemoryLock (); @@ -613,8 +621,12 @@ CoreFreePoolPagesI ( CoreReleaseMemoryLock (); GuardFreedPagesChecked (Memory, NoPages); - ApplyMemoryProtectionPolicy (PoolType, EfiConventionalMemory, - (EFI_PHYSICAL_ADDRESS)(UINTN)Memory, EFI_PAGES_TO_SIZE (NoPages)); + ApplyMemoryProtectionPolicy ( + PoolType, + EfiConventionalMemory, + (EFI_PHYSICAL_ADDRESS)(UINTN)Memory, + EFI_PAGES_TO_SIZE (NoPages) + ); } /** @@ -628,13 +640,13 @@ CoreFreePoolPagesI ( STATIC VOID CoreFreePoolPagesWithGuard ( - IN EFI_MEMORY_TYPE PoolType, - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages + IN EFI_MEMORY_TYPE PoolType, + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages ) { - EFI_PHYSICAL_ADDRESS MemoryGuarded; - UINTN NoPagesGuarded; + EFI_PHYSICAL_ADDRESS MemoryGuarded; + UINTN NoPagesGuarded; MemoryGuarded = Memory; NoPagesGuarded = NoPages; @@ -666,41 +678,44 @@ CoreFreePoolPagesWithGuard ( **/ EFI_STATUS CoreFreePoolI ( - IN VOID *Buffer, - OUT EFI_MEMORY_TYPE *PoolType OPTIONAL + IN VOID *Buffer, + OUT EFI_MEMORY_TYPE *PoolType OPTIONAL ) { - POOL *Pool; - POOL_HEAD *Head; - POOL_TAIL *Tail; - POOL_FREE *Free; - UINTN Index; - UINTN NoPages; - UINTN Size; - CHAR8 *NewPage; - UINTN Offset; - BOOLEAN AllFree; - UINTN Granularity; - BOOLEAN IsGuarded; - BOOLEAN HasPoolTail; - BOOLEAN PageAsPool; - - ASSERT(Buffer != NULL); + POOL *Pool; + POOL_HEAD *Head; + POOL_TAIL *Tail; + POOL_FREE *Free; + UINTN Index; + UINTN NoPages; + UINTN Size; + CHAR8 *NewPage; + UINTN Offset; + BOOLEAN AllFree; + UINTN Granularity; + BOOLEAN IsGuarded; + BOOLEAN HasPoolTail; + BOOLEAN PageAsPool; + + ASSERT (Buffer != NULL); // // Get the head & tail of the pool entry // Head = BASE_CR (Buffer, POOL_HEAD, Data); - ASSERT(Head != NULL); - - if (Head->Signature != POOL_HEAD_SIGNATURE && - Head->Signature != POOLPAGE_HEAD_SIGNATURE) { - ASSERT (Head->Signature == POOL_HEAD_SIGNATURE || - Head->Signature == POOLPAGE_HEAD_SIGNATURE); + ASSERT (Head != NULL); + + if ((Head->Signature != POOL_HEAD_SIGNATURE) && + (Head->Signature != POOLPAGE_HEAD_SIGNATURE)) + { + ASSERT ( + Head->Signature == POOL_HEAD_SIGNATURE || + Head->Signature == POOLPAGE_HEAD_SIGNATURE + ); return EFI_INVALID_PARAMETER; } - IsGuarded = IsPoolTypeToGuard (Head->Type) && - IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head); + IsGuarded = IsPoolTypeToGuard (Head->Type) && + IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head); HasPoolTail = !(IsGuarded && ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)); PageAsPool = (Head->Signature == POOLPAGE_HEAD_SIGNATURE); @@ -734,14 +749,15 @@ CoreFreePoolI ( if (Pool == NULL) { return EFI_INVALID_PARAMETER; } - Pool->Used -= Size; - DEBUG ((DEBUG_POOL, "FreePool: %p (len %lx) %,ld\n", Head->Data, (UINT64)(Head->Size - POOL_OVERHEAD), (UINT64) Pool->Used)); - if (Head->Type == EfiACPIReclaimMemory || - Head->Type == EfiACPIMemoryNVS || - Head->Type == EfiRuntimeServicesCode || - Head->Type == EfiRuntimeServicesData) { + Pool->Used -= Size; + DEBUG ((DEBUG_POOL, "FreePool: %p (len %lx) %,ld\n", Head->Data, (UINT64)(Head->Size - POOL_OVERHEAD), (UINT64)Pool->Used)); + if ((Head->Type == EfiACPIReclaimMemory) || + (Head->Type == EfiACPIMemoryNVS) || + (Head->Type == EfiRuntimeServicesCode) || + (Head->Type == EfiRuntimeServicesData)) + { Granularity = RUNTIME_PAGE_ALLOCATION_GRANULARITY; } else { Granularity = DEFAULT_PAGE_ALLOCATION_GRANULARITY; @@ -754,18 +770,17 @@ CoreFreePoolI ( // // Determine the pool list // - Index = SIZE_TO_LIST(Size); + Index = SIZE_TO_LIST (Size); DEBUG_CLEAR_MEMORY (Head, Size); // // If it's not on the list, it must be pool pages // - if (Index >= SIZE_TO_LIST (Granularity) || IsGuarded || PageAsPool) { - + if ((Index >= SIZE_TO_LIST (Granularity)) || IsGuarded || PageAsPool) { // // Return the memory pages back to free memory // - NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1; + NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1; NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1); if (IsGuarded) { Head = AdjustPoolHeadF ((EFI_PHYSICAL_ADDRESS)(UINTN)Head); @@ -781,14 +796,12 @@ CoreFreePoolI ( NoPages ); } - } else { - // // Put the pool entry onto the free pool list // - Free = (POOL_FREE *) Head; - ASSERT(Free != NULL); + Free = (POOL_FREE *)Head; + ASSERT (Free != NULL); Free->Signature = POOL_FREE_SIGNATURE; Free->Index = (UINT32)Index; InsertHeadList (&Pool->FreeList[Index], &Free->Link); @@ -798,46 +811,48 @@ CoreFreePoolI ( // entries // NewPage = (CHAR8 *)((UINTN)Free & ~(Granularity - 1)); - Free = (POOL_FREE *) &NewPage[0]; - ASSERT(Free != NULL); + Free = (POOL_FREE *)&NewPage[0]; + ASSERT (Free != NULL); if (Free->Signature == POOL_FREE_SIGNATURE) { - AllFree = TRUE; - Offset = 0; + Offset = 0; while ((Offset < Granularity) && (AllFree)) { - Free = (POOL_FREE *) &NewPage[Offset]; - ASSERT(Free != NULL); + Free = (POOL_FREE *)&NewPage[Offset]; + ASSERT (Free != NULL); if (Free->Signature != POOL_FREE_SIGNATURE) { AllFree = FALSE; } - Offset += LIST_TO_SIZE(Free->Index); + + Offset += LIST_TO_SIZE (Free->Index); } if (AllFree) { - // // All of the pool entries in the same page as Free are free pool // entries // Remove all of these pool entries from the free loop lists. // - Free = (POOL_FREE *) &NewPage[0]; - ASSERT(Free != NULL); + Free = (POOL_FREE *)&NewPage[0]; + ASSERT (Free != NULL); Offset = 0; while (Offset < Granularity) { - Free = (POOL_FREE *) &NewPage[Offset]; - ASSERT(Free != NULL); + Free = (POOL_FREE *)&NewPage[Offset]; + ASSERT (Free != NULL); RemoveEntryList (&Free->Link); - Offset += LIST_TO_SIZE(Free->Index); + Offset += LIST_TO_SIZE (Free->Index); } // // Free the page // - CoreFreePoolPagesI (Pool->MemoryType, (EFI_PHYSICAL_ADDRESS) (UINTN)NewPage, - EFI_SIZE_TO_PAGES (Granularity)); + CoreFreePoolPagesI ( + Pool->MemoryType, + (EFI_PHYSICAL_ADDRESS)(UINTN)NewPage, + EFI_SIZE_TO_PAGES (Granularity) + ); } } } @@ -847,11 +862,10 @@ CoreFreePoolI ( // portion of that memory type has been freed. If it has, then free the // list entry for that memory type // - if (((UINT32) Pool->MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) && Pool->Used == 0) { + if (((UINT32)Pool->MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) && (Pool->Used == 0)) { RemoveEntryList (&Pool->Link); CoreFreePoolI (Pool, NULL); } return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c b/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c index c637e35076..eeb18f6e47 100644 --- a/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c +++ b/MdeModulePkg/Core/Dxe/Misc/DebugImageInfo.c @@ -9,18 +9,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" - EFI_DEBUG_IMAGE_INFO_TABLE_HEADER mDebugInfoTableHeader = { 0, // volatile UINT32 UpdateStatus; 0, // UINT32 TableSize; NULL // EFI_DEBUG_IMAGE_INFO *EfiDebugImageInfoTable; }; -UINTN mMaxTableEntries = 0; +UINTN mMaxTableEntries = 0; EFI_SYSTEM_TABLE_POINTER *mDebugTable = NULL; -#define EFI_DEBUG_TABLE_ENTRY_SIZE (sizeof (VOID *)) +#define EFI_DEBUG_TABLE_ENTRY_SIZE (sizeof (VOID *)) /** Creates and initializes the DebugImageInfo Table. Also creates the configuration @@ -45,9 +44,9 @@ CoreInitializeDebugImageInfoTable ( // Ideally we would update the CRC now as well, but the service may not yet be available. // See comments in the CoreUpdateDebugTableCrc32() function below for details. // - Pages = EFI_SIZE_TO_PAGES (sizeof (EFI_SYSTEM_TABLE_POINTER)); - AlignmentMask = SIZE_4MB - 1; - RealPages = Pages + EFI_SIZE_TO_PAGES (SIZE_4MB); + Pages = EFI_SIZE_TO_PAGES (sizeof (EFI_SYSTEM_TABLE_POINTER)); + AlignmentMask = SIZE_4MB - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (SIZE_4MB); // // Attempt to allocate memory below PcdMaxEfiSystemTablePointerAddress @@ -58,6 +57,7 @@ CoreInitializeDebugImageInfoTable ( if (Memory == 0) { Memory = MAX_ADDRESS; } + Status = CoreAllocatePages ( AllocateMaxAddress, EfiBootServicesData, @@ -69,6 +69,7 @@ CoreInitializeDebugImageInfoTable ( DEBUG ((DEBUG_INFO, "Allocate memory for EFI_SYSTEM_TABLE_POINTER below PcdMaxEfiSystemTablePointerAddress failed. \ Retry to allocate memroy as close to the top of memory as feasible.\n")); } + // // If the initial memory allocation fails, then reattempt allocation // as close to the top of memory as feasible. @@ -88,7 +89,7 @@ CoreInitializeDebugImageInfoTable ( // // Free overallocated pages // - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // @@ -97,6 +98,7 @@ CoreInitializeDebugImageInfoTable ( Status = CoreFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } + Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -117,7 +119,7 @@ CoreInitializeDebugImageInfoTable ( // Initialize EFI_SYSTEM_TABLE_POINTER structure // mDebugTable->Signature = EFI_SYSTEM_TABLE_SIGNATURE; - mDebugTable->EfiSystemTableBase = (EFI_PHYSICAL_ADDRESS) (UINTN) gDxeCoreST; + mDebugTable->EfiSystemTableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)gDxeCoreST; mDebugTable->Crc32 = 0; // @@ -128,7 +130,6 @@ CoreInitializeDebugImageInfoTable ( ASSERT_EFI_ERROR (Status); } - /** Update the CRC32 in the Debug Table. Since the CRC32 service is made available by the Runtime driver, we have to @@ -142,12 +143,11 @@ CoreUpdateDebugTableCrc32 ( VOID ) { - ASSERT(mDebugTable != NULL); + ASSERT (mDebugTable != NULL); mDebugTable->Crc32 = 0; gBS->CalculateCrc32 ((VOID *)mDebugTable, sizeof (EFI_SYSTEM_TABLE_POINTER), &mDebugTable->Crc32); } - /** Adds a new DebugImageInfo structure to the DebugImageInfo Table. Re-Allocates the table if it's not large enough to accomidate another entry. @@ -160,15 +160,15 @@ CoreUpdateDebugTableCrc32 ( **/ VOID CoreNewDebugImageInfoEntry ( - IN UINT32 ImageInfoType, - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_HANDLE ImageHandle + IN UINT32 ImageInfoType, + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_HANDLE ImageHandle ) { - EFI_DEBUG_IMAGE_INFO *Table; - EFI_DEBUG_IMAGE_INFO *NewTable; - UINTN Index; - UINTN TableSize; + EFI_DEBUG_IMAGE_INFO *Table; + EFI_DEBUG_IMAGE_INFO *NewTable; + UINTN Index; + UINTN TableSize; // // Set the flag indicating that we're in the process of updating the table. @@ -185,6 +185,7 @@ CoreNewDebugImageInfoEntry ( while (Table[Index].NormalImage != NULL) { Index++; } + // // There must be an empty entry in the in the table. // @@ -194,11 +195,12 @@ CoreNewDebugImageInfoEntry ( // Table is full, so re-allocate another page for a larger table... // TableSize = mMaxTableEntries * EFI_DEBUG_TABLE_ENTRY_SIZE; - NewTable = AllocateZeroPool (TableSize + EFI_PAGE_SIZE); + NewTable = AllocateZeroPool (TableSize + EFI_PAGE_SIZE); if (NewTable == NULL) { mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS; return; } + // // Copy the old table into the new one // @@ -210,7 +212,7 @@ CoreNewDebugImageInfoEntry ( // // Update the table header // - Table = NewTable; + Table = NewTable; mDebugInfoTableHeader.EfiDebugImageInfoTable = NewTable; // // Enlarge the max table entries and set the first empty entry index to @@ -228,7 +230,7 @@ CoreNewDebugImageInfoEntry ( // // Update the entry // - Table[Index].NormalImage->ImageInfoType = (UINT32) ImageInfoType; + Table[Index].NormalImage->ImageInfoType = (UINT32)ImageInfoType; Table[Index].NormalImage->LoadedImageProtocolInstance = LoadedImage; Table[Index].NormalImage->ImageHandle = ImageHandle; // @@ -237,11 +239,10 @@ CoreNewDebugImageInfoEntry ( mDebugInfoTableHeader.TableSize++; mDebugInfoTableHeader.UpdateStatus |= EFI_DEBUG_IMAGE_INFO_TABLE_MODIFIED; } + mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS; } - - /** Removes and frees an entry from the DebugImageInfo Table. @@ -250,7 +251,7 @@ CoreNewDebugImageInfoEntry ( **/ VOID CoreRemoveDebugImageInfoEntry ( - EFI_HANDLE ImageHandle + EFI_HANDLE ImageHandle ) { EFI_DEBUG_IMAGE_INFO *Table; @@ -261,7 +262,7 @@ CoreRemoveDebugImageInfoEntry ( Table = mDebugInfoTableHeader.EfiDebugImageInfoTable; for (Index = 0; Index < mMaxTableEntries; Index++) { - if (Table[Index].NormalImage != NULL && Table[Index].NormalImage->ImageHandle == ImageHandle) { + if ((Table[Index].NormalImage != NULL) && (Table[Index].NormalImage->ImageHandle == ImageHandle)) { // // Found a match. Free up the record, then NULL the pointer to indicate the slot // is free. @@ -276,5 +277,6 @@ CoreRemoveDebugImageInfoEntry ( break; } } + mDebugInfoTableHeader.UpdateStatus &= ~EFI_DEBUG_IMAGE_INFO_UPDATE_IN_PROGRESS; } diff --git a/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c b/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c index ba4e55fcd0..f47f3bd804 100755 --- a/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c +++ b/MdeModulePkg/Core/Dxe/Misc/InstallConfigurationTable.c @@ -8,9 +8,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" -#define CONFIG_TABLE_SIZE_INCREASED 0x10 +#define CONFIG_TABLE_SIZE_INCREASED 0x10 -UINTN mSystemTableAllocateSize = 0; +UINTN mSystemTableAllocateSize = 0; /** Boot Service called to add, modify, or remove a system configuration table from @@ -30,13 +30,13 @@ UINTN mSystemTableAllocateSize = 0; EFI_STATUS EFIAPI CoreInstallConfigurationTable ( - IN EFI_GUID *Guid, - IN VOID *Table + IN EFI_GUID *Guid, + IN VOID *Table ) { - UINTN Index; - EFI_CONFIGURATION_TABLE *EfiConfigurationTable; - EFI_CONFIGURATION_TABLE *OldTable; + UINTN Index; + EFI_CONFIGURATION_TABLE *EfiConfigurationTable; + EFI_CONFIGURATION_TABLE *OldTable; // // If Guid is NULL, then this operation cannot be performed @@ -88,9 +88,7 @@ CoreInstallConfigurationTable ( &(gDxeCoreST->ConfigurationTable[Index + 1]), (gDxeCoreST->NumberOfTableEntries - Index) * sizeof (EFI_CONFIGURATION_TABLE) ); - } else { - // // No matching GUIDs were found, so this is an add operation. // @@ -110,7 +108,7 @@ CoreInstallConfigurationTable ( // Allocate a table with one additional entry. // mSystemTableAllocateSize += (CONFIG_TABLE_SIZE_INCREASED * sizeof (EFI_CONFIGURATION_TABLE)); - EfiConfigurationTable = AllocateRuntimePool (mSystemTableAllocateSize); + EfiConfigurationTable = AllocateRuntimePool (mSystemTableAllocateSize); if (EfiConfigurationTable == NULL) { // // If a new table could not be allocated, then return an error. @@ -159,7 +157,7 @@ CoreInstallConfigurationTable ( // Fill in the new entry // CopyGuid ((VOID *)&EfiConfigurationTable[Index].VendorGuid, Guid); - EfiConfigurationTable[Index].VendorTable = Table; + EfiConfigurationTable[Index].VendorTable = Table; // // This is an add operation, so increment the number of table entries diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c index 02a67cafa9..e079213711 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c @@ -67,13 +67,13 @@ CoreGetMemoryMapWithSeparatedImageSection ( #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \ ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size))) -#define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('I','P','P','D') +#define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('I','P','P','D') typedef struct { - UINT32 Signature; - UINTN ImageRecordCount; - UINTN CodeSegmentCountMax; - LIST_ENTRY ImageRecordList; + UINT32 Signature; + UINTN ImageRecordCount; + UINTN CodeSegmentCountMax; + LIST_ENTRY ImageRecordList; } IMAGE_PROPERTIES_PRIVATE_DATA; STATIC IMAGE_PROPERTIES_PRIVATE_DATA mImagePropertiesPrivateData = { @@ -83,11 +83,11 @@ STATIC IMAGE_PROPERTIES_PRIVATE_DATA mImagePropertiesPrivateData = { INITIALIZE_LIST_HEAD_VARIABLE (mImagePropertiesPrivateData.ImageRecordList) }; -STATIC EFI_LOCK mMemoryAttributesTableLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +STATIC EFI_LOCK mMemoryAttributesTableLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -BOOLEAN mMemoryAttributesTableEnable = TRUE; -BOOLEAN mMemoryAttributesTableEndOfDxe = FALSE; -EFI_MEMORY_ATTRIBUTES_TABLE *mMemoryAttributesTable = NULL; +BOOLEAN mMemoryAttributesTableEnable = TRUE; +BOOLEAN mMemoryAttributesTableEndOfDxe = FALSE; +EFI_MEMORY_ATTRIBUTES_TABLE *mMemoryAttributesTable = NULL; BOOLEAN mMemoryAttributesTableReadyToBoot = FALSE; /** @@ -99,17 +99,17 @@ InstallMemoryAttributesTable ( VOID ) { - UINTN MemoryMapSize; - EFI_MEMORY_DESCRIPTOR *MemoryMap; - EFI_MEMORY_DESCRIPTOR *MemoryMapStart; - UINTN MapKey; - UINTN DescriptorSize; - UINT32 DescriptorVersion; - UINTN Index; - EFI_STATUS Status; - UINT32 RuntimeEntryCount; - EFI_MEMORY_ATTRIBUTES_TABLE *MemoryAttributesTable; - EFI_MEMORY_DESCRIPTOR *MemoryAttributesEntry; + UINTN MemoryMapSize; + EFI_MEMORY_DESCRIPTOR *MemoryMap; + EFI_MEMORY_DESCRIPTOR *MemoryMapStart; + UINTN MapKey; + UINTN DescriptorSize; + UINT32 DescriptorVersion; + UINTN Index; + EFI_STATUS Status; + UINT32 RuntimeEntryCount; + EFI_MEMORY_ATTRIBUTES_TABLE *MemoryAttributesTable; + EFI_MEMORY_DESCRIPTOR *MemoryAttributesEntry; if (gMemoryMapTerminated) { // @@ -121,7 +121,7 @@ InstallMemoryAttributesTable ( if (!mMemoryAttributesTableEnable) { DEBUG ((DEBUG_VERBOSE, "Cannot install Memory Attributes Table ")); DEBUG ((DEBUG_VERBOSE, "because Runtime Driver Section Alignment is not %dK.\n", RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10)); - return ; + return; } if (mMemoryAttributesTable == NULL) { @@ -130,19 +130,19 @@ InstallMemoryAttributesTable ( // before GetMemoryMap below, as InstallConfigurationTable may allocate runtime // memory for the new entry. // - Status = gBS->InstallConfigurationTable (&gEfiMemoryAttributesTableGuid, (VOID *) (UINTN) MAX_ADDRESS); + Status = gBS->InstallConfigurationTable (&gEfiMemoryAttributesTableGuid, (VOID *)(UINTN)MAX_ADDRESS); ASSERT_EFI_ERROR (Status); } MemoryMapSize = 0; - MemoryMap = NULL; - Status = CoreGetMemoryMapWithSeparatedImageSection ( - &MemoryMapSize, - MemoryMap, - &MapKey, - &DescriptorSize, - &DescriptorVersion - ); + MemoryMap = NULL; + Status = CoreGetMemoryMapWithSeparatedImageSection ( + &MemoryMapSize, + MemoryMap, + &MapKey, + &DescriptorSize, + &DescriptorVersion + ); ASSERT (Status == EFI_BUFFER_TOO_SMALL); do { @@ -161,22 +161,23 @@ InstallMemoryAttributesTable ( } } while (Status == EFI_BUFFER_TOO_SMALL); - MemoryMapStart = MemoryMap; + MemoryMapStart = MemoryMap; RuntimeEntryCount = 0; for (Index = 0; Index < MemoryMapSize/DescriptorSize; Index++) { switch (MemoryMap->Type) { - case EfiRuntimeServicesCode: - case EfiRuntimeServicesData: - RuntimeEntryCount ++; - break; + case EfiRuntimeServicesCode: + case EfiRuntimeServicesData: + RuntimeEntryCount++; + break; } - MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, DescriptorSize); + + MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize); } // // Allocate MemoryAttributesTable // - MemoryAttributesTable = AllocatePool (sizeof(EFI_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount); + MemoryAttributesTable = AllocatePool (sizeof (EFI_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount); ASSERT (MemoryAttributesTable != NULL); MemoryAttributesTable->Version = EFI_MEMORY_ATTRIBUTES_TABLE_VERSION; MemoryAttributesTable->NumberOfEntries = RuntimeEntryCount; @@ -187,24 +188,26 @@ InstallMemoryAttributesTable ( DEBUG ((DEBUG_VERBOSE, " NumberOfEntries - 0x%08x\n", MemoryAttributesTable->NumberOfEntries)); DEBUG ((DEBUG_VERBOSE, " DescriptorSize - 0x%08x\n", MemoryAttributesTable->DescriptorSize)); MemoryAttributesEntry = (EFI_MEMORY_DESCRIPTOR *)(MemoryAttributesTable + 1); - MemoryMap = MemoryMapStart; + MemoryMap = MemoryMapStart; for (Index = 0; Index < MemoryMapSize/DescriptorSize; Index++) { switch (MemoryMap->Type) { - case EfiRuntimeServicesCode: - case EfiRuntimeServicesData: - CopyMem (MemoryAttributesEntry, MemoryMap, DescriptorSize); - MemoryAttributesEntry->Attribute &= (EFI_MEMORY_RO|EFI_MEMORY_XP|EFI_MEMORY_RUNTIME); - DEBUG ((DEBUG_VERBOSE, "Entry (0x%x)\n", MemoryAttributesEntry)); - DEBUG ((DEBUG_VERBOSE, " Type - 0x%x\n", MemoryAttributesEntry->Type)); - DEBUG ((DEBUG_VERBOSE, " PhysicalStart - 0x%016lx\n", MemoryAttributesEntry->PhysicalStart)); - DEBUG ((DEBUG_VERBOSE, " VirtualStart - 0x%016lx\n", MemoryAttributesEntry->VirtualStart)); - DEBUG ((DEBUG_VERBOSE, " NumberOfPages - 0x%016lx\n", MemoryAttributesEntry->NumberOfPages)); - DEBUG ((DEBUG_VERBOSE, " Attribute - 0x%016lx\n", MemoryAttributesEntry->Attribute)); - MemoryAttributesEntry = NEXT_MEMORY_DESCRIPTOR(MemoryAttributesEntry, DescriptorSize); - break; + case EfiRuntimeServicesCode: + case EfiRuntimeServicesData: + CopyMem (MemoryAttributesEntry, MemoryMap, DescriptorSize); + MemoryAttributesEntry->Attribute &= (EFI_MEMORY_RO|EFI_MEMORY_XP|EFI_MEMORY_RUNTIME); + DEBUG ((DEBUG_VERBOSE, "Entry (0x%x)\n", MemoryAttributesEntry)); + DEBUG ((DEBUG_VERBOSE, " Type - 0x%x\n", MemoryAttributesEntry->Type)); + DEBUG ((DEBUG_VERBOSE, " PhysicalStart - 0x%016lx\n", MemoryAttributesEntry->PhysicalStart)); + DEBUG ((DEBUG_VERBOSE, " VirtualStart - 0x%016lx\n", MemoryAttributesEntry->VirtualStart)); + DEBUG ((DEBUG_VERBOSE, " NumberOfPages - 0x%016lx\n", MemoryAttributesEntry->NumberOfPages)); + DEBUG ((DEBUG_VERBOSE, " Attribute - 0x%016lx\n", MemoryAttributesEntry->Attribute)); + MemoryAttributesEntry = NEXT_MEMORY_DESCRIPTOR (MemoryAttributesEntry, DescriptorSize); + break; } - MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, DescriptorSize); + + MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize); } + MemoryMap = MemoryMapStart; FreePool (MemoryMap); @@ -217,6 +220,7 @@ InstallMemoryAttributesTable ( if (mMemoryAttributesTable != NULL) { FreePool (mMemoryAttributesTable); } + mMemoryAttributesTable = MemoryAttributesTable; } @@ -227,14 +231,15 @@ InstallMemoryAttributesTable ( **/ VOID InstallMemoryAttributesTableOnMemoryAllocation ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { // // Install MemoryAttributesTable after ReadyToBoot on runtime memory allocation. // if (mMemoryAttributesTableReadyToBoot && - ((MemoryType == EfiRuntimeServicesCode) || (MemoryType == EfiRuntimeServicesData))) { + ((MemoryType == EfiRuntimeServicesCode) || (MemoryType == EfiRuntimeServicesData))) + { InstallMemoryAttributesTable (); } } @@ -248,8 +253,8 @@ InstallMemoryAttributesTableOnMemoryAllocation ( VOID EFIAPI InstallMemoryAttributesTableOnReadyToBoot ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { InstallMemoryAttributesTable (); @@ -266,8 +271,8 @@ InstallMemoryAttributesTableOnReadyToBoot ( VOID EFIAPI InstallMemoryAttributesTableOnEndOfDxe ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { mMemoryAttributesTableEndOfDxe = TRUE; @@ -315,7 +320,7 @@ CoreInitializeMemoryAttributesTable ( &EndOfDxeEvent ); ASSERT_EFI_ERROR (Status); - return ; + return; } // @@ -335,7 +340,7 @@ CoreInitializeMemoryAttributesTable ( STATIC UINT64 EfiPagesToSize ( - IN UINT64 Pages + IN UINT64 Pages ) { return LShiftU64 (Pages, EFI_PAGE_SHIFT); @@ -355,7 +360,7 @@ EfiPagesToSize ( STATIC UINT64 EfiSizeToPages ( - IN UINT64 Size + IN UINT64 Size ) { return RShiftU64 (Size, EFI_PAGE_SHIFT) + ((((UINTN)Size) & EFI_PAGE_MASK) ? 1 : 0); @@ -401,30 +406,30 @@ SortMemoryMap ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - EFI_MEMORY_DESCRIPTOR TempMemoryMap; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_MEMORY_DESCRIPTOR TempMemoryMap; - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while (MemoryMapEntry < MemoryMapEnd) { while (NextMemoryMapEntry < MemoryMapEnd) { if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) { - CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof (EFI_MEMORY_DESCRIPTOR)); } NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); } - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } - return ; + return; } /** @@ -445,28 +450,29 @@ MergeMemoryMap ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - UINT64 MemoryBlockLength; - EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + UINT64 MemoryBlockLength; + EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NewMemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + *MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { - CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); do { MergeGuardPages (NewMemoryMapEntry, NextMemoryMapEntry->PhysicalStart); - MemoryBlockLength = (UINT64) (EfiPagesToSize (NewMemoryMapEntry->NumberOfPages)); + MemoryBlockLength = (UINT64)(EfiPagesToSize (NewMemoryMapEntry->NumberOfPages)); if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && (NewMemoryMapEntry->Type == NextMemoryMapEntry->Type) && (NewMemoryMapEntry->Attribute == NextMemoryMapEntry->Attribute) && - ((NewMemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) { + ((NewMemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) + { NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; - NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); + NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); continue; } else { MemoryMapEntry = PREVIOUS_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); @@ -474,13 +480,13 @@ MergeMemoryMap ( } } while (TRUE); - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NewMemoryMapEntry, DescriptorSize); } *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap; - return ; + return; } /** @@ -500,30 +506,30 @@ EnforceMemoryMapAttribute ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; MemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { switch (MemoryMapEntry->Type) { - case EfiRuntimeServicesCode: - // do nothing - break; - case EfiRuntimeServicesData: - case EfiMemoryMappedIO: - case EfiMemoryMappedIOPortSpace: - MemoryMapEntry->Attribute |= EFI_MEMORY_XP; - break; - case EfiReservedMemoryType: - case EfiACPIMemoryNVS: - break; + case EfiRuntimeServicesCode: + // do nothing + break; + case EfiRuntimeServicesData: + case EfiMemoryMappedIO: + case EfiMemoryMappedIOPortSpace: + MemoryMapEntry->Attribute |= EFI_MEMORY_XP; + break; + case EfiReservedMemoryType: + case EfiACPIMemoryNVS: + break; } MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } - return ; + return; } /** @@ -541,15 +547,16 @@ GetImageRecordByAddress ( IN UINT64 Length ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *ImageRecordList; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *ImageRecordList; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; for (ImageRecordLink = ImageRecordList->ForwardLink; ImageRecordLink != ImageRecordList; - ImageRecordLink = ImageRecordLink->ForwardLink) { + ImageRecordLink = ImageRecordLink->ForwardLink) + { ImageRecord = CR ( ImageRecordLink, IMAGE_PROPERTIES_RECORD, @@ -558,7 +565,8 @@ GetImageRecordByAddress ( ); if ((Buffer <= ImageRecord->ImageBase) && - (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize)) { + (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize)) + { return ImageRecord; } } @@ -582,28 +590,28 @@ GetImageRecordByAddress ( STATIC UINTN SetNewRecord ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord, - IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, - IN EFI_MEMORY_DESCRIPTOR *OldRecord, - IN UINTN DescriptorSize + IN IMAGE_PROPERTIES_RECORD *ImageRecord, + IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, + IN EFI_MEMORY_DESCRIPTOR *OldRecord, + IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR TempRecord; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; - UINTN NewRecordCount; - UINT64 PhysicalEnd; - UINT64 ImageEnd; - - CopyMem (&TempRecord, OldRecord, sizeof(EFI_MEMORY_DESCRIPTOR)); - PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize(TempRecord.NumberOfPages); + EFI_MEMORY_DESCRIPTOR TempRecord; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; + UINTN NewRecordCount; + UINT64 PhysicalEnd; + UINT64 ImageEnd; + + CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR)); + PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages); NewRecordCount = 0; ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( @@ -621,11 +629,11 @@ SetNewRecord ( NewRecord->Type = TempRecord.Type; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; - NewRecord->NumberOfPages = EfiSizeToPages(ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart); + NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart); NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP; if (NewRecord->NumberOfPages != 0) { NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); - NewRecordCount ++; + NewRecordCount++; } // @@ -634,15 +642,15 @@ SetNewRecord ( NewRecord->Type = TempRecord.Type; NewRecord->PhysicalStart = ImageRecordCodeSection->CodeSegmentBase; NewRecord->VirtualStart = 0; - NewRecord->NumberOfPages = EfiSizeToPages(ImageRecordCodeSection->CodeSegmentSize); + NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize); NewRecord->Attribute = (TempRecord.Attribute & (~EFI_MEMORY_XP)) | EFI_MEMORY_RO; if (NewRecord->NumberOfPages != 0) { NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); - NewRecordCount ++; + NewRecordCount++; } - TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages(ImageRecordCodeSection->CodeSegmentSize)); - TempRecord.NumberOfPages = EfiSizeToPages(PhysicalEnd - TempRecord.PhysicalStart); + TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize)); + TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart); if (TempRecord.NumberOfPages == 0) { break; } @@ -660,7 +668,7 @@ SetNewRecord ( NewRecord->VirtualStart = 0; NewRecord->NumberOfPages = EfiSizeToPages (ImageEnd - TempRecord.PhysicalStart); NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP; - NewRecordCount ++; + NewRecordCount++; } return NewRecordCount; @@ -678,25 +686,26 @@ SetNewRecord ( STATIC UINTN GetMaxSplitRecordCount ( - IN EFI_MEMORY_DESCRIPTOR *OldRecord + IN EFI_MEMORY_DESCRIPTOR *OldRecord ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - UINTN SplitRecordCount; - UINT64 PhysicalStart; - UINT64 PhysicalEnd; + IMAGE_PROPERTIES_RECORD *ImageRecord; + UINTN SplitRecordCount; + UINT64 PhysicalStart; + UINT64 PhysicalEnd; SplitRecordCount = 0; - PhysicalStart = OldRecord->PhysicalStart; - PhysicalEnd = OldRecord->PhysicalStart + EfiPagesToSize(OldRecord->NumberOfPages); + PhysicalStart = OldRecord->PhysicalStart; + PhysicalEnd = OldRecord->PhysicalStart + EfiPagesToSize (OldRecord->NumberOfPages); do { ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart); if (ImageRecord == NULL) { break; } + SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 1); - PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; + PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd)); if (SplitRecordCount != 0) { @@ -724,20 +733,20 @@ GetMaxSplitRecordCount ( STATIC UINTN SplitRecord ( - IN EFI_MEMORY_DESCRIPTOR *OldRecord, - IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, - IN UINTN MaxSplitRecordCount, - IN UINTN DescriptorSize + IN EFI_MEMORY_DESCRIPTOR *OldRecord, + IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, + IN UINTN MaxSplitRecordCount, + IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR TempRecord; - IMAGE_PROPERTIES_RECORD *ImageRecord; - IMAGE_PROPERTIES_RECORD *NewImageRecord; - UINT64 PhysicalStart; - UINT64 PhysicalEnd; - UINTN NewRecordCount; - UINTN TotalNewRecordCount; - BOOLEAN IsLastRecordData; + EFI_MEMORY_DESCRIPTOR TempRecord; + IMAGE_PROPERTIES_RECORD *ImageRecord; + IMAGE_PROPERTIES_RECORD *NewImageRecord; + UINT64 PhysicalStart; + UINT64 PhysicalEnd; + UINTN NewRecordCount; + UINTN TotalNewRecordCount; + BOOLEAN IsLastRecordData; if (MaxSplitRecordCount == 0) { CopyMem (NewRecord, OldRecord, DescriptorSize); @@ -749,9 +758,9 @@ SplitRecord ( // // Override previous record // - CopyMem (&TempRecord, OldRecord, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR)); PhysicalStart = TempRecord.PhysicalStart; - PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize(TempRecord.NumberOfPages); + PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages); ImageRecord = NULL; do { @@ -764,44 +773,47 @@ SplitRecord ( // // If this is still address in this record, need record. // - NewRecord = PREVIOUS_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); + NewRecord = PREVIOUS_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); IsLastRecordData = FALSE; if ((NewRecord->Attribute & EFI_MEMORY_XP) != 0) { IsLastRecordData = TRUE; } + if (IsLastRecordData) { // // Last record is DATA, just merge it. // - NewRecord->NumberOfPages = EfiSizeToPages(PhysicalEnd - NewRecord->PhysicalStart); + NewRecord->NumberOfPages = EfiSizeToPages (PhysicalEnd - NewRecord->PhysicalStart); } else { // // Last record is CODE, create a new DATA entry. // - NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); + NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); NewRecord->Type = TempRecord.Type; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; NewRecord->NumberOfPages = TempRecord.NumberOfPages; NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP; - TotalNewRecordCount ++; + TotalNewRecordCount++; } } + break; } + ImageRecord = NewImageRecord; // // Set new record // - NewRecordCount = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize); + NewRecordCount = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize); TotalNewRecordCount += NewRecordCount; - NewRecord = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize); + NewRecord = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize); // // Update PhysicalStart, in order to exclude the image buffer already splitted. // - PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; + PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; TempRecord.PhysicalStart = PhysicalStart; TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - PhysicalStart); } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd)); @@ -868,12 +880,12 @@ SplitTable ( IN UINTN DescriptorSize ) { - INTN IndexOld; - INTN IndexNew; - UINTN MaxSplitRecordCount; - UINTN RealSplitRecordCount; - UINTN TotalSplitRecordCount; - UINTN AdditionalRecordCount; + INTN IndexOld; + INTN IndexNew; + UINTN MaxSplitRecordCount; + UINTN RealSplitRecordCount; + UINTN TotalSplitRecordCount; + UINTN AdditionalRecordCount; AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 1) * mImagePropertiesPrivateData.ImageRecordCount; @@ -886,12 +898,12 @@ SplitTable ( // Let new record point to end of full MemoryMap buffer. // IndexNew = ((*MemoryMapSize) / DescriptorSize) - 1 + AdditionalRecordCount; - for (; IndexOld >= 0; IndexOld--) { + for ( ; IndexOld >= 0; IndexOld--) { MaxSplitRecordCount = GetMaxSplitRecordCount ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize)); // // Split this MemoryMap record // - IndexNew -= MaxSplitRecordCount; + IndexNew -= MaxSplitRecordCount; RealSplitRecordCount = SplitRecord ( (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize), (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexNew * DescriptorSize), @@ -906,10 +918,11 @@ SplitTable ( ((UINT8 *)MemoryMap + IndexNew * DescriptorSize), RealSplitRecordCount * DescriptorSize ); - IndexNew = IndexNew + MaxSplitRecordCount - RealSplitRecordCount; + IndexNew = IndexNew + MaxSplitRecordCount - RealSplitRecordCount; TotalSplitRecordCount += RealSplitRecordCount; - IndexNew --; + IndexNew--; } + // // Move all records to the beginning. // @@ -936,7 +949,7 @@ SplitTable ( // MergeMemoryMap (MemoryMap, MemoryMapSize, DescriptorSize); - return ; + return; } /** @@ -1001,7 +1014,7 @@ CoreGetMemoryMapWithSeparatedImageSection ( AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 1) * mImagePropertiesPrivateData.ImageRecordCount; OldMemoryMapSize = *MemoryMapSize; - Status = CoreGetMemoryMap (MemoryMapSize, MemoryMap, MapKey, DescriptorSize, DescriptorVersion); + Status = CoreGetMemoryMap (MemoryMapSize, MemoryMap, MapKey, DescriptorSize, DescriptorVersion); if (Status == EFI_BUFFER_TOO_SMALL) { *MemoryMapSize = *MemoryMapSize + (*DescriptorSize) * AdditionalRecordCount; } else if (Status == EFI_SUCCESS) { @@ -1040,7 +1053,8 @@ SetMemoryAttributesTableSectionAlignment ( ) { if (((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) && - mMemoryAttributesTableEnable) { + mMemoryAttributesTableEnable) + { DEBUG ((DEBUG_VERBOSE, "SetMemoryAttributesTableSectionAlignment - Clear\n")); mMemoryAttributesTableEnable = FALSE; } @@ -1055,11 +1069,11 @@ SetMemoryAttributesTableSectionAlignment ( STATIC VOID SwapImageRecordCodeSection ( - IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *FirstImageRecordCodeSection, - IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *SecondImageRecordCodeSection + IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *FirstImageRecordCodeSection, + IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *SecondImageRecordCodeSection ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION TempImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION TempImageRecordCodeSection; TempImageRecordCodeSection.CodeSegmentBase = FirstImageRecordCodeSection->CodeSegmentBase; TempImageRecordCodeSection.CodeSegmentSize = FirstImageRecordCodeSection->CodeSegmentSize; @@ -1078,21 +1092,21 @@ SwapImageRecordCodeSection ( **/ VOID SortImageRecordCodeSection ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *NextImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *NextImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *NextImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *NextImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; - ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; + ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( ImageRecordCodeSectionLink, @@ -1110,10 +1124,11 @@ SortImageRecordCodeSection ( if (ImageRecordCodeSection->CodeSegmentBase > NextImageRecordCodeSection->CodeSegmentBase) { SwapImageRecordCodeSection (ImageRecordCodeSection, NextImageRecordCodeSection); } + NextImageRecordCodeSectionLink = NextImageRecordCodeSectionLink->ForwardLink; } - ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; } } @@ -1128,22 +1143,22 @@ SortImageRecordCodeSection ( **/ BOOLEAN IsImageRecordCodeSectionValid ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *LastImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *LastImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; DEBUG ((DEBUG_VERBOSE, "ImageCode SegmentCount - 0x%x\n", ImageRecord->CodeSegmentCount)); ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; - LastImageRecordCodeSection = NULL; + LastImageRecordCodeSection = NULL; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( ImageRecordCodeSectionLink, @@ -1154,15 +1169,19 @@ IsImageRecordCodeSectionValid ( if (ImageRecordCodeSection->CodeSegmentSize == 0) { return FALSE; } + if (ImageRecordCodeSection->CodeSegmentBase < ImageRecord->ImageBase) { return FALSE; } + if (ImageRecordCodeSection->CodeSegmentBase >= MAX_ADDRESS - ImageRecordCodeSection->CodeSegmentSize) { return FALSE; } + if ((ImageRecordCodeSection->CodeSegmentBase + ImageRecordCodeSection->CodeSegmentSize) > (ImageRecord->ImageBase + ImageRecord->ImageSize)) { return FALSE; } + if (LastImageRecordCodeSection != NULL) { if ((LastImageRecordCodeSection->CodeSegmentBase + LastImageRecordCodeSection->CodeSegmentSize) > ImageRecordCodeSection->CodeSegmentBase) { return FALSE; @@ -1185,22 +1204,22 @@ IsImageRecordCodeSectionValid ( STATIC VOID SwapImageRecord ( - IN IMAGE_PROPERTIES_RECORD *FirstImageRecord, - IN IMAGE_PROPERTIES_RECORD *SecondImageRecord + IN IMAGE_PROPERTIES_RECORD *FirstImageRecord, + IN IMAGE_PROPERTIES_RECORD *SecondImageRecord ) { - IMAGE_PROPERTIES_RECORD TempImageRecord; + IMAGE_PROPERTIES_RECORD TempImageRecord; - TempImageRecord.ImageBase = FirstImageRecord->ImageBase; - TempImageRecord.ImageSize = FirstImageRecord->ImageSize; + TempImageRecord.ImageBase = FirstImageRecord->ImageBase; + TempImageRecord.ImageSize = FirstImageRecord->ImageSize; TempImageRecord.CodeSegmentCount = FirstImageRecord->CodeSegmentCount; - FirstImageRecord->ImageBase = SecondImageRecord->ImageBase; - FirstImageRecord->ImageSize = SecondImageRecord->ImageSize; + FirstImageRecord->ImageBase = SecondImageRecord->ImageBase; + FirstImageRecord->ImageSize = SecondImageRecord->ImageSize; FirstImageRecord->CodeSegmentCount = SecondImageRecord->CodeSegmentCount; - SecondImageRecord->ImageBase = TempImageRecord.ImageBase; - SecondImageRecord->ImageSize = TempImageRecord.ImageSize; + SecondImageRecord->ImageBase = TempImageRecord.ImageBase; + SecondImageRecord->ImageSize = TempImageRecord.ImageSize; SecondImageRecord->CodeSegmentCount = TempImageRecord.CodeSegmentCount; SwapListEntries (&FirstImageRecord->CodeSegmentList, &SecondImageRecord->CodeSegmentList); @@ -1215,18 +1234,18 @@ SortImageRecord ( VOID ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - IMAGE_PROPERTIES_RECORD *NextImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *NextImageRecordLink; - LIST_ENTRY *ImageRecordEndLink; - LIST_ENTRY *ImageRecordList; + IMAGE_PROPERTIES_RECORD *ImageRecord; + IMAGE_PROPERTIES_RECORD *NextImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *NextImageRecordLink; + LIST_ENTRY *ImageRecordEndLink; + LIST_ENTRY *ImageRecordList; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; - ImageRecordLink = ImageRecordList->ForwardLink; + ImageRecordLink = ImageRecordList->ForwardLink; NextImageRecordLink = ImageRecordLink->ForwardLink; - ImageRecordEndLink = ImageRecordList; + ImageRecordEndLink = ImageRecordList; while (ImageRecordLink != ImageRecordEndLink) { ImageRecord = CR ( ImageRecordLink, @@ -1244,10 +1263,11 @@ SortImageRecord ( if (ImageRecord->ImageBase > NextImageRecord->ImageBase) { SwapImageRecord (ImageRecord, NextImageRecord); } + NextImageRecordLink = NextImageRecordLink->ForwardLink; } - ImageRecordLink = ImageRecordLink->ForwardLink; + ImageRecordLink = ImageRecordLink->ForwardLink; NextImageRecordLink = ImageRecordLink->ForwardLink; } } @@ -1262,30 +1282,31 @@ InsertImageRecord ( IN EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage ) { - VOID *ImageAddress; - EFI_IMAGE_DOS_HEADER *DosHdr; - UINT32 PeCoffHeaderOffset; - UINT32 SectionAlignment; - EFI_IMAGE_SECTION_HEADER *Section; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; - UINT8 *Name; - UINTN Index; - IMAGE_PROPERTIES_RECORD *ImageRecord; - CHAR8 *PdbPointer; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + VOID *ImageAddress; + EFI_IMAGE_DOS_HEADER *DosHdr; + UINT32 PeCoffHeaderOffset; + UINT32 SectionAlignment; + EFI_IMAGE_SECTION_HEADER *Section; + EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; + UINT8 *Name; + UINTN Index; + IMAGE_PROPERTIES_RECORD *ImageRecord; + CHAR8 *PdbPointer; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%x\n", RuntimeImage)); DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%016lx - 0x%016lx\n", (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize)); if (mMemoryAttributesTableEndOfDxe) { DEBUG ((DEBUG_INFO, "Do not insert runtime image record after EndOfDxe\n")); - return ; + return; } - ImageRecord = AllocatePool (sizeof(*ImageRecord)); + ImageRecord = AllocatePool (sizeof (*ImageRecord)); if (ImageRecord == NULL) { - return ; + return; } + ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE; DEBUG ((DEBUG_VERBOSE, "ImageRecordCount - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount)); @@ -1298,7 +1319,7 @@ InsertImageRecord ( ImageAddress = RuntimeImage->ImageBase; - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_VERBOSE, " Image - %a\n", PdbPointer)); } @@ -1306,13 +1327,13 @@ InsertImageRecord ( // // Check PE/COFF image // - DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress; + DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress; PeCoffHeaderOffset = 0; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { PeCoffHeaderOffset = DosHdr->e_lfanew; } - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset); if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { DEBUG ((DEBUG_VERBOSE, "Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature)); // It might be image in SMM. @@ -1323,29 +1344,34 @@ InsertImageRecord ( // Get SectionAlignment // if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { - SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; } else { - SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; } SetMemoryAttributesTableSectionAlignment (SectionAlignment); if ((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) { - DEBUG ((DEBUG_WARN, "!!!!!!!! InsertImageRecord - Section Alignment(0x%x) is not %dK !!!!!!!!\n", - SectionAlignment, RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10)); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + DEBUG (( + DEBUG_WARN, + "!!!!!!!! InsertImageRecord - Section Alignment(0x%x) is not %dK !!!!!!!!\n", + SectionAlignment, + RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10 + )); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_WARN, "!!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } - Section = (EFI_IMAGE_SECTION_HEADER *) ( - (UINT8 *) (UINTN) ImageAddress + - PeCoffHeaderOffset + - sizeof(UINT32) + - sizeof(EFI_IMAGE_FILE_HEADER) + - Hdr.Pe32->FileHeader.SizeOfOptionalHeader - ); + Section = (EFI_IMAGE_SECTION_HEADER *)( + (UINT8 *)(UINTN)ImageAddress + + PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + Hdr.Pe32->FileHeader.SizeOfOptionalHeader + ); ImageRecord->CodeSegmentCount = 0; InitializeListHead (&ImageRecord->CodeSegmentList); for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) { @@ -1377,10 +1403,11 @@ InsertImageRecord ( // // Step 2: record code section // - ImageRecordCodeSection = AllocatePool (sizeof(*ImageRecordCodeSection)); + ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection)); if (ImageRecordCodeSection == NULL) { - return ; + return; } + ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE; ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress; @@ -1396,10 +1423,11 @@ InsertImageRecord ( if (ImageRecord->CodeSegmentCount == 0) { SetMemoryAttributesTableSectionAlignment (1); DEBUG ((DEBUG_ERROR, "!!!!!!!! InsertImageRecord - CodeSegmentCount is 0 !!!!!!!!\n")); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_ERROR, "!!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } @@ -1425,7 +1453,7 @@ InsertImageRecord ( SortImageRecord (); Finish: - return ; + return; } /** @@ -1443,15 +1471,16 @@ FindImageRecord ( IN UINT64 ImageSize ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *ImageRecordList; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *ImageRecordList; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; for (ImageRecordLink = ImageRecordList->ForwardLink; ImageRecordLink != ImageRecordList; - ImageRecordLink = ImageRecordLink->ForwardLink) { + ImageRecordLink = ImageRecordLink->ForwardLink) + { ImageRecord = CR ( ImageRecordLink, IMAGE_PROPERTIES_RECORD, @@ -1460,7 +1489,8 @@ FindImageRecord ( ); if ((ImageBase == ImageRecord->ImageBase) && - (ImageSize == ImageRecord->ImageSize)) { + (ImageSize == ImageRecord->ImageSize)) + { return ImageRecord; } } @@ -1478,22 +1508,22 @@ RemoveImageRecord ( IN EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *CodeSegmentListHead; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *CodeSegmentListHead; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; DEBUG ((DEBUG_VERBOSE, "RemoveImageRecord - 0x%x\n", RuntimeImage)); DEBUG ((DEBUG_VERBOSE, "RemoveImageRecord - 0x%016lx - 0x%016lx\n", (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize)); if (mMemoryAttributesTableEndOfDxe) { DEBUG ((DEBUG_INFO, "Do not remove runtime image record after EndOfDxe\n")); - return ; + return; } ImageRecord = FindImageRecord ((EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize); if (ImageRecord == NULL) { DEBUG ((DEBUG_ERROR, "!!!!!!!! ImageRecord not found !!!!!!!!\n")); - return ; + return; } CodeSegmentListHead = &ImageRecord->CodeSegmentList; diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c index 7d1daf0b19..b89ab046fa 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c @@ -45,26 +45,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Image type definitions // -#define IMAGE_UNKNOWN 0x00000001 -#define IMAGE_FROM_FV 0x00000002 +#define IMAGE_UNKNOWN 0x00000001 +#define IMAGE_FROM_FV 0x00000002 // // Protection policy bit definition // -#define DO_NOT_PROTECT 0x00000000 -#define PROTECT_IF_ALIGNED_ELSE_ALLOW 0x00000001 +#define DO_NOT_PROTECT 0x00000000 +#define PROTECT_IF_ALIGNED_ELSE_ALLOW 0x00000001 -#define MEMORY_TYPE_OS_RESERVED_MIN 0x80000000 -#define MEMORY_TYPE_OEM_RESERVED_MIN 0x70000000 +#define MEMORY_TYPE_OS_RESERVED_MIN 0x80000000 +#define MEMORY_TYPE_OEM_RESERVED_MIN 0x70000000 #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \ ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size))) -UINT32 mImageProtectionPolicy; +UINT32 mImageProtectionPolicy; -extern LIST_ENTRY mGcdMemorySpaceMap; +extern LIST_ENTRY mGcdMemorySpaceMap; -STATIC LIST_ENTRY mProtectedImageRecordList; +STATIC LIST_ENTRY mProtectedImageRecordList; /** Sort code section in image record, based upon CodeSegmentBase from low to high. @@ -73,7 +73,7 @@ STATIC LIST_ENTRY mProtectedImageRecordList; **/ VOID SortImageRecordCodeSection ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ); /** @@ -86,7 +86,7 @@ SortImageRecordCodeSection ( **/ BOOLEAN IsImageRecordCodeSectionValid ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ); /** @@ -99,12 +99,12 @@ IsImageRecordCodeSectionValid ( **/ UINT32 GetImageType ( - IN CONST EFI_DEVICE_PATH_PROTOCOL *File + IN CONST EFI_DEVICE_PATH_PROTOCOL *File ) { - EFI_STATUS Status; - EFI_HANDLE DeviceHandle; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + EFI_STATUS Status; + EFI_HANDLE DeviceHandle; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; if (File == NULL) { return IMAGE_UNKNOWN; @@ -113,13 +113,13 @@ GetImageType ( // // First check to see if File is from a Firmware Volume // - DeviceHandle = NULL; - TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *) File; - Status = gBS->LocateDevicePath ( - &gEfiFirmwareVolume2ProtocolGuid, - &TempDevicePath, - &DeviceHandle - ); + DeviceHandle = NULL; + TempDevicePath = (EFI_DEVICE_PATH_PROTOCOL *)File; + Status = gBS->LocateDevicePath ( + &gEfiFirmwareVolume2ProtocolGuid, + &TempDevicePath, + &DeviceHandle + ); if (!EFI_ERROR (Status)) { Status = gBS->OpenProtocol ( DeviceHandle, @@ -133,6 +133,7 @@ GetImageType ( return IMAGE_FROM_FV; } } + return IMAGE_UNKNOWN; } @@ -165,13 +166,13 @@ GetProtectionPolicyFromImageType ( **/ UINT32 GetUefiImageProtectionPolicy ( - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath ) { - BOOLEAN InSmm; - UINT32 ImageType; - UINT32 ProtectionPolicy; + BOOLEAN InSmm; + UINT32 ImageType; + UINT32 ProtectionPolicy; // // Check SMM @@ -180,6 +181,7 @@ GetUefiImageProtectionPolicy ( if (gSmmBase2 != NULL) { gSmmBase2->InSmm (gSmmBase2, &InSmm); } + if (InSmm) { return FALSE; } @@ -192,11 +194,11 @@ GetUefiImageProtectionPolicy ( } else { ImageType = GetImageType (LoadedImageDevicePath); } + ProtectionPolicy = GetProtectionPolicyFromImageType (ImageType); return ProtectionPolicy; } - /** Set UEFI image memory attributes. @@ -206,23 +208,23 @@ GetUefiImageProtectionPolicy ( **/ VOID SetUefiImageMemoryAttributes ( - IN UINT64 BaseAddress, - IN UINT64 Length, - IN UINT64 Attributes + IN UINT64 BaseAddress, + IN UINT64 Length, + IN UINT64 Attributes ) { EFI_STATUS Status; EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor; UINT64 FinalAttributes; - Status = CoreGetMemorySpaceDescriptor(BaseAddress, &Descriptor); - ASSERT_EFI_ERROR(Status); + Status = CoreGetMemorySpaceDescriptor (BaseAddress, &Descriptor); + ASSERT_EFI_ERROR (Status); FinalAttributes = (Descriptor.Attributes & EFI_CACHE_ATTRIBUTE_MASK) | (Attributes & EFI_MEMORY_ATTRIBUTE_MASK); DEBUG ((DEBUG_INFO, "SetUefiImageMemoryAttributes - 0x%016lx - 0x%016lx (0x%016lx)\n", BaseAddress, Length, FinalAttributes)); - ASSERT(gCpu != NULL); + ASSERT (gCpu != NULL); gCpu->SetMemoryAttributes (gCpu, BaseAddress, Length, FinalAttributes); } @@ -233,22 +235,22 @@ SetUefiImageMemoryAttributes ( **/ VOID SetUefiImageProtectionAttributes ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; - UINT64 CurrentBase; - UINT64 ImageEnd; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; + UINT64 CurrentBase; + UINT64 ImageEnd; ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; CurrentBase = ImageRecord->ImageBase; ImageEnd = ImageRecord->ImageBase + ImageRecord->ImageSize; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( @@ -270,6 +272,7 @@ SetUefiImageProtectionAttributes ( EFI_MEMORY_XP ); } + // // CODE // @@ -280,6 +283,7 @@ SetUefiImageProtectionAttributes ( ); CurrentBase = ImageRecordCodeSection->CodeSegmentBase + ImageRecordCodeSection->CodeSegmentSize; } + // // Last DATA // @@ -294,7 +298,8 @@ SetUefiImageProtectionAttributes ( EFI_MEMORY_XP ); } - return ; + + return; } /** @@ -315,24 +320,24 @@ IsMemoryProtectionSectionAligned ( UINT32 PageAlignment; switch (MemoryType) { - case EfiRuntimeServicesCode: - case EfiACPIMemoryNVS: - PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; - break; - case EfiRuntimeServicesData: - case EfiACPIReclaimMemory: - ASSERT (FALSE); - PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; - break; - case EfiBootServicesCode: - case EfiLoaderCode: - case EfiReservedMemoryType: - PageAlignment = EFI_PAGE_SIZE; - break; - default: - ASSERT (FALSE); - PageAlignment = EFI_PAGE_SIZE; - break; + case EfiRuntimeServicesCode: + case EfiACPIMemoryNVS: + PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; + break; + case EfiRuntimeServicesData: + case EfiACPIReclaimMemory: + ASSERT (FALSE); + PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY; + break; + case EfiBootServicesCode: + case EfiLoaderCode: + case EfiReservedMemoryType: + PageAlignment = EFI_PAGE_SIZE; + break; + default: + ASSERT (FALSE); + PageAlignment = EFI_PAGE_SIZE; + break; } if ((SectionAlignment & (PageAlignment - 1)) != 0) { @@ -349,11 +354,11 @@ IsMemoryProtectionSectionAligned ( **/ VOID FreeImageRecord ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - LIST_ENTRY *CodeSegmentListHead; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + LIST_ENTRY *CodeSegmentListHead; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; CodeSegmentListHead = &ImageRecord->CodeSegmentList; while (!IsListEmpty (CodeSegmentListHead)) { @@ -370,6 +375,7 @@ FreeImageRecord ( if (ImageRecord->Link.ForwardLink != NULL) { RemoveEntryList (&ImageRecord->Link); } + FreePool (ImageRecord); } @@ -381,46 +387,47 @@ FreeImageRecord ( **/ VOID ProtectUefiImage ( - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath ) { - VOID *ImageAddress; - EFI_IMAGE_DOS_HEADER *DosHdr; - UINT32 PeCoffHeaderOffset; - UINT32 SectionAlignment; - EFI_IMAGE_SECTION_HEADER *Section; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; - UINT8 *Name; - UINTN Index; - IMAGE_PROPERTIES_RECORD *ImageRecord; - CHAR8 *PdbPointer; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - BOOLEAN IsAligned; - UINT32 ProtectionPolicy; + VOID *ImageAddress; + EFI_IMAGE_DOS_HEADER *DosHdr; + UINT32 PeCoffHeaderOffset; + UINT32 SectionAlignment; + EFI_IMAGE_SECTION_HEADER *Section; + EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; + UINT8 *Name; + UINTN Index; + IMAGE_PROPERTIES_RECORD *ImageRecord; + CHAR8 *PdbPointer; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + BOOLEAN IsAligned; + UINT32 ProtectionPolicy; DEBUG ((DEBUG_INFO, "ProtectUefiImageCommon - 0x%x\n", LoadedImage)); DEBUG ((DEBUG_INFO, " - 0x%016lx - 0x%016lx\n", (EFI_PHYSICAL_ADDRESS)(UINTN)LoadedImage->ImageBase, LoadedImage->ImageSize)); if (gCpu == NULL) { - return ; + return; } ProtectionPolicy = GetUefiImageProtectionPolicy (LoadedImage, LoadedImageDevicePath); switch (ProtectionPolicy) { - case DO_NOT_PROTECT: - return ; - case PROTECT_IF_ALIGNED_ELSE_ALLOW: - break; - default: - ASSERT(FALSE); - return ; + case DO_NOT_PROTECT: + return; + case PROTECT_IF_ALIGNED_ELSE_ALLOW: + break; + default: + ASSERT (FALSE); + return; } - ImageRecord = AllocateZeroPool (sizeof(*ImageRecord)); + ImageRecord = AllocateZeroPool (sizeof (*ImageRecord)); if (ImageRecord == NULL) { - return ; + return; } + ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE; // @@ -431,7 +438,7 @@ ProtectUefiImage ( ImageAddress = LoadedImage->ImageBase; - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_VERBOSE, " Image - %a\n", PdbPointer)); } @@ -439,13 +446,13 @@ ProtectUefiImage ( // // Check PE/COFF image // - DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress; + DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress; PeCoffHeaderOffset = 0; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { PeCoffHeaderOffset = DosHdr->e_lfanew; } - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset); if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { DEBUG ((DEBUG_VERBOSE, "Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature)); // It might be image in SMM. @@ -456,29 +463,33 @@ ProtectUefiImage ( // Get SectionAlignment // if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { - SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; } else { - SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; } IsAligned = IsMemoryProtectionSectionAligned (SectionAlignment, LoadedImage->ImageCodeType); if (!IsAligned) { - DEBUG ((DEBUG_VERBOSE, "!!!!!!!! ProtectUefiImageCommon - Section Alignment(0x%x) is incorrect !!!!!!!!\n", - SectionAlignment)); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + DEBUG (( + DEBUG_VERBOSE, + "!!!!!!!! ProtectUefiImageCommon - Section Alignment(0x%x) is incorrect !!!!!!!!\n", + SectionAlignment + )); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_VERBOSE, "!!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } - Section = (EFI_IMAGE_SECTION_HEADER *) ( - (UINT8 *) (UINTN) ImageAddress + - PeCoffHeaderOffset + - sizeof(UINT32) + - sizeof(EFI_IMAGE_FILE_HEADER) + - Hdr.Pe32->FileHeader.SizeOfOptionalHeader - ); + Section = (EFI_IMAGE_SECTION_HEADER *)( + (UINT8 *)(UINTN)ImageAddress + + PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + Hdr.Pe32->FileHeader.SizeOfOptionalHeader + ); ImageRecord->CodeSegmentCount = 0; InitializeListHead (&ImageRecord->CodeSegmentList); for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) { @@ -518,14 +529,15 @@ ProtectUefiImage ( // // Step 2: record code section // - ImageRecordCodeSection = AllocatePool (sizeof(*ImageRecordCodeSection)); + ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection)); if (ImageRecordCodeSection == NULL) { - return ; + return; } + ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE; ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress; - ImageRecordCodeSection->CodeSegmentSize = ALIGN_VALUE(Section[Index].SizeOfRawData, SectionAlignment); + ImageRecordCodeSection->CodeSegmentSize = ALIGN_VALUE (Section[Index].SizeOfRawData, SectionAlignment); DEBUG ((DEBUG_VERBOSE, "ImageCode: 0x%016lx - 0x%016lx\n", ImageRecordCodeSection->CodeSegmentBase, ImageRecordCodeSection->CodeSegmentSize)); @@ -544,10 +556,11 @@ ProtectUefiImage ( // of course). // DEBUG ((DEBUG_WARN, "!!!!!!!! ProtectUefiImageCommon - CodeSegmentCount is 0 !!!!!!!!\n")); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_WARN, "!!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } @@ -567,7 +580,7 @@ ProtectUefiImage ( // Round up the ImageSize, some CPU arch may return EFI_UNSUPPORTED if ImageSize is not aligned. // Given that the loader always allocates full pages, we know the space after the image is not used. // - ImageRecord->ImageSize = ALIGN_VALUE(LoadedImage->ImageSize, EFI_PAGE_SIZE); + ImageRecord->ImageSize = ALIGN_VALUE (LoadedImage->ImageSize, EFI_PAGE_SIZE); // // CPU ARCH present. Update memory attribute directly. @@ -580,7 +593,7 @@ ProtectUefiImage ( InsertTailList (&mProtectedImageRecordList, &ImageRecord->Link); Finish: - return ; + return; } /** @@ -591,17 +604,18 @@ Finish: **/ VOID UnprotectUefiImage ( - IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, - IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath + IN EFI_LOADED_IMAGE_PROTOCOL *LoadedImage, + IN EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *ImageRecordLink; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *ImageRecordLink; - if (PcdGet32(PcdImageProtectionPolicy) != 0) { + if (PcdGet32 (PcdImageProtectionPolicy) != 0) { for (ImageRecordLink = mProtectedImageRecordList.ForwardLink; ImageRecordLink != &mProtectedImageRecordList; - ImageRecordLink = ImageRecordLink->ForwardLink) { + ImageRecordLink = ImageRecordLink->ForwardLink) + { ImageRecord = CR ( ImageRecordLink, IMAGE_PROPERTIES_RECORD, @@ -610,9 +624,11 @@ UnprotectUefiImage ( ); if (ImageRecord->ImageBase == (EFI_PHYSICAL_ADDRESS)(UINTN)LoadedImage->ImageBase) { - SetUefiImageMemoryAttributes (ImageRecord->ImageBase, - ImageRecord->ImageSize, - 0); + SetUefiImageMemoryAttributes ( + ImageRecord->ImageBase, + ImageRecord->ImageSize, + 0 + ); FreeImageRecord (ImageRecord); return; } @@ -629,10 +645,10 @@ UnprotectUefiImage ( STATIC UINT64 GetPermissionAttributeForMemoryType ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - UINT64 TestBit; + UINT64 TestBit; if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) { TestBit = BIT63; @@ -665,27 +681,27 @@ SortMemoryMap ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - EFI_MEMORY_DESCRIPTOR TempMemoryMap; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_MEMORY_DESCRIPTOR TempMemoryMap; - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while (MemoryMapEntry < MemoryMapEnd) { while (NextMemoryMapEntry < MemoryMapEnd) { if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) { - CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof (EFI_MEMORY_DESCRIPTOR)); } NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); } - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } } @@ -708,29 +724,30 @@ MergeMemoryMapForProtectionPolicy ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - UINT64 MemoryBlockLength; - EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - UINT64 Attributes; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + UINT64 MemoryBlockLength; + EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + UINT64 Attributes; SortMemoryMap (MemoryMap, *MemoryMapSize, DescriptorSize); - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NewMemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + *MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { - CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); do { - MemoryBlockLength = (UINT64) (EFI_PAGES_TO_SIZE((UINTN)MemoryMapEntry->NumberOfPages)); - Attributes = GetPermissionAttributeForMemoryType (MemoryMapEntry->Type); + MemoryBlockLength = (UINT64)(EFI_PAGES_TO_SIZE ((UINTN)MemoryMapEntry->NumberOfPages)); + Attributes = GetPermissionAttributeForMemoryType (MemoryMapEntry->Type); if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && - Attributes == GetPermissionAttributeForMemoryType (NextMemoryMapEntry->Type) && - ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) { + (Attributes == GetPermissionAttributeForMemoryType (NextMemoryMapEntry->Type)) && + ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) + { MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; if (NewMemoryMapEntry != MemoryMapEntry) { NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; @@ -744,16 +761,15 @@ MergeMemoryMapForProtectionPolicy ( } } while (TRUE); - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NewMemoryMapEntry, DescriptorSize); } *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap; - return ; + return; } - /** Remove exec permissions from all regions whose type is identified by PcdDxeNxMemoryProtectionPolicy. @@ -764,20 +780,20 @@ InitializeDxeNxMemoryProtectionPolicy ( VOID ) { - UINTN MemoryMapSize; - UINTN MapKey; - UINTN DescriptorSize; - UINT32 DescriptorVersion; - EFI_MEMORY_DESCRIPTOR *MemoryMap; - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - EFI_STATUS Status; - UINT64 Attributes; - LIST_ENTRY *Link; - EFI_GCD_MAP_ENTRY *Entry; - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_MEMORY_ALLOCATION *MemoryHob; - EFI_PHYSICAL_ADDRESS StackBase; + UINTN MemoryMapSize; + UINTN MapKey; + UINTN DescriptorSize; + UINT32 DescriptorVersion; + EFI_MEMORY_DESCRIPTOR *MemoryMap; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_STATUS Status; + UINT64 Attributes; + LIST_ENTRY *Link; + EFI_GCD_MAP_ENTRY *Entry; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + EFI_PHYSICAL_ADDRESS StackBase; // // Get the EFI memory map. @@ -794,7 +810,7 @@ InitializeDxeNxMemoryProtectionPolicy ( ); ASSERT (Status == EFI_BUFFER_TOO_SMALL); do { - MemoryMap = (EFI_MEMORY_DESCRIPTOR *) AllocatePool (MemoryMapSize); + MemoryMap = (EFI_MEMORY_DESCRIPTOR *)AllocatePool (MemoryMapSize); ASSERT (MemoryMap != NULL); Status = gBS->GetMemoryMap ( &MemoryMapSize, @@ -807,6 +823,7 @@ InitializeDxeNxMemoryProtectionPolicy ( FreePool (MemoryMap); } } while (Status == EFI_BUFFER_TOO_SMALL); + ASSERT_EFI_ERROR (Status); StackBase = 0; @@ -817,7 +834,7 @@ InitializeDxeNxMemoryProtectionPolicy ( Hob.Raw = GetHobList (); while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) { MemoryHob = Hob.MemoryAllocation; - if (CompareGuid(&gEfiHobMemoryAllocStackGuid, &MemoryHob->AllocDescriptor.Name)) { + if (CompareGuid (&gEfiHobMemoryAllocStackGuid, &MemoryHob->AllocDescriptor.Name)) { DEBUG (( DEBUG_INFO, "%a: StackBase = 0x%016lx StackSize = 0x%016lx\n", @@ -833,6 +850,7 @@ InitializeDxeNxMemoryProtectionPolicy ( ASSERT ((StackBase & EFI_PAGE_MASK) == 0); break; } + Hob.Raw = GET_NEXT_HOB (Hob); } @@ -852,49 +870,52 @@ InitializeDxeNxMemoryProtectionPolicy ( MergeMemoryMapForProtectionPolicy (MemoryMap, &MemoryMapSize, DescriptorSize); MemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); - while ((UINTN) MemoryMapEntry < (UINTN) MemoryMapEnd) { - + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); + while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { Attributes = GetPermissionAttributeForMemoryType (MemoryMapEntry->Type); if (Attributes != 0) { SetUefiImageMemoryAttributes ( MemoryMapEntry->PhysicalStart, LShiftU64 (MemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT), - Attributes); + Attributes + ); // // Add EFI_MEMORY_RP attribute for page 0 if NULL pointer detection is // enabled. // - if (MemoryMapEntry->PhysicalStart == 0 && - PcdGet8 (PcdNullPointerDetectionPropertyMask) != 0) { - + if ((MemoryMapEntry->PhysicalStart == 0) && + (PcdGet8 (PcdNullPointerDetectionPropertyMask) != 0)) + { ASSERT (MemoryMapEntry->NumberOfPages > 0); SetUefiImageMemoryAttributes ( 0, EFI_PAGES_TO_SIZE (1), - EFI_MEMORY_RP | Attributes); + EFI_MEMORY_RP | Attributes + ); } // // Add EFI_MEMORY_RP attribute for the first page of the stack if stack // guard is enabled. // - if (StackBase != 0 && - (StackBase >= MemoryMapEntry->PhysicalStart && - StackBase < MemoryMapEntry->PhysicalStart + - LShiftU64 (MemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT)) && - PcdGetBool (PcdCpuStackGuard)) { - + if ((StackBase != 0) && + ((StackBase >= MemoryMapEntry->PhysicalStart) && + (StackBase < MemoryMapEntry->PhysicalStart + + LShiftU64 (MemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT))) && + PcdGetBool (PcdCpuStackGuard)) + { SetUefiImageMemoryAttributes ( StackBase, EFI_PAGES_TO_SIZE (1), - EFI_MEMORY_RP | Attributes); + EFI_MEMORY_RP | Attributes + ); } - } + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } + FreePool (MemoryMap); // @@ -912,34 +933,40 @@ InitializeDxeNxMemoryProtectionPolicy ( Link = mGcdMemorySpaceMap.ForwardLink; while (Link != &mGcdMemorySpaceMap) { - Entry = CR (Link, EFI_GCD_MAP_ENTRY, Link, EFI_GCD_MAP_SIGNATURE); - if (Entry->GcdMemoryType == EfiGcdMemoryTypeReserved && - Entry->EndAddress < MAX_ADDRESS && - (Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) == - (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED)) { - + if ((Entry->GcdMemoryType == EfiGcdMemoryTypeReserved) && + (Entry->EndAddress < MAX_ADDRESS) && + ((Entry->Capabilities & (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED | EFI_MEMORY_TESTED)) == + (EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED))) + { Attributes = GetPermissionAttributeForMemoryType (EfiConventionalMemory) | (Entry->Attributes & EFI_CACHE_ATTRIBUTE_MASK); - DEBUG ((DEBUG_INFO, + DEBUG (( + DEBUG_INFO, "Untested GCD memory space region: - 0x%016lx - 0x%016lx (0x%016lx)\n", - Entry->BaseAddress, Entry->EndAddress - Entry->BaseAddress + 1, - Attributes)); + Entry->BaseAddress, + Entry->EndAddress - Entry->BaseAddress + 1, + Attributes + )); - ASSERT(gCpu != NULL); - gCpu->SetMemoryAttributes (gCpu, Entry->BaseAddress, - Entry->EndAddress - Entry->BaseAddress + 1, Attributes); + ASSERT (gCpu != NULL); + gCpu->SetMemoryAttributes ( + gCpu, + Entry->BaseAddress, + Entry->EndAddress - Entry->BaseAddress + 1, + Attributes + ); } Link = Link->ForwardLink; } + CoreReleaseGcdMemoryLock (); } } - /** A notification for CPU_ARCH protocol. @@ -951,16 +978,16 @@ InitializeDxeNxMemoryProtectionPolicy ( VOID EFIAPI MemoryProtectionCpuArchProtocolNotify ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath; - UINTN NoHandles; - EFI_HANDLE *HandleBuffer; - UINTN Index; + EFI_STATUS Status; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + EFI_DEVICE_PATH_PROTOCOL *LoadedImageDevicePath; + UINTN NoHandles; + EFI_HANDLE *HandleBuffer; + UINTN Index; DEBUG ((DEBUG_INFO, "MemoryProtectionCpuArchProtocolNotify:\n")); Status = CoreLocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&gCpu); @@ -1001,20 +1028,22 @@ MemoryProtectionCpuArchProtocolNotify ( &gEfiLoadedImageProtocolGuid, (VOID **)&LoadedImage ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } + Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiLoadedImageDevicePathProtocolGuid, (VOID **)&LoadedImageDevicePath ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { LoadedImageDevicePath = NULL; } ProtectUefiImage (LoadedImage, LoadedImageDevicePath); } + FreePool (HandleBuffer); Done: @@ -1029,8 +1058,8 @@ MemoryProtectionExitBootServicesCallback ( VOID ) { - EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage; - LIST_ENTRY *Link; + EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage; + LIST_ENTRY *Link; // // We need remove the RT protection, because RT relocation need write code segment @@ -1044,7 +1073,7 @@ MemoryProtectionExitBootServicesCallback ( if (mImageProtectionPolicy != 0) { for (Link = gRuntime->ImageHead.ForwardLink; Link != &gRuntime->ImageHead; Link = Link->ForwardLink) { RuntimeImage = BASE_CR (Link, EFI_RUNTIME_IMAGE_ENTRY, Link); - SetUefiImageMemoryAttributes ((UINT64)(UINTN)RuntimeImage->ImageBase, ALIGN_VALUE(RuntimeImage->ImageSize, EFI_PAGE_SIZE), 0); + SetUefiImageMemoryAttributes ((UINT64)(UINTN)RuntimeImage->ImageBase, ALIGN_VALUE (RuntimeImage->ImageSize, EFI_PAGE_SIZE), 0); } } } @@ -1060,12 +1089,12 @@ MemoryProtectionExitBootServicesCallback ( VOID EFIAPI DisableNullDetectionAtTheEndOfDxe ( - EFI_EVENT Event, - VOID *Context + EFI_EVENT Event, + VOID *Context ) { - EFI_STATUS Status; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR Desc; + EFI_STATUS Status; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR Desc; DEBUG ((DEBUG_INFO, "DisableNullDetectionAtTheEndOfDxe(): start\r\n")); // @@ -1076,18 +1105,18 @@ DisableNullDetectionAtTheEndOfDxe ( if ((Desc.Capabilities & EFI_MEMORY_RP) == 0) { Status = CoreSetMemorySpaceCapabilities ( - 0, - EFI_PAGE_SIZE, - Desc.Capabilities | EFI_MEMORY_RP - ); + 0, + EFI_PAGE_SIZE, + Desc.Capabilities | EFI_MEMORY_RP + ); ASSERT_EFI_ERROR (Status); } Status = CoreSetMemorySpaceAttributes ( - 0, - EFI_PAGE_SIZE, - Desc.Attributes & ~EFI_MEMORY_RP - ); + 0, + EFI_PAGE_SIZE, + Desc.Attributes & ~EFI_MEMORY_RP + ); ASSERT_EFI_ERROR (Status); // @@ -1115,7 +1144,7 @@ CoreInitializeMemoryProtection ( EFI_EVENT EndOfDxeEvent; VOID *Registration; - mImageProtectionPolicy = PcdGet32(PcdImageProtectionPolicy); + mImageProtectionPolicy = PcdGet32 (PcdImageProtectionPolicy); InitializeListHead (&mProtectedImageRecordList); @@ -1128,8 +1157,10 @@ CoreInitializeMemoryProtection ( ASSERT ((GetPermissionAttributeForMemoryType (EfiBootServicesCode) & EFI_MEMORY_XP) == 0); ASSERT ((GetPermissionAttributeForMemoryType (EfiRuntimeServicesCode) & EFI_MEMORY_XP) == 0); ASSERT ((GetPermissionAttributeForMemoryType (EfiLoaderCode) & EFI_MEMORY_XP) == 0); - ASSERT (GetPermissionAttributeForMemoryType (EfiBootServicesData) == - GetPermissionAttributeForMemoryType (EfiConventionalMemory)); + ASSERT ( + GetPermissionAttributeForMemoryType (EfiBootServicesData) == + GetPermissionAttributeForMemoryType (EfiConventionalMemory) + ); Status = CoreCreateEvent ( EVT_NOTIFY_SIGNAL, @@ -1138,7 +1169,7 @@ CoreInitializeMemoryProtection ( NULL, &Event ); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); // // Register for protocol notifactions on this event @@ -1148,25 +1179,26 @@ CoreInitializeMemoryProtection ( Event, &Registration ); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); // // Register a callback to disable NULL pointer detection at EndOfDxe // if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & (BIT0|BIT7)) - == (BIT0|BIT7)) { + == (BIT0|BIT7)) + { Status = CoreCreateEventEx ( - EVT_NOTIFY_SIGNAL, - TPL_NOTIFY, - DisableNullDetectionAtTheEndOfDxe, - NULL, - &gEfiEndOfDxeEventGroupGuid, - &EndOfDxeEvent - ); + EVT_NOTIFY_SIGNAL, + TPL_NOTIFY, + DisableNullDetectionAtTheEndOfDxe, + NULL, + &gEfiEndOfDxeEventGroupGuid, + &EndOfDxeEvent + ); ASSERT_EFI_ERROR (Status); } - return ; + return; } /** @@ -1178,12 +1210,13 @@ IsInSmm ( VOID ) { - BOOLEAN InSmm; + BOOLEAN InSmm; InSmm = FALSE; if (gSmmBase2 != NULL) { gSmmBase2->InSmm (gSmmBase2, &InSmm); } + return InSmm; } @@ -1245,7 +1278,7 @@ ApplyMemoryProtectionPolicy ( // if any. // if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL)) { - if (IsGuardPage (Memory)) { + if (IsGuardPage (Memory)) { Memory += EFI_PAGE_SIZE; Length -= EFI_PAGE_SIZE; if (Length == 0) { @@ -1253,7 +1286,7 @@ ApplyMemoryProtectionPolicy ( } } - if (IsGuardPage (Memory + Length - EFI_PAGE_SIZE)) { + if (IsGuardPage (Memory + Length - EFI_PAGE_SIZE)) { Length -= EFI_PAGE_SIZE; if (Length == 0) { return EFI_SUCCESS; diff --git a/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c b/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c index a9bf1284f5..c3cabc0d36 100644 --- a/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c +++ b/MdeModulePkg/Core/Dxe/Misc/SetWatchdogTimer.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeMain.h" -#define WATCHDOG_TIMER_CALIBRATE_PER_SECOND 10000000 +#define WATCHDOG_TIMER_CALIBRATE_PER_SECOND 10000000 /** Sets the system's watchdog timer. @@ -35,10 +35,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI CoreSetWatchdogTimer ( - IN UINTN Timeout, - IN UINT64 WatchdogCode, - IN UINTN DataSize, - IN CHAR16 *WatchdogData OPTIONAL + IN UINTN Timeout, + IN UINT64 WatchdogCode, + IN UINTN DataSize, + IN CHAR16 *WatchdogData OPTIONAL ) { EFI_STATUS Status; diff --git a/MdeModulePkg/Core/Dxe/Misc/Stall.c b/MdeModulePkg/Core/Dxe/Misc/Stall.c index 6ecc708ac3..35e045d41a 100644 --- a/MdeModulePkg/Core/Dxe/Misc/Stall.c +++ b/MdeModulePkg/Core/Dxe/Misc/Stall.c @@ -30,6 +30,7 @@ CoreInternalWaitForTick ( gMetronome->WaitForTick (gMetronome, 0xffffffff); Counter -= 0xffffffff; } + gMetronome->WaitForTick (gMetronome, (UINT32)Counter); } @@ -46,7 +47,7 @@ CoreInternalWaitForTick ( EFI_STATUS EFIAPI CoreStall ( - IN UINTN Microseconds + IN UINTN Microseconds ) { UINT64 Counter; @@ -61,7 +62,7 @@ CoreStall ( // Counter = Microseconds * 10 / gMetronome->TickPeriod // 0x1999999999999999 = (2^64 - 1) / 10 // - if ((UINT64) Microseconds > 0x1999999999999999ULL) { + if ((UINT64)Microseconds > 0x1999999999999999ULL) { // // Microseconds is too large to multiple by 10 first. Perform the divide // operation first and loop 10 times to avoid 64-bit math overflow. @@ -100,6 +101,7 @@ CoreStall ( // Counter++; } + CoreInternalWaitForTick (Counter); } diff --git a/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c b/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c index 908617d1ca..b8d4184b50 100644 --- a/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c +++ b/MdeModulePkg/Core/Dxe/SectionExtraction/CoreSectionExtraction.c @@ -42,15 +42,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent CR (Node, CORE_SECTION_CHILD_NODE, Link, CORE_SECTION_CHILD_SIGNATURE) typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - UINT32 Type; - UINT32 Size; + UINT32 Signature; + LIST_ENTRY Link; + UINT32 Type; + UINT32 Size; // // StreamBase + OffsetInStream == pointer to section header in stream. The // stream base is always known when walking the sections within. // - UINT32 OffsetInStream; + UINT32 OffsetInStream; // // Then EncapsulatedStreamHandle below is always 0 if the section is NOT an // encapsulating section. Otherwise, it contains the stream handle @@ -58,33 +58,33 @@ typedef struct { // encapsulating child is encountered, irrespective of whether the // encapsulated stream is processed further. // - UINTN EncapsulatedStreamHandle; - EFI_GUID *EncapsulationGuid; + UINTN EncapsulatedStreamHandle; + EFI_GUID *EncapsulationGuid; // // If the section REQUIRES an extraction protocol, register for RPN // when the required GUIDed extraction protocol becomes available. // - EFI_EVENT Event; + EFI_EVENT Event; } CORE_SECTION_CHILD_NODE; -#define CORE_SECTION_STREAM_SIGNATURE SIGNATURE_32('S','X','S','S') +#define CORE_SECTION_STREAM_SIGNATURE SIGNATURE_32('S','X','S','S') #define STREAM_NODE_FROM_LINK(Node) \ CR (Node, CORE_SECTION_STREAM_NODE, Link, CORE_SECTION_STREAM_SIGNATURE) typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - UINTN StreamHandle; - UINT8 *StreamBuffer; - UINTN StreamLength; - LIST_ENTRY Children; + UINT32 Signature; + LIST_ENTRY Link; + UINTN StreamHandle; + UINT8 *StreamBuffer; + UINTN StreamLength; + LIST_ENTRY Children; // // Authentication status is from GUIDed encapsulations. // - UINT32 AuthenticationStatus; + UINT32 AuthenticationStatus; } CORE_SECTION_STREAM_NODE; -#define NULL_STREAM_HANDLE 0 +#define NULL_STREAM_HANDLE 0 typedef struct { CORE_SECTION_CHILD_NODE *ChildNode; @@ -92,7 +92,6 @@ typedef struct { VOID *Registration; } RPN_EVENT_CONTEXT; - /** The ExtractSection() function processes the input section and allocates a buffer from the pool in which it returns the section @@ -179,25 +178,24 @@ typedef struct { EFI_STATUS EFIAPI CustomGuidedSectionExtract ( - IN CONST EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *This, - IN CONST VOID *InputSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *This, + IN CONST VOID *InputSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize, + OUT UINT32 *AuthenticationStatus ); // // Module globals // -LIST_ENTRY mStreamRoot = INITIALIZE_LIST_HEAD_VARIABLE (mStreamRoot); +LIST_ENTRY mStreamRoot = INITIALIZE_LIST_HEAD_VARIABLE (mStreamRoot); -EFI_HANDLE mSectionExtractionHandle = NULL; +EFI_HANDLE mSectionExtractionHandle = NULL; -EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL mCustomGuidedSectionExtractionProtocol = { +EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL mCustomGuidedSectionExtractionProtocol = { CustomGuidedSectionExtract }; - /** Entry point of the section extraction code. Initializes an instance of the section extraction interface and installs it on a new handle. @@ -212,13 +210,13 @@ EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL mCustomGuidedSectionExtractionProtocol = EFI_STATUS EFIAPI InitializeSectionExtraction ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - EFI_GUID *ExtractHandlerGuidTable; - UINTN ExtractHandlerNumber; + EFI_STATUS Status; + EFI_GUID *ExtractHandlerGuidTable; + UINTN ExtractHandlerNumber; // // Get custom extract guided section method guid list @@ -231,18 +229,17 @@ InitializeSectionExtraction ( // while (ExtractHandlerNumber-- > 0) { Status = CoreInstallProtocolInterface ( - &mSectionExtractionHandle, - &ExtractHandlerGuidTable [ExtractHandlerNumber], - EFI_NATIVE_INTERFACE, - &mCustomGuidedSectionExtractionProtocol - ); + &mSectionExtractionHandle, + &ExtractHandlerGuidTable[ExtractHandlerNumber], + EFI_NATIVE_INTERFACE, + &mCustomGuidedSectionExtractionProtocol + ); ASSERT_EFI_ERROR (Status); } return Status; } - /** Check if a stream is valid. @@ -254,16 +251,16 @@ InitializeSectionExtraction ( **/ BOOLEAN IsValidSectionStream ( - IN VOID *SectionStream, - IN UINTN SectionStreamLength + IN VOID *SectionStream, + IN UINTN SectionStreamLength ) { - UINTN TotalLength; - UINTN SectionLength; - EFI_COMMON_SECTION_HEADER *SectionHeader; - EFI_COMMON_SECTION_HEADER *NextSectionHeader; + UINTN TotalLength; + UINTN SectionLength; + EFI_COMMON_SECTION_HEADER *SectionHeader; + EFI_COMMON_SECTION_HEADER *NextSectionHeader; - TotalLength = 0; + TotalLength = 0; SectionHeader = (EFI_COMMON_SECTION_HEADER *)SectionStream; while (TotalLength < SectionStreamLength) { @@ -272,6 +269,7 @@ IsValidSectionStream ( } else { SectionLength = SECTION_SIZE (SectionHeader); } + TotalLength += SectionLength; if (TotalLength == SectionStreamLength) { @@ -281,21 +279,20 @@ IsValidSectionStream ( // // Move to the next byte following the section... // - SectionHeader = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) SectionHeader + SectionLength); + SectionHeader = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)SectionHeader + SectionLength); // // Figure out where the next section begins // - NextSectionHeader = ALIGN_POINTER(SectionHeader, 4); - TotalLength += (UINTN) NextSectionHeader - (UINTN) SectionHeader; - SectionHeader = NextSectionHeader; + NextSectionHeader = ALIGN_POINTER (SectionHeader, 4); + TotalLength += (UINTN)NextSectionHeader - (UINTN)SectionHeader; + SectionHeader = NextSectionHeader; } ASSERT (FALSE); return FALSE; } - /** Worker function. Constructor for section streams. @@ -331,15 +328,15 @@ IsValidSectionStream ( **/ EFI_STATUS OpenSectionStreamEx ( - IN UINTN SectionStreamLength, - IN VOID *SectionStream, - IN BOOLEAN AllocateBuffer, - IN UINT32 AuthenticationStatus, - OUT UINTN *SectionStreamHandle + IN UINTN SectionStreamLength, + IN VOID *SectionStream, + IN BOOLEAN AllocateBuffer, + IN UINT32 AuthenticationStatus, + OUT UINTN *SectionStreamHandle ) { - CORE_SECTION_STREAM_NODE *NewStream; - EFI_TPL OldTpl; + CORE_SECTION_STREAM_NODE *NewStream; + EFI_TPL OldTpl; // // Allocate a new stream @@ -360,6 +357,7 @@ OpenSectionStreamEx ( CoreFreePool (NewStream); return EFI_OUT_OF_RESOURCES; } + // // Copy in stream data // @@ -382,8 +380,8 @@ OpenSectionStreamEx ( // // Initialize the rest of the section stream // - NewStream->Signature = CORE_SECTION_STREAM_SIGNATURE; - NewStream->StreamHandle = (UINTN) NewStream; + NewStream->Signature = CORE_SECTION_STREAM_SIGNATURE; + NewStream->StreamHandle = (UINTN)NewStream; NewStream->StreamLength = SectionStreamLength; InitializeListHead (&NewStream->Children); NewStream->AuthenticationStatus = AuthenticationStatus; @@ -400,7 +398,6 @@ OpenSectionStreamEx ( return EFI_SUCCESS; } - /** SEP member function. This function creates and returns a new section stream handle to represent the new section stream. @@ -419,9 +416,9 @@ OpenSectionStreamEx ( EFI_STATUS EFIAPI OpenSectionStream ( - IN UINTN SectionStreamLength, - IN VOID *SectionStream, - OUT UINTN *SectionStreamHandle + IN UINTN SectionStreamLength, + IN VOID *SectionStream, + OUT UINTN *SectionStreamHandle ) { // @@ -440,8 +437,6 @@ OpenSectionStream ( ); } - - /** Worker function. Determine if the input stream:child matches the input type. @@ -459,26 +454,29 @@ OpenSectionStream ( **/ BOOLEAN ChildIsType ( - IN CORE_SECTION_STREAM_NODE *Stream, - IN CORE_SECTION_CHILD_NODE *Child, - IN EFI_SECTION_TYPE SearchType, - IN EFI_GUID *SectionDefinitionGuid + IN CORE_SECTION_STREAM_NODE *Stream, + IN CORE_SECTION_CHILD_NODE *Child, + IN EFI_SECTION_TYPE SearchType, + IN EFI_GUID *SectionDefinitionGuid ) { - EFI_GUID_DEFINED_SECTION *GuidedSection; + EFI_GUID_DEFINED_SECTION *GuidedSection; if (SearchType == EFI_SECTION_ALL) { return TRUE; } + if (Child->Type != SearchType) { return FALSE; } + if ((SearchType != EFI_SECTION_GUID_DEFINED) || (SectionDefinitionGuid == NULL)) { return TRUE; } - GuidedSection = (EFI_GUID_DEFINED_SECTION * )(Stream->StreamBuffer + Child->OffsetInStream); + + GuidedSection = (EFI_GUID_DEFINED_SECTION *)(Stream->StreamBuffer + Child->OffsetInStream); if (IS_SECTION2 (GuidedSection)) { - return CompareGuid (&(((EFI_GUID_DEFINED_SECTION2 *) GuidedSection)->SectionDefinitionGuid), SectionDefinitionGuid); + return CompareGuid (&(((EFI_GUID_DEFINED_SECTION2 *)GuidedSection)->SectionDefinitionGuid), SectionDefinitionGuid); } else { return CompareGuid (&GuidedSection->SectionDefinitionGuid, SectionDefinitionGuid); } @@ -499,33 +497,34 @@ ChildIsType ( **/ BOOLEAN VerifyGuidedSectionGuid ( - IN EFI_GUID *GuidedSectionGuid, - OUT EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL **GuidedSectionExtraction + IN EFI_GUID *GuidedSectionGuid, + OUT EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL **GuidedSectionExtraction ) { - EFI_GUID *GuidRecorded; - VOID *Interface; - EFI_STATUS Status; + EFI_GUID *GuidRecorded; + VOID *Interface; + EFI_STATUS Status; Interface = NULL; // // Check if there is the Guided Section GUID configuration table recorded the GUID itself. // - Status = EfiGetSystemConfigurationTable (GuidedSectionGuid, (VOID **) &GuidRecorded); + Status = EfiGetSystemConfigurationTable (GuidedSectionGuid, (VOID **)&GuidRecorded); if (Status == EFI_SUCCESS) { if (CompareGuid (GuidRecorded, GuidedSectionGuid)) { // // Found the recorded GuidedSectionGuid. // - Status = CoreLocateProtocol (GuidedSectionGuid, NULL, (VOID **) &Interface); - if (!EFI_ERROR (Status) && Interface != NULL) { + Status = CoreLocateProtocol (GuidedSectionGuid, NULL, (VOID **)&Interface); + if (!EFI_ERROR (Status) && (Interface != NULL)) { // // Found the supported Guided Section Extraction Porotocol for the Guided Section. // - *GuidedSectionExtraction = (EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *) Interface; + *GuidedSectionExtraction = (EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *)Interface; return TRUE; } + return FALSE; } } @@ -544,8 +543,8 @@ VerifyGuidedSectionGuid ( VOID EFIAPI NotifyGuidedExtraction ( - IN EFI_EVENT Event, - IN VOID *RpnContext + IN EFI_EVENT Event, + IN VOID *RpnContext ) { EFI_STATUS Status; @@ -558,7 +557,7 @@ NotifyGuidedExtraction ( Context = RpnContext; - GuidedHeader = (EFI_GUID_DEFINED_SECTION *) (Context->ParentStream->StreamBuffer + Context->ChildNode->OffsetInStream); + GuidedHeader = (EFI_GUID_DEFINED_SECTION *)(Context->ParentStream->StreamBuffer + Context->ChildNode->OffsetInStream); ASSERT (GuidedHeader->CommonHeader.Type == EFI_SECTION_GUID_DEFINED); if (!VerifyGuidedSectionGuid (Context->ChildNode->EncapsulationGuid, &GuidedExtraction)) { @@ -617,11 +616,11 @@ NotifyGuidedExtraction ( **/ VOID CreateGuidedExtractionRpnEvent ( - IN CORE_SECTION_STREAM_NODE *ParentStream, - IN CORE_SECTION_CHILD_NODE *ChildNode + IN CORE_SECTION_STREAM_NODE *ParentStream, + IN CORE_SECTION_CHILD_NODE *ChildNode ) { - RPN_EVENT_CONTEXT *Context; + RPN_EVENT_CONTEXT *Context; // // Allocate new event structure and context @@ -629,7 +628,7 @@ CreateGuidedExtractionRpnEvent ( Context = AllocatePool (sizeof (RPN_EVENT_CONTEXT)); ASSERT (Context != NULL); - Context->ChildNode = ChildNode; + Context->ChildNode = ChildNode; Context->ParentStream = ParentStream; Context->ChildNode->Event = EfiCreateProtocolNotifyEvent ( @@ -664,37 +663,37 @@ CreateGuidedExtractionRpnEvent ( **/ EFI_STATUS CreateChildNode ( - IN CORE_SECTION_STREAM_NODE *Stream, - IN UINT32 ChildOffset, - OUT CORE_SECTION_CHILD_NODE **ChildNode + IN CORE_SECTION_STREAM_NODE *Stream, + IN UINT32 ChildOffset, + OUT CORE_SECTION_CHILD_NODE **ChildNode ) { - EFI_STATUS Status; - EFI_COMMON_SECTION_HEADER *SectionHeader; - EFI_COMPRESSION_SECTION *CompressionHeader; - EFI_GUID_DEFINED_SECTION *GuidedHeader; - EFI_DECOMPRESS_PROTOCOL *Decompress; - EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *GuidedExtraction; - VOID *NewStreamBuffer; - VOID *ScratchBuffer; - UINT32 ScratchSize; - UINTN NewStreamBufferSize; - UINT32 AuthenticationStatus; - VOID *CompressionSource; - UINT32 CompressionSourceSize; - UINT32 UncompressedLength; - UINT8 CompressionType; - UINT16 GuidedSectionAttributes; - - CORE_SECTION_CHILD_NODE *Node; - - SectionHeader = (EFI_COMMON_SECTION_HEADER *) (Stream->StreamBuffer + ChildOffset); + EFI_STATUS Status; + EFI_COMMON_SECTION_HEADER *SectionHeader; + EFI_COMPRESSION_SECTION *CompressionHeader; + EFI_GUID_DEFINED_SECTION *GuidedHeader; + EFI_DECOMPRESS_PROTOCOL *Decompress; + EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *GuidedExtraction; + VOID *NewStreamBuffer; + VOID *ScratchBuffer; + UINT32 ScratchSize; + UINTN NewStreamBufferSize; + UINT32 AuthenticationStatus; + VOID *CompressionSource; + UINT32 CompressionSourceSize; + UINT32 UncompressedLength; + UINT8 CompressionType; + UINT16 GuidedSectionAttributes; + + CORE_SECTION_CHILD_NODE *Node; + + SectionHeader = (EFI_COMMON_SECTION_HEADER *)(Stream->StreamBuffer + ChildOffset); // // Allocate a new node // *ChildNode = AllocateZeroPool (sizeof (CORE_SECTION_CHILD_NODE)); - Node = *ChildNode; + Node = *ChildNode; if (Node == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -703,15 +702,16 @@ CreateChildNode ( // Now initialize it // Node->Signature = CORE_SECTION_CHILD_SIGNATURE; - Node->Type = SectionHeader->Type; + Node->Type = SectionHeader->Type; if (IS_SECTION2 (SectionHeader)) { Node->Size = SECTION2_SIZE (SectionHeader); } else { Node->Size = SECTION_SIZE (SectionHeader); } - Node->OffsetInStream = ChildOffset; + + Node->OffsetInStream = ChildOffset; Node->EncapsulatedStreamHandle = NULL_STREAM_HANDLE; - Node->EncapsulationGuid = NULL; + Node->EncapsulationGuid = NULL; // // If it's an encapsulating section, then create the new section stream also @@ -726,18 +726,18 @@ CreateChildNode ( return EFI_NOT_FOUND; } - CompressionHeader = (EFI_COMPRESSION_SECTION *) SectionHeader; + CompressionHeader = (EFI_COMPRESSION_SECTION *)SectionHeader; if (IS_SECTION2 (CompressionHeader)) { - CompressionSource = (VOID *) ((UINT8 *) CompressionHeader + sizeof (EFI_COMPRESSION_SECTION2)); - CompressionSourceSize = (UINT32) (SECTION2_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION2)); - UncompressedLength = ((EFI_COMPRESSION_SECTION2 *) CompressionHeader)->UncompressedLength; - CompressionType = ((EFI_COMPRESSION_SECTION2 *) CompressionHeader)->CompressionType; + CompressionSource = (VOID *)((UINT8 *)CompressionHeader + sizeof (EFI_COMPRESSION_SECTION2)); + CompressionSourceSize = (UINT32)(SECTION2_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION2)); + UncompressedLength = ((EFI_COMPRESSION_SECTION2 *)CompressionHeader)->UncompressedLength; + CompressionType = ((EFI_COMPRESSION_SECTION2 *)CompressionHeader)->CompressionType; } else { - CompressionSource = (VOID *) ((UINT8 *) CompressionHeader + sizeof (EFI_COMPRESSION_SECTION)); - CompressionSourceSize = (UINT32) (SECTION_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION)); - UncompressedLength = CompressionHeader->UncompressedLength; - CompressionType = CompressionHeader->CompressionType; + CompressionSource = (VOID *)((UINT8 *)CompressionHeader + sizeof (EFI_COMPRESSION_SECTION)); + CompressionSourceSize = (UINT32)(SECTION_SIZE (CompressionHeader) - sizeof (EFI_COMPRESSION_SECTION)); + UncompressedLength = CompressionHeader->UncompressedLength; + CompressionType = CompressionHeader->CompressionType; } // @@ -745,7 +745,7 @@ CreateChildNode ( // if (UncompressedLength > 0) { NewStreamBufferSize = UncompressedLength; - NewStreamBuffer = AllocatePool (NewStreamBufferSize); + NewStreamBuffer = AllocatePool (NewStreamBufferSize); if (NewStreamBuffer == NULL) { CoreFreePool (Node); return EFI_OUT_OF_RESOURCES; @@ -781,6 +781,7 @@ CreateChildNode ( if (!EFI_ERROR (Status)) { Status = EFI_BAD_BUFFER_SIZE; } + return Status; } @@ -808,7 +809,7 @@ CreateChildNode ( } } } else { - NewStreamBuffer = NULL; + NewStreamBuffer = NULL; NewStreamBufferSize = 0; } @@ -824,17 +825,19 @@ CreateChildNode ( CoreFreePool (NewStreamBuffer); return Status; } + break; case EFI_SECTION_GUID_DEFINED: - GuidedHeader = (EFI_GUID_DEFINED_SECTION *) SectionHeader; + GuidedHeader = (EFI_GUID_DEFINED_SECTION *)SectionHeader; if (IS_SECTION2 (GuidedHeader)) { - Node->EncapsulationGuid = &(((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->SectionDefinitionGuid); - GuidedSectionAttributes = ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->Attributes; + Node->EncapsulationGuid = &(((EFI_GUID_DEFINED_SECTION2 *)GuidedHeader)->SectionDefinitionGuid); + GuidedSectionAttributes = ((EFI_GUID_DEFINED_SECTION2 *)GuidedHeader)->Attributes; } else { Node->EncapsulationGuid = &GuidedHeader->SectionDefinitionGuid; GuidedSectionAttributes = GuidedHeader->Attributes; } + if (VerifyGuidedSectionGuid (Node->EncapsulationGuid, &GuidedExtraction)) { // // NewStreamBuffer is always allocated by ExtractSection... No caller @@ -903,21 +906,22 @@ CreateChildNode ( if (IS_SECTION2 (GuidedHeader)) { Status = OpenSectionStreamEx ( - SECTION2_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->DataOffset, - (UINT8 *) GuidedHeader + ((EFI_GUID_DEFINED_SECTION2 *) GuidedHeader)->DataOffset, + SECTION2_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION2 *)GuidedHeader)->DataOffset, + (UINT8 *)GuidedHeader + ((EFI_GUID_DEFINED_SECTION2 *)GuidedHeader)->DataOffset, TRUE, AuthenticationStatus, &Node->EncapsulatedStreamHandle ); } else { Status = OpenSectionStreamEx ( - SECTION_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION *) GuidedHeader)->DataOffset, - (UINT8 *) GuidedHeader + ((EFI_GUID_DEFINED_SECTION *) GuidedHeader)->DataOffset, + SECTION_SIZE (GuidedHeader) - ((EFI_GUID_DEFINED_SECTION *)GuidedHeader)->DataOffset, + (UINT8 *)GuidedHeader + ((EFI_GUID_DEFINED_SECTION *)GuidedHeader)->DataOffset, TRUE, AuthenticationStatus, &Node->EncapsulatedStreamHandle ); } + if (EFI_ERROR (Status)) { CoreFreePool (Node); return Status; @@ -943,7 +947,6 @@ CreateChildNode ( return EFI_SUCCESS; } - /** Worker function Recursively searches / builds section stream database looking for requested section. @@ -978,22 +981,22 @@ CreateChildNode ( **/ EFI_STATUS FindChildNode ( - IN CORE_SECTION_STREAM_NODE *SourceStream, - IN EFI_SECTION_TYPE SearchType, - IN OUT UINTN *SectionInstance, - IN EFI_GUID *SectionDefinitionGuid, - IN UINT32 Depth, - OUT CORE_SECTION_CHILD_NODE **FoundChild, - OUT CORE_SECTION_STREAM_NODE **FoundStream, - OUT UINT32 *AuthenticationStatus + IN CORE_SECTION_STREAM_NODE *SourceStream, + IN EFI_SECTION_TYPE SearchType, + IN OUT UINTN *SectionInstance, + IN EFI_GUID *SectionDefinitionGuid, + IN UINT32 Depth, + OUT CORE_SECTION_CHILD_NODE **FoundChild, + OUT CORE_SECTION_STREAM_NODE **FoundStream, + OUT UINT32 *AuthenticationStatus ) { - CORE_SECTION_CHILD_NODE *CurrentChildNode; - CORE_SECTION_CHILD_NODE *RecursedChildNode; - CORE_SECTION_STREAM_NODE *RecursedFoundStream; - UINT32 NextChildOffset; - EFI_STATUS ErrorStatus; - EFI_STATUS Status; + CORE_SECTION_CHILD_NODE *CurrentChildNode; + CORE_SECTION_CHILD_NODE *RecursedChildNode; + CORE_SECTION_STREAM_NODE *RecursedFoundStream; + UINT32 NextChildOffset; + EFI_STATUS ErrorStatus; + EFI_STATUS Status; ASSERT (*SectionInstance > 0); @@ -1002,14 +1005,15 @@ FindChildNode ( } CurrentChildNode = NULL; - ErrorStatus = EFI_NOT_FOUND; + ErrorStatus = EFI_NOT_FOUND; if (SourceStream->StreamLength == 0) { return EFI_NOT_FOUND; } if (IsListEmpty (&SourceStream->Children) && - SourceStream->StreamLength >= sizeof (EFI_COMMON_SECTION_HEADER)) { + (SourceStream->StreamLength >= sizeof (EFI_COMMON_SECTION_HEADER))) + { // // This occurs when a section stream exists, but no child sections // have been parsed out yet. Therefore, extract the first child and add it @@ -1030,9 +1034,9 @@ FindChildNode ( // adding children until either the requested section is found, or we run // out of data // - CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetFirstNode(&SourceStream->Children)); + CurrentChildNode = CHILD_SECTION_NODE_FROM_LINK (GetFirstNode (&SourceStream->Children)); - for (;;) { + for ( ; ;) { ASSERT (CurrentChildNode != NULL); if (ChildIsType (SourceStream, CurrentChildNode, SearchType, SectionDefinitionGuid)) { // @@ -1043,8 +1047,8 @@ FindChildNode ( // // Got it! // - *FoundChild = CurrentChildNode; - *FoundStream = SourceStream; + *FoundChild = CurrentChildNode; + *FoundStream = SourceStream; *AuthenticationStatus = SourceStream->AuthenticationStatus; return EFI_SUCCESS; } @@ -1060,22 +1064,22 @@ FindChildNode ( // If the current node is an encapsulating node, recurse into it... // Status = FindChildNode ( - (CORE_SECTION_STREAM_NODE *)CurrentChildNode->EncapsulatedStreamHandle, - SearchType, - SectionInstance, - SectionDefinitionGuid, - Depth + 1, - &RecursedChildNode, - &RecursedFoundStream, - AuthenticationStatus - ); + (CORE_SECTION_STREAM_NODE *)CurrentChildNode->EncapsulatedStreamHandle, + SearchType, + SectionInstance, + SectionDefinitionGuid, + Depth + 1, + &RecursedChildNode, + &RecursedFoundStream, + AuthenticationStatus + ); if (*SectionInstance == 0) { // // The recursive FindChildNode() call decreased (*SectionInstance) to // zero. // ASSERT_EFI_ERROR (Status); - *FoundChild = RecursedChildNode; + *FoundChild = RecursedChildNode; *FoundStream = RecursedFoundStream; return EFI_SUCCESS; } else { @@ -1087,6 +1091,7 @@ FindChildNode ( // return Status; } + // // Save the error code and continue to find the requested child node in // the rest of the stream. @@ -1120,7 +1125,7 @@ FindChildNode ( // Round up to 4 byte boundary // NextChildOffset += 3; - NextChildOffset &= ~(UINTN) 3; + NextChildOffset &= ~(UINTN)3; if (NextChildOffset <= SourceStream->StreamLength - sizeof (EFI_COMMON_SECTION_HEADER)) { // // There's an unparsed child remaining in the stream, so create a new child node @@ -1137,7 +1142,6 @@ FindChildNode ( } } - /** Worker function. Search stream database for requested stream handle. @@ -1152,15 +1156,15 @@ FindChildNode ( **/ EFI_STATUS FindStreamNode ( - IN UINTN SearchHandle, - OUT CORE_SECTION_STREAM_NODE **FoundStream + IN UINTN SearchHandle, + OUT CORE_SECTION_STREAM_NODE **FoundStream ) { - CORE_SECTION_STREAM_NODE *StreamNode; + CORE_SECTION_STREAM_NODE *StreamNode; if (!IsListEmpty (&mStreamRoot)) { StreamNode = STREAM_NODE_FROM_LINK (GetFirstNode (&mStreamRoot)); - for (;;) { + for ( ; ;) { if (StreamNode->StreamHandle == SearchHandle) { *FoundStream = StreamNode; return EFI_SUCCESS; @@ -1175,7 +1179,6 @@ FindStreamNode ( return EFI_NOT_FOUND; } - /** SEP member function. Retrieves requested section from section stream. @@ -1237,32 +1240,31 @@ FindStreamNode ( EFI_STATUS EFIAPI GetSection ( - IN UINTN SectionStreamHandle, - IN EFI_SECTION_TYPE *SectionType, - IN EFI_GUID *SectionDefinitionGuid, - IN UINTN SectionInstance, - IN VOID **Buffer, - IN OUT UINTN *BufferSize, - OUT UINT32 *AuthenticationStatus, - IN BOOLEAN IsFfs3Fv + IN UINTN SectionStreamHandle, + IN EFI_SECTION_TYPE *SectionType, + IN EFI_GUID *SectionDefinitionGuid, + IN UINTN SectionInstance, + IN VOID **Buffer, + IN OUT UINTN *BufferSize, + OUT UINT32 *AuthenticationStatus, + IN BOOLEAN IsFfs3Fv ) { - CORE_SECTION_STREAM_NODE *StreamNode; - EFI_TPL OldTpl; - EFI_STATUS Status; - CORE_SECTION_CHILD_NODE *ChildNode; - CORE_SECTION_STREAM_NODE *ChildStreamNode; - UINTN CopySize; - UINT32 ExtractedAuthenticationStatus; - UINTN Instance; - UINT8 *CopyBuffer; - UINTN SectionSize; - EFI_COMMON_SECTION_HEADER *Section; - + CORE_SECTION_STREAM_NODE *StreamNode; + EFI_TPL OldTpl; + EFI_STATUS Status; + CORE_SECTION_CHILD_NODE *ChildNode; + CORE_SECTION_STREAM_NODE *ChildStreamNode; + UINTN CopySize; + UINT32 ExtractedAuthenticationStatus; + UINTN Instance; + UINT8 *CopyBuffer; + UINTN SectionSize; + EFI_COMMON_SECTION_HEADER *Section; ChildStreamNode = NULL; - OldTpl = CoreRaiseTpl (TPL_NOTIFY); - Instance = SectionInstance + 1; + OldTpl = CoreRaiseTpl (TPL_NOTIFY); + Instance = SectionInstance + 1; // // Locate target stream @@ -1280,8 +1282,8 @@ GetSection ( // // SectionType == NULL means return the WHOLE section stream... // - CopySize = StreamNode->StreamLength; - CopyBuffer = StreamNode->StreamBuffer; + CopySize = StreamNode->StreamLength; + CopyBuffer = StreamNode->StreamBuffer; *AuthenticationStatus = StreamNode->AuthenticationStatus; } else { // @@ -1299,17 +1301,21 @@ GetSection ( ); if (EFI_ERROR (Status)) { if (Status == EFI_ABORTED) { - DEBUG ((DEBUG_ERROR, "%a: recursion aborted due to nesting depth\n", - __FUNCTION__)); + DEBUG (( + DEBUG_ERROR, + "%a: recursion aborted due to nesting depth\n", + __FUNCTION__ + )); // // Map "aborted" to "not found". // Status = EFI_NOT_FOUND; } + goto GetSection_Done; } - Section = (EFI_COMMON_SECTION_HEADER *) (ChildStreamNode->StreamBuffer + ChildNode->OffsetInStream); + Section = (EFI_COMMON_SECTION_HEADER *)(ChildStreamNode->StreamBuffer + ChildNode->OffsetInStream); if (IS_SECTION2 (Section)) { ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF); @@ -1318,12 +1324,14 @@ GetSection ( Status = EFI_NOT_FOUND; goto GetSection_Done; } - CopySize = SECTION2_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER2); - CopyBuffer = (UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER2); + + CopySize = SECTION2_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER2); + CopyBuffer = (UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2); } else { - CopySize = SECTION_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER); - CopyBuffer = (UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER); + CopySize = SECTION_SIZE (Section) - sizeof (EFI_COMMON_SECTION_HEADER); + CopyBuffer = (UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER); } + *AuthenticationStatus = ExtractedAuthenticationStatus; } @@ -1333,7 +1341,7 @@ GetSection ( // Caller allocated buffer. Fill to size and return required size... // if (*BufferSize < CopySize) { - Status = EFI_WARN_BUFFER_TOO_SMALL; + Status = EFI_WARN_BUFFER_TOO_SMALL; CopySize = *BufferSize; } } else { @@ -1346,6 +1354,7 @@ GetSection ( goto GetSection_Done; } } + CopyMem (*Buffer, CopyBuffer, CopySize); *BufferSize = SectionSize; @@ -1355,7 +1364,6 @@ GetSection_Done: return Status; } - /** Worker function. Destructor for child nodes. @@ -1364,7 +1372,7 @@ GetSection_Done: **/ VOID FreeChildNode ( - IN CORE_SECTION_CHILD_NODE *ChildNode + IN CORE_SECTION_CHILD_NODE *ChildNode ) { ASSERT (ChildNode->Signature == CORE_SECTION_CHILD_SIGNATURE); @@ -1391,7 +1399,6 @@ FreeChildNode ( CoreFreePool (ChildNode); } - /** SEP member function. Deletes an existing section stream @@ -1408,15 +1415,15 @@ FreeChildNode ( EFI_STATUS EFIAPI CloseSectionStream ( - IN UINTN StreamHandleToClose, - IN BOOLEAN FreeStreamBuffer + IN UINTN StreamHandleToClose, + IN BOOLEAN FreeStreamBuffer ) { - CORE_SECTION_STREAM_NODE *StreamNode; - EFI_TPL OldTpl; - EFI_STATUS Status; - LIST_ENTRY *Link; - CORE_SECTION_CHILD_NODE *ChildNode; + CORE_SECTION_STREAM_NODE *StreamNode; + EFI_TPL OldTpl; + EFI_STATUS Status; + LIST_ENTRY *Link; + CORE_SECTION_CHILD_NODE *ChildNode; OldTpl = CoreRaiseTpl (TPL_NOTIFY); @@ -1430,13 +1437,15 @@ CloseSectionStream ( // RemoveEntryList (&StreamNode->Link); while (!IsListEmpty (&StreamNode->Children)) { - Link = GetFirstNode (&StreamNode->Children); + Link = GetFirstNode (&StreamNode->Children); ChildNode = CHILD_SECTION_NODE_FROM_LINK (Link); FreeChildNode (ChildNode); } + if (FreeStreamBuffer) { CoreFreePool (StreamNode->StreamBuffer); } + CoreFreePool (StreamNode); Status = EFI_SUCCESS; } else { @@ -1447,7 +1456,6 @@ CloseSectionStream ( return Status; } - /** The ExtractSection() function processes the input section and allocates a buffer from the pool in which it returns the section @@ -1534,19 +1542,19 @@ CloseSectionStream ( EFI_STATUS EFIAPI CustomGuidedSectionExtract ( - IN CONST EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *This, - IN CONST VOID *InputSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_GUIDED_SECTION_EXTRACTION_PROTOCOL *This, + IN CONST VOID *InputSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize, + OUT UINT32 *AuthenticationStatus ) { - EFI_STATUS Status; - VOID *ScratchBuffer; - VOID *AllocatedOutputBuffer; - UINT32 OutputBufferSize; - UINT32 ScratchBufferSize; - UINT16 SectionAttribute; + EFI_STATUS Status; + VOID *ScratchBuffer; + VOID *AllocatedOutputBuffer; + UINT32 OutputBufferSize; + UINT32 ScratchBufferSize; + UINT16 SectionAttribute; // // Init local variable @@ -1588,8 +1596,10 @@ CustomGuidedSectionExtract ( if (ScratchBuffer != NULL) { FreePool (ScratchBuffer); } + return EFI_OUT_OF_RESOURCES; } + *OutputBuffer = AllocatedOutputBuffer; } @@ -1609,9 +1619,11 @@ CustomGuidedSectionExtract ( if (AllocatedOutputBuffer != NULL) { CoreFreePool (AllocatedOutputBuffer); } + if (ScratchBuffer != NULL) { CoreFreePool (ScratchBuffer); } + DEBUG ((DEBUG_ERROR, "Extract guided section Failed - %r\n", Status)); return Status; } @@ -1628,7 +1640,7 @@ CustomGuidedSectionExtract ( // // Set real size of output buffer. // - *OutputSize = (UINTN) OutputBufferSize; + *OutputSize = (UINTN)OutputBufferSize; // // Free unused scratch buffer. diff --git a/MdeModulePkg/Core/DxeIplPeim/Arm/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Arm/DxeLoadFunc.c index 6619a65066..f62b6dcb38 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Arm/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Arm/DxeLoadFunc.c @@ -25,13 +25,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ) { - VOID *BaseOfStack; - VOID *TopOfStack; - EFI_STATUS Status; + VOID *BaseOfStack; + VOID *TopOfStack; + EFI_STATUS Status; // // Allocate 128KB for the Stack @@ -48,7 +48,7 @@ HandOffToDxeCore ( // Compute the top of the stack we were allocated. Pre-allocate a UINTN // for safety. // - TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); + TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); // @@ -60,7 +60,7 @@ HandOffToDxeCore ( // // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. // - UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, STACK_SIZE); + UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE); SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)DxeCoreEntryPoint, diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h index bc0d41f406..2f015befce 100644 --- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h +++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h @@ -46,11 +46,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define STACK_SIZE 0x20000 #define BSP_STORE_SIZE 0x4000 - // // This PPI is installed to indicate the end of the PEI usage of memory // -extern CONST EFI_PEI_PPI_DESCRIPTOR gEndOfPeiSignalPpi; +extern CONST EFI_PEI_PPI_DESCRIPTOR gEndOfPeiSignalPpi; /** This function installs the PPIs that require permanent memory. @@ -83,7 +82,6 @@ DxeIplFindDxeCore ( VOID ); - /** Main entry point to last PEIM @@ -98,13 +96,11 @@ DxeIplFindDxeCore ( EFI_STATUS EFIAPI DxeLoadCore ( - IN CONST EFI_DXE_IPL_PPI *This, - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_HOB_POINTERS HobList + IN CONST EFI_DXE_IPL_PPI *This, + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_HOB_POINTERS HobList ); - - /** Transfers control to DxeCore. @@ -118,12 +114,10 @@ DxeLoadCore ( **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ); - - /** Updates the Stack HOB passed to DXE phase. @@ -136,8 +130,8 @@ HandOffToDxeCore ( **/ VOID UpdateStackHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length ); /** @@ -197,14 +191,13 @@ UpdateStackHob ( EFI_STATUS EFIAPI CustomGuidedSectionExtract ( - IN CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *This, - IN CONST VOID *InputSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *This, + IN CONST VOID *InputSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize, + OUT UINT32 *AuthenticationStatus ); - /** Decompresses a section to the output buffer. @@ -228,10 +221,10 @@ CustomGuidedSectionExtract ( EFI_STATUS EFIAPI Decompress ( - IN CONST EFI_PEI_DECOMPRESS_PPI *This, - IN CONST EFI_COMPRESSION_SECTION *CompressionSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize + IN CONST EFI_PEI_DECOMPRESS_PPI *This, + IN CONST EFI_COMPRESSION_SECTION *CompressionSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize ); #endif diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c b/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c index d48028cea0..2c19f1a507 100644 --- a/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c +++ b/MdeModulePkg/Core/DxeIplPeim/DxeLoad.c @@ -10,42 +10,41 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeIpl.h" - // // Module Globals used in the DXE to PEI hand off // These must be module globals, so the stack can be switched // -CONST EFI_DXE_IPL_PPI mDxeIplPpi = { +CONST EFI_DXE_IPL_PPI mDxeIplPpi = { DxeLoadCore }; -CONST EFI_PEI_PPI_DESCRIPTOR mDxeIplPpiList = { +CONST EFI_PEI_PPI_DESCRIPTOR mDxeIplPpiList = { EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, &gEfiDxeIplPpiGuid, - (VOID *) &mDxeIplPpi + (VOID *)&mDxeIplPpi }; -CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI mCustomGuidedSectionExtractionPpi = { +CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI mCustomGuidedSectionExtractionPpi = { CustomGuidedSectionExtract }; -CONST EFI_PEI_DECOMPRESS_PPI mDecompressPpi = { +CONST EFI_PEI_DECOMPRESS_PPI mDecompressPpi = { Decompress }; -CONST EFI_PEI_PPI_DESCRIPTOR mDecompressPpiList = { +CONST EFI_PEI_PPI_DESCRIPTOR mDecompressPpiList = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiPeiDecompressPpiGuid, - (VOID *) &mDecompressPpi + (VOID *)&mDecompressPpi }; -CONST EFI_PEI_PPI_DESCRIPTOR gEndOfPeiSignalPpi = { +CONST EFI_PEI_PPI_DESCRIPTOR gEndOfPeiSignalPpi = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiEndOfPeiSignalPpiGuid, NULL }; -CONST EFI_PEI_NOTIFY_DESCRIPTOR mMemoryDiscoveredNotifyList = { +CONST EFI_PEI_NOTIFY_DESCRIPTOR mMemoryDiscoveredNotifyList = { (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_DISPATCH | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiPeiMemoryDiscoveredPpiGuid, InstallIplPermanentMemoryPpis @@ -71,9 +70,9 @@ PeimInitializeDxeIpl ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - EFI_BOOT_MODE BootMode; - VOID *Dummy; + EFI_STATUS Status; + EFI_BOOT_MODE BootMode; + VOID *Dummy; BootMode = GetBootModeHob (); @@ -98,7 +97,7 @@ PeimInitializeDxeIpl ( &gEfiPeiMemoryDiscoveredPpiGuid, 0, NULL, - (VOID **) &Dummy + (VOID **)&Dummy ); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { @@ -124,7 +123,7 @@ PeimInitializeDxeIpl ( // Install DxeIpl PPI. // Status = PeiServicesInstallPpi (&mDxeIplPpiList); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); return Status; } @@ -148,10 +147,10 @@ InstallIplPermanentMemoryPpis ( IN VOID *Ppi ) { - EFI_STATUS Status; - EFI_GUID *ExtractHandlerGuidTable; - UINTN ExtractHandlerNumber; - EFI_PEI_PPI_DESCRIPTOR *GuidPpi; + EFI_STATUS Status; + EFI_GUID *ExtractHandlerGuidTable; + UINTN ExtractHandlerNumber; + EFI_PEI_PPI_DESCRIPTOR *GuidPpi; // // Get custom extract guided section method guid list @@ -162,14 +161,14 @@ InstallIplPermanentMemoryPpis ( // Install custom guided section extraction PPI // if (ExtractHandlerNumber > 0) { - GuidPpi = (EFI_PEI_PPI_DESCRIPTOR *) AllocatePool (ExtractHandlerNumber * sizeof (EFI_PEI_PPI_DESCRIPTOR)); + GuidPpi = (EFI_PEI_PPI_DESCRIPTOR *)AllocatePool (ExtractHandlerNumber * sizeof (EFI_PEI_PPI_DESCRIPTOR)); ASSERT (GuidPpi != NULL); while (ExtractHandlerNumber-- > 0) { GuidPpi->Flags = EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST; - GuidPpi->Ppi = (VOID *) &mCustomGuidedSectionExtractionPpi; + GuidPpi->Ppi = (VOID *)&mCustomGuidedSectionExtractionPpi; GuidPpi->Guid = &ExtractHandlerGuidTable[ExtractHandlerNumber]; - Status = PeiServicesInstallPpi (GuidPpi++); - ASSERT_EFI_ERROR(Status); + Status = PeiServicesInstallPpi (GuidPpi++); + ASSERT_EFI_ERROR (Status); } } @@ -177,7 +176,7 @@ InstallIplPermanentMemoryPpis ( // Install Decompress PPI. // Status = PeiServicesInstallPpi (&mDecompressPpiList); - ASSERT_EFI_ERROR(Status); + ASSERT_EFI_ERROR (Status); return Status; } @@ -194,12 +193,12 @@ InstallIplPermanentMemoryPpis ( **/ BOOLEAN ValidateMemoryTypeInfoVariable ( - IN EFI_MEMORY_TYPE_INFORMATION *MemoryData, - IN UINTN MemoryDataSize + IN EFI_MEMORY_TYPE_INFORMATION *MemoryData, + IN UINTN MemoryDataSize ) { - UINTN Count; - UINTN Index; + UINTN Count; + UINTN Index; // Check the input parameter. if (MemoryData == NULL) { @@ -210,7 +209,7 @@ ValidateMemoryTypeInfoVariable ( Count = MemoryDataSize / sizeof (*MemoryData); // Check Size - if (Count * sizeof(*MemoryData) != MemoryDataSize) { + if (Count * sizeof (*MemoryData) != MemoryDataSize) { return FALSE; } @@ -246,28 +245,28 @@ ValidateMemoryTypeInfoVariable ( EFI_STATUS EFIAPI DxeLoadCore ( - IN CONST EFI_DXE_IPL_PPI *This, - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_HOB_POINTERS HobList + IN CONST EFI_DXE_IPL_PPI *This, + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_HOB_POINTERS HobList ) { - EFI_STATUS Status; - EFI_FV_FILE_INFO DxeCoreFileInfo; - EFI_PHYSICAL_ADDRESS DxeCoreAddress; - UINT64 DxeCoreSize; - EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint; - EFI_BOOT_MODE BootMode; - EFI_PEI_FILE_HANDLE FileHandle; - EFI_PEI_READ_ONLY_VARIABLE2_PPI *Variable; - EFI_PEI_LOAD_FILE_PPI *LoadFile; - UINTN Instance; - UINT32 AuthenticationState; - UINTN DataSize; - EFI_PEI_S3_RESUME2_PPI *S3Resume; - EFI_PEI_RECOVERY_MODULE_PPI *PeiRecovery; - EDKII_PEI_CAPSULE_ON_DISK_PPI *PeiCapsuleOnDisk; - EFI_MEMORY_TYPE_INFORMATION MemoryData[EfiMaxMemoryType + 1]; - VOID *CapsuleOnDiskModePpi; + EFI_STATUS Status; + EFI_FV_FILE_INFO DxeCoreFileInfo; + EFI_PHYSICAL_ADDRESS DxeCoreAddress; + UINT64 DxeCoreSize; + EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint; + EFI_BOOT_MODE BootMode; + EFI_PEI_FILE_HANDLE FileHandle; + EFI_PEI_READ_ONLY_VARIABLE2_PPI *Variable; + EFI_PEI_LOAD_FILE_PPI *LoadFile; + UINTN Instance; + UINT32 AuthenticationState; + UINTN DataSize; + EFI_PEI_S3_RESUME2_PPI *S3Resume; + EFI_PEI_RECOVERY_MODULE_PPI *PeiRecovery; + EDKII_PEI_CAPSULE_ON_DISK_PPI *PeiCapsuleOnDisk; + EFI_MEMORY_TYPE_INFORMATION MemoryData[EfiMaxMemoryType + 1]; + VOID *CapsuleOnDiskModePpi; // // if in S3 Resume, restore configure @@ -279,7 +278,7 @@ DxeLoadCore ( &gEfiPeiS3Resume2PpiGuid, 0, NULL, - (VOID **) &S3Resume + (VOID **)&S3Resume ); if (EFI_ERROR (Status)) { // @@ -290,6 +289,7 @@ DxeLoadCore ( (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_EC_S3_RESUME_PPI_NOT_FOUND) ); } + ASSERT_EFI_ERROR (Status); Status = S3Resume->S3RestoreConfig2 (S3Resume); @@ -300,7 +300,7 @@ DxeLoadCore ( &gEfiPeiRecoveryModulePpiGuid, 0, NULL, - (VOID **) &PeiRecovery + (VOID **)&PeiRecovery ); if (EFI_ERROR (Status)) { @@ -328,6 +328,7 @@ DxeLoadCore ( ); CpuDeadLoop (); } + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_PC_CAPSULE_START)); // // Now should have a HOB with the DXE core @@ -343,12 +344,12 @@ DxeLoadCore ( NULL, &CapsuleOnDiskModePpi ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { Status = PeiServicesLocatePpi ( &gEdkiiPeiCapsuleOnDiskPpiGuid, 0, NULL, - (VOID **) &PeiCapsuleOnDisk + (VOID **)&PeiCapsuleOnDisk ); // @@ -372,15 +373,15 @@ DxeLoadCore ( ); if (!EFI_ERROR (Status)) { DataSize = sizeof (MemoryData); - Status = Variable->GetVariable ( - Variable, - EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME, - &gEfiMemoryTypeInformationGuid, - NULL, - &DataSize, - &MemoryData - ); - if (!EFI_ERROR (Status) && ValidateMemoryTypeInfoVariable(MemoryData, DataSize)) { + Status = Variable->GetVariable ( + Variable, + EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME, + &gEfiMemoryTypeInformationGuid, + NULL, + &DataSize, + &MemoryData + ); + if (!EFI_ERROR (Status) && ValidateMemoryTypeInfoVariable (MemoryData, DataSize)) { // // Build the GUID'd HOB for DXE // @@ -403,7 +404,7 @@ DxeLoadCore ( // Instance = 0; do { - Status = PeiServicesLocatePpi (&gEfiPeiLoadFilePpiGuid, Instance++, NULL, (VOID **) &LoadFile); + Status = PeiServicesLocatePpi (&gEfiPeiLoadFilePpiGuid, Instance++, NULL, (VOID **)&LoadFile); // // These must exist an instance of EFI_PEI_LOAD_FILE_PPI to support to load DxeCore file handle successfully. // @@ -457,7 +458,6 @@ DxeLoadCore ( return EFI_OUT_OF_RESOURCES; } - /** Searches DxeCore in all firmware Volumes and loads the first instance that contains DxeCore. @@ -470,12 +470,12 @@ DxeIplFindDxeCore ( VOID ) { - EFI_STATUS Status; - UINTN Instance; - EFI_PEI_FV_HANDLE VolumeHandle; - EFI_PEI_FILE_HANDLE FileHandle; + EFI_STATUS Status; + UINTN Instance; + EFI_PEI_FV_HANDLE VolumeHandle; + EFI_PEI_FILE_HANDLE FileHandle; - Instance = 0; + Instance = 0; while (TRUE) { // // Traverse all firmware volume instances @@ -488,13 +488,14 @@ DxeIplFindDxeCore ( if (EFI_ERROR (Status)) { REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_PEI_MODULE | EFI_SW_PEI_CORE_EC_DXE_CORRUPT)); } + ASSERT_EFI_ERROR (Status); // // Find the DxeCore file type from the beginning in this firmware volume. // FileHandle = NULL; - Status = PeiServicesFfsFindNextFile (EFI_FV_FILETYPE_DXE_CORE, VolumeHandle, &FileHandle); + Status = PeiServicesFfsFindNextFile (EFI_FV_FILETYPE_DXE_CORE, VolumeHandle, &FileHandle); if (!EFI_ERROR (Status)) { // // Find DxeCore FileHandle in this volume, then we skip other firmware volume and @@ -502,6 +503,7 @@ DxeIplFindDxeCore ( // return FileHandle; } + // // We cannot find DxeCore in this firmware volume, then search the next volume. // @@ -509,8 +511,6 @@ DxeIplFindDxeCore ( } } - - /** The ExtractSection() function processes the input section and returns a pointer to the section contents. If the section being @@ -568,18 +568,18 @@ DxeIplFindDxeCore ( EFI_STATUS EFIAPI CustomGuidedSectionExtract ( - IN CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *This, - IN CONST VOID *InputSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize, - OUT UINT32 *AuthenticationStatus -) + IN CONST EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *This, + IN CONST VOID *InputSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize, + OUT UINT32 *AuthenticationStatus + ) { - EFI_STATUS Status; - UINT8 *ScratchBuffer; - UINT32 ScratchBufferSize; - UINT32 OutputBufferSize; - UINT16 SectionAttribute; + EFI_STATUS Status; + UINT8 *ScratchBuffer; + UINT32 ScratchBufferSize; + UINT32 OutputBufferSize; + UINT16 SectionAttribute; // // Init local variable @@ -611,7 +611,7 @@ CustomGuidedSectionExtract ( } } - if (((SectionAttribute & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) && OutputBufferSize > 0) { + if (((SectionAttribute & EFI_GUIDED_SECTION_PROCESSING_REQUIRED) != 0) && (OutputBufferSize > 0)) { // // Allocate output buffer // @@ -619,6 +619,7 @@ CustomGuidedSectionExtract ( if (*OutputBuffer == NULL) { return EFI_OUT_OF_RESOURCES; } + DEBUG ((DEBUG_INFO, "Customized Guided section Memory Size required is 0x%x and address is 0x%p\n", OutputBufferSize, *OutputBuffer)); } @@ -636,13 +637,11 @@ CustomGuidedSectionExtract ( return Status; } - *OutputSize = (UINTN) OutputBufferSize; + *OutputSize = (UINTN)OutputBufferSize; return EFI_SUCCESS; } - - /** Decompresses a section to the output buffer. @@ -666,21 +665,21 @@ CustomGuidedSectionExtract ( EFI_STATUS EFIAPI Decompress ( - IN CONST EFI_PEI_DECOMPRESS_PPI *This, - IN CONST EFI_COMPRESSION_SECTION *CompressionSection, - OUT VOID **OutputBuffer, - OUT UINTN *OutputSize - ) + IN CONST EFI_PEI_DECOMPRESS_PPI *This, + IN CONST EFI_COMPRESSION_SECTION *CompressionSection, + OUT VOID **OutputBuffer, + OUT UINTN *OutputSize + ) { - EFI_STATUS Status; - UINT8 *DstBuffer; - UINT8 *ScratchBuffer; - UINT32 DstBufferSize; - UINT32 ScratchBufferSize; - VOID *CompressionSource; - UINT32 CompressionSourceSize; - UINT32 UncompressedLength; - UINT8 CompressionType; + EFI_STATUS Status; + UINT8 *DstBuffer; + UINT8 *ScratchBuffer; + UINT32 DstBufferSize; + UINT32 ScratchBufferSize; + VOID *CompressionSource; + UINT32 CompressionSourceSize; + UINT32 UncompressedLength; + UINT8 CompressionType; if (CompressionSection->CommonHeader.Type != EFI_SECTION_COMPRESSION) { ASSERT (FALSE); @@ -688,109 +687,113 @@ Decompress ( } if (IS_SECTION2 (CompressionSection)) { - CompressionSource = (VOID *) ((UINT8 *) CompressionSection + sizeof (EFI_COMPRESSION_SECTION2)); - CompressionSourceSize = (UINT32) (SECTION2_SIZE (CompressionSection) - sizeof (EFI_COMPRESSION_SECTION2)); - UncompressedLength = ((EFI_COMPRESSION_SECTION2 *) CompressionSection)->UncompressedLength; - CompressionType = ((EFI_COMPRESSION_SECTION2 *) CompressionSection)->CompressionType; + CompressionSource = (VOID *)((UINT8 *)CompressionSection + sizeof (EFI_COMPRESSION_SECTION2)); + CompressionSourceSize = (UINT32)(SECTION2_SIZE (CompressionSection) - sizeof (EFI_COMPRESSION_SECTION2)); + UncompressedLength = ((EFI_COMPRESSION_SECTION2 *)CompressionSection)->UncompressedLength; + CompressionType = ((EFI_COMPRESSION_SECTION2 *)CompressionSection)->CompressionType; } else { - CompressionSource = (VOID *) ((UINT8 *) CompressionSection + sizeof (EFI_COMPRESSION_SECTION)); - CompressionSourceSize = (UINT32) (SECTION_SIZE (CompressionSection) - sizeof (EFI_COMPRESSION_SECTION)); - UncompressedLength = CompressionSection->UncompressedLength; - CompressionType = CompressionSection->CompressionType; + CompressionSource = (VOID *)((UINT8 *)CompressionSection + sizeof (EFI_COMPRESSION_SECTION)); + CompressionSourceSize = (UINT32)(SECTION_SIZE (CompressionSection) - sizeof (EFI_COMPRESSION_SECTION)); + UncompressedLength = CompressionSection->UncompressedLength; + CompressionType = CompressionSection->CompressionType; } // // This is a compression set, expand it // switch (CompressionType) { - case EFI_STANDARD_COMPRESSION: - if (FeaturePcdGet(PcdDxeIplSupportUefiDecompress)) { - // - // Load EFI standard compression. - // For compressed data, decompress them to destination buffer. - // - Status = UefiDecompressGetInfo ( - CompressionSource, - CompressionSourceSize, - &DstBufferSize, - &ScratchBufferSize - ); - if (EFI_ERROR (Status)) { + case EFI_STANDARD_COMPRESSION: + if (FeaturePcdGet (PcdDxeIplSupportUefiDecompress)) { + // + // Load EFI standard compression. + // For compressed data, decompress them to destination buffer. + // + Status = UefiDecompressGetInfo ( + CompressionSource, + CompressionSourceSize, + &DstBufferSize, + &ScratchBufferSize + ); + if (EFI_ERROR (Status)) { + // + // GetInfo failed + // + DEBUG ((DEBUG_ERROR, "Decompress GetInfo Failed - %r\n", Status)); + return EFI_NOT_FOUND; + } + + // + // Allocate scratch buffer + // + ScratchBuffer = AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize)); + if (ScratchBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Allocate destination buffer + // + DstBuffer = AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize)); + if (DstBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + // - // GetInfo failed + // Call decompress function // - DEBUG ((DEBUG_ERROR, "Decompress GetInfo Failed - %r\n", Status)); + Status = UefiDecompress ( + CompressionSource, + DstBuffer, + ScratchBuffer + ); + if (EFI_ERROR (Status)) { + // + // Decompress failed + // + DEBUG ((DEBUG_ERROR, "Decompress Failed - %r\n", Status)); + return EFI_NOT_FOUND; + } + + break; + } else { + // + // PcdDxeIplSupportUefiDecompress is FALSE + // Don't support UEFI decompression algorithm. + // + ASSERT (FALSE); return EFI_NOT_FOUND; } - // - // Allocate scratch buffer - // - ScratchBuffer = AllocatePages (EFI_SIZE_TO_PAGES (ScratchBufferSize)); - if (ScratchBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } + + case EFI_NOT_COMPRESSED: // // Allocate destination buffer // - DstBuffer = AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize)); + DstBufferSize = UncompressedLength; + DstBuffer = AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize)); if (DstBuffer == NULL) { return EFI_OUT_OF_RESOURCES; } + // - // Call decompress function + // stream is not actually compressed, just encapsulated. So just copy it. // - Status = UefiDecompress ( - CompressionSource, - DstBuffer, - ScratchBuffer - ); - if (EFI_ERROR (Status)) { - // - // Decompress failed - // - DEBUG ((DEBUG_ERROR, "Decompress Failed - %r\n", Status)); - return EFI_NOT_FOUND; - } + CopyMem (DstBuffer, CompressionSource, DstBufferSize); break; - } else { + + default: // - // PcdDxeIplSupportUefiDecompress is FALSE - // Don't support UEFI decompression algorithm. + // Don't support other unknown compression type. // ASSERT (FALSE); return EFI_NOT_FOUND; - } - - case EFI_NOT_COMPRESSED: - // - // Allocate destination buffer - // - DstBufferSize = UncompressedLength; - DstBuffer = AllocatePages (EFI_SIZE_TO_PAGES (DstBufferSize)); - if (DstBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - // - // stream is not actually compressed, just encapsulated. So just copy it. - // - CopyMem (DstBuffer, CompressionSource, DstBufferSize); - break; - - default: - // - // Don't support other unknown compression type. - // - ASSERT (FALSE); - return EFI_NOT_FOUND; } - *OutputSize = DstBufferSize; + *OutputSize = DstBufferSize; *OutputBuffer = DstBuffer; return EFI_SUCCESS; } - /** Updates the Stack HOB passed to DXE phase. @@ -803,11 +806,11 @@ Decompress ( **/ VOID UpdateStackHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length ) { - EFI_PEI_HOB_POINTERS Hob; + EFI_PEI_HOB_POINTERS Hob; Hob.Raw = GetHobList (); while ((Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw)) != NULL) { @@ -826,10 +829,10 @@ UpdateStackHob ( // Update the BSP Stack Hob to reflect the new stack info. // Hob.MemoryAllocationStack->AllocDescriptor.MemoryBaseAddress = BaseAddress; - Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength = Length; + Hob.MemoryAllocationStack->AllocDescriptor.MemoryLength = Length; break; } + Hob.Raw = GET_NEXT_HOB (Hob); } } - diff --git a/MdeModulePkg/Core/DxeIplPeim/Ebc/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Ebc/DxeLoadFunc.c index 5da42ff4de..c1a16b6024 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Ebc/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Ebc/DxeLoadFunc.c @@ -8,8 +8,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeIpl.h" - - /** Transfers control to DxeCore. @@ -23,13 +21,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ) { - VOID *BaseOfStack; - VOID *TopOfStack; - EFI_STATUS Status; + VOID *BaseOfStack; + VOID *TopOfStack; + EFI_STATUS Status; // // Allocate 128KB for the Stack @@ -41,7 +39,7 @@ HandOffToDxeCore ( // Compute the top of the stack we were allocated. Pre-allocate a UINTN // for safety. // - TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); + TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); // @@ -53,7 +51,7 @@ HandOffToDxeCore ( // // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. // - UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, STACK_SIZE); + UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE); // // Transfer the control to the entry point of DxeCore. diff --git a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c index b65b01c9e5..fdeaaa39d8 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c @@ -11,43 +11,61 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeIpl.h" #include "VirtualMemory.h" -#define IDT_ENTRY_COUNT 32 +#define IDT_ENTRY_COUNT 32 typedef struct _X64_IDT_TABLE { // // Reserved 4 bytes preceding PeiService and IdtTable, // since IDT base address should be 8-byte alignment. // - UINT32 Reserved; - CONST EFI_PEI_SERVICES **PeiService; - X64_IDT_GATE_DESCRIPTOR IdtTable[IDT_ENTRY_COUNT]; + UINT32 Reserved; + CONST EFI_PEI_SERVICES **PeiService; + X64_IDT_GATE_DESCRIPTOR IdtTable[IDT_ENTRY_COUNT]; } X64_IDT_TABLE; // // Global Descriptor Table (GDT) // -GLOBAL_REMOVE_IF_UNREFERENCED IA32_GDT gGdtEntries[] = { -/* selector { Global Segment Descriptor } */ -/* 0x00 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, //null descriptor -/* 0x08 */ {{0xffff, 0, 0, 0x2, 1, 0, 1, 0xf, 0, 0, 1, 1, 0}}, //linear data segment descriptor -/* 0x10 */ {{0xffff, 0, 0, 0xf, 1, 0, 1, 0xf, 0, 0, 1, 1, 0}}, //linear code segment descriptor -/* 0x18 */ {{0xffff, 0, 0, 0x3, 1, 0, 1, 0xf, 0, 0, 1, 1, 0}}, //system data segment descriptor -/* 0x20 */ {{0xffff, 0, 0, 0xa, 1, 0, 1, 0xf, 0, 0, 1, 1, 0}}, //system code segment descriptor -/* 0x28 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, //spare segment descriptor -/* 0x30 */ {{0xffff, 0, 0, 0x2, 1, 0, 1, 0xf, 0, 0, 1, 1, 0}}, //system data segment descriptor -/* 0x38 */ {{0xffff, 0, 0, 0xa, 1, 0, 1, 0xf, 0, 1, 0, 1, 0}}, //system code segment descriptor -/* 0x40 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, //spare segment descriptor +GLOBAL_REMOVE_IF_UNREFERENCED IA32_GDT gGdtEntries[] = { + /* selector { Global Segment Descriptor } */ + /* 0x00 */ { + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + }, // null descriptor + /* 0x08 */ { + { 0xffff, 0, 0, 0x2, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 } + }, // linear data segment descriptor + /* 0x10 */ { + { 0xffff, 0, 0, 0xf, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 } + }, // linear code segment descriptor + /* 0x18 */ { + { 0xffff, 0, 0, 0x3, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 } + }, // system data segment descriptor + /* 0x20 */ { + { 0xffff, 0, 0, 0xa, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 } + }, // system code segment descriptor + /* 0x28 */ { + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + }, // spare segment descriptor + /* 0x30 */ { + { 0xffff, 0, 0, 0x2, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 } + }, // system data segment descriptor + /* 0x38 */ { + { 0xffff, 0, 0, 0xa, 1, 0, 1, 0xf, 0, 1, 0, 1, 0 } + }, // system code segment descriptor + /* 0x40 */ { + { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } + }, // spare segment descriptor }; // // IA32 Gdt register // -GLOBAL_REMOVE_IF_UNREFERENCED CONST IA32_DESCRIPTOR gGdt = { +GLOBAL_REMOVE_IF_UNREFERENCED CONST IA32_DESCRIPTOR gGdt = { sizeof (gGdtEntries) - 1, - (UINTN) gGdtEntries - }; + (UINTN)gGdtEntries +}; -GLOBAL_REMOVE_IF_UNREFERENCED IA32_DESCRIPTOR gLidtDescriptor = { +GLOBAL_REMOVE_IF_UNREFERENCED IA32_DESCRIPTOR gLidtDescriptor = { sizeof (X64_IDT_GATE_DESCRIPTOR) * IDT_ENTRY_COUNT - 1, 0 }; @@ -64,21 +82,21 @@ GLOBAL_REMOVE_IF_UNREFERENCED IA32_DESCRIPTOR gLidtDescriptor = { **/ UINTN Create4GPageTablesIa32Pae ( - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize ) { - UINT8 PhysicalAddressBits; - EFI_PHYSICAL_ADDRESS PhysicalAddress; - UINTN IndexOfPdpEntries; - UINTN IndexOfPageDirectoryEntries; - UINT32 NumberOfPdpEntriesNeeded; - PAGE_MAP_AND_DIRECTORY_POINTER *PageMap; - PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry; - PAGE_TABLE_ENTRY *PageDirectoryEntry; - UINTN TotalPagesNum; - UINTN PageAddress; - UINT64 AddressEncMask; + UINT8 PhysicalAddressBits; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + UINTN IndexOfPdpEntries; + UINTN IndexOfPageDirectoryEntries; + UINT32 NumberOfPdpEntriesNeeded; + PAGE_MAP_AND_DIRECTORY_POINTER *PageMap; + PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry; + PAGE_TABLE_ENTRY *PageDirectoryEntry; + UINTN TotalPagesNum; + UINTN PageAddress; + UINT64 AddressEncMask; // // Make sure AddressEncMask is contained to smallest supported address field @@ -90,53 +108,54 @@ Create4GPageTablesIa32Pae ( // // Calculate the table entries needed. // - NumberOfPdpEntriesNeeded = (UINT32) LShiftU64 (1, (PhysicalAddressBits - 30)); + NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, (PhysicalAddressBits - 30)); TotalPagesNum = NumberOfPdpEntriesNeeded + 1; - PageAddress = (UINTN) AllocatePageTableMemory (TotalPagesNum); + PageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum); ASSERT (PageAddress != 0); - PageMap = (VOID *) PageAddress; + PageMap = (VOID *)PageAddress; PageAddress += SIZE_4KB; PageDirectoryPointerEntry = PageMap; - PhysicalAddress = 0; + PhysicalAddress = 0; for (IndexOfPdpEntries = 0; IndexOfPdpEntries < NumberOfPdpEntriesNeeded; IndexOfPdpEntries++, PageDirectoryPointerEntry++) { // // Each Directory Pointer entries points to a page of Page Directory entires. // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop. // - PageDirectoryEntry = (VOID *) PageAddress; - PageAddress += SIZE_4KB; + PageDirectoryEntry = (VOID *)PageAddress; + PageAddress += SIZE_4KB; // // Fill in a Page Directory Pointer Entries // - PageDirectoryPointerEntry->Uint64 = (UINT64) (UINTN) PageDirectoryEntry | AddressEncMask; + PageDirectoryPointerEntry->Uint64 = (UINT64)(UINTN)PageDirectoryEntry | AddressEncMask; PageDirectoryPointerEntry->Bits.Present = 1; for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PhysicalAddress += SIZE_2MB) { - if ((IsNullDetectionEnabled () && PhysicalAddress == 0) - || ((PhysicalAddress < StackBase + StackSize) - && ((PhysicalAddress + SIZE_2MB) > StackBase))) { + if ( (IsNullDetectionEnabled () && (PhysicalAddress == 0)) + || ( (PhysicalAddress < StackBase + StackSize) + && ((PhysicalAddress + SIZE_2MB) > StackBase))) + { // // Need to split this 2M page that covers stack range. // - Split2MPageTo4K (PhysicalAddress, (UINT64 *) PageDirectoryEntry, StackBase, StackSize, 0, 0); + Split2MPageTo4K (PhysicalAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize, 0, 0); } else { // // Fill in the Page Directory entries // - PageDirectoryEntry->Uint64 = (UINT64) PhysicalAddress | AddressEncMask; + PageDirectoryEntry->Uint64 = (UINT64)PhysicalAddress | AddressEncMask; PageDirectoryEntry->Bits.ReadWrite = 1; - PageDirectoryEntry->Bits.Present = 1; - PageDirectoryEntry->Bits.MustBe1 = 1; + PageDirectoryEntry->Bits.Present = 1; + PageDirectoryEntry->Bits.MustBe1 = 1; } } } - for (; IndexOfPdpEntries < 512; IndexOfPdpEntries++, PageDirectoryPointerEntry++) { + for ( ; IndexOfPdpEntries < 512; IndexOfPdpEntries++, PageDirectoryPointerEntry++) { ZeroMem ( PageDirectoryPointerEntry, sizeof (PAGE_MAP_AND_DIRECTORY_POINTER) @@ -149,7 +168,7 @@ Create4GPageTablesIa32Pae ( // EnablePageTableProtection ((UINTN)PageMap, FALSE); - return (UINTN) PageMap; + return (UINTN)PageMap; } /** @@ -164,9 +183,9 @@ IsIa32PaeSupport ( VOID ) { - UINT32 RegEax; - UINT32 RegEdx; - BOOLEAN Ia32PaeSupport; + UINT32 RegEax; + UINT32 RegEdx; + BOOLEAN Ia32PaeSupport; Ia32PaeSupport = FALSE; AsmCpuid (0x0, &RegEax, NULL, NULL, NULL); @@ -228,23 +247,23 @@ ToBuildPageTable ( **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS BaseOfStack; - EFI_PHYSICAL_ADDRESS TopOfStack; - UINTN PageTables; - X64_IDT_GATE_DESCRIPTOR *IdtTable; - UINTN SizeOfTemplate; - VOID *TemplateBase; - EFI_PHYSICAL_ADDRESS VectorAddress; - UINT32 Index; - X64_IDT_TABLE *IdtTableForX64; - EFI_VECTOR_HANDOFF_INFO *VectorInfo; - EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; - BOOLEAN BuildPageTablesIa32Pae; + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS BaseOfStack; + EFI_PHYSICAL_ADDRESS TopOfStack; + UINTN PageTables; + X64_IDT_GATE_DESCRIPTOR *IdtTable; + UINTN SizeOfTemplate; + VOID *TemplateBase; + EFI_PHYSICAL_ADDRESS VectorAddress; + UINT32 Index; + X64_IDT_TABLE *IdtTableForX64; + EFI_VECTOR_HANDOFF_INFO *VectorInfo; + EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; + BOOLEAN BuildPageTablesIa32Pae; // // Clear page 0 and mark it as allocated if NULL pointer detection is enabled. @@ -257,7 +276,7 @@ HandOffToDxeCore ( Status = PeiServicesAllocatePages (EfiBootServicesData, EFI_SIZE_TO_PAGES (STACK_SIZE), &BaseOfStack); ASSERT_EFI_ERROR (Status); - if (FeaturePcdGet(PcdDxeIplSwitchToLongMode)) { + if (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) { // // Compute the top of the stack we were allocated, which is used to load X64 dxe core. // Pre-allocate a 32 bytes which confroms to x64 calling convention. @@ -272,7 +291,7 @@ HandOffToDxeCore ( // // x64 Calling Conventions requires that the stack must be aligned to 16 bytes // - TopOfStack = (EFI_PHYSICAL_ADDRESS) (UINTN) ALIGN_POINTER (TopOfStack, 16); + TopOfStack = (EFI_PHYSICAL_ADDRESS)(UINTN)ALIGN_POINTER (TopOfStack, 16); // // Load the GDT of Go64. Since the GDT of 32-bit Tiano locates in the BS_DATA @@ -308,7 +327,7 @@ HandOffToDxeCore ( Status = PeiServicesAllocatePages ( EfiBootServicesData, - EFI_SIZE_TO_PAGES(sizeof (X64_IDT_TABLE) + SizeOfTemplate * IDT_ENTRY_COUNT), + EFI_SIZE_TO_PAGES (sizeof (X64_IDT_TABLE) + SizeOfTemplate * IDT_ENTRY_COUNT), &VectorAddress ); ASSERT_EFI_ERROR (Status); @@ -317,28 +336,28 @@ HandOffToDxeCore ( // Store EFI_PEI_SERVICES** in the 4 bytes immediately preceding IDT to avoid that // it may not be gotten correctly after IDT register is re-written. // - IdtTableForX64 = (X64_IDT_TABLE *) (UINTN) VectorAddress; + IdtTableForX64 = (X64_IDT_TABLE *)(UINTN)VectorAddress; IdtTableForX64->PeiService = GetPeiServicesTablePointer (); - VectorAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) (IdtTableForX64 + 1); + VectorAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)(IdtTableForX64 + 1); IdtTable = IdtTableForX64->IdtTable; for (Index = 0; Index < IDT_ENTRY_COUNT; Index++) { - IdtTable[Index].Ia32IdtEntry.Bits.GateType = 0x8e; - IdtTable[Index].Ia32IdtEntry.Bits.Reserved_0 = 0; - IdtTable[Index].Ia32IdtEntry.Bits.Selector = SYS_CODE64_SEL; + IdtTable[Index].Ia32IdtEntry.Bits.GateType = 0x8e; + IdtTable[Index].Ia32IdtEntry.Bits.Reserved_0 = 0; + IdtTable[Index].Ia32IdtEntry.Bits.Selector = SYS_CODE64_SEL; - IdtTable[Index].Ia32IdtEntry.Bits.OffsetLow = (UINT16) VectorAddress; - IdtTable[Index].Ia32IdtEntry.Bits.OffsetHigh = (UINT16) (RShiftU64 (VectorAddress, 16)); - IdtTable[Index].Offset32To63 = (UINT32) (RShiftU64 (VectorAddress, 32)); - IdtTable[Index].Reserved = 0; + IdtTable[Index].Ia32IdtEntry.Bits.OffsetLow = (UINT16)VectorAddress; + IdtTable[Index].Ia32IdtEntry.Bits.OffsetHigh = (UINT16)(RShiftU64 (VectorAddress, 16)); + IdtTable[Index].Offset32To63 = (UINT32)(RShiftU64 (VectorAddress, 32)); + IdtTable[Index].Reserved = 0; - CopyMem ((VOID *) (UINTN) VectorAddress, TemplateBase, SizeOfTemplate); - AsmVectorFixup ((VOID *) (UINTN) VectorAddress, (UINT8) Index); + CopyMem ((VOID *)(UINTN)VectorAddress, TemplateBase, SizeOfTemplate); + AsmVectorFixup ((VOID *)(UINTN)VectorAddress, (UINT8)Index); VectorAddress += SizeOfTemplate; } - gLidtDescriptor.Base = (UINTN) IdtTable; + gLidtDescriptor.Base = (UINTN)IdtTable; // // Disable interrupt of Debug timer, since new IDT table cannot handle it. @@ -380,11 +399,12 @@ HandOffToDxeCore ( if (Status == EFI_SUCCESS) { DEBUG ((DEBUG_INFO, "Vector Hand-off Info PPI is gotten, GUIDed HOB is created!\n")); VectorInfo = VectorHandoffInfoPpi->Info; - Index = 1; + Index = 1; while (VectorInfo->Attribute != EFI_VECTOR_HANDOFF_LAST_ENTRY) { - VectorInfo ++; - Index ++; + VectorInfo++; + Index++; } + BuildGuidDataHob ( &gEfiVectorHandoffInfoPpiGuid, VectorHandoffInfoPpi->Info, @@ -397,14 +417,14 @@ HandOffToDxeCore ( // for safety. // TopOfStack = BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT; - TopOfStack = (EFI_PHYSICAL_ADDRESS) (UINTN) ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); + TopOfStack = (EFI_PHYSICAL_ADDRESS)(UINTN)ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); - PageTables = 0; + PageTables = 0; BuildPageTablesIa32Pae = ToBuildPageTable (); if (BuildPageTablesIa32Pae) { PageTables = Create4GPageTablesIa32Pae (BaseOfStack, STACK_SIZE); if (IsEnableNonExecNeeded ()) { - EnableExecuteDisableBit(); + EnableExecuteDisableBit (); } } @@ -450,14 +470,14 @@ HandOffToDxeCore ( (SWITCH_STACK_ENTRY_POINT)(UINTN)DxeCoreEntryPoint, HobList.Raw, NULL, - (VOID *) (UINTN) TopOfStack + (VOID *)(UINTN)TopOfStack ); } else { SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)DxeCoreEntryPoint, HobList.Raw, NULL, - (VOID *) (UINTN) TopOfStack + (VOID *)(UINTN)TopOfStack ); } } diff --git a/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c index 2ce52eb0ec..f7b57df1c4 100644 --- a/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/RiscV64/DxeLoadFunc.c @@ -22,28 +22,29 @@ **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ) { - VOID *BaseOfStack; - VOID *TopOfStack; - EFI_STATUS Status; + VOID *BaseOfStack; + VOID *TopOfStack; + EFI_STATUS Status; + // // // Allocate 128KB for the Stack // BaseOfStack = AllocatePages (EFI_SIZE_TO_PAGES (STACK_SIZE)); if (BaseOfStack == NULL) { - DEBUG((DEBUG_ERROR, "%a: Can't allocate memory for stack.", __FUNCTION__)); - ASSERT(FALSE); + DEBUG ((DEBUG_ERROR, "%a: Can't allocate memory for stack.", __FUNCTION__)); + ASSERT (FALSE); } // // Compute the top of the stack we were allocated. Pre-allocate a UINTN // for safety. // - TopOfStack = (VOID *)((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); + TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); // @@ -51,13 +52,14 @@ HandOffToDxeCore ( // Status = PeiServicesInstallPpi (&gEndOfPeiSignalPpi); if (EFI_ERROR (Status)) { - DEBUG((DEBUG_ERROR, "%a: Fail to signal End of PEI event.", __FUNCTION__)); - ASSERT(FALSE); + DEBUG ((DEBUG_ERROR, "%a: Fail to signal End of PEI event.", __FUNCTION__)); + ASSERT (FALSE); } + // // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. // - UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, STACK_SIZE); + UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE); DEBUG ((DEBUG_INFO, "DXE Core new stack at %x, stack pointer at %x\n", BaseOfStack, TopOfStack)); @@ -71,4 +73,3 @@ HandOffToDxeCore ( TopOfStack ); } - diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c index 813445b1ef..fa2050cf02 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c @@ -9,8 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "DxeIpl.h" #include "X64/VirtualMemory.h" - - /** Transfers control to DxeCore. @@ -24,19 +22,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID HandOffToDxeCore ( - IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, - IN EFI_PEI_HOB_POINTERS HobList + IN EFI_PHYSICAL_ADDRESS DxeCoreEntryPoint, + IN EFI_PEI_HOB_POINTERS HobList ) { - VOID *BaseOfStack; - VOID *TopOfStack; - EFI_STATUS Status; - UINTN PageTables; - UINT32 Index; - EFI_VECTOR_HANDOFF_INFO *VectorInfo; - EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; - VOID *GhcbBase; - UINTN GhcbSize; + VOID *BaseOfStack; + VOID *TopOfStack; + EFI_STATUS Status; + UINTN PageTables; + UINT32 Index; + EFI_VECTOR_HANDOFF_INFO *VectorInfo; + EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; + VOID *GhcbBase; + UINTN GhcbSize; // // Clear page 0 and mark it as allocated if NULL pointer detection is enabled. @@ -58,11 +56,12 @@ HandOffToDxeCore ( if (Status == EFI_SUCCESS) { DEBUG ((DEBUG_INFO, "Vector Hand-off Info PPI is gotten, GUIDed HOB is created!\n")); VectorInfo = VectorHandoffInfoPpi->Info; - Index = 1; + Index = 1; while (VectorInfo->Attribute != EFI_VECTOR_HANDOFF_LAST_ENTRY) { - VectorInfo ++; - Index ++; + VectorInfo++; + Index++; } + BuildGuidDataHob ( &gEfiVectorHandoffInfoPpiGuid, VectorHandoffInfoPpi->Info, @@ -80,13 +79,13 @@ HandOffToDxeCore ( // Compute the top of the stack we were allocated. Pre-allocate a UINTN // for safety. // - TopOfStack = (VOID *) ((UINTN) BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); + TopOfStack = (VOID *)((UINTN)BaseOfStack + EFI_SIZE_TO_PAGES (STACK_SIZE) * EFI_PAGE_SIZE - CPU_STACK_ALIGNMENT); TopOfStack = ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT); // // Get the address and size of the GHCB pages // - GhcbBase = (VOID *) PcdGet64 (PcdGhcbBase); + GhcbBase = (VOID *)PcdGet64 (PcdGhcbBase); GhcbSize = PcdGet64 (PcdGhcbSize); PageTables = 0; @@ -94,8 +93,12 @@ HandOffToDxeCore ( // // Create page table and save PageMapLevel4 to CR3 // - PageTables = CreateIdentityMappingPageTables ((EFI_PHYSICAL_ADDRESS) (UINTN) BaseOfStack, STACK_SIZE, - (EFI_PHYSICAL_ADDRESS) (UINTN) GhcbBase, GhcbSize); + PageTables = CreateIdentityMappingPageTables ( + (EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, + STACK_SIZE, + (EFI_PHYSICAL_ADDRESS)(UINTN)GhcbBase, + GhcbSize + ); } else { // // Set NX for stack feature also require PcdDxeIplBuildPageTables be TRUE @@ -118,7 +121,7 @@ HandOffToDxeCore ( // // Update the contents of BSP stack HOB to reflect the real stack info passed to DxeCore. // - UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN) BaseOfStack, STACK_SIZE); + UpdateStackHob ((EFI_PHYSICAL_ADDRESS)(UINTN)BaseOfStack, STACK_SIZE); // // Transfer the control to the entry point of DxeCore. diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c index 6831946c54..0700f310b2 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c +++ b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c @@ -29,7 +29,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Global variable to keep track current available memory used as page table. // -PAGE_TABLE_POOL *mPageTablePool = NULL; +PAGE_TABLE_POOL *mPageTablePool = NULL; /** Clear legacy memory located at the first 4K-page, if available. @@ -42,39 +42,50 @@ PAGE_TABLE_POOL *mPageTablePool = NULL; **/ VOID ClearFirst4KPage ( - IN VOID *HobStart + IN VOID *HobStart ) { - EFI_PEI_HOB_POINTERS RscHob; - EFI_PEI_HOB_POINTERS MemHob; - BOOLEAN DoClear; + EFI_PEI_HOB_POINTERS RscHob; + EFI_PEI_HOB_POINTERS MemHob; + BOOLEAN DoClear; RscHob.Raw = HobStart; MemHob.Raw = HobStart; - DoClear = FALSE; + DoClear = FALSE; // // Check if page 0 exists and free // - while ((RscHob.Raw = GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, - RscHob.Raw)) != NULL) { - if (RscHob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && - RscHob.ResourceDescriptor->PhysicalStart == 0) { + while ((RscHob.Raw = GetNextHob ( + EFI_HOB_TYPE_RESOURCE_DESCRIPTOR, + RscHob.Raw + )) != NULL) + { + if ((RscHob.ResourceDescriptor->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && + (RscHob.ResourceDescriptor->PhysicalStart == 0)) + { DoClear = TRUE; // // Make sure memory at 0-4095 has not been allocated. // - while ((MemHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, - MemHob.Raw)) != NULL) { + while ((MemHob.Raw = GetNextHob ( + EFI_HOB_TYPE_MEMORY_ALLOCATION, + MemHob.Raw + )) != NULL) + { if (MemHob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress - < EFI_PAGE_SIZE) { + < EFI_PAGE_SIZE) + { DoClear = FALSE; break; } + MemHob.Raw = GET_NEXT_HOB (MemHob); } + break; } + RscHob.Raw = GET_NEXT_HOB (RscHob); } @@ -113,9 +124,9 @@ IsExecuteDisableBitAvailable ( VOID ) { - UINT32 RegEax; - UINT32 RegEdx; - BOOLEAN Available; + UINT32 RegEax; + UINT32 RegEdx; + BOOLEAN Available; Available = FALSE; AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); @@ -166,9 +177,9 @@ EnableExecuteDisableBit ( VOID ) { - UINT64 MsrRegisters; + UINT64 MsrRegisters; - MsrRegisters = AsmReadMsr64 (0xC0000080); + MsrRegisters = AsmReadMsr64 (0xC0000080); MsrRegisters |= BIT11; AsmWriteMsr64 (0xC0000080, MsrRegisters); } @@ -189,20 +200,20 @@ EnableExecuteDisableBit ( **/ BOOLEAN ToSplitPageTable ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN Size, - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbSize + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN Size, + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbSize ) { - if (IsNullDetectionEnabled () && Address == 0) { + if (IsNullDetectionEnabled () && (Address == 0)) { return TRUE; } if (PcdGetBool (PcdCpuStackGuard)) { - if (StackBase >= Address && StackBase < (Address + Size)) { + if ((StackBase >= Address) && (StackBase < (Address + Size))) { return TRUE; } } @@ -221,6 +232,7 @@ ToSplitPageTable ( return FALSE; } + /** Initialize a buffer pool for page table use only. @@ -240,18 +252,18 @@ ToSplitPageTable ( **/ BOOLEAN InitializePageTablePool ( - IN UINTN PoolPages + IN UINTN PoolPages ) { - VOID *Buffer; + VOID *Buffer; // // Always reserve at least PAGE_TABLE_POOL_UNIT_PAGES, including one page for // header. // PoolPages += 1; // Add one page for header. - PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) * - PAGE_TABLE_POOL_UNIT_PAGES; + PoolPages = ((PoolPages - 1) / PAGE_TABLE_POOL_UNIT_PAGES + 1) * + PAGE_TABLE_POOL_UNIT_PAGES; Buffer = AllocateAlignedPages (PoolPages, PAGE_TABLE_POOL_ALIGNMENT); if (Buffer == NULL) { DEBUG ((DEBUG_ERROR, "ERROR: Out of aligned pages\r\n")); @@ -262,19 +274,19 @@ InitializePageTablePool ( // Link all pools into a list for easier track later. // if (mPageTablePool == NULL) { - mPageTablePool = Buffer; + mPageTablePool = Buffer; mPageTablePool->NextPool = mPageTablePool; } else { ((PAGE_TABLE_POOL *)Buffer)->NextPool = mPageTablePool->NextPool; - mPageTablePool->NextPool = Buffer; - mPageTablePool = Buffer; + mPageTablePool->NextPool = Buffer; + mPageTablePool = Buffer; } // // Reserve one page for pool header. // - mPageTablePool->FreePages = PoolPages - 1; - mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1); + mPageTablePool->FreePages = PoolPages - 1; + mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1); return TRUE; } @@ -298,10 +310,10 @@ InitializePageTablePool ( **/ VOID * AllocatePageTableMemory ( - IN UINTN Pages + IN UINTN Pages ) { - VOID *Buffer; + VOID *Buffer; if (Pages == 0) { return NULL; @@ -310,8 +322,9 @@ AllocatePageTableMemory ( // // Renew the pool if necessary. // - if (mPageTablePool == NULL || - Pages > mPageTablePool->FreePages) { + if ((mPageTablePool == NULL) || + (Pages > mPageTablePool->FreePages)) + { if (!InitializePageTablePool (Pages)) { return NULL; } @@ -319,8 +332,8 @@ AllocatePageTableMemory ( Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset; - mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages); - mPageTablePool->FreePages -= Pages; + mPageTablePool->Offset += EFI_PAGES_TO_SIZE (Pages); + mPageTablePool->FreePages -= Pages; return Buffer; } @@ -338,18 +351,18 @@ AllocatePageTableMemory ( **/ VOID Split2MPageTo4K ( - IN EFI_PHYSICAL_ADDRESS PhysicalAddress, - IN OUT UINT64 *PageEntry2M, - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbSize + IN EFI_PHYSICAL_ADDRESS PhysicalAddress, + IN OUT UINT64 *PageEntry2M, + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbSize ) { - EFI_PHYSICAL_ADDRESS PhysicalAddress4K; - UINTN IndexOfPageTableEntries; - PAGE_TABLE_4K_ENTRY *PageTableEntry; - UINT64 AddressEncMask; + EFI_PHYSICAL_ADDRESS PhysicalAddress4K; + UINTN IndexOfPageTableEntries; + PAGE_TABLE_4K_ENTRY *PageTableEntry; + UINT64 AddressEncMask; // // Make sure AddressEncMask is contained to smallest supported address field @@ -362,14 +375,14 @@ Split2MPageTo4K ( // // Fill in 2M page entry. // - *PageEntry2M = (UINT64) (UINTN) PageTableEntry | AddressEncMask | IA32_PG_P | IA32_PG_RW; + *PageEntry2M = (UINT64)(UINTN)PageTableEntry | AddressEncMask | IA32_PG_P | IA32_PG_RW; PhysicalAddress4K = PhysicalAddress; for (IndexOfPageTableEntries = 0; IndexOfPageTableEntries < 512; IndexOfPageTableEntries++, PageTableEntry++, PhysicalAddress4K += SIZE_4KB) { // // Fill in the Page Table entries // - PageTableEntry->Uint64 = (UINT64) PhysicalAddress4K; + PageTableEntry->Uint64 = (UINT64)PhysicalAddress4K; // // The GHCB range consists of two pages per CPU, the GHCB and a @@ -377,24 +390,28 @@ Split2MPageTo4K ( // unencrypted page while the per-CPU variable page needs to be // mapped encrypted. These pages alternate in assignment. // - if ((GhcbBase == 0) - || (PhysicalAddress4K < GhcbBase) - || (PhysicalAddress4K >= GhcbBase + GhcbSize) - || (((PhysicalAddress4K - GhcbBase) & SIZE_4KB) != 0)) { + if ( (GhcbBase == 0) + || (PhysicalAddress4K < GhcbBase) + || (PhysicalAddress4K >= GhcbBase + GhcbSize) + || (((PhysicalAddress4K - GhcbBase) & SIZE_4KB) != 0)) + { PageTableEntry->Uint64 |= AddressEncMask; } + PageTableEntry->Bits.ReadWrite = 1; - if ((IsNullDetectionEnabled () && PhysicalAddress4K == 0) || - (PcdGetBool (PcdCpuStackGuard) && PhysicalAddress4K == StackBase)) { + if ((IsNullDetectionEnabled () && (PhysicalAddress4K == 0)) || + (PcdGetBool (PcdCpuStackGuard) && (PhysicalAddress4K == StackBase))) + { PageTableEntry->Bits.Present = 0; } else { PageTableEntry->Bits.Present = 1; } - if (PcdGetBool (PcdSetNxForStack) - && (PhysicalAddress4K >= StackBase) - && (PhysicalAddress4K < StackBase + StackSize)) { + if ( PcdGetBool (PcdSetNxForStack) + && (PhysicalAddress4K >= StackBase) + && (PhysicalAddress4K < StackBase + StackSize)) + { // // Set Nx bit for stack. // @@ -416,18 +433,18 @@ Split2MPageTo4K ( **/ VOID Split1GPageTo2M ( - IN EFI_PHYSICAL_ADDRESS PhysicalAddress, - IN OUT UINT64 *PageEntry1G, - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbSize + IN EFI_PHYSICAL_ADDRESS PhysicalAddress, + IN OUT UINT64 *PageEntry1G, + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbSize ) { - EFI_PHYSICAL_ADDRESS PhysicalAddress2M; - UINTN IndexOfPageDirectoryEntries; - PAGE_TABLE_ENTRY *PageDirectoryEntry; - UINT64 AddressEncMask; + EFI_PHYSICAL_ADDRESS PhysicalAddress2M; + UINTN IndexOfPageDirectoryEntries; + PAGE_TABLE_ENTRY *PageDirectoryEntry; + UINT64 AddressEncMask; // // Make sure AddressEncMask is contained to smallest supported address field @@ -440,7 +457,7 @@ Split1GPageTo2M ( // // Fill in 1G page entry. // - *PageEntry1G = (UINT64) (UINTN) PageDirectoryEntry | AddressEncMask | IA32_PG_P | IA32_PG_RW; + *PageEntry1G = (UINT64)(UINTN)PageDirectoryEntry | AddressEncMask | IA32_PG_P | IA32_PG_RW; PhysicalAddress2M = PhysicalAddress; for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PhysicalAddress2M += SIZE_2MB) { @@ -448,15 +465,15 @@ Split1GPageTo2M ( // // Need to split this 2M page that covers NULL or stack range. // - Split2MPageTo4K (PhysicalAddress2M, (UINT64 *) PageDirectoryEntry, StackBase, StackSize, GhcbBase, GhcbSize); + Split2MPageTo4K (PhysicalAddress2M, (UINT64 *)PageDirectoryEntry, StackBase, StackSize, GhcbBase, GhcbSize); } else { // // Fill in the Page Directory entries // - PageDirectoryEntry->Uint64 = (UINT64) PhysicalAddress2M | AddressEncMask; + PageDirectoryEntry->Uint64 = (UINT64)PhysicalAddress2M | AddressEncMask; PageDirectoryEntry->Bits.ReadWrite = 1; - PageDirectoryEntry->Bits.Present = 1; - PageDirectoryEntry->Bits.MustBe1 = 1; + PageDirectoryEntry->Bits.Present = 1; + PageDirectoryEntry->Bits.MustBe1 = 1; } } } @@ -471,9 +488,9 @@ Split1GPageTo2M ( **/ VOID SetPageTablePoolReadOnly ( - IN UINTN PageTableBase, - IN EFI_PHYSICAL_ADDRESS Address, - IN BOOLEAN Level4Paging + IN UINTN PageTableBase, + IN EFI_PHYSICAL_ADDRESS Address, + IN BOOLEAN Level4Paging ) { UINTN Index; @@ -513,13 +530,13 @@ SetPageTablePoolReadOnly ( LevelSize[3] = SIZE_1GB; LevelSize[4] = SIZE_512GB; - AddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & - PAGING_1G_ADDRESS_MASK_64; - PageTable = (UINT64 *)(UINTN)PageTableBase; - PoolUnitSize = PAGE_TABLE_POOL_UNIT_SIZE; + AddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & + PAGING_1G_ADDRESS_MASK_64; + PageTable = (UINT64 *)(UINTN)PageTableBase; + PoolUnitSize = PAGE_TABLE_POOL_UNIT_SIZE; for (Level = (Level4Paging) ? 4 : 3; Level > 0; --Level) { - Index = ((UINTN)RShiftU64 (Address, LevelShift[Level])); + Index = ((UINTN)RShiftU64 (Address, LevelShift[Level])); Index &= PAGING_PAE_INDEX_MASK; PageAttr = PageTable[Index]; @@ -547,14 +564,13 @@ SetPageTablePoolReadOnly ( ASSERT (Index < EFI_PAGE_SIZE/sizeof (UINT64)); PageTable[Index] &= ~(UINT64)IA32_PG_RW; - PoolUnitSize -= LevelSize[Level]; + PoolUnitSize -= LevelSize[Level]; ++Index; } } break; - } else { // // The smaller granularity of page must be needed. @@ -566,18 +582,20 @@ SetPageTablePoolReadOnly ( PhysicalAddress = PageAttr & LevelMask[Level]; for (EntryIndex = 0; - EntryIndex < EFI_PAGE_SIZE/sizeof (UINT64); - ++EntryIndex) { + EntryIndex < EFI_PAGE_SIZE/sizeof (UINT64); + ++EntryIndex) + { NewPageTable[EntryIndex] = PhysicalAddress | AddressEncMask | IA32_PG_P | IA32_PG_RW; if (Level > 2) { NewPageTable[EntryIndex] |= IA32_PG_PS; } + PhysicalAddress += LevelSize[Level - 1]; } PageTable[Index] = (UINT64)(UINTN)NewPageTable | AddressEncMask | - IA32_PG_P | IA32_PG_RW; + IA32_PG_P | IA32_PG_RW; PageTable = NewPageTable; } } @@ -592,14 +610,14 @@ SetPageTablePoolReadOnly ( **/ VOID EnablePageTableProtection ( - IN UINTN PageTableBase, - IN BOOLEAN Level4Paging + IN UINTN PageTableBase, + IN BOOLEAN Level4Paging ) { - PAGE_TABLE_POOL *HeadPool; - PAGE_TABLE_POOL *Pool; - UINT64 PoolSize; - EFI_PHYSICAL_ADDRESS Address; + PAGE_TABLE_POOL *HeadPool; + PAGE_TABLE_POOL *Pool; + UINT64 PoolSize; + EFI_PHYSICAL_ADDRESS Address; if (mPageTablePool == NULL) { return; @@ -609,14 +627,14 @@ EnablePageTableProtection ( // Disable write protection, because we need to mark page table to be write // protected. // - AsmWriteCr0 (AsmReadCr0() & ~CR0_WP); + AsmWriteCr0 (AsmReadCr0 () & ~CR0_WP); // // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to // remember original one in advance. // HeadPool = mPageTablePool; - Pool = HeadPool; + Pool = HeadPool; do { Address = (EFI_PHYSICAL_ADDRESS)(UINTN)Pool; PoolSize = Pool->Offset + EFI_PAGES_TO_SIZE (Pool->FreePages); @@ -627,9 +645,9 @@ EnablePageTableProtection ( // protection to them one by one. // while (PoolSize > 0) { - SetPageTablePoolReadOnly(PageTableBase, Address, Level4Paging); - Address += PAGE_TABLE_POOL_UNIT_SIZE; - PoolSize -= PAGE_TABLE_POOL_UNIT_SIZE; + SetPageTablePoolReadOnly (PageTableBase, Address, Level4Paging); + Address += PAGE_TABLE_POOL_UNIT_SIZE; + PoolSize -= PAGE_TABLE_POOL_UNIT_SIZE; } Pool = Pool->NextPool; @@ -638,7 +656,7 @@ EnablePageTableProtection ( // // Enable write protection, after page table attribute updated. // - AsmWriteCr0 (AsmReadCr0() | CR0_WP); + AsmWriteCr0 (AsmReadCr0 () | CR0_WP); } /** @@ -655,37 +673,37 @@ EnablePageTableProtection ( **/ UINTN CreateIdentityMappingPageTables ( - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbSize + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbSize ) { - UINT32 RegEax; - CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX EcxFlags; - UINT32 RegEdx; - UINT8 PhysicalAddressBits; - EFI_PHYSICAL_ADDRESS PageAddress; - UINTN IndexOfPml5Entries; - UINTN IndexOfPml4Entries; - UINTN IndexOfPdpEntries; - UINTN IndexOfPageDirectoryEntries; - UINT32 NumberOfPml5EntriesNeeded; - UINT32 NumberOfPml4EntriesNeeded; - UINT32 NumberOfPdpEntriesNeeded; - PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel5Entry; - PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel4Entry; - PAGE_MAP_AND_DIRECTORY_POINTER *PageMap; - PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry; - PAGE_TABLE_ENTRY *PageDirectoryEntry; - UINTN TotalPagesNum; - UINTN BigPageAddress; - VOID *Hob; - BOOLEAN Page5LevelSupport; - BOOLEAN Page1GSupport; - PAGE_TABLE_1G_ENTRY *PageDirectory1GEntry; - UINT64 AddressEncMask; - IA32_CR4 Cr4; + UINT32 RegEax; + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_ECX EcxFlags; + UINT32 RegEdx; + UINT8 PhysicalAddressBits; + EFI_PHYSICAL_ADDRESS PageAddress; + UINTN IndexOfPml5Entries; + UINTN IndexOfPml4Entries; + UINTN IndexOfPdpEntries; + UINTN IndexOfPageDirectoryEntries; + UINT32 NumberOfPml5EntriesNeeded; + UINT32 NumberOfPml4EntriesNeeded; + UINT32 NumberOfPdpEntriesNeeded; + PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel5Entry; + PAGE_MAP_AND_DIRECTORY_POINTER *PageMapLevel4Entry; + PAGE_MAP_AND_DIRECTORY_POINTER *PageMap; + PAGE_MAP_AND_DIRECTORY_POINTER *PageDirectoryPointerEntry; + PAGE_TABLE_ENTRY *PageDirectoryEntry; + UINTN TotalPagesNum; + UINTN BigPageAddress; + VOID *Hob; + BOOLEAN Page5LevelSupport; + BOOLEAN Page1GSupport; + PAGE_TABLE_1G_ENTRY *PageDirectory1GEntry; + UINT64 AddressEncMask; + IA32_CR4 Cr4; // // Set PageMapLevel5Entry to suppress incorrect compiler/analyzer warnings @@ -698,7 +716,7 @@ CreateIdentityMappingPageTables ( AddressEncMask = PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGING_1G_ADDRESS_MASK_64; Page1GSupport = FALSE; - if (PcdGetBool(PcdUse1GPageTable)) { + if (PcdGetBool (PcdUse1GPageTable)) { AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); if (RegEax >= 0x80000001) { AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx); @@ -713,12 +731,12 @@ CreateIdentityMappingPageTables ( // Hob = GetFirstHob (EFI_HOB_TYPE_CPU); if (Hob != NULL) { - PhysicalAddressBits = ((EFI_HOB_CPU *) Hob)->SizeOfMemorySpace; + PhysicalAddressBits = ((EFI_HOB_CPU *)Hob)->SizeOfMemorySpace; } else { AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); if (RegEax >= 0x80000008) { AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL); - PhysicalAddressBits = (UINT8) RegEax; + PhysicalAddressBits = (UINT8)RegEax; } else { PhysicalAddressBits = 36; } @@ -727,8 +745,12 @@ CreateIdentityMappingPageTables ( Page5LevelSupport = FALSE; if (PcdGetBool (PcdUse5LevelPageTable)) { AsmCpuidEx ( - CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_SUB_LEAF_INFO, NULL, - &EcxFlags.Uint32, NULL, NULL + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS, + CPUID_STRUCTURED_EXTENDED_FEATURE_FLAGS_SUB_LEAF_INFO, + NULL, + &EcxFlags.Uint32, + NULL, + NULL ); if (EcxFlags.Bits.FiveLevelPage != 0) { Page5LevelSupport = TRUE; @@ -743,7 +765,7 @@ CreateIdentityMappingPageTables ( // due to either unsupported by HW, or disabled by PCD. // ASSERT (PhysicalAddressBits <= 52); - if (!Page5LevelSupport && PhysicalAddressBits > 48) { + if (!Page5LevelSupport && (PhysicalAddressBits > 48)) { PhysicalAddressBits = 48; } @@ -752,19 +774,19 @@ CreateIdentityMappingPageTables ( // NumberOfPml5EntriesNeeded = 1; if (PhysicalAddressBits > 48) { - NumberOfPml5EntriesNeeded = (UINT32) LShiftU64 (1, PhysicalAddressBits - 48); - PhysicalAddressBits = 48; + NumberOfPml5EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 48); + PhysicalAddressBits = 48; } NumberOfPml4EntriesNeeded = 1; if (PhysicalAddressBits > 39) { - NumberOfPml4EntriesNeeded = (UINT32) LShiftU64 (1, PhysicalAddressBits - 39); - PhysicalAddressBits = 39; + NumberOfPml4EntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 39); + PhysicalAddressBits = 39; } NumberOfPdpEntriesNeeded = 1; ASSERT (PhysicalAddressBits > 30); - NumberOfPdpEntriesNeeded = (UINT32) LShiftU64 (1, PhysicalAddressBits - 30); + NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, PhysicalAddressBits - 30); // // Pre-allocate big pages to avoid later allocations. @@ -782,17 +804,22 @@ CreateIdentityMappingPageTables ( TotalPagesNum--; } - DEBUG ((DEBUG_INFO, "Pml5=%u Pml4=%u Pdp=%u TotalPage=%Lu\n", - NumberOfPml5EntriesNeeded, NumberOfPml4EntriesNeeded, - NumberOfPdpEntriesNeeded, (UINT64)TotalPagesNum)); + DEBUG (( + DEBUG_INFO, + "Pml5=%u Pml4=%u Pdp=%u TotalPage=%Lu\n", + NumberOfPml5EntriesNeeded, + NumberOfPml4EntriesNeeded, + NumberOfPdpEntriesNeeded, + (UINT64)TotalPagesNum + )); - BigPageAddress = (UINTN) AllocatePageTableMemory (TotalPagesNum); + BigPageAddress = (UINTN)AllocatePageTableMemory (TotalPagesNum); ASSERT (BigPageAddress != 0); // // By architecture only one PageMapLevel4 exists - so lets allocate storage for it. // - PageMap = (VOID *) BigPageAddress; + PageMap = (VOID *)BigPageAddress; if (Page5LevelSupport) { // // By architecture only one PageMapLevel5 exists - so lets allocate storage for it. @@ -800,94 +827,98 @@ CreateIdentityMappingPageTables ( PageMapLevel5Entry = PageMap; BigPageAddress += SIZE_4KB; } - PageAddress = 0; + + PageAddress = 0; for ( IndexOfPml5Entries = 0 - ; IndexOfPml5Entries < NumberOfPml5EntriesNeeded - ; IndexOfPml5Entries++) { + ; IndexOfPml5Entries < NumberOfPml5EntriesNeeded + ; IndexOfPml5Entries++) + { // // Each PML5 entry points to a page of PML4 entires. // So lets allocate space for them and fill them in in the IndexOfPml4Entries loop. // When 5-Level Paging is disabled, below allocation happens only once. // - PageMapLevel4Entry = (VOID *) BigPageAddress; + PageMapLevel4Entry = (VOID *)BigPageAddress; BigPageAddress += SIZE_4KB; if (Page5LevelSupport) { // // Make a PML5 Entry // - PageMapLevel5Entry->Uint64 = (UINT64) (UINTN) PageMapLevel4Entry | AddressEncMask; + PageMapLevel5Entry->Uint64 = (UINT64)(UINTN)PageMapLevel4Entry | AddressEncMask; PageMapLevel5Entry->Bits.ReadWrite = 1; PageMapLevel5Entry->Bits.Present = 1; PageMapLevel5Entry++; } for ( IndexOfPml4Entries = 0 - ; IndexOfPml4Entries < (NumberOfPml5EntriesNeeded == 1 ? NumberOfPml4EntriesNeeded : 512) - ; IndexOfPml4Entries++, PageMapLevel4Entry++) { + ; IndexOfPml4Entries < (NumberOfPml5EntriesNeeded == 1 ? NumberOfPml4EntriesNeeded : 512) + ; IndexOfPml4Entries++, PageMapLevel4Entry++) + { // // Each PML4 entry points to a page of Page Directory Pointer entires. // So lets allocate space for them and fill them in in the IndexOfPdpEntries loop. // - PageDirectoryPointerEntry = (VOID *) BigPageAddress; - BigPageAddress += SIZE_4KB; + PageDirectoryPointerEntry = (VOID *)BigPageAddress; + BigPageAddress += SIZE_4KB; // // Make a PML4 Entry // - PageMapLevel4Entry->Uint64 = (UINT64)(UINTN)PageDirectoryPointerEntry | AddressEncMask; + PageMapLevel4Entry->Uint64 = (UINT64)(UINTN)PageDirectoryPointerEntry | AddressEncMask; PageMapLevel4Entry->Bits.ReadWrite = 1; - PageMapLevel4Entry->Bits.Present = 1; + PageMapLevel4Entry->Bits.Present = 1; if (Page1GSupport) { - PageDirectory1GEntry = (VOID *) PageDirectoryPointerEntry; + PageDirectory1GEntry = (VOID *)PageDirectoryPointerEntry; for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) { if (ToSplitPageTable (PageAddress, SIZE_1GB, StackBase, StackSize, GhcbBase, GhcbSize)) { - Split1GPageTo2M (PageAddress, (UINT64 *) PageDirectory1GEntry, StackBase, StackSize, GhcbBase, GhcbSize); + Split1GPageTo2M (PageAddress, (UINT64 *)PageDirectory1GEntry, StackBase, StackSize, GhcbBase, GhcbSize); } else { // // Fill in the Page Directory entries // - PageDirectory1GEntry->Uint64 = (UINT64)PageAddress | AddressEncMask; + PageDirectory1GEntry->Uint64 = (UINT64)PageAddress | AddressEncMask; PageDirectory1GEntry->Bits.ReadWrite = 1; - PageDirectory1GEntry->Bits.Present = 1; - PageDirectory1GEntry->Bits.MustBe1 = 1; + PageDirectory1GEntry->Bits.Present = 1; + PageDirectory1GEntry->Bits.MustBe1 = 1; } } } else { for ( IndexOfPdpEntries = 0 - ; IndexOfPdpEntries < (NumberOfPml4EntriesNeeded == 1 ? NumberOfPdpEntriesNeeded : 512) - ; IndexOfPdpEntries++, PageDirectoryPointerEntry++) { + ; IndexOfPdpEntries < (NumberOfPml4EntriesNeeded == 1 ? NumberOfPdpEntriesNeeded : 512) + ; IndexOfPdpEntries++, PageDirectoryPointerEntry++) + { // // Each Directory Pointer entries points to a page of Page Directory entires. // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop. // - PageDirectoryEntry = (VOID *) BigPageAddress; - BigPageAddress += SIZE_4KB; + PageDirectoryEntry = (VOID *)BigPageAddress; + BigPageAddress += SIZE_4KB; // // Fill in a Page Directory Pointer Entries // - PageDirectoryPointerEntry->Uint64 = (UINT64)(UINTN)PageDirectoryEntry | AddressEncMask; + PageDirectoryPointerEntry->Uint64 = (UINT64)(UINTN)PageDirectoryEntry | AddressEncMask; PageDirectoryPointerEntry->Bits.ReadWrite = 1; - PageDirectoryPointerEntry->Bits.Present = 1; + PageDirectoryPointerEntry->Bits.Present = 1; for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) { if (ToSplitPageTable (PageAddress, SIZE_2MB, StackBase, StackSize, GhcbBase, GhcbSize)) { // // Need to split this 2M page that covers NULL or stack range. // - Split2MPageTo4K (PageAddress, (UINT64 *) PageDirectoryEntry, StackBase, StackSize, GhcbBase, GhcbSize); + Split2MPageTo4K (PageAddress, (UINT64 *)PageDirectoryEntry, StackBase, StackSize, GhcbBase, GhcbSize); } else { // // Fill in the Page Directory entries // - PageDirectoryEntry->Uint64 = (UINT64)PageAddress | AddressEncMask; + PageDirectoryEntry->Uint64 = (UINT64)PageAddress | AddressEncMask; PageDirectoryEntry->Bits.ReadWrite = 1; - PageDirectoryEntry->Bits.Present = 1; - PageDirectoryEntry->Bits.MustBe1 = 1; + PageDirectoryEntry->Bits.Present = 1; + PageDirectoryEntry->Bits.MustBe1 = 1; } } } @@ -895,7 +926,7 @@ CreateIdentityMappingPageTables ( // // Fill with null entry for unused PDPTE // - ZeroMem (PageDirectoryPointerEntry, (512 - IndexOfPdpEntries) * sizeof(PAGE_MAP_AND_DIRECTORY_POINTER)); + ZeroMem (PageDirectoryPointerEntry, (512 - IndexOfPdpEntries) * sizeof (PAGE_MAP_AND_DIRECTORY_POINTER)); } } @@ -906,7 +937,7 @@ CreateIdentityMappingPageTables ( } if (Page5LevelSupport) { - Cr4.UintN = AsmReadCr4 (); + Cr4.UintN = AsmReadCr4 (); Cr4.Bits.LA57 = 1; AsmWriteCr4 (Cr4.UintN); // @@ -930,4 +961,3 @@ CreateIdentityMappingPageTables ( return (UINTN)PageMap; } - diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h index 6b7c38a441..616ebe42b0 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h +++ b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h @@ -13,38 +13,37 @@ Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef _VIRTUAL_MEMORY_H_ #define _VIRTUAL_MEMORY_H_ - -#define SYS_CODE64_SEL 0x38 - +#define SYS_CODE64_SEL 0x38 #pragma pack(1) typedef union { struct { - UINT32 LimitLow : 16; - UINT32 BaseLow : 16; - UINT32 BaseMid : 8; - UINT32 Type : 4; - UINT32 System : 1; - UINT32 Dpl : 2; - UINT32 Present : 1; - UINT32 LimitHigh : 4; - UINT32 Software : 1; - UINT32 Reserved : 1; - UINT32 DefaultSize : 1; - UINT32 Granularity : 1; - UINT32 BaseHigh : 8; + UINT32 LimitLow : 16; + UINT32 BaseLow : 16; + UINT32 BaseMid : 8; + UINT32 Type : 4; + UINT32 System : 1; + UINT32 Dpl : 2; + UINT32 Present : 1; + UINT32 LimitHigh : 4; + UINT32 Software : 1; + UINT32 Reserved : 1; + UINT32 DefaultSize : 1; + UINT32 Granularity : 1; + UINT32 BaseHigh : 8; } Bits; - UINT64 Uint64; + UINT64 Uint64; } IA32_GDT; typedef struct { - IA32_IDT_GATE_DESCRIPTOR Ia32IdtEntry; - UINT32 Offset32To63; - UINT32 Reserved; + IA32_IDT_GATE_DESCRIPTOR Ia32IdtEntry; + UINT32 Offset32To63; + UINT32 Reserved; } X64_IDT_GATE_DESCRIPTOR; // @@ -54,18 +53,18 @@ typedef struct { typedef union { struct { - UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User - UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Reserved:1; // Reserved - UINT64 MustBeZero:2; // Must Be Zero - UINT64 Available:3; // Available for use by system software - UINT64 PageTableBaseAddress:40; // Page Table Base Address - UINT64 AvabilableHigh:11; // Available for use by system software - UINT64 Nx:1; // No Execute bit + UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT64 Reserved : 1; // Reserved + UINT64 MustBeZero : 2; // Must Be Zero + UINT64 Available : 3; // Available for use by system software + UINT64 PageTableBaseAddress : 40; // Page Table Base Address + UINT64 AvabilableHigh : 11; // Available for use by system software + UINT64 Nx : 1; // No Execute bit } Bits; UINT64 Uint64; } PAGE_MAP_AND_DIRECTORY_POINTER; @@ -75,19 +74,19 @@ typedef union { // typedef union { struct { - UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User - UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page - UINT64 PAT:1; // - UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write - UINT64 Available:3; // Available for use by system software - UINT64 PageTableBaseAddress:40; // Page Table Base Address - UINT64 AvabilableHigh:11; // Available for use by system software - UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution + UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT64 Dirty : 1; // 0 = Not Dirty, 1 = written by processor on access to page + UINT64 PAT : 1; // + UINT64 Global : 1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write + UINT64 Available : 3; // Available for use by system software + UINT64 PageTableBaseAddress : 40; // Page Table Base Address + UINT64 AvabilableHigh : 11; // Available for use by system software + UINT64 Nx : 1; // 0 = Execute Code, 1 = No Code Execution } Bits; UINT64 Uint64; } PAGE_TABLE_4K_ENTRY; @@ -97,21 +96,21 @@ typedef union { // typedef union { struct { - UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User - UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page - UINT64 MustBe1:1; // Must be 1 - UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write - UINT64 Available:3; // Available for use by system software - UINT64 PAT:1; // - UINT64 MustBeZero:8; // Must be zero; - UINT64 PageTableBaseAddress:31; // Page Table Base Address - UINT64 AvabilableHigh:11; // Available for use by system software - UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution + UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT64 Dirty : 1; // 0 = Not Dirty, 1 = written by processor on access to page + UINT64 MustBe1 : 1; // Must be 1 + UINT64 Global : 1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write + UINT64 Available : 3; // Available for use by system software + UINT64 PAT : 1; // + UINT64 MustBeZero : 8; // Must be zero; + UINT64 PageTableBaseAddress : 31; // Page Table Base Address + UINT64 AvabilableHigh : 11; // Available for use by system software + UINT64 Nx : 1; // 0 = Execute Code, 1 = No Code Execution } Bits; UINT64 Uint64; } PAGE_TABLE_ENTRY; @@ -121,45 +120,45 @@ typedef union { // typedef union { struct { - UINT64 Present:1; // 0 = Not present in memory, 1 = Present in memory - UINT64 ReadWrite:1; // 0 = Read-Only, 1= Read/Write - UINT64 UserSupervisor:1; // 0 = Supervisor, 1=User - UINT64 WriteThrough:1; // 0 = Write-Back caching, 1=Write-Through caching - UINT64 CacheDisabled:1; // 0 = Cached, 1=Non-Cached - UINT64 Accessed:1; // 0 = Not accessed, 1 = Accessed (set by CPU) - UINT64 Dirty:1; // 0 = Not Dirty, 1 = written by processor on access to page - UINT64 MustBe1:1; // Must be 1 - UINT64 Global:1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write - UINT64 Available:3; // Available for use by system software - UINT64 PAT:1; // - UINT64 MustBeZero:17; // Must be zero; - UINT64 PageTableBaseAddress:22; // Page Table Base Address - UINT64 AvabilableHigh:11; // Available for use by system software - UINT64 Nx:1; // 0 = Execute Code, 1 = No Code Execution + UINT64 Present : 1; // 0 = Not present in memory, 1 = Present in memory + UINT64 ReadWrite : 1; // 0 = Read-Only, 1= Read/Write + UINT64 UserSupervisor : 1; // 0 = Supervisor, 1=User + UINT64 WriteThrough : 1; // 0 = Write-Back caching, 1=Write-Through caching + UINT64 CacheDisabled : 1; // 0 = Cached, 1=Non-Cached + UINT64 Accessed : 1; // 0 = Not accessed, 1 = Accessed (set by CPU) + UINT64 Dirty : 1; // 0 = Not Dirty, 1 = written by processor on access to page + UINT64 MustBe1 : 1; // Must be 1 + UINT64 Global : 1; // 0 = Not global page, 1 = global page TLB not cleared on CR3 write + UINT64 Available : 3; // Available for use by system software + UINT64 PAT : 1; // + UINT64 MustBeZero : 17; // Must be zero; + UINT64 PageTableBaseAddress : 22; // Page Table Base Address + UINT64 AvabilableHigh : 11; // Available for use by system software + UINT64 Nx : 1; // 0 = Execute Code, 1 = No Code Execution } Bits; UINT64 Uint64; } PAGE_TABLE_1G_ENTRY; #pragma pack() -#define CR0_WP BIT16 +#define CR0_WP BIT16 -#define IA32_PG_P BIT0 -#define IA32_PG_RW BIT1 -#define IA32_PG_PS BIT7 +#define IA32_PG_P BIT0 +#define IA32_PG_RW BIT1 +#define IA32_PG_PS BIT7 -#define PAGING_PAE_INDEX_MASK 0x1FF +#define PAGING_PAE_INDEX_MASK 0x1FF -#define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull -#define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull -#define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull +#define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull +#define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull +#define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull -#define PAGING_L1_ADDRESS_SHIFT 12 -#define PAGING_L2_ADDRESS_SHIFT 21 -#define PAGING_L3_ADDRESS_SHIFT 30 -#define PAGING_L4_ADDRESS_SHIFT 39 +#define PAGING_L1_ADDRESS_SHIFT 12 +#define PAGING_L2_ADDRESS_SHIFT 21 +#define PAGING_L3_ADDRESS_SHIFT 30 +#define PAGING_L4_ADDRESS_SHIFT 39 -#define PAGING_PML4E_NUMBER 4 +#define PAGING_PML4E_NUMBER 4 #define PAGE_TABLE_POOL_ALIGNMENT BASE_2MB #define PAGE_TABLE_POOL_UNIT_SIZE SIZE_2MB @@ -168,9 +167,9 @@ typedef union { (~(EFI_PHYSICAL_ADDRESS)(PAGE_TABLE_POOL_ALIGNMENT - 1)) typedef struct { - VOID *NextPool; - UINTN Offset; - UINTN FreePages; + VOID *NextPool; + UINTN Offset; + UINTN FreePages; } PAGE_TABLE_POOL; /** @@ -207,12 +206,12 @@ EnableExecuteDisableBit ( **/ VOID Split2MPageTo4K ( - IN EFI_PHYSICAL_ADDRESS PhysicalAddress, - IN OUT UINT64 *PageEntry2M, - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbSize + IN EFI_PHYSICAL_ADDRESS PhysicalAddress, + IN OUT UINT64 *PageEntry2M, + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbSize ); /** @@ -229,13 +228,12 @@ Split2MPageTo4K ( **/ UINTN CreateIdentityMappingPageTables ( - IN EFI_PHYSICAL_ADDRESS StackBase, - IN UINTN StackSize, - IN EFI_PHYSICAL_ADDRESS GhcbBase, - IN UINTN GhcbkSize + IN EFI_PHYSICAL_ADDRESS StackBase, + IN UINTN StackSize, + IN EFI_PHYSICAL_ADDRESS GhcbBase, + IN UINTN GhcbkSize ); - /** Fix up the vector number in the vector code. @@ -247,11 +245,10 @@ CreateIdentityMappingPageTables ( VOID EFIAPI AsmVectorFixup ( - VOID *VectorBase, - UINT8 VectorNum + VOID *VectorBase, + UINT8 VectorNum ); - /** Get the information of vector template. @@ -278,7 +275,7 @@ AsmGetVectorTemplatInfo ( **/ VOID ClearFirst4KPage ( - IN VOID *HobStart + IN VOID *HobStart ); /** @@ -301,8 +298,8 @@ IsNullDetectionEnabled ( **/ VOID EnablePageTableProtection ( - IN UINTN PageTableBase, - IN BOOLEAN Level4Paging + IN UINTN PageTableBase, + IN BOOLEAN Level4Paging ); /** @@ -324,7 +321,7 @@ EnablePageTableProtection ( **/ VOID * AllocatePageTableMemory ( - IN UINTN Pages + IN UINTN Pages ); #endif diff --git a/MdeModulePkg/Core/Pei/BootMode/BootMode.c b/MdeModulePkg/Core/Pei/BootMode/BootMode.c index 37a49c4a4c..100942ecd0 100644 --- a/MdeModulePkg/Core/Pei/BootMode/BootMode.c +++ b/MdeModulePkg/Core/Pei/BootMode/BootMode.c @@ -29,25 +29,22 @@ PeiGetBootMode ( IN OUT EFI_BOOT_MODE *BootMode ) { - PEI_CORE_INSTANCE *PrivateData; - EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; - + PEI_CORE_INSTANCE *PrivateData; + EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; if (BootMode == NULL) { return EFI_INVALID_PARAMETER; } - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); - - HandOffHob = (PrivateData->HobList.HandoffInformationTable); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); - *BootMode = HandOffHob->BootMode; + HandOffHob = (PrivateData->HobList.HandoffInformationTable); + *BootMode = HandOffHob->BootMode; return EFI_SUCCESS; } - /** This service enables PEIMs to update the boot mode variable. @@ -65,16 +62,14 @@ PeiSetBootMode ( IN EFI_BOOT_MODE BootMode ) { - PEI_CORE_INSTANCE *PrivateData; - EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; + PEI_CORE_INSTANCE *PrivateData; + EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); - - HandOffHob = (PrivateData->HobList.HandoffInformationTable); + HandOffHob = (PrivateData->HobList.HandoffInformationTable); HandOffHob->BootMode = BootMode; - return EFI_SUCCESS; } diff --git a/MdeModulePkg/Core/Pei/CpuIo/CpuIo.c b/MdeModulePkg/Core/Pei/CpuIo/CpuIo.c index 3c62d7b607..8b48a0122c 100644 --- a/MdeModulePkg/Core/Pei/CpuIo/CpuIo.c +++ b/MdeModulePkg/Core/Pei/CpuIo/CpuIo.c @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// This default instance of EFI_PEI_CPU_IO_PPI install assigned to EFI_PEI_SERVICE.CpuIo /// when PeiCore's initialization. /// -EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi = { +EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi = { { PeiDefaultMemRead, PeiDefaultMemWrite @@ -66,12 +66,12 @@ EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi = { EFI_STATUS EFIAPI PeiDefaultMemRead ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -99,12 +99,12 @@ PeiDefaultMemRead ( EFI_STATUS EFIAPI PeiDefaultMemWrite ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -131,12 +131,12 @@ PeiDefaultMemWrite ( EFI_STATUS EFIAPI PeiDefaultIoRead ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -163,12 +163,12 @@ PeiDefaultIoRead ( EFI_STATUS EFIAPI PeiDefaultIoWrite ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -189,9 +189,9 @@ PeiDefaultIoWrite ( UINT8 EFIAPI PeiDefaultIoRead8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -212,9 +212,9 @@ PeiDefaultIoRead8 ( UINT16 EFIAPI PeiDefaultIoRead16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -235,9 +235,9 @@ PeiDefaultIoRead16 ( UINT32 EFIAPI PeiDefaultIoRead32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -258,9 +258,9 @@ PeiDefaultIoRead32 ( UINT64 EFIAPI PeiDefaultIoRead64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -279,10 +279,10 @@ PeiDefaultIoRead64 ( VOID EFIAPI PeiDefaultIoWrite8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT8 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT8 Data ) { } @@ -300,10 +300,10 @@ PeiDefaultIoWrite8 ( VOID EFIAPI PeiDefaultIoWrite16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT16 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT16 Data ) { } @@ -321,10 +321,10 @@ PeiDefaultIoWrite16 ( VOID EFIAPI PeiDefaultIoWrite32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT32 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT32 Data ) { } @@ -342,10 +342,10 @@ PeiDefaultIoWrite32 ( VOID EFIAPI PeiDefaultIoWrite64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT64 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT64 Data ) { } @@ -366,9 +366,9 @@ PeiDefaultIoWrite64 ( UINT8 EFIAPI PeiDefaultMemRead8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -390,9 +390,9 @@ PeiDefaultMemRead8 ( UINT16 EFIAPI PeiDefaultMemRead16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -414,9 +414,9 @@ PeiDefaultMemRead16 ( UINT32 EFIAPI PeiDefaultMemRead32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -438,9 +438,9 @@ PeiDefaultMemRead32 ( UINT64 EFIAPI PeiDefaultMemRead64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ) { return 0; @@ -460,10 +460,10 @@ PeiDefaultMemRead64 ( VOID EFIAPI PeiDefaultMemWrite8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT8 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT8 Data ) { } @@ -482,10 +482,10 @@ PeiDefaultMemWrite8 ( VOID EFIAPI PeiDefaultMemWrite16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT16 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT16 Data ) { } @@ -504,10 +504,10 @@ PeiDefaultMemWrite16 ( VOID EFIAPI PeiDefaultMemWrite32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT32 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT32 Data ) { } @@ -526,10 +526,10 @@ PeiDefaultMemWrite32 ( VOID EFIAPI PeiDefaultMemWrite64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT64 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT64 Data ) { } diff --git a/MdeModulePkg/Core/Pei/Dependency/Dependency.c b/MdeModulePkg/Core/Pei/Dependency/Dependency.c index b53e5f2686..9982167635 100644 --- a/MdeModulePkg/Core/Pei/Dependency/Dependency.c +++ b/MdeModulePkg/Core/Pei/Dependency/Dependency.c @@ -49,19 +49,19 @@ IsPpiInstalled ( // possibilities of alignment faults for cross-compilation // environments such as Intel?Itanium(TM). // - CopyMem(&PpiGuid, Stack->Operator, sizeof(EFI_GUID)); + CopyMem (&PpiGuid, Stack->Operator, sizeof (EFI_GUID)); // // Check if the PPI is installed. // - Status = PeiServicesLocatePpi( + Status = PeiServicesLocatePpi ( &PpiGuid, // GUID 0, // INSTANCE NULL, // EFI_PEI_PPI_DESCRIPTOR &PeiInstance // PPI ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return FALSE; } @@ -90,22 +90,20 @@ IsPpiInstalled ( **/ BOOLEAN PeimDispatchReadiness ( - IN EFI_PEI_SERVICES **PeiServices, - IN VOID *DependencyExpression + IN EFI_PEI_SERVICES **PeiServices, + IN VOID *DependencyExpression ) { DEPENDENCY_EXPRESSION_OPERAND *Iterator; EVAL_STACK_ENTRY *StackPtr; EVAL_STACK_ENTRY EvalStack[MAX_GRAMMAR_SIZE]; - Iterator = DependencyExpression; + Iterator = DependencyExpression; StackPtr = EvalStack; while (TRUE) { - switch (*(Iterator++)) { - // // For performance reason we put the frequently used items in front of // the rarely used items @@ -125,8 +123,8 @@ PeimDispatchReadiness ( // Push the pointer to the PUSH opcode operator (pointer to PPI GUID) // We will evaluate if the PPI is installed on the POP operation. // - StackPtr->Operator = (VOID *) Iterator; - Iterator = Iterator + sizeof (EFI_GUID); + StackPtr->Operator = (VOID *)Iterator; + Iterator = Iterator + sizeof (EFI_GUID); DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = %a\n", StackPtr->Operator, IsPpiInstalled (PeiServices, StackPtr) ? "TRUE" : "FALSE")); StackPtr++; break; @@ -138,6 +136,7 @@ PeimDispatchReadiness ( } else { DEBUG ((DEBUG_DISPATCH, " OR\n")); } + // // Check to make sure the dependency grammar doesn't underflow the // EvalStack on the two POPs for the AND operation. Don't need to @@ -166,15 +165,16 @@ PeimDispatchReadiness ( // if (*(Iterator - 1) == EFI_DEP_AND) { if (!(IsPpiInstalled (PeiServices, StackPtr))) { - (StackPtr-1)->Result = FALSE; + (StackPtr-1)->Result = FALSE; (StackPtr-1)->Operator = NULL; } } else { if (IsPpiInstalled (PeiServices, StackPtr)) { - (StackPtr-1)->Result = TRUE; + (StackPtr-1)->Result = TRUE; (StackPtr-1)->Operator = NULL; } } + break; case (EFI_DEP_END): @@ -188,6 +188,7 @@ PeimDispatchReadiness ( DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Underflow Error)\n")); return FALSE; } + DEBUG ((DEBUG_DISPATCH, " RESULT = %a\n", IsPpiInstalled (PeiServices, StackPtr) ? "TRUE" : "FALSE")); return IsPpiInstalled (PeiServices, StackPtr); @@ -203,7 +204,8 @@ PeimDispatchReadiness ( DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Underflow Error)\n")); return FALSE; } - (StackPtr-1)->Result = (BOOLEAN) !IsPpiInstalled (PeiServices, (StackPtr-1)); + + (StackPtr-1)->Result = (BOOLEAN) !IsPpiInstalled (PeiServices, (StackPtr-1)); (StackPtr-1)->Operator = NULL; break; @@ -214,6 +216,7 @@ PeimDispatchReadiness ( } else { DEBUG ((DEBUG_DISPATCH, " FALSE\n")); } + // // Check to make sure the dependency grammar doesn't overflow the // EvalStack on the push @@ -222,6 +225,7 @@ PeimDispatchReadiness ( DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Underflow Error)\n")); return FALSE; } + // // Iterator has increased by 1 after we retrieve the operand, so here we // should get the value pointed by (Iterator - 1), in order to obtain the @@ -232,6 +236,7 @@ PeimDispatchReadiness ( } else { StackPtr->Result = FALSE; } + StackPtr->Operator = NULL; StackPtr++; break; diff --git a/MdeModulePkg/Core/Pei/Dependency/Dependency.h b/MdeModulePkg/Core/Pei/Dependency/Dependency.h index ae066aee1d..c025863f71 100644 --- a/MdeModulePkg/Core/Pei/Dependency/Dependency.h +++ b/MdeModulePkg/Core/Pei/Dependency/Dependency.h @@ -10,7 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PEI_DEPENDENCY_H_ #define _PEI_DEPENDENCY_H_ - #define MAX_GRAMMAR_SIZE 64 // @@ -19,8 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef UINT8 DEPENDENCY_EXPRESSION_OPERAND; typedef struct { - BOOLEAN Result; - VOID *Operator; + BOOLEAN Result; + VOID *Operator; } EVAL_STACK_ENTRY; #endif diff --git a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c index 7d959b36ea..3552feda8f 100644 --- a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c @@ -21,32 +21,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID DiscoverPeimsAndOrderWithApriori ( - IN PEI_CORE_INSTANCE *Private, - IN PEI_CORE_FV_HANDLE *CoreFileHandle + IN PEI_CORE_INSTANCE *Private, + IN PEI_CORE_FV_HANDLE *CoreFileHandle ) { - EFI_STATUS Status; - EFI_PEI_FILE_HANDLE FileHandle; - EFI_PEI_FILE_HANDLE AprioriFileHandle; - EFI_GUID *Apriori; - UINTN Index; - UINTN Index2; - UINTN PeimIndex; - UINTN PeimCount; - EFI_GUID *Guid; - EFI_PEI_FILE_HANDLE *TempFileHandles; - EFI_GUID *TempFileGuid; - EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; - EFI_FV_FILE_INFO FileInfo; + EFI_STATUS Status; + EFI_PEI_FILE_HANDLE FileHandle; + EFI_PEI_FILE_HANDLE AprioriFileHandle; + EFI_GUID *Apriori; + UINTN Index; + UINTN Index2; + UINTN PeimIndex; + UINTN PeimCount; + EFI_GUID *Guid; + EFI_PEI_FILE_HANDLE *TempFileHandles; + EFI_GUID *TempFileGuid; + EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; + EFI_FV_FILE_INFO FileInfo; FvPpi = CoreFileHandle->FvPpi; // // Walk the FV and find all the PEIMs and the Apriori file. // - AprioriFileHandle = NULL; + AprioriFileHandle = NULL; Private->CurrentFvFileHandles = NULL; - Guid = NULL; + Guid = NULL; // // If the current FV has been scanned, directly get its cached records. @@ -62,7 +62,7 @@ DiscoverPeimsAndOrderWithApriori ( // // Go ahead to scan this FV, get PeimCount and cache FileHandles within it to TempFileHandles. // - PeimCount = 0; + PeimCount = 0; FileHandle = NULL; do { Status = FvPpi->FindFileByType (FvPpi, PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE, CoreFileHandle->FvHandle, &FileHandle); @@ -72,7 +72,8 @@ DiscoverPeimsAndOrderWithApriori ( // Run out of room, grow the buffer. // TempFileHandles = AllocatePool ( - sizeof (EFI_PEI_FILE_HANDLE) * (Private->TempPeimCount + TEMP_FILE_GROWTH_STEP)); + sizeof (EFI_PEI_FILE_HANDLE) * (Private->TempPeimCount + TEMP_FILE_GROWTH_STEP) + ); ASSERT (TempFileHandles != NULL); CopyMem ( TempFileHandles, @@ -80,15 +81,16 @@ DiscoverPeimsAndOrderWithApriori ( sizeof (EFI_PEI_FILE_HANDLE) * Private->TempPeimCount ); Private->TempFileHandles = TempFileHandles; - TempFileGuid = AllocatePool ( - sizeof (EFI_GUID) * (Private->TempPeimCount + TEMP_FILE_GROWTH_STEP)); + TempFileGuid = AllocatePool ( + sizeof (EFI_GUID) * (Private->TempPeimCount + TEMP_FILE_GROWTH_STEP) + ); ASSERT (TempFileGuid != NULL); CopyMem ( TempFileGuid, Private->TempFileGuid, sizeof (EFI_GUID) * Private->TempPeimCount ); - Private->TempFileGuid = TempFileGuid; + Private->TempFileGuid = TempFileGuid; Private->TempPeimCount = Private->TempPeimCount + TEMP_FILE_GROWTH_STEP; } @@ -125,12 +127,12 @@ DiscoverPeimsAndOrderWithApriori ( // Get Apriori File handle // Private->AprioriCount = 0; - Status = FvPpi->FindFileByName (FvPpi, &gPeiAprioriFileNameGuid, &CoreFileHandle->FvHandle, &AprioriFileHandle); - if (!EFI_ERROR(Status) && AprioriFileHandle != NULL) { + Status = FvPpi->FindFileByName (FvPpi, &gPeiAprioriFileNameGuid, &CoreFileHandle->FvHandle, &AprioriFileHandle); + if (!EFI_ERROR (Status) && (AprioriFileHandle != NULL)) { // // Read the Apriori file // - Status = FvPpi->FindSectionByType (FvPpi, EFI_SECTION_RAW, AprioriFileHandle, (VOID **) &Apriori); + Status = FvPpi->FindSectionByType (FvPpi, EFI_SECTION_RAW, AprioriFileHandle, (VOID **)&Apriori); if (!EFI_ERROR (Status)) { // // Calculate the number of PEIMs in the Apriori file @@ -143,6 +145,7 @@ DiscoverPeimsAndOrderWithApriori ( } else { Private->AprioriCount -= sizeof (EFI_COMMON_SECTION_HEADER); } + Private->AprioriCount /= sizeof (EFI_GUID); for (Index = 0; Index < PeimCount; Index++) { @@ -152,7 +155,7 @@ DiscoverPeimsAndOrderWithApriori ( // Status = FvPpi->GetFileInfo (FvPpi, TempFileHandles[Index], &FileInfo); ASSERT_EFI_ERROR (Status); - CopyMem (&TempFileGuid[Index], &FileInfo.FileName, sizeof(EFI_GUID)); + CopyMem (&TempFileGuid[Index], &FileInfo.FileName, sizeof (EFI_GUID)); } // @@ -163,7 +166,7 @@ DiscoverPeimsAndOrderWithApriori ( for (Index2 = 0; Index2 < Private->AprioriCount; Index2++) { Guid = ScanGuid (TempFileGuid, PeimCount * sizeof (EFI_GUID), &Apriori[Index2]); if (Guid != NULL) { - PeimIndex = ((UINTN)Guid - (UINTN)&TempFileGuid[0])/sizeof (EFI_GUID); + PeimIndex = ((UINTN)Guid - (UINTN)&TempFileGuid[0])/sizeof (EFI_GUID); CoreFileHandle->FvFileHandles[Index++] = TempFileHandles[PeimIndex]; // @@ -184,9 +187,10 @@ DiscoverPeimsAndOrderWithApriori ( for (Index2 = 0; Index2 < PeimCount; Index2++) { if (TempFileHandles[Index2] != NULL) { CoreFileHandle->FvFileHandles[Index++] = TempFileHandles[Index2]; - TempFileHandles[Index2] = NULL; + TempFileHandles[Index2] = NULL; } } + ASSERT (Index == PeimCount); } } else { @@ -197,7 +201,7 @@ DiscoverPeimsAndOrderWithApriori ( // The current FV File Handles have been cached. So that we don't have to scan the FV again. // Instead, we can retrieve the file handles within this FV from cached records. // - CoreFileHandle->ScanFv = TRUE; + CoreFileHandle->ScanFv = TRUE; Private->CurrentFvFileHandles = CoreFileHandle->FvFileHandles; } @@ -207,7 +211,8 @@ DiscoverPeimsAndOrderWithApriori ( // use these memory for data initialization. This macro should be sync with the same marco // defined in DXE Core. // -#define MINIMUM_INITIAL_MEMORY_SIZE 0x10000 +#define MINIMUM_INITIAL_MEMORY_SIZE 0x10000 + /** This function is to test if the memory range described in resource HOB is available or not. @@ -220,38 +225,40 @@ DiscoverPeimsAndOrderWithApriori ( **/ BOOLEAN PeiLoadFixAddressIsMemoryRangeAvailable ( - IN PEI_CORE_INSTANCE *PrivateData, - IN EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob + IN PEI_CORE_INSTANCE *PrivateData, + IN EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob ) { - EFI_HOB_MEMORY_ALLOCATION *MemoryHob; - BOOLEAN IsAvailable; - EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + BOOLEAN IsAvailable; + EFI_PEI_HOB_POINTERS Hob; IsAvailable = TRUE; - if (PrivateData == NULL || ResourceHob == NULL) { + if ((PrivateData == NULL) || (ResourceHob == NULL)) { return FALSE; } + // // test if the memory range describe in the HOB is already allocated. // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a memory allocation HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { MemoryHob = Hob.MemoryAllocation; - if(MemoryHob->AllocDescriptor.MemoryBaseAddress == ResourceHob->PhysicalStart && - MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength == ResourceHob->PhysicalStart + ResourceHob->ResourceLength) { - IsAvailable = FALSE; - break; - } - } + if ((MemoryHob->AllocDescriptor.MemoryBaseAddress == ResourceHob->PhysicalStart) && + (MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength == ResourceHob->PhysicalStart + ResourceHob->ResourceLength)) + { + IsAvailable = FALSE; + break; + } + } } return IsAvailable; - } + /** Hook function for Loading Module at Fixed Address feature @@ -264,123 +271,123 @@ PeiLoadFixAddressIsMemoryRangeAvailable ( **/ VOID -PeiLoadFixAddressHook( - IN PEI_CORE_INSTANCE *PrivateData +PeiLoadFixAddressHook ( + IN PEI_CORE_INSTANCE *PrivateData ) { - EFI_PHYSICAL_ADDRESS TopLoadingAddress; - UINT64 PeiMemorySize; - UINT64 TotalReservedMemorySize; - UINT64 MemoryRangeEnd; - EFI_PHYSICAL_ADDRESS HighAddress; - EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; - EFI_HOB_RESOURCE_DESCRIPTOR *NextResourceHob; - EFI_HOB_RESOURCE_DESCRIPTOR *CurrentResourceHob; - EFI_PEI_HOB_POINTERS CurrentHob; - EFI_PEI_HOB_POINTERS Hob; - EFI_PEI_HOB_POINTERS NextHob; - EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + EFI_PHYSICAL_ADDRESS TopLoadingAddress; + UINT64 PeiMemorySize; + UINT64 TotalReservedMemorySize; + UINT64 MemoryRangeEnd; + EFI_PHYSICAL_ADDRESS HighAddress; + EFI_HOB_RESOURCE_DESCRIPTOR *ResourceHob; + EFI_HOB_RESOURCE_DESCRIPTOR *NextResourceHob; + EFI_HOB_RESOURCE_DESCRIPTOR *CurrentResourceHob; + EFI_PEI_HOB_POINTERS CurrentHob; + EFI_PEI_HOB_POINTERS Hob; + EFI_PEI_HOB_POINTERS NextHob; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + // // Initialize Local Variables // - CurrentResourceHob = NULL; - ResourceHob = NULL; - NextResourceHob = NULL; - HighAddress = 0; - TopLoadingAddress = 0; - MemoryRangeEnd = 0; - CurrentHob.Raw = PrivateData->HobList.Raw; - PeiMemorySize = PrivateData->PhysicalMemoryLength; + CurrentResourceHob = NULL; + ResourceHob = NULL; + NextResourceHob = NULL; + HighAddress = 0; + TopLoadingAddress = 0; + MemoryRangeEnd = 0; + CurrentHob.Raw = PrivateData->HobList.Raw; + PeiMemorySize = PrivateData->PhysicalMemoryLength; // // The top reserved memory include 3 parts: the topest range is for DXE core initialization with the size MINIMUM_INITIAL_MEMORY_SIZE // then RuntimeCodePage range and Boot time code range. // - TotalReservedMemorySize = MINIMUM_INITIAL_MEMORY_SIZE + EFI_PAGES_TO_SIZE(PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber)); - TotalReservedMemorySize+= EFI_PAGES_TO_SIZE(PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber)) ; + TotalReservedMemorySize = MINIMUM_INITIAL_MEMORY_SIZE + EFI_PAGES_TO_SIZE (PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber)); + TotalReservedMemorySize += EFI_PAGES_TO_SIZE (PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber)); // // PEI memory range lies below the top reserved memory // TotalReservedMemorySize += PeiMemorySize; - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressRuntimeCodePageNumber= 0x%x.\n", PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber))); - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressBootTimeCodePageNumber= 0x%x.\n", PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber))); - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressPeiCodePageNumber= 0x%x.\n", PcdGet32(PcdLoadFixAddressPeiCodePageNumber))); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressRuntimeCodePageNumber= 0x%x.\n", PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber))); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressBootTimeCodePageNumber= 0x%x.\n", PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber))); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressPeiCodePageNumber= 0x%x.\n", PcdGet32 (PcdLoadFixAddressPeiCodePageNumber))); DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: Total Reserved Memory Size = 0x%lx.\n", TotalReservedMemorySize)); // // Loop through the system memory typed HOB to merge the adjacent memory range // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a resource descriptor HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - ResourceHob = Hob.ResourceDescriptor; // // If range described in this HOB is not system memory or higher than MAX_ADDRESS, ignored. // - if (ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY || - ResourceHob->PhysicalStart + ResourceHob->ResourceLength > MAX_ADDRESS) { + if ((ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY) || + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength > MAX_ADDRESS)) + { continue; } - for (NextHob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(NextHob); NextHob.Raw = GET_NEXT_HOB(NextHob)) { - if (NextHob.Raw == Hob.Raw){ + for (NextHob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (NextHob); NextHob.Raw = GET_NEXT_HOB (NextHob)) { + if (NextHob.Raw == Hob.Raw) { continue; } + // // See if this is a resource descriptor HOB // if (GET_HOB_TYPE (NextHob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - NextResourceHob = NextHob.ResourceDescriptor; // // test if range described in this NextResourceHob is system memory and have the same attribute. // Note: Here is a assumption that system memory should always be healthy even without test. // - if (NextResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && - (((NextResourceHob->ResourceAttribute^ResourceHob->ResourceAttribute)&(~EFI_RESOURCE_ATTRIBUTE_TESTED)) == 0)){ - - // - // See if the memory range described in ResourceHob and NextResourceHob is adjacent - // - if ((ResourceHob->PhysicalStart <= NextResourceHob->PhysicalStart && - ResourceHob->PhysicalStart + ResourceHob->ResourceLength >= NextResourceHob->PhysicalStart)|| - (ResourceHob->PhysicalStart >= NextResourceHob->PhysicalStart&& - ResourceHob->PhysicalStart <= NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength)) { - - MemoryRangeEnd = ((ResourceHob->PhysicalStart + ResourceHob->ResourceLength)>(NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength)) ? - (ResourceHob->PhysicalStart + ResourceHob->ResourceLength):(NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength); - - ResourceHob->PhysicalStart = (ResourceHob->PhysicalStart < NextResourceHob->PhysicalStart) ? - ResourceHob->PhysicalStart : NextResourceHob->PhysicalStart; - + if ((NextResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && + (((NextResourceHob->ResourceAttribute^ResourceHob->ResourceAttribute)&(~EFI_RESOURCE_ATTRIBUTE_TESTED)) == 0)) + { + // + // See if the memory range described in ResourceHob and NextResourceHob is adjacent + // + if (((ResourceHob->PhysicalStart <= NextResourceHob->PhysicalStart) && + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength >= NextResourceHob->PhysicalStart)) || + ((ResourceHob->PhysicalStart >= NextResourceHob->PhysicalStart) && + (ResourceHob->PhysicalStart <= NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength))) + { + MemoryRangeEnd = ((ResourceHob->PhysicalStart + ResourceHob->ResourceLength) > (NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength)) ? + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength) : (NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength); - ResourceHob->ResourceLength = (MemoryRangeEnd - ResourceHob->PhysicalStart); + ResourceHob->PhysicalStart = (ResourceHob->PhysicalStart < NextResourceHob->PhysicalStart) ? + ResourceHob->PhysicalStart : NextResourceHob->PhysicalStart; - ResourceHob->ResourceAttribute = ResourceHob->ResourceAttribute & (~EFI_RESOURCE_ATTRIBUTE_TESTED); - // - // Delete the NextResourceHob by marking it as unused. - // - GET_HOB_TYPE (NextHob) = EFI_HOB_TYPE_UNUSED; + ResourceHob->ResourceLength = (MemoryRangeEnd - ResourceHob->PhysicalStart); - } - } + ResourceHob->ResourceAttribute = ResourceHob->ResourceAttribute & (~EFI_RESOURCE_ATTRIBUTE_TESTED); + // + // Delete the NextResourceHob by marking it as unused. + // + GET_HOB_TYPE (NextHob) = EFI_HOB_TYPE_UNUSED; + } + } } } } } + // // Some platform is already allocated pages before the HOB re-org. Here to build dedicated resource HOB to describe // the allocated memory range // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a memory allocation HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { MemoryHob = Hob.MemoryAllocation; - for (NextHob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(NextHob); NextHob.Raw = GET_NEXT_HOB(NextHob)) { + for (NextHob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (NextHob); NextHob.Raw = GET_NEXT_HOB (NextHob)) { // // See if this is a resource descriptor HOB // @@ -389,36 +396,40 @@ PeiLoadFixAddressHook( // // If range described in this HOB is not system memory or higher than MAX_ADDRESS, ignored. // - if (NextResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY || NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength > MAX_ADDRESS) { + if ((NextResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY) || (NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength > MAX_ADDRESS)) { continue; } + // // If the range describe in memory allocation HOB belongs to the memory range described by the resource HOB // - if (MemoryHob->AllocDescriptor.MemoryBaseAddress >= NextResourceHob->PhysicalStart && - MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength <= NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength) { - // - // Build separate resource HOB for this allocated range - // - if (MemoryHob->AllocDescriptor.MemoryBaseAddress > NextResourceHob->PhysicalStart) { - BuildResourceDescriptorHob ( - EFI_RESOURCE_SYSTEM_MEMORY, - NextResourceHob->ResourceAttribute, - NextResourceHob->PhysicalStart, - (MemoryHob->AllocDescriptor.MemoryBaseAddress - NextResourceHob->PhysicalStart) - ); - } - if (MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength < NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength) { - BuildResourceDescriptorHob ( - EFI_RESOURCE_SYSTEM_MEMORY, - NextResourceHob->ResourceAttribute, - MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength, - (NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength -(MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength)) - ); - } - NextResourceHob->PhysicalStart = MemoryHob->AllocDescriptor.MemoryBaseAddress; - NextResourceHob->ResourceLength = MemoryHob->AllocDescriptor.MemoryLength; - break; + if ((MemoryHob->AllocDescriptor.MemoryBaseAddress >= NextResourceHob->PhysicalStart) && + (MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength <= NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength)) + { + // + // Build separate resource HOB for this allocated range + // + if (MemoryHob->AllocDescriptor.MemoryBaseAddress > NextResourceHob->PhysicalStart) { + BuildResourceDescriptorHob ( + EFI_RESOURCE_SYSTEM_MEMORY, + NextResourceHob->ResourceAttribute, + NextResourceHob->PhysicalStart, + (MemoryHob->AllocDescriptor.MemoryBaseAddress - NextResourceHob->PhysicalStart) + ); + } + + if (MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength < NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength) { + BuildResourceDescriptorHob ( + EFI_RESOURCE_SYSTEM_MEMORY, + NextResourceHob->ResourceAttribute, + MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength, + (NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength -(MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength)) + ); + } + + NextResourceHob->PhysicalStart = MemoryHob->AllocDescriptor.MemoryBaseAddress; + NextResourceHob->ResourceLength = MemoryHob->AllocDescriptor.MemoryLength; + break; } } } @@ -428,11 +439,11 @@ PeiLoadFixAddressHook( // // Try to find and validate the TOP address. // - if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) > 0 ) { + if ((INT64)PcdGet64 (PcdLoadModuleAtFixAddressEnable) > 0 ) { // // The LMFA feature is enabled as load module at fixed absolute address. // - TopLoadingAddress = (EFI_PHYSICAL_ADDRESS)PcdGet64(PcdLoadModuleAtFixAddressEnable); + TopLoadingAddress = (EFI_PHYSICAL_ADDRESS)PcdGet64 (PcdLoadModuleAtFixAddressEnable); DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: Loading module at fixed absolute address.\n")); // // validate the Address. Loop the resource descriptor HOB to make sure the address is in valid memory range @@ -441,67 +452,73 @@ PeiLoadFixAddressHook( DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR:Top Address 0x%lx is invalid since top address should be page align. \n", TopLoadingAddress)); ASSERT (FALSE); } + // // Search for a memory region that is below MAX_ADDRESS and in which TopLoadingAddress lies // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a resource descriptor HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - ResourceHob = Hob.ResourceDescriptor; // // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // - if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && - ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS) { - // - // See if Top address specified by user is valid. - // - if (ResourceHob->PhysicalStart + TotalReservedMemorySize < TopLoadingAddress && - (ResourceHob->PhysicalStart + ResourceHob->ResourceLength - MINIMUM_INITIAL_MEMORY_SIZE) >= TopLoadingAddress && - PeiLoadFixAddressIsMemoryRangeAvailable(PrivateData, ResourceHob)) { - CurrentResourceHob = ResourceHob; - CurrentHob = Hob; - break; - } + if ((ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS)) + { + // + // See if Top address specified by user is valid. + // + if ((ResourceHob->PhysicalStart + TotalReservedMemorySize < TopLoadingAddress) && + ((ResourceHob->PhysicalStart + ResourceHob->ResourceLength - MINIMUM_INITIAL_MEMORY_SIZE) >= TopLoadingAddress) && + PeiLoadFixAddressIsMemoryRangeAvailable (PrivateData, ResourceHob)) + { + CurrentResourceHob = ResourceHob; + CurrentHob = Hob; + break; + } } } } + if (CurrentResourceHob != NULL) { - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO:Top Address 0x%lx is valid \n", TopLoadingAddress)); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO:Top Address 0x%lx is valid \n", TopLoadingAddress)); TopLoadingAddress += MINIMUM_INITIAL_MEMORY_SIZE; } else { - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR:Top Address 0x%lx is invalid \n", TopLoadingAddress)); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR:Top Address 0x%lx is invalid \n", TopLoadingAddress)); DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR:The recommended Top Address for the platform is: \n")); // // Print the recommended Top address range. // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a resource descriptor HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - ResourceHob = Hob.ResourceDescriptor; // // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // - if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && - ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS) { - // - // See if Top address specified by user is valid. - // - if (ResourceHob->ResourceLength > TotalReservedMemorySize && PeiLoadFixAddressIsMemoryRangeAvailable(PrivateData, ResourceHob)) { - DEBUG ((DEBUG_INFO, "(0x%lx, 0x%lx)\n", - (ResourceHob->PhysicalStart + TotalReservedMemorySize -MINIMUM_INITIAL_MEMORY_SIZE), - (ResourceHob->PhysicalStart + ResourceHob->ResourceLength -MINIMUM_INITIAL_MEMORY_SIZE) - )); - } + if ((ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS)) + { + // + // See if Top address specified by user is valid. + // + if ((ResourceHob->ResourceLength > TotalReservedMemorySize) && PeiLoadFixAddressIsMemoryRangeAvailable (PrivateData, ResourceHob)) { + DEBUG (( + DEBUG_INFO, + "(0x%lx, 0x%lx)\n", + (ResourceHob->PhysicalStart + TotalReservedMemorySize -MINIMUM_INITIAL_MEMORY_SIZE), + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength -MINIMUM_INITIAL_MEMORY_SIZE) + )); + } } } } + // // Assert here // @@ -516,30 +533,31 @@ PeiLoadFixAddressHook( // // Search for a tested memory region that is below MAX_ADDRESS // - for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { + for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { // // See if this is a resource descriptor HOB // if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { - ResourceHob = Hob.ResourceDescriptor; // // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // - if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && - ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS && - ResourceHob->ResourceLength > TotalReservedMemorySize && PeiLoadFixAddressIsMemoryRangeAvailable(PrivateData, ResourceHob)) { + if ((ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY) && + (ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS) && + (ResourceHob->ResourceLength > TotalReservedMemorySize) && PeiLoadFixAddressIsMemoryRangeAvailable (PrivateData, ResourceHob)) + { // // See if this is the highest largest system memory region below MaxAddress // if (ResourceHob->PhysicalStart > HighAddress) { - CurrentResourceHob = ResourceHob; - CurrentHob = Hob; - HighAddress = CurrentResourceHob->PhysicalStart; + CurrentResourceHob = ResourceHob; + CurrentHob = Hob; + HighAddress = CurrentResourceHob->PhysicalStart; } } } } + if (CurrentResourceHob == NULL) { DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR:The System Memory is too small\n")); // @@ -548,7 +566,7 @@ PeiLoadFixAddressHook( ASSERT (FALSE); return; } else { - TopLoadingAddress = CurrentResourceHob->PhysicalStart + CurrentResourceHob->ResourceLength ; + TopLoadingAddress = CurrentResourceHob->PhysicalStart + CurrentResourceHob->ResourceLength; } } @@ -559,17 +577,17 @@ PeiLoadFixAddressHook( BuildResourceDescriptorHob ( EFI_RESOURCE_SYSTEM_MEMORY, ( - EFI_RESOURCE_ATTRIBUTE_PRESENT | - EFI_RESOURCE_ATTRIBUTE_INITIALIZED | - EFI_RESOURCE_ATTRIBUTE_TESTED | - EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | - EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE + EFI_RESOURCE_ATTRIBUTE_PRESENT | + EFI_RESOURCE_ATTRIBUTE_INITIALIZED | + EFI_RESOURCE_ATTRIBUTE_TESTED | + EFI_RESOURCE_ATTRIBUTE_UNCACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | + EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE ), (TopLoadingAddress - TotalReservedMemorySize), TotalReservedMemorySize - ); + ); // // rebuild resource for the remain memory if necessary // @@ -583,11 +601,12 @@ PeiLoadFixAddressHook( EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE - ), - CurrentResourceHob->PhysicalStart, - (TopLoadingAddress - TotalReservedMemorySize - CurrentResourceHob->PhysicalStart) - ); + ), + CurrentResourceHob->PhysicalStart, + (TopLoadingAddress - TotalReservedMemorySize - CurrentResourceHob->PhysicalStart) + ); } + if (CurrentResourceHob->PhysicalStart + CurrentResourceHob->ResourceLength > TopLoadingAddress ) { BuildResourceDescriptorHob ( EFI_RESOURCE_SYSTEM_MEMORY, @@ -598,11 +617,12 @@ PeiLoadFixAddressHook( EFI_RESOURCE_ATTRIBUTE_WRITE_COMBINEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_THROUGH_CACHEABLE | EFI_RESOURCE_ATTRIBUTE_WRITE_BACK_CACHEABLE - ), - TopLoadingAddress, - (CurrentResourceHob->PhysicalStart + CurrentResourceHob->ResourceLength - TopLoadingAddress) - ); + ), + TopLoadingAddress, + (CurrentResourceHob->PhysicalStart + CurrentResourceHob->ResourceLength - TopLoadingAddress) + ); } + // // Delete CurrentHob by marking it as unused since the memory range described by is rebuilt. // @@ -613,7 +633,7 @@ PeiLoadFixAddressHook( // Cache the top address for Loading Module at Fixed Address feature // PrivateData->LoadModuleAtFixAddressTopAddress = TopLoadingAddress - MINIMUM_INITIAL_MEMORY_SIZE; - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: Top address = 0x%lx\n", PrivateData->LoadModuleAtFixAddressTopAddress)); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: Top address = 0x%lx\n", PrivateData->LoadModuleAtFixAddressTopAddress)); // // reinstall the PEI memory relative to TopLoadingAddress // @@ -633,8 +653,8 @@ PeiLoadFixAddressHook( VOID EFIAPI PeiCoreEntry ( - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, - IN PEI_CORE_INSTANCE *Private + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, + IN PEI_CORE_INSTANCE *Private ) { // @@ -654,36 +674,36 @@ PeiCoreEntry ( **/ VOID PeiCheckAndSwitchStack ( - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, - IN PEI_CORE_INSTANCE *Private + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, + IN PEI_CORE_INSTANCE *Private ) { - VOID *LoadFixPeiCodeBegin; - EFI_STATUS Status; - CONST EFI_PEI_SERVICES **PeiServices; - UINT64 NewStackSize; - EFI_PHYSICAL_ADDRESS TopOfOldStack; - EFI_PHYSICAL_ADDRESS TopOfNewStack; - UINTN StackOffset; - BOOLEAN StackOffsetPositive; - EFI_PHYSICAL_ADDRESS TemporaryRamBase; - UINTN TemporaryRamSize; - UINTN TemporaryStackSize; - VOID *TemporaryStackBase; - UINTN PeiTemporaryRamSize; - VOID *PeiTemporaryRamBase; - EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI *TemporaryRamSupportPpi; - EFI_PHYSICAL_ADDRESS BaseOfNewHeap; - EFI_PHYSICAL_ADDRESS HoleMemBase; - UINTN HoleMemSize; - UINTN HeapTemporaryRamSize; - EFI_PHYSICAL_ADDRESS TempBase1; - UINTN TempSize1; - EFI_PHYSICAL_ADDRESS TempBase2; - UINTN TempSize2; - UINTN Index; - - PeiServices = (CONST EFI_PEI_SERVICES **) &Private->Ps; + VOID *LoadFixPeiCodeBegin; + EFI_STATUS Status; + CONST EFI_PEI_SERVICES **PeiServices; + UINT64 NewStackSize; + EFI_PHYSICAL_ADDRESS TopOfOldStack; + EFI_PHYSICAL_ADDRESS TopOfNewStack; + UINTN StackOffset; + BOOLEAN StackOffsetPositive; + EFI_PHYSICAL_ADDRESS TemporaryRamBase; + UINTN TemporaryRamSize; + UINTN TemporaryStackSize; + VOID *TemporaryStackBase; + UINTN PeiTemporaryRamSize; + VOID *PeiTemporaryRamBase; + EFI_PEI_TEMPORARY_RAM_SUPPORT_PPI *TemporaryRamSupportPpi; + EFI_PHYSICAL_ADDRESS BaseOfNewHeap; + EFI_PHYSICAL_ADDRESS HoleMemBase; + UINTN HoleMemSize; + UINTN HeapTemporaryRamSize; + EFI_PHYSICAL_ADDRESS TempBase1; + UINTN TempSize1; + EFI_PHYSICAL_ADDRESS TempBase2; + UINTN TempSize2; + UINTN Index; + + PeiServices = (CONST EFI_PEI_SERVICES **)&Private->Ps; if (Private->SwitchStackSignal) { // @@ -691,38 +711,49 @@ PeiCheckAndSwitchStack ( // usage in temporary memory for debugging. // DEBUG_CODE_BEGIN (); - UINT32 *StackPointer; - EFI_PEI_HOB_POINTERS Hob; + UINT32 *StackPointer; + EFI_PEI_HOB_POINTERS Hob; + + for ( StackPointer = (UINT32 *)SecCoreData->StackBase; + (StackPointer < (UINT32 *)((UINTN)SecCoreData->StackBase + SecCoreData->StackSize)) \ + && (*StackPointer == PcdGet32 (PcdInitValueInTempStack)); + StackPointer++) + { + } - for (StackPointer = (UINT32*)SecCoreData->StackBase; - (StackPointer < (UINT32*)((UINTN)SecCoreData->StackBase + SecCoreData->StackSize)) \ - && (*StackPointer == PcdGet32 (PcdInitValueInTempStack)); - StackPointer ++) { + DEBUG ((DEBUG_INFO, "Temp Stack : BaseAddress=0x%p Length=0x%X\n", SecCoreData->StackBase, (UINT32)SecCoreData->StackSize)); + DEBUG ((DEBUG_INFO, "Temp Heap : BaseAddress=0x%p Length=0x%X\n", SecCoreData->PeiTemporaryRamBase, (UINT32)SecCoreData->PeiTemporaryRamSize)); + DEBUG ((DEBUG_INFO, "Total temporary memory: %d bytes.\n", (UINT32)SecCoreData->TemporaryRamSize)); + DEBUG (( + DEBUG_INFO, + " temporary memory stack ever used: %d bytes.\n", + (UINT32)(SecCoreData->StackSize - ((UINTN)StackPointer - (UINTN)SecCoreData->StackBase)) + )); + DEBUG (( + DEBUG_INFO, + " temporary memory heap used for HobList: %d bytes.\n", + (UINT32)((UINTN)Private->HobList.HandoffInformationTable->EfiFreeMemoryBottom - (UINTN)Private->HobList.Raw) + )); + DEBUG (( + DEBUG_INFO, + " temporary memory heap occupied by memory pages: %d bytes.\n", + (UINT32)(UINTN)(Private->HobList.HandoffInformationTable->EfiMemoryTop - Private->HobList.HandoffInformationTable->EfiFreeMemoryTop) + )); + for (Hob.Raw = Private->HobList.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { + if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { + DEBUG (( + DEBUG_INFO, + "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ + Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ + Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ + Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1 + )); } + } - DEBUG ((DEBUG_INFO, "Temp Stack : BaseAddress=0x%p Length=0x%X\n", SecCoreData->StackBase, (UINT32)SecCoreData->StackSize)); - DEBUG ((DEBUG_INFO, "Temp Heap : BaseAddress=0x%p Length=0x%X\n", SecCoreData->PeiTemporaryRamBase, (UINT32)SecCoreData->PeiTemporaryRamSize)); - DEBUG ((DEBUG_INFO, "Total temporary memory: %d bytes.\n", (UINT32)SecCoreData->TemporaryRamSize)); - DEBUG ((DEBUG_INFO, " temporary memory stack ever used: %d bytes.\n", - (UINT32)(SecCoreData->StackSize - ((UINTN) StackPointer - (UINTN)SecCoreData->StackBase)) - )); - DEBUG ((DEBUG_INFO, " temporary memory heap used for HobList: %d bytes.\n", - (UINT32)((UINTN)Private->HobList.HandoffInformationTable->EfiFreeMemoryBottom - (UINTN)Private->HobList.Raw) - )); - DEBUG ((DEBUG_INFO, " temporary memory heap occupied by memory pages: %d bytes.\n", - (UINT32)(UINTN)(Private->HobList.HandoffInformationTable->EfiMemoryTop - Private->HobList.HandoffInformationTable->EfiFreeMemoryTop) - )); - for (Hob.Raw = Private->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { - if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_MEMORY_ALLOCATION) { - DEBUG ((DEBUG_INFO, "Memory Allocation 0x%08x 0x%0lx - 0x%0lx\n", \ - Hob.MemoryAllocation->AllocDescriptor.MemoryType, \ - Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress, \ - Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength - 1)); - } - } DEBUG_CODE_END (); - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { + if ((PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { // // Loading Module at Fixed Address is enabled // @@ -731,8 +762,8 @@ PeiCheckAndSwitchStack ( // // If Loading Module at Fixed Address is enabled, Allocating memory range for Pei code range. // - LoadFixPeiCodeBegin = AllocatePages((UINTN)PcdGet32(PcdLoadFixAddressPeiCodePageNumber)); - DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PeiCodeBegin = 0x%lX, PeiCodeTop= 0x%lX\n", (UINT64)(UINTN)LoadFixPeiCodeBegin, (UINT64)((UINTN)LoadFixPeiCodeBegin + PcdGet32(PcdLoadFixAddressPeiCodePageNumber) * EFI_PAGE_SIZE))); + LoadFixPeiCodeBegin = AllocatePages ((UINTN)PcdGet32 (PcdLoadFixAddressPeiCodePageNumber)); + DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED INFO: PeiCodeBegin = 0x%lX, PeiCodeTop= 0x%lX\n", (UINT64)(UINTN)LoadFixPeiCodeBegin, (UINT64)((UINTN)LoadFixPeiCodeBegin + PcdGet32 (PcdLoadFixAddressPeiCodePageNumber) * EFI_PAGE_SIZE))); } // @@ -745,7 +776,7 @@ PeiCheckAndSwitchStack ( // NewStackSize = RShiftU64 (Private->PhysicalMemoryLength, 1); NewStackSize = ALIGN_VALUE (NewStackSize, EFI_PAGE_SIZE); - NewStackSize = MIN (PcdGet32(PcdPeiCoreMaxPeiStackSize), NewStackSize); + NewStackSize = MIN (PcdGet32 (PcdPeiCoreMaxPeiStackSize), NewStackSize); DEBUG ((DEBUG_INFO, "Old Stack size %d, New stack size %d\n", (UINT32)SecCoreData->StackSize, (UINT32)NewStackSize)); ASSERT (NewStackSize >= SecCoreData->StackSize); @@ -757,13 +788,14 @@ PeiCheckAndSwitchStack ( TopOfNewStack = Private->PhysicalMemoryBegin + NewStackSize; if (TopOfNewStack >= TopOfOldStack) { StackOffsetPositive = TRUE; - StackOffset = (UINTN)(TopOfNewStack - TopOfOldStack); + StackOffset = (UINTN)(TopOfNewStack - TopOfOldStack); } else { StackOffsetPositive = FALSE; - StackOffset = (UINTN)(TopOfOldStack - TopOfNewStack); + StackOffset = (UINTN)(TopOfOldStack - TopOfNewStack); } + Private->StackOffsetPositive = StackOffsetPositive; - Private->StackOffset = StackOffset; + Private->StackOffset = StackOffset; // // Build Stack HOB that describes the permanent memory stack @@ -788,7 +820,7 @@ PeiCheckAndSwitchStack ( &gEfiTemporaryRamSupportPpiGuid, 0, NULL, - (VOID**)&TemporaryRamSupportPpi + (VOID **)&TemporaryRamSupportPpi ); if (!EFI_ERROR (Status)) { // @@ -797,23 +829,23 @@ PeiCheckAndSwitchStack ( BaseOfNewHeap = TopOfNewStack; if (BaseOfNewHeap >= (UINTN)SecCoreData->PeiTemporaryRamBase) { Private->HeapOffsetPositive = TRUE; - Private->HeapOffset = (UINTN)(BaseOfNewHeap - (UINTN)SecCoreData->PeiTemporaryRamBase); + Private->HeapOffset = (UINTN)(BaseOfNewHeap - (UINTN)SecCoreData->PeiTemporaryRamBase); } else { Private->HeapOffsetPositive = FALSE; - Private->HeapOffset = (UINTN)((UINTN)SecCoreData->PeiTemporaryRamBase - BaseOfNewHeap); + Private->HeapOffset = (UINTN)((UINTN)SecCoreData->PeiTemporaryRamBase - BaseOfNewHeap); } - DEBUG ((DEBUG_INFO, "Heap Offset = 0x%lX Stack Offset = 0x%lX\n", (UINT64) Private->HeapOffset, (UINT64) Private->StackOffset)); + DEBUG ((DEBUG_INFO, "Heap Offset = 0x%lX Stack Offset = 0x%lX\n", (UINT64)Private->HeapOffset, (UINT64)Private->StackOffset)); // // Calculate new HandOffTable and PrivateData address in permanent memory's stack // if (StackOffsetPositive) { SecCoreData = (CONST EFI_SEC_PEI_HAND_OFF *)((UINTN)(VOID *)SecCoreData + StackOffset); - Private = (PEI_CORE_INSTANCE *)((UINTN)(VOID *)Private + StackOffset); + Private = (PEI_CORE_INSTANCE *)((UINTN)(VOID *)Private + StackOffset); } else { SecCoreData = (CONST EFI_SEC_PEI_HAND_OFF *)((UINTN)(VOID *)SecCoreData - StackOffset); - Private = (PEI_CORE_INSTANCE *)((UINTN)(VOID *)Private - StackOffset); + Private = (PEI_CORE_INSTANCE *)((UINTN)(VOID *)Private - StackOffset); } // @@ -863,27 +895,28 @@ PeiCheckAndSwitchStack ( // BaseOfNewHeap = ALIGN_VALUE (BaseOfNewHeap + HoleMemSize, 8); } + if (BaseOfNewHeap >= (UINTN)SecCoreData->PeiTemporaryRamBase) { Private->HeapOffsetPositive = TRUE; - Private->HeapOffset = (UINTN)(BaseOfNewHeap - (UINTN)SecCoreData->PeiTemporaryRamBase); + Private->HeapOffset = (UINTN)(BaseOfNewHeap - (UINTN)SecCoreData->PeiTemporaryRamBase); } else { Private->HeapOffsetPositive = FALSE; - Private->HeapOffset = (UINTN)((UINTN)SecCoreData->PeiTemporaryRamBase - BaseOfNewHeap); + Private->HeapOffset = (UINTN)((UINTN)SecCoreData->PeiTemporaryRamBase - BaseOfNewHeap); } - DEBUG ((DEBUG_INFO, "Heap Offset = 0x%lX Stack Offset = 0x%lX\n", (UINT64) Private->HeapOffset, (UINT64) Private->StackOffset)); + DEBUG ((DEBUG_INFO, "Heap Offset = 0x%lX Stack Offset = 0x%lX\n", (UINT64)Private->HeapOffset, (UINT64)Private->StackOffset)); // // Migrate Heap // - HeapTemporaryRamSize = (UINTN) (Private->HobList.HandoffInformationTable->EfiFreeMemoryBottom - Private->HobList.HandoffInformationTable->EfiMemoryBottom); + HeapTemporaryRamSize = (UINTN)(Private->HobList.HandoffInformationTable->EfiFreeMemoryBottom - Private->HobList.HandoffInformationTable->EfiMemoryBottom); ASSERT (BaseOfNewHeap + HeapTemporaryRamSize <= Private->FreePhysicalMemoryTop); - CopyMem ((UINT8 *) (UINTN) BaseOfNewHeap, PeiTemporaryRamBase, HeapTemporaryRamSize); + CopyMem ((UINT8 *)(UINTN)BaseOfNewHeap, PeiTemporaryRamBase, HeapTemporaryRamSize); // // Migrate Stack // - CopyMem ((UINT8 *) (UINTN) (TopOfNewStack - TemporaryStackSize), TemporaryStackBase, TemporaryStackSize); + CopyMem ((UINT8 *)(UINTN)(TopOfNewStack - TemporaryStackSize), TemporaryStackBase, TemporaryStackSize); // // Copy Hole Range Data @@ -893,42 +926,46 @@ PeiCheckAndSwitchStack ( // Prepare Hole // if (PeiTemporaryRamBase < TemporaryStackBase) { - TempBase1 = (EFI_PHYSICAL_ADDRESS) (UINTN) PeiTemporaryRamBase; + TempBase1 = (EFI_PHYSICAL_ADDRESS)(UINTN)PeiTemporaryRamBase; TempSize1 = PeiTemporaryRamSize; - TempBase2 = (EFI_PHYSICAL_ADDRESS) (UINTN) TemporaryStackBase; + TempBase2 = (EFI_PHYSICAL_ADDRESS)(UINTN)TemporaryStackBase; TempSize2 = TemporaryStackSize; } else { - TempBase1 = (EFI_PHYSICAL_ADDRESS) (UINTN) TemporaryStackBase; + TempBase1 = (EFI_PHYSICAL_ADDRESS)(UINTN)TemporaryStackBase; TempSize1 = TemporaryStackSize; - TempBase2 =(EFI_PHYSICAL_ADDRESS) (UINTN) PeiTemporaryRamBase; + TempBase2 = (EFI_PHYSICAL_ADDRESS)(UINTN)PeiTemporaryRamBase; TempSize2 = PeiTemporaryRamSize; } + if (TemporaryRamBase < TempBase1) { Private->HoleData[0].Base = TemporaryRamBase; - Private->HoleData[0].Size = (UINTN) (TempBase1 - TemporaryRamBase); + Private->HoleData[0].Size = (UINTN)(TempBase1 - TemporaryRamBase); } + if (TempBase1 + TempSize1 < TempBase2) { Private->HoleData[1].Base = TempBase1 + TempSize1; - Private->HoleData[1].Size = (UINTN) (TempBase2 - TempBase1 - TempSize1); + Private->HoleData[1].Size = (UINTN)(TempBase2 - TempBase1 - TempSize1); } + if (TempBase2 + TempSize2 < TemporaryRamBase + TemporaryRamSize) { Private->HoleData[2].Base = TempBase2 + TempSize2; - Private->HoleData[2].Size = (UINTN) (TemporaryRamBase + TemporaryRamSize - TempBase2 - TempSize2); + Private->HoleData[2].Size = (UINTN)(TemporaryRamBase + TemporaryRamSize - TempBase2 - TempSize2); } // // Copy Hole Range data. // - for (Index = 0; Index < HOLE_MAX_NUMBER; Index ++) { + for (Index = 0; Index < HOLE_MAX_NUMBER; Index++) { if (Private->HoleData[Index].Size > 0) { if (HoleMemBase > Private->HoleData[Index].Base) { Private->HoleData[Index].OffsetPositive = TRUE; - Private->HoleData[Index].Offset = (UINTN) (HoleMemBase - Private->HoleData[Index].Base); + Private->HoleData[Index].Offset = (UINTN)(HoleMemBase - Private->HoleData[Index].Base); } else { Private->HoleData[Index].OffsetPositive = FALSE; - Private->HoleData[Index].Offset = (UINTN) (Private->HoleData[Index].Base - HoleMemBase); + Private->HoleData[Index].Offset = (UINTN)(Private->HoleData[Index].Base - HoleMemBase); } - CopyMem ((VOID *) (UINTN) HoleMemBase, (VOID *) (UINTN) Private->HoleData[Index].Base, Private->HoleData[Index].Size); + + CopyMem ((VOID *)(UINTN)HoleMemBase, (VOID *)(UINTN)Private->HoleData[Index].Base, Private->HoleData[Index].Size); HoleMemBase = HoleMemBase + Private->HoleData[Index].Size; } } @@ -939,9 +976,9 @@ PeiCheckAndSwitchStack ( // SwitchStack ( (SWITCH_STACK_ENTRY_POINT)(UINTN)PeiCoreEntry, - (VOID *) SecCoreData, - (VOID *) Private, - (VOID *) (UINTN) TopOfNewStack + (VOID *)SecCoreData, + (VOID *)Private, + (VOID *)(UINTN)TopOfNewStack ); } @@ -964,20 +1001,20 @@ PeiCheckAndSwitchStack ( EFI_STATUS EFIAPI MigratePeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN EFI_PEI_FILE_HANDLE MigratedFileHandle + IN EFI_PEI_FILE_HANDLE FileHandle, + IN EFI_PEI_FILE_HANDLE MigratedFileHandle ) { - EFI_STATUS Status; - EFI_FFS_FILE_HEADER *FileHeader; - VOID *Pe32Data; - VOID *ImageAddress; - CHAR8 *AsciiString; - UINTN Index; + EFI_STATUS Status; + EFI_FFS_FILE_HEADER *FileHeader; + VOID *Pe32Data; + VOID *ImageAddress; + CHAR8 *AsciiString; + UINTN Index; Status = EFI_SUCCESS; - FileHeader = (EFI_FFS_FILE_HEADER *) FileHandle; + FileHeader = (EFI_FFS_FILE_HEADER *)FileHandle; ASSERT (!IS_FFS_FILE2 (FileHeader)); ImageAddress = NULL; @@ -986,18 +1023,19 @@ MigratePeim ( DEBUG_CODE_BEGIN (); AsciiString = PeCoffLoaderGetPdbPointer (ImageAddress); for (Index = 0; AsciiString[Index] != 0; Index++) { - if (AsciiString[Index] == '\\' || AsciiString[Index] == '/') { + if ((AsciiString[Index] == '\\') || (AsciiString[Index] == '/')) { AsciiString = AsciiString + Index + 1; - Index = 0; + Index = 0; } else if (AsciiString[Index] == '.') { AsciiString[Index] = 0; } } + DEBUG ((DEBUG_VERBOSE, "%a", AsciiString)); DEBUG_CODE_END (); - Pe32Data = (VOID *) ((UINTN) ImageAddress - (UINTN) MigratedFileHandle + (UINTN) FileHandle); - Status = LoadAndRelocatePeCoffImageInPlace (Pe32Data, ImageAddress); + Pe32Data = (VOID *)((UINTN)ImageAddress - (UINTN)MigratedFileHandle + (UINTN)FileHandle); + Status = LoadAndRelocatePeCoffImageInPlace (Pe32Data, ImageAddress); ASSERT_EFI_ERROR (Status); } @@ -1014,22 +1052,22 @@ MigratePeim ( **/ VOID ConvertStatusCodeCallbacks ( - IN UINTN OrgFvHandle, - IN UINTN FvHandle, - IN UINTN FvSize + IN UINTN OrgFvHandle, + IN UINTN FvHandle, + IN UINTN FvSize ) { - EFI_PEI_HOB_POINTERS Hob; - UINTN *NumberOfEntries; - UINTN *CallbackEntry; - UINTN Index; + EFI_PEI_HOB_POINTERS Hob; + UINTN *NumberOfEntries; + UINTN *CallbackEntry; + UINTN Index; - Hob.Raw = GetFirstGuidHob (&gStatusCodeCallbackGuid); + Hob.Raw = GetFirstGuidHob (&gStatusCodeCallbackGuid); while (Hob.Raw != NULL) { NumberOfEntries = GET_GUID_HOB_DATA (Hob); CallbackEntry = NumberOfEntries + 1; for (Index = 0; Index < *NumberOfEntries; Index++) { - if (((VOID *) CallbackEntry[Index]) != NULL) { + if (((VOID *)CallbackEntry[Index]) != NULL) { if ((CallbackEntry[Index] >= OrgFvHandle) && (CallbackEntry[Index] < (OrgFvHandle + FvSize))) { DEBUG (( DEBUG_INFO, @@ -1043,6 +1081,7 @@ ConvertStatusCodeCallbacks ( } else { CallbackEntry[Index] = CallbackEntry[Index] + (FvHandle - OrgFvHandle); } + DEBUG (( DEBUG_INFO, "0x%0*Lx\n", @@ -1052,6 +1091,7 @@ ConvertStatusCodeCallbacks ( } } } + Hob.Raw = GET_NEXT_HOB (Hob); Hob.Raw = GetNextGuidHob (&gStatusCodeCallbackGuid, Hob.Raw); } @@ -1072,18 +1112,18 @@ ConvertStatusCodeCallbacks ( EFI_STATUS EFIAPI MigratePeimsInFv ( - IN PEI_CORE_INSTANCE *Private, - IN UINTN FvIndex, - IN UINTN OrgFvHandle, - IN UINTN FvHandle + IN PEI_CORE_INSTANCE *Private, + IN UINTN FvIndex, + IN UINTN OrgFvHandle, + IN UINTN FvHandle ) { - EFI_STATUS Status; - volatile UINTN FileIndex; - EFI_PEI_FILE_HANDLE MigratedFileHandle; - EFI_PEI_FILE_HANDLE FileHandle; + EFI_STATUS Status; + volatile UINTN FileIndex; + EFI_PEI_FILE_HANDLE MigratedFileHandle; + EFI_PEI_FILE_HANDLE FileHandle; - if (Private == NULL || FvIndex >= Private->FvCount) { + if ((Private == NULL) || (FvIndex >= Private->FvCount)) { return EFI_INVALID_PARAMETER; } @@ -1092,7 +1132,7 @@ MigratePeimsInFv ( if (Private->Fv[FvIndex].FvFileHandles[FileIndex] != NULL) { FileHandle = Private->Fv[FvIndex].FvFileHandles[FileIndex]; - MigratedFileHandle = (EFI_PEI_FILE_HANDLE) ((UINTN) FileHandle - OrgFvHandle + FvHandle); + MigratedFileHandle = (EFI_PEI_FILE_HANDLE)((UINTN)FileHandle - OrgFvHandle + FvHandle); DEBUG ((DEBUG_VERBOSE, " Migrating FileHandle %2d ", FileIndex)); Status = MigratePeim (FileHandle, MigratedFileHandle); @@ -1127,20 +1167,20 @@ MigratePeimsInFv ( EFI_STATUS EFIAPI EvacuateTempRam ( - IN PEI_CORE_INSTANCE *Private, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *Private, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ) { - EFI_STATUS Status; - volatile UINTN FvIndex; - volatile UINTN FvChildIndex; - UINTN ChildFvOffset; - EFI_PHYSICAL_ADDRESS FvHeaderAddress; - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - EFI_FIRMWARE_VOLUME_HEADER *ChildFvHeader; - EFI_FIRMWARE_VOLUME_HEADER *MigratedFvHeader; - EFI_FIRMWARE_VOLUME_HEADER *RawDataFvHeader; - EFI_FIRMWARE_VOLUME_HEADER *MigratedChildFvHeader; + EFI_STATUS Status; + volatile UINTN FvIndex; + volatile UINTN FvChildIndex; + UINTN ChildFvOffset; + EFI_PHYSICAL_ADDRESS FvHeaderAddress; + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_FIRMWARE_VOLUME_HEADER *ChildFvHeader; + EFI_FIRMWARE_VOLUME_HEADER *MigratedFvHeader; + EFI_FIRMWARE_VOLUME_HEADER *RawDataFvHeader; + EFI_FIRMWARE_VOLUME_HEADER *MigratedChildFvHeader; PEI_CORE_FV_HANDLE PeiCoreFvHandle; EFI_PEI_CORE_FV_LOCATION_PPI *PeiCoreFvLocationPpi; @@ -1153,18 +1193,20 @@ EvacuateTempRam ( // // Migrate PPI Pointers of PEI_CORE from temporary memory to newly loaded PEI_CORE in permanent memory. // - Status = PeiLocatePpi ((CONST EFI_PEI_SERVICES **) &Private->Ps, &gEfiPeiCoreFvLocationPpiGuid, 0, NULL, (VOID **) &PeiCoreFvLocationPpi); + Status = PeiLocatePpi ((CONST EFI_PEI_SERVICES **)&Private->Ps, &gEfiPeiCoreFvLocationPpiGuid, 0, NULL, (VOID **)&PeiCoreFvLocationPpi); if (!EFI_ERROR (Status) && (PeiCoreFvLocationPpi->PeiCoreFvLocation != NULL)) { - PeiCoreFvHandle.FvHandle = (EFI_PEI_FV_HANDLE) PeiCoreFvLocationPpi->PeiCoreFvLocation; + PeiCoreFvHandle.FvHandle = (EFI_PEI_FV_HANDLE)PeiCoreFvLocationPpi->PeiCoreFvLocation; } else { - PeiCoreFvHandle.FvHandle = (EFI_PEI_FV_HANDLE) SecCoreData->BootFirmwareVolumeBase; + PeiCoreFvHandle.FvHandle = (EFI_PEI_FV_HANDLE)SecCoreData->BootFirmwareVolumeBase; } + for (FvIndex = 0; FvIndex < Private->FvCount; FvIndex++) { if (Private->Fv[FvIndex].FvHandle == PeiCoreFvHandle.FvHandle) { CopyMem (&PeiCoreFvHandle, &Private->Fv[FvIndex], sizeof (PEI_CORE_FV_HANDLE)); break; } } + Status = EFI_SUCCESS; ConvertPeiCorePpiPointers (Private, &PeiCoreFvHandle); @@ -1174,19 +1216,20 @@ EvacuateTempRam ( ASSERT (FvHeader != NULL); ASSERT (FvIndex < Private->FvCount); - DEBUG ((DEBUG_VERBOSE, "FV[%02d] at 0x%x.\n", FvIndex, (UINTN) FvHeader)); + DEBUG ((DEBUG_VERBOSE, "FV[%02d] at 0x%x.\n", FvIndex, (UINTN)FvHeader)); if ( - !( - ((EFI_PHYSICAL_ADDRESS)(UINTN) FvHeader >= Private->PhysicalMemoryBegin) && - (((EFI_PHYSICAL_ADDRESS)(UINTN) FvHeader + (FvHeader->FvLength - 1)) < Private->FreePhysicalMemoryTop) + !( + ((EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader >= Private->PhysicalMemoryBegin) && + (((EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader + (FvHeader->FvLength - 1)) < Private->FreePhysicalMemoryTop) + ) ) - ) { + { // // Allocate page to save the rebased PEIMs, the PEIMs will get dispatched later. // Status = PeiServicesAllocatePages ( EfiBootServicesCode, - EFI_SIZE_TO_PAGES ((UINTN) FvHeader->FvLength), + EFI_SIZE_TO_PAGES ((UINTN)FvHeader->FvLength), &FvHeaderAddress ); ASSERT_EFI_ERROR (Status); @@ -1198,7 +1241,7 @@ EvacuateTempRam ( // Status = PeiServicesAllocatePages ( EfiBootServicesCode, - EFI_SIZE_TO_PAGES ((UINTN) FvHeader->FvLength), + EFI_SIZE_TO_PAGES ((UINTN)FvHeader->FvLength), &FvHeaderAddress ); ASSERT_EFI_ERROR (Status); @@ -1208,8 +1251,8 @@ EvacuateTempRam ( DEBUG_VERBOSE, " Migrating FV[%d] from 0x%08X to 0x%08X\n", FvIndex, - (UINTN) FvHeader, - (UINTN) MigratedFvHeader + (UINTN)FvHeader, + (UINTN)MigratedFvHeader )); // @@ -1218,12 +1261,12 @@ EvacuateTempRam ( // PcdMigrateTemporaryRamFirmwareVolumes is FALSE, because the PCD control the // feature. // - CopyMem (MigratedFvHeader, FvHeader, (UINTN) FvHeader->FvLength); - CopyMem (RawDataFvHeader, MigratedFvHeader, (UINTN) FvHeader->FvLength); - MigratedFvInfo.FvOrgBase = (UINT32) (UINTN) FvHeader; - MigratedFvInfo.FvNewBase = (UINT32) (UINTN) MigratedFvHeader; - MigratedFvInfo.FvDataBase = (UINT32) (UINTN) RawDataFvHeader; - MigratedFvInfo.FvLength = (UINT32) (UINTN) FvHeader->FvLength; + CopyMem (MigratedFvHeader, FvHeader, (UINTN)FvHeader->FvLength); + CopyMem (RawDataFvHeader, MigratedFvHeader, (UINTN)FvHeader->FvLength); + MigratedFvInfo.FvOrgBase = (UINT32)(UINTN)FvHeader; + MigratedFvInfo.FvNewBase = (UINT32)(UINTN)MigratedFvHeader; + MigratedFvInfo.FvDataBase = (UINT32)(UINTN)RawDataFvHeader; + MigratedFvInfo.FvLength = (UINT32)(UINTN)FvHeader->FvLength; BuildGuidDataHob (&gEdkiiMigratedFvInfoGuid, &MigratedFvInfo, sizeof (MigratedFvInfo)); // @@ -1232,56 +1275,58 @@ EvacuateTempRam ( for (FvChildIndex = FvIndex; FvChildIndex < Private->FvCount; FvChildIndex++) { ChildFvHeader = Private->Fv[FvChildIndex].FvHeader; if ( - ((UINTN) ChildFvHeader > (UINTN) FvHeader) && - (((UINTN) ChildFvHeader + ChildFvHeader->FvLength) < ((UINTN) FvHeader) + FvHeader->FvLength) - ) { + ((UINTN)ChildFvHeader > (UINTN)FvHeader) && + (((UINTN)ChildFvHeader + ChildFvHeader->FvLength) < ((UINTN)FvHeader) + FvHeader->FvLength) + ) + { DEBUG ((DEBUG_VERBOSE, " Child FV[%02d] is being migrated.\n", FvChildIndex)); - ChildFvOffset = (UINTN) ChildFvHeader - (UINTN) FvHeader; + ChildFvOffset = (UINTN)ChildFvHeader - (UINTN)FvHeader; DEBUG ((DEBUG_VERBOSE, " Child FV offset = 0x%x.\n", ChildFvOffset)); - MigratedChildFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) MigratedFvHeader + ChildFvOffset); + MigratedChildFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)((UINTN)MigratedFvHeader + ChildFvOffset); Private->Fv[FvChildIndex].FvHeader = MigratedChildFvHeader; - Private->Fv[FvChildIndex].FvHandle = (EFI_PEI_FV_HANDLE) MigratedChildFvHeader; - DEBUG ((DEBUG_VERBOSE, " Child migrated FV header at 0x%x.\n", (UINTN) MigratedChildFvHeader)); + Private->Fv[FvChildIndex].FvHandle = (EFI_PEI_FV_HANDLE)MigratedChildFvHeader; + DEBUG ((DEBUG_VERBOSE, " Child migrated FV header at 0x%x.\n", (UINTN)MigratedChildFvHeader)); - Status = MigratePeimsInFv (Private, FvChildIndex, (UINTN) ChildFvHeader, (UINTN) MigratedChildFvHeader); + Status = MigratePeimsInFv (Private, FvChildIndex, (UINTN)ChildFvHeader, (UINTN)MigratedChildFvHeader); ASSERT_EFI_ERROR (Status); ConvertPpiPointersFv ( Private, - (UINTN) ChildFvHeader, - (UINTN) MigratedChildFvHeader, - (UINTN) ChildFvHeader->FvLength - 1 + (UINTN)ChildFvHeader, + (UINTN)MigratedChildFvHeader, + (UINTN)ChildFvHeader->FvLength - 1 ); ConvertStatusCodeCallbacks ( - (UINTN) ChildFvHeader, - (UINTN) MigratedChildFvHeader, - (UINTN) ChildFvHeader->FvLength - 1 + (UINTN)ChildFvHeader, + (UINTN)MigratedChildFvHeader, + (UINTN)ChildFvHeader->FvLength - 1 ); - ConvertFvHob (Private, (UINTN) ChildFvHeader, (UINTN) MigratedChildFvHeader); + ConvertFvHob (Private, (UINTN)ChildFvHeader, (UINTN)MigratedChildFvHeader); } } + Private->Fv[FvIndex].FvHeader = MigratedFvHeader; - Private->Fv[FvIndex].FvHandle = (EFI_PEI_FV_HANDLE) MigratedFvHeader; + Private->Fv[FvIndex].FvHandle = (EFI_PEI_FV_HANDLE)MigratedFvHeader; - Status = MigratePeimsInFv (Private, FvIndex, (UINTN) FvHeader, (UINTN) MigratedFvHeader); + Status = MigratePeimsInFv (Private, FvIndex, (UINTN)FvHeader, (UINTN)MigratedFvHeader); ASSERT_EFI_ERROR (Status); ConvertPpiPointersFv ( Private, - (UINTN) FvHeader, - (UINTN) MigratedFvHeader, - (UINTN) FvHeader->FvLength - 1 + (UINTN)FvHeader, + (UINTN)MigratedFvHeader, + (UINTN)FvHeader->FvLength - 1 ); ConvertStatusCodeCallbacks ( - (UINTN) FvHeader, - (UINTN) MigratedFvHeader, - (UINTN) FvHeader->FvLength - 1 + (UINTN)FvHeader, + (UINTN)MigratedFvHeader, + (UINTN)FvHeader->FvLength - 1 ); - ConvertFvHob (Private, (UINTN) FvHeader, (UINTN) MigratedFvHeader); + ConvertFvHob (Private, (UINTN)FvHeader, (UINTN)MigratedFvHeader); } } @@ -1305,23 +1350,23 @@ PeiDispatcher ( IN PEI_CORE_INSTANCE *Private ) { - EFI_STATUS Status; - UINT32 Index1; - UINT32 Index2; - CONST EFI_PEI_SERVICES **PeiServices; - EFI_PEI_FILE_HANDLE PeimFileHandle; - UINTN FvCount; - UINTN PeimCount; - UINT32 AuthenticationState; - EFI_PHYSICAL_ADDRESS EntryPoint; - EFI_PEIM_ENTRY_POINT2 PeimEntryPoint; - UINTN SaveCurrentPeimCount; - UINTN SaveCurrentFvCount; - EFI_PEI_FILE_HANDLE SaveCurrentFileHandle; - EFI_FV_FILE_INFO FvFileInfo; - PEI_CORE_FV_HANDLE *CoreFvHandle; - - PeiServices = (CONST EFI_PEI_SERVICES **) &Private->Ps; + EFI_STATUS Status; + UINT32 Index1; + UINT32 Index2; + CONST EFI_PEI_SERVICES **PeiServices; + EFI_PEI_FILE_HANDLE PeimFileHandle; + UINTN FvCount; + UINTN PeimCount; + UINT32 AuthenticationState; + EFI_PHYSICAL_ADDRESS EntryPoint; + EFI_PEIM_ENTRY_POINT2 PeimEntryPoint; + UINTN SaveCurrentPeimCount; + UINTN SaveCurrentFvCount; + EFI_PEI_FILE_HANDLE SaveCurrentFileHandle; + EFI_FV_FILE_INFO FvFileInfo; + PEI_CORE_FV_HANDLE *CoreFvHandle; + + PeiServices = (CONST EFI_PEI_SERVICES **)&Private->Ps; PeimEntryPoint = NULL; PeimFileHandle = NULL; EntryPoint = 0; @@ -1330,7 +1375,8 @@ PeiDispatcher ( (PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME) || PcdGetBool (PcdShadowPeimOnS3Boot)) - ) { + ) + { // // Once real memory is available, shadow the RegisterForShadow modules. And meanwhile // update the modules' status from PEIM_STATE_REGISTER_FOR_SHADOW to PEIM_STATE_DONE. @@ -1342,17 +1388,17 @@ PeiDispatcher ( for (Index1 = 0; Index1 < Private->FvCount; Index1++) { for (Index2 = 0; Index2 < Private->Fv[Index1].PeimCount; Index2++) { if (Private->Fv[Index1].PeimState[Index2] == PEIM_STATE_REGISTER_FOR_SHADOW) { - PeimFileHandle = Private->Fv[Index1].FvFileHandles[Index2]; - Private->CurrentFileHandle = PeimFileHandle; - Private->CurrentPeimFvCount = Index1; - Private->CurrentPeimCount = Index2; - Status = PeiLoadImage ( - (CONST EFI_PEI_SERVICES **) &Private->Ps, - PeimFileHandle, - PEIM_STATE_REGISTER_FOR_SHADOW, - &EntryPoint, - &AuthenticationState - ); + PeimFileHandle = Private->Fv[Index1].FvFileHandles[Index2]; + Private->CurrentFileHandle = PeimFileHandle; + Private->CurrentPeimFvCount = Index1; + Private->CurrentPeimCount = Index2; + Status = PeiLoadImage ( + (CONST EFI_PEI_SERVICES **)&Private->Ps, + PeimFileHandle, + PEIM_STATE_REGISTER_FOR_SHADOW, + &EntryPoint, + &AuthenticationState + ); if (Status == EFI_SUCCESS) { // // PEIM_STATE_REGISTER_FOR_SHADOW move to PEIM_STATE_DONE @@ -1364,7 +1410,7 @@ PeiDispatcher ( PeimEntryPoint = (EFI_PEIM_ENTRY_POINT2)(UINTN)EntryPoint; PERF_START_IMAGE_BEGIN (PeimFileHandle); - PeimEntryPoint(PeimFileHandle, (const EFI_PEI_SERVICES **) &Private->Ps); + PeimEntryPoint (PeimFileHandle, (const EFI_PEI_SERVICES **)&Private->Ps); PERF_START_IMAGE_END (PeimFileHandle); } @@ -1376,6 +1422,7 @@ PeiDispatcher ( } } } + Private->CurrentFileHandle = SaveCurrentFileHandle; Private->CurrentPeimFvCount = SaveCurrentFvCount; Private->CurrentPeimCount = SaveCurrentPeimCount; @@ -1394,10 +1441,10 @@ PeiDispatcher ( // In case that reenter PeiCore happens, the last pass record is still available. // if (!Private->PeimDispatcherReenter) { - Private->PeimNeedingDispatch = FALSE; - Private->PeimDispatchOnThisPass = FALSE; + Private->PeimNeedingDispatch = FALSE; + Private->PeimDispatchOnThisPass = FALSE; } else { - Private->PeimDispatcherReenter = FALSE; + Private->PeimDispatcherReenter = FALSE; } for (FvCount = Private->CurrentPeimFvCount; FvCount < Private->FvCount; FvCount++) { @@ -1427,9 +1474,10 @@ PeiDispatcher ( // for (PeimCount = Private->CurrentPeimCount; PeimCount < Private->Fv[FvCount].PeimCount; - PeimCount++) { - Private->CurrentPeimCount = PeimCount; - PeimFileHandle = Private->CurrentFileHandle = Private->CurrentFvFileHandles[PeimCount]; + PeimCount++) + { + Private->CurrentPeimCount = PeimCount; + PeimFileHandle = Private->CurrentFileHandle = Private->CurrentFvFileHandles[PeimCount]; if (Private->Fv[FvCount].PeimState[PeimCount] == PEIM_STATE_NOT_DISPATCHED) { if (!DepexSatisfied (Private, PeimFileHandle, PeimCount)) { @@ -1491,7 +1539,7 @@ PeiDispatcher ( // Call the PEIM entry point for PEIM driver // PeimEntryPoint = (EFI_PEIM_ENTRY_POINT2)(UINTN)EntryPoint; - PeimEntryPoint (PeimFileHandle, (const EFI_PEI_SERVICES **) PeiServices); + PeimEntryPoint (PeimFileHandle, (const EFI_PEI_SERVICES **)PeiServices); Private->PeimDispatchOnThisPass = TRUE; } else { // @@ -1509,7 +1557,6 @@ PeiDispatcher ( sizeof (PeimFileHandle) ); PERF_START_IMAGE_END (PeimFileHandle); - } } @@ -1532,14 +1579,16 @@ PeiDispatcher ( (PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME) || PcdGetBool (PcdShadowPeimOnS3Boot)) - ) { + ) + { // // If memory is available we shadow images by default for performance reasons. // We call the entry point a 2nd time so the module knows it's shadowed. // - //PERF_START (PeiServices, L"PEIM", PeimFileHandle, 0); + // PERF_START (PeiServices, L"PEIM", PeimFileHandle, 0); if ((Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME) && !PcdGetBool (PcdShadowPeimOnBoot) && - !PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes)) { + !PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes)) + { // // Load PEIM into Memory for Register for shadow PEIM. // @@ -1554,9 +1603,10 @@ PeiDispatcher ( PeimEntryPoint = (EFI_PEIM_ENTRY_POINT2)(UINTN)EntryPoint; } } + ASSERT (PeimEntryPoint != NULL); - PeimEntryPoint (PeimFileHandle, (const EFI_PEI_SERVICES **) PeiServices); - //PERF_END (PeiServices, L"PEIM", PeimFileHandle, 0); + PeimEntryPoint (PeimFileHandle, (const EFI_PEI_SERVICES **)PeiServices); + // PERF_END (PeiServices, L"PEIM", PeimFileHandle, 0); // // PEIM_STATE_REGISTER_FOR_SHADOW move to PEIM_STATE_DONE @@ -1577,8 +1627,8 @@ PeiDispatcher ( // Before walking through the next FV, we should set them to NULL/0 to // start at the beginning of the next FV. // - Private->CurrentFileHandle = NULL; - Private->CurrentPeimCount = 0; + Private->CurrentFileHandle = NULL; + Private->CurrentPeimCount = 0; Private->CurrentFvFileHandles = NULL; } @@ -1597,7 +1647,6 @@ PeiDispatcher ( // as it will fail the next time too (nothing has changed). // } while (Private->PeimNeedingDispatch && Private->PeimDispatchOnThisPass); - } /** @@ -1615,9 +1664,9 @@ PeiDispatcher ( **/ VOID InitializeDispatcherData ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_INSTANCE *OldCoreData, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_INSTANCE *OldCoreData, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ) { if (OldCoreData == NULL) { @@ -1645,14 +1694,14 @@ InitializeDispatcherData ( **/ BOOLEAN DepexSatisfied ( - IN PEI_CORE_INSTANCE *Private, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINTN PeimCount + IN PEI_CORE_INSTANCE *Private, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINTN PeimCount ) { - EFI_STATUS Status; - VOID *DepexData; - EFI_FV_FILE_INFO FileInfo; + EFI_STATUS Status; + VOID *DepexData; + EFI_FV_FILE_INFO FileInfo; Status = PeiServicesFfsGetFileInfo (FileHandle, &FileInfo); if (EFI_ERROR (Status)) { @@ -1673,10 +1722,10 @@ DepexSatisfied ( // Depex section not in the encapsulated section. // Status = PeiServicesFfsFindSectionData ( - EFI_SECTION_PEI_DEPEX, - FileHandle, - (VOID **)&DepexData - ); + EFI_SECTION_PEI_DEPEX, + FileHandle, + (VOID **)&DepexData + ); if (EFI_ERROR (Status)) { // @@ -1706,10 +1755,11 @@ DepexSatisfied ( EFI_STATUS EFIAPI PeiRegisterForShadow ( - IN EFI_PEI_FILE_HANDLE FileHandle + IN EFI_PEI_FILE_HANDLE FileHandle ) { - PEI_CORE_INSTANCE *Private; + PEI_CORE_INSTANCE *Private; + Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ()); if (Private->CurrentFileHandle != FileHandle) { diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.c b/MdeModulePkg/Core/Pei/FwVol/FwVol.c index 8f9a41d21b..60bbe57332 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.c +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.c @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "FwVol.h" -EFI_PEI_NOTIFY_DESCRIPTOR mNotifyOnFvInfoList[] = { +EFI_PEI_NOTIFY_DESCRIPTOR mNotifyOnFvInfoList[] = { { EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK, &gEfiPeiFirmwareVolumeInfoPpiGuid, @@ -22,7 +22,7 @@ EFI_PEI_NOTIFY_DESCRIPTOR mNotifyOnFvInfoList[] = { } }; -PEI_FW_VOL_INSTANCE mPeiFfs2FwVol = { +PEI_FW_VOL_INSTANCE mPeiFfs2FwVol = { PEI_FW_VOL_SIGNATURE, FALSE, { @@ -39,7 +39,7 @@ PEI_FW_VOL_INSTANCE mPeiFfs2FwVol = { } }; -PEI_FW_VOL_INSTANCE mPeiFfs3FwVol = { +PEI_FW_VOL_INSTANCE mPeiFfs3FwVol = { PEI_FW_VOL_SIGNATURE, TRUE, { @@ -88,8 +88,8 @@ Required Alignment Alignment Value in FFS FFS_ATTRIB_DATA_ALIGNMENT2 Align 8 MB 6 1 23 16 MB 7 1 24 **/ -UINT8 mFvAttributes[] = {0, 4, 7, 9, 10, 12, 15, 16}; -UINT8 mFvAttributes2[] = {17, 18, 19, 20, 21, 22, 23, 24}; +UINT8 mFvAttributes[] = { 0, 4, 7, 9, 10, 12, 15, 16 }; +UINT8 mFvAttributes2[] = { 17, 18, 19, 20, 21, 22, 23, 24 }; /** Convert the FFS File Attributes to FV File Attributes @@ -101,19 +101,19 @@ UINT8 mFvAttributes2[] = {17, 18, 19, 20, 21, 22, 23, 24}; **/ EFI_FV_FILE_ATTRIBUTES FfsAttributes2FvFileAttributes ( - IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes + IN EFI_FFS_FILE_ATTRIBUTES FfsAttributes ) { - UINT8 DataAlignment; - EFI_FV_FILE_ATTRIBUTES FileAttribute; + UINT8 DataAlignment; + EFI_FV_FILE_ATTRIBUTES FileAttribute; - DataAlignment = (UINT8) ((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3); + DataAlignment = (UINT8)((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT) >> 3); ASSERT (DataAlignment < 8); if ((FfsAttributes & FFS_ATTRIB_DATA_ALIGNMENT_2) != 0) { - FileAttribute = (EFI_FV_FILE_ATTRIBUTES) mFvAttributes2[DataAlignment]; + FileAttribute = (EFI_FV_FILE_ATTRIBUTES)mFvAttributes2[DataAlignment]; } else { - FileAttribute = (EFI_FV_FILE_ATTRIBUTES) mFvAttributes[DataAlignment]; + FileAttribute = (EFI_FV_FILE_ATTRIBUTES)mFvAttributes[DataAlignment]; } if ((FfsAttributes & FFS_ATTRIB_FIXED) == FFS_ATTRIB_FIXED) { @@ -134,7 +134,7 @@ FfsAttributes2FvFileAttributes ( in the header State field. **/ EFI_FFS_FILE_STATE -GetFileState( +GetFileState ( IN UINT8 ErasePolarity, IN EFI_FFS_FILE_HEADER *FfsHeader ) @@ -145,7 +145,7 @@ GetFileState( FileState = FfsHeader->State; if (ErasePolarity != 0) { - FileState = (EFI_FFS_FILE_STATE)~FileState; + FileState = (EFI_FFS_FILE_STATE) ~FileState; } // @@ -173,26 +173,26 @@ CalculateHeaderChecksum ( IN EFI_FFS_FILE_HEADER *FileHeader ) { - EFI_FFS_FILE_HEADER2 TestFileHeader; + EFI_FFS_FILE_HEADER2 TestFileHeader; if (IS_FFS_FILE2 (FileHeader)) { CopyMem (&TestFileHeader, FileHeader, sizeof (EFI_FFS_FILE_HEADER2)); // // Ignore State and File field in FFS header. // - TestFileHeader.State = 0; + TestFileHeader.State = 0; TestFileHeader.IntegrityCheck.Checksum.File = 0; - return CalculateSum8 ((CONST UINT8 *) &TestFileHeader, sizeof (EFI_FFS_FILE_HEADER2)); + return CalculateSum8 ((CONST UINT8 *)&TestFileHeader, sizeof (EFI_FFS_FILE_HEADER2)); } else { CopyMem (&TestFileHeader, FileHeader, sizeof (EFI_FFS_FILE_HEADER)); // // Ignore State and File field in FFS header. // - TestFileHeader.State = 0; + TestFileHeader.State = 0; TestFileHeader.IntegrityCheck.Checksum.File = 0; - return CalculateSum8 ((CONST UINT8 *) &TestFileHeader, sizeof (EFI_FFS_FILE_HEADER)); + return CalculateSum8 ((CONST UINT8 *)&TestFileHeader, sizeof (EFI_FFS_FILE_HEADER)); } } @@ -203,9 +203,9 @@ CalculateHeaderChecksum ( @return Pointer to instance of PEI_CORE_FV_HANDLE. **/ -PEI_CORE_FV_HANDLE* +PEI_CORE_FV_HANDLE * FileHandleToVolume ( - IN EFI_PEI_FILE_HANDLE FileHandle + IN EFI_PEI_FILE_HANDLE FileHandle ) { UINTN Index; @@ -223,12 +223,13 @@ FileHandleToVolume ( // for (Index = 0; Index < PrivateData->FvCount; Index++) { FwVolHeader = PrivateData->Fv[Index].FvHeader; - if (((UINT64) (UINTN) FileHandle > (UINT64) (UINTN) FwVolHeader ) && \ - ((UINT64) (UINTN) FileHandle <= ((UINT64) (UINTN) FwVolHeader + FwVolHeader->FvLength - 1))) { + if (((UINT64)(UINTN)FileHandle > (UINT64)(UINTN)FwVolHeader) && \ + ((UINT64)(UINTN)FileHandle <= ((UINT64)(UINTN)FwVolHeader + FwVolHeader->FvLength - 1))) + { if (BestIndex == PrivateData->FvCount) { BestIndex = Index; } else { - if ((UINT64) (UINTN) PrivateData->Fv[BestIndex].FvHeader < (UINT64) (UINTN) FwVolHeader) { + if ((UINT64)(UINTN)PrivateData->Fv[BestIndex].FvHeader < (UINT64)(UINTN)FwVolHeader) { BestIndex = Index; } } @@ -263,30 +264,30 @@ FileHandleToVolume ( **/ EFI_STATUS FindFileEx ( - IN CONST EFI_PEI_FV_HANDLE FvHandle, - IN CONST EFI_GUID *FileName OPTIONAL, - IN EFI_FV_FILETYPE SearchType, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle, - IN OUT EFI_PEI_FILE_HANDLE *AprioriFile OPTIONAL + IN CONST EFI_PEI_FV_HANDLE FvHandle, + IN CONST EFI_GUID *FileName OPTIONAL, + IN EFI_FV_FILETYPE SearchType, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle, + IN OUT EFI_PEI_FILE_HANDLE *AprioriFile OPTIONAL ) { - EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; - EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader; - EFI_FFS_FILE_HEADER **FileHeader; - EFI_FFS_FILE_HEADER *FfsFileHeader; - UINT32 FileLength; - UINT32 FileOccupiedSize; - UINT32 FileOffset; - UINT64 FvLength; - UINT8 ErasePolarity; - UINT8 FileState; - UINT8 DataCheckSum; - BOOLEAN IsFfs3Fv; + EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExtHeader; + EFI_FFS_FILE_HEADER **FileHeader; + EFI_FFS_FILE_HEADER *FfsFileHeader; + UINT32 FileLength; + UINT32 FileOccupiedSize; + UINT32 FileOffset; + UINT64 FvLength; + UINT8 ErasePolarity; + UINT8 FileState; + UINT8 DataCheckSum; + BOOLEAN IsFfs3Fv; // // Convert the handle of FV to FV header for memory-mapped firmware volume // - FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) FvHandle; + FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)FvHandle; FileHeader = (EFI_FFS_FILE_HEADER **)FileHandle; IsFfs3Fv = CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem3Guid); @@ -308,30 +309,33 @@ FindFileEx ( // // Searching for files starts on an 8 byte aligned boundary after the end of the Extended Header if it exists. // - FwVolExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) ((UINT8 *) FwVolHeader + FwVolHeader->ExtHeaderOffset); - FfsFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FwVolExtHeader + FwVolExtHeader->ExtHeaderSize); + FwVolExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)((UINT8 *)FwVolHeader + FwVolHeader->ExtHeaderOffset); + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FwVolExtHeader + FwVolExtHeader->ExtHeaderSize); } else { - FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *) FwVolHeader + FwVolHeader->HeaderLength); + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FwVolHeader + FwVolHeader->HeaderLength); } - FfsFileHeader = (EFI_FFS_FILE_HEADER *) ALIGN_POINTER (FfsFileHeader, 8); + + FfsFileHeader = (EFI_FFS_FILE_HEADER *)ALIGN_POINTER (FfsFileHeader, 8); } else { if (IS_FFS_FILE2 (*FileHeader)) { if (!IsFfs3Fv) { DEBUG ((DEBUG_ERROR, "It is a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &(*FileHeader)->Name)); } + FileLength = FFS_FILE2_SIZE (*FileHeader); ASSERT (FileLength > 0x00FFFFFF); } else { FileLength = FFS_FILE_SIZE (*FileHeader); } + // // FileLength is adjusted to FileOccupiedSize as it is 8 byte aligned. // FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); - FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)*FileHeader + FileOccupiedSize); + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)*FileHeader + FileOccupiedSize); } - FileOffset = (UINT32) ((UINT8 *)FfsFileHeader - (UINT8 *)FwVolHeader); + FileOffset = (UINT32)((UINT8 *)FfsFileHeader - (UINT8 *)FwVolHeader); ASSERT (FileOffset <= 0xFFFFFFFF); while (FileOffset < (FvLength - sizeof (EFI_FFS_FILE_HEADER))) { @@ -340,105 +344,110 @@ FindFileEx ( // FileState = GetFileState (ErasePolarity, FfsFileHeader); switch (FileState) { + case EFI_FILE_HEADER_CONSTRUCTION: + case EFI_FILE_HEADER_INVALID: + if (IS_FFS_FILE2 (FfsFileHeader)) { + if (!IsFfs3Fv) { + DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); + } - case EFI_FILE_HEADER_CONSTRUCTION: - case EFI_FILE_HEADER_INVALID: - if (IS_FFS_FILE2 (FfsFileHeader)) { - if (!IsFfs3Fv) { - DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); + FileOffset += sizeof (EFI_FFS_FILE_HEADER2); + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2)); + } else { + FileOffset += sizeof (EFI_FFS_FILE_HEADER); + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER)); } - FileOffset += sizeof (EFI_FFS_FILE_HEADER2); - FfsFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2)); - } else { - FileOffset += sizeof (EFI_FFS_FILE_HEADER); - FfsFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER)); - } - break; - case EFI_FILE_DATA_VALID: - case EFI_FILE_MARKED_FOR_UPDATE: - if (CalculateHeaderChecksum (FfsFileHeader) != 0) { - ASSERT (FALSE); - *FileHeader = NULL; - return EFI_NOT_FOUND; - } + break; - if (IS_FFS_FILE2 (FfsFileHeader)) { - FileLength = FFS_FILE2_SIZE (FfsFileHeader); - ASSERT (FileLength > 0x00FFFFFF); - FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); - if (!IsFfs3Fv) { - DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); - FileOffset += FileOccupiedSize; - FfsFileHeader = (EFI_FFS_FILE_HEADER *) ((UINT8 *) FfsFileHeader + FileOccupiedSize); - break; + case EFI_FILE_DATA_VALID: + case EFI_FILE_MARKED_FOR_UPDATE: + if (CalculateHeaderChecksum (FfsFileHeader) != 0) { + ASSERT (FALSE); + *FileHeader = NULL; + return EFI_NOT_FOUND; } - } else { - FileLength = FFS_FILE_SIZE (FfsFileHeader); - FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); - } - DataCheckSum = FFS_FIXED_CHECKSUM; - if ((FfsFileHeader->Attributes & FFS_ATTRIB_CHECKSUM) == FFS_ATTRIB_CHECKSUM) { if (IS_FFS_FILE2 (FfsFileHeader)) { - DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2), FileLength - sizeof(EFI_FFS_FILE_HEADER2)); + FileLength = FFS_FILE2_SIZE (FfsFileHeader); + ASSERT (FileLength > 0x00FFFFFF); + FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); + if (!IsFfs3Fv) { + DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); + FileOffset += FileOccupiedSize; + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize); + break; + } } else { - DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER), FileLength - sizeof(EFI_FFS_FILE_HEADER)); + FileLength = FFS_FILE_SIZE (FfsFileHeader); + FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); } - } - if (FfsFileHeader->IntegrityCheck.Checksum.File != DataCheckSum) { - ASSERT (FALSE); - *FileHeader = NULL; - return EFI_NOT_FOUND; - } - if (FileName != NULL) { - if (CompareGuid (&FfsFileHeader->Name, (EFI_GUID*)FileName)) { - *FileHeader = FfsFileHeader; - return EFI_SUCCESS; + DataCheckSum = FFS_FIXED_CHECKSUM; + if ((FfsFileHeader->Attributes & FFS_ATTRIB_CHECKSUM) == FFS_ATTRIB_CHECKSUM) { + if (IS_FFS_FILE2 (FfsFileHeader)) { + DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2), FileLength - sizeof (EFI_FFS_FILE_HEADER2)); + } else { + DataCheckSum = CalculateCheckSum8 ((CONST UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER), FileLength - sizeof (EFI_FFS_FILE_HEADER)); + } } - } else if (SearchType == PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE) { - if ((FfsFileHeader->Type == EFI_FV_FILETYPE_PEIM) || - (FfsFileHeader->Type == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER) || - (FfsFileHeader->Type == EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE)) { - *FileHeader = FfsFileHeader; - return EFI_SUCCESS; - } else if (AprioriFile != NULL) { - if (FfsFileHeader->Type == EFI_FV_FILETYPE_FREEFORM) { - if (CompareGuid (&FfsFileHeader->Name, &gPeiAprioriFileNameGuid)) { - *AprioriFile = (EFI_PEI_FILE_HANDLE)FfsFileHeader; + if (FfsFileHeader->IntegrityCheck.Checksum.File != DataCheckSum) { + ASSERT (FALSE); + *FileHeader = NULL; + return EFI_NOT_FOUND; + } + + if (FileName != NULL) { + if (CompareGuid (&FfsFileHeader->Name, (EFI_GUID *)FileName)) { + *FileHeader = FfsFileHeader; + return EFI_SUCCESS; + } + } else if (SearchType == PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE) { + if ((FfsFileHeader->Type == EFI_FV_FILETYPE_PEIM) || + (FfsFileHeader->Type == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER) || + (FfsFileHeader->Type == EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE)) + { + *FileHeader = FfsFileHeader; + return EFI_SUCCESS; + } else if (AprioriFile != NULL) { + if (FfsFileHeader->Type == EFI_FV_FILETYPE_FREEFORM) { + if (CompareGuid (&FfsFileHeader->Name, &gPeiAprioriFileNameGuid)) { + *AprioriFile = (EFI_PEI_FILE_HANDLE)FfsFileHeader; + } } } + } else if (((SearchType == FfsFileHeader->Type) || (SearchType == EFI_FV_FILETYPE_ALL)) && + (FfsFileHeader->Type != EFI_FV_FILETYPE_FFS_PAD)) + { + *FileHeader = FfsFileHeader; + return EFI_SUCCESS; } - } else if (((SearchType == FfsFileHeader->Type) || (SearchType == EFI_FV_FILETYPE_ALL)) && - (FfsFileHeader->Type != EFI_FV_FILETYPE_FFS_PAD)) { - *FileHeader = FfsFileHeader; - return EFI_SUCCESS; - } - FileOffset += FileOccupiedSize; - FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize); - break; + FileOffset += FileOccupiedSize; + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize); + break; - case EFI_FILE_DELETED: - if (IS_FFS_FILE2 (FfsFileHeader)) { - if (!IsFfs3Fv) { - DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); + case EFI_FILE_DELETED: + if (IS_FFS_FILE2 (FfsFileHeader)) { + if (!IsFfs3Fv) { + DEBUG ((DEBUG_ERROR, "Found a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); + } + + FileLength = FFS_FILE2_SIZE (FfsFileHeader); + ASSERT (FileLength > 0x00FFFFFF); + } else { + FileLength = FFS_FILE_SIZE (FfsFileHeader); } - FileLength = FFS_FILE2_SIZE (FfsFileHeader); - ASSERT (FileLength > 0x00FFFFFF); - } else { - FileLength = FFS_FILE_SIZE (FfsFileHeader); - } - FileOccupiedSize = GET_OCCUPIED_SIZE(FileLength, 8); - FileOffset += FileOccupiedSize; - FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize); - break; - default: - *FileHeader = NULL; - return EFI_NOT_FOUND; + FileOccupiedSize = GET_OCCUPIED_SIZE (FileLength, 8); + FileOffset += FileOccupiedSize; + FfsFileHeader = (EFI_FFS_FILE_HEADER *)((UINT8 *)FfsFileHeader + FileOccupiedSize); + break; + + default: + *FileHeader = NULL; + return EFI_NOT_FOUND; } } @@ -454,14 +463,14 @@ FindFileEx ( **/ VOID PeiInitializeFv ( - IN PEI_CORE_INSTANCE *PrivateData, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ) { - EFI_STATUS Status; - EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; - EFI_PEI_FV_HANDLE FvHandle; - EFI_FIRMWARE_VOLUME_HEADER *BfvHeader; + EFI_STATUS Status; + EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; + EFI_PEI_FV_HANDLE FvHandle; + EFI_FIRMWARE_VOLUME_HEADER *BfvHeader; // // Install FV_PPI for FFS2 file system. @@ -482,7 +491,7 @@ PeiInitializeFv ( &BfvHeader->FileSystemGuid, 0, NULL, - (VOID**)&FvPpi + (VOID **)&FvPpi ); ASSERT_EFI_ERROR (Status); @@ -504,19 +513,19 @@ PeiInitializeFv ( // // Update internal PEI_CORE_FV array. // - PrivateData->Fv[PrivateData->FvCount].FvHeader = BfvHeader; - PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; - PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; + PrivateData->Fv[PrivateData->FvCount].FvHeader = BfvHeader; + PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; + PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; PrivateData->Fv[PrivateData->FvCount].AuthenticationStatus = 0; DEBUG (( DEBUG_INFO, "The %dth FV start address is 0x%11p, size is 0x%08x, handle is 0x%p\n", - (UINT32) PrivateData->FvCount, - (VOID *) BfvHeader, - (UINT32) BfvHeader->FvLength, + (UINT32)PrivateData->FvCount, + (VOID *)BfvHeader, + (UINT32)BfvHeader->FvLength, FvHandle )); - PrivateData->FvCount ++; + PrivateData->FvCount++; // // Post a call-back for the FvInfoPPI and FvInfo2PPI services to expose @@ -524,7 +533,6 @@ PeiInitializeFv ( // Status = PeiServicesNotifyPpi (mNotifyOnFvInfoList); ASSERT_EFI_ERROR (Status); - } /** @@ -543,25 +551,25 @@ PeiInitializeFv ( EFI_STATUS EFIAPI FirmwareVolumeInfoPpiNotifyCallback ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, - IN VOID *Ppi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi ) { - EFI_PEI_FIRMWARE_VOLUME_INFO2_PPI FvInfo2Ppi; - EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; - PEI_CORE_INSTANCE *PrivateData; - EFI_STATUS Status; - EFI_PEI_FV_HANDLE FvHandle; - UINTN FvIndex; - EFI_PEI_FILE_HANDLE FileHandle; - VOID *DepexData; - BOOLEAN IsFvInfo2; - UINTN CurFvCount; - VOID *TempPtr; - - Status = EFI_SUCCESS; - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); + EFI_PEI_FIRMWARE_VOLUME_INFO2_PPI FvInfo2Ppi; + EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; + PEI_CORE_INSTANCE *PrivateData; + EFI_STATUS Status; + EFI_PEI_FV_HANDLE FvHandle; + UINTN FvIndex; + EFI_PEI_FILE_HANDLE FileHandle; + VOID *DepexData; + BOOLEAN IsFvInfo2; + UINTN CurFvCount; + VOID *TempPtr; + + Status = EFI_SUCCESS; + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); if (CompareGuid (NotifyDescriptor->Guid, &gEfiPeiFirmwareVolumeInfo2PpiGuid)) { // @@ -575,7 +583,7 @@ FirmwareVolumeInfoPpiNotifyCallback ( // CopyMem (&FvInfo2Ppi, Ppi, sizeof (EFI_PEI_FIRMWARE_VOLUME_INFO_PPI)); FvInfo2Ppi.AuthenticationStatus = 0; - IsFvInfo2 = FALSE; + IsFvInfo2 = FALSE; } if (CompareGuid (&FvInfo2Ppi.FvFormat, &gEfiFirmwareFileSystem2Guid)) { @@ -589,7 +597,7 @@ FirmwareVolumeInfoPpiNotifyCallback ( // ((EFI_FIRMWARE_VOLUME_HEADER *) FvInfo)->FileSystemGuid can be just used for both // firmware file system 2 and 3 format. // - ASSERT (CompareGuid (&(((EFI_FIRMWARE_VOLUME_HEADER *) FvInfo2Ppi.FvInfo)->FileSystemGuid), &gEfiFirmwareFileSystem2Guid)); + ASSERT (CompareGuid (&(((EFI_FIRMWARE_VOLUME_HEADER *)FvInfo2Ppi.FvInfo)->FileSystemGuid), &gEfiFirmwareFileSystem2Guid)); } // @@ -599,7 +607,7 @@ FirmwareVolumeInfoPpiNotifyCallback ( &FvInfo2Ppi.FvFormat, 0, NULL, - (VOID**)&FvPpi + (VOID **)&FvPpi ); if (!EFI_ERROR (Status)) { // @@ -614,12 +622,13 @@ FirmwareVolumeInfoPpiNotifyCallback ( // // Check whether the FV has already been processed. // - for (FvIndex = 0; FvIndex < PrivateData->FvCount; FvIndex ++) { + for (FvIndex = 0; FvIndex < PrivateData->FvCount; FvIndex++) { if (PrivateData->Fv[FvIndex].FvHandle == FvHandle) { if (IsFvInfo2 && (FvInfo2Ppi.AuthenticationStatus != PrivateData->Fv[FvIndex].AuthenticationStatus)) { PrivateData->Fv[FvIndex].AuthenticationStatus = FvInfo2Ppi.AuthenticationStatus; DEBUG ((DEBUG_INFO, "Update AuthenticationStatus of the %dth FV to 0x%x!\n", FvIndex, FvInfo2Ppi.AuthenticationStatus)); } + DEBUG ((DEBUG_INFO, "The FV %p has already been processed!\n", FvInfo2Ppi.FvInfo)); return EFI_SUCCESS; } @@ -638,27 +647,27 @@ FirmwareVolumeInfoPpiNotifyCallback ( PrivateData->Fv, sizeof (PEI_CORE_FV_HANDLE) * PrivateData->MaxFvCount ); - PrivateData->Fv = TempPtr; + PrivateData->Fv = TempPtr; PrivateData->MaxFvCount = PrivateData->MaxFvCount + FV_GROWTH_STEP; } // // Update internal PEI_CORE_FV array. // - PrivateData->Fv[PrivateData->FvCount].FvHeader = (EFI_FIRMWARE_VOLUME_HEADER*) FvInfo2Ppi.FvInfo; - PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; - PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; + PrivateData->Fv[PrivateData->FvCount].FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)FvInfo2Ppi.FvInfo; + PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; + PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; PrivateData->Fv[PrivateData->FvCount].AuthenticationStatus = FvInfo2Ppi.AuthenticationStatus; - CurFvCount = PrivateData->FvCount; + CurFvCount = PrivateData->FvCount; DEBUG (( DEBUG_INFO, "The %dth FV start address is 0x%11p, size is 0x%08x, handle is 0x%p\n", - (UINT32) CurFvCount, - (VOID *) FvInfo2Ppi.FvInfo, + (UINT32)CurFvCount, + (VOID *)FvInfo2Ppi.FvInfo, FvInfo2Ppi.FvInfoSize, FvHandle )); - PrivateData->FvCount ++; + PrivateData->FvCount++; // // Scan and process the new discovered FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE @@ -670,13 +679,13 @@ FirmwareVolumeInfoPpiNotifyCallback ( EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, FvHandle, &FileHandle - ); + ); if (!EFI_ERROR (Status)) { Status = FvPpi->FindSectionByType ( FvPpi, EFI_SECTION_PEI_DEPEX, FileHandle, - (VOID**)&DepexData + (VOID **)&DepexData ); if (!EFI_ERROR (Status)) { if (!PeimDispatchReadiness (PeiServices, DepexData)) { @@ -715,8 +724,8 @@ FirmwareVolumeInfoPpiNotifyCallback ( **/ BOOLEAN VerifyGuidedSectionGuid ( - IN EFI_GUID *GuidedSectionGuid, - OUT EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI **GuidedSectionExtraction + IN EFI_GUID *GuidedSectionGuid, + OUT EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI **GuidedSectionExtraction ) { EFI_PEI_HOB_POINTERS Hob; @@ -729,19 +738,20 @@ VerifyGuidedSectionGuid ( // Hob.Raw = GetFirstGuidHob (GuidedSectionGuid); if (Hob.Raw != NULL) { - GuidRecorded = (EFI_GUID *) GET_GUID_HOB_DATA (Hob); + GuidRecorded = (EFI_GUID *)GET_GUID_HOB_DATA (Hob); if (CompareGuid (GuidRecorded, GuidedSectionGuid)) { // // Found the recorded GuidedSectionGuid. // - Status = PeiServicesLocatePpi (GuidedSectionGuid, 0, NULL, (VOID **) &Interface); - if (!EFI_ERROR (Status) && Interface != NULL) { + Status = PeiServicesLocatePpi (GuidedSectionGuid, 0, NULL, (VOID **)&Interface); + if (!EFI_ERROR (Status) && (Interface != NULL)) { // // Found the supported Guided Section Extraction Ppi for the Guided Section. // - *GuidedSectionExtraction = (EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *) Interface; + *GuidedSectionExtraction = (EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *)Interface; return TRUE; } + return FALSE; } } @@ -780,21 +790,21 @@ ProcessSection ( IN BOOLEAN IsFfs3Fv ) { - EFI_STATUS Status; - UINT32 SectionLength; - UINT32 ParsedLength; - EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *GuidSectionPpi; - EFI_PEI_DECOMPRESS_PPI *DecompressPpi; - VOID *PpiOutput; - UINTN PpiOutputSize; - UINTN Index; - UINT32 Authentication; - PEI_CORE_INSTANCE *PrivateData; - EFI_GUID *SectionDefinitionGuid; - BOOLEAN SectionCached; - VOID *TempOutputBuffer; - UINT32 TempAuthenticationStatus; - UINT16 GuidedSectionAttributes; + EFI_STATUS Status; + UINT32 SectionLength; + UINT32 ParsedLength; + EFI_PEI_GUIDED_SECTION_EXTRACTION_PPI *GuidSectionPpi; + EFI_PEI_DECOMPRESS_PPI *DecompressPpi; + VOID *PpiOutput; + UINTN PpiOutputSize; + UINTN Index; + UINT32 Authentication; + PEI_CORE_INSTANCE *PrivateData; + EFI_GUID *SectionDefinitionGuid; + BOOLEAN SectionCached; + VOID *TempOutputBuffer; + UINT32 TempAuthenticationStatus; + UINT16 GuidedSectionAttributes; PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); *OutputBuffer = NULL; @@ -804,7 +814,6 @@ ProcessSection ( PpiOutput = NULL; PpiOutputSize = 0; while (ParsedLength < SectionSize) { - if (IS_SECTION2 (Section)) { ASSERT (SECTION2_SIZE (Section) > 0x00FFFFFF); if (!IsFfs3Fv) { @@ -817,7 +826,7 @@ ProcessSection ( SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4); ASSERT (SectionLength != 0); ParsedLength += SectionLength; - Section = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) Section + SectionLength); + Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength); continue; } } @@ -832,10 +841,11 @@ ProcessSection ( // Got it! // if (IS_SECTION2 (Section)) { - *OutputBuffer = (VOID *)((UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER2)); + *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER2)); } else { - *OutputBuffer = (VOID *)((UINT8 *) Section + sizeof (EFI_COMMON_SECTION_HEADER)); + *OutputBuffer = (VOID *)((UINT8 *)Section + sizeof (EFI_COMMON_SECTION_HEADER)); } + return EFI_SUCCESS; } else { if (IS_SECTION2 (Section)) { @@ -843,6 +853,7 @@ ProcessSection ( } else { SectionLength = SECTION_SIZE (Section); } + // // SectionLength is adjusted it is 4 byte aligned. // Go to the next section @@ -850,7 +861,7 @@ ProcessSection ( SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4); ASSERT (SectionLength != 0); ParsedLength += SectionLength; - Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength); + Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength); continue; } } else if ((Section->Type == EFI_SECTION_GUID_DEFINED) || (Section->Type == EFI_SECTION_COMPRESSION)) { @@ -858,28 +869,28 @@ ProcessSection ( // Check the encapsulated section is extracted into the cache data. // SectionCached = FALSE; - for (Index = 0; Index < PrivateData->CacheSection.AllSectionCount; Index ++) { + for (Index = 0; Index < PrivateData->CacheSection.AllSectionCount; Index++) { if (Section == PrivateData->CacheSection.Section[Index]) { - SectionCached = TRUE; - PpiOutput = PrivateData->CacheSection.SectionData[Index]; - PpiOutputSize = PrivateData->CacheSection.SectionSize[Index]; + SectionCached = TRUE; + PpiOutput = PrivateData->CacheSection.SectionData[Index]; + PpiOutputSize = PrivateData->CacheSection.SectionSize[Index]; Authentication = PrivateData->CacheSection.AuthenticationStatus[Index]; // // Search section directly from the cache data. // TempAuthenticationStatus = 0; - Status = ProcessSection ( - PeiServices, - SectionType, - SectionInstance, - PpiOutput, - PpiOutputSize, - &TempOutputBuffer, - &TempAuthenticationStatus, - IsFfs3Fv - ); + Status = ProcessSection ( + PeiServices, + SectionType, + SectionInstance, + PpiOutput, + PpiOutputSize, + &TempOutputBuffer, + &TempAuthenticationStatus, + IsFfs3Fv + ); if (!EFI_ERROR (Status)) { - *OutputBuffer = TempOutputBuffer; + *OutputBuffer = TempOutputBuffer; *AuthenticationStatus = TempAuthenticationStatus | Authentication; return EFI_SUCCESS; } @@ -890,7 +901,7 @@ ProcessSection ( // If SectionCached is TRUE, the section data has been cached and scanned. // if (!SectionCached) { - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; Authentication = 0; if (Section->Type == EFI_SECTION_GUID_DEFINED) { if (IS_SECTION2 (Section)) { @@ -900,6 +911,7 @@ ProcessSection ( SectionDefinitionGuid = &((EFI_GUID_DEFINED_SECTION *)Section)->SectionDefinitionGuid; GuidedSectionAttributes = ((EFI_GUID_DEFINED_SECTION *)Section)->Attributes; } + if (VerifyGuidedSectionGuid (SectionDefinitionGuid, &GuidSectionPpi)) { Status = GuidSectionPpi->ExtractSection ( GuidSectionPpi, @@ -916,20 +928,21 @@ ProcessSection ( if ((GuidedSectionAttributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID) == EFI_GUIDED_SECTION_AUTH_STATUS_VALID) { Authentication |= EFI_AUTH_STATUS_IMAGE_SIGNED | EFI_AUTH_STATUS_NOT_TESTED; } + if (IS_SECTION2 (Section)) { - PpiOutputSize = SECTION2_SIZE (Section) - ((EFI_GUID_DEFINED_SECTION2 *) Section)->DataOffset; - PpiOutput = (UINT8 *) Section + ((EFI_GUID_DEFINED_SECTION2 *) Section)->DataOffset; + PpiOutputSize = SECTION2_SIZE (Section) - ((EFI_GUID_DEFINED_SECTION2 *)Section)->DataOffset; + PpiOutput = (UINT8 *)Section + ((EFI_GUID_DEFINED_SECTION2 *)Section)->DataOffset; } else { - PpiOutputSize = SECTION_SIZE (Section) - ((EFI_GUID_DEFINED_SECTION *) Section)->DataOffset; - PpiOutput = (UINT8 *) Section + ((EFI_GUID_DEFINED_SECTION *) Section)->DataOffset; + PpiOutputSize = SECTION_SIZE (Section) - ((EFI_GUID_DEFINED_SECTION *)Section)->DataOffset; + PpiOutput = (UINT8 *)Section + ((EFI_GUID_DEFINED_SECTION *)Section)->DataOffset; } } } else if (Section->Type == EFI_SECTION_COMPRESSION) { - Status = PeiServicesLocatePpi (&gEfiPeiDecompressPpiGuid, 0, NULL, (VOID **) &DecompressPpi); + Status = PeiServicesLocatePpi (&gEfiPeiDecompressPpiGuid, 0, NULL, (VOID **)&DecompressPpi); if (!EFI_ERROR (Status)) { Status = DecompressPpi->Decompress ( DecompressPpi, - (CONST EFI_COMPRESSION_SECTION*) Section, + (CONST EFI_COMPRESSION_SECTION *)Section, &PpiOutput, &PpiOutputSize ); @@ -942,28 +955,29 @@ ProcessSection ( // Update cache section data. // if (PrivateData->CacheSection.AllSectionCount < CACHE_SETION_MAX_NUMBER) { - PrivateData->CacheSection.AllSectionCount ++; + PrivateData->CacheSection.AllSectionCount++; } - PrivateData->CacheSection.Section [PrivateData->CacheSection.SectionIndex] = Section; - PrivateData->CacheSection.SectionData [PrivateData->CacheSection.SectionIndex] = PpiOutput; - PrivateData->CacheSection.SectionSize [PrivateData->CacheSection.SectionIndex] = PpiOutputSize; - PrivateData->CacheSection.AuthenticationStatus [PrivateData->CacheSection.SectionIndex] = Authentication; - PrivateData->CacheSection.SectionIndex = (PrivateData->CacheSection.SectionIndex + 1)%CACHE_SETION_MAX_NUMBER; + + PrivateData->CacheSection.Section[PrivateData->CacheSection.SectionIndex] = Section; + PrivateData->CacheSection.SectionData[PrivateData->CacheSection.SectionIndex] = PpiOutput; + PrivateData->CacheSection.SectionSize[PrivateData->CacheSection.SectionIndex] = PpiOutputSize; + PrivateData->CacheSection.AuthenticationStatus[PrivateData->CacheSection.SectionIndex] = Authentication; + PrivateData->CacheSection.SectionIndex = (PrivateData->CacheSection.SectionIndex + 1)%CACHE_SETION_MAX_NUMBER; } TempAuthenticationStatus = 0; - Status = ProcessSection ( - PeiServices, - SectionType, - SectionInstance, - PpiOutput, - PpiOutputSize, - &TempOutputBuffer, - &TempAuthenticationStatus, - IsFfs3Fv - ); + Status = ProcessSection ( + PeiServices, + SectionType, + SectionInstance, + PpiOutput, + PpiOutputSize, + &TempOutputBuffer, + &TempAuthenticationStatus, + IsFfs3Fv + ); if (!EFI_ERROR (Status)) { - *OutputBuffer = TempOutputBuffer; + *OutputBuffer = TempOutputBuffer; *AuthenticationStatus = TempAuthenticationStatus | Authentication; return EFI_SUCCESS; } @@ -976,6 +990,7 @@ ProcessSection ( } else { SectionLength = SECTION_SIZE (Section); } + // // SectionLength is adjusted it is 4 byte aligned. // Go to the next section @@ -983,13 +998,12 @@ ProcessSection ( SectionLength = GET_OCCUPIED_SIZE (SectionLength, 4); ASSERT (SectionLength != 0); ParsedLength += SectionLength; - Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength); + Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)Section + SectionLength); } return EFI_NOT_FOUND; } - /** Searches for the next matching section within the specified file. @@ -1006,13 +1020,13 @@ ProcessSection ( EFI_STATUS EFIAPI PeiFfsFindSectionData ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_SECTION_TYPE SectionType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_SECTION_TYPE SectionType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; CoreFvHandle = FileHandleToVolume (FileHandle); if ((CoreFvHandle == NULL) || (CoreFvHandle->FvPpi == NULL)) { @@ -1039,15 +1053,15 @@ PeiFfsFindSectionData ( EFI_STATUS EFIAPI PeiFfsFindSectionData3 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_SECTION_TYPE SectionType, - IN UINTN SectionInstance, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_SECTION_TYPE SectionType, + IN UINTN SectionInstance, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData, + OUT UINT32 *AuthenticationStatus ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; CoreFvHandle = FileHandleToVolume (FileHandle); if ((CoreFvHandle == NULL) || (CoreFvHandle->FvPpi == NULL)) { @@ -1055,9 +1069,11 @@ PeiFfsFindSectionData3 ( } if ((CoreFvHandle->FvPpi->Signature == EFI_PEI_FIRMWARE_VOLUME_PPI_SIGNATURE) && - (CoreFvHandle->FvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) { + (CoreFvHandle->FvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) + { return CoreFvHandle->FvPpi->FindSectionByType2 (CoreFvHandle->FvPpi, SectionType, SectionInstance, FileHandle, SectionData, AuthenticationStatus); } + // // The old FvPpi doesn't support to find section by section instance // and return authentication status, so return EFI_UNSUPPORTED. @@ -1084,24 +1100,23 @@ PeiFfsFindSectionData3 ( EFI_STATUS EFIAPI PeiFfsFindNextFile ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINT8 SearchType, - IN EFI_PEI_FV_HANDLE FvHandle, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINT8 SearchType, + IN EFI_PEI_FV_HANDLE FvHandle, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; CoreFvHandle = FvHandleToCoreHandle (FvHandle); - if ((CoreFvHandle == NULL) || CoreFvHandle->FvPpi == NULL) { + if ((CoreFvHandle == NULL) || (CoreFvHandle->FvPpi == NULL)) { return EFI_NOT_FOUND; } return CoreFvHandle->FvPpi->FindFileByType (CoreFvHandle->FvPpi, SearchType, FvHandle, FileHandle); } - /** Search the firmware volumes by index @@ -1118,13 +1133,13 @@ PeiFfsFindNextFile ( EFI_STATUS EFIAPI PeiFfsFindNextVolume ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINTN Instance, - IN OUT EFI_PEI_FV_HANDLE *VolumeHandle + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINTN Instance, + IN OUT EFI_PEI_FV_HANDLE *VolumeHandle ) { - PEI_CORE_INSTANCE *Private; - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_INSTANCE *Private; + PEI_CORE_FV_HANDLE *CoreFvHandle; if (VolumeHandle == NULL) { return EFI_INVALID_PARAMETER; @@ -1143,7 +1158,6 @@ PeiFfsFindNextVolume ( return EFI_SUCCESS; } - /** Find a file within a volume by its name. @@ -1160,12 +1174,12 @@ PeiFfsFindNextVolume ( EFI_STATUS EFIAPI PeiFfsFindFileByName ( - IN CONST EFI_GUID *FileName, - IN EFI_PEI_FV_HANDLE VolumeHandle, - OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_GUID *FileName, + IN EFI_PEI_FV_HANDLE VolumeHandle, + OUT EFI_PEI_FILE_HANDLE *FileHandle ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; if ((VolumeHandle == NULL) || (FileName == NULL) || (FileHandle == NULL)) { return EFI_INVALID_PARAMETER; @@ -1197,7 +1211,7 @@ PeiFfsGetFileInfo ( OUT EFI_FV_FILE_INFO *FileInfo ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; if ((FileHandle == NULL) || (FileInfo == NULL)) { return EFI_INVALID_PARAMETER; @@ -1232,7 +1246,7 @@ PeiFfsGetFileInfo2 ( OUT EFI_FV_FILE_INFO2 *FileInfo ) { - PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_CORE_FV_HANDLE *CoreFvHandle; if ((FileHandle == NULL) || (FileInfo == NULL)) { return EFI_INVALID_PARAMETER; @@ -1247,9 +1261,11 @@ PeiFfsGetFileInfo2 ( } if ((CoreFvHandle->FvPpi->Signature == EFI_PEI_FIRMWARE_VOLUME_PPI_SIGNATURE) && - (CoreFvHandle->FvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) { + (CoreFvHandle->FvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) + { return CoreFvHandle->FvPpi->GetFileInfo2 (CoreFvHandle->FvPpi, FileHandle, FileInfo); } + // // The old FvPpi doesn't support to return file info with authentication status, // so return EFI_UNSUPPORTED. @@ -1281,7 +1297,7 @@ PeiFfsGetVolumeInfo ( OUT EFI_FV_INFO *VolumeInfo ) { - PEI_CORE_FV_HANDLE *CoreHandle; + PEI_CORE_FV_HANDLE *CoreHandle; if ((VolumeInfo == NULL) || (VolumeHandle == NULL)) { return EFI_INVALID_PARAMETER; @@ -1312,9 +1328,9 @@ PeiFfsGetVolumeInfo ( **/ BOOLEAN GetFvUsedSize ( - IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader, - OUT UINT32 *FvUsedSize, - OUT UINT8 *EraseByte + IN EFI_FIRMWARE_VOLUME_HEADER *FvHeader, + OUT UINT32 *FvUsedSize, + OUT UINT8 *EraseByte ) { UINT16 ExtHeaderOffset; @@ -1324,20 +1340,21 @@ GetFvUsedSize ( ExtHeaderOffset = ReadUnaligned16 (&FvHeader->ExtHeaderOffset); if (ExtHeaderOffset != 0) { - ExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *) ((UINT8 *) FvHeader + ExtHeaderOffset); - ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *) (ExtHeader + 1); - while ((UINTN) ExtEntryList < ((UINTN) ExtHeader + ReadUnaligned32 (&ExtHeader->ExtHeaderSize))) { + ExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)((UINT8 *)FvHeader + ExtHeaderOffset); + ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *)(ExtHeader + 1); + while ((UINTN)ExtEntryList < ((UINTN)ExtHeader + ReadUnaligned32 (&ExtHeader->ExtHeaderSize))) { if (ReadUnaligned16 (&ExtEntryList->ExtEntryType) == EFI_FV_EXT_TYPE_USED_SIZE_TYPE) { // // USED_SIZE FV_EXT_TYPE entry is found. // - ExtEntryUsedSize = (EFI_FIRMWARE_VOLUME_EXT_ENTRY_USED_SIZE_TYPE *) ExtEntryList; - *FvUsedSize = ReadUnaligned32 (&ExtEntryUsedSize->UsedSize); + ExtEntryUsedSize = (EFI_FIRMWARE_VOLUME_EXT_ENTRY_USED_SIZE_TYPE *)ExtEntryList; + *FvUsedSize = ReadUnaligned32 (&ExtEntryUsedSize->UsedSize); if ((ReadUnaligned32 (&FvHeader->Attributes) & EFI_FVB2_ERASE_POLARITY) != 0) { *EraseByte = 0xFF; } else { *EraseByte = 0; } + DEBUG (( DEBUG_INFO, "FV at 0x%x has 0x%x used size, and erase byte is 0x%02x\n", @@ -1347,8 +1364,9 @@ GetFvUsedSize ( )); return TRUE; } + ExtEntryList = (EFI_FIRMWARE_VOLUME_EXT_ENTRY *) - ((UINT8 *) ExtEntryList + ReadUnaligned16 (&ExtEntryList->ExtEntrySize)); + ((UINT8 *)ExtEntryList + ReadUnaligned16 (&ExtEntryList->ExtEntrySize)); } } @@ -1374,25 +1392,25 @@ GetFvUsedSize ( **/ EFI_STATUS ProcessFvFile ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_FV_HANDLE *ParentFvCoreHandle, - IN EFI_PEI_FILE_HANDLE ParentFvFileHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_FV_HANDLE *ParentFvCoreHandle, + IN EFI_PEI_FILE_HANDLE ParentFvFileHandle ) { - EFI_STATUS Status; - EFI_FV_INFO ParentFvImageInfo; - UINT32 FvAlignment; - VOID *NewFvBuffer; - EFI_PEI_HOB_POINTERS HobPtr; - EFI_PEI_FIRMWARE_VOLUME_PPI *ParentFvPpi; - EFI_PEI_FV_HANDLE ParentFvHandle; - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - EFI_FV_FILE_INFO FileInfo; - UINT64 FvLength; - UINT32 AuthenticationStatus; - UINT32 FvUsedSize; - UINT8 EraseByte; - UINTN Index; + EFI_STATUS Status; + EFI_FV_INFO ParentFvImageInfo; + UINT32 FvAlignment; + VOID *NewFvBuffer; + EFI_PEI_HOB_POINTERS HobPtr; + EFI_PEI_FIRMWARE_VOLUME_PPI *ParentFvPpi; + EFI_PEI_FV_HANDLE ParentFvHandle; + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_FV_FILE_INFO FileInfo; + UINT64 FvLength; + UINT32 AuthenticationStatus; + UINT32 FvUsedSize; + UINT8 EraseByte; + UINTN Index; // // Check if this EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE file has already @@ -1407,6 +1425,7 @@ ProcessFvFile ( DEBUG ((DEBUG_INFO, "FV file %p has been dispatched!\r\n", ParentFvFileHandle)); return EFI_SUCCESS; } + HobPtr.Raw = GET_NEXT_HOB (HobPtr); } @@ -1422,7 +1441,8 @@ ProcessFvFile ( do { AuthenticationStatus = 0; if ((ParentFvPpi->Signature == EFI_PEI_FIRMWARE_VOLUME_PPI_SIGNATURE) && - (ParentFvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) { + (ParentFvPpi->Revision == EFI_PEI_FIRMWARE_VOLUME_PPI_REVISION)) + { Status = ParentFvPpi->FindSectionByType2 ( ParentFvPpi, EFI_SECTION_FIRMWARE_VOLUME_IMAGE, @@ -1439,6 +1459,7 @@ ProcessFvFile ( if (Index > 0) { break; } + Status = ParentFvPpi->FindSectionByType ( ParentFvPpi, EFI_SECTION_FIRMWARE_VOLUME_IMAGE, @@ -1446,6 +1467,7 @@ ProcessFvFile ( (VOID **)&FvHeader ); } + if (EFI_ERROR (Status)) { break; } @@ -1480,27 +1502,29 @@ ProcessFvFile ( // // Check FvImage alignment. // - if ((UINTN) FvHeader % FvAlignment != 0) { + if ((UINTN)FvHeader % FvAlignment != 0) { FvLength = ReadUnaligned64 (&FvHeader->FvLength); - NewFvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32) FvLength), FvAlignment); + NewFvBuffer = AllocateAlignedPages (EFI_SIZE_TO_PAGES ((UINT32)FvLength), FvAlignment); if (NewFvBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; break; } + if (GetFvUsedSize (FvHeader, &FvUsedSize, &EraseByte)) { // // Copy the used bytes and fill the rest with the erase value. // - CopyMem (NewFvBuffer, FvHeader, (UINTN) FvUsedSize); + CopyMem (NewFvBuffer, FvHeader, (UINTN)FvUsedSize); SetMem ( - (UINT8 *) NewFvBuffer + FvUsedSize, - (UINTN) (FvLength - FvUsedSize), + (UINT8 *)NewFvBuffer + FvUsedSize, + (UINTN)(FvLength - FvUsedSize), EraseByte ); } else { - CopyMem (NewFvBuffer, FvHeader, (UINTN) FvLength); + CopyMem (NewFvBuffer, FvHeader, (UINTN)FvLength); } - FvHeader = (EFI_FIRMWARE_VOLUME_HEADER*) NewFvBuffer; + + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)NewFvBuffer; } } @@ -1515,9 +1539,9 @@ ProcessFvFile ( // NOTE: FvInfo2 must be installed before FvInfo so that recursive processing of encapsulated // FVs inherit the proper AuthenticationStatus. // - PeiServicesInstallFvInfo2Ppi( + PeiServicesInstallFvInfo2Ppi ( &FvHeader->FileSystemGuid, - (VOID**)FvHeader, + (VOID **)FvHeader, (UINT32)FvHeader->FvLength, &ParentFvImageInfo.FvName, &FileInfo.FileName, @@ -1526,8 +1550,8 @@ ProcessFvFile ( PeiServicesInstallFvInfoPpi ( &FvHeader->FileSystemGuid, - (VOID**) FvHeader, - (UINT32) FvHeader->FvLength, + (VOID **)FvHeader, + (UINT32)FvHeader->FvLength, &ParentFvImageInfo.FvName, &FileInfo.FileName ); @@ -1536,7 +1560,7 @@ ProcessFvFile ( // Expose the extracted FvImage to the FV HOB consumer phase, i.e. DXE phase // BuildFvHob ( - (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, + (EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader, FvHeader->FvLength ); @@ -1545,7 +1569,7 @@ ProcessFvFile ( // encapsulated file again. // BuildFv2Hob ( - (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, + (EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader, FvHeader->FvLength, &ParentFvImageInfo.FvName, &FileInfo.FileName @@ -1555,7 +1579,7 @@ ProcessFvFile ( // Build FV3 HOB with authentication status to be propagated to DXE. // BuildFv3Hob ( - (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, + (EFI_PHYSICAL_ADDRESS)(UINTN)FvHeader, FvHeader->FvLength, AuthenticationStatus, TRUE, @@ -1603,13 +1627,13 @@ ProcessFvFile ( EFI_STATUS EFIAPI PeiFfsFvPpiProcessVolume ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN VOID *Buffer, - IN UINTN BufferSize, - OUT EFI_PEI_FV_HANDLE *FvHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN VOID *Buffer, + IN UINTN BufferSize, + OUT EFI_PEI_FV_HANDLE *FvHandle ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (FvHandle != NULL); @@ -1621,13 +1645,13 @@ PeiFfsFvPpiProcessVolume ( // The build-in EFI_PEI_FIRMWARE_VOLUME_PPI for FFS2/FFS3 support memory-mapped // FV image and the handle is pointed to FV image's buffer. // - *FvHandle = (EFI_PEI_FV_HANDLE) Buffer; + *FvHandle = (EFI_PEI_FV_HANDLE)Buffer; // // Do verify for given FV buffer. // - Status = VerifyFv ((EFI_FIRMWARE_VOLUME_HEADER*) Buffer); - if (EFI_ERROR(Status)) { + Status = VerifyFv ((EFI_FIRMWARE_VOLUME_HEADER *)Buffer); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Fail to verify FV which address is 0x%11p", Buffer)); return EFI_VOLUME_CORRUPTED; } @@ -1660,10 +1684,10 @@ PeiFfsFvPpiProcessVolume ( EFI_STATUS EFIAPI PeiFfsFvPpiFindFileByType ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_FV_FILETYPE SearchType, - IN EFI_PEI_FV_HANDLE FvHandle, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_FV_FILETYPE SearchType, + IN EFI_PEI_FV_HANDLE FvHandle, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle ) { return FindFileEx (FvHandle, NULL, SearchType, FileHandle, NULL); @@ -1697,15 +1721,15 @@ PeiFfsFvPpiFindFileByType ( EFI_STATUS EFIAPI PeiFfsFvPpiFindFileByName ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN CONST EFI_GUID *FileName, - IN EFI_PEI_FV_HANDLE *FvHandle, - OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN CONST EFI_GUID *FileName, + IN EFI_PEI_FV_HANDLE *FvHandle, + OUT EFI_PEI_FILE_HANDLE *FileHandle ) { - EFI_STATUS Status; - PEI_CORE_INSTANCE *PrivateData; - UINTN Index; + EFI_STATUS Status; + PEI_CORE_INSTANCE *PrivateData; + UINTN Index; if ((FvHandle == NULL) || (FileName == NULL) || (FileHandle == NULL)) { return EFI_INVALID_PARAMETER; @@ -1722,8 +1746,8 @@ PeiFfsFvPpiFindFileByName ( // Status = EFI_NOT_FOUND; - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer()); - for (Index = 0; Index < PrivateData->FvCount; Index ++) { + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ()); + for (Index = 0; Index < PrivateData->FvCount; Index++) { // // Only search the FV which is associated with a EFI_PEI_FIRMWARE_VOLUME_PPI instance. // @@ -1762,16 +1786,16 @@ PeiFfsFvPpiFindFileByName ( EFI_STATUS EFIAPI PeiFfsFvPpiGetFileInfo ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT EFI_FV_FILE_INFO *FileInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT EFI_FV_FILE_INFO *FileInfo ) { - UINT8 FileState; - UINT8 ErasePolarity; - EFI_FFS_FILE_HEADER *FileHeader; - PEI_CORE_FV_HANDLE *CoreFvHandle; - PEI_FW_VOL_INSTANCE *FwVolInstance; + UINT8 FileState; + UINT8 ErasePolarity; + EFI_FFS_FILE_HEADER *FileHeader; + PEI_CORE_FV_HANDLE *CoreFvHandle; + PEI_FW_VOL_INSTANCE *FwVolInstance; if ((FileHandle == NULL) || (FileInfo == NULL)) { return EFI_INVALID_PARAMETER; @@ -1796,7 +1820,7 @@ PeiFfsFvPpiGetFileInfo ( // // Get FileState which is the highest bit of the State // - FileState = GetFileState (ErasePolarity, (EFI_FFS_FILE_HEADER*)FileHandle); + FileState = GetFileState (ErasePolarity, (EFI_FFS_FILE_HEADER *)FileHandle); switch (FileState) { case EFI_FILE_DATA_VALID: @@ -1804,7 +1828,7 @@ PeiFfsFvPpiGetFileInfo ( break; default: return EFI_INVALID_PARAMETER; - } + } FileHeader = (EFI_FFS_FILE_HEADER *)FileHandle; if (IS_FFS_FILE2 (FileHeader)) { @@ -1813,18 +1837,21 @@ PeiFfsFvPpiGetFileInfo ( DEBUG ((DEBUG_ERROR, "It is a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FileHeader->Name)); return EFI_INVALID_PARAMETER; } + FileInfo->BufferSize = FFS_FILE2_SIZE (FileHeader) - sizeof (EFI_FFS_FILE_HEADER2); - FileInfo->Buffer = (UINT8 *) FileHeader + sizeof (EFI_FFS_FILE_HEADER2); + FileInfo->Buffer = (UINT8 *)FileHeader + sizeof (EFI_FFS_FILE_HEADER2); } else { FileInfo->BufferSize = FFS_FILE_SIZE (FileHeader) - sizeof (EFI_FFS_FILE_HEADER); - FileInfo->Buffer = (UINT8 *) FileHeader + sizeof (EFI_FFS_FILE_HEADER); + FileInfo->Buffer = (UINT8 *)FileHeader + sizeof (EFI_FFS_FILE_HEADER); } - CopyMem (&FileInfo->FileName, &FileHeader->Name, sizeof(EFI_GUID)); - FileInfo->FileType = FileHeader->Type; + + CopyMem (&FileInfo->FileName, &FileHeader->Name, sizeof (EFI_GUID)); + FileInfo->FileType = FileHeader->Type; FileInfo->FileAttributes = FfsAttributes2FvFileAttributes (FileHeader->Attributes); if ((CoreFvHandle->FvHeader->Attributes & EFI_FVB2_MEMORY_MAPPED) == EFI_FVB2_MEMORY_MAPPED) { FileInfo->FileAttributes |= EFI_FV_FILE_ATTRIB_MEMORY_MAPPED; } + return EFI_SUCCESS; } @@ -1850,13 +1877,13 @@ PeiFfsFvPpiGetFileInfo ( EFI_STATUS EFIAPI PeiFfsFvPpiGetFileInfo2 ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT EFI_FV_FILE_INFO2 *FileInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT EFI_FV_FILE_INFO2 *FileInfo ) { - EFI_STATUS Status; - PEI_CORE_FV_HANDLE *CoreFvHandle; + EFI_STATUS Status; + PEI_CORE_FV_HANDLE *CoreFvHandle; if ((FileHandle == NULL) || (FileInfo == NULL)) { return EFI_INVALID_PARAMETER; @@ -1870,7 +1897,7 @@ PeiFfsFvPpiGetFileInfo2 ( return EFI_INVALID_PARAMETER; } - Status = PeiFfsFvPpiGetFileInfo (This, FileHandle, (EFI_FV_FILE_INFO *) FileInfo); + Status = PeiFfsFvPpiGetFileInfo (This, FileHandle, (EFI_FV_FILE_INFO *)FileInfo); if (!EFI_ERROR (Status)) { FileInfo->AuthenticationStatus = CoreFvHandle->AuthenticationStatus; } @@ -1895,13 +1922,13 @@ PeiFfsFvPpiGetFileInfo2 ( EFI_STATUS EFIAPI PeiFfsFvPpiGetVolumeInfo ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FV_HANDLE FvHandle, - OUT EFI_FV_INFO *VolumeInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FV_HANDLE FvHandle, + OUT EFI_FV_INFO *VolumeInfo ) { - EFI_FIRMWARE_VOLUME_HEADER FwVolHeader; - EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo; + EFI_FIRMWARE_VOLUME_HEADER FwVolHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FwVolExHeaderInfo; if ((VolumeInfo == NULL) || (FvHandle == NULL)) { return EFI_INVALID_PARAMETER; @@ -1922,14 +1949,14 @@ PeiFfsFvPpiGetVolumeInfo ( } ZeroMem (VolumeInfo, sizeof (EFI_FV_INFO)); - VolumeInfo->FvAttributes = FwVolHeader.Attributes; - VolumeInfo->FvStart = (VOID *) FvHandle; - VolumeInfo->FvSize = FwVolHeader.FvLength; - CopyMem (&VolumeInfo->FvFormat, &FwVolHeader.FileSystemGuid, sizeof(EFI_GUID)); + VolumeInfo->FvAttributes = FwVolHeader.Attributes; + VolumeInfo->FvStart = (VOID *)FvHandle; + VolumeInfo->FvSize = FwVolHeader.FvLength; + CopyMem (&VolumeInfo->FvFormat, &FwVolHeader.FileSystemGuid, sizeof (EFI_GUID)); if (FwVolHeader.ExtHeaderOffset != 0) { - FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER*)(((UINT8 *)FvHandle) + FwVolHeader.ExtHeaderOffset); - CopyMem (&VolumeInfo->FvName, &FwVolExHeaderInfo->FvName, sizeof(EFI_GUID)); + FwVolExHeaderInfo = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(((UINT8 *)FvHandle) + FwVolHeader.ExtHeaderOffset); + CopyMem (&VolumeInfo->FvName, &FwVolExHeaderInfo->FvName, sizeof (EFI_GUID)); } return EFI_SUCCESS; @@ -1957,13 +1984,14 @@ PeiFfsFvPpiGetVolumeInfo ( EFI_STATUS EFIAPI PeiFfsFvPpiFindSectionByType ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_SECTION_TYPE SearchType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_SECTION_TYPE SearchType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ) { - UINT32 AuthenticationStatus; + UINT32 AuthenticationStatus; + return PeiFfsFvPpiFindSectionByType2 (This, SearchType, 0, FileHandle, SectionData, &AuthenticationStatus); } @@ -1993,22 +2021,22 @@ PeiFfsFvPpiFindSectionByType ( EFI_STATUS EFIAPI PeiFfsFvPpiFindSectionByType2 ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_SECTION_TYPE SearchType, - IN UINTN SearchInstance, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_SECTION_TYPE SearchType, + IN UINTN SearchInstance, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData, + OUT UINT32 *AuthenticationStatus ) { - EFI_STATUS Status; - EFI_FFS_FILE_HEADER *FfsFileHeader; - UINT32 FileSize; - EFI_COMMON_SECTION_HEADER *Section; - PEI_FW_VOL_INSTANCE *FwVolInstance; - PEI_CORE_FV_HANDLE *CoreFvHandle; - UINTN Instance; - UINT32 ExtractedAuthenticationStatus; + EFI_STATUS Status; + EFI_FFS_FILE_HEADER *FfsFileHeader; + UINT32 FileSize; + EFI_COMMON_SECTION_HEADER *Section; + PEI_FW_VOL_INSTANCE *FwVolInstance; + PEI_CORE_FV_HANDLE *CoreFvHandle; + UINTN Instance; + UINT32 ExtractedAuthenticationStatus; if (SectionData == NULL) { return EFI_NOT_FOUND; @@ -2032,31 +2060,33 @@ PeiFfsFvPpiFindSectionByType2 ( DEBUG ((DEBUG_ERROR, "It is a FFS3 formatted file: %g in a non-FFS3 formatted FV.\n", &FfsFileHeader->Name)); return EFI_NOT_FOUND; } - Section = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2)); + + Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER2)); FileSize = FFS_FILE2_SIZE (FfsFileHeader) - sizeof (EFI_FFS_FILE_HEADER2); } else { - Section = (EFI_COMMON_SECTION_HEADER *) ((UINT8 *) FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER)); + Section = (EFI_COMMON_SECTION_HEADER *)((UINT8 *)FfsFileHeader + sizeof (EFI_FFS_FILE_HEADER)); FileSize = FFS_FILE_SIZE (FfsFileHeader) - sizeof (EFI_FFS_FILE_HEADER); } - Instance = SearchInstance + 1; + Instance = SearchInstance + 1; ExtractedAuthenticationStatus = 0; - Status = ProcessSection ( - GetPeiServicesTablePointer (), - SearchType, - &Instance, - Section, - FileSize, - SectionData, - &ExtractedAuthenticationStatus, - FwVolInstance->IsFfs3Fv - ); + Status = ProcessSection ( + GetPeiServicesTablePointer (), + SearchType, + &Instance, + Section, + FileSize, + SectionData, + &ExtractedAuthenticationStatus, + FwVolInstance->IsFfs3Fv + ); if (!EFI_ERROR (Status)) { // // Inherit the authentication status. // *AuthenticationStatus = ExtractedAuthenticationStatus | CoreFvHandle->AuthenticationStatus; } + return Status; } @@ -2073,11 +2103,11 @@ FvHandleToCoreHandle ( IN EFI_PEI_FV_HANDLE FvHandle ) { - UINTN Index; - PEI_CORE_INSTANCE *PrivateData; + UINTN Index; + PEI_CORE_INSTANCE *PrivateData; - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer()); - for (Index = 0; Index < PrivateData->FvCount; Index ++) { + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ()); + for (Index = 0; Index < PrivateData->FvCount; Index++) { if (FvHandle == PrivateData->Fv[Index].FvHandle) { return &PrivateData->Fv[Index]; } @@ -2120,7 +2150,7 @@ FindNextCoreFvHandle ( **/ VOID PeiReinitializeFv ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ) { VOID *OldFfsFvPpi; @@ -2133,11 +2163,11 @@ PeiReinitializeFv ( // in flash. // Status = PeiServicesLocatePpi ( - &gEfiFirmwareFileSystem2Guid, - 0, - &OldDescriptor, - &OldFfsFvPpi - ); + &gEfiFirmwareFileSystem2Guid, + 0, + &OldDescriptor, + &OldFfsFvPpi + ); ASSERT_EFI_ERROR (Status); // @@ -2150,7 +2180,7 @@ PeiReinitializeFv ( // // Fixup all FvPpi pointers for the implementation in flash to permanent memory. // - for (Index = 0; Index < PrivateData->FvCount; Index ++) { + for (Index = 0; Index < PrivateData->FvCount; Index++) { if (PrivateData->Fv[Index].FvPpi == OldFfsFvPpi) { PrivateData->Fv[Index].FvPpi = &mPeiFfs2FwVol.Fv; } @@ -2178,7 +2208,7 @@ PeiReinitializeFv ( // // Fixup all FvPpi pointers for the implementation in flash to permanent memory. // - for (Index = 0; Index < PrivateData->FvCount; Index ++) { + for (Index = 0; Index < PrivateData->FvCount; Index++) { if (PrivateData->Fv[Index].FvPpi == OldFfsFvPpi) { PrivateData->Fv[Index].FvPpi = &mPeiFfs3FwVol.Fv; } @@ -2208,8 +2238,8 @@ AddUnknownFormatFvInfo ( IN EFI_PEI_FIRMWARE_VOLUME_INFO2_PPI *FvInfo2Ppi ) { - PEI_CORE_UNKNOW_FORMAT_FV_INFO *NewUnknownFv; - VOID *TempPtr; + PEI_CORE_UNKNOW_FORMAT_FV_INFO *NewUnknownFv; + VOID *TempPtr; if (PrivateData->UnknownFvInfoCount >= PrivateData->MaxUnknownFvInfoCount) { // @@ -2224,17 +2254,17 @@ AddUnknownFormatFvInfo ( PrivateData->UnknownFvInfo, sizeof (PEI_CORE_UNKNOW_FORMAT_FV_INFO) * PrivateData->MaxUnknownFvInfoCount ); - PrivateData->UnknownFvInfo = TempPtr; + PrivateData->UnknownFvInfo = TempPtr; PrivateData->MaxUnknownFvInfoCount = PrivateData->MaxUnknownFvInfoCount + FV_GROWTH_STEP; } NewUnknownFv = &PrivateData->UnknownFvInfo[PrivateData->UnknownFvInfoCount]; - PrivateData->UnknownFvInfoCount ++; + PrivateData->UnknownFvInfoCount++; CopyGuid (&NewUnknownFv->FvFormat, &FvInfo2Ppi->FvFormat); - NewUnknownFv->FvInfo = FvInfo2Ppi->FvInfo; - NewUnknownFv->FvInfoSize = FvInfo2Ppi->FvInfoSize; - NewUnknownFv->AuthenticationStatus = FvInfo2Ppi->AuthenticationStatus; + NewUnknownFv->FvInfo = FvInfo2Ppi->FvInfo; + NewUnknownFv->FvInfoSize = FvInfo2Ppi->FvInfoSize; + NewUnknownFv->AuthenticationStatus = FvInfo2Ppi->AuthenticationStatus; NewUnknownFv->NotifyDescriptor.Flags = (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST); NewUnknownFv->NotifyDescriptor.Guid = &NewUnknownFv->FvFormat; NewUnknownFv->NotifyDescriptor.Notify = ThirdPartyFvPpiNotifyCallback; @@ -2260,18 +2290,18 @@ AddUnknownFormatFvInfo ( **/ EFI_STATUS FindUnknownFormatFvInfo ( - IN PEI_CORE_INSTANCE *PrivateData, - IN EFI_GUID *Format, - OUT VOID **FvInfo, - OUT UINT32 *FvInfoSize, - OUT UINT32 *AuthenticationStatus + IN PEI_CORE_INSTANCE *PrivateData, + IN EFI_GUID *Format, + OUT VOID **FvInfo, + OUT UINT32 *FvInfoSize, + OUT UINT32 *AuthenticationStatus ) { - UINTN Index; - UINTN Index2; + UINTN Index; + UINTN Index2; Index = 0; - for (; Index < PrivateData->UnknownFvInfoCount; Index ++) { + for ( ; Index < PrivateData->UnknownFvInfoCount; Index++) { if (CompareGuid (Format, &PrivateData->UnknownFvInfo[Index].FvFormat)) { break; } @@ -2281,18 +2311,19 @@ FindUnknownFormatFvInfo ( return EFI_NOT_FOUND; } - *FvInfo = PrivateData->UnknownFvInfo[Index].FvInfo; - *FvInfoSize = PrivateData->UnknownFvInfo[Index].FvInfoSize; + *FvInfo = PrivateData->UnknownFvInfo[Index].FvInfo; + *FvInfoSize = PrivateData->UnknownFvInfo[Index].FvInfoSize; *AuthenticationStatus = PrivateData->UnknownFvInfo[Index].AuthenticationStatus; // // Remove an entry from UnknownFvInfo array. // Index2 = Index + 1; - for (;Index2 < PrivateData->UnknownFvInfoCount; Index2 ++, Index ++) { + for ( ; Index2 < PrivateData->UnknownFvInfoCount; Index2++, Index++) { CopyMem (&PrivateData->UnknownFvInfo[Index], &PrivateData->UnknownFvInfo[Index2], sizeof (PEI_CORE_UNKNOW_FORMAT_FV_INFO)); } - PrivateData->UnknownFvInfoCount --; + + PrivateData->UnknownFvInfoCount--; return EFI_SUCCESS; } @@ -2311,9 +2342,9 @@ FindUnknownFormatFvInfo ( EFI_STATUS EFIAPI ThirdPartyFvPpiNotifyCallback ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, - IN VOID *Ppi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi ) { PEI_CORE_INSTANCE *PrivateData; @@ -2330,8 +2361,8 @@ ThirdPartyFvPpiNotifyCallback ( UINTN CurFvCount; VOID *TempPtr; - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); - FvPpi = (EFI_PEI_FIRMWARE_VOLUME_PPI*) Ppi; + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); + FvPpi = (EFI_PEI_FIRMWARE_VOLUME_PPI *)Ppi; do { Status = FindUnknownFormatFvInfo (PrivateData, NotifyDescriptor->Guid, &FvInfo, &FvInfoSize, &AuthenticationStatus); @@ -2352,7 +2383,7 @@ ThirdPartyFvPpiNotifyCallback ( // Check whether the FV has already been processed. // IsProcessed = FALSE; - for (FvIndex = 0; FvIndex < PrivateData->FvCount; FvIndex ++) { + for (FvIndex = 0; FvIndex < PrivateData->FvCount; FvIndex++) { if (PrivateData->Fv[FvIndex].FvHandle == FvHandle) { DEBUG ((DEBUG_INFO, "The FV %p has already been processed!\n", FvInfo)); IsProcessed = TRUE; @@ -2377,27 +2408,27 @@ ThirdPartyFvPpiNotifyCallback ( PrivateData->Fv, sizeof (PEI_CORE_FV_HANDLE) * PrivateData->MaxFvCount ); - PrivateData->Fv = TempPtr; + PrivateData->Fv = TempPtr; PrivateData->MaxFvCount = PrivateData->MaxFvCount + FV_GROWTH_STEP; } // // Update internal PEI_CORE_FV array. // - PrivateData->Fv[PrivateData->FvCount].FvHeader = (EFI_FIRMWARE_VOLUME_HEADER*) FvInfo; - PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; - PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; + PrivateData->Fv[PrivateData->FvCount].FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)FvInfo; + PrivateData->Fv[PrivateData->FvCount].FvPpi = FvPpi; + PrivateData->Fv[PrivateData->FvCount].FvHandle = FvHandle; PrivateData->Fv[PrivateData->FvCount].AuthenticationStatus = AuthenticationStatus; - CurFvCount = PrivateData->FvCount; + CurFvCount = PrivateData->FvCount; DEBUG (( DEBUG_INFO, "The %dth FV start address is 0x%11p, size is 0x%08x, handle is 0x%p\n", - (UINT32) CurFvCount, - (VOID *) FvInfo, + (UINT32)CurFvCount, + (VOID *)FvInfo, FvInfoSize, FvHandle )); - PrivateData->FvCount ++; + PrivateData->FvCount++; // // Scan and process the new discovered FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE @@ -2409,13 +2440,13 @@ ThirdPartyFvPpiNotifyCallback ( EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE, FvHandle, &FileHandle - ); + ); if (!EFI_ERROR (Status)) { Status = FvPpi->FindSectionByType ( FvPpi, EFI_SECTION_PEI_DEPEX, FileHandle, - (VOID**)&DepexData + (VOID **)&DepexData ); if (!EFI_ERROR (Status)) { if (!PeimDispatchReadiness (PeiServices, DepexData)) { diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.h b/MdeModulePkg/Core/Pei/FwVol/FwVol.h index f4a0568068..7d1dc9cba1 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.h +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.h @@ -14,19 +14,17 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define GET_OCCUPIED_SIZE(ActualSize, Alignment) \ ((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))) - #define PEI_FW_VOL_SIGNATURE SIGNATURE_32('P','F','W','V') typedef struct { - UINTN Signature; - BOOLEAN IsFfs3Fv; - EFI_PEI_FIRMWARE_VOLUME_PPI Fv; + UINTN Signature; + BOOLEAN IsFfs3Fv; + EFI_PEI_FIRMWARE_VOLUME_PPI Fv; } PEI_FW_VOL_INSTANCE; #define PEI_FW_VOL_INSTANCE_FROM_FV_THIS(a) \ CR(a, PEI_FW_VOL_INSTANCE, Fv, PEI_FW_VOL_SIGNATURE) - /** Process a firmware volume and create a volume handle. @@ -54,10 +52,10 @@ typedef struct { EFI_STATUS EFIAPI PeiFfsFvPpiProcessVolume ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN VOID *Buffer, - IN UINTN BufferSize, - OUT EFI_PEI_FV_HANDLE *FvHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN VOID *Buffer, + IN UINTN BufferSize, + OUT EFI_PEI_FV_HANDLE *FvHandle ); /** @@ -85,10 +83,10 @@ PeiFfsFvPpiProcessVolume ( EFI_STATUS EFIAPI PeiFfsFvPpiFindFileByType ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_FV_FILETYPE SearchType, - IN EFI_PEI_FV_HANDLE FvHandle, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_FV_FILETYPE SearchType, + IN EFI_PEI_FV_HANDLE FvHandle, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle ); /** @@ -119,10 +117,10 @@ PeiFfsFvPpiFindFileByType ( EFI_STATUS EFIAPI PeiFfsFvPpiFindFileByName ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN CONST EFI_GUID *FileName, - IN EFI_PEI_FV_HANDLE *FvHandle, - OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN CONST EFI_GUID *FileName, + IN EFI_PEI_FV_HANDLE *FvHandle, + OUT EFI_PEI_FILE_HANDLE *FileHandle ); /** @@ -147,10 +145,10 @@ PeiFfsFvPpiFindFileByName ( EFI_STATUS EFIAPI PeiFfsFvPpiFindSectionByType ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_SECTION_TYPE SearchType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_SECTION_TYPE SearchType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ); /** @@ -179,12 +177,12 @@ PeiFfsFvPpiFindSectionByType ( EFI_STATUS EFIAPI PeiFfsFvPpiFindSectionByType2 ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_SECTION_TYPE SearchType, - IN UINTN SearchInstance, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_SECTION_TYPE SearchType, + IN UINTN SearchInstance, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData, + OUT UINT32 *AuthenticationStatus ); /** @@ -209,9 +207,9 @@ PeiFfsFvPpiFindSectionByType2 ( EFI_STATUS EFIAPI PeiFfsFvPpiGetFileInfo ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT EFI_FV_FILE_INFO *FileInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT EFI_FV_FILE_INFO *FileInfo ); /** @@ -236,9 +234,9 @@ PeiFfsFvPpiGetFileInfo ( EFI_STATUS EFIAPI PeiFfsFvPpiGetFileInfo2 ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT EFI_FV_FILE_INFO2 *FileInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT EFI_FV_FILE_INFO2 *FileInfo ); /** @@ -258,9 +256,9 @@ PeiFfsFvPpiGetFileInfo2 ( EFI_STATUS EFIAPI PeiFfsFvPpiGetVolumeInfo ( - IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, - IN EFI_PEI_FV_HANDLE FvHandle, - OUT EFI_FV_INFO *VolumeInfo + IN CONST EFI_PEI_FIRMWARE_VOLUME_PPI *This, + IN EFI_PEI_FV_HANDLE FvHandle, + OUT EFI_FV_INFO *VolumeInfo ); /** @@ -295,11 +293,11 @@ FvHandleToCoreHandle ( **/ EFI_STATUS FindFileEx ( - IN CONST EFI_PEI_FV_HANDLE FvHandle, - IN CONST EFI_GUID *FileName OPTIONAL, - IN EFI_FV_FILETYPE SearchType, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle, - IN OUT EFI_PEI_FILE_HANDLE *AprioriFile OPTIONAL + IN CONST EFI_PEI_FV_HANDLE FvHandle, + IN CONST EFI_GUID *FileName OPTIONAL, + IN EFI_FV_FILETYPE SearchType, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle, + IN OUT EFI_PEI_FILE_HANDLE *AprioriFile OPTIONAL ); /** @@ -342,11 +340,11 @@ AddUnknownFormatFvInfo ( **/ EFI_STATUS FindUnknownFormatFvInfo ( - IN PEI_CORE_INSTANCE *PrivateData, - IN EFI_GUID *Format, - OUT VOID **FvInfo, - OUT UINT32 *FvInfoSize, - OUT UINT32 *AuthenticationStatus + IN PEI_CORE_INSTANCE *PrivateData, + IN EFI_GUID *Format, + OUT VOID **FvInfo, + OUT UINT32 *FvInfoSize, + OUT UINT32 *AuthenticationStatus ); /** @@ -364,9 +362,9 @@ FindUnknownFormatFvInfo ( EFI_STATUS EFIAPI ThirdPartyFvPpiNotifyCallback ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, - IN VOID *Ppi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi ); #endif diff --git a/MdeModulePkg/Core/Pei/Hob/Hob.c b/MdeModulePkg/Core/Pei/Hob/Hob.c index d36b61417e..c4882a23cd 100644 --- a/MdeModulePkg/Core/Pei/Hob/Hob.c +++ b/MdeModulePkg/Core/Pei/Hob/Hob.c @@ -24,29 +24,29 @@ EFI_STATUS EFIAPI PeiGetHobList ( IN CONST EFI_PEI_SERVICES **PeiServices, - IN OUT VOID **HobList + IN OUT VOID **HobList ) { - PEI_CORE_INSTANCE *PrivateData; + PEI_CORE_INSTANCE *PrivateData; // // Only check this parameter in debug mode // DEBUG_CODE_BEGIN (); - if (HobList == NULL) { - return EFI_INVALID_PARAMETER; - } + if (HobList == NULL) { + return EFI_INVALID_PARAMETER; + } + DEBUG_CODE_END (); - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); - *HobList = PrivateData->HobList.Raw; + *HobList = PrivateData->HobList.Raw; return EFI_SUCCESS; } - /** Add a new HOB to the HOB List. @@ -65,19 +65,18 @@ EFI_STATUS EFIAPI PeiCreateHob ( IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINT16 Type, - IN UINT16 Length, - IN OUT VOID **Hob + IN UINT16 Type, + IN UINT16 Length, + IN OUT VOID **Hob ) { - EFI_STATUS Status; - EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; - EFI_HOB_GENERIC_HEADER *HobEnd; - EFI_PHYSICAL_ADDRESS FreeMemory; - + EFI_STATUS Status; + EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; + EFI_HOB_GENERIC_HEADER *HobEnd; + EFI_PHYSICAL_ADDRESS FreeMemory; Status = PeiGetHobList (PeiServices, Hob); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -89,7 +88,8 @@ PeiCreateHob ( if (0x10000 - Length <= 0x7) { return EFI_INVALID_PARAMETER; } - Length = (UINT16)((Length + 0x7) & (~0x7)); + + Length = (UINT16)((Length + 0x7) & (~0x7)); FreeMemory = HandOffHob->EfiFreeMemoryTop - HandOffHob->EfiFreeMemoryBottom; @@ -101,19 +101,19 @@ PeiCreateHob ( return EFI_OUT_OF_RESOURCES; } - *Hob = (VOID*) (UINTN) HandOffHob->EfiEndOfHobList; - ((EFI_HOB_GENERIC_HEADER*) *Hob)->HobType = Type; - ((EFI_HOB_GENERIC_HEADER*) *Hob)->HobLength = Length; - ((EFI_HOB_GENERIC_HEADER*) *Hob)->Reserved = 0; + *Hob = (VOID *)(UINTN)HandOffHob->EfiEndOfHobList; + ((EFI_HOB_GENERIC_HEADER *)*Hob)->HobType = Type; + ((EFI_HOB_GENERIC_HEADER *)*Hob)->HobLength = Length; + ((EFI_HOB_GENERIC_HEADER *)*Hob)->Reserved = 0; - HobEnd = (EFI_HOB_GENERIC_HEADER*) ((UINTN) *Hob + Length); - HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd; + HobEnd = (EFI_HOB_GENERIC_HEADER *)((UINTN)*Hob + Length); + HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd; HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST; - HobEnd->HobLength = (UINT16) sizeof (EFI_HOB_GENERIC_HEADER); + HobEnd->HobLength = (UINT16)sizeof (EFI_HOB_GENERIC_HEADER); HobEnd->Reserved = 0; HobEnd++; - HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd; + HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd; return EFI_SUCCESS; } @@ -130,26 +130,27 @@ PeiCreateHob ( **/ EFI_STATUS PeiInstallSecHobData ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_HOB_GENERIC_HEADER *SecHobList + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_HOB_GENERIC_HEADER *SecHobList ) { - EFI_STATUS Status; - EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; - EFI_PEI_HOB_POINTERS HobStart; - EFI_PEI_HOB_POINTERS Hob; - UINTN SecHobListLength; - EFI_PHYSICAL_ADDRESS FreeMemory; - EFI_HOB_GENERIC_HEADER *HobEnd; + EFI_STATUS Status; + EFI_HOB_HANDOFF_INFO_TABLE *HandOffHob; + EFI_PEI_HOB_POINTERS HobStart; + EFI_PEI_HOB_POINTERS Hob; + UINTN SecHobListLength; + EFI_PHYSICAL_ADDRESS FreeMemory; + EFI_HOB_GENERIC_HEADER *HobEnd; HandOffHob = NULL; - Status = PeiGetHobList (PeiServices, (VOID **) &HandOffHob); - if (EFI_ERROR(Status)) { + Status = PeiGetHobList (PeiServices, (VOID **)&HandOffHob); + if (EFI_ERROR (Status)) { return Status; } + ASSERT (HandOffHob != NULL); - HobStart.Raw = (UINT8 *) SecHobList; + HobStart.Raw = (UINT8 *)SecHobList; // // The HobList must not contain a EFI_HOB_HANDOFF_INFO_TABLE HOB (PHIT) HOB. // @@ -158,8 +159,10 @@ PeiInstallSecHobData ( // Calculate the SEC HOB List length, // not including the terminated HOB(EFI_HOB_TYPE_END_OF_HOB_LIST). // - for (Hob.Raw = HobStart.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)); - SecHobListLength = (UINTN) Hob.Raw - (UINTN) HobStart.Raw; + for (Hob.Raw = HobStart.Raw; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { + } + + SecHobListLength = (UINTN)Hob.Raw - (UINTN)HobStart.Raw; // // The length must be 8-bytes aligned. // @@ -175,17 +178,17 @@ PeiInstallSecHobData ( return EFI_OUT_OF_RESOURCES; } - Hob.Raw = (UINT8 *) (UINTN) HandOffHob->EfiEndOfHobList; + Hob.Raw = (UINT8 *)(UINTN)HandOffHob->EfiEndOfHobList; CopyMem (Hob.Raw, HobStart.Raw, SecHobListLength); - HobEnd = (EFI_HOB_GENERIC_HEADER *) ((UINTN) Hob.Raw + SecHobListLength); - HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd; + HobEnd = (EFI_HOB_GENERIC_HEADER *)((UINTN)Hob.Raw + SecHobListLength); + HandOffHob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd; HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST; - HobEnd->HobLength = (UINT16) sizeof (EFI_HOB_GENERIC_HEADER); + HobEnd->HobLength = (UINT16)sizeof (EFI_HOB_GENERIC_HEADER); HobEnd->Reserved = 0; HobEnd++; - HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd; + HandOffHob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd; return EFI_SUCCESS; } @@ -208,27 +211,27 @@ PeiCoreBuildHobHandoffInfoTable ( IN UINT64 MemoryLength ) { - EFI_HOB_HANDOFF_INFO_TABLE *Hob; - EFI_HOB_GENERIC_HEADER *HobEnd; + EFI_HOB_HANDOFF_INFO_TABLE *Hob; + EFI_HOB_GENERIC_HEADER *HobEnd; - Hob = (VOID *)(UINTN)MemoryBegin; - HobEnd = (EFI_HOB_GENERIC_HEADER*) (Hob+1); - Hob->Header.HobType = EFI_HOB_TYPE_HANDOFF; - Hob->Header.HobLength = (UINT16) sizeof (EFI_HOB_HANDOFF_INFO_TABLE); - Hob->Header.Reserved = 0; + Hob = (VOID *)(UINTN)MemoryBegin; + HobEnd = (EFI_HOB_GENERIC_HEADER *)(Hob+1); + Hob->Header.HobType = EFI_HOB_TYPE_HANDOFF; + Hob->Header.HobLength = (UINT16)sizeof (EFI_HOB_HANDOFF_INFO_TABLE); + Hob->Header.Reserved = 0; - HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST; - HobEnd->HobLength = (UINT16) sizeof (EFI_HOB_GENERIC_HEADER); - HobEnd->Reserved = 0; + HobEnd->HobType = EFI_HOB_TYPE_END_OF_HOB_LIST; + HobEnd->HobLength = (UINT16)sizeof (EFI_HOB_GENERIC_HEADER); + HobEnd->Reserved = 0; - Hob->Version = EFI_HOB_HANDOFF_TABLE_VERSION; - Hob->BootMode = BootMode; + Hob->Version = EFI_HOB_HANDOFF_TABLE_VERSION; + Hob->BootMode = BootMode; Hob->EfiMemoryTop = MemoryBegin + MemoryLength; Hob->EfiMemoryBottom = MemoryBegin; Hob->EfiFreeMemoryTop = MemoryBegin + MemoryLength; - Hob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS) (UINTN) (HobEnd + 1); - Hob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS) (UINTN) HobEnd; + Hob->EfiFreeMemoryBottom = (EFI_PHYSICAL_ADDRESS)(UINTN)(HobEnd + 1); + Hob->EfiEndOfHobList = (EFI_PHYSICAL_ADDRESS)(UINTN)HobEnd; return EFI_SUCCESS; } diff --git a/MdeModulePkg/Core/Pei/Image/Image.c b/MdeModulePkg/Core/Pei/Image/Image.c index d8f4525c3f..cee9f09c6e 100644 --- a/MdeModulePkg/Core/Pei/Image/Image.c +++ b/MdeModulePkg/Core/Pei/Image/Image.c @@ -8,13 +8,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PeiMain.h" - -EFI_PEI_LOAD_FILE_PPI mPeiLoadImagePpi = { +EFI_PEI_LOAD_FILE_PPI mPeiLoadImagePpi = { PeiLoadImageLoadImageWrapper }; - -EFI_PEI_PPI_DESCRIPTOR gPpiLoadFilePpiList = { +EFI_PEI_PPI_DESCRIPTOR gPpiLoadFilePpiList = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiPeiLoadFilePpiGuid, &mPeiLoadImagePpi @@ -36,17 +34,17 @@ EFI_PEI_PPI_DESCRIPTOR gPpiLoadFilePpiList = { EFI_STATUS EFIAPI PeiImageRead ( - IN VOID *FileHandle, - IN UINTN FileOffset, - IN UINTN *ReadSize, - OUT VOID *Buffer + IN VOID *FileHandle, + IN UINTN FileOffset, + IN UINTN *ReadSize, + OUT VOID *Buffer ) { - CHAR8 *Destination8; - CHAR8 *Source8; + CHAR8 *Destination8; + CHAR8 *Source8; - Destination8 = Buffer; - Source8 = (CHAR8 *) ((UINTN) FileHandle + FileOffset); + Destination8 = Buffer; + Source8 = (CHAR8 *)((UINTN)FileHandle + FileOffset); if (Destination8 != Source8) { CopyMem (Destination8, Source8, *ReadSize); } @@ -68,59 +66,61 @@ PeiImageRead ( **/ EFI_STATUS CheckAndMarkFixLoadingMemoryUsageBitMap ( - IN PEI_CORE_INSTANCE *Private, - IN EFI_PHYSICAL_ADDRESS ImageBase, - IN UINT32 ImageSize + IN PEI_CORE_INSTANCE *Private, + IN EFI_PHYSICAL_ADDRESS ImageBase, + IN UINT32 ImageSize ) { - UINT32 DxeCodePageNumber; - UINT64 ReservedCodeSize; - EFI_PHYSICAL_ADDRESS PeiCodeBase; - UINT32 BaseOffsetPageNumber; - UINT32 TopOffsetPageNumber; - UINT32 Index; - UINT64 *MemoryUsageBitMap; - - - // - // The reserved code range includes RuntimeCodePage range, Boot time code range and PEI code range. - // - DxeCodePageNumber = PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber); - DxeCodePageNumber += PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber); - ReservedCodeSize = EFI_PAGES_TO_SIZE(DxeCodePageNumber + PcdGet32(PcdLoadFixAddressPeiCodePageNumber)); - PeiCodeBase = Private->LoadModuleAtFixAddressTopAddress - ReservedCodeSize; - - // - // Test the memory range for loading the image in the PEI code range. - // - if ((Private->LoadModuleAtFixAddressTopAddress - EFI_PAGES_TO_SIZE(DxeCodePageNumber)) < (ImageBase + ImageSize) || - (PeiCodeBase > ImageBase)) { - return EFI_NOT_FOUND; - } - - // - // Test if the memory is available or not. - // - MemoryUsageBitMap = Private->PeiCodeMemoryRangeUsageBitMap; - BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - PeiCodeBase)); - TopOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - PeiCodeBase)); - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - if ((MemoryUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) { - // - // This page is already used. - // - return EFI_NOT_FOUND; - } - } - - // - // Being here means the memory range is available. So mark the bits for the memory range - // - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - MemoryUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64)); - } - return EFI_SUCCESS; + UINT32 DxeCodePageNumber; + UINT64 ReservedCodeSize; + EFI_PHYSICAL_ADDRESS PeiCodeBase; + UINT32 BaseOffsetPageNumber; + UINT32 TopOffsetPageNumber; + UINT32 Index; + UINT64 *MemoryUsageBitMap; + + // + // The reserved code range includes RuntimeCodePage range, Boot time code range and PEI code range. + // + DxeCodePageNumber = PcdGet32 (PcdLoadFixAddressBootTimeCodePageNumber); + DxeCodePageNumber += PcdGet32 (PcdLoadFixAddressRuntimeCodePageNumber); + ReservedCodeSize = EFI_PAGES_TO_SIZE (DxeCodePageNumber + PcdGet32 (PcdLoadFixAddressPeiCodePageNumber)); + PeiCodeBase = Private->LoadModuleAtFixAddressTopAddress - ReservedCodeSize; + + // + // Test the memory range for loading the image in the PEI code range. + // + if (((Private->LoadModuleAtFixAddressTopAddress - EFI_PAGES_TO_SIZE (DxeCodePageNumber)) < (ImageBase + ImageSize)) || + (PeiCodeBase > ImageBase)) + { + return EFI_NOT_FOUND; + } + + // + // Test if the memory is available or not. + // + MemoryUsageBitMap = Private->PeiCodeMemoryRangeUsageBitMap; + BaseOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase - PeiCodeBase)); + TopOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase + ImageSize - PeiCodeBase)); + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + if ((MemoryUsageBitMap[Index / 64] & LShiftU64 (1, (Index % 64))) != 0) { + // + // This page is already used. + // + return EFI_NOT_FOUND; + } + } + + // + // Being here means the memory range is available. So mark the bits for the memory range + // + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + MemoryUsageBitMap[Index / 64] |= LShiftU64 (1, (Index % 64)); + } + + return EFI_SUCCESS; } + /** Get the fixed loading address from image header assigned by build tool. This function only be called @@ -135,109 +135,114 @@ CheckAndMarkFixLoadingMemoryUsageBitMap ( **/ EFI_STATUS -GetPeCoffImageFixLoadingAssignedAddress( +GetPeCoffImageFixLoadingAssignedAddress ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext, IN PEI_CORE_INSTANCE *Private ) { - UINTN SectionHeaderOffset; - EFI_STATUS Status; - EFI_IMAGE_SECTION_HEADER SectionHeader; - EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; - EFI_PHYSICAL_ADDRESS FixLoadingAddress; - UINT16 Index; - UINTN Size; - UINT16 NumberOfSections; - UINT64 ValueInSectionHeader; - - - FixLoadingAddress = 0; - Status = EFI_NOT_FOUND; - - // - // Get PeHeader pointer - // - ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset); - if (ImageContext->IsTeImage) { - // - // for TE image, the fix loading address is saved in first section header that doesn't point - // to code section. - // - SectionHeaderOffset = sizeof (EFI_TE_IMAGE_HEADER); - NumberOfSections = ImgHdr->Te.NumberOfSections; - } else { - SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + - sizeof (UINT32) + - sizeof (EFI_IMAGE_FILE_HEADER) + - ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; - NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; - } - // - // Get base address from the first section header that doesn't point to code section. - // - for (Index = 0; Index < NumberOfSections; Index++) { - // - // Read section header from file - // - Size = sizeof (EFI_IMAGE_SECTION_HEADER); - Status = ImageContext->ImageRead ( - ImageContext->Handle, - SectionHeaderOffset, - &Size, - &SectionHeader - ); - if (EFI_ERROR (Status)) { - return Status; - } - - Status = EFI_NOT_FOUND; - - if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { - // - // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header - // that doesn't point to code section in image header, as well as ImageBase field of image header. A notable thing is - // that for PEIM, the value in ImageBase field may not be equal to the value in PointerToRelocations & PointerToLineNumbers because - // for XIP PEIM, ImageBase field holds the image base address running on the Flash. And PointerToRelocations & PointerToLineNumbers - // hold the image base address when it is shadow to the memory. And there is an assumption that when the feature is enabled, if a - // module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers fields should NOT be Zero, or - // else, these 2 fields should be set to Zero - // - ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations); - if (ValueInSectionHeader != 0) { - // - // Found first section header that doesn't point to code section. - // - if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) > 0) { - // - // When LMFA feature is configured as Load Module at Fixed Absolute Address mode, PointerToRelocations & PointerToLineNumbers field - // hold the absolute address of image base running in memory - // - FixLoadingAddress = ValueInSectionHeader; - } else { - // - // When LMFA feature is configured as Load Module at Fixed offset mode, PointerToRelocations & PointerToLineNumbers field - // hold the offset relative to a platform-specific top address. - // - FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(Private->LoadModuleAtFixAddressTopAddress + (INT64)ValueInSectionHeader); - } - // - // Check if the memory range is available. - // - Status = CheckAndMarkFixLoadingMemoryUsageBitMap (Private, FixLoadingAddress, (UINT32) ImageContext->ImageSize); - if (!EFI_ERROR(Status)) { - // - // The assigned address is valid. Return the specified loading address - // - ImageContext->ImageAddress = FixLoadingAddress; - } - } - break; - } - SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); - } - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status= %r \n", (VOID *)(UINTN)FixLoadingAddress, Status)); - return Status; + UINTN SectionHeaderOffset; + EFI_STATUS Status; + EFI_IMAGE_SECTION_HEADER SectionHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + EFI_PHYSICAL_ADDRESS FixLoadingAddress; + UINT16 Index; + UINTN Size; + UINT16 NumberOfSections; + UINT64 ValueInSectionHeader; + + FixLoadingAddress = 0; + Status = EFI_NOT_FOUND; + + // + // Get PeHeader pointer + // + ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8 *)ImageContext->Handle + ImageContext->PeCoffHeaderOffset); + if (ImageContext->IsTeImage) { + // + // for TE image, the fix loading address is saved in first section header that doesn't point + // to code section. + // + SectionHeaderOffset = sizeof (EFI_TE_IMAGE_HEADER); + NumberOfSections = ImgHdr->Te.NumberOfSections; + } else { + SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; + NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; + } + + // + // Get base address from the first section header that doesn't point to code section. + // + for (Index = 0; Index < NumberOfSections; Index++) { + // + // Read section header from file + // + Size = sizeof (EFI_IMAGE_SECTION_HEADER); + Status = ImageContext->ImageRead ( + ImageContext->Handle, + SectionHeaderOffset, + &Size, + &SectionHeader + ); + if (EFI_ERROR (Status)) { + return Status; + } + + Status = EFI_NOT_FOUND; + + if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { + // + // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header + // that doesn't point to code section in image header, as well as ImageBase field of image header. A notable thing is + // that for PEIM, the value in ImageBase field may not be equal to the value in PointerToRelocations & PointerToLineNumbers because + // for XIP PEIM, ImageBase field holds the image base address running on the Flash. And PointerToRelocations & PointerToLineNumbers + // hold the image base address when it is shadow to the memory. And there is an assumption that when the feature is enabled, if a + // module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers fields should NOT be Zero, or + // else, these 2 fields should be set to Zero + // + ValueInSectionHeader = ReadUnaligned64 ((UINT64 *)&SectionHeader.PointerToRelocations); + if (ValueInSectionHeader != 0) { + // + // Found first section header that doesn't point to code section. + // + if ((INT64)PcdGet64 (PcdLoadModuleAtFixAddressEnable) > 0) { + // + // When LMFA feature is configured as Load Module at Fixed Absolute Address mode, PointerToRelocations & PointerToLineNumbers field + // hold the absolute address of image base running in memory + // + FixLoadingAddress = ValueInSectionHeader; + } else { + // + // When LMFA feature is configured as Load Module at Fixed offset mode, PointerToRelocations & PointerToLineNumbers field + // hold the offset relative to a platform-specific top address. + // + FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(Private->LoadModuleAtFixAddressTopAddress + (INT64)ValueInSectionHeader); + } + + // + // Check if the memory range is available. + // + Status = CheckAndMarkFixLoadingMemoryUsageBitMap (Private, FixLoadingAddress, (UINT32)ImageContext->ImageSize); + if (!EFI_ERROR (Status)) { + // + // The assigned address is valid. Return the specified loading address + // + ImageContext->ImageAddress = FixLoadingAddress; + } + } + + break; + } + + SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); + } + + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status= %r \n", (VOID *)(UINTN)FixLoadingAddress, Status)); + return Status; } + /** Loads and relocates a PE/COFF image into memory. @@ -258,30 +263,30 @@ GetPeCoffImageFixLoadingAssignedAddress( **/ EFI_STATUS LoadAndRelocatePeCoffImage ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN VOID *Pe32Data, - OUT EFI_PHYSICAL_ADDRESS *ImageAddress, - OUT UINT64 *ImageSize, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint + IN EFI_PEI_FILE_HANDLE FileHandle, + IN VOID *Pe32Data, + OUT EFI_PHYSICAL_ADDRESS *ImageAddress, + OUT UINT64 *ImageSize, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint ) { - EFI_STATUS Status; - PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; - PEI_CORE_INSTANCE *Private; - UINT64 AlignImageSize; - BOOLEAN IsXipImage; - EFI_STATUS ReturnStatus; - BOOLEAN IsS3Boot; - BOOLEAN IsPeiModule; - BOOLEAN IsRegisterForShadow; - EFI_FV_FILE_INFO FileInfo; + EFI_STATUS Status; + PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; + PEI_CORE_INSTANCE *Private; + UINT64 AlignImageSize; + BOOLEAN IsXipImage; + EFI_STATUS ReturnStatus; + BOOLEAN IsS3Boot; + BOOLEAN IsPeiModule; + BOOLEAN IsRegisterForShadow; + EFI_FV_FILE_INFO FileInfo; Private = PEI_CORE_INSTANCE_FROM_PS_THIS (GetPeiServicesTablePointer ()); ReturnStatus = EFI_SUCCESS; IsXipImage = FALSE; ZeroMem (&ImageContext, sizeof (ImageContext)); - ImageContext.Handle = Pe32Data; + ImageContext.Handle = Pe32Data; ImageContext.ImageRead = PeiImageRead; Status = PeCoffLoaderGetImageInfo (&ImageContext); @@ -296,16 +301,18 @@ LoadAndRelocatePeCoffImage ( if (Private->HobList.HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) { IsS3Boot = TRUE; } + IsRegisterForShadow = FALSE; - if ((Private->CurrentFileHandle == FileHandle) - && (Private->Fv[Private->CurrentPeimFvCount].PeimState[Private->CurrentPeimCount] == PEIM_STATE_REGISTER_FOR_SHADOW)) { + if ( (Private->CurrentFileHandle == FileHandle) + && (Private->Fv[Private->CurrentPeimFvCount].PeimState[Private->CurrentPeimCount] == PEIM_STATE_REGISTER_FOR_SHADOW)) + { IsRegisterForShadow = TRUE; } // // XIP image that ImageAddress is same to Image handle. // - if (ImageContext.ImageAddress == (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) { + if (ImageContext.ImageAddress == (EFI_PHYSICAL_ADDRESS)(UINTN)Pe32Data) { IsXipImage = TRUE; } @@ -319,9 +326,10 @@ LoadAndRelocatePeCoffImage ( // Check whether the file type is PEI module. // IsPeiModule = FALSE; - if (FileInfo.FileType == EFI_FV_FILETYPE_PEI_CORE || - FileInfo.FileType == EFI_FV_FILETYPE_PEIM || - FileInfo.FileType == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER) { + if ((FileInfo.FileType == EFI_FV_FILETYPE_PEI_CORE) || + (FileInfo.FileType == EFI_FV_FILETYPE_PEIM) || + (FileInfo.FileType == EFI_FV_FILETYPE_COMBINED_PEIM_DRIVER)) + { IsPeiModule = TRUE; } @@ -332,14 +340,15 @@ LoadAndRelocatePeCoffImage ( ((!IsPeiModule) || PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) || (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot))) - ) { - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "The image at 0x%08x without reloc section can't be loaded into memory\n", (UINTN) Pe32Data)); + ) + { + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "The image at 0x%08x without reloc section can't be loaded into memory\n", (UINTN)Pe32Data)); } // // Set default base address to current image address. // - ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data; + ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Pe32Data; // // Allocate Memory for the image when memory is ready, and image is relocatable. @@ -350,12 +359,13 @@ LoadAndRelocatePeCoffImage ( ((!IsPeiModule) || PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || (!IsS3Boot && (PcdGetBool (PcdShadowPeimOnBoot) || IsRegisterForShadow)) || (IsS3Boot && PcdGetBool (PcdShadowPeimOnS3Boot))) - ) { + ) + { // // Allocate more buffer to avoid buffer overflow. // if (ImageContext.IsTeImage) { - AlignImageSize = ImageContext.ImageSize + ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER); + AlignImageSize = ImageContext.ImageSize + ((EFI_TE_IMAGE_HEADER *)Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER); } else { AlignImageSize = ImageContext.ImageSize; } @@ -364,38 +374,44 @@ LoadAndRelocatePeCoffImage ( AlignImageSize += ImageContext.SectionAlignment; } - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { - Status = GetPeCoffImageFixLoadingAssignedAddress(&ImageContext, Private); - if (EFI_ERROR (Status)){ + if ((PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) && (Private->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { + Status = GetPeCoffImageFixLoadingAssignedAddress (&ImageContext, Private); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n")); // // The PEIM is not assigned valid address, try to allocate page to load it. // - Status = PeiServicesAllocatePages (EfiBootServicesCode, - EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize), - &ImageContext.ImageAddress); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + EFI_SIZE_TO_PAGES ((UINT32)AlignImageSize), + &ImageContext.ImageAddress + ); } } else { - Status = PeiServicesAllocatePages (EfiBootServicesCode, - EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize), - &ImageContext.ImageAddress); + Status = PeiServicesAllocatePages ( + EfiBootServicesCode, + EFI_SIZE_TO_PAGES ((UINT32)AlignImageSize), + &ImageContext.ImageAddress + ); } + if (!EFI_ERROR (Status)) { // // Adjust the Image Address to make sure it is section alignment. // if (ImageContext.SectionAlignment > EFI_PAGE_SIZE) { ImageContext.ImageAddress = - (ImageContext.ImageAddress + ImageContext.SectionAlignment - 1) & - ~((UINTN)ImageContext.SectionAlignment - 1); + (ImageContext.ImageAddress + ImageContext.SectionAlignment - 1) & + ~((UINTN)ImageContext.SectionAlignment - 1); } + // // Fix alignment requirement when Load IPF TeImage into memory. // Skip the reserved space for the stripped PeHeader when load TeImage into memory. // if (ImageContext.IsTeImage) { ImageContext.ImageAddress = ImageContext.ImageAddress + - ((EFI_TE_IMAGE_HEADER *) Pe32Data)->StrippedSize - + ((EFI_TE_IMAGE_HEADER *)Pe32Data)->StrippedSize - sizeof (EFI_TE_IMAGE_HEADER); } } else { @@ -406,8 +422,8 @@ LoadAndRelocatePeCoffImage ( // // XIP image can still be invoked. // - ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data; - ReturnStatus = EFI_WARN_BUFFER_TOO_SMALL; + ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)Pe32Data; + ReturnStatus = EFI_WARN_BUFFER_TOO_SMALL; } else { // // Non XIP image can't be loaded because no enough memory is allocated. @@ -424,10 +440,12 @@ LoadAndRelocatePeCoffImage ( Status = PeCoffLoaderLoadImage (&ImageContext); if (EFI_ERROR (Status)) { if (ImageContext.ImageError == IMAGE_ERROR_INVALID_SECTION_ALIGNMENT) { - DEBUG ((DEBUG_ERROR, "PEIM Image Address 0x%11p doesn't meet with section alignment 0x%x.\n", (VOID*)(UINTN)ImageContext.ImageAddress, ImageContext.SectionAlignment)); + DEBUG ((DEBUG_ERROR, "PEIM Image Address 0x%11p doesn't meet with section alignment 0x%x.\n", (VOID *)(UINTN)ImageContext.ImageAddress, ImageContext.SectionAlignment)); } + return Status; } + // // Relocate the image in our new buffer // @@ -439,7 +457,7 @@ LoadAndRelocatePeCoffImage ( // // Flush the instruction cache so the image data is written before we execute it // - if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) { + if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN)Pe32Data) { InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize); } @@ -462,15 +480,15 @@ LoadAndRelocatePeCoffImage ( **/ EFI_STATUS LoadAndRelocatePeCoffImageInPlace ( - IN VOID *Pe32Data, - IN VOID *ImageAddress + IN VOID *Pe32Data, + IN VOID *ImageAddress ) { - EFI_STATUS Status; - PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; + EFI_STATUS Status; + PE_COFF_LOADER_IMAGE_CONTEXT ImageContext; ZeroMem (&ImageContext, sizeof (ImageContext)); - ImageContext.Handle = Pe32Data; + ImageContext.Handle = Pe32Data; ImageContext.ImageRead = PeiImageRead; Status = PeCoffLoaderGetImageInfo (&ImageContext); @@ -479,7 +497,7 @@ LoadAndRelocatePeCoffImageInPlace ( return Status; } - ImageContext.ImageAddress = (PHYSICAL_ADDRESS)(UINTN) ImageAddress; + ImageContext.ImageAddress = (PHYSICAL_ADDRESS)(UINTN)ImageAddress; // // Load the image in place @@ -502,7 +520,7 @@ LoadAndRelocatePeCoffImageInPlace ( // // Flush the instruction cache so the image data is written before we execute it // - if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN) Pe32Data) { + if (ImageContext.ImageAddress != (EFI_PHYSICAL_ADDRESS)(UINTN)Pe32Data) { InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize); } @@ -525,10 +543,10 @@ PeiGetPe32Data ( OUT VOID **Pe32Data ) { - EFI_STATUS Status; - EFI_SECTION_TYPE SearchType1; - EFI_SECTION_TYPE SearchType2; - UINT32 AuthenticationState; + EFI_STATUS Status; + EFI_SECTION_TYPE SearchType1; + EFI_SECTION_TYPE SearchType2; + UINT32 AuthenticationState; *Pe32Data = NULL; @@ -563,6 +581,7 @@ PeiGetPe32Data ( &AuthenticationState ); } + return Status; } @@ -588,22 +607,22 @@ PeiGetPe32Data ( **/ EFI_STATUS PeiLoadImageLoadImage ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT EFI_PHYSICAL_ADDRESS *ImageAddressArg OPTIONAL, - OUT UINT64 *ImageSizeArg OPTIONAL, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint, - OUT UINT32 *AuthenticationState + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT EFI_PHYSICAL_ADDRESS *ImageAddressArg OPTIONAL, + OUT UINT64 *ImageSizeArg OPTIONAL, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint, + OUT UINT32 *AuthenticationState ) { - EFI_STATUS Status; - VOID *Pe32Data; - EFI_PHYSICAL_ADDRESS ImageAddress; - UINT64 ImageSize; - EFI_PHYSICAL_ADDRESS ImageEntryPoint; - UINT16 Machine; - EFI_SECTION_TYPE SearchType1; - EFI_SECTION_TYPE SearchType2; + EFI_STATUS Status; + VOID *Pe32Data; + EFI_PHYSICAL_ADDRESS ImageAddress; + UINT64 ImageSize; + EFI_PHYSICAL_ADDRESS ImageEntryPoint; + UINT16 Machine; + EFI_SECTION_TYPE SearchType1; + EFI_SECTION_TYPE SearchType2; *EntryPoint = 0; ImageSize = 0; @@ -654,12 +673,12 @@ PeiLoadImageLoadImage ( // If memory is installed, perform the shadow operations // Status = LoadAndRelocatePeCoffImage ( - FileHandle, - Pe32Data, - &ImageAddress, - &ImageSize, - &ImageEntryPoint - ); + FileHandle, + Pe32Data, + &ImageAddress, + &ImageSize, + &ImageEntryPoint + ); if (EFI_ERROR (Status)) { return Status; @@ -668,7 +687,7 @@ PeiLoadImageLoadImage ( // // Got the entry point from the loaded Pe32Data // - Pe32Data = (VOID *) ((UINTN) ImageAddress); + Pe32Data = (VOID *)((UINTN)ImageAddress); *EntryPoint = ImageEntryPoint; Machine = PeCoffLoaderGetMachineType (Pe32Data); @@ -688,71 +707,70 @@ PeiLoadImageLoadImage ( } DEBUG_CODE_BEGIN (); - CHAR8 *AsciiString; - CHAR8 EfiFileName[512]; - INT32 Index; - INT32 StartIndex; + CHAR8 *AsciiString; + CHAR8 EfiFileName[512]; + INT32 Index; + INT32 StartIndex; + // + // Print debug message: Loading PEIM at 0x12345678 EntryPoint=0x12345688 Driver.efi + // + if (Machine != EFI_IMAGE_MACHINE_IA64) { + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)*EntryPoint)); + } else { // - // Print debug message: Loading PEIM at 0x12345678 EntryPoint=0x12345688 Driver.efi + // For IPF Image, the real entry point should be print. // - if (Machine != EFI_IMAGE_MACHINE_IA64) { - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)*EntryPoint)); - } else { - // - // For IPF Image, the real entry point should be print. - // - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)(*(UINT64 *)(UINTN)*EntryPoint))); - } + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "Loading PEIM at 0x%11p EntryPoint=0x%11p ", (VOID *)(UINTN)ImageAddress, (VOID *)(UINTN)(*(UINT64 *)(UINTN)*EntryPoint))); + } - // - // Print Module Name by PeImage PDB file name. - // - AsciiString = PeCoffLoaderGetPdbPointer (Pe32Data); + // + // Print Module Name by PeImage PDB file name. + // + AsciiString = PeCoffLoaderGetPdbPointer (Pe32Data); - if (AsciiString != NULL) { - StartIndex = 0; - for (Index = 0; AsciiString[Index] != 0; Index++) { - if (AsciiString[Index] == '\\' || AsciiString[Index] == '/') { - StartIndex = Index + 1; - } + if (AsciiString != NULL) { + StartIndex = 0; + for (Index = 0; AsciiString[Index] != 0; Index++) { + if ((AsciiString[Index] == '\\') || (AsciiString[Index] == '/')) { + StartIndex = Index + 1; } + } - // - // Copy the PDB file name to our temporary string, and replace .pdb with .efi - // The PDB file name is limited in the range of 0~511. - // If the length is bigger than 511, trim the redundant characters to avoid overflow in array boundary. - // - for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { - EfiFileName[Index] = AsciiString[Index + StartIndex]; - if (EfiFileName[Index] == 0) { - EfiFileName[Index] = '.'; - } - if (EfiFileName[Index] == '.') { - EfiFileName[Index + 1] = 'e'; - EfiFileName[Index + 2] = 'f'; - EfiFileName[Index + 3] = 'i'; - EfiFileName[Index + 4] = 0; - break; - } + // + // Copy the PDB file name to our temporary string, and replace .pdb with .efi + // The PDB file name is limited in the range of 0~511. + // If the length is bigger than 511, trim the redundant characters to avoid overflow in array boundary. + // + for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { + EfiFileName[Index] = AsciiString[Index + StartIndex]; + if (EfiFileName[Index] == 0) { + EfiFileName[Index] = '.'; } - if (Index == sizeof (EfiFileName) - 4) { - EfiFileName[Index] = 0; + if (EfiFileName[Index] == '.') { + EfiFileName[Index + 1] = 'e'; + EfiFileName[Index + 2] = 'f'; + EfiFileName[Index + 3] = 'i'; + EfiFileName[Index + 4] = 0; + break; } + } - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); + if (Index == sizeof (EfiFileName) - 4) { + EfiFileName[Index] = 0; } + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); + } + DEBUG_CODE_END (); DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n")); return EFI_SUCCESS; - } - /** The wrapper function of PeiLoadImageLoadImage(). @@ -811,7 +829,7 @@ RelocationIsStrip ( // // DOS image header is present, so read the PE header after the DOS image header. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff)); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff)); } else { // // DOS image header is not present, so PE header is at the image base. @@ -836,7 +854,7 @@ RelocationIsStrip ( } else { return FALSE; } - } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { + } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { if ((Hdr.Pe32->FileHeader.Characteristics & EFI_IMAGE_FILE_RELOCS_STRIPPED) != 0) { return TRUE; } else { @@ -865,20 +883,20 @@ RelocationIsStrip ( **/ EFI_STATUS PeiLoadImage ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINT8 PeimState, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint, - OUT UINT32 *AuthenticationState + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINT8 PeimState, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint, + OUT UINT32 *AuthenticationState ) { - EFI_STATUS PpiStatus; - EFI_STATUS Status; - UINTN Index; - EFI_PEI_LOAD_FILE_PPI *LoadFile; - EFI_PHYSICAL_ADDRESS ImageAddress; - UINT64 ImageSize; - BOOLEAN IsStrip; + EFI_STATUS PpiStatus; + EFI_STATUS Status; + UINTN Index; + EFI_PEI_LOAD_FILE_PPI *LoadFile; + EFI_PHYSICAL_ADDRESS ImageAddress; + UINT64 ImageSize; + BOOLEAN IsStrip; IsStrip = FALSE; // @@ -895,19 +913,19 @@ PeiLoadImage ( ); if (!EFI_ERROR (PpiStatus)) { Status = LoadFile->LoadFile ( - LoadFile, - FileHandle, - &ImageAddress, - &ImageSize, - EntryPoint, - AuthenticationState - ); - if (!EFI_ERROR (Status) || Status == EFI_WARN_BUFFER_TOO_SMALL) { + LoadFile, + FileHandle, + &ImageAddress, + &ImageSize, + EntryPoint, + AuthenticationState + ); + if (!EFI_ERROR (Status) || (Status == EFI_WARN_BUFFER_TOO_SMALL)) { // // The shadowed PEIM must be relocatable. // if (PeimState == PEIM_STATE_REGISTER_FOR_SHADOW) { - IsStrip = RelocationIsStrip ((VOID *) (UINTN) ImageAddress); + IsStrip = RelocationIsStrip ((VOID *)(UINTN)ImageAddress); ASSERT (!IsStrip); if (IsStrip) { return EFI_UNSUPPORTED; @@ -917,20 +935,21 @@ PeiLoadImage ( // // The image to be started must have the machine type supported by PeiCore. // - ASSERT (EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *) (UINTN) ImageAddress))); - if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *) (UINTN) ImageAddress))) { + ASSERT (EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *)(UINTN)ImageAddress))); + if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (PeCoffLoaderGetMachineType ((VOID *)(UINTN)ImageAddress))) { return EFI_UNSUPPORTED; } + return EFI_SUCCESS; } } + Index++; } while (!EFI_ERROR (PpiStatus)); return PpiStatus; } - /** Install Pei Load File PPI. @@ -942,8 +961,8 @@ PeiLoadImage ( **/ VOID InitializeImageServices ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_INSTANCE *OldCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_INSTANCE *OldCoreData ) { if (OldCoreData == NULL) { diff --git a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c index 53c9eaceb0..3b2e15699f 100644 --- a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c +++ b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c @@ -27,22 +27,20 @@ InitializeMemoryServices ( IN PEI_CORE_INSTANCE *OldCoreData ) { - - PrivateData->SwitchStackSignal = FALSE; + PrivateData->SwitchStackSignal = FALSE; // // First entering PeiCore, following code will initialized some field // in PeiCore's private data according to hand off data from SEC core. // if (OldCoreData == NULL) { - PrivateData->PeiMemoryInstalled = FALSE; PrivateData->HobList.Raw = SecCoreData->PeiTemporaryRamBase; PeiCoreBuildHobHandoffInfoTable ( BOOT_WITH_FULL_CONFIGURATION, - (EFI_PHYSICAL_ADDRESS) (UINTN) SecCoreData->PeiTemporaryRamBase, - (UINTN) SecCoreData->PeiTemporaryRamSize + (EFI_PHYSICAL_ADDRESS)(UINTN)SecCoreData->PeiTemporaryRamBase, + (UINTN)SecCoreData->PeiTemporaryRamSize ); // @@ -78,7 +76,7 @@ PeiInstallPeiMemory ( IN UINT64 MemoryLength ) { - PEI_CORE_INSTANCE *PrivateData; + PEI_CORE_INSTANCE *PrivateData; DEBUG ((DEBUG_INFO, "PeiInstallPeiMemory MemoryBegin 0x%LX, MemoryLength 0x%LX\n", MemoryBegin, MemoryLength)); PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); @@ -98,7 +96,7 @@ PeiInstallPeiMemory ( PrivateData->PhysicalMemoryLength = MemoryLength; PrivateData->FreePhysicalMemoryTop = MemoryBegin + MemoryLength; - PrivateData->SwitchStackSignal = TRUE; + PrivateData->SwitchStackSignal = TRUE; return EFI_SUCCESS; } @@ -113,25 +111,26 @@ PeiInstallPeiMemory ( **/ VOID MigrateMemoryPages ( - IN PEI_CORE_INSTANCE *Private, - IN BOOLEAN TemporaryRamMigrated + IN PEI_CORE_INSTANCE *Private, + IN BOOLEAN TemporaryRamMigrated ) { - EFI_PHYSICAL_ADDRESS NewMemPagesBase; - EFI_PHYSICAL_ADDRESS MemPagesBase; + EFI_PHYSICAL_ADDRESS NewMemPagesBase; + EFI_PHYSICAL_ADDRESS MemPagesBase; - Private->MemoryPages.Size = (UINTN) (Private->HobList.HandoffInformationTable->EfiMemoryTop - - Private->HobList.HandoffInformationTable->EfiFreeMemoryTop); + Private->MemoryPages.Size = (UINTN)(Private->HobList.HandoffInformationTable->EfiMemoryTop - + Private->HobList.HandoffInformationTable->EfiFreeMemoryTop); if (Private->MemoryPages.Size == 0) { // // No any memory page allocated in pre-memory phase. // return; } + Private->MemoryPages.Base = Private->HobList.HandoffInformationTable->EfiFreeMemoryTop; ASSERT (Private->MemoryPages.Size <= Private->FreePhysicalMemoryTop); - NewMemPagesBase = Private->FreePhysicalMemoryTop - Private->MemoryPages.Size; + NewMemPagesBase = Private->FreePhysicalMemoryTop - Private->MemoryPages.Size; NewMemPagesBase &= ~(UINT64)EFI_PAGE_MASK; ASSERT (NewMemPagesBase >= Private->PhysicalMemoryBegin); // @@ -148,6 +147,7 @@ MigrateMemoryPages ( } else { MemPagesBase -= Private->HeapOffset; } + CopyMem ((VOID *)(UINTN)NewMemPagesBase, (VOID *)(UINTN)MemPagesBase, Private->MemoryPages.Size); } else { CopyMem ((VOID *)(UINTN)NewMemPagesBase, (VOID *)(UINTN)Private->MemoryPages.Base, Private->MemoryPages.Size); @@ -155,13 +155,13 @@ MigrateMemoryPages ( if (NewMemPagesBase >= Private->MemoryPages.Base) { Private->MemoryPages.OffsetPositive = TRUE; - Private->MemoryPages.Offset = (UINTN)(NewMemPagesBase - Private->MemoryPages.Base); + Private->MemoryPages.Offset = (UINTN)(NewMemPagesBase - Private->MemoryPages.Base); } else { Private->MemoryPages.OffsetPositive = FALSE; - Private->MemoryPages.Offset = (UINTN)(Private->MemoryPages.Base - NewMemPagesBase); + Private->MemoryPages.Offset = (UINTN)(Private->MemoryPages.Base - NewMemPagesBase); } - DEBUG ((DEBUG_INFO, "Pages Offset = 0x%lX\n", (UINT64) Private->MemoryPages.Offset)); + DEBUG ((DEBUG_INFO, "Pages Offset = 0x%lX\n", (UINT64)Private->MemoryPages.Offset)); Private->FreePhysicalMemoryTop = NewMemPagesBase; } @@ -174,30 +174,31 @@ MigrateMemoryPages ( **/ VOID RemoveFvHobsInTemporaryMemory ( - IN PEI_CORE_INSTANCE *Private + IN PEI_CORE_INSTANCE *Private ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; DEBUG ((DEBUG_INFO, "Removing FVs in FV HOB not already migrated to permanent memory.\n")); for (Hob.Raw = GetHobList (); !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) { - if (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV || GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2 || GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3) { + if ((GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) || (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) || (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3)) { FirmwareVolumeHob = Hob.FirmwareVolume; DEBUG ((DEBUG_INFO, " Found FV HOB.\n")); DEBUG (( - DEBUG_INFO, - " BA=%016lx L=%016lx\n", - FirmwareVolumeHob->BaseAddress, - FirmwareVolumeHob->Length - )); + DEBUG_INFO, + " BA=%016lx L=%016lx\n", + FirmwareVolumeHob->BaseAddress, + FirmwareVolumeHob->Length + )); if ( - !( - ((EFI_PHYSICAL_ADDRESS) (UINTN) FirmwareVolumeHob->BaseAddress >= Private->PhysicalMemoryBegin) && - (((EFI_PHYSICAL_ADDRESS) (UINTN) FirmwareVolumeHob->BaseAddress + (FirmwareVolumeHob->Length - 1)) < Private->FreePhysicalMemoryTop) + !( + ((EFI_PHYSICAL_ADDRESS)(UINTN)FirmwareVolumeHob->BaseAddress >= Private->PhysicalMemoryBegin) && + (((EFI_PHYSICAL_ADDRESS)(UINTN)FirmwareVolumeHob->BaseAddress + (FirmwareVolumeHob->Length - 1)) < Private->FreePhysicalMemoryTop) + ) ) - ) { + { DEBUG ((DEBUG_INFO, " Removing FV HOB to an FV in T-RAM (was not migrated).\n")); Hob.Header->HobType = EFI_HOB_TYPE_UNUSED; } @@ -216,15 +217,15 @@ RemoveFvHobsInTemporaryMemory ( **/ VOID ConvertFvHob ( - IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN OrgFvHandle, - IN UINTN FvHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN UINTN OrgFvHandle, + IN UINTN FvHandle ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; - EFI_HOB_FIRMWARE_VOLUME2 *FirmwareVolume2Hob; - EFI_HOB_FIRMWARE_VOLUME3 *FirmwareVolume3Hob; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_FIRMWARE_VOLUME *FirmwareVolumeHob; + EFI_HOB_FIRMWARE_VOLUME2 *FirmwareVolume2Hob; + EFI_HOB_FIRMWARE_VOLUME3 *FirmwareVolume3Hob; DEBUG ((DEBUG_INFO, "Converting FVs in FV HOB.\n")); @@ -257,13 +258,13 @@ ConvertFvHob ( **/ VOID ConvertMemoryAllocationHobs ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; - EFI_PHYSICAL_ADDRESS OldMemPagesBase; - UINTN OldMemPagesSize; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + EFI_PHYSICAL_ADDRESS OldMemPagesBase; + UINTN OldMemPagesSize; if (PrivateData->MemoryPages.Size == 0) { // @@ -276,12 +277,13 @@ ConvertMemoryAllocationHobs ( OldMemPagesSize = PrivateData->MemoryPages.Size; MemoryAllocationHob = NULL; - Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { - MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; + MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; if ((MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress >= OldMemPagesBase) && (MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress < (OldMemPagesBase + OldMemPagesSize)) - ) { + ) + { if (PrivateData->MemoryPages.OffsetPositive) { MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress += PrivateData->MemoryPages.Offset; } else { @@ -306,22 +308,22 @@ ConvertMemoryAllocationHobs ( **/ VOID InternalBuildMemoryAllocationHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN EFI_MEMORY_TYPE MemoryType + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN EFI_MEMORY_TYPE MemoryType ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; // // Search unused(freed) memory allocation HOB. // MemoryAllocationHob = NULL; - Hob.Raw = GetFirstHob (EFI_HOB_TYPE_UNUSED); + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_UNUSED); while (Hob.Raw != NULL) { if (Hob.Header->HobLength == sizeof (EFI_HOB_MEMORY_ALLOCATION)) { - MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; + MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; break; } @@ -370,14 +372,15 @@ InternalBuildMemoryAllocationHob ( **/ VOID UpdateOrSplitMemoryAllocationHob ( - IN OUT EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob, - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINT64 Bytes, - IN EFI_MEMORY_TYPE MemoryType + IN OUT EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob, + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINT64 Bytes, + IN EFI_MEMORY_TYPE MemoryType ) { if ((Memory + Bytes) < - (MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress + MemoryAllocationHob->AllocDescriptor.MemoryLength)) { + (MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress + MemoryAllocationHob->AllocDescriptor.MemoryLength)) + { // // Last pages need to be split out. // @@ -403,8 +406,8 @@ UpdateOrSplitMemoryAllocationHob ( // Update the memory allocation HOB. // MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress = Memory; - MemoryAllocationHob->AllocDescriptor.MemoryLength = Bytes; - MemoryAllocationHob->AllocDescriptor.MemoryType = MemoryType; + MemoryAllocationHob->AllocDescriptor.MemoryLength = Bytes; + MemoryAllocationHob->AllocDescriptor.MemoryType = MemoryType; } /** @@ -419,34 +422,34 @@ MergeFreeMemoryInMemoryAllocationHob ( VOID ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_PEI_HOB_POINTERS Hob2; - EFI_HOB_MEMORY_ALLOCATION *MemoryHob; - EFI_HOB_MEMORY_ALLOCATION *MemoryHob2; - UINT64 Start; - UINT64 End; - BOOLEAN Merged; + EFI_PEI_HOB_POINTERS Hob; + EFI_PEI_HOB_POINTERS Hob2; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob; + EFI_HOB_MEMORY_ALLOCATION *MemoryHob2; + UINT64 Start; + UINT64 End; + BOOLEAN Merged; Merged = FALSE; Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { if (Hob.MemoryAllocation->AllocDescriptor.MemoryType == EfiConventionalMemory) { - MemoryHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; - Start = MemoryHob->AllocDescriptor.MemoryBaseAddress; - End = MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength; + MemoryHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; + Start = MemoryHob->AllocDescriptor.MemoryBaseAddress; + End = MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength; Hob2.Raw = GET_NEXT_HOB (Hob); Hob2.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw); while (Hob2.Raw != NULL) { if (Hob2.MemoryAllocation->AllocDescriptor.MemoryType == EfiConventionalMemory) { - MemoryHob2 = (EFI_HOB_MEMORY_ALLOCATION *) Hob2.Raw; + MemoryHob2 = (EFI_HOB_MEMORY_ALLOCATION *)Hob2.Raw; if (Start == (MemoryHob2->AllocDescriptor.MemoryBaseAddress + MemoryHob2->AllocDescriptor.MemoryLength)) { // // Merge adjacent two free memory ranges. // MemoryHob2->AllocDescriptor.MemoryLength += MemoryHob->AllocDescriptor.MemoryLength; - Merged = TRUE; + Merged = TRUE; // // Mark MemoryHob to be unused(freed). // @@ -457,8 +460,8 @@ MergeFreeMemoryInMemoryAllocationHob ( // Merge adjacent two free memory ranges. // MemoryHob2->AllocDescriptor.MemoryBaseAddress = MemoryHob->AllocDescriptor.MemoryBaseAddress; - MemoryHob2->AllocDescriptor.MemoryLength += MemoryHob->AllocDescriptor.MemoryLength; - Merged = TRUE; + MemoryHob2->AllocDescriptor.MemoryLength += MemoryHob->AllocDescriptor.MemoryLength; + Merged = TRUE; // // Mark MemoryHob to be unused(freed). // @@ -466,10 +469,12 @@ MergeFreeMemoryInMemoryAllocationHob ( break; } } + Hob2.Raw = GET_NEXT_HOB (Hob2); Hob2.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob2.Raw); } } + Hob.Raw = GET_NEXT_HOB (Hob); Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw); } @@ -492,41 +497,44 @@ MergeFreeMemoryInMemoryAllocationHob ( **/ EFI_STATUS FindFreeMemoryFromMemoryAllocationHob ( - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - IN UINTN Granularity, - OUT EFI_PHYSICAL_ADDRESS *Memory + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + IN UINTN Granularity, + OUT EFI_PHYSICAL_ADDRESS *Memory ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; - UINT64 Bytes; - EFI_PHYSICAL_ADDRESS BaseAddress; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + UINT64 Bytes; + EFI_PHYSICAL_ADDRESS BaseAddress; Bytes = LShiftU64 (Pages, EFI_PAGE_SHIFT); - BaseAddress = 0; + BaseAddress = 0; MemoryAllocationHob = NULL; - Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { if ((Hob.MemoryAllocation->AllocDescriptor.MemoryType == EfiConventionalMemory) && - (Hob.MemoryAllocation->AllocDescriptor.MemoryLength >= Bytes)) { + (Hob.MemoryAllocation->AllocDescriptor.MemoryLength >= Bytes)) + { // // Found one memory allocation HOB with big enough free memory. // - MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; - BaseAddress = MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress + - MemoryAllocationHob->AllocDescriptor.MemoryLength - Bytes; + MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; + BaseAddress = MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress + + MemoryAllocationHob->AllocDescriptor.MemoryLength - Bytes; // // Make sure the granularity could be satisfied. // - BaseAddress &= ~((EFI_PHYSICAL_ADDRESS) Granularity - 1); + BaseAddress &= ~((EFI_PHYSICAL_ADDRESS)Granularity - 1); if (BaseAddress >= MemoryAllocationHob->AllocDescriptor.MemoryBaseAddress) { break; } - BaseAddress = 0; + + BaseAddress = 0; MemoryAllocationHob = NULL; } + // // Continue to find. // @@ -545,6 +553,7 @@ FindFreeMemoryFromMemoryAllocationHob ( // return FindFreeMemoryFromMemoryAllocationHob (MemoryType, Pages, Granularity, Memory); } + return EFI_NOT_FOUND; } } @@ -574,20 +583,20 @@ FindFreeMemoryFromMemoryAllocationHob ( EFI_STATUS EFIAPI PeiAllocatePages ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT EFI_PHYSICAL_ADDRESS *Memory + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT EFI_PHYSICAL_ADDRESS *Memory ) { - EFI_STATUS Status; - PEI_CORE_INSTANCE *PrivateData; - EFI_PEI_HOB_POINTERS Hob; - EFI_PHYSICAL_ADDRESS *FreeMemoryTop; - EFI_PHYSICAL_ADDRESS *FreeMemoryBottom; - UINTN RemainingPages; - UINTN Granularity; - UINTN Padding; + EFI_STATUS Status; + PEI_CORE_INSTANCE *PrivateData; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS *FreeMemoryTop; + EFI_PHYSICAL_ADDRESS *FreeMemoryBottom; + UINTN RemainingPages; + UINTN Granularity; + UINTN Padding; if ((MemoryType != EfiLoaderCode) && (MemoryType != EfiLoaderData) && @@ -597,7 +606,8 @@ PeiAllocatePages ( (MemoryType != EfiBootServicesData) && (MemoryType != EfiACPIReclaimMemory) && (MemoryType != EfiReservedMemoryType) && - (MemoryType != EfiACPIMemoryNVS)) { + (MemoryType != EfiACPIMemoryNVS)) + { return EFI_INVALID_PARAMETER; } @@ -613,16 +623,19 @@ PeiAllocatePages ( return EFI_NOT_AVAILABLE_YET; } - if (RUNTIME_PAGE_ALLOCATION_GRANULARITY > DEFAULT_PAGE_ALLOCATION_GRANULARITY && - (MemoryType == EfiACPIReclaimMemory || - MemoryType == EfiACPIMemoryNVS || - MemoryType == EfiRuntimeServicesCode || - MemoryType == EfiRuntimeServicesData)) { - + if ((RUNTIME_PAGE_ALLOCATION_GRANULARITY > DEFAULT_PAGE_ALLOCATION_GRANULARITY) && + ((MemoryType == EfiACPIReclaimMemory) || + (MemoryType == EfiACPIMemoryNVS) || + (MemoryType == EfiRuntimeServicesCode) || + (MemoryType == EfiRuntimeServicesData))) + { Granularity = RUNTIME_PAGE_ALLOCATION_GRANULARITY; - DEBUG ((DEBUG_INFO, "AllocatePages: aligning allocation to %d KB\n", - Granularity / SIZE_1KB)); + DEBUG (( + DEBUG_INFO, + "AllocatePages: aligning allocation to %d KB\n", + Granularity / SIZE_1KB + )); } if (!PrivateData->PeiMemoryInstalled && PrivateData->SwitchStackSignal) { @@ -630,11 +643,11 @@ PeiAllocatePages ( // When PeiInstallMemory is called but temporary memory has *not* been moved to permanent memory, // the AllocatePage will depend on the field of PEI_CORE_INSTANCE structure. // - FreeMemoryTop = &(PrivateData->FreePhysicalMemoryTop); - FreeMemoryBottom = &(PrivateData->PhysicalMemoryBegin); + FreeMemoryTop = &(PrivateData->FreePhysicalMemoryTop); + FreeMemoryBottom = &(PrivateData->PhysicalMemoryBegin); } else { - FreeMemoryTop = &(Hob.HandoffInformationTable->EfiFreeMemoryTop); - FreeMemoryBottom = &(Hob.HandoffInformationTable->EfiFreeMemoryBottom); + FreeMemoryTop = &(Hob.HandoffInformationTable->EfiFreeMemoryTop); + FreeMemoryBottom = &(Hob.HandoffInformationTable->EfiFreeMemoryBottom); } // @@ -642,7 +655,7 @@ PeiAllocatePages ( // If not aligned, make the allocation aligned. // Padding = *(FreeMemoryTop) & (Granularity - 1); - if ((UINTN) (*FreeMemoryTop - *FreeMemoryBottom) < Padding) { + if ((UINTN)(*FreeMemoryTop - *FreeMemoryBottom) < Padding) { DEBUG ((DEBUG_ERROR, "AllocatePages failed: Out of space after padding.\n")); return EFI_OUT_OF_RESOURCES; } @@ -676,9 +689,10 @@ PeiAllocatePages ( if (!EFI_ERROR (Status)) { return Status; } - DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64) Pages)); - DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64) RemainingPages)); - return EFI_OUT_OF_RESOURCES; + + DEBUG ((DEBUG_ERROR, "AllocatePages failed: No 0x%lx Pages is available.\n", (UINT64)Pages)); + DEBUG ((DEBUG_ERROR, "There is only left 0x%lx pages memory resource to be allocated.\n", (UINT64)RemainingPages)); + return EFI_OUT_OF_RESOURCES; } else { // // Update the PHIT to reflect the memory usage @@ -713,13 +727,13 @@ PeiAllocatePages ( **/ VOID FreeMemoryAllocationHob ( - IN PEI_CORE_INSTANCE *PrivateData, - IN OUT EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHobToFree + IN PEI_CORE_INSTANCE *PrivateData, + IN OUT EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHobToFree ) { - EFI_PEI_HOB_POINTERS Hob; - EFI_PHYSICAL_ADDRESS *FreeMemoryTop; - EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + EFI_PEI_HOB_POINTERS Hob; + EFI_PHYSICAL_ADDRESS *FreeMemoryTop; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; Hob.Raw = PrivateData->HobList.Raw; @@ -744,20 +758,23 @@ FreeMemoryAllocationHob ( MemoryAllocationHobToFree->Header.HobType = EFI_HOB_TYPE_UNUSED; MemoryAllocationHob = NULL; - Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { if ((Hob.MemoryAllocation->AllocDescriptor.MemoryType == EfiConventionalMemory) && - (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress == *FreeMemoryTop)) { + (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress == *FreeMemoryTop)) + { // // Found memory allocation HOB that has EfiConventionalMemory MemoryType and // MemoryBaseAddress == new *FreeMemoryTop. // - MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; + MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; break; } + Hob.Raw = GET_NEXT_HOB (Hob); Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw); } + // // Free memory allocation HOB iteratively. // @@ -783,23 +800,23 @@ FreeMemoryAllocationHob ( EFI_STATUS EFIAPI PeiFreePages ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN Pages + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN Pages ) { - PEI_CORE_INSTANCE *PrivateData; - UINT64 Bytes; - UINT64 Start; - UINT64 End; - EFI_PEI_HOB_POINTERS Hob; - EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; + PEI_CORE_INSTANCE *PrivateData; + UINT64 Bytes; + UINT64 Start; + UINT64 End; + EFI_PEI_HOB_POINTERS Hob; + EFI_HOB_MEMORY_ALLOCATION *MemoryAllocationHob; Bytes = LShiftU64 (Pages, EFI_PAGE_SHIFT); Start = Memory; - End = Start + Bytes - 1; + End = Start + Bytes - 1; - if (Pages == 0 || ((Start & EFI_PAGE_MASK) != 0) || (Start >= End)) { + if ((Pages == 0) || ((Start & EFI_PAGE_MASK) != 0) || (Start >= End)) { return EFI_INVALID_PARAMETER; } @@ -814,17 +831,19 @@ PeiFreePages ( } MemoryAllocationHob = NULL; - Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); + Hob.Raw = GetFirstHob (EFI_HOB_TYPE_MEMORY_ALLOCATION); while (Hob.Raw != NULL) { if ((Hob.MemoryAllocation->AllocDescriptor.MemoryType != EfiConventionalMemory) && (Memory >= Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress) && - ((Memory + Bytes) <= (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength))) { + ((Memory + Bytes) <= (Hob.MemoryAllocation->AllocDescriptor.MemoryBaseAddress + Hob.MemoryAllocation->AllocDescriptor.MemoryLength))) + { // // Found the memory allocation HOB that includes the memory pages to be freed. // - MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *) Hob.Raw; + MemoryAllocationHob = (EFI_HOB_MEMORY_ALLOCATION *)Hob.Raw; break; } + Hob.Raw = GET_NEXT_HOB (Hob); Hob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, Hob.Raw); } @@ -857,13 +876,13 @@ PeiFreePages ( EFI_STATUS EFIAPI PeiAllocatePool ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINTN Size, - OUT VOID **Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINTN Size, + OUT VOID **Buffer ) { - EFI_STATUS Status; - EFI_HOB_MEMORY_POOL *Hob; + EFI_STATUS Status; + EFI_HOB_MEMORY_POOL *Hob; // // If some "post-memory" PEIM wishes to allocate larger pool, diff --git a/MdeModulePkg/Core/Pei/PciCfg2/PciCfg2.c b/MdeModulePkg/Core/Pei/PciCfg2/PciCfg2.c index 3dfc595675..cd15d016d7 100644 --- a/MdeModulePkg/Core/Pei/PciCfg2/PciCfg2.c +++ b/MdeModulePkg/Core/Pei/PciCfg2/PciCfg2.c @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// This default instance of EFI_PEI_PCI_CFG2_PPI install assigned to EFI_PEI_SERVICE.PciCfg /// when PeiCore's initialization. /// -EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi = { +EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi = { PeiDefaultPciCfg2Read, PeiDefaultPciCfg2Write, PeiDefaultPciCfg2Modify @@ -45,11 +45,11 @@ EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi = { EFI_STATUS EFIAPI PeiDefaultPciCfg2Read ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -76,11 +76,11 @@ PeiDefaultPciCfg2Read ( EFI_STATUS EFIAPI PeiDefaultPciCfg2Write ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN OUT VOID *Buffer ) { return EFI_NOT_AVAILABLE_YET; @@ -110,12 +110,12 @@ PeiDefaultPciCfg2Write ( EFI_STATUS EFIAPI PeiDefaultPciCfg2Modify ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN VOID *SetBits, - IN VOID *ClearBits + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN VOID *SetBits, + IN VOID *ClearBits ) { return EFI_NOT_AVAILABLE_YET; diff --git a/MdeModulePkg/Core/Pei/PeiMain.h b/MdeModulePkg/Core/Pei/PeiMain.h index 196944ca21..556beddad5 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.h +++ b/MdeModulePkg/Core/Pei/PeiMain.h @@ -50,51 +50,51 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// It is an FFS type extension used for PeiFindFileEx. It indicates current /// FFS searching is for all PEIMs can be dispatched by PeiCore. /// -#define PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE 0xff +#define PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE 0xff /// /// Pei Core private data structures /// typedef union { - EFI_PEI_PPI_DESCRIPTOR *Ppi; - EFI_PEI_NOTIFY_DESCRIPTOR *Notify; - VOID *Raw; + EFI_PEI_PPI_DESCRIPTOR *Ppi; + EFI_PEI_NOTIFY_DESCRIPTOR *Notify; + VOID *Raw; } PEI_PPI_LIST_POINTERS; /// /// Number of PEI_PPI_LIST_POINTERS to grow by each time we run out of room /// -#define PPI_GROWTH_STEP 64 -#define CALLBACK_NOTIFY_GROWTH_STEP 32 -#define DISPATCH_NOTIFY_GROWTH_STEP 8 +#define PPI_GROWTH_STEP 64 +#define CALLBACK_NOTIFY_GROWTH_STEP 32 +#define DISPATCH_NOTIFY_GROWTH_STEP 8 typedef struct { - UINTN CurrentCount; - UINTN MaxCount; - UINTN LastDispatchedCount; + UINTN CurrentCount; + UINTN MaxCount; + UINTN LastDispatchedCount; /// /// MaxCount number of entries. /// - PEI_PPI_LIST_POINTERS *PpiPtrs; + PEI_PPI_LIST_POINTERS *PpiPtrs; } PEI_PPI_LIST; typedef struct { - UINTN CurrentCount; - UINTN MaxCount; + UINTN CurrentCount; + UINTN MaxCount; /// /// MaxCount number of entries. /// - PEI_PPI_LIST_POINTERS *NotifyPtrs; + PEI_PPI_LIST_POINTERS *NotifyPtrs; } PEI_CALLBACK_NOTIFY_LIST; typedef struct { - UINTN CurrentCount; - UINTN MaxCount; - UINTN LastDispatchedCount; + UINTN CurrentCount; + UINTN MaxCount; + UINTN LastDispatchedCount; /// /// MaxCount number of entries. /// - PEI_PPI_LIST_POINTERS *NotifyPtrs; + PEI_PPI_LIST_POINTERS *NotifyPtrs; } PEI_DISPATCH_NOTIFY_LIST; /// @@ -105,15 +105,15 @@ typedef struct { /// /// PPI List. /// - PEI_PPI_LIST PpiList; + PEI_PPI_LIST PpiList; /// /// Notify List at dispatch level. /// - PEI_CALLBACK_NOTIFY_LIST CallbackNotifyList; + PEI_CALLBACK_NOTIFY_LIST CallbackNotifyList; /// /// Notify List at callback level. /// - PEI_DISPATCH_NOTIFY_LIST DispatchNotifyList; + PEI_DISPATCH_NOTIFY_LIST DispatchNotifyList; } PEI_PPI_DATABASE; // @@ -121,64 +121,63 @@ typedef struct { // Do not change these values as there is code doing math to change states. // Look for Private->Fv[FvCount].PeimState[PeimCount]++; // -#define PEIM_STATE_NOT_DISPATCHED 0x00 -#define PEIM_STATE_DISPATCHED 0x01 -#define PEIM_STATE_REGISTER_FOR_SHADOW 0x02 -#define PEIM_STATE_DONE 0x03 +#define PEIM_STATE_NOT_DISPATCHED 0x00 +#define PEIM_STATE_DISPATCHED 0x01 +#define PEIM_STATE_REGISTER_FOR_SHADOW 0x02 +#define PEIM_STATE_DONE 0x03 // // Number of FV instances to grow by each time we run out of room // -#define FV_GROWTH_STEP 8 +#define FV_GROWTH_STEP 8 typedef struct { - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; - EFI_PEI_FV_HANDLE FvHandle; - UINTN PeimCount; + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_PEI_FIRMWARE_VOLUME_PPI *FvPpi; + EFI_PEI_FV_HANDLE FvHandle; + UINTN PeimCount; // // Pointer to the buffer with the PeimCount number of Entries. // - UINT8 *PeimState; + UINT8 *PeimState; // // Pointer to the buffer with the PeimCount number of Entries. // - EFI_PEI_FILE_HANDLE *FvFileHandles; - BOOLEAN ScanFv; - UINT32 AuthenticationStatus; + EFI_PEI_FILE_HANDLE *FvFileHandles; + BOOLEAN ScanFv; + UINT32 AuthenticationStatus; } PEI_CORE_FV_HANDLE; typedef struct { - EFI_GUID FvFormat; - VOID *FvInfo; - UINT32 FvInfoSize; - UINT32 AuthenticationStatus; - EFI_PEI_NOTIFY_DESCRIPTOR NotifyDescriptor; + EFI_GUID FvFormat; + VOID *FvInfo; + UINT32 FvInfoSize; + UINT32 AuthenticationStatus; + EFI_PEI_NOTIFY_DESCRIPTOR NotifyDescriptor; } PEI_CORE_UNKNOW_FORMAT_FV_INFO; -#define CACHE_SETION_MAX_NUMBER 0x10 +#define CACHE_SETION_MAX_NUMBER 0x10 typedef struct { - EFI_COMMON_SECTION_HEADER* Section[CACHE_SETION_MAX_NUMBER]; - VOID* SectionData[CACHE_SETION_MAX_NUMBER]; - UINTN SectionSize[CACHE_SETION_MAX_NUMBER]; - UINT32 AuthenticationStatus[CACHE_SETION_MAX_NUMBER]; - UINTN AllSectionCount; - UINTN SectionIndex; + EFI_COMMON_SECTION_HEADER *Section[CACHE_SETION_MAX_NUMBER]; + VOID *SectionData[CACHE_SETION_MAX_NUMBER]; + UINTN SectionSize[CACHE_SETION_MAX_NUMBER]; + UINT32 AuthenticationStatus[CACHE_SETION_MAX_NUMBER]; + UINTN AllSectionCount; + UINTN SectionIndex; } CACHE_SECTION_DATA; -#define HOLE_MAX_NUMBER 0x3 +#define HOLE_MAX_NUMBER 0x3 typedef struct { - EFI_PHYSICAL_ADDRESS Base; - UINTN Size; - UINTN Offset; - BOOLEAN OffsetPositive; + EFI_PHYSICAL_ADDRESS Base; + UINTN Size; + UINTN Offset; + BOOLEAN OffsetPositive; } HOLE_MEMORY_DATA; /// /// Forward declaration for PEI_CORE_INSTANCE /// -typedef struct _PEI_CORE_INSTANCE PEI_CORE_INSTANCE; - +typedef struct _PEI_CORE_INSTANCE PEI_CORE_INSTANCE; /** Function Pointer type for PeiCore function. @@ -204,7 +203,7 @@ EFI_STATUS // // Number of files to grow by each time we run out of room // -#define TEMP_FILE_GROWTH_STEP 32 +#define TEMP_FILE_GROWTH_STEP 32 #define PEI_CORE_HANDLE_SIGNATURE SIGNATURE_32('P','e','i','C') @@ -212,75 +211,75 @@ EFI_STATUS /// Pei Core private data structure instance /// struct _PEI_CORE_INSTANCE { - UINTN Signature; + UINTN Signature; /// /// Point to ServiceTableShadow /// - EFI_PEI_SERVICES *Ps; - PEI_PPI_DATABASE PpiData; + EFI_PEI_SERVICES *Ps; + PEI_PPI_DATABASE PpiData; /// /// The count of FVs which contains FFS and could be dispatched by PeiCore. /// - UINTN FvCount; + UINTN FvCount; /// /// The max count of FVs which contains FFS and could be dispatched by PeiCore. /// - UINTN MaxFvCount; + UINTN MaxFvCount; /// /// Pointer to the buffer with the MaxFvCount number of entries. /// Each entry is for one FV which contains FFS and could be dispatched by PeiCore. /// - PEI_CORE_FV_HANDLE *Fv; + PEI_CORE_FV_HANDLE *Fv; /// /// Pointer to the buffer with the MaxUnknownFvInfoCount number of entries. /// Each entry is for one FV which could not be dispatched by PeiCore. /// - PEI_CORE_UNKNOW_FORMAT_FV_INFO *UnknownFvInfo; - UINTN MaxUnknownFvInfoCount; - UINTN UnknownFvInfoCount; + PEI_CORE_UNKNOW_FORMAT_FV_INFO *UnknownFvInfo; + UINTN MaxUnknownFvInfoCount; + UINTN UnknownFvInfoCount; /// /// Pointer to the buffer FvFileHandlers in PEI_CORE_FV_HANDLE specified by CurrentPeimFvCount. /// - EFI_PEI_FILE_HANDLE *CurrentFvFileHandles; - UINTN AprioriCount; - UINTN CurrentPeimFvCount; - UINTN CurrentPeimCount; - EFI_PEI_FILE_HANDLE CurrentFileHandle; - BOOLEAN PeimNeedingDispatch; - BOOLEAN PeimDispatchOnThisPass; - BOOLEAN PeimDispatcherReenter; - EFI_PEI_HOB_POINTERS HobList; - BOOLEAN SwitchStackSignal; - BOOLEAN PeiMemoryInstalled; - VOID *CpuIo; - EFI_PEI_SECURITY2_PPI *PrivateSecurityPpi; - EFI_PEI_SERVICES ServiceTableShadow; - EFI_PEI_PPI_DESCRIPTOR *XipLoadFile; - EFI_PHYSICAL_ADDRESS PhysicalMemoryBegin; - UINT64 PhysicalMemoryLength; - EFI_PHYSICAL_ADDRESS FreePhysicalMemoryTop; - UINTN HeapOffset; - BOOLEAN HeapOffsetPositive; - UINTN StackOffset; - BOOLEAN StackOffsetPositive; + EFI_PEI_FILE_HANDLE *CurrentFvFileHandles; + UINTN AprioriCount; + UINTN CurrentPeimFvCount; + UINTN CurrentPeimCount; + EFI_PEI_FILE_HANDLE CurrentFileHandle; + BOOLEAN PeimNeedingDispatch; + BOOLEAN PeimDispatchOnThisPass; + BOOLEAN PeimDispatcherReenter; + EFI_PEI_HOB_POINTERS HobList; + BOOLEAN SwitchStackSignal; + BOOLEAN PeiMemoryInstalled; + VOID *CpuIo; + EFI_PEI_SECURITY2_PPI *PrivateSecurityPpi; + EFI_PEI_SERVICES ServiceTableShadow; + EFI_PEI_PPI_DESCRIPTOR *XipLoadFile; + EFI_PHYSICAL_ADDRESS PhysicalMemoryBegin; + UINT64 PhysicalMemoryLength; + EFI_PHYSICAL_ADDRESS FreePhysicalMemoryTop; + UINTN HeapOffset; + BOOLEAN HeapOffsetPositive; + UINTN StackOffset; + BOOLEAN StackOffsetPositive; // // Information for migrating memory pages allocated in pre-memory phase. // - HOLE_MEMORY_DATA MemoryPages; - PEICORE_FUNCTION_POINTER ShadowedPeiCore; - CACHE_SECTION_DATA CacheSection; + HOLE_MEMORY_DATA MemoryPages; + PEICORE_FUNCTION_POINTER ShadowedPeiCore; + CACHE_SECTION_DATA CacheSection; // // For Loading modules at fixed address feature to cache the top address below which the // Runtime code, boot time code and PEI memory will be placed. Please note that the offset between this field // and Ps should not be changed since maybe user could get this top address by using the offset to Ps. // - EFI_PHYSICAL_ADDRESS LoadModuleAtFixAddressTopAddress; + EFI_PHYSICAL_ADDRESS LoadModuleAtFixAddressTopAddress; // // The field is define for Loading modules at fixed address feature to tracker the PEI code // memory range usage. It is a bit mapped array in which every bit indicates the corresponding memory page @@ -320,13 +319,13 @@ struct _PEI_CORE_INSTANCE { /// Union of temporarily used function pointers (to save stack space) /// typedef union { - PEICORE_FUNCTION_POINTER PeiCore; - EFI_PEIM_ENTRY_POINT2 PeimEntry; - EFI_PEIM_NOTIFY_ENTRY_POINT PeimNotifyEntry; - EFI_DXE_IPL_PPI *DxeIpl; - EFI_PEI_PPI_DESCRIPTOR *PpiDescriptor; - EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor; - VOID *Raw; + PEICORE_FUNCTION_POINTER PeiCore; + EFI_PEIM_ENTRY_POINT2 PeimEntry; + EFI_PEIM_NOTIFY_ENTRY_POINT PeimNotifyEntry; + EFI_DXE_IPL_PPI *DxeIpl; + EFI_PEI_PPI_DESCRIPTOR *PpiDescriptor; + EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor; + VOID *Raw; } PEI_CORE_TEMP_POINTERS; typedef struct { @@ -338,6 +337,7 @@ typedef struct { // // PeiCore function // + /** The entry routine to Pei Core, invoked by PeiMain during transition @@ -360,9 +360,9 @@ typedef struct { VOID EFIAPI PeiCore ( - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, - IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList, - IN VOID *Data + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData, + IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList, + IN VOID *Data ); // @@ -391,8 +391,8 @@ PeiCore ( **/ BOOLEAN PeimDispatchReadiness ( - IN EFI_PEI_SERVICES **PeiServices, - IN VOID *DependencyExpression + IN EFI_PEI_SERVICES **PeiServices, + IN VOID *DependencyExpression ); /** @@ -407,8 +407,8 @@ PeimDispatchReadiness ( EFI_STATUS EFIAPI MigratePeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN EFI_PEI_FILE_HANDLE MigratedFileHandle + IN EFI_PEI_FILE_HANDLE FileHandle, + IN EFI_PEI_FILE_HANDLE MigratedFileHandle ); /** @@ -426,8 +426,8 @@ MigratePeim ( EFI_STATUS EFIAPI EvacuateTempRam ( - IN PEI_CORE_INSTANCE *Private, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *Private, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ); /** @@ -455,9 +455,9 @@ PeiDispatcher ( **/ VOID InitializeDispatcherData ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_INSTANCE *OldCoreData, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_INSTANCE *OldCoreData, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ); /** @@ -475,14 +475,15 @@ InitializeDispatcherData ( **/ BOOLEAN DepexSatisfied ( - IN PEI_CORE_INSTANCE *Private, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINTN PeimCount + IN PEI_CORE_INSTANCE *Private, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINTN PeimCount ); // // PPI support functions // + /** Initialize PPI services. @@ -494,8 +495,8 @@ DepexSatisfied ( **/ VOID InitializePpiServices ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_INSTANCE *OldCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_INSTANCE *OldCoreData ); /** @@ -525,10 +526,10 @@ ConvertPpiPointers ( **/ VOID ConvertPpiPointersFv ( - IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN OrgFvHandle, - IN UINTN FvHandle, - IN UINTN FvSize + IN PEI_CORE_INSTANCE *PrivateData, + IN UINTN OrgFvHandle, + IN UINTN FvHandle, + IN UINTN FvSize ); /** @@ -541,8 +542,8 @@ ConvertPpiPointersFv ( **/ VOID ConvertPeiCorePpiPointers ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_FV_HANDLE *CoreFvHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_FV_HANDLE *CoreFvHandle ); /** @@ -554,7 +555,7 @@ ConvertPeiCorePpiPointers ( **/ VOID DumpPpiList ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ); /** @@ -672,11 +673,11 @@ ProcessDispatchNotifyList ( VOID ProcessNotify ( IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN NotifyType, - IN INTN InstallStartIndex, - IN INTN InstallStopIndex, - IN INTN NotifyStartIndex, - IN INTN NotifyStopIndex + IN UINTN NotifyType, + IN INTN InstallStartIndex, + IN INTN InstallStopIndex, + IN INTN NotifyStartIndex, + IN INTN NotifyStopIndex ); /** @@ -689,13 +690,14 @@ ProcessNotify ( **/ VOID ProcessPpiListFromSec ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList ); // // Boot mode support functions // + /** This service enables PEIMs to ascertain the present value of the boot mode. @@ -727,12 +729,13 @@ EFI_STATUS EFIAPI PeiSetBootMode ( IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_BOOT_MODE BootMode + IN EFI_BOOT_MODE BootMode ); // // Security support functions // + /** Initialize the security services. @@ -744,8 +747,8 @@ PeiSetBootMode ( **/ VOID InitializeSecurityServices ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_CORE_INSTANCE *OldCoreData + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_CORE_INSTANCE *OldCoreData ); /** @@ -776,10 +779,10 @@ VerifyFv ( **/ EFI_STATUS VerifyPeim ( - IN PEI_CORE_INSTANCE *PrivateData, - IN EFI_PEI_FV_HANDLE VolumeHandle, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINT32 AuthenticationStatus + IN PEI_CORE_INSTANCE *PrivateData, + IN EFI_PEI_FV_HANDLE VolumeHandle, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINT32 AuthenticationStatus ); /** @@ -799,7 +802,7 @@ EFI_STATUS EFIAPI PeiGetHobList ( IN CONST EFI_PEI_SERVICES **PeiServices, - IN OUT VOID **HobList + IN OUT VOID **HobList ); /** @@ -820,9 +823,9 @@ EFI_STATUS EFIAPI PeiCreateHob ( IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINT16 Type, - IN UINT16 Length, - IN OUT VOID **Hob + IN UINT16 Type, + IN UINT16 Length, + IN OUT VOID **Hob ); /** @@ -855,14 +858,14 @@ PeiCoreBuildHobHandoffInfoTable ( **/ EFI_STATUS PeiInstallSecHobData ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_HOB_GENERIC_HEADER *SecHobList + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_HOB_GENERIC_HEADER *SecHobList ); - // // FFS Fw Volume support functions // + /** Searches for the next matching file in the firmware volume. @@ -882,10 +885,10 @@ PeiInstallSecHobData ( EFI_STATUS EFIAPI PeiFfsFindNextFile ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINT8 SearchType, - IN EFI_PEI_FV_HANDLE FvHandle, - IN OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINT8 SearchType, + IN EFI_PEI_FV_HANDLE FvHandle, + IN OUT EFI_PEI_FILE_HANDLE *FileHandle ); /** @@ -935,10 +938,10 @@ ProcessSection ( EFI_STATUS EFIAPI PeiFfsFindSectionData ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_SECTION_TYPE SectionType, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_SECTION_TYPE SectionType, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData ); /** @@ -958,12 +961,12 @@ PeiFfsFindSectionData ( EFI_STATUS EFIAPI PeiFfsFindSectionData3 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_SECTION_TYPE SectionType, - IN UINTN SectionInstance, - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **SectionData, - OUT UINT32 *AuthenticationStatus + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_SECTION_TYPE SectionType, + IN UINTN SectionInstance, + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **SectionData, + OUT UINT32 *AuthenticationStatus ); /** @@ -982,14 +985,15 @@ PeiFfsFindSectionData3 ( EFI_STATUS EFIAPI PeiFfsFindNextVolume ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINTN Instance, - IN OUT EFI_PEI_FV_HANDLE *VolumeHandle + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINTN Instance, + IN OUT EFI_PEI_FV_HANDLE *VolumeHandle ); // // Memory support functions // + /** Initialize the memory services. @@ -1023,9 +1027,9 @@ InitializeMemoryServices ( EFI_STATUS EFIAPI PeiInstallPeiMemory ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PHYSICAL_ADDRESS MemoryBegin, - IN UINT64 MemoryLength + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PHYSICAL_ADDRESS MemoryBegin, + IN UINT64 MemoryLength ); /** @@ -1038,8 +1042,8 @@ PeiInstallPeiMemory ( **/ VOID MigrateMemoryPages ( - IN PEI_CORE_INSTANCE *Private, - IN BOOLEAN TemporaryRamMigrated + IN PEI_CORE_INSTANCE *Private, + IN BOOLEAN TemporaryRamMigrated ); /** @@ -1050,7 +1054,7 @@ MigrateMemoryPages ( **/ VOID RemoveFvHobsInTemporaryMemory ( - IN PEI_CORE_INSTANCE *Private + IN PEI_CORE_INSTANCE *Private ); /** @@ -1064,9 +1068,9 @@ RemoveFvHobsInTemporaryMemory ( **/ VOID ConvertFvHob ( - IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN OrgFvHandle, - IN UINTN FvHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN UINTN OrgFvHandle, + IN UINTN FvHandle ); /** @@ -1078,7 +1082,7 @@ ConvertFvHob ( **/ VOID ConvertMemoryAllocationHobs ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ); /** @@ -1106,10 +1110,10 @@ ConvertMemoryAllocationHobs ( EFI_STATUS EFIAPI PeiAllocatePages ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN Pages, - OUT EFI_PHYSICAL_ADDRESS *Memory + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + OUT EFI_PHYSICAL_ADDRESS *Memory ); /** @@ -1128,9 +1132,9 @@ PeiAllocatePages ( EFI_STATUS EFIAPI PeiFreePages ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN Pages + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN Pages ); /** @@ -1150,9 +1154,9 @@ PeiFreePages ( EFI_STATUS EFIAPI PeiAllocatePool ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN UINTN Size, - OUT VOID **Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN UINTN Size, + OUT VOID **Buffer ); /** @@ -1173,11 +1177,11 @@ PeiAllocatePool ( **/ EFI_STATUS PeiLoadImage ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINT8 PeimState, - OUT EFI_PHYSICAL_ADDRESS *EntryPoint, - OUT UINT32 *AuthenticationState + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINT8 PeimState, + OUT EFI_PHYSICAL_ADDRESS *EntryPoint, + OUT UINT32 *AuthenticationState ); /** @@ -1199,12 +1203,12 @@ PeiLoadImage ( EFI_STATUS EFIAPI PeiReportStatusCode ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_STATUS_CODE_TYPE CodeType, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId, - IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_STATUS_CODE_TYPE CodeType, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId, + IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL ); /** @@ -1222,7 +1226,7 @@ PeiReportStatusCode ( EFI_STATUS EFIAPI PeiResetSystem ( - IN CONST EFI_PEI_SERVICES **PeiServices + IN CONST EFI_PEI_SERVICES **PeiServices ); /** @@ -1241,10 +1245,10 @@ PeiResetSystem ( VOID EFIAPI PeiResetSystem2 ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ); /** @@ -1258,8 +1262,8 @@ PeiResetSystem2 ( **/ VOID PeiInitializeFv ( - IN PEI_CORE_INSTANCE *PrivateData, - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreData ); /** @@ -1275,9 +1279,9 @@ PeiInitializeFv ( EFI_STATUS EFIAPI FirmwareVolumeInfoPpiNotifyCallback ( - IN EFI_PEI_SERVICES **PeiServices, - IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, - IN VOID *Ppi + IN EFI_PEI_SERVICES **PeiServices, + IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, + IN VOID *Ppi ); /** @@ -1296,9 +1300,9 @@ FirmwareVolumeInfoPpiNotifyCallback ( EFI_STATUS EFIAPI PeiFfsFindFileByName ( - IN CONST EFI_GUID *FileName, - IN EFI_PEI_FV_HANDLE VolumeHandle, - OUT EFI_PEI_FILE_HANDLE *FileHandle + IN CONST EFI_GUID *FileName, + IN EFI_PEI_FV_HANDLE VolumeHandle, + OUT EFI_PEI_FILE_HANDLE *FileHandle ); /** @@ -1368,7 +1372,7 @@ PeiFfsGetVolumeInfo ( EFI_STATUS EFIAPI PeiRegisterForShadow ( - IN EFI_PEI_FILE_HANDLE FileHandle + IN EFI_PEI_FILE_HANDLE FileHandle ); /** @@ -1383,8 +1387,8 @@ PeiRegisterForShadow ( **/ VOID InitializeImageServices ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_INSTANCE *OldCoreData + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_INSTANCE *OldCoreData ); /** @@ -1399,8 +1403,8 @@ InitializeImageServices ( **/ EFI_STATUS LoadAndRelocatePeCoffImageInPlace ( - IN VOID *Pe32Data, - IN VOID *ImageAddress + IN VOID *Pe32Data, + IN VOID *ImageAddress ); /** @@ -1415,8 +1419,8 @@ LoadAndRelocatePeCoffImageInPlace ( **/ EFI_STATUS PeiGetPe32Data ( - IN EFI_PEI_FILE_HANDLE FileHandle, - OUT VOID **Pe32Data + IN EFI_PEI_FILE_HANDLE FileHandle, + OUT VOID **Pe32Data ); /** @@ -1478,9 +1482,9 @@ SecurityPpiNotifyCallback ( **/ EFI_STATUS ProcessFvFile ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_FV_HANDLE *ParentFvCoreHandle, - IN EFI_PEI_FILE_HANDLE ParentFvFileHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_FV_HANDLE *ParentFvCoreHandle, + IN EFI_PEI_FILE_HANDLE ParentFvFileHandle ); /** @@ -1526,12 +1530,12 @@ FindNextCoreFvHandle ( EFI_STATUS EFIAPI PeiDefaultMemRead ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ); /** @@ -1556,12 +1560,12 @@ PeiDefaultMemRead ( EFI_STATUS EFIAPI PeiDefaultMemWrite ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ); /** @@ -1585,12 +1589,12 @@ PeiDefaultMemWrite ( EFI_STATUS EFIAPI PeiDefaultIoRead ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ); /** @@ -1614,12 +1618,12 @@ PeiDefaultIoRead ( EFI_STATUS EFIAPI PeiDefaultIoWrite ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN EFI_PEI_CPU_IO_PPI_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN EFI_PEI_CPU_IO_PPI_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ); /** @@ -1637,9 +1641,9 @@ PeiDefaultIoWrite ( UINT8 EFIAPI PeiDefaultIoRead8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1657,9 +1661,9 @@ PeiDefaultIoRead8 ( UINT16 EFIAPI PeiDefaultIoRead16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1677,9 +1681,9 @@ PeiDefaultIoRead16 ( UINT32 EFIAPI PeiDefaultIoRead32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1697,9 +1701,9 @@ PeiDefaultIoRead32 ( UINT64 EFIAPI PeiDefaultIoRead64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1713,10 +1717,10 @@ PeiDefaultIoRead64 ( VOID EFIAPI PeiDefaultIoWrite8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT8 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT8 Data ); /** @@ -1730,10 +1734,10 @@ PeiDefaultIoWrite8 ( VOID EFIAPI PeiDefaultIoWrite16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT16 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT16 Data ); /** @@ -1747,10 +1751,10 @@ PeiDefaultIoWrite16 ( VOID EFIAPI PeiDefaultIoWrite32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT32 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT32 Data ); /** @@ -1764,10 +1768,10 @@ PeiDefaultIoWrite32 ( VOID EFIAPI PeiDefaultIoWrite64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT64 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT64 Data ); /** @@ -1786,9 +1790,9 @@ PeiDefaultIoWrite64 ( UINT8 EFIAPI PeiDefaultMemRead8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1807,9 +1811,9 @@ PeiDefaultMemRead8 ( UINT16 EFIAPI PeiDefaultMemRead16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1828,9 +1832,9 @@ PeiDefaultMemRead16 ( UINT32 EFIAPI PeiDefaultMemRead32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1849,9 +1853,9 @@ PeiDefaultMemRead32 ( UINT64 EFIAPI PeiDefaultMemRead64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address ); /** @@ -1866,10 +1870,10 @@ PeiDefaultMemRead64 ( VOID EFIAPI PeiDefaultMemWrite8 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT8 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT8 Data ); /** @@ -1884,10 +1888,10 @@ PeiDefaultMemWrite8 ( VOID EFIAPI PeiDefaultMemWrite16 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT16 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT16 Data ); /** @@ -1902,10 +1906,10 @@ PeiDefaultMemWrite16 ( VOID EFIAPI PeiDefaultMemWrite32 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT32 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT32 Data ); /** @@ -1920,13 +1924,13 @@ PeiDefaultMemWrite32 ( VOID EFIAPI PeiDefaultMemWrite64 ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_CPU_IO_PPI *This, - IN UINT64 Address, - IN UINT64 Data + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_CPU_IO_PPI *This, + IN UINT64 Address, + IN UINT64 Data ); -extern EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi; +extern EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi; // // Default EFI_PEI_PCI_CFG2_PPI support for EFI_PEI_SERVICES table when PeiCore initialization. @@ -1954,11 +1958,11 @@ extern EFI_PEI_CPU_IO_PPI gPeiDefaultCpuIoPpi; EFI_STATUS EFIAPI PeiDefaultPciCfg2Read ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN OUT VOID *Buffer ); /** @@ -1982,11 +1986,11 @@ PeiDefaultPciCfg2Read ( EFI_STATUS EFIAPI PeiDefaultPciCfg2Write ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN OUT VOID *Buffer + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN OUT VOID *Buffer ); /** @@ -2011,15 +2015,15 @@ PeiDefaultPciCfg2Write ( EFI_STATUS EFIAPI PeiDefaultPciCfg2Modify ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PCI_CFG2_PPI *This, - IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, - IN UINT64 Address, - IN VOID *SetBits, - IN VOID *ClearBits + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PCI_CFG2_PPI *This, + IN EFI_PEI_PCI_CFG_PPI_WIDTH Width, + IN UINT64 Address, + IN VOID *SetBits, + IN VOID *ClearBits ); -extern EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi; +extern EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi; /** After PeiCore image is shadowed into permanent memory, all build-in FvPpi should @@ -2031,7 +2035,7 @@ extern EFI_PEI_PCI_CFG2_PPI gPeiDefaultPciCfg2Ppi; **/ VOID PeiReinitializeFv ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ); #endif diff --git a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c index a72d07c4be..bf1719d794 100644 --- a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c +++ b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PeiMain.h" -EFI_PEI_PPI_DESCRIPTOR mMemoryDiscoveredPpi = { +EFI_PEI_PPI_DESCRIPTOR mMemoryDiscoveredPpi = { (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiPeiMemoryDiscoveredPpiGuid, NULL @@ -74,13 +74,13 @@ ShadowPeiCore ( IN PEI_CORE_INSTANCE *PrivateData ) { - EFI_PEI_FILE_HANDLE PeiCoreFileHandle; - EFI_PHYSICAL_ADDRESS EntryPoint; - EFI_STATUS Status; - UINT32 AuthenticationState; - UINTN Index; - EFI_PEI_CORE_FV_LOCATION_PPI *PeiCoreFvLocationPpi; - UINTN PeiCoreFvIndex; + EFI_PEI_FILE_HANDLE PeiCoreFileHandle; + EFI_PHYSICAL_ADDRESS EntryPoint; + EFI_STATUS Status; + UINT32 AuthenticationState; + UINTN Index; + EFI_PEI_CORE_FV_LOCATION_PPI *PeiCoreFvLocationPpi; + UINTN PeiCoreFvIndex; PeiCoreFileHandle = NULL; // @@ -94,20 +94,22 @@ ShadowPeiCore ( &gEfiPeiCoreFvLocationPpiGuid, 0, NULL, - (VOID **) &PeiCoreFvLocationPpi + (VOID **)&PeiCoreFvLocationPpi ); if (!EFI_ERROR (Status) && (PeiCoreFvLocationPpi->PeiCoreFvLocation != NULL)) { // // If PeiCoreFvLocation present, the PEI Core should be found from indicated FV // - for (Index = 0; Index < PrivateData->FvCount; Index ++) { + for (Index = 0; Index < PrivateData->FvCount; Index++) { if (PrivateData->Fv[Index].FvHandle == PeiCoreFvLocationPpi->PeiCoreFvLocation) { PeiCoreFvIndex = Index; break; } } + ASSERT (Index < PrivateData->FvCount); } + // // Find PEI Core from the given FV index // @@ -123,19 +125,19 @@ ShadowPeiCore ( // Shadow PEI Core into memory so it will run faster // Status = PeiLoadImage ( - GetPeiServicesTablePointer (), - *((EFI_PEI_FILE_HANDLE*)&PeiCoreFileHandle), - PEIM_STATE_REGISTER_FOR_SHADOW, - &EntryPoint, - &AuthenticationState - ); + GetPeiServicesTablePointer (), + *((EFI_PEI_FILE_HANDLE *)&PeiCoreFileHandle), + PEIM_STATE_REGISTER_FOR_SHADOW, + &EntryPoint, + &AuthenticationState + ); ASSERT_EFI_ERROR (Status); // // Compute the PeiCore's function address after shadowed PeiCore. // _ModuleEntryPoint is PeiCore main function entry // - return (PEICORE_FUNCTION_POINTER)((UINTN) EntryPoint + (UINTN) PeiCore - (UINTN) _ModuleEntryPoint); + return (PEICORE_FUNCTION_POINTER)((UINTN)EntryPoint + (UINTN)PeiCore - (UINTN)_ModuleEntryPoint); } /** @@ -160,28 +162,28 @@ ShadowPeiCore ( VOID EFIAPI PeiCore ( - IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreDataPtr, - IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList, - IN VOID *Data + IN CONST EFI_SEC_PEI_HAND_OFF *SecCoreDataPtr, + IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList, + IN VOID *Data ) { - PEI_CORE_INSTANCE PrivateData; - EFI_SEC_PEI_HAND_OFF *SecCoreData; - EFI_SEC_PEI_HAND_OFF NewSecCoreData; - EFI_STATUS Status; - PEI_CORE_TEMP_POINTERS TempPtr; - PEI_CORE_INSTANCE *OldCoreData; - EFI_PEI_CPU_IO_PPI *CpuIo; - EFI_PEI_PCI_CFG2_PPI *PciCfg; - EFI_HOB_HANDOFF_INFO_TABLE *HandoffInformationTable; - EFI_PEI_TEMPORARY_RAM_DONE_PPI *TemporaryRamDonePpi; - UINTN Index; + PEI_CORE_INSTANCE PrivateData; + EFI_SEC_PEI_HAND_OFF *SecCoreData; + EFI_SEC_PEI_HAND_OFF NewSecCoreData; + EFI_STATUS Status; + PEI_CORE_TEMP_POINTERS TempPtr; + PEI_CORE_INSTANCE *OldCoreData; + EFI_PEI_CPU_IO_PPI *CpuIo; + EFI_PEI_PCI_CFG2_PPI *PciCfg; + EFI_HOB_HANDOFF_INFO_TABLE *HandoffInformationTable; + EFI_PEI_TEMPORARY_RAM_DONE_PPI *TemporaryRamDonePpi; + UINTN Index; // // Retrieve context passed into PEI Core // - OldCoreData = (PEI_CORE_INSTANCE *) Data; - SecCoreData = (EFI_SEC_PEI_HAND_OFF *) SecCoreDataPtr; + OldCoreData = (PEI_CORE_INSTANCE *)Data; + SecCoreData = (EFI_SEC_PEI_HAND_OFF *)SecCoreDataPtr; // // Perform PEI Core phase specific actions. @@ -206,59 +208,73 @@ PeiCore ( if (OldCoreData->HeapOffsetPositive) { OldCoreData->HobList.Raw = (VOID *)(OldCoreData->HobList.Raw + OldCoreData->HeapOffset); if (OldCoreData->UnknownFvInfo != NULL) { - OldCoreData->UnknownFvInfo = (PEI_CORE_UNKNOW_FORMAT_FV_INFO *) ((UINT8 *) OldCoreData->UnknownFvInfo + OldCoreData->HeapOffset); + OldCoreData->UnknownFvInfo = (PEI_CORE_UNKNOW_FORMAT_FV_INFO *)((UINT8 *)OldCoreData->UnknownFvInfo + OldCoreData->HeapOffset); } + if (OldCoreData->CurrentFvFileHandles != NULL) { - OldCoreData->CurrentFvFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->CurrentFvFileHandles + OldCoreData->HeapOffset); + OldCoreData->CurrentFvFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->CurrentFvFileHandles + OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.PpiList.PpiPtrs != NULL) { - OldCoreData->PpiData.PpiList.PpiPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.PpiList.PpiPtrs + OldCoreData->HeapOffset); + OldCoreData->PpiData.PpiList.PpiPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.PpiList.PpiPtrs + OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs != NULL) { - OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs + OldCoreData->HeapOffset); + OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs + OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs != NULL) { - OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs + OldCoreData->HeapOffset); + OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs + OldCoreData->HeapOffset); } - OldCoreData->Fv = (PEI_CORE_FV_HANDLE *) ((UINT8 *) OldCoreData->Fv + OldCoreData->HeapOffset); - for (Index = 0; Index < OldCoreData->FvCount; Index ++) { + + OldCoreData->Fv = (PEI_CORE_FV_HANDLE *)((UINT8 *)OldCoreData->Fv + OldCoreData->HeapOffset); + for (Index = 0; Index < OldCoreData->FvCount; Index++) { if (OldCoreData->Fv[Index].PeimState != NULL) { - OldCoreData->Fv[Index].PeimState = (UINT8 *) OldCoreData->Fv[Index].PeimState + OldCoreData->HeapOffset; + OldCoreData->Fv[Index].PeimState = (UINT8 *)OldCoreData->Fv[Index].PeimState + OldCoreData->HeapOffset; } + if (OldCoreData->Fv[Index].FvFileHandles != NULL) { - OldCoreData->Fv[Index].FvFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->Fv[Index].FvFileHandles + OldCoreData->HeapOffset); + OldCoreData->Fv[Index].FvFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->Fv[Index].FvFileHandles + OldCoreData->HeapOffset); } } - OldCoreData->TempFileGuid = (EFI_GUID *) ((UINT8 *) OldCoreData->TempFileGuid + OldCoreData->HeapOffset); - OldCoreData->TempFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->TempFileHandles + OldCoreData->HeapOffset); + + OldCoreData->TempFileGuid = (EFI_GUID *)((UINT8 *)OldCoreData->TempFileGuid + OldCoreData->HeapOffset); + OldCoreData->TempFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->TempFileHandles + OldCoreData->HeapOffset); } else { OldCoreData->HobList.Raw = (VOID *)(OldCoreData->HobList.Raw - OldCoreData->HeapOffset); if (OldCoreData->UnknownFvInfo != NULL) { - OldCoreData->UnknownFvInfo = (PEI_CORE_UNKNOW_FORMAT_FV_INFO *) ((UINT8 *) OldCoreData->UnknownFvInfo - OldCoreData->HeapOffset); + OldCoreData->UnknownFvInfo = (PEI_CORE_UNKNOW_FORMAT_FV_INFO *)((UINT8 *)OldCoreData->UnknownFvInfo - OldCoreData->HeapOffset); } + if (OldCoreData->CurrentFvFileHandles != NULL) { - OldCoreData->CurrentFvFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->CurrentFvFileHandles - OldCoreData->HeapOffset); + OldCoreData->CurrentFvFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->CurrentFvFileHandles - OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.PpiList.PpiPtrs != NULL) { - OldCoreData->PpiData.PpiList.PpiPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.PpiList.PpiPtrs - OldCoreData->HeapOffset); + OldCoreData->PpiData.PpiList.PpiPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.PpiList.PpiPtrs - OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs != NULL) { - OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs - OldCoreData->HeapOffset); + OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.CallbackNotifyList.NotifyPtrs - OldCoreData->HeapOffset); } + if (OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs != NULL) { - OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *) ((UINT8 *) OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs - OldCoreData->HeapOffset); + OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs = (PEI_PPI_LIST_POINTERS *)((UINT8 *)OldCoreData->PpiData.DispatchNotifyList.NotifyPtrs - OldCoreData->HeapOffset); } - OldCoreData->Fv = (PEI_CORE_FV_HANDLE *) ((UINT8 *) OldCoreData->Fv - OldCoreData->HeapOffset); - for (Index = 0; Index < OldCoreData->FvCount; Index ++) { + + OldCoreData->Fv = (PEI_CORE_FV_HANDLE *)((UINT8 *)OldCoreData->Fv - OldCoreData->HeapOffset); + for (Index = 0; Index < OldCoreData->FvCount; Index++) { if (OldCoreData->Fv[Index].PeimState != NULL) { - OldCoreData->Fv[Index].PeimState = (UINT8 *) OldCoreData->Fv[Index].PeimState - OldCoreData->HeapOffset; + OldCoreData->Fv[Index].PeimState = (UINT8 *)OldCoreData->Fv[Index].PeimState - OldCoreData->HeapOffset; } + if (OldCoreData->Fv[Index].FvFileHandles != NULL) { - OldCoreData->Fv[Index].FvFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->Fv[Index].FvFileHandles - OldCoreData->HeapOffset); + OldCoreData->Fv[Index].FvFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->Fv[Index].FvFileHandles - OldCoreData->HeapOffset); } } - OldCoreData->TempFileGuid = (EFI_GUID *) ((UINT8 *) OldCoreData->TempFileGuid - OldCoreData->HeapOffset); - OldCoreData->TempFileHandles = (EFI_PEI_FILE_HANDLE *) ((UINT8 *) OldCoreData->TempFileHandles - OldCoreData->HeapOffset); + + OldCoreData->TempFileGuid = (EFI_GUID *)((UINT8 *)OldCoreData->TempFileGuid - OldCoreData->HeapOffset); + OldCoreData->TempFileHandles = (EFI_PEI_FILE_HANDLE *)((UINT8 *)OldCoreData->TempFileHandles - OldCoreData->HeapOffset); } // @@ -276,10 +292,11 @@ PeiCore ( // HandoffInformationTable = OldCoreData->HobList.HandoffInformationTable; if (OldCoreData->HeapOffsetPositive) { - HandoffInformationTable->EfiEndOfHobList = HandoffInformationTable->EfiEndOfHobList + OldCoreData->HeapOffset; + HandoffInformationTable->EfiEndOfHobList = HandoffInformationTable->EfiEndOfHobList + OldCoreData->HeapOffset; } else { - HandoffInformationTable->EfiEndOfHobList = HandoffInformationTable->EfiEndOfHobList - OldCoreData->HeapOffset; + HandoffInformationTable->EfiEndOfHobList = HandoffInformationTable->EfiEndOfHobList - OldCoreData->HeapOffset; } + HandoffInformationTable->EfiMemoryTop = OldCoreData->PhysicalMemoryBegin + OldCoreData->PhysicalMemoryLength; HandoffInformationTable->EfiMemoryBottom = OldCoreData->PhysicalMemoryBegin; HandoffInformationTable->EfiFreeMemoryTop = OldCoreData->FreePhysicalMemoryTop; @@ -306,22 +323,23 @@ PeiCore ( // OldCoreData->PeimDispatcherReenter = TRUE; - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 && (OldCoreData->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { + if ((PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) && (OldCoreData->HobList.HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME)) { // // if Loading Module at Fixed Address is enabled, allocate the PEI code memory range usage bit map array. // Every bit in the array indicate the status of the corresponding memory page available or not // - OldCoreData->PeiCodeMemoryRangeUsageBitMap = AllocateZeroPool (((PcdGet32(PcdLoadFixAddressPeiCodePageNumber)>>6) + 1)*sizeof(UINT64)); + OldCoreData->PeiCodeMemoryRangeUsageBitMap = AllocateZeroPool (((PcdGet32 (PcdLoadFixAddressPeiCodePageNumber)>>6) + 1)*sizeof (UINT64)); } // // Shadow PEI Core. When permanent memory is available, shadow // PEI Core and PEIMs to get high performance. // - OldCoreData->ShadowedPeiCore = (PEICORE_FUNCTION_POINTER) (UINTN) PeiCore; + OldCoreData->ShadowedPeiCore = (PEICORE_FUNCTION_POINTER)(UINTN)PeiCore; if (PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes) || - (HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME && PcdGetBool (PcdShadowPeimOnS3Boot)) || - (HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME && PcdGetBool (PcdShadowPeimOnBoot))) { + ((HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) && PcdGetBool (PcdShadowPeimOnS3Boot)) || + ((HandoffInformationTable->BootMode != BOOT_ON_S3_RESUME) && PcdGetBool (PcdShadowPeimOnBoot))) + { OldCoreData->ShadowedPeiCore = ShadowPeiCore (OldCoreData); } @@ -334,7 +352,7 @@ PeiCore ( // Should never reach here. // ASSERT (FALSE); - CpuDeadLoop(); + CpuDeadLoop (); UNREACHABLE (); } @@ -347,8 +365,8 @@ PeiCore ( CopyMem (&PrivateData, OldCoreData, sizeof (PrivateData)); - CpuIo = (VOID*)PrivateData.ServiceTableShadow.CpuIo; - PciCfg = (VOID*)PrivateData.ServiceTableShadow.PciCfg; + CpuIo = (VOID *)PrivateData.ServiceTableShadow.CpuIo; + PciCfg = (VOID *)PrivateData.ServiceTableShadow.PciCfg; CopyMem (&PrivateData.ServiceTableShadow, &gPs, sizeof (gPs)); @@ -374,7 +392,7 @@ PeiCore ( // // Initialize PEI Core Services // - InitializeMemoryServices (&PrivateData, SecCoreData, OldCoreData); + InitializeMemoryServices (&PrivateData, SecCoreData, OldCoreData); // // Update performance measurements @@ -387,7 +405,6 @@ PeiCore ( // PERF_CROSSMODULE_BEGIN ("PEI"); PERF_INMODULE_BEGIN ("PreMem"); - } else { PERF_INMODULE_END ("PreMem"); PERF_INMODULE_BEGIN ("PostMem"); @@ -397,8 +414,8 @@ PeiCore ( // Complete PEI Core Service initialization // InitializeSecurityServices (&PrivateData.Ps, OldCoreData); - InitializeDispatcherData (&PrivateData, OldCoreData, SecCoreData); - InitializeImageServices (&PrivateData, OldCoreData); + InitializeDispatcherData (&PrivateData, OldCoreData, SecCoreData); + InitializeImageServices (&PrivateData, OldCoreData); // // Perform PEI Core Phase specific actions @@ -416,7 +433,7 @@ PeiCore ( // If SEC provided the PpiList, process it. // if (PpiList != NULL) { - ProcessPpiListFromSec ((CONST EFI_PEI_SERVICES **) &PrivateData.Ps, PpiList); + ProcessPpiListFromSec ((CONST EFI_PEI_SERVICES **)&PrivateData.Ps, PpiList); } } else { if (PcdGetBool (PcdMigrateTemporaryRamFirmwareVolumes)) { @@ -443,7 +460,7 @@ PeiCore ( &gEfiTemporaryRamDonePpiGuid, 0, NULL, - (VOID**)&TemporaryRamDonePpi + (VOID **)&TemporaryRamDonePpi ); if (!EFI_ERROR (Status)) { // @@ -475,7 +492,7 @@ PeiCore ( // // Check if InstallPeiMemory service was called on non-S3 resume boot path. // - ASSERT(PrivateData.PeiMemoryInstalled == TRUE); + ASSERT (PrivateData.PeiMemoryInstalled == TRUE); } // @@ -518,7 +535,7 @@ PeiCore ( // Should never reach here. // ASSERT_EFI_ERROR (Status); - CpuDeadLoop(); + CpuDeadLoop (); UNREACHABLE (); } diff --git a/MdeModulePkg/Core/Pei/Ppi/Ppi.c b/MdeModulePkg/Core/Pei/Ppi/Ppi.c index 2e339e2522..0e85264ddb 100644 --- a/MdeModulePkg/Core/Pei/Ppi/Ppi.c +++ b/MdeModulePkg/Core/Pei/Ppi/Ppi.c @@ -21,19 +21,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID ConvertPointer ( - IN OUT VOID **Pointer, - IN UINTN TempBottom, - IN UINTN TempTop, - IN UINTN Offset, - IN BOOLEAN OffsetPositive + IN OUT VOID **Pointer, + IN UINTN TempBottom, + IN UINTN TempTop, + IN UINTN Offset, + IN BOOLEAN OffsetPositive ) { - if (((UINTN) *Pointer < TempTop) && - ((UINTN) *Pointer >= TempBottom)) { + if (((UINTN)*Pointer < TempTop) && + ((UINTN)*Pointer >= TempBottom)) + { if (OffsetPositive) { - *Pointer = (VOID *) ((UINTN) *Pointer + Offset); + *Pointer = (VOID *)((UINTN)*Pointer + Offset); } else { - *Pointer = (VOID *) ((UINTN) *Pointer - Offset); + *Pointer = (VOID *)((UINTN)*Pointer - Offset); } } } @@ -55,7 +56,7 @@ ConvertPointerInRanges ( IN OUT VOID **Pointer ) { - UINT8 IndexHole; + UINT8 IndexHole; if (PrivateData->MemoryPages.Size != 0) { // @@ -96,7 +97,7 @@ ConvertPointerInRanges ( // // Convert PPI pointer in old TempRam Hole // - for (IndexHole = 0; IndexHole < HOLE_MAX_NUMBER; IndexHole ++) { + for (IndexHole = 0; IndexHole < HOLE_MAX_NUMBER; IndexHole++) { if (PrivateData->HoleData[IndexHole].Size == 0) { continue; } @@ -139,12 +140,12 @@ ConvertSinglePpiPointer ( // 2. Convert the pointer to the GUID in the PPI or NOTIFY descriptor // from the old TempRam to the relocated physical memory. // - ConvertPointerInRanges (SecCoreData, PrivateData, (VOID **) &PpiPointer->Ppi->Guid); + ConvertPointerInRanges (SecCoreData, PrivateData, (VOID **)&PpiPointer->Ppi->Guid); // // 3. Convert the pointer to the PPI interface structure in the PPI descriptor // from the old TempRam to the relocated physical memory. // - ConvertPointerInRanges (SecCoreData, PrivateData, (VOID **) &PpiPointer->Ppi->Ppi); + ConvertPointerInRanges (SecCoreData, PrivateData, (VOID **)&PpiPointer->Ppi->Ppi); } /** @@ -162,7 +163,7 @@ ConvertPpiPointers ( IN PEI_CORE_INSTANCE *PrivateData ) { - UINT8 Index; + UINT8 Index; // // Convert normal PPIs. @@ -210,10 +211,10 @@ ConvertPpiPointers ( **/ VOID ConvertPpiPointersFv ( - IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN OrgFvHandle, - IN UINTN FvHandle, - IN UINTN FvSize + IN PEI_CORE_INSTANCE *PrivateData, + IN UINTN OrgFvHandle, + IN UINTN FvHandle, + IN UINTN FvSize ) { UINT8 Index; @@ -229,18 +230,18 @@ ConvertPpiPointersFv ( if (FvHandle > OrgFvHandle) { OffsetPositive = TRUE; - Offset = FvHandle - OrgFvHandle; + Offset = FvHandle - OrgFvHandle; } else { OffsetPositive = FALSE; - Offset = OrgFvHandle - FvHandle; + Offset = OrgFvHandle - FvHandle; } DEBUG ((DEBUG_VERBOSE, "Converting PPI pointers in FV.\n")); DEBUG (( DEBUG_VERBOSE, " OrgFvHandle at 0x%08x. FvHandle at 0x%08x. FvSize = 0x%x\n", - (UINTN) OrgFvHandle, - (UINTN) FvHandle, + (UINTN)OrgFvHandle, + (UINTN)FvHandle, FvSize )); DEBUG (( @@ -251,46 +252,46 @@ ConvertPpiPointersFv ( )); for (Index = 0; Index < PrivateData->PpiData.CallbackNotifyList.CurrentCount; Index++) { - ConvertPointer ( - (VOID **) &PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw, - OrgFvHandle, - OrgFvHandle + FvSize, - Offset, - OffsetPositive - ); - ConvertPointer ( - (VOID **) &PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Notify->Guid, - OrgFvHandle, - OrgFvHandle + FvSize, - Offset, - OffsetPositive - ); - ConvertPointer ( - (VOID **) &PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Notify->Notify, - OrgFvHandle, - OrgFvHandle + FvSize, - Offset, - OffsetPositive - ); + ConvertPointer ( + (VOID **)&PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw, + OrgFvHandle, + OrgFvHandle + FvSize, + Offset, + OffsetPositive + ); + ConvertPointer ( + (VOID **)&PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Notify->Guid, + OrgFvHandle, + OrgFvHandle + FvSize, + Offset, + OffsetPositive + ); + ConvertPointer ( + (VOID **)&PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Notify->Notify, + OrgFvHandle, + OrgFvHandle + FvSize, + Offset, + OffsetPositive + ); } for (Index = 0; Index < PrivateData->PpiData.DispatchNotifyList.CurrentCount; Index++) { ConvertPointer ( - (VOID **) &PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw, + (VOID **)&PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw, OrgFvHandle, OrgFvHandle + FvSize, Offset, OffsetPositive ); ConvertPointer ( - (VOID **) &PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Guid, + (VOID **)&PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Guid, OrgFvHandle, OrgFvHandle + FvSize, Offset, OffsetPositive ); ConvertPointer ( - (VOID **) &PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Notify, + (VOID **)&PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Notify, OrgFvHandle, OrgFvHandle + FvSize, Offset, @@ -300,21 +301,21 @@ ConvertPpiPointersFv ( for (Index = 0; Index < PrivateData->PpiData.PpiList.CurrentCount; Index++) { ConvertPointer ( - (VOID **) &PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw, + (VOID **)&PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw, OrgFvHandle, OrgFvHandle + FvSize, Offset, OffsetPositive ); ConvertPointer ( - (VOID **) &PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Guid, + (VOID **)&PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Guid, OrgFvHandle, OrgFvHandle + FvSize, Offset, OffsetPositive ); ConvertPointer ( - (VOID **) &PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Ppi, + (VOID **)&PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Ppi, OrgFvHandle, OrgFvHandle + FvSize, Offset, @@ -331,7 +332,8 @@ ConvertPpiPointersFv ( if ((((INT32 *)Guid)[0] == ((INT32 *)GuidCheckList[GuidIndex])[0]) && (((INT32 *)Guid)[1] == ((INT32 *)GuidCheckList[GuidIndex])[1]) && (((INT32 *)Guid)[2] == ((INT32 *)GuidCheckList[GuidIndex])[2]) && - (((INT32 *)Guid)[3] == ((INT32 *)GuidCheckList[GuidIndex])[3])) { + (((INT32 *)Guid)[3] == ((INT32 *)GuidCheckList[GuidIndex])[3])) + { FvInfoPpi = PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Ppi; DEBUG ((DEBUG_VERBOSE, " FvInfo: %p -> ", FvInfoPpi->FvInfo)); if ((UINTN)FvInfoPpi->FvInfo == OrgFvHandle) { @@ -344,6 +346,7 @@ ConvertPpiPointersFv ( ); DEBUG ((DEBUG_VERBOSE, "%p", FvInfoPpi->FvInfo)); } + DEBUG ((DEBUG_VERBOSE, "\n")); break; } @@ -360,11 +363,11 @@ ConvertPpiPointersFv ( **/ VOID DumpPpiList ( - IN PEI_CORE_INSTANCE *PrivateData + IN PEI_CORE_INSTANCE *PrivateData ) { DEBUG_CODE_BEGIN (); - UINTN Index; + UINTN Index; if (PrivateData == NULL) { return; @@ -376,46 +379,51 @@ DumpPpiList ( "CallbackNotify[%2d] {%g} at 0x%x (%a)\n", Index, PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Notify->Guid, - (UINTN) PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw, + (UINTN)PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw, ( - !( - ((EFI_PHYSICAL_ADDRESS) (UINTN) PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw >= PrivateData->PhysicalMemoryBegin) && - (((EFI_PHYSICAL_ADDRESS) ((UINTN) PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw) + sizeof (EFI_PEI_NOTIFY_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) - ) + !( + ((EFI_PHYSICAL_ADDRESS)(UINTN)PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw >= PrivateData->PhysicalMemoryBegin) && + (((EFI_PHYSICAL_ADDRESS)((UINTN)PrivateData->PpiData.CallbackNotifyList.NotifyPtrs[Index].Raw) + sizeof (EFI_PEI_NOTIFY_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) + ) ? "CAR" : "Post-Memory" - ) + ) )); } + for (Index = 0; Index < PrivateData->PpiData.DispatchNotifyList.CurrentCount; Index++) { - DEBUG ((DEBUG_VERBOSE, - "DispatchNotify[%2d] {%g} at 0x%x (%a)\n", - Index, - PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Guid, - (UINTN) PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw, - ( - !( - ((EFI_PHYSICAL_ADDRESS) (UINTN) PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw >=PrivateData->PhysicalMemoryBegin) && - (((EFI_PHYSICAL_ADDRESS) ((UINTN) PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw) + sizeof (EFI_PEI_NOTIFY_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) - ) + DEBUG (( + DEBUG_VERBOSE, + "DispatchNotify[%2d] {%g} at 0x%x (%a)\n", + Index, + PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Notify->Guid, + (UINTN)PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw, + ( + !( + ((EFI_PHYSICAL_ADDRESS)(UINTN)PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw >= PrivateData->PhysicalMemoryBegin) && + (((EFI_PHYSICAL_ADDRESS)((UINTN)PrivateData->PpiData.DispatchNotifyList.NotifyPtrs[Index].Raw) + sizeof (EFI_PEI_NOTIFY_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) + ) ? "CAR" : "Post-Memory" ) - )); + )); } + for (Index = 0; Index < PrivateData->PpiData.PpiList.CurrentCount; Index++) { - DEBUG ((DEBUG_VERBOSE, - "PPI[%2d] {%g} at 0x%x (%a)\n", - Index, - PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Guid, - (UINTN) PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw, - ( - !( - ((EFI_PHYSICAL_ADDRESS) (UINTN) PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw >= PrivateData->PhysicalMemoryBegin) && - (((EFI_PHYSICAL_ADDRESS) ((UINTN) PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw) + sizeof (EFI_PEI_PPI_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) - ) + DEBUG (( + DEBUG_VERBOSE, + "PPI[%2d] {%g} at 0x%x (%a)\n", + Index, + PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi->Guid, + (UINTN)PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw, + ( + !( + ((EFI_PHYSICAL_ADDRESS)(UINTN)PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw >= PrivateData->PhysicalMemoryBegin) && + (((EFI_PHYSICAL_ADDRESS)((UINTN)PrivateData->PpiData.PpiList.PpiPtrs[Index].Raw) + sizeof (EFI_PEI_PPI_DESCRIPTOR)) < PrivateData->FreePhysicalMemoryTop) + ) ? "CAR" : "Post-Memory" ) - )); + )); } + DEBUG_CODE_END (); } @@ -444,21 +452,21 @@ InternalPeiInstallPpi ( IN BOOLEAN Single ) { - PEI_CORE_INSTANCE *PrivateData; - PEI_PPI_LIST *PpiListPointer; - UINTN Index; - UINTN LastCount; - VOID *TempPtr; + PEI_CORE_INSTANCE *PrivateData; + PEI_PPI_LIST *PpiListPointer; + UINTN Index; + UINTN LastCount; + VOID *TempPtr; if (PpiList == NULL) { return EFI_INVALID_PARAMETER; } - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); PpiListPointer = &PrivateData->PpiData.PpiList; - Index = PpiListPointer->CurrentCount; - LastCount = Index; + Index = PpiListPointer->CurrentCount; + LastCount = Index; // // This is loop installs all PPI descriptors in the PpiList. It is terminated @@ -466,7 +474,7 @@ InternalPeiInstallPpi ( // EFI_PEI_PPI_DESCRIPTOR in the list. // - for (;;) { + for ( ; ;) { // // Check if it is a valid PPI. // If not, rollback list to exclude all in this list. @@ -474,8 +482,8 @@ InternalPeiInstallPpi ( // if ((PpiList->Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) == 0) { PpiListPointer->CurrentCount = LastCount; - DEBUG((DEBUG_ERROR, "ERROR -> InstallPpi: %g %p\n", PpiList->Guid, PpiList->Ppi)); - return EFI_INVALID_PARAMETER; + DEBUG ((DEBUG_ERROR, "ERROR -> InstallPpi: %g %p\n", PpiList->Guid, PpiList->Ppi)); + return EFI_INVALID_PARAMETER; } if (Index >= PpiListPointer->MaxCount) { @@ -491,12 +499,12 @@ InternalPeiInstallPpi ( PpiListPointer->PpiPtrs, sizeof (PEI_PPI_LIST_POINTERS) * PpiListPointer->MaxCount ); - PpiListPointer->PpiPtrs = TempPtr; + PpiListPointer->PpiPtrs = TempPtr; PpiListPointer->MaxCount = PpiListPointer->MaxCount + PPI_GROWTH_STEP; } - DEBUG((DEBUG_INFO, "Install PPI: %g\n", PpiList->Guid)); - PpiListPointer->PpiPtrs[Index].Ppi = (EFI_PEI_PPI_DESCRIPTOR *) PpiList; + DEBUG ((DEBUG_INFO, "Install PPI: %g\n", PpiList->Guid)); + PpiListPointer->PpiPtrs[Index].Ppi = (EFI_PEI_PPI_DESCRIPTOR *)PpiList; Index++; PpiListPointer->CurrentCount++; @@ -506,12 +514,14 @@ InternalPeiInstallPpi ( // break; } else if ((PpiList->Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == - EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) { + EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) + { // // Continue until the end of the PPI List. // break; } + // // Go to the next descriptor. // @@ -583,19 +593,18 @@ PeiReInstallPpi ( IN CONST EFI_PEI_PPI_DESCRIPTOR *NewPpi ) { - PEI_CORE_INSTANCE *PrivateData; - UINTN Index; - + PEI_CORE_INSTANCE *PrivateData; + UINTN Index; if ((OldPpi == NULL) || (NewPpi == NULL)) { return EFI_INVALID_PARAMETER; } if ((NewPpi->Flags & EFI_PEI_PPI_DESCRIPTOR_PPI) == 0) { - return EFI_INVALID_PARAMETER; + return EFI_INVALID_PARAMETER; } - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); // // Find the old PPI instance in the database. If we can not find it, @@ -606,6 +615,7 @@ PeiReInstallPpi ( break; } } + if (Index == PrivateData->PpiData.PpiList.CurrentCount) { return EFI_NOT_FOUND; } @@ -613,8 +623,8 @@ PeiReInstallPpi ( // // Replace the old PPI with the new one. // - DEBUG((DEBUG_INFO, "Reinstall PPI: %g\n", NewPpi->Guid)); - PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi = (EFI_PEI_PPI_DESCRIPTOR *) NewPpi; + DEBUG ((DEBUG_INFO, "Reinstall PPI: %g\n", NewPpi->Guid)); + PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi = (EFI_PEI_PPI_DESCRIPTOR *)NewPpi; // // Process any callback level notifies for the newly installed PPI. @@ -650,26 +660,25 @@ PeiReInstallPpi ( EFI_STATUS EFIAPI PeiLocatePpi ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_GUID *Guid, - IN UINTN Instance, - IN OUT EFI_PEI_PPI_DESCRIPTOR **PpiDescriptor, - IN OUT VOID **Ppi + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_GUID *Guid, + IN UINTN Instance, + IN OUT EFI_PEI_PPI_DESCRIPTOR **PpiDescriptor, + IN OUT VOID **Ppi ) { - PEI_CORE_INSTANCE *PrivateData; - UINTN Index; - EFI_GUID *CheckGuid; - EFI_PEI_PPI_DESCRIPTOR *TempPtr; - + PEI_CORE_INSTANCE *PrivateData; + UINTN Index; + EFI_GUID *CheckGuid; + EFI_PEI_PPI_DESCRIPTOR *TempPtr; - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); // // Search the data base for the matching instance of the GUIDed PPI. // for (Index = 0; Index < PrivateData->PpiData.PpiList.CurrentCount; Index++) { - TempPtr = PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi; + TempPtr = PrivateData->PpiData.PpiList.PpiPtrs[Index].Ppi; CheckGuid = TempPtr->Guid; // @@ -680,9 +689,9 @@ PeiLocatePpi ( if ((((INT32 *)Guid)[0] == ((INT32 *)CheckGuid)[0]) && (((INT32 *)Guid)[1] == ((INT32 *)CheckGuid)[1]) && (((INT32 *)Guid)[2] == ((INT32 *)CheckGuid)[2]) && - (((INT32 *)Guid)[3] == ((INT32 *)CheckGuid)[3])) { + (((INT32 *)Guid)[3] == ((INT32 *)CheckGuid)[3])) + { if (Instance == 0) { - if (PpiDescriptor != NULL) { *PpiDescriptor = TempPtr; } @@ -691,9 +700,9 @@ PeiLocatePpi ( *Ppi = TempPtr->Ppi; } - return EFI_SUCCESS; } + Instance--; } } @@ -738,15 +747,15 @@ InternalPeiNotifyPpi ( return EFI_INVALID_PARAMETER; } - PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS(PeiServices); + PrivateData = PEI_CORE_INSTANCE_FROM_PS_THIS (PeiServices); CallbackNotifyListPointer = &PrivateData->PpiData.CallbackNotifyList; - CallbackNotifyIndex = CallbackNotifyListPointer->CurrentCount; - LastCallbackNotifyCount = CallbackNotifyIndex; + CallbackNotifyIndex = CallbackNotifyListPointer->CurrentCount; + LastCallbackNotifyCount = CallbackNotifyIndex; DispatchNotifyListPointer = &PrivateData->PpiData.DispatchNotifyList; - DispatchNotifyIndex = DispatchNotifyListPointer->CurrentCount; - LastDispatchNotifyCount = DispatchNotifyIndex; + DispatchNotifyIndex = DispatchNotifyListPointer->CurrentCount; + LastDispatchNotifyCount = DispatchNotifyIndex; // // This is loop installs all Notify descriptors in the NotifyList. It is @@ -754,15 +763,15 @@ InternalPeiNotifyPpi ( // EFI_PEI_NOTIFY_DESCRIPTOR in the list. // - for (;;) { + for ( ; ;) { // // If some of the PPI data is invalid restore original Notify PPI database value // if ((NotifyList->Flags & EFI_PEI_PPI_DESCRIPTOR_NOTIFY_TYPES) == 0) { - CallbackNotifyListPointer->CurrentCount = LastCallbackNotifyCount; - DispatchNotifyListPointer->CurrentCount = LastDispatchNotifyCount; - DEBUG((DEBUG_ERROR, "ERROR -> NotifyPpi: %g %p\n", NotifyList->Guid, NotifyList->Notify)); - return EFI_INVALID_PARAMETER; + CallbackNotifyListPointer->CurrentCount = LastCallbackNotifyCount; + DispatchNotifyListPointer->CurrentCount = LastDispatchNotifyCount; + DEBUG ((DEBUG_ERROR, "ERROR -> NotifyPpi: %g %p\n", NotifyList->Guid, NotifyList->Notify)); + return EFI_INVALID_PARAMETER; } if ((NotifyList->Flags & EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK) != 0) { @@ -780,9 +789,10 @@ InternalPeiNotifyPpi ( sizeof (PEI_PPI_LIST_POINTERS) * CallbackNotifyListPointer->MaxCount ); CallbackNotifyListPointer->NotifyPtrs = TempPtr; - CallbackNotifyListPointer->MaxCount = CallbackNotifyListPointer->MaxCount + CALLBACK_NOTIFY_GROWTH_STEP; + CallbackNotifyListPointer->MaxCount = CallbackNotifyListPointer->MaxCount + CALLBACK_NOTIFY_GROWTH_STEP; } - CallbackNotifyListPointer->NotifyPtrs[CallbackNotifyIndex].Notify = (EFI_PEI_NOTIFY_DESCRIPTOR *) NotifyList; + + CallbackNotifyListPointer->NotifyPtrs[CallbackNotifyIndex].Notify = (EFI_PEI_NOTIFY_DESCRIPTOR *)NotifyList; CallbackNotifyIndex++; CallbackNotifyListPointer->CurrentCount++; } else { @@ -800,14 +810,15 @@ InternalPeiNotifyPpi ( sizeof (PEI_PPI_LIST_POINTERS) * DispatchNotifyListPointer->MaxCount ); DispatchNotifyListPointer->NotifyPtrs = TempPtr; - DispatchNotifyListPointer->MaxCount = DispatchNotifyListPointer->MaxCount + DISPATCH_NOTIFY_GROWTH_STEP; + DispatchNotifyListPointer->MaxCount = DispatchNotifyListPointer->MaxCount + DISPATCH_NOTIFY_GROWTH_STEP; } - DispatchNotifyListPointer->NotifyPtrs[DispatchNotifyIndex].Notify = (EFI_PEI_NOTIFY_DESCRIPTOR *) NotifyList; + + DispatchNotifyListPointer->NotifyPtrs[DispatchNotifyIndex].Notify = (EFI_PEI_NOTIFY_DESCRIPTOR *)NotifyList; DispatchNotifyIndex++; DispatchNotifyListPointer->CurrentCount++; } - DEBUG((DEBUG_INFO, "Register PPI Notify: %g\n", NotifyList->Guid)); + DEBUG ((DEBUG_INFO, "Register PPI Notify: %g\n", NotifyList->Guid)); if (Single) { // @@ -815,12 +826,14 @@ InternalPeiNotifyPpi ( // break; } else if ((NotifyList->Flags & EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) == - EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) { + EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST) + { // // Continue until the end of the Notify List. // break; } + // // Go to the next descriptor. // @@ -839,7 +852,7 @@ InternalPeiNotifyPpi ( CallbackNotifyListPointer->CurrentCount ); - return EFI_SUCCESS; + return EFI_SUCCESS; } /** @@ -878,7 +891,7 @@ ProcessDispatchNotifyList ( IN PEI_CORE_INSTANCE *PrivateData ) { - UINTN TempValue; + UINTN TempValue; while (TRUE) { // @@ -927,6 +940,7 @@ ProcessDispatchNotifyList ( break; } } + return; } @@ -945,18 +959,18 @@ ProcessDispatchNotifyList ( VOID ProcessNotify ( IN PEI_CORE_INSTANCE *PrivateData, - IN UINTN NotifyType, - IN INTN InstallStartIndex, - IN INTN InstallStopIndex, - IN INTN NotifyStartIndex, - IN INTN NotifyStopIndex + IN UINTN NotifyType, + IN INTN InstallStartIndex, + IN INTN InstallStopIndex, + IN INTN NotifyStartIndex, + IN INTN NotifyStopIndex ) { - INTN Index1; - INTN Index2; - EFI_GUID *SearchGuid; - EFI_GUID *CheckGuid; - EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor; + INTN Index1; + INTN Index2; + EFI_GUID *SearchGuid; + EFI_GUID *CheckGuid; + EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor; for (Index1 = NotifyStartIndex; Index1 < NotifyStopIndex; Index1++) { if (NotifyType == EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK) { @@ -977,13 +991,16 @@ ProcessNotify ( if ((((INT32 *)SearchGuid)[0] == ((INT32 *)CheckGuid)[0]) && (((INT32 *)SearchGuid)[1] == ((INT32 *)CheckGuid)[1]) && (((INT32 *)SearchGuid)[2] == ((INT32 *)CheckGuid)[2]) && - (((INT32 *)SearchGuid)[3] == ((INT32 *)CheckGuid)[3])) { - DEBUG ((DEBUG_INFO, "Notify: PPI Guid: %g, Peim notify entry point: %p\n", + (((INT32 *)SearchGuid)[3] == ((INT32 *)CheckGuid)[3])) + { + DEBUG (( + DEBUG_INFO, + "Notify: PPI Guid: %g, Peim notify entry point: %p\n", SearchGuid, NotifyDescriptor->Notify )); NotifyDescriptor->Notify ( - (EFI_PEI_SERVICES **) GetPeiServicesTablePointer (), + (EFI_PEI_SERVICES **)GetPeiServicesTablePointer (), NotifyDescriptor, (PrivateData->PpiData.PpiList.PpiPtrs[Index2].Ppi)->Ppi ); @@ -1002,20 +1019,20 @@ ProcessNotify ( **/ VOID ProcessPpiListFromSec ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList + IN CONST EFI_PEI_SERVICES **PeiServices, + IN CONST EFI_PEI_PPI_DESCRIPTOR *PpiList ) { - EFI_STATUS Status; - EFI_SEC_HOB_DATA_PPI *SecHobDataPpi; - EFI_HOB_GENERIC_HEADER *SecHobList; + EFI_STATUS Status; + EFI_SEC_HOB_DATA_PPI *SecHobDataPpi; + EFI_HOB_GENERIC_HEADER *SecHobList; - for (;;) { + for ( ; ;) { if ((PpiList->Flags & EFI_PEI_PPI_DESCRIPTOR_NOTIFY_TYPES) != 0) { // // It is a notification PPI. // - Status = InternalPeiNotifyPpi (PeiServices, (CONST EFI_PEI_NOTIFY_DESCRIPTOR *) PpiList, TRUE); + Status = InternalPeiNotifyPpi (PeiServices, (CONST EFI_PEI_NOTIFY_DESCRIPTOR *)PpiList, TRUE); ASSERT_EFI_ERROR (Status); } else { // @@ -1041,7 +1058,7 @@ ProcessPpiListFromSec ( // returned into the HOB list. It does this after installing all PPIs passed from SEC // into the PPI database and before dispatching any PEIMs. // - Status = PeiLocatePpi (PeiServices, &gEfiSecHobDataPpiGuid, 0, NULL, (VOID **) &SecHobDataPpi); + Status = PeiLocatePpi (PeiServices, &gEfiSecHobDataPpiGuid, 0, NULL, (VOID **)&SecHobDataPpi); if (!EFI_ERROR (Status)) { Status = SecHobDataPpi->GetHobs (SecHobDataPpi, &SecHobList); if (!EFI_ERROR (Status)) { @@ -1061,8 +1078,8 @@ ProcessPpiListFromSec ( **/ VOID ConvertPeiCorePpiPointers ( - IN PEI_CORE_INSTANCE *PrivateData, - IN PEI_CORE_FV_HANDLE *CoreFvHandle + IN PEI_CORE_INSTANCE *PrivateData, + IN PEI_CORE_FV_HANDLE *CoreFvHandle ) { EFI_FV_FILE_INFO FileInfo; @@ -1080,11 +1097,11 @@ ConvertPeiCorePpiPointers ( // Find the PEI Core in the BFV in temporary memory. // Status = CoreFvHandle->FvPpi->FindFileByType ( - CoreFvHandle->FvPpi, - EFI_FV_FILETYPE_PEI_CORE, - CoreFvHandle->FvHandle, - &PeiCoreFileHandle - ); + CoreFvHandle->FvPpi, + EFI_FV_FILETYPE_PEI_CORE, + CoreFvHandle->FvHandle, + &PeiCoreFileHandle + ); ASSERT_EFI_ERROR (Status); if (!EFI_ERROR (Status)) { @@ -1097,21 +1114,21 @@ ConvertPeiCorePpiPointers ( // // Find PEI Core EntryPoint in the BFV in temporary memory. // - Status = PeCoffLoaderGetEntryPoint ((VOID *) (UINTN) PeiCoreImageBase, &PeiCoreEntryPoint); + Status = PeCoffLoaderGetEntryPoint ((VOID *)(UINTN)PeiCoreImageBase, &PeiCoreEntryPoint); ASSERT_EFI_ERROR (Status); - OrgImageBase = (UINTN) PeiCoreImageBase; - MigratedImageBase = (UINTN) _ModuleEntryPoint - ((UINTN) PeiCoreEntryPoint - (UINTN) PeiCoreImageBase); + OrgImageBase = (UINTN)PeiCoreImageBase; + MigratedImageBase = (UINTN)_ModuleEntryPoint - ((UINTN)PeiCoreEntryPoint - (UINTN)PeiCoreImageBase); // // Size of loaded PEI_CORE in permanent memory. // - PeiCoreModuleSize = (UINTN)FileInfo.BufferSize - ((UINTN) OrgImageBase - (UINTN) FileInfo.Buffer); + PeiCoreModuleSize = (UINTN)FileInfo.BufferSize - ((UINTN)OrgImageBase - (UINTN)FileInfo.Buffer); // // Migrate PEI_CORE PPI pointers from temporary memory to newly // installed PEI_CORE in permanent memory. // - ConvertPpiPointersFv (PrivateData, (UINTN) OrgImageBase, (UINTN) MigratedImageBase, PeiCoreModuleSize); + ConvertPpiPointersFv (PrivateData, (UINTN)OrgImageBase, (UINTN)MigratedImageBase, PeiCoreModuleSize); } } diff --git a/MdeModulePkg/Core/Pei/Reset/Reset.c b/MdeModulePkg/Core/Pei/Reset/Reset.c index 0c3cfad035..a679cfecd0 100644 --- a/MdeModulePkg/Core/Pei/Reset/Reset.c +++ b/MdeModulePkg/Core/Pei/Reset/Reset.c @@ -59,7 +59,7 @@ PeiResetSystem ( // // No reset PPIs are available yet. // - return EFI_NOT_AVAILABLE_YET; + return EFI_NOT_AVAILABLE_YET; } /** diff --git a/MdeModulePkg/Core/Pei/Security/Security.c b/MdeModulePkg/Core/Pei/Security/Security.c index 8c18ed6cc8..a771007b6a 100644 --- a/MdeModulePkg/Core/Pei/Security/Security.c +++ b/MdeModulePkg/Core/Pei/Security/Security.c @@ -8,11 +8,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PeiMain.h" - -EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { - EFI_PEI_PPI_DESCRIPTOR_NOTIFY_DISPATCH | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, - &gEfiPeiSecurity2PpiGuid, - SecurityPpiNotifyCallback +EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { + EFI_PEI_PPI_DESCRIPTOR_NOTIFY_DISPATCH | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST, + &gEfiPeiSecurity2PpiGuid, + SecurityPpiNotifyCallback }; /** @@ -25,13 +24,14 @@ EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { **/ VOID InitializeSecurityServices ( - IN EFI_PEI_SERVICES **PeiServices, - IN PEI_CORE_INSTANCE *OldCoreData + IN EFI_PEI_SERVICES **PeiServices, + IN PEI_CORE_INSTANCE *OldCoreData ) { if (OldCoreData == NULL) { PeiServicesNotifyPpi (&mNotifyList); } + return; } @@ -55,7 +55,7 @@ SecurityPpiNotifyCallback ( IN VOID *Ppi ) { - PEI_CORE_INSTANCE *PrivateData; + PEI_CORE_INSTANCE *PrivateData; // // Get PEI Core private data @@ -68,6 +68,7 @@ SecurityPpiNotifyCallback ( if (PrivateData->PrivateSecurityPpi == NULL) { PrivateData->PrivateSecurityPpi = (EFI_PEI_SECURITY2_PPI *)Ppi; } + return EFI_SUCCESS; } @@ -85,14 +86,14 @@ SecurityPpiNotifyCallback ( **/ EFI_STATUS VerifyPeim ( - IN PEI_CORE_INSTANCE *PrivateData, - IN EFI_PEI_FV_HANDLE VolumeHandle, - IN EFI_PEI_FILE_HANDLE FileHandle, - IN UINT32 AuthenticationStatus + IN PEI_CORE_INSTANCE *PrivateData, + IN EFI_PEI_FV_HANDLE VolumeHandle, + IN EFI_PEI_FILE_HANDLE FileHandle, + IN UINT32 AuthenticationStatus ) { - EFI_STATUS Status; - BOOLEAN DeferExecution; + EFI_STATUS Status; + BOOLEAN DeferExecution; Status = EFI_NOT_FOUND; if (PrivateData->PrivateSecurityPpi == NULL) { @@ -109,7 +110,7 @@ VerifyPeim ( // Check to see if the image is OK // Status = PrivateData->PrivateSecurityPpi->AuthenticationState ( - (CONST EFI_PEI_SERVICES **) &PrivateData->Ps, + (CONST EFI_PEI_SERVICES **)&PrivateData->Ps, PrivateData->PrivateSecurityPpi, AuthenticationStatus, VolumeHandle, @@ -120,10 +121,10 @@ VerifyPeim ( Status = EFI_SECURITY_VIOLATION; } } + return Status; } - /** Verify a Firmware volume. diff --git a/MdeModulePkg/Core/Pei/StatusCode/StatusCode.c b/MdeModulePkg/Core/Pei/StatusCode/StatusCode.c index 482f8d8a0d..94e6e114ef 100644 --- a/MdeModulePkg/Core/Pei/StatusCode/StatusCode.c +++ b/MdeModulePkg/Core/Pei/StatusCode/StatusCode.c @@ -27,16 +27,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI PeiReportStatusCode ( - IN CONST EFI_PEI_SERVICES **PeiServices, - IN EFI_STATUS_CODE_TYPE CodeType, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId, - IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL + IN CONST EFI_PEI_SERVICES **PeiServices, + IN EFI_STATUS_CODE_TYPE CodeType, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId, + IN CONST EFI_STATUS_CODE_DATA *Data OPTIONAL ) { - EFI_STATUS Status; - EFI_PEI_PROGRESS_CODE_PPI *StatusCodePpi; + EFI_STATUS Status; + EFI_PEI_PROGRESS_CODE_PPI *StatusCodePpi; // // Locate StatusCode Ppi. @@ -50,19 +50,16 @@ PeiReportStatusCode ( if (!EFI_ERROR (Status)) { Status = StatusCodePpi->ReportStatusCode ( - PeiServices, - CodeType, - Value, - Instance, - CallerId, - Data - ); - - return Status; + PeiServices, + CodeType, + Value, + Instance, + CallerId, + Data + ); + + return Status; } - return EFI_NOT_AVAILABLE_YET; + return EFI_NOT_AVAILABLE_YET; } - - - diff --git a/MdeModulePkg/Core/PiSmmCore/Dependency.c b/MdeModulePkg/Core/PiSmmCore/Dependency.c index 1167807b15..c070f4216b 100644 --- a/MdeModulePkg/Core/PiSmmCore/Dependency.c +++ b/MdeModulePkg/Core/PiSmmCore/Dependency.c @@ -46,8 +46,8 @@ GrowDepexStack ( VOID ) { - BOOLEAN *NewStack; - UINTN Size; + BOOLEAN *NewStack; + UINTN Size; Size = DEPEX_STACK_SIZE_INCREMENT; if (mDepexEvaluationStack != NULL) { @@ -166,7 +166,7 @@ PopBool ( **/ BOOLEAN SmmIsSchedulable ( - IN EFI_SMM_DRIVER_ENTRY *DriverEntry + IN EFI_SMM_DRIVER_ENTRY *DriverEntry ) { EFI_STATUS Status; @@ -176,7 +176,7 @@ SmmIsSchedulable ( EFI_GUID DriverGuid; VOID *Interface; - Operator = FALSE; + Operator = FALSE; Operator2 = FALSE; if (DriverEntry->After || DriverEntry->Before) { @@ -205,7 +205,6 @@ SmmIsSchedulable ( // mDepexEvaluationStackPointer = mDepexEvaluationStack; - Iterator = DriverEntry->Depex; while (TRUE) { @@ -222,148 +221,155 @@ SmmIsSchedulable ( // Look at the opcode of the dependency expression instruction. // switch (*Iterator) { - case EFI_DEP_BEFORE: - case EFI_DEP_AFTER: - // - // For a well-formed Dependency Expression, the code should never get here. - // The BEFORE and AFTER are processed prior to this routine's invocation. - // If the code flow arrives at this point, there was a BEFORE or AFTER - // that were not the first opcodes. - // - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected BEFORE or AFTER opcode)\n")); - ASSERT (FALSE); - - case EFI_DEP_PUSH: - // - // Push operator is followed by a GUID. Test to see if the GUID protocol - // is installed and push the boolean result on the stack. - // - CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); - - Status = SmmLocateProtocol (&DriverGuid, NULL, &Interface); - if (EFI_ERROR (Status)) { + case EFI_DEP_BEFORE: + case EFI_DEP_AFTER: + // + // For a well-formed Dependency Expression, the code should never get here. + // The BEFORE and AFTER are processed prior to this routine's invocation. + // If the code flow arrives at this point, there was a BEFORE or AFTER + // that were not the first opcodes. + // + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected BEFORE or AFTER opcode)\n")); + ASSERT (FALSE); + + case EFI_DEP_PUSH: // - // For SMM Driver, it may depend on uefi protocols + // Push operator is followed by a GUID. Test to see if the GUID protocol + // is installed and push the boolean result on the stack. // - Status = gBS->LocateProtocol (&DriverGuid, NULL, &Interface); - } + CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); + + Status = SmmLocateProtocol (&DriverGuid, NULL, &Interface); + if (EFI_ERROR (Status)) { + // + // For SMM Driver, it may depend on uefi protocols + // + Status = gBS->LocateProtocol (&DriverGuid, NULL, &Interface); + } + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = FALSE\n", &DriverGuid)); + Status = PushBool (FALSE); + } else { + DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); + *Iterator = EFI_DEP_REPLACE_TRUE; + Status = PushBool (TRUE); + } + + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Iterator += sizeof (EFI_GUID); + break; + + case EFI_DEP_AND: + DEBUG ((DEBUG_DISPATCH, " AND\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PopBool (&Operator2); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(Operator && Operator2)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_OR: + DEBUG ((DEBUG_DISPATCH, " OR\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PopBool (&Operator2); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(Operator || Operator2)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_NOT: + DEBUG ((DEBUG_DISPATCH, " NOT\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Status = PushBool ((BOOLEAN)(!Operator)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_TRUE: + DEBUG ((DEBUG_DISPATCH, " TRUE\n")); + Status = PushBool (TRUE); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = FALSE\n", &DriverGuid)); + case EFI_DEP_FALSE: + DEBUG ((DEBUG_DISPATCH, " FALSE\n")); Status = PushBool (FALSE); - } else { + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + break; + + case EFI_DEP_END: + DEBUG ((DEBUG_DISPATCH, " END\n")); + Status = PopBool (&Operator); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + DEBUG ((DEBUG_DISPATCH, " RESULT = %a\n", Operator ? "TRUE" : "FALSE")); + return Operator; + + case EFI_DEP_REPLACE_TRUE: + CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); - *Iterator = EFI_DEP_REPLACE_TRUE; Status = PushBool (TRUE); - } - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Iterator += sizeof (EFI_GUID); - break; - - case EFI_DEP_AND: - DEBUG ((DEBUG_DISPATCH, " AND\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PopBool (&Operator2); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(Operator && Operator2)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_OR: - DEBUG ((DEBUG_DISPATCH, " OR\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PopBool (&Operator2); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(Operator || Operator2)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_NOT: - DEBUG ((DEBUG_DISPATCH, " NOT\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Status = PushBool ((BOOLEAN)(!Operator)); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_TRUE: - DEBUG ((DEBUG_DISPATCH, " TRUE\n")); - Status = PushBool (TRUE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_FALSE: - DEBUG ((DEBUG_DISPATCH, " FALSE\n")); - Status = PushBool (FALSE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - break; - - case EFI_DEP_END: - DEBUG ((DEBUG_DISPATCH, " END\n")); - Status = PopBool (&Operator); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - DEBUG ((DEBUG_DISPATCH, " RESULT = %a\n", Operator ? "TRUE" : "FALSE")); - return Operator; - - case EFI_DEP_REPLACE_TRUE: - CopyMem (&DriverGuid, Iterator + 1, sizeof (EFI_GUID)); - DEBUG ((DEBUG_DISPATCH, " PUSH GUID(%g) = TRUE\n", &DriverGuid)); - Status = PushBool (TRUE); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); - return FALSE; - } - - Iterator += sizeof (EFI_GUID); - break; - - default: - DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unknown opcode)\n")); - goto Done; + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unexpected error)\n")); + return FALSE; + } + + Iterator += sizeof (EFI_GUID); + break; + + default: + DEBUG ((DEBUG_DISPATCH, " RESULT = FALSE (Unknown opcode)\n")); + goto Done; } // diff --git a/MdeModulePkg/Core/PiSmmCore/Dispatcher.c b/MdeModulePkg/Core/PiSmmCore/Dispatcher.c index 1736edb8d0..f635565dd1 100644 --- a/MdeModulePkg/Core/PiSmmCore/Dispatcher.c +++ b/MdeModulePkg/Core/PiSmmCore/Dispatcher.c @@ -40,9 +40,9 @@ // #define KNOWN_HANDLE_SIGNATURE SIGNATURE_32('k','n','o','w') typedef struct { - UINTN Signature; - LIST_ENTRY Link; // mFvHandleList - EFI_HANDLE Handle; + UINTN Signature; + LIST_ENTRY Link; // mFvHandleList + EFI_HANDLE Handle; } KNOWN_HANDLE; // @@ -62,7 +62,7 @@ typedef struct { **/ VOID SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( - IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry + IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry ); // @@ -95,7 +95,7 @@ BOOLEAN gRequestDispatch = FALSE; // // List of file types supported by dispatcher // -EFI_FV_FILETYPE mSmmFileTypes[] = { +EFI_FV_FILETYPE mSmmFileTypes[] = { EFI_FV_FILETYPE_SMM, EFI_FV_FILETYPE_COMBINED_SMM_DXE, EFI_FV_FILETYPE_SMM_CORE, @@ -106,8 +106,8 @@ EFI_FV_FILETYPE mSmmFileTypes[] = { }; typedef struct { - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH File; - EFI_DEVICE_PATH_PROTOCOL End; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH File; + EFI_DEVICE_PATH_PROTOCOL End; } FV_FILEPATH_DEVICE_PATH; FV_FILEPATH_DEVICE_PATH mFvDevicePath; @@ -115,15 +115,15 @@ FV_FILEPATH_DEVICE_PATH mFvDevicePath; // // DXE Architecture Protocols // -EFI_SECURITY_ARCH_PROTOCOL *mSecurity = NULL; -EFI_SECURITY2_ARCH_PROTOCOL *mSecurity2 = NULL; +EFI_SECURITY_ARCH_PROTOCOL *mSecurity = NULL; +EFI_SECURITY2_ARCH_PROTOCOL *mSecurity2 = NULL; // // The global variable is defined for Loading modules at fixed address feature to track the SMM code // memory range usage. It is a bit mapped array in which every bit indicates the corresponding // memory page available or not. // -GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mSmmCodeMemoryRangeUsageBitMap=NULL; +GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mSmmCodeMemoryRangeUsageBitMap = NULL; /** To check memory usage bit map array to figure out if the memory range in which the image will be loaded is available or not. If @@ -138,64 +138,70 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mSmmCodeMemoryRangeUsage **/ EFI_STATUS CheckAndMarkFixLoadingMemoryUsageBitMap ( - IN EFI_PHYSICAL_ADDRESS ImageBase, - IN UINTN ImageSize + IN EFI_PHYSICAL_ADDRESS ImageBase, + IN UINTN ImageSize ) { - UINT32 SmmCodePageNumber; - UINT64 SmmCodeSize; - EFI_PHYSICAL_ADDRESS SmmCodeBase; - UINTN BaseOffsetPageNumber; - UINTN TopOffsetPageNumber; - UINTN Index; - // - // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber - // - SmmCodePageNumber = PcdGet32(PcdLoadFixAddressSmmCodePageNumber); - SmmCodeSize = EFI_PAGES_TO_SIZE (SmmCodePageNumber); - SmmCodeBase = gLoadModuleAtFixAddressSmramBase; - - // - // If the memory usage bit map is not initialized, do it. Every bit in the array - // indicate the status of the corresponding memory page, available or not - // - if (mSmmCodeMemoryRangeUsageBitMap == NULL) { - mSmmCodeMemoryRangeUsageBitMap = AllocateZeroPool(((SmmCodePageNumber / 64) + 1)*sizeof(UINT64)); - } - // - // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND - // - if (mSmmCodeMemoryRangeUsageBitMap == NULL) { - return EFI_NOT_FOUND; - } - // - // see if the memory range for loading the image is in the SMM code range. - // - if (SmmCodeBase + SmmCodeSize < ImageBase + ImageSize || SmmCodeBase > ImageBase) { - return EFI_NOT_FOUND; - } - // - // Test if the memory is available or not. - // - BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - SmmCodeBase)); - TopOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - SmmCodeBase)); - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - if ((mSmmCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) { - // - // This page is already used. - // - return EFI_NOT_FOUND; - } - } - - // - // Being here means the memory range is available. So mark the bits for the memory range - // - for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) { - mSmmCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64)); - } - return EFI_SUCCESS; + UINT32 SmmCodePageNumber; + UINT64 SmmCodeSize; + EFI_PHYSICAL_ADDRESS SmmCodeBase; + UINTN BaseOffsetPageNumber; + UINTN TopOffsetPageNumber; + UINTN Index; + + // + // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber + // + SmmCodePageNumber = PcdGet32 (PcdLoadFixAddressSmmCodePageNumber); + SmmCodeSize = EFI_PAGES_TO_SIZE (SmmCodePageNumber); + SmmCodeBase = gLoadModuleAtFixAddressSmramBase; + + // + // If the memory usage bit map is not initialized, do it. Every bit in the array + // indicate the status of the corresponding memory page, available or not + // + if (mSmmCodeMemoryRangeUsageBitMap == NULL) { + mSmmCodeMemoryRangeUsageBitMap = AllocateZeroPool (((SmmCodePageNumber / 64) + 1)*sizeof (UINT64)); + } + + // + // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND + // + if (mSmmCodeMemoryRangeUsageBitMap == NULL) { + return EFI_NOT_FOUND; + } + + // + // see if the memory range for loading the image is in the SMM code range. + // + if ((SmmCodeBase + SmmCodeSize < ImageBase + ImageSize) || (SmmCodeBase > ImageBase)) { + return EFI_NOT_FOUND; + } + + // + // Test if the memory is available or not. + // + BaseOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase - SmmCodeBase)); + TopOffsetPageNumber = EFI_SIZE_TO_PAGES ((UINT32)(ImageBase + ImageSize - SmmCodeBase)); + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + if ((mSmmCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64 (1, (Index % 64))) != 0) { + // + // This page is already used. + // + return EFI_NOT_FOUND; + } + } + + // + // Being here means the memory range is available. So mark the bits for the memory range + // + for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index++) { + mSmmCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64 (1, (Index % 64)); + } + + return EFI_SUCCESS; } + /** Get the fixed loading address from image header assigned by build tool. This function only be called when Loading module at Fixed address feature enabled. @@ -207,27 +213,27 @@ CheckAndMarkFixLoadingMemoryUsageBitMap ( **/ EFI_STATUS -GetPeCoffImageFixLoadingAssignedAddress( +GetPeCoffImageFixLoadingAssignedAddress ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) { - UINTN SectionHeaderOffset; - EFI_STATUS Status; - EFI_IMAGE_SECTION_HEADER SectionHeader; - EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; - EFI_PHYSICAL_ADDRESS FixLoadingAddress; - UINT16 Index; - UINTN Size; - UINT16 NumberOfSections; - UINT64 ValueInSectionHeader; + UINTN SectionHeaderOffset; + EFI_STATUS Status; + EFI_IMAGE_SECTION_HEADER SectionHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + EFI_PHYSICAL_ADDRESS FixLoadingAddress; + UINT16 Index; + UINTN Size; + UINT16 NumberOfSections; + UINT64 ValueInSectionHeader; FixLoadingAddress = 0; - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; // // Get PeHeader pointer // - ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset); + ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8 *)ImageContext->Handle + ImageContext->PeCoffHeaderOffset); SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) + @@ -241,13 +247,13 @@ GetPeCoffImageFixLoadingAssignedAddress( // // Read section header from file // - Size = sizeof (EFI_IMAGE_SECTION_HEADER); + Size = sizeof (EFI_IMAGE_SECTION_HEADER); Status = ImageContext->ImageRead ( - ImageContext->Handle, - SectionHeaderOffset, - &Size, - &SectionHeader - ); + ImageContext->Handle, + SectionHeaderOffset, + &Size, + &SectionHeader + ); if (EFI_ERROR (Status)) { return Status; } @@ -261,7 +267,7 @@ GetPeCoffImageFixLoadingAssignedAddress( // if a module with a loading address assigned by tools, the PointerToRelocations & PointerToLineNumbers fields // should not be Zero, or else, these 2 fields should be set to Zero // - ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations); + ValueInSectionHeader = ReadUnaligned64 ((UINT64 *)&SectionHeader.PointerToRelocations); if (ValueInSectionHeader != 0) { // // Found first section header that doesn't point to code section in which build tool saves the @@ -272,20 +278,24 @@ GetPeCoffImageFixLoadingAssignedAddress( // Check if the memory range is available. // Status = CheckAndMarkFixLoadingMemoryUsageBitMap (FixLoadingAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment)); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { // // The assigned address is valid. Return the specified loading address // ImageContext->ImageAddress = FixLoadingAddress; } } + break; } + SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); } + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r\n", FixLoadingAddress, Status)); return Status; } + /** Loads an EFI image into SMRAM. @@ -318,11 +328,11 @@ SmmLoadImage ( PERF_LOAD_IMAGE_BEGIN (DriverEntry->ImageHandle); - Buffer = NULL; - Size = 0; - Fv = DriverEntry->Fv; - NameGuid = &DriverEntry->FileName; - FilePath = DriverEntry->FvFileDevicePath; + Buffer = NULL; + Size = 0; + Fv = DriverEntry->Fv; + NameGuid = &DriverEntry->FileName; + FilePath = DriverEntry->FvFileDevicePath; OriginalFilePath = FilePath; HandleFilePath = FilePath; @@ -335,7 +345,7 @@ SmmLoadImage ( // Try to get the image device handle by checking the match protocol. // Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &HandleFilePath, &DeviceHandle); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -343,11 +353,13 @@ SmmLoadImage ( // If the Security2 and Security Architectural Protocol has not been located yet, then attempt to locate it // if (mSecurity2 == NULL) { - gBS->LocateProtocol (&gEfiSecurity2ArchProtocolGuid, NULL, (VOID**)&mSecurity2); + gBS->LocateProtocol (&gEfiSecurity2ArchProtocolGuid, NULL, (VOID **)&mSecurity2); } + if (mSecurity == NULL) { - gBS->LocateProtocol (&gEfiSecurityArchProtocolGuid, NULL, (VOID**)&mSecurity); + gBS->LocateProtocol (&gEfiSecurityArchProtocolGuid, NULL, (VOID **)&mSecurity); } + // // When Security2 is installed, Security Architectural Protocol must be published. // @@ -357,10 +369,10 @@ SmmLoadImage ( // Pull out just the file portion of the DevicePath for the LoadedImage FilePath // FilePath = OriginalFilePath; - Status = gBS->HandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath); + Status = gBS->HandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath); if (!EFI_ERROR (Status)) { - FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL); - FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize ); + FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); + FilePath = (EFI_DEVICE_PATH_PROTOCOL *)(((UINT8 *)FilePath) + FilePathSize); } // @@ -383,20 +395,21 @@ SmmLoadImage ( Buffer = NULL; Size = 0; Status = Fv->ReadSection ( - Fv, - NameGuid, - EFI_SECTION_TE, - 0, - &Buffer, - &Size, - &AuthenticationStatus - ); + Fv, + NameGuid, + EFI_SECTION_TE, + 0, + &Buffer, + &Size, + &AuthenticationStatus + ); } if (EFI_ERROR (Status)) { if (Buffer != NULL) { gBS->FreePool (Buffer); } + return Status; } @@ -405,12 +418,12 @@ SmmLoadImage ( // if (mSecurity2 != NULL) { SecurityStatus = mSecurity2->FileAuthentication ( - mSecurity2, - OriginalFilePath, - Buffer, - Size, - FALSE - ); + mSecurity2, + OriginalFilePath, + Buffer, + Size, + FALSE + ); } // @@ -426,7 +439,7 @@ SmmLoadImage ( ); } - if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) { + if (EFI_ERROR (SecurityStatus) && (SecurityStatus != EFI_SECURITY_VIOLATION)) { Status = SecurityStatus; return Status; } @@ -434,7 +447,7 @@ SmmLoadImage ( // // Initialize ImageContext // - ImageContext.Handle = Buffer; + ImageContext.Handle = Buffer; ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory; // @@ -445,13 +458,15 @@ SmmLoadImage ( if (Buffer != NULL) { gBS->FreePool (Buffer); } + return Status; } + // // if Loading module at Fixed Address feature is enabled, then cut out a memory range started from TESG BASE // to hold the Smm driver code // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { // // Get the fixed loading address assigned by Build tool // @@ -464,46 +479,50 @@ SmmLoadImage ( PageCount = 0; DstBuffer = (UINTN)gLoadModuleAtFixAddressSmramBase; } else { - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n")); - // - // allocate the memory to load the SMM driver - // - PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); - DstBuffer = (UINTN)(-1); - - Status = SmmAllocatePages ( - AllocateMaxAddress, - EfiRuntimeServicesCode, - PageCount, - &DstBuffer - ); - if (EFI_ERROR (Status)) { - if (Buffer != NULL) { - gBS->FreePool (Buffer); - } - return Status; - } + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n")); + // + // allocate the memory to load the SMM driver + // + PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); + DstBuffer = (UINTN)(-1); + + Status = SmmAllocatePages ( + AllocateMaxAddress, + EfiRuntimeServicesCode, + PageCount, + &DstBuffer + ); + if (EFI_ERROR (Status)) { + if (Buffer != NULL) { + gBS->FreePool (Buffer); + } + + return Status; + } + ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer; } } else { - PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); - DstBuffer = (UINTN)(-1); - - Status = SmmAllocatePages ( - AllocateMaxAddress, - EfiRuntimeServicesCode, - PageCount, - &DstBuffer - ); - if (EFI_ERROR (Status)) { - if (Buffer != NULL) { - gBS->FreePool (Buffer); - } - return Status; - } - - ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer; + PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); + DstBuffer = (UINTN)(-1); + + Status = SmmAllocatePages ( + AllocateMaxAddress, + EfiRuntimeServicesCode, + PageCount, + &DstBuffer + ); + if (EFI_ERROR (Status)) { + if (Buffer != NULL) { + gBS->FreePool (Buffer); + } + + return Status; + } + + ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer; } + // // Align buffer on section boundary // @@ -518,6 +537,7 @@ SmmLoadImage ( if (Buffer != NULL) { gBS->FreePool (Buffer); } + SmmFreePages (DstBuffer, PageCount); return Status; } @@ -530,6 +550,7 @@ SmmLoadImage ( if (Buffer != NULL) { gBS->FreePool (Buffer); } + SmmFreePages (DstBuffer, PageCount); return Status; } @@ -537,14 +558,14 @@ SmmLoadImage ( // // Flush the instruction cache so the image data are written before we execute it // - InvalidateInstructionCacheRange ((VOID *)(UINTN) ImageContext.ImageAddress, (UINTN) ImageContext.ImageSize); + InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize); // // Save Image EntryPoint in DriverEntry // - DriverEntry->ImageEntryPoint = ImageContext.EntryPoint; - DriverEntry->ImageBuffer = DstBuffer; - DriverEntry->NumberOfPage = PageCount; + DriverEntry->ImageEntryPoint = ImageContext.EntryPoint; + DriverEntry->ImageBuffer = DstBuffer; + DriverEntry->NumberOfPage = PageCount; // // Allocate a Loaded Image Protocol in EfiBootServicesData @@ -554,6 +575,7 @@ SmmLoadImage ( if (Buffer != NULL) { gBS->FreePool (Buffer); } + SmmFreePages (DstBuffer, PageCount); return Status; } @@ -563,10 +585,10 @@ SmmLoadImage ( // Fill in the remaining fields of the Loaded Image Protocol instance. // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed. // - DriverEntry->LoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; - DriverEntry->LoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle; - DriverEntry->LoadedImage->SystemTable = gST; - DriverEntry->LoadedImage->DeviceHandle = DeviceHandle; + DriverEntry->LoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; + DriverEntry->LoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle; + DriverEntry->LoadedImage->SystemTable = gST; + DriverEntry->LoadedImage->DeviceHandle = DeviceHandle; DriverEntry->SmmLoadedImage.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; DriverEntry->SmmLoadedImage.ParentHandle = gSmmCorePrivate->SmmIplImageHandle; @@ -581,12 +603,14 @@ SmmLoadImage ( if (Buffer != NULL) { gBS->FreePool (Buffer); } + SmmFreePages (DstBuffer, PageCount); return Status; } + CopyMem (DriverEntry->LoadedImage->FilePath, FilePath, GetDevicePathSize (FilePath)); - DriverEntry->LoadedImage->ImageBase = (VOID *)(UINTN) ImageContext.ImageAddress; + DriverEntry->LoadedImage->ImageBase = (VOID *)(UINTN)ImageContext.ImageAddress; DriverEntry->LoadedImage->ImageSize = ImageContext.ImageSize; DriverEntry->LoadedImage->ImageCodeType = EfiRuntimeServicesCode; DriverEntry->LoadedImage->ImageDataType = EfiRuntimeServicesData; @@ -594,19 +618,21 @@ SmmLoadImage ( // // Make a buffer copy of FilePath // - Status = SmmAllocatePool (EfiRuntimeServicesData, GetDevicePathSize(FilePath), (VOID **)&DriverEntry->SmmLoadedImage.FilePath); + Status = SmmAllocatePool (EfiRuntimeServicesData, GetDevicePathSize (FilePath), (VOID **)&DriverEntry->SmmLoadedImage.FilePath); if (EFI_ERROR (Status)) { if (Buffer != NULL) { gBS->FreePool (Buffer); } + gBS->FreePool (DriverEntry->LoadedImage->FilePath); SmmFreePages (DstBuffer, PageCount); return Status; } - CopyMem (DriverEntry->SmmLoadedImage.FilePath, FilePath, GetDevicePathSize(FilePath)); - DriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN) ImageContext.ImageAddress; - DriverEntry->SmmLoadedImage.ImageSize = ImageContext.ImageSize; + CopyMem (DriverEntry->SmmLoadedImage.FilePath, FilePath, GetDevicePathSize (FilePath)); + + DriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN)ImageContext.ImageAddress; + DriverEntry->SmmLoadedImage.ImageSize = ImageContext.ImageSize; DriverEntry->SmmLoadedImage.ImageCodeType = EfiRuntimeServicesCode; DriverEntry->SmmLoadedImage.ImageDataType = EfiRuntimeServicesData; @@ -614,22 +640,23 @@ SmmLoadImage ( // Create a new image handle in the UEFI handle database for the SMM Driver // DriverEntry->ImageHandle = NULL; - Status = gBS->InstallMultipleProtocolInterfaces ( - &DriverEntry->ImageHandle, - &gEfiLoadedImageProtocolGuid, DriverEntry->LoadedImage, - NULL - ); + Status = gBS->InstallMultipleProtocolInterfaces ( + &DriverEntry->ImageHandle, + &gEfiLoadedImageProtocolGuid, + DriverEntry->LoadedImage, + NULL + ); // // Create a new image handle in the SMM handle database for the SMM Driver // DriverEntry->SmmImageHandle = NULL; - Status = SmmInstallProtocolInterface ( - &DriverEntry->SmmImageHandle, - &gEfiLoadedImageProtocolGuid, - EFI_NATIVE_INTERFACE, - &DriverEntry->SmmLoadedImage - ); + Status = SmmInstallProtocolInterface ( + &DriverEntry->SmmImageHandle, + &gEfiLoadedImageProtocolGuid, + EFI_NATIVE_INTERFACE, + &DriverEntry->SmmLoadedImage + ); PERF_LOAD_IMAGE_END (DriverEntry->ImageHandle); @@ -639,53 +666,57 @@ SmmLoadImage ( DEBUG_CODE_BEGIN (); - UINTN Index; - UINTN StartIndex; - CHAR8 EfiFileName[256]; - + UINTN Index; + UINTN StartIndex; + CHAR8 EfiFileName[256]; - DEBUG ((DEBUG_INFO | DEBUG_LOAD, - "Loading SMM driver at 0x%11p EntryPoint=0x%11p ", - (VOID *)(UINTN) ImageContext.ImageAddress, - FUNCTION_ENTRY_POINT (ImageContext.EntryPoint))); + DEBUG (( + DEBUG_INFO | DEBUG_LOAD, + "Loading SMM driver at 0x%11p EntryPoint=0x%11p ", + (VOID *)(UINTN)ImageContext.ImageAddress, + FUNCTION_ENTRY_POINT (ImageContext.EntryPoint) + )); + // + // Print Module Name by Pdb file path. + // Windows and Unix style file path are all trimmed correctly. + // + if (ImageContext.PdbPointer != NULL) { + StartIndex = 0; + for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) { + if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) { + StartIndex = Index + 1; + } + } // - // Print Module Name by Pdb file path. - // Windows and Unix style file path are all trimmed correctly. + // Copy the PDB file name to our temporary string, and replace .pdb with .efi + // The PDB file name is limited in the range of 0~255. + // If the length is bigger than 255, trim the redundant characters to avoid overflow in array boundary. // - if (ImageContext.PdbPointer != NULL) { - StartIndex = 0; - for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) { - if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) { - StartIndex = Index + 1; - } - } - // - // Copy the PDB file name to our temporary string, and replace .pdb with .efi - // The PDB file name is limited in the range of 0~255. - // If the length is bigger than 255, trim the redundant characters to avoid overflow in array boundary. - // - for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { - EfiFileName[Index] = ImageContext.PdbPointer[Index + StartIndex]; - if (EfiFileName[Index] == 0) { - EfiFileName[Index] = '.'; - } - if (EfiFileName[Index] == '.') { - EfiFileName[Index + 1] = 'e'; - EfiFileName[Index + 2] = 'f'; - EfiFileName[Index + 3] = 'i'; - EfiFileName[Index + 4] = 0; - break; - } + for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { + EfiFileName[Index] = ImageContext.PdbPointer[Index + StartIndex]; + if (EfiFileName[Index] == 0) { + EfiFileName[Index] = '.'; } - if (Index == sizeof (EfiFileName) - 4) { - EfiFileName[Index] = 0; + if (EfiFileName[Index] == '.') { + EfiFileName[Index + 1] = 'e'; + EfiFileName[Index + 2] = 'f'; + EfiFileName[Index + 3] = 'i'; + EfiFileName[Index + 4] = 0; + break; } - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex])); } - DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n")); + + if (Index == sizeof (EfiFileName) - 4) { + EfiFileName[Index] = 0; + } + + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex])); + } + + DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n")); DEBUG_CODE_END (); @@ -695,10 +726,11 @@ SmmLoadImage ( // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection // used the UEFI Boot Services AllocatePool() function // - Status = gBS->FreePool(Buffer); + Status = gBS->FreePool (Buffer); if (!EFI_ERROR (Status) && EFI_ERROR (SecurityStatus)) { Status = SecurityStatus; } + return Status; } @@ -719,7 +751,7 @@ SmmPreProcessDepex ( { UINT8 *Iterator; - Iterator = DriverEntry->Depex; + Iterator = DriverEntry->Depex; DriverEntry->Dependent = TRUE; if (*Iterator == EFI_DEP_BEFORE) { @@ -763,16 +795,16 @@ SmmGetDepexSectionAndPreProccess ( // Grab Depex info, it will never be free'ed. // (Note: DriverEntry->Depex is in DXE memory) // - SectionType = EFI_SECTION_SMM_DEPEX; - Status = Fv->ReadSection ( - DriverEntry->Fv, - &DriverEntry->FileName, - SectionType, - 0, - &DriverEntry->Depex, - (UINTN *)&DriverEntry->DepexSize, - &AuthenticationStatus - ); + SectionType = EFI_SECTION_SMM_DEPEX; + Status = Fv->ReadSection ( + DriverEntry->Fv, + &DriverEntry->FileName, + SectionType, + 0, + &DriverEntry->Depex, + (UINTN *)&DriverEntry->DepexSize, + &AuthenticationStatus + ); if (EFI_ERROR (Status)) { if (Status == EFI_PROTOCOL_ERROR) { // @@ -783,8 +815,8 @@ SmmGetDepexSectionAndPreProccess ( // // If no Depex assume depend on all architectural protocols // - DriverEntry->Depex = NULL; - DriverEntry->Dependent = TRUE; + DriverEntry->Depex = NULL; + DriverEntry->Dependent = TRUE; DriverEntry->DepexProtocolError = FALSE; } } else { @@ -867,8 +899,8 @@ SmmDispatcher ( // The SMM Driver could not be loaded, and do not attempt to load or start it again. // Take driver from Scheduled to Initialized. // - DriverEntry->Initialized = TRUE; - DriverEntry->Scheduled = FALSE; + DriverEntry->Initialized = TRUE; + DriverEntry->Scheduled = FALSE; RemoveEntryList (&DriverEntry->ScheduledLink); // @@ -878,8 +910,8 @@ SmmDispatcher ( } } - DriverEntry->Scheduled = FALSE; - DriverEntry->Initialized = TRUE; + DriverEntry->Scheduled = FALSE; + DriverEntry->Initialized = TRUE; RemoveEntryList (&DriverEntry->ScheduledLink); REPORT_STATUS_CODE_WITH_EXTENDED_DATA ( @@ -901,7 +933,7 @@ SmmDispatcher ( PERF_START_IMAGE_BEGIN (DriverEntry->ImageHandle); Status = ((EFI_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint)(DriverEntry->ImageHandle, gST); PERF_START_IMAGE_END (DriverEntry->ImageHandle); - if (EFI_ERROR(Status)){ + if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "Error: SMM image at %11p start failed: %r\n", @@ -909,7 +941,7 @@ SmmDispatcher ( Status )); UnregisterSmramProfileImage (DriverEntry, TRUE); - SmmFreePages(DriverEntry->ImageBuffer, DriverEntry->NumberOfPage); + SmmFreePages (DriverEntry->ImageBuffer, DriverEntry->NumberOfPage); // // Uninstall LoadedImage // @@ -922,14 +954,16 @@ SmmDispatcher ( if (DriverEntry->LoadedImage->FilePath != NULL) { gBS->FreePool (DriverEntry->LoadedImage->FilePath); } + gBS->FreePool (DriverEntry->LoadedImage); } + Status = SmmUninstallProtocolInterface ( DriverEntry->SmmImageHandle, &gEfiLoadedImageProtocolGuid, &DriverEntry->SmmLoadedImage ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { if (DriverEntry->SmmLoadedImage.FilePath != NULL) { SmmFreePool (DriverEntry->SmmLoadedImage.FilePath); } @@ -952,7 +986,7 @@ SmmDispatcher ( // Once the SMM Entry Point has been registered, then SMM Mode will be // used. // - gRequestDispatch = TRUE; + gRequestDispatch = TRUE; gDispatcherRunning = FALSE; return EFI_NOT_READY; } @@ -965,7 +999,7 @@ SmmDispatcher ( for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->DepexProtocolError){ + if (DriverEntry->DepexProtocolError) { // // If Section Extraction Protocol did not let the Depex be read before retry the read // @@ -988,7 +1022,7 @@ SmmDispatcher ( for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); - if (!DriverEntry->Initialized){ + if (!DriverEntry->Initialized) { // // We have SMM driver pending to dispatch // @@ -1015,18 +1049,18 @@ SmmDispatcher ( **/ VOID SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( - IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry + IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry ) { LIST_ENTRY *Link; - EFI_SMM_DRIVER_ENTRY *DriverEntry; + EFI_SMM_DRIVER_ENTRY *DriverEntry; // // Process Before Dependency // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) { + DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); + if (DriverEntry->Before && DriverEntry->Dependent && (DriverEntry != InsertedDriverEntry)) { DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName)); DEBUG ((DEBUG_DISPATCH, " BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid)); if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) { @@ -1049,13 +1083,12 @@ SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter ( InsertedDriverEntry->Scheduled = TRUE; InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink); - // // Process After Dependency // for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); - if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) { + DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); + if (DriverEntry->After && DriverEntry->Dependent && (DriverEntry != InsertedDriverEntry)) { DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName)); DEBUG ((DEBUG_DISPATCH, " AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid)); if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) { @@ -1090,11 +1123,12 @@ FvHasBeenProcessed ( KNOWN_HANDLE *KnownHandle; for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) { - KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); + KnownHandle = CR (Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE); if (KnownHandle->Handle == FvHandle) { return TRUE; } } + return FALSE; } @@ -1117,7 +1151,7 @@ FvIsBeingProcessed ( ASSERT (KnownHandle != NULL); KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE; - KnownHandle->Handle = FvHandle; + KnownHandle->Handle = FvHandle; InsertTailList (&mFvHandleList, &KnownHandle->Link); } @@ -1136,14 +1170,14 @@ FvIsBeingProcessed ( **/ EFI_DEVICE_PATH_PROTOCOL * SmmFvToDevicePath ( - IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, - IN EFI_HANDLE FvHandle, - IN EFI_GUID *DriverName + IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv, + IN EFI_HANDLE FvHandle, + IN EFI_GUID *DriverName ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; - EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; + EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath; // // Remember the device path of the FV @@ -1162,10 +1196,11 @@ SmmFvToDevicePath ( // Note: FileNameDevicePath is in DXE memory // FileNameDevicePath = AppendDevicePath ( - FvDevicePath, - (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath - ); + FvDevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath + ); } + return FileNameDevicePath; } @@ -1205,7 +1240,7 @@ SmmAddToDriverList ( DriverEntry = AllocateZeroPool (sizeof (EFI_SMM_DRIVER_ENTRY)); ASSERT (DriverEntry != NULL); - DriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE; + DriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE; CopyGuid (&DriverEntry->FileName, DriverName); DriverEntry->FvHandle = FvHandle; DriverEntry->Fv = Fv; @@ -1253,36 +1288,36 @@ SmmDriverDispatchHandler ( IN OUT UINTN *CommBufferSize OPTIONAL ) { - EFI_STATUS Status; - UINTN HandleCount; - EFI_HANDLE *HandleBuffer; - EFI_STATUS GetNextFileStatus; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; - EFI_HANDLE FvHandle; - EFI_GUID NameGuid; - UINTN Key; - EFI_FV_FILETYPE Type; - EFI_FV_FILE_ATTRIBUTES Attributes; - UINTN Size; - EFI_SMM_DRIVER_ENTRY *DriverEntry; - EFI_GUID *AprioriFile; - UINTN AprioriEntryCount; - UINTN HandleIndex; - UINTN SmmTypeIndex; - UINTN AprioriIndex; - LIST_ENTRY *Link; - UINT32 AuthenticationStatus; - UINTN SizeOfBuffer; + EFI_STATUS Status; + UINTN HandleCount; + EFI_HANDLE *HandleBuffer; + EFI_STATUS GetNextFileStatus; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; + EFI_DEVICE_PATH_PROTOCOL *FvDevicePath; + EFI_HANDLE FvHandle; + EFI_GUID NameGuid; + UINTN Key; + EFI_FV_FILETYPE Type; + EFI_FV_FILE_ATTRIBUTES Attributes; + UINTN Size; + EFI_SMM_DRIVER_ENTRY *DriverEntry; + EFI_GUID *AprioriFile; + UINTN AprioriEntryCount; + UINTN HandleIndex; + UINTN SmmTypeIndex; + UINTN AprioriIndex; + LIST_ENTRY *Link; + UINT32 AuthenticationStatus; + UINTN SizeOfBuffer; HandleBuffer = NULL; - Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiFirmwareVolume2ProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiFirmwareVolume2ProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); if (EFI_ERROR (Status)) { return EFI_NOT_FOUND; } @@ -1330,7 +1365,7 @@ SmmDriverDispatchHandler ( // Key = 0; do { - Type = mSmmFileTypes[SmmTypeIndex]; + Type = mSmmFileTypes[SmmTypeIndex]; GetNextFileStatus = Fv->GetNextFile ( Fv, &Key, @@ -1365,6 +1400,7 @@ SmmDriverDispatchHandler ( mSmmCoreLoadedImage->DeviceHandle = FvHandle; } + if (mSmmCoreDriverEntry->SmmLoadedImage.FilePath == NULL) { // // Maybe one special FV contains only one SMM_CORE module, so its device path must @@ -1382,7 +1418,7 @@ SmmDriverDispatchHandler ( (VOID **)&mSmmCoreDriverEntry->SmmLoadedImage.FilePath ); ASSERT_EFI_ERROR (Status); - CopyMem (mSmmCoreDriverEntry->SmmLoadedImage.FilePath, &mFvDevicePath, GetDevicePathSize((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath)); + CopyMem (mSmmCoreDriverEntry->SmmLoadedImage.FilePath, &mFvDevicePath, GetDevicePathSize ((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath)); mSmmCoreDriverEntry->SmmLoadedImage.DeviceHandle = FvHandle; } @@ -1398,15 +1434,15 @@ SmmDriverDispatchHandler ( // (Note: AprioriFile is in DXE memory) // AprioriFile = NULL; - Status = Fv->ReadSection ( - Fv, - &gAprioriGuid, - EFI_SECTION_RAW, - 0, - (VOID **)&AprioriFile, - &SizeOfBuffer, - &AuthenticationStatus - ); + Status = Fv->ReadSection ( + Fv, + &gAprioriGuid, + EFI_SECTION_RAW, + 0, + (VOID **)&AprioriFile, + &SizeOfBuffer, + &AuthenticationStatus + ); if (!EFI_ERROR (Status)) { AprioriEntryCount = SizeOfBuffer / sizeof (EFI_GUID); } else { @@ -1421,9 +1457,10 @@ SmmDriverDispatchHandler ( for (AprioriIndex = 0; AprioriIndex < AprioriEntryCount; AprioriIndex++) { for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); + DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); if (CompareGuid (&DriverEntry->FileName, &AprioriFile[AprioriIndex]) && - (FvHandle == DriverEntry->FvHandle)) { + (FvHandle == DriverEntry->FvHandle)) + { DriverEntry->Dependent = FALSE; DriverEntry->Scheduled = TRUE; InsertTailList (&mScheduledQueue, &DriverEntry->ScheduledLink); @@ -1452,7 +1489,7 @@ SmmDriverDispatchHandler ( // // Check to see if CommBuffer and CommBufferSize are valid // - if (CommBuffer != NULL && CommBufferSize != NULL) { + if ((CommBuffer != NULL) && (CommBufferSize != NULL)) { if (*CommBufferSize > 0) { if (Status == EFI_NOT_READY) { // @@ -1487,11 +1524,11 @@ SmmDisplayDiscoveredNotDispatched ( VOID ) { - LIST_ENTRY *Link; - EFI_SMM_DRIVER_ENTRY *DriverEntry; + LIST_ENTRY *Link; + EFI_SMM_DRIVER_ENTRY *DriverEntry; - for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) { - DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); + for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) { + DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE); if (DriverEntry->Dependent) { DEBUG ((DEBUG_LOAD, "SMM Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName)); } diff --git a/MdeModulePkg/Core/PiSmmCore/Handle.c b/MdeModulePkg/Core/PiSmmCore/Handle.c index f8dbe46449..5a8760a430 100644 --- a/MdeModulePkg/Core/PiSmmCore/Handle.c +++ b/MdeModulePkg/Core/PiSmmCore/Handle.c @@ -12,8 +12,8 @@ // mProtocolDatabase - A list of all protocols in the system. (simple list for now) // gHandleList - A list of all the handles in the system // -LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); -LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); +LIST_ENTRY mProtocolDatabase = INITIALIZE_LIST_HEAD_VARIABLE (mProtocolDatabase); +LIST_ENTRY gHandleList = INITIALIZE_LIST_HEAD_VARIABLE (gHandleList); /** Check whether a handle is a valid EFI_HANDLE @@ -35,9 +35,11 @@ SmmValidateHandle ( if (Handle == NULL) { return EFI_INVALID_PARAMETER; } + if (Handle->Signature != EFI_HANDLE_SIGNATURE) { return EFI_INVALID_PARAMETER; } + return EFI_SUCCESS; } @@ -52,13 +54,13 @@ SmmValidateHandle ( **/ PROTOCOL_ENTRY * SmmFindProtocolEntry ( - IN EFI_GUID *Protocol, - IN BOOLEAN Create + IN EFI_GUID *Protocol, + IN BOOLEAN Create ) { - LIST_ENTRY *Link; - PROTOCOL_ENTRY *Item; - PROTOCOL_ENTRY *ProtEntry; + LIST_ENTRY *Link; + PROTOCOL_ENTRY *Item; + PROTOCOL_ENTRY *ProtEntry; // // Search the database for the matching GUID @@ -67,9 +69,9 @@ SmmFindProtocolEntry ( ProtEntry = NULL; for (Link = mProtocolDatabase.ForwardLink; Link != &mProtocolDatabase; - Link = Link->ForwardLink) { - - Item = CR(Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); + Link = Link->ForwardLink) + { + Item = CR (Link, PROTOCOL_ENTRY, AllEntries, PROTOCOL_ENTRY_SIGNATURE); if (CompareGuid (&Item->ProtocolID, Protocol)) { // // This is the protocol entry @@ -84,7 +86,7 @@ SmmFindProtocolEntry ( // allocate a new entry // if ((ProtEntry == NULL) && Create) { - ProtEntry = AllocatePool (sizeof(PROTOCOL_ENTRY)); + ProtEntry = AllocatePool (sizeof (PROTOCOL_ENTRY)); if (ProtEntry != NULL) { // // Initialize new protocol entry structure @@ -100,6 +102,7 @@ SmmFindProtocolEntry ( InsertTailList (&mProtocolDatabase, &ProtEntry->AllEntries); } } + return ProtEntry; } @@ -136,17 +139,19 @@ SmmFindProtocolInterface ( // // Look at each protocol interface for any matches // - for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link=Link->ForwardLink) { + for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { // // If this protocol interface matches, remove it // - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); - if (Prot->Interface == Interface && Prot->Protocol == ProtEntry) { + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + if ((Prot->Interface == Interface) && (Prot->Protocol == ProtEntry)) { break; } + Prot = NULL; } } + return Prot; } @@ -218,7 +223,7 @@ SmmInstallProtocolInterfaceNotify ( // returns EFI_INVALID_PARAMETER if InterfaceType is invalid. // Also added check for invalid UserHandle and Protocol pointers. // - if (UserHandle == NULL || Protocol == NULL) { + if ((UserHandle == NULL) || (Protocol == NULL)) { return EFI_INVALID_PARAMETER; } @@ -229,10 +234,10 @@ SmmInstallProtocolInterfaceNotify ( // // Print debug message // - DEBUG((DEBUG_LOAD | DEBUG_INFO, "SmmInstallProtocolInterface: %g %p\n", Protocol, Interface)); + DEBUG ((DEBUG_LOAD | DEBUG_INFO, "SmmInstallProtocolInterface: %g %p\n", Protocol, Interface)); Status = EFI_OUT_OF_RESOURCES; - Prot = NULL; + Prot = NULL; Handle = NULL; if (*UserHandle != NULL) { @@ -253,7 +258,7 @@ SmmInstallProtocolInterfaceNotify ( // // Allocate a new protocol interface structure // - Prot = AllocateZeroPool (sizeof(PROTOCOL_INTERFACE)); + Prot = AllocateZeroPool (sizeof (PROTOCOL_INTERFACE)); if (Prot == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -264,7 +269,7 @@ SmmInstallProtocolInterfaceNotify ( // Handle = (IHANDLE *)*UserHandle; if (Handle == NULL) { - Handle = AllocateZeroPool (sizeof(IHANDLE)); + Handle = AllocateZeroPool (sizeof (IHANDLE)); if (Handle == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; @@ -284,7 +289,7 @@ SmmInstallProtocolInterfaceNotify ( } else { Status = SmmValidateHandle (Handle); if (EFI_ERROR (Status)) { - DEBUG((DEBUG_ERROR, "SmmInstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); + DEBUG ((DEBUG_ERROR, "SmmInstallProtocolInterface: input handle at 0x%x is invalid\n", Handle)); goto Done; } } @@ -298,8 +303,8 @@ SmmInstallProtocolInterfaceNotify ( // Initialize the protocol interface structure // Prot->Signature = PROTOCOL_INTERFACE_SIGNATURE; - Prot->Handle = Handle; - Prot->Protocol = ProtEntry; + Prot->Handle = Handle; + Prot->Protocol = ProtEntry; Prot->Interface = Interface; // @@ -320,6 +325,7 @@ SmmInstallProtocolInterfaceNotify ( if (Notify) { SmmNotifyProtocol (Prot); } + Status = EFI_SUCCESS; Done: @@ -335,8 +341,10 @@ Done: if (Prot != NULL) { FreePool (Prot); } - DEBUG((DEBUG_ERROR, "SmmInstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); + + DEBUG ((DEBUG_ERROR, "SmmInstallProtocolInterface: %g %p failed with %r\n", Protocol, Interface, Status)); } + return Status; } @@ -417,6 +425,7 @@ SmmUninstallProtocolInterface ( RemoveEntryList (&Handle->AllHandles); FreePool (Handle); } + return Status; } @@ -452,12 +461,13 @@ SmmGetProtocolInterface ( // Look at each protocol interface for a match // for (Link = Handle->Protocols.ForwardLink; Link != &Handle->Protocols; Link = Link->ForwardLink) { - Prot = CR(Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); + Prot = CR (Link, PROTOCOL_INTERFACE, Link, PROTOCOL_INTERFACE_SIGNATURE); ProtEntry = Prot->Protocol; if (CompareGuid (&ProtEntry->ProtocolID, Protocol)) { return Prot; } } + return NULL; } diff --git a/MdeModulePkg/Core/PiSmmCore/HeapGuard.c b/MdeModulePkg/Core/PiSmmCore/HeapGuard.c index b0d0f72044..8f3bab6fee 100644 --- a/MdeModulePkg/Core/PiSmmCore/HeapGuard.c +++ b/MdeModulePkg/Core/PiSmmCore/HeapGuard.c @@ -12,34 +12,34 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Global to avoid infinite reentrance of memory allocation when updating // page table attributes, which may need allocating pages for new PDE/PTE. // -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE; // // Pointer to table tracking the Guarded memory with bitmap, in which '1' // is used to indicate memory guarded. '0' might be free memory or Guard // page itself, depending on status of memory adjacent to it. // -GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0; +GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0; // // Current depth level of map table pointed by mGuardedMemoryMap. // mMapLevel must be initialized at least by 1. It will be automatically // updated according to the address of memory just tracked. // -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1; // // Shift and mask for each level of map table // -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH] - = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS; -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH] - = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH] + = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH] + = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS; // // SMM memory attribute protocol // -EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *mSmmMemoryAttribute = NULL; +EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *mSmmMemoryAttribute = NULL; /** Set corresponding bits in bitmap table to 1 according to the address. @@ -53,29 +53,29 @@ EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *mSmmMemoryAttribute = NULL; STATIC VOID SetBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN Lsbs; - UINTN Qwords; - UINTN Msbs; - UINTN StartBit; - UINTN EndBit; + UINTN Lsbs; + UINTN Qwords; + UINTN Msbs; + UINTN StartBit; + UINTN EndBit; - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) >= GUARDED_HEAP_MAP_ENTRY_BITS) { - Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % - GUARDED_HEAP_MAP_ENTRY_BITS; - Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; - Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; + Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % + GUARDED_HEAP_MAP_ENTRY_BITS; + Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; } else { - Msbs = BitNumber; - Lsbs = 0; - Qwords = 0; + Msbs = BitNumber; + Lsbs = 0; + Qwords = 0; } if (Msbs > 0) { @@ -84,8 +84,11 @@ SetBits ( } if (Qwords > 0) { - SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, - (UINT64)-1); + SetMem64 ( + (VOID *)BitMap, + Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, + (UINT64)-1 + ); BitMap += Qwords; } @@ -106,29 +109,29 @@ SetBits ( STATIC VOID ClearBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN Lsbs; - UINTN Qwords; - UINTN Msbs; - UINTN StartBit; - UINTN EndBit; + UINTN Lsbs; + UINTN Qwords; + UINTN Msbs; + UINTN StartBit; + UINTN EndBit; - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) >= GUARDED_HEAP_MAP_ENTRY_BITS) { - Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % - GUARDED_HEAP_MAP_ENTRY_BITS; - Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; - Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; + Msbs = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) % + GUARDED_HEAP_MAP_ENTRY_BITS; + Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + Qwords = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS; } else { - Msbs = BitNumber; - Lsbs = 0; - Qwords = 0; + Msbs = BitNumber; + Lsbs = 0; + Qwords = 0; } if (Msbs > 0) { @@ -161,21 +164,21 @@ ClearBits ( STATIC UINT64 GetBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN BitNumber, - IN UINT64 *BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN BitNumber, + IN UINT64 *BitMap ) { - UINTN StartBit; - UINTN EndBit; - UINTN Lsbs; - UINTN Msbs; - UINT64 Result; + UINTN StartBit; + UINTN EndBit; + UINTN Lsbs; + UINTN Msbs; + UINT64 Result; ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS); - StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); - EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; + StartBit = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address); + EndBit = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS; if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) { Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit; @@ -185,13 +188,13 @@ GetBits ( Lsbs = 0; } - if (StartBit == 0 && BitNumber == GUARDED_HEAP_MAP_ENTRY_BITS) { + if ((StartBit == 0) && (BitNumber == GUARDED_HEAP_MAP_ENTRY_BITS)) { Result = *BitMap; } else { - Result = RShiftU64((*BitMap), StartBit) & (LShiftU64(1, Msbs) - 1); + Result = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1); if (Lsbs > 0) { - BitMap += 1; - Result |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs); + BitMap += 1; + Result |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs); } } @@ -210,11 +213,16 @@ PageAlloc ( IN UINTN Pages ) { - EFI_STATUS Status; - EFI_PHYSICAL_ADDRESS Memory; - - Status = SmmInternalAllocatePages (AllocateAnyPages, EfiRuntimeServicesData, - Pages, &Memory, FALSE); + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS Memory; + + Status = SmmInternalAllocatePages ( + AllocateAnyPages, + EfiRuntimeServicesData, + Pages, + &Memory, + FALSE + ); if (EFI_ERROR (Status)) { Memory = 0; } @@ -234,17 +242,17 @@ PageAlloc ( **/ UINTN FindGuardedMemoryMap ( - IN EFI_PHYSICAL_ADDRESS Address, - IN BOOLEAN AllocMapUnit, - OUT UINT64 **BitMap + IN EFI_PHYSICAL_ADDRESS Address, + IN BOOLEAN AllocMapUnit, + OUT UINT64 **BitMap ) { - UINTN Level; - UINT64 *GuardMap; - UINT64 MapMemory; - UINTN Index; - UINTN Size; - UINTN BitsToUnitEnd; + UINTN Level; + UINT64 *GuardMap; + UINT64 MapMemory; + UINTN Index; + UINTN Size; + UINTN BitsToUnitEnd; // // Adjust current map table depth according to the address to access @@ -254,8 +262,8 @@ FindGuardedMemoryMap ( RShiftU64 ( Address, mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] - ) != 0) { - + ) != 0) + { if (mGuardedMemoryMap != 0) { Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; @@ -265,25 +273,24 @@ FindGuardedMemoryMap ( SetMem ((VOID *)(UINTN)MapMemory, Size, 0); *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap; - mGuardedMemoryMap = MapMemory; + mGuardedMemoryMap = MapMemory; } mMapLevel++; - } GuardMap = &mGuardedMemoryMap; for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Level < GUARDED_HEAP_MAP_TABLE_DEPTH; - ++Level) { - + ++Level) + { if (*GuardMap == 0) { if (!AllocMapUnit) { GuardMap = NULL; break; } - Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; + Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES; MapMemory = (UINT64)(UINTN)PageAlloc (EFI_SIZE_TO_PAGES (Size)); ASSERT (MapMemory != 0); @@ -291,10 +298,9 @@ FindGuardedMemoryMap ( *GuardMap = MapMemory; } - Index = (UINTN)RShiftU64 (Address, mLevelShift[Level]); - Index &= mLevelMask[Level]; - GuardMap = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64)); - + Index = (UINTN)RShiftU64 (Address, mLevelShift[Level]); + Index &= mLevelMask[Level]; + GuardMap = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64)); } BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address); @@ -314,13 +320,13 @@ FindGuardedMemoryMap ( VOID EFIAPI SetGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINTN BitsToUnitEnd; while (NumberOfPages > 0) { BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap); @@ -330,7 +336,7 @@ SetGuardedMemoryBits ( // Cross map unit Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } SetBits (Address, Bits, BitMap); @@ -351,13 +357,13 @@ SetGuardedMemoryBits ( VOID EFIAPI ClearGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINTN BitsToUnitEnd; while (NumberOfPages > 0) { BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap); @@ -367,7 +373,7 @@ ClearGuardedMemoryBits ( // Cross map unit Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } ClearBits (Address, Bits, BitMap); @@ -387,15 +393,15 @@ ClearGuardedMemoryBits ( **/ UINTN GetGuardedMemoryBits ( - IN EFI_PHYSICAL_ADDRESS Address, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Address, + IN UINTN NumberOfPages ) { - UINT64 *BitMap; - UINTN Bits; - UINTN Result; - UINTN Shift; - UINTN BitsToUnitEnd; + UINT64 *BitMap; + UINTN Bits; + UINTN Result; + UINTN Shift; + UINTN BitsToUnitEnd; ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS); @@ -406,9 +412,9 @@ GetGuardedMemoryBits ( if (NumberOfPages > BitsToUnitEnd) { // Cross map unit - Bits = BitsToUnitEnd; + Bits = BitsToUnitEnd; } else { - Bits = NumberOfPages; + Bits = NumberOfPages; } if (BitMap != NULL) { @@ -433,15 +439,18 @@ GetGuardedMemoryBits ( UINTN EFIAPI GetGuardMapBit ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ) { - UINT64 *GuardMap; + UINT64 *GuardMap; FindGuardedMemoryMap (Address, FALSE, &GuardMap); if (GuardMap != NULL) { - if (RShiftU64 (*GuardMap, - GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) { + if (RShiftU64 ( + *GuardMap, + GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address) + ) & 1) + { return 1; } } @@ -449,7 +458,6 @@ GetGuardMapBit ( return 0; } - /** Check to see if the page at the given address is a Guard page or not. @@ -461,10 +469,10 @@ GetGuardMapBit ( BOOLEAN EFIAPI IsGuardPage ( - IN EFI_PHYSICAL_ADDRESS Address -) + IN EFI_PHYSICAL_ADDRESS Address + ) { - UINTN BitMap; + UINTN BitMap; // // There must be at least one guarded page before and/or after given @@ -475,8 +483,6 @@ IsGuardPage ( return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0))); } - - /** Check to see if the page at the given address is guarded or not. @@ -488,7 +494,7 @@ IsGuardPage ( BOOLEAN EFIAPI IsMemoryGuarded ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ) { return (GetGuardMapBit (Address) == 1); @@ -506,19 +512,19 @@ IsMemoryGuarded ( VOID EFIAPI SetGuardPage ( - IN EFI_PHYSICAL_ADDRESS BaseAddress + IN EFI_PHYSICAL_ADDRESS BaseAddress ) { - EFI_STATUS Status; + EFI_STATUS Status; if (mSmmMemoryAttribute != NULL) { mOnGuarding = TRUE; - Status = mSmmMemoryAttribute->SetMemoryAttributes ( - mSmmMemoryAttribute, - BaseAddress, - EFI_PAGE_SIZE, - EFI_MEMORY_RP - ); + Status = mSmmMemoryAttribute->SetMemoryAttributes ( + mSmmMemoryAttribute, + BaseAddress, + EFI_PAGE_SIZE, + EFI_MEMORY_RP + ); ASSERT_EFI_ERROR (Status); mOnGuarding = FALSE; } @@ -536,19 +542,19 @@ SetGuardPage ( VOID EFIAPI UnsetGuardPage ( - IN EFI_PHYSICAL_ADDRESS BaseAddress + IN EFI_PHYSICAL_ADDRESS BaseAddress ) { - EFI_STATUS Status; + EFI_STATUS Status; if (mSmmMemoryAttribute != NULL) { mOnGuarding = TRUE; - Status = mSmmMemoryAttribute->ClearMemoryAttributes ( - mSmmMemoryAttribute, - BaseAddress, - EFI_PAGE_SIZE, - EFI_MEMORY_RP - ); + Status = mSmmMemoryAttribute->ClearMemoryAttributes ( + mSmmMemoryAttribute, + BaseAddress, + EFI_PAGE_SIZE, + EFI_MEMORY_RP + ); ASSERT_EFI_ERROR (Status); mOnGuarding = FALSE; } @@ -567,17 +573,18 @@ UnsetGuardPage ( **/ BOOLEAN IsMemoryTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType, - IN UINT8 PageOrPool + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType, + IN UINT8 PageOrPool ) { - UINT64 TestBit; - UINT64 ConfigBit; + UINT64 TestBit; + UINT64 ConfigBit; - if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0 - || mOnGuarding - || AllocateType == AllocateAddress) { + if ( ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0) + || mOnGuarding + || (AllocateType == AllocateAddress)) + { return FALSE; } @@ -590,8 +597,9 @@ IsMemoryTypeToGuard ( ConfigBit |= PcdGet64 (PcdHeapGuardPageType); } - if (MemoryType == EfiRuntimeServicesData || - MemoryType == EfiRuntimeServicesCode) { + if ((MemoryType == EfiRuntimeServicesData) || + (MemoryType == EfiRuntimeServicesCode)) + { TestBit = LShiftU64 (1, MemoryType); } else if (MemoryType == EfiMaxMemoryType) { TestBit = (UINT64)-1; @@ -613,11 +621,14 @@ IsMemoryTypeToGuard ( **/ BOOLEAN IsPoolTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages, - GUARD_HEAP_TYPE_POOL); + return IsMemoryTypeToGuard ( + MemoryType, + AllocateAnyPages, + GUARD_HEAP_TYPE_POOL + ); } /** @@ -631,8 +642,8 @@ IsPoolTypeToGuard ( **/ BOOLEAN IsPageTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType ) { return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE); @@ -648,8 +659,11 @@ IsHeapGuardEnabled ( VOID ) { - return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages, - GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_PAGE); + return IsMemoryTypeToGuard ( + EfiMaxMemoryType, + AllocateAnyPages, + GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_PAGE + ); } /** @@ -662,11 +676,11 @@ IsHeapGuardEnabled ( **/ VOID SetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ) { - EFI_PHYSICAL_ADDRESS GuardPage; + EFI_PHYSICAL_ADDRESS GuardPage; // // Set tail Guard @@ -698,8 +712,8 @@ SetGuardForMemory ( **/ VOID UnsetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ) { EFI_PHYSICAL_ADDRESS GuardPage; @@ -721,7 +735,7 @@ UnsetGuardForMemory ( // ------------------- // Start -> -1 -2 // - GuardPage = Memory - EFI_PAGES_TO_SIZE (1); + GuardPage = Memory - EFI_PAGES_TO_SIZE (1); GuardBitmap = GetGuardedMemoryBits (Memory - EFI_PAGES_TO_SIZE (2), 2); if ((GuardBitmap & BIT1) == 0) { // @@ -754,7 +768,7 @@ UnsetGuardForMemory ( // -------------------- // +1 +0 <- End // - GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages); + GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages); GuardBitmap = GetGuardedMemoryBits (GuardPage, 2); if ((GuardBitmap & BIT0) == 0) { // @@ -778,11 +792,9 @@ UnsetGuardForMemory ( // // No matter what, we just clear the mark of the Guarded memory. // - ClearGuardedMemoryBits(Memory, NumberOfPages); + ClearGuardedMemoryBits (Memory, NumberOfPages); } - - /** Adjust the start address and number of pages to free according to Guard. @@ -797,8 +809,8 @@ UnsetGuardForMemory ( **/ VOID AdjustMemoryF ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ) { EFI_PHYSICAL_ADDRESS Start; @@ -807,11 +819,11 @@ AdjustMemoryF ( UINT64 GuardBitmap; UINT64 Attributes; - if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) { + if ((Memory == NULL) || (NumberOfPages == NULL) || (*NumberOfPages == 0)) { return; } - Start = *Memory; + Start = *Memory; PagesToFree = *NumberOfPages; // @@ -848,7 +860,7 @@ AdjustMemoryF ( // Start -> -1 -2 // MemoryToTest = Start - EFI_PAGES_TO_SIZE (2); - GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); + GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); if ((GuardBitmap & BIT1) == 0) { // // Head Guard exists. @@ -883,7 +895,7 @@ AdjustMemoryF ( // +1 +0 <- End // MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree); - GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); + GuardBitmap = GetGuardedMemoryBits (MemoryToTest, 2); if ((GuardBitmap & BIT0) == 0) { // // Tail Guard exists. @@ -903,11 +915,10 @@ AdjustMemoryF ( PagesToFree -= 1; } - *Memory = Start; - *NumberOfPages = PagesToFree; + *Memory = Start; + *NumberOfPages = PagesToFree; } - /** Adjust the pool head position to make sure the Guard page is adjavent to pool tail or pool head. @@ -921,12 +932,12 @@ AdjustMemoryF ( **/ VOID * AdjustPoolHeadA ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages, - IN UINTN Size + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages, + IN UINTN Size ) { - if (Memory == 0 || (PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) { + if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) { // // Pool head is put near the head Guard // @@ -949,10 +960,10 @@ AdjustPoolHeadA ( **/ VOID * AdjustPoolHeadF ( - IN EFI_PHYSICAL_ADDRESS Memory + IN EFI_PHYSICAL_ADDRESS Memory ) { - if (Memory == 0 || (PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) { + if ((Memory == 0) || ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0)) { // // Pool head is put near the head Guard // @@ -977,10 +988,10 @@ AdjustPoolHeadF ( **/ UINTN InternalAllocMaxAddressWithGuard ( - IN OUT LIST_ENTRY *FreePageList, - IN UINTN NumberOfPages, - IN UINTN MaxAddress, - IN EFI_MEMORY_TYPE MemoryType + IN OUT LIST_ENTRY *FreePageList, + IN UINTN NumberOfPages, + IN UINTN MaxAddress, + IN EFI_MEMORY_TYPE MemoryType ) { @@ -992,16 +1003,17 @@ InternalAllocMaxAddressWithGuard ( UINTN Address; for (Node = FreePageList->BackLink; Node != FreePageList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); - if (Pages->NumberOfPages >= NumberOfPages && - (UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress) { - + if ((Pages->NumberOfPages >= NumberOfPages) && + ((UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress)) + { // // We may need 1 or 2 more pages for Guard. Check it out. // PagesToAlloc = NumberOfPages; - TailGuard = (UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages); + TailGuard = (UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages); if (!IsGuardPage (TailGuard)) { // // Add one if no Guard at the end of current free memory block. @@ -1027,12 +1039,13 @@ InternalAllocMaxAddressWithGuard ( } Address = InternalAllocPagesOnOneNode (Pages, PagesToAlloc, MaxAddress); - ConvertSmmMemoryMapEntry(MemoryType, Address, PagesToAlloc, FALSE); - CoreFreeMemoryMapStack(); + ConvertSmmMemoryMapEntry (MemoryType, Address, PagesToAlloc, FALSE); + CoreFreeMemoryMapStack (); if (HeadGuard == 0) { // Don't pass the Guard page to user. Address += EFI_PAGE_SIZE; } + SetGuardForMemory (Address, NumberOfPages); return Address; } @@ -1059,15 +1072,15 @@ SmmInternalFreePagesExWithGuard ( IN BOOLEAN AddRegion ) { - EFI_PHYSICAL_ADDRESS MemoryToFree; - UINTN PagesToFree; + EFI_PHYSICAL_ADDRESS MemoryToFree; + UINTN PagesToFree; if (((Memory & EFI_PAGE_MASK) != 0) || (Memory == 0) || (NumberOfPages == 0)) { return EFI_INVALID_PARAMETER; } - MemoryToFree = Memory; - PagesToFree = NumberOfPages; + MemoryToFree = Memory; + PagesToFree = NumberOfPages; AdjustMemoryF (&MemoryToFree, &PagesToFree); UnsetGuardForMemory (Memory, NumberOfPages); @@ -1086,30 +1099,31 @@ SetAllGuardPages ( VOID ) { - UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 TableEntry; - UINT64 Address; - UINT64 GuardPage; - INTN Level; - UINTN Index; - BOOLEAN OnGuarding; - - if (mGuardedMemoryMap == 0 || - mMapLevel == 0 || - mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) { + UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 TableEntry; + UINT64 Address; + UINT64 GuardPage; + INTN Level; + UINTN Index; + BOOLEAN OnGuarding; + + if ((mGuardedMemoryMap == 0) || + (mMapLevel == 0) || + (mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH)) + { return; } CopyMem (Entries, mLevelMask, sizeof (Entries)); CopyMem (Shifts, mLevelShift, sizeof (Shifts)); - SetMem (Tables, sizeof(Tables), 0); - SetMem (Addresses, sizeof(Addresses), 0); - SetMem (Indices, sizeof(Indices), 0); + SetMem (Tables, sizeof (Tables), 0); + SetMem (Addresses, sizeof (Addresses), 0); + SetMem (Indices, sizeof (Indices), 0); Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Tables[Level] = mGuardedMemoryMap; @@ -1118,32 +1132,26 @@ SetAllGuardPages ( DEBUG_CODE ( DumpGuardedMemoryBitmap (); - ); + ); while (TRUE) { if (Indices[Level] > Entries[Level]) { Tables[Level] = 0; Level -= 1; } else { - - TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; - Address = Addresses[Level]; + TableEntry = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]]; + Address = Addresses[Level]; if (TableEntry == 0) { - OnGuarding = FALSE; - } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { - - Level += 1; - Tables[Level] = TableEntry; - Addresses[Level] = Address; - Indices[Level] = 0; + Level += 1; + Tables[Level] = TableEntry; + Addresses[Level] = Address; + Indices[Level] = 0; continue; - } else { - Index = 0; while (Index < GUARDED_HEAP_MAP_ENTRY_BITS) { if ((TableEntry & 1) == 1) { @@ -1152,6 +1160,7 @@ SetAllGuardPages ( } else { GuardPage = Address - EFI_PAGE_SIZE; } + OnGuarding = TRUE; } else { if (OnGuarding) { @@ -1159,6 +1168,7 @@ SetAllGuardPages ( } else { GuardPage = 0; } + OnGuarding = FALSE; } @@ -1181,10 +1191,9 @@ SetAllGuardPages ( break; } - Indices[Level] += 1; - Address = (Level == 0) ? 0 : Addresses[Level - 1]; - Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]); - + Indices[Level] += 1; + Address = (Level == 0) ? 0 : Addresses[Level - 1]; + Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]); } } @@ -1204,7 +1213,7 @@ SmmEntryPointMemoryManagementHook ( NULL, (VOID **)&mSmmMemoryAttribute ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { SetAllGuardPages (); } } @@ -1220,11 +1229,11 @@ SmmEntryPointMemoryManagementHook ( **/ VOID Uint64ToBinString ( - IN UINT64 Value, - OUT CHAR8 *BinString + IN UINT64 Value, + OUT CHAR8 *BinString ) { - UINTN Index; + UINTN Index; if (BinString == NULL) { return; @@ -1232,8 +1241,9 @@ Uint64ToBinString ( for (Index = 64; Index > 0; --Index) { BinString[Index - 1] = '0' + (Value & 1); - Value = RShiftU64 (Value, 1); + Value = RShiftU64 (Value, 1); } + BinString[64] = '\0'; } @@ -1246,40 +1256,44 @@ DumpGuardedMemoryBitmap ( VOID ) { - UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; - UINT64 TableEntry; - UINT64 Address; - INTN Level; - UINTN RepeatZero; - CHAR8 String[GUARDED_HEAP_MAP_ENTRY_BITS + 1]; - CHAR8 *Ruler1; - CHAR8 *Ruler2; - - if (mGuardedMemoryMap == 0 || - mMapLevel == 0 || - mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) { + UINTN Entries[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINTN Indices[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Tables[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH]; + UINT64 TableEntry; + UINT64 Address; + INTN Level; + UINTN RepeatZero; + CHAR8 String[GUARDED_HEAP_MAP_ENTRY_BITS + 1]; + CHAR8 *Ruler1; + CHAR8 *Ruler2; + + if ((mGuardedMemoryMap == 0) || + (mMapLevel == 0) || + (mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH)) + { return; } Ruler1 = " 3 2 1 0"; Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210"; - DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "=============================" - " Guarded Memory Bitmap " - "==============================\r\n")); + DEBUG (( + HEAP_GUARD_DEBUG_LEVEL, + "=============================" + " Guarded Memory Bitmap " + "==============================\r\n" + )); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, " %a\r\n", Ruler1)); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, " %a\r\n", Ruler2)); CopyMem (Entries, mLevelMask, sizeof (Entries)); CopyMem (Shifts, mLevelShift, sizeof (Shifts)); - SetMem (Indices, sizeof(Indices), 0); - SetMem (Tables, sizeof(Tables), 0); - SetMem (Addresses, sizeof(Addresses), 0); + SetMem (Indices, sizeof (Indices), 0); + SetMem (Tables, sizeof (Tables), 0); + SetMem (Addresses, sizeof (Addresses), 0); Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel; Tables[Level] = mGuardedMemoryMap; @@ -1288,7 +1302,6 @@ DumpGuardedMemoryBitmap ( while (TRUE) { if (Indices[Level] > Entries[Level]) { - Tables[Level] = 0; Level -= 1; RepeatZero = 0; @@ -1298,40 +1311,33 @@ DumpGuardedMemoryBitmap ( "=========================================" "=========================================\r\n" )); - } else { - - TableEntry = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]]; - Address = Addresses[Level]; + TableEntry = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]]; + Address = Addresses[Level]; if (TableEntry == 0) { - if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { if (RepeatZero == 0) { - Uint64ToBinString(TableEntry, String); + Uint64ToBinString (TableEntry, String); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String)); } else if (RepeatZero == 1) { DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "... : ...\r\n")); } + RepeatZero += 1; } - } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) { - - Level += 1; - Tables[Level] = TableEntry; - Addresses[Level] = Address; - Indices[Level] = 0; - RepeatZero = 0; + Level += 1; + Tables[Level] = TableEntry; + Addresses[Level] = Address; + Indices[Level] = 0; + RepeatZero = 0; continue; - } else { - RepeatZero = 0; - Uint64ToBinString(TableEntry, String); + Uint64ToBinString (TableEntry, String); DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String)); - } } @@ -1339,10 +1345,9 @@ DumpGuardedMemoryBitmap ( break; } - Indices[Level] += 1; - Address = (Level == 0) ? 0 : Addresses[Level - 1]; - Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]); - + Indices[Level] += 1; + Address = (Level == 0) ? 0 : Addresses[Level - 1]; + Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]); } } @@ -1357,8 +1362,8 @@ DumpGuardedMemoryBitmap ( **/ BOOLEAN VerifyMemoryGuard ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN NumberOfPages ) { EFI_STATUS Status; @@ -1370,35 +1375,42 @@ VerifyMemoryGuard ( } Attribute = 0; - Address = BaseAddress - EFI_PAGE_SIZE; - Status = mSmmMemoryAttribute->GetMemoryAttributes ( - mSmmMemoryAttribute, - Address, - EFI_PAGE_SIZE, - &Attribute - ); - if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) { - DEBUG ((DEBUG_ERROR, "Head Guard is not set at: %016lx (%016lX)!!!\r\n", - Address, Attribute)); + Address = BaseAddress - EFI_PAGE_SIZE; + Status = mSmmMemoryAttribute->GetMemoryAttributes ( + mSmmMemoryAttribute, + Address, + EFI_PAGE_SIZE, + &Attribute + ); + if (EFI_ERROR (Status) || ((Attribute & EFI_MEMORY_RP) == 0)) { + DEBUG (( + DEBUG_ERROR, + "Head Guard is not set at: %016lx (%016lX)!!!\r\n", + Address, + Attribute + )); DumpGuardedMemoryBitmap (); return FALSE; } Attribute = 0; - Address = BaseAddress + EFI_PAGES_TO_SIZE (NumberOfPages); - Status = mSmmMemoryAttribute->GetMemoryAttributes ( - mSmmMemoryAttribute, - Address, - EFI_PAGE_SIZE, - &Attribute - ); - if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) { - DEBUG ((DEBUG_ERROR, "Tail Guard is not set at: %016lx (%016lX)!!!\r\n", - Address, Attribute)); + Address = BaseAddress + EFI_PAGES_TO_SIZE (NumberOfPages); + Status = mSmmMemoryAttribute->GetMemoryAttributes ( + mSmmMemoryAttribute, + Address, + EFI_PAGE_SIZE, + &Attribute + ); + if (EFI_ERROR (Status) || ((Attribute & EFI_MEMORY_RP) == 0)) { + DEBUG (( + DEBUG_ERROR, + "Tail Guard is not set at: %016lx (%016lX)!!!\r\n", + Address, + Attribute + )); DumpGuardedMemoryBitmap (); return FALSE; } return TRUE; } - diff --git a/MdeModulePkg/Core/PiSmmCore/HeapGuard.h b/MdeModulePkg/Core/PiSmmCore/HeapGuard.h index 1b5c0f2a4f..0a447ce2e8 100644 --- a/MdeModulePkg/Core/PiSmmCore/HeapGuard.h +++ b/MdeModulePkg/Core/PiSmmCore/HeapGuard.h @@ -53,15 +53,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9 // bits in address. (512 = 1 << 9) // -#define BYTE_LENGTH_SHIFT 3 // (8 = 1 << 3) +#define BYTE_LENGTH_SHIFT 3 // (8 = 1 << 3) #define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT \ (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT) -#define GUARDED_HEAP_MAP_TABLE_DEPTH 5 +#define GUARDED_HEAP_MAP_TABLE_DEPTH 5 // Use UINT64_index + bit_index_of_UINT64 to locate the bit in may -#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT 6 // (64 = 1 << 6) +#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT 6 // (64 = 1 << 6) #define GUARDED_HEAP_MAP_ENTRY_BITS \ (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) @@ -154,8 +154,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Memory type to guard (matching the related PCD definition) // -#define GUARD_HEAP_TYPE_PAGE BIT2 -#define GUARD_HEAP_TYPE_POOL BIT3 +#define GUARD_HEAP_TYPE_PAGE BIT2 +#define GUARD_HEAP_TYPE_POOL BIT3 // // Debug message level @@ -163,10 +163,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define HEAP_GUARD_DEBUG_LEVEL (DEBUG_POOL|DEBUG_PAGE) typedef struct { - UINT32 TailMark; - UINT32 HeadMark; - EFI_PHYSICAL_ADDRESS Address; - LIST_ENTRY Link; + UINT32 TailMark; + UINT32 HeadMark; + EFI_PHYSICAL_ADDRESS Address; + LIST_ENTRY Link; } HEAP_GUARD_NODE; /** @@ -179,8 +179,8 @@ typedef struct { **/ VOID SetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -193,8 +193,8 @@ SetGuardForMemory ( **/ VOID UnsetGuardForMemory ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -207,8 +207,8 @@ UnsetGuardForMemory ( **/ VOID AdjustMemoryA ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ); /** @@ -225,8 +225,8 @@ AdjustMemoryA ( **/ VOID AdjustMemoryF ( - IN OUT EFI_PHYSICAL_ADDRESS *Memory, - IN OUT UINTN *NumberOfPages + IN OUT EFI_PHYSICAL_ADDRESS *Memory, + IN OUT UINTN *NumberOfPages ); /** @@ -240,7 +240,7 @@ AdjustMemoryF ( **/ BOOLEAN IsPoolTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ); /** @@ -254,8 +254,8 @@ IsPoolTypeToGuard ( **/ BOOLEAN IsPageTypeToGuard ( - IN EFI_MEMORY_TYPE MemoryType, - IN EFI_ALLOCATE_TYPE AllocateType + IN EFI_MEMORY_TYPE MemoryType, + IN EFI_ALLOCATE_TYPE AllocateType ); /** @@ -269,7 +269,7 @@ IsPageTypeToGuard ( BOOLEAN EFIAPI IsMemoryGuarded ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ); /** @@ -283,7 +283,7 @@ IsMemoryGuarded ( BOOLEAN EFIAPI IsGuardPage ( - IN EFI_PHYSICAL_ADDRESS Address + IN EFI_PHYSICAL_ADDRESS Address ); /** @@ -308,9 +308,9 @@ DumpGuardedMemoryBitmap ( **/ VOID * AdjustPoolHeadA ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NoPages, - IN UINTN Size + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NoPages, + IN UINTN Size ); /** @@ -322,7 +322,7 @@ AdjustPoolHeadA ( **/ VOID * AdjustPoolHeadF ( - IN EFI_PHYSICAL_ADDRESS Memory + IN EFI_PHYSICAL_ADDRESS Memory ); /** @@ -337,10 +337,10 @@ AdjustPoolHeadF ( **/ UINTN InternalAllocMaxAddressWithGuard ( - IN OUT LIST_ENTRY *FreePageList, - IN UINTN NumberOfPages, - IN UINTN MaxAddress, - IN EFI_MEMORY_TYPE MemoryType + IN OUT LIST_ENTRY *FreePageList, + IN UINTN NumberOfPages, + IN UINTN MaxAddress, + IN EFI_MEMORY_TYPE MemoryType ); /** @@ -383,10 +383,10 @@ IsHeapGuardEnabled ( **/ BOOLEAN VerifyMemoryGuard ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINTN NumberOfPages ); -extern BOOLEAN mOnGuarding; +extern BOOLEAN mOnGuarding; #endif diff --git a/MdeModulePkg/Core/PiSmmCore/InstallConfigurationTable.c b/MdeModulePkg/Core/PiSmmCore/InstallConfigurationTable.c index 57f31fa98f..0bc51be12b 100644 --- a/MdeModulePkg/Core/PiSmmCore/InstallConfigurationTable.c +++ b/MdeModulePkg/Core/PiSmmCore/InstallConfigurationTable.c @@ -8,7 +8,7 @@ #include "PiSmmCore.h" -#define CONFIG_TABLE_SIZE_INCREASED 0x10 +#define CONFIG_TABLE_SIZE_INCREASED 0x10 UINTN mSmmSystemTableAllocateSize = 0; @@ -86,7 +86,6 @@ SmmInstallConfigurationTable ( &(ConfigurationTable[Index + 1]), (gSmmCoreSmst.NumberOfTableEntries - Index) * sizeof (EFI_CONFIGURATION_TABLE) ); - } else { // // No matching GUIDs were found, so this is an add operation. @@ -106,7 +105,7 @@ SmmInstallConfigurationTable ( // Allocate a table with one additional entry. // mSmmSystemTableAllocateSize += (CONFIG_TABLE_SIZE_INCREASED * sizeof (EFI_CONFIGURATION_TABLE)); - ConfigurationTable = AllocatePool (mSmmSystemTableAllocateSize); + ConfigurationTable = AllocatePool (mSmmSystemTableAllocateSize); if (ConfigurationTable == NULL) { // // If a new table could not be allocated, then return an error. diff --git a/MdeModulePkg/Core/PiSmmCore/Locate.c b/MdeModulePkg/Core/PiSmmCore/Locate.c index 8458199ec8..2d55362580 100644 --- a/MdeModulePkg/Core/PiSmmCore/Locate.c +++ b/MdeModulePkg/Core/PiSmmCore/Locate.c @@ -11,24 +11,24 @@ // // ProtocolRequest - Last LocateHandle request ID // -UINTN mEfiLocateHandleRequest = 0; +UINTN mEfiLocateHandleRequest = 0; // // Internal prototypes // typedef struct { - EFI_GUID *Protocol; - VOID *SearchKey; - LIST_ENTRY *Position; - PROTOCOL_ENTRY *ProtEntry; + EFI_GUID *Protocol; + VOID *SearchKey; + LIST_ENTRY *Position; + PROTOCOL_ENTRY *ProtEntry; } LOCATE_POSITION; typedef IHANDLE * -(* CORE_GET_NEXT) ( - IN OUT LOCATE_POSITION *Position, - OUT VOID **Interface +(*CORE_GET_NEXT) ( + IN OUT LOCATE_POSITION *Position, + OUT VOID **Interface ); /** @@ -48,7 +48,7 @@ SmmGetNextLocateAllHandles ( OUT VOID **Interface ) { - IHANDLE *Handle; + IHANDLE *Handle; // // Next handle @@ -58,11 +58,12 @@ SmmGetNextLocateAllHandles ( // // If not at the end of the list, get the handle // - Handle = NULL; - *Interface = NULL; + Handle = NULL; + *Interface = NULL; if (Position->Position != &gHandleList) { Handle = CR (Position->Position, IHANDLE, AllHandles, EFI_HANDLE_SIGNATURE); } + return Handle; } @@ -89,15 +90,15 @@ SmmGetNextLocateByRegisterNotify ( PROTOCOL_INTERFACE *Prot; LIST_ENTRY *Link; - Handle = NULL; - *Interface = NULL; + Handle = NULL; + *Interface = NULL; ProtNotify = Position->SearchKey; // // If this is the first request, get the next handle // if (ProtNotify != NULL) { - ASSERT(ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); + ASSERT (ProtNotify->Signature == PROTOCOL_NOTIFY_SIGNATURE); Position->SearchKey = NULL; // @@ -105,11 +106,12 @@ SmmGetNextLocateByRegisterNotify ( // Link = ProtNotify->Position->ForwardLink; if (Link != &ProtNotify->Protocol->Protocols) { - Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; *Interface = Prot->Interface; } } + return Handle; } @@ -134,13 +136,13 @@ SmmGetNextLocateByProtocol ( LIST_ENTRY *Link; PROTOCOL_INTERFACE *Prot; - Handle = NULL; - *Interface = NULL; - for (; ;) { + Handle = NULL; + *Interface = NULL; + for ( ; ;) { // // Next entry // - Link = Position->Position->ForwardLink; + Link = Position->Position->ForwardLink; Position->Position = Link; // @@ -154,8 +156,8 @@ SmmGetNextLocateByProtocol ( // // Get the handle // - Prot = CR(Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); - Handle = Prot->Handle; + Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE); + Handle = Prot->Handle; *Interface = Prot->Interface; // @@ -167,6 +169,7 @@ SmmGetNextLocateByProtocol ( break; } } + return Handle; } @@ -194,17 +197,17 @@ SmmLocateProtocol ( OUT VOID **Interface ) { - EFI_STATUS Status; - LOCATE_POSITION Position; - PROTOCOL_NOTIFY *ProtNotify; - IHANDLE *Handle; + EFI_STATUS Status; + LOCATE_POSITION Position; + PROTOCOL_NOTIFY *ProtNotify; + IHANDLE *Handle; if ((Interface == NULL) || (Protocol == NULL)) { return EFI_INVALID_PARAMETER; } *Interface = NULL; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; // // Set initial position @@ -223,6 +226,7 @@ SmmLocateProtocol ( if (Position.ProtEntry == NULL) { return EFI_NOT_FOUND; } + Position.Position = &Position.ProtEntry->Protocols; Handle = SmmGetNextLocateByProtocol (&Position, Interface); @@ -237,7 +241,7 @@ SmmLocateProtocol ( // If this is a search by register notify and a handle was // returned, update the register notification position // - ProtNotify = Registration; + ProtNotify = Registration; ProtNotify->Position = ProtNotify->Position->ForwardLink; } @@ -298,51 +302,54 @@ SmmLocateHandle ( Position.SearchKey = SearchKey; Position.Position = &gHandleList; - ResultSize = 0; - ResultBuffer = (IHANDLE **) Buffer; - Status = EFI_SUCCESS; + ResultSize = 0; + ResultBuffer = (IHANDLE **)Buffer; + Status = EFI_SUCCESS; // // Get the search function based on type // switch (SearchType) { - case AllHandles: - GetNext = SmmGetNextLocateAllHandles; - break; + case AllHandles: + GetNext = SmmGetNextLocateAllHandles; + break; - case ByRegisterNotify: - GetNext = SmmGetNextLocateByRegisterNotify; - // - // Must have SearchKey for locate ByRegisterNotify - // - if (SearchKey == NULL) { - Status = EFI_INVALID_PARAMETER; - } - break; + case ByRegisterNotify: + GetNext = SmmGetNextLocateByRegisterNotify; + // + // Must have SearchKey for locate ByRegisterNotify + // + if (SearchKey == NULL) { + Status = EFI_INVALID_PARAMETER; + } - case ByProtocol: - GetNext = SmmGetNextLocateByProtocol; - if (Protocol == NULL) { - Status = EFI_INVALID_PARAMETER; break; - } - // - // Look up the protocol entry and set the head pointer - // - Position.ProtEntry = SmmFindProtocolEntry (Protocol, FALSE); - if (Position.ProtEntry == NULL) { - Status = EFI_NOT_FOUND; + + case ByProtocol: + GetNext = SmmGetNextLocateByProtocol; + if (Protocol == NULL) { + Status = EFI_INVALID_PARAMETER; + break; + } + + // + // Look up the protocol entry and set the head pointer + // + Position.ProtEntry = SmmFindProtocolEntry (Protocol, FALSE); + if (Position.ProtEntry == NULL) { + Status = EFI_NOT_FOUND; + break; + } + + Position.Position = &Position.ProtEntry->Protocols; break; - } - Position.Position = &Position.ProtEntry->Protocols; - break; - default: - Status = EFI_INVALID_PARAMETER; - break; + default: + Status = EFI_INVALID_PARAMETER; + break; } - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -350,7 +357,7 @@ SmmLocateHandle ( // Enumerate out the matching handles // mEfiLocateHandleRequest += 1; - for (; ;) { + for ( ; ;) { // // Get the next handle. If no more handles, stop // @@ -363,10 +370,10 @@ SmmLocateHandle ( // Increase the resulting buffer size, and if this handle // fits return it // - ResultSize += sizeof(Handle); + ResultSize += sizeof (Handle); if (ResultSize <= *BufferSize) { - *ResultBuffer = Handle; - ResultBuffer += 1; + *ResultBuffer = Handle; + ResultBuffer += 1; } } @@ -387,13 +394,13 @@ SmmLocateHandle ( *BufferSize = ResultSize; - if (SearchType == ByRegisterNotify && !EFI_ERROR(Status)) { + if ((SearchType == ByRegisterNotify) && !EFI_ERROR (Status)) { ASSERT (SearchKey != NULL); // // If this is a search by register notify and a handle was // returned, update the register notification position // - ProtNotify = SearchKey; + ProtNotify = SearchKey; ProtNotify->Position = ProtNotify->Position->ForwardLink; } } @@ -444,26 +451,27 @@ SmmLocateHandleBuffer ( return EFI_INVALID_PARAMETER; } - BufferSize = 0; + BufferSize = 0; *NumberHandles = 0; - *Buffer = NULL; - Status = SmmLocateHandle ( - SearchType, - Protocol, - SearchKey, - &BufferSize, - *Buffer - ); + *Buffer = NULL; + Status = SmmLocateHandle ( + SearchType, + Protocol, + SearchKey, + &BufferSize, + *Buffer + ); // // LocateHandleBuffer() returns incorrect status code if SearchType is // invalid. // // Add code to correctly handle expected errors from SmmLocateHandle(). // - if (EFI_ERROR(Status) && Status != EFI_BUFFER_TOO_SMALL) { + if (EFI_ERROR (Status) && (Status != EFI_BUFFER_TOO_SMALL)) { if (Status != EFI_INVALID_PARAMETER) { Status = EFI_NOT_FOUND; } + return Status; } @@ -480,8 +488,8 @@ SmmLocateHandleBuffer ( *Buffer ); - *NumberHandles = BufferSize / sizeof(EFI_HANDLE); - if (EFI_ERROR(Status)) { + *NumberHandles = BufferSize / sizeof (EFI_HANDLE); + if (EFI_ERROR (Status)) { *NumberHandles = 0; } diff --git a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c index 3e8a80dd7d..394fdae507 100644 --- a/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c +++ b/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c @@ -25,33 +25,33 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \ ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size))) -#define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE SIGNATURE_32 ('I','P','R','C') +#define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE SIGNATURE_32 ('I','P','R','C') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_PHYSICAL_ADDRESS CodeSegmentBase; - UINT64 CodeSegmentSize; + UINT32 Signature; + LIST_ENTRY Link; + EFI_PHYSICAL_ADDRESS CodeSegmentBase; + UINT64 CodeSegmentSize; } IMAGE_PROPERTIES_RECORD_CODE_SECTION; -#define IMAGE_PROPERTIES_RECORD_SIGNATURE SIGNATURE_32 ('I','P','R','D') +#define IMAGE_PROPERTIES_RECORD_SIGNATURE SIGNATURE_32 ('I','P','R','D') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_PHYSICAL_ADDRESS ImageBase; - UINT64 ImageSize; - UINTN CodeSegmentCount; - LIST_ENTRY CodeSegmentList; + UINT32 Signature; + LIST_ENTRY Link; + EFI_PHYSICAL_ADDRESS ImageBase; + UINT64 ImageSize; + UINTN CodeSegmentCount; + LIST_ENTRY CodeSegmentList; } IMAGE_PROPERTIES_RECORD; -#define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('I','P','P','D') +#define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE SIGNATURE_32 ('I','P','P','D') typedef struct { - UINT32 Signature; - UINTN ImageRecordCount; - UINTN CodeSegmentCountMax; - LIST_ENTRY ImageRecordList; + UINT32 Signature; + UINTN ImageRecordCount; + UINTN CodeSegmentCountMax; + LIST_ENTRY ImageRecordList; } IMAGE_PROPERTIES_PRIVATE_DATA; IMAGE_PROPERTIES_PRIVATE_DATA mImagePropertiesPrivateData = { @@ -63,7 +63,7 @@ IMAGE_PROPERTIES_PRIVATE_DATA mImagePropertiesPrivateData = { #define EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA BIT0 -UINT64 mMemoryProtectionAttribute = EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA; +UINT64 mMemoryProtectionAttribute = EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA; // // Below functions are for MemoryMap @@ -82,7 +82,7 @@ UINT64 mMemoryProtectionAttribute = EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECT STATIC UINT64 EfiPagesToSize ( - IN UINT64 Pages + IN UINT64 Pages ) { return LShiftU64 (Pages, EFI_PAGE_SHIFT); @@ -102,13 +102,12 @@ EfiPagesToSize ( STATIC UINT64 EfiSizeToPages ( - IN UINT64 Size + IN UINT64 Size ) { return RShiftU64 (Size, EFI_PAGE_SHIFT) + ((((UINTN)Size) & EFI_PAGE_MASK) ? 1 : 0); } - /** Sort memory map entries based upon PhysicalStart, from low to high. @@ -125,30 +124,30 @@ SortMemoryMap ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - EFI_MEMORY_DESCRIPTOR TempMemoryMap; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_MEMORY_DESCRIPTOR TempMemoryMap; - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while (MemoryMapEntry < MemoryMapEnd) { while (NextMemoryMapEntry < MemoryMapEnd) { if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) { - CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); - CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); + CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof (EFI_MEMORY_DESCRIPTOR)); } NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize); } - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); - NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } - return ; + return; } /** @@ -170,25 +169,26 @@ MergeMemoryMap ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; - UINT64 MemoryBlockLength; - EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + UINT64 MemoryBlockLength; + EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; - MemoryMapEntry = MemoryMap; + MemoryMapEntry = MemoryMap; NewMemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + *MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { - CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (NewMemoryMapEntry, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR)); NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); do { - MemoryBlockLength = (UINT64) (EfiPagesToSize (MemoryMapEntry->NumberOfPages)); + MemoryBlockLength = (UINT64)(EfiPagesToSize (MemoryMapEntry->NumberOfPages)); if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && (MemoryMapEntry->Type == NextMemoryMapEntry->Type) && (MemoryMapEntry->Attribute == NextMemoryMapEntry->Attribute) && - ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) { + ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) + { MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; if (NewMemoryMapEntry != MemoryMapEntry) { NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; @@ -202,13 +202,13 @@ MergeMemoryMap ( } } while (TRUE); - MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NewMemoryMapEntry, DescriptorSize); } *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap; - return ; + return; } /** @@ -228,29 +228,30 @@ EnforceMemoryMapAttribute ( IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; - EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; + EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; + EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; MemoryMapEntry = MemoryMap; - MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) MemoryMap + MemoryMapSize); + MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { if (MemoryMapEntry->Attribute != 0) { // It is PE image, the attribute is already set. } else { switch (MemoryMapEntry->Type) { - case EfiRuntimeServicesCode: - MemoryMapEntry->Attribute = EFI_MEMORY_RO; - break; - case EfiRuntimeServicesData: - default: - MemoryMapEntry->Attribute |= EFI_MEMORY_XP; - break; + case EfiRuntimeServicesCode: + MemoryMapEntry->Attribute = EFI_MEMORY_RO; + break; + case EfiRuntimeServicesData: + default: + MemoryMapEntry->Attribute |= EFI_MEMORY_XP; + break; } } + MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize); } - return ; + return; } /** @@ -268,15 +269,16 @@ GetImageRecordByAddress ( IN UINT64 Length ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *ImageRecordList; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *ImageRecordList; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; for (ImageRecordLink = ImageRecordList->ForwardLink; ImageRecordLink != ImageRecordList; - ImageRecordLink = ImageRecordLink->ForwardLink) { + ImageRecordLink = ImageRecordLink->ForwardLink) + { ImageRecord = CR ( ImageRecordLink, IMAGE_PROPERTIES_RECORD, @@ -285,7 +287,8 @@ GetImageRecordByAddress ( ); if ((Buffer <= ImageRecord->ImageBase) && - (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize)) { + (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize)) + { return ImageRecord; } } @@ -309,43 +312,43 @@ GetImageRecordByAddress ( STATIC UINTN SetNewRecord ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord, - IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, - IN EFI_MEMORY_DESCRIPTOR *OldRecord, - IN UINTN DescriptorSize + IN IMAGE_PROPERTIES_RECORD *ImageRecord, + IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, + IN EFI_MEMORY_DESCRIPTOR *OldRecord, + IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR TempRecord; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; - UINTN NewRecordCount; - UINT64 PhysicalEnd; - UINT64 ImageEnd; - - CopyMem (&TempRecord, OldRecord, sizeof(EFI_MEMORY_DESCRIPTOR)); - PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize(TempRecord.NumberOfPages); + EFI_MEMORY_DESCRIPTOR TempRecord; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; + UINTN NewRecordCount; + UINT64 PhysicalEnd; + UINT64 ImageEnd; + + CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR)); + PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages); NewRecordCount = 0; // // Always create a new entry for non-PE image record // if (ImageRecord->ImageBase > TempRecord.PhysicalStart) { - NewRecord->Type = TempRecord.Type; + NewRecord->Type = TempRecord.Type; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; - NewRecord->NumberOfPages = EfiSizeToPages(ImageRecord->ImageBase - TempRecord.PhysicalStart); + NewRecord->NumberOfPages = EfiSizeToPages (ImageRecord->ImageBase - TempRecord.PhysicalStart); NewRecord->Attribute = TempRecord.Attribute; - NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); - NewRecordCount ++; + NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); + NewRecordCount++; TempRecord.PhysicalStart = ImageRecord->ImageBase; - TempRecord.NumberOfPages = EfiSizeToPages(PhysicalEnd - TempRecord.PhysicalStart); + TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart); } ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( @@ -360,31 +363,31 @@ SetNewRecord ( // // DATA // - NewRecord->Type = EfiRuntimeServicesData; + NewRecord->Type = EfiRuntimeServicesData; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; - NewRecord->NumberOfPages = EfiSizeToPages(ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart); + NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart); NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP; if (NewRecord->NumberOfPages != 0) { NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); - NewRecordCount ++; + NewRecordCount++; } // // CODE // - NewRecord->Type = EfiRuntimeServicesCode; + NewRecord->Type = EfiRuntimeServicesCode; NewRecord->PhysicalStart = ImageRecordCodeSection->CodeSegmentBase; NewRecord->VirtualStart = 0; - NewRecord->NumberOfPages = EfiSizeToPages(ImageRecordCodeSection->CodeSegmentSize); + NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize); NewRecord->Attribute = (TempRecord.Attribute & (~EFI_MEMORY_XP)) | EFI_MEMORY_RO; if (NewRecord->NumberOfPages != 0) { NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize); - NewRecordCount ++; + NewRecordCount++; } - TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages(ImageRecordCodeSection->CodeSegmentSize)); - TempRecord.NumberOfPages = EfiSizeToPages(PhysicalEnd - TempRecord.PhysicalStart); + TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize)); + TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart); if (TempRecord.NumberOfPages == 0) { break; } @@ -397,12 +400,12 @@ SetNewRecord ( // Final DATA // if (TempRecord.PhysicalStart < ImageEnd) { - NewRecord->Type = EfiRuntimeServicesData; + NewRecord->Type = EfiRuntimeServicesData; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; NewRecord->NumberOfPages = EfiSizeToPages (ImageEnd - TempRecord.PhysicalStart); NewRecord->Attribute = TempRecord.Attribute | EFI_MEMORY_XP; - NewRecordCount ++; + NewRecordCount++; } return NewRecordCount; @@ -420,25 +423,26 @@ SetNewRecord ( STATIC UINTN GetMaxSplitRecordCount ( - IN EFI_MEMORY_DESCRIPTOR *OldRecord + IN EFI_MEMORY_DESCRIPTOR *OldRecord ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - UINTN SplitRecordCount; - UINT64 PhysicalStart; - UINT64 PhysicalEnd; + IMAGE_PROPERTIES_RECORD *ImageRecord; + UINTN SplitRecordCount; + UINT64 PhysicalStart; + UINT64 PhysicalEnd; SplitRecordCount = 0; - PhysicalStart = OldRecord->PhysicalStart; - PhysicalEnd = OldRecord->PhysicalStart + EfiPagesToSize(OldRecord->NumberOfPages); + PhysicalStart = OldRecord->PhysicalStart; + PhysicalEnd = OldRecord->PhysicalStart + EfiPagesToSize (OldRecord->NumberOfPages); do { ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart); if (ImageRecord == NULL) { break; } + SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 2); - PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; + PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd)); return SplitRecordCount; @@ -462,19 +466,19 @@ GetMaxSplitRecordCount ( STATIC UINTN SplitRecord ( - IN EFI_MEMORY_DESCRIPTOR *OldRecord, - IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, - IN UINTN MaxSplitRecordCount, - IN UINTN DescriptorSize + IN EFI_MEMORY_DESCRIPTOR *OldRecord, + IN OUT EFI_MEMORY_DESCRIPTOR *NewRecord, + IN UINTN MaxSplitRecordCount, + IN UINTN DescriptorSize ) { - EFI_MEMORY_DESCRIPTOR TempRecord; - IMAGE_PROPERTIES_RECORD *ImageRecord; - IMAGE_PROPERTIES_RECORD *NewImageRecord; - UINT64 PhysicalStart; - UINT64 PhysicalEnd; - UINTN NewRecordCount; - UINTN TotalNewRecordCount; + EFI_MEMORY_DESCRIPTOR TempRecord; + IMAGE_PROPERTIES_RECORD *ImageRecord; + IMAGE_PROPERTIES_RECORD *NewImageRecord; + UINT64 PhysicalStart; + UINT64 PhysicalEnd; + UINTN NewRecordCount; + UINTN TotalNewRecordCount; if (MaxSplitRecordCount == 0) { CopyMem (NewRecord, OldRecord, DescriptorSize); @@ -486,9 +490,9 @@ SplitRecord ( // // Override previous record // - CopyMem (&TempRecord, OldRecord, sizeof(EFI_MEMORY_DESCRIPTOR)); + CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR)); PhysicalStart = TempRecord.PhysicalStart; - PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize(TempRecord.NumberOfPages); + PhysicalEnd = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages); ImageRecord = NULL; do { @@ -501,28 +505,30 @@ SplitRecord ( // // Always create a new entry for non-PE image record // - NewRecord->Type = TempRecord.Type; + NewRecord->Type = TempRecord.Type; NewRecord->PhysicalStart = TempRecord.PhysicalStart; NewRecord->VirtualStart = 0; NewRecord->NumberOfPages = TempRecord.NumberOfPages; NewRecord->Attribute = TempRecord.Attribute; - TotalNewRecordCount ++; + TotalNewRecordCount++; } + break; } + ImageRecord = NewImageRecord; // // Set new record // - NewRecordCount = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize); + NewRecordCount = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize); TotalNewRecordCount += NewRecordCount; - NewRecord = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize); + NewRecord = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize); // // Update PhysicalStart, in order to exclude the image buffer already splitted. // - PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; + PhysicalStart = ImageRecord->ImageBase + ImageRecord->ImageSize; TempRecord.PhysicalStart = PhysicalStart; TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - PhysicalStart); } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd)); @@ -590,12 +596,12 @@ SplitTable ( IN UINTN DescriptorSize ) { - INTN IndexOld; - INTN IndexNew; - UINTN MaxSplitRecordCount; - UINTN RealSplitRecordCount; - UINTN TotalSplitRecordCount; - UINTN AdditionalRecordCount; + INTN IndexOld; + INTN IndexNew; + UINTN MaxSplitRecordCount; + UINTN RealSplitRecordCount; + UINTN TotalSplitRecordCount; + UINTN AdditionalRecordCount; AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 2) * mImagePropertiesPrivateData.ImageRecordCount; @@ -608,12 +614,12 @@ SplitTable ( // Let new record point to end of full MemoryMap buffer. // IndexNew = ((*MemoryMapSize) / DescriptorSize) - 1 + AdditionalRecordCount; - for (; IndexOld >= 0; IndexOld--) { + for ( ; IndexOld >= 0; IndexOld--) { MaxSplitRecordCount = GetMaxSplitRecordCount ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize)); // // Split this MemoryMap record // - IndexNew -= MaxSplitRecordCount; + IndexNew -= MaxSplitRecordCount; RealSplitRecordCount = SplitRecord ( (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize), (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexNew * DescriptorSize), @@ -630,10 +636,12 @@ SplitTable ( (RealSplitRecordCount + 1) * DescriptorSize ); } - IndexNew = IndexNew + MaxSplitRecordCount - RealSplitRecordCount; + + IndexNew = IndexNew + MaxSplitRecordCount - RealSplitRecordCount; TotalSplitRecordCount += RealSplitRecordCount; - IndexNew --; + IndexNew--; } + // // Move all records to the beginning. // @@ -660,7 +668,7 @@ SplitTable ( // MergeMemoryMap (MemoryMap, MemoryMapSize, DescriptorSize); - return ; + return; } /** @@ -724,7 +732,7 @@ SmmCoreGetMemoryMapMemoryAttributesTable ( AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 2) * mImagePropertiesPrivateData.ImageRecordCount; OldMemoryMapSize = *MemoryMapSize; - Status = SmmCoreGetMemoryMap (MemoryMapSize, MemoryMap, MapKey, DescriptorSize, DescriptorVersion); + Status = SmmCoreGetMemoryMap (MemoryMapSize, MemoryMap, MapKey, DescriptorSize, DescriptorVersion); if (Status == EFI_BUFFER_TOO_SMALL) { *MemoryMapSize = *MemoryMapSize + (*DescriptorSize) * AdditionalRecordCount; } else if (Status == EFI_SUCCESS) { @@ -738,7 +746,7 @@ SmmCoreGetMemoryMapMemoryAttributesTable ( // // Split PE code/data // - ASSERT(MemoryMap != NULL); + ASSERT (MemoryMap != NULL); SplitTable (MemoryMapSize, MemoryMap, *DescriptorSize); } } @@ -762,7 +770,8 @@ SetMemoryAttributesTableSectionAlignment ( ) { if (((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) && - ((mMemoryProtectionAttribute & EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA) != 0)) { + ((mMemoryProtectionAttribute & EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA) != 0)) + { DEBUG ((DEBUG_VERBOSE, "SMM SetMemoryAttributesTableSectionAlignment - Clear\n")); mMemoryProtectionAttribute &= ~((UINT64)EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA); } @@ -777,11 +786,11 @@ SetMemoryAttributesTableSectionAlignment ( STATIC VOID SwapImageRecordCodeSection ( - IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *FirstImageRecordCodeSection, - IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *SecondImageRecordCodeSection + IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *FirstImageRecordCodeSection, + IN IMAGE_PROPERTIES_RECORD_CODE_SECTION *SecondImageRecordCodeSection ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION TempImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION TempImageRecordCodeSection; TempImageRecordCodeSection.CodeSegmentBase = FirstImageRecordCodeSection->CodeSegmentBase; TempImageRecordCodeSection.CodeSegmentSize = FirstImageRecordCodeSection->CodeSegmentSize; @@ -801,21 +810,21 @@ SwapImageRecordCodeSection ( STATIC VOID SortImageRecordCodeSection ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *NextImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *NextImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *NextImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *NextImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; - ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; + ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( ImageRecordCodeSectionLink, @@ -833,10 +842,11 @@ SortImageRecordCodeSection ( if (ImageRecordCodeSection->CodeSegmentBase > NextImageRecordCodeSection->CodeSegmentBase) { SwapImageRecordCodeSection (ImageRecordCodeSection, NextImageRecordCodeSection); } + NextImageRecordCodeSectionLink = NextImageRecordCodeSectionLink->ForwardLink; } - ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink; } } @@ -852,22 +862,22 @@ SortImageRecordCodeSection ( STATIC BOOLEAN IsImageRecordCodeSectionValid ( - IN IMAGE_PROPERTIES_RECORD *ImageRecord + IN IMAGE_PROPERTIES_RECORD *ImageRecord ) { - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *LastImageRecordCodeSection; - LIST_ENTRY *ImageRecordCodeSectionLink; - LIST_ENTRY *ImageRecordCodeSectionEndLink; - LIST_ENTRY *ImageRecordCodeSectionList; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *LastImageRecordCodeSection; + LIST_ENTRY *ImageRecordCodeSectionLink; + LIST_ENTRY *ImageRecordCodeSectionEndLink; + LIST_ENTRY *ImageRecordCodeSectionList; DEBUG ((DEBUG_VERBOSE, "SMM ImageCode SegmentCount - 0x%x\n", ImageRecord->CodeSegmentCount)); ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList; - ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; + ImageRecordCodeSectionLink = ImageRecordCodeSectionList->ForwardLink; ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList; - LastImageRecordCodeSection = NULL; + LastImageRecordCodeSection = NULL; while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) { ImageRecordCodeSection = CR ( ImageRecordCodeSectionLink, @@ -878,15 +888,19 @@ IsImageRecordCodeSectionValid ( if (ImageRecordCodeSection->CodeSegmentSize == 0) { return FALSE; } + if (ImageRecordCodeSection->CodeSegmentBase < ImageRecord->ImageBase) { return FALSE; } + if (ImageRecordCodeSection->CodeSegmentBase >= MAX_ADDRESS - ImageRecordCodeSection->CodeSegmentSize) { return FALSE; } + if ((ImageRecordCodeSection->CodeSegmentBase + ImageRecordCodeSection->CodeSegmentSize) > (ImageRecord->ImageBase + ImageRecord->ImageSize)) { return FALSE; } + if (LastImageRecordCodeSection != NULL) { if ((LastImageRecordCodeSection->CodeSegmentBase + LastImageRecordCodeSection->CodeSegmentSize) > ImageRecordCodeSection->CodeSegmentBase) { return FALSE; @@ -909,22 +923,22 @@ IsImageRecordCodeSectionValid ( STATIC VOID SwapImageRecord ( - IN IMAGE_PROPERTIES_RECORD *FirstImageRecord, - IN IMAGE_PROPERTIES_RECORD *SecondImageRecord + IN IMAGE_PROPERTIES_RECORD *FirstImageRecord, + IN IMAGE_PROPERTIES_RECORD *SecondImageRecord ) { - IMAGE_PROPERTIES_RECORD TempImageRecord; + IMAGE_PROPERTIES_RECORD TempImageRecord; - TempImageRecord.ImageBase = FirstImageRecord->ImageBase; - TempImageRecord.ImageSize = FirstImageRecord->ImageSize; + TempImageRecord.ImageBase = FirstImageRecord->ImageBase; + TempImageRecord.ImageSize = FirstImageRecord->ImageSize; TempImageRecord.CodeSegmentCount = FirstImageRecord->CodeSegmentCount; - FirstImageRecord->ImageBase = SecondImageRecord->ImageBase; - FirstImageRecord->ImageSize = SecondImageRecord->ImageSize; + FirstImageRecord->ImageBase = SecondImageRecord->ImageBase; + FirstImageRecord->ImageSize = SecondImageRecord->ImageSize; FirstImageRecord->CodeSegmentCount = SecondImageRecord->CodeSegmentCount; - SecondImageRecord->ImageBase = TempImageRecord.ImageBase; - SecondImageRecord->ImageSize = TempImageRecord.ImageSize; + SecondImageRecord->ImageBase = TempImageRecord.ImageBase; + SecondImageRecord->ImageSize = TempImageRecord.ImageSize; SecondImageRecord->CodeSegmentCount = TempImageRecord.CodeSegmentCount; SwapListEntries (&FirstImageRecord->CodeSegmentList, &SecondImageRecord->CodeSegmentList); @@ -939,18 +953,18 @@ SortImageRecord ( VOID ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - IMAGE_PROPERTIES_RECORD *NextImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *NextImageRecordLink; - LIST_ENTRY *ImageRecordEndLink; - LIST_ENTRY *ImageRecordList; + IMAGE_PROPERTIES_RECORD *ImageRecord; + IMAGE_PROPERTIES_RECORD *NextImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *NextImageRecordLink; + LIST_ENTRY *ImageRecordEndLink; + LIST_ENTRY *ImageRecordList; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; - ImageRecordLink = ImageRecordList->ForwardLink; + ImageRecordLink = ImageRecordList->ForwardLink; NextImageRecordLink = ImageRecordLink->ForwardLink; - ImageRecordEndLink = ImageRecordList; + ImageRecordEndLink = ImageRecordList; while (ImageRecordLink != ImageRecordEndLink) { ImageRecord = CR ( ImageRecordLink, @@ -968,10 +982,11 @@ SortImageRecord ( if (ImageRecord->ImageBase > NextImageRecord->ImageBase) { SwapImageRecord (ImageRecord, NextImageRecord); } + NextImageRecordLink = NextImageRecordLink->ForwardLink; } - ImageRecordLink = ImageRecordLink->ForwardLink; + ImageRecordLink = ImageRecordLink->ForwardLink; NextImageRecordLink = ImageRecordLink->ForwardLink; } } @@ -985,16 +1000,17 @@ DumpImageRecord ( VOID ) { - IMAGE_PROPERTIES_RECORD *ImageRecord; - LIST_ENTRY *ImageRecordLink; - LIST_ENTRY *ImageRecordList; - UINTN Index; + IMAGE_PROPERTIES_RECORD *ImageRecord; + LIST_ENTRY *ImageRecordLink; + LIST_ENTRY *ImageRecordList; + UINTN Index; ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList; - for (ImageRecordLink = ImageRecordList->ForwardLink, Index= 0; + for (ImageRecordLink = ImageRecordList->ForwardLink, Index = 0; ImageRecordLink != ImageRecordList; - ImageRecordLink = ImageRecordLink->ForwardLink, Index++) { + ImageRecordLink = ImageRecordLink->ForwardLink, Index++) + { ImageRecord = CR ( ImageRecordLink, IMAGE_PROPERTIES_RECORD, @@ -1015,25 +1031,26 @@ SmmInsertImageRecord ( IN EFI_SMM_DRIVER_ENTRY *DriverEntry ) { - VOID *ImageAddress; - EFI_IMAGE_DOS_HEADER *DosHdr; - UINT32 PeCoffHeaderOffset; - UINT32 SectionAlignment; - EFI_IMAGE_SECTION_HEADER *Section; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; - UINT8 *Name; - UINTN Index; - IMAGE_PROPERTIES_RECORD *ImageRecord; - CHAR8 *PdbPointer; - IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; + VOID *ImageAddress; + EFI_IMAGE_DOS_HEADER *DosHdr; + UINT32 PeCoffHeaderOffset; + UINT32 SectionAlignment; + EFI_IMAGE_SECTION_HEADER *Section; + EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; + UINT8 *Name; + UINTN Index; + IMAGE_PROPERTIES_RECORD *ImageRecord; + CHAR8 *PdbPointer; + IMAGE_PROPERTIES_RECORD_CODE_SECTION *ImageRecordCodeSection; DEBUG ((DEBUG_VERBOSE, "SMM InsertImageRecord - 0x%x\n", DriverEntry)); DEBUG ((DEBUG_VERBOSE, "SMM InsertImageRecord - 0x%016lx - 0x%08x\n", DriverEntry->ImageBuffer, DriverEntry->NumberOfPage)); - ImageRecord = AllocatePool (sizeof(*ImageRecord)); + ImageRecord = AllocatePool (sizeof (*ImageRecord)); if (ImageRecord == NULL) { - return ; + return; } + ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE; DEBUG ((DEBUG_VERBOSE, "SMM ImageRecordCount - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount)); @@ -1042,11 +1059,11 @@ SmmInsertImageRecord ( // Step 1: record whole region // ImageRecord->ImageBase = DriverEntry->ImageBuffer; - ImageRecord->ImageSize = EfiPagesToSize(DriverEntry->NumberOfPage); + ImageRecord->ImageSize = EfiPagesToSize (DriverEntry->NumberOfPage); ImageAddress = (VOID *)(UINTN)DriverEntry->ImageBuffer; - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_VERBOSE, "SMM Image - %a\n", PdbPointer)); } @@ -1054,13 +1071,13 @@ SmmInsertImageRecord ( // // Check PE/COFF image // - DosHdr = (EFI_IMAGE_DOS_HEADER *) (UINTN) ImageAddress; + DosHdr = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress; PeCoffHeaderOffset = 0; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { PeCoffHeaderOffset = DosHdr->e_lfanew; } - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *) (UINTN) ImageAddress + PeCoffHeaderOffset); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset); if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) { DEBUG ((DEBUG_VERBOSE, "SMM Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature)); goto Finish; @@ -1070,29 +1087,34 @@ SmmInsertImageRecord ( // Get SectionAlignment // if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { - SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment; } else { - SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; + SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment; } SetMemoryAttributesTableSectionAlignment (SectionAlignment); if ((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) { - DEBUG ((DEBUG_WARN, "SMM !!!!!!!! InsertImageRecord - Section Alignment(0x%x) is not %dK !!!!!!!!\n", - SectionAlignment, RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10)); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + DEBUG (( + DEBUG_WARN, + "SMM !!!!!!!! InsertImageRecord - Section Alignment(0x%x) is not %dK !!!!!!!!\n", + SectionAlignment, + RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10 + )); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_WARN, "SMM !!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } - Section = (EFI_IMAGE_SECTION_HEADER *) ( - (UINT8 *) (UINTN) ImageAddress + - PeCoffHeaderOffset + - sizeof(UINT32) + - sizeof(EFI_IMAGE_FILE_HEADER) + - Hdr.Pe32->FileHeader.SizeOfOptionalHeader - ); + Section = (EFI_IMAGE_SECTION_HEADER *)( + (UINT8 *)(UINTN)ImageAddress + + PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + Hdr.Pe32->FileHeader.SizeOfOptionalHeader + ); ImageRecord->CodeSegmentCount = 0; InitializeListHead (&ImageRecord->CodeSegmentList); for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) { @@ -1124,10 +1146,11 @@ SmmInsertImageRecord ( // // Step 2: record code section // - ImageRecordCodeSection = AllocatePool (sizeof(*ImageRecordCodeSection)); + ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection)); if (ImageRecordCodeSection == NULL) { - return ; + return; } + ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE; ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress; @@ -1143,10 +1166,11 @@ SmmInsertImageRecord ( if (ImageRecord->CodeSegmentCount == 0) { SetMemoryAttributesTableSectionAlignment (1); DEBUG ((DEBUG_ERROR, "SMM !!!!!!!! InsertImageRecord - CodeSegmentCount is 0 !!!!!!!!\n")); - PdbPointer = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageAddress); + PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress); if (PdbPointer != NULL) { DEBUG ((DEBUG_ERROR, "SMM !!!!!!!! Image - %a !!!!!!!!\n", PdbPointer)); } + goto Finish; } @@ -1172,10 +1196,9 @@ SmmInsertImageRecord ( SortImageRecord (); Finish: - return ; + return; } - /** Publish MemoryAttributesTable to SMM configuration table. **/ @@ -1184,27 +1207,27 @@ PublishMemoryAttributesTable ( VOID ) { - UINTN MemoryMapSize; - EFI_MEMORY_DESCRIPTOR *MemoryMap; - UINTN MapKey; - UINTN DescriptorSize; - UINT32 DescriptorVersion; - UINTN Index; - EFI_STATUS Status; - UINTN RuntimeEntryCount; - EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE *MemoryAttributesTable; - EFI_MEMORY_DESCRIPTOR *MemoryAttributesEntry; - UINTN MemoryAttributesTableSize; + UINTN MemoryMapSize; + EFI_MEMORY_DESCRIPTOR *MemoryMap; + UINTN MapKey; + UINTN DescriptorSize; + UINT32 DescriptorVersion; + UINTN Index; + EFI_STATUS Status; + UINTN RuntimeEntryCount; + EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE *MemoryAttributesTable; + EFI_MEMORY_DESCRIPTOR *MemoryAttributesEntry; + UINTN MemoryAttributesTableSize; MemoryMapSize = 0; - MemoryMap = NULL; - Status = SmmCoreGetMemoryMapMemoryAttributesTable ( - &MemoryMapSize, - MemoryMap, - &MapKey, - &DescriptorSize, - &DescriptorVersion - ); + MemoryMap = NULL; + Status = SmmCoreGetMemoryMapMemoryAttributesTable ( + &MemoryMapSize, + MemoryMap, + &MapKey, + &DescriptorSize, + &DescriptorVersion + ); ASSERT (Status == EFI_BUFFER_TOO_SMALL); do { @@ -1228,9 +1251,9 @@ PublishMemoryAttributesTable ( // // Allocate MemoryAttributesTable // - RuntimeEntryCount = MemoryMapSize/DescriptorSize; - MemoryAttributesTableSize = sizeof(EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount; - MemoryAttributesTable = AllocatePool (sizeof(EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount); + RuntimeEntryCount = MemoryMapSize/DescriptorSize; + MemoryAttributesTableSize = sizeof (EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount; + MemoryAttributesTable = AllocatePool (sizeof (EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE) + DescriptorSize * RuntimeEntryCount); ASSERT (MemoryAttributesTable != NULL); MemoryAttributesTable->Version = EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE_VERSION; MemoryAttributesTable->NumberOfEntries = (UINT32)RuntimeEntryCount; @@ -1249,16 +1272,15 @@ PublishMemoryAttributesTable ( DEBUG ((DEBUG_VERBOSE, " VirtualStart - 0x%016lx\n", MemoryAttributesEntry->VirtualStart)); DEBUG ((DEBUG_VERBOSE, " NumberOfPages - 0x%016lx\n", MemoryAttributesEntry->NumberOfPages)); DEBUG ((DEBUG_VERBOSE, " Attribute - 0x%016lx\n", MemoryAttributesEntry->Attribute)); - MemoryAttributesEntry = NEXT_MEMORY_DESCRIPTOR(MemoryAttributesEntry, DescriptorSize); + MemoryAttributesEntry = NEXT_MEMORY_DESCRIPTOR (MemoryAttributesEntry, DescriptorSize); - MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, DescriptorSize); + MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, DescriptorSize); } Status = gSmst->SmmInstallConfigurationTable (gSmst, &gEdkiiPiSmmMemoryAttributesTableGuid, MemoryAttributesTable, MemoryAttributesTableSize); ASSERT_EFI_ERROR (Status); } - /** This function installs all SMM image record information. **/ @@ -1267,12 +1289,12 @@ SmmInstallImageRecord ( VOID ) { - EFI_STATUS Status; - UINTN NoHandles; - EFI_HANDLE *HandleBuffer; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - UINTN Index; - EFI_SMM_DRIVER_ENTRY DriverEntry; + EFI_STATUS Status; + UINTN NoHandles; + EFI_HANDLE *HandleBuffer; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + UINTN Index; + EFI_SMM_DRIVER_ENTRY DriverEntry; Status = SmmLocateHandleBuffer ( ByProtocol, @@ -1282,7 +1304,7 @@ SmmInstallImageRecord ( &HandleBuffer ); if (EFI_ERROR (Status)) { - return ; + return; } for (Index = 0; Index < NoHandles; Index++) { @@ -1294,18 +1316,19 @@ SmmInstallImageRecord ( if (EFI_ERROR (Status)) { continue; } + DEBUG ((DEBUG_VERBOSE, "LoadedImage - 0x%x 0x%x ", LoadedImage->ImageBase, LoadedImage->ImageSize)); { - VOID *PdbPointer; + VOID *PdbPointer; PdbPointer = PeCoffLoaderGetPdbPointer (LoadedImage->ImageBase); if (PdbPointer != NULL) { DEBUG ((DEBUG_VERBOSE, "(%a) ", PdbPointer)); } } DEBUG ((DEBUG_VERBOSE, "\n")); - ZeroMem (&DriverEntry, sizeof(DriverEntry)); + ZeroMem (&DriverEntry, sizeof (DriverEntry)); DriverEntry.ImageBuffer = (UINTN)LoadedImage->ImageBase; - DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES((UINTN)LoadedImage->ImageSize); + DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN)LoadedImage->ImageSize); SmmInsertImageRecord (&DriverEntry); } @@ -1354,8 +1377,8 @@ SmmCoreInitializeMemoryAttributesTable ( VOID ) { - EFI_STATUS Status; - VOID *Registration; + EFI_STATUS Status; + VOID *Registration; Status = gSmst->SmmRegisterProtocolNotify ( &gEfiSmmEndOfDxeProtocolGuid, @@ -1364,5 +1387,5 @@ SmmCoreInitializeMemoryAttributesTable ( ); ASSERT_EFI_ERROR (Status); - return ; + return; } diff --git a/MdeModulePkg/Core/PiSmmCore/Notify.c b/MdeModulePkg/Core/PiSmmCore/Notify.c index 8e078f7572..7d5bff2576 100644 --- a/MdeModulePkg/Core/PiSmmCore/Notify.c +++ b/MdeModulePkg/Core/PiSmmCore/Notify.c @@ -24,8 +24,8 @@ SmmNotifyProtocol ( LIST_ENTRY *Link; ProtEntry = Prot->Protocol; - for (Link=ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) { - ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); ProtNotify->Function (&ProtEntry->ProtocolID, Prot->Interface, Prot->Handle); } } @@ -54,14 +54,13 @@ SmmRemoveInterfaceFromProtocol ( Prot = SmmFindProtocolInterface (Handle, Protocol, Interface); if (Prot != NULL) { - ProtEntry = Prot->Protocol; // // If there's a protocol notify location pointing to this entry, back it up one // - for(Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link=Link->ForwardLink) { - ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; Link = Link->ForwardLink) { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); if (ProtNotify->Position == &Prot->ByProtocol) { ProtNotify->Position = Prot->ByProtocol.BackLink; @@ -105,7 +104,7 @@ SmmRegisterProtocolNotify ( LIST_ENTRY *Link; EFI_STATUS Status; - if (Protocol == NULL || Registration == NULL) { + if ((Protocol == NULL) || (Registration == NULL)) { return EFI_INVALID_PARAMETER; } @@ -113,16 +112,17 @@ SmmRegisterProtocolNotify ( // // Get the protocol entry per Protocol // - ProtEntry = SmmFindProtocolEntry ((EFI_GUID *) Protocol, FALSE); + ProtEntry = SmmFindProtocolEntry ((EFI_GUID *)Protocol, FALSE); if (ProtEntry != NULL) { - ProtNotify = (PROTOCOL_NOTIFY * )*Registration; + ProtNotify = (PROTOCOL_NOTIFY *)*Registration; for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; - Link = Link->ForwardLink) { + Link = Link->ForwardLink) + { // // Compare the notification record // - if (ProtNotify == (CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE))){ + if (ProtNotify == (CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE))) { // // If Registration is an existing registration, then unhook it // @@ -133,6 +133,7 @@ SmmRegisterProtocolNotify ( } } } + // // If the registration is not found // @@ -144,19 +145,19 @@ SmmRegisterProtocolNotify ( // // Get the protocol entry to add the notification too // - ProtEntry = SmmFindProtocolEntry ((EFI_GUID *) Protocol, TRUE); + ProtEntry = SmmFindProtocolEntry ((EFI_GUID *)Protocol, TRUE); if (ProtEntry != NULL) { // // Find whether notification already exist // for (Link = ProtEntry->Notify.ForwardLink; Link != &ProtEntry->Notify; - Link = Link->ForwardLink) { - - ProtNotify = CR(Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); + Link = Link->ForwardLink) + { + ProtNotify = CR (Link, PROTOCOL_NOTIFY, Link, PROTOCOL_NOTIFY_SIGNATURE); if (CompareGuid (&ProtNotify->Protocol->ProtocolID, Protocol) && - (ProtNotify->Function == Function)) { - + (ProtNotify->Function == Function)) + { // // Notification already exist // @@ -169,11 +170,11 @@ SmmRegisterProtocolNotify ( // // Allocate a new notification record // - ProtNotify = AllocatePool (sizeof(PROTOCOL_NOTIFY)); + ProtNotify = AllocatePool (sizeof (PROTOCOL_NOTIFY)); if (ProtNotify != NULL) { ProtNotify->Signature = PROTOCOL_NOTIFY_SIGNATURE; - ProtNotify->Protocol = ProtEntry; - ProtNotify->Function = Function; + ProtNotify->Protocol = ProtEntry; + ProtNotify->Function = Function; // // Start at the ending // @@ -190,7 +191,8 @@ SmmRegisterProtocolNotify ( Status = EFI_OUT_OF_RESOURCES; if (ProtNotify != NULL) { *Registration = ProtNotify; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } + return Status; } diff --git a/MdeModulePkg/Core/PiSmmCore/Page.c b/MdeModulePkg/Core/PiSmmCore/Page.c index d886187d9a..255964c23a 100644 --- a/MdeModulePkg/Core/PiSmmCore/Page.c +++ b/MdeModulePkg/Core/PiSmmCore/Page.c @@ -17,36 +17,34 @@ LIST_ENTRY mSmmMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (mSmmMemoryMap); // For GetMemoryMap() // -#define MEMORY_MAP_SIGNATURE SIGNATURE_32('m','m','a','p') +#define MEMORY_MAP_SIGNATURE SIGNATURE_32('m','m','a','p') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - - BOOLEAN FromStack; - EFI_MEMORY_TYPE Type; - UINT64 Start; - UINT64 End; + UINTN Signature; + LIST_ENTRY Link; + BOOLEAN FromStack; + EFI_MEMORY_TYPE Type; + UINT64 Start; + UINT64 End; } MEMORY_MAP; -LIST_ENTRY gMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (gMemoryMap); - +LIST_ENTRY gMemoryMap = INITIALIZE_LIST_HEAD_VARIABLE (gMemoryMap); -#define MAX_MAP_DEPTH 6 +#define MAX_MAP_DEPTH 6 /// /// mMapDepth - depth of new descriptor stack /// -UINTN mMapDepth = 0; +UINTN mMapDepth = 0; /// /// mMapStack - space to use as temp storage to build new map descriptors /// -MEMORY_MAP mMapStack[MAX_MAP_DEPTH]; -UINTN mFreeMapStack = 0; +MEMORY_MAP mMapStack[MAX_MAP_DEPTH]; +UINTN mFreeMapStack = 0; /// /// This list maintain the free memory map list /// -LIST_ENTRY mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList); +LIST_ENTRY mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList); /** Allocates pages from the memory map. @@ -91,16 +89,16 @@ AllocateMemoryMapEntry ( VOID ) { - EFI_PHYSICAL_ADDRESS Mem; - EFI_STATUS Status; - MEMORY_MAP* FreeDescriptorEntries; - MEMORY_MAP* Entry; - UINTN Index; + EFI_PHYSICAL_ADDRESS Mem; + EFI_STATUS Status; + MEMORY_MAP *FreeDescriptorEntries; + MEMORY_MAP *Entry; + UINTN Index; - //DEBUG((DEBUG_INFO, "AllocateMemoryMapEntry\n")); + // DEBUG((DEBUG_INFO, "AllocateMemoryMapEntry\n")); if (IsListEmpty (&mFreeMemoryMapEntryList)) { - //DEBUG((DEBUG_INFO, "mFreeMemoryMapEntryList is empty\n")); + // DEBUG((DEBUG_INFO, "mFreeMemoryMapEntryList is empty\n")); // // The list is empty, to allocate one page to refuel the list // @@ -113,13 +111,13 @@ AllocateMemoryMapEntry ( FALSE ); ASSERT_EFI_ERROR (Status); - if(!EFI_ERROR (Status)) { + if (!EFI_ERROR (Status)) { FreeDescriptorEntries = (MEMORY_MAP *)(UINTN)Mem; - //DEBUG((DEBUG_INFO, "New FreeDescriptorEntries - 0x%x\n", FreeDescriptorEntries)); + // DEBUG((DEBUG_INFO, "New FreeDescriptorEntries - 0x%x\n", FreeDescriptorEntries)); // // Enqueue the free memory map entries into the list // - for (Index = 0; Index< RUNTIME_PAGE_ALLOCATION_GRANULARITY / sizeof(MEMORY_MAP); Index++) { + for (Index = 0; Index < RUNTIME_PAGE_ALLOCATION_GRANULARITY / sizeof (MEMORY_MAP); Index++) { FreeDescriptorEntries[Index].Signature = MEMORY_MAP_SIGNATURE; InsertTailList (&mFreeMemoryMapEntryList, &FreeDescriptorEntries[Index].Link); } @@ -127,6 +125,7 @@ AllocateMemoryMapEntry ( return NULL; } } + // // dequeue the first descriptor from the list // @@ -136,7 +135,6 @@ AllocateMemoryMapEntry ( return Entry; } - /** Internal function. Moves any memory descriptors that are on the temporary descriptor stack to heap. @@ -147,14 +145,14 @@ CoreFreeMemoryMapStack ( VOID ) { - MEMORY_MAP *Entry; + MEMORY_MAP *Entry; // // If already freeing the map stack, then return // if (mFreeMapStack != 0) { ASSERT (FALSE); - return ; + return; } // @@ -175,8 +173,7 @@ CoreFreeMemoryMapStack ( mMapDepth -= 1; if (mMapStack[mMapDepth].Link.ForwardLink != NULL) { - - CopyMem (Entry , &mMapStack[mMapDepth], sizeof (MEMORY_MAP)); + CopyMem (Entry, &mMapStack[mMapDepth], sizeof (MEMORY_MAP)); Entry->FromStack = FALSE; // @@ -203,25 +200,25 @@ CoreFreeMemoryMapStack ( **/ VOID InsertNewEntry ( - IN LIST_ENTRY *Link, - IN UINT64 Start, - IN UINT64 End, - IN EFI_MEMORY_TYPE Type, - IN BOOLEAN Next, - IN BOOLEAN AddRegion + IN LIST_ENTRY *Link, + IN UINT64 Start, + IN UINT64 End, + IN EFI_MEMORY_TYPE Type, + IN BOOLEAN Next, + IN BOOLEAN AddRegion ) { MEMORY_MAP *Entry; - Entry = &mMapStack[mMapDepth]; + Entry = &mMapStack[mMapDepth]; mMapDepth += 1; ASSERT (mMapDepth < MAX_MAP_DEPTH); Entry->FromStack = TRUE; Entry->Signature = MEMORY_MAP_SIGNATURE; - Entry->Type = Type; - Entry->Start = Start; - Entry->End = End; + Entry->Type = Type; + Entry->Start = Start; + Entry->End = End; if (Next) { InsertHeadList (Link, &Entry->Link); } else { @@ -263,17 +260,17 @@ ConvertSmmMemoryMapEntry ( IN BOOLEAN AddRegion ) { - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - MEMORY_MAP *NextEntry; - LIST_ENTRY *NextLink; - MEMORY_MAP *PreviousEntry; - LIST_ENTRY *PreviousLink; - EFI_PHYSICAL_ADDRESS Start; - EFI_PHYSICAL_ADDRESS End; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + MEMORY_MAP *NextEntry; + LIST_ENTRY *NextLink; + MEMORY_MAP *PreviousEntry; + LIST_ENTRY *PreviousLink; + EFI_PHYSICAL_ADDRESS Start; + EFI_PHYSICAL_ADDRESS End; Start = Memory; - End = Memory + EFI_PAGES_TO_SIZE(NumberOfPages) - 1; + End = Memory + EFI_PAGES_TO_SIZE (NumberOfPages) - 1; // // Exclude memory region @@ -296,8 +293,9 @@ ConvertSmmMemoryMapEntry ( if (Entry->Start > End) { if ((Entry->Start == End + 1) && (Entry->Type == Type)) { Entry->Start = Start; - return ; + return; } + InsertNewEntry ( &Entry->Link, Start, @@ -306,7 +304,7 @@ ConvertSmmMemoryMapEntry ( FALSE, AddRegion ); - return ; + return; } if ((Entry->Start <= Start) && (Entry->End >= End)) { @@ -331,6 +329,7 @@ ConvertSmmMemoryMapEntry ( AddRegion ); } + if (Entry->End > End) { // // --------------------------------------------------- @@ -351,12 +350,13 @@ ConvertSmmMemoryMapEntry ( AddRegion ); } + // // Update this node // Entry->Start = Start; - Entry->End = End; - Entry->Type = Type; + Entry->End = End; + Entry->Type = Type; // // Check adjacent @@ -375,6 +375,7 @@ ConvertSmmMemoryMapEntry ( RemoveOldEntry (NextEntry); } } + PreviousLink = Entry->Link.BackLink; if (PreviousLink != &gMemoryMap) { PreviousEntry = CR (PreviousLink, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); @@ -390,7 +391,8 @@ ConvertSmmMemoryMapEntry ( } } } - return ; + + return; } } @@ -409,9 +411,10 @@ ConvertSmmMemoryMapEntry ( Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); if ((Entry->End + 1 == Start) && (Entry->Type == Type)) { Entry->End = End; - return ; + return; } } + InsertNewEntry ( &gMemoryMap, Start, @@ -420,7 +423,7 @@ ConvertSmmMemoryMapEntry ( FALSE, AddRegion ); - return ; + return; } /** @@ -433,20 +436,19 @@ GetSmmMemoryMapEntryCount ( VOID ) { - LIST_ENTRY *Link; - UINTN Count; + LIST_ENTRY *Link; + UINTN Count; Count = 0; - Link = gMemoryMap.ForwardLink; + Link = gMemoryMap.ForwardLink; while (Link != &gMemoryMap) { - Link = Link->ForwardLink; + Link = Link->ForwardLink; Count++; } + return Count; } - - /** Internal Function. Allocate n pages from given free page node. @@ -472,10 +474,11 @@ InternalAllocPagesOnOneNode ( if (Top > Pages->NumberOfPages) { Top = Pages->NumberOfPages; } + Bottom = Top - NumberOfPages; if (Top < Pages->NumberOfPages) { - Node = (FREE_PAGE_LIST*)((UINTN)Pages + EFI_PAGES_TO_SIZE (Top)); + Node = (FREE_PAGE_LIST *)((UINTN)Pages + EFI_PAGES_TO_SIZE (Top)); Node->NumberOfPages = Pages->NumberOfPages - Top; InsertHeadList (&Pages->Link, &Node->Link); } @@ -511,11 +514,13 @@ InternalAllocMaxAddress ( for (Node = FreePageList->BackLink; Node != FreePageList; Node = Node->BackLink) { Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); - if (Pages->NumberOfPages >= NumberOfPages && - (UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress) { + if ((Pages->NumberOfPages >= NumberOfPages) && + ((UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress)) + { return InternalAllocPagesOnOneNode (Pages, NumberOfPages, MaxAddress); } } + return (UINTN)(-1); } @@ -545,15 +550,17 @@ InternalAllocAddress ( } EndAddress = Address + EFI_PAGES_TO_SIZE (NumberOfPages); - for (Node = FreePageList->BackLink; Node!= FreePageList; Node = Node->BackLink) { + for (Node = FreePageList->BackLink; Node != FreePageList; Node = Node->BackLink) { Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); if ((UINTN)Pages <= Address) { if ((UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages) < EndAddress) { break; } + return InternalAllocPagesOnOneNode (Pages, NumberOfPages, EndAddress); } } + return ~Address; } @@ -588,8 +595,9 @@ SmmInternalAllocatePagesEx ( { UINTN RequestedAddress; - if (MemoryType != EfiRuntimeServicesCode && - MemoryType != EfiRuntimeServicesData) { + if ((MemoryType != EfiRuntimeServicesCode) && + (MemoryType != EfiRuntimeServicesData)) + { return EFI_INVALID_PARAMETER; } @@ -607,11 +615,11 @@ SmmInternalAllocatePagesEx ( case AllocateMaxAddress: if (NeedGuard) { *Memory = InternalAllocMaxAddressWithGuard ( - &mSmmMemoryMap, - NumberOfPages, - RequestedAddress, - MemoryType - ); + &mSmmMemoryMap, + NumberOfPages, + RequestedAddress, + MemoryType + ); if (*Memory == (UINTN)-1) { return EFI_OUT_OF_RESOURCES; } else { @@ -628,6 +636,7 @@ SmmInternalAllocatePagesEx ( if (*Memory == (UINTN)-1) { return EFI_OUT_OF_RESOURCES; } + break; case AllocateAddress: *Memory = InternalAllocAddress ( @@ -638,6 +647,7 @@ SmmInternalAllocatePagesEx ( if (*Memory != RequestedAddress) { return EFI_NOT_FOUND; } + break; default: return EFI_INVALID_PARAMETER; @@ -648,7 +658,7 @@ SmmInternalAllocatePagesEx ( // ConvertSmmMemoryMapEntry (MemoryType, *Memory, NumberOfPages, AddRegion); if (!AddRegion) { - CoreFreeMemoryMapStack(); + CoreFreeMemoryMapStack (); } return EFI_SUCCESS; @@ -682,8 +692,14 @@ SmmInternalAllocatePages ( IN BOOLEAN NeedGuard ) { - return SmmInternalAllocatePagesEx (Type, MemoryType, NumberOfPages, Memory, - FALSE, NeedGuard); + return SmmInternalAllocatePagesEx ( + Type, + MemoryType, + NumberOfPages, + Memory, + FALSE, + NeedGuard + ); } /** @@ -715,18 +731,24 @@ SmmAllocatePages ( BOOLEAN NeedGuard; NeedGuard = IsPageTypeToGuard (MemoryType, Type); - Status = SmmInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory, - NeedGuard); + Status = SmmInternalAllocatePages ( + Type, + MemoryType, + NumberOfPages, + Memory, + NeedGuard + ); if (!EFI_ERROR (Status)) { SmmCoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionAllocatePages, MemoryType, EFI_PAGES_TO_SIZE (NumberOfPages), - (VOID *) (UINTN) *Memory, + (VOID *)(UINTN)*Memory, NULL ); } + return Status; } @@ -747,13 +769,15 @@ InternalMergeNodes ( Next = BASE_CR (First->Link.ForwardLink, FREE_PAGE_LIST, Link); ASSERT ( - TRUNCATE_TO_PAGES ((UINTN)Next - (UINTN)First) >= First->NumberOfPages); + TRUNCATE_TO_PAGES ((UINTN)Next - (UINTN)First) >= First->NumberOfPages + ); if (TRUNCATE_TO_PAGES ((UINTN)Next - (UINTN)First) == First->NumberOfPages) { First->NumberOfPages += Next->NumberOfPages; RemoveEntryList (&Next->Link); Next = First; } + return Next; } @@ -784,17 +808,19 @@ SmmInternalFreePagesEx ( } Pages = NULL; - Node = mSmmMemoryMap.ForwardLink; + Node = mSmmMemoryMap.ForwardLink; while (Node != &mSmmMemoryMap) { Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); if (Memory < (UINTN)Pages) { break; } + Node = Node->ForwardLink; } - if (Node != &mSmmMemoryMap && - Memory + EFI_PAGES_TO_SIZE (NumberOfPages) > (UINTN)Pages) { + if ((Node != &mSmmMemoryMap) && + (Memory + EFI_PAGES_TO_SIZE (NumberOfPages) > (UINTN)Pages)) + { return EFI_INVALID_PARAMETER; } @@ -805,7 +831,7 @@ SmmInternalFreePagesEx ( } } - Pages = (FREE_PAGE_LIST*)(UINTN)Memory; + Pages = (FREE_PAGE_LIST *)(UINTN)Memory; Pages->NumberOfPages = NumberOfPages; InsertTailList (Node, &Pages->Link); @@ -824,7 +850,7 @@ SmmInternalFreePagesEx ( // ConvertSmmMemoryMapEntry (EfiConventionalMemory, Memory, NumberOfPages, AddRegion); if (!AddRegion) { - CoreFreeMemoryMapStack(); + CoreFreeMemoryMapStack (); } return EFI_SUCCESS; @@ -853,6 +879,7 @@ SmmInternalFreePages ( if (IsGuarded) { return SmmInternalFreePagesExWithGuard (Memory, NumberOfPages, FALSE); } + return SmmInternalFreePagesEx (Memory, NumberOfPages, FALSE); } @@ -872,9 +899,9 @@ InMemMap ( IN UINTN NumberOfPages ) { - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - EFI_PHYSICAL_ADDRESS Last; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + EFI_PHYSICAL_ADDRESS Last; Last = Memory + EFI_PAGES_TO_SIZE (NumberOfPages) - 1; @@ -912,22 +939,23 @@ SmmFreePages ( EFI_STATUS Status; BOOLEAN IsGuarded; - if (!InMemMap(Memory, NumberOfPages)) { + if (!InMemMap (Memory, NumberOfPages)) { return EFI_NOT_FOUND; } IsGuarded = IsHeapGuardEnabled () && IsMemoryGuarded (Memory); - Status = SmmInternalFreePages (Memory, NumberOfPages, IsGuarded); + Status = SmmInternalFreePages (Memory, NumberOfPages, IsGuarded); if (!EFI_ERROR (Status)) { SmmCoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionFreePages, EfiMaxMemoryType, EFI_PAGES_TO_SIZE (NumberOfPages), - (VOID *) (UINTN) Memory, + (VOID *)(UINTN)Memory, NULL ); } + return Status; } @@ -969,7 +997,7 @@ SmmAddMemoryRegion ( // Align range on an EFI_PAGE_SIZE boundary // AlignedMemBase = (UINTN)(MemBase + EFI_PAGE_MASK) & ~EFI_PAGE_MASK; - MemLength -= AlignedMemBase - MemBase; + MemLength -= AlignedMemBase - MemBase; if (Type == EfiConventionalMemory) { SmmInternalFreePagesEx (AlignedMemBase, TRUNCATE_TO_PAGES ((UINTN)MemLength), TRUE); } else { @@ -1019,11 +1047,11 @@ SmmCoreGetMemoryMap ( OUT UINT32 *DescriptorVersion ) { - UINTN Count; - LIST_ENTRY *Link; - MEMORY_MAP *Entry; - UINTN Size; - UINTN BufferSize; + UINTN Count; + LIST_ENTRY *Link; + MEMORY_MAP *Entry; + UINTN Size; + UINTN BufferSize; Size = sizeof (EFI_MEMORY_DESCRIPTOR); @@ -1032,7 +1060,7 @@ SmmCoreGetMemoryMap ( // prevent people from having pointer math bugs in their code. // now you have to use *DescriptorSize to make things work. // - Size += sizeof(UINT64) - (Size % sizeof (UINT64)); + Size += sizeof (UINT64) - (Size % sizeof (UINT64)); if (DescriptorSize != NULL) { *DescriptorSize = Size; @@ -1042,7 +1070,7 @@ SmmCoreGetMemoryMap ( *DescriptorVersion = EFI_MEMORY_DESCRIPTOR_VERSION; } - Count = GetSmmMemoryMapEntryCount (); + Count = GetSmmMemoryMapEntryCount (); BufferSize = Size * Count; if (*MemoryMapSize < BufferSize) { *MemoryMapSize = BufferSize; @@ -1060,9 +1088,9 @@ SmmCoreGetMemoryMap ( Entry = CR (Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE); Link = Link->ForwardLink; - MemoryMap->Type = Entry->Type; - MemoryMap->PhysicalStart = Entry->Start; - MemoryMap->NumberOfPages = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT); + MemoryMap->Type = Entry->Type; + MemoryMap->PhysicalStart = Entry->Start; + MemoryMap->NumberOfPages = RShiftU64 (Entry->End - Entry->Start + 1, EFI_PAGE_SHIFT); MemoryMap = NEXT_MEMORY_DESCRIPTOR (MemoryMap, Size); } diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c index 2e6d7913f4..9e5c6cbe33 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.c @@ -27,12 +27,12 @@ EFI_SMM_SYSTEM_TABLE2 gSmmCoreSmst = { SmmInstallConfigurationTable, { { - (EFI_SMM_CPU_IO2) SmmEfiNotAvailableYetArg5, // SmmMemRead - (EFI_SMM_CPU_IO2) SmmEfiNotAvailableYetArg5 // SmmMemWrite + (EFI_SMM_CPU_IO2)SmmEfiNotAvailableYetArg5, // SmmMemRead + (EFI_SMM_CPU_IO2)SmmEfiNotAvailableYetArg5 // SmmMemWrite }, { - (EFI_SMM_CPU_IO2) SmmEfiNotAvailableYetArg5, // SmmIoRead - (EFI_SMM_CPU_IO2) SmmEfiNotAvailableYetArg5 // SmmIoWrite + (EFI_SMM_CPU_IO2)SmmEfiNotAvailableYetArg5, // SmmIoRead + (EFI_SMM_CPU_IO2)SmmEfiNotAvailableYetArg5 // SmmIoWrite } }, SmmAllocatePool, @@ -81,30 +81,30 @@ BOOLEAN mAcpiS3Enable = FALSE; // Table of SMI Handlers that are registered by the SMM Core when it is initialized // SMM_CORE_SMI_HANDLERS mSmmCoreSmiHandlers[] = { - { SmmDriverDispatchHandler, &gEfiEventDxeDispatchGuid, NULL, TRUE }, - { SmmReadyToLockHandler, &gEfiDxeSmmReadyToLockProtocolGuid, NULL, TRUE }, - { SmmLegacyBootHandler, &gEfiEventLegacyBootGuid, NULL, FALSE }, - { SmmExitBootServicesHandler, &gEfiEventExitBootServicesGuid, NULL, FALSE }, - { SmmReadyToBootHandler, &gEfiEventReadyToBootGuid, NULL, FALSE }, - { SmmEndOfDxeHandler, &gEfiEndOfDxeEventGroupGuid, NULL, TRUE }, - { NULL, NULL, NULL, FALSE } + { SmmDriverDispatchHandler, &gEfiEventDxeDispatchGuid, NULL, TRUE }, + { SmmReadyToLockHandler, &gEfiDxeSmmReadyToLockProtocolGuid, NULL, TRUE }, + { SmmLegacyBootHandler, &gEfiEventLegacyBootGuid, NULL, FALSE }, + { SmmExitBootServicesHandler, &gEfiEventExitBootServicesGuid, NULL, FALSE }, + { SmmReadyToBootHandler, &gEfiEventReadyToBootGuid, NULL, FALSE }, + { SmmEndOfDxeHandler, &gEfiEndOfDxeEventGroupGuid, NULL, TRUE }, + { NULL, NULL, NULL, FALSE } }; // // Table of SMI Handlers that are registered by the SMM Core when it is initialized // SMM_CORE_SMI_HANDLERS mSmmCoreS3SmiHandlers[] = { - { SmmS3SmmInitDoneHandler, &gEdkiiS3SmmInitDoneGuid, NULL, FALSE }, - { SmmEndOfS3ResumeHandler, &gEdkiiEndOfS3ResumeGuid, NULL, FALSE }, - { NULL, NULL, NULL, FALSE } + { SmmS3SmmInitDoneHandler, &gEdkiiS3SmmInitDoneGuid, NULL, FALSE }, + { SmmEndOfS3ResumeHandler, &gEdkiiEndOfS3ResumeGuid, NULL, FALSE }, + { NULL, NULL, NULL, FALSE } }; -UINTN mFullSmramRangeCount; -EFI_SMRAM_DESCRIPTOR *mFullSmramRanges; +UINTN mFullSmramRangeCount; +EFI_SMRAM_DESCRIPTOR *mFullSmramRanges; -EFI_SMM_DRIVER_ENTRY *mSmmCoreDriverEntry; +EFI_SMM_DRIVER_ENTRY *mSmmCoreDriverEntry; -EFI_LOADED_IMAGE_PROTOCOL *mSmmCoreLoadedImage; +EFI_LOADED_IMAGE_PROTOCOL *mSmmCoreLoadedImage; /** Place holder function until all the SMM System Table Service are available. @@ -123,11 +123,11 @@ EFI_LOADED_IMAGE_PROTOCOL *mSmmCoreLoadedImage; EFI_STATUS EFIAPI SmmEfiNotAvailableYetArg5 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4, - UINTN Arg5 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4, + UINTN Arg5 ) { // @@ -163,20 +163,20 @@ SmmLegacyBootHandler ( IN OUT UINTN *CommBufferSize OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE SmmHandle; - UINTN Index; + EFI_STATUS Status; + EFI_HANDLE SmmHandle; + UINTN Index; // // Install SMM Legacy Boot protocol. // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEdkiiSmmLegacyBootProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEdkiiSmmLegacyBootProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); mInLegacyBoot = TRUE; @@ -218,20 +218,20 @@ SmmExitBootServicesHandler ( IN OUT UINTN *CommBufferSize OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE SmmHandle; - UINTN Index; + EFI_STATUS Status; + EFI_HANDLE SmmHandle; + UINTN Index; // // Install SMM Exit Boot Services protocol. // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEdkiiSmmExitBootServicesProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEdkiiSmmExitBootServicesProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); SmiHandlerUnRegister (DispatchHandle); @@ -269,10 +269,10 @@ SmmExitBootServicesHandler ( EFI_STATUS EFIAPI SmmS3EntryCallBack ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ) { mDuringS3Resume = TRUE; @@ -302,19 +302,19 @@ SmmReadyToBootHandler ( IN OUT UINTN *CommBufferSize OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE SmmHandle; + EFI_STATUS Status; + EFI_HANDLE SmmHandle; // // Install SMM Ready To Boot protocol. // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEdkiiSmmReadyToBootProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEdkiiSmmReadyToBootProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); SmiHandlerUnRegister (DispatchHandle); @@ -365,12 +365,12 @@ SmmReadyToLockHandler ( // Install SMM Ready to lock protocol // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEfiSmmReadyToLockProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEfiSmmReadyToLockProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); // // Make sure SMM CPU I/O 2 Protocol has been installed into the handle database @@ -381,9 +381,10 @@ SmmReadyToLockHandler ( // Print a message on a debug build if the SMM CPU I/O 2 Protocol is not installed // DEBUG_CODE_BEGIN (); - if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "\nSMM: SmmCpuIo Arch Protocol not present!!\n")); - } + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "\nSMM: SmmCpuIo Arch Protocol not present!!\n")); + } + DEBUG_CODE_END (); // @@ -396,7 +397,7 @@ SmmReadyToLockHandler ( // evaluated to false if this is a debug build // DEBUG_CODE_BEGIN (); - SmmDisplayDiscoveredNotDispatched (); + SmmDisplayDiscoveredNotDispatched (); DEBUG_CODE_END (); // @@ -433,11 +434,11 @@ SmmEndOfDxeHandler ( IN OUT UINTN *CommBufferSize OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE SmmHandle; - EFI_SMM_SX_DISPATCH2_PROTOCOL *SxDispatch; - EFI_SMM_SX_REGISTER_CONTEXT EntryRegisterContext; - EFI_HANDLE S3EntryHandle; + EFI_STATUS Status; + EFI_HANDLE SmmHandle; + EFI_SMM_SX_DISPATCH2_PROTOCOL *SxDispatch; + EFI_SMM_SX_REGISTER_CONTEXT EntryRegisterContext; + EFI_HANDLE S3EntryHandle; DEBUG ((DEBUG_INFO, "SmmEndOfDxeHandler\n")); @@ -445,12 +446,12 @@ SmmEndOfDxeHandler ( // Install SMM EndOfDxe protocol // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEfiSmmEndOfDxeProtocolGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEfiSmmEndOfDxeProtocolGuid, + EFI_NATIVE_INTERFACE, + NULL + ); if (mAcpiS3Enable) { // @@ -468,12 +469,12 @@ SmmEndOfDxeHandler ( // EntryRegisterContext.Type = SxS3; EntryRegisterContext.Phase = SxEntry; - Status = SxDispatch->Register ( - SxDispatch, - SmmS3EntryCallBack, - &EntryRegisterContext, - &S3EntryHandle - ); + Status = SxDispatch->Register ( + SxDispatch, + SmmS3EntryCallBack, + &EntryRegisterContext, + &S3EntryHandle + ); ASSERT_EFI_ERROR (Status); } } @@ -518,12 +519,12 @@ SmmS3SmmInitDoneHandler ( // Install SMM S3SmmInitDone protocol // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEdkiiS3SmmInitDoneGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEdkiiS3SmmInitDoneGuid, + EFI_NATIVE_INTERFACE, + NULL + ); ASSERT_EFI_ERROR (Status); // @@ -531,10 +532,10 @@ SmmS3SmmInitDoneHandler ( // installation event. // Status = SmmUninstallProtocolInterface ( - SmmHandle, - &gEdkiiS3SmmInitDoneGuid, - NULL - ); + SmmHandle, + &gEdkiiS3SmmInitDoneGuid, + NULL + ); ASSERT_EFI_ERROR (Status); return Status; @@ -577,12 +578,12 @@ SmmEndOfS3ResumeHandler ( // Install SMM EndOfS3Resume protocol // SmmHandle = NULL; - Status = SmmInstallProtocolInterface ( - &SmmHandle, - &gEdkiiEndOfS3ResumeGuid, - EFI_NATIVE_INTERFACE, - NULL - ); + Status = SmmInstallProtocolInterface ( + &SmmHandle, + &gEdkiiEndOfS3ResumeGuid, + EFI_NATIVE_INTERFACE, + NULL + ); ASSERT_EFI_ERROR (Status); // @@ -590,10 +591,10 @@ SmmEndOfS3ResumeHandler ( // installation event. // Status = SmmUninstallProtocolInterface ( - SmmHandle, - &gEdkiiEndOfS3ResumeGuid, - NULL - ); + SmmHandle, + &gEdkiiEndOfS3ResumeGuid, + NULL + ); ASSERT_EFI_ERROR (Status); mDuringS3Resume = FALSE; @@ -614,10 +615,10 @@ SmmEndOfS3ResumeHandler ( **/ BOOLEAN InternalIsBufferOverlapped ( - IN UINT8 *Buff1, - IN UINTN Size1, - IN UINT8 *Buff2, - IN UINTN Size2 + IN UINT8 *Buff1, + IN UINTN Size1, + IN UINT8 *Buff2, + IN UINTN Size2 ) { // @@ -644,7 +645,7 @@ VOID EFIAPI SmmEntryPoint ( IN CONST EFI_SMM_ENTRY_CONTEXT *SmmEntryContext -) + ) { EFI_STATUS Status; EFI_SMM_COMMUNICATE_HEADER *CommunicateHeader; @@ -693,9 +694,9 @@ SmmEntryPoint ( // Synchronous SMI for SMM Core or request from Communicate protocol // IsOverlapped = InternalIsBufferOverlapped ( - (UINT8 *) CommunicationBuffer, + (UINT8 *)CommunicationBuffer, BufferSize, - (UINT8 *) gSmmCorePrivate, + (UINT8 *)gSmmCorePrivate, sizeof (*gSmmCorePrivate) ); if (!SmmIsBufferOutsideSmmValid ((UINTN)CommunicationBuffer, BufferSize) || IsOverlapped) { @@ -705,23 +706,23 @@ SmmEntryPoint ( // return EFI_INVALID_PARAMETER // gSmmCorePrivate->CommunicationBuffer = NULL; - gSmmCorePrivate->ReturnStatus = EFI_ACCESS_DENIED; + gSmmCorePrivate->ReturnStatus = EFI_ACCESS_DENIED; } else { CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)CommunicationBuffer; - BufferSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); - Status = SmiManage ( - &CommunicateHeader->HeaderGuid, - NULL, - CommunicateHeader->Data, - &BufferSize - ); + BufferSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); + Status = SmiManage ( + &CommunicateHeader->HeaderGuid, + NULL, + CommunicateHeader->Data, + &BufferSize + ); // // Update CommunicationBuffer, BufferSize and ReturnStatus // Communicate service finished, reset the pointer to CommBuffer to NULL // - gSmmCorePrivate->BufferSize = BufferSize + OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); + gSmmCorePrivate->BufferSize = BufferSize + OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); gSmmCorePrivate->CommunicationBuffer = NULL; - gSmmCorePrivate->ReturnStatus = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND; + gSmmCorePrivate->ReturnStatus = (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND; } } } @@ -755,13 +756,13 @@ SmmCoreInstallLoadedImage ( VOID ) { - EFI_STATUS Status; - EFI_HANDLE Handle; + EFI_STATUS Status; + EFI_HANDLE Handle; // // Allocate a Loaded Image Protocol in EfiBootServicesData // - Status = gBS->AllocatePool (EfiBootServicesData, sizeof(EFI_LOADED_IMAGE_PROTOCOL), (VOID **)&mSmmCoreLoadedImage); + Status = gBS->AllocatePool (EfiBootServicesData, sizeof (EFI_LOADED_IMAGE_PROTOCOL), (VOID **)&mSmmCoreLoadedImage); ASSERT_EFI_ERROR (Status); ZeroMem (mSmmCoreLoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL)); @@ -769,9 +770,9 @@ SmmCoreInstallLoadedImage ( // Fill in the remaining fields of the Loaded Image Protocol instance. // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed. // - mSmmCoreLoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; - mSmmCoreLoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle; - mSmmCoreLoadedImage->SystemTable = gST; + mSmmCoreLoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; + mSmmCoreLoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle; + mSmmCoreLoadedImage->SystemTable = gST; mSmmCoreLoadedImage->ImageBase = (VOID *)(UINTN)gSmmCorePrivate->PiSmmCoreImageBase; mSmmCoreLoadedImage->ImageSize = gSmmCorePrivate->PiSmmCoreImageSize; @@ -784,7 +785,8 @@ SmmCoreInstallLoadedImage ( Handle = NULL; Status = gBS->InstallMultipleProtocolInterfaces ( &Handle, - &gEfiLoadedImageProtocolGuid, mSmmCoreLoadedImage, + &gEfiLoadedImageProtocolGuid, + mSmmCoreLoadedImage, NULL ); ASSERT_EFI_ERROR (Status); @@ -792,40 +794,40 @@ SmmCoreInstallLoadedImage ( // // Allocate a Loaded Image Protocol in SMM // - Status = SmmAllocatePool (EfiRuntimeServicesData, sizeof(EFI_SMM_DRIVER_ENTRY), (VOID **)&mSmmCoreDriverEntry); - ASSERT_EFI_ERROR(Status); + Status = SmmAllocatePool (EfiRuntimeServicesData, sizeof (EFI_SMM_DRIVER_ENTRY), (VOID **)&mSmmCoreDriverEntry); + ASSERT_EFI_ERROR (Status); - ZeroMem (mSmmCoreDriverEntry, sizeof(EFI_SMM_DRIVER_ENTRY)); + ZeroMem (mSmmCoreDriverEntry, sizeof (EFI_SMM_DRIVER_ENTRY)); // // Fill in the remaining fields of the Loaded Image Protocol instance. // - mSmmCoreDriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE; - mSmmCoreDriverEntry->SmmLoadedImage.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; + mSmmCoreDriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE; + mSmmCoreDriverEntry->SmmLoadedImage.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION; mSmmCoreDriverEntry->SmmLoadedImage.ParentHandle = gSmmCorePrivate->SmmIplImageHandle; - mSmmCoreDriverEntry->SmmLoadedImage.SystemTable = gST; + mSmmCoreDriverEntry->SmmLoadedImage.SystemTable = gST; - mSmmCoreDriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN)gSmmCorePrivate->PiSmmCoreImageBase; - mSmmCoreDriverEntry->SmmLoadedImage.ImageSize = gSmmCorePrivate->PiSmmCoreImageSize; + mSmmCoreDriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN)gSmmCorePrivate->PiSmmCoreImageBase; + mSmmCoreDriverEntry->SmmLoadedImage.ImageSize = gSmmCorePrivate->PiSmmCoreImageSize; mSmmCoreDriverEntry->SmmLoadedImage.ImageCodeType = EfiRuntimeServicesCode; mSmmCoreDriverEntry->SmmLoadedImage.ImageDataType = EfiRuntimeServicesData; mSmmCoreDriverEntry->ImageEntryPoint = gSmmCorePrivate->PiSmmCoreEntryPoint; mSmmCoreDriverEntry->ImageBuffer = gSmmCorePrivate->PiSmmCoreImageBase; - mSmmCoreDriverEntry->NumberOfPage = EFI_SIZE_TO_PAGES((UINTN)gSmmCorePrivate->PiSmmCoreImageSize); + mSmmCoreDriverEntry->NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN)gSmmCorePrivate->PiSmmCoreImageSize); // // Create a new image handle in the SMM handle database for the SMM Driver // mSmmCoreDriverEntry->SmmImageHandle = NULL; - Status = SmmInstallProtocolInterface ( - &mSmmCoreDriverEntry->SmmImageHandle, - &gEfiLoadedImageProtocolGuid, - EFI_NATIVE_INTERFACE, - &mSmmCoreDriverEntry->SmmLoadedImage - ); - ASSERT_EFI_ERROR(Status); + Status = SmmInstallProtocolInterface ( + &mSmmCoreDriverEntry->SmmImageHandle, + &gEfiLoadedImageProtocolGuid, + EFI_NATIVE_INTERFACE, + &mSmmCoreDriverEntry->SmmLoadedImage + ); + ASSERT_EFI_ERROR (Status); - return ; + return; } /** @@ -876,7 +878,7 @@ SmmMain ( // Copy FullSmramRanges to SMRAM // mFullSmramRangeCount = gSmmCorePrivate->SmramRangeCount; - mFullSmramRanges = AllocatePool (mFullSmramRangeCount * sizeof (EFI_SMRAM_DESCRIPTOR)); + mFullSmramRanges = AllocatePool (mFullSmramRangeCount * sizeof (EFI_SMRAM_DESCRIPTOR)); ASSERT (mFullSmramRanges != NULL); CopyMem (mFullSmramRanges, gSmmCorePrivate->SmramRanges, mFullSmramRangeCount * sizeof (EFI_SMRAM_DESCRIPTOR)); diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h index 19ce69f5e8..71422b9dfc 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h @@ -62,10 +62,10 @@ // Used to build a table of SMI Handlers that the SMM Core registers // typedef struct { - EFI_SMM_HANDLER_ENTRY_POINT2 Handler; - EFI_GUID *HandlerType; - EFI_HANDLE DispatchHandle; - BOOLEAN UnRegister; + EFI_SMM_HANDLER_ENTRY_POINT2 Handler; + EFI_GUID *HandlerType; + EFI_HANDLE DispatchHandle; + BOOLEAN UnRegister; } SMM_CORE_SMI_HANDLERS; // @@ -74,89 +74,89 @@ typedef struct { #define SMI_ENTRY_SIGNATURE SIGNATURE_32('s','m','i','e') - typedef struct { - UINTN Signature; - LIST_ENTRY AllEntries; // All entries +typedef struct { + UINTN Signature; + LIST_ENTRY AllEntries; // All entries - EFI_GUID HandlerType; // Type of interrupt - LIST_ENTRY SmiHandlers; // All handlers + EFI_GUID HandlerType; // Type of interrupt + LIST_ENTRY SmiHandlers; // All handlers } SMI_ENTRY; #define SMI_HANDLER_SIGNATURE SIGNATURE_32('s','m','i','h') - typedef struct { - UINTN Signature; - LIST_ENTRY Link; // Link on SMI_ENTRY.SmiHandlers - EFI_SMM_HANDLER_ENTRY_POINT2 Handler; // The smm handler's entry point - UINTN CallerAddr; // The address of caller who register the SMI handler. - SMI_ENTRY *SmiEntry; - VOID *Context; // for profile - UINTN ContextSize; // for profile +typedef struct { + UINTN Signature; + LIST_ENTRY Link; // Link on SMI_ENTRY.SmiHandlers + EFI_SMM_HANDLER_ENTRY_POINT2 Handler; // The smm handler's entry point + UINTN CallerAddr; // The address of caller who register the SMI handler. + SMI_ENTRY *SmiEntry; + VOID *Context; // for profile + UINTN ContextSize; // for profile } SMI_HANDLER; // // Structure for recording the state of an SMM Driver // -#define EFI_SMM_DRIVER_ENTRY_SIGNATURE SIGNATURE_32('s', 'd','r','v') +#define EFI_SMM_DRIVER_ENTRY_SIGNATURE SIGNATURE_32('s', 'd','r','v') typedef struct { - UINTN Signature; - LIST_ENTRY Link; // mDriverList + UINTN Signature; + LIST_ENTRY Link; // mDriverList - LIST_ENTRY ScheduledLink; // mScheduledQueue + LIST_ENTRY ScheduledLink; // mScheduledQueue - EFI_HANDLE FvHandle; - EFI_GUID FileName; - EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; - EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; + EFI_HANDLE FvHandle; + EFI_GUID FileName; + EFI_DEVICE_PATH_PROTOCOL *FvFileDevicePath; + EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv; - VOID *Depex; - UINTN DepexSize; + VOID *Depex; + UINTN DepexSize; - BOOLEAN Before; - BOOLEAN After; - EFI_GUID BeforeAfterGuid; + BOOLEAN Before; + BOOLEAN After; + EFI_GUID BeforeAfterGuid; - BOOLEAN Dependent; - BOOLEAN Scheduled; - BOOLEAN Initialized; - BOOLEAN DepexProtocolError; + BOOLEAN Dependent; + BOOLEAN Scheduled; + BOOLEAN Initialized; + BOOLEAN DepexProtocolError; - EFI_HANDLE ImageHandle; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + EFI_HANDLE ImageHandle; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; // // Image EntryPoint in SMRAM // - PHYSICAL_ADDRESS ImageEntryPoint; + PHYSICAL_ADDRESS ImageEntryPoint; // // Image Buffer in SMRAM // - PHYSICAL_ADDRESS ImageBuffer; + PHYSICAL_ADDRESS ImageBuffer; // // Image Page Number // - UINTN NumberOfPage; - EFI_HANDLE SmmImageHandle; - EFI_LOADED_IMAGE_PROTOCOL SmmLoadedImage; + UINTN NumberOfPage; + EFI_HANDLE SmmImageHandle; + EFI_LOADED_IMAGE_PROTOCOL SmmLoadedImage; } EFI_SMM_DRIVER_ENTRY; -#define EFI_HANDLE_SIGNATURE SIGNATURE_32('s','h','d','l') +#define EFI_HANDLE_SIGNATURE SIGNATURE_32('s','h','d','l') /// /// IHANDLE - contains a list of protocol handles /// typedef struct { - UINTN Signature; + UINTN Signature; /// All handles list of IHANDLE - LIST_ENTRY AllHandles; + LIST_ENTRY AllHandles; /// List of PROTOCOL_INTERFACE's for this handle - LIST_ENTRY Protocols; - UINTN LocateRequest; + LIST_ENTRY Protocols; + UINTN LocateRequest; } IHANDLE; #define ASSERT_IS_HANDLE(a) ASSERT((a)->Signature == EFI_HANDLE_SIGNATURE) -#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('s','p','t','e') +#define PROTOCOL_ENTRY_SIGNATURE SIGNATURE_32('s','p','t','e') /// /// PROTOCOL_ENTRY - each different protocol has 1 entry in the protocol @@ -164,15 +164,15 @@ typedef struct { /// with a list of registered notifies. /// typedef struct { - UINTN Signature; + UINTN Signature; /// Link Entry inserted to mProtocolDatabase - LIST_ENTRY AllEntries; + LIST_ENTRY AllEntries; /// ID of the protocol - EFI_GUID ProtocolID; + EFI_GUID ProtocolID; /// All protocol interfaces - LIST_ENTRY Protocols; + LIST_ENTRY Protocols; /// Registered notification handlers - LIST_ENTRY Notify; + LIST_ENTRY Notify; } PROTOCOL_ENTRY; #define PROTOCOL_INTERFACE_SIGNATURE SIGNATURE_32('s','p','i','f') @@ -182,33 +182,33 @@ typedef struct { /// with a protocol interface structure /// typedef struct { - UINTN Signature; + UINTN Signature; /// Link on IHANDLE.Protocols - LIST_ENTRY Link; + LIST_ENTRY Link; /// Back pointer - IHANDLE *Handle; + IHANDLE *Handle; /// Link on PROTOCOL_ENTRY.Protocols - LIST_ENTRY ByProtocol; + LIST_ENTRY ByProtocol; /// The protocol ID - PROTOCOL_ENTRY *Protocol; + PROTOCOL_ENTRY *Protocol; /// The interface value - VOID *Interface; + VOID *Interface; } PROTOCOL_INTERFACE; -#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('s','p','t','n') +#define PROTOCOL_NOTIFY_SIGNATURE SIGNATURE_32('s','p','t','n') /// /// PROTOCOL_NOTIFY - used for each register notification for a protocol /// typedef struct { - UINTN Signature; - PROTOCOL_ENTRY *Protocol; + UINTN Signature; + PROTOCOL_ENTRY *Protocol; /// All notifications for this protocol - LIST_ENTRY Link; + LIST_ENTRY Link; /// Notification function - EFI_SMM_NOTIFY_FN Function; + EFI_SMM_NOTIFY_FN Function; /// Last position notified - LIST_ENTRY *Position; + LIST_ENTRY *Position; } PROTOCOL_NOTIFY; // @@ -253,9 +253,9 @@ EFI_STATUS EFIAPI SmmInstallConfigurationTable ( IN CONST EFI_SMM_SYSTEM_TABLE2 *SystemTable, - IN CONST EFI_GUID *Guid, - IN VOID *Table, - IN UINTN TableSize + IN CONST EFI_GUID *Guid, + IN VOID *Table, + IN UINTN TableSize ); /** @@ -275,10 +275,10 @@ SmmInstallConfigurationTable ( EFI_STATUS EFIAPI SmmInstallProtocolInterface ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface ); /** @@ -300,10 +300,10 @@ SmmInstallProtocolInterface ( EFI_STATUS EFIAPI SmmAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, - OUT EFI_PHYSICAL_ADDRESS *Memory + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, + OUT EFI_PHYSICAL_ADDRESS *Memory ); /** @@ -326,11 +326,11 @@ SmmAllocatePages ( EFI_STATUS EFIAPI SmmInternalAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, - OUT EFI_PHYSICAL_ADDRESS *Memory, - IN BOOLEAN NeedGuard + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, + OUT EFI_PHYSICAL_ADDRESS *Memory, + IN BOOLEAN NeedGuard ); /** @@ -347,8 +347,8 @@ SmmInternalAllocatePages ( EFI_STATUS EFIAPI SmmFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -367,9 +367,9 @@ SmmFreePages ( EFI_STATUS EFIAPI SmmInternalFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages, - IN BOOLEAN IsGuarded + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages, + IN BOOLEAN IsGuarded ); /** @@ -388,9 +388,9 @@ SmmInternalFreePages ( EFI_STATUS EFIAPI SmmAllocatePool ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN Size, - OUT VOID **Buffer + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer ); /** @@ -409,9 +409,9 @@ SmmAllocatePool ( EFI_STATUS EFIAPI SmmInternalAllocatePool ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN Size, - OUT VOID **Buffer + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer ); /** @@ -426,7 +426,7 @@ SmmInternalAllocatePool ( EFI_STATUS EFIAPI SmmFreePool ( - IN VOID *Buffer + IN VOID *Buffer ); /** @@ -441,7 +441,7 @@ SmmFreePool ( EFI_STATUS EFIAPI SmmInternalFreePool ( - IN VOID *Buffer + IN VOID *Buffer ); /** @@ -463,11 +463,11 @@ SmmInternalFreePool ( **/ EFI_STATUS SmmInstallProtocolInterfaceNotify ( - IN OUT EFI_HANDLE *UserHandle, - IN EFI_GUID *Protocol, - IN EFI_INTERFACE_TYPE InterfaceType, - IN VOID *Interface, - IN BOOLEAN Notify + IN OUT EFI_HANDLE *UserHandle, + IN EFI_GUID *Protocol, + IN EFI_INTERFACE_TYPE InterfaceType, + IN VOID *Interface, + IN BOOLEAN Notify ); /** @@ -486,9 +486,9 @@ SmmInstallProtocolInterfaceNotify ( EFI_STATUS EFIAPI SmmUninstallProtocolInterface ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); /** @@ -505,9 +505,9 @@ SmmUninstallProtocolInterface ( EFI_STATUS EFIAPI SmmHandleProtocol ( - IN EFI_HANDLE UserHandle, - IN EFI_GUID *Protocol, - OUT VOID **Interface + IN EFI_HANDLE UserHandle, + IN EFI_GUID *Protocol, + OUT VOID **Interface ); /** @@ -526,9 +526,9 @@ SmmHandleProtocol ( EFI_STATUS EFIAPI SmmRegisterProtocolNotify ( - IN CONST EFI_GUID *Protocol, - IN EFI_SMM_NOTIFY_FN Function, - OUT VOID **Registration + IN CONST EFI_GUID *Protocol, + IN EFI_SMM_NOTIFY_FN Function, + OUT VOID **Registration ); /** @@ -552,11 +552,11 @@ SmmRegisterProtocolNotify ( EFI_STATUS EFIAPI SmmLocateHandle ( - IN EFI_LOCATE_SEARCH_TYPE SearchType, - IN EFI_GUID *Protocol OPTIONAL, - IN VOID *SearchKey OPTIONAL, - IN OUT UINTN *BufferSize, - OUT EFI_HANDLE *Buffer + IN EFI_LOCATE_SEARCH_TYPE SearchType, + IN EFI_GUID *Protocol OPTIONAL, + IN VOID *SearchKey OPTIONAL, + IN OUT UINTN *BufferSize, + OUT EFI_HANDLE *Buffer ); /** @@ -632,10 +632,10 @@ SmmLocateHandleBuffer ( EFI_STATUS EFIAPI SmiManage ( - IN CONST EFI_GUID *HandlerType, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN CONST EFI_GUID *HandlerType, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -652,9 +652,9 @@ SmiManage ( EFI_STATUS EFIAPI SmiHandlerRegister ( - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN CONST EFI_GUID *HandlerType OPTIONAL, - OUT EFI_HANDLE *DispatchHandle + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN CONST EFI_GUID *HandlerType OPTIONAL, + OUT EFI_HANDLE *DispatchHandle ); /** @@ -669,7 +669,7 @@ SmiHandlerRegister ( EFI_STATUS EFIAPI SmiHandlerUnRegister ( - IN EFI_HANDLE DispatchHandle + IN EFI_HANDLE DispatchHandle ); /** @@ -688,10 +688,10 @@ SmiHandlerUnRegister ( EFI_STATUS EFIAPI SmmDriverDispatchHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -710,10 +710,10 @@ SmmDriverDispatchHandler ( EFI_STATUS EFIAPI SmmLegacyBootHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -732,10 +732,10 @@ SmmLegacyBootHandler ( EFI_STATUS EFIAPI SmmReadyToLockHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -754,10 +754,10 @@ SmmReadyToLockHandler ( EFI_STATUS EFIAPI SmmEndOfDxeHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -776,10 +776,10 @@ SmmEndOfDxeHandler ( EFI_STATUS EFIAPI SmmExitBootServicesHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -798,10 +798,10 @@ SmmExitBootServicesHandler ( EFI_STATUS EFIAPI SmmReadyToBootHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ); /** @@ -865,15 +865,15 @@ SmmEndOfS3ResumeHandler ( EFI_STATUS EFIAPI SmmEfiNotAvailableYetArg5 ( - UINTN Arg1, - UINTN Arg2, - UINTN Arg3, - UINTN Arg4, - UINTN Arg5 + UINTN Arg1, + UINTN Arg2, + UINTN Arg3, + UINTN Arg4, + UINTN Arg5 ); // -//Functions used during debug builds +// Functions used during debug builds // /** @@ -897,10 +897,10 @@ SmmDisplayDiscoveredNotDispatched ( **/ VOID SmmAddMemoryRegion ( - IN EFI_PHYSICAL_ADDRESS MemBase, - IN UINT64 MemLength, - IN EFI_MEMORY_TYPE Type, - IN UINT64 Attributes + IN EFI_PHYSICAL_ADDRESS MemBase, + IN UINT64 MemLength, + IN EFI_MEMORY_TYPE Type, + IN UINT64 Attributes ); /** @@ -914,8 +914,8 @@ SmmAddMemoryRegion ( **/ PROTOCOL_ENTRY * SmmFindProtocolEntry ( - IN EFI_GUID *Protocol, - IN BOOLEAN Create + IN EFI_GUID *Protocol, + IN BOOLEAN Create ); /** @@ -926,7 +926,7 @@ SmmFindProtocolEntry ( **/ VOID SmmNotifyProtocol ( - IN PROTOCOL_INTERFACE *Prot + IN PROTOCOL_INTERFACE *Prot ); /** @@ -943,9 +943,9 @@ SmmNotifyProtocol ( **/ PROTOCOL_INTERFACE * SmmFindProtocolInterface ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); /** @@ -960,9 +960,9 @@ SmmFindProtocolInterface ( **/ PROTOCOL_INTERFACE * SmmRemoveInterfaceFromProtocol ( - IN IHANDLE *Handle, - IN EFI_GUID *Protocol, - IN VOID *Interface + IN IHANDLE *Handle, + IN EFI_GUID *Protocol, + IN VOID *Interface ); /** @@ -979,7 +979,7 @@ SmmRemoveInterfaceFromProtocol ( **/ BOOLEAN SmmIsSchedulable ( - IN EFI_SMM_DRIVER_ENTRY *DriverEntry + IN EFI_SMM_DRIVER_ENTRY *DriverEntry ); // @@ -1018,8 +1018,8 @@ SmramProfileInstallProtocol ( **/ EFI_STATUS RegisterSmramProfileImage ( - IN EFI_SMM_DRIVER_ENTRY *DriverEntry, - IN BOOLEAN RegisterToDxe + IN EFI_SMM_DRIVER_ENTRY *DriverEntry, + IN BOOLEAN RegisterToDxe ); /** @@ -1036,8 +1036,8 @@ RegisterSmramProfileImage ( **/ EFI_STATUS UnregisterSmramProfileImage ( - IN EFI_SMM_DRIVER_ENTRY *DriverEntry, - IN BOOLEAN UnregisterToDxe + IN EFI_SMM_DRIVER_ENTRY *DriverEntry, + IN BOOLEAN UnregisterToDxe ); /** @@ -1171,12 +1171,12 @@ SmmCoreInitializeSmiHandlerProfile ( EFI_STATUS EFIAPI SmiHandlerProfileRegisterHandler ( - IN SMI_HANDLER_PROFILE_PROTOCOL *This, - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN PHYSICAL_ADDRESS CallerAddress, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN SMI_HANDLER_PROFILE_PROTOCOL *This, + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN PHYSICAL_ADDRESS CallerAddress, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ); /** @@ -1199,17 +1199,17 @@ SmiHandlerProfileRegisterHandler ( EFI_STATUS EFIAPI SmiHandlerProfileUnregisterHandler ( - IN SMI_HANDLER_PROFILE_PROTOCOL *This, - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN SMI_HANDLER_PROFILE_PROTOCOL *This, + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ); -extern UINTN mFullSmramRangeCount; -extern EFI_SMRAM_DESCRIPTOR *mFullSmramRanges; +extern UINTN mFullSmramRangeCount; +extern EFI_SMRAM_DESCRIPTOR *mFullSmramRanges; -extern EFI_SMM_DRIVER_ENTRY *mSmmCoreDriverEntry; +extern EFI_SMM_DRIVER_ENTRY *mSmmCoreDriverEntry; extern EFI_LOADED_IMAGE_PROTOCOL *mSmmCoreLoadedImage; @@ -1218,8 +1218,8 @@ extern EFI_LOADED_IMAGE_PROTOCOL *mSmmCoreLoadedImage; // typedef struct { - LIST_ENTRY Link; - UINTN NumberOfPages; + LIST_ENTRY Link; + UINTN NumberOfPages; } FREE_PAGE_LIST; extern LIST_ENTRY mSmmMemoryMap; @@ -1245,31 +1245,31 @@ extern LIST_ENTRY mSmmMemoryMap; // #define MAX_POOL_INDEX (MAX_POOL_SHIFT - MIN_POOL_SHIFT + 1) -#define POOL_HEAD_SIGNATURE SIGNATURE_32('s','p','h','d') +#define POOL_HEAD_SIGNATURE SIGNATURE_32('s','p','h','d') typedef struct { - UINT32 Signature; - BOOLEAN Available; - EFI_MEMORY_TYPE Type; - UINTN Size; + UINT32 Signature; + BOOLEAN Available; + EFI_MEMORY_TYPE Type; + UINTN Size; } POOL_HEADER; -#define POOL_TAIL_SIGNATURE SIGNATURE_32('s','p','t','l') +#define POOL_TAIL_SIGNATURE SIGNATURE_32('s','p','t','l') typedef struct { - UINT32 Signature; - UINT32 Reserved; - UINTN Size; + UINT32 Signature; + UINT32 Reserved; + UINTN Size; } POOL_TAIL; -#define POOL_OVERHEAD (sizeof(POOL_HEADER) + sizeof(POOL_TAIL)) +#define POOL_OVERHEAD (sizeof(POOL_HEADER) + sizeof(POOL_TAIL)) #define HEAD_TO_TAIL(a) \ ((POOL_TAIL *) (((CHAR8 *) (a)) + (a)->Size - sizeof(POOL_TAIL))); typedef struct { - POOL_HEADER Header; - LIST_ENTRY Link; + POOL_HEADER Header; + LIST_ENTRY Link; } FREE_POOL_HEADER; typedef enum { @@ -1292,9 +1292,9 @@ extern LIST_ENTRY mSmmPoolLists[SmmPoolTypeMax][MAX_POOL_INDEX]; **/ UINTN InternalAllocPagesOnOneNode ( - IN OUT FREE_PAGE_LIST *Pages, - IN UINTN NumberOfPages, - IN UINTN MaxAddress + IN OUT FREE_PAGE_LIST *Pages, + IN UINTN NumberOfPages, + IN UINTN MaxAddress ); /** diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmCorePrivateData.h b/MdeModulePkg/Core/PiSmmCore/PiSmmCorePrivateData.h index 28f95d9b02..d8fe2dd9b9 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmCorePrivateData.h +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmCorePrivateData.h @@ -42,26 +42,26 @@ /// thos structure. /// typedef struct { - UINTN Signature; + UINTN Signature; /// /// The ImageHandle passed into the entry point of the SMM IPL. This ImageHandle /// is used by the SMM Core to fill in the ParentImageHandle field of the Loaded /// Image Protocol for each SMM Driver that is dispatched by the SMM Core. /// - EFI_HANDLE SmmIplImageHandle; + EFI_HANDLE SmmIplImageHandle; /// /// The number of SMRAM ranges passed from the SMM IPL to the SMM Core. The SMM /// Core uses these ranges of SMRAM to initialize the SMM Core memory manager. /// - UINTN SmramRangeCount; + UINTN SmramRangeCount; /// /// A table of SMRAM ranges passed from the SMM IPL to the SMM Core. The SMM /// Core uses these ranges of SMRAM to initialize the SMM Core memory manager. /// - EFI_SMRAM_DESCRIPTOR *SmramRanges; + EFI_SMRAM_DESCRIPTOR *SmramRanges; /// /// The SMM Foundation Entry Point. The SMM Core fills in this field when the @@ -72,48 +72,48 @@ typedef struct { /// the SMM Foundation Entry Point as soon as the SMM Configuration Protocol is /// available. /// - EFI_SMM_ENTRY_POINT SmmEntryPoint; + EFI_SMM_ENTRY_POINT SmmEntryPoint; /// /// Boolean flag set to TRUE while an SMI is being processed by the SMM Core. /// - BOOLEAN SmmEntryPointRegistered; + BOOLEAN SmmEntryPointRegistered; /// /// Boolean flag set to TRUE while an SMI is being processed by the SMM Core. /// - BOOLEAN InSmm; + BOOLEAN InSmm; /// /// This field is set by the SMM Core then the SMM Core is initialized. This field is /// used by the SMM Base 2 Protocol and SMM Communication Protocol implementations in /// the SMM IPL. /// - EFI_SMM_SYSTEM_TABLE2 *Smst; + EFI_SMM_SYSTEM_TABLE2 *Smst; /// /// This field is used by the SMM Communication Protocol to pass a buffer into /// a software SMI handler and for the software SMI handler to pass a buffer back to /// the caller of the SMM Communication Protocol. /// - VOID *CommunicationBuffer; + VOID *CommunicationBuffer; /// /// This field is used by the SMM Communication Protocol to pass the size of a buffer, /// in bytes, into a software SMI handler and for the software SMI handler to pass the /// size, in bytes, of a buffer back to the caller of the SMM Communication Protocol. /// - UINTN BufferSize; + UINTN BufferSize; /// /// This field is used by the SMM Communication Protocol to pass the return status from /// a software SMI handler back to the caller of the SMM Communication Protocol. /// - EFI_STATUS ReturnStatus; + EFI_STATUS ReturnStatus; - EFI_PHYSICAL_ADDRESS PiSmmCoreImageBase; - UINT64 PiSmmCoreImageSize; - EFI_PHYSICAL_ADDRESS PiSmmCoreEntryPoint; + EFI_PHYSICAL_ADDRESS PiSmmCoreImageBase; + UINT64 PiSmmCoreImageSize; + EFI_PHYSICAL_ADDRESS PiSmmCoreEntryPoint; } SMM_CORE_PRIVATE_DATA; #endif diff --git a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c index e8e25c6c91..4f00cebaf5 100644 --- a/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c +++ b/MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c @@ -140,10 +140,10 @@ SmmCommunicationCommunicate ( EFI_STATUS EFIAPI SmmCommunicationMmCommunicate2 ( - IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This, - IN OUT VOID *CommBufferPhysical, - IN OUT VOID *CommBufferVirtual, - IN OUT UINTN *CommSize OPTIONAL + IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This, + IN OUT VOID *CommBufferPhysical, + IN OUT VOID *CommBufferVirtual, + IN OUT UINTN *CommSize OPTIONAL ); /** @@ -239,13 +239,13 @@ SmmIplSetVirtualAddressNotify ( // notifications required by the SMM IPL // typedef struct { - BOOLEAN Protocol; - BOOLEAN CloseOnLock; - EFI_GUID *Guid; - EFI_EVENT_NOTIFY NotifyFunction; - VOID *NotifyContext; - EFI_TPL NotifyTpl; - EFI_EVENT Event; + BOOLEAN Protocol; + BOOLEAN CloseOnLock; + EFI_GUID *Guid; + EFI_EVENT_NOTIFY NotifyFunction; + VOID *NotifyContext; + EFI_TPL NotifyTpl; + EFI_EVENT Event; } SMM_IPL_EVENT_NOTIFICATION; // @@ -309,8 +309,8 @@ BOOLEAN mEndOfDxe = FALSE; EFI_PHYSICAL_ADDRESS mSmramCacheBase; UINT64 mSmramCacheSize; -EFI_SMM_COMMUNICATE_HEADER mCommunicateHeader; -EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *mLMFAConfigurationTable = NULL; +EFI_SMM_COMMUNICATE_HEADER mCommunicateHeader; +EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *mLMFAConfigurationTable = NULL; // // Table of Protocol notification and GUIDed Event notifications that the SMM IPL requires @@ -389,15 +389,15 @@ SMM_IPL_EVENT_NOTIFICATION mSmmIplEvents[] = { **/ VOID GetSmramCacheRange ( - IN EFI_SMRAM_DESCRIPTOR *SmramRange, - OUT EFI_PHYSICAL_ADDRESS *SmramCacheBase, - OUT UINT64 *SmramCacheSize + IN EFI_SMRAM_DESCRIPTOR *SmramRange, + OUT EFI_PHYSICAL_ADDRESS *SmramCacheBase, + OUT UINT64 *SmramCacheSize ) { - UINTN Index; - EFI_PHYSICAL_ADDRESS RangeCpuStart; - UINT64 RangePhysicalSize; - BOOLEAN FoundAjacentRange; + UINTN Index; + EFI_PHYSICAL_ADDRESS RangeCpuStart; + UINT64 RangePhysicalSize; + BOOLEAN FoundAjacentRange; *SmramCacheBase = SmramRange->CpuStart; *SmramCacheSize = SmramRange->PhysicalSize; @@ -407,17 +407,16 @@ GetSmramCacheRange ( for (Index = 0; Index < gSmmCorePrivate->SmramRangeCount; Index++) { RangeCpuStart = gSmmCorePrivate->SmramRanges[Index].CpuStart; RangePhysicalSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize; - if (RangeCpuStart < *SmramCacheBase && *SmramCacheBase == (RangeCpuStart + RangePhysicalSize)) { + if ((RangeCpuStart < *SmramCacheBase) && (*SmramCacheBase == (RangeCpuStart + RangePhysicalSize))) { *SmramCacheBase = RangeCpuStart; *SmramCacheSize += RangePhysicalSize; FoundAjacentRange = TRUE; - } else if ((*SmramCacheBase + *SmramCacheSize) == RangeCpuStart && RangePhysicalSize > 0) { + } else if (((*SmramCacheBase + *SmramCacheSize) == RangeCpuStart) && (RangePhysicalSize > 0)) { *SmramCacheSize += RangePhysicalSize; FoundAjacentRange = TRUE; } } } while (FoundAjacentRange); - } /** @@ -465,7 +464,7 @@ SmmBase2GetSmstLocation ( OUT EFI_SMM_SYSTEM_TABLE2 **Smst ) { - if ((This == NULL) ||(Smst == NULL)) { + if ((This == NULL) || (Smst == NULL)) { return EFI_INVALID_PARAMETER; } @@ -524,7 +523,7 @@ SmmCommunicationCommunicate ( return EFI_INVALID_PARAMETER; } - CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer; + CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)CommBuffer; if (CommSize == NULL) { TempCommSize = OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data) + CommunicateHeader->MessageLength; @@ -562,6 +561,7 @@ SmmCommunicationCommunicate ( if (CommSize != NULL) { *CommSize = gSmmCorePrivate->BufferSize; } + return gSmmCorePrivate->ReturnStatus; } @@ -571,7 +571,7 @@ SmmCommunicationCommunicate ( // has been called, then a direct invocation of the Software SMI is not allowed, // so return EFI_INVALID_PARAMETER. // - if (EfiGoneVirtual()) { + if (EfiGoneVirtual ()) { return EFI_INVALID_PARAMETER; } @@ -585,19 +585,19 @@ SmmCommunicationCommunicate ( // // Save current InSmm state and set InSmm state to TRUE // - OldInSmm = gSmmCorePrivate->InSmm; + OldInSmm = gSmmCorePrivate->InSmm; gSmmCorePrivate->InSmm = TRUE; // // Before SetVirtualAddressMap(), we are in SMM or SMRAM is open and unlocked, call SmiManage() directly. // TempCommSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); - Status = gSmmCorePrivate->Smst->SmiManage ( - &CommunicateHeader->HeaderGuid, - NULL, - CommunicateHeader->Data, - &TempCommSize - ); + Status = gSmmCorePrivate->Smst->SmiManage ( + &CommunicateHeader->HeaderGuid, + NULL, + CommunicateHeader->Data, + &TempCommSize + ); TempCommSize += OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data); if (CommSize != NULL) { *CommSize = TempCommSize; @@ -638,15 +638,17 @@ SmmCommunicationCommunicate ( EFI_STATUS EFIAPI SmmCommunicationMmCommunicate2 ( - IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This, - IN OUT VOID *CommBufferPhysical, - IN OUT VOID *CommBufferVirtual, - IN OUT UINTN *CommSize OPTIONAL + IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This, + IN OUT VOID *CommBufferPhysical, + IN OUT VOID *CommBufferVirtual, + IN OUT UINTN *CommSize OPTIONAL ) { - return SmmCommunicationCommunicate (&mSmmCommunication, - CommBufferPhysical, - CommSize); + return SmmCommunicationCommunicate ( + &mSmmCommunication, + CommBufferPhysical, + CommSize + ); } /** @@ -663,14 +665,14 @@ SmmIplGuidedEventNotify ( IN VOID *Context ) { - UINTN Size; + UINTN Size; // // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure // CopyGuid (&mCommunicateHeader.HeaderGuid, (EFI_GUID *)Context); mCommunicateHeader.MessageLength = 1; - mCommunicateHeader.Data[0] = 0; + mCommunicateHeader.Data[0] = 0; // // Generate the Software SMI and return the result @@ -710,8 +712,8 @@ SmmIplDxeDispatchEventNotify ( IN VOID *Context ) { - UINTN Size; - EFI_STATUS Status; + UINTN Size; + EFI_STATUS Status; // // Keep calling the SMM Core Dispatcher until there is no request to restart it. @@ -724,7 +726,7 @@ SmmIplDxeDispatchEventNotify ( // CopyGuid (&mCommunicateHeader.HeaderGuid, (EFI_GUID *)Context); mCommunicateHeader.MessageLength = 1; - mCommunicateHeader.Data[0] = 0; + mCommunicateHeader.Data[0] = 0; // // Generate the Software SMI and return the result @@ -911,89 +913,94 @@ SmmIplSetVirtualAddressNotify ( @retval EFI_NOT_FOUND The image has no assigned fixed loading address. **/ EFI_STATUS -GetPeCoffImageFixLoadingAssignedAddress( +GetPeCoffImageFixLoadingAssignedAddress ( IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext ) { - UINTN SectionHeaderOffset; - EFI_STATUS Status; - EFI_IMAGE_SECTION_HEADER SectionHeader; - EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; - EFI_PHYSICAL_ADDRESS FixLoadingAddress; - UINT16 Index; - UINTN Size; - UINT16 NumberOfSections; - EFI_PHYSICAL_ADDRESS SmramBase; - UINT64 SmmCodeSize; - UINT64 ValueInSectionHeader; - // - // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber - // - SmmCodeSize = EFI_PAGES_TO_SIZE (PcdGet32(PcdLoadFixAddressSmmCodePageNumber)); - - FixLoadingAddress = 0; - Status = EFI_NOT_FOUND; - SmramBase = mLMFAConfigurationTable->SmramBase; - // - // Get PeHeader pointer - // - ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset); - SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + - sizeof (UINT32) + - sizeof (EFI_IMAGE_FILE_HEADER) + - ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; - NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; - - // - // Get base address from the first section header that doesn't point to code section. - // - for (Index = 0; Index < NumberOfSections; Index++) { - // - // Read section header from file - // - Size = sizeof (EFI_IMAGE_SECTION_HEADER); - Status = ImageContext->ImageRead ( - ImageContext->Handle, - SectionHeaderOffset, - &Size, - &SectionHeader - ); - if (EFI_ERROR (Status)) { - return Status; - } - - Status = EFI_NOT_FOUND; - - if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { - // - // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the - // first section header that doesn't point to code section in image header. And there is an assumption that when the - // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers - // fields should NOT be Zero, or else, these 2 fields should be set to Zero - // - ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations); - if (ValueInSectionHeader != 0) { - // - // Found first section header that doesn't point to code section in which build tool saves the - // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields - // - FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(SmramBase + (INT64)ValueInSectionHeader); - - if (SmramBase + SmmCodeSize > FixLoadingAddress && SmramBase <= FixLoadingAddress) { - // - // The assigned address is valid. Return the specified loading address - // - ImageContext->ImageAddress = FixLoadingAddress; - Status = EFI_SUCCESS; - } - } - break; - } - SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); - } - DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoadingAddress, Status)); - return Status; + UINTN SectionHeaderOffset; + EFI_STATUS Status; + EFI_IMAGE_SECTION_HEADER SectionHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr; + EFI_PHYSICAL_ADDRESS FixLoadingAddress; + UINT16 Index; + UINTN Size; + UINT16 NumberOfSections; + EFI_PHYSICAL_ADDRESS SmramBase; + UINT64 SmmCodeSize; + UINT64 ValueInSectionHeader; + + // + // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber + // + SmmCodeSize = EFI_PAGES_TO_SIZE (PcdGet32 (PcdLoadFixAddressSmmCodePageNumber)); + + FixLoadingAddress = 0; + Status = EFI_NOT_FOUND; + SmramBase = mLMFAConfigurationTable->SmramBase; + // + // Get PeHeader pointer + // + ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8 *)ImageContext->Handle + ImageContext->PeCoffHeaderOffset); + SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + + sizeof (UINT32) + + sizeof (EFI_IMAGE_FILE_HEADER) + + ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader; + NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections; + + // + // Get base address from the first section header that doesn't point to code section. + // + for (Index = 0; Index < NumberOfSections; Index++) { + // + // Read section header from file + // + Size = sizeof (EFI_IMAGE_SECTION_HEADER); + Status = ImageContext->ImageRead ( + ImageContext->Handle, + SectionHeaderOffset, + &Size, + &SectionHeader + ); + if (EFI_ERROR (Status)) { + return Status; + } + + Status = EFI_NOT_FOUND; + + if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) { + // + // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the + // first section header that doesn't point to code section in image header. And there is an assumption that when the + // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers + // fields should NOT be Zero, or else, these 2 fields should be set to Zero + // + ValueInSectionHeader = ReadUnaligned64 ((UINT64 *)&SectionHeader.PointerToRelocations); + if (ValueInSectionHeader != 0) { + // + // Found first section header that doesn't point to code section in which build tool saves the + // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields + // + FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(SmramBase + (INT64)ValueInSectionHeader); + + if ((SmramBase + SmmCodeSize > FixLoadingAddress) && (SmramBase <= FixLoadingAddress)) { + // + // The assigned address is valid. Return the specified loading address + // + ImageContext->ImageAddress = FixLoadingAddress; + Status = EFI_SUCCESS; + } + } + + break; + } + + SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER); + } + + DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoadingAddress, Status)); + return Status; } + /** Load the SMM Core image into SMRAM and executes the SMM Core from SMRAM. @@ -1009,9 +1016,9 @@ GetPeCoffImageFixLoadingAssignedAddress( **/ EFI_STATUS ExecuteSmmCoreFromSmram ( - IN OUT EFI_SMRAM_DESCRIPTOR *SmramRange, - IN OUT EFI_SMRAM_DESCRIPTOR *SmramRangeSmmCore, - IN VOID *Context + IN OUT EFI_SMRAM_DESCRIPTOR *SmramRange, + IN OUT EFI_SMRAM_DESCRIPTOR *SmramRangeSmmCore, + IN VOID *Context ) { EFI_STATUS Status; @@ -1049,11 +1056,12 @@ ExecuteSmmCoreFromSmram ( if (EFI_ERROR (Status)) { return Status; } + // // if Loading module at Fixed Address feature is enabled, the SMM core driver will be loaded to // the address assigned by build tool. // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { // // Get the fixed loading address assigned by Build tool // @@ -1066,23 +1074,23 @@ ExecuteSmmCoreFromSmram ( // // Reserved Smram Region for SmmCore is not used, and remove it from SmramRangeCount. // - gSmmCorePrivate->SmramRangeCount --; + gSmmCorePrivate->SmramRangeCount--; } else { DEBUG ((DEBUG_INFO, "LOADING MODULE FIXED ERROR: Loading module at fixed address at address failed\n")); // // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR // specified by SmramRange // - PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); + PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0); ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount)); - SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount); - SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize; + SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount); + SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize; SmramRangeSmmCore->PhysicalStart = SmramRange->PhysicalStart + SmramRange->PhysicalSize; - SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED; - SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount); + SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED; + SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount); // // Align buffer on section boundary @@ -1094,16 +1102,16 @@ ExecuteSmmCoreFromSmram ( // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR // specified by SmramRange // - PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); + PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment); ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0); ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount)); - SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount); - SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize; + SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount); + SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize; SmramRangeSmmCore->PhysicalStart = SmramRange->PhysicalStart + SmramRange->PhysicalSize; - SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED; - SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount); + SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED; + SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount); // // Align buffer on section boundary @@ -1150,7 +1158,7 @@ ExecuteSmmCoreFromSmram ( // Execute image // EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)ImageContext.EntryPoint; - Status = EntryPoint ((EFI_HANDLE)Context, gST); + Status = EntryPoint ((EFI_HANDLE)Context, gST); } } @@ -1188,14 +1196,15 @@ SmmSplitSmramEntry ( IN OUT UINTN *FinalRangeCount ) { - UINT64 RangeToCompareEnd; - UINT64 ReservedRangeToCompareEnd; + UINT64 RangeToCompareEnd; + UINT64 ReservedRangeToCompareEnd; RangeToCompareEnd = RangeToCompare->CpuStart + RangeToCompare->PhysicalSize; ReservedRangeToCompareEnd = ReservedRangeToCompare->SmramReservedStart + ReservedRangeToCompare->SmramReservedSize; if ((RangeToCompare->CpuStart >= ReservedRangeToCompare->SmramReservedStart) && - (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) { + (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) + { if (RangeToCompareEnd < ReservedRangeToCompareEnd) { // // RangeToCompare ReservedRangeToCompare @@ -1222,14 +1231,14 @@ SmmSplitSmramEntry ( FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart; FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED; FinalRanges[*FinalRangeCount].PhysicalSize = RangeToCompare->PhysicalSize; - *FinalRangeCount += 1; - RangeToCompare->PhysicalSize = 0; + *FinalRangeCount += 1; + RangeToCompare->PhysicalSize = 0; // // 3. Update ReservedRanges[*ReservedRangeCount] and increment *ReservedRangeCount. // ReservedRanges[*ReservedRangeCount].SmramReservedStart = FinalRanges[*FinalRangeCount - 1].CpuStart + FinalRanges[*FinalRangeCount - 1].PhysicalSize; ReservedRanges[*ReservedRangeCount].SmramReservedSize = ReservedRangeToCompareEnd - RangeToCompareEnd; - *ReservedRangeCount += 1; + *ReservedRangeCount += 1; } else { // // RangeToCompare ReservedRangeToCompare @@ -1255,7 +1264,7 @@ SmmSplitSmramEntry ( FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart; FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED; FinalRanges[*FinalRangeCount].PhysicalSize = ReservedRangeToCompareEnd - RangeToCompare->CpuStart; - *FinalRangeCount += 1; + *FinalRangeCount += 1; // // 3. Update RangeToCompare. // @@ -1264,7 +1273,8 @@ SmmSplitSmramEntry ( RangeToCompare->PhysicalSize -= FinalRanges[*FinalRangeCount - 1].PhysicalSize; } } else if ((ReservedRangeToCompare->SmramReservedStart >= RangeToCompare->CpuStart) && - (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) { + (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) + { if (ReservedRangeToCompareEnd < RangeToCompareEnd) { // // RangeToCompare ReservedRangeToCompare @@ -1291,8 +1301,8 @@ SmmSplitSmramEntry ( FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart + RangeToCompare->PhysicalSize; FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED; FinalRanges[*FinalRangeCount].PhysicalSize = ReservedRangeToCompare->SmramReservedSize; - *FinalRangeCount += 1; - ReservedRangeToCompare->SmramReservedSize = 0; + *FinalRangeCount += 1; + ReservedRangeToCompare->SmramReservedSize = 0; // // 3. Update Ranges[*RangeCount] and increment *RangeCount. // @@ -1300,7 +1310,7 @@ SmmSplitSmramEntry ( Ranges[*RangeCount].PhysicalStart = FinalRanges[*FinalRangeCount - 1].PhysicalStart + FinalRanges[*FinalRangeCount - 1].PhysicalSize; Ranges[*RangeCount].RegionState = RangeToCompare->RegionState; Ranges[*RangeCount].PhysicalSize = RangeToCompareEnd - ReservedRangeToCompareEnd; - *RangeCount += 1; + *RangeCount += 1; } else { // // RangeToCompare ReservedRangeToCompare @@ -1327,7 +1337,7 @@ SmmSplitSmramEntry ( FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart + RangeToCompare->PhysicalSize; FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED; FinalRanges[*FinalRangeCount].PhysicalSize = RangeToCompareEnd - ReservedRangeToCompare->SmramReservedStart; - *FinalRangeCount += 1; + *FinalRangeCount += 1; // // 3. Update ReservedRangeToCompare. // @@ -1353,19 +1363,22 @@ SmmIsSmramOverlap ( IN EFI_SMM_RESERVED_SMRAM_REGION *ReservedRangeToCompare ) { - UINT64 RangeToCompareEnd; - UINT64 ReservedRangeToCompareEnd; + UINT64 RangeToCompareEnd; + UINT64 ReservedRangeToCompareEnd; RangeToCompareEnd = RangeToCompare->CpuStart + RangeToCompare->PhysicalSize; ReservedRangeToCompareEnd = ReservedRangeToCompare->SmramReservedStart + ReservedRangeToCompare->SmramReservedSize; if ((RangeToCompare->CpuStart >= ReservedRangeToCompare->SmramReservedStart) && - (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) { + (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) + { return TRUE; } else if ((ReservedRangeToCompare->SmramReservedStart >= RangeToCompare->CpuStart) && - (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) { + (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) + { return TRUE; } + return FALSE; } @@ -1383,35 +1396,35 @@ SmmIsSmramOverlap ( **/ EFI_SMRAM_DESCRIPTOR * GetFullSmramRanges ( - OUT UINTN *FullSmramRangeCount + OUT UINTN *FullSmramRangeCount ) { - EFI_STATUS Status; - EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration; - UINTN Size; - UINTN Index; - UINTN Index2; - EFI_SMRAM_DESCRIPTOR *FullSmramRanges; - UINTN TempSmramRangeCount; - UINTN AdditionSmramRangeCount; - EFI_SMRAM_DESCRIPTOR *TempSmramRanges; - UINTN SmramRangeCount; - EFI_SMRAM_DESCRIPTOR *SmramRanges; - UINTN SmramReservedCount; - EFI_SMM_RESERVED_SMRAM_REGION *SmramReservedRanges; - UINTN MaxCount; - BOOLEAN Rescan; + EFI_STATUS Status; + EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration; + UINTN Size; + UINTN Index; + UINTN Index2; + EFI_SMRAM_DESCRIPTOR *FullSmramRanges; + UINTN TempSmramRangeCount; + UINTN AdditionSmramRangeCount; + EFI_SMRAM_DESCRIPTOR *TempSmramRanges; + UINTN SmramRangeCount; + EFI_SMRAM_DESCRIPTOR *SmramRanges; + UINTN SmramReservedCount; + EFI_SMM_RESERVED_SMRAM_REGION *SmramReservedRanges; + UINTN MaxCount; + BOOLEAN Rescan; // // Get SMM Configuration Protocol if it is present. // SmmConfiguration = NULL; - Status = gBS->LocateProtocol (&gEfiSmmConfigurationProtocolGuid, NULL, (VOID **) &SmmConfiguration); + Status = gBS->LocateProtocol (&gEfiSmmConfigurationProtocolGuid, NULL, (VOID **)&SmmConfiguration); // // Get SMRAM information. // - Size = 0; + Size = 0; Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, NULL); ASSERT (Status == EFI_BUFFER_TOO_SMALL); @@ -1431,7 +1444,7 @@ GetFullSmramRanges ( // Reserve one entry for SMM Core in the full SMRAM ranges. // AdditionSmramRangeCount = 1; - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { // // Reserve two entries for all SMM drivers and SMM Core in the full SMRAM ranges. // @@ -1443,8 +1456,8 @@ GetFullSmramRanges ( // No reserved SMRAM entry from SMM Configuration Protocol. // *FullSmramRangeCount = SmramRangeCount + AdditionSmramRangeCount; - Size = (*FullSmramRangeCount) * sizeof (EFI_SMRAM_DESCRIPTOR); - FullSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocateZeroPool (Size); + Size = (*FullSmramRangeCount) * sizeof (EFI_SMRAM_DESCRIPTOR); + FullSmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocateZeroPool (Size); ASSERT (FullSmramRanges != NULL); Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, FullSmramRanges); @@ -1490,19 +1503,19 @@ GetFullSmramRanges ( // MaxCount = SmramRangeCount + 2 * SmramReservedCount; - Size = MaxCount * sizeof (EFI_SMM_RESERVED_SMRAM_REGION); - SmramReservedRanges = (EFI_SMM_RESERVED_SMRAM_REGION *) AllocatePool (Size); + Size = MaxCount * sizeof (EFI_SMM_RESERVED_SMRAM_REGION); + SmramReservedRanges = (EFI_SMM_RESERVED_SMRAM_REGION *)AllocatePool (Size); ASSERT (SmramReservedRanges != NULL); for (Index = 0; Index < SmramReservedCount; Index++) { CopyMem (&SmramReservedRanges[Index], &SmmConfiguration->SmramReservedRegions[Index], sizeof (EFI_SMM_RESERVED_SMRAM_REGION)); } - Size = MaxCount * sizeof (EFI_SMRAM_DESCRIPTOR); - TempSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size); + Size = MaxCount * sizeof (EFI_SMRAM_DESCRIPTOR); + TempSmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocatePool (Size); ASSERT (TempSmramRanges != NULL); TempSmramRangeCount = 0; - SmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size); + SmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocatePool (Size); ASSERT (SmramRanges != NULL); Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, SmramRanges); ASSERT_EFI_ERROR (Status); @@ -1522,7 +1535,8 @@ GetFullSmramRanges ( if (SmmIsSmramOverlap ( &SmramRanges[Index], &SmramReservedRanges[Index2] - )) { + )) + { // // There is overlap, need to split entry and then rescan. // @@ -1540,6 +1554,7 @@ GetFullSmramRanges ( } } } + if (!Rescan) { // // No any overlap, copy the entry to the temp SMRAM ranges. @@ -1551,6 +1566,7 @@ GetFullSmramRanges ( } } } while (Rescan); + ASSERT (TempSmramRangeCount <= MaxCount); // @@ -1565,16 +1581,19 @@ GetFullSmramRanges ( break; } } + ASSERT (Index < TempSmramRangeCount); for (Index2 = 0; Index2 < TempSmramRangeCount; Index2++) { if ((Index2 != Index) && (TempSmramRanges[Index2].PhysicalSize != 0) && (TempSmramRanges[Index2].CpuStart < TempSmramRanges[Index].CpuStart)) { Index = Index2; } } + CopyMem (&FullSmramRanges[*FullSmramRangeCount], &TempSmramRanges[Index], sizeof (EFI_SMRAM_DESCRIPTOR)); - *FullSmramRangeCount += 1; + *FullSmramRangeCount += 1; TempSmramRanges[Index].PhysicalSize = 0; } while (*FullSmramRangeCount < TempSmramRangeCount); + ASSERT (*FullSmramRangeCount == TempSmramRangeCount); *FullSmramRangeCount += AdditionSmramRangeCount; @@ -1606,15 +1625,15 @@ SmmIplEntry ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - UINTN Index; - UINT64 MaxSize; - VOID *Registration; - UINT64 SmmCodeSize; - EFI_CPU_ARCH_PROTOCOL *CpuArch; - EFI_STATUS SetAttrStatus; - EFI_SMRAM_DESCRIPTOR *SmramRangeSmmDriver; - EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; + EFI_STATUS Status; + UINTN Index; + UINT64 MaxSize; + VOID *Registration; + UINT64 SmmCodeSize; + EFI_CPU_ARCH_PROTOCOL *CpuArch; + EFI_STATUS SetAttrStatus; + EFI_SMRAM_DESCRIPTOR *SmramRangeSmmDriver; + EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc; // // Fill in the image handle of the SMM IPL so the SMM Core can use this as the @@ -1663,7 +1682,7 @@ SmmIplEntry ( if (gSmmCorePrivate->SmramRanges[Index].CpuStart >= BASE_1MB) { if ((gSmmCorePrivate->SmramRanges[Index].CpuStart + gSmmCorePrivate->SmramRanges[Index].PhysicalSize - 1) <= MAX_ADDRESS) { if (gSmmCorePrivate->SmramRanges[Index].PhysicalSize >= MaxSize) { - MaxSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize; + MaxSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize; mCurrentSmramRange = &gSmmCorePrivate->SmramRanges[Index]; } } @@ -1674,7 +1693,9 @@ SmmIplEntry ( // // Print debug message showing SMRAM window that will be used by SMM IPL and SMM Core // - DEBUG ((DEBUG_INFO, "SMM IPL found SMRAM window %p - %p\n", + DEBUG (( + DEBUG_INFO, + "SMM IPL found SMRAM window %p - %p\n", (VOID *)(UINTN)mCurrentSmramRange->CpuStart, (VOID *)(UINTN)(mCurrentSmramRange->CpuStart + mCurrentSmramRange->PhysicalSize - 1) )); @@ -1695,6 +1716,7 @@ SmmIplEntry ( MemDesc.Capabilities | SMRAM_CAPABILITIES ); } + // // If CPU AP is present, attempt to set SMRAM cacheability to WB and clear // all paging attributes. @@ -1702,15 +1724,15 @@ SmmIplEntry ( // is not available here. // CpuArch = NULL; - Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&CpuArch); + Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&CpuArch); if (!EFI_ERROR (Status)) { MemDesc.Attributes &= ~(EFI_CACHE_ATTRIBUTE_MASK | EFI_MEMORY_ATTRIBUTE_MASK); MemDesc.Attributes |= EFI_MEMORY_WB; - Status = gDS->SetMemorySpaceAttributes ( - mSmramCacheBase, - mSmramCacheSize, - MemDesc.Attributes - ); + Status = gDS->SetMemorySpaceAttributes ( + mSmramCacheBase, + mSmramCacheSize, + MemDesc.Attributes + ); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_WARN, "SMM IPL failed to set SMRAM window to EFI_MEMORY_WB\n")); } @@ -1722,17 +1744,18 @@ SmmIplEntry ( ); DEBUG ((DEBUG_INFO, "SMRAM attributes: %016lx\n", MemDesc.Attributes)); ASSERT ((MemDesc.Attributes & EFI_MEMORY_ATTRIBUTE_MASK) == 0); - ); + ); } + // // if Loading module at Fixed Address feature is enabled, save the SMRAM base to Load // Modules At Fixed Address Configuration Table. // - if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) { + if (PcdGet64 (PcdLoadModuleAtFixAddressEnable) != 0) { // // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber // - SmmCodeSize = LShiftU64 (PcdGet32(PcdLoadFixAddressSmmCodePageNumber), EFI_PAGE_SHIFT); + SmmCodeSize = LShiftU64 (PcdGet32 (PcdLoadFixAddressSmmCodePageNumber), EFI_PAGE_SHIFT); // // The SMRAM available memory is assumed to be larger than SmmCodeSize // @@ -1741,10 +1764,10 @@ SmmIplEntry ( // Retrieve Load modules At fixed address configuration table and save the SMRAM base. // Status = EfiGetSystemConfigurationTable ( - &gLoadFixedAddressConfigurationTableGuid, - (VOID **) &mLMFAConfigurationTable - ); - if (!EFI_ERROR (Status) && mLMFAConfigurationTable != NULL) { + &gLoadFixedAddressConfigurationTableGuid, + (VOID **)&mLMFAConfigurationTable + ); + if (!EFI_ERROR (Status) && (mLMFAConfigurationTable != NULL)) { mLMFAConfigurationTable->SmramBase = mCurrentSmramRange->CpuStart; // // Print the SMRAM base @@ -1755,16 +1778,17 @@ SmmIplEntry ( // // Fill the Smram range for all SMM code // - SmramRangeSmmDriver = &gSmmCorePrivate->SmramRanges[gSmmCorePrivate->SmramRangeCount - 2]; + SmramRangeSmmDriver = &gSmmCorePrivate->SmramRanges[gSmmCorePrivate->SmramRangeCount - 2]; SmramRangeSmmDriver->CpuStart = mCurrentSmramRange->CpuStart; SmramRangeSmmDriver->PhysicalStart = mCurrentSmramRange->PhysicalStart; SmramRangeSmmDriver->RegionState = mCurrentSmramRange->RegionState | EFI_ALLOCATED; SmramRangeSmmDriver->PhysicalSize = SmmCodeSize; - mCurrentSmramRange->PhysicalSize -= SmmCodeSize; - mCurrentSmramRange->CpuStart = mCurrentSmramRange->CpuStart + SmmCodeSize; - mCurrentSmramRange->PhysicalStart = mCurrentSmramRange->PhysicalStart + SmmCodeSize; + mCurrentSmramRange->PhysicalSize -= SmmCodeSize; + mCurrentSmramRange->CpuStart = mCurrentSmramRange->CpuStart + SmmCodeSize; + mCurrentSmramRange->PhysicalStart = mCurrentSmramRange->PhysicalStart + SmmCodeSize; } + // // Load SMM Core into SMRAM and execute it from SMRAM // @@ -1783,7 +1807,7 @@ SmmIplEntry ( // Attempt to reset SMRAM cacheability to UC // if (CpuArch != NULL) { - SetAttrStatus = gDS->SetMemorySpaceAttributes( + SetAttrStatus = gDS->SetMemorySpaceAttributes ( mSmramCacheBase, mSmramCacheSize, EFI_MEMORY_UC @@ -1804,7 +1828,7 @@ SmmIplEntry ( // If the SMM Core could not be loaded then close SMRAM window, free allocated // resources, and return an error so SMM IPL will be unloaded. // - if (mCurrentSmramRange == NULL || EFI_ERROR (Status)) { + if ((mCurrentSmramRange == NULL) || EFI_ERROR (Status)) { // // Close all SMRAM ranges // @@ -1829,9 +1853,12 @@ SmmIplEntry ( // Status = gBS->InstallMultipleProtocolInterfaces ( &mSmmIplHandle, - &gEfiSmmBase2ProtocolGuid, &mSmmBase2, - &gEfiSmmCommunicationProtocolGuid, &mSmmCommunication, - &gEfiMmCommunication2ProtocolGuid, &mMmCommunication2, + &gEfiSmmBase2ProtocolGuid, + &mSmmBase2, + &gEfiSmmCommunicationProtocolGuid, + &mSmmCommunication, + &gEfiMmCommunication2ProtocolGuid, + &mMmCommunication2, NULL ); ASSERT_EFI_ERROR (Status); @@ -1846,8 +1873,8 @@ SmmIplEntry ( mSmmIplEvents[Index].NotifyTpl, mSmmIplEvents[Index].NotifyFunction, mSmmIplEvents[Index].NotifyContext, - &Registration - ); + &Registration + ); } else { Status = gBS->CreateEventEx ( EVT_NOTIFY_SIGNAL, diff --git a/MdeModulePkg/Core/PiSmmCore/Pool.c b/MdeModulePkg/Core/PiSmmCore/Pool.c index a503ff51f5..96ebe811c6 100644 --- a/MdeModulePkg/Core/PiSmmCore/Pool.c +++ b/MdeModulePkg/Core/PiSmmCore/Pool.c @@ -13,7 +13,7 @@ LIST_ENTRY mSmmPoolLists[SmmPoolTypeMax][MAX_POOL_INDEX]; // To cache the SMRAM base since when Loading modules At fixed address feature is enabled, // all module is assigned an offset relative the SMRAM base in build time. // -GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS gLoadModuleAtFixAddressSmramBase = 0; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS gLoadModuleAtFixAddressSmramBase = 0; /** Convert a UEFI memory type to SMM pool type. @@ -24,21 +24,20 @@ GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS gLoadModuleAtFixAddres **/ SMM_POOL_TYPE UefiMemoryTypeToSmmPoolType ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { ASSERT ((MemoryType == EfiRuntimeServicesCode) || (MemoryType == EfiRuntimeServicesData)); switch (MemoryType) { - case EfiRuntimeServicesCode: - return SmmPoolTypeCode; - case EfiRuntimeServicesData: - return SmmPoolTypeData; - default: - return SmmPoolTypeMax; + case EfiRuntimeServicesCode: + return SmmPoolTypeCode; + case EfiRuntimeServicesData: + return SmmPoolTypeData; + default: + return SmmPoolTypeMax; } } - /** Called to initialize the memory service. @@ -52,10 +51,10 @@ SmmInitializeMemoryServices ( IN EFI_SMRAM_DESCRIPTOR *SmramRanges ) { - UINTN Index; - EFI_STATUS Status; - UINTN SmmPoolTypeIndex; - EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *LMFAConfigurationTable; + UINTN Index; + EFI_STATUS Status; + UINTN SmmPoolTypeIndex; + EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *LMFAConfigurationTable; // // Initialize Pool list @@ -67,10 +66,10 @@ SmmInitializeMemoryServices ( } Status = EfiGetSystemConfigurationTable ( - &gLoadFixedAddressConfigurationTableGuid, - (VOID **) &LMFAConfigurationTable - ); - if (!EFI_ERROR (Status) && LMFAConfigurationTable != NULL) { + &gLoadFixedAddressConfigurationTableGuid, + (VOID **)&LMFAConfigurationTable + ); + if (!EFI_ERROR (Status) && (LMFAConfigurationTable != NULL)) { gLoadModuleAtFixAddressSmramBase = LMFAConfigurationTable->SmramBase; } @@ -82,6 +81,7 @@ SmmInitializeMemoryServices ( if ((SmramRanges[Index].RegionState & (EFI_ALLOCATED | EFI_NEEDS_TESTING | EFI_NEEDS_ECC_INITIALIZATION)) != 0) { continue; } + SmmAddMemoryRegion ( SmramRanges[Index].CpuStart, SmramRanges[Index].PhysicalSize, @@ -97,6 +97,7 @@ SmmInitializeMemoryServices ( if ((SmramRanges[Index].RegionState & (EFI_ALLOCATED | EFI_NEEDS_TESTING | EFI_NEEDS_ECC_INITIALIZATION)) == 0) { continue; } + SmmAddMemoryRegion ( SmramRanges[Index].CpuStart, SmramRanges[Index].PhysicalSize, @@ -104,7 +105,6 @@ SmmInitializeMemoryServices ( SmramRanges[Index].RegionState ); } - } /** @@ -132,19 +132,24 @@ InternalAllocPoolByIndex ( SMM_POOL_TYPE SmmPoolType; Address = 0; - SmmPoolType = UefiMemoryTypeToSmmPoolType(PoolType); + SmmPoolType = UefiMemoryTypeToSmmPoolType (PoolType); ASSERT (PoolIndex <= MAX_POOL_INDEX); Status = EFI_SUCCESS; - Hdr = NULL; + Hdr = NULL; if (PoolIndex == MAX_POOL_INDEX) { - Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType, - EFI_SIZE_TO_PAGES (MAX_POOL_SIZE << 1), - &Address, FALSE); + Status = SmmInternalAllocatePages ( + AllocateAnyPages, + PoolType, + EFI_SIZE_TO_PAGES (MAX_POOL_SIZE << 1), + &Address, + FALSE + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } - Hdr = (FREE_POOL_HEADER *) (UINTN) Address; + + Hdr = (FREE_POOL_HEADER *)(UINTN)Address; } else if (!IsListEmpty (&mSmmPoolLists[SmmPoolType][PoolIndex])) { Hdr = BASE_CR (GetFirstNode (&mSmmPoolLists[SmmPoolType][PoolIndex]), FREE_POOL_HEADER, Link); RemoveEntryList (&Hdr->Link); @@ -152,25 +157,25 @@ InternalAllocPoolByIndex ( Status = InternalAllocPoolByIndex (PoolType, PoolIndex + 1, &Hdr); if (!EFI_ERROR (Status)) { Hdr->Header.Signature = 0; - Hdr->Header.Size >>= 1; + Hdr->Header.Size >>= 1; Hdr->Header.Available = TRUE; - Hdr->Header.Type = 0; - Tail = HEAD_TO_TAIL(&Hdr->Header); - Tail->Signature = 0; - Tail->Size = 0; + Hdr->Header.Type = 0; + Tail = HEAD_TO_TAIL (&Hdr->Header); + Tail->Signature = 0; + Tail->Size = 0; InsertHeadList (&mSmmPoolLists[SmmPoolType][PoolIndex], &Hdr->Link); - Hdr = (FREE_POOL_HEADER*)((UINT8*)Hdr + Hdr->Header.Size); + Hdr = (FREE_POOL_HEADER *)((UINT8 *)Hdr + Hdr->Header.Size); } } if (!EFI_ERROR (Status)) { Hdr->Header.Signature = POOL_HEAD_SIGNATURE; - Hdr->Header.Size = MIN_POOL_SIZE << PoolIndex; + Hdr->Header.Size = MIN_POOL_SIZE << PoolIndex; Hdr->Header.Available = FALSE; - Hdr->Header.Type = PoolType; - Tail = HEAD_TO_TAIL(&Hdr->Header); - Tail->Signature = POOL_TAIL_SIGNATURE; - Tail->Size = Hdr->Header.Size; + Hdr->Header.Type = PoolType; + Tail = HEAD_TO_TAIL (&Hdr->Header); + Tail->Signature = POOL_TAIL_SIGNATURE; + Tail->Size = Hdr->Header.Size; } *FreePoolHdr = Hdr; @@ -192,21 +197,21 @@ InternalFreePoolByIndex ( IN POOL_TAIL *PoolTail ) { - UINTN PoolIndex; - SMM_POOL_TYPE SmmPoolType; + UINTN PoolIndex; + SMM_POOL_TYPE SmmPoolType; ASSERT ((FreePoolHdr->Header.Size & (FreePoolHdr->Header.Size - 1)) == 0); ASSERT (((UINTN)FreePoolHdr & (FreePoolHdr->Header.Size - 1)) == 0); ASSERT (FreePoolHdr->Header.Size >= MIN_POOL_SIZE); - SmmPoolType = UefiMemoryTypeToSmmPoolType(FreePoolHdr->Header.Type); + SmmPoolType = UefiMemoryTypeToSmmPoolType (FreePoolHdr->Header.Type); - PoolIndex = (UINTN) (HighBitSet32 ((UINT32)FreePoolHdr->Header.Size) - MIN_POOL_SHIFT); + PoolIndex = (UINTN)(HighBitSet32 ((UINT32)FreePoolHdr->Header.Size) - MIN_POOL_SHIFT); FreePoolHdr->Header.Signature = 0; FreePoolHdr->Header.Available = TRUE; - FreePoolHdr->Header.Type = 0; - PoolTail->Signature = 0; - PoolTail->Size = 0; + FreePoolHdr->Header.Type = 0; + PoolTail->Signature = 0; + PoolTail->Size = 0; ASSERT (PoolIndex < MAX_POOL_INDEX); InsertHeadList (&mSmmPoolLists[SmmPoolType][PoolIndex], &FreePoolHdr->Link); return EFI_SUCCESS; @@ -245,8 +250,9 @@ SmmInternalAllocatePool ( Address = 0; - if (PoolType != EfiRuntimeServicesCode && - PoolType != EfiRuntimeServicesData) { + if ((PoolType != EfiRuntimeServicesCode) && + (PoolType != EfiRuntimeServicesData)) + { return EFI_INVALID_PARAMETER; } @@ -258,14 +264,19 @@ SmmInternalAllocatePool ( // Adjust the size by the pool header & tail overhead // Size += POOL_OVERHEAD; - if (Size > MAX_POOL_SIZE || NeedGuard) { + if ((Size > MAX_POOL_SIZE) || NeedGuard) { if (!HasPoolTail) { Size -= sizeof (POOL_TAIL); } NoPages = EFI_SIZE_TO_PAGES (Size); - Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType, NoPages, - &Address, NeedGuard); + Status = SmmInternalAllocatePages ( + AllocateAnyPages, + PoolType, + NoPages, + &Address, + NeedGuard + ); if (EFI_ERROR (Status)) { return Status; } @@ -279,32 +290,33 @@ SmmInternalAllocatePool ( ); } - PoolHdr = (POOL_HEADER*)(UINTN)Address; + PoolHdr = (POOL_HEADER *)(UINTN)Address; PoolHdr->Signature = POOL_HEAD_SIGNATURE; - PoolHdr->Size = EFI_PAGES_TO_SIZE (NoPages); + PoolHdr->Size = EFI_PAGES_TO_SIZE (NoPages); PoolHdr->Available = FALSE; - PoolHdr->Type = PoolType; + PoolHdr->Type = PoolType; if (HasPoolTail) { - PoolTail = HEAD_TO_TAIL (PoolHdr); + PoolTail = HEAD_TO_TAIL (PoolHdr); PoolTail->Signature = POOL_TAIL_SIGNATURE; - PoolTail->Size = PoolHdr->Size; + PoolTail->Size = PoolHdr->Size; } *Buffer = PoolHdr + 1; return Status; } - Size = (Size + MIN_POOL_SIZE - 1) >> MIN_POOL_SHIFT; - PoolIndex = (UINTN) HighBitSet32 ((UINT32)Size); + Size = (Size + MIN_POOL_SIZE - 1) >> MIN_POOL_SHIFT; + PoolIndex = (UINTN)HighBitSet32 ((UINT32)Size); if ((Size & (Size - 1)) != 0) { PoolIndex++; } Status = InternalAllocPoolByIndex (PoolType, PoolIndex, &FreePoolHdr); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { *Buffer = &FreePoolHdr->Header + 1; } + return Status; } @@ -334,7 +346,7 @@ SmmAllocatePool ( Status = SmmInternalAllocatePool (PoolType, Size, Buffer); if (!EFI_ERROR (Status)) { SmmCoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionAllocatePool, PoolType, Size, @@ -342,6 +354,7 @@ SmmAllocatePool ( NULL ); } + return Status; } @@ -371,10 +384,10 @@ SmmInternalFreePool ( MemoryGuarded = IsHeapGuardEnabled () && IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer); - HasPoolTail = !(MemoryGuarded && - ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)); + HasPoolTail = !(MemoryGuarded && + ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0)); - FreePoolHdr = (FREE_POOL_HEADER*)((POOL_HEADER*)Buffer - 1); + FreePoolHdr = (FREE_POOL_HEADER *)((POOL_HEADER *)Buffer - 1); ASSERT (FreePoolHdr->Header.Signature == POOL_HEAD_SIGNATURE); ASSERT (!FreePoolHdr->Header.Available); if (FreePoolHdr->Header.Signature != POOL_HEAD_SIGNATURE) { @@ -414,6 +427,7 @@ SmmInternalFreePool ( FALSE ); } + return InternalFreePoolByIndex (FreePoolHdr, PoolTail); } @@ -437,7 +451,7 @@ SmmFreePool ( Status = SmmInternalFreePool (Buffer); if (!EFI_ERROR (Status)) { SmmCoreUpdateProfile ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0), + (EFI_PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MemoryProfileActionFreePool, EfiMaxMemoryType, 0, @@ -445,5 +459,6 @@ SmmFreePool ( NULL ); } + return Status; } diff --git a/MdeModulePkg/Core/PiSmmCore/Smi.c b/MdeModulePkg/Core/PiSmmCore/Smi.c index aeefb392f7..6d13969979 100644 --- a/MdeModulePkg/Core/PiSmmCore/Smi.c +++ b/MdeModulePkg/Core/PiSmmCore/Smi.c @@ -8,12 +8,12 @@ #include "PiSmmCore.h" -LIST_ENTRY mSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mSmiEntryList); +LIST_ENTRY mSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mSmiEntryList); -SMI_ENTRY mRootSmiEntry = { +SMI_ENTRY mRootSmiEntry = { SMI_ENTRY_SIGNATURE, INITIALIZE_LIST_HEAD_VARIABLE (mRootSmiEntry.AllEntries), - {0}, + { 0 }, INITIALIZE_LIST_HEAD_VARIABLE (mRootSmiEntry.SmiHandlers), }; @@ -43,8 +43,8 @@ SmmCoreFindSmiEntry ( SmiEntry = NULL; for (Link = mSmiEntryList.ForwardLink; Link != &mSmiEntryList; - Link = Link->ForwardLink) { - + Link = Link->ForwardLink) + { Item = CR (Link, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); if (CompareGuid (&Item->HandlerType, HandlerType)) { // @@ -60,7 +60,7 @@ SmmCoreFindSmiEntry ( // allocate a new entry // if ((SmiEntry == NULL) && Create) { - SmiEntry = AllocatePool (sizeof(SMI_ENTRY)); + SmiEntry = AllocatePool (sizeof (SMI_ENTRY)); if (SmiEntry != NULL) { // // Initialize new SMI entry structure @@ -75,6 +75,7 @@ SmmCoreFindSmiEntry ( InsertTailList (&mSmiEntryList, &SmiEntry->AllEntries); } } + return SmiEntry; } @@ -108,7 +109,7 @@ SmiManage ( BOOLEAN SuccessReturn; EFI_STATUS Status; - Status = EFI_NOT_FOUND; + Status = EFI_NOT_FOUND; SuccessReturn = FALSE; if (HandlerType == NULL) { // @@ -119,7 +120,7 @@ SmiManage ( // // Non-root SMI handler // - SmiEntry = SmmCoreFindSmiEntry ((EFI_GUID *) HandlerType, FALSE); + SmiEntry = SmmCoreFindSmiEntry ((EFI_GUID *)HandlerType, FALSE); if (SmiEntry == NULL) { // // There is no handler registered for this interrupt source @@ -127,62 +128,65 @@ SmiManage ( return Status; } } + Head = &SmiEntry->SmiHandlers; for (Link = Head->ForwardLink; Link != Head; Link = Link->ForwardLink) { SmiHandler = CR (Link, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); Status = SmiHandler->Handler ( - (EFI_HANDLE) SmiHandler, - Context, - CommBuffer, - CommBufferSize - ); + (EFI_HANDLE)SmiHandler, + Context, + CommBuffer, + CommBufferSize + ); switch (Status) { - case EFI_INTERRUPT_PENDING: - // - // If a handler returns EFI_INTERRUPT_PENDING and HandlerType is not NULL then - // no additional handlers will be processed and EFI_INTERRUPT_PENDING will be returned. - // - if (HandlerType != NULL) { - return EFI_INTERRUPT_PENDING; - } - break; - - case EFI_SUCCESS: - // - // If at least one of the handlers returns EFI_SUCCESS then the function will return - // EFI_SUCCESS. If a handler returns EFI_SUCCESS and HandlerType is not NULL then no - // additional handlers will be processed. - // - if (HandlerType != NULL) { - return EFI_SUCCESS; - } - SuccessReturn = TRUE; - break; - - case EFI_WARN_INTERRUPT_SOURCE_QUIESCED: - // - // If at least one of the handlers returns EFI_WARN_INTERRUPT_SOURCE_QUIESCED - // then the function will return EFI_SUCCESS. - // - SuccessReturn = TRUE; - break; - - case EFI_WARN_INTERRUPT_SOURCE_PENDING: - // - // If all the handlers returned EFI_WARN_INTERRUPT_SOURCE_PENDING - // then EFI_WARN_INTERRUPT_SOURCE_PENDING will be returned. - // - break; - - default: - // - // Unexpected status code returned. - // - ASSERT (FALSE); - break; + case EFI_INTERRUPT_PENDING: + // + // If a handler returns EFI_INTERRUPT_PENDING and HandlerType is not NULL then + // no additional handlers will be processed and EFI_INTERRUPT_PENDING will be returned. + // + if (HandlerType != NULL) { + return EFI_INTERRUPT_PENDING; + } + + break; + + case EFI_SUCCESS: + // + // If at least one of the handlers returns EFI_SUCCESS then the function will return + // EFI_SUCCESS. If a handler returns EFI_SUCCESS and HandlerType is not NULL then no + // additional handlers will be processed. + // + if (HandlerType != NULL) { + return EFI_SUCCESS; + } + + SuccessReturn = TRUE; + break; + + case EFI_WARN_INTERRUPT_SOURCE_QUIESCED: + // + // If at least one of the handlers returns EFI_WARN_INTERRUPT_SOURCE_QUIESCED + // then the function will return EFI_SUCCESS. + // + SuccessReturn = TRUE; + break; + + case EFI_WARN_INTERRUPT_SOURCE_PENDING: + // + // If all the handlers returned EFI_WARN_INTERRUPT_SOURCE_PENDING + // then EFI_WARN_INTERRUPT_SOURCE_PENDING will be returned. + // + break; + + default: + // + // Unexpected status code returned. + // + ASSERT (FALSE); + break; } } @@ -216,7 +220,7 @@ SmiHandlerRegister ( SMI_ENTRY *SmiEntry; LIST_ENTRY *List; - if (Handler == NULL || DispatchHandle == NULL) { + if ((Handler == NULL) || (DispatchHandle == NULL)) { return EFI_INVALID_PARAMETER; } @@ -225,8 +229,8 @@ SmiHandlerRegister ( return EFI_OUT_OF_RESOURCES; } - SmiHandler->Signature = SMI_HANDLER_SIGNATURE; - SmiHandler->Handler = Handler; + SmiHandler->Signature = SMI_HANDLER_SIGNATURE; + SmiHandler->Handler = Handler; SmiHandler->CallerAddr = (UINTN)RETURN_ADDRESS (0); if (HandlerType == NULL) { @@ -238,17 +242,18 @@ SmiHandlerRegister ( // // None root SMI handler // - SmiEntry = SmmCoreFindSmiEntry ((EFI_GUID *) HandlerType, TRUE); + SmiEntry = SmmCoreFindSmiEntry ((EFI_GUID *)HandlerType, TRUE); if (SmiEntry == NULL) { return EFI_OUT_OF_RESOURCES; } } + List = &SmiEntry->SmiHandlers; SmiHandler->SmiEntry = SmiEntry; InsertTailList (List, &SmiHandler->Link); - *DispatchHandle = (EFI_HANDLE) SmiHandler; + *DispatchHandle = (EFI_HANDLE)SmiHandler; return EFI_SUCCESS; } @@ -282,9 +287,10 @@ SmiHandlerUnRegister ( // SmiHandler = NULL; for ( HandlerLink = GetFirstNode (&mRootSmiEntry.SmiHandlers) - ; !IsNull (&mRootSmiEntry.SmiHandlers, HandlerLink) && ((EFI_HANDLE) SmiHandler != DispatchHandle) - ; HandlerLink = GetNextNode (&mRootSmiEntry.SmiHandlers, HandlerLink) - ) { + ; !IsNull (&mRootSmiEntry.SmiHandlers, HandlerLink) && ((EFI_HANDLE)SmiHandler != DispatchHandle) + ; HandlerLink = GetNextNode (&mRootSmiEntry.SmiHandlers, HandlerLink) + ) + { SmiHandler = CR (HandlerLink, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); } @@ -292,19 +298,21 @@ SmiHandlerUnRegister ( // Look for it in non-root SMI handlers // for ( EntryLink = GetFirstNode (&mSmiEntryList) - ; !IsNull (&mSmiEntryList, EntryLink) && ((EFI_HANDLE) SmiHandler != DispatchHandle) - ; EntryLink = GetNextNode (&mSmiEntryList, EntryLink) - ) { + ; !IsNull (&mSmiEntryList, EntryLink) && ((EFI_HANDLE)SmiHandler != DispatchHandle) + ; EntryLink = GetNextNode (&mSmiEntryList, EntryLink) + ) + { SmiEntry = CR (EntryLink, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); for ( HandlerLink = GetFirstNode (&SmiEntry->SmiHandlers) - ; !IsNull (&SmiEntry->SmiHandlers, HandlerLink) && ((EFI_HANDLE) SmiHandler != DispatchHandle) - ; HandlerLink = GetNextNode (&SmiEntry->SmiHandlers, HandlerLink) - ) { + ; !IsNull (&SmiEntry->SmiHandlers, HandlerLink) && ((EFI_HANDLE)SmiHandler != DispatchHandle) + ; HandlerLink = GetNextNode (&SmiEntry->SmiHandlers, HandlerLink) + ) + { SmiHandler = CR (HandlerLink, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); } } - if ((EFI_HANDLE) SmiHandler != DispatchHandle) { + if ((EFI_HANDLE)SmiHandler != DispatchHandle) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Core/PiSmmCore/SmiHandlerProfile.c b/MdeModulePkg/Core/PiSmmCore/SmiHandlerProfile.c index 50d092d05d..27da2898dd 100644 --- a/MdeModulePkg/Core/PiSmmCore/SmiHandlerProfile.c +++ b/MdeModulePkg/Core/PiSmmCore/SmiHandlerProfile.c @@ -43,7 +43,7 @@ typedef struct { Register SMI handler profile handler. **/ VOID -RegisterSmiHandlerProfileHandler( +RegisterSmiHandlerProfileHandler ( VOID ); @@ -76,13 +76,13 @@ extern SMI_ENTRY mRootSmiEntry; extern SMI_HANDLER_PROFILE_PROTOCOL mSmiHandlerProfile; -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mHardwareSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mHardwareSmiEntryList); +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mHardwareSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mHardwareSmiEntryList); -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mRootSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mRootSmiEntryList); +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mRootSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mRootSmiEntryList); -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreRootSmiEntryList = &mRootSmiEntryList; -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreSmiEntryList = &mSmiEntryList; -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreHardwareSmiEntryList = &mHardwareSmiEntryList; +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreRootSmiEntryList = &mRootSmiEntryList; +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreSmiEntryList = &mSmiEntryList; +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY *mSmmCoreHardwareSmiEntryList = &mHardwareSmiEntryList; GLOBAL_REMOVE_IF_UNREFERENCED IMAGE_STRUCT *mImageStruct; GLOBAL_REMOVE_IF_UNREFERENCED UINT32 mImageStructCountMax; @@ -116,6 +116,7 @@ InternalDumpData ( ) { UINTN Index; + for (Index = 0; Index < Size; Index++) { DEBUG ((DEBUG_INFO, "%02x ", (UINTN)Data[Index])); } @@ -133,17 +134,19 @@ GetDriverGuid ( OUT EFI_GUID *Guid ) { - EFI_GUID *FileName; + EFI_GUID *FileName; FileName = NULL; - if ((DevicePathType(LoadedImage->FilePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType(LoadedImage->FilePath) == MEDIA_PIWG_FW_FILE_DP)) { + if ((DevicePathType (LoadedImage->FilePath) == MEDIA_DEVICE_PATH) && + (DevicePathSubType (LoadedImage->FilePath) == MEDIA_PIWG_FW_FILE_DP)) + { FileName = &((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)LoadedImage->FilePath)->FvFileName; } + if (FileName != NULL) { - CopyGuid(Guid, FileName); + CopyGuid (Guid, FileName); } else { - ZeroMem(Guid, sizeof(EFI_GUID)); + ZeroMem (Guid, sizeof (EFI_GUID)); } } @@ -157,31 +160,31 @@ GetDriverGuid ( @param PdbString image PDB string **/ VOID -AddImageStruct( - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize, - IN PHYSICAL_ADDRESS EntryPoint, - IN EFI_GUID *Guid, - IN CHAR8 *PdbString +AddImageStruct ( + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize, + IN PHYSICAL_ADDRESS EntryPoint, + IN EFI_GUID *Guid, + IN CHAR8 *PdbString ) { UINTN PdbStringSize; if (mImageStructCount >= mImageStructCountMax) { - ASSERT(FALSE); + ASSERT (FALSE); return; } - CopyGuid(&mImageStruct[mImageStructCount].FileGuid, Guid); - mImageStruct[mImageStructCount].ImageRef = mImageStructCount; - mImageStruct[mImageStructCount].ImageBase = ImageBase; - mImageStruct[mImageStructCount].ImageSize = ImageSize; + CopyGuid (&mImageStruct[mImageStructCount].FileGuid, Guid); + mImageStruct[mImageStructCount].ImageRef = mImageStructCount; + mImageStruct[mImageStructCount].ImageBase = ImageBase; + mImageStruct[mImageStructCount].ImageSize = ImageSize; mImageStruct[mImageStructCount].EntryPoint = EntryPoint; if (PdbString != NULL) { - PdbStringSize = AsciiStrSize(PdbString); + PdbStringSize = AsciiStrSize (PdbString); mImageStruct[mImageStructCount].PdbString = AllocateCopyPool (PdbStringSize, PdbString); if (mImageStruct[mImageStructCount].PdbString != NULL) { - mImageStruct[mImageStructCount].PdbStringSize = (UINT16) PdbStringSize; + mImageStruct[mImageStructCount].PdbStringSize = (UINT16)PdbStringSize; } } @@ -196,7 +199,7 @@ AddImageStruct( @return image structure **/ IMAGE_STRUCT * -AddressToImageStruct( +AddressToImageStruct ( IN UINTN Address ) { @@ -204,10 +207,12 @@ AddressToImageStruct( for (Index = 0; Index < mImageStructCount; Index++) { if ((Address >= mImageStruct[Index].ImageBase) && - (Address < mImageStruct[Index].ImageBase + mImageStruct[Index].ImageSize)) { + (Address < mImageStruct[Index].ImageBase + mImageStruct[Index].ImageSize)) + { return &mImageStruct[Index]; } } + return NULL; } @@ -219,16 +224,17 @@ AddressToImageStruct( @return image reference index **/ UINT32 -AddressToImageRef( +AddressToImageRef ( IN UINTN Address ) { - IMAGE_STRUCT *ImageStruct; + IMAGE_STRUCT *ImageStruct; - ImageStruct = AddressToImageStruct(Address); + ImageStruct = AddressToImageStruct (Address); if (ImageStruct != NULL) { return ImageStruct->ImageRef; } + return (UINT32)-1; } @@ -236,7 +242,7 @@ AddressToImageRef( Collect SMM image information based upon loaded image protocol. **/ VOID -GetSmmLoadedImage( +GetSmmLoadedImage ( VOID ) { @@ -255,55 +261,58 @@ GetSmmLoadedImage( PHYSICAL_ADDRESS RealImageBase; HandleBufferSize = 0; - HandleBuffer = NULL; - Status = gSmst->SmmLocateHandle( - ByProtocol, - &gEfiLoadedImageProtocolGuid, - NULL, - &HandleBufferSize, - HandleBuffer - ); + HandleBuffer = NULL; + Status = gSmst->SmmLocateHandle ( + ByProtocol, + &gEfiLoadedImageProtocolGuid, + NULL, + &HandleBufferSize, + HandleBuffer + ); if (Status != EFI_BUFFER_TOO_SMALL) { return; } + HandleBuffer = AllocateZeroPool (HandleBufferSize); if (HandleBuffer == NULL) { return; } - Status = gSmst->SmmLocateHandle( + + Status = gSmst->SmmLocateHandle ( ByProtocol, &gEfiLoadedImageProtocolGuid, NULL, &HandleBufferSize, HandleBuffer ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return; } - NoHandles = HandleBufferSize/sizeof(EFI_HANDLE); - mImageStructCountMax = (UINT32) NoHandles; - mImageStruct = AllocateZeroPool(mImageStructCountMax * sizeof(IMAGE_STRUCT)); + NoHandles = HandleBufferSize/sizeof (EFI_HANDLE); + mImageStructCountMax = (UINT32)NoHandles; + mImageStruct = AllocateZeroPool (mImageStructCountMax * sizeof (IMAGE_STRUCT)); if (mImageStruct == NULL) { goto Done; } for (Index = 0; Index < NoHandles; Index++) { - Status = gSmst->SmmHandleProtocol( + Status = gSmst->SmmHandleProtocol ( HandleBuffer[Index], &gEfiLoadedImageProtocolGuid, (VOID **)&LoadedImage ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } - PathStr = ConvertDevicePathToText(LoadedImage->FilePath, TRUE, TRUE); - GetDriverGuid(LoadedImage, &Guid); + + PathStr = ConvertDevicePathToText (LoadedImage->FilePath, TRUE, TRUE); + GetDriverGuid (LoadedImage, &Guid); DEBUG ((DEBUG_INFO, "Image: %g ", &Guid)); - EntryPoint = 0; - LoadedImagePrivate = BASE_CR(LoadedImage, EFI_SMM_DRIVER_ENTRY, SmmLoadedImage); - RealImageBase = (UINTN)LoadedImage->ImageBase; + EntryPoint = 0; + LoadedImagePrivate = BASE_CR (LoadedImage, EFI_SMM_DRIVER_ENTRY, SmmLoadedImage); + RealImageBase = (UINTN)LoadedImage->ImageBase; if (LoadedImagePrivate->Signature == EFI_SMM_DRIVER_ENTRY_SIGNATURE) { EntryPoint = LoadedImagePrivate->ImageEntryPoint; if ((EntryPoint != 0) && ((EntryPoint < (UINTN)LoadedImage->ImageBase) || (EntryPoint >= ((UINTN)LoadedImage->ImageBase + LoadedImage->ImageSize)))) { @@ -311,30 +320,33 @@ GetSmmLoadedImage( // If the EntryPoint is not in the range of image buffer, it should come from emulation environment. // So patch ImageBuffer here to align the EntryPoint. // - Status = InternalPeCoffGetEntryPoint(LoadedImage->ImageBase, &EntryPointInImage); - ASSERT_EFI_ERROR(Status); + Status = InternalPeCoffGetEntryPoint (LoadedImage->ImageBase, &EntryPointInImage); + ASSERT_EFI_ERROR (Status); RealImageBase = (UINTN)LoadedImage->ImageBase + EntryPoint - (UINTN)EntryPointInImage; } } + DEBUG ((DEBUG_INFO, "(0x%lx - 0x%lx", RealImageBase, LoadedImage->ImageSize)); if (EntryPoint != 0) { DEBUG ((DEBUG_INFO, ", EntryPoint:0x%lx", EntryPoint)); } + DEBUG ((DEBUG_INFO, ")\n")); if (RealImageBase != 0) { - PdbString = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) RealImageBase); + PdbString = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)RealImageBase); DEBUG ((DEBUG_INFO, " pdb - %a\n", PdbString)); } else { PdbString = NULL; } + DEBUG ((DEBUG_INFO, " (%s)\n", PathStr)); - AddImageStruct(RealImageBase, LoadedImage->ImageSize, EntryPoint, &Guid, PdbString); + AddImageStruct (RealImageBase, LoadedImage->ImageSize, EntryPoint, &Guid, PdbString); } Done: - FreePool(HandleBuffer); + FreePool (HandleBuffer); return; } @@ -347,12 +359,12 @@ Done: **/ VOID DumpSmiChildContext ( - IN EFI_GUID *HandlerType, - IN VOID *Context, - IN UINTN ContextSize + IN EFI_GUID *HandlerType, + IN VOID *Context, + IN UINTN ContextSize ) { - CHAR16 *Str; + CHAR16 *Str; if (CompareGuid (HandlerType, &gEfiSmmSwDispatch2ProtocolGuid)) { DEBUG ((DEBUG_INFO, " SwSmi - 0x%lx\n", ((SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT *)Context)->SwSmiInputValue)); @@ -374,7 +386,7 @@ DumpSmiChildContext ( DEBUG ((DEBUG_INFO, " IoTrapType - 0x%x\n", ((EFI_SMM_IO_TRAP_REGISTER_CONTEXT *)Context)->Type)); } else if (CompareGuid (HandlerType, &gEfiSmmUsbDispatch2ProtocolGuid)) { DEBUG ((DEBUG_INFO, " UsbType - 0x%x\n", ((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context)->Type)); - Str = ConvertDevicePathToText((EFI_DEVICE_PATH_PROTOCOL *)(((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context) + 1), TRUE, TRUE); + Str = ConvertDevicePathToText ((EFI_DEVICE_PATH_PROTOCOL *)(((SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *)Context) + 1), TRUE, TRUE); DEBUG ((DEBUG_INFO, " UsbDevicePath - %s\n", Str)); if (Str != NULL) { FreePool (Str); @@ -392,39 +404,45 @@ DumpSmiChildContext ( @param SmiEntry SMI entry. **/ VOID -DumpSmiHandlerOnSmiEntry( - IN SMI_ENTRY *SmiEntry +DumpSmiHandlerOnSmiEntry ( + IN SMI_ENTRY *SmiEntry ) { - LIST_ENTRY *ListEntry; - SMI_HANDLER *SmiHandler; - IMAGE_STRUCT *ImageStruct; + LIST_ENTRY *ListEntry; + SMI_HANDLER *SmiHandler; + IMAGE_STRUCT *ImageStruct; ListEntry = &SmiEntry->SmiHandlers; for (ListEntry = ListEntry->ForwardLink; ListEntry != &SmiEntry->SmiHandlers; - ListEntry = ListEntry->ForwardLink) { - SmiHandler = CR(ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); - ImageStruct = AddressToImageStruct((UINTN)SmiHandler->Handler); + ListEntry = ListEntry->ForwardLink) + { + SmiHandler = CR (ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); + ImageStruct = AddressToImageStruct ((UINTN)SmiHandler->Handler); if (ImageStruct != NULL) { DEBUG ((DEBUG_INFO, " Module - %g", &ImageStruct->FileGuid)); } + if ((ImageStruct != NULL) && (ImageStruct->PdbString[0] != 0)) { DEBUG ((DEBUG_INFO, " (Pdb - %a)", ImageStruct->PdbString)); } + DEBUG ((DEBUG_INFO, "\n")); if (SmiHandler->ContextSize != 0) { DumpSmiChildContext (&SmiEntry->HandlerType, SmiHandler->Context, SmiHandler->ContextSize); } + DEBUG ((DEBUG_INFO, " Handler - 0x%x", SmiHandler->Handler)); if (ImageStruct != NULL) { - DEBUG ((DEBUG_INFO, " <== RVA - 0x%x", (UINTN)SmiHandler->Handler - (UINTN) ImageStruct->ImageBase)); + DEBUG ((DEBUG_INFO, " <== RVA - 0x%x", (UINTN)SmiHandler->Handler - (UINTN)ImageStruct->ImageBase)); } + DEBUG ((DEBUG_INFO, "\n")); DEBUG ((DEBUG_INFO, " CallerAddr - 0x%x", SmiHandler->CallerAddr)); if (ImageStruct != NULL) { - DEBUG ((DEBUG_INFO, " <== RVA - 0x%x", SmiHandler->CallerAddr - (UINTN) ImageStruct->ImageBase)); + DEBUG ((DEBUG_INFO, " <== RVA - 0x%x", SmiHandler->CallerAddr - (UINTN)ImageStruct->ImageBase)); } + DEBUG ((DEBUG_INFO, "\n")); } @@ -437,20 +455,21 @@ DumpSmiHandlerOnSmiEntry( @param SmiEntryList a list of SMI entry. **/ VOID -DumpSmiEntryList( - IN LIST_ENTRY *SmiEntryList +DumpSmiEntryList ( + IN LIST_ENTRY *SmiEntryList ) { - LIST_ENTRY *ListEntry; - SMI_ENTRY *SmiEntry; + LIST_ENTRY *ListEntry; + SMI_ENTRY *SmiEntry; ListEntry = SmiEntryList; for (ListEntry = ListEntry->ForwardLink; ListEntry != SmiEntryList; - ListEntry = ListEntry->ForwardLink) { - SmiEntry = CR(ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); + ListEntry = ListEntry->ForwardLink) + { + SmiEntry = CR (ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); DEBUG ((DEBUG_INFO, "SmiEntry - %g\n", &SmiEntry->HandlerType)); - DumpSmiHandlerOnSmiEntry(SmiEntry); + DumpSmiHandlerOnSmiEntry (SmiEntry); } return; @@ -494,25 +513,25 @@ SmmReadyToLockInSmiHandlerProfile ( DEBUG ((DEBUG_INFO, "# 1. ROOT SMI Handler #\n")); DEBUG_CODE ( - DumpSmiEntryList(mSmmCoreRootSmiEntryList); - ); + DumpSmiEntryList (mSmmCoreRootSmiEntryList); + ); DEBUG ((DEBUG_INFO, "# 2. GUID SMI Handler #\n")); DEBUG_CODE ( - DumpSmiEntryList(mSmmCoreSmiEntryList); - ); + DumpSmiEntryList (mSmmCoreSmiEntryList); + ); DEBUG ((DEBUG_INFO, "# 3. Hardware SMI Handler #\n")); DEBUG_CODE ( - DumpSmiEntryList(mSmmCoreHardwareSmiEntryList); - ); + DumpSmiEntryList (mSmmCoreHardwareSmiEntryList); + ); DEBUG ((DEBUG_INFO, "\n")); - RegisterSmiHandlerProfileHandler(); + RegisterSmiHandlerProfileHandler (); if (mImageStruct != NULL) { - FreePool(mImageStruct); + FreePool (mImageStruct); } return EFI_SUCCESS; @@ -524,17 +543,18 @@ SmmReadyToLockInSmiHandlerProfile ( @return SMM image data base size. **/ UINTN -GetSmmImageDatabaseSize( +GetSmmImageDatabaseSize ( VOID ) { - UINTN Size; - UINT32 Index; + UINTN Size; + UINT32 Index; Size = 0; for (Index = 0; Index < mImageStructCount; Index++) { - Size += sizeof(SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)); + Size += sizeof (SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)); } + return Size; } @@ -546,21 +566,22 @@ GetSmmImageDatabaseSize( @return all SMI handlers' size associated with SmiEntry. **/ UINTN -GetSmmSmiHandlerSizeOnSmiEntry( - IN SMI_ENTRY *SmiEntry +GetSmmSmiHandlerSizeOnSmiEntry ( + IN SMI_ENTRY *SmiEntry ) { - LIST_ENTRY *ListEntry; - SMI_HANDLER *SmiHandler; - UINTN Size; + LIST_ENTRY *ListEntry; + SMI_HANDLER *SmiHandler; + UINTN Size; - Size = 0; + Size = 0; ListEntry = &SmiEntry->SmiHandlers; for (ListEntry = ListEntry->ForwardLink; ListEntry != &SmiEntry->SmiHandlers; - ListEntry = ListEntry->ForwardLink) { - SmiHandler = CR(ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); - Size += sizeof(SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)); + ListEntry = ListEntry->ForwardLink) + { + SmiHandler = CR (ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); + Size += sizeof (SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)); } return Size; @@ -574,23 +595,25 @@ GetSmmSmiHandlerSizeOnSmiEntry( @return all SMI handler database size on the SMI entry list. **/ UINTN -GetSmmSmiDatabaseSize( - IN LIST_ENTRY *SmiEntryList +GetSmmSmiDatabaseSize ( + IN LIST_ENTRY *SmiEntryList ) { - LIST_ENTRY *ListEntry; - SMI_ENTRY *SmiEntry; - UINTN Size; + LIST_ENTRY *ListEntry; + SMI_ENTRY *SmiEntry; + UINTN Size; - Size = 0; + Size = 0; ListEntry = SmiEntryList; for (ListEntry = ListEntry->ForwardLink; ListEntry != SmiEntryList; - ListEntry = ListEntry->ForwardLink) { - SmiEntry = CR(ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); - Size += sizeof(SMM_CORE_SMI_DATABASE_STRUCTURE); - Size += GetSmmSmiHandlerSizeOnSmiEntry(SmiEntry); + ListEntry = ListEntry->ForwardLink) + { + SmiEntry = CR (ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); + Size += sizeof (SMM_CORE_SMI_DATABASE_STRUCTURE); + Size += GetSmmSmiHandlerSizeOnSmiEntry (SmiEntry); } + return Size; } @@ -604,10 +627,10 @@ GetSmiHandlerProfileDatabaseSize ( VOID ) { - mSmmImageDatabaseSize = GetSmmImageDatabaseSize(); - mSmmRootSmiDatabaseSize = GetSmmSmiDatabaseSize(mSmmCoreRootSmiEntryList); - mSmmSmiDatabaseSize = GetSmmSmiDatabaseSize(mSmmCoreSmiEntryList); - mSmmHardwareSmiDatabaseSize = GetSmmSmiDatabaseSize(mSmmCoreHardwareSmiEntryList); + mSmmImageDatabaseSize = GetSmmImageDatabaseSize (); + mSmmRootSmiDatabaseSize = GetSmmSmiDatabaseSize (mSmmCoreRootSmiEntryList); + mSmmSmiDatabaseSize = GetSmmSmiDatabaseSize (mSmmCoreSmiEntryList); + mSmmHardwareSmiDatabaseSize = GetSmmSmiDatabaseSize (mSmmCoreHardwareSmiEntryList); return mSmmImageDatabaseSize + mSmmSmiDatabaseSize + mSmmRootSmiDatabaseSize + mSmmHardwareSmiDatabaseSize; } @@ -622,44 +645,48 @@ GetSmiHandlerProfileDatabaseSize ( **/ UINTN GetSmmImageDatabaseData ( - IN OUT VOID *Data, - IN UINTN ExpectedSize + IN OUT VOID *Data, + IN UINTN ExpectedSize ) { - SMM_CORE_IMAGE_DATABASE_STRUCTURE *ImageStruct; - UINTN Size; - UINTN Index; + SMM_CORE_IMAGE_DATABASE_STRUCTURE *ImageStruct; + UINTN Size; + UINTN Index; ImageStruct = Data; - Size = 0; + Size = 0; for (Index = 0; Index < mImageStructCount; Index++) { if (Size >= ExpectedSize) { return 0; } - if (sizeof(SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)) > ExpectedSize - Size) { + + if (sizeof (SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)) > ExpectedSize - Size) { return 0; } + ImageStruct->Header.Signature = SMM_CORE_IMAGE_DATABASE_SIGNATURE; - ImageStruct->Header.Length = (UINT32)(sizeof(SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64))); - ImageStruct->Header.Revision = SMM_CORE_IMAGE_DATABASE_REVISION; - CopyGuid(&ImageStruct->FileGuid, &mImageStruct[Index].FileGuid); - ImageStruct->ImageRef = mImageStruct[Index].ImageRef; + ImageStruct->Header.Length = (UINT32)(sizeof (SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64))); + ImageStruct->Header.Revision = SMM_CORE_IMAGE_DATABASE_REVISION; + CopyGuid (&ImageStruct->FileGuid, &mImageStruct[Index].FileGuid); + ImageStruct->ImageRef = mImageStruct[Index].ImageRef; ImageStruct->EntryPoint = mImageStruct[Index].EntryPoint; - ImageStruct->ImageBase = mImageStruct[Index].ImageBase; - ImageStruct->ImageSize = mImageStruct[Index].ImageSize; + ImageStruct->ImageBase = mImageStruct[Index].ImageBase; + ImageStruct->ImageSize = mImageStruct[Index].ImageSize; if (mImageStruct[Index].PdbStringSize != 0) { - ImageStruct->PdbStringOffset = sizeof(SMM_CORE_IMAGE_DATABASE_STRUCTURE); + ImageStruct->PdbStringOffset = sizeof (SMM_CORE_IMAGE_DATABASE_STRUCTURE); CopyMem ((VOID *)((UINTN)ImageStruct + ImageStruct->PdbStringOffset), mImageStruct[Index].PdbString, mImageStruct[Index].PdbStringSize); } else { ImageStruct->PdbStringOffset = 0; } + ImageStruct = (SMM_CORE_IMAGE_DATABASE_STRUCTURE *)((UINTN)ImageStruct + ImageStruct->Header.Length); - Size += sizeof(SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)); + Size += sizeof (SMM_CORE_IMAGE_DATABASE_STRUCTURE) + GET_OCCUPIED_SIZE (mImageStruct[Index].PdbStringSize, sizeof (UINT64)); } if (ExpectedSize != Size) { return 0; } + return Size; } @@ -674,48 +701,52 @@ GetSmmImageDatabaseData ( @return SMM image data base size. **/ UINTN -GetSmmSmiHandlerDataOnSmiEntry( - IN SMI_ENTRY *SmiEntry, - IN OUT VOID *Data, - IN UINTN MaxSize, - OUT UINT32 *Count +GetSmmSmiHandlerDataOnSmiEntry ( + IN SMI_ENTRY *SmiEntry, + IN OUT VOID *Data, + IN UINTN MaxSize, + OUT UINT32 *Count ) { - SMM_CORE_SMI_HANDLER_STRUCTURE *SmiHandlerStruct; - LIST_ENTRY *ListEntry; - SMI_HANDLER *SmiHandler; - UINTN Size; + SMM_CORE_SMI_HANDLER_STRUCTURE *SmiHandlerStruct; + LIST_ENTRY *ListEntry; + SMI_HANDLER *SmiHandler; + UINTN Size; SmiHandlerStruct = Data; - Size = 0; - *Count = 0; - ListEntry = &SmiEntry->SmiHandlers; + Size = 0; + *Count = 0; + ListEntry = &SmiEntry->SmiHandlers; for (ListEntry = ListEntry->ForwardLink; ListEntry != &SmiEntry->SmiHandlers; - ListEntry = ListEntry->ForwardLink) { - SmiHandler = CR(ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); + ListEntry = ListEntry->ForwardLink) + { + SmiHandler = CR (ListEntry, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); if (Size >= MaxSize) { *Count = 0; return 0; } - if (sizeof(SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)) > MaxSize - Size) { + + if (sizeof (SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)) > MaxSize - Size) { *Count = 0; return 0; } - SmiHandlerStruct->Length = (UINT32)(sizeof(SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64))); - SmiHandlerStruct->CallerAddr = (UINTN)SmiHandler->CallerAddr; - SmiHandlerStruct->Handler = (UINTN)SmiHandler->Handler; - SmiHandlerStruct->ImageRef = AddressToImageRef((UINTN)SmiHandler->Handler); + + SmiHandlerStruct->Length = (UINT32)(sizeof (SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64))); + SmiHandlerStruct->CallerAddr = (UINTN)SmiHandler->CallerAddr; + SmiHandlerStruct->Handler = (UINTN)SmiHandler->Handler; + SmiHandlerStruct->ImageRef = AddressToImageRef ((UINTN)SmiHandler->Handler); SmiHandlerStruct->ContextBufferSize = (UINT32)SmiHandler->ContextSize; if (SmiHandler->ContextSize != 0) { - SmiHandlerStruct->ContextBufferOffset = sizeof(SMM_CORE_SMI_HANDLER_STRUCTURE); + SmiHandlerStruct->ContextBufferOffset = sizeof (SMM_CORE_SMI_HANDLER_STRUCTURE); CopyMem ((UINT8 *)SmiHandlerStruct + SmiHandlerStruct->ContextBufferOffset, SmiHandler->Context, SmiHandler->ContextSize); } else { SmiHandlerStruct->ContextBufferOffset = 0; } - Size += sizeof(SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)); + + Size += sizeof (SMM_CORE_SMI_HANDLER_STRUCTURE) + GET_OCCUPIED_SIZE (SmiHandler->ContextSize, sizeof (UINT64)); SmiHandlerStruct = (SMM_CORE_SMI_HANDLER_STRUCTURE *)((UINTN)SmiHandlerStruct + SmiHandlerStruct->Length); - *Count = *Count + 1; + *Count = *Count + 1; } return Size; @@ -732,49 +763,53 @@ GetSmmSmiHandlerDataOnSmiEntry( @return all SMI database size on the SMI entry list. **/ UINTN -GetSmmSmiDatabaseData( - IN LIST_ENTRY *SmiEntryList, - IN UINT32 HandlerCategory, - IN OUT VOID *Data, - IN UINTN ExpectedSize +GetSmmSmiDatabaseData ( + IN LIST_ENTRY *SmiEntryList, + IN UINT32 HandlerCategory, + IN OUT VOID *Data, + IN UINTN ExpectedSize ) { - SMM_CORE_SMI_DATABASE_STRUCTURE *SmiStruct; - LIST_ENTRY *ListEntry; - SMI_ENTRY *SmiEntry; - UINTN Size; - UINTN SmiHandlerSize; - UINT32 SmiHandlerCount; + SMM_CORE_SMI_DATABASE_STRUCTURE *SmiStruct; + LIST_ENTRY *ListEntry; + SMI_ENTRY *SmiEntry; + UINTN Size; + UINTN SmiHandlerSize; + UINT32 SmiHandlerCount; SmiStruct = Data; - Size = 0; + Size = 0; ListEntry = SmiEntryList; for (ListEntry = ListEntry->ForwardLink; ListEntry != SmiEntryList; - ListEntry = ListEntry->ForwardLink) { - SmiEntry = CR(ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); + ListEntry = ListEntry->ForwardLink) + { + SmiEntry = CR (ListEntry, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); if (Size >= ExpectedSize) { return 0; } - if (sizeof(SMM_CORE_SMI_DATABASE_STRUCTURE) > ExpectedSize - Size) { + + if (sizeof (SMM_CORE_SMI_DATABASE_STRUCTURE) > ExpectedSize - Size) { return 0; } SmiStruct->Header.Signature = SMM_CORE_SMI_DATABASE_SIGNATURE; - SmiStruct->Header.Length = sizeof(SMM_CORE_SMI_DATABASE_STRUCTURE); - SmiStruct->Header.Revision = SMM_CORE_SMI_DATABASE_REVISION; - SmiStruct->HandlerCategory = HandlerCategory; - CopyGuid(&SmiStruct->HandlerType, &SmiEntry->HandlerType); - Size += sizeof(SMM_CORE_SMI_DATABASE_STRUCTURE); - SmiHandlerSize = GetSmmSmiHandlerDataOnSmiEntry(SmiEntry, (UINT8 *)SmiStruct + SmiStruct->Header.Length, ExpectedSize - Size, &SmiHandlerCount); - SmiStruct->HandlerCount = SmiHandlerCount; - Size += SmiHandlerSize; + SmiStruct->Header.Length = sizeof (SMM_CORE_SMI_DATABASE_STRUCTURE); + SmiStruct->Header.Revision = SMM_CORE_SMI_DATABASE_REVISION; + SmiStruct->HandlerCategory = HandlerCategory; + CopyGuid (&SmiStruct->HandlerType, &SmiEntry->HandlerType); + Size += sizeof (SMM_CORE_SMI_DATABASE_STRUCTURE); + SmiHandlerSize = GetSmmSmiHandlerDataOnSmiEntry (SmiEntry, (UINT8 *)SmiStruct + SmiStruct->Header.Length, ExpectedSize - Size, &SmiHandlerCount); + SmiStruct->HandlerCount = SmiHandlerCount; + Size += SmiHandlerSize; SmiStruct->Header.Length += (UINT32)SmiHandlerSize; - SmiStruct = (VOID *)((UINTN)SmiStruct + SmiStruct->Header.Length); + SmiStruct = (VOID *)((UINTN)SmiStruct + SmiStruct->Header.Length); } + if (ExpectedSize != Size) { return 0; } + return Size; } @@ -787,8 +822,8 @@ GetSmmSmiDatabaseData( @retval EFI_INVALID_PARAMETER the database size mismatch. **/ EFI_STATUS -GetSmiHandlerProfileDatabaseData( - IN OUT VOID *Data +GetSmiHandlerProfileDatabaseData ( + IN OUT VOID *Data ) { UINTN SmmImageDatabaseSize; @@ -796,25 +831,28 @@ GetSmiHandlerProfileDatabaseData( UINTN SmmRootSmiDatabaseSize; UINTN SmmHardwareSmiDatabaseSize; - DEBUG((DEBUG_VERBOSE, "GetSmiHandlerProfileDatabaseData\n")); - SmmImageDatabaseSize = GetSmmImageDatabaseData(Data, mSmmImageDatabaseSize); + DEBUG ((DEBUG_VERBOSE, "GetSmiHandlerProfileDatabaseData\n")); + SmmImageDatabaseSize = GetSmmImageDatabaseData (Data, mSmmImageDatabaseSize); if (SmmImageDatabaseSize != mSmmImageDatabaseSize) { - DEBUG((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmImageDatabaseSize mismatch!\n")); + DEBUG ((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmImageDatabaseSize mismatch!\n")); return EFI_INVALID_PARAMETER; } - SmmRootSmiDatabaseSize = GetSmmSmiDatabaseData(mSmmCoreRootSmiEntryList, SmmCoreSmiHandlerCategoryRootHandler, (UINT8 *)Data + SmmImageDatabaseSize, mSmmRootSmiDatabaseSize); + + SmmRootSmiDatabaseSize = GetSmmSmiDatabaseData (mSmmCoreRootSmiEntryList, SmmCoreSmiHandlerCategoryRootHandler, (UINT8 *)Data + SmmImageDatabaseSize, mSmmRootSmiDatabaseSize); if (SmmRootSmiDatabaseSize != mSmmRootSmiDatabaseSize) { - DEBUG((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmRootSmiDatabaseSize mismatch!\n")); + DEBUG ((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmRootSmiDatabaseSize mismatch!\n")); return EFI_INVALID_PARAMETER; } - SmmSmiDatabaseSize = GetSmmSmiDatabaseData(mSmmCoreSmiEntryList, SmmCoreSmiHandlerCategoryGuidHandler, (UINT8 *)Data + SmmImageDatabaseSize + mSmmRootSmiDatabaseSize, mSmmSmiDatabaseSize); + + SmmSmiDatabaseSize = GetSmmSmiDatabaseData (mSmmCoreSmiEntryList, SmmCoreSmiHandlerCategoryGuidHandler, (UINT8 *)Data + SmmImageDatabaseSize + mSmmRootSmiDatabaseSize, mSmmSmiDatabaseSize); if (SmmSmiDatabaseSize != mSmmSmiDatabaseSize) { - DEBUG((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmSmiDatabaseSize mismatch!\n")); + DEBUG ((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmSmiDatabaseSize mismatch!\n")); return EFI_INVALID_PARAMETER; } - SmmHardwareSmiDatabaseSize = GetSmmSmiDatabaseData(mSmmCoreHardwareSmiEntryList, SmmCoreSmiHandlerCategoryHardwareHandler, (UINT8 *)Data + SmmImageDatabaseSize + SmmRootSmiDatabaseSize + SmmSmiDatabaseSize, mSmmHardwareSmiDatabaseSize); + + SmmHardwareSmiDatabaseSize = GetSmmSmiDatabaseData (mSmmCoreHardwareSmiEntryList, SmmCoreSmiHandlerCategoryHardwareHandler, (UINT8 *)Data + SmmImageDatabaseSize + SmmRootSmiDatabaseSize + SmmSmiDatabaseSize, mSmmHardwareSmiDatabaseSize); if (SmmHardwareSmiDatabaseSize != mSmmHardwareSmiDatabaseSize) { - DEBUG((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmHardwareSmiDatabaseSize mismatch!\n")); + DEBUG ((DEBUG_ERROR, "GetSmiHandlerProfileDatabaseData - SmmHardwareSmiDatabaseSize mismatch!\n")); return EFI_INVALID_PARAMETER; } @@ -825,19 +863,21 @@ GetSmiHandlerProfileDatabaseData( build SMI handler profile database. **/ VOID -BuildSmiHandlerProfileDatabase( +BuildSmiHandlerProfileDatabase ( VOID ) { EFI_STATUS Status; - mSmiHandlerProfileDatabaseSize = GetSmiHandlerProfileDatabaseSize(); - mSmiHandlerProfileDatabase = AllocatePool(mSmiHandlerProfileDatabaseSize); + + mSmiHandlerProfileDatabaseSize = GetSmiHandlerProfileDatabaseSize (); + mSmiHandlerProfileDatabase = AllocatePool (mSmiHandlerProfileDatabaseSize); if (mSmiHandlerProfileDatabase == NULL) { return; } - Status = GetSmiHandlerProfileDatabaseData(mSmiHandlerProfileDatabase); - if (EFI_ERROR(Status)) { - FreePool(mSmiHandlerProfileDatabase); + + Status = GetSmiHandlerProfileDatabaseData (mSmiHandlerProfileDatabase); + if (EFI_ERROR (Status)) { + FreePool (mSmiHandlerProfileDatabase); mSmiHandlerProfileDatabase = NULL; } } @@ -853,21 +893,22 @@ BuildSmiHandlerProfileDatabase( **/ VOID -SmiHandlerProfileCopyData( - OUT VOID *DataBuffer, - IN OUT UINT64 *DataSize, - IN OUT UINT64 *DataOffset +SmiHandlerProfileCopyData ( + OUT VOID *DataBuffer, + IN OUT UINT64 *DataSize, + IN OUT UINT64 *DataOffset ) { if (*DataOffset >= mSmiHandlerProfileDatabaseSize) { *DataOffset = mSmiHandlerProfileDatabaseSize; return; } + if (mSmiHandlerProfileDatabaseSize - *DataOffset < *DataSize) { *DataSize = mSmiHandlerProfileDatabaseSize - *DataOffset; } - CopyMem( + CopyMem ( DataBuffer, (UINT8 *)mSmiHandlerProfileDatabase + *DataOffset, (UINTN)*DataSize @@ -882,16 +923,16 @@ SmiHandlerProfileCopyData( **/ VOID -SmiHandlerProfileHandlerGetInfo( - IN SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *SmiHandlerProfileParameterGetInfo +SmiHandlerProfileHandlerGetInfo ( + IN SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *SmiHandlerProfileParameterGetInfo ) { - BOOLEAN SmiHandlerProfileRecordingStatus; + BOOLEAN SmiHandlerProfileRecordingStatus; - SmiHandlerProfileRecordingStatus = mSmiHandlerProfileRecordingStatus; + SmiHandlerProfileRecordingStatus = mSmiHandlerProfileRecordingStatus; mSmiHandlerProfileRecordingStatus = FALSE; - SmiHandlerProfileParameterGetInfo->DataSize = mSmiHandlerProfileDatabaseSize; + SmiHandlerProfileParameterGetInfo->DataSize = mSmiHandlerProfileDatabaseSize; SmiHandlerProfileParameterGetInfo->Header.ReturnStatus = 0; mSmiHandlerProfileRecordingStatus = SmiHandlerProfileRecordingStatus; @@ -904,29 +945,29 @@ SmiHandlerProfileHandlerGetInfo( **/ VOID -SmiHandlerProfileHandlerGetDataByOffset( - IN SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *SmiHandlerProfileParameterGetDataByOffset +SmiHandlerProfileHandlerGetDataByOffset ( + IN SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *SmiHandlerProfileParameterGetDataByOffset ) { - SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET SmiHandlerProfileGetDataByOffset; - BOOLEAN SmiHandlerProfileRecordingStatus; + SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET SmiHandlerProfileGetDataByOffset; + BOOLEAN SmiHandlerProfileRecordingStatus; - SmiHandlerProfileRecordingStatus = mSmiHandlerProfileRecordingStatus; + SmiHandlerProfileRecordingStatus = mSmiHandlerProfileRecordingStatus; mSmiHandlerProfileRecordingStatus = FALSE; - CopyMem(&SmiHandlerProfileGetDataByOffset, SmiHandlerProfileParameterGetDataByOffset, sizeof(SmiHandlerProfileGetDataByOffset)); + CopyMem (&SmiHandlerProfileGetDataByOffset, SmiHandlerProfileParameterGetDataByOffset, sizeof (SmiHandlerProfileGetDataByOffset)); // // Sanity check // - if (!SmmIsBufferOutsideSmmValid((UINTN)SmiHandlerProfileGetDataByOffset.DataBuffer, (UINTN)SmiHandlerProfileGetDataByOffset.DataSize)) { - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandlerGetDataByOffset: SMI handler profile get data in SMRAM or overflow!\n")); + if (!SmmIsBufferOutsideSmmValid ((UINTN)SmiHandlerProfileGetDataByOffset.DataBuffer, (UINTN)SmiHandlerProfileGetDataByOffset.DataSize)) { + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandlerGetDataByOffset: SMI handler profile get data in SMRAM or overflow!\n")); SmiHandlerProfileParameterGetDataByOffset->Header.ReturnStatus = (UINT64)(INT64)(INTN)EFI_ACCESS_DENIED; goto Done; } - SmiHandlerProfileCopyData((VOID *)(UINTN)SmiHandlerProfileGetDataByOffset.DataBuffer, &SmiHandlerProfileGetDataByOffset.DataSize, &SmiHandlerProfileGetDataByOffset.DataOffset); - CopyMem(SmiHandlerProfileParameterGetDataByOffset, &SmiHandlerProfileGetDataByOffset, sizeof(SmiHandlerProfileGetDataByOffset)); + SmiHandlerProfileCopyData ((VOID *)(UINTN)SmiHandlerProfileGetDataByOffset.DataBuffer, &SmiHandlerProfileGetDataByOffset.DataSize, &SmiHandlerProfileGetDataByOffset.DataOffset); + CopyMem (SmiHandlerProfileParameterGetDataByOffset, &SmiHandlerProfileGetDataByOffset, sizeof (SmiHandlerProfileGetDataByOffset)); SmiHandlerProfileParameterGetDataByOffset->Header.ReturnStatus = 0; Done: @@ -950,17 +991,17 @@ Done: **/ EFI_STATUS EFIAPI -SmiHandlerProfileHandler( +SmiHandlerProfileHandler ( IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL ) { - SMI_HANDLER_PROFILE_PARAMETER_HEADER *SmiHandlerProfileParameterHeader; - UINTN TempCommBufferSize; + SMI_HANDLER_PROFILE_PARAMETER_HEADER *SmiHandlerProfileParameterHeader; + UINTN TempCommBufferSize; - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler Enter\n")); + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler Enter\n")); if (mSmiHandlerProfileDatabase == NULL) { return EFI_SUCCESS; @@ -969,47 +1010,49 @@ SmiHandlerProfileHandler( // // If input is invalid, stop processing this SMI // - if (CommBuffer == NULL || CommBufferSize == NULL) { + if ((CommBuffer == NULL) || (CommBufferSize == NULL)) { return EFI_SUCCESS; } TempCommBufferSize = *CommBufferSize; - if (TempCommBufferSize < sizeof(SMI_HANDLER_PROFILE_PARAMETER_HEADER)) { - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); + if (TempCommBufferSize < sizeof (SMI_HANDLER_PROFILE_PARAMETER_HEADER)) { + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); return EFI_SUCCESS; } - if (!SmmIsBufferOutsideSmmValid((UINTN)CommBuffer, TempCommBufferSize)) { - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer in SMRAM or overflow!\n")); + if (!SmmIsBufferOutsideSmmValid ((UINTN)CommBuffer, TempCommBufferSize)) { + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer in SMRAM or overflow!\n")); return EFI_SUCCESS; } - SmiHandlerProfileParameterHeader = (SMI_HANDLER_PROFILE_PARAMETER_HEADER *)((UINTN)CommBuffer); + SmiHandlerProfileParameterHeader = (SMI_HANDLER_PROFILE_PARAMETER_HEADER *)((UINTN)CommBuffer); SmiHandlerProfileParameterHeader->ReturnStatus = (UINT64)-1; switch (SmiHandlerProfileParameterHeader->Command) { - case SMI_HANDLER_PROFILE_COMMAND_GET_INFO: - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandlerGetInfo\n")); - if (TempCommBufferSize != sizeof(SMI_HANDLER_PROFILE_PARAMETER_GET_INFO)) { - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - SmiHandlerProfileHandlerGetInfo((SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *)(UINTN)CommBuffer); - break; - case SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET: - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandlerGetDataByOffset\n")); - if (TempCommBufferSize != sizeof(SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET)) { - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - SmiHandlerProfileHandlerGetDataByOffset((SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *)(UINTN)CommBuffer); - break; - default: - break; + case SMI_HANDLER_PROFILE_COMMAND_GET_INFO: + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandlerGetInfo\n")); + if (TempCommBufferSize != sizeof (SMI_HANDLER_PROFILE_PARAMETER_GET_INFO)) { + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + SmiHandlerProfileHandlerGetInfo ((SMI_HANDLER_PROFILE_PARAMETER_GET_INFO *)(UINTN)CommBuffer); + break; + case SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET: + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandlerGetDataByOffset\n")); + if (TempCommBufferSize != sizeof (SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET)) { + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + SmiHandlerProfileHandlerGetDataByOffset ((SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET *)(UINTN)CommBuffer); + break; + default: + break; } - DEBUG((DEBUG_ERROR, "SmiHandlerProfileHandler Exit\n")); + DEBUG ((DEBUG_ERROR, "SmiHandlerProfileHandler Exit\n")); return EFI_SUCCESS; } @@ -1022,8 +1065,8 @@ RegisterSmiHandlerProfileHandler ( VOID ) { - EFI_STATUS Status; - EFI_HANDLE DispatchHandle; + EFI_STATUS Status; + EFI_HANDLE DispatchHandle; Status = gSmst->SmiHandlerRegister ( SmiHandlerProfileHandler, @@ -1032,7 +1075,7 @@ RegisterSmiHandlerProfileHandler ( ); ASSERT_EFI_ERROR (Status); - BuildSmiHandlerProfileDatabase(); + BuildSmiHandlerProfileDatabase (); } /** @@ -1059,8 +1102,8 @@ SmmCoreFindHardwareSmiEntry ( SmiEntry = NULL; for (Link = mHardwareSmiEntryList.ForwardLink; Link != &mHardwareSmiEntryList; - Link = Link->ForwardLink) { - + Link = Link->ForwardLink) + { Item = CR (Link, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE); if (CompareGuid (&Item->HandlerType, HandlerType)) { // @@ -1076,7 +1119,7 @@ SmmCoreFindHardwareSmiEntry ( // allocate a new entry // if ((SmiEntry == NULL) && Create) { - SmiEntry = AllocatePool (sizeof(SMI_ENTRY)); + SmiEntry = AllocatePool (sizeof (SMI_ENTRY)); if (SmiEntry != NULL) { // // Initialize new SMI entry structure @@ -1091,6 +1134,7 @@ SmmCoreFindHardwareSmiEntry ( InsertTailList (&mHardwareSmiEntryList, &SmiEntry->AllEntries); } } + return SmiEntry; } @@ -1105,23 +1149,24 @@ SmmCoreFindHardwareSmiEntry ( **/ SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT * ConvertSmiHandlerUsbContext ( - IN EFI_SMM_USB_REGISTER_CONTEXT *UsbContext, - IN UINTN UsbContextSize, - OUT UINTN *SmiHandlerUsbContextSize + IN EFI_SMM_USB_REGISTER_CONTEXT *UsbContext, + IN UINTN UsbContextSize, + OUT UINTN *SmiHandlerUsbContextSize ) { UINTN DevicePathSize; SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT *SmiHandlerUsbContext; - ASSERT (UsbContextSize == sizeof(EFI_SMM_USB_REGISTER_CONTEXT)); + ASSERT (UsbContextSize == sizeof (EFI_SMM_USB_REGISTER_CONTEXT)); - DevicePathSize = GetDevicePathSize (UsbContext->Device); + DevicePathSize = GetDevicePathSize (UsbContext->Device); SmiHandlerUsbContext = AllocatePool (sizeof (SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT) + DevicePathSize); if (SmiHandlerUsbContext == NULL) { *SmiHandlerUsbContextSize = 0; return NULL; } - SmiHandlerUsbContext->Type = UsbContext->Type; + + SmiHandlerUsbContext->Type = UsbContext->Type; SmiHandlerUsbContext->DevicePathSize = (UINT32)DevicePathSize; CopyMem (SmiHandlerUsbContext + 1, UsbContext->Device, DevicePathSize); *SmiHandlerUsbContextSize = sizeof (SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT) + DevicePathSize; @@ -1139,22 +1184,23 @@ ConvertSmiHandlerUsbContext ( **/ SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT * ConvertSmiHandlerSwContext ( - IN EFI_SMM_SW_REGISTER_CONTEXT *SwContext, - IN UINTN SwContextSize, - OUT UINTN *SmiHandlerSwContextSize + IN EFI_SMM_SW_REGISTER_CONTEXT *SwContext, + IN UINTN SwContextSize, + OUT UINTN *SmiHandlerSwContextSize ) { SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT *SmiHandlerSwContext; - ASSERT (SwContextSize == sizeof(EFI_SMM_SW_REGISTER_CONTEXT)); + ASSERT (SwContextSize == sizeof (EFI_SMM_SW_REGISTER_CONTEXT)); SmiHandlerSwContext = AllocatePool (sizeof (SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT)); if (SmiHandlerSwContext == NULL) { *SmiHandlerSwContextSize = 0; return NULL; } + SmiHandlerSwContext->SwSmiInputValue = SwContext->SwSmiInputValue; - *SmiHandlerSwContextSize = sizeof (SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT); + *SmiHandlerSwContextSize = sizeof (SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT); return SmiHandlerSwContext; } @@ -1181,12 +1227,12 @@ ConvertSmiHandlerSwContext ( EFI_STATUS EFIAPI SmiHandlerProfileRegisterHandler ( - IN SMI_HANDLER_PROFILE_PROTOCOL *This, - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN PHYSICAL_ADDRESS CallerAddress, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN SMI_HANDLER_PROFILE_PROTOCOL *This, + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN PHYSICAL_ADDRESS CallerAddress, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ) { SMI_HANDLER *SmiHandler; @@ -1194,7 +1240,8 @@ SmiHandlerProfileRegisterHandler ( LIST_ENTRY *List; if (((ContextSize == 0) && (Context != NULL)) || - ((ContextSize != 0) && (Context == NULL))) { + ((ContextSize != 0) && (Context == NULL))) + { return EFI_INVALID_PARAMETER; } @@ -1203,10 +1250,10 @@ SmiHandlerProfileRegisterHandler ( return EFI_OUT_OF_RESOURCES; } - SmiHandler->Signature = SMI_HANDLER_SIGNATURE; - SmiHandler->Handler = Handler; - SmiHandler->CallerAddr = (UINTN)CallerAddress; - SmiHandler->Context = Context; + SmiHandler->Signature = SMI_HANDLER_SIGNATURE; + SmiHandler->Handler = Handler; + SmiHandler->CallerAddr = (UINTN)CallerAddress; + SmiHandler->Context = Context; SmiHandler->ContextSize = ContextSize; if (Context != NULL) { @@ -1218,6 +1265,7 @@ SmiHandlerProfileRegisterHandler ( SmiHandler->Context = AllocateCopyPool (ContextSize, Context); } } + if (SmiHandler->Context == NULL) { SmiHandler->ContextSize = 0; } @@ -1227,6 +1275,7 @@ SmiHandlerProfileRegisterHandler ( if (SmiHandler->Context != NULL) { FreePool (SmiHandler->Context); } + FreePool (SmiHandler); return EFI_OUT_OF_RESOURCES; } @@ -1259,11 +1308,11 @@ SmiHandlerProfileRegisterHandler ( EFI_STATUS EFIAPI SmiHandlerProfileUnregisterHandler ( - IN SMI_HANDLER_PROFILE_PROTOCOL *This, - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN SMI_HANDLER_PROFILE_PROTOCOL *This, + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ) { LIST_ENTRY *Link; @@ -1275,7 +1324,8 @@ SmiHandlerProfileUnregisterHandler ( UINTN SearchContextSize; if (((ContextSize == 0) && (Context != NULL)) || - ((ContextSize != 0) && (Context == NULL))) { + ((ContextSize != 0) && (Context == NULL))) + { return EFI_INVALID_PARAMETER; } @@ -1284,7 +1334,7 @@ SmiHandlerProfileUnregisterHandler ( return EFI_NOT_FOUND; } - SearchContext = Context; + SearchContext = Context; SearchContextSize = ContextSize; if (Context != NULL) { if (CompareGuid (HandlerGuid, &gEfiSmmUsbDispatch2ProtocolGuid)) { @@ -1295,12 +1345,13 @@ SmiHandlerProfileUnregisterHandler ( } TargetSmiHandler = NULL; - Head = &SmiEntry->SmiHandlers; + Head = &SmiEntry->SmiHandlers; for (Link = Head->ForwardLink; Link != Head; Link = Link->ForwardLink) { SmiHandler = CR (Link, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE); if (SmiHandler->Handler == Handler) { if ((SearchContext == NULL) || - ((SearchContextSize == SmiHandler->ContextSize) && (CompareMem (SearchContext, SmiHandler->Context, SearchContextSize) == 0))) { + ((SearchContextSize == SmiHandler->ContextSize) && (CompareMem (SearchContext, SmiHandler->Context, SearchContextSize) == 0))) + { TargetSmiHandler = SmiHandler; break; } @@ -1316,12 +1367,14 @@ SmiHandlerProfileUnregisterHandler ( if (TargetSmiHandler == NULL) { return EFI_NOT_FOUND; } + SmiHandler = TargetSmiHandler; RemoveEntryList (&SmiHandler->Link); if (SmiHandler->Context != NULL) { FreePool (SmiHandler->Context); } + FreePool (SmiHandler); if (IsListEmpty (&SmiEntry->SmiHandlers)) { diff --git a/MdeModulePkg/Core/PiSmmCore/SmramProfileRecord.c b/MdeModulePkg/Core/PiSmmCore/SmramProfileRecord.c index 002a8e4360..b437e4c433 100644 --- a/MdeModulePkg/Core/PiSmmCore/SmramProfileRecord.c +++ b/MdeModulePkg/Core/PiSmmCore/SmramProfileRecord.c @@ -8,16 +8,16 @@ #include "PiSmmCore.h" -#define IS_SMRAM_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT1) != 0) -#define IS_UEFI_MEMORY_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT0) != 0) +#define IS_SMRAM_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT1) != 0) +#define IS_UEFI_MEMORY_PROFILE_ENABLED ((PcdGet8 (PcdMemoryProfilePropertyMask) & BIT0) != 0) #define GET_OCCUPIED_SIZE(ActualSize, Alignment) \ ((ActualSize) + (((Alignment) - ((ActualSize) & ((Alignment) - 1))) & ((Alignment) - 1))) typedef struct { - UINT32 Signature; - MEMORY_PROFILE_CONTEXT Context; - LIST_ENTRY *DriverInfoList; + UINT32 Signature; + MEMORY_PROFILE_CONTEXT Context; + LIST_ENTRY *DriverInfoList; } MEMORY_PROFILE_CONTEXT_DATA; typedef struct { @@ -29,10 +29,10 @@ typedef struct { } MEMORY_PROFILE_DRIVER_INFO_DATA; typedef struct { - UINT32 Signature; - MEMORY_PROFILE_ALLOC_INFO AllocInfo; - CHAR8 *ActionString; - LIST_ENTRY Link; + UINT32 Signature; + MEMORY_PROFILE_ALLOC_INFO AllocInfo; + CHAR8 *ActionString; + LIST_ENTRY Link; } MEMORY_PROFILE_ALLOC_INFO_DATA; // @@ -40,7 +40,7 @@ typedef struct { // #define SMRAM_INFO_DUMP_PAGE_THRESHOLD 4 -GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_FREE_MEMORY mSmramFreeMemory = { +GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_FREE_MEMORY mSmramFreeMemory = { { MEMORY_PROFILE_FREE_MEMORY_SIGNATURE, sizeof (MEMORY_PROFILE_FREE_MEMORY), @@ -50,8 +50,8 @@ GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_FREE_MEMORY mSmramFreeMemory = { 0 }; -GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mImageQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageQueue); -GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mSmramProfileContext = { +GLOBAL_REMOVE_IF_UNREFERENCED LIST_ENTRY mImageQueue = INITIALIZE_LIST_HEAD_VARIABLE (mImageQueue); +GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mSmramProfileContext = { MEMORY_PROFILE_CONTEXT_SIGNATURE, { { @@ -61,21 +61,21 @@ GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA mSmramProfileContext = }, 0, 0, - {0}, - {0}, + { 0 }, + { 0 }, 0, 0, 0 }, &mImageQueue, }; -GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA *mSmramProfileContextPtr = NULL; +GLOBAL_REMOVE_IF_UNREFERENCED MEMORY_PROFILE_CONTEXT_DATA *mSmramProfileContextPtr = NULL; -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramReadyToLock; -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramProfileGettingStatus = FALSE; -GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramProfileRecordingEnable = MEMORY_PROFILE_RECORDING_DISABLE; -GLOBAL_REMOVE_IF_UNREFERENCED EFI_DEVICE_PATH_PROTOCOL *mSmramProfileDriverPath; -GLOBAL_REMOVE_IF_UNREFERENCED UINTN mSmramProfileDriverPathSize; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramReadyToLock; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramProfileGettingStatus = FALSE; +GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mSmramProfileRecordingEnable = MEMORY_PROFILE_RECORDING_DISABLE; +GLOBAL_REMOVE_IF_UNREFERENCED EFI_DEVICE_PATH_PROTOCOL *mSmramProfileDriverPath; +GLOBAL_REMOVE_IF_UNREFERENCED UINTN mSmramProfileDriverPathSize; /** Dump SMRAM information. @@ -105,7 +105,7 @@ EFIAPI SmramProfileProtocolGetData ( IN EDKII_SMM_MEMORY_PROFILE_PROTOCOL *This, IN OUT UINT64 *ProfileSize, - OUT VOID *ProfileBuffer + OUT VOID *ProfileBuffer ); /** @@ -226,7 +226,7 @@ SmramProfileProtocolRecord ( IN CHAR8 *ActionString OPTIONAL ); -GLOBAL_REMOVE_IF_UNREFERENCED EDKII_SMM_MEMORY_PROFILE_PROTOCOL mSmmProfileProtocol = { +GLOBAL_REMOVE_IF_UNREFERENCED EDKII_SMM_MEMORY_PROFILE_PROTOCOL mSmmProfileProtocol = { SmramProfileProtocolGetData, SmramProfileProtocolRegisterImage, SmramProfileProtocolUnregisterImage, @@ -269,22 +269,22 @@ InternalPeCoffGetSubsystem ( ASSERT (Pe32Data != NULL); - DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data; + DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, so read the PE header after the DOS image header. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) ((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff)); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff)); } else { // // DOS image header is not present, so PE header is at the image base. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) Pe32Data; + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data; } if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) { return Hdr.Te->Subsystem; - } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { + } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { Magic = Hdr.Pe32->OptionalHeader.Magic; if (Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) { return Hdr.Pe32->OptionalHeader.Subsystem; @@ -319,23 +319,23 @@ InternalPeCoffGetEntryPoint ( OUT VOID **EntryPoint ) { - EFI_IMAGE_DOS_HEADER *DosHdr; - EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; + EFI_IMAGE_DOS_HEADER *DosHdr; + EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION Hdr; ASSERT (Pe32Data != NULL); ASSERT (EntryPoint != NULL); - DosHdr = (EFI_IMAGE_DOS_HEADER *) Pe32Data; + DosHdr = (EFI_IMAGE_DOS_HEADER *)Pe32Data; if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) { // // DOS image header is present, so read the PE header after the DOS image header. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) ((UINTN) Pe32Data + (UINTN) ((DosHdr->e_lfanew) & 0x0ffff)); + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINTN)Pe32Data + (UINTN)((DosHdr->e_lfanew) & 0x0ffff)); } else { // // DOS image header is not present, so PE header is at the image base. // - Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *) Pe32Data; + Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)Pe32Data; } // @@ -343,10 +343,10 @@ InternalPeCoffGetEntryPoint ( // AddressOfEntryPoint is common for PE32 & PE32+ // if (Hdr.Te->Signature == EFI_TE_IMAGE_HEADER_SIGNATURE) { - *EntryPoint = (VOID *) ((UINTN) Pe32Data + (UINTN) (Hdr.Te->AddressOfEntryPoint & 0x0ffffffff) + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize); + *EntryPoint = (VOID *)((UINTN)Pe32Data + (UINTN)(Hdr.Te->AddressOfEntryPoint & 0x0ffffffff) + sizeof (EFI_TE_IMAGE_HEADER) - Hdr.Te->StrippedSize); return RETURN_SUCCESS; } else if (Hdr.Pe32->Signature == EFI_IMAGE_NT_SIGNATURE) { - *EntryPoint = (VOID *) ((UINTN) Pe32Data + (UINTN) (Hdr.Pe32->OptionalHeader.AddressOfEntryPoint & 0x0ffffffff)); + *EntryPoint = (VOID *)((UINTN)Pe32Data + (UINTN)(Hdr.Pe32->OptionalHeader.AddressOfEntryPoint & 0x0ffffffff)); return RETURN_SUCCESS; } @@ -369,30 +369,30 @@ InternalPeCoffGetEntryPoint ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * BuildDriverInfo ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize, - IN PHYSICAL_ADDRESS EntryPoint, - IN UINT16 ImageSubsystem, - IN EFI_FV_FILETYPE FileType + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize, + IN PHYSICAL_ADDRESS EntryPoint, + IN UINT16 ImageSubsystem, + IN EFI_FV_FILETYPE FileType ) { - EFI_STATUS Status; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - VOID *EntryPointInImage; - CHAR8 *PdbString; - UINTN PdbSize; - UINTN PdbOccupiedSize; - - PdbSize = 0; + EFI_STATUS Status; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + VOID *EntryPointInImage; + CHAR8 *PdbString; + UINTN PdbSize; + UINTN PdbOccupiedSize; + + PdbSize = 0; PdbOccupiedSize = 0; - PdbString = NULL; + PdbString = NULL; if (ImageBase != 0) { - PdbString = PeCoffLoaderGetPdbPointer ((VOID*) (UINTN) ImageBase); + PdbString = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageBase); if (PdbString != NULL) { - PdbSize = AsciiStrSize (PdbString); + PdbSize = AsciiStrSize (PdbString); PdbOccupiedSize = GET_OCCUPIED_SIZE (PdbSize, sizeof (UINT64)); } } @@ -403,53 +403,56 @@ BuildDriverInfo ( Status = SmmInternalAllocatePool ( EfiRuntimeServicesData, sizeof (*DriverInfoData) + sizeof (LIST_ENTRY) + PdbSize, - (VOID **) &DriverInfoData + (VOID **)&DriverInfoData ); if (EFI_ERROR (Status)) { return NULL; } + ASSERT (DriverInfoData != NULL); ZeroMem (DriverInfoData, sizeof (*DriverInfoData)); - DriverInfo = &DriverInfoData->DriverInfo; - DriverInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; + DriverInfo = &DriverInfoData->DriverInfo; + DriverInfoData->Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; DriverInfo->Header.Signature = MEMORY_PROFILE_DRIVER_INFO_SIGNATURE; - DriverInfo->Header.Length = (UINT16) (sizeof (MEMORY_PROFILE_DRIVER_INFO) + PdbOccupiedSize); - DriverInfo->Header.Revision = MEMORY_PROFILE_DRIVER_INFO_REVISION; + DriverInfo->Header.Length = (UINT16)(sizeof (MEMORY_PROFILE_DRIVER_INFO) + PdbOccupiedSize); + DriverInfo->Header.Revision = MEMORY_PROFILE_DRIVER_INFO_REVISION; if (FileName != NULL) { CopyMem (&DriverInfo->FileName, FileName, sizeof (EFI_GUID)); } - DriverInfo->ImageBase = ImageBase; - DriverInfo->ImageSize = ImageSize; - DriverInfo->EntryPoint = EntryPoint; + + DriverInfo->ImageBase = ImageBase; + DriverInfo->ImageSize = ImageSize; + DriverInfo->EntryPoint = EntryPoint; DriverInfo->ImageSubsystem = ImageSubsystem; if ((EntryPoint != 0) && ((EntryPoint < ImageBase) || (EntryPoint >= (ImageBase + ImageSize)))) { // // If the EntryPoint is not in the range of image buffer, it should come from emulation environment. // So patch ImageBuffer here to align the EntryPoint. // - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageBase, &EntryPointInImage); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageBase, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverInfo->ImageBase = ImageBase + EntryPoint - (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; + DriverInfo->ImageBase = ImageBase + EntryPoint - (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; } - DriverInfo->FileType = FileType; - DriverInfoData->AllocInfoList = (LIST_ENTRY *) (DriverInfoData + 1); + + DriverInfo->FileType = FileType; + DriverInfoData->AllocInfoList = (LIST_ENTRY *)(DriverInfoData + 1); InitializeListHead (DriverInfoData->AllocInfoList); - DriverInfo->CurrentUsage = 0; - DriverInfo->PeakUsage = 0; + DriverInfo->CurrentUsage = 0; + DriverInfo->PeakUsage = 0; DriverInfo->AllocRecordCount = 0; if (PdbSize != 0) { - DriverInfo->PdbStringOffset = (UINT16) sizeof (MEMORY_PROFILE_DRIVER_INFO); - DriverInfoData->PdbString = (CHAR8 *) (DriverInfoData->AllocInfoList + 1); + DriverInfo->PdbStringOffset = (UINT16)sizeof (MEMORY_PROFILE_DRIVER_INFO); + DriverInfoData->PdbString = (CHAR8 *)(DriverInfoData->AllocInfoList + 1); CopyMem (DriverInfoData->PdbString, PdbString, PdbSize); } else { DriverInfo->PdbStringOffset = 0; - DriverInfoData->PdbString = NULL; + DriverInfoData->PdbString = NULL; } InsertTailList (ContextData->DriverInfoList, &DriverInfoData->Link); - ContextData->Context.ImageCount ++; + ContextData->Context.ImageCount++; ContextData->Context.TotalImageSize += DriverInfo->ImageSize; return DriverInfoData; @@ -466,28 +469,27 @@ BuildDriverInfo ( **/ VOID RegisterImageToDxe ( - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize, - IN EFI_FV_FILETYPE FileType + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize, + IN EFI_FV_FILETYPE FileType ) { - EFI_STATUS Status; - EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; - UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + EFI_STATUS Status; + EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; if (IS_UEFI_MEMORY_PROFILE_ENABLED) { - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; - Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID **) &ProfileProtocol); + Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID **)&ProfileProtocol); if (!EFI_ERROR (Status)) { EfiInitializeFwVolDevicepathNode (FilePath, FileName); SetDevicePathEndNode (FilePath + 1); Status = ProfileProtocol->RegisterImage ( ProfileProtocol, - (EFI_DEVICE_PATH_PROTOCOL *) FilePath, + (EFI_DEVICE_PATH_PROTOCOL *)FilePath, ImageBase, ImageSize, FileType @@ -506,27 +508,26 @@ RegisterImageToDxe ( **/ VOID UnregisterImageFromDxe ( - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS ImageBase, - IN UINT64 ImageSize + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS ImageBase, + IN UINT64 ImageSize ) { - EFI_STATUS Status; - EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; - UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + EFI_STATUS Status; + EDKII_MEMORY_PROFILE_PROTOCOL *ProfileProtocol; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; if (IS_UEFI_MEMORY_PROFILE_ENABLED) { - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; - Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID *) &ProfileProtocol); + Status = gBS->LocateProtocol (&gEdkiiMemoryProfileGuid, NULL, (VOID *)&ProfileProtocol); if (!EFI_ERROR (Status)) { EfiInitializeFwVolDevicepathNode (FilePath, FileName); SetDevicePathEndNode (FilePath + 1); Status = ProfileProtocol->UnregisterImage ( ProfileProtocol, - (EFI_DEVICE_PATH_PROTOCOL *) FilePath, + (EFI_DEVICE_PATH_PROTOCOL *)FilePath, ImageBase, ImageSize ); @@ -545,13 +546,13 @@ UnregisterImageFromDxe ( **/ BOOLEAN NeedRecordThisDriver ( - IN EFI_DEVICE_PATH_PROTOCOL *DriverFilePath + IN EFI_DEVICE_PATH_PROTOCOL *DriverFilePath ) { - EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; - EFI_DEVICE_PATH_PROTOCOL *DevicePathInstance; - UINTN DevicePathSize; - UINTN FilePathSize; + EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePathInstance; + UINTN DevicePathSize; + UINTN FilePathSize; if (!IsDevicePathValid (mSmramProfileDriverPath, mSmramProfileDriverPathSize)) { // @@ -563,7 +564,7 @@ NeedRecordThisDriver ( // // Record FilePath without end node. // - FilePathSize = GetDevicePathSize (DriverFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL); + FilePathSize = GetDevicePathSize (DriverFilePath) - sizeof (EFI_DEVICE_PATH_PROTOCOL); DevicePathInstance = mSmramProfileDriverPath; do { @@ -580,14 +581,15 @@ NeedRecordThisDriver ( // DevicePathSize = (UINTN)TmpDevicePath - (UINTN)DevicePathInstance; if ((FilePathSize == DevicePathSize) && - (CompareMem (DriverFilePath, DevicePathInstance, DevicePathSize) == 0)) { + (CompareMem (DriverFilePath, DevicePathInstance, DevicePathSize) == 0)) + { return TRUE; } // // Get next instance // - DevicePathInstance = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)DevicePathInstance + DevicePathSize + DevicePathNodeLength(TmpDevicePath)); + DevicePathInstance = (EFI_DEVICE_PATH_PROTOCOL *)((UINTN)DevicePathInstance + DevicePathSize + DevicePathNodeLength (TmpDevicePath)); } while (DevicePathSubType (TmpDevicePath) != END_ENTIRE_DEVICE_PATH_SUBTYPE); return FALSE; @@ -604,30 +606,30 @@ NeedRecordThisDriver ( **/ BOOLEAN RegisterSmmCore ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData ) { - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - PHYSICAL_ADDRESS ImageBase; - UINT8 TempBuffer[sizeof(MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof(EFI_DEVICE_PATH_PROTOCOL)]; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + PHYSICAL_ADDRESS ImageBase; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) TempBuffer; + FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; EfiInitializeFwVolDevicepathNode (FilePath, &gEfiCallerIdGuid); SetDevicePathEndNode (FilePath + 1); - if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *) FilePath)) { + if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *)FilePath)) { return FALSE; } - ImageBase = gSmmCorePrivate->PiSmmCoreImageBase; + ImageBase = gSmmCorePrivate->PiSmmCoreImageBase; DriverInfoData = BuildDriverInfo ( ContextData, &gEfiCallerIdGuid, ImageBase, gSmmCorePrivate->PiSmmCoreImageSize, gSmmCorePrivate->PiSmmCoreEntryPoint, - InternalPeCoffGetSubsystem ((VOID *) (UINTN) ImageBase), + InternalPeCoffGetSubsystem ((VOID *)(UINTN)ImageBase), EFI_FV_FILETYPE_SMM_CORE ); if (DriverInfoData == NULL) { @@ -646,7 +648,7 @@ SmramProfileInit ( VOID ) { - MEMORY_PROFILE_CONTEXT_DATA *SmramProfileContext; + MEMORY_PROFILE_CONTEXT_DATA *SmramProfileContext; RegisterImageToDxe ( &gEfiCallerIdGuid, @@ -670,9 +672,10 @@ SmramProfileInit ( } else { mSmramProfileRecordingEnable = MEMORY_PROFILE_RECORDING_ENABLE; } + mSmramProfileDriverPathSize = PcdGetSize (PcdMemoryProfileDriverPath); - mSmramProfileDriverPath = AllocateCopyPool (mSmramProfileDriverPathSize, PcdGetPtr (PcdMemoryProfileDriverPath)); - mSmramProfileContextPtr = &mSmramProfileContext; + mSmramProfileDriverPath = AllocateCopyPool (mSmramProfileDriverPathSize, PcdGetPtr (PcdMemoryProfileDriverPath)); + mSmramProfileContextPtr = &mSmramProfileContext; RegisterSmmCore (&mSmramProfileContext); @@ -688,8 +691,8 @@ SmramProfileInstallProtocol ( VOID ) { - EFI_HANDLE Handle; - EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_STATUS Status; if (!IS_SMRAM_PROFILE_ENABLED) { return; @@ -715,21 +718,22 @@ SmramProfileInstallProtocol ( **/ EFI_GUID * GetFileNameFromFilePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *ThisFilePath; - EFI_GUID *FileName; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *ThisFilePath; + EFI_GUID *FileName; FileName = NULL; if (FilePath != NULL) { - ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) FilePath; + ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)FilePath; while (!IsDevicePathEnd (ThisFilePath)) { FileName = EfiGetNameGuidFromFwVolDevicePathNode (ThisFilePath); if (FileName != NULL) { break; } - ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) NextDevicePathNode (ThisFilePath); + + ThisFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)NextDevicePathNode (ThisFilePath); } } @@ -750,14 +754,14 @@ GetFileNameFromFilePath ( **/ EFI_STATUS RegisterSmramProfileImage ( - IN EFI_SMM_DRIVER_ENTRY *DriverEntry, - IN BOOLEAN RegisterToDxe + IN EFI_SMM_DRIVER_ENTRY *DriverEntry, + IN BOOLEAN RegisterToDxe ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - UINT8 TempBuffer[sizeof(MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof(EFI_DEVICE_PATH_PROTOCOL)]; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; if (RegisterToDxe) { RegisterImageToDxe ( @@ -772,11 +776,11 @@ RegisterSmramProfileImage ( return EFI_UNSUPPORTED; } - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) TempBuffer; + FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; EfiInitializeFwVolDevicepathNode (FilePath, &DriverEntry->FileName); SetDevicePathEndNode (FilePath + 1); - if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *) FilePath)) { + if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *)FilePath)) { return EFI_UNSUPPORTED; } @@ -791,7 +795,7 @@ RegisterSmramProfileImage ( DriverEntry->ImageBuffer, EFI_PAGES_TO_SIZE (DriverEntry->NumberOfPage), DriverEntry->ImageEntryPoint, - InternalPeCoffGetSubsystem ((VOID *) (UINTN) DriverEntry->ImageBuffer), + InternalPeCoffGetSubsystem ((VOID *)(UINTN)DriverEntry->ImageBuffer), EFI_FV_FILETYPE_SMM ); if (DriverInfoData == NULL) { @@ -813,21 +817,22 @@ RegisterSmramProfileImage ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * GetMemoryProfileDriverInfoByFileNameAndAddress ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN EFI_GUID *FileName, - IN PHYSICAL_ADDRESS Address + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN EFI_GUID *FileName, + IN PHYSICAL_ADDRESS Address ) { - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - LIST_ENTRY *DriverLink; - LIST_ENTRY *DriverInfoList; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + LIST_ENTRY *DriverLink; + LIST_ENTRY *DriverInfoList; DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -837,7 +842,8 @@ GetMemoryProfileDriverInfoByFileNameAndAddress ( DriverInfo = &DriverInfoData->DriverInfo; if ((CompareGuid (&DriverInfo->FileName, FileName)) && (Address >= DriverInfo->ImageBase) && - (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) { + (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) + { return DriverInfoData; } } @@ -857,20 +863,21 @@ GetMemoryProfileDriverInfoByFileNameAndAddress ( **/ MEMORY_PROFILE_DRIVER_INFO_DATA * GetMemoryProfileDriverInfoFromAddress ( - IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, - IN PHYSICAL_ADDRESS Address + IN MEMORY_PROFILE_CONTEXT_DATA *ContextData, + IN PHYSICAL_ADDRESS Address ) { - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - LIST_ENTRY *DriverLink; - LIST_ENTRY *DriverInfoList; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + LIST_ENTRY *DriverLink; + LIST_ENTRY *DriverInfoList; DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -879,7 +886,8 @@ GetMemoryProfileDriverInfoFromAddress ( ); DriverInfo = &DriverInfoData->DriverInfo; if ((Address >= DriverInfo->ImageBase) && - (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) { + (Address < (DriverInfo->ImageBase + DriverInfo->ImageSize))) + { return DriverInfoData; } } @@ -905,14 +913,14 @@ UnregisterSmramProfileImage ( IN BOOLEAN UnregisterFromDxe ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - EFI_GUID *FileName; - PHYSICAL_ADDRESS ImageAddress; - VOID *EntryPointInImage; - UINT8 TempBuffer[sizeof(MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof(EFI_DEVICE_PATH_PROTOCOL)]; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + EFI_GUID *FileName; + PHYSICAL_ADDRESS ImageAddress; + VOID *EntryPointInImage; + UINT8 TempBuffer[sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + sizeof (EFI_DEVICE_PATH_PROTOCOL)]; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FilePath; if (UnregisterFromDxe) { UnregisterImageFromDxe ( @@ -926,11 +934,11 @@ UnregisterSmramProfileImage ( return EFI_UNSUPPORTED; } - FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) TempBuffer; + FilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)TempBuffer; EfiInitializeFwVolDevicepathNode (FilePath, &DriverEntry->FileName); SetDevicePathEndNode (FilePath + 1); - if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *) FilePath)) { + if (!NeedRecordThisDriver ((EFI_DEVICE_PATH_PROTOCOL *)FilePath)) { return EFI_UNSUPPORTED; } @@ -940,23 +948,26 @@ UnregisterSmramProfileImage ( } DriverInfoData = NULL; - FileName = &DriverEntry->FileName; - ImageAddress = DriverEntry->ImageBuffer; + FileName = &DriverEntry->FileName; + ImageAddress = DriverEntry->ImageBuffer; if ((DriverEntry->ImageEntryPoint < ImageAddress) || (DriverEntry->ImageEntryPoint >= (ImageAddress + EFI_PAGES_TO_SIZE (DriverEntry->NumberOfPage)))) { // // If the EntryPoint is not in the range of image buffer, it should come from emulation environment. // So patch ImageAddress here to align the EntryPoint. // - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) ImageAddress, &EntryPointInImage); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)ImageAddress, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - ImageAddress = ImageAddress + (UINTN) DriverEntry->ImageEntryPoint - (UINTN) EntryPointInImage; + ImageAddress = ImageAddress + (UINTN)DriverEntry->ImageEntryPoint - (UINTN)EntryPointInImage; } + if (FileName != NULL) { DriverInfoData = GetMemoryProfileDriverInfoByFileNameAndAddress (ContextData, FileName, ImageAddress); } + if (DriverInfoData == NULL) { DriverInfoData = GetMemoryProfileDriverInfoFromAddress (ContextData, ImageAddress); } + if (DriverInfoData == NULL) { return EFI_NOT_FOUND; } @@ -964,11 +975,11 @@ UnregisterSmramProfileImage ( ContextData->Context.TotalImageSize -= DriverInfoData->DriverInfo.ImageSize; // Keep the ImageBase for RVA calculation in Application. - //DriverInfoData->DriverInfo.ImageBase = 0; + // DriverInfoData->DriverInfo.ImageBase = 0; DriverInfoData->DriverInfo.ImageSize = 0; if (DriverInfoData->DriverInfo.PeakUsage == 0) { - ContextData->Context.ImageCount --; + ContextData->Context.ImageCount--; RemoveEntryList (&DriverInfoData->Link); // // Use SmmInternalFreePool() that will not update profile for this FreePool action. @@ -991,13 +1002,14 @@ UnregisterSmramProfileImage ( **/ BOOLEAN SmmCoreNeedRecordProfile ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - UINT64 TestBit; + UINT64 TestBit; - if (MemoryType != EfiRuntimeServicesCode && - MemoryType != EfiRuntimeServicesData) { + if ((MemoryType != EfiRuntimeServicesCode) && + (MemoryType != EfiRuntimeServicesData)) + { return FALSE; } @@ -1023,7 +1035,7 @@ SmmCoreNeedRecordProfile ( **/ EFI_MEMORY_TYPE GetProfileMemoryIndex ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { return MemoryType; @@ -1040,17 +1052,18 @@ SmramProfileUpdateFreePages ( IN MEMORY_PROFILE_CONTEXT_DATA *ContextData ) { - LIST_ENTRY *Node; - FREE_PAGE_LIST *Pages; - LIST_ENTRY *FreePageList; - UINTN NumberOfPages; + LIST_ENTRY *Node; + FREE_PAGE_LIST *Pages; + LIST_ENTRY *FreePageList; + UINTN NumberOfPages; NumberOfPages = 0; - FreePageList = &mSmmMemoryMap; + FreePageList = &mSmmMemoryMap; for (Node = FreePageList->BackLink; Node != FreePageList; - Node = Node->BackLink) { - Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); + Node = Node->BackLink) + { + Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); NumberOfPages += Pages->NumberOfPages; } @@ -1087,17 +1100,17 @@ SmmCoreUpdateProfileAllocate ( IN CHAR8 *ActionString OPTIONAL ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - EFI_MEMORY_TYPE ProfileMemoryIndex; - MEMORY_PROFILE_ACTION BasicAction; - UINTN ActionStringSize; - UINTN ActionStringOccupiedSize; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + EFI_MEMORY_TYPE ProfileMemoryIndex; + MEMORY_PROFILE_ACTION BasicAction; + UINTN ActionStringSize; + UINTN ActionStringOccupiedSize; BasicAction = Action & MEMORY_PROFILE_ACTION_BASIC_MASK; @@ -1111,10 +1124,10 @@ SmmCoreUpdateProfileAllocate ( return EFI_UNSUPPORTED; } - ActionStringSize = 0; + ActionStringSize = 0; ActionStringOccupiedSize = 0; if (ActionString != NULL) { - ActionStringSize = AsciiStrSize (ActionString); + ActionStringSize = AsciiStrSize (ActionString); ActionStringOccupiedSize = GET_OCCUPIED_SIZE (ActionStringSize, sizeof (UINT64)); } @@ -1122,48 +1135,49 @@ SmmCoreUpdateProfileAllocate ( // Use SmmInternalAllocatePool() that will not update profile for this AllocatePool action. // AllocInfoData = NULL; - Status = SmmInternalAllocatePool ( - EfiRuntimeServicesData, - sizeof (*AllocInfoData) + ActionStringSize, - (VOID **) &AllocInfoData - ); + Status = SmmInternalAllocatePool ( + EfiRuntimeServicesData, + sizeof (*AllocInfoData) + ActionStringSize, + (VOID **)&AllocInfoData + ); if (EFI_ERROR (Status)) { return EFI_OUT_OF_RESOURCES; } + ASSERT (AllocInfoData != NULL); // // Only update SequenceCount if and only if it is basic action. // if (Action == BasicAction) { - ContextData->Context.SequenceCount ++; - } - - AllocInfo = &AllocInfoData->AllocInfo; - AllocInfoData->Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; - AllocInfo->Header.Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; - AllocInfo->Header.Length = (UINT16) (sizeof (MEMORY_PROFILE_ALLOC_INFO) + ActionStringOccupiedSize); - AllocInfo->Header.Revision = MEMORY_PROFILE_ALLOC_INFO_REVISION; - AllocInfo->CallerAddress = CallerAddress; - AllocInfo->SequenceId = ContextData->Context.SequenceCount; - AllocInfo->Action = Action; - AllocInfo->MemoryType = MemoryType; - AllocInfo->Buffer = (PHYSICAL_ADDRESS) (UINTN) Buffer; - AllocInfo->Size = Size; + ContextData->Context.SequenceCount++; + } + + AllocInfo = &AllocInfoData->AllocInfo; + AllocInfoData->Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; + AllocInfo->Header.Signature = MEMORY_PROFILE_ALLOC_INFO_SIGNATURE; + AllocInfo->Header.Length = (UINT16)(sizeof (MEMORY_PROFILE_ALLOC_INFO) + ActionStringOccupiedSize); + AllocInfo->Header.Revision = MEMORY_PROFILE_ALLOC_INFO_REVISION; + AllocInfo->CallerAddress = CallerAddress; + AllocInfo->SequenceId = ContextData->Context.SequenceCount; + AllocInfo->Action = Action; + AllocInfo->MemoryType = MemoryType; + AllocInfo->Buffer = (PHYSICAL_ADDRESS)(UINTN)Buffer; + AllocInfo->Size = Size; if (ActionString != NULL) { - AllocInfo->ActionStringOffset = (UINT16) sizeof (MEMORY_PROFILE_ALLOC_INFO); - AllocInfoData->ActionString = (CHAR8 *) (AllocInfoData + 1); + AllocInfo->ActionStringOffset = (UINT16)sizeof (MEMORY_PROFILE_ALLOC_INFO); + AllocInfoData->ActionString = (CHAR8 *)(AllocInfoData + 1); CopyMem (AllocInfoData->ActionString, ActionString, ActionStringSize); } else { AllocInfo->ActionStringOffset = 0; - AllocInfoData->ActionString = NULL; + AllocInfoData->ActionString = NULL; } InsertTailList (DriverInfoData->AllocInfoList, &AllocInfoData->Link); - Context = &ContextData->Context; + Context = &ContextData->Context; DriverInfo = &DriverInfoData->DriverInfo; - DriverInfo->AllocRecordCount ++; + DriverInfo->AllocRecordCount++; // // Update summary if and only if it is basic action. @@ -1175,6 +1189,7 @@ SmmCoreUpdateProfileAllocate ( if (DriverInfo->PeakUsage < DriverInfo->CurrentUsage) { DriverInfo->PeakUsage = DriverInfo->CurrentUsage; } + DriverInfo->CurrentUsageByType[ProfileMemoryIndex] += Size; if (DriverInfo->PeakUsageByType[ProfileMemoryIndex] < DriverInfo->CurrentUsageByType[ProfileMemoryIndex]) { DriverInfo->PeakUsageByType[ProfileMemoryIndex] = DriverInfo->CurrentUsageByType[ProfileMemoryIndex]; @@ -1184,6 +1199,7 @@ SmmCoreUpdateProfileAllocate ( if (Context->PeakTotalUsage < Context->CurrentTotalUsage) { Context->PeakTotalUsage = Context->CurrentTotalUsage; } + Context->CurrentTotalUsageByType[ProfileMemoryIndex] += Size; if (Context->PeakTotalUsageByType[ProfileMemoryIndex] < Context->CurrentTotalUsageByType[ProfileMemoryIndex]) { Context->PeakTotalUsageByType[ProfileMemoryIndex] = Context->CurrentTotalUsageByType[ProfileMemoryIndex]; @@ -1207,22 +1223,23 @@ SmmCoreUpdateProfileAllocate ( **/ MEMORY_PROFILE_ALLOC_INFO_DATA * GetMemoryProfileAllocInfoFromAddress ( - IN MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData, - IN MEMORY_PROFILE_ACTION BasicAction, - IN UINTN Size, - IN VOID *Buffer + IN MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData, + IN MEMORY_PROFILE_ACTION BasicAction, + IN UINTN Size, + IN VOID *Buffer ) { - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1233,17 +1250,21 @@ GetMemoryProfileAllocInfoFromAddress ( if ((AllocInfo->Action & MEMORY_PROFILE_ACTION_BASIC_MASK) != BasicAction) { continue; } + switch (BasicAction) { case MemoryProfileActionAllocatePages: - if ((AllocInfo->Buffer <= (PHYSICAL_ADDRESS) (UINTN) Buffer) && - ((AllocInfo->Buffer + AllocInfo->Size) >= ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size))) { + if ((AllocInfo->Buffer <= (PHYSICAL_ADDRESS)(UINTN)Buffer) && + ((AllocInfo->Buffer + AllocInfo->Size) >= ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size))) + { return AllocInfoData; } + break; case MemoryProfileActionAllocatePool: - if (AllocInfo->Buffer == (PHYSICAL_ADDRESS) (UINTN) Buffer) { + if (AllocInfo->Buffer == (PHYSICAL_ADDRESS)(UINTN)Buffer) { return AllocInfoData; } + break; default: ASSERT (FALSE); @@ -1306,7 +1327,7 @@ SmmCoreUpdateProfileFree ( // Need use do-while loop to find all possible record, // because one address might be recorded multiple times. // - Found = FALSE; + Found = FALSE; AllocInfoData = NULL; do { if (DriverInfoData != NULL) { @@ -1323,6 +1344,7 @@ SmmCoreUpdateProfileFree ( break; } } + if (AllocInfoData == NULL) { // // Legal case, because driver A might free memory allocated by driver B, by some protocol. @@ -1331,7 +1353,8 @@ SmmCoreUpdateProfileFree ( for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { ThisDriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -1350,6 +1373,7 @@ SmmCoreUpdateProfileFree ( AllocInfoData = NULL; break; } + if (AllocInfoData != NULL) { DriverInfoData = ThisDriverInfoData; break; @@ -1374,44 +1398,45 @@ SmmCoreUpdateProfileFree ( Found = TRUE; - Context = &ContextData->Context; + Context = &ContextData->Context; DriverInfo = &DriverInfoData->DriverInfo; - AllocInfo = &AllocInfoData->AllocInfo; + AllocInfo = &AllocInfoData->AllocInfo; - DriverInfo->AllocRecordCount --; + DriverInfo->AllocRecordCount--; // // Update summary if and only if it is basic action. // if (AllocInfo->Action == (AllocInfo->Action & MEMORY_PROFILE_ACTION_BASIC_MASK)) { ProfileMemoryIndex = GetProfileMemoryIndex (AllocInfo->MemoryType); - Context->CurrentTotalUsage -= AllocInfo->Size; + Context->CurrentTotalUsage -= AllocInfo->Size; Context->CurrentTotalUsageByType[ProfileMemoryIndex] -= AllocInfo->Size; - DriverInfo->CurrentUsage -= AllocInfo->Size; + DriverInfo->CurrentUsage -= AllocInfo->Size; DriverInfo->CurrentUsageByType[ProfileMemoryIndex] -= AllocInfo->Size; } RemoveEntryList (&AllocInfoData->Link); if (BasicAction == MemoryProfileActionFreePages) { - if (AllocInfo->Buffer != (PHYSICAL_ADDRESS) (UINTN) Buffer) { + if (AllocInfo->Buffer != (PHYSICAL_ADDRESS)(UINTN)Buffer) { SmmCoreUpdateProfileAllocate ( AllocInfo->CallerAddress, AllocInfo->Action, AllocInfo->MemoryType, - (UINTN) ((PHYSICAL_ADDRESS) (UINTN) Buffer - AllocInfo->Buffer), - (VOID *) (UINTN) AllocInfo->Buffer, + (UINTN)((PHYSICAL_ADDRESS)(UINTN)Buffer - AllocInfo->Buffer), + (VOID *)(UINTN)AllocInfo->Buffer, AllocInfoData->ActionString ); } - if (AllocInfo->Buffer + AllocInfo->Size != ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size)) { + + if (AllocInfo->Buffer + AllocInfo->Size != ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size)) { SmmCoreUpdateProfileAllocate ( AllocInfo->CallerAddress, AllocInfo->Action, AllocInfo->MemoryType, - (UINTN) ((AllocInfo->Buffer + AllocInfo->Size) - ((PHYSICAL_ADDRESS) (UINTN) Buffer + Size)), - (VOID *) ((UINTN) Buffer + Size), + (UINTN)((AllocInfo->Buffer + AllocInfo->Size) - ((PHYSICAL_ADDRESS)(UINTN)Buffer + Size)), + (VOID *)((UINTN)Buffer + Size), AllocInfoData->ActionString ); } @@ -1457,9 +1482,9 @@ SmmCoreUpdateProfile ( IN CHAR8 *ActionString OPTIONAL ) { - EFI_STATUS Status; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_ACTION BasicAction; + EFI_STATUS Status; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_ACTION BasicAction; if (!IS_SMRAM_PROFILE_ENABLED) { return EFI_UNSUPPORTED; @@ -1547,21 +1572,21 @@ SmramProfileGetDataSize ( VOID ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - LIST_ENTRY *DriverInfoList; - LIST_ENTRY *DriverLink; - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - UINTN TotalSize; - LIST_ENTRY *Node; - LIST_ENTRY *FreePageList; - LIST_ENTRY *FreePoolList; - FREE_POOL_HEADER *Pool; - UINTN PoolListIndex; - UINTN Index; - UINTN SmmPoolTypeIndex; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *DriverInfoList; + LIST_ENTRY *DriverLink; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + UINTN TotalSize; + LIST_ENTRY *Node; + LIST_ENTRY *FreePageList; + LIST_ENTRY *FreePoolList; + FREE_POOL_HEADER *Pool; + UINTN PoolListIndex; + UINTN Index; + UINTN SmmPoolTypeIndex; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { @@ -1573,19 +1598,21 @@ SmramProfileGetDataSize ( DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( - DriverLink, - MEMORY_PROFILE_DRIVER_INFO_DATA, - Link, - MEMORY_PROFILE_DRIVER_INFO_SIGNATURE - ); + DriverLink, + MEMORY_PROFILE_DRIVER_INFO_DATA, + Link, + MEMORY_PROFILE_DRIVER_INFO_SIGNATURE + ); TotalSize += DriverInfoData->DriverInfo.Header.Length; AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1596,20 +1623,22 @@ SmramProfileGetDataSize ( } } - - Index = 0; + Index = 0; FreePageList = &mSmmMemoryMap; for (Node = FreePageList->BackLink; Node != FreePageList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Index++; } + for (SmmPoolTypeIndex = 0; SmmPoolTypeIndex < SmmPoolTypeMax; SmmPoolTypeIndex++) { for (PoolListIndex = 0; PoolListIndex < MAX_POOL_INDEX; PoolListIndex++) { FreePoolList = &mSmmPoolLists[SmmPoolTypeIndex][PoolListIndex]; for (Node = FreePoolList->BackLink; Node != FreePoolList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Pool = BASE_CR (Node, FREE_POOL_HEADER, Link); if (Pool->Header.Available) { Index++; @@ -1636,9 +1665,9 @@ SmramProfileGetDataSize ( **/ VOID SmramProfileCopyData ( - OUT VOID *ProfileBuffer, - IN OUT UINT64 *ProfileSize, - IN OUT UINT64 *ProfileOffset + OUT VOID *ProfileBuffer, + IN OUT UINT64 *ProfileSize, + IN OUT UINT64 *ProfileOffset ) { MEMORY_PROFILE_CONTEXT *Context; @@ -1647,50 +1676,52 @@ SmramProfileCopyData ( MEMORY_PROFILE_CONTEXT_DATA *ContextData; MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - LIST_ENTRY *DriverInfoList; - LIST_ENTRY *DriverLink; - LIST_ENTRY *AllocInfoList; - LIST_ENTRY *AllocLink; - LIST_ENTRY *Node; - FREE_PAGE_LIST *Pages; - LIST_ENTRY *FreePageList; - LIST_ENTRY *FreePoolList; - FREE_POOL_HEADER *Pool; - UINTN PoolListIndex; - UINT32 Index; - MEMORY_PROFILE_FREE_MEMORY *FreeMemory; - MEMORY_PROFILE_MEMORY_RANGE *MemoryRange; - MEMORY_PROFILE_DESCRIPTOR *MemoryProfileDescriptor; - UINT64 Offset; - UINT64 RemainingSize; - UINTN PdbSize; - UINTN ActionStringSize; - UINTN SmmPoolTypeIndex; + LIST_ENTRY *DriverInfoList; + LIST_ENTRY *DriverLink; + LIST_ENTRY *AllocInfoList; + LIST_ENTRY *AllocLink; + LIST_ENTRY *Node; + FREE_PAGE_LIST *Pages; + LIST_ENTRY *FreePageList; + LIST_ENTRY *FreePoolList; + FREE_POOL_HEADER *Pool; + UINTN PoolListIndex; + UINT32 Index; + MEMORY_PROFILE_FREE_MEMORY *FreeMemory; + MEMORY_PROFILE_MEMORY_RANGE *MemoryRange; + MEMORY_PROFILE_DESCRIPTOR *MemoryProfileDescriptor; + UINT64 Offset; + UINT64 RemainingSize; + UINTN PdbSize; + UINTN ActionStringSize; + UINTN SmmPoolTypeIndex; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } RemainingSize = *ProfileSize; - Offset = 0; + Offset = 0; if (*ProfileOffset < sizeof (MEMORY_PROFILE_CONTEXT)) { if (RemainingSize >= sizeof (MEMORY_PROFILE_CONTEXT)) { Context = ProfileBuffer; CopyMem (Context, &ContextData->Context, sizeof (MEMORY_PROFILE_CONTEXT)); RemainingSize -= sizeof (MEMORY_PROFILE_CONTEXT); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_CONTEXT); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_CONTEXT); } else { goto Done; } } + Offset += sizeof (MEMORY_PROFILE_CONTEXT); DriverInfoList = ContextData->DriverInfoList; for (DriverLink = DriverInfoList->ForwardLink; DriverLink != DriverInfoList; - DriverLink = DriverLink->ForwardLink) { + DriverLink = DriverLink->ForwardLink) + { DriverInfoData = CR ( DriverLink, MEMORY_PROFILE_DRIVER_INFO_DATA, @@ -1703,20 +1734,23 @@ SmramProfileCopyData ( CopyMem (DriverInfo, &DriverInfoData->DriverInfo, sizeof (MEMORY_PROFILE_DRIVER_INFO)); if (DriverInfo->PdbStringOffset != 0) { PdbSize = AsciiStrSize (DriverInfoData->PdbString); - CopyMem ((VOID *) ((UINTN) DriverInfo + DriverInfo->PdbStringOffset), DriverInfoData->PdbString, PdbSize); + CopyMem ((VOID *)((UINTN)DriverInfo + DriverInfo->PdbStringOffset), DriverInfoData->PdbString, PdbSize); } + RemainingSize -= DriverInfo->Header.Length; - ProfileBuffer = (UINT8 *) ProfileBuffer + DriverInfo->Header.Length; + ProfileBuffer = (UINT8 *)ProfileBuffer + DriverInfo->Header.Length; } else { goto Done; } } + Offset += DriverInfoData->DriverInfo.Header.Length; AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink) { + AllocLink = AllocLink->ForwardLink) + { AllocInfoData = CR ( AllocLink, MEMORY_PROFILE_ALLOC_INFO_DATA, @@ -1729,36 +1763,40 @@ SmramProfileCopyData ( CopyMem (AllocInfo, &AllocInfoData->AllocInfo, sizeof (MEMORY_PROFILE_ALLOC_INFO)); if (AllocInfo->ActionStringOffset) { ActionStringSize = AsciiStrSize (AllocInfoData->ActionString); - CopyMem ((VOID *) ((UINTN) AllocInfo + AllocInfo->ActionStringOffset), AllocInfoData->ActionString, ActionStringSize); + CopyMem ((VOID *)((UINTN)AllocInfo + AllocInfo->ActionStringOffset), AllocInfoData->ActionString, ActionStringSize); } + RemainingSize -= AllocInfo->Header.Length; - ProfileBuffer = (UINT8 *) ProfileBuffer + AllocInfo->Header.Length; + ProfileBuffer = (UINT8 *)ProfileBuffer + AllocInfo->Header.Length; } else { goto Done; } } + Offset += AllocInfoData->AllocInfo.Header.Length; } } - if (*ProfileOffset < (Offset + sizeof (MEMORY_PROFILE_FREE_MEMORY))) { if (RemainingSize >= sizeof (MEMORY_PROFILE_FREE_MEMORY)) { FreeMemory = ProfileBuffer; CopyMem (FreeMemory, &mSmramFreeMemory, sizeof (MEMORY_PROFILE_FREE_MEMORY)); - Index = 0; + Index = 0; FreePageList = &mSmmMemoryMap; for (Node = FreePageList->BackLink; Node != FreePageList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Index++; } + for (SmmPoolTypeIndex = 0; SmmPoolTypeIndex < SmmPoolTypeMax; SmmPoolTypeIndex++) { for (PoolListIndex = 0; PoolListIndex < MAX_POOL_INDEX; PoolListIndex++) { FreePoolList = &mSmmPoolLists[SmmPoolTypeIndex][MAX_POOL_INDEX - PoolListIndex - 1]; for (Node = FreePoolList->BackLink; Node != FreePoolList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Pool = BASE_CR (Node, FREE_POOL_HEADER, Link); if (Pool->Header.Available) { Index++; @@ -1766,60 +1804,67 @@ SmramProfileCopyData ( } } } + FreeMemory->FreeMemoryEntryCount = Index; RemainingSize -= sizeof (MEMORY_PROFILE_FREE_MEMORY); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_FREE_MEMORY); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_FREE_MEMORY); } else { goto Done; } } - Offset += sizeof (MEMORY_PROFILE_FREE_MEMORY); + + Offset += sizeof (MEMORY_PROFILE_FREE_MEMORY); FreePageList = &mSmmMemoryMap; for (Node = FreePageList->BackLink; Node != FreePageList; - Node = Node->BackLink) { + Node = Node->BackLink) + { if (*ProfileOffset < (Offset + sizeof (MEMORY_PROFILE_DESCRIPTOR))) { if (RemainingSize >= sizeof (MEMORY_PROFILE_DESCRIPTOR)) { - Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); - MemoryProfileDescriptor = ProfileBuffer; + Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); + MemoryProfileDescriptor = ProfileBuffer; MemoryProfileDescriptor->Header.Signature = MEMORY_PROFILE_DESCRIPTOR_SIGNATURE; - MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); - MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; - MemoryProfileDescriptor->Address = (PHYSICAL_ADDRESS) (UINTN) Pages; - MemoryProfileDescriptor->Size = EFI_PAGES_TO_SIZE (Pages->NumberOfPages); + MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); + MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; + MemoryProfileDescriptor->Address = (PHYSICAL_ADDRESS)(UINTN)Pages; + MemoryProfileDescriptor->Size = EFI_PAGES_TO_SIZE (Pages->NumberOfPages); RemainingSize -= sizeof (MEMORY_PROFILE_DESCRIPTOR); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); } else { goto Done; } } + Offset += sizeof (MEMORY_PROFILE_DESCRIPTOR); } + for (SmmPoolTypeIndex = 0; SmmPoolTypeIndex < SmmPoolTypeMax; SmmPoolTypeIndex++) { for (PoolListIndex = 0; PoolListIndex < MAX_POOL_INDEX; PoolListIndex++) { FreePoolList = &mSmmPoolLists[SmmPoolTypeIndex][MAX_POOL_INDEX - PoolListIndex - 1]; for (Node = FreePoolList->BackLink; Node != FreePoolList; - Node = Node->BackLink) { + Node = Node->BackLink) + { Pool = BASE_CR (Node, FREE_POOL_HEADER, Link); if (Pool->Header.Available) { if (*ProfileOffset < (Offset + sizeof (MEMORY_PROFILE_DESCRIPTOR))) { if (RemainingSize >= sizeof (MEMORY_PROFILE_DESCRIPTOR)) { - MemoryProfileDescriptor = ProfileBuffer; + MemoryProfileDescriptor = ProfileBuffer; MemoryProfileDescriptor->Header.Signature = MEMORY_PROFILE_DESCRIPTOR_SIGNATURE; - MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); - MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; - MemoryProfileDescriptor->Address = (PHYSICAL_ADDRESS) (UINTN) Pool; - MemoryProfileDescriptor->Size = Pool->Header.Size; + MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); + MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; + MemoryProfileDescriptor->Address = (PHYSICAL_ADDRESS)(UINTN)Pool; + MemoryProfileDescriptor->Size = Pool->Header.Size; RemainingSize -= sizeof (MEMORY_PROFILE_DESCRIPTOR); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); } else { goto Done; } } + Offset += sizeof (MEMORY_PROFILE_DESCRIPTOR); } } @@ -1828,35 +1873,37 @@ SmramProfileCopyData ( if (*ProfileOffset < (Offset + sizeof (MEMORY_PROFILE_MEMORY_RANGE))) { if (RemainingSize >= sizeof (MEMORY_PROFILE_MEMORY_RANGE)) { - MemoryRange = ProfileBuffer; + MemoryRange = ProfileBuffer; MemoryRange->Header.Signature = MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE; - MemoryRange->Header.Length = sizeof (MEMORY_PROFILE_MEMORY_RANGE); - MemoryRange->Header.Revision = MEMORY_PROFILE_MEMORY_RANGE_REVISION; - MemoryRange->MemoryRangeCount = (UINT32) mFullSmramRangeCount; + MemoryRange->Header.Length = sizeof (MEMORY_PROFILE_MEMORY_RANGE); + MemoryRange->Header.Revision = MEMORY_PROFILE_MEMORY_RANGE_REVISION; + MemoryRange->MemoryRangeCount = (UINT32)mFullSmramRangeCount; RemainingSize -= sizeof (MEMORY_PROFILE_MEMORY_RANGE); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_MEMORY_RANGE); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_MEMORY_RANGE); } else { goto Done; } } + Offset += sizeof (MEMORY_PROFILE_MEMORY_RANGE); for (Index = 0; Index < mFullSmramRangeCount; Index++) { if (*ProfileOffset < (Offset + sizeof (MEMORY_PROFILE_DESCRIPTOR))) { if (RemainingSize >= sizeof (MEMORY_PROFILE_DESCRIPTOR)) { - MemoryProfileDescriptor = ProfileBuffer; + MemoryProfileDescriptor = ProfileBuffer; MemoryProfileDescriptor->Header.Signature = MEMORY_PROFILE_DESCRIPTOR_SIGNATURE; - MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); - MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; - MemoryProfileDescriptor->Address = mFullSmramRanges[Index].PhysicalStart; - MemoryProfileDescriptor->Size = mFullSmramRanges[Index].PhysicalSize; + MemoryProfileDescriptor->Header.Length = sizeof (MEMORY_PROFILE_DESCRIPTOR); + MemoryProfileDescriptor->Header.Revision = MEMORY_PROFILE_DESCRIPTOR_REVISION; + MemoryProfileDescriptor->Address = mFullSmramRanges[Index].PhysicalStart; + MemoryProfileDescriptor->Size = mFullSmramRanges[Index].PhysicalSize; RemainingSize -= sizeof (MEMORY_PROFILE_DESCRIPTOR); - ProfileBuffer = (UINT8 *) ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); + ProfileBuffer = (UINT8 *)ProfileBuffer + sizeof (MEMORY_PROFILE_DESCRIPTOR); } else { goto Done; } } + Offset += sizeof (MEMORY_PROFILE_DESCRIPTOR); } @@ -1890,26 +1937,26 @@ EFIAPI SmramProfileProtocolGetData ( IN EDKII_SMM_MEMORY_PROFILE_PROTOCOL *This, IN OUT UINT64 *ProfileSize, - OUT VOID *ProfileBuffer + OUT VOID *ProfileBuffer ) { - UINT64 Size; - UINT64 Offset; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; + UINT64 Size; + UINT64 Offset; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { return EFI_UNSUPPORTED; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; Size = SmramProfileGetDataSize (); if (*ProfileSize < Size) { - *ProfileSize = Size; + *ProfileSize = Size; mSmramProfileGettingStatus = SmramProfileGettingStatus; return EFI_BUFFER_TOO_SMALL; } @@ -1947,21 +1994,22 @@ SmramProfileProtocolRegisterImage ( IN EFI_FV_FILETYPE FileType ) { - EFI_STATUS Status; - EFI_SMM_DRIVER_ENTRY DriverEntry; - VOID *EntryPointInImage; - EFI_GUID *Name; + EFI_STATUS Status; + EFI_SMM_DRIVER_ENTRY DriverEntry; + VOID *EntryPointInImage; + EFI_GUID *Name; ZeroMem (&DriverEntry, sizeof (DriverEntry)); Name = GetFileNameFromFilePath (FilePath); if (Name != NULL) { CopyMem (&DriverEntry.FileName, Name, sizeof (EFI_GUID)); } - DriverEntry.ImageBuffer = ImageBase; - DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN) ImageSize); - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) DriverEntry.ImageBuffer, &EntryPointInImage); + + DriverEntry.ImageBuffer = ImageBase; + DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN)ImageSize); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)DriverEntry.ImageBuffer, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverEntry.ImageEntryPoint = (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; + DriverEntry.ImageEntryPoint = (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; return RegisterSmramProfileImage (&DriverEntry, FALSE); } @@ -1989,21 +2037,22 @@ SmramProfileProtocolUnregisterImage ( IN UINT64 ImageSize ) { - EFI_STATUS Status; - EFI_SMM_DRIVER_ENTRY DriverEntry; - VOID *EntryPointInImage; - EFI_GUID *Name; + EFI_STATUS Status; + EFI_SMM_DRIVER_ENTRY DriverEntry; + VOID *EntryPointInImage; + EFI_GUID *Name; ZeroMem (&DriverEntry, sizeof (DriverEntry)); Name = GetFileNameFromFilePath (FilePath); if (Name != NULL) { CopyMem (&DriverEntry.FileName, Name, sizeof (EFI_GUID)); } - DriverEntry.ImageBuffer = ImageBase; - DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN) ImageSize); - Status = InternalPeCoffGetEntryPoint ((VOID *) (UINTN) DriverEntry.ImageBuffer, &EntryPointInImage); + + DriverEntry.ImageBuffer = ImageBase; + DriverEntry.NumberOfPage = EFI_SIZE_TO_PAGES ((UINTN)ImageSize); + Status = InternalPeCoffGetEntryPoint ((VOID *)(UINTN)DriverEntry.ImageBuffer, &EntryPointInImage); ASSERT_EFI_ERROR (Status); - DriverEntry.ImageEntryPoint = (PHYSICAL_ADDRESS) (UINTN) EntryPointInImage; + DriverEntry.ImageEntryPoint = (PHYSICAL_ADDRESS)(UINTN)EntryPointInImage; return UnregisterSmramProfileImage (&DriverEntry, FALSE); } @@ -2026,7 +2075,7 @@ SmramProfileProtocolGetRecordingState ( OUT BOOLEAN *RecordingState ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { @@ -2036,6 +2085,7 @@ SmramProfileProtocolGetRecordingState ( if (RecordingState == NULL) { return EFI_INVALID_PARAMETER; } + *RecordingState = mSmramProfileRecordingEnable; return EFI_SUCCESS; } @@ -2057,7 +2107,7 @@ SmramProfileProtocolSetRecordingState ( IN BOOLEAN RecordingState ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { @@ -2114,21 +2164,21 @@ SmramProfileProtocolRecord ( **/ VOID SmramProfileHandlerGetInfo ( - IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *SmramProfileParameterGetInfo + IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *SmramProfileParameterGetInfo ) { - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; - SmramProfileParameterGetInfo->ProfileSize = SmramProfileGetDataSize(); + SmramProfileParameterGetInfo->ProfileSize = SmramProfileGetDataSize (); SmramProfileParameterGetInfo->Header.ReturnStatus = 0; mSmramProfileGettingStatus = SmramProfileGettingStatus; @@ -2142,7 +2192,7 @@ SmramProfileHandlerGetInfo ( **/ VOID SmramProfileHandlerGetData ( - IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA *SmramProfileParameterGetData + IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA *SmramProfileParameterGetData ) { UINT64 ProfileSize; @@ -2153,36 +2203,35 @@ SmramProfileHandlerGetData ( ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; - CopyMem (&SmramProfileGetData, SmramProfileParameterGetData, sizeof (SmramProfileGetData)); - ProfileSize = SmramProfileGetDataSize(); + ProfileSize = SmramProfileGetDataSize (); // // Sanity check // - if (!SmmIsBufferOutsideSmmValid ((UINTN) SmramProfileGetData.ProfileBuffer, (UINTN) ProfileSize)) { + if (!SmmIsBufferOutsideSmmValid ((UINTN)SmramProfileGetData.ProfileBuffer, (UINTN)ProfileSize)) { DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetData: SMM ProfileBuffer in SMRAM or overflow!\n")); - SmramProfileParameterGetData->ProfileSize = ProfileSize; - SmramProfileParameterGetData->Header.ReturnStatus = (UINT64) (INT64) (INTN) EFI_ACCESS_DENIED; + SmramProfileParameterGetData->ProfileSize = ProfileSize; + SmramProfileParameterGetData->Header.ReturnStatus = (UINT64)(INT64)(INTN)EFI_ACCESS_DENIED; goto Done; } if (SmramProfileGetData.ProfileSize < ProfileSize) { - SmramProfileParameterGetData->ProfileSize = ProfileSize; - SmramProfileParameterGetData->Header.ReturnStatus = (UINT64) (INT64) (INTN) EFI_BUFFER_TOO_SMALL; + SmramProfileParameterGetData->ProfileSize = ProfileSize; + SmramProfileParameterGetData->Header.ReturnStatus = (UINT64)(INT64)(INTN)EFI_BUFFER_TOO_SMALL; goto Done; } ProfileOffset = 0; - SmramProfileCopyData ((VOID *) (UINTN) SmramProfileGetData.ProfileBuffer, &ProfileSize, &ProfileOffset); - SmramProfileParameterGetData->ProfileSize = ProfileSize; + SmramProfileCopyData ((VOID *)(UINTN)SmramProfileGetData.ProfileBuffer, &ProfileSize, &ProfileOffset); + SmramProfileParameterGetData->ProfileSize = ProfileSize; SmramProfileParameterGetData->Header.ReturnStatus = 0; Done: @@ -2197,34 +2246,33 @@ Done: **/ VOID SmramProfileHandlerGetDataByOffset ( - IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *SmramProfileParameterGetDataByOffset + IN SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *SmramProfileParameterGetDataByOffset ) { - SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET SmramProfileGetDataByOffset; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; + SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET SmramProfileGetDataByOffset; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; - CopyMem (&SmramProfileGetDataByOffset, SmramProfileParameterGetDataByOffset, sizeof (SmramProfileGetDataByOffset)); // // Sanity check // - if (!SmmIsBufferOutsideSmmValid ((UINTN) SmramProfileGetDataByOffset.ProfileBuffer, (UINTN) SmramProfileGetDataByOffset.ProfileSize)) { + if (!SmmIsBufferOutsideSmmValid ((UINTN)SmramProfileGetDataByOffset.ProfileBuffer, (UINTN)SmramProfileGetDataByOffset.ProfileSize)) { DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetDataByOffset: SMM ProfileBuffer in SMRAM or overflow!\n")); - SmramProfileParameterGetDataByOffset->Header.ReturnStatus = (UINT64) (INT64) (INTN) EFI_ACCESS_DENIED; + SmramProfileParameterGetDataByOffset->Header.ReturnStatus = (UINT64)(INT64)(INTN)EFI_ACCESS_DENIED; goto Done; } - SmramProfileCopyData ((VOID *) (UINTN) SmramProfileGetDataByOffset.ProfileBuffer, &SmramProfileGetDataByOffset.ProfileSize, &SmramProfileGetDataByOffset.ProfileOffset); + SmramProfileCopyData ((VOID *)(UINTN)SmramProfileGetDataByOffset.ProfileBuffer, &SmramProfileGetDataByOffset.ProfileSize, &SmramProfileGetDataByOffset.ProfileOffset); CopyMem (SmramProfileParameterGetDataByOffset, &SmramProfileGetDataByOffset, sizeof (SmramProfileGetDataByOffset)); SmramProfileParameterGetDataByOffset->Header.ReturnStatus = 0; @@ -2266,7 +2314,7 @@ SmramProfileHandler ( // // If input is invalid, stop processing this SMI // - if (CommBuffer == NULL || CommBufferSize == NULL) { + if ((CommBuffer == NULL) || (CommBufferSize == NULL)) { return EFI_SUCCESS; } @@ -2282,72 +2330,77 @@ SmramProfileHandler ( return EFI_SUCCESS; } - SmramProfileParameterHeader = (SMRAM_PROFILE_PARAMETER_HEADER *) ((UINTN) CommBuffer); + SmramProfileParameterHeader = (SMRAM_PROFILE_PARAMETER_HEADER *)((UINTN)CommBuffer); SmramProfileParameterHeader->ReturnStatus = (UINT64)-1; if (GetSmramProfileContext () == NULL) { - SmramProfileParameterHeader->ReturnStatus = (UINT64) (INT64) (INTN) EFI_UNSUPPORTED; + SmramProfileParameterHeader->ReturnStatus = (UINT64)(INT64)(INTN)EFI_UNSUPPORTED; return EFI_SUCCESS; } switch (SmramProfileParameterHeader->Command) { - case SMRAM_PROFILE_COMMAND_GET_PROFILE_INFO: - DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetInfo\n")); - if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO)) { - DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - SmramProfileHandlerGetInfo ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *) (UINTN) CommBuffer); - break; - case SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA: - DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetData\n")); - if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA)) { - DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - SmramProfileHandlerGetData ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA *) (UINTN) CommBuffer); - break; - case SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA_BY_OFFSET: - DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetDataByOffset\n")); - if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET)) { - DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - SmramProfileHandlerGetDataByOffset ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *) (UINTN) CommBuffer); - break; - case SMRAM_PROFILE_COMMAND_GET_RECORDING_STATE: - DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetRecordingState\n")); - if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE)) { - DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - ParameterRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *) (UINTN) CommBuffer; - ParameterRecordingState->RecordingState = mSmramProfileRecordingEnable; - ParameterRecordingState->Header.ReturnStatus = 0; - break; - case SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE: - DEBUG ((DEBUG_ERROR, "SmramProfileHandlerSetRecordingState\n")); - if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE)) { - DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); - return EFI_SUCCESS; - } - ParameterRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *) (UINTN) CommBuffer; - mSmramProfileRecordingEnable = ParameterRecordingState->RecordingState; - ParameterRecordingState->Header.ReturnStatus = 0; - break; + case SMRAM_PROFILE_COMMAND_GET_PROFILE_INFO: + DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetInfo\n")); + if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO)) { + DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } - // - // Below 2 commands have been deprecated. They may not be (re-)used. - // - case SMRAM_PROFILE_COMMAND_DEPRECATED1: - case SMRAM_PROFILE_COMMAND_DEPRECATED2: - ASSERT (FALSE); + SmramProfileHandlerGetInfo ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_INFO *)(UINTN)CommBuffer); + break; + case SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA: + DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetData\n")); + if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA)) { + DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + SmramProfileHandlerGetData ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA *)(UINTN)CommBuffer); + break; + case SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA_BY_OFFSET: + DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetDataByOffset\n")); + if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET)) { + DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + SmramProfileHandlerGetDataByOffset ((SMRAM_PROFILE_PARAMETER_GET_PROFILE_DATA_BY_OFFSET *)(UINTN)CommBuffer); + break; + case SMRAM_PROFILE_COMMAND_GET_RECORDING_STATE: + DEBUG ((DEBUG_ERROR, "SmramProfileHandlerGetRecordingState\n")); + if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE)) { + DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + ParameterRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *)(UINTN)CommBuffer; + ParameterRecordingState->RecordingState = mSmramProfileRecordingEnable; + ParameterRecordingState->Header.ReturnStatus = 0; + break; + case SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE: + DEBUG ((DEBUG_ERROR, "SmramProfileHandlerSetRecordingState\n")); + if (TempCommBufferSize != sizeof (SMRAM_PROFILE_PARAMETER_RECORDING_STATE)) { + DEBUG ((DEBUG_ERROR, "SmramProfileHandler: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + + ParameterRecordingState = (SMRAM_PROFILE_PARAMETER_RECORDING_STATE *)(UINTN)CommBuffer; + mSmramProfileRecordingEnable = ParameterRecordingState->RecordingState; + ParameterRecordingState->Header.ReturnStatus = 0; + break; + + // + // Below 2 commands have been deprecated. They may not be (re-)used. + // + case SMRAM_PROFILE_COMMAND_DEPRECATED1: + case SMRAM_PROFILE_COMMAND_DEPRECATED2: + ASSERT (FALSE); // // Fall-through to the default (unrecognized command) case. // - default: - break; + default: + break; } DEBUG ((DEBUG_ERROR, "SmramProfileHandler Exit\n")); @@ -2364,8 +2417,8 @@ RegisterSmramProfileHandler ( VOID ) { - EFI_STATUS Status; - EFI_HANDLE DispatchHandle; + EFI_STATUS Status; + EFI_HANDLE DispatchHandle; if (!IS_SMRAM_PROFILE_ENABLED) { return; @@ -2390,16 +2443,16 @@ DumpSmramRange ( VOID ) { - UINTN Index; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; + UINTN Index; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; DEBUG ((DEBUG_INFO, "FullSmramRange address - 0x%08x\n", mFullSmramRanges)); @@ -2429,19 +2482,19 @@ DumpFreePagesList ( VOID ) { - LIST_ENTRY *FreePageList; - LIST_ENTRY *Node; - FREE_PAGE_LIST *Pages; - UINTN Index; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; + LIST_ENTRY *FreePageList; + LIST_ENTRY *Node; + FREE_PAGE_LIST *Pages; + UINTN Index; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; DEBUG ((DEBUG_INFO, "======= SmramProfile begin =======\n")); @@ -2450,10 +2503,11 @@ DumpFreePagesList ( FreePageList = &mSmmMemoryMap; for (Node = FreePageList->BackLink, Index = 0; Node != FreePageList; - Node = Node->BackLink, Index++) { + Node = Node->BackLink, Index++) + { Pages = BASE_CR (Node, FREE_PAGE_LIST, Link); DEBUG ((DEBUG_INFO, " Index - 0x%x\n", Index)); - DEBUG ((DEBUG_INFO, " PhysicalStart - 0x%016lx\n", (PHYSICAL_ADDRESS) (UINTN) Pages)); + DEBUG ((DEBUG_INFO, " PhysicalStart - 0x%016lx\n", (PHYSICAL_ADDRESS)(UINTN)Pages)); DEBUG ((DEBUG_INFO, " NumberOfPages - 0x%08x\n", Pages->NumberOfPages)); } @@ -2471,21 +2525,21 @@ DumpFreePoolList ( VOID ) { - LIST_ENTRY *FreePoolList; - LIST_ENTRY *Node; - FREE_POOL_HEADER *Pool; - UINTN Index; - UINTN PoolListIndex; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - BOOLEAN SmramProfileGettingStatus; - UINTN SmmPoolTypeIndex; + LIST_ENTRY *FreePoolList; + LIST_ENTRY *Node; + FREE_POOL_HEADER *Pool; + UINTN Index; + UINTN PoolListIndex; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + BOOLEAN SmramProfileGettingStatus; + UINTN SmmPoolTypeIndex; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; DEBUG ((DEBUG_INFO, "======= SmramProfile begin =======\n")); @@ -2496,10 +2550,11 @@ DumpFreePoolList ( FreePoolList = &mSmmPoolLists[SmmPoolTypeIndex][PoolListIndex]; for (Node = FreePoolList->BackLink, Index = 0; Node != FreePoolList; - Node = Node->BackLink, Index++) { + Node = Node->BackLink, Index++) + { Pool = BASE_CR (Node, FREE_POOL_HEADER, Link); DEBUG ((DEBUG_INFO, " Index - 0x%x\n", Index)); - DEBUG ((DEBUG_INFO, " PhysicalStart - 0x%016lx\n", (PHYSICAL_ADDRESS) (UINTN) Pool)); + DEBUG ((DEBUG_INFO, " PhysicalStart - 0x%016lx\n", (PHYSICAL_ADDRESS)(UINTN)Pool)); DEBUG ((DEBUG_INFO, " Size - 0x%08x\n", Pool->Header.Size)); DEBUG ((DEBUG_INFO, " Available - 0x%02x\n", Pool->Header.Available)); } @@ -2511,7 +2566,7 @@ DumpFreePoolList ( mSmramProfileGettingStatus = SmramProfileGettingStatus; } -GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mSmmActionString[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mSmmActionString[] = { "SmmUnknown", "gSmst->SmmAllocatePages", "gSmst->SmmFreePages", @@ -2520,42 +2575,42 @@ GLOBAL_REMOVE_IF_UNREFERENCED CHAR8 *mSmmActionString[] = { }; typedef struct { - MEMORY_PROFILE_ACTION Action; - CHAR8 *String; + MEMORY_PROFILE_ACTION Action; + CHAR8 *String; } ACTION_STRING; -GLOBAL_REMOVE_IF_UNREFERENCED ACTION_STRING mExtActionString[] = { - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, "Lib:AllocatePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, "Lib:AllocateRuntimePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES, "Lib:AllocateReservedPages"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_PAGES, "Lib:FreePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, "Lib:AllocateAlignedPages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, "Lib:AllocateAlignedRuntimePages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES, "Lib:AllocateAlignedReservedPages"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES, "Lib:FreeAlignedPages"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, "Lib:AllocatePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, "Lib:AllocateRuntimePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL, "Lib:AllocateReservedPool"}, - {MEMORY_PROFILE_ACTION_LIB_FREE_POOL, "Lib:FreePool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, "Lib:AllocateZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, "Lib:AllocateRuntimeZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL, "Lib:AllocateReservedZeroPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, "Lib:AllocateCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, "Lib:AllocateRuntimeCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL, "Lib:AllocateReservedCopyPool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, "Lib:ReallocatePool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, "Lib:ReallocateRuntimePool"}, - {MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL, "Lib:ReallocateReservedPool"}, +GLOBAL_REMOVE_IF_UNREFERENCED ACTION_STRING mExtActionString[] = { + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, "Lib:AllocatePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, "Lib:AllocateRuntimePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES, "Lib:AllocateReservedPages" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_PAGES, "Lib:FreePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, "Lib:AllocateAlignedPages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, "Lib:AllocateAlignedRuntimePages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES, "Lib:AllocateAlignedReservedPages" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES, "Lib:FreeAlignedPages" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, "Lib:AllocatePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, "Lib:AllocateRuntimePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL, "Lib:AllocateReservedPool" }, + { MEMORY_PROFILE_ACTION_LIB_FREE_POOL, "Lib:FreePool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, "Lib:AllocateZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, "Lib:AllocateRuntimeZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL, "Lib:AllocateReservedZeroPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, "Lib:AllocateCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, "Lib:AllocateRuntimeCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL, "Lib:AllocateReservedCopyPool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, "Lib:ReallocatePool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, "Lib:ReallocateRuntimePool" }, + { MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL, "Lib:ReallocateReservedPool" }, }; typedef struct { - EFI_MEMORY_TYPE MemoryType; - CHAR8 *MemoryTypeStr; + EFI_MEMORY_TYPE MemoryType; + CHAR8 *MemoryTypeStr; } PROFILE_MEMORY_TYPE_STRING; -GLOBAL_REMOVE_IF_UNREFERENCED PROFILE_MEMORY_TYPE_STRING mMemoryTypeString[] = { - {EfiRuntimeServicesCode, "EfiRuntimeServicesCode"}, - {EfiRuntimeServicesData, "EfiRuntimeServicesData"} +GLOBAL_REMOVE_IF_UNREFERENCED PROFILE_MEMORY_TYPE_STRING mMemoryTypeString[] = { + { EfiRuntimeServicesCode, "EfiRuntimeServicesCode" }, + { EfiRuntimeServicesData, "EfiRuntimeServicesData" } }; /** @@ -2568,10 +2623,11 @@ GLOBAL_REMOVE_IF_UNREFERENCED PROFILE_MEMORY_TYPE_STRING mMemoryTypeString[] = { **/ CHAR8 * ProfileMemoryTypeToStr ( - IN EFI_MEMORY_TYPE MemoryType + IN EFI_MEMORY_TYPE MemoryType ) { - UINTN Index; + UINTN Index; + for (Index = 0; Index < ARRAY_SIZE (mMemoryTypeString); Index++) { if (mMemoryTypeString[Index].MemoryType == MemoryType) { return mMemoryTypeString[Index].MemoryTypeStr; @@ -2594,16 +2650,17 @@ ProfileActionToStr ( IN MEMORY_PROFILE_ACTION Action ) { - UINTN Index; - UINTN ActionStringCount; - CHAR8 **ActionString; + UINTN Index; + UINTN ActionStringCount; + CHAR8 **ActionString; - ActionString = mSmmActionString; + ActionString = mSmmActionString; ActionStringCount = ARRAY_SIZE (mSmmActionString); - if ((UINTN) (UINT32) Action < ActionStringCount) { + if ((UINTN)(UINT32)Action < ActionStringCount) { return ActionString[Action]; } + for (Index = 0; Index < ARRAY_SIZE (mExtActionString); Index++) { if (mExtActionString[Index].Action == Action) { return mExtActionString[Index].String; @@ -2622,27 +2679,27 @@ DumpSmramProfile ( VOID ) { - MEMORY_PROFILE_CONTEXT *Context; - MEMORY_PROFILE_DRIVER_INFO *DriverInfo; - MEMORY_PROFILE_ALLOC_INFO *AllocInfo; - MEMORY_PROFILE_CONTEXT_DATA *ContextData; - MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; - MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; - LIST_ENTRY *SmramDriverInfoList; - UINTN DriverIndex; - LIST_ENTRY *DriverLink; - LIST_ENTRY *AllocInfoList; - UINTN AllocIndex; - LIST_ENTRY *AllocLink; - BOOLEAN SmramProfileGettingStatus; - UINTN TypeIndex; + MEMORY_PROFILE_CONTEXT *Context; + MEMORY_PROFILE_DRIVER_INFO *DriverInfo; + MEMORY_PROFILE_ALLOC_INFO *AllocInfo; + MEMORY_PROFILE_CONTEXT_DATA *ContextData; + MEMORY_PROFILE_DRIVER_INFO_DATA *DriverInfoData; + MEMORY_PROFILE_ALLOC_INFO_DATA *AllocInfoData; + LIST_ENTRY *SmramDriverInfoList; + UINTN DriverIndex; + LIST_ENTRY *DriverLink; + LIST_ENTRY *AllocInfoList; + UINTN AllocIndex; + LIST_ENTRY *AllocLink; + BOOLEAN SmramProfileGettingStatus; + UINTN TypeIndex; ContextData = GetSmramProfileContext (); if (ContextData == NULL) { - return ; + return; } - SmramProfileGettingStatus = mSmramProfileGettingStatus; + SmramProfileGettingStatus = mSmramProfileGettingStatus; mSmramProfileGettingStatus = TRUE; Context = &ContextData->Context; @@ -2653,11 +2710,13 @@ DumpSmramProfile ( DEBUG ((DEBUG_INFO, " PeakTotalUsage - 0x%016lx\n", Context->PeakTotalUsage)); for (TypeIndex = 0; TypeIndex < sizeof (Context->CurrentTotalUsageByType) / sizeof (Context->CurrentTotalUsageByType[0]); TypeIndex++) { if ((Context->CurrentTotalUsageByType[TypeIndex] != 0) || - (Context->PeakTotalUsageByType[TypeIndex] != 0)) { + (Context->PeakTotalUsageByType[TypeIndex] != 0)) + { DEBUG ((DEBUG_INFO, " CurrentTotalUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, Context->CurrentTotalUsageByType[TypeIndex], ProfileMemoryTypeToStr (TypeIndex))); DEBUG ((DEBUG_INFO, " PeakTotalUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, Context->PeakTotalUsageByType[TypeIndex], ProfileMemoryTypeToStr (TypeIndex))); } } + DEBUG ((DEBUG_INFO, " TotalImageSize - 0x%016lx\n", Context->TotalImageSize)); DEBUG ((DEBUG_INFO, " ImageCount - 0x%08x\n", Context->ImageCount)); DEBUG ((DEBUG_INFO, " SequenceCount - 0x%08x\n", Context->SequenceCount)); @@ -2665,13 +2724,14 @@ DumpSmramProfile ( SmramDriverInfoList = ContextData->DriverInfoList; for (DriverLink = SmramDriverInfoList->ForwardLink, DriverIndex = 0; DriverLink != SmramDriverInfoList; - DriverLink = DriverLink->ForwardLink, DriverIndex++) { + DriverLink = DriverLink->ForwardLink, DriverIndex++) + { DriverInfoData = CR ( - DriverLink, - MEMORY_PROFILE_DRIVER_INFO_DATA, - Link, - MEMORY_PROFILE_DRIVER_INFO_SIGNATURE - ); + DriverLink, + MEMORY_PROFILE_DRIVER_INFO_DATA, + Link, + MEMORY_PROFILE_DRIVER_INFO_SIGNATURE + ); DriverInfo = &DriverInfoData->DriverInfo; DEBUG ((DEBUG_INFO, " MEMORY_PROFILE_DRIVER_INFO (0x%x)\n", DriverIndex)); DEBUG ((DEBUG_INFO, " FileName - %g\n", &DriverInfo->FileName)); @@ -2684,23 +2744,26 @@ DumpSmramProfile ( DEBUG ((DEBUG_INFO, " PeakUsage - 0x%016lx\n", DriverInfo->PeakUsage)); for (TypeIndex = 0; TypeIndex < sizeof (DriverInfo->CurrentUsageByType) / sizeof (DriverInfo->CurrentUsageByType[0]); TypeIndex++) { if ((DriverInfo->CurrentUsageByType[TypeIndex] != 0) || - (DriverInfo->PeakUsageByType[TypeIndex] != 0)) { + (DriverInfo->PeakUsageByType[TypeIndex] != 0)) + { DEBUG ((DEBUG_INFO, " CurrentUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, DriverInfo->CurrentUsageByType[TypeIndex], ProfileMemoryTypeToStr (TypeIndex))); DEBUG ((DEBUG_INFO, " PeakUsage[0x%02x] - 0x%016lx (%a)\n", TypeIndex, DriverInfo->PeakUsageByType[TypeIndex], ProfileMemoryTypeToStr (TypeIndex))); } } + DEBUG ((DEBUG_INFO, " AllocRecordCount - 0x%08x\n", DriverInfo->AllocRecordCount)); AllocInfoList = DriverInfoData->AllocInfoList; for (AllocLink = AllocInfoList->ForwardLink, AllocIndex = 0; AllocLink != AllocInfoList; - AllocLink = AllocLink->ForwardLink, AllocIndex++) { + AllocLink = AllocLink->ForwardLink, AllocIndex++) + { AllocInfoData = CR ( - AllocLink, - MEMORY_PROFILE_ALLOC_INFO_DATA, - Link, - MEMORY_PROFILE_ALLOC_INFO_SIGNATURE - ); + AllocLink, + MEMORY_PROFILE_ALLOC_INFO_DATA, + Link, + MEMORY_PROFILE_ALLOC_INFO_SIGNATURE + ); AllocInfo = &AllocInfoData->AllocInfo; DEBUG ((DEBUG_INFO, " MEMORY_PROFILE_ALLOC_INFO (0x%x)\n", AllocIndex)); DEBUG ((DEBUG_INFO, " CallerAddress - 0x%016lx (Offset: 0x%08x)\n", AllocInfo->CallerAddress, AllocInfo->CallerAddress - DriverInfo->ImageBase)); @@ -2714,6 +2777,7 @@ DumpSmramProfile ( } else { DEBUG ((DEBUG_INFO, " Action - 0x%08x (%a)\n", AllocInfo->Action, ProfileActionToStr (AllocInfo->Action))); } + DEBUG ((DEBUG_INFO, " MemoryType - 0x%08x (%a)\n", AllocInfo->MemoryType, ProfileMemoryTypeToStr (AllocInfo->MemoryType))); DEBUG ((DEBUG_INFO, " Buffer - 0x%016lx\n", AllocInfo->Buffer)); DEBUG ((DEBUG_INFO, " Size - 0x%016lx\n", AllocInfo->Size)); @@ -2734,12 +2798,13 @@ DumpSmramInfo ( VOID ) { - DEBUG_CODE_BEGIN (); - if (IS_SMRAM_PROFILE_ENABLED) { - DumpSmramProfile (); - DumpFreePagesList (); - DumpFreePoolList (); - DumpSmramRange (); - } - DEBUG_CODE_END (); + DEBUG_CODE_BEGIN (); + if (IS_SMRAM_PROFILE_ENABLED) { + DumpSmramProfile (); + DumpFreePagesList (); + DumpFreePoolList (); + DumpSmramRange (); + } + + DEBUG_CODE_END (); } diff --git a/MdeModulePkg/Core/RuntimeDxe/Crc32.c b/MdeModulePkg/Core/RuntimeDxe/Crc32.c index 6a4677dabf..fa3e0decdb 100644 --- a/MdeModulePkg/Core/RuntimeDxe/Crc32.c +++ b/MdeModulePkg/Core/RuntimeDxe/Crc32.c @@ -12,7 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include #include @@ -36,7 +35,7 @@ RuntimeDriverCalculateCrc32 ( OUT UINT32 *CrcOut ) { - if (Data == NULL || DataSize == 0 || CrcOut == NULL) { + if ((Data == NULL) || (DataSize == 0) || (CrcOut == NULL)) { return EFI_INVALID_PARAMETER; } diff --git a/MdeModulePkg/Core/RuntimeDxe/Runtime.c b/MdeModulePkg/Core/RuntimeDxe/Runtime.c index f7220a205d..2a54140873 100644 --- a/MdeModulePkg/Core/RuntimeDxe/Runtime.c +++ b/MdeModulePkg/Core/RuntimeDxe/Runtime.c @@ -45,20 +45,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Global Variables // -EFI_MEMORY_DESCRIPTOR *mVirtualMap = NULL; -UINTN mVirtualMapDescriptorSize; -UINTN mVirtualMapMaxIndex; -VOID *mMyImageBase; +EFI_MEMORY_DESCRIPTOR *mVirtualMap = NULL; +UINTN mVirtualMapDescriptorSize; +UINTN mVirtualMapMaxIndex; +VOID *mMyImageBase; // // The handle onto which the Runtime Architectural Protocol instance is installed // -EFI_HANDLE mRuntimeHandle = NULL; +EFI_HANDLE mRuntimeHandle = NULL; // // The Runtime Architectural Protocol instance produced by this driver // -EFI_RUNTIME_ARCH_PROTOCOL mRuntime = { +EFI_RUNTIME_ARCH_PROTOCOL mRuntime = { INITIALIZE_LIST_HEAD_VARIABLE (mRuntime.ImageHead), INITIALIZE_LIST_HEAD_VARIABLE (mRuntime.EventHead), @@ -79,6 +79,7 @@ EFI_RUNTIME_ARCH_PROTOCOL mRuntime = { // // Worker Functions // + /** Calculate the 32-bit CRC in a EFI table using the Runtime Drivers @@ -97,10 +98,10 @@ RuntimeDriverCalculateEfiHdrCrc ( { UINT32 Crc; - Hdr->CRC32 = 0; + Hdr->CRC32 = 0; - Crc = 0; - RuntimeDriverCalculateCrc32 ((UINT8 *) Hdr, Hdr->HeaderSize, &Crc); + Crc = 0; + RuntimeDriverCalculateCrc32 ((UINT8 *)Hdr, Hdr->HeaderSize, &Crc); Hdr->CRC32 = Crc; } @@ -126,10 +127,10 @@ RuntimeDriverConvertPointer ( IN OUT VOID **ConvertAddress ) { - UINTN Address; - UINT64 VirtEndOfRange; - EFI_MEMORY_DESCRIPTOR *VirtEntry; - UINTN Index; + UINTN Address; + UINT64 VirtEndOfRange; + EFI_MEMORY_DESCRIPTOR *VirtEntry; + UINTN Index; // // Make sure ConvertAddress is a valid pointer @@ -137,10 +138,11 @@ RuntimeDriverConvertPointer ( if (ConvertAddress == NULL) { return EFI_INVALID_PARAMETER; } + // // Get the address to convert // - Address = (UINTN) *ConvertAddress; + Address = (UINTN)*ConvertAddress; // // If this is a null pointer, return if it's allowed @@ -161,16 +163,16 @@ RuntimeDriverConvertPointer ( // platforms. If you get this ASSERT remove the UINTN and do a 64-bit // multiply. // - ASSERT (((UINTN) VirtEntry->NumberOfPages < 0xffffffff) || (sizeof (UINTN) > 4)); + ASSERT (((UINTN)VirtEntry->NumberOfPages < 0xffffffff) || (sizeof (UINTN) > 4)); if ((VirtEntry->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) { if (Address >= VirtEntry->PhysicalStart) { - VirtEndOfRange = VirtEntry->PhysicalStart + (((UINTN) VirtEntry->NumberOfPages) * EFI_PAGE_SIZE); + VirtEndOfRange = VirtEntry->PhysicalStart + (((UINTN)VirtEntry->NumberOfPages) * EFI_PAGE_SIZE); if (Address < VirtEndOfRange) { // // Compute new address // - *ConvertAddress = (VOID *) (Address - (UINTN) VirtEntry->PhysicalStart + (UINTN) VirtEntry->VirtualStart); + *ConvertAddress = (VOID *)(Address - (UINTN)VirtEntry->PhysicalStart + (UINTN)VirtEntry->VirtualStart); return EFI_SUCCESS; } } @@ -200,7 +202,7 @@ RuntimeDriverConvertPointer ( **/ EFI_STATUS RuntimeDriverConvertInternalPointer ( - IN OUT VOID **ConvertAddress + IN OUT VOID **ConvertAddress ) { return RuntimeDriverConvertPointer (0x0, ConvertAddress); @@ -236,11 +238,11 @@ RuntimeDriverSetVirtualAddressMap ( IN EFI_MEMORY_DESCRIPTOR *VirtualMap ) { - EFI_STATUS Status; - EFI_RUNTIME_EVENT_ENTRY *RuntimeEvent; - EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage; - LIST_ENTRY *Link; - EFI_PHYSICAL_ADDRESS VirtImageBase; + EFI_STATUS Status; + EFI_RUNTIME_EVENT_ENTRY *RuntimeEvent; + EFI_RUNTIME_IMAGE_ENTRY *RuntimeImage; + LIST_ENTRY *Link; + EFI_PHYSICAL_ADDRESS VirtImageBase; // // Can only switch to virtual addresses once the memory map is locked down, @@ -249,12 +251,14 @@ RuntimeDriverSetVirtualAddressMap ( if (!mRuntime.AtRuntime || mRuntime.VirtualMode) { return EFI_UNSUPPORTED; } + // // Only understand the original descriptor format // - if (DescriptorVersion != EFI_MEMORY_DESCRIPTOR_VERSION || DescriptorSize < sizeof (EFI_MEMORY_DESCRIPTOR)) { + if ((DescriptorVersion != EFI_MEMORY_DESCRIPTOR_VERSION) || (DescriptorSize < sizeof (EFI_MEMORY_DESCRIPTOR))) { return EFI_INVALID_PARAMETER; } + // // We are now committed to go to virtual mode, so lets get to it! // @@ -294,7 +298,7 @@ RuntimeDriverSetVirtualAddressMap ( // we need an explicit cast here. // RuntimeEvent->NotifyFunction ( - (EFI_EVENT) RuntimeEvent->Event, + (EFI_EVENT)RuntimeEvent->Event, RuntimeEvent->NotifyContext ); } @@ -309,19 +313,18 @@ RuntimeDriverSetVirtualAddressMap ( // We don't want to relocate our selves, as we only run in physical mode. // if (mMyImageBase != RuntimeImage->ImageBase) { - - VirtImageBase = (EFI_PHYSICAL_ADDRESS) (UINTN) RuntimeImage->ImageBase; - Status = RuntimeDriverConvertPointer (0, (VOID **) &VirtImageBase); + VirtImageBase = (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase; + Status = RuntimeDriverConvertPointer (0, (VOID **)&VirtImageBase); ASSERT_EFI_ERROR (Status); PeCoffLoaderRelocateImageForRuntime ( - (EFI_PHYSICAL_ADDRESS) (UINTN) RuntimeImage->ImageBase, + (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, VirtImageBase, - (UINTN) RuntimeImage->ImageSize, + (UINTN)RuntimeImage->ImageSize, RuntimeImage->RelocationData ); - InvalidateInstructionCacheRange (RuntimeImage->ImageBase, (UINTN) RuntimeImage->ImageSize); + InvalidateInstructionCacheRange (RuntimeImage->ImageBase, (UINTN)RuntimeImage->ImageSize); } } @@ -329,18 +332,18 @@ RuntimeDriverSetVirtualAddressMap ( // Convert all the Runtime Services except ConvertPointer() and SetVirtualAddressMap() // and recompute the CRC-32 // - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->GetTime); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->SetTime); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->GetWakeupTime); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->SetWakeupTime); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->ResetSystem); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->GetNextHighMonotonicCount); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->GetVariable); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->SetVariable); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->GetNextVariableName); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->QueryVariableInfo); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->UpdateCapsule); - RuntimeDriverConvertInternalPointer ((VOID **) &gRT->QueryCapsuleCapabilities); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->GetTime); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->SetTime); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->GetWakeupTime); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->SetWakeupTime); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->ResetSystem); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->GetNextHighMonotonicCount); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->GetVariable); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->SetVariable); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->GetNextVariableName); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->QueryVariableInfo); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->UpdateCapsule); + RuntimeDriverConvertInternalPointer ((VOID **)&gRT->QueryCapsuleCapabilities); RuntimeDriverCalculateEfiHdrCrc (&gRT->Hdr); // @@ -350,9 +353,9 @@ RuntimeDriverSetVirtualAddressMap ( // // Convert the runtime fields of the EFI System Table and recompute the CRC-32 // - RuntimeDriverConvertInternalPointer ((VOID **) &gST->FirmwareVendor); - RuntimeDriverConvertInternalPointer ((VOID **) &gST->ConfigurationTable); - RuntimeDriverConvertInternalPointer ((VOID **) &gST->RuntimeServices); + RuntimeDriverConvertInternalPointer ((VOID **)&gST->FirmwareVendor); + RuntimeDriverConvertInternalPointer ((VOID **)&gST->ConfigurationTable); + RuntimeDriverConvertInternalPointer ((VOID **)&gST->RuntimeServices); RuntimeDriverCalculateEfiHdrCrc (&gST->Hdr); // @@ -383,12 +386,12 @@ RuntimeDriverSetVirtualAddressMap ( EFI_STATUS EFIAPI RuntimeDriverInitialize ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - EFI_LOADED_IMAGE_PROTOCOL *MyLoadedImage; + EFI_STATUS Status; + EFI_LOADED_IMAGE_PROTOCOL *MyLoadedImage; // // This image needs to be excluded from relocation for virtual mode, so cache @@ -397,7 +400,7 @@ RuntimeDriverInitialize ( Status = gBS->HandleProtocol ( ImageHandle, &gEfiLoadedImageProtocolGuid, - (VOID**)&MyLoadedImage + (VOID **)&MyLoadedImage ); ASSERT_EFI_ERROR (Status); mMyImageBase = MyLoadedImage->ImageBase; diff --git a/MdeModulePkg/Core/RuntimeDxe/Runtime.h b/MdeModulePkg/Core/RuntimeDxe/Runtime.h index 019a0cb140..cc422e783f 100644 --- a/MdeModulePkg/Core/RuntimeDxe/Runtime.h +++ b/MdeModulePkg/Core/RuntimeDxe/Runtime.h @@ -24,10 +24,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - // // Function Prototypes // + /** Calculate CRC32 for target data. @@ -112,8 +112,8 @@ RuntimeDriverSetVirtualAddressMap ( EFI_STATUS EFIAPI RuntimeDriverInitialize ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ); #endif diff --git a/MdeModulePkg/Include/Guid/AcpiS3Context.h b/MdeModulePkg/Include/Guid/AcpiS3Context.h index 72eb2cb278..645496d191 100644 --- a/MdeModulePkg/Include/Guid/AcpiS3Context.h +++ b/MdeModulePkg/Include/Guid/AcpiS3Context.h @@ -12,44 +12,43 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define SMM_S3_RESUME_SMM_32 SIGNATURE_64 ('S','M','M','S','3','_','3','2') -#define SMM_S3_RESUME_SMM_64 SIGNATURE_64 ('S','M','M','S','3','_','6','4') +#define SMM_S3_RESUME_SMM_32 SIGNATURE_64 ('S','M','M','S','3','_','3','2') +#define SMM_S3_RESUME_SMM_64 SIGNATURE_64 ('S','M','M','S','3','_','6','4') #pragma pack(1) typedef struct { - UINT64 Signature; - EFI_PHYSICAL_ADDRESS SmmS3ResumeEntryPoint; - EFI_PHYSICAL_ADDRESS SmmS3StackBase; - UINT64 SmmS3StackSize; - UINT64 SmmS3Cr0; - UINT64 SmmS3Cr3; - UINT64 SmmS3Cr4; - UINT16 ReturnCs; - EFI_PHYSICAL_ADDRESS ReturnEntryPoint; - EFI_PHYSICAL_ADDRESS ReturnContext1; - EFI_PHYSICAL_ADDRESS ReturnContext2; - EFI_PHYSICAL_ADDRESS ReturnStackPointer; - EFI_PHYSICAL_ADDRESS Smst; + UINT64 Signature; + EFI_PHYSICAL_ADDRESS SmmS3ResumeEntryPoint; + EFI_PHYSICAL_ADDRESS SmmS3StackBase; + UINT64 SmmS3StackSize; + UINT64 SmmS3Cr0; + UINT64 SmmS3Cr3; + UINT64 SmmS3Cr4; + UINT16 ReturnCs; + EFI_PHYSICAL_ADDRESS ReturnEntryPoint; + EFI_PHYSICAL_ADDRESS ReturnContext1; + EFI_PHYSICAL_ADDRESS ReturnContext2; + EFI_PHYSICAL_ADDRESS ReturnStackPointer; + EFI_PHYSICAL_ADDRESS Smst; } SMM_S3_RESUME_STATE; - typedef struct { - EFI_PHYSICAL_ADDRESS AcpiFacsTable; - EFI_PHYSICAL_ADDRESS IdtrProfile; - EFI_PHYSICAL_ADDRESS S3NvsPageTableAddress; - EFI_PHYSICAL_ADDRESS BootScriptStackBase; - UINT64 BootScriptStackSize; - EFI_PHYSICAL_ADDRESS S3DebugBufferAddress; + EFI_PHYSICAL_ADDRESS AcpiFacsTable; + EFI_PHYSICAL_ADDRESS IdtrProfile; + EFI_PHYSICAL_ADDRESS S3NvsPageTableAddress; + EFI_PHYSICAL_ADDRESS BootScriptStackBase; + UINT64 BootScriptStackSize; + EFI_PHYSICAL_ADDRESS S3DebugBufferAddress; } ACPI_S3_CONTEXT; typedef struct { - UINT16 ReturnCs; - UINT64 ReturnStatus; - EFI_PHYSICAL_ADDRESS ReturnEntryPoint; - EFI_PHYSICAL_ADDRESS ReturnStackPointer; - EFI_PHYSICAL_ADDRESS AsmTransferControl; - IA32_DESCRIPTOR Idtr; + UINT16 ReturnCs; + UINT64 ReturnStatus; + EFI_PHYSICAL_ADDRESS ReturnEntryPoint; + EFI_PHYSICAL_ADDRESS ReturnStackPointer; + EFI_PHYSICAL_ADDRESS AsmTransferControl; + IA32_DESCRIPTOR Idtr; } PEI_S3_RESUME_STATE; #pragma pack() @@ -59,8 +58,8 @@ typedef struct { 0xef98d3a, 0x3e33, 0x497a, {0xa4, 0x1, 0x77, 0xbe, 0x3e, 0xb7, 0x4f, 0x38} \ } -extern EFI_GUID gEfiAcpiS3ContextGuid; +extern EFI_GUID gEfiAcpiS3ContextGuid; -extern EFI_GUID gEfiAcpiVariableGuid; +extern EFI_GUID gEfiAcpiVariableGuid; #endif diff --git a/MdeModulePkg/Include/Guid/BootDiscoveryPolicy.h b/MdeModulePkg/Include/Guid/BootDiscoveryPolicy.h index f4e3b03ba1..69b5309530 100644 --- a/MdeModulePkg/Include/Guid/BootDiscoveryPolicy.h +++ b/MdeModulePkg/Include/Guid/BootDiscoveryPolicy.h @@ -11,13 +11,13 @@ #ifndef BOOT_DISCOVERY_POLICY_UI_LIB_H_ #define BOOT_DISCOVERY_POLICY_UI_LIB_H_ -#define BDP_CONNECT_MINIMAL 0 /* Do not connect any additional devices */ -#define BDP_CONNECT_NET 1 -#define BDP_CONNECT_ALL 2 +#define BDP_CONNECT_MINIMAL 0 /* Do not connect any additional devices */ +#define BDP_CONNECT_NET 1 +#define BDP_CONNECT_ALL 2 #define BOOT_DISCOVERY_POLICY_MGR_FORMSET_GUID { 0x5b6f7107, 0xbb3c, 0x4660, { 0x92, 0xcd, 0x54, 0x26, 0x90, 0x28, 0x0b, 0xbd } } -#define BOOT_DISCOVERY_POLICY_VAR L"BootDiscoveryPolicy" -#define BOOT_DISCOVERY_POLICY_OLD_VAR L"BootDiscoveryPolicyOld" +#define BOOT_DISCOVERY_POLICY_VAR L"BootDiscoveryPolicy" +#define BOOT_DISCOVERY_POLICY_OLD_VAR L"BootDiscoveryPolicyOld" #endif diff --git a/MdeModulePkg/Include/Guid/BootScriptExecutorVariable.h b/MdeModulePkg/Include/Guid/BootScriptExecutorVariable.h index 8eca785835..d780b1b853 100644 --- a/MdeModulePkg/Include/Guid/BootScriptExecutorVariable.h +++ b/MdeModulePkg/Include/Guid/BootScriptExecutorVariable.h @@ -23,20 +23,20 @@ #pragma pack(1) typedef struct { - EFI_PHYSICAL_ADDRESS BootScriptExecutorEntrypoint; + EFI_PHYSICAL_ADDRESS BootScriptExecutorEntrypoint; } BOOT_SCRIPT_EXECUTOR_VARIABLE; #pragma pack() #define BOOT_SCRIPT_EXECUTOR_VARIABLE_NAME L"BootScriptExecutorVariable" -extern EFI_GUID gEfiBootScriptExecutorVariableGuid; +extern EFI_GUID gEfiBootScriptExecutorVariableGuid; #define EFI_BOOT_SCRIPT_EXECUTOR_CONTEXT_GUID \ { \ 0x79cb58c4, 0xac51, 0x442f, {0xaf, 0xd7, 0x98, 0xe4, 0x7d, 0x2e, 0x99, 0x8} \ } -extern EFI_GUID gEfiBootScriptExecutorContextGuid; +extern EFI_GUID gEfiBootScriptExecutorContextGuid; #endif diff --git a/MdeModulePkg/Include/Guid/CapsuleVendor.h b/MdeModulePkg/Include/Guid/CapsuleVendor.h index aaa4369af6..46615adb25 100644 --- a/MdeModulePkg/Include/Guid/CapsuleVendor.h +++ b/MdeModulePkg/Include/Guid/CapsuleVendor.h @@ -30,7 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Name of capsule variable. /// -#define EFI_CAPSULE_VARIABLE_NAME L"CapsuleUpdateData" +#define EFI_CAPSULE_VARIABLE_NAME L"CapsuleUpdateData" /// /// The data structure of the capsule guid hob entry. @@ -38,22 +38,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// UEFI_CAPSULE_HOB instead. /// typedef struct { - EFI_PHYSICAL_ADDRESS BaseAddress; ///< Capsule data start address. - UINT32 Length; ///< Length of capsule data. + EFI_PHYSICAL_ADDRESS BaseAddress; ///< Capsule data start address. + UINT32 Length; ///< Length of capsule data. } CAPSULE_HOB_INFO; // // The variable describes the long mode buffer used by IA32 Capsule PEIM // to call X64 CapsuleCoalesce code to handle >4GB capsule blocks. // -#define EFI_CAPSULE_LONG_MODE_BUFFER_NAME L"CapsuleLongModeBuffer" +#define EFI_CAPSULE_LONG_MODE_BUFFER_NAME L"CapsuleLongModeBuffer" typedef struct { - EFI_PHYSICAL_ADDRESS PageTableAddress; - EFI_PHYSICAL_ADDRESS StackBaseAddress; - UINT64 StackSize; + EFI_PHYSICAL_ADDRESS PageTableAddress; + EFI_PHYSICAL_ADDRESS StackBaseAddress; + UINT64 StackSize; } EFI_CAPSULE_LONG_MODE_BUFFER; -extern EFI_GUID gEfiCapsuleVendorGuid; +extern EFI_GUID gEfiCapsuleVendorGuid; #endif // #ifndef _EFI_CAPSULE_VENDOR_GUID_H_ diff --git a/MdeModulePkg/Include/Guid/ConnectConInEvent.h b/MdeModulePkg/Include/Guid/ConnectConInEvent.h index 3deaa16e8a..6feeca2291 100644 --- a/MdeModulePkg/Include/Guid/ConnectConInEvent.h +++ b/MdeModulePkg/Include/Guid/ConnectConInEvent.h @@ -13,6 +13,6 @@ #define CONNECT_CONIN_EVENT_GUID \ { 0xdb4e8151, 0x57ed, 0x4bed, { 0x88, 0x33, 0x67, 0x51, 0xb5, 0xd1, 0xa8, 0xd7 }} -extern EFI_GUID gConnectConInEventGuid; +extern EFI_GUID gConnectConInEventGuid; #endif diff --git a/MdeModulePkg/Include/Guid/ConsoleInDevice.h b/MdeModulePkg/Include/Guid/ConsoleInDevice.h index 9df4962b98..597f0c248e 100644 --- a/MdeModulePkg/Include/Guid/ConsoleInDevice.h +++ b/MdeModulePkg/Include/Guid/ConsoleInDevice.h @@ -13,6 +13,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_CONSOLE_IN_DEVICE_GUID \ { 0xd3b36f2b, 0xd551, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } } -extern EFI_GUID gEfiConsoleInDeviceGuid; +extern EFI_GUID gEfiConsoleInDeviceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/ConsoleOutDevice.h b/MdeModulePkg/Include/Guid/ConsoleOutDevice.h index b65e026371..9cf13b8d54 100644 --- a/MdeModulePkg/Include/Guid/ConsoleOutDevice.h +++ b/MdeModulePkg/Include/Guid/ConsoleOutDevice.h @@ -12,6 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_CONSOLE_OUT_DEVICE_GUID \ { 0xd3b36f2c, 0xd551, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } } -extern EFI_GUID gEfiConsoleOutDeviceGuid; +extern EFI_GUID gEfiConsoleOutDeviceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h b/MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h index 32d71e2d04..84c7c09ac3 100644 --- a/MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h +++ b/MdeModulePkg/Include/Guid/Crc32GuidedSectionExtraction.h @@ -13,6 +13,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_CRC32_GUIDED_SECTION_EXTRACTION_GUID \ { 0xFC1BCDB0, 0x7D31, 0x49aa, {0x93, 0x6A, 0xA4, 0x60, 0x0D, 0x9D, 0xD0, 0x83 } } -extern EFI_GUID gEfiCrc32GuidedSectionExtractionGuid; +extern EFI_GUID gEfiCrc32GuidedSectionExtractionGuid; #endif diff --git a/MdeModulePkg/Include/Guid/DebugMask.h b/MdeModulePkg/Include/Guid/DebugMask.h index 4ea1981f1e..427bcbb147 100644 --- a/MdeModulePkg/Include/Guid/DebugMask.h +++ b/MdeModulePkg/Include/Guid/DebugMask.h @@ -19,26 +19,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Forward reference for pure ANSI compatability /// -typedef struct _EFI_DEBUG_MASK_PROTOCOL EFI_DEBUG_MASK_PROTOCOL; +typedef struct _EFI_DEBUG_MASK_PROTOCOL EFI_DEBUG_MASK_PROTOCOL; /// /// /// -#define EFI_DEBUG_MASK_REVISION 0x00010000 +#define EFI_DEBUG_MASK_REVISION 0x00010000 // // DebugMask member functions definition // typedef EFI_STATUS -(EFIAPI * EFI_GET_DEBUG_MASK) ( +(EFIAPI *EFI_GET_DEBUG_MASK)( IN EFI_DEBUG_MASK_PROTOCOL *This, IN OUT UINTN *CurrentDebugMask ); typedef EFI_STATUS -(EFIAPI *EFI_SET_DEBUG_MASK) ( +(EFIAPI *EFI_SET_DEBUG_MASK)( IN EFI_DEBUG_MASK_PROTOCOL *This, IN UINTN NewDebugMask ); @@ -47,12 +47,12 @@ EFI_STATUS /// DebugMask protocol definition /// struct _EFI_DEBUG_MASK_PROTOCOL { - INT64 Revision; - EFI_GET_DEBUG_MASK GetDebugMask; - EFI_SET_DEBUG_MASK SetDebugMask; + INT64 Revision; + EFI_GET_DEBUG_MASK GetDebugMask; + EFI_SET_DEBUG_MASK SetDebugMask; }; -extern EFI_GUID gEfiDebugMaskProtocolGuid; +extern EFI_GUID gEfiDebugMaskProtocolGuid; /// /// GUID used to store the global debug mask in an the "EFIDebug" EFI Variabe @@ -63,6 +63,6 @@ extern EFI_GUID gEfiDebugMaskProtocolGuid; #define DEBUG_MASK_VARIABLE_NAME L"EFIDebug" -extern EFI_GUID gEfiGenericVariableGuid; +extern EFI_GUID gEfiGenericVariableGuid; #endif diff --git a/MdeModulePkg/Include/Guid/DriverSampleHii.h b/MdeModulePkg/Include/Guid/DriverSampleHii.h index 434ae91a99..b8d8c79845 100644 --- a/MdeModulePkg/Include/Guid/DriverSampleHii.h +++ b/MdeModulePkg/Include/Guid/DriverSampleHii.h @@ -24,8 +24,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xF5E655D9, 0x02A6, 0x46f2, {0x9E, 0x76, 0xB8, 0xBE, 0x8E, 0x60, 0xAB, 0x22} \ } -extern EFI_GUID gDriverSampleFormSetGuid; -extern EFI_GUID gDriverSampleInventoryGuid; -extern EFI_GUID gEfiIfrRefreshIdOpGuid; +extern EFI_GUID gDriverSampleFormSetGuid; +extern EFI_GUID gDriverSampleInventoryGuid; +extern EFI_GUID gEfiIfrRefreshIdOpGuid; #endif diff --git a/MdeModulePkg/Include/Guid/EndOfS3Resume.h b/MdeModulePkg/Include/Guid/EndOfS3Resume.h index c823ec8551..1b89f3cc6e 100644 --- a/MdeModulePkg/Include/Guid/EndOfS3Resume.h +++ b/MdeModulePkg/Include/Guid/EndOfS3Resume.h @@ -15,6 +15,6 @@ 0x96f5296d, 0x05f7, 0x4f3c, {0x84, 0x67, 0xe4, 0x56, 0x89, 0x0e, 0x0c, 0xb5 } \ } -extern EFI_GUID gEdkiiEndOfS3ResumeGuid; +extern EFI_GUID gEdkiiEndOfS3ResumeGuid; #endif diff --git a/MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h b/MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h index 8bc2cfb069..fbed870afb 100644 --- a/MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h +++ b/MdeModulePkg/Include/Guid/EventExitBootServiceFailed.h @@ -13,6 +13,6 @@ #define EVENT_GROUP_EXIT_BOOT_SERVICES_FAILED \ { 0x4f6c5507, 0x232f, 0x4787, { 0xb9, 0x5e, 0x72, 0xf8, 0x62, 0x49, 0xc, 0xb1 } } -extern EFI_GUID gEventExitBootServicesFailedGuid; +extern EFI_GUID gEventExitBootServicesFailedGuid; #endif diff --git a/MdeModulePkg/Include/Guid/ExtendedFirmwarePerformance.h b/MdeModulePkg/Include/Guid/ExtendedFirmwarePerformance.h index c04f79c6eb..20be7654c8 100644 --- a/MdeModulePkg/Include/Guid/ExtendedFirmwarePerformance.h +++ b/MdeModulePkg/Include/Guid/ExtendedFirmwarePerformance.h @@ -15,26 +15,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Known performance tokens // -#define SEC_TOK "SEC" ///< SEC Phase -#define DXE_TOK "DXE" ///< DXE Phase -#define PEI_TOK "PEI" ///< PEI Phase -#define BDS_TOK "BDS" ///< BDS Phase -#define DRIVERBINDING_START_TOK "DB:Start:" ///< Driver Binding Start() function call -#define DRIVERBINDING_SUPPORT_TOK "DB:Support:" ///< Driver Binding Support() function call -#define DRIVERBINDING_STOP_TOK "DB:Stop:" ///< Driver Binding Stop() function call -#define LOAD_IMAGE_TOK "LoadImage:" ///< Load a dispatched module -#define START_IMAGE_TOK "StartImage:" ///< Dispatched Modules Entry Point execution -#define PEIM_TOK "PEIM" ///< PEIM Modules Entry Point execution +#define SEC_TOK "SEC" ///< SEC Phase +#define DXE_TOK "DXE" ///< DXE Phase +#define PEI_TOK "PEI" ///< PEI Phase +#define BDS_TOK "BDS" ///< BDS Phase +#define DRIVERBINDING_START_TOK "DB:Start:" ///< Driver Binding Start() function call +#define DRIVERBINDING_SUPPORT_TOK "DB:Support:" ///< Driver Binding Support() function call +#define DRIVERBINDING_STOP_TOK "DB:Stop:" ///< Driver Binding Stop() function call +#define LOAD_IMAGE_TOK "LoadImage:" ///< Load a dispatched module +#define START_IMAGE_TOK "StartImage:" ///< Dispatched Modules Entry Point execution +#define PEIM_TOK "PEIM" ///< PEIM Modules Entry Point execution // // Misc defines // -#define FPDT_RECORD_REVISION_1 (0x01) +#define FPDT_RECORD_REVISION_1 (0x01) // // Length field in EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER is a UINT8, thus: // -#define FPDT_MAX_PERF_RECORD_SIZE (MAX_UINT8) +#define FPDT_MAX_PERF_RECORD_SIZE (MAX_UINT8) // // FPDT Record Types @@ -48,168 +48,168 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // EDKII extended Fpdt record structures // -#define FPDT_STRING_EVENT_RECORD_NAME_LENGTH 24 +#define FPDT_STRING_EVENT_RECORD_NAME_LENGTH 24 #pragma pack(1) // // FPDT Boot Performance Guid Event Record Structure // typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; /// /// ProgressID < 0x10 are reserved for core performance entries. /// Start measurement point shall have lowered one nibble set to zero and /// corresponding end points shall have lowered one nibble set to non-zero value; /// keeping other nibbles same as start point. /// - UINT16 ProgressID; + UINT16 ProgressID; /// /// APIC ID for the processor in the system used as a timestamp clock source. /// If only one timestamp clock source is used, this field is Reserved and populated as 0. /// - UINT32 ApicID; + UINT32 ApicID; /// /// 64-bit value (nanosecond) describing elapsed time since the most recent deassertion of processor reset. /// - UINT64 Timestamp; + UINT64 Timestamp; /// /// If ProgressID < 0x10, GUID of the referenced module; otherwise, GUID of the module logging the event. /// - EFI_GUID Guid; + EFI_GUID Guid; } FPDT_GUID_EVENT_RECORD; // // FPDT Boot Performance Dynamic String Event Record Structure // typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; /// /// ProgressID < 0x10 are reserved for core performance entries. /// Start measurement point shall have lowered one nibble set to zero and /// corresponding end points shall have lowered one nibble set to non-zero value; /// keeping other nibbles same as start point. /// - UINT16 ProgressID; + UINT16 ProgressID; /// /// APIC ID for the processor in the system used as a timestamp clock source. /// If only one timestamp clock source is used, this field is Reserved and populated as 0. /// - UINT32 ApicID; + UINT32 ApicID; /// /// 64-bit value (nanosecond) describing elapsed time since the most recent deassertion of processor reset. /// - UINT64 Timestamp; + UINT64 Timestamp; /// /// If ProgressID < 0x10, GUID of the referenced module; otherwise, GUID of the module logging the event. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// ASCII string describing the module. Padding supplied at the end if necessary with null characters (0x00). /// It may be module name, function name, or token name. /// - CHAR8 String[0]; + CHAR8 String[0]; } FPDT_DYNAMIC_STRING_EVENT_RECORD; // // FPDT Boot Performance Dual GUID String Event Record Structure // typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; /// /// ProgressID < 0x10 are reserved for core performance entries. /// Start measurement point shall have lowered one nibble set to zero and /// corresponding end points shall have lowered one nibble set to non-zero value; /// keeping other nibbles same as start point. /// - UINT16 ProgressID; + UINT16 ProgressID; /// /// APIC ID for the processor in the system used as a timestamp clock source. /// If only one timestamp clock source is used, this field is Reserved and populated as 0. /// - UINT32 ApicID; + UINT32 ApicID; /// /// 64-bit value (nanosecond) describing elapsed time since the most recent deassertion of processor reset. /// - UINT64 Timestamp; + UINT64 Timestamp; /// /// GUID of the module logging the event. /// - EFI_GUID Guid1; + EFI_GUID Guid1; /// /// Event or Ppi or Protocol GUID for Callback. /// - EFI_GUID Guid2; + EFI_GUID Guid2; /// /// ASCII string describing the module. Padding supplied at the end if necessary with null characters (0x00). /// It is the function name. /// - CHAR8 String[0]; + CHAR8 String[0]; } FPDT_DUAL_GUID_STRING_EVENT_RECORD; // // FPDT Boot Performance GUID Qword Event Record Structure // typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; /// /// ProgressID < 0x10 are reserved for core performance entries. /// Start measurement point shall have lowered one nibble set to zero and /// corresponding end points shall have lowered one nibble set to non-zero value; /// keeping other nibbles same as start point. /// - UINT16 ProgressID; + UINT16 ProgressID; /// /// APIC ID for the processor in the system used as a timestamp clock source. /// If only one timestamp clock source is used, this field is Reserved and populated as 0. /// - UINT32 ApicID; + UINT32 ApicID; /// /// 64-bit value (nanosecond) describing elapsed time since the most recent deassertion of processor reset. /// - UINT64 Timestamp; + UINT64 Timestamp; /// /// GUID of the module logging the event /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// Qword of misc data, meaning depends on the ProgressId /// - UINT64 Qword; + UINT64 Qword; } FPDT_GUID_QWORD_EVENT_RECORD; // // FPDT Boot Performance GUID Qword String Event Record Structure // typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER Header; /// /// ProgressID < 0x10 are reserved for core performance entries. /// Start measurement point shall have lowered one nibble set to zero and /// corresponding end points shall have lowered one nibble set to non-zero value; /// keeping other nibbles same as start point. /// - UINT16 ProgressID; + UINT16 ProgressID; /// /// APIC ID for the processor in the system used as a timestamp clock source. /// If only one timestamp clock source is used, this field is Reserved and populated as 0. /// - UINT32 ApicID; + UINT32 ApicID; /// /// 64-bit value (nanosecond) describing elapsed time since the most recent deassertion of processor reset. /// - UINT64 Timestamp; + UINT64 Timestamp; /// /// GUID of the module logging the event /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// Qword of misc data, meaning depends on the ProgressId /// - UINT64 Qword; + UINT64 Qword; /// /// ASCII string describing the module. Padding supplied at the end if necessary with null characters (0x00). /// - CHAR8 String[0]; + CHAR8 String[0]; } FPDT_GUID_QWORD_STRING_EVENT_RECORD; #pragma pack() @@ -218,24 +218,24 @@ typedef struct { // Union of all FPDT records // typedef union { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER RecordHeader; - FPDT_GUID_EVENT_RECORD GuidEvent; - FPDT_DYNAMIC_STRING_EVENT_RECORD DynamicStringEvent; - FPDT_DUAL_GUID_STRING_EVENT_RECORD DualGuidStringEvent; - FPDT_GUID_QWORD_EVENT_RECORD GuidQwordEvent; - FPDT_GUID_QWORD_STRING_EVENT_RECORD GuidQwordStringEvent; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER RecordHeader; + FPDT_GUID_EVENT_RECORD GuidEvent; + FPDT_DYNAMIC_STRING_EVENT_RECORD DynamicStringEvent; + FPDT_DUAL_GUID_STRING_EVENT_RECORD DualGuidStringEvent; + FPDT_GUID_QWORD_EVENT_RECORD GuidQwordEvent; + FPDT_GUID_QWORD_STRING_EVENT_RECORD GuidQwordStringEvent; } FPDT_RECORD; // // Union of all pointers to FPDT records // typedef union { - EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *RecordHeader; - FPDT_GUID_EVENT_RECORD *GuidEvent; - FPDT_DYNAMIC_STRING_EVENT_RECORD *DynamicStringEvent; - FPDT_DUAL_GUID_STRING_EVENT_RECORD *DualGuidStringEvent; - FPDT_GUID_QWORD_EVENT_RECORD *GuidQwordEvent; - FPDT_GUID_QWORD_STRING_EVENT_RECORD *GuidQwordStringEvent; + EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *RecordHeader; + FPDT_GUID_EVENT_RECORD *GuidEvent; + FPDT_DYNAMIC_STRING_EVENT_RECORD *DynamicStringEvent; + FPDT_DUAL_GUID_STRING_EVENT_RECORD *DualGuidStringEvent; + FPDT_GUID_QWORD_EVENT_RECORD *GuidQwordEvent; + FPDT_GUID_QWORD_STRING_EVENT_RECORD *GuidQwordStringEvent; } FPDT_RECORD_PTR; /// @@ -244,11 +244,11 @@ typedef union { /// Data - FPDT_PEI_EXT_PERF_HEADER + one or more FPDT records /// typedef struct { - UINT32 SizeOfAllEntries; - UINT32 LoadImageCount; - UINT32 HobIsFull; + UINT32 SizeOfAllEntries; + UINT32 LoadImageCount; + UINT32 HobIsFull; } FPDT_PEI_EXT_PERF_HEADER; -extern EFI_GUID gEdkiiFpdtExtendedFirmwarePerformanceGuid; +extern EFI_GUID gEdkiiFpdtExtendedFirmwarePerformanceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/FaultTolerantWrite.h b/MdeModulePkg/Include/Guid/FaultTolerantWrite.h index da716ed144..29c4aeba6a 100644 --- a/MdeModulePkg/Include/Guid/FaultTolerantWrite.h +++ b/MdeModulePkg/Include/Guid/FaultTolerantWrite.h @@ -24,16 +24,16 @@ typedef struct { /// /// Target address to be updated in FTW last write. /// - EFI_PHYSICAL_ADDRESS TargetAddress; + EFI_PHYSICAL_ADDRESS TargetAddress; /// /// Spare address to back up the updated buffer. /// - EFI_PHYSICAL_ADDRESS SpareAddress; + EFI_PHYSICAL_ADDRESS SpareAddress; /// /// The length of data that have been backed up in spare block. /// It is also the length of target block that has been erased. /// - UINT64 Length; + UINT64 Length; } FAULT_TOLERANT_WRITE_LAST_WRITE_DATA; // @@ -43,6 +43,6 @@ typedef struct { // It means the target buffer has been backed up in spare block, then target block has been erased, // but the target buffer has not been writen in target block from spare block. // -extern EFI_GUID gEdkiiFaultTolerantWriteGuid; +extern EFI_GUID gEdkiiFaultTolerantWriteGuid; #endif diff --git a/MdeModulePkg/Include/Guid/FirmwarePerformance.h b/MdeModulePkg/Include/Guid/FirmwarePerformance.h index e101ddd987..3ce146eba1 100644 --- a/MdeModulePkg/Include/Guid/FirmwarePerformance.h +++ b/MdeModulePkg/Include/Guid/FirmwarePerformance.h @@ -60,9 +60,9 @@ /// This structure will be installed into ACPI table as FPDT in normal boot path. /// typedef struct { - EFI_ACPI_DESCRIPTION_HEADER Header; ///< Common ACPI description table header. - EFI_ACPI_5_0_FPDT_BOOT_PERFORMANCE_TABLE_POINTER_RECORD BootPointerRecord; ///< Basic Boot Performance Table Pointer record. - EFI_ACPI_5_0_FPDT_S3_PERFORMANCE_TABLE_POINTER_RECORD S3PointerRecord; ///< S3 Performance Table Pointer record. + EFI_ACPI_DESCRIPTION_HEADER Header; ///< Common ACPI description table header. + EFI_ACPI_5_0_FPDT_BOOT_PERFORMANCE_TABLE_POINTER_RECORD BootPointerRecord; ///< Basic Boot Performance Table Pointer record. + EFI_ACPI_5_0_FPDT_S3_PERFORMANCE_TABLE_POINTER_RECORD S3PointerRecord; ///< S3 Performance Table Pointer record. } FIRMWARE_PERFORMANCE_TABLE; /// @@ -71,9 +71,9 @@ typedef struct { /// suspend and S3 resume boot path. /// typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. - EFI_ACPI_5_0_FPDT_S3_RESUME_RECORD S3Resume; ///< Basic S3 Resume performance record. - EFI_ACPI_5_0_FPDT_S3_SUSPEND_RECORD S3Suspend; ///< Basic S3 Suspend performance record. + EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. + EFI_ACPI_5_0_FPDT_S3_RESUME_RECORD S3Resume; ///< Basic S3 Resume performance record. + EFI_ACPI_5_0_FPDT_S3_SUSPEND_RECORD S3Suspend; ///< Basic S3 Suspend performance record. } S3_PERFORMANCE_TABLE; /// @@ -81,8 +81,8 @@ typedef struct { /// This structure contains BasicBoot performance record. /// typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. - EFI_ACPI_5_0_FPDT_FIRMWARE_BASIC_BOOT_RECORD BasicBoot; ///< Basic Boot Resume performance record. + EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. + EFI_ACPI_5_0_FPDT_FIRMWARE_BASIC_BOOT_RECORD BasicBoot; ///< Basic Boot Resume performance record. // // one or more boot performance records. // @@ -93,7 +93,7 @@ typedef struct { /// /// typedef struct { - EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. + EFI_ACPI_5_0_FPDT_PERFORMANCE_TABLE_HEADER Header; ///< Common ACPI table header. // // one or more boot performance records. // @@ -103,8 +103,8 @@ typedef struct { /// Performance data pointed by Performance Pointer Record. /// typedef struct { - BOOT_PERFORMANCE_TABLE BootPerformance; ///< Basic Boot Performance. - S3_PERFORMANCE_TABLE S3Performance; ///< S3 performance. + BOOT_PERFORMANCE_TABLE BootPerformance; ///< Basic Boot Performance. + S3_PERFORMANCE_TABLE S3Performance; ///< S3 performance. } FIRMWARE_PERFORMANCE_RUNTIME_DATA; /// @@ -112,8 +112,8 @@ typedef struct { /// This Variable is produced by FPDT DXE module. /// typedef struct { - EFI_PHYSICAL_ADDRESS BootPerformanceTablePointer; ///< Pointer to Boot Performance Table. - EFI_PHYSICAL_ADDRESS S3PerformanceTablePointer; ///< Pointer to S3 Performance Table. + EFI_PHYSICAL_ADDRESS BootPerformanceTablePointer; ///< Pointer to Boot Performance Table. + EFI_PHYSICAL_ADDRESS S3PerformanceTablePointer; ///< Pointer to S3 Performance Table. } FIRMWARE_PERFORMANCE_VARIABLE; #pragma pack() @@ -121,19 +121,19 @@ typedef struct { // // Log BOOT RECORD from SMM driver on boot time. // -#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_SIZE 1 -#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA 2 -#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET 3 +#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_SIZE 1 +#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA 2 +#define SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET 3 typedef struct { - UINTN Function; - EFI_STATUS ReturnStatus; - UINTN BootRecordSize; - VOID *BootRecordData; - UINTN BootRecordOffset; + UINTN Function; + EFI_STATUS ReturnStatus; + UINTN BootRecordSize; + VOID *BootRecordData; + UINTN BootRecordOffset; } SMM_BOOT_RECORD_COMMUNICATE; -extern EFI_GUID gEfiFirmwarePerformanceGuid; -extern EFI_GUID gFirmwarePerformanceS3PointerGuid; +extern EFI_GUID gEfiFirmwarePerformanceGuid; +extern EFI_GUID gFirmwarePerformanceS3PointerGuid; #endif diff --git a/MdeModulePkg/Include/Guid/HiiBootMaintenanceFormset.h b/MdeModulePkg/Include/Guid/HiiBootMaintenanceFormset.h index 154ef52665..7c58557499 100644 --- a/MdeModulePkg/Include/Guid/HiiBootMaintenanceFormset.h +++ b/MdeModulePkg/Include/Guid/HiiBootMaintenanceFormset.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __HII_BOOT_MAINTENANCE_FORMSET_H__ #define __HII_BOOT_MAINTENANCE_FORMSET_H__ @@ -16,7 +15,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_IFR_BOOT_MAINTENANCE_GUID \ { 0xb2dedc91, 0xd59f, 0x48d2, { 0x89, 0x8a, 0x12, 0x49, 0xc, 0x74, 0xa4, 0xe0 } } - -extern EFI_GUID gEfiIfrBootMaintenanceGuid; +extern EFI_GUID gEfiIfrBootMaintenanceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/HiiResourceSampleHii.h b/MdeModulePkg/Include/Guid/HiiResourceSampleHii.h index e6ee4d2820..e59a7c47ee 100644 --- a/MdeModulePkg/Include/Guid/HiiResourceSampleHii.h +++ b/MdeModulePkg/Include/Guid/HiiResourceSampleHii.h @@ -12,6 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define HII_RESOURCE_SAMPLE_FORM_SET_GUID \ { 0x4f4ef7f0, 0xaa29, 0x4ce9, { 0xba, 0x41, 0x64, 0x3e, 0x1, 0x23, 0xa9, 0x9f }} -extern EFI_GUID gHiiResourceSamleFormSetGuid; +extern EFI_GUID gHiiResourceSamleFormSetGuid; #endif diff --git a/MdeModulePkg/Include/Guid/IdleLoopEvent.h b/MdeModulePkg/Include/Guid/IdleLoopEvent.h index 50613d7bee..7afc9dcbcf 100644 --- a/MdeModulePkg/Include/Guid/IdleLoopEvent.h +++ b/MdeModulePkg/Include/Guid/IdleLoopEvent.h @@ -13,6 +13,6 @@ #define IDLE_LOOP_EVENT_GUID \ { 0x3c8d294c, 0x5fc3, 0x4451, { 0xbb, 0x31, 0xc4, 0xc0, 0x32, 0x29, 0x5e, 0x6c } } -extern EFI_GUID gIdleLoopEventGuid; +extern EFI_GUID gIdleLoopEventGuid; #endif diff --git a/MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h b/MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h index 6d73bf3838..bf1f47531d 100644 --- a/MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h +++ b/MdeModulePkg/Include/Guid/LoadModuleAtFixedAddress.h @@ -17,8 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE_GUID \ { 0x2CA88B53,0xD296,0x4080, { 0xA4,0xA5,0xCA,0xD9,0xBA,0xE2,0x4B,0x9} } - -extern EFI_GUID gLoadFixedAddressConfigurationTableGuid; +extern EFI_GUID gLoadFixedAddressConfigurationTableGuid; typedef struct { EFI_PHYSICAL_ADDRESS DxeCodeTopAddress; ///< The top address below which the Dxe runtime code and below which the Dxe runtime/boot code and PEI code. diff --git a/MdeModulePkg/Include/Guid/LzmaDecompress.h b/MdeModulePkg/Include/Guid/LzmaDecompress.h index 24099eb36c..b2b6d61c94 100644 --- a/MdeModulePkg/Include/Guid/LzmaDecompress.h +++ b/MdeModulePkg/Include/Guid/LzmaDecompress.h @@ -23,7 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define LZMAF86_CUSTOM_DECOMPRESS_GUID \ { 0xD42AE6BD, 0x1352, 0x4bfb, { 0x90, 0x9A, 0xCA, 0x72, 0xA6, 0xEA, 0xE8, 0x89 } } -extern GUID gLzmaCustomDecompressGuid; -extern GUID gLzmaF86CustomDecompressGuid; +extern GUID gLzmaCustomDecompressGuid; +extern GUID gLzmaF86CustomDecompressGuid; #endif diff --git a/MdeModulePkg/Include/Guid/MdeModuleHii.h b/MdeModulePkg/Include/Guid/MdeModuleHii.h index 2de3846391..798bcbaaae 100644 --- a/MdeModulePkg/Include/Guid/MdeModuleHii.h +++ b/MdeModulePkg/Include/Guid/MdeModuleHii.h @@ -9,9 +9,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __MDEMODULE_HII_H__ #define __MDEMODULE_HII_H__ -#define NARROW_CHAR 0xFFF0 -#define WIDE_CHAR 0xFFF1 -#define NON_BREAKING_CHAR 0xFFF2 +#define NARROW_CHAR 0xFFF0 +#define WIDE_CHAR 0xFFF1 +#define NON_BREAKING_CHAR 0xFFF2 /// /// State defined for password statemachine . @@ -30,91 +30,91 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// EDKII implementation extension opcodes, new extension can be added here later. /// -#define EFI_IFR_EXTEND_OP_LABEL 0x0 -#define EFI_IFR_EXTEND_OP_BANNER 0x1 -#define EFI_IFR_EXTEND_OP_TIMEOUT 0x2 -#define EFI_IFR_EXTEND_OP_CLASS 0x3 -#define EFI_IFR_EXTEND_OP_SUBCLASS 0x4 +#define EFI_IFR_EXTEND_OP_LABEL 0x0 +#define EFI_IFR_EXTEND_OP_BANNER 0x1 +#define EFI_IFR_EXTEND_OP_TIMEOUT 0x2 +#define EFI_IFR_EXTEND_OP_CLASS 0x3 +#define EFI_IFR_EXTEND_OP_SUBCLASS 0x4 /// /// Label opcode. /// typedef struct _EFI_IFR_GUID_LABEL { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_TIANO_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_LABEL. /// - UINT8 ExtendOpCode; + UINT8 ExtendOpCode; /// /// Label Number. /// - UINT16 Number; + UINT16 Number; } EFI_IFR_GUID_LABEL; -#define EFI_IFR_BANNER_ALIGN_LEFT 0 -#define EFI_IFR_BANNER_ALIGN_CENTER 1 -#define EFI_IFR_BANNER_ALIGN_RIGHT 2 +#define EFI_IFR_BANNER_ALIGN_LEFT 0 +#define EFI_IFR_BANNER_ALIGN_CENTER 1 +#define EFI_IFR_BANNER_ALIGN_RIGHT 2 /// /// Banner opcode. /// typedef struct _EFI_IFR_GUID_BANNER { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_TIANO_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_BANNER /// - UINT8 ExtendOpCode; - EFI_STRING_ID Title; ///< The string token for the banner title. - UINT16 LineNumber; ///< 1-based line number. - UINT8 Alignment; ///< left, center, or right-aligned. + UINT8 ExtendOpCode; + EFI_STRING_ID Title; ///< The string token for the banner title. + UINT16 LineNumber; ///< 1-based line number. + UINT8 Alignment; ///< left, center, or right-aligned. } EFI_IFR_GUID_BANNER; /// /// Timeout opcode. /// typedef struct _EFI_IFR_GUID_TIMEOUT { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_TIANO_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_TIMEOUT. /// - UINT8 ExtendOpCode; - UINT16 TimeOut; ///< TimeOut Value. + UINT8 ExtendOpCode; + UINT16 TimeOut; ///< TimeOut Value. } EFI_IFR_GUID_TIMEOUT; -#define EFI_NON_DEVICE_CLASS 0x00 -#define EFI_DISK_DEVICE_CLASS 0x01 -#define EFI_VIDEO_DEVICE_CLASS 0x02 -#define EFI_NETWORK_DEVICE_CLASS 0x04 -#define EFI_INPUT_DEVICE_CLASS 0x08 -#define EFI_ON_BOARD_DEVICE_CLASS 0x10 -#define EFI_OTHER_DEVICE_CLASS 0x20 +#define EFI_NON_DEVICE_CLASS 0x00 +#define EFI_DISK_DEVICE_CLASS 0x01 +#define EFI_VIDEO_DEVICE_CLASS 0x02 +#define EFI_NETWORK_DEVICE_CLASS 0x04 +#define EFI_INPUT_DEVICE_CLASS 0x08 +#define EFI_ON_BOARD_DEVICE_CLASS 0x10 +#define EFI_OTHER_DEVICE_CLASS 0x20 /// /// Device Class opcode. /// typedef struct _EFI_IFR_GUID_CLASS { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_TIANO_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_CLASS. /// - UINT8 ExtendOpCode; - UINT16 Class; ///< Device Class from the above. + UINT8 ExtendOpCode; + UINT16 Class; ///< Device Class from the above. } EFI_IFR_GUID_CLASS; #define EFI_SETUP_APPLICATION_SUBCLASS 0x00 @@ -126,16 +126,16 @@ typedef struct _EFI_IFR_GUID_CLASS { /// SubClass opcode /// typedef struct _EFI_IFR_GUID_SUBCLASS { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_TIANO_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_SUBCLASS. /// - UINT8 ExtendOpCode; - UINT16 SubClass; ///< Sub Class type from the above. + UINT8 ExtendOpCode; + UINT16 SubClass; ///< Sub Class type from the above. } EFI_IFR_GUID_SUBCLASS; /// @@ -149,60 +149,60 @@ typedef struct _EFI_IFR_GUID_SUBCLASS { /// One is for framework OneOf question Option Key value; /// another is for framework vareqval. /// -#define EFI_IFR_EXTEND_OP_OPTIONKEY 0x0 -#define EFI_IFR_EXTEND_OP_VAREQNAME 0x1 +#define EFI_IFR_EXTEND_OP_OPTIONKEY 0x0 +#define EFI_IFR_EXTEND_OP_VAREQNAME 0x1 /// /// Store the framework vfr option key value. /// typedef struct _EFI_IFR_GUID_OPTIONKEY { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_FRAMEWORK_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_OPTIONKEY. /// - UINT8 ExtendOpCode; + UINT8 ExtendOpCode; /// /// OneOf Questiond ID binded by OneOf Option. /// - EFI_QUESTION_ID QuestionId; + EFI_QUESTION_ID QuestionId; /// /// The OneOf Option Value. /// - EFI_IFR_TYPE_VALUE OptionValue; + EFI_IFR_TYPE_VALUE OptionValue; /// /// The Framework OneOf Option Key Value. /// - UINT16 KeyValue; + UINT16 KeyValue; } EFI_IFR_GUID_OPTIONKEY; /// /// Store the framework vfr vareqval name number. /// typedef struct _EFI_IFR_GUID_VAREQNAME { - EFI_IFR_OP_HEADER Header; + EFI_IFR_OP_HEADER Header; /// /// EFI_IFR_FRAMEWORK_GUID. /// - EFI_GUID Guid; + EFI_GUID Guid; /// /// EFI_IFR_EXTEND_OP_VAREQNAME. /// - UINT8 ExtendOpCode; + UINT8 ExtendOpCode; /// /// Question ID of the Numeric Opcode created. /// - EFI_QUESTION_ID QuestionId; + EFI_QUESTION_ID QuestionId; /// /// For vareqval (0x100), NameId is 0x100. /// This value will convert to a Unicode String following this rule; /// sprintf(StringBuffer, "%d", NameId) . /// The the Unicode String will be used as a EFI Variable Name. /// - UINT16 NameId; + UINT16 NameId; } EFI_IFR_GUID_VAREQNAME; /// @@ -215,18 +215,17 @@ typedef struct _EFI_IFR_GUID_VAREQNAME { /// EDKII implementation extension flags, used to indaicate the disply style and bit width for bit filed storage. /// Two high bits for display style and the low six bits for bit width. /// -#define EDKII_IFR_DISPLAY_BIT 0xC0 -#define EDKII_IFR_DISPLAY_INT_DEC_BIT 0x00 -#define EDKII_IFR_DISPLAY_UINT_DEC_BIT 0x40 -#define EDKII_IFR_DISPLAY_UINT_HEX_BIT 0x80 +#define EDKII_IFR_DISPLAY_BIT 0xC0 +#define EDKII_IFR_DISPLAY_INT_DEC_BIT 0x00 +#define EDKII_IFR_DISPLAY_UINT_DEC_BIT 0x40 +#define EDKII_IFR_DISPLAY_UINT_HEX_BIT 0x80 -#define EDKII_IFR_NUMERIC_SIZE_BIT 0x3F +#define EDKII_IFR_NUMERIC_SIZE_BIT 0x3F #pragma pack() -extern EFI_GUID gEfiIfrTianoGuid; -extern EFI_GUID gEfiIfrFrameworkGuid; -extern EFI_GUID gEdkiiIfrBitVarstoreGuid; +extern EFI_GUID gEfiIfrTianoGuid; +extern EFI_GUID gEfiIfrFrameworkGuid; +extern EFI_GUID gEdkiiIfrBitVarstoreGuid; #endif - diff --git a/MdeModulePkg/Include/Guid/MdeModulePkgTokenSpace.h b/MdeModulePkg/Include/Guid/MdeModulePkgTokenSpace.h index e3822be3cd..210f42f0ae 100644 --- a/MdeModulePkg/Include/Guid/MdeModulePkgTokenSpace.h +++ b/MdeModulePkg/Include/Guid/MdeModulePkgTokenSpace.h @@ -14,6 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xA1AFF049, 0xFDEB, 0x442a, { 0xB3, 0x20, 0x13, 0xAB, 0x4C, 0xB7, 0x2B, 0xBC } \ } -extern EFI_GUID gEfiMdeModulePkgTokenSpaceGuid; +extern EFI_GUID gEfiMdeModulePkgTokenSpaceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/MemoryProfile.h b/MdeModulePkg/Include/Guid/MemoryProfile.h index 7565e68b5c..8194b06330 100644 --- a/MdeModulePkg/Include/Guid/MemoryProfile.h +++ b/MdeModulePkg/Include/Guid/MemoryProfile.h @@ -18,52 +18,52 @@ // typedef struct { - UINT32 Signature; - UINT16 Length; - UINT16 Revision; + UINT32 Signature; + UINT16 Length; + UINT16 Revision; } MEMORY_PROFILE_COMMON_HEADER; -#define MEMORY_PROFILE_CONTEXT_SIGNATURE SIGNATURE_32 ('M','P','C','T') -#define MEMORY_PROFILE_CONTEXT_REVISION 0x0002 +#define MEMORY_PROFILE_CONTEXT_SIGNATURE SIGNATURE_32 ('M','P','C','T') +#define MEMORY_PROFILE_CONTEXT_REVISION 0x0002 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - UINT64 CurrentTotalUsage; - UINT64 PeakTotalUsage; - UINT64 CurrentTotalUsageByType[EfiMaxMemoryType + 2]; - UINT64 PeakTotalUsageByType[EfiMaxMemoryType + 2]; - UINT64 TotalImageSize; - UINT32 ImageCount; - UINT32 SequenceCount; + MEMORY_PROFILE_COMMON_HEADER Header; + UINT64 CurrentTotalUsage; + UINT64 PeakTotalUsage; + UINT64 CurrentTotalUsageByType[EfiMaxMemoryType + 2]; + UINT64 PeakTotalUsageByType[EfiMaxMemoryType + 2]; + UINT64 TotalImageSize; + UINT32 ImageCount; + UINT32 SequenceCount; } MEMORY_PROFILE_CONTEXT; -#define MEMORY_PROFILE_DRIVER_INFO_SIGNATURE SIGNATURE_32 ('M','P','D','I') -#define MEMORY_PROFILE_DRIVER_INFO_REVISION 0x0003 +#define MEMORY_PROFILE_DRIVER_INFO_SIGNATURE SIGNATURE_32 ('M','P','D','I') +#define MEMORY_PROFILE_DRIVER_INFO_REVISION 0x0003 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - EFI_GUID FileName; - PHYSICAL_ADDRESS ImageBase; - UINT64 ImageSize; - PHYSICAL_ADDRESS EntryPoint; - UINT16 ImageSubsystem; - EFI_FV_FILETYPE FileType; - UINT8 Reserved[1]; - UINT32 AllocRecordCount; - UINT64 CurrentUsage; - UINT64 PeakUsage; - UINT64 CurrentUsageByType[EfiMaxMemoryType + 2]; - UINT64 PeakUsageByType[EfiMaxMemoryType + 2]; - UINT16 PdbStringOffset; - UINT8 Reserved2[6]; -//CHAR8 PdbString[]; + MEMORY_PROFILE_COMMON_HEADER Header; + EFI_GUID FileName; + PHYSICAL_ADDRESS ImageBase; + UINT64 ImageSize; + PHYSICAL_ADDRESS EntryPoint; + UINT16 ImageSubsystem; + EFI_FV_FILETYPE FileType; + UINT8 Reserved[1]; + UINT32 AllocRecordCount; + UINT64 CurrentUsage; + UINT64 PeakUsage; + UINT64 CurrentUsageByType[EfiMaxMemoryType + 2]; + UINT64 PeakUsageByType[EfiMaxMemoryType + 2]; + UINT16 PdbStringOffset; + UINT8 Reserved2[6]; + // CHAR8 PdbString[]; } MEMORY_PROFILE_DRIVER_INFO; typedef enum { MemoryProfileActionAllocatePages = 1, - MemoryProfileActionFreePages = 2, - MemoryProfileActionAllocatePool = 3, - MemoryProfileActionFreePool = 4, + MemoryProfileActionFreePages = 2, + MemoryProfileActionAllocatePool = 3, + MemoryProfileActionFreePool = 4, } MEMORY_PROFILE_ACTION; // @@ -82,7 +82,7 @@ typedef enum { // 3 : AllocatePool // 4 : FreePool // -#define MEMORY_PROFILE_ACTION_BASIC_MASK 0xF +#define MEMORY_PROFILE_ACTION_BASIC_MASK 0xF // // Extension @@ -101,27 +101,27 @@ typedef enum { // // Extension (used by memory allocation lib) // -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES 0x8001 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES 0x8011 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES 0x8021 -#define MEMORY_PROFILE_ACTION_LIB_FREE_PAGES 0x8002 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES 0x8041 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES 0x8051 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES 0x8061 -#define MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES 0x8042 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL 0x8003 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL 0x8013 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL 0x8023 -#define MEMORY_PROFILE_ACTION_LIB_FREE_POOL 0x8004 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL 0x8083 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL 0x8093 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL 0x80a3 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL 0x8103 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL 0x8113 -#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL 0x8123 -#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL 0x8203 -#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL 0x8213 -#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL 0x8223 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES 0x8001 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES 0x8011 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES 0x8021 +#define MEMORY_PROFILE_ACTION_LIB_FREE_PAGES 0x8002 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES 0x8041 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES 0x8051 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES 0x8061 +#define MEMORY_PROFILE_ACTION_LIB_FREE_ALIGNED_PAGES 0x8042 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL 0x8003 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL 0x8013 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL 0x8023 +#define MEMORY_PROFILE_ACTION_LIB_FREE_POOL 0x8004 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL 0x8083 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL 0x8093 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL 0x80a3 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL 0x8103 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL 0x8113 +#define MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL 0x8123 +#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL 0x8203 +#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL 0x8213 +#define MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL 0x8223 // // User defined: 0x80000000~0xFFFFFFFF @@ -131,52 +131,52 @@ typedef enum { // and the type is pages (can be freed partially) // or pool (cannot be freed partially). // -#define MEMORY_PROFILE_ACTION_USER_DEFINED_MASK 0x80000000 +#define MEMORY_PROFILE_ACTION_USER_DEFINED_MASK 0x80000000 -#define MEMORY_PROFILE_ALLOC_INFO_SIGNATURE SIGNATURE_32 ('M','P','A','I') -#define MEMORY_PROFILE_ALLOC_INFO_REVISION 0x0002 +#define MEMORY_PROFILE_ALLOC_INFO_SIGNATURE SIGNATURE_32 ('M','P','A','I') +#define MEMORY_PROFILE_ALLOC_INFO_REVISION 0x0002 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - PHYSICAL_ADDRESS CallerAddress; - UINT32 SequenceId; - UINT8 Reserved[2]; - UINT16 ActionStringOffset; - MEMORY_PROFILE_ACTION Action; - EFI_MEMORY_TYPE MemoryType; - PHYSICAL_ADDRESS Buffer; - UINT64 Size; -//CHAR8 ActionString[]; + MEMORY_PROFILE_COMMON_HEADER Header; + PHYSICAL_ADDRESS CallerAddress; + UINT32 SequenceId; + UINT8 Reserved[2]; + UINT16 ActionStringOffset; + MEMORY_PROFILE_ACTION Action; + EFI_MEMORY_TYPE MemoryType; + PHYSICAL_ADDRESS Buffer; + UINT64 Size; + // CHAR8 ActionString[]; } MEMORY_PROFILE_ALLOC_INFO; -#define MEMORY_PROFILE_DESCRIPTOR_SIGNATURE SIGNATURE_32 ('M','P','D','R') -#define MEMORY_PROFILE_DESCRIPTOR_REVISION 0x0001 +#define MEMORY_PROFILE_DESCRIPTOR_SIGNATURE SIGNATURE_32 ('M','P','D','R') +#define MEMORY_PROFILE_DESCRIPTOR_REVISION 0x0001 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - PHYSICAL_ADDRESS Address; - UINT64 Size; + MEMORY_PROFILE_COMMON_HEADER Header; + PHYSICAL_ADDRESS Address; + UINT64 Size; } MEMORY_PROFILE_DESCRIPTOR; -#define MEMORY_PROFILE_FREE_MEMORY_SIGNATURE SIGNATURE_32 ('M','P','R','M') -#define MEMORY_PROFILE_FREE_MEMORY_REVISION 0x0001 +#define MEMORY_PROFILE_FREE_MEMORY_SIGNATURE SIGNATURE_32 ('M','P','R','M') +#define MEMORY_PROFILE_FREE_MEMORY_REVISION 0x0001 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - UINT64 TotalFreeMemoryPages; - UINT32 FreeMemoryEntryCount; - UINT8 Reserved[4]; - //MEMORY_PROFILE_DESCRIPTOR MemoryDescriptor[FreeMemoryEntryCount]; + MEMORY_PROFILE_COMMON_HEADER Header; + UINT64 TotalFreeMemoryPages; + UINT32 FreeMemoryEntryCount; + UINT8 Reserved[4]; + // MEMORY_PROFILE_DESCRIPTOR MemoryDescriptor[FreeMemoryEntryCount]; } MEMORY_PROFILE_FREE_MEMORY; -#define MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE SIGNATURE_32 ('M','P','M','R') -#define MEMORY_PROFILE_MEMORY_RANGE_REVISION 0x0001 +#define MEMORY_PROFILE_MEMORY_RANGE_SIGNATURE SIGNATURE_32 ('M','P','M','R') +#define MEMORY_PROFILE_MEMORY_RANGE_REVISION 0x0001 typedef struct { - MEMORY_PROFILE_COMMON_HEADER Header; - UINT32 MemoryRangeCount; - UINT8 Reserved[4]; - //MEMORY_PROFILE_DESCRIPTOR MemoryDescriptor[MemoryRangeCount]; + MEMORY_PROFILE_COMMON_HEADER Header; + UINT32 MemoryRangeCount; + UINT8 Reserved[4]; + // MEMORY_PROFILE_DESCRIPTOR MemoryDescriptor[MemoryRangeCount]; } MEMORY_PROFILE_MEMORY_RANGE; // @@ -219,7 +219,7 @@ EFI_STATUS (EFIAPI *EDKII_MEMORY_PROFILE_GET_DATA)( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, IN OUT UINT64 *ProfileSize, - OUT VOID *ProfileBuffer + OUT VOID *ProfileBuffer ); /** @@ -270,8 +270,8 @@ EFI_STATUS IN UINT64 ImageSize ); -#define MEMORY_PROFILE_RECORDING_ENABLE TRUE -#define MEMORY_PROFILE_RECORDING_DISABLE FALSE +#define MEMORY_PROFILE_RECORDING_ENABLE TRUE +#define MEMORY_PROFILE_RECORDING_DISABLE FALSE /** Get memory profile recording state. @@ -286,7 +286,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_MEMORY_PROFILE_GET_RECORDING_STATE) ( +(EFIAPI *EDKII_MEMORY_PROFILE_GET_RECORDING_STATE)( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, OUT BOOLEAN *RecordingState ); @@ -303,7 +303,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_MEMORY_PROFILE_SET_RECORDING_STATE) ( +(EFIAPI *EDKII_MEMORY_PROFILE_SET_RECORDING_STATE)( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, IN BOOLEAN RecordingState ); @@ -333,7 +333,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_MEMORY_PROFILE_RECORD) ( +(EFIAPI *EDKII_MEMORY_PROFILE_RECORD)( IN EDKII_MEMORY_PROFILE_PROTOCOL *This, IN PHYSICAL_ADDRESS CallerAddress, IN MEMORY_PROFILE_ACTION Action, @@ -344,12 +344,12 @@ EFI_STATUS ); struct _EDKII_MEMORY_PROFILE_PROTOCOL { - EDKII_MEMORY_PROFILE_GET_DATA GetData; - EDKII_MEMORY_PROFILE_REGISTER_IMAGE RegisterImage; - EDKII_MEMORY_PROFILE_UNREGISTER_IMAGE UnregisterImage; - EDKII_MEMORY_PROFILE_GET_RECORDING_STATE GetRecordingState; - EDKII_MEMORY_PROFILE_SET_RECORDING_STATE SetRecordingState; - EDKII_MEMORY_PROFILE_RECORD Record; + EDKII_MEMORY_PROFILE_GET_DATA GetData; + EDKII_MEMORY_PROFILE_REGISTER_IMAGE RegisterImage; + EDKII_MEMORY_PROFILE_UNREGISTER_IMAGE UnregisterImage; + EDKII_MEMORY_PROFILE_GET_RECORDING_STATE GetRecordingState; + EDKII_MEMORY_PROFILE_SET_RECORDING_STATE SetRecordingState; + EDKII_MEMORY_PROFILE_RECORD Record; }; // @@ -386,22 +386,22 @@ struct _EDKII_MEMORY_PROFILE_PROTOCOL { // // SMRAM profile command // -#define SMRAM_PROFILE_COMMAND_GET_PROFILE_INFO 0x1 -#define SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA 0x2 +#define SMRAM_PROFILE_COMMAND_GET_PROFILE_INFO 0x1 +#define SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA 0x2 // // Below 2 commands have been deprecated. They may not be re-used. // -#define SMRAM_PROFILE_COMMAND_DEPRECATED1 0x3 -#define SMRAM_PROFILE_COMMAND_DEPRECATED2 0x4 +#define SMRAM_PROFILE_COMMAND_DEPRECATED1 0x3 +#define SMRAM_PROFILE_COMMAND_DEPRECATED2 0x4 -#define SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA_BY_OFFSET 0x5 -#define SMRAM_PROFILE_COMMAND_GET_RECORDING_STATE 0x6 -#define SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE 0x7 +#define SMRAM_PROFILE_COMMAND_GET_PROFILE_DATA_BY_OFFSET 0x5 +#define SMRAM_PROFILE_COMMAND_GET_RECORDING_STATE 0x6 +#define SMRAM_PROFILE_COMMAND_SET_RECORDING_STATE 0x7 typedef struct { - UINT32 Command; - UINT32 DataLength; - UINT64 ReturnStatus; + UINT32 Command; + UINT32 DataLength; + UINT64 ReturnStatus; } SMRAM_PROFILE_PARAMETER_HEADER; typedef struct { @@ -449,20 +449,18 @@ typedef struct { UINT64 NumberOfPage; } SMRAM_PROFILE_PARAMETER_UNREGISTER_IMAGE; - -#define EDKII_MEMORY_PROFILE_GUID { \ +#define EDKII_MEMORY_PROFILE_GUID {\ 0x821c9a09, 0x541a, 0x40f6, { 0x9f, 0x43, 0xa, 0xd1, 0x93, 0xa1, 0x2c, 0xfe } \ } -extern EFI_GUID gEdkiiMemoryProfileGuid; +extern EFI_GUID gEdkiiMemoryProfileGuid; typedef EDKII_MEMORY_PROFILE_PROTOCOL EDKII_SMM_MEMORY_PROFILE_PROTOCOL; -#define EDKII_SMM_MEMORY_PROFILE_GUID { \ +#define EDKII_SMM_MEMORY_PROFILE_GUID {\ 0xe22bbcca, 0x516a, 0x46a8, { 0x80, 0xe2, 0x67, 0x45, 0xe8, 0x36, 0x93, 0xbd } \ } -extern EFI_GUID gEdkiiSmmMemoryProfileGuid; +extern EFI_GUID gEdkiiSmmMemoryProfileGuid; #endif - diff --git a/MdeModulePkg/Include/Guid/MemoryStatusCodeRecord.h b/MdeModulePkg/Include/Guid/MemoryStatusCodeRecord.h index 8dafc6945b..a924c592c9 100644 --- a/MdeModulePkg/Include/Guid/MemoryStatusCodeRecord.h +++ b/MdeModulePkg/Include/Guid/MemoryStatusCodeRecord.h @@ -39,15 +39,15 @@ typedef struct { /// /// Index of the packet. /// - UINT16 PacketIndex; + UINT16 PacketIndex; /// /// The number of active records in the packet. /// - UINT16 RecordIndex; + UINT16 RecordIndex; /// /// The maximum number of records that the packet can store. /// - UINT32 MaxRecordsNumber; + UINT32 MaxRecordsNumber; } MEMORY_STATUSCODE_PACKET_HEADER; /// @@ -58,15 +58,15 @@ typedef struct { /// /// The index pointing to the last recored being stored. /// - UINT32 RecordIndex; + UINT32 RecordIndex; /// /// The number of records being stored. /// - UINT32 NumberOfRecords; + UINT32 NumberOfRecords; /// /// The maximum number of records that can be stored. /// - UINT32 MaxRecordsNumber; + UINT32 MaxRecordsNumber; } RUNTIME_MEMORY_STATUSCODE_HEADER; /// @@ -77,21 +77,21 @@ typedef struct { /// /// Status Code type to be reported. /// - EFI_STATUS_CODE_TYPE CodeType; + EFI_STATUS_CODE_TYPE CodeType; /// /// An operation, plus value information about the class and subclass, used to /// classify the hardware and software entity. /// - EFI_STATUS_CODE_VALUE Value; + EFI_STATUS_CODE_VALUE Value; /// /// The enumeration of a hardware or software entity within /// the system. Valid instance numbers start with the number 1. /// - UINT32 Instance; + UINT32 Instance; } MEMORY_STATUSCODE_RECORD; -extern EFI_GUID gMemoryStatusCodeRecordGuid; +extern EFI_GUID gMemoryStatusCodeRecordGuid; #endif diff --git a/MdeModulePkg/Include/Guid/MemoryTypeInformation.h b/MdeModulePkg/Include/Guid/MemoryTypeInformation.h index eba509f0fc..e97d88765e 100644 --- a/MdeModulePkg/Include/Guid/MemoryTypeInformation.h +++ b/MdeModulePkg/Include/Guid/MemoryTypeInformation.h @@ -18,13 +18,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_MEMORY_TYPE_INFORMATION_GUID \ { 0x4c19049f,0x4137,0x4dd3, { 0x9c,0x10,0x8b,0x97,0xa8,0x3f,0xfd,0xfa } } -#define EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME L"MemoryTypeInformation" +#define EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME L"MemoryTypeInformation" -extern EFI_GUID gEfiMemoryTypeInformationGuid; +extern EFI_GUID gEfiMemoryTypeInformationGuid; typedef struct { - UINT32 Type; ///< EFI memory type defined in UEFI specification. - UINT32 NumberOfPages; ///< The pages of this type memory. + UINT32 Type; ///< EFI memory type defined in UEFI specification. + UINT32 NumberOfPages; ///< The pages of this type memory. } EFI_MEMORY_TYPE_INFORMATION; #endif diff --git a/MdeModulePkg/Include/Guid/MigratedFvInfo.h b/MdeModulePkg/Include/Guid/MigratedFvInfo.h index 061c17ed0e..aca2332a0e 100644 --- a/MdeModulePkg/Include/Guid/MigratedFvInfo.h +++ b/MdeModulePkg/Include/Guid/MigratedFvInfo.h @@ -10,13 +10,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define __EDKII_MIGRATED_FV_INFO_GUID_H__ typedef struct { - UINT32 FvOrgBase; // original FV address - UINT32 FvNewBase; // new FV address - UINT32 FvDataBase; // original FV data - UINT32 FvLength; // Fv Length + UINT32 FvOrgBase; // original FV address + UINT32 FvNewBase; // new FV address + UINT32 FvDataBase; // original FV data + UINT32 FvLength; // Fv Length } EDKII_MIGRATED_FV_INFO; -extern EFI_GUID gEdkiiMigratedFvInfoGuid; +extern EFI_GUID gEdkiiMigratedFvInfoGuid; #endif // #ifndef __EDKII_MIGRATED_FV_INFO_GUID_H__ - diff --git a/MdeModulePkg/Include/Guid/MtcVendor.h b/MdeModulePkg/Include/Guid/MtcVendor.h index 3104c21d1e..74163972aa 100644 --- a/MdeModulePkg/Include/Guid/MtcVendor.h +++ b/MdeModulePkg/Include/Guid/MtcVendor.h @@ -18,8 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Name of the variable for the high part of monotonic counter // -#define MTC_VARIABLE_NAME L"MTC" +#define MTC_VARIABLE_NAME L"MTC" -extern EFI_GUID gMtcVendorGuid; +extern EFI_GUID gMtcVendorGuid; #endif diff --git a/MdeModulePkg/Include/Guid/NonDiscoverableDevice.h b/MdeModulePkg/Include/Guid/NonDiscoverableDevice.h index e277c0b878..26fa5d28a1 100644 --- a/MdeModulePkg/Include/Guid/NonDiscoverableDevice.h +++ b/MdeModulePkg/Include/Guid/NonDiscoverableDevice.h @@ -38,15 +38,14 @@ #define EDKII_NON_DISCOVERABLE_XHCI_DEVICE_GUID \ { 0xB1BE0BC5, 0x6C28, 0x442D, {0xAA, 0x37, 0x15, 0x1B, 0x42, 0x57, 0xBD, 0x78 } } - -extern EFI_GUID gEdkiiNonDiscoverableAhciDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableAmbaDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableEhciDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableNvmeDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableOhciDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableSdhciDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableUfsDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableUhciDeviceGuid; -extern EFI_GUID gEdkiiNonDiscoverableXhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableAhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableAmbaDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableEhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableNvmeDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableOhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableSdhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableUfsDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableUhciDeviceGuid; +extern EFI_GUID gEdkiiNonDiscoverableXhciDeviceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PcdDataBaseHobGuid.h b/MdeModulePkg/Include/Guid/PcdDataBaseHobGuid.h index 3db8b64941..0cfe8bc68d 100644 --- a/MdeModulePkg/Include/Guid/PcdDataBaseHobGuid.h +++ b/MdeModulePkg/Include/Guid/PcdDataBaseHobGuid.h @@ -14,6 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xEA296D92, 0x0B69, 0x423C, { 0x8C, 0x28, 0x33, 0xB4, 0xE0, 0xA9, 0x12, 0x68 } \ } -extern EFI_GUID gPcdDataBaseHobGuid; +extern EFI_GUID gPcdDataBaseHobGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PcdDataBaseSignatureGuid.h b/MdeModulePkg/Include/Guid/PcdDataBaseSignatureGuid.h index 7802d5497e..bac8fd59bf 100644 --- a/MdeModulePkg/Include/Guid/PcdDataBaseSignatureGuid.h +++ b/MdeModulePkg/Include/Guid/PcdDataBaseSignatureGuid.h @@ -12,21 +12,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define PCD_DATA_BASE_SIGNATURE_GUID \ { 0x3c7d193c, 0x682c, 0x4c14, { 0xa6, 0x8f, 0x55, 0x2d, 0xea, 0x4f, 0x43, 0x7e } } -extern EFI_GUID gPcdDataBaseSignatureGuid; +extern EFI_GUID gPcdDataBaseSignatureGuid; // // Common definitions // typedef UINT64 SKU_ID; -#define PCD_TYPE_SHIFT 28 +#define PCD_TYPE_SHIFT 28 -#define PCD_TYPE_DATA (0x0U << PCD_TYPE_SHIFT) -#define PCD_TYPE_HII (0x8U << PCD_TYPE_SHIFT) -#define PCD_TYPE_VPD (0x4U << PCD_TYPE_SHIFT) -#define PCD_TYPE_STRING (0x1U << PCD_TYPE_SHIFT) +#define PCD_TYPE_DATA (0x0U << PCD_TYPE_SHIFT) +#define PCD_TYPE_HII (0x8U << PCD_TYPE_SHIFT) +#define PCD_TYPE_VPD (0x4U << PCD_TYPE_SHIFT) +#define PCD_TYPE_STRING (0x1U << PCD_TYPE_SHIFT) -#define PCD_TYPE_ALL_SET (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_STRING) +#define PCD_TYPE_ALL_SET (PCD_TYPE_DATA | PCD_TYPE_HII | PCD_TYPE_VPD | PCD_TYPE_STRING) #define PCD_DATUM_TYPE_SHIFT 24 @@ -42,30 +42,30 @@ typedef UINT64 SKU_ID; PCD_DATUM_TYPE_UINT32 | \ PCD_DATUM_TYPE_UINT64) -#define PCD_DATUM_TYPE_SHIFT2 20 +#define PCD_DATUM_TYPE_SHIFT2 20 -#define PCD_DATUM_TYPE_UINT8_BOOLEAN (0x1U << PCD_DATUM_TYPE_SHIFT2) +#define PCD_DATUM_TYPE_UINT8_BOOLEAN (0x1U << PCD_DATUM_TYPE_SHIFT2) -#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET | PCD_DATUM_TYPE_UINT8_BOOLEAN)) +#define PCD_DATABASE_OFFSET_MASK (~(PCD_TYPE_ALL_SET | PCD_DATUM_TYPE_ALL_SET | PCD_DATUM_TYPE_UINT8_BOOLEAN)) typedef struct { - UINT32 ExTokenNumber; - UINT16 TokenNumber; // Token Number for Dynamic-Ex PCD. - UINT16 ExGuidIndex; // Index of GuidTable in units of GUID. + UINT32 ExTokenNumber; + UINT16 TokenNumber; // Token Number for Dynamic-Ex PCD. + UINT16 ExGuidIndex; // Index of GuidTable in units of GUID. } DYNAMICEX_MAPPING; typedef struct { - UINT32 StringIndex; // Offset in String Table in units of UINT8. - UINT32 DefaultValueOffset; // Offset of the Default Value. - UINT16 GuidTableIndex; // Offset in Guid Table in units of GUID. - UINT16 Offset; // Offset in Variable. - UINT32 Attributes; // Variable attributes. - UINT16 Property; // Variable property. - UINT16 Reserved; + UINT32 StringIndex; // Offset in String Table in units of UINT8. + UINT32 DefaultValueOffset; // Offset of the Default Value. + UINT16 GuidTableIndex; // Offset in Guid Table in units of GUID. + UINT16 Offset; // Offset in Variable. + UINT32 Attributes; // Variable attributes. + UINT16 Property; // Variable property. + UINT16 Reserved; } VARIABLE_HEAD; typedef struct { - UINT32 Offset; + UINT32 Offset; } VPD_HEAD; typedef UINT32 STRING_HEAD; @@ -73,96 +73,94 @@ typedef UINT32 STRING_HEAD; typedef UINT16 SIZE_INFO; typedef struct { - UINT32 TokenSpaceCNameIndex; // Offset in String Table in units of UINT8. - UINT32 PcdCNameIndex; // Offset in String Table in units of UINT8. + UINT32 TokenSpaceCNameIndex; // Offset in String Table in units of UINT8. + UINT32 PcdCNameIndex; // Offset in String Table in units of UINT8. } PCD_NAME_INDEX; typedef UINT32 TABLE_OFFSET; typedef struct { - GUID Signature; // PcdDataBaseGuid. - UINT32 BuildVersion; - UINT32 Length; // Length of DEFAULT SKU PCD DB - SKU_ID SystemSkuId; // Current SkuId value. - UINT32 LengthForAllSkus; // Length of all SKU PCD DB - UINT32 UninitDataBaseSize; // Total size for PCD those default value with 0. - TABLE_OFFSET LocalTokenNumberTableOffset; - TABLE_OFFSET ExMapTableOffset; - TABLE_OFFSET GuidTableOffset; - TABLE_OFFSET StringTableOffset; - TABLE_OFFSET SizeTableOffset; - TABLE_OFFSET SkuIdTableOffset; - TABLE_OFFSET PcdNameTableOffset; - UINT16 LocalTokenCount; // LOCAL_TOKEN_NUMBER for all. - UINT16 ExTokenCount; // EX_TOKEN_NUMBER for DynamicEx. - UINT16 GuidTableCount; // The Number of Guid in GuidTable. - UINT8 Pad[6]; // Pad bytes to satisfy the alignment. - - // - // Default initialized external PCD database binary structure - // - // Padding is needed to keep necessary alignment - // - //SKU_ID SkuIdTable[]; // SkuIds system supports. - //UINT64 ValueUint64[]; - //UINT32 ValueUint32[]; - //VPD_HEAD VpdHead[]; // VPD Offset - //DYNAMICEX_MAPPING ExMapTable[]; // DynamicEx PCD mapped to LocalIndex in LocalTokenNumberTable. It can be accessed by the ExMapTableOffset. - //UINT32 LocalTokenNumberTable[]; // Offset | DataType | PCD Type. It can be accessed by LocalTokenNumberTableOffset. - //GUID GuidTable[]; // GUID for DynamicEx and HII PCD variable Guid. It can be accessed by the GuidTableOffset. - //STRING_HEAD StringHead[]; // String PCD - //PCD_NAME_INDEX PcdNameTable[]; // PCD name index info. It can be accessed by the PcdNameTableOffset. - //VARIABLE_HEAD VariableHead[]; // HII PCD - //UINT8 StringTable[]; // String for String PCD value and HII PCD Variable Name. It can be accessed by StringTableOffset. - //SIZE_INFO SizeTable[]; // MaxSize and CurSize for String PCD. It can be accessed by SizeTableOffset. - //UINT16 ValueUint16[]; - //UINT8 ValueUint8[]; - //BOOLEAN ValueBoolean[]; - + GUID Signature; // PcdDataBaseGuid. + UINT32 BuildVersion; + UINT32 Length; // Length of DEFAULT SKU PCD DB + SKU_ID SystemSkuId; // Current SkuId value. + UINT32 LengthForAllSkus; // Length of all SKU PCD DB + UINT32 UninitDataBaseSize; // Total size for PCD those default value with 0. + TABLE_OFFSET LocalTokenNumberTableOffset; + TABLE_OFFSET ExMapTableOffset; + TABLE_OFFSET GuidTableOffset; + TABLE_OFFSET StringTableOffset; + TABLE_OFFSET SizeTableOffset; + TABLE_OFFSET SkuIdTableOffset; + TABLE_OFFSET PcdNameTableOffset; + UINT16 LocalTokenCount; // LOCAL_TOKEN_NUMBER for all. + UINT16 ExTokenCount; // EX_TOKEN_NUMBER for DynamicEx. + UINT16 GuidTableCount; // The Number of Guid in GuidTable. + UINT8 Pad[6]; // Pad bytes to satisfy the alignment. + + // + // Default initialized external PCD database binary structure + // + // Padding is needed to keep necessary alignment + // + // SKU_ID SkuIdTable[]; // SkuIds system supports. + // UINT64 ValueUint64[]; + // UINT32 ValueUint32[]; + // VPD_HEAD VpdHead[]; // VPD Offset + // DYNAMICEX_MAPPING ExMapTable[]; // DynamicEx PCD mapped to LocalIndex in LocalTokenNumberTable. It can be accessed by the ExMapTableOffset. + // UINT32 LocalTokenNumberTable[]; // Offset | DataType | PCD Type. It can be accessed by LocalTokenNumberTableOffset. + // GUID GuidTable[]; // GUID for DynamicEx and HII PCD variable Guid. It can be accessed by the GuidTableOffset. + // STRING_HEAD StringHead[]; // String PCD + // PCD_NAME_INDEX PcdNameTable[]; // PCD name index info. It can be accessed by the PcdNameTableOffset. + // VARIABLE_HEAD VariableHead[]; // HII PCD + // UINT8 StringTable[]; // String for String PCD value and HII PCD Variable Name. It can be accessed by StringTableOffset. + // SIZE_INFO SizeTable[]; // MaxSize and CurSize for String PCD. It can be accessed by SizeTableOffset. + // UINT16 ValueUint16[]; + // UINT8 ValueUint8[]; + // BOOLEAN ValueBoolean[]; } PCD_DATABASE_INIT; // // PEI and DXE Pcd driver use the same PCD database // -typedef PCD_DATABASE_INIT PEI_PCD_DATABASE; -typedef PCD_DATABASE_INIT DXE_PCD_DATABASE; - +typedef PCD_DATABASE_INIT PEI_PCD_DATABASE; +typedef PCD_DATABASE_INIT DXE_PCD_DATABASE; typedef struct { - PEI_PCD_DATABASE *PeiDb; - DXE_PCD_DATABASE *DxeDb; + PEI_PCD_DATABASE *PeiDb; + DXE_PCD_DATABASE *DxeDb; } PCD_DATABASE; typedef struct { - UINT32 Offset:24; - UINT32 Value:8; + UINT32 Offset : 24; + UINT32 Value : 8; } PCD_DATA_DELTA; typedef struct { - SKU_ID SkuId; - UINT16 DefaultId; - UINT8 Reserved[6]; + SKU_ID SkuId; + UINT16 DefaultId; + UINT8 Reserved[6]; } PCD_DEFAULT_INFO; typedef struct { // // Full size, it must be at 8 byte alignment. // - UINT32 DataSize; + UINT32 DataSize; // // HeaderSize includes HeaderSize fields and DefaultInfo arrays // - UINT32 HeaderSize; + UINT32 HeaderSize; // // DefaultInfo arrays those have the same default setting. // - PCD_DEFAULT_INFO DefaultInfo[1]; + PCD_DEFAULT_INFO DefaultInfo[1]; // // Default data is stored as variable storage or the array of DATA_DELTA. // } PCD_DEFAULT_DATA; -#define PCD_NV_STORE_DEFAULT_BUFFER_SIGNATURE SIGNATURE_32('N', 'S', 'D', 'B') +#define PCD_NV_STORE_DEFAULT_BUFFER_SIGNATURE SIGNATURE_32('N', 'S', 'D', 'B') typedef struct { // diff --git a/MdeModulePkg/Include/Guid/Performance.h b/MdeModulePkg/Include/Guid/Performance.h index a4244b8a19..58e8f5ec5b 100644 --- a/MdeModulePkg/Include/Guid/Performance.h +++ b/MdeModulePkg/Include/Guid/Performance.h @@ -12,39 +12,38 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __PERFORMANCE_DATA_H__ #define __PERFORMANCE_DATA_H__ -#define PERFORMANCE_PROPERTY_REVISION 0x1 +#define PERFORMANCE_PROPERTY_REVISION 0x1 typedef struct { - UINT32 Revision; - UINT32 Reserved; - UINT64 Frequency; - UINT64 TimerStartValue; - UINT64 TimerEndValue; + UINT32 Revision; + UINT32 Reserved; + UINT64 Frequency; + UINT64 TimerStartValue; + UINT64 TimerEndValue; } PERFORMANCE_PROPERTY; // // PEI_PERFORMANCE_STRING_SIZE must be a multiple of 8. // -#define PEI_PERFORMANCE_STRING_SIZE 8 -#define PEI_PERFORMANCE_STRING_LENGTH (PEI_PERFORMANCE_STRING_SIZE - 1) +#define PEI_PERFORMANCE_STRING_SIZE 8 +#define PEI_PERFORMANCE_STRING_LENGTH (PEI_PERFORMANCE_STRING_SIZE - 1) typedef struct { - EFI_PHYSICAL_ADDRESS Handle; - CHAR8 Token[PEI_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. - CHAR8 Module[PEI_PERFORMANCE_STRING_SIZE]; ///< Module string name. - UINT64 StartTimeStamp; ///< Start time point. - UINT64 EndTimeStamp; ///< End time point. + EFI_PHYSICAL_ADDRESS Handle; + CHAR8 Token[PEI_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. + CHAR8 Module[PEI_PERFORMANCE_STRING_SIZE]; ///< Module string name. + UINT64 StartTimeStamp; ///< Start time point. + UINT64 EndTimeStamp; ///< End time point. } PEI_PERFORMANCE_LOG_ENTRY; // // The header must be aligned at 8 bytes. // typedef struct { - UINT32 NumberOfEntries; ///< The number of all performance log entries. - UINT32 Reserved; + UINT32 NumberOfEntries; ///< The number of all performance log entries. + UINT32 Reserved; } PEI_PERFORMANCE_LOG_HEADER; - #define PERFORMANCE_PROTOCOL_GUID \ { 0x76b6bdfa, 0x2acd, 0x4462, { 0x9E, 0x3F, 0xcb, 0x58, 0xC9, 0x69, 0xd9, 0x37 } } @@ -54,43 +53,43 @@ typedef struct { // // Forward reference for pure ANSI compatibility // -typedef struct _PERFORMANCE_PROTOCOL PERFORMANCE_PROTOCOL; -typedef struct _PERFORMANCE_EX_PROTOCOL PERFORMANCE_EX_PROTOCOL; +typedef struct _PERFORMANCE_PROTOCOL PERFORMANCE_PROTOCOL; +typedef struct _PERFORMANCE_EX_PROTOCOL PERFORMANCE_EX_PROTOCOL; // // DXE_PERFORMANCE_STRING_SIZE must be a multiple of 8. // -#define DXE_PERFORMANCE_STRING_SIZE 32 -#define DXE_PERFORMANCE_STRING_LENGTH (DXE_PERFORMANCE_STRING_SIZE - 1) +#define DXE_PERFORMANCE_STRING_SIZE 32 +#define DXE_PERFORMANCE_STRING_LENGTH (DXE_PERFORMANCE_STRING_SIZE - 1) // // The default guage entries number for DXE phase. // -#define INIT_DXE_GAUGE_DATA_ENTRIES 800 +#define INIT_DXE_GAUGE_DATA_ENTRIES 800 typedef struct { - EFI_PHYSICAL_ADDRESS Handle; - CHAR8 Token[DXE_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. - CHAR8 Module[DXE_PERFORMANCE_STRING_SIZE]; ///< Module string name. - UINT64 StartTimeStamp; ///< Start time point. - UINT64 EndTimeStamp; ///< End time point. + EFI_PHYSICAL_ADDRESS Handle; + CHAR8 Token[DXE_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. + CHAR8 Module[DXE_PERFORMANCE_STRING_SIZE]; ///< Module string name. + UINT64 StartTimeStamp; ///< Start time point. + UINT64 EndTimeStamp; ///< End time point. } GAUGE_DATA_ENTRY; typedef struct { - EFI_PHYSICAL_ADDRESS Handle; - CHAR8 Token[DXE_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. - CHAR8 Module[DXE_PERFORMANCE_STRING_SIZE]; ///< Module string name. - UINT64 StartTimeStamp; ///< Start time point. - UINT64 EndTimeStamp; ///< End time point. - UINT32 Identifier; ///< Identifier. + EFI_PHYSICAL_ADDRESS Handle; + CHAR8 Token[DXE_PERFORMANCE_STRING_SIZE]; ///< Measured token string name. + CHAR8 Module[DXE_PERFORMANCE_STRING_SIZE]; ///< Module string name. + UINT64 StartTimeStamp; ///< Start time point. + UINT64 EndTimeStamp; ///< End time point. + UINT32 Identifier; ///< Identifier. } GAUGE_DATA_ENTRY_EX; // // The header must be aligned at 8 bytes // typedef struct { - UINT32 NumberOfEntries; ///< The number of all performance gauge entries. - UINT32 Reserved; + UINT32 NumberOfEntries; ///< The number of all performance gauge entries. + UINT32 Reserved; } GAUGE_DATA_HEADER; // @@ -106,32 +105,32 @@ typedef struct { // // SMM_PERFORMANCE_STRING_SIZE. // -#define SMM_PERFORMANCE_STRING_SIZE 32 -#define SMM_PERFORMANCE_STRING_LENGTH (SMM_PERFORMANCE_STRING_SIZE - 1) +#define SMM_PERFORMANCE_STRING_SIZE 32 +#define SMM_PERFORMANCE_STRING_LENGTH (SMM_PERFORMANCE_STRING_SIZE - 1) // // The default guage entries number for SMM phase. // -#define INIT_SMM_GAUGE_DATA_ENTRIES 200 +#define INIT_SMM_GAUGE_DATA_ENTRIES 200 typedef struct { - UINTN Function; - EFI_STATUS ReturnStatus; - UINTN NumberOfEntries; - UINTN LogEntryKey; - GAUGE_DATA_ENTRY *GaugeData; + UINTN Function; + EFI_STATUS ReturnStatus; + UINTN NumberOfEntries; + UINTN LogEntryKey; + GAUGE_DATA_ENTRY *GaugeData; } SMM_PERF_COMMUNICATE; typedef struct { - UINTN Function; - EFI_STATUS ReturnStatus; - UINTN NumberOfEntries; - UINTN LogEntryKey; - GAUGE_DATA_ENTRY_EX *GaugeDataEx; + UINTN Function; + EFI_STATUS ReturnStatus; + UINTN NumberOfEntries; + UINTN LogEntryKey; + GAUGE_DATA_ENTRY_EX *GaugeDataEx; } SMM_PERF_COMMUNICATE_EX; -#define SMM_PERF_FUNCTION_GET_GAUGE_ENTRY_NUMBER 1 -#define SMM_PERF_FUNCTION_GET_GAUGE_DATA 2 +#define SMM_PERF_FUNCTION_GET_GAUGE_ENTRY_NUMBER 1 +#define SMM_PERF_FUNCTION_GET_GAUGE_DATA 2 /** Adds a record at the end of the performance measurement log @@ -157,7 +156,7 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_START_GAUGE)( +(EFIAPI *PERFORMANCE_START_GAUGE)( IN CONST VOID *Handle OPTIONAL, IN CONST CHAR8 *Token OPTIONAL, IN CONST CHAR8 *Module OPTIONAL, @@ -190,7 +189,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_END_GAUGE)( +(EFIAPI *PERFORMANCE_END_GAUGE)( IN CONST VOID *Handle OPTIONAL, IN CONST CHAR8 *Token OPTIONAL, IN CONST CHAR8 *Module OPTIONAL, @@ -217,7 +216,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_GET_GAUGE)( +(EFIAPI *PERFORMANCE_GET_GAUGE)( IN UINTN LogEntryKey, OUT GAUGE_DATA_ENTRY **GaugeDataEntry ); @@ -248,7 +247,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_START_GAUGE_EX)( +(EFIAPI *PERFORMANCE_START_GAUGE_EX)( IN CONST VOID *Handle OPTIONAL, IN CONST CHAR8 *Token OPTIONAL, IN CONST CHAR8 *Module OPTIONAL, @@ -284,7 +283,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_END_GAUGE_EX)( +(EFIAPI *PERFORMANCE_END_GAUGE_EX)( IN CONST VOID *Handle OPTIONAL, IN CONST CHAR8 *Token OPTIONAL, IN CONST CHAR8 *Module OPTIONAL, @@ -312,26 +311,26 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * PERFORMANCE_GET_GAUGE_EX)( +(EFIAPI *PERFORMANCE_GET_GAUGE_EX)( IN UINTN LogEntryKey, OUT GAUGE_DATA_ENTRY_EX **GaugeDataEntryEx ); struct _PERFORMANCE_PROTOCOL { - PERFORMANCE_START_GAUGE StartGauge; - PERFORMANCE_END_GAUGE EndGauge; - PERFORMANCE_GET_GAUGE GetGauge; + PERFORMANCE_START_GAUGE StartGauge; + PERFORMANCE_END_GAUGE EndGauge; + PERFORMANCE_GET_GAUGE GetGauge; }; struct _PERFORMANCE_EX_PROTOCOL { - PERFORMANCE_START_GAUGE_EX StartGaugeEx; - PERFORMANCE_END_GAUGE_EX EndGaugeEx; - PERFORMANCE_GET_GAUGE_EX GetGaugeEx; + PERFORMANCE_START_GAUGE_EX StartGaugeEx; + PERFORMANCE_END_GAUGE_EX EndGaugeEx; + PERFORMANCE_GET_GAUGE_EX GetGaugeEx; }; -extern EFI_GUID gPerformanceProtocolGuid; -extern EFI_GUID gSmmPerformanceProtocolGuid; -extern EFI_GUID gPerformanceExProtocolGuid; -extern EFI_GUID gSmmPerformanceExProtocolGuid; +extern EFI_GUID gPerformanceProtocolGuid; +extern EFI_GUID gSmmPerformanceProtocolGuid; +extern EFI_GUID gPerformanceExProtocolGuid; +extern EFI_GUID gSmmPerformanceExProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PerformanceMeasurement.h b/MdeModulePkg/Include/Guid/PerformanceMeasurement.h index 9c5ef7f0df..ddee8bfe5b 100644 --- a/MdeModulePkg/Include/Guid/PerformanceMeasurement.h +++ b/MdeModulePkg/Include/Guid/PerformanceMeasurement.h @@ -63,10 +63,10 @@ EFI_STATUS ); struct _EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL { - CREATE_PERFORMANCE_MEASUREMENT CreatePerformanceMeasurement; + CREATE_PERFORMANCE_MEASUREMENT CreatePerformanceMeasurement; }; -extern EFI_GUID gEdkiiPerformanceMeasurementProtocolGuid; -extern EFI_GUID gEdkiiSmmPerformanceMeasurementProtocolGuid; +extern EFI_GUID gEdkiiPerformanceMeasurementProtocolGuid; +extern EFI_GUID gEdkiiSmmPerformanceMeasurementProtocolGuid; #endif // _PERFORMANCE_MEASUREMENT_H_ diff --git a/MdeModulePkg/Include/Guid/PiSmmCommunicationRegionTable.h b/MdeModulePkg/Include/Guid/PiSmmCommunicationRegionTable.h index 595003bfbc..93fa39771f 100644 --- a/MdeModulePkg/Include/Guid/PiSmmCommunicationRegionTable.h +++ b/MdeModulePkg/Include/Guid/PiSmmCommunicationRegionTable.h @@ -8,7 +8,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PI_SMM_COMMUNICATION_REGION_TABLE_H_ #define _PI_SMM_COMMUNICATION_REGION_TABLE_H_ -#define EDKII_PI_SMM_COMMUNICATION_REGION_TABLE_GUID {\ +#define EDKII_PI_SMM_COMMUNICATION_REGION_TABLE_GUID {\ 0x4e28ca50, 0xd582, 0x44ac, {0xa1, 0x1f, 0xe3, 0xd5, 0x65, 0x26, 0xdb, 0x34} \ } @@ -43,15 +43,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // to get SMM profile data in SMM. // typedef struct { - UINT32 Version; - UINT32 NumberOfEntries; - UINT32 DescriptorSize; - UINT32 Reserved; -//EFI_MEMORY_DESCRIPTOR Entry[1]; + UINT32 Version; + UINT32 NumberOfEntries; + UINT32 DescriptorSize; + UINT32 Reserved; + // EFI_MEMORY_DESCRIPTOR Entry[1]; } EDKII_PI_SMM_COMMUNICATION_REGION_TABLE; #define EDKII_PI_SMM_COMMUNICATION_REGION_TABLE_VERSION 0x00000001 -extern EFI_GUID gEdkiiPiSmmCommunicationRegionTableGuid; +extern EFI_GUID gEdkiiPiSmmCommunicationRegionTableGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PiSmmMemoryAttributesTable.h b/MdeModulePkg/Include/Guid/PiSmmMemoryAttributesTable.h index 63da8e77eb..88f67232bd 100644 --- a/MdeModulePkg/Include/Guid/PiSmmMemoryAttributesTable.h +++ b/MdeModulePkg/Include/Guid/PiSmmMemoryAttributesTable.h @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _PI_SMM_MEMORY_ATTRIBUTES_TABLE_H_ #define _PI_SMM_MEMORY_ATTRIBUTES_TABLE_H_ -#define EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE_GUID {\ +#define EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE_GUID {\ 0x6b9fd3f7, 0x16df, 0x45e8, {0xbd, 0x39, 0xb9, 0x4a, 0x66, 0x54, 0x1a, 0x5d} \ } @@ -31,15 +31,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // and it is EFI_MEMORY_XP. // typedef struct { - UINT32 Version; - UINT32 NumberOfEntries; - UINT32 DescriptorSize; - UINT32 Reserved; -//EFI_MEMORY_DESCRIPTOR Entry[1]; + UINT32 Version; + UINT32 NumberOfEntries; + UINT32 DescriptorSize; + UINT32 Reserved; + // EFI_MEMORY_DESCRIPTOR Entry[1]; } EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE; #define EDKII_PI_SMM_MEMORY_ATTRIBUTES_TABLE_VERSION 0x00000001 -extern EFI_GUID gEdkiiPiSmmMemoryAttributesTableGuid; +extern EFI_GUID gEdkiiPiSmmMemoryAttributesTableGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PlatDriOverrideHii.h b/MdeModulePkg/Include/Guid/PlatDriOverrideHii.h index 457f17a7d0..811160433a 100644 --- a/MdeModulePkg/Include/Guid/PlatDriOverrideHii.h +++ b/MdeModulePkg/Include/Guid/PlatDriOverrideHii.h @@ -14,6 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0x8614567d, 0x35be, 0x4415, {0x8d, 0x88, 0xbd, 0x7d, 0xc, 0x9c, 0x70, 0xc0} \ } -extern EFI_GUID gPlatformOverridesManagerGuid; +extern EFI_GUID gPlatformOverridesManagerGuid; #endif diff --git a/MdeModulePkg/Include/Guid/PlatformHasAcpi.h b/MdeModulePkg/Include/Guid/PlatformHasAcpi.h index 1f107abd04..d54fad77c0 100644 --- a/MdeModulePkg/Include/Guid/PlatformHasAcpi.h +++ b/MdeModulePkg/Include/Guid/PlatformHasAcpi.h @@ -14,7 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __EDKII_PLATFORM_HAS_ACPI_H__ #define __EDKII_PLATFORM_HAS_ACPI_H__ @@ -24,6 +23,6 @@ { 0x96, 0x04, 0x0f, 0xf7, 0xe1, 0x11, 0x96, 0x5a } \ } -extern EFI_GUID gEdkiiPlatformHasAcpiGuid; +extern EFI_GUID gEdkiiPlatformHasAcpiGuid; #endif diff --git a/MdeModulePkg/Include/Guid/RamDiskHii.h b/MdeModulePkg/Include/Guid/RamDiskHii.h index 69e5badb0b..3c8dfadf6b 100644 --- a/MdeModulePkg/Include/Guid/RamDiskHii.h +++ b/MdeModulePkg/Include/Guid/RamDiskHii.h @@ -14,6 +14,6 @@ 0x2a46715f, 0x3581, 0x4a55, {0x8e, 0x73, 0x2b, 0x76, 0x9a, 0xaa, 0x30, 0xc5} \ } -extern EFI_GUID gRamDiskFormSetGuid; +extern EFI_GUID gRamDiskFormSetGuid; #endif diff --git a/MdeModulePkg/Include/Guid/RecoveryDevice.h b/MdeModulePkg/Include/Guid/RecoveryDevice.h index 868fe7076b..c920ce04a3 100644 --- a/MdeModulePkg/Include/Guid/RecoveryDevice.h +++ b/MdeModulePkg/Include/Guid/RecoveryDevice.h @@ -53,10 +53,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xc770a27f, 0x956a, 0x497a, {0x85, 0x48, 0xe0, 0x61, 0x97, 0x58, 0x8b, 0xf6 } \ } -extern EFI_GUID gRecoveryOnDataCdGuid; -extern EFI_GUID gRecoveryOnFatFloppyDiskGuid; -extern EFI_GUID gRecoveryOnFatIdeDiskGuid; -extern EFI_GUID gRecoveryOnFatUsbDiskGuid; -extern EFI_GUID gRecoveryOnFatNvmeDiskGuid; +extern EFI_GUID gRecoveryOnDataCdGuid; +extern EFI_GUID gRecoveryOnFatFloppyDiskGuid; +extern EFI_GUID gRecoveryOnFatIdeDiskGuid; +extern EFI_GUID gRecoveryOnFatUsbDiskGuid; +extern EFI_GUID gRecoveryOnFatNvmeDiskGuid; #endif diff --git a/MdeModulePkg/Include/Guid/S3SmmInitDone.h b/MdeModulePkg/Include/Guid/S3SmmInitDone.h index f1ad496bc8..7deea2b968 100644 --- a/MdeModulePkg/Include/Guid/S3SmmInitDone.h +++ b/MdeModulePkg/Include/Guid/S3SmmInitDone.h @@ -16,6 +16,6 @@ 0x8f9d4825, 0x797d, 0x48fc, { 0x84, 0x71, 0x84, 0x50, 0x25, 0x79, 0x2e, 0xf6 } \ } -extern EFI_GUID gEdkiiS3SmmInitDoneGuid; +extern EFI_GUID gEdkiiS3SmmInitDoneGuid; #endif diff --git a/MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h b/MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h index c1bfaa41ed..5cc545de90 100644 --- a/MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h +++ b/MdeModulePkg/Include/Guid/S3StorageDeviceInitList.h @@ -54,4 +54,4 @@ // extern EFI_GUID gS3StorageDeviceInitListGuid; -#endif // __S3_STORAGE_DEVICE_INIT_LIST_H__ +#endif // __S3_STORAGE_DEVICE_INIT_LIST_H__ diff --git a/MdeModulePkg/Include/Guid/SerialPortLibVendor.h b/MdeModulePkg/Include/Guid/SerialPortLibVendor.h index 887f96c30a..6cb8e003c6 100644 --- a/MdeModulePkg/Include/Guid/SerialPortLibVendor.h +++ b/MdeModulePkg/Include/Guid/SerialPortLibVendor.h @@ -9,11 +9,11 @@ #ifndef __SERIAL_PORT_LIB_VENDOR_H__ #define __SERIAL_PORT_LIB_VENDOR_H__ -#define EDKII_SERIAL_PORT_LIB_VENDOR_GUID { \ +#define EDKII_SERIAL_PORT_LIB_VENDOR_GUID {\ 0xD3987D4B, 0x971A, 0x435F, \ { 0x8C, 0xAF, 0x49, 0x67, 0xEB, 0x62, 0x72, 0x41 } \ } -extern EFI_GUID gEdkiiSerialPortLibVendorGuid; +extern EFI_GUID gEdkiiSerialPortLibVendorGuid; #endif // __SERIAL_PORT_LIB_VENDOR_H__ diff --git a/MdeModulePkg/Include/Guid/SmiHandlerProfile.h b/MdeModulePkg/Include/Guid/SmiHandlerProfile.h index 359fe93fc1..6f155a09e0 100644 --- a/MdeModulePkg/Include/Guid/SmiHandlerProfile.h +++ b/MdeModulePkg/Include/Guid/SmiHandlerProfile.h @@ -20,29 +20,29 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include typedef struct { - UINT32 Signature; - UINT32 Length; - UINT32 Revision; - UINT8 Reserved[4]; + UINT32 Signature; + UINT32 Length; + UINT32 Revision; + UINT8 Reserved[4]; } SMM_CORE_DATABASE_COMMON_HEADER; -#define SMM_CORE_IMAGE_DATABASE_SIGNATURE SIGNATURE_32 ('S','C','I','D') -#define SMM_CORE_IMAGE_DATABASE_REVISION 0x0001 +#define SMM_CORE_IMAGE_DATABASE_SIGNATURE SIGNATURE_32 ('S','C','I','D') +#define SMM_CORE_IMAGE_DATABASE_REVISION 0x0001 typedef struct { - SMM_CORE_DATABASE_COMMON_HEADER Header; - EFI_GUID FileGuid; - PHYSICAL_ADDRESS EntryPoint; - PHYSICAL_ADDRESS ImageBase; - UINT64 ImageSize; - UINT32 ImageRef; - UINT16 PdbStringOffset; - UINT8 Reserved[2]; -//CHAR8 PdbString[]; + SMM_CORE_DATABASE_COMMON_HEADER Header; + EFI_GUID FileGuid; + PHYSICAL_ADDRESS EntryPoint; + PHYSICAL_ADDRESS ImageBase; + UINT64 ImageSize; + UINT32 ImageRef; + UINT16 PdbStringOffset; + UINT8 Reserved[2]; + // CHAR8 PdbString[]; } SMM_CORE_IMAGE_DATABASE_STRUCTURE; -#define SMM_CORE_SMI_DATABASE_SIGNATURE SIGNATURE_32 ('S','C','S','D') -#define SMM_CORE_SMI_DATABASE_REVISION 0x0001 +#define SMM_CORE_SMI_DATABASE_SIGNATURE SIGNATURE_32 ('S','C','S','D') +#define SMM_CORE_SMI_DATABASE_REVISION 0x0001 typedef enum { SmmCoreSmiHandlerCategoryRootHandler, @@ -68,32 +68,32 @@ typedef enum { // Other: GUID specific typedef struct { - EFI_USB_SMI_TYPE Type; - UINT32 DevicePathSize; -//UINT8 DevicePath[DevicePathSize]; + EFI_USB_SMI_TYPE Type; + UINT32 DevicePathSize; + // UINT8 DevicePath[DevicePathSize]; } SMI_HANDLER_PROFILE_USB_REGISTER_CONTEXT; typedef struct { - UINT64 SwSmiInputValue; + UINT64 SwSmiInputValue; } SMI_HANDLER_PROFILE_SW_REGISTER_CONTEXT; typedef struct { - UINT32 Length; - UINT32 ImageRef; - PHYSICAL_ADDRESS CallerAddr; - PHYSICAL_ADDRESS Handler; - UINT16 ContextBufferOffset; - UINT8 Reserved[2]; - UINT32 ContextBufferSize; -//UINT8 ContextBuffer[]; + UINT32 Length; + UINT32 ImageRef; + PHYSICAL_ADDRESS CallerAddr; + PHYSICAL_ADDRESS Handler; + UINT16 ContextBufferOffset; + UINT8 Reserved[2]; + UINT32 ContextBufferSize; + // UINT8 ContextBuffer[]; } SMM_CORE_SMI_HANDLER_STRUCTURE; typedef struct { - SMM_CORE_DATABASE_COMMON_HEADER Header; - EFI_GUID HandlerType; - UINT32 HandlerCategory; - UINT32 HandlerCount; -//SMM_CORE_SMI_HANDLER_STRUCTURE Handler[HandlerCount]; + SMM_CORE_DATABASE_COMMON_HEADER Header; + EFI_GUID HandlerType; + UINT32 HandlerCategory; + UINT32 HandlerCount; + // SMM_CORE_SMI_HANDLER_STRUCTURE Handler[HandlerCount]; } SMM_CORE_SMI_DATABASE_STRUCTURE; // @@ -105,18 +105,16 @@ typedef struct { // +-------------------------------------+ // - - // // SMM_CORE dump command // -#define SMI_HANDLER_PROFILE_COMMAND_GET_INFO 0x1 -#define SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET 0x2 +#define SMI_HANDLER_PROFILE_COMMAND_GET_INFO 0x1 +#define SMI_HANDLER_PROFILE_COMMAND_GET_DATA_BY_OFFSET 0x2 typedef struct { - UINT32 Command; - UINT32 DataLength; - UINT64 ReturnStatus; + UINT32 Command; + UINT32 DataLength; + UINT64 ReturnStatus; } SMI_HANDLER_PROFILE_PARAMETER_HEADER; typedef struct { @@ -139,11 +137,11 @@ typedef struct { UINT64 DataOffset; } SMI_HANDLER_PROFILE_PARAMETER_GET_DATA_BY_OFFSET; -#define SMI_HANDLER_PROFILE_GUID {0x49174342, 0x7108, 0x409b, {0x8b, 0xbe, 0x65, 0xfd, 0xa8, 0x53, 0x89, 0xf5}} +#define SMI_HANDLER_PROFILE_GUID {0x49174342, 0x7108, 0x409b, {0x8b, 0xbe, 0x65, 0xfd, 0xa8, 0x53, 0x89, 0xf5}} -extern EFI_GUID gSmiHandlerProfileGuid; +extern EFI_GUID gSmiHandlerProfileGuid; -typedef struct _SMI_HANDLER_PROFILE_PROTOCOL SMI_HANDLER_PROFILE_PROTOCOL; +typedef struct _SMI_HANDLER_PROFILE_PROTOCOL SMI_HANDLER_PROFILE_PROTOCOL; /** This function is called by SmmChildDispatcher module to report @@ -167,7 +165,7 @@ typedef struct _SMI_HANDLER_PROFILE_PROTOCOL SMI_HANDLER_PROFILE_PROTOCOL; **/ typedef EFI_STATUS -(EFIAPI *SMI_HANDLER_PROFILE_REGISTER_HANDLER) ( +(EFIAPI *SMI_HANDLER_PROFILE_REGISTER_HANDLER)( IN SMI_HANDLER_PROFILE_PROTOCOL *This, IN EFI_GUID *HandlerGuid, IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, @@ -195,7 +193,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *SMI_HANDLER_PROFILE_UNREGISTER_HANDLER) ( +(EFIAPI *SMI_HANDLER_PROFILE_UNREGISTER_HANDLER)( IN SMI_HANDLER_PROFILE_PROTOCOL *This, IN EFI_GUID *HandlerGuid, IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, @@ -204,8 +202,8 @@ EFI_STATUS ); struct _SMI_HANDLER_PROFILE_PROTOCOL { - SMI_HANDLER_PROFILE_REGISTER_HANDLER RegisterHandler; - SMI_HANDLER_PROFILE_UNREGISTER_HANDLER UnregisterHandler; + SMI_HANDLER_PROFILE_REGISTER_HANDLER RegisterHandler; + SMI_HANDLER_PROFILE_UNREGISTER_HANDLER UnregisterHandler; }; #endif diff --git a/MdeModulePkg/Include/Guid/SmmLockBox.h b/MdeModulePkg/Include/Guid/SmmLockBox.h index 0297ba93c1..3447c58728 100644 --- a/MdeModulePkg/Include/Guid/SmmLockBox.h +++ b/MdeModulePkg/Include/Guid/SmmLockBox.h @@ -17,50 +17,50 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Below data structure is used for communication between PEI/DXE to SMM. // -#define EFI_SMM_LOCK_BOX_COMMAND_SAVE 0x1 -#define EFI_SMM_LOCK_BOX_COMMAND_UPDATE 0x2 -#define EFI_SMM_LOCK_BOX_COMMAND_RESTORE 0x3 -#define EFI_SMM_LOCK_BOX_COMMAND_SET_ATTRIBUTES 0x4 -#define EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE 0x5 +#define EFI_SMM_LOCK_BOX_COMMAND_SAVE 0x1 +#define EFI_SMM_LOCK_BOX_COMMAND_UPDATE 0x2 +#define EFI_SMM_LOCK_BOX_COMMAND_RESTORE 0x3 +#define EFI_SMM_LOCK_BOX_COMMAND_SET_ATTRIBUTES 0x4 +#define EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE 0x5 typedef struct { - UINT32 Command; - UINT32 DataLength; - UINT64 ReturnStatus; + UINT32 Command; + UINT32 DataLength; + UINT64 ReturnStatus; } EFI_SMM_LOCK_BOX_PARAMETER_HEADER; typedef struct { - EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; - GUID Guid; - PHYSICAL_ADDRESS Buffer; - UINT64 Length; + EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; + GUID Guid; + PHYSICAL_ADDRESS Buffer; + UINT64 Length; } EFI_SMM_LOCK_BOX_PARAMETER_SAVE; typedef struct { - EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; - GUID Guid; - UINT64 Offset; - PHYSICAL_ADDRESS Buffer; - UINT64 Length; + EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; + GUID Guid; + UINT64 Offset; + PHYSICAL_ADDRESS Buffer; + UINT64 Length; } EFI_SMM_LOCK_BOX_PARAMETER_UPDATE; typedef struct { - EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; - GUID Guid; - PHYSICAL_ADDRESS Buffer; - UINT64 Length; + EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; + GUID Guid; + PHYSICAL_ADDRESS Buffer; + UINT64 Length; } EFI_SMM_LOCK_BOX_PARAMETER_RESTORE; typedef struct { - EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; - GUID Guid; - UINT64 Attributes; + EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; + GUID Guid; + UINT64 Attributes; } EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES; typedef struct { - EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; + EFI_SMM_LOCK_BOX_PARAMETER_HEADER Header; } EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE; -extern EFI_GUID gEfiSmmLockBoxCommunicationGuid; +extern EFI_GUID gEfiSmmLockBoxCommunicationGuid; #endif diff --git a/MdeModulePkg/Include/Guid/SmmVariableCommon.h b/MdeModulePkg/Include/Guid/SmmVariableCommon.h index 8ddc94b92d..1a1ab4fcc1 100644 --- a/MdeModulePkg/Include/Guid/SmmVariableCommon.h +++ b/MdeModulePkg/Include/Guid/SmmVariableCommon.h @@ -15,7 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_SMM_VARIABLE_WRITE_GUID \ { 0x93ba1826, 0xdffb, 0x45dd, { 0x82, 0xa7, 0xe7, 0xdc, 0xaa, 0x3b, 0xbd, 0xf3 } } -extern EFI_GUID gSmmVariableWriteGuid; +extern EFI_GUID gSmmVariableWriteGuid; // // This structure is used for SMM variable. the collected statistics data is saved in SMRAM. It can be got from @@ -23,15 +23,15 @@ extern EFI_GUID gSmmVariableWriteGuid; // EFI_MM_COMMUNICATE_HEADER + SMM_VARIABLE_COMMUNICATE_HEADER + payload. // typedef struct { - UINTN Function; - EFI_STATUS ReturnStatus; - UINT8 Data[1]; + UINTN Function; + EFI_STATUS ReturnStatus; + UINT8 Data[1]; } SMM_VARIABLE_COMMUNICATE_HEADER; // // The payload for this function is SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE. // -#define SMM_VARIABLE_FUNCTION_GET_VARIABLE 1 +#define SMM_VARIABLE_FUNCTION_GET_VARIABLE 1 // // The payload for this function is SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME. // @@ -39,44 +39,44 @@ typedef struct { // // The payload for this function is SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE. // -#define SMM_VARIABLE_FUNCTION_SET_VARIABLE 3 +#define SMM_VARIABLE_FUNCTION_SET_VARIABLE 3 // // The payload for this function is SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO. // -#define SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO 4 +#define SMM_VARIABLE_FUNCTION_QUERY_VARIABLE_INFO 4 // // It is a notify event, no extra payload for this function. // -#define SMM_VARIABLE_FUNCTION_READY_TO_BOOT 5 +#define SMM_VARIABLE_FUNCTION_READY_TO_BOOT 5 // // It is a notify event, no extra payload for this function. // -#define SMM_VARIABLE_FUNCTION_EXIT_BOOT_SERVICE 6 +#define SMM_VARIABLE_FUNCTION_EXIT_BOOT_SERVICE 6 // // The payload for this function is VARIABLE_INFO_ENTRY. The GUID in EFI_MM_COMMUNICATE_HEADER // is gEfiSmmVariableProtocolGuid. // -#define SMM_VARIABLE_FUNCTION_GET_STATISTICS 7 +#define SMM_VARIABLE_FUNCTION_GET_STATISTICS 7 // // The payload for this function is SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE // -#define SMM_VARIABLE_FUNCTION_LOCK_VARIABLE 8 +#define SMM_VARIABLE_FUNCTION_LOCK_VARIABLE 8 #define SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_SET 9 #define SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET 10 -#define SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE 11 +#define SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE 11 // // The payload for this function is SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT // -#define SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT 12 +#define SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT 12 -#define SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE 13 +#define SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE 13 // // The payload for this function is SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO // -#define SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO 14 +#define SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO 14 /// /// Size of SMM communicate header, without including the payload. @@ -112,39 +112,39 @@ typedef struct { /// This structure is used to communicate with SMI handler by QueryVariableInfo. /// typedef struct { - UINT64 MaximumVariableStorageSize; - UINT64 RemainingVariableStorageSize; - UINT64 MaximumVariableSize; - UINT32 Attributes; + UINT64 MaximumVariableStorageSize; + UINT64 RemainingVariableStorageSize; + UINT64 MaximumVariableSize; + UINT32 Attributes; } SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO; typedef SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE; typedef struct { - EFI_GUID Guid; - UINTN NameSize; - VAR_CHECK_VARIABLE_PROPERTY VariableProperty; - CHAR16 Name[1]; + EFI_GUID Guid; + UINTN NameSize; + VAR_CHECK_VARIABLE_PROPERTY VariableProperty; + CHAR16 Name[1]; } SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY; typedef struct { - UINTN VariablePayloadSize; + UINTN VariablePayloadSize; } SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE; typedef struct { - BOOLEAN *ReadLock; - BOOLEAN *PendingUpdate; - BOOLEAN *HobFlushComplete; - VARIABLE_STORE_HEADER *RuntimeHobCache; - VARIABLE_STORE_HEADER *RuntimeNvCache; - VARIABLE_STORE_HEADER *RuntimeVolatileCache; + BOOLEAN *ReadLock; + BOOLEAN *PendingUpdate; + BOOLEAN *HobFlushComplete; + VARIABLE_STORE_HEADER *RuntimeHobCache; + VARIABLE_STORE_HEADER *RuntimeNvCache; + VARIABLE_STORE_HEADER *RuntimeVolatileCache; } SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT; typedef struct { - UINTN TotalHobStorageSize; - UINTN TotalNvStorageSize; - UINTN TotalVolatileStorageSize; - BOOLEAN AuthenticatedVariableUsage; + UINTN TotalHobStorageSize; + UINTN TotalNvStorageSize; + UINTN TotalVolatileStorageSize; + BOOLEAN AuthenticatedVariableUsage; } SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO; #endif // _SMM_VARIABLE_COMMON_H_ diff --git a/MdeModulePkg/Include/Guid/StandardErrorDevice.h b/MdeModulePkg/Include/Guid/StandardErrorDevice.h index c15a00e714..400d9a039c 100644 --- a/MdeModulePkg/Include/Guid/StandardErrorDevice.h +++ b/MdeModulePkg/Include/Guid/StandardErrorDevice.h @@ -13,6 +13,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_STANDARD_ERROR_DEVICE_GUID \ { 0xd3b36f2d, 0xd551, 0x11d4, {0x9a, 0x46, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d } } -extern EFI_GUID gEfiStandardErrorDeviceGuid; +extern EFI_GUID gEfiStandardErrorDeviceGuid; #endif diff --git a/MdeModulePkg/Include/Guid/StatusCodeCallbackGuid.h b/MdeModulePkg/Include/Guid/StatusCodeCallbackGuid.h index 6730a00900..0e5af6aff6 100644 --- a/MdeModulePkg/Include/Guid/StatusCodeCallbackGuid.h +++ b/MdeModulePkg/Include/Guid/StatusCodeCallbackGuid.h @@ -15,6 +15,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xe701458c, 0x4900, 0x4ca5, {0xb7, 0x72, 0x3d, 0x37, 0x94, 0x9f, 0x79, 0x27} \ } -extern EFI_GUID gStatusCodeCallbackGuid; +extern EFI_GUID gStatusCodeCallbackGuid; #endif diff --git a/MdeModulePkg/Include/Guid/StatusCodeDataTypeDebug.h b/MdeModulePkg/Include/Guid/StatusCodeDataTypeDebug.h index e511c2d61a..16203452e4 100644 --- a/MdeModulePkg/Include/Guid/StatusCodeDataTypeDebug.h +++ b/MdeModulePkg/Include/Guid/StatusCodeDataTypeDebug.h @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// The maximum size of an EFI_DEBUG_INFO structure. /// -#define EFI_STATUS_CODE_DATA_MAX_SIZE 200 +#define EFI_STATUS_CODE_DATA_MAX_SIZE 200 /// /// This structure contains the ErrorLevel passed into the DEBUG() macro, followed @@ -35,9 +35,9 @@ typedef struct { /// /// The debug error level passed into a DEBUG() macro. /// - UINT32 ErrorLevel; + UINT32 ErrorLevel; } EFI_DEBUG_INFO; -extern EFI_GUID gEfiStatusCodeDataTypeDebugGuid; +extern EFI_GUID gEfiStatusCodeDataTypeDebugGuid; #endif // _STATUS_CODE_DATA_TYPE_DEBUG_H_ diff --git a/MdeModulePkg/Include/Guid/StatusCodeDataTypeVariable.h b/MdeModulePkg/Include/Guid/StatusCodeDataTypeVariable.h index 4663070025..a0edac365f 100644 --- a/MdeModulePkg/Include/Guid/StatusCodeDataTypeVariable.h +++ b/MdeModulePkg/Include/Guid/StatusCodeDataTypeVariable.h @@ -20,15 +20,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent } typedef struct { - EFI_GUID Guid; - UINTN NameSize; - UINTN DataSize; - EFI_STATUS SetStatus; - UINT32 Attributes; + EFI_GUID Guid; + UINTN NameSize; + UINTN DataSize; + EFI_STATUS SetStatus; + UINT32 Attributes; // CHAR16 Name[]; // UINT8 Data[]; } EDKII_SET_VARIABLE_STATUS; -extern EFI_GUID gEdkiiStatusCodeDataTypeVariableGuid; +extern EFI_GUID gEdkiiStatusCodeDataTypeVariableGuid; #endif // _STATUS_CODE_DATA_TYPE_VARIABLE_H_ diff --git a/MdeModulePkg/Include/Guid/SystemNvDataGuid.h b/MdeModulePkg/Include/Guid/SystemNvDataGuid.h index 57b457bfa8..85f226d0cc 100644 --- a/MdeModulePkg/Include/Guid/SystemNvDataGuid.h +++ b/MdeModulePkg/Include/Guid/SystemNvDataGuid.h @@ -18,11 +18,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EDKII_WORKING_BLOCK_SIGNATURE_GUID \ {0x9e58292b, 0x7c68, 0x497d, {0xa0, 0xce, 0x65, 0x0, 0xfd, 0x9f, 0x1b, 0x95} } -extern EFI_GUID gEfiSystemNvDataFvGuid; -extern EFI_GUID gEdkiiWorkingBlockSignatureGuid; +extern EFI_GUID gEfiSystemNvDataFvGuid; +extern EFI_GUID gEdkiiWorkingBlockSignatureGuid; -#define WORKING_BLOCK_VALID 0x1 -#define WORKING_BLOCK_INVALID 0x2 +#define WORKING_BLOCK_VALID 0x1 +#define WORKING_BLOCK_INVALID 0x2 /// /// The EDKII Fault tolerant working block header. @@ -34,22 +34,22 @@ typedef struct { /// Its value has be updated from gEfiSystemNvDataFvGuid to gEdkiiWorkingBlockSignatureGuid, /// because its write queue data format has been updated to support the crossing archs. /// - EFI_GUID Signature; + EFI_GUID Signature; /// /// 32bit CRC calculated for this header. /// - UINT32 Crc; + UINT32 Crc; /// /// Working block valid bit. /// - UINT8 WorkingBlockValid : 1; - UINT8 WorkingBlockInvalid : 1; - UINT8 Reserved : 6; - UINT8 Reserved3[3]; + UINT8 WorkingBlockValid : 1; + UINT8 WorkingBlockInvalid : 1; + UINT8 Reserved : 6; + UINT8 Reserved3[3]; /// /// Total size of the following write queue range. /// - UINT64 WriteQueueSize; + UINT64 WriteQueueSize; /// /// Write Queue data. /// @@ -61,37 +61,37 @@ typedef struct { /// } EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER; -#define FTW_VALID_STATE 0 -#define FTW_INVALID_STATE 1 +#define FTW_VALID_STATE 0 +#define FTW_INVALID_STATE 1 // // EFI Fault tolerant block update write queue entry. // typedef struct { - UINT8 HeaderAllocated : 1; - UINT8 WritesAllocated : 1; - UINT8 Complete : 1; - UINT8 Reserved : 5; - EFI_GUID CallerId; - UINT64 NumberOfWrites; - UINT64 PrivateDataSize; + UINT8 HeaderAllocated : 1; + UINT8 WritesAllocated : 1; + UINT8 Complete : 1; + UINT8 Reserved : 5; + EFI_GUID CallerId; + UINT64 NumberOfWrites; + UINT64 PrivateDataSize; } EFI_FAULT_TOLERANT_WRITE_HEADER; // // EFI Fault tolerant block update write queue record. // typedef struct { - UINT8 BootBlockUpdate : 1; - UINT8 SpareComplete : 1; - UINT8 DestinationComplete : 1; - UINT8 Reserved : 5; - EFI_LBA Lba; - UINT64 Offset; - UINT64 Length; + UINT8 BootBlockUpdate : 1; + UINT8 SpareComplete : 1; + UINT8 DestinationComplete : 1; + UINT8 Reserved : 5; + EFI_LBA Lba; + UINT64 Offset; + UINT64 Length; // // Relative offset to spare block. // - INT64 RelativeOffset; + INT64 RelativeOffset; // // UINT8 PrivateData[PrivateDataSize] // diff --git a/MdeModulePkg/Include/Guid/TtyTerm.h b/MdeModulePkg/Include/Guid/TtyTerm.h index a87c1e8b3a..6bd999cc96 100644 --- a/MdeModulePkg/Include/Guid/TtyTerm.h +++ b/MdeModulePkg/Include/Guid/TtyTerm.h @@ -27,10 +27,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EDKII_SCO_TERM_GUID \ {0xfc7dd6e0, 0x813c, 0x434d, {0xb4, 0xda, 0x3b, 0xd6, 0x49, 0xe9, 0xe1, 0x5a } } -extern EFI_GUID gEfiTtyTermGuid; -extern EFI_GUID gEdkiiLinuxTermGuid; -extern EFI_GUID gEdkiiXtermR6Guid; -extern EFI_GUID gEdkiiVT400Guid; -extern EFI_GUID gEdkiiSCOTermGuid; +extern EFI_GUID gEfiTtyTermGuid; +extern EFI_GUID gEdkiiLinuxTermGuid; +extern EFI_GUID gEdkiiXtermR6Guid; +extern EFI_GUID gEdkiiVT400Guid; +extern EFI_GUID gEdkiiSCOTermGuid; #endif diff --git a/MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h b/MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h index 77bcc62f3c..ff3d4a1fd6 100644 --- a/MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h +++ b/MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h @@ -15,21 +15,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #pragma pack(push, 1) typedef struct _VAR_CHECK_POLICY_COMM_HEADER { - UINT32 Signature; - UINT32 Revision; - UINT32 Command; - EFI_STATUS Result; + UINT32 Signature; + UINT32 Revision; + UINT32 Command; + EFI_STATUS Result; } VAR_CHECK_POLICY_COMM_HEADER; typedef struct _VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS { - BOOLEAN State; + BOOLEAN State; } VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS; typedef struct _VAR_CHECK_POLICY_COMM_DUMP_PARAMS { - UINT32 PageRequested; - UINT32 TotalSize; - UINT32 PageSize; - BOOLEAN HasMore; + UINT32 PageRequested; + UINT32 TotalSize; + UINT32 PageSize; + BOOLEAN HasMore; } VAR_CHECK_POLICY_COMM_DUMP_PARAMS; #pragma pack(pop) @@ -45,10 +45,10 @@ STATIC_ASSERT ( "an integer underflow may have occurred calculating VAR_CHECK_POLICY_MM_DUMP_BUFFER_SIZE" ); -#define VAR_CHECK_POLICY_COMMAND_DISABLE 0x0001 -#define VAR_CHECK_POLICY_COMMAND_IS_ENABLED 0x0002 -#define VAR_CHECK_POLICY_COMMAND_REGISTER 0x0003 -#define VAR_CHECK_POLICY_COMMAND_DUMP 0x0004 -#define VAR_CHECK_POLICY_COMMAND_LOCK 0x0005 +#define VAR_CHECK_POLICY_COMMAND_DISABLE 0x0001 +#define VAR_CHECK_POLICY_COMMAND_IS_ENABLED 0x0002 +#define VAR_CHECK_POLICY_COMMAND_REGISTER 0x0003 +#define VAR_CHECK_POLICY_COMMAND_DUMP 0x0004 +#define VAR_CHECK_POLICY_COMMAND_LOCK 0x0005 #endif // _VAR_CHECK_POLICY_MMI_COMMON_H_ diff --git a/MdeModulePkg/Include/Guid/VarErrorFlag.h b/MdeModulePkg/Include/Guid/VarErrorFlag.h index cc12222fff..e59ad79283 100644 --- a/MdeModulePkg/Include/Guid/VarErrorFlag.h +++ b/MdeModulePkg/Include/Guid/VarErrorFlag.h @@ -17,19 +17,18 @@ // // If the variable is not present, it has the same meaning with VAR_ERROR_FLAG_NO_ERROR. // -#define VAR_ERROR_FLAG_NAME L"VarErrorFlag" +#define VAR_ERROR_FLAG_NAME L"VarErrorFlag" -#define VAR_ERROR_FLAG_NO_ERROR 0xFF // 1111-1111 -#define VAR_ERROR_FLAG_SYSTEM_ERROR 0xEF // 1110-1111 -#define VAR_ERROR_FLAG_USER_ERROR 0xFE // 1111-1110 +#define VAR_ERROR_FLAG_NO_ERROR 0xFF // 1111-1111 +#define VAR_ERROR_FLAG_SYSTEM_ERROR 0xEF // 1110-1111 +#define VAR_ERROR_FLAG_USER_ERROR 0xFE // 1111-1110 typedef UINT8 VAR_ERROR_FLAG; -#define EDKII_VAR_ERROR_FLAG_GUID { \ +#define EDKII_VAR_ERROR_FLAG_GUID {\ 0x4b37fe8, 0xf6ae, 0x480b, { 0xbd, 0xd5, 0x37, 0xd9, 0x8c, 0x5e, 0x89, 0xaa } \ }; -extern EFI_GUID gEdkiiVarErrorFlagGuid; +extern EFI_GUID gEdkiiVarErrorFlagGuid; #endif - diff --git a/MdeModulePkg/Include/Guid/VariableFormat.h b/MdeModulePkg/Include/Guid/VariableFormat.h index a5574fe821..534007a710 100644 --- a/MdeModulePkg/Include/Guid/VariableFormat.h +++ b/MdeModulePkg/Include/Guid/VariableFormat.h @@ -16,22 +16,22 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_AUTHENTICATED_VARIABLE_GUID \ { 0xaaf32c78, 0x947b, 0x439a, { 0xa1, 0x80, 0x2e, 0x14, 0x4e, 0xc3, 0x77, 0x92 } } -extern EFI_GUID gEfiVariableGuid; -extern EFI_GUID gEfiAuthenticatedVariableGuid; +extern EFI_GUID gEfiVariableGuid; +extern EFI_GUID gEfiAuthenticatedVariableGuid; /// /// Alignment of variable name and data, according to the architecture: /// * For IA-32 and Intel(R) 64 architectures: 1. /// -#define ALIGNMENT 1 +#define ALIGNMENT 1 // // GET_PAD_SIZE calculates the miminal pad bytes needed to make the current pad size satisfy the alignment requirement. // #if (ALIGNMENT == 1) -#define GET_PAD_SIZE(a) (0) +#define GET_PAD_SIZE(a) (0) #else -#define GET_PAD_SIZE(a) (((~a) + 1) & (ALIGNMENT - 1)) +#define GET_PAD_SIZE(a) (((~a) + 1) & (ALIGNMENT - 1)) #endif /// @@ -52,14 +52,14 @@ typedef enum { #pragma pack(1) -#define VARIABLE_STORE_SIGNATURE EFI_VARIABLE_GUID +#define VARIABLE_STORE_SIGNATURE EFI_VARIABLE_GUID #define AUTHENTICATED_VARIABLE_STORE_SIGNATURE EFI_AUTHENTICATED_VARIABLE_GUID /// /// Variable Store Header Format and State. /// -#define VARIABLE_STORE_FORMATTED 0x5a -#define VARIABLE_STORE_HEALTHY 0xfe +#define VARIABLE_STORE_FORMATTED 0x5a +#define VARIABLE_STORE_HEALTHY 0xfe /// /// Variable Store region header. @@ -68,54 +68,54 @@ typedef struct { /// /// Variable store region signature. /// - EFI_GUID Signature; + EFI_GUID Signature; /// /// Size of entire variable store, /// including size of variable store header but not including the size of FvHeader. /// - UINT32 Size; + UINT32 Size; /// /// Variable region format state. /// - UINT8 Format; + UINT8 Format; /// /// Variable region healthy state. /// - UINT8 State; - UINT16 Reserved; - UINT32 Reserved1; + UINT8 State; + UINT16 Reserved; + UINT32 Reserved1; } VARIABLE_STORE_HEADER; /// /// Variable data start flag. /// -#define VARIABLE_DATA 0x55AA +#define VARIABLE_DATA 0x55AA /// /// Variable State flags. /// -#define VAR_IN_DELETED_TRANSITION 0xfe ///< Variable is in obsolete transition. -#define VAR_DELETED 0xfd ///< Variable is obsolete. -#define VAR_HEADER_VALID_ONLY 0x7f ///< Variable header has been valid. -#define VAR_ADDED 0x3f ///< Variable has been completely added. +#define VAR_IN_DELETED_TRANSITION 0xfe ///< Variable is in obsolete transition. +#define VAR_DELETED 0xfd ///< Variable is obsolete. +#define VAR_HEADER_VALID_ONLY 0x7f ///< Variable header has been valid. +#define VAR_ADDED 0x3f ///< Variable has been completely added. /// /// Variable Attribute combinations. /// -#define VARIABLE_ATTRIBUTE_NV_BS (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS) -#define VARIABLE_ATTRIBUTE_BS_RT (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS) -#define VARIABLE_ATTRIBUTE_BS_RT_AT (VARIABLE_ATTRIBUTE_BS_RT | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) -#define VARIABLE_ATTRIBUTE_NV_BS_RT (VARIABLE_ATTRIBUTE_BS_RT | EFI_VARIABLE_NON_VOLATILE) -#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_HARDWARE_ERROR_RECORD) -#define VARIABLE_ATTRIBUTE_NV_BS_RT_AT (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) -#define VARIABLE_ATTRIBUTE_AT EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS -#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR_AT (VARIABLE_ATTRIBUTE_NV_BS_RT_HR | VARIABLE_ATTRIBUTE_AT) +#define VARIABLE_ATTRIBUTE_NV_BS (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS) +#define VARIABLE_ATTRIBUTE_BS_RT (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS) +#define VARIABLE_ATTRIBUTE_BS_RT_AT (VARIABLE_ATTRIBUTE_BS_RT | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) +#define VARIABLE_ATTRIBUTE_NV_BS_RT (VARIABLE_ATTRIBUTE_BS_RT | EFI_VARIABLE_NON_VOLATILE) +#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_HARDWARE_ERROR_RECORD) +#define VARIABLE_ATTRIBUTE_NV_BS_RT_AT (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) +#define VARIABLE_ATTRIBUTE_AT EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS +#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR_AT (VARIABLE_ATTRIBUTE_NV_BS_RT_HR | VARIABLE_ATTRIBUTE_AT) /// /// EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is deprecated and should be considered as reserved /// -#define VARIABLE_ATTRIBUTE_AT_AW (EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) -#define VARIABLE_ATTRIBUTE_NV_BS_RT_AW (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) -#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR_AT_AW (VARIABLE_ATTRIBUTE_NV_BS_RT_HR | VARIABLE_ATTRIBUTE_AT_AW) +#define VARIABLE_ATTRIBUTE_AT_AW (EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) +#define VARIABLE_ATTRIBUTE_NV_BS_RT_AW (VARIABLE_ATTRIBUTE_NV_BS_RT | EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) +#define VARIABLE_ATTRIBUTE_NV_BS_RT_HR_AT_AW (VARIABLE_ATTRIBUTE_NV_BS_RT_HR | VARIABLE_ATTRIBUTE_AT_AW) /// /// Single Variable Data Header Structure. @@ -199,7 +199,7 @@ typedef struct { #pragma pack() -typedef struct _VARIABLE_INFO_ENTRY VARIABLE_INFO_ENTRY; +typedef struct _VARIABLE_INFO_ENTRY VARIABLE_INFO_ENTRY; /// /// This structure contains the variable list that is put in EFI system table. @@ -207,15 +207,15 @@ typedef struct _VARIABLE_INFO_ENTRY VARIABLE_INFO_ENTRY; /// This is an optional feature to dump all used variables in shell environment. /// struct _VARIABLE_INFO_ENTRY { - VARIABLE_INFO_ENTRY *Next; ///< Pointer to next entry. - EFI_GUID VendorGuid; ///< Guid of Variable. - CHAR16 *Name; ///< Name of Variable. - UINT32 Attributes; ///< Attributes of variable defined in UEFI specification. - UINT32 ReadCount; ///< Number of times to read this variable. - UINT32 WriteCount; ///< Number of times to write this variable. - UINT32 DeleteCount; ///< Number of times to delete this variable. - UINT32 CacheCount; ///< Number of times that cache hits this variable. - BOOLEAN Volatile; ///< TRUE if volatile, FALSE if non-volatile. + VARIABLE_INFO_ENTRY *Next; ///< Pointer to next entry. + EFI_GUID VendorGuid; ///< Guid of Variable. + CHAR16 *Name; ///< Name of Variable. + UINT32 Attributes; ///< Attributes of variable defined in UEFI specification. + UINT32 ReadCount; ///< Number of times to read this variable. + UINT32 WriteCount; ///< Number of times to write this variable. + UINT32 DeleteCount; ///< Number of times to delete this variable. + UINT32 CacheCount; ///< Number of times that cache hits this variable. + BOOLEAN Volatile; ///< TRUE if volatile, FALSE if non-volatile. }; #endif // _EFI_VARIABLE_H_ diff --git a/MdeModulePkg/Include/Guid/VariableIndexTable.h b/MdeModulePkg/Include/Guid/VariableIndexTable.h index 5d6123330b..f18a5e3c43 100644 --- a/MdeModulePkg/Include/Guid/VariableIndexTable.h +++ b/MdeModulePkg/Include/Guid/VariableIndexTable.h @@ -11,31 +11,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define __VARIABLE_INDEX_TABLE_H__ typedef struct { - VARIABLE_HEADER *CurrPtr; - VARIABLE_HEADER *EndPtr; - VARIABLE_HEADER *StartPtr; + VARIABLE_HEADER *CurrPtr; + VARIABLE_HEADER *EndPtr; + VARIABLE_HEADER *StartPtr; } VARIABLE_POINTER_TRACK; -#define VARIABLE_INDEX_TABLE_VOLUME 122 +#define VARIABLE_INDEX_TABLE_VOLUME 122 #define EFI_VARIABLE_INDEX_TABLE_GUID \ { 0x8cfdb8c8, 0xd6b2, 0x40f3, { 0x8e, 0x97, 0x02, 0x30, 0x7c, 0xc9, 0x8b, 0x7c } } -extern EFI_GUID gEfiVariableIndexTableGuid; +extern EFI_GUID gEfiVariableIndexTableGuid; /// /// Use this data structure to store variable-related info, which can decrease /// the cost of access to NV. /// typedef struct { - UINT16 Length; - UINT16 GoneThrough; - VARIABLE_HEADER *EndPtr; - VARIABLE_HEADER *StartPtr; + UINT16 Length; + UINT16 GoneThrough; + VARIABLE_HEADER *EndPtr; + VARIABLE_HEADER *StartPtr; /// /// This field is used to store the distance of two neighbouring VAR_ADDED type variables. /// The meaning of the field is implement-dependent. - UINT16 Index[VARIABLE_INDEX_TABLE_VOLUME]; + UINT16 Index[VARIABLE_INDEX_TABLE_VOLUME]; } VARIABLE_INDEX_TABLE; #endif // __VARIABLE_INDEX_TABLE_H__ diff --git a/MdeModulePkg/Include/Guid/ZeroGuid.h b/MdeModulePkg/Include/Guid/ZeroGuid.h index a3b31ed701..bcdca8353c 100644 --- a/MdeModulePkg/Include/Guid/ZeroGuid.h +++ b/MdeModulePkg/Include/Guid/ZeroGuid.h @@ -14,6 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0x0, 0x0, 0x0, {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} \ } -extern EFI_GUID gZeroGuid; +extern EFI_GUID gZeroGuid; #endif diff --git a/MdeModulePkg/Include/Library/AuthVariableLib.h b/MdeModulePkg/Include/Library/AuthVariableLib.h index 76a8c8bd50..37aceba699 100644 --- a/MdeModulePkg/Include/Library/AuthVariableLib.h +++ b/MdeModulePkg/Include/Library/AuthVariableLib.h @@ -14,25 +14,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Size of AuthInfo prior to the data payload. /// -#define AUTHINFO_SIZE ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION, AuthInfo)) + \ +#define AUTHINFO_SIZE ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION, AuthInfo)) +\ (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) + \ sizeof (EFI_CERT_BLOCK_RSA_2048_SHA256)) -#define AUTHINFO2_SIZE(VarAuth2) ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) + \ +#define AUTHINFO2_SIZE(VarAuth2) ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) +\ (UINTN) ((EFI_VARIABLE_AUTHENTICATION_2 *) (VarAuth2))->AuthInfo.Hdr.dwLength) -#define OFFSET_OF_AUTHINFO2_CERT_DATA ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) + \ +#define OFFSET_OF_AUTHINFO2_CERT_DATA ((OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo)) +\ (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData))) typedef struct { - CHAR16 *VariableName; - EFI_GUID *VendorGuid; - UINT32 Attributes; - UINTN DataSize; - VOID *Data; - UINT32 PubKeyIndex; - UINT64 MonotonicCount; - EFI_TIME *TimeStamp; + CHAR16 *VariableName; + EFI_GUID *VendorGuid; + UINT32 Attributes; + UINTN DataSize; + VOID *Data; + UINT32 PubKeyIndex; + UINT64 MonotonicCount; + EFI_TIME *TimeStamp; } AUTH_VARIABLE_INFO; /** @@ -55,7 +55,7 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *AUTH_VAR_LIB_FIND_VARIABLE) ( +(EFIAPI *AUTH_VAR_LIB_FIND_VARIABLE)( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, OUT AUTH_VARIABLE_INFO *AuthVariableInfo @@ -81,7 +81,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *AUTH_VAR_LIB_FIND_NEXT_VARIABLE) ( +(EFIAPI *AUTH_VAR_LIB_FIND_NEXT_VARIABLE)( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, OUT AUTH_VARIABLE_INFO *AuthVariableInfo @@ -101,7 +101,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *AUTH_VAR_LIB_UPDATE_VARIABLE) ( +(EFIAPI *AUTH_VAR_LIB_UPDATE_VARIABLE)( IN AUTH_VARIABLE_INFO *AuthVariableInfo ); @@ -119,7 +119,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *AUTH_VAR_LIB_GET_SCRATCH_BUFFER) ( +(EFIAPI *AUTH_VAR_LIB_GET_SCRATCH_BUFFER)( IN OUT UINTN *ScratchBufferSize, OUT VOID **ScratchBuffer ); @@ -145,7 +145,7 @@ EFI_STATUS **/ typedef BOOLEAN -(EFIAPI *AUTH_VAR_LIB_CHECK_REMAINING_SPACE) ( +(EFIAPI *AUTH_VAR_LIB_CHECK_REMAINING_SPACE)( IN UINT32 Attributes, ... ); @@ -159,7 +159,7 @@ BOOLEAN **/ typedef BOOLEAN -(EFIAPI *AUTH_VAR_LIB_AT_RUNTIME) ( +(EFIAPI *AUTH_VAR_LIB_AT_RUNTIME)( VOID ); @@ -183,21 +183,21 @@ typedef struct { AUTH_VAR_LIB_AT_RUNTIME AtRuntime; } AUTH_VAR_LIB_CONTEXT_IN; -#define AUTH_VAR_LIB_CONTEXT_OUT_STRUCT_VERSION 0x01 +#define AUTH_VAR_LIB_CONTEXT_OUT_STRUCT_VERSION 0x01 typedef struct { - UINTN StructVersion; - UINTN StructSize; + UINTN StructVersion; + UINTN StructSize; // // Caller needs to set variable property for the variables. // - VARIABLE_ENTRY_PROPERTY *AuthVarEntry; - UINTN AuthVarEntryCount; + VARIABLE_ENTRY_PROPERTY *AuthVarEntry; + UINTN AuthVarEntryCount; // // Caller needs to ConvertPointer() for the pointers. // - VOID ***AddressPointer; - UINTN AddressPointerCount; + VOID ***AddressPointer; + UINTN AddressPointerCount; } AUTH_VAR_LIB_CONTEXT_OUT; /** @@ -244,11 +244,11 @@ AuthVariableLibInitialize ( EFI_STATUS EFIAPI AuthVariableLibProcessVariable ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN VOID *Data, - IN UINTN DataSize, - IN UINT32 Attributes + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN VOID *Data, + IN UINTN DataSize, + IN UINT32 Attributes ); #endif diff --git a/MdeModulePkg/Include/Library/BootLogoLib.h b/MdeModulePkg/Include/Library/BootLogoLib.h index afd895b257..2d6209a278 100644 --- a/MdeModulePkg/Include/Library/BootLogoLib.h +++ b/MdeModulePkg/Include/Library/BootLogoLib.h @@ -22,7 +22,6 @@ BootLogoEnableLogo ( VOID ); - /** Use SystemTable ConOut to turn on video based Simple Text Out consoles. The Simple Text Out screens will now be synced up with all non-video output devices. @@ -53,12 +52,12 @@ BootLogoDisableLogo ( EFI_STATUS EFIAPI BootLogoUpdateProgress ( - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground, - IN CHAR16 *Title, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor, - IN UINTN Progress, - IN UINTN PreviousValue + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground, + IN CHAR16 *Title, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor, + IN UINTN Progress, + IN UINTN PreviousValue ); #endif diff --git a/MdeModulePkg/Include/Library/CapsuleLib.h b/MdeModulePkg/Include/Library/CapsuleLib.h index 0f41642576..92904ebfb6 100644 --- a/MdeModulePkg/Include/Library/CapsuleLib.h +++ b/MdeModulePkg/Include/Library/CapsuleLib.h @@ -13,7 +13,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // BOOLEAN Variable to indicate whether system is in the capsule on disk state. // -#define COD_RELOCATION_INFO_VAR_NAME L"CodRelocationInfo" +#define COD_RELOCATION_INFO_VAR_NAME L"CodRelocationInfo" /** The firmware checks whether the capsule image is supported @@ -30,7 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI SupportCapsuleImage ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ); /** @@ -47,7 +47,7 @@ SupportCapsuleImage ( EFI_STATUS EFIAPI ProcessCapsuleImage ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ); /** @@ -96,7 +96,7 @@ ProcessCapsules ( **/ BOOLEAN EFIAPI -CoDCheckCapsuleOnDiskFlag( +CoDCheckCapsuleOnDiskFlag ( VOID ); @@ -108,7 +108,7 @@ CoDCheckCapsuleOnDiskFlag( **/ EFI_STATUS EFIAPI -CoDClearCapsuleOnDiskFlag( +CoDClearCapsuleOnDiskFlag ( VOID ); @@ -136,8 +136,8 @@ CoDClearCapsuleOnDiskFlag( **/ EFI_STATUS EFIAPI -CoDRelocateCapsule( - UINTN MaxRetry +CoDRelocateCapsule ( + UINTN MaxRetry ); /** @@ -154,7 +154,7 @@ CoDRelocateCapsule( EFI_STATUS EFIAPI CoDRemoveTempFile ( - UINTN MaxRetry + UINTN MaxRetry ); #endif diff --git a/MdeModulePkg/Include/Library/CpuExceptionHandlerLib.h b/MdeModulePkg/Include/Library/CpuExceptionHandlerLib.h index 2c18dacf5c..22a4408f9f 100644 --- a/MdeModulePkg/Include/Library/CpuExceptionHandlerLib.h +++ b/MdeModulePkg/Include/Library/CpuExceptionHandlerLib.h @@ -13,70 +13,70 @@ #include #include -#define CPU_EXCEPTION_INIT_DATA_REV 1 +#define CPU_EXCEPTION_INIT_DATA_REV 1 typedef union { struct { // // Revision number of this structure. // - UINT32 Revision; + UINT32 Revision; // // The address of top of known good stack reserved for *ALL* exceptions // listed in field StackSwitchExceptions. // - UINTN KnownGoodStackTop; + UINTN KnownGoodStackTop; // // The size of known good stack for *ONE* exception only. // - UINTN KnownGoodStackSize; + UINTN KnownGoodStackSize; // // Buffer of exception vector list for stack switch. // - UINT8 *StackSwitchExceptions; + UINT8 *StackSwitchExceptions; // // Number of exception vectors in StackSwitchExceptions. // - UINTN StackSwitchExceptionNumber; + UINTN StackSwitchExceptionNumber; // // Buffer of IDT table. It must be type of IA32_IDT_GATE_DESCRIPTOR. // Normally there's no need to change IDT table size. // - VOID *IdtTable; + VOID *IdtTable; // // Size of buffer for IdtTable. // - UINTN IdtTableSize; + UINTN IdtTableSize; // // Buffer of GDT table. It must be type of IA32_SEGMENT_DESCRIPTOR. // - VOID *GdtTable; + VOID *GdtTable; // // Size of buffer for GdtTable. // - UINTN GdtTableSize; + UINTN GdtTableSize; // // Pointer to start address of descriptor of exception task gate in the // GDT table. It must be type of IA32_TSS_DESCRIPTOR. // - VOID *ExceptionTssDesc; + VOID *ExceptionTssDesc; // // Size of buffer for ExceptionTssDesc. // - UINTN ExceptionTssDescSize; + UINTN ExceptionTssDescSize; // // Buffer of task-state segment for exceptions. It must be type of // IA32_TASK_STATE_SEGMENT. // - VOID *ExceptionTss; + VOID *ExceptionTss; // // Size of buffer for ExceptionTss. // - UINTN ExceptionTssSize; + UINTN ExceptionTssSize; // // Flag to indicate if default handlers should be initialized or not. // - BOOLEAN InitDefaultHandlers; + BOOLEAN InitDefaultHandlers; } Ia32, X64; } CPU_EXCEPTION_INIT_DATA; @@ -99,7 +99,7 @@ typedef union { EFI_STATUS EFIAPI InitializeCpuExceptionHandlers ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL ); /** @@ -128,8 +128,8 @@ InitializeCpuExceptionHandlers ( EFI_STATUS EFIAPI InitializeCpuExceptionHandlersEx ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL, - IN CPU_EXCEPTION_INIT_DATA *InitData OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL, + IN CPU_EXCEPTION_INIT_DATA *InitData OPTIONAL ); /** @@ -151,7 +151,7 @@ InitializeCpuExceptionHandlersEx ( EFI_STATUS EFIAPI InitializeCpuInterruptHandlers ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL ); /** @@ -180,8 +180,8 @@ InitializeCpuInterruptHandlers ( EFI_STATUS EFIAPI RegisterCpuInterruptHandler ( - IN EFI_EXCEPTION_TYPE InterruptType, - IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler ); /** @@ -193,8 +193,8 @@ RegisterCpuInterruptHandler ( VOID EFIAPI DumpCpuContext ( - IN EFI_EXCEPTION_TYPE ExceptionType, - IN EFI_SYSTEM_CONTEXT SystemContext + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext ); #endif diff --git a/MdeModulePkg/Include/Library/CustomizedDisplayLib.h b/MdeModulePkg/Include/Library/CustomizedDisplayLib.h index 8898350d6b..0607dd1a61 100644 --- a/MdeModulePkg/Include/Library/CustomizedDisplayLib.h +++ b/MdeModulePkg/Include/Library/CustomizedDisplayLib.h @@ -45,8 +45,8 @@ Statement EFI_STATUS EFIAPI DisplayPageFrame ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - OUT EFI_SCREEN_DESCRIPTOR *ScreenForStatement + IN FORM_DISPLAY_ENGINE_FORM *FormData, + OUT EFI_SCREEN_DESCRIPTOR *ScreenForStatement ); /** @@ -70,9 +70,9 @@ ClearDisplayPage ( VOID EFIAPI RefreshKeyHelp ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, - IN BOOLEAN Selected + IN FORM_DISPLAY_ENGINE_FORM *FormData, + IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, + IN BOOLEAN Selected ); /** @@ -87,8 +87,8 @@ RefreshKeyHelp ( VOID EFIAPI UpdateStatusBar ( - IN UINTN MessageType, - IN BOOLEAN State + IN UINTN MessageType, + IN BOOLEAN State ); /** @@ -147,12 +147,13 @@ FormExitPolicy ( UINT64 EFIAPI FormExitTimeout ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ); // // Print Functions // + /** Prints a unicode string to the default console, at the supplied cursor position, using L"%s" format. @@ -167,12 +168,11 @@ FormExitTimeout ( UINTN EFIAPI PrintStringAt ( - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *String + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *String ); - /** Prints a unicode string with the specified width to the default console, at the supplied cursor position, using L"%s" format. @@ -189,10 +189,10 @@ PrintStringAt ( UINTN EFIAPI PrintStringAtWithWidth ( - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *String, - IN UINTN Width + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *String, + IN UINTN Width ); /** @@ -209,9 +209,9 @@ PrintStringAtWithWidth ( UINTN EFIAPI PrintCharAt ( - IN UINTN Column, - IN UINTN Row, - CHAR16 Character + IN UINTN Column, + IN UINTN Row, + CHAR16 Character ); /** @@ -227,16 +227,17 @@ PrintCharAt ( VOID EFIAPI ClearLines ( - IN UINTN LeftColumn, - IN UINTN RightColumn, - IN UINTN TopRow, - IN UINTN BottomRow, - IN UINTN TextAttribute + IN UINTN LeftColumn, + IN UINTN RightColumn, + IN UINTN TopRow, + IN UINTN BottomRow, + IN UINTN TextAttribute ); // // Color Setting Functions // + /** Get OEM/Vendor specific popup attribute colors. diff --git a/MdeModulePkg/Include/Library/DebugAgentLib.h b/MdeModulePkg/Include/Library/DebugAgentLib.h index 262a156b76..f44bc5c563 100644 --- a/MdeModulePkg/Include/Library/DebugAgentLib.h +++ b/MdeModulePkg/Include/Library/DebugAgentLib.h @@ -9,25 +9,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __DEBUG_AGENT_LIB_H__ #define __DEBUG_AGENT_LIB_H__ -#define DEBUG_AGENT_INIT_PREMEM_SEC 1 -#define DEBUG_AGENT_INIT_POSTMEM_SEC 2 -#define DEBUG_AGENT_INIT_DXE_CORE 3 -#define DEBUG_AGENT_INIT_SMM 4 -#define DEBUG_AGENT_INIT_ENTER_SMI 5 -#define DEBUG_AGENT_INIT_EXIT_SMI 6 -#define DEBUG_AGENT_INIT_S3 7 -#define DEBUG_AGENT_INIT_DXE_AP 8 -#define DEBUG_AGENT_INIT_PEI 9 -#define DEBUG_AGENT_INIT_DXE_LOAD 10 -#define DEBUG_AGENT_INIT_DXE_UNLOAD 11 -#define DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64 12 +#define DEBUG_AGENT_INIT_PREMEM_SEC 1 +#define DEBUG_AGENT_INIT_POSTMEM_SEC 2 +#define DEBUG_AGENT_INIT_DXE_CORE 3 +#define DEBUG_AGENT_INIT_SMM 4 +#define DEBUG_AGENT_INIT_ENTER_SMI 5 +#define DEBUG_AGENT_INIT_EXIT_SMI 6 +#define DEBUG_AGENT_INIT_S3 7 +#define DEBUG_AGENT_INIT_DXE_AP 8 +#define DEBUG_AGENT_INIT_PEI 9 +#define DEBUG_AGENT_INIT_DXE_LOAD 10 +#define DEBUG_AGENT_INIT_DXE_UNLOAD 11 +#define DEBUG_AGENT_INIT_THUNK_PEI_IA32TOX64 12 // // Context for DEBUG_AGENT_INIT_POSTMEM_SEC // typedef struct { - UINTN HeapMigrateOffset; - UINTN StackMigrateOffset; + UINTN HeapMigrateOffset; + UINTN StackMigrateOffset; } DEBUG_AGENT_CONTEXT_POSTMEM_SEC; /** @@ -40,11 +40,10 @@ typedef struct { **/ typedef VOID -(EFIAPI * DEBUG_AGENT_CONTINUE)( +(EFIAPI *DEBUG_AGENT_CONTINUE)( IN VOID *Context ); - /** Initialize debug agent. @@ -91,7 +90,7 @@ InitializeDebugAgent ( BOOLEAN EFIAPI SaveAndSetDebugTimerInterrupt ( - IN BOOLEAN EnableStatus + IN BOOLEAN EnableStatus ); #endif diff --git a/MdeModulePkg/Include/Library/FmpAuthenticationLib.h b/MdeModulePkg/Include/Library/FmpAuthenticationLib.h index 480e6a101c..7b07b13984 100644 --- a/MdeModulePkg/Include/Library/FmpAuthenticationLib.h +++ b/MdeModulePkg/Include/Library/FmpAuthenticationLib.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __FMP_AUTHENTICATION_LIB_H__ #define __FMP_AUTHENTICATION_LIB_H__ @@ -57,4 +56,3 @@ AuthenticateFmpImage ( ); #endif - diff --git a/MdeModulePkg/Include/Library/HiiLib.h b/MdeModulePkg/Include/Library/HiiLib.h index 5d16358412..2439cd0472 100644 --- a/MdeModulePkg/Include/Library/HiiLib.h +++ b/MdeModulePkg/Include/Library/HiiLib.h @@ -71,7 +71,7 @@ HiiAddPackages ( VOID EFIAPI HiiRemovePackages ( - IN EFI_HII_HANDLE HiiHandle + IN EFI_HII_HANDLE HiiHandle ) ; @@ -269,10 +269,10 @@ HiiGetHiiHandles ( **/ EFI_STATUS EFIAPI -HiiGetFormSetFromHiiHandle( - IN EFI_HII_HANDLE Handle, - OUT EFI_IFR_FORM_SET **Buffer, - OUT UINTN *BufferSize +HiiGetFormSetFromHiiHandle ( + IN EFI_HII_HANDLE Handle, + OUT EFI_IFR_FORM_SET **Buffer, + OUT UINTN *BufferSize ); /** @@ -296,7 +296,7 @@ HiiGetFormSetFromHiiHandle( CHAR8 * EFIAPI HiiGetSupportedLanguages ( - IN EFI_HII_HANDLE HiiHandle + IN EFI_HII_HANDLE HiiHandle ) ; diff --git a/MdeModulePkg/Include/Library/IpmiLib.h b/MdeModulePkg/Include/Library/IpmiLib.h index 4b5c11bcfe..d3129d230b 100644 --- a/MdeModulePkg/Include/Library/IpmiLib.h +++ b/MdeModulePkg/Include/Library/IpmiLib.h @@ -12,7 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include - /** This service enables submitting commands via Ipmi. @@ -34,12 +33,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI IpmiSubmitCommand ( - IN UINT8 NetFunction, - IN UINT8 Command, - IN UINT8 *RequestData, - IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, - IN OUT UINT32 *ResponseDataSize + IN UINT8 NetFunction, + IN UINT8 Command, + IN UINT8 *RequestData, + IN UINT32 RequestDataSize, + OUT UINT8 *ResponseData, + IN OUT UINT32 *ResponseDataSize ); #endif diff --git a/MdeModulePkg/Include/Library/LockBoxLib.h b/MdeModulePkg/Include/Library/LockBoxLib.h index cab50da527..ab0eb942d3 100644 --- a/MdeModulePkg/Include/Library/LockBoxLib.h +++ b/MdeModulePkg/Include/Library/LockBoxLib.h @@ -29,9 +29,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent RETURN_STATUS EFIAPI SaveLockBox ( - IN GUID *Guid, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN VOID *Buffer, + IN UINTN Length ); /** @@ -50,22 +50,22 @@ SaveLockBox ( RETURN_STATUS EFIAPI SetLockBoxAttributes ( - IN GUID *Guid, - IN UINT64 Attributes + IN GUID *Guid, + IN UINT64 Attributes ); // // With this flag, this LockBox can be restored to this Buffer // with RestoreAllLockBoxInPlace() // -#define LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE BIT0 +#define LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE BIT0 // // With this flag, this LockBox can be restored in S3 resume only. // This LockBox can not be restored after SmmReadyToLock in normal boot // and after EndOfS3Resume in S3 resume. // It can not be set together with LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE. // -#define LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY BIT1 +#define LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY BIT1 /** This function will update confidential information to lockbox. @@ -89,10 +89,10 @@ SetLockBoxAttributes ( RETURN_STATUS EFIAPI UpdateLockBox ( - IN GUID *Guid, - IN UINTN Offset, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN UINTN Offset, + IN VOID *Buffer, + IN UINTN Length ); /** @@ -116,9 +116,9 @@ UpdateLockBox ( RETURN_STATUS EFIAPI RestoreLockBox ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ); /** diff --git a/MdeModulePkg/Include/Library/MemoryProfileLib.h b/MdeModulePkg/Include/Library/MemoryProfileLib.h index beb637e1a6..f87f245158 100644 --- a/MdeModulePkg/Include/Library/MemoryProfileLib.h +++ b/MdeModulePkg/Include/Library/MemoryProfileLib.h @@ -36,12 +36,12 @@ EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ); #endif diff --git a/MdeModulePkg/Include/Library/OemHookStatusCodeLib.h b/MdeModulePkg/Include/Library/OemHookStatusCodeLib.h index 9aeff52b81..c12f61f4f9 100644 --- a/MdeModulePkg/Include/Library/OemHookStatusCodeLib.h +++ b/MdeModulePkg/Include/Library/OemHookStatusCodeLib.h @@ -62,11 +62,11 @@ OemHookStatusCodeInitialize ( EFI_STATUS EFIAPI OemHookStatusCodeReport ( - IN EFI_STATUS_CODE_TYPE CodeType, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE CodeType, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ); #endif // __OEM_HOOK_STATUSCODE_LIB__ diff --git a/MdeModulePkg/Include/Library/PciHostBridgeLib.h b/MdeModulePkg/Include/Library/PciHostBridgeLib.h index 1606589354..54b5a14243 100644 --- a/MdeModulePkg/Include/Library/PciHostBridgeLib.h +++ b/MdeModulePkg/Include/Library/PciHostBridgeLib.h @@ -6,6 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __PCI_HOST_BRIDGE_LIB_H__ #define __PCI_HOST_BRIDGE_LIB_H__ @@ -17,8 +18,8 @@ typedef struct { // Base and Limit are the device address instead of host address when // Translation is not zero // - UINT64 Base; - UINT64 Limit; + UINT64 Base; + UINT64 Limit; // // According to UEFI 2.7, Device Address = Host Address + Translation, // so Translation = Device Address - Host Address. @@ -33,36 +34,36 @@ typedef struct { // situation and makes the current resource allocation code in generic PCI // host bridge driver still work. // - UINT64 Translation; + UINT64 Translation; } PCI_ROOT_BRIDGE_APERTURE; typedef struct { - UINT32 Segment; ///< Segment number. - UINT64 Supports; ///< Supported attributes. - ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() - ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. - UINT64 Attributes; ///< Initial attributes. - ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() - ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. - BOOLEAN DmaAbove4G; ///< DMA above 4GB memory. - ///< Set to TRUE when root bridge supports DMA above 4GB memory. - BOOLEAN NoExtendedConfigSpace; ///< When FALSE, the root bridge supports - ///< Extended (4096-byte) Configuration Space. - ///< When TRUE, the root bridge supports - ///< 256-byte Configuration Space only. - BOOLEAN ResourceAssigned; ///< Resource assignment status of the root bridge. - ///< Set to TRUE if Bus/IO/MMIO resources for root bridge have been assigned. - UINT64 AllocationAttributes; ///< Allocation attributes. - ///< Refer to EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM and - ///< EFI_PCI_HOST_BRIDGE_MEM64_DECODE used by GetAllocAttributes() - ///< in EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. - PCI_ROOT_BRIDGE_APERTURE Bus; ///< Bus aperture which can be used by the root bridge. - PCI_ROOT_BRIDGE_APERTURE Io; ///< IO aperture which can be used by the root bridge. - PCI_ROOT_BRIDGE_APERTURE Mem; ///< MMIO aperture below 4GB which can be used by the root bridge. - PCI_ROOT_BRIDGE_APERTURE MemAbove4G; ///< MMIO aperture above 4GB which can be used by the root bridge. - PCI_ROOT_BRIDGE_APERTURE PMem; ///< Prefetchable MMIO aperture below 4GB which can be used by the root bridge. - PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; ///< Prefetchable MMIO aperture above 4GB which can be used by the root bridge. - EFI_DEVICE_PATH_PROTOCOL *DevicePath; ///< Device path. + UINT32 Segment; ///< Segment number. + UINT64 Supports; ///< Supported attributes. + ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() + ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. + UINT64 Attributes; ///< Initial attributes. + ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() + ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. + BOOLEAN DmaAbove4G; ///< DMA above 4GB memory. + ///< Set to TRUE when root bridge supports DMA above 4GB memory. + BOOLEAN NoExtendedConfigSpace; ///< When FALSE, the root bridge supports + ///< Extended (4096-byte) Configuration Space. + ///< When TRUE, the root bridge supports + ///< 256-byte Configuration Space only. + BOOLEAN ResourceAssigned; ///< Resource assignment status of the root bridge. + ///< Set to TRUE if Bus/IO/MMIO resources for root bridge have been assigned. + UINT64 AllocationAttributes; ///< Allocation attributes. + ///< Refer to EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM and + ///< EFI_PCI_HOST_BRIDGE_MEM64_DECODE used by GetAllocAttributes() + ///< in EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. + PCI_ROOT_BRIDGE_APERTURE Bus; ///< Bus aperture which can be used by the root bridge. + PCI_ROOT_BRIDGE_APERTURE Io; ///< IO aperture which can be used by the root bridge. + PCI_ROOT_BRIDGE_APERTURE Mem; ///< MMIO aperture below 4GB which can be used by the root bridge. + PCI_ROOT_BRIDGE_APERTURE MemAbove4G; ///< MMIO aperture above 4GB which can be used by the root bridge. + PCI_ROOT_BRIDGE_APERTURE PMem; ///< Prefetchable MMIO aperture below 4GB which can be used by the root bridge. + PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; ///< Prefetchable MMIO aperture above 4GB which can be used by the root bridge. + EFI_DEVICE_PATH_PROTOCOL *DevicePath; ///< Device path. } PCI_ROOT_BRIDGE; /** @@ -77,7 +78,7 @@ typedef struct { PCI_ROOT_BRIDGE * EFIAPI PciHostBridgeGetRootBridges ( - UINTN *Count + UINTN *Count ); /** @@ -89,8 +90,8 @@ PciHostBridgeGetRootBridges ( VOID EFIAPI PciHostBridgeFreeRootBridges ( - PCI_ROOT_BRIDGE *Bridges, - UINTN Count + PCI_ROOT_BRIDGE *Bridges, + UINTN Count ); /** @@ -108,8 +109,8 @@ PciHostBridgeFreeRootBridges ( VOID EFIAPI PciHostBridgeResourceConflict ( - EFI_HANDLE HostBridgeHandle, - VOID *Configuration + EFI_HANDLE HostBridgeHandle, + VOID *Configuration ); #endif diff --git a/MdeModulePkg/Include/Library/PlatformBootManagerLib.h b/MdeModulePkg/Include/Library/PlatformBootManagerLib.h index 5d3062e9dd..9dd590c9e0 100644 --- a/MdeModulePkg/Include/Library/PlatformBootManagerLib.h +++ b/MdeModulePkg/Include/Library/PlatformBootManagerLib.h @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __PLATFORM_BOOT_MANAGER_LIB_H_ #define __PLATFORM_BOOT_MANAGER_LIB_H_ #include @@ -50,7 +49,7 @@ PlatformBootManagerAfterConsole ( VOID EFIAPI PlatformBootManagerWaitCallback ( - UINT16 TimeoutRemain + UINT16 TimeoutRemain ); /** diff --git a/MdeModulePkg/Include/Library/PlatformHookLib.h b/MdeModulePkg/Include/Library/PlatformHookLib.h index bc80355704..04cccd9bba 100644 --- a/MdeModulePkg/Include/Library/PlatformHookLib.h +++ b/MdeModulePkg/Include/Library/PlatformHookLib.h @@ -29,4 +29,3 @@ PlatformHookSerialPortInitialize ( ); #endif // __PLATFORM_HOOK_LIB__ - diff --git a/MdeModulePkg/Include/Library/PlatformVarCleanupLib.h b/MdeModulePkg/Include/Library/PlatformVarCleanupLib.h index bf0ad06be7..ac530ff867 100644 --- a/MdeModulePkg/Include/Library/PlatformVarCleanupLib.h +++ b/MdeModulePkg/Include/Library/PlatformVarCleanupLib.h @@ -48,9 +48,8 @@ GetLastBootVarErrorFlag ( EFI_STATUS EFIAPI PlatformVarCleanup ( - IN VAR_ERROR_FLAG Flag, - IN VAR_CLEANUP_TYPE Type + IN VAR_ERROR_FLAG Flag, + IN VAR_CLEANUP_TYPE Type ); #endif - diff --git a/MdeModulePkg/Include/Library/ResetSystemLib.h b/MdeModulePkg/Include/Library/ResetSystemLib.h index 09ee14540c..472a9355ea 100644 --- a/MdeModulePkg/Include/Library/ResetSystemLib.h +++ b/MdeModulePkg/Include/Library/ResetSystemLib.h @@ -65,8 +65,8 @@ ResetShutdown ( VOID EFIAPI ResetPlatformSpecific ( - IN UINTN DataSize, - IN VOID *ResetData + IN UINTN DataSize, + IN VOID *ResetData ); /** @@ -84,10 +84,10 @@ ResetPlatformSpecific ( VOID EFIAPI ResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ); #endif diff --git a/MdeModulePkg/Include/Library/ResetUtilityLib.h b/MdeModulePkg/Include/Library/ResetUtilityLib.h index 656703e782..27aca52490 100644 --- a/MdeModulePkg/Include/Library/ResetUtilityLib.h +++ b/MdeModulePkg/Include/Library/ResetUtilityLib.h @@ -7,6 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef _RESET_UTILITY_LIB_H_ #define _RESET_UTILITY_LIB_H_ @@ -32,8 +33,8 @@ VOID EFIAPI ResetSystemWithSubtype ( - IN EFI_RESET_TYPE ResetType, - IN CONST GUID *ResetSubtype + IN EFI_RESET_TYPE ResetType, + IN CONST GUID *ResetSubtype ); /** @@ -55,7 +56,7 @@ ResetSystemWithSubtype ( VOID EFIAPI ResetPlatformSpecificGuid ( - IN CONST GUID *ResetSubtype + IN CONST GUID *ResetSubtype ); /** @@ -119,12 +120,12 @@ GetResetPlatformSpecificGuid ( RETURN_STATUS EFIAPI BuildResetData ( - IN OUT UINTN *ResetDataSize, - IN OUT VOID *ResetData, - IN CONST GUID *ResetSubtype OPTIONAL, - IN CONST CHAR16 *ResetString OPTIONAL, - IN UINTN ExtraDataSize OPTIONAL, - IN CONST VOID *ExtraData OPTIONAL + IN OUT UINTN *ResetDataSize, + IN OUT VOID *ResetData, + IN CONST GUID *ResetSubtype OPTIONAL, + IN CONST CHAR16 *ResetString OPTIONAL, + IN UINTN ExtraDataSize OPTIONAL, + IN CONST VOID *ExtraData OPTIONAL ); #endif // _RESET_UTILITY_LIB_H_ diff --git a/MdeModulePkg/Include/Library/SecurityManagementLib.h b/MdeModulePkg/Include/Library/SecurityManagementLib.h index 8efe3117c7..e10a4cdd02 100644 --- a/MdeModulePkg/Include/Library/SecurityManagementLib.h +++ b/MdeModulePkg/Include/Library/SecurityManagementLib.h @@ -14,11 +14,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Authentication Operation defintions for User Identity (UID), Measured and Secure boot. // -#define EFI_AUTH_OPERATION_NONE 0x00 -#define EFI_AUTH_OPERATION_VERIFY_IMAGE 0x01 -#define EFI_AUTH_OPERATION_DEFER_IMAGE_LOAD 0x02 -#define EFI_AUTH_OPERATION_MEASURE_IMAGE 0x04 -#define EFI_AUTH_OPERATION_CONNECT_POLICY 0x08 +#define EFI_AUTH_OPERATION_NONE 0x00 +#define EFI_AUTH_OPERATION_VERIFY_IMAGE 0x01 +#define EFI_AUTH_OPERATION_DEFER_IMAGE_LOAD 0x02 +#define EFI_AUTH_OPERATION_MEASURE_IMAGE 0x04 +#define EFI_AUTH_OPERATION_CONNECT_POLICY 0x08 // // Authentication State Operation will check the authentication status of a file. // @@ -27,7 +27,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Image buffer is required by the security handler. /// -#define EFI_AUTH_OPERATION_IMAGE_REQUIRED 0x80000000 +#define EFI_AUTH_OPERATION_IMAGE_REQUIRED 0x80000000 /** The security handler is used to abstract platform-specific policy @@ -141,8 +141,8 @@ RegisterSecurityHandler ( EFI_STATUS EFIAPI ExecuteSecurityHandlers ( - IN UINT32 AuthenticationStatus, - IN CONST EFI_DEVICE_PATH_PROTOCOL *FilePath + IN UINT32 AuthenticationStatus, + IN CONST EFI_DEVICE_PATH_PROTOCOL *FilePath ); /** @@ -184,7 +184,7 @@ ExecuteSecurityHandlers ( **/ typedef EFI_STATUS -(EFIAPI *SECURITY2_FILE_AUTHENTICATION_HANDLER) ( +(EFIAPI *SECURITY2_FILE_AUTHENTICATION_HANDLER)( IN UINT32 AuthenticationStatus, IN CONST EFI_DEVICE_PATH_PROTOCOL *File, IN VOID *FileBuffer, @@ -210,8 +210,8 @@ EFI_STATUS EFI_STATUS EFIAPI RegisterSecurity2Handler ( - IN SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler, - IN UINT32 AuthenticationOperation + IN SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler, + IN UINT32 AuthenticationOperation ); /** @@ -259,12 +259,12 @@ RegisterSecurity2Handler ( EFI_STATUS EFIAPI ExecuteSecurity2Handlers ( - IN UINT32 AuthenticationOperation, - IN UINT32 AuthenticationStatus, - IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL, - IN VOID *FileBuffer, - IN UINTN FileSize, - IN BOOLEAN BootPolicy + IN UINT32 AuthenticationOperation, + IN UINT32 AuthenticationStatus, + IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL, + IN VOID *FileBuffer, + IN UINTN FileSize, + IN BOOLEAN BootPolicy ); #endif diff --git a/MdeModulePkg/Include/Library/SmmCorePlatformHookLib.h b/MdeModulePkg/Include/Library/SmmCorePlatformHookLib.h index ca4180aa26..6a76c1de39 100644 --- a/MdeModulePkg/Include/Library/SmmCorePlatformHookLib.h +++ b/MdeModulePkg/Include/Library/SmmCorePlatformHookLib.h @@ -25,7 +25,6 @@ PlatformHookBeforeSmmDispatch ( VOID ); - /** Performs platform specific tasks after invoking registered SMI handlers. diff --git a/MdeModulePkg/Include/Library/SortLib.h b/MdeModulePkg/Include/Library/SortLib.h index 70789709a7..8d5045fc7f 100644 --- a/MdeModulePkg/Include/Library/SortLib.h +++ b/MdeModulePkg/Include/Library/SortLib.h @@ -5,6 +5,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __SORT_LIB_H__ #define __SORT_LIB_H__ @@ -46,13 +47,12 @@ INTN VOID EFIAPI PerformQuickSort ( - IN OUT VOID *BufferToSort, - IN CONST UINTN Count, - IN CONST UINTN ElementSize, - IN SORT_COMPARE CompareFunction + IN OUT VOID *BufferToSort, + IN CONST UINTN Count, + IN CONST UINTN ElementSize, + IN SORT_COMPARE CompareFunction ); - /** Function to compare 2 device paths for use as CompareFunction. @@ -66,8 +66,8 @@ PerformQuickSort ( INTN EFIAPI DevicePathCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ); /** @@ -83,8 +83,8 @@ DevicePathCompare ( INTN EFIAPI StringNoCaseCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ); /** @@ -100,8 +100,8 @@ StringNoCaseCompare ( INTN EFIAPI StringCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ); #endif //__SORT_LIB_H__ diff --git a/MdeModulePkg/Include/Library/TpmMeasurementLib.h b/MdeModulePkg/Include/Library/TpmMeasurementLib.h index ddf6723f03..a38072b5bd 100644 --- a/MdeModulePkg/Include/Library/TpmMeasurementLib.h +++ b/MdeModulePkg/Include/Library/TpmMeasurementLib.h @@ -27,12 +27,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI TpmMeasureAndLogData ( - IN UINT32 PcrIndex, - IN UINT32 EventType, - IN VOID *EventLog, - IN UINT32 LogLen, - IN VOID *HashData, - IN UINT64 HashDataLen + IN UINT32 PcrIndex, + IN UINT32 EventType, + IN VOID *EventLog, + IN UINT32 LogLen, + IN VOID *HashData, + IN UINT64 HashDataLen ); #endif diff --git a/MdeModulePkg/Include/Library/UefiBootManagerLib.h b/MdeModulePkg/Include/Library/UefiBootManagerLib.h index 41a4c2b498..34e217707e 100644 --- a/MdeModulePkg/Include/Library/UefiBootManagerLib.h +++ b/MdeModulePkg/Include/Library/UefiBootManagerLib.h @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _UEFI_BOOT_MANAGER_LIB_H_ #define _UEFI_BOOT_MANAGER_LIB_H_ @@ -30,7 +29,7 @@ typedef enum { } EFI_BOOT_MANAGER_LOAD_OPTION_TYPE; typedef enum { - LoadOptionNumberMax = 0x10000, + LoadOptionNumberMax = 0x10000, LoadOptionNumberUnassigned = LoadOptionNumberMax } EFI_BOOT_MANAGER_LOAD_OPTION_NUMBER; @@ -41,21 +40,21 @@ typedef struct { // // Data read from UEFI NV variables // - UINTN OptionNumber; // #### numerical value, could be LoadOptionNumberUnassigned - EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; // LoadOptionTypeBoot or LoadOptionTypeDriver - UINT32 Attributes; // Load Option Attributes - CHAR16 *Description; // Load Option Description - EFI_DEVICE_PATH_PROTOCOL *FilePath; // Load Option Device Path - UINT8 *OptionalData; // Load Option optional data to pass into image - UINT32 OptionalDataSize; // Load Option size of OptionalData - EFI_GUID VendorGuid; + UINTN OptionNumber; // #### numerical value, could be LoadOptionNumberUnassigned + EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; // LoadOptionTypeBoot or LoadOptionTypeDriver + UINT32 Attributes; // Load Option Attributes + CHAR16 *Description; // Load Option Description + EFI_DEVICE_PATH_PROTOCOL *FilePath; // Load Option Device Path + UINT8 *OptionalData; // Load Option optional data to pass into image + UINT32 OptionalDataSize; // Load Option size of OptionalData + EFI_GUID VendorGuid; // // Used at runtime // - EFI_STATUS Status; // Status returned from boot attempt gBS->StartImage () - CHAR16 *ExitData; // Exit data returned from gBS->StartImage () - UINTN ExitDataSize; // Size of ExitData + EFI_STATUS Status; // Status returned from boot attempt gBS->StartImage () + CHAR16 *ExitData; // Exit data returned from gBS->StartImage () + UINTN ExitDataSize; // Size of ExitData } EFI_BOOT_MANAGER_LOAD_OPTION; /** @@ -73,8 +72,8 @@ typedef struct { EFI_BOOT_MANAGER_LOAD_OPTION * EFIAPI EfiBootManagerGetLoadOptions ( - OUT UINTN *LoadOptionCount, - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType + OUT UINTN *LoadOptionCount, + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType ); /** @@ -111,14 +110,14 @@ EfiBootManagerFreeLoadOptions ( EFI_STATUS EFIAPI EfiBootManagerInitializeLoadOption ( - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, - IN UINTN OptionNumber, - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, - IN UINT32 Attributes, - IN CHAR16 *Description, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN UINT8 *OptionalData, - IN UINT32 OptionalDataSize + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, + IN UINTN OptionNumber, + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, + IN UINT32 Attributes, + IN CHAR16 *Description, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN UINT8 *OptionalData, + IN UINT32 OptionalDataSize ); /** @@ -151,8 +150,8 @@ EfiBootManagerFreeLoadOption ( EFI_STATUS EFIAPI EfiBootManagerVariableToLoadOption ( - IN CHAR16 *VariableName, - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption + IN CHAR16 *VariableName, + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption ); /** @@ -166,7 +165,7 @@ EfiBootManagerVariableToLoadOption ( EFI_STATUS EFIAPI EfiBootManagerLoadOptionToVariable ( - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption ); /** @@ -192,8 +191,8 @@ EfiBootManagerLoadOptionToVariable ( EFI_STATUS EFIAPI EfiBootManagerAddLoadOptionVariable ( - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, - IN UINTN Position + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, + IN UINTN Position ); /** @@ -224,8 +223,8 @@ EfiBootManagerDeleteLoadOptionVariable ( VOID EFIAPI EfiBootManagerSortLoadOptionVariable ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, - IN SORT_COMPARE CompareFunction + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, + IN SORT_COMPARE CompareFunction ); /** @@ -244,9 +243,9 @@ EfiBootManagerSortLoadOptionVariable ( INTN EFIAPI EfiBootManagerFindLoadOption ( - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, - IN UINTN Count + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, + IN UINTN Count ); // @@ -261,25 +260,25 @@ typedef struct { /// /// Specifies options about how the key will be processed. /// - EFI_BOOT_KEY_DATA KeyData; + EFI_BOOT_KEY_DATA KeyData; /// /// The CRC-32 which should match the CRC-32 of the entire EFI_LOAD_OPTION to /// which BootOption refers. If the CRC-32s do not match this value, then this key /// option is ignored. /// - UINT32 BootOptionCrc; + UINT32 BootOptionCrc; /// /// The Boot#### option which will be invoked if this key is pressed and the boot option /// is active (LOAD_OPTION_ACTIVE is set). /// - UINT16 BootOption; + UINT16 BootOption; /// /// The key codes to compare against those returned by the /// EFI_SIMPLE_TEXT_INPUT and EFI_SIMPLE_TEXT_INPUT_EX protocols. /// The number of key codes (0-3) is specified by the EFI_KEY_CODE_COUNT field in KeyOptions. /// - EFI_INPUT_KEY Keys[3]; - UINT16 OptionNumber; + EFI_INPUT_KEY Keys[3]; + UINT16 OptionNumber; } EFI_BOOT_MANAGER_KEY_OPTION; #pragma pack() @@ -294,18 +293,18 @@ typedef struct { EFI_STATUS EFIAPI EfiBootManagerStartHotkeyService ( - IN EFI_EVENT *HotkeyTriggered + IN EFI_EVENT *HotkeyTriggered ); // // Modifier for EfiBootManagerAddKeyOptionVariable and EfiBootManagerDeleteKeyOptionVariable // -#define EFI_BOOT_MANAGER_SHIFT_PRESSED 0x00000001 -#define EFI_BOOT_MANAGER_CONTROL_PRESSED 0x00000002 -#define EFI_BOOT_MANAGER_ALT_PRESSED 0x00000004 -#define EFI_BOOT_MANAGER_LOGO_PRESSED 0x00000008 -#define EFI_BOOT_MANAGER_MENU_KEY_PRESSED 0x00000010 -#define EFI_BOOT_MANAGER_SYS_REQ_PRESSED 0x00000020 +#define EFI_BOOT_MANAGER_SHIFT_PRESSED 0x00000001 +#define EFI_BOOT_MANAGER_CONTROL_PRESSED 0x00000002 +#define EFI_BOOT_MANAGER_ALT_PRESSED 0x00000004 +#define EFI_BOOT_MANAGER_LOGO_PRESSED 0x00000008 +#define EFI_BOOT_MANAGER_MENU_KEY_PRESSED 0x00000010 +#define EFI_BOOT_MANAGER_SYS_REQ_PRESSED 0x00000020 /** Add the key option. @@ -322,9 +321,9 @@ EfiBootManagerStartHotkeyService ( EFI_STATUS EFIAPI EfiBootManagerAddKeyOptionVariable ( - OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption OPTIONAL, - IN UINT16 BootOptionNumber, - IN UINT32 Modifier, + OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption OPTIONAL, + IN UINT16 BootOptionNumber, + IN UINT32 Modifier, ... ); @@ -341,8 +340,8 @@ EfiBootManagerAddKeyOptionVariable ( EFI_STATUS EFIAPI EfiBootManagerDeleteKeyOptionVariable ( - IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption OPTIONAL, - IN UINT32 Modifier, + IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption OPTIONAL, + IN UINT32 Modifier, ... ); @@ -360,7 +359,7 @@ EfiBootManagerDeleteKeyOptionVariable ( EFI_STATUS EFIAPI EfiBootManagerRegisterContinueKeyOption ( - IN UINT32 Modifier, + IN UINT32 Modifier, ... ); @@ -372,6 +371,7 @@ EFIAPI EfiBootManagerHotkeyBoot ( VOID ); + // // Boot Manager boot library functions. // @@ -436,7 +436,7 @@ EfiBootManagerBoot ( EFI_STATUS EFIAPI EfiBootManagerGetBootManagerMenu ( - EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ); /** @@ -456,8 +456,8 @@ EfiBootManagerGetBootManagerMenu ( EFI_DEVICE_PATH_PROTOCOL * EFIAPI EfiBootManagerGetNextLoadOptionDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ); /** @@ -475,9 +475,9 @@ EfiBootManagerGetNextLoadOptionDevicePath ( VOID * EFIAPI EfiBootManagerGetLoadOptionBuffer ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, - OUT UINTN *FileSize + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, + OUT UINTN *FileSize ); /** @@ -486,7 +486,7 @@ EfiBootManagerGetLoadOptionBuffer ( **/ typedef VOID -(EFIAPI *EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION) ( +(EFIAPI *EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION)( VOID ); @@ -495,7 +495,7 @@ VOID **/ typedef VOID -(EFIAPI *EFI_BOOT_MANAGER_LEGACY_BOOT) ( +(EFIAPI *EFI_BOOT_MANAGER_LEGACY_BOOT)( IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ); @@ -508,8 +508,8 @@ VOID VOID EFIAPI EfiBootManagerRegisterLegacyBootSupport ( - EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption, - EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot + EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption, + EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot ); /** @@ -523,7 +523,7 @@ EfiBootManagerRegisterLegacyBootSupport ( **/ typedef CHAR16 * -(EFIAPI *EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER) ( +(EFIAPI *EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER)( IN EFI_HANDLE Handle, IN CONST CHAR16 *DefaultDescription ); @@ -597,7 +597,6 @@ EfiBootManagerDisconnectAll ( VOID ); - // // Boot Manager console library functions // @@ -666,7 +665,7 @@ EfiBootManagerUpdateConsoleVariable ( EFI_STATUS EFIAPI EfiBootManagerConnectConsoleVariable ( - IN CONSOLE_TYPE ConsoleType + IN CONSOLE_TYPE ConsoleType ); /** @@ -680,7 +679,7 @@ EfiBootManagerConnectConsoleVariable ( EFI_DEVICE_PATH_PROTOCOL * EFIAPI EfiBootManagerGetGopDevicePath ( - IN EFI_HANDLE VideoController + IN EFI_HANDLE VideoController ); /** @@ -694,7 +693,7 @@ EfiBootManagerGetGopDevicePath ( EFI_STATUS EFIAPI EfiBootManagerConnectVideoController ( - EFI_HANDLE VideoController OPTIONAL + EFI_HANDLE VideoController OPTIONAL ); // @@ -702,29 +701,29 @@ EfiBootManagerConnectVideoController ( // typedef struct { - EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth; + EFI_DRIVER_HEALTH_PROTOCOL *DriverHealth; /// /// Driver relative handles /// - EFI_HANDLE DriverHealthHandle; - EFI_HANDLE ControllerHandle; - EFI_HANDLE ChildHandle; + EFI_HANDLE DriverHealthHandle; + EFI_HANDLE ControllerHandle; + EFI_HANDLE ChildHandle; /// /// Driver health messages of the specify Driver /// - EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList; + EFI_DRIVER_HEALTH_HII_MESSAGE *MessageList; /// /// HII relative handles /// - EFI_HII_HANDLE HiiHandle; + EFI_HII_HANDLE HiiHandle; /// /// Driver Health status /// - EFI_DRIVER_HEALTH_STATUS HealthStatus; + EFI_DRIVER_HEALTH_STATUS HealthStatus; } EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO; /** @@ -746,7 +745,7 @@ typedef struct { EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO * EFIAPI EfiBootManagerGetDriverHealthInfo ( - UINTN *Count + UINTN *Count ); /** @@ -778,7 +777,7 @@ EfiBootManagerFreeDriverHealthInfo ( EFI_STATUS EFIAPI EfiBootManagerProcessLoadOption ( - EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption + EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption ); /** @@ -796,12 +795,11 @@ EfiBootManagerProcessLoadOption ( BOOLEAN EFIAPI EfiBootManagerIsValidLoadOptionVariableName ( - IN CHAR16 *VariableName, - OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL, - OUT UINT16 *OptionNumber OPTIONAL + IN CHAR16 *VariableName, + OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL, + OUT UINT16 *OptionNumber OPTIONAL ); - /** Dispatch the deferred images that are returned from all DeferredImageLoad instances. @@ -814,4 +812,5 @@ EFIAPI EfiBootManagerDispatchDeferredImages ( VOID ); + #endif diff --git a/MdeModulePkg/Include/Library/VarCheckLib.h b/MdeModulePkg/Include/Library/VarCheckLib.h index b2b296506c..155fcd0223 100644 --- a/MdeModulePkg/Include/Library/VarCheckLib.h +++ b/MdeModulePkg/Include/Library/VarCheckLib.h @@ -14,13 +14,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent typedef enum { VarCheckRequestReserved0 = 0, VarCheckRequestReserved1 = 1, - VarCheckFromTrusted = 2, - VarCheckFromUntrusted = 3, + VarCheckFromTrusted = 2, + VarCheckFromUntrusted = 3, } VAR_CHECK_REQUEST_SOURCE; typedef VOID -(EFIAPI *VAR_CHECK_END_OF_DXE_CALLBACK) ( +(EFIAPI *VAR_CHECK_END_OF_DXE_CALLBACK)( VOID ); @@ -58,7 +58,7 @@ VarCheckLibRegisterEndOfDxeCallback ( VOID *** EFIAPI VarCheckLibInitializeAtEndOfDxe ( - IN OUT UINTN *AddressPointerCount OPTIONAL + IN OUT UINTN *AddressPointerCount OPTIONAL ); /** @@ -77,7 +77,7 @@ VarCheckLibInitializeAtEndOfDxe ( EFI_STATUS EFIAPI VarCheckLibRegisterAddressPointer ( - IN VOID **AddressPointer + IN VOID **AddressPointer ); /** @@ -97,7 +97,7 @@ VarCheckLibRegisterAddressPointer ( EFI_STATUS EFIAPI VarCheckLibRegisterSetVariableCheckHandler ( - IN VAR_CHECK_SET_VARIABLE_CHECK_HANDLER Handler + IN VAR_CHECK_SET_VARIABLE_CHECK_HANDLER Handler ); /** @@ -118,9 +118,9 @@ VarCheckLibRegisterSetVariableCheckHandler ( EFI_STATUS EFIAPI VarCheckLibVariablePropertySet ( - IN CHAR16 *Name, - IN EFI_GUID *Guid, - IN VAR_CHECK_VARIABLE_PROPERTY *VariableProperty + IN CHAR16 *Name, + IN EFI_GUID *Guid, + IN VAR_CHECK_VARIABLE_PROPERTY *VariableProperty ); /** @@ -138,9 +138,9 @@ VarCheckLibVariablePropertySet ( EFI_STATUS EFIAPI VarCheckLibVariablePropertyGet ( - IN CHAR16 *Name, - IN EFI_GUID *Guid, - OUT VAR_CHECK_VARIABLE_PROPERTY *VariableProperty + IN CHAR16 *Name, + IN EFI_GUID *Guid, + OUT VAR_CHECK_VARIABLE_PROPERTY *VariableProperty ); /** @@ -163,12 +163,12 @@ VarCheckLibVariablePropertyGet ( EFI_STATUS EFIAPI VarCheckLibSetVariableCheck ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN UINT32 Attributes, - IN UINTN DataSize, - IN VOID *Data, - IN VAR_CHECK_REQUEST_SOURCE RequestSource + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINT32 Attributes, + IN UINTN DataSize, + IN VOID *Data, + IN VAR_CHECK_REQUEST_SOURCE RequestSource ); #endif diff --git a/MdeModulePkg/Include/Library/VariablePolicyHelperLib.h b/MdeModulePkg/Include/Library/VariablePolicyHelperLib.h index 3b75e97860..e471ed78f3 100644 --- a/MdeModulePkg/Include/Library/VariablePolicyHelperLib.h +++ b/MdeModulePkg/Include/Library/VariablePolicyHelperLib.h @@ -40,17 +40,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI CreateBasicVariablePolicy ( - IN CONST EFI_GUID *Namespace, - IN CONST CHAR16 *Name OPTIONAL, - IN UINT32 MinSize, - IN UINT32 MaxSize, - IN UINT32 AttributesMustHave, - IN UINT32 AttributesCantHave, - IN UINT8 LockPolicyType, - OUT VARIABLE_POLICY_ENTRY **NewEntry + IN CONST EFI_GUID *Namespace, + IN CONST CHAR16 *Name OPTIONAL, + IN UINT32 MinSize, + IN UINT32 MaxSize, + IN UINT32 AttributesMustHave, + IN UINT32 AttributesCantHave, + IN UINT8 LockPolicyType, + OUT VARIABLE_POLICY_ENTRY **NewEntry ); - /** This helper function will allocate and populate a new VariablePolicy structure for a policy with a lock type of VARIABLE_POLICY_TYPE_LOCK_ON_VAR_STATE. @@ -79,19 +78,18 @@ CreateBasicVariablePolicy ( EFI_STATUS EFIAPI CreateVarStateVariablePolicy ( - IN CONST EFI_GUID *Namespace, - IN CONST CHAR16 *Name OPTIONAL, - IN UINT32 MinSize, - IN UINT32 MaxSize, - IN UINT32 AttributesMustHave, - IN UINT32 AttributesCantHave, - IN CONST EFI_GUID *VarStateNamespace, - IN UINT8 VarStateValue, - IN CONST CHAR16 *VarStateName, - OUT VARIABLE_POLICY_ENTRY **NewEntry + IN CONST EFI_GUID *Namespace, + IN CONST CHAR16 *Name OPTIONAL, + IN UINT32 MinSize, + IN UINT32 MaxSize, + IN UINT32 AttributesMustHave, + IN UINT32 AttributesCantHave, + IN CONST EFI_GUID *VarStateNamespace, + IN UINT8 VarStateValue, + IN CONST CHAR16 *VarStateName, + OUT VARIABLE_POLICY_ENTRY **NewEntry ); - /** This helper function does everything that CreateBasicVariablePolicy() does, but also uses the passed in protocol to register the policy with the infrastructure. @@ -124,7 +122,6 @@ RegisterBasicVariablePolicy ( IN UINT8 LockPolicyType ); - /** This helper function does everything that CreateBasicVariablePolicy() does, but also uses the passed in protocol to register the policy with the infrastructure. diff --git a/MdeModulePkg/Include/Library/VariablePolicyLib.h b/MdeModulePkg/Include/Library/VariablePolicyLib.h index efd1840112..63c49fbca1 100644 --- a/MdeModulePkg/Include/Library/VariablePolicyLib.h +++ b/MdeModulePkg/Include/Library/VariablePolicyLib.h @@ -30,10 +30,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI RegisterVariablePolicy ( - IN CONST VARIABLE_POLICY_ENTRY *NewPolicy + IN CONST VARIABLE_POLICY_ENTRY *NewPolicy ); - /** This API function checks to see whether the parameters to SetVariable would be allowed according to the current variable policies. @@ -56,14 +55,13 @@ RegisterVariablePolicy ( EFI_STATUS EFIAPI ValidateSetVariable ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN UINT32 Attributes, - IN UINTN DataSize, - IN VOID *Data + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINT32 Attributes, + IN UINTN DataSize, + IN VOID *Data ); - /** This API function disables the variable policy enforcement. If it's already been called once, will return EFI_ALREADY_STARTED. @@ -81,7 +79,6 @@ DisableVariablePolicy ( VOID ); - /** This API function will dump the entire contents of the variable policy table. @@ -101,11 +98,10 @@ DisableVariablePolicy ( EFI_STATUS EFIAPI DumpVariablePolicy ( - OUT UINT8 *Policy, - IN OUT UINT32 *Size + OUT UINT8 *Policy, + IN OUT UINT32 *Size ); - /** This API function returns whether or not the policy engine is currently being enforced. @@ -121,7 +117,6 @@ IsVariablePolicyEnabled ( VOID ); - /** This API function locks the interface so that no more policy updates can be performed or changes made to the enforcement until the next boot. @@ -136,7 +131,6 @@ LockVariablePolicy ( VOID ); - /** This API function returns whether or not the policy interface is locked for the remainder of the boot. @@ -152,7 +146,6 @@ IsVariablePolicyInterfaceLocked ( VOID ); - /** This helper function initializes the library and sets up any required internal structures or handlers. @@ -170,10 +163,9 @@ IsVariablePolicyInterfaceLocked ( EFI_STATUS EFIAPI InitVariablePolicyLib ( - IN EFI_GET_VARIABLE GetVariableHelper + IN EFI_GET_VARIABLE GetVariableHelper ); - /** This helper function returns whether or not the library is currently initialized. @@ -187,7 +179,6 @@ IsVariablePolicyLibInitialized ( VOID ); - /** This helper function tears down the library. @@ -203,5 +194,4 @@ DeinitVariablePolicyLib ( VOID ); - #endif // _VARIABLE_POLICY_LIB_H_ diff --git a/MdeModulePkg/Include/Ppi/AtaAhciController.h b/MdeModulePkg/Include/Ppi/AtaAhciController.h index 07a2c8c28c..896659027a 100644 --- a/MdeModulePkg/Include/Ppi/AtaAhciController.h +++ b/MdeModulePkg/Include/Ppi/AtaAhciController.h @@ -21,7 +21,7 @@ // // Forward declaration for the EDKII_ATA_AHCI_HOST_CONTROLLER_PPI. // -typedef struct _EDKII_ATA_AHCI_HOST_CONTROLLER_PPI EDKII_ATA_AHCI_HOST_CONTROLLER_PPI; +typedef struct _EDKII_ATA_AHCI_HOST_CONTROLLER_PPI EDKII_ATA_AHCI_HOST_CONTROLLER_PPI; /** Get the MMIO base address of ATA AHCI host controller. @@ -37,7 +37,7 @@ typedef struct _EDKII_ATA_AHCI_HOST_CONTROLLER_PPI EDKII_ATA_AHCI_HOST_CONTROLL **/ typedef EFI_STATUS -(EFIAPI *EDKII_ATA_AHCI_HC_GET_MMIO_BAR) ( +(EFIAPI *EDKII_ATA_AHCI_HC_GET_MMIO_BAR)( IN EDKII_ATA_AHCI_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, OUT UINTN *MmioBar @@ -63,7 +63,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_ATA_AHCI_HC_GET_DEVICE_PATH) ( +(EFIAPI *EDKII_ATA_AHCI_HC_GET_DEVICE_PATH)( IN EDKII_ATA_AHCI_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, OUT UINTN *DevicePathLength, @@ -78,6 +78,6 @@ struct _EDKII_ATA_AHCI_HOST_CONTROLLER_PPI { EDKII_ATA_AHCI_HC_GET_DEVICE_PATH GetAhciHcDevicePath; }; -extern EFI_GUID gEdkiiPeiAtaAhciHostControllerPpiGuid; +extern EFI_GUID gEdkiiPeiAtaAhciHostControllerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/AtaController.h b/MdeModulePkg/Include/Ppi/AtaController.h index 2c17f31c3b..0096f7bae0 100644 --- a/MdeModulePkg/Include/Ppi/AtaController.h +++ b/MdeModulePkg/Include/Ppi/AtaController.h @@ -30,7 +30,7 @@ typedef struct _PEI_ATA_CONTROLLER_PPI PEI_ATA_CONTROLLER_PPI; /// This is designed for old generation chipset with PATA/SATA controllers. /// It may be ignored in PPI implementation for new generation chipset without PATA controller. /// -#define PEI_ICH_IDE_NONE 0x00 +#define PEI_ICH_IDE_NONE 0x00 /// /// This bit is used in the ChannelMask parameter of EnableAtaChannel() to @@ -38,7 +38,7 @@ typedef struct _PEI_ATA_CONTROLLER_PPI PEI_ATA_CONTROLLER_PPI; /// This is designed for old generation chipset with PATA/SATA controllers. /// It may be ignored in PPI implementation for new generation chipset without PATA controller. /// -#define PEI_ICH_IDE_PRIMARY 0x01 +#define PEI_ICH_IDE_PRIMARY 0x01 /// /// This bit is used in the ChannelMask parameter of EnableAtaChannel() to @@ -46,7 +46,7 @@ typedef struct _PEI_ATA_CONTROLLER_PPI PEI_ATA_CONTROLLER_PPI; /// This is designed for old generation chipset with PATA/SATA controllers. /// It may be ignored in PPI implementation for new generation chipset without PATA controller. /// -#define PEI_ICH_IDE_SECONDARY 0x02 +#define PEI_ICH_IDE_SECONDARY 0x02 /// /// This bit is used in the ChannelMask parameter of EnableAtaChannel() to @@ -54,7 +54,7 @@ typedef struct _PEI_ATA_CONTROLLER_PPI PEI_ATA_CONTROLLER_PPI; /// This is designed for old generation chipset with PATA/SATA controllers. /// It may be ignored in PPI implementation for new generation chipset without PATA controller. /// -#define PEI_ICH_SATA_NONE 0x04 +#define PEI_ICH_SATA_NONE 0x04 /// /// This bit is used in the ChannelMask parameter of EnableAtaChannel() to @@ -62,7 +62,7 @@ typedef struct _PEI_ATA_CONTROLLER_PPI PEI_ATA_CONTROLLER_PPI; /// This is designed for old generation chipset with PATA/SATA controllers. /// It may be ignored in PPI implementation for new generation chipset without PATA controller. /// -#define PEI_ICH_SATA_PRIMARY 0x08 +#define PEI_ICH_SATA_PRIMARY 0x08 /// /// This bit is used in the ChannelMask parameter of EnableAtaChannel() to @@ -79,11 +79,11 @@ typedef struct { /// /// Base I/O port address of the IDE controller's command block /// - UINT16 CommandBlockBaseAddr; + UINT16 CommandBlockBaseAddr; /// /// Base I/O port address of the IDE controller's control block /// - UINT16 ControlBlockBaseAddr; + UINT16 ControlBlockBaseAddr; } IDE_REGS_BASE_ADDR; /** @@ -144,12 +144,10 @@ UINT32 /// retrieves the base I/O port addresses to the enabled IDE and SATA channels. /// struct _PEI_ATA_CONTROLLER_PPI { - PEI_ENABLE_ATA EnableAtaChannel; - GET_IDE_REGS_BASE_ADDR GetIdeRegsBaseAddr; + PEI_ENABLE_ATA EnableAtaChannel; + GET_IDE_REGS_BASE_ADDR GetIdeRegsBaseAddr; }; -extern EFI_GUID gPeiAtaControllerPpiGuid; +extern EFI_GUID gPeiAtaControllerPpiGuid; #endif - - diff --git a/MdeModulePkg/Include/Ppi/AtaPassThru.h b/MdeModulePkg/Include/Ppi/AtaPassThru.h index f8ebe56df2..73fb688c8a 100644 --- a/MdeModulePkg/Include/Ppi/AtaPassThru.h +++ b/MdeModulePkg/Include/Ppi/AtaPassThru.h @@ -22,15 +22,14 @@ // // Forward declaration for the EDKII_PEI_ATA_PASS_THRU_PPI. // -typedef struct _EDKII_PEI_ATA_PASS_THRU_PPI EDKII_PEI_ATA_PASS_THRU_PPI; +typedef struct _EDKII_PEI_ATA_PASS_THRU_PPI EDKII_PEI_ATA_PASS_THRU_PPI; // // Revision The revision to which the ATA Pass Thru PPI interface adheres. // All future revisions must be backwards compatible. // If a future version is not back wards compatible it is not the same GUID. // -#define EDKII_PEI_ATA_PASS_THRU_PPI_REVISION 0x00010000 - +#define EDKII_PEI_ATA_PASS_THRU_PPI_REVISION 0x00010000 /** Sends an ATA command to an ATA device that is attached to the ATA controller. @@ -69,7 +68,7 @@ typedef struct _EDKII_PEI_ATA_PASS_THRU_PPI EDKII_PEI_ATA_PASS_THRU_PPI; **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_ATA_PASS_THRU_PASSTHRU) ( +(EFIAPI *EDKII_PEI_ATA_PASS_THRU_PASSTHRU)( IN EDKII_PEI_ATA_PASS_THRU_PPI *This, IN UINT16 Port, IN UINT16 PortMultiplierPort, @@ -110,7 +109,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_ATA_PASS_THRU_THRU_GET_NEXT_PORT) ( +(EFIAPI *EDKII_PEI_ATA_PASS_THRU_THRU_GET_NEXT_PORT)( IN EDKII_PEI_ATA_PASS_THRU_PPI *This, IN OUT UINT16 *Port ); @@ -164,7 +163,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_ATA_PASS_THRU_GET_NEXT_DEVICE) ( +(EFIAPI *EDKII_PEI_ATA_PASS_THRU_GET_NEXT_DEVICE)( IN EDKII_PEI_ATA_PASS_THRU_PPI *This, IN UINT16 Port, IN OUT UINT16 *PortMultiplierPort @@ -189,7 +188,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_ATA_PASS_THRU_GET_DEVICE_PATH) ( +(EFIAPI *EDKII_PEI_ATA_PASS_THRU_GET_DEVICE_PATH)( IN EDKII_PEI_ATA_PASS_THRU_PPI *This, OUT UINTN *DevicePathLength, OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath @@ -208,6 +207,6 @@ struct _EDKII_PEI_ATA_PASS_THRU_PPI { EDKII_PEI_ATA_PASS_THRU_GET_DEVICE_PATH GetDevicePath; }; -extern EFI_GUID gEdkiiPeiAtaPassThruPpiGuid; +extern EFI_GUID gEdkiiPeiAtaPassThruPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/CapsuleOnDisk.h b/MdeModulePkg/Include/Ppi/CapsuleOnDisk.h index 8ff2ba4b17..8a7f4874f4 100644 --- a/MdeModulePkg/Include/Ppi/CapsuleOnDisk.h +++ b/MdeModulePkg/Include/Ppi/CapsuleOnDisk.h @@ -40,16 +40,16 @@ EFI_STATUS /// Finds and loads the recovery files. /// struct _EDKII_PEI_CAPSULE_ON_DISK_PPI { - EDKII_PEI_LOAD_CAPSULE_ON_DISK LoadCapsuleOnDisk; ///< Loads a DXE binary capsule into memory. + EDKII_PEI_LOAD_CAPSULE_ON_DISK LoadCapsuleOnDisk; ///< Loads a DXE binary capsule into memory. }; -extern EFI_GUID gEdkiiPeiCapsuleOnDiskPpiGuid; +extern EFI_GUID gEdkiiPeiCapsuleOnDiskPpiGuid; #define EDKII_PEI_BOOT_IN_CAPSULE_ON_DISK_MODE_PPI \ { \ 0xb08a11e4, 0xe2b7, 0x4b75, { 0xb5, 0x15, 0xaf, 0x61, 0x6, 0x68, 0xbf, 0xd1 } \ } -extern EFI_GUID gEdkiiPeiBootInCapsuleOnDiskModePpiGuid; +extern EFI_GUID gEdkiiPeiBootInCapsuleOnDiskModePpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/Debug.h b/MdeModulePkg/Include/Ppi/Debug.h index d14caa2bf8..f1332ccaa6 100644 --- a/MdeModulePkg/Include/Ppi/Debug.h +++ b/MdeModulePkg/Include/Ppi/Debug.h @@ -65,11 +65,10 @@ VOID /// This PPI contains a set of services to print message to debug output device /// struct _EDKII_DEBUG_PPI { - EDKII_DEBUG_BPRINT DebugBPrint; - EDKII_DEBUG_ASSERT DebugAssert; + EDKII_DEBUG_BPRINT DebugBPrint; + EDKII_DEBUG_ASSERT DebugAssert; }; -extern EFI_GUID gEdkiiDebugPpiGuid; +extern EFI_GUID gEdkiiDebugPpiGuid; #endif - diff --git a/MdeModulePkg/Include/Ppi/IoMmu.h b/MdeModulePkg/Include/Ppi/IoMmu.h index 34d7f05348..8439bb071b 100644 --- a/MdeModulePkg/Include/Ppi/IoMmu.h +++ b/MdeModulePkg/Include/Ppi/IoMmu.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __PEI_IOMMU_H__ #define __PEI_IOMMU_H__ @@ -33,14 +32,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EDKII_IOMMU_PPI EDKII_IOMMU_PPI; +typedef struct _EDKII_IOMMU_PPI EDKII_IOMMU_PPI; // // Revision The revision to which the IOMMU interface adheres. // All future revisions must be backwards compatible. // If a future version is not back wards compatible it is not the same GUID. // -#define EDKII_IOMMU_PPI_REVISION 0x00010000 +#define EDKII_IOMMU_PPI_REVISION 0x00010000 /** Set IOMMU attribute for a system memory. @@ -185,17 +184,17 @@ EFI_STATUS /// IOMMU PPI structure. /// struct _EDKII_IOMMU_PPI { - UINT64 Revision; - EDKII_PEI_IOMMU_SET_ATTRIBUTE SetAttribute; - EDKII_PEI_IOMMU_MAP Map; - EDKII_PEI_IOMMU_UNMAP Unmap; - EDKII_PEI_IOMMU_ALLOCATE_BUFFER AllocateBuffer; - EDKII_PEI_IOMMU_FREE_BUFFER FreeBuffer; + UINT64 Revision; + EDKII_PEI_IOMMU_SET_ATTRIBUTE SetAttribute; + EDKII_PEI_IOMMU_MAP Map; + EDKII_PEI_IOMMU_UNMAP Unmap; + EDKII_PEI_IOMMU_ALLOCATE_BUFFER AllocateBuffer; + EDKII_PEI_IOMMU_FREE_BUFFER FreeBuffer; }; /// /// IOMMU PPI GUID variable. /// -extern EFI_GUID gEdkiiIoMmuPpiGuid; +extern EFI_GUID gEdkiiIoMmuPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/IpmiPpi.h b/MdeModulePkg/Include/Ppi/IpmiPpi.h index c3412e17b7..e88b4adfb8 100644 --- a/MdeModulePkg/Include/Ppi/IpmiPpi.h +++ b/MdeModulePkg/Include/Ppi/IpmiPpi.h @@ -37,13 +37,13 @@ typedef struct _PEI_IPMI_PPI PEI_IPMI_PPI; **/ typedef EFI_STATUS -(EFIAPI *PEI_IPMI_SUBMIT_COMMAND) ( +(EFIAPI *PEI_IPMI_SUBMIT_COMMAND)( IN PEI_IPMI_PPI *This, IN UINT8 NetFunction, IN UINT8 Command, IN UINT8 *RequestData, IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, + OUT UINT8 *ResponseData, IN OUT UINT32 *ResponseDataSize ); @@ -51,9 +51,9 @@ EFI_STATUS // IPMI PPI // struct _PEI_IPMI_PPI { - PEI_IPMI_SUBMIT_COMMAND IpmiSubmitCommand; + PEI_IPMI_SUBMIT_COMMAND IpmiSubmitCommand; }; -extern EFI_GUID gPeiIpmiPpiGuid; +extern EFI_GUID gPeiIpmiPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/NvmExpressHostController.h b/MdeModulePkg/Include/Ppi/NvmExpressHostController.h index 3a88180aa7..6d98de6b18 100644 --- a/MdeModulePkg/Include/Ppi/NvmExpressHostController.h +++ b/MdeModulePkg/Include/Ppi/NvmExpressHostController.h @@ -21,7 +21,7 @@ // // Forward declaration for the EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI. // -typedef struct _EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI; +typedef struct _EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI; /** Get the MMIO base address of NVM Express host controller. @@ -38,7 +38,7 @@ typedef struct _EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI EDKII_NVM_EXPRESS_HOST_CO **/ typedef EFI_STATUS -(EFIAPI *EDKII_NVM_EXPRESS_HC_GET_MMIO_BAR) ( +(EFIAPI *EDKII_NVM_EXPRESS_HC_GET_MMIO_BAR)( IN EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, OUT UINTN *MmioBar @@ -65,7 +65,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_NVM_EXPRESS_HC_GET_DEVICE_PATH) ( +(EFIAPI *EDKII_NVM_EXPRESS_HC_GET_DEVICE_PATH)( IN EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, OUT UINTN *DevicePathLength, @@ -81,6 +81,6 @@ struct _EDKII_NVM_EXPRESS_HOST_CONTROLLER_PPI { EDKII_NVM_EXPRESS_HC_GET_DEVICE_PATH GetNvmeHcDevicePath; }; -extern EFI_GUID gEdkiiPeiNvmExpressHostControllerPpiGuid; +extern EFI_GUID gEdkiiPeiNvmExpressHostControllerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/NvmExpressPassThru.h b/MdeModulePkg/Include/Ppi/NvmExpressPassThru.h index cb5b3b3b18..c5ccf0e775 100644 --- a/MdeModulePkg/Include/Ppi/NvmExpressPassThru.h +++ b/MdeModulePkg/Include/Ppi/NvmExpressPassThru.h @@ -22,7 +22,7 @@ // // Forward declaration for the EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI. // -typedef struct _EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI; +typedef struct _EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI; // // Revision The revision to which the Nvme Pass Thru PPI interface adheres. @@ -50,7 +50,7 @@ typedef struct _EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI EDKII_PEI_NVM_EXPRESS_PASS_ **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_NVME_PASS_THRU_GET_DEVICE_PATH) ( +(EFIAPI *EDKII_PEI_NVME_PASS_THRU_GET_DEVICE_PATH)( IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, OUT UINTN *DevicePathLength, OUT EFI_DEVICE_PATH_PROTOCOL **DevicePath @@ -99,7 +99,6 @@ EFI_STATUS IN OUT UINT32 *NamespaceId ); - /** Sends an NVM Express Command Packet to an NVM Express controller or namespace. This function only supports blocking execution of the command. @@ -133,7 +132,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_NVME_PASS_THRU_PASSTHRU) ( +(EFIAPI *EDKII_PEI_NVME_PASS_THRU_PASSTHRU)( IN EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI *This, IN UINT32 NamespaceId, IN OUT EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET *Packet @@ -144,13 +143,13 @@ EFI_STATUS // to a mass storage device. // struct _EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI { - UINT64 Revision; - EFI_NVM_EXPRESS_PASS_THRU_MODE *Mode; - EDKII_PEI_NVME_PASS_THRU_GET_DEVICE_PATH GetDevicePath; - EDKII_PEI_NVME_PASS_THRU_GET_NEXT_NAMESPACE GetNextNameSpace; - EDKII_PEI_NVME_PASS_THRU_PASSTHRU PassThru; + UINT64 Revision; + EFI_NVM_EXPRESS_PASS_THRU_MODE *Mode; + EDKII_PEI_NVME_PASS_THRU_GET_DEVICE_PATH GetDevicePath; + EDKII_PEI_NVME_PASS_THRU_GET_NEXT_NAMESPACE GetNextNameSpace; + EDKII_PEI_NVME_PASS_THRU_PASSTHRU PassThru; }; -extern EFI_GUID gEdkiiPeiNvmExpressPassThruPpiGuid; +extern EFI_GUID gEdkiiPeiNvmExpressPassThruPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/PlatformSpecificResetFilter.h b/MdeModulePkg/Include/Ppi/PlatformSpecificResetFilter.h index b5ee324db5..823600f8b7 100644 --- a/MdeModulePkg/Include/Ppi/PlatformSpecificResetFilter.h +++ b/MdeModulePkg/Include/Ppi/PlatformSpecificResetFilter.h @@ -18,8 +18,8 @@ #define EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PPI_GUID \ { 0x8c9f4de3, 0x7b90, 0x47ef, { 0x93, 0x8, 0x28, 0x7c, 0xec, 0xd6, 0x6d, 0xe8 } } -typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PPI; +typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PPI; -extern EFI_GUID gEdkiiPlatformSpecificResetFilterPpiGuid; +extern EFI_GUID gEdkiiPlatformSpecificResetFilterPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/PlatformSpecificResetHandler.h b/MdeModulePkg/Include/Ppi/PlatformSpecificResetHandler.h index 069a4f7075..50c68deb14 100644 --- a/MdeModulePkg/Include/Ppi/PlatformSpecificResetHandler.h +++ b/MdeModulePkg/Include/Ppi/PlatformSpecificResetHandler.h @@ -16,8 +16,8 @@ #define EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PPI_GUID \ { 0x75cf14ae, 0x3441, 0x49dc, { 0xaa, 0x10, 0xbb, 0x35, 0xa7, 0xba, 0x8b, 0xab } } -typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PPI; +typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PPI; -extern EFI_GUID gEdkiiPlatformSpecificResetHandlerPpiGuid; +extern EFI_GUID gEdkiiPlatformSpecificResetHandlerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/PlatformSpecificResetNotification.h b/MdeModulePkg/Include/Ppi/PlatformSpecificResetNotification.h index f97e46f5ec..d671ee07f1 100644 --- a/MdeModulePkg/Include/Ppi/PlatformSpecificResetNotification.h +++ b/MdeModulePkg/Include/Ppi/PlatformSpecificResetNotification.h @@ -19,8 +19,8 @@ #define EDKII_PLATFORM_SPECIFIC_RESET_NOTIFICATION_PPI_GUID \ { 0xe09f355d, 0xdae8, 0x4910, { 0xb1, 0x4a, 0x92, 0x78, 0x0f, 0xdc, 0xf7, 0xcb } } -typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_NOTIFICATION_PPI; +typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_NOTIFICATION_PPI; -extern EFI_GUID gEdkiiPlatformSpecificResetNotificationPpiGuid; +extern EFI_GUID gEdkiiPlatformSpecificResetNotificationPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/PostBootScriptTable.h b/MdeModulePkg/Include/Ppi/PostBootScriptTable.h index 09327c0d50..923eb49ad7 100644 --- a/MdeModulePkg/Include/Ppi/PostBootScriptTable.h +++ b/MdeModulePkg/Include/Ppi/PostBootScriptTable.h @@ -15,6 +15,6 @@ #define PEI_POST_BOOT_SCRIPT_TABLE_PPI_GUID \ {0x88c9d306, 0x900, 0x4eb5, 0x82, 0x60, 0x3e, 0x2d, 0xbe, 0xda, 0x1f, 0x89}; -extern EFI_GUID gPeiPostScriptTablePpiGuid; +extern EFI_GUID gPeiPostScriptTablePpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SdMmcHostController.h b/MdeModulePkg/Include/Ppi/SdMmcHostController.h index f224f2546a..253953cc81 100644 --- a/MdeModulePkg/Include/Ppi/SdMmcHostController.h +++ b/MdeModulePkg/Include/Ppi/SdMmcHostController.h @@ -20,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Forward declaration for the SD_MMC_HOST_CONTROLLER_PPI. /// -typedef struct _EDKII_SD_MMC_HOST_CONTROLLER_PPI EDKII_SD_MMC_HOST_CONTROLLER_PPI; +typedef struct _EDKII_SD_MMC_HOST_CONTROLLER_PPI EDKII_SD_MMC_HOST_CONTROLLER_PPI; /** Get the MMIO base address of SD/MMC host controller. @@ -42,16 +42,16 @@ EFI_STATUS IN EDKII_SD_MMC_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, IN OUT UINTN **MmioBar, - OUT UINT8 *BarNum + OUT UINT8 *BarNum ); /// /// This PPI contains a set of services to interact with the SD_MMC host controller. /// struct _EDKII_SD_MMC_HOST_CONTROLLER_PPI { - EDKII_SD_MMC_HC_GET_MMIO_BAR GetSdMmcHcMmioBar; + EDKII_SD_MMC_HC_GET_MMIO_BAR GetSdMmcHcMmioBar; }; -extern EFI_GUID gEdkiiPeiSdMmcHostControllerPpiGuid; +extern EFI_GUID gEdkiiPeiSdMmcHostControllerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SecPerformance.h b/MdeModulePkg/Include/Ppi/SecPerformance.h index cbdaccdb99..fdeb434f5d 100644 --- a/MdeModulePkg/Include/Ppi/SecPerformance.h +++ b/MdeModulePkg/Include/Ppi/SecPerformance.h @@ -21,7 +21,7 @@ typedef struct _PEI_SEC_PERFORMANCE_PPI PEI_SEC_PERFORMANCE_PPI; /// Performance data collected in SEC phase. /// typedef struct { - UINT64 ResetEnd; ///< Timer value logged at the beginning of firmware image execution, in unit of nanosecond. + UINT64 ResetEnd; ///< Timer value logged at the beginning of firmware image execution, in unit of nanosecond. } FIRMWARE_SEC_PERFORMANCE; /** @@ -42,7 +42,7 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *GET_SEC_PERFORMANCE) ( +(EFIAPI *GET_SEC_PERFORMANCE)( IN CONST EFI_PEI_SERVICES **PeiServices, IN PEI_SEC_PERFORMANCE_PPI *This, OUT FIRMWARE_SEC_PERFORMANCE *Performance @@ -52,9 +52,9 @@ EFI_STATUS /// This PPI provides function to get performance data collected in SEC phase. /// struct _PEI_SEC_PERFORMANCE_PPI { - GET_SEC_PERFORMANCE GetPerformance; + GET_SEC_PERFORMANCE GetPerformance; }; -extern EFI_GUID gPeiSecPerformancePpiGuid; +extern EFI_GUID gPeiSecPerformancePpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SerialPortPei.h b/MdeModulePkg/Include/Ppi/SerialPortPei.h index 0016114927..6d26e88dde 100644 --- a/MdeModulePkg/Include/Ppi/SerialPortPei.h +++ b/MdeModulePkg/Include/Ppi/SerialPortPei.h @@ -15,6 +15,6 @@ 0x490e9d85, 0x8aef, 0x4193, { 0x8e, 0x56, 0xf7, 0x34, 0xa9, 0xff, 0xac, 0x8b } \ } -extern EFI_GUID gPeiSerialPortPpiGuid; +extern EFI_GUID gPeiSerialPortPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SmmAccess.h b/MdeModulePkg/Include/Ppi/SmmAccess.h index b920f599c9..9bafbd9667 100644 --- a/MdeModulePkg/Include/Ppi/SmmAccess.h +++ b/MdeModulePkg/Include/Ppi/SmmAccess.h @@ -23,7 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define PEI_SMM_ACCESS_PPI_GUID \ { 0x268f33a9, 0xcccd, 0x48be, { 0x88, 0x17, 0x86, 0x5, 0x3a, 0xc3, 0x2e, 0xd6 }} -typedef struct _PEI_SMM_ACCESS_PPI PEI_SMM_ACCESS_PPI; +typedef struct _PEI_SMM_ACCESS_PPI PEI_SMM_ACCESS_PPI; /** Opens the SMRAM area to be accessible by a PEIM driver. @@ -126,14 +126,14 @@ EFI_STATUS /// memory controller would publish this PPI. /// struct _PEI_SMM_ACCESS_PPI { - PEI_SMM_OPEN Open; - PEI_SMM_CLOSE Close; - PEI_SMM_LOCK Lock; - PEI_SMM_CAPABILITIES GetCapabilities; - BOOLEAN LockState; - BOOLEAN OpenState; + PEI_SMM_OPEN Open; + PEI_SMM_CLOSE Close; + PEI_SMM_LOCK Lock; + PEI_SMM_CAPABILITIES GetCapabilities; + BOOLEAN LockState; + BOOLEAN OpenState; }; -extern EFI_GUID gPeiSmmAccessPpiGuid; +extern EFI_GUID gPeiSmmAccessPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SmmCommunication.h b/MdeModulePkg/Include/Ppi/SmmCommunication.h index 30922cf32c..d4e5568e5b 100644 --- a/MdeModulePkg/Include/Ppi/SmmCommunication.h +++ b/MdeModulePkg/Include/Ppi/SmmCommunication.h @@ -12,7 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _SMM_COMMUNICATION_PPI_H_ #define _SMM_COMMUNICATION_PPI_H_ @@ -21,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0xae933e1c, 0xcc47, 0x4e38, { 0x8f, 0xe, 0xe2, 0xf6, 0x1d, 0x26, 0x5, 0xdf } \ } -typedef struct _EFI_PEI_SMM_COMMUNICATION_PPI EFI_PEI_SMM_COMMUNICATION_PPI; +typedef struct _EFI_PEI_SMM_COMMUNICATION_PPI EFI_PEI_SMM_COMMUNICATION_PPI; /** Communicates with a registered handler. @@ -49,9 +48,9 @@ EFI_STATUS /// between DXE drivers and a registered SMI handler. /// struct _EFI_PEI_SMM_COMMUNICATION_PPI { - EFI_PEI_SMM_COMMUNICATE Communicate; + EFI_PEI_SMM_COMMUNICATE Communicate; }; -extern EFI_GUID gEfiPeiSmmCommunicationPpiGuid; +extern EFI_GUID gEfiPeiSmmCommunicationPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/SmmControl.h b/MdeModulePkg/Include/Ppi/SmmControl.h index 855cfec6bd..f88dbd5932 100644 --- a/MdeModulePkg/Include/Ppi/SmmControl.h +++ b/MdeModulePkg/Include/Ppi/SmmControl.h @@ -15,14 +15,13 @@ **/ - #ifndef _SMM_CONTROL_PPI_H_ #define _SMM_CONTROL_PPI_H_ #define PEI_SMM_CONTROL_PPI_GUID \ { 0x61c68702, 0x4d7e, 0x4f43, 0x8d, 0xef, 0xa7, 0x43, 0x5, 0xce, 0x74, 0xc5 } -typedef struct _PEI_SMM_CONTROL_PPI PEI_SMM_CONTROL_PPI; +typedef struct _PEI_SMM_CONTROL_PPI PEI_SMM_CONTROL_PPI; /** Invokes SMI activation from either the preboot or runtime environment. @@ -43,9 +42,9 @@ typedef struct _PEI_SMM_CONTROL_PPI PEI_SMM_CONTROL_PPI; **/ typedef EFI_STATUS -(EFIAPI *PEI_SMM_ACTIVATE) ( +(EFIAPI *PEI_SMM_ACTIVATE)( IN EFI_PEI_SERVICES **PeiServices, - IN PEI_SMM_CONTROL_PPI * This, + IN PEI_SMM_CONTROL_PPI *This, IN OUT INT8 *ArgumentBuffer OPTIONAL, IN OUT UINTN *ArgumentBufferSize OPTIONAL, IN BOOLEAN Periodic OPTIONAL, @@ -67,9 +66,9 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *PEI_SMM_DEACTIVATE) ( +(EFIAPI *PEI_SMM_DEACTIVATE)( IN EFI_PEI_SERVICES **PeiServices, - IN PEI_SMM_CONTROL_PPI * This, + IN PEI_SMM_CONTROL_PPI *This, IN BOOLEAN Periodic OPTIONAL ); @@ -80,10 +79,10 @@ EFI_STATUS /// Intel chipset /// struct _PEI_SMM_CONTROL_PPI { - PEI_SMM_ACTIVATE Trigger; - PEI_SMM_DEACTIVATE Clear; + PEI_SMM_ACTIVATE Trigger; + PEI_SMM_DEACTIVATE Clear; }; -extern EFI_GUID gPeiSmmControlPpiGuid; +extern EFI_GUID gPeiSmmControlPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/StorageSecurityCommand.h b/MdeModulePkg/Include/Ppi/StorageSecurityCommand.h index 89c7edea99..360628ad21 100644 --- a/MdeModulePkg/Include/Ppi/StorageSecurityCommand.h +++ b/MdeModulePkg/Include/Ppi/StorageSecurityCommand.h @@ -21,7 +21,7 @@ // // Forward declaration for the EDKII_PEI_STORAGE_SECURITY_CMD_PPI. // -typedef struct _EDKII_PEI_STORAGE_SECURITY_CMD_PPI EDKII_PEI_STORAGE_SECURITY_CMD_PPI; +typedef struct _EDKII_PEI_STORAGE_SECURITY_CMD_PPI EDKII_PEI_STORAGE_SECURITY_CMD_PPI; // // Revision The revision to which the Storage Security Command interface adheres. @@ -30,7 +30,6 @@ typedef struct _EDKII_PEI_STORAGE_SECURITY_CMD_PPI EDKII_PEI_STORAGE_SECURITY_C // #define EDKII_STORAGE_SECURITY_PPI_REVISION 0x00010000 - /** Gets the count of storage security devices that one specific driver detects. @@ -43,7 +42,7 @@ typedef struct _EDKII_PEI_STORAGE_SECURITY_CMD_PPI EDKII_PEI_STORAGE_SECURITY_C **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_STORAGE_SECURITY_GET_NUMBER_DEVICES) ( +(EFIAPI *EDKII_PEI_STORAGE_SECURITY_GET_NUMBER_DEVICES)( IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, OUT UINTN *NumberofDevices ); @@ -75,7 +74,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_STORAGE_SECURITY_GET_DEVICE_PATH) ( +(EFIAPI *EDKII_PEI_STORAGE_SECURITY_GET_DEVICE_PATH)( IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, IN UINTN DeviceIndex, OUT UINTN *DevicePathLength, @@ -170,7 +169,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_STORAGE_SECURITY_RECEIVE_DATA) ( +(EFIAPI *EDKII_PEI_STORAGE_SECURITY_RECEIVE_DATA)( IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, IN UINTN DeviceIndex, IN UINT64 Timeout, @@ -247,7 +246,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PEI_STORAGE_SECURITY_SEND_DATA) ( +(EFIAPI *EDKII_PEI_STORAGE_SECURITY_SEND_DATA)( IN EDKII_PEI_STORAGE_SECURITY_CMD_PPI *This, IN UINTN DeviceIndex, IN UINT64 Timeout, @@ -272,6 +271,6 @@ struct _EDKII_PEI_STORAGE_SECURITY_CMD_PPI { EDKII_PEI_STORAGE_SECURITY_SEND_DATA SendData; }; -extern EFI_GUID gEdkiiPeiStorageSecurityCommandPpiGuid; +extern EFI_GUID gEdkiiPeiStorageSecurityCommandPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/UfsHostController.h b/MdeModulePkg/Include/Ppi/UfsHostController.h index 84ee785ed7..e43321cd32 100644 --- a/MdeModulePkg/Include/Ppi/UfsHostController.h +++ b/MdeModulePkg/Include/Ppi/UfsHostController.h @@ -20,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Forward declaration for the UFS_HOST_CONTROLLER_PPI. /// -typedef struct _EDKII_UFS_HOST_CONTROLLER_PPI EDKII_UFS_HOST_CONTROLLER_PPI; +typedef struct _EDKII_UFS_HOST_CONTROLLER_PPI EDKII_UFS_HOST_CONTROLLER_PPI; /** Get the MMIO base address of UFS host controller. @@ -38,16 +38,16 @@ EFI_STATUS (EFIAPI *EDKII_UFS_HC_GET_MMIO_BAR)( IN EDKII_UFS_HOST_CONTROLLER_PPI *This, IN UINT8 ControllerId, - OUT UINTN *MmioBar + OUT UINTN *MmioBar ); /// /// This PPI contains a set of services to interact with the UFS host controller. /// struct _EDKII_UFS_HOST_CONTROLLER_PPI { - EDKII_UFS_HC_GET_MMIO_BAR GetUfsHcMmioBar; + EDKII_UFS_HC_GET_MMIO_BAR GetUfsHcMmioBar; }; -extern EFI_GUID gEdkiiPeiUfsHostControllerPpiGuid; +extern EFI_GUID gEdkiiPeiUfsHostControllerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/Usb2HostController.h b/MdeModulePkg/Include/Ppi/Usb2HostController.h index f93af9ae0e..e979e9ebec 100644 --- a/MdeModulePkg/Include/Ppi/Usb2HostController.h +++ b/MdeModulePkg/Include/Ppi/Usb2HostController.h @@ -248,15 +248,14 @@ EFI_STATUS /// Specification for more information on these interfaces. /// struct _PEI_USB2_HOST_CONTROLLER_PPI { - PEI_USB2_HOST_CONTROLLER_CONTROL_TRANSFER ControlTransfer; - PEI_USB2_HOST_CONTROLLER_BULK_TRANSFER BulkTransfer; - PEI_USB2_HOST_CONTROLLER_GET_ROOTHUB_PORT_NUMBER GetRootHubPortNumber; - PEI_USB2_HOST_CONTROLLER_GET_ROOTHUB_PORT_STATUS GetRootHubPortStatus; - PEI_USB2_HOST_CONTROLLER_SET_ROOTHUB_PORT_FEATURE SetRootHubPortFeature; - PEI_USB2_HOST_CONTROLLER_CLEAR_ROOTHUB_PORT_FEATURE ClearRootHubPortFeature; + PEI_USB2_HOST_CONTROLLER_CONTROL_TRANSFER ControlTransfer; + PEI_USB2_HOST_CONTROLLER_BULK_TRANSFER BulkTransfer; + PEI_USB2_HOST_CONTROLLER_GET_ROOTHUB_PORT_NUMBER GetRootHubPortNumber; + PEI_USB2_HOST_CONTROLLER_GET_ROOTHUB_PORT_STATUS GetRootHubPortStatus; + PEI_USB2_HOST_CONTROLLER_SET_ROOTHUB_PORT_FEATURE SetRootHubPortFeature; + PEI_USB2_HOST_CONTROLLER_CLEAR_ROOTHUB_PORT_FEATURE ClearRootHubPortFeature; }; -extern EFI_GUID gPeiUsb2HostControllerPpiGuid; +extern EFI_GUID gPeiUsb2HostControllerPpiGuid; #endif - diff --git a/MdeModulePkg/Include/Ppi/UsbController.h b/MdeModulePkg/Include/Ppi/UsbController.h index 664c7a21ad..5f2db2b62f 100644 --- a/MdeModulePkg/Include/Ppi/UsbController.h +++ b/MdeModulePkg/Include/Ppi/UsbController.h @@ -28,25 +28,25 @@ typedef struct _PEI_USB_CONTROLLER_PPI PEI_USB_CONTROLLER_PPI; /// This bit is used in the ControllerType return parameter of GetUsbController() /// to identify the USB Host Controller type as UHCI /// -#define PEI_UHCI_CONTROLLER 0x01 +#define PEI_UHCI_CONTROLLER 0x01 /// /// This bit is used in the ControllerType return parameter of GetUsbController() /// to identify the USB Host Controller type as OHCI /// -#define PEI_OHCI_CONTROLLER 0x02 +#define PEI_OHCI_CONTROLLER 0x02 /// /// This bit is used in the ControllerType return parameter of GetUsbController() /// to identify the USB Host Controller type as EHCI /// -#define PEI_EHCI_CONTROLLER 0x03 +#define PEI_EHCI_CONTROLLER 0x03 /// /// This bit is used in the ControllerType return parameter of GetUsbController() /// to identify the USB Host Controller type as XHCI /// -#define PEI_XHCI_CONTROLLER 0x04 +#define PEI_XHCI_CONTROLLER 0x04 /** Retrieve USB Host Controller Info such as controller type and I/O Base Address. @@ -79,9 +79,9 @@ EFI_STATUS /// and the base address of the I/O ports used to access the USB Host Controller. /// struct _PEI_USB_CONTROLLER_PPI { - PEI_GET_USB_CONTROLLER GetUsbController; + PEI_GET_USB_CONTROLLER GetUsbController; }; -extern EFI_GUID gPeiUsbControllerPpiGuid; +extern EFI_GUID gPeiUsbControllerPpiGuid; #endif diff --git a/MdeModulePkg/Include/Ppi/UsbHostController.h b/MdeModulePkg/Include/Ppi/UsbHostController.h index 4dbdb44561..cf468f9478 100644 --- a/MdeModulePkg/Include/Ppi/UsbHostController.h +++ b/MdeModulePkg/Include/Ppi/UsbHostController.h @@ -236,15 +236,14 @@ EFI_STATUS /// Specification for more information on these interfaces. /// struct _PEI_USB_HOST_CONTROLLER_PPI { - PEI_USB_HOST_CONTROLLER_CONTROL_TRANSFER ControlTransfer; - PEI_USB_HOST_CONTROLLER_BULK_TRANSFER BulkTransfer; - PEI_USB_HOST_CONTROLLER_GET_ROOTHUB_PORT_NUMBER GetRootHubPortNumber; - PEI_USB_HOST_CONTROLLER_GET_ROOTHUB_PORT_STATUS GetRootHubPortStatus; - PEI_USB_HOST_CONTROLLER_SET_ROOTHUB_PORT_FEATURE SetRootHubPortFeature; - PEI_USB_HOST_CONTROLLER_CLEAR_ROOTHUB_PORT_FEATURE ClearRootHubPortFeature; + PEI_USB_HOST_CONTROLLER_CONTROL_TRANSFER ControlTransfer; + PEI_USB_HOST_CONTROLLER_BULK_TRANSFER BulkTransfer; + PEI_USB_HOST_CONTROLLER_GET_ROOTHUB_PORT_NUMBER GetRootHubPortNumber; + PEI_USB_HOST_CONTROLLER_GET_ROOTHUB_PORT_STATUS GetRootHubPortStatus; + PEI_USB_HOST_CONTROLLER_SET_ROOTHUB_PORT_FEATURE SetRootHubPortFeature; + PEI_USB_HOST_CONTROLLER_CLEAR_ROOTHUB_PORT_FEATURE ClearRootHubPortFeature; }; -extern EFI_GUID gPeiUsbHostControllerPpiGuid; +extern EFI_GUID gPeiUsbHostControllerPpiGuid; #endif - diff --git a/MdeModulePkg/Include/Ppi/UsbIo.h b/MdeModulePkg/Include/Ppi/UsbIo.h index 71f52f086a..a7122f31ed 100644 --- a/MdeModulePkg/Include/Ppi/UsbIo.h +++ b/MdeModulePkg/Include/Ppi/UsbIo.h @@ -28,7 +28,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Forward declaration for the PEI_USB_IO_PPI. /// -typedef struct _PEI_USB_IO_PPI PEI_USB_IO_PPI; +typedef struct _PEI_USB_IO_PPI PEI_USB_IO_PPI; /** Submits control transfer to a target USB device. @@ -177,13 +177,13 @@ EFI_STATUS /// these interfaces. /// struct _PEI_USB_IO_PPI { - PEI_USB_CONTROL_TRANSFER UsbControlTransfer; - PEI_USB_BULK_TRANSFER UsbBulkTransfer; - PEI_USB_GET_INTERFACE_DESCRIPTOR UsbGetInterfaceDescriptor; - PEI_USB_GET_ENDPOINT_DESCRIPTOR UsbGetEndpointDescriptor; - PEI_USB_PORT_RESET UsbPortReset; + PEI_USB_CONTROL_TRANSFER UsbControlTransfer; + PEI_USB_BULK_TRANSFER UsbBulkTransfer; + PEI_USB_GET_INTERFACE_DESCRIPTOR UsbGetInterfaceDescriptor; + PEI_USB_GET_ENDPOINT_DESCRIPTOR UsbGetEndpointDescriptor; + PEI_USB_PORT_RESET UsbPortReset; }; -extern EFI_GUID gPeiUsbIoPpiGuid; +extern EFI_GUID gPeiUsbIoPpiGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/AtaAtapiPolicy.h b/MdeModulePkg/Include/Protocol/AtaAtapiPolicy.h index 5013eefa94..1b8a45344c 100644 --- a/MdeModulePkg/Include/Protocol/AtaAtapiPolicy.h +++ b/MdeModulePkg/Include/Protocol/AtaAtapiPolicy.h @@ -6,6 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __ATA_ATAPI_POLICY_H__ #define __ATA_ATAPI_POLICY_H__ @@ -18,36 +19,34 @@ typedef struct { /// /// Protocol version. /// - UINT32 Version; + UINT32 Version; /// /// 0: Disable Power-up in Standby; /// 1: Enable Power-up in Standby; /// others: Since PUIS setting is non-volatile, platform can use other value than 0/1 to keep hardware PUIS setting. /// - UINT8 PuisEnable; + UINT8 PuisEnable; /// /// 0: Disable Device Sleep; /// 1: Enable Device Sleep; /// others: Ignored. /// - UINT8 DeviceSleepEnable; + UINT8 DeviceSleepEnable; /// /// 0: Disable Aggressive Device Sleep; /// 1: Enable Aggressive Device Sleep; /// others: Ignored. /// - UINT8 AggressiveDeviceSleepEnable; + UINT8 AggressiveDeviceSleepEnable; - UINT8 Reserved; + UINT8 Reserved; } EDKII_ATA_ATAPI_POLICY_PROTOCOL; -#define EDKII_ATA_ATAPI_POLICY_VERSION 0x00010000 - +#define EDKII_ATA_ATAPI_POLICY_VERSION 0x00010000 -extern EFI_GUID gEdkiiAtaAtapiPolicyProtocolGuid; +extern EFI_GUID gEdkiiAtaAtapiPolicyProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/BootLogo.h b/MdeModulePkg/Include/Protocol/BootLogo.h index 5dfd7840bc..94a9cd1282 100644 --- a/MdeModulePkg/Include/Protocol/BootLogo.h +++ b/MdeModulePkg/Include/Protocol/BootLogo.h @@ -19,7 +19,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EFI_BOOT_LOGO_PROTOCOL EFI_BOOT_LOGO_PROTOCOL; +typedef struct _EFI_BOOT_LOGO_PROTOCOL EFI_BOOT_LOGO_PROTOCOL; /** Update information of logo image drawn on screen. @@ -51,9 +51,9 @@ EFI_STATUS ); struct _EFI_BOOT_LOGO_PROTOCOL { - EFI_SET_BOOT_LOGO SetBootLogo; + EFI_SET_BOOT_LOGO SetBootLogo; }; -extern EFI_GUID gEfiBootLogoProtocolGuid; +extern EFI_GUID gEfiBootLogoProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/BootLogo2.h b/MdeModulePkg/Include/Protocol/BootLogo2.h index b7b52d1211..8542d00e43 100644 --- a/MdeModulePkg/Include/Protocol/BootLogo2.h +++ b/MdeModulePkg/Include/Protocol/BootLogo2.h @@ -92,8 +92,8 @@ EFI_STATUS ); struct _EDKII_BOOT_LOGO2_PROTOCOL { - EDKII_SET_BOOT_LOGO2 SetBootLogo; - EDKII_GET_BOOT_LOGO2 GetBootLogo; + EDKII_SET_BOOT_LOGO2 SetBootLogo; + EDKII_GET_BOOT_LOGO2 GetBootLogo; }; extern EFI_GUID gEdkiiBootLogo2ProtocolGuid; diff --git a/MdeModulePkg/Include/Protocol/DebuggerConfiguration.h b/MdeModulePkg/Include/Protocol/DebuggerConfiguration.h index d91c90b32e..6db5b757ff 100644 --- a/MdeModulePkg/Include/Protocol/DebuggerConfiguration.h +++ b/MdeModulePkg/Include/Protocol/DebuggerConfiguration.h @@ -16,10 +16,10 @@ #define EFI_DEBUGGER_CONFIGURATION_VERSION 0x00000001 typedef struct _EFI_DEBUGGER_CONFIGURATION_PROTOCOL { - UINT32 DebuggerConfigurationRevision; - VOID *DebuggerPrivateData; + UINT32 DebuggerConfigurationRevision; + VOID *DebuggerPrivateData; } EFI_DEBUGGER_CONFIGURATION_PROTOCOL; -extern EFI_GUID gEfiDebuggerConfigurationProtocolGuid; +extern EFI_GUID gEfiDebuggerConfigurationProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/DeviceSecurity.h b/MdeModulePkg/Include/Protocol/DeviceSecurity.h index c3bf624cac..7492d42e8f 100644 --- a/MdeModulePkg/Include/Protocol/DeviceSecurity.h +++ b/MdeModulePkg/Include/Protocol/DeviceSecurity.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __DEVICE_SECURITY_H__ #define __DEVICE_SECURITY_H__ @@ -24,14 +23,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EDKII_DEVICE_SECURITY_PROTOCOL EDKII_DEVICE_SECURITY_PROTOCOL; +typedef struct _EDKII_DEVICE_SECURITY_PROTOCOL EDKII_DEVICE_SECURITY_PROTOCOL; // // Revision The revision to which the DEVICE_SECURITY interface adheres. // All future revisions must be backwards compatible. // If a future version is not back wards compatible it is not the same GUID. // -#define EDKII_DEVICE_SECURITY_PROTOCOL_REVISION 0x00010000 +#define EDKII_DEVICE_SECURITY_PROTOCOL_REVISION 0x00010000 // // The device identifier. @@ -40,7 +39,7 @@ typedef struct { /// /// Version of this data structure. /// - UINT32 Version; + UINT32 Version; /// /// Type of the device. /// This field is also served as a device Access protocol GUID. @@ -49,7 +48,7 @@ typedef struct { /// EDKII_DEVICE_IDENTIFIER_TYPE_PCI_GUID means the device access protocol is PciIo. /// EDKII_DEVICE_IDENTIFIER_TYPE_USB_GUID means the device access protocol is UsbIo. /// - EFI_GUID DeviceType; + EFI_GUID DeviceType; /// /// The handle created for this device. /// NOTE: This might be a temporary handle. @@ -72,14 +71,14 @@ typedef struct { /// register a protocol notify function. Installing a real protocol may cause /// the callback function being executed before the device is authenticated. /// - EFI_HANDLE DeviceHandle; + EFI_HANDLE DeviceHandle; } EDKII_DEVICE_IDENTIFIER; // // Revision The revision to which the DEVICE_IDENTIFIER interface adheres. // All future revisions must be backwards compatible. // -#define EDKII_DEVICE_IDENTIFIER_REVISION 0x00010000 +#define EDKII_DEVICE_IDENTIFIER_REVISION 0x00010000 // // Device Identifier GUID value @@ -144,19 +143,19 @@ EFI_STATUS /// This protocol is used to authenticate a device based upon the platform policy. /// struct _EDKII_DEVICE_SECURITY_PROTOCOL { - UINT64 Revision; - EDKII_DEVICE_AUTHENTICATE DeviceAuthenticate; + UINT64 Revision; + EDKII_DEVICE_AUTHENTICATE DeviceAuthenticate; }; /// /// Device Security Protocol GUID variable. /// -extern EFI_GUID gEdkiiDeviceSecurityProtocolGuid; +extern EFI_GUID gEdkiiDeviceSecurityProtocolGuid; /// /// Device Identifier tpye GUID variable. /// -extern EFI_GUID gEdkiiDeviceIdentifierTypePciGuid; -extern EFI_GUID gEdkiiDeviceIdentifierTypeUsbGuid; +extern EFI_GUID gEdkiiDeviceIdentifierTypePciGuid; +extern EFI_GUID gEdkiiDeviceIdentifierTypeUsbGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/DisplayProtocol.h b/MdeModulePkg/Include/Protocol/DisplayProtocol.h index 748ceed177..be08b74b29 100644 --- a/MdeModulePkg/Include/Protocol/DisplayProtocol.h +++ b/MdeModulePkg/Include/Protocol/DisplayProtocol.h @@ -17,11 +17,11 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Do nothing. // -#define BROWSER_ACTION_NONE BIT16 +#define BROWSER_ACTION_NONE BIT16 // // ESC Exit // -#define BROWSER_ACTION_FORM_EXIT BIT17 +#define BROWSER_ACTION_FORM_EXIT BIT17 #define BROWSER_SUCCESS 0x0 #define BROWSER_ERROR BIT31 @@ -44,53 +44,53 @@ typedef struct { // // HII Data Type // - UINT8 Type; + UINT8 Type; // // Buffer Data and Length if Type is EFI_IFR_TYPE_BUFFER or EFI_IFR_TYPE_STRING // - UINT8 *Buffer; - UINT16 BufferLen; - EFI_IFR_TYPE_VALUE Value; + UINT8 *Buffer; + UINT16 BufferLen; + EFI_IFR_TYPE_VALUE Value; } EFI_HII_VALUE; #define DISPLAY_QUESTION_OPTION_SIGNATURE SIGNATURE_32 ('Q', 'O', 'P', 'T') typedef struct { - UINTN Signature; - LIST_ENTRY Link; + UINTN Signature; + LIST_ENTRY Link; // // OneOfOption Data // - EFI_IFR_ONE_OF_OPTION *OptionOpCode; + EFI_IFR_ONE_OF_OPTION *OptionOpCode; // // Option ImageId and AnimationId // - EFI_IMAGE_ID ImageId; - EFI_ANIMATION_ID AnimationId; + EFI_IMAGE_ID ImageId; + EFI_ANIMATION_ID AnimationId; } DISPLAY_QUESTION_OPTION; #define DISPLAY_QUESTION_OPTION_FROM_LINK(a) CR (a, DISPLAY_QUESTION_OPTION, Link, DISPLAY_QUESTION_OPTION_SIGNATURE) -typedef struct _FORM_DISPLAY_ENGINE_STATEMENT FORM_DISPLAY_ENGINE_STATEMENT; -typedef struct _FORM_DISPLAY_ENGINE_FORM FORM_DISPLAY_ENGINE_FORM; +typedef struct _FORM_DISPLAY_ENGINE_STATEMENT FORM_DISPLAY_ENGINE_STATEMENT; +typedef struct _FORM_DISPLAY_ENGINE_FORM FORM_DISPLAY_ENGINE_FORM; -#define STATEMENT_VALID 0x0 -#define STATEMENT_INVALID BIT31 +#define STATEMENT_VALID 0x0 +#define STATEMENT_INVALID BIT31 -#define INCOSISTENT_IF_TRUE STATEMENT_INVALID | 0x01 -#define WARNING_IF_TRUE STATEMENT_INVALID | 0x02 -#define STRING_TOO_LONG STATEMENT_INVALID | 0x03 +#define INCOSISTENT_IF_TRUE STATEMENT_INVALID | 0x01 +#define WARNING_IF_TRUE STATEMENT_INVALID | 0x02 +#define STRING_TOO_LONG STATEMENT_INVALID | 0x03 // ... to be extended. typedef struct { // // StringId for INCONSITENT_IF or WARNING_IF // - EFI_STRING_ID StringId; + EFI_STRING_ID StringId; // // TimeOut for WARNING_IF // - UINT8 TimeOut; + UINT8 TimeOut; } STATEMENT_ERROR_INFO; /** @@ -105,7 +105,7 @@ typedef struct { **/ typedef UINT32 -(EFIAPI *VALIDATE_QUESTION) ( +(EFIAPI *VALIDATE_QUESTION)( IN FORM_DISPLAY_ENGINE_FORM *Form, IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, IN EFI_HII_VALUE *Value, @@ -126,7 +126,7 @@ UINT32 **/ typedef EFI_STATUS -(EFIAPI *PASSWORD_CHECK) ( +(EFIAPI *PASSWORD_CHECK)( IN FORM_DISPLAY_ENGINE_FORM *Form, IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, IN EFI_STRING PasswordString OPTIONAL @@ -137,66 +137,66 @@ EFI_STATUS // // Attribute for Statement and Form // -#define HII_DISPLAY_NONE 0 -#define HII_DISPLAY_GRAYOUT BIT0 -#define HII_DISPLAY_LOCK BIT1 -#define HII_DISPLAY_READONLY BIT2 -#define HII_DISPLAY_MODAL BIT3 -#define HII_DISPLAY_SUPPRESS BIT4 - -struct _FORM_DISPLAY_ENGINE_STATEMENT{ - UINTN Signature; +#define HII_DISPLAY_NONE 0 +#define HII_DISPLAY_GRAYOUT BIT0 +#define HII_DISPLAY_LOCK BIT1 +#define HII_DISPLAY_READONLY BIT2 +#define HII_DISPLAY_MODAL BIT3 +#define HII_DISPLAY_SUPPRESS BIT4 + +struct _FORM_DISPLAY_ENGINE_STATEMENT { + UINTN Signature; // // Version for future structure extension // - UINTN Version; + UINTN Version; // // link to all the statement which will show in the display form. // - LIST_ENTRY DisplayLink; + LIST_ENTRY DisplayLink; // // Pointer to statement opcode. // for Guided Opcode. All buffers will be here if GUIDED opcode scope is set. // - EFI_IFR_OP_HEADER *OpCode; + EFI_IFR_OP_HEADER *OpCode; // // Question CurrentValue // - EFI_HII_VALUE CurrentValue; + EFI_HII_VALUE CurrentValue; // // Flag to describe whether setting is changed or not. // Displayer may depend on it to show it with the different color. // - BOOLEAN SettingChangedFlag; + BOOLEAN SettingChangedFlag; // // nested Statement list inside of EFI_IFR_SUBTITLE // - LIST_ENTRY NestStatementList; + LIST_ENTRY NestStatementList; // // nested EFI_IFR_ONE_OF_OPTION list (QUESTION_OPTION) // - LIST_ENTRY OptionListHead; + LIST_ENTRY OptionListHead; // // Statement attributes: GRAYOUT, LOCK and READONLY // - UINT32 Attribute; + UINT32 Attribute; // // ValidateQuestion to do InconsistIf check // It may be NULL if any value is valid. // - VALIDATE_QUESTION ValidateQuestion; + VALIDATE_QUESTION ValidateQuestion; // // Password additional check. It may be NULL when the additional check is not required. // - PASSWORD_CHECK PasswordCheck; + PASSWORD_CHECK PasswordCheck; // // Statement ImageId and AnimationId // - EFI_IMAGE_ID ImageId; - EFI_ANIMATION_ID AnimationId; + EFI_IMAGE_ID ImageId; + EFI_ANIMATION_ID AnimationId; }; #define FORM_DISPLAY_ENGINE_STATEMENT_FROM_LINK(a) CR (a, FORM_DISPLAY_ENGINE_STATEMENT, DisplayLink, FORM_DISPLAY_ENGINE_STATEMENT_SIGNATURE) @@ -204,19 +204,19 @@ struct _FORM_DISPLAY_ENGINE_STATEMENT{ #define BROWSER_HOT_KEY_SIGNATURE SIGNATURE_32 ('B', 'H', 'K', 'S') typedef struct { - UINTN Signature; - LIST_ENTRY Link; + UINTN Signature; + LIST_ENTRY Link; - EFI_INPUT_KEY *KeyData; + EFI_INPUT_KEY *KeyData; // // Action is Discard, Default, Submit, Reset and Exit. // - UINT32 Action; - UINT16 DefaultId; + UINT32 Action; + UINT16 DefaultId; // // HotKey Help String // - EFI_STRING HelpString; + EFI_STRING HelpString; } BROWSER_HOT_KEY; #define BROWSER_HOT_KEY_FROM_LINK(a) CR (a, BROWSER_HOT_KEY, Link, BROWSER_HOT_KEY_SIGNATURE) @@ -224,86 +224,86 @@ typedef struct { #define FORM_DISPLAY_ENGINE_FORM_SIGNATURE SIGNATURE_32 ('F', 'F', 'R', 'M') struct _FORM_DISPLAY_ENGINE_FORM { - UINTN Signature; + UINTN Signature; // // Version for future structure extension // - UINTN Version; + UINTN Version; // // Statement List inside of Form // - LIST_ENTRY StatementListHead; + LIST_ENTRY StatementListHead; // // Statement List outside of Form // - LIST_ENTRY StatementListOSF; + LIST_ENTRY StatementListOSF; // // The input screen dimenstions info. // - EFI_SCREEN_DESCRIPTOR *ScreenDimensions; + EFI_SCREEN_DESCRIPTOR *ScreenDimensions; // // FormSet information // - EFI_GUID FormSetGuid; + EFI_GUID FormSetGuid; // // HiiHandle can be used to get String, Image or Animation // - EFI_HII_HANDLE HiiHandle; + EFI_HII_HANDLE HiiHandle; // // Form ID and Title. // - UINT16 FormId; - EFI_STRING_ID FormTitle; + UINT16 FormId; + EFI_STRING_ID FormTitle; // // Form Attributes: Lock, Modal. // - UINT32 Attribute; + UINT32 Attribute; // // Flag to describe whether setting is changed or not. // Displayer depends on it to show ChangedFlag. // - BOOLEAN SettingChangedFlag; + BOOLEAN SettingChangedFlag; // // Statement to be HighLighted // - FORM_DISPLAY_ENGINE_STATEMENT *HighLightedStatement; + FORM_DISPLAY_ENGINE_STATEMENT *HighLightedStatement; // // Event to notify Displayer that FormData is updated to be refreshed. // - EFI_EVENT FormRefreshEvent; + EFI_EVENT FormRefreshEvent; // // Additional Hotkey registered by BrowserEx protocol. // - LIST_ENTRY HotKeyListHead; + LIST_ENTRY HotKeyListHead; // // Form ImageId and AnimationId // - EFI_IMAGE_ID ImageId; - EFI_ANIMATION_ID AnimationId; + EFI_IMAGE_ID ImageId; + EFI_ANIMATION_ID AnimationId; // // If Status is error, display needs to handle it. // - UINT32 BrowserStatus; + UINT32 BrowserStatus; // // String for error status. It may be NULL. // - EFI_STRING ErrorString; + EFI_STRING ErrorString; }; #define FORM_DISPLAY_ENGINE_FORM_FROM_LINK(a) CR (a, FORM_DISPLAY_ENGINE_FORM, Link, FORM_DISPLAY_ENGINE_FORM_SIGNATURE) typedef struct { - FORM_DISPLAY_ENGINE_STATEMENT *SelectedStatement; // Selected Statement and InputValue + FORM_DISPLAY_ENGINE_STATEMENT *SelectedStatement; // Selected Statement and InputValue - EFI_HII_VALUE InputValue; + EFI_HII_VALUE InputValue; - UINT32 Action; // If SelectedStatement is NULL, Action will be used. + UINT32 Action; // If SelectedStatement is NULL, Action will be used. // Trig Action (Discard, Default, Submit, Reset and Exit) - UINT16 DefaultId; + UINT16 DefaultId; } USER_INPUT; /** @@ -316,10 +316,10 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *FORM_DISPLAY) ( +(EFIAPI *FORM_DISPLAY)( IN FORM_DISPLAY_ENGINE_FORM *FormData, OUT USER_INPUT *UserInputData -); + ); /** Exit Display and Clear Screen to the original state. @@ -327,9 +327,9 @@ EFI_STATUS **/ typedef VOID -(EFIAPI *EXIT_DISPLAY) ( +(EFIAPI *EXIT_DISPLAY)( VOID -); + ); /** Confirm how to handle the changed data. @@ -338,15 +338,15 @@ VOID **/ typedef UINTN -(EFIAPI *CONFIRM_DATA_CHANGE) ( +(EFIAPI *CONFIRM_DATA_CHANGE)( VOID -); + ); typedef struct { - FORM_DISPLAY FormDisplay; - EXIT_DISPLAY ExitDisplay; - CONFIRM_DATA_CHANGE ConfirmDataChange; + FORM_DISPLAY FormDisplay; + EXIT_DISPLAY ExitDisplay; + CONFIRM_DATA_CHANGE ConfirmDataChange; } EDKII_FORM_DISPLAY_ENGINE_PROTOCOL; -extern EFI_GUID gEdkiiFormDisplayEngineProtocolGuid; +extern EFI_GUID gEdkiiFormDisplayEngineProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/EbcSimpleDebugger.h b/MdeModulePkg/Include/Protocol/EbcSimpleDebugger.h index bb257826b1..503c4aed18 100644 --- a/MdeModulePkg/Include/Protocol/EbcSimpleDebugger.h +++ b/MdeModulePkg/Include/Protocol/EbcSimpleDebugger.h @@ -36,7 +36,7 @@ typedef struct _EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL EFI_EBC_SIMPLE_DEBUGGER_PROTOCO **/ typedef EFI_STATUS -(EFIAPI *EBC_DEBUGGER_SIGNAL_EXCEPTION) ( +(EFIAPI *EBC_DEBUGGER_SIGNAL_EXCEPTION)( IN EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL *This, IN VM_CONTEXT *VmPtr, IN EFI_EXCEPTION_TYPE ExceptionType @@ -54,7 +54,7 @@ EFI_STATUS **/ typedef VOID -(EFIAPI *EBC_DEBUGGER_DEBUG) ( +(EFIAPI *EBC_DEBUGGER_DEBUG)( IN EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL *This, IN VM_CONTEXT *VmPtr ); @@ -73,7 +73,7 @@ VOID **/ typedef UINT32 -(EFIAPI *EBC_DEBUGGER_DASM) ( +(EFIAPI *EBC_DEBUGGER_DASM)( IN EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL *This, IN VM_CONTEXT *VmPtr, IN UINT16 *DasmString OPTIONAL, @@ -96,7 +96,7 @@ UINT32 **/ typedef EFI_STATUS -(EFIAPI *EBC_DEBUGGER_CONFIGURE) ( +(EFIAPI *EBC_DEBUGGER_CONFIGURE)( IN EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL *This, IN UINT32 ConfigId, IN UINTN ConfigValue @@ -106,12 +106,12 @@ EFI_STATUS // Prototype for the actual EBC debug support protocol interface // struct _EFI_EBC_SIMPLE_DEBUGGER_PROTOCOL { - EBC_DEBUGGER_DEBUG Debugger; - EBC_DEBUGGER_SIGNAL_EXCEPTION SignalException; - EBC_DEBUGGER_DASM Dasm; - EBC_DEBUGGER_CONFIGURE Configure; + EBC_DEBUGGER_DEBUG Debugger; + EBC_DEBUGGER_SIGNAL_EXCEPTION SignalException; + EBC_DEBUGGER_DASM Dasm; + EBC_DEBUGGER_CONFIGURE Configure; }; -extern EFI_GUID gEfiEbcSimpleDebuggerProtocolGuid; +extern EFI_GUID gEfiEbcSimpleDebuggerProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/EbcVmTest.h b/MdeModulePkg/Include/Protocol/EbcVmTest.h index 55628a2091..a4ed4894db 100644 --- a/MdeModulePkg/Include/Protocol/EbcVmTest.h +++ b/MdeModulePkg/Include/Protocol/EbcVmTest.h @@ -40,16 +40,16 @@ typedef struct _EFI_EBC_VM_TEST_PROTOCOL EFI_EBC_VM_TEST_PROTOCOL; // // Masks for working with the VM flags register // -#define VMFLAGS_CC 0x0001 // condition flag -#define VMFLAGS_STEP 0x0002 // step instruction mode -#define VMFLAGS_ALL_VALID (VMFLAGS_CC | VMFLAGS_STEP) +#define VMFLAGS_CC 0x0001 // condition flag +#define VMFLAGS_STEP 0x0002 // step instruction mode +#define VMFLAGS_ALL_VALID (VMFLAGS_CC | VMFLAGS_STEP) // // Macros for operating on the VM flags register // -#define VMFLAG_SET(pVM, Flag) (pVM->Flags |= (Flag)) -#define VMFLAG_ISSET(pVM, Flag) ((pVM->Flags & (Flag)) ? 1 : 0) -#define VMFLAG_CLEAR(pVM, Flag) (pVM->Flags &= ~(Flag)) +#define VMFLAG_SET(pVM, Flag) (pVM->Flags |= (Flag)) +#define VMFLAG_ISSET(pVM, Flag) ((pVM->Flags & (Flag)) ? 1 : 0) +#define VMFLAG_CLEAR(pVM, Flag) (pVM->Flags &= ~(Flag)) // // Define a macro to get the operand. Then we can change it to be either a @@ -61,8 +61,8 @@ typedef struct _EFI_EBC_VM_TEST_PROTOCOL EFI_EBC_VM_TEST_PROTOCOL; // // Macros for operating on the VM GP registers // -#define OPERAND1_REGDATA(pVM, Op) pVM->Gpr[OPERAND1_REGNUM (Op)] -#define OPERAND2_REGDATA(pVM, Op) pVM->Gpr[OPERAND2_REGNUM (Op)] +#define OPERAND1_REGDATA(pVM, Op) pVM->Gpr[OPERAND1_REGNUM (Op)] +#define OPERAND2_REGDATA(pVM, Op) pVM->Gpr[OPERAND2_REGNUM (Op)] // // Bits of exception flags field of VM context @@ -75,35 +75,35 @@ typedef struct _EFI_EBC_VM_TEST_PROTOCOL EFI_EBC_VM_TEST_PROTOCOL; /// /// instruction pointer for the VM /// -typedef UINT8 *VMIP; +typedef UINT8 *VMIP; -typedef INT64 VM_REGISTER; -typedef UINT32 EXCEPTION_FLAGS; +typedef INT64 VM_REGISTER; +typedef UINT32 EXCEPTION_FLAGS; typedef struct { - VM_REGISTER Gpr[8]; ///< General purpose registers. + VM_REGISTER Gpr[8]; ///< General purpose registers. ///< Flags register: ///< 0 Set to 1 if the result of the last compare was true ///< 1 Set to 1 if stepping - UINT64 Flags; ///< 2..63 Reserved. - VMIP Ip; ///< Instruction pointer. - UINTN LastException; - EXCEPTION_FLAGS ExceptionFlags; ///< to keep track of exceptions - UINT32 StopFlags; - UINT32 CompilerVersion; ///< via break(6) - UINTN HighStackBottom; ///< bottom of the upper stack - UINTN LowStackTop; ///< top of the lower stack - UINT64 StackRetAddr; ///< location of final return address on stack - UINTN *StackMagicPtr; ///< pointer to magic value on stack to detect corruption - EFI_HANDLE ImageHandle; ///< for this EBC driver - EFI_SYSTEM_TABLE *SystemTable; ///< for debugging only - UINTN LastAddrConverted; ///< for debug - UINTN LastAddrConvertedValue; ///< for debug - VOID *FramePtr; - VOID *EntryPoint; ///< entry point of EBC image - UINTN ImageBase; - VOID *StackPool; - VOID *StackTop; + UINT64 Flags; ///< 2..63 Reserved. + VMIP Ip; ///< Instruction pointer. + UINTN LastException; + EXCEPTION_FLAGS ExceptionFlags; ///< to keep track of exceptions + UINT32 StopFlags; + UINT32 CompilerVersion; ///< via break(6) + UINTN HighStackBottom; ///< bottom of the upper stack + UINTN LowStackTop; ///< top of the lower stack + UINT64 StackRetAddr; ///< location of final return address on stack + UINTN *StackMagicPtr; ///< pointer to magic value on stack to detect corruption + EFI_HANDLE ImageHandle; ///< for this EBC driver + EFI_SYSTEM_TABLE *SystemTable; ///< for debugging only + UINTN LastAddrConverted; ///< for debug + UINTN LastAddrConvertedValue; ///< for debug + VOID *FramePtr; + VOID *EntryPoint; ///< entry point of EBC image + UINTN ImageBase; + VOID *StackPool; + VOID *StackTop; } VM_CONTEXT; /** @@ -122,7 +122,7 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *EBC_VM_TEST_EXECUTE) ( +(EFIAPI *EBC_VM_TEST_EXECUTE)( IN EFI_EBC_VM_TEST_PROTOCOL *This, IN VM_CONTEXT *VmPtr, IN OUT UINTN *InstructionCount @@ -142,7 +142,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EBC_VM_TEST_ASM) ( +(EFIAPI *EBC_VM_TEST_ASM)( IN EFI_EBC_VM_TEST_PROTOCOL *This, IN CHAR16 *AsmText, IN OUT INT8 *Buffer, @@ -163,7 +163,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EBC_VM_TEST_DASM) ( +(EFIAPI *EBC_VM_TEST_DASM)( IN EFI_EBC_VM_TEST_PROTOCOL *This, IN OUT CHAR16 *AsmText, IN OUT INT8 *Buffer, @@ -174,11 +174,11 @@ EFI_STATUS // Prototype for the actual EBC test protocol interface // struct _EFI_EBC_VM_TEST_PROTOCOL { - EBC_VM_TEST_EXECUTE Execute; - EBC_VM_TEST_ASM Assemble; - EBC_VM_TEST_DASM Disassemble; + EBC_VM_TEST_EXECUTE Execute; + EBC_VM_TEST_ASM Assemble; + EBC_VM_TEST_DASM Disassemble; }; -extern EFI_GUID gEfiEbcVmTestProtocolGuid; +extern EFI_GUID gEfiEbcVmTestProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/EsrtManagement.h b/MdeModulePkg/Include/Protocol/EsrtManagement.h index e5afb83888..f4dfefba3b 100644 --- a/MdeModulePkg/Include/Protocol/EsrtManagement.h +++ b/MdeModulePkg/Include/Protocol/EsrtManagement.h @@ -22,7 +22,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Forward declaration for the _ESRT_MANAGEMENT_PROTOCOL. /// -typedef struct _ESRT_MANAGEMENT_PROTOCOL ESRT_MANAGEMENT_PROTOCOL; +typedef struct _ESRT_MANAGEMENT_PROTOCOL ESRT_MANAGEMENT_PROTOCOL; /** Get Variable name and data by Esrt Entry FwClass @@ -41,7 +41,6 @@ EFI_STATUS IN OUT EFI_SYSTEM_RESOURCE_ENTRY *Entry ); - /** Update one ESRT entry in ESRT Cache. @@ -58,7 +57,6 @@ EFI_STATUS IN EFI_SYSTEM_RESOURCE_ENTRY *Entry ); - /** Non-FMP instance to unregister Esrt Entry from ESRT Cache. @@ -74,7 +72,6 @@ EFI_STATUS IN EFI_GUID *FwClass ); - /** Non-FMP instance to register one ESRT entry into ESRT Cache. @@ -91,7 +88,6 @@ EFI_STATUS IN EFI_SYSTEM_RESOURCE_ENTRY *Entry ); - /** This function syn up Cached ESRT with data from FMP instances Function should be called after Connect All in order to locate all FMP protocols @@ -108,7 +104,6 @@ EFI_STATUS VOID ); - /** This function locks up Esrt repository to be readonly. It should be called before gEfiEndOfDxeEventGroupGuid event signaled @@ -122,17 +117,15 @@ EFI_STATUS VOID ); - struct _ESRT_MANAGEMENT_PROTOCOL { - GET_ESRT_ENTRY GetEsrtEntry; - UPDATE_ESRT_ENTRY UpdateEsrtEntry; - REGISTER_ESRT_ENTRY RegisterEsrtEntry; - UNREGISTER_ESRT_ENTRY UnRegisterEsrtEntry; - SYNC_ESRT_FMP SyncEsrtFmp; - LOCK_ESRT_REPOSITORY LockEsrtRepository; + GET_ESRT_ENTRY GetEsrtEntry; + UPDATE_ESRT_ENTRY UpdateEsrtEntry; + REGISTER_ESRT_ENTRY RegisterEsrtEntry; + UNREGISTER_ESRT_ENTRY UnRegisterEsrtEntry; + SYNC_ESRT_FMP SyncEsrtFmp; + LOCK_ESRT_REPOSITORY LockEsrtRepository; }; -extern EFI_GUID gEsrtManagementProtocolGuid; +extern EFI_GUID gEsrtManagementProtocolGuid; #endif // #ifndef _ESRT_MANAGEMENT_H_ - diff --git a/MdeModulePkg/Include/Protocol/FaultTolerantWrite.h b/MdeModulePkg/Include/Protocol/FaultTolerantWrite.h index cf7026169f..8fbd8c665e 100644 --- a/MdeModulePkg/Include/Protocol/FaultTolerantWrite.h +++ b/MdeModulePkg/Include/Protocol/FaultTolerantWrite.h @@ -20,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EFI_FAULT_TOLERANT_WRITE_PROTOCOL EFI_FAULT_TOLERANT_WRITE_PROTOCOL; +typedef struct _EFI_FAULT_TOLERANT_WRITE_PROTOCOL EFI_FAULT_TOLERANT_WRITE_PROTOCOL; /** Get the size of the largest block that can be updated in a fault-tolerant manner. @@ -37,7 +37,7 @@ typedef struct _EFI_FAULT_TOLERANT_WRITE_PROTOCOL EFI_FAULT_TOLERANT_WRITE_PROT typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_GET_MAX_BLOCK_SIZE)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This, + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This, OUT UINTN *BlockSize ); @@ -65,8 +65,8 @@ EFI_STATUS typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_ALLOCATE)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This, - IN EFI_GUID * CallerId, + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This, + IN EFI_GUID *CallerId, IN UINTN PrivateDataSize, IN UINTN NumberOfWrites ); @@ -101,7 +101,7 @@ EFI_STATUS typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_WRITE)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This, + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This, IN EFI_LBA Lba, IN UINTN Offset, IN UINTN Length, @@ -126,7 +126,7 @@ EFI_STATUS typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_RESTART)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This, + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This, IN EFI_HANDLE FvbHandle ); @@ -143,7 +143,7 @@ EFI_STATUS typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_ABORT)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This ); /** @@ -174,8 +174,8 @@ EFI_STATUS typedef EFI_STATUS (EFIAPI *EFI_FAULT_TOLERANT_WRITE_GET_LAST_WRITE)( - IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL * This, - OUT EFI_GUID * CallerId, + IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL *This, + OUT EFI_GUID *CallerId, OUT EFI_LBA *Lba, OUT UINTN *Offset, OUT UINTN *Length, @@ -188,14 +188,14 @@ EFI_STATUS // Protocol declaration // struct _EFI_FAULT_TOLERANT_WRITE_PROTOCOL { - EFI_FAULT_TOLERANT_WRITE_GET_MAX_BLOCK_SIZE GetMaxBlockSize; - EFI_FAULT_TOLERANT_WRITE_ALLOCATE Allocate; - EFI_FAULT_TOLERANT_WRITE_WRITE Write; - EFI_FAULT_TOLERANT_WRITE_RESTART Restart; - EFI_FAULT_TOLERANT_WRITE_ABORT Abort; - EFI_FAULT_TOLERANT_WRITE_GET_LAST_WRITE GetLastWrite; + EFI_FAULT_TOLERANT_WRITE_GET_MAX_BLOCK_SIZE GetMaxBlockSize; + EFI_FAULT_TOLERANT_WRITE_ALLOCATE Allocate; + EFI_FAULT_TOLERANT_WRITE_WRITE Write; + EFI_FAULT_TOLERANT_WRITE_RESTART Restart; + EFI_FAULT_TOLERANT_WRITE_ABORT Abort; + EFI_FAULT_TOLERANT_WRITE_GET_LAST_WRITE GetLastWrite; }; -extern EFI_GUID gEfiFaultTolerantWriteProtocolGuid; +extern EFI_GUID gEfiFaultTolerantWriteProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/FileExplorer.h b/MdeModulePkg/Include/Protocol/FileExplorer.h index a6e949d688..aa14d27793 100644 --- a/MdeModulePkg/Include/Protocol/FileExplorer.h +++ b/MdeModulePkg/Include/Protocol/FileExplorer.h @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EFI_FILE_EXPLORER_PROTOCOL EFI_FILE_EXPLORER_PROTOCOL; +typedef struct _EFI_FILE_EXPLORER_PROTOCOL EFI_FILE_EXPLORER_PROTOCOL; /** Prototype for the next process after user chosed one file. @@ -53,7 +53,7 @@ BOOLEAN **/ typedef EFI_STATUS -(EFIAPI *CHOOSE_FILE) ( +(EFIAPI *CHOOSE_FILE)( IN EFI_DEVICE_PATH_PROTOCOL *RootDirectory, IN CHAR16 *FileType OPTIONAL, IN CHOOSE_HANDLER ChooseHandler OPTIONAL, @@ -61,9 +61,9 @@ EFI_STATUS ); struct _EFI_FILE_EXPLORER_PROTOCOL { - CHOOSE_FILE ChooseFile; + CHOOSE_FILE ChooseFile; }; -extern EFI_GUID gEfiFileExplorerProtocolGuid; +extern EFI_GUID gEfiFileExplorerProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h b/MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h index 8e89bfec67..1f518e745d 100644 --- a/MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h +++ b/MdeModulePkg/Include/Protocol/FirmwareManagementProgress.h @@ -26,24 +26,24 @@ typedef struct { /// /// The version of this structure. Initial version value is 0x00000001. /// - UINT32 Version; + UINT32 Version; /// /// The foreground color of a progress bar that is used by the Progress() /// function that is passed into the Firmware Management Protocol SetImage() /// service is called. /// - EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION ProgressBarForegroundColor; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION ProgressBarForegroundColor; /// /// The time in seconds to arm the watchdog timer each time the Progress() /// function passed into the Firmware Management Protocol SetImage() service /// is called. /// - UINTN WatchdogSeconds; + UINTN WatchdogSeconds; } EDKII_FIRMWARE_MANAGEMENT_PROGRESS_PROTOCOL; /// /// EDK II Firmware Management Progress Protocol GUID variable. /// -extern EFI_GUID gEdkiiFirmwareManagementProgressProtocolGuid; +extern EFI_GUID gEdkiiFirmwareManagementProgressProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/FormBrowserEx.h b/MdeModulePkg/Include/Protocol/FormBrowserEx.h index e7e7cd18ab..d03665b7ad 100644 --- a/MdeModulePkg/Include/Protocol/FormBrowserEx.h +++ b/MdeModulePkg/Include/Protocol/FormBrowserEx.h @@ -13,32 +13,32 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define FORM_BROWSER_EXTENSION_PROTOCOL_GUID \ { 0x1f73b18d, 0x4630, 0x43c1, { 0xa1, 0xde, 0x6f, 0x80, 0x85, 0x5d, 0x7d, 0xa4 } } -typedef struct _EDKII_FORM_BROWSER_EXTENSION_PROTOCOL EDKII_FORM_BROWSER_EXTENSION_PROTOCOL; +typedef struct _EDKII_FORM_BROWSER_EXTENSION_PROTOCOL EDKII_FORM_BROWSER_EXTENSION_PROTOCOL; // // To be compatible, keep EFI_FORM_BROWSER_EXTENSION_PROTOCOL definition // -typedef EDKII_FORM_BROWSER_EXTENSION_PROTOCOL EFI_FORM_BROWSER_EXTENSION_PROTOCOL; +typedef EDKII_FORM_BROWSER_EXTENSION_PROTOCOL EFI_FORM_BROWSER_EXTENSION_PROTOCOL; // // Return value of SAVE_REMINDER() that describes whether the changed data is saved or discarded. // -#define BROWSER_NO_CHANGES 0 -#define BROWSER_SAVE_CHANGES 1 -#define BROWSER_DISCARD_CHANGES 2 -#define BROWSER_KEEP_CURRENT 3 +#define BROWSER_NO_CHANGES 0 +#define BROWSER_SAVE_CHANGES 1 +#define BROWSER_DISCARD_CHANGES 2 +#define BROWSER_KEEP_CURRENT 3 // // Browser actions. They can be cominbed together. // If more than one actions are specified, the action with low bit will be executed first. // -#define BROWSER_ACTION_UNREGISTER 0 -#define BROWSER_ACTION_DISCARD BIT0 -#define BROWSER_ACTION_DEFAULT BIT1 -#define BROWSER_ACTION_SUBMIT BIT2 -#define BROWSER_ACTION_RESET BIT3 -#define BROWSER_ACTION_EXIT BIT4 -#define BROWSER_ACTION_GOTO BIT5 +#define BROWSER_ACTION_UNREGISTER 0 +#define BROWSER_ACTION_DISCARD BIT0 +#define BROWSER_ACTION_DEFAULT BIT1 +#define BROWSER_ACTION_SUBMIT BIT2 +#define BROWSER_ACTION_RESET BIT3 +#define BROWSER_ACTION_EXIT BIT4 +#define BROWSER_ACTION_GOTO BIT5 // // Scope for Browser action. It may be Form, FormSet or System level. @@ -65,7 +65,7 @@ typedef enum { **/ typedef EFI_STATUS -(EFIAPI *SET_SCOPE) ( +(EFIAPI *SET_SCOPE)( IN BROWSER_SETTING_SCOPE Scope ); @@ -87,7 +87,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *REGISTER_HOT_KEY) ( +(EFIAPI *REGISTER_HOT_KEY)( IN EFI_INPUT_KEY *KeyData, IN UINT32 Action, IN UINT16 DefaultId, @@ -102,7 +102,7 @@ EFI_STATUS **/ typedef VOID -(EFIAPI *EXIT_HANDLER) ( +(EFIAPI *EXIT_HANDLER)( VOID ); @@ -116,7 +116,7 @@ VOID **/ typedef VOID -(EFIAPI *REGISTER_EXIT_HANDLER) ( +(EFIAPI *REGISTER_EXIT_HANDLER)( IN EXIT_HANDLER Handler ); @@ -137,13 +137,12 @@ UINT32 ); struct _EDKII_FORM_BROWSER_EXTENSION_PROTOCOL { - SET_SCOPE SetScope; - REGISTER_HOT_KEY RegisterHotKey; - REGISTER_EXIT_HANDLER RegiserExitHandler; - SAVE_REMINDER SaveReminder; + SET_SCOPE SetScope; + REGISTER_HOT_KEY RegisterHotKey; + REGISTER_EXIT_HANDLER RegiserExitHandler; + SAVE_REMINDER SaveReminder; }; -extern EFI_GUID gEdkiiFormBrowserExProtocolGuid; +extern EFI_GUID gEdkiiFormBrowserExProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/FormBrowserEx2.h b/MdeModulePkg/Include/Protocol/FormBrowserEx2.h index 438c8ee3ed..725f927856 100644 --- a/MdeModulePkg/Include/Protocol/FormBrowserEx2.h +++ b/MdeModulePkg/Include/Protocol/FormBrowserEx2.h @@ -15,7 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL_GUID \ { 0xa770c357, 0xb693, 0x4e6d, { 0xa6, 0xcf, 0xd2, 0x1c, 0x72, 0x8e, 0x55, 0xb }} -typedef struct _EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL; +typedef struct _EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL; #define BROWSER_EXTENSION2_VERSION_1 0x10000 #define BROWSER_EXTENSION2_VERSION_1_1 0x10001 @@ -29,7 +29,7 @@ typedef struct _EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL EDKII_FORM_BROWSER_EXTE **/ typedef BOOLEAN -(EFIAPI *IS_BROWSER_DATA_MODIFIED) ( +(EFIAPI *IS_BROWSER_DATA_MODIFIED)( VOID ); @@ -44,7 +44,7 @@ BOOLEAN **/ typedef EFI_STATUS -(EFIAPI *EXECUTE_ACTION) ( +(EFIAPI *EXECUTE_ACTION)( IN UINT32 Action, IN UINT16 DefaultId ); @@ -58,35 +58,35 @@ EFI_STATUS **/ typedef BOOLEAN -(EFIAPI *IS_RESET_REQUIRED) ( +(EFIAPI *IS_RESET_REQUIRED)( VOID ); -#define FORM_ENTRY_INFO_SIGNATURE SIGNATURE_32 ('f', 'e', 'i', 's') +#define FORM_ENTRY_INFO_SIGNATURE SIGNATURE_32 ('f', 'e', 'i', 's') typedef struct { - UINTN Signature; - LIST_ENTRY Link; + UINTN Signature; + LIST_ENTRY Link; - EFI_HII_HANDLE HiiHandle; - EFI_GUID FormSetGuid; - EFI_FORM_ID FormId; - EFI_QUESTION_ID QuestionId; + EFI_HII_HANDLE HiiHandle; + EFI_GUID FormSetGuid; + EFI_FORM_ID FormId; + EFI_QUESTION_ID QuestionId; } FORM_ENTRY_INFO; #define FORM_ENTRY_INFO_FROM_LINK(a) CR (a, FORM_ENTRY_INFO, Link, FORM_ENTRY_INFO_SIGNATURE) -#define FORM_QUESTION_ATTRIBUTE_OVERRIDE_SIGNATURE SIGNATURE_32 ('f', 'q', 'o', 's') +#define FORM_QUESTION_ATTRIBUTE_OVERRIDE_SIGNATURE SIGNATURE_32 ('f', 'q', 'o', 's') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - - EFI_QUESTION_ID QuestionId; // Find the question - EFI_FORM_ID FormId; // Find the form - EFI_GUID FormSetGuid; // Find the formset. - EFI_HII_HANDLE HiiHandle; // Find the HII handle - UINT32 Attribute; // Hide or grayout ... + UINTN Signature; + LIST_ENTRY Link; + + EFI_QUESTION_ID QuestionId; // Find the question + EFI_FORM_ID FormId; // Find the form + EFI_GUID FormSetGuid; // Find the formset. + EFI_HII_HANDLE HiiHandle; // Find the HII handle + UINT32 Attribute; // Hide or grayout ... } QUESTION_ATTRIBUTE_OVERRIDE; #define FORM_QUESTION_ATTRIBUTE_OVERRIDE_FROM_LINK(a) CR (a, QUESTION_ATTRIBUTE_OVERRIDE, Link, FORM_QUESTION_ATTRIBUTE_OVERRIDE_SIGNATURE) @@ -95,25 +95,24 @@ struct _EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL { /// /// Version for protocol future extension. /// - UINT32 Version; - SET_SCOPE SetScope; - REGISTER_HOT_KEY RegisterHotKey; - REGISTER_EXIT_HANDLER RegiserExitHandler; - IS_BROWSER_DATA_MODIFIED IsBrowserDataModified; - EXECUTE_ACTION ExecuteAction; + UINT32 Version; + SET_SCOPE SetScope; + REGISTER_HOT_KEY RegisterHotKey; + REGISTER_EXIT_HANDLER RegiserExitHandler; + IS_BROWSER_DATA_MODIFIED IsBrowserDataModified; + EXECUTE_ACTION ExecuteAction; /// /// A list of type FORMID_INFO is Browser View Form History List. /// - LIST_ENTRY FormViewHistoryHead; + LIST_ENTRY FormViewHistoryHead; /// /// A list of type QUESTION_ATTRIBUTE_OVERRIDE. /// - LIST_ENTRY OverrideQestListHead; + LIST_ENTRY OverrideQestListHead; - IS_RESET_REQUIRED IsResetRequired; + IS_RESET_REQUIRED IsResetRequired; }; -extern EFI_GUID gEdkiiFormBrowserEx2ProtocolGuid; +extern EFI_GUID gEdkiiFormBrowserEx2ProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/GenericMemoryTest.h b/MdeModulePkg/Include/Protocol/GenericMemoryTest.h index 08157f35f5..00cf6016be 100644 --- a/MdeModulePkg/Include/Protocol/GenericMemoryTest.h +++ b/MdeModulePkg/Include/Protocol/GenericMemoryTest.h @@ -12,7 +12,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_GENERIC_MEMORY_TEST_PROTOCOL_GUID \ { 0x309de7f1, 0x7f5e, 0x4ace, {0xb4, 0x9c, 0x53, 0x1b, 0xe5, 0xaa, 0x95, 0xef} } -typedef struct _EFI_GENERIC_MEMORY_TEST_PROTOCOL EFI_GENERIC_MEMORY_TEST_PROTOCOL; +typedef struct _EFI_GENERIC_MEMORY_TEST_PROTOCOL EFI_GENERIC_MEMORY_TEST_PROTOCOL; /// /// Memory test coverage level. @@ -26,7 +26,6 @@ typedef enum { MAXLEVEL } EXTENDMEM_COVERAGE_LEVEL; - /** Initialize the generic memory test. @@ -46,7 +45,6 @@ EFI_STATUS OUT BOOLEAN *RequireSoftECCInit ); - /** Perform the memory test. @@ -72,7 +70,6 @@ EFI_STATUS IN BOOLEAN IfTestAbort ); - /** Finish the memory test. @@ -108,13 +105,12 @@ EFI_STATUS ); struct _EFI_GENERIC_MEMORY_TEST_PROTOCOL { - EFI_MEMORY_TEST_INIT MemoryTestInit; - EFI_PERFORM_MEMORY_TEST PerformMemoryTest; - EFI_MEMORY_TEST_FINISHED Finished; - EFI_MEMORY_TEST_COMPATIBLE_RANGE CompatibleRangeTest; + EFI_MEMORY_TEST_INIT MemoryTestInit; + EFI_PERFORM_MEMORY_TEST PerformMemoryTest; + EFI_MEMORY_TEST_FINISHED Finished; + EFI_MEMORY_TEST_COMPATIBLE_RANGE CompatibleRangeTest; }; -extern EFI_GUID gEfiGenericMemTestProtocolGuid; +extern EFI_GUID gEfiGenericMemTestProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/IoMmu.h b/MdeModulePkg/Include/Protocol/IoMmu.h index 3fd35b8b04..f14ed96516 100644 --- a/MdeModulePkg/Include/Protocol/IoMmu.h +++ b/MdeModulePkg/Include/Protocol/IoMmu.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __IOMMU_H__ #define __IOMMU_H__ @@ -21,14 +20,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EDKII_IOMMU_PROTOCOL EDKII_IOMMU_PROTOCOL; +typedef struct _EDKII_IOMMU_PROTOCOL EDKII_IOMMU_PROTOCOL; // // Revision The revision to which the IOMMU interface adheres. // All future revisions must be backwards compatible. // If a future version is not back wards compatible it is not the same GUID. // -#define EDKII_IOMMU_PROTOCOL_REVISION 0x00010000 +#define EDKII_IOMMU_PROTOCOL_REVISION 0x00010000 // // IOMMU Access for SetAttribute @@ -80,13 +79,13 @@ typedef enum { // IOMMU attribute for AllocateBuffer // Any undefined bits are reserved and must be zero. // -#define EDKII_IOMMU_ATTRIBUTE_MEMORY_WRITE_COMBINE 0x0080 -#define EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED 0x0800 -#define EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE 0x8000 +#define EDKII_IOMMU_ATTRIBUTE_MEMORY_WRITE_COMBINE 0x0080 +#define EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED 0x0800 +#define EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE 0x8000 -#define EDKII_IOMMU_ATTRIBUTE_VALID_FOR_ALLOCATE_BUFFER (EDKII_IOMMU_ATTRIBUTE_MEMORY_WRITE_COMBINE | EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED | EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) +#define EDKII_IOMMU_ATTRIBUTE_VALID_FOR_ALLOCATE_BUFFER (EDKII_IOMMU_ATTRIBUTE_MEMORY_WRITE_COMBINE | EDKII_IOMMU_ATTRIBUTE_MEMORY_CACHED | EDKII_IOMMU_ATTRIBUTE_DUAL_ADDRESS_CYCLE) -#define EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER (~EDKII_IOMMU_ATTRIBUTE_VALID_FOR_ALLOCATE_BUFFER) +#define EDKII_IOMMU_ATTRIBUTE_INVALID_FOR_ALLOCATE_BUFFER (~EDKII_IOMMU_ATTRIBUTE_VALID_FOR_ALLOCATE_BUFFER) /** Set IOMMU attribute for a system memory. @@ -237,17 +236,17 @@ EFI_STATUS /// IOMMU Protocol structure. /// struct _EDKII_IOMMU_PROTOCOL { - UINT64 Revision; - EDKII_IOMMU_SET_ATTRIBUTE SetAttribute; - EDKII_IOMMU_MAP Map; - EDKII_IOMMU_UNMAP Unmap; - EDKII_IOMMU_ALLOCATE_BUFFER AllocateBuffer; - EDKII_IOMMU_FREE_BUFFER FreeBuffer; + UINT64 Revision; + EDKII_IOMMU_SET_ATTRIBUTE SetAttribute; + EDKII_IOMMU_MAP Map; + EDKII_IOMMU_UNMAP Unmap; + EDKII_IOMMU_ALLOCATE_BUFFER AllocateBuffer; + EDKII_IOMMU_FREE_BUFFER FreeBuffer; }; /// /// IOMMU Protocol GUID variable. /// -extern EFI_GUID gEdkiiIoMmuProtocolGuid; +extern EFI_GUID gEdkiiIoMmuProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/IpmiProtocol.h b/MdeModulePkg/Include/Protocol/IpmiProtocol.h index 41db3bcbbf..61083b0352 100644 --- a/MdeModulePkg/Include/Protocol/IpmiProtocol.h +++ b/MdeModulePkg/Include/Protocol/IpmiProtocol.h @@ -21,7 +21,6 @@ typedef struct _IPMI_PROTOCOL IPMI_PROTOCOL; 0x5169af60, 0x8c5a, 0x4243, 0xb3, 0xe9, 0x56, 0xc5, 0x6d, 0x18, 0xee, 0x26 \ } - /** This service enables submitting commands via Ipmi. @@ -43,24 +42,24 @@ typedef struct _IPMI_PROTOCOL IPMI_PROTOCOL; **/ typedef EFI_STATUS -(EFIAPI *IPMI_SUBMIT_COMMAND) ( +(EFIAPI *IPMI_SUBMIT_COMMAND)( IN IPMI_PROTOCOL *This, IN UINT8 NetFunction, IN UINT8 Command, IN UINT8 *RequestData, IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, + OUT UINT8 *ResponseData, IN OUT UINT32 *ResponseDataSize ); // // IPMI COMMAND PROTOCOL // -struct _IPMI_PROTOCOL{ - IPMI_SUBMIT_COMMAND IpmiSubmitCommand; +struct _IPMI_PROTOCOL { + IPMI_SUBMIT_COMMAND IpmiSubmitCommand; }; -extern EFI_GUID gIpmiProtocolGuid; -extern EFI_GUID gSmmIpmiProtocolGuid; +extern EFI_GUID gIpmiProtocolGuid; +extern EFI_GUID gSmmIpmiProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/LoadPe32Image.h b/MdeModulePkg/Include/Protocol/LoadPe32Image.h index f71e92ca0b..514942890e 100644 --- a/MdeModulePkg/Include/Protocol/LoadPe32Image.h +++ b/MdeModulePkg/Include/Protocol/LoadPe32Image.h @@ -18,7 +18,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION 0x01 #define EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION 0x02 -typedef struct _EFI_PE32_IMAGE_PROTOCOL EFI_PE32_IMAGE_PROTOCOL; +typedef struct _EFI_PE32_IMAGE_PROTOCOL EFI_PE32_IMAGE_PROTOCOL; /** @@ -87,11 +87,10 @@ EFI_STATUS ); struct _EFI_PE32_IMAGE_PROTOCOL { - LOAD_PE_IMAGE LoadPeImage; - UNLOAD_PE_IMAGE UnLoadPeImage; + LOAD_PE_IMAGE LoadPeImage; + UNLOAD_PE_IMAGE UnLoadPeImage; }; -extern EFI_GUID gEfiLoadPeImageProtocolGuid; +extern EFI_GUID gEfiLoadPeImageProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/LockBox.h b/MdeModulePkg/Include/Protocol/LockBox.h index 9453650ef2..4c6e28c0ec 100644 --- a/MdeModulePkg/Include/Protocol/LockBox.h +++ b/MdeModulePkg/Include/Protocol/LockBox.h @@ -19,6 +19,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define EFI_LOCK_BOX_PROTOCOL_GUID \ { 0xbd445d79, 0xb7ad, 0x4f04, { 0x9a, 0xd8, 0x29, 0xbd, 0x20, 0x40, 0xeb, 0x3c }} -extern EFI_GUID gEfiLockBoxProtocolGuid; +extern EFI_GUID gEfiLockBoxProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/NonDiscoverableDevice.h b/MdeModulePkg/Include/Protocol/NonDiscoverableDevice.h index 53ab804f32..2399e6fdc1 100644 --- a/MdeModulePkg/Include/Protocol/NonDiscoverableDevice.h +++ b/MdeModulePkg/Include/Protocol/NonDiscoverableDevice.h @@ -43,7 +43,7 @@ typedef enum { **/ typedef EFI_STATUS -(EFIAPI *NON_DISCOVERABLE_DEVICE_INIT) ( +(EFIAPI *NON_DISCOVERABLE_DEVICE_INIT)( IN NON_DISCOVERABLE_DEVICE *This ); @@ -51,21 +51,21 @@ struct _NON_DISCOVERABLE_DEVICE { // // The type of device // - CONST EFI_GUID *Type; + CONST EFI_GUID *Type; // // Whether this device is DMA coherent // - NON_DISCOVERABLE_DEVICE_DMA_TYPE DmaType; + NON_DISCOVERABLE_DEVICE_DMA_TYPE DmaType; // // Initialization function for the device // - NON_DISCOVERABLE_DEVICE_INIT Initialize; + NON_DISCOVERABLE_DEVICE_INIT Initialize; // // The MMIO and I/O regions owned by the device // - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Resources; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Resources; }; -extern EFI_GUID gEdkiiNonDiscoverableDeviceProtocolGuid; +extern EFI_GUID gEdkiiNonDiscoverableDeviceProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/PeCoffImageEmulator.h b/MdeModulePkg/Include/Protocol/PeCoffImageEmulator.h index c7f287d776..ca6c94b26c 100644 --- a/MdeModulePkg/Include/Protocol/PeCoffImageEmulator.h +++ b/MdeModulePkg/Include/Protocol/PeCoffImageEmulator.h @@ -27,7 +27,7 @@ typedef struct _EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL EDKII_PECOFF_IMAGE_EMULATOR **/ typedef BOOLEAN -(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_IS_IMAGE_SUPPORTED) ( +(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_IS_IMAGE_SUPPORTED)( IN EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *This, IN UINT16 ImageType, IN EFI_DEVICE_PATH_PROTOCOL *DevicePath OPTIONAL @@ -57,7 +57,7 @@ BOOLEAN **/ typedef EFI_STATUS -(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_REGISTER_IMAGE) ( +(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_REGISTER_IMAGE)( IN EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *This, IN EFI_PHYSICAL_ADDRESS ImageBase, IN UINT64 ImageSize, @@ -77,12 +77,12 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_UNREGISTER_IMAGE) ( +(EFIAPI *EDKII_PECOFF_IMAGE_EMULATOR_UNREGISTER_IMAGE)( IN EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL *This, IN EFI_PHYSICAL_ADDRESS ImageBase ); -#define EDKII_PECOFF_IMAGE_EMULATOR_VERSION 0x1 +#define EDKII_PECOFF_IMAGE_EMULATOR_VERSION 0x1 typedef struct _EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL { EDKII_PECOFF_IMAGE_EMULATOR_IS_IMAGE_SUPPORTED IsImageSupported; @@ -95,6 +95,6 @@ typedef struct _EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL { UINT16 MachineType; } EDKII_PECOFF_IMAGE_EMULATOR_PROTOCOL; -extern EFI_GUID gEdkiiPeCoffImageEmulatorProtocolGuid; +extern EFI_GUID gEdkiiPeCoffImageEmulatorProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/PlatformBootManager.h b/MdeModulePkg/Include/Protocol/PlatformBootManager.h index 26b9ce48ad..e527b0ee0e 100644 --- a/MdeModulePkg/Include/Protocol/PlatformBootManager.h +++ b/MdeModulePkg/Include/Protocol/PlatformBootManager.h @@ -29,7 +29,7 @@ typedef struct _EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL EDKII_PLATFORM_BOOT_MANAGER // All future revisions must be backwards compatible. // If a future version is not back wards compatible it is not the same GUID. // -#define EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL_REVISION 0x00000001 +#define EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL_REVISION 0x00000001 // // Function Prototypes @@ -65,7 +65,7 @@ typedef struct _EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL EDKII_PLATFORM_BOOT_MANAGER */ typedef EFI_STATUS -(EFIAPI *PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS) ( +(EFIAPI *PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS)( IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, IN CONST UINTN BootOptionsCount, OUT EFI_BOOT_MANAGER_LOAD_OPTION **UpdatedBootOptions, @@ -73,10 +73,10 @@ EFI_STATUS ); struct _EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL { - UINT64 Revision; - PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS RefreshAllBootOptions; + UINT64 Revision; + PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS RefreshAllBootOptions; }; -extern EFI_GUID gEdkiiPlatformBootManagerProtocolGuid; +extern EFI_GUID gEdkiiPlatformBootManagerProtocolGuid; #endif /* __PLATFORM_BOOT_MANAGER_PROTOCOL_H__ */ diff --git a/MdeModulePkg/Include/Protocol/PlatformLogo.h b/MdeModulePkg/Include/Protocol/PlatformLogo.h index 55c9e08696..08e1dc35a4 100644 --- a/MdeModulePkg/Include/Protocol/PlatformLogo.h +++ b/MdeModulePkg/Include/Protocol/PlatformLogo.h @@ -50,18 +50,16 @@ EFI_STATUS (EFIAPI *EDKII_PLATFORM_LOGO_GET_IMAGE)( IN EDKII_PLATFORM_LOGO_PROTOCOL *This, IN OUT UINT32 *Instance, - OUT EFI_IMAGE_INPUT *Image, - OUT EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE *Attribute, - OUT INTN *OffsetX, - OUT INTN *OffsetY + OUT EFI_IMAGE_INPUT *Image, + OUT EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE *Attribute, + OUT INTN *OffsetX, + OUT INTN *OffsetY ); - struct _EDKII_PLATFORM_LOGO_PROTOCOL { - EDKII_PLATFORM_LOGO_GET_IMAGE GetImage; + EDKII_PLATFORM_LOGO_GET_IMAGE GetImage; }; - -extern EFI_GUID gEdkiiPlatformLogoProtocolGuid; +extern EFI_GUID gEdkiiPlatformLogoProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/PlatformSpecificResetFilter.h b/MdeModulePkg/Include/Protocol/PlatformSpecificResetFilter.h index 4a55a3a4d7..482be1eb98 100644 --- a/MdeModulePkg/Include/Protocol/PlatformSpecificResetFilter.h +++ b/MdeModulePkg/Include/Protocol/PlatformSpecificResetFilter.h @@ -18,8 +18,8 @@ #define EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PROTOCOL_GUID \ { 0x695d7835, 0x8d47, 0x4c11, { 0xab, 0x22, 0xfa, 0x8a, 0xcc, 0xe7, 0xae, 0x7a } } -typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PROTOCOL; +typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_FILTER_PROTOCOL; -extern EFI_GUID gEdkiiPlatformSpecificResetFilterProtocolGuid; +extern EFI_GUID gEdkiiPlatformSpecificResetFilterProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/PlatformSpecificResetHandler.h b/MdeModulePkg/Include/Protocol/PlatformSpecificResetHandler.h index a2e936b8d2..11dede469c 100644 --- a/MdeModulePkg/Include/Protocol/PlatformSpecificResetHandler.h +++ b/MdeModulePkg/Include/Protocol/PlatformSpecificResetHandler.h @@ -16,8 +16,8 @@ #define EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL_GUID \ { 0x2df6ba0b, 0x7092, 0x440d, { 0xbd, 0x4, 0xfb, 0x9, 0x1e, 0xc3, 0xf3, 0xc1 } } -typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL; +typedef EFI_RESET_NOTIFICATION_PROTOCOL EDKII_PLATFORM_SPECIFIC_RESET_HANDLER_PROTOCOL; -extern EFI_GUID gEdkiiPlatformSpecificResetHandlerProtocolGuid; +extern EFI_GUID gEdkiiPlatformSpecificResetHandlerProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/Print2.h b/MdeModulePkg/Include/Protocol/Print2.h index 9f15d59908..1e10a04be2 100644 --- a/MdeModulePkg/Include/Protocol/Print2.h +++ b/MdeModulePkg/Include/Protocol/Print2.h @@ -18,7 +18,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EFI_PRINT2_PROTOCOL EFI_PRINT2_PROTOCOL; +typedef struct _EFI_PRINT2_PROTOCOL EFI_PRINT2_PROTOCOL; /** Produces a Null-terminated Unicode string in an output buffer based on @@ -496,20 +496,19 @@ UINTN ); struct _EFI_PRINT2_PROTOCOL { - UNICODE_BS_PRINT UnicodeBSPrint; - UNICODE_S_PRINT UnicodeSPrint; - UNICODE_BS_PRINT_ASCII_FORMAT UnicodeBSPrintAsciiFormat; - UNICODE_S_PRINT_ASCII_FORMAT UnicodeSPrintAsciiFormat; - UNICODE_VALUE_TO_STRING UnicodeValueToString; - ASCII_BS_PRINT AsciiBSPrint; - ASCII_S_PRINT AsciiSPrint; - ASCII_BS_PRINT_UNICODE_FORMAT AsciiBSPrintUnicodeFormat; - ASCII_S_PRINT_UNICODE_FORMAT AsciiSPrintUnicodeFormat; - ASCII_VALUE_TO_STRING AsciiValueToString; + UNICODE_BS_PRINT UnicodeBSPrint; + UNICODE_S_PRINT UnicodeSPrint; + UNICODE_BS_PRINT_ASCII_FORMAT UnicodeBSPrintAsciiFormat; + UNICODE_S_PRINT_ASCII_FORMAT UnicodeSPrintAsciiFormat; + UNICODE_VALUE_TO_STRING UnicodeValueToString; + ASCII_BS_PRINT AsciiBSPrint; + ASCII_S_PRINT AsciiSPrint; + ASCII_BS_PRINT_UNICODE_FORMAT AsciiBSPrintUnicodeFormat; + ASCII_S_PRINT_UNICODE_FORMAT AsciiSPrintUnicodeFormat; + ASCII_VALUE_TO_STRING AsciiValueToString; }; -extern EFI_GUID gEfiPrint2ProtocolGuid; - +extern EFI_GUID gEfiPrint2ProtocolGuid; #define EFI_PRINT2S_PROTOCOL_GUID \ { 0xcc252d2, 0xc106, 0x4661, { 0xb5, 0xbd, 0x31, 0x47, 0xa4, 0xf8, 0x1f, 0x92 } } @@ -517,7 +516,7 @@ extern EFI_GUID gEfiPrint2ProtocolGuid; // // Forward reference for pure ANSI compatability // -typedef struct _EFI_PRINT2S_PROTOCOL EFI_PRINT2S_PROTOCOL; +typedef struct _EFI_PRINT2S_PROTOCOL EFI_PRINT2S_PROTOCOL; /** Converts a decimal value to a Null-terminated Unicode string. @@ -640,18 +639,18 @@ RETURN_STATUS ); struct _EFI_PRINT2S_PROTOCOL { - UNICODE_BS_PRINT UnicodeBSPrint; - UNICODE_S_PRINT UnicodeSPrint; - UNICODE_BS_PRINT_ASCII_FORMAT UnicodeBSPrintAsciiFormat; - UNICODE_S_PRINT_ASCII_FORMAT UnicodeSPrintAsciiFormat; - UNICODE_VALUE_TO_STRING_S UnicodeValueToStringS; - ASCII_BS_PRINT AsciiBSPrint; - ASCII_S_PRINT AsciiSPrint; - ASCII_BS_PRINT_UNICODE_FORMAT AsciiBSPrintUnicodeFormat; - ASCII_S_PRINT_UNICODE_FORMAT AsciiSPrintUnicodeFormat; - ASCII_VALUE_TO_STRING_S AsciiValueToStringS; + UNICODE_BS_PRINT UnicodeBSPrint; + UNICODE_S_PRINT UnicodeSPrint; + UNICODE_BS_PRINT_ASCII_FORMAT UnicodeBSPrintAsciiFormat; + UNICODE_S_PRINT_ASCII_FORMAT UnicodeSPrintAsciiFormat; + UNICODE_VALUE_TO_STRING_S UnicodeValueToStringS; + ASCII_BS_PRINT AsciiBSPrint; + ASCII_S_PRINT AsciiSPrint; + ASCII_BS_PRINT_UNICODE_FORMAT AsciiBSPrintUnicodeFormat; + ASCII_S_PRINT_UNICODE_FORMAT AsciiSPrintUnicodeFormat; + ASCII_VALUE_TO_STRING_S AsciiValueToStringS; }; -extern EFI_GUID gEfiPrint2SProtocolGuid; +extern EFI_GUID gEfiPrint2SProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/Ps2Policy.h b/MdeModulePkg/Include/Protocol/Ps2Policy.h index 35ff6e074a..2f73b3d559 100644 --- a/MdeModulePkg/Include/Protocol/Ps2Policy.h +++ b/MdeModulePkg/Include/Protocol/Ps2Policy.h @@ -6,7 +6,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _PS2_POLICY_PROTOCOL_H_ #define _PS2_POLICY_PROTOCOL_H_ @@ -15,21 +14,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0x4df19259, 0xdc71, 0x4d46, {0xbe, 0xf1, 0x35, 0x7b, 0xb5, 0x78, 0xc4, 0x18 } \ } -#define EFI_KEYBOARD_CAPSLOCK 0x0004 -#define EFI_KEYBOARD_NUMLOCK 0x0002 -#define EFI_KEYBOARD_SCROLLLOCK 0x0001 +#define EFI_KEYBOARD_CAPSLOCK 0x0004 +#define EFI_KEYBOARD_NUMLOCK 0x0002 +#define EFI_KEYBOARD_SCROLLLOCK 0x0001 typedef EFI_STATUS -(EFIAPI *EFI_PS2_INIT_HARDWARE) ( +(EFIAPI *EFI_PS2_INIT_HARDWARE)( IN EFI_HANDLE Handle ); typedef struct { - UINT8 KeyboardLight; - EFI_PS2_INIT_HARDWARE Ps2InitHardware; + UINT8 KeyboardLight; + EFI_PS2_INIT_HARDWARE Ps2InitHardware; } EFI_PS2_POLICY_PROTOCOL; -extern EFI_GUID gEfiPs2PolicyProtocolGuid; +extern EFI_GUID gEfiPs2PolicyProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SdMmcOverride.h b/MdeModulePkg/Include/Protocol/SdMmcOverride.h index d44027260a..4fd12b9ad4 100644 --- a/MdeModulePkg/Include/Protocol/SdMmcOverride.h +++ b/MdeModulePkg/Include/Protocol/SdMmcOverride.h @@ -16,16 +16,16 @@ #define EDKII_SD_MMC_OVERRIDE_PROTOCOL_GUID \ { 0xeaf9e3c1, 0xc9cd, 0x46db, { 0xa5, 0xe5, 0x5a, 0x12, 0x4c, 0x83, 0x23, 0x23 } } -#define EDKII_SD_MMC_OVERRIDE_PROTOCOL_VERSION 0x3 +#define EDKII_SD_MMC_OVERRIDE_PROTOCOL_VERSION 0x3 typedef struct _EDKII_SD_MMC_OVERRIDE EDKII_SD_MMC_OVERRIDE; -#define EDKII_SD_MMC_BUS_WIDTH_IGNORE MAX_UINT8 -#define EDKII_SD_MMC_CLOCK_FREQ_IGNORE MAX_UINT32 +#define EDKII_SD_MMC_BUS_WIDTH_IGNORE MAX_UINT8 +#define EDKII_SD_MMC_CLOCK_FREQ_IGNORE MAX_UINT32 #define EDKII_SD_MMC_DRIVER_STRENGTH_IGNORE MAX_UINT8 typedef enum { - SdDriverStrengthTypeB = 0, + SdDriverStrengthTypeB = 0, SdDriverStrengthTypeA, SdDriverStrengthTypeC, SdDriverStrengthTypeD, @@ -33,7 +33,7 @@ typedef enum { } SD_DRIVER_STRENGTH_TYPE; typedef enum { - EmmcDriverStrengthType0 = 0, + EmmcDriverStrengthType0 = 0, EmmcDriverStrengthType1, EmmcDriverStrengthType2, EmmcDriverStrengthType3, @@ -52,20 +52,20 @@ typedef struct { // or specifies unsupported width driver will choose highest supported // bus width for a given mode. // - UINT8 BusWidth; + UINT8 BusWidth; // // The target clock frequency of the bus in MHz. If user tells driver to ignore // it or specifies unsupported frequency driver will choose highest supported // clock frequency for a given mode. // - UINT32 ClockFreq; + UINT32 ClockFreq; // // The target driver strength of the bus. If user tells driver to // ignore it or specifies unsupported driver strength, driver will // default to Type0 for eMMC cards and TypeB for SD cards. Driver strength // setting is only considered if chosen bus timing supports them. // - EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; + EDKII_SD_MMC_DRIVER_STRENGTH DriverStrength; } EDKII_SD_MMC_OPERATING_PARAMETERS; typedef enum { @@ -109,7 +109,7 @@ typedef enum { **/ typedef EFI_STATUS -(EFIAPI * EDKII_SD_MMC_CAPABILITY) ( +(EFIAPI *EDKII_SD_MMC_CAPABILITY)( IN EFI_HANDLE ControllerHandle, IN UINT8 Slot, IN OUT VOID *SdMmcHcSlotCapability, @@ -133,7 +133,7 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * EDKII_SD_MMC_NOTIFY_PHASE) ( +(EFIAPI *EDKII_SD_MMC_NOTIFY_PHASE)( IN EFI_HANDLE ControllerHandle, IN UINT8 Slot, IN EDKII_SD_MMC_PHASE_TYPE PhaseType, @@ -144,17 +144,17 @@ struct _EDKII_SD_MMC_OVERRIDE { // // Protocol version of this implementation // - UINTN Version; + UINTN Version; // // Callback to override SD/MMC host controller capability bits // - EDKII_SD_MMC_CAPABILITY Capability; + EDKII_SD_MMC_CAPABILITY Capability; // // Callback to invoke SD/MMC override hooks // - EDKII_SD_MMC_NOTIFY_PHASE NotifyPhase; + EDKII_SD_MMC_NOTIFY_PHASE NotifyPhase; }; -extern EFI_GUID gEdkiiSdMmcOverrideProtocolGuid; +extern EFI_GUID gEdkiiSdMmcOverrideProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmExitBootServices.h b/MdeModulePkg/Include/Protocol/SmmExitBootServices.h index 27d8b5e6f5..ec8e754946 100644 --- a/MdeModulePkg/Include/Protocol/SmmExitBootServices.h +++ b/MdeModulePkg/Include/Protocol/SmmExitBootServices.h @@ -18,6 +18,6 @@ 0x296eb418, 0xc4c8, 0x4e05, { 0xab, 0x59, 0x39, 0xe8, 0xaf, 0x56, 0xf0, 0xa } \ } -extern EFI_GUID gEdkiiSmmExitBootServicesProtocolGuid; +extern EFI_GUID gEdkiiSmmExitBootServicesProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmFaultTolerantWrite.h b/MdeModulePkg/Include/Protocol/SmmFaultTolerantWrite.h index 63bc3a16cd..39fc0cbb4e 100644 --- a/MdeModulePkg/Include/Protocol/SmmFaultTolerantWrite.h +++ b/MdeModulePkg/Include/Protocol/SmmFaultTolerantWrite.h @@ -27,6 +27,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // typedef EFI_FAULT_TOLERANT_WRITE_PROTOCOL EFI_SMM_FAULT_TOLERANT_WRITE_PROTOCOL; -extern EFI_GUID gEfiSmmFaultTolerantWriteProtocolGuid; +extern EFI_GUID gEfiSmmFaultTolerantWriteProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmFirmwareVolumeBlock.h b/MdeModulePkg/Include/Protocol/SmmFirmwareVolumeBlock.h index d18c2dc11a..032b5cba41 100644 --- a/MdeModulePkg/Include/Protocol/SmmFirmwareVolumeBlock.h +++ b/MdeModulePkg/Include/Protocol/SmmFirmwareVolumeBlock.h @@ -25,6 +25,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // typedef EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL EFI_SMM_FIRMWARE_VOLUME_BLOCK_PROTOCOL; -extern EFI_GUID gEfiSmmFirmwareVolumeBlockProtocolGuid; +extern EFI_GUID gEfiSmmFirmwareVolumeBlockProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmLegacyBoot.h b/MdeModulePkg/Include/Protocol/SmmLegacyBoot.h index ecff9ab41f..4f415cccf8 100644 --- a/MdeModulePkg/Include/Protocol/SmmLegacyBoot.h +++ b/MdeModulePkg/Include/Protocol/SmmLegacyBoot.h @@ -17,6 +17,6 @@ 0x85a8ab57, 0x644, 0x4110, { 0x85, 0xf, 0x98, 0x13, 0x22, 0x4, 0x70, 0x70 } \ } -extern EFI_GUID gEdkiiSmmLegacyBootProtocolGuid; +extern EFI_GUID gEdkiiSmmLegacyBootProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmMemoryAttribute.h b/MdeModulePkg/Include/Protocol/SmmMemoryAttribute.h index 7e45fb907c..0a8b251dd4 100644 --- a/MdeModulePkg/Include/Protocol/SmmMemoryAttribute.h +++ b/MdeModulePkg/Include/Protocol/SmmMemoryAttribute.h @@ -10,7 +10,7 @@ #ifndef __SMM_MEMORYATTRIBUTE_H__ #define __SMM_MEMORYATTRIBUTE_H__ -//{69B792EA-39CE-402D-A2A6-F721DE351DFE} +// {69B792EA-39CE-402D-A2A6-F721DE351DFE} #define EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL_GUID \ { \ 0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } \ @@ -117,11 +117,11 @@ EFI_STATUS /// attribute of memory in the EFI SMM environment. /// struct _EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL { - EDKII_SMM_GET_MEMORY_ATTRIBUTES GetMemoryAttributes; - EDKII_SMM_SET_MEMORY_ATTRIBUTES SetMemoryAttributes; - EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES ClearMemoryAttributes; + EDKII_SMM_GET_MEMORY_ATTRIBUTES GetMemoryAttributes; + EDKII_SMM_SET_MEMORY_ATTRIBUTES SetMemoryAttributes; + EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES ClearMemoryAttributes; }; -extern EFI_GUID gEdkiiSmmMemoryAttributeProtocolGuid; +extern EFI_GUID gEdkiiSmmMemoryAttributeProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmReadyToBoot.h b/MdeModulePkg/Include/Protocol/SmmReadyToBoot.h index 0b499529af..5603050977 100644 --- a/MdeModulePkg/Include/Protocol/SmmReadyToBoot.h +++ b/MdeModulePkg/Include/Protocol/SmmReadyToBoot.h @@ -18,6 +18,6 @@ 0x6e057ecf, 0xfa99, 0x4f39, { 0x95, 0xbc, 0x59, 0xf9, 0x92, 0x1d, 0x17, 0xe4 } \ } -extern EFI_GUID gEdkiiSmmReadyToBootProtocolGuid; +extern EFI_GUID gEdkiiSmmReadyToBootProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmSwapAddressRange.h b/MdeModulePkg/Include/Protocol/SmmSwapAddressRange.h index d2c9fc554a..80697e171f 100644 --- a/MdeModulePkg/Include/Protocol/SmmSwapAddressRange.h +++ b/MdeModulePkg/Include/Protocol/SmmSwapAddressRange.h @@ -29,6 +29,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // typedef EFI_SWAP_ADDRESS_RANGE_PROTOCOL EFI_SMM_SWAP_ADDRESS_RANGE_PROTOCOL; -extern EFI_GUID gEfiSmmSwapAddressRangeProtocolGuid; +extern EFI_GUID gEfiSmmSwapAddressRangeProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SmmVarCheck.h b/MdeModulePkg/Include/Protocol/SmmVarCheck.h index 269a407fc6..4b601f2cad 100644 --- a/MdeModulePkg/Include/Protocol/SmmVarCheck.h +++ b/MdeModulePkg/Include/Protocol/SmmVarCheck.h @@ -19,12 +19,11 @@ typedef struct _EDKII_SMM_VAR_CHECK_PROTOCOL EDKII_SMM_VAR_CHECK_PROTOCOL; struct _EDKII_SMM_VAR_CHECK_PROTOCOL { - EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER SmmRegisterSetVariableCheckHandler; - EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET SmmVariablePropertySet; - EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET SmmVariablePropertyGet; + EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER SmmRegisterSetVariableCheckHandler; + EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET SmmVariablePropertySet; + EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET SmmVariablePropertyGet; }; -extern EFI_GUID gEdkiiSmmVarCheckProtocolGuid; +extern EFI_GUID gEdkiiSmmVarCheckProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/SmmVariable.h b/MdeModulePkg/Include/Protocol/SmmVariable.h index 9d57343775..7f657082ce 100644 --- a/MdeModulePkg/Include/Protocol/SmmVariable.h +++ b/MdeModulePkg/Include/Protocol/SmmVariable.h @@ -15,19 +15,19 @@ 0xed32d533, 0x99e6, 0x4209, { 0x9c, 0xc0, 0x2d, 0x72, 0xcd, 0xd9, 0x98, 0xa7 } \ } -typedef struct _EFI_SMM_VARIABLE_PROTOCOL EFI_SMM_VARIABLE_PROTOCOL; +typedef struct _EFI_SMM_VARIABLE_PROTOCOL EFI_SMM_VARIABLE_PROTOCOL; /// /// EFI SMM Variable Protocol is intended for use as a means /// to store data in the EFI SMM environment. /// struct _EFI_SMM_VARIABLE_PROTOCOL { - EFI_GET_VARIABLE SmmGetVariable; - EFI_GET_NEXT_VARIABLE_NAME SmmGetNextVariableName; - EFI_SET_VARIABLE SmmSetVariable; - EFI_QUERY_VARIABLE_INFO SmmQueryVariableInfo; + EFI_GET_VARIABLE SmmGetVariable; + EFI_GET_NEXT_VARIABLE_NAME SmmGetNextVariableName; + EFI_SET_VARIABLE SmmSetVariable; + EFI_QUERY_VARIABLE_INFO SmmQueryVariableInfo; }; -extern EFI_GUID gEfiSmmVariableProtocolGuid; +extern EFI_GUID gEfiSmmVariableProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/SwapAddressRange.h b/MdeModulePkg/Include/Protocol/SwapAddressRange.h index fb01dbf3ff..053987767a 100644 --- a/MdeModulePkg/Include/Protocol/SwapAddressRange.h +++ b/MdeModulePkg/Include/Protocol/SwapAddressRange.h @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EFI_SWAP_ADDRESS_RANGE_PROTOCOL EFI_SWAP_ADDRESS_RANGE_PROTOCOL; +typedef struct _EFI_SWAP_ADDRESS_RANGE_PROTOCOL EFI_SWAP_ADDRESS_RANGE_PROTOCOL; #define EFI_UNSUPPORT_LOCK 0 #define EFI_SOFTWARE_LOCK 1 @@ -93,8 +93,6 @@ EFI_STATUS IN BOOLEAN NewSwapState ); - - /** This service checks if a Real Time Clock (RTC) power failure happened. @@ -132,8 +130,6 @@ EFI_STATUS OUT EFI_SWAP_LOCK_CAPABILITY *LockCapability ); - - /** This service is used to acquire or release appointed kind of lock for Swap Address Range operations. @@ -155,14 +151,14 @@ EFI_STATUS ); struct _EFI_SWAP_ADDRESS_RANGE_PROTOCOL { - EFI_GET_RANGE_LOCATION GetRangeLocation; // has output parameters for base and length - EFI_GET_SWAP_STATE GetSwapState; // are ranges swapped or not - EFI_SET_SWAP_STATE SetSwapState; // swap or unswap ranges - EFI_GET_RTC_POWER_STATUS GetRtcPowerStatus; // checks RTC battery, or whatever... - EFI_GET_SWAP_LOCK_CAPABILITY GetSwapLockCapability; // Get TOP_SWAP lock capability, - EFI_SET_SWAP_LOCK SetSwapLock; // Set TOP_SWAP lock state + EFI_GET_RANGE_LOCATION GetRangeLocation; // has output parameters for base and length + EFI_GET_SWAP_STATE GetSwapState; // are ranges swapped or not + EFI_SET_SWAP_STATE SetSwapState; // swap or unswap ranges + EFI_GET_RTC_POWER_STATUS GetRtcPowerStatus; // checks RTC battery, or whatever... + EFI_GET_SWAP_LOCK_CAPABILITY GetSwapLockCapability; // Get TOP_SWAP lock capability, + EFI_SET_SWAP_LOCK SetSwapLock; // Set TOP_SWAP lock state }; -extern EFI_GUID gEfiSwapAddressRangeProtocolGuid; +extern EFI_GUID gEfiSwapAddressRangeProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/UfsHostController.h b/MdeModulePkg/Include/Protocol/UfsHostController.h index ba51938716..e0e00f08fb 100644 --- a/MdeModulePkg/Include/Protocol/UfsHostController.h +++ b/MdeModulePkg/Include/Protocol/UfsHostController.h @@ -7,7 +7,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef __EDKII_UFS_HC_PROTOCOL_H__ #define __EDKII_UFS_HC_PROTOCOL_H__ @@ -22,8 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Forward reference for pure ANSI compatability // -typedef struct _EDKII_UFS_HOST_CONTROLLER_PROTOCOL EDKII_UFS_HOST_CONTROLLER_PROTOCOL; - +typedef struct _EDKII_UFS_HOST_CONTROLLER_PROTOCOL EDKII_UFS_HOST_CONTROLLER_PROTOCOL; /** Get the MMIO base address of UFS host controller. @@ -39,7 +37,7 @@ typedef EFI_STATUS (EFIAPI *EDKII_UFS_HC_GET_MMIO_BAR)( IN EDKII_UFS_HOST_CONTROLLER_PROTOCOL *This, - OUT UINTN *MmioBar + OUT UINTN *MmioBar ); /// @@ -90,8 +88,8 @@ EFI_STATUS IN EDKII_UFS_HOST_CONTROLLER_OPERATION Operation, IN VOID *HostAddress, IN OUT UINTN *NumberOfBytes, - OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, - OUT VOID **Mapping + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping ); /** @@ -138,7 +136,7 @@ EFI_STATUS IN EFI_ALLOCATE_TYPE Type, IN EFI_MEMORY_TYPE MemoryType, IN UINTN Pages, - OUT VOID **HostAddress, + OUT VOID **HostAddress, IN UINT64 Attributes ); @@ -180,7 +178,7 @@ EFI_STATUS ); typedef enum { - EfiUfsHcWidthUint8 = 0, + EfiUfsHcWidthUint8 = 0, EfiUfsHcWidthUint16, EfiUfsHcWidthUint32, EfiUfsHcWidthUint64, @@ -219,19 +217,19 @@ EFI_STATUS /// UFS Host Controller Protocol structure. /// struct _EDKII_UFS_HOST_CONTROLLER_PROTOCOL { - EDKII_UFS_HC_GET_MMIO_BAR GetUfsHcMmioBar; - EDKII_UFS_HC_ALLOCATE_BUFFER AllocateBuffer; - EDKII_UFS_HC_FREE_BUFFER FreeBuffer; - EDKII_UFS_HC_MAP Map; - EDKII_UFS_HC_UNMAP Unmap; - EDKII_UFS_HC_FLUSH Flush; - EDKII_UFS_HC_MMIO_READ_WRITE Read; - EDKII_UFS_HC_MMIO_READ_WRITE Write; + EDKII_UFS_HC_GET_MMIO_BAR GetUfsHcMmioBar; + EDKII_UFS_HC_ALLOCATE_BUFFER AllocateBuffer; + EDKII_UFS_HC_FREE_BUFFER FreeBuffer; + EDKII_UFS_HC_MAP Map; + EDKII_UFS_HC_UNMAP Unmap; + EDKII_UFS_HC_FLUSH Flush; + EDKII_UFS_HC_MMIO_READ_WRITE Read; + EDKII_UFS_HC_MMIO_READ_WRITE Write; }; /// /// UFS Host Controller Protocol GUID variable. /// -extern EFI_GUID gEdkiiUfsHostControllerProtocolGuid; +extern EFI_GUID gEdkiiUfsHostControllerProtocolGuid; #endif diff --git a/MdeModulePkg/Include/Protocol/UfsHostControllerPlatform.h b/MdeModulePkg/Include/Protocol/UfsHostControllerPlatform.h index 0f6732a1f8..faa82d0c4e 100644 --- a/MdeModulePkg/Include/Protocol/UfsHostControllerPlatform.h +++ b/MdeModulePkg/Include/Protocol/UfsHostControllerPlatform.h @@ -11,19 +11,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include -#define EDKII_UFS_HC_PLATFORM_PROTOCOL_VERSION 1 +#define EDKII_UFS_HC_PLATFORM_PROTOCOL_VERSION 1 extern EFI_GUID gEdkiiUfsHcPlatformProtocolGuid; -typedef struct _EDKII_UFS_HC_PLATFORM_PROTOCOL EDKII_UFS_HC_PLATFORM_PROTOCOL; +typedef struct _EDKII_UFS_HC_PLATFORM_PROTOCOL EDKII_UFS_HC_PLATFORM_PROTOCOL; -typedef struct _EDKII_UFS_HC_DRIVER_INTERFACE EDKII_UFS_HC_DRIVER_INTERFACE; +typedef struct _EDKII_UFS_HC_DRIVER_INTERFACE EDKII_UFS_HC_DRIVER_INTERFACE; typedef struct { - UINT32 Opcode; - UINT32 Arg1; - UINT32 Arg2; - UINT32 Arg3; + UINT32 Opcode; + UINT32 Arg1; + UINT32 Arg2; + UINT32 Arg3; } EDKII_UIC_COMMAND; /** @@ -38,25 +38,25 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *EDKII_UFS_EXEC_UIC_COMMAND) ( +(EFIAPI *EDKII_UFS_EXEC_UIC_COMMAND)( IN EDKII_UFS_HC_DRIVER_INTERFACE *This, IN OUT EDKII_UIC_COMMAND *UicCommand -); + ); struct _EDKII_UFS_HC_DRIVER_INTERFACE { /// /// Protocol to accesss host controller MMIO and PCI registers. /// - EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHcProtocol; + EDKII_UFS_HOST_CONTROLLER_PROTOCOL *UfsHcProtocol; /// /// Function implementing UIC command execution. /// - EDKII_UFS_EXEC_UIC_COMMAND UfsExecUicCommand; + EDKII_UFS_EXEC_UIC_COMMAND UfsExecUicCommand; }; typedef struct { - UINT32 Capabilities; - UINT32 Version; + UINT32 Capabilities; + UINT32 Version; } EDKII_UFS_HC_INFO; /** @@ -71,10 +71,10 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI *EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO) ( +(EFIAPI *EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO)( IN EFI_HANDLE ControllerHandle, IN OUT EDKII_UFS_HC_INFO *HcInfo -); + ); typedef enum { EdkiiUfsHcPreHce, @@ -98,27 +98,26 @@ typedef enum { **/ typedef EFI_STATUS -(EFIAPI *EDKII_UFS_HC_PLATFORM_CALLBACK) ( +(EFIAPI *EDKII_UFS_HC_PLATFORM_CALLBACK)( IN EFI_HANDLE ControllerHandle, IN EDKII_UFS_HC_PLATFORM_CALLBACK_PHASE CallbackPhase, IN OUT VOID *CallbackData -); + ); struct _EDKII_UFS_HC_PLATFORM_PROTOCOL { /// /// Version of the protocol. /// - UINT32 Version; + UINT32 Version; /// /// Allows platform driver to override host controller information. /// - EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO OverrideHcInfo; + EDKII_UFS_HC_PLATFORM_OVERRIDE_HC_INFO OverrideHcInfo; /// /// Allows platform driver to implement platform specific flows /// for host controller. /// - EDKII_UFS_HC_PLATFORM_CALLBACK Callback; + EDKII_UFS_HC_PLATFORM_CALLBACK Callback; }; #endif - diff --git a/MdeModulePkg/Include/Protocol/VarCheck.h b/MdeModulePkg/Include/Protocol/VarCheck.h index 013ec6fbbb..bb3db5b2bc 100644 --- a/MdeModulePkg/Include/Protocol/VarCheck.h +++ b/MdeModulePkg/Include/Protocol/VarCheck.h @@ -11,9 +11,9 @@ #include -typedef struct _EDKII_VAR_CHECK_PROTOCOL EDKII_VAR_CHECK_PROTOCOL; +typedef struct _EDKII_VAR_CHECK_PROTOCOL EDKII_VAR_CHECK_PROTOCOL; -#define EDKII_VAR_CHECK_PROTOCOL_GUID { \ +#define EDKII_VAR_CHECK_PROTOCOL_GUID {\ 0xaf23b340, 0x97b4, 0x4685, { 0x8d, 0x4f, 0xa3, 0xf2, 0x81, 0x69, 0xb2, 0x1d } \ }; @@ -36,31 +36,31 @@ typedef EFI_SET_VARIABLE VAR_CHECK_SET_VARIABLE_CHECK_HANDLER; **/ typedef EFI_STATUS -(EFIAPI * EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER) ( +(EFIAPI *EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER)( IN VAR_CHECK_SET_VARIABLE_CHECK_HANDLER Handler ); -#define VAR_CHECK_VARIABLE_PROPERTY_REVISION 0x0001 +#define VAR_CHECK_VARIABLE_PROPERTY_REVISION 0x0001 // // 1. Set by VariableLock PROTOCOL // 2. Set by VarCheck PROTOCOL // // If set, other fields for check will be ignored. // -#define VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY BIT0 +#define VAR_CHECK_VARIABLE_PROPERTY_READ_ONLY BIT0 typedef struct { - UINT16 Revision; - UINT16 Property; - UINT32 Attributes; - UINTN MinSize; - UINTN MaxSize; + UINT16 Revision; + UINT16 Property; + UINT32 Attributes; + UINTN MinSize; + UINTN MaxSize; } VAR_CHECK_VARIABLE_PROPERTY; typedef struct { - EFI_GUID *Guid; - CHAR16 *Name; - VAR_CHECK_VARIABLE_PROPERTY VariableProperty; + EFI_GUID *Guid; + CHAR16 *Name; + VAR_CHECK_VARIABLE_PROPERTY VariableProperty; } VARIABLE_ENTRY_PROPERTY; /** @@ -82,7 +82,7 @@ typedef struct { **/ typedef EFI_STATUS -(EFIAPI * EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET) ( +(EFIAPI *EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET)( IN CHAR16 *Name, IN EFI_GUID *Guid, IN VAR_CHECK_VARIABLE_PROPERTY *VariableProperty @@ -102,19 +102,18 @@ EFI_STATUS **/ typedef EFI_STATUS -(EFIAPI * EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET) ( +(EFIAPI *EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET)( IN CHAR16 *Name, IN EFI_GUID *Guid, OUT VAR_CHECK_VARIABLE_PROPERTY *VariableProperty ); struct _EDKII_VAR_CHECK_PROTOCOL { - EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER RegisterSetVariableCheckHandler; - EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET VariablePropertySet; - EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET VariablePropertyGet; + EDKII_VAR_CHECK_REGISTER_SET_VARIABLE_CHECK_HANDLER RegisterSetVariableCheckHandler; + EDKII_VAR_CHECK_VARIABLE_PROPERTY_SET VariablePropertySet; + EDKII_VAR_CHECK_VARIABLE_PROPERTY_GET VariablePropertyGet; }; -extern EFI_GUID gEdkiiVarCheckProtocolGuid; +extern EFI_GUID gEdkiiVarCheckProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/VariableLock.h b/MdeModulePkg/Include/Protocol/VariableLock.h index eaffd5b104..2d15cc1ca4 100644 --- a/MdeModulePkg/Include/Protocol/VariableLock.h +++ b/MdeModulePkg/Include/Protocol/VariableLock.h @@ -16,7 +16,7 @@ 0xcd3d0a05, 0x9e24, 0x437c, { 0xa8, 0x91, 0x1e, 0xe0, 0x53, 0xdb, 0x76, 0x38 } \ } -typedef struct _EDKII_VARIABLE_LOCK_PROTOCOL EDKII_VARIABLE_LOCK_PROTOCOL; +typedef struct _EDKII_VARIABLE_LOCK_PROTOCOL EDKII_VARIABLE_LOCK_PROTOCOL; /** Mark a variable that will become read-only after leaving the DXE phase of execution. @@ -36,7 +36,7 @@ typedef struct _EDKII_VARIABLE_LOCK_PROTOCOL EDKII_VARIABLE_LOCK_PROTOCOL; **/ typedef EFI_STATUS -(EFIAPI * EDKII_VARIABLE_LOCK_PROTOCOL_REQUEST_TO_LOCK) ( +(EFIAPI *EDKII_VARIABLE_LOCK_PROTOCOL_REQUEST_TO_LOCK)( IN CONST EDKII_VARIABLE_LOCK_PROTOCOL *This, IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid @@ -48,10 +48,9 @@ EFI_STATUS /// EFI_END_OF_DXE_EVENT_GUID is signaled. /// struct _EDKII_VARIABLE_LOCK_PROTOCOL { - EDKII_VARIABLE_LOCK_PROTOCOL_REQUEST_TO_LOCK RequestToLock; + EDKII_VARIABLE_LOCK_PROTOCOL_REQUEST_TO_LOCK RequestToLock; }; -extern EFI_GUID gEdkiiVariableLockProtocolGuid; +extern EFI_GUID gEdkiiVariableLockProtocolGuid; #endif - diff --git a/MdeModulePkg/Include/Protocol/VariablePolicy.h b/MdeModulePkg/Include/Protocol/VariablePolicy.h index 8226c187a7..98d739401f 100644 --- a/MdeModulePkg/Include/Protocol/VariablePolicy.h +++ b/MdeModulePkg/Include/Protocol/VariablePolicy.h @@ -9,35 +9,35 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __EDKII_VARIABLE_POLICY_PROTOCOL__ #define __EDKII_VARIABLE_POLICY_PROTOCOL__ -#define EDKII_VARIABLE_POLICY_PROTOCOL_REVISION 0x0000000000010000 +#define EDKII_VARIABLE_POLICY_PROTOCOL_REVISION 0x0000000000010000 #define EDKII_VARIABLE_POLICY_PROTOCOL_GUID \ { \ 0x81D1675C, 0x86F6, 0x48DF, { 0xBD, 0x95, 0x9A, 0x6E, 0x4F, 0x09, 0x25, 0xC3 } \ } -#define VARIABLE_POLICY_ENTRY_REVISION 0x00010000 +#define VARIABLE_POLICY_ENTRY_REVISION 0x00010000 #pragma pack(push, 1) typedef struct { - UINT32 Version; - UINT16 Size; - UINT16 OffsetToName; - EFI_GUID Namespace; - UINT32 MinSize; - UINT32 MaxSize; - UINT32 AttributesMustHave; - UINT32 AttributesCantHave; - UINT8 LockPolicyType; - UINT8 Padding[3]; + UINT32 Version; + UINT16 Size; + UINT16 OffsetToName; + EFI_GUID Namespace; + UINT32 MinSize; + UINT32 MaxSize; + UINT32 AttributesMustHave; + UINT32 AttributesCantHave; + UINT8 LockPolicyType; + UINT8 Padding[3]; // UINT8 LockPolicy[]; // Variable Length Field // CHAR16 Name[] // Variable Length Field } VARIABLE_POLICY_ENTRY; -#define VARIABLE_POLICY_NO_MIN_SIZE 0 -#define VARIABLE_POLICY_NO_MAX_SIZE MAX_UINT32 -#define VARIABLE_POLICY_NO_MUST_ATTR 0 -#define VARIABLE_POLICY_NO_CANT_ATTR 0 +#define VARIABLE_POLICY_NO_MIN_SIZE 0 +#define VARIABLE_POLICY_NO_MAX_SIZE MAX_UINT32 +#define VARIABLE_POLICY_NO_MUST_ATTR 0 +#define VARIABLE_POLICY_NO_CANT_ATTR 0 #define VARIABLE_POLICY_TYPE_NO_LOCK 0 #define VARIABLE_POLICY_TYPE_LOCK_NOW 1 @@ -45,9 +45,9 @@ typedef struct { #define VARIABLE_POLICY_TYPE_LOCK_ON_VAR_STATE 3 typedef struct { - EFI_GUID Namespace; - UINT8 Value; - UINT8 Padding; + EFI_GUID Namespace; + UINT8 Value; + UINT8 Padding; // CHAR16 Name[]; // Variable Length Field } VARIABLE_LOCK_ON_VAR_STATE_POLICY; #pragma pack(pop) @@ -142,16 +142,16 @@ EFI_STATUS ); typedef struct { - UINT64 Revision; - DISABLE_VARIABLE_POLICY DisableVariablePolicy; - IS_VARIABLE_POLICY_ENABLED IsVariablePolicyEnabled; - REGISTER_VARIABLE_POLICY RegisterVariablePolicy; - DUMP_VARIABLE_POLICY DumpVariablePolicy; - LOCK_VARIABLE_POLICY LockVariablePolicy; + UINT64 Revision; + DISABLE_VARIABLE_POLICY DisableVariablePolicy; + IS_VARIABLE_POLICY_ENABLED IsVariablePolicyEnabled; + REGISTER_VARIABLE_POLICY RegisterVariablePolicy; + DUMP_VARIABLE_POLICY DumpVariablePolicy; + LOCK_VARIABLE_POLICY LockVariablePolicy; } _EDKII_VARIABLE_POLICY_PROTOCOL; typedef _EDKII_VARIABLE_POLICY_PROTOCOL EDKII_VARIABLE_POLICY_PROTOCOL; -extern EFI_GUID gEdkiiVariablePolicyProtocolGuid; +extern EFI_GUID gEdkiiVariablePolicyProtocolGuid; #endif diff --git a/MdeModulePkg/Include/UniversalPayload/AcpiTable.h b/MdeModulePkg/Include/UniversalPayload/AcpiTable.h index 33ef72637e..6b590b3932 100644 --- a/MdeModulePkg/Include/UniversalPayload/AcpiTable.h +++ b/MdeModulePkg/Include/UniversalPayload/AcpiTable.h @@ -17,14 +17,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #pragma pack(1) typedef struct { - UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; - EFI_PHYSICAL_ADDRESS Rsdp; + UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; + EFI_PHYSICAL_ADDRESS Rsdp; } UNIVERSAL_PAYLOAD_ACPI_TABLE; #pragma pack() -#define UNIVERSAL_PAYLOAD_ACPI_TABLE_REVISION 1 +#define UNIVERSAL_PAYLOAD_ACPI_TABLE_REVISION 1 -extern GUID gUniversalPayloadAcpiTableGuid; +extern GUID gUniversalPayloadAcpiTableGuid; #endif // UNIVERSAL_PAYLOAD_ACPI_TABLE_H_ diff --git a/MdeModulePkg/Include/UniversalPayload/ExtraData.h b/MdeModulePkg/Include/UniversalPayload/ExtraData.h index 1128f5f47b..334dfd2b9e 100644 --- a/MdeModulePkg/Include/UniversalPayload/ExtraData.h +++ b/MdeModulePkg/Include/UniversalPayload/ExtraData.h @@ -4,27 +4,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef EXTRA_DATA_H_ #define EXTRA_DATA_H_ -extern GUID gUniversalPayloadExtraDataGuid; +extern GUID gUniversalPayloadExtraDataGuid; #pragma pack(1) typedef struct { - CHAR8 Identifier[16]; - EFI_PHYSICAL_ADDRESS Base; - UINT64 Size; + CHAR8 Identifier[16]; + EFI_PHYSICAL_ADDRESS Base; + UINT64 Size; } UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY; typedef struct { - UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; - UINT32 Count; - UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY Entry[0]; + UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; + UINT32 Count; + UNIVERSAL_PAYLOAD_EXTRA_DATA_ENTRY Entry[0]; } UNIVERSAL_PAYLOAD_EXTRA_DATA; #pragma pack() -#define UNIVERSAL_PAYLOAD_EXTRA_DATA_REVISION 1 +#define UNIVERSAL_PAYLOAD_EXTRA_DATA_REVISION 1 #endif diff --git a/MdeModulePkg/Include/UniversalPayload/PciRootBridges.h b/MdeModulePkg/Include/UniversalPayload/PciRootBridges.h index 3a7aae82d4..37260da3b1 100644 --- a/MdeModulePkg/Include/UniversalPayload/PciRootBridges.h +++ b/MdeModulePkg/Include/UniversalPayload/PciRootBridges.h @@ -23,8 +23,8 @@ typedef struct { // Base and Limit are the device address instead of host address when // Translation is not zero // - UINT64 Base; - UINT64 Limit; + UINT64 Base; + UINT64 Limit; // // According to UEFI 2.7, Device Address = Host Address + Translation, // so Translation = Device Address - Host Address. @@ -39,53 +39,53 @@ typedef struct { // situation and makes the current resource allocation code in generic PCI // host bridge driver still work. // - UINT64 Translation; + UINT64 Translation; } UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE; /// /// Payload PCI Root Bridge Information HOB /// typedef struct { - UINT32 Segment; ///< Segment number. - UINT64 Supports; ///< Supported attributes. - ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() - ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. - UINT64 Attributes; ///< Initial attributes. - ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() - ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. - BOOLEAN DmaAbove4G; ///< DMA above 4GB memory. - ///< Set to TRUE when root bridge supports DMA above 4GB memory. - BOOLEAN NoExtendedConfigSpace; ///< When FALSE, the root bridge supports - ///< Extended (4096-byte) Configuration Space. - ///< When TRUE, the root bridge supports - ///< 256-byte Configuration Space only. - UINT64 AllocationAttributes; ///< Allocation attributes. - ///< Refer to EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM and - ///< EFI_PCI_HOST_BRIDGE_MEM64_DECODE used by GetAllocAttributes() - ///< in EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Bus; ///< Bus aperture which can be used by the root bridge. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Io; ///< IO aperture which can be used by the root bridge. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Mem; ///< MMIO aperture below 4GB which can be used by the root bridge. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE MemAbove4G; ///< MMIO aperture above 4GB which can be used by the root bridge. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE PMem; ///< Prefetchable MMIO aperture below 4GB which can be used by the root bridge. - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; ///< Prefetchable MMIO aperture above 4GB which can be used by the root bridge. - UINT32 HID; ///< PnP hardware ID of the root bridge. This value must match the corresponding - ///< _HID in the ACPI name space. - UINT32 UID; ///< Unique ID that is required by ACPI if two devices have the same _HID. - ///< This value must also match the corresponding _UID/_HID pair in the ACPI name space. + UINT32 Segment; ///< Segment number. + UINT64 Supports; ///< Supported attributes. + ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() + ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. + UINT64 Attributes; ///< Initial attributes. + ///< Refer to EFI_PCI_ATTRIBUTE_xxx used by GetAttributes() + ///< and SetAttributes() in EFI_PCI_ROOT_BRIDGE_IO_PROTOCOL. + BOOLEAN DmaAbove4G; ///< DMA above 4GB memory. + ///< Set to TRUE when root bridge supports DMA above 4GB memory. + BOOLEAN NoExtendedConfigSpace; ///< When FALSE, the root bridge supports + ///< Extended (4096-byte) Configuration Space. + ///< When TRUE, the root bridge supports + ///< 256-byte Configuration Space only. + UINT64 AllocationAttributes; ///< Allocation attributes. + ///< Refer to EFI_PCI_HOST_BRIDGE_COMBINE_MEM_PMEM and + ///< EFI_PCI_HOST_BRIDGE_MEM64_DECODE used by GetAllocAttributes() + ///< in EFI_PCI_HOST_BRIDGE_RESOURCE_ALLOCATION_PROTOCOL. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Bus; ///< Bus aperture which can be used by the root bridge. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Io; ///< IO aperture which can be used by the root bridge. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE Mem; ///< MMIO aperture below 4GB which can be used by the root bridge. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE MemAbove4G; ///< MMIO aperture above 4GB which can be used by the root bridge. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE PMem; ///< Prefetchable MMIO aperture below 4GB which can be used by the root bridge. + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE_APERTURE PMemAbove4G; ///< Prefetchable MMIO aperture above 4GB which can be used by the root bridge. + UINT32 HID; ///< PnP hardware ID of the root bridge. This value must match the corresponding + ///< _HID in the ACPI name space. + UINT32 UID; ///< Unique ID that is required by ACPI if two devices have the same _HID. + ///< This value must also match the corresponding _UID/_HID pair in the ACPI name space. } UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE; typedef struct { - UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; - BOOLEAN ResourceAssigned; - UINT8 Count; - UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE RootBridge[0]; + UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; + BOOLEAN ResourceAssigned; + UINT8 Count; + UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGE RootBridge[0]; } UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGES; #pragma pack() -#define UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGES_REVISION 1 +#define UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGES_REVISION 1 -extern GUID gUniversalPayloadPciRootBridgeInfoGuid; +extern GUID gUniversalPayloadPciRootBridgeInfoGuid; #endif // UNIVERSAL_PAYLOAD_PCI_ROOT_BRIDGES_H_ diff --git a/MdeModulePkg/Include/UniversalPayload/SerialPortInfo.h b/MdeModulePkg/Include/UniversalPayload/SerialPortInfo.h index 87181f7634..3c4459e2c0 100644 --- a/MdeModulePkg/Include/UniversalPayload/SerialPortInfo.h +++ b/MdeModulePkg/Include/UniversalPayload/SerialPortInfo.h @@ -15,16 +15,16 @@ #pragma pack(1) typedef struct { - UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; - BOOLEAN UseMmio; - UINT8 RegisterStride; - UINT32 BaudRate; - EFI_PHYSICAL_ADDRESS RegisterBase; + UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; + BOOLEAN UseMmio; + UINT8 RegisterStride; + UINT32 BaudRate; + EFI_PHYSICAL_ADDRESS RegisterBase; } UNIVERSAL_PAYLOAD_SERIAL_PORT_INFO; #pragma pack() -#define UNIVERSAL_PAYLOAD_SERIAL_PORT_INFO_REVISION 1 +#define UNIVERSAL_PAYLOAD_SERIAL_PORT_INFO_REVISION 1 -extern GUID gUniversalPayloadSerialPortInfoGuid; +extern GUID gUniversalPayloadSerialPortInfoGuid; #endif // UNIVERSAL_PAYLOAD_SERIAL_PORT_INFO_H_ diff --git a/MdeModulePkg/Include/UniversalPayload/SmbiosTable.h b/MdeModulePkg/Include/UniversalPayload/SmbiosTable.h index 94c4aaf7ee..ba5a8696e2 100644 --- a/MdeModulePkg/Include/UniversalPayload/SmbiosTable.h +++ b/MdeModulePkg/Include/UniversalPayload/SmbiosTable.h @@ -17,14 +17,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #pragma pack (1) typedef struct { - UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; - EFI_PHYSICAL_ADDRESS SmBiosEntryPoint; + UNIVERSAL_PAYLOAD_GENERIC_HEADER Header; + EFI_PHYSICAL_ADDRESS SmBiosEntryPoint; } UNIVERSAL_PAYLOAD_SMBIOS_TABLE; #pragma pack() -#define UNIVERSAL_PAYLOAD_SMBIOS_TABLE_REVISION 1 +#define UNIVERSAL_PAYLOAD_SMBIOS_TABLE_REVISION 1 -extern GUID gUniversalPayloadSmbios3TableGuid; -extern GUID gUniversalPayloadSmbiosTableGuid; +extern GUID gUniversalPayloadSmbios3TableGuid; +extern GUID gUniversalPayloadSmbiosTableGuid; #endif // UNIVERSAL_PAYLOAD_SMBIOS_TABLE_H_ diff --git a/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h b/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h index bc8a3e0cf8..1a42d61f77 100644 --- a/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h +++ b/MdeModulePkg/Include/UniversalPayload/UniversalPayload.h @@ -16,31 +16,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @param HobList Pointer to the beginning of the HOB List from boot loader. **/ -typedef VOID (EFIAPI *UNIVERSAL_PAYLOAD_ENTRY) (VOID *HobList); +typedef VOID (EFIAPI *UNIVERSAL_PAYLOAD_ENTRY)(VOID *HobList); -#define UNIVERSAL_PAYLOAD_IDENTIFIER SIGNATURE_32('U', 'P', 'L', 'D') -#define UNIVERSAL_PAYLOAD_INFO_SEC_NAME ".upld_info" -#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX ".upld." -#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH (sizeof (UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX) - 1) +#define UNIVERSAL_PAYLOAD_IDENTIFIER SIGNATURE_32('U', 'P', 'L', 'D') +#define UNIVERSAL_PAYLOAD_INFO_SEC_NAME ".upld_info" +#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX ".upld." +#define UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX_LENGTH (sizeof (UNIVERSAL_PAYLOAD_EXTRA_SEC_NAME_PREFIX) - 1) #pragma pack(1) typedef struct { - UINT32 Identifier; - UINT32 HeaderLength; - UINT16 SpecRevision; - UINT8 Reserved[2]; - UINT32 Revision; - UINT32 Attribute; - UINT32 Capability; - CHAR8 ProducerId[16]; - CHAR8 ImageId[16]; + UINT32 Identifier; + UINT32 HeaderLength; + UINT16 SpecRevision; + UINT8 Reserved[2]; + UINT32 Revision; + UINT32 Attribute; + UINT32 Capability; + CHAR8 ProducerId[16]; + CHAR8 ImageId[16]; } UNIVERSAL_PAYLOAD_INFO_HEADER; typedef struct { - UINT8 Revision; - UINT8 Reserved; - UINT16 Length; + UINT8 Revision; + UINT8 Reserved; + UINT16 Length; } UNIVERSAL_PAYLOAD_GENERIC_HEADER; #pragma pack() @@ -54,6 +54,6 @@ typedef struct { @return size, in bytes. **/ -#define UNIVERSAL_PAYLOAD_SIZEOF_THROUGH_FIELD(TYPE, Field) (OFFSET_OF(TYPE, Field) + sizeof (((TYPE *) 0)->Field)) +#define UNIVERSAL_PAYLOAD_SIZEOF_THROUGH_FIELD(TYPE, Field) (OFFSET_OF(TYPE, Field) + sizeof (((TYPE *) 0)->Field)) #endif // UNIVERSAL_PAYLOAD_H_ diff --git a/MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.c b/MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.c index b6922d3dc0..480560b4cf 100644 --- a/MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.c +++ b/MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.c @@ -59,11 +59,11 @@ AuthVariableLibInitialize ( EFI_STATUS EFIAPI AuthVariableLibProcessVariable ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN VOID *Data, - IN UINTN DataSize, - IN UINT32 Attributes + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN VOID *Data, + IN UINTN DataSize, + IN UINT32 Attributes ) { ASSERT (FALSE); diff --git a/MdeModulePkg/Library/BaseBmpSupportLib/BmpSupportLib.c b/MdeModulePkg/Library/BaseBmpSupportLib/BmpSupportLib.c index 3ac31f6723..c5e885d7a6 100644 --- a/MdeModulePkg/Library/BaseBmpSupportLib/BmpSupportLib.c +++ b/MdeModulePkg/Library/BaseBmpSupportLib/BmpSupportLib.c @@ -31,22 +31,22 @@ // BMP Image header for an uncompressed 24-bit per pixel BMP image. // const BMP_IMAGE_HEADER mBmpImageHeaderTemplate = { - 'B', // CharB - 'M', // CharM - 0, // Size will be updated at runtime - {0, 0}, // Reserved - sizeof (BMP_IMAGE_HEADER), // ImageOffset + 'B', // CharB + 'M', // CharM + 0, // Size will be updated at runtime + { 0, 0 }, // Reserved + sizeof (BMP_IMAGE_HEADER), // ImageOffset sizeof (BMP_IMAGE_HEADER) - OFFSET_OF (BMP_IMAGE_HEADER, HeaderSize), // HeaderSize - 0, // PixelWidth will be updated at runtime - 0, // PixelHeight will be updated at runtime - 1, // Planes - 24, // BitPerPixel - 0, // CompressionType - 0, // ImageSize will be updated at runtime - 0, // XPixelsPerMeter - 0, // YPixelsPerMeter - 0, // NumberOfColors - 0 // ImportantColors + 0, // PixelWidth will be updated at runtime + 0, // PixelHeight will be updated at runtime + 1, // Planes + 24, // BitPerPixel + 0, // CompressionType + 0, // ImageSize will be updated at runtime + 0, // XPixelsPerMeter + 0, // YPixelsPerMeter + 0, // NumberOfColors + 0 // ImportantColors }; /** @@ -104,10 +104,11 @@ TranslateBmpToGopBlt ( UINT32 DataSize; UINT32 Temp; - if (BmpImage == NULL || GopBlt == NULL || GopBltSize == NULL) { + if ((BmpImage == NULL) || (GopBlt == NULL) || (GopBltSize == NULL)) { return RETURN_INVALID_PARAMETER; } - if (PixelHeight == NULL || PixelWidth == NULL) { + + if ((PixelHeight == NULL) || (PixelWidth == NULL)) { return RETURN_INVALID_PARAMETER; } @@ -118,7 +119,7 @@ TranslateBmpToGopBlt ( BmpHeader = (BMP_IMAGE_HEADER *)BmpImage; - if (BmpHeader->CharB != 'B' || BmpHeader->CharM != 'M') { + if ((BmpHeader->CharB != 'B') || (BmpHeader->CharM != 'M')) { DEBUG ((DEBUG_ERROR, "TranslateBmpToGopBlt: BmpHeader->Char fields incorrect\n")); return RETURN_UNSUPPORTED; } @@ -179,17 +180,18 @@ TranslateBmpToGopBlt ( } DataSizePerLine = (DataSizePerLine >> 3) &(~0x3); - Status = SafeUint32Mult ( - DataSizePerLine, - BmpHeader->PixelHeight, - &BltBufferSize - ); + Status = SafeUint32Mult ( + DataSizePerLine, + BmpHeader->PixelHeight, + &BltBufferSize + ); if (EFI_ERROR (Status)) { DEBUG (( DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BmpImage... DataSizePerLine:0x%x PixelHeight:0x%x\n", - DataSizePerLine, BmpHeader->PixelHeight + DataSizePerLine, + BmpHeader->PixelHeight )); return RETURN_UNSUPPORTED; @@ -205,7 +207,8 @@ TranslateBmpToGopBlt ( DEBUG (( DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BmpImage... PixelHeight:0x%x DataSizePerLine:0x%x\n", - BmpHeader->PixelHeight, DataSizePerLine + BmpHeader->PixelHeight, + DataSizePerLine )); return RETURN_UNSUPPORTED; @@ -213,8 +216,8 @@ TranslateBmpToGopBlt ( if ((BmpHeader->Size != BmpImageSize) || (BmpHeader->Size < BmpHeader->ImageOffset) || - (BmpHeader->Size - BmpHeader->ImageOffset != DataSize)) { - + (BmpHeader->Size - BmpHeader->ImageOffset != DataSize)) + { DEBUG ((DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BmpImage... \n")); DEBUG ((DEBUG_ERROR, " BmpHeader->Size: 0x%x\n", BmpHeader->Size)); DEBUG ((DEBUG_ERROR, " BmpHeader->ImageOffset: 0x%x\n", BmpHeader->ImageOffset)); @@ -227,7 +230,7 @@ TranslateBmpToGopBlt ( // // Calculate Color Map offset in the image. // - Image = BmpImage; + Image = BmpImage; BmpColorMap = (BMP_COLOR_MAP *)(Image + sizeof (BMP_IMAGE_HEADER)); if (BmpHeader->ImageOffset < sizeof (BMP_IMAGE_HEADER)) { return RETURN_UNSUPPORTED; @@ -235,19 +238,20 @@ TranslateBmpToGopBlt ( if (BmpHeader->ImageOffset > sizeof (BMP_IMAGE_HEADER)) { switch (BmpHeader->BitPerPixel) { - case 1: - ColorMapNum = 2; - break; - case 4: - ColorMapNum = 16; - break; - case 8: - ColorMapNum = 256; - break; - default: - ColorMapNum = 0; - break; + case 1: + ColorMapNum = 2; + break; + case 4: + ColorMapNum = 16; + break; + case 8: + ColorMapNum = 256; + break; + default: + ColorMapNum = 0; + break; } + // // BMP file may has padding data between the bmp header section and the // bmp data section. @@ -260,7 +264,7 @@ TranslateBmpToGopBlt ( // // Calculate graphics image data address in the image // - Image = ((UINT8 *)BmpImage) + BmpHeader->ImageOffset; + Image = ((UINT8 *)BmpImage) + BmpHeader->ImageOffset; ImageHeader = Image; // @@ -276,13 +280,14 @@ TranslateBmpToGopBlt ( DEBUG (( DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BltBuffer needed size... PixelWidth:0x%x PixelHeight:0x%x\n", - BmpHeader->PixelWidth, BmpHeader->PixelHeight + BmpHeader->PixelWidth, + BmpHeader->PixelHeight )); return RETURN_UNSUPPORTED; } - Temp = BltBufferSize; + Temp = BltBufferSize; Status = SafeUint32Mult ( BltBufferSize, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL), @@ -293,7 +298,8 @@ TranslateBmpToGopBlt ( DEBUG (( DEBUG_ERROR, "TranslateBmpToGopBlt: invalid BltBuffer needed size... PixelWidth x PixelHeight:0x%x struct size:0x%x\n", - Temp, sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + Temp, + sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) )); return RETURN_UNSUPPORTED; @@ -306,7 +312,7 @@ TranslateBmpToGopBlt ( // DEBUG ((DEBUG_INFO, "Bmp Support: Allocating 0x%X bytes of memory\n", BltBufferSize)); *GopBltSize = (UINTN)BltBufferSize; - *GopBlt = AllocatePool (*GopBltSize); + *GopBlt = AllocatePool (*GopBltSize); IsAllocated = TRUE; if (*GopBlt == NULL) { return RETURN_OUT_OF_RESOURCES; @@ -336,82 +342,83 @@ TranslateBmpToGopBlt ( // BltBuffer = *GopBlt; for (Height = 0; Height < BmpHeader->PixelHeight; Height++) { - Blt = &BltBuffer[ (BmpHeader->PixelHeight - Height - 1) * BmpHeader->PixelWidth]; + Blt = &BltBuffer[(BmpHeader->PixelHeight - Height - 1) * BmpHeader->PixelWidth]; for (Width = 0; Width < BmpHeader->PixelWidth; Width++, Image++, Blt++) { switch (BmpHeader->BitPerPixel) { - case 1: - // - // Translate 1-bit (2 colors) BMP to 24-bit color - // - for (Index = 0; Index < 8 && Width < BmpHeader->PixelWidth; Index++) { - Blt->Red = BmpColorMap[ ((*Image) >> (7 - Index)) & 0x1].Red; - Blt->Green = BmpColorMap[ ((*Image) >> (7 - Index)) & 0x1].Green; - Blt->Blue = BmpColorMap[ ((*Image) >> (7 - Index)) & 0x1].Blue; - Blt++; - Width++; - } - - Blt--; - Width--; - break; - - case 4: - // - // Translate 4-bit (16 colors) BMP Palette to 24-bit color - // - Index = (*Image) >> 4; - Blt->Red = BmpColorMap[Index].Red; - Blt->Green = BmpColorMap[Index].Green; - Blt->Blue = BmpColorMap[Index].Blue; - if (Width < (BmpHeader->PixelWidth - 1)) { - Blt++; - Width++; - Index = (*Image) & 0x0f; + case 1: + // + // Translate 1-bit (2 colors) BMP to 24-bit color + // + for (Index = 0; Index < 8 && Width < BmpHeader->PixelWidth; Index++) { + Blt->Red = BmpColorMap[((*Image) >> (7 - Index)) & 0x1].Red; + Blt->Green = BmpColorMap[((*Image) >> (7 - Index)) & 0x1].Green; + Blt->Blue = BmpColorMap[((*Image) >> (7 - Index)) & 0x1].Blue; + Blt++; + Width++; + } + + Blt--; + Width--; + break; + + case 4: + // + // Translate 4-bit (16 colors) BMP Palette to 24-bit color + // + Index = (*Image) >> 4; Blt->Red = BmpColorMap[Index].Red; Blt->Green = BmpColorMap[Index].Green; Blt->Blue = BmpColorMap[Index].Blue; - } - break; - - case 8: - // - // Translate 8-bit (256 colors) BMP Palette to 24-bit color - // - Blt->Red = BmpColorMap[*Image].Red; - Blt->Green = BmpColorMap[*Image].Green; - Blt->Blue = BmpColorMap[*Image].Blue; - break; - - case 24: - // - // It is 24-bit BMP. - // - Blt->Blue = *Image++; - Blt->Green = *Image++; - Blt->Red = *Image; - break; - - case 32: - // - //Conver 32 bit to 24bit bmp - just ignore the final byte of each pixel - Blt->Blue = *Image++; - Blt->Green = *Image++; - Blt->Red = *Image++; - break; - - default: - // - // Other bit format BMP is not supported. - // - if (IsAllocated) { - FreePool (*GopBlt); - *GopBlt = NULL; - } - DEBUG ((DEBUG_ERROR, "Bmp Bit format not supported. 0x%X\n", BmpHeader->BitPerPixel)); - return RETURN_UNSUPPORTED; - break; - }; - + if (Width < (BmpHeader->PixelWidth - 1)) { + Blt++; + Width++; + Index = (*Image) & 0x0f; + Blt->Red = BmpColorMap[Index].Red; + Blt->Green = BmpColorMap[Index].Green; + Blt->Blue = BmpColorMap[Index].Blue; + } + + break; + + case 8: + // + // Translate 8-bit (256 colors) BMP Palette to 24-bit color + // + Blt->Red = BmpColorMap[*Image].Red; + Blt->Green = BmpColorMap[*Image].Green; + Blt->Blue = BmpColorMap[*Image].Blue; + break; + + case 24: + // + // It is 24-bit BMP. + // + Blt->Blue = *Image++; + Blt->Green = *Image++; + Blt->Red = *Image; + break; + + case 32: + // + // Conver 32 bit to 24bit bmp - just ignore the final byte of each pixel + Blt->Blue = *Image++; + Blt->Green = *Image++; + Blt->Red = *Image++; + break; + + default: + // + // Other bit format BMP is not supported. + // + if (IsAllocated) { + FreePool (*GopBlt); + *GopBlt = NULL; + } + + DEBUG ((DEBUG_ERROR, "Bmp Bit format not supported. 0x%X\n", BmpHeader->BitPerPixel)); + return RETURN_UNSUPPORTED; + break; + } } ImageIndex = (UINTN)Image - (UINTN)ImageHeader; @@ -468,7 +475,7 @@ TranslateGopBltToBmp ( UINTN Row; EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltPixel; - if (GopBlt == NULL || BmpImage == NULL || BmpImageSize == NULL) { + if ((GopBlt == NULL) || (BmpImage == NULL) || (BmpImageSize == NULL)) { return RETURN_INVALID_PARAMETER; } @@ -494,6 +501,7 @@ TranslateGopBltToBmp ( )); return RETURN_UNSUPPORTED; } + Status = SafeUint32Add (BmpSize, PaddingSize, &BmpSize); if (EFI_ERROR (Status)) { DEBUG (( @@ -518,6 +526,7 @@ TranslateGopBltToBmp ( )); return RETURN_UNSUPPORTED; } + Status = SafeUint32Add (BmpSize, sizeof (BMP_IMAGE_HEADER), &BmpSize); if (EFI_ERROR (Status)) { DEBUG (( @@ -538,6 +547,7 @@ TranslateGopBltToBmp ( if (*BmpImage == NULL) { return EFI_OUT_OF_RESOURCES; } + *BmpImageSize = BmpSize; } else if (*BmpImageSize < BmpSize) { *BmpImageSize = BmpSize; diff --git a/MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.c b/MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.c index 41ff4412ce..4dc73fa282 100644 --- a/MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.c +++ b/MdeModulePkg/Library/BaseHobLibNull/BaseHobLibNull.c @@ -59,8 +59,8 @@ GetHobList ( VOID * EFIAPI GetNextHob ( - IN UINT16 Type, - IN CONST VOID *HobStart + IN UINT16 Type, + IN CONST VOID *HobStart ) { ASSERT (FALSE); @@ -83,7 +83,7 @@ GetNextHob ( VOID * EFIAPI GetFirstHob ( - IN UINT16 Type + IN UINT16 Type ) { ASSERT (FALSE); @@ -115,8 +115,8 @@ GetFirstHob ( VOID * EFIAPI GetNextGuidHob ( - IN CONST EFI_GUID *Guid, - IN CONST VOID *HobStart + IN CONST EFI_GUID *Guid, + IN CONST VOID *HobStart ) { ASSERT (FALSE); @@ -144,7 +144,7 @@ GetNextGuidHob ( VOID * EFIAPI GetFirstGuidHob ( - IN CONST EFI_GUID *Guid + IN CONST EFI_GUID *Guid ) { ASSERT (FALSE); @@ -193,10 +193,10 @@ GetBootModeHob ( VOID EFIAPI BuildModuleHob ( - IN CONST EFI_GUID *ModuleName, - IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule, - IN UINT64 ModuleLength, - IN EFI_PHYSICAL_ADDRESS EntryPoint + IN CONST EFI_GUID *ModuleName, + IN EFI_PHYSICAL_ADDRESS MemoryAllocationModule, + IN UINT64 ModuleLength, + IN EFI_PHYSICAL_ADDRESS EntryPoint ) { ASSERT (FALSE); @@ -283,8 +283,8 @@ BuildResourceDescriptorHob ( VOID * EFIAPI BuildGuidHob ( - IN CONST EFI_GUID *Guid, - IN UINTN DataLength + IN CONST EFI_GUID *Guid, + IN UINTN DataLength ) { ASSERT (FALSE); @@ -319,9 +319,9 @@ BuildGuidHob ( VOID * EFIAPI BuildGuidDataHob ( - IN CONST EFI_GUID *Guid, - IN VOID *Data, - IN UINTN DataLength + IN CONST EFI_GUID *Guid, + IN VOID *Data, + IN UINTN DataLength ) { ASSERT (FALSE); @@ -345,8 +345,8 @@ BuildGuidDataHob ( VOID EFIAPI BuildFvHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length ) { ASSERT (FALSE); @@ -371,10 +371,10 @@ BuildFvHob ( VOID EFIAPI BuildFv2Hob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN CONST EFI_GUID *FvName, - IN CONST EFI_GUID *FileName + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN CONST EFI_GUID *FvName, + IN CONST EFI_GUID *FileName ) { ASSERT (FALSE); @@ -404,12 +404,12 @@ BuildFv2Hob ( VOID EFIAPI BuildFv3Hob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN UINT32 AuthenticationStatus, - IN BOOLEAN ExtractedFv, - IN CONST EFI_GUID *FvName OPTIONAL, - IN CONST EFI_GUID *FileName OPTIONAL + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN UINT32 AuthenticationStatus, + IN BOOLEAN ExtractedFv, + IN CONST EFI_GUID *FvName OPTIONAL, + IN CONST EFI_GUID *FileName OPTIONAL ) { ASSERT (FALSE); @@ -432,8 +432,8 @@ BuildFv3Hob ( VOID EFIAPI BuildCvHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length ) { ASSERT (FALSE); @@ -455,8 +455,8 @@ BuildCvHob ( VOID EFIAPI BuildCpuHob ( - IN UINT8 SizeOfMemorySpace, - IN UINT8 SizeOfIoSpace + IN UINT8 SizeOfMemorySpace, + IN UINT8 SizeOfIoSpace ) { ASSERT (FALSE); @@ -478,8 +478,8 @@ BuildCpuHob ( VOID EFIAPI BuildStackHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length ) { ASSERT (FALSE); @@ -502,9 +502,9 @@ BuildStackHob ( VOID EFIAPI BuildBspStoreHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN EFI_MEMORY_TYPE MemoryType + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN EFI_MEMORY_TYPE MemoryType ) { ASSERT (FALSE); @@ -527,9 +527,9 @@ BuildBspStoreHob ( VOID EFIAPI BuildMemoryAllocationHob ( - IN EFI_PHYSICAL_ADDRESS BaseAddress, - IN UINT64 Length, - IN EFI_MEMORY_TYPE MemoryType + IN EFI_PHYSICAL_ADDRESS BaseAddress, + IN UINT64 Length, + IN EFI_MEMORY_TYPE MemoryType ) { ASSERT (FALSE); diff --git a/MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.c b/MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.c index 44ad5ed5b4..68ac802efa 100644 --- a/MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.c +++ b/MdeModulePkg/Library/BaseIpmiLibNull/BaseIpmiLibNull.c @@ -10,7 +10,6 @@ #include #include - /** This service enables submitting commands via Ipmi. @@ -32,12 +31,12 @@ EFI_STATUS EFIAPI IpmiSubmitCommand ( - IN UINT8 NetFunction, - IN UINT8 Command, - IN UINT8 *RequestData, - IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, - IN OUT UINT32 *ResponseDataSize + IN UINT8 NetFunction, + IN UINT8 Command, + IN UINT8 *RequestData, + IN UINT32 RequestDataSize, + OUT UINT8 *ResponseData, + IN OUT UINT32 *ResponseDataSize ) { // diff --git a/MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.c b/MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.c index 4079472e82..3061ec6cd0 100644 --- a/MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.c +++ b/MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.c @@ -7,13 +7,11 @@ **/ - #include #include #include - /** Allocates one or more 4KB pages of type EfiBootServicesData. @@ -562,7 +560,7 @@ ReallocateReservedPool ( VOID EFIAPI FreePool ( - IN VOID *Buffer + IN VOID *Buffer ) { ASSERT (FALSE); diff --git a/MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.c b/MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.c index a33f1ddd7b..1942031d66 100644 --- a/MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.c +++ b/MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.c @@ -26,6 +26,5 @@ PlatformHookSerialPortInitialize ( VOID ) { - return RETURN_SUCCESS; + return RETURN_SUCCESS; } - diff --git a/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c b/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c index 33a896bee0..c34a968d9b 100644 --- a/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c +++ b/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c @@ -72,8 +72,8 @@ ResetShutdown ( VOID EFIAPI ResetPlatformSpecific ( - IN UINTN DataSize, - IN VOID *ResetData + IN UINTN DataSize, + IN VOID *ResetData ) { ResetCold (); @@ -94,12 +94,11 @@ ResetPlatformSpecific ( VOID EFIAPI ResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { ASSERT (FALSE); } - diff --git a/MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.c b/MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.c index 10e053076a..e413cea4b3 100644 --- a/MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.c +++ b/MdeModulePkg/Library/BaseSerialPortLib16550/BaseSerialPortLib16550.c @@ -22,41 +22,41 @@ // // PCI Defintions. // -#define PCI_BRIDGE_32_BIT_IO_SPACE 0x01 +#define PCI_BRIDGE_32_BIT_IO_SPACE 0x01 // // 16550 UART register offsets and bitfields // -#define R_UART_RXBUF 0 // LCR_DLAB = 0 -#define R_UART_TXBUF 0 // LCR_DLAB = 0 -#define R_UART_BAUD_LOW 0 // LCR_DLAB = 1 -#define R_UART_BAUD_HIGH 1 // LCR_DLAB = 1 -#define R_UART_IER 1 // LCR_DLAB = 0 -#define R_UART_FCR 2 -#define B_UART_FCR_FIFOE BIT0 -#define B_UART_FCR_FIFO64 BIT5 -#define R_UART_LCR 3 -#define B_UART_LCR_DLAB BIT7 -#define R_UART_MCR 4 -#define B_UART_MCR_DTRC BIT0 -#define B_UART_MCR_RTS BIT1 -#define R_UART_LSR 5 -#define B_UART_LSR_RXRDY BIT0 -#define B_UART_LSR_TXRDY BIT5 -#define B_UART_LSR_TEMT BIT6 -#define R_UART_MSR 6 -#define B_UART_MSR_CTS BIT4 -#define B_UART_MSR_DSR BIT5 -#define B_UART_MSR_RI BIT6 -#define B_UART_MSR_DCD BIT7 +#define R_UART_RXBUF 0 // LCR_DLAB = 0 +#define R_UART_TXBUF 0 // LCR_DLAB = 0 +#define R_UART_BAUD_LOW 0 // LCR_DLAB = 1 +#define R_UART_BAUD_HIGH 1 // LCR_DLAB = 1 +#define R_UART_IER 1 // LCR_DLAB = 0 +#define R_UART_FCR 2 +#define B_UART_FCR_FIFOE BIT0 +#define B_UART_FCR_FIFO64 BIT5 +#define R_UART_LCR 3 +#define B_UART_LCR_DLAB BIT7 +#define R_UART_MCR 4 +#define B_UART_MCR_DTRC BIT0 +#define B_UART_MCR_RTS BIT1 +#define R_UART_LSR 5 +#define B_UART_LSR_RXRDY BIT0 +#define B_UART_LSR_TXRDY BIT5 +#define B_UART_LSR_TEMT BIT6 +#define R_UART_MSR 6 +#define B_UART_MSR_CTS BIT4 +#define B_UART_MSR_DSR BIT5 +#define B_UART_MSR_RI BIT6 +#define B_UART_MSR_DCD BIT7 // // 4-byte structure for each PCI node in PcdSerialPciDeviceInfo // typedef struct { - UINT8 Device; - UINT8 Function; - UINT16 PowerManagementStatusAndControlRegister; + UINT8 Device; + UINT8 Function; + UINT16 PowerManagementStatusAndControlRegister; } PCI_UART_DEVICE_INFO; /** @@ -80,8 +80,9 @@ SerialPortReadRegister ( { if (PcdGetBool (PcdSerialUseMmio)) { if (PcdGet8 (PcdSerialRegisterAccessWidth) == 32) { - return (UINT8) MmioRead32 (Base + Offset * PcdGet32 (PcdSerialRegisterStride)); + return (UINT8)MmioRead32 (Base + Offset * PcdGet32 (PcdSerialRegisterStride)); } + return MmioRead8 (Base + Offset * PcdGet32 (PcdSerialRegisterStride)); } else { return IoRead8 (Base + Offset * PcdGet32 (PcdSerialRegisterStride)); @@ -111,8 +112,9 @@ SerialPortWriteRegister ( { if (PcdGetBool (PcdSerialUseMmio)) { if (PcdGet8 (PcdSerialRegisterAccessWidth) == 32) { - return (UINT8) MmioWrite32 (Base + Offset * PcdGet32 (PcdSerialRegisterStride), (UINT8)Value); + return (UINT8)MmioWrite32 (Base + Offset * PcdGet32 (PcdSerialRegisterStride), (UINT8)Value); } + return MmioWrite8 (Base + Offset * PcdGet32 (PcdSerialRegisterStride), Value); } else { return IoWrite8 (Base + Offset * PcdGet32 (PcdSerialRegisterStride), Value); @@ -145,6 +147,7 @@ SerialPortLibUpdatePciRegister16 ( if (CurrentValue != 0) { return CurrentValue; } + return PciWrite16 (PciAddress, Value & Mask); } @@ -176,6 +179,7 @@ SerialPortLibUpdatePciRegister32 ( if (CurrentValue != 0) { return CurrentValue; } + return PciWrite32 (PciAddress, Value & Mask); } @@ -212,7 +216,7 @@ GetSerialRegisterBase ( // // Get PCI Device Info // - DeviceInfo = (PCI_UART_DEVICE_INFO *) PcdGetPtr (PcdSerialPciDeviceInfo); + DeviceInfo = (PCI_UART_DEVICE_INFO *)PcdGetPtr (PcdSerialPciDeviceInfo); // // If PCI Device Info is empty, then assume fixed address UART and return PcdSerialRegisterBase @@ -244,7 +248,7 @@ GetSerialRegisterBase ( // BusNumber = PciRead8 (PciLibAddress + PCI_BRIDGE_SECONDARY_BUS_REGISTER_OFFSET); SubordinateBusNumber = PciRead8 (PciLibAddress + PCI_BRIDGE_SUBORDINATE_BUS_REGISTER_OFFSET); - if (BusNumber == 0 || BusNumber > SubordinateBusNumber) { + if ((BusNumber == 0) || (BusNumber > SubordinateBusNumber)) { return 0; } @@ -265,20 +269,22 @@ GetSerialRegisterBase ( // // If PCI Bridge MMIO window is not in the address range decoded by the parent PCI Bridge, then return 0 // - if (MemoryBase < ParentMemoryBase || MemoryBase > ParentMemoryLimit || MemoryLimit > ParentMemoryLimit) { + if ((MemoryBase < ParentMemoryBase) || (MemoryBase > ParentMemoryLimit) || (MemoryLimit > ParentMemoryLimit)) { return 0; } + ParentMemoryBase = MemoryBase; ParentMemoryLimit = MemoryLimit; } else { IoLimit = PciRead8 (PciLibAddress + OFFSET_OF (PCI_TYPE01, Bridge.IoLimit)); - if ((IoLimit & PCI_BRIDGE_32_BIT_IO_SPACE ) == 0) { + if ((IoLimit & PCI_BRIDGE_32_BIT_IO_SPACE) == 0) { IoLimit = IoLimit >> 4; } else { IoLimit = (PciRead16 (PciLibAddress + OFFSET_OF (PCI_TYPE01, Bridge.IoLimitUpper16)) << 4) | (IoLimit >> 4); } + IoBase = PciRead8 (PciLibAddress + OFFSET_OF (PCI_TYPE01, Bridge.IoBase)); - if ((IoBase & PCI_BRIDGE_32_BIT_IO_SPACE ) == 0) { + if ((IoBase & PCI_BRIDGE_32_BIT_IO_SPACE) == 0) { IoBase = IoBase >> 4; } else { IoBase = (PciRead16 (PciLibAddress + OFFSET_OF (PCI_TYPE01, Bridge.IoBaseUpper16)) << 4) | (IoBase >> 4); @@ -294,9 +300,10 @@ GetSerialRegisterBase ( // // If PCI Bridge I/O window is not in the address range decoded by the parent PCI Bridge, then return 0 // - if (IoBase < ParentIoBase || IoBase > ParentIoLimit || IoLimit > ParentIoLimit) { + if ((IoBase < ParentIoBase) || (IoBase > ParentIoLimit) || (IoLimit > ParentIoLimit)) { return 0; } + ParentIoBase = IoBase; ParentIoLimit = IoLimit; } @@ -311,7 +318,7 @@ GetSerialRegisterBase ( // Find the first IO or MMIO BAR // RegisterBaseMask = 0xFFFFFFF0; - for (BarIndex = 0; BarIndex < PCI_MAX_BAR; BarIndex ++) { + for (BarIndex = 0; BarIndex < PCI_MAX_BAR; BarIndex++) { SerialRegisterBase = PciRead32 (PciLibAddress + PCI_BASE_ADDRESSREG_OFFSET + BarIndex * 4); if (PcdGetBool (PcdSerialUseMmio) && ((SerialRegisterBase & BIT0) == 0)) { // @@ -350,11 +357,11 @@ GetSerialRegisterBase ( // Verify that the UART BAR is in the address range decoded by the parent PCI Bridge // if (PcdGetBool (PcdSerialUseMmio)) { - if (((SerialRegisterBase >> 16) & 0xfff0) < ParentMemoryBase || ((SerialRegisterBase >> 16) & 0xfff0) > ParentMemoryLimit) { + if ((((SerialRegisterBase >> 16) & 0xfff0) < ParentMemoryBase) || (((SerialRegisterBase >> 16) & 0xfff0) > ParentMemoryLimit)) { return 0; } } else { - if ((SerialRegisterBase >> 12) < ParentIoBase || (SerialRegisterBase >> 12) > ParentIoLimit) { + if (((SerialRegisterBase >> 12) < ParentIoBase) || ((SerialRegisterBase >> 12) > ParentIoLimit)) { return 0; } } @@ -372,7 +379,7 @@ GetSerialRegisterBase ( // if (DeviceInfo->PowerManagementStatusAndControlRegister != 0x00) { if ((PciRead16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister) & (BIT0 | BIT1)) != 0x00) { - PciAnd16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister, (UINT16)~(BIT0 | BIT1)); + PciAnd16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister, (UINT16) ~(BIT0 | BIT1)); // // If PCI UART was not in D0, then make sure FIFOs are enabled, but do not reset FIFOs // @@ -383,7 +390,7 @@ GetSerialRegisterBase ( // // Get PCI Device Info // - DeviceInfo = (PCI_UART_DEVICE_INFO *) PcdGetPtr (PcdSerialPciDeviceInfo); + DeviceInfo = (PCI_UART_DEVICE_INFO *)PcdGetPtr (PcdSerialPciDeviceInfo); // // Enable I/O or MMIO in PCI Bridge @@ -408,7 +415,7 @@ GetSerialRegisterBase ( // if (DeviceInfo->PowerManagementStatusAndControlRegister != 0x00) { if ((PciRead16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister) & (BIT0 | BIT1)) != 0x00) { - PciAnd16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister, (UINT16)~(BIT0 | BIT1)); + PciAnd16 (PciLibAddress + DeviceInfo->PowerManagementStatusAndControlRegister, (UINT16) ~(BIT0 | BIT1)); } } @@ -445,7 +452,7 @@ SerialPortWritable ( // 1 0 Cable connected, but not clear to send. Wait // 1 1 Cable connected, and clear to send. Transmit // - return (BOOLEAN) ((SerialPortReadRegister (SerialRegisterBase, R_UART_MSR) & (B_UART_MSR_DSR | B_UART_MSR_CTS)) == (B_UART_MSR_DSR | B_UART_MSR_CTS)); + return (BOOLEAN)((SerialPortReadRegister (SerialRegisterBase, R_UART_MSR) & (B_UART_MSR_DSR | B_UART_MSR_CTS)) == (B_UART_MSR_DSR | B_UART_MSR_CTS)); } else { // // Wait for both DSR and CTS to be set OR for DSR to be clear. @@ -459,7 +466,7 @@ SerialPortWritable ( // 1 0 Cable connected, but not clear to send. Wait // 1 1 Cable connected, and clar to send. Transmit // - return (BOOLEAN) ((SerialPortReadRegister (SerialRegisterBase, R_UART_MSR) & (B_UART_MSR_DSR | B_UART_MSR_CTS)) != (B_UART_MSR_DSR)); + return (BOOLEAN)((SerialPortReadRegister (SerialRegisterBase, R_UART_MSR) & (B_UART_MSR_DSR | B_UART_MSR_CTS)) != (B_UART_MSR_DSR)); } } @@ -511,7 +518,7 @@ SerialPortInitialize ( // Get the base address of the serial port in either I/O or MMIO space // SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return RETURN_DEVICE_ERROR; } @@ -522,13 +529,15 @@ SerialPortInitialize ( if ((SerialPortReadRegister (SerialRegisterBase, R_UART_LCR) & 0x3F) != (PcdGet8 (PcdSerialLineControl) & 0x3F)) { Initialized = FALSE; } + SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, (UINT8)(SerialPortReadRegister (SerialRegisterBase, R_UART_LCR) | B_UART_LCR_DLAB)); - CurrentDivisor = SerialPortReadRegister (SerialRegisterBase, R_UART_BAUD_HIGH) << 8; - CurrentDivisor |= (UINT32) SerialPortReadRegister (SerialRegisterBase, R_UART_BAUD_LOW); + CurrentDivisor = SerialPortReadRegister (SerialRegisterBase, R_UART_BAUD_HIGH) << 8; + CurrentDivisor |= (UINT32)SerialPortReadRegister (SerialRegisterBase, R_UART_BAUD_LOW); SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, (UINT8)(SerialPortReadRegister (SerialRegisterBase, R_UART_LCR) & ~B_UART_LCR_DLAB)); if (CurrentDivisor != Divisor) { Initialized = FALSE; } + if (Initialized) { return RETURN_SUCCESS; } @@ -537,14 +546,15 @@ SerialPortInitialize ( // Wait for the serial port to be ready. // Verify that both the transmit FIFO and the shift register are empty. // - while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)); + while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) { + } // // Configure baud rate // SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, B_UART_LCR_DLAB); - SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_HIGH, (UINT8) (Divisor >> 8)); - SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_LOW, (UINT8) (Divisor & 0xff)); + SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_HIGH, (UINT8)(Divisor >> 8)); + SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_LOW, (UINT8)(Divisor & 0xff)); // // Clear DLAB and configure Data Bits, Parity, and Stop Bits. @@ -594,8 +604,8 @@ SerialPortInitialize ( UINTN EFIAPI SerialPortWrite ( - IN UINT8 *Buffer, - IN UINTN NumberOfBytes + IN UINT8 *Buffer, + IN UINTN NumberOfBytes ) { UINTN SerialRegisterBase; @@ -608,7 +618,7 @@ SerialPortWrite ( } SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return 0; } @@ -620,12 +630,15 @@ SerialPortWrite ( // // Wait for both the transmit FIFO and shift register empty. // - while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)); + while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) { + } // // Wait for the hardware flow control signal // - while (!SerialPortWritable (SerialRegisterBase)); + while (!SerialPortWritable (SerialRegisterBase)) { + } + return 0; } @@ -647,7 +660,8 @@ SerialPortWrite ( // Wait for the serial port to be ready, to make sure both the transmit FIFO // and shift register empty. // - while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)); + while ((SerialPortReadRegister (SerialRegisterBase, R_UART_LSR) & (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) != (B_UART_LSR_TEMT | B_UART_LSR_TXRDY)) { + } // // Fill then entire Tx FIFO @@ -656,7 +670,8 @@ SerialPortWrite ( // // Wait for the hardware flow control signal // - while (!SerialPortWritable (SerialRegisterBase)); + while (!SerialPortWritable (SerialRegisterBase)) { + } // // Write byte to the transmit buffer. @@ -664,6 +679,7 @@ SerialPortWrite ( SerialPortWriteRegister (SerialRegisterBase, R_UART_TXBUF, *Buffer); } } + return Result; } @@ -681,8 +697,8 @@ SerialPortWrite ( UINTN EFIAPI SerialPortRead ( - OUT UINT8 *Buffer, - IN UINTN NumberOfBytes + OUT UINT8 *Buffer, + IN UINTN NumberOfBytes ) { UINTN SerialRegisterBase; @@ -694,7 +710,7 @@ SerialPortRead ( } SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return 0; } @@ -712,6 +728,7 @@ SerialPortRead ( SerialPortWriteRegister (SerialRegisterBase, R_UART_MCR, (UINT8)(Mcr | B_UART_MCR_RTS)); } } + if (PcdGetBool (PcdSerialUseHardwareFlowControl)) { // // Clear RTS to prevent peer from sending data @@ -728,7 +745,6 @@ SerialPortRead ( return Result; } - /** Polls a serial device to see if there is any data waiting to be read. @@ -749,7 +765,7 @@ SerialPortPoll ( UINTN SerialRegisterBase; SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return FALSE; } @@ -763,6 +779,7 @@ SerialPortPoll ( // SerialPortWriteRegister (SerialRegisterBase, R_UART_MCR, (UINT8)(SerialPortReadRegister (SerialRegisterBase, R_UART_MCR) & ~B_UART_MCR_RTS)); } + return TRUE; } @@ -789,29 +806,30 @@ SerialPortPoll ( RETURN_STATUS EFIAPI SerialPortSetControl ( - IN UINT32 Control + IN UINT32 Control ) { - UINTN SerialRegisterBase; - UINT8 Mcr; + UINTN SerialRegisterBase; + UINT8 Mcr; // // First determine the parameter is invalid. // if ((Control & (~(EFI_SERIAL_REQUEST_TO_SEND | EFI_SERIAL_DATA_TERMINAL_READY | - EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0) { + EFI_SERIAL_HARDWARE_FLOW_CONTROL_ENABLE))) != 0) + { return RETURN_UNSUPPORTED; } SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return RETURN_UNSUPPORTED; } // // Read the Modem Control Register. // - Mcr = SerialPortReadRegister (SerialRegisterBase, R_UART_MCR); + Mcr = SerialPortReadRegister (SerialRegisterBase, R_UART_MCR); Mcr &= (~(B_UART_MCR_DTRC | B_UART_MCR_RTS)); if ((Control & EFI_SERIAL_DATA_TERMINAL_READY) == EFI_SERIAL_DATA_TERMINAL_READY) { @@ -843,16 +861,16 @@ SerialPortSetControl ( RETURN_STATUS EFIAPI SerialPortGetControl ( - OUT UINT32 *Control + OUT UINT32 *Control ) { - UINTN SerialRegisterBase; - UINT8 Msr; - UINT8 Mcr; - UINT8 Lsr; + UINTN SerialRegisterBase; + UINT8 Msr; + UINT8 Mcr; + UINT8 Lsr; SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return RETURN_UNSUPPORTED; } @@ -948,24 +966,24 @@ SerialPortGetControl ( RETURN_STATUS EFIAPI SerialPortSetAttributes ( - IN OUT UINT64 *BaudRate, - IN OUT UINT32 *ReceiveFifoDepth, - IN OUT UINT32 *Timeout, - IN OUT EFI_PARITY_TYPE *Parity, - IN OUT UINT8 *DataBits, - IN OUT EFI_STOP_BITS_TYPE *StopBits + IN OUT UINT64 *BaudRate, + IN OUT UINT32 *ReceiveFifoDepth, + IN OUT UINT32 *Timeout, + IN OUT EFI_PARITY_TYPE *Parity, + IN OUT UINT8 *DataBits, + IN OUT EFI_STOP_BITS_TYPE *StopBits ) { - UINTN SerialRegisterBase; - UINT32 SerialBaudRate; - UINTN Divisor; - UINT8 Lcr; - UINT8 LcrData; - UINT8 LcrParity; - UINT8 LcrStop; + UINTN SerialRegisterBase; + UINT32 SerialBaudRate; + UINTN Divisor; + UINT8 Lcr; + UINT8 LcrData; + UINT8 LcrParity; + UINT8 LcrStop; SerialRegisterBase = GetSerialRegisterBase (); - if (SerialRegisterBase ==0) { + if (SerialRegisterBase == 0) { return RETURN_UNSUPPORTED; } @@ -975,23 +993,25 @@ SerialPortSetAttributes ( if (*BaudRate == 0) { *BaudRate = PcdGet32 (PcdSerialBaudRate); } - SerialBaudRate = (UINT32) *BaudRate; + + SerialBaudRate = (UINT32)*BaudRate; if (*DataBits == 0) { - LcrData = (UINT8) (PcdGet8 (PcdSerialLineControl) & 0x3); + LcrData = (UINT8)(PcdGet8 (PcdSerialLineControl) & 0x3); *DataBits = LcrData + 5; } else { if ((*DataBits < 5) || (*DataBits > 8)) { return RETURN_INVALID_PARAMETER; } + // // Map 5..8 to 0..3 // - LcrData = (UINT8) (*DataBits - (UINT8) 5); + LcrData = (UINT8)(*DataBits - (UINT8)5); } if (*Parity == DefaultParity) { - LcrParity = (UINT8) ((PcdGet8 (PcdSerialLineControl) >> 3) & 0x7); + LcrParity = (UINT8)((PcdGet8 (PcdSerialLineControl) >> 3) & 0x7); switch (LcrParity) { case 0: *Parity = NoParity; @@ -1044,7 +1064,7 @@ SerialPortSetAttributes ( } if (*StopBits == DefaultStopBits) { - LcrStop = (UINT8) ((PcdGet8 (PcdSerialLineControl) >> 2) & 0x1); + LcrStop = (UINT8)((PcdGet8 (PcdSerialLineControl) >> 2) & 0x1); switch (LcrStop) { case 0: *StopBits = OneStopBit; @@ -1056,6 +1076,7 @@ SerialPortSetAttributes ( } else { *StopBits = TwoStopBits; } + break; default: @@ -1090,15 +1111,15 @@ SerialPortSetAttributes ( // Configure baud rate // SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, B_UART_LCR_DLAB); - SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_HIGH, (UINT8) (Divisor >> 8)); - SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_LOW, (UINT8) (Divisor & 0xff)); + SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_HIGH, (UINT8)(Divisor >> 8)); + SerialPortWriteRegister (SerialRegisterBase, R_UART_BAUD_LOW, (UINT8)(Divisor & 0xff)); // // Clear DLAB and configure Data Bits, Parity, and Stop Bits. // Strip reserved bits from line control value // - Lcr = (UINT8) ((LcrParity << 3) | (LcrStop << 2) | LcrData); - SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, (UINT8) (Lcr & 0x3F)); + Lcr = (UINT8)((LcrParity << 3) | (LcrStop << 2) | LcrData); + SerialPortWriteRegister (SerialRegisterBase, R_UART_LCR, (UINT8)(Lcr & 0x3F)); return RETURN_SUCCESS; } diff --git a/MdeModulePkg/Library/BaseSortLib/BaseSortLib.c b/MdeModulePkg/Library/BaseSortLib/BaseSortLib.c index 0903943ee4..b5a84e366a 100644 --- a/MdeModulePkg/Library/BaseSortLib/BaseSortLib.c +++ b/MdeModulePkg/Library/BaseSortLib/BaseSortLib.c @@ -34,19 +34,19 @@ VOID EFIAPI PerformQuickSort ( - IN OUT VOID *BufferToSort, - IN CONST UINTN Count, - IN CONST UINTN ElementSize, - IN SORT_COMPARE CompareFunction + IN OUT VOID *BufferToSort, + IN CONST UINTN Count, + IN CONST UINTN ElementSize, + IN SORT_COMPARE CompareFunction ) { VOID *Buffer; - ASSERT(BufferToSort != NULL); - ASSERT(CompareFunction != NULL); + ASSERT (BufferToSort != NULL); + ASSERT (CompareFunction != NULL); - Buffer = AllocateZeroPool(ElementSize); - ASSERT(Buffer != NULL); + Buffer = AllocateZeroPool (ElementSize); + ASSERT (Buffer != NULL); QuickSort ( BufferToSort, @@ -56,7 +56,7 @@ PerformQuickSort ( Buffer ); - FreePool(Buffer); + FreePool (Buffer); return; } @@ -71,11 +71,11 @@ PerformQuickSort ( INTN EFIAPI DevicePathCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ) { - ASSERT(FALSE); + ASSERT (FALSE); return 0; } @@ -90,15 +90,14 @@ DevicePathCompare ( INTN EFIAPI StringNoCaseCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ) { - ASSERT(FALSE); + ASSERT (FALSE); return 0; } - /** Not supported in Base version. @@ -110,12 +109,10 @@ StringNoCaseCompare ( INTN EFIAPI StringCompare ( - IN CONST VOID *Buffer1, - IN CONST VOID *Buffer2 + IN CONST VOID *Buffer1, + IN CONST VOID *Buffer2 ) { - ASSERT(FALSE); + ASSERT (FALSE); return 0; } - - diff --git a/MdeModulePkg/Library/BootDiscoveryPolicyUiLib/BootDiscoveryPolicyUiLib.c b/MdeModulePkg/Library/BootDiscoveryPolicyUiLib/BootDiscoveryPolicyUiLib.c index 615958799c..a17d62a012 100644 --- a/MdeModulePkg/Library/BootDiscoveryPolicyUiLib/BootDiscoveryPolicyUiLib.c +++ b/MdeModulePkg/Library/BootDiscoveryPolicyUiLib/BootDiscoveryPolicyUiLib.c @@ -24,16 +24,16 @@ /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; -extern UINT8 BootDiscoveryPolicyUiLibVfrBin[]; +extern UINT8 BootDiscoveryPolicyUiLibVfrBin[]; -EFI_HII_HANDLE mBPHiiHandle = NULL; +EFI_HII_HANDLE mBPHiiHandle = NULL; EFI_HANDLE mBPDriverHandle = NULL; -STATIC HII_VENDOR_DEVICE_PATH mVendorDevicePath = { +STATIC HII_VENDOR_DEVICE_PATH mVendorDevicePath = { { { HARDWARE_DEVICE_PATH, @@ -69,15 +69,15 @@ STATIC HII_VENDOR_DEVICE_PATH mVendorDevicePath = { EFI_STATUS EFIAPI BootDiscoveryPolicyUiLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - UINTN Size; - UINT32 BootDiscoveryPolicy; + EFI_STATUS Status; + UINTN Size; + UINT32 BootDiscoveryPolicy; - Size = sizeof (UINT32); + Size = sizeof (UINT32); Status = gRT->GetVariable ( BOOT_DISCOVERY_POLICY_VAR, &gBootDiscoveryPolicyMgrFormsetGuid, @@ -141,7 +141,6 @@ BootDiscoveryPolicyUiLibDestructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - if (mBPDriverHandle != NULL) { gBS->UninstallProtocolInterface ( mBPDriverHandle, diff --git a/MdeModulePkg/Library/BootLogoLib/BootLogoLib.c b/MdeModulePkg/Library/BootLogoLib/BootLogoLib.c index 134660f28d..478ec2d40e 100644 --- a/MdeModulePkg/Library/BootLogoLib/BootLogoLib.c +++ b/MdeModulePkg/Library/BootLogoLib/BootLogoLib.c @@ -35,35 +35,35 @@ BootLogoEnableLogo ( VOID ) { - EFI_STATUS Status; - EDKII_PLATFORM_LOGO_PROTOCOL *PlatformLogo; - EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE Attribute; - INTN OffsetX; - INTN OffsetY; - UINT32 SizeOfX; - UINT32 SizeOfY; - INTN DestX; - INTN DestY; - UINT32 Instance; - EFI_IMAGE_INPUT Image; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; - EFI_UGA_DRAW_PROTOCOL *UgaDraw; - UINT32 ColorDepth; - UINT32 RefreshRate; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; - EFI_BOOT_LOGO_PROTOCOL *BootLogo; - EDKII_BOOT_LOGO2_PROTOCOL *BootLogo2; - UINTN NumberOfLogos; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *LogoBlt; - UINTN LogoDestX; - UINTN LogoDestY; - UINTN LogoHeight; - UINTN LogoWidth; - UINTN NewDestX; - UINTN NewDestY; - UINTN BufferSize; - - Status = gBS->LocateProtocol (&gEdkiiPlatformLogoProtocolGuid, NULL, (VOID **) &PlatformLogo); + EFI_STATUS Status; + EDKII_PLATFORM_LOGO_PROTOCOL *PlatformLogo; + EDKII_PLATFORM_LOGO_DISPLAY_ATTRIBUTE Attribute; + INTN OffsetX; + INTN OffsetY; + UINT32 SizeOfX; + UINT32 SizeOfY; + INTN DestX; + INTN DestY; + UINT32 Instance; + EFI_IMAGE_INPUT Image; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; + EFI_UGA_DRAW_PROTOCOL *UgaDraw; + UINT32 ColorDepth; + UINT32 RefreshRate; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + EFI_BOOT_LOGO_PROTOCOL *BootLogo; + EDKII_BOOT_LOGO2_PROTOCOL *BootLogo2; + UINTN NumberOfLogos; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *LogoBlt; + UINTN LogoDestX; + UINTN LogoDestY; + UINTN LogoHeight; + UINTN LogoWidth; + UINTN NewDestX; + UINTN NewDestY; + UINTN BufferSize; + + Status = gBS->LocateProtocol (&gEdkiiPlatformLogoProtocolGuid, NULL, (VOID **)&PlatformLogo); if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -72,17 +72,18 @@ BootLogoEnableLogo ( // // Try to open GOP first // - Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID **) &GraphicsOutput); + Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID **)&GraphicsOutput); if (EFI_ERROR (Status) && FeaturePcdGet (PcdUgaConsumeSupport)) { GraphicsOutput = NULL; // // Open GOP failed, try to open UGA // - Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiUgaDrawProtocolGuid, (VOID **) &UgaDraw); + Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiUgaDrawProtocolGuid, (VOID **)&UgaDraw); if (EFI_ERROR (Status)) { UgaDraw = NULL; } } + if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -90,7 +91,7 @@ BootLogoEnableLogo ( // // Try to open Boot Logo Protocol. // - Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); + Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **)&BootLogo); if (EFI_ERROR (Status)) { BootLogo = NULL; } @@ -98,7 +99,7 @@ BootLogoEnableLogo ( // // Try to open Boot Logo 2 Protocol. // - Status = gBS->LocateProtocol (&gEdkiiBootLogo2ProtocolGuid, NULL, (VOID **) &BootLogo2); + Status = gBS->LocateProtocol (&gEdkiiBootLogo2ProtocolGuid, NULL, (VOID **)&BootLogo2); if (EFI_ERROR (Status)) { BootLogo2 = NULL; } @@ -111,7 +112,6 @@ BootLogoEnableLogo ( if (GraphicsOutput != NULL) { SizeOfX = GraphicsOutput->Mode->Info->HorizontalResolution; SizeOfY = GraphicsOutput->Mode->Info->VerticalResolution; - } else { ASSERT (UgaDraw != NULL); Status = UgaDraw->GetMode (UgaDraw, &SizeOfX, &SizeOfY, &ColorDepth, &RefreshRate); @@ -120,17 +120,17 @@ BootLogoEnableLogo ( } } - Blt = NULL; + Blt = NULL; NumberOfLogos = 0; - LogoDestX = 0; - LogoDestY = 0; - LogoHeight = 0; - LogoWidth = 0; - NewDestX = 0; - NewDestY = 0; - Instance = 0; - DestX = 0; - DestY = 0; + LogoDestX = 0; + LogoDestY = 0; + LogoHeight = 0; + LogoWidth = 0; + NewDestX = 0; + NewDestY = 0; + Instance = 0; + DestX = 0; + DestY = 0; while (TRUE) { // // Get image from PlatformLogo protocol. @@ -150,55 +150,56 @@ BootLogoEnableLogo ( if (Blt != NULL) { FreePool (Blt); } + Blt = Image.Bitmap; // // Calculate the display position according to Attribute. // switch (Attribute) { - case EdkiiPlatformLogoDisplayAttributeLeftTop: - DestX = 0; - DestY = 0; - break; - case EdkiiPlatformLogoDisplayAttributeCenterTop: - DestX = (SizeOfX - Image.Width) / 2; - DestY = 0; - break; - case EdkiiPlatformLogoDisplayAttributeRightTop: - DestX = SizeOfX - Image.Width; - DestY = 0; - break; - - case EdkiiPlatformLogoDisplayAttributeCenterLeft: - DestX = 0; - DestY = (SizeOfY - Image.Height) / 2; - break; - case EdkiiPlatformLogoDisplayAttributeCenter: - DestX = (SizeOfX - Image.Width) / 2; - DestY = (SizeOfY - Image.Height) / 2; - break; - case EdkiiPlatformLogoDisplayAttributeCenterRight: - DestX = SizeOfX - Image.Width; - DestY = (SizeOfY - Image.Height) / 2; - break; - - case EdkiiPlatformLogoDisplayAttributeLeftBottom: - DestX = 0; - DestY = SizeOfY - Image.Height; - break; - case EdkiiPlatformLogoDisplayAttributeCenterBottom: - DestX = (SizeOfX - Image.Width) / 2; - DestY = SizeOfY - Image.Height; - break; - case EdkiiPlatformLogoDisplayAttributeRightBottom: - DestX = SizeOfX - Image.Width; - DestY = SizeOfY - Image.Height; - break; - - default: - ASSERT (FALSE); - continue; - break; + case EdkiiPlatformLogoDisplayAttributeLeftTop: + DestX = 0; + DestY = 0; + break; + case EdkiiPlatformLogoDisplayAttributeCenterTop: + DestX = (SizeOfX - Image.Width) / 2; + DestY = 0; + break; + case EdkiiPlatformLogoDisplayAttributeRightTop: + DestX = SizeOfX - Image.Width; + DestY = 0; + break; + + case EdkiiPlatformLogoDisplayAttributeCenterLeft: + DestX = 0; + DestY = (SizeOfY - Image.Height) / 2; + break; + case EdkiiPlatformLogoDisplayAttributeCenter: + DestX = (SizeOfX - Image.Width) / 2; + DestY = (SizeOfY - Image.Height) / 2; + break; + case EdkiiPlatformLogoDisplayAttributeCenterRight: + DestX = SizeOfX - Image.Width; + DestY = (SizeOfY - Image.Height) / 2; + break; + + case EdkiiPlatformLogoDisplayAttributeLeftBottom: + DestX = 0; + DestY = SizeOfY - Image.Height; + break; + case EdkiiPlatformLogoDisplayAttributeCenterBottom: + DestX = (SizeOfX - Image.Width) / 2; + DestY = SizeOfY - Image.Height; + break; + case EdkiiPlatformLogoDisplayAttributeRightBottom: + DestX = SizeOfX - Image.Width; + DestY = SizeOfY - Image.Height; + break; + + default: + ASSERT (FALSE); + continue; + break; } DestX += OffsetX; @@ -212,8 +213,8 @@ BootLogoEnableLogo ( EfiBltBufferToVideo, 0, 0, - (UINTN) DestX, - (UINTN) DestY, + (UINTN)DestX, + (UINTN)DestY, Image.Width, Image.Height, Image.Width * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) @@ -222,12 +223,12 @@ BootLogoEnableLogo ( ASSERT (UgaDraw != NULL); Status = UgaDraw->Blt ( UgaDraw, - (EFI_UGA_PIXEL *) Blt, + (EFI_UGA_PIXEL *)Blt, EfiUgaBltBufferToVideo, 0, 0, - (UINTN) DestX, - (UINTN) DestY, + (UINTN)DestX, + (UINTN)DestY, Image.Width, Image.Height, Image.Width * sizeof (EFI_UGA_PIXEL) @@ -244,18 +245,18 @@ BootLogoEnableLogo ( // // The first Logo. // - LogoDestX = (UINTN) DestX; - LogoDestY = (UINTN) DestY; - LogoWidth = Image.Width; + LogoDestX = (UINTN)DestX; + LogoDestY = (UINTN)DestY; + LogoWidth = Image.Width; LogoHeight = Image.Height; } else { // // Merge new logo with old one. // - NewDestX = MIN ((UINTN) DestX, LogoDestX); - NewDestY = MIN ((UINTN) DestY, LogoDestY); - LogoWidth = MAX ((UINTN) DestX + Image.Width, LogoDestX + LogoWidth) - NewDestX; - LogoHeight = MAX ((UINTN) DestY + Image.Height, LogoDestY + LogoHeight) - NewDestY; + NewDestX = MIN ((UINTN)DestX, LogoDestX); + NewDestY = MIN ((UINTN)DestY, LogoDestY); + LogoWidth = MAX ((UINTN)DestX + Image.Width, LogoDestX + LogoWidth) - NewDestX; + LogoHeight = MAX ((UINTN)DestY + Image.Height, LogoDestY + LogoHeight) - NewDestY; LogoDestX = NewDestX; LogoDestY = NewDestY; @@ -264,7 +265,7 @@ BootLogoEnableLogo ( } } - if ((BootLogo == NULL && BootLogo2 == NULL) || NumberOfLogos == 0) { + if (((BootLogo == NULL) && (BootLogo2 == NULL)) || (NumberOfLogos == 0)) { // // No logo displayed. // @@ -283,7 +284,7 @@ BootLogoEnableLogo ( // Only one logo displayed, use its Blt buffer directly for BootLogo protocol. // LogoBlt = Blt; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } else { // // More than one Logo displayed, get merged BltBuffer using VideoToBuffer operation. @@ -298,6 +299,7 @@ BootLogoEnableLogo ( if (LogoHeight > MAX_UINTN / LogoWidth / sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)) { return EFI_UNSUPPORTED; } + BufferSize = LogoWidth * LogoHeight * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL); LogoBlt = AllocatePool (BufferSize); @@ -307,21 +309,21 @@ BootLogoEnableLogo ( if (GraphicsOutput != NULL) { Status = GraphicsOutput->Blt ( - GraphicsOutput, - LogoBlt, - EfiBltVideoToBltBuffer, - LogoDestX, - LogoDestY, - 0, - 0, - LogoWidth, - LogoHeight, - LogoWidth * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) - ); + GraphicsOutput, + LogoBlt, + EfiBltVideoToBltBuffer, + LogoDestX, + LogoDestY, + 0, + 0, + LogoWidth, + LogoHeight, + LogoWidth * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + ); } else { Status = UgaDraw->Blt ( UgaDraw, - (EFI_UGA_PIXEL *) LogoBlt, + (EFI_UGA_PIXEL *)LogoBlt, EfiUgaVideoToBltBuffer, LogoDestX, LogoDestY, @@ -341,19 +343,22 @@ BootLogoEnableLogo ( if (BootLogo2 != NULL) { Status = BootLogo2->SetBootLogo (BootLogo2, LogoBlt, LogoDestX, LogoDestY, LogoWidth, LogoHeight); } + // // If Boot Logo 2 Protocol is not available or registration with Boot Logo 2 // Protocol failed, then attempt to register logo with Boot Logo Protocol // - if (EFI_ERROR (Status) && BootLogo != NULL) { + if (EFI_ERROR (Status) && (BootLogo != NULL)) { Status = BootLogo->SetBootLogo (BootLogo, LogoBlt, LogoDestX, LogoDestY, LogoWidth, LogoHeight); } + // // Status of this function is EFI_SUCCESS even if registration with Boot // Logo 2 Protocol or Boot Logo Protocol fails. // Status = EFI_SUCCESS; } + FreePool (LogoBlt); return Status; @@ -372,7 +377,6 @@ BootLogoDisableLogo ( VOID ) { - // // Enable Cursor on Screen // @@ -380,7 +384,6 @@ BootLogoDisableLogo ( return EFI_SUCCESS; } - /** Update progress bar with title above it. It only works in Graphics mode. @@ -398,12 +401,12 @@ BootLogoDisableLogo ( EFI_STATUS EFIAPI BootLogoUpdateProgress ( - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground, - IN CHAR16 *Title, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor, - IN UINTN Progress, - IN UINTN PreviousValue + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleForeground, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL TitleBackground, + IN CHAR16 *Title, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL ProgressColor, + IN UINTN Progress, + IN UINTN PreviousValue ) { EFI_STATUS Status; @@ -426,15 +429,16 @@ BootLogoUpdateProgress ( } UgaDraw = NULL; - Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID **) &GraphicsOutput); + Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID **)&GraphicsOutput); if (EFI_ERROR (Status) && FeaturePcdGet (PcdUgaConsumeSupport)) { GraphicsOutput = NULL; - Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiUgaDrawProtocolGuid, (VOID **) &UgaDraw); + Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiUgaDrawProtocolGuid, (VOID **)&UgaDraw); if (EFI_ERROR (Status)) { UgaDraw = NULL; } } + if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } @@ -462,10 +466,10 @@ BootLogoUpdateProgress ( BlockWidth = SizeOfX / 100; BlockHeight = SizeOfY / 50; - BlockNum = Progress; + BlockNum = Progress; - PosX = 0; - PosY = SizeOfY * 48 / 50; + PosX = 0; + PosY = SizeOfY * 48 / 50; if (BlockNum == 0) { // @@ -475,21 +479,21 @@ BootLogoUpdateProgress ( if (GraphicsOutput != NULL) { Status = GraphicsOutput->Blt ( - GraphicsOutput, - &Color, - EfiBltVideoFill, - 0, - 0, - 0, - PosY - EFI_GLYPH_HEIGHT - 1, - SizeOfX, - SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1), - SizeOfX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) - ); + GraphicsOutput, + &Color, + EfiBltVideoFill, + 0, + 0, + 0, + PosY - EFI_GLYPH_HEIGHT - 1, + SizeOfX, + SizeOfY - (PosY - EFI_GLYPH_HEIGHT - 1), + SizeOfX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { Status = UgaDraw->Blt ( UgaDraw, - (EFI_UGA_PIXEL *) &Color, + (EFI_UGA_PIXEL *)&Color, EfiUgaVideoFill, 0, 0, @@ -503,6 +507,7 @@ BootLogoUpdateProgress ( return EFI_UNSUPPORTED; } } + // // Show progress by drawing blocks // @@ -510,21 +515,21 @@ BootLogoUpdateProgress ( PosX = Index * BlockWidth; if (GraphicsOutput != NULL) { Status = GraphicsOutput->Blt ( - GraphicsOutput, - &ProgressColor, - EfiBltVideoFill, - 0, - 0, - PosX, - PosY, - BlockWidth - 1, - BlockHeight, - (BlockWidth) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) - ); + GraphicsOutput, + &ProgressColor, + EfiBltVideoFill, + 0, + 0, + PosX, + PosY, + BlockWidth - 1, + BlockHeight, + (BlockWidth) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) + ); } else if (FeaturePcdGet (PcdUgaConsumeSupport)) { Status = UgaDraw->Blt ( UgaDraw, - (EFI_UGA_PIXEL *) &ProgressColor, + (EFI_UGA_PIXEL *)&ProgressColor, EfiUgaVideoFill, 0, 0, diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BmLib.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BmLib.c index 4a1905a1cd..c2e3bff54c 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BmLib.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BmLib.c @@ -23,8 +23,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EfiLibDeleteVariable ( - IN CHAR16 *VarName, - IN EFI_GUID *VarGuid + IN CHAR16 *VarName, + IN EFI_GUID *VarGuid ) { return gRT->SetVariable ( @@ -49,11 +49,11 @@ EfiLibDeleteVariable ( **/ UINTN EfiDevicePathInstanceCount ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - UINTN Count; - UINTN Size; + UINTN Count; + UINTN Size; Count = 0; while (GetNextDevicePathInstance (&DevicePath, &Size) != NULL) { @@ -76,7 +76,7 @@ EfiDevicePathInstanceCount ( **/ UINT16 * EfiLibStrFromDatahub ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ) { return NULL; diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenance.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenance.c index 28592f9f47..19751642a3 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenance.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenance.c @@ -8,23 +8,23 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "BootMaintenanceManager.h" -#define FRONT_PAGE_KEY_OFFSET 0x4000 +#define FRONT_PAGE_KEY_OFFSET 0x4000 // // Boot video resolution and text mode. // -UINT32 mBmmBootHorizontalResolution = 0; -UINT32 mBmmBootVerticalResolution = 0; -UINT32 mBmmBootTextModeColumn = 0; -UINT32 mBmmBootTextModeRow = 0; +UINT32 mBmmBootHorizontalResolution = 0; +UINT32 mBmmBootVerticalResolution = 0; +UINT32 mBmmBootTextModeColumn = 0; +UINT32 mBmmBootTextModeRow = 0; // // BIOS setup video resolution and text mode. // -UINT32 mBmmSetupTextModeColumn = 0; -UINT32 mBmmSetupTextModeRow = 0; -UINT32 mBmmSetupHorizontalResolution = 0; -UINT32 mBmmSetupVerticalResolution = 0; +UINT32 mBmmSetupTextModeColumn = 0; +UINT32 mBmmSetupTextModeRow = 0; +UINT32 mBmmSetupHorizontalResolution = 0; +UINT32 mBmmSetupVerticalResolution = 0; -BOOLEAN mBmmModeInitialized = FALSE; +BOOLEAN mBmmModeInitialized = FALSE; EFI_DEVICE_PATH_PROTOCOL EndDevicePath[] = { { @@ -43,28 +43,29 @@ HII_VENDOR_DEVICE_PATH mBmmHiiVendorDevicePath = { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, // // {165A028F-0BB2-4b5f-8747-77592E3F6499} // - { 0x165a028f, 0xbb2, 0x4b5f, { 0x87, 0x47, 0x77, 0x59, 0x2e, 0x3f, 0x64, 0x99 } } + { 0x165a028f, 0xbb2, 0x4b5f, { 0x87, 0x47, 0x77, 0x59, 0x2e, 0x3f, 0x64, 0x99 } + } }, { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (END_DEVICE_PATH_LENGTH), - (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8) + (UINT8)(END_DEVICE_PATH_LENGTH), + (UINT8)((END_DEVICE_PATH_LENGTH) >> 8) } } }; -EFI_GUID mBootMaintGuid = BOOT_MAINT_FORMSET_GUID; +EFI_GUID mBootMaintGuid = BOOT_MAINT_FORMSET_GUID; -CHAR16 mBootMaintStorageName[] = L"BmmData"; +CHAR16 mBootMaintStorageName[] = L"BmmData"; BMM_CALLBACK_DATA gBootMaintenancePrivate = { BMM_CALLBACK_DATA_SIGNATURE, NULL, @@ -76,9 +77,9 @@ BMM_CALLBACK_DATA gBootMaintenancePrivate = { } }; -BMM_CALLBACK_DATA *mBmmCallbackInfo = &gBootMaintenancePrivate; -BOOLEAN mAllMenuInit = FALSE; -BOOLEAN mFirstEnterBMMForm = FALSE; +BMM_CALLBACK_DATA *mBmmCallbackInfo = &gBootMaintenancePrivate; +BOOLEAN mAllMenuInit = FALSE; +BOOLEAN mFirstEnterBMMForm = FALSE; /** Init all memu. @@ -88,7 +89,7 @@ BOOLEAN mFirstEnterBMMForm = FALSE; **/ VOID InitAllMenu ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -152,7 +153,7 @@ BmmSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -161,7 +162,7 @@ BmmSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -190,7 +191,7 @@ BmmSetConsoleMode ( } if (GraphicsOutput != NULL) { - MaxGopMode = GraphicsOutput->Mode->MaxMode; + MaxGopMode = GraphicsOutput->Mode->MaxMode; } if (SimpleTextOut != NULL) { @@ -206,22 +207,24 @@ BmmSetConsoleMode ( // for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( - GraphicsOutput, - ModeNumber, - &SizeOfInfo, - &Info - ); + GraphicsOutput, + ModeNumber, + &SizeOfInfo, + &Info + ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == NewHorizontalResolution) && - (Info->VerticalResolution == NewVerticalResolution)) { + (Info->VerticalResolution == NewVerticalResolution)) + { if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) && - (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) { + (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) + { // // Current resolution is same with required resolution, check if text mode need be set // Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow); ASSERT_EFI_ERROR (Status); - if (CurrentColumn == NewColumns && CurrentRow == NewRows) { + if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // If current text mode is same with required text mode. Do nothing // @@ -233,7 +236,7 @@ BmmSetConsoleMode ( // for (Index = 0; Index < MaxTextMode; Index++) { Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // Required text mode is supported, set it. @@ -252,6 +255,7 @@ BmmSetConsoleMode ( } } } + if (Index == MaxTextMode) { // // If required text mode is not supported, return error. @@ -272,6 +276,7 @@ BmmSetConsoleMode ( } } } + FreePool (Info); } } @@ -302,19 +307,21 @@ BmmSetConsoleMode ( // Locate all the handles with GOP protocol and reconnect it. // Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextOutProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextOutProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); } + for (Index = 0; Index < HandleCount; Index++) { gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } + if (HandleBuffer != NULL) { FreePool (HandleBuffer); } @@ -333,12 +340,12 @@ BmmSetConsoleMode ( **/ CHAR16 * UiDevicePathToStr ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ) { - EFI_STATUS Status; - CHAR16 *ToText; - EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; + EFI_STATUS Status; + CHAR16 *ToText; + EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; if (DevPath == NULL) { return NULL; @@ -347,7 +354,7 @@ UiDevicePathToStr ( Status = gBS->LocateProtocol ( &gEfiDevicePathToTextProtocolGuid, NULL, - (VOID **) &DevPathToText + (VOID **)&DevPathToText ); ASSERT_EFI_ERROR (Status); ToText = DevPathToText->ConvertDevicePathToText ( @@ -370,34 +377,34 @@ UiDevicePathToStr ( **/ CHAR16 * ExtractFileNameFromDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - CHAR16 *String; - CHAR16 *MatchString; - CHAR16 *LastMatch; - CHAR16 *FileName; - UINTN Length; + CHAR16 *String; + CHAR16 *MatchString; + CHAR16 *LastMatch; + CHAR16 *FileName; + UINTN Length; - ASSERT(DevicePath != NULL); + ASSERT (DevicePath != NULL); - String = UiDevicePathToStr(DevicePath); + String = UiDevicePathToStr (DevicePath); MatchString = String; LastMatch = String; FileName = NULL; - while(MatchString != NULL){ + while (MatchString != NULL) { LastMatch = MatchString + 1; - MatchString = StrStr(LastMatch,L"\\"); + MatchString = StrStr (LastMatch, L"\\"); } - Length = StrLen(LastMatch); - FileName = AllocateCopyPool ((Length + 1) * sizeof(CHAR16), LastMatch); + Length = StrLen (LastMatch); + FileName = AllocateCopyPool ((Length + 1) * sizeof (CHAR16), LastMatch); if (FileName != NULL) { *(FileName + Length) = 0; } - FreePool(String); + FreePool (String); return FileName; } @@ -413,11 +420,11 @@ ExtractFileNameFromDevicePath ( **/ CHAR16 * BmmExtractDevicePathFromHiiHandle ( - IN EFI_HII_HANDLE Handle + IN EFI_HII_HANDLE Handle ) { - EFI_STATUS Status; - EFI_HANDLE DriverHandle; + EFI_STATUS Status; + EFI_HANDLE DriverHandle; ASSERT (Handle != NULL); @@ -433,8 +440,7 @@ BmmExtractDevicePathFromHiiHandle ( // // Get device path string. // - return ConvertDevicePathToText(DevicePathFromHandle (DriverHandle), FALSE, FALSE); - + return ConvertDevicePathToText (DevicePathFromHandle (DriverHandle), FALSE, FALSE); } /** @@ -462,8 +468,8 @@ HiiToLower ( Lower = TRUE; } else if (*String == L'&') { Lower = FALSE; - } else if (Lower && *String >= L'A' && *String <= L'F') { - *String = (CHAR16) (*String - L'A' + L'a'); + } else if (Lower && (*String >= L'A') && (*String <= L'F')) { + *String = (CHAR16)(*String - L'A' + L'a'); } } } @@ -476,10 +482,10 @@ HiiToLower ( **/ EFI_STRING -UpdateProgress( +UpdateProgress ( IN UINTN Offset, IN EFI_STRING Configuration -) + ) { UINTN Length; EFI_STRING StringPtr; @@ -492,12 +498,12 @@ UpdateProgress( // &OFFSET=XXXX followed by a Null-terminator. // Length = StrLen (L"&OFFSET=") + 4 + 1 // - Length = StrLen (L"&OFFSET=") + 4 + 1; + Length = StrLen (L"&OFFSET=") + 4 + 1; StringPtr = AllocateZeroPool (Length * sizeof (CHAR16)); if (StringPtr == NULL) { - return NULL; + return NULL; } UnicodeSPrint ( @@ -530,31 +536,31 @@ UpdateProgress( **/ VOID UpdateTerminalContent ( - IN BMM_FAKE_NV_DATA *BmmData + IN BMM_FAKE_NV_DATA *BmmData ) { - UINT16 Index; - BM_TERMINAL_CONTEXT *NewTerminalContext; - BM_MENU_ENTRY *NewMenuEntry; + UINT16 Index; + BM_TERMINAL_CONTEXT *NewTerminalContext; + BM_MENU_ENTRY *NewMenuEntry; for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); ASSERT (NewMenuEntry != NULL); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; NewTerminalContext->BaudRateIndex = BmmData->COMBaudRate[Index]; ASSERT (BmmData->COMBaudRate[Index] < (ARRAY_SIZE (BaudRateList))); NewTerminalContext->BaudRate = BaudRateList[BmmData->COMBaudRate[Index]].Value; NewTerminalContext->DataBitsIndex = BmmData->COMDataRate[Index]; ASSERT (BmmData->COMDataRate[Index] < (ARRAY_SIZE (DataBitsList))); - NewTerminalContext->DataBits = (UINT8) DataBitsList[BmmData->COMDataRate[Index]].Value; + NewTerminalContext->DataBits = (UINT8)DataBitsList[BmmData->COMDataRate[Index]].Value; NewTerminalContext->StopBitsIndex = BmmData->COMStopBits[Index]; ASSERT (BmmData->COMStopBits[Index] < (ARRAY_SIZE (StopBitsList))); - NewTerminalContext->StopBits = (UINT8) StopBitsList[BmmData->COMStopBits[Index]].Value; - NewTerminalContext->ParityIndex = BmmData->COMParity[Index]; + NewTerminalContext->StopBits = (UINT8)StopBitsList[BmmData->COMStopBits[Index]].Value; + NewTerminalContext->ParityIndex = BmmData->COMParity[Index]; ASSERT (BmmData->COMParity[Index] < (ARRAY_SIZE (ParityList))); - NewTerminalContext->Parity = (UINT8) ParityList[BmmData->COMParity[Index]].Value; - NewTerminalContext->TerminalType = BmmData->COMTerminalType[Index]; - NewTerminalContext->FlowControl = BmmData->COMFlowControl[Index]; + NewTerminalContext->Parity = (UINT8)ParityList[BmmData->COMParity[Index]].Value; + NewTerminalContext->TerminalType = BmmData->COMTerminalType[Index]; + NewTerminalContext->FlowControl = BmmData->COMFlowControl[Index]; ChangeTerminalDevicePath ( NewTerminalContext->DevicePath, FALSE @@ -570,55 +576,59 @@ UpdateTerminalContent ( **/ VOID -UpdateConsoleContent( - IN CHAR16 *ConsoleName, - IN BMM_FAKE_NV_DATA *BmmData +UpdateConsoleContent ( + IN CHAR16 *ConsoleName, + IN BMM_FAKE_NV_DATA *BmmData ) { - UINT16 Index; - BM_CONSOLE_CONTEXT *NewConsoleContext; - BM_TERMINAL_CONTEXT *NewTerminalContext; - BM_MENU_ENTRY *NewMenuEntry; + UINT16 Index; + BM_CONSOLE_CONTEXT *NewConsoleContext; + BM_TERMINAL_CONTEXT *NewTerminalContext; + BM_MENU_ENTRY *NewMenuEntry; if (StrCmp (ConsoleName, L"ConIn") == 0) { - for (Index = 0; Index < ConsoleInpMenu.MenuNumber; Index++){ - NewMenuEntry = BOpt_GetMenuEntry(&ConsoleInpMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; + for (Index = 0; Index < ConsoleInpMenu.MenuNumber; Index++) { + NewMenuEntry = BOpt_GetMenuEntry (&ConsoleInpMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index < MAX_MENU_NUMBER); NewConsoleContext->IsActive = BmmData->ConsoleInCheck[Index]; } + for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleInpMenu.MenuNumber < MAX_MENU_NUMBER); NewTerminalContext->IsConIn = BmmData->ConsoleInCheck[Index + ConsoleInpMenu.MenuNumber]; } } if (StrCmp (ConsoleName, L"ConOut") == 0) { - for (Index = 0; Index < ConsoleOutMenu.MenuNumber; Index++){ - NewMenuEntry = BOpt_GetMenuEntry(&ConsoleOutMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; + for (Index = 0; Index < ConsoleOutMenu.MenuNumber; Index++) { + NewMenuEntry = BOpt_GetMenuEntry (&ConsoleOutMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index < MAX_MENU_NUMBER); NewConsoleContext->IsActive = BmmData->ConsoleOutCheck[Index]; } + for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleOutMenu.MenuNumber < MAX_MENU_NUMBER); NewTerminalContext->IsConOut = BmmData->ConsoleOutCheck[Index + ConsoleOutMenu.MenuNumber]; } } + if (StrCmp (ConsoleName, L"ErrOut") == 0) { - for (Index = 0; Index < ConsoleErrMenu.MenuNumber; Index++){ - NewMenuEntry = BOpt_GetMenuEntry(&ConsoleErrMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; + for (Index = 0; Index < ConsoleErrMenu.MenuNumber; Index++) { + NewMenuEntry = BOpt_GetMenuEntry (&ConsoleErrMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index < MAX_MENU_NUMBER); NewConsoleContext->IsActive = BmmData->ConsoleErrCheck[Index]; } + for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleErrMenu.MenuNumber < MAX_MENU_NUMBER); NewTerminalContext->IsStdErr = BmmData->ConsoleErrCheck[Index + ConsoleErrMenu.MenuNumber]; } @@ -649,21 +659,21 @@ UpdateConsoleContent( EFI_STATUS EFIAPI BootMaintExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { EFI_STATUS Status; UINTN BufferSize; BMM_CALLBACK_DATA *Private; - EFI_STRING ConfigRequestHdr; - EFI_STRING ConfigRequest; - BOOLEAN AllocatedRequest; - UINTN Size; + EFI_STRING ConfigRequestHdr; + EFI_STRING ConfigRequest; + BOOLEAN AllocatedRequest; + UINTN Size; - if (Progress == NULL || Results == NULL) { + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } @@ -681,7 +691,7 @@ BootMaintExtractConfig ( // // Convert buffer data to by helper function BlockToConfig() // - BufferSize = sizeof (BMM_FAKE_NV_DATA); + BufferSize = sizeof (BMM_FAKE_NV_DATA); ConfigRequest = Request; if ((Request == NULL) || (StrStr (Request, L"OFFSET") == NULL)) { // @@ -690,8 +700,8 @@ BootMaintExtractConfig ( // followed by "&OFFSET=0&WIDTH=WWWWWWWWWWWWWWWW" followed by a Null-terminator // ConfigRequestHdr = HiiConstructConfigHdr (&mBootMaintGuid, mBootMaintStorageName, Private->BmmDriverHandle); - Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16); - ConfigRequest = AllocateZeroPool (Size); + Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16); + ConfigRequest = AllocateZeroPool (Size); ASSERT (ConfigRequest != NULL); AllocatedRequest = TRUE; UnicodeSPrint (ConfigRequest, Size, L"%s&OFFSET=0&WIDTH=%016LX", ConfigRequestHdr, (UINT64)BufferSize); @@ -701,7 +711,7 @@ BootMaintExtractConfig ( Status = gHiiConfigRouting->BlockToConfig ( gHiiConfigRouting, ConfigRequest, - (UINT8 *) &Private->BmmFakeNvData, + (UINT8 *)&Private->BmmFakeNvData, BufferSize, Results, Progress @@ -713,6 +723,7 @@ BootMaintExtractConfig ( FreePool (ConfigRequest); ConfigRequest = NULL; } + // // Set Progress string to the original request string. // @@ -761,26 +772,27 @@ BootMaintExtractConfig ( EFI_STATUS EFIAPI BootMaintRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - EFI_STATUS Status; - UINTN BufferSize; - EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting; - BMM_FAKE_NV_DATA *NewBmmData; - BMM_FAKE_NV_DATA *OldBmmData; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT16 Index; - BOOLEAN TerminalAttChange; - BMM_CALLBACK_DATA *Private; - UINTN Offset; + EFI_STATUS Status; + UINTN BufferSize; + EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting; + BMM_FAKE_NV_DATA *NewBmmData; + BMM_FAKE_NV_DATA *OldBmmData; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT16 Index; + BOOLEAN TerminalAttChange; + BMM_CALLBACK_DATA *Private; + UINTN Offset; if (Progress == NULL) { return EFI_INVALID_PARAMETER; } + *Progress = Configuration; if (Configuration == NULL) { @@ -818,7 +830,7 @@ BootMaintRouteConfig ( Status = ConfigRouting->ConfigToBlock ( ConfigRouting, Configuration, - (UINT8 *) NewBmmData, + (UINT8 *)NewBmmData, &BufferSize, Progress ); @@ -845,11 +857,12 @@ BootMaintRouteConfig ( if (CompareMem (NewBmmData->BootOptionDel, OldBmmData->BootOptionDel, sizeof (NewBmmData->BootOptionDel)) != 0) { for (Index = 0; ((Index < BootOptionMenu.MenuNumber) && (Index < (sizeof (NewBmmData->BootOptionDel) / sizeof (NewBmmData->BootOptionDel[0])))); - Index ++) { - NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - NewLoadContext->Deleted = NewBmmData->BootOptionDel[Index]; - NewBmmData->BootOptionDel[Index] = FALSE; + Index++) + { + NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + NewLoadContext->Deleted = NewBmmData->BootOptionDel[Index]; + NewBmmData->BootOptionDel[Index] = FALSE; NewBmmData->BootOptionDelMark[Index] = FALSE; } @@ -868,18 +881,19 @@ BootMaintRouteConfig ( } } - if (CompareMem (&NewBmmData->BootTimeOut, &OldBmmData->BootTimeOut, sizeof (NewBmmData->BootTimeOut)) != 0){ - Status = gRT->SetVariable( + if (CompareMem (&NewBmmData->BootTimeOut, &OldBmmData->BootTimeOut, sizeof (NewBmmData->BootTimeOut)) != 0) { + Status = gRT->SetVariable ( L"Timeout", &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, - sizeof(UINT16), + sizeof (UINT16), &(NewBmmData->BootTimeOut) ); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, BootTimeOut); goto Exit; } + Private->BmmOldFakeNVData.BootTimeOut = NewBmmData->BootTimeOut; } @@ -889,13 +903,15 @@ BootMaintRouteConfig ( if (CompareMem (NewBmmData->DriverOptionDel, OldBmmData->DriverOptionDel, sizeof (NewBmmData->DriverOptionDel)) != 0) { for (Index = 0; ((Index < DriverOptionMenu.MenuNumber) && (Index < (sizeof (NewBmmData->DriverOptionDel) / sizeof (NewBmmData->DriverOptionDel[0])))); - Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - NewLoadContext->Deleted = NewBmmData->DriverOptionDel[Index]; - NewBmmData->DriverOptionDel[Index] = FALSE; + Index++) + { + NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + NewLoadContext->Deleted = NewBmmData->DriverOptionDel[Index]; + NewBmmData->DriverOptionDel[Index] = FALSE; NewBmmData->DriverOptionDelMark[Index] = FALSE; } + Status = Var_DelDriverOption (); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, DriverOptionDel); @@ -911,8 +927,8 @@ BootMaintRouteConfig ( } } - if (CompareMem (&NewBmmData->ConsoleOutMode, &OldBmmData->ConsoleOutMode, sizeof (NewBmmData->ConsoleOutMode)) != 0){ - Status = Var_UpdateConMode(Private); + if (CompareMem (&NewBmmData->ConsoleOutMode, &OldBmmData->ConsoleOutMode, sizeof (NewBmmData->ConsoleOutMode)) != 0) { + Status = Var_UpdateConMode (Private); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, ConsoleOutMode); goto Exit; @@ -921,21 +937,22 @@ BootMaintRouteConfig ( TerminalAttChange = FALSE; for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - // // only need update modified items // - if (CompareMem (&NewBmmData->COMBaudRate[Index], &OldBmmData->COMBaudRate[Index], sizeof (NewBmmData->COMBaudRate[Index])) == 0 && - CompareMem (&NewBmmData->COMDataRate[Index], &OldBmmData->COMDataRate[Index], sizeof (NewBmmData->COMDataRate[Index])) == 0 && - CompareMem (&NewBmmData->COMStopBits[Index], &OldBmmData->COMStopBits[Index], sizeof (NewBmmData->COMStopBits[Index])) == 0 && - CompareMem (&NewBmmData->COMParity[Index], &OldBmmData->COMParity[Index], sizeof (NewBmmData->COMParity[Index])) == 0 && - CompareMem (&NewBmmData->COMTerminalType[Index], &OldBmmData->COMTerminalType[Index], sizeof (NewBmmData->COMTerminalType[Index])) == 0 && - CompareMem (&NewBmmData->COMFlowControl[Index], &OldBmmData->COMFlowControl[Index], sizeof (NewBmmData->COMFlowControl[Index])) == 0) { + if ((CompareMem (&NewBmmData->COMBaudRate[Index], &OldBmmData->COMBaudRate[Index], sizeof (NewBmmData->COMBaudRate[Index])) == 0) && + (CompareMem (&NewBmmData->COMDataRate[Index], &OldBmmData->COMDataRate[Index], sizeof (NewBmmData->COMDataRate[Index])) == 0) && + (CompareMem (&NewBmmData->COMStopBits[Index], &OldBmmData->COMStopBits[Index], sizeof (NewBmmData->COMStopBits[Index])) == 0) && + (CompareMem (&NewBmmData->COMParity[Index], &OldBmmData->COMParity[Index], sizeof (NewBmmData->COMParity[Index])) == 0) && + (CompareMem (&NewBmmData->COMTerminalType[Index], &OldBmmData->COMTerminalType[Index], sizeof (NewBmmData->COMTerminalType[Index])) == 0) && + (CompareMem (&NewBmmData->COMFlowControl[Index], &OldBmmData->COMFlowControl[Index], sizeof (NewBmmData->COMFlowControl[Index])) == 0)) + { continue; } TerminalAttChange = TRUE; } + if (TerminalAttChange) { if (CompareMem (&NewBmmData->COMBaudRate[Index], &OldBmmData->COMBaudRate[Index], sizeof (NewBmmData->COMBaudRate[Index])) != 0) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, COMBaudRate); @@ -950,49 +967,54 @@ BootMaintRouteConfig ( } else if (CompareMem (&NewBmmData->COMFlowControl[Index], &OldBmmData->COMFlowControl[Index], sizeof (NewBmmData->COMFlowControl[Index])) != 0) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, COMFlowControl); } + Status = Var_UpdateConsoleInpOption (); if (EFI_ERROR (Status)) { goto Exit; } + Status = Var_UpdateConsoleOutOption (); if (EFI_ERROR (Status)) { goto Exit; } + Status = Var_UpdateErrorOutOption (); if (EFI_ERROR (Status)) { goto Exit; } } + // // Check data which located in Console Options Menu and save the settings if need // - if (CompareMem (NewBmmData->ConsoleInCheck, OldBmmData->ConsoleInCheck, sizeof (NewBmmData->ConsoleInCheck)) != 0){ - Status = Var_UpdateConsoleInpOption(); + if (CompareMem (NewBmmData->ConsoleInCheck, OldBmmData->ConsoleInCheck, sizeof (NewBmmData->ConsoleInCheck)) != 0) { + Status = Var_UpdateConsoleInpOption (); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, ConsoleInCheck); goto Exit; } } - if (CompareMem (NewBmmData->ConsoleOutCheck, OldBmmData->ConsoleOutCheck, sizeof (NewBmmData->ConsoleOutCheck)) != 0){ - Status = Var_UpdateConsoleOutOption(); + if (CompareMem (NewBmmData->ConsoleOutCheck, OldBmmData->ConsoleOutCheck, sizeof (NewBmmData->ConsoleOutCheck)) != 0) { + Status = Var_UpdateConsoleOutOption (); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, ConsoleOutCheck); goto Exit; } } - if (CompareMem (NewBmmData->ConsoleErrCheck, OldBmmData->ConsoleErrCheck, sizeof (NewBmmData->ConsoleErrCheck)) != 0){ - Status = Var_UpdateErrorOutOption(); + if (CompareMem (NewBmmData->ConsoleErrCheck, OldBmmData->ConsoleErrCheck, sizeof (NewBmmData->ConsoleErrCheck)) != 0) { + Status = Var_UpdateErrorOutOption (); if (EFI_ERROR (Status)) { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, ConsoleErrCheck); goto Exit; } } - if (CompareMem (NewBmmData->BootDescriptionData, OldBmmData->BootDescriptionData, sizeof (NewBmmData->BootDescriptionData)) != 0 || - CompareMem (NewBmmData->BootOptionalData, OldBmmData->BootOptionalData, sizeof (NewBmmData->BootOptionalData)) != 0) { - Status = Var_UpdateBootOption (Private); + if ((CompareMem (NewBmmData->BootDescriptionData, OldBmmData->BootDescriptionData, sizeof (NewBmmData->BootDescriptionData)) != 0) || + (CompareMem (NewBmmData->BootOptionalData, OldBmmData->BootOptionalData, sizeof (NewBmmData->BootOptionalData)) != 0)) + { + Status = Var_UpdateBootOption (Private); NewBmmData->BootOptionChanged = FALSE; if (EFI_ERROR (Status)) { if (CompareMem (NewBmmData->BootDescriptionData, OldBmmData->BootDescriptionData, sizeof (NewBmmData->BootDescriptionData)) != 0) { @@ -1000,20 +1022,23 @@ BootMaintRouteConfig ( } else { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, BootOptionalData); } + goto Exit; } + BOpt_GetBootOptions (Private); } - if (CompareMem (NewBmmData->DriverDescriptionData, OldBmmData->DriverDescriptionData, sizeof (NewBmmData->DriverDescriptionData)) != 0 || - CompareMem (NewBmmData->DriverOptionalData, OldBmmData->DriverOptionalData, sizeof (NewBmmData->DriverOptionalData)) != 0) { + if ((CompareMem (NewBmmData->DriverDescriptionData, OldBmmData->DriverDescriptionData, sizeof (NewBmmData->DriverDescriptionData)) != 0) || + (CompareMem (NewBmmData->DriverOptionalData, OldBmmData->DriverOptionalData, sizeof (NewBmmData->DriverOptionalData)) != 0)) + { Status = Var_UpdateDriverOption ( - Private, - Private->BmmHiiHandle, - NewBmmData->DriverDescriptionData, - NewBmmData->DriverOptionalData, - NewBmmData->ForceReconnect - ); + Private, + Private->BmmHiiHandle, + NewBmmData->DriverDescriptionData, + NewBmmData->DriverOptionalData, + NewBmmData->ForceReconnect + ); NewBmmData->DriverOptionChanged = FALSE; NewBmmData->ForceReconnect = TRUE; if (EFI_ERROR (Status)) { @@ -1022,6 +1047,7 @@ BootMaintRouteConfig ( } else { Offset = OFFSET_OF (BMM_FAKE_NV_DATA, DriverOptionalData); } + goto Exit; } @@ -1068,29 +1094,29 @@ Exit: EFI_STATUS EFIAPI BootMaintCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - BMM_CALLBACK_DATA *Private; - BM_MENU_ENTRY *NewMenuEntry; - BMM_FAKE_NV_DATA *CurrentFakeNVMap; - BMM_FAKE_NV_DATA *OldFakeNVMap; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL * File; - - if (Action != EFI_BROWSER_ACTION_CHANGING && Action != EFI_BROWSER_ACTION_CHANGED && Action != EFI_BROWSER_ACTION_FORM_OPEN) { + BMM_CALLBACK_DATA *Private; + BM_MENU_ENTRY *NewMenuEntry; + BMM_FAKE_NV_DATA *CurrentFakeNVMap; + BMM_FAKE_NV_DATA *OldFakeNVMap; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *File; + + if ((Action != EFI_BROWSER_ACTION_CHANGING) && (Action != EFI_BROWSER_ACTION_CHANGED) && (Action != EFI_BROWSER_ACTION_FORM_OPEN)) { // // Do nothing for other UEFI Action. Only do call back when data is changed or the form is open. // return EFI_UNSUPPORTED; } - Private = BMM_CALLBACK_DATA_FROM_THIS (This); + Private = BMM_CALLBACK_DATA_FROM_THIS (This); if (Action == EFI_BROWSER_ACTION_FORM_OPEN) { if (QuestionId == KEY_VALUE_TRIGGER_FORM_OPEN_ACTION) { @@ -1111,12 +1137,13 @@ BootMaintCallback ( } } } + // // Retrieve uncommitted data from Form Browser // CurrentFakeNVMap = &Private->BmmFakeNvData; OldFakeNVMap = &Private->BmmOldFakeNVData; - HiiGetBrowserData (&mBootMaintGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *) CurrentFakeNVMap); + HiiGetBrowserData (&mBootMaintGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *)CurrentFakeNVMap); if (Action == EFI_BROWSER_ACTION_CHANGING) { if (Value == NULL) { @@ -1128,78 +1155,78 @@ BootMaintCallback ( if (QuestionId < FILE_OPTION_OFFSET) { if (QuestionId < CONFIG_OPTION_OFFSET) { switch (QuestionId) { - case FORM_BOOT_ADD_ID: - // Leave BMM and enter FileExplorer. - ChooseFile (NULL, L".efi", CreateBootOptionFromFile, &File); - break; + case FORM_BOOT_ADD_ID: + // Leave BMM and enter FileExplorer. + ChooseFile (NULL, L".efi", CreateBootOptionFromFile, &File); + break; - case FORM_DRV_ADD_FILE_ID: - // Leave BMM and enter FileExplorer. - ChooseFile (NULL, L".efi", CreateDriverOptionFromFile, &File); - break; + case FORM_DRV_ADD_FILE_ID: + // Leave BMM and enter FileExplorer. + ChooseFile (NULL, L".efi", CreateDriverOptionFromFile, &File); + break; - case FORM_DRV_ADD_HANDLE_ID: - CleanUpPage (FORM_DRV_ADD_HANDLE_ID, Private); - UpdateDrvAddHandlePage (Private); - break; + case FORM_DRV_ADD_HANDLE_ID: + CleanUpPage (FORM_DRV_ADD_HANDLE_ID, Private); + UpdateDrvAddHandlePage (Private); + break; - case FORM_BOOT_DEL_ID: - CleanUpPage (FORM_BOOT_DEL_ID, Private); - UpdateBootDelPage (Private); - break; + case FORM_BOOT_DEL_ID: + CleanUpPage (FORM_BOOT_DEL_ID, Private); + UpdateBootDelPage (Private); + break; - case FORM_BOOT_CHG_ID: - case FORM_DRV_CHG_ID: - UpdatePageBody (QuestionId, Private); - break; + case FORM_BOOT_CHG_ID: + case FORM_DRV_CHG_ID: + UpdatePageBody (QuestionId, Private); + break; - case FORM_DRV_DEL_ID: - CleanUpPage (FORM_DRV_DEL_ID, Private); - UpdateDrvDelPage (Private); - break; + case FORM_DRV_DEL_ID: + CleanUpPage (FORM_DRV_DEL_ID, Private); + UpdateDrvDelPage (Private); + break; - case FORM_CON_IN_ID: - case FORM_CON_OUT_ID: - case FORM_CON_ERR_ID: - UpdatePageBody (QuestionId, Private); - break; + case FORM_CON_IN_ID: + case FORM_CON_OUT_ID: + case FORM_CON_ERR_ID: + UpdatePageBody (QuestionId, Private); + break; - case FORM_CON_MODE_ID: - CleanUpPage (FORM_CON_MODE_ID, Private); - UpdateConModePage (Private); - break; + case FORM_CON_MODE_ID: + CleanUpPage (FORM_CON_MODE_ID, Private); + UpdateConModePage (Private); + break; - case FORM_CON_COM_ID: - CleanUpPage (FORM_CON_COM_ID, Private); - UpdateConCOMPage (Private); - break; + case FORM_CON_COM_ID: + CleanUpPage (FORM_CON_COM_ID, Private); + UpdateConCOMPage (Private); + break; - default: - break; + default: + break; } } else if ((QuestionId >= TERMINAL_OPTION_OFFSET) && (QuestionId < CONSOLE_OPTION_OFFSET)) { - Index = (UINT16) (QuestionId - TERMINAL_OPTION_OFFSET); - Private->CurrentTerminal = Index; + Index = (UINT16)(QuestionId - TERMINAL_OPTION_OFFSET); + Private->CurrentTerminal = Index; CleanUpPage (FORM_CON_COM_SETUP_ID, Private); UpdateTerminalPage (Private); - } else if (QuestionId >= HANDLE_OPTION_OFFSET) { - Index = (UINT16) (QuestionId - HANDLE_OPTION_OFFSET); + Index = (UINT16)(QuestionId - HANDLE_OPTION_OFFSET); - NewMenuEntry = BOpt_GetMenuEntry (&DriverMenu, Index); + NewMenuEntry = BOpt_GetMenuEntry (&DriverMenu, Index); ASSERT (NewMenuEntry != NULL); - Private->HandleContext = (BM_HANDLE_CONTEXT *) NewMenuEntry->VariableContext; + Private->HandleContext = (BM_HANDLE_CONTEXT *)NewMenuEntry->VariableContext; CleanUpPage (FORM_DRV_ADD_HANDLE_DESC_ID, Private); - Private->MenuEntry = NewMenuEntry; - Private->LoadContext->FilePathList = Private->HandleContext->DevicePath; + Private->MenuEntry = NewMenuEntry; + Private->LoadContext->FilePathList = Private->HandleContext->DevicePath; UpdateDriverAddHandleDescPage (Private); } } - if (QuestionId == KEY_VALUE_BOOT_FROM_FILE){ + + if (QuestionId == KEY_VALUE_BOOT_FROM_FILE) { // Leave BMM and enter FileExplorer. ChooseFile (NULL, L".efi", BootFromFile, &File); } @@ -1211,11 +1238,11 @@ BootMaintCallback ( if (QuestionId == KEY_VALUE_SAVE_AND_EXIT_BOOT) { CleanUselessBeforeSubmit (Private); CurrentFakeNVMap->BootOptionChanged = FALSE; - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; } else if (QuestionId == KEY_VALUE_SAVE_AND_EXIT_DRIVER) { CleanUselessBeforeSubmit (Private); CurrentFakeNVMap->DriverOptionChanged = FALSE; - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER) { // // Discard changes and exit formset @@ -1226,7 +1253,7 @@ BootMaintCallback ( ZeroMem (OldFakeNVMap->DriverDescriptionData, sizeof (OldFakeNVMap->DriverDescriptionData)); CurrentFakeNVMap->DriverOptionChanged = FALSE; CurrentFakeNVMap->ForceReconnect = TRUE; - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT_BOOT) { // // Discard changes and exit formset @@ -1236,15 +1263,15 @@ BootMaintCallback ( ZeroMem (OldFakeNVMap->BootOptionalData, sizeof (OldFakeNVMap->BootOptionalData)); ZeroMem (OldFakeNVMap->BootDescriptionData, sizeof (OldFakeNVMap->BootDescriptionData)); CurrentFakeNVMap->BootOptionChanged = FALSE; - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; - } else if (QuestionId == KEY_VALUE_BOOT_DESCRIPTION || QuestionId == KEY_VALUE_BOOT_OPTION) { + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; + } else if ((QuestionId == KEY_VALUE_BOOT_DESCRIPTION) || (QuestionId == KEY_VALUE_BOOT_OPTION)) { CurrentFakeNVMap->BootOptionChanged = TRUE; - } else if (QuestionId == KEY_VALUE_DRIVER_DESCRIPTION || QuestionId == KEY_VALUE_DRIVER_OPTION) { + } else if ((QuestionId == KEY_VALUE_DRIVER_DESCRIPTION) || (QuestionId == KEY_VALUE_DRIVER_OPTION)) { CurrentFakeNVMap->DriverOptionChanged = TRUE; } if ((QuestionId >= BOOT_OPTION_DEL_QUESTION_ID) && (QuestionId < BOOT_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER)) { - if (Value->b){ + if (Value->b) { // // Means user try to delete this boot option but not press F10 or "Commit Changes and Exit" menu. // @@ -1256,44 +1283,47 @@ BootMaintCallback ( CurrentFakeNVMap->BootOptionDelMark[QuestionId - BOOT_OPTION_DEL_QUESTION_ID] = FALSE; } } else if ((QuestionId >= DRIVER_OPTION_DEL_QUESTION_ID) && (QuestionId < DRIVER_OPTION_DEL_QUESTION_ID + MAX_MENU_NUMBER)) { - if (Value->b){ + if (Value->b) { CurrentFakeNVMap->DriverOptionDelMark[QuestionId - DRIVER_OPTION_DEL_QUESTION_ID] = TRUE; } else { CurrentFakeNVMap->DriverOptionDelMark[QuestionId - DRIVER_OPTION_DEL_QUESTION_ID] = FALSE; } } else { switch (QuestionId) { - case KEY_VALUE_SAVE_AND_EXIT: - case KEY_VALUE_NO_SAVE_AND_EXIT: - if (QuestionId == KEY_VALUE_SAVE_AND_EXIT) { - CleanUselessBeforeSubmit (Private); - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; - } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT) { - DiscardChangeHandler (Private, CurrentFakeNVMap); - *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; - } + case KEY_VALUE_SAVE_AND_EXIT: + case KEY_VALUE_NO_SAVE_AND_EXIT: + if (QuestionId == KEY_VALUE_SAVE_AND_EXIT) { + CleanUselessBeforeSubmit (Private); + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_SUBMIT_EXIT; + } else if (QuestionId == KEY_VALUE_NO_SAVE_AND_EXIT) { + DiscardChangeHandler (Private, CurrentFakeNVMap); + *ActionRequest = EFI_BROWSER_ACTION_REQUEST_FORM_DISCARD_EXIT; + } - break; + break; - case FORM_RESET: - gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); - return EFI_UNSUPPORTED; + case FORM_RESET: + gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); + return EFI_UNSUPPORTED; - default: - break; + default: + break; } } + // // Update the content in Terminal menu and Console menu here. // - if (QuestionId == COM_BAUD_RATE_QUESTION_ID + Private->CurrentTerminal || QuestionId == COM_DATA_RATE_QUESTION_ID + Private->CurrentTerminal || - QuestionId == COM_PARITY_QUESTION_ID + Private->CurrentTerminal || QuestionId == COM_STOP_BITS_QUESTION_ID + Private->CurrentTerminal || - QuestionId == COM_TERMINAL_QUESTION_ID + Private->CurrentTerminal || QuestionId == COM_FLOWCONTROL_QUESTION_ID + Private->CurrentTerminal - ) { - UpdateTerminalContent(CurrentFakeNVMap); + if ((QuestionId == COM_BAUD_RATE_QUESTION_ID + Private->CurrentTerminal) || (QuestionId == COM_DATA_RATE_QUESTION_ID + Private->CurrentTerminal) || + (QuestionId == COM_PARITY_QUESTION_ID + Private->CurrentTerminal) || (QuestionId == COM_STOP_BITS_QUESTION_ID + Private->CurrentTerminal) || + (QuestionId == COM_TERMINAL_QUESTION_ID + Private->CurrentTerminal) || (QuestionId == COM_FLOWCONTROL_QUESTION_ID + Private->CurrentTerminal) + ) + { + UpdateTerminalContent (CurrentFakeNVMap); } + if ((QuestionId >= CON_IN_DEVICE_QUESTION_ID) && (QuestionId < CON_IN_DEVICE_QUESTION_ID + MAX_MENU_NUMBER)) { - UpdateConsoleContent (L"ConIn",CurrentFakeNVMap); + UpdateConsoleContent (L"ConIn", CurrentFakeNVMap); } else if ((QuestionId >= CON_OUT_DEVICE_QUESTION_ID) && (QuestionId < CON_OUT_DEVICE_QUESTION_ID + MAX_MENU_NUMBER)) { UpdateConsoleContent (L"ConOut", CurrentFakeNVMap); } else if ((QuestionId >= CON_ERR_DEVICE_QUESTION_ID) && (QuestionId < CON_ERR_DEVICE_QUESTION_ID + MAX_MENU_NUMBER)) { @@ -1304,7 +1334,7 @@ BootMaintCallback ( // // Pass changed uncommitted data back to Form Browser // - HiiSetBrowserData (&mBootMaintGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *) CurrentFakeNVMap, NULL); + HiiSetBrowserData (&mBootMaintGuid, mBootMaintStorageName, sizeof (BMM_FAKE_NV_DATA), (UINT8 *)CurrentFakeNVMap, NULL); return EFI_SUCCESS; } @@ -1319,52 +1349,54 @@ BootMaintCallback ( **/ VOID DiscardChangeHandler ( - IN BMM_CALLBACK_DATA *Private, - IN BMM_FAKE_NV_DATA *CurrentFakeNVMap + IN BMM_CALLBACK_DATA *Private, + IN BMM_FAKE_NV_DATA *CurrentFakeNVMap ) { UINT16 Index; switch (Private->BmmPreviousPageId) { - case FORM_BOOT_CHG_ID: - CopyMem (CurrentFakeNVMap->BootOptionOrder, Private->BmmOldFakeNVData.BootOptionOrder, sizeof (CurrentFakeNVMap->BootOptionOrder)); - break; + case FORM_BOOT_CHG_ID: + CopyMem (CurrentFakeNVMap->BootOptionOrder, Private->BmmOldFakeNVData.BootOptionOrder, sizeof (CurrentFakeNVMap->BootOptionOrder)); + break; - case FORM_DRV_CHG_ID: - CopyMem (CurrentFakeNVMap->DriverOptionOrder, Private->BmmOldFakeNVData.DriverOptionOrder, sizeof (CurrentFakeNVMap->DriverOptionOrder)); - break; + case FORM_DRV_CHG_ID: + CopyMem (CurrentFakeNVMap->DriverOptionOrder, Private->BmmOldFakeNVData.DriverOptionOrder, sizeof (CurrentFakeNVMap->DriverOptionOrder)); + break; - case FORM_BOOT_DEL_ID: - ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->BootOptionDel) / sizeof (CurrentFakeNVMap->BootOptionDel[0]))); - for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { - CurrentFakeNVMap->BootOptionDel[Index] = FALSE; - } - break; + case FORM_BOOT_DEL_ID: + ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->BootOptionDel) / sizeof (CurrentFakeNVMap->BootOptionDel[0]))); + for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { + CurrentFakeNVMap->BootOptionDel[Index] = FALSE; + } - case FORM_DRV_DEL_ID: - ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->DriverOptionDel) / sizeof (CurrentFakeNVMap->DriverOptionDel[0]))); - for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { - CurrentFakeNVMap->DriverOptionDel[Index] = FALSE; - } - break; + break; - case FORM_BOOT_NEXT_ID: - CurrentFakeNVMap->BootNext = Private->BmmOldFakeNVData.BootNext; - break; + case FORM_DRV_DEL_ID: + ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CurrentFakeNVMap->DriverOptionDel) / sizeof (CurrentFakeNVMap->DriverOptionDel[0]))); + for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { + CurrentFakeNVMap->DriverOptionDel[Index] = FALSE; + } - case FORM_TIME_OUT_ID: - CurrentFakeNVMap->BootTimeOut = Private->BmmOldFakeNVData.BootTimeOut; - break; + break; - case FORM_DRV_ADD_HANDLE_DESC_ID: - case FORM_DRV_ADD_FILE_ID: - case FORM_DRV_ADD_HANDLE_ID: - CurrentFakeNVMap->DriverAddHandleDesc[0] = 0x0000; - CurrentFakeNVMap->DriverAddHandleOptionalData[0] = 0x0000; - break; + case FORM_BOOT_NEXT_ID: + CurrentFakeNVMap->BootNext = Private->BmmOldFakeNVData.BootNext; + break; + + case FORM_TIME_OUT_ID: + CurrentFakeNVMap->BootTimeOut = Private->BmmOldFakeNVData.BootTimeOut; + break; - default: - break; + case FORM_DRV_ADD_HANDLE_DESC_ID: + case FORM_DRV_ADD_FILE_ID: + case FORM_DRV_ADD_HANDLE_ID: + CurrentFakeNVMap->DriverAddHandleDesc[0] = 0x0000; + CurrentFakeNVMap->DriverAddHandleOptionalData[0] = 0x0000; + break; + + default: + break; } } @@ -1376,22 +1408,24 @@ DiscardChangeHandler ( **/ VOID CleanUselessBeforeSubmit ( - IN BMM_CALLBACK_DATA *Private + IN BMM_CALLBACK_DATA *Private ) { UINT16 Index; + if (Private->BmmPreviousPageId != FORM_BOOT_DEL_ID) { for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { if (Private->BmmFakeNvData.BootOptionDel[Index] && !Private->BmmFakeNvData.BootOptionDelMark[Index]) { - Private->BmmFakeNvData.BootOptionDel[Index] = FALSE; + Private->BmmFakeNvData.BootOptionDel[Index] = FALSE; Private->BmmOldFakeNVData.BootOptionDel[Index] = FALSE; } } } + if (Private->BmmPreviousPageId != FORM_DRV_DEL_ID) { for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { if (Private->BmmFakeNvData.DriverOptionDel[Index] && !Private->BmmFakeNvData.DriverOptionDelMark[Index]) { - Private->BmmFakeNvData.DriverOptionDel[Index] = FALSE; + Private->BmmFakeNvData.DriverOptionDel[Index] = FALSE; Private->BmmOldFakeNVData.DriverOptionDel[Index] = FALSE; } } @@ -1408,10 +1442,10 @@ CustomizeMenus ( VOID ) { - VOID *StartOpCodeHandle; - VOID *EndOpCodeHandle; - EFI_IFR_GUID_LABEL *StartGuidLabel; - EFI_IFR_GUID_LABEL *EndGuidLabel; + VOID *StartOpCodeHandle; + VOID *EndOpCodeHandle; + EFI_IFR_GUID_LABEL *StartGuidLabel; + EFI_IFR_GUID_LABEL *EndGuidLabel; // // Allocate space for creation of UpdateData Buffer @@ -1424,18 +1458,18 @@ CustomizeMenus ( // // Create Hii Extend Label OpCode as the start opcode // - StartGuidLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + StartGuidLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); StartGuidLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; StartGuidLabel->Number = LABEL_FORM_MAIN_START; // // Create Hii Extend Label OpCode as the end opcode // - EndGuidLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + EndGuidLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); EndGuidLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; EndGuidLabel->Number = LABEL_FORM_MAIN_END; // - //Updata Front Page form + // Updata Front Page form // UiCustomizeBMMPage ( mBmmCallbackInfo->BmmHiiHandle, @@ -1463,12 +1497,12 @@ CustomizeMenus ( **/ VOID InitializeBmmConfig ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT16 Index; ASSERT (CallbackData != NULL); @@ -1477,8 +1511,8 @@ InitializeBmmConfig ( // CallbackData->BmmFakeNvData.BootNext = NONE_BOOTNEXT_VALUE; for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (NewLoadContext->IsBootNext) { CallbackData->BmmFakeNvData.BootNext = Index; @@ -1523,7 +1557,7 @@ InitializeBmmConfig ( **/ VOID InitAllMenu ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { InitializeListHead (&BootOptionMenu.Head); @@ -1549,9 +1583,10 @@ FreeAllMenu ( VOID ) { - if (!mAllMenuInit){ + if (!mAllMenuInit) { return; } + BOpt_FreeMenu (&BootOptionMenu); BOpt_FreeMenu (&DriverOptionMenu); BOpt_FreeMenu (&DriverMenu); @@ -1568,11 +1603,11 @@ BmmInitialBootModeInfo ( VOID ) { - EFI_STATUS Status; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; - EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; - UINTN BootTextColumn; - UINTN BootTextRow; + EFI_STATUS Status; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; + UINTN BootTextColumn; + UINTN BootTextRow; if (mBmmModeInitialized) { return; @@ -1585,7 +1620,7 @@ BmmInitialBootModeInfo ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -1594,7 +1629,7 @@ BmmInitialBootModeInfo ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -1627,7 +1662,7 @@ BmmInitialBootModeInfo ( mBmmSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn); mBmmSetupTextModeRow = PcdGet32 (PcdSetupConOutRow); - mBmmModeInitialized = TRUE; + mBmmModeInitialized = TRUE; } /** @@ -1644,13 +1679,13 @@ BmmInitialBootModeInfo ( EFI_STATUS EFIAPI BootMaintenanceManagerUiLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - UINT8 *Ptr; + EFI_STATUS Status; + UINT8 *Ptr; Status = EFI_SUCCESS; @@ -1671,18 +1706,18 @@ BootMaintenanceManagerUiLibConstructor ( // Post our Boot Maint VFR binary to the HII database. // mBmmCallbackInfo->BmmHiiHandle = HiiAddPackages ( - &mBootMaintGuid, - mBmmCallbackInfo->BmmDriverHandle, - BootMaintenanceManagerBin, - BootMaintenanceManagerUiLibStrings, - NULL - ); + &mBootMaintGuid, + mBmmCallbackInfo->BmmDriverHandle, + BootMaintenanceManagerBin, + BootMaintenanceManagerUiLibStrings, + NULL + ); ASSERT (mBmmCallbackInfo->BmmHiiHandle != NULL); // // Locate Formbrowser2 protocol // - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &mBmmCallbackInfo->FormBrowser2); + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&mBmmCallbackInfo->FormBrowser2); ASSERT_EFI_ERROR (Status); // @@ -1694,29 +1729,29 @@ BootMaintenanceManagerUiLibConstructor ( // // Initialize Bmm callback data. // - mBmmCallbackInfo->LoadContext = (BM_LOAD_CONTEXT *) Ptr; - Ptr += sizeof (BM_LOAD_CONTEXT); + mBmmCallbackInfo->LoadContext = (BM_LOAD_CONTEXT *)Ptr; + Ptr += sizeof (BM_LOAD_CONTEXT); - mBmmCallbackInfo->FileContext = (BM_FILE_CONTEXT *) Ptr; - Ptr += sizeof (BM_FILE_CONTEXT); + mBmmCallbackInfo->FileContext = (BM_FILE_CONTEXT *)Ptr; + Ptr += sizeof (BM_FILE_CONTEXT); - mBmmCallbackInfo->HandleContext = (BM_HANDLE_CONTEXT *) Ptr; - Ptr += sizeof (BM_HANDLE_CONTEXT); + mBmmCallbackInfo->HandleContext = (BM_HANDLE_CONTEXT *)Ptr; + Ptr += sizeof (BM_HANDLE_CONTEXT); - mBmmCallbackInfo->MenuEntry = (BM_MENU_ENTRY *) Ptr; + mBmmCallbackInfo->MenuEntry = (BM_MENU_ENTRY *)Ptr; - mBmmCallbackInfo->BmmPreviousPageId = FORM_MAIN_ID; - mBmmCallbackInfo->BmmCurrentPageId = FORM_MAIN_ID; + mBmmCallbackInfo->BmmPreviousPageId = FORM_MAIN_ID; + mBmmCallbackInfo->BmmCurrentPageId = FORM_MAIN_ID; InitAllMenu (mBmmCallbackInfo); - CreateUpdateData(); + CreateUpdateData (); // // Update boot maintenance manager page // - InitializeBmmConfig(mBmmCallbackInfo); + InitializeBmmConfig (mBmmCallbackInfo); - BmmInitialBootModeInfo(); + BmmInitialBootModeInfo (); return EFI_SUCCESS; } @@ -1733,8 +1768,8 @@ BootMaintenanceManagerUiLibConstructor ( EFI_STATUS EFIAPI BootMaintenanceManagerUiLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { @@ -1767,4 +1802,3 @@ BootMaintenanceManagerUiLibDestructor ( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManager.h b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManager.h index 67847d8bf3..2e9a70dccb 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManager.h +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManager.h @@ -44,8 +44,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; #pragma pack() @@ -53,19 +53,19 @@ typedef struct { // Constants which are variable names used to access variables // -#define VAR_CON_OUT_MODE L"ConOutMode" +#define VAR_CON_OUT_MODE L"ConOutMode" // // Variable created with this flag will be "Efi:...." // #define VAR_FLAG EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE -extern EFI_GUID mBootMaintGuid; -extern CHAR16 mBootMaintStorageName[]; +extern EFI_GUID mBootMaintGuid; +extern CHAR16 mBootMaintStorageName[]; // // These are the VFR compiler generated data representing our VFR data. // -extern UINT8 BootMaintenanceManagerBin[]; +extern UINT8 BootMaintenanceManagerBin[]; // // Below are the number of options in Baudrate, Databits, @@ -79,7 +79,7 @@ extern UINT8 BootMaintenanceManagerBin[]; // // Callback function helper // -#define BMM_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('C', 'b', 'c', 'k') +#define BMM_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('C', 'b', 'c', 'k') #define BMM_CALLBACK_DATA_FROM_THIS(a) CR (a, BMM_CALLBACK_DATA, BmmConfigAccess, BMM_CALLBACK_DATA_SIGNATURE) // @@ -88,7 +88,7 @@ extern UINT8 BootMaintenanceManagerBin[]; typedef UINT8 BBS_TYPE; typedef enum _TYPE_OF_TERMINAL { - TerminalTypePcAnsi = 0, + TerminalTypePcAnsi = 0, TerminalTypeVt100, TerminalTypeVt100Plus, TerminalTypeVtUtf8, @@ -110,20 +110,20 @@ typedef enum _TYPE_OF_TERMINAL { #define BM_TERMINAL_OPTION_SIGNATURE SIGNATURE_32 ('t', 'r', 'm', 'l') #define BM_MENU_ENTRY_SIGNATURE SIGNATURE_32 ('e', 'n', 't', 'r') -#define BM_LOAD_CONTEXT_SELECT 0x0 -#define BM_CONSOLE_CONTEXT_SELECT 0x1 -#define BM_FILE_CONTEXT_SELECT 0x2 -#define BM_HANDLE_CONTEXT_SELECT 0x3 -#define BM_TERMINAL_CONTEXT_SELECT 0x5 +#define BM_LOAD_CONTEXT_SELECT 0x0 +#define BM_CONSOLE_CONTEXT_SELECT 0x1 +#define BM_FILE_CONTEXT_SELECT 0x2 +#define BM_HANDLE_CONTEXT_SELECT 0x3 +#define BM_TERMINAL_CONTEXT_SELECT 0x5 -#define BM_CONSOLE_IN_CONTEXT_SELECT 0x6 -#define BM_CONSOLE_OUT_CONTEXT_SELECT 0x7 -#define BM_CONSOLE_ERR_CONTEXT_SELECT 0x8 +#define BM_CONSOLE_IN_CONTEXT_SELECT 0x6 +#define BM_CONSOLE_OUT_CONTEXT_SELECT 0x7 +#define BM_CONSOLE_ERR_CONTEXT_SELECT 0x8 // // Buffer size for update data // -#define UPDATE_DATA_SIZE 0x100000 +#define UPDATE_DATA_SIZE 0x100000 // // Namespace of callback keys used in display and file system navigation @@ -148,12 +148,12 @@ typedef enum _TYPE_OF_TERMINAL { // all these values are computed from the structure // defined below // -#define VAR_OFFSET(Field) ((UINT16) ((UINTN) &(((BMM_FAKE_NV_DATA *) 0)->Field))) +#define VAR_OFFSET(Field) ((UINT16) ((UINTN) &(((BMM_FAKE_NV_DATA *) 0)->Field))) // // Question Id of Zero is invalid, so add an offset to it // -#define QUESTION_ID(Field) (VAR_OFFSET (Field) + CONFIG_OPTION_OFFSET) +#define QUESTION_ID(Field) (VAR_OFFSET (Field) + CONFIG_OPTION_OFFSET) #define BOOT_TIME_OUT_VAR_OFFSET VAR_OFFSET (BootTimeOut) #define BOOT_NEXT_VAR_OFFSET VAR_OFFSET (BootNext) @@ -193,47 +193,47 @@ typedef enum _TYPE_OF_TERMINAL { #define COM_TERMINAL_VAR_OFFSET VAR_OFFSET (COMTerminalType) #define COM_FLOWCONTROL_VAR_OFFSET VAR_OFFSET (COMFlowControl) -#define BOOT_TIME_OUT_QUESTION_ID QUESTION_ID (BootTimeOut) -#define BOOT_NEXT_QUESTION_ID QUESTION_ID (BootNext) -#define COM1_BAUD_RATE_QUESTION_ID QUESTION_ID (COM1BaudRate) -#define COM1_DATA_RATE_QUESTION_ID QUESTION_ID (COM1DataRate) -#define COM1_STOP_BITS_QUESTION_ID QUESTION_ID (COM1StopBits) -#define COM1_PARITY_QUESTION_ID QUESTION_ID (COM1Parity) -#define COM1_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType) -#define COM2_BAUD_RATE_QUESTION_ID QUESTION_ID (COM2BaudRate) -#define COM2_DATA_RATE_QUESTION_ID QUESTION_ID (COM2DataRate) -#define COM2_STOP_BITS_QUESTION_ID QUESTION_ID (COM2StopBits) -#define COM2_PARITY_QUESTION_ID QUESTION_ID (COM2Parity) -#define COM2_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType) -#define DRV_ADD_HANDLE_DESC_QUESTION_ID QUESTION_ID (DriverAddHandleDesc) -#define DRV_ADD_ACTIVE_QUESTION_ID QUESTION_ID (DriverAddActive) -#define DRV_ADD_RECON_QUESTION_ID QUESTION_ID (DriverAddForceReconnect) -#define CON_IN_COM1_QUESTION_ID QUESTION_ID (ConsoleInputCOM1) -#define CON_IN_COM2_QUESTION_ID QUESTION_ID (ConsoleInputCOM2) -#define CON_OUT_COM1_QUESTION_ID QUESTION_ID (ConsoleOutputCOM1) -#define CON_OUT_COM2_QUESTION_ID QUESTION_ID (ConsoleOutputCOM2) -#define CON_ERR_COM1_QUESTION_ID QUESTION_ID (ConsoleErrorCOM1) -#define CON_ERR_COM2_QUESTION_ID QUESTION_ID (ConsoleErrorCOM2) -#define CON_MODE_QUESTION_ID QUESTION_ID (ConsoleOutMode) -#define CON_DEVICE_QUESTION_ID QUESTION_ID (ConsoleCheck) -#define CON_IN_DEVICE_QUESTION_ID QUESTION_ID (ConsoleInCheck) -#define CON_OUT_DEVICE_QUESTION_ID QUESTION_ID (ConsoleOutCheck) -#define CON_ERR_DEVICE_QUESTION_ID QUESTION_ID (ConsoleErrCheck) -#define BOOT_OPTION_ORDER_QUESTION_ID QUESTION_ID (BootOptionOrder) -#define DRIVER_OPTION_ORDER_QUESTION_ID QUESTION_ID (DriverOptionOrder) -#define BOOT_OPTION_DEL_QUESTION_ID QUESTION_ID (BootOptionDel) -#define DRIVER_OPTION_DEL_QUESTION_ID QUESTION_ID (DriverOptionDel) -#define DRIVER_ADD_OPTION_QUESTION_ID QUESTION_ID (DriverAddHandleOptionalData) -#define COM_BAUD_RATE_QUESTION_ID QUESTION_ID (COMBaudRate) -#define COM_DATA_RATE_QUESTION_ID QUESTION_ID (COMDataRate) -#define COM_STOP_BITS_QUESTION_ID QUESTION_ID (COMStopBits) -#define COM_PARITY_QUESTION_ID QUESTION_ID (COMParity) -#define COM_TERMINAL_QUESTION_ID QUESTION_ID (COMTerminalType) -#define COM_FLOWCONTROL_QUESTION_ID QUESTION_ID (COMFlowControl) - -#define STRING_DEPOSITORY_NUMBER 8 - -#define NONE_BOOTNEXT_VALUE (0xFFFF + 1) +#define BOOT_TIME_OUT_QUESTION_ID QUESTION_ID (BootTimeOut) +#define BOOT_NEXT_QUESTION_ID QUESTION_ID (BootNext) +#define COM1_BAUD_RATE_QUESTION_ID QUESTION_ID (COM1BaudRate) +#define COM1_DATA_RATE_QUESTION_ID QUESTION_ID (COM1DataRate) +#define COM1_STOP_BITS_QUESTION_ID QUESTION_ID (COM1StopBits) +#define COM1_PARITY_QUESTION_ID QUESTION_ID (COM1Parity) +#define COM1_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType) +#define COM2_BAUD_RATE_QUESTION_ID QUESTION_ID (COM2BaudRate) +#define COM2_DATA_RATE_QUESTION_ID QUESTION_ID (COM2DataRate) +#define COM2_STOP_BITS_QUESTION_ID QUESTION_ID (COM2StopBits) +#define COM2_PARITY_QUESTION_ID QUESTION_ID (COM2Parity) +#define COM2_TERMINAL_QUESTION_ID QUESTION_ID (COM2TerminalType) +#define DRV_ADD_HANDLE_DESC_QUESTION_ID QUESTION_ID (DriverAddHandleDesc) +#define DRV_ADD_ACTIVE_QUESTION_ID QUESTION_ID (DriverAddActive) +#define DRV_ADD_RECON_QUESTION_ID QUESTION_ID (DriverAddForceReconnect) +#define CON_IN_COM1_QUESTION_ID QUESTION_ID (ConsoleInputCOM1) +#define CON_IN_COM2_QUESTION_ID QUESTION_ID (ConsoleInputCOM2) +#define CON_OUT_COM1_QUESTION_ID QUESTION_ID (ConsoleOutputCOM1) +#define CON_OUT_COM2_QUESTION_ID QUESTION_ID (ConsoleOutputCOM2) +#define CON_ERR_COM1_QUESTION_ID QUESTION_ID (ConsoleErrorCOM1) +#define CON_ERR_COM2_QUESTION_ID QUESTION_ID (ConsoleErrorCOM2) +#define CON_MODE_QUESTION_ID QUESTION_ID (ConsoleOutMode) +#define CON_DEVICE_QUESTION_ID QUESTION_ID (ConsoleCheck) +#define CON_IN_DEVICE_QUESTION_ID QUESTION_ID (ConsoleInCheck) +#define CON_OUT_DEVICE_QUESTION_ID QUESTION_ID (ConsoleOutCheck) +#define CON_ERR_DEVICE_QUESTION_ID QUESTION_ID (ConsoleErrCheck) +#define BOOT_OPTION_ORDER_QUESTION_ID QUESTION_ID (BootOptionOrder) +#define DRIVER_OPTION_ORDER_QUESTION_ID QUESTION_ID (DriverOptionOrder) +#define BOOT_OPTION_DEL_QUESTION_ID QUESTION_ID (BootOptionDel) +#define DRIVER_OPTION_DEL_QUESTION_ID QUESTION_ID (DriverOptionDel) +#define DRIVER_ADD_OPTION_QUESTION_ID QUESTION_ID (DriverAddHandleOptionalData) +#define COM_BAUD_RATE_QUESTION_ID QUESTION_ID (COMBaudRate) +#define COM_DATA_RATE_QUESTION_ID QUESTION_ID (COMDataRate) +#define COM_STOP_BITS_QUESTION_ID QUESTION_ID (COMStopBits) +#define COM_PARITY_QUESTION_ID QUESTION_ID (COMParity) +#define COM_TERMINAL_QUESTION_ID QUESTION_ID (COMTerminalType) +#define COM_FLOWCONTROL_QUESTION_ID QUESTION_ID (COMFlowControl) + +#define STRING_DEPOSITORY_NUMBER 8 + +#define NONE_BOOTNEXT_VALUE (0xFFFF + 1) /// /// Serial Ports attributes, first one is the value for @@ -241,125 +241,122 @@ typedef enum _TYPE_OF_TERMINAL { /// display the value properly /// typedef struct { - UINTN Value; - UINT16 StringToken; + UINTN Value; + UINT16 StringToken; } COM_ATTR; typedef struct { - UINT64 BaudRate; - UINT8 DataBits; - UINT8 Parity; - UINT8 StopBits; + UINT64 BaudRate; + UINT8 DataBits; + UINT8 Parity; + UINT8 StopBits; - UINT8 BaudRateIndex; - UINT8 DataBitsIndex; - UINT8 ParityIndex; - UINT8 StopBitsIndex; + UINT8 BaudRateIndex; + UINT8 DataBitsIndex; + UINT8 ParityIndex; + UINT8 StopBitsIndex; - UINT8 FlowControl; + UINT8 FlowControl; - UINT8 IsConIn; - UINT8 IsConOut; - UINT8 IsStdErr; - UINT8 TerminalType; + UINT8 IsConIn; + UINT8 IsConOut; + UINT8 IsStdErr; + UINT8 TerminalType; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } BM_TERMINAL_CONTEXT; typedef struct { - BOOLEAN IsBootNext; - BOOLEAN Deleted; + BOOLEAN IsBootNext; + BOOLEAN Deleted; - BOOLEAN IsLegacy; + BOOLEAN IsLegacy; - UINT32 Attributes; - UINT16 FilePathListLength; - UINT16 *Description; - EFI_DEVICE_PATH_PROTOCOL *FilePathList; - UINT8 *OptionalData; + UINT32 Attributes; + UINT16 FilePathListLength; + UINT16 *Description; + EFI_DEVICE_PATH_PROTOCOL *FilePathList; + UINT8 *OptionalData; } BM_LOAD_CONTEXT; typedef struct { + BOOLEAN IsActive; - BOOLEAN IsActive; + BOOLEAN IsTerminal; - BOOLEAN IsTerminal; - - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } BM_CONSOLE_CONTEXT; typedef struct { - UINTN Column; - UINTN Row; + UINTN Column; + UINTN Row; } CONSOLE_OUT_MODE; typedef struct { - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_FILE_HANDLE FHandle; - UINT16 *FileName; - EFI_FILE_SYSTEM_VOLUME_LABEL *Info; - - BOOLEAN IsRoot; - BOOLEAN IsDir; - BOOLEAN IsRemovableMedia; - BOOLEAN IsLoadFile; - BOOLEAN IsBootLegacy; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_FILE_HANDLE FHandle; + UINT16 *FileName; + EFI_FILE_SYSTEM_VOLUME_LABEL *Info; + + BOOLEAN IsRoot; + BOOLEAN IsDir; + BOOLEAN IsRemovableMedia; + BOOLEAN IsLoadFile; + BOOLEAN IsBootLegacy; } BM_FILE_CONTEXT; typedef struct { - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; } BM_HANDLE_CONTEXT; typedef struct { - UINTN Signature; - LIST_ENTRY Head; - UINTN MenuNumber; + UINTN Signature; + LIST_ENTRY Head; + UINTN MenuNumber; } BM_MENU_OPTION; typedef struct { - UINTN Signature; - LIST_ENTRY Link; - UINTN OptionNumber; - UINT16 *DisplayString; - UINT16 *HelpString; - EFI_STRING_ID DisplayStringToken; - EFI_STRING_ID HelpStringToken; - UINTN ContextSelection; - VOID *VariableContext; + UINTN Signature; + LIST_ENTRY Link; + UINTN OptionNumber; + UINT16 *DisplayString; + UINT16 *HelpString; + EFI_STRING_ID DisplayStringToken; + EFI_STRING_ID HelpStringToken; + UINTN ContextSelection; + VOID *VariableContext; } BM_MENU_ENTRY; typedef struct { + UINTN Signature; - UINTN Signature; - - EFI_HII_HANDLE BmmHiiHandle; - EFI_HANDLE BmmDriverHandle; + EFI_HII_HANDLE BmmHiiHandle; + EFI_HANDLE BmmDriverHandle; /// /// Boot Maintenance Manager Produced protocols /// - EFI_HII_CONFIG_ACCESS_PROTOCOL BmmConfigAccess; - EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; + EFI_HII_CONFIG_ACCESS_PROTOCOL BmmConfigAccess; + EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; - BM_MENU_ENTRY *MenuEntry; - BM_HANDLE_CONTEXT *HandleContext; - BM_FILE_CONTEXT *FileContext; - BM_LOAD_CONTEXT *LoadContext; - BM_TERMINAL_CONTEXT *TerminalContext; - UINTN CurrentTerminal; - BBS_TYPE BbsType; + BM_MENU_ENTRY *MenuEntry; + BM_HANDLE_CONTEXT *HandleContext; + BM_FILE_CONTEXT *FileContext; + BM_LOAD_CONTEXT *LoadContext; + BM_TERMINAL_CONTEXT *TerminalContext; + UINTN CurrentTerminal; + BBS_TYPE BbsType; // // BMM main formset callback data. // - EFI_FORM_ID BmmCurrentPageId; - EFI_FORM_ID BmmPreviousPageId; - BOOLEAN BmmAskSaveOrNot; - BMM_FAKE_NV_DATA BmmFakeNvData; - BMM_FAKE_NV_DATA BmmOldFakeNVData; - + EFI_FORM_ID BmmCurrentPageId; + EFI_FORM_ID BmmPreviousPageId; + BOOLEAN BmmAskSaveOrNot; + BMM_FAKE_NV_DATA BmmFakeNvData; + BMM_FAKE_NV_DATA BmmOldFakeNVData; } BMM_CALLBACK_DATA; /** @@ -390,7 +387,7 @@ BOpt_FindDrivers ( **/ EFI_STATUS BOpt_GetBootOptions ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -406,7 +403,7 @@ BOpt_GetBootOptions ( **/ EFI_STATUS BOpt_GetDriverOptions ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -417,7 +414,7 @@ BOpt_GetDriverOptions ( **/ VOID BOpt_FreeMenu ( - BM_MENU_OPTION *FreeMenu + BM_MENU_OPTION *FreeMenu ); /** @@ -431,7 +428,7 @@ BOpt_FreeMenu ( **/ UINT16 BOpt_GetOptionNumber ( - CHAR16 *Type + CHAR16 *Type ); /** @@ -470,7 +467,7 @@ BOpt_GetDriverOptionNumber ( **/ BM_MENU_ENTRY * BOpt_CreateMenuEntry ( - UINTN MenuType + UINTN MenuType ); /** @@ -481,7 +478,7 @@ BOpt_CreateMenuEntry ( **/ VOID BOpt_DestroyMenuEntry ( - BM_MENU_ENTRY *MenuEntry + BM_MENU_ENTRY *MenuEntry ); /** @@ -498,8 +495,8 @@ BOpt_DestroyMenuEntry ( **/ BM_MENU_ENTRY * BOpt_GetMenuEntry ( - BM_MENU_OPTION *MenuOption, - UINTN MenuNumber + BM_MENU_OPTION *MenuOption, + UINTN MenuNumber ); /** @@ -510,7 +507,7 @@ BOpt_GetMenuEntry ( **/ VOID GetBootOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -521,12 +518,13 @@ GetBootOrder ( **/ VOID GetDriverOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); // // Locate all serial io devices for console // + /** Build a list containing all serial devices. @@ -542,6 +540,7 @@ LocateSerialIo ( // // Initializing Console menu // + /** Build up ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu @@ -549,13 +548,14 @@ LocateSerialIo ( **/ EFI_STATUS -GetAllConsoles( +GetAllConsoles ( VOID ); // // Get current mode information // + /** Get mode number according to column and row @@ -563,12 +563,13 @@ GetAllConsoles( **/ VOID GetConsoleOutMode ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); // // Cleaning up console menu // + /** Free ConsoleOutMenu, ConsoleInpMenu and ConsoleErrMenu @@ -607,12 +608,13 @@ ChangeVariableDevicePath ( EFI_STATUS ChangeTerminalDevicePath ( IN OUT EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN BOOLEAN ChangeTerminal + IN BOOLEAN ChangeTerminal ); // // Variable operation by menu selection // + /** This function create a currently loaded Boot Option from the BMM. It then appends this Boot Option to the end of @@ -627,7 +629,7 @@ ChangeTerminalDevicePath ( **/ EFI_STATUS Var_UpdateBootOption ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -661,11 +663,11 @@ Var_DelBootOption ( **/ EFI_STATUS Var_UpdateDriverOption ( - IN BMM_CALLBACK_DATA *CallbackData, - IN EFI_HII_HANDLE HiiHandle, - IN UINT16 *DescriptionData, - IN UINT16 *OptionalData, - IN UINT8 ForceReconnect + IN BMM_CALLBACK_DATA *CallbackData, + IN EFI_HII_HANDLE HiiHandle, + IN UINT16 *DescriptionData, + IN UINT16 *OptionalData, + IN UINT8 ForceReconnect ); /** @@ -725,7 +727,7 @@ Var_UpdateErrorOutOption ( **/ EFI_STATUS Var_UpdateOutOfBandOption ( - IN UINT16 MenuIndex + IN UINT16 MenuIndex ); /** @@ -741,7 +743,7 @@ Var_UpdateOutOfBandOption ( **/ EFI_STATUS Var_UpdateBootNext ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -757,7 +759,7 @@ Var_UpdateBootNext ( **/ EFI_STATUS Var_UpdateBootOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -774,7 +776,7 @@ Var_UpdateBootOrder ( **/ EFI_STATUS Var_UpdateDriverOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -788,12 +790,13 @@ Var_UpdateDriverOrder ( **/ EFI_STATUS Var_UpdateConMode ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); // // Following are page create and refresh functions // + /** Create the global UpdateData structure. @@ -823,8 +826,8 @@ RefreshUpdateData ( **/ VOID CleanUpPage ( - IN UINT16 LabelId, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 LabelId, + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -836,7 +839,7 @@ CleanUpPage ( **/ VOID UpdateBootDelPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -846,7 +849,7 @@ UpdateBootDelPage ( **/ VOID UpdateDrvAddHandlePage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -857,7 +860,7 @@ UpdateDrvAddHandlePage ( **/ VOID UpdateDrvDelPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -867,7 +870,7 @@ UpdateDrvDelPage ( **/ VOID UpdateDriverAddHandleDescPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -878,8 +881,8 @@ UpdateDriverAddHandleDescPage ( **/ VOID UpdatePageBody ( - IN UINT16 UpdatePageId, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 UpdatePageId, + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -890,7 +893,7 @@ UpdatePageBody ( **/ VOID UpdateTerminalPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -900,7 +903,7 @@ UpdateTerminalPage ( **/ VOID UpdateConModePage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -911,7 +914,7 @@ UpdateConModePage ( **/ VOID UpdateConCOMPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -923,10 +926,10 @@ UpdateConCOMPage ( **/ VOID -UpdateOptionPage( - IN BMM_CALLBACK_DATA *CallbackData, - IN EFI_FORM_ID FormId, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath +UpdateOptionPage ( + IN BMM_CALLBACK_DATA *CallbackData, + IN EFI_FORM_ID FormId, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ); /** @@ -946,8 +949,8 @@ UpdateOptionPage( **/ EFI_STATUS EfiLibDeleteVariable ( - IN CHAR16 *VarName, - IN EFI_GUID *VarGuid + IN CHAR16 *VarName, + IN EFI_GUID *VarGuid ); /** @@ -963,7 +966,7 @@ EfiLibDeleteVariable ( **/ UINTN EfiDevicePathInstanceCount ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ); /** @@ -979,7 +982,7 @@ EfiDevicePathInstanceCount ( **/ UINT16 * EfiLibStrFromDatahub ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ); /** @@ -994,9 +997,9 @@ EfiLibStrFromDatahub ( **/ VOID * GetLegacyBootOptionVar ( - IN UINTN DeviceType, - OUT UINTN *OptionIndex, - OUT UINTN *OptionSize + IN UINTN DeviceType, + OUT UINTN *OptionIndex, + OUT UINTN *OptionSize ); /** @@ -1009,11 +1012,10 @@ GetLegacyBootOptionVar ( **/ VOID DiscardChangeHandler ( - IN BMM_CALLBACK_DATA *Private, - IN BMM_FAKE_NV_DATA *CurrentFakeNVMap + IN BMM_CALLBACK_DATA *Private, + IN BMM_FAKE_NV_DATA *CurrentFakeNVMap ); - /** This function is to clean some useless data before submit changes. @@ -1022,7 +1024,7 @@ DiscardChangeHandler ( **/ VOID CleanUselessBeforeSubmit ( - IN BMM_CALLBACK_DATA *Private + IN BMM_CALLBACK_DATA *Private ); /** @@ -1034,8 +1036,8 @@ CleanUselessBeforeSubmit ( **/ VOID UpdatePageId ( - BMM_CALLBACK_DATA *Private, - UINT16 NewPageId + BMM_CALLBACK_DATA *Private, + UINT16 NewPageId ); /** @@ -1043,7 +1045,7 @@ UpdatePageId ( **/ VOID -FreeBMPackage( +FreeBMPackage ( VOID ); @@ -1052,7 +1054,7 @@ FreeBMPackage( **/ VOID -InitBootMaintenance( +InitBootMaintenance ( VOID ); @@ -1066,7 +1068,7 @@ InitBootMaintenance( **/ VOID GetConsoleInCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -1079,7 +1081,7 @@ GetConsoleInCheck ( **/ VOID GetConsoleOutCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -1092,7 +1094,7 @@ GetConsoleOutCheck ( **/ VOID GetConsoleErrCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -1105,7 +1107,7 @@ GetConsoleErrCheck ( **/ VOID GetTerminalAttribute ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ); /** @@ -1123,7 +1125,6 @@ BmmSetConsoleMode ( BOOLEAN IsSetupMode ); - /** This function converts an input device structure to a Unicode string. @@ -1134,7 +1135,7 @@ BmmSetConsoleMode ( **/ CHAR16 * UiDevicePathToStr ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ); /** @@ -1148,7 +1149,7 @@ UiDevicePathToStr ( **/ CHAR16 * ExtractFileNameFromDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ); /** @@ -1175,10 +1176,10 @@ ExtractFileNameFromDevicePath ( EFI_STATUS EFIAPI BootMaintExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ); /** @@ -1217,9 +1218,9 @@ BootMaintExtractConfig ( EFI_STATUS EFIAPI BootMaintRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ); /** @@ -1243,12 +1244,12 @@ BootMaintRouteConfig ( EFI_STATUS EFIAPI BootMaintCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); /** @@ -1263,7 +1264,7 @@ BootMaintCallback ( BOOLEAN EFIAPI CreateBootOptionFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ); /** @@ -1277,7 +1278,7 @@ CreateBootOptionFromFile ( BOOLEAN EFIAPI CreateDriverOptionFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ); /** @@ -1292,37 +1293,37 @@ CreateDriverOptionFromFile ( BOOLEAN EFIAPI BootFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ); // // Global variable in this program (defined in data.c) // -extern BM_MENU_OPTION BootOptionMenu; -extern BM_MENU_OPTION DriverOptionMenu; -extern BM_MENU_OPTION ConsoleInpMenu; -extern BM_MENU_OPTION ConsoleOutMenu; -extern BM_MENU_OPTION ConsoleErrMenu; -extern BM_MENU_OPTION DriverMenu; -extern BM_MENU_OPTION TerminalMenu; -extern UINT16 TerminalType[9]; -extern COM_ATTR BaudRateList[19]; -extern COM_ATTR DataBitsList[4]; -extern COM_ATTR ParityList[5]; -extern COM_ATTR StopBitsList[3]; -extern EFI_GUID TerminalTypeGuid[9]; -extern EFI_DEVICE_PATH_PROTOCOL EndDevicePath[]; -extern UINT16 mFlowControlType[2]; -extern UINT32 mFlowControlValue[2]; +extern BM_MENU_OPTION BootOptionMenu; +extern BM_MENU_OPTION DriverOptionMenu; +extern BM_MENU_OPTION ConsoleInpMenu; +extern BM_MENU_OPTION ConsoleOutMenu; +extern BM_MENU_OPTION ConsoleErrMenu; +extern BM_MENU_OPTION DriverMenu; +extern BM_MENU_OPTION TerminalMenu; +extern UINT16 TerminalType[9]; +extern COM_ATTR BaudRateList[19]; +extern COM_ATTR DataBitsList[4]; +extern COM_ATTR ParityList[5]; +extern COM_ATTR StopBitsList[3]; +extern EFI_GUID TerminalTypeGuid[9]; +extern EFI_DEVICE_PATH_PROTOCOL EndDevicePath[]; +extern UINT16 mFlowControlType[2]; +extern UINT32 mFlowControlValue[2]; // // Shared IFR form update data // -extern VOID *mStartOpCodeHandle; -extern VOID *mEndOpCodeHandle; -extern EFI_IFR_GUID_LABEL *mStartLabel; -extern EFI_IFR_GUID_LABEL *mEndLabel; -extern BMM_CALLBACK_DATA gBootMaintenancePrivate; -extern BMM_CALLBACK_DATA *mBmmCallbackInfo; +extern VOID *mStartOpCodeHandle; +extern VOID *mEndOpCodeHandle; +extern EFI_IFR_GUID_LABEL *mStartLabel; +extern EFI_IFR_GUID_LABEL *mEndLabel; +extern BMM_CALLBACK_DATA gBootMaintenancePrivate; +extern BMM_CALLBACK_DATA *mBmmCallbackInfo; #endif diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.c index ff5e9f8f27..d79212e75c 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.c @@ -27,19 +27,19 @@ UiCustomizeBMMPage ( // // Create "Boot Option" menu. // - BmmCreateBootOptionMenu(HiiHandle, StartOpCodeHandle); + BmmCreateBootOptionMenu (HiiHandle, StartOpCodeHandle); // // Create "Driver Option" menu. // - BmmCreateDriverOptionMenu(HiiHandle, StartOpCodeHandle); + BmmCreateDriverOptionMenu (HiiHandle, StartOpCodeHandle); // // Create "Com Option" menu. // - BmmCreateComOptionMenu(HiiHandle, StartOpCodeHandle); + BmmCreateComOptionMenu (HiiHandle, StartOpCodeHandle); // // Create "Boot From File" menu. // - BmmCreateBootFromFileMenu(HiiHandle, StartOpCodeHandle); + BmmCreateBootFromFileMenu (HiiHandle, StartOpCodeHandle); // // Find third party drivers which need to be shown in the Bmm page. @@ -81,12 +81,12 @@ UiCustomizeBMMPage ( **/ EFI_STATUS UiBMMCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.h b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.h index f1074c3b3d..21cfc5dcdc 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.h +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUi.h @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __CUSTOMIZED_UI_H__ #define __CUSTOMIZED_UI_H__ - /** Customize menus in the page. @@ -43,12 +42,12 @@ UiCustomizeBMMPage ( **/ EFI_STATUS UiBMMCallbackHandler ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN EFI_HII_HANDLE HiiHandle, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); #endif diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.c index 656106fc24..e16936041a 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.c @@ -6,22 +6,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "BootMaintenanceManager.h" #include "BootMaintenanceManagerCustomizedUiSupport.h" -#define UI_HII_DRIVER_LIST_SIZE 0x8 +#define UI_HII_DRIVER_LIST_SIZE 0x8 typedef struct { - EFI_STRING_ID PromptId; - EFI_STRING_ID HelpId; - EFI_STRING_ID DevicePathId; - EFI_GUID FormSetGuid; - BOOLEAN EmptyLineAfter; + EFI_STRING_ID PromptId; + EFI_STRING_ID HelpId; + EFI_STRING_ID DevicePathId; + EFI_GUID FormSetGuid; + BOOLEAN EmptyLineAfter; } UI_HII_DRIVER_INSTANCE; -STATIC UI_HII_DRIVER_INSTANCE *gHiiDriverList; - +STATIC UI_HII_DRIVER_INSTANCE *gHiiDriverList; /** Create the dynamic item to allow user to set the "BootNext" vaule. @@ -31,16 +29,16 @@ STATIC UI_HII_DRIVER_INSTANCE *gHiiDriverList; **/ VOID -BmmCreateBootNextMenu( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle +BmmCreateBootNextMenu ( + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT16 Index; - VOID *OptionsOpCodeHandle; - UINT32 BootNextIndex; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT16 Index; + VOID *OptionsOpCodeHandle; + UINT32 BootNextIndex; if (BootOptionMenu.MenuNumber == 0) { return; @@ -52,8 +50,8 @@ BmmCreateBootNextMenu( ASSERT (OptionsOpCodeHandle != NULL); for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (NewLoadContext->IsBootNext) { HiiCreateOneOfOptionOpCode ( @@ -95,7 +93,7 @@ BmmCreateBootNextMenu( HiiCreateOneOfOpCode ( StartOpCodeHandle, - (EFI_QUESTION_ID) BOOT_NEXT_QUESTION_ID, + (EFI_QUESTION_ID)BOOT_NEXT_QUESTION_ID, VARSTORE_ID_BOOT_MAINT, BOOT_NEXT_VAR_OFFSET, STRING_TOKEN (STR_BOOT_NEXT), @@ -107,7 +105,6 @@ BmmCreateBootNextMenu( ); HiiFreeOpCodeHandle (OptionsOpCodeHandle); - } /** @@ -119,17 +116,17 @@ BmmCreateBootNextMenu( **/ VOID BmmCreateTimeOutMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateNumericOpCode ( StartOpCodeHandle, - (EFI_QUESTION_ID) FORM_TIME_OUT_ID, + (EFI_QUESTION_ID)FORM_TIME_OUT_ID, VARSTORE_ID_BOOT_MAINT, BOOT_TIME_OUT_VAR_OFFSET, - STRING_TOKEN(STR_NUM_AUTO_BOOT), - STRING_TOKEN(STR_HLP_AUTO_BOOT), + STRING_TOKEN (STR_NUM_AUTO_BOOT), + STRING_TOKEN (STR_HLP_AUTO_BOOT), EFI_IFR_FLAG_CALLBACK, EFI_IFR_NUMERIC_SIZE_2 | EFI_IFR_DISPLAY_UINT_DEC, 0, @@ -148,8 +145,8 @@ BmmCreateTimeOutMenu ( **/ VOID BmmCreateBootOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateGotoOpCode ( @@ -171,8 +168,8 @@ BmmCreateBootOptionMenu ( **/ VOID BmmCreateDriverOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateGotoOpCode ( @@ -194,8 +191,8 @@ BmmCreateDriverOptionMenu ( **/ VOID BmmCreateComOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateGotoOpCode ( @@ -217,8 +214,8 @@ BmmCreateComOptionMenu ( **/ VOID BmmCreateBootFromFileMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateGotoOpCode ( @@ -240,8 +237,8 @@ BmmCreateBootFromFileMenu ( **/ VOID BmmCreateEmptyLine ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ) { HiiCreateSubTitleOpCode (StartOpCodeHandle, STRING_TOKEN (STR_NULL_STRING), 0, 0, 0); @@ -258,11 +255,11 @@ BmmCreateEmptyLine ( **/ CHAR16 * ExtractDevicePathFromHandle ( - IN EFI_HII_HANDLE Handle + IN EFI_HII_HANDLE Handle ) { - EFI_STATUS Status; - EFI_HANDLE DriverHandle; + EFI_STATUS Status; + EFI_HANDLE DriverHandle; ASSERT (Handle != NULL); @@ -275,7 +272,7 @@ ExtractDevicePathFromHandle ( return NULL; } - return ConvertDevicePathToText(DevicePathFromHandle (DriverHandle), FALSE, FALSE); + return ConvertDevicePathToText (DevicePathFromHandle (DriverHandle), FALSE, FALSE); } /** @@ -292,49 +289,49 @@ ExtractDevicePathFromHandle ( **/ BOOLEAN IsRequiredDriver ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *Guid, - OUT EFI_STRING_ID *PromptId, - OUT EFI_STRING_ID *HelpId, - OUT VOID *FormsetGuid + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *Guid, + OUT EFI_STRING_ID *PromptId, + OUT EFI_STRING_ID *HelpId, + OUT VOID *FormsetGuid ) { - EFI_STATUS Status; - UINT8 ClassGuidNum; - EFI_GUID *ClassGuid; - EFI_IFR_FORM_SET *Buffer; - UINTN BufferSize; - UINT8 *Ptr; - UINTN TempSize; - BOOLEAN RetVal; - - Status = HiiGetFormSetFromHiiHandle(HiiHandle, &Buffer,&BufferSize); + EFI_STATUS Status; + UINT8 ClassGuidNum; + EFI_GUID *ClassGuid; + EFI_IFR_FORM_SET *Buffer; + UINTN BufferSize; + UINT8 *Ptr; + UINTN TempSize; + BOOLEAN RetVal; + + Status = HiiGetFormSetFromHiiHandle (HiiHandle, &Buffer, &BufferSize); if (EFI_ERROR (Status)) { return FALSE; } - RetVal = FALSE; + RetVal = FALSE; TempSize = 0; - Ptr = (UINT8 *) Buffer; - while(TempSize < BufferSize) { - TempSize += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + Ptr = (UINT8 *)Buffer; + while (TempSize < BufferSize) { + TempSize += ((EFI_IFR_OP_HEADER *)Ptr)->Length; - if (((EFI_IFR_OP_HEADER *) Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)){ - Ptr += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + if (((EFI_IFR_OP_HEADER *)Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)) { + Ptr += ((EFI_IFR_OP_HEADER *)Ptr)->Length; continue; } - ClassGuidNum = (UINT8) (((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); - ClassGuid = (EFI_GUID *) (VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); + ClassGuidNum = (UINT8)(((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); + ClassGuid = (EFI_GUID *)(VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); while (ClassGuidNum-- > 0) { - if (!CompareGuid (Guid, ClassGuid)){ - ClassGuid ++; + if (!CompareGuid (Guid, ClassGuid)) { + ClassGuid++; continue; } *PromptId = ((EFI_IFR_FORM_SET *)Ptr)->FormSetTitle; - *HelpId = ((EFI_IFR_FORM_SET *)Ptr)->Help; - CopyMem (FormsetGuid, &((EFI_IFR_FORM_SET *) Ptr)->Guid, sizeof (EFI_GUID)); + *HelpId = ((EFI_IFR_FORM_SET *)Ptr)->Help; + CopyMem (FormsetGuid, &((EFI_IFR_FORM_SET *)Ptr)->Guid, sizeof (EFI_GUID)); RetVal = TRUE; } } @@ -358,23 +355,23 @@ IsRequiredDriver ( **/ EFI_STATUS BmmListThirdPartyDrivers ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *ClassGuid, - IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *ClassGuid, + IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, + IN VOID *StartOpCodeHandle ) { - UINTN Index; - EFI_STRING String; - EFI_STRING_ID Token; - EFI_STRING_ID TokenHelp; - EFI_HII_HANDLE *HiiHandles; - CHAR16 *DevicePathStr; - UINTN Count; - UINTN CurrentSize; - UI_HII_DRIVER_INSTANCE *DriverListPtr; - EFI_STRING NewName; - BOOLEAN EmptyLineAfter; + UINTN Index; + EFI_STRING String; + EFI_STRING_ID Token; + EFI_STRING_ID TokenHelp; + EFI_HII_HANDLE *HiiHandles; + CHAR16 *DevicePathStr; + UINTN Count; + UINTN CurrentSize; + UI_HII_DRIVER_INSTANCE *DriverListPtr; + EFI_STRING NewName; + BOOLEAN EmptyLineAfter; if (gHiiDriverList != NULL) { FreePool (gHiiDriverList); @@ -386,7 +383,7 @@ BmmListThirdPartyDrivers ( gHiiDriverList = AllocateZeroPool (UI_HII_DRIVER_LIST_SIZE * sizeof (UI_HII_DRIVER_INSTANCE)); ASSERT (gHiiDriverList != NULL); DriverListPtr = gHiiDriverList; - CurrentSize = UI_HII_DRIVER_LIST_SIZE; + CurrentSize = UI_HII_DRIVER_LIST_SIZE; for (Index = 0, Count = 0; HiiHandles[Index] != NULL; Index++) { if (!IsRequiredDriver (HiiHandles[Index], ClassGuid, &Token, &TokenHelp, &gHiiDriverList[Count].FormSetGuid)) { @@ -404,10 +401,11 @@ BmmListThirdPartyDrivers ( EmptyLineAfter = FALSE; if (SpecialHandlerFn (String, &NewName, &EmptyLineAfter)) { FreePool (String); - String = NewName; + String = NewName; DriverListPtr[Count].EmptyLineAfter = EmptyLineAfter; } } + DriverListPtr[Count].PromptId = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); @@ -416,11 +414,12 @@ BmmListThirdPartyDrivers ( String = HiiGetString (HiiHandle, STRING_TOKEN (STR_MISSING_STRING), NULL); ASSERT (String != NULL); } + DriverListPtr[Count].HelpId = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); - DevicePathStr = ExtractDevicePathFromHandle(HiiHandles[Index]); - if (DevicePathStr != NULL){ + DevicePathStr = ExtractDevicePathFromHandle (HiiHandles[Index]); + if (DevicePathStr != NULL) { DriverListPtr[Count].DevicePathId = HiiSetString (HiiHandle, 0, DevicePathStr, NULL); FreePool (DevicePathStr); } else { @@ -437,7 +436,7 @@ BmmListThirdPartyDrivers ( ); ASSERT (DriverListPtr != NULL); gHiiDriverList = DriverListPtr; - CurrentSize += UI_HII_DRIVER_LIST_SIZE; + CurrentSize += UI_HII_DRIVER_LIST_SIZE; } } @@ -455,15 +454,14 @@ BmmListThirdPartyDrivers ( 0, &gHiiDriverList[Index].FormSetGuid, gHiiDriverList[Index].DevicePathId - ); + ); if (gHiiDriverList[Index].EmptyLineAfter) { BmmCreateEmptyLine (HiiHandle, StartOpCodeHandle); } - Index ++; + Index++; } return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.h b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.h index 0dff6e5569..dece1ec175 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.h +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerCustomizedUiSupport.h @@ -18,8 +18,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ VOID BmmCreateTimeOutMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -30,9 +30,9 @@ BmmCreateTimeOutMenu ( **/ VOID -BmmCreateBootNextMenu( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle +BmmCreateBootNextMenu ( + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -44,8 +44,8 @@ BmmCreateBootNextMenu( **/ VOID BmmCreateBootOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -57,8 +57,8 @@ BmmCreateBootOptionMenu ( **/ VOID BmmCreateDriverOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -70,8 +70,8 @@ BmmCreateDriverOptionMenu ( **/ VOID BmmCreateComOptionMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -83,8 +83,8 @@ BmmCreateComOptionMenu ( **/ VOID BmmCreateBootFromFileMenu ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -96,8 +96,8 @@ BmmCreateBootFromFileMenu ( **/ VOID BmmCreateEmptyLine ( - IN EFI_HII_HANDLE HiiHandle, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN VOID *StartOpCodeHandle ); /** @@ -116,7 +116,7 @@ EFI_STATUS IN CHAR16 *DriverName, OUT CHAR16 **NewName, OUT BOOLEAN *EmptyLineAfter -); + ); /** Search the drivers in the system which need to show in the front page @@ -132,10 +132,10 @@ EFI_STATUS **/ EFI_STATUS BmmListThirdPartyDrivers ( - IN EFI_HII_HANDLE HiiHandle, - IN EFI_GUID *ClassGuid, - IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, - IN VOID *StartOpCodeHandle + IN EFI_HII_HANDLE HiiHandle, + IN EFI_GUID *ClassGuid, + IN DRIVER_SPECIAL_HANDLER SpecialHandlerFn, + IN VOID *StartOpCodeHandle ); #endif diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c index 45d0fbb8a1..cdaa2db153 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootOption.c @@ -15,7 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// Define the maximum characters that will be accepted. /// -#define MAX_CHAR 480 +#define MAX_CHAR 480 /** @@ -27,21 +27,21 @@ BmmSetupResetReminder ( VOID ) { - EFI_INPUT_KEY Key; - CHAR16 *StringBuffer1; - CHAR16 *StringBuffer2; - EFI_STATUS Status; - EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL *FormBrowserEx2; + EFI_INPUT_KEY Key; + CHAR16 *StringBuffer1; + CHAR16 *StringBuffer2; + EFI_STATUS Status; + EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL *FormBrowserEx2; // // Use BrowserEx2 protocol to check whether reset is required. // - Status = gBS->LocateProtocol (&gEdkiiFormBrowserEx2ProtocolGuid, NULL, (VOID **) &FormBrowserEx2); + Status = gBS->LocateProtocol (&gEdkiiFormBrowserEx2ProtocolGuid, NULL, (VOID **)&FormBrowserEx2); // - //check any reset required change is applied? if yes, reset system + // check any reset required change is applied? if yes, reset system // - if (!EFI_ERROR(Status) && FormBrowserEx2->IsResetRequired()) { + if (!EFI_ERROR (Status) && FormBrowserEx2->IsResetRequired ()) { StringBuffer1 = AllocateZeroPool (MAX_CHAR * sizeof (CHAR16)); ASSERT (StringBuffer1 != NULL); StringBuffer2 = AllocateZeroPool (MAX_CHAR * sizeof (CHAR16)); @@ -73,39 +73,39 @@ BmmSetupResetReminder ( **/ BM_MENU_ENTRY * BOpt_CreateMenuEntry ( - UINTN MenuType + UINTN MenuType ) { - BM_MENU_ENTRY *MenuEntry; - UINTN ContextSize; + BM_MENU_ENTRY *MenuEntry; + UINTN ContextSize; // // Get context size according to menu type // switch (MenuType) { - case BM_LOAD_CONTEXT_SELECT: - ContextSize = sizeof (BM_LOAD_CONTEXT); - break; + case BM_LOAD_CONTEXT_SELECT: + ContextSize = sizeof (BM_LOAD_CONTEXT); + break; - case BM_FILE_CONTEXT_SELECT: - ContextSize = sizeof (BM_FILE_CONTEXT); - break; + case BM_FILE_CONTEXT_SELECT: + ContextSize = sizeof (BM_FILE_CONTEXT); + break; - case BM_CONSOLE_CONTEXT_SELECT: - ContextSize = sizeof (BM_CONSOLE_CONTEXT); - break; + case BM_CONSOLE_CONTEXT_SELECT: + ContextSize = sizeof (BM_CONSOLE_CONTEXT); + break; - case BM_TERMINAL_CONTEXT_SELECT: - ContextSize = sizeof (BM_TERMINAL_CONTEXT); - break; + case BM_TERMINAL_CONTEXT_SELECT: + ContextSize = sizeof (BM_TERMINAL_CONTEXT); + break; - case BM_HANDLE_CONTEXT_SELECT: - ContextSize = sizeof (BM_HANDLE_CONTEXT); - break; + case BM_HANDLE_CONTEXT_SELECT: + ContextSize = sizeof (BM_HANDLE_CONTEXT); + break; - default: - ContextSize = 0; - break; + default: + ContextSize = 0; + break; } if (ContextSize == 0) { @@ -139,67 +139,70 @@ BOpt_CreateMenuEntry ( **/ VOID BOpt_DestroyMenuEntry ( - BM_MENU_ENTRY *MenuEntry + BM_MENU_ENTRY *MenuEntry ) { - BM_LOAD_CONTEXT *LoadContext; - BM_FILE_CONTEXT *FileContext; - BM_CONSOLE_CONTEXT *ConsoleContext; - BM_TERMINAL_CONTEXT *TerminalContext; - BM_HANDLE_CONTEXT *HandleContext; + BM_LOAD_CONTEXT *LoadContext; + BM_FILE_CONTEXT *FileContext; + BM_CONSOLE_CONTEXT *ConsoleContext; + BM_TERMINAL_CONTEXT *TerminalContext; + BM_HANDLE_CONTEXT *HandleContext; // // Select by the type in Menu entry for current context type // switch (MenuEntry->ContextSelection) { - case BM_LOAD_CONTEXT_SELECT: - LoadContext = (BM_LOAD_CONTEXT *) MenuEntry->VariableContext; - FreePool (LoadContext->FilePathList); - if (LoadContext->OptionalData != NULL) { - FreePool (LoadContext->OptionalData); - } - FreePool (LoadContext); - break; + case BM_LOAD_CONTEXT_SELECT: + LoadContext = (BM_LOAD_CONTEXT *)MenuEntry->VariableContext; + FreePool (LoadContext->FilePathList); + if (LoadContext->OptionalData != NULL) { + FreePool (LoadContext->OptionalData); + } - case BM_FILE_CONTEXT_SELECT: - FileContext = (BM_FILE_CONTEXT *) MenuEntry->VariableContext; + FreePool (LoadContext); + break; - if (!FileContext->IsRoot) { - FreePool (FileContext->DevicePath); - } else { - if (FileContext->FHandle != NULL) { - FileContext->FHandle->Close (FileContext->FHandle); + case BM_FILE_CONTEXT_SELECT: + FileContext = (BM_FILE_CONTEXT *)MenuEntry->VariableContext; + + if (!FileContext->IsRoot) { + FreePool (FileContext->DevicePath); + } else { + if (FileContext->FHandle != NULL) { + FileContext->FHandle->Close (FileContext->FHandle); + } } - } - if (FileContext->FileName != NULL) { - FreePool (FileContext->FileName); - } - if (FileContext->Info != NULL) { - FreePool (FileContext->Info); - } - FreePool (FileContext); - break; - - case BM_CONSOLE_CONTEXT_SELECT: - ConsoleContext = (BM_CONSOLE_CONTEXT *) MenuEntry->VariableContext; - FreePool (ConsoleContext->DevicePath); - FreePool (ConsoleContext); - break; - - case BM_TERMINAL_CONTEXT_SELECT: - TerminalContext = (BM_TERMINAL_CONTEXT *) MenuEntry->VariableContext; - FreePool (TerminalContext->DevicePath); - FreePool (TerminalContext); - break; - - case BM_HANDLE_CONTEXT_SELECT: - HandleContext = (BM_HANDLE_CONTEXT *) MenuEntry->VariableContext; - FreePool (HandleContext); - break; - - default: - break; + if (FileContext->FileName != NULL) { + FreePool (FileContext->FileName); + } + + if (FileContext->Info != NULL) { + FreePool (FileContext->Info); + } + + FreePool (FileContext); + break; + + case BM_CONSOLE_CONTEXT_SELECT: + ConsoleContext = (BM_CONSOLE_CONTEXT *)MenuEntry->VariableContext; + FreePool (ConsoleContext->DevicePath); + FreePool (ConsoleContext); + break; + + case BM_TERMINAL_CONTEXT_SELECT: + TerminalContext = (BM_TERMINAL_CONTEXT *)MenuEntry->VariableContext; + FreePool (TerminalContext->DevicePath); + FreePool (TerminalContext); + break; + + case BM_HANDLE_CONTEXT_SELECT: + HandleContext = (BM_HANDLE_CONTEXT *)MenuEntry->VariableContext; + FreePool (HandleContext); + break; + + default: + break; } FreePool (MenuEntry->DisplayString); @@ -224,13 +227,13 @@ BOpt_DestroyMenuEntry ( **/ BM_MENU_ENTRY * BOpt_GetMenuEntry ( - BM_MENU_OPTION *MenuOption, - UINTN MenuNumber + BM_MENU_OPTION *MenuOption, + UINTN MenuNumber ) { - BM_MENU_ENTRY *NewMenuEntry; - UINTN Index; - LIST_ENTRY *List; + BM_MENU_ENTRY *NewMenuEntry; + UINTN Index; + LIST_ENTRY *List; ASSERT (MenuNumber < MenuOption->MenuNumber); @@ -251,10 +254,11 @@ BOpt_GetMenuEntry ( **/ VOID BOpt_FreeMenu ( - BM_MENU_OPTION *FreeMenu + BM_MENU_OPTION *FreeMenu ) { - BM_MENU_ENTRY *MenuEntry; + BM_MENU_ENTRY *MenuEntry; + while (!IsListEmpty (&FreeMenu->Head)) { MenuEntry = CR ( FreeMenu->Head.ForwardLink, @@ -265,6 +269,7 @@ BOpt_FreeMenu ( RemoveEntryList (&MenuEntry->Link); BOpt_DestroyMenuEntry (MenuEntry); } + FreeMenu->MenuNumber = 0; } @@ -281,7 +286,7 @@ BOpt_FreeMenu ( **/ EFI_STATUS BOpt_GetBootOptions ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { UINTN Index; @@ -317,7 +322,7 @@ BOpt_GetBootOptions ( // // Get the BootOrder from the Var // - GetEfiGlobalVariable2 (L"BootOrder", (VOID **) &BootOrderList, &BootOrderListSize); + GetEfiGlobalVariable2 (L"BootOrder", (VOID **)&BootOrderList, &BootOrderListSize); if (BootOrderList == NULL) { return EFI_NOT_FOUND; } @@ -325,13 +330,14 @@ BOpt_GetBootOptions ( // // Get the BootNext from the Var // - GetEfiGlobalVariable2 (L"BootNext", (VOID **) &BootNext, &BootNextSize); + GetEfiGlobalVariable2 (L"BootNext", (VOID **)&BootNext, &BootNextSize); if (BootNext != NULL) { if (BootNextSize != sizeof (UINT16)) { FreePool (BootNext); BootNext = NULL; } } + BootOption = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot); for (Index = 0; Index < BootOrderListSize / sizeof (UINT16); Index++) { // @@ -345,13 +351,13 @@ BOpt_GetBootOptions ( // // Get all loadoptions from the VAR // - GetEfiGlobalVariable2 (BootString, (VOID **) &LoadOptionFromVar, &BootOptionSize); + GetEfiGlobalVariable2 (BootString, (VOID **)&LoadOptionFromVar, &BootOptionSize); if (LoadOptionFromVar == NULL) { continue; } if (BootNext != NULL) { - BootNextFlag = (BOOLEAN) (*BootNext == BootOrderList[Index]); + BootNextFlag = (BOOLEAN)(*BootNext == BootOrderList[Index]); } else { BootNextFlag = FALSE; } @@ -359,19 +365,19 @@ BOpt_GetBootOptions ( NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT); ASSERT (NULL != NewMenuEntry); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; - LoadOptionPtr = LoadOptionFromVar; - LoadOptionEnd = LoadOptionFromVar + BootOptionSize; + LoadOptionPtr = LoadOptionFromVar; + LoadOptionEnd = LoadOptionFromVar + BootOptionSize; - NewMenuEntry->OptionNumber = BootOrderList[Index]; - NewLoadContext->Deleted = FALSE; - NewLoadContext->IsBootNext = BootNextFlag; + NewMenuEntry->OptionNumber = BootOrderList[Index]; + NewLoadContext->Deleted = FALSE; + NewLoadContext->IsBootNext = BootNextFlag; // // Is a Legacy Device? // - Ptr = (UINT8 *) LoadOptionFromVar; + Ptr = (UINT8 *)LoadOptionFromVar; // // Attribute = *(UINT32 *)Ptr; @@ -386,38 +392,39 @@ BOpt_GetBootOptions ( // // Description = (CHAR16 *)Ptr; // - Ptr += StrSize ((CHAR16 *) Ptr); + Ptr += StrSize ((CHAR16 *)Ptr); // // Now Ptr point to Device Path // - DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Ptr; + DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)Ptr; if ((BBS_DEVICE_PATH == DevicePath->Type) && (BBS_BBS_DP == DevicePath->SubType)) { NewLoadContext->IsLegacy = TRUE; } else { NewLoadContext->IsLegacy = FALSE; } + // // LoadOption is a pointer type of UINT8 // for easy use with following LOAD_OPTION // embedded in this struct // - NewLoadContext->Attributes = *(UINT32 *) LoadOptionPtr; + NewLoadContext->Attributes = *(UINT32 *)LoadOptionPtr; LoadOptionPtr += sizeof (UINT32); - NewLoadContext->FilePathListLength = *(UINT16 *) LoadOptionPtr; - LoadOptionPtr += sizeof (UINT16); + NewLoadContext->FilePathListLength = *(UINT16 *)LoadOptionPtr; + LoadOptionPtr += sizeof (UINT16); - StringSize = StrSize((UINT16*)LoadOptionPtr); + StringSize = StrSize ((UINT16 *)LoadOptionPtr); - NewLoadContext->Description = AllocateZeroPool (StrSize((UINT16*)LoadOptionPtr)); + NewLoadContext->Description = AllocateZeroPool (StrSize ((UINT16 *)LoadOptionPtr)); ASSERT (NewLoadContext->Description != NULL); - StrCpyS (NewLoadContext->Description, StrSize((UINT16*)LoadOptionPtr) / sizeof (UINT16), (UINT16*)LoadOptionPtr); + StrCpyS (NewLoadContext->Description, StrSize ((UINT16 *)LoadOptionPtr) / sizeof (UINT16), (UINT16 *)LoadOptionPtr); ASSERT (NewLoadContext->Description != NULL); - NewMenuEntry->DisplayString = NewLoadContext->Description; + NewMenuEntry->DisplayString = NewLoadContext->Description; NewMenuEntry->DisplayStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->DisplayString, NULL); LoadOptionPtr += StringSize; @@ -426,21 +433,21 @@ BOpt_GetBootOptions ( ASSERT (NewLoadContext->FilePathList != NULL); CopyMem ( NewLoadContext->FilePathList, - (EFI_DEVICE_PATH_PROTOCOL *) LoadOptionPtr, + (EFI_DEVICE_PATH_PROTOCOL *)LoadOptionPtr, NewLoadContext->FilePathListLength ); - NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); + NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); NewMenuEntry->HelpStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->HelpString, NULL); LoadOptionPtr += NewLoadContext->FilePathListLength; if (LoadOptionPtr < LoadOptionEnd) { OptionalDataSize = BootOptionSize - - sizeof (UINT32) - - sizeof (UINT16) - - StringSize - - NewLoadContext->FilePathListLength; + sizeof (UINT32) - + sizeof (UINT16) - + StringSize - + NewLoadContext->FilePathListLength; NewLoadContext->OptionalData = AllocateZeroPool (OptionalDataSize); ASSERT (NewLoadContext->OptionalData != NULL); @@ -455,11 +462,13 @@ BOpt_GetBootOptions ( MenuCount++; FreePool (LoadOptionFromVar); } + EfiBootManagerFreeLoadOptions (BootOption, BootOptionCount); if (BootNext != NULL) { FreePool (BootNext); } + if (BootOrderList != NULL) { FreePool (BootOrderList); } @@ -484,19 +493,19 @@ BOpt_FindDrivers ( VOID ) { - UINTN NoDevicePathHandles; - EFI_HANDLE *DevicePathHandle; - UINTN Index; - EFI_STATUS Status; - BM_MENU_ENTRY *NewMenuEntry; - BM_HANDLE_CONTEXT *NewHandleContext; - EFI_HANDLE CurHandle; - UINTN OptionNumber; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *SimpleFs; - EFI_LOAD_FILE_PROTOCOL *LoadFile; - - SimpleFs = NULL; - LoadFile = NULL; + UINTN NoDevicePathHandles; + EFI_HANDLE *DevicePathHandle; + UINTN Index; + EFI_STATUS Status; + BM_MENU_ENTRY *NewMenuEntry; + BM_HANDLE_CONTEXT *NewHandleContext; + EFI_HANDLE CurHandle; + UINTN OptionNumber; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *SimpleFs; + EFI_LOAD_FILE_PROTOCOL *LoadFile; + + SimpleFs = NULL; + LoadFile = NULL; InitializeListHead (&DriverMenu.Head); @@ -523,7 +532,7 @@ BOpt_FindDrivers ( Status = gBS->HandleProtocol ( CurHandle, &gEfiSimpleFileSystemProtocolGuid, - (VOID **) &SimpleFs + (VOID **)&SimpleFs ); if (Status == EFI_SUCCESS) { continue; @@ -532,7 +541,7 @@ BOpt_FindDrivers ( Status = gBS->HandleProtocol ( CurHandle, &gEfiLoadFileProtocolGuid, - (VOID **) &LoadFile + (VOID **)&LoadFile ); if (Status == EFI_SUCCESS) { continue; @@ -544,17 +553,16 @@ BOpt_FindDrivers ( return EFI_OUT_OF_RESOURCES; } - NewHandleContext = (BM_HANDLE_CONTEXT *) NewMenuEntry->VariableContext; - NewHandleContext->Handle = CurHandle; - NewHandleContext->DevicePath = DevicePathFromHandle (CurHandle); - NewMenuEntry->DisplayString = UiDevicePathToStr (NewHandleContext->DevicePath); - NewMenuEntry->DisplayStringToken = HiiSetString (mBmmCallbackInfo->BmmHiiHandle,0,NewMenuEntry->DisplayString,NULL); - NewMenuEntry->HelpString = NULL; - NewMenuEntry->HelpStringToken = NewMenuEntry->DisplayStringToken; - NewMenuEntry->OptionNumber = OptionNumber; + NewHandleContext = (BM_HANDLE_CONTEXT *)NewMenuEntry->VariableContext; + NewHandleContext->Handle = CurHandle; + NewHandleContext->DevicePath = DevicePathFromHandle (CurHandle); + NewMenuEntry->DisplayString = UiDevicePathToStr (NewHandleContext->DevicePath); + NewMenuEntry->DisplayStringToken = HiiSetString (mBmmCallbackInfo->BmmHiiHandle, 0, NewMenuEntry->DisplayString, NULL); + NewMenuEntry->HelpString = NULL; + NewMenuEntry->HelpStringToken = NewMenuEntry->DisplayStringToken; + NewMenuEntry->OptionNumber = OptionNumber; OptionNumber++; InsertTailList (&DriverMenu.Head, &NewMenuEntry->Link); - } if (DevicePathHandle != NULL) { @@ -576,16 +584,16 @@ BOpt_FindDrivers ( **/ UINT16 BOpt_GetOptionNumber ( - CHAR16 *Type + CHAR16 *Type ) { - UINT16 *OrderList; - UINTN OrderListSize; - UINTN Index; - CHAR16 StrTemp[20]; - UINT16 *OptionBuffer; - UINT16 OptionNumber; - UINTN OptionSize; + UINT16 *OrderList; + UINTN OrderListSize; + UINTN Index; + CHAR16 StrTemp[20]; + UINT16 *OptionBuffer; + UINT16 OptionNumber; + UINTN OptionSize; OrderListSize = 0; OrderList = NULL; @@ -594,7 +602,7 @@ BOpt_GetOptionNumber ( UnicodeSPrint (StrTemp, sizeof (StrTemp), L"%sOrder", Type); - GetEfiGlobalVariable2 (StrTemp, (VOID **) &OrderList, &OrderListSize); + GetEfiGlobalVariable2 (StrTemp, (VOID **)&OrderList, &OrderListSize); for (OptionNumber = 0; ; OptionNumber++) { if (OrderList != NULL) { for (Index = 0; Index < OrderListSize / sizeof (UINT16); Index++) { @@ -610,9 +618,10 @@ BOpt_GetOptionNumber ( // continue; } - UnicodeSPrint (StrTemp, sizeof (StrTemp), L"%s%04x", Type, (UINTN) OptionNumber); - DEBUG((DEBUG_ERROR,"Option = %s\n", StrTemp)); - GetEfiGlobalVariable2 (StrTemp, (VOID **) &OptionBuffer, &OptionSize); + + UnicodeSPrint (StrTemp, sizeof (StrTemp), L"%s%04x", Type, (UINTN)OptionNumber); + DEBUG ((DEBUG_ERROR, "Option = %s\n", StrTemp)); + GetEfiGlobalVariable2 (StrTemp, (VOID **)&OptionBuffer, &OptionSize); if (NULL == OptionBuffer) { // // The Boot[OptionNumber] / Driver[OptionNumber] NOT occurs, we found it @@ -667,22 +676,22 @@ BOpt_GetDriverOptionNumber ( **/ EFI_STATUS BOpt_GetDriverOptions ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINTN Index; - UINT16 DriverString[12]; - UINT8 *LoadOptionFromVar; - UINTN DriverOptionSize; - - UINT16 *DriverOrderList; - UINTN DriverOrderListSize; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT8 *LoadOptionPtr; - UINTN StringSize; - UINTN OptionalDataSize; - UINT8 *LoadOptionEnd; + UINTN Index; + UINT16 DriverString[12]; + UINT8 *LoadOptionFromVar; + UINTN DriverOptionSize; + + UINT16 *DriverOrderList; + UINTN DriverOrderListSize; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT8 *LoadOptionPtr; + UINTN StringSize; + UINTN OptionalDataSize; + UINT8 *LoadOptionEnd; DriverOrderListSize = 0; DriverOrderList = NULL; @@ -693,7 +702,7 @@ BOpt_GetDriverOptions ( // // Get the DriverOrder from the Var // - GetEfiGlobalVariable2 (L"DriverOrder", (VOID **) &DriverOrderList, &DriverOrderListSize); + GetEfiGlobalVariable2 (L"DriverOrder", (VOID **)&DriverOrderList, &DriverOrderListSize); if (DriverOrderList == NULL) { return EFI_NOT_FOUND; } @@ -708,23 +717,22 @@ BOpt_GetDriverOptions ( // // Get all loadoptions from the VAR // - GetEfiGlobalVariable2 (DriverString, (VOID **) &LoadOptionFromVar, &DriverOptionSize); + GetEfiGlobalVariable2 (DriverString, (VOID **)&LoadOptionFromVar, &DriverOptionSize); if (LoadOptionFromVar == NULL) { continue; } - NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT); if (NULL == NewMenuEntry) { return EFI_OUT_OF_RESOURCES; } - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - LoadOptionPtr = LoadOptionFromVar; - LoadOptionEnd = LoadOptionFromVar + DriverOptionSize; - NewMenuEntry->OptionNumber = DriverOrderList[Index]; - NewLoadContext->Deleted = FALSE; - NewLoadContext->IsLegacy = FALSE; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + LoadOptionPtr = LoadOptionFromVar; + LoadOptionEnd = LoadOptionFromVar + DriverOptionSize; + NewMenuEntry->OptionNumber = DriverOrderList[Index]; + NewLoadContext->Deleted = FALSE; + NewLoadContext->IsLegacy = FALSE; // // LoadOption is a pointer type of UINT8 @@ -732,22 +740,22 @@ BOpt_GetDriverOptions ( // embedded in this struct // - NewLoadContext->Attributes = *(UINT32 *) LoadOptionPtr; + NewLoadContext->Attributes = *(UINT32 *)LoadOptionPtr; LoadOptionPtr += sizeof (UINT32); - NewLoadContext->FilePathListLength = *(UINT16 *) LoadOptionPtr; - LoadOptionPtr += sizeof (UINT16); + NewLoadContext->FilePathListLength = *(UINT16 *)LoadOptionPtr; + LoadOptionPtr += sizeof (UINT16); - StringSize = StrSize ((UINT16 *) LoadOptionPtr); + StringSize = StrSize ((UINT16 *)LoadOptionPtr); NewLoadContext->Description = AllocateZeroPool (StringSize); ASSERT (NewLoadContext->Description != NULL); CopyMem ( NewLoadContext->Description, - (UINT16 *) LoadOptionPtr, + (UINT16 *)LoadOptionPtr, StringSize ); - NewMenuEntry->DisplayString = NewLoadContext->Description; + NewMenuEntry->DisplayString = NewLoadContext->Description; NewMenuEntry->DisplayStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->DisplayString, NULL); LoadOptionPtr += StringSize; @@ -756,21 +764,21 @@ BOpt_GetDriverOptions ( ASSERT (NewLoadContext->FilePathList != NULL); CopyMem ( NewLoadContext->FilePathList, - (EFI_DEVICE_PATH_PROTOCOL *) LoadOptionPtr, + (EFI_DEVICE_PATH_PROTOCOL *)LoadOptionPtr, NewLoadContext->FilePathListLength ); - NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); + NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); NewMenuEntry->HelpStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->HelpString, NULL); LoadOptionPtr += NewLoadContext->FilePathListLength; if (LoadOptionPtr < LoadOptionEnd) { OptionalDataSize = DriverOptionSize - - sizeof (UINT32) - - sizeof (UINT16) - - StringSize - - NewLoadContext->FilePathListLength; + sizeof (UINT32) - + sizeof (UINT16) - + StringSize - + NewLoadContext->FilePathListLength; NewLoadContext->OptionalData = AllocateZeroPool (OptionalDataSize); ASSERT (NewLoadContext->OptionalData != NULL); @@ -779,12 +787,10 @@ BOpt_GetDriverOptions ( LoadOptionPtr, OptionalDataSize ); - } InsertTailList (&DriverOptionMenu.Head, &NewMenuEntry->Link); FreePool (LoadOptionFromVar); - } if (DriverOrderList != NULL) { @@ -793,7 +799,6 @@ BOpt_GetDriverOptions ( DriverOptionMenu.MenuNumber = Index; return EFI_SUCCESS; - } /** @@ -804,31 +809,32 @@ BOpt_GetDriverOptions ( **/ VOID GetBootOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BMM_FAKE_NV_DATA *BmmConfig; - UINT16 Index; - UINT16 OptionOrderIndex; - UINTN DeviceType; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; + BMM_FAKE_NV_DATA *BmmConfig; + UINT16 Index; + UINT16 OptionOrderIndex; + UINTN DeviceType; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; ASSERT (CallbackData != NULL); - DeviceType = (UINTN) -1; + DeviceType = (UINTN)-1; BmmConfig = &CallbackData->BmmFakeNvData; ZeroMem (BmmConfig->BootOptionOrder, sizeof (BmmConfig->BootOptionOrder)); for (Index = 0, OptionOrderIndex = 0; ((Index < BootOptionMenu.MenuNumber) && - (OptionOrderIndex < (sizeof (BmmConfig->BootOptionOrder) / sizeof (BmmConfig->BootOptionOrder[0])))); - Index++) { + (OptionOrderIndex < (sizeof (BmmConfig->BootOptionOrder) / sizeof (BmmConfig->BootOptionOrder[0])))); + Index++) + { NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (NewLoadContext->IsLegacy) { - if (((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType != DeviceType) { - DeviceType = ((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType; + if (((BBS_BBS_DEVICE_PATH *)NewLoadContext->FilePathList)->DeviceType != DeviceType) { + DeviceType = ((BBS_BBS_DEVICE_PATH *)NewLoadContext->FilePathList)->DeviceType; } else { // // Only show one legacy boot option for the same device type @@ -837,7 +843,8 @@ GetBootOrder ( continue; } } - BmmConfig->BootOptionOrder[OptionOrderIndex++] = (UINT32) (NewMenuEntry->OptionNumber + 1); + + BmmConfig->BootOptionOrder[OptionOrderIndex++] = (UINT32)(NewMenuEntry->OptionNumber + 1); } } @@ -849,32 +856,32 @@ GetBootOrder ( **/ VOID GetDriverOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BMM_FAKE_NV_DATA *BmmConfig; - UINT16 Index; - UINT16 OptionOrderIndex; - UINTN DeviceType; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - + BMM_FAKE_NV_DATA *BmmConfig; + UINT16 Index; + UINT16 OptionOrderIndex; + UINTN DeviceType; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; ASSERT (CallbackData != NULL); - DeviceType = (UINTN) -1; + DeviceType = (UINTN)-1; BmmConfig = &CallbackData->BmmFakeNvData; ZeroMem (BmmConfig->DriverOptionOrder, sizeof (BmmConfig->DriverOptionOrder)); for (Index = 0, OptionOrderIndex = 0; ((Index < DriverOptionMenu.MenuNumber) && - (OptionOrderIndex < (sizeof (BmmConfig->DriverOptionOrder) / sizeof (BmmConfig->DriverOptionOrder[0])))); - Index++) { + (OptionOrderIndex < (sizeof (BmmConfig->DriverOptionOrder) / sizeof (BmmConfig->DriverOptionOrder[0])))); + Index++) + { NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (NewLoadContext->IsLegacy) { - if (((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType != DeviceType) { - DeviceType = ((BBS_BBS_DEVICE_PATH *) NewLoadContext->FilePathList)->DeviceType; + if (((BBS_BBS_DEVICE_PATH *)NewLoadContext->FilePathList)->DeviceType != DeviceType) { + DeviceType = ((BBS_BBS_DEVICE_PATH *)NewLoadContext->FilePathList)->DeviceType; } else { // // Only show one legacy boot option for the same device type @@ -883,7 +890,8 @@ GetDriverOrder ( continue; } } - BmmConfig->DriverOptionOrder[OptionOrderIndex++] = (UINT32) (NewMenuEntry->OptionNumber + 1); + + BmmConfig->DriverOptionOrder[OptionOrderIndex++] = (UINT32)(NewMenuEntry->OptionNumber + 1); } } @@ -898,15 +906,15 @@ GetDriverOrder ( BOOLEAN EFIAPI BootFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - EFI_BOOT_MANAGER_LOAD_OPTION BootOption; - CHAR16 *FileName; + EFI_BOOT_MANAGER_LOAD_OPTION BootOption; + CHAR16 *FileName; FileName = NULL; - FileName = ExtractFileNameFromDevicePath(FilePath); + FileName = ExtractFileNameFromDevicePath (FilePath); if (FileName != NULL) { EfiBootManagerInitializeLoadOption ( &BootOption, @@ -931,7 +939,7 @@ BootFromFile ( EfiBootManagerBoot (&BootOption); BmmSetConsoleMode (TRUE); - FreePool(FileName); + FreePool (FileName); EfiBootManagerFreeLoadOption (&BootOption); } @@ -947,24 +955,24 @@ BootFromFile ( **/ BOOLEAN -ReSendForm( +ReSendForm ( IN EFI_DEVICE_PATH_PROTOCOL *FilePath, IN EFI_FORM_ID FormId ) { gBootMaintenancePrivate.LoadContext->FilePathList = FilePath; - UpdateOptionPage(&gBootMaintenancePrivate, FormId, FilePath); + UpdateOptionPage (&gBootMaintenancePrivate, FormId, FilePath); gBootMaintenancePrivate.FormBrowser2->SendForm ( - gBootMaintenancePrivate.FormBrowser2, - &gBootMaintenancePrivate.BmmHiiHandle, - 1, - &mBootMaintGuid, - FormId, - NULL, - NULL - ); + gBootMaintenancePrivate.FormBrowser2, + &gBootMaintenancePrivate.BmmHiiHandle, + 1, + &mBootMaintGuid, + FormId, + NULL, + NULL + ); return TRUE; } @@ -979,10 +987,10 @@ ReSendForm( BOOLEAN EFIAPI CreateBootOptionFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - return ReSendForm(FilePath, FORM_BOOT_ADD_ID); + return ReSendForm (FilePath, FORM_BOOT_ADD_ID); } /** @@ -997,8 +1005,8 @@ CreateBootOptionFromFile ( BOOLEAN EFIAPI CreateDriverOptionFromFile ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - return ReSendForm(FilePath, FORM_DRV_ADD_FILE_ID); + return ReSendForm (FilePath, FORM_DRV_ADD_FILE_ID); } diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/ConsoleOption.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/ConsoleOption.c index 5d1c6d34e6..7c02a78166 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/ConsoleOption.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/ConsoleOption.c @@ -31,7 +31,7 @@ MatchDevicePaths ( EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; UINTN Size; - if (Multi == NULL || Single == NULL) { + if ((Multi == NULL) || (Single == NULL)) { return FALSE; } @@ -69,14 +69,14 @@ MatchDevicePaths ( **/ BOOLEAN IsIsaSerialNode ( - IN ACPI_HID_DEVICE_PATH *Acpi + IN ACPI_HID_DEVICE_PATH *Acpi ) { - return (BOOLEAN) ( - (DevicePathType (Acpi) == ACPI_DEVICE_PATH) && - (DevicePathSubType (Acpi) == ACPI_DP) && - (ReadUnaligned32 (&Acpi->HID) == EISA_PNP_ID (0x0501)) - ); + return (BOOLEAN)( + (DevicePathType (Acpi) == ACPI_DEVICE_PATH) && + (DevicePathSubType (Acpi) == ACPI_DP) && + (ReadUnaligned32 (&Acpi->HID) == EISA_PNP_ID (0x0501)) + ); } /** @@ -119,20 +119,20 @@ ChangeTerminalDevicePath ( BM_TERMINAL_CONTEXT *NewTerminalContext; BM_MENU_ENTRY *NewMenuEntry; - Node = DevicePath; - Node = NextDevicePathNode (Node); - Com = 0; + Node = DevicePath; + Node = NextDevicePathNode (Node); + Com = 0; while (!IsDevicePathEnd (Node)) { - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; if (IsIsaSerialNode (Acpi)) { CopyMem (&Com, &Acpi->UID, sizeof (UINT32)); } NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Com); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) { - Uart = (UART_DEVICE_PATH *) Node; + Uart = (UART_DEVICE_PATH *)Node; CopyMem ( &Uart->BaudRate, &NewTerminalContext->BaudRate, @@ -164,7 +164,7 @@ ChangeTerminalDevicePath ( Node1 = NextDevicePathNode (Node1); while (!IsDevicePathEnd (Node1)) { if ((DevicePathType (Node1) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node1) == MSG_UART_DP)) { - Uart1 = (UART_DEVICE_PATH *) Node1; + Uart1 = (UART_DEVICE_PATH *)Node1; CopyMem ( &Uart1->BaudRate, &NewTerminalContext->BaudRate, @@ -190,11 +190,13 @@ ChangeTerminalDevicePath ( ); break; } + // // end if // Node1 = NextDevicePathNode (Node1); } + // // end while // @@ -206,7 +208,6 @@ ChangeTerminalDevicePath ( } return EFI_SUCCESS; - } /** @@ -229,23 +230,23 @@ ChangeVariableDevicePath ( BM_TERMINAL_CONTEXT *NewTerminalContext; BM_MENU_ENTRY *NewMenuEntry; - Node = DevicePath; - Node = NextDevicePathNode (Node); - Com = 0; + Node = DevicePath; + Node = NextDevicePathNode (Node); + Com = 0; while (!IsDevicePathEnd (Node)) { - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; if (IsIsaSerialNode (Acpi)) { CopyMem (&Com, &Acpi->UID, sizeof (UINT32)); } if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) { NewMenuEntry = BOpt_GetMenuEntry ( - &TerminalMenu, - Com - ); + &TerminalMenu, + Com + ); ASSERT (NewMenuEntry != NULL); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; - Uart = (UART_DEVICE_PATH *) Node; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; + Uart = (UART_DEVICE_PATH *)Node; CopyMem ( &Uart->BaudRate, &NewTerminalContext->BaudRate, @@ -287,8 +288,8 @@ ChangeVariableDevicePath ( **/ BOOLEAN RetrieveUartUid ( - IN EFI_HANDLE Handle, - IN OUT UINT32 *AcpiUid + IN EFI_HANDLE Handle, + IN OUT UINT32 *AcpiUid ) { EFI_STATUS Status; @@ -298,27 +299,29 @@ RetrieveUartUid ( Status = gBS->HandleProtocol ( Handle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath + (VOID **)&DevicePath ); if (EFI_ERROR (Status)) { return FALSE; } Acpi = NULL; - for (; !IsDevicePathEnd (DevicePath); DevicePath = NextDevicePathNode (DevicePath)) { + for ( ; !IsDevicePathEnd (DevicePath); DevicePath = NextDevicePathNode (DevicePath)) { if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_UART_DP)) { break; } + // // Acpi points to the node before the Uart node // - Acpi = (ACPI_HID_DEVICE_PATH *) DevicePath; + Acpi = (ACPI_HID_DEVICE_PATH *)DevicePath; } if ((Acpi != NULL) && IsIsaSerialNode (Acpi)) { if (AcpiUid != NULL) { CopyMem (AcpiUid, &Acpi->UID, sizeof (UINT32)); } + return TRUE; } else { return FALSE; @@ -333,8 +336,8 @@ RetrieveUartUid ( **/ VOID SortedUartHandle ( - IN EFI_HANDLE *Handles, - IN UINTN NoHandles + IN EFI_HANDLE *Handles, + IN UINTN NoHandles ) { UINTN Index1; @@ -349,6 +352,7 @@ SortedUartHandle ( if (!RetrieveUartUid (Handles[Index1], &AcpiUid1)) { continue; } + TempHandle = Handles[Index1]; Position = Index1; TempAcpiUid = AcpiUid1; @@ -357,12 +361,14 @@ SortedUartHandle ( if (!RetrieveUartUid (Handles[Index2], &AcpiUid2)) { continue; } + if (AcpiUid2 < TempAcpiUid) { TempAcpiUid = AcpiUid2; TempHandle = Handles[Index2]; Position = Index2; } } + Handles[Position] = Handles[Index1]; Handles[Index1] = TempHandle; } @@ -382,9 +388,9 @@ SortedUartHandle ( **/ BOOLEAN IsTerminalDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT TYPE_OF_TERMINAL *Termi, - OUT UINTN *Com + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT TYPE_OF_TERMINAL *Termi, + OUT UINTN *Com ); /** @@ -422,13 +428,13 @@ LocateSerialIo ( // InitializeListHead (&TerminalMenu.Head); TerminalMenu.MenuNumber = 0; - Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSerialIoProtocolGuid, - NULL, - &NoHandles, - &Handles - ); + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiSerialIoProtocolGuid, + NULL, + &NoHandles, + &Handles + ); if (EFI_ERROR (Status)) { // // No serial ports present @@ -447,20 +453,21 @@ LocateSerialIo ( // Check to see whether the handle has DevicePath Protocol installed // gBS->HandleProtocol ( - Handles[Index], - &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath - ); + Handles[Index], + &gEfiDevicePathProtocolGuid, + (VOID **)&DevicePath + ); Acpi = NULL; for (Node = DevicePath; !IsDevicePathEnd (Node); Node = NextDevicePathNode (Node)) { if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) { break; } + // // Acpi points to the node before Uart node // - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; } if ((Acpi != NULL) && IsIsaSerialNode (Acpi)) { @@ -470,7 +477,7 @@ LocateSerialIo ( return EFI_OUT_OF_RESOURCES; } - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; CopyMem (&NewMenuEntry->OptionNumber, &Acpi->UID, sizeof (UINT32)); NewTerminalContext->DevicePath = DuplicateDevicePath (DevicePath); // @@ -491,10 +498,10 @@ LocateSerialIo ( NewMenuEntry->HelpStringToken = NewMenuEntry->DisplayStringToken; gBS->HandleProtocol ( - Handles[Index], - &gEfiSerialIoProtocolGuid, - (VOID **) &SerialIo - ); + Handles[Index], + &gEfiSerialIoProtocolGuid, + (VOID **)&SerialIo + ); CopyMem ( &NewTerminalContext->BaudRate, @@ -523,6 +530,7 @@ LocateSerialIo ( TerminalMenu.MenuNumber++; } } + if (Handles != NULL) { FreePool (Handles); } @@ -530,9 +538,9 @@ LocateSerialIo ( // // Get L"ConOut", L"ConIn" and L"ErrOut" from the Var // - GetEfiGlobalVariable2 (L"ConOut", (VOID**)&OutDevicePath, NULL); - GetEfiGlobalVariable2 (L"ConIn", (VOID**)&InpDevicePath, NULL); - GetEfiGlobalVariable2 (L"ErrOut", (VOID**)&ErrDevicePath, NULL); + GetEfiGlobalVariable2 (L"ConOut", (VOID **)&OutDevicePath, NULL); + GetEfiGlobalVariable2 (L"ConIn", (VOID **)&InpDevicePath, NULL); + GetEfiGlobalVariable2 (L"ErrOut", (VOID **)&ErrDevicePath, NULL); if (OutDevicePath != NULL) { UpdateComAttributeFromVariable (OutDevicePath); } @@ -551,26 +559,27 @@ LocateSerialIo ( return EFI_NOT_FOUND; } - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; - NewTerminalContext->TerminalType = 0; - NewTerminalContext->IsConIn = FALSE; - NewTerminalContext->IsConOut = FALSE; - NewTerminalContext->IsStdErr = FALSE; + NewTerminalContext->TerminalType = 0; + NewTerminalContext->IsConIn = FALSE; + NewTerminalContext->IsConOut = FALSE; + NewTerminalContext->IsStdErr = FALSE; - Vendor.Header.Type = MESSAGING_DEVICE_PATH; - Vendor.Header.SubType = MSG_VENDOR_DP; + Vendor.Header.Type = MESSAGING_DEVICE_PATH; + Vendor.Header.SubType = MSG_VENDOR_DP; for (Index2 = 0; Index2 < (ARRAY_SIZE (TerminalTypeGuid)); Index2++) { CopyMem (&Vendor.Guid, &TerminalTypeGuid[Index2], sizeof (EFI_GUID)); SetDevicePathNodeLength (&Vendor.Header, sizeof (VENDOR_DEVICE_PATH)); NewDevicePath = AppendDevicePathNode ( NewTerminalContext->DevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &Vendor + (EFI_DEVICE_PATH_PROTOCOL *)&Vendor ); if (NewMenuEntry->HelpString != NULL) { FreePool (NewMenuEntry->HelpString); } + // // NewMenuEntry->HelpString = UiDevicePathToStr (NewDevicePath); // NewMenuEntry->DisplayString = NewMenuEntry->HelpString; @@ -582,18 +591,18 @@ LocateSerialIo ( NewMenuEntry->HelpStringToken = NewMenuEntry->DisplayStringToken; if (MatchDevicePaths (OutDevicePath, NewDevicePath)) { - NewTerminalContext->IsConOut = TRUE; - NewTerminalContext->TerminalType = (UINT8) Index2; + NewTerminalContext->IsConOut = TRUE; + NewTerminalContext->TerminalType = (UINT8)Index2; } if (MatchDevicePaths (InpDevicePath, NewDevicePath)) { - NewTerminalContext->IsConIn = TRUE; - NewTerminalContext->TerminalType = (UINT8) Index2; + NewTerminalContext->IsConIn = TRUE; + NewTerminalContext->TerminalType = (UINT8)Index2; } if (MatchDevicePaths (ErrDevicePath, NewDevicePath)) { - NewTerminalContext->IsStdErr = TRUE; - NewTerminalContext->TerminalType = (UINT8) Index2; + NewTerminalContext->IsStdErr = TRUE; + NewTerminalContext->TerminalType = (UINT8)Index2; } } } @@ -624,24 +633,24 @@ UpdateComAttributeFromVariable ( BM_TERMINAL_CONTEXT *NewTerminalContext; UINTN Index; - Node = DevicePath; - Node = NextDevicePathNode (Node); - TerminalNumber = 0; + Node = DevicePath; + Node = NextDevicePathNode (Node); + TerminalNumber = 0; for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { while (!IsDevicePathEnd (Node)) { - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; if (IsIsaSerialNode (Acpi)) { CopyMem (&TerminalNumber, &Acpi->UID, sizeof (UINT32)); } if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) { - Uart = (UART_DEVICE_PATH *) Node; - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalNumber); + Uart = (UART_DEVICE_PATH *)Node; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalNumber); if (NULL == NewMenuEntry) { return EFI_NOT_FOUND; } - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; CopyMem ( &NewTerminalContext->BaudRate, &Uart->BaudRate, @@ -666,15 +675,15 @@ UpdateComAttributeFromVariable ( sizeof (UINT8) ); - SerialNode = NewTerminalContext->DevicePath; - SerialNode = NextDevicePathNode (SerialNode); + SerialNode = NewTerminalContext->DevicePath; + SerialNode = NextDevicePathNode (SerialNode); while (!IsDevicePathEnd (SerialNode)) { if ((DevicePathType (SerialNode) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (SerialNode) == MSG_UART_DP)) { // // Update following device paths according to // previous acquired uart attributes // - Uart1 = (UART_DEVICE_PATH *) SerialNode; + Uart1 = (UART_DEVICE_PATH *)SerialNode; CopyMem ( &Uart1->BaudRate, &NewTerminalContext->BaudRate, @@ -702,6 +711,7 @@ UpdateComAttributeFromVariable ( SerialNode = NextDevicePathNode (SerialNode); } + // // end while // @@ -709,6 +719,7 @@ UpdateComAttributeFromVariable ( Node = NextDevicePathNode (Node); } + // // end while // @@ -734,7 +745,7 @@ UpdateComAttributeFromVariable ( **/ EFI_STATUS GetConsoleMenu ( - IN UINTN ConsoleMenuType + IN UINTN ConsoleMenuType ) { EFI_DEVICE_PATH_PROTOCOL *DevicePath; @@ -755,26 +766,26 @@ GetConsoleMenu ( AllDevicePath = NULL; AllCount = 0; switch (ConsoleMenuType) { - case BM_CONSOLE_IN_CONTEXT_SELECT: - ConsoleMenu = &ConsoleInpMenu; - GetEfiGlobalVariable2 (L"ConIn", (VOID**)&DevicePath, NULL); - GetEfiGlobalVariable2 (L"ConInDev", (VOID**)&AllDevicePath, NULL); - break; - - case BM_CONSOLE_OUT_CONTEXT_SELECT: - ConsoleMenu = &ConsoleOutMenu; - GetEfiGlobalVariable2 (L"ConOut", (VOID**)&DevicePath, NULL); - GetEfiGlobalVariable2 (L"ConOutDev", (VOID**)&AllDevicePath, NULL); - break; - - case BM_CONSOLE_ERR_CONTEXT_SELECT: - ConsoleMenu = &ConsoleErrMenu; - GetEfiGlobalVariable2 (L"ErrOut", (VOID**)&DevicePath, NULL); - GetEfiGlobalVariable2 (L"ErrOutDev", (VOID**)&AllDevicePath, NULL); - break; - - default: - return EFI_UNSUPPORTED; + case BM_CONSOLE_IN_CONTEXT_SELECT: + ConsoleMenu = &ConsoleInpMenu; + GetEfiGlobalVariable2 (L"ConIn", (VOID **)&DevicePath, NULL); + GetEfiGlobalVariable2 (L"ConInDev", (VOID **)&AllDevicePath, NULL); + break; + + case BM_CONSOLE_OUT_CONTEXT_SELECT: + ConsoleMenu = &ConsoleOutMenu; + GetEfiGlobalVariable2 (L"ConOut", (VOID **)&DevicePath, NULL); + GetEfiGlobalVariable2 (L"ConOutDev", (VOID **)&AllDevicePath, NULL); + break; + + case BM_CONSOLE_ERR_CONTEXT_SELECT: + ConsoleMenu = &ConsoleErrMenu; + GetEfiGlobalVariable2 (L"ErrOut", (VOID **)&DevicePath, NULL); + GetEfiGlobalVariable2 (L"ErrOutDev", (VOID **)&AllDevicePath, NULL); + break; + + default: + return EFI_UNSUPPORTED; } if (NULL == AllDevicePath) { @@ -791,19 +802,19 @@ GetConsoleMenu ( MultiDevicePath = AllDevicePath; Index2 = 0; for (Index = 0; Index < AllCount; Index++) { - DevicePathInst = GetNextDevicePathInstance (&MultiDevicePath, &Size); + DevicePathInst = GetNextDevicePathInstance (&MultiDevicePath, &Size); - NewMenuEntry = BOpt_CreateMenuEntry (BM_CONSOLE_CONTEXT_SELECT); + NewMenuEntry = BOpt_CreateMenuEntry (BM_CONSOLE_CONTEXT_SELECT); if (NULL == NewMenuEntry) { return EFI_OUT_OF_RESOURCES; } - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; - NewMenuEntry->OptionNumber = Index2; + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; + NewMenuEntry->OptionNumber = Index2; NewConsoleContext->DevicePath = DuplicateDevicePath (DevicePathInst); ASSERT (NewConsoleContext->DevicePath != NULL); - NewMenuEntry->DisplayString = EfiLibStrFromDatahub (NewConsoleContext->DevicePath); + NewMenuEntry->DisplayString = EfiLibStrFromDatahub (NewConsoleContext->DevicePath); if (NULL == NewMenuEntry->DisplayString) { NewMenuEntry->DisplayString = UiDevicePathToStr (NewConsoleContext->DevicePath); } @@ -887,9 +898,9 @@ FreeAllConsoles ( **/ BOOLEAN IsTerminalDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT TYPE_OF_TERMINAL *Termi, - OUT UINTN *Com + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT TYPE_OF_TERMINAL *Termi, + OUT UINTN *Com ) { BOOLEAN IsTerminal; @@ -908,24 +919,25 @@ IsTerminalDevicePath ( // // Vendor points to the node before the End node // - Vendor = (VENDOR_DEVICE_PATH *) Node; + Vendor = (VENDOR_DEVICE_PATH *)Node; if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (Node) == MSG_UART_DP)) { - Uart = (UART_DEVICE_PATH *) Node; + Uart = (UART_DEVICE_PATH *)Node; } if (Uart == NULL) { // // Acpi points to the node before the UART node // - Acpi = (ACPI_HID_DEVICE_PATH *) Node; + Acpi = (ACPI_HID_DEVICE_PATH *)Node; } } - if (Vendor == NULL || - DevicePathType (Vendor) != MESSAGING_DEVICE_PATH || - DevicePathSubType (Vendor) != MSG_VENDOR_DP || - Uart == NULL) { + if ((Vendor == NULL) || + (DevicePathType (Vendor) != MESSAGING_DEVICE_PATH) || + (DevicePathSubType (Vendor) != MSG_VENDOR_DP) || + (Uart == NULL)) + { return FALSE; } @@ -936,7 +948,7 @@ IsTerminalDevicePath ( // for (Index = 0; Index < ARRAY_SIZE (TerminalTypeGuid); Index++) { if (CompareGuid (&Vendor->Guid, &TerminalTypeGuid[Index])) { - *Termi = Index; + *Termi = Index; IsTerminal = TRUE; break; } @@ -966,28 +978,28 @@ IsTerminalDevicePath ( **/ VOID GetConsoleOutMode ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINTN Col; - UINTN Row; - UINTN CurrentCol; - UINTN CurrentRow; - UINTN Mode; - UINTN MaxMode; - EFI_STATUS Status; + UINTN Col; + UINTN Row; + UINTN CurrentCol; + UINTN CurrentRow; + UINTN Mode; + UINTN MaxMode; + EFI_STATUS Status; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut; - ConOut = gST->ConOut; - MaxMode = (UINTN) (ConOut->Mode->MaxMode); + ConOut = gST->ConOut; + MaxMode = (UINTN)(ConOut->Mode->MaxMode); CurrentCol = PcdGet32 (PcdSetupConOutColumn); CurrentRow = PcdGet32 (PcdSetupConOutRow); for (Mode = 0; Mode < MaxMode; Mode++) { Status = ConOut->QueryMode (ConOut, Mode, &Col, &Row); - if (!EFI_ERROR(Status)) { - if (CurrentCol == Col && CurrentRow == Row) { - CallbackData->BmmFakeNvData.ConsoleOutMode = (UINT16) Mode; + if (!EFI_ERROR (Status)) { + if ((CurrentCol == Col) && (CurrentRow == Row)) { + CallbackData->BmmFakeNvData.ConsoleOutMode = (UINT16)Mode; break; } } @@ -1004,28 +1016,29 @@ GetConsoleOutMode ( **/ VOID GetConsoleInCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINT16 Index; - BM_MENU_ENTRY *NewMenuEntry; - UINT8 *ConInCheck; - BM_CONSOLE_CONTEXT *NewConsoleContext; - BM_TERMINAL_CONTEXT *NewTerminalContext; + UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + UINT8 *ConInCheck; + BM_CONSOLE_CONTEXT *NewConsoleContext; + BM_TERMINAL_CONTEXT *NewTerminalContext; ASSERT (CallbackData != NULL); ConInCheck = &CallbackData->BmmFakeNvData.ConsoleInCheck[0]; for (Index = 0; ((Index < ConsoleInpMenu.MenuNumber) && \ - (Index < MAX_MENU_NUMBER)) ; Index++) { + (Index < MAX_MENU_NUMBER)); Index++) + { NewMenuEntry = BOpt_GetMenuEntry (&ConsoleInpMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ConInCheck[Index] = NewConsoleContext->IsActive; } for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleInpMenu.MenuNumber < MAX_MENU_NUMBER); ConInCheck[Index + ConsoleInpMenu.MenuNumber] = NewTerminalContext->IsConIn; } @@ -1041,27 +1054,28 @@ GetConsoleInCheck ( **/ VOID GetConsoleOutCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINT16 Index; - BM_MENU_ENTRY *NewMenuEntry; - UINT8 *ConOutCheck; - BM_CONSOLE_CONTEXT *NewConsoleContext; - BM_TERMINAL_CONTEXT *NewTerminalContext; + UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + UINT8 *ConOutCheck; + BM_CONSOLE_CONTEXT *NewConsoleContext; + BM_TERMINAL_CONTEXT *NewTerminalContext; ASSERT (CallbackData != NULL); ConOutCheck = &CallbackData->BmmFakeNvData.ConsoleOutCheck[0]; for (Index = 0; ((Index < ConsoleOutMenu.MenuNumber) && \ - (Index < MAX_MENU_NUMBER)) ; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&ConsoleOutMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; + (Index < MAX_MENU_NUMBER)); Index++) + { + NewMenuEntry = BOpt_GetMenuEntry (&ConsoleOutMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ConOutCheck[Index] = NewConsoleContext->IsActive; } for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleOutMenu.MenuNumber < MAX_MENU_NUMBER); ConOutCheck[Index + ConsoleOutMenu.MenuNumber] = NewTerminalContext->IsConOut; } @@ -1077,27 +1091,28 @@ GetConsoleOutCheck ( **/ VOID GetConsoleErrCheck ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINT16 Index; - BM_MENU_ENTRY *NewMenuEntry; - UINT8 *ConErrCheck; - BM_CONSOLE_CONTEXT *NewConsoleContext; - BM_TERMINAL_CONTEXT *NewTerminalContext; + UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + UINT8 *ConErrCheck; + BM_CONSOLE_CONTEXT *NewConsoleContext; + BM_TERMINAL_CONTEXT *NewTerminalContext; ASSERT (CallbackData != NULL); ConErrCheck = &CallbackData->BmmFakeNvData.ConsoleErrCheck[0]; for (Index = 0; ((Index < ConsoleErrMenu.MenuNumber) && \ - (Index < MAX_MENU_NUMBER)) ; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&ConsoleErrMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; + (Index < MAX_MENU_NUMBER)); Index++) + { + NewMenuEntry = BOpt_GetMenuEntry (&ConsoleErrMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; ConErrCheck[Index] = NewConsoleContext->IsActive; } for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index + ConsoleErrMenu.MenuNumber < MAX_MENU_NUMBER); ConErrCheck[Index + ConsoleErrMenu.MenuNumber] = NewTerminalContext->IsStdErr; } @@ -1113,7 +1128,7 @@ GetConsoleErrCheck ( **/ VOID GetTerminalAttribute ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { BMM_FAKE_NV_DATA *CurrentFakeNVMap; @@ -1126,35 +1141,38 @@ GetTerminalAttribute ( CurrentFakeNVMap = &CallbackData->BmmFakeNvData; for (TerminalIndex = 0; ((TerminalIndex < TerminalMenu.MenuNumber) && \ - (TerminalIndex < MAX_MENU_NUMBER)); TerminalIndex++) { - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalIndex); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; - for (AttributeIndex = 0; AttributeIndex < sizeof (BaudRateList) / sizeof (BaudRateList [0]); AttributeIndex++) { - if (NewTerminalContext->BaudRate == (UINT64) (BaudRateList[AttributeIndex].Value)) { + (TerminalIndex < MAX_MENU_NUMBER)); TerminalIndex++) + { + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, TerminalIndex); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; + for (AttributeIndex = 0; AttributeIndex < sizeof (BaudRateList) / sizeof (BaudRateList[0]); AttributeIndex++) { + if (NewTerminalContext->BaudRate == (UINT64)(BaudRateList[AttributeIndex].Value)) { NewTerminalContext->BaudRateIndex = AttributeIndex; break; } } + for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (DataBitsList); AttributeIndex++) { - if (NewTerminalContext->DataBits == (UINT64) (DataBitsList[AttributeIndex].Value)) { + if (NewTerminalContext->DataBits == (UINT64)(DataBitsList[AttributeIndex].Value)) { NewTerminalContext->DataBitsIndex = AttributeIndex; break; } } for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (ParityList); AttributeIndex++) { - if (NewTerminalContext->Parity == (UINT64) (ParityList[AttributeIndex].Value)) { + if (NewTerminalContext->Parity == (UINT64)(ParityList[AttributeIndex].Value)) { NewTerminalContext->ParityIndex = AttributeIndex; break; } } for (AttributeIndex = 0; AttributeIndex < ARRAY_SIZE (StopBitsList); AttributeIndex++) { - if (NewTerminalContext->StopBits == (UINT64) (StopBitsList[AttributeIndex].Value)) { + if (NewTerminalContext->StopBits == (UINT64)(StopBitsList[AttributeIndex].Value)) { NewTerminalContext->StopBitsIndex = AttributeIndex; break; } } + CurrentFakeNVMap->COMBaudRate[TerminalIndex] = NewTerminalContext->BaudRateIndex; CurrentFakeNVMap->COMDataRate[TerminalIndex] = NewTerminalContext->DataBitsIndex; CurrentFakeNVMap->COMStopBits[TerminalIndex] = NewTerminalContext->StopBitsIndex; @@ -1163,4 +1181,3 @@ GetTerminalAttribute ( CurrentFakeNVMap->COMFlowControl[TerminalIndex] = NewTerminalContext->FlowControl; } } - diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Data.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Data.c index 21c4ef3d55..ba2f05808c 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Data.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Data.c @@ -9,34 +9,34 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "BootMaintenanceManager.h" VOID *mStartOpCodeHandle = NULL; -VOID *mEndOpCodeHandle = NULL; -EFI_IFR_GUID_LABEL *mStartLabel = NULL; -EFI_IFR_GUID_LABEL *mEndLabel = NULL; +VOID *mEndOpCodeHandle = NULL; +EFI_IFR_GUID_LABEL *mStartLabel = NULL; +EFI_IFR_GUID_LABEL *mEndLabel = NULL; /// /// Terminal type string token storage /// -UINT16 TerminalType[9] = { - STRING_TOKEN(STR_COM_TYPE_0), - STRING_TOKEN(STR_COM_TYPE_1), - STRING_TOKEN(STR_COM_TYPE_2), - STRING_TOKEN(STR_COM_TYPE_3), - STRING_TOKEN(STR_COM_TYPE_4), - STRING_TOKEN(STR_COM_TYPE_5), - STRING_TOKEN(STR_COM_TYPE_6), - STRING_TOKEN(STR_COM_TYPE_7), - STRING_TOKEN(STR_COM_TYPE_8), +UINT16 TerminalType[9] = { + STRING_TOKEN (STR_COM_TYPE_0), + STRING_TOKEN (STR_COM_TYPE_1), + STRING_TOKEN (STR_COM_TYPE_2), + STRING_TOKEN (STR_COM_TYPE_3), + STRING_TOKEN (STR_COM_TYPE_4), + STRING_TOKEN (STR_COM_TYPE_5), + STRING_TOKEN (STR_COM_TYPE_6), + STRING_TOKEN (STR_COM_TYPE_7), + STRING_TOKEN (STR_COM_TYPE_8), }; /// /// Flow Control type string token storage /// -UINT16 mFlowControlType[2] = { - STRING_TOKEN(STR_NONE_FLOW_CONTROL), - STRING_TOKEN(STR_HARDWARE_FLOW_CONTROL) +UINT16 mFlowControlType[2] = { + STRING_TOKEN (STR_NONE_FLOW_CONTROL), + STRING_TOKEN (STR_HARDWARE_FLOW_CONTROL) }; -UINT32 mFlowControlValue[2] = { +UINT32 mFlowControlValue[2] = { 0, UART_FLOW_CONTROL_HARDWARE }; @@ -44,215 +44,215 @@ UINT32 mFlowControlValue[2] = { /// /// Console Input Device Selection Menu /// -BM_MENU_OPTION ConsoleInpMenu = { +BM_MENU_OPTION ConsoleInpMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Console Output Device Selection Menu /// -BM_MENU_OPTION ConsoleOutMenu = { +BM_MENU_OPTION ConsoleOutMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Error Output Device Selection Menu /// -BM_MENU_OPTION ConsoleErrMenu = { +BM_MENU_OPTION ConsoleErrMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Boot Option from variable Menu /// -BM_MENU_OPTION BootOptionMenu = { +BM_MENU_OPTION BootOptionMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Driver Option from variable menu /// -BM_MENU_OPTION DriverOptionMenu = { +BM_MENU_OPTION DriverOptionMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Handles in current system selection menu /// -BM_MENU_OPTION DriverMenu = { +BM_MENU_OPTION DriverMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; -BM_MENU_OPTION TerminalMenu = { +BM_MENU_OPTION TerminalMenu = { BM_MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0 }; /// /// Value and string token correspondency for BaudRate /// -COM_ATTR BaudRateList[19] = { +COM_ATTR BaudRateList[19] = { { 115200, - STRING_TOKEN(STR_COM_BAUD_RATE_0) + STRING_TOKEN (STR_COM_BAUD_RATE_0) }, { 57600, - STRING_TOKEN(STR_COM_BAUD_RATE_1) + STRING_TOKEN (STR_COM_BAUD_RATE_1) }, { 38400, - STRING_TOKEN(STR_COM_BAUD_RATE_2) + STRING_TOKEN (STR_COM_BAUD_RATE_2) }, { 19200, - STRING_TOKEN(STR_COM_BAUD_RATE_3) + STRING_TOKEN (STR_COM_BAUD_RATE_3) }, { 9600, - STRING_TOKEN(STR_COM_BAUD_RATE_4) + STRING_TOKEN (STR_COM_BAUD_RATE_4) }, { 7200, - STRING_TOKEN(STR_COM_BAUD_RATE_5) + STRING_TOKEN (STR_COM_BAUD_RATE_5) }, { 4800, - STRING_TOKEN(STR_COM_BAUD_RATE_6) + STRING_TOKEN (STR_COM_BAUD_RATE_6) }, { 3600, - STRING_TOKEN(STR_COM_BAUD_RATE_7) + STRING_TOKEN (STR_COM_BAUD_RATE_7) }, { 2400, - STRING_TOKEN(STR_COM_BAUD_RATE_8) + STRING_TOKEN (STR_COM_BAUD_RATE_8) }, { 2000, - STRING_TOKEN(STR_COM_BAUD_RATE_9) + STRING_TOKEN (STR_COM_BAUD_RATE_9) }, { 1800, - STRING_TOKEN(STR_COM_BAUD_RATE_10) + STRING_TOKEN (STR_COM_BAUD_RATE_10) }, { 1200, - STRING_TOKEN(STR_COM_BAUD_RATE_11) + STRING_TOKEN (STR_COM_BAUD_RATE_11) }, { 600, - STRING_TOKEN(STR_COM_BAUD_RATE_12) + STRING_TOKEN (STR_COM_BAUD_RATE_12) }, { 300, - STRING_TOKEN(STR_COM_BAUD_RATE_13) + STRING_TOKEN (STR_COM_BAUD_RATE_13) }, { 150, - STRING_TOKEN(STR_COM_BAUD_RATE_14) + STRING_TOKEN (STR_COM_BAUD_RATE_14) }, { 134, - STRING_TOKEN(STR_COM_BAUD_RATE_15) + STRING_TOKEN (STR_COM_BAUD_RATE_15) }, { 110, - STRING_TOKEN(STR_COM_BAUD_RATE_16) + STRING_TOKEN (STR_COM_BAUD_RATE_16) }, { 75, - STRING_TOKEN(STR_COM_BAUD_RATE_17) + STRING_TOKEN (STR_COM_BAUD_RATE_17) }, { 50, - STRING_TOKEN(STR_COM_BAUD_RATE_18) + STRING_TOKEN (STR_COM_BAUD_RATE_18) } }; /// /// Value and string token correspondency for DataBits /// -COM_ATTR DataBitsList[4] = { +COM_ATTR DataBitsList[4] = { { 5, - STRING_TOKEN(STR_COM_DATA_BITS_0) + STRING_TOKEN (STR_COM_DATA_BITS_0) }, { 6, - STRING_TOKEN(STR_COM_DATA_BITS_1) + STRING_TOKEN (STR_COM_DATA_BITS_1) }, { 7, - STRING_TOKEN(STR_COM_DATA_BITS_2) + STRING_TOKEN (STR_COM_DATA_BITS_2) }, { 8, - STRING_TOKEN(STR_COM_DATA_BITS_3) + STRING_TOKEN (STR_COM_DATA_BITS_3) } }; /// /// Value and string token correspondency for Parity /// -COM_ATTR ParityList[5] = { +COM_ATTR ParityList[5] = { { NoParity, - STRING_TOKEN(STR_COM_PAR_0) + STRING_TOKEN (STR_COM_PAR_0) }, { EvenParity, - STRING_TOKEN(STR_COM_PAR_1) + STRING_TOKEN (STR_COM_PAR_1) }, { OddParity, - STRING_TOKEN(STR_COM_PAR_2) + STRING_TOKEN (STR_COM_PAR_2) }, { MarkParity, - STRING_TOKEN(STR_COM_PAR_3) + STRING_TOKEN (STR_COM_PAR_3) }, { SpaceParity, - STRING_TOKEN(STR_COM_PAR_4) + STRING_TOKEN (STR_COM_PAR_4) } }; /// /// Value and string token correspondency for Baudreate /// -COM_ATTR StopBitsList[3] = { +COM_ATTR StopBitsList[3] = { { OneStopBit, - STRING_TOKEN(STR_COM_STOP_BITS_0) + STRING_TOKEN (STR_COM_STOP_BITS_0) }, { OneFiveStopBits, - STRING_TOKEN(STR_COM_STOP_BITS_1) + STRING_TOKEN (STR_COM_STOP_BITS_1) }, { TwoStopBits, - STRING_TOKEN(STR_COM_STOP_BITS_2) + STRING_TOKEN (STR_COM_STOP_BITS_2) } }; /// /// Guid for messaging path, used in Serial port setting. /// -EFI_GUID TerminalTypeGuid[9] = { +EFI_GUID TerminalTypeGuid[9] = { DEVICE_PATH_MESSAGING_PC_ANSI, DEVICE_PATH_MESSAGING_VT_100, DEVICE_PATH_MESSAGING_VT_100_PLUS, diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/FormGuid.h b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/FormGuid.h index 3031242923..2bf233423d 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/FormGuid.h +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/FormGuid.h @@ -5,6 +5,7 @@ Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef _FORM_GUID_H_ #define _FORM_GUID_H_ @@ -41,50 +42,48 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define FORM_CON_MODE_ID 0x1021 #define FORM_BOOT_FROM_FILE_ID 0x1024 - -#define MAXIMUM_FORM_ID 0x10FF - -#define KEY_VALUE_COM_SET_BAUD_RATE 0x1101 -#define KEY_VALUE_COM_SET_DATA_BITS 0x1102 -#define KEY_VALUE_COM_SET_STOP_BITS 0x1103 -#define KEY_VALUE_COM_SET_PARITY 0x1104 -#define KEY_VALUE_COM_SET_TERMI_TYPE 0x1105 -#define KEY_VALUE_MAIN_BOOT_NEXT 0x1106 -#define KEY_VALUE_BOOT_ADD_DESC_DATA 0x1107 -#define KEY_VALUE_BOOT_ADD_OPT_DATA 0x1108 -#define KEY_VALUE_DRIVER_ADD_DESC_DATA 0x1109 -#define KEY_VALUE_DRIVER_ADD_OPT_DATA 0x110A -#define KEY_VALUE_SAVE_AND_EXIT 0x110B -#define KEY_VALUE_NO_SAVE_AND_EXIT 0x110C -#define KEY_VALUE_BOOT_FROM_FILE 0x110D -#define FORM_RESET 0x110E -#define KEY_VALUE_BOOT_DESCRIPTION 0x110F -#define KEY_VALUE_BOOT_OPTION 0x1110 -#define KEY_VALUE_DRIVER_DESCRIPTION 0x1111 -#define KEY_VALUE_DRIVER_OPTION 0x1112 -#define KEY_VALUE_SAVE_AND_EXIT_BOOT 0x1113 -#define KEY_VALUE_NO_SAVE_AND_EXIT_BOOT 0x1114 -#define KEY_VALUE_SAVE_AND_EXIT_DRIVER 0x1115 -#define KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER 0x1116 -#define KEY_VALUE_TRIGGER_FORM_OPEN_ACTION 0x1117 - -#define MAXIMUM_NORMAL_KEY_VALUE 0x11FF +#define MAXIMUM_FORM_ID 0x10FF + +#define KEY_VALUE_COM_SET_BAUD_RATE 0x1101 +#define KEY_VALUE_COM_SET_DATA_BITS 0x1102 +#define KEY_VALUE_COM_SET_STOP_BITS 0x1103 +#define KEY_VALUE_COM_SET_PARITY 0x1104 +#define KEY_VALUE_COM_SET_TERMI_TYPE 0x1105 +#define KEY_VALUE_MAIN_BOOT_NEXT 0x1106 +#define KEY_VALUE_BOOT_ADD_DESC_DATA 0x1107 +#define KEY_VALUE_BOOT_ADD_OPT_DATA 0x1108 +#define KEY_VALUE_DRIVER_ADD_DESC_DATA 0x1109 +#define KEY_VALUE_DRIVER_ADD_OPT_DATA 0x110A +#define KEY_VALUE_SAVE_AND_EXIT 0x110B +#define KEY_VALUE_NO_SAVE_AND_EXIT 0x110C +#define KEY_VALUE_BOOT_FROM_FILE 0x110D +#define FORM_RESET 0x110E +#define KEY_VALUE_BOOT_DESCRIPTION 0x110F +#define KEY_VALUE_BOOT_OPTION 0x1110 +#define KEY_VALUE_DRIVER_DESCRIPTION 0x1111 +#define KEY_VALUE_DRIVER_OPTION 0x1112 +#define KEY_VALUE_SAVE_AND_EXIT_BOOT 0x1113 +#define KEY_VALUE_NO_SAVE_AND_EXIT_BOOT 0x1114 +#define KEY_VALUE_SAVE_AND_EXIT_DRIVER 0x1115 +#define KEY_VALUE_NO_SAVE_AND_EXIT_DRIVER 0x1116 +#define KEY_VALUE_TRIGGER_FORM_OPEN_ACTION 0x1117 + +#define MAXIMUM_NORMAL_KEY_VALUE 0x11FF // // Varstore ID defined for Buffer Storage // -#define VARSTORE_ID_BOOT_MAINT 0x1000 +#define VARSTORE_ID_BOOT_MAINT 0x1000 // // End Label // -#define LABEL_FORM_MAIN_START 0xfffc -#define LABEL_FORM_MAIN_END 0xfffd - -#define LABEL_BMM_PLATFORM_INFORMATION 0xfffe -#define LABEL_END 0xffff -#define MAX_MENU_NUMBER 100 +#define LABEL_FORM_MAIN_START 0xfffc +#define LABEL_FORM_MAIN_END 0xfffd +#define LABEL_BMM_PLATFORM_INFORMATION 0xfffe +#define LABEL_END 0xffff +#define MAX_MENU_NUMBER 100 /// /// This is the structure that will be used to store the @@ -99,81 +98,81 @@ typedef struct { // Three questions displayed at the main page // for Timeout, BootNext, Variables respectively // - UINT16 BootTimeOut; - UINT32 BootNext; + UINT16 BootTimeOut; + UINT32 BootNext; // // This is the COM1 Attributes value storage // - UINT8 COM1BaudRate; - UINT8 COM1DataRate; - UINT8 COM1StopBits; - UINT8 COM1Parity; - UINT8 COM1TerminalType; + UINT8 COM1BaudRate; + UINT8 COM1DataRate; + UINT8 COM1StopBits; + UINT8 COM1Parity; + UINT8 COM1TerminalType; // // This is the COM2 Attributes value storage // - UINT8 COM2BaudRate; - UINT8 COM2DataRate; - UINT8 COM2StopBits; - UINT8 COM2Parity; - UINT8 COM2TerminalType; + UINT8 COM2BaudRate; + UINT8 COM2DataRate; + UINT8 COM2StopBits; + UINT8 COM2Parity; + UINT8 COM2TerminalType; // // Driver Option Add Handle page storage // - UINT16 DriverAddHandleDesc[MAX_MENU_NUMBER]; - UINT16 DriverAddHandleOptionalData[MAX_MENU_NUMBER]; - UINT8 DriverAddActive; - UINT8 DriverAddForceReconnect; + UINT16 DriverAddHandleDesc[MAX_MENU_NUMBER]; + UINT16 DriverAddHandleOptionalData[MAX_MENU_NUMBER]; + UINT8 DriverAddActive; + UINT8 DriverAddForceReconnect; // // Console Input/Output/Errorout using COM port check storage // - UINT8 ConsoleInputCOM1; - UINT8 ConsoleInputCOM2; - UINT8 ConsoleOutputCOM1; - UINT8 ConsoleOutputCOM2; - UINT8 ConsoleErrorCOM1; - UINT8 ConsoleErrorCOM2; + UINT8 ConsoleInputCOM1; + UINT8 ConsoleInputCOM2; + UINT8 ConsoleOutputCOM1; + UINT8 ConsoleOutputCOM2; + UINT8 ConsoleErrorCOM1; + UINT8 ConsoleErrorCOM2; // // At most 100 input/output/errorout device for console storage // - UINT8 ConsoleCheck[MAX_MENU_NUMBER]; + UINT8 ConsoleCheck[MAX_MENU_NUMBER]; // // At most 100 input/output/errorout device for console storage // - UINT8 ConsoleInCheck[MAX_MENU_NUMBER]; - UINT8 ConsoleOutCheck[MAX_MENU_NUMBER]; - UINT8 ConsoleErrCheck[MAX_MENU_NUMBER]; + UINT8 ConsoleInCheck[MAX_MENU_NUMBER]; + UINT8 ConsoleOutCheck[MAX_MENU_NUMBER]; + UINT8 ConsoleErrCheck[MAX_MENU_NUMBER]; // // Boot or Driver Option Order storage // The value is the OptionNumber+1 because the order list value cannot be 0 // Use UINT32 to hold the potential value 0xFFFF+1=0x10000 // - UINT32 BootOptionOrder[MAX_MENU_NUMBER]; - UINT32 DriverOptionOrder[MAX_MENU_NUMBER]; + UINT32 BootOptionOrder[MAX_MENU_NUMBER]; + UINT32 DriverOptionOrder[MAX_MENU_NUMBER]; // // Boot or Driver Option Delete storage // - BOOLEAN BootOptionDel[MAX_MENU_NUMBER]; - BOOLEAN DriverOptionDel[MAX_MENU_NUMBER]; - BOOLEAN BootOptionDelMark[MAX_MENU_NUMBER]; - BOOLEAN DriverOptionDelMark[MAX_MENU_NUMBER]; + BOOLEAN BootOptionDel[MAX_MENU_NUMBER]; + BOOLEAN DriverOptionDel[MAX_MENU_NUMBER]; + BOOLEAN BootOptionDelMark[MAX_MENU_NUMBER]; + BOOLEAN DriverOptionDelMark[MAX_MENU_NUMBER]; // // This is the Terminal Attributes value storage // - UINT8 COMBaudRate[MAX_MENU_NUMBER]; - UINT8 COMDataRate[MAX_MENU_NUMBER]; - UINT8 COMStopBits[MAX_MENU_NUMBER]; - UINT8 COMParity[MAX_MENU_NUMBER]; - UINT8 COMTerminalType[MAX_MENU_NUMBER]; - UINT8 COMFlowControl[MAX_MENU_NUMBER]; + UINT8 COMBaudRate[MAX_MENU_NUMBER]; + UINT8 COMDataRate[MAX_MENU_NUMBER]; + UINT8 COMStopBits[MAX_MENU_NUMBER]; + UINT8 COMParity[MAX_MENU_NUMBER]; + UINT8 COMTerminalType[MAX_MENU_NUMBER]; + UINT8 COMFlowControl[MAX_MENU_NUMBER]; // // We use DisableMap array to record the enable/disable state of each boot device @@ -181,26 +180,25 @@ typedef struct { // the most left one stands for BBS table item 0, and the most right one stands for item 256 // If the bit is 1, it means the boot device has been disabled. // - UINT8 DisableMap[32]; + UINT8 DisableMap[32]; // // Console Output Text Mode // - UINT16 ConsoleOutMode; + UINT16 ConsoleOutMode; // // UINT16 PadArea[10]; // - UINT16 BootDescriptionData[MAX_MENU_NUMBER]; - UINT16 BootOptionalData[127]; - UINT16 DriverDescriptionData[MAX_MENU_NUMBER]; - UINT16 DriverOptionalData[127]; - BOOLEAN BootOptionChanged; - BOOLEAN DriverOptionChanged; - UINT8 Active; - UINT8 ForceReconnect; + UINT16 BootDescriptionData[MAX_MENU_NUMBER]; + UINT16 BootOptionalData[127]; + UINT16 DriverDescriptionData[MAX_MENU_NUMBER]; + UINT16 DriverOptionalData[127]; + BOOLEAN BootOptionChanged; + BOOLEAN DriverOptionChanged; + UINT8 Active; + UINT8 ForceReconnect; } BMM_FAKE_NV_DATA; #endif - diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/UpdatePage.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/UpdatePage.c index e2b444cc45..ca81b7f352 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/UpdatePage.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/UpdatePage.c @@ -29,13 +29,13 @@ CreateUpdateData ( // // Create Hii Extend Label OpCode as the start opcode // - mStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + mStartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); mStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; // // Create Hii Extend Label OpCode as the end opcode // - mEndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mEndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + mEndLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (mEndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); mEndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; mEndLabel->Number = LABEL_END; } @@ -64,9 +64,8 @@ RefreshUpdateData ( // // Create Hii Extend Label OpCode as the start opcode // - mStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + mStartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (mStartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); mStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; - } /** @@ -78,7 +77,7 @@ RefreshUpdateData ( **/ VOID UpdatePageStart ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { RefreshUpdateData (); @@ -109,7 +108,7 @@ UpdatePageStart ( **/ VOID UpdatePageEnd ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { // @@ -164,8 +163,8 @@ UpdatePageEnd ( **/ VOID CleanUpPage ( - IN UINT16 LabelId, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 LabelId, + IN BMM_CALLBACK_DATA *CallbackData ) { RefreshUpdateData (); @@ -191,11 +190,11 @@ CleanUpPage ( **/ VOID UpdateConCOMPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + UINT16 Index; CallbackData->BmmAskSaveOrNot = TRUE; @@ -210,14 +209,13 @@ UpdateConCOMPage ( NewMenuEntry->DisplayStringToken, STRING_TOKEN (STR_NULL_STRING), EFI_IFR_FLAG_CALLBACK, - (UINT16) (TERMINAL_OPTION_OFFSET + Index) + (UINT16)(TERMINAL_OPTION_OFFSET + Index) ); } UpdatePageEnd (CallbackData); } - /** Create a list of boot option from global BootOptionMenu. It allow user to delete the boot option. @@ -227,12 +225,12 @@ UpdateConCOMPage ( **/ VOID UpdateBootDelPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT16 Index; CallbackData->BmmAskSaveOrNot = TRUE; @@ -240,8 +238,8 @@ UpdateBootDelPage ( ASSERT (BootOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.BootOptionDel) / sizeof (CallbackData->BmmFakeNvData.BootOptionDel[0]))); for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (NewLoadContext->IsLegacy) { continue; } @@ -255,15 +253,15 @@ UpdateBootDelPage ( // deleted, browser maintains old useless info. So clear this info here, and later update this info to browser // through HiiSetBrowserData function. // - CallbackData->BmmFakeNvData.BootOptionDel[Index] = FALSE; + CallbackData->BmmFakeNvData.BootOptionDel[Index] = FALSE; CallbackData->BmmOldFakeNVData.BootOptionDel[Index] = FALSE; } HiiCreateCheckBoxOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (BOOT_OPTION_DEL_QUESTION_ID + Index), + (EFI_QUESTION_ID)(BOOT_OPTION_DEL_QUESTION_ID + Index), VARSTORE_ID_BOOT_MAINT, - (UINT16) (BOOT_OPTION_DEL_VAR_OFFSET + Index), + (UINT16)(BOOT_OPTION_DEL_VAR_OFFSET + Index), NewMenuEntry->DisplayStringToken, NewMenuEntry->HelpStringToken, EFI_IFR_FLAG_CALLBACK, @@ -271,6 +269,7 @@ UpdateBootDelPage ( NULL ); } + UpdatePageEnd (CallbackData); } @@ -282,11 +281,11 @@ UpdateBootDelPage ( **/ VOID UpdateDrvAddHandlePage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + UINT16 Index; CallbackData->BmmAskSaveOrNot = FALSE; @@ -301,7 +300,7 @@ UpdateDrvAddHandlePage ( NewMenuEntry->DisplayStringToken, STRING_TOKEN (STR_NULL_STRING), EFI_IFR_FLAG_CALLBACK, - (UINT16) (HANDLE_OPTION_OFFSET + Index) + (UINT16)(HANDLE_OPTION_OFFSET + Index) ); } @@ -317,12 +316,12 @@ UpdateDrvAddHandlePage ( **/ VOID UpdateDrvDelPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + UINT16 Index; CallbackData->BmmAskSaveOrNot = TRUE; @@ -330,9 +329,9 @@ UpdateDrvDelPage ( ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.DriverOptionDel) / sizeof (CallbackData->BmmFakeNvData.DriverOptionDel[0]))); for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index); + NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, Index); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; NewLoadContext->Deleted = FALSE; if (CallbackData->BmmFakeNvData.DriverOptionDel[Index] && !CallbackData->BmmFakeNvData.DriverOptionDelMark[Index]) { @@ -342,14 +341,15 @@ UpdateDrvDelPage ( // deleted, browser maintains old useless info. So clear this info here, and later update this info to browser // through HiiSetBrowserData function. // - CallbackData->BmmFakeNvData.DriverOptionDel[Index] = FALSE; + CallbackData->BmmFakeNvData.DriverOptionDel[Index] = FALSE; CallbackData->BmmOldFakeNVData.DriverOptionDel[Index] = FALSE; } + HiiCreateCheckBoxOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (DRIVER_OPTION_DEL_QUESTION_ID + Index), + (EFI_QUESTION_ID)(DRIVER_OPTION_DEL_QUESTION_ID + Index), VARSTORE_ID_BOOT_MAINT, - (UINT16) (DRIVER_OPTION_DEL_VAR_OFFSET + Index), + (UINT16)(DRIVER_OPTION_DEL_VAR_OFFSET + Index), NewMenuEntry->DisplayStringToken, NewMenuEntry->HelpStringToken, EFI_IFR_FLAG_CALLBACK, @@ -370,15 +370,15 @@ UpdateDrvDelPage ( **/ VOID UpdateDriverAddHandleDescPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; + BM_MENU_ENTRY *NewMenuEntry; - CallbackData->BmmFakeNvData.DriverAddActive = 0x01; - CallbackData->BmmFakeNvData.DriverAddForceReconnect = 0x00; - CallbackData->BmmAskSaveOrNot = TRUE; - NewMenuEntry = CallbackData->MenuEntry; + CallbackData->BmmFakeNvData.DriverAddActive = 0x01; + CallbackData->BmmFakeNvData.DriverAddForceReconnect = 0x00; + CallbackData->BmmAskSaveOrNot = TRUE; + NewMenuEntry = CallbackData->MenuEntry; UpdatePageStart (CallbackData); @@ -392,7 +392,7 @@ UpdateDriverAddHandleDescPage ( HiiCreateStringOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) DRV_ADD_HANDLE_DESC_QUESTION_ID, + (EFI_QUESTION_ID)DRV_ADD_HANDLE_DESC_QUESTION_ID, VARSTORE_ID_BOOT_MAINT, DRV_ADD_HANDLE_DESC_VAR_OFFSET, STRING_TOKEN (STR_LOAD_OPTION_DESC), @@ -406,7 +406,7 @@ UpdateDriverAddHandleDescPage ( HiiCreateCheckBoxOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) DRV_ADD_RECON_QUESTION_ID, + (EFI_QUESTION_ID)DRV_ADD_RECON_QUESTION_ID, VARSTORE_ID_BOOT_MAINT, DRV_ADD_RECON_VAR_OFFSET, STRING_TOKEN (STR_LOAD_OPTION_FORCE_RECON), @@ -418,7 +418,7 @@ UpdateDriverAddHandleDescPage ( HiiCreateStringOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) DRIVER_ADD_OPTION_QUESTION_ID, + (EFI_QUESTION_ID)DRIVER_ADD_OPTION_QUESTION_ID, VARSTORE_ID_BOOT_MAINT, DRIVER_ADD_OPTION_VAR_OFFSET, STRING_TOKEN (STR_OPTIONAL_DATA), @@ -443,20 +443,20 @@ UpdateDriverAddHandleDescPage ( **/ VOID UpdateConsolePage ( - IN UINT16 UpdatePageId, - IN BM_MENU_OPTION *ConsoleMenu, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 UpdatePageId, + IN BM_MENU_OPTION *ConsoleMenu, + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_CONSOLE_CONTEXT *NewConsoleContext; - BM_TERMINAL_CONTEXT *NewTerminalContext; - UINT16 Index; - UINT16 Index2; - UINT8 CheckFlags; - UINT8 *ConsoleCheck; - EFI_QUESTION_ID QuestionIdBase; - UINT16 VariableOffsetBase; + BM_MENU_ENTRY *NewMenuEntry; + BM_CONSOLE_CONTEXT *NewConsoleContext; + BM_TERMINAL_CONTEXT *NewTerminalContext; + UINT16 Index; + UINT16 Index2; + UINT8 CheckFlags; + UINT8 *ConsoleCheck; + EFI_QUESTION_ID QuestionIdBase; + UINT16 VariableOffsetBase; CallbackData->BmmAskSaveOrNot = TRUE; @@ -467,42 +467,45 @@ UpdateConsolePage ( VariableOffsetBase = 0; switch (UpdatePageId) { - case FORM_CON_IN_ID: - ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleInCheck[0]; - QuestionIdBase = CON_IN_DEVICE_QUESTION_ID; - VariableOffsetBase = CON_IN_DEVICE_VAR_OFFSET; - break; - - case FORM_CON_OUT_ID: - ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleOutCheck[0]; - QuestionIdBase = CON_OUT_DEVICE_QUESTION_ID; - VariableOffsetBase = CON_OUT_DEVICE_VAR_OFFSET; - break; - - case FORM_CON_ERR_ID: - ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleErrCheck[0]; - QuestionIdBase = CON_ERR_DEVICE_QUESTION_ID; - VariableOffsetBase = CON_ERR_DEVICE_VAR_OFFSET; - break; + case FORM_CON_IN_ID: + ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleInCheck[0]; + QuestionIdBase = CON_IN_DEVICE_QUESTION_ID; + VariableOffsetBase = CON_IN_DEVICE_VAR_OFFSET; + break; + + case FORM_CON_OUT_ID: + ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleOutCheck[0]; + QuestionIdBase = CON_OUT_DEVICE_QUESTION_ID; + VariableOffsetBase = CON_OUT_DEVICE_VAR_OFFSET; + break; + + case FORM_CON_ERR_ID: + ConsoleCheck = &CallbackData->BmmFakeNvData.ConsoleErrCheck[0]; + QuestionIdBase = CON_ERR_DEVICE_QUESTION_ID; + VariableOffsetBase = CON_ERR_DEVICE_VAR_OFFSET; + break; } + ASSERT (ConsoleCheck != NULL); for (Index = 0; ((Index < ConsoleMenu->MenuNumber) && \ - (Index < MAX_MENU_NUMBER)) ; Index++) { - CheckFlags = 0; - NewMenuEntry = BOpt_GetMenuEntry (ConsoleMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; + (Index < MAX_MENU_NUMBER)); Index++) + { + CheckFlags = 0; + NewMenuEntry = BOpt_GetMenuEntry (ConsoleMenu, Index); + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; if (NewConsoleContext->IsActive) { - CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT; + CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT; ConsoleCheck[Index] = TRUE; } else { ConsoleCheck[Index] = FALSE; } + HiiCreateCheckBoxOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (QuestionIdBase + Index), + (EFI_QUESTION_ID)(QuestionIdBase + Index), VARSTORE_ID_BOOT_MAINT, - (UINT16) (VariableOffsetBase + Index), + (UINT16)(VariableOffsetBase + Index), NewMenuEntry->DisplayStringToken, NewMenuEntry->HelpStringToken, EFI_IFR_FLAG_CALLBACK, @@ -512,26 +515,29 @@ UpdateConsolePage ( } for (Index2 = 0; ((Index2 < TerminalMenu.MenuNumber) && \ - (Index2 < MAX_MENU_NUMBER)); Index2++) { - CheckFlags = 0; - NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index2); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + (Index2 < MAX_MENU_NUMBER)); Index2++) + { + CheckFlags = 0; + NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index2); + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; ASSERT (Index < MAX_MENU_NUMBER); if (((NewTerminalContext->IsConIn != 0) && (UpdatePageId == FORM_CON_IN_ID)) || ((NewTerminalContext->IsConOut != 0) && (UpdatePageId == FORM_CON_OUT_ID)) || ((NewTerminalContext->IsStdErr != 0) && (UpdatePageId == FORM_CON_ERR_ID)) - ) { - CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT; + ) + { + CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT; ConsoleCheck[Index] = TRUE; } else { ConsoleCheck[Index] = FALSE; } + HiiCreateCheckBoxOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (QuestionIdBase + Index), + (EFI_QUESTION_ID)(QuestionIdBase + Index), VARSTORE_ID_BOOT_MAINT, - (UINT16) (VariableOffsetBase + Index), + (UINT16)(VariableOffsetBase + Index), NewMenuEntry->DisplayStringToken, NewMenuEntry->HelpStringToken, EFI_IFR_FLAG_CALLBACK, @@ -556,58 +562,60 @@ UpdateConsolePage ( **/ VOID UpdateOrderPage ( - IN UINT16 UpdatePageId, - IN BM_MENU_OPTION *OptionMenu, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 UpdatePageId, + IN BM_MENU_OPTION *OptionMenu, + IN BMM_CALLBACK_DATA *CallbackData ) { - BM_MENU_ENTRY *NewMenuEntry; - UINT16 Index; - UINT16 OptionIndex; - VOID *OptionsOpCodeHandle; - BOOLEAN BootOptionFound; - UINT32 *OptionOrder; - EFI_QUESTION_ID QuestionId; - UINT16 VarOffset; + BM_MENU_ENTRY *NewMenuEntry; + UINT16 Index; + UINT16 OptionIndex; + VOID *OptionsOpCodeHandle; + BOOLEAN BootOptionFound; + UINT32 *OptionOrder; + EFI_QUESTION_ID QuestionId; + UINT16 VarOffset; CallbackData->BmmAskSaveOrNot = TRUE; UpdatePageStart (CallbackData); OptionOrder = NULL; - QuestionId = 0; - VarOffset = 0; + QuestionId = 0; + VarOffset = 0; switch (UpdatePageId) { + case FORM_BOOT_CHG_ID: + // + // If the BootOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData, + // means all Boot Options has been save in BootOptionMenu, we can get the date from the menu. + // else means browser maintains some uncommitted date which are not saved in BootOptionMenu, + // so we should not get the data from BootOptionMenu to show it. + // + if (CompareMem (CallbackData->BmmFakeNvData.BootOptionOrder, CallbackData->BmmOldFakeNVData.BootOptionOrder, sizeof (CallbackData->BmmFakeNvData.BootOptionOrder)) == 0) { + GetBootOrder (CallbackData); + } - case FORM_BOOT_CHG_ID: - // - // If the BootOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData, - // means all Boot Options has been save in BootOptionMenu, we can get the date from the menu. - // else means browser maintains some uncommitted date which are not saved in BootOptionMenu, - // so we should not get the data from BootOptionMenu to show it. - // - if (CompareMem (CallbackData->BmmFakeNvData.BootOptionOrder, CallbackData->BmmOldFakeNVData.BootOptionOrder, sizeof (CallbackData->BmmFakeNvData.BootOptionOrder)) == 0) { - GetBootOrder (CallbackData); - } - OptionOrder = CallbackData->BmmFakeNvData.BootOptionOrder; - QuestionId = BOOT_OPTION_ORDER_QUESTION_ID; - VarOffset = BOOT_OPTION_ORDER_VAR_OFFSET; - break; + OptionOrder = CallbackData->BmmFakeNvData.BootOptionOrder; + QuestionId = BOOT_OPTION_ORDER_QUESTION_ID; + VarOffset = BOOT_OPTION_ORDER_VAR_OFFSET; + break; - case FORM_DRV_CHG_ID: - // - // If the DriverOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData, - // means all Driver Options has been save in DriverOptionMenu, we can get the DriverOptionOrder from the menu. - // else means browser maintains some uncommitted date which are not saved in DriverOptionMenu, - // so we should not get the data from DriverOptionMenu to show it. - // - if (CompareMem (CallbackData->BmmFakeNvData.DriverOptionOrder, CallbackData->BmmOldFakeNVData.DriverOptionOrder, sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder)) == 0) { - GetDriverOrder (CallbackData); - } - OptionOrder = CallbackData->BmmFakeNvData.DriverOptionOrder; - QuestionId = DRIVER_OPTION_ORDER_QUESTION_ID; - VarOffset = DRIVER_OPTION_ORDER_VAR_OFFSET; - break; + case FORM_DRV_CHG_ID: + // + // If the DriverOptionOrder in the BmmFakeNvData are same with the date in the BmmOldFakeNVData, + // means all Driver Options has been save in DriverOptionMenu, we can get the DriverOptionOrder from the menu. + // else means browser maintains some uncommitted date which are not saved in DriverOptionMenu, + // so we should not get the data from DriverOptionMenu to show it. + // + if (CompareMem (CallbackData->BmmFakeNvData.DriverOptionOrder, CallbackData->BmmOldFakeNVData.DriverOptionOrder, sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder)) == 0) { + GetDriverOrder (CallbackData); + } + + OptionOrder = CallbackData->BmmFakeNvData.DriverOptionOrder; + QuestionId = DRIVER_OPTION_ORDER_QUESTION_ID; + VarOffset = DRIVER_OPTION_ORDER_VAR_OFFSET; + break; } + ASSERT (OptionOrder != NULL); OptionsOpCodeHandle = HiiAllocateOpCodeHandle (); @@ -617,12 +625,13 @@ UpdateOrderPage ( for (OptionIndex = 0; (OptionOrder[OptionIndex] != 0 && OptionIndex < MAX_MENU_NUMBER); OptionIndex++) { BootOptionFound = FALSE; for (Index = 0; Index < OptionMenu->MenuNumber; Index++) { - NewMenuEntry = BOpt_GetMenuEntry (OptionMenu, Index); - if ((UINT32) (NewMenuEntry->OptionNumber + 1) == OptionOrder[OptionIndex]) { + NewMenuEntry = BOpt_GetMenuEntry (OptionMenu, Index); + if ((UINT32)(NewMenuEntry->OptionNumber + 1) == OptionOrder[OptionIndex]) { BootOptionFound = TRUE; break; } } + if (BootOptionFound) { HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, @@ -654,7 +663,6 @@ UpdateOrderPage ( HiiFreeOpCodeHandle (OptionsOpCodeHandle); UpdatePageEnd (CallbackData); - } /** @@ -665,26 +673,26 @@ UpdateOrderPage ( **/ VOID UpdateConModePage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINTN Mode; - UINTN Index; - UINTN Col; - UINTN Row; - CHAR16 ModeString[50]; - CHAR16 *PStr; - UINTN MaxMode; - UINTN ValidMode; - EFI_STRING_ID *ModeToken; - EFI_STATUS Status; - VOID *OptionsOpCodeHandle; + UINTN Mode; + UINTN Index; + UINTN Col; + UINTN Row; + CHAR16 ModeString[50]; + CHAR16 *PStr; + UINTN MaxMode; + UINTN ValidMode; + EFI_STRING_ID *ModeToken; + EFI_STATUS Status; + VOID *OptionsOpCodeHandle; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut; ConOut = gST->ConOut; Index = 0; ValidMode = 0; - MaxMode = (UINTN) (ConOut->Mode->MaxMode); + MaxMode = (UINTN)(ConOut->Mode->MaxMode); CallbackData->BmmAskSaveOrNot = TRUE; @@ -698,6 +706,7 @@ UpdateConModePage ( if (EFI_ERROR (Status)) { continue; } + ValidMode++; } @@ -708,8 +717,8 @@ UpdateConModePage ( OptionsOpCodeHandle = HiiAllocateOpCodeHandle (); ASSERT (OptionsOpCodeHandle != NULL); - ModeToken = AllocateZeroPool (sizeof (EFI_STRING_ID) * ValidMode); - ASSERT(ModeToken != NULL); + ModeToken = AllocateZeroPool (sizeof (EFI_STRING_ID) * ValidMode); + ASSERT (ModeToken != NULL); // // Determin which mode should be the first entry in menu @@ -730,7 +739,7 @@ UpdateConModePage ( // UnicodeValueToStringS (ModeString, sizeof (ModeString), 0, Col, 0); PStr = &ModeString[0]; - StrnCatS (PStr, ARRAY_SIZE (ModeString), L" x ", StrLen(L" x ") + 1); + StrnCatS (PStr, ARRAY_SIZE (ModeString), L" x ", StrLen (L" x ") + 1); PStr = PStr + StrLen (PStr); UnicodeValueToStringS ( PStr, @@ -748,7 +757,7 @@ UpdateConModePage ( ModeToken[Index], EFI_IFR_OPTION_DEFAULT, EFI_IFR_TYPE_NUM_SIZE_16, - (UINT16) Mode + (UINT16)Mode ); } else { HiiCreateOneOfOptionOpCode ( @@ -756,15 +765,16 @@ UpdateConModePage ( ModeToken[Index], 0, EFI_IFR_TYPE_NUM_SIZE_16, - (UINT16) Mode + (UINT16)Mode ); } + Index++; } HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) CON_MODE_QUESTION_ID, + (EFI_QUESTION_ID)CON_MODE_QUESTION_ID, VARSTORE_ID_BOOT_MAINT, CON_MODE_VAR_OFFSET, STRING_TOKEN (STR_CON_MODE_SETUP), @@ -781,46 +791,47 @@ UpdateConModePage ( UpdatePageEnd (CallbackData); } - /** - Create the dynamic page which allows user to set the property such as Baud Rate, Data Bits, - Parity, Stop Bits, Terminal Type. +/** + Create the dynamic page which allows user to set the property such as Baud Rate, Data Bits, + Parity, Stop Bits, Terminal Type. - @param CallbackData The BMM context data. + @param CallbackData The BMM context data. **/ VOID UpdateTerminalPage ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINT8 Index; - UINT8 CheckFlags; - BM_MENU_ENTRY *NewMenuEntry; - VOID *OptionsOpCodeHandle; - UINTN CurrentTerminal; + UINT8 Index; + UINT8 CheckFlags; + BM_MENU_ENTRY *NewMenuEntry; + VOID *OptionsOpCodeHandle; + UINTN CurrentTerminal; CallbackData->BmmAskSaveOrNot = TRUE; UpdatePageStart (CallbackData); CurrentTerminal = CallbackData->CurrentTerminal; - NewMenuEntry = BOpt_GetMenuEntry ( - &TerminalMenu, - CurrentTerminal - ); + NewMenuEntry = BOpt_GetMenuEntry ( + &TerminalMenu, + CurrentTerminal + ); if (NewMenuEntry == NULL) { - return ; + return; } OptionsOpCodeHandle = HiiAllocateOpCodeHandle (); ASSERT (OptionsOpCodeHandle != NULL); - for (Index = 0; Index < sizeof (BaudRateList) / sizeof (BaudRateList [0]); Index++) { + for (Index = 0; Index < sizeof (BaudRateList) / sizeof (BaudRateList[0]); Index++) { CheckFlags = 0; if (BaudRateList[Index].Value == 115200) { CheckFlags |= EFI_IFR_OPTION_DEFAULT; } + HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, BaudRateList[Index].StringToken, @@ -832,9 +843,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_BAUD_RATE_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_BAUD_RATE_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_BAUD_RATE_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_BAUD_RATE_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_BAUD_RATE), STRING_TOKEN (STR_COM_BAUD_RATE), EFI_IFR_FLAG_CALLBACK, @@ -865,9 +876,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_DATA_RATE_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_DATA_RATE_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_DATA_RATE_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_DATA_RATE_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_DATA_BITS), STRING_TOKEN (STR_COM_DATA_BITS), EFI_IFR_FLAG_CALLBACK, @@ -897,9 +908,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_PARITY_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_PARITY_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_PARITY_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_PARITY_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_PARITY), STRING_TOKEN (STR_COM_PARITY), EFI_IFR_FLAG_CALLBACK, @@ -929,9 +940,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_STOP_BITS_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_STOP_BITS_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_STOP_BITS_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_STOP_BITS_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_STOP_BITS), STRING_TOKEN (STR_COM_STOP_BITS), EFI_IFR_FLAG_CALLBACK, @@ -952,7 +963,7 @@ UpdateTerminalPage ( HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, - (EFI_STRING_ID) TerminalType[Index], + (EFI_STRING_ID)TerminalType[Index], CheckFlags, EFI_IFR_TYPE_NUM_SIZE_8, Index @@ -961,9 +972,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_TERMINAL_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_TERMINAL_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_TERMINAL_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_TERMINAL_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_TERMI_TYPE), STRING_TOKEN (STR_COM_TERMI_TYPE), EFI_IFR_FLAG_CALLBACK, @@ -977,13 +988,14 @@ UpdateTerminalPage ( ASSERT (OptionsOpCodeHandle != NULL); for (Index = 0; Index < ARRAY_SIZE (mFlowControlType); Index++) { - CheckFlags = 0; + CheckFlags = 0; if (Index == 0) { CheckFlags |= EFI_IFR_OPTION_DEFAULT; } + HiiCreateOneOfOptionOpCode ( OptionsOpCodeHandle, - (EFI_STRING_ID) mFlowControlType[Index], + (EFI_STRING_ID)mFlowControlType[Index], CheckFlags, EFI_IFR_TYPE_NUM_SIZE_8, mFlowControlValue[Index] @@ -992,9 +1004,9 @@ UpdateTerminalPage ( HiiCreateOneOfOpCode ( mStartOpCodeHandle, - (EFI_QUESTION_ID) (COM_FLOWCONTROL_QUESTION_ID + CurrentTerminal), + (EFI_QUESTION_ID)(COM_FLOWCONTROL_QUESTION_ID + CurrentTerminal), VARSTORE_ID_BOOT_MAINT, - (UINT16) (COM_FLOWCONTROL_VAR_OFFSET + CurrentTerminal), + (UINT16)(COM_FLOWCONTROL_VAR_OFFSET + CurrentTerminal), STRING_TOKEN (STR_COM_FLOW_CONTROL), STRING_TOKEN (STR_COM_FLOW_CONTROL), EFI_IFR_FLAG_CALLBACK, @@ -1017,20 +1029,21 @@ Update add boot/driver option page. **/ VOID -UpdateOptionPage( - IN BMM_CALLBACK_DATA *CallbackData, - IN EFI_FORM_ID FormId, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath +UpdateOptionPage ( + IN BMM_CALLBACK_DATA *CallbackData, + IN EFI_FORM_ID FormId, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - CHAR16 *String; - EFI_STRING_ID StringToken; + CHAR16 *String; + EFI_STRING_ID StringToken; String = NULL; - if (DevicePath != NULL){ - String = ExtractFileNameFromDevicePath(DevicePath); + if (DevicePath != NULL) { + String = ExtractFileNameFromDevicePath (DevicePath); } + if (String == NULL) { String = HiiGetString (CallbackData->BmmHiiHandle, STRING_TOKEN (STR_NULL_STRING), NULL); ASSERT (String != NULL); @@ -1039,14 +1052,14 @@ UpdateOptionPage( StringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, String, NULL); FreePool (String); - if(FormId == FORM_BOOT_ADD_ID){ + if (FormId == FORM_BOOT_ADD_ID) { if (!CallbackData->BmmFakeNvData.BootOptionChanged) { ZeroMem (CallbackData->BmmFakeNvData.BootOptionalData, sizeof (CallbackData->BmmFakeNvData.BootOptionalData)); ZeroMem (CallbackData->BmmFakeNvData.BootDescriptionData, sizeof (CallbackData->BmmFakeNvData.BootDescriptionData)); ZeroMem (CallbackData->BmmOldFakeNVData.BootOptionalData, sizeof (CallbackData->BmmOldFakeNVData.BootOptionalData)); ZeroMem (CallbackData->BmmOldFakeNVData.BootDescriptionData, sizeof (CallbackData->BmmOldFakeNVData.BootDescriptionData)); } - } else if (FormId == FORM_DRV_ADD_FILE_ID){ + } else if (FormId == FORM_DRV_ADD_FILE_ID) { if (!CallbackData->BmmFakeNvData.DriverOptionChanged) { ZeroMem (CallbackData->BmmFakeNvData.DriverOptionalData, sizeof (CallbackData->BmmFakeNvData.DriverOptionalData)); ZeroMem (CallbackData->BmmFakeNvData.DriverDescriptionData, sizeof (CallbackData->BmmFakeNvData.DriverDescriptionData)); @@ -1055,7 +1068,7 @@ UpdateOptionPage( } } - RefreshUpdateData(); + RefreshUpdateData (); mStartLabel->Number = FormId; HiiCreateSubTitleOpCode ( @@ -1070,8 +1083,8 @@ UpdateOptionPage( CallbackData->BmmHiiHandle, &mBootMaintGuid, FormId, - mStartOpCodeHandle,// Label FormId - mEndOpCodeHandle // LABEL_END + mStartOpCodeHandle, // Label FormId + mEndOpCodeHandle // LABEL_END ); } @@ -1085,34 +1098,34 @@ UpdateOptionPage( **/ VOID UpdatePageBody ( - IN UINT16 UpdatePageId, - IN BMM_CALLBACK_DATA *CallbackData + IN UINT16 UpdatePageId, + IN BMM_CALLBACK_DATA *CallbackData ) { CleanUpPage (UpdatePageId, CallbackData); switch (UpdatePageId) { - case FORM_CON_IN_ID: - UpdateConsolePage (UpdatePageId, &ConsoleInpMenu, CallbackData); - break; + case FORM_CON_IN_ID: + UpdateConsolePage (UpdatePageId, &ConsoleInpMenu, CallbackData); + break; - case FORM_CON_OUT_ID: - UpdateConsolePage (UpdatePageId, &ConsoleOutMenu, CallbackData); - break; + case FORM_CON_OUT_ID: + UpdateConsolePage (UpdatePageId, &ConsoleOutMenu, CallbackData); + break; - case FORM_CON_ERR_ID: - UpdateConsolePage (UpdatePageId, &ConsoleErrMenu, CallbackData); - break; + case FORM_CON_ERR_ID: + UpdateConsolePage (UpdatePageId, &ConsoleErrMenu, CallbackData); + break; - case FORM_BOOT_CHG_ID: - UpdateOrderPage (UpdatePageId, &BootOptionMenu, CallbackData); - break; + case FORM_BOOT_CHG_ID: + UpdateOrderPage (UpdatePageId, &BootOptionMenu, CallbackData); + break; - case FORM_DRV_CHG_ID: - UpdateOrderPage (UpdatePageId, &DriverOptionMenu, CallbackData); - break; + case FORM_DRV_CHG_ID: + UpdateOrderPage (UpdatePageId, &DriverOptionMenu, CallbackData); + break; - default: - break; + default: + break; } } @@ -1125,8 +1138,8 @@ UpdatePageBody ( **/ VOID UpdatePageId ( - BMM_CALLBACK_DATA *Private, - UINT16 NewPageId + BMM_CALLBACK_DATA *Private, + UINT16 NewPageId ) { if ((NewPageId < FILE_OPTION_OFFSET) && (NewPageId >= HANDLE_OPTION_OFFSET)) { @@ -1144,7 +1157,7 @@ UpdatePageId ( } if ((NewPageId > 0) && (NewPageId < MAXIMUM_FORM_ID)) { - Private->BmmPreviousPageId = Private->BmmCurrentPageId; - Private->BmmCurrentPageId = NewPageId; + Private->BmmPreviousPageId = Private->BmmCurrentPageId; + Private->BmmCurrentPageId = NewPageId; } } diff --git a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Variable.c b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Variable.c index e28f76b8de..82a0ed66a7 100644 --- a/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Variable.c +++ b/MdeModulePkg/Library/BootMaintenanceManagerUiLib/Variable.c @@ -22,28 +22,29 @@ Var_DelBootOption ( VOID ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - EFI_STATUS Status; - UINTN Index; - UINTN Index2; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + EFI_STATUS Status; + UINTN Index; + UINTN Index2; - Index2 = 0; + Index2 = 0; for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, (Index - Index2)); if (NULL == NewMenuEntry) { return EFI_NOT_FOUND; } - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (!NewLoadContext->Deleted) { continue; } - Status = EfiBootManagerDeleteLoadOptionVariable (NewMenuEntry->OptionNumber,LoadOptionTypeBoot); + Status = EfiBootManagerDeleteLoadOptionVariable (NewMenuEntry->OptionNumber, LoadOptionTypeBoot); if (EFI_ERROR (Status)) { - return Status; + return Status; } + Index2++; // // If current Load Option is the same as BootNext, @@ -78,24 +79,25 @@ Var_DelDriverOption ( VOID ) { - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - EFI_STATUS Status; - UINTN Index; - UINTN Index2; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + EFI_STATUS Status; + UINTN Index; + UINTN Index2; - Index2 = 0; + Index2 = 0; for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (&DriverOptionMenu, (Index - Index2)); if (NULL == NewMenuEntry) { return EFI_NOT_FOUND; } - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; if (!NewLoadContext->Deleted) { continue; } - Status = EfiBootManagerDeleteLoadOptionVariable (NewMenuEntry->OptionNumber,LoadOptionTypeDriver); + + Status = EfiBootManagerDeleteLoadOptionVariable (NewMenuEntry->OptionNumber, LoadOptionTypeDriver); if (EFI_ERROR (Status)) { return Status; } @@ -136,9 +138,9 @@ Var_DelDriverOption ( **/ EFI_STATUS Var_UpdateConsoleOption ( - IN UINT16 *ConsoleName, - IN BM_MENU_OPTION *ConsoleMenu, - IN UINT16 UpdatePageId + IN UINT16 *ConsoleName, + IN BM_MENU_OPTION *ConsoleMenu, + IN UINT16 UpdatePageId ) { EFI_DEVICE_PATH_PROTOCOL *ConDevicePath; @@ -150,12 +152,12 @@ Var_UpdateConsoleOption ( EFI_DEVICE_PATH_PROTOCOL *TerminalDevicePath; UINTN Index; - GetEfiGlobalVariable2 (ConsoleName, (VOID**)&ConDevicePath, NULL); + GetEfiGlobalVariable2 (ConsoleName, (VOID **)&ConDevicePath, NULL); if (ConDevicePath != NULL) { EfiLibDeleteVariable (ConsoleName, &gEfiGlobalVariableGuid); FreePool (ConDevicePath); ConDevicePath = NULL; - }; + } // // First add all console input device from console input menu @@ -163,7 +165,7 @@ Var_UpdateConsoleOption ( for (Index = 0; Index < ConsoleMenu->MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (ConsoleMenu, Index); - NewConsoleContext = (BM_CONSOLE_CONTEXT *) NewMenuEntry->VariableContext; + NewConsoleContext = (BM_CONSOLE_CONTEXT *)NewMenuEntry->VariableContext; if (NewConsoleContext->IsActive) { ConDevicePath = AppendDevicePathInstance ( ConDevicePath, @@ -175,11 +177,12 @@ Var_UpdateConsoleOption ( for (Index = 0; Index < TerminalMenu.MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (&TerminalMenu, Index); - NewTerminalContext = (BM_TERMINAL_CONTEXT *) NewMenuEntry->VariableContext; + NewTerminalContext = (BM_TERMINAL_CONTEXT *)NewMenuEntry->VariableContext; if (((NewTerminalContext->IsConIn != 0) && (UpdatePageId == FORM_CON_IN_ID)) || ((NewTerminalContext->IsConOut != 0) && (UpdatePageId == FORM_CON_OUT_ID)) || ((NewTerminalContext->IsStdErr != 0) && (UpdatePageId == FORM_CON_ERR_ID)) - ) { + ) + { Vendor.Header.Type = MESSAGING_DEVICE_PATH; Vendor.Header.SubType = MSG_VENDOR_DP; @@ -191,9 +194,9 @@ Var_UpdateConsoleOption ( ); SetDevicePathNodeLength (&Vendor.Header, sizeof (VENDOR_DEVICE_PATH)); TerminalDevicePath = AppendDevicePathNode ( - NewTerminalContext->DevicePath, - (EFI_DEVICE_PATH_PROTOCOL *) &Vendor - ); + NewTerminalContext->DevicePath, + (EFI_DEVICE_PATH_PROTOCOL *)&Vendor + ); ASSERT (TerminalDevicePath != NULL); ChangeTerminalDevicePath (TerminalDevicePath, TRUE); ConDevicePath = AppendDevicePathInstance ( @@ -217,7 +220,6 @@ Var_UpdateConsoleOption ( } return EFI_SUCCESS; - } /** @@ -285,28 +287,28 @@ Var_UpdateErrorOutOption ( **/ EFI_STATUS Var_UpdateDriverOption ( - IN BMM_CALLBACK_DATA *CallbackData, - IN EFI_HII_HANDLE HiiHandle, - IN UINT16 *DescriptionData, - IN UINT16 *OptionalData, - IN UINT8 ForceReconnect + IN BMM_CALLBACK_DATA *CallbackData, + IN EFI_HII_HANDLE HiiHandle, + IN UINT16 *DescriptionData, + IN UINT16 *OptionalData, + IN UINT8 ForceReconnect ) { - UINT16 Index; - UINT16 DriverString[12]; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - BOOLEAN OptionalDataExist; - EFI_STATUS Status; + UINT16 Index; + UINT16 DriverString[12]; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + BOOLEAN OptionalDataExist; + EFI_STATUS Status; EFI_BOOT_MANAGER_LOAD_OPTION LoadOption; UINT8 *OptionalDesData; UINT32 OptionalDataSize; OptionalDataExist = FALSE; - OptionalDesData = NULL; - OptionalDataSize = 0; + OptionalDesData = NULL; + OptionalDataSize = 0; - Index = BOpt_GetDriverOptionNumber (); + Index = BOpt_GetDriverOptionNumber (); UnicodeSPrint ( DriverString, sizeof (DriverString), @@ -320,8 +322,8 @@ Var_UpdateDriverOption ( if (*OptionalData != 0x0000) { OptionalDataExist = TRUE; - OptionalDesData = (UINT8 *)OptionalData; - OptionalDataSize = (UINT32)StrSize (OptionalData); + OptionalDesData = (UINT8 *)OptionalData; + OptionalDataSize = (UINT32)StrSize (OptionalData); } NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT); @@ -338,20 +340,20 @@ Var_UpdateDriverOption ( CallbackData->LoadContext->FilePathList, OptionalDesData, OptionalDataSize - ); - if (EFI_ERROR (Status)){ + ); + if (EFI_ERROR (Status)) { return Status; } - Status = EfiBootManagerAddLoadOptionVariable (&LoadOption,(UINTN) -1 ); + Status = EfiBootManagerAddLoadOptionVariable (&LoadOption, (UINTN)-1); if (EFI_ERROR (Status)) { - EfiBootManagerFreeLoadOption(&LoadOption); + EfiBootManagerFreeLoadOption (&LoadOption); return Status; } - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - NewLoadContext->Deleted = FALSE; - NewLoadContext->Attributes = LoadOption.Attributes; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + NewLoadContext->Deleted = FALSE; + NewLoadContext->Attributes = LoadOption.Attributes; NewLoadContext->FilePathListLength = (UINT16)GetDevicePathSize (LoadOption.FilePath); NewLoadContext->Description = AllocateZeroPool (StrSize (DescriptionData)); @@ -371,10 +373,10 @@ Var_UpdateDriverOption ( GetDevicePathSize (CallbackData->LoadContext->FilePathList) ); - NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); - NewMenuEntry->OptionNumber = Index; + NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); + NewMenuEntry->OptionNumber = Index; NewMenuEntry->DisplayStringToken = HiiSetString (HiiHandle, 0, NewMenuEntry->DisplayString, NULL); - NewMenuEntry->HelpStringToken = HiiSetString (HiiHandle, 0, NewMenuEntry->HelpString, NULL); + NewMenuEntry->HelpStringToken = HiiSetString (HiiHandle, 0, NewMenuEntry->HelpString, NULL); if (OptionalDataExist) { NewLoadContext->OptionalData = AllocateZeroPool (LoadOption.OptionalDataSize); @@ -389,7 +391,7 @@ Var_UpdateDriverOption ( InsertTailList (&DriverOptionMenu.Head, &NewMenuEntry->Link); DriverOptionMenu.MenuNumber++; - EfiBootManagerFreeLoadOption(&LoadOption); + EfiBootManagerFreeLoadOption (&LoadOption); return EFI_SUCCESS; } @@ -410,26 +412,26 @@ Var_UpdateDriverOption ( **/ EFI_STATUS Var_UpdateBootOption ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { - UINT16 BootString[10]; - UINT16 Index; - BM_MENU_ENTRY *NewMenuEntry; - BM_LOAD_CONTEXT *NewLoadContext; - BOOLEAN OptionalDataExist; - EFI_STATUS Status; - BMM_FAKE_NV_DATA *NvRamMap; + UINT16 BootString[10]; + UINT16 Index; + BM_MENU_ENTRY *NewMenuEntry; + BM_LOAD_CONTEXT *NewLoadContext; + BOOLEAN OptionalDataExist; + EFI_STATUS Status; + BMM_FAKE_NV_DATA *NvRamMap; EFI_BOOT_MANAGER_LOAD_OPTION LoadOption; UINT8 *OptionalData; UINT32 OptionalDataSize; OptionalDataExist = FALSE; - NvRamMap = &CallbackData->BmmFakeNvData; - OptionalData = NULL; - OptionalDataSize = 0; + NvRamMap = &CallbackData->BmmFakeNvData; + OptionalData = NULL; + OptionalDataSize = 0; - Index = BOpt_GetBootOptionNumber () ; + Index = BOpt_GetBootOptionNumber (); UnicodeSPrint (BootString, sizeof (BootString), L"Boot%04x", Index); if (NvRamMap->BootDescriptionData[0] == 0x0000) { @@ -438,8 +440,8 @@ Var_UpdateBootOption ( if (NvRamMap->BootOptionalData[0] != 0x0000) { OptionalDataExist = TRUE; - OptionalData = (UINT8 *)NvRamMap->BootOptionalData; - OptionalDataSize = (UINT32)StrSize (NvRamMap->BootOptionalData); + OptionalData = (UINT8 *)NvRamMap->BootOptionalData; + OptionalDataSize = (UINT32)StrSize (NvRamMap->BootOptionalData); } NewMenuEntry = BOpt_CreateMenuEntry (BM_LOAD_CONTEXT_SELECT); @@ -456,21 +458,21 @@ Var_UpdateBootOption ( CallbackData->LoadContext->FilePathList, OptionalData, OptionalDataSize - ); - if (EFI_ERROR (Status)){ + ); + if (EFI_ERROR (Status)) { return Status; } - Status = EfiBootManagerAddLoadOptionVariable (&LoadOption,(UINTN) -1 ); + Status = EfiBootManagerAddLoadOptionVariable (&LoadOption, (UINTN)-1); if (EFI_ERROR (Status)) { - EfiBootManagerFreeLoadOption(&LoadOption); + EfiBootManagerFreeLoadOption (&LoadOption); return Status; } - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - NewLoadContext->Deleted = FALSE; - NewLoadContext->Attributes = LoadOption.Attributes; - NewLoadContext->FilePathListLength = (UINT16) GetDevicePathSize (LoadOption.FilePath); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + NewLoadContext->Deleted = FALSE; + NewLoadContext->Attributes = LoadOption.Attributes; + NewLoadContext->FilePathListLength = (UINT16)GetDevicePathSize (LoadOption.FilePath); NewLoadContext->Description = AllocateZeroPool (StrSize (NvRamMap->BootDescriptionData)); ASSERT (NewLoadContext->Description != NULL); @@ -491,10 +493,10 @@ Var_UpdateBootOption ( GetDevicePathSize (CallbackData->LoadContext->FilePathList) ); - NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); - NewMenuEntry->OptionNumber = Index; + NewMenuEntry->HelpString = UiDevicePathToStr (NewLoadContext->FilePathList); + NewMenuEntry->OptionNumber = Index; NewMenuEntry->DisplayStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->DisplayString, NULL); - NewMenuEntry->HelpStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->HelpString, NULL); + NewMenuEntry->HelpStringToken = HiiSetString (CallbackData->BmmHiiHandle, 0, NewMenuEntry->HelpString, NULL); if (OptionalDataExist) { NewLoadContext->OptionalData = AllocateZeroPool (LoadOption.OptionalDataSize); @@ -509,7 +511,7 @@ Var_UpdateBootOption ( InsertTailList (&BootOptionMenu.Head, &NewMenuEntry->Link); BootOptionMenu.MenuNumber++; - EfiBootManagerFreeLoadOption(&LoadOption); + EfiBootManagerFreeLoadOption (&LoadOption); return EFI_SUCCESS; } @@ -529,7 +531,7 @@ Var_UpdateBootOption ( **/ EFI_STATUS Var_UpdateBootNext ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { BM_MENU_ENTRY *NewMenuEntry; @@ -538,14 +540,14 @@ Var_UpdateBootNext ( UINT16 Index; EFI_STATUS Status; - Status = EFI_SUCCESS; - CurrentFakeNVMap = &CallbackData->BmmFakeNvData; + Status = EFI_SUCCESS; + CurrentFakeNVMap = &CallbackData->BmmFakeNvData; for (Index = 0; Index < BootOptionMenu.MenuNumber; Index++) { NewMenuEntry = BOpt_GetMenuEntry (&BootOptionMenu, Index); ASSERT (NULL != NewMenuEntry); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - NewLoadContext->IsBootNext = FALSE; + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + NewLoadContext->IsBootNext = FALSE; } if (CurrentFakeNVMap->BootNext == NONE_BOOTNEXT_VALUE) { @@ -554,19 +556,19 @@ Var_UpdateBootNext ( } NewMenuEntry = BOpt_GetMenuEntry ( - &BootOptionMenu, - CurrentFakeNVMap->BootNext - ); + &BootOptionMenu, + CurrentFakeNVMap->BootNext + ); ASSERT (NewMenuEntry != NULL); - NewLoadContext = (BM_LOAD_CONTEXT *) NewMenuEntry->VariableContext; - Status = gRT->SetVariable ( - L"BootNext", - &gEfiGlobalVariableGuid, - VAR_FLAG, - sizeof (UINT16), - &NewMenuEntry->OptionNumber - ); + NewLoadContext = (BM_LOAD_CONTEXT *)NewMenuEntry->VariableContext; + Status = gRT->SetVariable ( + L"BootNext", + &gEfiGlobalVariableGuid, + VAR_FLAG, + sizeof (UINT16), + &NewMenuEntry->OptionNumber + ); NewLoadContext->IsBootNext = TRUE; CallbackData->BmmOldFakeNVData.BootNext = CurrentFakeNVMap->BootNext; return Status; @@ -586,7 +588,7 @@ Var_UpdateBootNext ( **/ EFI_STATUS Var_UpdateBootOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { EFI_STATUS Status; @@ -599,7 +601,7 @@ Var_UpdateBootOrder ( // // First check whether BootOrder is present in current configuration // - GetEfiGlobalVariable2 (L"BootOrder", (VOID **) &BootOrder, &BootOrderSize); + GetEfiGlobalVariable2 (L"BootOrder", (VOID **)&BootOrder, &BootOrderSize); if (BootOrder == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -611,7 +613,7 @@ Var_UpdateBootOrder ( // for (OrderIndex = 0; (OrderIndex < BootOptionMenu.MenuNumber) && (CallbackData->BmmFakeNvData.BootOptionOrder[OrderIndex] != 0); OrderIndex++) { for (Index = OrderIndex; Index < BootOrderSize / sizeof (UINT16); Index++) { - if ((BootOrder[Index] == (UINT16) (CallbackData->BmmFakeNvData.BootOptionOrder[OrderIndex] - 1)) && (OrderIndex != Index)) { + if ((BootOrder[Index] == (UINT16)(CallbackData->BmmFakeNvData.BootOptionOrder[OrderIndex] - 1)) && (OrderIndex != Index)) { OptionNumber = BootOrder[Index]; CopyMem (&BootOrder[OrderIndex + 1], &BootOrder[OrderIndex], (Index - OrderIndex) * sizeof (UINT16)); BootOrder[OrderIndex] = OptionNumber; @@ -632,7 +634,6 @@ Var_UpdateBootOrder ( BOpt_GetBootOptions (CallbackData); return Status; - } /** @@ -649,7 +650,7 @@ Var_UpdateBootOrder ( **/ EFI_STATUS Var_UpdateDriverOrder ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { EFI_STATUS Status; @@ -664,12 +665,13 @@ Var_UpdateDriverOrder ( // // First check whether DriverOrder is present in current configuration // - GetEfiGlobalVariable2 (L"DriverOrder", (VOID **) &DriverOrderList, &DriverOrderListSize); + GetEfiGlobalVariable2 (L"DriverOrder", (VOID **)&DriverOrderList, &DriverOrderListSize); NewDriverOrderList = AllocateZeroPool (DriverOrderListSize); if (NewDriverOrderList == NULL) { return EFI_OUT_OF_RESOURCES; } + // // If exists, delete it to hold new DriverOrder // @@ -680,7 +682,7 @@ Var_UpdateDriverOrder ( ASSERT (DriverOptionMenu.MenuNumber <= (sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder) / sizeof (CallbackData->BmmFakeNvData.DriverOptionOrder[0]))); for (Index = 0; Index < DriverOptionMenu.MenuNumber; Index++) { - NewDriverOrderList[Index] = (UINT16) (CallbackData->BmmFakeNvData.DriverOptionOrder[Index] - 1); + NewDriverOrderList[Index] = (UINT16)(CallbackData->BmmFakeNvData.DriverOptionOrder[Index] - 1); } Status = gRT->SetVariable ( @@ -710,7 +712,7 @@ Var_UpdateDriverOrder ( **/ EFI_STATUS Var_UpdateConMode ( - IN BMM_CALLBACK_DATA *CallbackData + IN BMM_CALLBACK_DATA *CallbackData ) { EFI_STATUS Status; @@ -720,10 +722,10 @@ Var_UpdateConMode ( Mode = CallbackData->BmmFakeNvData.ConsoleOutMode; Status = gST->ConOut->QueryMode (gST->ConOut, Mode, &(ModeInfo.Column), &(ModeInfo.Row)); - if (!EFI_ERROR(Status)) { - Status = PcdSet32S (PcdSetupConOutColumn, (UINT32) ModeInfo.Column); + if (!EFI_ERROR (Status)) { + Status = PcdSet32S (PcdSetupConOutColumn, (UINT32)ModeInfo.Column); if (!EFI_ERROR (Status)) { - Status = PcdSet32S (PcdSetupConOutRow, (UINT32) ModeInfo.Row); + Status = PcdSet32S (PcdSetupConOutRow, (UINT32)ModeInfo.Row); } } diff --git a/MdeModulePkg/Library/BootManagerUiLib/BootManager.c b/MdeModulePkg/Library/BootManagerUiLib/BootManager.c index e378ac52b5..b7526796d6 100644 --- a/MdeModulePkg/Library/BootManagerUiLib/BootManager.c +++ b/MdeModulePkg/Library/BootManagerUiLib/BootManager.c @@ -8,26 +8,26 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "BootManager.h" -UINT16 mKeyInput; -EFI_GUID mBootManagerGuid = BOOT_MANAGER_FORMSET_GUID; +UINT16 mKeyInput; +EFI_GUID mBootManagerGuid = BOOT_MANAGER_FORMSET_GUID; // // Boot video resolution and text mode. // -UINT32 mBmBootHorizontalResolution = 0; -UINT32 mBmBootVerticalResolution = 0; -UINT32 mBmBootTextModeColumn = 0; -UINT32 mBmBootTextModeRow = 0; +UINT32 mBmBootHorizontalResolution = 0; +UINT32 mBmBootVerticalResolution = 0; +UINT32 mBmBootTextModeColumn = 0; +UINT32 mBmBootTextModeRow = 0; // // BIOS setup video resolution and text mode. // -UINT32 mBmSetupTextModeColumn = 0; -UINT32 mBmSetupTextModeRow = 0; -UINT32 mBmSetupHorizontalResolution = 0; -UINT32 mBmSetupVerticalResolution = 0; +UINT32 mBmSetupTextModeColumn = 0; +UINT32 mBmSetupTextModeRow = 0; +UINT32 mBmSetupHorizontalResolution = 0; +UINT32 mBmSetupVerticalResolution = 0; -BOOLEAN mBmModeInitialized = FALSE; +BOOLEAN mBmModeInitialized = FALSE; -CHAR16 *mDeviceTypeStr[] = { +CHAR16 *mDeviceTypeStr[] = { L"Legacy BEV", L"Legacy Floppy", L"Legacy Hard Drive", @@ -44,21 +44,22 @@ HII_VENDOR_DEVICE_PATH mBootManagerHiiVendorDevicePath = { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, // // {1DDDBE15-481D-4d2b-8277-B191EAF66525} // - { 0x1dddbe15, 0x481d, 0x4d2b, { 0x82, 0x77, 0xb1, 0x91, 0xea, 0xf6, 0x65, 0x25 } } + { 0x1dddbe15, 0x481d, 0x4d2b, { 0x82, 0x77, 0xb1, 0x91, 0xea, 0xf6, 0x65, 0x25 } + } }, { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (END_DEVICE_PATH_LENGTH), - (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8) + (UINT8)(END_DEVICE_PATH_LENGTH), + (UINT8)((END_DEVICE_PATH_LENGTH) >> 8) } } }; @@ -116,7 +117,7 @@ BmSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -125,7 +126,7 @@ BmSetConsoleMode ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -154,7 +155,7 @@ BmSetConsoleMode ( } if (GraphicsOutput != NULL) { - MaxGopMode = GraphicsOutput->Mode->MaxMode; + MaxGopMode = GraphicsOutput->Mode->MaxMode; } if (SimpleTextOut != NULL) { @@ -170,22 +171,24 @@ BmSetConsoleMode ( // for (ModeNumber = 0; ModeNumber < MaxGopMode; ModeNumber++) { Status = GraphicsOutput->QueryMode ( - GraphicsOutput, - ModeNumber, - &SizeOfInfo, - &Info - ); + GraphicsOutput, + ModeNumber, + &SizeOfInfo, + &Info + ); if (!EFI_ERROR (Status)) { if ((Info->HorizontalResolution == NewHorizontalResolution) && - (Info->VerticalResolution == NewVerticalResolution)) { + (Info->VerticalResolution == NewVerticalResolution)) + { if ((GraphicsOutput->Mode->Info->HorizontalResolution == NewHorizontalResolution) && - (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) { + (GraphicsOutput->Mode->Info->VerticalResolution == NewVerticalResolution)) + { // // Current resolution is same with required resolution, check if text mode need be set // Status = SimpleTextOut->QueryMode (SimpleTextOut, SimpleTextOut->Mode->Mode, &CurrentColumn, &CurrentRow); ASSERT_EFI_ERROR (Status); - if (CurrentColumn == NewColumns && CurrentRow == NewRows) { + if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // If current text mode is same with required text mode. Do nothing // @@ -197,7 +200,7 @@ BmSetConsoleMode ( // for (Index = 0; Index < MaxTextMode; Index++) { Status = SimpleTextOut->QueryMode (SimpleTextOut, Index, &CurrentColumn, &CurrentRow); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { if ((CurrentColumn == NewColumns) && (CurrentRow == NewRows)) { // // Required text mode is supported, set it. @@ -216,6 +219,7 @@ BmSetConsoleMode ( } } } + if (Index == MaxTextMode) { // // If required text mode is not supported, return error. @@ -236,6 +240,7 @@ BmSetConsoleMode ( } } } + FreePool (Info); } } @@ -266,19 +271,21 @@ BmSetConsoleMode ( // Locate all the handles with GOP protocol and reconnect it. // Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextOutProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextOutProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { gBS->DisconnectController (HandleBuffer[Index], NULL, NULL); } + for (Index = 0; Index < HandleCount; Index++) { gBS->ConnectController (HandleBuffer[Index], NULL, NULL, TRUE); } + if (HandleBuffer != NULL) { FreePool (HandleBuffer); } @@ -297,20 +304,20 @@ BmSetupResetReminder ( VOID ) { - EFI_INPUT_KEY Key; - CHAR16 *StringBuffer1; - CHAR16 *StringBuffer2; - EFI_STATUS Status; - EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL *FormBrowserEx2; + EFI_INPUT_KEY Key; + CHAR16 *StringBuffer1; + CHAR16 *StringBuffer2; + EFI_STATUS Status; + EDKII_FORM_BROWSER_EXTENSION2_PROTOCOL *FormBrowserEx2; // // Use BrowserEx2 protocol to check whether reset is required. // - Status = gBS->LocateProtocol (&gEdkiiFormBrowserEx2ProtocolGuid, NULL, (VOID **) &FormBrowserEx2); + Status = gBS->LocateProtocol (&gEdkiiFormBrowserEx2ProtocolGuid, NULL, (VOID **)&FormBrowserEx2); // - //check any reset required change is applied? if yes, reset system + // check any reset required change is applied? if yes, reset system // - if (!EFI_ERROR(Status) && FormBrowserEx2->IsResetRequired ()) { + if (!EFI_ERROR (Status) && FormBrowserEx2->IsResetRequired ()) { StringBuffer1 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16)); ASSERT (StringBuffer1 != NULL); StringBuffer2 = AllocateZeroPool (MAX_STRING_LEN * sizeof (CHAR16)); @@ -352,20 +359,20 @@ GroupMultipleLegacyBootOption4SameType ( VOID ) { - EFI_STATUS Status; - UINTN Index; - UINTN DeviceIndex; - UINTN DeviceTypeIndex[7]; - UINTN *NextIndex; - UINT16 OptionNumber; - UINT16 *BootOrder; - UINTN BootOrderSize; - CHAR16 OptionName[sizeof ("Boot####")]; - EFI_BOOT_MANAGER_LOAD_OPTION BootOption; + EFI_STATUS Status; + UINTN Index; + UINTN DeviceIndex; + UINTN DeviceTypeIndex[7]; + UINTN *NextIndex; + UINT16 OptionNumber; + UINT16 *BootOrder; + UINTN BootOrderSize; + CHAR16 OptionName[sizeof ("Boot####")]; + EFI_BOOT_MANAGER_LOAD_OPTION BootOption; SetMem (DeviceTypeIndex, sizeof (DeviceTypeIndex), 0xff); - GetEfiGlobalVariable2 (L"BootOrder", (VOID **) &BootOrder, &BootOrderSize); + GetEfiGlobalVariable2 (L"BootOrder", (VOID **)&BootOrder, &BootOrderSize); if (BootOrder == NULL) { return; } @@ -376,15 +383,16 @@ GroupMultipleLegacyBootOption4SameType ( ASSERT_EFI_ERROR (Status); if ((DevicePathType (BootOption.FilePath) == BBS_DEVICE_PATH) && - (DevicePathSubType (BootOption.FilePath) == BBS_BBS_DP)) { + (DevicePathSubType (BootOption.FilePath) == BBS_BBS_DP)) + { // // Legacy Boot Option // DEBUG ((DEBUG_ERROR, "[BootManagerDxe] ==== Find Legacy Boot Option 0x%x! ==== \n", Index)); - ASSERT ((((BBS_BBS_DEVICE_PATH *) BootOption.FilePath)->DeviceType & 0xF) < ARRAY_SIZE (DeviceTypeIndex)); - NextIndex = &DeviceTypeIndex[((BBS_BBS_DEVICE_PATH *) BootOption.FilePath)->DeviceType & 0xF]; + ASSERT ((((BBS_BBS_DEVICE_PATH *)BootOption.FilePath)->DeviceType & 0xF) < ARRAY_SIZE (DeviceTypeIndex)); + NextIndex = &DeviceTypeIndex[((BBS_BBS_DEVICE_PATH *)BootOption.FilePath)->DeviceType & 0xF]; - if (*NextIndex == (UINTN) -1) { + if (*NextIndex == (UINTN)-1) { // // *NextIndex is the Index in BootOrder to put the next Option Number for the same type // @@ -401,12 +409,13 @@ GroupMultipleLegacyBootOption4SameType ( // Update the DeviceTypeIndex array to reflect the right shift operation // for (DeviceIndex = 0; DeviceIndex < ARRAY_SIZE (DeviceTypeIndex); DeviceIndex++) { - if (DeviceTypeIndex[DeviceIndex] != (UINTN) -1 && DeviceTypeIndex[DeviceIndex] >= *NextIndex) { + if ((DeviceTypeIndex[DeviceIndex] != (UINTN)-1) && (DeviceTypeIndex[DeviceIndex] >= *NextIndex)) { DeviceTypeIndex[DeviceIndex]++; } } } } + EfiBootManagerFreeLoadOption (&BootOption); } @@ -430,12 +439,12 @@ GroupMultipleLegacyBootOption4SameType ( **/ CHAR16 * BmDevicePathToStr ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ) { - EFI_STATUS Status; - CHAR16 *ToText; - EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; + EFI_STATUS Status; + CHAR16 *ToText; + EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; if (DevPath == NULL) { return NULL; @@ -444,7 +453,7 @@ BmDevicePathToStr ( Status = gBS->LocateProtocol ( &gEfiDevicePathToTextProtocolGuid, NULL, - (VOID **) &DevPathToText + (VOID **)&DevPathToText ); ASSERT_EFI_ERROR (Status); ToText = DevPathToText->ConvertDevicePathToText ( @@ -485,7 +494,7 @@ UpdateBootManager ( BOOLEAN NeedEndOp; UINTN MaxLen; - DeviceType = (UINT16) -1; + DeviceType = (UINT16)-1; // // for better user experience @@ -516,18 +525,18 @@ UpdateBootManager ( // // Create Hii Extend Label OpCode as the start opcode // - StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + StartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; StartLabel->Number = LABEL_BOOT_OPTION; // // Create Hii Extend Label OpCode as the end opcode // - EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + EndLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; EndLabel->Number = LABEL_BOOT_OPTION_END; - mKeyInput = 0; - NeedEndOp = FALSE; + mKeyInput = 0; + NeedEndOp = FALSE; for (Index = 0; Index < BootOptionCount; Index++) { // // At this stage we are creating a menu entry, thus the Keys are reproduceable @@ -544,28 +553,28 @@ UpdateBootManager ( // // Group the legacy boot option in the sub title created dynamically // - IsLegacyOption = (BOOLEAN) ( - (DevicePathType (BootOption[Index].FilePath) == BBS_DEVICE_PATH) && - (DevicePathSubType (BootOption[Index].FilePath) == BBS_BBS_DP) - ); + IsLegacyOption = (BOOLEAN)( + (DevicePathType (BootOption[Index].FilePath) == BBS_DEVICE_PATH) && + (DevicePathSubType (BootOption[Index].FilePath) == BBS_BBS_DP) + ); if (!IsLegacyOption && NeedEndOp) { NeedEndOp = FALSE; HiiCreateEndOpCode (StartOpCodeHandle); } - if (IsLegacyOption && DeviceType != ((BBS_BBS_DEVICE_PATH *) BootOption[Index].FilePath)->DeviceType) { + if (IsLegacyOption && (DeviceType != ((BBS_BBS_DEVICE_PATH *)BootOption[Index].FilePath)->DeviceType)) { if (NeedEndOp) { HiiCreateEndOpCode (StartOpCodeHandle); } - DeviceType = ((BBS_BBS_DEVICE_PATH *) BootOption[Index].FilePath)->DeviceType; + DeviceType = ((BBS_BBS_DEVICE_PATH *)BootOption[Index].FilePath)->DeviceType; Token = HiiSetString ( HiiHandle, 0, mDeviceTypeStr[ - MIN (DeviceType & 0xF, ARRAY_SIZE (mDeviceTypeStr) - 1) - ], + MIN (DeviceType & 0xF, ARRAY_SIZE (mDeviceTypeStr) - 1) + ], NULL ); HiiCreateSubTitleOpCode (StartOpCodeHandle, Token, 0, 0, 1); @@ -576,10 +585,10 @@ UpdateBootManager ( Token = HiiSetString (HiiHandle, 0, BootOption[Index].Description, NULL); - TempStr = BmDevicePathToStr (BootOption[Index].FilePath); - TempSize = StrSize (TempStr); + TempStr = BmDevicePathToStr (BootOption[Index].FilePath); + TempSize = StrSize (TempStr); HelpString = AllocateZeroPool (TempSize + StrSize (L"Device Path : ")); - MaxLen = (TempSize + StrSize (L"Device Path : "))/sizeof(CHAR16); + MaxLen = (TempSize + StrSize (L"Device Path : "))/sizeof (CHAR16); ASSERT (HelpString != NULL); StrCatS (HelpString, MaxLen, L"Device Path : "); StrCatS (HelpString, MaxLen, TempStr); @@ -639,15 +648,16 @@ UpdateBootManager ( EFI_STATUS EFIAPI BootManagerExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { - if (Progress == NULL || Results == NULL) { + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } + *Progress = Request; return EFI_NOT_FOUND; } @@ -671,12 +681,12 @@ BootManagerExtractConfig ( EFI_STATUS EFIAPI BootManagerRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - if (Configuration == NULL || Progress == NULL) { + if ((Configuration == NULL) || (Progress == NULL)) { return EFI_INVALID_PARAMETER; } @@ -694,11 +704,11 @@ BmInitialBootModeInfo ( VOID ) { - EFI_STATUS Status; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; - EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; - UINTN BootTextColumn; - UINTN BootTextRow; + EFI_STATUS Status; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *SimpleTextOut; + UINTN BootTextColumn; + UINTN BootTextRow; if (mBmModeInitialized) { return; @@ -711,7 +721,7 @@ BmInitialBootModeInfo ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&GraphicsOutput + (VOID **)&GraphicsOutput ); if (EFI_ERROR (Status)) { GraphicsOutput = NULL; @@ -720,7 +730,7 @@ BmInitialBootModeInfo ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiSimpleTextOutProtocolGuid, - (VOID**)&SimpleTextOut + (VOID **)&SimpleTextOut ); if (EFI_ERROR (Status)) { SimpleTextOut = NULL; @@ -753,7 +763,7 @@ BmInitialBootModeInfo ( mBmSetupTextModeColumn = PcdGet32 (PcdSetupConOutColumn); mBmSetupTextModeRow = PcdGet32 (PcdSetupConOutRow); - mBmModeInitialized = TRUE; + mBmModeInitialized = TRUE; } /** @@ -777,26 +787,27 @@ BmInitialBootModeInfo ( EFI_STATUS EFIAPI BootManagerCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - EFI_BOOT_MANAGER_LOAD_OPTION *BootOption; - UINTN BootOptionCount; - EFI_INPUT_KEY Key; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOption; + UINTN BootOptionCount; + EFI_INPUT_KEY Key; if (Action == EFI_BROWSER_ACTION_FORM_OPEN) { // - //Means enter the boot manager form. - //Update the boot manage page,because the boot option may changed. + // Means enter the boot manager form. + // Update the boot manage page,because the boot option may changed. // - if (QuestionId == 0x1212){ - UpdateBootManager(); + if (QuestionId == 0x1212) { + UpdateBootManager (); } + return EFI_SUCCESS; } @@ -820,7 +831,7 @@ BootManagerCallback ( gST->ConOut->ClearScreen (gST->ConOut); // - //check any reset required change is applied? if yes, reset system + // check any reset required change is applied? if yes, reset system // BmSetupResetReminder (); @@ -833,9 +844,9 @@ BootManagerCallback ( if (EFI_ERROR (BootOption[QuestionId - 1].Status)) { gST->ConOut->OutputString ( - gST->ConOut, - HiiGetString (gBootManagerPrivate.HiiHandle, STRING_TOKEN (STR_ANY_KEY_CONTINUE), NULL) - ); + gST->ConOut, + HiiGetString (gBootManagerPrivate.HiiHandle, STRING_TOKEN (STR_ANY_KEY_CONTINUE), NULL) + ); gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); } @@ -858,24 +869,24 @@ BootManagerCallback ( EFI_STATUS EFIAPI BootManagerUiLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Install Device Path Protocol and Config Access protocol to driver handle // gBootManagerPrivate.DriverHandle = NULL; - Status = gBS->InstallMultipleProtocolInterfaces ( - &gBootManagerPrivate.DriverHandle, - &gEfiDevicePathProtocolGuid, - &mBootManagerHiiVendorDevicePath, - &gEfiHiiConfigAccessProtocolGuid, - &gBootManagerPrivate.ConfigAccess, - NULL - ); + Status = gBS->InstallMultipleProtocolInterfaces ( + &gBootManagerPrivate.DriverHandle, + &gEfiDevicePathProtocolGuid, + &mBootManagerHiiVendorDevicePath, + &gEfiHiiConfigAccessProtocolGuid, + &gBootManagerPrivate.ConfigAccess, + NULL + ); ASSERT_EFI_ERROR (Status); // @@ -906,11 +917,11 @@ BootManagerUiLibConstructor ( EFI_STATUS EFIAPI BootManagerUiLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = gBS->UninstallMultipleProtocolInterfaces ( gBootManagerPrivate.DriverHandle, diff --git a/MdeModulePkg/Library/BootManagerUiLib/BootManager.h b/MdeModulePkg/Library/BootManagerUiLib/BootManager.h index f1ee922b37..0076a9dfce 100644 --- a/MdeModulePkg/Library/BootManagerUiLib/BootManager.h +++ b/MdeModulePkg/Library/BootManagerUiLib/BootManager.h @@ -33,8 +33,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; #pragma pack() @@ -46,11 +46,11 @@ typedef struct { 0x847bc3fe, 0xb974, 0x446d, {0x94, 0x49, 0x5a, 0xd5, 0x41, 0x2e, 0x99, 0x3b} \ } -#define BOOT_MANAGER_FORM_ID 0x1000 +#define BOOT_MANAGER_FORM_ID 0x1000 -#define LABEL_BOOT_OPTION 0x00 -#define LABEL_BOOT_OPTION_END 0x01 -#define MAX_STRING_LEN 200 +#define LABEL_BOOT_OPTION 0x00 +#define LABEL_BOOT_OPTION_END 0x01 +#define MAX_STRING_LEN 200 // // Variable created with this flag will be "Efi:...." @@ -60,23 +60,23 @@ typedef struct { // // These are the VFR compiler generated data representing our VFR data. // -extern UINT8 BootManagerVfrBin[]; +extern UINT8 BootManagerVfrBin[]; #define BOOT_MANAGER_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('B', 'M', 'C', 'B') typedef struct { - UINTN Signature; + UINTN Signature; // // HII relative handles // - EFI_HII_HANDLE HiiHandle; - EFI_HANDLE DriverHandle; + EFI_HII_HANDLE HiiHandle; + EFI_HANDLE DriverHandle; // // Produced protocols // - EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; + EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; } BOOT_MANAGER_CALLBACK_DATA; /** @@ -100,12 +100,12 @@ typedef struct { EFI_STATUS EFIAPI BootManagerCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); /** @@ -133,10 +133,10 @@ BootManagerCallback ( EFI_STATUS EFIAPI BootManagerExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ); /** @@ -158,9 +158,9 @@ BootManagerExtractConfig ( EFI_STATUS EFIAPI BootManagerRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ); #endif diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.c b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.c index 102146535b..f89db846ef 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.c +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.c @@ -12,7 +12,7 @@ **/ VOID * BrDummyMalloc ( - IN size_t Size + IN size_t Size ) { ASSERT (FALSE); @@ -24,7 +24,7 @@ BrDummyMalloc ( **/ VOID BrDummyFree ( - IN VOID * Ptr + IN VOID *Ptr ) { ASSERT (FALSE); diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.h b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.h index 9f84347670..71e76bcbf2 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.h +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecUefiSupport.h @@ -14,30 +14,30 @@ #include #include #include -#define memcpy CopyMem -#define memmove CopyMem -#define memset(dest,ch,count) SetMem(dest,(UINTN)(count),(UINT8)(ch)) -#define malloc BrDummyMalloc -#define free BrDummyFree - -typedef INT8 int8_t; -typedef INT16 int16_t; -typedef INT32 int32_t; -typedef INT64 int64_t; -typedef UINT8 uint8_t; -typedef UINT16 uint16_t; -typedef UINT32 uint32_t; -typedef UINT64 uint64_t; -typedef UINTN size_t; +#define memcpy CopyMem +#define memmove CopyMem +#define memset(dest, ch, count) SetMem(dest,(UINTN)(count),(UINT8)(ch)) +#define malloc BrDummyMalloc +#define free BrDummyFree + +typedef INT8 int8_t; +typedef INT16 int16_t; +typedef INT32 int32_t; +typedef INT64 int64_t; +typedef UINT8 uint8_t; +typedef UINT16 uint16_t; +typedef UINT32 uint32_t; +typedef UINT64 uint64_t; +typedef UINTN size_t; VOID * BrDummyMalloc ( - IN size_t Size + IN size_t Size ); VOID BrDummyFree ( - IN VOID * Ptr + IN VOID *Ptr ); #endif diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompress.c b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompress.c index 53e2255f5f..3cb31ab984 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompress.c +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompress.c @@ -17,18 +17,18 @@ **/ VOID * BrAlloc ( - IN VOID * Ptr, - IN size_t Size + IN VOID *Ptr, + IN size_t Size ) { - VOID *Addr; - BROTLI_BUFF *Private; + VOID *Addr; + BROTLI_BUFF *Private; Private = (BROTLI_BUFF *)Ptr; if (Private->BuffSize >= Size) { - Addr = Private->Buff; - Private->Buff = (VOID *) ((UINT8 *)Addr + Size); + Addr = Private->Buff; + Private->Buff = (VOID *)((UINT8 *)Addr + Size); Private->BuffSize -= Size; return Addr; } else { @@ -45,8 +45,8 @@ BrAlloc ( **/ VOID BrFree ( - IN VOID * Ptr, - IN VOID * Address + IN VOID *Ptr, + IN VOID *Address ) { // @@ -79,83 +79,89 @@ BrFree ( **/ EFI_STATUS BrotliDecompress ( - IN CONST VOID* Source, - IN UINTN SourceSize, - IN OUT VOID* Destination, - IN OUT UINTN DestSize, - IN VOID * BuffInfo + IN CONST VOID *Source, + IN UINTN SourceSize, + IN OUT VOID *Destination, + IN OUT UINTN DestSize, + IN VOID *BuffInfo ) { - UINT8 * Input; - UINT8 * Output; - const UINT8 * NextIn; - UINT8 * NextOut; - size_t TotalOut; - size_t AvailableIn; - size_t AvailableOut; - VOID * Temp; - BrotliDecoderResult Result; - BrotliDecoderState * BroState; - - TotalOut = 0; + UINT8 *Input; + UINT8 *Output; + const UINT8 *NextIn; + UINT8 *NextOut; + size_t TotalOut; + size_t AvailableIn; + size_t AvailableOut; + VOID *Temp; + BrotliDecoderResult Result; + BrotliDecoderState *BroState; + + TotalOut = 0; AvailableOut = FILE_BUFFER_SIZE; - Result = BROTLI_DECODER_RESULT_ERROR; - BroState = BrotliDecoderCreateInstance(BrAlloc, BrFree, BuffInfo); - Temp = Destination; + Result = BROTLI_DECODER_RESULT_ERROR; + BroState = BrotliDecoderCreateInstance (BrAlloc, BrFree, BuffInfo); + Temp = Destination; if (BroState == NULL) { return EFI_INVALID_PARAMETER; } - Input = (UINT8 *)BrAlloc(BuffInfo, FILE_BUFFER_SIZE); - Output = (UINT8 *)BrAlloc(BuffInfo, FILE_BUFFER_SIZE); - if ((Input==NULL) || (Output==NULL)) { - BrFree(BuffInfo, Input); - BrFree(BuffInfo, Output); - BrotliDecoderDestroyInstance(BroState); + + Input = (UINT8 *)BrAlloc (BuffInfo, FILE_BUFFER_SIZE); + Output = (UINT8 *)BrAlloc (BuffInfo, FILE_BUFFER_SIZE); + if ((Input == NULL) || (Output == NULL)) { + BrFree (BuffInfo, Input); + BrFree (BuffInfo, Output); + BrotliDecoderDestroyInstance (BroState); return EFI_INVALID_PARAMETER; } + NextOut = Output; - Result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; + Result = BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; while (1) { if (Result == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT) { if (SourceSize == 0) { break; } + if (SourceSize >= FILE_BUFFER_SIZE) { AvailableIn = FILE_BUFFER_SIZE; - }else{ + } else { AvailableIn = SourceSize; } - CopyMem(Input, Source, AvailableIn); - Source = (VOID *)((UINT8 *)Source + AvailableIn); + + CopyMem (Input, Source, AvailableIn); + Source = (VOID *)((UINT8 *)Source + AvailableIn); SourceSize -= AvailableIn; - NextIn = Input; + NextIn = Input; } else if (Result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { - CopyMem(Temp, Output, FILE_BUFFER_SIZE); + CopyMem (Temp, Output, FILE_BUFFER_SIZE); AvailableOut = FILE_BUFFER_SIZE; - Temp = (VOID *)((UINT8 *)Temp +FILE_BUFFER_SIZE); - NextOut = Output; + Temp = (VOID *)((UINT8 *)Temp +FILE_BUFFER_SIZE); + NextOut = Output; } else { break; /* Error or success. */ } - Result = BrotliDecoderDecompressStream( - BroState, - &AvailableIn, - &NextIn, - &AvailableOut, - &NextOut, - &TotalOut - ); + + Result = BrotliDecoderDecompressStream ( + BroState, + &AvailableIn, + &NextIn, + &AvailableOut, + &NextOut, + &TotalOut + ); } + if (NextOut != Output) { - CopyMem(Temp, Output, (size_t)(NextOut - Output)); + CopyMem (Temp, Output, (size_t)(NextOut - Output)); } DestSize = TotalOut; - BrFree(BuffInfo, Input); - BrFree(BuffInfo, Output); - BrotliDecoderDestroyInstance(BroState); + BrFree (BuffInfo, Input); + BrFree (BuffInfo, Output); + BrotliDecoderDestroyInstance (BroState); return (Result == BROTLI_DECODER_RESULT_SUCCESS) ? EFI_SUCCESS : EFI_INVALID_PARAMETER; } @@ -169,19 +175,20 @@ BrotliDecompress ( @return The size of the uncompressed buffer. **/ UINT64 -BrGetDecodedSizeOfBuf( - IN UINT8 * EncodedData, - IN UINT8 StartOffset, - IN UINT8 EndOffset +BrGetDecodedSizeOfBuf ( + IN UINT8 *EncodedData, + IN UINT8 StartOffset, + IN UINT8 EndOffset ) { - UINT64 DecodedSize; - INTN Index; + UINT64 DecodedSize; + INTN Index; /* Parse header */ DecodedSize = 0; - for (Index = EndOffset - 1; Index >= StartOffset; Index--) - DecodedSize = LShiftU64(DecodedSize, 8) + EncodedData[Index]; + for (Index = EndOffset - 1; Index >= StartOffset; Index--) { + DecodedSize = LShiftU64 (DecodedSize, 8) + EncodedData[Index]; + } return DecodedSize; } @@ -218,23 +225,23 @@ BrGetDecodedSizeOfBuf( EFI_STATUS EFIAPI BrotliUefiDecompressGetInfo ( - IN CONST VOID * Source, - IN UINT32 SourceSize, - OUT UINT32 * DestinationSize, - OUT UINT32 * ScratchSize + IN CONST VOID *Source, + IN UINT32 SourceSize, + OUT UINT32 *DestinationSize, + OUT UINT32 *ScratchSize ) { UINT64 GetSize; UINT8 MaxOffset; - ASSERT(SourceSize >= BROTLI_SCRATCH_MAX); + ASSERT (SourceSize >= BROTLI_SCRATCH_MAX); - MaxOffset = BROTLI_DECODE_MAX; - GetSize = BrGetDecodedSizeOfBuf((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); + MaxOffset = BROTLI_DECODE_MAX; + GetSize = BrGetDecodedSizeOfBuf ((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); *DestinationSize = (UINT32)GetSize; - MaxOffset = BROTLI_SCRATCH_MAX; - GetSize = BrGetDecodedSizeOfBuf((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); - *ScratchSize = (UINT32)GetSize; + MaxOffset = BROTLI_SCRATCH_MAX; + GetSize = BrGetDecodedSizeOfBuf ((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); + *ScratchSize = (UINT32)GetSize; return EFI_SUCCESS; } @@ -263,31 +270,31 @@ BrotliUefiDecompressGetInfo ( EFI_STATUS EFIAPI BrotliUefiDecompress ( - IN CONST VOID * Source, - IN UINTN SourceSize, - IN OUT VOID * Destination, - IN OUT VOID * Scratch + IN CONST VOID *Source, + IN UINTN SourceSize, + IN OUT VOID *Destination, + IN OUT VOID *Scratch ) { - UINTN DestSize = 0; - EFI_STATUS Status; - BROTLI_BUFF BroBuff; - UINT64 GetSize; - UINT8 MaxOffset; + UINTN DestSize = 0; + EFI_STATUS Status; + BROTLI_BUFF BroBuff; + UINT64 GetSize; + UINT8 MaxOffset; MaxOffset = BROTLI_SCRATCH_MAX; - GetSize = BrGetDecodedSizeOfBuf((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); + GetSize = BrGetDecodedSizeOfBuf ((UINT8 *)Source, MaxOffset - BROTLI_INFO_SIZE, MaxOffset); BroBuff.Buff = Scratch; BroBuff.BuffSize = (UINTN)GetSize; - Status = BrotliDecompress( - (VOID *)((UINT8 *)Source + BROTLI_SCRATCH_MAX), - SourceSize - BROTLI_SCRATCH_MAX, - Destination, - DestSize, - (VOID *)(&BroBuff) - ); + Status = BrotliDecompress ( + (VOID *)((UINT8 *)Source + BROTLI_SCRATCH_MAX), + SourceSize - BROTLI_SCRATCH_MAX, + Destination, + DestSize, + (VOID *)(&BroBuff) + ); return Status; } diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompressLibInternal.h b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompressLibInternal.h index 8f91829a0e..312a5ede52 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompressLibInternal.h +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliDecompressLibInternal.h @@ -16,16 +16,15 @@ #include #include -typedef struct -{ +typedef struct { VOID *Buff; UINTN BuffSize; } BROTLI_BUFF; -#define FILE_BUFFER_SIZE 65536 -#define BROTLI_INFO_SIZE 8 -#define BROTLI_DECODE_MAX 8 -#define BROTLI_SCRATCH_MAX 16 +#define FILE_BUFFER_SIZE 65536 +#define BROTLI_INFO_SIZE 8 +#define BROTLI_DECODE_MAX 8 +#define BROTLI_SCRATCH_MAX 16 EFI_STATUS EFIAPI diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/GuidedSectionExtraction.c b/MdeModulePkg/Library/BrotliCustomDecompressLib/GuidedSectionExtraction.c index fd5a0d7cdb..262f218f1f 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/GuidedSectionExtraction.c +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/GuidedSectionExtraction.c @@ -59,31 +59,35 @@ BrotliGuidedSectionGetInfo ( if (IS_SECTION2 (InputSection)) { if (!CompareGuid ( - &gBrotliCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gBrotliCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes; return BrotliUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, - SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, + SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); } else { if (!CompareGuid ( - &gBrotliCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gBrotliCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes; return BrotliUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, - SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, + SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); @@ -136,38 +140,44 @@ BrotliGuidedSectionExtraction ( if (IS_SECTION2 (InputSection)) { if (!CompareGuid ( - &gBrotliCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gBrotliCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } + // // Authentication is set to Zero, which may be ignored. // *AuthenticationStatus = 0; return BrotliUefiDecompress ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, - SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, + SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, *OutputBuffer, ScratchBuffer ); } else { if (!CompareGuid ( - &gBrotliCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gBrotliCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } + // // Authentication is set to Zero, which may be ignored. // *AuthenticationStatus = 0; return BrotliUefiDecompress ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, - SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, + SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, *OutputBuffer, ScratchBuffer - ); + ); } } @@ -184,8 +194,8 @@ BrotliDecompressLibConstructor ( ) { return ExtractGuidedSectionRegisterHandlers ( - &gBrotliCustomDecompressGuid, - BrotliGuidedSectionGetInfo, - BrotliGuidedSectionExtraction - ); + &gBrotliCustomDecompressGuid, + BrotliGuidedSectionGetInfo, + BrotliGuidedSectionExtraction + ); } diff --git a/MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.c b/MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.c index ecd0886dc4..35ab5a8db5 100644 --- a/MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.c +++ b/MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.c @@ -27,7 +27,7 @@ EFI_STATUS EFIAPI InitializeCpuExceptionHandlers ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL ) { return EFI_SUCCESS; @@ -52,7 +52,7 @@ InitializeCpuExceptionHandlers ( EFI_STATUS EFIAPI InitializeCpuInterruptHandlers ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL ) { return EFI_SUCCESS; @@ -84,8 +84,8 @@ InitializeCpuInterruptHandlers ( EFI_STATUS EFIAPI RegisterCpuInterruptHandler ( - IN EFI_EXCEPTION_TYPE InterruptType, - IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler + IN EFI_EXCEPTION_TYPE InterruptType, + IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler ) { return EFI_UNSUPPORTED; @@ -100,8 +100,8 @@ RegisterCpuInterruptHandler ( VOID EFIAPI DumpCpuContext ( - IN EFI_EXCEPTION_TYPE ExceptionType, - IN EFI_SYSTEM_CONTEXT SystemContext + IN EFI_EXCEPTION_TYPE ExceptionType, + IN EFI_SYSTEM_CONTEXT SystemContext ) { } @@ -132,10 +132,9 @@ DumpCpuContext ( EFI_STATUS EFIAPI InitializeCpuExceptionHandlersEx ( - IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL, - IN CPU_EXCEPTION_INIT_DATA *InitData OPTIONAL + IN EFI_VECTOR_HANDOFF_INFO *VectorInfo OPTIONAL, + IN CPU_EXCEPTION_INIT_DATA *InitData OPTIONAL ) { return InitializeCpuExceptionHandlers (VectorInfo); } - diff --git a/MdeModulePkg/Library/CustomizedDisplayLib/Colors.h b/MdeModulePkg/Library/CustomizedDisplayLib/Colors.h index f2cbb8940f..487c6d4f2d 100644 --- a/MdeModulePkg/Library/CustomizedDisplayLib/Colors.h +++ b/MdeModulePkg/Library/CustomizedDisplayLib/Colors.h @@ -14,25 +14,25 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Screen Color Settings // -#define PICKLIST_HIGHLIGHT_TEXT EFI_WHITE -#define PICKLIST_HIGHLIGHT_BACKGROUND EFI_BACKGROUND_CYAN -#define TITLE_TEXT EFI_WHITE -#define TITLE_BACKGROUND EFI_BACKGROUND_BLUE -#define KEYHELP_TEXT EFI_LIGHTGRAY -#define KEYHELP_BACKGROUND EFI_BACKGROUND_BLACK -#define SUBTITLE_BACKGROUND EFI_BACKGROUND_LIGHTGRAY -#define BANNER_TEXT EFI_BLUE -#define BANNER_BACKGROUND EFI_BACKGROUND_LIGHTGRAY -#define FIELD_TEXT_GRAYED EFI_DARKGRAY -#define FIELD_BACKGROUND EFI_BACKGROUND_LIGHTGRAY -#define POPUP_TEXT EFI_LIGHTGRAY -#define POPUP_BACKGROUND EFI_BACKGROUND_BLUE -#define POPUP_INVERSE_TEXT EFI_LIGHTGRAY -#define POPUP_INVERSE_BACKGROUND EFI_BACKGROUND_BLACK -#define HELP_TEXT EFI_BLUE -#define ERROR_TEXT EFI_RED | EFI_BRIGHT -#define INFO_TEXT EFI_YELLOW | EFI_BRIGHT -#define ARROW_TEXT EFI_RED | EFI_BRIGHT -#define ARROW_BACKGROUND EFI_BACKGROUND_LIGHTGRAY +#define PICKLIST_HIGHLIGHT_TEXT EFI_WHITE +#define PICKLIST_HIGHLIGHT_BACKGROUND EFI_BACKGROUND_CYAN +#define TITLE_TEXT EFI_WHITE +#define TITLE_BACKGROUND EFI_BACKGROUND_BLUE +#define KEYHELP_TEXT EFI_LIGHTGRAY +#define KEYHELP_BACKGROUND EFI_BACKGROUND_BLACK +#define SUBTITLE_BACKGROUND EFI_BACKGROUND_LIGHTGRAY +#define BANNER_TEXT EFI_BLUE +#define BANNER_BACKGROUND EFI_BACKGROUND_LIGHTGRAY +#define FIELD_TEXT_GRAYED EFI_DARKGRAY +#define FIELD_BACKGROUND EFI_BACKGROUND_LIGHTGRAY +#define POPUP_TEXT EFI_LIGHTGRAY +#define POPUP_BACKGROUND EFI_BACKGROUND_BLUE +#define POPUP_INVERSE_TEXT EFI_LIGHTGRAY +#define POPUP_INVERSE_BACKGROUND EFI_BACKGROUND_BLACK +#define HELP_TEXT EFI_BLUE +#define ERROR_TEXT EFI_RED | EFI_BRIGHT +#define INFO_TEXT EFI_YELLOW | EFI_BRIGHT +#define ARROW_TEXT EFI_RED | EFI_BRIGHT +#define ARROW_BACKGROUND EFI_BACKGROUND_LIGHTGRAY #endif diff --git a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.c b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.c index 4dca484eb8..b3da13d0a3 100644 --- a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.c +++ b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.c @@ -8,14 +8,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "CustomizedDisplayLibInternal.h" -EFI_GUID gCustomizedDisplayLibGuid = { 0x99fdc8fd, 0x849b, 0x4eba, { 0xad, 0x13, 0xfb, 0x96, 0x99, 0xc9, 0xa, 0x4d } }; +EFI_GUID gCustomizedDisplayLibGuid = { + 0x99fdc8fd, 0x849b, 0x4eba, { 0xad, 0x13, 0xfb, 0x96, 0x99, 0xc9, 0xa, 0x4d } +}; -EFI_HII_HANDLE mCDLStringPackHandle; -UINT16 gClassOfVfr; // Formset class information -BOOLEAN gLibIsFirstForm = TRUE; -BANNER_DATA *gBannerData; +EFI_HII_HANDLE mCDLStringPackHandle; +UINT16 gClassOfVfr; // Formset class information +BOOLEAN gLibIsFirstForm = TRUE; +BANNER_DATA *gBannerData; -UINTN gFooterHeight; +UINTN gFooterHeight; /** +------------------------------------------------------------------------------+ @@ -51,14 +53,14 @@ Statement EFI_STATUS EFIAPI DisplayPageFrame ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - OUT EFI_SCREEN_DESCRIPTOR *ScreenForStatement + IN FORM_DISPLAY_ENGINE_FORM *FormData, + OUT EFI_SCREEN_DESCRIPTOR *ScreenForStatement ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (FormData != NULL && ScreenForStatement != NULL); - if (FormData == NULL || ScreenForStatement == NULL) { + if ((FormData == NULL) || (ScreenForStatement == NULL)) { return EFI_INVALID_PARAMETER; } @@ -69,17 +71,18 @@ DisplayPageFrame ( gClassOfVfr = FORMSET_CLASS_PLATFORM_SETUP; - ProcessExternedOpcode(FormData); + ProcessExternedOpcode (FormData); // // Calculate the ScreenForStatement. // - ScreenForStatement->BottomRow = gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - gFooterHeight; + ScreenForStatement->BottomRow = gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - gFooterHeight; if (gClassOfVfr == FORMSET_CLASS_FRONT_PAGE) { - ScreenForStatement->TopRow = gScreenDimensions.TopRow + FRONT_PAGE_HEADER_HEIGHT; + ScreenForStatement->TopRow = gScreenDimensions.TopRow + FRONT_PAGE_HEADER_HEIGHT; } else { - ScreenForStatement->TopRow = gScreenDimensions.TopRow + NONE_FRONT_PAGE_HEADER_HEIGHT; + ScreenForStatement->TopRow = gScreenDimensions.TopRow + NONE_FRONT_PAGE_HEADER_HEIGHT; } + ScreenForStatement->LeftColumn = gScreenDimensions.LeftColumn; ScreenForStatement->RightColumn = gScreenDimensions.RightColumn; @@ -105,7 +108,7 @@ DisplayPageFrame ( PrintFramework (FormData); - UpdateStatusBar(NV_UPDATE_REQUIRED, FormData->SettingChangedFlag); + UpdateStatusBar (NV_UPDATE_REQUIRED, FormData->SettingChangedFlag); return EFI_SUCCESS; } @@ -122,27 +125,27 @@ DisplayPageFrame ( VOID EFIAPI RefreshKeyHelp ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, - IN BOOLEAN Selected + IN FORM_DISPLAY_ENGINE_FORM *FormData, + IN FORM_DISPLAY_ENGINE_STATEMENT *Statement, + IN BOOLEAN Selected ) { - UINTN SecCol; - UINTN ThdCol; - UINTN RightColumnOfHelp; - UINTN TopRowOfHelp; - UINTN BottomRowOfHelp; - UINTN StartColumnOfHelp; - EFI_IFR_NUMERIC *NumericOp; - EFI_IFR_DATE *DateOp; - EFI_IFR_TIME *TimeOp; - BOOLEAN HexDisplay; - UINTN ColumnWidth1; - UINTN ColumnWidth2; - UINTN ColumnWidth3; - CHAR16 *ColumnStr1; - CHAR16 *ColumnStr2; - CHAR16 *ColumnStr3; + UINTN SecCol; + UINTN ThdCol; + UINTN RightColumnOfHelp; + UINTN TopRowOfHelp; + UINTN BottomRowOfHelp; + UINTN StartColumnOfHelp; + EFI_IFR_NUMERIC *NumericOp; + EFI_IFR_DATE *DateOp; + EFI_IFR_TIME *TimeOp; + BOOLEAN HexDisplay; + UINTN ColumnWidth1; + UINTN ColumnWidth2; + UINTN ColumnWidth3; + CHAR16 *ColumnStr1; + CHAR16 *ColumnStr2; + CHAR16 *ColumnStr3; ASSERT (FormData != NULL); if (FormData == NULL) { @@ -155,8 +158,8 @@ RefreshKeyHelp ( return; } - SecCol = gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3; - ThdCol = gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3 * 2; + SecCol = gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3; + ThdCol = gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3 * 2; // // + 2 means leave 1 space before the first hotkey info. @@ -166,12 +169,12 @@ RefreshKeyHelp ( TopRowOfHelp = gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - gFooterHeight + 1; BottomRowOfHelp = gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - 2; - ColumnWidth1 = SecCol - StartColumnOfHelp; - ColumnWidth2 = ThdCol - SecCol; - ColumnWidth3 = RightColumnOfHelp - ThdCol; - ColumnStr1 = gLibEmptyString; - ColumnStr2 = gLibEmptyString; - ColumnStr3 = gLibEmptyString; + ColumnWidth1 = SecCol - StartColumnOfHelp; + ColumnWidth2 = ThdCol - SecCol; + ColumnWidth3 = RightColumnOfHelp - ThdCol; + ColumnStr1 = gLibEmptyString; + ColumnStr2 = gLibEmptyString; + ColumnStr3 = gLibEmptyString; // // Clean the space at gScreenDimensions.LeftColumn + 1. @@ -190,139 +193,152 @@ RefreshKeyHelp ( if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { ColumnStr3 = gEscapeString; } + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); return; } HexDisplay = FALSE; - NumericOp = NULL; - DateOp = NULL; - TimeOp = NULL; + NumericOp = NULL; + DateOp = NULL; + TimeOp = NULL; if (Statement->OpCode->OpCode == EFI_IFR_NUMERIC_OP) { - NumericOp = (EFI_IFR_NUMERIC *) Statement->OpCode; + NumericOp = (EFI_IFR_NUMERIC *)Statement->OpCode; HexDisplay = (NumericOp->Flags & EFI_IFR_DISPLAY_UINT_HEX) == EFI_IFR_DISPLAY_UINT_HEX; } else if (Statement->OpCode->OpCode == EFI_IFR_DATE_OP) { - DateOp = (EFI_IFR_DATE *) Statement->OpCode; + DateOp = (EFI_IFR_DATE *)Statement->OpCode; HexDisplay = (DateOp->Flags & EFI_IFR_DISPLAY_UINT_HEX) == EFI_IFR_DISPLAY_UINT_HEX; } else if (Statement->OpCode->OpCode == EFI_IFR_TIME_OP) { - TimeOp = (EFI_IFR_TIME *) Statement->OpCode; + TimeOp = (EFI_IFR_TIME *)Statement->OpCode; HexDisplay = (TimeOp->Flags & EFI_IFR_DISPLAY_UINT_HEX) == EFI_IFR_DISPLAY_UINT_HEX; } - switch (Statement->OpCode->OpCode) { - case EFI_IFR_ORDERED_LIST_OP: - case EFI_IFR_ONE_OF_OP: - case EFI_IFR_NUMERIC_OP: - case EFI_IFR_TIME_OP: - case EFI_IFR_DATE_OP: - if (!Selected) { - PrintHotKeyHelpString (FormData, TRUE); - - if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { - ColumnStr3 = gEscapeString; - } - PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); - if ((Statement->OpCode->OpCode == EFI_IFR_DATE_OP) || - (Statement->OpCode->OpCode == EFI_IFR_TIME_OP)) { - PrintAt ( - ColumnWidth1, - StartColumnOfHelp, - BottomRowOfHelp, - L"%c%c%c%c%s", - ARROW_UP, - ARROW_DOWN, - ARROW_RIGHT, - ARROW_LEFT, - gMoveHighlight - ); - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterString, ColumnWidth2); - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, gAdjustNumber, ColumnWidth1); - } else { - PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); - if (Statement->OpCode->OpCode == EFI_IFR_NUMERIC_OP && NumericOp != NULL && LibGetFieldFromNum(Statement->OpCode) != 0) { - ColumnStr1 = gAdjustNumber; + switch (Statement->OpCode->OpCode) { + case EFI_IFR_ORDERED_LIST_OP: + case EFI_IFR_ONE_OF_OP: + case EFI_IFR_NUMERIC_OP: + case EFI_IFR_TIME_OP: + case EFI_IFR_DATE_OP: + if (!Selected) { + PrintHotKeyHelpString (FormData, TRUE); + + if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { + ColumnStr3 = gEscapeString; } - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterString, ColumnWidth2); - } - } else { - PrintHotKeyHelpString (FormData, FALSE); - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterCommitString, ColumnWidth2); - // - // If it is a selected numeric with manual input, display different message - // - if ((Statement->OpCode->OpCode == EFI_IFR_NUMERIC_OP) || - (Statement->OpCode->OpCode == EFI_IFR_DATE_OP) || - (Statement->OpCode->OpCode == EFI_IFR_TIME_OP)) { - ColumnStr2 = HexDisplay ? gHexNumericInput : gDecNumericInput; - PrintStringAtWithWidth (StartColumnOfHelp, BottomRowOfHelp, gLibEmptyString, ColumnWidth1); + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); + + if ((Statement->OpCode->OpCode == EFI_IFR_DATE_OP) || + (Statement->OpCode->OpCode == EFI_IFR_TIME_OP)) + { + PrintAt ( + ColumnWidth1, + StartColumnOfHelp, + BottomRowOfHelp, + L"%c%c%c%c%s", + ARROW_UP, + ARROW_DOWN, + ARROW_RIGHT, + ARROW_LEFT, + gMoveHighlight + ); + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterString, ColumnWidth2); + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, gAdjustNumber, ColumnWidth1); + } else { + PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); + if ((Statement->OpCode->OpCode == EFI_IFR_NUMERIC_OP) && (NumericOp != NULL) && (LibGetFieldFromNum (Statement->OpCode) != 0)) { + ColumnStr1 = gAdjustNumber; + } + + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterString, ColumnWidth2); + } } else { - PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); - } + PrintHotKeyHelpString (FormData, FALSE); + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gEnterCommitString, ColumnWidth2); + + // + // If it is a selected numeric with manual input, display different message + // + if ((Statement->OpCode->OpCode == EFI_IFR_NUMERIC_OP) || + (Statement->OpCode->OpCode == EFI_IFR_DATE_OP) || + (Statement->OpCode->OpCode == EFI_IFR_TIME_OP)) + { + ColumnStr2 = HexDisplay ? gHexNumericInput : gDecNumericInput; + PrintStringAtWithWidth (StartColumnOfHelp, BottomRowOfHelp, gLibEmptyString, ColumnWidth1); + } else { + PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); + } - if (Statement->OpCode->OpCode == EFI_IFR_ORDERED_LIST_OP) { - ColumnStr1 = gPlusString; - ColumnStr3 = gMinusString; - } - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); - PrintStringAtWithWidth (ThdCol, TopRowOfHelp, ColumnStr3, ColumnWidth3); - PrintStringAtWithWidth (SecCol, TopRowOfHelp, ColumnStr2, ColumnWidth2); + if (Statement->OpCode->OpCode == EFI_IFR_ORDERED_LIST_OP) { + ColumnStr1 = gPlusString; + ColumnStr3 = gMinusString; + } - PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, gEnterEscapeString, ColumnWidth3); - } - break; + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); + PrintStringAtWithWidth (ThdCol, TopRowOfHelp, ColumnStr3, ColumnWidth3); + PrintStringAtWithWidth (SecCol, TopRowOfHelp, ColumnStr2, ColumnWidth2); - case EFI_IFR_CHECKBOX_OP: - PrintHotKeyHelpString (FormData, TRUE); + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, gEnterEscapeString, ColumnWidth3); + } - if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { - ColumnStr3 = gEscapeString; - } - PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); + break; - PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gToggleCheckBox, ColumnWidth2); - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, gLibEmptyString, ColumnWidth1); - break; - - case EFI_IFR_REF_OP: - case EFI_IFR_PASSWORD_OP: - case EFI_IFR_STRING_OP: - case EFI_IFR_TEXT_OP: - case EFI_IFR_ACTION_OP: - case EFI_IFR_RESET_BUTTON_OP: - case EFI_IFR_SUBTITLE_OP: - if (!Selected) { + case EFI_IFR_CHECKBOX_OP: PrintHotKeyHelpString (FormData, TRUE); if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { ColumnStr3 = gEscapeString; } + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); - if (Statement->OpCode->OpCode != EFI_IFR_TEXT_OP && Statement->OpCode->OpCode != EFI_IFR_SUBTITLE_OP) { - ColumnStr2 = gEnterString; - } - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, ColumnStr2, ColumnWidth2); - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); - } else { - PrintHotKeyHelpString (FormData, FALSE); - if (Statement->OpCode->OpCode != EFI_IFR_REF_OP) { - ColumnStr2 = gEnterCommitString; - ColumnStr3 = gEnterEscapeString; + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, gToggleCheckBox, ColumnWidth2); + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, gLibEmptyString, ColumnWidth1); + break; + + case EFI_IFR_REF_OP: + case EFI_IFR_PASSWORD_OP: + case EFI_IFR_STRING_OP: + case EFI_IFR_TEXT_OP: + case EFI_IFR_ACTION_OP: + case EFI_IFR_RESET_BUTTON_OP: + case EFI_IFR_SUBTITLE_OP: + if (!Selected) { + PrintHotKeyHelpString (FormData, TRUE); + + if (gClassOfVfr == FORMSET_CLASS_PLATFORM_SETUP) { + ColumnStr3 = gEscapeString; + } + + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); + + PrintAt (ColumnWidth1, StartColumnOfHelp, BottomRowOfHelp, L"%c%c%s", ARROW_UP, ARROW_DOWN, gMoveHighlight); + if ((Statement->OpCode->OpCode != EFI_IFR_TEXT_OP) && (Statement->OpCode->OpCode != EFI_IFR_SUBTITLE_OP)) { + ColumnStr2 = gEnterString; + } + + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, ColumnStr2, ColumnWidth2); + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); + } else { + PrintHotKeyHelpString (FormData, FALSE); + if (Statement->OpCode->OpCode != EFI_IFR_REF_OP) { + ColumnStr2 = gEnterCommitString; + ColumnStr3 = gEnterEscapeString; + } + + PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); + PrintStringAtWithWidth (StartColumnOfHelp, BottomRowOfHelp, ColumnStr1, ColumnWidth1); + PrintStringAtWithWidth (SecCol, BottomRowOfHelp, ColumnStr2, ColumnWidth2); + PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); } - PrintStringAtWithWidth (StartColumnOfHelp, TopRowOfHelp, ColumnStr1, ColumnWidth1); - PrintStringAtWithWidth (StartColumnOfHelp, BottomRowOfHelp, ColumnStr1, ColumnWidth1); - PrintStringAtWithWidth (SecCol, BottomRowOfHelp, ColumnStr2, ColumnWidth2); - PrintStringAtWithWidth (ThdCol, BottomRowOfHelp, ColumnStr3, ColumnWidth3); - } - break; - default: - break; + break; + + default: + break; } } @@ -338,57 +354,59 @@ RefreshKeyHelp ( VOID EFIAPI UpdateStatusBar ( - IN UINTN MessageType, - IN BOOLEAN State + IN UINTN MessageType, + IN BOOLEAN State ) { - UINTN Index; - CHAR16 OptionWidth; + UINTN Index; + CHAR16 OptionWidth; - OptionWidth = (CHAR16) ((gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3); + OptionWidth = (CHAR16)((gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3); switch (MessageType) { - case INPUT_ERROR: - if (State) { - gST->ConOut->SetAttribute (gST->ConOut, ERROR_TEXT); - PrintStringAt ( - gScreenDimensions.LeftColumn + OptionWidth, - gScreenDimensions.BottomRow - 1, - gInputErrorMessage - ); - } else { - gST->ConOut->SetAttribute (gST->ConOut, KEYHELP_BACKGROUND); - for (Index = 0; Index < (LibGetStringWidth (gInputErrorMessage) - 2) / 2; Index++) { - PrintStringAt (gScreenDimensions.LeftColumn + OptionWidth + Index, gScreenDimensions.BottomRow - 1, L" "); + case INPUT_ERROR: + if (State) { + gST->ConOut->SetAttribute (gST->ConOut, ERROR_TEXT); + PrintStringAt ( + gScreenDimensions.LeftColumn + OptionWidth, + gScreenDimensions.BottomRow - 1, + gInputErrorMessage + ); + } else { + gST->ConOut->SetAttribute (gST->ConOut, KEYHELP_BACKGROUND); + for (Index = 0; Index < (LibGetStringWidth (gInputErrorMessage) - 2) / 2; Index++) { + PrintStringAt (gScreenDimensions.LeftColumn + OptionWidth + Index, gScreenDimensions.BottomRow - 1, L" "); + } } - } - break; - case NV_UPDATE_REQUIRED: - // - // Global setting support. Show configuration change on every form. - // - if (State) { - gST->ConOut->SetAttribute (gST->ConOut, INFO_TEXT); - PrintStringAt ( - gScreenDimensions.LeftColumn + OptionWidth * 2, - gScreenDimensions.BottomRow - 1, - gNvUpdateMessage - ); - } else { - gST->ConOut->SetAttribute (gST->ConOut, KEYHELP_BACKGROUND); - for (Index = 0; Index < (LibGetStringWidth (gNvUpdateMessage) - 2) / 2; Index++) { + break; + + case NV_UPDATE_REQUIRED: + // + // Global setting support. Show configuration change on every form. + // + if (State) { + gST->ConOut->SetAttribute (gST->ConOut, INFO_TEXT); PrintStringAt ( - (gScreenDimensions.LeftColumn + OptionWidth * 2 + Index), + gScreenDimensions.LeftColumn + OptionWidth * 2, gScreenDimensions.BottomRow - 1, - L" " + gNvUpdateMessage ); + } else { + gST->ConOut->SetAttribute (gST->ConOut, KEYHELP_BACKGROUND); + for (Index = 0; Index < (LibGetStringWidth (gNvUpdateMessage) - 2) / 2; Index++) { + PrintStringAt ( + (gScreenDimensions.LeftColumn + OptionWidth * 2 + Index), + gScreenDimensions.BottomRow - 1, + L" " + ); + } } - } - break; - default: - break; + break; + + default: + break; } } @@ -408,28 +426,28 @@ CreateDialog ( ... ) { - VA_LIST Marker; - EFI_INPUT_KEY KeyValue; - EFI_STATUS Status; - UINTN LargestString; - UINTN LineNum; - UINTN Index; - UINTN Count; - CHAR16 Character; - UINTN Start; - UINTN End; - UINTN Top; - UINTN Bottom; - CHAR16 *String; - UINTN DimensionsWidth; - UINTN DimensionsHeight; - UINTN CurrentAttribute; - BOOLEAN CursorVisible; + VA_LIST Marker; + EFI_INPUT_KEY KeyValue; + EFI_STATUS Status; + UINTN LargestString; + UINTN LineNum; + UINTN Index; + UINTN Count; + CHAR16 Character; + UINTN Start; + UINTN End; + UINTN Top; + UINTN Bottom; + CHAR16 *String; + UINTN DimensionsWidth; + UINTN DimensionsHeight; + UINTN CurrentAttribute; + BOOLEAN CursorVisible; // // If screen dimension info is not ready, get it from console. // - if (gScreenDimensions.RightColumn == 0 || gScreenDimensions.BottomRow == 0) { + if ((gScreenDimensions.RightColumn == 0) || (gScreenDimensions.BottomRow == 0)) { ZeroMem (&gScreenDimensions, sizeof (EFI_SCREEN_DESCRIPTOR)); gST->ConOut->QueryMode ( gST->ConOut, @@ -439,27 +457,28 @@ CreateDialog ( ); } - DimensionsWidth = gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn; - DimensionsHeight = gScreenDimensions.BottomRow - gScreenDimensions.TopRow; + DimensionsWidth = gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn; + DimensionsHeight = gScreenDimensions.BottomRow - gScreenDimensions.TopRow; LargestString = 0; LineNum = 0; VA_START (Marker, Key); - while ((String = VA_ARG (Marker, CHAR16 *)) != NULL) { - LineNum ++; + while ((String = VA_ARG (Marker, CHAR16 *)) != NULL) { + LineNum++; if ((LibGetStringWidth (String) / 2) > LargestString) { LargestString = (LibGetStringWidth (String) / 2); } } + VA_END (Marker); if ((LargestString + 2) > DimensionsWidth) { LargestString = DimensionsWidth - 2; } - CurrentAttribute = gST->ConOut->Mode->Attribute; - CursorVisible = gST->ConOut->Mode->CursorVisible; + CurrentAttribute = gST->ConOut->Mode->Attribute; + CursorVisible = gST->ConOut->Mode->CursorVisible; gST->ConOut->EnableCursor (gST->ConOut, FALSE); gST->ConOut->SetAttribute (gST->ConOut, GetPopupColor ()); @@ -467,11 +486,11 @@ CreateDialog ( // Subtract the PopUp width from total Columns, allow for one space extra on // each end plus a border. // - Start = (DimensionsWidth - LargestString - 2) / 2 + gScreenDimensions.LeftColumn + 1; - End = Start + LargestString + 1; + Start = (DimensionsWidth - LargestString - 2) / 2 + gScreenDimensions.LeftColumn + 1; + End = Start + LargestString + 1; - Top = ((DimensionsHeight - LineNum - 2) / 2) + gScreenDimensions.TopRow - 1; - Bottom = Top + LineNum + 2; + Top = ((DimensionsHeight - LineNum - 2) / 2) + gScreenDimensions.TopRow - 1; + Bottom = Top + LineNum + 2; Character = BOXDRAW_DOWN_RIGHT; PrintCharAt (Start, Top, Character); @@ -487,7 +506,7 @@ CreateDialog ( Count = 0; VA_START (Marker, Key); for (Index = Top; Index + 2 < Bottom; Index++, Count++) { - String = VA_ARG (Marker, CHAR16*); + String = VA_ARG (Marker, CHAR16 *); if (String[0] == CHAR_NULL) { // @@ -522,17 +541,18 @@ CreateDialog ( PrintCharAt (Start, Index + 1, Character); PrintCharAt (End - 1, Index + 1, Character); } + VA_END (Marker); Character = BOXDRAW_UP_RIGHT; PrintCharAt (Start, Bottom - 1, Character); Character = BOXDRAW_HORIZONTAL; for (Index = Start; Index + 2 < End; Index++) { - PrintCharAt ((UINTN)-1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); } Character = BOXDRAW_UP_LEFT; - PrintCharAt ((UINTN)-1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); if (Key != NULL) { Status = WaitForKeyStroke (&KeyValue); @@ -555,9 +575,9 @@ ConfirmDataChange ( VOID ) { - CHAR16 YesResponse; - CHAR16 NoResponse; - EFI_INPUT_KEY Key; + CHAR16 YesResponse; + CHAR16 NoResponse; + EFI_INPUT_KEY Key; gST->ConIn->ReadKeyStroke (gST->ConIn, &Key); @@ -571,9 +591,9 @@ ConfirmDataChange ( CreateDialog (&Key, gLibEmptyString, gSaveChanges, gAreYouSure, gLibEmptyString, NULL); } while ( - (Key.ScanCode != SCAN_ESC) && - ((Key.UnicodeChar | UPPER_LOWER_CASE_OFFSET) != (NoResponse | UPPER_LOWER_CASE_OFFSET)) && - ((Key.UnicodeChar | UPPER_LOWER_CASE_OFFSET) != (YesResponse | UPPER_LOWER_CASE_OFFSET)) + (Key.ScanCode != SCAN_ESC) && + ((Key.UnicodeChar | UPPER_LOWER_CASE_OFFSET) != (NoResponse | UPPER_LOWER_CASE_OFFSET)) && + ((Key.UnicodeChar | UPPER_LOWER_CASE_OFFSET) != (YesResponse | UPPER_LOWER_CASE_OFFSET)) ); if (Key.ScanCode == SCAN_ESC) { @@ -617,14 +637,16 @@ FormExitPolicy ( UINT64 EFIAPI FormExitTimeout ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ) { return 0; } + // // Print Functions // + /** Prints a unicode string to the default console, at the supplied cursor position, using L"%s" format. @@ -639,9 +661,9 @@ FormExitTimeout ( UINTN EFIAPI PrintStringAt ( - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *String + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *String ) { return PrintAt (0, Column, Row, L"%s", String); @@ -662,10 +684,10 @@ PrintStringAt ( UINTN EFIAPI PrintStringAtWithWidth ( - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *String, - IN UINTN Width + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *String, + IN UINTN Width ) { return PrintAt (Width, Column, Row, L"%s", String); @@ -685,9 +707,9 @@ PrintStringAtWithWidth ( UINTN EFIAPI PrintCharAt ( - IN UINTN Column, - IN UINTN Row, - CHAR16 Character + IN UINTN Column, + IN UINTN Row, + CHAR16 Character ) { return PrintAt (0, Column, Row, L"%c", Character); @@ -706,11 +728,11 @@ PrintCharAt ( VOID EFIAPI ClearLines ( - IN UINTN LeftColumn, - IN UINTN RightColumn, - IN UINTN TopRow, - IN UINTN BottomRow, - IN UINTN TextAttribute + IN UINTN LeftColumn, + IN UINTN RightColumn, + IN UINTN TopRow, + IN UINTN BottomRow, + IN UINTN TextAttribute ) { CHAR16 *Buffer; @@ -914,14 +936,14 @@ ClearDisplayPage ( EFI_STATUS EFIAPI CustomizedDisplayLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { mCDLStringPackHandle = HiiAddPackages (&gCustomizedDisplayLibGuid, ImageHandle, CustomizedDisplayLibStrings, NULL); ASSERT (mCDLStringPackHandle != NULL); - InitializeLibStrings(); + InitializeLibStrings (); return EFI_SUCCESS; } @@ -943,7 +965,7 @@ CustomizedDisplayLibDestructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - HiiRemovePackages(mCDLStringPackHandle); + HiiRemovePackages (mCDLStringPackHandle); FreeLibStrings (); diff --git a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.c b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.c index d770a0f873..58130d9383 100644 --- a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.c +++ b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.c @@ -8,33 +8,33 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "CustomizedDisplayLibInternal.h" -EFI_SCREEN_DESCRIPTOR gScreenDimensions; -CHAR16 *mLibUnknownString; -extern EFI_HII_HANDLE mCDLStringPackHandle; -CHAR16 *mSpaceBuffer; -#define SPACE_BUFFER_SIZE 1000 +EFI_SCREEN_DESCRIPTOR gScreenDimensions; +CHAR16 *mLibUnknownString; +extern EFI_HII_HANDLE mCDLStringPackHandle; +CHAR16 *mSpaceBuffer; +#define SPACE_BUFFER_SIZE 1000 // // Browser Global Strings // -CHAR16 *gEnterString; -CHAR16 *gEnterCommitString; -CHAR16 *gEnterEscapeString; -CHAR16 *gEscapeString; -CHAR16 *gMoveHighlight; -CHAR16 *gDecNumericInput; -CHAR16 *gHexNumericInput; -CHAR16 *gToggleCheckBox; -CHAR16 *gLibEmptyString; -CHAR16 *gAreYouSure; -CHAR16 *gYesResponse; -CHAR16 *gNoResponse; -CHAR16 *gPlusString; -CHAR16 *gMinusString; -CHAR16 *gAdjustNumber; -CHAR16 *gSaveChanges; -CHAR16 *gNvUpdateMessage; -CHAR16 *gInputErrorMessage; +CHAR16 *gEnterString; +CHAR16 *gEnterCommitString; +CHAR16 *gEnterEscapeString; +CHAR16 *gEscapeString; +CHAR16 *gMoveHighlight; +CHAR16 *gDecNumericInput; +CHAR16 *gHexNumericInput; +CHAR16 *gToggleCheckBox; +CHAR16 *gLibEmptyString; +CHAR16 *gAreYouSure; +CHAR16 *gYesResponse; +CHAR16 *gNoResponse; +CHAR16 *gPlusString; +CHAR16 *gMinusString; +CHAR16 *gAdjustNumber; +CHAR16 *gSaveChanges; +CHAR16 *gNvUpdateMessage; +CHAR16 *gInputErrorMessage; /** @@ -45,14 +45,14 @@ CHAR16 *gInputErrorMessage; **/ VOID PrintBannerInfo ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ) { - UINT8 Line; - UINT8 Alignment; - CHAR16 *StrFrontPageBanner; - UINT8 RowIdx; - UINT8 ColumnIdx; + UINT8 Line; + UINT8 Alignment; + CHAR16 *StrFrontPageBanner; + UINT8 RowIdx; + UINT8 ColumnIdx; // // ClearLines(0, LocalScreen.RightColumn, 0, BANNER_HEIGHT-1, BANNER_TEXT | BANNER_BACKGROUND); @@ -68,54 +68,55 @@ PrintBannerInfo ( // // for (Line = 0; Line < BANNER_HEIGHT; Line++) { // - for (Line = (UINT8) gScreenDimensions.TopRow; Line < BANNER_HEIGHT + (UINT8) gScreenDimensions.TopRow; Line++) { + for (Line = (UINT8)gScreenDimensions.TopRow; Line < BANNER_HEIGHT + (UINT8)gScreenDimensions.TopRow; Line++) { // // for (Alignment = 0; Alignment < BANNER_COLUMNS; Alignment++) { // - for (Alignment = (UINT8) gScreenDimensions.LeftColumn; - Alignment < BANNER_COLUMNS + (UINT8) gScreenDimensions.LeftColumn; + for (Alignment = (UINT8)gScreenDimensions.LeftColumn; + Alignment < BANNER_COLUMNS + (UINT8)gScreenDimensions.LeftColumn; Alignment++ - ) { - RowIdx = (UINT8) (Line - (UINT8) gScreenDimensions.TopRow); - ColumnIdx = (UINT8) (Alignment - (UINT8) gScreenDimensions.LeftColumn); + ) + { + RowIdx = (UINT8)(Line - (UINT8)gScreenDimensions.TopRow); + ColumnIdx = (UINT8)(Alignment - (UINT8)gScreenDimensions.LeftColumn); ASSERT (RowIdx < BANNER_HEIGHT && ColumnIdx < BANNER_COLUMNS); - if (gBannerData!= NULL && gBannerData->Banner[RowIdx][ColumnIdx] != 0x0000) { + if ((gBannerData != NULL) && (gBannerData->Banner[RowIdx][ColumnIdx] != 0x0000)) { StrFrontPageBanner = LibGetToken (gBannerData->Banner[RowIdx][ColumnIdx], FormData->HiiHandle); } else { continue; } switch (Alignment - gScreenDimensions.LeftColumn) { - case 0: - // - // Handle left column - // - PrintStringAt (gScreenDimensions.LeftColumn + BANNER_LEFT_COLUMN_INDENT, Line, StrFrontPageBanner); - break; + case 0: + // + // Handle left column + // + PrintStringAt (gScreenDimensions.LeftColumn + BANNER_LEFT_COLUMN_INDENT, Line, StrFrontPageBanner); + break; - case 1: - // - // Handle center column - // - PrintStringAt ( - gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3, - Line, - StrFrontPageBanner - ); - break; - - case 2: - // - // Handle right column - // - PrintStringAt ( - gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) * 2 / 3, - Line, - StrFrontPageBanner - ); - break; + case 1: + // + // Handle center column + // + PrintStringAt ( + gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) / 3, + Line, + StrFrontPageBanner + ); + break; + + case 2: + // + // Handle right column + // + PrintStringAt ( + gScreenDimensions.LeftColumn + (gScreenDimensions.RightColumn - gScreenDimensions.LeftColumn) * 2 / 3, + Line, + StrFrontPageBanner + ); + break; } FreePool (StrFrontPageBanner); @@ -130,15 +131,15 @@ PrintBannerInfo ( **/ VOID PrintFramework ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ) { - UINTN Index; - CHAR16 Character; - CHAR16 *Buffer; - UINTN Row; - CHAR16 *TitleStr; - UINTN TitleColumn; + UINTN Index; + CHAR16 Character; + CHAR16 *Buffer; + UINTN Row; + CHAR16 *TitleStr; + UINTN TitleColumn; if (gClassOfVfr != FORMSET_CLASS_PLATFORM_SETUP) { // @@ -171,10 +172,10 @@ PrintFramework ( Character = BOXDRAW_DOWN_RIGHT; PrintCharAt (gScreenDimensions.LeftColumn, gScreenDimensions.TopRow, Character); - PrintStringAt ((UINTN) -1, (UINTN) -1, Buffer); + PrintStringAt ((UINTN)-1, (UINTN)-1, Buffer); Character = BOXDRAW_DOWN_LEFT; - PrintCharAt ((UINTN) -1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); Character = BOXDRAW_VERTICAL; for (Row = gScreenDimensions.TopRow + 1; Row <= gScreenDimensions.TopRow + NONE_FRONT_PAGE_HEADER_HEIGHT - 2; Row++) { @@ -199,10 +200,10 @@ PrintFramework ( Character = BOXDRAW_UP_RIGHT; PrintCharAt (gScreenDimensions.LeftColumn, gScreenDimensions.TopRow + NONE_FRONT_PAGE_HEADER_HEIGHT - 1, Character); - PrintStringAt ((UINTN) -1, (UINTN) -1, Buffer); + PrintStringAt ((UINTN)-1, (UINTN)-1, Buffer); Character = BOXDRAW_UP_LEFT; - PrintCharAt ((UINTN) -1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); // // Print Bottom border line @@ -213,15 +214,16 @@ PrintFramework ( Character = BOXDRAW_DOWN_RIGHT; PrintCharAt (gScreenDimensions.LeftColumn, gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - gFooterHeight, Character); - PrintStringAt ((UINTN) -1, (UINTN) -1, Buffer); + PrintStringAt ((UINTN)-1, (UINTN)-1, Buffer); Character = BOXDRAW_DOWN_LEFT; - PrintCharAt ((UINTN) -1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); Character = BOXDRAW_VERTICAL; for (Row = gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - gFooterHeight + 1; Row <= gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - 2; Row++ - ) { + ) + { PrintCharAt (gScreenDimensions.LeftColumn, Row, Character); PrintCharAt (gScreenDimensions.RightColumn - 1, Row, Character); } @@ -229,10 +231,10 @@ PrintFramework ( Character = BOXDRAW_UP_RIGHT; PrintCharAt (gScreenDimensions.LeftColumn, gScreenDimensions.BottomRow - STATUS_BAR_HEIGHT - 1, Character); - PrintStringAt ((UINTN) -1, (UINTN) -1, Buffer); + PrintStringAt ((UINTN)-1, (UINTN)-1, Buffer); Character = BOXDRAW_UP_LEFT; - PrintCharAt ((UINTN) -1, (UINTN) -1, Character); + PrintCharAt ((UINTN)-1, (UINTN)-1, Character); FreePool (Buffer); } @@ -246,12 +248,12 @@ PrintFramework ( **/ VOID -ProcessUserOpcode( - IN EFI_IFR_OP_HEADER *OpCodeData +ProcessUserOpcode ( + IN EFI_IFR_OP_HEADER *OpCodeData ) { - EFI_GUID * ClassGuid; - UINT8 ClassGuidNum; + EFI_GUID *ClassGuid; + UINT8 ClassGuidNum; ClassGuid = NULL; ClassGuidNum = 0; @@ -261,65 +263,70 @@ ProcessUserOpcode( // // process the statement outside of form,if it is formset op, get its formsetguid or classguid and compared with gFrontPageFormSetGuid // - if (CompareMem (PcdGetPtr (PcdFrontPageFormSetGuid), &((EFI_IFR_FORM_SET *) OpCodeData)->Guid, sizeof (EFI_GUID)) == 0){ + if (CompareMem (PcdGetPtr (PcdFrontPageFormSetGuid), &((EFI_IFR_FORM_SET *)OpCodeData)->Guid, sizeof (EFI_GUID)) == 0) { gClassOfVfr = FORMSET_CLASS_FRONT_PAGE; - } else{ + } else { ClassGuidNum = (UINT8)(((EFI_IFR_FORM_SET *)OpCodeData)->Flags & 0x3); ClassGuid = (EFI_GUID *)(VOID *)((UINT8 *)OpCodeData + sizeof (EFI_IFR_FORM_SET)); - while (ClassGuidNum-- > 0){ - if (CompareGuid((EFI_GUID*)PcdGetPtr (PcdFrontPageFormSetGuid),ClassGuid)){ + while (ClassGuidNum-- > 0) { + if (CompareGuid ((EFI_GUID *)PcdGetPtr (PcdFrontPageFormSetGuid), ClassGuid)) { gClassOfVfr = FORMSET_CLASS_FRONT_PAGE; break; } - ClassGuid ++; + + ClassGuid++; } } + break; case EFI_IFR_GUID_OP: - if (CompareGuid (&gEfiIfrTianoGuid, (EFI_GUID *)((CHAR8*) OpCodeData + sizeof (EFI_IFR_OP_HEADER)))) { + if (CompareGuid (&gEfiIfrTianoGuid, (EFI_GUID *)((CHAR8 *)OpCodeData + sizeof (EFI_IFR_OP_HEADER)))) { // // Tiano specific GUIDed opcodes // - switch (((EFI_IFR_GUID_LABEL *) OpCodeData)->ExtendOpCode) { - case EFI_IFR_EXTEND_OP_LABEL: - // - // just ignore label - // - break; + switch (((EFI_IFR_GUID_LABEL *)OpCodeData)->ExtendOpCode) { + case EFI_IFR_EXTEND_OP_LABEL: + // + // just ignore label + // + break; - case EFI_IFR_EXTEND_OP_BANNER: - // - // Only in front page form set, we care about the banner data. - // - if (gClassOfVfr == FORMSET_CLASS_FRONT_PAGE) { + case EFI_IFR_EXTEND_OP_BANNER: // - // Initialize Driver private data + // Only in front page form set, we care about the banner data. // - if (gBannerData == NULL) { - gBannerData = AllocateZeroPool (sizeof (BANNER_DATA)); - ASSERT (gBannerData != NULL); + if (gClassOfVfr == FORMSET_CLASS_FRONT_PAGE) { + // + // Initialize Driver private data + // + if (gBannerData == NULL) { + gBannerData = AllocateZeroPool (sizeof (BANNER_DATA)); + ASSERT (gBannerData != NULL); + } + + CopyMem ( + &gBannerData->Banner[((EFI_IFR_GUID_BANNER *)OpCodeData)->LineNumber][ + ((EFI_IFR_GUID_BANNER *)OpCodeData)->Alignment], + &((EFI_IFR_GUID_BANNER *)OpCodeData)->Title, + sizeof (EFI_STRING_ID) + ); } - CopyMem ( - &gBannerData->Banner[((EFI_IFR_GUID_BANNER *) OpCodeData)->LineNumber][ - ((EFI_IFR_GUID_BANNER *) OpCodeData)->Alignment], - &((EFI_IFR_GUID_BANNER *) OpCodeData)->Title, - sizeof (EFI_STRING_ID) - ); - } - break; + break; - case EFI_IFR_EXTEND_OP_SUBCLASS: - if (((EFI_IFR_GUID_SUBCLASS *) OpCodeData)->SubClass == EFI_FRONT_PAGE_SUBCLASS) { - gClassOfVfr = FORMSET_CLASS_FRONT_PAGE; - } - break; + case EFI_IFR_EXTEND_OP_SUBCLASS: + if (((EFI_IFR_GUID_SUBCLASS *)OpCodeData)->SubClass == EFI_FRONT_PAGE_SUBCLASS) { + gClassOfVfr = FORMSET_CLASS_FRONT_PAGE; + } - default: - break; + break; + + default: + break; } } + break; default: @@ -337,37 +344,36 @@ ProcessUserOpcode( **/ VOID ProcessExternedOpcode ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ) { - LIST_ENTRY *Link; - LIST_ENTRY *NestLink; - FORM_DISPLAY_ENGINE_STATEMENT *Statement; - FORM_DISPLAY_ENGINE_STATEMENT *NestStatement; + LIST_ENTRY *Link; + LIST_ENTRY *NestLink; + FORM_DISPLAY_ENGINE_STATEMENT *Statement; + FORM_DISPLAY_ENGINE_STATEMENT *NestStatement; Link = GetFirstNode (&FormData->StatementListOSF); while (!IsNull (&FormData->StatementListOSF, Link)) { Statement = FORM_DISPLAY_ENGINE_STATEMENT_FROM_LINK (Link); - Link = GetNextNode (&FormData->StatementListOSF, Link); + Link = GetNextNode (&FormData->StatementListOSF, Link); - ProcessUserOpcode(Statement->OpCode); + ProcessUserOpcode (Statement->OpCode); } Link = GetFirstNode (&FormData->StatementListHead); while (!IsNull (&FormData->StatementListHead, Link)) { Statement = FORM_DISPLAY_ENGINE_STATEMENT_FROM_LINK (Link); - Link = GetNextNode (&FormData->StatementListHead, Link); + Link = GetNextNode (&FormData->StatementListHead, Link); - ProcessUserOpcode(Statement->OpCode); + ProcessUserOpcode (Statement->OpCode); NestLink = GetFirstNode (&Statement->NestStatementList); while (!IsNull (&Statement->NestStatementList, NestLink)) { NestStatement = FORM_DISPLAY_ENGINE_STATEMENT_FROM_LINK (NestLink); - NestLink = GetNextNode (&Statement->NestStatementList, NestLink); + NestLink = GetNextNode (&Statement->NestStatementList, NestLink); - ProcessUserOpcode(NestStatement->OpCode); + ProcessUserOpcode (NestStatement->OpCode); } - } } @@ -382,21 +388,21 @@ ProcessExternedOpcode ( **/ EFI_STATUS ScreenDiemensionInfoValidate ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ) { - LIST_ENTRY *Link; - UINTN Index; + LIST_ENTRY *Link; + UINTN Index; // // Calculate total number of Register HotKeys. // Index = 0; - if (!IsListEmpty (&FormData->HotKeyListHead)){ - Link = GetFirstNode (&FormData->HotKeyListHead); + if (!IsListEmpty (&FormData->HotKeyListHead)) { + Link = GetFirstNode (&FormData->HotKeyListHead); while (!IsNull (&FormData->HotKeyListHead, Link)) { Link = GetNextNode (&FormData->HotKeyListHead, Link); - Index ++; + Index++; } } @@ -405,7 +411,6 @@ ScreenDiemensionInfoValidate ( // gFooterHeight = FOOTER_HEIGHT + (Index / 3); - ZeroMem (&gScreenDimensions, sizeof (EFI_SCREEN_DESCRIPTOR)); gST->ConOut->QueryMode ( gST->ConOut, @@ -420,7 +425,8 @@ ScreenDiemensionInfoValidate ( if (FormData->ScreenDimensions != NULL) { if ((gScreenDimensions.RightColumn < FormData->ScreenDimensions->RightColumn) || (gScreenDimensions.BottomRow < FormData->ScreenDimensions->BottomRow) - ) { + ) + { return EFI_INVALID_PARAMETER; } else { // @@ -430,8 +436,9 @@ ScreenDiemensionInfoValidate ( (FormData->ScreenDimensions->BottomRow > FormData->ScreenDimensions->TopRow) && ((FormData->ScreenDimensions->RightColumn - FormData->ScreenDimensions->LeftColumn) > 2) && ((FormData->ScreenDimensions->BottomRow - FormData->ScreenDimensions->TopRow) > STATUS_BAR_HEIGHT + - FRONT_PAGE_HEADER_HEIGHT + gFooterHeight + 3)) { - CopyMem (&gScreenDimensions, (VOID *) FormData->ScreenDimensions, sizeof (EFI_SCREEN_DESCRIPTOR)); + FRONT_PAGE_HEADER_HEIGHT + gFooterHeight + 3)) + { + CopyMem (&gScreenDimensions, (VOID *)FormData->ScreenDimensions, sizeof (EFI_SCREEN_DESCRIPTOR)); } else { return EFI_INVALID_PARAMETER; } @@ -453,8 +460,8 @@ ScreenDiemensionInfoValidate ( **/ CHAR16 * LibGetToken ( - IN EFI_STRING_ID Token, - IN EFI_HII_HANDLE HiiHandle + IN EFI_STRING_ID Token, + IN EFI_HII_HANDLE HiiHandle ) { EFI_STRING String; @@ -465,10 +472,9 @@ LibGetToken ( ASSERT (String != NULL); } - return (CHAR16 *) String; + return (CHAR16 *)String; } - /** Count the storage space of a Unicode string. @@ -487,31 +493,32 @@ LibGetToken ( **/ UINTN LibGetStringWidth ( - IN CHAR16 *String + IN CHAR16 *String ) { - UINTN Index; - UINTN Count; - UINTN IncrementValue; + UINTN Index; + UINTN Count; + UINTN IncrementValue; ASSERT (String != NULL); if (String == NULL) { return 0; } - Index = 0; - Count = 0; - IncrementValue = 1; + Index = 0; + Count = 0; + IncrementValue = 1; do { // // Advance to the null-terminator or to the first width directive // - for (; - (String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); - Index++, Count = Count + IncrementValue - ) - ; + for ( ; + (String[Index] != NARROW_CHAR) && (String[Index] != WIDE_CHAR) && (String[Index] != 0); + Index++, Count = Count + IncrementValue + ) + { + } // // We hit the null-terminator, we now have a count @@ -519,6 +526,7 @@ LibGetStringWidth ( if (String[Index] == 0) { break; } + // // We encountered a narrow directive - strip it from the size calculation since it doesn't get printed // and also set the flag that determines what we increment by.(if narrow, increment by 1, if wide increment by 2) @@ -555,8 +563,8 @@ LibGetStringWidth ( **/ VOID PrintHotKeyHelpString ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - IN BOOLEAN SetState + IN FORM_DISPLAY_ENGINE_FORM *FormData, + IN BOOLEAN SetState ) { UINTN CurrentCol; @@ -573,9 +581,9 @@ PrintHotKeyHelpString ( CHAR16 *ColumnStr; CopyMem (&LocalScreen, &gScreenDimensions, sizeof (EFI_SCREEN_DESCRIPTOR)); - ColumnWidth = (LocalScreen.RightColumn - LocalScreen.LeftColumn) / 3; - BottomRowOfHotKeyHelp = LocalScreen.BottomRow - STATUS_BAR_HEIGHT - 3; - ColumnStr = gLibEmptyString; + ColumnWidth = (LocalScreen.RightColumn - LocalScreen.LeftColumn) / 3; + BottomRowOfHotKeyHelp = LocalScreen.BottomRow - STATUS_BAR_HEIGHT - 3; + ColumnStr = gLibEmptyString; // // Calculate total number of Register HotKeys. @@ -598,6 +606,7 @@ PrintHotKeyHelpString ( CurrentCol = LocalScreen.LeftColumn + 2; ColumnIndexWidth = ColumnWidth - 2; } + CurrentRow = BottomRowOfHotKeyHelp - Index / 3; // @@ -605,7 +614,7 @@ PrintHotKeyHelpString ( // BakChar = L'\0'; if (StrLen (HotKey->HelpString) > ColumnIndexWidth) { - BakChar = HotKey->HelpString[ColumnIndexWidth]; + BakChar = HotKey->HelpString[ColumnIndexWidth]; HotKey->HelpString[ColumnIndexWidth] = L'\0'; } @@ -615,16 +624,18 @@ PrintHotKeyHelpString ( if (SetState) { ColumnStr = HotKey->HelpString; } + PrintStringAtWithWidth (CurrentCol, CurrentRow, ColumnStr, ColumnIndexWidth); if (BakChar != L'\0') { HotKey->HelpString[ColumnIndexWidth] = BakChar; } + // // Get Next Hot Key. // Link = GetNextNode (&FormData->HotKeyListHead, Link); - Index ++; + Index++; } if (SetState) { @@ -636,9 +647,10 @@ PrintHotKeyHelpString ( if (ColumnIndex == 0) { CurrentCol = LocalScreen.LeftColumn + 2 * ColumnWidth; ColumnIndexWidth = ColumnWidth - 1; - ColumnIndex ++; + ColumnIndex++; PrintStringAtWithWidth (CurrentCol, CurrentRow, gLibEmptyString, ColumnIndexWidth); } + if (ColumnIndex == 1) { CurrentCol = LocalScreen.LeftColumn + ColumnWidth; ColumnIndexWidth = ColumnWidth; @@ -658,34 +670,34 @@ PrintHotKeyHelpString ( **/ UINT64 LibGetFieldFromNum ( - IN EFI_IFR_OP_HEADER *OpCode + IN EFI_IFR_OP_HEADER *OpCode ) { - EFI_IFR_NUMERIC *NumericOp; - UINT64 Step; + EFI_IFR_NUMERIC *NumericOp; + UINT64 Step; - NumericOp = (EFI_IFR_NUMERIC *) OpCode; + NumericOp = (EFI_IFR_NUMERIC *)OpCode; switch (NumericOp->Flags & EFI_IFR_NUMERIC_SIZE) { - case EFI_IFR_NUMERIC_SIZE_1: - Step = NumericOp->data.u8.Step; - break; + case EFI_IFR_NUMERIC_SIZE_1: + Step = NumericOp->data.u8.Step; + break; - case EFI_IFR_NUMERIC_SIZE_2: - Step = NumericOp->data.u16.Step; - break; + case EFI_IFR_NUMERIC_SIZE_2: + Step = NumericOp->data.u16.Step; + break; - case EFI_IFR_NUMERIC_SIZE_4: - Step = NumericOp->data.u32.Step; - break; + case EFI_IFR_NUMERIC_SIZE_4: + Step = NumericOp->data.u32.Step; + break; - case EFI_IFR_NUMERIC_SIZE_8: - Step = NumericOp->data.u64.Step; - break; + case EFI_IFR_NUMERIC_SIZE_8: + Step = NumericOp->data.u64.Step; + break; - default: - Step = 0; - break; + default: + Step = 0; + break; } return Step; @@ -700,29 +712,29 @@ InitializeLibStrings ( VOID ) { - mLibUnknownString = L"!"; - - gEnterString = LibGetToken (STRING_TOKEN (ENTER_STRING), mCDLStringPackHandle); - gEnterCommitString = LibGetToken (STRING_TOKEN (ENTER_COMMIT_STRING), mCDLStringPackHandle); - gEnterEscapeString = LibGetToken (STRING_TOKEN (ENTER_ESCAPE_STRING), mCDLStringPackHandle); - gEscapeString = LibGetToken (STRING_TOKEN (ESCAPE_STRING), mCDLStringPackHandle); - gMoveHighlight = LibGetToken (STRING_TOKEN (MOVE_HIGHLIGHT), mCDLStringPackHandle); - gDecNumericInput = LibGetToken (STRING_TOKEN (DEC_NUMERIC_INPUT), mCDLStringPackHandle); - gHexNumericInput = LibGetToken (STRING_TOKEN (HEX_NUMERIC_INPUT), mCDLStringPackHandle); - gToggleCheckBox = LibGetToken (STRING_TOKEN (TOGGLE_CHECK_BOX), mCDLStringPackHandle); - - gAreYouSure = LibGetToken (STRING_TOKEN (ARE_YOU_SURE), mCDLStringPackHandle); - gYesResponse = LibGetToken (STRING_TOKEN (ARE_YOU_SURE_YES), mCDLStringPackHandle); - gNoResponse = LibGetToken (STRING_TOKEN (ARE_YOU_SURE_NO), mCDLStringPackHandle); - gPlusString = LibGetToken (STRING_TOKEN (PLUS_STRING), mCDLStringPackHandle); - gMinusString = LibGetToken (STRING_TOKEN (MINUS_STRING), mCDLStringPackHandle); - gAdjustNumber = LibGetToken (STRING_TOKEN (ADJUST_NUMBER), mCDLStringPackHandle); - gSaveChanges = LibGetToken (STRING_TOKEN (SAVE_CHANGES), mCDLStringPackHandle); - - gLibEmptyString = LibGetToken (STRING_TOKEN (EMPTY_STRING), mCDLStringPackHandle); - - gNvUpdateMessage = LibGetToken (STRING_TOKEN (NV_UPDATE_MESSAGE), mCDLStringPackHandle); - gInputErrorMessage = LibGetToken (STRING_TOKEN (INPUT_ERROR_MESSAGE), mCDLStringPackHandle); + mLibUnknownString = L"!"; + + gEnterString = LibGetToken (STRING_TOKEN (ENTER_STRING), mCDLStringPackHandle); + gEnterCommitString = LibGetToken (STRING_TOKEN (ENTER_COMMIT_STRING), mCDLStringPackHandle); + gEnterEscapeString = LibGetToken (STRING_TOKEN (ENTER_ESCAPE_STRING), mCDLStringPackHandle); + gEscapeString = LibGetToken (STRING_TOKEN (ESCAPE_STRING), mCDLStringPackHandle); + gMoveHighlight = LibGetToken (STRING_TOKEN (MOVE_HIGHLIGHT), mCDLStringPackHandle); + gDecNumericInput = LibGetToken (STRING_TOKEN (DEC_NUMERIC_INPUT), mCDLStringPackHandle); + gHexNumericInput = LibGetToken (STRING_TOKEN (HEX_NUMERIC_INPUT), mCDLStringPackHandle); + gToggleCheckBox = LibGetToken (STRING_TOKEN (TOGGLE_CHECK_BOX), mCDLStringPackHandle); + + gAreYouSure = LibGetToken (STRING_TOKEN (ARE_YOU_SURE), mCDLStringPackHandle); + gYesResponse = LibGetToken (STRING_TOKEN (ARE_YOU_SURE_YES), mCDLStringPackHandle); + gNoResponse = LibGetToken (STRING_TOKEN (ARE_YOU_SURE_NO), mCDLStringPackHandle); + gPlusString = LibGetToken (STRING_TOKEN (PLUS_STRING), mCDLStringPackHandle); + gMinusString = LibGetToken (STRING_TOKEN (MINUS_STRING), mCDLStringPackHandle); + gAdjustNumber = LibGetToken (STRING_TOKEN (ADJUST_NUMBER), mCDLStringPackHandle); + gSaveChanges = LibGetToken (STRING_TOKEN (SAVE_CHANGES), mCDLStringPackHandle); + + gLibEmptyString = LibGetToken (STRING_TOKEN (EMPTY_STRING), mCDLStringPackHandle); + + gNvUpdateMessage = LibGetToken (STRING_TOKEN (NV_UPDATE_MESSAGE), mCDLStringPackHandle); + gInputErrorMessage = LibGetToken (STRING_TOKEN (INPUT_ERROR_MESSAGE), mCDLStringPackHandle); // // SpaceBuffer; @@ -733,7 +745,6 @@ InitializeLibStrings ( mSpaceBuffer[SPACE_BUFFER_SIZE] = L'\0'; } - /** Free the HII String. @@ -778,7 +789,7 @@ FreeLibStrings ( **/ EFI_STATUS WaitForKeyStroke ( - OUT EFI_INPUT_KEY *Key + OUT EFI_INPUT_KEY *Key ) { EFI_STATUS Status; @@ -796,10 +807,10 @@ WaitForKeyStroke ( gBS->WaitForEvent (1, &gST->ConIn->WaitForKey, &Index); } + return Status; } - /** Set Buffer to Value for Size bytes. @@ -810,9 +821,9 @@ WaitForKeyStroke ( **/ VOID LibSetUnicodeMem ( - IN VOID *Buffer, - IN UINTN Size, - IN CHAR16 Value + IN VOID *Buffer, + IN UINTN Size, + IN CHAR16 Value ) { CHAR16 *Ptr; @@ -859,12 +870,12 @@ PrintInternal ( // // For now, allocate an arbitrarily long buffer // - Buffer = AllocateZeroPool (0x10000); - BackupBuffer = AllocateZeroPool (0x10000); + Buffer = AllocateZeroPool (0x10000); + BackupBuffer = AllocateZeroPool (0x10000); ASSERT (Buffer); ASSERT (BackupBuffer); - if (Column != (UINTN) -1) { + if (Column != (UINTN)-1) { Out->SetCursorPosition (Out, Column, Row); } @@ -882,7 +893,7 @@ PrintInternal ( CharWidth = 1; do { - for (; (Buffer[Index] != NARROW_CHAR) && (Buffer[Index] != WIDE_CHAR) && (Buffer[Index] != 0); Index++) { + for ( ; (Buffer[Index] != NARROW_CHAR) && (Buffer[Index] != WIDE_CHAR) && (Buffer[Index] != 0); Index++) { BackupBuffer[Index] = Buffer[Index]; } @@ -894,7 +905,7 @@ PrintInternal ( // Print this out, we are about to switch widths // Out->OutputString (Out, &BackupBuffer[PreviousIndex]); - Count = StrLen (&BackupBuffer[PreviousIndex]); + Count = StrLen (&BackupBuffer[PreviousIndex]); PrintWidth += Count * CharWidth; TotalCount += Count; @@ -923,14 +934,13 @@ PrintInternal ( } Index++; - } while (Buffer[Index] != 0); // // We hit the end of the string - print it // Out->OutputString (Out, &BackupBuffer[PreviousIndex]); - Count = StrLen (&BackupBuffer[PreviousIndex]); + Count = StrLen (&BackupBuffer[PreviousIndex]); PrintWidth += Count * CharWidth; TotalCount += Count; if (PrintWidth < Width) { @@ -960,19 +970,18 @@ PrintInternal ( UINTN EFIAPI PrintAt ( - IN UINTN Width, - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *Fmt, + IN UINTN Width, + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *Fmt, ... ) { - VA_LIST Args; - UINTN LengthOfPrinted; + VA_LIST Args; + UINTN LengthOfPrinted; VA_START (Args, Fmt); LengthOfPrinted = PrintInternal (Width, Column, Row, gST->ConOut, Fmt, Args); VA_END (Args); return LengthOfPrinted; } - diff --git a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.h b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.h index 08a330401b..01213cb059 100644 --- a/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.h +++ b/MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLibInternal.h @@ -10,8 +10,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef __CUSTOMIZED_DISPLAY_LIB_INTERNAL_H__ #define __CUSTOMIZED_DISPLAY_LIB_INTERNAL_H__ - - #include #include @@ -47,33 +45,30 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Colors.h" +#define FORMSET_CLASS_PLATFORM_SETUP 0x0001 +#define FORMSET_CLASS_FRONT_PAGE 0x0002 - -#define FORMSET_CLASS_PLATFORM_SETUP 0x0001 -#define FORMSET_CLASS_FRONT_PAGE 0x0002 - - -#define FRONT_PAGE_HEADER_HEIGHT 6 -#define NONE_FRONT_PAGE_HEADER_HEIGHT 3 -#define FOOTER_HEIGHT 4 -#define STATUS_BAR_HEIGHT 1 +#define FRONT_PAGE_HEADER_HEIGHT 6 +#define NONE_FRONT_PAGE_HEADER_HEIGHT 3 +#define FOOTER_HEIGHT 4 +#define STATUS_BAR_HEIGHT 1 // // Screen definitions // -#define BANNER_HEIGHT 6 -#define BANNER_COLUMNS 3 -#define BANNER_LEFT_COLUMN_INDENT 1 +#define BANNER_HEIGHT 6 +#define BANNER_COLUMNS 3 +#define BANNER_LEFT_COLUMN_INDENT 1 // // Character definitions // -#define UPPER_LOWER_CASE_OFFSET 0x20 +#define UPPER_LOWER_CASE_OFFSET 0x20 // // This is the Input Error Message // -#define INPUT_ERROR 1 +#define INPUT_ERROR 1 // // This is the NV RAM update required Message @@ -81,35 +76,36 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define NV_UPDATE_REQUIRED 2 typedef struct { - EFI_STRING_ID Banner[BANNER_HEIGHT][BANNER_COLUMNS]; + EFI_STRING_ID Banner[BANNER_HEIGHT][BANNER_COLUMNS]; } BANNER_DATA; -extern UINT16 gClassOfVfr; // Formset class information -extern BANNER_DATA *gBannerData; -extern EFI_SCREEN_DESCRIPTOR gScreenDimensions; -extern UINTN gFooterHeight; +extern UINT16 gClassOfVfr; // Formset class information +extern BANNER_DATA *gBannerData; +extern EFI_SCREEN_DESCRIPTOR gScreenDimensions; +extern UINTN gFooterHeight; // // Browser Global Strings // -extern CHAR16 *gEnterString; -extern CHAR16 *gEnterCommitString; -extern CHAR16 *gEnterEscapeString; -extern CHAR16 *gEscapeString; -extern CHAR16 *gMoveHighlight; -extern CHAR16 *gDecNumericInput; -extern CHAR16 *gHexNumericInput; -extern CHAR16 *gToggleCheckBox; -extern CHAR16 *gLibEmptyString; -extern CHAR16 *gAreYouSure; -extern CHAR16 *gYesResponse; -extern CHAR16 *gNoResponse; -extern CHAR16 *gPlusString; -extern CHAR16 *gMinusString; -extern CHAR16 *gAdjustNumber; -extern CHAR16 *gSaveChanges; -extern CHAR16 *gNvUpdateMessage; -extern CHAR16 *gInputErrorMessage; +extern CHAR16 *gEnterString; +extern CHAR16 *gEnterCommitString; +extern CHAR16 *gEnterEscapeString; +extern CHAR16 *gEscapeString; +extern CHAR16 *gMoveHighlight; +extern CHAR16 *gDecNumericInput; +extern CHAR16 *gHexNumericInput; +extern CHAR16 *gToggleCheckBox; +extern CHAR16 *gLibEmptyString; +extern CHAR16 *gAreYouSure; +extern CHAR16 *gYesResponse; +extern CHAR16 *gNoResponse; +extern CHAR16 *gPlusString; +extern CHAR16 *gMinusString; +extern CHAR16 *gAdjustNumber; +extern CHAR16 *gSaveChanges; +extern CHAR16 *gNvUpdateMessage; +extern CHAR16 *gInputErrorMessage; + /** Print banner info for front page. @@ -119,7 +115,7 @@ extern CHAR16 *gInputErrorMessage; **/ VOID PrintBannerInfo ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ); /** @@ -129,7 +125,7 @@ PrintBannerInfo ( **/ VOID PrintFramework ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ); /** @@ -143,7 +139,7 @@ PrintFramework ( **/ EFI_STATUS ScreenDiemensionInfoValidate ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ); /** @@ -158,8 +154,8 @@ ScreenDiemensionInfoValidate ( **/ CHAR16 * LibGetToken ( - IN EFI_STRING_ID Token, - IN EFI_HII_HANDLE HiiHandle + IN EFI_STRING_ID Token, + IN EFI_HII_HANDLE HiiHandle ); /** @@ -180,7 +176,7 @@ LibGetToken ( **/ UINTN LibGetStringWidth ( - IN CHAR16 *String + IN CHAR16 *String ); /** @@ -192,8 +188,8 @@ LibGetStringWidth ( **/ VOID PrintHotKeyHelpString ( - IN FORM_DISPLAY_ENGINE_FORM *FormData, - IN BOOLEAN SetState + IN FORM_DISPLAY_ENGINE_FORM *FormData, + IN BOOLEAN SetState ); /** @@ -205,7 +201,7 @@ PrintHotKeyHelpString ( **/ UINT64 LibGetFieldFromNum ( - IN EFI_IFR_OP_HEADER *OpCode + IN EFI_IFR_OP_HEADER *OpCode ); /** @@ -236,7 +232,7 @@ FreeLibStrings ( **/ EFI_STATUS WaitForKeyStroke ( - OUT EFI_INPUT_KEY *Key + OUT EFI_INPUT_KEY *Key ); /** @@ -249,9 +245,9 @@ WaitForKeyStroke ( **/ VOID LibSetUnicodeMem ( - IN VOID *Buffer, - IN UINTN Size, - IN CHAR16 Value + IN VOID *Buffer, + IN UINTN Size, + IN CHAR16 Value ); /** @@ -270,10 +266,10 @@ LibSetUnicodeMem ( UINTN EFIAPI PrintAt ( - IN UINTN Width, - IN UINTN Column, - IN UINTN Row, - IN CHAR16 *Fmt, + IN UINTN Width, + IN UINTN Column, + IN UINTN Row, + IN CHAR16 *Fmt, ... ); @@ -285,7 +281,7 @@ PrintAt ( **/ VOID ProcessExternedOpcode ( - IN FORM_DISPLAY_ENGINE_FORM *FormData + IN FORM_DISPLAY_ENGINE_FORM *FormData ); #endif diff --git a/MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.c b/MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.c index e180f90e6b..8e70705eb6 100644 --- a/MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.c +++ b/MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.c @@ -58,7 +58,7 @@ InitializeDebugAgent ( BOOLEAN EFIAPI SaveAndSetDebugTimerInterrupt ( - IN BOOLEAN EnableStatus + IN BOOLEAN EnableStatus ) { return FALSE; diff --git a/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.c b/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.c index 3bc13d3407..c8ca25e87f 100644 --- a/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.c +++ b/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.c @@ -19,9 +19,9 @@ DEVICE_MANAGER_CALLBACK_DATA gDeviceManagerPrivate = { } }; -#define MAX_MAC_ADDRESS_NODE_LIST_LEN 10 +#define MAX_MAC_ADDRESS_NODE_LIST_LEN 10 -EFI_GUID mDeviceManagerGuid = DEVICE_MANAGER_FORMSET_GUID; +EFI_GUID mDeviceManagerGuid = DEVICE_MANAGER_FORMSET_GUID; // // Which Mac Address string is select @@ -40,21 +40,22 @@ HII_VENDOR_DEVICE_PATH mDeviceManagerHiiVendorDevicePath = { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, // // {102579A0-3686-466e-ACD8-80C087044F4A} // - { 0x102579a0, 0x3686, 0x466e, { 0xac, 0xd8, 0x80, 0xc0, 0x87, 0x4, 0x4f, 0x4a } } + { 0x102579a0, 0x3686, 0x466e, { 0xac, 0xd8, 0x80, 0xc0, 0x87, 0x4, 0x4f, 0x4a } + } }, { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (END_DEVICE_PATH_LENGTH), - (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8) + (UINT8)(END_DEVICE_PATH_LENGTH), + (UINT8)((END_DEVICE_PATH_LENGTH) >> 8) } } }; @@ -70,11 +71,11 @@ HII_VENDOR_DEVICE_PATH mDeviceManagerHiiVendorDevicePath = { **/ CHAR16 * DmExtractDevicePathFromHiiHandle ( - IN EFI_HII_HANDLE Handle + IN EFI_HII_HANDLE Handle ) { - EFI_STATUS Status; - EFI_HANDLE DriverHandle; + EFI_STATUS Status; + EFI_HANDLE DriverHandle; ASSERT (Handle != NULL); @@ -86,10 +87,11 @@ DmExtractDevicePathFromHiiHandle ( if (EFI_ERROR (Status)) { return NULL; } + // // Get device path string. // - return ConvertDevicePathToText(DevicePathFromHandle (DriverHandle), FALSE, FALSE); + return ConvertDevicePathToText (DevicePathFromHandle (DriverHandle), FALSE, FALSE); } /** @@ -101,25 +103,25 @@ DmExtractDevicePathFromHiiHandle ( **/ BOOLEAN -GetMacAddressString( - IN MAC_ADDR_DEVICE_PATH *MacAddressNode, - OUT CHAR16 **PBuffer +GetMacAddressString ( + IN MAC_ADDR_DEVICE_PATH *MacAddressNode, + OUT CHAR16 **PBuffer ) { - UINTN HwAddressSize; - UINTN Index; - UINT8 *HwAddress; + UINTN HwAddressSize; + UINTN Index; + UINT8 *HwAddress; EFI_DEVICE_PATH_PROTOCOL *Node; - UINT16 VlanId; - CHAR16 *String; - UINTN BufferLen; + UINT16 VlanId; + CHAR16 *String; + UINTN BufferLen; VlanId = 0; String = NULL; - ASSERT(MacAddressNode != NULL); + ASSERT (MacAddressNode != NULL); HwAddressSize = sizeof (EFI_MAC_ADDRESS); - if (MacAddressNode->IfType == 0x01 || MacAddressNode->IfType == 0x00) { + if ((MacAddressNode->IfType == 0x01) || (MacAddressNode->IfType == 0x00)) { HwAddressSize = 6; } @@ -128,13 +130,13 @@ GetMacAddressString( // The size is the Number size + ":" size + Vlan size(\XXXX) + End // BufferLen = (4 + 2 * HwAddressSize + (HwAddressSize - 1) + 5 + 1) * sizeof (CHAR16); - String = AllocateZeroPool (BufferLen); + String = AllocateZeroPool (BufferLen); if (String == NULL) { return FALSE; } *PBuffer = String; - StrCpyS(String, BufferLen / sizeof (CHAR16), L"MAC:"); + StrCpyS (String, BufferLen / sizeof (CHAR16), L"MAC:"); String += 4; // @@ -161,9 +163,10 @@ GetMacAddressString( // Node = (EFI_DEVICE_PATH_PROTOCOL *)MacAddressNode; while (!IsDevicePathEnd (Node)) { - if (Node->Type == MESSAGING_DEVICE_PATH && Node->SubType == MSG_VLAN_DP) { - VlanId = ((VLAN_DEVICE_PATH *) Node)->VlanId; + if ((Node->Type == MESSAGING_DEVICE_PATH) && (Node->SubType == MSG_VLAN_DP)) { + VlanId = ((VLAN_DEVICE_PATH *)Node)->VlanId; } + Node = NextDevicePathNode (Node); } @@ -198,19 +201,19 @@ GetMacAddressString( **/ BOOLEAN AddIdToMacDeviceList ( - IN EFI_STRING MacAddrString + IN EFI_STRING MacAddrString ) { - MENU_INFO_ITEM *TempDeviceList; - UINTN Index; - EFI_STRING StoredString; - EFI_STRING_ID PromptId; - EFI_HII_HANDLE HiiHandle; + MENU_INFO_ITEM *TempDeviceList; + UINTN Index; + EFI_STRING StoredString; + EFI_STRING_ID PromptId; + EFI_HII_HANDLE HiiHandle; - HiiHandle = gDeviceManagerPrivate.HiiHandle; + HiiHandle = gDeviceManagerPrivate.HiiHandle; TempDeviceList = NULL; - for (Index = 0; Index < mMacDeviceList.CurListLen; Index ++) { + for (Index = 0; Index < mMacDeviceList.CurListLen; Index++) { StoredString = HiiGetString (HiiHandle, mMacDeviceList.NodeList[Index].PromptId, NULL); if (StoredString == NULL) { return FALSE; @@ -224,13 +227,13 @@ AddIdToMacDeviceList ( } } - PromptId = HiiSetString(HiiHandle, 0, MacAddrString, NULL); + PromptId = HiiSetString (HiiHandle, 0, MacAddrString, NULL); // // If not in the list, save it. // if (mMacDeviceList.MaxListLen > mMacDeviceList.CurListLen + 1) { - mMacDeviceList.NodeList[mMacDeviceList.CurListLen].PromptId = PromptId; - mMacDeviceList.NodeList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID) (mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET); + mMacDeviceList.NodeList[mMacDeviceList.CurListLen].PromptId = PromptId; + mMacDeviceList.NodeList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID)(mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET); } else { mMacDeviceList.MaxListLen += MAX_MAC_ADDRESS_NODE_LIST_LEN; if (mMacDeviceList.CurListLen != 0) { @@ -246,12 +249,14 @@ AddIdToMacDeviceList ( if (TempDeviceList == NULL) { return FALSE; } - TempDeviceList[mMacDeviceList.CurListLen].PromptId = PromptId; - TempDeviceList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID) (mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET); + + TempDeviceList[mMacDeviceList.CurListLen].PromptId = PromptId; + TempDeviceList[mMacDeviceList.CurListLen].QuestionId = (EFI_QUESTION_ID)(mMacDeviceList.CurListLen + NETWORK_DEVICE_LIST_KEY_OFFSET); mMacDeviceList.NodeList = TempDeviceList; } - mMacDeviceList.CurListLen ++; + + mMacDeviceList.CurListLen++; return TRUE; } @@ -273,28 +278,29 @@ AddIdToMacDeviceList ( **/ BOOLEAN IsMacAddressDevicePath ( - IN VOID *Node, - IN EFI_FORM_ID NextShowFormId, - OUT BOOLEAN *NeedAddItem + IN VOID *Node, + IN EFI_FORM_ID NextShowFormId, + OUT BOOLEAN *NeedAddItem ) { - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - CHAR16 *Buffer; - BOOLEAN ReturnVal; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + CHAR16 *Buffer; + BOOLEAN ReturnVal; ASSERT (Node != NULL); *NeedAddItem = FALSE; ReturnVal = FALSE; - Buffer = NULL; + Buffer = NULL; - DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Node; + DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)Node; // // find the partition device path node // while (!IsDevicePathEnd (DevicePath)) { if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && - (DevicePathSubType (DevicePath) == MSG_MAC_ADDR_DP)) { + (DevicePathSubType (DevicePath) == MSG_MAC_ADDR_DP)) + { ReturnVal = TRUE; if (DEVICE_MANAGER_FORM_ID == NextShowFormId) { @@ -302,7 +308,7 @@ IsMacAddressDevicePath ( break; } - if (!GetMacAddressString((MAC_ADDR_DEVICE_PATH*)DevicePath, &Buffer)) { + if (!GetMacAddressString ((MAC_ADDR_DEVICE_PATH *)DevicePath, &Buffer)) { break; } @@ -310,6 +316,7 @@ IsMacAddressDevicePath ( if (StrCmp (Buffer, mSelectedMacAddrString) == 0) { *NeedAddItem = TRUE; } + break; } @@ -321,9 +328,11 @@ IsMacAddressDevicePath ( if (AddIdToMacDeviceList (Buffer)) { *NeedAddItem = TRUE; } + break; } } + DevicePath = NextDevicePathNode (DevicePath); } @@ -347,40 +356,43 @@ IsMacAddressDevicePath ( **/ BOOLEAN IsNeedAddNetworkMenu ( - IN EFI_HII_HANDLE Handle, - IN EFI_FORM_ID NextShowFormId, - OUT UINTN *ItemCount + IN EFI_HII_HANDLE Handle, + IN EFI_FORM_ID NextShowFormId, + OUT UINTN *ItemCount ) { - EFI_STATUS Status; - UINTN EntryCount; - UINTN Index; - EFI_HANDLE DriverHandle; - EFI_HANDLE ControllerHandle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; - EFI_DEVICE_PATH_PROTOCOL *ChildDevicePath; - EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; - BOOLEAN IsNeedAdd; - - IsNeedAdd = FALSE; + EFI_STATUS Status; + UINTN EntryCount; + UINTN Index; + EFI_HANDLE DriverHandle; + EFI_HANDLE ControllerHandle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *TmpDevicePath; + EFI_DEVICE_PATH_PROTOCOL *ChildDevicePath; + EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfoBuffer; + BOOLEAN IsNeedAdd; + + IsNeedAdd = FALSE; OpenInfoBuffer = NULL; if ((Handle == NULL) || (ItemCount == NULL)) { return FALSE; } + *ItemCount = 0; Status = gHiiDatabase->GetPackageListHandle (gHiiDatabase, Handle, &DriverHandle); if (EFI_ERROR (Status)) { return FALSE; } + // // Get the device path by the got Driver handle . // - Status = gBS->HandleProtocol (DriverHandle, &gEfiDevicePathProtocolGuid, (VOID **) &DevicePath); + Status = gBS->HandleProtocol (DriverHandle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePath); if (EFI_ERROR (Status)) { return FALSE; } + TmpDevicePath = DevicePath; // @@ -389,10 +401,11 @@ IsNeedAddNetworkMenu ( // add this info to the menu and return. // Else check more about the child handle devcie path. // - if (IsMacAddressDevicePath(TmpDevicePath, NextShowFormId,&IsNeedAdd)) { + if (IsMacAddressDevicePath (TmpDevicePath, NextShowFormId, &IsNeedAdd)) { if ((NETWORK_DEVICE_LIST_FORM_ID == NextShowFormId) && IsNeedAdd) { (*ItemCount) = 1; } + return IsNeedAdd; } @@ -401,7 +414,7 @@ IsNeedAddNetworkMenu ( // And the child handle has the network devcie connected. // TmpDevicePath = DevicePath; - Status = gBS->LocateDevicePath(&gEfiDevicePathProtocolGuid, &TmpDevicePath, &ControllerHandle); + Status = gBS->LocateDevicePath (&gEfiDevicePathProtocolGuid, &TmpDevicePath, &ControllerHandle); if (EFI_ERROR (Status)) { return FALSE; } @@ -437,7 +450,7 @@ IsNeedAddNetworkMenu ( Status = gBS->OpenProtocol ( OpenInfoBuffer[Index].ControllerHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &ChildDevicePath, + (VOID **)&ChildDevicePath, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -449,7 +462,7 @@ IsNeedAddNetworkMenu ( // // Check whether this device path include mac address device path. // - if (!IsMacAddressDevicePath(ChildDevicePath, NextShowFormId,&IsNeedAdd)) { + if (!IsMacAddressDevicePath (ChildDevicePath, NextShowFormId, &IsNeedAdd)) { // // If this path not has mac address path, check the other. // @@ -462,6 +475,7 @@ IsNeedAddNetworkMenu ( if (IsNeedAdd) { (*ItemCount) += 1; } + continue; } else { // @@ -477,6 +491,7 @@ Done: if (OpenInfoBuffer != NULL) { FreePool (OpenInfoBuffer); } + return IsNeedAdd; } @@ -487,42 +502,42 @@ Done: **/ VOID -CreateDeviceManagerForm( - IN EFI_FORM_ID NextShowFormId -) +CreateDeviceManagerForm ( + IN EFI_FORM_ID NextShowFormId + ) { - UINTN Index; - EFI_STRING String; - EFI_STRING_ID Token; - EFI_STRING_ID TokenHelp; - EFI_HII_HANDLE *HiiHandles; - EFI_HII_HANDLE HiiHandle; - EFI_GUID FormSetGuid; - VOID *StartOpCodeHandle; - VOID *EndOpCodeHandle; - EFI_IFR_GUID_LABEL *StartLabel; - EFI_IFR_GUID_LABEL *EndLabel; - BOOLEAN AddNetworkMenu; - UINTN AddItemCount; - UINTN NewStringLen; - EFI_STRING NewStringTitle; - CHAR16 *DevicePathStr; - EFI_STRING_ID DevicePathId; - EFI_IFR_FORM_SET *Buffer; - UINTN BufferSize; - UINT8 ClassGuidNum; - EFI_GUID *ClassGuid; - UINTN TempSize; - UINT8 *Ptr; - EFI_STATUS Status; - - TempSize =0; + UINTN Index; + EFI_STRING String; + EFI_STRING_ID Token; + EFI_STRING_ID TokenHelp; + EFI_HII_HANDLE *HiiHandles; + EFI_HII_HANDLE HiiHandle; + EFI_GUID FormSetGuid; + VOID *StartOpCodeHandle; + VOID *EndOpCodeHandle; + EFI_IFR_GUID_LABEL *StartLabel; + EFI_IFR_GUID_LABEL *EndLabel; + BOOLEAN AddNetworkMenu; + UINTN AddItemCount; + UINTN NewStringLen; + EFI_STRING NewStringTitle; + CHAR16 *DevicePathStr; + EFI_STRING_ID DevicePathId; + EFI_IFR_FORM_SET *Buffer; + UINTN BufferSize; + UINT8 ClassGuidNum; + EFI_GUID *ClassGuid; + UINTN TempSize; + UINT8 *Ptr; + EFI_STATUS Status; + + TempSize = 0; BufferSize = 0; - Buffer = NULL; + Buffer = NULL; - HiiHandle = gDeviceManagerPrivate.HiiHandle; + HiiHandle = gDeviceManagerPrivate.HiiHandle; AddNetworkMenu = FALSE; - AddItemCount = 0; + AddItemCount = 0; // // If need show the Network device list form, clear the old save list first. // @@ -538,8 +553,9 @@ CreateDeviceManagerForm( if (String == NULL) { return; } - NewStringLen = StrLen (mSelectedMacAddrString) * 2; - NewStringLen += (StrLen (String) + 2) * 2; + + NewStringLen = StrLen (mSelectedMacAddrString) * 2; + NewStringLen += (StrLen (String) + 2) * 2; NewStringTitle = AllocatePool (NewStringLen); UnicodeSPrint (NewStringTitle, NewStringLen, L"%s %s", String, mSelectedMacAddrString); HiiSetString (HiiHandle, STRING_TOKEN (STR_FORM_NETWORK_DEVICE_TITLE), NewStringTitle, NULL); @@ -559,17 +575,17 @@ CreateDeviceManagerForm( // // Create Hii Extend Label OpCode as the start opcode // - StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + StartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; // // According to the next show Form id(mNextShowFormId) to decide which form need to update. // - StartLabel->Number = (UINT16) (LABEL_FORM_ID_OFFSET + NextShowFormId); + StartLabel->Number = (UINT16)(LABEL_FORM_ID_OFFSET + NextShowFormId); // // Create Hii Extend Label OpCode as the end opcode // - EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + EndLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; EndLabel->Number = LABEL_END; @@ -583,23 +599,24 @@ CreateDeviceManagerForm( // Search for formset of each class type // for (Index = 0; HiiHandles[Index] != NULL; Index++) { - Status = HiiGetFormSetFromHiiHandle(HiiHandles[Index], &Buffer,&BufferSize); - if (EFI_ERROR (Status)){ + Status = HiiGetFormSetFromHiiHandle (HiiHandles[Index], &Buffer, &BufferSize); + if (EFI_ERROR (Status)) { continue; } + Ptr = (UINT8 *)Buffer; - while(TempSize < BufferSize) { - TempSize += ((EFI_IFR_OP_HEADER *) Ptr)->Length; - if (((EFI_IFR_OP_HEADER *) Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)){ - Ptr += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + while (TempSize < BufferSize) { + TempSize += ((EFI_IFR_OP_HEADER *)Ptr)->Length; + if (((EFI_IFR_OP_HEADER *)Ptr)->Length <= OFFSET_OF (EFI_IFR_FORM_SET, Flags)) { + Ptr += ((EFI_IFR_OP_HEADER *)Ptr)->Length; continue; } - ClassGuidNum = (UINT8) (((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); - ClassGuid = (EFI_GUID *) (VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); + ClassGuidNum = (UINT8)(((EFI_IFR_FORM_SET *)Ptr)->Flags & 0x3); + ClassGuid = (EFI_GUID *)(VOID *)(Ptr + sizeof (EFI_IFR_FORM_SET)); while (ClassGuidNum-- > 0) { - if (CompareGuid (&gEfiHiiPlatformSetupFormsetGuid, ClassGuid)== 0) { - ClassGuid ++; + if (CompareGuid (&gEfiHiiPlatformSetupFormsetGuid, ClassGuid) == 0) { + ClassGuid++; continue; } @@ -608,6 +625,7 @@ CreateDeviceManagerForm( String = HiiGetString (HiiHandle, STRING_TOKEN (STR_MISSING_STRING), NULL); ASSERT (String != NULL); } + Token = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); @@ -616,15 +634,16 @@ CreateDeviceManagerForm( String = HiiGetString (HiiHandle, STRING_TOKEN (STR_MISSING_STRING), NULL); ASSERT (String != NULL); } + TokenHelp = HiiSetString (HiiHandle, 0, String, NULL); FreePool (String); - CopyMem (&FormSetGuid, &((EFI_IFR_FORM_SET *) Ptr)->Guid, sizeof (EFI_GUID)); + CopyMem (&FormSetGuid, &((EFI_IFR_FORM_SET *)Ptr)->Guid, sizeof (EFI_GUID)); // // Network device process // - if (IsNeedAddNetworkMenu (HiiHandles[Index], NextShowFormId,&AddItemCount)) { + if (IsNeedAddNetworkMenu (HiiHandles[Index], NextShowFormId, &AddItemCount)) { if (NextShowFormId == DEVICE_MANAGER_FORM_ID) { // // Only show one menu item "Network Config" in the device manger form. @@ -637,8 +656,8 @@ CreateDeviceManagerForm( STRING_TOKEN (STR_FORM_NETWORK_DEVICE_LIST_TITLE), STRING_TOKEN (STR_FORM_NETWORK_DEVICE_LIST_HELP), EFI_IFR_FLAG_CALLBACK, - (EFI_QUESTION_ID) QUESTION_NETWORK_DEVICE_ID - ); + (EFI_QUESTION_ID)QUESTION_NETWORK_DEVICE_ID + ); } } else if (NextShowFormId == NETWORK_DEVICE_LIST_FORM_ID) { // @@ -652,63 +671,67 @@ CreateDeviceManagerForm( STRING_TOKEN (STR_NETWORK_DEVICE_HELP), EFI_IFR_FLAG_CALLBACK, mMacDeviceList.NodeList[mMacDeviceList.CurListLen - AddItemCount].QuestionId - ); + ); AddItemCount -= 1; } } else if (NextShowFormId == NETWORK_DEVICE_FORM_ID) { // // In network device form, only the selected mac address device need to be show. // - DevicePathStr = DmExtractDevicePathFromHiiHandle(HiiHandles[Index]); + DevicePathStr = DmExtractDevicePathFromHiiHandle (HiiHandles[Index]); DevicePathId = 0; - if (DevicePathStr != NULL){ + if (DevicePathStr != NULL) { DevicePathId = HiiSetString (HiiHandle, 0, DevicePathStr, NULL); - FreePool(DevicePathStr); + FreePool (DevicePathStr); } + HiiCreateGotoExOpCode ( StartOpCodeHandle, 0, Token, TokenHelp, 0, - (EFI_QUESTION_ID) (Index + DEVICE_KEY_OFFSET), + (EFI_QUESTION_ID)(Index + DEVICE_KEY_OFFSET), 0, &FormSetGuid, DevicePathId - ); + ); } } else { // // Not network device process, only need to show at device manger form. // if (NextShowFormId == DEVICE_MANAGER_FORM_ID) { - DevicePathStr = DmExtractDevicePathFromHiiHandle(HiiHandles[Index]); + DevicePathStr = DmExtractDevicePathFromHiiHandle (HiiHandles[Index]); DevicePathId = 0; - if (DevicePathStr != NULL){ + if (DevicePathStr != NULL) { DevicePathId = HiiSetString (HiiHandle, 0, DevicePathStr, NULL); - FreePool(DevicePathStr); + FreePool (DevicePathStr); } + HiiCreateGotoExOpCode ( StartOpCodeHandle, 0, Token, TokenHelp, 0, - (EFI_QUESTION_ID) (Index + DEVICE_KEY_OFFSET), + (EFI_QUESTION_ID)(Index + DEVICE_KEY_OFFSET), 0, &FormSetGuid, DevicePathId - ); + ); } } + break; } - Ptr += ((EFI_IFR_OP_HEADER *) Ptr)->Length; + Ptr += ((EFI_IFR_OP_HEADER *)Ptr)->Length; } - FreePool(Buffer); - Buffer = NULL; - TempSize = 0; + + FreePool (Buffer); + Buffer = NULL; + TempSize = 0; BufferSize = 0; } @@ -750,15 +773,16 @@ CreateDeviceManagerForm( EFI_STATUS EFIAPI DeviceManagerExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { - if (Progress == NULL || Results == NULL) { + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } + *Progress = Request; return EFI_NOT_FOUND; } @@ -781,12 +805,12 @@ DeviceManagerExtractConfig ( EFI_STATUS EFIAPI DeviceManagerRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - if (Configuration == NULL || Progress == NULL) { + if ((Configuration == NULL) || (Progress == NULL)) { return EFI_INVALID_PARAMETER; } @@ -814,15 +838,15 @@ DeviceManagerRouteConfig ( EFI_STATUS EFIAPI DeviceManagerCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - UINTN CurIndex; + UINTN CurIndex; if (Action != EFI_BROWSER_ACTION_CHANGING) { // @@ -830,21 +854,24 @@ DeviceManagerCallback ( // return EFI_UNSUPPORTED; } + if ((Value == NULL) || (ActionRequest == NULL)) { return EFI_INVALID_PARAMETER; } + if ((QuestionId < MAX_KEY_SECTION_LEN + NETWORK_DEVICE_LIST_KEY_OFFSET) && (QuestionId >= NETWORK_DEVICE_LIST_KEY_OFFSET)) { // // If user select the mac address, need to record mac address string to support next form show. // - for (CurIndex = 0; CurIndex < mMacDeviceList.CurListLen; CurIndex ++) { + for (CurIndex = 0; CurIndex < mMacDeviceList.CurListLen; CurIndex++) { if (mMacDeviceList.NodeList[CurIndex].QuestionId == QuestionId) { - mSelectedMacAddrString = HiiGetString (gDeviceManagerPrivate.HiiHandle, mMacDeviceList.NodeList[CurIndex].PromptId, NULL); + mSelectedMacAddrString = HiiGetString (gDeviceManagerPrivate.HiiHandle, mMacDeviceList.NodeList[CurIndex].PromptId, NULL); } } - CreateDeviceManagerForm(NETWORK_DEVICE_FORM_ID); - } else if(QuestionId == QUESTION_NETWORK_DEVICE_ID){ - CreateDeviceManagerForm(NETWORK_DEVICE_LIST_FORM_ID); + + CreateDeviceManagerForm (NETWORK_DEVICE_FORM_ID); + } else if (QuestionId == QUESTION_NETWORK_DEVICE_ID) { + CreateDeviceManagerForm (NETWORK_DEVICE_LIST_FORM_ID); } return EFI_SUCCESS; @@ -863,33 +890,33 @@ DeviceManagerCallback ( EFI_STATUS EFIAPI DeviceManagerUiLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable -) + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) { - EFI_STATUS Status; + EFI_STATUS Status; gDeviceManagerPrivate.DriverHandle = NULL; - Status = gBS->InstallMultipleProtocolInterfaces ( - &gDeviceManagerPrivate.DriverHandle, - &gEfiDevicePathProtocolGuid, - &mDeviceManagerHiiVendorDevicePath, - &gEfiHiiConfigAccessProtocolGuid, - &gDeviceManagerPrivate.ConfigAccess, - NULL - ); + Status = gBS->InstallMultipleProtocolInterfaces ( + &gDeviceManagerPrivate.DriverHandle, + &gEfiDevicePathProtocolGuid, + &mDeviceManagerHiiVendorDevicePath, + &gEfiHiiConfigAccessProtocolGuid, + &gDeviceManagerPrivate.ConfigAccess, + NULL + ); ASSERT_EFI_ERROR (Status); // // Publish our HII data. // gDeviceManagerPrivate.HiiHandle = HiiAddPackages ( - &mDeviceManagerGuid, - gDeviceManagerPrivate.DriverHandle, - DeviceManagerVfrBin, - DeviceManagerUiLibStrings, - NULL - ); + &mDeviceManagerGuid, + gDeviceManagerPrivate.DriverHandle, + DeviceManagerVfrBin, + DeviceManagerUiLibStrings, + NULL + ); ASSERT (gDeviceManagerPrivate.HiiHandle != NULL); // @@ -917,12 +944,12 @@ DeviceManagerUiLibConstructor ( **/ EFI_STATUS EFIAPI -DeviceManagerUiLibDestructor( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable -) +DeviceManagerUiLibDestructor ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = gBS->UninstallMultipleProtocolInterfaces ( gDeviceManagerPrivate.DriverHandle, @@ -938,4 +965,3 @@ DeviceManagerUiLibDestructor( return EFI_SUCCESS; } - diff --git a/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.h b/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.h index c53c2a1a0e..4c711234db 100644 --- a/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.h +++ b/MdeModulePkg/Library/DeviceManagerUiLib/DeviceManager.h @@ -34,18 +34,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0x3ebfa8e6, 0x511d, 0x4b5b, {0xa9, 0x5f, 0xfb, 0x38, 0x26, 0xf, 0x1c, 0x27} \ } -#define LABEL_END 0xffff -#define LABEL_FORM_ID_OFFSET 0x0100 +#define LABEL_END 0xffff +#define LABEL_FORM_ID_OFFSET 0x0100 -#define DEVICE_MANAGER_FORM_ID 0x1000 -#define NETWORK_DEVICE_LIST_FORM_ID 0x1001 -#define NETWORK_DEVICE_FORM_ID 0x1002 -#define DEVICE_KEY_OFFSET 0x4000 -#define NETWORK_DEVICE_LIST_KEY_OFFSET 0x2000 +#define DEVICE_MANAGER_FORM_ID 0x1000 +#define NETWORK_DEVICE_LIST_FORM_ID 0x1001 +#define NETWORK_DEVICE_FORM_ID 0x1002 +#define DEVICE_KEY_OFFSET 0x4000 +#define NETWORK_DEVICE_LIST_KEY_OFFSET 0x2000 -#define MAX_KEY_SECTION_LEN 0x1000 +#define MAX_KEY_SECTION_LEN 0x1000 -#define QUESTION_NETWORK_DEVICE_ID 0x3FFF +#define QUESTION_NETWORK_DEVICE_ID 0x3FFF // // These are the VFR compiler generated data representing our VFR data. // @@ -57,40 +57,40 @@ extern UINT8 DeviceManagerVfrBin[]; /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; typedef struct { - UINTN Signature; + UINTN Signature; /// /// Device Manager HII relative handles /// - EFI_HII_HANDLE HiiHandle; + EFI_HII_HANDLE HiiHandle; - EFI_HANDLE DriverHandle; + EFI_HANDLE DriverHandle; /// /// Device Manager Produced protocols /// - EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; + EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; /// /// Configuration data /// - UINT8 VideoBios; + UINT8 VideoBios; } DEVICE_MANAGER_CALLBACK_DATA; typedef struct { - EFI_STRING_ID PromptId; - EFI_QUESTION_ID QuestionId; -}MENU_INFO_ITEM; + EFI_STRING_ID PromptId; + EFI_QUESTION_ID QuestionId; +} MENU_INFO_ITEM; typedef struct { - UINTN CurListLen; - UINTN MaxListLen; - MENU_INFO_ITEM *NodeList; + UINTN CurListLen; + UINTN MaxListLen; + MENU_INFO_ITEM *NodeList; } MAC_ADDRESS_NODE_LIST; #define DEVICE_MANAGER_CALLBACK_DATA_FROM_THIS(a) \ @@ -100,8 +100,8 @@ typedef struct { DEVICE_MANAGER_CALLBACK_DATA_SIGNATURE \ ) typedef struct { - EFI_STRING_ID StringId; - UINT16 Class; + EFI_STRING_ID StringId; + UINT16 Class; } DEVICE_MANAGER_MENU_ITEM; /** @@ -129,10 +129,10 @@ typedef struct { EFI_STATUS EFIAPI DeviceManagerExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ); /** @@ -154,9 +154,9 @@ DeviceManagerExtractConfig ( EFI_STATUS EFIAPI DeviceManagerRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ); /** @@ -178,12 +178,12 @@ DeviceManagerRouteConfig ( EFI_STATUS EFIAPI DeviceManagerCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); #endif diff --git a/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c b/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c index 5f3ae6ab72..83053464e0 100644 --- a/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c +++ b/MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.c @@ -34,7 +34,7 @@ EFI_GRAPHICS_OUTPUT_PROTOCOL *mGop = NULL; // // Set to 100 percent so it is reset on first call. // -UINTN mPreviousProgress = 100; +UINTN mPreviousProgress = 100; // // Display coordinates for the progress bar. @@ -99,7 +99,7 @@ const EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION mProgressBarDefaultColor = { // Set to TRUE if a valid Graphics Output Protocol is found and the progress // bar fits under the boot logo using the current graphics mode. // -BOOLEAN mGraphicsGood = FALSE; +BOOLEAN mGraphicsGood = FALSE; /** Internal function used to find the bounds of the white logo (on black or @@ -110,7 +110,7 @@ BOOLEAN mGraphicsGood = FALSE; **/ VOID FindDim ( - VOID + VOID ) { EFI_STATUS Status; @@ -189,6 +189,7 @@ FindDim ( DEBUG ((DEBUG_INFO, "StartX found at (%d, %d) Color is: 0x%X \n", LogoX, LogoY, Pixel->Raw)); break; } + Pixel = Pixel + Width; } } @@ -204,6 +205,7 @@ FindDim ( DEBUG ((DEBUG_INFO, "EndX found at (%d, %d) Color is: 0x%X \n", LogoX, LogoY, Pixel->Raw)); break; } + Pixel = Pixel + Width; } } @@ -226,13 +228,14 @@ FindDim ( for (LogoY = 0, LogoStartY = Height; LogoY < LogoStartY; LogoY++) { Pixel = (EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION *)(Logo + (Width * LogoY)); for (LogoX = 0; LogoX < (INTN)Width; LogoX++) { - //not black or red + // not black or red if ((Pixel->Raw & mLogoDetectionColorMask.Raw) != 0x0) { LogoStartY = LogoY; - LogoEndY = LogoY; //for next loop will search from bottom side back to this row. + LogoEndY = LogoY; // for next loop will search from bottom side back to this row. DEBUG ((DEBUG_INFO, "StartY found at (%d, %d) Color is: 0x%X \n", LogoX, LogoY, Pixel->Raw)); break; } + Pixel++; } } @@ -248,6 +251,7 @@ FindDim ( DEBUG ((DEBUG_INFO, "EndY found at (%d, %d) Color is: 0x%X \n", LogoX, LogoY, Pixel->Raw)); break; } + Pixel++; } } @@ -360,7 +364,7 @@ DisplayUpdateProgress ( Status = gBS->HandleProtocol ( gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, - (VOID**)&mGop + (VOID **)&mGop ); if (EFI_ERROR (Status)) { Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&mGop); @@ -405,7 +409,9 @@ DisplayUpdateProgress ( 0 ); - DEBUG ((DEBUG_VERBOSE, "Color is 0x%X\n", + DEBUG (( + DEBUG_VERBOSE, + "Color is 0x%X\n", (Color == NULL) ? mProgressBarDefaultColor.Raw : Color->Raw )); diff --git a/MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.c b/MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.c index 960a4165fc..4823a24d0d 100644 --- a/MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.c +++ b/MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.c @@ -86,15 +86,19 @@ DisplayUpdateProgress ( if (Color->Pixel.Blue >= 0x40) { mProgressBarForegroundColor |= EFI_BLUE; } + if (Color->Pixel.Green >= 0x40) { mProgressBarForegroundColor |= EFI_GREEN; } + if (Color->Pixel.Red >= 0x40) { mProgressBarForegroundColor |= EFI_RED; } - if (Color->Pixel.Blue >= 0xC0 || Color->Pixel.Green >= 0xC0 || Color->Pixel.Red >= 0xC0) { + + if ((Color->Pixel.Blue >= 0xC0) || (Color->Pixel.Green >= 0xC0) || (Color->Pixel.Red >= 0xC0)) { mProgressBarForegroundColor |= EFI_BRIGHT; } + if (mProgressBarForegroundColor == EFI_BLACK) { mProgressBarForegroundColor = EFI_WHITE; } @@ -147,7 +151,7 @@ DisplayUpdateProgress ( // // Print remaining portion of progress bar // - for (; Index < 50; Index++) { + for ( ; Index < 50; Index++) { Print (L"%c", BLOCKELEMENT_LIGHT_SHADE); } diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.c index 060abef3ab..41b3282d29 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.c @@ -18,7 +18,7 @@ **/ BOOLEAN IsCapsuleNameCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ); /** @@ -37,16 +37,16 @@ IsCapsuleNameCapsule ( **/ EFI_PHYSICAL_ADDRESS * ValidateCapsuleNameCapsuleIntegrity ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - OUT UINTN *CapsuleNameNum + IN EFI_CAPSULE_HEADER *CapsuleHeader, + OUT UINTN *CapsuleNameNum ) { - UINT8 *CapsuleNamePtr; - UINT8 *CapsuleNameBufStart; - UINT8 *CapsuleNameBufEnd; - UINTN Index; - UINTN StringSize; - EFI_PHYSICAL_ADDRESS *CapsuleNameBuf; + UINT8 *CapsuleNamePtr; + UINT8 *CapsuleNameBufStart; + UINT8 *CapsuleNameBufEnd; + UINTN Index; + UINTN StringSize; + EFI_PHYSICAL_ADDRESS *CapsuleNameBuf; if (!IsCapsuleNameCapsule (CapsuleHeader)) { return NULL; @@ -59,14 +59,14 @@ ValidateCapsuleNameCapsuleIntegrity ( return NULL; } - *CapsuleNameNum = 0; - Index = 0; - CapsuleNameBufStart = (UINT8 *) CapsuleHeader + CapsuleHeader->HeaderSize; + *CapsuleNameNum = 0; + Index = 0; + CapsuleNameBufStart = (UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize; // // If strings are not aligned on a 16-bit boundary, reallocate memory for it. // - if (((UINTN) CapsuleNameBufStart & BIT0) != 0) { + if (((UINTN)CapsuleNameBufStart & BIT0) != 0) { CapsuleNameBufStart = AllocateCopyPool (CapsuleHeader->CapsuleImageSize - CapsuleHeader->HeaderSize, CapsuleNameBufStart); if (CapsuleNameBufStart == NULL) { return NULL; @@ -77,9 +77,9 @@ ValidateCapsuleNameCapsuleIntegrity ( CapsuleNamePtr = CapsuleNameBufStart; while (CapsuleNamePtr < CapsuleNameBufEnd) { - StringSize= StrnSizeS ((CHAR16 *) CapsuleNamePtr, (CapsuleNameBufEnd - CapsuleNamePtr)/sizeof(CHAR16)); + StringSize = StrnSizeS ((CHAR16 *)CapsuleNamePtr, (CapsuleNameBufEnd - CapsuleNamePtr)/sizeof (CHAR16)); CapsuleNamePtr += StringSize; - (*CapsuleNameNum) ++; + (*CapsuleNameNum)++; } // @@ -89,6 +89,7 @@ ValidateCapsuleNameCapsuleIntegrity ( if (CapsuleNameBufStart != (UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize) { FreePool (CapsuleNameBufStart); } + return NULL; } @@ -97,15 +98,16 @@ ValidateCapsuleNameCapsuleIntegrity ( if (CapsuleNameBufStart != (UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize) { FreePool (CapsuleNameBufStart); } + return NULL; } CapsuleNamePtr = CapsuleNameBufStart; while (CapsuleNamePtr < CapsuleNameBufEnd) { - StringSize= StrnSizeS ((CHAR16 *) CapsuleNamePtr, (CapsuleNameBufEnd - CapsuleNamePtr)/sizeof(CHAR16)); - CapsuleNameBuf[Index] = (EFI_PHYSICAL_ADDRESS)(UINTN) CapsuleNamePtr; - CapsuleNamePtr += StringSize; - Index ++; + StringSize = StrnSizeS ((CHAR16 *)CapsuleNamePtr, (CapsuleNameBufEnd - CapsuleNamePtr)/sizeof (CHAR16)); + CapsuleNameBuf[Index] = (EFI_PHYSICAL_ADDRESS)(UINTN)CapsuleNamePtr; + CapsuleNamePtr += StringSize; + Index++; } return CapsuleNameBuf; @@ -122,13 +124,13 @@ ValidateCapsuleNameCapsuleIntegrity ( static CHAR16 * UpperCaseString ( - IN CHAR16 *Str + IN CHAR16 *Str ) { CHAR16 *Cptr; for (Cptr = Str; *Cptr != L'\0'; Cptr++) { - if (L'a' <= *Cptr && *Cptr <= L'z') { + if ((L'a' <= *Cptr) && (*Cptr <= L'z')) { *Cptr = *Cptr - L'a' + L'A'; } } @@ -148,18 +150,19 @@ UpperCaseString ( static VOID GetSubStringBeforePeriod ( - IN CHAR16 *Str, - OUT CHAR16 *SubStr, - OUT UINTN *SubStrLen + IN CHAR16 *Str, + OUT CHAR16 *SubStr, + OUT UINTN *SubStrLen ) { - UINTN Index; + UINTN Index; + for (Index = 0; Str[Index] != L'.' && Str[Index] != L'\0'; Index++) { SubStr[Index] = Str[Index]; } SubStr[Index] = L'\0'; - *SubStrLen = Index; + *SubStrLen = Index; } /** @@ -173,16 +176,17 @@ GetSubStringBeforePeriod ( static VOID PadStrInTail ( - IN CHAR16 *StrBuf, - IN UINTN PadLen, - IN CHAR16 Character + IN CHAR16 *StrBuf, + IN UINTN PadLen, + IN CHAR16 Character ) { - UINTN Index; + UINTN Index; - for (Index = 0; StrBuf[Index] != L'\0'; Index++); + for (Index = 0; StrBuf[Index] != L'\0'; Index++) { + } - while(PadLen != 0) { + while (PadLen != 0) { StrBuf[Index] = Character; Index++; PadLen--; @@ -208,26 +212,27 @@ SplitFileNameExtension ( OUT CHAR16 *FileNameExtension ) { - UINTN Index; - UINTN StringLen; + UINTN Index; + UINTN StringLen; - StringLen = StrnLenS(FileName, MAX_FILE_NAME_SIZE); - for (Index = StringLen; Index > 0 && FileName[Index] != L'.'; Index--); + StringLen = StrnLenS (FileName, MAX_FILE_NAME_SIZE); + for (Index = StringLen; Index > 0 && FileName[Index] != L'.'; Index--) { + } // // No period exists. No FileName Extension // - if (Index == 0 && FileName[Index] != L'.') { + if ((Index == 0) && (FileName[Index] != L'.')) { FileNameExtension[0] = L'\0'; - Index = StringLen; + Index = StringLen; } else { - StrCpyS(FileNameExtension, MAX_FILE_NAME_SIZE, &FileName[Index+1]); + StrCpyS (FileNameExtension, MAX_FILE_NAME_SIZE, &FileName[Index+1]); } // // Copy First file name // - StrnCpyS(FileNameFirst, MAX_FILE_NAME_SIZE, FileName, Index); + StrnCpyS (FileNameFirst, MAX_FILE_NAME_SIZE, FileName, Index); FileNameFirst[Index] = L'\0'; } @@ -243,51 +248,51 @@ SplitFileNameExtension ( **/ EFI_STATUS -GetBootOptionInOrder( - OUT EFI_BOOT_MANAGER_LOAD_OPTION **OptionBuf, - OUT UINTN *OptionCount +GetBootOptionInOrder ( + OUT EFI_BOOT_MANAGER_LOAD_OPTION **OptionBuf, + OUT UINTN *OptionCount ) { - EFI_STATUS Status; - UINTN DataSize; - UINT16 BootNext; - CHAR16 BootOptionName[20]; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOrderOptionBuf; - UINTN BootOrderCount; - EFI_BOOT_MANAGER_LOAD_OPTION BootNextOptionEntry; - UINTN BootNextCount; - EFI_BOOT_MANAGER_LOAD_OPTION *TempBuf; - - BootOrderOptionBuf = NULL; - TempBuf = NULL; - BootNextCount = 0; - BootOrderCount = 0; - *OptionBuf = NULL; - *OptionCount = 0; + EFI_STATUS Status; + UINTN DataSize; + UINT16 BootNext; + CHAR16 BootOptionName[20]; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOrderOptionBuf; + UINTN BootOrderCount; + EFI_BOOT_MANAGER_LOAD_OPTION BootNextOptionEntry; + UINTN BootNextCount; + EFI_BOOT_MANAGER_LOAD_OPTION *TempBuf; + + BootOrderOptionBuf = NULL; + TempBuf = NULL; + BootNextCount = 0; + BootOrderCount = 0; + *OptionBuf = NULL; + *OptionCount = 0; // // First Get BootOption from "BootNext" // - DataSize = sizeof(BootNext); - Status = gRT->GetVariable ( - EFI_BOOT_NEXT_VARIABLE_NAME, - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - (VOID *)&BootNext - ); + DataSize = sizeof (BootNext); + Status = gRT->GetVariable ( + EFI_BOOT_NEXT_VARIABLE_NAME, + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + (VOID *)&BootNext + ); // // BootNext variable is a single UINT16 // - if (!EFI_ERROR(Status) && DataSize == sizeof(UINT16)) { + if (!EFI_ERROR (Status) && (DataSize == sizeof (UINT16))) { // // Add the boot next boot option // UnicodeSPrint (BootOptionName, sizeof (BootOptionName), L"Boot%04x", BootNext); - ZeroMem(&BootNextOptionEntry, sizeof(EFI_BOOT_MANAGER_LOAD_OPTION)); + ZeroMem (&BootNextOptionEntry, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); Status = EfiBootManagerVariableToLoadOption (BootOptionName, &BootNextOptionEntry); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { BootNextCount = 1; } } @@ -296,31 +301,31 @@ GetBootOptionInOrder( // Second get BootOption from "BootOrder" // BootOrderOptionBuf = EfiBootManagerGetLoadOptions (&BootOrderCount, LoadOptionTypeBoot); - if (BootNextCount == 0 && BootOrderCount == 0) { + if ((BootNextCount == 0) && (BootOrderCount == 0)) { return EFI_NOT_FOUND; } // // At least one BootOption is found // - TempBuf = AllocatePool(sizeof(EFI_BOOT_MANAGER_LOAD_OPTION) * (BootNextCount + BootOrderCount)); + TempBuf = AllocatePool (sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (BootNextCount + BootOrderCount)); if (TempBuf != NULL) { if (BootNextCount == 1) { - CopyMem(TempBuf, &BootNextOptionEntry, sizeof(EFI_BOOT_MANAGER_LOAD_OPTION)); + CopyMem (TempBuf, &BootNextOptionEntry, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); } if (BootOrderCount > 0) { - CopyMem(TempBuf + BootNextCount, BootOrderOptionBuf, sizeof(EFI_BOOT_MANAGER_LOAD_OPTION) * BootOrderCount); + CopyMem (TempBuf + BootNextCount, BootOrderOptionBuf, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * BootOrderCount); } *OptionBuf = TempBuf; *OptionCount = BootNextCount + BootOrderCount; - Status = EFI_SUCCESS; + Status = EFI_SUCCESS; } else { Status = EFI_OUT_OF_RESOURCES; } - FreePool(BootOrderOptionBuf); + FreePool (BootOrderOptionBuf); return Status; } @@ -335,9 +340,9 @@ GetBootOptionInOrder( **/ EFI_STATUS -GetBootOptionByNumber( - IN UINT16 Number, - OUT EFI_BOOT_MANAGER_LOAD_OPTION **OptionBuf +GetBootOptionByNumber ( + IN UINT16 Number, + OUT EFI_BOOT_MANAGER_LOAD_OPTION **OptionBuf ) { EFI_STATUS Status; @@ -372,16 +377,16 @@ GetBootOptionByNumber( **/ EFI_STATUS -GetEfiSysPartitionFromDevPath( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - OUT EFI_HANDLE *FsHandle +GetEfiSysPartitionFromDevPath ( + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + OUT EFI_HANDLE *FsHandle ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - HARDDRIVE_DEVICE_PATH *Hd; - EFI_HANDLE Handle; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + HARDDRIVE_DEVICE_PATH *Hd; + EFI_HANDLE Handle; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; // // Check if the device path contains GPT node @@ -389,12 +394,14 @@ GetEfiSysPartitionFromDevPath( TempDevicePath = DevicePath; while (!IsDevicePathEnd (TempDevicePath)) { if ((DevicePathType (TempDevicePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) { + (DevicePathSubType (TempDevicePath) == MEDIA_HARDDRIVE_DP)) + { Hd = (HARDDRIVE_DEVICE_PATH *)TempDevicePath; if (Hd->MBRType == MBR_TYPE_EFI_PARTITION_TABLE_HEADER) { break; } } + TempDevicePath = NextDevicePathNode (TempDevicePath); } @@ -407,9 +414,9 @@ GetEfiSysPartitionFromDevPath( // // Search for simple file system on this handler // - if (!EFI_ERROR(Status)) { - Status = gBS->HandleProtocol(Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { + Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); + if (!EFI_ERROR (Status)) { *FsHandle = Handle; return EFI_SUCCESS; } @@ -437,33 +444,33 @@ GetEfiSysPartitionFromDevPath( **/ EFI_STATUS -GetEfiSysPartitionFromActiveBootOption( - IN UINTN MaxRetry, - IN OUT UINT16 **LoadOptionNumber, - OUT EFI_HANDLE *FsHandle +GetEfiSysPartitionFromActiveBootOption ( + IN UINTN MaxRetry, + IN OUT UINT16 **LoadOptionNumber, + OUT EFI_HANDLE *FsHandle ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptionBuf; - UINTN BootOptionNum; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_DEVICE_PATH_PROTOCOL *CurFullPath; - EFI_DEVICE_PATH_PROTOCOL *PreFullPath; - - *FsHandle = NULL; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptionBuf; + UINTN BootOptionNum; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *CurFullPath; + EFI_DEVICE_PATH_PROTOCOL *PreFullPath; + + *FsHandle = NULL; CurFullPath = NULL; if (*LoadOptionNumber != NULL) { BootOptionNum = 1; - Status = GetBootOptionByNumber(**LoadOptionNumber, &BootOptionBuf); - if (EFI_ERROR(Status)) { + Status = GetBootOptionByNumber (**LoadOptionNumber, &BootOptionBuf); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "GetBootOptionByIndex Failed %x! No BootOption available for connection\n", Status)); return Status; } } else { - Status = GetBootOptionInOrder(&BootOptionBuf, &BootOptionNum); - if (EFI_ERROR(Status)) { + Status = GetBootOptionInOrder (&BootOptionBuf, &BootOptionNum); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "GetBootOptionInOrder Failed %x! No BootOption available for connection\n", Status)); return Status; } @@ -479,26 +486,28 @@ GetEfiSysPartitionFromActiveBootOption( // // Get the boot option from the link list // - DevicePath = BootOptionBuf[Index].FilePath; + DevicePath = BootOptionBuf[Index].FilePath; // // Skip inactive or legacy boot options // - if ((BootOptionBuf[Index].Attributes & LOAD_OPTION_ACTIVE) == 0 || - DevicePathType (DevicePath) == BBS_DEVICE_PATH) { + if (((BootOptionBuf[Index].Attributes & LOAD_OPTION_ACTIVE) == 0) || + (DevicePathType (DevicePath) == BBS_DEVICE_PATH)) + { continue; } DEBUG_CODE_BEGIN (); - CHAR16 *DevicePathStr; - - DevicePathStr = ConvertDevicePathToText(DevicePath, TRUE, TRUE); - if (DevicePathStr != NULL){ - DEBUG((DEBUG_INFO, "Try BootOption %s\n", DevicePathStr)); - FreePool(DevicePathStr); - } else { - DEBUG((DEBUG_INFO, "DevicePathToStr failed\n")); - } + CHAR16 *DevicePathStr; + + DevicePathStr = ConvertDevicePathToText (DevicePath, TRUE, TRUE); + if (DevicePathStr != NULL) { + DEBUG ((DEBUG_INFO, "Try BootOption %s\n", DevicePathStr)); + FreePool (DevicePathStr); + } else { + DEBUG ((DEBUG_INFO, "DevicePathToStr failed\n")); + } + DEBUG_CODE_END (); CurFullPath = NULL; @@ -507,7 +516,7 @@ GetEfiSysPartitionFromActiveBootOption( // do { PreFullPath = CurFullPath; - CurFullPath = EfiBootManagerGetNextLoadOptionDevicePath(DevicePath, CurFullPath); + CurFullPath = EfiBootManagerGetNextLoadOptionDevicePath (DevicePath, CurFullPath); if (PreFullPath != NULL) { FreePool (PreFullPath); @@ -522,13 +531,14 @@ GetEfiSysPartitionFromActiveBootOption( } DEBUG_CODE_BEGIN (); - CHAR16 *DevicePathStr1; + CHAR16 *DevicePathStr1; + + DevicePathStr1 = ConvertDevicePathToText (CurFullPath, TRUE, TRUE); + if (DevicePathStr1 != NULL) { + DEBUG ((DEBUG_INFO, "Full device path %s\n", DevicePathStr1)); + FreePool (DevicePathStr1); + } - DevicePathStr1 = ConvertDevicePathToText(CurFullPath, TRUE, TRUE); - if (DevicePathStr1 != NULL){ - DEBUG((DEBUG_INFO, "Full device path %s\n", DevicePathStr1)); - FreePool(DevicePathStr1); - } DEBUG_CODE_END (); // @@ -537,44 +547,44 @@ GetEfiSysPartitionFromActiveBootOption( // FullDevice could contain extra directory & file info. So don't check connection status here. // EfiBootManagerConnectDevicePath (CurFullPath, NULL); - Status = GetEfiSysPartitionFromDevPath(CurFullPath, FsHandle); + Status = GetEfiSysPartitionFromDevPath (CurFullPath, FsHandle); // // Some relocation device like USB need more time to get enumerated // - while (EFI_ERROR(Status) && MaxRetry > 0) { - EfiBootManagerConnectDevicePath(CurFullPath, NULL); + while (EFI_ERROR (Status) && MaxRetry > 0) { + EfiBootManagerConnectDevicePath (CurFullPath, NULL); // // Search for EFI system partition protocol on full device path in Boot Option // - Status = GetEfiSysPartitionFromDevPath(CurFullPath, FsHandle); - if (!EFI_ERROR(Status)) { + Status = GetEfiSysPartitionFromDevPath (CurFullPath, FsHandle); + if (!EFI_ERROR (Status)) { break; } - DEBUG((DEBUG_ERROR, "GetEfiSysPartitionFromDevPath Loop %x\n", Status)); + + DEBUG ((DEBUG_ERROR, "GetEfiSysPartitionFromDevPath Loop %x\n", Status)); // // Stall 100ms if connection failed to ensure USB stack is ready // - gBS->Stall(100000); - MaxRetry --; + gBS->Stall (100000); + MaxRetry--; } - } while(EFI_ERROR(Status)); + } while (EFI_ERROR (Status)); // // Find a qualified Simple File System // - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { break; } - } // // Return the OptionNumber of the boot option where EFI system partition is got from // if (*LoadOptionNumber == NULL) { - *LoadOptionNumber = AllocateCopyPool (sizeof(UINT16), (UINT16 *) &BootOptionBuf[Index].OptionNumber); + *LoadOptionNumber = AllocateCopyPool (sizeof (UINT16), (UINT16 *)&BootOptionBuf[Index].OptionNumber); if (*LoadOptionNumber == NULL) { Status = EFI_OUT_OF_RESOURCES; } @@ -588,20 +598,22 @@ GetEfiSysPartitionFromActiveBootOption( } DEBUG_CODE_BEGIN (); - CHAR16 *DevicePathStr2; - if (*FsHandle != NULL) { - DevicePathStr2 = ConvertDevicePathToText(CurFullPath, TRUE, TRUE); - if (DevicePathStr2 != NULL){ - DEBUG((DEBUG_INFO, "Found Active EFI System Partion on %s\n", DevicePathStr2)); - FreePool(DevicePathStr2); - } - } else { - DEBUG((DEBUG_INFO, "Failed to found Active EFI System Partion\n")); + CHAR16 *DevicePathStr2; + + if (*FsHandle != NULL) { + DevicePathStr2 = ConvertDevicePathToText (CurFullPath, TRUE, TRUE); + if (DevicePathStr2 != NULL) { + DEBUG ((DEBUG_INFO, "Found Active EFI System Partion on %s\n", DevicePathStr2)); + FreePool (DevicePathStr2); } + } else { + DEBUG ((DEBUG_INFO, "Failed to found Active EFI System Partion\n")); + } + DEBUG_CODE_END (); if (CurFullPath != NULL) { - FreePool(CurFullPath); + FreePool (CurFullPath); } // @@ -609,24 +621,23 @@ GetEfiSysPartitionFromActiveBootOption( // for (Index = 0; Index < BootOptionNum; Index++) { if (BootOptionBuf[Index].Description != NULL) { - FreePool(BootOptionBuf[Index].Description); + FreePool (BootOptionBuf[Index].Description); } if (BootOptionBuf[Index].FilePath != NULL) { - FreePool(BootOptionBuf[Index].FilePath); + FreePool (BootOptionBuf[Index].FilePath); } if (BootOptionBuf[Index].OptionalData != NULL) { - FreePool(BootOptionBuf[Index].OptionalData); + FreePool (BootOptionBuf[Index].OptionalData); } } - FreePool(BootOptionBuf); + FreePool (BootOptionBuf); return Status; } - /** This routine is called to get all file infos with in a given dir & with given file attribute, the file info is listed in alphabetical order described in UEFI spec. @@ -640,31 +651,31 @@ GetEfiSysPartitionFromActiveBootOption( **/ EFI_STATUS -GetFileInfoListInAlphabetFromDir( +GetFileInfoListInAlphabetFromDir ( IN EFI_FILE_HANDLE Dir, IN UINT64 FileAttr, OUT LIST_ENTRY *FileInfoList, OUT UINTN *FileNum ) { - EFI_STATUS Status; - FILE_INFO_ENTRY *NewFileInfoEntry; - FILE_INFO_ENTRY *TempFileInfoEntry; - EFI_FILE_INFO *FileInfo; - CHAR16 *NewFileName; - CHAR16 *ListedFileName; - CHAR16 *NewFileNameExtension; - CHAR16 *ListedFileNameExtension; - CHAR16 *TempNewSubStr; - CHAR16 *TempListedSubStr; - LIST_ENTRY *Link; - BOOLEAN NoFile; - UINTN FileCount; - UINTN IndexNew; - UINTN IndexListed; - UINTN NewSubStrLen; - UINTN ListedSubStrLen; - INTN SubStrCmpResult; + EFI_STATUS Status; + FILE_INFO_ENTRY *NewFileInfoEntry; + FILE_INFO_ENTRY *TempFileInfoEntry; + EFI_FILE_INFO *FileInfo; + CHAR16 *NewFileName; + CHAR16 *ListedFileName; + CHAR16 *NewFileNameExtension; + CHAR16 *ListedFileNameExtension; + CHAR16 *TempNewSubStr; + CHAR16 *TempListedSubStr; + LIST_ENTRY *Link; + BOOLEAN NoFile; + UINTN FileCount; + UINTN IndexNew; + UINTN IndexListed; + UINTN NewSubStrLen; + UINTN ListedSubStrLen; + INTN SubStrCmpResult; Status = EFI_SUCCESS; NewFileName = NULL; @@ -677,20 +688,21 @@ GetFileInfoListInAlphabetFromDir( NoFile = FALSE; FileCount = 0; - InitializeListHead(FileInfoList); + InitializeListHead (FileInfoList); - TempNewSubStr = (CHAR16 *) AllocateZeroPool(MAX_FILE_NAME_SIZE); - TempListedSubStr = (CHAR16 *) AllocateZeroPool(MAX_FILE_NAME_SIZE); + TempNewSubStr = (CHAR16 *)AllocateZeroPool (MAX_FILE_NAME_SIZE); + TempListedSubStr = (CHAR16 *)AllocateZeroPool (MAX_FILE_NAME_SIZE); - if (TempNewSubStr == NULL || TempListedSubStr == NULL ) { + if ((TempNewSubStr == NULL) || (TempListedSubStr == NULL)) { Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - for ( Status = FileHandleFindFirstFile(Dir, &FileInfo) - ; !EFI_ERROR(Status) && !NoFile - ; Status = FileHandleFindNextFile(Dir, FileInfo, &NoFile) - ){ + for ( Status = FileHandleFindFirstFile (Dir, &FileInfo) + ; !EFI_ERROR (Status) && !NoFile + ; Status = FileHandleFindNextFile (Dir, FileInfo, &NoFile) + ) + { if (FileInfo == NULL) { goto EXIT; } @@ -703,31 +715,33 @@ GetFileInfoListInAlphabetFromDir( } NewFileInfoEntry = NULL; - NewFileInfoEntry = (FILE_INFO_ENTRY*)AllocateZeroPool(sizeof(FILE_INFO_ENTRY)); + NewFileInfoEntry = (FILE_INFO_ENTRY *)AllocateZeroPool (sizeof (FILE_INFO_ENTRY)); if (NewFileInfoEntry == NULL) { Status = EFI_OUT_OF_RESOURCES; goto EXIT; } + NewFileInfoEntry->Signature = FILE_INFO_SIGNATURE; - NewFileInfoEntry->FileInfo = AllocateCopyPool((UINTN) FileInfo->Size, FileInfo); + NewFileInfoEntry->FileInfo = AllocateCopyPool ((UINTN)FileInfo->Size, FileInfo); if (NewFileInfoEntry->FileInfo == NULL) { - FreePool(NewFileInfoEntry); + FreePool (NewFileInfoEntry); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - NewFileInfoEntry->FileNameFirstPart = (CHAR16 *) AllocateZeroPool(MAX_FILE_NAME_SIZE); + NewFileInfoEntry->FileNameFirstPart = (CHAR16 *)AllocateZeroPool (MAX_FILE_NAME_SIZE); if (NewFileInfoEntry->FileNameFirstPart == NULL) { - FreePool(NewFileInfoEntry->FileInfo); - FreePool(NewFileInfoEntry); + FreePool (NewFileInfoEntry->FileInfo); + FreePool (NewFileInfoEntry); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - NewFileInfoEntry->FileNameSecondPart = (CHAR16 *) AllocateZeroPool(MAX_FILE_NAME_SIZE); + + NewFileInfoEntry->FileNameSecondPart = (CHAR16 *)AllocateZeroPool (MAX_FILE_NAME_SIZE); if (NewFileInfoEntry->FileNameSecondPart == NULL) { - FreePool(NewFileInfoEntry->FileInfo); - FreePool(NewFileInfoEntry->FileNameFirstPart); - FreePool(NewFileInfoEntry); + FreePool (NewFileInfoEntry->FileInfo); + FreePool (NewFileInfoEntry->FileNameFirstPart); + FreePool (NewFileInfoEntry); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } @@ -738,9 +752,9 @@ GetFileInfoListInAlphabetFromDir( // NewFileName = NewFileInfoEntry->FileNameFirstPart; NewFileNameExtension = NewFileInfoEntry->FileNameSecondPart; - SplitFileNameExtension(FileInfo->FileName, NewFileName, NewFileNameExtension); - UpperCaseString(NewFileName); - UpperCaseString(NewFileNameExtension); + SplitFileNameExtension (FileInfo->FileName, NewFileName, NewFileNameExtension); + UpperCaseString (NewFileName); + UpperCaseString (NewFileNameExtension); // // Insert capsule file in alphabetical ordered list @@ -749,7 +763,7 @@ GetFileInfoListInAlphabetFromDir( // // Get the FileInfo from the link list // - TempFileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); + TempFileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); ListedFileName = TempFileInfoEntry->FileNameFirstPart; ListedFileNameExtension = TempFileInfoEntry->FileNameSecondPart; @@ -758,25 +772,25 @@ GetFileInfoListInAlphabetFromDir( // IndexListed = 0; IndexNew = 0; - while (TRUE){ + while (TRUE) { // // First compare each substrings in NewFileName & ListedFileName between periods // - GetSubStringBeforePeriod(&NewFileName[IndexNew], TempNewSubStr, &NewSubStrLen); - GetSubStringBeforePeriod(&ListedFileName[IndexListed], TempListedSubStr, &ListedSubStrLen); + GetSubStringBeforePeriod (&NewFileName[IndexNew], TempNewSubStr, &NewSubStrLen); + GetSubStringBeforePeriod (&ListedFileName[IndexListed], TempListedSubStr, &ListedSubStrLen); if (NewSubStrLen > ListedSubStrLen) { // // Substr in NewFileName is longer. Pad tail with SPACE // - PadStrInTail(TempListedSubStr, NewSubStrLen - ListedSubStrLen, L' '); - } else if (NewSubStrLen < ListedSubStrLen){ + PadStrInTail (TempListedSubStr, NewSubStrLen - ListedSubStrLen, L' '); + } else if (NewSubStrLen < ListedSubStrLen) { // // Substr in ListedFileName is longer. Pad tail with SPACE // - PadStrInTail(TempNewSubStr, ListedSubStrLen - NewSubStrLen, L' '); + PadStrInTail (TempNewSubStr, ListedSubStrLen - NewSubStrLen, L' '); } - SubStrCmpResult = StrnCmp(TempNewSubStr, TempListedSubStr, MAX_FILE_NAME_LEN); + SubStrCmpResult = StrnCmp (TempNewSubStr, TempListedSubStr, MAX_FILE_NAME_LEN); if (SubStrCmpResult != 0) { break; } @@ -789,7 +803,7 @@ GetFileInfoListInAlphabetFromDir( // // Reach File First Name end // - if (NewFileName[IndexNew] == L'\0' || ListedFileName[IndexListed] == L'\0') { + if ((NewFileName[IndexNew] == L'\0') || (ListedFileName[IndexListed] == L'\0')) { break; } @@ -812,7 +826,7 @@ GetFileInfoListInAlphabetFromDir( // 2. if NewFileName is shorter than ListedFileName // if (NewFileName[IndexNew] == L'\0') { - if (ListedFileName[IndexListed] != L'\0' || (StrnCmp(NewFileNameExtension, ListedFileNameExtension, MAX_FILE_NAME_LEN) < 0)) { + if ((ListedFileName[IndexListed] != L'\0') || (StrnCmp (NewFileNameExtension, ListedFileNameExtension, MAX_FILE_NAME_LEN) < 0)) { break; } } @@ -829,7 +843,7 @@ GetFileInfoListInAlphabetFromDir( // else // Insert at the tail of this list (Link = FileInfoList) // - InsertTailList(Link, &NewFileInfoEntry->Link); + InsertTailList (Link, &NewFileInfoEntry->Link); FileCount++; } @@ -839,32 +853,32 @@ GetFileInfoListInAlphabetFromDir( EXIT: if (TempNewSubStr != NULL) { - FreePool(TempNewSubStr); + FreePool (TempNewSubStr); } if (TempListedSubStr != NULL) { - FreePool(TempListedSubStr); + FreePool (TempListedSubStr); } - if (EFI_ERROR(Status)) { - while(!IsListEmpty(FileInfoList)) { + if (EFI_ERROR (Status)) { + while (!IsListEmpty (FileInfoList)) { Link = FileInfoList->ForwardLink; - RemoveEntryList(Link); + RemoveEntryList (Link); TempFileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); - FreePool(TempFileInfoEntry->FileInfo); - FreePool(TempFileInfoEntry->FileNameFirstPart); - FreePool(TempFileInfoEntry->FileNameSecondPart); - FreePool(TempFileInfoEntry); + FreePool (TempFileInfoEntry->FileInfo); + FreePool (TempFileInfoEntry->FileNameFirstPart); + FreePool (TempFileInfoEntry->FileNameSecondPart); + FreePool (TempFileInfoEntry); } + *FileNum = 0; } return Status; } - /** This routine is called to get all qualified image from file from an given directory in alphabetic order. All the file image is copied to allocated boottime memory. @@ -879,38 +893,38 @@ EXIT: **/ EFI_STATUS -GetFileImageInAlphabetFromDir( - IN EFI_FILE_HANDLE Dir, - IN UINT64 FileAttr, - OUT IMAGE_INFO **FilePtr, - OUT UINTN *FileNum +GetFileImageInAlphabetFromDir ( + IN EFI_FILE_HANDLE Dir, + IN UINT64 FileAttr, + OUT IMAGE_INFO **FilePtr, + OUT UINTN *FileNum ) { - EFI_STATUS Status; - LIST_ENTRY *Link; - EFI_FILE_HANDLE FileHandle; - FILE_INFO_ENTRY *FileInfoEntry; - EFI_FILE_INFO *FileInfo; - UINTN FileCount; - IMAGE_INFO *TempFilePtrBuf; - UINTN Size; - LIST_ENTRY FileInfoList; - - FileHandle = NULL; - FileCount = 0; - TempFilePtrBuf = NULL; - *FilePtr = NULL; + EFI_STATUS Status; + LIST_ENTRY *Link; + EFI_FILE_HANDLE FileHandle; + FILE_INFO_ENTRY *FileInfoEntry; + EFI_FILE_INFO *FileInfo; + UINTN FileCount; + IMAGE_INFO *TempFilePtrBuf; + UINTN Size; + LIST_ENTRY FileInfoList; + + FileHandle = NULL; + FileCount = 0; + TempFilePtrBuf = NULL; + *FilePtr = NULL; // // Get file list in Dir in alphabetical order // - Status = GetFileInfoListInAlphabetFromDir( + Status = GetFileInfoListInAlphabetFromDir ( Dir, FileAttr, &FileInfoList, &FileCount ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "GetFileInfoListInAlphabetFromDir Failed!\n")); goto EXIT; } @@ -921,7 +935,7 @@ GetFileImageInAlphabetFromDir( goto EXIT; } - TempFilePtrBuf = (IMAGE_INFO *)AllocateZeroPool(sizeof(IMAGE_INFO) * FileCount); + TempFilePtrBuf = (IMAGE_INFO *)AllocateZeroPool (sizeof (IMAGE_INFO) * FileCount); if (TempFilePtrBuf == NULL) { Status = EFI_OUT_OF_RESOURCES; goto EXIT; @@ -938,64 +952,66 @@ GetFileImageInAlphabetFromDir( FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); FileInfo = FileInfoEntry->FileInfo; - Status = Dir->Open( + Status = Dir->Open ( Dir, &FileHandle, FileInfo->FileName, EFI_FILE_MODE_READ, 0 ); - if (EFI_ERROR(Status)){ + if (EFI_ERROR (Status)) { continue; } - Size = (UINTN)FileInfo->FileSize; - TempFilePtrBuf[FileCount].ImageAddress = AllocateZeroPool(Size); + Size = (UINTN)FileInfo->FileSize; + TempFilePtrBuf[FileCount].ImageAddress = AllocateZeroPool (Size); if (TempFilePtrBuf[FileCount].ImageAddress == NULL) { - DEBUG((DEBUG_ERROR, "Fail to allocate memory for capsule. Stop processing the rest.\n")); + DEBUG ((DEBUG_ERROR, "Fail to allocate memory for capsule. Stop processing the rest.\n")); break; } - Status = FileHandle->Read( + Status = FileHandle->Read ( FileHandle, &Size, TempFilePtrBuf[FileCount].ImageAddress ); - FileHandle->Close(FileHandle); + FileHandle->Close (FileHandle); // // Skip read error file // - if (EFI_ERROR(Status) || Size != (UINTN)FileInfo->FileSize) { + if (EFI_ERROR (Status) || (Size != (UINTN)FileInfo->FileSize)) { // // Remove this error file info accordingly // & move Link to BackLink // - Link = RemoveEntryList(Link); + Link = RemoveEntryList (Link); Link = Link->BackLink; - FreePool(FileInfoEntry->FileInfo); - FreePool(FileInfoEntry->FileNameFirstPart); - FreePool(FileInfoEntry->FileNameSecondPart); - FreePool(FileInfoEntry); + FreePool (FileInfoEntry->FileInfo); + FreePool (FileInfoEntry->FileNameFirstPart); + FreePool (FileInfoEntry->FileNameSecondPart); + FreePool (FileInfoEntry); - FreePool(TempFilePtrBuf[FileCount].ImageAddress); + FreePool (TempFilePtrBuf[FileCount].ImageAddress); TempFilePtrBuf[FileCount].ImageAddress = NULL; TempFilePtrBuf[FileCount].FileInfo = NULL; continue; } + TempFilePtrBuf[FileCount].FileInfo = FileInfo; FileCount++; } DEBUG_CODE_BEGIN (); - for (Link = FileInfoList.ForwardLink; Link != &FileInfoList; Link = Link->ForwardLink) { - FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); - FileInfo = FileInfoEntry->FileInfo; - DEBUG((DEBUG_INFO, "Successfully read capsule file %s from disk.\n", FileInfo->FileName)); - } + for (Link = FileInfoList.ForwardLink; Link != &FileInfoList; Link = Link->ForwardLink) { + FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); + FileInfo = FileInfoEntry->FileInfo; + DEBUG ((DEBUG_INFO, "Successfully read capsule file %s from disk.\n", FileInfo->FileName)); + } + DEBUG_CODE_END (); EXIT: @@ -1006,15 +1022,15 @@ EXIT: // // FileInfo will be freed by Calller // - while(!IsListEmpty(&FileInfoList)) { + while (!IsListEmpty (&FileInfoList)) { Link = FileInfoList.ForwardLink; - RemoveEntryList(Link); + RemoveEntryList (Link); FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); - FreePool(FileInfoEntry->FileNameFirstPart); - FreePool(FileInfoEntry->FileNameSecondPart); - FreePool(FileInfoEntry); + FreePool (FileInfoEntry->FileNameFirstPart); + FreePool (FileInfoEntry->FileNameSecondPart); + FreePool (FileInfoEntry); } return Status; @@ -1030,31 +1046,31 @@ EXIT: **/ EFI_STATUS -RemoveFileFromDir( - IN EFI_FILE_HANDLE Dir, - IN UINT64 FileAttr +RemoveFileFromDir ( + IN EFI_FILE_HANDLE Dir, + IN UINT64 FileAttr ) { - EFI_STATUS Status; - LIST_ENTRY *Link; - LIST_ENTRY FileInfoList; - EFI_FILE_HANDLE FileHandle; - FILE_INFO_ENTRY *FileInfoEntry; - EFI_FILE_INFO *FileInfo; - UINTN FileCount; + EFI_STATUS Status; + LIST_ENTRY *Link; + LIST_ENTRY FileInfoList; + EFI_FILE_HANDLE FileHandle; + FILE_INFO_ENTRY *FileInfoEntry; + EFI_FILE_INFO *FileInfo; + UINTN FileCount; FileHandle = NULL; // // Get file list in Dir in alphabetical order // - Status = GetFileInfoListInAlphabetFromDir( + Status = GetFileInfoListInAlphabetFromDir ( Dir, FileAttr, &FileInfoList, &FileCount ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "GetFileInfoListInAlphabetFromDir Failed!\n")); goto EXIT; } @@ -1075,30 +1091,30 @@ RemoveFileFromDir( FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); FileInfo = FileInfoEntry->FileInfo; - Status = Dir->Open( + Status = Dir->Open ( Dir, &FileHandle, FileInfo->FileName, EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0 ); - if (EFI_ERROR(Status)){ + if (EFI_ERROR (Status)) { continue; } - Status = FileHandle->Delete(FileHandle); + Status = FileHandle->Delete (FileHandle); } EXIT: - while(!IsListEmpty(&FileInfoList)) { + while (!IsListEmpty (&FileInfoList)) { Link = FileInfoList.ForwardLink; - RemoveEntryList(Link); + RemoveEntryList (Link); FileInfoEntry = CR (Link, FILE_INFO_ENTRY, Link, FILE_INFO_SIGNATURE); - FreePool(FileInfoEntry->FileInfo); - FreePool(FileInfoEntry); + FreePool (FileInfoEntry->FileInfo); + FreePool (FileInfoEntry); } return Status; @@ -1119,12 +1135,12 @@ EXIT: **/ EFI_STATUS -GetAllCapsuleOnDisk( - IN UINTN MaxRetry, - OUT IMAGE_INFO **CapsulePtr, - OUT UINTN *CapsuleNum, - OUT EFI_HANDLE *FsHandle, - OUT UINT16 *LoadOptionNumber +GetAllCapsuleOnDisk ( + IN UINTN MaxRetry, + OUT IMAGE_INFO **CapsulePtr, + OUT UINTN *CapsuleNum, + OUT EFI_HANDLE *FsHandle, + OUT UINT16 *LoadOptionNumber ) { EFI_STATUS Status; @@ -1136,52 +1152,53 @@ GetAllCapsuleOnDisk( TempOptionNumber = NULL; *CapsuleNum = 0; - Status = GetEfiSysPartitionFromActiveBootOption(MaxRetry, &TempOptionNumber, FsHandle); - if (EFI_ERROR(Status)) { + Status = GetEfiSysPartitionFromActiveBootOption (MaxRetry, &TempOptionNumber, FsHandle); + if (EFI_ERROR (Status)) { return Status; } - Status = gBS->HandleProtocol(*FsHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); - if (EFI_ERROR(Status)) { + Status = gBS->HandleProtocol (*FsHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); + if (EFI_ERROR (Status)) { return Status; } - Status = Fs->OpenVolume(Fs, &RootDir); - if (EFI_ERROR(Status)) { + Status = Fs->OpenVolume (Fs, &RootDir); + if (EFI_ERROR (Status)) { return Status; } - Status = RootDir->Open( + Status = RootDir->Open ( RootDir, &FileDir, EFI_CAPSULE_FILE_DIRECTORY, EFI_FILE_MODE_READ, 0 ); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "CodLibGetAllCapsuleOnDisk fail to open RootDir!\n")); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "CodLibGetAllCapsuleOnDisk fail to open RootDir!\n")); RootDir->Close (RootDir); return Status; } + RootDir->Close (RootDir); // // Only Load files with EFI_FILE_SYSTEM or EFI_FILE_ARCHIVE attribute // ignore EFI_FILE_READ_ONLY, EFI_FILE_HIDDEN, EFI_FILE_RESERVED, EFI_FILE_DIRECTORY // - Status = GetFileImageInAlphabetFromDir( + Status = GetFileImageInAlphabetFromDir ( FileDir, EFI_FILE_SYSTEM | EFI_FILE_ARCHIVE, CapsulePtr, CapsuleNum ); - DEBUG((DEBUG_INFO, "GetFileImageInAlphabetFromDir status %x\n", Status)); + DEBUG ((DEBUG_INFO, "GetFileImageInAlphabetFromDir status %x\n", Status)); // // Always remove file to avoid deadloop in capsule process // - Status = RemoveFileFromDir(FileDir, EFI_FILE_SYSTEM | EFI_FILE_ARCHIVE); - DEBUG((DEBUG_INFO, "RemoveFileFromDir status %x\n", Status)); + Status = RemoveFileFromDir (FileDir, EFI_FILE_SYSTEM | EFI_FILE_ARCHIVE); + DEBUG ((DEBUG_INFO, "RemoveFileFromDir status %x\n", Status)); FileDir->Close (FileDir); @@ -1205,10 +1222,10 @@ GetAllCapsuleOnDisk( **/ EFI_STATUS BuildGatherList ( - IN VOID **CapsuleBuffer, - IN UINTN *CapsuleSize, - IN UINTN CapsuleNum, - OUT EFI_CAPSULE_BLOCK_DESCRIPTOR **BlockDescriptors + IN VOID **CapsuleBuffer, + IN UINTN *CapsuleSize, + IN UINTN CapsuleNum, + OUT EFI_CAPSULE_BLOCK_DESCRIPTOR **BlockDescriptors ) { EFI_STATUS Status; @@ -1225,13 +1242,13 @@ BuildGatherList ( // // Allocate memory for the descriptors. // - BlockDescriptors1 = AllocateZeroPool (2 * sizeof (EFI_CAPSULE_BLOCK_DESCRIPTOR)); + BlockDescriptors1 = AllocateZeroPool (2 * sizeof (EFI_CAPSULE_BLOCK_DESCRIPTOR)); if (BlockDescriptors1 == NULL) { DEBUG ((DEBUG_ERROR, "BuildGatherList: failed to allocate memory for descriptors\n")); Status = EFI_OUT_OF_RESOURCES; goto ERREXIT; } else { - DEBUG ((DEBUG_INFO, "BuildGatherList: creating capsule descriptors at 0x%X\n", (UINTN) BlockDescriptors1)); + DEBUG ((DEBUG_INFO, "BuildGatherList: creating capsule descriptors at 0x%X\n", (UINTN)BlockDescriptors1)); } // @@ -1242,15 +1259,15 @@ BuildGatherList ( } if (BlockDescriptorPre != NULL) { - BlockDescriptorPre->Union.ContinuationPointer = (UINTN) BlockDescriptors1; - BlockDescriptorPre->Length = 0; + BlockDescriptorPre->Union.ContinuationPointer = (UINTN)BlockDescriptors1; + BlockDescriptorPre->Length = 0; } - BlockDescriptors1->Union.DataBlock = (UINTN) CapsuleBuffer[Index]; - BlockDescriptors1->Length = CapsuleSize[Index]; + BlockDescriptors1->Union.DataBlock = (UINTN)CapsuleBuffer[Index]; + BlockDescriptors1->Length = CapsuleSize[Index]; BlockDescriptorPre = BlockDescriptors1 + 1; - BlockDescriptors1 = NULL; + BlockDescriptors1 = NULL; } // @@ -1258,8 +1275,8 @@ BuildGatherList ( // if (BlockDescriptorPre != NULL) { BlockDescriptorPre->Union.ContinuationPointer = (UINTN)NULL; - BlockDescriptorPre->Length = 0; - *BlockDescriptors = BlockDescriptorsHeader; + BlockDescriptorPre->Length = 0; + *BlockDescriptors = BlockDescriptorsHeader; } return EFI_SUCCESS; @@ -1282,35 +1299,35 @@ ERREXIT: **/ BOOLEAN EFIAPI -CoDCheckCapsuleOnDiskFlag( +CoDCheckCapsuleOnDiskFlag ( VOID ) { - EFI_STATUS Status; - UINT64 OsIndication; - UINTN DataSize; + EFI_STATUS Status; + UINT64 OsIndication; + UINTN DataSize; // // Check File Capsule Delivery Supported Flag in OsIndication variable // OsIndication = 0; - DataSize = sizeof(UINT64); - Status = gRT->GetVariable ( - EFI_OS_INDICATIONS_VARIABLE_NAME, - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - &OsIndication - ); - if (!EFI_ERROR(Status) && - (OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) != 0) { + DataSize = sizeof (UINT64); + Status = gRT->GetVariable ( + EFI_OS_INDICATIONS_VARIABLE_NAME, + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + &OsIndication + ); + if (!EFI_ERROR (Status) && + ((OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) != 0)) + { return TRUE; } return FALSE; } - /** This routine is called to clear CapsuleOnDisk flags including OsIndications and BootNext variable. @@ -1319,40 +1336,41 @@ CoDCheckCapsuleOnDiskFlag( **/ EFI_STATUS EFIAPI -CoDClearCapsuleOnDiskFlag( +CoDClearCapsuleOnDiskFlag ( VOID ) { - EFI_STATUS Status; - UINT64 OsIndication; - UINTN DataSize; + EFI_STATUS Status; + UINT64 OsIndication; + UINTN DataSize; // // Reset File Capsule Delivery Supported Flag in OsIndication variable // OsIndication = 0; - DataSize = sizeof(UINT64); - Status = gRT->GetVariable ( - EFI_OS_INDICATIONS_VARIABLE_NAME, - &gEfiGlobalVariableGuid, - NULL, - &DataSize, - &OsIndication - ); - if (EFI_ERROR(Status) || - (OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) == 0) { + DataSize = sizeof (UINT64); + Status = gRT->GetVariable ( + EFI_OS_INDICATIONS_VARIABLE_NAME, + &gEfiGlobalVariableGuid, + NULL, + &DataSize, + &OsIndication + ); + if (EFI_ERROR (Status) || + ((OsIndication & EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED) == 0)) + { return Status; } OsIndication &= ~((UINT64)EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED); - Status = gRT->SetVariable ( - EFI_OS_INDICATIONS_VARIABLE_NAME, - &gEfiGlobalVariableGuid, - EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, - sizeof(UINT64), - &OsIndication - ); - ASSERT(!EFI_ERROR(Status)); + Status = gRT->SetVariable ( + EFI_OS_INDICATIONS_VARIABLE_NAME, + &gEfiGlobalVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, + sizeof (UINT64), + &OsIndication + ); + ASSERT (!EFI_ERROR (Status)); // // Delete BootNext variable. Capsule Process may reset system, so can't rely on Bds to clear this variable @@ -1377,7 +1395,7 @@ CoDClearCapsuleOnDiskFlag( **/ EFI_STATUS -CoDClearCapsuleRelocationInfo( +CoDClearCapsuleRelocationInfo ( VOID ) { @@ -1408,32 +1426,32 @@ CoDClearCapsuleRelocationInfo( **/ EFI_STATUS -RelocateCapsuleToDisk( - UINTN MaxRetry +RelocateCapsuleToDisk ( + UINTN MaxRetry ) { - EFI_STATUS Status; - UINTN CapsuleOnDiskNum; - UINTN Index; - UINTN DataSize; - UINT64 TotalImageSize; - UINT64 TotalImageNameSize; - IMAGE_INFO *CapsuleOnDiskBuf; - EFI_HANDLE Handle; - EFI_HANDLE TempHandle; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - UINT8 *CapsuleDataBuf; - UINT8 *CapsulePtr; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; - EFI_FILE_HANDLE RootDir; - EFI_FILE_HANDLE TempCodFile; - UINT64 TempCodFileSize; - EFI_DEVICE_PATH *TempDevicePath; - BOOLEAN RelocationInfo; - UINT16 LoadOptionNumber; - EFI_CAPSULE_HEADER FileNameCapsuleHeader; + EFI_STATUS Status; + UINTN CapsuleOnDiskNum; + UINTN Index; + UINTN DataSize; + UINT64 TotalImageSize; + UINT64 TotalImageNameSize; + IMAGE_INFO *CapsuleOnDiskBuf; + EFI_HANDLE Handle; + EFI_HANDLE TempHandle; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + UINT8 *CapsuleDataBuf; + UINT8 *CapsulePtr; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + EFI_FILE_HANDLE RootDir; + EFI_FILE_HANDLE TempCodFile; + UINT64 TempCodFileSize; + EFI_DEVICE_PATH *TempDevicePath; + BOOLEAN RelocationInfo; + UINT16 LoadOptionNumber; + EFI_CAPSULE_HEADER FileNameCapsuleHeader; RootDir = NULL; TempCodFile = NULL; @@ -1447,8 +1465,8 @@ RelocateCapsuleToDisk( // // 1. Load all Capsule On Disks in to memory // - Status = GetAllCapsuleOnDisk(MaxRetry, &CapsuleOnDiskBuf, &CapsuleOnDiskNum, &Handle, &LoadOptionNumber); - if (EFI_ERROR(Status) || CapsuleOnDiskNum == 0 || CapsuleOnDiskBuf == NULL) { + Status = GetAllCapsuleOnDisk (MaxRetry, &CapsuleOnDiskBuf, &CapsuleOnDiskNum, &Handle, &LoadOptionNumber); + if (EFI_ERROR (Status) || (CapsuleOnDiskNum == 0) || (CapsuleOnDiskBuf == NULL)) { DEBUG ((DEBUG_INFO, "RelocateCapsule: GetAllCapsuleOnDisk Status - 0x%x\n", Status)); return EFI_NOT_FOUND; } @@ -1458,9 +1476,9 @@ RelocateCapsuleToDisk( // If no platform special device path specified or the device path is invalid, use the EFI system partition where // stores the capsules as relocation device. // - if (IsDevicePathValid ((EFI_DEVICE_PATH *)PcdGetPtr(PcdCodRelocationDevPath), PcdGetSize(PcdCodRelocationDevPath))) { - Status = EfiBootManagerConnectDevicePath ((EFI_DEVICE_PATH *)PcdGetPtr(PcdCodRelocationDevPath), &TempHandle); - if (EFI_ERROR(Status)) { + if (IsDevicePathValid ((EFI_DEVICE_PATH *)PcdGetPtr (PcdCodRelocationDevPath), PcdGetSize (PcdCodRelocationDevPath))) { + Status = EfiBootManagerConnectDevicePath ((EFI_DEVICE_PATH *)PcdGetPtr (PcdCodRelocationDevPath), &TempHandle); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "RelocateCapsule: EfiBootManagerConnectDevicePath Status - 0x%x\n", Status)); goto EXIT; } @@ -1469,14 +1487,14 @@ RelocateCapsuleToDisk( // Connect all the child handle. Partition & FAT drivers are allowed in this case // gBS->ConnectController (TempHandle, NULL, NULL, TRUE); - Status = gBS->LocateHandleBuffer( + Status = gBS->LocateHandleBuffer ( ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &NumberOfHandles, &HandleBuffer ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "RelocateCapsule: LocateHandleBuffer Status - 0x%x\n", Status)); goto EXIT; } @@ -1485,19 +1503,19 @@ RelocateCapsuleToDisk( // Find first Simple File System Handle which can match PcdCodRelocationDevPath // for (Index = 0; Index < NumberOfHandles; Index++) { - Status = gBS->HandleProtocol(HandleBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **)&TempDevicePath); - if (EFI_ERROR(Status)) { + Status = gBS->HandleProtocol (HandleBuffer[Index], &gEfiDevicePathProtocolGuid, (VOID **)&TempDevicePath); + if (EFI_ERROR (Status)) { continue; } - DataSize = GetDevicePathSize((EFI_DEVICE_PATH *)PcdGetPtr(PcdCodRelocationDevPath)) - sizeof(EFI_DEVICE_PATH); - if (0 == CompareMem((EFI_DEVICE_PATH *)PcdGetPtr(PcdCodRelocationDevPath), TempDevicePath, DataSize)) { + DataSize = GetDevicePathSize ((EFI_DEVICE_PATH *)PcdGetPtr (PcdCodRelocationDevPath)) - sizeof (EFI_DEVICE_PATH); + if (0 == CompareMem ((EFI_DEVICE_PATH *)PcdGetPtr (PcdCodRelocationDevPath), TempDevicePath, DataSize)) { Handle = HandleBuffer[Index]; break; } } - FreePool(HandleBuffer); + FreePool (HandleBuffer); if (Index == NumberOfHandles) { DEBUG ((DEBUG_ERROR, "RelocateCapsule: No simple file system protocol found.\n")); @@ -1505,14 +1523,14 @@ RelocateCapsuleToDisk( } } - Status = gBS->HandleProtocol(Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo); - if (EFI_ERROR(Status) || BlockIo->Media->ReadOnly) { - DEBUG((DEBUG_ERROR, "Fail to find Capsule on Disk relocation BlockIo device or device is ReadOnly!\n")); + Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo); + if (EFI_ERROR (Status) || BlockIo->Media->ReadOnly) { + DEBUG ((DEBUG_ERROR, "Fail to find Capsule on Disk relocation BlockIo device or device is ReadOnly!\n")); goto EXIT; } - Status = gBS->HandleProtocol(Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); - if (EFI_ERROR(Status)) { + Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); + if (EFI_ERROR (Status)) { goto EXIT; } @@ -1530,40 +1548,41 @@ RelocateCapsuleToDisk( goto EXIT; } - if (MAX_ADDRESS - (UINTN)TotalImageNameSize <= StrSize(CapsuleOnDiskBuf[Index].FileInfo->FileName)) { + if (MAX_ADDRESS - (UINTN)TotalImageNameSize <= StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName)) { Status = EFI_INVALID_PARAMETER; goto EXIT; } TotalImageSize += CapsuleOnDiskBuf[Index].FileInfo->FileSize; - TotalImageNameSize += StrSize(CapsuleOnDiskBuf[Index].FileInfo->FileName); - DEBUG((DEBUG_INFO, "RelocateCapsule: %x Size %x\n",CapsuleOnDiskBuf[Index].FileInfo->FileName, CapsuleOnDiskBuf[Index].FileInfo->FileSize)); + TotalImageNameSize += StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName); + DEBUG ((DEBUG_INFO, "RelocateCapsule: %x Size %x\n", CapsuleOnDiskBuf[Index].FileInfo->FileName, CapsuleOnDiskBuf[Index].FileInfo->FileSize)); } - DEBUG((DEBUG_INFO, "RelocateCapsule: TotalImageSize %x\n", TotalImageSize)); - DEBUG((DEBUG_INFO, "RelocateCapsule: TotalImageNameSize %x\n", TotalImageNameSize)); + DEBUG ((DEBUG_INFO, "RelocateCapsule: TotalImageSize %x\n", TotalImageSize)); + DEBUG ((DEBUG_INFO, "RelocateCapsule: TotalImageNameSize %x\n", TotalImageNameSize)); - if (MAX_ADDRESS - (UINTN)TotalImageNameSize <= sizeof(UINT64) * 2 || - MAX_ADDRESS - (UINTN)TotalImageSize <= (UINTN)TotalImageNameSize + sizeof(UINT64) * 2) { + if ((MAX_ADDRESS - (UINTN)TotalImageNameSize <= sizeof (UINT64) * 2) || + (MAX_ADDRESS - (UINTN)TotalImageSize <= (UINTN)TotalImageNameSize + sizeof (UINT64) * 2)) + { Status = EFI_INVALID_PARAMETER; goto EXIT; } - TempCodFileSize = sizeof(UINT64) + TotalImageSize + sizeof(EFI_CAPSULE_HEADER) + TotalImageNameSize; + TempCodFileSize = sizeof (UINT64) + TotalImageSize + sizeof (EFI_CAPSULE_HEADER) + TotalImageNameSize; // // Check if CapsuleTotalSize. There could be reminder, so use LastBlock number directly // - if (DivU64x32(TempCodFileSize, BlockIo->Media->BlockSize) > BlockIo->Media->LastBlock) { - DEBUG((DEBUG_ERROR, "RelocateCapsule: Relocation device isn't big enough to hold all Capsule on Disk!\n")); - DEBUG((DEBUG_ERROR, "TotalImageSize = %x\n", TotalImageSize)); - DEBUG((DEBUG_ERROR, "TotalImageNameSize = %x\n", TotalImageNameSize)); - DEBUG((DEBUG_ERROR, "RelocationDev BlockSize = %x LastBlock = %x\n", BlockIo->Media->BlockSize, BlockIo->Media->LastBlock)); + if (DivU64x32 (TempCodFileSize, BlockIo->Media->BlockSize) > BlockIo->Media->LastBlock) { + DEBUG ((DEBUG_ERROR, "RelocateCapsule: Relocation device isn't big enough to hold all Capsule on Disk!\n")); + DEBUG ((DEBUG_ERROR, "TotalImageSize = %x\n", TotalImageSize)); + DEBUG ((DEBUG_ERROR, "TotalImageNameSize = %x\n", TotalImageNameSize)); + DEBUG ((DEBUG_ERROR, "RelocationDev BlockSize = %x LastBlock = %x\n", BlockIo->Media->BlockSize, BlockIo->Media->LastBlock)); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - CapsuleDataBuf = AllocatePool((UINTN) TempCodFileSize); + CapsuleDataBuf = AllocatePool ((UINTN)TempCodFileSize); if (CapsuleDataBuf == NULL) { Status = EFI_OUT_OF_RESOURCES; goto EXIT; @@ -1572,79 +1591,80 @@ RelocateCapsuleToDisk( // // First UINT64 reserved for total image size, including capsule name capsule. // - *(UINT64 *) CapsuleDataBuf = TotalImageSize + sizeof(EFI_CAPSULE_HEADER) + TotalImageNameSize; + *(UINT64 *)CapsuleDataBuf = TotalImageSize + sizeof (EFI_CAPSULE_HEADER) + TotalImageNameSize; // // Line up all the Capsule on Disk and write to relocation disk at one time. It could save some time in disk write // - for (Index = 0, CapsulePtr = CapsuleDataBuf + sizeof(UINT64); Index < CapsuleOnDiskNum; Index++) { - CopyMem(CapsulePtr, CapsuleOnDiskBuf[Index].ImageAddress, (UINTN) CapsuleOnDiskBuf[Index].FileInfo->FileSize); + for (Index = 0, CapsulePtr = CapsuleDataBuf + sizeof (UINT64); Index < CapsuleOnDiskNum; Index++) { + CopyMem (CapsulePtr, CapsuleOnDiskBuf[Index].ImageAddress, (UINTN)CapsuleOnDiskBuf[Index].FileInfo->FileSize); CapsulePtr += CapsuleOnDiskBuf[Index].FileInfo->FileSize; } // // Line the capsule header for capsule name capsule. // - CopyGuid(&FileNameCapsuleHeader.CapsuleGuid, &gEdkiiCapsuleOnDiskNameGuid); - FileNameCapsuleHeader.CapsuleImageSize = (UINT32) TotalImageNameSize + sizeof(EFI_CAPSULE_HEADER); + CopyGuid (&FileNameCapsuleHeader.CapsuleGuid, &gEdkiiCapsuleOnDiskNameGuid); + FileNameCapsuleHeader.CapsuleImageSize = (UINT32)TotalImageNameSize + sizeof (EFI_CAPSULE_HEADER); FileNameCapsuleHeader.Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; - FileNameCapsuleHeader.HeaderSize = sizeof(EFI_CAPSULE_HEADER); - CopyMem(CapsulePtr, &FileNameCapsuleHeader, FileNameCapsuleHeader.HeaderSize); + FileNameCapsuleHeader.HeaderSize = sizeof (EFI_CAPSULE_HEADER); + CopyMem (CapsulePtr, &FileNameCapsuleHeader, FileNameCapsuleHeader.HeaderSize); CapsulePtr += FileNameCapsuleHeader.HeaderSize; // // Line up all the Capsule file names. // for (Index = 0; Index < CapsuleOnDiskNum; Index++) { - CopyMem(CapsulePtr, CapsuleOnDiskBuf[Index].FileInfo->FileName, StrSize(CapsuleOnDiskBuf[Index].FileInfo->FileName)); - CapsulePtr += StrSize(CapsuleOnDiskBuf[Index].FileInfo->FileName); + CopyMem (CapsulePtr, CapsuleOnDiskBuf[Index].FileInfo->FileName, StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName)); + CapsulePtr += StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName); } // // 5. Flash all Capsules on Disk to TempCoD.tmp under RootDir // - Status = Fs->OpenVolume(Fs, &RootDir); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "RelocateCapsule: OpenVolume error. %x\n", Status)); + Status = Fs->OpenVolume (Fs, &RootDir); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "RelocateCapsule: OpenVolume error. %x\n", Status)); goto EXIT; } - Status = RootDir->Open( + Status = RootDir->Open ( RootDir, &TempCodFile, - (CHAR16 *)PcdGetPtr(PcdCoDRelocationFileName), + (CHAR16 *)PcdGetPtr (PcdCoDRelocationFileName), EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0 ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { // // Error handling code to prevent malicious code to hold this file to block capsule on disk // - TempCodFile->Delete(TempCodFile); + TempCodFile->Delete (TempCodFile); } - Status = RootDir->Open( + + Status = RootDir->Open ( RootDir, &TempCodFile, - (CHAR16 *)PcdGetPtr(PcdCoDRelocationFileName), + (CHAR16 *)PcdGetPtr (PcdCoDRelocationFileName), EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE, 0 ); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "RelocateCapsule: Open TemCoD.tmp error. %x\n", Status)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "RelocateCapsule: Open TemCoD.tmp error. %x\n", Status)); goto EXIT; } // // Always write at the begining of TempCap file // - DataSize = (UINTN) TempCodFileSize; - Status = TempCodFile->Write( - TempCodFile, - &DataSize, - CapsuleDataBuf - ); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "RelocateCapsule: Write TemCoD.tmp error. %x\n", Status)); + DataSize = (UINTN)TempCodFileSize; + Status = TempCodFile->Write ( + TempCodFile, + &DataSize, + CapsuleDataBuf + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "RelocateCapsule: Write TemCoD.tmp error. %x\n", Status)); goto EXIT; } @@ -1658,30 +1678,30 @@ RelocateCapsuleToDisk( // It is used in next reboot by TCB // RelocationInfo = TRUE; - Status = gRT->SetVariable( - COD_RELOCATION_INFO_VAR_NAME, - &gEfiCapsuleVendorGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, - sizeof (BOOLEAN), - &RelocationInfo - ); + Status = gRT->SetVariable ( + COD_RELOCATION_INFO_VAR_NAME, + &gEfiCapsuleVendorGuid, + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, + sizeof (BOOLEAN), + &RelocationInfo + ); // // Save the LoadOptionNumber of the boot option, where the capsule is relocated, // into "CodRelocationLoadOption" var. It is used in next reboot after capsule is // updated out of TCB to remove the TempCoDFile. // - Status = gRT->SetVariable( - COD_RELOCATION_LOAD_OPTION_VAR_NAME, - &gEfiCapsuleVendorGuid, - EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, - sizeof (UINT16), - &LoadOptionNumber - ); + Status = gRT->SetVariable ( + COD_RELOCATION_LOAD_OPTION_VAR_NAME, + &gEfiCapsuleVendorGuid, + EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS, + sizeof (UINT16), + &LoadOptionNumber + ); EXIT: if (CapsuleDataBuf != NULL) { - FreePool(CapsuleDataBuf); + FreePool (CapsuleDataBuf); } if (CapsuleOnDiskBuf != NULL) { @@ -1689,14 +1709,15 @@ EXIT: // Free resources allocated by CodLibGetAllCapsuleOnDisk // for (Index = 0; Index < CapsuleOnDiskNum; Index++ ) { - FreePool(CapsuleOnDiskBuf[Index].ImageAddress); - FreePool(CapsuleOnDiskBuf[Index].FileInfo); + FreePool (CapsuleOnDiskBuf[Index].ImageAddress); + FreePool (CapsuleOnDiskBuf[Index].FileInfo); } - FreePool(CapsuleOnDiskBuf); + + FreePool (CapsuleOnDiskBuf); } if (TempCodFile != NULL) { - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { TempCodFile->Delete (TempCodFile); } else { TempCodFile->Close (TempCodFile); @@ -1724,7 +1745,7 @@ EXIT: **/ EFI_STATUS RelocateCapsuleToRam ( - UINTN MaxRetry + UINTN MaxRetry ) { EFI_STATUS Status; @@ -1752,7 +1773,7 @@ RelocateCapsuleToRam ( // 1. Load all Capsule On Disks into memory // Status = GetAllCapsuleOnDisk (MaxRetry, &CapsuleOnDiskBuf, &CapsuleOnDiskNum, &Handle, NULL); - if (EFI_ERROR (Status) || CapsuleOnDiskNum == 0 || CapsuleOnDiskBuf == NULL) { + if (EFI_ERROR (Status) || (CapsuleOnDiskNum == 0) || (CapsuleOnDiskBuf == NULL)) { DEBUG ((DEBUG_ERROR, "GetAllCapsuleOnDisk Status - 0x%x\n", Status)); return EFI_NOT_FOUND; } @@ -1774,9 +1795,9 @@ RelocateCapsuleToRam ( } for (Index = 0; Index < CapsuleOnDiskNum; Index++) { - CapsuleBuffer[Index] = (VOID *)(UINTN) CapsuleOnDiskBuf[Index].ImageAddress; - CapsuleSize[Index] = (UINTN) CapsuleOnDiskBuf[Index].FileInfo->FileSize; - TotalStringSize += StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName); + CapsuleBuffer[Index] = (VOID *)(UINTN)CapsuleOnDiskBuf[Index].ImageAddress; + CapsuleSize[Index] = (UINTN)CapsuleOnDiskBuf[Index].FileInfo->FileSize; + TotalStringSize += StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName); } // If Persist Across Reset isn't supported, skip the file name strings capsule @@ -1784,6 +1805,7 @@ RelocateCapsuleToRam ( CapsulesToProcess = CapsuleOnDiskNum; goto BuildGather; } + CapsulesToProcess = CapsuleOnDiskNum + 1; FileNameCapsule = AllocateZeroPool (sizeof (EFI_CAPSULE_HEADER) + TotalStringSize); @@ -1794,41 +1816,44 @@ RelocateCapsuleToRam ( return EFI_OUT_OF_RESOURCES; } - FileNameCapsule->CapsuleImageSize = (UINT32) (sizeof (EFI_CAPSULE_HEADER) + TotalStringSize); - FileNameCapsule->Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; - FileNameCapsule->HeaderSize = sizeof (EFI_CAPSULE_HEADER); + FileNameCapsule->CapsuleImageSize = (UINT32)(sizeof (EFI_CAPSULE_HEADER) + TotalStringSize); + FileNameCapsule->Flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET; + FileNameCapsule->HeaderSize = sizeof (EFI_CAPSULE_HEADER); CopyGuid (&(FileNameCapsule->CapsuleGuid), &gEdkiiCapsuleOnDiskNameGuid); StringBuf = (UINT8 *)FileNameCapsule + FileNameCapsule->HeaderSize; - for (Index = 0; Index < CapsuleOnDiskNum; Index ++) { + for (Index = 0; Index < CapsuleOnDiskNum; Index++) { StringSize = StrSize (CapsuleOnDiskBuf[Index].FileInfo->FileName); CopyMem (StringBuf, CapsuleOnDiskBuf[Index].FileInfo->FileName, StringSize); StringBuf += StringSize; } CapsuleBuffer[CapsuleOnDiskNum] = FileNameCapsule; - CapsuleSize[CapsuleOnDiskNum] = TotalStringSize + sizeof (EFI_CAPSULE_HEADER); + CapsuleSize[CapsuleOnDiskNum] = TotalStringSize + sizeof (EFI_CAPSULE_HEADER); // // 3. Build Gather list for the capsules // BuildGather: Status = BuildGatherList (CapsuleBuffer, CapsuleSize, CapsulesToProcess, &BlockDescriptors); - if (EFI_ERROR (Status) || BlockDescriptors == NULL) { + if (EFI_ERROR (Status) || (BlockDescriptors == NULL)) { FreePool (CapsuleBuffer); FreePool (CapsuleSize); if (FileNameCapsule != NULL) { FreePool (FileNameCapsule); } + return EFI_OUT_OF_RESOURCES; } // // 4. Call UpdateCapsule() service // - Status = gRT->UpdateCapsule ((EFI_CAPSULE_HEADER **) CapsuleBuffer, - CapsulesToProcess, - (UINTN) BlockDescriptors); + Status = gRT->UpdateCapsule ( + (EFI_CAPSULE_HEADER **)CapsuleBuffer, + CapsulesToProcess, + (UINTN)BlockDescriptors + ); return Status; } @@ -1857,8 +1882,8 @@ BuildGather: **/ EFI_STATUS EFIAPI -CoDRelocateCapsule( - UINTN MaxRetry +CoDRelocateCapsule ( + UINTN MaxRetry ) { if (!PcdGetBool (PcdCapsuleOnDiskSupport)) { @@ -1877,7 +1902,7 @@ CoDRelocateCapsule( DEBUG ((DEBUG_INFO, "Capsule In Ram is supported, call gRT->UpdateCapsule().\n")); return RelocateCapsuleToRam (MaxRetry); } else { - DEBUG ((DEBUG_INFO, "Reallcoate all Capsule on Disks to %s in RootDir.\n", (CHAR16 *)PcdGetPtr(PcdCoDRelocationFileName))); + DEBUG ((DEBUG_INFO, "Reallcoate all Capsule on Disks to %s in RootDir.\n", (CHAR16 *)PcdGetPtr (PcdCoDRelocationFileName))); return RelocateCapsuleToDisk (MaxRetry); } } @@ -1896,7 +1921,7 @@ CoDRelocateCapsule( EFI_STATUS EFIAPI CoDRemoveTempFile ( - UINTN MaxRetry + UINTN MaxRetry ) { EFI_STATUS Status; @@ -1909,9 +1934,9 @@ CoDRemoveTempFile ( RootDir = NULL; TempCodFile = NULL; - DataSize = sizeof(UINT16); + DataSize = sizeof (UINT16); - LoadOptionNumber = AllocatePool (sizeof(UINT16)); + LoadOptionNumber = AllocatePool (sizeof (UINT16)); if (LoadOptionNumber == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -1926,54 +1951,54 @@ CoDRemoveTempFile ( &DataSize, (VOID *)LoadOptionNumber ); - if (EFI_ERROR(Status) || DataSize != sizeof(UINT16)) { + if (EFI_ERROR (Status) || (DataSize != sizeof (UINT16))) { goto EXIT; } // // Get the EFI file system from the boot option where the capsules are relocated // - Status = GetEfiSysPartitionFromActiveBootOption(MaxRetry, &LoadOptionNumber, &FsHandle); - if (EFI_ERROR(Status)) { + Status = GetEfiSysPartitionFromActiveBootOption (MaxRetry, &LoadOptionNumber, &FsHandle); + if (EFI_ERROR (Status)) { goto EXIT; } - Status = gBS->HandleProtocol(FsHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); - if (EFI_ERROR(Status)) { + Status = gBS->HandleProtocol (FsHandle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); + if (EFI_ERROR (Status)) { goto EXIT; } - Status = Fs->OpenVolume(Fs, &RootDir); - if (EFI_ERROR(Status)) { + Status = Fs->OpenVolume (Fs, &RootDir); + if (EFI_ERROR (Status)) { goto EXIT; } // // Delete the TempCoDFile // - Status = RootDir->Open( + Status = RootDir->Open ( RootDir, &TempCodFile, - (CHAR16 *)PcdGetPtr(PcdCoDRelocationFileName), + (CHAR16 *)PcdGetPtr (PcdCoDRelocationFileName), EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0 ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { goto EXIT; } - TempCodFile->Delete(TempCodFile); + TempCodFile->Delete (TempCodFile); // // Clear "CoDRelocationLoadOption" variable // Status = gRT->SetVariable ( - COD_RELOCATION_LOAD_OPTION_VAR_NAME, - &gEfiCapsuleVendorGuid, - 0, - 0, - NULL - ); + COD_RELOCATION_LOAD_OPTION_VAR_NAME, + &gEfiCapsuleVendorGuid, + 0, + 0, + NULL + ); EXIT: if (LoadOptionNumber != NULL) { @@ -1981,7 +2006,7 @@ EXIT: } if (RootDir != NULL) { - RootDir->Close(RootDir); + RootDir->Close (RootDir); } return Status; diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.h b/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.h index 4300e32770..39f9596d50 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.h +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/CapsuleOnDisk.h @@ -38,26 +38,26 @@ // // This data structure is the part of FILE_INFO_ENTRY // -#define FILE_INFO_SIGNATURE SIGNATURE_32 ('F', 'L', 'I', 'F') +#define FILE_INFO_SIGNATURE SIGNATURE_32 ('F', 'L', 'I', 'F') // // LoadOptionNumber of the boot option where the capsules is relocated. // -#define COD_RELOCATION_LOAD_OPTION_VAR_NAME L"CodRelocationLoadOption" +#define COD_RELOCATION_LOAD_OPTION_VAR_NAME L"CodRelocationLoadOption" // // (20 * (6+5+2))+1) unicode characters from EFI FAT spec (doubled for bytes) // -#define MAX_FILE_NAME_SIZE 522 -#define MAX_FILE_NAME_LEN (MAX_FILE_NAME_SIZE / sizeof(CHAR16)) -#define MAX_FILE_INFO_LEN (OFFSET_OF(EFI_FILE_INFO, FileName) + MAX_FILE_NAME_LEN) +#define MAX_FILE_NAME_SIZE 522 +#define MAX_FILE_NAME_LEN (MAX_FILE_NAME_SIZE / sizeof(CHAR16)) +#define MAX_FILE_INFO_LEN (OFFSET_OF(EFI_FILE_INFO, FileName) + MAX_FILE_NAME_LEN) typedef struct { - UINTN Signature; - LIST_ENTRY Link; /// Linked list members. - EFI_FILE_INFO *FileInfo; /// Pointer to the FileInfo struct for this file or NULL. - CHAR16 *FileNameFirstPart; /// Text to the left of right-most period in the file name. String is capitialized - CHAR16 *FileNameSecondPart; /// Text to the right of right-most period in the file name.String is capitialized. Maybe NULL + UINTN Signature; + LIST_ENTRY Link; /// Linked list members. + EFI_FILE_INFO *FileInfo; /// Pointer to the FileInfo struct for this file or NULL. + CHAR16 *FileNameFirstPart; /// Text to the left of right-most period in the file name. String is capitialized + CHAR16 *FileNameSecondPart; /// Text to the right of right-most period in the file name.String is capitialized. Maybe NULL } FILE_INFO_ENTRY; typedef struct { diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c index 395311b2bf..197af267af 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c @@ -41,11 +41,11 @@ #include #include -EFI_SYSTEM_RESOURCE_TABLE *mEsrtTable = NULL; -BOOLEAN mIsVirtualAddrConverted = FALSE; +EFI_SYSTEM_RESOURCE_TABLE *mEsrtTable = NULL; +BOOLEAN mIsVirtualAddrConverted = FALSE; -BOOLEAN mDxeCapsuleLibEndOfDxe = FALSE; -EFI_EVENT mDxeCapsuleLibEndOfDxeEvent = NULL; +BOOLEAN mDxeCapsuleLibEndOfDxe = FALSE; +EFI_EVENT mDxeCapsuleLibEndOfDxeEvent = NULL; EDKII_FIRMWARE_MANAGEMENT_PROGRESS_PROTOCOL *mFmpProgress = NULL; @@ -68,8 +68,8 @@ InitCapsuleVariable ( **/ EFI_STATUS RecordCapsuleStatusVariable ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - IN EFI_STATUS CapsuleStatus + IN EFI_CAPSULE_HEADER *CapsuleHeader, + IN EFI_STATUS CapsuleStatus ); /** @@ -121,7 +121,7 @@ UpdateImageProgress ( **/ BOOLEAN IsCapsuleNameCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { return CompareGuid (&CapsuleHeader->CapsuleGuid, &gEdkiiCapsuleOnDiskNameGuid); @@ -140,7 +140,7 @@ IsFmpCapsuleGuid ( IN EFI_GUID *CapsuleGuid ) { - if (CompareGuid(&gEfiFmpCapsuleGuid, CapsuleGuid)) { + if (CompareGuid (&gEfiFmpCapsuleGuid, CapsuleGuid)) { return TRUE; } @@ -170,9 +170,11 @@ IsValidCapsuleHeader ( if (CapsuleHeader->CapsuleImageSize != CapsuleSize) { return FALSE; } + if (CapsuleHeader->HeaderSize >= CapsuleHeader->CapsuleImageSize) { return FALSE; } + return TRUE; } @@ -202,68 +204,72 @@ ValidateFmpCapsule ( OUT UINT16 *EmbeddedDriverCount OPTIONAL ) { - EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *FmpCapsuleHeader; - UINT8 *EndOfCapsule; - EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader; - UINT8 *EndOfPayload; - UINT64 *ItemOffsetList; - UINT32 ItemNum; - UINTN Index; - UINTN FmpCapsuleSize; - UINTN FmpCapsuleHeaderSize; - UINT64 FmpImageSize; - UINTN FmpImageHeaderSize; - - if (!IsFmpCapsuleGuid(&CapsuleHeader->CapsuleGuid)) { + EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *FmpCapsuleHeader; + UINT8 *EndOfCapsule; + EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader; + UINT8 *EndOfPayload; + UINT64 *ItemOffsetList; + UINT32 ItemNum; + UINTN Index; + UINTN FmpCapsuleSize; + UINTN FmpCapsuleHeaderSize; + UINT64 FmpImageSize; + UINTN FmpImageHeaderSize; + + if (!IsFmpCapsuleGuid (&CapsuleHeader->CapsuleGuid)) { return ValidateFmpCapsule ((EFI_CAPSULE_HEADER *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize), EmbeddedDriverCount); } if (CapsuleHeader->HeaderSize >= CapsuleHeader->CapsuleImageSize) { - DEBUG((DEBUG_ERROR, "HeaderSize(0x%x) >= CapsuleImageSize(0x%x)\n", CapsuleHeader->HeaderSize, CapsuleHeader->CapsuleImageSize)); + DEBUG ((DEBUG_ERROR, "HeaderSize(0x%x) >= CapsuleImageSize(0x%x)\n", CapsuleHeader->HeaderSize, CapsuleHeader->CapsuleImageSize)); return EFI_INVALID_PARAMETER; } - FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *) ((UINT8 *) CapsuleHeader + CapsuleHeader->HeaderSize); - EndOfCapsule = (UINT8 *) CapsuleHeader + CapsuleHeader->CapsuleImageSize; + FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); + EndOfCapsule = (UINT8 *)CapsuleHeader + CapsuleHeader->CapsuleImageSize; FmpCapsuleSize = (UINTN)EndOfCapsule - (UINTN)FmpCapsuleHeader; - if (FmpCapsuleSize < sizeof(EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER)) { - DEBUG((DEBUG_ERROR, "FmpCapsuleSize(0x%x) < EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER\n", FmpCapsuleSize)); + if (FmpCapsuleSize < sizeof (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER)) { + DEBUG ((DEBUG_ERROR, "FmpCapsuleSize(0x%x) < EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER\n", FmpCapsuleSize)); return EFI_INVALID_PARAMETER; } // Check EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER if (FmpCapsuleHeader->Version != EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER_INIT_VERSION) { - DEBUG((DEBUG_ERROR, "FmpCapsuleHeader->Version(0x%x) != EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER_INIT_VERSION\n", FmpCapsuleHeader->Version)); + DEBUG ((DEBUG_ERROR, "FmpCapsuleHeader->Version(0x%x) != EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER_INIT_VERSION\n", FmpCapsuleHeader->Version)); return EFI_INVALID_PARAMETER; } + ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); // No overflow ItemNum = FmpCapsuleHeader->EmbeddedDriverCount + FmpCapsuleHeader->PayloadItemCount; - if ((FmpCapsuleSize - sizeof(EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER))/sizeof(UINT64) < ItemNum) { - DEBUG((DEBUG_ERROR, "ItemNum(0x%x) too big\n", ItemNum)); + if ((FmpCapsuleSize - sizeof (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER))/sizeof (UINT64) < ItemNum) { + DEBUG ((DEBUG_ERROR, "ItemNum(0x%x) too big\n", ItemNum)); return EFI_INVALID_PARAMETER; } - FmpCapsuleHeaderSize = sizeof(EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER) + sizeof(UINT64)*ItemNum; + + FmpCapsuleHeaderSize = sizeof (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER) + sizeof (UINT64)*ItemNum; // Check ItemOffsetList for (Index = 0; Index < ItemNum; Index++) { if (ItemOffsetList[Index] >= FmpCapsuleSize) { - DEBUG((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) >= FmpCapsuleSize(0x%x)\n", Index, ItemOffsetList[Index], FmpCapsuleSize)); + DEBUG ((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) >= FmpCapsuleSize(0x%x)\n", Index, ItemOffsetList[Index], FmpCapsuleSize)); return EFI_INVALID_PARAMETER; } + if (ItemOffsetList[Index] < FmpCapsuleHeaderSize) { - DEBUG((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) < FmpCapsuleHeaderSize(0x%x)\n", Index, ItemOffsetList[Index], FmpCapsuleHeaderSize)); + DEBUG ((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) < FmpCapsuleHeaderSize(0x%x)\n", Index, ItemOffsetList[Index], FmpCapsuleHeaderSize)); return EFI_INVALID_PARAMETER; } + // // All the address in ItemOffsetList must be stored in ascending order // if (Index > 0) { if (ItemOffsetList[Index] <= ItemOffsetList[Index - 1]) { - DEBUG((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) < ItemOffsetList[%d](0x%x)\n", Index, ItemOffsetList[Index], Index - 1, ItemOffsetList[Index - 1])); + DEBUG ((DEBUG_ERROR, "ItemOffsetList[%d](0x%lx) < ItemOffsetList[%d](0x%x)\n", Index, ItemOffsetList[Index], Index - 1, ItemOffsetList[Index - 1])); return EFI_INVALID_PARAMETER; } } @@ -271,33 +277,37 @@ ValidateFmpCapsule ( // Check EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER for (Index = FmpCapsuleHeader->EmbeddedDriverCount; Index < ItemNum; Index++) { - ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); + ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); if (Index == ItemNum - 1) { EndOfPayload = (UINT8 *)((UINTN)EndOfCapsule - (UINTN)FmpCapsuleHeader); } else { EndOfPayload = (UINT8 *)(UINTN)ItemOffsetList[Index+1]; } + FmpImageSize = (UINTN)EndOfPayload - ItemOffsetList[Index]; - FmpImageHeaderSize = sizeof(EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER); + FmpImageHeaderSize = sizeof (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER); if ((ImageHeader->Version > EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER_INIT_VERSION) || - (ImageHeader->Version < 1)) { - DEBUG((DEBUG_ERROR, "ImageHeader->Version(0x%x) Unknown\n", ImageHeader->Version)); + (ImageHeader->Version < 1)) + { + DEBUG ((DEBUG_ERROR, "ImageHeader->Version(0x%x) Unknown\n", ImageHeader->Version)); return EFI_INVALID_PARAMETER; } + if (ImageHeader->Version == 1) { - FmpImageHeaderSize = OFFSET_OF(EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, UpdateHardwareInstance); + FmpImageHeaderSize = OFFSET_OF (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, UpdateHardwareInstance); } else if (ImageHeader->Version == 2) { - FmpImageHeaderSize = OFFSET_OF(EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, ImageCapsuleSupport); + FmpImageHeaderSize = OFFSET_OF (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, ImageCapsuleSupport); } + if (FmpImageSize < FmpImageHeaderSize) { - DEBUG((DEBUG_ERROR, "FmpImageSize(0x%lx) < FmpImageHeaderSize(0x%x)\n", FmpImageSize, FmpImageHeaderSize)); + DEBUG ((DEBUG_ERROR, "FmpImageSize(0x%lx) < FmpImageHeaderSize(0x%x)\n", FmpImageSize, FmpImageHeaderSize)); return EFI_INVALID_PARAMETER; } // No overflow if (FmpImageSize != (UINT64)FmpImageHeaderSize + (UINT64)ImageHeader->UpdateImageSize + (UINT64)ImageHeader->UpdateVendorCodeSize) { - DEBUG((DEBUG_ERROR, "FmpImageSize(0x%lx) mismatch, UpdateImageSize(0x%x) UpdateVendorCodeSize(0x%x)\n", FmpImageSize, ImageHeader->UpdateImageSize, ImageHeader->UpdateVendorCodeSize)); + DEBUG ((DEBUG_ERROR, "FmpImageSize(0x%lx) mismatch, UpdateImageSize(0x%x) UpdateVendorCodeSize(0x%x)\n", FmpImageSize, ImageHeader->UpdateImageSize, ImageHeader->UpdateVendorCodeSize)); return EFI_INVALID_PARAMETER; } } @@ -308,9 +318,10 @@ ValidateFmpCapsule ( // EndOfPayload = (UINT8 *)(FmpCapsuleHeader + 1); if (EndOfPayload != EndOfCapsule) { - DEBUG((DEBUG_ERROR, "EndOfPayload(0x%x) mismatch, EndOfCapsule(0x%x)\n", EndOfPayload, EndOfCapsule)); + DEBUG ((DEBUG_ERROR, "EndOfPayload(0x%x) mismatch, EndOfCapsule(0x%x)\n", EndOfPayload, EndOfCapsule)); return EFI_INVALID_PARAMETER; } + return EFI_UNSUPPORTED; } @@ -336,14 +347,14 @@ DisplayCapsuleImage ( IN EFI_CAPSULE_HEADER *CapsuleHeader ) { - DISPLAY_DISPLAY_PAYLOAD *ImagePayload; - UINTN PayloadSize; - EFI_STATUS Status; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; - UINTN BltSize; - UINTN Height; - UINTN Width; - EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; + DISPLAY_DISPLAY_PAYLOAD *ImagePayload; + UINTN PayloadSize; + EFI_STATUS Status; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; + UINTN BltSize; + UINTN Height; + UINTN Width; + EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput; // // UX capsule doesn't have extended header entries. @@ -351,7 +362,8 @@ DisplayCapsuleImage ( if (CapsuleHeader->HeaderSize != sizeof (EFI_CAPSULE_HEADER)) { return EFI_UNSUPPORTED; } - ImagePayload = (DISPLAY_DISPLAY_PAYLOAD *)((UINTN) CapsuleHeader + CapsuleHeader->HeaderSize); + + ImagePayload = (DISPLAY_DISPLAY_PAYLOAD *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize); // // (CapsuleImageSize > HeaderSize) is guaranteed by IsValidCapsuleHeader(). // @@ -368,9 +380,11 @@ DisplayCapsuleImage ( if (ImagePayload->Version != 1) { return EFI_UNSUPPORTED; } - if (CalculateCheckSum8((UINT8 *)CapsuleHeader, CapsuleHeader->CapsuleImageSize) != 0) { + + if (CalculateCheckSum8 ((UINT8 *)CapsuleHeader, CapsuleHeader->CapsuleImageSize) != 0) { return EFI_UNSUPPORTED; } + // // Only Support Bitmap by now // @@ -383,8 +397,8 @@ DisplayCapsuleImage ( // Status = gBS->HandleProtocol (gST->ConsoleOutHandle, &gEfiGraphicsOutputProtocolGuid, (VOID **)&GraphicsOutput); if (EFI_ERROR (Status)) { - Status = gBS->LocateProtocol(&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&GraphicsOutput); - if (EFI_ERROR(Status)) { + Status = gBS->LocateProtocol (&gEfiGraphicsOutputProtocolGuid, NULL, (VOID **)&GraphicsOutput); + if (EFI_ERROR (Status)) { return EFI_UNSUPPORTED; } } @@ -393,12 +407,12 @@ DisplayCapsuleImage ( return EFI_UNSUPPORTED; } - Blt = NULL; - Width = 0; + Blt = NULL; + Width = 0; Height = 0; Status = TranslateBmpToGopBlt ( ImagePayload + 1, - PayloadSize - sizeof(DISPLAY_DISPLAY_PAYLOAD), + PayloadSize - sizeof (DISPLAY_DISPLAY_PAYLOAD), &Blt, &BltSize, &Height, @@ -415,14 +429,14 @@ DisplayCapsuleImage ( EfiBltBufferToVideo, 0, 0, - (UINTN) ImagePayload->OffsetX, - (UINTN) ImagePayload->OffsetY, + (UINTN)ImagePayload->OffsetX, + (UINTN)ImagePayload->OffsetY, Width, Height, Width * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL) ); - FreePool(Blt); + FreePool (Blt); return Status; } @@ -440,44 +454,45 @@ DisplayCapsuleImage ( **/ VOID DumpFmpImageInfo ( - IN UINTN ImageInfoSize, - IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, - IN UINT32 DescriptorVersion, - IN UINT8 DescriptorCount, - IN UINTN DescriptorSize, - IN UINT32 PackageVersion, - IN CHAR16 *PackageVersionName + IN UINTN ImageInfoSize, + IN EFI_FIRMWARE_IMAGE_DESCRIPTOR *ImageInfo, + IN UINT32 DescriptorVersion, + IN UINT8 DescriptorCount, + IN UINTN DescriptorSize, + IN UINT32 PackageVersion, + IN CHAR16 *PackageVersionName ) { - EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; - UINTN Index; - - DEBUG((DEBUG_VERBOSE, " DescriptorVersion - 0x%x\n", DescriptorVersion)); - DEBUG((DEBUG_VERBOSE, " DescriptorCount - 0x%x\n", DescriptorCount)); - DEBUG((DEBUG_VERBOSE, " DescriptorSize - 0x%x\n", DescriptorSize)); - DEBUG((DEBUG_VERBOSE, " PackageVersion - 0x%x\n", PackageVersion)); - DEBUG((DEBUG_VERBOSE, " PackageVersionName - %s\n\n", PackageVersionName)); + EFI_FIRMWARE_IMAGE_DESCRIPTOR *CurrentImageInfo; + UINTN Index; + + DEBUG ((DEBUG_VERBOSE, " DescriptorVersion - 0x%x\n", DescriptorVersion)); + DEBUG ((DEBUG_VERBOSE, " DescriptorCount - 0x%x\n", DescriptorCount)); + DEBUG ((DEBUG_VERBOSE, " DescriptorSize - 0x%x\n", DescriptorSize)); + DEBUG ((DEBUG_VERBOSE, " PackageVersion - 0x%x\n", PackageVersion)); + DEBUG ((DEBUG_VERBOSE, " PackageVersionName - %s\n\n", PackageVersionName)); CurrentImageInfo = ImageInfo; for (Index = 0; Index < DescriptorCount; Index++) { - DEBUG((DEBUG_VERBOSE, " ImageDescriptor (%d)\n", Index)); - DEBUG((DEBUG_VERBOSE, " ImageIndex - 0x%x\n", CurrentImageInfo->ImageIndex)); - DEBUG((DEBUG_VERBOSE, " ImageTypeId - %g\n", &CurrentImageInfo->ImageTypeId)); - DEBUG((DEBUG_VERBOSE, " ImageId - 0x%lx\n", CurrentImageInfo->ImageId)); - DEBUG((DEBUG_VERBOSE, " ImageIdName - %s\n", CurrentImageInfo->ImageIdName)); - DEBUG((DEBUG_VERBOSE, " Version - 0x%x\n", CurrentImageInfo->Version)); - DEBUG((DEBUG_VERBOSE, " VersionName - %s\n", CurrentImageInfo->VersionName)); - DEBUG((DEBUG_VERBOSE, " Size - 0x%x\n", CurrentImageInfo->Size)); - DEBUG((DEBUG_VERBOSE, " AttributesSupported - 0x%lx\n", CurrentImageInfo->AttributesSupported)); - DEBUG((DEBUG_VERBOSE, " AttributesSetting - 0x%lx\n", CurrentImageInfo->AttributesSetting)); - DEBUG((DEBUG_VERBOSE, " Compatibilities - 0x%lx\n", CurrentImageInfo->Compatibilities)); + DEBUG ((DEBUG_VERBOSE, " ImageDescriptor (%d)\n", Index)); + DEBUG ((DEBUG_VERBOSE, " ImageIndex - 0x%x\n", CurrentImageInfo->ImageIndex)); + DEBUG ((DEBUG_VERBOSE, " ImageTypeId - %g\n", &CurrentImageInfo->ImageTypeId)); + DEBUG ((DEBUG_VERBOSE, " ImageId - 0x%lx\n", CurrentImageInfo->ImageId)); + DEBUG ((DEBUG_VERBOSE, " ImageIdName - %s\n", CurrentImageInfo->ImageIdName)); + DEBUG ((DEBUG_VERBOSE, " Version - 0x%x\n", CurrentImageInfo->Version)); + DEBUG ((DEBUG_VERBOSE, " VersionName - %s\n", CurrentImageInfo->VersionName)); + DEBUG ((DEBUG_VERBOSE, " Size - 0x%x\n", CurrentImageInfo->Size)); + DEBUG ((DEBUG_VERBOSE, " AttributesSupported - 0x%lx\n", CurrentImageInfo->AttributesSupported)); + DEBUG ((DEBUG_VERBOSE, " AttributesSetting - 0x%lx\n", CurrentImageInfo->AttributesSetting)); + DEBUG ((DEBUG_VERBOSE, " Compatibilities - 0x%lx\n", CurrentImageInfo->Compatibilities)); if (DescriptorVersion > 1) { - DEBUG((DEBUG_VERBOSE, " LowestSupportedImageVersion - 0x%x\n", CurrentImageInfo->LowestSupportedImageVersion)); + DEBUG ((DEBUG_VERBOSE, " LowestSupportedImageVersion - 0x%x\n", CurrentImageInfo->LowestSupportedImageVersion)); if (DescriptorVersion > 2) { - DEBUG((DEBUG_VERBOSE, " LastAttemptVersion - 0x%x\n", CurrentImageInfo->LastAttemptVersion)); - DEBUG((DEBUG_VERBOSE, " LastAttemptStatus - 0x%x\n", CurrentImageInfo->LastAttemptStatus)); - DEBUG((DEBUG_VERBOSE, " HardwareInstance - 0x%lx\n", CurrentImageInfo->HardwareInstance)); + DEBUG ((DEBUG_VERBOSE, " LastAttemptVersion - 0x%x\n", CurrentImageInfo->LastAttemptVersion)); + DEBUG ((DEBUG_VERBOSE, " LastAttemptStatus - 0x%x\n", CurrentImageInfo->LastAttemptStatus)); + DEBUG ((DEBUG_VERBOSE, " HardwareInstance - 0x%lx\n", CurrentImageInfo->HardwareInstance)); } } + // // Use DescriptorSize to move ImageInfo Pointer to stay compatible with different ImageInfo version // @@ -492,7 +507,7 @@ DumpFmpImageInfo ( **/ VOID DumpFmpCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *FmpCapsuleHeader; @@ -502,29 +517,30 @@ DumpFmpCapsule ( FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); - DEBUG((DEBUG_VERBOSE, "FmpCapsule:\n")); - DEBUG((DEBUG_VERBOSE, " Version - 0x%x\n", FmpCapsuleHeader->Version)); - DEBUG((DEBUG_VERBOSE, " EmbeddedDriverCount - 0x%x\n", FmpCapsuleHeader->EmbeddedDriverCount)); - DEBUG((DEBUG_VERBOSE, " PayloadItemCount - 0x%x\n", FmpCapsuleHeader->PayloadItemCount)); + DEBUG ((DEBUG_VERBOSE, "FmpCapsule:\n")); + DEBUG ((DEBUG_VERBOSE, " Version - 0x%x\n", FmpCapsuleHeader->Version)); + DEBUG ((DEBUG_VERBOSE, " EmbeddedDriverCount - 0x%x\n", FmpCapsuleHeader->EmbeddedDriverCount)); + DEBUG ((DEBUG_VERBOSE, " PayloadItemCount - 0x%x\n", FmpCapsuleHeader->PayloadItemCount)); ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); for (Index = 0; Index < FmpCapsuleHeader->EmbeddedDriverCount; Index++) { - DEBUG((DEBUG_VERBOSE, " ItemOffsetList[%d] - 0x%lx\n", Index, ItemOffsetList[Index])); + DEBUG ((DEBUG_VERBOSE, " ItemOffsetList[%d] - 0x%lx\n", Index, ItemOffsetList[Index])); } - for (; Index < (UINT32)FmpCapsuleHeader->EmbeddedDriverCount + FmpCapsuleHeader->PayloadItemCount; Index++) { - DEBUG((DEBUG_VERBOSE, " ItemOffsetList[%d] - 0x%lx\n", Index, ItemOffsetList[Index])); + + for ( ; Index < (UINT32)FmpCapsuleHeader->EmbeddedDriverCount + FmpCapsuleHeader->PayloadItemCount; Index++) { + DEBUG ((DEBUG_VERBOSE, " ItemOffsetList[%d] - 0x%lx\n", Index, ItemOffsetList[Index])); ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); - DEBUG((DEBUG_VERBOSE, " ImageHeader:\n")); - DEBUG((DEBUG_VERBOSE, " Version - 0x%x\n", ImageHeader->Version)); - DEBUG((DEBUG_VERBOSE, " UpdateImageTypeId - %g\n", &ImageHeader->UpdateImageTypeId)); - DEBUG((DEBUG_VERBOSE, " UpdateImageIndex - 0x%x\n", ImageHeader->UpdateImageIndex)); - DEBUG((DEBUG_VERBOSE, " UpdateImageSize - 0x%x\n", ImageHeader->UpdateImageSize)); - DEBUG((DEBUG_VERBOSE, " UpdateVendorCodeSize - 0x%x\n", ImageHeader->UpdateVendorCodeSize)); + DEBUG ((DEBUG_VERBOSE, " ImageHeader:\n")); + DEBUG ((DEBUG_VERBOSE, " Version - 0x%x\n", ImageHeader->Version)); + DEBUG ((DEBUG_VERBOSE, " UpdateImageTypeId - %g\n", &ImageHeader->UpdateImageTypeId)); + DEBUG ((DEBUG_VERBOSE, " UpdateImageIndex - 0x%x\n", ImageHeader->UpdateImageIndex)); + DEBUG ((DEBUG_VERBOSE, " UpdateImageSize - 0x%x\n", ImageHeader->UpdateImageSize)); + DEBUG ((DEBUG_VERBOSE, " UpdateVendorCodeSize - 0x%x\n", ImageHeader->UpdateVendorCodeSize)); if (ImageHeader->Version >= 2) { - DEBUG((DEBUG_VERBOSE, " UpdateHardwareInstance - 0x%lx\n", ImageHeader->UpdateHardwareInstance)); + DEBUG ((DEBUG_VERBOSE, " UpdateHardwareInstance - 0x%lx\n", ImageHeader->UpdateHardwareInstance)); if (ImageHeader->Version >= EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER_INIT_VERSION) { - DEBUG((DEBUG_VERBOSE, " ImageCapsuleSupport - 0x%lx\n", ImageHeader->ImageCapsuleSupport)); + DEBUG ((DEBUG_VERBOSE, " ImageCapsuleSupport - 0x%lx\n", ImageHeader->ImageCapsuleSupport)); } } } @@ -538,18 +554,18 @@ DumpAllFmpInfo ( VOID ) { - EFI_STATUS Status; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - UINTN Index; - UINTN ImageInfoSize; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; - UINT32 FmpImageInfoDescriptorVer; - UINT8 FmpImageInfoCount; - UINTN DescriptorSize; - UINT32 PackageVersion; - CHAR16 *PackageVersionName; + EFI_STATUS Status; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + UINTN Index; + UINTN ImageInfoSize; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; + UINT32 FmpImageInfoDescriptorVer; + UINT8 FmpImageInfoCount; + UINTN DescriptorSize; + UINT32 PackageVersion; + CHAR16 *PackageVersionName; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -558,31 +574,31 @@ DumpAllFmpInfo ( &NumberOfHandles, &HandleBuffer ); - if (EFI_ERROR(Status)) { - return ; + if (EFI_ERROR (Status)) { + return; } for (Index = 0; Index < NumberOfHandles; Index++) { - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } ImageInfoSize = 0; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + ); if (Status != EFI_BUFFER_TOO_SMALL) { continue; } @@ -593,23 +609,23 @@ DumpAllFmpInfo ( } PackageVersionName = NULL; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, // ImageInfoSize - FmpImageInfoBuf, // ImageInfo - &FmpImageInfoDescriptorVer, // DescriptorVersion - &FmpImageInfoCount, // DescriptorCount - &DescriptorSize, // DescriptorSize - &PackageVersion, // PackageVersion - &PackageVersionName // PackageVersionName - ); - if (EFI_ERROR(Status)) { - FreePool(FmpImageInfoBuf); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, // ImageInfoSize + FmpImageInfoBuf, // ImageInfo + &FmpImageInfoDescriptorVer, // DescriptorVersion + &FmpImageInfoCount, // DescriptorCount + &DescriptorSize, // DescriptorSize + &PackageVersion, // PackageVersion + &PackageVersionName // PackageVersionName + ); + if (EFI_ERROR (Status)) { + FreePool (FmpImageInfoBuf); continue; } - DEBUG((DEBUG_INFO, "FMP (%d) ImageInfo:\n", Index)); - DumpFmpImageInfo( + DEBUG ((DEBUG_INFO, "FMP (%d) ImageInfo:\n", Index)); + DumpFmpImageInfo ( ImageInfoSize, // ImageInfoSize FmpImageInfoBuf, // ImageInfo FmpImageInfoDescriptorVer, // DescriptorVersion @@ -620,15 +636,15 @@ DumpAllFmpInfo ( ); if (PackageVersionName != NULL) { - FreePool(PackageVersionName); + FreePool (PackageVersionName); } - FreePool(FmpImageInfoBuf); + FreePool (FmpImageInfoBuf); } FreePool (HandleBuffer); - return ; + return; } /** @@ -649,37 +665,39 @@ DumpAllFmpInfo ( **/ EFI_STATUS GetFmpHandleBufferByType ( - IN EFI_GUID *UpdateImageTypeId, - IN UINT64 UpdateHardwareInstance, - OUT UINTN *NoHandles OPTIONAL, - OUT EFI_HANDLE **HandleBuf OPTIONAL, - OUT BOOLEAN **ResetRequiredBuf OPTIONAL + IN EFI_GUID *UpdateImageTypeId, + IN UINT64 UpdateHardwareInstance, + OUT UINTN *NoHandles OPTIONAL, + OUT EFI_HANDLE **HandleBuf OPTIONAL, + OUT BOOLEAN **ResetRequiredBuf OPTIONAL ) { - EFI_STATUS Status; - EFI_HANDLE *HandleBuffer; - UINTN NumberOfHandles; - EFI_HANDLE *MatchedHandleBuffer; - BOOLEAN *MatchedResetRequiredBuffer; - UINTN MatchedNumberOfHandles; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - UINTN Index; - UINTN ImageInfoSize; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; - UINT32 FmpImageInfoDescriptorVer; - UINT8 FmpImageInfoCount; - UINTN DescriptorSize; - UINT32 PackageVersion; - CHAR16 *PackageVersionName; - UINTN Index2; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *TempFmpImageInfo; + EFI_STATUS Status; + EFI_HANDLE *HandleBuffer; + UINTN NumberOfHandles; + EFI_HANDLE *MatchedHandleBuffer; + BOOLEAN *MatchedResetRequiredBuffer; + UINTN MatchedNumberOfHandles; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + UINTN Index; + UINTN ImageInfoSize; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; + UINT32 FmpImageInfoDescriptorVer; + UINT8 FmpImageInfoCount; + UINTN DescriptorSize; + UINT32 PackageVersion; + CHAR16 *PackageVersionName; + UINTN Index2; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *TempFmpImageInfo; if (NoHandles != NULL) { *NoHandles = 0; } + if (HandleBuf != NULL) { *HandleBuf = NULL; } + if (ResetRequiredBuf != NULL) { *ResetRequiredBuf = NULL; } @@ -691,7 +709,7 @@ GetFmpHandleBufferByType ( &NumberOfHandles, &HandleBuffer ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -699,7 +717,7 @@ GetFmpHandleBufferByType ( MatchedHandleBuffer = NULL; if (HandleBuf != NULL) { - MatchedHandleBuffer = AllocateZeroPool (sizeof(EFI_HANDLE) * NumberOfHandles); + MatchedHandleBuffer = AllocateZeroPool (sizeof (EFI_HANDLE) * NumberOfHandles); if (MatchedHandleBuffer == NULL) { FreePool (HandleBuffer); return EFI_OUT_OF_RESOURCES; @@ -708,37 +726,38 @@ GetFmpHandleBufferByType ( MatchedResetRequiredBuffer = NULL; if (ResetRequiredBuf != NULL) { - MatchedResetRequiredBuffer = AllocateZeroPool (sizeof(BOOLEAN) * NumberOfHandles); + MatchedResetRequiredBuffer = AllocateZeroPool (sizeof (BOOLEAN) * NumberOfHandles); if (MatchedResetRequiredBuffer == NULL) { if (MatchedHandleBuffer != NULL) { FreePool (MatchedHandleBuffer); } + FreePool (HandleBuffer); return EFI_OUT_OF_RESOURCES; } } for (Index = 0; Index < NumberOfHandles; Index++) { - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { continue; } ImageInfoSize = 0; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + ); if (Status != EFI_BUFFER_TOO_SMALL) { continue; } @@ -749,23 +768,23 @@ GetFmpHandleBufferByType ( } PackageVersionName = NULL; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, // ImageInfoSize - FmpImageInfoBuf, // ImageInfo - &FmpImageInfoDescriptorVer, // DescriptorVersion - &FmpImageInfoCount, // DescriptorCount - &DescriptorSize, // DescriptorSize - &PackageVersion, // PackageVersion - &PackageVersionName // PackageVersionName - ); - if (EFI_ERROR(Status)) { - FreePool(FmpImageInfoBuf); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, // ImageInfoSize + FmpImageInfoBuf, // ImageInfo + &FmpImageInfoDescriptorVer, // DescriptorVersion + &FmpImageInfoCount, // DescriptorCount + &DescriptorSize, // DescriptorSize + &PackageVersion, // PackageVersion + &PackageVersionName // PackageVersionName + ); + if (EFI_ERROR (Status)) { + FreePool (FmpImageInfoBuf); continue; } if (PackageVersionName != NULL) { - FreePool(PackageVersionName); + FreePool (PackageVersionName); } TempFmpImageInfo = FmpImageInfoBuf; @@ -773,26 +792,31 @@ GetFmpHandleBufferByType ( // // Check if this FMP instance matches // - if (CompareGuid(UpdateImageTypeId, &TempFmpImageInfo->ImageTypeId)) { + if (CompareGuid (UpdateImageTypeId, &TempFmpImageInfo->ImageTypeId)) { if ((UpdateHardwareInstance == 0) || ((FmpImageInfoDescriptorVer >= EFI_FIRMWARE_IMAGE_DESCRIPTOR_VERSION) && - (UpdateHardwareInstance == TempFmpImageInfo->HardwareInstance))) { + (UpdateHardwareInstance == TempFmpImageInfo->HardwareInstance))) + { if (MatchedHandleBuffer != NULL) { MatchedHandleBuffer[MatchedNumberOfHandles] = HandleBuffer[Index]; } + if (MatchedResetRequiredBuffer != NULL) { MatchedResetRequiredBuffer[MatchedNumberOfHandles] = (((TempFmpImageInfo->AttributesSupported & - IMAGE_ATTRIBUTE_RESET_REQUIRED) != 0) && - ((TempFmpImageInfo->AttributesSetting & - IMAGE_ATTRIBUTE_RESET_REQUIRED) != 0)); + IMAGE_ATTRIBUTE_RESET_REQUIRED) != 0) && + ((TempFmpImageInfo->AttributesSetting & + IMAGE_ATTRIBUTE_RESET_REQUIRED) != 0)); } + MatchedNumberOfHandles++; break; } } + TempFmpImageInfo = (EFI_FIRMWARE_IMAGE_DESCRIPTOR *)((UINT8 *)TempFmpImageInfo + DescriptorSize); } - FreePool(FmpImageInfoBuf); + + FreePool (FmpImageInfoBuf); } FreePool (HandleBuffer); @@ -804,9 +828,11 @@ GetFmpHandleBufferByType ( if (NoHandles != NULL) { *NoHandles = MatchedNumberOfHandles; } + if (HandleBuf != NULL) { *HandleBuf = MatchedHandleBuffer; } + if (ResetRequiredBuf != NULL) { *ResetRequiredBuf = MatchedResetRequiredBuffer; } @@ -823,39 +849,39 @@ GetFmpHandleBufferByType ( **/ UINT32 GetFmpImageInfoDescriptorVer ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - UINTN ImageInfoSize; - EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; - UINT32 FmpImageInfoDescriptorVer; - UINT8 FmpImageInfoCount; - UINTN DescriptorSize; - UINT32 PackageVersion; - CHAR16 *PackageVersionName; - - Status = gBS->HandleProtocol( + EFI_STATUS Status; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + UINTN ImageInfoSize; + EFI_FIRMWARE_IMAGE_DESCRIPTOR *FmpImageInfoBuf; + UINT32 FmpImageInfoDescriptorVer; + UINT8 FmpImageInfoCount; + UINTN DescriptorSize; + UINT32 PackageVersion; + CHAR16 *PackageVersionName; + + Status = gBS->HandleProtocol ( Handle, &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return 0; } ImageInfoSize = 0; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL - ); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL + ); if (Status != EFI_BUFFER_TOO_SMALL) { return 0; } @@ -866,20 +892,21 @@ GetFmpImageInfoDescriptorVer ( } PackageVersionName = NULL; - Status = Fmp->GetImageInfo ( - Fmp, - &ImageInfoSize, // ImageInfoSize - FmpImageInfoBuf, // ImageInfo - &FmpImageInfoDescriptorVer, // DescriptorVersion - &FmpImageInfoCount, // DescriptorCount - &DescriptorSize, // DescriptorSize - &PackageVersion, // PackageVersion - &PackageVersionName // PackageVersionName - ); - if (EFI_ERROR(Status)) { - FreePool(FmpImageInfoBuf); + Status = Fmp->GetImageInfo ( + Fmp, + &ImageInfoSize, // ImageInfoSize + FmpImageInfoBuf, // ImageInfo + &FmpImageInfoDescriptorVer, // DescriptorVersion + &FmpImageInfoCount, // DescriptorCount + &DescriptorSize, // DescriptorSize + &PackageVersion, // PackageVersion + &PackageVersionName // PackageVersionName + ); + if (EFI_ERROR (Status)) { + FreePool (FmpImageInfoBuf); return 0; } + return FmpImageInfoDescriptorVer; } @@ -894,24 +921,24 @@ GetFmpImageInfoDescriptorVer ( **/ EFI_STATUS SetFmpImageData ( - IN EFI_HANDLE Handle, - IN EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader, - IN UINTN PayloadIndex + IN EFI_HANDLE Handle, + IN EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *ImageHeader, + IN UINTN PayloadIndex ) { - EFI_STATUS Status; - EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; - UINT8 *Image; - VOID *VendorCode; - CHAR16 *AbortReason; - EFI_FIRMWARE_MANAGEMENT_UPDATE_IMAGE_PROGRESS ProgressCallback; + EFI_STATUS Status; + EFI_FIRMWARE_MANAGEMENT_PROTOCOL *Fmp; + UINT8 *Image; + VOID *VendorCode; + CHAR16 *AbortReason; + EFI_FIRMWARE_MANAGEMENT_UPDATE_IMAGE_PROGRESS ProgressCallback; - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( Handle, &gEfiFirmwareManagementProtocolGuid, (VOID **)&Fmp ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return Status; } @@ -937,9 +964,9 @@ SetFmpImageData ( // ImageCapsuleSupport field if version is 2. // if (ImageHeader->Version == 1) { - Image = (UINT8 *)ImageHeader + OFFSET_OF(EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, UpdateHardwareInstance); + Image = (UINT8 *)ImageHeader + OFFSET_OF (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, UpdateHardwareInstance); } else { - Image = (UINT8 *)ImageHeader + OFFSET_OF(EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, ImageCapsuleSupport); + Image = (UINT8 *)ImageHeader + OFFSET_OF (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER, ImageCapsuleSupport); } } @@ -948,29 +975,31 @@ SetFmpImageData ( } else { VendorCode = Image + ImageHeader->UpdateImageSize; } + AbortReason = NULL; - DEBUG((DEBUG_INFO, "Fmp->SetImage ...\n")); - DEBUG((DEBUG_INFO, "ImageTypeId - %g, ", &ImageHeader->UpdateImageTypeId)); - DEBUG((DEBUG_INFO, "PayloadIndex - 0x%x, ", PayloadIndex)); - DEBUG((DEBUG_INFO, "ImageIndex - 0x%x ", ImageHeader->UpdateImageIndex)); + DEBUG ((DEBUG_INFO, "Fmp->SetImage ...\n")); + DEBUG ((DEBUG_INFO, "ImageTypeId - %g, ", &ImageHeader->UpdateImageTypeId)); + DEBUG ((DEBUG_INFO, "PayloadIndex - 0x%x, ", PayloadIndex)); + DEBUG ((DEBUG_INFO, "ImageIndex - 0x%x ", ImageHeader->UpdateImageIndex)); if (ImageHeader->Version >= 2) { - DEBUG((DEBUG_INFO, "(UpdateHardwareInstance - 0x%x)", ImageHeader->UpdateHardwareInstance)); + DEBUG ((DEBUG_INFO, "(UpdateHardwareInstance - 0x%x)", ImageHeader->UpdateHardwareInstance)); if (ImageHeader->Version >= EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER_INIT_VERSION) { - DEBUG((DEBUG_INFO, "(ImageCapsuleSupport - 0x%x)", ImageHeader->ImageCapsuleSupport)); + DEBUG ((DEBUG_INFO, "(ImageCapsuleSupport - 0x%x)", ImageHeader->ImageCapsuleSupport)); } } - DEBUG((DEBUG_INFO, "\n")); + + DEBUG ((DEBUG_INFO, "\n")); // // Before calling SetImage(), reset the progress bar to 0% // ProgressCallback = UpdateImageProgress; - Status = UpdateImageProgress (0); + Status = UpdateImageProgress (0); if (EFI_ERROR (Status)) { ProgressCallback = NULL; } - Status = Fmp->SetImage( + Status = Fmp->SetImage ( Fmp, ImageHeader->UpdateImageIndex, // ImageIndex Image, // Image @@ -986,10 +1015,10 @@ SetFmpImageData ( UpdateImageProgress (100); } - DEBUG((DEBUG_INFO, "Fmp->SetImage - %r\n", Status)); + DEBUG ((DEBUG_INFO, "Fmp->SetImage - %r\n", Status)); if (AbortReason != NULL) { DEBUG ((DEBUG_ERROR, "%s\n", AbortReason)); - FreePool(AbortReason); + FreePool (AbortReason); } // @@ -1014,11 +1043,11 @@ StartFmpImage ( IN UINTN ImageSize ) { - MEMMAP_DEVICE_PATH MemMapNode; - EFI_STATUS Status; - EFI_HANDLE ImageHandle; - EFI_DEVICE_PATH_PROTOCOL *DriverDevicePath; - UINTN ExitDataSize; + MEMMAP_DEVICE_PATH MemMapNode; + EFI_STATUS Status; + EFI_HANDLE ImageHandle; + EFI_DEVICE_PATH_PROTOCOL *DriverDevicePath; + UINTN ExitDataSize; SetDevicePathNodeLength (&MemMapNode.Header, sizeof (MemMapNode)); MemMapNode.Header.Type = HARDWARE_DEVICE_PATH; @@ -1032,8 +1061,8 @@ StartFmpImage ( return EFI_OUT_OF_RESOURCES; } - DEBUG((DEBUG_INFO, "FmpCapsule: LoadImage ...\n")); - Status = gBS->LoadImage( + DEBUG ((DEBUG_INFO, "FmpCapsule: LoadImage ...\n")); + Status = gBS->LoadImage ( FALSE, gImageHandle, DriverDevicePath, @@ -1041,8 +1070,8 @@ StartFmpImage ( ImageSize, &ImageHandle ); - DEBUG((DEBUG_INFO, "FmpCapsule: LoadImage - %r\n", Status)); - if (EFI_ERROR(Status)) { + DEBUG ((DEBUG_INFO, "FmpCapsule: LoadImage - %r\n", Status)); + if (EFI_ERROR (Status)) { // // With EFI_SECURITY_VIOLATION retval, the Image was loaded and an ImageHandle was created // with a valid EFI_LOADED_IMAGE_PROTOCOL, but the image can not be started right now. @@ -1052,22 +1081,23 @@ StartFmpImage ( if (Status == EFI_SECURITY_VIOLATION) { gBS->UnloadImage (ImageHandle); } - FreePool(DriverDevicePath); + + FreePool (DriverDevicePath); return Status; } - DEBUG((DEBUG_INFO, "FmpCapsule: StartImage ...\n")); - Status = gBS->StartImage( + DEBUG ((DEBUG_INFO, "FmpCapsule: StartImage ...\n")); + Status = gBS->StartImage ( ImageHandle, &ExitDataSize, NULL ); - DEBUG((DEBUG_INFO, "FmpCapsule: StartImage - %r\n", Status)); - if (EFI_ERROR(Status)) { + DEBUG ((DEBUG_INFO, "FmpCapsule: StartImage - %r\n", Status)); + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Driver Return Status = %r\n", Status)); } - FreePool(DriverDevicePath); + FreePool (DriverDevicePath); return Status; } @@ -1091,16 +1121,16 @@ RecordFmpCapsuleStatus ( IN CHAR16 *CapFileName OPTIONAL ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FmpDevicePath; - UINT32 FmpImageInfoDescriptorVer; - EFI_STATUS StatusEsrt; - ESRT_MANAGEMENT_PROTOCOL *EsrtProtocol; - EFI_SYSTEM_RESOURCE_ENTRY EsrtEntry; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FmpDevicePath; + UINT32 FmpImageInfoDescriptorVer; + EFI_STATUS StatusEsrt; + ESRT_MANAGEMENT_PROTOCOL *EsrtProtocol; + EFI_SYSTEM_RESOURCE_ENTRY EsrtEntry; FmpDevicePath = NULL; if (Handle != NULL) { - gBS->HandleProtocol( + gBS->HandleProtocol ( Handle, &gEfiDevicePathProtocolGuid, (VOID **)&FmpDevicePath @@ -1119,13 +1149,13 @@ RecordFmpCapsuleStatus ( // // Update corresponding ESRT entry LastAttemp Status // - Status = gBS->LocateProtocol(&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtProtocol); + Status = gBS->LocateProtocol (&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtProtocol); if (EFI_ERROR (Status)) { - return ; + return; } if (Handle == NULL) { - return ; + return; } // @@ -1134,15 +1164,16 @@ RecordFmpCapsuleStatus ( // FmpImageInfoDescriptorVer = GetFmpImageInfoDescriptorVer (Handle); if (FmpImageInfoDescriptorVer < EFI_FIRMWARE_IMAGE_DESCRIPTOR_VERSION) { - StatusEsrt = EsrtProtocol->GetEsrtEntry(&ImageHeader->UpdateImageTypeId, &EsrtEntry); - if (!EFI_ERROR(StatusEsrt)){ - if (!EFI_ERROR(CapsuleStatus)) { + StatusEsrt = EsrtProtocol->GetEsrtEntry (&ImageHeader->UpdateImageTypeId, &EsrtEntry); + if (!EFI_ERROR (StatusEsrt)) { + if (!EFI_ERROR (CapsuleStatus)) { EsrtEntry.LastAttemptStatus = LAST_ATTEMPT_STATUS_SUCCESS; } else { EsrtEntry.LastAttemptStatus = LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL; } + EsrtEntry.LastAttemptVersion = 0; - EsrtProtocol->UpdateEsrtEntry(&EsrtEntry); + EsrtProtocol->UpdateEsrtEntry (&EsrtEntry); } } } @@ -1189,20 +1220,21 @@ ProcessFmpCapsuleImage ( BOOLEAN NotReady; BOOLEAN Abort; - if (!IsFmpCapsuleGuid(&CapsuleHeader->CapsuleGuid)) { + if (!IsFmpCapsuleGuid (&CapsuleHeader->CapsuleGuid)) { return ProcessFmpCapsuleImage ((EFI_CAPSULE_HEADER *)((UINTN)CapsuleHeader + CapsuleHeader->HeaderSize), CapFileName, ResetRequired); } NotReady = FALSE; - Abort = FALSE; + Abort = FALSE; - DumpFmpCapsule(CapsuleHeader); + DumpFmpCapsule (CapsuleHeader); - FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *) ((UINT8 *) CapsuleHeader + CapsuleHeader->HeaderSize); + FmpCapsuleHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); if (FmpCapsuleHeader->Version > EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER_INIT_VERSION) { return EFI_INVALID_PARAMETER; } + ItemOffsetList = (UINT64 *)(FmpCapsuleHeader + 1); ItemNum = FmpCapsuleHeader->EmbeddedDriverCount + FmpCapsuleHeader->PayloadItemCount; @@ -1219,7 +1251,8 @@ ProcessFmpCapsuleImage ( // for (Index = 0; Index < FmpCapsuleHeader->EmbeddedDriverCount; Index++) { if ((FmpCapsuleHeader->PayloadItemCount == 0) && - (Index == (UINTN)FmpCapsuleHeader->EmbeddedDriverCount - 1)) { + (Index == (UINTN)FmpCapsuleHeader->EmbeddedDriverCount - 1)) + { // // When driver is last element in the ItemOffsetList array, the driver size is calculated by reference CapsuleImageSize in EFI_CAPSULE_HEADER // @@ -1232,7 +1265,7 @@ ProcessFmpCapsuleImage ( (UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index], DriverLen ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "Driver Return Status = %r\n", Status)); return Status; } @@ -1241,7 +1274,7 @@ ProcessFmpCapsuleImage ( // // 2. Route payload to right FMP instance // - DEBUG((DEBUG_INFO, "FmpCapsule: route payload to right FMP instance ...\n")); + DEBUG ((DEBUG_INFO, "FmpCapsule: route payload to right FMP instance ...\n")); DumpAllFmpInfo (); @@ -1249,7 +1282,7 @@ ProcessFmpCapsuleImage ( // Check all the payload entry in capsule payload list // for (Index = FmpCapsuleHeader->EmbeddedDriverCount; Index < ItemNum; Index++) { - ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); + ImageHeader = (EFI_FIRMWARE_MANAGEMENT_CAPSULE_IMAGE_HEADER *)((UINT8 *)FmpCapsuleHeader + ItemOffsetList[Index]); UpdateHardwareInstance = 0; /// @@ -1266,9 +1299,10 @@ ProcessFmpCapsuleImage ( &HandleBuffer, &ResetRequiredBuffer ); - if (EFI_ERROR(Status) || + if (EFI_ERROR (Status) || (HandleBuffer == NULL) || - (ResetRequiredBuffer == NULL)) { + (ResetRequiredBuffer == NULL)) + { NotReady = TRUE; RecordFmpCapsuleStatus ( NULL, @@ -1316,11 +1350,13 @@ ProcessFmpCapsuleImage ( CapFileName ); } + if (HandleBuffer != NULL) { - FreePool(HandleBuffer); + FreePool (HandleBuffer); } + if (ResetRequiredBuffer != NULL) { - FreePool(ResetRequiredBuffer); + FreePool (ResetRequiredBuffer); } } @@ -1345,7 +1381,7 @@ ProcessFmpCapsuleImage ( **/ BOOLEAN IsNestedFmpCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { EFI_STATUS Status; @@ -1359,10 +1395,10 @@ IsNestedFmpCapsule ( EsrtGuidFound = FALSE; if (mIsVirtualAddrConverted) { - if(mEsrtTable != NULL) { + if (mEsrtTable != NULL) { EsrtEntry = (EFI_SYSTEM_RESOURCE_ENTRY *)(mEsrtTable + 1); - for (Index = 0; Index < mEsrtTable->FwResourceCount ; Index++, EsrtEntry++) { - if (CompareGuid(&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) { + for (Index = 0; Index < mEsrtTable->FwResourceCount; Index++, EsrtEntry++) { + if (CompareGuid (&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) { EsrtGuidFound = TRUE; break; } @@ -1372,10 +1408,10 @@ IsNestedFmpCapsule ( // // Check ESRT protocol // - Status = gBS->LocateProtocol(&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtProtocol); - if (!EFI_ERROR(Status)) { - Status = EsrtProtocol->GetEsrtEntry(&CapsuleHeader->CapsuleGuid, &Entry); - if (!EFI_ERROR(Status)) { + Status = gBS->LocateProtocol (&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtProtocol); + if (!EFI_ERROR (Status)) { + Status = EsrtProtocol->GetEsrtEntry (&CapsuleHeader->CapsuleGuid, &Entry); + if (!EFI_ERROR (Status)) { EsrtGuidFound = TRUE; } } @@ -1391,11 +1427,12 @@ IsNestedFmpCapsule ( NULL, NULL ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { EsrtGuidFound = TRUE; } } } + if (!EsrtGuidFound) { return FALSE; } @@ -1405,16 +1442,19 @@ IsNestedFmpCapsule ( // FMP GUID after ESRT one // NestedCapsuleHeader = (EFI_CAPSULE_HEADER *)((UINT8 *)CapsuleHeader + CapsuleHeader->HeaderSize); - NestedCapsuleSize = (UINTN)CapsuleHeader + CapsuleHeader->CapsuleImageSize - (UINTN)NestedCapsuleHeader; - if (NestedCapsuleSize < sizeof(EFI_CAPSULE_HEADER)) { + NestedCapsuleSize = (UINTN)CapsuleHeader + CapsuleHeader->CapsuleImageSize - (UINTN)NestedCapsuleHeader; + if (NestedCapsuleSize < sizeof (EFI_CAPSULE_HEADER)) { return FALSE; } - if (!IsValidCapsuleHeader(NestedCapsuleHeader, NestedCapsuleSize)) { + + if (!IsValidCapsuleHeader (NestedCapsuleHeader, NestedCapsuleSize)) { return FALSE; } - if (!IsFmpCapsuleGuid(&NestedCapsuleHeader->CapsuleGuid)) { + + if (!IsFmpCapsuleGuid (&NestedCapsuleHeader->CapsuleGuid)) { return FALSE; } + DEBUG ((DEBUG_INFO, "IsNestedFmpCapsule\n")); return TRUE; } @@ -1429,15 +1469,17 @@ IsNestedFmpCapsule ( **/ BOOLEAN IsFmpCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { - if (IsFmpCapsuleGuid(&CapsuleHeader->CapsuleGuid)) { + if (IsFmpCapsuleGuid (&CapsuleHeader->CapsuleGuid)) { return TRUE; } - if (IsNestedFmpCapsule(CapsuleHeader)) { + + if (IsNestedFmpCapsule (CapsuleHeader)) { return TRUE; } + return FALSE; } @@ -1468,23 +1510,25 @@ SupportCapsuleImage ( // // Check capsule file name capsule // - if (IsCapsuleNameCapsule(CapsuleHeader)) { + if (IsCapsuleNameCapsule (CapsuleHeader)) { return EFI_SUCCESS; } - if (IsFmpCapsule(CapsuleHeader)) { + if (IsFmpCapsule (CapsuleHeader)) { // // Fake capsule header is valid case in QueryCapsuleCpapbilities(). // if (CapsuleHeader->HeaderSize == CapsuleHeader->CapsuleImageSize) { return EFI_SUCCESS; } + // // Check layout of FMP capsule // - return ValidateFmpCapsule(CapsuleHeader, NULL); + return ValidateFmpCapsule (CapsuleHeader, NULL); } - DEBUG((DEBUG_ERROR, "Unknown Capsule Guid - %g\n", &CapsuleHeader->CapsuleGuid)); + + DEBUG ((DEBUG_ERROR, "Unknown Capsule Guid - %g\n", &CapsuleHeader->CapsuleGuid)); return EFI_UNSUPPORTED; } @@ -1510,10 +1554,10 @@ ProcessThisCapsuleImage ( OUT BOOLEAN *ResetRequired OPTIONAL ) { - EFI_STATUS Status; + EFI_STATUS Status; if (SupportCapsuleImage (CapsuleHeader) != EFI_SUCCESS) { - RecordCapsuleStatusVariable(CapsuleHeader, EFI_UNSUPPORTED); + RecordCapsuleStatusVariable (CapsuleHeader, EFI_UNSUPPORTED); return EFI_UNSUPPORTED; } @@ -1521,9 +1565,9 @@ ProcessThisCapsuleImage ( // Display image in firmware update display capsule // if (CompareGuid (&gWindowsUxCapsuleGuid, &CapsuleHeader->CapsuleGuid)) { - DEBUG((DEBUG_INFO, "ProcessCapsuleImage for WindowsUxCapsule ...\n")); - Status = DisplayCapsuleImage(CapsuleHeader); - RecordCapsuleStatusVariable(CapsuleHeader, Status); + DEBUG ((DEBUG_INFO, "ProcessCapsuleImage for WindowsUxCapsule ...\n")); + Status = DisplayCapsuleImage (CapsuleHeader); + RecordCapsuleStatusVariable (CapsuleHeader, Status); return Status; } @@ -1531,21 +1575,21 @@ ProcessThisCapsuleImage ( // Check FMP capsule layout // if (IsFmpCapsule (CapsuleHeader)) { - DEBUG((DEBUG_INFO, "ProcessCapsuleImage for FmpCapsule ...\n")); - DEBUG((DEBUG_INFO, "ValidateFmpCapsule ...\n")); - Status = ValidateFmpCapsule(CapsuleHeader, NULL); - DEBUG((DEBUG_INFO, "ValidateFmpCapsule - %r\n", Status)); - if (EFI_ERROR(Status)) { - RecordCapsuleStatusVariable(CapsuleHeader, Status); + DEBUG ((DEBUG_INFO, "ProcessCapsuleImage for FmpCapsule ...\n")); + DEBUG ((DEBUG_INFO, "ValidateFmpCapsule ...\n")); + Status = ValidateFmpCapsule (CapsuleHeader, NULL); + DEBUG ((DEBUG_INFO, "ValidateFmpCapsule - %r\n", Status)); + if (EFI_ERROR (Status)) { + RecordCapsuleStatusVariable (CapsuleHeader, Status); return Status; } // // Process EFI FMP Capsule // - DEBUG((DEBUG_INFO, "ProcessFmpCapsuleImage ...\n")); - Status = ProcessFmpCapsuleImage(CapsuleHeader, CapFileName, ResetRequired); - DEBUG((DEBUG_INFO, "ProcessFmpCapsuleImage - %r\n", Status)); + DEBUG ((DEBUG_INFO, "ProcessFmpCapsuleImage ...\n")); + Status = ProcessFmpCapsuleImage (CapsuleHeader, CapFileName, ResetRequired); + DEBUG ((DEBUG_INFO, "ProcessFmpCapsuleImage - %r\n", Status)); return Status; } @@ -1602,11 +1646,11 @@ DxeCapsuleLibEndOfDxe ( EFI_STATUS EFIAPI DxeCapsuleLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = gBS->CreateEventEx ( EVT_NOTIFY_SIGNAL, @@ -1618,7 +1662,7 @@ DxeCapsuleLibConstructor ( ); ASSERT_EFI_ERROR (Status); - InitCapsuleVariable(); + InitCapsuleVariable (); return EFI_SUCCESS; } @@ -1634,11 +1678,11 @@ DxeCapsuleLibConstructor ( EFI_STATUS EFIAPI DxeCapsuleLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Close the End of DXE event. diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleProcessLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleProcessLib.c index 6d05a9f229..2a38a3d95b 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleProcessLib.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleProcessLib.c @@ -102,7 +102,7 @@ IsValidCapsuleHeader ( **/ BOOLEAN IsCapsuleNameCapsule ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ); /** @@ -118,17 +118,17 @@ IsCapsuleNameCapsule ( **/ EFI_PHYSICAL_ADDRESS * ValidateCapsuleNameCapsuleIntegrity ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - OUT UINTN *CapsuleNameNum + IN EFI_CAPSULE_HEADER *CapsuleHeader, + OUT UINTN *CapsuleNameNum ); -extern BOOLEAN mDxeCapsuleLibEndOfDxe; -BOOLEAN mNeedReset = FALSE; +extern BOOLEAN mDxeCapsuleLibEndOfDxe; +BOOLEAN mNeedReset = FALSE; -VOID **mCapsulePtr; -CHAR16 **mCapsuleNamePtr; -EFI_STATUS *mCapsuleStatusArray; -UINT32 mCapsuleTotalNumber; +VOID **mCapsulePtr; +CHAR16 **mCapsuleNamePtr; +EFI_STATUS *mCapsuleStatusArray; +UINT32 mCapsuleTotalNumber; /** The firmware implements to process the capsule image. @@ -172,7 +172,7 @@ UpdateImageProgress ( UINTN Seconds; EFI_GRAPHICS_OUTPUT_BLT_PIXEL_UNION *Color; - DEBUG((DEBUG_INFO, "Update Progress - %d%%\n", Completion)); + DEBUG ((DEBUG_INFO, "Update Progress - %d%%\n", Completion)); if (Completion > 100) { return EFI_INVALID_PARAMETER; @@ -216,15 +216,15 @@ InitCapsulePtr ( VOID ) { - EFI_PEI_HOB_POINTERS HobPointer; - UINTN Index; - UINTN Index2; - UINTN Index3; - UINTN CapsuleNameNumber; - UINTN CapsuleNameTotalNumber; - UINTN CapsuleNameCapsuleTotalNumber; - VOID **CapsuleNameCapsulePtr; - EFI_PHYSICAL_ADDRESS *CapsuleNameAddress; + EFI_PEI_HOB_POINTERS HobPointer; + UINTN Index; + UINTN Index2; + UINTN Index3; + UINTN CapsuleNameNumber; + UINTN CapsuleNameTotalNumber; + UINTN CapsuleNameCapsuleTotalNumber; + VOID **CapsuleNameCapsulePtr; + EFI_PHYSICAL_ADDRESS *CapsuleNameAddress; CapsuleNameNumber = 0; CapsuleNameTotalNumber = 0; @@ -236,44 +236,47 @@ InitCapsulePtr ( // HobPointer.Raw = GetHobList (); while ((HobPointer.Raw = GetNextHob (EFI_HOB_TYPE_UEFI_CAPSULE, HobPointer.Raw)) != NULL) { - if (!IsValidCapsuleHeader((VOID *)(UINTN)HobPointer.Capsule->BaseAddress, HobPointer.Capsule->Length)) { + if (!IsValidCapsuleHeader ((VOID *)(UINTN)HobPointer.Capsule->BaseAddress, HobPointer.Capsule->Length)) { HobPointer.Header->HobType = EFI_HOB_TYPE_UNUSED; // Mark this hob as invalid } else { - if (IsCapsuleNameCapsule((VOID *)(UINTN)HobPointer.Capsule->BaseAddress)) { + if (IsCapsuleNameCapsule ((VOID *)(UINTN)HobPointer.Capsule->BaseAddress)) { CapsuleNameCapsuleTotalNumber++; } else { mCapsuleTotalNumber++; } } + HobPointer.Raw = GET_NEXT_HOB (HobPointer); } DEBUG ((DEBUG_INFO, "mCapsuleTotalNumber - 0x%x\n", mCapsuleTotalNumber)); if (mCapsuleTotalNumber == 0) { - return ; + return; } // // Init temp Capsule Data table. // - mCapsulePtr = (VOID **) AllocateZeroPool (sizeof (VOID *) * mCapsuleTotalNumber); + mCapsulePtr = (VOID **)AllocateZeroPool (sizeof (VOID *) * mCapsuleTotalNumber); if (mCapsulePtr == NULL) { DEBUG ((DEBUG_ERROR, "Allocate mCapsulePtr fail!\n")); mCapsuleTotalNumber = 0; - return ; + return; } - mCapsuleStatusArray = (EFI_STATUS *) AllocateZeroPool (sizeof (EFI_STATUS) * mCapsuleTotalNumber); + + mCapsuleStatusArray = (EFI_STATUS *)AllocateZeroPool (sizeof (EFI_STATUS) * mCapsuleTotalNumber); if (mCapsuleStatusArray == NULL) { DEBUG ((DEBUG_ERROR, "Allocate mCapsuleStatusArray fail!\n")); FreePool (mCapsulePtr); - mCapsulePtr = NULL; + mCapsulePtr = NULL; mCapsuleTotalNumber = 0; - return ; + return; } + SetMemN (mCapsuleStatusArray, sizeof (EFI_STATUS) * mCapsuleTotalNumber, EFI_NOT_READY); - CapsuleNameCapsulePtr = (VOID **) AllocateZeroPool (sizeof (VOID *) * CapsuleNameCapsuleTotalNumber); + CapsuleNameCapsulePtr = (VOID **)AllocateZeroPool (sizeof (VOID *) * CapsuleNameCapsuleTotalNumber); if (CapsuleNameCapsulePtr == NULL) { DEBUG ((DEBUG_ERROR, "Allocate CapsuleNameCapsulePtr fail!\n")); FreePool (mCapsulePtr); @@ -281,28 +284,29 @@ InitCapsulePtr ( mCapsulePtr = NULL; mCapsuleStatusArray = NULL; mCapsuleTotalNumber = 0; - return ; + return; } // // Find all capsule images from hob // HobPointer.Raw = GetHobList (); - Index = 0; - Index2 = 0; + Index = 0; + Index2 = 0; while ((HobPointer.Raw = GetNextHob (EFI_HOB_TYPE_UEFI_CAPSULE, HobPointer.Raw)) != NULL) { - if (IsCapsuleNameCapsule ((VOID *) (UINTN) HobPointer.Capsule->BaseAddress)) { - CapsuleNameCapsulePtr [Index2++] = (VOID *) (UINTN) HobPointer.Capsule->BaseAddress; + if (IsCapsuleNameCapsule ((VOID *)(UINTN)HobPointer.Capsule->BaseAddress)) { + CapsuleNameCapsulePtr[Index2++] = (VOID *)(UINTN)HobPointer.Capsule->BaseAddress; } else { - mCapsulePtr [Index++] = (VOID *) (UINTN) HobPointer.Capsule->BaseAddress; + mCapsulePtr[Index++] = (VOID *)(UINTN)HobPointer.Capsule->BaseAddress; } + HobPointer.Raw = GET_NEXT_HOB (HobPointer); } // // Find Capsule On Disk Names // - for (Index = 0; Index < CapsuleNameCapsuleTotalNumber; Index ++) { + for (Index = 0; Index < CapsuleNameCapsuleTotalNumber; Index++) { CapsuleNameAddress = ValidateCapsuleNameCapsuleIntegrity (CapsuleNameCapsulePtr[Index], &CapsuleNameNumber); if (CapsuleNameAddress != NULL ) { CapsuleNameTotalNumber += CapsuleNameNumber; @@ -310,7 +314,7 @@ InitCapsulePtr ( } if (CapsuleNameTotalNumber == mCapsuleTotalNumber) { - mCapsuleNamePtr = (CHAR16 **) AllocateZeroPool (sizeof (CHAR16 *) * mCapsuleTotalNumber); + mCapsuleNamePtr = (CHAR16 **)AllocateZeroPool (sizeof (CHAR16 *) * mCapsuleTotalNumber); if (mCapsuleNamePtr == NULL) { DEBUG ((DEBUG_ERROR, "Allocate mCapsuleNamePtr fail!\n")); FreePool (mCapsulePtr); @@ -319,14 +323,14 @@ InitCapsulePtr ( mCapsulePtr = NULL; mCapsuleStatusArray = NULL; mCapsuleTotalNumber = 0; - return ; + return; } - for (Index = 0, Index3 = 0; Index < CapsuleNameCapsuleTotalNumber; Index ++) { + for (Index = 0, Index3 = 0; Index < CapsuleNameCapsuleTotalNumber; Index++) { CapsuleNameAddress = ValidateCapsuleNameCapsuleIntegrity (CapsuleNameCapsulePtr[Index], &CapsuleNameNumber); if (CapsuleNameAddress != NULL ) { - for (Index2 = 0; Index2 < CapsuleNameNumber; Index2 ++) { - mCapsuleNamePtr[Index3 ++] = (CHAR16 *)(UINTN) CapsuleNameAddress[Index2]; + for (Index2 = 0; Index2 < CapsuleNameNumber; Index2++) { + mCapsuleNamePtr[Index3++] = (CHAR16 *)(UINTN)CapsuleNameAddress[Index2]; } } } @@ -367,36 +371,37 @@ PopulateCapsuleInConfigurationTable ( VOID ) { - VOID **CapsulePtrCache; - EFI_GUID *CapsuleGuidCache; - EFI_CAPSULE_HEADER *CapsuleHeader; - EFI_CAPSULE_TABLE *CapsuleTable; - UINT32 CacheIndex; - UINT32 CacheNumber; - UINT32 CapsuleNumber; - UINTN Index; - UINTN Size; - EFI_STATUS Status; + VOID **CapsulePtrCache; + EFI_GUID *CapsuleGuidCache; + EFI_CAPSULE_HEADER *CapsuleHeader; + EFI_CAPSULE_TABLE *CapsuleTable; + UINT32 CacheIndex; + UINT32 CacheNumber; + UINT32 CapsuleNumber; + UINTN Index; + UINTN Size; + EFI_STATUS Status; if (mCapsuleTotalNumber == 0) { - return ; + return; } - CapsulePtrCache = NULL; - CapsuleGuidCache = NULL; - CacheIndex = 0; - CacheNumber = 0; + CapsulePtrCache = NULL; + CapsuleGuidCache = NULL; + CacheIndex = 0; + CacheNumber = 0; - CapsulePtrCache = (VOID **) AllocateZeroPool (sizeof (VOID *) * mCapsuleTotalNumber); + CapsulePtrCache = (VOID **)AllocateZeroPool (sizeof (VOID *) * mCapsuleTotalNumber); if (CapsulePtrCache == NULL) { DEBUG ((DEBUG_ERROR, "Allocate CapsulePtrCache fail!\n")); - return ; + return; } - CapsuleGuidCache = (EFI_GUID *) AllocateZeroPool (sizeof (EFI_GUID) * mCapsuleTotalNumber); + + CapsuleGuidCache = (EFI_GUID *)AllocateZeroPool (sizeof (EFI_GUID) * mCapsuleTotalNumber); if (CapsuleGuidCache == NULL) { DEBUG ((DEBUG_ERROR, "Allocate CapsuleGuidCache fail!\n")); FreePool (CapsulePtrCache); - return ; + return; } // @@ -410,7 +415,7 @@ PopulateCapsuleInConfigurationTable ( // array for later sorting capsules by CapsuleGuid. // for (Index = 0; Index < mCapsuleTotalNumber; Index++) { - CapsuleHeader = (EFI_CAPSULE_HEADER*) mCapsulePtr [Index]; + CapsuleHeader = (EFI_CAPSULE_HEADER *)mCapsulePtr[Index]; if ((CapsuleHeader->Flags & CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE) != 0) { // // For each capsule, we compare it with known CapsuleGuid in the CacheArray. @@ -419,13 +424,15 @@ PopulateCapsuleInConfigurationTable ( // CacheIndex = 0; while (CacheIndex < CacheNumber) { - if (CompareGuid(&CapsuleGuidCache[CacheIndex],&CapsuleHeader->CapsuleGuid)) { + if (CompareGuid (&CapsuleGuidCache[CacheIndex], &CapsuleHeader->CapsuleGuid)) { break; } + CacheIndex++; } + if (CacheIndex == CacheNumber) { - CopyMem(&CapsuleGuidCache[CacheNumber++],&CapsuleHeader->CapsuleGuid,sizeof(EFI_GUID)); + CopyMem (&CapsuleGuidCache[CacheNumber++], &CapsuleHeader->CapsuleGuid, sizeof (EFI_GUID)); } } } @@ -442,34 +449,36 @@ PopulateCapsuleInConfigurationTable ( for (CacheIndex = 0; CacheIndex < CacheNumber; CacheIndex++) { CapsuleNumber = 0; for (Index = 0; Index < mCapsuleTotalNumber; Index++) { - CapsuleHeader = (EFI_CAPSULE_HEADER*) mCapsulePtr [Index]; + CapsuleHeader = (EFI_CAPSULE_HEADER *)mCapsulePtr[Index]; if ((CapsuleHeader->Flags & CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE) != 0) { if (CompareGuid (&CapsuleGuidCache[CacheIndex], &CapsuleHeader->CapsuleGuid)) { // // Cache Caspuleheader to the array, this array is uniqued with certain CapsuleGuid. // - CapsulePtrCache[CapsuleNumber++] = (VOID*)CapsuleHeader; + CapsulePtrCache[CapsuleNumber++] = (VOID *)CapsuleHeader; } } } + if (CapsuleNumber != 0) { - Size = sizeof(EFI_CAPSULE_TABLE) + (CapsuleNumber - 1) * sizeof(VOID*); + Size = sizeof (EFI_CAPSULE_TABLE) + (CapsuleNumber - 1) * sizeof (VOID *); CapsuleTable = AllocateRuntimePool (Size); if (CapsuleTable == NULL) { DEBUG ((DEBUG_ERROR, "Allocate CapsuleTable (%g) fail!\n", &CapsuleGuidCache[CacheIndex])); continue; } + CapsuleTable->CapsuleArrayNumber = CapsuleNumber; - CopyMem(&CapsuleTable->CapsulePtr[0], CapsulePtrCache, CapsuleNumber * sizeof(VOID*)); - Status = gBS->InstallConfigurationTable (&CapsuleGuidCache[CacheIndex], (VOID*)CapsuleTable); + CopyMem (&CapsuleTable->CapsulePtr[0], CapsulePtrCache, CapsuleNumber * sizeof (VOID *)); + Status = gBS->InstallConfigurationTable (&CapsuleGuidCache[CacheIndex], (VOID *)CapsuleTable); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "InstallConfigurationTable (%g) fail!\n", &CapsuleGuidCache[CacheIndex])); } } } - FreePool(CapsuleGuidCache); - FreePool(CapsulePtrCache); + FreePool (CapsuleGuidCache); + FreePool (CapsulePtrCache); } /** @@ -492,15 +501,15 @@ ProcessTheseCapsules ( IN BOOLEAN FirstRound ) { - EFI_STATUS Status; - EFI_CAPSULE_HEADER *CapsuleHeader; - UINT32 Index; - ESRT_MANAGEMENT_PROTOCOL *EsrtManagement; - UINT16 EmbeddedDriverCount; - BOOLEAN ResetRequired; - CHAR16 *CapsuleName; + EFI_STATUS Status; + EFI_CAPSULE_HEADER *CapsuleHeader; + UINT32 Index; + ESRT_MANAGEMENT_PROTOCOL *EsrtManagement; + UINT16 EmbeddedDriverCount; + BOOLEAN ResetRequired; + CHAR16 *CapsuleName; - REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeProcessCapsulesBegin))); + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeProcessCapsulesBegin))); if (FirstRound) { InitCapsulePtr (); @@ -527,20 +536,20 @@ ProcessTheseCapsules ( PopulateCapsuleInConfigurationTable (); } - REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeUpdatingFirmware))); + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeUpdatingFirmware))); // // If Windows UX capsule exist, process it first // for (Index = 0; Index < mCapsuleTotalNumber; Index++) { - CapsuleHeader = (EFI_CAPSULE_HEADER*) mCapsulePtr [Index]; - CapsuleName = (mCapsuleNamePtr == NULL) ? NULL : mCapsuleNamePtr[Index]; + CapsuleHeader = (EFI_CAPSULE_HEADER *)mCapsulePtr[Index]; + CapsuleName = (mCapsuleNamePtr == NULL) ? NULL : mCapsuleNamePtr[Index]; if (CompareGuid (&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { DEBUG ((DEBUG_INFO, "ProcessThisCapsuleImage (Ux) - 0x%x\n", CapsuleHeader)); DEBUG ((DEBUG_INFO, "Display logo capsule is found.\n")); - Status = ProcessThisCapsuleImage (CapsuleHeader, CapsuleName, NULL); - mCapsuleStatusArray [Index] = EFI_SUCCESS; - DEBUG((DEBUG_INFO, "ProcessThisCapsuleImage (Ux) - %r\n", Status)); + Status = ProcessThisCapsuleImage (CapsuleHeader, CapsuleName, NULL); + mCapsuleStatusArray[Index] = EFI_SUCCESS; + DEBUG ((DEBUG_INFO, "ProcessThisCapsuleImage (Ux) - %r\n", Status)); break; } } @@ -551,46 +560,47 @@ ProcessTheseCapsules ( // All capsules left are recognized by platform. // for (Index = 0; Index < mCapsuleTotalNumber; Index++) { - if (mCapsuleStatusArray [Index] != EFI_NOT_READY) { + if (mCapsuleStatusArray[Index] != EFI_NOT_READY) { // already processed continue; } - CapsuleHeader = (EFI_CAPSULE_HEADER*) mCapsulePtr [Index]; - CapsuleName = (mCapsuleNamePtr == NULL) ? NULL : mCapsuleNamePtr[Index]; + + CapsuleHeader = (EFI_CAPSULE_HEADER *)mCapsulePtr[Index]; + CapsuleName = (mCapsuleNamePtr == NULL) ? NULL : mCapsuleNamePtr[Index]; if (!CompareGuid (&CapsuleHeader->CapsuleGuid, &gWindowsUxCapsuleGuid)) { // // Call capsule library to process capsule image. // EmbeddedDriverCount = 0; - if (IsFmpCapsule(CapsuleHeader)) { + if (IsFmpCapsule (CapsuleHeader)) { Status = ValidateFmpCapsule (CapsuleHeader, &EmbeddedDriverCount); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "ValidateFmpCapsule failed. Ignore!\n")); - mCapsuleStatusArray [Index] = EFI_ABORTED; + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "ValidateFmpCapsule failed. Ignore!\n")); + mCapsuleStatusArray[Index] = EFI_ABORTED; continue; } } else { - mCapsuleStatusArray [Index] = EFI_ABORTED; + mCapsuleStatusArray[Index] = EFI_ABORTED; continue; } if ((!FirstRound) || (EmbeddedDriverCount == 0)) { - DEBUG((DEBUG_INFO, "ProcessThisCapsuleImage - 0x%x\n", CapsuleHeader)); - ResetRequired = FALSE; - Status = ProcessThisCapsuleImage (CapsuleHeader, CapsuleName, &ResetRequired); - mCapsuleStatusArray [Index] = Status; - DEBUG((DEBUG_INFO, "ProcessThisCapsuleImage - %r\n", Status)); + DEBUG ((DEBUG_INFO, "ProcessThisCapsuleImage - 0x%x\n", CapsuleHeader)); + ResetRequired = FALSE; + Status = ProcessThisCapsuleImage (CapsuleHeader, CapsuleName, &ResetRequired); + mCapsuleStatusArray[Index] = Status; + DEBUG ((DEBUG_INFO, "ProcessThisCapsuleImage - %r\n", Status)); if (Status != EFI_NOT_READY) { - if (EFI_ERROR(Status)) { - REPORT_STATUS_CODE(EFI_ERROR_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeUpdateFirmwareFailed))); + if (EFI_ERROR (Status)) { + REPORT_STATUS_CODE (EFI_ERROR_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeUpdateFirmwareFailed))); DEBUG ((DEBUG_ERROR, "Capsule process failed!\n")); } else { - REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeUpdateFirmwareSuccess))); + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeUpdateFirmwareSuccess))); } mNeedReset |= ResetRequired; - if ((CapsuleHeader->Flags & PcdGet16(PcdSystemRebootAfterCapsuleProcessFlag)) != 0) { + if ((CapsuleHeader->Flags & PcdGet16 (PcdSystemRebootAfterCapsuleProcessFlag)) != 0) { mNeedReset = TRUE; } } @@ -598,16 +608,17 @@ ProcessTheseCapsules ( } } - Status = gBS->LocateProtocol(&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtManagement); + Status = gBS->LocateProtocol (&gEsrtManagementProtocolGuid, NULL, (VOID **)&EsrtManagement); // // Always sync ESRT Cache from FMP Instance // - if (!EFI_ERROR(Status)) { - EsrtManagement->SyncEsrtFmp(); + if (!EFI_ERROR (Status)) { + EsrtManagement->SyncEsrtFmp (); } + Status = EFI_SUCCESS; - REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeProcessCapsulesEnd))); + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeProcessCapsulesEnd))); return Status; } @@ -620,13 +631,13 @@ DoResetSystem ( VOID ) { - DEBUG((DEBUG_INFO, "Capsule Request Cold Reboot.")); + DEBUG ((DEBUG_INFO, "Capsule Request Cold Reboot.")); - REPORT_STATUS_CODE(EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32(PcdStatusCodeSubClassCapsule) | PcdGet32(PcdCapsuleStatusCodeResettingSystem))); + REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE | PcdGet32 (PcdStatusCodeSubClassCapsule) | PcdGet32 (PcdCapsuleStatusCodeResettingSystem))); - gRT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); + gRT->ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); - CpuDeadLoop(); + CpuDeadLoop (); } /** @@ -666,26 +677,27 @@ ProcessCapsules ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; if (!mDxeCapsuleLibEndOfDxe) { - Status = ProcessTheseCapsules(TRUE); + Status = ProcessTheseCapsules (TRUE); // // Reboot System if and only if all capsule processed. // If not, defer reset to 2nd process. // - if (mNeedReset && AreAllImagesProcessed()) { - DoResetSystem(); + if (mNeedReset && AreAllImagesProcessed ()) { + DoResetSystem (); } } else { - Status = ProcessTheseCapsules(FALSE); + Status = ProcessTheseCapsules (FALSE); // // Reboot System if required after all capsule processed // if (mNeedReset) { - DoResetSystem(); + DoResetSystem (); } } + return Status; } diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c index 82f8c1f49c..efc6b4ce26 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLib.c @@ -37,7 +37,7 @@ **/ EFI_STATUS -CoDClearCapsuleRelocationInfo( +CoDClearCapsuleRelocationInfo ( VOID ); @@ -52,23 +52,24 @@ GetCurrentCapsuleLastIndex ( VOID ) { - UINTN Size; - CHAR16 CapsuleLastStr[sizeof("Capsule####")]; - EFI_STATUS Status; - UINT16 CurrentIndex; + UINTN Size; + CHAR16 CapsuleLastStr[sizeof ("Capsule####")]; + EFI_STATUS Status; + UINT16 CurrentIndex; - Size = sizeof(L"Capsule####") - sizeof(CHAR16); // no zero terminator - Status = gRT->GetVariable( + Size = sizeof (L"Capsule####") - sizeof (CHAR16); // no zero terminator + Status = gRT->GetVariable ( L"CapsuleLast", &gEfiCapsuleReportGuid, NULL, &Size, CapsuleLastStr ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { return -1; } - CurrentIndex = (UINT16)StrHexToUintn(&CapsuleLastStr[sizeof("Capsule") - 1]); + + CurrentIndex = (UINT16)StrHexToUintn (&CapsuleLastStr[sizeof ("Capsule") - 1]); return CurrentIndex; } @@ -83,11 +84,11 @@ GetNewCapsuleResultIndex ( VOID ) { - INTN CurrentIndex; + INTN CurrentIndex; - CurrentIndex = GetCurrentCapsuleLastIndex(); - if (CurrentIndex >= PcdGet16(PcdCapsuleMax)) { - DEBUG((DEBUG_INFO, " CapsuleResult variable Rolling Over!\n")); + CurrentIndex = GetCurrentCapsuleLastIndex (); + if (CurrentIndex >= PcdGet16 (PcdCapsuleMax)) { + DEBUG ((DEBUG_INFO, " CapsuleResult variable Rolling Over!\n")); return 0; } @@ -108,22 +109,27 @@ LockVariable ( IN EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy ) { - EFI_STATUS Status; + EFI_STATUS Status; // Set the policies to protect the target variables - Status = RegisterBasicVariablePolicy (VariablePolicy, - &VariableGuid, - VariableName, - VARIABLE_POLICY_NO_MIN_SIZE, - VARIABLE_POLICY_NO_MAX_SIZE, - VARIABLE_POLICY_NO_MUST_ATTR, - VARIABLE_POLICY_NO_CANT_ATTR, - VARIABLE_POLICY_TYPE_LOCK_NOW); + Status = RegisterBasicVariablePolicy ( + VariablePolicy, + &VariableGuid, + VariableName, + VARIABLE_POLICY_NO_MIN_SIZE, + VARIABLE_POLICY_NO_MAX_SIZE, + VARIABLE_POLICY_NO_MUST_ATTR, + VARIABLE_POLICY_NO_CANT_ATTR, + VARIABLE_POLICY_TYPE_LOCK_NOW + ); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "DxeCapsuleLibFmp: Failed to lock variable %g %s. Status = %r\n", - &VariableGuid, - VariableName, - Status)); + DEBUG (( + DEBUG_ERROR, + "DxeCapsuleLibFmp: Failed to lock variable %g %s. Status = %r\n", + &VariableGuid, + VariableName, + Status + )); ASSERT_EFI_ERROR (Status); } } @@ -139,36 +145,36 @@ LockVariable ( **/ EFI_STATUS WriteNewCapsuleResultVariable ( - IN VOID *CapsuleResult, - IN UINTN CapsuleResultSize + IN VOID *CapsuleResult, + IN UINTN CapsuleResultSize ) { - INTN CapsuleResultIndex; - CHAR16 CapsuleResultStr[sizeof("Capsule####")]; - UINTN Size; - EFI_STATUS Status; + INTN CapsuleResultIndex; + CHAR16 CapsuleResultStr[sizeof ("Capsule####")]; + UINTN Size; + EFI_STATUS Status; - CapsuleResultIndex = GetNewCapsuleResultIndex(); - DEBUG((DEBUG_INFO, "New CapsuleResultIndex - 0x%x\n", CapsuleResultIndex)); + CapsuleResultIndex = GetNewCapsuleResultIndex (); + DEBUG ((DEBUG_INFO, "New CapsuleResultIndex - 0x%x\n", CapsuleResultIndex)); - UnicodeSPrint( + UnicodeSPrint ( CapsuleResultStr, - sizeof(CapsuleResultStr), + sizeof (CapsuleResultStr), L"Capsule%04x", CapsuleResultIndex ); - Status = gRT->SetVariable( + Status = gRT->SetVariable ( CapsuleResultStr, &gEfiCapsuleReportGuid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, CapsuleResultSize, CapsuleResult ); - if (!EFI_ERROR(Status)) { - Size = sizeof(L"Capsule####") - sizeof(CHAR16); // no zero terminator - DEBUG((DEBUG_INFO, "Set CapsuleLast - %s\n", CapsuleResultStr)); - Status = gRT->SetVariable( + if (!EFI_ERROR (Status)) { + Size = sizeof (L"Capsule####") - sizeof (CHAR16); // no zero terminator + DEBUG ((DEBUG_INFO, "Set CapsuleLast - %s\n", CapsuleResultStr)); + Status = gRT->SetVariable ( L"CapsuleLast", &gEfiCapsuleReportGuid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, @@ -191,24 +197,25 @@ WriteNewCapsuleResultVariable ( **/ EFI_STATUS RecordCapsuleStatusVariable ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - IN EFI_STATUS CapsuleStatus + IN EFI_CAPSULE_HEADER *CapsuleHeader, + IN EFI_STATUS CapsuleStatus ) { EFI_CAPSULE_RESULT_VARIABLE_HEADER CapsuleResultVariable; EFI_STATUS Status; - CapsuleResultVariable.VariableTotalSize = sizeof(CapsuleResultVariable); - CapsuleResultVariable.Reserved = 0; + CapsuleResultVariable.VariableTotalSize = sizeof (CapsuleResultVariable); + CapsuleResultVariable.Reserved = 0; CopyGuid (&CapsuleResultVariable.CapsuleGuid, &CapsuleHeader->CapsuleGuid); - ZeroMem(&CapsuleResultVariable.CapsuleProcessed, sizeof(CapsuleResultVariable.CapsuleProcessed)); - gRT->GetTime(&CapsuleResultVariable.CapsuleProcessed, NULL); + ZeroMem (&CapsuleResultVariable.CapsuleProcessed, sizeof (CapsuleResultVariable.CapsuleProcessed)); + gRT->GetTime (&CapsuleResultVariable.CapsuleProcessed, NULL); CapsuleResultVariable.CapsuleStatus = CapsuleStatus; Status = EFI_SUCCESS; if ((CapsuleHeader->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { - Status = WriteNewCapsuleResultVariable(&CapsuleResultVariable, sizeof(CapsuleResultVariable)); + Status = WriteNewCapsuleResultVariable (&CapsuleResultVariable, sizeof (CapsuleResultVariable)); } + return Status; } @@ -245,58 +252,61 @@ RecordFmpCapsuleStatusVariable ( UINTN CapFileNameSize; DevicePathStr = NULL; - CapFileNameSize = sizeof(CHAR16); + CapFileNameSize = sizeof (CHAR16); if (FmpDevicePath != NULL) { DevicePathStr = ConvertDevicePathToText (FmpDevicePath, FALSE, FALSE); } + if (DevicePathStr != NULL) { - DevicePathStrSize = StrSize(DevicePathStr); + DevicePathStrSize = StrSize (DevicePathStr); } else { - DevicePathStrSize = sizeof(CHAR16); + DevicePathStrSize = sizeof (CHAR16); } if (CapFileName != NULL) { - CapFileNameSize = StrSize(CapFileName); + CapFileNameSize = StrSize (CapFileName); } // // Allocate room for CapsuleFileName. // - CapsuleResultVariableSize = sizeof(EFI_CAPSULE_RESULT_VARIABLE_HEADER) + sizeof(EFI_CAPSULE_RESULT_VARIABLE_FMP) + CapFileNameSize + DevicePathStrSize; + CapsuleResultVariableSize = sizeof (EFI_CAPSULE_RESULT_VARIABLE_HEADER) + sizeof (EFI_CAPSULE_RESULT_VARIABLE_FMP) + CapFileNameSize + DevicePathStrSize; - CapsuleResultVariable = AllocateZeroPool (CapsuleResultVariableSize); + CapsuleResultVariable = AllocateZeroPool (CapsuleResultVariableSize); if (CapsuleResultVariable == NULL) { return EFI_OUT_OF_RESOURCES; } - CapsuleResultVariableHeader = (VOID *)CapsuleResultVariable; + + CapsuleResultVariableHeader = (VOID *)CapsuleResultVariable; CapsuleResultVariableHeader->VariableTotalSize = (UINT32)CapsuleResultVariableSize; - CapsuleResultVariableHeader->Reserved = 0; - CopyGuid(&CapsuleResultVariableHeader->CapsuleGuid, &CapsuleHeader->CapsuleGuid); - ZeroMem(&CapsuleResultVariableHeader->CapsuleProcessed, sizeof(CapsuleResultVariableHeader->CapsuleProcessed)); - gRT->GetTime(&CapsuleResultVariableHeader->CapsuleProcessed, NULL); + CapsuleResultVariableHeader->Reserved = 0; + CopyGuid (&CapsuleResultVariableHeader->CapsuleGuid, &CapsuleHeader->CapsuleGuid); + ZeroMem (&CapsuleResultVariableHeader->CapsuleProcessed, sizeof (CapsuleResultVariableHeader->CapsuleProcessed)); + gRT->GetTime (&CapsuleResultVariableHeader->CapsuleProcessed, NULL); CapsuleResultVariableHeader->CapsuleStatus = CapsuleStatus; - CapsuleResultVariableFmp = (VOID *)(CapsuleResultVariable + sizeof(EFI_CAPSULE_RESULT_VARIABLE_HEADER)); - CapsuleResultVariableFmp->Version = 0x1; - CapsuleResultVariableFmp->PayloadIndex = (UINT8)PayloadIndex; + CapsuleResultVariableFmp = (VOID *)(CapsuleResultVariable + sizeof (EFI_CAPSULE_RESULT_VARIABLE_HEADER)); + CapsuleResultVariableFmp->Version = 0x1; + CapsuleResultVariableFmp->PayloadIndex = (UINT8)PayloadIndex; CapsuleResultVariableFmp->UpdateImageIndex = ImageHeader->UpdateImageIndex; CopyGuid (&CapsuleResultVariableFmp->UpdateImageTypeId, &ImageHeader->UpdateImageTypeId); if (CapFileName != NULL) { - CopyMem((UINT8 *)CapsuleResultVariableFmp + sizeof(EFI_CAPSULE_RESULT_VARIABLE_FMP), CapFileName, CapFileNameSize); + CopyMem ((UINT8 *)CapsuleResultVariableFmp + sizeof (EFI_CAPSULE_RESULT_VARIABLE_FMP), CapFileName, CapFileNameSize); } if (DevicePathStr != NULL) { - CopyMem ((UINT8 *)CapsuleResultVariableFmp + sizeof(EFI_CAPSULE_RESULT_VARIABLE_FMP) + CapFileNameSize, DevicePathStr, DevicePathStrSize); + CopyMem ((UINT8 *)CapsuleResultVariableFmp + sizeof (EFI_CAPSULE_RESULT_VARIABLE_FMP) + CapFileNameSize, DevicePathStr, DevicePathStrSize); FreePool (DevicePathStr); DevicePathStr = NULL; } Status = EFI_SUCCESS; if ((CapsuleHeader->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { - Status = WriteNewCapsuleResultVariable(CapsuleResultVariable, CapsuleResultVariableSize); + Status = WriteNewCapsuleResultVariable (CapsuleResultVariable, CapsuleResultVariableSize); } + FreePool (CapsuleResultVariable); return Status; } @@ -308,29 +318,29 @@ RecordFmpCapsuleStatusVariable ( **/ VOID InitCapsuleMaxVariable ( - EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy + EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy ) { - EFI_STATUS Status; - UINTN Size; - CHAR16 CapsuleMaxStr[sizeof("Capsule####")]; + EFI_STATUS Status; + UINTN Size; + CHAR16 CapsuleMaxStr[sizeof ("Capsule####")]; - UnicodeSPrint( + UnicodeSPrint ( CapsuleMaxStr, - sizeof(CapsuleMaxStr), + sizeof (CapsuleMaxStr), L"Capsule%04x", - PcdGet16(PcdCapsuleMax) + PcdGet16 (PcdCapsuleMax) ); - Size = sizeof(L"Capsule####") - sizeof(CHAR16); // no zero terminator - Status = gRT->SetVariable( + Size = sizeof (L"Capsule####") - sizeof (CHAR16); // no zero terminator + Status = gRT->SetVariable ( L"CapsuleMax", &gEfiCapsuleReportGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, Size, CapsuleMaxStr ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { // Lock it per UEFI spec. LockVariable (gEfiCapsuleReportGuid, L"CapsuleMax", VariablePolicy); } @@ -343,18 +353,18 @@ InitCapsuleMaxVariable ( **/ VOID InitCapsuleLastVariable ( - EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy + EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy ) { - EFI_STATUS Status; - EFI_BOOT_MODE BootMode; - VOID *CapsuleResult; - UINTN Size; - CHAR16 CapsuleLastStr[sizeof("Capsule####")]; + EFI_STATUS Status; + EFI_BOOT_MODE BootMode; + VOID *CapsuleResult; + UINTN Size; + CHAR16 CapsuleLastStr[sizeof ("Capsule####")]; - BootMode = GetBootModeHob(); + BootMode = GetBootModeHob (); if (BootMode == BOOT_ON_FLASH_UPDATE) { - Status = gRT->SetVariable( + Status = gRT->SetVariable ( L"CapsuleLast", &gEfiCapsuleReportGuid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, @@ -366,30 +376,30 @@ InitCapsuleLastVariable ( // // Check if OS/APP cleared L"Capsule####" // - ZeroMem(CapsuleLastStr, sizeof(CapsuleLastStr)); - Size = sizeof(L"Capsule####") - sizeof(CHAR16); // no zero terminator - Status = gRT->GetVariable( + ZeroMem (CapsuleLastStr, sizeof (CapsuleLastStr)); + Size = sizeof (L"Capsule####") - sizeof (CHAR16); // no zero terminator + Status = gRT->GetVariable ( L"CapsuleLast", &gEfiCapsuleReportGuid, NULL, &Size, CapsuleLastStr ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { // // L"CapsuleLast" is got, check if data is there. // Status = GetVariable2 ( CapsuleLastStr, &gEfiCapsuleReportGuid, - (VOID **) &CapsuleResult, + (VOID **)&CapsuleResult, NULL ); - if (EFI_ERROR(Status)) { + if (EFI_ERROR (Status)) { // // If no data, delete L"CapsuleLast" // - Status = gRT->SetVariable( + Status = gRT->SetVariable ( L"CapsuleLast", &gEfiCapsuleReportGuid, EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS, @@ -416,19 +426,19 @@ InitCapsuleUpdateVariable ( VOID ) { - EFI_STATUS Status; - UINTN Index; - CHAR16 CapsuleVarName[30]; - CHAR16 *TempVarName; + EFI_STATUS Status; + UINTN Index; + CHAR16 CapsuleVarName[30]; + CHAR16 *TempVarName; // // Clear all the capsule variables CapsuleUpdateData, CapsuleUpdateData1, CapsuleUpdateData2... // as early as possible which will avoid the next time boot after the capsule update // will still into the capsule loop // - StrCpyS (CapsuleVarName, sizeof(CapsuleVarName)/sizeof(CapsuleVarName[0]), EFI_CAPSULE_VARIABLE_NAME); + StrCpyS (CapsuleVarName, sizeof (CapsuleVarName)/sizeof (CapsuleVarName[0]), EFI_CAPSULE_VARIABLE_NAME); TempVarName = CapsuleVarName + StrLen (CapsuleVarName); - Index = 0; + Index = 0; while (TRUE) { if (Index > 0) { UnicodeValueToStringS ( @@ -439,6 +449,7 @@ InitCapsuleUpdateVariable ( 0 ); } + Status = gRT->SetVariable ( CapsuleVarName, &gEfiCapsuleVendorGuid, @@ -452,6 +463,7 @@ InitCapsuleUpdateVariable ( // break; } + Index++; } } @@ -463,15 +475,15 @@ InitCapsuleUpdateVariable ( **/ VOID InitCapsuleRelocationInfo ( - EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy + EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy ) { - CoDClearCapsuleRelocationInfo(); + CoDClearCapsuleRelocationInfo (); // // Unlock Capsule On Disk relocation Info variable only when Capsule On Disk flag is enabled // - if (!CoDCheckCapsuleOnDiskFlag()) { + if (!CoDCheckCapsuleOnDiskFlag ()) { LockVariable (gEfiCapsuleVendorGuid, COD_RELOCATION_INFO_VAR_NAME, VariablePolicy); } } @@ -484,16 +496,17 @@ InitCapsuleVariable ( VOID ) { - EFI_STATUS Status; - EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy; + EFI_STATUS Status; + EDKII_VARIABLE_POLICY_PROTOCOL *VariablePolicy; // Locate the VariablePolicy protocol - Status = gBS->LocateProtocol (&gEdkiiVariablePolicyProtocolGuid, NULL, (VOID**)&VariablePolicy); + Status = gBS->LocateProtocol (&gEdkiiVariablePolicyProtocolGuid, NULL, (VOID **)&VariablePolicy); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "DxeCapsuleReportLib %a - Could not locate VariablePolicy protocol! %r\n", __FUNCTION__, Status)); ASSERT_EFI_ERROR (Status); } - InitCapsuleUpdateVariable(); + + InitCapsuleUpdateVariable (); InitCapsuleMaxVariable (VariablePolicy); InitCapsuleLastVariable (VariablePolicy); InitCapsuleRelocationInfo (VariablePolicy); diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLibNull.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLibNull.c index 958229521e..b425e99e67 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLibNull.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleReportLibNull.c @@ -24,8 +24,8 @@ **/ EFI_STATUS RecordCapsuleStatusVariable ( - IN EFI_CAPSULE_HEADER *CapsuleHeader, - IN EFI_STATUS CapsuleStatus + IN EFI_CAPSULE_HEADER *CapsuleHeader, + IN EFI_STATUS CapsuleStatus ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleRuntime.c b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleRuntime.c index f94044a409..9ceb44fe4d 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleRuntime.c +++ b/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleRuntime.c @@ -20,10 +20,10 @@ #include #include -extern EFI_SYSTEM_RESOURCE_TABLE *mEsrtTable; -extern BOOLEAN mIsVirtualAddrConverted; -EFI_EVENT mDxeRuntimeCapsuleLibVirtualAddressChangeEvent = NULL; -EFI_EVENT mDxeRuntimeCapsuleLibReadyToBootEvent = NULL; +extern EFI_SYSTEM_RESOURCE_TABLE *mEsrtTable; +extern BOOLEAN mIsVirtualAddrConverted; +EFI_EVENT mDxeRuntimeCapsuleLibVirtualAddressChangeEvent = NULL; +EFI_EVENT mDxeRuntimeCapsuleLibReadyToBootEvent = NULL; /** Convert EsrtTable physical address to virtual address. @@ -35,8 +35,8 @@ EFI_EVENT mDxeRuntimeCapsuleLibReadyToBootEvent = NULL; VOID EFIAPI DxeCapsuleLibVirtualAddressChangeEvent ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { gRT->ConvertPointer (EFI_OPTIONAL_PTR, (VOID **)&mEsrtTable); @@ -54,22 +54,23 @@ STATIC VOID EFIAPI DxeCapsuleLibReadyToBootEventNotify ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - UINTN Index; - EFI_CONFIGURATION_TABLE *ConfigEntry; - EFI_SYSTEM_RESOURCE_TABLE *EsrtTable; + UINTN Index; + EFI_CONFIGURATION_TABLE *ConfigEntry; + EFI_SYSTEM_RESOURCE_TABLE *EsrtTable; // // Get Esrt table first // ConfigEntry = gST->ConfigurationTable; for (Index = 0; Index < gST->NumberOfTableEntries; Index++) { - if (CompareGuid(&gEfiSystemResourceTableGuid, &ConfigEntry->VendorGuid)) { + if (CompareGuid (&gEfiSystemResourceTableGuid, &ConfigEntry->VendorGuid)) { break; } + ConfigEntry++; } @@ -80,12 +81,13 @@ DxeCapsuleLibReadyToBootEventNotify ( // // Search Esrt to check given capsule is qualified // - EsrtTable = (EFI_SYSTEM_RESOURCE_TABLE *) ConfigEntry->VendorTable; + EsrtTable = (EFI_SYSTEM_RESOURCE_TABLE *)ConfigEntry->VendorTable; mEsrtTable = AllocateRuntimeCopyPool ( sizeof (EFI_SYSTEM_RESOURCE_TABLE) + EsrtTable->FwResourceCount * sizeof (EFI_SYSTEM_RESOURCE_ENTRY), - EsrtTable); + EsrtTable + ); ASSERT (mEsrtTable != NULL); // @@ -106,11 +108,11 @@ DxeCapsuleLibReadyToBootEventNotify ( EFI_STATUS EFIAPI DxeRuntimeCapsuleLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Make sure we can handle virtual address changes. @@ -152,11 +154,11 @@ DxeRuntimeCapsuleLibConstructor ( EFI_STATUS EFIAPI DxeRuntimeCapsuleLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Close the VirtualAddressChange event. diff --git a/MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.c b/MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.c index 55985abd78..aced356324 100644 --- a/MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.c +++ b/MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.c @@ -21,7 +21,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI SupportCapsuleImage ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { return EFI_UNSUPPORTED; @@ -40,7 +40,7 @@ SupportCapsuleImage ( EFI_STATUS EFIAPI ProcessCapsuleImage ( - IN EFI_CAPSULE_HEADER *CapsuleHeader + IN EFI_CAPSULE_HEADER *CapsuleHeader ) { return EFI_UNSUPPORTED; @@ -85,7 +85,6 @@ ProcessCapsules ( return EFI_UNSUPPORTED; } - /** This routine is called to check if CapsuleOnDisk flag in OsIndications Variable is enabled. @@ -96,7 +95,7 @@ ProcessCapsules ( **/ BOOLEAN EFIAPI -CoDCheckCapsuleOnDiskFlag( +CoDCheckCapsuleOnDiskFlag ( VOID ) { @@ -111,7 +110,7 @@ CoDCheckCapsuleOnDiskFlag( **/ EFI_STATUS EFIAPI -CoDClearCapsuleOnDiskFlag( +CoDClearCapsuleOnDiskFlag ( VOID ) { @@ -142,8 +141,8 @@ CoDClearCapsuleOnDiskFlag( **/ EFI_STATUS EFIAPI -CoDRelocateCapsule( - UINTN MaxRetry +CoDRelocateCapsule ( + UINTN MaxRetry ) { return EFI_UNSUPPORTED; @@ -163,7 +162,7 @@ CoDRelocateCapsule( EFI_STATUS EFIAPI CoDRemoveTempFile ( - UINTN MaxRetry + UINTN MaxRetry ) { return EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationServices.h b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationServices.h index 73b3569b64..acbb666bbd 100644 --- a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationServices.h +++ b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationServices.h @@ -12,7 +12,6 @@ #ifndef _DXE_CORE_MEMORY_ALLOCATION_SERVICES_H_ #define _DXE_CORE_MEMORY_ALLOCATION_SERVICES_H_ - /** Allocates pages from the memory map. @@ -34,14 +33,12 @@ EFI_STATUS EFIAPI CoreAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, IN OUT EFI_PHYSICAL_ADDRESS *Memory ); - - /** Frees previous allocated pages. @@ -56,11 +53,10 @@ CoreAllocatePages ( EFI_STATUS EFIAPI CoreFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); - /** Allocate pool of a particular type. @@ -94,7 +90,7 @@ CoreAllocatePool ( EFI_STATUS EFIAPI CoreFreePool ( - IN VOID *Buffer + IN VOID *Buffer ); #endif diff --git a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLib.c b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLib.c index 3ef31562c1..0e12669eaa 100644 --- a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLib.c +++ b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLib.c @@ -6,7 +6,6 @@ **/ - #include #include @@ -38,14 +37,13 @@ EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { return CoreUpdateProfile (CallerAddress, Action, MemoryType, Size, Buffer, ActionString); } - diff --git a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLibNull.c b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLibNull.c index 42d4bd26f4..01f9210777 100644 --- a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLibNull.c +++ b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryProfileLibNull.c @@ -6,7 +6,6 @@ **/ - #include #include @@ -36,14 +35,13 @@ EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { return EFI_UNSUPPORTED; } - diff --git a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/MemoryAllocationLib.c b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/MemoryAllocationLib.c index cecf2ddbe7..e813e87f24 100644 --- a/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/MemoryAllocationLib.c +++ b/MdeModulePkg/Library/DxeCoreMemoryAllocationLib/MemoryAllocationLib.c @@ -8,10 +8,8 @@ **/ - #include - #include #include #include @@ -49,7 +47,8 @@ InternalAllocatePages ( if (EFI_ERROR (Status)) { return NULL; } - return (VOID *) (UINTN) Memory; + + return (VOID *)(UINTN)Memory; } /** @@ -76,7 +75,7 @@ AllocatePages ( Buffer = InternalAllocatePages (EfiBootServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, EfiBootServicesData, Buffer, @@ -84,6 +83,7 @@ AllocatePages ( NULL ); } + return Buffer; } @@ -111,7 +111,7 @@ AllocateRuntimePages ( Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, @@ -119,6 +119,7 @@ AllocateRuntimePages ( NULL ); } + return Buffer; } @@ -146,7 +147,7 @@ AllocateReservedPages ( Buffer = InternalAllocatePages (EfiReservedMemoryType, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_PAGES, EfiReservedMemoryType, Buffer, @@ -154,6 +155,7 @@ AllocateReservedPages ( NULL ); } + return Buffer; } @@ -184,7 +186,7 @@ FreePages ( EFI_STATUS Status; ASSERT (Pages != 0); - Status = CoreFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = CoreFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); ASSERT_EFI_ERROR (Status); } @@ -228,23 +230,25 @@ InternalAllocateAlignedPages ( if (Pages == 0) { return NULL; } + if (Alignment > EFI_PAGE_SIZE) { // // Calculate the total number of pages since alignment is larger than page size. // - AlignmentMask = Alignment - 1; - RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); + AlignmentMask = Alignment - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); // // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow. // ASSERT (RealPages > Pages); - Status = CoreAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); + Status = CoreAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; - UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); + + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). @@ -252,6 +256,7 @@ InternalAllocateAlignedPages ( Status = CoreFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } + Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -269,9 +274,11 @@ InternalAllocateAlignedPages ( if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = (UINTN) Memory; + + AlignedMemory = (UINTN)Memory; } - return (VOID *) AlignedMemory; + + return (VOID *)AlignedMemory; } /** @@ -304,7 +311,7 @@ AllocateAlignedPages ( Buffer = InternalAllocateAlignedPages (EfiBootServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, EfiBootServicesData, Buffer, @@ -312,6 +319,7 @@ AllocateAlignedPages ( NULL ); } + return Buffer; } @@ -345,7 +353,7 @@ AllocateAlignedRuntimePages ( Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, @@ -353,6 +361,7 @@ AllocateAlignedRuntimePages ( NULL ); } + return Buffer; } @@ -386,7 +395,7 @@ AllocateAlignedReservedPages ( Buffer = InternalAllocateAlignedPages (EfiReservedMemoryType, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RESERVED_PAGES, EfiReservedMemoryType, Buffer, @@ -394,6 +403,7 @@ AllocateAlignedReservedPages ( NULL ); } + return Buffer; } @@ -424,7 +434,7 @@ FreeAlignedPages ( EFI_STATUS Status; ASSERT (Pages != 0); - Status = CoreFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = CoreFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); ASSERT_EFI_ERROR (Status); } @@ -456,6 +466,7 @@ InternalAllocatePool ( if (EFI_ERROR (Status)) { Memory = NULL; } + return Memory; } @@ -482,7 +493,7 @@ AllocatePool ( Buffer = InternalAllocatePool (EfiBootServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, EfiBootServicesData, Buffer, @@ -490,6 +501,7 @@ AllocatePool ( NULL ); } + return Buffer; } @@ -516,7 +528,7 @@ AllocateRuntimePool ( Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -524,6 +536,7 @@ AllocateRuntimePool ( NULL ); } + return Buffer; } @@ -550,7 +563,7 @@ AllocateReservedPool ( Buffer = InternalAllocatePool (EfiReservedMemoryType, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_POOL, EfiReservedMemoryType, Buffer, @@ -558,6 +571,7 @@ AllocateReservedPool ( NULL ); } + return Buffer; } @@ -587,6 +601,7 @@ InternalAllocateZeroPool ( if (Memory != NULL) { Memory = ZeroMem (Memory, AllocationSize); } + return Memory; } @@ -614,7 +629,7 @@ AllocateZeroPool ( Buffer = InternalAllocateZeroPool (EfiBootServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, EfiBootServicesData, Buffer, @@ -622,6 +637,7 @@ AllocateZeroPool ( NULL ); } + return Buffer; } @@ -649,7 +665,7 @@ AllocateRuntimeZeroPool ( Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, EfiRuntimeServicesData, Buffer, @@ -657,6 +673,7 @@ AllocateRuntimeZeroPool ( NULL ); } + return Buffer; } @@ -684,7 +701,7 @@ AllocateReservedZeroPool ( Buffer = InternalAllocateZeroPool (EfiReservedMemoryType, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_ZERO_POOL, EfiReservedMemoryType, Buffer, @@ -692,6 +709,7 @@ AllocateReservedZeroPool ( NULL ); } + return Buffer; } @@ -722,12 +740,13 @@ InternalAllocateCopyPool ( VOID *Memory; ASSERT (Buffer != NULL); - ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN) Buffer + 1)); + ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN)Buffer + 1)); Memory = InternalAllocatePool (PoolType, AllocationSize); if (Memory != NULL) { - Memory = CopyMem (Memory, Buffer, AllocationSize); + Memory = CopyMem (Memory, Buffer, AllocationSize); } + return Memory; } @@ -760,7 +779,7 @@ AllocateCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiBootServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, EfiBootServicesData, NewBuffer, @@ -768,6 +787,7 @@ AllocateCopyPool ( NULL ); } + return NewBuffer; } @@ -800,7 +820,7 @@ AllocateRuntimeCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -808,6 +828,7 @@ AllocateRuntimeCopyPool ( NULL ); } + return NewBuffer; } @@ -840,7 +861,7 @@ AllocateReservedCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiReservedMemoryType, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RESERVED_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -848,6 +869,7 @@ AllocateReservedCopyPool ( NULL ); } + return NewBuffer; } @@ -884,10 +906,11 @@ InternalReallocatePool ( VOID *NewBuffer; NewBuffer = InternalAllocateZeroPool (PoolType, NewSize); - if (NewBuffer != NULL && OldBuffer != NULL) { + if ((NewBuffer != NULL) && (OldBuffer != NULL)) { CopyMem (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); FreePool (OldBuffer); } + return NewBuffer; } @@ -925,7 +948,7 @@ ReallocatePool ( Buffer = InternalReallocatePool (EfiBootServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, EfiBootServicesData, Buffer, @@ -933,6 +956,7 @@ ReallocatePool ( NULL ); } + return Buffer; } @@ -970,7 +994,7 @@ ReallocateRuntimePool ( Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -978,6 +1002,7 @@ ReallocateRuntimePool ( NULL ); } + return Buffer; } @@ -1015,7 +1040,7 @@ ReallocateReservedPool ( Buffer = InternalReallocatePool (EfiReservedMemoryType, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RESERVED_POOL, EfiReservedMemoryType, Buffer, @@ -1023,6 +1048,7 @@ ReallocateReservedPool ( NULL ); } + return Buffer; } @@ -1043,12 +1069,11 @@ ReallocateReservedPool ( VOID EFIAPI FreePool ( - IN VOID *Buffer + IN VOID *Buffer ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = CoreFreePool (Buffer); ASSERT_EFI_ERROR (Status); } - diff --git a/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.c b/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.c index eb9cea5011..ef14bc0738 100644 --- a/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.c +++ b/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.c @@ -16,19 +16,18 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "DxeCorePerformanceLibInternal.h" // // Data for FPDT performance records. // -#define SMM_BOOT_RECORD_COMM_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data) + sizeof(SMM_BOOT_RECORD_COMMUNICATE)) -#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) -#define FIRMWARE_RECORD_BUFFER 0x10000 -#define CACHE_HANDLE_GUID_COUNT 0x800 +#define SMM_BOOT_RECORD_COMM_SIZE (OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data) + sizeof(SMM_BOOT_RECORD_COMMUNICATE)) +#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) +#define FIRMWARE_RECORD_BUFFER 0x10000 +#define CACHE_HANDLE_GUID_COUNT 0x800 -BOOT_PERFORMANCE_TABLE *mAcpiBootPerformanceTable = NULL; -BOOT_PERFORMANCE_TABLE mBootPerformanceTableTemplate = { +BOOT_PERFORMANCE_TABLE *mAcpiBootPerformanceTable = NULL; +BOOT_PERFORMANCE_TABLE mBootPerformanceTableTemplate = { { EFI_ACPI_5_0_FPDT_BOOT_PERFORMANCE_TABLE_SIGNATURE, sizeof (BOOT_PERFORMANCE_TABLE) @@ -57,8 +56,8 @@ typedef struct { EFI_GUID ModuleGuid; } HANDLE_GUID_MAP; -HANDLE_GUID_MAP mCacheHandleGuidTable[CACHE_HANDLE_GUID_COUNT]; -UINTN mCachePairCount = 0; +HANDLE_GUID_MAP mCacheHandleGuidTable[CACHE_HANDLE_GUID_COUNT]; +UINTN mCachePairCount = 0; UINT32 mLoadImageCount = 0; UINT32 mPerformanceLength = 0; @@ -67,22 +66,22 @@ UINT32 mBootRecordSize = 0; UINTN mBootRecordMaxSize = 0; UINT32 mCachedLength = 0; -BOOLEAN mFpdtBufferIsReported = FALSE; -BOOLEAN mLackSpaceIsReported = FALSE; -CHAR8 *mPlatformLanguage = NULL; -UINT8 *mPerformancePointer = NULL; -UINT8 *mBootRecordBuffer = NULL; -BOOLEAN mLockInsertRecord = FALSE; -CHAR8 *mDevicePathString = NULL; +BOOLEAN mFpdtBufferIsReported = FALSE; +BOOLEAN mLackSpaceIsReported = FALSE; +CHAR8 *mPlatformLanguage = NULL; +UINT8 *mPerformancePointer = NULL; +UINT8 *mBootRecordBuffer = NULL; +BOOLEAN mLockInsertRecord = FALSE; +CHAR8 *mDevicePathString = NULL; EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *mDevicePathToText = NULL; // // Interfaces for PerformanceMeasurement Protocol. // -EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL mPerformanceMeasurementInterface = { +EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL mPerformanceMeasurementInterface = { CreatePerformanceMeasurement, - }; +}; PERFORMANCE_PROPERTY mPerformanceProperty; @@ -97,9 +96,9 @@ PERFORMANCE_PROPERTY mPerformanceProperty; **/ EFI_STATUS GetFpdtRecordPtr ( - IN UINT8 RecordSize, - IN OUT FPDT_RECORD_PTR *FpdtRecordPtr -) + IN UINT8 RecordSize, + IN OUT FPDT_RECORD_PTR *FpdtRecordPtr + ) { if (mFpdtBufferIsReported) { // @@ -110,6 +109,7 @@ GetFpdtRecordPtr ( DEBUG ((DEBUG_INFO, "DxeCorePerformanceLib: No enough space to save boot records\n")); mLackSpaceIsReported = TRUE; } + return EFI_OUT_OF_RESOURCES; } else { // @@ -128,15 +128,18 @@ GetFpdtRecordPtr ( mPerformancePointer ); if (mPerformancePointer == NULL) { - return EFI_OUT_OF_RESOURCES; - } + return EFI_OUT_OF_RESOURCES; + } + mMaxPerformanceLength = mPerformanceLength + RecordSize + FIRMWARE_RECORD_BUFFER; } + // // Covert buffer to FPDT Ptr Union type. // FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mPerformanceLength); } + return EFI_SUCCESS; } @@ -158,16 +161,17 @@ IsKnownTokens ( return FALSE; } - if (AsciiStrCmp (Token, SEC_TOK) == 0 || - AsciiStrCmp (Token, PEI_TOK) == 0 || - AsciiStrCmp (Token, DXE_TOK) == 0 || - AsciiStrCmp (Token, BDS_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0 || - AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, START_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, PEIM_TOK) == 0) { + if ((AsciiStrCmp (Token, SEC_TOK) == 0) || + (AsciiStrCmp (Token, PEI_TOK) == 0) || + (AsciiStrCmp (Token, DXE_TOK) == 0) || + (AsciiStrCmp (Token, BDS_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0) || + (AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, START_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, PEIM_TOK) == 0)) + { return TRUE; } else { return FALSE; @@ -185,19 +189,20 @@ Check whether the ID is a known one which map to the known Token. **/ BOOLEAN IsKnownID ( - IN UINT32 Identifier + IN UINT32 Identifier ) { - if (Identifier == MODULE_START_ID || - Identifier == MODULE_END_ID || - Identifier == MODULE_LOADIMAGE_START_ID || - Identifier == MODULE_LOADIMAGE_END_ID || - Identifier == MODULE_DB_START_ID || - Identifier == MODULE_DB_END_ID || - Identifier == MODULE_DB_SUPPORT_START_ID || - Identifier == MODULE_DB_SUPPORT_END_ID || - Identifier == MODULE_DB_STOP_START_ID || - Identifier == MODULE_DB_STOP_END_ID) { + if ((Identifier == MODULE_START_ID) || + (Identifier == MODULE_END_ID) || + (Identifier == MODULE_LOADIMAGE_START_ID) || + (Identifier == MODULE_LOADIMAGE_END_ID) || + (Identifier == MODULE_DB_START_ID) || + (Identifier == MODULE_DB_END_ID) || + (Identifier == MODULE_DB_SUPPORT_START_ID) || + (Identifier == MODULE_DB_SUPPORT_END_ID) || + (Identifier == MODULE_DB_STOP_START_ID) || + (Identifier == MODULE_DB_STOP_END_ID)) + { return TRUE; } else { return FALSE; @@ -214,23 +219,23 @@ IsKnownID ( **/ VOID InternalGetSmmPerfData ( - OUT VOID **SmmPerfData, - OUT UINTN *SmmPerfDataSize, - IN BOOLEAN SkipGetPerfData + OUT VOID **SmmPerfData, + OUT UINTN *SmmPerfDataSize, + IN BOOLEAN SkipGetPerfData ) { - EFI_STATUS Status; - UINT8 *SmmBootRecordCommBuffer; - EFI_SMM_COMMUNICATE_HEADER *SmmCommBufferHeader; - SMM_BOOT_RECORD_COMMUNICATE *SmmCommData; - UINTN CommSize; - EFI_SMM_COMMUNICATION_PROTOCOL *Communication; - EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *SmmCommRegionTable; - EFI_MEMORY_DESCRIPTOR *SmmCommMemRegion; - UINTN Index; - VOID *SmmBootRecordData; - UINTN SmmBootRecordDataSize; - UINTN ReservedMemSize; + EFI_STATUS Status; + UINT8 *SmmBootRecordCommBuffer; + EFI_SMM_COMMUNICATE_HEADER *SmmCommBufferHeader; + SMM_BOOT_RECORD_COMMUNICATE *SmmCommData; + UINTN CommSize; + EFI_SMM_COMMUNICATION_PROTOCOL *Communication; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *SmmCommRegionTable; + EFI_MEMORY_DESCRIPTOR *SmmCommMemRegion; + UINTN Index; + VOID *SmmBootRecordData; + UINTN SmmBootRecordDataSize; + UINTN ReservedMemSize; // // Collect boot records from SMM drivers. @@ -239,76 +244,81 @@ InternalGetSmmPerfData ( SmmCommData = NULL; SmmBootRecordData = NULL; ReservedMemSize = 0; - Status = gBS->LocateProtocol (&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **) &Communication); + Status = gBS->LocateProtocol (&gEfiSmmCommunicationProtocolGuid, NULL, (VOID **)&Communication); if (!EFI_ERROR (Status)) { // // Initialize communicate buffer // Get the prepared Reserved Memory Range // Status = EfiGetSystemConfigurationTable ( - &gEdkiiPiSmmCommunicationRegionTableGuid, - (VOID **) &SmmCommRegionTable - ); + &gEdkiiPiSmmCommunicationRegionTableGuid, + (VOID **)&SmmCommRegionTable + ); if (!EFI_ERROR (Status)) { ASSERT (SmmCommRegionTable != NULL); - SmmCommMemRegion = (EFI_MEMORY_DESCRIPTOR *) (SmmCommRegionTable + 1); - for (Index = 0; Index < SmmCommRegionTable->NumberOfEntries; Index ++) { + SmmCommMemRegion = (EFI_MEMORY_DESCRIPTOR *)(SmmCommRegionTable + 1); + for (Index = 0; Index < SmmCommRegionTable->NumberOfEntries; Index++) { if (SmmCommMemRegion->Type == EfiConventionalMemory) { break; } - SmmCommMemRegion = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) SmmCommMemRegion + SmmCommRegionTable->DescriptorSize); + + SmmCommMemRegion = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)SmmCommMemRegion + SmmCommRegionTable->DescriptorSize); } + ASSERT (Index < SmmCommRegionTable->NumberOfEntries); ASSERT (SmmCommMemRegion->PhysicalStart > 0); ASSERT (SmmCommMemRegion->NumberOfPages > 0); - ReservedMemSize = (UINTN) SmmCommMemRegion->NumberOfPages * EFI_PAGE_SIZE; + ReservedMemSize = (UINTN)SmmCommMemRegion->NumberOfPages * EFI_PAGE_SIZE; // // Check enough reserved memory space // if (ReservedMemSize > SMM_BOOT_RECORD_COMM_SIZE) { - SmmBootRecordCommBuffer = (VOID *) (UINTN) SmmCommMemRegion->PhysicalStart; - SmmCommBufferHeader = (EFI_SMM_COMMUNICATE_HEADER*)SmmBootRecordCommBuffer; - SmmCommData = (SMM_BOOT_RECORD_COMMUNICATE*)SmmCommBufferHeader->Data; - ZeroMem((UINT8*)SmmCommData, sizeof(SMM_BOOT_RECORD_COMMUNICATE)); + SmmBootRecordCommBuffer = (VOID *)(UINTN)SmmCommMemRegion->PhysicalStart; + SmmCommBufferHeader = (EFI_SMM_COMMUNICATE_HEADER *)SmmBootRecordCommBuffer; + SmmCommData = (SMM_BOOT_RECORD_COMMUNICATE *)SmmCommBufferHeader->Data; + ZeroMem ((UINT8 *)SmmCommData, sizeof (SMM_BOOT_RECORD_COMMUNICATE)); CopyGuid (&SmmCommBufferHeader->HeaderGuid, &gEfiFirmwarePerformanceGuid); - SmmCommBufferHeader->MessageLength = sizeof(SMM_BOOT_RECORD_COMMUNICATE); - CommSize = SMM_BOOT_RECORD_COMM_SIZE; + SmmCommBufferHeader->MessageLength = sizeof (SMM_BOOT_RECORD_COMMUNICATE); + CommSize = SMM_BOOT_RECORD_COMM_SIZE; // // Get the size of boot records. // SmmCommData->Function = SMM_FPDT_FUNCTION_GET_BOOT_RECORD_SIZE; SmmCommData->BootRecordData = NULL; - Status = Communication->Communicate (Communication, SmmBootRecordCommBuffer, &CommSize); + Status = Communication->Communicate (Communication, SmmBootRecordCommBuffer, &CommSize); - if (!EFI_ERROR (Status) && !EFI_ERROR (SmmCommData->ReturnStatus) && SmmCommData->BootRecordSize != 0) { + if (!EFI_ERROR (Status) && !EFI_ERROR (SmmCommData->ReturnStatus) && (SmmCommData->BootRecordSize != 0)) { if (SkipGetPerfData) { *SmmPerfDataSize = SmmCommData->BootRecordSize; return; } + // // Get all boot records // - SmmCommData->Function = SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET; - SmmBootRecordDataSize = SmmCommData->BootRecordSize; - SmmBootRecordData = AllocateZeroPool(SmmBootRecordDataSize); + SmmCommData->Function = SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET; + SmmBootRecordDataSize = SmmCommData->BootRecordSize; + SmmBootRecordData = AllocateZeroPool (SmmBootRecordDataSize); ASSERT (SmmBootRecordData != NULL); SmmCommData->BootRecordOffset = 0; - SmmCommData->BootRecordData = (VOID *) ((UINTN) SmmCommMemRegion->PhysicalStart + SMM_BOOT_RECORD_COMM_SIZE); + SmmCommData->BootRecordData = (VOID *)((UINTN)SmmCommMemRegion->PhysicalStart + SMM_BOOT_RECORD_COMM_SIZE); SmmCommData->BootRecordSize = ReservedMemSize - SMM_BOOT_RECORD_COMM_SIZE; while (SmmCommData->BootRecordOffset < SmmBootRecordDataSize) { Status = Communication->Communicate (Communication, SmmBootRecordCommBuffer, &CommSize); ASSERT_EFI_ERROR (Status); - ASSERT_EFI_ERROR(SmmCommData->ReturnStatus); + ASSERT_EFI_ERROR (SmmCommData->ReturnStatus); if (SmmCommData->BootRecordOffset + SmmCommData->BootRecordSize > SmmBootRecordDataSize) { - CopyMem ((UINT8 *) SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmBootRecordDataSize - SmmCommData->BootRecordOffset); + CopyMem ((UINT8 *)SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmBootRecordDataSize - SmmCommData->BootRecordOffset); } else { - CopyMem ((UINT8 *) SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmCommData->BootRecordSize); + CopyMem ((UINT8 *)SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmCommData->BootRecordSize); } + SmmCommData->BootRecordOffset = SmmCommData->BootRecordOffset + SmmCommData->BootRecordSize; } + *SmmPerfData = SmmBootRecordData; *SmmPerfDataSize = SmmBootRecordDataSize; } @@ -328,12 +338,12 @@ AllocateBootPerformanceTable ( VOID ) { - EFI_STATUS Status; - UINTN Size; - UINTN BootPerformanceDataSize; - UINT8 *BootPerformanceData; - FIRMWARE_PERFORMANCE_VARIABLE PerformanceVariable; - UINTN SmmBootRecordDataSize; + EFI_STATUS Status; + UINTN Size; + UINTN BootPerformanceDataSize; + UINT8 *BootPerformanceData; + FIRMWARE_PERFORMANCE_VARIABLE PerformanceVariable; + UINTN SmmBootRecordDataSize; SmmBootRecordDataSize = 0; @@ -353,7 +363,7 @@ AllocateBootPerformanceTable ( // Try to allocate the same runtime buffer as last time boot. // ZeroMem (&PerformanceVariable, sizeof (PerformanceVariable)); - Size = sizeof (PerformanceVariable); + Size = sizeof (PerformanceVariable); Status = gRT->GetVariable ( EFI_FIRMWARE_PERFORMANCE_VARIABLE_NAME, &gEfiFirmwarePerformanceGuid, @@ -369,7 +379,7 @@ AllocateBootPerformanceTable ( &PerformanceVariable.BootPerformanceTablePointer ); if (!EFI_ERROR (Status)) { - mAcpiBootPerformanceTable = (BOOT_PERFORMANCE_TABLE *) (UINTN) PerformanceVariable.BootPerformanceTablePointer; + mAcpiBootPerformanceTable = (BOOT_PERFORMANCE_TABLE *)(UINTN)PerformanceVariable.BootPerformanceTablePointer; } } @@ -377,14 +387,15 @@ AllocateBootPerformanceTable ( // // Fail to allocate at specified address, continue to allocate at any address. // - mAcpiBootPerformanceTable = (BOOT_PERFORMANCE_TABLE *) AllocatePeiAccessiblePages ( - EfiReservedMemoryType, - EFI_SIZE_TO_PAGES (BootPerformanceDataSize) - ); + mAcpiBootPerformanceTable = (BOOT_PERFORMANCE_TABLE *)AllocatePeiAccessiblePages ( + EfiReservedMemoryType, + EFI_SIZE_TO_PAGES (BootPerformanceDataSize) + ); if (mAcpiBootPerformanceTable != NULL) { ZeroMem (mAcpiBootPerformanceTable, BootPerformanceDataSize); } } + DEBUG ((DEBUG_INFO, "DxeCorePerformanceLib: ACPI Boot Performance Table address = 0x%x\n", mAcpiBootPerformanceTable)); if (mAcpiBootPerformanceTable == NULL) { @@ -394,7 +405,7 @@ AllocateBootPerformanceTable ( // // Prepare Boot Performance Table. // - BootPerformanceData = (UINT8 *) mAcpiBootPerformanceTable; + BootPerformanceData = (UINT8 *)mAcpiBootPerformanceTable; // // Fill Basic Boot record to Boot Performance Table. // @@ -406,14 +417,14 @@ AllocateBootPerformanceTable ( if (mPerformancePointer != NULL) { CopyMem (BootPerformanceData, mPerformancePointer, mPerformanceLength); mAcpiBootPerformanceTable->Header.Length += mPerformanceLength; - BootPerformanceData = BootPerformanceData + mPerformanceLength; + BootPerformanceData = BootPerformanceData + mPerformanceLength; FreePool (mPerformancePointer); mPerformancePointer = NULL; mPerformanceLength = 0; mMaxPerformanceLength = 0; } - mBootRecordBuffer = (UINT8 *) mAcpiBootPerformanceTable; + mBootRecordBuffer = (UINT8 *)mAcpiBootPerformanceTable; mBootRecordSize = mAcpiBootPerformanceTable->Header.Length; mBootRecordMaxSize = BootPerformanceDataSize; @@ -437,28 +448,29 @@ AllocateBootPerformanceTable ( EFI_STATUS GetModuleInfoFromHandle ( IN EFI_HANDLE Handle, - OUT CHAR8 *NameString, - IN UINTN BufferSize, - OUT EFI_GUID *ModuleGuid OPTIONAL + OUT CHAR8 *NameString, + IN UINTN BufferSize, + OUT EFI_GUID *ModuleGuid OPTIONAL ) { - EFI_STATUS Status; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; - CHAR8 *PdbFileName; - EFI_GUID *TempGuid; - UINTN StartIndex; - UINTN Index; - INTN Count; - BOOLEAN ModuleGuidIsGet; - UINTN StringSize; - CHAR16 *StringPtr; - EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvFilePath; - - if (NameString == NULL || BufferSize == 0) { + EFI_STATUS Status; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; + CHAR8 *PdbFileName; + EFI_GUID *TempGuid; + UINTN StartIndex; + UINTN Index; + INTN Count; + BOOLEAN ModuleGuidIsGet; + UINTN StringSize; + CHAR16 *StringPtr; + EFI_COMPONENT_NAME2_PROTOCOL *ComponentName2; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvFilePath; + + if ((NameString == NULL) || (BufferSize == 0)) { return EFI_INVALID_PARAMETER; } + // // Try to get the ModuleGuid and name string form the caached array. // @@ -472,14 +484,14 @@ GetModuleInfoFromHandle ( } } - Status = EFI_INVALID_PARAMETER; + Status = EFI_INVALID_PARAMETER; LoadedImage = NULL; ModuleGuidIsGet = FALSE; // // Initialize GUID as zero value. // - TempGuid = &gZeroGuid; + TempGuid = &gZeroGuid; // // Initialize it as "" string. // @@ -490,49 +502,50 @@ GetModuleInfoFromHandle ( // Try Handle as ImageHandle. // Status = gBS->HandleProtocol ( - Handle, - &gEfiLoadedImageProtocolGuid, - (VOID**) &LoadedImage - ); + Handle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&LoadedImage + ); if (EFI_ERROR (Status)) { // // Try Handle as Controller Handle // Status = gBS->OpenProtocol ( - Handle, - &gEfiDriverBindingProtocolGuid, - (VOID **) &DriverBinding, - NULL, - NULL, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Handle, + &gEfiDriverBindingProtocolGuid, + (VOID **)&DriverBinding, + NULL, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); if (!EFI_ERROR (Status)) { // // Get Image protocol from ImageHandle // Status = gBS->HandleProtocol ( - DriverBinding->ImageHandle, - &gEfiLoadedImageProtocolGuid, - (VOID**) &LoadedImage - ); + DriverBinding->ImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&LoadedImage + ); } } } - if (!EFI_ERROR (Status) && LoadedImage != NULL) { + if (!EFI_ERROR (Status) && (LoadedImage != NULL)) { // // Get Module Guid from DevicePath. // - if (LoadedImage->FilePath != NULL && - LoadedImage->FilePath->Type == MEDIA_DEVICE_PATH && - LoadedImage->FilePath->SubType == MEDIA_PIWG_FW_FILE_DP - ) { + if ((LoadedImage->FilePath != NULL) && + (LoadedImage->FilePath->Type == MEDIA_DEVICE_PATH) && + (LoadedImage->FilePath->SubType == MEDIA_PIWG_FW_FILE_DP) + ) + { // // Determine GUID associated with module logging performance // ModuleGuidIsGet = TRUE; - FvFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LoadedImage->FilePath; + FvFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)LoadedImage->FilePath; TempGuid = &FvFilePath->FvFileName; } @@ -540,20 +553,21 @@ GetModuleInfoFromHandle ( // Method 1 Get Module Name from PDB string. // PdbFileName = PeCoffLoaderGetPdbPointer (LoadedImage->ImageBase); - if (PdbFileName != NULL && BufferSize > 0) { + if ((PdbFileName != NULL) && (BufferSize > 0)) { StartIndex = 0; for (Index = 0; PdbFileName[Index] != 0; Index++) { if ((PdbFileName[Index] == '\\') || (PdbFileName[Index] == '/')) { StartIndex = Index + 1; } } + // // Copy the PDB file name to our temporary string. // If the length is bigger than BufferSize, trim the redudant characters to avoid overflow in array boundary. // for (Index = 0; Index < BufferSize - 1; Index++) { NameString[Index] = PdbFileName[Index + StartIndex]; - if (NameString[Index] == 0 || NameString[Index] == '.') { + if ((NameString[Index] == 0) || (NameString[Index] == '.')) { NameString[Index] = 0; break; } @@ -562,6 +576,7 @@ GetModuleInfoFromHandle ( if (Index == BufferSize - 1) { NameString[Index] = 0; } + // // Module Name is got. // @@ -575,15 +590,16 @@ GetModuleInfoFromHandle ( Status = gBS->HandleProtocol ( Handle, &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName2 + (VOID **)&ComponentName2 ); if (!EFI_ERROR (Status)) { // // Get the current platform language setting // if (mPlatformLanguage == NULL) { - GetEfiGlobalVariable2 (L"PlatformLang", (VOID **) &mPlatformLanguage, NULL); + GetEfiGlobalVariable2 (L"PlatformLang", (VOID **)&mPlatformLanguage, NULL); } + if (mPlatformLanguage != NULL) { Status = ComponentName2->GetDriverName ( ComponentName2, @@ -592,8 +608,9 @@ GetModuleInfoFromHandle ( ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < BufferSize - 1 && StringPtr[Index] != 0; Index++) { - NameString[Index] = (CHAR8) StringPtr[Index]; + NameString[Index] = (CHAR8)StringPtr[Index]; } + NameString[Index] = 0; // // Module Name is got. @@ -609,21 +626,22 @@ GetModuleInfoFromHandle ( // StringPtr = NULL; StringSize = 0; - Status = GetSectionFromAnyFv ( - TempGuid, - EFI_SECTION_USER_INTERFACE, - 0, - (VOID **) &StringPtr, - &StringSize - ); + Status = GetSectionFromAnyFv ( + TempGuid, + EFI_SECTION_USER_INTERFACE, + 0, + (VOID **)&StringPtr, + &StringSize + ); if (!EFI_ERROR (Status)) { // // Method 3. Get the name string from FFS UI section // for (Index = 0; Index < BufferSize - 1 && StringPtr[Index] != 0; Index++) { - NameString[Index] = (CHAR8) StringPtr[Index]; + NameString[Index] = (CHAR8)StringPtr[Index]; } + NameString[Index] = 0; FreePool (StringPtr); } @@ -635,9 +653,9 @@ Done: // if (ModuleGuid != NULL) { CopyGuid (ModuleGuid, TempGuid); - if (IsZeroGuid(TempGuid) && (Handle != NULL) && !ModuleGuidIsGet) { - // Handle is GUID - CopyGuid (ModuleGuid, (EFI_GUID *) Handle); + if (IsZeroGuid (TempGuid) && (Handle != NULL) && !ModuleGuidIsGet) { + // Handle is GUID + CopyGuid (ModuleGuid, (EFI_GUID *)Handle); } } @@ -648,7 +666,7 @@ Done: mCacheHandleGuidTable[mCachePairCount].Handle = Handle; CopyGuid (&mCacheHandleGuidTable[mCachePairCount].ModuleGuid, ModuleGuid); AsciiStrCpyS (mCacheHandleGuidTable[mCachePairCount].NameString, FPDT_STRING_EVENT_RECORD_NAME_LENGTH, NameString); - mCachePairCount ++; + mCachePairCount++; } return Status; @@ -671,75 +689,86 @@ Done: EFI_STATUS GetFpdtRecordId ( IN PERF_MEASUREMENT_ATTRIBUTE Attribute, - IN CONST VOID *Handle, - IN CONST CHAR8 *String, - OUT UINT16 *ProgressID + IN CONST VOID *Handle, + IN CONST CHAR8 *String, + OUT UINT16 *ProgressID ) { // // Token to PerfId. // if (String != NULL) { - if (AsciiStrCmp (String, START_IMAGE_TOK) == 0) { // "StartImage:" + if (AsciiStrCmp (String, START_IMAGE_TOK) == 0) { + // "StartImage:" if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_START_ID; + *ProgressID = MODULE_START_ID; } else { - *ProgressID = MODULE_END_ID; + *ProgressID = MODULE_END_ID; } - } else if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { // "LoadImage:" + } else if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { + // "LoadImage:" if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_LOADIMAGE_START_ID; + *ProgressID = MODULE_LOADIMAGE_START_ID; } else { - *ProgressID = MODULE_LOADIMAGE_END_ID; + *ProgressID = MODULE_LOADIMAGE_END_ID; } - } else if (AsciiStrCmp (String, DRIVERBINDING_START_TOK) == 0) { // "DB:Start:" + } else if (AsciiStrCmp (String, DRIVERBINDING_START_TOK) == 0) { + // "DB:Start:" if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_DB_START_ID; + *ProgressID = MODULE_DB_START_ID; } else { - *ProgressID = MODULE_DB_END_ID; + *ProgressID = MODULE_DB_END_ID; } - } else if (AsciiStrCmp (String, DRIVERBINDING_SUPPORT_TOK) == 0) { // "DB:Support:" + } else if (AsciiStrCmp (String, DRIVERBINDING_SUPPORT_TOK) == 0) { + // "DB:Support:" if (PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { return RETURN_UNSUPPORTED; } + if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_DB_SUPPORT_START_ID; + *ProgressID = MODULE_DB_SUPPORT_START_ID; } else { - *ProgressID = MODULE_DB_SUPPORT_END_ID; + *ProgressID = MODULE_DB_SUPPORT_END_ID; } - } else if (AsciiStrCmp (String, DRIVERBINDING_STOP_TOK) == 0) { // "DB:Stop:" + } else if (AsciiStrCmp (String, DRIVERBINDING_STOP_TOK) == 0) { + // "DB:Stop:" if (PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - return RETURN_UNSUPPORTED; + return RETURN_UNSUPPORTED; } + if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_DB_STOP_START_ID; + *ProgressID = MODULE_DB_STOP_START_ID; } else { - *ProgressID = MODULE_DB_STOP_END_ID; + *ProgressID = MODULE_DB_STOP_END_ID; } - } else if (AsciiStrCmp (String, PEI_TOK) == 0 || // "PEI" - AsciiStrCmp (String, DXE_TOK) == 0 || // "DXE" - AsciiStrCmp (String, BDS_TOK) == 0) { // "BDS" + } else if ((AsciiStrCmp (String, PEI_TOK) == 0) || // "PEI" + (AsciiStrCmp (String, DXE_TOK) == 0) || // "DXE" + (AsciiStrCmp (String, BDS_TOK) == 0)) // "BDS" + { if (Attribute == PerfStartEntry) { - *ProgressID = PERF_CROSSMODULE_START_ID; + *ProgressID = PERF_CROSSMODULE_START_ID; } else { - *ProgressID = PERF_CROSSMODULE_END_ID; + *ProgressID = PERF_CROSSMODULE_END_ID; } - } else { // Pref used in Modules. + } else { + // Pref used in Modules. if (Attribute == PerfStartEntry) { - *ProgressID = PERF_INMODULE_START_ID; + *ProgressID = PERF_INMODULE_START_ID; } else { - *ProgressID = PERF_INMODULE_END_ID; + *ProgressID = PERF_INMODULE_END_ID; } } - } else if (Handle!= NULL) { // Pref used in Modules. + } else if (Handle != NULL) { + // Pref used in Modules. if (Attribute == PerfStartEntry) { - *ProgressID = PERF_INMODULE_START_ID; + *ProgressID = PERF_INMODULE_START_ID; } else { - *ProgressID = PERF_INMODULE_END_ID; + *ProgressID = PERF_INMODULE_END_ID; } } else { return EFI_INVALID_PARAMETER; } + return EFI_SUCCESS; } @@ -754,9 +783,9 @@ GetFpdtRecordId ( **/ VOID CopyStringIntoPerfRecordAndUpdateLength ( - IN OUT CHAR8 *Destination, + IN OUT CHAR8 *Destination, IN CONST CHAR8 *Source, - IN OUT UINT8 *Length + IN OUT UINT8 *Length ) { UINTN StringLen; @@ -772,12 +801,13 @@ CopyStringIntoPerfRecordAndUpdateLength ( DestMax = STRING_SIZE; } } + StringLen = AsciiStrLen (Source); if (StringLen >= DestMax) { StringLen = DestMax -1; } - AsciiStrnCpyS(Destination, DestMax, Source, StringLen); + AsciiStrnCpyS (Destination, DestMax, Source, StringLen); *Length += (UINT8)DestMax; return; @@ -799,10 +829,10 @@ CopyStringIntoPerfRecordAndUpdateLength ( **/ EFI_STATUS GetDeviceInfoFromHandleAndUpdateLength ( - IN CONST VOID *Handle, - IN EFI_HANDLE ControllerHandle, - OUT CHAR8 *ComponentNameString, - IN OUT UINT8 *Length + IN CONST VOID *Handle, + IN EFI_HANDLE ControllerHandle, + OUT CHAR8 *ComponentNameString, + IN OUT UINT8 *Length ) { EFI_DEVICE_PATH_PROTOCOL *DevicePathProtocol; @@ -816,12 +846,12 @@ GetDeviceInfoFromHandleAndUpdateLength ( ControllerNameStringSize = 0; Status = gBS->HandleProtocol ( - (EFI_HANDLE) Handle, + (EFI_HANDLE)Handle, &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName2 + (VOID **)&ComponentName2 ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { // // Get the current platform language setting // @@ -843,7 +873,7 @@ GetDeviceInfoFromHandleAndUpdateLength ( // This will produce the size of the unicode string, which is twice as large as the ASCII one // This must be an even number, so ok to divide by 2 // - ControllerNameStringSize = StrSize(StringPtr) / 2; + ControllerNameStringSize = StrSize (StringPtr) / 2; // // The + 1 is because we want to add a space between the ControllerName and the device path @@ -855,12 +885,12 @@ GetDeviceInfoFromHandleAndUpdateLength ( ControllerNameStringSize = FPDT_MAX_PERF_RECORD_SIZE - (*Length) - 1; } - UnicodeStrnToAsciiStrS(StringPtr, ControllerNameStringSize - 1, ComponentNameString, ControllerNameStringSize, &ControllerNameStringSize); + UnicodeStrnToAsciiStrS (StringPtr, ControllerNameStringSize - 1, ComponentNameString, ControllerNameStringSize, &ControllerNameStringSize); // // Add a space in the end of the ControllerName // - AsciiStringPtr = ComponentNameString + ControllerNameStringSize - 1; + AsciiStringPtr = ComponentNameString + ControllerNameStringSize - 1; *AsciiStringPtr = 0x20; AsciiStringPtr++; *AsciiStringPtr = 0; @@ -873,7 +903,7 @@ GetDeviceInfoFromHandleAndUpdateLength ( // This function returns the device path protocol from the handle specified by Handle. If Handle is // NULL or Handle does not contain a device path protocol, then NULL is returned. // - DevicePathProtocol = DevicePathFromHandle(ControllerHandle); + DevicePathProtocol = DevicePathFromHandle (ControllerHandle); if (DevicePathProtocol != NULL) { StringPtr = ConvertDevicePathToText (DevicePathProtocol, TRUE, FALSE); @@ -882,7 +912,7 @@ GetDeviceInfoFromHandleAndUpdateLength ( // This will produce the size of the unicode string, which is twice as large as the ASCII one // This must be an even number, so ok to divide by 2 // - DevicePathStringSize = StrSize(StringPtr) / 2; + DevicePathStringSize = StrSize (StringPtr) / 2; if ((DevicePathStringSize + (*Length)) > FPDT_MAX_PERF_RECORD_SIZE) { // @@ -897,7 +927,7 @@ GetDeviceInfoFromHandleAndUpdateLength ( AsciiStringPtr = ComponentNameString; } - UnicodeStrnToAsciiStrS(StringPtr, DevicePathStringSize - 1, AsciiStringPtr, DevicePathStringSize, &DevicePathStringSize); + UnicodeStrnToAsciiStrS (StringPtr, DevicePathStringSize - 1, AsciiStringPtr, DevicePathStringSize, &DevicePathStringSize); *Length += (UINT8)DevicePathStringSize; return EFI_SUCCESS; } @@ -941,19 +971,19 @@ InsertFpdtRecord ( IN PERF_MEASUREMENT_ATTRIBUTE Attribute ) { - EFI_GUID ModuleGuid; - CHAR8 ModuleName[FPDT_STRING_EVENT_RECORD_NAME_LENGTH]; - FPDT_RECORD_PTR FpdtRecordPtr; - FPDT_RECORD_PTR CachedFpdtRecordPtr; - UINT64 TimeStamp; - CONST CHAR8 *StringPtr; - UINTN DestMax; - UINTN StringLen; - EFI_STATUS Status; - UINT16 ProgressId; - - StringPtr = NULL; - ProgressId = 0; + EFI_GUID ModuleGuid; + CHAR8 ModuleName[FPDT_STRING_EVENT_RECORD_NAME_LENGTH]; + FPDT_RECORD_PTR FpdtRecordPtr; + FPDT_RECORD_PTR CachedFpdtRecordPtr; + UINT64 TimeStamp; + CONST CHAR8 *StringPtr; + UINTN DestMax; + UINTN StringLen; + EFI_STATUS Status; + UINT16 ProgressId; + + StringPtr = NULL; + ProgressId = 0; ZeroMem (ModuleName, sizeof (ModuleName)); // @@ -986,6 +1016,7 @@ InsertFpdtRecord ( if (EFI_ERROR (Status)) { return Status; } + PerfId = ProgressId; } } @@ -999,7 +1030,7 @@ InsertFpdtRecord ( } // - //3. Get the TimeStamp. + // 3. Get the TimeStamp. // if (Ticker == 0) { Ticker = GetPerformanceCounter (); @@ -1014,199 +1045,217 @@ InsertFpdtRecord ( // 4. Fill in the FPDT record according to different Performance Identifier. // switch (PerfId) { - case MODULE_START_ID: - case MODULE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - // - // Cache the offset of start image start record and use to update the start image end record if needed. - // - if (Attribute == PerfEntry && PerfId == MODULE_START_ID) { - if (mFpdtBufferIsReported) { - mCachedLength = mBootRecordSize; - } else { - mCachedLength = mPerformanceLength; - } - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; - FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); - FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); - if (CallerIdentifier == NULL && PerfId == MODULE_END_ID && mCachedLength != 0) { - if (mFpdtBufferIsReported) { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mBootRecordBuffer + mCachedLength); - } else { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mCachedLength); - } - CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &CachedFpdtRecordPtr.GuidEvent->Guid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); - mCachedLength = 0; - } - } - break; - - case MODULE_LOADIMAGE_START_ID: - case MODULE_LOADIMAGE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - if (PerfId == MODULE_LOADIMAGE_START_ID) { - mLoadImageCount ++; + case MODULE_START_ID: + case MODULE_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + StringPtr = ModuleName; // - // Cache the offset of load image start record and use to be updated by the load image end record if needed. + // Cache the offset of start image start record and use to update the start image end record if needed. // - if (CallerIdentifier == NULL && Attribute == PerfEntry) { + if ((Attribute == PerfEntry) && (PerfId == MODULE_START_ID)) { if (mFpdtBufferIsReported) { mCachedLength = mBootRecordSize; } else { mCachedLength = mPerformanceLength; } } - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; - FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); - FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; - FpdtRecordPtr.GuidQwordEvent->Qword = mLoadImageCount; - CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); - if (PerfId == MODULE_LOADIMAGE_END_ID && mCachedLength != 0) { - if (mFpdtBufferIsReported) { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mBootRecordBuffer + mCachedLength); - } else { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mCachedLength); + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; + FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); + FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); + if ((CallerIdentifier == NULL) && (PerfId == MODULE_END_ID) && (mCachedLength != 0)) { + if (mFpdtBufferIsReported) { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mBootRecordBuffer + mCachedLength); + } else { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mCachedLength); + } + + CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &CachedFpdtRecordPtr.GuidEvent->Guid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); + mCachedLength = 0; } - CopyMem (&CachedFpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.GuidQwordEvent->Guid)); - mCachedLength = 0; } - } - break; - - case MODULE_DB_START_ID: - case MODULE_DB_SUPPORT_START_ID: - case MODULE_DB_SUPPORT_END_ID: - case MODULE_DB_STOP_START_ID: - case MODULE_DB_STOP_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; - FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); - FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; - FpdtRecordPtr.GuidQwordEvent->Qword = Address; - CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); - } - break; - - case MODULE_DB_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidQwordStringEvent->Header.Type = FPDT_GUID_QWORD_STRING_EVENT_TYPE; - FpdtRecordPtr.GuidQwordStringEvent->Header.Length = sizeof (FPDT_GUID_QWORD_STRING_EVENT_RECORD);; - FpdtRecordPtr.GuidQwordStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidQwordStringEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidQwordStringEvent->Timestamp = TimeStamp; - FpdtRecordPtr.GuidQwordStringEvent->Qword = Address; - CopyMem (&FpdtRecordPtr.GuidQwordStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordStringEvent->Guid)); - if (Address != 0) { - GetDeviceInfoFromHandleAndUpdateLength(CallerIdentifier, (EFI_HANDLE)(UINTN)Address, FpdtRecordPtr.GuidQwordStringEvent->String, &FpdtRecordPtr.GuidQwordStringEvent->Header.Length); + + break; + + case MODULE_LOADIMAGE_START_ID: + case MODULE_LOADIMAGE_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + StringPtr = ModuleName; + if (PerfId == MODULE_LOADIMAGE_START_ID) { + mLoadImageCount++; + // + // Cache the offset of load image start record and use to be updated by the load image end record if needed. + // + if ((CallerIdentifier == NULL) && (Attribute == PerfEntry)) { + if (mFpdtBufferIsReported) { + mCachedLength = mBootRecordSize; + } else { + mCachedLength = mPerformanceLength; + } + } } - } - break; - case PERF_EVENTSIGNAL_START_ID: - case PERF_EVENTSIGNAL_END_ID: - case PERF_CALLBACK_START_ID: - case PERF_CALLBACK_END_ID: - if (String == NULL || Guid == NULL) { - return EFI_INVALID_PARAMETER; - } - StringPtr = String; - if (AsciiStrLen (String) == 0) { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; - FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); - FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, CallerIdentifier, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); - } - break; - - case PERF_EVENT_ID: - case PERF_FUNCTION_START_ID: - case PERF_FUNCTION_END_ID: - case PERF_INMODULE_START_ID: - case PERF_INMODULE_END_ID: - case PERF_CROSSMODULE_START_ID: - case PERF_CROSSMODULE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - if (String != NULL) { - StringPtr = String; - } else { + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; + FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); + FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; + FpdtRecordPtr.GuidQwordEvent->Qword = mLoadImageCount; + CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); + if ((PerfId == MODULE_LOADIMAGE_END_ID) && (mCachedLength != 0)) { + if (mFpdtBufferIsReported) { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mBootRecordBuffer + mCachedLength); + } else { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mCachedLength); + } + + CopyMem (&CachedFpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.GuidQwordEvent->Guid)); + mCachedLength = 0; + } + } + + break; + + case MODULE_DB_START_ID: + case MODULE_DB_SUPPORT_START_ID: + case MODULE_DB_SUPPORT_END_ID: + case MODULE_DB_STOP_START_ID: + case MODULE_DB_STOP_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); StringPtr = ModuleName; - } - if (AsciiStrLen (StringPtr) == 0) { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); - } - break; + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; + FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); + FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; + FpdtRecordPtr.GuidQwordEvent->Qword = Address; + CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); + } + + break; + + case MODULE_DB_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + StringPtr = ModuleName; + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidQwordStringEvent->Header.Type = FPDT_GUID_QWORD_STRING_EVENT_TYPE; + FpdtRecordPtr.GuidQwordStringEvent->Header.Length = sizeof (FPDT_GUID_QWORD_STRING_EVENT_RECORD); + FpdtRecordPtr.GuidQwordStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidQwordStringEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidQwordStringEvent->Timestamp = TimeStamp; + FpdtRecordPtr.GuidQwordStringEvent->Qword = Address; + CopyMem (&FpdtRecordPtr.GuidQwordStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordStringEvent->Guid)); + if (Address != 0) { + GetDeviceInfoFromHandleAndUpdateLength (CallerIdentifier, (EFI_HANDLE)(UINTN)Address, FpdtRecordPtr.GuidQwordStringEvent->String, &FpdtRecordPtr.GuidQwordStringEvent->Header.Length); + } + } + + break; + + case PERF_EVENTSIGNAL_START_ID: + case PERF_EVENTSIGNAL_END_ID: + case PERF_CALLBACK_START_ID: + case PERF_CALLBACK_END_ID: + if ((String == NULL) || (Guid == NULL)) { + return EFI_INVALID_PARAMETER; + } + + StringPtr = String; + if (AsciiStrLen (String) == 0) { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; + FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); + FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, CallerIdentifier, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); + } - default: - if (Attribute != PerfEntry) { + break; + + case PERF_EVENT_ID: + case PERF_FUNCTION_START_ID: + case PERF_FUNCTION_END_ID: + case PERF_INMODULE_START_ID: + case PERF_INMODULE_END_ID: + case PERF_CROSSMODULE_START_ID: + case PERF_CROSSMODULE_END_ID: GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); if (String != NULL) { StringPtr = String; } else { StringPtr = ModuleName; } + if (AsciiStrLen (StringPtr) == 0) { StringPtr = "unknown name"; } + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); } - } else { - return EFI_INVALID_PARAMETER; - } - break; + + break; + + default: + if (Attribute != PerfEntry) { + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + if (String != NULL) { + StringPtr = String; + } else { + StringPtr = ModuleName; + } + + if (AsciiStrLen (StringPtr) == 0) { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); + } + } else { + return EFI_INVALID_PARAMETER; + } + + break; } // // 4.2 When PcdEdkiiFpdtStringRecordEnableOnly==TRUE, create string record for all Perf entries. // if (PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - if (StringPtr == NULL ||PerfId == MODULE_DB_SUPPORT_START_ID || PerfId == MODULE_DB_SUPPORT_END_ID) { + if ((StringPtr == NULL) || (PerfId == MODULE_DB_SUPPORT_START_ID) || (PerfId == MODULE_DB_SUPPORT_END_ID)) { return EFI_INVALID_PARAMETER; } - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; if (Guid != NULL) { // // Cache the event guid in string event record. @@ -1215,37 +1264,44 @@ InsertFpdtRecord ( } else { CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); } + if (AsciiStrLen (StringPtr) == 0) { StringPtr = "unknown name"; } + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); if ((PerfId == MODULE_LOADIMAGE_START_ID) || (PerfId == MODULE_END_ID)) { FpdtRecordPtr.DynamicStringEvent->Header.Length = (UINT8)(sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD)+ STRING_SIZE); } - if ((PerfId == MODULE_LOADIMAGE_END_ID || PerfId == MODULE_END_ID) && mCachedLength != 0) { + + if (((PerfId == MODULE_LOADIMAGE_END_ID) || (PerfId == MODULE_END_ID)) && (mCachedLength != 0)) { if (mFpdtBufferIsReported) { CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mBootRecordBuffer + mCachedLength); } else { CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(mPerformancePointer + mCachedLength); } + if (PerfId == MODULE_LOADIMAGE_END_ID) { - DestMax = CachedFpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + DestMax = CachedFpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); StringLen = AsciiStrLen (StringPtr); if (StringLen >= DestMax) { StringLen = DestMax -1; } + CopyMem (&CachedFpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.DynamicStringEvent->Guid)); AsciiStrnCpyS (CachedFpdtRecordPtr.DynamicStringEvent->String, DestMax, StringPtr, StringLen); } else if (PerfId == MODULE_END_ID) { - DestMax = FpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + DestMax = FpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); StringLen = AsciiStrLen (CachedFpdtRecordPtr.DynamicStringEvent->String); if (StringLen >= DestMax) { StringLen = DestMax -1; } + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &CachedFpdtRecordPtr.DynamicStringEvent->Guid, sizeof (CachedFpdtRecordPtr.DynamicStringEvent->Guid)); AsciiStrnCpyS (FpdtRecordPtr.DynamicStringEvent->String, DestMax, CachedFpdtRecordPtr.DynamicStringEvent->String, StringLen); } + mCachedLength = 0; } } @@ -1254,11 +1310,12 @@ InsertFpdtRecord ( // 5. Update the length of the used buffer after fill in the record. // if (mFpdtBufferIsReported) { - mBootRecordSize += FpdtRecordPtr.RecordHeader->Length; + mBootRecordSize += FpdtRecordPtr.RecordHeader->Length; mAcpiBootPerformanceTable->Header.Length += FpdtRecordPtr.RecordHeader->Length; } else { mPerformanceLength += FpdtRecordPtr.RecordHeader->Length; } + return EFI_SUCCESS; } @@ -1277,10 +1334,10 @@ InternalGetPeiPerformance ( VOID *HobStart ) { - UINT8 *FirmwarePerformanceHob; - FPDT_PEI_EXT_PERF_HEADER *PeiPerformanceLogHeader; - UINT8 *EventRec; - EFI_HOB_GUID_TYPE *GuidHob; + UINT8 *FirmwarePerformanceHob; + FPDT_PEI_EXT_PERF_HEADER *PeiPerformanceLogHeader; + UINT8 *EventRec; + EFI_HOB_GUID_TYPE *GuidHob; GuidHob = GetNextGuidHob (&gEdkiiFpdtExtendedFirmwarePerformanceGuid, HobStart); while (GuidHob != NULL) { @@ -1326,27 +1383,28 @@ InternalGetPeiPerformance ( VOID EFIAPI ReportFpdtRecordBuffer ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_STATUS Status; - UINT64 BPDTAddr; + EFI_STATUS Status; + UINT64 BPDTAddr; if (!mFpdtBufferIsReported) { Status = AllocateBootPerformanceTable (); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { BPDTAddr = (UINT64)(UINTN)mAcpiBootPerformanceTable; REPORT_STATUS_CODE_EX ( - EFI_PROGRESS_CODE, - EFI_SOFTWARE_DXE_BS_DRIVER, - 0, - NULL, - &gEdkiiFpdtExtendedFirmwarePerformanceGuid, - &BPDTAddr, - sizeof (UINT64) - ); + EFI_PROGRESS_CODE, + EFI_SOFTWARE_DXE_BS_DRIVER, + 0, + NULL, + &gEdkiiFpdtExtendedFirmwarePerformanceGuid, + &BPDTAddr, + sizeof (UINT64) + ); } + // // Set FPDT report state to TRUE. // @@ -1364,14 +1422,14 @@ ReportFpdtRecordBuffer ( VOID EFIAPI UpdateBootPerformanceTable ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - VOID *SmmBootRecordData; - UINTN SmmBootRecordDataSize; - UINTN AppendSize; - UINT8 *FirmwarePerformanceTablePtr; + VOID *SmmBootRecordData; + UINTN SmmBootRecordDataSize; + UINTN AppendSize; + UINT8 *FirmwarePerformanceTablePtr; SmmBootRecordDataSize = 0; @@ -1381,7 +1439,7 @@ UpdateBootPerformanceTable ( SmmBootRecordData = NULL; InternalGetSmmPerfData (&SmmBootRecordData, &SmmBootRecordDataSize, FALSE); - FirmwarePerformanceTablePtr = (UINT8 *) mAcpiBootPerformanceTable + mAcpiBootPerformanceTable->Header.Length; + FirmwarePerformanceTablePtr = (UINT8 *)mAcpiBootPerformanceTable + mAcpiBootPerformanceTable->Header.Length; if (mAcpiBootPerformanceTable->Header.Length + SmmBootRecordDataSize > mBootRecordMaxSize) { DEBUG ((DEBUG_INFO, "DxeCorePerformanceLib: No enough space to save all SMM boot performance data\n")); @@ -1389,10 +1447,11 @@ UpdateBootPerformanceTable ( } else { AppendSize = SmmBootRecordDataSize; } + if (SmmBootRecordData != NULL) { CopyMem (FirmwarePerformanceTablePtr, SmmBootRecordData, AppendSize); - mAcpiBootPerformanceTable->Header.Length += (UINT32) AppendSize; - mBootRecordSize += (UINT32) AppendSize; + mAcpiBootPerformanceTable->Header.Length += (UINT32)AppendSize; + mBootRecordSize += (UINT32)AppendSize; FreePool (SmmBootRecordData); } } @@ -1417,11 +1476,11 @@ DxeCorePerformanceLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_EVENT EndOfDxeEvent; - EFI_EVENT ReadyToBootEvent; - PERFORMANCE_PROPERTY *PerformanceProperty; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_EVENT EndOfDxeEvent; + EFI_EVENT ReadyToBootEvent; + PERFORMANCE_PROPERTY *PerformanceProperty; if (!PerformanceMeasurementEnabled ()) { // @@ -1433,7 +1492,7 @@ DxeCorePerformanceLibConstructor ( // // Dump normal PEI performance records // - InternalGetPeiPerformance (GetHobList()); + InternalGetPeiPerformance (GetHobList ()); // // Install the protocol interfaces for DXE performance library instance. @@ -1473,7 +1532,7 @@ DxeCorePerformanceLibConstructor ( ASSERT_EFI_ERROR (Status); - Status = EfiGetSystemConfigurationTable (&gPerformanceProtocolGuid, (VOID **) &PerformanceProperty); + Status = EfiGetSystemConfigurationTable (&gPerformanceProtocolGuid, (VOID **)&PerformanceProperty); if (EFI_ERROR (Status)) { // // Install configuration table for performance property. @@ -1521,13 +1580,14 @@ CreatePerformanceMeasurement ( IN PERF_MEASUREMENT_ATTRIBUTE Attribute ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EFI_SUCCESS; if (mLockInsertRecord) { return EFI_INVALID_PARAMETER; } + mLockInsertRecord = TRUE; Status = InsertFpdtRecord (CallerIdentifier, Guid, String, TimeStamp, Address, (UINT16)Identifier, Attribute); @@ -1572,7 +1632,7 @@ StartPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -1621,7 +1681,7 @@ EndPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -1681,13 +1741,13 @@ EndPerformanceMeasurementEx ( UINTN EFIAPI GetPerformanceMeasurementEx ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp, - OUT UINT32 *Identifier + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp, + OUT UINT32 *Identifier ) { return 0; @@ -1808,12 +1868,12 @@ EndPerformanceMeasurement ( UINTN EFIAPI GetPerformanceMeasurement ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp ) { return 0; @@ -1837,7 +1897,7 @@ PerformanceMeasurementEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8(PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); } /** @@ -1883,14 +1943,15 @@ LogPerformanceMeasurement ( BOOLEAN EFIAPI LogPerformanceMeasurementEnabled ( - IN CONST UINTN Type + IN CONST UINTN Type ) { // // When Performance measurement is enabled and the type is not filtered, the performance can be logged. // - if (PerformanceMeasurementEnabled () && (PcdGet8(PcdPerformanceLibraryPropertyMask) & Type) == 0) { + if (PerformanceMeasurementEnabled () && ((PcdGet8 (PcdPerformanceLibraryPropertyMask) & Type) == 0)) { return TRUE; } + return FALSE; } diff --git a/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLibInternal.h b/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLibInternal.h index bfb472711e..8f32018c06 100644 --- a/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLibInternal.h +++ b/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLibInternal.h @@ -12,7 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _DXE_CORE_PERFORMANCE_LIB_INTERNAL_H_ #define _DXE_CORE_PERFORMANCE_LIB_INTERNAL_H_ - #include #include @@ -65,7 +64,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EFIAPI -CreatePerformanceMeasurement( +CreatePerformanceMeasurement ( IN CONST VOID *CallerIdentifier OPTIONAL, IN CONST VOID *Guid OPTIONAL, IN CONST CHAR8 *String OPTIONAL, diff --git a/MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.c b/MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.c index 1c0904c8f0..3e40dfa618 100644 --- a/MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.c +++ b/MdeModulePkg/Library/DxeCrc32GuidedSectionExtractLib/DxeCrc32GuidedSectionExtractLib.c @@ -21,13 +21,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// CRC32 Guided Section header /// typedef struct { - EFI_GUID_DEFINED_SECTION GuidedSectionHeader; ///< EFI guided section header - UINT32 CRC32Checksum; ///< 32bit CRC check sum + EFI_GUID_DEFINED_SECTION GuidedSectionHeader; ///< EFI guided section header + UINT32 CRC32Checksum; ///< 32bit CRC check sum } CRC32_SECTION_HEADER; typedef struct { - EFI_GUID_DEFINED_SECTION2 GuidedSectionHeader; ///< EFI guided section header - UINT32 CRC32Checksum; ///< 32bit CRC check sum + EFI_GUID_DEFINED_SECTION2 GuidedSectionHeader; ///< EFI guided section header + UINT32 CRC32Checksum; ///< 32bit CRC check sum } CRC32_SECTION2_HEADER; /** @@ -60,31 +60,37 @@ Crc32GuidedSectionGetInfo ( // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } + // // Retrieve the size and attribute of the input section data. // - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes; *ScratchBufferSize = 0; - *OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; + *OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } + // // Retrieve the size and attribute of the input section data. // - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes; *ScratchBufferSize = 0; - *OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; + *OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; } return EFI_SUCCESS; @@ -116,55 +122,59 @@ Crc32GuidedSectionHandler ( OUT UINT32 *AuthenticationStatus ) { - EFI_STATUS Status; - UINT32 SectionCrc32Checksum; - UINT32 Crc32Checksum; - UINT32 OutputBufferSize; - VOID *DummyInterface; + EFI_STATUS Status; + UINT32 SectionCrc32Checksum; + UINT32 Crc32Checksum; + UINT32 OutputBufferSize; + VOID *DummyInterface; if (IS_SECTION2 (InputSection)) { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } // // Get section Crc32 checksum. // - SectionCrc32Checksum = ((CRC32_SECTION2_HEADER *) InputSection)->CRC32Checksum; - *OutputBuffer = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; - OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; + SectionCrc32Checksum = ((CRC32_SECTION2_HEADER *)InputSection)->CRC32Checksum; + *OutputBuffer = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; + OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; // // Implicitly CRC32 GUIDed section should have STATUS_VALID bit set // - ASSERT (((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); + ASSERT (((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } // // Get section Crc32 checksum. // - SectionCrc32Checksum = ((CRC32_SECTION_HEADER *) InputSection)->CRC32Checksum; - *OutputBuffer = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; - OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; + SectionCrc32Checksum = ((CRC32_SECTION_HEADER *)InputSection)->CRC32Checksum; + *OutputBuffer = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; + OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; // // Implicitly CRC32 GUIDed section should have STATUS_VALID bit set // - ASSERT (((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); + ASSERT (((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } @@ -222,8 +232,8 @@ DxeCrc32GuidedSectionExtractLibConstructor ( ) { return ExtractGuidedSectionRegisterHandlers ( - &gEfiCrc32GuidedSectionExtractionGuid, - Crc32GuidedSectionGetInfo, - Crc32GuidedSectionHandler - ); + &gEfiCrc32GuidedSectionExtractionGuid, + Crc32GuidedSectionGetInfo, + Crc32GuidedSectionHandler + ); } diff --git a/MdeModulePkg/Library/DxeDebugPrintErrorLevelLib/DxeDebugPrintErrorLevelLib.c b/MdeModulePkg/Library/DxeDebugPrintErrorLevelLib/DxeDebugPrintErrorLevelLib.c index 7f3ccb06d8..547eb1532c 100644 --- a/MdeModulePkg/Library/DxeDebugPrintErrorLevelLib/DxeDebugPrintErrorLevelLib.c +++ b/MdeModulePkg/Library/DxeDebugPrintErrorLevelLib/DxeDebugPrintErrorLevelLib.c @@ -78,7 +78,7 @@ EFI_DEBUG_MASK_PROTOCOL mDebugMaskProtocol = { /// This variable prevents the EFI Variable Services from being called fort /// every DEBUG() macro. /// -BOOLEAN mGlobalErrorLevelInitialized = FALSE; +BOOLEAN mGlobalErrorLevelInitialized = FALSE; /// /// Global variable that contains the current debug error level mask for the @@ -90,7 +90,7 @@ BOOLEAN mGlobalErrorLevelInitialized = FALSE; /// Debug Mask Protocol SetDebugMask() service is called, then that overrides /// the PcdDebugPrintErrorLevel and the EFI Variable setting. /// -UINT32 mDebugPrintErrorLevel = 0; +UINT32 mDebugPrintErrorLevel = 0; /// /// Global variable that is used to cache a pointer to the EFI System Table @@ -98,7 +98,7 @@ UINT32 mDebugPrintErrorLevel = 0; /// the global debug print error level mask value. The UefiBootServicesTableLib /// is not used to prevent a circular dependency between these libraries. /// -EFI_SYSTEM_TABLE *mSystemTable = NULL; +EFI_SYSTEM_TABLE *mSystemTable = NULL; /** The constructor function caches the PCI Express Base Address and creates a @@ -118,7 +118,7 @@ DxeDebugPrintErrorLevelLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Initialize the error level mask from PCD setting. @@ -129,11 +129,12 @@ DxeDebugPrintErrorLevelLibConstructor ( // Install Debug Mask Protocol onto ImageHandle // mSystemTable = SystemTable; - Status = SystemTable->BootServices->InstallMultipleProtocolInterfaces ( - &ImageHandle, - &gEfiDebugMaskProtocolGuid, &mDebugMaskProtocol, - NULL - ); + Status = SystemTable->BootServices->InstallMultipleProtocolInterfaces ( + &ImageHandle, + &gEfiDebugMaskProtocolGuid, + &mDebugMaskProtocol, + NULL + ); // // Attempt to retrieve the global debug print error level mask from the EFI Variable @@ -170,7 +171,8 @@ DxeDebugPrintErrorLevelLibDestructor ( // return SystemTable->BootServices->UninstallMultipleProtocolInterfaces ( ImageHandle, - &gEfiDebugMaskProtocolGuid, &mDebugMaskProtocol, + &gEfiDebugMaskProtocolGuid, + &mDebugMaskProtocol, NULL ); } @@ -219,14 +221,14 @@ GetDebugPrintErrorLevel ( // Attempt to retrieve the global debug print error level mask from the // EFI Variable // - Size = sizeof (GlobalErrorLevel); + Size = sizeof (GlobalErrorLevel); Status = mSystemTable->RuntimeServices->GetVariable ( - DEBUG_MASK_VARIABLE_NAME, - &gEfiGenericVariableGuid, - NULL, - &Size, - &GlobalErrorLevel - ); + DEBUG_MASK_VARIABLE_NAME, + &gEfiGenericVariableGuid, + NULL, + &Size, + &GlobalErrorLevel + ); if (Status != EFI_NOT_AVAILABLE_YET) { // // If EFI Variable Services are available, then set a flag so the EFI @@ -248,7 +250,7 @@ GetDebugPrintErrorLevel ( Hob = GetFirstGuidHob (&gEfiGenericVariableGuid); if (Hob != NULL) { if (GET_GUID_HOB_DATA_SIZE (Hob) == sizeof (UINT32)) { - mDebugPrintErrorLevel = *(UINT32 *)GET_GUID_HOB_DATA (Hob); + mDebugPrintErrorLevel = *(UINT32 *)GET_GUID_HOB_DATA (Hob); mGlobalErrorLevelInitialized = TRUE; } } @@ -296,25 +298,26 @@ SetDebugPrintErrorLevel ( // Attempt to store the global debug print error level mask in an EFI Variable // GlobalErrorLevel = (UINTN)ErrorLevel; - Size = sizeof (GlobalErrorLevel); - Status = mSystemTable->RuntimeServices->SetVariable ( - DEBUG_MASK_VARIABLE_NAME, - &gEfiGenericVariableGuid, - (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS), - Size, - &GlobalErrorLevel - ); + Size = sizeof (GlobalErrorLevel); + Status = mSystemTable->RuntimeServices->SetVariable ( + DEBUG_MASK_VARIABLE_NAME, + &gEfiGenericVariableGuid, + (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS), + Size, + &GlobalErrorLevel + ); if (!EFI_ERROR (Status)) { // // If the EFI Variable was updated, then update the mask value for this // module and return TRUE. // mGlobalErrorLevelInitialized = TRUE; - mDebugPrintErrorLevel = ErrorLevel; + mDebugPrintErrorLevel = ErrorLevel; return TRUE; } } } + // // Return FALSE since the EFI Variable could not be updated. // diff --git a/MdeModulePkg/Library/DxeFileExplorerProtocol/DxeFileExplorerProtocol.c b/MdeModulePkg/Library/DxeFileExplorerProtocol/DxeFileExplorerProtocol.c index 14f29b55bb..a8f07c8996 100644 --- a/MdeModulePkg/Library/DxeFileExplorerProtocol/DxeFileExplorerProtocol.c +++ b/MdeModulePkg/Library/DxeFileExplorerProtocol/DxeFileExplorerProtocol.c @@ -20,7 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -EFI_FILE_EXPLORER_PROTOCOL *mProtocol = NULL; +EFI_FILE_EXPLORER_PROTOCOL *mProtocol = NULL; /** The constructor function caches the pointer to file explorer protocol. @@ -37,16 +37,16 @@ EFI_FILE_EXPLORER_PROTOCOL *mProtocol = NULL; EFI_STATUS EFIAPI FileExplorerConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = SystemTable->BootServices->LocateProtocol ( &gEfiFileExplorerProtocolGuid, NULL, - (VOID**) &mProtocol + (VOID **)&mProtocol ); ASSERT_EFI_ERROR (Status); ASSERT (mProtocol != NULL); diff --git a/MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.c b/MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.c index 0ee7095aba..05847de9ad 100644 --- a/MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.c +++ b/MdeModulePkg/Library/DxeIpmiLibIpmiProtocol/DxeIpmiLibIpmiProtocol.c @@ -11,7 +11,7 @@ #include #include -IPMI_PROTOCOL *mIpmiProtocol = NULL; +IPMI_PROTOCOL *mIpmiProtocol = NULL; /** This service enables submitting commands via Ipmi. @@ -34,22 +34,22 @@ IPMI_PROTOCOL *mIpmiProtocol = NULL; EFI_STATUS EFIAPI IpmiSubmitCommand ( - IN UINT8 NetFunction, - IN UINT8 Command, - IN UINT8 *RequestData, - IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, - IN OUT UINT32 *ResponseDataSize + IN UINT8 NetFunction, + IN UINT8 Command, + IN UINT8 *RequestData, + IN UINT32 RequestDataSize, + OUT UINT8 *ResponseData, + IN OUT UINT32 *ResponseDataSize ) { EFI_STATUS Status; if (mIpmiProtocol == NULL) { Status = gBS->LocateProtocol ( - &gIpmiProtocolGuid, - NULL, - (VOID **) &mIpmiProtocol - ); + &gIpmiProtocolGuid, + NULL, + (VOID **)&mIpmiProtocol + ); if (EFI_ERROR (Status)) { // // Dxe Ipmi Protocol is not installed. So, IPMI device is not present. @@ -71,5 +71,6 @@ IpmiSubmitCommand ( if (EFI_ERROR (Status)) { return Status; } + return EFI_SUCCESS; } diff --git a/MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.c b/MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.c index 9a7f8c440a..8e35cc4302 100644 --- a/MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.c +++ b/MdeModulePkg/Library/DxePerformanceLib/DxePerformanceLib.c @@ -11,7 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include #include @@ -24,7 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // The cached Performance Protocol and PerformanceEx Protocol interface. // -EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *mPerformanceMeasurement = NULL; +EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *mPerformanceMeasurement = NULL; /** The function caches the pointers to PerformanceEx protocol and Performance Protocol. @@ -40,14 +39,14 @@ GetPerformanceMeasurementProtocol ( VOID ) { - EFI_STATUS Status; - EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *PerformanceMeasurement; + EFI_STATUS Status; + EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *PerformanceMeasurement; if (mPerformanceMeasurement != NULL) { return EFI_SUCCESS; } - Status = gBS->LocateProtocol (&gEdkiiPerformanceMeasurementProtocolGuid, NULL, (VOID **) &PerformanceMeasurement); + Status = gBS->LocateProtocol (&gEdkiiPerformanceMeasurementProtocolGuid, NULL, (VOID **)&PerformanceMeasurement); if (!EFI_ERROR (Status)) { ASSERT (PerformanceMeasurement != NULL); // @@ -92,8 +91,8 @@ StartPerformanceMeasurementEx ( IN UINT32 Identifier ) { - EFI_STATUS Status; - CONST CHAR8* String; + EFI_STATUS Status; + CONST CHAR8 *String; Status = GetPerformanceMeasurementProtocol (); if (EFI_ERROR (Status)) { @@ -114,7 +113,7 @@ StartPerformanceMeasurementEx ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -151,8 +150,8 @@ EndPerformanceMeasurementEx ( IN UINT32 Identifier ) { - EFI_STATUS Status; - CONST CHAR8* String; + EFI_STATUS Status; + CONST CHAR8 *String; Status = GetPerformanceMeasurementProtocol (); if (EFI_ERROR (Status)) { @@ -173,7 +172,7 @@ EndPerformanceMeasurementEx ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -220,17 +219,16 @@ EndPerformanceMeasurementEx ( UINTN EFIAPI GetPerformanceMeasurementEx ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp, - OUT UINT32 *Identifier + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp, + OUT UINT32 *Identifier ) { return 0; - } /** @@ -341,12 +339,12 @@ EndPerformanceMeasurement ( UINTN EFIAPI GetPerformanceMeasurement ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp ) { return 0; @@ -370,7 +368,7 @@ PerformanceMeasurementEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8(PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); } /** @@ -394,7 +392,7 @@ LogPerformanceMeasurement ( IN CONST VOID *CallerIdentifier, IN CONST VOID *Guid OPTIONAL, IN CONST CHAR8 *String OPTIONAL, - IN UINT64 Address OPTIONAL, + IN UINT64 Address OPTIONAL, IN UINT32 Identifier ) { @@ -411,7 +409,7 @@ LogPerformanceMeasurement ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -429,14 +427,15 @@ LogPerformanceMeasurement ( BOOLEAN EFIAPI LogPerformanceMeasurementEnabled ( - IN CONST UINTN Type + IN CONST UINTN Type ) { // // When Performance measurement is enabled and the type is not filtered, the performance can be logged. // - if (PerformanceMeasurementEnabled () && (PcdGet8(PcdPerformanceLibraryPropertyMask) & Type) == 0) { + if (PerformanceMeasurementEnabled () && ((PcdGet8 (PcdPerformanceLibraryPropertyMask) & Type) == 0)) { return TRUE; } + return FALSE; } diff --git a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c index b702170388..21f8a0beab 100644 --- a/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c +++ b/MdeModulePkg/Library/DxePrintLibPrint2Protocol/PrintLib.c @@ -21,13 +21,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define ASSERT_UNICODE_BUFFER(Buffer) ASSERT ((((UINTN) (Buffer)) & 0x01) == 0) +#define ASSERT_UNICODE_BUFFER(Buffer) ASSERT ((((UINTN) (Buffer)) & 0x01) == 0) // // Safe print checks // -#define RSIZE_MAX (PcdGet32 (PcdMaximumUnicodeStringLength)) -#define ASCII_RSIZE_MAX (PcdGet32 (PcdMaximumAsciiStringLength)) +#define RSIZE_MAX (PcdGet32 (PcdMaximumUnicodeStringLength)) +#define ASCII_RSIZE_MAX (PcdGet32 (PcdMaximumAsciiStringLength)) #define SAFE_PRINT_CONSTRAINT_CHECK(Expression, RetVal) \ do { \ @@ -54,16 +54,16 @@ EFI_PRINT2S_PROTOCOL *mPrint2SProtocol = NULL; EFI_STATUS EFIAPI PrintLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = SystemTable->BootServices->LocateProtocol ( &gEfiPrint2SProtocolGuid, NULL, - (VOID**) &mPrint2SProtocol + (VOID **)&mPrint2SProtocol ); ASSERT_EFI_ERROR (Status); ASSERT (mPrint2SProtocol != NULL); @@ -71,7 +71,6 @@ PrintLibConstructor ( return Status; } - /** Worker function that converts a VA_LIST to a BASE_LIST based on a Null-terminated format string. @@ -111,14 +110,16 @@ DxePrintLibPrint2ProtocolVaListToBaseList ( if (ASCII_RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((AsciiStrnLenS (Format, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), FALSE); } + BytesPerFormatCharacter = 1; - FormatMask = 0xff; + FormatMask = 0xff; } else { if (RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((StrnLenS ((CHAR16 *)Format, RSIZE_MAX + 1) <= RSIZE_MAX), FALSE); } + BytesPerFormatCharacter = 2; - FormatMask = 0xffff; + FormatMask = 0xffff; } // @@ -145,41 +146,41 @@ DxePrintLibPrint2ProtocolVaListToBaseList ( FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; switch (FormatCharacter) { - case '.': - case '-': - case '+': - case ' ': - case ',': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - break; - case 'L': - case 'l': - Long = TRUE; - break; - case '*': - BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); - break; - case '\0': - // - // Make no output if Format string terminates unexpectedly when - // looking up for flag, width, precision and type. - // - Format -= BytesPerFormatCharacter; + case '.': + case '-': + case '+': + case ' ': + case ',': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + break; + case 'L': + case 'l': + Long = TRUE; + break; + case '*': + BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); + break; + case '\0': + // + // Make no output if Format string terminates unexpectedly when + // looking up for flag, width, precision and type. + // + Format -= BytesPerFormatCharacter; // // break skipped on purpose. // - default: - Done = TRUE; - break; + default: + Done = TRUE; + break; } } @@ -187,33 +188,35 @@ DxePrintLibPrint2ProtocolVaListToBaseList ( // Handle each argument type // switch (FormatCharacter) { - case 'p': - if (sizeof (VOID *) > 4) { - Long = TRUE; - } - case 'X': - case 'x': - case 'u': - case 'd': - if (Long) { - BASE_ARG (BaseListMarker, INT64) = VA_ARG (VaListMarker, INT64); - } else { - BASE_ARG (BaseListMarker, int) = VA_ARG (VaListMarker, int); - } - break; - case 's': - case 'S': - case 'a': - case 'g': - case 't': - BASE_ARG (BaseListMarker, VOID *) = VA_ARG (VaListMarker, VOID *); - break; - case 'c': - BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); - break; - case 'r': - BASE_ARG (BaseListMarker, RETURN_STATUS) = VA_ARG (VaListMarker, RETURN_STATUS); - break; + case 'p': + if (sizeof (VOID *) > 4) { + Long = TRUE; + } + + case 'X': + case 'x': + case 'u': + case 'd': + if (Long) { + BASE_ARG (BaseListMarker, INT64) = VA_ARG (VaListMarker, INT64); + } else { + BASE_ARG (BaseListMarker, int) = VA_ARG (VaListMarker, int); + } + + break; + case 's': + case 'S': + case 'a': + case 'g': + case 't': + BASE_ARG (BaseListMarker, VOID *) = VA_ARG (VaListMarker, VOID *); + break; + case 'c': + BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); + break; + case 'r': + BASE_ARG (BaseListMarker, RETURN_STATUS) = VA_ARG (VaListMarker, RETURN_STATUS); + break; } } @@ -235,6 +238,7 @@ DxePrintLibPrint2ProtocolVaListToBaseList ( // FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; } + return TRUE; } @@ -408,8 +412,8 @@ UnicodeSPrint ( ... ) { - VA_LIST Marker; - UINTN NumberOfPrinted; + VA_LIST Marker; + UINTN NumberOfPrinted; VA_START (Marker, FormatString); NumberOfPrinted = UnicodeVSPrint (StartOfBuffer, BufferSize, FormatString, Marker); @@ -583,8 +587,8 @@ UnicodeSPrintAsciiFormat ( ... ) { - VA_LIST Marker; - UINTN NumberOfPrinted; + VA_LIST Marker; + UINTN NumberOfPrinted; VA_START (Marker, FormatString); NumberOfPrinted = UnicodeVSPrintAsciiFormat (StartOfBuffer, BufferSize, FormatString, Marker); @@ -696,10 +700,10 @@ UnicodeValueToStringS ( UINTN EFIAPI AsciiVSPrint ( - OUT CHAR8 *StartOfBuffer, - IN UINTN BufferSize, - IN CONST CHAR8 *FormatString, - IN VA_LIST Marker + OUT CHAR8 *StartOfBuffer, + IN UINTN BufferSize, + IN CONST CHAR8 *FormatString, + IN VA_LIST Marker ) { UINT64 BaseListMarker[256 / sizeof (UINT64)]; @@ -757,10 +761,10 @@ AsciiVSPrint ( UINTN EFIAPI AsciiBSPrint ( - OUT CHAR8 *StartOfBuffer, - IN UINTN BufferSize, - IN CONST CHAR8 *FormatString, - IN BASE_LIST Marker + OUT CHAR8 *StartOfBuffer, + IN UINTN BufferSize, + IN CONST CHAR8 *FormatString, + IN BASE_LIST Marker ) { return mPrint2SProtocol->AsciiBSPrint (StartOfBuffer, BufferSize, FormatString, Marker); @@ -813,8 +817,8 @@ AsciiSPrint ( ... ) { - VA_LIST Marker; - UINTN NumberOfPrinted; + VA_LIST Marker; + UINTN NumberOfPrinted; VA_START (Marker, FormatString); NumberOfPrinted = AsciiVSPrint (StartOfBuffer, BufferSize, FormatString, Marker); @@ -988,8 +992,8 @@ AsciiSPrintUnicodeFormat ( ... ) { - VA_LIST Marker; - UINTN NumberOfPrinted; + VA_LIST Marker; + UINTN NumberOfPrinted; VA_START (Marker, FormatString); NumberOfPrinted = AsciiVSPrintUnicodeFormat (StartOfBuffer, BufferSize, FormatString, Marker); @@ -997,7 +1001,6 @@ AsciiSPrintUnicodeFormat ( return NumberOfPrinted; } - /** Converts a decimal value to a Null-terminated Ascii string. @@ -1050,46 +1053,46 @@ AsciiSPrintUnicodeFormat ( RETURN_STATUS EFIAPI AsciiValueToStringS ( - IN OUT CHAR8 *Buffer, - IN UINTN BufferSize, - IN UINTN Flags, - IN INT64 Value, - IN UINTN Width + IN OUT CHAR8 *Buffer, + IN UINTN BufferSize, + IN UINTN Flags, + IN INT64 Value, + IN UINTN Width ) { return mPrint2SProtocol->AsciiValueToStringS (Buffer, BufferSize, Flags, Value, Width); } -#define PREFIX_SIGN BIT1 -#define PREFIX_BLANK BIT2 -#define LONG_TYPE BIT4 -#define OUTPUT_UNICODE BIT6 -#define FORMAT_UNICODE BIT8 -#define PAD_TO_WIDTH BIT9 -#define ARGUMENT_UNICODE BIT10 -#define PRECISION BIT11 -#define ARGUMENT_REVERSED BIT12 -#define COUNT_ONLY_NO_PRINT BIT13 -#define UNSIGNED_TYPE BIT14 +#define PREFIX_SIGN BIT1 +#define PREFIX_BLANK BIT2 +#define LONG_TYPE BIT4 +#define OUTPUT_UNICODE BIT6 +#define FORMAT_UNICODE BIT8 +#define PAD_TO_WIDTH BIT9 +#define ARGUMENT_UNICODE BIT10 +#define PRECISION BIT11 +#define ARGUMENT_REVERSED BIT12 +#define COUNT_ONLY_NO_PRINT BIT13 +#define UNSIGNED_TYPE BIT14 // // Record date and time information // typedef struct { - UINT16 Year; - UINT8 Month; - UINT8 Day; - UINT8 Hour; - UINT8 Minute; - UINT8 Second; - UINT8 Pad1; - UINT32 Nanosecond; - INT16 TimeZone; - UINT8 Daylight; - UINT8 Pad2; + UINT16 Year; + UINT8 Month; + UINT8 Day; + UINT8 Hour; + UINT8 Minute; + UINT8 Second; + UINT8 Pad1; + UINT32 Nanosecond; + INT16 TimeZone; + UINT8 Daylight; + UINT8 Pad2; } TIME; -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 mHexStr[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 mHexStr[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /** Internal function that convert a number to a string in Buffer. @@ -1117,7 +1120,7 @@ InternalPrintLibValueToString ( // *Buffer = 0; do { - Value = (INT64)DivU64x32Remainder ((UINT64)Value, (UINT32)Radix, &Remainder); + Value = (INT64)DivU64x32Remainder ((UINT64)Value, (UINT32)Radix, &Remainder); *(++Buffer) = mHexStr[Remainder]; } while (Value != 0); @@ -1204,10 +1207,10 @@ InternalPrintLibSPrint ( return NumberOfPrinted; } -#define WARNING_STATUS_NUMBER 5 -#define ERROR_STATUS_NUMBER 33 +#define WARNING_STATUS_NUMBER 5 +#define ERROR_STATUS_NUMBER 33 -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 * CONST mStatusString[] = { +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 *CONST mStatusString[] = { "Success", // RETURN_SUCCESS = 0 "Warning Unknown Glyph", // RETURN_WARN_UNKNOWN_GLYPH = 1 "Warning Delete Failure", // RETURN_WARN_DELETE_FAILURE = 2 @@ -1267,20 +1270,21 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR8 * CONST mStatusString[] = { **/ CHAR8 * InternalPrintLibFillBuffer ( - OUT CHAR8 *Buffer, - IN CHAR8 *EndBuffer, - IN INTN Length, - IN UINTN Character, - IN INTN Increment + OUT CHAR8 *Buffer, + IN CHAR8 *EndBuffer, + IN INTN Length, + IN UINTN Character, + IN INTN Increment ) { INTN Index; for (Index = 0; Index < Length && Buffer < EndBuffer; Index++) { - *Buffer = (CHAR8) Character; + *Buffer = (CHAR8)Character; if (Increment != 1) { *(Buffer + 1) = (CHAR8)(Character >> 8); } + Buffer += Increment; } @@ -1325,36 +1329,36 @@ InternalPrintLibSPrintMarker ( IN BASE_LIST BaseListMarker OPTIONAL ) { - CHAR8 *OriginalBuffer; - CHAR8 *EndBuffer; - CHAR8 ValueBuffer[MAXIMUM_VALUE_CHARACTERS]; - UINT32 BytesPerOutputCharacter; - UINTN BytesPerFormatCharacter; - UINTN FormatMask; - UINTN FormatCharacter; - UINTN Width; - UINTN Precision; - INT64 Value; - CONST CHAR8 *ArgumentString; - UINTN Character; - GUID *TmpGuid; - TIME *TmpTime; - UINTN Count; - UINTN ArgumentMask; - INTN BytesPerArgumentCharacter; - UINTN ArgumentCharacter; - BOOLEAN Done; - UINTN Index; - CHAR8 Prefix; - BOOLEAN ZeroPad; - BOOLEAN Comma; - UINTN Digits; - UINTN Radix; - RETURN_STATUS Status; - UINT32 GuidData1; - UINT16 GuidData2; - UINT16 GuidData3; - UINTN LengthToReturn; + CHAR8 *OriginalBuffer; + CHAR8 *EndBuffer; + CHAR8 ValueBuffer[MAXIMUM_VALUE_CHARACTERS]; + UINT32 BytesPerOutputCharacter; + UINTN BytesPerFormatCharacter; + UINTN FormatMask; + UINTN FormatCharacter; + UINTN Width; + UINTN Precision; + INT64 Value; + CONST CHAR8 *ArgumentString; + UINTN Character; + GUID *TmpGuid; + TIME *TmpTime; + UINTN Count; + UINTN ArgumentMask; + INTN BytesPerArgumentCharacter; + UINTN ArgumentCharacter; + BOOLEAN Done; + UINTN Index; + CHAR8 Prefix; + BOOLEAN ZeroPad; + BOOLEAN Comma; + UINTN Digits; + UINTN Radix; + RETURN_STATUS Status; + UINT32 GuidData1; + UINT16 GuidData2; + UINT16 GuidData3; + UINTN LengthToReturn; // // If you change this code be sure to match the 2 versions of this function. @@ -1386,11 +1390,13 @@ InternalPrintLibSPrintMarker ( if (RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((BufferSize <= RSIZE_MAX), 0); } + BytesPerOutputCharacter = 2; } else { if (ASCII_RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((BufferSize <= ASCII_RSIZE_MAX), 0); } + BytesPerOutputCharacter = 1; } @@ -1402,14 +1408,16 @@ InternalPrintLibSPrintMarker ( if (RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((StrnLenS ((CHAR16 *)Format, RSIZE_MAX + 1) <= RSIZE_MAX), 0); } + BytesPerFormatCharacter = 2; - FormatMask = 0xffff; + FormatMask = 0xffff; } else { if (ASCII_RSIZE_MAX != 0) { SAFE_PRINT_CONSTRAINT_CHECK ((AsciiStrnLenS (Format, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), 0); } + BytesPerFormatCharacter = 1; - FormatMask = 0xff; + FormatMask = 0xff; } if ((Flags & COUNT_ONLY_NO_PRINT) != 0) { @@ -1426,7 +1434,7 @@ InternalPrintLibSPrintMarker ( } LengthToReturn = 0; - EndBuffer = NULL; + EndBuffer = NULL; OriginalBuffer = NULL; // @@ -1454,10 +1462,11 @@ InternalPrintLibSPrintMarker ( if ((Buffer != NULL) && (Buffer >= EndBuffer)) { break; } + // // Clear all the flag bits except those that may have been passed in // - Flags &= (UINTN) (OUTPUT_UNICODE | FORMAT_UNICODE | COUNT_ONLY_NO_PRINT); + Flags &= (UINTN)(OUTPUT_UNICODE | FORMAT_UNICODE | COUNT_ONLY_NO_PRINT); // // Set the default width to zero, and the default precision to 1 @@ -1471,344 +1480,415 @@ InternalPrintLibSPrintMarker ( Digits = 0; switch (FormatCharacter) { - case '%': - // - // Parse Flags and Width - // - for (Done = FALSE; !Done; ) { - Format += BytesPerFormatCharacter; - FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; + case '%': + // + // Parse Flags and Width + // + for (Done = FALSE; !Done; ) { + Format += BytesPerFormatCharacter; + FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; + switch (FormatCharacter) { + case '.': + Flags |= PRECISION; + break; + case '-': + Flags |= LEFT_JUSTIFY; + break; + case '+': + Flags |= PREFIX_SIGN; + break; + case ' ': + Flags |= PREFIX_BLANK; + break; + case ',': + Flags |= COMMA_TYPE; + break; + case 'L': + case 'l': + Flags |= LONG_TYPE; + break; + case '*': + if ((Flags & PRECISION) == 0) { + Flags |= PAD_TO_WIDTH; + if (BaseListMarker == NULL) { + Width = VA_ARG (VaListMarker, UINTN); + } else { + Width = BASE_ARG (BaseListMarker, UINTN); + } + } else { + if (BaseListMarker == NULL) { + Precision = VA_ARG (VaListMarker, UINTN); + } else { + Precision = BASE_ARG (BaseListMarker, UINTN); + } + } + + break; + case '0': + if ((Flags & PRECISION) == 0) { + Flags |= PREFIX_ZERO; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + for (Count = 0; ((FormatCharacter >= '0') && (FormatCharacter <= '9')); ) { + Count = (Count * 10) + FormatCharacter - '0'; + Format += BytesPerFormatCharacter; + FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; + } + + Format -= BytesPerFormatCharacter; + if ((Flags & PRECISION) == 0) { + Flags |= PAD_TO_WIDTH; + Width = Count; + } else { + Precision = Count; + } + + break; + + case '\0': + // + // Make no output if Format string terminates unexpectedly when + // looking up for flag, width, precision and type. + // + Format -= BytesPerFormatCharacter; + Precision = 0; + // + // break skipped on purpose. + // + default: + Done = TRUE; + break; + } + } + + // + // Handle each argument type + // switch (FormatCharacter) { - case '.': - Flags |= PRECISION; - break; - case '-': - Flags |= LEFT_JUSTIFY; - break; - case '+': - Flags |= PREFIX_SIGN; - break; - case ' ': - Flags |= PREFIX_BLANK; - break; - case ',': - Flags |= COMMA_TYPE; - break; - case 'L': - case 'l': - Flags |= LONG_TYPE; - break; - case '*': - if ((Flags & PRECISION) == 0) { - Flags |= PAD_TO_WIDTH; - if (BaseListMarker == NULL) { - Width = VA_ARG (VaListMarker, UINTN); - } else { - Width = BASE_ARG (BaseListMarker, UINTN); - } - } else { - if (BaseListMarker == NULL) { - Precision = VA_ARG (VaListMarker, UINTN); - } else { - Precision = BASE_ARG (BaseListMarker, UINTN); + case 'p': + // + // Flag space, +, 0, L & l are invalid for type p. + // + Flags &= ~((UINTN)(PREFIX_BLANK | PREFIX_SIGN | PREFIX_ZERO | LONG_TYPE)); + if (sizeof (VOID *) > 4) { + Flags |= LONG_TYPE; } - } - break; - case '0': - if ((Flags & PRECISION) == 0) { - Flags |= PREFIX_ZERO; - } - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - for (Count = 0; ((FormatCharacter >= '0') && (FormatCharacter <= '9')); ){ - Count = (Count * 10) + FormatCharacter - '0'; - Format += BytesPerFormatCharacter; - FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; - } - Format -= BytesPerFormatCharacter; - if ((Flags & PRECISION) == 0) { - Flags |= PAD_TO_WIDTH; - Width = Count; - } else { - Precision = Count; - } - break; - case '\0': // - // Make no output if Format string terminates unexpectedly when - // looking up for flag, width, precision and type. + // break skipped on purpose // - Format -= BytesPerFormatCharacter; - Precision = 0; + case 'X': + Flags |= PREFIX_ZERO; // - // break skipped on purpose. + // break skipped on purpose // - default: - Done = TRUE; - break; - } - } + case 'x': + Flags |= RADIX_HEX; + // + // break skipped on purpose + // + case 'u': + if ((Flags & RADIX_HEX) == 0) { + Flags &= ~((UINTN)(PREFIX_SIGN)); + Flags |= UNSIGNED_TYPE; + } - // - // Handle each argument type - // - switch (FormatCharacter) { - case 'p': - // - // Flag space, +, 0, L & l are invalid for type p. - // - Flags &= ~((UINTN) (PREFIX_BLANK | PREFIX_SIGN | PREFIX_ZERO | LONG_TYPE)); - if (sizeof (VOID *) > 4) { - Flags |= LONG_TYPE; - } - // - // break skipped on purpose - // - case 'X': - Flags |= PREFIX_ZERO; - // - // break skipped on purpose - // - case 'x': - Flags |= RADIX_HEX; - // - // break skipped on purpose - // - case 'u': - if ((Flags & RADIX_HEX) == 0) { - Flags &= ~((UINTN) (PREFIX_SIGN)); - Flags |= UNSIGNED_TYPE; - } - // - // break skipped on purpose - // - case 'd': - if ((Flags & LONG_TYPE) == 0) { // - // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". - // This assumption is made so the format string definition is compatible with the ANSI C - // Specification for formatted strings. It is recommended that the Base Types be used - // everywhere, but in this one case, compliance with ANSI C is more important, and - // provides an implementation that is compatible with that largest possible set of CPU - // architectures. This is why the type "int" is used in this one case. + // break skipped on purpose // - if (BaseListMarker == NULL) { - Value = VA_ARG (VaListMarker, int); - } else { - Value = BASE_ARG (BaseListMarker, int); - } - } else { - if (BaseListMarker == NULL) { - Value = VA_ARG (VaListMarker, INT64); - } else { - Value = BASE_ARG (BaseListMarker, INT64); - } - } - if ((Flags & PREFIX_BLANK) != 0) { - Prefix = ' '; - } - if ((Flags & PREFIX_SIGN) != 0) { - Prefix = '+'; - } - if ((Flags & COMMA_TYPE) != 0) { - Comma = TRUE; - } - if ((Flags & RADIX_HEX) == 0) { - Radix = 10; - if (Comma) { - Flags &= ~((UINTN) PREFIX_ZERO); - Precision = 1; - } - if (Value < 0 && (Flags & UNSIGNED_TYPE) == 0) { - Flags |= PREFIX_SIGN; - Prefix = '-'; - Value = -Value; - } else if ((Flags & UNSIGNED_TYPE) != 0 && (Flags & LONG_TYPE) == 0) { + case 'd': + if ((Flags & LONG_TYPE) == 0) { + // + // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". + // This assumption is made so the format string definition is compatible with the ANSI C + // Specification for formatted strings. It is recommended that the Base Types be used + // everywhere, but in this one case, compliance with ANSI C is more important, and + // provides an implementation that is compatible with that largest possible set of CPU + // architectures. This is why the type "int" is used in this one case. + // + if (BaseListMarker == NULL) { + Value = VA_ARG (VaListMarker, int); + } else { + Value = BASE_ARG (BaseListMarker, int); + } + } else { + if (BaseListMarker == NULL) { + Value = VA_ARG (VaListMarker, INT64); + } else { + Value = BASE_ARG (BaseListMarker, INT64); + } + } + + if ((Flags & PREFIX_BLANK) != 0) { + Prefix = ' '; + } + + if ((Flags & PREFIX_SIGN) != 0) { + Prefix = '+'; + } + + if ((Flags & COMMA_TYPE) != 0) { + Comma = TRUE; + } + + if ((Flags & RADIX_HEX) == 0) { + Radix = 10; + if (Comma) { + Flags &= ~((UINTN)PREFIX_ZERO); + Precision = 1; + } + + if ((Value < 0) && ((Flags & UNSIGNED_TYPE) == 0)) { + Flags |= PREFIX_SIGN; + Prefix = '-'; + Value = -Value; + } else if (((Flags & UNSIGNED_TYPE) != 0) && ((Flags & LONG_TYPE) == 0)) { + // + // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". + // This assumption is made so the format string definition is compatible with the ANSI C + // Specification for formatted strings. It is recommended that the Base Types be used + // everywhere, but in this one case, compliance with ANSI C is more important, and + // provides an implementation that is compatible with that largest possible set of CPU + // architectures. This is why the type "unsigned int" is used in this one case. + // + Value = (unsigned int)Value; + } + } else { + Radix = 16; + Comma = FALSE; + if (((Flags & LONG_TYPE) == 0) && (Value < 0)) { + // + // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". + // This assumption is made so the format string definition is compatible with the ANSI C + // Specification for formatted strings. It is recommended that the Base Types be used + // everywhere, but in this one case, compliance with ANSI C is more important, and + // provides an implementation that is compatible with that largest possible set of CPU + // architectures. This is why the type "unsigned int" is used in this one case. + // + Value = (unsigned int)Value; + } + } + // - // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". - // This assumption is made so the format string definition is compatible with the ANSI C - // Specification for formatted strings. It is recommended that the Base Types be used - // everywhere, but in this one case, compliance with ANSI C is more important, and - // provides an implementation that is compatible with that largest possible set of CPU - // architectures. This is why the type "unsigned int" is used in this one case. + // Convert Value to a reversed string // - Value = (unsigned int)Value; - } - } else { - Radix = 16; - Comma = FALSE; - if ((Flags & LONG_TYPE) == 0 && Value < 0) { + Count = InternalPrintLibValueToString (ValueBuffer, Value, Radix) - ValueBuffer; + if ((Value == 0) && (Precision == 0)) { + Count = 0; + } + + ArgumentString = (CHAR8 *)ValueBuffer + Count; + + Digits = Count % 3; + if (Digits != 0) { + Digits = 3 - Digits; + } + + if (Comma && (Count != 0)) { + Count += ((Count - 1) / 3); + } + + if (Prefix != 0) { + Count++; + Precision++; + } + + Flags |= ARGUMENT_REVERSED; + ZeroPad = TRUE; + if ((Flags & PREFIX_ZERO) != 0) { + if ((Flags & LEFT_JUSTIFY) == 0) { + if ((Flags & PAD_TO_WIDTH) != 0) { + if ((Flags & PRECISION) == 0) { + Precision = Width; + } + } + } + } + + break; + + case 's': + case 'S': + Flags |= ARGUMENT_UNICODE; + // + // break skipped on purpose + // + case 'a': + if (BaseListMarker == NULL) { + ArgumentString = VA_ARG (VaListMarker, CHAR8 *); + } else { + ArgumentString = BASE_ARG (BaseListMarker, CHAR8 *); + } + + if (ArgumentString == NULL) { + Flags &= (~(UINTN)ARGUMENT_UNICODE); + ArgumentString = ""; + } + // - // 'd', 'u', 'x', and 'X' that are not preceded by 'l' or 'L' are assumed to be type "int". - // This assumption is made so the format string definition is compatible with the ANSI C - // Specification for formatted strings. It is recommended that the Base Types be used - // everywhere, but in this one case, compliance with ANSI C is more important, and - // provides an implementation that is compatible with that largest possible set of CPU - // architectures. This is why the type "unsigned int" is used in this one case. + // Set the default precision for string to be zero if not specified. // - Value = (unsigned int)Value; - } - } - // - // Convert Value to a reversed string - // - Count = InternalPrintLibValueToString (ValueBuffer, Value, Radix) - ValueBuffer; - if (Value == 0 && Precision == 0) { - Count = 0; - } - ArgumentString = (CHAR8 *)ValueBuffer + Count; + if ((Flags & PRECISION) == 0) { + Precision = 0; + } - Digits = Count % 3; - if (Digits != 0) { - Digits = 3 - Digits; - } - if (Comma && Count != 0) { - Count += ((Count - 1) / 3); - } - if (Prefix != 0) { - Count++; - Precision++; - } - Flags |= ARGUMENT_REVERSED; - ZeroPad = TRUE; - if ((Flags & PREFIX_ZERO) != 0) { - if ((Flags & LEFT_JUSTIFY) == 0) { - if ((Flags & PAD_TO_WIDTH) != 0) { - if ((Flags & PRECISION) == 0) { - Precision = Width; + break; + + case 'c': + if (BaseListMarker == NULL) { + Character = VA_ARG (VaListMarker, UINTN) & 0xffff; + } else { + Character = BASE_ARG (BaseListMarker, UINTN) & 0xffff; + } + + ArgumentString = (CHAR8 *)&Character; + Flags |= ARGUMENT_UNICODE; + break; + + case 'g': + if (BaseListMarker == NULL) { + TmpGuid = VA_ARG (VaListMarker, GUID *); + } else { + TmpGuid = BASE_ARG (BaseListMarker, GUID *); + } + + if (TmpGuid == NULL) { + ArgumentString = ""; + } else { + GuidData1 = ReadUnaligned32 (&(TmpGuid->Data1)); + GuidData2 = ReadUnaligned16 (&(TmpGuid->Data2)); + GuidData3 = ReadUnaligned16 (&(TmpGuid->Data3)); + InternalPrintLibSPrint ( + ValueBuffer, + MAXIMUM_VALUE_CHARACTERS, + 0, + "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", + GuidData1, + GuidData2, + GuidData3, + TmpGuid->Data4[0], + TmpGuid->Data4[1], + TmpGuid->Data4[2], + TmpGuid->Data4[3], + TmpGuid->Data4[4], + TmpGuid->Data4[5], + TmpGuid->Data4[6], + TmpGuid->Data4[7] + ); + ArgumentString = ValueBuffer; + } + + break; + + case 't': + if (BaseListMarker == NULL) { + TmpTime = VA_ARG (VaListMarker, TIME *); + } else { + TmpTime = BASE_ARG (BaseListMarker, TIME *); + } + + if (TmpTime == NULL) { + ArgumentString = ""; + } else { + InternalPrintLibSPrint ( + ValueBuffer, + MAXIMUM_VALUE_CHARACTERS, + 0, + "%02d/%02d/%04d %02d:%02d", + TmpTime->Month, + TmpTime->Day, + TmpTime->Year, + TmpTime->Hour, + TmpTime->Minute + ); + ArgumentString = ValueBuffer; + } + + break; + + case 'r': + if (BaseListMarker == NULL) { + Status = VA_ARG (VaListMarker, RETURN_STATUS); + } else { + Status = BASE_ARG (BaseListMarker, RETURN_STATUS); + } + + ArgumentString = ValueBuffer; + if (RETURN_ERROR (Status)) { + // + // Clear error bit + // + Index = Status & ~MAX_BIT; + if ((Index > 0) && (Index <= ERROR_STATUS_NUMBER)) { + ArgumentString = mStatusString[Index + WARNING_STATUS_NUMBER]; + } + } else { + Index = Status; + if (Index <= WARNING_STATUS_NUMBER) { + ArgumentString = mStatusString[Index]; } } - } - } - break; - case 's': - case 'S': - Flags |= ARGUMENT_UNICODE; - // - // break skipped on purpose - // - case 'a': - if (BaseListMarker == NULL) { - ArgumentString = VA_ARG (VaListMarker, CHAR8 *); - } else { - ArgumentString = BASE_ARG (BaseListMarker, CHAR8 *); - } - if (ArgumentString == NULL) { - Flags &= (~(UINTN)ARGUMENT_UNICODE); - ArgumentString = ""; - } - // - // Set the default precision for string to be zero if not specified. - // - if ((Flags & PRECISION) == 0) { - Precision = 0; - } - break; + if (ArgumentString == ValueBuffer) { + InternalPrintLibSPrint ((CHAR8 *)ValueBuffer, MAXIMUM_VALUE_CHARACTERS, 0, "%08X", Status); + } - case 'c': - if (BaseListMarker == NULL) { - Character = VA_ARG (VaListMarker, UINTN) & 0xffff; - } else { - Character = BASE_ARG (BaseListMarker, UINTN) & 0xffff; - } - ArgumentString = (CHAR8 *)&Character; - Flags |= ARGUMENT_UNICODE; - break; + break; - case 'g': - if (BaseListMarker == NULL) { - TmpGuid = VA_ARG (VaListMarker, GUID *); - } else { - TmpGuid = BASE_ARG (BaseListMarker, GUID *); - } - if (TmpGuid == NULL) { - ArgumentString = ""; - } else { - GuidData1 = ReadUnaligned32 (&(TmpGuid->Data1)); - GuidData2 = ReadUnaligned16 (&(TmpGuid->Data2)); - GuidData3 = ReadUnaligned16 (&(TmpGuid->Data3)); - InternalPrintLibSPrint ( - ValueBuffer, - MAXIMUM_VALUE_CHARACTERS, - 0, - "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", - GuidData1, - GuidData2, - GuidData3, - TmpGuid->Data4[0], - TmpGuid->Data4[1], - TmpGuid->Data4[2], - TmpGuid->Data4[3], - TmpGuid->Data4[4], - TmpGuid->Data4[5], - TmpGuid->Data4[6], - TmpGuid->Data4[7] - ); - ArgumentString = ValueBuffer; - } - break; + case '\r': + Format += BytesPerFormatCharacter; + FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; + if (FormatCharacter == '\n') { + // + // Translate '\r\n' to '\r\n' + // + ArgumentString = "\r\n"; + } else { + // + // Translate '\r' to '\r' + // + ArgumentString = "\r"; + Format -= BytesPerFormatCharacter; + } - case 't': - if (BaseListMarker == NULL) { - TmpTime = VA_ARG (VaListMarker, TIME *); - } else { - TmpTime = BASE_ARG (BaseListMarker, TIME *); - } - if (TmpTime == NULL) { - ArgumentString = ""; - } else { - InternalPrintLibSPrint ( - ValueBuffer, - MAXIMUM_VALUE_CHARACTERS, - 0, - "%02d/%02d/%04d %02d:%02d", - TmpTime->Month, - TmpTime->Day, - TmpTime->Year, - TmpTime->Hour, - TmpTime->Minute - ); - ArgumentString = ValueBuffer; - } - break; + break; - case 'r': - if (BaseListMarker == NULL) { - Status = VA_ARG (VaListMarker, RETURN_STATUS); - } else { - Status = BASE_ARG (BaseListMarker, RETURN_STATUS); - } - ArgumentString = ValueBuffer; - if (RETURN_ERROR (Status)) { - // - // Clear error bit - // - Index = Status & ~MAX_BIT; - if (Index > 0 && Index <= ERROR_STATUS_NUMBER) { - ArgumentString = mStatusString [Index + WARNING_STATUS_NUMBER]; - } - } else { - Index = Status; - if (Index <= WARNING_STATUS_NUMBER) { - ArgumentString = mStatusString [Index]; - } - } - if (ArgumentString == ValueBuffer) { - InternalPrintLibSPrint ((CHAR8 *) ValueBuffer, MAXIMUM_VALUE_CHARACTERS, 0, "%08X", Status); + case '\n': + // + // Translate '\n' to '\r\n' and '\n\r' to '\r\n' + // + ArgumentString = "\r\n"; + Format += BytesPerFormatCharacter; + FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; + if (FormatCharacter != '\r') { + Format -= BytesPerFormatCharacter; + } + + break; + + case '%': + default: + // + // if the type is '%' or unknown, then print it to the screen + // + ArgumentString = (CHAR8 *)&FormatCharacter; + Flags |= ARGUMENT_UNICODE; + break; } + break; case '\r': - Format += BytesPerFormatCharacter; + Format += BytesPerFormatCharacter; FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; if (FormatCharacter == '\n') { // @@ -1820,78 +1900,41 @@ InternalPrintLibSPrintMarker ( // Translate '\r' to '\r' // ArgumentString = "\r"; - Format -= BytesPerFormatCharacter; + Format -= BytesPerFormatCharacter; } + break; case '\n': // // Translate '\n' to '\r\n' and '\n\r' to '\r\n' // - ArgumentString = "\r\n"; - Format += BytesPerFormatCharacter; + ArgumentString = "\r\n"; + Format += BytesPerFormatCharacter; FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; if (FormatCharacter != '\r') { - Format -= BytesPerFormatCharacter; + Format -= BytesPerFormatCharacter; } + break; - case '%': default: - // - // if the type is '%' or unknown, then print it to the screen - // ArgumentString = (CHAR8 *)&FormatCharacter; - Flags |= ARGUMENT_UNICODE; + Flags |= ARGUMENT_UNICODE; break; - } - break; - - case '\r': - Format += BytesPerFormatCharacter; - FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; - if (FormatCharacter == '\n') { - // - // Translate '\r\n' to '\r\n' - // - ArgumentString = "\r\n"; - } else { - // - // Translate '\r' to '\r' - // - ArgumentString = "\r"; - Format -= BytesPerFormatCharacter; - } - break; - - case '\n': - // - // Translate '\n' to '\r\n' and '\n\r' to '\r\n' - // - ArgumentString = "\r\n"; - Format += BytesPerFormatCharacter; - FormatCharacter = ((*Format & 0xff) | ((BytesPerFormatCharacter == 1) ? 0 : (*(Format + 1) << 8))) & FormatMask; - if (FormatCharacter != '\r') { - Format -= BytesPerFormatCharacter; - } - break; - - default: - ArgumentString = (CHAR8 *)&FormatCharacter; - Flags |= ARGUMENT_UNICODE; - break; } // // Retrieve the ArgumentString attriubutes // if ((Flags & ARGUMENT_UNICODE) != 0) { - ArgumentMask = 0xffff; + ArgumentMask = 0xffff; BytesPerArgumentCharacter = 2; } else { - ArgumentMask = 0xff; + ArgumentMask = 0xff; BytesPerArgumentCharacter = 1; } + if ((Flags & ARGUMENT_REVERSED) != 0) { BytesPerArgumentCharacter = -BytesPerArgumentCharacter; } else { @@ -1900,11 +1943,12 @@ InternalPrintLibSPrintMarker ( // ArgumentString is either null-terminated, or it contains Precision characters // for (Count = 0; - (ArgumentString[Count * BytesPerArgumentCharacter] != '\0' || - (BytesPerArgumentCharacter > 1 && - ArgumentString[Count * BytesPerArgumentCharacter + 1]!= '\0')) && - (Count < Precision || ((Flags & PRECISION) == 0)); - Count++) { + (ArgumentString[Count * BytesPerArgumentCharacter] != '\0' || + (BytesPerArgumentCharacter > 1 && + ArgumentString[Count * BytesPerArgumentCharacter + 1] != '\0')) && + (Count < Precision || ((Flags & PRECISION) == 0)); + Count++) + { ArgumentCharacter = ((ArgumentString[Count * BytesPerArgumentCharacter] & 0xff) | ((ArgumentString[Count * BytesPerArgumentCharacter + 1]) << 8)) & ArgumentMask; if (ArgumentCharacter == 0) { break; @@ -1921,7 +1965,7 @@ InternalPrintLibSPrintMarker ( // if ((Flags & (PAD_TO_WIDTH | LEFT_JUSTIFY)) == (PAD_TO_WIDTH)) { LengthToReturn += ((Width - Precision) * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, Width - Precision, ' ', BytesPerOutputCharacter); } } @@ -1929,22 +1973,24 @@ InternalPrintLibSPrintMarker ( if (ZeroPad) { if (Prefix != 0) { LengthToReturn += (1 * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, 1, Prefix, BytesPerOutputCharacter); } } + LengthToReturn += ((Precision - Count) * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, Precision - Count, '0', BytesPerOutputCharacter); } } else { LengthToReturn += ((Precision - Count) * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, Precision - Count, ' ', BytesPerOutputCharacter); } + if (Prefix != 0) { LengthToReturn += (1 * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, 1, Prefix, BytesPerOutputCharacter); } } @@ -1963,14 +2009,16 @@ InternalPrintLibSPrintMarker ( // while (Index < Count && (ArgumentString[0] != '\0' || - (BytesPerArgumentCharacter > 1 && ArgumentString[1] != '\0'))) { + (BytesPerArgumentCharacter > 1 && ArgumentString[1] != '\0'))) + { ArgumentCharacter = ((*ArgumentString & 0xff) | (((UINT8)*(ArgumentString + 1)) << 8)) & ArgumentMask; LengthToReturn += (1 * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, 1, ArgumentCharacter, BytesPerOutputCharacter); } - ArgumentString += BytesPerArgumentCharacter; + + ArgumentString += BytesPerArgumentCharacter; Index++; if (Comma) { Digits++; @@ -1979,7 +2027,7 @@ InternalPrintLibSPrintMarker ( Index++; if (Index < Count) { LengthToReturn += (1 * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, 1, ',', BytesPerOutputCharacter); } } @@ -1992,7 +2040,7 @@ InternalPrintLibSPrintMarker ( // if ((Flags & (PAD_TO_WIDTH | LEFT_JUSTIFY)) == (PAD_TO_WIDTH | LEFT_JUSTIFY)) { LengthToReturn += ((Width - Precision) * BytesPerOutputCharacter); - if ((Flags & COUNT_ONLY_NO_PRINT) == 0 && Buffer != NULL) { + if (((Flags & COUNT_ONLY_NO_PRINT) == 0) && (Buffer != NULL)) { Buffer = InternalPrintLibFillBuffer (Buffer, EndBuffer, Width - Precision, ' ', BytesPerOutputCharacter); } } @@ -2041,7 +2089,7 @@ InternalPrintLibSPrintMarker ( UINTN EFIAPI SPrintLength ( - IN CONST CHAR16 *FormatString, + IN CONST CHAR16 *FormatString, IN VA_LIST Marker ) { @@ -2067,8 +2115,8 @@ SPrintLength ( UINTN EFIAPI SPrintLengthAsciiFormat ( - IN CONST CHAR8 *FormatString, - IN VA_LIST Marker + IN CONST CHAR8 *FormatString, + IN VA_LIST Marker ) { return InternalPrintLibSPrintMarker (NULL, 0, OUTPUT_UNICODE | COUNT_ONLY_NO_PRINT, (CHAR8 *)FormatString, Marker, NULL); diff --git a/MdeModulePkg/Library/DxeReportStatusCodeLib/ReportStatusCodeLib.c b/MdeModulePkg/Library/DxeReportStatusCodeLib/ReportStatusCodeLib.c index 92559a54f3..ed01d8aacb 100644 --- a/MdeModulePkg/Library/DxeReportStatusCodeLib/ReportStatusCodeLib.c +++ b/MdeModulePkg/Library/DxeReportStatusCodeLib/ReportStatusCodeLib.c @@ -47,8 +47,8 @@ InternalGetReportStatusCode ( // // Check gBS just in case ReportStatusCode is called before gBS is initialized. // - if (gBS != NULL && gBS->LocateProtocol != NULL) { - Status = gBS->LocateProtocol (&gEfiStatusCodeRuntimeProtocolGuid, NULL, (VOID**) &mReportStatusCodeLibStatusCodeProtocol); + if ((gBS != NULL) && (gBS->LocateProtocol != NULL)) { + Status = gBS->LocateProtocol (&gEfiStatusCodeRuntimeProtocolGuid, NULL, (VOID **)&mReportStatusCodeLibStatusCodeProtocol); if (EFI_ERROR (Status)) { mReportStatusCodeLibStatusCodeProtocol = NULL; } @@ -80,16 +80,17 @@ InternalGetReportStatusCode ( **/ EFI_STATUS InternalReportStatusCode ( - IN EFI_STATUS_CODE_TYPE Type, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE Type, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ) { - if ((ReportProgressCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - (ReportErrorCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) || - (ReportDebugCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE)) { + if ((ReportProgressCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE)) || + (ReportErrorCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) || + (ReportDebugCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE))) + { // // If mReportStatusCodeLibStatusCodeProtocol is NULL, then check if Report Status Code Protocol is available in system. // @@ -107,7 +108,6 @@ InternalReportStatusCode ( return EFI_UNSUPPORTED; } - /** Converts a status code to an 8-bit POST code value. @@ -146,15 +146,16 @@ CodeTypeToPostCode ( // Convert Value to an 8 bit post code // if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) ) { - *PostCode = (UINT8) ((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | - (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); + ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) + { + *PostCode = (UINT8)((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | + (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); return TRUE; } + return FALSE; } - /** Extracts ASSERT() information from a status code structure. @@ -208,17 +209,18 @@ ReportStatusCodeExtractAssertInfo ( if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) && ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) && - ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) { + ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) + { AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1); *Filename = (CHAR8 *)(AssertData + 1); *Description = *Filename + AsciiStrLen (*Filename) + 1; *LineNumber = AssertData->LineNumber; return TRUE; } + return FALSE; } - /** Extracts DEBUG() information from a status code structure. @@ -287,13 +289,12 @@ ReportStatusCodeExtractDebugInfo ( // 64-bit aligned is a must, otherwise retrieving 64-bit parameter from BASE_LIST will // cause unalignment exception. // - *Marker = (BASE_LIST) (DebugInfo + 1); + *Marker = (BASE_LIST)(DebugInfo + 1); *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12); return TRUE; } - /** Reports a status code. @@ -325,7 +326,6 @@ ReportStatusCode ( return InternalReportStatusCode (Type, Value, 0, &gEfiCallerIdGuid, NULL); } - /** Reports a status code with a Device Path Protocol as the extended data. @@ -371,7 +371,6 @@ ReportStatusCodeWithDevicePath ( ); } - /** Reports a status code with an extended data buffer. @@ -427,7 +426,6 @@ ReportStatusCodeWithExtendedData ( ); } - /** Reports a status code with full parameters. @@ -496,7 +494,7 @@ ReportStatusCodeEx ( // StatusCodeData = (EFI_STATUS_CODE_DATA *)Buffer; } else { - if (gBS == NULL || gBS->AllocatePool == NULL || gBS->FreePool == NULL) { + if ((gBS == NULL) || (gBS->AllocatePool == NULL) || (gBS->FreePool == NULL)) { return EFI_UNSUPPORTED; } @@ -523,11 +521,12 @@ ReportStatusCodeEx ( // // Fill in the extended data header // - StatusCodeData->HeaderSize = (UINT16) sizeof (EFI_STATUS_CODE_DATA); - StatusCodeData->Size = (UINT16) ExtendedDataSize; + StatusCodeData->HeaderSize = (UINT16)sizeof (EFI_STATUS_CODE_DATA); + StatusCodeData->Size = (UINT16)ExtendedDataSize; if (ExtendedDataGuid == NULL) { ExtendedDataGuid = &gEfiStatusCodeSpecificDataGuid; } + CopyGuid (&StatusCodeData->Type, ExtendedDataGuid); // @@ -543,6 +542,7 @@ ReportStatusCodeEx ( if (CallerId == NULL) { CallerId = &gEfiCallerIdGuid; } + Status = InternalReportStatusCode (Type, Value, Instance, CallerId, StatusCodeData); // @@ -555,7 +555,6 @@ ReportStatusCodeEx ( return Status; } - /** Returns TRUE if status codes of type EFI_PROGRESS_CODE are enabled @@ -574,10 +573,9 @@ ReportProgressCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_ERROR_CODE are enabled @@ -596,10 +594,9 @@ ReportErrorCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_DEBUG_CODE are enabled @@ -618,5 +615,5 @@ ReportDebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); } diff --git a/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c b/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c index 47b814fe8d..98e979dff6 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c @@ -71,8 +71,8 @@ ResetShutdown ( VOID EFIAPI ResetPlatformSpecific ( - IN UINTN DataSize, - IN VOID *ResetData + IN UINTN DataSize, + IN VOID *ResetData ) { gRT->ResetSystem (EfiResetPlatformSpecific, EFI_SUCCESS, DataSize, ResetData); @@ -93,10 +93,10 @@ ResetPlatformSpecific ( VOID EFIAPI ResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { gRT->ResetSystem (ResetType, ResetStatus, DataSize, ResetData); diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index 3bba38b579..c286f57c85 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -22,8 +22,8 @@ #include #include -#define UNIT_TEST_APP_NAME "DxeResetSystemLib Unit Tests" -#define UNIT_TEST_APP_VERSION "1.0" +#define UNIT_TEST_APP_NAME "DxeResetSystemLib Unit Tests" +#define UNIT_TEST_APP_VERSION "1.0" /** Resets the entire platform. @@ -44,10 +44,10 @@ STATIC VOID EFIAPI MockResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { check_expected_ptr (ResetType); @@ -256,15 +256,15 @@ UnitTestingEntry ( Framework = NULL; - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION)); // // Start setting up the test framework for running the tests. // Status = InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; } // @@ -304,8 +304,8 @@ EXIT: **/ int main ( - int argc, - char *argv[] + int argc, + char *argv[] ) { return UnitTestingEntry (); diff --git a/MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.c b/MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.c index f72d9a0362..8b8cf3a7d3 100644 --- a/MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.c +++ b/MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.c @@ -15,7 +15,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define SECURITY_HANDLER_TABLE_SIZE 0x10 +#define SECURITY_HANDLER_TABLE_SIZE 0x10 // // Secruity Operation on Image and none Image. @@ -27,24 +27,24 @@ SPDX-License-Identifier: BSD-2-Clause-Patent | EFI_AUTH_OPERATION_AUTHENTICATION_STATE) typedef struct { - UINT32 SecurityOperation; - SECURITY_FILE_AUTHENTICATION_STATE_HANDLER SecurityHandler; + UINT32 SecurityOperation; + SECURITY_FILE_AUTHENTICATION_STATE_HANDLER SecurityHandler; } SECURITY_INFO; typedef struct { - UINT32 Security2Operation; - SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler; + UINT32 Security2Operation; + SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler; } SECURITY2_INFO; -UINT32 mCurrentAuthOperation = 0; -UINT32 mNumberOfSecurityHandler = 0; -UINT32 mMaxNumberOfSecurityHandler = 0; -SECURITY_INFO *mSecurityTable = NULL; +UINT32 mCurrentAuthOperation = 0; +UINT32 mNumberOfSecurityHandler = 0; +UINT32 mMaxNumberOfSecurityHandler = 0; +SECURITY_INFO *mSecurityTable = NULL; -UINT32 mCurrentAuthOperation2 = 0; -UINT32 mNumberOfSecurity2Handler = 0; -UINT32 mMaxNumberOfSecurity2Handler = 0; -SECURITY2_INFO *mSecurity2Table = NULL; +UINT32 mCurrentAuthOperation2 = 0; +UINT32 mNumberOfSecurity2Handler = 0; +UINT32 mMaxNumberOfSecurity2Handler = 0; +SECURITY2_INFO *mSecurity2Table = NULL; /** Reallocates more global memory to store the registered Handler list. @@ -93,8 +93,8 @@ ReallocateSecurityHandlerTable ( **/ BOOLEAN CheckAuthenticationOperation ( - IN UINT32 CurrentAuthOperation, - IN UINT32 CheckAuthOperation + IN UINT32 CurrentAuthOperation, + IN UINT32 CheckAuthOperation ) { // @@ -108,7 +108,8 @@ CheckAuthenticationOperation ( // if ((CurrentAuthOperation & EFI_AUTH_OPERATION_MEASURE_IMAGE) == EFI_AUTH_OPERATION_MEASURE_IMAGE) { if (((CheckAuthOperation & EFI_AUTH_OPERATION_MEASURE_IMAGE) == EFI_AUTH_OPERATION_MEASURE_IMAGE) || - ((CheckAuthOperation & EFI_AUTH_IMAGE_OPERATION_MASK) == EFI_AUTH_OPERATION_NONE)) { + ((CheckAuthOperation & EFI_AUTH_IMAGE_OPERATION_MASK) == EFI_AUTH_OPERATION_NONE)) + { return TRUE; } else { return FALSE; @@ -160,7 +161,7 @@ RegisterSecurityHandler ( // // Allocate more resources for new handler. // - Status = ReallocateSecurityHandlerTable(); + Status = ReallocateSecurityHandlerTable (); ASSERT_EFI_ERROR (Status); } @@ -169,7 +170,7 @@ RegisterSecurityHandler ( // mSecurityTable[mNumberOfSecurityHandler].SecurityOperation = AuthenticationOperation; mSecurityTable[mNumberOfSecurityHandler].SecurityHandler = SecurityHandler; - mNumberOfSecurityHandler ++; + mNumberOfSecurityHandler++; return EFI_SUCCESS; } @@ -208,18 +209,18 @@ RegisterSecurityHandler ( EFI_STATUS EFIAPI ExecuteSecurityHandlers ( - IN UINT32 AuthenticationStatus, - IN CONST EFI_DEVICE_PATH_PROTOCOL *FilePath + IN UINT32 AuthenticationStatus, + IN CONST EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - UINT32 Index; - EFI_STATUS Status; - UINT32 HandlerAuthenticationStatus; - VOID *FileBuffer; - UINTN FileSize; - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *Node; - EFI_DEVICE_PATH_PROTOCOL *FilePathToVerfiy; + UINT32 Index; + EFI_STATUS Status; + UINT32 HandlerAuthenticationStatus; + VOID *FileBuffer; + UINTN FileSize; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_DEVICE_PATH_PROTOCOL *FilePathToVerfiy; if (FilePath == NULL) { return EFI_INVALID_PARAMETER; @@ -236,11 +237,11 @@ ExecuteSecurityHandlers ( FileBuffer = NULL; FileSize = 0; HandlerAuthenticationStatus = AuthenticationStatus; - FilePathToVerfiy = (EFI_DEVICE_PATH_PROTOCOL *) FilePath; + FilePathToVerfiy = (EFI_DEVICE_PATH_PROTOCOL *)FilePath; // // Run security handler in same order to their registered list // - for (Index = 0; Index < mNumberOfSecurityHandler; Index ++) { + for (Index = 0; Index < mNumberOfSecurityHandler; Index++) { if ((mSecurityTable[Index].SecurityOperation & EFI_AUTH_OPERATION_IMAGE_REQUIRED) == EFI_AUTH_OPERATION_IMAGE_REQUIRED) { // // Try get file buffer when the handler requires image buffer. @@ -258,6 +259,7 @@ ExecuteSecurityHandlers ( // FileBuffer = GetFileBufferByFilePath (TRUE, FilePath, &FileSize, &AuthenticationStatus); } + if ((FileBuffer != NULL) && (!EFI_ERROR (Status))) { // // LoadFile () may cause the device path of the Handle be updated. @@ -266,12 +268,13 @@ ExecuteSecurityHandlers ( } } } + Status = mSecurityTable[Index].SecurityHandler ( - HandlerAuthenticationStatus, - FilePathToVerfiy, - FileBuffer, - FileSize - ); + HandlerAuthenticationStatus, + FilePathToVerfiy, + FileBuffer, + FileSize + ); if (EFI_ERROR (Status)) { break; } @@ -280,6 +283,7 @@ ExecuteSecurityHandlers ( if (FileBuffer != NULL) { FreePool (FileBuffer); } + if (FilePathToVerfiy != FilePath) { FreePool (FilePathToVerfiy); } @@ -303,10 +307,10 @@ ReallocateSecurity2HandlerTable ( // Reallocate memory for security info structure. // mSecurity2Table = ReallocatePool ( - mMaxNumberOfSecurity2Handler * sizeof (SECURITY2_INFO), - (mMaxNumberOfSecurity2Handler + SECURITY_HANDLER_TABLE_SIZE) * sizeof (SECURITY2_INFO), - mSecurity2Table - ); + mMaxNumberOfSecurity2Handler * sizeof (SECURITY2_INFO), + (mMaxNumberOfSecurity2Handler + SECURITY_HANDLER_TABLE_SIZE) * sizeof (SECURITY2_INFO), + mSecurity2Table + ); // // No enough resource is allocated. @@ -339,8 +343,8 @@ ReallocateSecurity2HandlerTable ( **/ BOOLEAN CheckAuthentication2Operation ( - IN UINT32 CurrentAuthOperation, - IN UINT32 CheckAuthOperation + IN UINT32 CurrentAuthOperation, + IN UINT32 CheckAuthOperation ) { // @@ -349,9 +353,11 @@ CheckAuthentication2Operation ( if (CheckAuthOperation == EFI_AUTH_OPERATION_NONE) { return FALSE; } + if ((CheckAuthOperation & ~(EFI_AUTH_IMAGE_OPERATION_MASK | EFI_AUTH_NONE_IMAGE_OPERATION_MASK | - EFI_AUTH_OPERATION_IMAGE_REQUIRED)) != 0) { + EFI_AUTH_OPERATION_IMAGE_REQUIRED)) != 0) + { return FALSE; } @@ -361,7 +367,8 @@ CheckAuthentication2Operation ( // if ((CurrentAuthOperation & EFI_AUTH_OPERATION_MEASURE_IMAGE) == EFI_AUTH_OPERATION_MEASURE_IMAGE) { if (((CheckAuthOperation & EFI_AUTH_OPERATION_MEASURE_IMAGE) == EFI_AUTH_OPERATION_MEASURE_IMAGE) || - ((CheckAuthOperation & EFI_AUTH_IMAGE_OPERATION_MASK) == 0)) { + ((CheckAuthOperation & EFI_AUTH_IMAGE_OPERATION_MASK) == 0)) + { return TRUE; } else { return FALSE; @@ -392,8 +399,8 @@ CheckAuthentication2Operation ( EFI_STATUS EFIAPI RegisterSecurity2Handler ( - IN SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler, - IN UINT32 AuthenticationOperation + IN SECURITY2_FILE_AUTHENTICATION_HANDLER Security2Handler, + IN UINT32 AuthenticationOperation ) { EFI_STATUS Status; @@ -413,7 +420,7 @@ RegisterSecurity2Handler ( // // Allocate more resources for new handler. // - Status = ReallocateSecurity2HandlerTable(); + Status = ReallocateSecurity2HandlerTable (); ASSERT_EFI_ERROR (Status); } @@ -422,7 +429,7 @@ RegisterSecurity2Handler ( // mSecurity2Table[mNumberOfSecurity2Handler].Security2Operation = AuthenticationOperation; mSecurity2Table[mNumberOfSecurity2Handler].Security2Handler = Security2Handler; - mNumberOfSecurity2Handler ++; + mNumberOfSecurity2Handler++; return EFI_SUCCESS; } @@ -471,21 +478,21 @@ RegisterSecurity2Handler ( EFI_STATUS EFIAPI ExecuteSecurity2Handlers ( - IN UINT32 AuthenticationOperation, - IN UINT32 AuthenticationStatus, - IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL, - IN VOID *FileBuffer, - IN UINTN FileSize, - IN BOOLEAN BootPolicy + IN UINT32 AuthenticationOperation, + IN UINT32 AuthenticationStatus, + IN CONST EFI_DEVICE_PATH_PROTOCOL *File OPTIONAL, + IN VOID *FileBuffer, + IN UINTN FileSize, + IN BOOLEAN BootPolicy ) { - UINT32 Index; - EFI_STATUS Status; + UINT32 Index; + EFI_STATUS Status; // // Invalid case if File and FileBuffer are both NULL. // - if (File == NULL && FileBuffer == NULL) { + if ((File == NULL) && (FileBuffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -499,25 +506,26 @@ ExecuteSecurity2Handlers ( // // Run security handler in same order to their registered list // - for (Index = 0; Index < mNumberOfSecurity2Handler; Index ++) { + for (Index = 0; Index < mNumberOfSecurity2Handler; Index++) { // // If FileBuffer is not NULL, the input is Image, which will be handled by EFI_AUTH_IMAGE_OPERATION_MASK operation. // If FileBuffer is NULL, the input is not Image, which will be handled by EFI_AUTH_NONE_IMAGE_OPERATION_MASK operation. // Other cases are ignored. // - if ((FileBuffer != NULL && (mSecurity2Table[Index].Security2Operation & EFI_AUTH_IMAGE_OPERATION_MASK) != 0) || - (FileBuffer == NULL && (mSecurity2Table[Index].Security2Operation & EFI_AUTH_NONE_IMAGE_OPERATION_MASK) != 0)) { + if (((FileBuffer != NULL) && ((mSecurity2Table[Index].Security2Operation & EFI_AUTH_IMAGE_OPERATION_MASK) != 0)) || + ((FileBuffer == NULL) && ((mSecurity2Table[Index].Security2Operation & EFI_AUTH_NONE_IMAGE_OPERATION_MASK) != 0))) + { // // Execute registered handlers based on input AuthenticationOperation // if ((mSecurity2Table[Index].Security2Operation & AuthenticationOperation) != 0) { Status = mSecurity2Table[Index].Security2Handler ( - AuthenticationStatus, - File, - FileBuffer, - FileSize, - BootPolicy - ); + AuthenticationStatus, + File, + FileBuffer, + FileSize, + BootPolicy + ); if (EFI_ERROR (Status)) { return Status; } diff --git a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c index b262cf714f..ef949267fc 100644 --- a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c +++ b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.c @@ -6,17 +6,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "FileExplorer.h" -EFI_GUID FileExplorerGuid = EFI_FILE_EXPLORE_FORMSET_GUID; +EFI_GUID FileExplorerGuid = EFI_FILE_EXPLORE_FORMSET_GUID; /// /// File system selection menu /// -MENU_OPTION mFsOptionMenu = { +MENU_OPTION mFsOptionMenu = { MENU_OPTION_SIGNATURE, - {NULL}, + { NULL }, 0, FALSE }; @@ -43,34 +42,35 @@ HII_VENDOR_DEVICE_PATH FeHiiVendorDevicePath = { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, // // Will be replace with gEfiCallerIdGuid in code. // - { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } } + { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } + } }, { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (END_DEVICE_PATH_LENGTH), - (UINT8) ((END_DEVICE_PATH_LENGTH) >> 8) + (UINT8)(END_DEVICE_PATH_LENGTH), + (UINT8)((END_DEVICE_PATH_LENGTH) >> 8) } } }; VOID *mLibStartOpCodeHandle = NULL; -VOID *mLibEndOpCodeHandle = NULL; -EFI_IFR_GUID_LABEL *mLibStartLabel = NULL; -EFI_IFR_GUID_LABEL *mLibEndLabel = NULL; +VOID *mLibEndOpCodeHandle = NULL; +EFI_IFR_GUID_LABEL *mLibStartLabel = NULL; +EFI_IFR_GUID_LABEL *mLibEndLabel = NULL; UINT16 mQuestionIdUpdate; -CHAR16 mNewFileName[MAX_FILE_NAME_LEN]; -CHAR16 mNewFolderName[MAX_FOLDER_NAME_LEN]; -UINTN mNewFileQuestionId = NEW_FILE_QUESTION_ID_BASE; -UINTN mNewFolderQuestionId = NEW_FOLDER_QUESTION_ID_BASE; +CHAR16 mNewFileName[MAX_FILE_NAME_LEN]; +CHAR16 mNewFolderName[MAX_FOLDER_NAME_LEN]; +UINTN mNewFileQuestionId = NEW_FILE_QUESTION_ID_BASE; +UINTN mNewFolderQuestionId = NEW_FOLDER_QUESTION_ID_BASE; /** Create a new file or folder in current directory. @@ -82,8 +82,8 @@ UINTN mNewFolderQuestionId = NEW_FOLDER_QUESTION_ID_BASE; **/ EFI_STATUS LibCreateNewFile ( - IN CHAR16 *FileName, - IN BOOLEAN CreateFile + IN CHAR16 *FileName, + IN BOOLEAN CreateFile ); /** @@ -109,13 +109,13 @@ LibCreateNewFile ( EFI_STATUS EFIAPI LibExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { - if (Progress == NULL || Results == NULL) { + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } @@ -141,12 +141,12 @@ LibExtractConfig ( EFI_STATUS EFIAPI LibRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - if (Configuration == NULL || Progress == NULL) { + if ((Configuration == NULL) || (Progress == NULL)) { return EFI_INVALID_PARAMETER; } @@ -177,24 +177,24 @@ LibRouteConfig ( EFI_STATUS EFIAPI LibCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - EFI_STATUS Status; - BOOLEAN NeedExit; - CHAR16 *NewFileName; - CHAR16 *NewFolderName; + EFI_STATUS Status; + BOOLEAN NeedExit; + CHAR16 *NewFileName; + CHAR16 *NewFolderName; - NeedExit = TRUE; + NeedExit = TRUE; NewFileName = NULL; NewFolderName = NULL; - if (Action != EFI_BROWSER_ACTION_CHANGING && Action != EFI_BROWSER_ACTION_CHANGED) { + if ((Action != EFI_BROWSER_ACTION_CHANGING) && (Action != EFI_BROWSER_ACTION_CHANGED)) { // // Do nothing for other UEFI Action. Only do call back when data is changed. // @@ -209,13 +209,13 @@ LibCallback ( if (QuestionId == KEY_VALUE_CREATE_FILE_AND_EXIT) { *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; if (!IsZeroBuffer (mNewFileName, sizeof (mNewFileName))) { - Status = LibCreateNewFile (mNewFileName,TRUE); - ZeroMem (mNewFileName,sizeof (mNewFileName)); + Status = LibCreateNewFile (mNewFileName, TRUE); + ZeroMem (mNewFileName, sizeof (mNewFileName)); } } if (QuestionId == KEY_VALUE_NO_CREATE_FILE_AND_EXIT) { - ZeroMem (mNewFileName,sizeof (mNewFileName)); + ZeroMem (mNewFileName, sizeof (mNewFileName)); *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; } @@ -223,12 +223,12 @@ LibCallback ( *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; if (!IsZeroBuffer (mNewFolderName, sizeof (mNewFolderName))) { Status = LibCreateNewFile (mNewFolderName, FALSE); - ZeroMem (mNewFolderName,sizeof (mNewFolderName)); + ZeroMem (mNewFolderName, sizeof (mNewFolderName)); } } if (QuestionId == KEY_VALUE_NO_CREATE_FOLDER_AND_EXIT) { - ZeroMem (mNewFolderName,sizeof (mNewFolderName)); + ZeroMem (mNewFolderName, sizeof (mNewFolderName)); *ActionRequest = EFI_BROWSER_ACTION_REQUEST_EXIT; } @@ -255,7 +255,7 @@ LibCallback ( } if (QuestionId >= FILE_OPTION_OFFSET) { - LibGetDevicePath(QuestionId); + LibGetDevicePath (QuestionId); // // Process the extra action. @@ -272,8 +272,9 @@ LibCallback ( if (Value == NULL) { return EFI_INVALID_PARAMETER; } + if (QuestionId >= FILE_OPTION_OFFSET) { - LibGetDevicePath(QuestionId); + LibGetDevicePath (QuestionId); Status = LibUpdateFileExplorer (QuestionId); if (EFI_ERROR (Status)) { return Status; @@ -296,7 +297,7 @@ LibCreateMenuEntry ( VOID ) { - MENU_ENTRY *MenuEntry; + MENU_ENTRY *MenuEntry; // // Create new menu entry @@ -312,11 +313,10 @@ LibCreateMenuEntry ( return NULL; } - MenuEntry->Signature = MENU_ENTRY_SIGNATURE; + MenuEntry->Signature = MENU_ENTRY_SIGNATURE; return MenuEntry; } - /** Get the Menu Entry from the list in Menu Entry List. @@ -331,13 +331,13 @@ LibCreateMenuEntry ( **/ MENU_ENTRY * LibGetMenuEntry ( - MENU_OPTION *MenuOption, - UINTN MenuNumber + MENU_OPTION *MenuOption, + UINTN MenuNumber ) { - MENU_ENTRY *NewMenuEntry; - UINTN Index; - LIST_ENTRY *List; + MENU_ENTRY *NewMenuEntry; + UINTN Index; + LIST_ENTRY *List; ASSERT (MenuNumber < MenuOption->MenuNumber); @@ -359,12 +359,12 @@ LibGetMenuEntry ( **/ VOID LibDestroyMenuEntry ( - MENU_ENTRY *MenuEntry + MENU_ENTRY *MenuEntry ) { - FILE_CONTEXT *FileContext; + FILE_CONTEXT *FileContext; - FileContext = (FILE_CONTEXT *) MenuEntry->VariableContext; + FileContext = (FILE_CONTEXT *)MenuEntry->VariableContext; if (!FileContext->IsRoot) { if (FileContext->DevicePath != NULL) { @@ -385,6 +385,7 @@ LibDestroyMenuEntry ( if (MenuEntry->DisplayString != NULL) { FreePool (MenuEntry->DisplayString); } + if (MenuEntry->HelpString != NULL) { FreePool (MenuEntry->HelpString); } @@ -392,7 +393,6 @@ LibDestroyMenuEntry ( FreePool (MenuEntry); } - /** Free resources allocated in Allocate Rountine. @@ -400,10 +400,11 @@ LibDestroyMenuEntry ( **/ VOID LibFreeMenu ( - MENU_OPTION *FreeMenu + MENU_OPTION *FreeMenu ) { - MENU_ENTRY *MenuEntry; + MENU_ENTRY *MenuEntry; + while (!IsListEmpty (&FreeMenu->Head)) { MenuEntry = CR ( FreeMenu->Head.ForwardLink, @@ -414,6 +415,7 @@ LibFreeMenu ( RemoveEntryList (&MenuEntry->Link); LibDestroyMenuEntry (MenuEntry); } + FreeMenu->MenuNumber = 0; } @@ -428,12 +430,12 @@ LibFreeMenu ( **/ EFI_FILE_HANDLE LibOpenRoot ( - IN EFI_HANDLE DeviceHandle + IN EFI_HANDLE DeviceHandle ) { - EFI_STATUS Status; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume; - EFI_FILE_HANDLE File; + EFI_STATUS Status; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume; + EFI_FILE_HANDLE File; File = NULL; @@ -443,7 +445,7 @@ LibOpenRoot ( Status = gBS->HandleProtocol ( DeviceHandle, &gEfiSimpleFileSystemProtocolGuid, - (VOID *) &Volume + (VOID *)&Volume ); // @@ -451,10 +453,11 @@ LibOpenRoot ( // if (!EFI_ERROR (Status)) { Status = Volume->OpenVolume ( - Volume, - &File - ); + Volume, + &File + ); } + // // Done // @@ -471,12 +474,12 @@ LibOpenRoot ( **/ CHAR16 * LibDevicePathToStr ( - IN EFI_DEVICE_PATH_PROTOCOL *DevPath + IN EFI_DEVICE_PATH_PROTOCOL *DevPath ) { - EFI_STATUS Status; - CHAR16 *ToText; - EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; + EFI_STATUS Status; + CHAR16 *ToText; + EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *DevPathToText; if (DevPath == NULL) { return NULL; @@ -485,7 +488,7 @@ LibDevicePathToStr ( Status = gBS->LocateProtocol ( &gEfiDevicePathToTextProtocolGuid, NULL, - (VOID **) &DevPathToText + (VOID **)&DevPathToText ); ASSERT_EFI_ERROR (Status); ToText = DevPathToText->ConvertDevicePathToText ( @@ -509,14 +512,14 @@ LibDevicePathToStr ( **/ CHAR16 * LibStrDuplicate ( - IN CHAR16 *Src + IN CHAR16 *Src ) { CHAR16 *Dest; UINTN Size; - Size = StrSize (Src); - Dest = AllocateZeroPool (Size); + Size = StrSize (Src); + Dest = AllocateZeroPool (Size); ASSERT (Dest != NULL); if (Dest != NULL) { CopyMem (Dest, Src, Size); @@ -538,16 +541,16 @@ LibStrDuplicate ( **/ VOID * LibFileInfo ( - IN EFI_FILE_HANDLE FHand, - IN EFI_GUID *InfoType + IN EFI_FILE_HANDLE FHand, + IN EFI_GUID *InfoType ) { - EFI_STATUS Status; - EFI_FILE_INFO *Buffer; - UINTN BufferSize; + EFI_STATUS Status; + EFI_FILE_INFO *Buffer; + UINTN BufferSize; - Buffer = NULL; - BufferSize = 0; + Buffer = NULL; + BufferSize = 0; Status = FHand->GetInfo ( FHand, @@ -580,12 +583,12 @@ LibFileInfo ( @retval the file type string. **/ -CHAR16* +CHAR16 * LibGetTypeFromName ( - IN CHAR16 *FileName + IN CHAR16 *FileName ) { - UINTN Index; + UINTN Index; Index = StrLen (FileName) - 1; while ((FileName[Index] != L'.') && (Index != 0)) { @@ -607,11 +610,11 @@ LibToLowerString ( IN CHAR16 *String ) { - CHAR16 *TmpStr; + CHAR16 *TmpStr; for (TmpStr = String; *TmpStr != L'\0'; TmpStr++) { - if (*TmpStr >= L'A' && *TmpStr <= L'Z') { - *TmpStr = (CHAR16) (*TmpStr - L'A' + L'a'); + if ((*TmpStr >= L'A') && (*TmpStr <= L'Z')) { + *TmpStr = (CHAR16)(*TmpStr - L'A' + L'a'); } } } @@ -632,9 +635,9 @@ LibIsSupportedFileType ( IN UINT16 *FileName ) { - CHAR16 *InputFileType; - CHAR16 *TmpStr; - BOOLEAN IsSupported; + CHAR16 *InputFileType; + CHAR16 *TmpStr; + BOOLEAN IsSupported; if (gFileExplorerPrivate.FileType == NULL) { return TRUE; @@ -649,8 +652,8 @@ LibIsSupportedFileType ( } TmpStr = AllocateCopyPool (StrSize (InputFileType), InputFileType); - ASSERT(TmpStr != NULL); - LibToLowerString(TmpStr); + ASSERT (TmpStr != NULL); + LibToLowerString (TmpStr); IsSupported = (StrStr (gFileExplorerPrivate.FileType, TmpStr) == NULL ? FALSE : TRUE); @@ -689,12 +692,12 @@ LibAppendFileName ( // // Check overflow // - if (((MAX_UINTN - Size1) < Size2) || ((MAX_UINTN - Size1 - Size2) < sizeof(CHAR16))) { + if (((MAX_UINTN - Size1) < Size2) || ((MAX_UINTN - Size1 - Size2) < sizeof (CHAR16))) { return NULL; } MaxLen = (Size1 + Size2 + sizeof (CHAR16))/ sizeof (CHAR16); - Str = AllocateZeroPool (Size1 + Size2 + sizeof (CHAR16)); + Str = AllocateZeroPool (Size1 + Size2 + sizeof (CHAR16)); ASSERT (Str != NULL); TmpStr = AllocateZeroPool (Size1 + Size2 + sizeof (CHAR16)); @@ -710,7 +713,7 @@ LibAppendFileName ( Ptr = Str; LastSlash = Str; while (*Ptr != 0) { - if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '.' && *(Ptr + 3) == L'\\') { + if ((*Ptr == '\\') && (*(Ptr + 1) == '.') && (*(Ptr + 2) == '.') && (*(Ptr + 3) == L'\\')) { // // Convert "\Name\..\" to "\" // DO NOT convert the .. if it is at the end of the string. This will @@ -722,9 +725,9 @@ LibAppendFileName ( // that overlap. // StrCpyS (TmpStr, MaxLen, Ptr + 3); - StrCpyS (LastSlash, MaxLen - ((UINTN) LastSlash - (UINTN) Str) / sizeof (CHAR16), TmpStr); + StrCpyS (LastSlash, MaxLen - ((UINTN)LastSlash - (UINTN)Str) / sizeof (CHAR16), TmpStr); Ptr = LastSlash; - } else if (*Ptr == '\\' && *(Ptr + 1) == '.' && *(Ptr + 2) == '\\') { + } else if ((*Ptr == '\\') && (*(Ptr + 1) == '.') && (*(Ptr + 2) == '\\')) { // // Convert a "\.\" to a "\" // @@ -734,7 +737,7 @@ LibAppendFileName ( // that overlap. // StrCpyS (TmpStr, MaxLen, Ptr + 2); - StrCpyS (Ptr, MaxLen - ((UINTN) Ptr - (UINTN) Str) / sizeof (CHAR16), TmpStr); + StrCpyS (Ptr, MaxLen - ((UINTN)Ptr - (UINTN)Str) / sizeof (CHAR16), TmpStr); Ptr = LastSlash; } else if (*Ptr == '\\') { LastSlash = Ptr; @@ -763,15 +766,15 @@ LibFindFileSystem ( VOID ) { - UINTN NoSimpleFsHandles; - EFI_HANDLE *SimpleFsHandle; - UINT16 *VolumeLabel; - UINTN Index; - EFI_STATUS Status; - MENU_ENTRY *MenuEntry; - FILE_CONTEXT *FileContext; - UINTN OptionNumber; - EFI_FILE_SYSTEM_VOLUME_LABEL *Info; + UINTN NoSimpleFsHandles; + EFI_HANDLE *SimpleFsHandle; + UINT16 *VolumeLabel; + UINTN Index; + EFI_STATUS Status; + MENU_ENTRY *MenuEntry; + FILE_CONTEXT *FileContext; + UINTN OptionNumber; + EFI_FILE_SYSTEM_VOLUME_LABEL *Info; NoSimpleFsHandles = 0; OptionNumber = 0; @@ -800,24 +803,24 @@ LibFindFileSystem ( return EFI_OUT_OF_RESOURCES; } - FileContext = (FILE_CONTEXT *) MenuEntry->VariableContext; + FileContext = (FILE_CONTEXT *)MenuEntry->VariableContext; FileContext->DeviceHandle = SimpleFsHandle[Index]; - FileContext->FileHandle = LibOpenRoot (FileContext->DeviceHandle); + FileContext->FileHandle = LibOpenRoot (FileContext->DeviceHandle); if (FileContext->FileHandle == NULL) { LibDestroyMenuEntry (MenuEntry); continue; } - MenuEntry->HelpString = LibDevicePathToStr (DevicePathFromHandle (FileContext->DeviceHandle)); - FileContext->FileName = LibStrDuplicate (L"\\"); + MenuEntry->HelpString = LibDevicePathToStr (DevicePathFromHandle (FileContext->DeviceHandle)); + FileContext->FileName = LibStrDuplicate (L"\\"); FileContext->DevicePath = FileDevicePath (FileContext->DeviceHandle, FileContext->FileName); - FileContext->IsDir = TRUE; - FileContext->IsRoot = TRUE; + FileContext->IsDir = TRUE; + FileContext->IsRoot = TRUE; // // Get current file system's Volume Label // - Info = (EFI_FILE_SYSTEM_VOLUME_LABEL *) LibFileInfo (FileContext->FileHandle, &gEfiFileSystemVolumeLabelInfoIdGuid); + Info = (EFI_FILE_SYSTEM_VOLUME_LABEL *)LibFileInfo (FileContext->FileHandle, &gEfiFileSystemVolumeLabelInfoIdGuid); if (Info == NULL) { VolumeLabel = L"NO FILE SYSTEM INFO"; } else { @@ -826,7 +829,8 @@ LibFindFileSystem ( VolumeLabel = L"NO VOLUME LABEL"; } } - MenuEntry->DisplayString = AllocateZeroPool (MAX_CHAR); + + MenuEntry->DisplayString = AllocateZeroPool (MAX_CHAR); ASSERT (MenuEntry->DisplayString != NULL); UnicodeSPrint ( MenuEntry->DisplayString, @@ -836,14 +840,15 @@ LibFindFileSystem ( MenuEntry->HelpString ); MenuEntry->DisplayStringToken = HiiSetString ( - gFileExplorerPrivate.FeHiiHandle, - 0, - MenuEntry->DisplayString, - NULL - ); + gFileExplorerPrivate.FeHiiHandle, + 0, + MenuEntry->DisplayString, + NULL + ); - if (Info != NULL) + if (Info != NULL) { FreePool (Info); + } OptionNumber++; InsertTailList (&gFileExplorerPrivate.FsOptionMenu->Head, &MenuEntry->Link); @@ -870,17 +875,17 @@ LibFindFileSystem ( **/ EFI_STATUS LibGetFileHandleFromMenu ( - IN MENU_ENTRY *MenuEntry, - OUT EFI_FILE_HANDLE *RetFileHandle + IN MENU_ENTRY *MenuEntry, + OUT EFI_FILE_HANDLE *RetFileHandle ) { - EFI_FILE_HANDLE Dir; - EFI_FILE_HANDLE NewDir; - FILE_CONTEXT *FileContext; - EFI_STATUS Status; + EFI_FILE_HANDLE Dir; + EFI_FILE_HANDLE NewDir; + FILE_CONTEXT *FileContext; + EFI_STATUS Status; - FileContext = (FILE_CONTEXT *) MenuEntry->VariableContext; - Dir = FileContext->FileHandle; + FileContext = (FILE_CONTEXT *)MenuEntry->VariableContext; + Dir = FileContext->FileHandle; // // Open current directory to get files from it @@ -924,14 +929,14 @@ LibGetFileHandleFromDevicePath ( OUT EFI_HANDLE *DeviceHandle ) { - EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePathNode; - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume; - EFI_FILE_HANDLE FileHandle; - EFI_FILE_HANDLE LastHandle; - CHAR16 *TempPath; + EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePathNode; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Volume; + EFI_FILE_HANDLE FileHandle; + EFI_FILE_HANDLE LastHandle; + CHAR16 *TempPath; *ParentFileName = NULL; @@ -939,12 +944,12 @@ LibGetFileHandleFromDevicePath ( // Attempt to access the file via a file system interface // DevicePathNode = RootDirectory; - Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &DevicePathNode, &Handle); + Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &DevicePathNode, &Handle); if (EFI_ERROR (Status)) { return Status; } - Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID**)&Volume); + Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Volume); if (EFI_ERROR (Status)) { return Status; } @@ -959,9 +964,9 @@ LibGetFileHandleFromDevicePath ( *DeviceHandle = Handle; - if (IsDevicePathEnd(DevicePathNode)) { + if (IsDevicePathEnd (DevicePathNode)) { *ParentFileName = AllocateCopyPool (StrSize (L"\\"), L"\\"); - *RetFileHandle = FileHandle; + *RetFileHandle = FileHandle; return EFI_SUCCESS; } @@ -972,7 +977,6 @@ LibGetFileHandleFromDevicePath ( // TempDevicePathNode = DuplicateDevicePath (DevicePathNode); if (TempDevicePathNode == NULL) { - // // Setting Status to an EFI_ERROR value will cause the rest of // the file system support below to be skipped. @@ -988,8 +992,9 @@ LibGetFileHandleFromDevicePath ( // DevicePathNode = TempDevicePathNode; while (!EFI_ERROR (Status) && !IsDevicePathEnd (DevicePathNode)) { - if (DevicePathType (DevicePathNode) != MEDIA_DEVICE_PATH || - DevicePathSubType (DevicePathNode) != MEDIA_FILEPATH_DP) { + if ((DevicePathType (DevicePathNode) != MEDIA_DEVICE_PATH) || + (DevicePathSubType (DevicePathNode) != MEDIA_FILEPATH_DP)) + { Status = EFI_UNSUPPORTED; goto Done; } @@ -998,21 +1003,22 @@ LibGetFileHandleFromDevicePath ( FileHandle = NULL; Status = LastHandle->Open ( - LastHandle, - &FileHandle, - ((FILEPATH_DEVICE_PATH *) DevicePathNode)->PathName, - EFI_FILE_MODE_READ, - 0 - ); + LastHandle, + &FileHandle, + ((FILEPATH_DEVICE_PATH *)DevicePathNode)->PathName, + EFI_FILE_MODE_READ, + 0 + ); if (*ParentFileName == NULL) { - *ParentFileName = AllocateCopyPool (StrSize (((FILEPATH_DEVICE_PATH *) DevicePathNode)->PathName), ((FILEPATH_DEVICE_PATH *) DevicePathNode)->PathName); + *ParentFileName = AllocateCopyPool (StrSize (((FILEPATH_DEVICE_PATH *)DevicePathNode)->PathName), ((FILEPATH_DEVICE_PATH *)DevicePathNode)->PathName); } else { - TempPath = LibAppendFileName (*ParentFileName, ((FILEPATH_DEVICE_PATH *) DevicePathNode)->PathName); + TempPath = LibAppendFileName (*ParentFileName, ((FILEPATH_DEVICE_PATH *)DevicePathNode)->PathName); if (TempPath == NULL) { LastHandle->Close (LastHandle); Status = EFI_OUT_OF_RESOURCES; goto Done; } + FreePool (*ParentFileName); *ParentFileName = TempPath; } @@ -1055,45 +1061,46 @@ Done: **/ EFI_STATUS LibCreateNewFile ( - IN CHAR16 *FileName, - IN BOOLEAN CreateFile + IN CHAR16 *FileName, + IN BOOLEAN CreateFile ) { - EFI_FILE_HANDLE FileHandle; - EFI_FILE_HANDLE NewHandle; - EFI_HANDLE DeviceHandle; - EFI_STATUS Status; - CHAR16 *ParentName; - CHAR16 *FullFileName; - - NewHandle = NULL; + EFI_FILE_HANDLE FileHandle; + EFI_FILE_HANDLE NewHandle; + EFI_HANDLE DeviceHandle; + EFI_STATUS Status; + CHAR16 *ParentName; + CHAR16 *FullFileName; + + NewHandle = NULL; FullFileName = NULL; - LibGetFileHandleFromDevicePath(gFileExplorerPrivate.RetDevicePath, &FileHandle, &ParentName, &DeviceHandle); + LibGetFileHandleFromDevicePath (gFileExplorerPrivate.RetDevicePath, &FileHandle, &ParentName, &DeviceHandle); FullFileName = LibAppendFileName (ParentName, FileName); if (FullFileName == NULL) { return EFI_OUT_OF_RESOURCES; } + if (CreateFile) { - Status = FileHandle->Open( - FileHandle, - &NewHandle, - FullFileName, - EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE| EFI_FILE_MODE_CREATE, - 0 - ); + Status = FileHandle->Open ( + FileHandle, + &NewHandle, + FullFileName, + EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE| EFI_FILE_MODE_CREATE, + 0 + ); if (EFI_ERROR (Status)) { FileHandle->Close (FileHandle); return Status; } } else { - Status = FileHandle->Open( - FileHandle, - &NewHandle, - FullFileName, - EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE| EFI_FILE_MODE_CREATE, - EFI_FILE_DIRECTORY - ); + Status = FileHandle->Open ( + FileHandle, + &NewHandle, + FullFileName, + EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE| EFI_FILE_MODE_CREATE, + EFI_FILE_DIRECTORY + ); if (EFI_ERROR (Status)) { FileHandle->Close (FileHandle); return Status; @@ -1108,7 +1115,6 @@ LibCreateNewFile ( gFileExplorerPrivate.RetDevicePath = FileDevicePath (DeviceHandle, FullFileName); return EFI_SUCCESS; - } /** @@ -1127,19 +1133,19 @@ LibCreateNewFile ( **/ EFI_STATUS LibFindFiles ( - IN EFI_FILE_HANDLE FileHandle, - IN UINT16 *FileName, - IN EFI_HANDLE DeviceHandle + IN EFI_FILE_HANDLE FileHandle, + IN UINT16 *FileName, + IN EFI_HANDLE DeviceHandle ) { - EFI_FILE_INFO *DirInfo; - UINTN BufferSize; - UINTN DirBufferSize; - MENU_ENTRY *NewMenuEntry; - FILE_CONTEXT *NewFileContext; - UINTN Pass; - EFI_STATUS Status; - UINTN OptionNumber; + EFI_FILE_INFO *DirInfo; + UINTN BufferSize; + UINTN DirBufferSize; + MENU_ENTRY *NewMenuEntry; + FILE_CONTEXT *NewFileContext; + UINTN Pass; + EFI_STATUS Status; + UINTN OptionNumber; OptionNumber = 0; @@ -1157,17 +1163,18 @@ LibFindFiles ( Status = EFI_SUCCESS; for (Pass = 1; Pass <= 2; Pass++) { FileHandle->SetPosition (FileHandle, 0); - for (;;) { - BufferSize = DirBufferSize; - Status = FileHandle->Read (FileHandle, &BufferSize, DirInfo); - if (EFI_ERROR (Status) || BufferSize == 0) { + for ( ; ;) { + BufferSize = DirBufferSize; + Status = FileHandle->Read (FileHandle, &BufferSize, DirInfo); + if (EFI_ERROR (Status) || (BufferSize == 0)) { Status = EFI_SUCCESS; break; } - if (((DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0 && Pass == 2) || - ((DirInfo->Attribute & EFI_FILE_DIRECTORY) == 0 && Pass == 1) - ) { + if ((((DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0) && (Pass == 2)) || + (((DirInfo->Attribute & EFI_FILE_DIRECTORY) == 0) && (Pass == 1)) + ) + { // // Pass 1 is for Directories // Pass 2 is for file names @@ -1175,7 +1182,7 @@ LibFindFiles ( continue; } - if (!((DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0 || LibIsSupportedFileType (DirInfo->FileName))) { + if (!(((DirInfo->Attribute & EFI_FILE_DIRECTORY) != 0) || LibIsSupportedFileType (DirInfo->FileName))) { // // Slip file unless it is a directory entry or a .EFI file // @@ -1188,21 +1195,22 @@ LibFindFiles ( goto Done; } - NewFileContext = (FILE_CONTEXT *) NewMenuEntry->VariableContext; + NewFileContext = (FILE_CONTEXT *)NewMenuEntry->VariableContext; NewFileContext->DeviceHandle = DeviceHandle; - NewFileContext->FileName = LibAppendFileName (FileName, DirInfo->FileName); - if (NewFileContext->FileName == NULL) { + NewFileContext->FileName = LibAppendFileName (FileName, DirInfo->FileName); + if (NewFileContext->FileName == NULL) { LibDestroyMenuEntry (NewMenuEntry); Status = EFI_OUT_OF_RESOURCES; goto Done; } + NewFileContext->FileHandle = FileHandle; NewFileContext->DevicePath = FileDevicePath (NewFileContext->DeviceHandle, NewFileContext->FileName); - NewMenuEntry->HelpString = NULL; - NewFileContext->IsDir = (BOOLEAN) ((DirInfo->Attribute & EFI_FILE_DIRECTORY) == EFI_FILE_DIRECTORY); + NewMenuEntry->HelpString = NULL; + NewFileContext->IsDir = (BOOLEAN)((DirInfo->Attribute & EFI_FILE_DIRECTORY) == EFI_FILE_DIRECTORY); if (NewFileContext->IsDir) { - BufferSize = StrLen (DirInfo->FileName) * 2 + 6; + BufferSize = StrLen (DirInfo->FileName) * 2 + 6; NewMenuEntry->DisplayString = AllocateZeroPool (BufferSize); UnicodeSPrint ( NewMenuEntry->DisplayString, @@ -1221,7 +1229,7 @@ LibFindFiles ( NULL ); - NewFileContext->IsRoot = FALSE; + NewFileContext->IsRoot = FALSE; OptionNumber++; InsertTailList (&gFileExplorerPrivate.FsOptionMenu->Head, &NewMenuEntry->Link); @@ -1252,6 +1260,7 @@ LibRefreshUpdateData ( if (mLibStartOpCodeHandle != NULL) { HiiFreeOpCodeHandle (mLibStartOpCodeHandle); } + if (mLibEndOpCodeHandle != NULL) { HiiFreeOpCodeHandle (mLibEndOpCodeHandle); } @@ -1260,17 +1269,17 @@ LibRefreshUpdateData ( // Create new OpCode Handle // mLibStartOpCodeHandle = HiiAllocateOpCodeHandle (); - mLibEndOpCodeHandle = HiiAllocateOpCodeHandle (); + mLibEndOpCodeHandle = HiiAllocateOpCodeHandle (); // // Create Hii Extend Label OpCode as the start opcode // - mLibStartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode ( - mLibStartOpCodeHandle, - &gEfiIfrTianoGuid, - NULL, - sizeof (EFI_IFR_GUID_LABEL) - ); + mLibStartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode ( + mLibStartOpCodeHandle, + &gEfiIfrTianoGuid, + NULL, + sizeof (EFI_IFR_GUID_LABEL) + ); mLibStartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; mLibStartLabel->Number = FORM_FILE_EXPLORER_ID; @@ -1278,7 +1287,7 @@ LibRefreshUpdateData ( // // Create Hii Extend Label OpCode as the start opcode // - mLibEndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode ( + mLibEndLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode ( mLibEndOpCodeHandle, &gEfiIfrTianoGuid, NULL, @@ -1299,15 +1308,15 @@ LibUpdateFileExplorePage ( VOID ) { - UINTN Index; - MENU_ENTRY *NewMenuEntry; - FILE_CONTEXT *NewFileContext; - MENU_OPTION *MenuOption; - BOOLEAN CreateNewFile; + UINTN Index; + MENU_ENTRY *NewMenuEntry; + FILE_CONTEXT *NewFileContext; + MENU_OPTION *MenuOption; + BOOLEAN CreateNewFile; - NewMenuEntry = NULL; - NewFileContext = NULL; - CreateNewFile = FALSE; + NewMenuEntry = NULL; + NewFileContext = NULL; + CreateNewFile = FALSE; LibRefreshUpdateData (); MenuOption = gFileExplorerPrivate.FsOptionMenu; @@ -1315,8 +1324,8 @@ LibUpdateFileExplorePage ( mQuestionIdUpdate += QUESTION_ID_UPDATE_STEP; for (Index = 0; Index < MenuOption->MenuNumber; Index++) { - NewMenuEntry = LibGetMenuEntry (MenuOption, Index); - NewFileContext = (FILE_CONTEXT *) NewMenuEntry->VariableContext; + NewMenuEntry = LibGetMenuEntry (MenuOption, Index); + NewFileContext = (FILE_CONTEXT *)NewMenuEntry->VariableContext; if (!NewFileContext->IsRoot && !CreateNewFile) { HiiCreateGotoOpCode ( @@ -1325,7 +1334,7 @@ LibUpdateFileExplorePage ( STRING_TOKEN (STR_NEW_FILE), STRING_TOKEN (STR_NEW_FILE_HELP), EFI_IFR_FLAG_CALLBACK, - (UINT16) (mNewFileQuestionId++) + (UINT16)(mNewFileQuestionId++) ); HiiCreateGotoOpCode ( mLibStartOpCodeHandle, @@ -1333,9 +1342,9 @@ LibUpdateFileExplorePage ( STRING_TOKEN (STR_NEW_FOLDER), STRING_TOKEN (STR_NEW_FOLDER_HELP), EFI_IFR_FLAG_CALLBACK, - (UINT16) (mNewFolderQuestionId++) + (UINT16)(mNewFolderQuestionId++) ); - HiiCreateTextOpCode( + HiiCreateTextOpCode ( mLibStartOpCodeHandle, STRING_TOKEN (STR_NULL_STRING), STRING_TOKEN (STR_NULL_STRING), @@ -1350,7 +1359,7 @@ LibUpdateFileExplorePage ( // HiiCreateActionOpCode ( mLibStartOpCodeHandle, - (UINT16) (FILE_OPTION_OFFSET + Index + mQuestionIdUpdate), + (UINT16)(FILE_OPTION_OFFSET + Index + mQuestionIdUpdate), NewMenuEntry->DisplayStringToken, STRING_TOKEN (STR_NULL_STRING), EFI_IFR_FLAG_CALLBACK, @@ -1366,7 +1375,7 @@ LibUpdateFileExplorePage ( NewMenuEntry->DisplayStringToken, STRING_TOKEN (STR_NULL_STRING), EFI_IFR_FLAG_CALLBACK, - (UINT16) (FILE_OPTION_OFFSET + Index + mQuestionIdUpdate) + (UINT16)(FILE_OPTION_OFFSET + Index + mQuestionIdUpdate) ); } } @@ -1391,19 +1400,19 @@ LibUpdateFileExplorePage ( **/ EFI_STATUS LibUpdateFileExplorer ( - IN UINT16 KeyValue + IN UINT16 KeyValue ) { - UINT16 FileOptionMask; - MENU_ENTRY *NewMenuEntry; - FILE_CONTEXT *NewFileContext; - EFI_STATUS Status; - EFI_FILE_HANDLE FileHandle; - - Status = EFI_SUCCESS; - FileOptionMask = (UINT16) (FILE_OPTION_MASK & KeyValue) - mQuestionIdUpdate; + UINT16 FileOptionMask; + MENU_ENTRY *NewMenuEntry; + FILE_CONTEXT *NewFileContext; + EFI_STATUS Status; + EFI_FILE_HANDLE FileHandle; + + Status = EFI_SUCCESS; + FileOptionMask = (UINT16)(FILE_OPTION_MASK & KeyValue) - mQuestionIdUpdate; NewMenuEntry = LibGetMenuEntry (gFileExplorerPrivate.FsOptionMenu, FileOptionMask); - NewFileContext = (FILE_CONTEXT *) NewMenuEntry->VariableContext; + NewFileContext = (FILE_CONTEXT *)NewMenuEntry->VariableContext; if (NewFileContext->IsDir) { RemoveEntryList (&NewMenuEntry->Link); @@ -1417,6 +1426,7 @@ LibUpdateFileExplorer ( LibFreeMenu (gFileExplorerPrivate.FsOptionMenu); } } + LibDestroyMenuEntry (NewMenuEntry); } @@ -1431,22 +1441,23 @@ LibUpdateFileExplorer ( **/ VOID LibGetDevicePath ( - IN UINT16 KeyValue + IN UINT16 KeyValue ) { - UINT16 FileOptionMask; - MENU_ENTRY *NewMenuEntry; - FILE_CONTEXT *NewFileContext; + UINT16 FileOptionMask; + MENU_ENTRY *NewMenuEntry; + FILE_CONTEXT *NewFileContext; - FileOptionMask = (UINT16) (FILE_OPTION_MASK & KeyValue) - mQuestionIdUpdate; + FileOptionMask = (UINT16)(FILE_OPTION_MASK & KeyValue) - mQuestionIdUpdate; NewMenuEntry = LibGetMenuEntry (gFileExplorerPrivate.FsOptionMenu, FileOptionMask); - NewFileContext = (FILE_CONTEXT *) NewMenuEntry->VariableContext; + NewFileContext = (FILE_CONTEXT *)NewMenuEntry->VariableContext; if (gFileExplorerPrivate.RetDevicePath != NULL) { FreePool (gFileExplorerPrivate.RetDevicePath); } + gFileExplorerPrivate.RetDevicePath = DuplicateDevicePath (NewFileContext->DevicePath); } @@ -1478,57 +1489,58 @@ ChooseFile ( OUT EFI_DEVICE_PATH_PROTOCOL **File OPTIONAL ) { - EFI_FILE_HANDLE FileHandle; - EFI_STATUS Status; - UINT16 *FileName; - EFI_HANDLE DeviceHandle; + EFI_FILE_HANDLE FileHandle; + EFI_STATUS Status; + UINT16 *FileName; + EFI_HANDLE DeviceHandle; if ((ChooseHandler == NULL) && (File == NULL)) { return EFI_INVALID_PARAMETER; } mQuestionIdUpdate = 0; - FileName = NULL; + FileName = NULL; gFileExplorerPrivate.RetDevicePath = NULL; gFileExplorerPrivate.ChooseHandler = ChooseHandler; if (FileType != NULL) { gFileExplorerPrivate.FileType = AllocateCopyPool (StrSize (FileType), FileType); - ASSERT(gFileExplorerPrivate.FileType != NULL); - LibToLowerString(gFileExplorerPrivate.FileType); + ASSERT (gFileExplorerPrivate.FileType != NULL); + LibToLowerString (gFileExplorerPrivate.FileType); } else { gFileExplorerPrivate.FileType = NULL; } if (RootDirectory == NULL) { - Status = LibFindFileSystem(); + Status = LibFindFileSystem (); } else { - Status = LibGetFileHandleFromDevicePath(RootDirectory, &FileHandle, &FileName, &DeviceHandle); + Status = LibGetFileHandleFromDevicePath (RootDirectory, &FileHandle, &FileName, &DeviceHandle); if (EFI_ERROR (Status)) { goto Done; } Status = LibFindFiles (FileHandle, FileName, DeviceHandle); } + if (EFI_ERROR (Status)) { goto Done; } - LibUpdateFileExplorePage(); + LibUpdateFileExplorePage (); gFileExplorerPrivate.FormBrowser2->SendForm ( - gFileExplorerPrivate.FormBrowser2, - &gFileExplorerPrivate.FeHiiHandle, - 1, - &FileExplorerGuid, - 0, - NULL, - NULL - ); + gFileExplorerPrivate.FormBrowser2, + &gFileExplorerPrivate.FeHiiHandle, + 1, + &FileExplorerGuid, + 0, + NULL, + NULL + ); Done: if ((Status == EFI_SUCCESS) && (File != NULL)) { - *File = gFileExplorerPrivate.RetDevicePath; + *File = gFileExplorerPrivate.RetDevicePath; } else if (gFileExplorerPrivate.RetDevicePath != NULL) { FreePool (gFileExplorerPrivate.RetDevicePath); } @@ -1559,13 +1571,13 @@ Done: EFI_STATUS EFIAPI FileExplorerLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; - gHiiVendorDevicePath = (HII_VENDOR_DEVICE_PATH*) DuplicateDevicePath ((EFI_DEVICE_PATH_PROTOCOL*)&FeHiiVendorDevicePath); + gHiiVendorDevicePath = (HII_VENDOR_DEVICE_PATH *)DuplicateDevicePath ((EFI_DEVICE_PATH_PROTOCOL *)&FeHiiVendorDevicePath); ASSERT (gHiiVendorDevicePath != NULL); CopyGuid (&gHiiVendorDevicePath->VendorDevicePath.Guid, &gEfiCallerIdGuid); @@ -1583,6 +1595,7 @@ FileExplorerLibConstructor ( if (Status == EFI_ALREADY_STARTED) { return EFI_SUCCESS; } + if (EFI_ERROR (Status)) { return Status; } @@ -1591,18 +1604,18 @@ FileExplorerLibConstructor ( // Post our File Explorer VFR binary to the HII database. // gFileExplorerPrivate.FeHiiHandle = HiiAddPackages ( - &FileExplorerGuid, - gFileExplorerPrivate.FeDriverHandle, - FileExplorerVfrBin, - FileExplorerLibStrings, - NULL - ); + &FileExplorerGuid, + gFileExplorerPrivate.FeDriverHandle, + FileExplorerVfrBin, + FileExplorerLibStrings, + NULL + ); ASSERT (gFileExplorerPrivate.FeHiiHandle != NULL); // // Locate Formbrowser2 protocol // - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &gFileExplorerPrivate.FormBrowser2); + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&gFileExplorerPrivate.FormBrowser2); ASSERT_EFI_ERROR (Status); InitializeListHead (&gFileExplorerPrivate.FsOptionMenu->Head); @@ -1621,11 +1634,11 @@ FileExplorerLibConstructor ( EFI_STATUS EFIAPI FileExplorerLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (gHiiVendorDevicePath != NULL); diff --git a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.h b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.h index cc84c2a654..c7587c166b 100644 --- a/MdeModulePkg/Library/FileExplorerLib/FileExplorer.h +++ b/MdeModulePkg/Library/FileExplorerLib/FileExplorer.h @@ -32,8 +32,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "FormGuid.h" -#define FILE_EXPLORER_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('f', 'e', 'c', 'k') - +#define FILE_EXPLORER_CALLBACK_DATA_SIGNATURE SIGNATURE_32 ('f', 'e', 'c', 'k') #pragma pack(1) @@ -41,77 +40,76 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// HII specific Vendor Device Path definition. /// typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; #pragma pack() typedef struct { - EFI_HANDLE DeviceHandle; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - EFI_FILE_HANDLE FileHandle; - UINT16 *FileName; + EFI_HANDLE DeviceHandle; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_FILE_HANDLE FileHandle; + UINT16 *FileName; - BOOLEAN IsRoot; - BOOLEAN IsDir; + BOOLEAN IsRoot; + BOOLEAN IsDir; } FILE_CONTEXT; typedef struct { - UINTN Signature; - LIST_ENTRY Link; - UINT16 *DisplayString; - UINT16 *HelpString; - EFI_STRING_ID DisplayStringToken; - EFI_STRING_ID HelpStringToken; - VOID *VariableContext; + UINTN Signature; + LIST_ENTRY Link; + UINT16 *DisplayString; + UINT16 *HelpString; + EFI_STRING_ID DisplayStringToken; + EFI_STRING_ID HelpStringToken; + VOID *VariableContext; } MENU_ENTRY; typedef struct { - UINTN Signature; - LIST_ENTRY Head; - UINTN MenuNumber; - BOOLEAN Used; + UINTN Signature; + LIST_ENTRY Head; + UINTN MenuNumber; + BOOLEAN Used; } MENU_OPTION; typedef struct { // // Shared callback data. // - UINTN Signature; + UINTN Signature; // // File explorer formset callback data. // - EFI_HII_HANDLE FeHiiHandle; - EFI_HANDLE FeDriverHandle; - EFI_HII_CONFIG_ACCESS_PROTOCOL FeConfigAccess; - EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; - MENU_OPTION *FsOptionMenu; - CHAR16 *FileType; - CHOOSE_HANDLER ChooseHandler; - EFI_DEVICE_PATH_PROTOCOL *RetDevicePath; - + EFI_HII_HANDLE FeHiiHandle; + EFI_HANDLE FeDriverHandle; + EFI_HII_CONFIG_ACCESS_PROTOCOL FeConfigAccess; + EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; + MENU_OPTION *FsOptionMenu; + CHAR16 *FileType; + CHOOSE_HANDLER ChooseHandler; + EFI_DEVICE_PATH_PROTOCOL *RetDevicePath; } FILE_EXPLORER_CALLBACK_DATA; #define FILE_EXPLORER_PRIVATE_FROM_THIS(a) CR (a, FILE_EXPLORER_CALLBACK_DATA, FeConfigAccess, FILE_EXPLORER_CALLBACK_DATA_SIGNATURE) -extern UINT8 FileExplorerVfrBin[]; +extern UINT8 FileExplorerVfrBin[]; -#define MENU_OPTION_SIGNATURE SIGNATURE_32 ('m', 'e', 'n', 'u') -#define MENU_ENTRY_SIGNATURE SIGNATURE_32 ('e', 'n', 't', 'r') +#define MENU_OPTION_SIGNATURE SIGNATURE_32 ('m', 'e', 'n', 'u') +#define MENU_ENTRY_SIGNATURE SIGNATURE_32 ('e', 'n', 't', 'r') /// /// Define the maximum characters that will be accepted. /// -#define MAX_CHAR 480 -#define FILE_OPTION_OFFSET 0x8000 -#define FILE_OPTION_MASK 0x7FFF -#define QUESTION_ID_UPDATE_STEP 200 -#define MAX_FILE_NAME_LEN 20 -#define MAX_FOLDER_NAME_LEN 20 -#define NEW_FILE_QUESTION_ID_BASE 0x5000; -#define NEW_FOLDER_QUESTION_ID_BASE 0x6000; +#define MAX_CHAR 480 +#define FILE_OPTION_OFFSET 0x8000 +#define FILE_OPTION_MASK 0x7FFF +#define QUESTION_ID_UPDATE_STEP 200 +#define MAX_FILE_NAME_LEN 20 +#define MAX_FOLDER_NAME_LEN 20 +#define NEW_FILE_QUESTION_ID_BASE 0x5000; +#define NEW_FOLDER_QUESTION_ID_BASE 0x6000; /** This function processes the results of changes in configuration. @@ -143,15 +141,14 @@ extern UINT8 FileExplorerVfrBin[]; EFI_STATUS EFIAPI LibCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ); - /** This function allows a caller to extract the current configuration for one or more named elements from the target driver. @@ -177,10 +174,10 @@ LibCallback ( EFI_STATUS EFIAPI LibExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ); /** @@ -202,9 +199,9 @@ LibExtractConfig ( EFI_STATUS EFIAPI LibRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ); /** @@ -218,10 +215,9 @@ LibRouteConfig ( **/ EFI_STATUS LibUpdateFileExplorer ( - IN UINT16 KeyValue + IN UINT16 KeyValue ); - /** Get the device path info saved in the menu structure. @@ -230,7 +226,7 @@ LibUpdateFileExplorer ( **/ VOID LibGetDevicePath ( - IN UINT16 KeyValue + IN UINT16 KeyValue ); #endif diff --git a/MdeModulePkg/Library/FileExplorerLib/FormGuid.h b/MdeModulePkg/Library/FileExplorerLib/FormGuid.h index a084a50b3b..52a34dc283 100644 --- a/MdeModulePkg/Library/FileExplorerLib/FormGuid.h +++ b/MdeModulePkg/Library/FileExplorerLib/FormGuid.h @@ -6,11 +6,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #ifndef _FILE_EXPLORER_FORM_GUID_H_ #define _FILE_EXPLORER_FORM_GUID_H_ - #define EFI_FILE_EXPLORE_FORMSET_GUID \ { \ 0xfe561596, 0xe6bf, 0x41a6, {0x83, 0x76, 0xc7, 0x2b, 0x71, 0x98, 0x74, 0xd0} \ @@ -26,7 +24,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define KEY_VALUE_CREATE_FOLDER_AND_EXIT 0x3002 #define KEY_VALUE_NO_CREATE_FOLDER_AND_EXIT 0x3003 -#define LABEL_END 0xffff +#define LABEL_END 0xffff #endif - diff --git a/MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.c b/MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.c index 533e1ea5ac..6b205a9715 100644 --- a/MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.c +++ b/MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.c @@ -55,6 +55,6 @@ AuthenticateFmpImage ( IN UINTN PublicKeyDataLength ) { - ASSERT(FALSE); + ASSERT (FALSE); return RETURN_UNSUPPORTED; } diff --git a/MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.c b/MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.c index 3731c3f34a..432577bcfd 100644 --- a/MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.c +++ b/MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.c @@ -15,23 +15,23 @@ #include struct FRAME_BUFFER_CONFIGURE { - UINT32 PixelsPerScanLine; - UINT32 BytesPerPixel; - UINT32 Width; - UINT32 Height; - UINT8 *FrameBuffer; - EFI_GRAPHICS_PIXEL_FORMAT PixelFormat; - EFI_PIXEL_BITMASK PixelMasks; - INT8 PixelShl[4]; // R-G-B-Rsvd - INT8 PixelShr[4]; // R-G-B-Rsvd - UINT8 LineBuffer[0]; + UINT32 PixelsPerScanLine; + UINT32 BytesPerPixel; + UINT32 Width; + UINT32 Height; + UINT8 *FrameBuffer; + EFI_GRAPHICS_PIXEL_FORMAT PixelFormat; + EFI_PIXEL_BITMASK PixelMasks; + INT8 PixelShl[4]; // R-G-B-Rsvd + INT8 PixelShr[4]; // R-G-B-Rsvd + UINT8 LineBuffer[0]; }; -CONST EFI_PIXEL_BITMASK mRgbPixelMasks = { +CONST EFI_PIXEL_BITMASK mRgbPixelMasks = { 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 }; -CONST EFI_PIXEL_BITMASK mBgrPixelMasks = { +CONST EFI_PIXEL_BITMASK mBgrPixelMasks = { 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 }; @@ -45,10 +45,10 @@ CONST EFI_PIXEL_BITMASK mBgrPixelMasks = { **/ VOID FrameBufferBltLibConfigurePixelFormat ( - IN CONST EFI_PIXEL_BITMASK *BitMask, - OUT UINT32 *BytesPerPixel, - OUT INT8 *PixelShl, - OUT INT8 *PixelShr + IN CONST EFI_PIXEL_BITMASK *BitMask, + OUT UINT32 *BytesPerPixel, + OUT INT8 *PixelShl, + OUT INT8 *PixelShr ) { UINT8 Index; @@ -58,26 +58,34 @@ FrameBufferBltLibConfigurePixelFormat ( ASSERT (BytesPerPixel != NULL); MergedMasks = 0; - Masks = (UINT32*) BitMask; + Masks = (UINT32 *)BitMask; for (Index = 0; Index < 3; Index++) { ASSERT ((MergedMasks & Masks[Index]) == 0); - PixelShl[Index] = (INT8) HighBitSet32 (Masks[Index]) - 23 + (Index * 8); + PixelShl[Index] = (INT8)HighBitSet32 (Masks[Index]) - 23 + (Index * 8); if (PixelShl[Index] < 0) { PixelShr[Index] = -PixelShl[Index]; PixelShl[Index] = 0; } else { PixelShr[Index] = 0; } - DEBUG ((DEBUG_INFO, "%d: shl:%d shr:%d mask:%x\n", Index, - PixelShl[Index], PixelShr[Index], Masks[Index])); - MergedMasks = (UINT32) (MergedMasks | Masks[Index]); + DEBUG (( + DEBUG_INFO, + "%d: shl:%d shr:%d mask:%x\n", + Index, + PixelShl[Index], + PixelShr[Index], + Masks[Index] + )); + + MergedMasks = (UINT32)(MergedMasks | Masks[Index]); } - MergedMasks = (UINT32) (MergedMasks | Masks[3]); + + MergedMasks = (UINT32)(MergedMasks | Masks[3]); ASSERT (MergedMasks != 0); - *BytesPerPixel = (UINT32) ((HighBitSet32 (MergedMasks) + 7) / 8); + *BytesPerPixel = (UINT32)((HighBitSet32 (MergedMasks) + 7) / 8); DEBUG ((DEBUG_INFO, "Bytes per pixel: %d\n", *BytesPerPixel)); } @@ -107,35 +115,35 @@ FrameBufferBltConfigure ( IN OUT UINTN *ConfigureSize ) { - CONST EFI_PIXEL_BITMASK *BitMask; - UINT32 BytesPerPixel; - INT8 PixelShl[4]; - INT8 PixelShr[4]; + CONST EFI_PIXEL_BITMASK *BitMask; + UINT32 BytesPerPixel; + INT8 PixelShl[4]; + INT8 PixelShr[4]; if (ConfigureSize == NULL) { return RETURN_INVALID_PARAMETER; } switch (FrameBufferInfo->PixelFormat) { - case PixelRedGreenBlueReserved8BitPerColor: - BitMask = &mRgbPixelMasks; - break; + case PixelRedGreenBlueReserved8BitPerColor: + BitMask = &mRgbPixelMasks; + break; - case PixelBlueGreenRedReserved8BitPerColor: - BitMask = &mBgrPixelMasks; - break; + case PixelBlueGreenRedReserved8BitPerColor: + BitMask = &mBgrPixelMasks; + break; - case PixelBitMask: - BitMask = &FrameBufferInfo->PixelInformation; - break; + case PixelBitMask: + BitMask = &FrameBufferInfo->PixelInformation; + break; - case PixelBltOnly: - ASSERT (FrameBufferInfo->PixelFormat != PixelBltOnly); - return RETURN_UNSUPPORTED; + case PixelBltOnly: + ASSERT (FrameBufferInfo->PixelFormat != PixelBltOnly); + return RETURN_UNSUPPORTED; - default: - ASSERT (FALSE); - return RETURN_INVALID_PARAMETER; + default: + ASSERT (FALSE); + return RETURN_INVALID_PARAMETER; } if (FrameBufferInfo->PixelsPerScanLine < FrameBufferInfo->HorizontalResolution) { @@ -145,9 +153,10 @@ FrameBufferBltConfigure ( FrameBufferBltLibConfigurePixelFormat (BitMask, &BytesPerPixel, PixelShl, PixelShr); if (*ConfigureSize < sizeof (FRAME_BUFFER_CONFIGURE) - + FrameBufferInfo->HorizontalResolution * BytesPerPixel) { + + FrameBufferInfo->HorizontalResolution * BytesPerPixel) + { *ConfigureSize = sizeof (FRAME_BUFFER_CONFIGURE) - + FrameBufferInfo->HorizontalResolution * BytesPerPixel; + + FrameBufferInfo->HorizontalResolution * BytesPerPixel; return RETURN_BUFFER_TOO_SMALL; } @@ -155,12 +164,12 @@ FrameBufferBltConfigure ( return RETURN_INVALID_PARAMETER; } - CopyMem (&Configure->PixelMasks, BitMask, sizeof (*BitMask)); - CopyMem (Configure->PixelShl, PixelShl, sizeof (PixelShl)); - CopyMem (Configure->PixelShr, PixelShr, sizeof (PixelShr)); + CopyMem (&Configure->PixelMasks, BitMask, sizeof (*BitMask)); + CopyMem (Configure->PixelShl, PixelShl, sizeof (PixelShl)); + CopyMem (Configure->PixelShr, PixelShr, sizeof (PixelShr)); Configure->BytesPerPixel = BytesPerPixel; Configure->PixelFormat = FrameBufferInfo->PixelFormat; - Configure->FrameBuffer = (UINT8*) FrameBuffer; + Configure->FrameBuffer = (UINT8 *)FrameBuffer; Configure->Width = FrameBufferInfo->HorizontalResolution; Configure->Height = FrameBufferInfo->VerticalResolution; Configure->PixelsPerScanLine = FrameBufferInfo->PixelsPerScanLine; @@ -185,25 +194,25 @@ FrameBufferBltConfigure ( **/ EFI_STATUS FrameBufferBltLibVideoFill ( - IN FRAME_BUFFER_CONFIGURE *Configure, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Color, - IN UINTN DestinationX, - IN UINTN DestinationY, - IN UINTN Width, - IN UINTN Height + IN FRAME_BUFFER_CONFIGURE *Configure, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Color, + IN UINTN DestinationX, + IN UINTN DestinationY, + IN UINTN Width, + IN UINTN Height ) { - UINTN IndexX; - UINTN IndexY; - UINT8 *Destination; - UINT8 Uint8; - UINT32 Uint32; - UINT64 WideFill; - BOOLEAN UseWideFill; - BOOLEAN LineBufferReady; - UINTN Offset; - UINTN WidthInBytes; - UINTN SizeInBytes; + UINTN IndexX; + UINTN IndexY; + UINT8 *Destination; + UINT8 Uint8; + UINT32 Uint32; + UINT64 WideFill; + BOOLEAN UseWideFill; + BOOLEAN LineBufferReady; + UINTN Offset; + UINTN WidthInBytes; + UINTN SizeInBytes; // // BltBuffer to Video: Source is BltBuffer, destination is Video @@ -218,25 +227,29 @@ FrameBufferBltLibVideoFill ( return RETURN_INVALID_PARAMETER; } - if (Width == 0 || Height == 0) { + if ((Width == 0) || (Height == 0)) { DEBUG ((DEBUG_VERBOSE, "VideoFill: Width or Height is 0\n")); return RETURN_INVALID_PARAMETER; } WidthInBytes = Width * Configure->BytesPerPixel; - Uint32 = *(UINT32*) Color; + Uint32 = *(UINT32 *)Color; WideFill = - (UINT32) ( - (((Uint32 << Configure->PixelShl[0]) >> Configure->PixelShr[0]) & - Configure->PixelMasks.RedMask) | - (((Uint32 << Configure->PixelShl[1]) >> Configure->PixelShr[1]) & - Configure->PixelMasks.GreenMask) | - (((Uint32 << Configure->PixelShl[2]) >> Configure->PixelShr[2]) & - Configure->PixelMasks.BlueMask) - ); - DEBUG ((DEBUG_VERBOSE, "VideoFill: color=0x%x, wide-fill=0x%x\n", - Uint32, WideFill)); + (UINT32)( + (((Uint32 << Configure->PixelShl[0]) >> Configure->PixelShr[0]) & + Configure->PixelMasks.RedMask) | + (((Uint32 << Configure->PixelShl[1]) >> Configure->PixelShr[1]) & + Configure->PixelMasks.GreenMask) | + (((Uint32 << Configure->PixelShl[2]) >> Configure->PixelShr[2]) & + Configure->PixelMasks.BlueMask) + ); + DEBUG (( + DEBUG_VERBOSE, + "VideoFill: color=0x%x, wide-fill=0x%x\n", + Uint32, + WideFill + )); // // If the size of the pixel data evenly divides the sizeof @@ -245,7 +258,7 @@ FrameBufferBltLibVideoFill ( UseWideFill = TRUE; if ((sizeof (WideFill) % Configure->BytesPerPixel) == 0) { for (IndexX = Configure->BytesPerPixel; IndexX < sizeof (WideFill); IndexX++) { - ((UINT8*) &WideFill)[IndexX] = ((UINT8*) &WideFill)[IndexX % Configure->BytesPerPixel]; + ((UINT8 *)&WideFill)[IndexX] = ((UINT8 *)&WideFill)[IndexX % Configure->BytesPerPixel]; } } else { // @@ -253,14 +266,16 @@ FrameBufferBltLibVideoFill ( // a wide fill operation. // for ( - IndexX = 1, Uint8 = ((UINT8*) &WideFill)[0]; - IndexX < Configure->BytesPerPixel; - IndexX++) { - if (Uint8 != ((UINT8*) &WideFill)[IndexX]) { + IndexX = 1, Uint8 = ((UINT8 *)&WideFill)[0]; + IndexX < Configure->BytesPerPixel; + IndexX++) + { + if (Uint8 != ((UINT8 *)&WideFill)[IndexX]) { UseWideFill = FALSE; break; } } + if (UseWideFill) { SetMem (&WideFill, sizeof (WideFill), Uint8); } @@ -268,26 +283,27 @@ FrameBufferBltLibVideoFill ( if (UseWideFill && (DestinationX == 0) && (Width == Configure->PixelsPerScanLine)) { DEBUG ((DEBUG_VERBOSE, "VideoFill (wide, one-shot)\n")); - Offset = DestinationY * Configure->PixelsPerScanLine; - Offset = Configure->BytesPerPixel * Offset; + Offset = DestinationY * Configure->PixelsPerScanLine; + Offset = Configure->BytesPerPixel * Offset; Destination = Configure->FrameBuffer + Offset; SizeInBytes = WidthInBytes * Height; if (SizeInBytes >= 8) { - SetMem32 (Destination, SizeInBytes & ~3, (UINT32) WideFill); + SetMem32 (Destination, SizeInBytes & ~3, (UINT32)WideFill); Destination += SizeInBytes & ~3; SizeInBytes &= 3; } + if (SizeInBytes > 0) { - SetMem (Destination, SizeInBytes, (UINT8) (UINTN) WideFill); + SetMem (Destination, SizeInBytes, (UINT8)(UINTN)WideFill); } } else { LineBufferReady = FALSE; for (IndexY = DestinationY; IndexY < (Height + DestinationY); IndexY++) { - Offset = (IndexY * Configure->PixelsPerScanLine) + DestinationX; - Offset = Configure->BytesPerPixel * Offset; + Offset = (IndexY * Configure->PixelsPerScanLine) + DestinationX; + Offset = Configure->BytesPerPixel * Offset; Destination = Configure->FrameBuffer + Offset; - if (UseWideFill && (((UINTN) Destination & 7) == 0)) { + if (UseWideFill && (((UINTN)Destination & 7) == 0)) { DEBUG ((DEBUG_VERBOSE, "VideoFill (wide)\n")); SizeInBytes = WidthInBytes; if (SizeInBytes >= 8) { @@ -295,6 +311,7 @@ FrameBufferBltLibVideoFill ( Destination += SizeInBytes & ~7; SizeInBytes &= 7; } + if (SizeInBytes > 0) { CopyMem (Destination, &WideFill, SizeInBytes); } @@ -307,11 +324,13 @@ FrameBufferBltLibVideoFill ( (Configure->LineBuffer + (IndexX * Configure->BytesPerPixel)), Configure->LineBuffer, MIN (IndexX, Width - IndexX) * Configure->BytesPerPixel - ); + ); IndexX += MIN (IndexX, Width - IndexX); } + LineBufferReady = TRUE; } + CopyMem (Destination, Configure->LineBuffer, WidthInBytes); } } @@ -340,26 +359,26 @@ FrameBufferBltLibVideoFill ( **/ RETURN_STATUS FrameBufferBltLibVideoToBltBuffer ( - IN FRAME_BUFFER_CONFIGURE *Configure, - OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, - IN UINTN SourceX, - IN UINTN SourceY, - IN UINTN DestinationX, - IN UINTN DestinationY, - IN UINTN Width, - IN UINTN Height, - IN UINTN Delta + IN FRAME_BUFFER_CONFIGURE *Configure, + OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, + IN UINTN SourceX, + IN UINTN SourceY, + IN UINTN DestinationX, + IN UINTN DestinationY, + IN UINTN Width, + IN UINTN Height, + IN UINTN Delta ) { - UINTN DstY; - UINTN SrcY; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; - UINT8 *Source; - UINT8 *Destination; - UINTN IndexX; - UINT32 Uint32; - UINTN Offset; - UINTN WidthInBytes; + UINTN DstY; + UINTN SrcY; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; + UINT8 *Source; + UINT8 *Destination; + UINTN IndexX; + UINT32 Uint32; + UINTN Offset; + UINTN WidthInBytes; // // Video to BltBuffer: Source is Video, destination is BltBuffer @@ -372,7 +391,7 @@ FrameBufferBltLibVideoToBltBuffer ( return RETURN_INVALID_PARAMETER; } - if (Width == 0 || Height == 0) { + if ((Width == 0) || (Height == 0)) { return RETURN_INVALID_PARAMETER; } @@ -392,14 +411,14 @@ FrameBufferBltLibVideoToBltBuffer ( // for (SrcY = SourceY, DstY = DestinationY; DstY < (Height + DestinationY); - SrcY++, DstY++) { - + SrcY++, DstY++) + { Offset = (SrcY * Configure->PixelsPerScanLine) + SourceX; Offset = Configure->BytesPerPixel * Offset; Source = Configure->FrameBuffer + Offset; if (Configure->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) { - Destination = (UINT8 *) BltBuffer + (DstY * Delta) + (DestinationX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); + Destination = (UINT8 *)BltBuffer + (DstY * Delta) + (DestinationX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); } else { Destination = Configure->LineBuffer; } @@ -409,18 +428,18 @@ FrameBufferBltLibVideoToBltBuffer ( if (Configure->PixelFormat != PixelBlueGreenRedReserved8BitPerColor) { for (IndexX = 0; IndexX < Width; IndexX++) { Blt = (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) - ((UINT8 *) BltBuffer + (DstY * Delta) + - (DestinationX + IndexX) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); - Uint32 = *(UINT32*) (Configure->LineBuffer + (IndexX * Configure->BytesPerPixel)); - *(UINT32*) Blt = - (UINT32) ( - (((Uint32 & Configure->PixelMasks.RedMask) >> - Configure->PixelShl[0]) << Configure->PixelShr[0]) | - (((Uint32 & Configure->PixelMasks.GreenMask) >> - Configure->PixelShl[1]) << Configure->PixelShr[1]) | - (((Uint32 & Configure->PixelMasks.BlueMask) >> - Configure->PixelShl[2]) << Configure->PixelShr[2]) - ); + ((UINT8 *)BltBuffer + (DstY * Delta) + + (DestinationX + IndexX) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)); + Uint32 = *(UINT32 *)(Configure->LineBuffer + (IndexX * Configure->BytesPerPixel)); + *(UINT32 *)Blt = + (UINT32)( + (((Uint32 & Configure->PixelMasks.RedMask) >> + Configure->PixelShl[0]) << Configure->PixelShr[0]) | + (((Uint32 & Configure->PixelMasks.GreenMask) >> + Configure->PixelShl[1]) << Configure->PixelShr[1]) | + (((Uint32 & Configure->PixelMasks.BlueMask) >> + Configure->PixelShl[2]) << Configure->PixelShr[2]) + ); } } } @@ -448,26 +467,26 @@ FrameBufferBltLibVideoToBltBuffer ( **/ RETURN_STATUS FrameBufferBltLibBufferToVideo ( - IN FRAME_BUFFER_CONFIGURE *Configure, - IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, - IN UINTN SourceX, - IN UINTN SourceY, - IN UINTN DestinationX, - IN UINTN DestinationY, - IN UINTN Width, - IN UINTN Height, - IN UINTN Delta + IN FRAME_BUFFER_CONFIGURE *Configure, + IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer, + IN UINTN SourceX, + IN UINTN SourceY, + IN UINTN DestinationX, + IN UINTN DestinationY, + IN UINTN Width, + IN UINTN Height, + IN UINTN Delta ) { - UINTN DstY; - UINTN SrcY; - EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; - UINT8 *Source; - UINT8 *Destination; - UINTN IndexX; - UINT32 Uint32; - UINTN Offset; - UINTN WidthInBytes; + UINTN DstY; + UINTN SrcY; + EFI_GRAPHICS_OUTPUT_BLT_PIXEL *Blt; + UINT8 *Source; + UINT8 *Destination; + UINTN IndexX; + UINT32 Uint32; + UINTN Offset; + UINTN WidthInBytes; // // BltBuffer to Video: Source is BltBuffer, destination is Video @@ -480,7 +499,7 @@ FrameBufferBltLibBufferToVideo ( return RETURN_INVALID_PARAMETER; } - if (Width == 0 || Height == 0) { + if ((Width == 0) || (Height == 0)) { return RETURN_INVALID_PARAMETER; } @@ -497,33 +516,34 @@ FrameBufferBltLibBufferToVideo ( for (SrcY = SourceY, DstY = DestinationY; SrcY < (Height + SourceY); - SrcY++, DstY++) { - - Offset = (DstY * Configure->PixelsPerScanLine) + DestinationX; - Offset = Configure->BytesPerPixel * Offset; + SrcY++, DstY++) + { + Offset = (DstY * Configure->PixelsPerScanLine) + DestinationX; + Offset = Configure->BytesPerPixel * Offset; Destination = Configure->FrameBuffer + Offset; if (Configure->PixelFormat == PixelBlueGreenRedReserved8BitPerColor) { - Source = (UINT8 *) BltBuffer + (SrcY * Delta) + SourceX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL); + Source = (UINT8 *)BltBuffer + (SrcY * Delta) + SourceX * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL); } else { for (IndexX = 0; IndexX < Width; IndexX++) { Blt = - (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *) ( - (UINT8 *) BltBuffer + - (SrcY * Delta) + - ((SourceX + IndexX) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)) - ); - Uint32 = *(UINT32*) Blt; - *(UINT32*) (Configure->LineBuffer + (IndexX * Configure->BytesPerPixel)) = - (UINT32) ( - (((Uint32 << Configure->PixelShl[0]) >> Configure->PixelShr[0]) & - Configure->PixelMasks.RedMask) | - (((Uint32 << Configure->PixelShl[1]) >> Configure->PixelShr[1]) & - Configure->PixelMasks.GreenMask) | - (((Uint32 << Configure->PixelShl[2]) >> Configure->PixelShr[2]) & - Configure->PixelMasks.BlueMask) - ); + (EFI_GRAPHICS_OUTPUT_BLT_PIXEL *)( + (UINT8 *)BltBuffer + + (SrcY * Delta) + + ((SourceX + IndexX) * sizeof (EFI_GRAPHICS_OUTPUT_BLT_PIXEL)) + ); + Uint32 = *(UINT32 *)Blt; + *(UINT32 *)(Configure->LineBuffer + (IndexX * Configure->BytesPerPixel)) = + (UINT32)( + (((Uint32 << Configure->PixelShl[0]) >> Configure->PixelShr[0]) & + Configure->PixelMasks.RedMask) | + (((Uint32 << Configure->PixelShl[1]) >> Configure->PixelShr[1]) & + Configure->PixelMasks.GreenMask) | + (((Uint32 << Configure->PixelShl[2]) >> Configure->PixelShr[2]) & + Configure->PixelMasks.BlueMask) + ); } + Source = Configure->LineBuffer; } @@ -550,20 +570,20 @@ FrameBufferBltLibBufferToVideo ( **/ RETURN_STATUS FrameBufferBltLibVideoToVideo ( - IN FRAME_BUFFER_CONFIGURE *Configure, - IN UINTN SourceX, - IN UINTN SourceY, - IN UINTN DestinationX, - IN UINTN DestinationY, - IN UINTN Width, - IN UINTN Height + IN FRAME_BUFFER_CONFIGURE *Configure, + IN UINTN SourceX, + IN UINTN SourceY, + IN UINTN DestinationX, + IN UINTN DestinationY, + IN UINTN Width, + IN UINTN Height ) { - UINT8 *Source; - UINT8 *Destination; - UINTN Offset; - UINTN WidthInBytes; - INTN LineStride; + UINT8 *Source; + UINT8 *Destination; + UINTN Offset; + UINTN WidthInBytes; + INTN LineStride; // // Video to Video: Source is Video, destination is Video @@ -584,7 +604,7 @@ FrameBufferBltLibVideoToVideo ( return RETURN_INVALID_PARAMETER; } - if (Width == 0 || Height == 0) { + if ((Width == 0) || (Height == 0)) { return RETURN_INVALID_PARAMETER; } @@ -594,8 +614,8 @@ FrameBufferBltLibVideoToVideo ( Offset = Configure->BytesPerPixel * Offset; Source = Configure->FrameBuffer + Offset; - Offset = (DestinationY * Configure->PixelsPerScanLine) + DestinationX; - Offset = Configure->BytesPerPixel * Offset; + Offset = (DestinationY * Configure->PixelsPerScanLine) + DestinationX; + Offset = Configure->BytesPerPixel * Offset; Destination = Configure->FrameBuffer + Offset; LineStride = Configure->BytesPerPixel * Configure->PixelsPerScanLine; @@ -603,15 +623,15 @@ FrameBufferBltLibVideoToVideo ( // // Copy from last line to avoid source is corrupted by copying // - Source += Height * LineStride; + Source += Height * LineStride; Destination += Height * LineStride; - LineStride = -LineStride; + LineStride = -LineStride; } while (Height-- > 0) { CopyMem (Destination, Source, WidthInBytes); - Source += LineStride; + Source += LineStride; Destination += LineStride; } @@ -648,16 +668,16 @@ FrameBufferBltLibVideoToVideo ( RETURN_STATUS EFIAPI FrameBufferBlt ( - IN FRAME_BUFFER_CONFIGURE *Configure, - IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer OPTIONAL, - IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation, - IN UINTN SourceX, - IN UINTN SourceY, - IN UINTN DestinationX, - IN UINTN DestinationY, - IN UINTN Width, - IN UINTN Height, - IN UINTN Delta + IN FRAME_BUFFER_CONFIGURE *Configure, + IN OUT EFI_GRAPHICS_OUTPUT_BLT_PIXEL *BltBuffer OPTIONAL, + IN EFI_GRAPHICS_OUTPUT_BLT_OPERATION BltOperation, + IN UINTN SourceX, + IN UINTN SourceY, + IN UINTN DestinationX, + IN UINTN DestinationY, + IN UINTN Width, + IN UINTN Height, + IN UINTN Delta ) { if (Configure == NULL) { @@ -665,54 +685,54 @@ FrameBufferBlt ( } switch (BltOperation) { - case EfiBltVideoToBltBuffer: - return FrameBufferBltLibVideoToBltBuffer ( - Configure, - BltBuffer, - SourceX, - SourceY, - DestinationX, - DestinationY, - Width, - Height, - Delta - ); - - case EfiBltVideoToVideo: - return FrameBufferBltLibVideoToVideo ( - Configure, - SourceX, - SourceY, - DestinationX, - DestinationY, - Width, - Height - ); - - case EfiBltVideoFill: - return FrameBufferBltLibVideoFill ( - Configure, - BltBuffer, - DestinationX, - DestinationY, - Width, - Height - ); - - case EfiBltBufferToVideo: - return FrameBufferBltLibBufferToVideo ( - Configure, - BltBuffer, - SourceX, - SourceY, - DestinationX, - DestinationY, - Width, - Height, - Delta - ); - - default: - return RETURN_INVALID_PARAMETER; + case EfiBltVideoToBltBuffer: + return FrameBufferBltLibVideoToBltBuffer ( + Configure, + BltBuffer, + SourceX, + SourceY, + DestinationX, + DestinationY, + Width, + Height, + Delta + ); + + case EfiBltVideoToVideo: + return FrameBufferBltLibVideoToVideo ( + Configure, + SourceX, + SourceY, + DestinationX, + DestinationY, + Width, + Height + ); + + case EfiBltVideoFill: + return FrameBufferBltLibVideoFill ( + Configure, + BltBuffer, + DestinationX, + DestinationY, + Width, + Height + ); + + case EfiBltBufferToVideo: + return FrameBufferBltLibBufferToVideo ( + Configure, + BltBuffer, + SourceX, + SourceY, + DestinationX, + DestinationY, + Width, + Height, + Delta + ); + + default: + return RETURN_INVALID_PARAMETER; } } diff --git a/MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.c b/MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.c index 41d2972b34..4ce45ae409 100644 --- a/MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.c +++ b/MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.c @@ -27,9 +27,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent RETURN_STATUS EFIAPI SaveLockBox ( - IN GUID *Guid, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN VOID *Buffer, + IN UINTN Length ) { return RETURN_SUCCESS; @@ -51,8 +51,8 @@ SaveLockBox ( RETURN_STATUS EFIAPI SetLockBoxAttributes ( - IN GUID *Guid, - IN UINT64 Attributes + IN GUID *Guid, + IN UINT64 Attributes ) { return RETURN_SUCCESS; @@ -80,10 +80,10 @@ SetLockBoxAttributes ( RETURN_STATUS EFIAPI UpdateLockBox ( - IN GUID *Guid, - IN UINTN Offset, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN UINTN Offset, + IN VOID *Buffer, + IN UINTN Length ) { return RETURN_SUCCESS; @@ -110,9 +110,9 @@ UpdateLockBox ( RETURN_STATUS EFIAPI RestoreLockBox ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ) { return RETURN_SUCCESS; diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/F86GuidedSectionExtraction.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/F86GuidedSectionExtraction.c index fefe02033f..70cfae5660 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/F86GuidedSectionExtraction.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/F86GuidedSectionExtraction.c @@ -61,31 +61,35 @@ LzmaArchGuidedSectionGetInfo ( if (IS_SECTION2 (InputSection)) { if (!CompareGuid ( - &gLzmaF86CustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gLzmaF86CustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes; return LzmaUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, - SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, + SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); } else { if (!CompareGuid ( - &gLzmaF86CustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gLzmaF86CustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes; return LzmaUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, - SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, + SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); @@ -134,25 +138,25 @@ LzmaArchGuidedSectionExtraction ( OUT UINT32 *AuthenticationStatus ) { - EFI_GUID *InputGuid; - VOID *Source; - UINTN SourceSize; - EFI_STATUS Status; - UINT32 X86State; - UINT32 OutputBufferSize; - UINT32 ScratchBufferSize; + EFI_GUID *InputGuid; + VOID *Source; + UINTN SourceSize; + EFI_STATUS Status; + UINT32 X86State; + UINT32 OutputBufferSize; + UINT32 ScratchBufferSize; ASSERT (OutputBuffer != NULL); ASSERT (InputSection != NULL); if (IS_SECTION2 (InputSection)) { - InputGuid = &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid); - Source = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; - SourceSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; + InputGuid = &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid); + Source = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; + SourceSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; } else { - InputGuid = &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid); - Source = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; - SourceSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; + InputGuid = &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid); + Source = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; + SourceSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; } if (!CompareGuid (&gLzmaF86CustomDecompressGuid, InputGuid)) { @@ -165,33 +169,32 @@ LzmaArchGuidedSectionExtraction ( *AuthenticationStatus = 0; Status = LzmaUefiDecompress ( - Source, - SourceSize, - *OutputBuffer, - ScratchBuffer - ); + Source, + SourceSize, + *OutputBuffer, + ScratchBuffer + ); // // After decompress, the data need to be converted to the raw data. // if (!EFI_ERROR (Status)) { Status = LzmaUefiDecompressGetInfo ( - Source, - (UINT32) SourceSize, - &OutputBufferSize, - &ScratchBufferSize - ); + Source, + (UINT32)SourceSize, + &OutputBufferSize, + &ScratchBufferSize + ); if (!EFI_ERROR (Status)) { - x86_Convert_Init(X86State); - x86_Convert(*OutputBuffer, OutputBufferSize, 0, &X86State, 0); + x86_Convert_Init (X86State); + x86_Convert (*OutputBuffer, OutputBufferSize, 0, &X86State, 0); } } return Status; } - /** Register LzmaArchDecompress and LzmaArchDecompressGetInfo handlers with LzmaF86CustomDecompressGuid. @@ -205,8 +208,8 @@ LzmaArchDecompressLibConstructor ( ) { return ExtractGuidedSectionRegisterHandlers ( - &gLzmaF86CustomDecompressGuid, - LzmaArchGuidedSectionGetInfo, - LzmaArchGuidedSectionExtraction - ); + &gLzmaF86CustomDecompressGuid, + LzmaArchGuidedSectionGetInfo, + LzmaArchGuidedSectionExtraction + ); } diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/GuidedSectionExtraction.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/GuidedSectionExtraction.c index 4d89836d0c..cace79e32b 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/GuidedSectionExtraction.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/GuidedSectionExtraction.c @@ -59,31 +59,35 @@ LzmaGuidedSectionGetInfo ( if (IS_SECTION2 (InputSection)) { if (!CompareGuid ( - &gLzmaCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gLzmaCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes; return LzmaUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, - SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, + SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); } else { if (!CompareGuid ( - &gLzmaCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gLzmaCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes; return LzmaUefiDecompressGetInfo ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, - SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, + SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, OutputBufferSize, ScratchBufferSize ); @@ -137,8 +141,10 @@ LzmaGuidedSectionExtraction ( if (IS_SECTION2 (InputSection)) { if (!CompareGuid ( - &gLzmaCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gLzmaCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } @@ -148,15 +154,17 @@ LzmaGuidedSectionExtraction ( *AuthenticationStatus = 0; return LzmaUefiDecompress ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, - SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, + SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset, *OutputBuffer, ScratchBuffer ); } else { if (!CompareGuid ( - &gLzmaCustomDecompressGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gLzmaCustomDecompressGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return RETURN_INVALID_PARAMETER; } @@ -166,15 +174,14 @@ LzmaGuidedSectionExtraction ( *AuthenticationStatus = 0; return LzmaUefiDecompress ( - (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, - SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset, + (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, + SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset, *OutputBuffer, ScratchBuffer - ); + ); } } - /** Register LzmaDecompress and LzmaDecompressGetInfo handlers with LzmaCustomerDecompressGuid. @@ -188,8 +195,8 @@ LzmaDecompressLibConstructor ( ) { return ExtractGuidedSectionRegisterHandlers ( - &gLzmaCustomDecompressGuid, - LzmaGuidedSectionGetInfo, - LzmaGuidedSectionExtraction - ); + &gLzmaCustomDecompressGuid, + LzmaGuidedSectionGetInfo, + LzmaGuidedSectionExtraction + ); } diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompress.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompress.c index 8f7c242dca..18577acf38 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompress.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompress.c @@ -11,13 +11,12 @@ #include "Sdk/C/7zVersion.h" #include "Sdk/C/LzmaDec.h" -#define SCRATCH_BUFFER_REQUEST_SIZE SIZE_64KB +#define SCRATCH_BUFFER_REQUEST_SIZE SIZE_64KB -typedef struct -{ - ISzAlloc Functions; - VOID *Buffer; - UINTN BufferSize; +typedef struct { + ISzAlloc Functions; + VOID *Buffer; + UINTN BufferSize; } ISzAllocWithData; /** @@ -30,18 +29,18 @@ typedef struct **/ VOID * SzAlloc ( - CONST ISzAlloc *P, - size_t Size + CONST ISzAlloc *P, + size_t Size ) { - VOID *Addr; - ISzAllocWithData *Private; + VOID *Addr; + ISzAllocWithData *Private; - Private = (ISzAllocWithData*) P; + Private = (ISzAllocWithData *)P; if (Private->BufferSize >= Size) { - Addr = Private->Buffer; - Private->Buffer = (VOID*) ((UINT8*)Addr + Size); + Addr = Private->Buffer; + Private->Buffer = (VOID *)((UINT8 *)Addr + Size); Private->BufferSize -= Size; return Addr; } else { @@ -58,8 +57,8 @@ SzAlloc ( **/ VOID SzFree ( - CONST ISzAlloc *P, - VOID *Address + CONST ISzAlloc *P, + VOID *Address ) { // @@ -69,7 +68,7 @@ SzFree ( // } -#define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + 8) +#define LZMA_HEADER_SIZE (LZMA_PROPS_SIZE + 8) /** Get the size of the uncompressed buffer by parsing EncodeData header. @@ -79,17 +78,18 @@ SzFree ( @return The size of the uncompressed buffer. **/ UINT64 -GetDecodedSizeOfBuf( - UINT8 *EncodedData +GetDecodedSizeOfBuf ( + UINT8 *EncodedData ) { - UINT64 DecodedSize; - INTN Index; + UINT64 DecodedSize; + INTN Index; /* Parse header */ DecodedSize = 0; - for (Index = LZMA_PROPS_SIZE + 7; Index >= LZMA_PROPS_SIZE; Index--) - DecodedSize = LShiftU64(DecodedSize, 8) + EncodedData[Index]; + for (Index = LZMA_PROPS_SIZE + 7; Index >= LZMA_PROPS_SIZE; Index--) { + DecodedSize = LShiftU64 (DecodedSize, 8) + EncodedData[Index]; + } return DecodedSize; } @@ -143,15 +143,15 @@ LzmaUefiDecompressGetInfo ( { UInt64 DecodedSize; - ASSERT(SourceSize >= LZMA_HEADER_SIZE); + ASSERT (SourceSize >= LZMA_HEADER_SIZE); - DecodedSize = GetDecodedSizeOfBuf((UINT8*)Source); + DecodedSize = GetDecodedSizeOfBuf ((UINT8 *)Source); if (DecodedSize > MAX_UINT32) { return RETURN_UNSUPPORTED; } *DestinationSize = (UINT32)DecodedSize; - *ScratchSize = SCRATCH_BUFFER_REQUEST_SIZE; + *ScratchSize = SCRATCH_BUFFER_REQUEST_SIZE; return RETURN_SUCCESS; } @@ -192,25 +192,25 @@ LzmaUefiDecompress ( SizeT EncodedDataSize; ISzAllocWithData AllocFuncs; - AllocFuncs.Functions.Alloc = SzAlloc; - AllocFuncs.Functions.Free = SzFree; - AllocFuncs.Buffer = Scratch; - AllocFuncs.BufferSize = SCRATCH_BUFFER_REQUEST_SIZE; - - DecodedBufSize = (SizeT)GetDecodedSizeOfBuf((UINT8*)Source); - EncodedDataSize = (SizeT) (SourceSize - LZMA_HEADER_SIZE); - - LzmaResult = LzmaDecode( - Destination, - &DecodedBufSize, - (Byte*)((UINT8*)Source + LZMA_HEADER_SIZE), - &EncodedDataSize, - Source, - LZMA_PROPS_SIZE, - LZMA_FINISH_END, - &Status, - &(AllocFuncs.Functions) - ); + AllocFuncs.Functions.Alloc = SzAlloc; + AllocFuncs.Functions.Free = SzFree; + AllocFuncs.Buffer = Scratch; + AllocFuncs.BufferSize = SCRATCH_BUFFER_REQUEST_SIZE; + + DecodedBufSize = (SizeT)GetDecodedSizeOfBuf ((UINT8 *)Source); + EncodedDataSize = (SizeT)(SourceSize - LZMA_HEADER_SIZE); + + LzmaResult = LzmaDecode ( + Destination, + &DecodedBufSize, + (Byte *)((UINT8 *)Source + LZMA_HEADER_SIZE), + &EncodedDataSize, + Source, + LZMA_PROPS_SIZE, + LZMA_FINISH_END, + &Status, + &(AllocFuncs.Functions) + ); if (LzmaResult == SZ_OK) { return RETURN_SUCCESS; @@ -218,4 +218,3 @@ LzmaUefiDecompress ( return RETURN_INVALID_PARAMETER; } } - diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompressLibInternal.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompressLibInternal.h index fbafd5f100..1dc54eb930 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompressLibInternal.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaDecompressLibInternal.h @@ -92,4 +92,3 @@ LzmaUefiDecompress ( ); #endif - diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zTypes.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zTypes.h index 42b7040dd7..502a32e4da 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zTypes.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zTypes.h @@ -9,73 +9,71 @@ #endif #ifdef EFIAPI -#include "UefiLzma.h" + #include "UefiLzma.h" #else -#include + #include #endif #ifndef EXTERN_C_BEGIN -#ifdef __cplusplus -#define EXTERN_C_BEGIN extern "C" { -#define EXTERN_C_END } -#else + #ifdef __cplusplus +#define EXTERN_C_BEGIN extern "C" { +#define EXTERN_C_END } + #else #define EXTERN_C_BEGIN #define EXTERN_C_END -#endif + #endif #endif EXTERN_C_BEGIN -#define SZ_OK 0 +#define SZ_OK 0 -#define SZ_ERROR_DATA 1 -#define SZ_ERROR_MEM 2 -#define SZ_ERROR_CRC 3 -#define SZ_ERROR_UNSUPPORTED 4 -#define SZ_ERROR_PARAM 5 -#define SZ_ERROR_INPUT_EOF 6 -#define SZ_ERROR_OUTPUT_EOF 7 -#define SZ_ERROR_READ 8 -#define SZ_ERROR_WRITE 9 -#define SZ_ERROR_PROGRESS 10 -#define SZ_ERROR_FAIL 11 -#define SZ_ERROR_THREAD 12 +#define SZ_ERROR_DATA 1 +#define SZ_ERROR_MEM 2 +#define SZ_ERROR_CRC 3 +#define SZ_ERROR_UNSUPPORTED 4 +#define SZ_ERROR_PARAM 5 +#define SZ_ERROR_INPUT_EOF 6 +#define SZ_ERROR_OUTPUT_EOF 7 +#define SZ_ERROR_READ 8 +#define SZ_ERROR_WRITE 9 +#define SZ_ERROR_PROGRESS 10 +#define SZ_ERROR_FAIL 11 +#define SZ_ERROR_THREAD 12 -#define SZ_ERROR_ARCHIVE 16 -#define SZ_ERROR_NO_ARCHIVE 17 +#define SZ_ERROR_ARCHIVE 16 +#define SZ_ERROR_NO_ARCHIVE 17 typedef int SRes; - #ifdef _WIN32 /* typedef DWORD WRes; */ typedef unsigned WRes; -#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) +#define MY_SRes_HRESULT_FROM_WRes(x) HRESULT_FROM_WIN32(x) #else typedef int WRes; -#define MY__FACILITY_WIN32 7 -#define MY__FACILITY__WRes MY__FACILITY_WIN32 -#define MY_SRes_HRESULT_FROM_WRes(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (MY__FACILITY__WRes << 16) | 0x80000000))) +#define MY__FACILITY_WIN32 7 +#define MY__FACILITY__WRes MY__FACILITY_WIN32 +#define MY_SRes_HRESULT_FROM_WRes(x) ((HRESULT)(x) <= 0 ? ((HRESULT)(x)) : ((HRESULT) (((x) & 0x0000FFFF) | (MY__FACILITY__WRes << 16) | 0x80000000))) #endif - #ifndef RINOK -#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } +#define RINOK(x) { int __result__ = (x); if (__result__ != 0) return __result__; } #endif -typedef unsigned char Byte; -typedef short Int16; +typedef unsigned char Byte; +typedef short Int16; typedef unsigned short UInt16; #ifdef _LZMA_UINT32_IS_ULONG -typedef long Int32; +typedef long Int32; typedef unsigned long UInt32; #else -typedef int Int32; +typedef int Int32; typedef unsigned int UInt32; #endif @@ -84,20 +82,20 @@ typedef unsigned int UInt32; /* define _SZ_NO_INT_64, if your compiler doesn't support 64-bit integers. NOTES: Some code will work incorrectly in that case! */ -typedef long Int64; +typedef long Int64; typedef unsigned long UInt64; #else -#if defined(_MSC_VER) || defined(__BORLANDC__) -typedef __int64 Int64; + #if defined (_MSC_VER) || defined (__BORLANDC__) +typedef __int64 Int64; typedef unsigned __int64 UInt64; -#define UINT64_CONST(n) n -#else -typedef long long int Int64; +#define UINT64_CONST(n) n + #else +typedef long long int Int64; typedef unsigned long long int UInt64; -#define UINT64_CONST(n) n ## ULL -#endif +#define UINT64_CONST(n) n ## ULL + #endif #endif @@ -109,28 +107,27 @@ typedef size_t SizeT; typedef int BoolInt; /* typedef BoolInt Bool; */ -#define True 1 -#define False 0 - +#define True 1 +#define False 0 #ifdef _WIN32 -#define MY_STD_CALL __stdcall +#define MY_STD_CALL __stdcall #else #define MY_STD_CALL #endif -#if defined(_MSC_VER) && !defined(__clang__) +#if defined (_MSC_VER) && !defined (__clang__) -#if _MSC_VER >= 1300 -#define MY_NO_INLINE __declspec(noinline) -#else + #if _MSC_VER >= 1300 +#define MY_NO_INLINE __declspec(noinline) + #else #define MY_NO_INLINE -#endif + #endif -#define MY_FORCE_INLINE __forceinline +#define MY_FORCE_INLINE __forceinline -#define MY_CDECL __cdecl -#define MY_FAST_CALL __fastcall +#define MY_CDECL __cdecl +#define MY_FAST_CALL __fastcall #else @@ -142,6 +139,7 @@ typedef int BoolInt; /* inline keyword : for C++ / C99 */ /* GCC, clang: */ + /* #if defined (__GNUC__) && (__GNUC__ >= 4) #define MY_FORCE_INLINE __attribute__((always_inline)) @@ -151,179 +149,252 @@ typedef int BoolInt; #endif - /* The following interfaces use first parameter as pointer to structure */ typedef struct IByteIn IByteIn; -struct IByteIn -{ - Byte (*Read)(const IByteIn *p); /* reads one byte, returns 0 in case of EOF or error */ +struct IByteIn { + Byte (*Read)( + const IByteIn *p + ); /* reads one byte, returns 0 in case of EOF or error */ }; -#define IByteIn_Read(p) (p)->Read(p) +#define IByteIn_Read(p) (p)->Read(p) typedef struct IByteOut IByteOut; -struct IByteOut -{ - void (*Write)(const IByteOut *p, Byte b); +struct IByteOut { + void (*Write)( + const IByteOut *p, + Byte b + ); }; -#define IByteOut_Write(p, b) (p)->Write(p, b) +#define IByteOut_Write(p, b) (p)->Write(p, b) typedef struct ISeqInStream ISeqInStream; -struct ISeqInStream -{ - SRes (*Read)(const ISeqInStream *p, void *buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) < input(*size)) is allowed */ +struct ISeqInStream { + SRes (*Read)( + const ISeqInStream *p, + void *buf, + size_t *size + ); + + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) < input(*size)) is allowed */ }; -#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) -/* it can return SZ_ERROR_INPUT_EOF */ -SRes SeqInStream_Read(const ISeqInStream *stream, void *buf, size_t size); -SRes SeqInStream_Read2(const ISeqInStream *stream, void *buf, size_t size, SRes errorType); -SRes SeqInStream_ReadByte(const ISeqInStream *stream, Byte *buf); +#define ISeqInStream_Read(p, buf, size) (p)->Read(p, buf, size) +/* it can return SZ_ERROR_INPUT_EOF */ +SRes +SeqInStream_Read ( + const ISeqInStream *stream, + void *buf, + size_t size + ); + +SRes +SeqInStream_Read2 ( + const ISeqInStream *stream, + void *buf, + size_t size, + SRes errorType + ); + +SRes +SeqInStream_ReadByte ( + const ISeqInStream *stream, + Byte *buf + ); typedef struct ISeqOutStream ISeqOutStream; -struct ISeqOutStream -{ - size_t (*Write)(const ISeqOutStream *p, const void *buf, size_t size); - /* Returns: result - the number of actually written bytes. - (result < size) means error */ +struct ISeqOutStream { + size_t (*Write)( + const ISeqOutStream *p, + const void *buf, + size_t size + ); + + /* Returns: result - the number of actually written bytes. + (result < size) means error */ }; -#define ISeqOutStream_Write(p, buf, size) (p)->Write(p, buf, size) -typedef enum -{ +#define ISeqOutStream_Write(p, buf, size) (p)->Write(p, buf, size) + +typedef enum { SZ_SEEK_SET = 0, SZ_SEEK_CUR = 1, SZ_SEEK_END = 2 } ESzSeek; - typedef struct ISeekInStream ISeekInStream; -struct ISeekInStream -{ - SRes (*Read)(const ISeekInStream *p, void *buf, size_t *size); /* same as ISeqInStream::Read */ - SRes (*Seek)(const ISeekInStream *p, Int64 *pos, ESzSeek origin); +struct ISeekInStream { + SRes (*Read)( + const ISeekInStream *p, + void *buf, + size_t *size + ); /* same as ISeqInStream::Read */ + SRes (*Seek)( + const ISeekInStream *p, + Int64 *pos, + ESzSeek origin + ); }; -#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) -#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) +#define ISeekInStream_Read(p, buf, size) (p)->Read(p, buf, size) +#define ISeekInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) typedef struct ILookInStream ILookInStream; -struct ILookInStream -{ - SRes (*Look)(const ILookInStream *p, const void **buf, size_t *size); - /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. - (output(*size) > input(*size)) is not allowed - (output(*size) < input(*size)) is allowed */ - SRes (*Skip)(const ILookInStream *p, size_t offset); - /* offset must be <= output(*size) of Look */ - - SRes (*Read)(const ILookInStream *p, void *buf, size_t *size); - /* reads directly (without buffer). It's same as ISeqInStream::Read */ - SRes (*Seek)(const ILookInStream *p, Int64 *pos, ESzSeek origin); +struct ILookInStream { + SRes (*Look)( + const ILookInStream *p, + const void **buf, + size_t *size + ); + + /* if (input(*size) != 0 && output(*size) == 0) means end_of_stream. + (output(*size) > input(*size)) is not allowed + (output(*size) < input(*size)) is allowed */ + SRes (*Skip)( + const ILookInStream *p, + size_t offset + ); + /* offset must be <= output(*size) of Look */ + + SRes (*Read)( + const ILookInStream *p, + void *buf, + size_t *size + ); + /* reads directly (without buffer). It's same as ISeqInStream::Read */ + SRes (*Seek)( + const ILookInStream *p, + Int64 *pos, + ESzSeek origin + ); }; -#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) -#define ILookInStream_Skip(p, offset) (p)->Skip(p, offset) -#define ILookInStream_Read(p, buf, size) (p)->Read(p, buf, size) -#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) +#define ILookInStream_Look(p, buf, size) (p)->Look(p, buf, size) +#define ILookInStream_Skip(p, offset) (p)->Skip(p, offset) +#define ILookInStream_Read(p, buf, size) (p)->Read(p, buf, size) +#define ILookInStream_Seek(p, pos, origin) (p)->Seek(p, pos, origin) +SRes +LookInStream_LookRead ( + const ILookInStream *stream, + void *buf, + size_t *size + ); -SRes LookInStream_LookRead(const ILookInStream *stream, void *buf, size_t *size); -SRes LookInStream_SeekTo(const ILookInStream *stream, UInt64 offset); +SRes +LookInStream_SeekTo ( + const ILookInStream *stream, + UInt64 offset + ); /* reads via ILookInStream::Read */ -SRes LookInStream_Read2(const ILookInStream *stream, void *buf, size_t size, SRes errorType); -SRes LookInStream_Read(const ILookInStream *stream, void *buf, size_t size); - - - -typedef struct -{ - ILookInStream vt; - const ISeekInStream *realStream; - - size_t pos; - size_t size; /* it's data size */ +SRes +LookInStream_Read2 ( + const ILookInStream *stream, + void *buf, + size_t size, + SRes errorType + ); + +SRes +LookInStream_Read ( + const ILookInStream *stream, + void *buf, + size_t size + ); + +typedef struct { + ILookInStream vt; + const ISeekInStream *realStream; + + size_t pos; + size_t size; /* it's data size */ /* the following variables must be set outside */ - Byte *buf; - size_t bufSize; + Byte *buf; + size_t bufSize; } CLookToRead2; -void LookToRead2_CreateVTable(CLookToRead2 *p, int lookahead); - -#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } +void +LookToRead2_CreateVTable ( + CLookToRead2 *p, + int lookahead + ); +#define LookToRead2_Init(p) { (p)->pos = (p)->size = 0; } -typedef struct -{ - ISeqInStream vt; - const ILookInStream *realStream; +typedef struct { + ISeqInStream vt; + const ILookInStream *realStream; } CSecToLook; -void SecToLook_CreateVTable(CSecToLook *p); +void +SecToLook_CreateVTable ( + CSecToLook *p + ); - - -typedef struct -{ - ISeqInStream vt; - const ILookInStream *realStream; +typedef struct { + ISeqInStream vt; + const ILookInStream *realStream; } CSecToRead; -void SecToRead_CreateVTable(CSecToRead *p); - +void +SecToRead_CreateVTable ( + CSecToRead *p + ); typedef struct ICompressProgress ICompressProgress; -struct ICompressProgress -{ - SRes (*Progress)(const ICompressProgress *p, UInt64 inSize, UInt64 outSize); - /* Returns: result. (result != SZ_OK) means break. - Value (UInt64)(Int64)-1 for size means unknown value. */ -}; -#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) +struct ICompressProgress { + SRes (*Progress)( + const ICompressProgress *p, + UInt64 inSize, + UInt64 outSize + ); + /* Returns: result. (result != SZ_OK) means break. + Value (UInt64)(Int64)-1 for size means unknown value. */ +}; +#define ICompressProgress_Progress(p, inSize, outSize) (p)->Progress(p, inSize, outSize) typedef struct ISzAlloc ISzAlloc; -typedef const ISzAlloc * ISzAllocPtr; - -struct ISzAlloc -{ - void *(*Alloc)(ISzAllocPtr p, size_t size); - void (*Free)(ISzAllocPtr p, void *address); /* address can be 0 */ +typedef const ISzAlloc *ISzAllocPtr; + +struct ISzAlloc { + void *(*Alloc)( + ISzAllocPtr p, + size_t size + ); + void (*Free)( + ISzAllocPtr p, + void *address + ); /* address can be 0 */ }; -#define ISzAlloc_Alloc(p, size) (p)->Alloc(p, size) -#define ISzAlloc_Free(p, a) (p)->Free(p, a) +#define ISzAlloc_Alloc(p, size) (p)->Alloc(p, size) +#define ISzAlloc_Free(p, a) (p)->Free(p, a) /* deprecated */ -#define IAlloc_Alloc(p, size) ISzAlloc_Alloc(p, size) -#define IAlloc_Free(p, a) ISzAlloc_Free(p, a) - - - - +#define IAlloc_Alloc(p, size) ISzAlloc_Alloc(p, size) +#define IAlloc_Free(p, a) ISzAlloc_Free(p, a) #ifndef MY_offsetof #ifdef offsetof - #define MY_offsetof(type, m) offsetof(type, m) - /* - #define MY_offsetof(type, m) FIELD_OFFSET(type, m) - */ +#define MY_offsetof(type, m) offsetof(type, m) + +/* +#define MY_offsetof(type, m) FIELD_OFFSET(type, m) +*/ #else - #define MY_offsetof(type, m) ((size_t)&(((type *)0)->m)) +#define MY_offsetof(type, m) ((size_t)&(((type *)0)->m)) #endif #endif - - #ifndef MY_container_of /* @@ -339,38 +410,36 @@ struct ISzAlloc GCC 4.8.1 : classes with non-public variable members" */ -#define MY_container_of(ptr, type, m) ((type *)((char *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) - +#define MY_container_of(ptr, type, m) ((type *)((char *)(1 ? (ptr) : &((type *)0)->m) - MY_offsetof(type, m))) #endif -#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(ptr)) +#define CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) ((type *)(ptr)) /* #define CONTAINER_FROM_VTBL(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) */ -#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) +#define CONTAINER_FROM_VTBL(ptr, type, m) MY_container_of(ptr, type, m) + +#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) -#define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL_SIMPLE(ptr, type, m) /* #define CONTAINER_FROM_VTBL_CLS(ptr, type, m) CONTAINER_FROM_VTBL(ptr, type, m) */ - - #ifdef _WIN32 -#define CHAR_PATH_SEPARATOR '\\' -#define WCHAR_PATH_SEPARATOR L'\\' -#define STRING_PATH_SEPARATOR "\\" -#define WSTRING_PATH_SEPARATOR L"\\" +#define CHAR_PATH_SEPARATOR '\\' +#define WCHAR_PATH_SEPARATOR L'\\' +#define STRING_PATH_SEPARATOR "\\" +#define WSTRING_PATH_SEPARATOR L"\\" #else -#define CHAR_PATH_SEPARATOR '/' -#define WCHAR_PATH_SEPARATOR L'/' -#define STRING_PATH_SEPARATOR "/" -#define WSTRING_PATH_SEPARATOR L"/" +#define CHAR_PATH_SEPARATOR '/' +#define WCHAR_PATH_SEPARATOR L'/' +#define STRING_PATH_SEPARATOR "/" +#define WSTRING_PATH_SEPARATOR L"/" #endif diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zVersion.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zVersion.h index 0074c64be9..a45aa2008f 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zVersion.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/7zVersion.h @@ -1,27 +1,27 @@ -#define MY_VER_MAJOR 19 -#define MY_VER_MINOR 00 -#define MY_VER_BUILD 0 -#define MY_VERSION_NUMBERS "19.00" -#define MY_VERSION MY_VERSION_NUMBERS +#define MY_VER_MAJOR 19 +#define MY_VER_MINOR 00 +#define MY_VER_BUILD 0 +#define MY_VERSION_NUMBERS "19.00" +#define MY_VERSION MY_VERSION_NUMBERS #ifdef MY_CPU_NAME - #define MY_VERSION_CPU MY_VERSION " (" MY_CPU_NAME ")" +#define MY_VERSION_CPU MY_VERSION " (" MY_CPU_NAME ")" #else - #define MY_VERSION_CPU MY_VERSION +#define MY_VERSION_CPU MY_VERSION #endif -#define MY_DATE "2019-02-21" +#define MY_DATE "2019-02-21" #undef MY_COPYRIGHT #undef MY_VERSION_COPYRIGHT_DATE -#define MY_AUTHOR_NAME "Igor Pavlov" -#define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" -#define MY_COPYRIGHT_CR "Copyright (c) 1999-2018 Igor Pavlov" +#define MY_AUTHOR_NAME "Igor Pavlov" +#define MY_COPYRIGHT_PD "Igor Pavlov : Public domain" +#define MY_COPYRIGHT_CR "Copyright (c) 1999-2018 Igor Pavlov" #ifdef USE_COPYRIGHT_CR - #define MY_COPYRIGHT MY_COPYRIGHT_CR +#define MY_COPYRIGHT MY_COPYRIGHT_CR #else - #define MY_COPYRIGHT MY_COPYRIGHT_PD +#define MY_COPYRIGHT MY_COPYRIGHT_PD #endif -#define MY_COPYRIGHT_DATE MY_COPYRIGHT " : " MY_DATE -#define MY_VERSION_COPYRIGHT_DATE MY_VERSION_CPU " : " MY_COPYRIGHT " : " MY_DATE +#define MY_COPYRIGHT_DATE MY_COPYRIGHT " : " MY_DATE +#define MY_VERSION_COPYRIGHT_DATE MY_VERSION_CPU " : " MY_COPYRIGHT " : " MY_DATE diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra.h index ecf7b0c447..85085192fb 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra.h @@ -51,13 +51,55 @@ in CALL instructions to increase the compression ratio. } */ -#define x86_Convert_Init(state) { state = 0; } -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding); -SizeT ARM_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT ARMT_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT PPC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT SPARC_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); -SizeT IA64_Convert(Byte *data, SizeT size, UInt32 ip, int encoding); +#define x86_Convert_Init(state) { state = 0; } +SizeT +x86_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + UInt32 *state, + int encoding + ); + +SizeT +ARM_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + int encoding + ); + +SizeT +ARMT_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + int encoding + ); + +SizeT +PPC_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + int encoding + ); + +SizeT +SPARC_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + int encoding + ); + +SizeT +IA64_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + int encoding + ); EXTERN_C_END diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra86.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra86.c index a6463c63ba..ec5f574035 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra86.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Bra86.c @@ -5,40 +5,49 @@ #include "Bra.h" -#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0) +#define Test86MSByte(b) ((((b) + 1) & 0xFE) == 0) -SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding) +SizeT +x86_Convert ( + Byte *data, + SizeT size, + UInt32 ip, + UInt32 *state, + int encoding + ) { - SizeT pos = 0; - UInt32 mask = *state & 7; - if (size < 5) + SizeT pos = 0; + UInt32 mask = *state & 7; + + if (size < 5) { return 0; + } + size -= 4; - ip += 5; + ip += 5; - for (;;) - { - Byte *p = data + pos; - const Byte *limit = data + size; - for (; p < limit; p++) - if ((*p & 0xFE) == 0xE8) + for ( ; ;) { + Byte *p = data + pos; + const Byte *limit = data + size; + for ( ; p < limit; p++) { + if ((*p & 0xFE) == 0xE8) { break; + } + } { - SizeT d = (SizeT)(p - data - pos); + SizeT d = (SizeT)(p - data - pos); pos = (SizeT)(p - data); - if (p >= limit) - { + if (p >= limit) { *state = (d > 2 ? 0 : mask >> (unsigned)d); return pos; } - if (d > 2) + + if (d > 2) { mask = 0; - else - { + } else { mask >>= (unsigned)d; - if (mask != 0 && (mask > 4 || mask == 3 || Test86MSByte(p[(size_t)(mask >> 1) + 1]))) - { + if ((mask != 0) && ((mask > 4) || (mask == 3) || Test86MSByte (p[(size_t)(mask >> 1) + 1]))) { mask = (mask >> 1) | 4; pos++; continue; @@ -46,35 +55,35 @@ SizeT x86_Convert(Byte *data, SizeT size, UInt32 ip, UInt32 *state, int encoding } } - if (Test86MSByte(p[4])) - { - UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); - UInt32 cur = ip + (UInt32)pos; + if (Test86MSByte (p[4])) { + UInt32 v = ((UInt32)p[4] << 24) | ((UInt32)p[3] << 16) | ((UInt32)p[2] << 8) | ((UInt32)p[1]); + UInt32 cur = ip + (UInt32)pos; pos += 5; - if (encoding) + if (encoding) { v += cur; - else + } else { v -= cur; - if (mask != 0) - { - unsigned sh = (mask & 6) << 2; - if (Test86MSByte((Byte)(v >> sh))) - { + } + + if (mask != 0) { + unsigned sh = (mask & 6) << 2; + if (Test86MSByte ((Byte)(v >> sh))) { v ^= (((UInt32)0x100 << sh) - 1); - if (encoding) + if (encoding) { v += cur; - else + } else { v -= cur; + } } + mask = 0; } + p[1] = (Byte)v; p[2] = (Byte)(v >> 8); p[3] = (Byte)(v >> 16); p[4] = (Byte)(0 - ((v >> 24) & 1)); - } - else - { + } else { mask = (mask >> 1) | 4; pos++; } diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Compiler.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Compiler.h index c788648cd2..e8968d3497 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Compiler.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/Compiler.h @@ -7,8 +7,8 @@ #ifdef _MSC_VER #ifdef UNDER_CE - #define RPC_NO_WINDOWS_H - /* #pragma warning(disable : 4115) // '_RPC_ASYNC_STATE' : named type definition in parentheses */ +#define RPC_NO_WINDOWS_H +/* #pragma warning(disable : 4115) // '_RPC_ASYNC_STATE' : named type definition in parentheses */ #pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union #pragma warning(disable : 4214) // nonstandard extension used : bit field types other than int #endif @@ -27,7 +27,7 @@ #endif -#define UNUSED_VAR(x) (void)x; +#define UNUSED_VAR(x) (void)x; /* #define UNUSED_VAR(x) x=x; */ #endif diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/CpuArch.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/CpuArch.h index 5f74c1c0cb..671a77bdb7 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/CpuArch.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/CpuArch.h @@ -16,269 +16,252 @@ If MY_CPU_LE and MY_CPU_BE are not defined, we don't know about ENDIANNESS of pl MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned memory accesses. */ -#if defined(_M_X64) \ - || defined(_M_AMD64) \ - || defined(__x86_64__) \ - || defined(__AMD64__) \ - || defined(__amd64__) - #define MY_CPU_AMD64 +#if defined (_M_X64) \ + || defined (_M_AMD64) \ + || defined (__x86_64__) \ + || defined (__AMD64__) \ + || defined (__amd64__) +#define MY_CPU_AMD64 #ifdef __ILP32__ - #define MY_CPU_NAME "x32" +#define MY_CPU_NAME "x32" #else - #define MY_CPU_NAME "x64" +#define MY_CPU_NAME "x64" #endif - #define MY_CPU_64BIT +#define MY_CPU_64BIT #endif - -#if defined(_M_IX86) \ - || defined(__i386__) - #define MY_CPU_X86 - #define MY_CPU_NAME "x86" - #define MY_CPU_32BIT +#if defined (_M_IX86) \ + || defined (__i386__) +#define MY_CPU_X86 +#define MY_CPU_NAME "x86" +#define MY_CPU_32BIT #endif - -#if defined(_M_ARM64) \ - || defined(__AARCH64EL__) \ - || defined(__AARCH64EB__) \ - || defined(__aarch64__) - #define MY_CPU_ARM64 - #define MY_CPU_NAME "arm64" - #define MY_CPU_64BIT +#if defined (_M_ARM64) \ + || defined (__AARCH64EL__) \ + || defined (__AARCH64EB__) \ + || defined (__aarch64__) +#define MY_CPU_ARM64 +#define MY_CPU_NAME "arm64" +#define MY_CPU_64BIT #endif - -#if defined(_M_ARM) \ - || defined(_M_ARM_NT) \ - || defined(_M_ARMT) \ - || defined(__arm__) \ - || defined(__thumb__) \ - || defined(__ARMEL__) \ - || defined(__ARMEB__) \ - || defined(__THUMBEL__) \ - || defined(__THUMBEB__) - #define MY_CPU_ARM - #define MY_CPU_NAME "arm" - #define MY_CPU_32BIT +#if defined (_M_ARM) \ + || defined (_M_ARM_NT) \ + || defined (_M_ARMT) \ + || defined (__arm__) \ + || defined (__thumb__) \ + || defined (__ARMEL__) \ + || defined (__ARMEB__) \ + || defined (__THUMBEL__) \ + || defined (__THUMBEB__) +#define MY_CPU_ARM +#define MY_CPU_NAME "arm" +#define MY_CPU_32BIT #endif - -#if defined(_M_IA64) \ - || defined(__ia64__) - #define MY_CPU_IA64 - #define MY_CPU_NAME "ia64" - #define MY_CPU_64BIT +#if defined (_M_IA64) \ + || defined (__ia64__) +#define MY_CPU_IA64 +#define MY_CPU_NAME "ia64" +#define MY_CPU_64BIT #endif - -#if defined(__mips64) \ - || defined(__mips64__) \ - || (defined(__mips) && (__mips == 64 || __mips == 4 || __mips == 3)) - #define MY_CPU_NAME "mips64" - #define MY_CPU_64BIT -#elif defined(__mips__) - #define MY_CPU_NAME "mips" - /* #define MY_CPU_32BIT */ +#if defined (__mips64) \ + || defined (__mips64__) \ + || (defined (__mips) && (__mips == 64 || __mips == 4 || __mips == 3)) +#define MY_CPU_NAME "mips64" +#define MY_CPU_64BIT +#elif defined (__mips__) +#define MY_CPU_NAME "mips" +/* #define MY_CPU_32BIT */ #endif - -#if defined(__ppc64__) \ - || defined(__powerpc64__) +#if defined (__ppc64__) \ + || defined (__powerpc64__) #ifdef __ILP32__ - #define MY_CPU_NAME "ppc64-32" +#define MY_CPU_NAME "ppc64-32" #else - #define MY_CPU_NAME "ppc64" +#define MY_CPU_NAME "ppc64" #endif - #define MY_CPU_64BIT -#elif defined(__ppc__) \ - || defined(__powerpc__) - #define MY_CPU_NAME "ppc" - #define MY_CPU_32BIT +#define MY_CPU_64BIT +#elif defined (__ppc__) \ + || defined (__powerpc__) +#define MY_CPU_NAME "ppc" +#define MY_CPU_32BIT #endif - -#if defined(__sparc64__) - #define MY_CPU_NAME "sparc64" - #define MY_CPU_64BIT -#elif defined(__sparc__) - #define MY_CPU_NAME "sparc" - /* #define MY_CPU_32BIT */ +#if defined (__sparc64__) +#define MY_CPU_NAME "sparc64" +#define MY_CPU_64BIT +#elif defined (__sparc__) +#define MY_CPU_NAME "sparc" +/* #define MY_CPU_32BIT */ #endif - -#if defined(MY_CPU_X86) || defined(MY_CPU_AMD64) +#if defined (MY_CPU_X86) || defined (MY_CPU_AMD64) #define MY_CPU_X86_OR_AMD64 #endif - #ifdef _WIN32 #ifdef MY_CPU_ARM - #define MY_CPU_ARM_LE +#define MY_CPU_ARM_LE #endif #ifdef MY_CPU_ARM64 - #define MY_CPU_ARM64_LE +#define MY_CPU_ARM64_LE #endif #ifdef _M_IA64 - #define MY_CPU_IA64_LE +#define MY_CPU_IA64_LE #endif #endif - -#if defined(MY_CPU_X86_OR_AMD64) \ - || defined(MY_CPU_ARM_LE) \ - || defined(MY_CPU_ARM64_LE) \ - || defined(MY_CPU_IA64_LE) \ - || defined(__LITTLE_ENDIAN__) \ - || defined(__ARMEL__) \ - || defined(__THUMBEL__) \ - || defined(__AARCH64EL__) \ - || defined(__MIPSEL__) \ - || defined(__MIPSEL) \ - || defined(_MIPSEL) \ - || defined(__BFIN__) \ - || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) - #define MY_CPU_LE +#if defined (MY_CPU_X86_OR_AMD64) \ + || defined (MY_CPU_ARM_LE) \ + || defined (MY_CPU_ARM64_LE) \ + || defined (MY_CPU_IA64_LE) \ + || defined (__LITTLE_ENDIAN__) \ + || defined (__ARMEL__) \ + || defined (__THUMBEL__) \ + || defined (__AARCH64EL__) \ + || defined (__MIPSEL__) \ + || defined (__MIPSEL) \ + || defined (_MIPSEL) \ + || defined (__BFIN__) \ + || (defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) +#define MY_CPU_LE #endif -#if defined(__BIG_ENDIAN__) \ - || defined(__ARMEB__) \ - || defined(__THUMBEB__) \ - || defined(__AARCH64EB__) \ - || defined(__MIPSEB__) \ - || defined(__MIPSEB) \ - || defined(_MIPSEB) \ - || defined(__m68k__) \ - || defined(__s390__) \ - || defined(__s390x__) \ - || defined(__zarch__) \ - || (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) - #define MY_CPU_BE +#if defined (__BIG_ENDIAN__) \ + || defined (__ARMEB__) \ + || defined (__THUMBEB__) \ + || defined (__AARCH64EB__) \ + || defined (__MIPSEB__) \ + || defined (__MIPSEB) \ + || defined (_MIPSEB) \ + || defined (__m68k__) \ + || defined (__s390__) \ + || defined (__s390x__) \ + || defined (__zarch__) \ + || (defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) +#define MY_CPU_BE #endif - -#if defined(MY_CPU_LE) && defined(MY_CPU_BE) +#if defined (MY_CPU_LE) && defined (MY_CPU_BE) #error Stop_Compiling_Bad_Endian #endif - -#if defined(MY_CPU_32BIT) && defined(MY_CPU_64BIT) +#if defined (MY_CPU_32BIT) && defined (MY_CPU_64BIT) #error Stop_Compiling_Bad_32_64_BIT #endif - #ifndef MY_CPU_NAME #ifdef MY_CPU_LE - #define MY_CPU_NAME "LE" - #elif defined(MY_CPU_BE) - #define MY_CPU_NAME "BE" +#define MY_CPU_NAME "LE" + #elif defined (MY_CPU_BE) +#define MY_CPU_NAME "BE" #else - /* - #define MY_CPU_NAME "" - */ + +/* +#define MY_CPU_NAME "" +*/ #endif #endif - - - - #ifdef MY_CPU_LE - #if defined(MY_CPU_X86_OR_AMD64) \ - || defined(MY_CPU_ARM64) \ - || defined(__ARM_FEATURE_UNALIGNED) - #define MY_CPU_LE_UNALIGN + #if defined (MY_CPU_X86_OR_AMD64) \ + || defined (MY_CPU_ARM64) \ + || defined (__ARM_FEATURE_UNALIGNED) +#define MY_CPU_LE_UNALIGN #endif #endif - #ifdef MY_CPU_LE_UNALIGN -#define GetUi16(p) (*(const UInt16 *)(const void *)(p)) -#define GetUi32(p) (*(const UInt32 *)(const void *)(p)) -#define GetUi64(p) (*(const UInt64 *)(const void *)(p)) +#define GetUi16(p) (*(const UInt16 *)(const void *)(p)) +#define GetUi32(p) (*(const UInt32 *)(const void *)(p)) +#define GetUi64(p) (*(const UInt64 *)(const void *)(p)) -#define SetUi16(p, v) { *(UInt16 *)(p) = (v); } -#define SetUi32(p, v) { *(UInt32 *)(p) = (v); } -#define SetUi64(p, v) { *(UInt64 *)(p) = (v); } +#define SetUi16(p, v) { *(UInt16 *)(p) = (v); } +#define SetUi32(p, v) { *(UInt32 *)(p) = (v); } +#define SetUi64(p, v) { *(UInt64 *)(p) = (v); } #else -#define GetUi16(p) ( (UInt16) ( \ +#define GetUi16(p) ( (UInt16) (\ ((const Byte *)(p))[0] | \ ((UInt16)((const Byte *)(p))[1] << 8) )) -#define GetUi32(p) ( \ +#define GetUi32(p) (\ ((const Byte *)(p))[0] | \ ((UInt32)((const Byte *)(p))[1] << 8) | \ ((UInt32)((const Byte *)(p))[2] << 16) | \ ((UInt32)((const Byte *)(p))[3] << 24)) -#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) +#define GetUi64(p) (GetUi32(p) | ((UInt64)GetUi32(((const Byte *)(p)) + 4) << 32)) -#define SetUi16(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ +#define SetUi16(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v);\ _ppp_[0] = (Byte)_vvv_; \ _ppp_[1] = (Byte)(_vvv_ >> 8); } -#define SetUi32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ +#define SetUi32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v);\ _ppp_[0] = (Byte)_vvv_; \ _ppp_[1] = (Byte)(_vvv_ >> 8); \ _ppp_[2] = (Byte)(_vvv_ >> 16); \ _ppp_[3] = (Byte)(_vvv_ >> 24); } -#define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v); \ +#define SetUi64(p, v) { Byte *_ppp2_ = (Byte *)(p); UInt64 _vvv2_ = (v);\ SetUi32(_ppp2_ , (UInt32)_vvv2_); \ SetUi32(_ppp2_ + 4, (UInt32)(_vvv2_ >> 32)); } #endif #ifdef __has_builtin - #define MY__has_builtin(x) __has_builtin(x) +#define MY__has_builtin(x) __has_builtin(x) #else - #define MY__has_builtin(x) 0 +#define MY__has_builtin(x) 0 #endif -#if defined(MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ (_MSC_VER >= 1300) +#if defined (MY_CPU_LE_UNALIGN) && /* defined(_WIN64) && */ (_MSC_VER >= 1300) /* Note: we use bswap instruction, that is unsupported in 386 cpu */ -#include + #include -#pragma intrinsic(_byteswap_ushort) -#pragma intrinsic(_byteswap_ulong) -#pragma intrinsic(_byteswap_uint64) + #pragma intrinsic(_byteswap_ushort) + #pragma intrinsic(_byteswap_ulong) + #pragma intrinsic(_byteswap_uint64) /* #define GetBe16(p) _byteswap_ushort(*(const UInt16 *)(const Byte *)(p)) */ -#define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) -#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) +#define GetBe32(p) _byteswap_ulong(*(const UInt32 *)(const Byte *)(p)) +#define GetBe64(p) _byteswap_uint64(*(const UInt64 *)(const Byte *)(p)) -#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) +#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = _byteswap_ulong(v) -#elif defined(MY_CPU_LE_UNALIGN) && ( \ - (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ - || (defined(__clang__) && MY__has_builtin(__builtin_bswap16)) ) +#elif defined (MY_CPU_LE_UNALIGN) && ( \ + (defined (__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))) \ + || (defined (__clang__) && MY__has_builtin (__builtin_bswap16))) /* #define GetBe16(p) __builtin_bswap16(*(const UInt16 *)(const Byte *)(p)) */ -#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const Byte *)(p)) -#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const Byte *)(p)) +#define GetBe32(p) __builtin_bswap32(*(const UInt32 *)(const Byte *)(p)) +#define GetBe64(p) __builtin_bswap64(*(const UInt64 *)(const Byte *)(p)) -#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) +#define SetBe32(p, v) (*(UInt32 *)(void *)(p)) = __builtin_bswap32(v) #else -#define GetBe32(p) ( \ +#define GetBe32(p) (\ ((UInt32)((const Byte *)(p))[0] << 24) | \ ((UInt32)((const Byte *)(p))[1] << 16) | \ ((UInt32)((const Byte *)(p))[2] << 8) | \ ((const Byte *)(p))[3] ) -#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) +#define GetBe64(p) (((UInt64)GetBe32(p) << 32) | GetBe32(((const Byte *)(p)) + 4)) -#define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v); \ +#define SetBe32(p, v) { Byte *_ppp_ = (Byte *)(p); UInt32 _vvv_ = (v);\ _ppp_[0] = (Byte)(_vvv_ >> 24); \ _ppp_[1] = (Byte)(_vvv_ >> 16); \ _ppp_[2] = (Byte)(_vvv_ >> 8); \ @@ -286,48 +269,65 @@ MY_CPU_LE_UNALIGN means that CPU is LITTLE ENDIAN and CPU supports unaligned mem #endif - #ifndef GetBe16 -#define GetBe16(p) ( (UInt16) ( \ +#define GetBe16(p) ( (UInt16) (\ ((UInt16)((const Byte *)(p))[0] << 8) | \ ((const Byte *)(p))[1] )) #endif - - #ifdef MY_CPU_X86_OR_AMD64 -typedef struct -{ - UInt32 maxFunc; - UInt32 vendor[3]; - UInt32 ver; - UInt32 b; - UInt32 c; - UInt32 d; +typedef struct { + UInt32 maxFunc; + UInt32 vendor[3]; + UInt32 ver; + UInt32 b; + UInt32 c; + UInt32 d; } Cx86cpuid; -enum -{ +enum { CPU_FIRM_INTEL, CPU_FIRM_AMD, CPU_FIRM_VIA }; -void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d); - -BoolInt x86cpuid_CheckAndRead(Cx86cpuid *p); -int x86cpuid_GetFirm(const Cx86cpuid *p); - -#define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF)) -#define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF)) -#define x86cpuid_GetStepping(ver) (ver & 0xF) - -BoolInt CPU_Is_InOrder(); -BoolInt CPU_Is_Aes_Supported(); -BoolInt CPU_IsSupported_PageGB(); +void +MyCPUID ( + UInt32 function, + UInt32 *a, + UInt32 *b, + UInt32 *c, + UInt32 *d + ); + +BoolInt +x86cpuid_CheckAndRead ( + Cx86cpuid *p + ); + +int +x86cpuid_GetFirm ( + const Cx86cpuid *p + ); + +#define x86cpuid_GetFamily(ver) (((ver >> 16) & 0xFF0) | ((ver >> 8) & 0xF)) +#define x86cpuid_GetModel(ver) (((ver >> 12) & 0xF0) | ((ver >> 4) & 0xF)) +#define x86cpuid_GetStepping(ver) (ver & 0xF) + +BoolInt +CPU_Is_InOrder ( + ); + +BoolInt +CPU_Is_Aes_Supported ( + ); + +BoolInt +CPU_IsSupported_PageGB ( + ); #endif diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.c index 670a9fab12..2102409a4b 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.c @@ -4,393 +4,547 @@ #include "Precomp.h" #ifndef EFIAPI -#include + #include #endif #include "LzFind.h" #include "LzHash.h" -#define kEmptyHashValue 0 -#define kMaxValForNormalize ((UInt32)0xFFFFFFFF) -#define kNormalizeStepMin (1 << 10) /* it must be power of 2 */ -#define kNormalizeMask (~(UInt32)(kNormalizeStepMin - 1)) -#define kMaxHistorySize ((UInt32)7 << 29) +#define kEmptyHashValue 0 +#define kMaxValForNormalize ((UInt32)0xFFFFFFFF) +#define kNormalizeStepMin (1 << 10)/* it must be power of 2 */ +#define kNormalizeMask (~(UInt32)(kNormalizeStepMin - 1)) +#define kMaxHistorySize ((UInt32)7 << 29) -#define kStartMaxLen 3 +#define kStartMaxLen 3 -static void LzInWindow_Free(CMatchFinder *p, ISzAllocPtr alloc) +static void +LzInWindow_Free ( + CMatchFinder *p, + ISzAllocPtr alloc + ) { - if (!p->directInput) - { - ISzAlloc_Free(alloc, p->bufferBase); + if (!p->directInput) { + ISzAlloc_Free (alloc, p->bufferBase); p->bufferBase = NULL; } } /* keepSizeBefore + keepSizeAfter + keepSizeReserv must be < 4G) */ -static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAllocPtr alloc) +static int +LzInWindow_Create ( + CMatchFinder *p, + UInt32 keepSizeReserv, + ISzAllocPtr alloc + ) { - UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv; - if (p->directInput) - { + UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv; + + if (p->directInput) { p->blockSize = blockSize; return 1; } - if (!p->bufferBase || p->blockSize != blockSize) - { - LzInWindow_Free(p, alloc); - p->blockSize = blockSize; - p->bufferBase = (Byte *)ISzAlloc_Alloc(alloc, (size_t)blockSize); + + if (!p->bufferBase || (p->blockSize != blockSize)) { + LzInWindow_Free (p, alloc); + p->blockSize = blockSize; + p->bufferBase = (Byte *)ISzAlloc_Alloc (alloc, (size_t)blockSize); } + return (p->bufferBase != NULL); } -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p) { return p->buffer; } +Byte * +MatchFinder_GetPointerToCurrentPos ( + CMatchFinder *p + ) +{ + return p->buffer; +} -UInt32 MatchFinder_GetNumAvailableBytes(CMatchFinder *p) { return p->streamPos - p->pos; } +UInt32 +MatchFinder_GetNumAvailableBytes ( + CMatchFinder *p + ) +{ + return p->streamPos - p->pos; +} -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue) +void +MatchFinder_ReduceOffsets ( + CMatchFinder *p, + UInt32 subValue + ) { - p->posLimit -= subValue; - p->pos -= subValue; + p->posLimit -= subValue; + p->pos -= subValue; p->streamPos -= subValue; } -static void MatchFinder_ReadBlock(CMatchFinder *p) +static void +MatchFinder_ReadBlock ( + CMatchFinder *p + ) { - if (p->streamEndWasReached || p->result != SZ_OK) + if (p->streamEndWasReached || (p->result != SZ_OK)) { return; + } /* We use (p->streamPos - p->pos) value. (p->streamPos < p->pos) is allowed. */ - if (p->directInput) - { - UInt32 curSize = 0xFFFFFFFF - (p->streamPos - p->pos); - if (curSize > p->directInputRem) + if (p->directInput) { + UInt32 curSize = 0xFFFFFFFF - (p->streamPos - p->pos); + if (curSize > p->directInputRem) { curSize = (UInt32)p->directInputRem; + } + p->directInputRem -= curSize; - p->streamPos += curSize; - if (p->directInputRem == 0) + p->streamPos += curSize; + if (p->directInputRem == 0) { p->streamEndWasReached = 1; + } + return; } - for (;;) - { - Byte *dest = p->buffer + (p->streamPos - p->pos); - size_t size = (p->bufferBase + p->blockSize - dest); - if (size == 0) + for ( ; ;) { + Byte *dest = p->buffer + (p->streamPos - p->pos); + size_t size = (p->bufferBase + p->blockSize - dest); + if (size == 0) { return; + } - p->result = ISeqInStream_Read(p->stream, dest, &size); - if (p->result != SZ_OK) + p->result = ISeqInStream_Read (p->stream, dest, &size); + if (p->result != SZ_OK) { return; - if (size == 0) - { + } + + if (size == 0) { p->streamEndWasReached = 1; return; } + p->streamPos += (UInt32)size; - if (p->streamPos - p->pos > p->keepSizeAfter) + if (p->streamPos - p->pos > p->keepSizeAfter) { return; + } } } -void MatchFinder_MoveBlock(CMatchFinder *p) +void +MatchFinder_MoveBlock ( + CMatchFinder *p + ) { - memmove(p->bufferBase, - p->buffer - p->keepSizeBefore, - (size_t)(p->streamPos - p->pos) + p->keepSizeBefore); + memmove ( + p->bufferBase, + p->buffer - p->keepSizeBefore, + (size_t)(p->streamPos - p->pos) + p->keepSizeBefore + ); p->buffer = p->bufferBase + p->keepSizeBefore; } -int MatchFinder_NeedMove(CMatchFinder *p) +int +MatchFinder_NeedMove ( + CMatchFinder *p + ) { - if (p->directInput) + if (p->directInput) { return 0; + } + /* if (p->streamEndWasReached) return 0; */ return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); } -void MatchFinder_ReadIfRequired(CMatchFinder *p) +void +MatchFinder_ReadIfRequired ( + CMatchFinder *p + ) { - if (p->streamEndWasReached) + if (p->streamEndWasReached) { return; - if (p->keepSizeAfter >= p->streamPos - p->pos) - MatchFinder_ReadBlock(p); + } + + if (p->keepSizeAfter >= p->streamPos - p->pos) { + MatchFinder_ReadBlock (p); + } } -static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p) +static void +MatchFinder_CheckAndMoveAndRead ( + CMatchFinder *p + ) { - if (MatchFinder_NeedMove(p)) - MatchFinder_MoveBlock(p); - MatchFinder_ReadBlock(p); + if (MatchFinder_NeedMove (p)) { + MatchFinder_MoveBlock (p); + } + + MatchFinder_ReadBlock (p); } -static void MatchFinder_SetDefaultSettings(CMatchFinder *p) +static void +MatchFinder_SetDefaultSettings ( + CMatchFinder *p + ) { - p->cutValue = 32; - p->btMode = 1; + p->cutValue = 32; + p->btMode = 1; p->numHashBytes = 4; - p->bigHash = 0; + p->bigHash = 0; } -#define kCrcPoly 0xEDB88320 +#define kCrcPoly 0xEDB88320 -void MatchFinder_Construct(CMatchFinder *p) +void +MatchFinder_Construct ( + CMatchFinder *p + ) { - unsigned i; - p->bufferBase = NULL; - p->directInput = 0; - p->hash = NULL; + unsigned i; + + p->bufferBase = NULL; + p->directInput = 0; + p->hash = NULL; p->expectedDataSize = (UInt64)(Int64)-1; - MatchFinder_SetDefaultSettings(p); + MatchFinder_SetDefaultSettings (p); - for (i = 0; i < 256; i++) - { - UInt32 r = (UInt32)i; - unsigned j; - for (j = 0; j < 8; j++) + for (i = 0; i < 256; i++) { + UInt32 r = (UInt32)i; + unsigned j; + for (j = 0; j < 8; j++) { r = (r >> 1) ^ (kCrcPoly & ((UInt32)0 - (r & 1))); + } + p->crc[i] = r; } } -static void MatchFinder_FreeThisClassMemory(CMatchFinder *p, ISzAllocPtr alloc) +static void +MatchFinder_FreeThisClassMemory ( + CMatchFinder *p, + ISzAllocPtr alloc + ) { - ISzAlloc_Free(alloc, p->hash); + ISzAlloc_Free (alloc, p->hash); p->hash = NULL; } -void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc) +void +MatchFinder_Free ( + CMatchFinder *p, + ISzAllocPtr alloc + ) { - MatchFinder_FreeThisClassMemory(p, alloc); - LzInWindow_Free(p, alloc); + MatchFinder_FreeThisClassMemory (p, alloc); + LzInWindow_Free (p, alloc); } -static CLzRef* AllocRefs(size_t num, ISzAllocPtr alloc) +static CLzRef * +AllocRefs ( + size_t num, + ISzAllocPtr alloc + ) { - size_t sizeInBytes = (size_t)num * sizeof(CLzRef); - if (sizeInBytes / sizeof(CLzRef) != num) + size_t sizeInBytes = (size_t)num * sizeof (CLzRef); + + if (sizeInBytes / sizeof (CLzRef) != num) { return NULL; - return (CLzRef *)ISzAlloc_Alloc(alloc, sizeInBytes); + } + + return (CLzRef *)ISzAlloc_Alloc (alloc, sizeInBytes); } -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAllocPtr alloc) +int +MatchFinder_Create ( + CMatchFinder *p, + UInt32 historySize, + UInt32 keepAddBufferBefore, + UInt32 matchMaxLen, + UInt32 keepAddBufferAfter, + ISzAllocPtr alloc + ) { - UInt32 sizeReserv; + UInt32 sizeReserv; - if (historySize > kMaxHistorySize) - { - MatchFinder_Free(p, alloc); + if (historySize > kMaxHistorySize) { + MatchFinder_Free (p, alloc); return 0; } sizeReserv = historySize >> 1; - if (historySize >= ((UInt32)3 << 30)) sizeReserv = historySize >> 3; - else if (historySize >= ((UInt32)2 << 30)) sizeReserv = historySize >> 2; + if (historySize >= ((UInt32)3 << 30)) { + sizeReserv = historySize >> 3; + } else if (historySize >= ((UInt32)2 << 30)) { + sizeReserv = historySize >> 2; + } sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19); p->keepSizeBefore = historySize + keepAddBufferBefore + 1; - p->keepSizeAfter = matchMaxLen + keepAddBufferAfter; + p->keepSizeAfter = matchMaxLen + keepAddBufferAfter; /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */ - if (LzInWindow_Create(p, sizeReserv, alloc)) - { - UInt32 newCyclicBufferSize = historySize + 1; - UInt32 hs; + if (LzInWindow_Create (p, sizeReserv, alloc)) { + UInt32 newCyclicBufferSize = historySize + 1; + UInt32 hs; p->matchMaxLen = matchMaxLen; { p->fixedHashSize = 0; - if (p->numHashBytes == 2) + if (p->numHashBytes == 2) { hs = (1 << 16) - 1; - else - { + } else { hs = historySize; - if (hs > p->expectedDataSize) + if (hs > p->expectedDataSize) { hs = (UInt32)p->expectedDataSize; - if (hs != 0) + } + + if (hs != 0) { hs--; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); + } + + hs |= (hs >> 1); + hs |= (hs >> 2); + hs |= (hs >> 4); + hs |= (hs >> 8); hs >>= 1; - hs |= 0xFFFF; /* don't change it! It's required for Deflate */ - if (hs > (1 << 24)) - { - if (p->numHashBytes == 3) + hs |= 0xFFFF; /* don't change it! It's required for Deflate */ + if (hs > (1 << 24)) { + if (p->numHashBytes == 3) { hs = (1 << 24) - 1; - else + } else { hs >>= 1; + } + /* if (bigHash) mode, GetHeads4b() in LzFindMt.c needs (hs >= ((1 << 24) - 1))) */ } } + p->hashMask = hs; hs++; - if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; - if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; - if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size; + if (p->numHashBytes > 2) { + p->fixedHashSize += kHash2Size; + } + + if (p->numHashBytes > 3) { + p->fixedHashSize += kHash3Size; + } + + if (p->numHashBytes > 4) { + p->fixedHashSize += kHash4Size; + } + hs += p->fixedHashSize; } { - size_t newSize; - size_t numSons; - p->historySize = historySize; - p->hashSizeSum = hs; + size_t newSize; + size_t numSons; + p->historySize = historySize; + p->hashSizeSum = hs; p->cyclicBufferSize = newCyclicBufferSize; numSons = newCyclicBufferSize; - if (p->btMode) + if (p->btMode) { numSons <<= 1; + } + newSize = hs + numSons; - if (p->hash && p->numRefs == newSize) + if (p->hash && (p->numRefs == newSize)) { return 1; + } - MatchFinder_FreeThisClassMemory(p, alloc); + MatchFinder_FreeThisClassMemory (p, alloc); p->numRefs = newSize; - p->hash = AllocRefs(newSize, alloc); + p->hash = AllocRefs (newSize, alloc); - if (p->hash) - { + if (p->hash) { p->son = p->hash + p->hashSizeSum; return 1; } } } - MatchFinder_Free(p, alloc); + MatchFinder_Free (p, alloc); return 0; } -static void MatchFinder_SetLimits(CMatchFinder *p) +static void +MatchFinder_SetLimits ( + CMatchFinder *p + ) { - UInt32 limit = kMaxValForNormalize - p->pos; - UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos; + UInt32 limit = kMaxValForNormalize - p->pos; + UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos; - if (limit2 < limit) + if (limit2 < limit) { limit = limit2; + } + limit2 = p->streamPos - p->pos; - if (limit2 <= p->keepSizeAfter) - { - if (limit2 > 0) + if (limit2 <= p->keepSizeAfter) { + if (limit2 > 0) { limit2 = 1; - } - else + } + } else { limit2 -= p->keepSizeAfter; + } - if (limit2 < limit) + if (limit2 < limit) { limit = limit2; + } { - UInt32 lenLimit = p->streamPos - p->pos; - if (lenLimit > p->matchMaxLen) + UInt32 lenLimit = p->streamPos - p->pos; + if (lenLimit > p->matchMaxLen) { lenLimit = p->matchMaxLen; + } + p->lenLimit = lenLimit; } p->posLimit = p->pos + limit; } - -void MatchFinder_Init_LowHash(CMatchFinder *p) +void +MatchFinder_Init_LowHash ( + CMatchFinder *p + ) { - size_t i; - CLzRef *items = p->hash; - size_t numItems = p->fixedHashSize; - for (i = 0; i < numItems; i++) + size_t i; + CLzRef *items = p->hash; + size_t numItems = p->fixedHashSize; + + for (i = 0; i < numItems; i++) { items[i] = kEmptyHashValue; + } } - -void MatchFinder_Init_HighHash(CMatchFinder *p) +void +MatchFinder_Init_HighHash ( + CMatchFinder *p + ) { - size_t i; - CLzRef *items = p->hash + p->fixedHashSize; - size_t numItems = (size_t)p->hashMask + 1; - for (i = 0; i < numItems; i++) + size_t i; + CLzRef *items = p->hash + p->fixedHashSize; + size_t numItems = (size_t)p->hashMask + 1; + + for (i = 0; i < numItems; i++) { items[i] = kEmptyHashValue; + } } - -void MatchFinder_Init_3(CMatchFinder *p, int readData) +void +MatchFinder_Init_3 ( + CMatchFinder *p, + int readData + ) { - p->cyclicBufferPos = 0; - p->buffer = p->bufferBase; - p->pos = - p->streamPos = p->cyclicBufferSize; - p->result = SZ_OK; + p->cyclicBufferPos = 0; + p->buffer = p->bufferBase; + p->pos = + p->streamPos = p->cyclicBufferSize; + p->result = SZ_OK; p->streamEndWasReached = 0; - if (readData) - MatchFinder_ReadBlock(p); + if (readData) { + MatchFinder_ReadBlock (p); + } - MatchFinder_SetLimits(p); + MatchFinder_SetLimits (p); } - -void MatchFinder_Init(CMatchFinder *p) +void +MatchFinder_Init ( + CMatchFinder *p + ) { - MatchFinder_Init_HighHash(p); - MatchFinder_Init_LowHash(p); - MatchFinder_Init_3(p, True); + MatchFinder_Init_HighHash (p); + MatchFinder_Init_LowHash (p); + MatchFinder_Init_3 (p, True); } - -static UInt32 MatchFinder_GetSubValue(CMatchFinder *p) +static UInt32 +MatchFinder_GetSubValue ( + CMatchFinder *p + ) { return (p->pos - p->historySize - 1) & kNormalizeMask; } -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems) +void +MatchFinder_Normalize3 ( + UInt32 subValue, + CLzRef *items, + size_t numItems + ) { - size_t i; - for (i = 0; i < numItems; i++) - { - UInt32 value = items[i]; - if (value <= subValue) + size_t i; + + for (i = 0; i < numItems; i++) { + UInt32 value = items[i]; + if (value <= subValue) { value = kEmptyHashValue; - else + } else { value -= subValue; + } + items[i] = value; } } -static void MatchFinder_Normalize(CMatchFinder *p) +static void +MatchFinder_Normalize ( + CMatchFinder *p + ) { - UInt32 subValue = MatchFinder_GetSubValue(p); - MatchFinder_Normalize3(subValue, p->hash, p->numRefs); - MatchFinder_ReduceOffsets(p, subValue); -} + UInt32 subValue = MatchFinder_GetSubValue (p); + MatchFinder_Normalize3 (subValue, p->hash, p->numRefs); + MatchFinder_ReduceOffsets (p, subValue); +} MY_NO_INLINE -static void MatchFinder_CheckLimits(CMatchFinder *p) +static void +MatchFinder_CheckLimits ( + CMatchFinder *p + ) { - if (p->pos == kMaxValForNormalize) - MatchFinder_Normalize(p); - if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos) - MatchFinder_CheckAndMoveAndRead(p); - if (p->cyclicBufferPos == p->cyclicBufferSize) + if (p->pos == kMaxValForNormalize) { + MatchFinder_Normalize (p); + } + + if (!p->streamEndWasReached && (p->keepSizeAfter == p->streamPos - p->pos)) { + MatchFinder_CheckAndMoveAndRead (p); + } + + if (p->cyclicBufferPos == p->cyclicBufferSize) { p->cyclicBufferPos = 0; - MatchFinder_SetLimits(p); -} + } + MatchFinder_SetLimits (p); +} /* (lenLimit > maxLen) */ MY_FORCE_INLINE -static UInt32 * Hc_GetMatchesSpec(unsigned lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, unsigned maxLen) +static UInt32 * +Hc_GetMatchesSpec ( + unsigned lenLimit, + UInt32 curMatch, + UInt32 pos, + const Byte *cur, + CLzRef *son, + UInt32 _cyclicBufferPos, + UInt32 _cyclicBufferSize, + UInt32 cutValue, + UInt32 *distances, + unsigned maxLen + ) { /* son[_cyclicBufferPos] = curMatch; @@ -421,151 +575,165 @@ static UInt32 * Hc_GetMatchesSpec(unsigned lenLimit, UInt32 curMatch, UInt32 pos } */ - const Byte *lim = cur + lenLimit; + const Byte *lim = cur + lenLimit; + son[_cyclicBufferPos] = curMatch; - do - { - UInt32 delta = pos - curMatch; - if (delta >= _cyclicBufferSize) + do { + UInt32 delta = pos - curMatch; + if (delta >= _cyclicBufferSize) { break; + } + { - ptrdiff_t diff; + ptrdiff_t diff; curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; - diff = (ptrdiff_t)0 - delta; - if (cur[maxLen] == cur[maxLen + diff]) - { - const Byte *c = cur; - while (*c == c[diff]) - { - if (++c == lim) - { + diff = (ptrdiff_t)0 - delta; + if (cur[maxLen] == cur[maxLen + diff]) { + const Byte *c = cur; + while (*c == c[diff]) { + if (++c == lim) { distances[0] = (UInt32)(lim - cur); distances[1] = delta - 1; return distances + 2; } } + { - unsigned len = (unsigned)(c - cur); - if (maxLen < len) - { - maxLen = len; + unsigned len = (unsigned)(c - cur); + if (maxLen < len) { + maxLen = len; distances[0] = (UInt32)len; distances[1] = delta - 1; - distances += 2; + distances += 2; } } } } - } - while (--cutValue); + } while (--cutValue); return distances; } - MY_FORCE_INLINE -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) +UInt32 * +GetMatchesSpec1 ( + UInt32 lenLimit, + UInt32 curMatch, + UInt32 pos, + const Byte *cur, + CLzRef *son, + UInt32 _cyclicBufferPos, + UInt32 _cyclicBufferSize, + UInt32 cutValue, + UInt32 *distances, + UInt32 maxLen + ) { - CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); - unsigned len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { + CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; + CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); + unsigned len0 = 0, len1 = 0; + + for ( ; ;) { + UInt32 delta = pos - curMatch; + if ((cutValue-- == 0) || (delta >= _cyclicBufferSize)) { *ptr0 = *ptr1 = kEmptyHashValue; return distances; } + { - CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - unsigned len = (len0 < len1 ? len0 : len1); - UInt32 pair0 = pair[0]; - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) + CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); + const Byte *pb = cur - delta; + unsigned len = (len0 < len1 ? len0 : len1); + UInt32 pair0 = pair[0]; + if (pb[len] == cur[len]) { + if ((++len != lenLimit) && (pb[len] == cur[len])) { + while (++len != lenLimit) { + if (pb[len] != cur[len]) { break; - if (maxLen < len) - { - maxLen = (UInt32)len; + } + } + } + + if (maxLen < len) { + maxLen = (UInt32)len; *distances++ = (UInt32)len; *distances++ = delta - 1; - if (len == lenLimit) - { + if (len == lenLimit) { *ptr1 = pair0; *ptr0 = pair[1]; return distances; } } } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; + + if (pb[len] < cur[len]) { + *ptr1 = curMatch; + ptr1 = pair + 1; curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; + len1 = len; + } else { + *ptr0 = curMatch; + ptr0 = pair; curMatch = *ptr0; - len0 = len; + len0 = len; } } } } -static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) +static void +SkipMatchesSpec ( + UInt32 lenLimit, + UInt32 curMatch, + UInt32 pos, + const Byte *cur, + CLzRef *son, + UInt32 _cyclicBufferPos, + UInt32 _cyclicBufferSize, + UInt32 cutValue + ) { - CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; - CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); - unsigned len0 = 0, len1 = 0; - for (;;) - { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { + CLzRef *ptr0 = son + ((size_t)_cyclicBufferPos << 1) + 1; + CLzRef *ptr1 = son + ((size_t)_cyclicBufferPos << 1); + unsigned len0 = 0, len1 = 0; + + for ( ; ;) { + UInt32 delta = pos - curMatch; + if ((cutValue-- == 0) || (delta >= _cyclicBufferSize)) { *ptr0 = *ptr1 = kEmptyHashValue; return; } + { - CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - unsigned len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - while (++len != lenLimit) - if (pb[len] != cur[len]) + CLzRef *pair = son + ((size_t)(_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); + const Byte *pb = cur - delta; + unsigned len = (len0 < len1 ? len0 : len1); + if (pb[len] == cur[len]) { + while (++len != lenLimit) { + if (pb[len] != cur[len]) { break; + } + } + { - if (len == lenLimit) - { + if (len == lenLimit) { *ptr1 = pair[0]; *ptr0 = pair[1]; return; } } } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; + + if (pb[len] < cur[len]) { + *ptr1 = curMatch; + ptr1 = pair + 1; curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; + len1 = len; + } else { + *ptr0 = curMatch; + ptr0 = pair; curMatch = *ptr0; - len0 = len; + len0 = len; } } } @@ -576,19 +744,25 @@ static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const p->buffer++; \ if (++p->pos == p->posLimit) MatchFinder_CheckLimits(p); -#define MOVE_POS_RET MOVE_POS return (UInt32)offset; +#define MOVE_POS_RET MOVE_POS return (UInt32)offset; -static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; } +static void +MatchFinder_MovePos ( + CMatchFinder *p + ) +{ + MOVE_POS; +} #define GET_MATCHES_HEADER2(minLen, ret_op) \ unsigned lenLimit; UInt32 hv; const Byte *cur; UInt32 curMatch; \ lenLimit = (unsigned)p->lenLimit; { if (lenLimit < minLen) { MatchFinder_MovePos(p); ret_op; }} \ cur = p->buffer; -#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0) -#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue) +#define GET_MATCHES_HEADER(minLen) GET_MATCHES_HEADER2(minLen, return 0) +#define SKIP_HEADER(minLen) GET_MATCHES_HEADER2(minLen, continue) -#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue +#define MF_PARAMS(p) p->pos, p->buffer, p->son, p->cyclicBufferPos, p->cyclicBufferSize, p->cutValue #define GET_MATCHES_FOOTER(offset, maxLen) \ offset = (unsigned)(GetMatchesSpec1((UInt32)lenLimit, curMatch, MF_PARAMS(p), \ @@ -597,128 +771,143 @@ static void MatchFinder_MovePos(CMatchFinder *p) { MOVE_POS; } #define SKIP_FOOTER \ SkipMatchesSpec((UInt32)lenLimit, curMatch, MF_PARAMS(p)); MOVE_POS; -#define UPDATE_maxLen { \ +#define UPDATE_maxLen {\ ptrdiff_t diff = (ptrdiff_t)0 - d2; \ const Byte *c = cur + maxLen; \ const Byte *lim = cur + lenLimit; \ for (; c != lim; c++) if (*(c + diff) != *c) break; \ maxLen = (unsigned)(c - cur); } -static UInt32 Bt2_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +static UInt32 +Bt2_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - unsigned offset; - GET_MATCHES_HEADER(2) + unsigned offset; + + GET_MATCHES_HEADER (2) HASH2_CALC; - curMatch = p->hash[hv]; + curMatch = p->hash[hv]; p->hash[hv] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 1) + offset = 0; + GET_MATCHES_FOOTER (offset, 1) } -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +UInt32 +Bt3Zip_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - unsigned offset; - GET_MATCHES_HEADER(3) + unsigned offset; + + GET_MATCHES_HEADER (3) HASH_ZIP_CALC; - curMatch = p->hash[hv]; + curMatch = p->hash[hv]; p->hash[hv] = p->pos; - offset = 0; - GET_MATCHES_FOOTER(offset, 2) + offset = 0; + GET_MATCHES_FOOTER (offset, 2) } -static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +static UInt32 +Bt3_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - UInt32 h2, d2, pos; - unsigned maxLen, offset; - UInt32 *hash; - GET_MATCHES_HEADER(3) + UInt32 h2, d2, pos; + unsigned maxLen, offset; + UInt32 *hash; + + GET_MATCHES_HEADER (3) HASH3_CALC; hash = p->hash; - pos = p->pos; + pos = p->pos; d2 = pos - hash[h2]; curMatch = (hash + kFix3HashSize)[hv]; - hash[h2] = pos; + hash[h2] = pos; (hash + kFix3HashSize)[hv] = pos; maxLen = 2; offset = 0; - if (d2 < p->cyclicBufferSize && *(cur - d2) == *cur) - { + if ((d2 < p->cyclicBufferSize) && (*(cur - d2) == *cur)) { UPDATE_maxLen - distances[0] = (UInt32)maxLen; + distances[0] = (UInt32)maxLen; distances[1] = d2 - 1; - offset = 2; - if (maxLen == lenLimit) - { - SkipMatchesSpec((UInt32)lenLimit, curMatch, MF_PARAMS(p)); + offset = 2; + if (maxLen == lenLimit) { + SkipMatchesSpec ((UInt32)lenLimit, curMatch, MF_PARAMS (p)); MOVE_POS_RET; } } - GET_MATCHES_FOOTER(offset, maxLen) + GET_MATCHES_FOOTER (offset, maxLen) } -static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +static UInt32 +Bt4_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - UInt32 h2, h3, d2, d3, pos; - unsigned maxLen, offset; - UInt32 *hash; - GET_MATCHES_HEADER(4) + UInt32 h2, h3, d2, d3, pos; + unsigned maxLen, offset; + UInt32 *hash; + + GET_MATCHES_HEADER (4) HASH4_CALC; hash = p->hash; - pos = p->pos; + pos = p->pos; - d2 = pos - hash[ h2]; + d2 = pos - hash[h2]; d3 = pos - (hash + kFix3HashSize)[h3]; curMatch = (hash + kFix4HashSize)[hv]; - hash[ h2] = pos; + hash[h2] = pos; (hash + kFix3HashSize)[h3] = pos; (hash + kFix4HashSize)[hv] = pos; maxLen = 0; offset = 0; - if (d2 < p->cyclicBufferSize && *(cur - d2) == *cur) - { - maxLen = 2; + if ((d2 < p->cyclicBufferSize) && (*(cur - d2) == *cur)) { + maxLen = 2; distances[0] = 2; distances[1] = d2 - 1; - offset = 2; + offset = 2; } - if (d2 != d3 && d3 < p->cyclicBufferSize && *(cur - d3) == *cur) - { - maxLen = 3; + if ((d2 != d3) && (d3 < p->cyclicBufferSize) && (*(cur - d3) == *cur)) { + maxLen = 3; distances[(size_t)offset + 1] = d3 - 1; - offset += 2; - d2 = d3; + offset += 2; + d2 = d3; } - if (offset != 0) - { + if (offset != 0) { UPDATE_maxLen - distances[(size_t)offset - 2] = (UInt32)maxLen; - if (maxLen == lenLimit) - { - SkipMatchesSpec((UInt32)lenLimit, curMatch, MF_PARAMS(p)); + distances[(size_t)offset - 2] = (UInt32)maxLen; + if (maxLen == lenLimit) { + SkipMatchesSpec ((UInt32)lenLimit, curMatch, MF_PARAMS (p)); MOVE_POS_RET; } } - if (maxLen < 3) + if (maxLen < 3) { maxLen = 3; + } - GET_MATCHES_FOOTER(offset, maxLen) + GET_MATCHES_FOOTER (offset, maxLen) } /* @@ -797,63 +986,69 @@ static UInt32 Bt5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) GET_MATCHES_FOOTER(offset, maxLen) } */ - -static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +static UInt32 +Hc4_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - UInt32 h2, h3, d2, d3, pos; - unsigned maxLen, offset; - UInt32 *hash; - GET_MATCHES_HEADER(4) + UInt32 h2, h3, d2, d3, pos; + unsigned maxLen, offset; + UInt32 *hash; + + GET_MATCHES_HEADER (4) HASH4_CALC; hash = p->hash; - pos = p->pos; + pos = p->pos; - d2 = pos - hash[ h2]; + d2 = pos - hash[h2]; d3 = pos - (hash + kFix3HashSize)[h3]; curMatch = (hash + kFix4HashSize)[hv]; - hash[ h2] = pos; + hash[h2] = pos; (hash + kFix3HashSize)[h3] = pos; (hash + kFix4HashSize)[hv] = pos; maxLen = 0; offset = 0; - if (d2 < p->cyclicBufferSize && *(cur - d2) == *cur) - { - maxLen = 2; + if ((d2 < p->cyclicBufferSize) && (*(cur - d2) == *cur)) { + maxLen = 2; distances[0] = 2; distances[1] = d2 - 1; - offset = 2; + offset = 2; } - if (d2 != d3 && d3 < p->cyclicBufferSize && *(cur - d3) == *cur) - { - maxLen = 3; + if ((d2 != d3) && (d3 < p->cyclicBufferSize) && (*(cur - d3) == *cur)) { + maxLen = 3; distances[(size_t)offset + 1] = d3 - 1; - offset += 2; - d2 = d3; + offset += 2; + d2 = d3; } - if (offset != 0) - { + if (offset != 0) { UPDATE_maxLen - distances[(size_t)offset - 2] = (UInt32)maxLen; - if (maxLen == lenLimit) - { + distances[(size_t)offset - 2] = (UInt32)maxLen; + if (maxLen == lenLimit) { p->son[p->cyclicBufferPos] = curMatch; MOVE_POS_RET; } } - if (maxLen < 3) + if (maxLen < 3) { maxLen = 3; + } - offset = (unsigned)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances + offset, maxLen) - (distances)); + offset = (unsigned)(Hc_GetMatchesSpec ( + lenLimit, + curMatch, + MF_PARAMS (p), + distances + offset, + maxLen + ) - (distances)); MOVE_POS_RET } @@ -935,78 +1130,95 @@ static UInt32 Hc5_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) MOVE_POS_RET } */ - -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) +UInt32 +Hc3Zip_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ) { - unsigned offset; - GET_MATCHES_HEADER(3) + unsigned offset; + + GET_MATCHES_HEADER (3) HASH_ZIP_CALC; - curMatch = p->hash[hv]; + curMatch = p->hash[hv]; p->hash[hv] = p->pos; - offset = (unsigned)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances, 2) - (distances)); + offset = (unsigned)(Hc_GetMatchesSpec ( + lenLimit, + curMatch, + MF_PARAMS (p), + distances, + 2 + ) - (distances)); MOVE_POS_RET } -static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +static void +Bt2_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - SKIP_HEADER(2) + do { + SKIP_HEADER (2) HASH2_CALC; - curMatch = p->hash[hv]; + curMatch = p->hash[hv]; p->hash[hv] = p->pos; SKIP_FOOTER - } - while (--num != 0); + } while (--num != 0); } -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +void +Bt3Zip_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - SKIP_HEADER(3) + do { + SKIP_HEADER (3) HASH_ZIP_CALC; - curMatch = p->hash[hv]; + curMatch = p->hash[hv]; p->hash[hv] = p->pos; SKIP_FOOTER - } - while (--num != 0); + } while (--num != 0); } -static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +static void +Bt3_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - UInt32 h2; - UInt32 *hash; - SKIP_HEADER(3) + do { + UInt32 h2; + UInt32 *hash; + SKIP_HEADER (3) HASH3_CALC; - hash = p->hash; - curMatch = (hash + kFix3HashSize)[hv]; - hash[h2] = - (hash + kFix3HashSize)[hv] = p->pos; + hash = p->hash; + curMatch = (hash + kFix3HashSize)[hv]; + hash[h2] = + (hash + kFix3HashSize)[hv] = p->pos; SKIP_FOOTER - } - while (--num != 0); + } while (--num != 0); } -static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +static void +Bt4_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - UInt32 h2, h3; - UInt32 *hash; - SKIP_HEADER(4) + do { + UInt32 h2, h3; + UInt32 *hash; + SKIP_HEADER (4) HASH4_CALC; - hash = p->hash; - curMatch = (hash + kFix4HashSize)[hv]; - hash[ h2] = - (hash + kFix3HashSize)[h3] = - (hash + kFix4HashSize)[hv] = p->pos; + hash = p->hash; + curMatch = (hash + kFix4HashSize)[hv]; + hash[h2] = + (hash + kFix3HashSize)[h3] = + (hash + kFix4HashSize)[hv] = p->pos; SKIP_FOOTER - } - while (--num != 0); + } while (--num != 0); } /* @@ -1029,24 +1241,25 @@ static void Bt5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) while (--num != 0); } */ - -static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +static void +Hc4_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - UInt32 h2, h3; - UInt32 *hash; - SKIP_HEADER(4) + do { + UInt32 h2, h3; + UInt32 *hash; + SKIP_HEADER (4) HASH4_CALC; - hash = p->hash; - curMatch = (hash + kFix4HashSize)[hv]; - hash[ h2] = - (hash + kFix3HashSize)[h3] = - (hash + kFix4HashSize)[hv] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; + hash = p->hash; + curMatch = (hash + kFix4HashSize)[hv]; + hash[h2] = + (hash + kFix3HashSize)[h3] = + (hash + kFix4HashSize)[hv] = p->pos; + p->son[p->cyclicBufferPos] = curMatch; MOVE_POS - } - while (--num != 0); + } while (--num != 0); } /* @@ -1070,33 +1283,38 @@ static void Hc5_MatchFinder_Skip(CMatchFinder *p, UInt32 num) while (--num != 0); } */ - -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) +void +Hc3Zip_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ) { - do - { - SKIP_HEADER(3) + do { + SKIP_HEADER (3) HASH_ZIP_CALC; - curMatch = p->hash[hv]; - p->hash[hv] = p->pos; + curMatch = p->hash[hv]; + p->hash[hv] = p->pos; p->son[p->cyclicBufferPos] = curMatch; MOVE_POS - } - while (--num != 0); + } while (--num != 0); } -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) +void +MatchFinder_CreateVTable ( + CMatchFinder *p, + IMatchFinder *vTable + ) { - vTable->Init = (Mf_Init_Func)MatchFinder_Init; - vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes; + vTable->Init = (Mf_Init_Func)MatchFinder_Init; + vTable->GetNumAvailableBytes = (Mf_GetNumAvailableBytes_Func)MatchFinder_GetNumAvailableBytes; vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos; - if (!p->btMode) - { + if (!p->btMode) { /* if (p->numHashBytes <= 4) */ { vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; + vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; } + /* else { @@ -1104,22 +1322,18 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) vTable->Skip = (Mf_Skip_Func)Hc5_MatchFinder_Skip; } */ - } - else if (p->numHashBytes == 2) - { + } else if (p->numHashBytes == 2) { vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; - } - else if (p->numHashBytes == 3) - { + vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; + } else if (p->numHashBytes == 3) { vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; - } - else /* if (p->numHashBytes == 4) */ - { + vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; + } else { + /* if (p->numHashBytes == 4) */ vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; + vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; } + /* else { diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.h index 61bb9dd302..923d3e3d95 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzFind.h @@ -10,77 +10,126 @@ EXTERN_C_BEGIN typedef UInt32 CLzRef; -typedef struct _CMatchFinder -{ - Byte *buffer; - UInt32 pos; - UInt32 posLimit; - UInt32 streamPos; - UInt32 lenLimit; - - UInt32 cyclicBufferPos; - UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */ - - Byte streamEndWasReached; - Byte btMode; - Byte bigHash; - Byte directInput; - - UInt32 matchMaxLen; - CLzRef *hash; - CLzRef *son; - UInt32 hashMask; - UInt32 cutValue; - - Byte *bufferBase; - ISeqInStream *stream; - - UInt32 blockSize; - UInt32 keepSizeBefore; - UInt32 keepSizeAfter; - - UInt32 numHashBytes; - size_t directInputRem; - UInt32 historySize; - UInt32 fixedHashSize; - UInt32 hashSizeSum; - SRes result; - UInt32 crc[256]; - size_t numRefs; - - UInt64 expectedDataSize; +typedef struct _CMatchFinder { + Byte *buffer; + UInt32 pos; + UInt32 posLimit; + UInt32 streamPos; + UInt32 lenLimit; + + UInt32 cyclicBufferPos; + UInt32 cyclicBufferSize; /* it must be = (historySize + 1) */ + + Byte streamEndWasReached; + Byte btMode; + Byte bigHash; + Byte directInput; + + UInt32 matchMaxLen; + CLzRef *hash; + CLzRef *son; + UInt32 hashMask; + UInt32 cutValue; + + Byte *bufferBase; + ISeqInStream *stream; + + UInt32 blockSize; + UInt32 keepSizeBefore; + UInt32 keepSizeAfter; + + UInt32 numHashBytes; + size_t directInputRem; + UInt32 historySize; + UInt32 fixedHashSize; + UInt32 hashSizeSum; + SRes result; + UInt32 crc[256]; + size_t numRefs; + + UInt64 expectedDataSize; } CMatchFinder; -#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer) +#define Inline_MatchFinder_GetPointerToCurrentPos(p) ((p)->buffer) -#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos) +#define Inline_MatchFinder_GetNumAvailableBytes(p) ((p)->streamPos - (p)->pos) #define Inline_MatchFinder_IsFinishedOK(p) \ ((p)->streamEndWasReached \ && (p)->streamPos == (p)->pos \ && (!(p)->directInput || (p)->directInputRem == 0)) -int MatchFinder_NeedMove(CMatchFinder *p); -Byte *MatchFinder_GetPointerToCurrentPos(CMatchFinder *p); -void MatchFinder_MoveBlock(CMatchFinder *p); -void MatchFinder_ReadIfRequired(CMatchFinder *p); +int +MatchFinder_NeedMove ( + CMatchFinder *p + ); -void MatchFinder_Construct(CMatchFinder *p); +Byte * +MatchFinder_GetPointerToCurrentPos ( + CMatchFinder *p + ); + +void +MatchFinder_MoveBlock ( + CMatchFinder *p + ); + +void +MatchFinder_ReadIfRequired ( + CMatchFinder *p + ); + +void +MatchFinder_Construct ( + CMatchFinder *p + ); /* Conditions: historySize <= 3 GB keepAddBufferBefore + matchMaxLen + keepAddBufferAfter < 511MB */ -int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAllocPtr alloc); -void MatchFinder_Free(CMatchFinder *p, ISzAllocPtr alloc); -void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, size_t numItems); -void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue); - -UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *buffer, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 _cutValue, - UInt32 *distances, UInt32 maxLen); +int +MatchFinder_Create ( + CMatchFinder *p, + UInt32 historySize, + UInt32 keepAddBufferBefore, + UInt32 matchMaxLen, + UInt32 keepAddBufferAfter, + ISzAllocPtr alloc + ); + +void +MatchFinder_Free ( + CMatchFinder *p, + ISzAllocPtr alloc + ); + +void +MatchFinder_Normalize3 ( + UInt32 subValue, + CLzRef *items, + size_t numItems + ); + +void +MatchFinder_ReduceOffsets ( + CMatchFinder *p, + UInt32 subValue + ); + +UInt32 * +GetMatchesSpec1 ( + UInt32 lenLimit, + UInt32 curMatch, + UInt32 pos, + const Byte *buffer, + CLzRef *son, + UInt32 _cyclicBufferPos, + UInt32 _cyclicBufferSize, + UInt32 _cutValue, + UInt32 *distances, + UInt32 maxLen + ); /* Conditions: @@ -88,33 +137,82 @@ Conditions: Mf_GetPointerToCurrentPos_Func's result must be used only before any other function */ -typedef void (*Mf_Init_Func)(void *object); -typedef UInt32 (*Mf_GetNumAvailableBytes_Func)(void *object); -typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)(void *object); -typedef UInt32 (*Mf_GetMatches_Func)(void *object, UInt32 *distances); -typedef void (*Mf_Skip_Func)(void *object, UInt32); - -typedef struct _IMatchFinder -{ - Mf_Init_Func Init; - Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; - Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos; - Mf_GetMatches_Func GetMatches; - Mf_Skip_Func Skip; +typedef void (*Mf_Init_Func)( + void *object + ); +typedef UInt32 (*Mf_GetNumAvailableBytes_Func)( + void *object + ); +typedef const Byte * (*Mf_GetPointerToCurrentPos_Func)( + void *object + ); +typedef UInt32 (*Mf_GetMatches_Func)( + void *object, + UInt32 *distances + ); +typedef void (*Mf_Skip_Func)( + void *object, + UInt32 + ); + +typedef struct _IMatchFinder { + Mf_Init_Func Init; + Mf_GetNumAvailableBytes_Func GetNumAvailableBytes; + Mf_GetPointerToCurrentPos_Func GetPointerToCurrentPos; + Mf_GetMatches_Func GetMatches; + Mf_Skip_Func Skip; } IMatchFinder; -void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable); - -void MatchFinder_Init_LowHash(CMatchFinder *p); -void MatchFinder_Init_HighHash(CMatchFinder *p); -void MatchFinder_Init_3(CMatchFinder *p, int readData); -void MatchFinder_Init(CMatchFinder *p); - -UInt32 Bt3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); -UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances); - -void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); -void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num); +void +MatchFinder_CreateVTable ( + CMatchFinder *p, + IMatchFinder *vTable + ); + +void +MatchFinder_Init_LowHash ( + CMatchFinder *p + ); + +void +MatchFinder_Init_HighHash ( + CMatchFinder *p + ); + +void +MatchFinder_Init_3 ( + CMatchFinder *p, + int readData + ); + +void +MatchFinder_Init ( + CMatchFinder *p + ); + +UInt32 +Bt3Zip_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ); + +UInt32 +Hc3Zip_MatchFinder_GetMatches ( + CMatchFinder *p, + UInt32 *distances + ); + +void +Bt3Zip_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ); + +void +Hc3Zip_MatchFinder_Skip ( + CMatchFinder *p, + UInt32 num + ); EXTERN_C_END diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzHash.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzHash.h index 2191444072..eec8bb13bd 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzHash.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzHash.h @@ -4,29 +4,29 @@ #ifndef __LZ_HASH_H #define __LZ_HASH_H -#define kHash2Size (1 << 10) -#define kHash3Size (1 << 16) -#define kHash4Size (1 << 20) +#define kHash2Size (1 << 10) +#define kHash3Size (1 << 16) +#define kHash4Size (1 << 20) -#define kFix3HashSize (kHash2Size) -#define kFix4HashSize (kHash2Size + kHash3Size) -#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size) +#define kFix3HashSize (kHash2Size) +#define kFix4HashSize (kHash2Size + kHash3Size) +#define kFix5HashSize (kHash2Size + kHash3Size + kHash4Size) -#define HASH2_CALC hv = cur[0] | ((UInt32)cur[1] << 8); +#define HASH2_CALC hv = cur[0] | ((UInt32)cur[1] << 8); -#define HASH3_CALC { \ +#define HASH3_CALC {\ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ hv = (temp ^ ((UInt32)cur[2] << 8)) & p->hashMask; } -#define HASH4_CALC { \ +#define HASH4_CALC {\ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ temp ^= ((UInt32)cur[2] << 8); \ h3 = temp & (kHash3Size - 1); \ hv = (temp ^ (p->crc[cur[3]] << 5)) & p->hashMask; } -#define HASH5_CALC { \ +#define HASH5_CALC {\ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ temp ^= ((UInt32)cur[2] << 8); \ @@ -36,18 +36,17 @@ hv = (temp ^ (p->crc[cur[4]] << 3)) & p->hashMask; } /* #define HASH_ZIP_CALC hv = ((cur[0] | ((UInt32)cur[1] << 8)) ^ p->crc[cur[2]]) & 0xFFFF; */ -#define HASH_ZIP_CALC hv = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF; - +#define HASH_ZIP_CALC hv = ((cur[2] | ((UInt32)cur[0] << 8)) ^ p->crc[cur[1]]) & 0xFFFF; #define MT_HASH2_CALC \ h2 = (p->crc[cur[0]] ^ cur[1]) & (kHash2Size - 1); -#define MT_HASH3_CALC { \ +#define MT_HASH3_CALC {\ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ h3 = (temp ^ ((UInt32)cur[2] << 8)) & (kHash3Size - 1); } -#define MT_HASH4_CALC { \ +#define MT_HASH4_CALC {\ UInt32 temp = p->crc[cur[0]] ^ cur[1]; \ h2 = temp & (kHash2Size - 1); \ temp ^= ((UInt32)cur[2] << 8); \ diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.c b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.c index 80fb74525a..54c7077984 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.c +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.c @@ -4,38 +4,38 @@ #include "Precomp.h" #ifndef EFIAPI -#include + #include #endif /* #include "CpuArch.h" */ #include "LzmaDec.h" -#define kNumTopBits 24 -#define kTopValue ((UInt32)1 << kNumTopBits) +#define kNumTopBits 24 +#define kTopValue ((UInt32)1 << kNumTopBits) -#define kNumBitModelTotalBits 11 -#define kBitModelTotal (1 << kNumBitModelTotalBits) -#define kNumMoveBits 5 +#define kNumBitModelTotalBits 11 +#define kBitModelTotal (1 << kNumBitModelTotalBits) +#define kNumMoveBits 5 -#define RC_INIT_SIZE 5 +#define RC_INIT_SIZE 5 -#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } +#define NORMALIZE if (range < kTopValue) { range <<= 8; code = (code << 8) | (*buf++); } -#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) -#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); -#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); -#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p) \ +#define IF_BIT_0(p) ttt = *(p); NORMALIZE; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) +#define UPDATE_0(p) range = bound; *(p) = (CLzmaProb)(ttt + ((kBitModelTotal - ttt) >> kNumMoveBits)); +#define UPDATE_1(p) range -= bound; code -= bound; *(p) = (CLzmaProb)(ttt - (ttt >> kNumMoveBits)); +#define GET_BIT2(p, i, A0, A1) IF_BIT_0(p)\ { UPDATE_0(p); i = (i + i); A0; } else \ { UPDATE_1(p); i = (i + i) + 1; A1; } -#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } +#define TREE_GET_BIT(probs, i) { GET_BIT2(probs + i, i, ;, ;); } -#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i) \ +#define REV_BIT(p, i, A0, A1) IF_BIT_0(p + i)\ { UPDATE_0(p + i); A0; } else \ { UPDATE_1(p + i); A1; } -#define REV_BIT_VAR( p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) -#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) -#define REV_BIT_LAST( p, i, m) REV_BIT(p, i, i -= m , ; ) +#define REV_BIT_VAR(p, i, m) REV_BIT(p, i, i += m; m += m, m += m; i += m; ) +#define REV_BIT_CONST(p, i, m) REV_BIT(p, i, i += m; , i += m * 2; ) +#define REV_BIT_LAST(p, i, m) REV_BIT(p, i, i -= m , ; ) #define TREE_DECODE(probs, limit, i) \ { i = 1; do { TREE_GET_BIT(probs, i); } while (i < limit); i -= limit; } @@ -43,7 +43,7 @@ /* #define _LZMA_SIZE_OPT */ #ifdef _LZMA_SIZE_OPT -#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) +#define TREE_6_DECODE(probs, i) TREE_DECODE(probs, (1 << 6), i) #else #define TREE_6_DECODE(probs, i) \ { i = 1; \ @@ -56,7 +56,7 @@ i -= 0x40; } #endif -#define NORMAL_LITER_DEC TREE_GET_BIT(prob, symbol) +#define NORMAL_LITER_DEC TREE_GET_BIT(prob, symbol) #define MATCHED_LITER_DEC \ matchByte += matchByte; \ bit = offs; \ @@ -64,66 +64,64 @@ probLit = prob + (offs + bit + symbol); \ GET_BIT2(probLit, symbol, offs ^= bit; , ;) +#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } - -#define NORMALIZE_CHECK if (range < kTopValue) { if (buf >= bufLimit) return DUMMY_ERROR; range <<= 8; code = (code << 8) | (*buf++); } - -#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) -#define UPDATE_0_CHECK range = bound; -#define UPDATE_1_CHECK range -= bound; code -= bound; -#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p) \ +#define IF_BIT_0_CHECK(p) ttt = *(p); NORMALIZE_CHECK; bound = (range >> kNumBitModelTotalBits) * (UInt32)ttt; if (code < bound) +#define UPDATE_0_CHECK range = bound; +#define UPDATE_1_CHECK range -= bound; code -= bound; +#define GET_BIT2_CHECK(p, i, A0, A1) IF_BIT_0_CHECK(p)\ { UPDATE_0_CHECK; i = (i + i); A0; } else \ { UPDATE_1_CHECK; i = (i + i) + 1; A1; } -#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) +#define GET_BIT_CHECK(p, i) GET_BIT2_CHECK(p, i, ; , ;) #define TREE_DECODE_CHECK(probs, limit, i) \ { i = 1; do { GET_BIT_CHECK(probs + i, i) } while (i < limit); i -= limit; } - -#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i) \ +#define REV_BIT_CHECK(p, i, m) IF_BIT_0_CHECK(p + i)\ { UPDATE_0_CHECK; i += m; m += m; } else \ { UPDATE_1_CHECK; m += m; i += m; } +#define kNumPosBitsMax 4 +#define kNumPosStatesMax (1 << kNumPosBitsMax) -#define kNumPosBitsMax 4 -#define kNumPosStatesMax (1 << kNumPosBitsMax) - -#define kLenNumLowBits 3 -#define kLenNumLowSymbols (1 << kLenNumLowBits) -#define kLenNumHighBits 8 -#define kLenNumHighSymbols (1 << kLenNumHighBits) +#define kLenNumLowBits 3 +#define kLenNumLowSymbols (1 << kLenNumLowBits) +#define kLenNumHighBits 8 +#define kLenNumHighSymbols (1 << kLenNumHighBits) -#define LenLow 0 -#define LenHigh (LenLow + 2 * (kNumPosStatesMax << kLenNumLowBits)) -#define kNumLenProbs (LenHigh + kLenNumHighSymbols) +#define LenLow 0 +#define LenHigh (LenLow + 2 * (kNumPosStatesMax << kLenNumLowBits)) +#define kNumLenProbs (LenHigh + kLenNumHighSymbols) -#define LenChoice LenLow -#define LenChoice2 (LenLow + (1 << kLenNumLowBits)) +#define LenChoice LenLow +#define LenChoice2 (LenLow + (1 << kLenNumLowBits)) -#define kNumStates 12 -#define kNumStates2 16 -#define kNumLitStates 7 +#define kNumStates 12 +#define kNumStates2 16 +#define kNumLitStates 7 -#define kStartPosModelIndex 4 -#define kEndPosModelIndex 14 -#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) +#define kStartPosModelIndex 4 +#define kEndPosModelIndex 14 +#define kNumFullDistances (1 << (kEndPosModelIndex >> 1)) -#define kNumPosSlotBits 6 -#define kNumLenToPosStates 4 +#define kNumPosSlotBits 6 +#define kNumLenToPosStates 4 -#define kNumAlignBits 4 -#define kAlignTableSize (1 << kNumAlignBits) +#define kNumAlignBits 4 +#define kAlignTableSize (1 << kNumAlignBits) -#define kMatchMinLen 2 -#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols) +#define kMatchMinLen 2 +#define kMatchSpecLenStart (kMatchMinLen + kLenNumLowSymbols * 2 + kLenNumHighSymbols) /* External ASM code needs same CLzmaProb array layout. So don't change it. */ /* (probs_1664) is faster and better for code size at some platforms */ + /* #ifdef MY_CPU_X86_OR_AMD64 */ -#define kStartOffset 1664 -#define GET_PROBS p->probs_1664 +#define kStartOffset 1664 +#define GET_PROBS p->probs_1664 + /* #define GET_PROBS p->probs + kStartOffset #else @@ -132,19 +130,19 @@ #endif */ -#define SpecPos (-kStartOffset) -#define IsRep0Long (SpecPos + kNumFullDistances) -#define RepLenCoder (IsRep0Long + (kNumStates2 << kNumPosBitsMax)) -#define LenCoder (RepLenCoder + kNumLenProbs) -#define IsMatch (LenCoder + kNumLenProbs) -#define Align (IsMatch + (kNumStates2 << kNumPosBitsMax)) -#define IsRep (Align + kAlignTableSize) -#define IsRepG0 (IsRep + kNumStates) -#define IsRepG1 (IsRepG0 + kNumStates) -#define IsRepG2 (IsRepG1 + kNumStates) -#define PosSlot (IsRepG2 + kNumStates) -#define Literal (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) -#define NUM_BASE_PROBS (Literal + kStartOffset) +#define SpecPos (-kStartOffset) +#define IsRep0Long (SpecPos + kNumFullDistances) +#define RepLenCoder (IsRep0Long + (kNumStates2 << kNumPosBitsMax)) +#define LenCoder (RepLenCoder + kNumLenProbs) +#define IsMatch (LenCoder + kNumLenProbs) +#define Align (IsMatch + (kNumStates2 << kNumPosBitsMax)) +#define IsRep (Align + kAlignTableSize) +#define IsRepG0 (IsRep + kNumStates) +#define IsRepG1 (IsRepG0 + kNumStates) +#define IsRepG2 (IsRepG1 + kNumStates) +#define PosSlot (IsRepG2 + kNumStates) +#define Literal (PosSlot + (kNumLenToPosStates << kNumPosSlotBits)) +#define NUM_BASE_PROBS (Literal + kStartOffset) #if Align != 0 && kStartOffset != 0 #error Stop_Compiling_Bad_LZMA_kAlign @@ -154,17 +152,15 @@ #error Stop_Compiling_Bad_LZMA_PROBS #endif +#define LZMA_LIT_SIZE 0x300 -#define LZMA_LIT_SIZE 0x300 - -#define LzmaProps_GetNumProbs(p) (NUM_BASE_PROBS + ((UInt32)LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) - +#define LzmaProps_GetNumProbs(p) (NUM_BASE_PROBS + ((UInt32)LZMA_LIT_SIZE << ((p)->lc + (p)->lp))) -#define CALC_POS_STATE(processedPos, pbMask) (((processedPos) & (pbMask)) << 4) -#define COMBINED_PS_STATE (posState + state) -#define GET_LEN_STATE (posState) +#define CALC_POS_STATE(processedPos, pbMask) (((processedPos) & (pbMask)) << 4) +#define COMBINED_PS_STATE (posState + state) +#define GET_LEN_STATE (posState) -#define LZMA_DIC_MIN (1 << 12) +#define LZMA_DIC_MIN (1 << 12) /* p->remainLen : shows status of LZMA decoder: @@ -175,12 +171,13 @@ p->remainLen : shows status of LZMA decoder: */ /* ---------- LZMA_DECODE_REAL ---------- */ + /* LzmaDec_DecodeReal_3() can be implemented in external ASM file. 3 - is the code compatibility version of that function for check at link time. */ -#define LZMA_DECODE_REAL LzmaDec_DecodeReal_3 +#define LZMA_DECODE_REAL LzmaDec_DecodeReal_3 /* LZMA_DECODE_REAL() @@ -209,60 +206,71 @@ Out: = kMatchSpecLenStart : finished */ - #ifdef _LZMA_DEC_OPT -int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit); +int MY_FAST_CALL +LZMA_DECODE_REAL ( + CLzmaDec *p, + SizeT limit, + const Byte *bufLimit + ); #else static -int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +int MY_FAST_CALL +LZMA_DECODE_REAL ( + CLzmaDec *p, + SizeT limit, + const Byte *bufLimit + ) { - CLzmaProb *probs = GET_PROBS; - unsigned state = (unsigned)p->state; - UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; - unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; - unsigned lc = p->prop.lc; - unsigned lpMask = ((unsigned)0x100 << p->prop.lp) - ((unsigned)0x100 >> lc); - - Byte *dic = p->dic; - SizeT dicBufSize = p->dicBufSize; - SizeT dicPos = p->dicPos; - - UInt32 processedPos = p->processedPos; - UInt32 checkDicSize = p->checkDicSize; - unsigned len = 0; - - const Byte *buf = p->buf; - UInt32 range = p->range; - UInt32 code = p->code; - - do - { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = CALC_POS_STATE(processedPos, pbMask); + CLzmaProb *probs = GET_PROBS; + unsigned state = (unsigned)p->state; + UInt32 rep0 = p->reps[0], rep1 = p->reps[1], rep2 = p->reps[2], rep3 = p->reps[3]; + unsigned pbMask = ((unsigned)1 << (p->prop.pb)) - 1; + unsigned lc = p->prop.lc; + unsigned lpMask = ((unsigned)0x100 << p->prop.lp) - ((unsigned)0x100 >> lc); + + Byte *dic = p->dic; + SizeT dicBufSize = p->dicBufSize; + SizeT dicPos = p->dicPos; + + UInt32 processedPos = p->processedPos; + UInt32 checkDicSize = p->checkDicSize; + unsigned len = 0; + + const Byte *buf = p->buf; + UInt32 range = p->range; + UInt32 code = p->code; + + do { + CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = CALC_POS_STATE (processedPos, pbMask); prob = probs + IsMatch + COMBINED_PS_STATE; - IF_BIT_0(prob) - { - unsigned symbol; - UPDATE_0(prob); + IF_BIT_0 (prob) { + unsigned symbol; + + UPDATE_0 (prob); prob = probs + Literal; - if (processedPos != 0 || checkDicSize != 0) + if ((processedPos != 0) || (checkDicSize != 0)) { prob += (UInt32)3 * ((((processedPos << 8) + dic[(dicPos == 0 ? dicBufSize : dicPos) - 1]) & lpMask) << lc); + } + processedPos++; - if (state < kNumLitStates) - { + if (state < kNumLitStates) { state -= (state < 4) ? state : 3; symbol = 1; - #ifdef _LZMA_SIZE_OPT - do { NORMAL_LITER_DEC } while (symbol < 0x100); - #else - NORMAL_LITER_DEC + #ifdef _LZMA_SIZE_OPT + do { + NORMAL_LITER_DEC + } while (symbol < 0x100); + + #else NORMAL_LITER_DEC NORMAL_LITER_DEC NORMAL_LITER_DEC @@ -270,27 +278,24 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit NORMAL_LITER_DEC NORMAL_LITER_DEC NORMAL_LITER_DEC - #endif - } - else - { - unsigned matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; - unsigned offs = 0x100; + NORMAL_LITER_DEC + #endif + } else { + unsigned matchByte = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; + unsigned offs = 0x100; state -= (state < 10) ? 3 : 6; symbol = 1; - #ifdef _LZMA_SIZE_OPT - do - { - unsigned bit; - CLzmaProb *probLit; + #ifdef _LZMA_SIZE_OPT + do { + unsigned bit; + CLzmaProb *probLit; MATCHED_LITER_DEC - } - while (symbol < 0x100); - #else + } while (symbol < 0x100); + + #else { - unsigned bit; - CLzmaProb *probLit; - MATCHED_LITER_DEC + unsigned bit; + CLzmaProb *probLit; MATCHED_LITER_DEC MATCHED_LITER_DEC MATCHED_LITER_DEC @@ -298,8 +303,9 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit MATCHED_LITER_DEC MATCHED_LITER_DEC MATCHED_LITER_DEC + MATCHED_LITER_DEC } - #endif + #endif } dic[dicPos++] = (Byte)symbol; @@ -307,62 +313,50 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit } { - UPDATE_1(prob); + UPDATE_1 (prob); prob = probs + IsRep + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); + IF_BIT_0 (prob) { + UPDATE_0 (prob); state += kNumStates; - prob = probs + LenCoder; - } - else - { - UPDATE_1(prob); + prob = probs + LenCoder; + } else { + UPDATE_1 (prob); + /* // that case was checked before with kBadRepCode if (checkDicSize == 0 && processedPos == 0) return SZ_ERROR_DATA; */ prob = probs + IsRepG0 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); + IF_BIT_0 (prob) { + UPDATE_0 (prob); prob = probs + IsRep0Long + COMBINED_PS_STATE; - IF_BIT_0(prob) - { - UPDATE_0(prob); + IF_BIT_0 (prob) { + UPDATE_0 (prob); dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; dicPos++; processedPos++; state = state < kNumLitStates ? 9 : 11; continue; } - UPDATE_1(prob); - } - else - { - UInt32 distance; - UPDATE_1(prob); + UPDATE_1 (prob); + } else { + UInt32 distance; + UPDATE_1 (prob); prob = probs + IsRepG1 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); + IF_BIT_0 (prob) { + UPDATE_0 (prob); distance = rep1; - } - else - { - UPDATE_1(prob); + } else { + UPDATE_1 (prob); prob = probs + IsRepG2 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); + IF_BIT_0 (prob) { + UPDATE_0 (prob); distance = rep2; - } - else - { - UPDATE_1(prob); + } else { + UPDATE_1 (prob); distance = rep3; - rep3 = rep2; + rep3 = rep2; } rep2 = rep1; } @@ -370,120 +364,102 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit rep0 = distance; } state = state < kNumLitStates ? 8 : 11; - prob = probs + RepLenCoder; + prob = probs + RepLenCoder; } - #ifdef _LZMA_SIZE_OPT + #ifdef _LZMA_SIZE_OPT { - unsigned lim, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); + unsigned lim, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0 (probLen) { + UPDATE_0 (probLen); probLen = prob + LenLow + GET_LEN_STATE; - offset = 0; - lim = (1 << kLenNumLowBits); - } - else - { - UPDATE_1(probLen); + offset = 0; + lim = (1 << kLenNumLowBits); + } else { + UPDATE_1 (probLen); probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); + IF_BIT_0 (probLen) { + UPDATE_0 (probLen); probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - offset = kLenNumLowSymbols; - lim = (1 << kLenNumLowBits); - } - else - { - UPDATE_1(probLen); + offset = kLenNumLowSymbols; + lim = (1 << kLenNumLowBits); + } else { + UPDATE_1 (probLen); probLen = prob + LenHigh; - offset = kLenNumLowSymbols * 2; - lim = (1 << kLenNumHighBits); + offset = kLenNumLowSymbols * 2; + lim = (1 << kLenNumHighBits); } } - TREE_DECODE(probLen, lim, len); + TREE_DECODE (probLen, lim, len); len += offset; } - #else + #else { - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0 (probLen) { + UPDATE_0 (probLen); probLen = prob + LenLow + GET_LEN_STATE; - len = 1; - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); + len = 1; + TREE_GET_BIT (probLen, len); + TREE_GET_BIT (probLen, len); + TREE_GET_BIT (probLen, len); len -= 8; - } - else - { - UPDATE_1(probLen); + } else { + UPDATE_1 (probLen); probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); + IF_BIT_0 (probLen) { + UPDATE_0 (probLen); probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - len = 1; - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); - TREE_GET_BIT(probLen, len); - } - else - { - UPDATE_1(probLen); + len = 1; + TREE_GET_BIT (probLen, len); + TREE_GET_BIT (probLen, len); + TREE_GET_BIT (probLen, len); + } else { + UPDATE_1 (probLen); probLen = prob + LenHigh; - TREE_DECODE(probLen, (1 << kLenNumHighBits), len); + TREE_DECODE (probLen, (1 << kLenNumHighBits), len); len += kLenNumLowSymbols * 2; } } } - #endif + #endif - if (state >= kNumStates) - { - UInt32 distance; + if (state >= kNumStates) { + UInt32 distance; prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_6_DECODE(prob, distance); - if (distance >= kStartPosModelIndex) - { - unsigned posSlot = (unsigned)distance; - unsigned numDirectBits = (unsigned)(((distance >> 1) - 1)); + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); + TREE_6_DECODE (prob, distance); + if (distance >= kStartPosModelIndex) { + unsigned posSlot = (unsigned)distance; + unsigned numDirectBits = (unsigned)(((distance >> 1) - 1)); distance = (2 | (distance & 1)); - if (posSlot < kEndPosModelIndex) - { + if (posSlot < kEndPosModelIndex) { distance <<= numDirectBits; - prob = probs + SpecPos; + prob = probs + SpecPos; { - UInt32 m = 1; + UInt32 m = 1; distance++; - do - { - REV_BIT_VAR(prob, distance, m); - } - while (--numDirectBits); + do { + REV_BIT_VAR (prob, distance, m); + } while (--numDirectBits); + distance -= m; } - } - else - { + } else { numDirectBits -= kNumAlignBits; - do - { + do { NORMALIZE - range >>= 1; + range >>= 1; { - UInt32 t; - code -= range; - t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ + UInt32 t; + code -= range; + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ distance = (distance << 1) + (t + 1); - code += range & t; + code += range & t; } + /* distance <<= 1; if (code >= range) @@ -492,34 +468,32 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit distance |= 1; } */ - } - while (--numDirectBits); - prob = probs + Align; + } while (--numDirectBits); + + prob = probs + Align; distance <<= kNumAlignBits; { - unsigned i = 1; - REV_BIT_CONST(prob, i, 1); - REV_BIT_CONST(prob, i, 2); - REV_BIT_CONST(prob, i, 4); + unsigned i = 1; + REV_BIT_CONST (prob, i, 1); + REV_BIT_CONST (prob, i, 2); + REV_BIT_CONST (prob, i, 4); REV_BIT_LAST (prob, i, 8); distance |= i; } - if (distance == (UInt32)0xFFFFFFFF) - { - len = kMatchSpecLenStart; + if (distance == (UInt32)0xFFFFFFFF) { + len = kMatchSpecLenStart; state -= kNumStates; break; } } } - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - rep0 = distance + 1; + rep3 = rep2; + rep2 = rep1; + rep1 = rep0; + rep0 = distance + 1; state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; - if (distance >= (checkDicSize == 0 ? processedPos: checkDicSize)) - { + if (distance >= ((checkDicSize == 0) ? processedPos : checkDicSize)) { p->dicPos = dicPos; return SZ_ERROR_DATA; } @@ -528,660 +502,740 @@ int MY_FAST_CALL LZMA_DECODE_REAL(CLzmaDec *p, SizeT limit, const Byte *bufLimit len += kMatchMinLen; { - SizeT rem; - unsigned curLen; - SizeT pos; + SizeT rem; + unsigned curLen; + SizeT pos; - if ((rem = limit - dicPos) == 0) - { + if ((rem = limit - dicPos) == 0) { p->dicPos = dicPos; return SZ_ERROR_DATA; } curLen = ((rem < len) ? (unsigned)rem : len); - pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0); + pos = dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0); processedPos += (UInt32)curLen; len -= curLen; - if (curLen <= dicBufSize - pos) - { - Byte *dest = dic + dicPos; - ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; - const Byte *lim = dest + curLen; + if (curLen <= dicBufSize - pos) { + Byte *dest = dic + dicPos; + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; + const Byte *lim = dest + curLen; dicPos += (SizeT)curLen; - do + do { *(dest) = (Byte)*(dest + src); - while (++dest != lim); - } - else - { - do - { + } while (++dest != lim); + } else { + do { dic[dicPos++] = dic[pos]; - if (++pos == dicBufSize) + if (++pos == dicBufSize) { pos = 0; - } - while (--curLen != 0); + } + } while (--curLen != 0); } } } - } - while (dicPos < limit && buf < bufLimit); + } while (dicPos < limit && buf < bufLimit); NORMALIZE; - p->buf = buf; - p->range = range; - p->code = code; - p->remainLen = (UInt32)len; - p->dicPos = dicPos; + p->buf = buf; + p->range = range; + p->code = code; + p->remainLen = (UInt32)len; + p->dicPos = dicPos; p->processedPos = processedPos; - p->reps[0] = rep0; - p->reps[1] = rep1; - p->reps[2] = rep2; - p->reps[3] = rep3; - p->state = (UInt32)state; + p->reps[0] = rep0; + p->reps[1] = rep1; + p->reps[2] = rep2; + p->reps[3] = rep3; + p->state = (UInt32)state; return SZ_OK; } + #endif -static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) +static void MY_FAST_CALL +LzmaDec_WriteRem ( + CLzmaDec *p, + SizeT limit + ) { - if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) - { - Byte *dic = p->dic; - SizeT dicPos = p->dicPos; - SizeT dicBufSize = p->dicBufSize; - unsigned len = (unsigned)p->remainLen; - SizeT rep0 = p->reps[0]; /* we use SizeT to avoid the BUG of VC14 for AMD64 */ - SizeT rem = limit - dicPos; - if (rem < len) + if ((p->remainLen != 0) && (p->remainLen < kMatchSpecLenStart)) { + Byte *dic = p->dic; + SizeT dicPos = p->dicPos; + SizeT dicBufSize = p->dicBufSize; + unsigned len = (unsigned)p->remainLen; + SizeT rep0 = p->reps[0]; /* we use SizeT to avoid the BUG of VC14 for AMD64 */ + SizeT rem = limit - dicPos; + if (rem < len) { len = (unsigned)(rem); + } - if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) + if ((p->checkDicSize == 0) && (p->prop.dicSize - p->processedPos <= len)) { p->checkDicSize = p->prop.dicSize; + } p->processedPos += (UInt32)len; - p->remainLen -= (UInt32)len; - while (len != 0) - { + p->remainLen -= (UInt32)len; + while (len != 0) { len--; dic[dicPos] = dic[dicPos - rep0 + (dicPos < rep0 ? dicBufSize : 0)]; dicPos++; } + p->dicPos = dicPos; } } - -#define kRange0 0xFFFFFFFF -#define kBound0 ((kRange0 >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1)) -#define kBadRepCode (kBound0 + (((kRange0 - kBound0) >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1))) +#define kRange0 0xFFFFFFFF +#define kBound0 ((kRange0 >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1)) +#define kBadRepCode (kBound0 + (((kRange0 - kBound0) >> kNumBitModelTotalBits) << (kNumBitModelTotalBits - 1))) #if kBadRepCode != (0xC0000000 - 0x400) #error Stop_Compiling_Bad_LZMA_Check #endif -static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte *bufLimit) +static int MY_FAST_CALL +LzmaDec_DecodeReal2 ( + CLzmaDec *p, + SizeT limit, + const Byte *bufLimit + ) { - do - { - SizeT limit2 = limit; - if (p->checkDicSize == 0) - { - UInt32 rem = p->prop.dicSize - p->processedPos; - if (limit - p->dicPos > rem) + do { + SizeT limit2 = limit; + if (p->checkDicSize == 0) { + UInt32 rem = p->prop.dicSize - p->processedPos; + if (limit - p->dicPos > rem) { limit2 = p->dicPos + rem; + } - if (p->processedPos == 0) - if (p->code >= kBadRepCode) + if (p->processedPos == 0) { + if (p->code >= kBadRepCode) { return SZ_ERROR_DATA; + } + } } - RINOK(LZMA_DECODE_REAL(p, limit2, bufLimit)); + RINOK (LZMA_DECODE_REAL (p, limit2, bufLimit)); - if (p->checkDicSize == 0 && p->processedPos >= p->prop.dicSize) + if ((p->checkDicSize == 0) && (p->processedPos >= p->prop.dicSize)) { p->checkDicSize = p->prop.dicSize; + } - LzmaDec_WriteRem(p, limit); - } - while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); + LzmaDec_WriteRem (p, limit); + } while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); return 0; } -typedef enum -{ +typedef enum { DUMMY_ERROR, /* unexpected end of input stream */ DUMMY_LIT, DUMMY_MATCH, DUMMY_REP } ELzmaDummy; -static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inSize) +static ELzmaDummy +LzmaDec_TryDummy ( + const CLzmaDec *p, + const Byte *buf, + SizeT inSize + ) { - UInt32 range = p->range; - UInt32 code = p->code; - const Byte *bufLimit = buf + inSize; - const CLzmaProb *probs = GET_PROBS; - unsigned state = (unsigned)p->state; - ELzmaDummy res; + UInt32 range = p->range; + UInt32 code = p->code; + const Byte *bufLimit = buf + inSize; + const CLzmaProb *probs = GET_PROBS; + unsigned state = (unsigned)p->state; + ELzmaDummy res; { - const CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = CALC_POS_STATE(p->processedPos, (1 << p->prop.pb) - 1); + const CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = CALC_POS_STATE (p->processedPos, (1 << p->prop.pb) - 1); prob = probs + IsMatch + COMBINED_PS_STATE; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ - prob = probs + Literal; - if (p->checkDicSize != 0 || p->processedPos != 0) - prob += ((UInt32)LZMA_LIT_SIZE * - ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + - (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); + prob = probs + Literal; - if (state < kNumLitStates) - { - unsigned symbol = 1; - do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); + if ((p->checkDicSize != 0) || (p->processedPos != 0)) { + prob += ((UInt32)LZMA_LIT_SIZE * + ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); } - else - { - unsigned matchByte = p->dic[p->dicPos - p->reps[0] + - (p->dicPos < p->reps[0] ? p->dicBufSize : 0)]; - unsigned offs = 0x100; - unsigned symbol = 1; - do - { - unsigned bit; - const CLzmaProb *probLit; + + if (state < kNumLitStates) { + unsigned symbol = 1; + do { + GET_BIT_CHECK (prob + symbol, symbol) + } while (symbol < 0x100); + } else { + unsigned matchByte = p->dic[p->dicPos - p->reps[0] + + (p->dicPos < p->reps[0] ? p->dicBufSize : 0)]; + unsigned offs = 0x100; + unsigned symbol = 1; + do { + unsigned bit; + const CLzmaProb *probLit; matchByte += matchByte; - bit = offs; - offs &= matchByte; - probLit = prob + (offs + bit + symbol); - GET_BIT2_CHECK(probLit, symbol, offs ^= bit; , ; ) - } - while (symbol < 0x100); + bit = offs; + offs &= matchByte; + probLit = prob + (offs + bit + symbol); + GET_BIT2_CHECK ( + probLit, + symbol, + offs ^= bit; + , + ; + ) + } while (symbol < 0x100); } + res = DUMMY_LIT; - } - else - { - unsigned len; + } else { + unsigned len; UPDATE_1_CHECK; prob = probs + IsRep + state; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK; state = 0; - prob = probs + LenCoder; - res = DUMMY_MATCH; - } - else - { + prob = probs + LenCoder; + res = DUMMY_MATCH; + } else { UPDATE_1_CHECK; - res = DUMMY_REP; + res = DUMMY_REP; prob = probs + IsRepG0 + state; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK; prob = probs + IsRep0Long + COMBINED_PS_STATE; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK; NORMALIZE_CHECK; return DUMMY_REP; - } - else - { + } else { UPDATE_1_CHECK; } - } - else - { + } else { UPDATE_1_CHECK; prob = probs + IsRepG1 + state; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK; - } - else - { + } else { UPDATE_1_CHECK; prob = probs + IsRepG2 + state; - IF_BIT_0_CHECK(prob) - { + IF_BIT_0_CHECK (prob) { UPDATE_0_CHECK; - } - else - { + } else { UPDATE_1_CHECK; } } } state = kNumStates; - prob = probs + RepLenCoder; + prob = probs + RepLenCoder; } { - unsigned limit, offset; - const CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0_CHECK(probLen) - { + unsigned limit, offset; + const CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0_CHECK (probLen) { UPDATE_0_CHECK; probLen = prob + LenLow + GET_LEN_STATE; - offset = 0; - limit = 1 << kLenNumLowBits; - } - else - { + offset = 0; + limit = 1 << kLenNumLowBits; + } else { UPDATE_1_CHECK; probLen = prob + LenChoice2; - IF_BIT_0_CHECK(probLen) - { + IF_BIT_0_CHECK (probLen) { UPDATE_0_CHECK; probLen = prob + LenLow + GET_LEN_STATE + (1 << kLenNumLowBits); - offset = kLenNumLowSymbols; - limit = 1 << kLenNumLowBits; - } - else - { + offset = kLenNumLowSymbols; + limit = 1 << kLenNumLowBits; + } else { UPDATE_1_CHECK; probLen = prob + LenHigh; - offset = kLenNumLowSymbols * 2; - limit = 1 << kLenNumHighBits; + offset = kLenNumLowSymbols * 2; + limit = 1 << kLenNumHighBits; } } - TREE_DECODE_CHECK(probLen, limit, len); + TREE_DECODE_CHECK (probLen, limit, len); len += offset; } - if (state < 4) - { - unsigned posSlot; + if (state < 4) { + unsigned posSlot; prob = probs + PosSlot + - ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << - kNumPosSlotBits); - TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); - if (posSlot >= kStartPosModelIndex) - { - unsigned numDirectBits = ((posSlot >> 1) - 1); + ((len < kNumLenToPosStates - 1 ? len : kNumLenToPosStates - 1) << + kNumPosSlotBits); + TREE_DECODE_CHECK (prob, 1 << kNumPosSlotBits, posSlot); + if (posSlot >= kStartPosModelIndex) { + unsigned numDirectBits = ((posSlot >> 1) - 1); /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ - if (posSlot < kEndPosModelIndex) - { + if (posSlot < kEndPosModelIndex) { prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits); - } - else - { + } else { numDirectBits -= kNumAlignBits; - do - { + do { NORMALIZE_CHECK - range >>= 1; + range >>= 1; code -= range & (((code - range) >> 31) - 1); /* if (code >= range) code -= range; */ - } - while (--numDirectBits); - prob = probs + Align; + } while (--numDirectBits); + + prob = probs + Align; numDirectBits = kNumAlignBits; } + { - unsigned i = 1; - unsigned m = 1; - do - { - REV_BIT_CHECK(prob, i, m); - } - while (--numDirectBits); + unsigned i = 1; + unsigned m = 1; + do { + REV_BIT_CHECK (prob, i, m); + } while (--numDirectBits); } } } } } + NORMALIZE_CHECK; return res; } - -void LzmaDec_InitDicAndState(CLzmaDec *p, BoolInt initDic, BoolInt initState) +void +LzmaDec_InitDicAndState ( + CLzmaDec *p, + BoolInt initDic, + BoolInt initState + ) { - p->remainLen = kMatchSpecLenStart + 1; + p->remainLen = kMatchSpecLenStart + 1; p->tempBufSize = 0; - if (initDic) - { + if (initDic) { p->processedPos = 0; p->checkDicSize = 0; - p->remainLen = kMatchSpecLenStart + 2; + p->remainLen = kMatchSpecLenStart + 2; } - if (initState) + + if (initState) { p->remainLen = kMatchSpecLenStart + 2; + } } -void LzmaDec_Init(CLzmaDec *p) +void +LzmaDec_Init ( + CLzmaDec *p + ) { p->dicPos = 0; - LzmaDec_InitDicAndState(p, True, True); + LzmaDec_InitDicAndState (p, True, True); } - -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen, - ELzmaFinishMode finishMode, ELzmaStatus *status) +SRes +LzmaDec_DecodeToDic ( + CLzmaDec *p, + SizeT dicLimit, + const Byte *src, + SizeT *srcLen, + ELzmaFinishMode finishMode, + ELzmaStatus *status + ) { - SizeT inSize = *srcLen; + SizeT inSize = *srcLen; + (*srcLen) = 0; *status = LZMA_STATUS_NOT_SPECIFIED; - if (p->remainLen > kMatchSpecLenStart) - { - for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) + if (p->remainLen > kMatchSpecLenStart) { + for ( ; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) { p->tempBuf[p->tempBufSize++] = *src++; - if (p->tempBufSize != 0 && p->tempBuf[0] != 0) + } + + if ((p->tempBufSize != 0) && (p->tempBuf[0] != 0)) { return SZ_ERROR_DATA; - if (p->tempBufSize < RC_INIT_SIZE) - { + } + + if (p->tempBufSize < RC_INIT_SIZE) { *status = LZMA_STATUS_NEEDS_MORE_INPUT; return SZ_OK; } + p->code = - ((UInt32)p->tempBuf[1] << 24) + ((UInt32)p->tempBuf[1] << 24) | ((UInt32)p->tempBuf[2] << 16) | ((UInt32)p->tempBuf[3] << 8) | ((UInt32)p->tempBuf[4]); - p->range = 0xFFFFFFFF; + p->range = 0xFFFFFFFF; p->tempBufSize = 0; - if (p->remainLen > kMatchSpecLenStart + 1) - { - SizeT numProbs = LzmaProps_GetNumProbs(&p->prop); - SizeT i; - CLzmaProb *probs = p->probs; - for (i = 0; i < numProbs; i++) + if (p->remainLen > kMatchSpecLenStart + 1) { + SizeT numProbs = LzmaProps_GetNumProbs (&p->prop); + SizeT i; + CLzmaProb *probs = p->probs; + for (i = 0; i < numProbs; i++) { probs[i] = kBitModelTotal >> 1; + } + p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; - p->state = 0; + p->state = 0; } p->remainLen = 0; } - LzmaDec_WriteRem(p, dicLimit); + LzmaDec_WriteRem (p, dicLimit); - while (p->remainLen != kMatchSpecLenStart) - { - int checkEndMarkNow = 0; + while (p->remainLen != kMatchSpecLenStart) { + int checkEndMarkNow = 0; - if (p->dicPos >= dicLimit) - { - if (p->remainLen == 0 && p->code == 0) - { - *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; + if (p->dicPos >= dicLimit) { + if ((p->remainLen == 0) && (p->code == 0)) { + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; + return SZ_OK; + } + + if (finishMode == LZMA_FINISH_ANY) { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_OK; + } + + if (p->remainLen != 0) { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_ERROR_DATA; + } + + checkEndMarkNow = 1; + } + + if (p->tempBufSize == 0) { + SizeT processed; + const Byte *bufLimit; + if ((inSize < LZMA_REQUIRED_INPUT_MAX) || checkEndMarkNow) { + int dummyRes = LzmaDec_TryDummy (p, src, inSize); + if (dummyRes == DUMMY_ERROR) { + memcpy (p->tempBuf, src, inSize); + p->tempBufSize = (unsigned)inSize; + (*srcLen) += inSize; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; return SZ_OK; } - if (finishMode == LZMA_FINISH_ANY) - { + + if (checkEndMarkNow && (dummyRes != DUMMY_MATCH)) { *status = LZMA_STATUS_NOT_FINISHED; + return SZ_ERROR_DATA; + } + + bufLimit = src; + } else { + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; + } + + p->buf = src; + if (LzmaDec_DecodeReal2 (p, dicLimit, bufLimit) != 0) { + return SZ_ERROR_DATA; + } + + processed = (SizeT)(p->buf - src); + (*srcLen) += processed; + src += processed; + inSize -= processed; + } else { + unsigned rem = p->tempBufSize, lookAhead = 0; + while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) { + p->tempBuf[rem++] = src[lookAhead++]; + } + + p->tempBufSize = rem; + if ((rem < LZMA_REQUIRED_INPUT_MAX) || checkEndMarkNow) { + int dummyRes = LzmaDec_TryDummy (p, p->tempBuf, (SizeT)rem); + if (dummyRes == DUMMY_ERROR) { + (*srcLen) += (SizeT)lookAhead; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; return SZ_OK; } - if (p->remainLen != 0) - { + + if (checkEndMarkNow && (dummyRes != DUMMY_MATCH)) { *status = LZMA_STATUS_NOT_FINISHED; return SZ_ERROR_DATA; } - checkEndMarkNow = 1; } - if (p->tempBufSize == 0) - { - SizeT processed; - const Byte *bufLimit; - if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, src, inSize); - if (dummyRes == DUMMY_ERROR) - { - memcpy(p->tempBuf, src, inSize); - p->tempBufSize = (unsigned)inSize; - (*srcLen) += inSize; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - bufLimit = src; - } - else - bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; - p->buf = src; - if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) - return SZ_ERROR_DATA; - processed = (SizeT)(p->buf - src); - (*srcLen) += processed; - src += processed; - inSize -= processed; + p->buf = p->tempBuf; + if (LzmaDec_DecodeReal2 (p, dicLimit, p->buf) != 0) { + return SZ_ERROR_DATA; } - else + { - unsigned rem = p->tempBufSize, lookAhead = 0; - while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) - p->tempBuf[rem++] = src[lookAhead++]; - p->tempBufSize = rem; - if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, (SizeT)rem); - if (dummyRes == DUMMY_ERROR) - { - (*srcLen) += (SizeT)lookAhead; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } + unsigned kkk = (unsigned)(p->buf - p->tempBuf); + if (rem < kkk) { + return SZ_ERROR_FAIL; /* some internal error */ } - p->buf = p->tempBuf; - if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) - return SZ_ERROR_DATA; - { - unsigned kkk = (unsigned)(p->buf - p->tempBuf); - if (rem < kkk) - return SZ_ERROR_FAIL; /* some internal error */ - rem -= kkk; - if (lookAhead < rem) - return SZ_ERROR_FAIL; /* some internal error */ - lookAhead -= rem; + rem -= kkk; + if (lookAhead < rem) { + return SZ_ERROR_FAIL; /* some internal error */ } - (*srcLen) += (SizeT)lookAhead; - src += lookAhead; - inSize -= (SizeT)lookAhead; - p->tempBufSize = 0; + + lookAhead -= rem; } + (*srcLen) += (SizeT)lookAhead; + src += lookAhead; + inSize -= (SizeT)lookAhead; + p->tempBufSize = 0; + } } - if (p->code != 0) + if (p->code != 0) { return SZ_ERROR_DATA; + } + *status = LZMA_STATUS_FINISHED_WITH_MARK; return SZ_OK; } - -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status) +SRes +LzmaDec_DecodeToBuf ( + CLzmaDec *p, + Byte *dest, + SizeT *destLen, + const Byte *src, + SizeT *srcLen, + ELzmaFinishMode finishMode, + ELzmaStatus *status + ) { - SizeT outSize = *destLen; - SizeT inSize = *srcLen; + SizeT outSize = *destLen; + SizeT inSize = *srcLen; + *srcLen = *destLen = 0; - for (;;) - { - SizeT inSizeCur = inSize, outSizeCur, dicPos; - ELzmaFinishMode curFinishMode; - SRes res; - if (p->dicPos == p->dicBufSize) + for ( ; ;) { + SizeT inSizeCur = inSize, outSizeCur, dicPos; + ELzmaFinishMode curFinishMode; + SRes res; + if (p->dicPos == p->dicBufSize) { p->dicPos = 0; + } + dicPos = p->dicPos; - if (outSize > p->dicBufSize - dicPos) - { - outSizeCur = p->dicBufSize; + if (outSize > p->dicBufSize - dicPos) { + outSizeCur = p->dicBufSize; curFinishMode = LZMA_FINISH_ANY; - } - else - { - outSizeCur = dicPos + outSize; + } else { + outSizeCur = dicPos + outSize; curFinishMode = finishMode; } - res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); - src += inSizeCur; - inSize -= inSizeCur; - *srcLen += inSizeCur; + res = LzmaDec_DecodeToDic (p, outSizeCur, src, &inSizeCur, curFinishMode, status); + src += inSizeCur; + inSize -= inSizeCur; + *srcLen += inSizeCur; outSizeCur = p->dicPos - dicPos; - memcpy(dest, p->dic + dicPos, outSizeCur); - dest += outSizeCur; - outSize -= outSizeCur; + memcpy (dest, p->dic + dicPos, outSizeCur); + dest += outSizeCur; + outSize -= outSizeCur; *destLen += outSizeCur; - if (res != 0) + if (res != 0) { return res; - if (outSizeCur == 0 || outSize == 0) + } + + if ((outSizeCur == 0) || (outSize == 0)) { return SZ_OK; + } } } -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc) +void +LzmaDec_FreeProbs ( + CLzmaDec *p, + ISzAllocPtr alloc + ) { - ISzAlloc_Free(alloc, p->probs); + ISzAlloc_Free (alloc, p->probs); p->probs = NULL; } -static void LzmaDec_FreeDict(CLzmaDec *p, ISzAllocPtr alloc) +static void +LzmaDec_FreeDict ( + CLzmaDec *p, + ISzAllocPtr alloc + ) { - ISzAlloc_Free(alloc, p->dic); + ISzAlloc_Free (alloc, p->dic); p->dic = NULL; } -void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc) +void +LzmaDec_Free ( + CLzmaDec *p, + ISzAllocPtr alloc + ) { - LzmaDec_FreeProbs(p, alloc); - LzmaDec_FreeDict(p, alloc); + LzmaDec_FreeProbs (p, alloc); + LzmaDec_FreeDict (p, alloc); } -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size) +SRes +LzmaProps_Decode ( + CLzmaProps *p, + const Byte *data, + unsigned size + ) { - UInt32 dicSize; - Byte d; + UInt32 dicSize; + Byte d; - if (size < LZMA_PROPS_SIZE) + if (size < LZMA_PROPS_SIZE) { return SZ_ERROR_UNSUPPORTED; - else + } else { dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); + } - if (dicSize < LZMA_DIC_MIN) + if (dicSize < LZMA_DIC_MIN) { dicSize = LZMA_DIC_MIN; + } + p->dicSize = dicSize; d = data[0]; - if (d >= (9 * 5 * 5)) + if (d >= (9 * 5 * 5)) { return SZ_ERROR_UNSUPPORTED; + } p->lc = (Byte)(d % 9); - d /= 9; + d /= 9; p->pb = (Byte)(d / 5); p->lp = (Byte)(d % 5); return SZ_OK; } -static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAllocPtr alloc) +static SRes +LzmaDec_AllocateProbs2 ( + CLzmaDec *p, + const CLzmaProps *propNew, + ISzAllocPtr alloc + ) { - UInt32 numProbs = LzmaProps_GetNumProbs(propNew); - if (!p->probs || numProbs != p->numProbs) - { - LzmaDec_FreeProbs(p, alloc); - p->probs = (CLzmaProb *)ISzAlloc_Alloc(alloc, numProbs * sizeof(CLzmaProb)); - if (!p->probs) + UInt32 numProbs = LzmaProps_GetNumProbs (propNew); + + if (!p->probs || (numProbs != p->numProbs)) { + LzmaDec_FreeProbs (p, alloc); + p->probs = (CLzmaProb *)ISzAlloc_Alloc (alloc, numProbs * sizeof (CLzmaProb)); + if (!p->probs) { return SZ_ERROR_MEM; + } + p->probs_1664 = p->probs + 1664; - p->numProbs = numProbs; + p->numProbs = numProbs; } + return SZ_OK; } -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) +SRes +LzmaDec_AllocateProbs ( + CLzmaDec *p, + const Byte *props, + unsigned propsSize, + ISzAllocPtr alloc + ) { - CLzmaProps propNew; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); + CLzmaProps propNew; + + RINOK (LzmaProps_Decode (&propNew, props, propsSize)); + RINOK (LzmaDec_AllocateProbs2 (p, &propNew, alloc)); p->prop = propNew; return SZ_OK; } -SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc) +SRes +LzmaDec_Allocate ( + CLzmaDec *p, + const Byte *props, + unsigned propsSize, + ISzAllocPtr alloc + ) { - CLzmaProps propNew; - SizeT dicBufSize; - RINOK(LzmaProps_Decode(&propNew, props, propsSize)); - RINOK(LzmaDec_AllocateProbs2(p, &propNew, alloc)); + CLzmaProps propNew; + SizeT dicBufSize; + + RINOK (LzmaProps_Decode (&propNew, props, propsSize)); + RINOK (LzmaDec_AllocateProbs2 (p, &propNew, alloc)); { - UInt32 dictSize = propNew.dicSize; - SizeT mask = ((UInt32)1 << 12) - 1; - if (dictSize >= ((UInt32)1 << 30)) mask = ((UInt32)1 << 22) - 1; - else if (dictSize >= ((UInt32)1 << 22)) mask = ((UInt32)1 << 20) - 1;; + UInt32 dictSize = propNew.dicSize; + SizeT mask = ((UInt32)1 << 12) - 1; + if (dictSize >= ((UInt32)1 << 30)) { + mask = ((UInt32)1 << 22) - 1; + } else if (dictSize >= ((UInt32)1 << 22)) { + mask = ((UInt32)1 << 20) - 1; + } + dicBufSize = ((SizeT)dictSize + mask) & ~mask; - if (dicBufSize < dictSize) + if (dicBufSize < dictSize) { dicBufSize = dictSize; + } } - if (!p->dic || dicBufSize != p->dicBufSize) - { - LzmaDec_FreeDict(p, alloc); - p->dic = (Byte *)ISzAlloc_Alloc(alloc, dicBufSize); - if (!p->dic) - { - LzmaDec_FreeProbs(p, alloc); + if (!p->dic || (dicBufSize != p->dicBufSize)) { + LzmaDec_FreeDict (p, alloc); + p->dic = (Byte *)ISzAlloc_Alloc (alloc, dicBufSize); + if (!p->dic) { + LzmaDec_FreeProbs (p, alloc); return SZ_ERROR_MEM; } } + p->dicBufSize = dicBufSize; - p->prop = propNew; + p->prop = propNew; return SZ_OK; } -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAllocPtr alloc) +SRes +LzmaDecode ( + Byte *dest, + SizeT *destLen, + const Byte *src, + SizeT *srcLen, + const Byte *propData, + unsigned propSize, + ELzmaFinishMode finishMode, + ELzmaStatus *status, + ISzAllocPtr alloc + ) { - CLzmaDec p; - SRes res; - SizeT outSize = *destLen, inSize = *srcLen; + CLzmaDec p; + SRes res; + SizeT outSize = *destLen, inSize = *srcLen; + *destLen = *srcLen = 0; - *status = LZMA_STATUS_NOT_SPECIFIED; - if (inSize < RC_INIT_SIZE) + *status = LZMA_STATUS_NOT_SPECIFIED; + if (inSize < RC_INIT_SIZE) { return SZ_ERROR_INPUT_EOF; - LzmaDec_Construct(&p); - RINOK(LzmaDec_AllocateProbs(&p, propData, propSize, alloc)); - p.dic = dest; + } + + LzmaDec_Construct (&p); + RINOK (LzmaDec_AllocateProbs (&p, propData, propSize, alloc)); + p.dic = dest; p.dicBufSize = outSize; - LzmaDec_Init(&p); - *srcLen = inSize; - res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status); + LzmaDec_Init (&p); + *srcLen = inSize; + res = LzmaDec_DecodeToDic (&p, outSize, src, srcLen, finishMode, status); *destLen = p.dicPos; - if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT) + if ((res == SZ_OK) && (*status == LZMA_STATUS_NEEDS_MORE_INPUT)) { res = SZ_ERROR_INPUT_EOF; - LzmaDec_FreeProbs(&p, alloc); + } + + LzmaDec_FreeProbs (&p, alloc); return res; } diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.h index ebc568cb4f..11f028876f 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/Sdk/C/LzmaDec.h @@ -9,6 +9,7 @@ EXTERN_C_BEGIN /* #define _LZMA_PROB32 */ + /* _LZMA_PROB32 can increase the speed on some CPUs, but memory usage for CLzmaDec::probs will be doubled in that case */ @@ -20,18 +21,16 @@ typedef #endif CLzmaProb; - /* ---------- LZMA Properties ---------- */ -#define LZMA_PROPS_SIZE 5 +#define LZMA_PROPS_SIZE 5 -typedef struct _CLzmaProps -{ - Byte lc; - Byte lp; - Byte pb; - Byte _pad_; - UInt32 dicSize; +typedef struct _CLzmaProps { + Byte lc; + Byte lp; + Byte pb; + Byte _pad_; + UInt32 dicSize; } CLzmaProps; /* LzmaProps_Decode - decodes properties @@ -40,49 +39,54 @@ Returns: SZ_ERROR_UNSUPPORTED - Unsupported properties */ -SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size); - +SRes +LzmaProps_Decode ( + CLzmaProps *p, + const Byte *data, + unsigned size + ); /* ---------- LZMA Decoder state ---------- */ /* LZMA_REQUIRED_INPUT_MAX = number of required input bytes for worst case. Num bits = log2((2^11 / 31) ^ 22) + 26 < 134 + 26 = 160; */ -#define LZMA_REQUIRED_INPUT_MAX 20 +#define LZMA_REQUIRED_INPUT_MAX 20 -typedef struct -{ +typedef struct { /* Don't change this structure. ASM code can use it. */ - CLzmaProps prop; - CLzmaProb *probs; - CLzmaProb *probs_1664; - Byte *dic; - SizeT dicBufSize; - SizeT dicPos; - const Byte *buf; - UInt32 range; - UInt32 code; - UInt32 processedPos; - UInt32 checkDicSize; - UInt32 reps[4]; - UInt32 state; - UInt32 remainLen; - - UInt32 numProbs; - unsigned tempBufSize; - Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; + CLzmaProps prop; + CLzmaProb *probs; + CLzmaProb *probs_1664; + Byte *dic; + SizeT dicBufSize; + SizeT dicPos; + const Byte *buf; + UInt32 range; + UInt32 code; + UInt32 processedPos; + UInt32 checkDicSize; + UInt32 reps[4]; + UInt32 state; + UInt32 remainLen; + + UInt32 numProbs; + unsigned tempBufSize; + Byte tempBuf[LZMA_REQUIRED_INPUT_MAX]; } CLzmaDec; -#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } +#define LzmaDec_Construct(p) { (p)->dic = NULL; (p)->probs = NULL; } -void LzmaDec_Init(CLzmaDec *p); +void +LzmaDec_Init ( + CLzmaDec *p + ); /* There are two types of LZMA streams: - Stream with end mark. That end mark adds about 6 bytes to compressed size. - Stream without end mark. You must know exact uncompressed size to decompress such stream. */ -typedef enum -{ +typedef enum { LZMA_FINISH_ANY, /* finish at any point */ LZMA_FINISH_END /* block must be finished at the end */ } ELzmaFinishMode; @@ -102,8 +106,7 @@ typedef enum 3) Check that output(srcLen) = compressedSize, if you know real compressedSize. You must use correct finish mode in that case. */ -typedef enum -{ +typedef enum { LZMA_STATUS_NOT_SPECIFIED, /* use main error code instead */ LZMA_STATUS_FINISHED_WITH_MARK, /* stream was finished with end mark. */ LZMA_STATUS_NOT_FINISHED, /* stream was not finished */ @@ -113,7 +116,6 @@ typedef enum /* ELzmaStatus is used only as output value for function call */ - /* ---------- Interfaces ---------- */ /* There are 3 levels of interfaces: @@ -123,7 +125,6 @@ typedef enum You can select any of these interfaces, but don't mix functions from different groups for same object. */ - /* There are two variants to allocate state for Dictionary Interface: 1) LzmaDec_Allocate / LzmaDec_Free 2) LzmaDec_AllocateProbs / LzmaDec_FreeProbs @@ -136,11 +137,33 @@ LzmaDec_Allocate* can return: SZ_ERROR_UNSUPPORTED - Unsupported properties */ -SRes LzmaDec_AllocateProbs(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc); -void LzmaDec_FreeProbs(CLzmaDec *p, ISzAllocPtr alloc); - -SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAllocPtr alloc); -void LzmaDec_Free(CLzmaDec *p, ISzAllocPtr alloc); +SRes +LzmaDec_AllocateProbs ( + CLzmaDec *p, + const Byte *props, + unsigned propsSize, + ISzAllocPtr alloc + ); + +void +LzmaDec_FreeProbs ( + CLzmaDec *p, + ISzAllocPtr alloc + ); + +SRes +LzmaDec_Allocate ( + CLzmaDec *p, + const Byte *props, + unsigned propsSize, + ISzAllocPtr alloc + ); + +void +LzmaDec_Free ( + CLzmaDec *p, + ISzAllocPtr alloc + ); /* ---------- Dictionary Interface ---------- */ @@ -183,9 +206,15 @@ Returns: SZ_ERROR_DATA - Data error */ -SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - +SRes +LzmaDec_DecodeToDic ( + CLzmaDec *p, + SizeT dicLimit, + const Byte *src, + SizeT *srcLen, + ELzmaFinishMode finishMode, + ELzmaStatus *status + ); /* ---------- Buffer Interface ---------- */ @@ -200,9 +229,16 @@ finishMode: LZMA_FINISH_END - Stream must be finished after (*destLen). */ -SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, - const Byte *src, SizeT *srcLen, ELzmaFinishMode finishMode, ELzmaStatus *status); - +SRes +LzmaDec_DecodeToBuf ( + CLzmaDec *p, + Byte *dest, + SizeT *destLen, + const Byte *src, + SizeT *srcLen, + ELzmaFinishMode finishMode, + ELzmaStatus *status + ); /* ---------- One Call Interface ---------- */ @@ -225,9 +261,18 @@ Returns: SZ_ERROR_INPUT_EOF - It needs more bytes in input buffer (src). */ -SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAllocPtr alloc); +SRes +LzmaDecode ( + Byte *dest, + SizeT *destLen, + const Byte *src, + SizeT *srcLen, + const Byte *propData, + unsigned propSize, + ELzmaFinishMode finishMode, + ELzmaStatus *status, + ISzAllocPtr alloc + ); EXTERN_C_END diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h index e1315b6ec3..b1941bd403 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h @@ -15,23 +15,22 @@ #include #ifdef _WIN32 -#undef _WIN32 + #undef _WIN32 #endif typedef UINTN size_t; #ifdef _WIN64 -#undef _WIN64 + #undef _WIN64 #endif #ifndef _PTRDIFF_T_DEFINED typedef int ptrdiff_t; #endif -#define memcpy CopyMem -#define memmove CopyMem +#define memcpy CopyMem +#define memmove CopyMem #define _LZMA_SIZE_OPT #endif // __UEFILZMA_H__ - diff --git a/MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.c b/MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.c index 8074268986..a68612dd76 100644 --- a/MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.c +++ b/MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.c @@ -34,44 +34,44 @@ GetGuidFromType ( ) { switch (Type) { - case NonDiscoverableDeviceTypeAhci: - return &gEdkiiNonDiscoverableAhciDeviceGuid; + case NonDiscoverableDeviceTypeAhci: + return &gEdkiiNonDiscoverableAhciDeviceGuid; - case NonDiscoverableDeviceTypeAmba: - return &gEdkiiNonDiscoverableAmbaDeviceGuid; + case NonDiscoverableDeviceTypeAmba: + return &gEdkiiNonDiscoverableAmbaDeviceGuid; - case NonDiscoverableDeviceTypeEhci: - return &gEdkiiNonDiscoverableEhciDeviceGuid; + case NonDiscoverableDeviceTypeEhci: + return &gEdkiiNonDiscoverableEhciDeviceGuid; - case NonDiscoverableDeviceTypeNvme: - return &gEdkiiNonDiscoverableNvmeDeviceGuid; + case NonDiscoverableDeviceTypeNvme: + return &gEdkiiNonDiscoverableNvmeDeviceGuid; - case NonDiscoverableDeviceTypeOhci: - return &gEdkiiNonDiscoverableOhciDeviceGuid; + case NonDiscoverableDeviceTypeOhci: + return &gEdkiiNonDiscoverableOhciDeviceGuid; - case NonDiscoverableDeviceTypeSdhci: - return &gEdkiiNonDiscoverableSdhciDeviceGuid; + case NonDiscoverableDeviceTypeSdhci: + return &gEdkiiNonDiscoverableSdhciDeviceGuid; - case NonDiscoverableDeviceTypeUfs: - return &gEdkiiNonDiscoverableUfsDeviceGuid; + case NonDiscoverableDeviceTypeUfs: + return &gEdkiiNonDiscoverableUfsDeviceGuid; - case NonDiscoverableDeviceTypeUhci: - return &gEdkiiNonDiscoverableUhciDeviceGuid; + case NonDiscoverableDeviceTypeUhci: + return &gEdkiiNonDiscoverableUhciDeviceGuid; - case NonDiscoverableDeviceTypeXhci: - return &gEdkiiNonDiscoverableXhciDeviceGuid; + case NonDiscoverableDeviceTypeXhci: + return &gEdkiiNonDiscoverableXhciDeviceGuid; - default: - return NULL; + default: + return NULL; } } #pragma pack (1) typedef struct { - VENDOR_DEVICE_PATH Vendor; - UINT64 BaseAddress; - UINT8 ResourceType; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH Vendor; + UINT64 BaseAddress; + UINT8 ResourceType; + EFI_DEVICE_PATH_PROTOCOL End; } NON_DISCOVERABLE_DEVICE_PATH; #pragma pack () @@ -108,25 +108,26 @@ RegisterNonDiscoverableMmioDevice ( ... ) { - NON_DISCOVERABLE_DEVICE *Device; - NON_DISCOVERABLE_DEVICE_PATH *DevicePath; - EFI_HANDLE LocalHandle; - EFI_STATUS Status; - UINTN AllocSize; - UINTN Index; - VA_LIST Args; - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; - EFI_ACPI_END_TAG_DESCRIPTOR *End; - UINTN Base, Size; - - if (Type >= NonDiscoverableDeviceTypeMax || - DmaType >= NonDiscoverableDeviceDmaTypeMax || - NumMmioResources == 0) { + NON_DISCOVERABLE_DEVICE *Device; + NON_DISCOVERABLE_DEVICE_PATH *DevicePath; + EFI_HANDLE LocalHandle; + EFI_STATUS Status; + UINTN AllocSize; + UINTN Index; + VA_LIST Args; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Desc; + EFI_ACPI_END_TAG_DESCRIPTOR *End; + UINTN Base, Size; + + if ((Type >= NonDiscoverableDeviceTypeMax) || + (DmaType >= NonDiscoverableDeviceDmaTypeMax) || + (NumMmioResources == 0)) + { return EFI_INVALID_PARAMETER; } if (Handle == NULL) { - Handle = &LocalHandle; + Handle = &LocalHandle; LocalHandle = NULL; } @@ -141,13 +142,13 @@ RegisterNonDiscoverableMmioDevice ( Device->Type = GetGuidFromType (Type); ASSERT (Device->Type != NULL); - Device->DmaType = DmaType; + Device->DmaType = DmaType; Device->Initialize = InitFunc; - Device->Resources = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)(Device + 1); + Device->Resources = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)(Device + 1); VA_START (Args, NumMmioResources); for (Index = 0; Index < NumMmioResources; Index++) { - Desc = &Device->Resources [Index]; + Desc = &Device->Resources[Index]; Base = VA_ARG (Args, UINTN); Size = VA_ARG (Args, UINTN); @@ -160,9 +161,10 @@ RegisterNonDiscoverableMmioDevice ( Desc->AddrSpaceGranularity = ((EFI_PHYSICAL_ADDRESS)Base + Size > SIZE_4GB) ? 64 : 32; Desc->AddrTranslationOffset = 0; } + VA_END (Args); - End = (EFI_ACPI_END_TAG_DESCRIPTOR *)&Device->Resources [NumMmioResources]; + End = (EFI_ACPI_END_TAG_DESCRIPTOR *)&Device->Resources[NumMmioResources]; End->Desc = ACPI_END_TAG_DESCRIPTOR; End->Checksum = 0; @@ -170,7 +172,8 @@ RegisterNonDiscoverableMmioDevice ( DevicePath = (NON_DISCOVERABLE_DEVICE_PATH *)CreateDeviceNode ( HARDWARE_DEVICE_PATH, HW_VENDOR_DP, - sizeof (*DevicePath)); + sizeof (*DevicePath) + ); if (DevicePath == NULL) { Status = EFI_OUT_OF_RESOURCES; goto FreeDevice; @@ -182,20 +185,27 @@ RegisterNonDiscoverableMmioDevice ( // Use the base address and type of the first region to // make the device path unique // - DevicePath->BaseAddress = Device->Resources [0].AddrRangeMin; - DevicePath->ResourceType = Device->Resources [0].ResType; + DevicePath->BaseAddress = Device->Resources[0].AddrRangeMin; + DevicePath->ResourceType = Device->Resources[0].ResType; - SetDevicePathNodeLength (&DevicePath->Vendor, - sizeof (*DevicePath) - sizeof (DevicePath->End)); + SetDevicePathNodeLength ( + &DevicePath->Vendor, + sizeof (*DevicePath) - sizeof (DevicePath->End) + ); SetDevicePathEndNode (&DevicePath->End); - Status = gBS->InstallMultipleProtocolInterfaces (Handle, - &gEdkiiNonDiscoverableDeviceProtocolGuid, Device, - &gEfiDevicePathProtocolGuid, DevicePath, - NULL); + Status = gBS->InstallMultipleProtocolInterfaces ( + Handle, + &gEdkiiNonDiscoverableDeviceProtocolGuid, + Device, + &gEfiDevicePathProtocolGuid, + DevicePath, + NULL + ); if (EFI_ERROR (Status)) { goto FreeDevicePath; } + return EFI_SUCCESS; FreeDevicePath: diff --git a/MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.c b/MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.c index d545050f02..f1f088efd7 100644 --- a/MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.c +++ b/MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.c @@ -6,7 +6,6 @@ **/ - /** Initialize OEM status code device . @@ -44,11 +43,11 @@ OemHookStatusCodeInitialize ( EFI_STATUS EFIAPI OemHookStatusCodeReport ( - IN EFI_STATUS_CODE_TYPE CodeType, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE CodeType, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ) { return EFI_SUCCESS; diff --git a/MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.c b/MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.c index 0b86ef3ad5..097387607c 100644 --- a/MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.c +++ b/MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.c @@ -11,7 +11,7 @@ #include GLOBAL_REMOVE_IF_UNREFERENCED -CHAR16 *mPciHostBridgeLibAcpiAddressSpaceTypeStr[] = { +CHAR16 *mPciHostBridgeLibAcpiAddressSpaceTypeStr[] = { L"Mem", L"I/O", L"Bus" }; @@ -27,7 +27,7 @@ CHAR16 *mPciHostBridgeLibAcpiAddressSpaceTypeStr[] = { PCI_ROOT_BRIDGE * EFIAPI PciHostBridgeGetRootBridges ( - UINTN *Count + UINTN *Count ) { *Count = 0; @@ -43,8 +43,8 @@ PciHostBridgeGetRootBridges ( VOID EFIAPI PciHostBridgeFreeRootBridges ( - PCI_ROOT_BRIDGE *Bridges, - UINTN Count + PCI_ROOT_BRIDGE *Bridges, + UINTN Count ) { return; @@ -67,43 +67,52 @@ PciHostBridgeFreeRootBridges ( VOID EFIAPI PciHostBridgeResourceConflict ( - EFI_HANDLE HostBridgeHandle, - VOID *Configuration + EFI_HANDLE HostBridgeHandle, + VOID *Configuration ) { - EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; - UINTN RootBridgeIndex; + EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *Descriptor; + UINTN RootBridgeIndex; + DEBUG ((DEBUG_ERROR, "PciHostBridge: Resource conflict happens!\n")); RootBridgeIndex = 0; - Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *) Configuration; + Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)Configuration; while (Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR) { DEBUG ((DEBUG_ERROR, "RootBridge[%d]:\n", RootBridgeIndex++)); - for (; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { - ASSERT (Descriptor->ResType < - (sizeof (mPciHostBridgeLibAcpiAddressSpaceTypeStr) / - sizeof (mPciHostBridgeLibAcpiAddressSpaceTypeStr[0]) - ) - ); - DEBUG ((DEBUG_ERROR, " %s: Length/Alignment = 0x%lx / 0x%lx\n", - mPciHostBridgeLibAcpiAddressSpaceTypeStr[Descriptor->ResType], - Descriptor->AddrLen, Descriptor->AddrRangeMax - )); + for ( ; Descriptor->Desc == ACPI_ADDRESS_SPACE_DESCRIPTOR; Descriptor++) { + ASSERT ( + Descriptor->ResType < + (sizeof (mPciHostBridgeLibAcpiAddressSpaceTypeStr) / + sizeof (mPciHostBridgeLibAcpiAddressSpaceTypeStr[0]) + ) + ); + DEBUG (( + DEBUG_ERROR, + " %s: Length/Alignment = 0x%lx / 0x%lx\n", + mPciHostBridgeLibAcpiAddressSpaceTypeStr[Descriptor->ResType], + Descriptor->AddrLen, + Descriptor->AddrRangeMax + )); if (Descriptor->ResType == ACPI_ADDRESS_SPACE_TYPE_MEM) { - DEBUG ((DEBUG_ERROR, " Granularity/SpecificFlag = %ld / %02x%s\n", - Descriptor->AddrSpaceGranularity, Descriptor->SpecificFlag, - ((Descriptor->SpecificFlag & - EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE - ) != 0) ? L" (Prefetchable)" : L"" - )); + DEBUG (( + DEBUG_ERROR, + " Granularity/SpecificFlag = %ld / %02x%s\n", + Descriptor->AddrSpaceGranularity, + Descriptor->SpecificFlag, + ((Descriptor->SpecificFlag & + EFI_ACPI_MEMORY_RESOURCE_SPECIFIC_FLAG_CACHEABLE_PREFETCHABLE + ) != 0) ? L" (Prefetchable)" : L"" + )); } } + // // Skip the END descriptor for root bridge // ASSERT (Descriptor->Desc == ACPI_END_TAG_DESCRIPTOR); Descriptor = (EFI_ACPI_ADDRESS_SPACE_DESCRIPTOR *)( - (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor + 1 - ); + (EFI_ACPI_END_TAG_DESCRIPTOR *)Descriptor + 1 + ); } } diff --git a/MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.c b/MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.c index 4bd4e4b32e..63f149e7e0 100644 --- a/MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.c +++ b/MdeModulePkg/Library/PeiCrc32GuidedSectionExtractLib/PeiCrc32GuidedSectionExtractLib.c @@ -19,13 +19,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// CRC32 Guided Section header /// typedef struct { - EFI_GUID_DEFINED_SECTION GuidedSectionHeader; ///< EFI guided section header - UINT32 CRC32Checksum; ///< 32bit CRC check sum + EFI_GUID_DEFINED_SECTION GuidedSectionHeader; ///< EFI guided section header + UINT32 CRC32Checksum; ///< 32bit CRC check sum } CRC32_SECTION_HEADER; typedef struct { - EFI_GUID_DEFINED_SECTION2 GuidedSectionHeader; ///< EFI guided section header - UINT32 CRC32Checksum; ///< 32bit CRC check sum + EFI_GUID_DEFINED_SECTION2 GuidedSectionHeader; ///< EFI guided section header + UINT32 CRC32Checksum; ///< 32bit CRC check sum } CRC32_SECTION2_HEADER; /** @@ -58,31 +58,37 @@ Crc32GuidedSectionGetInfo ( // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } + // // Retrieve the size and attribute of the input section data. // - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes; *ScratchBufferSize = 0; - *OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; + *OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } + // // Retrieve the size and attribute of the input section data. // - *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes; + *SectionAttribute = ((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes; *ScratchBufferSize = 0; - *OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; + *OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; } return EFI_SUCCESS; @@ -114,53 +120,57 @@ Crc32GuidedSectionHandler ( OUT UINT32 *AuthenticationStatus ) { - UINT32 SectionCrc32Checksum; - UINT32 Crc32Checksum; - UINT32 OutputBufferSize; + UINT32 SectionCrc32Checksum; + UINT32 Crc32Checksum; + UINT32 OutputBufferSize; if (IS_SECTION2 (InputSection)) { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION2 *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION2 *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } // // Get section Crc32 checksum. // - SectionCrc32Checksum = ((CRC32_SECTION2_HEADER *) InputSection)->CRC32Checksum; - *OutputBuffer = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; - OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *) InputSection)->DataOffset; + SectionCrc32Checksum = ((CRC32_SECTION2_HEADER *)InputSection)->CRC32Checksum; + *OutputBuffer = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; + OutputBufferSize = SECTION2_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION2 *)InputSection)->DataOffset; // // Implicitly CRC32 GUIDed section should have STATUS_VALID bit set // - ASSERT (((EFI_GUID_DEFINED_SECTION2 *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); + ASSERT (((EFI_GUID_DEFINED_SECTION2 *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } else { // // Check whether the input guid section is recognized. // if (!CompareGuid ( - &gEfiCrc32GuidedSectionExtractionGuid, - &(((EFI_GUID_DEFINED_SECTION *) InputSection)->SectionDefinitionGuid))) { + &gEfiCrc32GuidedSectionExtractionGuid, + &(((EFI_GUID_DEFINED_SECTION *)InputSection)->SectionDefinitionGuid) + )) + { return EFI_INVALID_PARAMETER; } // // Get section Crc32 checksum. // - SectionCrc32Checksum = ((CRC32_SECTION_HEADER *) InputSection)->CRC32Checksum; - *OutputBuffer = (UINT8 *) InputSection + ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; - OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *) InputSection)->DataOffset; + SectionCrc32Checksum = ((CRC32_SECTION_HEADER *)InputSection)->CRC32Checksum; + *OutputBuffer = (UINT8 *)InputSection + ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; + OutputBufferSize = SECTION_SIZE (InputSection) - ((EFI_GUID_DEFINED_SECTION *)InputSection)->DataOffset; // // Implicitly CRC32 GUIDed section should have STATUS_VALID bit set // - ASSERT (((EFI_GUID_DEFINED_SECTION *) InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); + ASSERT (((EFI_GUID_DEFINED_SECTION *)InputSection)->Attributes & EFI_GUIDED_SECTION_AUTH_STATUS_VALID); *AuthenticationStatus = EFI_AUTH_STATUS_IMAGE_SIGNED; } @@ -198,13 +208,13 @@ Crc32GuidedSectionHandler ( EFI_STATUS EFIAPI PeiCrc32GuidedSectionExtractLibConstructor ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { return ExtractGuidedSectionRegisterHandlers ( - &gEfiCrc32GuidedSectionExtractionGuid, - Crc32GuidedSectionGetInfo, - Crc32GuidedSectionHandler - ); + &gEfiCrc32GuidedSectionExtractionGuid, + Crc32GuidedSectionGetInfo, + Crc32GuidedSectionHandler + ); } diff --git a/MdeModulePkg/Library/PeiDebugLibDebugPpi/DebugLib.c b/MdeModulePkg/Library/PeiDebugLibDebugPpi/DebugLib.c index 05a7dab99c..4fb0ad8b84 100644 --- a/MdeModulePkg/Library/PeiDebugLibDebugPpi/DebugLib.c +++ b/MdeModulePkg/Library/PeiDebugLibDebugPpi/DebugLib.c @@ -40,14 +40,13 @@ DebugPrint ( ... ) { - VA_LIST Marker; + VA_LIST Marker; VA_START (Marker, Format); DebugVPrint (ErrorLevel, Format, Marker); VA_END (Marker); } - /** Prints a debug message to the debug output device if the specified error level is enabled. @@ -68,13 +67,13 @@ DebugPrint ( VOID EFIAPI DebugBPrint ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - IN BASE_LIST BaseListMarker + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN BASE_LIST BaseListMarker ) { - EFI_STATUS Status; - EDKII_DEBUG_PPI *DebugPpi; + EFI_STATUS Status; + EDKII_DEBUG_PPI *DebugPpi; // // If Format is NULL, then ASSERT(). @@ -89,11 +88,11 @@ DebugBPrint ( } Status = PeiServicesLocatePpi ( - &gEdkiiDebugPpiGuid, - 0, - NULL, - (VOID **)&DebugPpi - ); + &gEdkiiDebugPpiGuid, + 0, + NULL, + (VOID **)&DebugPpi + ); if (EFI_ERROR (Status)) { return; } @@ -105,7 +104,6 @@ DebugBPrint ( ); } - /** Worker function that convert a VA_LIST to a BASE_LIST based on a Null-terminated format string. @@ -129,8 +127,8 @@ VaListToBaseList ( IN UINTN Size ) { - BASE_LIST BaseListStart; - BOOLEAN Long; + BASE_LIST BaseListStart; + BOOLEAN Long; ASSERT (Format != NULL); @@ -138,7 +136,7 @@ VaListToBaseList ( BaseListStart = BaseListMarker; - for (; *Format != '\0'; Format++) { + for ( ; *Format != '\0'; Format++) { // // Only format with prefix % is processed. // @@ -152,25 +150,28 @@ VaListToBaseList ( // Parse Flags and Width // for (Format++; TRUE; Format++) { - if (*Format == '.' || *Format == '-' || *Format == '+' || *Format == ' ') { + if ((*Format == '.') || (*Format == '-') || (*Format == '+') || (*Format == ' ')) { // // These characters in format field are omitted. // continue; } - if (*Format >= '0' && *Format <= '9') { + + if ((*Format >= '0') && (*Format <= '9')) { // // These characters in format field are omitted. // continue; } - if (*Format == 'L' || *Format == 'l') { + + if ((*Format == 'L') || (*Format == 'l')) { // // 'L" or "l" in format field means the number being printed is a UINT64 // Long = TRUE; continue; } + if (*Format == '*') { // // '*' in format field means the precision of the field is specified by @@ -179,6 +180,7 @@ VaListToBaseList ( BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); continue; } + if (*Format == '\0') { // // Make no output if Format string terminates unexpectedly when @@ -186,6 +188,7 @@ VaListToBaseList ( // Format--; } + // // When valid argument type detected or format string terminates unexpectedly, // the inner loop is done. @@ -199,13 +202,14 @@ VaListToBaseList ( if ((*Format == 'p') && (sizeof (VOID *) > 4)) { Long = TRUE; } - if (*Format == 'p' || *Format == 'X' || *Format == 'x' || *Format == 'd' || *Format == 'u') { + + if ((*Format == 'p') || (*Format == 'X') || (*Format == 'x') || (*Format == 'd') || (*Format == 'u')) { if (Long) { BASE_ARG (BaseListMarker, INT64) = VA_ARG (VaListMarker, INT64); } else { BASE_ARG (BaseListMarker, int) = VA_ARG (VaListMarker, int); } - } else if (*Format == 's' || *Format == 'S' || *Format == 'a' || *Format == 'g' || *Format == 't') { + } else if ((*Format == 's') || (*Format == 'S') || (*Format == 'a') || (*Format == 'g') || (*Format == 't')) { BASE_ARG (BaseListMarker, VOID *) = VA_ARG (VaListMarker, VOID *); } else if (*Format == 'c') { BASE_ARG (BaseListMarker, UINTN) = VA_ARG (VaListMarker, UINTN); @@ -224,7 +228,6 @@ VaListToBaseList ( return TRUE; } - /** Prints a debug message to the debug output device if the specified error level is enabled. @@ -243,13 +246,13 @@ VaListToBaseList ( VOID EFIAPI DebugVPrint ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - IN VA_LIST VaListMarker + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN VA_LIST VaListMarker ) { - UINT64 BaseListMarker[256 / sizeof (UINT64)]; - BOOLEAN Converted; + UINT64 BaseListMarker[256 / sizeof (UINT64)]; + BOOLEAN Converted; // // Convert the VaList to BaseList @@ -268,7 +271,6 @@ DebugVPrint ( DebugBPrint (ErrorLevel, Format, (BASE_LIST)BaseListMarker); } - /** Prints an assert message containing a filename, line number, and description. This may be followed by a breakpoint or a dead loop. @@ -298,15 +300,15 @@ DebugAssert ( IN CONST CHAR8 *Description ) { - EFI_STATUS Status; - EDKII_DEBUG_PPI *DebugPpi; + EFI_STATUS Status; + EDKII_DEBUG_PPI *DebugPpi; Status = PeiServicesLocatePpi ( - &gEdkiiDebugPpiGuid, - 0, - NULL, - (VOID **)&DebugPpi - ); + &gEdkiiDebugPpiGuid, + 0, + NULL, + (VOID **)&DebugPpi + ); if (EFI_ERROR (Status)) { // // Generate a Breakpoint, DeadLoop, or NOP based on PCD settings @@ -325,7 +327,6 @@ DebugAssert ( } } - /** Fills a target buffer with PcdDebugClearMemoryValue, and returns the target buffer. @@ -353,7 +354,6 @@ DebugClearMemory ( return SetMem (Buffer, Length, PcdGet8 (PcdDebugClearMemoryValue)); } - /** Returns TRUE if ASSERT() macros are enabled. @@ -370,10 +370,9 @@ DebugAssertEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED) != 0); } - /** Returns TRUE if DEBUG() macros are enabled. @@ -390,10 +389,9 @@ DebugPrintEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_PRINT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_PRINT_ENABLED) != 0); } - /** Returns TRUE if DEBUG_CODE() macros are enabled. @@ -410,10 +408,9 @@ DebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_CODE_ENABLED) != 0); } - /** Returns TRUE if DEBUG_CLEAR_MEMORY() macro is enabled. @@ -430,10 +427,9 @@ DebugClearMemoryEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED) != 0); } - /** Returns TRUE if any one of the bit is set both in ErrorLevel and PcdFixedDebugPrintErrorLevel. @@ -446,9 +442,8 @@ DebugClearMemoryEnabled ( BOOLEAN EFIAPI DebugPrintLevelEnabled ( - IN CONST UINTN ErrorLevel + IN CONST UINTN ErrorLevel ) { - return (BOOLEAN) ((ErrorLevel & PcdGet32(PcdFixedDebugPrintErrorLevel)) != 0); + return (BOOLEAN)((ErrorLevel & PcdGet32 (PcdFixedDebugPrintErrorLevel)) != 0); } - diff --git a/MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.c b/MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.c index e545be206f..1228587b9d 100644 --- a/MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.c +++ b/MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.c @@ -16,7 +16,6 @@ #include #include - /** The constructor reads variable and sets HOB @@ -29,15 +28,15 @@ EFI_STATUS EFIAPI PeiDebugPrintHobLibConstructor ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - EFI_PEI_READ_ONLY_VARIABLE2_PPI *Variable; - UINTN Size; - UINT64 GlobalErrorLevel; - UINT32 HobErrorLevel; + EFI_STATUS Status; + EFI_PEI_READ_ONLY_VARIABLE2_PPI *Variable; + UINTN Size; + UINT64 GlobalErrorLevel; + UINT32 HobErrorLevel; Status = PeiServicesLocatePpi ( &gEfiPeiReadOnlyVariable2PpiGuid, @@ -46,7 +45,7 @@ PeiDebugPrintHobLibConstructor ( (VOID **)&Variable ); if (!EFI_ERROR (Status)) { - Size = sizeof (GlobalErrorLevel); + Size = sizeof (GlobalErrorLevel); Status = Variable->GetVariable ( Variable, DEBUG_MASK_VARIABLE_NAME, diff --git a/MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/DebugLib.c b/MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/DebugLib.c index fb47401466..7ae5b16c84 100644 --- a/MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/DebugLib.c +++ b/MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/DebugLib.c @@ -25,7 +25,7 @@ // VA_LIST can not initialize to NULL for all compiler, so we use this to // indicate a null VA_LIST // -VA_LIST mVaListNull; +VA_LIST mVaListNull; /** Prints a debug message to the debug output device if the specified error level is enabled. @@ -53,7 +53,7 @@ DebugPrint ( ... ) { - VA_LIST Marker; + VA_LIST Marker; VA_START (Marker, Format); DebugVPrint (ErrorLevel, Format, Marker); @@ -84,10 +84,10 @@ DebugPrint ( **/ VOID DebugPrintMarker ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - IN VA_LIST VaListMarker, - IN BASE_LIST BaseListMarker + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN VA_LIST VaListMarker, + IN BASE_LIST BaseListMarker ) { UINT64 Buffer[(EFI_STATUS_CODE_DATA_MAX_SIZE / sizeof (UINT64)) + 1]; @@ -152,8 +152,10 @@ DebugPrintMarker ( // Copy the Format string into the record. It will be truncated if it's too long. // AsciiStrnCpyS ( - FormatString, sizeof(Buffer) - (4 + sizeof(EFI_DEBUG_INFO) + 12 * sizeof(UINT64)), - Format, sizeof(Buffer) - (4 + sizeof(EFI_DEBUG_INFO) + 12 * sizeof(UINT64)) - 1 + FormatString, + sizeof (Buffer) - (4 + sizeof (EFI_DEBUG_INFO) + 12 * sizeof (UINT64)), + Format, + sizeof (Buffer) - (4 + sizeof (EFI_DEBUG_INFO) + 12 * sizeof (UINT64)) - 1 ); // @@ -166,37 +168,41 @@ DebugPrintMarker ( // Use the actual format string. // Format = FormatString; - for (; *Format != '\0'; Format++) { + for ( ; *Format != '\0'; Format++) { // // Only format with prefix % is processed. // if (*Format != '%') { continue; } + Long = FALSE; // // Parse Flags and Width // for (Format++; TRUE; Format++) { - if (*Format == '.' || *Format == '-' || *Format == '+' || *Format == ' ') { + if ((*Format == '.') || (*Format == '-') || (*Format == '+') || (*Format == ' ')) { // // These characters in format field are omitted. // continue; } - if (*Format >= '0' && *Format <= '9') { + + if ((*Format >= '0') && (*Format <= '9')) { // // These characters in format field are omitted. // continue; } - if (*Format == 'L' || *Format == 'l') { + + if ((*Format == 'L') || (*Format == 'l')) { // // 'L" or "l" in format field means the number being printed is a UINT64 // Long = TRUE; continue; } + if (*Format == '*') { // // '*' in format field means the precision of the field is specified by @@ -207,8 +213,10 @@ DebugPrintMarker ( } else { BASE_ARG (BaseListMarkerPointer, UINTN) = BASE_ARG (BaseListMarker, UINTN); } + continue; } + if (*Format == '\0') { // // Make no output if Format string terminates unexpectedly when @@ -216,6 +224,7 @@ DebugPrintMarker ( // Format--; } + // // When valid argument type detected or format string terminates unexpectedly, // the inner loop is done. @@ -229,7 +238,8 @@ DebugPrintMarker ( if ((*Format == 'p') && (sizeof (VOID *) > 4)) { Long = TRUE; } - if (*Format == 'p' || *Format == 'X' || *Format == 'x' || *Format == 'd' || *Format == 'u') { + + if ((*Format == 'p') || (*Format == 'X') || (*Format == 'x') || (*Format == 'd') || (*Format == 'u')) { if (Long) { if (BaseListMarker == NULL) { BASE_ARG (BaseListMarkerPointer, INT64) = VA_ARG (VaListMarker, INT64); @@ -243,7 +253,7 @@ DebugPrintMarker ( BASE_ARG (BaseListMarkerPointer, int) = BASE_ARG (BaseListMarker, int); } } - } else if (*Format == 's' || *Format == 'S' || *Format == 'a' || *Format == 'g' || *Format == 't') { + } else if ((*Format == 's') || (*Format == 'S') || (*Format == 'a') || (*Format == 'g') || (*Format == 't')) { if (BaseListMarker == NULL) { BASE_ARG (BaseListMarkerPointer, VOID *) = VA_ARG (VaListMarker, VOID *); } else { @@ -310,9 +320,9 @@ DebugPrintMarker ( VOID EFIAPI DebugVPrint ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - IN VA_LIST VaListMarker + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN VA_LIST VaListMarker ) { DebugPrintMarker (ErrorLevel, Format, VaListMarker, NULL); @@ -338,9 +348,9 @@ DebugVPrint ( VOID EFIAPI DebugBPrint ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - IN BASE_LIST BaseListMarker + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN BASE_LIST BaseListMarker ) { DebugPrintMarker (ErrorLevel, Format, mVaListNull, BaseListMarker); @@ -375,7 +385,7 @@ DebugAssert ( IN CONST CHAR8 *Description ) { - UINT64 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE / sizeof(UINT64)]; + UINT64 Buffer[EFI_STATUS_CODE_DATA_MAX_SIZE / sizeof (UINT64)]; EFI_DEBUG_ASSERT_DATA *AssertData; UINTN HeaderSize; UINTN TotalSize; @@ -387,13 +397,13 @@ DebugAssert ( // // Get string size // - HeaderSize = sizeof (EFI_DEBUG_ASSERT_DATA); + HeaderSize = sizeof (EFI_DEBUG_ASSERT_DATA); // // Compute string size of module name enclosed by [] // - ModuleNameSize = 2 + AsciiStrSize (gEfiCallerBaseName); - FileNameSize = AsciiStrSize (FileName); - DescriptionSize = AsciiStrSize (Description); + ModuleNameSize = 2 + AsciiStrSize (gEfiCallerBaseName); + FileNameSize = AsciiStrSize (FileName); + DescriptionSize = AsciiStrSize (Description); // // Make sure it will all fit in the passed in buffer. @@ -422,12 +432,13 @@ DebugAssert ( } } } + // // Fill in EFI_DEBUG_ASSERT_DATA // - AssertData = (EFI_DEBUG_ASSERT_DATA *)Buffer; + AssertData = (EFI_DEBUG_ASSERT_DATA *)Buffer; AssertData->LineNumber = (UINT32)LineNumber; - TotalSize = sizeof (EFI_DEBUG_ASSERT_DATA); + TotalSize = sizeof (EFI_DEBUG_ASSERT_DATA); Temp = (CHAR8 *)(AssertData + 1); @@ -435,24 +446,24 @@ DebugAssert ( // Copy Ascii [ModuleName]. // if (ModuleNameSize != 0) { - CopyMem(Temp, "[", 1); - CopyMem(Temp + 1, gEfiCallerBaseName, ModuleNameSize - 3); - CopyMem(Temp + ModuleNameSize - 2, "] ", 2); + CopyMem (Temp, "[", 1); + CopyMem (Temp + 1, gEfiCallerBaseName, ModuleNameSize - 3); + CopyMem (Temp + ModuleNameSize - 2, "] ", 2); } // // Copy Ascii FileName including NULL terminator. // - Temp = CopyMem (Temp + ModuleNameSize, FileName, FileNameSize); + Temp = CopyMem (Temp + ModuleNameSize, FileName, FileNameSize); Temp[FileNameSize - 1] = 0; - TotalSize += (ModuleNameSize + FileNameSize); + TotalSize += (ModuleNameSize + FileNameSize); // // Copy Ascii Description include NULL terminator. // - Temp = CopyMem (Temp + FileNameSize, Description, DescriptionSize); + Temp = CopyMem (Temp + FileNameSize, Description, DescriptionSize); Temp[DescriptionSize - 1] = 0; - TotalSize += DescriptionSize; + TotalSize += DescriptionSize; REPORT_STATUS_CODE_EX ( (EFI_ERROR_CODE | EFI_ERROR_UNRECOVERED), @@ -474,7 +485,6 @@ DebugAssert ( } } - /** Fills a target buffer with PcdDebugClearMemoryValue, and returns the target buffer. @@ -502,7 +512,6 @@ DebugClearMemory ( return SetMem (Buffer, Length, PcdGet8 (PcdDebugClearMemoryValue)); } - /** Returns TRUE if ASSERT() macros are enabled. @@ -519,10 +528,9 @@ DebugAssertEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED) != 0); } - /** Returns TRUE if DEBUG() macros are enabled. @@ -539,10 +547,9 @@ DebugPrintEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_PRINT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_PRINT_ENABLED) != 0); } - /** Returns TRUE if DEBUG_CODE() macros are enabled. @@ -559,10 +566,9 @@ DebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_CODE_ENABLED) != 0); } - /** Returns TRUE if DEBUG_CLEAR_MEMORY() macro is enabled. @@ -579,7 +585,7 @@ DebugClearMemoryEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdDebugPropertyMask) & DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED) != 0); } /** @@ -594,8 +600,8 @@ DebugClearMemoryEnabled ( BOOLEAN EFIAPI DebugPrintLevelEnabled ( - IN CONST UINTN ErrorLevel + IN CONST UINTN ErrorLevel ) { - return (BOOLEAN) ((ErrorLevel & PcdGet32(PcdFixedDebugPrintErrorLevel)) != 0); + return (BOOLEAN)((ErrorLevel & PcdGet32 (PcdFixedDebugPrintErrorLevel)) != 0); } diff --git a/MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.c b/MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.c index 648af08761..a543a11b7c 100644 --- a/MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.c +++ b/MdeModulePkg/Library/PeiIpmiLibIpmiPpi/PeiIpmiLibIpmiPpi.c @@ -12,7 +12,6 @@ #include #include - /** This service enables submitting commands via Ipmi. @@ -34,23 +33,23 @@ EFI_STATUS EFIAPI IpmiSubmitCommand ( - IN UINT8 NetFunction, - IN UINT8 Command, - IN UINT8 *RequestData, - IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, - IN OUT UINT32 *ResponseDataSize + IN UINT8 NetFunction, + IN UINT8 Command, + IN UINT8 *RequestData, + IN UINT32 RequestDataSize, + OUT UINT8 *ResponseData, + IN OUT UINT32 *ResponseDataSize ) { - EFI_STATUS Status; - PEI_IPMI_PPI *IpmiPpi; + EFI_STATUS Status; + PEI_IPMI_PPI *IpmiPpi; - Status = PeiServicesLocatePpi( - &gPeiIpmiPpiGuid, - 0, - NULL, - (VOID **) &IpmiPpi - ); + Status = PeiServicesLocatePpi ( + &gPeiIpmiPpiGuid, + 0, + NULL, + (VOID **)&IpmiPpi + ); if (EFI_ERROR (Status)) { // // Ipmi Ppi is not installed. So, IPMI device is not present. @@ -60,16 +59,17 @@ IpmiSubmitCommand ( } Status = IpmiPpi->IpmiSubmitCommand ( - IpmiPpi, - NetFunction, - Command, - RequestData, - RequestDataSize, - ResponseData, - ResponseDataSize - ); + IpmiPpi, + NetFunction, + Command, + RequestData, + RequestDataSize, + ResponseData, + ResponseDataSize + ); if (EFI_ERROR (Status)) { return Status; } + return EFI_SUCCESS; } diff --git a/MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.c b/MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.c index ac033d4a6a..93edc01014 100644 --- a/MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.c +++ b/MdeModulePkg/Library/PeiPerformanceLib/PeiPerformanceLib.c @@ -13,7 +13,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include #include @@ -27,9 +26,8 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) -#define PEI_MAX_RECORD_SIZE (sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD) + STRING_SIZE) - +#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) +#define PEI_MAX_RECORD_SIZE (sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD) + STRING_SIZE) /** Return the pointer to the FPDT record in the allocated memory. @@ -46,38 +44,40 @@ GetFpdtRecordPtr ( IN UINT8 RecordSize, IN OUT FPDT_RECORD_PTR *FpdtRecordPtr, IN OUT FPDT_PEI_EXT_PERF_HEADER **PeiPerformanceLogHeader -) + ) { - UINT16 PeiPerformanceLogEntries; - UINTN PeiPerformanceSize; - UINT8 *PeiFirmwarePerformance; - EFI_HOB_GUID_TYPE *GuidHob; + UINT16 PeiPerformanceLogEntries; + UINTN PeiPerformanceSize; + UINT8 *PeiFirmwarePerformance; + EFI_HOB_GUID_TYPE *GuidHob; // // Get the number of PeiPerformanceLogEntries form PCD. // - PeiPerformanceLogEntries = (UINT16) (PcdGet16 (PcdMaxPeiPerformanceLogEntries16) != 0 ? - PcdGet16 (PcdMaxPeiPerformanceLogEntries16) : - PcdGet8 (PcdMaxPeiPerformanceLogEntries)); + PeiPerformanceLogEntries = (UINT16)(PcdGet16 (PcdMaxPeiPerformanceLogEntries16) != 0 ? + PcdGet16 (PcdMaxPeiPerformanceLogEntries16) : + PcdGet8 (PcdMaxPeiPerformanceLogEntries)); // // Create GUID HOB Data. // - GuidHob = GetFirstGuidHob (&gEdkiiFpdtExtendedFirmwarePerformanceGuid); + GuidHob = GetFirstGuidHob (&gEdkiiFpdtExtendedFirmwarePerformanceGuid); PeiFirmwarePerformance = NULL; while (GuidHob != NULL) { // // PEI Performance HOB was found, then return the existing one. // - PeiFirmwarePerformance = (UINT8*)GET_GUID_HOB_DATA (GuidHob); + PeiFirmwarePerformance = (UINT8 *)GET_GUID_HOB_DATA (GuidHob); *PeiPerformanceLogHeader = (FPDT_PEI_EXT_PERF_HEADER *)PeiFirmwarePerformance; - if (!(*PeiPerformanceLogHeader)->HobIsFull && (*PeiPerformanceLogHeader)->SizeOfAllEntries + RecordSize > (PeiPerformanceLogEntries * PEI_MAX_RECORD_SIZE)) { + if (!(*PeiPerformanceLogHeader)->HobIsFull && ((*PeiPerformanceLogHeader)->SizeOfAllEntries + RecordSize > (PeiPerformanceLogEntries * PEI_MAX_RECORD_SIZE))) { (*PeiPerformanceLogHeader)->HobIsFull = TRUE; } - if (!(*PeiPerformanceLogHeader)->HobIsFull && (*PeiPerformanceLogHeader)->SizeOfAllEntries + RecordSize <= (PeiPerformanceLogEntries * PEI_MAX_RECORD_SIZE)) { + + if (!(*PeiPerformanceLogHeader)->HobIsFull && ((*PeiPerformanceLogHeader)->SizeOfAllEntries + RecordSize <= (PeiPerformanceLogEntries * PEI_MAX_RECORD_SIZE))) { FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(PeiFirmwarePerformance + sizeof (FPDT_PEI_EXT_PERF_HEADER) + (*PeiPerformanceLogHeader)->SizeOfAllEntries); break; } + // // Previous HOB is used, then find next one. // @@ -88,12 +88,12 @@ GetFpdtRecordPtr ( // // PEI Performance HOB was not found, then build one. // - PeiPerformanceSize = sizeof (FPDT_PEI_EXT_PERF_HEADER) + - PEI_MAX_RECORD_SIZE * PeiPerformanceLogEntries; - PeiFirmwarePerformance = (UINT8*)BuildGuidHob (&gEdkiiFpdtExtendedFirmwarePerformanceGuid, PeiPerformanceSize); + PeiPerformanceSize = sizeof (FPDT_PEI_EXT_PERF_HEADER) + + PEI_MAX_RECORD_SIZE * PeiPerformanceLogEntries; + PeiFirmwarePerformance = (UINT8 *)BuildGuidHob (&gEdkiiFpdtExtendedFirmwarePerformanceGuid, PeiPerformanceSize); if (PeiFirmwarePerformance != NULL) { ZeroMem (PeiFirmwarePerformance, PeiPerformanceSize); - (*PeiPerformanceLogHeader) = (FPDT_PEI_EXT_PERF_HEADER *)PeiFirmwarePerformance; + (*PeiPerformanceLogHeader) = (FPDT_PEI_EXT_PERF_HEADER *)PeiFirmwarePerformance; FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)(PeiFirmwarePerformance + sizeof (FPDT_PEI_EXT_PERF_HEADER)); } } @@ -126,16 +126,17 @@ IsKnownTokens ( return FALSE; } - if (AsciiStrCmp (Token, SEC_TOK) == 0 || - AsciiStrCmp (Token, PEI_TOK) == 0 || - AsciiStrCmp (Token, DXE_TOK) == 0 || - AsciiStrCmp (Token, BDS_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0 || - AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, START_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, PEIM_TOK) == 0) { + if ((AsciiStrCmp (Token, SEC_TOK) == 0) || + (AsciiStrCmp (Token, PEI_TOK) == 0) || + (AsciiStrCmp (Token, DXE_TOK) == 0) || + (AsciiStrCmp (Token, BDS_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0) || + (AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, START_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, PEIM_TOK) == 0)) + { return TRUE; } else { return FALSE; @@ -153,19 +154,20 @@ Check whether the ID is a known one which map to the known Token. **/ BOOLEAN IsKnownID ( - IN UINT32 Identifier + IN UINT32 Identifier ) { - if (Identifier == MODULE_START_ID || - Identifier == MODULE_END_ID || - Identifier == MODULE_LOADIMAGE_START_ID || - Identifier == MODULE_LOADIMAGE_END_ID || - Identifier == MODULE_DB_START_ID || - Identifier == MODULE_DB_END_ID || - Identifier == MODULE_DB_SUPPORT_START_ID || - Identifier == MODULE_DB_SUPPORT_END_ID || - Identifier == MODULE_DB_STOP_START_ID || - Identifier == MODULE_DB_STOP_END_ID) { + if ((Identifier == MODULE_START_ID) || + (Identifier == MODULE_END_ID) || + (Identifier == MODULE_LOADIMAGE_START_ID) || + (Identifier == MODULE_LOADIMAGE_END_ID) || + (Identifier == MODULE_DB_START_ID) || + (Identifier == MODULE_DB_END_ID) || + (Identifier == MODULE_DB_SUPPORT_START_ID) || + (Identifier == MODULE_DB_SUPPORT_END_ID) || + (Identifier == MODULE_DB_STOP_START_ID) || + (Identifier == MODULE_DB_STOP_END_ID)) + { return TRUE; } else { return FALSE; @@ -188,10 +190,10 @@ IsKnownID ( **/ EFI_STATUS GetFpdtRecordId ( - IN BOOLEAN Attribute, - IN CONST VOID *Handle, - IN CONST CHAR8 *String, - OUT UINT16 *ProgressID + IN BOOLEAN Attribute, + IN CONST VOID *Handle, + IN CONST CHAR8 *String, + OUT UINT16 *ProgressID ) { // @@ -199,33 +201,38 @@ GetFpdtRecordId ( // When PcdEdkiiFpdtStringRecordEnableOnly is TRUE, all records are with type of FPDT_DYNAMIC_STRING_EVENT_TYPE. // if (String != NULL) { - if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { // "LoadImage:" + if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { + // "LoadImage:" if (Attribute == PerfStartEntry) { *ProgressID = MODULE_LOADIMAGE_START_ID; } else { *ProgressID = MODULE_LOADIMAGE_END_ID; } - } else if (AsciiStrCmp (String, SEC_TOK) == 0 || // "SEC" - AsciiStrCmp (String, PEI_TOK) == 0) { // "PEI" + } else if ((AsciiStrCmp (String, SEC_TOK) == 0) || // "SEC" + (AsciiStrCmp (String, PEI_TOK) == 0)) // "PEI" + { if (Attribute == PerfStartEntry) { *ProgressID = PERF_CROSSMODULE_START_ID; } else { *ProgressID = PERF_CROSSMODULE_END_ID; } - } else if (AsciiStrCmp (String, PEIM_TOK) == 0) { // "PEIM" + } else if (AsciiStrCmp (String, PEIM_TOK) == 0) { + // "PEIM" if (Attribute == PerfStartEntry) { *ProgressID = MODULE_START_ID; } else { *ProgressID = MODULE_END_ID; } - } else { //Pref used in Modules. + } else { + // Pref used in Modules. if (Attribute == PerfStartEntry) { *ProgressID = PERF_INMODULE_START_ID; } else { *ProgressID = PERF_INMODULE_END_ID; } } - } else if (Handle != NULL) { //Pref used in Modules. + } else if (Handle != NULL) { + // Pref used in Modules. if (Attribute == PerfStartEntry) { *ProgressID = PERF_INMODULE_START_ID; } else { @@ -249,9 +256,9 @@ GetFpdtRecordId ( **/ VOID CopyStringIntoPerfRecordAndUpdateLength ( - IN OUT CHAR8 *Destination, + IN OUT CHAR8 *Destination, IN CONST CHAR8 *Source, - IN OUT UINT8 *Length + IN OUT UINT8 *Length ) { UINTN StringLen; @@ -267,18 +274,18 @@ CopyStringIntoPerfRecordAndUpdateLength ( DestMax = STRING_SIZE; } } + StringLen = AsciiStrLen (Source); if (StringLen >= DestMax) { StringLen = DestMax -1; } - AsciiStrnCpyS(Destination, DestMax, Source, StringLen); + AsciiStrnCpyS (Destination, DestMax, Source, StringLen); *Length += (UINT8)DestMax; return; } - /** Convert PEI performance log to FPDT String boot record. @@ -309,16 +316,16 @@ InsertFpdtRecord ( IN PERF_MEASUREMENT_ATTRIBUTE Attribute ) { - FPDT_RECORD_PTR FpdtRecordPtr; - CONST VOID *ModuleGuid; - CONST CHAR8 *StringPtr; - EFI_STATUS Status; - UINT64 TimeStamp; - FPDT_PEI_EXT_PERF_HEADER *PeiPerformanceLogHeader; - - StringPtr = NULL; + FPDT_RECORD_PTR FpdtRecordPtr; + CONST VOID *ModuleGuid; + CONST CHAR8 *StringPtr; + EFI_STATUS Status; + UINT64 TimeStamp; + FPDT_PEI_EXT_PERF_HEADER *PeiPerformanceLogHeader; + + StringPtr = NULL; FpdtRecordPtr.RecordHeader = NULL; - PeiPerformanceLogHeader = NULL; + PeiPerformanceLogHeader = NULL; // // 1. Get the Perf Id for records from PERF_START/PERF_END, PERF_START_EX/PERF_END_EX. @@ -337,7 +344,7 @@ InsertFpdtRecord ( if ((PerfId != 0) && (IsKnownID (PerfId)) && (!IsKnownTokens (String))) { return EFI_UNSUPPORTED; } else if ((PerfId != 0) && (!IsKnownID (PerfId)) && (!IsKnownTokens (String))) { - if (Attribute == PerfStartEntry && ((PerfId & 0x000F) != 0)) { + if ((Attribute == PerfStartEntry) && ((PerfId & 0x000F) != 0)) { PerfId &= 0xFFF0; } else if ((Attribute == PerfEndEntry) && ((PerfId & 0x000F) == 0)) { PerfId += 1; @@ -383,113 +390,123 @@ InsertFpdtRecord ( // 5. Fill in the FPDT record according to different Performance Identifier. // switch (PerfId) { - case MODULE_START_ID: - case MODULE_END_ID: - StringPtr = PEIM_TOK; - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; - FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); - FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.GuidEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); - } - break; - - case MODULE_LOADIMAGE_START_ID: - case MODULE_LOADIMAGE_END_ID: - StringPtr = LOAD_IMAGE_TOK; - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; - FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); - FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; - if (PerfId == MODULE_LOADIMAGE_START_ID) { - PeiPerformanceLogHeader->LoadImageCount++; + case MODULE_START_ID: + case MODULE_END_ID: + StringPtr = PEIM_TOK; + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; + FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); + FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.GuidEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); } - FpdtRecordPtr.GuidQwordEvent->Qword = PeiPerformanceLogHeader->LoadImageCount; - CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); - } - break; - - case PERF_EVENTSIGNAL_START_ID: - case PERF_EVENTSIGNAL_END_ID: - case PERF_CALLBACK_START_ID: - case PERF_CALLBACK_END_ID: - if (String == NULL || Guid == NULL) { - return EFI_INVALID_PARAMETER; - } - StringPtr = String; - if (AsciiStrLen (String) == 0) { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; - FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); - FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, ModuleGuid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); - } - break; - - case PERF_EVENT_ID: - case PERF_FUNCTION_START_ID: - case PERF_FUNCTION_END_ID: - case PERF_INMODULE_START_ID: - case PERF_INMODULE_END_ID: - case PERF_CROSSMODULE_START_ID: - case PERF_CROSSMODULE_END_ID: - if (String != NULL && AsciiStrLen (String) != 0) { + + break; + + case MODULE_LOADIMAGE_START_ID: + case MODULE_LOADIMAGE_END_ID: + StringPtr = LOAD_IMAGE_TOK; + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; + FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); + FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; + if (PerfId == MODULE_LOADIMAGE_START_ID) { + PeiPerformanceLogHeader->LoadImageCount++; + } + + FpdtRecordPtr.GuidQwordEvent->Qword = PeiPerformanceLogHeader->LoadImageCount; + CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); + } + + break; + + case PERF_EVENTSIGNAL_START_ID: + case PERF_EVENTSIGNAL_END_ID: + case PERF_CALLBACK_START_ID: + case PERF_CALLBACK_END_ID: + if ((String == NULL) || (Guid == NULL)) { + return EFI_INVALID_PARAMETER; + } + StringPtr = String; - } else { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); - } - break; - - default: - if (Attribute != PerfEntry) { - if (String != NULL && AsciiStrLen (String) != 0) { - StringPtr = String; - } else { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); - } - } else { - return EFI_INVALID_PARAMETER; - } - break; + if (AsciiStrLen (String) == 0) { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; + FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); + FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, ModuleGuid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); + } + + break; + + case PERF_EVENT_ID: + case PERF_FUNCTION_START_ID: + case PERF_FUNCTION_END_ID: + case PERF_INMODULE_START_ID: + case PERF_INMODULE_END_ID: + case PERF_CROSSMODULE_START_ID: + case PERF_CROSSMODULE_END_ID: + if ((String != NULL) && (AsciiStrLen (String) != 0)) { + StringPtr = String; + } else { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); + } + + break; + + default: + if (Attribute != PerfEntry) { + if ((String != NULL) && (AsciiStrLen (String) != 0)) { + StringPtr = String; + } else { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); + } + } else { + return EFI_INVALID_PARAMETER; + } + + break; } // // 5.2 When PcdEdkiiFpdtStringRecordEnableOnly==TRUE, create string record for all Perf entries. // if (PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; if (Guid != NULL) { // // Cache the event guid in string event record. @@ -498,6 +515,7 @@ InsertFpdtRecord ( } else { CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, ModuleGuid, sizeof (EFI_GUID)); } + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); } @@ -543,7 +561,7 @@ StartPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -554,7 +572,6 @@ StartPerformanceMeasurementEx ( } return (RETURN_STATUS)InsertFpdtRecord (Handle, NULL, String, TimeStamp, 0, (UINT16)Identifier, PerfStartEntry); - } /** @@ -589,7 +606,7 @@ EndPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -648,13 +665,13 @@ EndPerformanceMeasurementEx ( UINTN EFIAPI GetPerformanceMeasurementEx ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp, - OUT UINT32 *Identifier + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp, + OUT UINT32 *Identifier ) { return 0; @@ -771,12 +788,12 @@ EndPerformanceMeasurement ( UINTN EFIAPI GetPerformanceMeasurement ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp ) { return 0; @@ -800,7 +817,7 @@ PerformanceMeasurementEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8(PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); } /** @@ -846,14 +863,15 @@ LogPerformanceMeasurement ( BOOLEAN EFIAPI LogPerformanceMeasurementEnabled ( - IN CONST UINTN Type + IN CONST UINTN Type ) { // // When Performance measurement is enabled and the type is not filtered, the performance can be logged. // - if (PerformanceMeasurementEnabled () && (PcdGet8(PcdPerformanceLibraryPropertyMask) & Type) == 0) { + if (PerformanceMeasurementEnabled () && ((PcdGet8 (PcdPerformanceLibraryPropertyMask) & Type) == 0)) { return TRUE; } + return FALSE; } diff --git a/MdeModulePkg/Library/PeiReportStatusCodeLib/ReportStatusCodeLib.c b/MdeModulePkg/Library/PeiReportStatusCodeLib/ReportStatusCodeLib.c index 43b4d49d30..b0a5f61cda 100644 --- a/MdeModulePkg/Library/PeiReportStatusCodeLib/ReportStatusCodeLib.c +++ b/MdeModulePkg/Library/PeiReportStatusCodeLib/ReportStatusCodeLib.c @@ -45,41 +45,42 @@ **/ EFI_STATUS InternalReportStatusCode ( - IN EFI_STATUS_CODE_TYPE Type, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE Type, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ) { CONST EFI_PEI_SERVICES **PeiServices; EFI_STATUS Status; - if ((ReportProgressCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - (ReportErrorCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) || - (ReportDebugCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE)) { + if ((ReportProgressCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE)) || + (ReportErrorCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) || + (ReportDebugCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE))) + { PeiServices = GetPeiServicesTablePointer (); - Status = (*PeiServices)->ReportStatusCode ( - PeiServices, - Type, - Value, - Instance, - (EFI_GUID *)CallerId, - Data - ); + Status = (*PeiServices)->ReportStatusCode ( + PeiServices, + Type, + Value, + Instance, + (EFI_GUID *)CallerId, + Data + ); if (Status == EFI_NOT_AVAILABLE_YET) { Status = OemHookStatusCodeInitialize (); if (!EFI_ERROR (Status)) { - return OemHookStatusCodeReport (Type, Value, Instance, (EFI_GUID *) CallerId, Data); + return OemHookStatusCodeReport (Type, Value, Instance, (EFI_GUID *)CallerId, Data); } } + return Status; } return EFI_UNSUPPORTED; } - /** Converts a status code to an 8-bit POST code value. @@ -118,15 +119,16 @@ CodeTypeToPostCode ( // Convert Value to an 8 bit post code // if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) { - *PostCode = (UINT8) ((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | - (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); + ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) + { + *PostCode = (UINT8)((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | + (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); return TRUE; } + return FALSE; } - /** Extracts ASSERT() information from a status code structure. @@ -180,17 +182,18 @@ ReportStatusCodeExtractAssertInfo ( if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) && ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) && - ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) { + ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) + { AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1); *Filename = (CHAR8 *)(AssertData + 1); *Description = *Filename + AsciiStrLen (*Filename) + 1; *LineNumber = AssertData->LineNumber; return TRUE; } + return FALSE; } - /** Extracts DEBUG() information from a status code structure. @@ -259,13 +262,12 @@ ReportStatusCodeExtractDebugInfo ( // 64-bit aligned is a must, otherwise retrieving 64-bit parameter from BASE_LIST will // cause unalignment exception. // - *Marker = (BASE_LIST) (DebugInfo + 1); + *Marker = (BASE_LIST)(DebugInfo + 1); *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12); return TRUE; } - /** Reports a status code. @@ -297,7 +299,6 @@ ReportStatusCode ( return InternalReportStatusCode (Type, Value, 0, &gEfiCallerIdGuid, NULL); } - /** Reports a status code with a Device Path Protocol as the extended data. @@ -341,7 +342,6 @@ ReportStatusCodeWithDevicePath ( return EFI_UNSUPPORTED; } - /** Reports a status code with an extended data buffer. @@ -397,7 +397,6 @@ ReportStatusCodeWithExtendedData ( ); } - /** Reports a status code with full parameters. @@ -471,23 +470,26 @@ ReportStatusCodeEx ( DEBUG ((DEBUG_ERROR, "Status code extended data is too large to be reported!\n")); return EFI_OUT_OF_RESOURCES; } - StatusCodeData = (EFI_STATUS_CODE_DATA *) Buffer; - StatusCodeData->HeaderSize = (UINT16) sizeof (EFI_STATUS_CODE_DATA); - StatusCodeData->Size = (UINT16) ExtendedDataSize; + + StatusCodeData = (EFI_STATUS_CODE_DATA *)Buffer; + StatusCodeData->HeaderSize = (UINT16)sizeof (EFI_STATUS_CODE_DATA); + StatusCodeData->Size = (UINT16)ExtendedDataSize; if (ExtendedDataGuid == NULL) { ExtendedDataGuid = &gEfiStatusCodeSpecificDataGuid; } + CopyGuid (&StatusCodeData->Type, ExtendedDataGuid); if (ExtendedData != NULL) { CopyMem (StatusCodeData + 1, ExtendedData, ExtendedDataSize); } + if (CallerId == NULL) { CallerId = &gEfiCallerIdGuid; } + return InternalReportStatusCode (Type, Value, Instance, CallerId, StatusCodeData); } - /** Returns TRUE if status codes of type EFI_PROGRESS_CODE are enabled @@ -506,10 +508,9 @@ ReportProgressCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_ERROR_CODE are enabled @@ -528,10 +529,9 @@ ReportErrorCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_DEBUG_CODE are enabled @@ -550,5 +550,5 @@ ReportDebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); } diff --git a/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c b/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c index 6c8c770ca3..2a4ee80317 100644 --- a/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c +++ b/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c @@ -71,8 +71,8 @@ ResetShutdown ( VOID EFIAPI ResetPlatformSpecific ( - IN UINTN DataSize, - IN VOID *ResetData + IN UINTN DataSize, + IN VOID *ResetData ) { PeiServicesResetSystem2 (EfiResetPlatformSpecific, EFI_SUCCESS, DataSize, ResetData); @@ -93,10 +93,10 @@ ResetPlatformSpecific ( VOID EFIAPI ResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { PeiServicesResetSystem2 (ResetType, ResetStatus, DataSize, ResetData); diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c index f7fb787cd5..279daefac1 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptExecute.c @@ -51,14 +51,14 @@ **/ EFI_STATUS InternalSmbusExecute ( - IN UINTN SmbusAddress, - IN EFI_SMBUS_OPERATION Operation, - IN OUT UINTN *Length, - IN OUT VOID *Buffer + IN UINTN SmbusAddress, + IN EFI_SMBUS_OPERATION Operation, + IN OUT UINTN *Length, + IN OUT VOID *Buffer ) { - EFI_STATUS Status; - UINT8 WorkBuffer[MAX_SMBUS_BLOCK_LEN]; + EFI_STATUS Status; + UINT8 WorkBuffer[MAX_SMBUS_BLOCK_LEN]; switch (Operation) { case EfiSmbusQuickRead: @@ -74,28 +74,28 @@ InternalSmbusExecute ( SmBusReceiveByte (SmbusAddress, &Status); break; case EfiSmbusSendByte: - DEBUG ((DEBUG_INFO, "EfiSmbusSendByte - 0x%08x (0x%02x)\n", SmbusAddress, (UINTN)*(UINT8 *) Buffer)); - SmBusSendByte (SmbusAddress, *(UINT8 *) Buffer, &Status); + DEBUG ((DEBUG_INFO, "EfiSmbusSendByte - 0x%08x (0x%02x)\n", SmbusAddress, (UINTN)*(UINT8 *)Buffer)); + SmBusSendByte (SmbusAddress, *(UINT8 *)Buffer, &Status); break; case EfiSmbusReadByte: DEBUG ((DEBUG_INFO, "EfiSmbusReadByte - 0x%08x\n", SmbusAddress)); SmBusReadDataByte (SmbusAddress, &Status); break; case EfiSmbusWriteByte: - DEBUG ((DEBUG_INFO, "EfiSmbusWriteByte - 0x%08x (0x%02x)\n", SmbusAddress, (UINTN)*(UINT8 *) Buffer)); - SmBusWriteDataByte (SmbusAddress, *(UINT8 *) Buffer, &Status); + DEBUG ((DEBUG_INFO, "EfiSmbusWriteByte - 0x%08x (0x%02x)\n", SmbusAddress, (UINTN)*(UINT8 *)Buffer)); + SmBusWriteDataByte (SmbusAddress, *(UINT8 *)Buffer, &Status); break; case EfiSmbusReadWord: DEBUG ((DEBUG_INFO, "EfiSmbusReadWord - 0x%08x\n", SmbusAddress)); SmBusReadDataWord (SmbusAddress, &Status); break; case EfiSmbusWriteWord: - DEBUG ((DEBUG_INFO, "EfiSmbusWriteWord - 0x%08x (0x%04x)\n", SmbusAddress, (UINTN)*(UINT16 *) Buffer)); - SmBusWriteDataWord (SmbusAddress, *(UINT16 *) Buffer, &Status); + DEBUG ((DEBUG_INFO, "EfiSmbusWriteWord - 0x%08x (0x%04x)\n", SmbusAddress, (UINTN)*(UINT16 *)Buffer)); + SmBusWriteDataWord (SmbusAddress, *(UINT16 *)Buffer, &Status); break; case EfiSmbusProcessCall: - DEBUG ((DEBUG_INFO, "EfiSmbusProcessCall - 0x%08x (0x%04x)\n", SmbusAddress, (UINTN)*(UINT16 *) Buffer)); - SmBusProcessCall (SmbusAddress, *(UINT16 *) Buffer, &Status); + DEBUG ((DEBUG_INFO, "EfiSmbusProcessCall - 0x%08x (0x%04x)\n", SmbusAddress, (UINTN)*(UINT16 *)Buffer)); + SmBusProcessCall (SmbusAddress, *(UINT16 *)Buffer, &Status); break; case EfiSmbusReadBlock: DEBUG ((DEBUG_INFO, "EfiSmbusReadBlock - 0x%08x\n", SmbusAddress)); @@ -130,31 +130,31 @@ InternalSmbusExecute ( **/ EFI_STATUS BuildLoopData ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, IN UINT64 Address, OUT UINTN *AddressStride, OUT UINTN *BufferStride ) { - UINTN AlignMask; + UINTN AlignMask; if (Width >= S3BootScriptWidthMaximum) { return EFI_INVALID_PARAMETER; } - *AddressStride = (UINT32)(1 << (Width & 0x03)); - *BufferStride = *AddressStride; + *AddressStride = (UINT32)(1 << (Width & 0x03)); + *BufferStride = *AddressStride; - AlignMask = *AddressStride - 1; + AlignMask = *AddressStride - 1; if ((Address & AlignMask) != 0) { return EFI_INVALID_PARAMETER; } - if (Width >= S3BootScriptWidthFifoUint8 && Width <= S3BootScriptWidthFifoUint64) { + if ((Width >= S3BootScriptWidthFifoUint8) && (Width <= S3BootScriptWidthFifoUint64)) { *AddressStride = 0; } - if (Width >= S3BootScriptWidthFillUint8 && Width <= S3BootScriptWidthFillUint64) { + if ((Width >= S3BootScriptWidthFillUint8) && (Width <= S3BootScriptWidthFillUint64)) { *BufferStride = 0; } @@ -178,10 +178,10 @@ BuildLoopData ( **/ EFI_STATUS ScriptIoRead ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - OUT VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + OUT VOID *Buffer ) { EFI_STATUS Status; @@ -189,7 +189,7 @@ ScriptIoRead ( UINTN BufferStride; PTR Out; - Out.Buf = (UINT8 *) Buffer; + Out.Buf = (UINT8 *)Buffer; if (Address > MAX_IO_ADDRESS) { return EFI_INVALID_PARAMETER; @@ -199,66 +199,66 @@ ScriptIoRead ( if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // - for (; Count > 0; Count--, Address += AddressStride, Out.Buf += BufferStride) { + for ( ; Count > 0; Count--, Address += AddressStride, Out.Buf += BufferStride) { switch (Width) { + case S3BootScriptWidthUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = IoRead8 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = IoRead8 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = IoRead8 ((UINTN)Address); + break; - case S3BootScriptWidthUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x\n", (UINTN) Address)); - *Out.Uint8 = IoRead8 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x\n", (UINTN) Address)); - *Out.Uint8 = IoRead8 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x\n", (UINTN) Address)); - *Out.Uint8 = IoRead8 ((UINTN) Address); - break; - - case S3BootScriptWidthUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x\n", (UINTN) Address)); - *Out.Uint16 = IoRead16 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x\n", (UINTN) Address)); - *Out.Uint16 = IoRead16 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x\n", (UINTN) Address)); - *Out.Uint16 = IoRead16 ((UINTN) Address); - break; + case S3BootScriptWidthUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = IoRead16 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = IoRead16 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = IoRead16 ((UINTN)Address); + break; - case S3BootScriptWidthUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x\n", (UINTN) Address)); - *Out.Uint32 = IoRead32 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x\n", (UINTN) Address)); - *Out.Uint32 = IoRead32 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x\n", (UINTN) Address)); - *Out.Uint32 = IoRead32 ((UINTN) Address); - break; + case S3BootScriptWidthUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = IoRead32 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = IoRead32 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = IoRead32 ((UINTN)Address); + break; - case S3BootScriptWidthUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x\n", (UINTN) Address)); - *Out.Uint64 = IoRead64 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x\n", (UINTN) Address)); - *Out.Uint64 = IoRead64 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x\n", (UINTN) Address)); - *Out.Uint64 = IoRead64 ((UINTN) Address); - break; + case S3BootScriptWidthUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = IoRead64 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = IoRead64 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = IoRead64 ((UINTN)Address); + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } } @@ -283,9 +283,9 @@ ScriptIoRead ( EFI_STATUS ScriptIoWrite ( IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { EFI_STATUS Status; @@ -295,7 +295,7 @@ ScriptIoWrite ( PTR In; PTR OriginalIn; - In.Buf = (UINT8 *) Buffer; + In.Buf = (UINT8 *)Buffer; if (Address > MAX_IO_ADDRESS) { return EFI_INVALID_PARAMETER; @@ -305,69 +305,70 @@ ScriptIoWrite ( if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // OriginalAddress = Address; - OriginalIn.Buf = In.Buf; - for (; Count > 0; Count--, Address += AddressStride, In.Buf += BufferStride) { + OriginalIn.Buf = In.Buf; + for ( ; Count > 0; Count--, Address += AddressStride, In.Buf += BufferStride) { switch (Width) { case S3BootScriptWidthUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x (0x%02x)\n", (UINTN)Address, (UINTN)*In.Uint8)); - IoWrite8 ((UINTN) Address, *In.Uint8); + IoWrite8 ((UINTN)Address, *In.Uint8); break; case S3BootScriptWidthFifoUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x (0x%02x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint8)); - IoWrite8 ((UINTN) OriginalAddress, *In.Uint8); + IoWrite8 ((UINTN)OriginalAddress, *In.Uint8); break; case S3BootScriptWidthFillUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x (0x%02x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint8)); - IoWrite8 ((UINTN) Address, *OriginalIn.Uint8); + IoWrite8 ((UINTN)Address, *OriginalIn.Uint8); break; case S3BootScriptWidthUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x (0x%04x)\n", (UINTN)Address, (UINTN)*In.Uint16)); - IoWrite16 ((UINTN) Address, *In.Uint16); + IoWrite16 ((UINTN)Address, *In.Uint16); break; case S3BootScriptWidthFifoUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x (0x%04x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint16)); - IoWrite16 ((UINTN) OriginalAddress, *In.Uint16); + IoWrite16 ((UINTN)OriginalAddress, *In.Uint16); break; case S3BootScriptWidthFillUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x (0x%04x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint16)); - IoWrite16 ((UINTN) Address, *OriginalIn.Uint16); + IoWrite16 ((UINTN)Address, *OriginalIn.Uint16); break; case S3BootScriptWidthUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x (0x%08x)\n", (UINTN)Address, (UINTN)*In.Uint32)); - IoWrite32 ((UINTN) Address, *In.Uint32); + IoWrite32 ((UINTN)Address, *In.Uint32); break; case S3BootScriptWidthFifoUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x (0x%08x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint32)); - IoWrite32 ((UINTN) OriginalAddress, *In.Uint32); + IoWrite32 ((UINTN)OriginalAddress, *In.Uint32); break; case S3BootScriptWidthFillUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x (0x%08x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint32)); - IoWrite32 ((UINTN) Address, *OriginalIn.Uint32); + IoWrite32 ((UINTN)Address, *OriginalIn.Uint32); break; case S3BootScriptWidthUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x (0x%016lx)\n", (UINTN)Address, *In.Uint64)); - IoWrite64 ((UINTN) Address, *In.Uint64); + IoWrite64 ((UINTN)Address, *In.Uint64); break; case S3BootScriptWidthFifoUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x (0x%016lx)\n", (UINTN)OriginalAddress, *In.Uint64)); - IoWrite64 ((UINTN) OriginalAddress, *In.Uint64); + IoWrite64 ((UINTN)OriginalAddress, *In.Uint64); break; case S3BootScriptWidthFillUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x (0x%016lx)\n", (UINTN)Address, *OriginalIn.Uint64)); - IoWrite64 ((UINTN) Address, *OriginalIn.Uint64); + IoWrite64 ((UINTN)Address, *OriginalIn.Uint64); break; default: return EFI_INVALID_PARAMETER; } } - return EFI_SUCCESS; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_IO_WRITE OP code. @@ -382,24 +383,25 @@ ScriptIoWrite ( **/ EFI_STATUS BootScriptExecuteIoWrite ( - IN UINT8 *Script + IN UINT8 *Script ) { - S3_BOOT_SCRIPT_LIB_WIDTH Width; - UINT64 Address; - UINTN Count; + S3_BOOT_SCRIPT_LIB_WIDTH Width; + UINT64 Address; + UINTN Count; VOID *Buffer; - EFI_BOOT_SCRIPT_IO_WRITE IoWrite; + EFI_BOOT_SCRIPT_IO_WRITE IoWrite; - CopyMem ((VOID*)&IoWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_IO_WRITE)); - Width = (S3_BOOT_SCRIPT_LIB_WIDTH) IoWrite.Width; + CopyMem ((VOID *)&IoWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_IO_WRITE)); + Width = (S3_BOOT_SCRIPT_LIB_WIDTH)IoWrite.Width; Address = IoWrite.Address; - Count = IoWrite.Count; - Buffer = Script + sizeof (EFI_BOOT_SCRIPT_IO_WRITE); + Count = IoWrite.Count; + Buffer = Script + sizeof (EFI_BOOT_SCRIPT_IO_WRITE); DEBUG ((DEBUG_INFO, "BootScriptExecuteIoWrite - 0x%08x, 0x%08x, 0x%08x\n", (UINTN)Address, Count, (UINTN)Width)); - return ScriptIoWrite(Width, Address, Count, Buffer); + return ScriptIoWrite (Width, Address, Count, Buffer); } + /** Perform memory read operation @@ -418,10 +420,10 @@ BootScriptExecuteIoWrite ( **/ EFI_STATUS ScriptMemoryRead ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { EFI_STATUS Status; @@ -431,74 +433,76 @@ ScriptMemoryRead ( Out.Buf = Buffer; - Status = BuildLoopData (Width, Address, &AddressStride, &BufferStride); + Status = BuildLoopData (Width, Address, &AddressStride, &BufferStride); if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // - for (; Count > 0; Count--, Address += AddressStride, Out.Buf += BufferStride) { + for ( ; Count > 0; Count--, Address += AddressStride, Out.Buf += BufferStride) { switch (Width) { - case S3BootScriptWidthUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x\n", (UINTN)Address)); - *Out.Uint8 = MmioRead8 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x\n", (UINTN)Address)); - *Out.Uint8 = MmioRead8 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x\n", (UINTN)Address)); - *Out.Uint8 = MmioRead8 ((UINTN) Address); - break; + case S3BootScriptWidthUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = MmioRead8 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = MmioRead8 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x\n", (UINTN)Address)); + *Out.Uint8 = MmioRead8 ((UINTN)Address); + break; - case S3BootScriptWidthUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x\n", (UINTN)Address)); - *Out.Uint16 = MmioRead16 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x\n", (UINTN)Address)); - *Out.Uint16 = MmioRead16 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x\n", (UINTN)Address)); - *Out.Uint16 = MmioRead16 ((UINTN) Address); - break; + case S3BootScriptWidthUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = MmioRead16 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = MmioRead16 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x\n", (UINTN)Address)); + *Out.Uint16 = MmioRead16 ((UINTN)Address); + break; - case S3BootScriptWidthUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x\n", (UINTN)Address)); - *Out.Uint32 = MmioRead32 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x\n", (UINTN)Address)); - *Out.Uint32 = MmioRead32 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x\n", (UINTN)Address)); - *Out.Uint32 = MmioRead32 ((UINTN) Address); - break; + case S3BootScriptWidthUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = MmioRead32 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = MmioRead32 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x\n", (UINTN)Address)); + *Out.Uint32 = MmioRead32 ((UINTN)Address); + break; - case S3BootScriptWidthUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x\n", (UINTN)Address)); - *Out.Uint64 = MmioRead64 ((UINTN) Address); - break; - case S3BootScriptWidthFifoUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x\n", (UINTN)Address)); - *Out.Uint64 = MmioRead64 ((UINTN) Address); - break; - case S3BootScriptWidthFillUint64: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x\n", (UINTN)Address)); - *Out.Uint64 = MmioRead64 ((UINTN) Address); - break; + case S3BootScriptWidthUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = MmioRead64 ((UINTN)Address); + break; + case S3BootScriptWidthFifoUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = MmioRead64 ((UINTN)Address); + break; + case S3BootScriptWidthFillUint64: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x\n", (UINTN)Address)); + *Out.Uint64 = MmioRead64 ((UINTN)Address); + break; - default: - return EFI_UNSUPPORTED; + default: + return EFI_UNSUPPORTED; } } return EFI_SUCCESS; } + /** Perform memory write operation @@ -517,10 +521,10 @@ ScriptMemoryRead ( **/ EFI_STATUS ScriptMemoryWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN OUT VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN OUT VOID *Buffer ) { EFI_STATUS Status; @@ -530,73 +534,76 @@ ScriptMemoryWrite ( PTR In; PTR OriginalIn; - In.Buf = Buffer; + In.Buf = Buffer; - Status = BuildLoopData (Width, Address, &AddressStride, &BufferStride); + Status = BuildLoopData (Width, Address, &AddressStride, &BufferStride); if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // OriginalAddress = Address; - OriginalIn.Buf = In.Buf; - for (; Count > 0; Count--, Address += AddressStride, In.Buf += BufferStride) { + OriginalIn.Buf = In.Buf; + for ( ; Count > 0; Count--, Address += AddressStride, In.Buf += BufferStride) { switch (Width) { case S3BootScriptWidthUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%08x (0x%02x)\n", (UINTN)Address, (UINTN)*In.Uint8)); - MmioWrite8 ((UINTN) Address, *In.Uint8); + MmioWrite8 ((UINTN)Address, *In.Uint8); break; case S3BootScriptWidthFifoUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%08x (0x%02x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint8)); - MmioWrite8 ((UINTN) OriginalAddress, *In.Uint8); + MmioWrite8 ((UINTN)OriginalAddress, *In.Uint8); break; case S3BootScriptWidthFillUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%08x (0x%02x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint8)); - MmioWrite8 ((UINTN) Address, *OriginalIn.Uint8); + MmioWrite8 ((UINTN)Address, *OriginalIn.Uint8); break; case S3BootScriptWidthUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%08x (0x%04x)\n", (UINTN)Address, (UINTN)*In.Uint16)); - MmioWrite16 ((UINTN) Address, *In.Uint16); + MmioWrite16 ((UINTN)Address, *In.Uint16); break; case S3BootScriptWidthFifoUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%08x (0x%04x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint16)); - MmioWrite16 ((UINTN) OriginalAddress, *In.Uint16); + MmioWrite16 ((UINTN)OriginalAddress, *In.Uint16); break; case S3BootScriptWidthFillUint16: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%08x (0x%04x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint16)); - MmioWrite16 ((UINTN) Address, *OriginalIn.Uint16); + MmioWrite16 ((UINTN)Address, *OriginalIn.Uint16); break; case S3BootScriptWidthUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%08x (0x%08x)\n", (UINTN)Address, (UINTN)*In.Uint32)); - MmioWrite32 ((UINTN) Address, *In.Uint32); + MmioWrite32 ((UINTN)Address, *In.Uint32); break; case S3BootScriptWidthFifoUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%08x (0x%08x)\n", (UINTN)OriginalAddress, (UINTN)*In.Uint32)); - MmioWrite32 ((UINTN) OriginalAddress, *In.Uint32); + MmioWrite32 ((UINTN)OriginalAddress, *In.Uint32); break; case S3BootScriptWidthFillUint32: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%08x (0x%08x)\n", (UINTN)Address, (UINTN)*OriginalIn.Uint32)); - MmioWrite32 ((UINTN) Address, *OriginalIn.Uint32); + MmioWrite32 ((UINTN)Address, *OriginalIn.Uint32); break; case S3BootScriptWidthUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint64 - 0x%08x (0x%016lx)\n", (UINTN)Address, *In.Uint64)); - MmioWrite64 ((UINTN) Address, *In.Uint64); + MmioWrite64 ((UINTN)Address, *In.Uint64); break; case S3BootScriptWidthFifoUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint64 - 0x%08x (0x%016lx)\n", (UINTN)OriginalAddress, *In.Uint64)); - MmioWrite64 ((UINTN) OriginalAddress, *In.Uint64); + MmioWrite64 ((UINTN)OriginalAddress, *In.Uint64); break; case S3BootScriptWidthFillUint64: DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint64 - 0x%08x (0x%016lx)\n", (UINTN)Address, *OriginalIn.Uint64)); - MmioWrite64 ((UINTN) Address, *OriginalIn.Uint64); + MmioWrite64 ((UINTN)Address, *OriginalIn.Uint64); break; default: return EFI_UNSUPPORTED; } } + return EFI_SUCCESS; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_MEM_WRITE OP code. @@ -612,25 +619,25 @@ ScriptMemoryWrite ( **/ EFI_STATUS BootScriptExecuteMemoryWrite ( - IN UINT8 *Script + IN UINT8 *Script ) { - VOID *Buffer; - S3_BOOT_SCRIPT_LIB_WIDTH Width; - UINT64 Address; - UINTN Count; + VOID *Buffer; + S3_BOOT_SCRIPT_LIB_WIDTH Width; + UINT64 Address; + UINTN Count; EFI_BOOT_SCRIPT_MEM_WRITE MemWrite; - CopyMem((VOID*)&MemWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_MEM_WRITE)); + CopyMem ((VOID *)&MemWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_MEM_WRITE)); Width = (S3_BOOT_SCRIPT_LIB_WIDTH)MemWrite.Width; Address = MemWrite.Address; Count = MemWrite.Count; - Buffer = Script + sizeof(EFI_BOOT_SCRIPT_MEM_WRITE); + Buffer = Script + sizeof (EFI_BOOT_SCRIPT_MEM_WRITE); DEBUG ((DEBUG_INFO, "BootScriptExecuteMemoryWrite - 0x%08x, 0x%08x, 0x%08x\n", (UINTN)Address, Count, (UINTN)Width)); - return ScriptMemoryWrite (Width,Address, Count, Buffer); - + return ScriptMemoryWrite (Width, Address, Count, Buffer); } + /** Performance PCI configuration 2 read operation @@ -647,11 +654,11 @@ BootScriptExecuteMemoryWrite ( **/ EFI_STATUS ScriptPciCfg2Read ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT16 Segment, - IN UINT64 Address, - IN UINTN Count, - OUT VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT16 Segment, + IN UINT64 Address, + IN UINTN Count, + OUT VOID *Buffer ) { EFI_STATUS Status; @@ -660,7 +667,7 @@ ScriptPciCfg2Read ( PTR Out; UINT64 PciAddress; - Out.Buf = (UINT8 *) Buffer; + Out.Buf = (UINT8 *)Buffer; PciAddress = PCI_ADDRESS_ENCODE (Segment, Address); @@ -668,54 +675,56 @@ ScriptPciCfg2Read ( if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // - for (; Count > 0; Count--, PciAddress += AddressStride, Out.Buf += BufferStride) { + for ( ; Count > 0; Count--, PciAddress += AddressStride, Out.Buf += BufferStride) { switch (Width) { - case S3BootScriptWidthUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%016lx\n", PciAddress)); - *Out.Uint8 = PciSegmentRead8 (PciAddress); - break; - case S3BootScriptWidthFifoUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%016lx\n", PciAddress)); - *Out.Uint8 = PciSegmentRead8 (PciAddress); - break; - case S3BootScriptWidthFillUint8: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%016lx\n", PciAddress)); - *Out.Uint8 = PciSegmentRead8 (PciAddress); - break; + case S3BootScriptWidthUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%016lx\n", PciAddress)); + *Out.Uint8 = PciSegmentRead8 (PciAddress); + break; + case S3BootScriptWidthFifoUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint8 - 0x%016lx\n", PciAddress)); + *Out.Uint8 = PciSegmentRead8 (PciAddress); + break; + case S3BootScriptWidthFillUint8: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint8 - 0x%016lx\n", PciAddress)); + *Out.Uint8 = PciSegmentRead8 (PciAddress); + break; - case S3BootScriptWidthUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%016lx\n", PciAddress)); - *Out.Uint16 = PciSegmentRead16 (PciAddress); - break; - case S3BootScriptWidthFifoUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%016lx\n", PciAddress)); - *Out.Uint16 = PciSegmentRead16 (PciAddress); - break; - case S3BootScriptWidthFillUint16: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%016lx\n", PciAddress)); - *Out.Uint16 = PciSegmentRead16 (PciAddress); - break; + case S3BootScriptWidthUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint16 - 0x%016lx\n", PciAddress)); + *Out.Uint16 = PciSegmentRead16 (PciAddress); + break; + case S3BootScriptWidthFifoUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint16 - 0x%016lx\n", PciAddress)); + *Out.Uint16 = PciSegmentRead16 (PciAddress); + break; + case S3BootScriptWidthFillUint16: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint16 - 0x%016lx\n", PciAddress)); + *Out.Uint16 = PciSegmentRead16 (PciAddress); + break; - case S3BootScriptWidthUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%016lx\n", PciAddress)); - *Out.Uint32 = PciSegmentRead32 (PciAddress); - break; - case S3BootScriptWidthFifoUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%016lx\n", PciAddress)); - *Out.Uint32 = PciSegmentRead32 (PciAddress); - break; - case S3BootScriptWidthFillUint32: - DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%016lx\n", PciAddress)); - *Out.Uint32 = PciSegmentRead32 (PciAddress); - break; + case S3BootScriptWidthUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint32 - 0x%016lx\n", PciAddress)); + *Out.Uint32 = PciSegmentRead32 (PciAddress); + break; + case S3BootScriptWidthFifoUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFifoUint32 - 0x%016lx\n", PciAddress)); + *Out.Uint32 = PciSegmentRead32 (PciAddress); + break; + case S3BootScriptWidthFillUint32: + DEBUG ((DEBUG_INFO, "S3BootScriptWidthFillUint32 - 0x%016lx\n", PciAddress)); + *Out.Uint32 = PciSegmentRead32 (PciAddress); + break; - default: - return EFI_INVALID_PARAMETER; + default: + return EFI_INVALID_PARAMETER; } } + return EFI_SUCCESS; } @@ -735,11 +744,11 @@ ScriptPciCfg2Read ( **/ EFI_STATUS ScriptPciCfg2Write ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT16 Segment, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT16 Segment, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { EFI_STATUS Status; @@ -750,7 +759,7 @@ ScriptPciCfg2Write ( PTR OriginalIn; UINT64 PciAddress; - In.Buf = (UINT8 *) Buffer; + In.Buf = (UINT8 *)Buffer; PciAddress = PCI_ADDRESS_ENCODE (Segment, Address); @@ -758,12 +767,13 @@ ScriptPciCfg2Write ( if (EFI_ERROR (Status)) { return Status; } + // // Loop for each iteration and move the data // OriginalPciAddress = PciAddress; - OriginalIn.Buf = In.Buf; - for (; Count > 0; Count--, PciAddress += AddressStride, In.Buf += BufferStride) { + OriginalIn.Buf = In.Buf; + for ( ; Count > 0; Count--, PciAddress += AddressStride, In.Buf += BufferStride) { switch (Width) { case S3BootScriptWidthUint8: DEBUG ((DEBUG_INFO, "S3BootScriptWidthUint8 - 0x%016lx (0x%02x)\n", PciAddress, (UINTN)*In.Uint8)); @@ -805,8 +815,10 @@ ScriptPciCfg2Write ( return EFI_INVALID_PARAMETER; } } + return EFI_SUCCESS; } + /** Performance PCI configuration read operation @@ -824,14 +836,15 @@ ScriptPciCfg2Write ( **/ EFI_STATUS ScriptPciCfgRead ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - OUT VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + OUT VOID *Buffer ) { return ScriptPciCfg2Read (Width, 0, Address, Count, Buffer); } + /** Performance PCI configuration write operation @@ -850,14 +863,15 @@ ScriptPciCfgRead ( EFI_STATUS EFIAPI ScriptPciCfgWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { return ScriptPciCfg2Write (Width, 0, Address, Count, Buffer); } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE OP code. @@ -867,7 +881,7 @@ ScriptPciCfgWrite ( **/ EFI_STATUS BootScriptExecutePciCfgWrite ( - IN UINT8 *Script + IN UINT8 *Script ) { VOID *Buffer; @@ -876,16 +890,17 @@ BootScriptExecutePciCfgWrite ( UINTN Count; EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE PciCfgWrite; - CopyMem ((VOID*)&PciCfgWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)); + CopyMem ((VOID *)&PciCfgWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)); Width = (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfgWrite.Width; Address = PciCfgWrite.Address; Count = PciCfgWrite.Count; - Buffer = Script + sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE); + Buffer = Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE); DEBUG ((DEBUG_INFO, "BootScriptExecutePciCfgWrite - 0x%016lx, 0x%08x, 0x%08x\n", PCI_ADDRESS_ENCODE (0, Address), Count, (UINTN)Width)); return ScriptPciCfgWrite (Width, Address, Count, Buffer); } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_IO_READ_WRITE OP code. @@ -897,39 +912,41 @@ BootScriptExecutePciCfgWrite ( **/ EFI_STATUS BootScriptExecuteIoReadWrite ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - EFI_STATUS Status; - UINT64 Data; - EFI_BOOT_SCRIPT_IO_READ_WRITE IoReadWrite; + EFI_STATUS Status; + UINT64 Data; + EFI_BOOT_SCRIPT_IO_READ_WRITE IoReadWrite; Data = 0; - CopyMem((VOID*)&IoReadWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_IO_READ_WRITE)); + CopyMem ((VOID *)&IoReadWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE)); DEBUG ((DEBUG_INFO, "BootScriptExecuteIoReadWrite - 0x%08x, 0x%016lx, 0x%016lx\n", (UINTN)IoReadWrite.Address, AndMask, OrMask)); Status = ScriptIoRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) IoReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)IoReadWrite.Width, IoReadWrite.Address, 1, &Data ); if (!EFI_ERROR (Status)) { - Data = (Data & AndMask) | OrMask; + Data = (Data & AndMask) | OrMask; Status = ScriptIoWrite ( - (S3_BOOT_SCRIPT_LIB_WIDTH) IoReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)IoReadWrite.Width, IoReadWrite.Address, 1, &Data ); } + return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_MEM_READ_WRITE OP code. @@ -941,39 +958,41 @@ BootScriptExecuteIoReadWrite ( **/ EFI_STATUS BootScriptExecuteMemoryReadWrite ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - EFI_STATUS Status; - UINT64 Data; + EFI_STATUS Status; + UINT64 Data; EFI_BOOT_SCRIPT_MEM_READ_WRITE MemReadWrite; Data = 0; - CopyMem((VOID*)&MemReadWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_MEM_READ_WRITE)); + CopyMem ((VOID *)&MemReadWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE)); DEBUG ((DEBUG_INFO, "BootScriptExecuteMemoryReadWrite - 0x%08x, 0x%016lx, 0x%016lx\n", (UINTN)MemReadWrite.Address, AndMask, OrMask)); Status = ScriptMemoryRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) MemReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)MemReadWrite.Width, MemReadWrite.Address, 1, &Data ); if (!EFI_ERROR (Status)) { - Data = (Data & AndMask) | OrMask; + Data = (Data & AndMask) | OrMask; Status = ScriptMemoryWrite ( - (S3_BOOT_SCRIPT_LIB_WIDTH) MemReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)MemReadWrite.Width, MemReadWrite.Address, 1, &Data ); } + return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_PCI_CFG_READ_WRITE OP code. @@ -985,24 +1004,24 @@ BootScriptExecuteMemoryReadWrite ( **/ EFI_STATUS BootScriptExecutePciCfgReadWrite ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - EFI_STATUS Status; - UINT64 Data; + EFI_STATUS Status; + UINT64 Data; EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE PciCfgReadWrite; Data = 0; - CopyMem((VOID*)&PciCfgReadWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)); + CopyMem ((VOID *)&PciCfgReadWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)); DEBUG ((DEBUG_INFO, "BootScriptExecutePciCfgReadWrite - 0x%016lx, 0x%016lx, 0x%016lx\n", PCI_ADDRESS_ENCODE (0, PciCfgReadWrite.Address), AndMask, OrMask)); Status = ScriptPciCfgRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfgReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfgReadWrite.Width, PciCfgReadWrite.Address, 1, &Data @@ -1014,7 +1033,7 @@ BootScriptExecutePciCfgReadWrite ( Data = (Data & AndMask) | OrMask; Status = ScriptPciCfgWrite ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfgReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfgReadWrite.Width, PciCfgReadWrite.Address, 1, &Data @@ -1022,6 +1041,7 @@ BootScriptExecutePciCfgReadWrite ( return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_SMBUS_EXECUTE OP code. @@ -1033,26 +1053,27 @@ BootScriptExecutePciCfgReadWrite ( **/ EFI_STATUS BootScriptExecuteSmbusExecute ( - IN UINT8 *Script + IN UINT8 *Script ) { - UINTN SmBusAddress; - UINTN DataSize; - EFI_BOOT_SCRIPT_SMBUS_EXECUTE SmbusExecuteEntry; + UINTN SmBusAddress; + UINTN DataSize; + EFI_BOOT_SCRIPT_SMBUS_EXECUTE SmbusExecuteEntry; - CopyMem ((VOID*)&SmbusExecuteEntry, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_SMBUS_EXECUTE )); + CopyMem ((VOID *)&SmbusExecuteEntry, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)); DEBUG ((DEBUG_INFO, "BootScriptExecuteSmbusExecute - 0x%08x, 0x%08x\n", (UINTN)SmbusExecuteEntry.SmBusAddress, (UINTN)SmbusExecuteEntry.Operation)); SmBusAddress = (UINTN)SmbusExecuteEntry.SmBusAddress; - DataSize = (UINTN) SmbusExecuteEntry.DataSize; + DataSize = (UINTN)SmbusExecuteEntry.DataSize; return InternalSmbusExecute ( SmBusAddress, - (EFI_SMBUS_OPERATION) SmbusExecuteEntry.Operation, + (EFI_SMBUS_OPERATION)SmbusExecuteEntry.Operation, &DataSize, Script + sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE) ); } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_STALL OP code. @@ -1062,18 +1083,19 @@ BootScriptExecuteSmbusExecute ( **/ EFI_STATUS BootScriptExecuteStall ( - IN UINT8 *Script + IN UINT8 *Script ) { - EFI_BOOT_SCRIPT_STALL Stall; + EFI_BOOT_SCRIPT_STALL Stall; - CopyMem ((VOID*)&Stall, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_STALL)); + CopyMem ((VOID *)&Stall, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_STALL)); DEBUG ((DEBUG_INFO, "BootScriptExecuteStall - 0x%08x\n", (UINTN)Stall.Duration)); - MicroSecondDelay ((UINTN) Stall.Duration); + MicroSecondDelay ((UINTN)Stall.Duration); return EFI_SUCCESS; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_DISPATCH OP code. @@ -1082,22 +1104,23 @@ BootScriptExecuteStall ( **/ EFI_STATUS BootScriptExecuteDispatch ( - IN UINT8 *Script + IN UINT8 *Script ) { EFI_STATUS Status; DISPATCH_ENTRYPOINT_FUNC EntryFunc; EFI_BOOT_SCRIPT_DISPATCH ScriptDispatch; - CopyMem ((VOID*)&ScriptDispatch, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_DISPATCH)); - EntryFunc = (DISPATCH_ENTRYPOINT_FUNC) (UINTN) (ScriptDispatch.EntryPoint); + CopyMem ((VOID *)&ScriptDispatch, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_DISPATCH)); + EntryFunc = (DISPATCH_ENTRYPOINT_FUNC)(UINTN)(ScriptDispatch.EntryPoint); DEBUG ((DEBUG_INFO, "BootScriptExecuteDispatch - 0x%08x\n", (UINTN)ScriptDispatch.EntryPoint)); - Status = EntryFunc (NULL, NULL); + Status = EntryFunc (NULL, NULL); return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_DISPATCH_2 OP code. @@ -1106,23 +1129,24 @@ BootScriptExecuteDispatch ( **/ EFI_STATUS BootScriptExecuteDispatch2 ( - IN UINT8 *Script + IN UINT8 *Script ) { - EFI_STATUS Status; - DISPATCH_ENTRYPOINT_FUNC EntryFunc; + EFI_STATUS Status; + DISPATCH_ENTRYPOINT_FUNC EntryFunc; EFI_BOOT_SCRIPT_DISPATCH_2 ScriptDispatch2; - CopyMem ((VOID*)&ScriptDispatch2, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_DISPATCH_2)); + CopyMem ((VOID *)&ScriptDispatch2, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_DISPATCH_2)); DEBUG ((DEBUG_INFO, "BootScriptExecuteDispatch2 - 0x%08x(0x%08x)\n", (UINTN)ScriptDispatch2.EntryPoint, (UINTN)ScriptDispatch2.Context)); - EntryFunc = (DISPATCH_ENTRYPOINT_FUNC) (UINTN) (ScriptDispatch2.EntryPoint); + EntryFunc = (DISPATCH_ENTRYPOINT_FUNC)(UINTN)(ScriptDispatch2.EntryPoint); - Status = EntryFunc (NULL, (VOID *) (UINTN) ScriptDispatch2.Context); + Status = EntryFunc (NULL, (VOID *)(UINTN)ScriptDispatch2.Context); return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_MEM_POLL OP code. @@ -1136,45 +1160,44 @@ BootScriptExecuteDispatch2 ( **/ EFI_STATUS BootScriptExecuteMemPoll ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { + UINT64 Data; + UINT64 LoopTimes; + EFI_STATUS Status; + EFI_BOOT_SCRIPT_MEM_POLL MemPoll; - UINT64 Data; - UINT64 LoopTimes; - EFI_STATUS Status; - EFI_BOOT_SCRIPT_MEM_POLL MemPoll; - - CopyMem ((VOID*)&MemPoll, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_MEM_POLL)); + CopyMem ((VOID *)&MemPoll, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_MEM_POLL)); DEBUG ((DEBUG_INFO, "BootScriptExecuteMemPoll - 0x%08x, 0x%016lx, 0x%016lx\n", (UINTN)MemPoll.Address, AndMask, OrMask)); - Data = 0; + Data = 0; Status = ScriptMemoryRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) MemPoll.Width, - MemPoll.Address, - 1, - &Data - ); - if ((!EFI_ERROR (Status)) && (Data & AndMask) == OrMask) { + (S3_BOOT_SCRIPT_LIB_WIDTH)MemPoll.Width, + MemPoll.Address, + 1, + &Data + ); + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } for (LoopTimes = 0; LoopTimes < MemPoll.LoopTimes; LoopTimes++) { MicroSecondDelay ((UINTN)MemPoll.Duration); - Data = 0; + Data = 0; Status = ScriptMemoryRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) MemPoll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)MemPoll.Width, MemPoll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) && (Data & AndMask) == OrMask) { - return EFI_SUCCESS; - } + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { + return EFI_SUCCESS; + } } if (LoopTimes < MemPoll.LoopTimes) { @@ -1183,6 +1206,7 @@ BootScriptExecuteMemPoll ( return EFI_DEVICE_ERROR; } } + /** Execute the boot script to interpret the Store arbitrary information. This opcode is a no-op on dispatch and is only used for debugging script issues. @@ -1192,23 +1216,24 @@ BootScriptExecuteMemPoll ( **/ VOID BootScriptExecuteInformation ( - IN UINT8 *Script + IN UINT8 *Script ) { - UINT32 Index; - EFI_BOOT_SCRIPT_INFORMATION Information; - UINT8 *InformationData; + UINT32 Index; + EFI_BOOT_SCRIPT_INFORMATION Information; + UINT8 *InformationData; - CopyMem ((VOID*)&Information, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_INFORMATION)); + CopyMem ((VOID *)&Information, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); InformationData = Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION); - DEBUG ((DEBUG_INFO, "BootScriptExecuteInformation - 0x%08x\n", (UINTN) InformationData)); + DEBUG ((DEBUG_INFO, "BootScriptExecuteInformation - 0x%08x\n", (UINTN)InformationData)); DEBUG ((DEBUG_INFO, "BootScriptInformation: ")); for (Index = 0; Index < Information.InformationLength; Index++) { DEBUG ((DEBUG_INFO, "%02x ", InformationData[Index])); } + DEBUG ((DEBUG_INFO, "\n")); } @@ -1220,23 +1245,24 @@ BootScriptExecuteInformation ( **/ VOID BootScriptExecuteLabel ( - IN UINT8 *Script + IN UINT8 *Script ) { - UINT32 Index; - EFI_BOOT_SCRIPT_INFORMATION Information; - UINT8 *InformationData; + UINT32 Index; + EFI_BOOT_SCRIPT_INFORMATION Information; + UINT8 *InformationData; - CopyMem ((VOID*)&Information, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_INFORMATION)); + CopyMem ((VOID *)&Information, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); InformationData = Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION); - DEBUG ((DEBUG_INFO, "BootScriptExecuteLabel - 0x%08x\n", (UINTN) InformationData)); + DEBUG ((DEBUG_INFO, "BootScriptExecuteLabel - 0x%08x\n", (UINTN)InformationData)); DEBUG ((DEBUG_INFO, "BootScriptLabel: ")); for (Index = 0; Index < Information.InformationLength; Index++) { DEBUG ((DEBUG_INFO, "%02x ", InformationData[Index])); } + DEBUG ((DEBUG_INFO, "\n")); } @@ -1251,79 +1277,80 @@ BootScriptExecuteLabel ( VOID CheckAndOrMask ( IN EFI_BOOT_SCRIPT_COMMON_HEADER *ScriptHeader, - OUT UINT64 *AndMask, - OUT UINT64 *OrMask, - IN UINT8 *Script + OUT UINT64 *AndMask, + OUT UINT64 *OrMask, + IN UINT8 *Script ) { - UINT8 *DataPtr; - UINTN Size; + UINT8 *DataPtr; + UINTN Size; switch (ScriptHeader->OpCode) { - case EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE); - break; - - case EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE); - break; - - case EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE); - break; - case EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_MEM_POLL); - break; - - case EFI_BOOT_SCRIPT_IO_POLL_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_IO_POLL); - break; - - case EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE); - break; - - case EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL); - break; - - case EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE: - Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL); - break; - - default: - return; + case EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE); + break; + + case EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE); + break; + + case EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE); + break; + case EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_MEM_POLL); + break; + + case EFI_BOOT_SCRIPT_IO_POLL_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_IO_POLL); + break; + + case EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE); + break; + + case EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL); + break; + + case EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE: + Size = sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL); + break; + + default: + return; } DataPtr = Script + Size; switch (ScriptHeader->Width) { - case S3BootScriptWidthUint8: - *AndMask = (UINT64) (*(UINT8*) (DataPtr + 1)); - *OrMask = (UINT64) (*DataPtr); - break; - - case S3BootScriptWidthUint16: - *AndMask = (UINT64) (*(UINT16 *) (DataPtr + 2)); - *OrMask = (UINT64) (*(UINT16 *) DataPtr); - break; - - case S3BootScriptWidthUint32: - *AndMask = (UINT64) (*(UINT32 *) (DataPtr + 4)); - *OrMask = (UINT64) (*(UINT32 *) DataPtr); - break; - - case S3BootScriptWidthUint64: - *AndMask = (UINT64) (*(UINT64 *) (DataPtr + 8)); - *OrMask = (UINT64) (*(UINT64 *) DataPtr); - break; - - default: - break; + case S3BootScriptWidthUint8: + *AndMask = (UINT64)(*(UINT8 *)(DataPtr + 1)); + *OrMask = (UINT64)(*DataPtr); + break; + + case S3BootScriptWidthUint16: + *AndMask = (UINT64)(*(UINT16 *)(DataPtr + 2)); + *OrMask = (UINT64)(*(UINT16 *)DataPtr); + break; + + case S3BootScriptWidthUint32: + *AndMask = (UINT64)(*(UINT32 *)(DataPtr + 4)); + *OrMask = (UINT64)(*(UINT32 *)DataPtr); + break; + + case S3BootScriptWidthUint64: + *AndMask = (UINT64)(*(UINT64 *)(DataPtr + 8)); + *OrMask = (UINT64)(*(UINT64 *)DataPtr); + break; + + default: + break; } return; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_IO_POLL OP code. @@ -1337,40 +1364,41 @@ CheckAndOrMask ( **/ EFI_STATUS BootScriptExecuteIoPoll ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 LoopTimes; - EFI_BOOT_SCRIPT_IO_POLL IoPoll; + EFI_STATUS Status; + UINT64 Data; + UINT64 LoopTimes; + EFI_BOOT_SCRIPT_IO_POLL IoPoll; - CopyMem ((VOID*)&IoPoll, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_IO_POLL)); + CopyMem ((VOID *)&IoPoll, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_IO_POLL)); DEBUG ((DEBUG_INFO, "BootScriptExecuteIoPoll - 0x%08x, 0x%016lx, 0x%016lx\n", (UINTN)IoPoll.Address, AndMask, OrMask)); - Data = 0; + Data = 0; Status = ScriptIoRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) IoPoll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)IoPoll.Width, IoPoll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) && (Data & AndMask) == OrMask) { + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } + for (LoopTimes = 0; LoopTimes < IoPoll.Delay; LoopTimes++) { NanoSecondDelay (100); - Data = 0; + Data = 0; Status = ScriptIoRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) IoPoll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)IoPoll.Width, IoPoll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) &&(Data & AndMask) == OrMask) { + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } } @@ -1381,6 +1409,7 @@ BootScriptExecuteIoPoll ( return EFI_DEVICE_ERROR; } } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE OP code. @@ -1391,29 +1420,28 @@ BootScriptExecuteIoPoll ( **/ EFI_STATUS BootScriptExecutePciCfg2Write ( - IN UINT8 *Script + IN UINT8 *Script ) { - VOID *Buffer; - S3_BOOT_SCRIPT_LIB_WIDTH Width; - UINT16 Segment; - UINT64 Address; - UINTN Count; - EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE PciCfg2Write; + VOID *Buffer; + S3_BOOT_SCRIPT_LIB_WIDTH Width; + UINT16 Segment; + UINT64 Address; + UINTN Count; + EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE PciCfg2Write; - CopyMem ((VOID*)&PciCfg2Write, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)); + CopyMem ((VOID *)&PciCfg2Write, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)); Width = (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfg2Write.Width; Segment = PciCfg2Write.Segment; Address = PciCfg2Write.Address; Count = PciCfg2Write.Count; - Buffer = Script + sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE); + Buffer = Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE); DEBUG ((DEBUG_INFO, "BootScriptExecutePciCfg2Write - 0x%016lx, 0x%08x, 0x%08x\n", PCI_ADDRESS_ENCODE (Segment, Address), Count, (UINTN)Width)); return ScriptPciCfg2Write (Width, Segment, Address, Count, Buffer); } - /** Interpret the boot script node with EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE OP code. @@ -1426,23 +1454,23 @@ BootScriptExecutePciCfg2Write ( **/ EFI_STATUS BootScriptExecutePciCfg2ReadWrite ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - UINT64 Data; - EFI_STATUS Status; - EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE PciCfg2ReadWrite; + UINT64 Data; + EFI_STATUS Status; + EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE PciCfg2ReadWrite; Data = 0; - CopyMem ((VOID*)&PciCfg2ReadWrite, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)); + CopyMem ((VOID *)&PciCfg2ReadWrite, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)); DEBUG ((DEBUG_INFO, "BootScriptExecutePciCfg2ReadWrite - 0x%016lx, 0x%016lx, 0x%016lx\n", PCI_ADDRESS_ENCODE (PciCfg2ReadWrite.Segment, PciCfg2ReadWrite.Address), AndMask, OrMask)); Status = ScriptPciCfg2Read ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfg2ReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfg2ReadWrite.Width, PciCfg2ReadWrite.Segment, PciCfg2ReadWrite.Address, 1, @@ -1452,9 +1480,9 @@ BootScriptExecutePciCfg2ReadWrite ( return Status; } - Data = (Data & AndMask) | OrMask; + Data = (Data & AndMask) | OrMask; Status = ScriptPciCfg2Write ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfg2ReadWrite.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfg2ReadWrite.Width, PciCfg2ReadWrite.Segment, PciCfg2ReadWrite.Address, 1, @@ -1462,6 +1490,7 @@ BootScriptExecutePciCfg2ReadWrite ( ); return Status; } + /** Interpret the boot script node with EFI_BOOT_SCRIPT_PCI_CONFIG_POLL OP code. @@ -1475,41 +1504,43 @@ BootScriptExecutePciCfg2ReadWrite ( **/ EFI_STATUS BootScriptPciCfgPoll ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - UINT64 Data; - UINT64 LoopTimes; - EFI_STATUS Status; - EFI_BOOT_SCRIPT_PCI_CONFIG_POLL PciCfgPoll; - CopyMem ((VOID*)&PciCfgPoll, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)); + UINT64 Data; + UINT64 LoopTimes; + EFI_STATUS Status; + EFI_BOOT_SCRIPT_PCI_CONFIG_POLL PciCfgPoll; + + CopyMem ((VOID *)&PciCfgPoll, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)); DEBUG ((DEBUG_INFO, "BootScriptPciCfgPoll - 0x%016lx, 0x%016lx, 0x%016lx\n", PCI_ADDRESS_ENCODE (0, PciCfgPoll.Address), AndMask, OrMask)); - Data = 0; + Data = 0; Status = ScriptPciCfgRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfgPoll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfgPoll.Width, PciCfgPoll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) &&(Data & AndMask) == OrMask) { + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } for (LoopTimes = 0; LoopTimes < PciCfgPoll.Delay; LoopTimes++) { NanoSecondDelay (100); - Data = 0; + Data = 0; Status = ScriptPciCfgRead ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfgPoll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfgPoll.Width, PciCfgPoll.Address, 1, &Data ); if ((!EFI_ERROR (Status)) && - (Data & AndMask) == OrMask) { + ((Data & AndMask) == OrMask)) + { return EFI_SUCCESS; } } @@ -1535,44 +1566,44 @@ BootScriptPciCfgPoll ( **/ EFI_STATUS BootScriptPciCfg2Poll ( - IN UINT8 *Script, - IN UINT64 AndMask, - IN UINT64 OrMask + IN UINT8 *Script, + IN UINT64 AndMask, + IN UINT64 OrMask ) { - EFI_STATUS Status; - UINT64 Data; - UINT64 LoopTimes; - EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL PciCfg2Poll; + EFI_STATUS Status; + UINT64 Data; + UINT64 LoopTimes; + EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL PciCfg2Poll; Data = 0; - CopyMem ((VOID*)&PciCfg2Poll, (VOID*)Script, sizeof(EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)); + CopyMem ((VOID *)&PciCfg2Poll, (VOID *)Script, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)); DEBUG ((DEBUG_INFO, "BootScriptPciCfg2Poll - 0x%016lx, 0x%016lx, 0x%016lx\n", PCI_ADDRESS_ENCODE (PciCfg2Poll.Segment, PciCfg2Poll.Address), AndMask, OrMask)); Status = ScriptPciCfg2Read ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfg2Poll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfg2Poll.Width, PciCfg2Poll.Segment, PciCfg2Poll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) && (Data & AndMask) == OrMask) { + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } for (LoopTimes = 0; LoopTimes < PciCfg2Poll.Delay; LoopTimes++) { NanoSecondDelay (100); - Data = 0; + Data = 0; Status = ScriptPciCfg2Read ( - (S3_BOOT_SCRIPT_LIB_WIDTH) PciCfg2Poll.Width, + (S3_BOOT_SCRIPT_LIB_WIDTH)PciCfg2Poll.Width, PciCfg2Poll.Segment, PciCfg2Poll.Address, 1, &Data ); - if ((!EFI_ERROR (Status)) && (Data & AndMask) == OrMask) { + if ((!EFI_ERROR (Status)) && ((Data & AndMask) == OrMask)) { return EFI_SUCCESS; } } @@ -1582,7 +1613,6 @@ BootScriptPciCfg2Poll ( } else { return EFI_DEVICE_ERROR; } - } /** @@ -1598,17 +1628,18 @@ S3BootScriptExecute ( VOID ) { - EFI_STATUS Status; - UINT8* Script; - UINTN StartAddress; - UINT32 TableLength; - UINT64 AndMask; - UINT64 OrMask; + EFI_STATUS Status; + UINT8 *Script; + UINTN StartAddress; + UINT32 TableLength; + UINT64 AndMask; + UINT64 OrMask; EFI_BOOT_SCRIPT_COMMON_HEADER ScriptHeader; EFI_BOOT_SCRIPT_TABLE_HEADER TableHeader; + Script = mS3BootScriptTablePtr->TableBase; if (Script != 0) { - CopyMem ((VOID*)&TableHeader, Script, sizeof(EFI_BOOT_SCRIPT_TABLE_HEADER)); + CopyMem ((VOID *)&TableHeader, Script, sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER)); } else { return EFI_INVALID_PARAMETER; } @@ -1620,145 +1651,144 @@ S3BootScriptExecute ( DEBUG ((DEBUG_INFO, "TableHeader - 0x%08x\n", Script)); - StartAddress = (UINTN) Script; - TableLength = TableHeader.TableLength; - Script = Script + TableHeader.Length; - Status = EFI_SUCCESS; - AndMask = 0; - OrMask = 0; + StartAddress = (UINTN)Script; + TableLength = TableHeader.TableLength; + Script = Script + TableHeader.Length; + Status = EFI_SUCCESS; + AndMask = 0; + OrMask = 0; DEBUG ((DEBUG_INFO, "TableHeader.Version - 0x%04x\n", (UINTN)TableHeader.Version)); DEBUG ((DEBUG_INFO, "TableHeader.TableLength - 0x%08x\n", (UINTN)TableLength)); - while ((UINTN) Script < (UINTN) (StartAddress + TableLength)) { + while ((UINTN)Script < (UINTN)(StartAddress + TableLength)) { DEBUG ((DEBUG_INFO, "ExecuteBootScript - %08x\n", (UINTN)Script)); - CopyMem ((VOID*)&ScriptHeader, Script, sizeof(EFI_BOOT_SCRIPT_COMMON_HEADER)); + CopyMem ((VOID *)&ScriptHeader, Script, sizeof (EFI_BOOT_SCRIPT_COMMON_HEADER)); switch (ScriptHeader.OpCode) { + case EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE\n")); + Status = BootScriptExecuteMemoryWrite (Script); + break; - case EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE\n")); - Status = BootScriptExecuteMemoryWrite (Script); - break; - - case EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecuteMemoryReadWrite ( - Script, - AndMask, - OrMask - ); - break; + case EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecuteMemoryReadWrite ( + Script, + AndMask, + OrMask + ); + break; - case EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_WRITE_OPCODE\n")); - Status = BootScriptExecuteIoWrite (Script); - break; + case EFI_BOOT_SCRIPT_IO_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_WRITE_OPCODE\n")); + Status = BootScriptExecuteIoWrite (Script); + break; - case EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE\n")); - Status = BootScriptExecutePciCfgWrite (Script); - break; + case EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE\n")); + Status = BootScriptExecutePciCfgWrite (Script); + break; - case EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecutePciCfgReadWrite ( - Script, - AndMask, - OrMask - ); - break; - case EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE\n")); - Status = BootScriptExecutePciCfg2Write (Script); - break; + case EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecutePciCfgReadWrite ( + Script, + AndMask, + OrMask + ); + break; + case EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE\n")); + Status = BootScriptExecutePciCfg2Write (Script); + break; - case EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecutePciCfg2ReadWrite ( - Script, - AndMask, - OrMask - ); - break; - case EFI_BOOT_SCRIPT_DISPATCH_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_DISPATCH_OPCODE\n")); - Status = BootScriptExecuteDispatch (Script); - break; + case EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecutePciCfg2ReadWrite ( + Script, + AndMask, + OrMask + ); + break; + case EFI_BOOT_SCRIPT_DISPATCH_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_DISPATCH_OPCODE\n")); + Status = BootScriptExecuteDispatch (Script); + break; - case EFI_BOOT_SCRIPT_DISPATCH_2_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_DISPATCH_2_OPCODE\n")); - Status = BootScriptExecuteDispatch2 (Script); - break; + case EFI_BOOT_SCRIPT_DISPATCH_2_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_DISPATCH_2_OPCODE\n")); + Status = BootScriptExecuteDispatch2 (Script); + break; - case EFI_BOOT_SCRIPT_INFORMATION_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_INFORMATION_OPCODE\n")); - BootScriptExecuteInformation (Script); - break; + case EFI_BOOT_SCRIPT_INFORMATION_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_INFORMATION_OPCODE\n")); + BootScriptExecuteInformation (Script); + break; - case S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE: - DEBUG ((DEBUG_INFO, "S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE\n")); - DEBUG ((DEBUG_INFO, "S3BootScriptDone - %r\n", EFI_SUCCESS)); - return EFI_SUCCESS; + case S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE: + DEBUG ((DEBUG_INFO, "S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE\n")); + DEBUG ((DEBUG_INFO, "S3BootScriptDone - %r\n", EFI_SUCCESS)); + return EFI_SUCCESS; + + case EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecuteIoReadWrite ( + Script, + AndMask, + OrMask + ); + break; - case EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_READ_WRITE_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecuteIoReadWrite ( - Script, - AndMask, - OrMask - ); - break; + case EFI_BOOT_SCRIPT_SMBUS_EXECUTE_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_SMBUS_EXECUTE_OPCODE\n")); + Status = BootScriptExecuteSmbusExecute (Script); + break; - case EFI_BOOT_SCRIPT_SMBUS_EXECUTE_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_SMBUS_EXECUTE_OPCODE\n")); - Status = BootScriptExecuteSmbusExecute (Script); - break; + case EFI_BOOT_SCRIPT_STALL_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_STALL_OPCODE\n")); + Status = BootScriptExecuteStall (Script); + break; - case EFI_BOOT_SCRIPT_STALL_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_STALL_OPCODE\n")); - Status = BootScriptExecuteStall (Script); - break; + case EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_POLL_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecuteMemPoll (Script, AndMask, OrMask); - case EFI_BOOT_SCRIPT_MEM_POLL_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_MEM_POLL_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecuteMemPoll (Script, AndMask, OrMask); + break; - break; + case EFI_BOOT_SCRIPT_IO_POLL_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_POLL_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptExecuteIoPoll (Script, AndMask, OrMask); + break; - case EFI_BOOT_SCRIPT_IO_POLL_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_IO_POLL_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptExecuteIoPoll (Script, AndMask, OrMask); - break; + case EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptPciCfgPoll (Script, AndMask, OrMask); + break; - case EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptPciCfgPoll (Script, AndMask, OrMask); - break; + case EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE: + DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE\n")); + CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); + Status = BootScriptPciCfg2Poll (Script, AndMask, OrMask); + break; - case EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE: - DEBUG ((DEBUG_INFO, "EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE\n")); - CheckAndOrMask (&ScriptHeader, &AndMask, &OrMask, Script); - Status = BootScriptPciCfg2Poll (Script, AndMask, OrMask); - break; - - case S3_BOOT_SCRIPT_LIB_LABEL_OPCODE: - // - // For label - // - DEBUG ((DEBUG_INFO, "S3_BOOT_SCRIPT_LIB_LABEL_OPCODE\n")); - BootScriptExecuteLabel (Script); - break; - default: - DEBUG ((DEBUG_INFO, "S3BootScriptDone - %r\n", EFI_UNSUPPORTED)); - return EFI_UNSUPPORTED; + case S3_BOOT_SCRIPT_LIB_LABEL_OPCODE: + // + // For label + // + DEBUG ((DEBUG_INFO, "S3_BOOT_SCRIPT_LIB_LABEL_OPCODE\n")); + BootScriptExecuteLabel (Script); + break; + default: + DEBUG ((DEBUG_INFO, "S3BootScriptDone - %r\n", EFI_UNSUPPORTED)); + return EFI_UNSUPPORTED; } if (EFI_ERROR (Status)) { @@ -1766,7 +1796,7 @@ S3BootScriptExecute ( return Status; } - Script = Script + ScriptHeader.Length; + Script = Script + ScriptHeader.Length; } DEBUG ((DEBUG_INFO, "S3BootScriptDone - %r\n", Status)); diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptInternalFormat.h b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptInternalFormat.h index 85bc8af39b..cf49368303 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptInternalFormat.h +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptInternalFormat.h @@ -18,164 +18,163 @@ // typedef struct { - UINT16 OpCode; - UINT8 Length; + UINT16 OpCode; + UINT8 Length; } EFI_BOOT_SCRIPT_GENERIC_HEADER; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT16 Version; - UINT32 TableLength; - UINT16 Reserved[2]; + UINT16 OpCode; + UINT8 Length; + UINT16 Version; + UINT32 TableLength; + UINT16 Reserved[2]; } EFI_BOOT_SCRIPT_TABLE_HEADER; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; } EFI_BOOT_SCRIPT_COMMON_HEADER; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT32 Count; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT32 Count; + UINT64 Address; } EFI_BOOT_SCRIPT_IO_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; } EFI_BOOT_SCRIPT_IO_READ_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT32 Count; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT32 Count; + UINT64 Address; } EFI_BOOT_SCRIPT_MEM_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; } EFI_BOOT_SCRIPT_MEM_READ_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT32 Count; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT32 Count; + UINT64 Address; } EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT32 Count; - UINT64 Address; - UINT16 Segment; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT32 Count; + UINT64 Address; + UINT16 Segment; } EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; } EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; - UINT16 Segment; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; + UINT16 Segment; } EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT64 SmBusAddress; - UINT32 Operation; - UINT32 DataSize; + UINT16 OpCode; + UINT8 Length; + UINT64 SmBusAddress; + UINT32 Operation; + UINT32 DataSize; } EFI_BOOT_SCRIPT_SMBUS_EXECUTE; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT64 Duration; + UINT16 OpCode; + UINT8 Length; + UINT64 Duration; } EFI_BOOT_SCRIPT_STALL; typedef struct { - UINT16 OpCode; - UINT8 Length; - EFI_PHYSICAL_ADDRESS EntryPoint; + UINT16 OpCode; + UINT8 Length; + EFI_PHYSICAL_ADDRESS EntryPoint; } EFI_BOOT_SCRIPT_DISPATCH; typedef struct { - UINT16 OpCode; - UINT8 Length; - EFI_PHYSICAL_ADDRESS EntryPoint; - EFI_PHYSICAL_ADDRESS Context; + UINT16 OpCode; + UINT8 Length; + EFI_PHYSICAL_ADDRESS EntryPoint; + EFI_PHYSICAL_ADDRESS Context; } EFI_BOOT_SCRIPT_DISPATCH_2; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; - UINT64 Duration; - UINT64 LoopTimes; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; + UINT64 Duration; + UINT64 LoopTimes; } EFI_BOOT_SCRIPT_MEM_POLL; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 InformationLength; -// UINT8 InformationData[InformationLength]; + UINT16 OpCode; + UINT8 Length; + UINT32 InformationLength; + // UINT8 InformationData[InformationLength]; } EFI_BOOT_SCRIPT_INFORMATION; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; - UINT64 Delay; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; + UINT64 Delay; } EFI_BOOT_SCRIPT_IO_POLL; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; - UINT64 Delay; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; + UINT64 Delay; } EFI_BOOT_SCRIPT_PCI_CONFIG_POLL; typedef struct { - UINT16 OpCode; - UINT8 Length; - UINT32 Width; - UINT64 Address; - UINT16 Segment; - UINT64 Delay; + UINT16 OpCode; + UINT8 Length; + UINT32 Width; + UINT64 Address; + UINT16 Segment; + UINT64 Delay; } EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL; typedef struct { - UINT16 OpCode; - UINT8 Length; + UINT16 OpCode; + UINT8 Length; } EFI_BOOT_SCRIPT_TERMINATE; - #pragma pack() -#define BOOT_SCRIPT_NODE_MAX_LENGTH 1024 +#define BOOT_SCRIPT_NODE_MAX_LENGTH 1024 -#define BOOT_SCRIPT_TABLE_VERSION 0x0001 +#define BOOT_SCRIPT_TABLE_VERSION 0x0001 #endif diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c index 20378502c8..f8d4983d81 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/BootScriptSave.c @@ -94,37 +94,37 @@ **/ -SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTablePtr; +SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTablePtr; // // Allocate SMM copy because we can not use mS3BootScriptTablePtr after SmmReadyToLock in InSmm. // -SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTableSmmPtr; +SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTableSmmPtr; -EFI_GUID mBootScriptDataGuid = { +EFI_GUID mBootScriptDataGuid = { 0xaea6b965, 0xdcf5, 0x4311, { 0xb4, 0xb8, 0xf, 0x12, 0x46, 0x44, 0x94, 0xd2 } }; -EFI_GUID mBootScriptDataBootTimeGuid = { +EFI_GUID mBootScriptDataBootTimeGuid = { 0xb5af1d7a, 0xb8cf, 0x4eb3, { 0x89, 0x25, 0xa8, 0x20, 0xe1, 0x6b, 0x68, 0x7d } }; -EFI_GUID mBootScriptTableBaseGuid = { +EFI_GUID mBootScriptTableBaseGuid = { 0x1810ab4a, 0x2314, 0x4df6, { 0x81, 0xeb, 0x67, 0xc6, 0xec, 0x5, 0x85, 0x91 } }; -EFI_GUID mBootScriptSmmPrivateDataGuid = { +EFI_GUID mBootScriptSmmPrivateDataGuid = { 0x627ee2da, 0x3bf9, 0x439b, { 0x92, 0x9f, 0x2e, 0xe, 0x6e, 0x9d, 0xba, 0x62 } }; -EFI_EVENT mEventDxeSmmReadyToLock = NULL; -VOID *mRegistrationSmmExitBootServices = NULL; -VOID *mRegistrationSmmLegacyBoot = NULL; -VOID *mRegistrationSmmReadyToLock = NULL; -BOOLEAN mS3BootScriptTableAllocated = FALSE; -BOOLEAN mS3BootScriptTableSmmAllocated = FALSE; -EFI_SMM_SYSTEM_TABLE2 *mBootScriptSmst = NULL; -BOOLEAN mS3BootScriptAcpiS3Enable = TRUE; +EFI_EVENT mEventDxeSmmReadyToLock = NULL; +VOID *mRegistrationSmmExitBootServices = NULL; +VOID *mRegistrationSmmLegacyBoot = NULL; +VOID *mRegistrationSmmReadyToLock = NULL; +BOOLEAN mS3BootScriptTableAllocated = FALSE; +BOOLEAN mS3BootScriptTableSmmAllocated = FALSE; +EFI_SMM_SYSTEM_TABLE2 *mBootScriptSmst = NULL; +BOOLEAN mS3BootScriptAcpiS3Enable = TRUE; /** This is an internal function to add a terminate node the entry, recalculate the table @@ -132,14 +132,15 @@ BOOLEAN mS3BootScriptAcpiS3Enable = TRUE; @return the base address of the boot script table. **/ -UINT8* +UINT8 * S3BootScriptInternalCloseTable ( VOID ) { - UINT8 *S3TableBase; - EFI_BOOT_SCRIPT_TERMINATE ScriptTerminate; - EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; + UINT8 *S3TableBase; + EFI_BOOT_SCRIPT_TERMINATE ScriptTerminate; + EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; + S3TableBase = mS3BootScriptTablePtr->TableBase; if (S3TableBase == NULL) { @@ -148,20 +149,19 @@ S3BootScriptInternalCloseTable ( // return S3TableBase; } + // // Append the termination entry. // - ScriptTerminate.OpCode = S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE; - ScriptTerminate.Length = (UINT8) sizeof (EFI_BOOT_SCRIPT_TERMINATE); + ScriptTerminate.OpCode = S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE; + ScriptTerminate.Length = (UINT8)sizeof (EFI_BOOT_SCRIPT_TERMINATE); CopyMem (mS3BootScriptTablePtr->TableBase + mS3BootScriptTablePtr->TableLength, &ScriptTerminate, sizeof (EFI_BOOT_SCRIPT_TERMINATE)); // // fill the table length // - ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER*)(mS3BootScriptTablePtr->TableBase); + ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER *)(mS3BootScriptTablePtr->TableBase); ScriptTableInfo->TableLength = mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE); - - return S3TableBase; // // NOTE: Here we did NOT adjust the mS3BootScriptTablePtr->TableLength to @@ -180,7 +180,7 @@ SaveBootScriptDataToLockBox ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Save whole memory copy into LockBox. @@ -203,7 +203,7 @@ SaveBootScriptDataToLockBox ( Status = SaveLockBox ( &mBootScriptTableBaseGuid, (VOID *)&mS3BootScriptTablePtr->TableBase, - sizeof(mS3BootScriptTablePtr->TableBase) + sizeof (mS3BootScriptTablePtr->TableBase) ); ASSERT_EFI_ERROR (Status); @@ -225,8 +225,8 @@ S3BootScriptEventCallBack ( IN VOID *Context ) { - EFI_STATUS Status; - VOID *Interface; + EFI_STATUS Status; + VOID *Interface; // // Try to locate it because EfiCreateProtocolNotifyEvent will trigger it once when registration. @@ -238,7 +238,7 @@ S3BootScriptEventCallBack ( &Interface ); if (EFI_ERROR (Status)) { - return ; + return; } // @@ -295,7 +295,7 @@ S3BootScriptSmmEventCallBack ( // Save a SMM copy. If TableBase is NOT null, it means SMM copy has been ready, skip copy mem. // if (mS3BootScriptTableSmmPtr->TableBase == NULL) { - CopyMem (mS3BootScriptTableSmmPtr, mS3BootScriptTablePtr, sizeof(*mS3BootScriptTablePtr)); + CopyMem (mS3BootScriptTableSmmPtr, mS3BootScriptTablePtr, sizeof (*mS3BootScriptTablePtr)); // // Set InSmm, we allow boot script update when InSmm, but not allow boot script outside SMM. @@ -303,6 +303,7 @@ S3BootScriptSmmEventCallBack ( // mS3BootScriptTableSmmPtr->InSmm = TRUE; } + // // We should not use ACPI Reserved copy, because it is not safe. // @@ -325,7 +326,7 @@ SaveBootTimeDataToLockBox ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; // // ACPI Reserved copy is not safe, restore from BootScriptData LockBox first, @@ -344,7 +345,7 @@ SaveBootTimeDataToLockBox ( // Status = SaveLockBox ( &mBootScriptDataBootTimeGuid, - (VOID *) mS3BootScriptTablePtr->TableBase, + (VOID *)mS3BootScriptTablePtr->TableBase, mS3BootScriptTablePtr->BootTimeScriptLength ); ASSERT_EFI_ERROR (Status); @@ -360,17 +361,17 @@ SaveSmmPriviateDataToLockBoxAtRuntime ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Save boot script SMM private data with BackFromS3 = TRUE. // mS3BootScriptTablePtr->BackFromS3 = TRUE; - Status = SaveLockBox ( - &mBootScriptSmmPrivateDataGuid, - (VOID *) mS3BootScriptTablePtr, - sizeof (SCRIPT_TABLE_PRIVATE_DATA) - ); + Status = SaveLockBox ( + &mBootScriptSmmPrivateDataGuid, + (VOID *)mS3BootScriptTablePtr, + sizeof (SCRIPT_TABLE_PRIVATE_DATA) + ); ASSERT_EFI_ERROR (Status); Status = SetLockBoxAttributes (&mBootScriptSmmPrivateDataGuid, LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE); @@ -395,13 +396,13 @@ SaveSmmPriviateDataToLockBoxAtRuntime ( EFI_STATUS EFIAPI S3BootScriptSmmAtRuntimeCallBack ( - IN CONST EFI_GUID *Protocol, - IN VOID *Interface, - IN EFI_HANDLE Handle + IN CONST EFI_GUID *Protocol, + IN VOID *Interface, + IN EFI_HANDLE Handle ) { if (!mS3BootScriptTablePtr->AtRuntime) { - mS3BootScriptTablePtr->BootTimeScriptLength = (UINT32) (mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)); + mS3BootScriptTablePtr->BootTimeScriptLength = (UINT32)(mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)); SaveBootTimeDataToLockBox (); mS3BootScriptTablePtr->AtRuntime = TRUE; @@ -425,17 +426,17 @@ S3BootScriptSmmAtRuntimeCallBack ( RETURN_STATUS EFIAPI S3BootScriptLibInitialize ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - SCRIPT_TABLE_PRIVATE_DATA *S3TablePtr; - SCRIPT_TABLE_PRIVATE_DATA *S3TableSmmPtr; - VOID *Registration; - EFI_SMM_BASE2_PROTOCOL *SmmBase2; - BOOLEAN InSmm; - EFI_PHYSICAL_ADDRESS Buffer; + EFI_STATUS Status; + SCRIPT_TABLE_PRIVATE_DATA *S3TablePtr; + SCRIPT_TABLE_PRIVATE_DATA *S3TableSmmPtr; + VOID *Registration; + EFI_SMM_BASE2_PROTOCOL *SmmBase2; + BOOLEAN InSmm; + EFI_PHYSICAL_ADDRESS Buffer; if (!PcdGetBool (PcdAcpiS3Enable)) { mS3BootScriptAcpiS3Enable = FALSE; @@ -443,7 +444,7 @@ S3BootScriptLibInitialize ( return RETURN_SUCCESS; } - S3TablePtr = (SCRIPT_TABLE_PRIVATE_DATA*)(UINTN)PcdGet64(PcdS3BootScriptTablePrivateDataPtr); + S3TablePtr = (SCRIPT_TABLE_PRIVATE_DATA *)(UINTN)PcdGet64 (PcdS3BootScriptTablePrivateDataPtr); // // The Boot script private data is not be initialized. create it // @@ -452,16 +453,16 @@ S3BootScriptLibInitialize ( Status = gBS->AllocatePages ( AllocateMaxAddress, EfiReservedMemoryType, - EFI_SIZE_TO_PAGES(sizeof(SCRIPT_TABLE_PRIVATE_DATA)), + EFI_SIZE_TO_PAGES (sizeof (SCRIPT_TABLE_PRIVATE_DATA)), &Buffer ); ASSERT_EFI_ERROR (Status); mS3BootScriptTableAllocated = TRUE; - S3TablePtr = (VOID *) (UINTN) Buffer; + S3TablePtr = (VOID *)(UINTN)Buffer; - Status = PcdSet64S (PcdS3BootScriptTablePrivateDataPtr, (UINT64) (UINTN)S3TablePtr); + Status = PcdSet64S (PcdS3BootScriptTablePrivateDataPtr, (UINT64)(UINTN)S3TablePtr); ASSERT_EFI_ERROR (Status); - ZeroMem (S3TablePtr, sizeof(SCRIPT_TABLE_PRIVATE_DATA)); + ZeroMem (S3TablePtr, sizeof (SCRIPT_TABLE_PRIVATE_DATA)); // // Create event to notify the library system enter the SmmLocked phase. // @@ -474,22 +475,26 @@ S3BootScriptLibInitialize ( ); ASSERT (mEventDxeSmmReadyToLock != NULL); } + mS3BootScriptTablePtr = S3TablePtr; // // Get InSmm, we need to register SmmReadyToLock if this library is linked to SMM driver. // - Status = gBS->LocateProtocol (&gEfiSmmBase2ProtocolGuid, NULL, (VOID**) &SmmBase2); + Status = gBS->LocateProtocol (&gEfiSmmBase2ProtocolGuid, NULL, (VOID **)&SmmBase2); if (EFI_ERROR (Status)) { return RETURN_SUCCESS; } + Status = SmmBase2->InSmm (SmmBase2, &InSmm); if (EFI_ERROR (Status)) { return RETURN_SUCCESS; } + if (!InSmm) { return RETURN_SUCCESS; } + // // Good, we are in SMM // @@ -498,22 +503,22 @@ S3BootScriptLibInitialize ( return RETURN_SUCCESS; } - S3TableSmmPtr = (SCRIPT_TABLE_PRIVATE_DATA*)(UINTN)PcdGet64(PcdS3BootScriptTablePrivateSmmDataPtr); + S3TableSmmPtr = (SCRIPT_TABLE_PRIVATE_DATA *)(UINTN)PcdGet64 (PcdS3BootScriptTablePrivateSmmDataPtr); // // The Boot script private data in SMM is not be initialized. create it // if (S3TableSmmPtr == 0) { Status = mBootScriptSmst->SmmAllocatePool ( EfiRuntimeServicesData, - sizeof(SCRIPT_TABLE_PRIVATE_DATA), - (VOID **) &S3TableSmmPtr + sizeof (SCRIPT_TABLE_PRIVATE_DATA), + (VOID **)&S3TableSmmPtr ); ASSERT_EFI_ERROR (Status); mS3BootScriptTableSmmAllocated = TRUE; - Status = PcdSet64S (PcdS3BootScriptTablePrivateSmmDataPtr, (UINT64) (UINTN)S3TableSmmPtr); + Status = PcdSet64S (PcdS3BootScriptTablePrivateSmmDataPtr, (UINT64)(UINTN)S3TableSmmPtr); ASSERT_EFI_ERROR (Status); - ZeroMem (S3TableSmmPtr, sizeof(SCRIPT_TABLE_PRIVATE_DATA)); + ZeroMem (S3TableSmmPtr, sizeof (SCRIPT_TABLE_PRIVATE_DATA)); // // Register SmmExitBootServices and SmmLegacyBoot notification. @@ -532,6 +537,7 @@ S3BootScriptLibInitialize ( ); ASSERT_EFI_ERROR (Status); } + mS3BootScriptTableSmmPtr = S3TableSmmPtr; // @@ -563,11 +569,11 @@ S3BootScriptLibInitialize ( RETURN_STATUS EFIAPI S3BootScriptLibDeinitialize ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; if (!mS3BootScriptAcpiS3Enable) { return RETURN_SUCCESS; @@ -595,6 +601,7 @@ S3BootScriptLibDeinitialize ( ); ASSERT_EFI_ERROR (Status); } + if (mRegistrationSmmLegacyBoot != NULL) { // // Unregister SmmLegacyBoot notification. @@ -606,6 +613,7 @@ S3BootScriptLibDeinitialize ( ); ASSERT_EFI_ERROR (Status); } + if (mRegistrationSmmReadyToLock != NULL) { // // Unregister SmmReadyToLock notification. @@ -623,11 +631,12 @@ S3BootScriptLibDeinitialize ( // Free the resources allocated and set PCDs to 0. // if (mS3BootScriptTableAllocated) { - Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) mS3BootScriptTablePtr, EFI_SIZE_TO_PAGES(sizeof(SCRIPT_TABLE_PRIVATE_DATA))); + Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)mS3BootScriptTablePtr, EFI_SIZE_TO_PAGES (sizeof (SCRIPT_TABLE_PRIVATE_DATA))); ASSERT_EFI_ERROR (Status); Status = PcdSet64S (PcdS3BootScriptTablePrivateDataPtr, 0); ASSERT_EFI_ERROR (Status); } + if ((mBootScriptSmst != NULL) && mS3BootScriptTableSmmAllocated) { Status = mBootScriptSmst->SmmFreePool (mS3BootScriptTableSmmPtr); ASSERT_EFI_ERROR (Status); @@ -648,95 +657,98 @@ S3BootScriptLibDeinitialize ( @retval the address from which the a new s3 boot script entry will write into **/ -UINT8* +UINT8 * S3BootScriptGetBootTimeEntryAddAddress ( UINT8 EntryLength ) { - EFI_PHYSICAL_ADDRESS S3TableBase; - EFI_PHYSICAL_ADDRESS NewS3TableBase; - UINT8 *NewEntryPtr; - UINT32 TableLength; - UINT16 PageNumber; - EFI_STATUS Status; - EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; - - S3TableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)(mS3BootScriptTablePtr->TableBase); - if (S3TableBase == 0) { - // - // The table is not exist. This is the first to add entry. - // Allocate ACPI script table space under 4G memory. - // - S3TableBase = 0xffffffff; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - 2 + PcdGet16(PcdS3BootScriptRuntimeTableReservePageNumber), - (EFI_PHYSICAL_ADDRESS*)&S3TableBase - ); + EFI_PHYSICAL_ADDRESS S3TableBase; + EFI_PHYSICAL_ADDRESS NewS3TableBase; + UINT8 *NewEntryPtr; + UINT32 TableLength; + UINT16 PageNumber; + EFI_STATUS Status; + EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; + + S3TableBase = (EFI_PHYSICAL_ADDRESS)(UINTN)(mS3BootScriptTablePtr->TableBase); + if (S3TableBase == 0) { + // + // The table is not exist. This is the first to add entry. + // Allocate ACPI script table space under 4G memory. + // + S3TableBase = 0xffffffff; + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiReservedMemoryType, + 2 + PcdGet16 (PcdS3BootScriptRuntimeTableReservePageNumber), + (EFI_PHYSICAL_ADDRESS *)&S3TableBase + ); + + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return 0; + } - if (EFI_ERROR(Status)) { - ASSERT_EFI_ERROR (Status); - return 0; - } - // - // Fill Table Header - // - ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER*)(UINTN)S3TableBase; - ScriptTableInfo->OpCode = S3_BOOT_SCRIPT_LIB_TABLE_OPCODE; - ScriptTableInfo->Length = (UINT8) sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); - ScriptTableInfo->Version = BOOT_SCRIPT_TABLE_VERSION; - ScriptTableInfo->TableLength = 0; // will be calculate at CloseTable - mS3BootScriptTablePtr->TableLength = sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); - mS3BootScriptTablePtr->TableBase = (UINT8*)(UINTN)S3TableBase; - mS3BootScriptTablePtr->TableMemoryPageNumber = (UINT16)(2 + PcdGet16(PcdS3BootScriptRuntimeTableReservePageNumber)); - } - - // Here we do not count the reserved memory for runtime script table. - PageNumber = (UINT16) (mS3BootScriptTablePtr->TableMemoryPageNumber - PcdGet16(PcdS3BootScriptRuntimeTableReservePageNumber)); - TableLength = mS3BootScriptTablePtr->TableLength; - if (EFI_PAGES_TO_SIZE ((UINTN) PageNumber) < (TableLength + EntryLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE))) { - // - // The buffer is too small to hold the table, Reallocate the buffer - // - NewS3TableBase = 0xffffffff; - Status = gBS->AllocatePages ( - AllocateMaxAddress, - EfiReservedMemoryType, - 2 + PageNumber + PcdGet16(PcdS3BootScriptRuntimeTableReservePageNumber), - (EFI_PHYSICAL_ADDRESS*)&NewS3TableBase - ); + // + // Fill Table Header + // + ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER *)(UINTN)S3TableBase; + ScriptTableInfo->OpCode = S3_BOOT_SCRIPT_LIB_TABLE_OPCODE; + ScriptTableInfo->Length = (UINT8)sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); + ScriptTableInfo->Version = BOOT_SCRIPT_TABLE_VERSION; + ScriptTableInfo->TableLength = 0; // will be calculate at CloseTable + mS3BootScriptTablePtr->TableLength = sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); + mS3BootScriptTablePtr->TableBase = (UINT8 *)(UINTN)S3TableBase; + mS3BootScriptTablePtr->TableMemoryPageNumber = (UINT16)(2 + PcdGet16 (PcdS3BootScriptRuntimeTableReservePageNumber)); + } + + // Here we do not count the reserved memory for runtime script table. + PageNumber = (UINT16)(mS3BootScriptTablePtr->TableMemoryPageNumber - PcdGet16 (PcdS3BootScriptRuntimeTableReservePageNumber)); + TableLength = mS3BootScriptTablePtr->TableLength; + if (EFI_PAGES_TO_SIZE ((UINTN)PageNumber) < (TableLength + EntryLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE))) { + // + // The buffer is too small to hold the table, Reallocate the buffer + // + NewS3TableBase = 0xffffffff; + Status = gBS->AllocatePages ( + AllocateMaxAddress, + EfiReservedMemoryType, + 2 + PageNumber + PcdGet16 (PcdS3BootScriptRuntimeTableReservePageNumber), + (EFI_PHYSICAL_ADDRESS *)&NewS3TableBase + ); + + if (EFI_ERROR (Status)) { + ASSERT_EFI_ERROR (Status); + return 0; + } + + CopyMem ((VOID *)(UINTN)NewS3TableBase, (VOID *)(UINTN)S3TableBase, TableLength); + gBS->FreePages (S3TableBase, mS3BootScriptTablePtr->TableMemoryPageNumber); + + mS3BootScriptTablePtr->TableBase = (UINT8 *)(UINTN)NewS3TableBase; + mS3BootScriptTablePtr->TableMemoryPageNumber = (UINT16)(2 + PageNumber + PcdGet16 (PcdS3BootScriptRuntimeTableReservePageNumber)); + } + + // + // calculate the the start address for the new entry. + // + NewEntryPtr = mS3BootScriptTablePtr->TableBase + TableLength; + + // + // update the table lenghth + // + mS3BootScriptTablePtr->TableLength = TableLength + EntryLength; - if (EFI_ERROR(Status)) { - ASSERT_EFI_ERROR (Status); - return 0; - } - - CopyMem ((VOID*)(UINTN)NewS3TableBase, (VOID*)(UINTN)S3TableBase, TableLength); - gBS->FreePages (S3TableBase, mS3BootScriptTablePtr->TableMemoryPageNumber); - - mS3BootScriptTablePtr->TableBase = (UINT8*)(UINTN)NewS3TableBase; - mS3BootScriptTablePtr->TableMemoryPageNumber = (UINT16) (2 + PageNumber + PcdGet16(PcdS3BootScriptRuntimeTableReservePageNumber)); - } - // - // calculate the the start address for the new entry. - // - NewEntryPtr = mS3BootScriptTablePtr->TableBase + TableLength; - - // - // update the table lenghth - // - mS3BootScriptTablePtr->TableLength = TableLength + EntryLength; - - // - // In the boot time, we will not append the termination entry to the boot script - // table until the callers think there is no boot time data that should be added and - // it is caller's responsibility to explicit call the CloseTable. - // - // - - return NewEntryPtr; + // + // In the boot time, we will not append the termination entry to the boot script + // table until the callers think there is no boot time data that should be added and + // it is caller's responsibility to explicit call the CloseTable. + // + // + + return NewEntryPtr; } + /** To get the start address from which a new runtime(after SmmReadyToLock) s3 boot script entry will write into. In this case, it should be ensured that there is enough buffer to hold the entry. @@ -745,26 +757,27 @@ S3BootScriptGetBootTimeEntryAddAddress ( @retval the address from which the a new s3 runtime(after SmmReadyToLock) script entry will write into **/ -UINT8* +UINT8 * S3BootScriptGetRuntimeEntryAddAddress ( UINT8 EntryLength ) { - UINT8 *NewEntryPtr; - - NewEntryPtr = NULL; - // - // Check if the memory range reserved for S3 Boot Script table is large enough to hold the node. - // - if ((mS3BootScriptTablePtr->TableLength + EntryLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)) <= EFI_PAGES_TO_SIZE ((UINTN) (mS3BootScriptTablePtr->TableMemoryPageNumber))) { - NewEntryPtr = mS3BootScriptTablePtr->TableBase + mS3BootScriptTablePtr->TableLength; - mS3BootScriptTablePtr->TableLength = mS3BootScriptTablePtr->TableLength + EntryLength; - // - // Append a terminate node on every insert - // - S3BootScriptInternalCloseTable (); - } - return (UINT8*)NewEntryPtr; + UINT8 *NewEntryPtr; + + NewEntryPtr = NULL; + // + // Check if the memory range reserved for S3 Boot Script table is large enough to hold the node. + // + if ((mS3BootScriptTablePtr->TableLength + EntryLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)) <= EFI_PAGES_TO_SIZE ((UINTN)(mS3BootScriptTablePtr->TableMemoryPageNumber))) { + NewEntryPtr = mS3BootScriptTablePtr->TableBase + mS3BootScriptTablePtr->TableLength; + mS3BootScriptTablePtr->TableLength = mS3BootScriptTablePtr->TableLength + EntryLength; + // + // Append a terminate node on every insert + // + S3BootScriptInternalCloseTable (); + } + + return (UINT8 *)NewEntryPtr; } /** @@ -776,18 +789,18 @@ RestoreBootTimeDataFromLockBox ( VOID ) { - EFI_STATUS Status; - UINTN LockBoxLength; + EFI_STATUS Status; + UINTN LockBoxLength; // // Restore boot time boot script data from LockBox. // LockBoxLength = mS3BootScriptTablePtr->BootTimeScriptLength; - Status = RestoreLockBox ( - &mBootScriptDataBootTimeGuid, - (VOID *) mS3BootScriptTablePtr->TableBase, - &LockBoxLength - ); + Status = RestoreLockBox ( + &mBootScriptDataBootTimeGuid, + (VOID *)mS3BootScriptTablePtr->TableBase, + &LockBoxLength + ); ASSERT_EFI_ERROR (Status); // @@ -796,7 +809,7 @@ RestoreBootTimeDataFromLockBox ( Status = UpdateLockBox ( &mBootScriptDataGuid, 0, - (VOID *) mS3BootScriptTablePtr->TableBase, + (VOID *)mS3BootScriptTablePtr->TableBase, LockBoxLength ); ASSERT_EFI_ERROR (Status); @@ -804,7 +817,7 @@ RestoreBootTimeDataFromLockBox ( // // Update TableLength. // - mS3BootScriptTablePtr->TableLength = (UINT32) (mS3BootScriptTablePtr->BootTimeScriptLength - sizeof (EFI_BOOT_SCRIPT_TERMINATE)); + mS3BootScriptTablePtr->TableLength = (UINT32)(mS3BootScriptTablePtr->BootTimeScriptLength - sizeof (EFI_BOOT_SCRIPT_TERMINATE)); } /** @@ -814,12 +827,12 @@ RestoreBootTimeDataFromLockBox ( @retval the address from which the a new s3 boot script entry will write into **/ -UINT8* +UINT8 * S3BootScriptGetEntryAddAddress ( UINT8 EntryLength ) { - UINT8* NewEntryPtr; + UINT8 *NewEntryPtr; if (!mS3BootScriptAcpiS3Enable) { return NULL; @@ -847,12 +860,12 @@ S3BootScriptGetEntryAddAddress ( mS3BootScriptTablePtr->BackFromS3 = FALSE; } - NewEntryPtr = S3BootScriptGetRuntimeEntryAddAddress (EntryLength); + NewEntryPtr = S3BootScriptGetRuntimeEntryAddAddress (EntryLength); } else { - NewEntryPtr = S3BootScriptGetBootTimeEntryAddAddress (EntryLength); + NewEntryPtr = S3BootScriptGetBootTimeEntryAddAddress (EntryLength); } - return NewEntryPtr; + return NewEntryPtr; } /** @@ -863,7 +876,7 @@ S3BootScriptGetEntryAddAddress ( **/ VOID SyncBootScript ( - IN UINT8 *Script + IN UINT8 *Script ) { EFI_STATUS Status; @@ -875,12 +888,12 @@ SyncBootScript ( // If it is not after SmmReadyToLock in SMM, // just return. // - return ; + return; } - ScriptOffset = (UINT32) (Script - mS3BootScriptTablePtr->TableBase); + ScriptOffset = (UINT32)(Script - mS3BootScriptTablePtr->TableBase); - TotalScriptLength = (UINT32) (mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)); + TotalScriptLength = (UINT32)(mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE)); // // Update BootScriptData @@ -932,26 +945,27 @@ SyncBootScript ( @note this function could only called in boot time phase **/ -UINT8* +UINT8 * EFIAPI S3BootScriptCloseTable ( VOID ) { - UINT8 *S3TableBase; - UINT32 TableLength; - UINT8 *Buffer; - EFI_STATUS Status; - EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; + UINT8 *S3TableBase; + UINT32 TableLength; + UINT8 *Buffer; + EFI_STATUS Status; + EFI_BOOT_SCRIPT_TABLE_HEADER *ScriptTableInfo; S3TableBase = mS3BootScriptTablePtr->TableBase; if (S3TableBase == 0) { return 0; } + // // Append the termination record the S3 boot script table // - S3BootScriptInternalCloseTable(); + S3BootScriptInternalCloseTable (); TableLength = mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE); // // Allocate the buffer and copy the boot script to the buffer. @@ -959,11 +973,12 @@ S3BootScriptCloseTable ( Status = gBS->AllocatePool ( EfiBootServicesData, (UINTN)TableLength, - (VOID **) &Buffer + (VOID **)&Buffer ); if (EFI_ERROR (Status)) { - return 0; + return 0; } + CopyMem (Buffer, S3TableBase, TableLength); // @@ -971,14 +986,15 @@ S3BootScriptCloseTable ( // will write the record to the first entry of the table. // // Fill the table header. - ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER*)S3TableBase; + ScriptTableInfo = (EFI_BOOT_SCRIPT_TABLE_HEADER *)S3TableBase; ScriptTableInfo->OpCode = S3_BOOT_SCRIPT_LIB_TABLE_OPCODE; - ScriptTableInfo->Length = (UINT8) sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); + ScriptTableInfo->Length = (UINT8)sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); ScriptTableInfo->TableLength = 0; // will be calculate at close the table mS3BootScriptTablePtr->TableLength = sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); return Buffer; } + /** Save I/O write to boot script @@ -993,33 +1009,36 @@ S3BootScriptCloseTable ( RETURN_STATUS EFIAPI S3BootScriptSaveIoWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { UINT8 Length; - UINT8 *Script; + UINT8 *Script; UINT8 WidthInByte; EFI_BOOT_SCRIPT_IO_WRITE ScriptIoWrite; - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // // Truncation check // if ((Count > MAX_UINT8) || - (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_IO_WRITE))) { + (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_IO_WRITE))) + { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_WRITE) + (WidthInByte * Count)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // save script data // @@ -1027,9 +1046,9 @@ S3BootScriptSaveIoWrite ( ScriptIoWrite.Length = Length; ScriptIoWrite.Width = Width; ScriptIoWrite.Address = Address; - ScriptIoWrite.Count = (UINT32) Count; - CopyMem ((VOID*)Script, (VOID*)&ScriptIoWrite, sizeof(EFI_BOOT_SCRIPT_IO_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_IO_WRITE)), Buffer, WidthInByte * Count); + ScriptIoWrite.Count = (UINT32)Count; + CopyMem ((VOID *)Script, (VOID *)&ScriptIoWrite, sizeof (EFI_BOOT_SCRIPT_IO_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_IO_WRITE)), Buffer, WidthInByte * Count); SyncBootScript (Script); @@ -1050,24 +1069,25 @@ S3BootScriptSaveIoWrite ( RETURN_STATUS EFIAPI S3BootScriptSaveIoReadWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_IO_READ_WRITE ScriptIoReadWrite; - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // @@ -1076,14 +1096,15 @@ S3BootScriptSaveIoReadWrite ( ScriptIoReadWrite.Width = Width; ScriptIoReadWrite.Address = Address; - CopyMem ((VOID*)Script, (VOID*)&ScriptIoReadWrite, sizeof(EFI_BOOT_SCRIPT_IO_READ_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE)), Data, WidthInByte); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE) + WidthInByte), DataMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptIoReadWrite, sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE)), Data, WidthInByte); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_IO_READ_WRITE) + WidthInByte), DataMask, WidthInByte); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for a memory write operation into a specified boot script table. @@ -1098,48 +1119,52 @@ S3BootScriptSaveIoReadWrite ( RETURN_STATUS EFIAPI S3BootScriptSaveMemWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_MEM_WRITE ScriptMemWrite; - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // // Truncation check // if ((Count > MAX_UINT8) || - (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_MEM_WRITE))) { + (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_MEM_WRITE))) + { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_WRITE) + (WidthInByte * Count)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptMemWrite.OpCode = EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE; - ScriptMemWrite.Length = Length; - ScriptMemWrite.Width = Width; - ScriptMemWrite.Address = Address; - ScriptMemWrite.Count = (UINT32) Count; + ScriptMemWrite.OpCode = EFI_BOOT_SCRIPT_MEM_WRITE_OPCODE; + ScriptMemWrite.Length = Length; + ScriptMemWrite.Width = Width; + ScriptMemWrite.Address = Address; + ScriptMemWrite.Count = (UINT32)Count; - CopyMem ((VOID*)Script, (VOID*)&ScriptMemWrite, sizeof(EFI_BOOT_SCRIPT_MEM_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_WRITE)), Buffer, WidthInByte * Count); + CopyMem ((VOID *)Script, (VOID *)&ScriptMemWrite, sizeof (EFI_BOOT_SCRIPT_MEM_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_WRITE)), Buffer, WidthInByte * Count); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for a memory modify operation into a specified boot script table. @@ -1154,40 +1179,42 @@ S3BootScriptSaveMemWrite ( RETURN_STATUS EFIAPI S3BootScriptSaveMemReadWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_MEM_READ_WRITE ScriptMemReadWrite; - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptMemReadWrite.OpCode = EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE; - ScriptMemReadWrite.Length = Length; - ScriptMemReadWrite.Width = Width; - ScriptMemReadWrite.Address = Address; + ScriptMemReadWrite.OpCode = EFI_BOOT_SCRIPT_MEM_READ_WRITE_OPCODE; + ScriptMemReadWrite.Length = Length; + ScriptMemReadWrite.Width = Width; + ScriptMemReadWrite.Address = Address; - CopyMem ((VOID*)Script, (VOID*)&ScriptMemReadWrite , sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE)), Data, WidthInByte); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE) + WidthInByte), DataMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptMemReadWrite, sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE)), Data, WidthInByte); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_READ_WRITE) + WidthInByte), DataMask, WidthInByte); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for a PCI configuration space write operation into a specified boot script table. @@ -1204,54 +1231,59 @@ S3BootScriptSaveMemReadWrite ( RETURN_STATUS EFIAPI S3BootScriptSavePciCfgWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE ScriptPciWrite; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // // Truncation check // if ((Count > MAX_UINT8) || - (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE))) { + (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE))) + { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE) + (WidthInByte * Count)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPciWrite.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE; - ScriptPciWrite.Length = Length; - ScriptPciWrite.Width = Width; - ScriptPciWrite.Address = Address; - ScriptPciWrite.Count = (UINT32) Count; + ScriptPciWrite.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE_OPCODE; + ScriptPciWrite.Length = Length; + ScriptPciWrite.Width = Width; + ScriptPciWrite.Address = Address; + ScriptPciWrite.Count = (UINT32)Count; - CopyMem ((VOID*)Script, (VOID*)&ScriptPciWrite, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)), Buffer, WidthInByte * Count); + CopyMem ((VOID *)Script, (VOID *)&ScriptPciWrite, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_WRITE)), Buffer, WidthInByte * Count); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for a PCI configuration space modify operation into a specified boot script table. @@ -1268,42 +1300,44 @@ S3BootScriptSavePciCfgWrite ( RETURN_STATUS EFIAPI S3BootScriptSavePciCfgReadWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE ScriptPciReadWrite; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPciReadWrite.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE; - ScriptPciReadWrite.Length = Length; - ScriptPciReadWrite.Width = Width; - ScriptPciReadWrite.Address = Address; + ScriptPciReadWrite.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE_OPCODE; + ScriptPciReadWrite.Length = Length; + ScriptPciReadWrite.Width = Width; + ScriptPciReadWrite.Address = Address; - CopyMem ((VOID*)Script, (VOID*)&ScriptPciReadWrite, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)), Data, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptPciReadWrite, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE)), Data, WidthInByte); CopyMem ( - (VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE) + WidthInByte), + (VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_READ_WRITE) + WidthInByte), DataMask, WidthInByte ); @@ -1312,6 +1346,7 @@ S3BootScriptSavePciCfgReadWrite ( return RETURN_SUCCESS; } + /** Adds a record for a PCI configuration 2 space write operation into a specified boot script table. @@ -1329,56 +1364,61 @@ S3BootScriptSavePciCfgReadWrite ( RETURN_STATUS EFIAPI S3BootScriptSavePciCfg2Write ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT16 Segment, - IN UINT64 Address, - IN UINTN Count, - IN VOID *Buffer + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT16 Segment, + IN UINT64 Address, + IN UINTN Count, + IN VOID *Buffer ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE ScriptPciWrite2; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); // // Truncation check // if ((Count > MAX_UINT8) || - (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE))) { + (WidthInByte * Count > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE))) + { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE) + (WidthInByte * Count)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPciWrite2.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE; - ScriptPciWrite2.Length = Length; - ScriptPciWrite2.Width = Width; - ScriptPciWrite2.Address = Address; - ScriptPciWrite2.Segment = Segment; - ScriptPciWrite2.Count = (UINT32)Count; + ScriptPciWrite2.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE_OPCODE; + ScriptPciWrite2.Length = Length; + ScriptPciWrite2.Width = Width; + ScriptPciWrite2.Address = Address; + ScriptPciWrite2.Segment = Segment; + ScriptPciWrite2.Count = (UINT32)Count; - CopyMem ((VOID*)Script, (VOID*)&ScriptPciWrite2, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)), Buffer, WidthInByte * Count); + CopyMem ((VOID *)Script, (VOID *)&ScriptPciWrite2, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_WRITE)), Buffer, WidthInByte * Count); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for a PCI configuration 2 space modify operation into a specified boot script table. @@ -1396,44 +1436,46 @@ S3BootScriptSavePciCfg2Write ( RETURN_STATUS EFIAPI S3BootScriptSavePciCfg2ReadWrite ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT16 Segment, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT16 Segment, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE ScriptPciReadWrite2; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPciReadWrite2.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE; - ScriptPciReadWrite2.Length = Length; - ScriptPciReadWrite2.Width = Width; - ScriptPciReadWrite2.Segment = Segment; - ScriptPciReadWrite2.Address = Address; + ScriptPciReadWrite2.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE_OPCODE; + ScriptPciReadWrite2.Length = Length; + ScriptPciReadWrite2.Width = Width; + ScriptPciReadWrite2.Segment = Segment; + ScriptPciReadWrite2.Address = Address; - CopyMem ((VOID*)Script, (VOID*)&ScriptPciReadWrite2, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)), Data, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptPciReadWrite2, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE)), Data, WidthInByte); CopyMem ( - (VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE) + WidthInByte), + (VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_READ_WRITE) + WidthInByte), DataMask, WidthInByte ); @@ -1477,19 +1519,19 @@ S3BootScriptSavePciCfg2ReadWrite ( **/ EFI_STATUS CheckParameters ( - IN UINTN SmBusAddress, - IN EFI_SMBUS_OPERATION Operation, - IN OUT UINTN *Length, - IN VOID *Buffer + IN UINTN SmBusAddress, + IN EFI_SMBUS_OPERATION Operation, + IN OUT UINTN *Length, + IN VOID *Buffer ) { - EFI_STATUS Status; - UINTN RequiredLen; - EFI_SMBUS_DEVICE_COMMAND Command; - BOOLEAN PecCheck; + EFI_STATUS Status; + UINTN RequiredLen; + EFI_SMBUS_DEVICE_COMMAND Command; + BOOLEAN PecCheck; - Command = SMBUS_LIB_COMMAND (SmBusAddress); - PecCheck = SMBUS_LIB_PEC (SmBusAddress); + Command = SMBUS_LIB_COMMAND (SmBusAddress); + PecCheck = SMBUS_LIB_PEC (SmBusAddress); // // Set default value to be 2: // for SmbusReadWord, SmbusWriteWord and SmbusProcessCall. @@ -1499,32 +1541,35 @@ CheckParameters ( switch (Operation) { case EfiSmbusQuickRead: case EfiSmbusQuickWrite: - if (PecCheck || Command != 0) { + if (PecCheck || (Command != 0)) { return EFI_UNSUPPORTED; } + break; case EfiSmbusReceiveByte: case EfiSmbusSendByte: if (Command != 0) { return EFI_UNSUPPORTED; } - // - // Cascade to check length parameter. - // + + // + // Cascade to check length parameter. + // case EfiSmbusReadByte: case EfiSmbusWriteByte: RequiredLen = 1; - // - // Cascade to check length parameter. - // + // + // Cascade to check length parameter. + // case EfiSmbusReadWord: case EfiSmbusWriteWord: case EfiSmbusProcessCall: - if (Buffer == NULL || Length == NULL) { + if ((Buffer == NULL) || (Length == NULL)) { return EFI_INVALID_PARAMETER; } else if (*Length < RequiredLen) { Status = EFI_BUFFER_TOO_SMALL; } + *Length = RequiredLen; break; case EfiSmbusReadBlock: @@ -1533,13 +1578,16 @@ CheckParameters ( if ((Buffer == NULL) || (Length == NULL) || (*Length < MIN_SMBUS_BLOCK_LEN) || - (*Length > MAX_SMBUS_BLOCK_LEN)) { + (*Length > MAX_SMBUS_BLOCK_LEN)) + { return EFI_INVALID_PARAMETER; } + break; default: return EFI_INVALID_PARAMETER; } + return Status; } @@ -1558,16 +1606,16 @@ CheckParameters ( RETURN_STATUS EFIAPI S3BootScriptSaveSmbusExecute ( - IN UINTN SmBusAddress, - IN EFI_SMBUS_OPERATION Operation, - IN UINTN *Length, - IN VOID *Buffer + IN UINTN SmBusAddress, + IN EFI_SMBUS_OPERATION Operation, + IN UINTN *Length, + IN VOID *Buffer ) { - EFI_STATUS Status; - UINTN BufferLength; - UINT8 DataSize; - UINT8 *Script; + EFI_STATUS Status; + UINTN BufferLength; + UINT8 DataSize; + UINT8 *Script; EFI_BOOT_SCRIPT_SMBUS_EXECUTE ScriptSmbusExecute; if (Length == NULL) { @@ -1587,24 +1635,26 @@ S3BootScriptSaveSmbusExecute ( if (BufferLength > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)) { return RETURN_OUT_OF_RESOURCES; } + DataSize = (UINT8)(sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE) + BufferLength); Script = S3BootScriptGetEntryAddAddress (DataSize); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // ScriptSmbusExecute.OpCode = EFI_BOOT_SCRIPT_SMBUS_EXECUTE_OPCODE; ScriptSmbusExecute.Length = DataSize; - ScriptSmbusExecute.SmBusAddress = (UINT64) SmBusAddress; + ScriptSmbusExecute.SmBusAddress = (UINT64)SmBusAddress; ScriptSmbusExecute.Operation = Operation; - ScriptSmbusExecute.DataSize = (UINT32) BufferLength; + ScriptSmbusExecute.DataSize = (UINT32)BufferLength; - CopyMem ((VOID*)Script, (VOID*)&ScriptSmbusExecute, sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)); + CopyMem ((VOID *)Script, (VOID *)&ScriptSmbusExecute, sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)); CopyMem ( - (VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)), + (VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_SMBUS_EXECUTE)), Buffer, BufferLength ); @@ -1613,6 +1663,7 @@ S3BootScriptSaveSmbusExecute ( return RETURN_SUCCESS; } + /** Adds a record for an execution stall on the processor into a specified boot script table. @@ -1624,11 +1675,11 @@ S3BootScriptSaveSmbusExecute ( RETURN_STATUS EFIAPI S3BootScriptSaveStall ( - IN UINTN Duration + IN UINTN Duration ) { - UINT8 Length; - UINT8 *Script; + UINT8 Length; + UINT8 *Script; EFI_BOOT_SCRIPT_STALL ScriptStall; Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_STALL)); @@ -1637,19 +1688,21 @@ S3BootScriptSaveStall ( if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptStall.OpCode = EFI_BOOT_SCRIPT_STALL_OPCODE; - ScriptStall.Length = Length; - ScriptStall.Duration = Duration; + ScriptStall.OpCode = EFI_BOOT_SCRIPT_STALL_OPCODE; + ScriptStall.Length = Length; + ScriptStall.Duration = Duration; - CopyMem ((VOID*)Script, (VOID*)&ScriptStall, sizeof (EFI_BOOT_SCRIPT_STALL)); + CopyMem ((VOID *)Script, (VOID *)&ScriptStall, sizeof (EFI_BOOT_SCRIPT_STALL)); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for dispatching specified arbitrary code into a specified boot script table. @@ -1662,34 +1715,36 @@ S3BootScriptSaveStall ( RETURN_STATUS EFIAPI S3BootScriptSaveDispatch2 ( - IN VOID *EntryPoint, - IN VOID *Context + IN VOID *EntryPoint, + IN VOID *Context ) { - UINT8 Length; - UINT8 *Script; + UINT8 Length; + UINT8 *Script; EFI_BOOT_SCRIPT_DISPATCH_2 ScriptDispatch2; + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_DISPATCH_2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // ScriptDispatch2.OpCode = EFI_BOOT_SCRIPT_DISPATCH_2_OPCODE; ScriptDispatch2.Length = Length; ScriptDispatch2.EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)EntryPoint; - ScriptDispatch2.Context = (EFI_PHYSICAL_ADDRESS)(UINTN)Context; + ScriptDispatch2.Context = (EFI_PHYSICAL_ADDRESS)(UINTN)Context; - CopyMem ((VOID*)Script, (VOID*)&ScriptDispatch2, sizeof (EFI_BOOT_SCRIPT_DISPATCH_2)); + CopyMem ((VOID *)Script, (VOID *)&ScriptDispatch2, sizeof (EFI_BOOT_SCRIPT_DISPATCH_2)); SyncBootScript (Script); return RETURN_SUCCESS; - } + /** Adds a record for memory reads of the memory location and continues when the exit criteria is satisfied or after a defined duration. @@ -1713,20 +1768,20 @@ S3BootScriptSaveDispatch2 ( RETURN_STATUS EFIAPI S3BootScriptSaveMemPoll ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN VOID *BitMask, - IN VOID *BitValue, - IN UINTN Duration, - IN UINT64 LoopTimes + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN VOID *BitMask, + IN VOID *BitValue, + IN UINTN Duration, + IN UINT64 LoopTimes ) { - UINT8 Length; - UINT8 *Script; - UINT8 WidthInByte; - EFI_BOOT_SCRIPT_MEM_POLL ScriptMemPoll; + UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; + EFI_BOOT_SCRIPT_MEM_POLL ScriptMemPoll; - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_MEM_POLL) + (WidthInByte * 2)); @@ -1734,24 +1789,26 @@ S3BootScriptSaveMemPoll ( if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptMemPoll.OpCode = EFI_BOOT_SCRIPT_MEM_POLL_OPCODE; - ScriptMemPoll.Length = Length; - ScriptMemPoll.Width = Width; - ScriptMemPoll.Address = Address; - ScriptMemPoll.Duration = Duration; + ScriptMemPoll.OpCode = EFI_BOOT_SCRIPT_MEM_POLL_OPCODE; + ScriptMemPoll.Length = Length; + ScriptMemPoll.Width = Width; + ScriptMemPoll.Address = Address; + ScriptMemPoll.Duration = Duration; ScriptMemPoll.LoopTimes = LoopTimes; - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_MEM_POLL)), BitValue, WidthInByte); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_MEM_POLL) + WidthInByte), BitMask, WidthInByte); - CopyMem ((VOID*)Script, (VOID*)&ScriptMemPoll, sizeof (EFI_BOOT_SCRIPT_MEM_POLL)); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_POLL)), BitValue, WidthInByte); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_MEM_POLL) + WidthInByte), BitMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptMemPoll, sizeof (EFI_BOOT_SCRIPT_MEM_POLL)); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Store arbitrary information in the boot script table. This opcode is a no-op on dispatch and is only used for debugging script issues. @@ -1766,12 +1823,12 @@ S3BootScriptSaveMemPoll ( RETURN_STATUS EFIAPI S3BootScriptSaveInformation ( - IN UINT32 InformationLength, - IN VOID *Information + IN UINT32 InformationLength, + IN VOID *Information ) { - UINT8 Length; - UINT8 *Script; + UINT8 Length; + UINT8 *Script; EFI_BOOT_SCRIPT_INFORMATION ScriptInformation; // @@ -1780,29 +1837,30 @@ S3BootScriptSaveInformation ( if (InformationLength > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_INFORMATION)) { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_INFORMATION) + InformationLength); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptInformation.OpCode = EFI_BOOT_SCRIPT_INFORMATION_OPCODE; - ScriptInformation.Length = Length; - + ScriptInformation.OpCode = EFI_BOOT_SCRIPT_INFORMATION_OPCODE; + ScriptInformation.Length = Length; ScriptInformation.InformationLength = InformationLength; - CopyMem ((VOID*)Script, (VOID*)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *) Information, (UINTN) InformationLength); + CopyMem ((VOID *)Script, (VOID *)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *)Information, (UINTN)InformationLength); SyncBootScript (Script); return RETURN_SUCCESS; - } + /** Store a string in the boot script table. This opcode is a no-op on dispatch and is only used for debugging script issues. @@ -1816,14 +1874,15 @@ S3BootScriptSaveInformation ( RETURN_STATUS EFIAPI S3BootScriptSaveInformationAsciiString ( - IN CONST CHAR8 *String + IN CONST CHAR8 *String ) { return S3BootScriptSaveInformation ( - (UINT32) AsciiStrLen (String) + 1, - (VOID*) String + (UINT32)AsciiStrLen (String) + 1, + (VOID *)String ); } + /** Adds a record for dispatching specified arbitrary code into a specified boot script table. @@ -1835,11 +1894,11 @@ S3BootScriptSaveInformationAsciiString ( RETURN_STATUS EFIAPI S3BootScriptSaveDispatch ( - IN VOID *EntryPoint + IN VOID *EntryPoint ) { - UINT8 Length; - UINT8 *Script; + UINT8 Length; + UINT8 *Script; EFI_BOOT_SCRIPT_DISPATCH ScriptDispatch; Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_DISPATCH)); @@ -1848,6 +1907,7 @@ S3BootScriptSaveDispatch ( if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // @@ -1855,13 +1915,13 @@ S3BootScriptSaveDispatch ( ScriptDispatch.Length = Length; ScriptDispatch.EntryPoint = (EFI_PHYSICAL_ADDRESS)(UINTN)EntryPoint; - CopyMem ((VOID*)Script, (VOID*)&ScriptDispatch, sizeof (EFI_BOOT_SCRIPT_DISPATCH)); + CopyMem ((VOID *)Script, (VOID *)&ScriptDispatch, sizeof (EFI_BOOT_SCRIPT_DISPATCH)); SyncBootScript (Script); return RETURN_SUCCESS; - } + /** Adds a record for I/O reads the I/O location and continues when the exit criteria is satisfied or after a defined duration. @@ -1881,38 +1941,38 @@ S3BootScriptSaveDispatch ( RETURN_STATUS EFIAPI S3BootScriptSaveIoPoll ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, IN VOID *Data, IN VOID *DataMask, - IN UINT64 Delay + IN UINT64 Delay ) { - UINT8 WidthInByte; - UINT8 *Script; - UINT8 Length; + UINT8 WidthInByte; + UINT8 *Script; + UINT8 Length; EFI_BOOT_SCRIPT_IO_POLL ScriptIoPoll; - - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_POLL) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_POLL) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptIoPoll.OpCode = EFI_BOOT_SCRIPT_IO_POLL_OPCODE; - ScriptIoPoll.Length = (UINT8) (sizeof (EFI_BOOT_SCRIPT_IO_POLL) + (WidthInByte * 2)); - ScriptIoPoll.Width = Width; - ScriptIoPoll.Address = Address; - ScriptIoPoll.Delay = Delay; + ScriptIoPoll.OpCode = EFI_BOOT_SCRIPT_IO_POLL_OPCODE; + ScriptIoPoll.Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_IO_POLL) + (WidthInByte * 2)); + ScriptIoPoll.Width = Width; + ScriptIoPoll.Address = Address; + ScriptIoPoll.Delay = Delay; - CopyMem ((VOID*)Script, (VOID*)&ScriptIoPoll, sizeof (EFI_BOOT_SCRIPT_IO_POLL)); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_IO_POLL)), Data, WidthInByte); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_IO_POLL) + WidthInByte), DataMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptIoPoll, sizeof (EFI_BOOT_SCRIPT_IO_POLL)); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_IO_POLL)), Data, WidthInByte); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_IO_POLL) + WidthInByte), DataMask, WidthInByte); SyncBootScript (Script); @@ -1939,48 +1999,51 @@ S3BootScriptSaveIoPoll ( RETURN_STATUS EFIAPI S3BootScriptSavePciPoll ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask, - IN UINT64 Delay -) + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask, + IN UINT64 Delay + ) { - UINT8 *Script; - UINT8 WidthInByte; - UINT8 Length; + UINT8 *Script; + UINT8 WidthInByte; + UINT8 Length; EFI_BOOT_SCRIPT_PCI_CONFIG_POLL ScriptPciPoll; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPciPoll.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE; - ScriptPciPoll.Length = (UINT8) (sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + (WidthInByte * 2)); - ScriptPciPoll.Width = Width; - ScriptPciPoll.Address = Address; - ScriptPciPoll.Delay = Delay; + ScriptPciPoll.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG_POLL_OPCODE; + ScriptPciPoll.Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + (WidthInByte * 2)); + ScriptPciPoll.Width = Width; + ScriptPciPoll.Address = Address; + ScriptPciPoll.Delay = Delay; - CopyMem ((VOID*)Script, (VOID*)&ScriptPciPoll, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)), Data, WidthInByte); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + WidthInByte), DataMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptPciPoll, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL)), Data, WidthInByte); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG_POLL) + WidthInByte), DataMask, WidthInByte); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Adds a record for PCI configuration space reads and continues when the exit criteria is satisfied or after a defined duration. @@ -2002,50 +2065,53 @@ S3BootScriptSavePciPoll ( RETURN_STATUS EFIAPI S3BootScriptSavePci2Poll ( - IN S3_BOOT_SCRIPT_LIB_WIDTH Width, - IN UINT16 Segment, - IN UINT64 Address, - IN VOID *Data, - IN VOID *DataMask, - IN UINT64 Delay -) + IN S3_BOOT_SCRIPT_LIB_WIDTH Width, + IN UINT16 Segment, + IN UINT64 Address, + IN VOID *Data, + IN VOID *DataMask, + IN UINT64 Delay + ) { - UINT8 WidthInByte; - UINT8 *Script; - UINT8 Length; + UINT8 WidthInByte; + UINT8 *Script; + UINT8 Length; EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL ScriptPci2Poll; - if (Width == S3BootScriptWidthUint64 || - Width == S3BootScriptWidthFifoUint64 || - Width == S3BootScriptWidthFillUint64) { + if ((Width == S3BootScriptWidthUint64) || + (Width == S3BootScriptWidthFifoUint64) || + (Width == S3BootScriptWidthFillUint64)) + { return EFI_INVALID_PARAMETER; } - WidthInByte = (UINT8) (0x01 << (Width & 0x03)); - Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + (WidthInByte * 2)); + WidthInByte = (UINT8)(0x01 << (Width & 0x03)); + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + (WidthInByte * 2)); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptPci2Poll.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE; - ScriptPci2Poll.Length = (UINT8) (sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + (WidthInByte * 2)); - ScriptPci2Poll.Width = Width; - ScriptPci2Poll.Segment = Segment; - ScriptPci2Poll.Address = Address; - ScriptPci2Poll.Delay = Delay; + ScriptPci2Poll.OpCode = EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL_OPCODE; + ScriptPci2Poll.Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + (WidthInByte * 2)); + ScriptPci2Poll.Width = Width; + ScriptPci2Poll.Segment = Segment; + ScriptPci2Poll.Address = Address; + ScriptPci2Poll.Delay = Delay; - CopyMem ((VOID*)Script, (VOID*)&ScriptPci2Poll, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)), Data, WidthInByte); - CopyMem ((UINT8 *) (Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + WidthInByte), DataMask, WidthInByte); + CopyMem ((VOID *)Script, (VOID *)&ScriptPci2Poll, sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL)), Data, WidthInByte); + CopyMem ((UINT8 *)(Script + sizeof (EFI_BOOT_SCRIPT_PCI_CONFIG2_POLL) + WidthInByte), DataMask, WidthInByte); SyncBootScript (Script); return RETURN_SUCCESS; } + /** Do the calculation of start address from which a new s3 boot script entry will write into. @@ -2058,59 +2124,61 @@ S3BootScriptSavePci2Poll ( **/ VOID S3BootScriptCalculateInsertAddress ( - IN UINT8 EntryLength, + IN UINT8 EntryLength, IN VOID *Position OPTIONAL, - IN BOOLEAN BeforeOrAfter OPTIONAL, - OUT UINT8 **Script + IN BOOLEAN BeforeOrAfter OPTIONAL, + OUT UINT8 **Script ) { - UINTN TableLength; - UINT8 *S3TableBase; - UINTN PositionOffset; - EFI_BOOT_SCRIPT_COMMON_HEADER ScriptHeader; - // - // The entry inserting to table is already added to the end of the table - // - TableLength = mS3BootScriptTablePtr->TableLength - EntryLength; - S3TableBase = mS3BootScriptTablePtr->TableBase ; - // - // calculate the Position offset - // - if (Position != NULL) { - PositionOffset = (UINTN)Position - (UINTN)S3TableBase; - - // - // If the BeforeOrAfter is FALSE, that means to insert the node right after the node. - // - if (!BeforeOrAfter) { - CopyMem ((VOID*)&ScriptHeader, Position, sizeof(EFI_BOOT_SCRIPT_COMMON_HEADER)); - PositionOffset += (ScriptHeader.Length); - } - // - // Insert the node before the adjusted Position - // - CopyMem (S3TableBase+PositionOffset+EntryLength, S3TableBase+PositionOffset, TableLength - PositionOffset); - // - // calculate the the start address for the new entry. - // - *Script = S3TableBase + PositionOffset; - - } else { - if (!BeforeOrAfter) { - // - // Insert the node to the end of the table - // - *Script = S3TableBase + TableLength; - } else { - // - // Insert the node to the beginning of the table - // - PositionOffset = (UINTN) sizeof(EFI_BOOT_SCRIPT_TABLE_HEADER); - CopyMem (S3TableBase+PositionOffset+EntryLength, S3TableBase+PositionOffset, TableLength - PositionOffset); - *Script = S3TableBase + PositionOffset; - } - } + UINTN TableLength; + UINT8 *S3TableBase; + UINTN PositionOffset; + EFI_BOOT_SCRIPT_COMMON_HEADER ScriptHeader; + + // + // The entry inserting to table is already added to the end of the table + // + TableLength = mS3BootScriptTablePtr->TableLength - EntryLength; + S3TableBase = mS3BootScriptTablePtr->TableBase; + // + // calculate the Position offset + // + if (Position != NULL) { + PositionOffset = (UINTN)Position - (UINTN)S3TableBase; + + // + // If the BeforeOrAfter is FALSE, that means to insert the node right after the node. + // + if (!BeforeOrAfter) { + CopyMem ((VOID *)&ScriptHeader, Position, sizeof (EFI_BOOT_SCRIPT_COMMON_HEADER)); + PositionOffset += (ScriptHeader.Length); + } + + // + // Insert the node before the adjusted Position + // + CopyMem (S3TableBase+PositionOffset+EntryLength, S3TableBase+PositionOffset, TableLength - PositionOffset); + // + // calculate the the start address for the new entry. + // + *Script = S3TableBase + PositionOffset; + } else { + if (!BeforeOrAfter) { + // + // Insert the node to the end of the table + // + *Script = S3TableBase + TableLength; + } else { + // + // Insert the node to the beginning of the table + // + PositionOffset = (UINTN)sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); + CopyMem (S3TableBase+PositionOffset+EntryLength, S3TableBase+PositionOffset, TableLength - PositionOffset); + *Script = S3TableBase + PositionOffset; + } + } } + /** Move the last boot script entry to the position @@ -2129,21 +2197,21 @@ S3BootScriptCalculateInsertAddress ( RETURN_STATUS EFIAPI S3BootScriptMoveLastOpcode ( - IN BOOLEAN BeforeOrAfter, - IN OUT VOID **Position OPTIONAL -) + IN BOOLEAN BeforeOrAfter, + IN OUT VOID **Position OPTIONAL + ) { - UINT8* Script; - VOID *TempPosition; - UINTN StartAddress; - UINT32 TableLength; + UINT8 *Script; + VOID *TempPosition; + UINTN StartAddress; + UINT32 TableLength; EFI_BOOT_SCRIPT_COMMON_HEADER ScriptHeader; - BOOLEAN ValidatePosition; - UINT8* LastOpcode; - UINT8 TempBootScriptEntry[BOOT_SCRIPT_NODE_MAX_LENGTH]; + BOOLEAN ValidatePosition; + UINT8 *LastOpcode; + UINT8 TempBootScriptEntry[BOOT_SCRIPT_NODE_MAX_LENGTH]; ValidatePosition = FALSE; - TempPosition = (Position == NULL) ? NULL:(*Position); + TempPosition = (Position == NULL) ? NULL : (*Position); // // Check that the script is initialized and synced without adding an entry to the script. @@ -2152,38 +2220,42 @@ S3BootScriptMoveLastOpcode ( if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + Script = mS3BootScriptTablePtr->TableBase; - StartAddress = (UINTN) Script; - TableLength = mS3BootScriptTablePtr->TableLength; - Script = Script + sizeof(EFI_BOOT_SCRIPT_TABLE_HEADER); - LastOpcode = Script; + StartAddress = (UINTN)Script; + TableLength = mS3BootScriptTablePtr->TableLength; + Script = Script + sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER); + LastOpcode = Script; // // Find the last boot Script Entry which is not the terminate node // - while ((UINTN) Script < (UINTN) (StartAddress + TableLength)) { - CopyMem ((VOID*)&ScriptHeader, Script, sizeof(EFI_BOOT_SCRIPT_COMMON_HEADER)); - if (TempPosition != NULL && TempPosition == Script) { + while ((UINTN)Script < (UINTN)(StartAddress + TableLength)) { + CopyMem ((VOID *)&ScriptHeader, Script, sizeof (EFI_BOOT_SCRIPT_COMMON_HEADER)); + if ((TempPosition != NULL) && (TempPosition == Script)) { // // If the position is specified, the position must be pointed to a boot script entry start address. // ValidatePosition = TRUE; } + if (ScriptHeader.OpCode != S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE) { LastOpcode = Script; } - Script = Script + ScriptHeader.Length; + + Script = Script + ScriptHeader.Length; } + // // If the position is specified, but not the start of a boot script entry, it is a invalid input // - if (TempPosition != NULL && !ValidatePosition) { + if ((TempPosition != NULL) && !ValidatePosition) { return RETURN_INVALID_PARAMETER; } - CopyMem ((VOID*)&ScriptHeader, LastOpcode, sizeof(EFI_BOOT_SCRIPT_COMMON_HEADER)); + CopyMem ((VOID *)&ScriptHeader, LastOpcode, sizeof (EFI_BOOT_SCRIPT_COMMON_HEADER)); - CopyMem((VOID*)TempBootScriptEntry, LastOpcode, ScriptHeader.Length); + CopyMem ((VOID *)TempBootScriptEntry, LastOpcode, ScriptHeader.Length); // // Find the right position to write the node in // @@ -2192,11 +2264,11 @@ S3BootScriptMoveLastOpcode ( TempPosition, BeforeOrAfter, &Script - ); + ); // // Copy the node to Boot script table // - CopyMem((VOID*)Script, (VOID*)TempBootScriptEntry, ScriptHeader.Length); + CopyMem ((VOID *)Script, (VOID *)TempBootScriptEntry, ScriptHeader.Length); SyncBootScript (Script); @@ -2206,8 +2278,10 @@ S3BootScriptMoveLastOpcode ( if (Position != NULL) { *Position = Script; } + return RETURN_SUCCESS; } + /** Create a Label node in the boot script table. @@ -2229,14 +2303,14 @@ S3BootScriptMoveLastOpcode ( RETURN_STATUS EFIAPI S3BootScriptLabelInternal ( - IN BOOLEAN BeforeOrAfter, - IN OUT VOID **Position OPTIONAL, - IN UINT32 InformationLength, - IN CONST CHAR8 *Information + IN BOOLEAN BeforeOrAfter, + IN OUT VOID **Position OPTIONAL, + IN UINT32 InformationLength, + IN CONST CHAR8 *Information ) { - UINT8 Length; - UINT8 *Script; + UINT8 Length; + UINT8 *Script; EFI_BOOT_SCRIPT_INFORMATION ScriptInformation; // @@ -2245,29 +2319,30 @@ S3BootScriptLabelInternal ( if (InformationLength > MAX_UINT8 - sizeof (EFI_BOOT_SCRIPT_INFORMATION)) { return RETURN_OUT_OF_RESOURCES; } + Length = (UINT8)(sizeof (EFI_BOOT_SCRIPT_INFORMATION) + InformationLength); Script = S3BootScriptGetEntryAddAddress (Length); if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + // // Build script data // - ScriptInformation.OpCode = S3_BOOT_SCRIPT_LIB_LABEL_OPCODE; - ScriptInformation.Length = Length; - + ScriptInformation.OpCode = S3_BOOT_SCRIPT_LIB_LABEL_OPCODE; + ScriptInformation.Length = Length; ScriptInformation.InformationLength = InformationLength; - CopyMem ((VOID*)Script, (VOID*)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); - CopyMem ((VOID*)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *) Information, (UINTN) InformationLength); + CopyMem ((VOID *)Script, (VOID *)&ScriptInformation, sizeof (EFI_BOOT_SCRIPT_INFORMATION)); + CopyMem ((VOID *)(Script + sizeof (EFI_BOOT_SCRIPT_INFORMATION)), (VOID *)Information, (UINTN)InformationLength); SyncBootScript (Script); return S3BootScriptMoveLastOpcode (BeforeOrAfter, Position); - } + /** Find a label within the boot script table and, if not present, optionally create it. @@ -2293,24 +2368,26 @@ S3BootScriptLabelInternal ( RETURN_STATUS EFIAPI S3BootScriptLabel ( - IN BOOLEAN BeforeOrAfter, - IN BOOLEAN CreateIfNotFound, - IN OUT VOID **Position OPTIONAL, - IN CONST CHAR8 *Label + IN BOOLEAN BeforeOrAfter, + IN BOOLEAN CreateIfNotFound, + IN OUT VOID **Position OPTIONAL, + IN CONST CHAR8 *Label ) { - UINT8* Script; - UINTN StartAddress; - UINT32 TableLength; + UINT8 *Script; + UINTN StartAddress; + UINT32 TableLength; EFI_BOOT_SCRIPT_COMMON_HEADER ScriptHeader; EFI_BOOT_SCRIPT_TABLE_HEADER TableHeader; UINT32 LabelLength; + // // Check NULL Label // if (Label == NULL) { return EFI_INVALID_PARAMETER; } + // // Check empty Label // @@ -2332,27 +2409,29 @@ S3BootScriptLabel ( // Check the header and search for existing label. // Script = mS3BootScriptTablePtr->TableBase; - CopyMem ((VOID*)&TableHeader, Script, sizeof(EFI_BOOT_SCRIPT_TABLE_HEADER)); + CopyMem ((VOID *)&TableHeader, Script, sizeof (EFI_BOOT_SCRIPT_TABLE_HEADER)); if (TableHeader.OpCode != S3_BOOT_SCRIPT_LIB_TABLE_OPCODE) { return EFI_INVALID_PARAMETER; } - StartAddress = (UINTN) Script; - TableLength = mS3BootScriptTablePtr->TableLength; - Script = Script + TableHeader.Length; - while ((UINTN) Script < (UINTN) (StartAddress + TableLength)) { - CopyMem ((VOID*)&ScriptHeader, Script, sizeof(EFI_BOOT_SCRIPT_COMMON_HEADER)); + StartAddress = (UINTN)Script; + TableLength = mS3BootScriptTablePtr->TableLength; + Script = Script + TableHeader.Length; + while ((UINTN)Script < (UINTN)(StartAddress + TableLength)) { + CopyMem ((VOID *)&ScriptHeader, Script, sizeof (EFI_BOOT_SCRIPT_COMMON_HEADER)); if (ScriptHeader.OpCode == S3_BOOT_SCRIPT_LIB_LABEL_OPCODE) { - if (AsciiStrCmp ((CHAR8 *)(UINTN)(Script+sizeof(EFI_BOOT_SCRIPT_INFORMATION)), Label) == 0) { + if (AsciiStrCmp ((CHAR8 *)(UINTN)(Script+sizeof (EFI_BOOT_SCRIPT_INFORMATION)), Label) == 0) { (*Position) = Script; return EFI_SUCCESS; } } - Script = Script + ScriptHeader.Length; + + Script = Script + ScriptHeader.Length; } + if (CreateIfNotFound) { - LabelLength = (UINT32)AsciiStrSize(Label); - return S3BootScriptLabelInternal (BeforeOrAfter,Position, LabelLength, Label); + LabelLength = (UINT32)AsciiStrSize (Label); + return S3BootScriptLabelInternal (BeforeOrAfter, Position, LabelLength, Label); } else { return EFI_NOT_FOUND; } @@ -2375,13 +2454,13 @@ S3BootScriptLabel ( RETURN_STATUS EFIAPI S3BootScriptCompare ( - IN UINT8 *Position1, - IN UINT8 *Position2, - OUT UINTN *RelativePosition + IN UINT8 *Position1, + IN UINT8 *Position2, + OUT UINTN *RelativePosition ) { - UINT8* Script; - UINT32 TableLength; + UINT8 *Script; + UINT32 TableLength; if (RelativePosition == NULL) { return EFI_INVALID_PARAMETER; @@ -2394,19 +2473,22 @@ S3BootScriptCompare ( if (Script == NULL) { return RETURN_OUT_OF_RESOURCES; } + Script = mS3BootScriptTablePtr->TableBase; // // mS3BootScriptTablePtr->TableLength does not include the termination node, so add it up // TableLength = mS3BootScriptTablePtr->TableLength + sizeof (EFI_BOOT_SCRIPT_TERMINATE); - if (Position1 < Script || Position1 > Script+TableLength) { + if ((Position1 < Script) || (Position1 > Script+TableLength)) { return EFI_INVALID_PARAMETER; } - if (Position2 < Script || Position2 > Script+TableLength) { + + if ((Position2 < Script) || (Position2 > Script+TableLength)) { return EFI_INVALID_PARAMETER; } - *RelativePosition = (Position1 < Position2)?-1:((Position1 == Position2)?0:1); + + *RelativePosition = (Position1 < Position2) ? -1 : ((Position1 == Position2) ? 0 : 1); return EFI_SUCCESS; } diff --git a/MdeModulePkg/Library/PiDxeS3BootScriptLib/InternalBootScriptLib.h b/MdeModulePkg/Library/PiDxeS3BootScriptLib/InternalBootScriptLib.h index 9485994087..b443aec08e 100644 --- a/MdeModulePkg/Library/PiDxeS3BootScriptLib/InternalBootScriptLib.h +++ b/MdeModulePkg/Library/PiDxeS3BootScriptLib/InternalBootScriptLib.h @@ -7,6 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ + #ifndef __INTERNAL_BOOT_SCRIPT_LIB__ #define __INTERNAL_BOOT_SCRIPT_LIB__ @@ -35,12 +36,12 @@ #include "BootScriptInternalFormat.h" -#define MAX_IO_ADDRESS 0xFFFF +#define MAX_IO_ADDRESS 0xFFFF // // Macro to convert a UEFI PCI address + segment to a PCI Segment Library PCI address // -#define PCI_ADDRESS_ENCODE(S, A) PCI_SEGMENT_LIB_ADDRESS( \ +#define PCI_ADDRESS_ENCODE(S, A) PCI_SEGMENT_LIB_ADDRESS(\ S, \ ((((UINTN)(A)) & 0xff000000) >> 24), \ ((((UINTN)(A)) & 0x00ff0000) >> 16), \ @@ -49,57 +50,54 @@ ) typedef union { - UINT8 volatile *Buf; - UINT8 volatile *Uint8; - UINT16 volatile *Uint16; - UINT32 volatile *Uint32; - UINT64 volatile *Uint64; - UINTN volatile Uint; + UINT8 volatile *Buf; + UINT8 volatile *Uint8; + UINT16 volatile *Uint16; + UINT32 volatile *Uint32; + UINT64 volatile *Uint64; + UINTN volatile Uint; } PTR; - // Minimum and maximum length for SMBus bus block protocols defined in SMBus spec 2.0. // -#define MIN_SMBUS_BLOCK_LEN 1 -#define MAX_SMBUS_BLOCK_LEN 32 +#define MIN_SMBUS_BLOCK_LEN 1 +#define MAX_SMBUS_BLOCK_LEN 32 // // The boot script private data. // typedef struct { - UINT8 *TableBase; - UINT32 TableLength; // Record the actual memory length - UINT16 TableMemoryPageNumber; // Record the page number Allocated for the table - BOOLEAN InSmm; // Record if this library is in SMM. - BOOLEAN AtRuntime; // Record if current state is after SmmExitBootServices or SmmLegacyBoot. - UINT32 BootTimeScriptLength; // Maintain boot time script length in LockBox after SmmReadyToLock in SMM. - BOOLEAN SmmLocked; // Record if current state is after SmmReadyToLock - BOOLEAN BackFromS3; // Indicate that the system is back from S3. + UINT8 *TableBase; + UINT32 TableLength; // Record the actual memory length + UINT16 TableMemoryPageNumber; // Record the page number Allocated for the table + BOOLEAN InSmm; // Record if this library is in SMM. + BOOLEAN AtRuntime; // Record if current state is after SmmExitBootServices or SmmLegacyBoot. + UINT32 BootTimeScriptLength; // Maintain boot time script length in LockBox after SmmReadyToLock in SMM. + BOOLEAN SmmLocked; // Record if current state is after SmmReadyToLock + BOOLEAN BackFromS3; // Indicate that the system is back from S3. } SCRIPT_TABLE_PRIVATE_DATA; typedef EFI_STATUS -(EFIAPI *DISPATCH_ENTRYPOINT_FUNC) ( +(EFIAPI *DISPATCH_ENTRYPOINT_FUNC)( IN EFI_HANDLE ImageHandle, IN VOID *Context ); -extern SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTablePtr; +extern SCRIPT_TABLE_PRIVATE_DATA *mS3BootScriptTablePtr; // // Define Opcode for Label which is implementation specific and no standard spec define. // -#define S3_BOOT_SCRIPT_LIB_LABEL_OPCODE 0xFE +#define S3_BOOT_SCRIPT_LIB_LABEL_OPCODE 0xFE /// /// The opcode indicate the start of the boot script table. /// -#define S3_BOOT_SCRIPT_LIB_TABLE_OPCODE 0xAA +#define S3_BOOT_SCRIPT_LIB_TABLE_OPCODE 0xAA /// /// The opcode indicate the end of the boot script table. /// -#define S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE 0xFF - +#define S3_BOOT_SCRIPT_LIB_TERMINATE_OPCODE 0xFF #endif //__INTERNAL_BOOT_SCRIPT_LIB__ - diff --git a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/MemoryAllocationLib.c b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/MemoryAllocationLib.c index fd20a779cd..9a4d5b8cac 100644 --- a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/MemoryAllocationLib.c +++ b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/MemoryAllocationLib.c @@ -40,14 +40,15 @@ UINTN mSmmCoreMemoryAllocLibSmramRangeCount = 0; BOOLEAN EFIAPI BufferInSmram ( - IN VOID *Buffer + IN VOID *Buffer ) { UINTN Index; - for (Index = 0; Index < mSmmCoreMemoryAllocLibSmramRangeCount; Index ++) { - if (((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer >= mSmmCoreMemoryAllocLibSmramRanges[Index].CpuStart) && - ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer < (mSmmCoreMemoryAllocLibSmramRanges[Index].CpuStart + mSmmCoreMemoryAllocLibSmramRanges[Index].PhysicalSize))) { + for (Index = 0; Index < mSmmCoreMemoryAllocLibSmramRangeCount; Index++) { + if (((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer >= mSmmCoreMemoryAllocLibSmramRanges[Index].CpuStart) && + ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer < (mSmmCoreMemoryAllocLibSmramRanges[Index].CpuStart + mSmmCoreMemoryAllocLibSmramRanges[Index].PhysicalSize))) + { return TRUE; } } @@ -85,7 +86,8 @@ InternalAllocatePages ( if (EFI_ERROR (Status)) { return NULL; } - return (VOID *) (UINTN) Memory; + + return (VOID *)(UINTN)Memory; } /** @@ -112,14 +114,15 @@ AllocatePages ( Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -147,14 +150,15 @@ AllocateRuntimePages ( Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -212,14 +216,15 @@ FreePages ( // When Buffer is in SMRAM range, it should be allocated by SmmAllocatePages() service. // So, SmmFreePages() service is used to free it. // - Status = SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = SmmFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // - Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } + ASSERT_EFI_ERROR (Status); } @@ -263,23 +268,25 @@ InternalAllocateAlignedPages ( if (Pages == 0) { return NULL; } + if (Alignment > EFI_PAGE_SIZE) { // // Calculate the total number of pages since alignment is larger than page size. // - AlignmentMask = Alignment - 1; - RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); + AlignmentMask = Alignment - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); // // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow. // ASSERT (RealPages > Pages); - Status = SmmAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); + Status = SmmAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; - UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); + + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). @@ -287,6 +294,7 @@ InternalAllocateAlignedPages ( Status = SmmFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } + Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -304,9 +312,11 @@ InternalAllocateAlignedPages ( if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = (UINTN) Memory; + + AlignedMemory = (UINTN)Memory; } - return (VOID *) AlignedMemory; + + return (VOID *)AlignedMemory; } /** @@ -339,14 +349,15 @@ AllocateAlignedPages ( Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -380,14 +391,15 @@ AllocateAlignedRuntimePages ( Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -451,14 +463,15 @@ FreeAlignedPages ( // When Buffer is in SMRAM range, it should be allocated by SmmAllocatePages() service. // So, SmmFreePages() service is used to free it. // - Status = SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = SmmFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // - Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } + ASSERT_EFI_ERROR (Status); } @@ -490,6 +503,7 @@ InternalAllocatePool ( if (EFI_ERROR (Status)) { Memory = NULL; } + return Memory; } @@ -516,7 +530,7 @@ AllocatePool ( Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, EfiRuntimeServicesData, Buffer, @@ -524,6 +538,7 @@ AllocatePool ( NULL ); } + return Buffer; } @@ -550,7 +565,7 @@ AllocateRuntimePool ( Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -558,6 +573,7 @@ AllocateRuntimePool ( NULL ); } + return Buffer; } @@ -608,6 +624,7 @@ InternalAllocateZeroPool ( if (Memory != NULL) { Memory = ZeroMem (Memory, AllocationSize); } + return Memory; } @@ -635,7 +652,7 @@ AllocateZeroPool ( Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, EfiRuntimeServicesData, Buffer, @@ -643,6 +660,7 @@ AllocateZeroPool ( NULL ); } + return Buffer; } @@ -670,7 +688,7 @@ AllocateRuntimeZeroPool ( Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, EfiRuntimeServicesData, Buffer, @@ -678,6 +696,7 @@ AllocateRuntimeZeroPool ( NULL ); } + return Buffer; } @@ -730,12 +749,13 @@ InternalAllocateCopyPool ( VOID *Memory; ASSERT (Buffer != NULL); - ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN) Buffer + 1)); + ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN)Buffer + 1)); Memory = InternalAllocatePool (PoolType, AllocationSize); if (Memory != NULL) { - Memory = CopyMem (Memory, Buffer, AllocationSize); + Memory = CopyMem (Memory, Buffer, AllocationSize); } + return Memory; } @@ -768,7 +788,7 @@ AllocateCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -776,6 +796,7 @@ AllocateCopyPool ( NULL ); } + return NewBuffer; } @@ -808,7 +829,7 @@ AllocateRuntimeCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -816,6 +837,7 @@ AllocateRuntimeCopyPool ( NULL ); } + return NewBuffer; } @@ -879,10 +901,11 @@ InternalReallocatePool ( VOID *NewBuffer; NewBuffer = InternalAllocateZeroPool (PoolType, NewSize); - if (NewBuffer != NULL && OldBuffer != NULL) { + if ((NewBuffer != NULL) && (OldBuffer != NULL)) { CopyMem (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); FreePool (OldBuffer); } + return NewBuffer; } @@ -920,7 +943,7 @@ ReallocatePool ( Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, EfiRuntimeServicesData, Buffer, @@ -928,6 +951,7 @@ ReallocatePool ( NULL ); } + return Buffer; } @@ -965,7 +989,7 @@ ReallocateRuntimePool ( Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -973,6 +997,7 @@ ReallocateRuntimePool ( NULL ); } + return Buffer; } @@ -1025,10 +1050,10 @@ ReallocateReservedPool ( VOID EFIAPI FreePool ( - IN VOID *Buffer + IN VOID *Buffer ) { - EFI_STATUS Status; + EFI_STATUS Status; if (BufferInSmram (Buffer)) { // @@ -1043,6 +1068,7 @@ FreePool ( // Status = gBS->FreePool (Buffer); } + ASSERT_EFI_ERROR (Status); } @@ -1077,8 +1103,8 @@ PiSmmCoreMemoryAllocationLibConstructor ( // so temporarily use BootServicesData to hold the SmramRanges data. // mSmmCoreMemoryAllocLibSmramRangeCount = SmmCorePrivate->SmramRangeCount; - Size = mSmmCoreMemoryAllocLibSmramRangeCount * sizeof (EFI_SMRAM_DESCRIPTOR); - Status = gBS->AllocatePool (EfiBootServicesData, Size, (VOID **) &mSmmCoreMemoryAllocLibSmramRanges); + Size = mSmmCoreMemoryAllocLibSmramRangeCount * sizeof (EFI_SMRAM_DESCRIPTOR); + Status = gBS->AllocatePool (EfiBootServicesData, Size, (VOID **)&mSmmCoreMemoryAllocLibSmramRanges); ASSERT_EFI_ERROR (Status); ASSERT (mSmmCoreMemoryAllocLibSmramRanges != NULL); CopyMem (mSmmCoreMemoryAllocLibSmramRanges, SmmCorePrivate->SmramRanges, Size); @@ -1091,8 +1117,8 @@ PiSmmCoreMemoryAllocationLibConstructor ( // // Move the SmramRanges data from BootServicesData to SMRAM. // - BootServicesData = mSmmCoreMemoryAllocLibSmramRanges; - mSmmCoreMemoryAllocLibSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocateCopyPool (Size, (VOID *) BootServicesData); + BootServicesData = mSmmCoreMemoryAllocLibSmramRanges; + mSmmCoreMemoryAllocLibSmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocateCopyPool (Size, (VOID *)BootServicesData); ASSERT (mSmmCoreMemoryAllocLibSmramRanges != NULL); // diff --git a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationServices.h b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationServices.h index 789fcf2c01..64429e028a 100644 --- a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationServices.h +++ b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationServices.h @@ -16,26 +16,26 @@ // It should be aligned with the definition in PiSmmCore. // typedef struct { - UINTN Signature; + UINTN Signature; /// /// The ImageHandle passed into the entry point of the SMM IPL. This ImageHandle /// is used by the SMM Core to fill in the ParentImageHandle field of the Loaded /// Image Protocol for each SMM Driver that is dispatched by the SMM Core. /// - EFI_HANDLE SmmIplImageHandle; + EFI_HANDLE SmmIplImageHandle; /// /// The number of SMRAM ranges passed from the SMM IPL to the SMM Core. The SMM /// Core uses these ranges of SMRAM to initialize the SMM Core memory manager. /// - UINTN SmramRangeCount; + UINTN SmramRangeCount; /// /// A table of SMRAM ranges passed from the SMM IPL to the SMM Core. The SMM /// Core uses these ranges of SMRAM to initialize the SMM Core memory manager. /// - EFI_SMRAM_DESCRIPTOR *SmramRanges; + EFI_SMRAM_DESCRIPTOR *SmramRanges; /// /// The SMM Foundation Entry Point. The SMM Core fills in this field when the @@ -46,48 +46,48 @@ typedef struct { /// the SMM Foundation Entry Point as soon as the SMM Configuration Protocol is /// available. /// - EFI_SMM_ENTRY_POINT SmmEntryPoint; + EFI_SMM_ENTRY_POINT SmmEntryPoint; /// /// Boolean flag set to TRUE while an SMI is being processed by the SMM Core. /// - BOOLEAN SmmEntryPointRegistered; + BOOLEAN SmmEntryPointRegistered; /// /// Boolean flag set to TRUE while an SMI is being processed by the SMM Core. /// - BOOLEAN InSmm; + BOOLEAN InSmm; /// /// This field is set by the SMM Core then the SMM Core is initialized. This field is /// used by the SMM Base 2 Protocol and SMM Communication Protocol implementations in /// the SMM IPL. /// - EFI_SMM_SYSTEM_TABLE2 *Smst; + EFI_SMM_SYSTEM_TABLE2 *Smst; /// /// This field is used by the SMM Communicatioon Protocol to pass a buffer into /// a software SMI handler and for the software SMI handler to pass a buffer back to /// the caller of the SMM Communication Protocol. /// - VOID *CommunicationBuffer; + VOID *CommunicationBuffer; /// /// This field is used by the SMM Communicatioon Protocol to pass the size of a buffer, /// in bytes, into a software SMI handler and for the software SMI handler to pass the /// size, in bytes, of a buffer back to the caller of the SMM Communication Protocol. /// - UINTN BufferSize; + UINTN BufferSize; /// /// This field is used by the SMM Communication Protocol to pass the return status from /// a software SMI handler back to the caller of the SMM Communication Protocol. /// - EFI_STATUS ReturnStatus; + EFI_STATUS ReturnStatus; - EFI_PHYSICAL_ADDRESS PiSmmCoreImageBase; - UINT64 PiSmmCoreImageSize; - EFI_PHYSICAL_ADDRESS PiSmmCoreEntryPoint; + EFI_PHYSICAL_ADDRESS PiSmmCoreImageBase; + UINT64 PiSmmCoreImageSize; + EFI_PHYSICAL_ADDRESS PiSmmCoreEntryPoint; } SMM_CORE_PRIVATE_DATA; /** @@ -122,10 +122,10 @@ SmmInitializeMemoryServices ( EFI_STATUS EFIAPI SmmAllocatePages ( - IN EFI_ALLOCATE_TYPE Type, - IN EFI_MEMORY_TYPE MemoryType, - IN UINTN NumberOfPages, - OUT EFI_PHYSICAL_ADDRESS *Memory + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN NumberOfPages, + OUT EFI_PHYSICAL_ADDRESS *Memory ); /** @@ -142,8 +142,8 @@ SmmAllocatePages ( EFI_STATUS EFIAPI SmmFreePages ( - IN EFI_PHYSICAL_ADDRESS Memory, - IN UINTN NumberOfPages + IN EFI_PHYSICAL_ADDRESS Memory, + IN UINTN NumberOfPages ); /** @@ -162,9 +162,9 @@ SmmFreePages ( EFI_STATUS EFIAPI SmmAllocatePool ( - IN EFI_MEMORY_TYPE PoolType, - IN UINTN Size, - OUT VOID **Buffer + IN EFI_MEMORY_TYPE PoolType, + IN UINTN Size, + OUT VOID **Buffer ); /** @@ -179,7 +179,7 @@ SmmAllocatePool ( EFI_STATUS EFIAPI SmmFreePool ( - IN VOID *Buffer + IN VOID *Buffer ); #endif diff --git a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLib.c b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLib.c index 32ef22256f..82ad226e2e 100644 --- a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLib.c +++ b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLib.c @@ -15,7 +15,7 @@ #include "PiSmmCoreMemoryProfileServices.h" -EDKII_MEMORY_PROFILE_PROTOCOL *mLibProfileProtocol; +EDKII_MEMORY_PROFILE_PROTOCOL *mLibProfileProtocol; /** Check whether the start address of buffer is within any of the SMRAM ranges. @@ -28,7 +28,7 @@ EDKII_MEMORY_PROFILE_PROTOCOL *mLibProfileProtocol; BOOLEAN EFIAPI BufferInSmram ( - IN VOID *Buffer + IN VOID *Buffer ); /** @@ -47,7 +47,7 @@ PiSmmCoreMemoryProfileLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Locate Profile Protocol @@ -89,12 +89,12 @@ PiSmmCoreMemoryProfileLibConstructor ( EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { if (BufferInSmram (Buffer)) { @@ -103,6 +103,7 @@ MemoryProfileLibRecord ( if (mLibProfileProtocol == NULL) { return EFI_UNSUPPORTED; } + return mLibProfileProtocol->Record ( mLibProfileProtocol, CallerAddress, @@ -114,4 +115,3 @@ MemoryProfileLibRecord ( ); } } - diff --git a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLibNull.c b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLibNull.c index b132024d04..22b2cf883a 100644 --- a/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLibNull.c +++ b/MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryProfileLibNull.c @@ -35,14 +35,13 @@ EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { return EFI_UNSUPPORTED; } - diff --git a/MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManager.c b/MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManager.c index 43560bf2aa..db6ada3aac 100644 --- a/MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManager.c +++ b/MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManager.c @@ -9,7 +9,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include - /** Do the platform specific action before the console is connected. @@ -54,7 +53,7 @@ PlatformBootManagerAfterConsole ( VOID EFIAPI PlatformBootManagerWaitCallback ( - UINT16 TimeoutRemain + UINT16 TimeoutRemain ) { return; @@ -75,4 +74,3 @@ PlatformBootManagerUnableToBoot ( { return; } - diff --git a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanup.h b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanup.h index c809a7086b..332521360d 100644 --- a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanup.h +++ b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanup.h @@ -38,65 +38,65 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // This data array is ready to be used as input of HiiAddPackages() to // create a packagelist (which contains Form packages, String packages, etc). // -extern UINT8 PlatVarCleanupBin[]; +extern UINT8 PlatVarCleanupBin[]; // // This is the generated String package data for all .UNI files. // This data array is ready to be used as input of HiiAddPackages() to // create a packagelist (which contains Form packages, String packages, etc). // -extern UINT8 PlatformVarCleanupLibStrings[]; +extern UINT8 PlatformVarCleanupLibStrings[]; -#define USER_VARIABLE_NODE_SIGNATURE SIGNATURE_32 ('U', 'V', 'N', 'S') +#define USER_VARIABLE_NODE_SIGNATURE SIGNATURE_32 ('U', 'V', 'N', 'S') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - EFI_GUID Guid; - CHAR16 *PromptString; - LIST_ENTRY NameLink; + UINTN Signature; + LIST_ENTRY Link; + EFI_GUID Guid; + CHAR16 *PromptString; + LIST_ENTRY NameLink; } USER_VARIABLE_NODE; -#define USER_VARIABLE_FROM_LINK(a) CR (a, USER_VARIABLE_NODE, Link, USER_VARIABLE_NODE_SIGNATURE) +#define USER_VARIABLE_FROM_LINK(a) CR (a, USER_VARIABLE_NODE, Link, USER_VARIABLE_NODE_SIGNATURE) -#define USER_VARIABLE_NAME_NODE_SIGNATURE SIGNATURE_32 ('U', 'V', 'N', 'N') +#define USER_VARIABLE_NAME_NODE_SIGNATURE SIGNATURE_32 ('U', 'V', 'N', 'N') typedef struct { - UINTN Signature; - LIST_ENTRY Link; - CHAR16 *Name; - UINTN DataSize; - UINT32 Attributes; - UINT16 Index; - EFI_QUESTION_ID QuestionId; - CHAR16 *PromptString; - CHAR16 *HelpString; - BOOLEAN Deleted; + UINTN Signature; + LIST_ENTRY Link; + CHAR16 *Name; + UINTN DataSize; + UINT32 Attributes; + UINT16 Index; + EFI_QUESTION_ID QuestionId; + CHAR16 *PromptString; + CHAR16 *HelpString; + BOOLEAN Deleted; } USER_VARIABLE_NAME_NODE; -#define USER_VARIABLE_NAME_FROM_LINK(a) CR (a, USER_VARIABLE_NAME_NODE, Link, USER_VARIABLE_NAME_NODE_SIGNATURE) +#define USER_VARIABLE_NAME_FROM_LINK(a) CR (a, USER_VARIABLE_NAME_NODE, Link, USER_VARIABLE_NAME_NODE_SIGNATURE) #pragma pack(1) // // HII specific Vendor Device Path definition. // typedef struct { - VENDOR_DEVICE_PATH VendorDevicePath; - EFI_DEVICE_PATH_PROTOCOL End; + VENDOR_DEVICE_PATH VendorDevicePath; + EFI_DEVICE_PATH_PROTOCOL End; } HII_VENDOR_DEVICE_PATH; #pragma pack() -#define VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE SIGNATURE_32 ('V', 'C', 'H', 'P') +#define VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE SIGNATURE_32 ('V', 'C', 'H', 'P') typedef struct { - UINTN Signature; - EFI_HANDLE DriverHandle; - EFI_HII_HANDLE HiiHandle; - EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; - EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting; - VARIABLE_CLEANUP_DATA VariableCleanupData; + UINTN Signature; + EFI_HANDLE DriverHandle; + EFI_HII_HANDLE HiiHandle; + EFI_HII_CONFIG_ACCESS_PROTOCOL ConfigAccess; + EFI_HII_CONFIG_ROUTING_PROTOCOL *ConfigRouting; + VARIABLE_CLEANUP_DATA VariableCleanupData; } VARIABLE_CLEANUP_HII_PRIVATE_DATA; -#define VARIABLE_CLEANUP_HII_PRIVATE_FROM_THIS(a) CR (a, VARIABLE_CLEANUP_HII_PRIVATE_DATA, ConfigAccess, VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE) +#define VARIABLE_CLEANUP_HII_PRIVATE_FROM_THIS(a) CR (a, VARIABLE_CLEANUP_HII_PRIVATE_DATA, ConfigAccess, VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE) #endif diff --git a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupHii.h b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupHii.h index 74bcdb4b9f..9f9cc94bfe 100644 --- a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupHii.h +++ b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupHii.h @@ -17,37 +17,37 @@ SPDX-License-Identifier: BSD-2-Clause-Patent 0x24f14d8a, 0xd7a8, 0x4991, { 0x91, 0xe0, 0x96, 0xc3, 0xb7, 0xdb, 0x84, 0x56 } \ } -#define MAX_USER_VARIABLE_COUNT 0x1000 +#define MAX_USER_VARIABLE_COUNT 0x1000 typedef struct { - UINT8 SelectAll; + UINT8 SelectAll; // // FALSE is to not delete, TRUE is to delete. // - UINT8 UserVariable[MAX_USER_VARIABLE_COUNT]; + UINT8 UserVariable[MAX_USER_VARIABLE_COUNT]; } VARIABLE_CLEANUP_DATA; -#define VARIABLE_CLEANUP_VARSTORE_ID 0x8000 +#define VARIABLE_CLEANUP_VARSTORE_ID 0x8000 // // Field offset of structure VARIABLE_CLEANUP_DATA // -#define VAR_OFFSET(Field) ((UINTN) &(((VARIABLE_CLEANUP_DATA *) 0)->Field)) -#define USER_VARIABLE_VAR_OFFSET (VAR_OFFSET (UserVariable)) +#define VAR_OFFSET(Field) ((UINTN) &(((VARIABLE_CLEANUP_DATA *) 0)->Field)) +#define USER_VARIABLE_VAR_OFFSET (VAR_OFFSET (UserVariable)) -#define FORM_ID_VARIABLE_CLEANUP 0x8000 +#define FORM_ID_VARIABLE_CLEANUP 0x8000 -#define LABEL_START 0x0000 -#define LABEL_END 0xFFFF +#define LABEL_START 0x0000 +#define LABEL_END 0xFFFF -#define SELECT_ALL_QUESTION_ID 0x7FFD -#define SAVE_AND_EXIT_QUESTION_ID 0x7FFE -#define NO_SAVE_AND_EXIT_QUESTION_ID 0x7FFF +#define SELECT_ALL_QUESTION_ID 0x7FFD +#define SAVE_AND_EXIT_QUESTION_ID 0x7FFE +#define NO_SAVE_AND_EXIT_QUESTION_ID 0x7FFF // // Tool automatic generated Question Id start from 1. // In order to avoid to conflict them, the user variable QuestionID offset is defined from 0x8000. // -#define USER_VARIABLE_QUESTION_ID 0x8000 +#define USER_VARIABLE_QUESTION_ID 0x8000 #endif diff --git a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupLib.c b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupLib.c index 0633f8197f..d37367823d 100644 --- a/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupLib.c +++ b/MdeModulePkg/Library/PlatformVarCleanupLib/PlatVarCleanupLib.c @@ -8,31 +8,31 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PlatVarCleanup.h" -VAR_ERROR_FLAG mLastVarErrorFlag = VAR_ERROR_FLAG_NO_ERROR; -EDKII_VAR_CHECK_PROTOCOL *mVarCheck = NULL; +VAR_ERROR_FLAG mLastVarErrorFlag = VAR_ERROR_FLAG_NO_ERROR; +EDKII_VAR_CHECK_PROTOCOL *mVarCheck = NULL; /// /// The flag to indicate whether the platform has left the DXE phase of execution. /// -BOOLEAN mEndOfDxe = FALSE; +BOOLEAN mEndOfDxe = FALSE; -EFI_EVENT mPlatVarCleanupLibEndOfDxeEvent = NULL; +EFI_EVENT mPlatVarCleanupLibEndOfDxeEvent = NULL; -LIST_ENTRY mUserVariableList = INITIALIZE_LIST_HEAD_VARIABLE (mUserVariableList); -UINT16 mUserVariableCount = 0; -UINT16 mMarkedUserVariableCount = 0; +LIST_ENTRY mUserVariableList = INITIALIZE_LIST_HEAD_VARIABLE (mUserVariableList); +UINT16 mUserVariableCount = 0; +UINT16 mMarkedUserVariableCount = 0; -EFI_GUID mVariableCleanupHiiGuid = VARIABLE_CLEANUP_HII_GUID; -CHAR16 mVarStoreName[] = L"VariableCleanup"; +EFI_GUID mVariableCleanupHiiGuid = VARIABLE_CLEANUP_HII_GUID; +CHAR16 mVarStoreName[] = L"VariableCleanup"; -HII_VENDOR_DEVICE_PATH mVarCleanupHiiVendorDevicePath = { +HII_VENDOR_DEVICE_PATH mVarCleanupHiiVendorDevicePath = { { { HARDWARE_DEVICE_PATH, HW_VENDOR_DP, { - (UINT8) (sizeof (VENDOR_DEVICE_PATH)), - (UINT8) ((sizeof (VENDOR_DEVICE_PATH)) >> 8) + (UINT8)(sizeof (VENDOR_DEVICE_PATH)), + (UINT8)((sizeof (VENDOR_DEVICE_PATH)) >> 8) } }, VARIABLE_CLEANUP_HII_GUID @@ -41,8 +41,8 @@ HII_VENDOR_DEVICE_PATH mVarCleanupHiiVendorDevicePath = { END_DEVICE_PATH_TYPE, END_ENTIRE_DEVICE_PATH_SUBTYPE, { - (UINT8) (sizeof (EFI_DEVICE_PATH_PROTOCOL)), - (UINT8) ((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) + (UINT8)(sizeof (EFI_DEVICE_PATH_PROTOCOL)), + (UINT8)((sizeof (EFI_DEVICE_PATH_PROTOCOL)) >> 8) } } }; @@ -58,11 +58,11 @@ InternalGetVarErrorFlag ( VOID ) { - EFI_STATUS Status; - UINTN Size; - VAR_ERROR_FLAG ErrorFlag; + EFI_STATUS Status; + UINTN Size; + VAR_ERROR_FLAG ErrorFlag; - Size = sizeof (ErrorFlag); + Size = sizeof (ErrorFlag); Status = gRT->GetVariable ( VAR_ERROR_FLAG_NAME, &gEdkiiVarErrorFlagGuid, @@ -74,6 +74,7 @@ InternalGetVarErrorFlag ( DEBUG ((DEBUG_INFO, "%s - not found\n", VAR_ERROR_FLAG_NAME)); return VAR_ERROR_FLAG_NO_ERROR; } + return ErrorFlag; } @@ -89,20 +90,21 @@ InternalGetVarErrorFlag ( **/ BOOLEAN IsUserVariable ( - IN CHAR16 *Name, - IN EFI_GUID *Guid + IN CHAR16 *Name, + IN EFI_GUID *Guid ) { - EFI_STATUS Status; - VAR_CHECK_VARIABLE_PROPERTY Property; + EFI_STATUS Status; + VAR_CHECK_VARIABLE_PROPERTY Property; if (mVarCheck == NULL) { gBS->LocateProtocol ( &gEdkiiVarCheckProtocolGuid, NULL, - (VOID **) &mVarCheck + (VOID **)&mVarCheck ); } + ASSERT (mVarCheck != NULL); ZeroMem (&Property, sizeof (Property)); @@ -119,12 +121,12 @@ IsUserVariable ( return TRUE; } -// DEBUG ((DEBUG_INFO, "PlatformVarCleanup - Variable Property: %g:%s\n", Guid, Name)); -// DEBUG ((DEBUG_INFO, " Revision - 0x%04x\n", Property.Revision)); -// DEBUG ((DEBUG_INFO, " Property - 0x%04x\n", Property.Property)); -// DEBUG ((DEBUG_INFO, " Attribute - 0x%08x\n", Property.Attributes)); -// DEBUG ((DEBUG_INFO, " MinSize - 0x%x\n", Property.MinSize)); -// DEBUG ((DEBUG_INFO, " MaxSize - 0x%x\n", Property.MaxSize)); + // DEBUG ((DEBUG_INFO, "PlatformVarCleanup - Variable Property: %g:%s\n", Guid, Name)); + // DEBUG ((DEBUG_INFO, " Revision - 0x%04x\n", Property.Revision)); + // DEBUG ((DEBUG_INFO, " Property - 0x%04x\n", Property.Property)); + // DEBUG ((DEBUG_INFO, " Attribute - 0x%08x\n", Property.Attributes)); + // DEBUG ((DEBUG_INFO, " MinSize - 0x%x\n", Property.MinSize)); + // DEBUG ((DEBUG_INFO, " MaxSize - 0x%x\n", Property.MaxSize)); return FALSE; } @@ -139,15 +141,16 @@ IsUserVariable ( **/ USER_VARIABLE_NODE * FindUserVariableNodeByGuid ( - IN EFI_GUID *Guid + IN EFI_GUID *Guid ) { - USER_VARIABLE_NODE *UserVariableNode; - LIST_ENTRY *Link; + USER_VARIABLE_NODE *UserVariableNode; + LIST_ENTRY *Link; for (Link = mUserVariableList.ForwardLink - ;Link != &mUserVariableList - ;Link = Link->ForwardLink) { + ; Link != &mUserVariableList + ; Link = Link->ForwardLink) + { UserVariableNode = USER_VARIABLE_FROM_LINK (Link); if (CompareGuid (Guid, &UserVariableNode->Guid)) { @@ -185,56 +188,57 @@ CreateUserVariableNode ( VOID ) { - EFI_STATUS Status; - EFI_STATUS GetVariableStatus; - CHAR16 *VarName; - UINTN MaxVarNameSize; - UINTN VarNameSize; - UINTN MaxDataSize; - UINTN DataSize; - VOID *Data; - UINT32 Attributes; - EFI_GUID Guid; - USER_VARIABLE_NODE *UserVariableNode; - USER_VARIABLE_NAME_NODE *UserVariableNameNode; - UINT16 Index; - UINTN StringSize; + EFI_STATUS Status; + EFI_STATUS GetVariableStatus; + CHAR16 *VarName; + UINTN MaxVarNameSize; + UINTN VarNameSize; + UINTN MaxDataSize; + UINTN DataSize; + VOID *Data; + UINT32 Attributes; + EFI_GUID Guid; + USER_VARIABLE_NODE *UserVariableNode; + USER_VARIABLE_NAME_NODE *UserVariableNameNode; + UINT16 Index; + UINTN StringSize; // // Initialize 128 * sizeof (CHAR16) variable name size. // MaxVarNameSize = 128 * sizeof (CHAR16); - VarName = AllocateZeroPool (MaxVarNameSize); + VarName = AllocateZeroPool (MaxVarNameSize); ASSERT (VarName != NULL); // // Initialize 0x1000 variable data size. // MaxDataSize = 0x1000; - Data = AllocateZeroPool (MaxDataSize); + Data = AllocateZeroPool (MaxDataSize); ASSERT (Data != NULL); Index = 0; do { VarNameSize = MaxVarNameSize; - Status = gRT->GetNextVariableName (&VarNameSize, VarName, &Guid); + Status = gRT->GetNextVariableName (&VarNameSize, VarName, &Guid); if (Status == EFI_BUFFER_TOO_SMALL) { VarName = ReallocatePool (MaxVarNameSize, VarNameSize, VarName); ASSERT (VarName != NULL); MaxVarNameSize = VarNameSize; - Status = gRT->GetNextVariableName (&VarNameSize, VarName, &Guid); + Status = gRT->GetNextVariableName (&VarNameSize, VarName, &Guid); } if (!EFI_ERROR (Status)) { if (IsUserVariable (VarName, &Guid)) { - DataSize = MaxDataSize; + DataSize = MaxDataSize; GetVariableStatus = gRT->GetVariable (VarName, &Guid, &Attributes, &DataSize, Data); if (GetVariableStatus == EFI_BUFFER_TOO_SMALL) { Data = ReallocatePool (MaxDataSize, DataSize, Data); ASSERT (Data != NULL); - MaxDataSize = DataSize; + MaxDataSize = DataSize; GetVariableStatus = gRT->GetVariable (VarName, &Guid, &Attributes, &DataSize, Data); } + ASSERT_EFI_ERROR (GetVariableStatus); if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) { @@ -246,23 +250,23 @@ CreateUserVariableNode ( // UserVariableNameNode = AllocateZeroPool (sizeof (*UserVariableNameNode)); ASSERT (UserVariableNameNode != NULL); - UserVariableNameNode->Signature = USER_VARIABLE_NAME_NODE_SIGNATURE; - UserVariableNameNode->Name = AllocateCopyPool (VarNameSize, VarName); + UserVariableNameNode->Signature = USER_VARIABLE_NAME_NODE_SIGNATURE; + UserVariableNameNode->Name = AllocateCopyPool (VarNameSize, VarName); UserVariableNameNode->Attributes = Attributes; - UserVariableNameNode->DataSize = DataSize; - UserVariableNameNode->Index = Index; - UserVariableNameNode->QuestionId = (EFI_QUESTION_ID) (USER_VARIABLE_QUESTION_ID + Index); + UserVariableNameNode->DataSize = DataSize; + UserVariableNameNode->Index = Index; + UserVariableNameNode->QuestionId = (EFI_QUESTION_ID)(USER_VARIABLE_QUESTION_ID + Index); // // 2 space * sizeof (CHAR16) + StrSize. // - StringSize = 2 * sizeof (CHAR16) + StrSize (UserVariableNameNode->Name); + StringSize = 2 * sizeof (CHAR16) + StrSize (UserVariableNameNode->Name); UserVariableNameNode->PromptString = AllocatePool (StringSize); ASSERT (UserVariableNameNode->PromptString != NULL); UnicodeSPrint (UserVariableNameNode->PromptString, StringSize, L" %s", UserVariableNameNode->Name); // // (33 chars of "Attribtues = 0x and DataSize = 0x" + 1 terminator + (sizeof (UINT32) + sizeof (UINTN)) * 2) * sizeof (CHAR16). // - StringSize = (33 + 1 + (sizeof (UINT32) + sizeof (UINTN)) * 2) * sizeof (CHAR16); + StringSize = (33 + 1 + (sizeof (UINT32) + sizeof (UINTN)) * 2) * sizeof (CHAR16); UserVariableNameNode->HelpString = AllocatePool (StringSize); ASSERT (UserVariableNameNode->HelpString != NULL); UnicodeSPrint (UserVariableNameNode->HelpString, StringSize, L"Attribtues = 0x%08x and DataSize = 0x%x", UserVariableNameNode->Attributes, UserVariableNameNode->DataSize); @@ -291,19 +295,19 @@ DestroyUserVariableNode ( VOID ) { - USER_VARIABLE_NODE *UserVariableNode; - LIST_ENTRY *Link; - USER_VARIABLE_NAME_NODE *UserVariableNameNode; - LIST_ENTRY *NameLink; + USER_VARIABLE_NODE *UserVariableNode; + LIST_ENTRY *Link; + USER_VARIABLE_NAME_NODE *UserVariableNameNode; + LIST_ENTRY *NameLink; while (mUserVariableList.ForwardLink != &mUserVariableList) { - Link = mUserVariableList.ForwardLink; + Link = mUserVariableList.ForwardLink; UserVariableNode = USER_VARIABLE_FROM_LINK (Link); RemoveEntryList (&UserVariableNode->Link); while (UserVariableNode->NameLink.ForwardLink != &UserVariableNode->NameLink) { - NameLink = UserVariableNode->NameLink.ForwardLink; + NameLink = UserVariableNode->NameLink.ForwardLink; UserVariableNameNode = USER_VARIABLE_NAME_FROM_LINK (NameLink); RemoveEntryList (&UserVariableNameNode->Link); @@ -339,19 +343,19 @@ DestroyUserVariableNode ( **/ EFI_STATUS CreateTimeBasedPayload ( - IN OUT UINTN *DataSize, - IN OUT UINT8 **Data + IN OUT UINTN *DataSize, + IN OUT UINT8 **Data ) { - EFI_STATUS Status; - UINT8 *NewData; - UINT8 *Payload; - UINTN PayloadSize; - EFI_VARIABLE_AUTHENTICATION_2 *DescriptorData; - UINTN DescriptorSize; - EFI_TIME Time; - - if (Data == NULL || DataSize == NULL) { + EFI_STATUS Status; + UINT8 *NewData; + UINT8 *Payload; + UINTN PayloadSize; + EFI_VARIABLE_AUTHENTICATION_2 *DescriptorData; + UINTN DescriptorSize; + EFI_TIME Time; + + if ((Data == NULL) || (DataSize == NULL)) { return EFI_INVALID_PARAMETER; } @@ -365,7 +369,7 @@ CreateTimeBasedPayload ( PayloadSize = *DataSize; DescriptorSize = OFFSET_OF (EFI_VARIABLE_AUTHENTICATION_2, AuthInfo) + OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData); - NewData = (UINT8 *) AllocateZeroPool (DescriptorSize + PayloadSize); + NewData = (UINT8 *)AllocateZeroPool (DescriptorSize + PayloadSize); if (NewData == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -374,7 +378,7 @@ CreateTimeBasedPayload ( CopyMem (NewData + DescriptorSize, Payload, PayloadSize); } - DescriptorData = (EFI_VARIABLE_AUTHENTICATION_2 *) (NewData); + DescriptorData = (EFI_VARIABLE_AUTHENTICATION_2 *)(NewData); ZeroMem (&Time, sizeof (EFI_TIME)); Status = gRT->GetTime (&Time, NULL); @@ -382,6 +386,7 @@ CreateTimeBasedPayload ( FreePool (NewData); return Status; } + Time.Pad1 = 0; Time.Nanosecond = 0; Time.TimeZone = 0; @@ -423,19 +428,19 @@ CreateTimeBasedPayload ( **/ EFI_STATUS CreateCounterBasedPayload ( - IN OUT UINTN *DataSize, - IN OUT UINT8 **Data + IN OUT UINTN *DataSize, + IN OUT UINT8 **Data ) { - EFI_STATUS Status; - UINT8 *NewData; - UINT8 *Payload; - UINTN PayloadSize; - EFI_VARIABLE_AUTHENTICATION *DescriptorData; - UINTN DescriptorSize; - UINT64 MonotonicCount; - - if (Data == NULL || DataSize == NULL) { + EFI_STATUS Status; + UINT8 *NewData; + UINT8 *Payload; + UINTN PayloadSize; + EFI_VARIABLE_AUTHENTICATION *DescriptorData; + UINTN DescriptorSize; + UINT64 MonotonicCount; + + if ((Data == NULL) || (DataSize == NULL)) { return EFI_INVALID_PARAMETER; } @@ -451,7 +456,7 @@ CreateCounterBasedPayload ( DescriptorSize = (OFFSET_OF (EFI_VARIABLE_AUTHENTICATION, AuthInfo)) + \ (OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData)) + \ sizeof (EFI_CERT_BLOCK_RSA_2048_SHA256); - NewData = (UINT8 *) AllocateZeroPool (DescriptorSize + PayloadSize); + NewData = (UINT8 *)AllocateZeroPool (DescriptorSize + PayloadSize); if (NewData == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -460,13 +465,14 @@ CreateCounterBasedPayload ( CopyMem (NewData + DescriptorSize, Payload, PayloadSize); } - DescriptorData = (EFI_VARIABLE_AUTHENTICATION *) (NewData); + DescriptorData = (EFI_VARIABLE_AUTHENTICATION *)(NewData); Status = gBS->GetNextMonotonicCount (&MonotonicCount); if (EFI_ERROR (Status)) { FreePool (NewData); return Status; } + DescriptorData->MonotonicCount = MonotonicCount; DescriptorData->AuthInfo.Hdr.dwLength = OFFSET_OF (WIN_CERTIFICATE_UEFI_GUID, CertData) + sizeof (EFI_CERT_BLOCK_RSA_2048_SHA256); @@ -496,38 +502,40 @@ DeleteUserVariable ( IN VARIABLE_CLEANUP_DATA *VariableCleanupData OPTIONAL ) { - EFI_STATUS Status; - USER_VARIABLE_NODE *UserVariableNode; - LIST_ENTRY *Link; - USER_VARIABLE_NAME_NODE *UserVariableNameNode; - LIST_ENTRY *NameLink; - UINTN DataSize; - UINT8 *Data; + EFI_STATUS Status; + USER_VARIABLE_NODE *UserVariableNode; + LIST_ENTRY *Link; + USER_VARIABLE_NAME_NODE *UserVariableNameNode; + LIST_ENTRY *NameLink; + UINTN DataSize; + UINT8 *Data; for (Link = mUserVariableList.ForwardLink - ;Link != &mUserVariableList - ;Link = Link->ForwardLink) { + ; Link != &mUserVariableList + ; Link = Link->ForwardLink) + { UserVariableNode = USER_VARIABLE_FROM_LINK (Link); for (NameLink = UserVariableNode->NameLink.ForwardLink - ;NameLink != &UserVariableNode->NameLink - ;NameLink = NameLink->ForwardLink) { + ; NameLink != &UserVariableNode->NameLink + ; NameLink = NameLink->ForwardLink) + { UserVariableNameNode = USER_VARIABLE_NAME_FROM_LINK (NameLink); if (!UserVariableNameNode->Deleted && (DeleteAll || ((VariableCleanupData != NULL) && (VariableCleanupData->UserVariable[UserVariableNameNode->Index] == TRUE)))) { DEBUG ((DEBUG_INFO, "PlatformVarCleanup - Delete variable: %g:%s\n", &UserVariableNode->Guid, UserVariableNameNode->Name)); if ((UserVariableNameNode->Attributes & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS) != 0) { DataSize = 0; - Data = NULL; - Status = CreateTimeBasedPayload (&DataSize, &Data); + Data = NULL; + Status = CreateTimeBasedPayload (&DataSize, &Data); if (!EFI_ERROR (Status)) { Status = gRT->SetVariable (UserVariableNameNode->Name, &UserVariableNode->Guid, UserVariableNameNode->Attributes, DataSize, Data); FreePool (Data); } } else if ((UserVariableNameNode->Attributes & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS) != 0) { DataSize = 0; - Data = NULL; - Status = CreateCounterBasedPayload (&DataSize, &Data); + Data = NULL; + Status = CreateCounterBasedPayload (&DataSize, &Data); if (!EFI_ERROR (Status)) { Status = gRT->SetVariable (UserVariableNameNode->Name, &UserVariableNode->Guid, UserVariableNameNode->Attributes, DataSize, Data); FreePool (Data); @@ -535,6 +543,7 @@ DeleteUserVariable ( } else { Status = gRT->SetVariable (UserVariableNameNode->Name, &UserVariableNode->Guid, 0, 0, NULL); } + if (!EFI_ERROR (Status)) { UserVariableNameNode->Deleted = TRUE; } else { @@ -569,21 +578,21 @@ DeleteUserVariable ( EFI_STATUS EFIAPI VariableCleanupHiiExtractConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Request, - OUT EFI_STRING *Progress, - OUT EFI_STRING *Results + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Request, + OUT EFI_STRING *Progress, + OUT EFI_STRING *Results ) { - EFI_STATUS Status; - VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; - UINTN BufferSize; - EFI_STRING ConfigRequestHdr; - EFI_STRING ConfigRequest; - BOOLEAN AllocatedRequest; - UINTN Size; - - if (Progress == NULL || Results == NULL) { + EFI_STATUS Status; + VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; + UINTN BufferSize; + EFI_STRING ConfigRequestHdr; + EFI_STRING ConfigRequest; + BOOLEAN AllocatedRequest; + UINTN Size; + + if ((Progress == NULL) || (Results == NULL)) { return EFI_INVALID_PARAMETER; } @@ -601,7 +610,7 @@ VariableCleanupHiiExtractConfig ( // // Convert buffer data to by helper function BlockToConfig(). // - BufferSize = sizeof (VARIABLE_CLEANUP_DATA); + BufferSize = sizeof (VARIABLE_CLEANUP_DATA); ConfigRequest = Request; if ((Request == NULL) || (StrStr (Request, L"OFFSET") == NULL)) { // @@ -614,7 +623,7 @@ VariableCleanupHiiExtractConfig ( mVarStoreName, Private->DriverHandle ); - Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16); + Size = (StrLen (ConfigRequestHdr) + 32 + 1) * sizeof (CHAR16); ConfigRequest = AllocateZeroPool (Size); ASSERT (ConfigRequest != NULL); AllocatedRequest = TRUE; @@ -625,7 +634,7 @@ VariableCleanupHiiExtractConfig ( Status = Private->ConfigRouting->BlockToConfig ( Private->ConfigRouting, ConfigRequest, - (UINT8 *) &Private->VariableCleanupData, + (UINT8 *)&Private->VariableCleanupData, BufferSize, Results, Progress @@ -639,6 +648,7 @@ VariableCleanupHiiExtractConfig ( FreePool (ConfigRequest); ConfigRequest = NULL; } + // // Set Progress string to the original request string or the string's null terminator. // @@ -662,17 +672,17 @@ UpdateUserVariableForm ( IN VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private ) { - EFI_STRING_ID PromptStringToken; - EFI_STRING_ID HelpStringToken; - VOID *StartOpCodeHandle; - VOID *EndOpCodeHandle; - EFI_IFR_GUID_LABEL *StartLabel; - EFI_IFR_GUID_LABEL *EndLabel; - USER_VARIABLE_NODE *UserVariableNode; - LIST_ENTRY *Link; - USER_VARIABLE_NAME_NODE *UserVariableNameNode; - LIST_ENTRY *NameLink; - BOOLEAN Created; + EFI_STRING_ID PromptStringToken; + EFI_STRING_ID HelpStringToken; + VOID *StartOpCodeHandle; + VOID *EndOpCodeHandle; + EFI_IFR_GUID_LABEL *StartLabel; + EFI_IFR_GUID_LABEL *EndLabel; + USER_VARIABLE_NODE *UserVariableNode; + LIST_ENTRY *Link; + USER_VARIABLE_NAME_NODE *UserVariableNameNode; + LIST_ENTRY *NameLink; + BOOLEAN Created; // // Init OpCode Handle. @@ -686,16 +696,16 @@ UpdateUserVariableForm ( // // Create Hii Extend Label OpCode as the start opcode. // - StartLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + StartLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (StartOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); StartLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; - StartLabel->Number = LABEL_START; + StartLabel->Number = LABEL_START; // // Create Hii Extend Label OpCode as the end opcode. // - EndLabel = (EFI_IFR_GUID_LABEL *) HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); + EndLabel = (EFI_IFR_GUID_LABEL *)HiiCreateGuidOpCode (EndOpCodeHandle, &gEfiIfrTianoGuid, NULL, sizeof (EFI_IFR_GUID_LABEL)); EndLabel->ExtendOpCode = EFI_IFR_EXTEND_OP_LABEL; - EndLabel->Number = LABEL_END; + EndLabel->Number = LABEL_END; HiiUpdateForm ( Private->HiiHandle, @@ -706,8 +716,9 @@ UpdateUserVariableForm ( ); for (Link = mUserVariableList.ForwardLink - ;Link != &mUserVariableList - ;Link = Link->ForwardLink) { + ; Link != &mUserVariableList + ; Link = Link->ForwardLink) + { UserVariableNode = USER_VARIABLE_FROM_LINK (Link); // @@ -715,8 +726,9 @@ UpdateUserVariableForm ( // Created = FALSE; for (NameLink = UserVariableNode->NameLink.ForwardLink - ;NameLink != &UserVariableNode->NameLink - ;NameLink = NameLink->ForwardLink) { + ; NameLink != &UserVariableNode->NameLink + ; NameLink = NameLink->ForwardLink) + { UserVariableNameNode = USER_VARIABLE_NAME_FROM_LINK (NameLink); if (!UserVariableNameNode->Deleted) { @@ -733,12 +745,12 @@ UpdateUserVariableForm ( // Only create opcode for the non-deleted variables. // PromptStringToken = HiiSetString (Private->HiiHandle, 0, UserVariableNameNode->PromptString, NULL); - HelpStringToken = HiiSetString (Private->HiiHandle, 0, UserVariableNameNode->HelpString, NULL); + HelpStringToken = HiiSetString (Private->HiiHandle, 0, UserVariableNameNode->HelpString, NULL); HiiCreateCheckBoxOpCode ( StartOpCodeHandle, UserVariableNameNode->QuestionId, VARIABLE_CLEANUP_VARSTORE_ID, - (UINT16) (USER_VARIABLE_VAR_OFFSET + UserVariableNameNode->Index), + (UINT16)(USER_VARIABLE_VAR_OFFSET + UserVariableNameNode->Index), PromptStringToken, HelpStringToken, EFI_IFR_FLAG_CALLBACK, @@ -826,18 +838,19 @@ UpdateUserVariableForm ( EFI_STATUS EFIAPI VariableCleanupHiiRouteConfig ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN CONST EFI_STRING Configuration, - OUT EFI_STRING *Progress + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN CONST EFI_STRING Configuration, + OUT EFI_STRING *Progress ) { - EFI_STATUS Status; - VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; - UINTN BufferSize; + EFI_STATUS Status; + VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; + UINTN BufferSize; if (Progress == NULL) { return EFI_INVALID_PARAMETER; } + *Progress = Configuration; if (Configuration == NULL) { @@ -861,19 +874,19 @@ VariableCleanupHiiRouteConfig ( // Convert to buffer data by helper function ConfigToBlock(). // Status = Private->ConfigRouting->ConfigToBlock ( - Private->ConfigRouting, - Configuration, - (UINT8 *) &Private->VariableCleanupData, - &BufferSize, - Progress - ); + Private->ConfigRouting, + Configuration, + (UINT8 *)&Private->VariableCleanupData, + &BufferSize, + Progress + ); ASSERT_EFI_ERROR (Status); DeleteUserVariable (FALSE, &Private->VariableCleanupData); // // For "F10" hotkey to refresh the form. // -// UpdateUserVariableForm (Private); + // UpdateUserVariableForm (Private); return EFI_SUCCESS; } @@ -905,16 +918,16 @@ VariableCleanupHiiRouteConfig ( EFI_STATUS EFIAPI VariableCleanupHiiCallback ( - IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, - IN EFI_BROWSER_ACTION Action, - IN EFI_QUESTION_ID QuestionId, - IN UINT8 Type, - IN EFI_IFR_TYPE_VALUE *Value, - OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest + IN CONST EFI_HII_CONFIG_ACCESS_PROTOCOL *This, + IN EFI_BROWSER_ACTION Action, + IN EFI_QUESTION_ID QuestionId, + IN UINT8 Type, + IN EFI_IFR_TYPE_VALUE *Value, + OUT EFI_BROWSER_ACTION_REQUEST *ActionRequest ) { - VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; - VARIABLE_CLEANUP_DATA *VariableCleanupData; + VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; + VARIABLE_CLEANUP_DATA *VariableCleanupData; Private = VARIABLE_CLEANUP_HII_PRIVATE_FROM_THIS (This); @@ -929,7 +942,7 @@ VariableCleanupHiiCallback ( // Retrieve uncommitted data from Form Browser. // VariableCleanupData = &Private->VariableCleanupData; - HiiGetBrowserData (&mVariableCleanupHiiGuid, mVarStoreName, sizeof (VARIABLE_CLEANUP_DATA), (UINT8 *) VariableCleanupData); + HiiGetBrowserData (&mVariableCleanupHiiGuid, mVarStoreName, sizeof (VARIABLE_CLEANUP_DATA), (UINT8 *)VariableCleanupData); if (Action == EFI_BROWSER_ACTION_CHANGING) { if (Value == NULL) { return EFI_INVALID_PARAMETER; @@ -938,8 +951,9 @@ VariableCleanupHiiCallback ( if ((Value == NULL) || (ActionRequest == NULL)) { return EFI_INVALID_PARAMETER; } + if ((QuestionId >= USER_VARIABLE_QUESTION_ID) && (QuestionId < USER_VARIABLE_QUESTION_ID + MAX_USER_VARIABLE_COUNT)) { - if (Value->b){ + if (Value->b) { // // Means one user variable checkbox is marked to delete but not press F10 or "Commit Changes and Exit" menu. // @@ -964,7 +978,7 @@ VariableCleanupHiiCallback ( } else { switch (QuestionId) { case SELECT_ALL_QUESTION_ID: - if (Value->b){ + if (Value->b) { // // Means the SelectAll checkbox is marked to delete all user variables but not press F10 or "Commit Changes and Exit" menu. // @@ -977,6 +991,7 @@ VariableCleanupHiiCallback ( SetMem (VariableCleanupData->UserVariable, sizeof (VariableCleanupData->UserVariable), FALSE); mMarkedUserVariableCount = 0; } + break; case SAVE_AND_EXIT_QUESTION_ID: DeleteUserVariable (FALSE, VariableCleanupData); @@ -999,7 +1014,7 @@ VariableCleanupHiiCallback ( // // Pass changed uncommitted data back to Form Browser. // - HiiSetBrowserData (&mVariableCleanupHiiGuid, mVarStoreName, sizeof (VARIABLE_CLEANUP_DATA), (UINT8 *) VariableCleanupData, NULL); + HiiSetBrowserData (&mVariableCleanupHiiGuid, mVarStoreName, sizeof (VARIABLE_CLEANUP_DATA), (UINT8 *)VariableCleanupData, NULL); return EFI_SUCCESS; } @@ -1022,13 +1037,13 @@ VariableCleanupHiiCallback ( EFI_STATUS EFIAPI PlatformVarCleanup ( - IN VAR_ERROR_FLAG Flag, - IN VAR_CLEANUP_TYPE Type + IN VAR_ERROR_FLAG Flag, + IN VAR_CLEANUP_TYPE Type ) { - EFI_STATUS Status; - EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; - VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; + EFI_STATUS Status; + EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; + VARIABLE_CLEANUP_HII_PRIVATE_DATA *Private; if (!mEndOfDxe) { // @@ -1037,7 +1052,7 @@ PlatformVarCleanup ( return EFI_UNSUPPORTED; } - if ((Type >= VarCleanupMax) || ((Flag & ((VAR_ERROR_FLAG) (VAR_ERROR_FLAG_SYSTEM_ERROR & VAR_ERROR_FLAG_USER_ERROR))) == 0)) { + if ((Type >= VarCleanupMax) || ((Flag & ((VAR_ERROR_FLAG)(VAR_ERROR_FLAG_SYSTEM_ERROR & VAR_ERROR_FLAG_USER_ERROR))) == 0)) { return EFI_INVALID_PARAMETER; } @@ -1048,7 +1063,7 @@ PlatformVarCleanup ( return EFI_SUCCESS; } - if ((Flag & (~((VAR_ERROR_FLAG) VAR_ERROR_FLAG_SYSTEM_ERROR))) == 0) { + if ((Flag & (~((VAR_ERROR_FLAG)VAR_ERROR_FLAG_SYSTEM_ERROR))) == 0) { // // This sample does not support system variables cleanup. // @@ -1080,7 +1095,7 @@ PlatformVarCleanup ( // // Locate FormBrowser2 protocol. // - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &FormBrowser2); + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&FormBrowser2); if (EFI_ERROR (Status)) { return Status; } @@ -1090,7 +1105,7 @@ PlatformVarCleanup ( return EFI_OUT_OF_RESOURCES; } - Private->Signature = VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE; + Private->Signature = VARIABLE_CLEANUP_HII_PRIVATE_SIGNATURE; Private->ConfigAccess.ExtractConfig = VariableCleanupHiiExtractConfig; Private->ConfigAccess.RouteConfig = VariableCleanupHiiRouteConfig; Private->ConfigAccess.Callback = VariableCleanupHiiCallback; @@ -1098,7 +1113,7 @@ PlatformVarCleanup ( Status = gBS->LocateProtocol ( &gEfiHiiConfigRoutingProtocolGuid, NULL, - (VOID **) &Private->ConfigRouting + (VOID **)&Private->ConfigRouting ); if (EFI_ERROR (Status)) { goto Done; @@ -1163,6 +1178,7 @@ Done: NULL ); } + if (Private->HiiHandle != NULL) { HiiRemovePackages (Private->HiiHandle); } @@ -1225,11 +1241,11 @@ PlatformVarCleanupEndOfDxeEvent ( EFI_STATUS EFIAPI PlatformVarCleanupLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; mLastVarErrorFlag = InternalGetVarErrorFlag (); DEBUG ((DEBUG_INFO, "mLastVarErrorFlag - 0x%02x\n", mLastVarErrorFlag)); @@ -1262,11 +1278,11 @@ PlatformVarCleanupLibConstructor ( EFI_STATUS EFIAPI PlatformVarCleanupLibDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Close the End of DXE event. diff --git a/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c b/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c index bb151d0331..50131a431f 100644 --- a/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c +++ b/MdeModulePkg/Library/ResetUtilityLib/ResetUtility.c @@ -15,8 +15,8 @@ #pragma pack(1) typedef struct { - CHAR16 NullTerminator; - GUID ResetSubtype; + CHAR16 NullTerminator; + GUID ResetSubtype; } RESET_UTILITY_GUID_SPECIFIC_RESET_DATA; #pragma pack() @@ -45,8 +45,8 @@ STATIC_ASSERT ( VOID EFIAPI ResetSystemWithSubtype ( - IN EFI_RESET_TYPE ResetType, - IN CONST GUID *ResetSubtype + IN EFI_RESET_TYPE ResetType, + IN CONST GUID *ResetSubtype ) { RESET_UTILITY_GUID_SPECIFIC_RESET_DATA ResetData; @@ -79,7 +79,7 @@ ResetSystemWithSubtype ( VOID EFIAPI ResetPlatformSpecificGuid ( - IN CONST GUID *ResetSubtype + IN CONST GUID *ResetSubtype ) { ResetSystemWithSubtype (EfiResetPlatformSpecific, ResetSubtype); @@ -110,8 +110,8 @@ GetResetPlatformSpecificGuid ( IN CONST VOID *ResetData ) { - UINTN ResetDataStringSize; - GUID *ResetSubtypeGuid; + UINTN ResetDataStringSize; + GUID *ResetSubtypeGuid; // // Make sure parameters are valid @@ -130,11 +130,12 @@ GetResetPlatformSpecificGuid ( // Now, assuming that we have enough data for a GUID after the string, the // GUID should be immediately after the string itself. // - if ((ResetDataStringSize < DataSize) && (DataSize - ResetDataStringSize) >= sizeof (GUID)) { + if ((ResetDataStringSize < DataSize) && ((DataSize - ResetDataStringSize) >= sizeof (GUID))) { ResetSubtypeGuid = (GUID *)((UINT8 *)ResetData + ResetDataStringSize); DEBUG ((DEBUG_VERBOSE, "%a - Detected reset subtype %g...\n", __FUNCTION__, ResetSubtypeGuid)); return ResetSubtypeGuid; } + return NULL; } @@ -174,12 +175,12 @@ GetResetPlatformSpecificGuid ( RETURN_STATUS EFIAPI BuildResetData ( - IN OUT UINTN *ResetDataSize, - IN OUT VOID *ResetData, - IN CONST GUID *ResetSubtype OPTIONAL, - IN CONST CHAR16 *ResetString OPTIONAL, - IN UINTN ExtraDataSize OPTIONAL, - IN CONST VOID *ExtraData OPTIONAL + IN OUT UINTN *ResetDataSize, + IN OUT VOID *ResetData, + IN CONST GUID *ResetSubtype OPTIONAL, + IN CONST CHAR16 *ResetString OPTIONAL, + IN UINTN ExtraDataSize OPTIONAL, + IN CONST VOID *ExtraData OPTIONAL ) { UINTN ResetStringSize; @@ -192,16 +193,18 @@ BuildResetData ( if (ResetDataSize == NULL) { return RETURN_INVALID_PARAMETER; } + // // If extra data is indicated, but pointer is NULL. // - if (ExtraDataSize > 0 && ExtraData == NULL) { + if ((ExtraDataSize > 0) && (ExtraData == NULL)) { return RETURN_INVALID_PARAMETER; } + // // If extra data is indicated, but no subtype GUID is supplied. // - if (ResetSubtype == NULL && ExtraDataSize > 0) { + if ((ResetSubtype == NULL) && (ExtraDataSize > 0)) { return RETURN_INVALID_PARAMETER; } @@ -229,6 +232,7 @@ BuildResetData ( *ResetDataSize = ResetDataBufferSize; return RETURN_BUFFER_TOO_SMALL; } + *ResetDataSize = ResetDataBufferSize; if (ResetData == NULL) { return RETURN_INVALID_PARAMETER; @@ -244,6 +248,7 @@ BuildResetData ( CopyMem (Data, ResetSubtype, sizeof (GUID)); Data += sizeof (GUID); } + if (ExtraDataSize > 0) { CopyMem (Data, ExtraData, ExtraDataSize); } diff --git a/MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/ReportStatusCodeLib.c b/MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/ReportStatusCodeLib.c index dc7fcf7a2d..fdda288d33 100644 --- a/MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/ReportStatusCodeLib.c +++ b/MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/ReportStatusCodeLib.c @@ -21,7 +21,6 @@ #include #include - // // Define the maximum extended data size that is supported when a status code is reported. // @@ -56,8 +55,8 @@ InternalGetReportStatusCode ( // // Check gBS just in case ReportStatusCode is called before gBS is initialized. // - if (gBS != NULL && gBS->LocateProtocol != NULL) { - Status = gBS->LocateProtocol (&gEfiStatusCodeRuntimeProtocolGuid, NULL, (VOID**) &mReportStatusCodeLibStatusCodeProtocol); + if ((gBS != NULL) && (gBS->LocateProtocol != NULL)) { + Status = gBS->LocateProtocol (&gEfiStatusCodeRuntimeProtocolGuid, NULL, (VOID **)&mReportStatusCodeLibStatusCodeProtocol); if (EFI_ERROR (Status)) { mReportStatusCodeLibStatusCodeProtocol = NULL; } @@ -74,14 +73,15 @@ InternalGetReportStatusCode ( VOID EFIAPI ReportStatusCodeLibVirtualAddressChange ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { if (mReportStatusCodeLibStatusCodeProtocol == NULL) { return; } - EfiConvertPointer (0, (VOID **) &mReportStatusCodeLibStatusCodeProtocol); + + EfiConvertPointer (0, (VOID **)&mReportStatusCodeLibStatusCodeProtocol); } /** @@ -94,8 +94,8 @@ ReportStatusCodeLibVirtualAddressChange ( VOID EFIAPI ReportStatusCodeLibExitBootServices ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { // @@ -121,8 +121,8 @@ ReportStatusCodeLibExitBootServices ( EFI_STATUS EFIAPI ReportStatusCodeLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; @@ -217,16 +217,17 @@ ReportStatusCodeLibDestructor ( **/ EFI_STATUS InternalReportStatusCode ( - IN EFI_STATUS_CODE_TYPE Type, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE Type, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ) { - if ((ReportProgressCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - (ReportErrorCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) || - (ReportDebugCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE)) { + if ((ReportProgressCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE)) || + (ReportErrorCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) || + (ReportDebugCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE))) + { // // If mReportStatusCodeLibStatusCodeProtocol is NULL, then check if Report Status Code Protocol is available in system. // @@ -244,7 +245,6 @@ InternalReportStatusCode ( return EFI_UNSUPPORTED; } - /** Converts a status code to an 8-bit POST code value. @@ -283,15 +283,16 @@ CodeTypeToPostCode ( // Convert Value to an 8 bit post code // if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) ) { - *PostCode = (UINT8) ((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | - (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); + ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) + { + *PostCode = (UINT8)((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | + (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); return TRUE; } + return FALSE; } - /** Extracts ASSERT() information from a status code structure. @@ -345,17 +346,18 @@ ReportStatusCodeExtractAssertInfo ( if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) && ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) && - ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) { + ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) + { AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1); *Filename = (CHAR8 *)(AssertData + 1); *Description = *Filename + AsciiStrLen (*Filename) + 1; *LineNumber = AssertData->LineNumber; return TRUE; } + return FALSE; } - /** Extracts DEBUG() information from a status code structure. @@ -424,13 +426,12 @@ ReportStatusCodeExtractDebugInfo ( // 64-bit aligned is a must, otherwise retrieving 64-bit parameter from BASE_LIST will // cause unalignment exception. // - *Marker = (BASE_LIST) (DebugInfo + 1); + *Marker = (BASE_LIST)(DebugInfo + 1); *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12); return TRUE; } - /** Reports a status code. @@ -462,7 +463,6 @@ ReportStatusCode ( return InternalReportStatusCode (Type, Value, 0, &gEfiCallerIdGuid, NULL); } - /** Reports a status code with a Device Path Protocol as the extended data. @@ -508,7 +508,6 @@ ReportStatusCodeWithDevicePath ( ); } - /** Reports a status code with an extended data buffer. @@ -564,7 +563,6 @@ ReportStatusCodeWithExtendedData ( ); } - /** Reports a status code with full parameters. @@ -630,13 +628,13 @@ ReportStatusCodeEx ( // // Use Buffer instead of allocating if possible. // - StatusCodeData = (EFI_STATUS_CODE_DATA *) StatusCodeBuffer; + StatusCodeData = (EFI_STATUS_CODE_DATA *)StatusCodeBuffer; } else { if (mHaveExitedBootServices) { return EFI_OUT_OF_RESOURCES; } - if (gBS == NULL || gBS->AllocatePool == NULL || gBS->FreePool == NULL) { + if ((gBS == NULL) || (gBS->AllocatePool == NULL) || (gBS->FreePool == NULL)) { return EFI_UNSUPPORTED; } @@ -653,11 +651,12 @@ ReportStatusCodeEx ( // // Fill in the extended data header // - StatusCodeData->HeaderSize = (UINT16) sizeof (EFI_STATUS_CODE_DATA); - StatusCodeData->Size = (UINT16) ExtendedDataSize; + StatusCodeData->HeaderSize = (UINT16)sizeof (EFI_STATUS_CODE_DATA); + StatusCodeData->Size = (UINT16)ExtendedDataSize; if (ExtendedDataGuid == NULL) { ExtendedDataGuid = &gEfiStatusCodeSpecificDataGuid; } + CopyGuid (&StatusCodeData->Type, ExtendedDataGuid); // @@ -673,19 +672,19 @@ ReportStatusCodeEx ( if (CallerId == NULL) { CallerId = &gEfiCallerIdGuid; } + Status = InternalReportStatusCode (Type, Value, Instance, CallerId, StatusCodeData); // // Free the allocated buffer // - if (StatusCodeData != (EFI_STATUS_CODE_DATA *) StatusCodeBuffer) { + if (StatusCodeData != (EFI_STATUS_CODE_DATA *)StatusCodeBuffer) { gBS->FreePool (StatusCodeData); } return Status; } - /** Returns TRUE if status codes of type EFI_PROGRESS_CODE are enabled @@ -704,10 +703,9 @@ ReportProgressCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_ERROR_CODE are enabled @@ -726,10 +724,9 @@ ReportErrorCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_DEBUG_CODE are enabled @@ -748,5 +745,5 @@ ReportDebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); } diff --git a/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c b/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c index f4490180cc..59b5c2b9d8 100644 --- a/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c +++ b/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c @@ -12,8 +12,8 @@ #include #include -EFI_EVENT mRuntimeResetSystemLibVirtualAddressChangeEvent; -EFI_RUNTIME_SERVICES *mInternalRT; +EFI_EVENT mRuntimeResetSystemLibVirtualAddressChangeEvent; +EFI_RUNTIME_SERVICES *mInternalRT; /** This function causes a system-wide reset (cold reset), in which @@ -76,8 +76,8 @@ ResetShutdown ( VOID EFIAPI ResetPlatformSpecific ( - IN UINTN DataSize, - IN VOID *ResetData + IN UINTN DataSize, + IN VOID *ResetData ) { mInternalRT->ResetSystem (EfiResetPlatformSpecific, EFI_SUCCESS, DataSize, ResetData); @@ -98,10 +98,10 @@ ResetPlatformSpecific ( VOID EFIAPI ResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL ) { mInternalRT->ResetSystem (ResetType, ResetStatus, DataSize, ResetData); @@ -117,11 +117,11 @@ ResetSystem ( VOID EFIAPI RuntimeResetSystemLibVirtualAddressChange ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - mInternalRT->ConvertPointer (0, (VOID **) &mInternalRT); + mInternalRT->ConvertPointer (0, (VOID **)&mInternalRT); } /** @@ -139,8 +139,8 @@ RuntimeResetSystemLibVirtualAddressChange ( EFI_STATUS EFIAPI RuntimeResetSystemLibConstruct ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; @@ -181,8 +181,8 @@ RuntimeResetSystemLibConstruct ( EFI_STATUS EFIAPI RuntimeResetSystemLibDeconstruct ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; diff --git a/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLib.c b/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLib.c index 7cdf5d0b79..3efe56e056 100644 --- a/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLib.c +++ b/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLib.c @@ -21,14 +21,13 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include "SmmCorePerformanceLibInternal.h" -#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) -#define FIRMWARE_RECORD_BUFFER 0x1000 -#define CACHE_HANDLE_GUID_COUNT 0x100 +#define STRING_SIZE (FPDT_STRING_EVENT_RECORD_NAME_LENGTH * sizeof (CHAR8)) +#define FIRMWARE_RECORD_BUFFER 0x1000 +#define CACHE_HANDLE_GUID_COUNT 0x100 -SMM_BOOT_PERFORMANCE_TABLE *mSmmBootPerformanceTable = NULL; +SMM_BOOT_PERFORMANCE_TABLE *mSmmBootPerformanceTable = NULL; typedef struct { EFI_HANDLE Handle; @@ -36,24 +35,24 @@ typedef struct { EFI_GUID ModuleGuid; } HANDLE_GUID_MAP; -HANDLE_GUID_MAP mCacheHandleGuidTable[CACHE_HANDLE_GUID_COUNT]; -UINTN mCachePairCount = 0; +HANDLE_GUID_MAP mCacheHandleGuidTable[CACHE_HANDLE_GUID_COUNT]; +UINTN mCachePairCount = 0; -UINT32 mPerformanceLength = sizeof (SMM_BOOT_PERFORMANCE_TABLE); -UINT32 mMaxPerformanceLength = 0; -UINT32 mLoadImageCount = 0; -BOOLEAN mFpdtDataIsReported = FALSE; -BOOLEAN mLackSpaceIsReport = FALSE; -CHAR8 *mPlatformLanguage = NULL; -SPIN_LOCK mSmmFpdtLock; +UINT32 mPerformanceLength = sizeof (SMM_BOOT_PERFORMANCE_TABLE); +UINT32 mMaxPerformanceLength = 0; +UINT32 mLoadImageCount = 0; +BOOLEAN mFpdtDataIsReported = FALSE; +BOOLEAN mLackSpaceIsReport = FALSE; +CHAR8 *mPlatformLanguage = NULL; +SPIN_LOCK mSmmFpdtLock; PERFORMANCE_PROPERTY mPerformanceProperty; -UINT32 mCachedLength = 0; -UINT32 mBootRecordSize = 0; +UINT32 mCachedLength = 0; +UINT32 mBootRecordSize = 0; // // Interfaces for SMM PerformanceMeasurement Protocol. // -EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL mPerformanceMeasurementInterface = { +EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL mPerformanceMeasurementInterface = { CreatePerformanceMeasurement, }; @@ -68,9 +67,9 @@ EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL mPerformanceMeasurementInterface = { **/ EFI_STATUS GetFpdtRecordPtr ( - IN UINT8 RecordSize, - IN OUT FPDT_RECORD_PTR *FpdtRecordPtr -) + IN UINT8 RecordSize, + IN OUT FPDT_RECORD_PTR *FpdtRecordPtr + ) { if (mFpdtDataIsReported) { // @@ -81,12 +80,13 @@ GetFpdtRecordPtr ( DEBUG ((DEBUG_INFO, "SmmCorePerformanceLib: No enough space to save boot records\n")); mLackSpaceIsReport = TRUE; } + return EFI_OUT_OF_RESOURCES; } else { // // Covert buffer to FPDT Ptr Union type. // - FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8*)mSmmBootPerformanceTable + mSmmBootPerformanceTable->Header.Length); + FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8 *)mSmmBootPerformanceTable + mSmmBootPerformanceTable->Header.Length); } } else { // @@ -97,24 +97,26 @@ GetFpdtRecordPtr ( mPerformanceLength, mPerformanceLength + RecordSize + FIRMWARE_RECORD_BUFFER, mSmmBootPerformanceTable - ); + ); if (mSmmBootPerformanceTable == NULL) { return EFI_OUT_OF_RESOURCES; } + mSmmBootPerformanceTable->Header.Length = mPerformanceLength; - mMaxPerformanceLength = mPerformanceLength + RecordSize + FIRMWARE_RECORD_BUFFER; + mMaxPerformanceLength = mPerformanceLength + RecordSize + FIRMWARE_RECORD_BUFFER; } + // // Covert buffer to FPDT Ptr Union type. // - FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8*)mSmmBootPerformanceTable + mSmmBootPerformanceTable->Header.Length); + FpdtRecordPtr->RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8 *)mSmmBootPerformanceTable + mSmmBootPerformanceTable->Header.Length); } + FpdtRecordPtr->RecordHeader->Length = 0; return EFI_SUCCESS; } - /** Check whether the Token is a known one which is uesed by core. @@ -133,16 +135,17 @@ IsKnownTokens ( return FALSE; } - if (AsciiStrCmp (Token, SEC_TOK) == 0 || - AsciiStrCmp (Token, PEI_TOK) == 0 || - AsciiStrCmp (Token, DXE_TOK) == 0 || - AsciiStrCmp (Token, BDS_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0 || - AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0 || - AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, START_IMAGE_TOK) == 0 || - AsciiStrCmp (Token, PEIM_TOK) == 0) { + if ((AsciiStrCmp (Token, SEC_TOK) == 0) || + (AsciiStrCmp (Token, PEI_TOK) == 0) || + (AsciiStrCmp (Token, DXE_TOK) == 0) || + (AsciiStrCmp (Token, BDS_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_START_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_SUPPORT_TOK) == 0) || + (AsciiStrCmp (Token, DRIVERBINDING_STOP_TOK) == 0) || + (AsciiStrCmp (Token, LOAD_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, START_IMAGE_TOK) == 0) || + (AsciiStrCmp (Token, PEIM_TOK) == 0)) + { return TRUE; } else { return FALSE; @@ -160,19 +163,20 @@ Check whether the ID is a known one which map to the known Token. **/ BOOLEAN IsKnownID ( - IN UINT32 Identifier + IN UINT32 Identifier ) { - if (Identifier == MODULE_START_ID || - Identifier == MODULE_END_ID || - Identifier == MODULE_LOADIMAGE_START_ID || - Identifier == MODULE_LOADIMAGE_END_ID || - Identifier == MODULE_DB_START_ID || - Identifier == MODULE_DB_END_ID || - Identifier == MODULE_DB_SUPPORT_START_ID || - Identifier == MODULE_DB_SUPPORT_END_ID || - Identifier == MODULE_DB_STOP_START_ID || - Identifier == MODULE_DB_STOP_END_ID) { + if ((Identifier == MODULE_START_ID) || + (Identifier == MODULE_END_ID) || + (Identifier == MODULE_LOADIMAGE_START_ID) || + (Identifier == MODULE_LOADIMAGE_END_ID) || + (Identifier == MODULE_DB_START_ID) || + (Identifier == MODULE_DB_END_ID) || + (Identifier == MODULE_DB_SUPPORT_START_ID) || + (Identifier == MODULE_DB_SUPPORT_END_ID) || + (Identifier == MODULE_DB_STOP_START_ID) || + (Identifier == MODULE_DB_STOP_END_ID)) + { return TRUE; } else { return FALSE; @@ -205,34 +209,39 @@ GetFpdtRecordId ( // Token to Id. // if (String != NULL) { - if (AsciiStrCmp (String, START_IMAGE_TOK) == 0) { // "StartImage:" + if (AsciiStrCmp (String, START_IMAGE_TOK) == 0) { + // "StartImage:" if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_START_ID; + *ProgressID = MODULE_START_ID; } else { - *ProgressID = MODULE_END_ID; + *ProgressID = MODULE_END_ID; } - } else if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { // "LoadImage:" + } else if (AsciiStrCmp (String, LOAD_IMAGE_TOK) == 0) { + // "LoadImage:" if (Attribute == PerfStartEntry) { - *ProgressID = MODULE_LOADIMAGE_START_ID; + *ProgressID = MODULE_LOADIMAGE_START_ID; } else { - *ProgressID = MODULE_LOADIMAGE_END_ID; + *ProgressID = MODULE_LOADIMAGE_END_ID; } - } else { // Pref used in Modules + } else { + // Pref used in Modules if (Attribute == PerfStartEntry) { - *ProgressID = PERF_INMODULE_START_ID; + *ProgressID = PERF_INMODULE_START_ID; } else { - *ProgressID = PERF_INMODULE_END_ID; + *ProgressID = PERF_INMODULE_END_ID; } } - } else if (Handle != NULL) { // Pref used in Modules + } else if (Handle != NULL) { + // Pref used in Modules if (Attribute == PerfStartEntry) { - *ProgressID = PERF_INMODULE_START_ID; + *ProgressID = PERF_INMODULE_START_ID; } else { - *ProgressID = PERF_INMODULE_END_ID; + *ProgressID = PERF_INMODULE_END_ID; } } else { return EFI_UNSUPPORTED; } + return EFI_SUCCESS; } @@ -253,26 +262,26 @@ GetFpdtRecordId ( EFI_STATUS EFIAPI GetModuleInfoFromHandle ( - IN EFI_HANDLE Handle, - OUT CHAR8 *NameString, - IN UINTN BufferSize, - OUT EFI_GUID *ModuleGuid OPTIONAL + IN EFI_HANDLE Handle, + OUT CHAR8 *NameString, + IN UINTN BufferSize, + OUT EFI_GUID *ModuleGuid OPTIONAL ) { - EFI_STATUS Status; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; - CHAR8 *PdbFileName; - EFI_GUID *TempGuid; - UINTN StartIndex; - UINTN Index; - INTN Count; - BOOLEAN ModuleGuidIsGet; - UINTN StringSize; - CHAR16 *StringPtr; - MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvFilePath; - - if (NameString == NULL || BufferSize == 0) { + EFI_STATUS Status; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; + CHAR8 *PdbFileName; + EFI_GUID *TempGuid; + UINTN StartIndex; + UINTN Index; + INTN Count; + BOOLEAN ModuleGuidIsGet; + UINTN StringSize; + CHAR16 *StringPtr; + MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvFilePath; + + if ((NameString == NULL) || (BufferSize == 0)) { return EFI_INVALID_PARAMETER; } @@ -289,14 +298,14 @@ GetModuleInfoFromHandle ( } } - Status = EFI_INVALID_PARAMETER; + Status = EFI_INVALID_PARAMETER; LoadedImage = NULL; ModuleGuidIsGet = FALSE; // // Initialize GUID as zero value. // - TempGuid = &gZeroGuid; + TempGuid = &gZeroGuid; // // Initialize it as "" string. // @@ -307,49 +316,50 @@ GetModuleInfoFromHandle ( // Try Handle as ImageHandle. // Status = gBS->HandleProtocol ( - Handle, - &gEfiLoadedImageProtocolGuid, - (VOID**) &LoadedImage - ); + Handle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&LoadedImage + ); if (EFI_ERROR (Status)) { // // Try Handle as Controller Handle // Status = gBS->OpenProtocol ( - Handle, - &gEfiDriverBindingProtocolGuid, - (VOID **) &DriverBinding, - NULL, - NULL, - EFI_OPEN_PROTOCOL_GET_PROTOCOL - ); + Handle, + &gEfiDriverBindingProtocolGuid, + (VOID **)&DriverBinding, + NULL, + NULL, + EFI_OPEN_PROTOCOL_GET_PROTOCOL + ); if (!EFI_ERROR (Status)) { // // Get Image protocol from ImageHandle // Status = gBS->HandleProtocol ( - DriverBinding->ImageHandle, - &gEfiLoadedImageProtocolGuid, - (VOID**) &LoadedImage - ); + DriverBinding->ImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID **)&LoadedImage + ); } } } - if (!EFI_ERROR (Status) && LoadedImage != NULL) { + if (!EFI_ERROR (Status) && (LoadedImage != NULL)) { // // Get Module Guid from DevicePath. // - if (LoadedImage->FilePath != NULL && - LoadedImage->FilePath->Type == MEDIA_DEVICE_PATH && - LoadedImage->FilePath->SubType == MEDIA_PIWG_FW_FILE_DP - ) { + if ((LoadedImage->FilePath != NULL) && + (LoadedImage->FilePath->Type == MEDIA_DEVICE_PATH) && + (LoadedImage->FilePath->SubType == MEDIA_PIWG_FW_FILE_DP) + ) + { // // Determine GUID associated with module logging performance // ModuleGuidIsGet = TRUE; - FvFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LoadedImage->FilePath; + FvFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)LoadedImage->FilePath; TempGuid = &FvFilePath->FvFileName; } @@ -357,20 +367,21 @@ GetModuleInfoFromHandle ( // Method 1 Get Module Name from PDB string. // PdbFileName = PeCoffLoaderGetPdbPointer (LoadedImage->ImageBase); - if (PdbFileName != NULL && BufferSize > 0) { + if ((PdbFileName != NULL) && (BufferSize > 0)) { StartIndex = 0; for (Index = 0; PdbFileName[Index] != 0; Index++) { if ((PdbFileName[Index] == '\\') || (PdbFileName[Index] == '/')) { StartIndex = Index + 1; } } + // // Copy the PDB file name to our temporary string. // If the length is bigger than BufferSize, trim the redudant characters to avoid overflow in array boundary. // for (Index = 0; Index < BufferSize - 1; Index++) { NameString[Index] = PdbFileName[Index + StartIndex]; - if (NameString[Index] == 0 || NameString[Index] == '.') { + if ((NameString[Index] == 0) || (NameString[Index] == '.')) { NameString[Index] = 0; break; } @@ -379,6 +390,7 @@ GetModuleInfoFromHandle ( if (Index == BufferSize - 1) { NameString[Index] = 0; } + // // Module Name is got. // @@ -392,21 +404,22 @@ GetModuleInfoFromHandle ( // StringPtr = NULL; StringSize = 0; - Status = GetSectionFromAnyFv ( - TempGuid, - EFI_SECTION_USER_INTERFACE, - 0, - (VOID **) &StringPtr, - &StringSize - ); + Status = GetSectionFromAnyFv ( + TempGuid, + EFI_SECTION_USER_INTERFACE, + 0, + (VOID **)&StringPtr, + &StringSize + ); if (!EFI_ERROR (Status)) { // // Method 3. Get the name string from FFS UI section // for (Index = 0; Index < BufferSize - 1 && StringPtr[Index] != 0; Index++) { - NameString[Index] = (CHAR8) StringPtr[Index]; + NameString[Index] = (CHAR8)StringPtr[Index]; } + NameString[Index] = 0; FreePool (StringPtr); } @@ -418,9 +431,9 @@ Done: // if (ModuleGuid != NULL) { CopyGuid (ModuleGuid, TempGuid); - if (IsZeroGuid(TempGuid) && (Handle != NULL) && !ModuleGuidIsGet) { - // Handle is GUID - CopyGuid (ModuleGuid, (EFI_GUID *) Handle); + if (IsZeroGuid (TempGuid) && (Handle != NULL) && !ModuleGuidIsGet) { + // Handle is GUID + CopyGuid (ModuleGuid, (EFI_GUID *)Handle); } } @@ -431,7 +444,7 @@ Done: mCacheHandleGuidTable[mCachePairCount].Handle = Handle; CopyGuid (&mCacheHandleGuidTable[mCachePairCount].ModuleGuid, ModuleGuid); AsciiStrCpyS (mCacheHandleGuidTable[mCachePairCount].NameString, FPDT_STRING_EVENT_RECORD_NAME_LENGTH, NameString); - mCachePairCount ++; + mCachePairCount++; } return Status; @@ -448,9 +461,9 @@ Done: **/ VOID CopyStringIntoPerfRecordAndUpdateLength ( - IN OUT CHAR8 *Destination, + IN OUT CHAR8 *Destination, IN CONST CHAR8 *Source, - IN OUT UINT8 *Length + IN OUT UINT8 *Length ) { UINTN StringLen; @@ -466,12 +479,13 @@ CopyStringIntoPerfRecordAndUpdateLength ( DestMax = STRING_SIZE; } } + StringLen = AsciiStrLen (Source); if (StringLen >= DestMax) { StringLen = DestMax -1; } - AsciiStrnCpyS(Destination, DestMax, Source, StringLen); + AsciiStrnCpyS (Destination, DestMax, Source, StringLen); *Length += (UINT8)DestMax; return; @@ -513,18 +527,18 @@ InsertFpdtRecord ( ) { - EFI_STATUS Status; - EFI_GUID ModuleGuid; - CHAR8 ModuleName[FPDT_STRING_EVENT_RECORD_NAME_LENGTH]; - FPDT_RECORD_PTR FpdtRecordPtr; - FPDT_RECORD_PTR CachedFpdtRecordPtr; - UINT64 TimeStamp; - CONST CHAR8 *StringPtr; - UINTN DestMax; - UINTN StringLen; - UINT16 ProgressId; - - StringPtr = NULL; + EFI_STATUS Status; + EFI_GUID ModuleGuid; + CHAR8 ModuleName[FPDT_STRING_EVENT_RECORD_NAME_LENGTH]; + FPDT_RECORD_PTR FpdtRecordPtr; + FPDT_RECORD_PTR CachedFpdtRecordPtr; + UINT64 TimeStamp; + CONST CHAR8 *StringPtr; + UINTN DestMax; + UINTN StringLen; + UINT16 ProgressId; + + StringPtr = NULL; ZeroMem (ModuleName, sizeof (ModuleName)); // @@ -550,6 +564,7 @@ InsertFpdtRecord ( PerfId += 1; } } + if (PerfId == 0) { // // Get ProgressID form the String Token. @@ -558,6 +573,7 @@ InsertFpdtRecord ( if (EFI_ERROR (Status)) { return Status; } + PerfId = ProgressId; } } @@ -586,134 +602,147 @@ InsertFpdtRecord ( // 4. Fill in the FPDT record according to different Performance Identifier. // switch (PerfId) { - case MODULE_START_ID: - case MODULE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - // - // Cache the offset of start image start record and use to update the start image end record if needed. - // - if (PerfId == MODULE_START_ID && Attribute == PerfEntry) { - mCachedLength = mSmmBootPerformanceTable->Header.Length; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; - FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); - FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); - if (CallerIdentifier == NULL && PerfId == MODULE_END_ID && mCachedLength != 0) { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8*)mSmmBootPerformanceTable + mCachedLength); - CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &CachedFpdtRecordPtr.GuidEvent->Guid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); - mCachedLength = 0; - } - } - break; - - case MODULE_LOADIMAGE_START_ID: - case MODULE_LOADIMAGE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - StringPtr = ModuleName; - if (PerfId == MODULE_LOADIMAGE_START_ID) { - mLoadImageCount++; + case MODULE_START_ID: + case MODULE_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + StringPtr = ModuleName; // - // Cache the offset of load image start record and use to be updated by the load image end record if needed. + // Cache the offset of start image start record and use to update the start image end record if needed. // - if (CallerIdentifier == NULL && Attribute == PerfEntry) { + if ((PerfId == MODULE_START_ID) && (Attribute == PerfEntry)) { mCachedLength = mSmmBootPerformanceTable->Header.Length; } - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; - FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); - FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; - FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; - FpdtRecordPtr.GuidQwordEvent->Qword = mLoadImageCount; - CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); - if (PerfId == MODULE_LOADIMAGE_END_ID && mCachedLength != 0) { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8*)mSmmBootPerformanceTable + mCachedLength); - CopyMem (&CachedFpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.GuidQwordEvent->Guid)); - mCachedLength = 0; + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidEvent->Header.Type = FPDT_GUID_EVENT_TYPE; + FpdtRecordPtr.GuidEvent->Header.Length = sizeof (FPDT_GUID_EVENT_RECORD); + FpdtRecordPtr.GuidEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); + if ((CallerIdentifier == NULL) && (PerfId == MODULE_END_ID) && (mCachedLength != 0)) { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8 *)mSmmBootPerformanceTable + mCachedLength); + CopyMem (&FpdtRecordPtr.GuidEvent->Guid, &CachedFpdtRecordPtr.GuidEvent->Guid, sizeof (FpdtRecordPtr.GuidEvent->Guid)); + mCachedLength = 0; + } } - } - break; - case PERF_EVENTSIGNAL_START_ID: - case PERF_EVENTSIGNAL_END_ID: - case PERF_CALLBACK_START_ID: - case PERF_CALLBACK_END_ID: - if (String == NULL || Guid == NULL) { - return EFI_INVALID_PARAMETER; - } - StringPtr = String; - if (AsciiStrLen (String) == 0) { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; - FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); - FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, CallerIdentifier, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); - CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); - } - break; - - case PERF_EVENT_ID: - case PERF_FUNCTION_START_ID: - case PERF_FUNCTION_END_ID: - case PERF_INMODULE_START_ID: - case PERF_INMODULE_END_ID: - case PERF_CROSSMODULE_START_ID: - case PERF_CROSSMODULE_END_ID: - GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); - if (String != NULL) { - StringPtr = String; - } else { + break; + + case MODULE_LOADIMAGE_START_ID: + case MODULE_LOADIMAGE_END_ID: + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); StringPtr = ModuleName; - } - if (AsciiStrLen (StringPtr) == 0) { - StringPtr = "unknown name"; - } - if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; - CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); - CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); - } - break; + if (PerfId == MODULE_LOADIMAGE_START_ID) { + mLoadImageCount++; + // + // Cache the offset of load image start record and use to be updated by the load image end record if needed. + // + if ((CallerIdentifier == NULL) && (Attribute == PerfEntry)) { + mCachedLength = mSmmBootPerformanceTable->Header.Length; + } + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.GuidQwordEvent->Header.Type = FPDT_GUID_QWORD_EVENT_TYPE; + FpdtRecordPtr.GuidQwordEvent->Header.Length = sizeof (FPDT_GUID_QWORD_EVENT_RECORD); + FpdtRecordPtr.GuidQwordEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.GuidQwordEvent->ProgressID = PerfId; + FpdtRecordPtr.GuidQwordEvent->Timestamp = TimeStamp; + FpdtRecordPtr.GuidQwordEvent->Qword = mLoadImageCount; + CopyMem (&FpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.GuidQwordEvent->Guid)); + if ((PerfId == MODULE_LOADIMAGE_END_ID) && (mCachedLength != 0)) { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8 *)mSmmBootPerformanceTable + mCachedLength); + CopyMem (&CachedFpdtRecordPtr.GuidQwordEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.GuidQwordEvent->Guid)); + mCachedLength = 0; + } + } + + break; + + case PERF_EVENTSIGNAL_START_ID: + case PERF_EVENTSIGNAL_END_ID: + case PERF_CALLBACK_START_ID: + case PERF_CALLBACK_END_ID: + if ((String == NULL) || (Guid == NULL)) { + return EFI_INVALID_PARAMETER; + } + + StringPtr = String; + if (AsciiStrLen (String) == 0) { + StringPtr = "unknown name"; + } - default: - if (Attribute != PerfEntry) { + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DualGuidStringEvent->Header.Type = FPDT_DUAL_GUID_STRING_EVENT_TYPE; + FpdtRecordPtr.DualGuidStringEvent->Header.Length = sizeof (FPDT_DUAL_GUID_STRING_EVENT_RECORD); + FpdtRecordPtr.DualGuidStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DualGuidStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DualGuidStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid1, CallerIdentifier, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid1)); + CopyMem (&FpdtRecordPtr.DualGuidStringEvent->Guid2, Guid, sizeof (FpdtRecordPtr.DualGuidStringEvent->Guid2)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DualGuidStringEvent->String, StringPtr, &FpdtRecordPtr.DualGuidStringEvent->Header.Length); + } + + break; + + case PERF_EVENT_ID: + case PERF_FUNCTION_START_ID: + case PERF_FUNCTION_END_ID: + case PERF_INMODULE_START_ID: + case PERF_INMODULE_END_ID: + case PERF_CROSSMODULE_START_ID: + case PERF_CROSSMODULE_END_ID: GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); if (String != NULL) { StringPtr = String; } else { StringPtr = ModuleName; } + if (AsciiStrLen (StringPtr) == 0) { StringPtr = "unknown name"; } + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); } - } else { - return EFI_INVALID_PARAMETER; - } - break; + + break; + + default: + if (Attribute != PerfEntry) { + GetModuleInfoFromHandle ((EFI_HANDLE)CallerIdentifier, ModuleName, sizeof (ModuleName), &ModuleGuid); + if (String != NULL) { + StringPtr = String; + } else { + StringPtr = ModuleName; + } + + if (AsciiStrLen (StringPtr) == 0) { + StringPtr = "unknown name"; + } + + if (!PcdGetBool (PcdEdkiiFpdtStringRecordEnableOnly)) { + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); + } + } else { + return EFI_INVALID_PARAMETER; + } + + break; } // @@ -723,11 +752,12 @@ InsertFpdtRecord ( if (StringPtr == NULL) { return EFI_INVALID_PARAMETER; } - FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; - FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); - FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; - FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; - FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; + + FpdtRecordPtr.DynamicStringEvent->Header.Type = FPDT_DYNAMIC_STRING_EVENT_TYPE; + FpdtRecordPtr.DynamicStringEvent->Header.Length = sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + FpdtRecordPtr.DynamicStringEvent->Header.Revision = FPDT_RECORD_REVISION_1; + FpdtRecordPtr.DynamicStringEvent->ProgressID = PerfId; + FpdtRecordPtr.DynamicStringEvent->Timestamp = TimeStamp; if (Guid != NULL) { // // Cache the event guid in string event record. @@ -736,33 +766,39 @@ InsertFpdtRecord ( } else { CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (FpdtRecordPtr.DynamicStringEvent->Guid)); } + if (AsciiStrLen (StringPtr) == 0) { StringPtr = "unknown name"; } + CopyStringIntoPerfRecordAndUpdateLength (FpdtRecordPtr.DynamicStringEvent->String, StringPtr, &FpdtRecordPtr.DynamicStringEvent->Header.Length); if ((PerfId == MODULE_LOADIMAGE_START_ID) || (PerfId == MODULE_END_ID)) { FpdtRecordPtr.DynamicStringEvent->Header.Length = (UINT8)(sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD)+ STRING_SIZE); } - if ((PerfId == MODULE_LOADIMAGE_END_ID || PerfId == MODULE_END_ID) && mCachedLength != 0) { - CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8*)mSmmBootPerformanceTable + mCachedLength); + + if (((PerfId == MODULE_LOADIMAGE_END_ID) || (PerfId == MODULE_END_ID)) && (mCachedLength != 0)) { + CachedFpdtRecordPtr.RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *)((UINT8 *)mSmmBootPerformanceTable + mCachedLength); if (PerfId == MODULE_LOADIMAGE_END_ID) { - DestMax = CachedFpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + DestMax = CachedFpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); StringLen = AsciiStrLen (StringPtr); if (StringLen >= DestMax) { StringLen = DestMax -1; } + CopyMem (&CachedFpdtRecordPtr.DynamicStringEvent->Guid, &ModuleGuid, sizeof (CachedFpdtRecordPtr.DynamicStringEvent->Guid)); AsciiStrnCpyS (CachedFpdtRecordPtr.DynamicStringEvent->String, DestMax, StringPtr, StringLen); } else if (PerfId == MODULE_END_ID) { - DestMax = FpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); + DestMax = FpdtRecordPtr.DynamicStringEvent->Header.Length - sizeof (FPDT_DYNAMIC_STRING_EVENT_RECORD); StringLen = AsciiStrLen (CachedFpdtRecordPtr.DynamicStringEvent->String); if (StringLen >= DestMax) { StringLen = DestMax -1; } + CopyMem (&FpdtRecordPtr.DynamicStringEvent->Guid, &CachedFpdtRecordPtr.DynamicStringEvent->Guid, sizeof (CachedFpdtRecordPtr.DynamicStringEvent->Guid)); AsciiStrnCpyS (FpdtRecordPtr.DynamicStringEvent->String, DestMax, CachedFpdtRecordPtr.DynamicStringEvent->String, StringLen); } + mCachedLength = 0; } } @@ -770,7 +806,7 @@ InsertFpdtRecord ( // // 5. Update the length of the used buffer after fill in the record. // - mPerformanceLength += FpdtRecordPtr.RecordHeader->Length; + mPerformanceLength += FpdtRecordPtr.RecordHeader->Length; mSmmBootPerformanceTable->Header.Length += FpdtRecordPtr.RecordHeader->Length; return EFI_SUCCESS; @@ -803,10 +839,10 @@ InsertFpdtRecord ( EFI_STATUS EFIAPI FpdtSmiHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *RegisterContext, - IN OUT VOID *CommBuffer, - IN OUT UINTN *CommBufferSize + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *RegisterContext, + IN OUT VOID *CommBuffer, + IN OUT UINTN *CommBufferSize ) { EFI_STATUS Status; @@ -820,13 +856,13 @@ FpdtSmiHandler ( // // If input is invalid, stop processing this SMI // - if (CommBuffer == NULL || CommBufferSize == NULL) { + if ((CommBuffer == NULL) || (CommBufferSize == NULL)) { return EFI_SUCCESS; } TempCommBufferSize = *CommBufferSize; - if(TempCommBufferSize < sizeof (SMM_BOOT_RECORD_COMMUNICATE)) { + if (TempCommBufferSize < sizeof (SMM_BOOT_RECORD_COMMUNICATE)) { return EFI_SUCCESS; } @@ -835,27 +871,28 @@ FpdtSmiHandler ( return EFI_SUCCESS; } - SmmCommData = (SMM_BOOT_RECORD_COMMUNICATE*)CommBuffer; + SmmCommData = (SMM_BOOT_RECORD_COMMUNICATE *)CommBuffer; Status = EFI_SUCCESS; switch (SmmCommData->Function) { - case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_SIZE : + case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_SIZE: if (mSmmBootPerformanceTable != NULL) { mBootRecordSize = mSmmBootPerformanceTable->Header.Length - sizeof (SMM_BOOT_PERFORMANCE_TABLE); } + SmmCommData->BootRecordSize = mBootRecordSize; break; - case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA : + case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA: Status = EFI_UNSUPPORTED; break; - case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET : + case SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET: BootRecordOffset = SmmCommData->BootRecordOffset; BootRecordData = SmmCommData->BootRecordData; BootRecordSize = SmmCommData->BootRecordSize; - if (BootRecordData == NULL || BootRecordOffset >= mBootRecordSize) { + if ((BootRecordData == NULL) || (BootRecordOffset >= mBootRecordSize)) { Status = EFI_INVALID_PARAMETER; break; } @@ -866,15 +903,17 @@ FpdtSmiHandler ( if (BootRecordSize > mBootRecordSize - BootRecordOffset) { BootRecordSize = mBootRecordSize - BootRecordOffset; } + SmmCommData->BootRecordSize = BootRecordSize; if (!SmmIsBufferOutsideSmmValid ((UINTN)BootRecordData, BootRecordSize)) { DEBUG ((DEBUG_ERROR, "FpdtSmiHandler: MM Data buffer in MMRAM or overflow!\n")); Status = EFI_ACCESS_DENIED; break; } - BootRecordBuffer = ((UINT8 *) (mSmmBootPerformanceTable)) + sizeof (SMM_BOOT_PERFORMANCE_TABLE); + + BootRecordBuffer = ((UINT8 *)(mSmmBootPerformanceTable)) + sizeof (SMM_BOOT_PERFORMANCE_TABLE); CopyMem ( - (UINT8*)BootRecordData, + (UINT8 *)BootRecordData, BootRecordBuffer + BootRecordOffset, BootRecordSize ); @@ -901,14 +940,14 @@ FpdtSmiHandler ( VOID EFIAPI InitializeSmmCorePerformanceLib ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - EFI_HANDLE Handle; - EFI_HANDLE SmiHandle; - EFI_STATUS Status; - PERFORMANCE_PROPERTY *PerformanceProperty; + EFI_HANDLE Handle; + EFI_HANDLE SmiHandle; + EFI_STATUS Status; + PERFORMANCE_PROPERTY *PerformanceProperty; // // Initialize spin lock @@ -931,10 +970,10 @@ InitializeSmmCorePerformanceLib ( // Register SMI handler. // SmiHandle = NULL; - Status = gSmst->SmiHandlerRegister (FpdtSmiHandler, &gEfiFirmwarePerformanceGuid, &SmiHandle); + Status = gSmst->SmiHandlerRegister (FpdtSmiHandler, &gEfiFirmwarePerformanceGuid, &SmiHandle); ASSERT_EFI_ERROR (Status); - Status = EfiGetSystemConfigurationTable (&gPerformanceProtocolGuid, (VOID **) &PerformanceProperty); + Status = EfiGetSystemConfigurationTable (&gPerformanceProtocolGuid, (VOID **)&PerformanceProperty); if (EFI_ERROR (Status)) { // // Install configuration table for performance property. @@ -1025,7 +1064,7 @@ SmmCorePerformanceLibConstructor ( **/ EFI_STATUS EFIAPI -CreatePerformanceMeasurement( +CreatePerformanceMeasurement ( IN CONST VOID *CallerIdentifier OPTIONAL, IN CONST VOID *Guid OPTIONAL, IN CONST CHAR8 *String OPTIONAL, @@ -1035,7 +1074,7 @@ CreatePerformanceMeasurement( IN PERF_MEASUREMENT_ATTRIBUTE Attribute ) { - EFI_STATUS Status; + EFI_STATUS Status; Status = EFI_SUCCESS; @@ -1080,7 +1119,7 @@ StartPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -1129,7 +1168,7 @@ EndPerformanceMeasurementEx ( IN UINT32 Identifier ) { - CONST CHAR8 *String; + CONST CHAR8 *String; if (Token != NULL) { String = Token; @@ -1188,13 +1227,13 @@ EndPerformanceMeasurementEx ( UINTN EFIAPI GetPerformanceMeasurementEx ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp, - OUT UINT32 *Identifier + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp, + OUT UINT32 *Identifier ) { return 0; @@ -1315,12 +1354,12 @@ EndPerformanceMeasurement ( UINTN EFIAPI GetPerformanceMeasurement ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp ) { return 0; @@ -1344,7 +1383,7 @@ PerformanceMeasurementEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8(PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); } /** @@ -1390,14 +1429,15 @@ LogPerformanceMeasurement ( BOOLEAN EFIAPI LogPerformanceMeasurementEnabled ( - IN CONST UINTN Type + IN CONST UINTN Type ) { // // When Performance measurement is enabled and the type is not filtered, the performance can be logged. // - if (PerformanceMeasurementEnabled () && (PcdGet8(PcdPerformanceLibraryPropertyMask) & Type) == 0) { + if (PerformanceMeasurementEnabled () && ((PcdGet8 (PcdPerformanceLibraryPropertyMask) & Type) == 0)) { return TRUE; } + return FALSE; } diff --git a/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLibInternal.h b/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLibInternal.h index c6963d2ebe..62b496484c 100644 --- a/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLibInternal.h +++ b/MdeModulePkg/Library/SmmCorePerformanceLib/SmmCorePerformanceLibInternal.h @@ -12,7 +12,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SMM_CORE_PERFORMANCE_LIB_INTERNAL_H_ #define _SMM_CORE_PERFORMANCE_LIB_INTERNAL_H_ - #include #include #include @@ -43,6 +42,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Interface declarations for SMM PerformanceMeasurement Protocol. // + /** Create performance record with event description and a timestamp. @@ -63,7 +63,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ EFI_STATUS EFIAPI -CreatePerformanceMeasurement( +CreatePerformanceMeasurement ( IN CONST VOID *CallerIdentifier OPTIONAL, IN CONST VOID *Guid OPTIONAL, IN CONST CHAR8 *String OPTIONAL, diff --git a/MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.c b/MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.c index 8046b0fa5a..9396a5fe8a 100644 --- a/MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.c +++ b/MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.c @@ -26,7 +26,6 @@ PlatformHookBeforeSmmDispatch ( return EFI_SUCCESS; } - /** Performs platform specific tasks after invoking registered SMI handlers. diff --git a/MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.c b/MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.c index e06944d833..607126aa0b 100644 --- a/MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.c +++ b/MdeModulePkg/Library/SmmIpmiLibSmmIpmiProtocol/SmmIpmiLibSmmIpmiProtocol.c @@ -12,7 +12,7 @@ #include #include -IPMI_PROTOCOL *mIpmiProtocol = NULL; +IPMI_PROTOCOL *mIpmiProtocol = NULL; /** This service enables submitting commands via Ipmi. @@ -35,22 +35,22 @@ IPMI_PROTOCOL *mIpmiProtocol = NULL; EFI_STATUS EFIAPI IpmiSubmitCommand ( - IN UINT8 NetFunction, - IN UINT8 Command, - IN UINT8 *RequestData, - IN UINT32 RequestDataSize, - OUT UINT8 *ResponseData, - IN OUT UINT32 *ResponseDataSize + IN UINT8 NetFunction, + IN UINT8 Command, + IN UINT8 *RequestData, + IN UINT32 RequestDataSize, + OUT UINT8 *ResponseData, + IN OUT UINT32 *ResponseDataSize ) { EFI_STATUS Status; if (mIpmiProtocol == NULL) { Status = gSmst->SmmLocateProtocol ( - &gSmmIpmiProtocolGuid, - NULL, - (VOID **) &mIpmiProtocol - ); + &gSmmIpmiProtocolGuid, + NULL, + (VOID **)&mIpmiProtocol + ); if (EFI_ERROR (Status)) { // // Smm Ipmi Protocol is not installed. So, IPMI device is not present. @@ -72,5 +72,6 @@ IpmiSubmitCommand ( if (EFI_ERROR (Status)) { return Status; } + return EFI_SUCCESS; } diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.c b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.c index 3740b9863e..78a9b86af4 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.c +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.c @@ -34,7 +34,7 @@ LockBoxGetSmmCommProtocol ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; // // If the protocol has been got previously, return it. @@ -51,6 +51,7 @@ LockBoxGetSmmCommProtocol ( if (EFI_ERROR (Status)) { mLockBoxSmmCommProtocol = NULL; } + return mLockBoxSmmCommProtocol; } @@ -65,12 +66,12 @@ LockBoxGetSmmCommBuffer ( VOID ) { - EFI_STATUS Status; - UINTN MinimalSizeNeeded; - EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; - UINT32 Index; - EFI_MEMORY_DESCRIPTOR *Entry; - UINTN Size; + EFI_STATUS Status; + UINTN MinimalSizeNeeded; + EDKII_PI_SMM_COMMUNICATION_REGION_TABLE *PiSmmCommunicationRegionTable; + UINT32 Index; + EFI_MEMORY_DESCRIPTOR *Entry; + UINTN Size; // // If the buffer has been got previously, return it. @@ -81,37 +82,49 @@ LockBoxGetSmmCommBuffer ( MinimalSizeNeeded = sizeof (EFI_GUID) + sizeof (UINTN) + - MAX (sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SAVE), - MAX (sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES), - MAX (sizeof (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE), - MAX (sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE), - sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE))))); + MAX ( + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SAVE), + MAX ( + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES), + MAX ( + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE), + MAX ( + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE), + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE) + ) + ) + ) + ); Status = EfiGetSystemConfigurationTable ( &gEdkiiPiSmmCommunicationRegionTableGuid, - (VOID **) &PiSmmCommunicationRegionTable + (VOID **)&PiSmmCommunicationRegionTable ); if (EFI_ERROR (Status)) { mLockBoxSmmCommBuffer = NULL; return mLockBoxSmmCommBuffer; } + ASSERT (PiSmmCommunicationRegionTable != NULL); - Entry = (EFI_MEMORY_DESCRIPTOR *) (PiSmmCommunicationRegionTable + 1); - Size = 0; + Entry = (EFI_MEMORY_DESCRIPTOR *)(PiSmmCommunicationRegionTable + 1); + Size = 0; for (Index = 0; Index < PiSmmCommunicationRegionTable->NumberOfEntries; Index++) { if (Entry->Type == EfiConventionalMemory) { - Size = EFI_PAGES_TO_SIZE ((UINTN) Entry->NumberOfPages); + Size = EFI_PAGES_TO_SIZE ((UINTN)Entry->NumberOfPages); if (Size >= MinimalSizeNeeded) { break; } } - Entry = (EFI_MEMORY_DESCRIPTOR *) ((UINT8 *) Entry + PiSmmCommunicationRegionTable->DescriptorSize); + + Entry = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)Entry + PiSmmCommunicationRegionTable->DescriptorSize); } + if (Index >= PiSmmCommunicationRegionTable->NumberOfEntries) { mLockBoxSmmCommBuffer = NULL; } else { - mLockBoxSmmCommBuffer = (UINT8 *) (UINTN) Entry->PhysicalStart; + mLockBoxSmmCommBuffer = (UINT8 *)(UINTN)Entry->PhysicalStart; } + return mLockBoxSmmCommBuffer; } @@ -133,18 +146,18 @@ LockBoxGetSmmCommBuffer ( RETURN_STATUS EFIAPI SaveLockBox ( - IN GUID *Guid, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN VOID *Buffer, + IN UINTN Length ) { - EFI_STATUS Status; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - EFI_SMM_LOCK_BOX_PARAMETER_SAVE *LockBoxParameterSave; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_SAVE)]; - UINT8 *CommBuffer; - UINTN CommSize; + EFI_STATUS Status; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + EFI_SMM_LOCK_BOX_PARAMETER_SAVE *LockBoxParameterSave; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 TempCommBuffer[sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SAVE)]; + UINT8 *CommBuffer; + UINTN CommSize; DEBUG ((DEBUG_INFO, "SmmLockBoxDxeLib SaveLockBox - Enter\n")); @@ -167,27 +180,28 @@ SaveLockBox ( if (CommBuffer == NULL) { CommBuffer = &TempCommBuffer[0]; } + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - CommHeader->MessageLength = sizeof(*LockBoxParameterSave); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + CommHeader->MessageLength = sizeof (*LockBoxParameterSave); - LockBoxParameterSave = (EFI_SMM_LOCK_BOX_PARAMETER_SAVE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; - LockBoxParameterSave->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_SAVE; - LockBoxParameterSave->Header.DataLength = sizeof(*LockBoxParameterSave); + LockBoxParameterSave = (EFI_SMM_LOCK_BOX_PARAMETER_SAVE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + LockBoxParameterSave->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_SAVE; + LockBoxParameterSave->Header.DataLength = sizeof (*LockBoxParameterSave); LockBoxParameterSave->Header.ReturnStatus = (UINT64)-1; - CopyMem (&LockBoxParameterSave->Guid, Guid, sizeof(*Guid)); - LockBoxParameterSave->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; - LockBoxParameterSave->Length = (UINT64)Length; + CopyMem (&LockBoxParameterSave->Guid, Guid, sizeof (*Guid)); + LockBoxParameterSave->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; + LockBoxParameterSave->Length = (UINT64)Length; // // Send command // - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_SAVE); - Status = SmmCommunication->Communicate ( - SmmCommunication, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SAVE); + Status = SmmCommunication->Communicate ( + SmmCommunication, + &CommBuffer[0], + &CommSize + ); ASSERT_EFI_ERROR (Status); Status = (EFI_STATUS)LockBoxParameterSave->Header.ReturnStatus; @@ -216,17 +230,17 @@ SaveLockBox ( RETURN_STATUS EFIAPI SetLockBoxAttributes ( - IN GUID *Guid, - IN UINT64 Attributes + IN GUID *Guid, + IN UINT64 Attributes ) { - EFI_STATUS Status; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES *LockBoxParameterSetAttributes; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES)]; - UINT8 *CommBuffer; - UINTN CommSize; + EFI_STATUS Status; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES *LockBoxParameterSetAttributes; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 TempCommBuffer[sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES)]; + UINT8 *CommBuffer; + UINTN CommSize; DEBUG ((DEBUG_INFO, "SmmLockBoxDxeLib SetLockBoxAttributes - Enter\n")); @@ -234,7 +248,8 @@ SetLockBoxAttributes ( // Basic check // if ((Guid == NULL) || - ((Attributes & ~(LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE | LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY)) != 0)) { + ((Attributes & ~(LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE | LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY)) != 0)) + { return EFI_INVALID_PARAMETER; } @@ -250,26 +265,27 @@ SetLockBoxAttributes ( if (CommBuffer == NULL) { CommBuffer = &TempCommBuffer[0]; } + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - CommHeader->MessageLength = sizeof(*LockBoxParameterSetAttributes); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + CommHeader->MessageLength = sizeof (*LockBoxParameterSetAttributes); - LockBoxParameterSetAttributes = (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; - LockBoxParameterSetAttributes->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_SET_ATTRIBUTES; - LockBoxParameterSetAttributes->Header.DataLength = sizeof(*LockBoxParameterSetAttributes); + LockBoxParameterSetAttributes = (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + LockBoxParameterSetAttributes->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_SET_ATTRIBUTES; + LockBoxParameterSetAttributes->Header.DataLength = sizeof (*LockBoxParameterSetAttributes); LockBoxParameterSetAttributes->Header.ReturnStatus = (UINT64)-1; - CopyMem (&LockBoxParameterSetAttributes->Guid, Guid, sizeof(*Guid)); + CopyMem (&LockBoxParameterSetAttributes->Guid, Guid, sizeof (*Guid)); LockBoxParameterSetAttributes->Attributes = (UINT64)Attributes; // // Send command // - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES); - Status = SmmCommunication->Communicate ( - SmmCommunication, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_SET_ATTRIBUTES); + Status = SmmCommunication->Communicate ( + SmmCommunication, + &CommBuffer[0], + &CommSize + ); ASSERT_EFI_ERROR (Status); Status = (EFI_STATUS)LockBoxParameterSetAttributes->Header.ReturnStatus; @@ -304,19 +320,19 @@ SetLockBoxAttributes ( RETURN_STATUS EFIAPI UpdateLockBox ( - IN GUID *Guid, - IN UINTN Offset, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN UINTN Offset, + IN VOID *Buffer, + IN UINTN Length ) { - EFI_STATUS Status; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - EFI_SMM_LOCK_BOX_PARAMETER_UPDATE *LockBoxParameterUpdate; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_UPDATE)]; - UINT8 *CommBuffer; - UINTN CommSize; + EFI_STATUS Status; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + EFI_SMM_LOCK_BOX_PARAMETER_UPDATE *LockBoxParameterUpdate; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 TempCommBuffer[sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE)]; + UINT8 *CommBuffer; + UINTN CommSize; DEBUG ((DEBUG_INFO, "SmmLockBoxDxeLib UpdateLockBox - Enter\n")); @@ -339,15 +355,16 @@ UpdateLockBox ( if (CommBuffer == NULL) { CommBuffer = &TempCommBuffer[0]; } + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - CommHeader->MessageLength = sizeof(*LockBoxParameterUpdate); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + CommHeader->MessageLength = sizeof (*LockBoxParameterUpdate); - LockBoxParameterUpdate = (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE *)(UINTN)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; - LockBoxParameterUpdate->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_UPDATE; - LockBoxParameterUpdate->Header.DataLength = sizeof(*LockBoxParameterUpdate); + LockBoxParameterUpdate = (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE *)(UINTN)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + LockBoxParameterUpdate->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_UPDATE; + LockBoxParameterUpdate->Header.DataLength = sizeof (*LockBoxParameterUpdate); LockBoxParameterUpdate->Header.ReturnStatus = (UINT64)-1; - CopyMem (&LockBoxParameterUpdate->Guid, Guid, sizeof(*Guid)); + CopyMem (&LockBoxParameterUpdate->Guid, Guid, sizeof (*Guid)); LockBoxParameterUpdate->Offset = (UINT64)Offset; LockBoxParameterUpdate->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; LockBoxParameterUpdate->Length = (UINT64)Length; @@ -355,12 +372,12 @@ UpdateLockBox ( // // Send command // - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_UPDATE); - Status = SmmCommunication->Communicate ( - SmmCommunication, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_UPDATE); + Status = SmmCommunication->Communicate ( + SmmCommunication, + &CommBuffer[0], + &CommSize + ); ASSERT_EFI_ERROR (Status); Status = (EFI_STATUS)LockBoxParameterUpdate->Header.ReturnStatus; @@ -394,18 +411,18 @@ UpdateLockBox ( RETURN_STATUS EFIAPI RestoreLockBox ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ) { - EFI_STATUS Status; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *LockBoxParameterRestore; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE)]; - UINT8 *CommBuffer; - UINTN CommSize; + EFI_STATUS Status; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *LockBoxParameterRestore; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 TempCommBuffer[sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE)]; + UINT8 *CommBuffer; + UINTN CommSize; DEBUG ((DEBUG_INFO, "SmmLockBoxDxeLib RestoreLockBox - Enter\n")); @@ -414,7 +431,8 @@ RestoreLockBox ( // if ((Guid == NULL) || ((Buffer == NULL) && (Length != NULL)) || - ((Buffer != NULL) && (Length == NULL))) { + ((Buffer != NULL) && (Length == NULL))) + { return EFI_INVALID_PARAMETER; } @@ -430,15 +448,16 @@ RestoreLockBox ( if (CommBuffer == NULL) { CommBuffer = &TempCommBuffer[0]; } + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - CommHeader->MessageLength = sizeof(*LockBoxParameterRestore); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + CommHeader->MessageLength = sizeof (*LockBoxParameterRestore); - LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; - LockBoxParameterRestore->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE; - LockBoxParameterRestore->Header.DataLength = sizeof(*LockBoxParameterRestore); + LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + LockBoxParameterRestore->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE; + LockBoxParameterRestore->Header.DataLength = sizeof (*LockBoxParameterRestore); LockBoxParameterRestore->Header.ReturnStatus = (UINT64)-1; - CopyMem (&LockBoxParameterRestore->Guid, Guid, sizeof(*Guid)); + CopyMem (&LockBoxParameterRestore->Guid, Guid, sizeof (*Guid)); LockBoxParameterRestore->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; if (Length != NULL) { LockBoxParameterRestore->Length = (EFI_PHYSICAL_ADDRESS)*Length; @@ -449,12 +468,12 @@ RestoreLockBox ( // // Send command // - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE); - Status = SmmCommunication->Communicate ( - SmmCommunication, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE); + Status = SmmCommunication->Communicate ( + SmmCommunication, + &CommBuffer[0], + &CommSize + ); ASSERT_EFI_ERROR (Status); if (Length != NULL) { @@ -484,13 +503,13 @@ RestoreAllLockBoxInPlace ( VOID ) { - EFI_STATUS Status; - EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; - EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *LockBoxParameterRestoreAllInPlace; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 TempCommBuffer[sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE)]; - UINT8 *CommBuffer; - UINTN CommSize; + EFI_STATUS Status; + EFI_SMM_COMMUNICATION_PROTOCOL *SmmCommunication; + EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *LockBoxParameterRestoreAllInPlace; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 TempCommBuffer[sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE)]; + UINT8 *CommBuffer; + UINTN CommSize; DEBUG ((DEBUG_INFO, "SmmLockBoxDxeLib RestoreAllLockBoxInPlace - Enter\n")); @@ -506,24 +525,25 @@ RestoreAllLockBoxInPlace ( if (CommBuffer == NULL) { CommBuffer = &TempCommBuffer[0]; } + CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - CommHeader->MessageLength = sizeof(*LockBoxParameterRestoreAllInPlace); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + CommHeader->MessageLength = sizeof (*LockBoxParameterRestoreAllInPlace); - LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; - LockBoxParameterRestoreAllInPlace->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE; - LockBoxParameterRestoreAllInPlace->Header.DataLength = sizeof(*LockBoxParameterRestoreAllInPlace); + LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)]; + LockBoxParameterRestoreAllInPlace->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE; + LockBoxParameterRestoreAllInPlace->Header.DataLength = sizeof (*LockBoxParameterRestoreAllInPlace); LockBoxParameterRestoreAllInPlace->Header.ReturnStatus = (UINT64)-1; // // Send command // - CommSize = sizeof(EFI_GUID) + sizeof(UINTN) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE); - Status = SmmCommunication->Communicate ( - SmmCommunication, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (EFI_GUID) + sizeof (UINTN) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE); + Status = SmmCommunication->Communicate ( + SmmCommunication, + &CommBuffer[0], + &CommSize + ); ASSERT_EFI_ERROR (Status); Status = (EFI_STATUS)LockBoxParameterRestoreAllInPlace->Header.ReturnStatus; diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxLibPrivate.h b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxLibPrivate.h index 449333e94b..583be6b6ed 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxLibPrivate.h +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxLibPrivate.h @@ -17,28 +17,28 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Below data structure is used for lockbox registration in SMST // -#define SMM_LOCK_BOX_SIGNATURE_32 SIGNATURE_64 ('L','O','C','K','B','_','3','2') -#define SMM_LOCK_BOX_SIGNATURE_64 SIGNATURE_64 ('L','O','C','K','B','_','6','4') +#define SMM_LOCK_BOX_SIGNATURE_32 SIGNATURE_64 ('L','O','C','K','B','_','3','2') +#define SMM_LOCK_BOX_SIGNATURE_64 SIGNATURE_64 ('L','O','C','K','B','_','6','4') typedef struct { - UINT64 Signature; - EFI_PHYSICAL_ADDRESS LockBoxDataAddress; + UINT64 Signature; + EFI_PHYSICAL_ADDRESS LockBoxDataAddress; } SMM_LOCK_BOX_CONTEXT; // // Below data structure is used for lockbox management // -#define SMM_LOCK_BOX_DATA_SIGNATURE SIGNATURE_64 ('L','O','C','K','B','O','X','D') +#define SMM_LOCK_BOX_DATA_SIGNATURE SIGNATURE_64 ('L','O','C','K','B','O','X','D') typedef struct { - UINT64 Signature; - EFI_GUID Guid; - EFI_PHYSICAL_ADDRESS Buffer; - UINT64 Length; - UINT64 Attributes; - EFI_PHYSICAL_ADDRESS SmramBuffer; - LIST_ENTRY Link; + UINT64 Signature; + EFI_GUID Guid; + EFI_PHYSICAL_ADDRESS Buffer; + UINT64 Length; + UINT64 Attributes; + EFI_PHYSICAL_ADDRESS SmramBuffer; + LIST_ENTRY Link; } SMM_LOCK_BOX_DATA; #pragma pack() @@ -69,4 +69,3 @@ SmmLockBoxMmDestructor ( ); #endif - diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxMmLib.c b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxMmLib.c index 7f7ab10427..ab2cb7a2b4 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxMmLib.c +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxMmLib.c @@ -24,15 +24,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent We need handle this library carefully. Only one library instance will construct the environment. Below 2 global variable can only be used in constructor. They should NOT be used in any other library functions. **/ -SMM_LOCK_BOX_CONTEXT mSmmLockBoxContext; -LIST_ENTRY mLockBoxQueue = INITIALIZE_LIST_HEAD_VARIABLE (mLockBoxQueue); +SMM_LOCK_BOX_CONTEXT mSmmLockBoxContext; +LIST_ENTRY mLockBoxQueue = INITIALIZE_LIST_HEAD_VARIABLE (mLockBoxQueue); -BOOLEAN mSmmConfigurationTableInstalled = FALSE; -VOID *mSmmLockBoxRegistrationSmmEndOfDxe = NULL; -VOID *mSmmLockBoxRegistrationSmmReadyToLock = NULL; -VOID *mSmmLockBoxRegistrationEndOfS3Resume = NULL; -BOOLEAN mSmmLockBoxSmmReadyToLock = FALSE; -BOOLEAN mSmmLockBoxDuringS3Resume = FALSE; +BOOLEAN mSmmConfigurationTableInstalled = FALSE; +VOID *mSmmLockBoxRegistrationSmmEndOfDxe = NULL; +VOID *mSmmLockBoxRegistrationSmmReadyToLock = NULL; +VOID *mSmmLockBoxRegistrationEndOfS3Resume = NULL; +BOOLEAN mSmmLockBoxSmmReadyToLock = FALSE; +BOOLEAN mSmmLockBoxDuringS3Resume = FALSE; /** This function return SmmLockBox context from SMST. @@ -44,7 +44,7 @@ InternalGetSmmLockBoxContext ( VOID ) { - UINTN Index; + UINTN Index; // // Check if gEfiSmmLockBoxCommunicationGuid is installed by someone @@ -107,10 +107,10 @@ SmmLockBoxSmmReadyToLockNotify ( EFI_STATUS EFIAPI SmmLockBoxS3EntryCallBack ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *Context OPTIONAL, - IN OUT VOID *CommBuffer OPTIONAL, - IN OUT UINTN *CommBufferSize OPTIONAL + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *Context OPTIONAL, + IN OUT VOID *CommBuffer OPTIONAL, + IN OUT UINTN *CommBufferSize OPTIONAL ) { mSmmLockBoxDuringS3Resume = TRUE; @@ -134,10 +134,10 @@ SmmLockBoxSmmEndOfDxeNotify ( IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_SMM_SX_DISPATCH2_PROTOCOL *SxDispatch; - EFI_SMM_SX_REGISTER_CONTEXT EntryRegisterContext; - EFI_HANDLE S3EntryHandle; + EFI_STATUS Status; + EFI_SMM_SX_DISPATCH2_PROTOCOL *SxDispatch; + EFI_SMM_SX_REGISTER_CONTEXT EntryRegisterContext; + EFI_HANDLE S3EntryHandle; // // Locate SmmSxDispatch2 protocol. @@ -154,12 +154,12 @@ SmmLockBoxSmmEndOfDxeNotify ( // EntryRegisterContext.Type = SxS3; EntryRegisterContext.Phase = SxEntry; - Status = SxDispatch->Register ( - SxDispatch, - SmmLockBoxS3EntryCallBack, - &EntryRegisterContext, - &S3EntryHandle - ); + Status = SxDispatch->Register ( + SxDispatch, + SmmLockBoxS3EntryCallBack, + &EntryRegisterContext, + &S3EntryHandle + ); ASSERT_EFI_ERROR (Status); } @@ -199,8 +199,8 @@ SmmLockBoxMmConstructor ( VOID ) { - EFI_STATUS Status; - SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; + EFI_STATUS Status; + SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SmmLockBoxMmConstructor - Enter\n")); @@ -251,18 +251,19 @@ SmmLockBoxMmConstructor ( // // If no one install this, it means this is first instance. Install it. // - if (sizeof(UINTN) == sizeof(UINT64)) { + if (sizeof (UINTN) == sizeof (UINT64)) { mSmmLockBoxContext.Signature = SMM_LOCK_BOX_SIGNATURE_64; } else { mSmmLockBoxContext.Signature = SMM_LOCK_BOX_SIGNATURE_32; } + mSmmLockBoxContext.LockBoxDataAddress = (EFI_PHYSICAL_ADDRESS)(UINTN)&mLockBoxQueue; Status = gMmst->MmInstallConfigurationTable ( gMmst, &gEfiSmmLockBoxCommunicationGuid, &mSmmLockBoxContext, - sizeof(mSmmLockBoxContext) + sizeof (mSmmLockBoxContext) ); ASSERT_EFI_ERROR (Status); mSmmConfigurationTableInstalled = TRUE; @@ -287,7 +288,7 @@ SmmLockBoxMmDestructor ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SmmLockBoxMmDestructor in %a module\n", gEfiCallerBaseName)); @@ -313,6 +314,7 @@ SmmLockBoxMmDestructor ( ); ASSERT_EFI_ERROR (Status); } + if (mSmmLockBoxRegistrationSmmEndOfDxe != NULL) { // // Unregister SmmEndOfDxe notification. @@ -324,6 +326,7 @@ SmmLockBoxMmDestructor ( ); ASSERT_EFI_ERROR (Status); } + if (mSmmLockBoxRegistrationEndOfS3Resume != NULL) { // // Unregister EndOfS3Resume notification. @@ -349,13 +352,14 @@ InternalGetLockBoxQueue ( VOID ) { - SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; + SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; SmmLockBoxContext = InternalGetSmmLockBoxContext (); ASSERT (SmmLockBoxContext != NULL); if (SmmLockBoxContext == NULL) { return NULL; } + return (LIST_ENTRY *)(UINTN)SmmLockBoxContext->LockBoxDataAddress; } @@ -368,19 +372,20 @@ InternalGetLockBoxQueue ( **/ SMM_LOCK_BOX_DATA * InternalFindLockBoxByGuid ( - IN EFI_GUID *Guid + IN EFI_GUID *Guid ) { - LIST_ENTRY *Link; - SMM_LOCK_BOX_DATA *LockBox; - LIST_ENTRY *LockBoxQueue; + LIST_ENTRY *Link; + SMM_LOCK_BOX_DATA *LockBox; + LIST_ENTRY *LockBoxQueue; LockBoxQueue = InternalGetLockBoxQueue (); ASSERT (LockBoxQueue != NULL); for (Link = LockBoxQueue->ForwardLink; Link != LockBoxQueue; - Link = Link->ForwardLink) { + Link = Link->ForwardLink) + { LockBox = BASE_CR ( Link, SMM_LOCK_BOX_DATA, @@ -390,6 +395,7 @@ InternalFindLockBoxByGuid ( return LockBox; } } + return NULL; } @@ -411,15 +417,15 @@ InternalFindLockBoxByGuid ( RETURN_STATUS EFIAPI SaveLockBox ( - IN GUID *Guid, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN VOID *Buffer, + IN UINTN Length ) { - SMM_LOCK_BOX_DATA *LockBox; - EFI_PHYSICAL_ADDRESS SmramBuffer; - EFI_STATUS Status; - LIST_ENTRY *LockBoxQueue; + SMM_LOCK_BOX_DATA *LockBox; + EFI_PHYSICAL_ADDRESS SmramBuffer; + EFI_STATUS Status; + LIST_ENTRY *LockBoxQueue; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SaveLockBox - Enter\n")); @@ -460,7 +466,7 @@ SaveLockBox ( // Status = gMmst->MmAllocatePool ( EfiRuntimeServicesData, - sizeof(*LockBox), + sizeof (*LockBox), (VOID **)&LockBox ); ASSERT_EFI_ERROR (Status); @@ -478,8 +484,8 @@ SaveLockBox ( // // Insert LockBox to queue // - LockBox->Signature = SMM_LOCK_BOX_DATA_SIGNATURE; - CopyMem (&LockBox->Guid, Guid, sizeof(EFI_GUID)); + LockBox->Signature = SMM_LOCK_BOX_DATA_SIGNATURE; + CopyMem (&LockBox->Guid, Guid, sizeof (EFI_GUID)); LockBox->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; LockBox->Length = (UINT64)Length; LockBox->Attributes = 0; @@ -520,11 +526,11 @@ SaveLockBox ( RETURN_STATUS EFIAPI SetLockBoxAttributes ( - IN GUID *Guid, - IN UINT64 Attributes + IN GUID *Guid, + IN UINT64 Attributes ) { - SMM_LOCK_BOX_DATA *LockBox; + SMM_LOCK_BOX_DATA *LockBox; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SetLockBoxAttributes - Enter\n")); @@ -532,13 +538,15 @@ SetLockBoxAttributes ( // Basic check // if ((Guid == NULL) || - ((Attributes & ~(LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE | LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY)) != 0)) { + ((Attributes & ~(LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE | LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY)) != 0)) + { DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SetLockBoxAttributes - Exit (%r)\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } if (((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE) != 0) && - ((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0)) { + ((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0)) + { DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SetLockBoxAttributes - Exit (%r)\n", EFI_INVALID_PARAMETER)); DEBUG ((DEBUG_INFO, " LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE and LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY\n\n")); DEBUG ((DEBUG_INFO, " can not be set together\n")); @@ -555,9 +563,10 @@ SetLockBoxAttributes ( } if ((((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE) != 0) && - ((LockBox->Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0)) || + ((LockBox->Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0)) || (((LockBox->Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE) != 0) && - ((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0))) { + ((Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0))) + { DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib SetLockBoxAttributes 0x%lx 0x%lx - Exit (%r)\n", LockBox->Attributes, Attributes, EFI_INVALID_PARAMETER)); DEBUG ((DEBUG_INFO, " LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE and LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY\n\n")); DEBUG ((DEBUG_INFO, " can not be set together\n")); @@ -598,15 +607,15 @@ SetLockBoxAttributes ( RETURN_STATUS EFIAPI UpdateLockBox ( - IN GUID *Guid, - IN UINTN Offset, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN UINTN Offset, + IN VOID *Buffer, + IN UINTN Length ) { - SMM_LOCK_BOX_DATA *LockBox; - EFI_PHYSICAL_ADDRESS SmramBuffer; - EFI_STATUS Status; + SMM_LOCK_BOX_DATA *LockBox; + EFI_PHYSICAL_ADDRESS SmramBuffer; + EFI_STATUS Status; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib UpdateLockBox - Enter\n")); @@ -614,7 +623,8 @@ UpdateLockBox ( // Basic check // if ((Guid == NULL) || (Buffer == NULL) || (Length == 0) || - (Length > MAX_UINTN - Offset)) { + (Length > MAX_UINTN - Offset)) + { DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib UpdateLockBox - Exit (%r)\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } @@ -683,6 +693,7 @@ UpdateLockBox ( Offset - (UINTN)LockBox->Length ); } + LockBox->Length = Offset + Length; } else { // @@ -693,6 +704,7 @@ UpdateLockBox ( return EFI_BUFFER_TOO_SMALL; } } + ASSERT ((UINTN)LockBox->SmramBuffer <= (MAX_ADDRESS - Offset)); CopyMem ((VOID *)((UINTN)LockBox->SmramBuffer + Offset), Buffer, Length); @@ -724,13 +736,13 @@ UpdateLockBox ( RETURN_STATUS EFIAPI RestoreLockBox ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ) { - SMM_LOCK_BOX_DATA *LockBox; - VOID *RestoreBuffer; + SMM_LOCK_BOX_DATA *LockBox; + VOID *RestoreBuffer; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib RestoreLockBox - Enter\n")); @@ -739,7 +751,8 @@ RestoreLockBox ( // if ((Guid == NULL) || ((Buffer == NULL) && (Length != NULL)) || - ((Buffer != NULL) && (Length == NULL))) { + ((Buffer != NULL) && (Length == NULL))) + { DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib RestoreLockBox - Exit (%r)\n", EFI_INVALID_PARAMETER)); return EFI_INVALID_PARAMETER; } @@ -758,7 +771,8 @@ RestoreLockBox ( if (((LockBox->Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY) != 0) && mSmmLockBoxSmmReadyToLock && - !mSmmLockBoxDuringS3Resume) { + !mSmmLockBoxDuringS3Resume) + { // // With LOCK_BOX_ATTRIBUTE_RESTORE_IN_S3_ONLY, // this LockBox can be restored in S3 resume only. @@ -782,6 +796,7 @@ RestoreLockBox ( DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib RestoreLockBox - Exit (%r)\n", EFI_WRITE_PROTECTED)); return EFI_WRITE_PROTECTED; } + RestoreBuffer = (VOID *)(UINTN)LockBox->Buffer; } @@ -797,6 +812,7 @@ RestoreLockBox ( DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib RestoreLockBox - Exit (%r)\n", EFI_BUFFER_TOO_SMALL)); return EFI_BUFFER_TOO_SMALL; } + *Length = (UINTN)LockBox->Length; } @@ -825,9 +841,9 @@ RestoreAllLockBoxInPlace ( VOID ) { - SMM_LOCK_BOX_DATA *LockBox; - LIST_ENTRY *Link; - LIST_ENTRY *LockBoxQueue; + SMM_LOCK_BOX_DATA *LockBox; + LIST_ENTRY *Link; + LIST_ENTRY *LockBoxQueue; DEBUG ((DEBUG_INFO, "SmmLockBoxSmmLib RestoreAllLockBoxInPlace - Enter\n")); @@ -839,7 +855,8 @@ RestoreAllLockBoxInPlace ( // for (Link = LockBoxQueue->ForwardLink; Link != LockBoxQueue; - Link = Link->ForwardLink) { + Link = Link->ForwardLink) + { LockBox = BASE_CR ( Link, SMM_LOCK_BOX_DATA, @@ -852,6 +869,7 @@ RestoreAllLockBoxInPlace ( CopyMem ((VOID *)(UINTN)LockBox->Buffer, (VOID *)(UINTN)LockBox->SmramBuffer, (UINTN)LockBox->Length); } } + // // Done // diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.c b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.c index 2dfbfc92a5..69d4c42ad1 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.c +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.c @@ -28,10 +28,10 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #if defined (MDE_CPU_IA32) typedef struct _LIST_ENTRY64 LIST_ENTRY64; struct _LIST_ENTRY64 { - LIST_ENTRY64 *ForwardLink; - UINT32 Reserved1; - LIST_ENTRY64 *BackLink; - UINT32 Reserved2; + LIST_ENTRY64 *ForwardLink; + UINT32 Reserved1; + LIST_ENTRY64 *BackLink; + UINT32 Reserved2; }; typedef struct { @@ -57,14 +57,14 @@ typedef struct { } EFI_SMM_SYSTEM_TABLE2_64; typedef struct { - EFI_GUID VendorGuid; - UINT64 VendorTable; + EFI_GUID VendorGuid; + UINT64 VendorTable; } EFI_CONFIGURATION_TABLE64; #endif #if defined (MDE_CPU_X64) -typedef LIST_ENTRY LIST_ENTRY64; -typedef EFI_SMM_SYSTEM_TABLE2 EFI_SMM_SYSTEM_TABLE2_64; +typedef LIST_ENTRY LIST_ENTRY64; +typedef EFI_SMM_SYSTEM_TABLE2 EFI_SMM_SYSTEM_TABLE2_64; typedef EFI_CONFIGURATION_TABLE EFI_CONFIGURATION_TABLE64; #endif @@ -77,10 +77,10 @@ typedef EFI_CONFIGURATION_TABLE EFI_CONFIGURATION_TABLE64; **/ LIST_ENTRY * InternalInitLinkDxe ( - IN LIST_ENTRY *LinkList + IN LIST_ENTRY *LinkList ) { - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { // // 32 PEI + 64 DXE // @@ -99,10 +99,10 @@ InternalInitLinkDxe ( **/ LIST_ENTRY * InternalNextLinkDxe ( - IN LIST_ENTRY *Link + IN LIST_ENTRY *Link ) { - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { // // 32 PEI + 64 DXE // @@ -122,16 +122,17 @@ InternalNextLinkDxe ( **/ SMM_LOCK_BOX_DATA * InternalFindLockBoxByGuidFromSmram ( - IN LIST_ENTRY *LockBoxQueue, - IN EFI_GUID *Guid + IN LIST_ENTRY *LockBoxQueue, + IN EFI_GUID *Guid ) { - LIST_ENTRY *Link; - SMM_LOCK_BOX_DATA *LockBox; + LIST_ENTRY *Link; + SMM_LOCK_BOX_DATA *LockBox; for (Link = InternalInitLinkDxe (LockBoxQueue); Link != LockBoxQueue; - Link = InternalNextLinkDxe (Link)) { + Link = InternalNextLinkDxe (Link)) + { LockBox = BASE_CR ( Link, SMM_LOCK_BOX_DATA, @@ -141,6 +142,7 @@ InternalFindLockBoxByGuidFromSmram ( return LockBox; } } + return NULL; } @@ -155,38 +157,40 @@ InternalFindLockBoxByGuidFromSmram ( **/ VOID * InternalSmstGetVendorTableByGuid ( - IN UINT64 Signature, - IN EFI_SMM_SYSTEM_TABLE2 *Smst, - IN EFI_GUID *VendorGuid + IN UINT64 Signature, + IN EFI_SMM_SYSTEM_TABLE2 *Smst, + IN EFI_GUID *VendorGuid ) { - EFI_CONFIGURATION_TABLE *SmmConfigurationTable; - UINTN NumberOfTableEntries; - UINTN Index; - EFI_SMM_SYSTEM_TABLE2_64 *Smst64; - EFI_CONFIGURATION_TABLE64 *SmmConfigurationTable64; + EFI_CONFIGURATION_TABLE *SmmConfigurationTable; + UINTN NumberOfTableEntries; + UINTN Index; + EFI_SMM_SYSTEM_TABLE2_64 *Smst64; + EFI_CONFIGURATION_TABLE64 *SmmConfigurationTable64; - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { // // 32 PEI + 64 DXE // - Smst64 = (EFI_SMM_SYSTEM_TABLE2_64 *)Smst; + Smst64 = (EFI_SMM_SYSTEM_TABLE2_64 *)Smst; SmmConfigurationTable64 = (EFI_CONFIGURATION_TABLE64 *)(UINTN)Smst64->SmmConfigurationTable; - NumberOfTableEntries = (UINTN)Smst64->NumberOfTableEntries; + NumberOfTableEntries = (UINTN)Smst64->NumberOfTableEntries; for (Index = 0; Index < NumberOfTableEntries; Index++) { if (CompareGuid (&SmmConfigurationTable64[Index].VendorGuid, VendorGuid)) { return (VOID *)(UINTN)SmmConfigurationTable64[Index].VendorTable; } } + return NULL; } else { SmmConfigurationTable = Smst->SmmConfigurationTable; - NumberOfTableEntries = Smst->NumberOfTableEntries; + NumberOfTableEntries = Smst->NumberOfTableEntries; for (Index = 0; Index < NumberOfTableEntries; Index++) { if (CompareGuid (&SmmConfigurationTable[Index].VendorGuid, VendorGuid)) { return (VOID *)SmmConfigurationTable[Index].VendorTable; } } + return NULL; } } @@ -201,14 +205,14 @@ InternalGetSmmLockBoxContext ( VOID ) { - EFI_SMRAM_DESCRIPTOR *SmramDescriptor; - SMM_S3_RESUME_STATE *SmmS3ResumeState; - VOID *GuidHob; - SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; + EFI_SMRAM_DESCRIPTOR *SmramDescriptor; + SMM_S3_RESUME_STATE *SmmS3ResumeState; + VOID *GuidHob; + SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; GuidHob = GetFirstGuidHob (&gEfiAcpiVariableGuid); ASSERT (GuidHob != NULL); - SmramDescriptor = (EFI_SMRAM_DESCRIPTOR *) GET_GUID_HOB_DATA (GuidHob); + SmramDescriptor = (EFI_SMRAM_DESCRIPTOR *)GET_GUID_HOB_DATA (GuidHob); SmmS3ResumeState = (SMM_S3_RESUME_STATE *)(UINTN)SmramDescriptor->CpuStart; SmmLockBoxContext = (SMM_LOCK_BOX_CONTEXT *)InternalSmstGetVendorTableByGuid ( @@ -237,18 +241,18 @@ InternalGetSmmLockBoxContext ( **/ EFI_STATUS InternalRestoreLockBoxFromSmram ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ) { - PEI_SMM_ACCESS_PPI *SmmAccess; - UINTN Index; - EFI_STATUS Status; - SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; - LIST_ENTRY *LockBoxQueue; - SMM_LOCK_BOX_DATA *LockBox; - VOID *RestoreBuffer; + PEI_SMM_ACCESS_PPI *SmmAccess; + UINTN Index; + EFI_STATUS Status; + SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; + LIST_ENTRY *LockBoxQueue; + SMM_LOCK_BOX_DATA *LockBox; + VOID *RestoreBuffer; // // Get needed resource @@ -269,7 +273,7 @@ InternalRestoreLockBoxFromSmram ( // Get LockBox context // SmmLockBoxContext = InternalGetSmmLockBoxContext (); - LockBoxQueue = (LIST_ENTRY *)(UINTN)SmmLockBoxContext->LockBoxDataAddress; + LockBoxQueue = (LIST_ENTRY *)(UINTN)SmmLockBoxContext->LockBoxDataAddress; // // We do NOT check Buffer address in SMRAM, because if SMRAM not locked, we trust the caller. @@ -305,6 +309,7 @@ InternalRestoreLockBoxFromSmram ( if ((LockBox->Attributes & LOCK_BOX_ATTRIBUTE_RESTORE_IN_PLACE) == 0) { return EFI_WRITE_PROTECTED; } + RestoreBuffer = (VOID *)(UINTN)LockBox->Buffer; } @@ -319,6 +324,7 @@ InternalRestoreLockBoxFromSmram ( *Length = (UINTN)LockBox->Length; return EFI_BUFFER_TOO_SMALL; } + *Length = (UINTN)LockBox->Length; } @@ -343,13 +349,13 @@ InternalRestoreAllLockBoxInPlaceFromSmram ( VOID ) { - PEI_SMM_ACCESS_PPI *SmmAccess; - UINTN Index; - EFI_STATUS Status; - SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; - LIST_ENTRY *LockBoxQueue; - SMM_LOCK_BOX_DATA *LockBox; - LIST_ENTRY *Link; + PEI_SMM_ACCESS_PPI *SmmAccess; + UINTN Index; + EFI_STATUS Status; + SMM_LOCK_BOX_CONTEXT *SmmLockBoxContext; + LIST_ENTRY *LockBoxQueue; + SMM_LOCK_BOX_DATA *LockBox; + LIST_ENTRY *Link; // // Get needed resource @@ -370,7 +376,7 @@ InternalRestoreAllLockBoxInPlaceFromSmram ( // Get LockBox context // SmmLockBoxContext = InternalGetSmmLockBoxContext (); - LockBoxQueue = (LIST_ENTRY *)(UINTN)SmmLockBoxContext->LockBoxDataAddress; + LockBoxQueue = (LIST_ENTRY *)(UINTN)SmmLockBoxContext->LockBoxDataAddress; // // We do NOT check Buffer address in SMRAM, because if SMRAM not locked, we trust the caller. @@ -381,7 +387,8 @@ InternalRestoreAllLockBoxInPlaceFromSmram ( // for (Link = InternalInitLinkDxe (LockBoxQueue); Link != LockBoxQueue; - Link = InternalNextLinkDxe (Link)) { + Link = InternalNextLinkDxe (Link)) + { LockBox = BASE_CR ( Link, SMM_LOCK_BOX_DATA, @@ -394,6 +401,7 @@ InternalRestoreAllLockBoxInPlaceFromSmram ( CopyMem ((VOID *)(UINTN)LockBox->Buffer, (VOID *)(UINTN)LockBox->SmramBuffer, (UINTN)LockBox->Length); } } + // // Done // @@ -418,9 +426,9 @@ InternalRestoreAllLockBoxInPlaceFromSmram ( RETURN_STATUS EFIAPI SaveLockBox ( - IN GUID *Guid, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN VOID *Buffer, + IN UINTN Length ) { ASSERT (FALSE); @@ -447,8 +455,8 @@ SaveLockBox ( RETURN_STATUS EFIAPI SetLockBoxAttributes ( - IN GUID *Guid, - IN UINT64 Attributes + IN GUID *Guid, + IN UINT64 Attributes ) { ASSERT (FALSE); @@ -481,10 +489,10 @@ SetLockBoxAttributes ( RETURN_STATUS EFIAPI UpdateLockBox ( - IN GUID *Guid, - IN UINTN Offset, - IN VOID *Buffer, - IN UINTN Length + IN GUID *Guid, + IN UINTN Offset, + IN VOID *Buffer, + IN UINTN Length ) { ASSERT (FALSE); @@ -516,18 +524,18 @@ UpdateLockBox ( RETURN_STATUS EFIAPI RestoreLockBox ( - IN GUID *Guid, - IN VOID *Buffer OPTIONAL, - IN OUT UINTN *Length OPTIONAL + IN GUID *Guid, + IN VOID *Buffer OPTIONAL, + IN OUT UINTN *Length OPTIONAL ) { - EFI_STATUS Status; - EFI_PEI_SMM_COMMUNICATION_PPI *SmmCommunicationPpi; - EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *LockBoxParameterRestore; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 CommBuffer[sizeof(EFI_GUID) + sizeof(UINT64) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE)]; - UINTN CommSize; - UINT64 MessageLength; + EFI_STATUS Status; + EFI_PEI_SMM_COMMUNICATION_PPI *SmmCommunicationPpi; + EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *LockBoxParameterRestore; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 CommBuffer[sizeof (EFI_GUID) + sizeof (UINT64) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE)]; + UINTN CommSize; + UINT64 MessageLength; // // Please aware that there is UINTN in EFI_SMM_COMMUNICATE_HEADER. It might be UINT64 in DXE, while it is UINT32 in PEI. @@ -545,7 +553,8 @@ RestoreLockBox ( // if ((Guid == NULL) || ((Buffer == NULL) && (Length != NULL)) || - ((Buffer != NULL) && (Length == NULL))) { + ((Buffer != NULL) && (Length == NULL))) + { return EFI_INVALID_PARAMETER; } @@ -569,29 +578,31 @@ RestoreLockBox ( // Prepare parameter // CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { - MessageLength = sizeof(*LockBoxParameterRestore); - CopyMem (&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength)], &MessageLength, sizeof(MessageLength)); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { + MessageLength = sizeof (*LockBoxParameterRestore); + CopyMem (&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength)], &MessageLength, sizeof (MessageLength)); } else { - CommHeader->MessageLength = sizeof(*LockBoxParameterRestore); + CommHeader->MessageLength = sizeof (*LockBoxParameterRestore); } DEBUG ((DEBUG_INFO, "SmmLockBoxPeiLib CommBuffer - %x\n", &CommBuffer[0])); - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { - LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof(UINT64)]; + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { + LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof (UINT64)]; } else { - LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof(UINTN)]; + LockBoxParameterRestore = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof (UINTN)]; } + DEBUG ((DEBUG_INFO, "SmmLockBoxPeiLib LockBoxParameterRestore - %x\n", LockBoxParameterRestore)); - LockBoxParameterRestore->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE; - LockBoxParameterRestore->Header.DataLength = sizeof(*LockBoxParameterRestore); + LockBoxParameterRestore->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE; + LockBoxParameterRestore->Header.DataLength = sizeof (*LockBoxParameterRestore); LockBoxParameterRestore->Header.ReturnStatus = (UINT64)-1; if (Guid != 0) { - CopyMem (&LockBoxParameterRestore->Guid, Guid, sizeof(*Guid)); + CopyMem (&LockBoxParameterRestore->Guid, Guid, sizeof (*Guid)); } else { - ZeroMem (&LockBoxParameterRestore->Guid, sizeof(*Guid)); + ZeroMem (&LockBoxParameterRestore->Guid, sizeof (*Guid)); } + LockBoxParameterRestore->Buffer = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; if (Length != NULL) { LockBoxParameterRestore->Length = (EFI_PHYSICAL_ADDRESS)*Length; @@ -602,18 +613,18 @@ RestoreLockBox ( // // Send command // - CommSize = sizeof(CommBuffer); - Status = SmmCommunicationPpi->Communicate ( - SmmCommunicationPpi, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (CommBuffer); + Status = SmmCommunicationPpi->Communicate ( + SmmCommunicationPpi, + &CommBuffer[0], + &CommSize + ); if (Status == EFI_NOT_STARTED) { // // Pei SMM communication not ready yet, so we access SMRAM directly // DEBUG ((DEBUG_INFO, "SmmLockBoxPeiLib Communicate - (%r)\n", Status)); - Status = InternalRestoreLockBoxFromSmram (Guid, Buffer, Length); + Status = InternalRestoreLockBoxFromSmram (Guid, Buffer, Length); LockBoxParameterRestore->Header.ReturnStatus = (UINT64)Status; if (Length != NULL) { LockBoxParameterRestore->Length = (UINT64)*Length; @@ -651,13 +662,13 @@ RestoreAllLockBoxInPlace ( VOID ) { - EFI_STATUS Status; - EFI_PEI_SMM_COMMUNICATION_PPI *SmmCommunicationPpi; - EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *LockBoxParameterRestoreAllInPlace; - EFI_SMM_COMMUNICATE_HEADER *CommHeader; - UINT8 CommBuffer[sizeof(EFI_GUID) + sizeof(UINT64) + sizeof(EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE)]; - UINTN CommSize; - UINT64 MessageLength; + EFI_STATUS Status; + EFI_PEI_SMM_COMMUNICATION_PPI *SmmCommunicationPpi; + EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *LockBoxParameterRestoreAllInPlace; + EFI_SMM_COMMUNICATE_HEADER *CommHeader; + UINT8 CommBuffer[sizeof (EFI_GUID) + sizeof (UINT64) + sizeof (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE)]; + UINTN CommSize; + UINT64 MessageLength; // // Please aware that there is UINTN in EFI_SMM_COMMUNICATE_HEADER. It might be UINT64 in DXE, while it is UINT32 in PEI. @@ -690,40 +701,42 @@ RestoreAllLockBoxInPlace ( // Prepare parameter // CommHeader = (EFI_SMM_COMMUNICATE_HEADER *)&CommBuffer[0]; - CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof(gEfiSmmLockBoxCommunicationGuid)); - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { - MessageLength = sizeof(*LockBoxParameterRestoreAllInPlace); - CopyMem (&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength)], &MessageLength, sizeof(MessageLength)); + CopyMem (&CommHeader->HeaderGuid, &gEfiSmmLockBoxCommunicationGuid, sizeof (gEfiSmmLockBoxCommunicationGuid)); + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { + MessageLength = sizeof (*LockBoxParameterRestoreAllInPlace); + CopyMem (&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength)], &MessageLength, sizeof (MessageLength)); } else { - CommHeader->MessageLength = sizeof(*LockBoxParameterRestoreAllInPlace); + CommHeader->MessageLength = sizeof (*LockBoxParameterRestoreAllInPlace); } - if ((sizeof(UINTN) == sizeof(UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode)) ) { - LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof(UINT64)]; + if ((sizeof (UINTN) == sizeof (UINT32)) && (FeaturePcdGet (PcdDxeIplSwitchToLongMode))) { + LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof (UINT64)]; } else { - LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof(UINTN)]; + LockBoxParameterRestoreAllInPlace = (EFI_SMM_LOCK_BOX_PARAMETER_RESTORE_ALL_IN_PLACE *)&CommBuffer[OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, MessageLength) + sizeof (UINTN)]; } - LockBoxParameterRestoreAllInPlace->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE; - LockBoxParameterRestoreAllInPlace->Header.DataLength = sizeof(*LockBoxParameterRestoreAllInPlace); + + LockBoxParameterRestoreAllInPlace->Header.Command = EFI_SMM_LOCK_BOX_COMMAND_RESTORE_ALL_IN_PLACE; + LockBoxParameterRestoreAllInPlace->Header.DataLength = sizeof (*LockBoxParameterRestoreAllInPlace); LockBoxParameterRestoreAllInPlace->Header.ReturnStatus = (UINT64)-1; // // Send command // - CommSize = sizeof(CommBuffer); - Status = SmmCommunicationPpi->Communicate ( - SmmCommunicationPpi, - &CommBuffer[0], - &CommSize - ); + CommSize = sizeof (CommBuffer); + Status = SmmCommunicationPpi->Communicate ( + SmmCommunicationPpi, + &CommBuffer[0], + &CommSize + ); if (Status == EFI_NOT_STARTED) { // // Pei SMM communication not ready yet, so we access SMRAM directly // DEBUG ((DEBUG_INFO, "SmmLockBoxPeiLib Communicate - (%r)\n", Status)); - Status = InternalRestoreAllLockBoxInPlaceFromSmram (); + Status = InternalRestoreAllLockBoxInPlaceFromSmram (); LockBoxParameterRestoreAllInPlace->Header.ReturnStatus = (UINT64)Status; } + ASSERT_EFI_ERROR (Status); Status = (EFI_STATUS)LockBoxParameterRestoreAllInPlace->Header.ReturnStatus; diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxStandaloneMmLib.c b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxStandaloneMmLib.c index 722121da43..a8f9d30862 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxStandaloneMmLib.c +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxStandaloneMmLib.c @@ -45,8 +45,8 @@ SmmLockBoxStandaloneMmConstructor ( EFI_STATUS EFIAPI SmmLockBoxStandaloneMmDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_MM_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_MM_SYSTEM_TABLE *SystemTable ) { return SmmLockBoxMmDestructor (); diff --git a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxTraditionalMmLib.c b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxTraditionalMmLib.c index a748abb16c..fbbea1a49a 100644 --- a/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxTraditionalMmLib.c +++ b/MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxTraditionalMmLib.c @@ -45,8 +45,8 @@ SmmLockBoxTraditionalConstructor ( EFI_STATUS EFIAPI SmmLockBoxTraditionalDestructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return SmmLockBoxMmDestructor (); diff --git a/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/MemoryAllocationLib.c b/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/MemoryAllocationLib.c index 27a6748f58..17c380a1d8 100644 --- a/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/MemoryAllocationLib.c +++ b/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/MemoryAllocationLib.c @@ -69,11 +69,11 @@ SmmMemoryAllocationLibConstructor ( // // Get SMRAM range information // - Size = 0; + Size = 0; Status = SmmAccess->GetCapabilities (SmmAccess, &Size, NULL); ASSERT (Status == EFI_BUFFER_TOO_SMALL); - mSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size); + mSmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocatePool (Size); ASSERT (mSmramRanges != NULL); Status = SmmAccess->GetCapabilities (SmmAccess, &Size, mSmramRanges); @@ -116,14 +116,15 @@ SmmMemoryAllocationLibDestructor ( BOOLEAN EFIAPI BufferInSmram ( - IN VOID *Buffer + IN VOID *Buffer ) { UINTN Index; - for (Index = 0; Index < mSmramRangeCount; Index ++) { - if (((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer >= mSmramRanges[Index].CpuStart) && - ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer < (mSmramRanges[Index].CpuStart + mSmramRanges[Index].PhysicalSize))) { + for (Index = 0; Index < mSmramRangeCount; Index++) { + if (((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer >= mSmramRanges[Index].CpuStart) && + ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer < (mSmramRanges[Index].CpuStart + mSmramRanges[Index].PhysicalSize))) + { return TRUE; } } @@ -162,7 +163,8 @@ InternalAllocatePages ( if (EFI_ERROR (Status)) { return NULL; } - return (VOID *) (UINTN) Memory; + + return (VOID *)(UINTN)Memory; } /** @@ -189,14 +191,15 @@ AllocatePages ( Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -224,14 +227,15 @@ AllocateRuntimePages ( Buffer = InternalAllocatePages (EfiRuntimeServicesData, Pages); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -289,14 +293,15 @@ FreePages ( // When Buffer is in SMRAM range, it should be allocated by gSmst->SmmAllocatePages() service. // So, gSmst->SmmFreePages() service is used to free it. // - Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // - Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } + ASSERT_EFI_ERROR (Status); } @@ -341,23 +346,25 @@ InternalAllocateAlignedPages ( if (Pages == 0) { return NULL; } + if (Alignment > EFI_PAGE_SIZE) { // // Calculate the total number of pages since alignment is larger than page size. // - AlignmentMask = Alignment - 1; - RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); + AlignmentMask = Alignment - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); // // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not overflow. // ASSERT (RealPages > Pages); - Status = gSmst->SmmAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); + Status = gSmst->SmmAllocatePages (AllocateAnyPages, MemoryType, RealPages, &Memory); if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = ((UINTN) Memory + AlignmentMask) & ~AlignmentMask; - UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN) Memory); + + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); if (UnalignedPages > 0) { // // Free first unaligned page(s). @@ -365,6 +372,7 @@ InternalAllocateAlignedPages ( Status = gSmst->SmmFreePages (Memory, UnalignedPages); ASSERT_EFI_ERROR (Status); } + Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); UnalignedPages = RealPages - Pages - UnalignedPages; if (UnalignedPages > 0) { @@ -382,9 +390,11 @@ InternalAllocateAlignedPages ( if (EFI_ERROR (Status)) { return NULL; } - AlignedMemory = (UINTN) Memory; + + AlignedMemory = (UINTN)Memory; } - return (VOID *) AlignedMemory; + + return (VOID *)AlignedMemory; } /** @@ -418,14 +428,15 @@ AllocateAlignedPages ( Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -460,14 +471,15 @@ AllocateAlignedRuntimePages ( Buffer = InternalAllocateAlignedPages (EfiRuntimeServicesData, Pages, Alignment); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ALIGNED_RUNTIME_PAGES, EfiRuntimeServicesData, Buffer, - EFI_PAGES_TO_SIZE(Pages), + EFI_PAGES_TO_SIZE (Pages), NULL ); } + return Buffer; } @@ -532,14 +544,15 @@ FreeAlignedPages ( // When Buffer is in SMRAM range, it should be allocated by gSmst->SmmAllocatePages() service. // So, gSmst->SmmFreePages() service is used to free it. // - Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gSmst->SmmFreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } else { // // When Buffer is out of SMRAM range, it should be allocated by gBS->AllocatePages() service. // So, gBS->FreePages() service is used to free it. // - Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS) (UINTN) Buffer, Pages); + Status = gBS->FreePages ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, Pages); } + ASSERT_EFI_ERROR (Status); } @@ -570,6 +583,7 @@ InternalAllocatePool ( if (EFI_ERROR (Status)) { Memory = NULL; } + return Memory; } @@ -597,7 +611,7 @@ AllocatePool ( Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_POOL, EfiRuntimeServicesData, Buffer, @@ -605,6 +619,7 @@ AllocatePool ( NULL ); } + return Buffer; } @@ -632,7 +647,7 @@ AllocateRuntimePool ( Buffer = InternalAllocatePool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -640,6 +655,7 @@ AllocateRuntimePool ( NULL ); } + return Buffer; } @@ -691,6 +707,7 @@ InternalAllocateZeroPool ( if (Memory != NULL) { Memory = ZeroMem (Memory, AllocationSize); } + return Memory; } @@ -718,7 +735,7 @@ AllocateZeroPool ( Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_ZERO_POOL, EfiRuntimeServicesData, Buffer, @@ -726,6 +743,7 @@ AllocateZeroPool ( NULL ); } + return Buffer; } @@ -753,7 +771,7 @@ AllocateRuntimeZeroPool ( Buffer = InternalAllocateZeroPool (EfiRuntimeServicesData, AllocationSize); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_ZERO_POOL, EfiRuntimeServicesData, Buffer, @@ -761,6 +779,7 @@ AllocateRuntimeZeroPool ( NULL ); } + return Buffer; } @@ -813,12 +832,13 @@ InternalAllocateCopyPool ( VOID *Memory; ASSERT (Buffer != NULL); - ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN) Buffer + 1)); + ASSERT (AllocationSize <= (MAX_ADDRESS - (UINTN)Buffer + 1)); Memory = InternalAllocatePool (PoolType, AllocationSize); if (Memory != NULL) { - Memory = CopyMem (Memory, Buffer, AllocationSize); + Memory = CopyMem (Memory, Buffer, AllocationSize); } + return Memory; } @@ -852,7 +872,7 @@ AllocateCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -860,6 +880,7 @@ AllocateCopyPool ( NULL ); } + return NewBuffer; } @@ -893,7 +914,7 @@ AllocateRuntimeCopyPool ( NewBuffer = InternalAllocateCopyPool (EfiRuntimeServicesData, AllocationSize, Buffer); if (NewBuffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_ALLOCATE_RUNTIME_COPY_POOL, EfiRuntimeServicesData, NewBuffer, @@ -901,6 +922,7 @@ AllocateRuntimeCopyPool ( NULL ); } + return NewBuffer; } @@ -965,10 +987,11 @@ InternalReallocatePool ( VOID *NewBuffer; NewBuffer = InternalAllocateZeroPool (PoolType, NewSize); - if (NewBuffer != NULL && OldBuffer != NULL) { + if ((NewBuffer != NULL) && (OldBuffer != NULL)) { CopyMem (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); FreePool (OldBuffer); } + return NewBuffer; } @@ -1006,7 +1029,7 @@ ReallocatePool ( Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_POOL, EfiRuntimeServicesData, Buffer, @@ -1014,6 +1037,7 @@ ReallocatePool ( NULL ); } + return Buffer; } @@ -1051,7 +1075,7 @@ ReallocateRuntimePool ( Buffer = InternalReallocatePool (EfiRuntimeServicesData, OldSize, NewSize, OldBuffer); if (Buffer != NULL) { MemoryProfileLibRecord ( - (PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS(0), + (PHYSICAL_ADDRESS)(UINTN)RETURN_ADDRESS (0), MEMORY_PROFILE_ACTION_LIB_REALLOCATE_RUNTIME_POOL, EfiRuntimeServicesData, Buffer, @@ -1059,6 +1083,7 @@ ReallocateRuntimePool ( NULL ); } + return Buffer; } @@ -1112,10 +1137,10 @@ ReallocateReservedPool ( VOID EFIAPI FreePool ( - IN VOID *Buffer + IN VOID *Buffer ) { - EFI_STATUS Status; + EFI_STATUS Status; if (BufferInSmram (Buffer)) { // @@ -1130,5 +1155,6 @@ FreePool ( // Status = gBS->FreePool (Buffer); } + ASSERT_EFI_ERROR (Status); } diff --git a/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/SmmMemoryProfileLib.c b/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/SmmMemoryProfileLib.c index 83ffcf5109..a874a7489d 100644 --- a/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/SmmMemoryProfileLib.c +++ b/MdeModulePkg/Library/SmmMemoryAllocationProfileLib/SmmMemoryProfileLib.c @@ -14,8 +14,8 @@ #include -EDKII_MEMORY_PROFILE_PROTOCOL *mLibProfileProtocol; -EDKII_SMM_MEMORY_PROFILE_PROTOCOL *mLibSmmProfileProtocol; +EDKII_MEMORY_PROFILE_PROTOCOL *mLibProfileProtocol; +EDKII_SMM_MEMORY_PROFILE_PROTOCOL *mLibSmmProfileProtocol; /** Check whether the start address of buffer is within any of the SMRAM ranges. @@ -28,7 +28,7 @@ EDKII_SMM_MEMORY_PROFILE_PROTOCOL *mLibSmmProfileProtocol; BOOLEAN EFIAPI BufferInSmram ( - IN VOID *Buffer + IN VOID *Buffer ); /** @@ -47,7 +47,7 @@ SmmMemoryProfileLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS Status; // // Locate Profile Protocol @@ -98,18 +98,19 @@ SmmMemoryProfileLibConstructor ( EFI_STATUS EFIAPI MemoryProfileLibRecord ( - IN PHYSICAL_ADDRESS CallerAddress, - IN MEMORY_PROFILE_ACTION Action, - IN EFI_MEMORY_TYPE MemoryType, - IN VOID *Buffer, - IN UINTN Size, - IN CHAR8 *ActionString OPTIONAL + IN PHYSICAL_ADDRESS CallerAddress, + IN MEMORY_PROFILE_ACTION Action, + IN EFI_MEMORY_TYPE MemoryType, + IN VOID *Buffer, + IN UINTN Size, + IN CHAR8 *ActionString OPTIONAL ) { if (BufferInSmram (Buffer)) { if (mLibSmmProfileProtocol == NULL) { return EFI_UNSUPPORTED; } + return mLibSmmProfileProtocol->Record ( mLibSmmProfileProtocol, CallerAddress, @@ -123,6 +124,7 @@ MemoryProfileLibRecord ( if (mLibProfileProtocol == NULL) { return EFI_UNSUPPORTED; } + return mLibProfileProtocol->Record ( mLibProfileProtocol, CallerAddress, @@ -134,4 +136,3 @@ MemoryProfileLibRecord ( ); } } - diff --git a/MdeModulePkg/Library/SmmPerformanceLib/SmmPerformanceLib.c b/MdeModulePkg/Library/SmmPerformanceLib/SmmPerformanceLib.c index c3fa79b2de..623f8a978c 100644 --- a/MdeModulePkg/Library/SmmPerformanceLib/SmmPerformanceLib.c +++ b/MdeModulePkg/Library/SmmPerformanceLib/SmmPerformanceLib.c @@ -11,7 +11,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ - #include #include @@ -41,8 +40,7 @@ SmmPerformanceLibConstructor ( IN EFI_SYSTEM_TABLE *SystemTable ) { - - mPerformanceMeasurementEnabled = (BOOLEAN) ((PcdGet8(PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); + mPerformanceMeasurementEnabled = (BOOLEAN)((PcdGet8 (PcdPerformanceLibraryPropertyMask) & PERFORMANCE_LIBRARY_PROPERTY_MEASUREMENT_ENABLED) != 0); return EFI_SUCCESS; } @@ -61,14 +59,14 @@ GetPerformanceMeasurementProtocol ( VOID ) { - EFI_STATUS Status; - EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *PerformanceMeasurement; + EFI_STATUS Status; + EDKII_PERFORMANCE_MEASUREMENT_PROTOCOL *PerformanceMeasurement; if (mPerformanceMeasurement != NULL) { return EFI_SUCCESS; } - Status = gSmst->SmmLocateProtocol (&gEdkiiSmmPerformanceMeasurementProtocolGuid, NULL, (VOID **) &PerformanceMeasurement); + Status = gSmst->SmmLocateProtocol (&gEdkiiSmmPerformanceMeasurementProtocolGuid, NULL, (VOID **)&PerformanceMeasurement); if (!EFI_ERROR (Status)) { ASSERT (PerformanceMeasurement != NULL); // @@ -77,6 +75,7 @@ GetPerformanceMeasurementProtocol ( mPerformanceMeasurement = PerformanceMeasurement; return EFI_SUCCESS; } + return EFI_NOT_FOUND; } @@ -112,8 +111,8 @@ StartPerformanceMeasurementEx ( IN UINT32 Identifier ) { - EFI_STATUS Status; - CONST CHAR8* String; + EFI_STATUS Status; + CONST CHAR8 *String; Status = GetPerformanceMeasurementProtocol (); if (EFI_ERROR (Status)) { @@ -134,7 +133,7 @@ StartPerformanceMeasurementEx ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -171,8 +170,8 @@ EndPerformanceMeasurementEx ( IN UINT32 Identifier ) { - EFI_STATUS Status; - CONST CHAR8* String; + EFI_STATUS Status; + CONST CHAR8 *String; Status = GetPerformanceMeasurementProtocol (); if (EFI_ERROR (Status)) { @@ -193,7 +192,7 @@ EndPerformanceMeasurementEx ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -240,13 +239,13 @@ EndPerformanceMeasurementEx ( UINTN EFIAPI GetPerformanceMeasurementEx ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp, - OUT UINT32 *Identifier + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp, + OUT UINT32 *Identifier ) { return 0; @@ -360,12 +359,12 @@ EndPerformanceMeasurement ( UINTN EFIAPI GetPerformanceMeasurement ( - IN UINTN LogEntryKey, - OUT CONST VOID **Handle, - OUT CONST CHAR8 **Token, - OUT CONST CHAR8 **Module, - OUT UINT64 *StartTimeStamp, - OUT UINT64 *EndTimeStamp + IN UINTN LogEntryKey, + OUT CONST VOID **Handle, + OUT CONST CHAR8 **Token, + OUT CONST CHAR8 **Module, + OUT UINT64 *StartTimeStamp, + OUT UINT64 *EndTimeStamp ) { return 0; @@ -430,7 +429,7 @@ LogPerformanceMeasurement ( ASSERT (FALSE); } - return (RETURN_STATUS) Status; + return (RETURN_STATUS)Status; } /** @@ -448,14 +447,15 @@ LogPerformanceMeasurement ( BOOLEAN EFIAPI LogPerformanceMeasurementEnabled ( - IN CONST UINTN Type + IN CONST UINTN Type ) { // // When Performance measurement is enabled and the type is not filtered, the performance can be logged. // - if (PerformanceMeasurementEnabled () && (PcdGet8(PcdPerformanceLibraryPropertyMask) & Type) == 0) { + if (PerformanceMeasurementEnabled () && ((PcdGet8 (PcdPerformanceLibraryPropertyMask) & Type) == 0)) { return TRUE; } + return FALSE; } diff --git a/MdeModulePkg/Library/SmmReportStatusCodeLib/ReportStatusCodeLib.c b/MdeModulePkg/Library/SmmReportStatusCodeLib/ReportStatusCodeLib.c index fb1769db92..f9afd1f13c 100644 --- a/MdeModulePkg/Library/SmmReportStatusCodeLib/ReportStatusCodeLib.c +++ b/MdeModulePkg/Library/SmmReportStatusCodeLib/ReportStatusCodeLib.c @@ -20,9 +20,8 @@ #include "ReportStatusCodeLib.h" -EFI_MM_REPORT_STATUS_CODE mReportStatusCode = NULL; -EFI_MM_STATUS_CODE_PROTOCOL *mStatusCodeProtocol = NULL; - +EFI_MM_REPORT_STATUS_CODE mReportStatusCode = NULL; +EFI_MM_STATUS_CODE_PROTOCOL *mStatusCodeProtocol = NULL; /** Locate the report status code service. @@ -36,12 +35,13 @@ InternalGetReportStatusCode ( VOID ) { - EFI_STATUS Status; + EFI_STATUS Status; - Status = InternalLocateProtocol (&gEfiMmStatusCodeProtocolGuid, NULL, (VOID**)&mStatusCodeProtocol); - if (!EFI_ERROR (Status) && mStatusCodeProtocol != NULL) { + Status = InternalLocateProtocol (&gEfiMmStatusCodeProtocolGuid, NULL, (VOID **)&mStatusCodeProtocol); + if (!EFI_ERROR (Status) && (mStatusCodeProtocol != NULL)) { return mStatusCodeProtocol->ReportStatusCode; } + return NULL; } @@ -69,16 +69,17 @@ InternalGetReportStatusCode ( **/ EFI_STATUS InternalReportStatusCode ( - IN EFI_STATUS_CODE_TYPE Type, - IN EFI_STATUS_CODE_VALUE Value, - IN UINT32 Instance, - IN CONST EFI_GUID *CallerId OPTIONAL, - IN EFI_STATUS_CODE_DATA *Data OPTIONAL + IN EFI_STATUS_CODE_TYPE Type, + IN EFI_STATUS_CODE_VALUE Value, + IN UINT32 Instance, + IN CONST EFI_GUID *CallerId OPTIONAL, + IN EFI_STATUS_CODE_DATA *Data OPTIONAL ) { - if ((ReportProgressCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - (ReportErrorCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) || - (ReportDebugCodeEnabled() && ((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE)) { + if ((ReportProgressCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE)) || + (ReportErrorCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) || + (ReportDebugCodeEnabled () && (((Type) & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE))) + { // // If mReportStatusCode is NULL, then check if status code service is available in system. // @@ -92,13 +93,12 @@ InternalReportStatusCode ( // // A status code service is present in system, so pass in all the parameters to the service. // - return (*mReportStatusCode) (mStatusCodeProtocol, Type, Value, Instance, (EFI_GUID *)CallerId, Data); + return (*mReportStatusCode)(mStatusCodeProtocol, Type, Value, Instance, (EFI_GUID *)CallerId, Data); } return EFI_UNSUPPORTED; } - /** Converts a status code to an 8-bit POST code value. @@ -137,15 +137,16 @@ CodeTypeToPostCode ( // Convert Value to an 8 bit post code // if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) || - ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) ) { - *PostCode = (UINT8) ((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | - (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); + ((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE)) + { + *PostCode = (UINT8)((((Value & EFI_STATUS_CODE_CLASS_MASK) >> 24) << 5) | + (((Value & EFI_STATUS_CODE_SUBCLASS_MASK) >> 16) & 0x1f)); return TRUE; } + return FALSE; } - /** Extracts ASSERT() information from a status code structure. @@ -199,17 +200,18 @@ ReportStatusCodeExtractAssertInfo ( if (((CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) && ((CodeType & EFI_STATUS_CODE_SEVERITY_MASK) == EFI_ERROR_UNRECOVERED) && - ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) { + ((Value & EFI_STATUS_CODE_OPERATION_MASK) == EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)) + { AssertData = (EFI_DEBUG_ASSERT_DATA *)(Data + 1); *Filename = (CHAR8 *)(AssertData + 1); *Description = *Filename + AsciiStrLen (*Filename) + 1; *LineNumber = AssertData->LineNumber; return TRUE; } + return FALSE; } - /** Extracts DEBUG() information from a status code structure. @@ -278,13 +280,12 @@ ReportStatusCodeExtractDebugInfo ( // 64-bit aligned is a must, otherwise retrieving 64-bit parameter from BASE_LIST will // cause unalignment exception. // - *Marker = (BASE_LIST) (DebugInfo + 1); + *Marker = (BASE_LIST)(DebugInfo + 1); *Format = (CHAR8 *)(((UINT64 *)*Marker) + 12); return TRUE; } - /** Reports a status code. @@ -316,7 +317,6 @@ ReportStatusCode ( return InternalReportStatusCode (Type, Value, 0, &gEfiCallerIdGuid, NULL); } - /** Reports a status code with an extended data buffer. @@ -372,7 +372,6 @@ ReportStatusCodeWithExtendedData ( ); } - /** Reports a status code with full parameters. @@ -444,11 +443,12 @@ ReportStatusCodeEx ( // // Fill in the extended data header // - StatusCodeData->HeaderSize = (UINT16) sizeof (EFI_STATUS_CODE_DATA); - StatusCodeData->Size = (UINT16) ExtendedDataSize; + StatusCodeData->HeaderSize = (UINT16)sizeof (EFI_STATUS_CODE_DATA); + StatusCodeData->Size = (UINT16)ExtendedDataSize; if (ExtendedDataGuid == NULL) { ExtendedDataGuid = &gEfiStatusCodeSpecificDataGuid; } + CopyGuid (&StatusCodeData->Type, ExtendedDataGuid); // @@ -464,6 +464,7 @@ ReportStatusCodeEx ( if (CallerId == NULL) { CallerId = &gEfiCallerIdGuid; } + Status = InternalReportStatusCode (Type, Value, Instance, CallerId, StatusCodeData); // @@ -474,7 +475,6 @@ ReportStatusCodeEx ( return Status; } - /** Returns TRUE if status codes of type EFI_PROGRESS_CODE are enabled @@ -493,10 +493,9 @@ ReportProgressCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_PROGRESS_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_ERROR_CODE are enabled @@ -515,10 +514,9 @@ ReportErrorCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_ERROR_CODE_ENABLED) != 0); } - /** Returns TRUE if status codes of type EFI_DEBUG_CODE are enabled @@ -537,5 +535,5 @@ ReportDebugCodeEnabled ( VOID ) { - return (BOOLEAN) ((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); + return (BOOLEAN)((PcdGet8 (PcdReportStatusCodePropertyMask) & REPORT_STATUS_CODE_PROPERTY_DEBUG_CODE_ENABLED) != 0); } diff --git a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/MmSmiHandlerProfileLib.c b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/MmSmiHandlerProfileLib.c index 25a0ccb49d..c5d840326e 100644 --- a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/MmSmiHandlerProfileLib.c +++ b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/MmSmiHandlerProfileLib.c @@ -37,16 +37,17 @@ SMI_HANDLER_PROFILE_PROTOCOL *mSmiHandlerProfile; EFI_STATUS EFIAPI SmiHandlerProfileRegisterHandler ( - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN PHYSICAL_ADDRESS CallerAddress, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN PHYSICAL_ADDRESS CallerAddress, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ) { if (mSmiHandlerProfile != NULL) { return mSmiHandlerProfile->RegisterHandler (mSmiHandlerProfile, HandlerGuid, Handler, CallerAddress, Context, ContextSize); } + return EFI_UNSUPPORTED; } @@ -70,15 +71,16 @@ SmiHandlerProfileRegisterHandler ( EFI_STATUS EFIAPI SmiHandlerProfileUnregisterHandler ( - IN EFI_GUID *HandlerGuid, - IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, - IN VOID *Context OPTIONAL, - IN UINTN ContextSize OPTIONAL + IN EFI_GUID *HandlerGuid, + IN EFI_SMM_HANDLER_ENTRY_POINT2 Handler, + IN VOID *Context OPTIONAL, + IN UINTN ContextSize OPTIONAL ) { if (mSmiHandlerProfile != NULL) { return mSmiHandlerProfile->UnregisterHandler (mSmiHandlerProfile, HandlerGuid, Handler, Context, ContextSize); } + return EFI_UNSUPPORTED; } @@ -95,7 +97,7 @@ MmSmiHandlerProfileLibInitialization ( gMmst->MmLocateProtocol ( &gSmiHandlerProfileGuid, NULL, - (VOID **) &mSmiHandlerProfile + (VOID **)&mSmiHandlerProfile ); return EFI_SUCCESS; } diff --git a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/SmmSmiHandlerProfileLib.c b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/SmmSmiHandlerProfileLib.c index 0167d81b88..da8cee7f15 100644 --- a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/SmmSmiHandlerProfileLib.c +++ b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/SmmSmiHandlerProfileLib.c @@ -22,8 +22,8 @@ EFI_STATUS EFIAPI SmmSmiHandlerProfileLibConstructor ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable ) { return MmSmiHandlerProfileLibInitialization (); diff --git a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/StandaloneMmSmiHandlerProfileLib.c b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/StandaloneMmSmiHandlerProfileLib.c index a7714390e5..c426b11159 100644 --- a/MdeModulePkg/Library/SmmSmiHandlerProfileLib/StandaloneMmSmiHandlerProfileLib.c +++ b/MdeModulePkg/Library/SmmSmiHandlerProfileLib/StandaloneMmSmiHandlerProfileLib.c @@ -28,4 +28,3 @@ StandaloneMmSmiHandlerProfileLibConstructor ( { return MmSmiHandlerProfileLibInitialization (); } - diff --git a/MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.c b/MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.c index b9c5b68de8..880b428d56 100644 --- a/MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.c +++ b/MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.c @@ -24,12 +24,12 @@ SPDX-License-Identifier: BSD-2-Clause-Patent EFI_STATUS EFIAPI TpmMeasureAndLogData ( - IN UINT32 PcrIndex, - IN UINT32 EventType, - IN VOID *EventLog, - IN UINT32 LogLen, - IN VOID *HashData, - IN UINT64 HashDataLen + IN UINT32 PcrIndex, + IN UINT32 EventType, + IN VOID *EventLog, + IN UINT32 LogLen, + IN VOID *HashData, + IN UINT64 HashDataLen ) { // diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c index a7261d64f0..962892d38f 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c @@ -10,7 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalBm.h" -EFI_RAM_DISK_PROTOCOL *mRamDisk = NULL; +EFI_RAM_DISK_PROTOCOL *mRamDisk = NULL; EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION mBmRefreshLegacyBootOption = NULL; EFI_BOOT_MANAGER_LEGACY_BOOT mBmLegacyBoot = NULL; @@ -19,8 +19,12 @@ EFI_BOOT_MANAGER_LEGACY_BOOT mBmLegacyBoot = NULL; /// This GUID is used for an EFI Variable that stores the front device pathes /// for a partial device path that starts with the HD node. /// -EFI_GUID mBmHardDriveBootVariableGuid = { 0xfab7e9e1, 0x39dd, 0x4f2b, { 0x84, 0x08, 0xe2, 0x0e, 0x90, 0x6c, 0xb6, 0xde } }; -EFI_GUID mBmAutoCreateBootOptionGuid = { 0x8108ac4e, 0x9f11, 0x4d59, { 0x85, 0x0e, 0xe2, 0x1a, 0x52, 0x2c, 0x59, 0xb2 } }; +EFI_GUID mBmHardDriveBootVariableGuid = { + 0xfab7e9e1, 0x39dd, 0x4f2b, { 0x84, 0x08, 0xe2, 0x0e, 0x90, 0x6c, 0xb6, 0xde } +}; +EFI_GUID mBmAutoCreateBootOptionGuid = { + 0x8108ac4e, 0x9f11, 0x4d59, { 0x85, 0x0e, 0xe2, 0x1a, 0x52, 0x2c, 0x59, 0xb2 } +}; /** @@ -40,9 +44,9 @@ BmEndOfBdsPerfCode ( // // Record the performance data for End of BDS // - PERF_CROSSMODULE_END("BDS"); + PERF_CROSSMODULE_END ("BDS"); - return ; + return; } /** @@ -54,8 +58,8 @@ BmEndOfBdsPerfCode ( VOID EFIAPI EfiBootManagerRegisterLegacyBootSupport ( - EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption, - EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot + EFI_BOOT_MANAGER_REFRESH_LEGACY_BOOT_OPTION RefreshLegacyBootOption, + EFI_BOOT_MANAGER_LEGACY_BOOT LegacyBoot ) { mBmRefreshLegacyBootOption = RefreshLegacyBootOption; @@ -72,12 +76,13 @@ EfiBootManagerRegisterLegacyBootSupport ( **/ BOOLEAN BmIsAutoCreateBootOption ( - EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { if ((BootOption->OptionalDataSize == sizeof (EFI_GUID)) && - CompareGuid ((EFI_GUID *) BootOption->OptionalData, &mBmAutoCreateBootOptionGuid) - ) { + CompareGuid ((EFI_GUID *)BootOption->OptionalData, &mBmAutoCreateBootOptionGuid) + ) + { return TRUE; } else { return FALSE; @@ -94,16 +99,16 @@ BmIsAutoCreateBootOption ( **/ UINTN BmFindBootOptionInVariable ( - IN EFI_BOOT_MANAGER_LOAD_OPTION *OptionToFind + IN EFI_BOOT_MANAGER_LOAD_OPTION *OptionToFind ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION BootOption; - UINTN OptionNumber; - CHAR16 OptionName[BM_OPTION_NAME_LEN]; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; - UINTN BootOptionCount; - UINTN Index; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION BootOption; + UINTN OptionNumber; + CHAR16 OptionName[BM_OPTION_NAME_LEN]; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; + UINTN BootOptionCount; + UINTN Index; OptionNumber = LoadOptionNumberUnassigned; @@ -112,8 +117,11 @@ BmFindBootOptionInVariable ( // if (OptionToFind->OptionNumber != LoadOptionNumberUnassigned) { UnicodeSPrint ( - OptionName, sizeof (OptionName), L"%s%04x", - mBmLoadOptionName[OptionToFind->OptionType], OptionToFind->OptionNumber + OptionName, + sizeof (OptionName), + L"%s%04x", + mBmLoadOptionName[OptionToFind->OptionType], + OptionToFind->OptionNumber ); Status = EfiBootManagerVariableToLoadOption (OptionName, &BootOption); @@ -124,9 +132,11 @@ BmFindBootOptionInVariable ( (CompareMem (OptionToFind->FilePath, BootOption.FilePath, GetDevicePathSize (OptionToFind->FilePath)) == 0) && (OptionToFind->OptionalDataSize == BootOption.OptionalDataSize) && (CompareMem (OptionToFind->OptionalData, BootOption.OptionalData, OptionToFind->OptionalDataSize) == 0) - ) { + ) + { OptionNumber = OptionToFind->OptionNumber; } + EfiBootManagerFreeLoadOption (&BootOption); } } @@ -158,24 +168,24 @@ BmFindBootOptionInVariable ( **/ EFI_DEVICE_PATH_PROTOCOL * BmAdjustFvFilePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - EFI_STATUS Status; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *FvFileNode; - EFI_HANDLE FvHandle; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - UINTN FvHandleCount; - EFI_HANDLE *FvHandles; - EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; - EFI_DEVICE_PATH_PROTOCOL *FullPath; + EFI_STATUS Status; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *FvFileNode; + EFI_HANDLE FvHandle; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + UINTN FvHandleCount; + EFI_HANDLE *FvHandles; + EFI_DEVICE_PATH_PROTOCOL *NewDevicePath; + EFI_DEVICE_PATH_PROTOCOL *FullPath; // // Get the file buffer by using the exactly FilePath. // FvFileNode = FilePath; - Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &FvFileNode, &FvHandle); + Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &FvFileNode, &FvHandle); if (!EFI_ERROR (Status)) { return DuplicateDevicePath (FilePath); } @@ -195,10 +205,10 @@ BmAdjustFvFilePath ( gBS->HandleProtocol ( gImageHandle, &gEfiLoadedImageProtocolGuid, - (VOID **) &LoadedImage + (VOID **)&LoadedImage ); NewDevicePath = AppendDevicePathNode (DevicePathFromHandle (LoadedImage->DeviceHandle), FvFileNode); - FullPath = BmAdjustFvFilePath (NewDevicePath); + FullPath = BmAdjustFvFilePath (NewDevicePath); FreePool (NewDevicePath); if (FullPath != NULL) { return FullPath; @@ -221,8 +231,9 @@ BmAdjustFvFilePath ( // continue; } + NewDevicePath = AppendDevicePathNode (DevicePathFromHandle (FvHandles[Index]), FvFileNode); - FullPath = BmAdjustFvFilePath (NewDevicePath); + FullPath = BmAdjustFvFilePath (NewDevicePath); FreePool (NewDevicePath); if (FullPath != NULL) { break; @@ -232,6 +243,7 @@ BmAdjustFvFilePath ( if (FvHandles != NULL) { FreePool (FvHandles); } + return FullPath; } @@ -247,14 +259,14 @@ BmAdjustFvFilePath ( **/ BOOLEAN BmIsFvFilePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *Node; - Node = DevicePath; + Node = DevicePath; Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &Node, &Handle); if (!EFI_ERROR (Status)) { return TRUE; @@ -266,6 +278,7 @@ BmIsFvFilePath ( return IsDevicePathEnd (NextDevicePathNode (DevicePath)); } } + return FALSE; } @@ -282,8 +295,8 @@ BmIsFvFilePath ( **/ BOOLEAN BmMatchUsbClass ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN USB_CLASS_DEVICE_PATH *UsbClass + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN USB_CLASS_DEVICE_PATH *UsbClass ) { EFI_STATUS Status; @@ -294,7 +307,8 @@ BmMatchUsbClass ( UINT8 DeviceProtocol; if ((DevicePathType (UsbClass) != MESSAGING_DEVICE_PATH) || - (DevicePathSubType (UsbClass) != MSG_USB_CLASS_DP)){ + (DevicePathSubType (UsbClass) != MSG_USB_CLASS_DP)) + { return FALSE; } @@ -307,12 +321,14 @@ BmMatchUsbClass ( } if ((UsbClass->VendorId != 0xffff) && - (UsbClass->VendorId != DevDesc.IdVendor)) { + (UsbClass->VendorId != DevDesc.IdVendor)) + { return FALSE; } if ((UsbClass->ProductId != 0xffff) && - (UsbClass->ProductId != DevDesc.IdProduct)) { + (UsbClass->ProductId != DevDesc.IdProduct)) + { return FALSE; } @@ -338,17 +354,20 @@ BmMatchUsbClass ( // Check Class, SubClass and Protocol. // if ((UsbClass->DeviceClass != 0xff) && - (UsbClass->DeviceClass != DeviceClass)) { + (UsbClass->DeviceClass != DeviceClass)) + { return FALSE; } if ((UsbClass->DeviceSubClass != 0xff) && - (UsbClass->DeviceSubClass != DeviceSubClass)) { + (UsbClass->DeviceSubClass != DeviceSubClass)) + { return FALSE; } if ((UsbClass->DeviceProtocol != 0xff) && - (UsbClass->DeviceProtocol != DeviceProtocol)) { + (UsbClass->DeviceProtocol != DeviceProtocol)) + { return FALSE; } @@ -368,23 +387,24 @@ BmMatchUsbClass ( **/ BOOLEAN BmMatchUsbWwid ( - IN EFI_USB_IO_PROTOCOL *UsbIo, - IN USB_WWID_DEVICE_PATH *UsbWwid + IN EFI_USB_IO_PROTOCOL *UsbIo, + IN USB_WWID_DEVICE_PATH *UsbWwid ) { - EFI_STATUS Status; - EFI_USB_DEVICE_DESCRIPTOR DevDesc; - EFI_USB_INTERFACE_DESCRIPTOR IfDesc; - UINT16 *LangIdTable; - UINT16 TableSize; - UINT16 Index; - CHAR16 *CompareStr; - UINTN CompareLen; - CHAR16 *SerialNumberStr; - UINTN Length; + EFI_STATUS Status; + EFI_USB_DEVICE_DESCRIPTOR DevDesc; + EFI_USB_INTERFACE_DESCRIPTOR IfDesc; + UINT16 *LangIdTable; + UINT16 TableSize; + UINT16 Index; + CHAR16 *CompareStr; + UINTN CompareLen; + CHAR16 *SerialNumberStr; + UINTN Length; if ((DevicePathType (UsbWwid) != MESSAGING_DEVICE_PATH) || - (DevicePathSubType (UsbWwid) != MSG_USB_WWID_DP)) { + (DevicePathSubType (UsbWwid) != MSG_USB_WWID_DP)) + { return FALSE; } @@ -395,8 +415,10 @@ BmMatchUsbWwid ( if (EFI_ERROR (Status)) { return FALSE; } + if ((DevDesc.IdVendor != UsbWwid->VendorId) || - (DevDesc.IdProduct != UsbWwid->ProductId)) { + (DevDesc.IdProduct != UsbWwid->ProductId)) + { return FALSE; } @@ -407,6 +429,7 @@ BmMatchUsbWwid ( if (EFI_ERROR (Status)) { return FALSE; } + if (IfDesc.InterfaceNumber != UsbWwid->InterfaceNumber) { return FALSE; } @@ -421,9 +444,9 @@ BmMatchUsbWwid ( // // Get all supported languages. // - TableSize = 0; + TableSize = 0; LangIdTable = NULL; - Status = UsbIo->UsbGetSupportedLanguages (UsbIo, &LangIdTable, &TableSize); + Status = UsbIo->UsbGetSupportedLanguages (UsbIo, &LangIdTable, &TableSize); if (EFI_ERROR (Status) || (TableSize == 0) || (LangIdTable == NULL)) { return FALSE; } @@ -431,7 +454,7 @@ BmMatchUsbWwid ( // // Serial number in USB WWID device path is the last 64-or-less UTF-16 characters. // - CompareStr = (CHAR16 *) (UINTN) (UsbWwid + 1); + CompareStr = (CHAR16 *)(UINTN)(UsbWwid + 1); CompareLen = (DevicePathNodeLength (UsbWwid) - sizeof (USB_WWID_DEVICE_PATH)) / sizeof (CHAR16); if (CompareStr[CompareLen - 1] == L'\0') { CompareLen--; @@ -442,19 +465,20 @@ BmMatchUsbWwid ( // for (Index = 0; Index < TableSize / sizeof (UINT16); Index++) { SerialNumberStr = NULL; - Status = UsbIo->UsbGetStringDescriptor ( - UsbIo, - LangIdTable[Index], - DevDesc.StrSerialNumber, - &SerialNumberStr - ); + Status = UsbIo->UsbGetStringDescriptor ( + UsbIo, + LangIdTable[Index], + DevDesc.StrSerialNumber, + &SerialNumberStr + ); if (EFI_ERROR (Status) || (SerialNumberStr == NULL)) { continue; } Length = StrLen (SerialNumberStr); if ((Length >= CompareLen) && - (CompareMem (SerialNumberStr + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) { + (CompareMem (SerialNumberStr + Length - CompareLen, CompareStr, CompareLen * sizeof (CHAR16)) == 0)) + { FreePool (SerialNumberStr); return TRUE; } @@ -515,28 +539,28 @@ BmFindUsbDevice ( // // Get the Usb IO interface. // - Status = gBS->HandleProtocol( + Status = gBS->HandleProtocol ( UsbIoHandles[Index], &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo + (VOID **)&UsbIo ); UsbIoDevicePath = DevicePathFromHandle (UsbIoHandles[Index]); Matched = FALSE; if (!EFI_ERROR (Status) && (UsbIoDevicePath != NULL)) { - // // Compare starting part of UsbIoHandle's device path with ParentDevicePath. // if (CompareMem (UsbIoDevicePath, DevicePath, ParentDevicePathSize) == 0) { - if (BmMatchUsbClass (UsbIo, (USB_CLASS_DEVICE_PATH *) ((UINTN) DevicePath + ParentDevicePathSize)) || - BmMatchUsbWwid (UsbIo, (USB_WWID_DEVICE_PATH *) ((UINTN) DevicePath + ParentDevicePathSize))) { + if (BmMatchUsbClass (UsbIo, (USB_CLASS_DEVICE_PATH *)((UINTN)DevicePath + ParentDevicePathSize)) || + BmMatchUsbWwid (UsbIo, (USB_WWID_DEVICE_PATH *)((UINTN)DevicePath + ParentDevicePathSize))) + { Matched = TRUE; } } } if (!Matched) { - (*UsbIoHandleCount) --; + (*UsbIoHandleCount)--; CopyMem (&UsbIoHandles[Index], &UsbIoHandles[Index + 1], (*UsbIoHandleCount - Index) * sizeof (EFI_HANDLE)); } else { Index++; @@ -579,19 +603,19 @@ BmExpandUsbDevicePath ( IN EFI_DEVICE_PATH_PROTOCOL *ShortformNode ) { - UINTN ParentDevicePathSize; - EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; - EFI_DEVICE_PATH_PROTOCOL *NextFullPath; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN Index; - BOOLEAN GetNext; + UINTN ParentDevicePathSize; + EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath; + EFI_DEVICE_PATH_PROTOCOL *NextFullPath; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN Index; + BOOLEAN GetNext; - NextFullPath = NULL; - GetNext = (BOOLEAN)(FullPath == NULL); - ParentDevicePathSize = (UINTN) ShortformNode - (UINTN) FilePath; - RemainingDevicePath = NextDevicePathNode (ShortformNode); - Handles = BmFindUsbDevice (FilePath, ParentDevicePathSize, &HandleCount); + NextFullPath = NULL; + GetNext = (BOOLEAN)(FullPath == NULL); + ParentDevicePathSize = (UINTN)ShortformNode - (UINTN)FilePath; + RemainingDevicePath = NextDevicePathNode (ShortformNode); + Handles = BmFindUsbDevice (FilePath, ParentDevicePathSize, &HandleCount); for (Index = 0; Index < HandleCount; Index++) { FilePath = AppendDevicePath (DevicePathFromHandle (Handles[Index]), RemainingDevicePath); @@ -601,6 +625,7 @@ BmExpandUsbDevicePath ( // continue; } + NextFullPath = BmGetNextLoadOptionDevicePath (FilePath, NULL); FreePool (FilePath); if (NextFullPath == NULL) { @@ -609,6 +634,7 @@ BmExpandUsbDevicePath ( // continue; } + if (GetNext) { break; } else { @@ -638,27 +664,27 @@ BmExpandUsbDevicePath ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandFileDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ) { - EFI_STATUS Status; - UINTN Index; - UINTN HandleCount; - EFI_HANDLE *Handles; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - UINTN MediaType; - EFI_DEVICE_PATH_PROTOCOL *NextFullPath; - BOOLEAN GetNext; + EFI_STATUS Status; + UINTN Index; + UINTN HandleCount; + EFI_HANDLE *Handles; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + UINTN MediaType; + EFI_DEVICE_PATH_PROTOCOL *NextFullPath; + BOOLEAN GetNext; EfiBootManagerConnectAll (); Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiSimpleFileSystemProtocolGuid, NULL, &HandleCount, &Handles); if (EFI_ERROR (Status)) { HandleCount = 0; - Handles = NULL; + Handles = NULL; } - GetNext = (BOOLEAN)(FullPath == NULL); + GetNext = (BOOLEAN)(FullPath == NULL); NextFullPath = NULL; // // Enumerate all removable media devices followed by all fixed media devices, @@ -666,14 +692,16 @@ BmExpandFileDevicePath ( // for (MediaType = 0; MediaType < 3; MediaType++) { for (Index = 0; Index < HandleCount; Index++) { - Status = gBS->HandleProtocol (Handles[Index], &gEfiBlockIoProtocolGuid, (VOID *) &BlockIo); + Status = gBS->HandleProtocol (Handles[Index], &gEfiBlockIoProtocolGuid, (VOID *)&BlockIo); if (EFI_ERROR (Status)) { BlockIo = NULL; } - if ((MediaType == 0 && BlockIo != NULL && BlockIo->Media->RemovableMedia) || - (MediaType == 1 && BlockIo != NULL && !BlockIo->Media->RemovableMedia) || - (MediaType == 2 && BlockIo == NULL) - ) { + + if (((MediaType == 0) && (BlockIo != NULL) && BlockIo->Media->RemovableMedia) || + ((MediaType == 1) && (BlockIo != NULL) && !BlockIo->Media->RemovableMedia) || + ((MediaType == 2) && (BlockIo == NULL)) + ) + { NextFullPath = AppendDevicePath (DevicePathFromHandle (Handles[Index]), FilePath); if (GetNext) { break; @@ -684,6 +712,7 @@ BmExpandFileDevicePath ( } } } + if (NextFullPath != NULL) { break; } @@ -709,27 +738,27 @@ BmExpandFileDevicePath ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandUriDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ) { - EFI_STATUS Status; - UINTN Index; - UINTN HandleCount; - EFI_HANDLE *Handles; - EFI_DEVICE_PATH_PROTOCOL *NextFullPath; - EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; - BOOLEAN GetNext; + EFI_STATUS Status; + UINTN Index; + UINTN HandleCount; + EFI_HANDLE *Handles; + EFI_DEVICE_PATH_PROTOCOL *NextFullPath; + EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; + BOOLEAN GetNext; EfiBootManagerConnectAll (); Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiLoadFileProtocolGuid, NULL, &HandleCount, &Handles); if (EFI_ERROR (Status)) { HandleCount = 0; - Handles = NULL; + Handles = NULL; } NextFullPath = NULL; - GetNext = (BOOLEAN)(FullPath == NULL); + GetNext = (BOOLEAN)(FullPath == NULL); for (Index = 0; Index < HandleCount; Index++) { NextFullPath = BmExpandLoadFile (Handles[Index], FilePath); @@ -749,6 +778,7 @@ BmExpandUriDevicePath ( BmDestroyRamDisk (RamDiskDevicePath); FreePool (RamDiskDevicePath); } + FreePool (NextFullPath); NextFullPath = NULL; } @@ -769,15 +799,15 @@ BmExpandUriDevicePath ( **/ VOID BmCachePartitionDevicePath ( - IN OUT EFI_DEVICE_PATH_PROTOCOL **CachedDevicePath, - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN OUT EFI_DEVICE_PATH_PROTOCOL **CachedDevicePath, + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - UINTN Count; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + UINTN Count; if (BmMatchDevicePaths (*CachedDevicePath, DevicePath)) { - TempDevicePath = *CachedDevicePath; + TempDevicePath = *CachedDevicePath; *CachedDevicePath = BmDelPartMatchInstance (*CachedDevicePath, DevicePath); FreePool (TempDevicePath); } @@ -787,7 +817,7 @@ BmCachePartitionDevicePath ( return; } - TempDevicePath = *CachedDevicePath; + TempDevicePath = *CachedDevicePath; *CachedDevicePath = AppendDevicePathInstance (DevicePath, *CachedDevicePath); if (TempDevicePath != NULL) { FreePool (TempDevicePath); @@ -797,7 +827,7 @@ BmCachePartitionDevicePath ( // Here limit the device path instance number to 12, which is max number for a system support 3 IDE controller // If the user try to boot many OS in different HDs or partitions, in theory, the 'HDDP' variable maybe become larger and larger. // - Count = 0; + Count = 0; TempDevicePath = *CachedDevicePath; while (!IsDevicePathEnd (TempDevicePath)) { TempDevicePath = NextDevicePathNode (TempDevicePath); @@ -807,6 +837,7 @@ BmCachePartitionDevicePath ( while (!IsDevicePathEndType (TempDevicePath)) { TempDevicePath = NextDevicePathNode (TempDevicePath); } + Count++; // // If the CachedDevicePath variable contain too much instance, only remain 12 instances. @@ -855,7 +886,7 @@ BmExpandPartitionDevicePath ( // If exist, search the front path which point to partition node in the variable instants. // If fail to find or 'HDDP' not exist, reconnect all and search in all system // - GetVariable2 (L"HDDP", &mBmHardDriveBootVariableGuid, (VOID **) &CachedDevicePath, &CachedDevicePathSize); + GetVariable2 (L"HDDP", &mBmHardDriveBootVariableGuid, (VOID **)&CachedDevicePath, &CachedDevicePathSize); // // Delete the invalid 'HDDP' variable. @@ -863,28 +894,28 @@ BmExpandPartitionDevicePath ( if ((CachedDevicePath != NULL) && !IsDevicePathValid (CachedDevicePath, CachedDevicePathSize)) { FreePool (CachedDevicePath); CachedDevicePath = NULL; - Status = gRT->SetVariable ( - L"HDDP", - &mBmHardDriveBootVariableGuid, - 0, - 0, - NULL - ); + Status = gRT->SetVariable ( + L"HDDP", + &mBmHardDriveBootVariableGuid, + 0, + 0, + NULL + ); ASSERT_EFI_ERROR (Status); } FullPath = NULL; if (CachedDevicePath != NULL) { TempNewDevicePath = CachedDevicePath; - NeedAdjust = FALSE; + NeedAdjust = FALSE; do { // // Check every instance of the variable // First, check whether the instance contain the partition node, which is needed for distinguishing multi // partial partition boot option. Second, check whether the instance could be connected. // - Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size); - if (BmMatchPartitionDevicePathNode (Instance, (HARDDRIVE_DEVICE_PATH *) FilePath)) { + Instance = GetNextDevicePathInstance (&TempNewDevicePath, &Size); + if (BmMatchPartitionDevicePathNode (Instance, (HARDDRIVE_DEVICE_PATH *)FilePath)) { // // Connect the device path instance, the device path point to hard drive media device path node // e.g. ACPI() /PCI()/ATA()/Partition() @@ -916,12 +947,12 @@ BmExpandPartitionDevicePath ( // Failing to save only impacts performance next time expanding the short-form device path // Status = gRT->SetVariable ( - L"HDDP", - &mBmHardDriveBootVariableGuid, - EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE, - GetDevicePathSize (CachedDevicePath), - CachedDevicePath - ); + L"HDDP", + &mBmHardDriveBootVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE, + GetDevicePathSize (CachedDevicePath), + CachedDevicePath + ); } FreePool (Instance); @@ -930,11 +961,12 @@ BmExpandPartitionDevicePath ( } } } + // // Come here means the first instance is not matched // NeedAdjust = TRUE; - FreePool(Instance); + FreePool (Instance); } while (TempNewDevicePath != NULL); } @@ -948,6 +980,7 @@ BmExpandPartitionDevicePath ( BlockIoHandleCount = 0; BlockIoBuffer = NULL; } + // // Loop through all the device handles that support the BLOCK_IO Protocol // @@ -957,12 +990,12 @@ BmExpandPartitionDevicePath ( continue; } - if (BmMatchPartitionDevicePathNode (BlockIoDevicePath, (HARDDRIVE_DEVICE_PATH *) FilePath)) { + if (BmMatchPartitionDevicePathNode (BlockIoDevicePath, (HARDDRIVE_DEVICE_PATH *)FilePath)) { // // Find the matched partition device path // TempDevicePath = AppendDevicePath (BlockIoDevicePath, NextDevicePathNode (FilePath)); - FullPath = BmGetNextLoadOptionDevicePath (TempDevicePath, NULL); + FullPath = BmGetNextLoadOptionDevicePath (TempDevicePath, NULL); FreePool (TempDevicePath); if (FullPath != NULL) { @@ -988,9 +1021,11 @@ BmExpandPartitionDevicePath ( if (CachedDevicePath != NULL) { FreePool (CachedDevicePath); } + if (BlockIoBuffer != NULL) { FreePool (BlockIoBuffer); } + return FullPath; } @@ -1007,29 +1042,29 @@ BmExpandPartitionDevicePath ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandMediaDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ) { - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - VOID *Buffer; - EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; - EFI_DEVICE_PATH_PROTOCOL *NextFullPath; - UINTN Size; - UINTN TempSize; - EFI_HANDLE *SimpleFileSystemHandles; - UINTN NumberSimpleFileSystemHandles; - UINTN Index; - BOOLEAN GetNext; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + VOID *Buffer; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; + EFI_DEVICE_PATH_PROTOCOL *NextFullPath; + UINTN Size; + UINTN TempSize; + EFI_HANDLE *SimpleFileSystemHandles; + UINTN NumberSimpleFileSystemHandles; + UINTN Index; + BOOLEAN GetNext; GetNext = (BOOLEAN)(FullPath == NULL); // // Check whether the device is connected // TempDevicePath = DevicePath; - Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle); + Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &TempDevicePath, &Handle); if (!EFI_ERROR (Status)) { ASSERT (IsDevicePathEnd (TempDevicePath)); @@ -1062,20 +1097,21 @@ BmExpandMediaDevicePath ( // returned. After the Block IO protocol is reinstalled, subsequent // Block IO read/write will success. // - Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo); + Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { return NULL; } + Buffer = AllocatePool (BlockIo->Media->BlockSize); if (Buffer != NULL) { BlockIo->ReadBlocks ( - BlockIo, - BlockIo->Media->MediaId, - 0, - BlockIo->Media->BlockSize, - Buffer - ); + BlockIo, + BlockIo->Media->MediaId, + 0, + BlockIo->Media->BlockSize, + Buffer + ); FreePool (Buffer); } @@ -1083,7 +1119,7 @@ BmExpandMediaDevicePath ( // Detect the the default boot file from removable Media // NextFullPath = NULL; - Size = GetDevicePathSize (DevicePath) - END_DEVICE_PATH_LENGTH; + Size = GetDevicePathSize (DevicePath) - END_DEVICE_PATH_LENGTH; gBS->LocateHandleBuffer ( ByProtocol, &gEfiSimpleFileSystemProtocolGuid, @@ -1096,7 +1132,7 @@ BmExpandMediaDevicePath ( // Get the device path size of SimpleFileSystem handle // TempDevicePath = DevicePathFromHandle (SimpleFileSystemHandles[Index]); - TempSize = GetDevicePathSize (TempDevicePath) - END_DEVICE_PATH_LENGTH; + TempSize = GetDevicePathSize (TempDevicePath) - END_DEVICE_PATH_LENGTH; // // Check whether the device path of boot option is part of the SimpleFileSystem handle's device path // @@ -1128,13 +1164,14 @@ BmExpandMediaDevicePath ( **/ BOOLEAN BmMatchHttpBootDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *Left, - IN EFI_DEVICE_PATH_PROTOCOL *Right + IN EFI_DEVICE_PATH_PROTOCOL *Left, + IN EFI_DEVICE_PATH_PROTOCOL *Right ) { - for (; !IsDevicePathEnd (Left) && !IsDevicePathEnd (Right) - ; Left = NextDevicePathNode (Left), Right = NextDevicePathNode (Right) - ) { + for ( ; !IsDevicePathEnd (Left) && !IsDevicePathEnd (Right) + ; Left = NextDevicePathNode (Left), Right = NextDevicePathNode (Right) + ) + { if (CompareMem (Left, Right, DevicePathNodeLength (Left)) != 0) { if ((DevicePathType (Left) != MESSAGING_DEVICE_PATH) || (DevicePathType (Right) != MESSAGING_DEVICE_PATH)) { return FALSE; @@ -1151,12 +1188,14 @@ BmMatchHttpBootDevicePath ( if (((DevicePathSubType (Left) != MSG_IPv4_DP) || (DevicePathSubType (Right) != MSG_IPv4_DP)) && ((DevicePathSubType (Left) != MSG_IPv6_DP) || (DevicePathSubType (Right) != MSG_IPv6_DP)) && ((DevicePathSubType (Left) != MSG_URI_DP) || (DevicePathSubType (Right) != MSG_URI_DP)) - ) { + ) + { return FALSE; } } } - return (BOOLEAN) (IsDevicePathEnd (Left) && IsDevicePathEnd (Right)); + + return (BOOLEAN)(IsDevicePathEnd (Left) && IsDevicePathEnd (Right)); } /** @@ -1170,16 +1209,16 @@ BmMatchHttpBootDevicePath ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandNetworkFileSystem ( - IN EFI_HANDLE LoadFileHandle, - OUT EFI_HANDLE *RamDiskHandle + IN EFI_HANDLE LoadFileHandle, + OUT EFI_HANDLE *RamDiskHandle ) { - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *Node; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -1189,17 +1228,18 @@ BmExpandNetworkFileSystem ( &Handles ); if (EFI_ERROR (Status)) { - Handles = NULL; + Handles = NULL; HandleCount = 0; } Handle = NULL; for (Index = 0; Index < HandleCount; Index++) { - Node = DevicePathFromHandle (Handles[Index]); + Node = DevicePathFromHandle (Handles[Index]); Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &Node, &Handle); if (!EFI_ERROR (Status) && (Handle == LoadFileHandle) && - (DevicePathType (Node) == MEDIA_DEVICE_PATH) && (DevicePathSubType (Node) == MEDIA_RAM_DISK_DP)) { + (DevicePathType (Node) == MEDIA_DEVICE_PATH) && (DevicePathSubType (Node) == MEDIA_RAM_DISK_DP)) + { // // Find the BlockIo instance populated from the LoadFile. // @@ -1238,28 +1278,28 @@ BmExpandNetworkFileSystem ( **/ EFI_DEVICE_PATH_PROTOCOL * BmGetRamDiskDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; - EFI_DEVICE_PATH_PROTOCOL *Node; - EFI_HANDLE Handle; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; + EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_HANDLE Handle; - Node = FilePath; + Node = FilePath; Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &Node, &Handle); if (!EFI_ERROR (Status) && (DevicePathType (Node) == MEDIA_DEVICE_PATH) && (DevicePathSubType (Node) == MEDIA_RAM_DISK_DP) - ) { - + ) + { // // Construct the device path pointing to RAM Disk // - Node = NextDevicePathNode (Node); + Node = NextDevicePathNode (Node); RamDiskDevicePath = DuplicateDevicePath (FilePath); ASSERT (RamDiskDevicePath != NULL); - SetDevicePathEndNode ((VOID *) ((UINTN) RamDiskDevicePath + ((UINTN) Node - (UINTN) FilePath))); + SetDevicePathEndNode ((VOID *)((UINTN)RamDiskDevicePath + ((UINTN)Node - (UINTN)FilePath))); return RamDiskDevicePath; } @@ -1276,15 +1316,14 @@ BmGetRamDiskDevicePath ( **/ VOID * BmGetRamDiskMemoryInfo ( - IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath, - OUT UINTN *RamDiskSizeInPages + IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath, + OUT UINTN *RamDiskSizeInPages ) { - - EFI_STATUS Status; - EFI_HANDLE Handle; - UINT64 StartingAddr; - UINT64 EndingAddr; + EFI_STATUS Status; + EFI_HANDLE Handle; + UINT64 StartingAddr; + UINT64 EndingAddr; ASSERT (RamDiskDevicePath != NULL); @@ -1295,12 +1334,14 @@ BmGetRamDiskMemoryInfo ( // Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &RamDiskDevicePath, &Handle); ASSERT_EFI_ERROR (Status); - ASSERT ((DevicePathType (RamDiskDevicePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (RamDiskDevicePath) == MEDIA_RAM_DISK_DP)); - StartingAddr = ReadUnaligned64 ((UINT64 *) ((MEDIA_RAM_DISK_DEVICE_PATH *) RamDiskDevicePath)->StartingAddr); - EndingAddr = ReadUnaligned64 ((UINT64 *) ((MEDIA_RAM_DISK_DEVICE_PATH *) RamDiskDevicePath)->EndingAddr); - *RamDiskSizeInPages = EFI_SIZE_TO_PAGES ((UINTN) (EndingAddr - StartingAddr + 1)); - return (VOID *) (UINTN) StartingAddr; + ASSERT ( + (DevicePathType (RamDiskDevicePath) == MEDIA_DEVICE_PATH) && + (DevicePathSubType (RamDiskDevicePath) == MEDIA_RAM_DISK_DP) + ); + StartingAddr = ReadUnaligned64 ((UINT64 *)((MEDIA_RAM_DISK_DEVICE_PATH *)RamDiskDevicePath)->StartingAddr); + EndingAddr = ReadUnaligned64 ((UINT64 *)((MEDIA_RAM_DISK_DEVICE_PATH *)RamDiskDevicePath)->EndingAddr); + *RamDiskSizeInPages = EFI_SIZE_TO_PAGES ((UINTN)(EndingAddr - StartingAddr + 1)); + return (VOID *)(UINTN)StartingAddr; } /** @@ -1314,12 +1355,12 @@ BmGetRamDiskMemoryInfo ( **/ VOID BmDestroyRamDisk ( - IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath + IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath ) { - EFI_STATUS Status; - VOID *RamDiskBuffer; - UINTN RamDiskSizeInPages; + EFI_STATUS Status; + VOID *RamDiskBuffer; + UINTN RamDiskSizeInPages; ASSERT (RamDiskDevicePath != NULL); @@ -1329,9 +1370,10 @@ BmDestroyRamDisk ( // Destroy RAM Disk. // if (mRamDisk == NULL) { - Status = gBS->LocateProtocol (&gEfiRamDiskProtocolGuid, NULL, (VOID *) &mRamDisk); + Status = gBS->LocateProtocol (&gEfiRamDiskProtocolGuid, NULL, (VOID *)&mRamDisk); ASSERT_EFI_ERROR (Status); } + Status = mRamDisk->Unregister (RamDiskDevicePath); ASSERT_EFI_ERROR (Status); FreePages (RamDiskBuffer, RamDiskSizeInPages); @@ -1347,21 +1389,21 @@ BmDestroyRamDisk ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandLoadFile ( - IN EFI_HANDLE LoadFileHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_HANDLE LoadFileHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - EFI_STATUS Status; - EFI_LOAD_FILE_PROTOCOL *LoadFile; - VOID *FileBuffer; - EFI_HANDLE RamDiskHandle; - UINTN BufferSize; - EFI_DEVICE_PATH_PROTOCOL *FullPath; + EFI_STATUS Status; + EFI_LOAD_FILE_PROTOCOL *LoadFile; + VOID *FileBuffer; + EFI_HANDLE RamDiskHandle; + UINTN BufferSize; + EFI_DEVICE_PATH_PROTOCOL *FullPath; Status = gBS->OpenProtocol ( LoadFileHandle, &gEfiLoadFileProtocolGuid, - (VOID **) &LoadFile, + (VOID **)&LoadFile, gImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -1370,7 +1412,7 @@ BmExpandLoadFile ( FileBuffer = NULL; BufferSize = 0; - Status = LoadFile->LoadFile (LoadFile, FilePath, TRUE, &BufferSize, FileBuffer); + Status = LoadFile->LoadFile (LoadFile, FilePath, TRUE, &BufferSize, FileBuffer); if ((Status != EFI_WARN_FILE_SYSTEM) && (Status != EFI_BUFFER_TOO_SMALL)) { return NULL; } @@ -1388,35 +1430,38 @@ BmExpandLoadFile ( FileBuffer = AllocateReservedPages (EFI_SIZE_TO_PAGES (BufferSize)); if (FileBuffer == NULL) { DEBUG_CODE_BEGIN (); - EFI_DEVICE_PATH *LoadFilePath; - CHAR16 *LoadFileText; - CHAR16 *FileText; + EFI_DEVICE_PATH *LoadFilePath; + CHAR16 *LoadFileText; + CHAR16 *FileText; + + LoadFilePath = DevicePathFromHandle (LoadFileHandle); + if (LoadFilePath == NULL) { + LoadFileText = NULL; + } else { + LoadFileText = ConvertDevicePathToText (LoadFilePath, FALSE, FALSE); + } + + FileText = ConvertDevicePathToText (FilePath, FALSE, FALSE); + + DEBUG (( + DEBUG_ERROR, + "%a:%a: failed to allocate reserved pages: " + "BufferSize=%Lu LoadFile=\"%s\" FilePath=\"%s\"\n", + gEfiCallerBaseName, + __FUNCTION__, + (UINT64)BufferSize, + LoadFileText, + FileText + )); + + if (FileText != NULL) { + FreePool (FileText); + } + + if (LoadFileText != NULL) { + FreePool (LoadFileText); + } - LoadFilePath = DevicePathFromHandle (LoadFileHandle); - if (LoadFilePath == NULL) { - LoadFileText = NULL; - } else { - LoadFileText = ConvertDevicePathToText (LoadFilePath, FALSE, FALSE); - } - FileText = ConvertDevicePathToText (FilePath, FALSE, FALSE); - - DEBUG (( - DEBUG_ERROR, - "%a:%a: failed to allocate reserved pages: " - "BufferSize=%Lu LoadFile=\"%s\" FilePath=\"%s\"\n", - gEfiCallerBaseName, - __FUNCTION__, - (UINT64)BufferSize, - LoadFileText, - FileText - )); - - if (FileText != NULL) { - FreePool (FileText); - } - if (LoadFileText != NULL) { - FreePool (LoadFileText); - } DEBUG_CODE_END (); return NULL; } @@ -1459,20 +1504,20 @@ BmExpandLoadFile ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandLoadFiles ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ) { - EFI_STATUS Status; - EFI_HANDLE Handle; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN Index; - EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN Index; + EFI_DEVICE_PATH_PROTOCOL *Node; // // Get file buffer from load file instance. // - Node = FilePath; + Node = FilePath; Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &Node, &Handle); if (!EFI_ERROR (Status) && IsDevicePathEnd (Node)) { // @@ -1494,15 +1539,17 @@ BmExpandLoadFiles ( &Handles ); if (EFI_ERROR (Status)) { - Handles = NULL; + Handles = NULL; HandleCount = 0; } + for (Index = 0; Index < HandleCount; Index++) { if (BmMatchHttpBootDevicePath (DevicePathFromHandle (Handles[Index]), FilePath)) { Handle = Handles[Index]; break; } } + if (Handles != NULL) { FreePool (Handles); } @@ -1530,9 +1577,9 @@ BmExpandLoadFiles ( VOID * EFIAPI EfiBootManagerGetLoadOptionBuffer ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, - OUT UINTN *FileSize + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, + OUT UINTN *FileSize ) { *FullPath = NULL; @@ -1557,20 +1604,20 @@ EfiBootManagerGetLoadOptionBuffer ( **/ EFI_DEVICE_PATH_PROTOCOL * BmGetNextLoadOptionDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ) { - EFI_HANDLE Handle; - EFI_DEVICE_PATH_PROTOCOL *Node; - EFI_STATUS Status; + EFI_HANDLE Handle; + EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_STATUS Status; ASSERT (FilePath != NULL); // // Boot from media device by adding a default file name \EFI\BOOT\BOOT{machine type short-name}.EFI // - Node = FilePath; + Node = FilePath; Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &Node, &Handle); if (EFI_ERROR (Status)) { Status = gBS->LocateDevicePath (&gEfiBlockIoProtocolGuid, &Node, &Handle); @@ -1584,7 +1631,8 @@ BmGetNextLoadOptionDevicePath ( // Expand the short-form device path to full device path // if ((DevicePathType (FilePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (FilePath) == MEDIA_HARDDRIVE_DP)) { + (DevicePathSubType (FilePath) == MEDIA_HARDDRIVE_DP)) + { // // Expand the Harddrive device path // @@ -1594,19 +1642,21 @@ BmGetNextLoadOptionDevicePath ( return NULL; } } else if ((DevicePathType (FilePath) == MEDIA_DEVICE_PATH) && - (DevicePathSubType (FilePath) == MEDIA_FILEPATH_DP)) { + (DevicePathSubType (FilePath) == MEDIA_FILEPATH_DP)) + { // // Expand the File-path device path // return BmExpandFileDevicePath (FilePath, FullPath); } else if ((DevicePathType (FilePath) == MESSAGING_DEVICE_PATH) && - (DevicePathSubType (FilePath) == MSG_URI_DP)) { + (DevicePathSubType (FilePath) == MSG_URI_DP)) + { // // Expand the URI device path // return BmExpandUriDevicePath (FilePath, FullPath); } else { - Node = FilePath; + Node = FilePath; Status = gBS->LocateDevicePath (&gEfiUsbIoProtocolGuid, &Node, &Handle); if (EFI_ERROR (Status)) { // @@ -1616,7 +1666,8 @@ BmGetNextLoadOptionDevicePath ( // for (Node = FilePath; !IsDevicePathEnd (Node); Node = NextDevicePathNode (Node)) { if ((DevicePathType (Node) == MESSAGING_DEVICE_PATH) && - ((DevicePathSubType (Node) == MSG_USB_CLASS_DP) || (DevicePathSubType (Node) == MSG_USB_WWID_DP))) { + ((DevicePathSubType (Node) == MSG_USB_CLASS_DP) || (DevicePathSubType (Node) == MSG_USB_WWID_DP))) + { break; } } @@ -1633,6 +1684,7 @@ BmGetNextLoadOptionDevicePath ( // BmConnectUsbShortFormDevicePath (FilePath); } + return BmExpandUsbDevicePath (FilePath, FullPath, Node); } } @@ -1678,16 +1730,16 @@ BmGetNextLoadOptionDevicePath ( **/ BOOLEAN BmIsBootManagerMenuFilePath ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath -) + EFI_DEVICE_PATH_PROTOCOL *DevicePath + ) { - EFI_HANDLE FvHandle; - VOID *NameGuid; - EFI_STATUS Status; + EFI_HANDLE FvHandle; + VOID *NameGuid; + EFI_STATUS Status; Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &DevicePath, &FvHandle); if (!EFI_ERROR (Status)) { - NameGuid = EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) DevicePath); + NameGuid = EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *)DevicePath); if (NameGuid != NULL) { return CompareGuid (NameGuid, PcdGetPtr (PcdBootManagerMenuFile)); } @@ -1712,11 +1764,11 @@ BmIsBootManagerMenuFilePath ( **/ VOID BmReportLoadFailure ( - IN UINT32 ErrorCode, - IN EFI_STATUS FailureStatus + IN UINT32 ErrorCode, + IN EFI_STATUS FailureStatus ) { - EFI_RETURN_STATUS_EXTENDED_DATA ExtendedData; + EFI_RETURN_STATUS_EXTENDED_DATA ExtendedData; if (!ReportErrorCodeEnabled ()) { return; @@ -1764,27 +1816,27 @@ BmReportLoadFailure ( VOID EFIAPI EfiBootManagerBoot ( - IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { - EFI_STATUS Status; - EFI_HANDLE ImageHandle; - EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; - UINT16 Uint16; - UINTN OptionNumber; - UINTN OriginalOptionNumber; - EFI_DEVICE_PATH_PROTOCOL *FilePath; - EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; - VOID *FileBuffer; - UINTN FileSize; - EFI_BOOT_LOGO_PROTOCOL *BootLogo; - EFI_EVENT LegacyBootEvent; + EFI_STATUS Status; + EFI_HANDLE ImageHandle; + EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; + UINT16 Uint16; + UINTN OptionNumber; + UINTN OriginalOptionNumber; + EFI_DEVICE_PATH_PROTOCOL *FilePath; + EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; + VOID *FileBuffer; + UINTN FileSize; + EFI_BOOT_LOGO_PROTOCOL *BootLogo; + EFI_EVENT LegacyBootEvent; if (BootOption == NULL) { return; } - if (BootOption->FilePath == NULL || BootOption->OptionType != LoadOptionTypeBoot) { + if ((BootOption->FilePath == NULL) || (BootOption->OptionType != LoadOptionTypeBoot)) { BootOption->Status = EFI_INVALID_PARAMETER; return; } @@ -1802,21 +1854,21 @@ EfiBootManagerBoot ( OptionNumber = Uint16; OriginalOptionNumber = BootOption->OptionNumber; BootOption->OptionNumber = OptionNumber; - Status = EfiBootManagerLoadOptionToVariable (BootOption); + Status = EfiBootManagerLoadOptionToVariable (BootOption); BootOption->OptionNumber = OriginalOptionNumber; } if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "[Bds] Failed to create Boot#### for a temporary boot - %r!\n", Status)); BootOption->Status = Status; - return ; + return; } } // // 2. Set BootCurrent // - Uint16 = (UINT16) OptionNumber; + Uint16 = (UINT16)OptionNumber; BmSetVariableAndReportStatusCodeOnError ( L"BootCurrent", &gEfiGlobalVariableGuid, @@ -1833,7 +1885,7 @@ EfiBootManagerBoot ( DEBUG ((DEBUG_INFO, "[Bds] Booting Boot Manager Menu.\n")); BmStopHotkeyService (NULL, NULL); } else { - EfiSignalEventReadyToBoot(); + EfiSignalEventReadyToBoot (); // // Report Status Code to indicate ReadyToBoot was signalled // @@ -1844,15 +1896,15 @@ EfiBootManagerBoot ( BmRepairAllControllers (0); } - PERF_START_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber); + PERF_START_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32)OptionNumber); // // 5. Adjust the different type memory page number just before booting // and save the updated info into the variable for next boot to use // BmSetMemoryTypeInformationVariable ( - (BOOLEAN) ((BootOption->Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_BOOT) - ); + (BOOLEAN)((BootOption->Attributes & LOAD_OPTION_CATEGORY) == LOAD_OPTION_CATEGORY_BOOT) + ); // // 6. Load EFI boot option to ImageHandle @@ -1863,6 +1915,7 @@ EfiBootManagerBoot ( } else { DEBUG ((DEBUG_INFO | DEBUG_LOAD, "[Bds]Booting %s\n", BootOption->Description)); } + DEBUG_CODE_END (); ImageHandle = NULL; @@ -1885,9 +1938,11 @@ EfiBootManagerBoot ( &ImageHandle ); } + if (FileBuffer != NULL) { FreePool (FileBuffer); } + if (FilePath != NULL) { FreePool (FilePath); } @@ -1902,6 +1957,7 @@ EfiBootManagerBoot ( if (Status == EFI_SECURITY_VIOLATION) { gBS->UnloadImage (ImageHandle); } + // // Destroy the RAM disk // @@ -1909,6 +1965,7 @@ EfiBootManagerBoot ( BmDestroyRamDisk (RamDiskDevicePath); FreePool (RamDiskDevicePath); } + // // Report Status Code with the failure status to indicate that the failure to load boot option // @@ -1931,28 +1988,28 @@ EfiBootManagerBoot ( // // Create an event to be signalled when Legacy Boot occurs to write performance data. // - Status = EfiCreateEventLegacyBootEx( + Status = EfiCreateEventLegacyBootEx ( TPL_NOTIFY, BmEndOfBdsPerfCode, NULL, &LegacyBootEvent ); ASSERT_EFI_ERROR (Status); - ); + ); mBmLegacyBoot (BootOption); } else { BootOption->Status = EFI_UNSUPPORTED; } - PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber); + PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32)OptionNumber); return; } // // Provide the image with its load options // - Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **) &ImageInfo); + Status = gBS->HandleProtocol (ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID **)&ImageInfo); ASSERT_EFI_ERROR (Status); if (!BmIsAutoCreateBootOption (BootOption)) { @@ -1975,7 +2032,7 @@ EfiBootManagerBoot ( // PERF_CODE ( BmEndOfBdsPerfCode (NULL, NULL); - ); + ); REPORT_STATUS_CODE (EFI_PROGRESS_CODE, PcdGet32 (PcdProgressCodeOsLoaderStart)); @@ -1997,8 +2054,8 @@ EfiBootManagerBoot ( // BmReportLoadFailure (EFI_SW_DXE_BS_EC_BOOT_OPTION_FAILED, Status); } - PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32) OptionNumber); + PERF_END_EX (gImageHandle, "BdsAttempt", NULL, 0, (UINT32)OptionNumber); // // Clear the Watchdog Timer after the image returns @@ -2009,7 +2066,7 @@ EfiBootManagerBoot ( // Set Logo status invalid after trying one boot option // BootLogo = NULL; - Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **) &BootLogo); + Status = gBS->LocateProtocol (&gEfiBootLogoProtocolGuid, NULL, (VOID **)&BootLogo); if (!EFI_ERROR (Status) && (BootLogo != NULL)) { Status = BootLogo->SetBootLogo (BootLogo, NULL, 0, 0, 0, 0); ASSERT_EFI_ERROR (Status); @@ -2047,11 +2104,11 @@ EfiBootManagerBoot ( **/ BOOLEAN BmMatchPartitionDevicePathNode ( - IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath, - IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath + IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath, + IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath ) { - HARDDRIVE_DEVICE_PATH *Node; + HARDDRIVE_DEVICE_PATH *Node; if ((BlockIoDevicePath == NULL) || (HardDriveDevicePath == NULL)) { return FALSE; @@ -2063,11 +2120,12 @@ BmMatchPartitionDevicePathNode ( while (!IsDevicePathEnd (BlockIoDevicePath)) { if ((DevicePathType (BlockIoDevicePath) == MEDIA_DEVICE_PATH) && (DevicePathSubType (BlockIoDevicePath) == MEDIA_HARDDRIVE_DP) - ) { + ) + { // // See if the harddrive device path in blockio matches the orig Hard Drive Node // - Node = (HARDDRIVE_DEVICE_PATH *) BlockIoDevicePath; + Node = (HARDDRIVE_DEVICE_PATH *)BlockIoDevicePath; // // Match Signature and PartitionNumber. @@ -2076,7 +2134,8 @@ BmMatchPartitionDevicePathNode ( if ((Node->PartitionNumber == HardDriveDevicePath->PartitionNumber) && (Node->MBRType == HardDriveDevicePath->MBRType) && (Node->SignatureType == HardDriveDevicePath->SignatureType) && - (CompareMem (Node->Signature, HardDriveDevicePath->Signature, sizeof (Node->Signature)) == 0)) { + (CompareMem (Node->Signature, HardDriveDevicePath->Signature, sizeof (Node->Signature)) == 0)) + { return TRUE; } } @@ -2106,17 +2165,17 @@ BmMatchPartitionDevicePathNode ( **/ EFI_BOOT_MANAGER_LOAD_OPTION * BmEnumerateBootOptions ( - UINTN *BootOptionCount + UINTN *BootOptionCount ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; - UINTN HandleCount; - EFI_HANDLE *Handles; - EFI_BLOCK_IO_PROTOCOL *BlkIo; - UINTN Removable; - UINTN Index; - CHAR16 *Description; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; + UINTN HandleCount; + EFI_HANDLE *Handles; + EFI_BLOCK_IO_PROTOCOL *BlkIo; + UINTN Removable; + UINTN Index; + CHAR16 *Description; ASSERT (BootOptionCount != NULL); @@ -2139,7 +2198,7 @@ BmEnumerateBootOptions ( Status = gBS->HandleProtocol ( Handles[Index], &gEfiBlockIoProtocolGuid, - (VOID **) &BlkIo + (VOID **)&BlkIo ); if (EFI_ERROR (Status)) { continue; @@ -2201,14 +2260,15 @@ BmEnumerateBootOptions ( Status = gBS->HandleProtocol ( Handles[Index], &gEfiBlockIoProtocolGuid, - (VOID **) &BlkIo + (VOID **)&BlkIo ); - if (!EFI_ERROR (Status)) { + if (!EFI_ERROR (Status)) { // // Skip if the file system handle supports a BlkIo protocol, which we've handled in above // continue; } + Description = BmGetBootDescription (Handles[Index]); BootOptions = ReallocatePool ( sizeof (EFI_BOOT_MANAGER_LOAD_OPTION) * (*BootOptionCount), @@ -2292,15 +2352,15 @@ EfiBootManagerRefreshAllBootOption ( VOID ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions; - UINTN NvBootOptionCount; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; - UINTN BootOptionCount; - EFI_BOOT_MANAGER_LOAD_OPTION *UpdatedBootOptions; - UINTN UpdatedBootOptionCount; - UINTN Index; - EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL *PlatformBootManager; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions; + UINTN NvBootOptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; + UINTN BootOptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION *UpdatedBootOptions; + UINTN UpdatedBootOptionCount; + UINTN Index; + EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL *PlatformBootManager; // // Optionally refresh the legacy boot option @@ -2309,7 +2369,7 @@ EfiBootManagerRefreshAllBootOption ( mBmRefreshLegacyBootOption (); } - BootOptions = BmEnumerateBootOptions (&BootOptionCount); + BootOptions = BmEnumerateBootOptions (&BootOptionCount); // // Mark the boot option as added by BDS by setting OptionalData to a special GUID @@ -2322,21 +2382,25 @@ EfiBootManagerRefreshAllBootOption ( // // Locate Platform Boot Options Protocol // - Status = gBS->LocateProtocol (&gEdkiiPlatformBootManagerProtocolGuid, - NULL, - (VOID **)&PlatformBootManager); + Status = gBS->LocateProtocol ( + &gEdkiiPlatformBootManagerProtocolGuid, + NULL, + (VOID **)&PlatformBootManager + ); if (!EFI_ERROR (Status)) { // // If found, call platform specific refresh to all auto enumerated and NV // boot options. // - Status = PlatformBootManager->RefreshAllBootOptions ((CONST EFI_BOOT_MANAGER_LOAD_OPTION *)BootOptions, - (CONST UINTN)BootOptionCount, - &UpdatedBootOptions, - &UpdatedBootOptionCount); + Status = PlatformBootManager->RefreshAllBootOptions ( + (CONST EFI_BOOT_MANAGER_LOAD_OPTION *)BootOptions, + (CONST UINTN)BootOptionCount, + &UpdatedBootOptions, + &UpdatedBootOptionCount + ); if (!EFI_ERROR (Status)) { EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); - BootOptions = UpdatedBootOptions; + BootOptions = UpdatedBootOptions; BootOptionCount = UpdatedBootOptionCount; } } @@ -2349,8 +2413,9 @@ EfiBootManagerRefreshAllBootOption ( for (Index = 0; Index < NvBootOptionCount; Index++) { if (((DevicePathType (NvBootOptions[Index].FilePath) != BBS_DEVICE_PATH) || (DevicePathSubType (NvBootOptions[Index].FilePath) != BBS_BBS_DP) - ) && BmIsAutoCreateBootOption (&NvBootOptions[Index]) - ) { + ) && BmIsAutoCreateBootOption (&NvBootOptions[Index]) + ) + { // // Only check those added by BDS // so that the boot options added by end-user or OS installer won't be deleted @@ -2370,14 +2435,14 @@ EfiBootManagerRefreshAllBootOption ( // for (Index = 0; Index < BootOptionCount; Index++) { if (EfiBootManagerFindLoadOption (&BootOptions[Index], NvBootOptions, NvBootOptionCount) == -1) { - EfiBootManagerAddLoadOptionVariable (&BootOptions[Index], (UINTN) -1); + EfiBootManagerAddLoadOptionVariable (&BootOptions[Index], (UINTN)-1); // // Try best to add the boot options so continue upon failure. // } } - EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); + EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); EfiBootManagerFreeLoadOptions (NvBootOptions, NvBootOptionCount); } @@ -2398,18 +2463,18 @@ EfiBootManagerRefreshAllBootOption ( **/ EFI_STATUS BmRegisterBootManagerMenu ( - OUT EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + OUT EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { - EFI_STATUS Status; - CHAR16 *Description; - UINTN DescriptionLength; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - UINTN HandleCount; - EFI_HANDLE *Handles; - UINTN Index; - - DevicePath = NULL; + EFI_STATUS Status; + CHAR16 *Description; + UINTN DescriptionLength; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + UINTN HandleCount; + EFI_HANDLE *Handles; + UINTN Index; + + DevicePath = NULL; Description = NULL; // // Try to find BootManagerMenu from LoadFile protocol @@ -2428,6 +2493,7 @@ BmRegisterBootManagerMenu ( break; } } + if (HandleCount != 0) { FreePool (Handles); } @@ -2443,6 +2509,7 @@ BmRegisterBootManagerMenu ( DEBUG ((DEBUG_WARN, "[Bds]BootManagerMenu FFS section can not be found, skip its boot option registration\n")); return EFI_NOT_FOUND; } + ASSERT (DevicePath != NULL); // // Get BootManagerMenu application's description from EFI User Interface Section. @@ -2451,7 +2518,7 @@ BmRegisterBootManagerMenu ( PcdGetPtr (PcdBootManagerMenuFile), EFI_SECTION_USER_INTERFACE, 0, - (VOID **) &Description, + (VOID **)&Description, &DescriptionLength ); if (EFI_ERROR (Status)) { @@ -2484,7 +2551,7 @@ BmRegisterBootManagerMenu ( EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); ); - return EfiBootManagerAddLoadOptionVariable (BootOption, (UINTN) -1); + return EfiBootManagerAddLoadOptionVariable (BootOption, (UINTN)-1); } /** @@ -2502,30 +2569,30 @@ BmRegisterBootManagerMenu ( EFI_STATUS EFIAPI EfiBootManagerGetBootManagerMenu ( - EFI_BOOT_MANAGER_LOAD_OPTION *BootOption + EFI_BOOT_MANAGER_LOAD_OPTION *BootOption ) { - EFI_STATUS Status; - UINTN BootOptionCount; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; - UINTN Index; + EFI_STATUS Status; + UINTN BootOptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; + UINTN Index; BootOptions = EfiBootManagerGetLoadOptions (&BootOptionCount, LoadOptionTypeBoot); for (Index = 0; Index < BootOptionCount; Index++) { if (BmIsBootManagerMenuFilePath (BootOptions[Index].FilePath)) { - Status = EfiBootManagerInitializeLoadOption ( - BootOption, - BootOptions[Index].OptionNumber, - BootOptions[Index].OptionType, - BootOptions[Index].Attributes, - BootOptions[Index].Description, - BootOptions[Index].FilePath, - BootOptions[Index].OptionalData, - BootOptions[Index].OptionalDataSize - ); - ASSERT_EFI_ERROR (Status); - break; + Status = EfiBootManagerInitializeLoadOption ( + BootOption, + BootOptions[Index].OptionNumber, + BootOptions[Index].OptionType, + BootOptions[Index].Attributes, + BootOptions[Index].Description, + BootOptions[Index].FilePath, + BootOptions[Index].OptionalData, + BootOptions[Index].OptionalDataSize + ); + ASSERT_EFI_ERROR (Status); + break; } } @@ -2558,9 +2625,9 @@ EfiBootManagerGetBootManagerMenu ( EFI_DEVICE_PATH_PROTOCOL * EFIAPI EfiBootManagerGetNextLoadOptionDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ) { - return BmGetNextLoadOptionDevicePath(FilePath, FullPath); + return BmGetNextLoadOptionDevicePath (FilePath, FullPath); } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c index aa891feb17..fac33b9ee9 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBootDescription.c @@ -9,15 +9,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalBm.h" -#define VENDOR_IDENTIFICATION_OFFSET 3 -#define VENDOR_IDENTIFICATION_LENGTH 8 -#define PRODUCT_IDENTIFICATION_OFFSET 11 -#define PRODUCT_IDENTIFICATION_LENGTH 16 +#define VENDOR_IDENTIFICATION_OFFSET 3 +#define VENDOR_IDENTIFICATION_LENGTH 8 +#define PRODUCT_IDENTIFICATION_OFFSET 11 +#define PRODUCT_IDENTIFICATION_LENGTH 16 -CONST UINT16 mBmUsbLangId = 0x0409; // English -CHAR16 mBmUefiPrefix[] = L"UEFI "; +CONST UINT16 mBmUsbLangId = 0x0409; // English +CHAR16 mBmUefiPrefix[] = L"UEFI "; -LIST_ENTRY mPlatformBootDescriptionHandlers = INITIALIZE_LIST_HEAD_VARIABLE (mPlatformBootDescriptionHandlers); +LIST_ENTRY mPlatformBootDescriptionHandlers = INITIALIZE_LIST_HEAD_VARIABLE (mPlatformBootDescriptionHandlers); /** For a bootable Device path, return its boot type. @@ -39,27 +39,28 @@ LIST_ENTRY mPlatformBootDescriptionHandlers = INITIALIZE_LIST_HEAD_VARIABLE (mPl **/ BM_BOOT_TYPE BmDevicePathType ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_DEVICE_PATH_PROTOCOL *Node; - EFI_DEVICE_PATH_PROTOCOL *NextNode; + EFI_DEVICE_PATH_PROTOCOL *Node; + EFI_DEVICE_PATH_PROTOCOL *NextNode; ASSERT (DevicePath != NULL); for (Node = DevicePath; !IsDevicePathEndType (Node); Node = NextDevicePathNode (Node)) { switch (DevicePathType (Node)) { - case ACPI_DEVICE_PATH: - if (EISA_ID_TO_NUM (((ACPI_HID_DEVICE_PATH *) Node)->HID) == 0x0604) { + if (EISA_ID_TO_NUM (((ACPI_HID_DEVICE_PATH *)Node)->HID) == 0x0604) { return BmAcpiFloppyBoot; } + break; case HARDWARE_DEVICE_PATH: if (DevicePathSubType (Node) == HW_CONTROLLER_DP) { return BmHardwareDeviceBoot; } + break; case MESSAGING_DEVICE_PATH: @@ -70,9 +71,9 @@ BmDevicePathType ( do { NextNode = NextDevicePathNode (NextNode); } while ( - (DevicePathType (NextNode) == MESSAGING_DEVICE_PATH) && - (DevicePathSubType(NextNode) == MSG_DEVICE_LOGICAL_UNIT_DP) - ); + (DevicePathType (NextNode) == MESSAGING_DEVICE_PATH) && + (DevicePathSubType (NextNode) == MSG_DEVICE_LOGICAL_UNIT_DP) + ); // // If the device path not only point to driver device, it is not a messaging device path, @@ -82,21 +83,21 @@ BmDevicePathType ( } switch (DevicePathSubType (Node)) { - case MSG_ATAPI_DP: - return BmMessageAtapiBoot; - break; + case MSG_ATAPI_DP: + return BmMessageAtapiBoot; + break; - case MSG_SATA_DP: - return BmMessageSataBoot; - break; + case MSG_SATA_DP: + return BmMessageSataBoot; + break; - case MSG_USB_DP: - return BmMessageUsbBoot; - break; + case MSG_USB_DP: + return BmMessageUsbBoot; + break; - case MSG_SCSI_DP: - return BmMessageScsiBoot; - break; + case MSG_SCSI_DP: + return BmMessageScsiBoot; + break; } } } @@ -111,17 +112,18 @@ BmDevicePathType ( **/ VOID BmEliminateExtraSpaces ( - IN CHAR16 *Str + IN CHAR16 *Str ) { - UINTN Index; - UINTN ActualIndex; + UINTN Index; + UINTN ActualIndex; for (Index = 0, ActualIndex = 0; Str[Index] != L'\0'; Index++) { if ((Str[Index] != L' ') || ((ActualIndex > 0) && (Str[ActualIndex - 1] != L' '))) { Str[ActualIndex++] = Str[Index]; } } + Str[ActualIndex] = L'\0'; } @@ -134,70 +136,72 @@ BmEliminateExtraSpaces ( **/ CHAR16 * BmGetDescriptionFromDiskInfo ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - UINTN Index; - EFI_STATUS Status; - EFI_DISK_INFO_PROTOCOL *DiskInfo; - UINT32 BufferSize; - EFI_ATAPI_IDENTIFY_DATA IdentifyData; - EFI_SCSI_INQUIRY_DATA InquiryData; - CHAR16 *Description; - UINTN Length; - CONST UINTN ModelNameLength = 40; - CONST UINTN SerialNumberLength = 20; - CHAR8 *StrPtr; - UINT8 Temp; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - - Description = NULL; + UINTN Index; + EFI_STATUS Status; + EFI_DISK_INFO_PROTOCOL *DiskInfo; + UINT32 BufferSize; + EFI_ATAPI_IDENTIFY_DATA IdentifyData; + EFI_SCSI_INQUIRY_DATA InquiryData; + CHAR16 *Description; + UINTN Length; + CONST UINTN ModelNameLength = 40; + CONST UINTN SerialNumberLength = 20; + CHAR8 *StrPtr; + UINT8 Temp; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + + Description = NULL; Status = gBS->HandleProtocol ( Handle, &gEfiDiskInfoProtocolGuid, - (VOID **) &DiskInfo + (VOID **)&DiskInfo ); if (EFI_ERROR (Status)) { return NULL; } if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoAhciInterfaceGuid) || - CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoIdeInterfaceGuid)) { - BufferSize = sizeof (EFI_ATAPI_IDENTIFY_DATA); - Status = DiskInfo->Identify ( - DiskInfo, - &IdentifyData, - &BufferSize - ); + CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoIdeInterfaceGuid)) + { + BufferSize = sizeof (EFI_ATAPI_IDENTIFY_DATA); + Status = DiskInfo->Identify ( + DiskInfo, + &IdentifyData, + &BufferSize + ); if (!EFI_ERROR (Status)) { Description = AllocateZeroPool ((ModelNameLength + SerialNumberLength + 2) * sizeof (CHAR16)); ASSERT (Description != NULL); for (Index = 0; Index + 1 < ModelNameLength; Index += 2) { - Description[Index] = (CHAR16) IdentifyData.ModelName[Index + 1]; - Description[Index + 1] = (CHAR16) IdentifyData.ModelName[Index]; + Description[Index] = (CHAR16)IdentifyData.ModelName[Index + 1]; + Description[Index + 1] = (CHAR16)IdentifyData.ModelName[Index]; } - Length = Index; + Length = Index; Description[Length++] = L' '; for (Index = 0; Index + 1 < SerialNumberLength; Index += 2) { - Description[Length + Index] = (CHAR16) IdentifyData.SerialNo[Index + 1]; - Description[Length + Index + 1] = (CHAR16) IdentifyData.SerialNo[Index]; + Description[Length + Index] = (CHAR16)IdentifyData.SerialNo[Index + 1]; + Description[Length + Index + 1] = (CHAR16)IdentifyData.SerialNo[Index]; } - Length += Index; + + Length += Index; Description[Length++] = L'\0'; ASSERT (Length == ModelNameLength + SerialNumberLength + 2); BmEliminateExtraSpaces (Description); } } else if (CompareGuid (&DiskInfo->Interface, &gEfiDiskInfoScsiInterfaceGuid)) { - BufferSize = sizeof (EFI_SCSI_INQUIRY_DATA); - Status = DiskInfo->Inquiry ( - DiskInfo, - &InquiryData, - &BufferSize - ); + BufferSize = sizeof (EFI_SCSI_INQUIRY_DATA); + Status = DiskInfo->Inquiry ( + DiskInfo, + &InquiryData, + &BufferSize + ); if (!EFI_ERROR (Status)) { Description = AllocateZeroPool ((VENDOR_IDENTIFICATION_LENGTH + PRODUCT_IDENTIFICATION_LENGTH + 2) * sizeof (CHAR16)); ASSERT (Description != NULL); @@ -207,8 +211,8 @@ BmGetDescriptionFromDiskInfo ( // EFI_SCSI_INQUIRY_DATA.Reserved_5_95[11 - 26] save the product identification, // Here combine the vendor identification and product identification to the description. // - StrPtr = (CHAR8 *) (&InquiryData.Reserved_5_95[VENDOR_IDENTIFICATION_OFFSET]); - Temp = StrPtr[VENDOR_IDENTIFICATION_LENGTH]; + StrPtr = (CHAR8 *)(&InquiryData.Reserved_5_95[VENDOR_IDENTIFICATION_OFFSET]); + Temp = StrPtr[VENDOR_IDENTIFICATION_LENGTH]; StrPtr[VENDOR_IDENTIFICATION_LENGTH] = '\0'; AsciiStrToUnicodeStrS (StrPtr, Description, VENDOR_IDENTIFICATION_LENGTH + 1); StrPtr[VENDOR_IDENTIFICATION_LENGTH] = Temp; @@ -218,7 +222,7 @@ BmGetDescriptionFromDiskInfo ( // Description[VENDOR_IDENTIFICATION_LENGTH] = L' '; - StrPtr = (CHAR8 *) (&InquiryData.Reserved_5_95[PRODUCT_IDENTIFICATION_OFFSET]); + StrPtr = (CHAR8 *)(&InquiryData.Reserved_5_95[PRODUCT_IDENTIFICATION_OFFSET]); StrPtr[PRODUCT_IDENTIFICATION_LENGTH] = '\0'; AsciiStrToUnicodeStrS (StrPtr, Description + VENDOR_IDENTIFICATION_LENGTH + 1, PRODUCT_IDENTIFICATION_LENGTH + 1); @@ -233,6 +237,7 @@ BmGetDescriptionFromDiskInfo ( while (!IsDevicePathEnd (DevicePath) && (DevicePathType (DevicePath) != MESSAGING_DEVICE_PATH)) { DevicePath = NextDevicePathNode (DevicePath); } + if (IsDevicePathEnd (DevicePath)) { return NULL; } @@ -260,23 +265,23 @@ BmGetDescriptionFromDiskInfo ( **/ CHAR16 * BmGetUsbDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_USB_IO_PROTOCOL *UsbIo; - CHAR16 NullChar; - CHAR16 *Manufacturer; - CHAR16 *Product; - CHAR16 *SerialNumber; - CHAR16 *Description; - EFI_USB_DEVICE_DESCRIPTOR DevDesc; - UINTN DescMaxSize; + EFI_STATUS Status; + EFI_USB_IO_PROTOCOL *UsbIo; + CHAR16 NullChar; + CHAR16 *Manufacturer; + CHAR16 *Product; + CHAR16 *SerialNumber; + CHAR16 *Description; + EFI_USB_DEVICE_DESCRIPTOR DevDesc; + UINTN DescMaxSize; Status = gBS->HandleProtocol ( Handle, &gEfiUsbIoProtocolGuid, - (VOID **) &UsbIo + (VOID **)&UsbIo ); if (EFI_ERROR (Status)) { return NULL; @@ -322,27 +327,30 @@ BmGetUsbDescription ( if ((Manufacturer == &NullChar) && (Product == &NullChar) && (SerialNumber == &NullChar) - ) { + ) + { return NULL; } DescMaxSize = StrSize (Manufacturer) + StrSize (Product) + StrSize (SerialNumber); Description = AllocateZeroPool (DescMaxSize); ASSERT (Description != NULL); - StrCatS (Description, DescMaxSize/sizeof(CHAR16), Manufacturer); - StrCatS (Description, DescMaxSize/sizeof(CHAR16), L" "); + StrCatS (Description, DescMaxSize/sizeof (CHAR16), Manufacturer); + StrCatS (Description, DescMaxSize/sizeof (CHAR16), L" "); - StrCatS (Description, DescMaxSize/sizeof(CHAR16), Product); - StrCatS (Description, DescMaxSize/sizeof(CHAR16), L" "); + StrCatS (Description, DescMaxSize/sizeof (CHAR16), Product); + StrCatS (Description, DescMaxSize/sizeof (CHAR16), L" "); - StrCatS (Description, DescMaxSize/sizeof(CHAR16), SerialNumber); + StrCatS (Description, DescMaxSize/sizeof (CHAR16), SerialNumber); if (Manufacturer != &NullChar) { FreePool (Manufacturer); } + if (Product != &NullChar) { FreePool (Product); } + if (SerialNumber != &NullChar) { FreePool (SerialNumber); } @@ -361,17 +369,17 @@ BmGetUsbDescription ( **/ CHAR16 * BmGetNetworkDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *DevicePath; - MAC_ADDR_DEVICE_PATH *Mac; - VLAN_DEVICE_PATH *Vlan; - EFI_DEVICE_PATH_PROTOCOL *Ip; - EFI_DEVICE_PATH_PROTOCOL *Uri; - CHAR16 *Description; - UINTN DescriptionSize; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *DevicePath; + MAC_ADDR_DEVICE_PATH *Mac; + VLAN_DEVICE_PATH *Vlan; + EFI_DEVICE_PATH_PROTOCOL *Ip; + EFI_DEVICE_PATH_PROTOCOL *Uri; + CHAR16 *Description; + UINTN DescriptionSize; Status = gBS->OpenProtocol ( Handle, @@ -388,7 +396,7 @@ BmGetNetworkDescription ( Status = gBS->OpenProtocol ( Handle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, gImageHandle, Handle, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -410,7 +418,8 @@ BmGetNetworkDescription ( while (!IsDevicePathEnd (DevicePath) && ((DevicePathType (DevicePath) != MESSAGING_DEVICE_PATH) || (DevicePathSubType (DevicePath) != MSG_MAC_ADDR_DP)) - ) { + ) + { DevicePath = NextDevicePathNode (DevicePath); } @@ -418,7 +427,7 @@ BmGetNetworkDescription ( return NULL; } - Mac = (MAC_ADDR_DEVICE_PATH *) DevicePath; + Mac = (MAC_ADDR_DEVICE_PATH *)DevicePath; DevicePath = NextDevicePathNode (DevicePath); // @@ -426,8 +435,9 @@ BmGetNetworkDescription ( // if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_VLAN_DP) - ) { - Vlan = (VLAN_DEVICE_PATH *) DevicePath; + ) + { + Vlan = (VLAN_DEVICE_PATH *)DevicePath; DevicePath = NextDevicePathNode (DevicePath); } else { Vlan = NULL; @@ -438,7 +448,8 @@ BmGetNetworkDescription ( // if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_WIFI_DP) - ) { + ) + { DevicePath = NextDevicePathNode (DevicePath); } @@ -448,8 +459,9 @@ BmGetNetworkDescription ( if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && ((DevicePathSubType (DevicePath) == MSG_IPv4_DP) || (DevicePathSubType (DevicePath) == MSG_IPv6_DP)) - ) { - Ip = DevicePath; + ) + { + Ip = DevicePath; DevicePath = NextDevicePathNode (DevicePath); } else { Ip = NULL; @@ -460,7 +472,8 @@ BmGetNetworkDescription ( // if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_DNS_DP) - ) { + ) + { DevicePath = NextDevicePathNode (DevicePath); } @@ -469,8 +482,9 @@ BmGetNetworkDescription ( // if ((DevicePathType (DevicePath) == MESSAGING_DEVICE_PATH) && (DevicePathSubType (DevicePath) == MSG_URI_DP) - ) { - Uri = DevicePath; + ) + { + Uri = DevicePath; DevicePath = NextDevicePathNode (DevicePath); } else { Uri = NULL; @@ -485,14 +499,19 @@ BmGetNetworkDescription ( Description = AllocatePool (DescriptionSize); ASSERT (Description != NULL); UnicodeSPrint ( - Description, DescriptionSize, + Description, + DescriptionSize, (Vlan == NULL) ? L"%sv%d (MAC:%02x%02x%02x%02x%02x%02x)" : L"%sv%d (MAC:%02x%02x%02x%02x%02x%02x VLAN%d)", (Uri == NULL) ? L"PXE" : L"HTTP", ((Ip == NULL) || (DevicePathSubType (Ip) == MSG_IPv4_DP)) ? 4 : 6, - Mac->MacAddress.Addr[0], Mac->MacAddress.Addr[1], Mac->MacAddress.Addr[2], - Mac->MacAddress.Addr[3], Mac->MacAddress.Addr[4], Mac->MacAddress.Addr[5], + Mac->MacAddress.Addr[0], + Mac->MacAddress.Addr[1], + Mac->MacAddress.Addr[2], + Mac->MacAddress.Addr[3], + Mac->MacAddress.Addr[4], + Mac->MacAddress.Addr[5], (Vlan == NULL) ? 0 : Vlan->VlanId ); return Description; @@ -507,14 +526,14 @@ BmGetNetworkDescription ( **/ CHAR16 * BmGetLoadFileDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FilePath; - EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; - CHAR16 *Description; - EFI_LOAD_FILE_PROTOCOL *LoadFile; + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FilePath; + EFI_DEVICE_PATH_PROTOCOL *DevicePathNode; + CHAR16 *Description; + EFI_LOAD_FILE_PROTOCOL *LoadFile; Status = gBS->HandleProtocol (Handle, &gEfiLoadFileProtocolGuid, (VOID **)&LoadFile); if (EFI_ERROR (Status)) { @@ -525,14 +544,15 @@ BmGetLoadFileDescription ( // Get the file name // Description = NULL; - Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&FilePath); + Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&FilePath); if (!EFI_ERROR (Status)) { DevicePathNode = FilePath; while (!IsDevicePathEnd (DevicePathNode)) { - if (DevicePathNode->Type == MEDIA_DEVICE_PATH && DevicePathNode->SubType == MEDIA_FILEPATH_DP) { + if ((DevicePathNode->Type == MEDIA_DEVICE_PATH) && (DevicePathNode->SubType == MEDIA_FILEPATH_DP)) { Description = (CHAR16 *)(DevicePathNode + 1); break; } + DevicePathNode = NextDevicePathNode (DevicePathNode); } } @@ -553,21 +573,21 @@ BmGetLoadFileDescription ( **/ CHAR16 * BmGetNvmeDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *NvmePassthru; - EFI_DEV_PATH_PTR DevicePath; - EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; - EFI_NVM_EXPRESS_COMMAND Command; - EFI_NVM_EXPRESS_COMPLETION Completion; - NVME_ADMIN_CONTROLLER_DATA ControllerData; - CHAR16 *Description; - CHAR16 *Char; - UINTN Index; - - Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **) &DevicePath.DevPath); + EFI_STATUS Status; + EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL *NvmePassthru; + EFI_DEV_PATH_PTR DevicePath; + EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET CommandPacket; + EFI_NVM_EXPRESS_COMMAND Command; + EFI_NVM_EXPRESS_COMPLETION Completion; + NVME_ADMIN_CONTROLLER_DATA ControllerData; + CHAR16 *Description; + CHAR16 *Char; + UINTN Index; + + Status = gBS->HandleProtocol (Handle, &gEfiDevicePathProtocolGuid, (VOID **)&DevicePath.DevPath); if (EFI_ERROR (Status)) { return NULL; } @@ -575,7 +595,8 @@ BmGetNvmeDescription ( Status = gBS->LocateDevicePath (&gEfiNvmExpressPassThruProtocolGuid, &DevicePath.DevPath, &Handle); if (EFI_ERROR (Status) || (DevicePathType (DevicePath.DevPath) != MESSAGING_DEVICE_PATH) || - (DevicePathSubType (DevicePath.DevPath) != MSG_NVME_NAMESPACE_DP)) { + (DevicePathSubType (DevicePath.DevPath) != MSG_NVME_NAMESPACE_DP)) + { // // Do not return description when the Handle is not a child of NVME controller. // @@ -585,19 +606,19 @@ BmGetNvmeDescription ( // // Send ADMIN_IDENTIFY command to NVME controller to get the model and serial number. // - Status = gBS->HandleProtocol (Handle, &gEfiNvmExpressPassThruProtocolGuid, (VOID **) &NvmePassthru); + Status = gBS->HandleProtocol (Handle, &gEfiNvmExpressPassThruProtocolGuid, (VOID **)&NvmePassthru); ASSERT_EFI_ERROR (Status); - ZeroMem (&CommandPacket, sizeof(EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); - ZeroMem (&Command, sizeof(EFI_NVM_EXPRESS_COMMAND)); - ZeroMem (&Completion, sizeof(EFI_NVM_EXPRESS_COMPLETION)); + ZeroMem (&CommandPacket, sizeof (EFI_NVM_EXPRESS_PASS_THRU_COMMAND_PACKET)); + ZeroMem (&Command, sizeof (EFI_NVM_EXPRESS_COMMAND)); + ZeroMem (&Completion, sizeof (EFI_NVM_EXPRESS_COMPLETION)); Command.Cdw0.Opcode = NVME_ADMIN_IDENTIFY_CMD; // // According to Nvm Express 1.1 spec Figure 38, When not used, the field shall be cleared to 0h. // For the Identify command, the Namespace Identifier is only used for the Namespace data structure. // - Command.Nsid = 0; + Command.Nsid = 0; CommandPacket.NvmeCmd = &Command; CommandPacket.NvmeCompletion = &Completion; CommandPacket.TransferBuffer = &ControllerData; @@ -607,15 +628,15 @@ BmGetNvmeDescription ( // // Set bit 0 (Cns bit) to 1 to identify a controller // - Command.Cdw10 = 1; - Command.Flags = CDW10_VALID; + Command.Cdw10 = 1; + Command.Flags = CDW10_VALID; Status = NvmePassthru->PassThru ( - NvmePassthru, - 0, - &CommandPacket, - NULL - ); + NvmePassthru, + 0, + &CommandPacket, + NULL + ); if (EFI_ERROR (Status)) { return NULL; } @@ -624,20 +645,26 @@ BmGetNvmeDescription ( (ARRAY_SIZE (ControllerData.Mn) + 1 + ARRAY_SIZE (ControllerData.Sn) + 1 + MAXIMUM_VALUE_CHARACTERS + 1 - ) * sizeof (CHAR16)); + ) * sizeof (CHAR16) + ); if (Description != NULL) { Char = Description; for (Index = 0; Index < ARRAY_SIZE (ControllerData.Mn); Index++) { - *(Char++) = (CHAR16) ControllerData.Mn[Index]; + *(Char++) = (CHAR16)ControllerData.Mn[Index]; } + *(Char++) = L' '; for (Index = 0; Index < ARRAY_SIZE (ControllerData.Sn); Index++) { - *(Char++) = (CHAR16) ControllerData.Sn[Index]; + *(Char++) = (CHAR16)ControllerData.Sn[Index]; } + *(Char++) = L' '; UnicodeValueToStringS ( - Char, sizeof (CHAR16) * (MAXIMUM_VALUE_CHARACTERS + 1), - 0, DevicePath.NvmeNamespace->NamespaceId, 0 + Char, + sizeof (CHAR16) * (MAXIMUM_VALUE_CHARACTERS + 1), + 0, + DevicePath.NvmeNamespace->NamespaceId, + 0 ); BmEliminateExtraSpaces (Description); } @@ -654,54 +681,56 @@ BmGetNvmeDescription ( **/ CHAR16 * BmGetMiscDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - EFI_STATUS Status; - CHAR16 *Description; - EFI_BLOCK_IO_PROTOCOL *BlockIo; - EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; + EFI_STATUS Status; + CHAR16 *Description; + EFI_BLOCK_IO_PROTOCOL *BlockIo; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Fs; switch (BmDevicePathType (DevicePathFromHandle (Handle))) { - case BmAcpiFloppyBoot: - Description = L"Floppy"; - break; - - case BmMessageAtapiBoot: - case BmMessageSataBoot: - Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo); - ASSERT_EFI_ERROR (Status); - // - // Assume a removable SATA device should be the DVD/CD device - // - Description = BlockIo->Media->RemovableMedia ? L"DVD/CDROM" : L"Hard Drive"; - break; + case BmAcpiFloppyBoot: + Description = L"Floppy"; + break; + + case BmMessageAtapiBoot: + case BmMessageSataBoot: + Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo); + ASSERT_EFI_ERROR (Status); + // + // Assume a removable SATA device should be the DVD/CD device + // + Description = BlockIo->Media->RemovableMedia ? L"DVD/CDROM" : L"Hard Drive"; + break; - case BmMessageUsbBoot: - Description = L"USB Device"; - break; + case BmMessageUsbBoot: + Description = L"USB Device"; + break; - case BmMessageScsiBoot: - Description = L"SCSI Device"; - break; + case BmMessageScsiBoot: + Description = L"SCSI Device"; + break; - case BmHardwareDeviceBoot: - Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **) &BlockIo); - if (!EFI_ERROR (Status)) { - Description = BlockIo->Media->RemovableMedia ? L"Removable Disk" : L"Hard Drive"; - } else { - Description = L"Misc Device"; - } - break; + case BmHardwareDeviceBoot: + Status = gBS->HandleProtocol (Handle, &gEfiBlockIoProtocolGuid, (VOID **)&BlockIo); + if (!EFI_ERROR (Status)) { + Description = BlockIo->Media->RemovableMedia ? L"Removable Disk" : L"Hard Drive"; + } else { + Description = L"Misc Device"; + } - default: - Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **) &Fs); - if (!EFI_ERROR (Status)) { - Description = L"Non-Block Boot Device"; - } else { - Description = L"Misc Device"; - } - break; + break; + + default: + Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID **)&Fs); + if (!EFI_ERROR (Status)) { + Description = L"Non-Block Boot Device"; + } else { + Description = L"Misc Device"; + } + + break; } return AllocateCopyPool (StrSize (Description), Description); @@ -722,13 +751,14 @@ EfiBootManagerRegisterBootDescriptionHandler ( IN EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler ) { - LIST_ENTRY *Link; - BM_BOOT_DESCRIPTION_ENTRY *Entry; + LIST_ENTRY *Link; + BM_BOOT_DESCRIPTION_ENTRY *Entry; for ( Link = GetFirstNode (&mPlatformBootDescriptionHandlers) - ; !IsNull (&mPlatformBootDescriptionHandlers, Link) - ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link) - ) { + ; !IsNull (&mPlatformBootDescriptionHandlers, Link) + ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link) + ) + { Entry = CR (Link, BM_BOOT_DESCRIPTION_ENTRY, Link, BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE); if (Entry->Handler == Handler) { return EFI_ALREADY_STARTED; @@ -746,7 +776,7 @@ EfiBootManagerRegisterBootDescriptionHandler ( return EFI_SUCCESS; } -BM_GET_BOOT_DESCRIPTION mBmBootDescriptionHandlers[] = { +BM_GET_BOOT_DESCRIPTION mBmBootDescriptionHandlers[] = { BmGetUsbDescription, BmGetDescriptionFromDiskInfo, BmGetNetworkDescription, @@ -764,22 +794,22 @@ BM_GET_BOOT_DESCRIPTION mBmBootDescriptionHandlers[] = { **/ CHAR16 * BmGetBootDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ) { - LIST_ENTRY *Link; - BM_BOOT_DESCRIPTION_ENTRY *Entry; - CHAR16 *Description; - CHAR16 *DefaultDescription; - CHAR16 *Temp; - UINTN Index; + LIST_ENTRY *Link; + BM_BOOT_DESCRIPTION_ENTRY *Entry; + CHAR16 *Description; + CHAR16 *DefaultDescription; + CHAR16 *Temp; + UINTN Index; // // Firstly get the default boot description // DefaultDescription = NULL; for (Index = 0; Index < ARRAY_SIZE (mBmBootDescriptionHandlers); Index++) { - DefaultDescription = mBmBootDescriptionHandlers[Index] (Handle); + DefaultDescription = mBmBootDescriptionHandlers[Index](Handle); if (DefaultDescription != NULL) { // // Avoid description confusion between UEFI & Legacy boot option by adding "UEFI " prefix @@ -794,16 +824,18 @@ BmGetBootDescription ( break; } } + ASSERT (DefaultDescription != NULL); // // Secondly query platform for the better boot description // for ( Link = GetFirstNode (&mPlatformBootDescriptionHandlers) - ; !IsNull (&mPlatformBootDescriptionHandlers, Link) - ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link) - ) { - Entry = CR (Link, BM_BOOT_DESCRIPTION_ENTRY, Link, BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE); + ; !IsNull (&mPlatformBootDescriptionHandlers, Link) + ; Link = GetNextNode (&mPlatformBootDescriptionHandlers, Link) + ) + { + Entry = CR (Link, BM_BOOT_DESCRIPTION_ENTRY, Link, BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE); Description = Entry->Handler (Handle, DefaultDescription); if (Description != NULL) { FreePool (DefaultDescription); @@ -823,16 +855,16 @@ BmGetBootDescription ( **/ VOID BmMakeBootOptionDescriptionUnique ( - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, - UINTN BootOptionCount + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, + UINTN BootOptionCount ) { - UINTN Base; - UINTN Index; - UINTN DescriptionSize; - UINTN MaxSuffixSize; - BOOLEAN *Visited; - UINTN MatchCount; + UINTN Base; + UINTN Index; + UINTN DescriptionSize; + UINTN MaxSuffixSize; + BOOLEAN *Visited; + UINTN MatchCount; if (BootOptionCount == 0) { return; @@ -856,15 +888,17 @@ BmMakeBootOptionDescriptionUnique ( Visited[Base] = TRUE; DescriptionSize = StrSize (BootOptions[Base].Description); for (Index = Base + 1; Index < BootOptionCount; Index++) { - if (!Visited[Index] && StrCmp (BootOptions[Base].Description, BootOptions[Index].Description) == 0) { + if (!Visited[Index] && (StrCmp (BootOptions[Base].Description, BootOptions[Index].Description) == 0)) { Visited[Index] = TRUE; MatchCount++; FreePool (BootOptions[Index].Description); BootOptions[Index].Description = AllocatePool (DescriptionSize + MaxSuffixSize); UnicodeSPrint ( - BootOptions[Index].Description, DescriptionSize + MaxSuffixSize, + BootOptions[Index].Description, + DescriptionSize + MaxSuffixSize, L"%s %d", - BootOptions[Base].Description, MatchCount + BootOptions[Base].Description, + MatchCount ); } } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmConnect.c b/MdeModulePkg/Library/UefiBootManagerLib/BmConnect.c index d4a263b8fe..d1fb0f72ba 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmConnect.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmConnect.c @@ -52,7 +52,6 @@ BmConnectAllDriversToAllControllers ( // the connect again. // Status = gDS->Dispatch (); - } while (!EFI_ERROR (Status)); } @@ -154,7 +153,6 @@ EfiBootManagerConnectDevicePath ( } } - if (!EFI_ERROR (Status)) { PreviousHandle = Handle; // @@ -175,11 +173,13 @@ EfiBootManagerConnectDevicePath ( if (Status == EFI_NOT_FOUND) { Status = EFI_SUCCESS; } + if (MatchingHandle != NULL) { *MatchingHandle = Handle; } } } + // // Loop until RemainingDevicePath is an empty device path // @@ -243,16 +243,16 @@ EfiBootManagerDisconnectAll ( **/ EFI_STATUS BmConnectUsbShortFormDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - EFI_STATUS Status; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN Index; - EFI_PCI_IO_PROTOCOL *PciIo; - UINT8 Class[3]; - BOOLEAN AtLeastOneConnected; + EFI_STATUS Status; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN Index; + EFI_PCI_IO_PROTOCOL *PciIo; + UINT8 Class[3]; + BOOLEAN AtLeastOneConnected; // // Check the passed in parameters @@ -263,7 +263,8 @@ BmConnectUsbShortFormDevicePath ( if ((DevicePathType (DevicePath) != MESSAGING_DEVICE_PATH) || ((DevicePathSubType (DevicePath) != MSG_USB_CLASS_DP) && (DevicePathSubType (DevicePath) != MSG_USB_WWID_DP)) - ) { + ) + { return EFI_INVALID_PARAMETER; } @@ -271,19 +272,19 @@ BmConnectUsbShortFormDevicePath ( // Find the usb host controller firstly, then connect with the remaining device path // AtLeastOneConnected = FALSE; - Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiPciIoProtocolGuid, - NULL, - &HandleCount, - &Handles - ); + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiPciIoProtocolGuid, + NULL, + &HandleCount, + &Handles + ); if (!EFI_ERROR (Status)) { for (Index = 0; Index < HandleCount; Index++) { Status = gBS->HandleProtocol ( Handles[Index], &gEfiPciIoProtocolGuid, - (VOID **) &PciIo + (VOID **)&PciIo ); if (!EFI_ERROR (Status)) { // @@ -292,14 +293,15 @@ BmConnectUsbShortFormDevicePath ( Status = PciIo->Pci.Read (PciIo, EfiPciIoWidthUint8, 0x09, 3, &Class); if (!EFI_ERROR (Status) && ((PCI_CLASS_SERIAL == Class[2]) && (PCI_CLASS_SERIAL_USB == Class[1])) - ) { + ) + { Status = gBS->ConnectController ( Handles[Index], NULL, DevicePath, FALSE ); - if (!EFI_ERROR(Status)) { + if (!EFI_ERROR (Status)) { AtLeastOneConnected = TRUE; } } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmConsole.c b/MdeModulePkg/Library/UefiBootManagerLib/BmConsole.c index bdbb9a8770..60e7b1099a 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmConsole.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmConsole.c @@ -9,7 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalBm.h" -CHAR16 *mConVarName[] = { +CHAR16 *mConVarName[] = { L"ConIn", L"ConOut", L"ErrOut", @@ -28,16 +28,16 @@ BmGetVideoController ( VOID ) { - EFI_STATUS Status; - UINTN RootBridgeHandleCount; - EFI_HANDLE *RootBridgeHandleBuffer; - UINTN HandleCount; - EFI_HANDLE *HandleBuffer; - UINTN RootBridgeIndex; - UINTN Index; - EFI_HANDLE VideoController; - EFI_PCI_IO_PROTOCOL *PciIo; - PCI_TYPE00 Pci; + EFI_STATUS Status; + UINTN RootBridgeHandleCount; + EFI_HANDLE *RootBridgeHandleBuffer; + UINTN HandleCount; + EFI_HANDLE *HandleBuffer; + UINTN RootBridgeIndex; + UINTN Index; + EFI_HANDLE VideoController; + EFI_PCI_IO_PROTOCOL *PciIo; + PCI_TYPE00 Pci; // // Make all the PCI_IO protocols show up @@ -72,18 +72,18 @@ BmGetVideoController ( } for (Index = 0; Index < HandleCount; Index++) { - Status = gBS->HandleProtocol (HandleBuffer[Index], &gEfiPciIoProtocolGuid, (VOID **) &PciIo); + Status = gBS->HandleProtocol (HandleBuffer[Index], &gEfiPciIoProtocolGuid, (VOID **)&PciIo); if (!EFI_ERROR (Status)) { // // Check for all video controller // Status = PciIo->Pci.Read ( - PciIo, - EfiPciIoWidthUint32, - 0, - sizeof (Pci) / sizeof (UINT32), - &Pci - ); + PciIo, + EfiPciIoWidthUint32, + 0, + sizeof (Pci) / sizeof (UINT32), + &Pci + ); if (!EFI_ERROR (Status) && IS_PCI_VGA (&Pci)) { // TODO: use IS_PCI_DISPLAY?? VideoController = HandleBuffer[Index]; @@ -91,12 +91,14 @@ BmGetVideoController ( } } } + FreePool (HandleBuffer); if (VideoController != NULL) { break; } } + FreePool (RootBridgeHandleBuffer); return VideoController; @@ -113,7 +115,7 @@ BmGetVideoController ( EFI_DEVICE_PATH_PROTOCOL * EFIAPI EfiBootManagerGetGopDevicePath ( - IN EFI_HANDLE VideoController + IN EFI_HANDLE VideoController ) { UINTN Index; @@ -130,7 +132,6 @@ EfiBootManagerGetGopDevicePath ( EFI_DEVICE_PATH_PROTOCOL *GopPool; EFI_DEVICE_PATH_PROTOCOL *ReturnDevicePath; - Status = gBS->ProtocolsPerHandle ( VideoController, &ProtocolBuffer, @@ -161,7 +162,7 @@ EfiBootManagerGetGopDevicePath ( Status = gBS->OpenProtocol ( OpenInfoBuffer[Index].ControllerHandle, &gEfiDevicePathProtocolGuid, - (VOID **) &DevicePath, + (VOID **)&DevicePath, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL @@ -174,9 +175,10 @@ EfiBootManagerGetGopDevicePath ( for (Next = DevicePath; !IsDevicePathEnd (Next); Next = NextDevicePathNode (Next)) { Previous = Next; } + ASSERT (Previous != NULL); - if (DevicePathType (Previous) == ACPI_DEVICE_PATH && DevicePathSubType (Previous) == ACPI_ADR_DP) { + if ((DevicePathType (Previous) == ACPI_DEVICE_PATH) && (DevicePathSubType (Previous) == ACPI_ADR_DP)) { Status = gBS->OpenProtocol ( OpenInfoBuffer[Index].ControllerHandle, &gEfiGraphicsOutputProtocolGuid, @@ -190,19 +192,19 @@ EfiBootManagerGetGopDevicePath ( // Append the device path to GOP pool when there is GOP protocol installed. // TempDevicePath = GopPool; - GopPool = AppendDevicePathInstance (GopPool, DevicePath); + GopPool = AppendDevicePathInstance (GopPool, DevicePath); gBS->FreePool (TempDevicePath); } } - if (DevicePathType (Previous) == HARDWARE_DEVICE_PATH && DevicePathSubType (Previous) == HW_CONTROLLER_DP) { + if ((DevicePathType (Previous) == HARDWARE_DEVICE_PATH) && (DevicePathSubType (Previous) == HW_CONTROLLER_DP)) { // // Recursively look for GOP child in this frame buffer handle // DEBUG ((DEBUG_INFO, "[Bds] Looking for GOP child deeper ... \n")); - TempDevicePath = GopPool; + TempDevicePath = GopPool; ReturnDevicePath = EfiBootManagerGetGopDevicePath (OpenInfoBuffer[Index].ControllerHandle); - GopPool = AppendDevicePathInstance (GopPool, ReturnDevicePath); + GopPool = AppendDevicePathInstance (GopPool, ReturnDevicePath); gBS->FreePool (ReturnDevicePath); gBS->FreePool (TempDevicePath); } @@ -228,10 +230,10 @@ EfiBootManagerGetGopDevicePath ( EFI_STATUS EFIAPI EfiBootManagerConnectVideoController ( - EFI_HANDLE VideoController OPTIONAL + EFI_HANDLE VideoController OPTIONAL ) { - EFI_DEVICE_PATH_PROTOCOL *Gop; + EFI_DEVICE_PATH_PROTOCOL *Gop; if (VideoController == NULL) { // @@ -285,21 +287,21 @@ EfiBootManagerConnectVideoController ( **/ BOOLEAN BmUpdateSystemTableConsole ( - IN CHAR16 *VarName, - IN EFI_GUID *ConsoleGuid, - IN OUT EFI_HANDLE *ConsoleHandle, - IN OUT VOID **ProtocolInterface + IN CHAR16 *VarName, + IN EFI_GUID *ConsoleGuid, + IN OUT EFI_HANDLE *ConsoleHandle, + IN OUT VOID **ProtocolInterface ) { - EFI_STATUS Status; - UINTN DevicePathSize; - EFI_DEVICE_PATH_PROTOCOL *FullDevicePath; - EFI_DEVICE_PATH_PROTOCOL *VarConsole; - EFI_DEVICE_PATH_PROTOCOL *Instance; - EFI_DEVICE_PATH_PROTOCOL *FullInstance; - VOID *Interface; - EFI_HANDLE NewHandle; - EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *TextOut; + EFI_STATUS Status; + UINTN DevicePathSize; + EFI_DEVICE_PATH_PROTOCOL *FullDevicePath; + EFI_DEVICE_PATH_PROTOCOL *VarConsole; + EFI_DEVICE_PATH_PROTOCOL *Instance; + EFI_DEVICE_PATH_PROTOCOL *FullInstance; + VOID *Interface; + EFI_HANDLE NewHandle; + EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *TextOut; ASSERT (VarName != NULL); ASSERT (ConsoleHandle != NULL); @@ -308,11 +310,11 @@ BmUpdateSystemTableConsole ( if (*ConsoleHandle != NULL) { Status = gBS->HandleProtocol ( - *ConsoleHandle, - ConsoleGuid, - &Interface - ); - if (Status == EFI_SUCCESS && Interface == *ProtocolInterface) { + *ConsoleHandle, + ConsoleGuid, + &Interface + ); + if ((Status == EFI_SUCCESS) && (Interface == *ProtocolInterface)) { // // If ConsoleHandle is valid and console protocol on this handle also // also matched, just return. @@ -324,7 +326,7 @@ BmUpdateSystemTableConsole ( // // Get all possible consoles device path from EFI variable // - GetEfiGlobalVariable2 (VarName, (VOID **) &VarConsole, NULL); + GetEfiGlobalVariable2 (VarName, (VOID **)&VarConsole, NULL); if (VarConsole == NULL) { // // If there is no any console device, just return. @@ -338,7 +340,7 @@ BmUpdateSystemTableConsole ( // // Check every instance of the console variable // - Instance = GetNextDevicePathInstance (&VarConsole, &DevicePathSize); + Instance = GetNextDevicePathInstance (&VarConsole, &DevicePathSize); if (Instance == NULL) { DEBUG ((DEBUG_ERROR, "[Bds] No valid console instance is found for %s!\n", VarName)); // We should not ASSERT when all the console devices are removed. @@ -351,11 +353,11 @@ BmUpdateSystemTableConsole ( // Find console device handle by device path instance // FullInstance = Instance; - Status = gBS->LocateDevicePath ( - ConsoleGuid, - &Instance, - &NewHandle - ); + Status = gBS->LocateDevicePath ( + ConsoleGuid, + &Instance, + &NewHandle + ); FreePool (FullInstance); if (!EFI_ERROR (Status)) { // @@ -376,16 +378,16 @@ BmUpdateSystemTableConsole ( // // If it is console out device, set console mode 80x25 if current mode is invalid. // - TextOut = (EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *) Interface; + TextOut = (EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *)Interface; if (TextOut->Mode->Mode == -1) { TextOut->SetMode (TextOut, 0); } } + FreePool (FullDevicePath); return TRUE; } } - } while (Instance != NULL); // @@ -435,10 +437,11 @@ EfiBootManagerUpdateConsoleVariable ( if (CustomizedConDevicePath == ExclusiveDevicePath) { return EFI_UNSUPPORTED; } + // // Delete the ExclusiveDevicePath from current default console // - GetEfiGlobalVariable2 (mConVarName[ConsoleType], (VOID **) &VarConsole, NULL); + GetEfiGlobalVariable2 (mConVarName[ConsoleType], (VOID **)&VarConsole, NULL); // // Initialize NewDevicePath // @@ -448,9 +451,10 @@ EfiBootManagerUpdateConsoleVariable ( // If ExclusiveDevicePath is even the part of the instance in VarConsole, delete it. // In the end, NewDevicePath is the final device path. // - if (ExclusiveDevicePath != NULL && VarConsole != NULL) { - NewDevicePath = BmDelPartMatchInstance (VarConsole, ExclusiveDevicePath); + if ((ExclusiveDevicePath != NULL) && (VarConsole != NULL)) { + NewDevicePath = BmDelPartMatchInstance (VarConsole, ExclusiveDevicePath); } + // // Try to append customized device path to NewDevicePath. // @@ -465,9 +469,9 @@ EfiBootManagerUpdateConsoleVariable ( // just append current customized device path // TempNewDevicePath = NewDevicePath; - NewDevicePath = AppendDevicePathInstance (NewDevicePath, CustomizedConDevicePath); + NewDevicePath = AppendDevicePathInstance (NewDevicePath, CustomizedConDevicePath); if (TempNewDevicePath != NULL) { - FreePool(TempNewDevicePath); + FreePool (TempNewDevicePath); } } } @@ -479,28 +483,28 @@ EfiBootManagerUpdateConsoleVariable ( mConVarName[ConsoleType], &gEfiGlobalVariableGuid, EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS - | ((ConsoleType < ConInDev) ? EFI_VARIABLE_NON_VOLATILE : 0), + | ((ConsoleType < ConInDev) ? EFI_VARIABLE_NON_VOLATILE : 0), GetDevicePathSize (NewDevicePath), NewDevicePath ); if (VarConsole == NewDevicePath) { if (VarConsole != NULL) { - FreePool(VarConsole); + FreePool (VarConsole); } } else { if (VarConsole != NULL) { - FreePool(VarConsole); + FreePool (VarConsole); } + if (NewDevicePath != NULL) { - FreePool(NewDevicePath); + FreePool (NewDevicePath); } } return Status; } - /** Connect the console device base on the variable ConsoleType. @@ -515,7 +519,7 @@ EfiBootManagerUpdateConsoleVariable ( EFI_STATUS EFIAPI EfiBootManagerConnectConsoleVariable ( - IN CONSOLE_TYPE ConsoleType + IN CONSOLE_TYPE ConsoleType ) { EFI_STATUS Status; @@ -538,7 +542,7 @@ EfiBootManagerConnectConsoleVariable ( // // Check if the console variable exist // - GetEfiGlobalVariable2 (mConVarName[ConsoleType], (VOID **) &StartDevicePath, NULL); + GetEfiGlobalVariable2 (mConVarName[ConsoleType], (VOID **)&StartDevicePath, NULL); if (StartDevicePath == NULL) { return EFI_UNSUPPORTED; } @@ -548,13 +552,13 @@ EfiBootManagerConnectConsoleVariable ( // // Check every instance of the console variable // - Instance = GetNextDevicePathInstance (&CopyOfDevicePath, &Size); + Instance = GetNextDevicePathInstance (&CopyOfDevicePath, &Size); if (Instance == NULL) { FreePool (StartDevicePath); return EFI_UNSUPPORTED; } - Next = Instance; + Next = Instance; while (!IsDevicePathEndType (Next)) { Next = NextDevicePathNode (Next); } @@ -568,23 +572,26 @@ EfiBootManagerConnectConsoleVariable ( // if ((DevicePathType (Instance) == MESSAGING_DEVICE_PATH) && ((DevicePathSubType (Instance) == MSG_USB_CLASS_DP) || (DevicePathSubType (Instance) == MSG_USB_WWID_DP)) - ) { + ) + { Status = BmConnectUsbShortFormDevicePath (Instance); if (!EFI_ERROR (Status)) { DeviceExist = TRUE; } } else { for (Next = Instance; !IsDevicePathEnd (Next); Next = NextDevicePathNode (Next)) { - if (DevicePathType (Next) == ACPI_DEVICE_PATH && DevicePathSubType (Next) == ACPI_ADR_DP) { + if ((DevicePathType (Next) == ACPI_DEVICE_PATH) && (DevicePathSubType (Next) == ACPI_ADR_DP)) { break; - } else if (DevicePathType (Next) == HARDWARE_DEVICE_PATH && - DevicePathSubType (Next) == HW_CONTROLLER_DP && - DevicePathType (NextDevicePathNode (Next)) == ACPI_DEVICE_PATH && - DevicePathSubType (NextDevicePathNode (Next)) == ACPI_ADR_DP - ) { + } else if ((DevicePathType (Next) == HARDWARE_DEVICE_PATH) && + (DevicePathSubType (Next) == HW_CONTROLLER_DP) && + (DevicePathType (NextDevicePathNode (Next)) == ACPI_DEVICE_PATH) && + (DevicePathSubType (NextDevicePathNode (Next)) == ACPI_ADR_DP) + ) + { break; } } + if (!IsDevicePathEnd (Next)) { // // For GOP device path, start the video driver with NULL remaining device path @@ -597,6 +604,7 @@ EfiBootManagerConnectConsoleVariable ( } else { Status = EfiBootManagerConnectDevicePath (Instance, NULL); } + if (EFI_ERROR (Status)) { // // Delete the instance from the console varialbe @@ -606,7 +614,8 @@ EfiBootManagerConnectConsoleVariable ( DeviceExist = TRUE; } } - FreePool(Instance); + + FreePool (Instance); } while (CopyOfDevicePath != NULL); FreePool (StartDevicePath); @@ -618,7 +627,6 @@ EfiBootManagerConnectConsoleVariable ( return EFI_SUCCESS; } - /** This function will search every input/output device in current system, and make every input/output device as potential console device. @@ -643,46 +651,46 @@ EfiBootManagerConnectAllConsoles ( // Update all the console variables // gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextInProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextInProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); for (Index = 0; Index < HandleCount; Index++) { gBS->HandleProtocol ( - HandleBuffer[Index], - &gEfiDevicePathProtocolGuid, - (VOID **) &ConDevicePath - ); + HandleBuffer[Index], + &gEfiDevicePathProtocolGuid, + (VOID **)&ConDevicePath + ); EfiBootManagerUpdateConsoleVariable (ConIn, ConDevicePath, NULL); } if (HandleBuffer != NULL) { - FreePool(HandleBuffer); + FreePool (HandleBuffer); HandleBuffer = NULL; } gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiSimpleTextOutProtocolGuid, - NULL, - &HandleCount, - &HandleBuffer - ); + ByProtocol, + &gEfiSimpleTextOutProtocolGuid, + NULL, + &HandleCount, + &HandleBuffer + ); for (Index = 0; Index < HandleCount; Index++) { gBS->HandleProtocol ( - HandleBuffer[Index], - &gEfiDevicePathProtocolGuid, - (VOID **) &ConDevicePath - ); + HandleBuffer[Index], + &gEfiDevicePathProtocolGuid, + (VOID **)&ConDevicePath + ); EfiBootManagerUpdateConsoleVariable (ConOut, ConDevicePath, NULL); EfiBootManagerUpdateConsoleVariable (ErrOut, ConDevicePath, NULL); } if (HandleBuffer != NULL) { - FreePool(HandleBuffer); + FreePool (HandleBuffer); } // @@ -691,7 +699,6 @@ EfiBootManagerConnectAllConsoles ( EfiBootManagerConnectAllDefaultConsoles (); } - /** This function will connect all the console devices base on the console device variable ConIn, ConOut and ErrOut. @@ -706,9 +713,9 @@ EfiBootManagerConnectAllDefaultConsoles ( VOID ) { - EFI_STATUS Status; - BOOLEAN OneConnected; - BOOLEAN SystemTableUpdated; + EFI_STATUS Status; + BOOLEAN OneConnected; + BOOLEAN SystemTableUpdated; OneConnected = FALSE; @@ -716,32 +723,36 @@ EfiBootManagerConnectAllDefaultConsoles ( if (!EFI_ERROR (Status)) { OneConnected = TRUE; } - PERF_EVENT ("ConOutReady"); + PERF_EVENT ("ConOutReady"); Status = EfiBootManagerConnectConsoleVariable (ConIn); if (!EFI_ERROR (Status)) { OneConnected = TRUE; } + PERF_EVENT ("ConInReady"); Status = EfiBootManagerConnectConsoleVariable (ErrOut); if (!EFI_ERROR (Status)) { OneConnected = TRUE; } + PERF_EVENT ("ErrOutReady"); SystemTableUpdated = FALSE; // // Fill console handles in System Table if no console device assignd. // - if (BmUpdateSystemTableConsole (L"ConIn", &gEfiSimpleTextInProtocolGuid, &gST->ConsoleInHandle, (VOID **) &gST->ConIn)) { + if (BmUpdateSystemTableConsole (L"ConIn", &gEfiSimpleTextInProtocolGuid, &gST->ConsoleInHandle, (VOID **)&gST->ConIn)) { SystemTableUpdated = TRUE; } - if (BmUpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **) &gST->ConOut)) { + + if (BmUpdateSystemTableConsole (L"ConOut", &gEfiSimpleTextOutProtocolGuid, &gST->ConsoleOutHandle, (VOID **)&gST->ConOut)) { SystemTableUpdated = TRUE; } - if (BmUpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **) &gST->StdErr)) { + + if (BmUpdateSystemTableConsole (L"ErrOut", &gEfiSimpleTextOutProtocolGuid, &gST->StandardErrorHandle, (VOID **)&gST->StdErr)) { SystemTableUpdated = TRUE; } @@ -751,10 +762,10 @@ EfiBootManagerConnectAllDefaultConsoles ( // gST->Hdr.CRC32 = 0; gBS->CalculateCrc32 ( - (UINT8 *) &gST->Hdr, - gST->Hdr.HeaderSize, - &gST->Hdr.CRC32 - ); + (UINT8 *)&gST->Hdr, + gST->Hdr.HeaderSize, + &gST->Hdr.CRC32 + ); } return OneConnected ? EFI_SUCCESS : EFI_DEVICE_ERROR; diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c b/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c index eacd45439b..46a2fa2016 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmDriverHealth.c @@ -11,14 +11,14 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalBm.h" GLOBAL_REMOVE_IF_UNREFERENCED - CHAR16 *mBmHealthStatusText[] = { - L"Healthy", - L"Repair Required", - L"Configuration Required", - L"Failed", - L"Reconnect Required", - L"Reboot Required" - }; +CHAR16 *mBmHealthStatusText[] = { + L"Healthy", + L"Repair Required", + L"Configuration Required", + L"Failed", + L"Reconnect Required", + L"Reboot Required" +}; /** Return the controller name. @@ -37,17 +37,17 @@ GLOBAL_REMOVE_IF_UNREFERENCED **/ CHAR16 * BmGetControllerName ( - IN EFI_HANDLE DriverHealthHandle, - IN EFI_HANDLE ControllerHandle, - IN EFI_HANDLE ChildHandle + IN EFI_HANDLE DriverHealthHandle, + IN EFI_HANDLE ControllerHandle, + IN EFI_HANDLE ChildHandle ) { - EFI_STATUS Status; - CHAR16 *ControllerName; - CHAR8 *LanguageVariable; - CHAR8 *BestLanguage; - BOOLEAN Iso639Language; - EFI_COMPONENT_NAME_PROTOCOL *ComponentName; + EFI_STATUS Status; + CHAR16 *ControllerName; + CHAR8 *LanguageVariable; + CHAR8 *BestLanguage; + BOOLEAN Iso639Language; + EFI_COMPONENT_NAME_PROTOCOL *ComponentName; ControllerName = NULL; @@ -55,16 +55,16 @@ BmGetControllerName ( // Locate Component Name (2) protocol on the driver binging handle. // Iso639Language = FALSE; - Status = gBS->HandleProtocol ( - DriverHealthHandle, - &gEfiComponentName2ProtocolGuid, - (VOID **) &ComponentName - ); + Status = gBS->HandleProtocol ( + DriverHealthHandle, + &gEfiComponentName2ProtocolGuid, + (VOID **)&ComponentName + ); if (EFI_ERROR (Status)) { Status = gBS->HandleProtocol ( DriverHealthHandle, &gEfiComponentNameProtocolGuid, - (VOID **) &ComponentName + (VOID **)&ComponentName ); if (!EFI_ERROR (Status)) { Iso639Language = TRUE; @@ -72,14 +72,14 @@ BmGetControllerName ( } if (!EFI_ERROR (Status)) { - GetEfiGlobalVariable2 (Iso639Language ? L"Lang" : L"PlatformLang", (VOID**)&LanguageVariable, NULL); - BestLanguage = GetBestLanguage( - ComponentName->SupportedLanguages, - Iso639Language, - (LanguageVariable != NULL) ? LanguageVariable : "", - Iso639Language ? "eng" : "en-US", - NULL - ); + GetEfiGlobalVariable2 (Iso639Language ? L"Lang" : L"PlatformLang", (VOID **)&LanguageVariable, NULL); + BestLanguage = GetBestLanguage ( + ComponentName->SupportedLanguages, + Iso639Language, + (LanguageVariable != NULL) ? LanguageVariable : "", + Iso639Language ? "eng" : "en-US", + NULL + ); if (LanguageVariable != NULL) { FreePool (LanguageVariable); } @@ -111,15 +111,16 @@ BmGetControllerName ( **/ VOID BmDisplayMessages ( - IN EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo + IN EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo ) { - UINTN Index; - EFI_STRING String; - CHAR16 *ControllerName; + UINTN Index; + EFI_STRING String; + CHAR16 *ControllerName; - if (DriverHealthInfo->MessageList == NULL || - DriverHealthInfo->MessageList[0].HiiHandle == NULL) { + if ((DriverHealthInfo->MessageList == NULL) || + (DriverHealthInfo->MessageList[0].HiiHandle == NULL)) + { return; } @@ -163,8 +164,8 @@ BmDisplayMessages ( EFI_STATUS EFIAPI BmRepairNotify ( - IN UINTN Value, - IN UINTN Limit + IN UINTN Value, + IN UINTN Limit ) { DEBUG ((DEBUG_INFO, "[BDS]RepairNotify: %d/%d\n", Value, Limit)); @@ -189,11 +190,11 @@ BmRepairNotify ( **/ EFI_STATUS BmGetSingleControllerHealthStatus ( - IN OUT EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO **DriverHealthInfo, - IN OUT UINTN *Count, - IN EFI_HANDLE DriverHealthHandle, - IN EFI_HANDLE ControllerHandle OPTIONAL, - IN EFI_HANDLE ChildHandle OPTIONAL + IN OUT EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO **DriverHealthInfo, + IN OUT UINTN *Count, + IN EFI_HANDLE DriverHealthHandle, + IN EFI_HANDLE ControllerHandle OPTIONAL, + IN EFI_HANDLE ChildHandle OPTIONAL ) { EFI_STATUS Status; @@ -209,17 +210,16 @@ BmGetSingleControllerHealthStatus ( Status = gBS->HandleProtocol ( DriverHealthHandle, &gEfiDriverHealthProtocolGuid, - (VOID **) &DriverHealth + (VOID **)&DriverHealth ); ASSERT_EFI_ERROR (Status); - if (ControllerHandle == NULL) { // // If ControllerHandle is NULL, the return the cumulative health status of the driver // Status = DriverHealth->GetHealthStatus (DriverHealth, NULL, NULL, &HealthStatus, NULL, NULL); - if (!EFI_ERROR (Status) && HealthStatus == EfiDriverHealthStatusHealthy) { + if (!EFI_ERROR (Status) && (HealthStatus == EfiDriverHealthStatusHealthy)) { *DriverHealthInfo = ReallocatePool ( (*Count) * sizeof (EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO), (*Count + 1) * sizeof (EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO), @@ -235,6 +235,7 @@ BmGetSingleControllerHealthStatus ( Status = EFI_ABORTED; } + return Status; } @@ -285,28 +286,28 @@ BmGetSingleControllerHealthStatus ( EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO * EFIAPI EfiBootManagerGetDriverHealthInfo ( - UINTN *Count + UINTN *Count ) { - EFI_STATUS Status; - UINTN NumHandles; - EFI_HANDLE *DriverHealthHandles; - UINTN DriverHealthIndex; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN ControllerIndex; - UINTN ChildIndex; + EFI_STATUS Status; + UINTN NumHandles; + EFI_HANDLE *DriverHealthHandles; + UINTN DriverHealthIndex; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN ControllerIndex; + UINTN ChildIndex; EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo; // // Initialize local variables // - *Count = 0; - DriverHealthInfo = NULL; - Handles = NULL; - DriverHealthHandles = NULL; - NumHandles = 0; - HandleCount = 0; + *Count = 0; + DriverHealthInfo = NULL; + Handles = NULL; + DriverHealthHandles = NULL; + NumHandles = 0; + HandleCount = 0; Status = gBS->LocateHandleBuffer ( ByProtocol, @@ -316,7 +317,7 @@ EfiBootManagerGetDriverHealthInfo ( &DriverHealthHandles ); - if (Status == EFI_NOT_FOUND || NumHandles == 0) { + if ((Status == EFI_NOT_FOUND) || (NumHandles == 0)) { // // If there are no Driver Health Protocols handles, then return EFI_NOT_FOUND // @@ -348,14 +349,15 @@ EfiBootManagerGetDriverHealthInfo ( // Retrieve the list of all handles from the handle database // Status = gBS->LocateHandleBuffer ( - AllHandles, - NULL, - NULL, - &HandleCount, - &Handles - ); + AllHandles, + NULL, + NULL, + &HandleCount, + &Handles + ); ASSERT_EFI_ERROR (Status); } + // // Loop through all the controller handles in the handle database // @@ -382,6 +384,7 @@ EfiBootManagerGetDriverHealthInfo ( if (Handles != NULL) { FreePool (Handles); } + if (DriverHealthHandles != NULL) { FreePool (DriverHealthHandles); } @@ -401,17 +404,18 @@ EfiBootManagerGetDriverHealthInfo ( EFI_STATUS EFIAPI EfiBootManagerFreeDriverHealthInfo ( - EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo, - UINTN Count + EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo, + UINTN Count ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Count; Index++) { if (DriverHealthInfo[Index].MessageList != NULL) { FreePool (DriverHealthInfo[Index].MessageList); } } + return gBS->FreePool (DriverHealthInfo); } @@ -423,22 +427,22 @@ EfiBootManagerFreeDriverHealthInfo ( **/ VOID BmRepairAllControllers ( - UINTN ReconnectRepairCount + UINTN ReconnectRepairCount ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo; - EFI_DRIVER_HEALTH_STATUS HealthStatus; - UINTN Count; - UINTN Index; - BOOLEAN RepairRequired; - BOOLEAN ConfigurationRequired; - BOOLEAN ReconnectRequired; - BOOLEAN RebootRequired; - EFI_HII_HANDLE *HiiHandles; - EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; - UINT32 MaxRepairCount; - UINT32 RepairCount; + EFI_STATUS Status; + EFI_BOOT_MANAGER_DRIVER_HEALTH_INFO *DriverHealthInfo; + EFI_DRIVER_HEALTH_STATUS HealthStatus; + UINTN Count; + UINTN Index; + BOOLEAN RepairRequired; + BOOLEAN ConfigurationRequired; + BOOLEAN ReconnectRequired; + BOOLEAN RebootRequired; + EFI_HII_HANDLE *HiiHandles; + EFI_FORM_BROWSER2_PROTOCOL *FormBrowser2; + UINT32 MaxRepairCount; + UINT32 RepairCount; // // Configure PcdDriverHealthConfigureForm to ZeroGuid to disable driver health check. @@ -447,11 +451,11 @@ BmRepairAllControllers ( return; } - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &FormBrowser2); + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&FormBrowser2); ASSERT_EFI_ERROR (Status); MaxRepairCount = PcdGet32 (PcdMaxRepairCount); - RepairCount = 0; + RepairCount = 0; do { RepairRequired = FALSE; @@ -467,7 +471,7 @@ BmRepairAllControllers ( } if (DriverHealthInfo[Index].HealthStatus == EfiDriverHealthStatusRepairRequired) { - RepairRequired = TRUE; + RepairRequired = TRUE; BmDisplayMessages (&DriverHealthInfo[Index]); @@ -510,6 +514,7 @@ BmRepairAllControllers ( break; } } + FreePool (HiiHandles); } } @@ -522,7 +527,6 @@ BmRepairAllControllers ( ReconnectRequired = FALSE; DriverHealthInfo = EfiBootManagerGetDriverHealthInfo (&Count); for (Index = 0; Index < Count; Index++) { - BmDisplayMessages (&DriverHealthInfo[Index]); if (DriverHealthInfo[Index].HealthStatus == EfiDriverHealthStatusReconnectRequired) { @@ -531,7 +535,7 @@ BmRepairAllControllers ( // // Disconnect failed. Need to promote reconnect to a reboot. // - RebootRequired = TRUE; + RebootRequired = TRUE; } else { gBS->ConnectController (DriverHealthInfo[Index].ControllerHandle, NULL, NULL, TRUE); ReconnectRequired = TRUE; @@ -539,42 +543,48 @@ BmRepairAllControllers ( } if (DriverHealthInfo[Index].HealthStatus == EfiDriverHealthStatusRebootRequired) { - RebootRequired = TRUE; + RebootRequired = TRUE; } } - EfiBootManagerFreeDriverHealthInfo (DriverHealthInfo, Count); + EfiBootManagerFreeDriverHealthInfo (DriverHealthInfo, Count); DEBUG_CODE_BEGIN (); - CHAR16 *ControllerName; + CHAR16 *ControllerName; - DriverHealthInfo = EfiBootManagerGetDriverHealthInfo (&Count); - for (Index = 0; Index < Count; Index++) { - ControllerName = BmGetControllerName ( - DriverHealthInfo[Index].DriverHealthHandle, - DriverHealthInfo[Index].ControllerHandle, - DriverHealthInfo[Index].ChildHandle - ); - DEBUG (( - DEBUG_INFO, - "%02d: %s - %s\n", - Index, - ControllerName, - mBmHealthStatusText[DriverHealthInfo[Index].HealthStatus] - )); - if (ControllerName != NULL) { - FreePool (ControllerName); - } + DriverHealthInfo = EfiBootManagerGetDriverHealthInfo (&Count); + for (Index = 0; Index < Count; Index++) { + ControllerName = BmGetControllerName ( + DriverHealthInfo[Index].DriverHealthHandle, + DriverHealthInfo[Index].ControllerHandle, + DriverHealthInfo[Index].ChildHandle + ); + DEBUG (( + DEBUG_INFO, + "%02d: %s - %s\n", + Index, + ControllerName, + mBmHealthStatusText[DriverHealthInfo[Index].HealthStatus] + )); + if (ControllerName != NULL) { + FreePool (ControllerName); } - EfiBootManagerFreeDriverHealthInfo (DriverHealthInfo, Count); + } + + EfiBootManagerFreeDriverHealthInfo (DriverHealthInfo, Count); DEBUG_CODE_END (); if (ReconnectRequired) { if (ReconnectRepairCount < MAX_RECONNECT_REPAIR) { BmRepairAllControllers (ReconnectRepairCount + 1); } else { - DEBUG ((DEBUG_ERROR, "[%a:%d] Repair failed after %d retries.\n", - __FUNCTION__, DEBUG_LINE_NUMBER, ReconnectRepairCount)); + DEBUG (( + DEBUG_ERROR, + "[%a:%d] Repair failed after %d retries.\n", + __FUNCTION__, + DEBUG_LINE_NUMBER, + ReconnectRepairCount + )); } } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmHotkey.c b/MdeModulePkg/Library/UefiBootManagerLib/BmHotkey.c index 9dd3c56617..90bee73a23 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmHotkey.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmHotkey.c @@ -12,20 +12,19 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // // Lock for linked list // -EFI_LOCK mBmHotkeyLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); -LIST_ENTRY mBmHotkeyList = INITIALIZE_LIST_HEAD_VARIABLE (mBmHotkeyList); -EFI_EVENT mBmHotkeyTriggered = NULL; -BOOLEAN mBmHotkeyServiceStarted = FALSE; -UINTN mBmHotkeySupportCount = 0; +EFI_LOCK mBmHotkeyLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY); +LIST_ENTRY mBmHotkeyList = INITIALIZE_LIST_HEAD_VARIABLE (mBmHotkeyList); +EFI_EVENT mBmHotkeyTriggered = NULL; +BOOLEAN mBmHotkeyServiceStarted = FALSE; +UINTN mBmHotkeySupportCount = 0; // // Set OptionNumber as unassigned value to indicate the option isn't initialized // -EFI_BOOT_MANAGER_LOAD_OPTION mBmHotkeyBootOption = { LoadOptionNumberUnassigned }; - -EFI_BOOT_MANAGER_KEY_OPTION *mBmContinueKeyOption = NULL; -VOID *mBmTxtInExRegistration = NULL; +EFI_BOOT_MANAGER_LOAD_OPTION mBmHotkeyBootOption = { LoadOptionNumberUnassigned }; +EFI_BOOT_MANAGER_KEY_OPTION *mBmContinueKeyOption = NULL; +VOID *mBmTxtInExRegistration = NULL; /** Return the buffer size of the EFI_BOOT_MANAGER_KEY_OPTION data. @@ -40,7 +39,7 @@ BmSizeOfKeyOption ( ) { return OFFSET_OF (EFI_BOOT_MANAGER_KEY_OPTION, Keys) - + KeyOption->KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY); + + KeyOption->KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY); } /** @@ -55,14 +54,14 @@ BmSizeOfKeyOption ( **/ BOOLEAN BmIsKeyOptionValid ( - IN CONST EFI_BOOT_MANAGER_KEY_OPTION *KeyOption, - IN UINTN KeyOptionSize -) + IN CONST EFI_BOOT_MANAGER_KEY_OPTION *KeyOption, + IN UINTN KeyOptionSize + ) { - UINT16 OptionName[BM_OPTION_NAME_LEN]; - UINT8 *BootOption; - UINTN BootOptionSize; - UINT32 Crc; + UINT16 OptionName[BM_OPTION_NAME_LEN]; + UINT8 *BootOption; + UINTN BootOptionSize; + UINT32 Crc; if (BmSizeOfKeyOption (KeyOption) != KeyOptionSize) { return FALSE; @@ -72,10 +71,13 @@ BmIsKeyOptionValid ( // Check whether corresponding Boot Option exist // UnicodeSPrint ( - OptionName, sizeof (OptionName), L"%s%04x", - mBmLoadOptionName[LoadOptionTypeBoot], KeyOption->BootOption + OptionName, + sizeof (OptionName), + L"%s%04x", + mBmLoadOptionName[LoadOptionTypeBoot], + KeyOption->BootOption ); - GetEfiGlobalVariable2 (OptionName, (VOID **) &BootOption, &BootOptionSize); + GetEfiGlobalVariable2 (OptionName, (VOID **)&BootOption, &BootOptionSize); if (BootOption == NULL) { return FALSE; @@ -87,7 +89,7 @@ BmIsKeyOptionValid ( gBS->CalculateCrc32 (BootOption, BootOptionSize, &Crc); FreePool (BootOption); - return (BOOLEAN) (KeyOption->BootOptionCrc == Crc); + return (BOOLEAN)(KeyOption->BootOptionCrc == Crc); } /** @@ -103,18 +105,19 @@ BmIsKeyOptionValid ( **/ BOOLEAN BmIsKeyOptionVariable ( - CHAR16 *Name, - EFI_GUID *Guid, - UINT16 *OptionNumber + CHAR16 *Name, + EFI_GUID *Guid, + UINT16 *OptionNumber ) { - UINTN Index; - UINTN Uint; + UINTN Index; + UINTN Uint; if (!CompareGuid (Guid, &gEfiGlobalVariableGuid) || (StrSize (Name) != sizeof (L"Key####")) || (StrnCmp (Name, L"Key", 3) != 0) - ) { + ) + { return FALSE; } @@ -124,7 +127,7 @@ BmIsKeyOptionVariable ( if (Uint == -1) { return FALSE; } else { - *OptionNumber = (UINT16) Uint + *OptionNumber * 0x10; + *OptionNumber = (UINT16)Uint + *OptionNumber * 0x10; } } @@ -132,8 +135,8 @@ BmIsKeyOptionVariable ( } typedef struct { - EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; - UINTN KeyOptionCount; + EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; + UINTN KeyOptionCount; } BM_COLLECT_KEY_OPTIONS_PARAM; /** @@ -145,18 +148,18 @@ typedef struct { **/ VOID BmCollectKeyOptions ( - CHAR16 *Name, - EFI_GUID *Guid, - VOID *Context + CHAR16 *Name, + EFI_GUID *Guid, + VOID *Context ) { - UINTN Index; - BM_COLLECT_KEY_OPTIONS_PARAM *Param; - VOID *KeyOption; - UINT16 OptionNumber; - UINTN KeyOptionSize; + UINTN Index; + BM_COLLECT_KEY_OPTIONS_PARAM *Param; + VOID *KeyOption; + UINT16 OptionNumber; + UINTN KeyOptionSize; - Param = (BM_COLLECT_KEY_OPTIONS_PARAM *) Context; + Param = (BM_COLLECT_KEY_OPTIONS_PARAM *)Context; if (BmIsKeyOptionVariable (Name, Guid, &OptionNumber)) { GetEfiGlobalVariable2 (Name, &KeyOption, &KeyOptionSize); @@ -176,11 +179,13 @@ BmCollectKeyOptions ( break; } } + CopyMem (&Param->KeyOptions[Index + 1], &Param->KeyOptions[Index], (Param->KeyOptionCount - Index) * sizeof (EFI_BOOT_MANAGER_KEY_OPTION)); CopyMem (&Param->KeyOptions[Index], KeyOption, KeyOptionSize); Param->KeyOptions[Index].OptionNumber = OptionNumber; Param->KeyOptionCount++; } + FreePool (KeyOption); } } @@ -195,19 +200,19 @@ BmCollectKeyOptions ( **/ EFI_BOOT_MANAGER_KEY_OPTION * BmGetKeyOptions ( - OUT UINTN *Count + OUT UINTN *Count ) { - BM_COLLECT_KEY_OPTIONS_PARAM Param; + BM_COLLECT_KEY_OPTIONS_PARAM Param; if (Count == NULL) { return NULL; } - Param.KeyOptions = NULL; + Param.KeyOptions = NULL; Param.KeyOptionCount = 0; - BmForEachVariable (BmCollectKeyOptions, (VOID *) &Param); + BmForEachVariable (BmCollectKeyOptions, (VOID *)&Param); *Count = Param.KeyOptionCount; @@ -225,11 +230,11 @@ BmGetKeyOptions ( **/ BOOLEAN BmBitSet ( - IN UINT32 Value, - IN UINT32 Bit + IN UINT32 Value, + IN UINT32 Bit ) { - return (BOOLEAN) ((Value & Bit) != 0); + return (BOOLEAN)((Value & Bit) != 0); } /** @@ -244,12 +249,12 @@ BmBitSet ( **/ EFI_STATUS BmInitializeKeyFields ( - IN UINT32 Modifier, - IN VA_LIST Args, - OUT EFI_BOOT_MANAGER_KEY_OPTION *KeyOption + IN UINT32 Modifier, + IN VA_LIST Args, + OUT EFI_BOOT_MANAGER_KEY_OPTION *KeyOption ) { - EFI_INPUT_KEY *Key; + EFI_INPUT_KEY *Key; if (KeyOption == NULL) { return EFI_INVALID_PARAMETER; @@ -261,6 +266,7 @@ BmInitializeKeyFields ( if (Key == NULL) { break; } + CopyMem ( &KeyOption->Keys[KeyOption->KeyData.Options.InputKeyCount], Key, @@ -277,30 +283,36 @@ BmInitializeKeyFields ( } if ((Modifier & ~(EFI_BOOT_MANAGER_SHIFT_PRESSED - | EFI_BOOT_MANAGER_CONTROL_PRESSED - | EFI_BOOT_MANAGER_ALT_PRESSED - | EFI_BOOT_MANAGER_LOGO_PRESSED - | EFI_BOOT_MANAGER_MENU_KEY_PRESSED - | EFI_BOOT_MANAGER_SYS_REQ_PRESSED - )) != 0) { + | EFI_BOOT_MANAGER_CONTROL_PRESSED + | EFI_BOOT_MANAGER_ALT_PRESSED + | EFI_BOOT_MANAGER_LOGO_PRESSED + | EFI_BOOT_MANAGER_MENU_KEY_PRESSED + | EFI_BOOT_MANAGER_SYS_REQ_PRESSED + )) != 0) + { return EFI_INVALID_PARAMETER; } if (BmBitSet (Modifier, EFI_BOOT_MANAGER_SHIFT_PRESSED)) { KeyOption->KeyData.Options.ShiftPressed = 1; } + if (BmBitSet (Modifier, EFI_BOOT_MANAGER_CONTROL_PRESSED)) { KeyOption->KeyData.Options.ControlPressed = 1; } + if (BmBitSet (Modifier, EFI_BOOT_MANAGER_ALT_PRESSED)) { KeyOption->KeyData.Options.AltPressed = 1; } + if (BmBitSet (Modifier, EFI_BOOT_MANAGER_LOGO_PRESSED)) { KeyOption->KeyData.Options.LogoPressed = 1; } + if (BmBitSet (Modifier, EFI_BOOT_MANAGER_MENU_KEY_PRESSED)) { KeyOption->KeyData.Options.MenuPressed = 1; } + if (BmBitSet (Modifier, EFI_BOOT_MANAGER_SYS_REQ_PRESSED)) { KeyOption->KeyData.Options.SysReqPressed = 1; } @@ -337,14 +349,14 @@ EfiBootManagerHotkeyBoot ( EFI_STATUS EFIAPI BmHotkeyCallback ( - IN EFI_KEY_DATA *KeyData -) + IN EFI_KEY_DATA *KeyData + ) { - LIST_ENTRY *Link; - BM_HOTKEY *Hotkey; - CHAR16 OptionName[BM_OPTION_NAME_LEN]; - EFI_STATUS Status; - EFI_KEY_DATA *HotkeyData; + LIST_ENTRY *Link; + BM_HOTKEY *Hotkey; + CHAR16 OptionName[BM_OPTION_NAME_LEN]; + EFI_STATUS Status; + EFI_KEY_DATA *HotkeyData; if (mBmHotkeyBootOption.OptionNumber != LoadOptionNumberUnassigned) { // @@ -357,9 +369,10 @@ BmHotkeyCallback ( EfiAcquireLock (&mBmHotkeyLock); for ( Link = GetFirstNode (&mBmHotkeyList) - ; !IsNull (&mBmHotkeyList, Link) - ; Link = GetNextNode (&mBmHotkeyList, Link) - ) { + ; !IsNull (&mBmHotkeyList, Link) + ; Link = GetNextNode (&mBmHotkeyList, Link) + ) + { Hotkey = BM_HOTKEY_FROM_LINK (Link); // @@ -370,10 +383,10 @@ BmHotkeyCallback ( if ((KeyData->Key.ScanCode == HotkeyData->Key.ScanCode) && (KeyData->Key.UnicodeChar == HotkeyData->Key.UnicodeChar) && (((KeyData->KeyState.KeyShiftState & EFI_SHIFT_STATE_VALID) != 0) ? - (KeyData->KeyState.KeyShiftState == HotkeyData->KeyState.KeyShiftState) : TRUE + (KeyData->KeyState.KeyShiftState == HotkeyData->KeyState.KeyShiftState) : TRUE ) - ) { - + ) + { // // Receive an expecting key stroke, transit to next waiting state // @@ -395,8 +408,11 @@ BmHotkeyCallback ( // Launch its BootOption // UnicodeSPrint ( - OptionName, sizeof (OptionName), L"%s%04x", - mBmLoadOptionName[LoadOptionTypeBoot], Hotkey->BootOption + OptionName, + sizeof (OptionName), + L"%s%04x", + mBmLoadOptionName[LoadOptionTypeBoot], + Hotkey->BootOption ); Status = EfiBootManagerVariableToLoadOption (OptionName, &mBmHotkeyBootOption); DEBUG ((DEBUG_INFO, "[Bds]Hotkey for %s pressed - %r\n", OptionName, Status)); @@ -413,8 +429,8 @@ BmHotkeyCallback ( // Hotkey->WaitingKey = 0; } - } + EfiReleaseLock (&mBmHotkeyLock); return EFI_SUCCESS; @@ -432,11 +448,11 @@ BmHotkeyCallback ( **/ EFI_HANDLE * BmGetActiveConsoleIn ( - OUT UINTN *Count + OUT UINTN *Count ) { - EFI_STATUS Status; - EFI_HANDLE *Handles; + EFI_STATUS Status; + EFI_HANDLE *Handles; Handles = NULL; *Count = 0; @@ -479,20 +495,20 @@ BmGetActiveConsoleIn ( **/ EFI_STATUS BmUnregisterHotkeyNotify ( - IN BM_HOTKEY *Hotkey + IN BM_HOTKEY *Hotkey ) { - EFI_STATUS Status; - UINTN Index; - UINTN KeyIndex; - EFI_HANDLE *Handles; - UINTN HandleCount; - EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *TxtInEx; - VOID *NotifyHandle; + EFI_STATUS Status; + UINTN Index; + UINTN KeyIndex; + EFI_HANDLE *Handles; + UINTN HandleCount; + EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *TxtInEx; + VOID *NotifyHandle; Handles = BmGetActiveConsoleIn (&HandleCount); for (Index = 0; Index < HandleCount; Index++) { - Status = gBS->HandleProtocol (Handles[Index], &gEfiSimpleTextInputExProtocolGuid, (VOID **) &TxtInEx); + Status = gBS->HandleProtocol (Handles[Index], &gEfiSimpleTextInputExProtocolGuid, (VOID **)&TxtInEx); ASSERT_EFI_ERROR (Status); for (KeyIndex = 0; KeyIndex < Hotkey->CodeCount; KeyIndex++) { Status = TxtInEx->RegisterKeyNotify ( @@ -530,9 +546,9 @@ BmRegisterHotkeyNotify ( IN BM_HOTKEY *Hotkey ) { - EFI_STATUS Status; - UINTN Index; - VOID *NotifyHandle; + EFI_STATUS Status; + UINTN Index; + VOID *NotifyHandle; for (Index = 0; Index < Hotkey->CodeCount; Index++) { Status = TxtInEx->RegisterKeyNotify ( @@ -573,58 +589,64 @@ BmRegisterHotkeyNotify ( **/ VOID BmGenerateKeyShiftState ( - IN UINTN Depth, - IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOption, - IN UINT32 KeyShiftState, - IN UINT32 *KeyShiftStates, - IN UINTN *KeyShiftStateCount + IN UINTN Depth, + IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOption, + IN UINT32 KeyShiftState, + IN UINT32 *KeyShiftStates, + IN UINTN *KeyShiftStateCount ) { switch (Depth) { - case 0: - if (KeyOption->KeyData.Options.ShiftPressed) { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_SHIFT_PRESSED, KeyShiftStates, KeyShiftStateCount); - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_SHIFT_PRESSED, KeyShiftStates, KeyShiftStateCount); - } else { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); - } - break; + case 0: + if (KeyOption->KeyData.Options.ShiftPressed) { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_SHIFT_PRESSED, KeyShiftStates, KeyShiftStateCount); + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_SHIFT_PRESSED, KeyShiftStates, KeyShiftStateCount); + } else { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); + } - case 1: - if (KeyOption->KeyData.Options.ControlPressed) { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_CONTROL_PRESSED, KeyShiftStates, KeyShiftStateCount); - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_CONTROL_PRESSED, KeyShiftStates, KeyShiftStateCount); - } else { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); - } - break; + break; - case 2: - if (KeyOption->KeyData.Options.AltPressed) { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_ALT_PRESSED, KeyShiftStates, KeyShiftStateCount); - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_ALT_PRESSED, KeyShiftStates, KeyShiftStateCount); - } else { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); - } - break; - case 3: - if (KeyOption->KeyData.Options.LogoPressed) { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_LOGO_PRESSED, KeyShiftStates, KeyShiftStateCount); - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_LOGO_PRESSED, KeyShiftStates, KeyShiftStateCount); - } else { - BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); - } - break; - case 4: - if (KeyOption->KeyData.Options.MenuPressed) { - KeyShiftState |= EFI_MENU_KEY_PRESSED; - } - if (KeyOption->KeyData.Options.SysReqPressed) { - KeyShiftState |= EFI_SYS_REQ_PRESSED; - } - KeyShiftStates[*KeyShiftStateCount] = KeyShiftState; - (*KeyShiftStateCount)++; - break; + case 1: + if (KeyOption->KeyData.Options.ControlPressed) { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_CONTROL_PRESSED, KeyShiftStates, KeyShiftStateCount); + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_CONTROL_PRESSED, KeyShiftStates, KeyShiftStateCount); + } else { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); + } + + break; + + case 2: + if (KeyOption->KeyData.Options.AltPressed) { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_ALT_PRESSED, KeyShiftStates, KeyShiftStateCount); + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_ALT_PRESSED, KeyShiftStates, KeyShiftStateCount); + } else { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); + } + + break; + case 3: + if (KeyOption->KeyData.Options.LogoPressed) { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_RIGHT_LOGO_PRESSED, KeyShiftStates, KeyShiftStateCount); + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState | EFI_LEFT_LOGO_PRESSED, KeyShiftStates, KeyShiftStateCount); + } else { + BmGenerateKeyShiftState (Depth + 1, KeyOption, KeyShiftState, KeyShiftStates, KeyShiftStateCount); + } + + break; + case 4: + if (KeyOption->KeyData.Options.MenuPressed) { + KeyShiftState |= EFI_MENU_KEY_PRESSED; + } + + if (KeyOption->KeyData.Options.SysReqPressed) { + KeyShiftState |= EFI_SYS_REQ_PRESSED; + } + + KeyShiftStates[*KeyShiftStateCount] = KeyShiftState; + (*KeyShiftStateCount)++; + break; } } @@ -636,22 +658,22 @@ BmGenerateKeyShiftState ( **/ EFI_STATUS BmProcessKeyOption ( - IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOption + IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOption ) { - EFI_STATUS Status; - EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *TxtInEx; - EFI_HANDLE *Handles; - UINTN HandleCount; - UINTN HandleIndex; - UINTN Index; - BM_HOTKEY *Hotkey; - UINTN KeyIndex; + EFI_STATUS Status; + EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *TxtInEx; + EFI_HANDLE *Handles; + UINTN HandleCount; + UINTN HandleIndex; + UINTN Index; + BM_HOTKEY *Hotkey; + UINTN KeyIndex; // // 16 is enough to enumerate all the possible combination of LEFT_XXX and RIGHT_XXX // - UINT32 KeyShiftStates[16]; - UINTN KeyShiftStateCount; + UINT32 KeyShiftStates[16]; + UINTN KeyShiftStateCount; if (KeyOption->KeyData.Options.InputKeyCount > mBmHotkeySupportCount) { return EFI_UNSUPPORTED; @@ -671,17 +693,18 @@ BmProcessKeyOption ( Hotkey->Signature = BM_HOTKEY_SIGNATURE; Hotkey->BootOption = KeyOption->BootOption; - Hotkey->IsContinue = (BOOLEAN) (KeyOption == mBmContinueKeyOption); - Hotkey->CodeCount = (UINT8) KeyOption->KeyData.Options.InputKeyCount; + Hotkey->IsContinue = (BOOLEAN)(KeyOption == mBmContinueKeyOption); + Hotkey->CodeCount = (UINT8)KeyOption->KeyData.Options.InputKeyCount; for (KeyIndex = 0; KeyIndex < Hotkey->CodeCount; KeyIndex++) { CopyMem (&Hotkey->KeyData[KeyIndex].Key, &KeyOption->Keys[KeyIndex], sizeof (EFI_INPUT_KEY)); Hotkey->KeyData[KeyIndex].KeyState.KeyShiftState = KeyShiftStates[Index]; } + InsertTailList (&mBmHotkeyList, &Hotkey->Link); for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) { - Status = gBS->HandleProtocol (Handles[HandleIndex], &gEfiSimpleTextInputExProtocolGuid, (VOID **) &TxtInEx); + Status = gBS->HandleProtocol (Handles[HandleIndex], &gEfiSimpleTextInputExProtocolGuid, (VOID **)&TxtInEx); ASSERT_EFI_ERROR (Status); BmRegisterHotkeyNotify (TxtInEx, Hotkey); } @@ -690,6 +713,7 @@ BmProcessKeyOption ( if (Handles != NULL) { FreePool (Handles); } + EfiReleaseLock (&mBmHotkeyLock); return EFI_SUCCESS; @@ -705,8 +729,8 @@ BmProcessKeyOption ( VOID EFIAPI BmTxtInExCallback ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { EFI_STATUS Status; @@ -717,24 +741,24 @@ BmTxtInExCallback ( while (TRUE) { BufferSize = sizeof (EFI_HANDLE); - Status = gBS->LocateHandle ( - ByRegisterNotify, - NULL, - mBmTxtInExRegistration, - &BufferSize, - &Handle - ); + Status = gBS->LocateHandle ( + ByRegisterNotify, + NULL, + mBmTxtInExRegistration, + &BufferSize, + &Handle + ); if (EFI_ERROR (Status)) { // // If no more notification events exist // - return ; + return; } Status = gBS->HandleProtocol ( Handle, &gEfiSimpleTextInputExProtocolGuid, - (VOID **) &TxtInEx + (VOID **)&TxtInEx ); ASSERT_EFI_ERROR (Status); @@ -745,6 +769,7 @@ BmTxtInExCallback ( for (Link = GetFirstNode (&mBmHotkeyList); !IsNull (&mBmHotkeyList, Link); Link = GetNextNode (&mBmHotkeyList, Link)) { BmRegisterHotkeyNotify (TxtInEx, BM_HOTKEY_FROM_LINK (Link)); } + EfiReleaseLock (&mBmHotkeyLock); } } @@ -760,8 +785,8 @@ BmTxtInExCallback ( **/ EFI_STATUS BmFreeKeyOptions ( - IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions, - IN UINTN KeyOptionCount + IN EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions, + IN UINTN KeyOptionCount ) { if (KeyOptions != NULL) { @@ -786,7 +811,7 @@ BmFreeKeyOptions ( EFI_STATUS EFIAPI EfiBootManagerRegisterContinueKeyOption ( - IN UINT32 Modifier, + IN UINT32 Modifier, ... ) { @@ -823,12 +848,12 @@ EfiBootManagerRegisterContinueKeyOption ( VOID EFIAPI BmStopHotkeyService ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ) { - LIST_ENTRY *Link; - BM_HOTKEY *Hotkey; + LIST_ENTRY *Link; + BM_HOTKEY *Hotkey; DEBUG ((DEBUG_INFO, "[Bds]Stop Hotkey Service!\n")); gBS->CloseEvent (Event); @@ -837,9 +862,10 @@ BmStopHotkeyService ( for (Link = GetFirstNode (&mBmHotkeyList); !IsNull (&mBmHotkeyList, Link); ) { Hotkey = BM_HOTKEY_FROM_LINK (Link); BmUnregisterHotkeyNotify (Hotkey); - Link = RemoveEntryList (Link); + Link = RemoveEntryList (Link); FreePool (Hotkey); } + EfiReleaseLock (&mBmHotkeyLock); } @@ -854,7 +880,7 @@ BmStopHotkeyService ( EFI_STATUS EFIAPI EfiBootManagerStartHotkeyService ( - IN EFI_EVENT *HotkeyTriggered + IN EFI_EVENT *HotkeyTriggered ) { EFI_STATUS Status; @@ -864,11 +890,12 @@ EfiBootManagerStartHotkeyService ( EFI_EVENT Event; UINT32 *BootOptionSupport; - GetEfiGlobalVariable2 (EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME, (VOID **) &BootOptionSupport, NULL); + GetEfiGlobalVariable2 (EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME, (VOID **)&BootOptionSupport, NULL); if (BootOptionSupport != NULL) { if ((*BootOptionSupport & EFI_BOOT_OPTION_SUPPORT_KEY) != 0) { mBmHotkeySupportCount = ((*BootOptionSupport & EFI_BOOT_OPTION_SUPPORT_COUNT) >> LowBitSet32 (EFI_BOOT_OPTION_SUPPORT_COUNT)); } + FreePool (BootOptionSupport); } @@ -891,9 +918,10 @@ EfiBootManagerStartHotkeyService ( } KeyOptions = BmGetKeyOptions (&KeyOptionCount); - for (Index = 0; Index < KeyOptionCount; Index ++) { + for (Index = 0; Index < KeyOptionCount; Index++) { BmProcessKeyOption (&KeyOptions[Index]); } + BmFreeKeyOptions (KeyOptions, KeyOptionCount); if (mBmContinueKeyOption != NULL) { @@ -942,27 +970,30 @@ EfiBootManagerStartHotkeyService ( EFI_STATUS EFIAPI EfiBootManagerAddKeyOptionVariable ( - OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption OPTIONAL, - IN UINT16 BootOptionNumber, - IN UINT32 Modifier, + OUT EFI_BOOT_MANAGER_KEY_OPTION *AddedOption OPTIONAL, + IN UINT16 BootOptionNumber, + IN UINT32 Modifier, ... ) { - EFI_STATUS Status; - VA_LIST Args; - VOID *BootOption; - UINTN BootOptionSize; - CHAR16 BootOptionName[BM_OPTION_NAME_LEN]; - EFI_BOOT_MANAGER_KEY_OPTION KeyOption; - EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; - UINTN KeyOptionCount; - UINTN Index; - UINTN KeyOptionNumber; - CHAR16 KeyOptionName[sizeof ("Key####")]; + EFI_STATUS Status; + VA_LIST Args; + VOID *BootOption; + UINTN BootOptionSize; + CHAR16 BootOptionName[BM_OPTION_NAME_LEN]; + EFI_BOOT_MANAGER_KEY_OPTION KeyOption; + EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; + UINTN KeyOptionCount; + UINTN Index; + UINTN KeyOptionNumber; + CHAR16 KeyOptionName[sizeof ("Key####")]; UnicodeSPrint ( - BootOptionName, sizeof (BootOptionName), L"%s%04x", - mBmLoadOptionName[LoadOptionTypeBoot], BootOptionNumber + BootOptionName, + sizeof (BootOptionName), + L"%s%04x", + mBmLoadOptionName[LoadOptionTypeBoot], + BootOptionNumber ); GetEfiGlobalVariable2 (BootOptionName, &BootOption, &BootOptionSize); @@ -972,7 +1003,7 @@ EfiBootManagerAddKeyOptionVariable ( ZeroMem (&KeyOption, sizeof (EFI_BOOT_MANAGER_KEY_OPTION)); KeyOption.BootOption = BootOptionNumber; - Status = gBS->CalculateCrc32 (BootOption, BootOptionSize, &KeyOption.BootOptionCrc); + Status = gBS->CalculateCrc32 (BootOption, BootOptionSize, &KeyOption.BootOptionCrc); ASSERT_EFI_ERROR (Status); FreePool (BootOption); @@ -990,16 +1021,19 @@ EfiBootManagerAddKeyOptionVariable ( KeyOptions = BmGetKeyOptions (&KeyOptionCount); for (Index = 0; Index < KeyOptionCount; Index++) { if ((KeyOptions[Index].KeyData.PackedValue == KeyOption.KeyData.PackedValue) && - (CompareMem (KeyOptions[Index].Keys, KeyOption.Keys, KeyOption.KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY)) == 0)) { + (CompareMem (KeyOptions[Index].Keys, KeyOption.Keys, KeyOption.KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY)) == 0)) + { break; } if ((KeyOptionNumber == LoadOptionNumberUnassigned) && (KeyOptions[Index].OptionNumber > Index) - ){ + ) + { KeyOptionNumber = Index; } } + BmFreeKeyOptions (KeyOptions, KeyOptionCount); if (Index < KeyOptionCount) { @@ -1053,22 +1087,22 @@ EfiBootManagerAddKeyOptionVariable ( EFI_STATUS EFIAPI EfiBootManagerDeleteKeyOptionVariable ( - IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption OPTIONAL, - IN UINT32 Modifier, + IN EFI_BOOT_MANAGER_KEY_OPTION *DeletedOption OPTIONAL, + IN UINT32 Modifier, ... ) { - EFI_STATUS Status; - UINTN Index; - VA_LIST Args; - EFI_BOOT_MANAGER_KEY_OPTION KeyOption; - EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; - UINTN KeyOptionCount; - LIST_ENTRY *Link; - BM_HOTKEY *Hotkey; - UINT32 ShiftState; - BOOLEAN Match; - CHAR16 KeyOptionName[sizeof ("Key####")]; + EFI_STATUS Status; + UINTN Index; + VA_LIST Args; + EFI_BOOT_MANAGER_KEY_OPTION KeyOption; + EFI_BOOT_MANAGER_KEY_OPTION *KeyOptions; + UINTN KeyOptionCount; + LIST_ENTRY *Link; + BM_HOTKEY *Hotkey; + UINT32 ShiftState; + BOOLEAN Match; + CHAR16 KeyOptionName[sizeof ("Key####")]; ZeroMem (&KeyOption, sizeof (EFI_BOOT_MANAGER_KEY_OPTION)); VA_START (Args, Modifier); @@ -1086,19 +1120,20 @@ EfiBootManagerDeleteKeyOptionVariable ( // for (Link = GetFirstNode (&mBmHotkeyList); !IsNull (&mBmHotkeyList, Link); ) { Hotkey = BM_HOTKEY_FROM_LINK (Link); - Match = (BOOLEAN) (Hotkey->CodeCount == KeyOption.KeyData.Options.InputKeyCount); + Match = (BOOLEAN)(Hotkey->CodeCount == KeyOption.KeyData.Options.InputKeyCount); for (Index = 0; Match && (Index < Hotkey->CodeCount); Index++) { ShiftState = Hotkey->KeyData[Index].KeyState.KeyShiftState; if ( - (BmBitSet (ShiftState, EFI_RIGHT_SHIFT_PRESSED | EFI_LEFT_SHIFT_PRESSED) != KeyOption.KeyData.Options.ShiftPressed) || - (BmBitSet (ShiftState, EFI_RIGHT_CONTROL_PRESSED | EFI_LEFT_CONTROL_PRESSED) != KeyOption.KeyData.Options.ControlPressed) || - (BmBitSet (ShiftState, EFI_RIGHT_ALT_PRESSED | EFI_LEFT_ALT_PRESSED) != KeyOption.KeyData.Options.AltPressed) || - (BmBitSet (ShiftState, EFI_RIGHT_LOGO_PRESSED | EFI_LEFT_LOGO_PRESSED) != KeyOption.KeyData.Options.LogoPressed) || - (BmBitSet (ShiftState, EFI_MENU_KEY_PRESSED) != KeyOption.KeyData.Options.MenuPressed) || - (BmBitSet (ShiftState, EFI_SYS_REQ_PRESSED) != KeyOption.KeyData.Options.SysReqPressed) || - (CompareMem (&Hotkey->KeyData[Index].Key, &KeyOption.Keys[Index], sizeof (EFI_INPUT_KEY)) != 0) - ) { + (BmBitSet (ShiftState, EFI_RIGHT_SHIFT_PRESSED | EFI_LEFT_SHIFT_PRESSED) != KeyOption.KeyData.Options.ShiftPressed) || + (BmBitSet (ShiftState, EFI_RIGHT_CONTROL_PRESSED | EFI_LEFT_CONTROL_PRESSED) != KeyOption.KeyData.Options.ControlPressed) || + (BmBitSet (ShiftState, EFI_RIGHT_ALT_PRESSED | EFI_LEFT_ALT_PRESSED) != KeyOption.KeyData.Options.AltPressed) || + (BmBitSet (ShiftState, EFI_RIGHT_LOGO_PRESSED | EFI_LEFT_LOGO_PRESSED) != KeyOption.KeyData.Options.LogoPressed) || + (BmBitSet (ShiftState, EFI_MENU_KEY_PRESSED) != KeyOption.KeyData.Options.MenuPressed) || + (BmBitSet (ShiftState, EFI_SYS_REQ_PRESSED) != KeyOption.KeyData.Options.SysReqPressed) || + (CompareMem (&Hotkey->KeyData[Index].Key, &KeyOption.Keys[Index], sizeof (EFI_INPUT_KEY)) != 0) + ) + { // // Break when any field doesn't match // @@ -1123,26 +1158,31 @@ EfiBootManagerDeleteKeyOptionVariable ( for (Index = 0; Index < KeyOptionCount; Index++) { if ((KeyOptions[Index].KeyData.PackedValue == KeyOption.KeyData.PackedValue) && (CompareMem ( - KeyOptions[Index].Keys, KeyOption.Keys, - KeyOption.KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY)) == 0) - ) { + KeyOptions[Index].Keys, + KeyOption.Keys, + KeyOption.KeyData.Options.InputKeyCount * sizeof (EFI_INPUT_KEY) + ) == 0) + ) + { UnicodeSPrint (KeyOptionName, sizeof (KeyOptionName), L"Key%04x", KeyOptions[Index].OptionNumber); Status = gRT->SetVariable ( - KeyOptionName, - &gEfiGlobalVariableGuid, - EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, - 0, - NULL - ); + KeyOptionName, + &gEfiGlobalVariableGuid, + EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE, + 0, + NULL + ); // // Return the deleted key option in case needed by caller // if (DeletedOption != NULL) { CopyMem (DeletedOption, &KeyOptions[Index], sizeof (EFI_BOOT_MANAGER_KEY_OPTION)); } + break; } } + BmFreeKeyOptions (KeyOptions, KeyOptionCount); EfiReleaseLock (&mBmHotkeyLock); diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c index de9dde2d3d..32a9cbb425 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c @@ -10,20 +10,20 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "InternalBm.h" GLOBAL_REMOVE_IF_UNREFERENCED - CHAR16 *mBmLoadOptionName[] = { - L"Driver", - L"SysPrep", - L"Boot", - L"PlatformRecovery" - }; +CHAR16 *mBmLoadOptionName[] = { + L"Driver", + L"SysPrep", + L"Boot", + L"PlatformRecovery" +}; GLOBAL_REMOVE_IF_UNREFERENCED - CHAR16 *mBmLoadOptionOrderName[] = { - EFI_DRIVER_ORDER_VARIABLE_NAME, - EFI_SYS_PREP_ORDER_VARIABLE_NAME, - EFI_BOOT_ORDER_VARIABLE_NAME, - NULL // PlatformRecovery#### doesn't have associated *Order variable - }; +CHAR16 *mBmLoadOptionOrderName[] = { + EFI_DRIVER_ORDER_VARIABLE_NAME, + EFI_SYS_PREP_ORDER_VARIABLE_NAME, + EFI_BOOT_ORDER_VARIABLE_NAME, + NULL // PlatformRecovery#### doesn't have associated *Order variable +}; /** Call Visitor function for each variable in variable storage. @@ -33,32 +33,33 @@ GLOBAL_REMOVE_IF_UNREFERENCED **/ VOID BmForEachVariable ( - BM_VARIABLE_VISITOR Visitor, - VOID *Context + BM_VARIABLE_VISITOR Visitor, + VOID *Context ) { - EFI_STATUS Status; - CHAR16 *Name; - EFI_GUID Guid; - UINTN NameSize; - UINTN NewNameSize; + EFI_STATUS Status; + CHAR16 *Name; + EFI_GUID Guid; + UINTN NameSize; + UINTN NewNameSize; NameSize = sizeof (CHAR16); - Name = AllocateZeroPool (NameSize); + Name = AllocateZeroPool (NameSize); ASSERT (Name != NULL); while (TRUE) { NewNameSize = NameSize; - Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid); + Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid); if (Status == EFI_BUFFER_TOO_SMALL) { Name = ReallocatePool (NameSize, NewNameSize, Name); ASSERT (Name != NULL); - Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid); + Status = gRT->GetNextVariableName (&NewNameSize, Name, &Guid); NameSize = NewNameSize; } if (Status == EFI_NOT_FOUND) { break; } + ASSERT_EFI_ERROR (Status); Visitor (Name, &Guid, Context); @@ -80,35 +81,37 @@ BmForEachVariable ( **/ EFI_STATUS BmGetFreeOptionNumber ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType, - OUT UINT16 *FreeOptionNumber + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType, + OUT UINT16 *FreeOptionNumber ) { - - UINTN OptionNumber; - UINTN Index; - UINT16 *OptionOrder; - UINTN OptionOrderSize; - UINT16 *BootNext; + UINTN OptionNumber; + UINTN Index; + UINT16 *OptionOrder; + UINTN OptionOrderSize; + UINT16 *BootNext; ASSERT (FreeOptionNumber != NULL); - ASSERT (LoadOptionType == LoadOptionTypeDriver || - LoadOptionType == LoadOptionTypeBoot || - LoadOptionType == LoadOptionTypeSysPrep); + ASSERT ( + LoadOptionType == LoadOptionTypeDriver || + LoadOptionType == LoadOptionTypeBoot || + LoadOptionType == LoadOptionTypeSysPrep + ); - GetEfiGlobalVariable2 (mBmLoadOptionOrderName[LoadOptionType], (VOID **) &OptionOrder, &OptionOrderSize); + GetEfiGlobalVariable2 (mBmLoadOptionOrderName[LoadOptionType], (VOID **)&OptionOrder, &OptionOrderSize); ASSERT ((OptionOrder != NULL && OptionOrderSize != 0) || (OptionOrder == NULL && OptionOrderSize == 0)); BootNext = NULL; if (LoadOptionType == LoadOptionTypeBoot) { - GetEfiGlobalVariable2 (L"BootNext", (VOID**) &BootNext, NULL); + GetEfiGlobalVariable2 (L"BootNext", (VOID **)&BootNext, NULL); } for (OptionNumber = 0; OptionNumber < OptionOrderSize / sizeof (UINT16) - + ((BootNext != NULL) ? 1 : 0); + + ((BootNext != NULL) ? 1 : 0); OptionNumber++ - ) { + ) + { // // Search in OptionOrder whether the OptionNumber exists // @@ -124,10 +127,12 @@ BmGetFreeOptionNumber ( // if ((Index == OptionOrderSize / sizeof (UINT16)) && ((BootNext == NULL) || (OptionNumber != *BootNext)) - ) { + ) + { break; } } + if (OptionOrder != NULL) { FreePool (OptionOrder); } @@ -144,7 +149,7 @@ BmGetFreeOptionNumber ( if (OptionNumber == 0x10000) { return EFI_OUT_OF_RESOURCES; } else { - *FreeOptionNumber = (UINT16) OptionNumber; + *FreeOptionNumber = (UINT16)OptionNumber; return EFI_SUCCESS; } } @@ -161,23 +166,24 @@ BmGetFreeOptionNumber ( EFI_STATUS EFIAPI EfiBootManagerLoadOptionToVariable ( - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Option + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { - EFI_STATUS Status; - UINTN VariableSize; - UINT8 *Variable; - UINT8 *Ptr; - CHAR16 OptionName[BM_OPTION_NAME_LEN]; - CHAR16 *Description; - CHAR16 NullChar; - EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock; - UINT32 VariableAttributes; + EFI_STATUS Status; + UINTN VariableSize; + UINT8 *Variable; + UINT8 *Ptr; + CHAR16 OptionName[BM_OPTION_NAME_LEN]; + CHAR16 *Description; + CHAR16 NullChar; + EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock; + UINT32 VariableAttributes; if ((Option->OptionNumber == LoadOptionNumberUnassigned) || (Option->FilePath == NULL) || - ((UINT32) Option->OptionType >= LoadOptionTypeMax) - ) { + ((UINT32)Option->OptionType >= LoadOptionTypeMax) + ) + { return EFI_INVALID_PARAMETER; } @@ -206,26 +212,26 @@ in the array is variable length, and ends at the device path end structure. */ VariableSize = sizeof (Option->Attributes) - + sizeof (UINT16) - + StrSize (Description) - + GetDevicePathSize (Option->FilePath) - + Option->OptionalDataSize; + + sizeof (UINT16) + + StrSize (Description) + + GetDevicePathSize (Option->FilePath) + + Option->OptionalDataSize; - Variable = AllocatePool (VariableSize); + Variable = AllocatePool (VariableSize); ASSERT (Variable != NULL); - Ptr = Variable; - WriteUnaligned32 ((UINT32 *) Ptr, Option->Attributes); - Ptr += sizeof (Option->Attributes); + Ptr = Variable; + WriteUnaligned32 ((UINT32 *)Ptr, Option->Attributes); + Ptr += sizeof (Option->Attributes); - WriteUnaligned16 ((UINT16 *) Ptr, (UINT16) GetDevicePathSize (Option->FilePath)); - Ptr += sizeof (UINT16); + WriteUnaligned16 ((UINT16 *)Ptr, (UINT16)GetDevicePathSize (Option->FilePath)); + Ptr += sizeof (UINT16); CopyMem (Ptr, Description, StrSize (Description)); - Ptr += StrSize (Description); + Ptr += StrSize (Description); CopyMem (Ptr, Option->FilePath, GetDevicePathSize (Option->FilePath)); - Ptr += GetDevicePathSize (Option->FilePath); + Ptr += GetDevicePathSize (Option->FilePath); CopyMem (Ptr, Option->OptionalData, Option->OptionalDataSize); @@ -236,11 +242,12 @@ structure. // // Lock the PlatformRecovery#### // - Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock); + Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **)&VariableLock); if (!EFI_ERROR (Status)) { Status = VariableLock->RequestToLock (VariableLock, OptionName, &gEfiGlobalVariableGuid); ASSERT_EFI_ERROR (Status); } + VariableAttributes = EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS; } @@ -270,20 +277,21 @@ structure. **/ EFI_STATUS BmAddOptionNumberToOrderVariable ( - IN CHAR16 *OptionOrderName, - IN UINT16 OptionNumber, - IN UINTN Position + IN CHAR16 *OptionOrderName, + IN UINT16 OptionNumber, + IN UINTN Position ) { - EFI_STATUS Status; - UINTN Index; - UINT16 *OptionOrder; - UINT16 *NewOptionOrder; - UINTN OptionOrderSize; + EFI_STATUS Status; + UINTN Index; + UINT16 *OptionOrder; + UINT16 *NewOptionOrder; + UINTN OptionOrderSize; + // // Update the option order variable // - GetEfiGlobalVariable2 (OptionOrderName, (VOID **) &OptionOrder, &OptionOrderSize); + GetEfiGlobalVariable2 (OptionOrderName, (VOID **)&OptionOrder, &OptionOrderSize); ASSERT ((OptionOrder != NULL && OptionOrderSize != 0) || (OptionOrder == NULL && OptionOrderSize == 0)); Status = EFI_SUCCESS; @@ -295,7 +303,7 @@ BmAddOptionNumberToOrderVariable ( } if (!EFI_ERROR (Status)) { - Position = MIN (Position, OptionOrderSize / sizeof (UINT16)); + Position = MIN (Position, OptionOrderSize / sizeof (UINT16)); NewOptionOrder = AllocatePool (OptionOrderSize + sizeof (UINT16)); ASSERT (NewOptionOrder != NULL); @@ -303,6 +311,7 @@ BmAddOptionNumberToOrderVariable ( CopyMem (NewOptionOrder, OptionOrder, Position * sizeof (UINT16)); CopyMem (&NewOptionOrder[Position + 1], &OptionOrder[Position], OptionOrderSize - Position * sizeof (UINT16)); } + NewOptionOrder[Position] = OptionNumber; Status = gRT->SetVariable ( @@ -345,21 +354,22 @@ BmAddOptionNumberToOrderVariable ( EFI_STATUS EFIAPI EfiBootManagerAddLoadOptionVariable ( - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, - IN UINTN Position + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, + IN UINTN Position ) { - EFI_STATUS Status; - UINT16 OptionNumber; + EFI_STATUS Status; + UINT16 OptionNumber; if (Option == NULL) { return EFI_INVALID_PARAMETER; } - if (Option->OptionType != LoadOptionTypeDriver && - Option->OptionType != LoadOptionTypeSysPrep && - Option->OptionType != LoadOptionTypeBoot - ) { + if ((Option->OptionType != LoadOptionTypeDriver) && + (Option->OptionType != LoadOptionTypeSysPrep) && + (Option->OptionType != LoadOptionTypeBoot) + ) + { return EFI_INVALID_PARAMETER; } @@ -371,6 +381,7 @@ EfiBootManagerAddLoadOptionVariable ( if (EFI_ERROR (Status)) { return Status; } + Option->OptionNumber = OptionNumber; } @@ -378,7 +389,7 @@ EfiBootManagerAddLoadOptionVariable ( return EFI_INVALID_PARAMETER; } - Status = BmAddOptionNumberToOrderVariable (mBmLoadOptionOrderName[Option->OptionType], (UINT16) Option->OptionNumber, Position); + Status = BmAddOptionNumberToOrderVariable (mBmLoadOptionOrderName[Option->OptionType], (UINT16)Option->OptionNumber, Position); if (!EFI_ERROR (Status)) { // // Save the Boot#### or Driver#### variable @@ -405,15 +416,15 @@ EfiBootManagerAddLoadOptionVariable ( VOID EFIAPI EfiBootManagerSortLoadOptionVariable ( - EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, - SORT_COMPARE CompareFunction + EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, + SORT_COMPARE CompareFunction ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption; - UINTN LoadOptionCount; - UINTN Index; - UINT16 *OptionOrder; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption; + UINTN LoadOptionCount; + UINTN Index; + UINT16 *OptionOrder; LoadOption = EfiBootManagerGetLoadOptions (&LoadOptionCount, OptionType); @@ -433,7 +444,7 @@ EfiBootManagerSortLoadOptionVariable ( OptionOrder = AllocatePool (LoadOptionCount * sizeof (UINT16)); ASSERT (OptionOrder != NULL); for (Index = 0; Index < LoadOptionCount; Index++) { - OptionOrder[Index] = (UINT16) LoadOption[Index].OptionNumber; + OptionOrder[Index] = (UINT16)LoadOption[Index].OptionNumber; } Status = gRT->SetVariable ( @@ -470,14 +481,14 @@ EfiBootManagerSortLoadOptionVariable ( EFI_STATUS EFIAPI EfiBootManagerInitializeLoadOption ( - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, - IN UINTN OptionNumber, - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, - IN UINT32 Attributes, - IN CHAR16 *Description, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN UINT8 *OptionalData OPTIONAL, - IN UINT32 OptionalDataSize + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option, + IN UINTN OptionNumber, + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType, + IN UINT32 Attributes, + IN CHAR16 *Description, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN UINT8 *OptionalData OPTIONAL, + IN UINT32 OptionalDataSize ) { if ((Option == NULL) || (Description == NULL) || (FilePath == NULL)) { @@ -485,20 +496,21 @@ EfiBootManagerInitializeLoadOption ( } if (((OptionalData != NULL) && (OptionalDataSize == 0)) || - ((OptionalData == NULL) && (OptionalDataSize != 0))) { + ((OptionalData == NULL) && (OptionalDataSize != 0))) + { return EFI_INVALID_PARAMETER; } - if ((UINT32) OptionType >= LoadOptionTypeMax) { + if ((UINT32)OptionType >= LoadOptionTypeMax) { return EFI_INVALID_PARAMETER; } ZeroMem (Option, sizeof (EFI_BOOT_MANAGER_LOAD_OPTION)); - Option->OptionNumber = OptionNumber; - Option->OptionType = OptionType; - Option->Attributes = Attributes; - Option->Description = AllocateCopyPool (StrSize (Description), Description); - Option->FilePath = DuplicateDevicePath (FilePath); + Option->OptionNumber = OptionNumber; + Option->OptionType = OptionType; + Option->Attributes = Attributes; + Option->Description = AllocateCopyPool (StrSize (Description), Description); + Option->FilePath = DuplicateDevicePath (FilePath); if (OptionalData != NULL) { Option->OptionalData = AllocateCopyPool (OptionalDataSize, OptionalData); Option->OptionalDataSize = OptionalDataSize; @@ -507,7 +519,6 @@ EfiBootManagerInitializeLoadOption ( return EFI_SUCCESS; } - /** Return the index of the load option in the load option array. @@ -524,12 +535,12 @@ EfiBootManagerInitializeLoadOption ( INTN EFIAPI EfiBootManagerFindLoadOption ( - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, - IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, - IN UINTN Count + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Key, + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *Array, + IN UINTN Count ) { - UINTN Index; + UINTN Index; for (Index = 0; Index < Count; Index++) { if ((Key->OptionType == Array[Index].OptionType) && @@ -537,8 +548,9 @@ EfiBootManagerFindLoadOption ( (StrCmp (Key->Description, Array[Index].Description) == 0) && (CompareMem (Key->FilePath, Array[Index].FilePath, GetDevicePathSize (Key->FilePath)) == 0) && (Key->OptionalDataSize == Array[Index].OptionalDataSize) && - (CompareMem (Key->OptionalData, Array[Index].OptionalData, Key->OptionalDataSize) == 0)) { - return (INTN) Index; + (CompareMem (Key->OptionalData, Array[Index].OptionalData, Key->OptionalDataSize) == 0)) + { + return (INTN)Index; } } @@ -563,21 +575,21 @@ EfiBootManagerDeleteLoadOptionVariable ( IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType ) { - UINT16 *OptionOrder; - UINTN OptionOrderSize; - UINTN Index; - CHAR16 OptionName[BM_OPTION_NAME_LEN]; + UINT16 *OptionOrder; + UINTN OptionOrderSize; + UINTN Index; + CHAR16 OptionName[BM_OPTION_NAME_LEN]; - if (((UINT32) OptionType >= LoadOptionTypeMax) || (OptionNumber >= LoadOptionNumberMax)) { + if (((UINT32)OptionType >= LoadOptionTypeMax) || (OptionNumber >= LoadOptionNumberMax)) { return EFI_INVALID_PARAMETER; } - if (OptionType == LoadOptionTypeDriver || OptionType == LoadOptionTypeSysPrep || OptionType == LoadOptionTypeBoot) { + if ((OptionType == LoadOptionTypeDriver) || (OptionType == LoadOptionTypeSysPrep) || (OptionType == LoadOptionTypeBoot)) { // // If the associated *Order exists, firstly remove the reference in *Order for // Driver####, SysPrep#### and Boot####. // - GetEfiGlobalVariable2 (mBmLoadOptionOrderName[OptionType], (VOID **) &OptionOrder, &OptionOrderSize); + GetEfiGlobalVariable2 (mBmLoadOptionOrderName[OptionType], (VOID **)&OptionOrder, &OptionOrderSize); ASSERT ((OptionOrder != NULL && OptionOrderSize != 0) || (OptionOrder == NULL && OptionOrderSize == 0)); for (Index = 0; Index < OptionOrderSize / sizeof (UINT16); Index++) { @@ -594,6 +606,7 @@ EfiBootManagerDeleteLoadOptionVariable ( break; } } + if (OptionOrder != NULL) { FreePool (OptionOrder); } @@ -650,12 +663,15 @@ BmGetDevicePathSizeEx ( if (NodeSize == 0) { return 0; } + Size += NodeSize; if (Size > MaxSize) { return 0; } + DevicePath = NextDevicePathNode (DevicePath); } + Size += DevicePathNodeLength (DevicePath); if (Size > MaxSize) { return 0; @@ -684,18 +700,19 @@ BmGetDevicePathSizeEx ( **/ UINTN BmStrSizeEx ( - IN CONST CHAR16 *String, - IN UINTN MaxStringLen + IN CONST CHAR16 *String, + IN UINTN MaxStringLen ) { - UINTN Length; + UINTN Length; ASSERT (String != NULL && MaxStringLen != 0); - ASSERT (((UINTN) String & BIT0) == 0); + ASSERT (((UINTN)String & BIT0) == 0); - for (Length = 0; *String != L'\0' && MaxStringLen != Length; String++, Length+=2); + for (Length = 0; *String != L'\0' && MaxStringLen != Length; String++, Length += 2) { + } - if (*String != L'\0' && MaxStringLen == Length) { + if ((*String != L'\0') && (MaxStringLen == Length)) { return 0; } @@ -715,8 +732,8 @@ BmStrSizeEx ( **/ BOOLEAN BmValidateOption ( - UINT8 *Variable, - UINTN VariableSize + UINT8 *Variable, + UINTN VariableSize ) { UINT16 FilePathSize; @@ -735,19 +752,19 @@ BmValidateOption ( // // Get the option's device path size // - FilePathSize = ReadUnaligned16 ((UINT16 *) Variable); - Variable += sizeof (UINT16); + FilePathSize = ReadUnaligned16 ((UINT16 *)Variable); + Variable += sizeof (UINT16); // // Get the option's description string size // - DescriptionSize = BmStrSizeEx ((CHAR16 *) Variable, VariableSize - sizeof (UINT16) - sizeof (UINT32)); - Variable += DescriptionSize; + DescriptionSize = BmStrSizeEx ((CHAR16 *)Variable, VariableSize - sizeof (UINT16) - sizeof (UINT32)); + Variable += DescriptionSize; // // Get the option's device path // - DevicePath = (EFI_DEVICE_PATH_PROTOCOL *) Variable; + DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)Variable; // // Validation boot option variable. @@ -760,7 +777,7 @@ BmValidateOption ( return FALSE; } - return (BOOLEAN) (BmGetDevicePathSizeEx (DevicePath, FilePathSize) != 0); + return (BOOLEAN)(BmGetDevicePathSizeEx (DevicePath, FilePathSize) != 0); } /** @@ -778,16 +795,16 @@ BmValidateOption ( BOOLEAN EFIAPI EfiBootManagerIsValidLoadOptionVariableName ( - IN CHAR16 *VariableName, - OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL, - OUT UINT16 *OptionNumber OPTIONAL + IN CHAR16 *VariableName, + OUT EFI_BOOT_MANAGER_LOAD_OPTION_TYPE *OptionType OPTIONAL, + OUT UINT16 *OptionNumber OPTIONAL ) { - UINTN VariableNameLen; - UINTN Index; - UINTN Uint; - EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LocalOptionType; - UINT16 LocalOptionNumber; + UINTN VariableNameLen; + UINTN Index; + UINTN Uint; + EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LocalOptionType; + UINT16 LocalOptionNumber; if (VariableName == NULL) { return FALSE; @@ -808,10 +825,12 @@ EfiBootManagerIsValidLoadOptionVariableName ( for (LocalOptionType = 0; LocalOptionType < ARRAY_SIZE (mBmLoadOptionName); LocalOptionType++) { if ((VariableNameLen - 4 == StrLen (mBmLoadOptionName[LocalOptionType])) && (StrnCmp (VariableName, mBmLoadOptionName[LocalOptionType], VariableNameLen - 4) == 0) - ) { + ) + { break; } } + if (LocalOptionType == ARRAY_SIZE (mBmLoadOptionName)) { return FALSE; } @@ -825,9 +844,10 @@ EfiBootManagerIsValidLoadOptionVariableName ( if (Uint == -1) { break; } else { - LocalOptionNumber = (UINT16) Uint + LocalOptionNumber * 0x10; + LocalOptionNumber = (UINT16)Uint + LocalOptionNumber * 0x10; } } + if (Index != VariableNameLen) { return FALSE; } @@ -857,9 +877,9 @@ EfiBootManagerIsValidLoadOptionVariableName ( EFI_STATUS EFIAPI EfiBootManagerVariableToLoadOptionEx ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { EFI_STATUS Status; @@ -886,7 +906,7 @@ EfiBootManagerVariableToLoadOptionEx ( // // Read the variable // - GetVariable2 (VariableName, VendorGuid, (VOID **) &Variable, &VariableSize); + GetVariable2 (VariableName, VendorGuid, (VOID **)&Variable, &VariableSize); if (Variable == NULL) { return EFI_NOT_FOUND; } @@ -894,7 +914,7 @@ EfiBootManagerVariableToLoadOptionEx ( // // Validate *#### variable data. // - if (!BmValidateOption(Variable, VariableSize)) { + if (!BmValidateOption (Variable, VariableSize)) { FreePool (Variable); return EFI_INVALID_PARAMETER; } @@ -902,33 +922,33 @@ EfiBootManagerVariableToLoadOptionEx ( // // Get the option attribute // - VariablePtr = Variable; - Attribute = ReadUnaligned32 ((UINT32 *) VariablePtr); + VariablePtr = Variable; + Attribute = ReadUnaligned32 ((UINT32 *)VariablePtr); VariablePtr += sizeof (UINT32); // // Get the option's device path size // - FilePathSize = ReadUnaligned16 ((UINT16 *) VariablePtr); + FilePathSize = ReadUnaligned16 ((UINT16 *)VariablePtr); VariablePtr += sizeof (UINT16); // // Get the option's description string // - Description = (CHAR16 *) VariablePtr; + Description = (CHAR16 *)VariablePtr; // // Get the option's description string size // - VariablePtr += StrSize ((CHAR16 *) VariablePtr); + VariablePtr += StrSize ((CHAR16 *)VariablePtr); // // Get the option's device path // - FilePath = (EFI_DEVICE_PATH_PROTOCOL *) VariablePtr; + FilePath = (EFI_DEVICE_PATH_PROTOCOL *)VariablePtr; VariablePtr += FilePathSize; - OptionalDataSize = (UINT32) (VariableSize - ((UINTN) VariablePtr - (UINTN) Variable)); + OptionalDataSize = (UINT32)(VariableSize - ((UINTN)VariablePtr - (UINTN)Variable)); if (OptionalDataSize == 0) { OptionalData = NULL; } else { @@ -965,18 +985,18 @@ Build the Boot#### or Driver#### option from the VariableName. EFI_STATUS EFIAPI EfiBootManagerVariableToLoadOption ( - IN CHAR16 *VariableName, - IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option + IN CHAR16 *VariableName, + IN OUT EFI_BOOT_MANAGER_LOAD_OPTION *Option ) { return EfiBootManagerVariableToLoadOptionEx (VariableName, &gEfiGlobalVariableGuid, Option); } typedef struct { - EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; - EFI_GUID *Guid; - EFI_BOOT_MANAGER_LOAD_OPTION *Options; - UINTN OptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; + EFI_GUID *Guid; + EFI_BOOT_MANAGER_LOAD_OPTION *Options; + UINTN OptionCount; } BM_COLLECT_LOAD_OPTIONS_PARAM; /** @@ -989,25 +1009,26 @@ typedef struct { **/ VOID BmCollectLoadOptions ( - IN CHAR16 *Name, - IN EFI_GUID *Guid, - IN VOID *Context + IN CHAR16 *Name, + IN EFI_GUID *Guid, + IN VOID *Context ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; - UINT16 OptionNumber; - EFI_BOOT_MANAGER_LOAD_OPTION Option; - UINTN Index; - BM_COLLECT_LOAD_OPTIONS_PARAM *Param; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION_TYPE OptionType; + UINT16 OptionNumber; + EFI_BOOT_MANAGER_LOAD_OPTION Option; + UINTN Index; + BM_COLLECT_LOAD_OPTIONS_PARAM *Param; - Param = (BM_COLLECT_LOAD_OPTIONS_PARAM *) Context; + Param = (BM_COLLECT_LOAD_OPTIONS_PARAM *)Context; if (CompareGuid (Guid, Param->Guid) && ( - Param->OptionType == LoadOptionTypePlatformRecovery && - EfiBootManagerIsValidLoadOptionVariableName (Name, &OptionType, &OptionNumber) && - OptionType == LoadOptionTypePlatformRecovery - )) { + (Param->OptionType == LoadOptionTypePlatformRecovery) && + EfiBootManagerIsValidLoadOptionVariableName (Name, &OptionType, &OptionNumber) && + (OptionType == LoadOptionTypePlatformRecovery) + )) + { Status = EfiBootManagerVariableToLoadOptionEx (Name, Guid, &Option); if (!EFI_ERROR (Status)) { for (Index = 0; Index < Param->OptionCount; Index++) { @@ -1015,6 +1036,7 @@ BmCollectLoadOptions ( break; } } + Param->Options = ReallocatePool ( Param->OptionCount * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), (Param->OptionCount + 1) * sizeof (EFI_BOOT_MANAGER_LOAD_OPTION), @@ -1047,24 +1069,24 @@ EfiBootManagerGetLoadOptions ( IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType ) { - EFI_STATUS Status; - UINT16 *OptionOrder; - UINTN OptionOrderSize; - UINTN Index; - UINTN OptionIndex; - EFI_BOOT_MANAGER_LOAD_OPTION *Options; - CHAR16 OptionName[BM_OPTION_NAME_LEN]; - UINT16 OptionNumber; - BM_COLLECT_LOAD_OPTIONS_PARAM Param; + EFI_STATUS Status; + UINT16 *OptionOrder; + UINTN OptionOrderSize; + UINTN Index; + UINTN OptionIndex; + EFI_BOOT_MANAGER_LOAD_OPTION *Options; + CHAR16 OptionName[BM_OPTION_NAME_LEN]; + UINT16 OptionNumber; + BM_COLLECT_LOAD_OPTIONS_PARAM Param; *OptionCount = 0; Options = NULL; - if (LoadOptionType == LoadOptionTypeDriver || LoadOptionType == LoadOptionTypeSysPrep || LoadOptionType == LoadOptionTypeBoot) { + if ((LoadOptionType == LoadOptionTypeDriver) || (LoadOptionType == LoadOptionTypeSysPrep) || (LoadOptionType == LoadOptionTypeBoot)) { // // Read the BootOrder, or DriverOrder variable. // - GetEfiGlobalVariable2 (mBmLoadOptionOrderName[LoadOptionType], (VOID **) &OptionOrder, &OptionOrderSize); + GetEfiGlobalVariable2 (mBmLoadOptionOrderName[LoadOptionType], (VOID **)&OptionOrder, &OptionOrderSize); if (OptionOrder == NULL) { return NULL; } @@ -1098,17 +1120,16 @@ EfiBootManagerGetLoadOptions ( ASSERT (Options != NULL); *OptionCount = OptionIndex; } - } else if (LoadOptionType == LoadOptionTypePlatformRecovery) { - Param.OptionType = LoadOptionTypePlatformRecovery; - Param.Options = NULL; + Param.OptionType = LoadOptionTypePlatformRecovery; + Param.Options = NULL; Param.OptionCount = 0; - Param.Guid = &gEfiGlobalVariableGuid; + Param.Guid = &gEfiGlobalVariableGuid; - BmForEachVariable (BmCollectLoadOptions, (VOID *) &Param); + BmForEachVariable (BmCollectLoadOptions, (VOID *)&Param); *OptionCount = Param.OptionCount; - Options = Param.Options; + Options = Param.Options; } return Options; @@ -1136,9 +1157,11 @@ EfiBootManagerFreeLoadOption ( if (LoadOption->Description != NULL) { FreePool (LoadOption->Description); } + if (LoadOption->FilePath != NULL) { FreePool (LoadOption->FilePath); } + if (LoadOption->OptionalData != NULL) { FreePool (LoadOption->OptionalData); } @@ -1164,13 +1187,13 @@ EfiBootManagerFreeLoadOptions ( IN UINTN OptionCount ) { - UINTN Index; + UINTN Index; if (Option == NULL) { return EFI_NOT_FOUND; } - for (Index = 0;Index < OptionCount; Index++) { + for (Index = 0; Index < OptionCount; Index++) { EfiBootManagerFreeLoadOption (&Option[Index]); } @@ -1195,40 +1218,43 @@ EfiBootManagerFreeLoadOptions ( **/ BOOLEAN BmIsLoadOptionPeHeaderValid ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, - IN VOID *FileBuffer, - IN UINTN FileSize + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, + IN VOID *FileBuffer, + IN UINTN FileSize ) { - EFI_IMAGE_DOS_HEADER *DosHeader; - EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHeader; - EFI_IMAGE_OPTIONAL_HEADER32 *OptionalHeader; - UINT16 Subsystem; + EFI_IMAGE_DOS_HEADER *DosHeader; + EFI_IMAGE_OPTIONAL_HEADER_UNION *PeHeader; + EFI_IMAGE_OPTIONAL_HEADER32 *OptionalHeader; + UINT16 Subsystem; - if (FileBuffer == NULL || FileSize == 0) { + if ((FileBuffer == NULL) || (FileSize == 0)) { return FALSE; } // // Read dos header // - DosHeader = (EFI_IMAGE_DOS_HEADER *) FileBuffer; - if (FileSize >= sizeof (EFI_IMAGE_DOS_HEADER) && - FileSize > DosHeader->e_lfanew && DosHeader->e_magic == EFI_IMAGE_DOS_SIGNATURE - ) { + DosHeader = (EFI_IMAGE_DOS_HEADER *)FileBuffer; + if ((FileSize >= sizeof (EFI_IMAGE_DOS_HEADER)) && + (FileSize > DosHeader->e_lfanew) && (DosHeader->e_magic == EFI_IMAGE_DOS_SIGNATURE) + ) + { // // Read and check PE signature // - PeHeader = (EFI_IMAGE_OPTIONAL_HEADER_UNION *) ((UINT8 *) FileBuffer + DosHeader->e_lfanew); - if (FileSize >= DosHeader->e_lfanew + sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION) && - PeHeader->Pe32.Signature == EFI_IMAGE_NT_SIGNATURE - ) { + PeHeader = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((UINT8 *)FileBuffer + DosHeader->e_lfanew); + if ((FileSize >= DosHeader->e_lfanew + sizeof (EFI_IMAGE_OPTIONAL_HEADER_UNION)) && + (PeHeader->Pe32.Signature == EFI_IMAGE_NT_SIGNATURE) + ) + { // // Check PE32 or PE32+ magic, and machine type // - OptionalHeader = (EFI_IMAGE_OPTIONAL_HEADER32 *) &PeHeader->Pe32.OptionalHeader; - if (OptionalHeader->Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC || - OptionalHeader->Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC) { + OptionalHeader = (EFI_IMAGE_OPTIONAL_HEADER32 *)&PeHeader->Pe32.OptionalHeader; + if ((OptionalHeader->Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) || + (OptionalHeader->Magic == EFI_IMAGE_NT_OPTIONAL_HDR64_MAGIC)) + { // // Check the Subsystem: // Driver#### must be of type BootServiceDriver or RuntimeDriver @@ -1236,12 +1262,13 @@ BmIsLoadOptionPeHeaderValid ( // Subsystem = OptionalHeader->Subsystem; if ((Type == LoadOptionTypeMax) || - (Type == LoadOptionTypeDriver && Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER) || - (Type == LoadOptionTypeDriver && Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) || - (Type == LoadOptionTypeSysPrep && Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) || - (Type == LoadOptionTypeBoot && Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) || - (Type == LoadOptionTypePlatformRecovery && Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) - ) { + ((Type == LoadOptionTypeDriver) && (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)) || + ((Type == LoadOptionTypeDriver) && (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)) || + ((Type == LoadOptionTypeSysPrep) && (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) || + ((Type == LoadOptionTypeBoot) && (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) || + ((Type == LoadOptionTypePlatformRecovery) && (Subsystem == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION)) + ) + { return TRUE; } } @@ -1273,22 +1300,22 @@ BmIsLoadOptionPeHeaderValid ( **/ VOID * BmGetNextLoadOptionBuffer ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, - OUT UINTN *FileSize + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, + OUT UINTN *FileSize ) { - VOID *FileBuffer; - EFI_DEVICE_PATH_PROTOCOL *PreFullPath; - EFI_DEVICE_PATH_PROTOCOL *CurFullPath; - UINTN LocalFileSize; - UINT32 AuthenticationStatus; - EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; + VOID *FileBuffer; + EFI_DEVICE_PATH_PROTOCOL *PreFullPath; + EFI_DEVICE_PATH_PROTOCOL *CurFullPath; + UINTN LocalFileSize; + UINT32 AuthenticationStatus; + EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath; LocalFileSize = 0; - FileBuffer = NULL; - CurFullPath = *FullPath; + FileBuffer = NULL; + CurFullPath = *FullPath; do { PreFullPath = CurFullPath; CurFullPath = BmGetNextLoadOptionDevicePath (FilePath, CurFullPath); @@ -1298,9 +1325,11 @@ BmGetNextLoadOptionBuffer ( if ((PreFullPath != NULL) && (PreFullPath != *FullPath)) { FreePool (PreFullPath); } + if (CurFullPath == NULL) { break; } + FileBuffer = GetFileBufferByFilePath (TRUE, CurFullPath, &LocalFileSize, &AuthenticationStatus); if ((FileBuffer != NULL) && !BmIsLoadOptionPeHeaderValid (Type, FileBuffer, LocalFileSize)) { // @@ -1321,7 +1350,7 @@ BmGetNextLoadOptionBuffer ( } while (FileBuffer == NULL); if (FileBuffer == NULL) { - CurFullPath = NULL; + CurFullPath = NULL; LocalFileSize = 0; } @@ -1349,18 +1378,18 @@ BmGetNextLoadOptionBuffer ( EFI_STATUS EFIAPI EfiBootManagerProcessLoadOption ( - IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption + IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOption ) { - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *PreFullPath; - EFI_DEVICE_PATH_PROTOCOL *CurFullPath; - EFI_HANDLE ImageHandle; - EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; - VOID *FileBuffer; - UINTN FileSize; - - if ((UINT32) LoadOption->OptionType >= LoadOptionTypeMax) { + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *PreFullPath; + EFI_DEVICE_PATH_PROTOCOL *CurFullPath; + EFI_HANDLE ImageHandle; + EFI_LOADED_IMAGE_PROTOCOL *ImageInfo; + VOID *FileBuffer; + UINTN FileSize; + + if ((UINT32)LoadOption->OptionType >= LoadOptionTypeMax) { return EFI_INVALID_PARAMETER; } @@ -1380,8 +1409,10 @@ EfiBootManagerProcessLoadOption ( // Load and start the load option. // DEBUG (( - DEBUG_INFO | DEBUG_LOAD, "Process %s%04x (%s) ...\n", - mBmLoadOptionName[LoadOption->OptionType], LoadOption->OptionNumber, + DEBUG_INFO | DEBUG_LOAD, + "Process %s%04x (%s) ...\n", + mBmLoadOptionName[LoadOption->OptionType], + LoadOption->OptionNumber, LoadOption->Description )); ImageHandle = NULL; @@ -1398,9 +1429,11 @@ EfiBootManagerProcessLoadOption ( if (PreFullPath != NULL) { FreePool (PreFullPath); } + if (FileBuffer == NULL) { break; } + Status = gBS->LoadImage ( FALSE, gImageHandle, @@ -1426,7 +1459,7 @@ EfiBootManagerProcessLoadOption ( ASSERT_EFI_ERROR (Status); ImageInfo->LoadOptionsSize = LoadOption->OptionalDataSize; - ImageInfo->LoadOptions = LoadOption->OptionalData; + ImageInfo->LoadOptions = LoadOption->OptionalData; // // Before calling the image, enable the Watchdog Timer for the 5-minute period // @@ -1434,9 +1467,12 @@ EfiBootManagerProcessLoadOption ( LoadOption->Status = gBS->StartImage (ImageHandle, &LoadOption->ExitDataSize, &LoadOption->ExitData); DEBUG (( - DEBUG_INFO | DEBUG_LOAD, "%s%04x Return Status = %r\n", - mBmLoadOptionName[LoadOption->OptionType], LoadOption->OptionNumber, LoadOption->Status - )); + DEBUG_INFO | DEBUG_LOAD, + "%s%04x Return Status = %r\n", + mBmLoadOptionName[LoadOption->OptionType], + LoadOption->OptionNumber, + LoadOption->Status + )); // // Clear the Watchdog Timer after the image returns diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmMisc.c b/MdeModulePkg/Library/UefiBootManagerLib/BmMisc.c index 6e7af3e3d9..a5e32ebdba 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmMisc.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmMisc.c @@ -37,27 +37,27 @@ BmDelPartMatchInstance ( NewDevicePath = NULL; TempNewDevicePath = NULL; - if (Multi == NULL || Single == NULL) { + if ((Multi == NULL) || (Single == NULL)) { return Multi; } - Instance = GetNextDevicePathInstance (&Multi, &InstanceSize); - SingleDpSize = GetDevicePathSize (Single) - END_DEVICE_PATH_LENGTH; - InstanceSize -= END_DEVICE_PATH_LENGTH; + Instance = GetNextDevicePathInstance (&Multi, &InstanceSize); + SingleDpSize = GetDevicePathSize (Single) - END_DEVICE_PATH_LENGTH; + InstanceSize -= END_DEVICE_PATH_LENGTH; while (Instance != NULL) { - if (CompareMem (Instance, Single, MIN (SingleDpSize, InstanceSize)) != 0) { // // Append the device path instance which does not match with Single // TempNewDevicePath = NewDevicePath; - NewDevicePath = AppendDevicePathInstance (NewDevicePath, Instance); + NewDevicePath = AppendDevicePathInstance (NewDevicePath, Instance); if (TempNewDevicePath != NULL) { - FreePool(TempNewDevicePath); + FreePool (TempNewDevicePath); } } - FreePool(Instance); + + FreePool (Instance); Instance = GetNextDevicePathInstance (&Multi, &InstanceSize); InstanceSize -= END_DEVICE_PATH_LENGTH; } @@ -88,7 +88,7 @@ BmMatchDevicePaths ( EFI_DEVICE_PATH_PROTOCOL *DevicePathInst; UINTN Size; - if (Multi == NULL || Single == NULL) { + if ((Multi == NULL) || (Single == NULL)) { return FALSE; } @@ -127,7 +127,7 @@ BmMatchDevicePaths ( **/ VOID BmSetMemoryTypeInformationVariable ( - IN BOOLEAN Boot + IN BOOLEAN Boot ) { EFI_STATUS Status; @@ -147,7 +147,6 @@ BmSetMemoryTypeInformationVariable ( MemoryTypeInformationModified = FALSE; MemoryTypeInformationVariableExists = FALSE; - BootMode = GetBootModeHob (); // // In BOOT_IN_RECOVERY_MODE, Variable region is not reliable. @@ -163,13 +162,13 @@ BmSetMemoryTypeInformationVariable ( // if (BootMode != BOOT_WITH_DEFAULT_SETTINGS) { VariableSize = 0; - Status = gRT->GetVariable ( - EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME, - &gEfiMemoryTypeInformationGuid, - NULL, - &VariableSize, - NULL - ); + Status = gRT->GetVariable ( + EFI_MEMORY_TYPE_INFORMATION_VARIABLE_NAME, + &gEfiMemoryTypeInformationGuid, + NULL, + &VariableSize, + NULL + ); if (Status == EFI_BUFFER_TOO_SMALL) { MemoryTypeInformationVariableExists = TRUE; } @@ -181,9 +180,9 @@ BmSetMemoryTypeInformationVariable ( // Status = EfiGetSystemConfigurationTable ( &gEfiMemoryTypeInformationGuid, - (VOID **) &CurrentMemoryTypeInformation + (VOID **)&CurrentMemoryTypeInformation ); - if (EFI_ERROR (Status) || CurrentMemoryTypeInformation == NULL) { + if (EFI_ERROR (Status) || (CurrentMemoryTypeInformation == NULL)) { return; } @@ -199,6 +198,7 @@ BmSetMemoryTypeInformationVariable ( // return; } + VariableSize = GET_GUID_HOB_DATA_SIZE (GuidHob); PreviousMemoryTypeInformation = AllocateCopyPool (VariableSize, GET_GUID_HOB_DATA (GuidHob)); if (PreviousMemoryTypeInformation == NULL) { @@ -213,12 +213,12 @@ BmSetMemoryTypeInformationVariable ( DEBUG ((DEBUG_INFO, "====== ======== ======== ========\n")); for (Index = 0; PreviousMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) { - for (Index1 = 0; CurrentMemoryTypeInformation[Index1].Type != EfiMaxMemoryType; Index1++) { if (PreviousMemoryTypeInformation[Index].Type == CurrentMemoryTypeInformation[Index1].Type) { break; } } + if (CurrentMemoryTypeInformation[Index1].Type == EfiMaxMemoryType) { continue; } @@ -244,13 +244,14 @@ BmSetMemoryTypeInformationVariable ( } else if (Current > Previous) { Next = Current + (Current >> 2); } - if (Next > 0 && Next < 4) { + + if ((Next > 0) && (Next < 4)) { Next = 4; } if (Next != Previous) { PreviousMemoryTypeInformation[Index].NumberOfPages = Next; - MemoryTypeInformationModified = TRUE; + MemoryTypeInformationModified = TRUE; } DEBUG ((DEBUG_INFO, " %02x %08x %08x %08x\n", PreviousMemoryTypeInformation[Index].Type, Previous, Current, Next)); @@ -286,6 +287,7 @@ BmSetMemoryTypeInformationVariable ( DEBUG ((DEBUG_ERROR, "Memory Type Information settings cannot be saved. OS S4 may fail!\n")); } } + FreePool (PreviousMemoryTypeInformation); } @@ -324,11 +326,11 @@ BmSetMemoryTypeInformationVariable ( **/ EFI_STATUS BmSetVariableAndReportStatusCodeOnError ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN UINT32 Attributes, - IN UINTN DataSize, - IN VOID *Data + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINT32 Attributes, + IN UINTN DataSize, + IN VOID *Data ) { EFI_STATUS Status; @@ -343,7 +345,7 @@ BmSetVariableAndReportStatusCodeOnError ( Data ); if (EFI_ERROR (Status)) { - NameSize = StrSize (VariableName); + NameSize = StrSize (VariableName); SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize); if (SetVariableStatus != NULL) { CopyGuid (&SetVariableStatus->Guid, VendorGuid); @@ -351,8 +353,8 @@ BmSetVariableAndReportStatusCodeOnError ( SetVariableStatus->DataSize = DataSize; SetVariableStatus->SetStatus = Status; SetVariableStatus->Attributes = Attributes; - CopyMem (SetVariableStatus + 1, VariableName, NameSize); - CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize); + CopyMem (SetVariableStatus + 1, VariableName, NameSize); + CopyMem (((UINT8 *)(SetVariableStatus + 1)) + NameSize, Data, DataSize); REPORT_STATUS_CODE_EX ( EFI_ERROR_CODE, @@ -371,7 +373,6 @@ BmSetVariableAndReportStatusCodeOnError ( return Status; } - /** Print the device path info. @@ -379,10 +380,10 @@ BmSetVariableAndReportStatusCodeOnError ( **/ VOID BmPrintDp ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath + EFI_DEVICE_PATH_PROTOCOL *DevicePath ) { - CHAR16 *Str; + CHAR16 *Str; Str = ConvertDevicePathToText (DevicePath, FALSE, FALSE); DEBUG ((DEBUG_INFO, "%s", Str)); @@ -401,7 +402,7 @@ BmPrintDp ( **/ UINTN BmCharToUint ( - IN CHAR16 Char + IN CHAR16 Char ) { if ((Char >= L'0') && (Char <= L'9')) { @@ -412,7 +413,7 @@ BmCharToUint ( return (Char - L'A' + 0xA); } - return (UINTN) -1; + return (UINTN)-1; } /** @@ -428,32 +429,32 @@ EfiBootManagerDispatchDeferredImages ( VOID ) { - EFI_STATUS Status; - EFI_DEFERRED_IMAGE_LOAD_PROTOCOL *DeferredImage; - UINTN HandleCount; - EFI_HANDLE *Handles; - UINTN Index; - UINTN ImageIndex; - EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath; - VOID *Image; - UINTN ImageSize; - BOOLEAN BootOption; - EFI_HANDLE ImageHandle; - UINTN ImageCount; - UINTN LoadCount; + EFI_STATUS Status; + EFI_DEFERRED_IMAGE_LOAD_PROTOCOL *DeferredImage; + UINTN HandleCount; + EFI_HANDLE *Handles; + UINTN Index; + UINTN ImageIndex; + EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath; + VOID *Image; + UINTN ImageSize; + BOOLEAN BootOption; + EFI_HANDLE ImageHandle; + UINTN ImageCount; + UINTN LoadCount; // // Find all the deferred image load protocols. // HandleCount = 0; - Handles = NULL; - Status = gBS->LocateHandleBuffer ( - ByProtocol, - &gEfiDeferredImageLoadProtocolGuid, - NULL, - &HandleCount, - &Handles - ); + Handles = NULL; + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiDeferredImageLoadProtocolGuid, + NULL, + &HandleCount, + &Handles + ); if (EFI_ERROR (Status)) { return EFI_NOT_FOUND; } @@ -461,12 +462,12 @@ EfiBootManagerDispatchDeferredImages ( ImageCount = 0; LoadCount = 0; for (Index = 0; Index < HandleCount; Index++) { - Status = gBS->HandleProtocol (Handles[Index], &gEfiDeferredImageLoadProtocolGuid, (VOID **) &DeferredImage); + Status = gBS->HandleProtocol (Handles[Index], &gEfiDeferredImageLoadProtocolGuid, (VOID **)&DeferredImage); if (EFI_ERROR (Status)) { continue; } - for (ImageIndex = 0; ;ImageIndex++) { + for (ImageIndex = 0; ; ImageIndex++) { // // Load all the deferred images in this protocol instance. // @@ -474,25 +475,26 @@ EfiBootManagerDispatchDeferredImages ( DeferredImage, ImageIndex, &ImageDevicePath, - (VOID **) &Image, + (VOID **)&Image, &ImageSize, &BootOption ); if (EFI_ERROR (Status)) { break; } + ImageCount++; // // Load and start the image. // Status = gBS->LoadImage ( - BootOption, - gImageHandle, - ImageDevicePath, - NULL, - 0, - &ImageHandle - ); + BootOption, + gImageHandle, + ImageDevicePath, + NULL, + 0, + &ImageHandle + ); if (EFI_ERROR (Status)) { // // With EFI_SECURITY_VIOLATION retval, the Image was loaded and an ImageHandle was created @@ -519,6 +521,7 @@ EfiBootManagerDispatchDeferredImages ( } } } + if (Handles != NULL) { FreePool (Handles); } diff --git a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h index ac866ac25f..a9b0d485ca 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h +++ b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h @@ -72,15 +72,15 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #if !defined (EFI_REMOVABLE_MEDIA_FILE_NAME) - #if defined (MDE_CPU_EBC) - // - // Uefi specification only defines the default boot file name for IA32, X64 - // and IPF processor, so need define boot file name for EBC architecture here. - // - #define EFI_REMOVABLE_MEDIA_FILE_NAME L"\\EFI\\BOOT\\BOOTEBC.EFI" - #else - #error "Can not determine the default boot file name for unknown processor type!" - #endif + #if defined (MDE_CPU_EBC) +// +// Uefi specification only defines the default boot file name for IA32, X64 +// and IPF processor, so need define boot file name for EBC architecture here. +// +#define EFI_REMOVABLE_MEDIA_FILE_NAME L"\\EFI\\BOOT\\BOOTEBC.EFI" + #else + #error "Can not determine the default boot file name for unknown processor type!" + #endif #endif typedef enum { @@ -95,21 +95,21 @@ typedef enum { typedef CHAR16 * -(* BM_GET_BOOT_DESCRIPTION) ( - IN EFI_HANDLE Handle +(*BM_GET_BOOT_DESCRIPTION) ( + IN EFI_HANDLE Handle ); // // PlatformRecovery#### is the load option with the longest name // -#define BM_OPTION_NAME_LEN sizeof ("PlatformRecovery####") +#define BM_OPTION_NAME_LEN sizeof ("PlatformRecovery####") extern CHAR16 *mBmLoadOptionName[]; // // Maximum number of reconnect retry to repair controller; it is to limit the // number of recursive call of BmRepairAllControllers. // -#define MAX_RECONNECT_REPAIR 10 +#define MAX_RECONNECT_REPAIR 10 /** Visitor function to be called by BmForEachVariable for each variable @@ -122,9 +122,9 @@ extern CHAR16 *mBmLoadOptionName[]; typedef VOID (*BM_VARIABLE_VISITOR) ( - CHAR16 *Name, - EFI_GUID *Guid, - VOID *Context + CHAR16 *Name, + EFI_GUID *Guid, + VOID *Context ); /** @@ -135,15 +135,15 @@ VOID **/ VOID BmForEachVariable ( - BM_VARIABLE_VISITOR Visitor, - VOID *Context + BM_VARIABLE_VISITOR Visitor, + VOID *Context ); -#define BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE SIGNATURE_32 ('b', 'm', 'd', 'h') +#define BM_BOOT_DESCRIPTION_ENTRY_SIGNATURE SIGNATURE_32 ('b', 'm', 'd', 'h') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler; + UINT32 Signature; + LIST_ENTRY Link; + EFI_BOOT_MANAGER_BOOT_DESCRIPTION_HANDLER Handler; } BM_BOOT_DESCRIPTION_ENTRY; /** @@ -154,22 +154,22 @@ typedef struct { **/ VOID BmRepairAllControllers ( - UINTN ReconnectRepairCount + UINTN ReconnectRepairCount ); -#define BM_HOTKEY_SIGNATURE SIGNATURE_32 ('b', 'm', 'h', 'k') +#define BM_HOTKEY_SIGNATURE SIGNATURE_32 ('b', 'm', 'h', 'k') typedef struct { - UINT32 Signature; - LIST_ENTRY Link; - - BOOLEAN IsContinue; - UINT16 BootOption; - UINT8 CodeCount; - UINT8 WaitingKey; - EFI_KEY_DATA KeyData[3]; + UINT32 Signature; + LIST_ENTRY Link; + + BOOLEAN IsContinue; + UINT16 BootOption; + UINT8 CodeCount; + UINT8 WaitingKey; + EFI_KEY_DATA KeyData[3]; } BM_HOTKEY; -#define BM_HOTKEY_FROM_LINK(a) CR (a, BM_HOTKEY, Link, BM_HOTKEY_SIGNATURE) +#define BM_HOTKEY_FROM_LINK(a) CR (a, BM_HOTKEY, Link, BM_HOTKEY_SIGNATURE) /** Get the Option Number that wasn't used. @@ -184,8 +184,8 @@ typedef struct { **/ EFI_STATUS BmGetFreeOptionNumber ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType, - OUT UINT16 *FreeOptionNumber + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType, + OUT UINT16 *FreeOptionNumber ); /** @@ -200,7 +200,7 @@ BmGetFreeOptionNumber ( **/ VOID BmSetMemoryTypeInformationVariable ( - IN BOOLEAN Boot + IN BOOLEAN Boot ); /** @@ -217,8 +217,8 @@ BmSetMemoryTypeInformationVariable ( **/ BOOLEAN BmMatchPartitionDevicePathNode ( - IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath, - IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath + IN EFI_DEVICE_PATH_PROTOCOL *BlockIoDevicePath, + IN HARDDRIVE_DEVICE_PATH *HardDriveDevicePath ); /** @@ -237,7 +237,7 @@ BmMatchPartitionDevicePathNode ( **/ EFI_STATUS BmConnectUsbShortFormDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *DevicePath + IN EFI_DEVICE_PATH_PROTOCOL *DevicePath ); /** @@ -249,8 +249,8 @@ BmConnectUsbShortFormDevicePath ( VOID EFIAPI BmStopHotkeyService ( - IN EFI_EVENT Event, - IN VOID *Context + IN EFI_EVENT Event, + IN VOID *Context ); /** @@ -288,11 +288,11 @@ BmStopHotkeyService ( **/ EFI_STATUS BmSetVariableAndReportStatusCodeOnError ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN UINT32 Attributes, - IN UINTN DataSize, - IN VOID *Data + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN UINT32 Attributes, + IN UINTN DataSize, + IN VOID *Data ); /** @@ -340,7 +340,7 @@ BmDelPartMatchInstance ( **/ VOID BmPrintDp ( - EFI_DEVICE_PATH_PROTOCOL *DevicePath + EFI_DEVICE_PATH_PROTOCOL *DevicePath ); /** @@ -353,7 +353,7 @@ BmPrintDp ( **/ UINTN BmCharToUint ( - IN CHAR16 Char + IN CHAR16 Char ); /** @@ -365,7 +365,7 @@ BmCharToUint ( **/ CHAR16 * BmGetBootDescription ( - IN EFI_HANDLE Handle + IN EFI_HANDLE Handle ); /** @@ -377,8 +377,8 @@ BmGetBootDescription ( **/ VOID BmMakeBootOptionDescriptionUnique ( - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, - UINTN BootOptionCount + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, + UINTN BootOptionCount ); /** @@ -391,8 +391,8 @@ BmMakeBootOptionDescriptionUnique ( **/ EFI_DEVICE_PATH_PROTOCOL * BmExpandLoadFile ( - IN EFI_HANDLE LoadFileHandle, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_HANDLE LoadFileHandle, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ); /** @@ -404,7 +404,7 @@ BmExpandLoadFile ( **/ EFI_DEVICE_PATH_PROTOCOL * BmGetRamDiskDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath ); /** @@ -418,7 +418,7 @@ BmGetRamDiskDevicePath ( **/ VOID BmDestroyRamDisk ( - IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath + IN EFI_DEVICE_PATH_PROTOCOL *RamDiskDevicePath ); /** @@ -434,8 +434,8 @@ BmDestroyRamDisk ( **/ EFI_DEVICE_PATH_PROTOCOL * BmGetNextLoadOptionDevicePath ( - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - IN EFI_DEVICE_PATH_PROTOCOL *FullPath + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + IN EFI_DEVICE_PATH_PROTOCOL *FullPath ); /** @@ -460,9 +460,10 @@ BmGetNextLoadOptionDevicePath ( **/ VOID * BmGetNextLoadOptionBuffer ( - IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, - IN EFI_DEVICE_PATH_PROTOCOL *FilePath, - OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, - OUT UINTN *FileSize + IN EFI_BOOT_MANAGER_LOAD_OPTION_TYPE Type, + IN EFI_DEVICE_PATH_PROTOCOL *FilePath, + OUT EFI_DEVICE_PATH_PROTOCOL **FullPath, + OUT UINTN *FileSize ); + #endif // _INTERNAL_BM_H_ diff --git a/MdeModulePkg/Library/UefiHiiLib/HiiLanguage.c b/MdeModulePkg/Library/UefiHiiLib/HiiLanguage.c index b2f3723242..47f03d540d 100644 --- a/MdeModulePkg/Library/UefiHiiLib/HiiLanguage.c +++ b/MdeModulePkg/Library/UefiHiiLib/HiiLanguage.c @@ -6,7 +6,6 @@ **/ - #include "InternalHiiLib.h" /** @@ -30,7 +29,7 @@ CHAR8 * EFIAPI HiiGetSupportedLanguages ( - IN EFI_HII_HANDLE HiiHandle + IN EFI_HII_HANDLE HiiHandle ) { EFI_STATUS Status; @@ -44,7 +43,7 @@ HiiGetSupportedLanguages ( // Retrieve the size required for the supported languages buffer. // LanguageSize = 0; - Status = gHiiString->GetLanguages (gHiiString, HiiHandle, &TempSupportedLanguages, &LanguageSize); + Status = gHiiString->GetLanguages (gHiiString, HiiHandle, &TempSupportedLanguages, &LanguageSize); // // If GetLanguages() returns EFI_SUCCESS for a zero size, @@ -87,4 +86,3 @@ HiiGetSupportedLanguages ( // return SupportedLanguages; } - diff --git a/MdeModulePkg/Library/UefiHiiLib/HiiLib.c b/MdeModulePkg/Library/UefiHiiLib/HiiLib.c index 6cca1ba1d6..63a37ab59a 100644 --- a/MdeModulePkg/Library/UefiHiiLib/HiiLib.c +++ b/MdeModulePkg/Library/UefiHiiLib/HiiLib.c @@ -8,32 +8,32 @@ #include "InternalHiiLib.h" -#define GUID_CONFIG_STRING_TYPE 0x00 -#define NAME_CONFIG_STRING_TYPE 0x01 -#define PATH_CONFIG_STRING_TYPE 0x02 +#define GUID_CONFIG_STRING_TYPE 0x00 +#define NAME_CONFIG_STRING_TYPE 0x01 +#define PATH_CONFIG_STRING_TYPE 0x02 -#define ACTION_SET_DEFAUTL_VALUE 0x01 -#define ACTION_VALIDATE_SETTING 0x02 +#define ACTION_SET_DEFAUTL_VALUE 0x01 +#define ACTION_VALIDATE_SETTING 0x02 #define HII_LIB_DEFAULT_VARSTORE_SIZE 0x200 typedef struct { - LIST_ENTRY Entry; // Link to Block array - UINT16 Offset; - UINT16 Width; - UINT8 OpCode; - UINT8 Scope; + LIST_ENTRY Entry; // Link to Block array + UINT16 Offset; + UINT16 Width; + UINT8 OpCode; + UINT8 Scope; } IFR_BLOCK_DATA; typedef struct { - EFI_VARSTORE_ID VarStoreId; - UINT16 Size; + EFI_VARSTORE_ID VarStoreId; + UINT16 Size; } IFR_VARSTORAGE_DATA; // // Template // -GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR16 mConfigHdrTemplate[] = L"GUID=00000000000000000000000000000000&NAME=0000&PATH=00"; +GLOBAL_REMOVE_IF_UNREFERENCED CONST CHAR16 mConfigHdrTemplate[] = L"GUID=00000000000000000000000000000000&NAME=0000&PATH=00"; EFI_FORM_BROWSER2_PROTOCOL *mUefiFormBrowser2 = NULL; @@ -60,8 +60,8 @@ GLOBAL_REMOVE_IF_UNREFERENCED CONST EFI_HII_PACKAGE_HEADER mEndOfPakageList = { EFI_STATUS EFIAPI InternalHiiExtractGuidFromHiiHandle ( - IN EFI_HII_HANDLE Handle, - OUT EFI_GUID *Guid + IN EFI_HII_HANDLE Handle, + OUT EFI_GUID *Guid ) { EFI_STATUS Status; @@ -74,7 +74,7 @@ InternalHiiExtractGuidFromHiiHandle ( // // Get HII PackageList // - BufferSize = 0; + BufferSize = 0; HiiPackageList = NULL; Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &BufferSize, HiiPackageList); @@ -86,6 +86,7 @@ InternalHiiExtractGuidFromHiiHandle ( Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &BufferSize, HiiPackageList); } + if (EFI_ERROR (Status)) { FreePool (HiiPackageList); return Status; @@ -159,6 +160,7 @@ HiiAddPackages ( for (Length = 0, VA_START (Args, DeviceHandle); (Package = VA_ARG (Args, UINT32 *)) != NULL; ) { Length += (ReadUnaligned32 (Package) - sizeof (UINT32)); } + VA_END (Args); // @@ -205,6 +207,7 @@ HiiAddPackages ( CopyMem (Data, Package + 1, Length); Data += Length; } + VA_END (Args); // @@ -248,17 +251,16 @@ HiiAddPackages ( VOID EFIAPI HiiRemovePackages ( - IN EFI_HII_HANDLE HiiHandle + IN EFI_HII_HANDLE HiiHandle ) { - EFI_STATUS Status; + EFI_STATUS Status; ASSERT (HiiHandle != NULL); Status = gHiiDatabase->RemovePackageList (gHiiDatabase, HiiHandle); ASSERT_EFI_ERROR (Status); } - /** Retrieves the array of all the HII Handles or the HII handles of a specific package list GUID in the HII Database. @@ -297,13 +299,13 @@ HiiGetHiiHandles ( // Retrieve the size required for the buffer of all HII handles. // HandleBufferLength = 0; - Status = gHiiDatabase->ListPackageLists ( - gHiiDatabase, - EFI_HII_PACKAGE_TYPE_ALL, - NULL, - &HandleBufferLength, - &TempHiiHandleBuffer - ); + Status = gHiiDatabase->ListPackageLists ( + gHiiDatabase, + EFI_HII_PACKAGE_TYPE_ALL, + NULL, + &HandleBufferLength, + &TempHiiHandleBuffer + ); // // If ListPackageLists() returns EFI_SUCCESS for a zero size, @@ -361,6 +363,7 @@ HiiGetHiiHandles ( HiiHandleBuffer[Index2++] = HiiHandleBuffer[Index1]; } } + if (Index2 > 0) { HiiHandleBuffer[Index2] = NULL; return HiiHandleBuffer; @@ -388,10 +391,10 @@ HiiGetHiiHandles ( **/ EFI_STATUS EFIAPI -HiiGetFormSetFromHiiHandle( - IN EFI_HII_HANDLE Handle, - OUT EFI_IFR_FORM_SET **Buffer, - OUT UINTN *BufferSize +HiiGetFormSetFromHiiHandle ( + IN EFI_HII_HANDLE Handle, + OUT EFI_IFR_FORM_SET **Buffer, + OUT UINTN *BufferSize ) { EFI_STATUS Status; @@ -407,7 +410,7 @@ HiiGetFormSetFromHiiHandle( UINT32 PackageListLength; EFI_HII_PACKAGE_HEADER PackageHeader; - TempSize = 0; + TempSize = 0; FormSetBuffer = NULL; TempBuffer = NULL; @@ -415,8 +418,8 @@ HiiGetFormSetFromHiiHandle( // Get HII PackageList // PackageListSize = 0; - HiiPackageList = NULL; - Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &PackageListSize, HiiPackageList); + HiiPackageList = NULL; + Status = gHiiDatabase->ExportPackageLists (gHiiDatabase, Handle, &PackageListSize, HiiPackageList); if (EFI_ERROR (Status) && (Status != EFI_BUFFER_TOO_SMALL)) { return Status; } @@ -432,12 +435,12 @@ HiiGetFormSetFromHiiHandle( // // Get Form package from this HII package List // - Status = EFI_NOT_FOUND; - Offset = sizeof (EFI_HII_PACKAGE_LIST_HEADER); + Status = EFI_NOT_FOUND; + Offset = sizeof (EFI_HII_PACKAGE_LIST_HEADER); PackageListLength = ReadUnaligned32 (&HiiPackageList->PackageLength); while (Offset < PackageListLength) { - Package = ((UINT8 *) HiiPackageList) + Offset; + Package = ((UINT8 *)HiiPackageList) + Offset; CopyMem (&PackageHeader, Package, sizeof (EFI_HII_PACKAGE_HEADER)); Offset += PackageHeader.Length; @@ -451,47 +454,51 @@ HiiGetFormSetFromHiiHandle( Offset2 = sizeof (EFI_HII_PACKAGE_HEADER); while (Offset2 < PackageHeader.Length) { OpCodeData = Package + Offset2; - Offset2 += ((EFI_IFR_OP_HEADER *) OpCodeData)->Length; + Offset2 += ((EFI_IFR_OP_HEADER *)OpCodeData)->Length; - if (((EFI_IFR_OP_HEADER *) OpCodeData)->OpCode != EFI_IFR_FORM_SET_OP) { + if (((EFI_IFR_OP_HEADER *)OpCodeData)->OpCode != EFI_IFR_FORM_SET_OP) { continue; } - if (FormSetBuffer != NULL){ + if (FormSetBuffer != NULL) { TempBuffer = ReallocatePool ( TempSize, - TempSize + ((EFI_IFR_OP_HEADER *) OpCodeData)->Length, + TempSize + ((EFI_IFR_OP_HEADER *)OpCodeData)->Length, FormSetBuffer ); if (TempBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } - CopyMem (TempBuffer + TempSize, OpCodeData, ((EFI_IFR_OP_HEADER *) OpCodeData)->Length); + + CopyMem (TempBuffer + TempSize, OpCodeData, ((EFI_IFR_OP_HEADER *)OpCodeData)->Length); FormSetBuffer = NULL; } else { - TempBuffer = AllocatePool (TempSize + ((EFI_IFR_OP_HEADER *) OpCodeData)->Length); + TempBuffer = AllocatePool (TempSize + ((EFI_IFR_OP_HEADER *)OpCodeData)->Length); if (TempBuffer == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Done; } - CopyMem (TempBuffer, OpCodeData, ((EFI_IFR_OP_HEADER *) OpCodeData)->Length); + + CopyMem (TempBuffer, OpCodeData, ((EFI_IFR_OP_HEADER *)OpCodeData)->Length); } - TempSize += ((EFI_IFR_OP_HEADER *) OpCodeData)->Length; + + TempSize += ((EFI_IFR_OP_HEADER *)OpCodeData)->Length; FormSetBuffer = TempBuffer; Status = EFI_SUCCESS; // - //One form package has one formset, exit current form package to search other form package in the packagelist. + // One form package has one formset, exit current form package to search other form package in the packagelist. // break; } } + Done: FreePool (HiiPackageList); *BufferSize = TempSize; - *Buffer = (EFI_IFR_FORM_SET *)FormSetBuffer; + *Buffer = (EFI_IFR_FORM_SET *)FormSetBuffer; return Status; } @@ -526,8 +533,8 @@ InternalHiiLowerConfigString ( Lower = TRUE; } else if (*String == L'&') { Lower = FALSE; - } else if (Lower && *String >= L'A' && *String <= L'F') { - *String = (CHAR16) (*String - L'A' + L'a'); + } else if (Lower && (*String >= L'A') && (*String <= L'F')) { + *String = (CHAR16)(*String - L'A' + L'a'); } } @@ -578,6 +585,7 @@ InternalHiiBlockToConfig ( if (EFI_ERROR (Status)) { return NULL; } + return ConfigResp; } @@ -617,8 +625,8 @@ InternalHiiBrowserCallback ( // Locate protocols // if (mUefiFormBrowser2 == NULL) { - Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **) &mUefiFormBrowser2); - if (EFI_ERROR (Status) || mUefiFormBrowser2 == NULL) { + Status = gBS->LocateProtocol (&gEfiFormBrowser2ProtocolGuid, NULL, (VOID **)&mUefiFormBrowser2); + if (EFI_ERROR (Status) || (mUefiFormBrowser2 == NULL)) { return NULL; } } @@ -635,13 +643,13 @@ InternalHiiBrowserCallback ( // Retrieve the length of the buffer required ResultsData from the Browser Callback // Status = mUefiFormBrowser2->BrowserCallback ( - mUefiFormBrowser2, - &ResultsDataSize, - &TempResultsData, - TRUE, - VariableGuid, - VariableName - ); + mUefiFormBrowser2, + &ResultsDataSize, + &TempResultsData, + TRUE, + VariableGuid, + VariableName + ); if (!EFI_ERROR (Status)) { // @@ -668,13 +676,13 @@ InternalHiiBrowserCallback ( // Retrieve or set the ResultsData from the Browser Callback // Status = mUefiFormBrowser2->BrowserCallback ( - mUefiFormBrowser2, - &ResultsDataSize, - ResultsData, - (BOOLEAN)(SetResultsData == NULL), - VariableGuid, - VariableName - ); + mUefiFormBrowser2, + &ResultsDataSize, + ResultsData, + (BOOLEAN)(SetResultsData == NULL), + VariableGuid, + VariableName + ); if (EFI_ERROR (Status)) { return NULL; } @@ -736,7 +744,7 @@ HiiConstructConfigHdr ( NameLength = StrLen (Name); } - DevicePath = NULL; + DevicePath = NULL; DevicePathSize = 0; // // Retrieve DevicePath Protocol associated with DriverHandle @@ -746,6 +754,7 @@ HiiConstructConfigHdr ( if (DevicePath == NULL) { return NULL; } + // // Compute the size of the device path in bytes // @@ -767,7 +776,7 @@ HiiConstructConfigHdr ( // StrCpyS (String, MaxLen, L"GUID="); ReturnString = String; - String += StrLen (String); + String += StrLen (String); if (Guid != NULL) { // @@ -795,7 +804,7 @@ HiiConstructConfigHdr ( // // Append Name converted to NameLength // - for (; *Name != L'\0'; Name++) { + for ( ; *Name != L'\0'; Name++) { UnicodeValueToStringS ( String, sizeof (CHAR16) * MaxLen - ((UINTN)String - (UINTN)ReturnString), @@ -856,20 +865,20 @@ HiiConstructConfigHdr ( **/ EFI_STATUS InternalHiiGetBufferFromString ( - IN EFI_STRING String, - IN UINT8 Flag, - OUT UINT8 **Buffer + IN EFI_STRING String, + IN UINT8 Flag, + OUT UINT8 **Buffer ) { - UINTN Length; - EFI_STRING ConfigHdr; - CHAR16 *StringPtr; - UINT8 *DataBuffer; - CHAR16 TemStr[5]; - UINTN Index; - UINT8 DigitUint8; - - if (String == NULL || Buffer == NULL) { + UINTN Length; + EFI_STRING ConfigHdr; + CHAR16 *StringPtr; + UINT8 *DataBuffer; + CHAR16 TemStr[5]; + UINTN Index; + UINT8 DigitUint8; + + if ((String == NULL) || (Buffer == NULL)) { return EFI_INVALID_PARAMETER; } @@ -880,68 +889,72 @@ InternalHiiGetBufferFromString ( // The content between 'GUID', 'NAME', 'PATH' of and '&' of next element // or '\0' (end of configuration string) is the UNICODE %02x bytes encoding string. // - for (Length = 0; *String != 0 && *String != L'&'; String++, Length++); + for (Length = 0; *String != 0 && *String != L'&'; String++, Length++) { + } switch (Flag) { - case GUID_CONFIG_STRING_TYPE: - case PATH_CONFIG_STRING_TYPE: - // - // The data in is encoded as hex UNICODE %02x bytes in the same order - // as the device path and Guid resides in RAM memory. - // Translate the data into binary. - // - DataBuffer = (UINT8 *) AllocateZeroPool ((Length + 1) / 2); - if (DataBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - // - // Convert binary byte one by one - // - ZeroMem (TemStr, sizeof (TemStr)); - for (Index = 0; Index < Length; Index ++) { - TemStr[0] = ConfigHdr[Index]; - DigitUint8 = (UINT8) StrHexToUint64 (TemStr); - if ((Index & 1) == 0) { - DataBuffer [Index/2] = DigitUint8; - } else { - DataBuffer [Index/2] = (UINT8) ((DataBuffer [Index/2] << 4) + DigitUint8); + case GUID_CONFIG_STRING_TYPE: + case PATH_CONFIG_STRING_TYPE: + // + // The data in is encoded as hex UNICODE %02x bytes in the same order + // as the device path and Guid resides in RAM memory. + // Translate the data into binary. + // + DataBuffer = (UINT8 *)AllocateZeroPool ((Length + 1) / 2); + if (DataBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; } - } - *Buffer = DataBuffer; - break; + // + // Convert binary byte one by one + // + ZeroMem (TemStr, sizeof (TemStr)); + for (Index = 0; Index < Length; Index++) { + TemStr[0] = ConfigHdr[Index]; + DigitUint8 = (UINT8)StrHexToUint64 (TemStr); + if ((Index & 1) == 0) { + DataBuffer[Index/2] = DigitUint8; + } else { + DataBuffer[Index/2] = (UINT8)((DataBuffer[Index/2] << 4) + DigitUint8); + } + } - case NAME_CONFIG_STRING_TYPE: - // - // Convert Config String to Unicode String, e.g. "0041004200430044" => "ABCD" - // + *Buffer = DataBuffer; + break; - // - // Add the tailling char L'\0' - // - DataBuffer = (UINT8 *) AllocateZeroPool ((Length/4 + 1) * sizeof (CHAR16)); - if (DataBuffer == NULL) { - return EFI_OUT_OF_RESOURCES; - } - // - // Convert character one by one - // - StringPtr = (CHAR16 *) DataBuffer; - ZeroMem (TemStr, sizeof (TemStr)); - for (Index = 0; Index < Length; Index += 4) { - StrnCpyS (TemStr, sizeof (TemStr) / sizeof (CHAR16), ConfigHdr + Index, 4); - StringPtr[Index/4] = (CHAR16) StrHexToUint64 (TemStr); - } - // - // Add tailing L'\0' character - // - StringPtr[Index/4] = L'\0'; + case NAME_CONFIG_STRING_TYPE: + // + // Convert Config String to Unicode String, e.g. "0041004200430044" => "ABCD" + // - *Buffer = DataBuffer; - break; + // + // Add the tailling char L'\0' + // + DataBuffer = (UINT8 *)AllocateZeroPool ((Length/4 + 1) * sizeof (CHAR16)); + if (DataBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } - default: - return EFI_INVALID_PARAMETER; + // + // Convert character one by one + // + StringPtr = (CHAR16 *)DataBuffer; + ZeroMem (TemStr, sizeof (TemStr)); + for (Index = 0; Index < Length; Index += 4) { + StrnCpyS (TemStr, sizeof (TemStr) / sizeof (CHAR16), ConfigHdr + Index, 4); + StringPtr[Index/4] = (CHAR16)StrHexToUint64 (TemStr); + } + + // + // Add tailing L'\0' character + // + StringPtr[Index/4] = L'\0'; + + *Buffer = DataBuffer; + break; + + default: + return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; @@ -964,8 +977,8 @@ BlockArrayCheck ( IN UINT16 VarWidth ) { - LIST_ENTRY *Link; - IFR_BLOCK_DATA *BlockData; + LIST_ENTRY *Link; + IFR_BLOCK_DATA *BlockData; // // No Request Block array, all vars are got. @@ -1007,17 +1020,17 @@ BlockArrayCheck ( EFI_STATUS EFIAPI InternalHiiGetValueOfNumber ( - IN EFI_STRING ValueString, - OUT UINT8 **ValueData, - OUT UINTN *ValueLength + IN EFI_STRING ValueString, + OUT UINT8 **ValueData, + OUT UINTN *ValueLength ) { - EFI_STRING StringPtr; - UINTN Length; - UINT8 *Buf; - UINT8 DigitUint8; - UINTN Index; - CHAR16 TemStr[2]; + EFI_STRING StringPtr; + UINTN Length; + UINT8 *Buf; + UINT8 DigitUint8; + UINTN Index; + CHAR16 TemStr[2]; ASSERT (ValueString != NULL && ValueData != NULL && ValueLength != NULL); ASSERT (*ValueString != L'\0'); @@ -1029,12 +1042,13 @@ InternalHiiGetValueOfNumber ( while (*StringPtr != L'\0' && *StringPtr != L'&') { StringPtr++; } + Length = StringPtr - ValueString; // // Allocate buffer to store the value // - Buf = (UINT8 *) AllocateZeroPool ((Length + 1) / 2); + Buf = (UINT8 *)AllocateZeroPool ((Length + 1) / 2); if (Buf == NULL) { return EFI_OUT_OF_RESOURCES; } @@ -1043,21 +1057,21 @@ InternalHiiGetValueOfNumber ( // Convert character one by one to the value buffer // ZeroMem (TemStr, sizeof (TemStr)); - for (Index = 0; Index < Length; Index ++) { - TemStr[0] = ValueString[Length - Index - 1]; - DigitUint8 = (UINT8) StrHexToUint64 (TemStr); + for (Index = 0; Index < Length; Index++) { + TemStr[0] = ValueString[Length - Index - 1]; + DigitUint8 = (UINT8)StrHexToUint64 (TemStr); if ((Index & 1) == 0) { - Buf [Index/2] = DigitUint8; + Buf[Index/2] = DigitUint8; } else { - Buf [Index/2] = (UINT8) ((DigitUint8 << 4) + Buf [Index/2]); + Buf[Index/2] = (UINT8)((DigitUint8 << 4) + Buf[Index/2]); } } // // Set the converted value and string length. // - *ValueData = Buf; - *ValueLength = Length; + *ValueData = Buf; + *ValueLength = Length; return EFI_SUCCESS; } @@ -1073,15 +1087,15 @@ InternalHiiGetValueOfNumber ( **/ EFI_STATUS GetValueFromRequest ( - IN CHAR16 *ConfigElement, - IN CHAR16 *VarName, - OUT UINT64 *VarValue + IN CHAR16 *ConfigElement, + IN CHAR16 *VarName, + OUT UINT64 *VarValue ) { - UINT8 *TmpBuffer; - CHAR16 *StringPtr; - UINTN Length; - EFI_STATUS Status; + UINT8 *TmpBuffer; + CHAR16 *StringPtr; + UINTN Length; + EFI_STATUS Status; // // Find VarName related string. @@ -1132,15 +1146,15 @@ GetValueFromRequest ( **/ EFI_STATUS ValidateQuestionFromVfr ( - IN EFI_HII_PACKAGE_LIST_HEADER *HiiPackageList, - IN UINTN PackageListLength, - IN EFI_GUID *VarGuid, - IN CHAR16 *VarName, - IN UINT8 *VarBuffer, - IN IFR_BLOCK_DATA *CurrentBlockArray, - IN CHAR16 *RequestElement, - IN EFI_HII_HANDLE HiiHandle, - IN BOOLEAN NameValueType + IN EFI_HII_PACKAGE_LIST_HEADER *HiiPackageList, + IN UINTN PackageListLength, + IN EFI_GUID *VarGuid, + IN CHAR16 *VarName, + IN UINT8 *VarBuffer, + IN IFR_BLOCK_DATA *CurrentBlockArray, + IN CHAR16 *RequestElement, + IN EFI_HII_HANDLE HiiHandle, + IN BOOLEAN NameValueType ) { IFR_BLOCK_DATA VarBlockData; @@ -1187,8 +1201,8 @@ ValidateQuestionFromVfr ( IfrEfiVarStore = NULL; ZeroMem (&VarStoreData, sizeof (IFR_VARSTORAGE_DATA)); ZeroMem (&VarBlockData, sizeof (VarBlockData)); - BitOffset = 0; - BitWidth = 0; + BitOffset = 0; + BitWidth = 0; QuestionReferBitField = FALSE; // @@ -1196,639 +1210,679 @@ ValidateQuestionFromVfr ( // PackageOffset = sizeof (EFI_HII_PACKAGE_LIST_HEADER); while (PackageOffset < PackageListLength) { - CopyMem (&PackageHeader, (UINT8 *) HiiPackageList + PackageOffset, sizeof (PackageHeader)); + CopyMem (&PackageHeader, (UINT8 *)HiiPackageList + PackageOffset, sizeof (PackageHeader)); // // Parse IFR opcode from the form package. // if (PackageHeader.Type == EFI_HII_PACKAGE_FORMS) { IfrOffset = sizeof (PackageHeader); - PackageData = (UINT8 *) HiiPackageList + PackageOffset; + PackageData = (UINT8 *)HiiPackageList + PackageOffset; while (IfrOffset < PackageHeader.Length) { - IfrOpHdr = (EFI_IFR_OP_HEADER *) (PackageData + IfrOffset); + IfrOpHdr = (EFI_IFR_OP_HEADER *)(PackageData + IfrOffset); // // Validate current setting to the value built in IFR opcode // switch (IfrOpHdr->OpCode) { - case EFI_IFR_VARSTORE_OP: - // - // VarStoreId has been found. No further found. - // - if (VarStoreData.VarStoreId != 0) { - break; - } - // - // Find the matched VarStoreId to the input VarGuid and VarName - // - IfrVarStore = (EFI_IFR_VARSTORE *) IfrOpHdr; - if (CompareGuid ((EFI_GUID *) (VOID *) &IfrVarStore->Guid, VarGuid)) { - VarStoreName = (CHAR8 *) IfrVarStore->Name; - for (Index = 0; VarStoreName[Index] != 0; Index ++) { - if ((CHAR16) VarStoreName[Index] != VarName[Index]) { - break; - } + case EFI_IFR_VARSTORE_OP: + // + // VarStoreId has been found. No further found. + // + if (VarStoreData.VarStoreId != 0) { + break; } + // - // The matched VarStore is found. + // Find the matched VarStoreId to the input VarGuid and VarName // - if ((VarStoreName[Index] != 0) || (VarName[Index] != 0)) { + IfrVarStore = (EFI_IFR_VARSTORE *)IfrOpHdr; + if (CompareGuid ((EFI_GUID *)(VOID *)&IfrVarStore->Guid, VarGuid)) { + VarStoreName = (CHAR8 *)IfrVarStore->Name; + for (Index = 0; VarStoreName[Index] != 0; Index++) { + if ((CHAR16)VarStoreName[Index] != VarName[Index]) { + break; + } + } + + // + // The matched VarStore is found. + // + if ((VarStoreName[Index] != 0) || (VarName[Index] != 0)) { + IfrVarStore = NULL; + } + } else { IfrVarStore = NULL; } - } else { - IfrVarStore = NULL; - } - if (IfrVarStore != NULL) { - VarStoreData.VarStoreId = IfrVarStore->VarStoreId; - VarStoreData.Size = IfrVarStore->Size; - } - break; - case EFI_IFR_VARSTORE_NAME_VALUE_OP: - // - // VarStoreId has been found. No further found. - // - if (VarStoreData.VarStoreId != 0) { - break; - } - // - // Find the matched VarStoreId to the input VarGuid - // - IfrNameValueStore = (EFI_IFR_VARSTORE_NAME_VALUE *) IfrOpHdr; - if (!CompareGuid ((EFI_GUID *) (VOID *) &IfrNameValueStore->Guid, VarGuid)) { - IfrNameValueStore = NULL; - } + if (IfrVarStore != NULL) { + VarStoreData.VarStoreId = IfrVarStore->VarStoreId; + VarStoreData.Size = IfrVarStore->Size; + } - if (IfrNameValueStore != NULL) { - VarStoreData.VarStoreId = IfrNameValueStore->VarStoreId; - } - break; - case EFI_IFR_VARSTORE_EFI_OP: - // - // VarStore is found. Don't need to search any more. - // - if (VarStoreData.VarStoreId != 0) { break; - } - - IfrEfiVarStore = (EFI_IFR_VARSTORE_EFI *) IfrOpHdr; + case EFI_IFR_VARSTORE_NAME_VALUE_OP: + // + // VarStoreId has been found. No further found. + // + if (VarStoreData.VarStoreId != 0) { + break; + } - // - // If the length is small than the structure, this is from old efi - // varstore definition. Old efi varstore get config directly from - // GetVariable function. - // - if (IfrOpHdr->Length < sizeof (EFI_IFR_VARSTORE_EFI)) { - break; - } + // + // Find the matched VarStoreId to the input VarGuid + // + IfrNameValueStore = (EFI_IFR_VARSTORE_NAME_VALUE *)IfrOpHdr; + if (!CompareGuid ((EFI_GUID *)(VOID *)&IfrNameValueStore->Guid, VarGuid)) { + IfrNameValueStore = NULL; + } - if (CompareGuid ((EFI_GUID *) (VOID *) &IfrEfiVarStore->Guid, VarGuid)) { - VarStoreName = (CHAR8 *) IfrEfiVarStore->Name; - for (Index = 0; VarStoreName[Index] != 0; Index ++) { - if ((CHAR16) VarStoreName[Index] != VarName[Index]) { - break; - } + if (IfrNameValueStore != NULL) { + VarStoreData.VarStoreId = IfrNameValueStore->VarStoreId; } + + break; + case EFI_IFR_VARSTORE_EFI_OP: // - // The matched VarStore is found. + // VarStore is found. Don't need to search any more. // - if ((VarStoreName[Index] != 0) || (VarName[Index] != 0)) { - IfrEfiVarStore = NULL; + if (VarStoreData.VarStoreId != 0) { + break; } - } else { - IfrEfiVarStore = NULL; - } - if (IfrEfiVarStore != NULL) { + IfrEfiVarStore = (EFI_IFR_VARSTORE_EFI *)IfrOpHdr; + // - // Find the matched VarStore + // If the length is small than the structure, this is from old efi + // varstore definition. Old efi varstore get config directly from + // GetVariable function. // - VarStoreData.VarStoreId = IfrEfiVarStore->VarStoreId; - VarStoreData.Size = IfrEfiVarStore->Size; - } - break; - case EFI_IFR_FORM_OP: - case EFI_IFR_FORM_MAP_OP: - // - // Check the matched VarStoreId is found. - // - if (VarStoreData.VarStoreId == 0) { - return EFI_SUCCESS; - } - break; - case EFI_IFR_ONE_OF_OP: - // - // Check whether current value is the one of option. - // - - // - // OneOf question is not in IFR Form. This IFR form is not valid. - // - if (VarStoreData.VarStoreId == 0) { - return EFI_INVALID_PARAMETER; - } - // - // Check whether this question is for the requested varstore. - // - IfrOneOf = (EFI_IFR_ONE_OF *) IfrOpHdr; - if (IfrOneOf->Question.VarStoreId != VarStoreData.VarStoreId) { - break; - } + if (IfrOpHdr->Length < sizeof (EFI_IFR_VARSTORE_EFI)) { + break; + } - if (NameValueType) { - QuestionName = HiiGetString (HiiHandle, IfrOneOf->Question.VarStoreInfo.VarName, NULL); - ASSERT (QuestionName != NULL); + if (CompareGuid ((EFI_GUID *)(VOID *)&IfrEfiVarStore->Guid, VarGuid)) { + VarStoreName = (CHAR8 *)IfrEfiVarStore->Name; + for (Index = 0; VarStoreName[Index] != 0; Index++) { + if ((CHAR16)VarStoreName[Index] != VarName[Index]) { + break; + } + } - if (StrStr (RequestElement, QuestionName) == NULL) { // - // This question is not in the current configuration string. Skip it. + // The matched VarStore is found. // - break; + if ((VarStoreName[Index] != 0) || (VarName[Index] != 0)) { + IfrEfiVarStore = NULL; + } + } else { + IfrEfiVarStore = NULL; } - Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); - if (EFI_ERROR (Status)) { - return Status; - } - } else { - // - // Get Offset by Question header and Width by DataType Flags - // - if (QuestionReferBitField) { + if (IfrEfiVarStore != NULL) { // - // Get the byte offset/width for bit field. + // Find the matched VarStore // - BitOffset = IfrOneOf->Question.VarStoreInfo.VarOffset; - BitWidth = IfrOneOf->Flags & EDKII_IFR_NUMERIC_SIZE_BIT; - Offset = BitOffset / 8; - TotalBits = BitOffset % 8 + BitWidth; - Width = (TotalBits % 8 == 0 ? TotalBits / 8: TotalBits / 8 + 1); - } else { - Offset = IfrOneOf->Question.VarStoreInfo.VarOffset; - Width = (UINT16) (1 << (IfrOneOf->Flags & EFI_IFR_NUMERIC_SIZE)); + VarStoreData.VarStoreId = IfrEfiVarStore->VarStoreId; + VarStoreData.Size = IfrEfiVarStore->Size; } + + break; + case EFI_IFR_FORM_OP: + case EFI_IFR_FORM_MAP_OP: // - // Check whether this question is in current block array. + // Check the matched VarStoreId is found. // - if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { - // - // This question is not in the current configuration string. Skip it. - // - break; + if (VarStoreData.VarStoreId == 0) { + return EFI_SUCCESS; } + + break; + case EFI_IFR_ONE_OF_OP: // - // Check this var question is in the var storage + // Check whether current value is the one of option. // - if ((Offset + Width) > VarStoreData.Size) { - // - // This question exceeds the var store size. - // + + // + // OneOf question is not in IFR Form. This IFR form is not valid. + // + if (VarStoreData.VarStoreId == 0) { return EFI_INVALID_PARAMETER; } // - // Get the current value for oneof opcode + // Check whether this question is for the requested varstore. // - VarValue = 0; - if (QuestionReferBitField) { + IfrOneOf = (EFI_IFR_ONE_OF *)IfrOpHdr; + if (IfrOneOf->Question.VarStoreId != VarStoreData.VarStoreId) { + break; + } + + if (NameValueType) { + QuestionName = HiiGetString (HiiHandle, IfrOneOf->Question.VarStoreInfo.VarName, NULL); + ASSERT (QuestionName != NULL); + + if (StrStr (RequestElement, QuestionName) == NULL) { + // + // This question is not in the current configuration string. Skip it. + // + break; + } + + Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); + if (EFI_ERROR (Status)) { + return Status; + } + } else { // - // Get the value in bit fields. + // Get Offset by Question header and Width by DataType Flags // - StartBit = BitOffset % 8; - EndBit = StartBit + BitWidth - 1; - CopyMem ((UINT8 *) &BufferValue, VarBuffer + Offset, Width); - VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); - } else { - CopyMem (&VarValue, VarBuffer + Offset, Width); - } - } - // - // Set Block Data, to be checked in the following Oneof option opcode. - // - VarBlockData.OpCode = IfrOpHdr->OpCode; - VarBlockData.Scope = IfrOpHdr->Scope; - break; - case EFI_IFR_NUMERIC_OP: - // - // Check the current value is in the numeric range. - // + if (QuestionReferBitField) { + // + // Get the byte offset/width for bit field. + // + BitOffset = IfrOneOf->Question.VarStoreInfo.VarOffset; + BitWidth = IfrOneOf->Flags & EDKII_IFR_NUMERIC_SIZE_BIT; + Offset = BitOffset / 8; + TotalBits = BitOffset % 8 + BitWidth; + Width = (TotalBits % 8 == 0 ? TotalBits / 8 : TotalBits / 8 + 1); + } else { + Offset = IfrOneOf->Question.VarStoreInfo.VarOffset; + Width = (UINT16)(1 << (IfrOneOf->Flags & EFI_IFR_NUMERIC_SIZE)); + } - // - // Numeric question is not in IFR Form. This IFR form is not valid. - // - if (VarStoreData.VarStoreId == 0) { - return EFI_INVALID_PARAMETER; - } - // - // Check whether this question is for the requested varstore. - // - IfrNumeric = (EFI_IFR_NUMERIC *) IfrOpHdr; - if (IfrNumeric->Question.VarStoreId != VarStoreData.VarStoreId) { - break; - } + // + // Check whether this question is in current block array. + // + if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { + // + // This question is not in the current configuration string. Skip it. + // + break; + } - if (NameValueType) { - QuestionName = HiiGetString (HiiHandle, IfrNumeric->Question.VarStoreInfo.VarName, NULL); - ASSERT (QuestionName != NULL); + // + // Check this var question is in the var storage + // + if ((Offset + Width) > VarStoreData.Size) { + // + // This question exceeds the var store size. + // + return EFI_INVALID_PARAMETER; + } - if (StrStr (RequestElement, QuestionName) == NULL) { // - // This question is not in the current configuration string. Skip it. + // Get the current value for oneof opcode // - break; + VarValue = 0; + if (QuestionReferBitField) { + // + // Get the value in bit fields. + // + StartBit = BitOffset % 8; + EndBit = StartBit + BitWidth - 1; + CopyMem ((UINT8 *)&BufferValue, VarBuffer + Offset, Width); + VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); + } else { + CopyMem (&VarValue, VarBuffer + Offset, Width); + } } - Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); - if (EFI_ERROR (Status)) { - return Status; - } - } else { // - // Get Offset by Question header and Width by DataType Flags + // Set Block Data, to be checked in the following Oneof option opcode. // - if (QuestionReferBitField) { - // - // Get the byte offset/width for bit field. - // - BitOffset = IfrNumeric->Question.VarStoreInfo.VarOffset; - BitWidth = IfrNumeric->Flags & EDKII_IFR_NUMERIC_SIZE_BIT; - Offset = BitOffset / 8; - TotalBits = BitOffset % 8 + BitWidth; - Width = (TotalBits % 8 == 0 ? TotalBits / 8: TotalBits / 8 + 1); - } else { - Offset = IfrNumeric->Question.VarStoreInfo.VarOffset; - Width = (UINT16) (1 << (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE)); - } + VarBlockData.OpCode = IfrOpHdr->OpCode; + VarBlockData.Scope = IfrOpHdr->Scope; + break; + case EFI_IFR_NUMERIC_OP: // - // Check whether this question is in current block array. + // Check the current value is in the numeric range. // - if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { - // - // This question is not in the current configuration string. Skip it. - // - break; - } + // - // Check this var question is in the var storage + // Numeric question is not in IFR Form. This IFR form is not valid. // - if ((Offset + Width) > VarStoreData.Size) { - // - // This question exceeds the var store size. - // + if (VarStoreData.VarStoreId == 0) { return EFI_INVALID_PARAMETER; } // - // Check the current value is in the numeric range. + // Check whether this question is for the requested varstore. // - VarValue = 0; - if (QuestionReferBitField) { - // - // Get the value in the bit fields. - // - StartBit = BitOffset % 8; - EndBit = StartBit + BitWidth - 1; - CopyMem ((UINT8 *) &BufferValue, VarBuffer + Offset, Width); - VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); - } else { - CopyMem (&VarValue, VarBuffer + Offset, Width); + IfrNumeric = (EFI_IFR_NUMERIC *)IfrOpHdr; + if (IfrNumeric->Question.VarStoreId != VarStoreData.VarStoreId) { + break; } - } - if ( QuestionReferBitField) { - // - // Value in bit fields was stored as UINt32 type. - // - if ((IfrNumeric->Flags & EDKII_IFR_DISPLAY_BIT) == 0) { - if ((INT32) VarValue < (INT32) IfrNumeric->data.u32.MinValue || (INT32) VarValue > (INT32) IfrNumeric->data.u32.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } - } else { - if (VarValue < IfrNumeric->data.u32.MinValue || VarValue > IfrNumeric->data.u32.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } - } - } else { - if ((IfrNumeric->Flags & EFI_IFR_DISPLAY) == 0) { - switch (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE) { - case EFI_IFR_NUMERIC_SIZE_1: - if ((INT8) VarValue < (INT8) IfrNumeric->data.u8.MinValue || (INT8) VarValue > (INT8) IfrNumeric->data.u8.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } + + if (NameValueType) { + QuestionName = HiiGetString (HiiHandle, IfrNumeric->Question.VarStoreInfo.VarName, NULL); + ASSERT (QuestionName != NULL); + + if (StrStr (RequestElement, QuestionName) == NULL) { + // + // This question is not in the current configuration string. Skip it. + // break; - case EFI_IFR_NUMERIC_SIZE_2: - if ((INT16) VarValue < (INT16) IfrNumeric->data.u16.MinValue || (INT16) VarValue > (INT16) IfrNumeric->data.u16.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } + } + + Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); + if (EFI_ERROR (Status)) { + return Status; + } + } else { + // + // Get Offset by Question header and Width by DataType Flags + // + if (QuestionReferBitField) { + // + // Get the byte offset/width for bit field. + // + BitOffset = IfrNumeric->Question.VarStoreInfo.VarOffset; + BitWidth = IfrNumeric->Flags & EDKII_IFR_NUMERIC_SIZE_BIT; + Offset = BitOffset / 8; + TotalBits = BitOffset % 8 + BitWidth; + Width = (TotalBits % 8 == 0 ? TotalBits / 8 : TotalBits / 8 + 1); + } else { + Offset = IfrNumeric->Question.VarStoreInfo.VarOffset; + Width = (UINT16)(1 << (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE)); + } + + // + // Check whether this question is in current block array. + // + if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { + // + // This question is not in the current configuration string. Skip it. + // break; - case EFI_IFR_NUMERIC_SIZE_4: - if ((INT32) VarValue < (INT32) IfrNumeric->data.u32.MinValue || (INT32) VarValue > (INT32) IfrNumeric->data.u32.MaxValue) { + } + + // + // Check this var question is in the var storage + // + if ((Offset + Width) > VarStoreData.Size) { + // + // This question exceeds the var store size. + // + return EFI_INVALID_PARAMETER; + } + + // + // Check the current value is in the numeric range. + // + VarValue = 0; + if (QuestionReferBitField) { + // + // Get the value in the bit fields. + // + StartBit = BitOffset % 8; + EndBit = StartBit + BitWidth - 1; + CopyMem ((UINT8 *)&BufferValue, VarBuffer + Offset, Width); + VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); + } else { + CopyMem (&VarValue, VarBuffer + Offset, Width); + } + } + + if ( QuestionReferBitField) { + // + // Value in bit fields was stored as UINt32 type. + // + if ((IfrNumeric->Flags & EDKII_IFR_DISPLAY_BIT) == 0) { + if (((INT32)VarValue < (INT32)IfrNumeric->data.u32.MinValue) || ((INT32)VarValue > (INT32)IfrNumeric->data.u32.MaxValue)) { // // Not in the valid range. // return EFI_INVALID_PARAMETER; } - break; - case EFI_IFR_NUMERIC_SIZE_8: - if ((INT64) VarValue < (INT64) IfrNumeric->data.u64.MinValue || (INT64) VarValue > (INT64) IfrNumeric->data.u64.MaxValue) { + } else { + if ((VarValue < IfrNumeric->data.u32.MinValue) || (VarValue > IfrNumeric->data.u32.MaxValue)) { // // Not in the valid range. // return EFI_INVALID_PARAMETER; } - break; } } else { - switch (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE) { - case EFI_IFR_NUMERIC_SIZE_1: - if ((UINT8) VarValue < IfrNumeric->data.u8.MinValue || (UINT8) VarValue > IfrNumeric->data.u8.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; + if ((IfrNumeric->Flags & EFI_IFR_DISPLAY) == 0) { + switch (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE) { + case EFI_IFR_NUMERIC_SIZE_1: + if (((INT8)VarValue < (INT8)IfrNumeric->data.u8.MinValue) || ((INT8)VarValue > (INT8)IfrNumeric->data.u8.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_2: + if (((INT16)VarValue < (INT16)IfrNumeric->data.u16.MinValue) || ((INT16)VarValue > (INT16)IfrNumeric->data.u16.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_4: + if (((INT32)VarValue < (INT32)IfrNumeric->data.u32.MinValue) || ((INT32)VarValue > (INT32)IfrNumeric->data.u32.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_8: + if (((INT64)VarValue < (INT64)IfrNumeric->data.u64.MinValue) || ((INT64)VarValue > (INT64)IfrNumeric->data.u64.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; } - break; - case EFI_IFR_NUMERIC_SIZE_2: - if ((UINT16) VarValue < IfrNumeric->data.u16.MinValue || (UINT16) VarValue > IfrNumeric->data.u16.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; + } else { + switch (IfrNumeric->Flags & EFI_IFR_NUMERIC_SIZE) { + case EFI_IFR_NUMERIC_SIZE_1: + if (((UINT8)VarValue < IfrNumeric->data.u8.MinValue) || ((UINT8)VarValue > IfrNumeric->data.u8.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_2: + if (((UINT16)VarValue < IfrNumeric->data.u16.MinValue) || ((UINT16)VarValue > IfrNumeric->data.u16.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_4: + if (((UINT32)VarValue < IfrNumeric->data.u32.MinValue) || ((UINT32)VarValue > IfrNumeric->data.u32.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; + case EFI_IFR_NUMERIC_SIZE_8: + if (((UINT64)VarValue < IfrNumeric->data.u64.MinValue) || ((UINT64)VarValue > IfrNumeric->data.u64.MaxValue)) { + // + // Not in the valid range. + // + return EFI_INVALID_PARAMETER; + } + + break; } - break; - case EFI_IFR_NUMERIC_SIZE_4: - if ((UINT32) VarValue < IfrNumeric->data.u32.MinValue || (UINT32) VarValue > IfrNumeric->data.u32.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } - break; - case EFI_IFR_NUMERIC_SIZE_8: - if ((UINT64) VarValue < IfrNumeric->data.u64.MinValue || (UINT64) VarValue > IfrNumeric->data.u64.MaxValue) { - // - // Not in the valid range. - // - return EFI_INVALID_PARAMETER; - } - break; } } - } - break; - case EFI_IFR_CHECKBOX_OP: - // - // Check value is BOOLEAN type, only 0 and 1 is valid. - // - - // - // CheckBox question is not in IFR Form. This IFR form is not valid. - // - if (VarStoreData.VarStoreId == 0) { - return EFI_INVALID_PARAMETER; - } - // - // Check whether this question is for the requested varstore. - // - IfrCheckBox = (EFI_IFR_CHECKBOX *) IfrOpHdr; - if (IfrCheckBox->Question.VarStoreId != VarStoreData.VarStoreId) { break; - } - - if (NameValueType) { - QuestionName = HiiGetString (HiiHandle, IfrCheckBox->Question.VarStoreInfo.VarName, NULL); - ASSERT (QuestionName != NULL); - - if (StrStr (RequestElement, QuestionName) == NULL) { - // - // This question is not in the current configuration string. Skip it. - // - break; - } + case EFI_IFR_CHECKBOX_OP: + // + // Check value is BOOLEAN type, only 0 and 1 is valid. + // - Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); - if (EFI_ERROR (Status)) { - return Status; - } - } else { // - // Get Offset by Question header + // CheckBox question is not in IFR Form. This IFR form is not valid. // - if (QuestionReferBitField) { - // - // Get the byte offset/width for bit field. - // - BitOffset = IfrCheckBox->Question.VarStoreInfo.VarOffset; - BitWidth = 1; - Offset = BitOffset / 8; - TotalBits = BitOffset % 8 + BitWidth; - Width = (TotalBits % 8 == 0 ? TotalBits / 8: TotalBits / 8 + 1); - } else { - Offset = IfrCheckBox->Question.VarStoreInfo.VarOffset; - Width = (UINT16) sizeof (BOOLEAN); + if (VarStoreData.VarStoreId == 0) { + return EFI_INVALID_PARAMETER; } + // - // Check whether this question is in current block array. + // Check whether this question is for the requested varstore. // - if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { - // - // This question is not in the current configuration string. Skip it. - // + IfrCheckBox = (EFI_IFR_CHECKBOX *)IfrOpHdr; + if (IfrCheckBox->Question.VarStoreId != VarStoreData.VarStoreId) { break; } - // - // Check this var question is in the var storage - // - if ((Offset + Width) > VarStoreData.Size) { + + if (NameValueType) { + QuestionName = HiiGetString (HiiHandle, IfrCheckBox->Question.VarStoreInfo.VarName, NULL); + ASSERT (QuestionName != NULL); + + if (StrStr (RequestElement, QuestionName) == NULL) { + // + // This question is not in the current configuration string. Skip it. + // + break; + } + + Status = GetValueFromRequest (RequestElement, QuestionName, &VarValue); + if (EFI_ERROR (Status)) { + return Status; + } + } else { // - // This question exceeds the var store size. + // Get Offset by Question header // - return EFI_INVALID_PARAMETER; - } - // - // Check the current value is in the numeric range. - // - VarValue = 0; - if (QuestionReferBitField) { + if (QuestionReferBitField) { + // + // Get the byte offset/width for bit field. + // + BitOffset = IfrCheckBox->Question.VarStoreInfo.VarOffset; + BitWidth = 1; + Offset = BitOffset / 8; + TotalBits = BitOffset % 8 + BitWidth; + Width = (TotalBits % 8 == 0 ? TotalBits / 8 : TotalBits / 8 + 1); + } else { + Offset = IfrCheckBox->Question.VarStoreInfo.VarOffset; + Width = (UINT16)sizeof (BOOLEAN); + } + // - // Get the value in bit fields. + // Check whether this question is in current block array. // - StartBit = BitOffset % 8; - EndBit = StartBit + BitWidth - 1; - CopyMem ((UINT8 *) &BufferValue, VarBuffer + Offset, Width); - VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); - } else { - CopyMem (&VarValue, VarBuffer + Offset, Width); - } - } - // - // Boolean type, only 1 and 0 is valid. - // - if (VarValue > 1) { - return EFI_INVALID_PARAMETER; - } - break; - case EFI_IFR_STRING_OP: - // - // Check current string length is less than maxsize - // - - // - // CheckBox question is not in IFR Form. This IFR form is not valid. - // - if (VarStoreData.VarStoreId == 0) { - return EFI_INVALID_PARAMETER; - } + if (!BlockArrayCheck (CurrentBlockArray, Offset, Width)) { + // + // This question is not in the current configuration string. Skip it. + // + break; + } - // - // Check whether this question is for the requested varstore. - // - IfrString = (EFI_IFR_STRING *) IfrOpHdr; - if (IfrString->Question.VarStoreId != VarStoreData.VarStoreId) { - break; - } - // - // Get the Max size of the string. - // - Width = (UINT16) (IfrString->MaxSize * sizeof (UINT16)); - if (NameValueType) { - QuestionName = HiiGetString (HiiHandle, IfrString->Question.VarStoreInfo.VarName, NULL); - ASSERT (QuestionName != NULL); + // + // Check this var question is in the var storage + // + if ((Offset + Width) > VarStoreData.Size) { + // + // This question exceeds the var store size. + // + return EFI_INVALID_PARAMETER; + } - StringPtr = StrStr (RequestElement, QuestionName); - if (StringPtr == NULL) { // - // This question is not in the current configuration string. Skip it. + // Check the current value is in the numeric range. // - break; + VarValue = 0; + if (QuestionReferBitField) { + // + // Get the value in bit fields. + // + StartBit = BitOffset % 8; + EndBit = StartBit + BitWidth - 1; + CopyMem ((UINT8 *)&BufferValue, VarBuffer + Offset, Width); + VarValue = BitFieldRead32 (BufferValue, StartBit, EndBit); + } else { + CopyMem (&VarValue, VarBuffer + Offset, Width); + } } + // - // Skip the VarName. + // Boolean type, only 1 and 0 is valid. // - StringPtr += StrLen (QuestionName); + if (VarValue > 1) { + return EFI_INVALID_PARAMETER; + } + break; + case EFI_IFR_STRING_OP: // - // Skip the "=". + // Check current string length is less than maxsize // - StringPtr += 1; // - // Check current string length is less than maxsize - // e.g Config String: "0041004200430044", Unicode String: "ABCD". Unicode String length = Config String length / 4. - // Config string format in UEFI spec. - // ::=