]> git.proxmox.com Git - mirror_edk2.git/blob - ArmPlatformPkg/Drivers/NorFlashDxe/NorFlashFvbDxe.c
ArmPlatformPkg/NorFlashDxe: Optimise FVB protocol
[mirror_edk2.git] / ArmPlatformPkg / Drivers / NorFlashDxe / NorFlashFvbDxe.c
1 /*++ @file NorFlashFvbDxe.c
2
3 Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.<BR>
4
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 --*/
14
15 #include <PiDxe.h>
16
17 #include <Library/PcdLib.h>
18 #include <Library/BaseLib.h>
19 #include <Library/HobLib.h>
20 #include <Library/UefiLib.h>
21 #include <Library/BaseMemoryLib.h>
22 #include <Library/MemoryAllocationLib.h>
23 #include <Library/DxeServicesTableLib.h>
24 #include <Library/UefiBootServicesTableLib.h>
25
26 #include <Guid/VariableFormat.h>
27 #include <Guid/SystemNvDataGuid.h>
28
29 #include "NorFlashDxe.h"
30
31 STATIC EFI_EVENT mFvbVirtualAddrChangeEvent;
32 STATIC UINTN mFlashNvStorageVariableBase;
33
34 ///
35 /// The Firmware Volume Block Protocol is the low-level interface
36 /// to a firmware volume. File-level access to a firmware volume
37 /// should not be done using the Firmware Volume Block Protocol.
38 /// Normal access to a firmware volume must use the Firmware
39 /// Volume Protocol. Typically, only the file system driver that
40 /// produces the Firmware Volume Protocol will bind to the
41 /// Firmware Volume Block Protocol.
42 ///
43
44 /**
45 Initialises the FV Header and Variable Store Header
46 to support variable operations.
47
48 @param[in] Ptr - Location to initialise the headers
49
50 **/
51 EFI_STATUS
52 InitializeFvAndVariableStoreHeaders (
53 IN NOR_FLASH_INSTANCE *Instance
54 )
55 {
56 EFI_STATUS Status;
57 VOID* Headers;
58 UINTN HeadersLength;
59 EFI_FIRMWARE_VOLUME_HEADER *FirmwareVolumeHeader;
60 VARIABLE_STORE_HEADER *VariableStoreHeader;
61
62 if (!Instance->Initialized && Instance->Initialize) {
63 Instance->Initialize (Instance);
64 }
65
66 HeadersLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY) + sizeof(VARIABLE_STORE_HEADER);
67 Headers = AllocateZeroPool(HeadersLength);
68
69 // FirmwareVolumeHeader->FvLength is declared to have the Variable area AND the FTW working area AND the FTW Spare contiguous.
70 ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) + PcdGet32(PcdFlashNvStorageVariableSize) == PcdGet32(PcdFlashNvStorageFtwWorkingBase));
71 ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) == PcdGet32(PcdFlashNvStorageFtwSpareBase));
72
73 // Check if the size of the area is at least one block size
74 ASSERT((PcdGet32(PcdFlashNvStorageVariableSize) > 0) && (PcdGet32(PcdFlashNvStorageVariableSize) / Instance->Media.BlockSize > 0));
75 ASSERT((PcdGet32(PcdFlashNvStorageFtwWorkingSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwWorkingSize) / Instance->Media.BlockSize > 0));
76 ASSERT((PcdGet32(PcdFlashNvStorageFtwSpareSize) > 0) && (PcdGet32(PcdFlashNvStorageFtwSpareSize) / Instance->Media.BlockSize > 0));
77
78 // Ensure the Variable area Base Addresses are aligned on a block size boundaries
79 ASSERT(PcdGet32(PcdFlashNvStorageVariableBase) % Instance->Media.BlockSize == 0);
80 ASSERT(PcdGet32(PcdFlashNvStorageFtwWorkingBase) % Instance->Media.BlockSize == 0);
81 ASSERT(PcdGet32(PcdFlashNvStorageFtwSpareBase) % Instance->Media.BlockSize == 0);
82
83 //
84 // EFI_FIRMWARE_VOLUME_HEADER
85 //
86 FirmwareVolumeHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Headers;
87 CopyGuid (&FirmwareVolumeHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid);
88 FirmwareVolumeHeader->FvLength =
89 PcdGet32(PcdFlashNvStorageVariableSize) +
90 PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
91 PcdGet32(PcdFlashNvStorageFtwSpareSize);
92 FirmwareVolumeHeader->Signature = EFI_FVH_SIGNATURE;
93 FirmwareVolumeHeader->Attributes = (EFI_FVB_ATTRIBUTES_2) (
94 EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
95 EFI_FVB2_READ_STATUS | // Reads are currently enabled
96 EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
97 EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
98 EFI_FVB2_ERASE_POLARITY | // After erasure all bits take this value (i.e. '1')
99 EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
100 EFI_FVB2_WRITE_ENABLED_CAP // Writes may be enabled
101 );
102 FirmwareVolumeHeader->HeaderLength = sizeof(EFI_FIRMWARE_VOLUME_HEADER) + sizeof(EFI_FV_BLOCK_MAP_ENTRY);
103 FirmwareVolumeHeader->Revision = EFI_FVH_REVISION;
104 FirmwareVolumeHeader->BlockMap[0].NumBlocks = Instance->Media.LastBlock + 1;
105 FirmwareVolumeHeader->BlockMap[0].Length = Instance->Media.BlockSize;
106 FirmwareVolumeHeader->BlockMap[1].NumBlocks = 0;
107 FirmwareVolumeHeader->BlockMap[1].Length = 0;
108 FirmwareVolumeHeader->Checksum = CalculateCheckSum16 ((UINT16*)FirmwareVolumeHeader,FirmwareVolumeHeader->HeaderLength);
109
110 //
111 // VARIABLE_STORE_HEADER
112 //
113 VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)Headers + FirmwareVolumeHeader->HeaderLength);
114 CopyGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid);
115 VariableStoreHeader->Size = PcdGet32(PcdFlashNvStorageVariableSize) - FirmwareVolumeHeader->HeaderLength;
116 VariableStoreHeader->Format = VARIABLE_STORE_FORMATTED;
117 VariableStoreHeader->State = VARIABLE_STORE_HEALTHY;
118
119 // Install the combined super-header in the NorFlash
120 Status = FvbWrite (&Instance->FvbProtocol, 0, 0, &HeadersLength, Headers);
121
122 FreePool (Headers);
123 return Status;
124 }
125
126 /**
127 Check the integrity of firmware volume header.
128
129 @param[in] FwVolHeader - A pointer to a firmware volume header
130
131 @retval EFI_SUCCESS - The firmware volume is consistent
132 @retval EFI_NOT_FOUND - The firmware volume has been corrupted.
133
134 **/
135 EFI_STATUS
136 ValidateFvHeader (
137 IN NOR_FLASH_INSTANCE *Instance
138 )
139 {
140 UINT16 Checksum;
141 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
142 VARIABLE_STORE_HEADER *VariableStoreHeader;
143 UINTN VariableStoreLength;
144 UINTN FvLength;
145
146 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER*)Instance->RegionBaseAddress;
147
148 FvLength = PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) +
149 PcdGet32(PcdFlashNvStorageFtwSpareSize);
150
151 //
152 // Verify the header revision, header signature, length
153 // Length of FvBlock cannot be 2**64-1
154 // HeaderLength cannot be an odd number
155 //
156 if ( (FwVolHeader->Revision != EFI_FVH_REVISION)
157 || (FwVolHeader->Signature != EFI_FVH_SIGNATURE)
158 || (FwVolHeader->FvLength != FvLength)
159 )
160 {
161 DEBUG ((EFI_D_ERROR, "ValidateFvHeader: No Firmware Volume header present\n"));
162 return EFI_NOT_FOUND;
163 }
164
165 // Check the Firmware Volume Guid
166 if( CompareGuid (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid) == FALSE ) {
167 DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Firmware Volume Guid non-compatible\n"));
168 return EFI_NOT_FOUND;
169 }
170
171 // Verify the header checksum
172 Checksum = CalculateSum16((UINT16*)FwVolHeader, FwVolHeader->HeaderLength);
173 if (Checksum != 0) {
174 DEBUG ((EFI_D_ERROR, "ValidateFvHeader: FV checksum is invalid (Checksum:0x%X)\n",Checksum));
175 return EFI_NOT_FOUND;
176 }
177
178 VariableStoreHeader = (VARIABLE_STORE_HEADER*)((UINTN)FwVolHeader + FwVolHeader->HeaderLength);
179
180 // Check the Variable Store Guid
181 if( CompareGuid (&VariableStoreHeader->Signature, &gEfiVariableGuid) == FALSE ) {
182 DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Guid non-compatible\n"));
183 return EFI_NOT_FOUND;
184 }
185
186 VariableStoreLength = PcdGet32 (PcdFlashNvStorageVariableSize) - FwVolHeader->HeaderLength;
187 if (VariableStoreHeader->Size != VariableStoreLength) {
188 DEBUG ((EFI_D_ERROR, "ValidateFvHeader: Variable Store Length does not match\n"));
189 return EFI_NOT_FOUND;
190 }
191
192 return EFI_SUCCESS;
193 }
194
195 /**
196 The GetAttributes() function retrieves the attributes and
197 current settings of the block.
198
199 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
200
201 @param Attributes Pointer to EFI_FVB_ATTRIBUTES_2 in which the attributes and
202 current settings are returned.
203 Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
204
205 @retval EFI_SUCCESS The firmware volume attributes were returned.
206
207 **/
208 EFI_STATUS
209 EFIAPI
210 FvbGetAttributes(
211 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
212 OUT EFI_FVB_ATTRIBUTES_2 *Attributes
213 )
214 {
215 EFI_FVB_ATTRIBUTES_2 FlashFvbAttributes;
216 NOR_FLASH_INSTANCE *Instance;
217
218 Instance = INSTANCE_FROM_FVB_THIS(This);
219
220 FlashFvbAttributes = (EFI_FVB_ATTRIBUTES_2) (
221
222 EFI_FVB2_READ_ENABLED_CAP | // Reads may be enabled
223 EFI_FVB2_READ_STATUS | // Reads are currently enabled
224 EFI_FVB2_STICKY_WRITE | // A block erase is required to flip bits into EFI_FVB2_ERASE_POLARITY
225 EFI_FVB2_MEMORY_MAPPED | // It is memory mapped
226 EFI_FVB2_ERASE_POLARITY // After erasure all bits take this value (i.e. '1')
227
228 );
229
230 // Check if it is write protected
231 if (Instance->Media.ReadOnly != TRUE) {
232
233 FlashFvbAttributes = FlashFvbAttributes |
234 EFI_FVB2_WRITE_STATUS | // Writes are currently enabled
235 EFI_FVB2_WRITE_ENABLED_CAP; // Writes may be enabled
236 }
237
238 *Attributes = FlashFvbAttributes;
239
240 DEBUG ((DEBUG_BLKIO, "FvbGetAttributes(0x%X)\n", *Attributes));
241
242 return EFI_SUCCESS;
243 }
244
245 /**
246 The SetAttributes() function sets configurable firmware volume attributes
247 and returns the new settings of the firmware volume.
248
249
250 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
251
252 @param Attributes On input, Attributes is a pointer to EFI_FVB_ATTRIBUTES_2
253 that contains the desired firmware volume settings.
254 On successful return, it contains the new settings of
255 the firmware volume.
256 Type EFI_FVB_ATTRIBUTES_2 is defined in EFI_FIRMWARE_VOLUME_HEADER.
257
258 @retval EFI_SUCCESS The firmware volume attributes were returned.
259
260 @retval EFI_INVALID_PARAMETER The attributes requested are in conflict with the capabilities
261 as declared in the firmware volume header.
262
263 **/
264 EFI_STATUS
265 EFIAPI
266 FvbSetAttributes(
267 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
268 IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
269 )
270 {
271 DEBUG ((DEBUG_BLKIO, "FvbSetAttributes(0x%X) is not supported\n",*Attributes));
272 return EFI_UNSUPPORTED;
273 }
274
275 /**
276 The GetPhysicalAddress() function retrieves the base address of
277 a memory-mapped firmware volume. This function should be called
278 only for memory-mapped firmware volumes.
279
280 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
281
282 @param Address Pointer to a caller-allocated
283 EFI_PHYSICAL_ADDRESS that, on successful
284 return from GetPhysicalAddress(), contains the
285 base address of the firmware volume.
286
287 @retval EFI_SUCCESS The firmware volume base address was returned.
288
289 @retval EFI_NOT_SUPPORTED The firmware volume is not memory mapped.
290
291 **/
292 EFI_STATUS
293 EFIAPI
294 FvbGetPhysicalAddress (
295 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
296 OUT EFI_PHYSICAL_ADDRESS *Address
297 )
298 {
299 NOR_FLASH_INSTANCE *Instance;
300
301 Instance = INSTANCE_FROM_FVB_THIS(This);
302
303 DEBUG ((DEBUG_BLKIO, "FvbGetPhysicalAddress(BaseAddress=0x%08x)\n", Instance->RegionBaseAddress));
304
305 ASSERT(Address != NULL);
306
307 *Address = mFlashNvStorageVariableBase;
308 return EFI_SUCCESS;
309 }
310
311 /**
312 The GetBlockSize() function retrieves the size of the requested
313 block. It also returns the number of additional blocks with
314 the identical size. The GetBlockSize() function is used to
315 retrieve the block map (see EFI_FIRMWARE_VOLUME_HEADER).
316
317
318 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
319
320 @param Lba Indicates the block for which to return the size.
321
322 @param BlockSize Pointer to a caller-allocated UINTN in which
323 the size of the block is returned.
324
325 @param NumberOfBlocks Pointer to a caller-allocated UINTN in
326 which the number of consecutive blocks,
327 starting with Lba, is returned. All
328 blocks in this range have a size of
329 BlockSize.
330
331
332 @retval EFI_SUCCESS The firmware volume base address was returned.
333
334 @retval EFI_INVALID_PARAMETER The requested LBA is out of range.
335
336 **/
337 EFI_STATUS
338 EFIAPI
339 FvbGetBlockSize (
340 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
341 IN EFI_LBA Lba,
342 OUT UINTN *BlockSize,
343 OUT UINTN *NumberOfBlocks
344 )
345 {
346 EFI_STATUS Status;
347 NOR_FLASH_INSTANCE *Instance;
348
349 Instance = INSTANCE_FROM_FVB_THIS(This);
350
351 DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize(Lba=%ld, BlockSize=0x%x, LastBlock=%ld)\n", Lba, Instance->Media.BlockSize, Instance->Media.LastBlock));
352
353 if (Lba > Instance->Media.LastBlock) {
354 DEBUG ((EFI_D_ERROR, "FvbGetBlockSize: ERROR - Parameter LBA %ld is beyond the last Lba (%ld).\n", Lba, Instance->Media.LastBlock));
355 Status = EFI_INVALID_PARAMETER;
356 } else {
357 // This is easy because in this platform each NorFlash device has equal sized blocks.
358 *BlockSize = (UINTN) Instance->Media.BlockSize;
359 *NumberOfBlocks = (UINTN) (Instance->Media.LastBlock - Lba + 1);
360
361 DEBUG ((DEBUG_BLKIO, "FvbGetBlockSize: *BlockSize=0x%x, *NumberOfBlocks=0x%x.\n", *BlockSize, *NumberOfBlocks));
362
363 Status = EFI_SUCCESS;
364 }
365
366 return Status;
367 }
368
369 /**
370 Reads the specified number of bytes into a buffer from the specified block.
371
372 The Read() function reads the requested number of bytes from the
373 requested block and stores them in the provided buffer.
374 Implementations should be mindful that the firmware volume
375 might be in the ReadDisabled state. If it is in this state,
376 the Read() function must return the status code
377 EFI_ACCESS_DENIED without modifying the contents of the
378 buffer. The Read() function must also prevent spanning block
379 boundaries. If a read is requested that would span a block
380 boundary, the read must read up to the boundary but not
381 beyond. The output parameter NumBytes must be set to correctly
382 indicate the number of bytes actually read. The caller must be
383 aware that a read may be partially completed.
384
385 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
386
387 @param Lba The starting logical block index from which to read.
388
389 @param Offset Offset into the block at which to begin reading.
390
391 @param NumBytes Pointer to a UINTN.
392 At entry, *NumBytes contains the total size of the buffer.
393 At exit, *NumBytes contains the total number of bytes read.
394
395 @param Buffer Pointer to a caller-allocated buffer that will be used
396 to hold the data that is read.
397
398 @retval EFI_SUCCESS The firmware volume was read successfully, and contents are
399 in Buffer.
400
401 @retval EFI_BAD_BUFFER_SIZE Read attempted across an LBA boundary.
402 On output, NumBytes contains the total number of bytes
403 returned in Buffer.
404
405 @retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state.
406
407 @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be read.
408
409 **/
410 EFI_STATUS
411 EFIAPI
412 FvbRead (
413 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
414 IN EFI_LBA Lba,
415 IN UINTN Offset,
416 IN OUT UINTN *NumBytes,
417 IN OUT UINT8 *Buffer
418 )
419 {
420 EFI_STATUS TempStatus;
421 UINTN BlockSize;
422 NOR_FLASH_INSTANCE *Instance;
423
424 Instance = INSTANCE_FROM_FVB_THIS(This);
425
426 DEBUG ((DEBUG_BLKIO, "FvbRead(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
427
428 if (!Instance->Initialized && Instance->Initialize) {
429 Instance->Initialize(Instance);
430 }
431
432 TempStatus = EFI_SUCCESS;
433
434 // Cache the block size to avoid de-referencing pointers all the time
435 BlockSize = Instance->Media.BlockSize;
436
437 DEBUG ((DEBUG_BLKIO, "FvbRead: Check if (Offset=0x%x + NumBytes=0x%x) <= BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
438
439 // The read must not span block boundaries.
440 // We need to check each variable individually because adding two large values together overflows.
441 if ((Offset >= BlockSize) ||
442 (*NumBytes > BlockSize) ||
443 ((Offset + *NumBytes) > BlockSize)) {
444 DEBUG ((EFI_D_ERROR, "FvbRead: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
445 return EFI_BAD_BUFFER_SIZE;
446 }
447
448 // We must have some bytes to read
449 if (*NumBytes == 0) {
450 return EFI_BAD_BUFFER_SIZE;
451 }
452
453 // Decide if we are doing full block reads or not.
454 if (*NumBytes % BlockSize != 0) {
455 TempStatus = NorFlashRead (Instance, Instance->StartLba + Lba, Offset, *NumBytes, Buffer);
456 if (EFI_ERROR (TempStatus)) {
457 return EFI_DEVICE_ERROR;
458 }
459 } else {
460 // Read NOR Flash data into shadow buffer
461 TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, Buffer);
462 if (EFI_ERROR (TempStatus)) {
463 // Return one of the pre-approved error statuses
464 return EFI_DEVICE_ERROR;
465 }
466 }
467 return EFI_SUCCESS;
468 }
469
470 /**
471 Writes the specified number of bytes from the input buffer to the block.
472
473 The Write() function writes the specified number of bytes from
474 the provided buffer to the specified block and offset. If the
475 firmware volume is sticky write, the caller must ensure that
476 all the bits of the specified range to write are in the
477 EFI_FVB_ERASE_POLARITY state before calling the Write()
478 function, or else the result will be unpredictable. This
479 unpredictability arises because, for a sticky-write firmware
480 volume, a write may negate a bit in the EFI_FVB_ERASE_POLARITY
481 state but cannot flip it back again. Before calling the
482 Write() function, it is recommended for the caller to first call
483 the EraseBlocks() function to erase the specified block to
484 write. A block erase cycle will transition bits from the
485 (NOT)EFI_FVB_ERASE_POLARITY state back to the
486 EFI_FVB_ERASE_POLARITY state. Implementations should be
487 mindful that the firmware volume might be in the WriteDisabled
488 state. If it is in this state, the Write() function must
489 return the status code EFI_ACCESS_DENIED without modifying the
490 contents of the firmware volume. The Write() function must
491 also prevent spanning block boundaries. If a write is
492 requested that spans a block boundary, the write must store up
493 to the boundary but not beyond. The output parameter NumBytes
494 must be set to correctly indicate the number of bytes actually
495 written. The caller must be aware that a write may be
496 partially completed. All writes, partial or otherwise, must be
497 fully flushed to the hardware before the Write() service
498 returns.
499
500 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL instance.
501
502 @param Lba The starting logical block index to write to.
503
504 @param Offset Offset into the block at which to begin writing.
505
506 @param NumBytes The pointer to a UINTN.
507 At entry, *NumBytes contains the total size of the buffer.
508 At exit, *NumBytes contains the total number of bytes actually written.
509
510 @param Buffer The pointer to a caller-allocated buffer that contains the source for the write.
511
512 @retval EFI_SUCCESS The firmware volume was written successfully.
513
514 @retval EFI_BAD_BUFFER_SIZE The write was attempted across an LBA boundary.
515 On output, NumBytes contains the total number of bytes
516 actually written.
517
518 @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
519
520 @retval EFI_DEVICE_ERROR The block device is malfunctioning and could not be written.
521
522
523 **/
524 EFI_STATUS
525 EFIAPI
526 FvbWrite (
527 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
528 IN EFI_LBA Lba,
529 IN UINTN Offset,
530 IN OUT UINTN *NumBytes,
531 IN UINT8 *Buffer
532 )
533 {
534 EFI_STATUS TempStatus;
535 UINT32 Tmp;
536 UINT32 TmpBuf;
537 UINT32 WordToWrite;
538 UINT32 Mask;
539 UINTN DoErase;
540 UINTN BytesToWrite;
541 UINTN CurOffset;
542 UINTN WordAddr;
543 UINTN BlockSize;
544 NOR_FLASH_INSTANCE *Instance;
545 UINTN BlockAddress;
546 UINTN PrevBlockAddress;
547
548 PrevBlockAddress = 0;
549
550 Instance = INSTANCE_FROM_FVB_THIS(This);
551
552 if (!Instance->Initialized && Instance->Initialize) {
553 Instance->Initialize(Instance);
554 }
555
556 DEBUG ((DEBUG_BLKIO, "FvbWrite(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Instance->StartLba + Lba, Offset, *NumBytes, Buffer));
557
558 // Detect WriteDisabled state
559 if (Instance->Media.ReadOnly == TRUE) {
560 DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Can not write: Device is in WriteDisabled state.\n"));
561 // It is in WriteDisabled state, return an error right away
562 return EFI_ACCESS_DENIED;
563 }
564
565 // Cache the block size to avoid de-referencing pointers all the time
566 BlockSize = Instance->Media.BlockSize;
567
568 // The write must not span block boundaries.
569 // We need to check each variable individually because adding two large values together overflows.
570 if ( ( Offset >= BlockSize ) ||
571 ( *NumBytes > BlockSize ) ||
572 ( (Offset + *NumBytes) > BlockSize ) ) {
573 DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
574 return EFI_BAD_BUFFER_SIZE;
575 }
576
577 // We must have some bytes to write
578 if (*NumBytes == 0) {
579 DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
580 return EFI_BAD_BUFFER_SIZE;
581 }
582
583 // Pick 128bytes as a good start for word operations as opposed to erasing the
584 // block and writing the data regardless if an erase is really needed.
585 // It looks like most individual NV variable writes are smaller than 128bytes.
586 if (*NumBytes <= 128) {
587 // Check to see if we need to erase before programming the data into NOR.
588 // If the destination bits are only changing from 1s to 0s we can just write.
589 // After a block is erased all bits in the block is set to 1.
590 // If any byte requires us to erase we just give up and rewrite all of it.
591 DoErase = 0;
592 BytesToWrite = *NumBytes;
593 CurOffset = Offset;
594
595 while (BytesToWrite > 0) {
596 // Read full word from NOR, splice as required. A word is the smallest
597 // unit we can write.
598 TempStatus = NorFlashRead (Instance, Instance->StartLba + Lba,
599 CurOffset & ~(0x3), sizeof(Tmp), &Tmp);
600 if (EFI_ERROR (TempStatus)) {
601 return EFI_DEVICE_ERROR;
602 }
603
604 // Physical address of word in NOR to write.
605 WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
606 Lba, BlockSize);
607 // The word of data that is to be written.
608 TmpBuf = *((UINT32*)(Buffer + (*NumBytes - BytesToWrite)));
609
610 // First do word aligned chunks.
611 if ((CurOffset & 0x3) == 0) {
612 if (BytesToWrite >= 4) {
613 // Is the destination still in 'erased' state?
614 if (~Tmp != 0) {
615 // Check to see if we are only changing bits to zero.
616 if ((Tmp ^ TmpBuf) & TmpBuf) {
617 DoErase = 1;
618 break;
619 }
620 }
621 // Write this word to NOR
622 WordToWrite = TmpBuf;
623 CurOffset += sizeof(TmpBuf);
624 BytesToWrite -= sizeof(TmpBuf);
625 } else {
626 // BytesToWrite < 4. Do small writes and left-overs
627 Mask = ~((~0) << (BytesToWrite * 8));
628 // Mask out the bytes we want.
629 TmpBuf &= Mask;
630 // Is the destination still in 'erased' state?
631 if ((Tmp & Mask) != Mask) {
632 // Check to see if we are only changing bits to zero.
633 if ((Tmp ^ TmpBuf) & TmpBuf) {
634 DoErase = 1;
635 break;
636 }
637 }
638 // Merge old and new data. Write merged word to NOR
639 WordToWrite = (Tmp & ~Mask) | TmpBuf;
640 CurOffset += BytesToWrite;
641 BytesToWrite = 0;
642 }
643 } else {
644 // Do multiple words, but starting unaligned.
645 if (BytesToWrite > (4 - (CurOffset & 0x3))) {
646 Mask = ~((~0) << ((CurOffset & 0x3) * 8));
647 // Mask out the bytes we want.
648 TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
649 // Is the destination still in 'erased' state?
650 if ((Tmp & Mask) != Mask) {
651 // Check to see if we are only changing bits to zero.
652 if ((Tmp ^ TmpBuf) & TmpBuf) {
653 DoErase = 1;
654 break;
655 }
656 }
657 // Merge old and new data. Write merged word to NOR
658 WordToWrite = (Tmp & ~Mask) | TmpBuf;
659 BytesToWrite -= (4 - (CurOffset & 0x3));
660 CurOffset += (4 - (CurOffset & 0x3));
661 } else {
662 // Unaligned and fits in one word.
663 Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
664 // Mask out the bytes we want.
665 TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
666 // Is the destination still in 'erased' state?
667 if ((Tmp & Mask) != Mask) {
668 // Check to see if we are only changing bits to zero.
669 if ((Tmp ^ TmpBuf) & TmpBuf) {
670 DoErase = 1;
671 break;
672 }
673 }
674 // Merge old and new data. Write merged word to NOR
675 WordToWrite = (Tmp & ~Mask) | TmpBuf;
676 CurOffset += BytesToWrite;
677 BytesToWrite = 0;
678 }
679 }
680
681 //
682 // Write the word to NOR.
683 //
684
685 BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize);
686 if (BlockAddress != PrevBlockAddress) {
687 TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
688 if (EFI_ERROR (TempStatus)) {
689 return EFI_DEVICE_ERROR;
690 }
691 PrevBlockAddress = BlockAddress;
692 }
693 TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
694 if (EFI_ERROR (TempStatus)) {
695 return EFI_DEVICE_ERROR;
696 }
697 }
698 // Exit if we got here and could write all the data. Otherwise do the
699 // Erase-Write cycle.
700 if (!DoErase) {
701 return EFI_SUCCESS;
702 }
703 }
704
705 // Check we did get some memory. Buffer is BlockSize.
706 if (Instance->FvbBuffer == NULL) {
707 DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
708 return EFI_DEVICE_ERROR;
709 }
710
711 // Read NOR Flash data into shadow buffer
712 TempStatus = NorFlashReadBlocks (Instance, Instance->StartLba + Lba, BlockSize, Instance->FvbBuffer);
713 if (EFI_ERROR (TempStatus)) {
714 // Return one of the pre-approved error statuses
715 return EFI_DEVICE_ERROR;
716 }
717
718 // Put the data at the appropriate location inside the buffer area
719 CopyMem ((VOID*)((UINTN)Instance->FvbBuffer + Offset), Buffer, *NumBytes);
720
721 // Write the modified buffer back to the NorFlash
722 TempStatus = NorFlashWriteBlocks (Instance, Instance->StartLba + Lba, BlockSize, Instance->FvbBuffer);
723 if (EFI_ERROR (TempStatus)) {
724 // Return one of the pre-approved error statuses
725 return EFI_DEVICE_ERROR;
726 }
727
728 return EFI_SUCCESS;
729 }
730
731 /**
732 Erases and initialises a firmware volume block.
733
734 The EraseBlocks() function erases one or more blocks as denoted
735 by the variable argument list. The entire parameter list of
736 blocks must be verified before erasing any blocks. If a block is
737 requested that does not exist within the associated firmware
738 volume (it has a larger index than the last block of the
739 firmware volume), the EraseBlocks() function must return the
740 status code EFI_INVALID_PARAMETER without modifying the contents
741 of the firmware volume. Implementations should be mindful that
742 the firmware volume might be in the WriteDisabled state. If it
743 is in this state, the EraseBlocks() function must return the
744 status code EFI_ACCESS_DENIED without modifying the contents of
745 the firmware volume. All calls to EraseBlocks() must be fully
746 flushed to the hardware before the EraseBlocks() service
747 returns.
748
749 @param This Indicates the EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL
750 instance.
751
752 @param ... The variable argument list is a list of tuples.
753 Each tuple describes a range of LBAs to erase
754 and consists of the following:
755 - An EFI_LBA that indicates the starting LBA
756 - A UINTN that indicates the number of blocks to erase.
757
758 The list is terminated with an EFI_LBA_LIST_TERMINATOR.
759 For example, the following indicates that two ranges of blocks
760 (5-7 and 10-11) are to be erased:
761 EraseBlocks (This, 5, 3, 10, 2, EFI_LBA_LIST_TERMINATOR);
762
763 @retval EFI_SUCCESS The erase request successfully completed.
764
765 @retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
766
767 @retval EFI_DEVICE_ERROR The block device is not functioning correctly and could not be written.
768 The firmware device may have been partially erased.
769
770 @retval EFI_INVALID_PARAMETER One or more of the LBAs listed in the variable argument list do
771 not exist in the firmware volume.
772
773 **/
774 EFI_STATUS
775 EFIAPI
776 FvbEraseBlocks (
777 IN CONST EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL *This,
778 ...
779 )
780 {
781 EFI_STATUS Status;
782 VA_LIST Args;
783 UINTN BlockAddress; // Physical address of Lba to erase
784 EFI_LBA StartingLba; // Lba from which we start erasing
785 UINTN NumOfLba; // Number of Lba blocks to erase
786 NOR_FLASH_INSTANCE *Instance;
787
788 Instance = INSTANCE_FROM_FVB_THIS(This);
789
790 DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks()\n"));
791
792 Status = EFI_SUCCESS;
793
794 // Detect WriteDisabled state
795 if (Instance->Media.ReadOnly == TRUE) {
796 // Firmware volume is in WriteDisabled state
797 DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Device is in WriteDisabled state.\n"));
798 return EFI_ACCESS_DENIED;
799 }
800
801 // Before erasing, check the entire list of parameters to ensure all specified blocks are valid
802
803 VA_START (Args, This);
804 do {
805 // Get the Lba from which we start erasing
806 StartingLba = VA_ARG (Args, EFI_LBA);
807
808 // Have we reached the end of the list?
809 if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
810 //Exit the while loop
811 break;
812 }
813
814 // How many Lba blocks are we requested to erase?
815 NumOfLba = VA_ARG (Args, UINT32);
816
817 // All blocks must be within range
818 DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Check if: ( StartingLba=%ld + NumOfLba=%d - 1 ) > LastBlock=%ld.\n", Instance->StartLba + StartingLba, NumOfLba, Instance->Media.LastBlock));
819 if ((NumOfLba == 0) || ((Instance->StartLba + StartingLba + NumOfLba - 1) > Instance->Media.LastBlock)) {
820 VA_END (Args);
821 DEBUG ((EFI_D_ERROR, "FvbEraseBlocks: ERROR - Lba range goes past the last Lba.\n"));
822 Status = EFI_INVALID_PARAMETER;
823 goto EXIT;
824 }
825 } while (TRUE);
826 VA_END (Args);
827
828 //
829 // To get here, all must be ok, so start erasing
830 //
831 VA_START (Args, This);
832 do {
833 // Get the Lba from which we start erasing
834 StartingLba = VA_ARG (Args, EFI_LBA);
835
836 // Have we reached the end of the list?
837 if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
838 // Exit the while loop
839 break;
840 }
841
842 // How many Lba blocks are we requested to erase?
843 NumOfLba = VA_ARG (Args, UINT32);
844
845 // Go through each one and erase it
846 while (NumOfLba > 0) {
847
848 // Get the physical address of Lba to erase
849 BlockAddress = GET_NOR_BLOCK_ADDRESS (
850 Instance->RegionBaseAddress,
851 Instance->StartLba + StartingLba,
852 Instance->Media.BlockSize
853 );
854
855 // Erase it
856 DEBUG ((DEBUG_BLKIO, "FvbEraseBlocks: Erasing Lba=%ld @ 0x%08x.\n", Instance->StartLba + StartingLba, BlockAddress));
857 Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
858 if (EFI_ERROR(Status)) {
859 VA_END (Args);
860 Status = EFI_DEVICE_ERROR;
861 goto EXIT;
862 }
863
864 // Move to the next Lba
865 StartingLba++;
866 NumOfLba--;
867 }
868 } while (TRUE);
869 VA_END (Args);
870
871 EXIT:
872 return Status;
873 }
874
875 /**
876 Fixup internal data so that EFI can be call in virtual mode.
877 Call the passed in Child Notify event and convert any pointers in
878 lib to virtual mode.
879
880 @param[in] Event The Event that is being processed
881 @param[in] Context Event Context
882 **/
883 VOID
884 EFIAPI
885 FvbVirtualNotifyEvent (
886 IN EFI_EVENT Event,
887 IN VOID *Context
888 )
889 {
890 EfiConvertPointer (0x0, (VOID**)&mFlashNvStorageVariableBase);
891 return;
892 }
893
894 EFI_STATUS
895 EFIAPI
896 NorFlashFvbInitialize (
897 IN NOR_FLASH_INSTANCE* Instance
898 )
899 {
900 EFI_STATUS Status;
901 UINT32 FvbNumLba;
902 EFI_BOOT_MODE BootMode;
903 UINTN RuntimeMmioRegionSize;
904
905 DEBUG((DEBUG_BLKIO,"NorFlashFvbInitialize\n"));
906
907 Instance->Initialized = TRUE;
908 mFlashNvStorageVariableBase = FixedPcdGet32 (PcdFlashNvStorageVariableBase);
909
910 // Set the index of the first LBA for the FVB
911 Instance->StartLba = (PcdGet32 (PcdFlashNvStorageVariableBase) - Instance->RegionBaseAddress) / Instance->Media.BlockSize;
912
913 BootMode = GetBootModeHob ();
914 if (BootMode == BOOT_WITH_DEFAULT_SETTINGS) {
915 Status = EFI_INVALID_PARAMETER;
916 } else {
917 // Determine if there is a valid header at the beginning of the NorFlash
918 Status = ValidateFvHeader (Instance);
919 }
920
921 // Install the Default FVB header if required
922 if (EFI_ERROR(Status)) {
923 // There is no valid header, so time to install one.
924 DEBUG((EFI_D_ERROR,"NorFlashFvbInitialize: ERROR - The FVB Header is not valid. Installing a correct one for this volume.\n"));
925
926 // Erase all the NorFlash that is reserved for variable storage
927 FvbNumLba = (PcdGet32(PcdFlashNvStorageVariableSize) + PcdGet32(PcdFlashNvStorageFtwWorkingSize) + PcdGet32(PcdFlashNvStorageFtwSpareSize)) / Instance->Media.BlockSize;
928
929 Status = FvbEraseBlocks (&Instance->FvbProtocol, (EFI_LBA)0, FvbNumLba, EFI_LBA_LIST_TERMINATOR);
930 if (EFI_ERROR(Status)) {
931 return Status;
932 }
933
934 // Install all appropriate headers
935 Status = InitializeFvAndVariableStoreHeaders (Instance);
936 if (EFI_ERROR(Status)) {
937 return Status;
938 }
939 }
940
941 //
942 // Declare the Non-Volatile storage as EFI_MEMORY_RUNTIME
943 //
944
945 // Note: all the NOR Flash region needs to be reserved into the UEFI Runtime memory;
946 // even if we only use the small block region at the top of the NOR Flash.
947 // The reason is when the NOR Flash memory is set into program mode, the command
948 // is written as the base of the flash region (ie: Instance->DeviceBaseAddress)
949 RuntimeMmioRegionSize = (Instance->RegionBaseAddress - Instance->DeviceBaseAddress) + Instance->Size;
950
951 Status = gDS->AddMemorySpace (
952 EfiGcdMemoryTypeMemoryMappedIo,
953 Instance->DeviceBaseAddress, RuntimeMmioRegionSize,
954 EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
955 );
956 ASSERT_EFI_ERROR (Status);
957
958 Status = gDS->SetMemorySpaceAttributes (
959 Instance->DeviceBaseAddress, RuntimeMmioRegionSize,
960 EFI_MEMORY_UC | EFI_MEMORY_RUNTIME);
961 ASSERT_EFI_ERROR (Status);
962
963 //
964 // Register for the virtual address change event
965 //
966 Status = gBS->CreateEventEx (
967 EVT_NOTIFY_SIGNAL,
968 TPL_NOTIFY,
969 FvbVirtualNotifyEvent,
970 NULL,
971 &gEfiEventVirtualAddressChangeGuid,
972 &mFvbVirtualAddrChangeEvent
973 );
974 ASSERT_EFI_ERROR (Status);
975
976 return Status;
977 }