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