NorFlashFvbDxe.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /*++ @file NorFlashFvbDxe.c
  2. Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.<BR>
  3. SPDX-License-Identifier: BSD-2-Clause-Patent
  4. --*/
  5. #include <PiDxe.h>
  6. #include <Library/PcdLib.h>
  7. #include <Library/BaseLib.h>
  8. #include <Library/HobLib.h>
  9. #include <Library/UefiLib.h>
  10. #include <Library/BaseMemoryLib.h>
  11. #include <Library/MemoryAllocationLib.h>
  12. #include <Library/DxeServicesTableLib.h>
  13. #include <Library/UefiBootServicesTableLib.h>
  14. #include <Guid/VariableFormat.h>
  15. #include <Guid/SystemNvDataGuid.h>
  16. #include <Guid/NvVarStoreFormatted.h>
  17. #include "NorFlashDxe.h"
  18. STATIC EFI_EVENT mFvbVirtualAddrChangeEvent;
  19. STATIC UINTN mFlashNvStorageVariableBase;
  20. ///
  21. /// The Firmware Volume Block Protocol is the low-level interface
  22. /// to a firmware volume. File-level access to a firmware volume
  23. /// should not be done using the Firmware Volume Block Protocol.
  24. /// Normal access to a firmware volume must use the Firmware
  25. /// Volume Protocol. Typically, only the file system driver that
  26. /// produces the Firmware Volume Protocol will bind to the
  27. /// Firmware Volume Block Protocol.
  28. ///
  29. /**
  30. Initialises the FV Header and Variable Store Header
  31. to support variable operations.
  32. @param[in] Ptr - Location to initialise the headers
  33. **/
  34. EFI_STATUS
  35. InitializeFvAndVariableStoreHeaders (
  36. IN NOR_FLASH_INSTANCE *Instance
  37. )
  38. {
  39. EFI_STATUS Status;
  40. VOID* Headers;
  41. UINTN HeadersLength;
  42. EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
  43. VARIABLE_STORE_HEADER *VariableStoreHeader;
  44. HeadersLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + sizeof(VARIABLE_STORE_HEADER);
  45. Headers = AllocateZeroPool(HeadersLength);
  46. // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous.
  47. ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) + PcdGet32(PcdFlashNvStorageVariableSize) == PcdGet32(PcdFlashNvStorageFtwWorkingBase));
  48. ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) == PcdGet32(PcdFlashNvStorageFtwSpareBase));
  49. // Check if the size of the area is at least one block size
  50. ASSERT((PcdGet32(PcdFlashNvStorageVariableSize) > 0) && (PcdGet32(PcdFlashNvStorageVariableSize) / Instance->Media.BlockSize > 0));
  51. ASSERT((PcdGet32(PcdFlashNvStorageFtwWorkingSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwWorkingSize) / Instance->Media.BlockSize > 0));
  52. ASSERT((PcdGet32(PcdFlashNvStorageFtwSpareSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwSpareSize) / Instance->Media.BlockSize > 0));
  53. // Ensure the Variable area Base Addresses are aligned on a block size boundaries
  54. ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) % Instance->Media.BlockSize == 0);
  55. ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) % Instance->Media.BlockSize == 0);
  56. ASSERT(PcdGet32(PcdFlashNvStorageFtwSpareBase) % Instance->Media.BlockSize == 0);
  57. //
  58. // EFI_FIRMWARE_VOLUME_HEADER
  59. //
  60. FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Headers;
  61. CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid);
  62. FirmwareVolumeHeader->FvLength =
  63. PcdGet32(PcdFlashNvStorageVariableSize) +
  64. PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
  65. PcdGet32(PcdFlashNvStorageFtwSpareSize);
  66. FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE;
  67. FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2) (
  68. EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
  69. EFI_FVB2_READ_STATUS | // Reads are currently enabled
  70. EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
  71. EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
  72. EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1')
  73. EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
  74. EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled
  75. );
  76. FirmwareVolumeHeader->HeaderLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY);
  77. FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
  78. FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
  79. FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
  80. FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
  81. FirmwareVolumeHeader->BlockMap[1].Length = 0;
  82. FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16*)FirmwareVolumeHeader,FirmwareVolumeHeader->HeaderLength);
  83. //
  84. // VARIABLE_STORE_HEADER
  85. //
  86. VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)Headers + FirmwareVolumeHeader->HeaderLength);
  87. CopyGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid);
  88. VariableStoreHeader->Size = PcdGet32(PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength;
  89. VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED;
  90. VariableStoreHeader->State = VARIABLE_STORE_HEALTHY;
  91. // Install the combined super-header in the NorFlash
  92. Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers);
  93. FreePool (Headers);
  94. return Status;
  95. }
  96. /**
  97. Check the integrity of firmware volume header.
  98. @param[in] FwVolHeader - A pointer to a firmware volume header
  99. @retval EFI_SUCCESS - The firmware volume is consistent
  100. @retval EFI_NOT_FOUND - The firmware volume has been corrupted.
  101. **/
  102. EFI_STATUS
  103. ValidateFvHeader (
  104. IN NOR_FLASH_INSTANCE *Instance
  105. )
  106. {
  107. UINT16 Checksum;
  108. EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
  109. VARIABLE_STORE_HEADER *VariableStoreHeader;
  110. UINTN VariableStoreLength;
  111. UINTN FvLength;
  112. FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Instance->RegionBaseAddress;
  113. FvLength = PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
  114. PcdGet32(PcdFlashNvStorageFtwSpareSize);
  115. //
  116. // Verify the header revision, header signature, length
  117. // Length of FvBlock cannot be 2**64-1
  118. // HeaderLength cannot be an odd number
  119. //
  120. if ( (FwVolHeader->Revision != EFI_FVH_REVISION)
  121. || (FwVolHeader->Signature != EFI_FVH_SIGNATURE)
  122. || (FwVolHeader->FvLength != FvLength)
  123. )
  124. {
  125. DEBUG ((EFI_D_INFO, "%a: No Firmware Volume header present\n",
  126. __FUNCTION__));
  127. return EFI_NOT_FOUND;
  128. }
  129. // Check the Firmware Volume Guid
  130. if( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) {
  131. DEBUG ((EFI_D_INFO, "%a: Firmware Volume Guid non-compatible\n",
  132. __FUNCTION__));
  133. return EFI_NOT_FOUND;
  134. }
  135. // Verify the header checksum
  136. Checksum = CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLength);
  137. if (Checksum != 0) {
  138. DEBUG ((EFI_D_INFO, "%a: FV checksum is invalid (Checksum:0x%X)\n",
  139. __FUNCTION__, Checksum));
  140. return EFI_NOT_FOUND;
  141. }
  142. VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader + FwVolHeader->HeaderLength);
  143. // Check the Variable Store Guid
  144. if (!CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) &&
  145. !CompareGuid (&VariableStoreHeader->Signature, &gEfiAuthenticatedVariableGuid)) {
  146. DEBUG ((EFI_D_INFO, "%a: Variable Store Guid non-compatible\n",
  147. __FUNCTION__));
  148. return EFI_NOT_FOUND;
  149. }
  150. VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength;
  151. if (VariableStoreHeader->Size != VariableStoreLength) {
  152. DEBUG ((EFI_D_INFO, "%a: Variable Store Length does not match\n",
  153. __FUNCTION__));
  154. return EFI_NOT_FOUND;
  155. }
  156. return EFI_SUCCESS;
  157. }
  158. /**
  159. The GetAttributes() function retrieves the attributes and
  160. current settings of the block.
  161. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  162. @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and
  163. current settings are returned.
  164. Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
  165. @retval EFI_SUCCESS The firmware volume attributes were returned.
  166. **/
  167. EFI_STATUS
  168. EFIAPI
  169. FvbGetAttributes(
  170. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  171. OUT EFI_FVB_ATTRIBUTES_2 *Attributes
  172. )
  173. {
  174. EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes;
  175. NOR_FLASH_INSTANCE *Instance;
  176. Instance = INSTANCE_FROM_FVB_THIS(This);
  177. FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2) (
  178. EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
  179. EFI_FVB2_READ_STATUS | // Reads are currently enabled
  180. EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
  181. EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
  182. EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1')
  183. );
  184. // Check if it is write protected
  185. if (Instance->Media.ReadOnly != TRUE) {
  186. FlashFvbAttributes = FlashFvbAttributes |
  187. EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
  188. EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled
  189. }
  190. *Attributes = FlashFvbAttributes;
  191. DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes));
  192. return EFI_SUCCESS;
  193. }
  194. /**
  195. The SetAttributes() function sets configurable firmware volume attributes
  196. and returns the new settings of the firmware volume.
  197. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  198. @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2
  199. that contains the desired firmware volume settings.
  200. On successful return, it contains the new settings of
  201. the firmware volume.
  202. Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
  203. @retval EFI_SUCCESS The firmware volume attributes were returned.
  204. @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities
  205. as declared in the firmware volume header.
  206. **/
  207. EFI_STATUS
  208. EFIAPI
  209. FvbSetAttributes(
  210. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  211. IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
  212. )
  213. {
  214. DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n",*Attributes));
  215. return EFI_UNSUPPORTED;
  216. }
  217. /**
  218. The GetPhysicalAddress() function retrieves the base address of
  219. a memory-mapped firmware volume. This function should be called
  220. only for memory-mapped firmware volumes.
  221. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  222. @param Address Pointer to a caller-allocated
  223. EFI_PHYSICAL_ADDRESS that, on successful
  224. return from GetPhysicalAddress(), contains the
  225. base address of the firmware volume.
  226. @retval EFI_SUCCESS The firmware volume base address was returned.
  227. @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped.
  228. **/
  229. EFI_STATUS
  230. EFIAPI
  231. FvbGetPhysicalAddress (
  232. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  233. OUT EFI_PHYSICAL_ADDRESS *Address
  234. )
  235. {
  236. NOR_FLASH_INSTANCE *Instance;
  237. Instance = INSTANCE_FROM_FVB_THIS(This);
  238. DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress));
  239. ASSERT(Address != NULL);
  240. *Address = mFlashNvStorageVariableBase;
  241. return EFI_SUCCESS;
  242. }
  243. /**
  244. The GetBlockSize() function retrieves the size of the requested
  245. block. It also returns the number of additional blocks with
  246. the identical size. The GetBlockSize() function is used to
  247. retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).
  248. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  249. @param Lba Indicates the block for which to return the size.
  250. @param BlockSize Pointer to a caller-allocated UINTN in which
  251. the size of the block is returned.
  252. @param NumberOfBlocks Pointer to a caller-allocated UINTN in
  253. which the number of consecutive blocks,
  254. starting with Lba, is returned. All
  255. blocks in this range have a size of
  256. BlockSize.
  257. @retval EFI_SUCCESS The firmware volume base address was returned.
  258. @retval EFI_INVALID_PARAMETER The requested LBA is out of range.
  259. **/
  260. EFI_STATUS
  261. EFIAPI
  262. FvbGetBlockSize (
  263. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  264. IN EFI_LBA Lba,
  265. OUT UINTN *BlockSize,
  266. OUT UINTN *NumberOfBlocks
  267. )
  268. {
  269. EFI_STATUS Status;
  270. NOR_FLASH_INSTANCE *Instance;
  271. Instance = INSTANCE_FROM_FVB_THIS(This);
  272. DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock));
  273. if (Lba > Instance->Media.LastBlock) {
  274. DEBUG ((EFI_D_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock));
  275. Status = EFI_INVALID_PARAMETER;
  276. } else {
  277. // This is easy because in this platform each NorFlash device has equal sized blocks.
  278. *BlockSize = (UINTN) Instance->Media.BlockSize;
  279. *NumberOfBlocks = (UINTN) (Instance->Media.LastBlock - Lba + 1);
  280. DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks));
  281. Status = EFI_SUCCESS;
  282. }
  283. return Status;
  284. }
  285. /**
  286. Reads the specified number of bytes into a buffer from the specified block.
  287. The Read() function reads the requested number of bytes from the
  288. requested block and stores them in the provided buffer.
  289. Implementations should be mindful that the firmware volume
  290. might be in the ReadDisabled state. If it is in this state,
  291. the Read() function must return the status code
  292. EFI_ACCESS_DENIED without modifying the contents of the
  293. buffer. The Read() function must also prevent spanning block
  294. boundaries. If a read is requested that would span a block
  295. boundary, the read must read up to the boundary but not
  296. beyond. The output parameter NumBytes must be set to correctly
  297. indicate the number of bytes actually read. The caller must be
  298. aware that a read may be partially completed.
  299. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  300. @param Lba The starting logical block index from which to read.
  301. @param Offset Offset into the block at which to begin reading.
  302. @param NumBytes Pointer to a UINTN.
  303. At entry, *NumBytes contains the total size of the buffer.
  304. At exit, *NumBytes contains the total number of bytes read.
  305. @param Buffer Pointer to a caller-allocated buffer that will be used
  306. to hold the data that is read.
  307. @retval EFI_SUCCESS The firmware volume was read successfully, and contents are
  308. in Buffer.
  309. @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary.
  310. On output, NumBytes contains the total number of bytes
  311. returned in Buffer.
  312. @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state.
  313. @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read.
  314. **/
  315. EFI_STATUS
  316. EFIAPI
  317. FvbRead (
  318. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  319. IN EFI_LBA Lba,
  320. IN UINTN Offset,
  321. IN OUT UINTN *NumBytes,
  322. IN OUT UINT8 *Buffer
  323. )
  324. {
  325. EFI_STATUS TempStatus;
  326. UINTN BlockSize;
  327. NOR_FLASH_INSTANCE *Instance;
  328. Instance = INSTANCE_FROM_FVB_THIS(This);
  329. DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
  330. TempStatus = EFI_SUCCESS;
  331. // Cache the block size to avoid de-referencing pointers all the time
  332. BlockSize = Instance->Media.BlockSize;
  333. DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
  334. // The read must not span block boundaries.
  335. // We need to check each variable individually because adding two large values together overflows.
  336. if ((Offset >= BlockSize) ||
  337. (*NumBytes > BlockSize) ||
  338. ((Offset + *NumBytes) > BlockSize)) {
  339. DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
  340. return EFI_BAD_BUFFER_SIZE;
  341. }
  342. // We must have some bytes to read
  343. if (*NumBytes == 0) {
  344. return EFI_BAD_BUFFER_SIZE;
  345. }
  346. // Decide if we are doing full block reads or not.
  347. if (*NumBytes % BlockSize != 0) {
  348. TempStatus = NorFlashRead (Instance, Instance->StartLba + Lba, Offset, *NumBytes, Buffer);
  349. if (EFI_ERROR (TempStatus)) {
  350. return EFI_DEVICE_ERROR;
  351. }
  352. } else {
  353. // Read NOR Flash data into shadow buffer
  354. TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, Buffer);
  355. if (EFI_ERROR (TempStatus)) {
  356. // Return one of the pre-approved error statuses
  357. return EFI_DEVICE_ERROR;
  358. }
  359. }
  360. return EFI_SUCCESS;
  361. }
  362. /**
  363. Writes the specified number of bytes from the input buffer to the block.
  364. The Write() function writes the specified number of bytes from
  365. the provided buffer to the specified block and offset. If the
  366. firmware volume is sticky write, the caller must ensure that
  367. all the bits of the specified range to write are in the
  368. EFI_FVB_ERASE_POLARITY state before calling the Write()
  369. function, or else the result will be unpredictable. This
  370. unpredictability arises because, for a sticky-write firmware
  371. volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY
  372. state but cannot flip it back again. Before calling the
  373. Write() function, it is recommended for the caller to first call
  374. the EraseBlocks() function to erase the specified block to
  375. write. A block erase cycle will transition bits from the
  376. (NOT)EFI_FVB_ERASE_POLARITY state back to the
  377. EFI_FVB_ERASE_POLARITY state. Implementations should be
  378. mindful that the firmware volume might be in the WriteDisabled
  379. state. If it is in this state, the Write() function must
  380. return the status code EFI_ACCESS_DENIED without modifying the
  381. contents of the firmware volume. The Write() function must
  382. also prevent spanning block boundaries. If a write is
  383. requested that spans a block boundary, the write must store up
  384. to the boundary but not beyond. The output parameter NumBytes
  385. must be set to correctly indicate the number of bytes actually
  386. written. The caller must be aware that a write may be
  387. partially completed. All writes, partial or otherwise, must be
  388. fully flushed to the hardware before the Write() service
  389. returns.
  390. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
  391. @param Lba The starting logical block index to write to.
  392. @param Offset Offset into the block at which to begin writing.
  393. @param NumBytes The pointer to a UINTN.
  394. At entry, *NumBytes contains the total size of the buffer.
  395. At exit, *NumBytes contains the total number of bytes actually written.
  396. @param Buffer The pointer to a caller-allocated buffer that contains the source for the write.
  397. @retval EFI_SUCCESS The firmware volume was written successfully.
  398. @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary.
  399. On output, NumBytes contains the total number of bytes
  400. actually written.
  401. @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
  402. @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written.
  403. **/
  404. EFI_STATUS
  405. EFIAPI
  406. FvbWrite (
  407. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  408. IN EFI_LBA Lba,
  409. IN UINTN Offset,
  410. IN OUT UINTN *NumBytes,
  411. IN UINT8 *Buffer
  412. )
  413. {
  414. NOR_FLASH_INSTANCE *Instance;
  415. Instance = INSTANCE_FROM_FVB_THIS (This);
  416. return NorFlashWriteSingleBlock (Instance, Instance->StartLba + Lba, Offset, NumBytes, Buffer);
  417. }
  418. /**
  419. Erases and initialises a firmware volume block.
  420. The EraseBlocks() function erases one or more blocks as denoted
  421. by the variable argument list. The entire parameter list of
  422. blocks must be verified before erasing any blocks. If a block is
  423. requested that does not exist within the associated firmware
  424. volume (it has a larger index than the last block of the
  425. firmware volume), the EraseBlocks() function must return the
  426. status code EFI_INVALID_PARAMETER without modifying the contents
  427. of the firmware volume. Implementations should be mindful that
  428. the firmware volume might be in the WriteDisabled state. If it
  429. is in this state, the EraseBlocks() function must return the
  430. status code EFI_ACCESS_DENIED without modifying the contents of
  431. the firmware volume. All calls to EraseBlocks() must be fully
  432. flushed to the hardware before the EraseBlocks() service
  433. returns.
  434. @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL
  435. instance.
  436. @param ... The variable argument list is a list of tuples.
  437. Each tuple describes a range of LBAs to erase
  438. and consists of the following:
  439. - An EFI_LBA that indicates the starting LBA
  440. - A UINTN that indicates the number of blocks to erase.
  441. The list is terminated with an EFI_LBA_LIST_TERMINATOR.
  442. For example, the following indicates that two ranges of blocks
  443. (5-7 and 10-11) are to be erased:
  444. EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);
  445. @retval EFI_SUCCESS The erase request successfully completed.
  446. @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
  447. @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written.
  448. The firmware device may have been partially erased.
  449. @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do
  450. not exist in the firmware volume.
  451. **/
  452. EFI_STATUS
  453. EFIAPI
  454. FvbEraseBlocks (
  455. IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
  456. ...
  457. )
  458. {
  459. EFI_STATUS Status;
  460. VA_LIST Args;
  461. UINTN BlockAddress; // Physical address of Lba to erase
  462. EFI_LBA StartingLba; // Lba from which we start erasing
  463. UINTN NumOfLba; // Number of Lba blocks to erase
  464. NOR_FLASH_INSTANCE *Instance;
  465. Instance = INSTANCE_FROM_FVB_THIS(This);
  466. DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n"));
  467. Status = EFI_SUCCESS;
  468. // Detect WriteDisabled state
  469. if (Instance->Media.ReadOnly == TRUE) {
  470. // Firmware volume is in WriteDisabled state
  471. DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n"));
  472. return EFI_ACCESS_DENIED;
  473. }
  474. // Before erasing, check the entire list of parameters to ensure all specified blocks are valid
  475. VA_START (Args, This);
  476. do {
  477. // Get the Lba from which we start erasing
  478. StartingLba = VA_ARG (Args, EFI_LBA);
  479. // Have we reached the end of the list?
  480. if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
  481. //Exit the while loop
  482. break;
  483. }
  484. // How many Lba blocks are we requested to erase?
  485. NumOfLba = VA_ARG (Args, UINTN);
  486. // All blocks must be within range
  487. DEBUG ((
  488. DEBUG_BLKIO,
  489. "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%Lu - 1 ) > LastBlock=%ld.\n",
  490. Instance->StartLba + StartingLba,
  491. (UINT64)NumOfLba,
  492. Instance->Media.LastBlock
  493. ));
  494. if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) {
  495. VA_END (Args);
  496. DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n"));
  497. Status = EFI_INVALID_PARAMETER;
  498. goto EXIT;
  499. }
  500. } while (TRUE);
  501. VA_END (Args);
  502. //
  503. // To get here, all must be ok, so start erasing
  504. //
  505. VA_START (Args, This);
  506. do {
  507. // Get the Lba from which we start erasing
  508. StartingLba = VA_ARG (Args, EFI_LBA);
  509. // Have we reached the end of the list?
  510. if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
  511. // Exit the while loop
  512. break;
  513. }
  514. // How many Lba blocks are we requested to erase?
  515. NumOfLba = VA_ARG (Args, UINTN);
  516. // Go through each one and erase it
  517. while (NumOfLba > 0) {
  518. // Get the physical address of Lba to erase
  519. BlockAddress = GET_NOR_BLOCK_ADDRESS (
  520. Instance->RegionBaseAddress,
  521. Instance->StartLba + StartingLba,
  522. Instance->Media.BlockSize
  523. );
  524. // Erase it
  525. DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress));
  526. Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
  527. if (EFI_ERROR(Status)) {
  528. VA_END (Args);
  529. Status = EFI_DEVICE_ERROR;
  530. goto EXIT;
  531. }
  532. // Move to the next Lba
  533. StartingLba++;
  534. NumOfLba--;
  535. }
  536. } while (TRUE);
  537. VA_END (Args);
  538. EXIT:
  539. return Status;
  540. }
  541. /**
  542. Fixup internal data so that EFI can be call in virtual mode.
  543. Call the passed in Child Notify event and convert any pointers in
  544. lib to virtual mode.
  545. @param[in] Event The Event that is being processed
  546. @param[in] Context Event Context
  547. **/
  548. VOID
  549. EFIAPI
  550. FvbVirtualNotifyEvent (
  551. IN EFI_EVENT Event,
  552. IN VOID *Context
  553. )
  554. {
  555. EfiConvertPointer (0x0, (VOID**)&mFlashNvStorageVariableBase);
  556. return;
  557. }
  558. EFI_STATUS
  559. EFIAPI
  560. NorFlashFvbInitialize (
  561. IN NOR_FLASH_INSTANCE* Instance
  562. )
  563. {
  564. EFI_STATUS Status;
  565. UINT32 FvbNumLba;
  566. EFI_BOOT_MODE BootMode;
  567. UINTN RuntimeMmioRegionSize;
  568. DEBUG((DEBUG_BLKIO,"NorFlashFvbInitialize\n"));
  569. ASSERT((Instance != NULL));
  570. //
  571. // Declare the Non-Volatile storage as EFI_MEMORY_RUNTIME
  572. //
  573. // Note: all the NOR Flash region needs to be reserved into the UEFI Runtime memory;
  574. // even if we only use the small block region at the top of the NOR Flash.
  575. // The reason is when the NOR Flash memory is set into program mode, the command
  576. // is written as the base of the flash region (ie: Instance->DeviceBaseAddress)
  577. RuntimeMmioRegionSize = (Instance->RegionBaseAddress - Instance->DeviceBaseAddress) + Instance->Size;
  578. Status = gDS->AddMemorySpace (
  579. EfiGcdMemoryTypeMemoryMappedIo,
  580. Instance->DeviceBaseAddress, RuntimeMmioRegionSize,
  581. EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
  582. );
  583. ASSERT_EFI_ERROR (Status);
  584. Status = gDS->SetMemorySpaceAttributes (
  585. Instance->DeviceBaseAddress, RuntimeMmioRegionSize,
  586. EFI_MEMORY_UC | EFI_MEMORY_RUNTIME);
  587. ASSERT_EFI_ERROR (Status);
  588. mFlashNvStorageVariableBase = FixedPcdGet32 (PcdFlashNvStorageVariableBase);
  589. // Set the index of the first LBA for the FVB
  590. Instance->StartLba = (PcdGet32 (PcdFlashNvStorageVariableBase) - Instance->RegionBaseAddress) / Instance->Media.BlockSize;
  591. BootMode = GetBootModeHob ();
  592. if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
  593. Status = EFI_INVALID_PARAMETER;
  594. } else {
  595. // Determine if there is a valid header at the beginning of the NorFlash
  596. Status = ValidateFvHeader (Instance);
  597. }
  598. // Install the Default FVB header if required
  599. if (EFI_ERROR(Status)) {
  600. // There is no valid header, so time to install one.
  601. DEBUG ((EFI_D_INFO, "%a: The FVB Header is not valid.\n", __FUNCTION__));
  602. DEBUG ((EFI_D_INFO, "%a: Installing a correct one for this volume.\n",
  603. __FUNCTION__));
  604. // Erase all the NorFlash that is reserved for variable storage
  605. FvbNumLba = (PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + PcdGet32(PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize;
  606. Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR);
  607. if (EFI_ERROR(Status)) {
  608. return Status;
  609. }
  610. // Install all appropriate headers
  611. Status = InitializeFvAndVariableStoreHeaders (Instance);
  612. if (EFI_ERROR(Status)) {
  613. return Status;
  614. }
  615. }
  616. //
  617. // The driver implementing the variable read service can now be dispatched;
  618. // the varstore headers are in place.
  619. //
  620. Status = gBS->InstallProtocolInterface (
  621. &gImageHandle,
  622. &gEdkiiNvVarStoreFormattedGuid,
  623. EFI_NATIVE_INTERFACE,
  624. NULL
  625. );
  626. ASSERT_EFI_ERROR (Status);
  627. //
  628. // Register for the virtual address change event
  629. //
  630. Status = gBS->CreateEventEx (
  631. EVT_NOTIFY_SIGNAL,
  632. TPL_NOTIFY,
  633. FvbVirtualNotifyEvent,
  634. NULL,
  635. &gEfiEventVirtualAddressChangeGuid,
  636. &mFvbVirtualAddrChangeEvent
  637. );
  638. ASSERT_EFI_ERROR (Status);
  639. return Status;
  640. }