ArmPlatformPkg/NorFlashDxe: prepare for devicepath format change
[mirror_edk2.git] / ArmPlatformPkg / Drivers / NorFlashDxe / NorFlashDxe.c
1 /** @file NorFlashDxe.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 <Library/UefiLib.h>
16 #include <Library/BaseMemoryLib.h>
17 #include <Library/MemoryAllocationLib.h>
18 #include <Library/UefiBootServicesTableLib.h>
19 #include <Library/PcdLib.h>
20
21 #include "NorFlashDxe.h"
22
23 STATIC EFI_EVENT mNorFlashVirtualAddrChangeEvent;
24
25 //
26 // Global variable declarations
27 //
28 NOR_FLASH_INSTANCE **mNorFlashInstances;
29 UINT32 mNorFlashDeviceCount;
30
31 NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = {
32 NOR_FLASH_SIGNATURE, // Signature
33 NULL, // Handle ... NEED TO BE FILLED
34
35 0, // DeviceBaseAddress ... NEED TO BE FILLED
36 0, // RegionBaseAddress ... NEED TO BE FILLED
37 0, // Size ... NEED TO BE FILLED
38 0, // StartLba
39
40 {
41 EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision
42 NULL, // Media ... NEED TO BE FILLED
43 NorFlashBlockIoReset, // Reset;
44 NorFlashBlockIoReadBlocks, // ReadBlocks
45 NorFlashBlockIoWriteBlocks, // WriteBlocks
46 NorFlashBlockIoFlushBlocks // FlushBlocks
47 }, // BlockIoProtocol
48
49 {
50 0, // MediaId ... NEED TO BE FILLED
51 FALSE, // RemovableMedia
52 TRUE, // MediaPresent
53 FALSE, // LogicalPartition
54 FALSE, // ReadOnly
55 FALSE, // WriteCaching;
56 0, // BlockSize ... NEED TO BE FILLED
57 4, // IoAlign
58 0, // LastBlock ... NEED TO BE FILLED
59 0, // LowestAlignedLba
60 1, // LogicalBlocksPerPhysicalBlock
61 }, //Media;
62
63 {
64 EFI_DISK_IO_PROTOCOL_REVISION, // Revision
65 NorFlashDiskIoReadDisk, // ReadDisk
66 NorFlashDiskIoWriteDisk // WriteDisk
67 },
68
69 {
70 FvbGetAttributes, // GetAttributes
71 FvbSetAttributes, // SetAttributes
72 FvbGetPhysicalAddress, // GetPhysicalAddress
73 FvbGetBlockSize, // GetBlockSize
74 FvbRead, // Read
75 FvbWrite, // Write
76 FvbEraseBlocks, // EraseBlocks
77 NULL, //ParentHandle
78 }, // FvbProtoccol;
79 NULL, // ShadowBuffer
80 {
81 {
82 {
83 HARDWARE_DEVICE_PATH,
84 HW_VENDOR_DP,
85 {
86 (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End)),
87 (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End) >> 8)
88 }
89 },
90 { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } }, // GUID ... NEED TO BE FILLED
91 },
92 {
93 END_DEVICE_PATH_TYPE,
94 END_ENTIRE_DEVICE_PATH_SUBTYPE,
95 { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 }
96 }
97 } // DevicePath
98 };
99
100 EFI_STATUS
101 NorFlashCreateInstance (
102 IN UINTN NorFlashDeviceBase,
103 IN UINTN NorFlashRegionBase,
104 IN UINTN NorFlashSize,
105 IN UINT32 Index,
106 IN UINT32 BlockSize,
107 IN BOOLEAN SupportFvb,
108 IN CONST GUID *NorFlashGuid,
109 OUT NOR_FLASH_INSTANCE** NorFlashInstance
110 )
111 {
112 EFI_STATUS Status;
113 NOR_FLASH_INSTANCE* Instance;
114
115 ASSERT(NorFlashInstance != NULL);
116
117 Instance = AllocateRuntimeCopyPool (sizeof(NOR_FLASH_INSTANCE),&mNorFlashInstanceTemplate);
118 if (Instance == NULL) {
119 return EFI_OUT_OF_RESOURCES;
120 }
121
122 Instance->DeviceBaseAddress = NorFlashDeviceBase;
123 Instance->RegionBaseAddress = NorFlashRegionBase;
124 Instance->Size = NorFlashSize;
125
126 Instance->BlockIoProtocol.Media = &Instance->Media;
127 Instance->Media.MediaId = Index;
128 Instance->Media.BlockSize = BlockSize;
129 Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1;
130
131 CopyGuid (&Instance->DevicePath.Vendor.Guid, NorFlashGuid);
132
133 Instance->ShadowBuffer = AllocateRuntimePool (BlockSize);;
134 if (Instance->ShadowBuffer == NULL) {
135 return EFI_OUT_OF_RESOURCES;
136 }
137
138 if (SupportFvb) {
139 NorFlashFvbInitialize (Instance);
140
141 Status = gBS->InstallMultipleProtocolInterfaces (
142 &Instance->Handle,
143 &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
144 &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
145 &gEfiFirmwareVolumeBlockProtocolGuid, &Instance->FvbProtocol,
146 NULL
147 );
148 if (EFI_ERROR(Status)) {
149 FreePool (Instance);
150 return Status;
151 }
152 } else {
153 Status = gBS->InstallMultipleProtocolInterfaces (
154 &Instance->Handle,
155 &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
156 &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
157 &gEfiDiskIoProtocolGuid, &Instance->DiskIoProtocol,
158 NULL
159 );
160 if (EFI_ERROR(Status)) {
161 FreePool (Instance);
162 return Status;
163 }
164 }
165
166 *NorFlashInstance = Instance;
167 return Status;
168 }
169
170 UINT32
171 NorFlashReadStatusRegister (
172 IN NOR_FLASH_INSTANCE *Instance,
173 IN UINTN SR_Address
174 )
175 {
176 // Prepare to read the status register
177 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
178 return MmioRead32 (Instance->DeviceBaseAddress);
179 }
180
181 STATIC
182 BOOLEAN
183 NorFlashBlockIsLocked (
184 IN NOR_FLASH_INSTANCE *Instance,
185 IN UINTN BlockAddress
186 )
187 {
188 UINT32 LockStatus;
189
190 // Send command for reading device id
191 SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
192
193 // Read block lock status
194 LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
195
196 // Decode block lock status
197 LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
198
199 if ((LockStatus & 0x2) != 0) {
200 DEBUG((EFI_D_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
201 }
202
203 return ((LockStatus & 0x1) != 0);
204 }
205
206 STATIC
207 EFI_STATUS
208 NorFlashUnlockSingleBlock (
209 IN NOR_FLASH_INSTANCE *Instance,
210 IN UINTN BlockAddress
211 )
212 {
213 UINT32 LockStatus;
214
215 // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
216 // and to protect shared data structures.
217
218 if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
219 do {
220 // Request a lock setup
221 SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
222
223 // Request an unlock
224 SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
225
226 // Send command for reading device id
227 SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
228
229 // Read block lock status
230 LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
231
232 // Decode block lock status
233 LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
234 } while ((LockStatus & 0x1) == 1);
235 } else {
236 // Request a lock setup
237 SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
238
239 // Request an unlock
240 SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
241
242 // Wait until the status register gives us the all clear
243 do {
244 LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
245 } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
246 }
247
248 // Put device back into Read Array mode
249 SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
250
251 DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress));
252
253 return EFI_SUCCESS;
254 }
255
256 STATIC
257 EFI_STATUS
258 NorFlashUnlockSingleBlockIfNecessary (
259 IN NOR_FLASH_INSTANCE *Instance,
260 IN UINTN BlockAddress
261 )
262 {
263 EFI_STATUS Status;
264
265 Status = EFI_SUCCESS;
266
267 if (NorFlashBlockIsLocked (Instance, BlockAddress) == TRUE) {
268 Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
269 }
270
271 return Status;
272 }
273
274
275 /**
276 * The following function presumes that the block has already been unlocked.
277 **/
278 STATIC
279 EFI_STATUS
280 NorFlashEraseSingleBlock (
281 IN NOR_FLASH_INSTANCE *Instance,
282 IN UINTN BlockAddress
283 )
284 {
285 EFI_STATUS Status;
286 UINT32 StatusRegister;
287
288 Status = EFI_SUCCESS;
289
290 // Request a block erase and then confirm it
291 SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
292 SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
293
294 // Wait until the status register gives us the all clear
295 do {
296 StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
297 } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
298
299 if (StatusRegister & P30_SR_BIT_VPP) {
300 DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
301 Status = EFI_DEVICE_ERROR;
302 }
303
304 if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
305 DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
306 Status = EFI_DEVICE_ERROR;
307 }
308
309 if (StatusRegister & P30_SR_BIT_ERASE) {
310 DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
311 Status = EFI_DEVICE_ERROR;
312 }
313
314 if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
315 // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
316 DEBUG((EFI_D_INFO,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
317 Status = EFI_WRITE_PROTECTED;
318 }
319
320 if (EFI_ERROR(Status)) {
321 // Clear the Status Register
322 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
323 }
324
325 // Put device back into Read Array mode
326 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
327
328 return Status;
329 }
330
331 /**
332 * This function unlock and erase an entire NOR Flash block.
333 **/
334 EFI_STATUS
335 NorFlashUnlockAndEraseSingleBlock (
336 IN NOR_FLASH_INSTANCE *Instance,
337 IN UINTN BlockAddress
338 )
339 {
340 EFI_STATUS Status;
341 UINTN Index;
342 EFI_TPL OriginalTPL;
343
344 if (!EfiAtRuntime ()) {
345 // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
346 OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
347 } else {
348 // This initialization is only to prevent the compiler to complain about the
349 // use of uninitialized variables
350 OriginalTPL = TPL_HIGH_LEVEL;
351 }
352
353 Index = 0;
354 // The block erase might fail a first time (SW bug ?). Retry it ...
355 do {
356 // Unlock the block if we have to
357 Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
358 if (EFI_ERROR (Status)) {
359 break;
360 }
361 Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
362 Index++;
363 } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
364
365 if (Index == NOR_FLASH_ERASE_RETRY) {
366 DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress,Index));
367 }
368
369 if (!EfiAtRuntime ()) {
370 // Interruptions can resume.
371 gBS->RestoreTPL (OriginalTPL);
372 }
373
374 return Status;
375 }
376
377
378 STATIC
379 EFI_STATUS
380 NorFlashWriteSingleWord (
381 IN NOR_FLASH_INSTANCE *Instance,
382 IN UINTN WordAddress,
383 IN UINT32 WriteData
384 )
385 {
386 EFI_STATUS Status;
387 UINT32 StatusRegister;
388
389 Status = EFI_SUCCESS;
390
391 // Request a write single word command
392 SEND_NOR_COMMAND(WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
393
394 // Store the word into NOR Flash;
395 MmioWrite32 (WordAddress, WriteData);
396
397 // Wait for the write to complete and then check for any errors; i.e. check the Status Register
398 do {
399 // Prepare to read the status register
400 StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
401 // The chip is busy while the WRITE bit is not asserted
402 } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
403
404
405 // Perform a full status check:
406 // Mask the relevant bits of Status Register.
407 // Everything should be zero, if not, we have a problem
408
409 if (StatusRegister & P30_SR_BIT_VPP) {
410 DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n",WordAddress));
411 Status = EFI_DEVICE_ERROR;
412 }
413
414 if (StatusRegister & P30_SR_BIT_PROGRAM) {
415 DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n",WordAddress));
416 Status = EFI_DEVICE_ERROR;
417 }
418
419 if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
420 DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n",WordAddress));
421 Status = EFI_DEVICE_ERROR;
422 }
423
424 if (!EFI_ERROR(Status)) {
425 // Clear the Status Register
426 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
427 }
428
429 // Put device back into Read Array mode
430 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
431
432 return Status;
433 }
434
435 /*
436 * Writes data to the NOR Flash using the Buffered Programming method.
437 *
438 * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
439 * Therefore this function will only handle buffers up to 32 words or 128 bytes.
440 * To deal with larger buffers, call this function again.
441 *
442 * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
443 * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
444 *
445 * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
446 * then programming time is doubled and power consumption is increased.
447 * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
448 * i.e. the last 4 bits of the target start address must be zero: 0x......00
449 */
450 EFI_STATUS
451 NorFlashWriteBuffer (
452 IN NOR_FLASH_INSTANCE *Instance,
453 IN UINTN TargetAddress,
454 IN UINTN BufferSizeInBytes,
455 IN UINT32 *Buffer
456 )
457 {
458 EFI_STATUS Status;
459 UINTN BufferSizeInWords;
460 UINTN Count;
461 volatile UINT32 *Data;
462 UINTN WaitForBuffer;
463 BOOLEAN BufferAvailable;
464 UINT32 StatusRegister;
465
466 WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS;
467 BufferAvailable = FALSE;
468
469 // Check that the target address does not cross a 32-word boundary.
470 if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
471 return EFI_INVALID_PARAMETER;
472 }
473
474 // Check there are some data to program
475 if (BufferSizeInBytes == 0) {
476 return EFI_BUFFER_TOO_SMALL;
477 }
478
479 // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
480 if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
481 return EFI_BAD_BUFFER_SIZE;
482 }
483
484 // Check that the buffer size is a multiple of 32-bit words
485 if ((BufferSizeInBytes % 4) != 0) {
486 return EFI_BAD_BUFFER_SIZE;
487 }
488
489 // Pre-programming conditions checked, now start the algorithm.
490
491 // Prepare the data destination address
492 Data = (UINT32 *)TargetAddress;
493
494 // Check the availability of the buffer
495 do {
496 // Issue the Buffered Program Setup command
497 SEND_NOR_COMMAND(TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
498
499 // Read back the status register bit#7 from the same address
500 if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
501 BufferAvailable = TRUE;
502 }
503
504 // Update the loop counter
505 WaitForBuffer--;
506
507 } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
508
509 // The buffer was not available for writing
510 if (WaitForBuffer == 0) {
511 Status = EFI_DEVICE_ERROR;
512 goto EXIT;
513 }
514
515 // From now on we work in 32-bit words
516 BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
517
518 // Write the word count, which is (buffer_size_in_words - 1),
519 // because word count 0 means one word.
520 SEND_NOR_COMMAND(TargetAddress, 0, (BufferSizeInWords - 1));
521
522 // Write the data to the NOR Flash, advancing each address by 4 bytes
523 for(Count=0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
524 MmioWrite32 ((UINTN)Data, *Buffer);
525 }
526
527 // Issue the Buffered Program Confirm command, to start the programming operation
528 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
529
530 // Wait for the write to complete and then check for any errors; i.e. check the Status Register
531 do {
532 StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
533 // The chip is busy while the WRITE bit is not asserted
534 } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
535
536
537 // Perform a full status check:
538 // Mask the relevant bits of Status Register.
539 // Everything should be zero, if not, we have a problem
540
541 Status = EFI_SUCCESS;
542
543 if (StatusRegister & P30_SR_BIT_VPP) {
544 DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
545 Status = EFI_DEVICE_ERROR;
546 }
547
548 if (StatusRegister & P30_SR_BIT_PROGRAM) {
549 DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
550 Status = EFI_DEVICE_ERROR;
551 }
552
553 if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
554 DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n",TargetAddress));
555 Status = EFI_DEVICE_ERROR;
556 }
557
558 if (!EFI_ERROR(Status)) {
559 // Clear the Status Register
560 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
561 }
562
563 EXIT:
564 // Put device back into Read Array mode
565 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
566
567 return Status;
568 }
569
570 STATIC
571 EFI_STATUS
572 NorFlashWriteFullBlock (
573 IN NOR_FLASH_INSTANCE *Instance,
574 IN EFI_LBA Lba,
575 IN UINT32 *DataBuffer,
576 IN UINT32 BlockSizeInWords
577 )
578 {
579 EFI_STATUS Status;
580 UINTN WordAddress;
581 UINT32 WordIndex;
582 UINTN BufferIndex;
583 UINTN BlockAddress;
584 UINTN BuffersInBlock;
585 UINTN RemainingWords;
586 EFI_TPL OriginalTPL;
587 UINTN Cnt;
588
589 Status = EFI_SUCCESS;
590
591 // Get the physical address of the block
592 BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
593
594 // Start writing from the first address at the start of the block
595 WordAddress = BlockAddress;
596
597 if (!EfiAtRuntime ()) {
598 // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
599 OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
600 } else {
601 // This initialization is only to prevent the compiler to complain about the
602 // use of uninitialized variables
603 OriginalTPL = TPL_HIGH_LEVEL;
604 }
605
606 Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
607 if (EFI_ERROR(Status)) {
608 DEBUG((EFI_D_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
609 goto EXIT;
610 }
611
612 // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
613
614 // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
615 if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
616
617 // First, break the entire block into buffer-sized chunks.
618 BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
619
620 // Then feed each buffer chunk to the NOR Flash
621 // If a buffer does not contain any data, don't write it.
622 for(BufferIndex=0;
623 BufferIndex < BuffersInBlock;
624 BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
625 ) {
626 // Check the buffer to see if it contains any data (not set all 1s).
627 for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
628 if (~DataBuffer[Cnt] != 0 ) {
629 // Some data found, write the buffer.
630 Status = NorFlashWriteBuffer (Instance, WordAddress, P30_MAX_BUFFER_SIZE_IN_BYTES,
631 DataBuffer);
632 if (EFI_ERROR(Status)) {
633 goto EXIT;
634 }
635 break;
636 }
637 }
638 }
639
640 // Finally, finish off any remaining words that are less than the maximum size of the buffer
641 RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
642
643 if(RemainingWords != 0) {
644 Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
645 if (EFI_ERROR(Status)) {
646 goto EXIT;
647 }
648 }
649
650 } else {
651 // For now, use the single word programming algorithm
652 // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
653 // i.e. which ends in the range 0x......01 - 0x......7F.
654 for(WordIndex=0; WordIndex<BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
655 Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
656 if (EFI_ERROR(Status)) {
657 goto EXIT;
658 }
659 }
660 }
661
662 EXIT:
663 if (!EfiAtRuntime ()) {
664 // Interruptions can resume.
665 gBS->RestoreTPL (OriginalTPL);
666 }
667
668 if (EFI_ERROR(Status)) {
669 DEBUG((EFI_D_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
670 }
671 return Status;
672 }
673
674
675 EFI_STATUS
676 NorFlashWriteBlocks (
677 IN NOR_FLASH_INSTANCE *Instance,
678 IN EFI_LBA Lba,
679 IN UINTN BufferSizeInBytes,
680 IN VOID *Buffer
681 )
682 {
683 UINT32 *pWriteBuffer;
684 EFI_STATUS Status = EFI_SUCCESS;
685 EFI_LBA CurrentBlock;
686 UINT32 BlockSizeInWords;
687 UINT32 NumBlocks;
688 UINT32 BlockCount;
689
690 // The buffer must be valid
691 if (Buffer == NULL) {
692 return EFI_INVALID_PARAMETER;
693 }
694
695 if(Instance->Media.ReadOnly == TRUE) {
696 return EFI_WRITE_PROTECTED;
697 }
698
699 // We must have some bytes to read
700 DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
701 if(BufferSizeInBytes == 0) {
702 return EFI_BAD_BUFFER_SIZE;
703 }
704
705 // The size of the buffer must be a multiple of the block size
706 DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
707 if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
708 return EFI_BAD_BUFFER_SIZE;
709 }
710
711 // All blocks must be within the device
712 NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
713
714 DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
715
716 if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
717 DEBUG((EFI_D_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
718 return EFI_INVALID_PARAMETER;
719 }
720
721 BlockSizeInWords = Instance->Media.BlockSize / 4;
722
723 // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
724 // to a proper data type, so use *ReadBuffer
725 pWriteBuffer = (UINT32 *)Buffer;
726
727 CurrentBlock = Lba;
728 for (BlockCount=0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
729
730 DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
731
732 Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
733
734 if (EFI_ERROR(Status)) {
735 break;
736 }
737 }
738
739 DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
740 return Status;
741 }
742
743 #define BOTH_ALIGNED(a, b, align) ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0)
744
745 /**
746 Copy Length bytes from Source to Destination, using aligned accesses only.
747 Note that this implementation uses memcpy() semantics rather then memmove()
748 semantics, i.e., SourceBuffer and DestinationBuffer should not overlap.
749
750 @param DestinationBuffer The target of the copy request.
751 @param SourceBuffer The place to copy from.
752 @param Length The number of bytes to copy.
753
754 @return Destination
755
756 **/
757 STATIC
758 VOID *
759 AlignedCopyMem (
760 OUT VOID *DestinationBuffer,
761 IN CONST VOID *SourceBuffer,
762 IN UINTN Length
763 )
764 {
765 UINT8 *Destination8;
766 CONST UINT8 *Source8;
767 UINT32 *Destination32;
768 CONST UINT32 *Source32;
769 UINT64 *Destination64;
770 CONST UINT64 *Source64;
771
772 if (BOTH_ALIGNED(DestinationBuffer, SourceBuffer, 8) && Length >= 8) {
773 Destination64 = DestinationBuffer;
774 Source64 = SourceBuffer;
775 while (Length >= 8) {
776 *Destination64++ = *Source64++;
777 Length -= 8;
778 }
779
780 Destination8 = (UINT8 *)Destination64;
781 Source8 = (CONST UINT8 *)Source64;
782 } else if (BOTH_ALIGNED(DestinationBuffer, SourceBuffer, 4) && Length >= 4) {
783 Destination32 = DestinationBuffer;
784 Source32 = SourceBuffer;
785 while (Length >= 4) {
786 *Destination32++ = *Source32++;
787 Length -= 4;
788 }
789
790 Destination8 = (UINT8 *)Destination32;
791 Source8 = (CONST UINT8 *)Source32;
792 } else {
793 Destination8 = DestinationBuffer;
794 Source8 = SourceBuffer;
795 }
796 while (Length-- != 0) {
797 *Destination8++ = *Source8++;
798 }
799 return DestinationBuffer;
800 }
801
802 EFI_STATUS
803 NorFlashReadBlocks (
804 IN NOR_FLASH_INSTANCE *Instance,
805 IN EFI_LBA Lba,
806 IN UINTN BufferSizeInBytes,
807 OUT VOID *Buffer
808 )
809 {
810 UINT32 NumBlocks;
811 UINTN StartAddress;
812
813 DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n",
814 BufferSizeInBytes, Instance->Media.BlockSize, Instance->Media.LastBlock, Lba));
815
816 // The buffer must be valid
817 if (Buffer == NULL) {
818 return EFI_INVALID_PARAMETER;
819 }
820
821 // Return if we have not any byte to read
822 if (BufferSizeInBytes == 0) {
823 return EFI_SUCCESS;
824 }
825
826 // The size of the buffer must be a multiple of the block size
827 if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
828 return EFI_BAD_BUFFER_SIZE;
829 }
830
831 // All blocks must be within the device
832 NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
833
834 if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
835 DEBUG((EFI_D_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
836 return EFI_INVALID_PARAMETER;
837 }
838
839 // Get the address to start reading from
840 StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
841 Lba,
842 Instance->Media.BlockSize
843 );
844
845 // Put the device into Read Array mode
846 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
847
848 // Readout the data
849 AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes);
850
851 return EFI_SUCCESS;
852 }
853
854 EFI_STATUS
855 NorFlashRead (
856 IN NOR_FLASH_INSTANCE *Instance,
857 IN EFI_LBA Lba,
858 IN UINTN Offset,
859 IN UINTN BufferSizeInBytes,
860 OUT VOID *Buffer
861 )
862 {
863 UINTN StartAddress;
864
865 // The buffer must be valid
866 if (Buffer == NULL) {
867 return EFI_INVALID_PARAMETER;
868 }
869
870 // Return if we have not any byte to read
871 if (BufferSizeInBytes == 0) {
872 return EFI_SUCCESS;
873 }
874
875 if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) {
876 DEBUG ((EFI_D_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n"));
877 return EFI_INVALID_PARAMETER;
878 }
879
880 // Get the address to start reading from
881 StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
882 Lba,
883 Instance->Media.BlockSize
884 );
885
886 // Put the device into Read Array mode
887 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
888
889 // Readout the data
890 AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes);
891
892 return EFI_SUCCESS;
893 }
894
895 /*
896 Write a full or portion of a block. It must not span block boundaries; that is,
897 Offset + *NumBytes <= Instance->Media.BlockSize.
898 */
899 EFI_STATUS
900 NorFlashWriteSingleBlock (
901 IN NOR_FLASH_INSTANCE *Instance,
902 IN EFI_LBA Lba,
903 IN UINTN Offset,
904 IN OUT UINTN *NumBytes,
905 IN UINT8 *Buffer
906 )
907 {
908 EFI_STATUS TempStatus;
909 UINT32 Tmp;
910 UINT32 TmpBuf;
911 UINT32 WordToWrite;
912 UINT32 Mask;
913 BOOLEAN DoErase;
914 UINTN BytesToWrite;
915 UINTN CurOffset;
916 UINTN WordAddr;
917 UINTN BlockSize;
918 UINTN BlockAddress;
919 UINTN PrevBlockAddress;
920
921 PrevBlockAddress = 0;
922
923 DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer));
924
925 // Detect WriteDisabled state
926 if (Instance->Media.ReadOnly == TRUE) {
927 DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n"));
928 // It is in WriteDisabled state, return an error right away
929 return EFI_ACCESS_DENIED;
930 }
931
932 // Cache the block size to avoid de-referencing pointers all the time
933 BlockSize = Instance->Media.BlockSize;
934
935 // The write must not span block boundaries.
936 // We need to check each variable individually because adding two large values together overflows.
937 if ( ( Offset >= BlockSize ) ||
938 ( *NumBytes > BlockSize ) ||
939 ( (Offset + *NumBytes) > BlockSize ) ) {
940 DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
941 return EFI_BAD_BUFFER_SIZE;
942 }
943
944 // We must have some bytes to write
945 if (*NumBytes == 0) {
946 DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
947 return EFI_BAD_BUFFER_SIZE;
948 }
949
950 // Pick 128bytes as a good start for word operations as opposed to erasing the
951 // block and writing the data regardless if an erase is really needed.
952 // It looks like most individual NV variable writes are smaller than 128bytes.
953 if (*NumBytes <= 128) {
954 // Check to see if we need to erase before programming the data into NOR.
955 // If the destination bits are only changing from 1s to 0s we can just write.
956 // After a block is erased all bits in the block is set to 1.
957 // If any byte requires us to erase we just give up and rewrite all of it.
958 DoErase = FALSE;
959 BytesToWrite = *NumBytes;
960 CurOffset = Offset;
961
962 while (BytesToWrite > 0) {
963 // Read full word from NOR, splice as required. A word is the smallest
964 // unit we can write.
965 TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof(Tmp), &Tmp);
966 if (EFI_ERROR (TempStatus)) {
967 return EFI_DEVICE_ERROR;
968 }
969
970 // Physical address of word in NOR to write.
971 WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
972 Lba, BlockSize);
973 // The word of data that is to be written.
974 TmpBuf = *((UINT32*)(Buffer + (*NumBytes - BytesToWrite)));
975
976 // First do word aligned chunks.
977 if ((CurOffset & 0x3) == 0) {
978 if (BytesToWrite >= 4) {
979 // Is the destination still in 'erased' state?
980 if (~Tmp != 0) {
981 // Check to see if we are only changing bits to zero.
982 if ((Tmp ^ TmpBuf) & TmpBuf) {
983 DoErase = TRUE;
984 break;
985 }
986 }
987 // Write this word to NOR
988 WordToWrite = TmpBuf;
989 CurOffset += sizeof(TmpBuf);
990 BytesToWrite -= sizeof(TmpBuf);
991 } else {
992 // BytesToWrite < 4. Do small writes and left-overs
993 Mask = ~((~0) << (BytesToWrite * 8));
994 // Mask out the bytes we want.
995 TmpBuf &= Mask;
996 // Is the destination still in 'erased' state?
997 if ((Tmp & Mask) != Mask) {
998 // Check to see if we are only changing bits to zero.
999 if ((Tmp ^ TmpBuf) & TmpBuf) {
1000 DoErase = TRUE;
1001 break;
1002 }
1003 }
1004 // Merge old and new data. Write merged word to NOR
1005 WordToWrite = (Tmp & ~Mask) | TmpBuf;
1006 CurOffset += BytesToWrite;
1007 BytesToWrite = 0;
1008 }
1009 } else {
1010 // Do multiple words, but starting unaligned.
1011 if (BytesToWrite > (4 - (CurOffset & 0x3))) {
1012 Mask = ((~0) << ((CurOffset & 0x3) * 8));
1013 // Mask out the bytes we want.
1014 TmpBuf &= Mask;
1015 // Is the destination still in 'erased' state?
1016 if ((Tmp & Mask) != Mask) {
1017 // Check to see if we are only changing bits to zero.
1018 if ((Tmp ^ TmpBuf) & TmpBuf) {
1019 DoErase = TRUE;
1020 break;
1021 }
1022 }
1023 // Merge old and new data. Write merged word to NOR
1024 WordToWrite = (Tmp & ~Mask) | TmpBuf;
1025 BytesToWrite -= (4 - (CurOffset & 0x3));
1026 CurOffset += (4 - (CurOffset & 0x3));
1027 } else {
1028 // Unaligned and fits in one word.
1029 Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
1030 // Mask out the bytes we want.
1031 TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
1032 // Is the destination still in 'erased' state?
1033 if ((Tmp & Mask) != Mask) {
1034 // Check to see if we are only changing bits to zero.
1035 if ((Tmp ^ TmpBuf) & TmpBuf) {
1036 DoErase = TRUE;
1037 break;
1038 }
1039 }
1040 // Merge old and new data. Write merged word to NOR
1041 WordToWrite = (Tmp & ~Mask) | TmpBuf;
1042 CurOffset += BytesToWrite;
1043 BytesToWrite = 0;
1044 }
1045 }
1046
1047 //
1048 // Write the word to NOR.
1049 //
1050
1051 BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize);
1052 if (BlockAddress != PrevBlockAddress) {
1053 TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
1054 if (EFI_ERROR (TempStatus)) {
1055 return EFI_DEVICE_ERROR;
1056 }
1057 PrevBlockAddress = BlockAddress;
1058 }
1059 TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
1060 if (EFI_ERROR (TempStatus)) {
1061 return EFI_DEVICE_ERROR;
1062 }
1063 }
1064 // Exit if we got here and could write all the data. Otherwise do the
1065 // Erase-Write cycle.
1066 if (!DoErase) {
1067 return EFI_SUCCESS;
1068 }
1069 }
1070
1071 // Check we did get some memory. Buffer is BlockSize.
1072 if (Instance->ShadowBuffer == NULL) {
1073 DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
1074 return EFI_DEVICE_ERROR;
1075 }
1076
1077 // Read NOR Flash data into shadow buffer
1078 TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
1079 if (EFI_ERROR (TempStatus)) {
1080 // Return one of the pre-approved error statuses
1081 return EFI_DEVICE_ERROR;
1082 }
1083
1084 // Put the data at the appropriate location inside the buffer area
1085 CopyMem ((VOID*)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes);
1086
1087 // Write the modified buffer back to the NorFlash
1088 TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
1089 if (EFI_ERROR (TempStatus)) {
1090 // Return one of the pre-approved error statuses
1091 return EFI_DEVICE_ERROR;
1092 }
1093
1094 return EFI_SUCCESS;
1095 }
1096
1097 /*
1098 Although DiskIoDxe will automatically install the DiskIO protocol whenever
1099 we install the BlockIO protocol, its implementation is sub-optimal as it reads
1100 and writes entire blocks using the BlockIO protocol. In fact we can access
1101 NOR flash with a finer granularity than that, so we can improve performance
1102 by directly producing the DiskIO protocol.
1103 */
1104
1105 /**
1106 Read BufferSize bytes from Offset into Buffer.
1107
1108 @param This Protocol instance pointer.
1109 @param MediaId Id of the media, changes every time the media is replaced.
1110 @param Offset The starting byte offset to read from
1111 @param BufferSize Size of Buffer
1112 @param Buffer Buffer containing read data
1113
1114 @retval EFI_SUCCESS The data was read correctly from the device.
1115 @retval EFI_DEVICE_ERROR The device reported an error while performing the read.
1116 @retval EFI_NO_MEDIA There is no media in the device.
1117 @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
1118 @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not
1119 valid for the device.
1120
1121 **/
1122 EFI_STATUS
1123 EFIAPI
1124 NorFlashDiskIoReadDisk (
1125 IN EFI_DISK_IO_PROTOCOL *This,
1126 IN UINT32 MediaId,
1127 IN UINT64 DiskOffset,
1128 IN UINTN BufferSize,
1129 OUT VOID *Buffer
1130 )
1131 {
1132 NOR_FLASH_INSTANCE *Instance;
1133 UINT32 BlockSize;
1134 UINT32 BlockOffset;
1135 EFI_LBA Lba;
1136
1137 Instance = INSTANCE_FROM_DISKIO_THIS(This);
1138
1139 if (MediaId != Instance->Media.MediaId) {
1140 return EFI_MEDIA_CHANGED;
1141 }
1142
1143 BlockSize = Instance->Media.BlockSize;
1144 Lba = (EFI_LBA) DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
1145
1146 return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer);
1147 }
1148
1149 /**
1150 Writes a specified number of bytes to a device.
1151
1152 @param This Indicates a pointer to the calling context.
1153 @param MediaId ID of the medium to be written.
1154 @param Offset The starting byte offset on the logical block I/O device to write.
1155 @param BufferSize The size in bytes of Buffer. The number of bytes to write to the device.
1156 @param Buffer A pointer to the buffer containing the data to be written.
1157
1158 @retval EFI_SUCCESS The data was written correctly to the device.
1159 @retval EFI_WRITE_PROTECTED The device can not be written to.
1160 @retval EFI_DEVICE_ERROR The device reported an error while performing the write.
1161 @retval EFI_NO_MEDIA There is no media in the device.
1162 @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
1163 @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not
1164 valid for the device.
1165
1166 **/
1167 EFI_STATUS
1168 EFIAPI
1169 NorFlashDiskIoWriteDisk (
1170 IN EFI_DISK_IO_PROTOCOL *This,
1171 IN UINT32 MediaId,
1172 IN UINT64 DiskOffset,
1173 IN UINTN BufferSize,
1174 IN VOID *Buffer
1175 )
1176 {
1177 NOR_FLASH_INSTANCE *Instance;
1178 UINT32 BlockSize;
1179 UINT32 BlockOffset;
1180 EFI_LBA Lba;
1181 UINTN RemainingBytes;
1182 UINTN WriteSize;
1183 EFI_STATUS Status;
1184
1185 Instance = INSTANCE_FROM_DISKIO_THIS(This);
1186
1187 if (MediaId != Instance->Media.MediaId) {
1188 return EFI_MEDIA_CHANGED;
1189 }
1190
1191 BlockSize = Instance->Media.BlockSize;
1192 Lba = (EFI_LBA) DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
1193
1194 RemainingBytes = BufferSize;
1195
1196 // Write either all the remaining bytes, or the number of bytes that bring
1197 // us up to a block boundary, whichever is less.
1198 // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next
1199 // block boundary (even if it is already on one).
1200 WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset);
1201
1202 do {
1203 if (WriteSize == BlockSize) {
1204 // Write a full block
1205 Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32));
1206 } else {
1207 // Write a partial block
1208 Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer);
1209 }
1210 if (EFI_ERROR (Status)) {
1211 return Status;
1212 }
1213 // Now continue writing either all the remaining bytes or single blocks.
1214 RemainingBytes -= WriteSize;
1215 Buffer = (UINT8 *) Buffer + WriteSize;
1216 Lba++;
1217 BlockOffset = 0;
1218 WriteSize = MIN (RemainingBytes, BlockSize);
1219 } while (RemainingBytes);
1220
1221 return Status;
1222 }
1223
1224 EFI_STATUS
1225 NorFlashReset (
1226 IN NOR_FLASH_INSTANCE *Instance
1227 )
1228 {
1229 // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
1230 SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
1231 return EFI_SUCCESS;
1232 }
1233
1234 /**
1235 Fixup internal data so that EFI can be call in virtual mode.
1236 Call the passed in Child Notify event and convert any pointers in
1237 lib to virtual mode.
1238
1239 @param[in] Event The Event that is being processed
1240 @param[in] Context Event Context
1241 **/
1242 VOID
1243 EFIAPI
1244 NorFlashVirtualNotifyEvent (
1245 IN EFI_EVENT Event,
1246 IN VOID *Context
1247 )
1248 {
1249 UINTN Index;
1250
1251 for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
1252 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->DeviceBaseAddress);
1253 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->RegionBaseAddress);
1254
1255 // Convert BlockIo protocol
1256 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks);
1257 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks);
1258 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.Reset);
1259 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks);
1260
1261 // Convert Fvb
1262 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks);
1263 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes);
1264 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize);
1265 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress);
1266 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.Read);
1267 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes);
1268 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.Write);
1269
1270 if (mNorFlashInstances[Index]->ShadowBuffer != NULL) {
1271 EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->ShadowBuffer);
1272 }
1273 }
1274
1275 return;
1276 }
1277
1278 EFI_STATUS
1279 EFIAPI
1280 NorFlashInitialise (
1281 IN EFI_HANDLE ImageHandle,
1282 IN EFI_SYSTEM_TABLE *SystemTable
1283 )
1284 {
1285 EFI_STATUS Status;
1286 UINT32 Index;
1287 NOR_FLASH_DESCRIPTION* NorFlashDevices;
1288 BOOLEAN ContainVariableStorage;
1289
1290 Status = NorFlashPlatformInitialization ();
1291 if (EFI_ERROR(Status)) {
1292 DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to initialize Nor Flash devices\n"));
1293 return Status;
1294 }
1295
1296 Status = NorFlashPlatformGetDevices (&NorFlashDevices, &mNorFlashDeviceCount);
1297 if (EFI_ERROR(Status)) {
1298 DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to get Nor Flash devices\n"));
1299 return Status;
1300 }
1301
1302 mNorFlashInstances = AllocateRuntimePool (sizeof(NOR_FLASH_INSTANCE*) * mNorFlashDeviceCount);
1303
1304 for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
1305 // Check if this NOR Flash device contain the variable storage region
1306 ContainVariableStorage =
1307 (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) &&
1308 (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size);
1309
1310 Status = NorFlashCreateInstance (
1311 NorFlashDevices[Index].DeviceBaseAddress,
1312 NorFlashDevices[Index].RegionBaseAddress,
1313 NorFlashDevices[Index].Size,
1314 Index,
1315 NorFlashDevices[Index].BlockSize,
1316 ContainVariableStorage,
1317 &NorFlashDevices[Index].Guid,
1318 &mNorFlashInstances[Index]
1319 );
1320 if (EFI_ERROR(Status)) {
1321 DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to create instance for NorFlash[%d]\n",Index));
1322 }
1323 }
1324
1325 //
1326 // Register for the virtual address change event
1327 //
1328 Status = gBS->CreateEventEx (
1329 EVT_NOTIFY_SIGNAL,
1330 TPL_NOTIFY,
1331 NorFlashVirtualNotifyEvent,
1332 NULL,
1333 &gEfiEventVirtualAddressChangeGuid,
1334 &mNorFlashVirtualAddrChangeEvent
1335 );
1336 ASSERT_EFI_ERROR (Status);
1337
1338 return Status;
1339 }