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