public inbox for devel@edk2.groups.io
 help / color / mirror / Atom feed
* [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library
@ 2024-05-29  8:55 Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 01/17] Platform/ARM/NorFlashDxe: Move DiskIo related functions out of NorFlash.c Sahil Kaushal
                   ` (18 more replies)
  0 siblings, 19 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch series adds the following changes:

1. Splits the NorFlashDxe driver to introduce a NorFlashDeviceLib that
implements the specifics for the respective flash. This will allow us
to plug different libraries implementing functionality of various NOR
Flash. The flash specific code in NorFlashDxe has been moved to
P30NorFlashDeviceLib library.

2. Adds support for CadenceQspiNorFlashDeviceLib which is used by N1Sdp
platform along with NorFlashDxe driver. N1Sdp uses an emulated variable
storage on DDR memory for the variable storage. But this emulated
variable storage is a volatile memory and so the values of variables
can't persist on next reboot or in power cycle. In N1Sdp platform, the
SoC is connected to IOFPGA which has a Cadence Quad SPI (QSPI)
controller. This QSPI controller manages the flash chip device via QSPI
bus. With these changes we use this NOR flash device for persistent
variable storage.

3. Fixes memory leak in NorFlashCreateInstance() function.

v4:
  - Fixed code review comments

v3:
  - Fixed code review comments
  - Added 3 new patches for the following:
    - Fix memory leak in NorFlashCreateInstance()
    - Make local functions STATIC in NorFlashDxe
    - Remove unimplemented functions from NorFlash.h

v2:
  - Fixed code review comments
  - Split the NorFlashDxe driver and moved flash specific code to
    P30NorFlashDeviceLib
  - Added NOR flash Dxe Driver for N1Sdp as a library instead of a
    driver

Link to branch with the patches in this series -
https://github.com/sah01Kaushal/edk2-platforms/tree/n1sdp_persistent_storage_v4

Links to v3:
https://edk2.groups.io/g/devel/message/119142
https://edk2.groups.io/g/devel/message/119143
https://edk2.groups.io/g/devel/message/119144
https://edk2.groups.io/g/devel/message/119145
https://edk2.groups.io/g/devel/message/119146
https://edk2.groups.io/g/devel/message/119147
https://edk2.groups.io/g/devel/message/119148
https://edk2.groups.io/g/devel/message/119149
https://edk2.groups.io/g/devel/message/119150
https://edk2.groups.io/g/devel/message/119151
https://edk2.groups.io/g/devel/message/119152
https://edk2.groups.io/g/devel/message/119153
https://edk2.groups.io/g/devel/message/119154
https://edk2.groups.io/g/devel/message/119155
https://edk2.groups.io/g/devel/message/119156
https://edk2.groups.io/g/devel/message/119157
https://edk2.groups.io/g/devel/message/119158
https://edk2.groups.io/g/devel/message/119159

https://github.com/sah01Kaushal/edk2-platforms/tree/n1sdp_persistent_storage_v3

Links to v2:
https://edk2.groups.io/g/devel/topic/105690949
https://edk2.groups.io/g/devel/topic/105690948
https://edk2.groups.io/g/devel/topic/105690947
https://edk2.groups.io/g/devel/topic/105690946
https://edk2.groups.io/g/devel/topic/105690945
https://edk2.groups.io/g/devel/topic/105690944
https://edk2.groups.io/g/devel/topic/105690943
https://edk2.groups.io/g/devel/topic/105690942
https://edk2.groups.io/g/devel/topic/105690941
https://edk2.groups.io/g/devel/topic/105690940
https://edk2.groups.io/g/devel/topic/105690939
https://edk2.groups.io/g/devel/topic/105690938
https://edk2.groups.io/g/devel/topic/105690937
https://edk2.groups.io/g/devel/topic/105690936
https://edk2.groups.io/g/devel/topic/105690935

https://github.com/sah01Kaushal/edk2-platforms/tree/n1sdp_persistent_storage_v2

Links to v1:
https://edk2.groups.io/g/devel/topic/102625035
https://edk2.groups.io/g/devel/topic/102625033
https://edk2.groups.io/g/devel/topic/102625034
https://edk2.groups.io/g/devel/topic/102625036
https://edk2.groups.io/g/devel/topic/102625037
https://edk2.groups.io/g/devel/topic/102625038

sahil (17):
  Platform/ARM/NorFlashDxe: Move DiskIo related functions out of
    NorFlash.c
  Platform/ARM/NorFlashDxe: Move NorFlashVirtualNotifyEvent
  Platform/ARM/NorFlashDxe: Add NorFlashCommon.h header file
  Platform/ARM/NorFlashDxe: Move flash specific functions to NorFlash.c
  Platform/ARM/NorFlashDxe: Remove unimplemented functions from
    NorFlash.h
  Platform/ARM/NorFlashDxe: Make local functions STATIC
  Platform/ARM: Create NorFlashDeviceLib library interface for flash
    specific functions
  Platform/ARM: Add P30NorFlashDeviceLib Library
  Platform/ARM/NorFlashDxe: Switch from NorFlash.c to NorFlashDeviceLib
  Platform/ARM: Add HostControllerBaseAddress variable
  Platform/ARM/NorFlashDxe: Fix memory leak in NorFlashCreateInstance()
  Platform/ARM: Add optional provision to fetch and print NOR Flash info
  Silicon/ARM/NeoverseN1Soc: Enable SCP QSPI flash region
  Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp
  Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
  Platform/ARM/N1Sdp: Persistent storage for N1Sdp
  Platform/ARM/N1Sdp: Enable FaultTolerantWrite Dxe driver for N1Sdp

 Platform/ARM/ARM.dec                                                                                 |    4 +
 Platform/ARM/SgiPkg/SgiPlatform.dsc.inc                                                              |    3 +
 Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc                                                            |    3 +
 Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc                                                         |    3 +
 Platform/ARM/JunoPkg/ArmJuno.dsc                                                                     |    3 +
 Platform/ARM/N1Sdp/N1SdpPlatform.dsc                                                                 |   24 +-
 Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc                                                    |    3 +
 Platform/ARM/N1Sdp/N1SdpPlatform.fdf                                                                 |    3 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf                                                     |    8 +-
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf                                            |    8 +-
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf                   |   32 +
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf                                   |   35 +
 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf                                        |   35 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h                                                          |  422 --------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h                                                    |  209 ++++
 Platform/ARM/Include/Library/NorFlashDeviceLib.h                                                     |  256 +++++
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h                     |   46 +
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h                                     |   98 ++
 Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h                                                    |    8 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c                                                |  131 ++-
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c                                                       |  301 +++---
 Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c                                                       |    2 +-
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c                                              |  194 ++--
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c                     | 1034 ++++++++++++++++++++
 Platform/ARM/{Drivers/NorFlashDxe/NorFlash.c => Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c} |  306 +++---
 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c                                          |   80 ++
 Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c                                       |    8 +-
 27 files changed, 2365 insertions(+), 894 deletions(-)
 create mode 100644 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
 create mode 100644 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
 create mode 100644 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
 delete mode 100644 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
 create mode 100644 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
 create mode 100644 Platform/ARM/Include/Library/NorFlashDeviceLib.h
 create mode 100644 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
 create mode 100644 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h
 create mode 100644 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
 rename Platform/ARM/{Drivers/NorFlashDxe/NorFlash.c => Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c} (77%)
 create mode 100644 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c

-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119315): https://edk2.groups.io/g/devel/message/119315
Mute This Topic: https://groups.io/mt/106365450/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 01/17] Platform/ARM/NorFlashDxe: Move DiskIo related functions out of NorFlash.c
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 02/17] Platform/ARM/NorFlashDxe: Move NorFlashVirtualNotifyEvent Sahil Kaushal
                   ` (17 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Moving these functions from NorFlash.c to NorFlashBlockIoDxe.c as
they are not dependent on any particular flash implementation.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c           | 129 --------------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c | 129 ++++++++++++++++++++
 2 files changed, 129 insertions(+), 129 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
index 1b431073ee93..60854ef2a7d0 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
@@ -807,135 +807,6 @@ NorFlashWriteSingleBlock (
   return EFI_SUCCESS;
 }
 
-/*
-  Although DiskIoDxe will automatically install the DiskIO protocol whenever
-  we install the BlockIO protocol, its implementation is sub-optimal as it reads
-  and writes entire blocks using the BlockIO protocol. In fact we can access
-  NOR flash with a finer granularity than that, so we can improve performance
-  by directly producing the DiskIO protocol.
-*/
-
-/**
-  Read BufferSize bytes from Offset into Buffer.
-
-  @param  This                  Protocol instance pointer.
-  @param  MediaId               Id of the media, changes every time the media is replaced.
-  @param  Offset                The starting byte offset to read from
-  @param  BufferSize            Size of Buffer
-  @param  Buffer                Buffer containing read data
-
-  @retval EFI_SUCCESS           The data was read correctly from the device.
-  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
-  @retval EFI_NO_MEDIA          There is no media in the device.
-  @retval EFI_MEDIA_CHANGED     The MediaId does not match the current device.
-  @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not
-                                valid for the device.
-
-**/
-EFI_STATUS
-EFIAPI
-NorFlashDiskIoReadDisk (
-  IN EFI_DISK_IO_PROTOCOL  *This,
-  IN UINT32                MediaId,
-  IN UINT64                DiskOffset,
-  IN UINTN                 BufferSize,
-  OUT VOID                 *Buffer
-  )
-{
-  NOR_FLASH_INSTANCE  *Instance;
-  UINT32              BlockSize;
-  UINT32              BlockOffset;
-  EFI_LBA             Lba;
-
-  Instance = INSTANCE_FROM_DISKIO_THIS (This);
-
-  if (MediaId != Instance->Media.MediaId) {
-    return EFI_MEDIA_CHANGED;
-  }
-
-  BlockSize = Instance->Media.BlockSize;
-  Lba       = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
-
-  return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer);
-}
-
-/**
-  Writes a specified number of bytes to a device.
-
-  @param  This       Indicates a pointer to the calling context.
-  @param  MediaId    ID of the medium to be written.
-  @param  Offset     The starting byte offset on the logical block I/O device to write.
-  @param  BufferSize The size in bytes of Buffer. The number of bytes to write to the device.
-  @param  Buffer     A pointer to the buffer containing the data to be written.
-
-  @retval EFI_SUCCESS           The data was written correctly to the device.
-  @retval EFI_WRITE_PROTECTED   The device can not be written to.
-  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
-  @retval EFI_NO_MEDIA          There is no media in the device.
-  @retval EFI_MEDIA_CHANGED     The MediaId does not match the current device.
-  @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not
-                                 valid for the device.
-
-**/
-EFI_STATUS
-EFIAPI
-NorFlashDiskIoWriteDisk (
-  IN EFI_DISK_IO_PROTOCOL  *This,
-  IN UINT32                MediaId,
-  IN UINT64                DiskOffset,
-  IN UINTN                 BufferSize,
-  IN VOID                  *Buffer
-  )
-{
-  NOR_FLASH_INSTANCE  *Instance;
-  UINT32              BlockSize;
-  UINT32              BlockOffset;
-  EFI_LBA             Lba;
-  UINTN               RemainingBytes;
-  UINTN               WriteSize;
-  EFI_STATUS          Status;
-
-  Instance = INSTANCE_FROM_DISKIO_THIS (This);
-
-  if (MediaId != Instance->Media.MediaId) {
-    return EFI_MEDIA_CHANGED;
-  }
-
-  BlockSize = Instance->Media.BlockSize;
-  Lba       = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
-
-  RemainingBytes = BufferSize;
-
-  // Write either all the remaining bytes, or the number of bytes that bring
-  // us up to a block boundary, whichever is less.
-  // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next
-  // block boundary (even if it is already on one).
-  WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset);
-
-  do {
-    if (WriteSize == BlockSize) {
-      // Write a full block
-      Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32));
-    } else {
-      // Write a partial block
-      Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer);
-    }
-
-    if (EFI_ERROR (Status)) {
-      return Status;
-    }
-
-    // Now continue writing either all the remaining bytes or single blocks.
-    RemainingBytes -= WriteSize;
-    Buffer          = (UINT8 *)Buffer + WriteSize;
-    Lba++;
-    BlockOffset = 0;
-    WriteSize   = MIN (RemainingBytes, BlockSize);
-  } while (RemainingBytes);
-
-  return Status;
-}
-
 EFI_STATUS
 NorFlashReset (
   IN  NOR_FLASH_INSTANCE  *Instance
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
index 9d4732c6905a..9b8c76a171d4 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
@@ -121,3 +121,132 @@ NorFlashBlockIoFlushBlocks (
   // Nothing to do so just return without error
   return EFI_SUCCESS;
 }
+
+/*
+  Although DiskIoDxe will automatically install the DiskIO protocol whenever
+  we install the BlockIO protocol, its implementation is sub-optimal as it reads
+  and writes entire blocks using the BlockIO protocol. In fact we can access
+  NOR flash with a finer granularity than that, so we can improve performance
+  by directly producing the DiskIO protocol.
+*/
+
+/**
+  Read BufferSize bytes from Offset into Buffer.
+
+  @param  This                  Protocol instance pointer.
+  @param  MediaId               Id of the media, changes every time the media is replaced.
+  @param  Offset                The starting byte offset to read from
+  @param  BufferSize            Size of Buffer
+  @param  Buffer                Buffer containing read data
+
+  @retval EFI_SUCCESS           The data was read correctly from the device.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the read.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not match the current device.
+  @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not
+                                valid for the device.
+
+**/
+EFI_STATUS
+EFIAPI
+NorFlashDiskIoReadDisk (
+  IN EFI_DISK_IO_PROTOCOL  *This,
+  IN UINT32                MediaId,
+  IN UINT64                DiskOffset,
+  IN UINTN                 BufferSize,
+  OUT VOID                 *Buffer
+  )
+{
+  NOR_FLASH_INSTANCE  *Instance;
+  UINT32              BlockSize;
+  UINT32              BlockOffset;
+  EFI_LBA             Lba;
+
+  Instance = INSTANCE_FROM_DISKIO_THIS (This);
+
+  if (MediaId != Instance->Media.MediaId) {
+    return EFI_MEDIA_CHANGED;
+  }
+
+  BlockSize = Instance->Media.BlockSize;
+  Lba       = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
+
+  return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer);
+}
+
+/**
+  Writes a specified number of bytes to a device.
+
+  @param  This       Indicates a pointer to the calling context.
+  @param  MediaId    ID of the medium to be written.
+  @param  Offset     The starting byte offset on the logical block I/O device to write.
+  @param  BufferSize The size in bytes of Buffer. The number of bytes to write to the device.
+  @param  Buffer     A pointer to the buffer containing the data to be written.
+
+  @retval EFI_SUCCESS           The data was written correctly to the device.
+  @retval EFI_WRITE_PROTECTED   The device can not be written to.
+  @retval EFI_DEVICE_ERROR      The device reported an error while performing the write.
+  @retval EFI_NO_MEDIA          There is no media in the device.
+  @retval EFI_MEDIA_CHANGED     The MediaId does not match the current device.
+  @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not
+                                 valid for the device.
+
+**/
+EFI_STATUS
+EFIAPI
+NorFlashDiskIoWriteDisk (
+  IN EFI_DISK_IO_PROTOCOL  *This,
+  IN UINT32                MediaId,
+  IN UINT64                DiskOffset,
+  IN UINTN                 BufferSize,
+  IN VOID                  *Buffer
+  )
+{
+  NOR_FLASH_INSTANCE  *Instance;
+  UINT32              BlockSize;
+  UINT32              BlockOffset;
+  EFI_LBA             Lba;
+  UINTN               RemainingBytes;
+  UINTN               WriteSize;
+  EFI_STATUS          Status;
+
+  Instance = INSTANCE_FROM_DISKIO_THIS (This);
+
+  if (MediaId != Instance->Media.MediaId) {
+    return EFI_MEDIA_CHANGED;
+  }
+
+  BlockSize = Instance->Media.BlockSize;
+  Lba       = (EFI_LBA)DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
+
+  RemainingBytes = BufferSize;
+
+  // Write either all the remaining bytes, or the number of bytes that bring
+  // us up to a block boundary, whichever is less.
+  // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next
+  // block boundary (even if it is already on one).
+  WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset);
+
+  do {
+    if (WriteSize == BlockSize) {
+      // Write a full block
+      Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32));
+    } else {
+      // Write a partial block
+      Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer);
+    }
+
+    if (EFI_ERROR (Status)) {
+      return Status;
+    }
+
+    // Now continue writing either all the remaining bytes or single blocks.
+    RemainingBytes -= WriteSize;
+    Buffer          = (UINT8 *)Buffer + WriteSize;
+    Lba++;
+    BlockOffset = 0;
+    WriteSize   = MIN (RemainingBytes, BlockSize);
+  } while (RemainingBytes);
+
+  return Status;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119316): https://edk2.groups.io/g/devel/message/119316
Mute This Topic: https://groups.io/mt/106365451/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 02/17] Platform/ARM/NorFlashDxe: Move NorFlashVirtualNotifyEvent
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 01/17] Platform/ARM/NorFlashDxe: Move DiskIo related functions out of NorFlash.c Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 03/17] Platform/ARM/NorFlashDxe: Add NorFlashCommon.h header file Sahil Kaushal
                   ` (16 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Moving this function from NorFlash.c to NorFlashDxe.c as it is not
dependent on any particular flash implementation.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h    | 14 +++----
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c    | 44 --------------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c | 44 ++++++++++++++++++++
 3 files changed, 51 insertions(+), 51 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index c83032e87d9c..d4d97bd22cc5 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -342,6 +342,13 @@ NorFlashFvbInitialize (
   IN NOR_FLASH_INSTANCE  *Instance
   );
 
+VOID
+EFIAPI
+NorFlashVirtualNotifyEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  );
+
 //
 // NorFlash.c
 //
@@ -412,11 +419,4 @@ NorFlashWriteSingleWord (
   IN UINT32              WriteData
   );
 
-VOID
-EFIAPI
-NorFlashVirtualNotifyEvent (
-  IN EFI_EVENT  Event,
-  IN VOID       *Context
-  );
-
 #endif /* __NOR_FLASH_H__ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
index 60854ef2a7d0..55f6abd0eef3 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
@@ -816,47 +816,3 @@ NorFlashReset (
   SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
   return EFI_SUCCESS;
 }
-
-/**
-  Fixup internal data so that EFI can be call in virtual mode.
-  Call the passed in Child Notify event and convert any pointers in
-  lib to virtual mode.
-
-  @param[in]    Event   The Event that is being processed
-  @param[in]    Context Event Context
-**/
-VOID
-EFIAPI
-NorFlashVirtualNotifyEvent (
-  IN EFI_EVENT  Event,
-  IN VOID       *Context
-  )
-{
-  UINTN  Index;
-
-  for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress);
-
-    // Convert BlockIo protocol
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.Reset);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks);
-
-    // Convert Fvb
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Read);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes);
-    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Write);
-
-    if (mNorFlashInstances[Index]->ShadowBuffer != NULL) {
-      EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->ShadowBuffer);
-    }
-  }
-
-  return;
-}
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index f7b92de21a57..963af7dcf435 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -504,3 +504,47 @@ NorFlashFvbInitialize (
 
   return Status;
 }
+
+/**
+  Fixup internal data so that EFI can be call in virtual mode.
+  Call the passed in Child Notify event and convert any pointers in
+  lib to virtual mode.
+
+  @param[in]    Event   The Event that is being processed
+  @param[in]    Context Event Context
+**/
+VOID
+EFIAPI
+NorFlashVirtualNotifyEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  )
+{
+  UINTN  Index;
+
+  for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress);
+
+    // Convert BlockIo protocol
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.Reset);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks);
+
+    // Convert Fvb
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Read);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes);
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->FvbProtocol.Write);
+
+    if (mNorFlashInstances[Index]->ShadowBuffer != NULL) {
+      EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->ShadowBuffer);
+    }
+  }
+
+  return;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119317): https://edk2.groups.io/g/devel/message/119317
Mute This Topic: https://groups.io/mt/106365452/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 03/17] Platform/ARM/NorFlashDxe: Add NorFlashCommon.h header file
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 01/17] Platform/ARM/NorFlashDxe: Move DiskIo related functions out of NorFlash.c Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 02/17] Platform/ARM/NorFlashDxe: Move NorFlashVirtualNotifyEvent Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 04/17] Platform/ARM/NorFlashDxe: Move flash specific functions to NorFlash.c Sahil Kaushal
                   ` (15 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch splits NorFlash.h and adds NorFlashCommon.h which
will have all the flash independent functions and macros.
Whereas all the flash specific functions will be in NorFlash.h
header file.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf          |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h               | 199 ------------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h         | 221 ++++++++++++++++++++
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c               |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c     |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c            |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c            |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c   |   1 +
 9 files changed, 228 insertions(+), 199 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
index cdf1f5c27f35..18e99bac8888 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
@@ -21,6 +21,7 @@ [Sources.common]
   NorFlash.h
   NorFlashBlockIoDxe.c
   NorFlashDxe.c
+  NorFlashCommon.h
   NorFlashFvb.c
 
 [Packages]
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
index 001f281220f2..69c40ccf9c27 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
@@ -22,6 +22,7 @@ [Sources.common]
   NorFlash.c
   NorFlash.h
   NorFlashFvb.c
+  NorFlashCommon.h
   NorFlashStandaloneMm.c
 
 [Packages]
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index d4d97bd22cc5..e0ebb1e2fd35 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -20,9 +20,6 @@
 
 #include <Library/DebugLib.h>
 #include <Library/IoLib.h>
-#include <Library/NorFlashPlatformLib.h>
-#include <Library/UefiLib.h>
-#include <Library/UefiRuntimeLib.h>
 
 #define NOR_FLASH_ERASE_RETRY  10
 
@@ -108,11 +105,6 @@
 #define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP  0x0060
 #define P30_CMD_READ_CONFIGURATION_REGISTER        0x0003
 
-#define NOR_FLASH_SIGNATURE  SIGNATURE_32('n', 'o', 'r', '0')
-#define INSTANCE_FROM_FVB_THIS(a)     CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE)
-#define INSTANCE_FROM_BLKIO_THIS(a)   CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE)
-#define INSTANCE_FROM_DISKIO_THIS(a)  CR(a, NOR_FLASH_INSTANCE, DiskIoProtocol, NOR_FLASH_SIGNATURE)
-
 typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE;
 
 #pragma pack (1)
@@ -158,197 +150,6 @@ NorFlashWriteBuffer (
   IN UINT32              *Buffer
   );
 
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReset (
-  IN EFI_BLOCK_IO_PROTOCOL  *This,
-  IN BOOLEAN                ExtendedVerification
-  );
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoReadBlocks (
-  IN  EFI_BLOCK_IO_PROTOCOL  *This,
-  IN  UINT32                 MediaId,
-  IN  EFI_LBA                Lba,
-  IN  UINTN                  BufferSizeInBytes,
-  OUT VOID                   *Buffer
-  );
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoWriteBlocks (
-  IN  EFI_BLOCK_IO_PROTOCOL  *This,
-  IN  UINT32                 MediaId,
-  IN  EFI_LBA                Lba,
-  IN  UINTN                  BufferSizeInBytes,
-  IN  VOID                   *Buffer
-  );
-
-//
-// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
-//
-EFI_STATUS
-EFIAPI
-NorFlashBlockIoFlushBlocks (
-  IN EFI_BLOCK_IO_PROTOCOL  *This
-  );
-
-//
-// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.ReadDisk
-//
-EFI_STATUS
-EFIAPI
-NorFlashDiskIoReadDisk (
-  IN EFI_DISK_IO_PROTOCOL  *This,
-  IN UINT32                MediaId,
-  IN UINT64                Offset,
-  IN UINTN                 BufferSize,
-  OUT VOID                 *Buffer
-  );
-
-//
-// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.WriteDisk
-//
-EFI_STATUS
-EFIAPI
-NorFlashDiskIoWriteDisk (
-  IN EFI_DISK_IO_PROTOCOL  *This,
-  IN UINT32                MediaId,
-  IN UINT64                Offset,
-  IN UINTN                 BufferSize,
-  IN VOID                  *Buffer
-  );
-
-//
-// NorFlashFvbDxe.c
-//
-
-EFI_STATUS
-EFIAPI
-FvbGetAttributes (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  OUT       EFI_FVB_ATTRIBUTES_2                 *Attributes
-  );
-
-EFI_STATUS
-EFIAPI
-FvbSetAttributes (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  IN OUT    EFI_FVB_ATTRIBUTES_2                 *Attributes
-  );
-
-EFI_STATUS
-EFIAPI
-FvbGetPhysicalAddress (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  OUT       EFI_PHYSICAL_ADDRESS                 *Address
-  );
-
-EFI_STATUS
-EFIAPI
-FvbGetBlockSize (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  IN        EFI_LBA                              Lba,
-  OUT       UINTN                                *BlockSize,
-  OUT       UINTN                                *NumberOfBlocks
-  );
-
-EFI_STATUS
-EFIAPI
-FvbRead (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  IN        EFI_LBA                              Lba,
-  IN        UINTN                                Offset,
-  IN OUT    UINTN                                *NumBytes,
-  IN OUT    UINT8                                *Buffer
-  );
-
-EFI_STATUS
-EFIAPI
-FvbWrite (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  IN        EFI_LBA                              Lba,
-  IN        UINTN                                Offset,
-  IN OUT    UINTN                                *NumBytes,
-  IN        UINT8                                *Buffer
-  );
-
-EFI_STATUS
-EFIAPI
-FvbEraseBlocks (
-  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
-  ...
-  );
-
-EFI_STATUS
-ValidateFvHeader (
-  IN  NOR_FLASH_INSTANCE  *Instance
-  );
-
-EFI_STATUS
-InitializeFvAndVariableStoreHeaders (
-  IN NOR_FLASH_INSTANCE  *Instance
-  );
-
-VOID
-EFIAPI
-FvbVirtualNotifyEvent (
-  IN EFI_EVENT  Event,
-  IN VOID       *Context
-  );
-
-//
-// NorFlashDxe.c
-//
-
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  );
-
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  );
-
-EFI_STATUS
-NorFlashCreateInstance (
-  IN UINTN                NorFlashDeviceBase,
-  IN UINTN                NorFlashRegionBase,
-  IN UINTN                NorFlashSize,
-  IN UINT32               Index,
-  IN UINT32               BlockSize,
-  IN BOOLEAN              SupportFvb,
-  OUT NOR_FLASH_INSTANCE  **NorFlashInstance
-  );
-
-EFI_STATUS
-EFIAPI
-NorFlashFvbInitialize (
-  IN NOR_FLASH_INSTANCE  *Instance
-  );
-
-VOID
-EFIAPI
-NorFlashVirtualNotifyEvent (
-  IN EFI_EVENT  Event,
-  IN VOID       *Context
-  );
-
 //
 // NorFlash.c
 //
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
new file mode 100644
index 000000000000..e329e0727617
--- /dev/null
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
@@ -0,0 +1,221 @@
+/** @file
+
+ Copyright (c) 2011-2024, Arm Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef NOR_FLASH_COMMON_H_
+#define NOR_FLASH_COMMON_H_
+
+#include <Base.h>
+#include <PiDxe.h>
+
+#include <Guid/EventGroup.h>
+
+#include <Protocol/BlockIo.h>
+#include <Protocol/DiskIo.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+
+#include <Library/DebugLib.h>
+#include <Library/NorFlashPlatformLib.h>
+#include <Library/UefiLib.h>
+#include <Library/UefiRuntimeLib.h>
+
+#define NOR_FLASH_SIGNATURE  SIGNATURE_32('n', 'o', 'r', '0')
+#define INSTANCE_FROM_FVB_THIS(a)     CR(a, NOR_FLASH_INSTANCE, FvbProtocol, NOR_FLASH_SIGNATURE)
+#define INSTANCE_FROM_BLKIO_THIS(a)   CR(a, NOR_FLASH_INSTANCE, BlockIoProtocol, NOR_FLASH_SIGNATURE)
+#define INSTANCE_FROM_DISKIO_THIS(a)  CR(a, NOR_FLASH_INSTANCE, DiskIoProtocol, NOR_FLASH_SIGNATURE)
+
+//
+// NorFlashDxe.c
+//
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  );
+
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  );
+
+EFI_STATUS
+NorFlashCreateInstance (
+  IN UINTN                NorFlashDeviceBase,
+  IN UINTN                NorFlashRegionBase,
+  IN UINTN                NorFlashSize,
+  IN UINT32               Index,
+  IN UINT32               BlockSize,
+  IN BOOLEAN              SupportFvb,
+  OUT NOR_FLASH_INSTANCE  **NorFlashInstance
+  );
+
+EFI_STATUS
+EFIAPI
+NorFlashFvbInitialize (
+  IN NOR_FLASH_INSTANCE  *Instance
+  );
+
+VOID
+EFIAPI
+NorFlashVirtualNotifyEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReset (
+  IN EFI_BLOCK_IO_PROTOCOL  *This,
+  IN BOOLEAN                ExtendedVerification
+  );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.ReadBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoReadBlocks (
+  IN  EFI_BLOCK_IO_PROTOCOL  *This,
+  IN  UINT32                 MediaId,
+  IN  EFI_LBA                Lba,
+  IN  UINTN                  BufferSizeInBytes,
+  OUT VOID                   *Buffer
+  );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.WriteBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoWriteBlocks (
+  IN  EFI_BLOCK_IO_PROTOCOL  *This,
+  IN  UINT32                 MediaId,
+  IN  EFI_LBA                Lba,
+  IN  UINTN                  BufferSizeInBytes,
+  IN  VOID                   *Buffer
+  );
+
+//
+// BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.FlushBlocks
+//
+EFI_STATUS
+EFIAPI
+NorFlashBlockIoFlushBlocks (
+  IN EFI_BLOCK_IO_PROTOCOL  *This
+  );
+
+//
+// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.ReadDisk
+//
+EFI_STATUS
+EFIAPI
+NorFlashDiskIoReadDisk (
+  IN EFI_DISK_IO_PROTOCOL  *This,
+  IN UINT32                MediaId,
+  IN UINT64                Offset,
+  IN UINTN                 BufferSize,
+  OUT VOID                 *Buffer
+  );
+
+//
+// DiskIO Protocol function EFI_DISK_IO_PROTOCOL.WriteDisk
+//
+EFI_STATUS
+EFIAPI
+NorFlashDiskIoWriteDisk (
+  IN EFI_DISK_IO_PROTOCOL  *This,
+  IN UINT32                MediaId,
+  IN UINT64                Offset,
+  IN UINTN                 BufferSize,
+  IN VOID                  *Buffer
+  );
+
+//
+// NorFlashFvbDxe.c
+//
+
+EFI_STATUS
+EFIAPI
+FvbGetAttributes (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  OUT       EFI_FVB_ATTRIBUTES_2                 *Attributes
+  );
+
+EFI_STATUS
+EFIAPI
+FvbSetAttributes (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  IN OUT    EFI_FVB_ATTRIBUTES_2                 *Attributes
+  );
+
+EFI_STATUS
+EFIAPI
+FvbGetPhysicalAddress (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  OUT       EFI_PHYSICAL_ADDRESS                 *Address
+  );
+
+EFI_STATUS
+EFIAPI
+FvbGetBlockSize (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  IN        EFI_LBA                              Lba,
+  OUT       UINTN                                *BlockSize,
+  OUT       UINTN                                *NumberOfBlocks
+  );
+
+EFI_STATUS
+EFIAPI
+FvbRead (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  IN        EFI_LBA                              Lba,
+  IN        UINTN                                Offset,
+  IN OUT    UINTN                                *NumBytes,
+  IN OUT    UINT8                                *Buffer
+  );
+
+EFI_STATUS
+EFIAPI
+FvbWrite (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  IN        EFI_LBA                              Lba,
+  IN        UINTN                                Offset,
+  IN OUT    UINTN                                *NumBytes,
+  IN        UINT8                                *Buffer
+  );
+
+EFI_STATUS
+EFIAPI
+FvbEraseBlocks (
+  IN CONST  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL  *This,
+  ...
+  );
+
+EFI_STATUS
+ValidateFvHeader (
+  IN  NOR_FLASH_INSTANCE  *Instance
+  );
+
+EFI_STATUS
+InitializeFvAndVariableStoreHeaders (
+  IN NOR_FLASH_INSTANCE  *Instance
+  );
+
+VOID
+EFIAPI
+FvbVirtualNotifyEvent (
+  IN EFI_EVENT  Event,
+  IN VOID       *Context
+  );
+
+#endif /* NOR_FLASH_COMMON_H_ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
index 55f6abd0eef3..4e5a97c83c7b 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
@@ -10,6 +10,7 @@
 #include <Library/BaseMemoryLib.h>
 
 #include "NorFlash.h"
+#include "NorFlashCommon.h"
 
 //
 // Global variable declarations
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
index 9b8c76a171d4..a6c73312c596 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
@@ -10,6 +10,7 @@
 #include <Library/UefiBootServicesTableLib.h>
 
 #include "NorFlash.h"
+#include "NorFlashCommon.h"
 
 //
 // BlockIO Protocol function EFI_BLOCK_IO_PROTOCOL.Reset
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index 963af7dcf435..b1e01169c24e 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -15,6 +15,7 @@
 #include <Library/DxeServicesTableLib.h>
 
 #include "NorFlash.h"
+#include "NorFlashCommon.h"
 
 STATIC EFI_EVENT  mNorFlashVirtualAddrChangeEvent;
 
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
index 0767581308d2..f9f2856e0c81 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
@@ -19,6 +19,7 @@
 #include <Guid/NvVarStoreFormatted.h>
 
 #include "NorFlash.h"
+#include "NorFlashCommon.h"
 
 extern UINTN  mFlashNvStorageVariableBase;
 ///
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index b72ad97b0b55..f2919265139b 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -12,6 +12,7 @@
 #include <Library/MmServicesTableLib.h>
 
 #include "NorFlash.h"
+#include "NorFlashCommon.h"
 
 //
 // Global variable declarations
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119318): https://edk2.groups.io/g/devel/message/119318
Mute This Topic: https://groups.io/mt/106365453/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 04/17] Platform/ARM/NorFlashDxe: Move flash specific functions to NorFlash.c
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (2 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 03/17] Platform/ARM/NorFlashDxe: Add NorFlashCommon.h header file Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 05/17] Platform/ARM/NorFlashDxe: Remove unimplemented functions from NorFlash.h Sahil Kaushal
                   ` (14 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Refactoring done in this patch has two major parts:

1. Moving out NorFlashUnlockAndEraseSingleBlock and
NorFlashWriteFullBlock functions from NorFlashDxe.c and
NorFlashStandaloneMm.c to NorFlash.c files.

2. At the same time, we are adding NorFlashLock and NorFlashUnlock
functions which will take care of TPL related operations needed by
functions mentioned in point 1. These functions are implemented
in NorFlashDxe.c but are just dummy placeholder functions in
NorFlashStandaloneMm.c file.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h             |  26 +++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h       |  14 --
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c             | 136 +++++++++++++-
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c          | 193 ++++----------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c | 151 +++------------
 5 files changed, 225 insertions(+), 295 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index e0ebb1e2fd35..bd5c6a949cf0 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -220,4 +220,30 @@ NorFlashWriteSingleWord (
   IN UINT32              WriteData
   );
 
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  );
+
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  );
+
+VOID
+EFIAPI
+NorFlashLock (
+  IN EFI_TPL  *OriginalTPL
+  );
+
+VOID
+EFIAPI
+NorFlashUnlock (
+  IN EFI_TPL OriginalTPL
+  );
+
 #endif /* __NOR_FLASH_H__ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
index e329e0727617..c0a3b5861532 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
@@ -31,20 +31,6 @@
 //
 // NorFlashDxe.c
 //
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  );
-
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  );
-
 EFI_STATUS
 NorFlashCreateInstance (
   IN UINTN                NorFlashDeviceBase,
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
index 4e5a97c83c7b..15000a692b02 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
@@ -10,7 +10,6 @@
 #include <Library/BaseMemoryLib.h>
 
 #include "NorFlash.h"
-#include "NorFlashCommon.h"
 
 //
 // Global variable declarations
@@ -817,3 +816,138 @@ NorFlashReset (
   SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
   return EFI_SUCCESS;
 }
+
+/**
+ * This function unlock and erase an entire NOR Flash block.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       Index;
+  EFI_TPL     OriginalTPL;
+
+  NorFlashLock (&OriginalTPL);
+
+  Index = 0;
+  // The block erase might fail a first time (SW bug ?). Retry it ...
+  do {
+    // Unlock the block if we have to
+    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+
+    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+    Index++;
+  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
+
+  if (Index == NOR_FLASH_ERASE_RETRY) {
+    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index));
+  }
+
+  NorFlashUnlock (OriginalTPL);
+
+  return Status;
+}
+
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       WordAddress;
+  UINT32      WordIndex;
+  UINTN       BufferIndex;
+  UINTN       BlockAddress;
+  UINTN       BuffersInBlock;
+  UINTN       RemainingWords;
+  EFI_TPL     OriginalTPL;
+  UINTN       Cnt;
+
+  Status = EFI_SUCCESS;
+
+  // Get the physical address of the block
+  BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
+
+  // Start writing from the first address at the start of the block
+  WordAddress = BlockAddress;
+
+  NorFlashLock (&OriginalTPL);
+
+  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
+    goto EXIT;
+  }
+
+  // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
+
+  // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
+  if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
+    // First, break the entire block into buffer-sized chunks.
+    BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
+
+    // Then feed each buffer chunk to the NOR Flash
+    // If a buffer does not contain any data, don't write it.
+    for (BufferIndex = 0;
+         BufferIndex < BuffersInBlock;
+         BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
+         )
+    {
+      // Check the buffer to see if it contains any data (not set all 1s).
+      for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
+        if (~DataBuffer[Cnt] != 0 ) {
+          // Some data found, write the buffer.
+          Status = NorFlashWriteBuffer (
+                     Instance,
+                     WordAddress,
+                     P30_MAX_BUFFER_SIZE_IN_BYTES,
+                     DataBuffer
+                     );
+          if (EFI_ERROR (Status)) {
+            goto EXIT;
+          }
+
+          break;
+        }
+      }
+    }
+
+    // Finally, finish off any remaining words that are less than the maximum size of the buffer
+    RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
+
+    if (RemainingWords != 0) {
+      Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
+      if (EFI_ERROR (Status)) {
+        goto EXIT;
+      }
+    }
+  } else {
+    // For now, use the single word programming algorithm
+    // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
+    // i.e. which ends in the range 0x......01 - 0x......7F.
+    for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
+      Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+      if (EFI_ERROR (Status)) {
+        goto EXIT;
+      }
+    }
+  }
+
+EXIT:
+  NorFlashUnlock (OriginalTPL);
+
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
+  }
+
+  return Status;
+}
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index b1e01169c24e..4bad6e9b2a6b 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -174,161 +174,6 @@ NorFlashCreateInstance (
   return Status;
 }
 
-/**
- * This function unlock and erase an entire NOR Flash block.
- **/
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       Index;
-  EFI_TPL     OriginalTPL;
-
-  if (!EfiAtRuntime ()) {
-    // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
-    OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-  } else {
-    // This initialization is only to prevent the compiler to complain about the
-    // use of uninitialized variables
-    OriginalTPL = TPL_HIGH_LEVEL;
-  }
-
-  Index = 0;
-  // The block erase might fail a first time (SW bug ?). Retry it ...
-  do {
-    // Unlock the block if we have to
-    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
-    if (EFI_ERROR (Status)) {
-      break;
-    }
-
-    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
-    Index++;
-  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
-
-  if (Index == NOR_FLASH_ERASE_RETRY) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index));
-  }
-
-  if (!EfiAtRuntime ()) {
-    // Interruptions can resume.
-    gBS->RestoreTPL (OriginalTPL);
-  }
-
-  return Status;
-}
-
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       WordAddress;
-  UINT32      WordIndex;
-  UINTN       BufferIndex;
-  UINTN       BlockAddress;
-  UINTN       BuffersInBlock;
-  UINTN       RemainingWords;
-  EFI_TPL     OriginalTPL;
-  UINTN       Cnt;
-
-  Status = EFI_SUCCESS;
-
-  // Get the physical address of the block
-  BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
-
-  // Start writing from the first address at the start of the block
-  WordAddress = BlockAddress;
-
-  if (!EfiAtRuntime ()) {
-    // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
-    OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
-  } else {
-    // This initialization is only to prevent the compiler to complain about the
-    // use of uninitialized variables
-    OriginalTPL = TPL_HIGH_LEVEL;
-  }
-
-  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
-    goto EXIT;
-  }
-
-  // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
-
-  // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
-  if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
-    // First, break the entire block into buffer-sized chunks.
-    BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
-
-    // Then feed each buffer chunk to the NOR Flash
-    // If a buffer does not contain any data, don't write it.
-    for (BufferIndex = 0;
-         BufferIndex < BuffersInBlock;
-         BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
-         )
-    {
-      // Check the buffer to see if it contains any data (not set all 1s).
-      for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
-        if (~DataBuffer[Cnt] != 0 ) {
-          // Some data found, write the buffer.
-          Status = NorFlashWriteBuffer (
-                     Instance,
-                     WordAddress,
-                     P30_MAX_BUFFER_SIZE_IN_BYTES,
-                     DataBuffer
-                     );
-          if (EFI_ERROR (Status)) {
-            goto EXIT;
-          }
-
-          break;
-        }
-      }
-    }
-
-    // Finally, finish off any remaining words that are less than the maximum size of the buffer
-    RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
-
-    if (RemainingWords != 0) {
-      Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  } else {
-    // For now, use the single word programming algorithm
-    // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
-    // i.e. which ends in the range 0x......01 - 0x......7F.
-    for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
-      Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  }
-
-EXIT:
-  if (!EfiAtRuntime ()) {
-    // Interruptions can resume.
-    gBS->RestoreTPL (OriginalTPL);
-  }
-
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
-  }
-
-  return Status;
-}
-
 EFI_STATUS
 EFIAPI
 NorFlashInitialise (
@@ -549,3 +394,41 @@ NorFlashVirtualNotifyEvent (
 
   return;
 }
+
+/**
+  Lock all pending read/write to Nor flash device
+
+  @param[in]     *OriginalTPL     Pointer to Nor flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashLock (
+  IN EFI_TPL  *OriginalTPL
+  )
+{
+  if (!EfiAtRuntime ()) {
+    // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
+    *OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
+  } else {
+    // This initialization is only to prevent the compiler to complain about the
+    // use of uninitialized variables
+    *OriginalTPL = TPL_HIGH_LEVEL;
+  }
+}
+
+/**
+  Unlock all pending read/write to Nor flash device
+
+  @param[in]     OriginalTPL     Nor flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashUnlock (
+  IN EFI_TPL  OriginalTPL
+  )
+{
+  if (!EfiAtRuntime ()) {
+    // Interruptions can resume.
+    gBS->RestoreTPL (OriginalTPL);
+  }
+}
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index f2919265139b..5bff524e5e18 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -153,131 +153,6 @@ NorFlashCreateInstance (
   return Status;
 }
 
-/**
- * This function unlock and erase an entire NOR Flash block.
- **/
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       Index;
-
-  Index = 0;
-  // The block erase might fail a first time (SW bug ?). Retry it ...
-  do {
-    // Unlock the block if we have to
-    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
-    if (EFI_ERROR (Status)) {
-      break;
-    }
-
-    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
-    Index++;
-  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
-
-  if (Index == NOR_FLASH_ERASE_RETRY) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index));
-  }
-
-  return Status;
-}
-
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       WordAddress;
-  UINT32      WordIndex;
-  UINTN       BufferIndex;
-  UINTN       BlockAddress;
-  UINTN       BuffersInBlock;
-  UINTN       RemainingWords;
-  UINTN       Cnt;
-
-  Status = EFI_SUCCESS;
-
-  // Get the physical address of the block
-  BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
-
-  // Start writing from the first address at the start of the block
-  WordAddress = BlockAddress;
-
-  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
-    goto EXIT;
-  }
-
-  // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
-
-  // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
-  if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
-    // First, break the entire block into buffer-sized chunks.
-    BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
-
-    // Then feed each buffer chunk to the NOR Flash
-    // If a buffer does not contain any data, don't write it.
-    for (BufferIndex = 0;
-         BufferIndex < BuffersInBlock;
-         BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
-         )
-    {
-      // Check the buffer to see if it contains any data (not set all 1s).
-      for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
-        if (~DataBuffer[Cnt] != 0 ) {
-          // Some data found, write the buffer.
-          Status = NorFlashWriteBuffer (
-                     Instance,
-                     WordAddress,
-                     P30_MAX_BUFFER_SIZE_IN_BYTES,
-                     DataBuffer
-                     );
-          if (EFI_ERROR (Status)) {
-            goto EXIT;
-          }
-
-          break;
-        }
-      }
-    }
-
-    // Finally, finish off any remaining words that are less than the maximum size of the buffer
-    RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
-
-    if (RemainingWords != 0) {
-      Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  } else {
-    // For now, use the single word programming algorithm
-    // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
-    // i.e. which ends in the range 0x......01 - 0x......7F.
-    for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
-      Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  }
-
-EXIT:
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
-  }
-
-  return Status;
-}
-
 EFI_STATUS
 EFIAPI
 NorFlashInitialise (
@@ -382,3 +257,29 @@ NorFlashFvbInitialize (
 
   return Status;
 }
+
+/**
+  Lock all pending read/write to Nor flash device
+
+  @param[in]     OriginalTPL     Nor flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashLock (
+  IN EFI_TPL  *OriginalTPL
+  )
+{
+}
+
+/**
+  Unlock all pending read/write to Nor flash device
+
+  @param[in]     OriginalTPL     Nor flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashUnlock (
+  IN EFI_TPL  OriginalTPL
+  )
+{
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119319): https://edk2.groups.io/g/devel/message/119319
Mute This Topic: https://groups.io/mt/106365454/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 05/17] Platform/ARM/NorFlashDxe: Remove unimplemented functions from NorFlash.h
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (3 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 04/17] Platform/ARM/NorFlashDxe: Move flash specific functions to NorFlash.c Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 06/17] Platform/ARM/NorFlashDxe: Make local functions STATIC Sahil Kaushal
                   ` (13 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch removes NorFlashReadCfiData() and NorFlashWrite()
prototypes from NorFlash.h as these are not implemented or
used anywhere in NorFlashDxe driver.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h | 17 -----------------
 1 file changed, 17 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index bd5c6a949cf0..3102c5e13bad 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -134,14 +134,6 @@ struct _NOR_FLASH_INSTANCE {
   NOR_FLASH_DEVICE_PATH                  DevicePath;
 };
 
-EFI_STATUS
-NorFlashReadCfiData (
-  IN  UINTN   DeviceBaseAddress,
-  IN  UINTN   CFI_Offset,
-  IN  UINT32  NumberOfBytes,
-  OUT UINT32  *Data
-  );
-
 EFI_STATUS
 NorFlashWriteBuffer (
   IN NOR_FLASH_INSTANCE  *Instance,
@@ -187,15 +179,6 @@ NorFlashRead (
   OUT VOID               *Buffer
   );
 
-EFI_STATUS
-NorFlashWrite (
-  IN        NOR_FLASH_INSTANCE  *Instance,
-  IN        EFI_LBA             Lba,
-  IN        UINTN               Offset,
-  IN OUT    UINTN               *NumBytes,
-  IN        UINT8               *Buffer
-  );
-
 EFI_STATUS
 NorFlashReset (
   IN  NOR_FLASH_INSTANCE  *Instance
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119320): https://edk2.groups.io/g/devel/message/119320
Mute This Topic: https://groups.io/mt/106365455/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 06/17] Platform/ARM/NorFlashDxe: Make local functions STATIC
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (4 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 05/17] Platform/ARM/NorFlashDxe: Remove unimplemented functions from NorFlash.h Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 07/17] Platform/ARM: Create NorFlashDeviceLib library interface for flash specific functions Sahil Kaushal
                   ` (12 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch makes local functions not being used outside
NorFlash.c STATIC.
Also, NorFlashWriteBuffer() is specific to a particular
flash implementation and need not be implemented by
other NOR flash device IPs.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h | 21 --------------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c |  3 +++
 2 files changed, 3 insertions(+), 21 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index 3102c5e13bad..f30d499042ed 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -134,14 +134,6 @@ struct _NOR_FLASH_INSTANCE {
   NOR_FLASH_DEVICE_PATH                  DevicePath;
 };
 
-EFI_STATUS
-NorFlashWriteBuffer (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               TargetAddress,
-  IN UINTN               BufferSizeInBytes,
-  IN UINT32              *Buffer
-  );
-
 //
 // NorFlash.c
 //
@@ -190,19 +182,6 @@ NorFlashEraseSingleBlock (
   IN UINTN               BlockAddress
   );
 
-EFI_STATUS
-NorFlashUnlockSingleBlockIfNecessary (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  );
-
-EFI_STATUS
-NorFlashWriteSingleWord (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               WordAddress,
-  IN UINT32              WriteData
-  );
-
 EFI_STATUS
 NorFlashWriteFullBlock (
   IN NOR_FLASH_INSTANCE  *Instance,
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
index 15000a692b02..254b8937e210 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
@@ -103,6 +103,7 @@ NorFlashUnlockSingleBlock (
   return EFI_SUCCESS;
 }
 
+STATIC
 EFI_STATUS
 NorFlashUnlockSingleBlockIfNecessary (
   IN NOR_FLASH_INSTANCE  *Instance,
@@ -175,6 +176,7 @@ NorFlashEraseSingleBlock (
   return Status;
 }
 
+STATIC
 EFI_STATUS
 NorFlashWriteSingleWord (
   IN NOR_FLASH_INSTANCE  *Instance,
@@ -245,6 +247,7 @@ NorFlashWriteSingleWord (
  * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
  * i.e. the last 4 bits of the target start address must be zero: 0x......00
  */
+STATIC
 EFI_STATUS
 NorFlashWriteBuffer (
   IN NOR_FLASH_INSTANCE  *Instance,
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119321): https://edk2.groups.io/g/devel/message/119321
Mute This Topic: https://groups.io/mt/106365456/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 07/17] Platform/ARM: Create NorFlashDeviceLib library interface for flash specific functions
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (5 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 06/17] Platform/ARM/NorFlashDxe: Make local functions STATIC Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 08/17] Platform/ARM: Add P30NorFlashDeviceLib Library Sahil Kaushal
                   ` (11 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

NorFlashDeviceLib can be used to provide implementations of different
NOR Flash to NorFlashDxe, i.e. NorFlashDxe links with NorFlashDeviceLib
and the platforms can specify their respective NorFlashDeviceLib
instances.

This patch splits NorFlash.h and moves out the function prototypes and
macros that are expected by NorFlashDxe to be implemented by any
Nor Flash implementation to NorFlashDeviceLib.h file.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/ARM.dec                              |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h       | 105 +--------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h |   1 +
 Platform/ARM/Include/Library/NorFlashDeviceLib.h  | 236 ++++++++++++++++++++
 4 files changed, 239 insertions(+), 104 deletions(-)

diff --git a/Platform/ARM/ARM.dec b/Platform/ARM/ARM.dec
index be7e6dc83fde..86d1fcb4878e 100644
--- a/Platform/ARM/ARM.dec
+++ b/Platform/ARM/ARM.dec
@@ -17,6 +17,7 @@ [Includes]
 
 [LibraryClasses]
   BdsLib|Include/Library/BdsLib.h
+  NorFlashDeviceLib|Include/Library/NorFlashDeviceLib.h
   NorFlashPlatformLib|Include/Library/NorFlashPlatformLib.h
 
 [Guids]
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
index f30d499042ed..6cb1f64b9875 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
@@ -20,6 +20,7 @@
 
 #include <Library/DebugLib.h>
 #include <Library/IoLib.h>
+#include <Library/NorFlashDeviceLib.h>
 
 #define NOR_FLASH_ERASE_RETRY  10
 
@@ -40,7 +41,6 @@
 #define CREATE_NOR_ADDRESS(BaseAddr, OffsetAddr)       ((BaseAddr) + ((OffsetAddr) << 2))
 #define CREATE_DUAL_CMD(Cmd)                           ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) )
 #define SEND_NOR_COMMAND(BaseAddr, Offset, Cmd)        MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd))
-#define GET_NOR_BLOCK_ADDRESS(BaseAddr, Lba, LbaSize)  ( BaseAddr + (UINTN)((Lba) * LbaSize) )
 
 // Status Register Bits
 #define P30_SR_BIT_WRITE            (BIT7 << 16 | BIT7)
@@ -105,107 +105,4 @@
 #define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP  0x0060
 #define P30_CMD_READ_CONFIGURATION_REGISTER        0x0003
 
-typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE;
-
-#pragma pack (1)
-typedef struct {
-  VENDOR_DEVICE_PATH          Vendor;
-  UINT8                       Index;
-  EFI_DEVICE_PATH_PROTOCOL    End;
-} NOR_FLASH_DEVICE_PATH;
-#pragma pack ()
-
-struct _NOR_FLASH_INSTANCE {
-  UINT32                                 Signature;
-  EFI_HANDLE                             Handle;
-
-  UINTN                                  DeviceBaseAddress;
-  UINTN                                  RegionBaseAddress;
-  UINTN                                  Size;
-  EFI_LBA                                StartLba;
-
-  EFI_BLOCK_IO_PROTOCOL                  BlockIoProtocol;
-  EFI_BLOCK_IO_MEDIA                     Media;
-  EFI_DISK_IO_PROTOCOL                   DiskIoProtocol;
-
-  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL    FvbProtocol;
-  VOID                                   *ShadowBuffer;
-
-  NOR_FLASH_DEVICE_PATH                  DevicePath;
-};
-
-//
-// NorFlash.c
-//
-EFI_STATUS
-NorFlashWriteSingleBlock (
-  IN        NOR_FLASH_INSTANCE  *Instance,
-  IN        EFI_LBA             Lba,
-  IN        UINTN               Offset,
-  IN OUT    UINTN               *NumBytes,
-  IN        UINT8               *Buffer
-  );
-
-EFI_STATUS
-NorFlashWriteBlocks (
-  IN  NOR_FLASH_INSTANCE  *Instance,
-  IN  EFI_LBA             Lba,
-  IN  UINTN               BufferSizeInBytes,
-  IN  VOID                *Buffer
-  );
-
-EFI_STATUS
-NorFlashReadBlocks (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINTN               BufferSizeInBytes,
-  OUT VOID               *Buffer
-  );
-
-EFI_STATUS
-NorFlashRead (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINTN               Offset,
-  IN UINTN               BufferSizeInBytes,
-  OUT VOID               *Buffer
-  );
-
-EFI_STATUS
-NorFlashReset (
-  IN  NOR_FLASH_INSTANCE  *Instance
-  );
-
-EFI_STATUS
-NorFlashEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  );
-
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  );
-
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  );
-
-VOID
-EFIAPI
-NorFlashLock (
-  IN EFI_TPL  *OriginalTPL
-  );
-
-VOID
-EFIAPI
-NorFlashUnlock (
-  IN EFI_TPL OriginalTPL
-  );
-
 #endif /* __NOR_FLASH_H__ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
index c0a3b5861532..7fcb949843e8 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
@@ -19,6 +19,7 @@
 #include <Protocol/FirmwareVolumeBlock.h>
 
 #include <Library/DebugLib.h>
+#include <Library/NorFlashDeviceLib.h>
 #include <Library/NorFlashPlatformLib.h>
 #include <Library/UefiLib.h>
 #include <Library/UefiRuntimeLib.h>
diff --git a/Platform/ARM/Include/Library/NorFlashDeviceLib.h b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
new file mode 100644
index 000000000000..6833c1ddc456
--- /dev/null
+++ b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
@@ -0,0 +1,236 @@
+/** @file  NorFlashDeviceLib.h
+
+  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef NOR_FLASH_DEVICE_LIB_H_
+#define NOR_FLASH_DEVICE_LIB_H_
+
+#include <Protocol/BlockIo.h>
+#include <Protocol/DiskIo.h>
+#include <Protocol/FirmwareVolumeBlock.h>
+
+typedef struct _NOR_FLASH_INSTANCE NOR_FLASH_INSTANCE;
+
+#define GET_NOR_BLOCK_ADDRESS(BaseAddr, Lba, LbaSize)  ( BaseAddr + (UINTN)((Lba) * LbaSize) )
+
+/**
+  This structure describes the device path for a NOR flash device instance.
+**/
+#pragma pack (1)
+typedef struct {
+  VENDOR_DEVICE_PATH          Vendor;  ///< Vendor specific device path node.
+  UINT8                       Index;   ///< Index of a NOR flash device instance.
+  EFI_DEVICE_PATH_PROTOCOL    End;     ///< End node of a hardware device path.
+} NOR_FLASH_DEVICE_PATH;
+#pragma pack ()
+
+/**
+  NOR Flash instance structure used to identify different flash
+  or regions within a flash.
+**/
+struct _NOR_FLASH_INSTANCE {
+  UINT32                                 Signature; ///< NOR Flash instance signature.
+  EFI_HANDLE                             Handle;    ///< NOR Flash instance handle.
+
+  UINTN                                  DeviceBaseAddress; ///< NOR Flash device base address.
+  UINTN                                  RegionBaseAddress; ///< NOR Flash region base address.
+  UINTN                                  Size;              ///< NOR Flash region size.
+  EFI_LBA                                StartLba;          ///< Region start LBA.
+
+  EFI_BLOCK_IO_PROTOCOL                  BlockIoProtocol; ///< Instance's Block IO protocol handle.
+  EFI_BLOCK_IO_MEDIA                     Media;           ///< Instance's  Media information.
+  EFI_DISK_IO_PROTOCOL                   DiskIoProtocol;  ///< Instance's Disk IO protocol handle.
+
+  EFI_FIRMWARE_VOLUME_BLOCK2_PROTOCOL    FvbProtocol;   ///< Instance's FVB protocol handle.
+  VOID                                   *ShadowBuffer; ///< Instance's shadow buffer.
+
+  NOR_FLASH_DEVICE_PATH                  DevicePath;  ///< Instance's device path.
+};
+
+/**
+  Write a full block to a given location.
+
+  @param[in]    Instance               NOR flash Instance.
+  @param[in]    Lba                    The logical block address in NOR flash.
+  @param[in]    DataBuffer             The data to write into NOR flash location.
+  @param[in]    BlockSizeInWords       The number of bytes to write.
+
+  @retval       EFI_SUCCESS            Write is complete.
+  @retval       EFI_DEVICE_ERROR       The device reported an error.
+  @retval       EFI_WRITE_PROTECTED    The block is write protected.
+  @retval       EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval       EFI_BUFFER_TOO_SMALL   Insufficient buffer size.
+  @retval       EFI_BAD_BUFFER_SIZE    Invalid buffer size.
+**/
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  );
+
+/**
+  This function unlocks and erases an entire NOR Flash block.
+
+  @param[in]     Instance             NOR flash Instance.
+  @param[in]     BlockAddress         Block address to unlock and erase.
+
+  @retval        EFI_SUCCESS          Erase and unlock successfully completed.
+  @retval        EFI_DEVICE_ERROR     The device reported an error.
+  @retval        EFI_WRITE_PROTECTED  The block is write protected.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  );
+
+/**
+  Write a full or portion of a block.
+
+  @param[in]       Instance              NOR flash Instance.
+  @param[in]       Lba                   The starting logical block index to write to.
+  @param[in]       Offset                Offset into the block at which to begin writing.
+  @param[in, out]  NumBytes              The total size of the buffer.
+  @param[in]       Buffer                The pointer to a caller-allocated buffer that
+                                         contains the source for the write.
+
+  @retval          EFI_SUCCESS           Write is complete.
+  @retval          EFI_OUT_OF_RESOURCES  Invalid Buffer passed.
+  @retval          EFI_BAD_BUFFER_SIZE   Buffer size not enough.
+  @retval          EFI_DEVICE_ERROR      The device reported an error.
+  @retval          EFI_ACCESS_DENIED     Device is in write disabled mode.
+**/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+  IN        NOR_FLASH_INSTANCE  *Instance,
+  IN        EFI_LBA             Lba,
+  IN        UINTN               Offset,
+  IN OUT    UINTN               *NumBytes,
+  IN        UINT8               *Buffer
+  );
+
+/**
+  Write multiple blocks.
+
+  @param[in]    Instance               NOR flash Instance.
+  @param[in]    Lba                    The starting logical block index.
+  @param[in]    BufferSizeInBytes      The number of bytes to write.
+  @param[in]    Buffer                 The pointer to a caller-allocated buffer that
+                                       contains the source for the write.
+
+  @retval       EFI_SUCCESS            Write is complete.
+  @retval       EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval       EFI_BAD_BUFFER_SIZE    Invalid buffer size passed.
+  @retval       EFI_DEVICE_ERROR       The device reported an error.
+  @retval       EFI_WRITE_PROTECTED    The block is write protected.
+  @retval       EFI_BUFFER_TOO_SMALL   Insufficient buffer size.
+**/
+EFI_STATUS
+NorFlashWriteBlocks (
+  IN  NOR_FLASH_INSTANCE  *Instance,
+  IN  EFI_LBA             Lba,
+  IN  UINTN               BufferSizeInBytes,
+  IN  VOID                *Buffer
+  );
+
+/**
+  Read multiple blocks.
+
+  @param[in]     Instance               NOR flash Instance.
+  @param[in]     Lba                    The starting logical block index to read from.
+  @param[in]     BufferSizeInBytes      The number of bytes to read.
+  @param[out]    Buffer                 The pointer to a caller-allocated buffer that
+                                        should be copied with read data.
+
+  @retval        EFI_SUCCESS            Read is complete.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval        EFI_BAD_BUFFER_SIZE    Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashReadBlocks (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  );
+
+/**
+  Read from NOR flash.
+
+  @param[in]     Instance               NOR flash Instance.
+  @param[in]     Lba                    The starting logical block index to read from.
+  @param[in]     Offset                 Offset into the block at which to begin reading.
+  @param[in]     BufferSizeInBytes      The number of bytes to read.
+  @param[out]    Buffer                 The pointer to a caller-allocated buffer that
+                                        should be copied with read data.
+
+  @retval        EFI_SUCCESS            Read is complete.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashRead (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               Offset,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  );
+
+/**
+  NOR Flash Reset.
+
+  @param[in]    Instance          NOR flash instance.
+
+  @retval       EFI_SUCCESS       Return success on successful reset.
+  @retval       EFI_DEVICE_ERROR  The device reported an error.
+**/
+EFI_STATUS
+NorFlashReset (
+  IN  NOR_FLASH_INSTANCE  *Instance
+  );
+
+/**
+  The following function presumes that the block has already been unlocked.
+
+  @param[in]    Instance            NOR flash instance.
+  @param[in]    BlockAddress        Block address to erase.
+
+  @retval       EFI_SUCCESS         Request is executed successfully.
+  @retval       EFI_DEVICE_ERROR    The device reported an error.
+  @retval       EFI_WRITE_PROTECTED The block is write protected.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  );
+
+/**
+  Lock all pending read/write to NOR flash device.
+
+  @param[in]     OriginalTPL     Pointer to NOR flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashLock (
+  IN EFI_TPL  *OriginalTPL
+  );
+
+/**
+  Unlock all pending read/write to NOR flash device.
+
+  @param[in]     OriginalTPL     NOR flash device Original TPL.
+**/
+VOID
+EFIAPI
+NorFlashUnlock (
+  IN EFI_TPL  OriginalTPL
+  );
+
+#endif /* NOR_FLASH_DEVICE_LIB_H_ */
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119322): https://edk2.groups.io/g/devel/message/119322
Mute This Topic: https://groups.io/mt/106365457/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 08/17] Platform/ARM: Add P30NorFlashDeviceLib Library
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (6 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 07/17] Platform/ARM: Create NorFlashDeviceLib library interface for flash specific functions Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 09/17] Platform/ARM/NorFlashDxe: Switch from NorFlash.c to NorFlashDeviceLib Sahil Kaushal
                   ` (10 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch implements functions to interact with P30 NOR Flash.
The code is taken from Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
file.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf |  35 +
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h   |  98 ++
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c   | 953 ++++++++++++++++++++
 3 files changed, 1086 insertions(+)

diff --git a/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
new file mode 100644
index 000000000000..0707edb54442
--- /dev/null
+++ b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
@@ -0,0 +1,35 @@
+#/** @file
+#
+#  Component description file for P30NorFlashDeviceLib library
+#
+#  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
+#  Copyright (c) 2020, Linaro, Ltd. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+  INF_VERSION                = 0x00010005
+  BASE_NAME                  = P30NorFlashDeviceLib
+  FILE_GUID                  = ed172366-066b-4998-9b5e-ca7f385a1709
+  MODULE_TYPE                = DXE_DRIVER
+  VERSION_STRING             = 1.0
+  LIBRARY_CLASS              = NorFlashDeviceLib
+
+[Sources.common]
+  P30NorFlashDeviceLib.c
+  P30NorFlashDeviceLib.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  Platform/ARM/ARM.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  DebugLib
+  IoLib
+
+[Pcd.common]
+  gPlatformArmTokenSpaceGuid.PcdNorFlashCheckBlockLocked
diff --git a/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h
new file mode 100644
index 000000000000..c310b2310d62
--- /dev/null
+++ b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.h
@@ -0,0 +1,98 @@
+/** @file  P30NorFlashDeviceLib.h
+
+  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
+  Copyright (c) 2020, Linaro, Ltd. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef P30_NOR_FLASH_DEVICE_LIB_H_
+#define P30_NOR_FLASH_DEVICE_LIB_H_
+
+#define NOR_FLASH_ERASE_RETRY  10
+
+// Device access macros
+// These are necessary because we use 2 x 16bit parts to make up 32bit data
+
+#define HIGH_16_BITS  0xFFFF0000
+#define LOW_16_BITS   0x0000FFFF
+#define LOW_8_BITS    0x000000FF
+
+#define FOLD_32BIT_INTO_16BIT(value)  ( ( value >> 16 ) | ( value & LOW_16_BITS ) )
+
+#define GET_LOW_BYTE(value)   ( value & LOW_8_BITS )
+#define GET_HIGH_BYTE(value)  ( GET_LOW_BYTE( value >> 16 ) )
+
+// Each command must be sent simultaneously to both chips,
+// i.e. at the lower 16 bits AND at the higher 16 bits
+#define CREATE_NOR_ADDRESS(BaseAddr, OffsetAddr)  ((BaseAddr) + ((OffsetAddr) << 2))
+#define CREATE_DUAL_CMD(Cmd)                      ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) )
+#define SEND_NOR_COMMAND(BaseAddr, Offset, Cmd)   MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd))
+
+#define BOTH_ALIGNED(a, b, align)  ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0)
+
+// Status Register Bits
+#define P30_SR_BIT_WRITE            (BIT7 << 16 | BIT7)
+#define P30_SR_BIT_ERASE_SUSPEND    (BIT6 << 16 | BIT6)
+#define P30_SR_BIT_ERASE            (BIT5 << 16 | BIT5)
+#define P30_SR_BIT_PROGRAM          (BIT4 << 16 | BIT4)
+#define P30_SR_BIT_VPP              (BIT3 << 16 | BIT3)
+#define P30_SR_BIT_PROGRAM_SUSPEND  (BIT2 << 16 | BIT2)
+#define P30_SR_BIT_BLOCK_LOCKED     (BIT1 << 16 | BIT1)
+#define P30_SR_BIT_BEFP             (BIT0 << 16 | BIT0)
+
+// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family
+
+// On chip buffer size for buffered programming operations
+// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes.
+// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes
+#define P30_MAX_BUFFER_SIZE_IN_BYTES  ((UINTN)128)
+#define P30_MAX_BUFFER_SIZE_IN_WORDS  (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4))
+#define MAX_BUFFERED_PROG_ITERATIONS  10000000
+#define BOUNDARY_OF_32_WORDS          0x7F
+
+// CFI Addresses
+#define P30_CFI_ADDR_QUERY_UNIQUE_QRY  0x10
+#define P30_CFI_ADDR_VENDOR_ID         0x13
+
+// CFI Data
+#define CFI_QRY  0x00595251
+
+// READ Commands
+#define P30_CMD_READ_DEVICE_ID         0x0090
+#define P30_CMD_READ_STATUS_REGISTER   0x0070
+#define P30_CMD_CLEAR_STATUS_REGISTER  0x0050
+#define P30_CMD_READ_ARRAY             0x00FF
+#define P30_CMD_READ_CFI_QUERY         0x0098
+
+// WRITE Commands
+#define P30_CMD_WORD_PROGRAM_SETUP            0x0040
+#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP  0x0010
+#define P30_CMD_BUFFERED_PROGRAM_SETUP        0x00E8
+#define P30_CMD_BUFFERED_PROGRAM_CONFIRM      0x00D0
+#define P30_CMD_BEFP_SETUP                    0x0080
+#define P30_CMD_BEFP_CONFIRM                  0x00D0
+
+// ERASE Commands
+#define P30_CMD_BLOCK_ERASE_SETUP    0x0020
+#define P30_CMD_BLOCK_ERASE_CONFIRM  0x00D0
+
+// SUSPEND Commands
+#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND  0x00B0
+#define P30_CMD_SUSPEND_RESUME            0x00D0
+
+// BLOCK LOCKING / UNLOCKING Commands
+#define P30_CMD_LOCK_BLOCK_SETUP  0x0060
+#define P30_CMD_LOCK_BLOCK        0x0001
+#define P30_CMD_UNLOCK_BLOCK      0x00D0
+#define P30_CMD_LOCK_DOWN_BLOCK   0x002F
+
+// PROTECTION Commands
+#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP  0x00C0
+
+// CONFIGURATION Commands
+#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP  0x0060
+#define P30_CMD_READ_CONFIGURATION_REGISTER        0x0003
+
+#endif /* P30_NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c
new file mode 100644
index 000000000000..5af085bdf493
--- /dev/null
+++ b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c
@@ -0,0 +1,953 @@
+/** @file  P30NorFlashDeviceLib.c
+
+  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
+  Copyright (c) 2020, Linaro, Ltd. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/PcdLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/NorFlashDeviceLib.h>
+
+#include "P30NorFlashDeviceLib.h"
+
+STATIC
+UINT32
+NorFlashReadStatusRegister (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               SR_Address
+  )
+{
+  // Prepare to read the status register
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
+  return MmioRead32 (Instance->DeviceBaseAddress);
+}
+
+STATIC
+BOOLEAN
+NorFlashBlockIsLocked (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  UINT32  LockStatus;
+
+  // Send command for reading device id
+  SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
+
+  // Read block lock status
+  LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2));
+
+  // Decode block lock status
+  LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus);
+
+  if ((LockStatus & 0x2) != 0) {
+    DEBUG ((DEBUG_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
+  }
+
+  return ((LockStatus & 0x1) != 0);
+}
+
+STATIC
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  UINT32  LockStatus;
+
+  // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
+  // and to protect shared data structures.
+
+  if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
+    do {
+      // Request a lock setup
+      SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
+
+      // Request an unlock
+      SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
+
+      // Send command for reading device id
+      SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
+
+      // Read block lock status
+      LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2));
+
+      // Decode block lock status
+      LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus);
+    } while ((LockStatus & 0x1) == 1);
+  } else {
+    // Request a lock setup
+    SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
+
+    // Request an unlock
+    SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
+
+    // Wait until the status register gives us the all clear
+    do {
+      LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
+    } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+  }
+
+  // Put device back into Read Array mode
+  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
+
+  DEBUG ((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress));
+
+  return EFI_SUCCESS;
+}
+
+STATIC
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = EFI_SUCCESS;
+
+  if (NorFlashBlockIsLocked (Instance, BlockAddress)) {
+    Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+  }
+
+  return Status;
+}
+
+/**
+ * The following function presumes that the block has already been unlocked.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+  UINT32      StatusRegister;
+
+  Status = EFI_SUCCESS;
+
+  // Request a block erase and then confirm it
+  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
+  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
+
+  // Wait until the status register gives us the all clear
+  do {
+    StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
+  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+  if (StatusRegister & P30_SR_BIT_VPP) {
+    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
+    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_ERASE) {
+    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+    // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
+    DEBUG ((DEBUG_INFO, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
+    Status = EFI_WRITE_PROTECTED;
+  }
+
+  if (EFI_ERROR (Status)) {
+    // Clear the Status Register
+    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+  }
+
+  // Put device back into Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+  return Status;
+}
+
+STATIC
+EFI_STATUS
+NorFlashWriteSingleWord (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               WordAddress,
+  IN UINT32              WriteData
+  )
+{
+  EFI_STATUS  Status;
+  UINT32      StatusRegister;
+
+  Status = EFI_SUCCESS;
+
+  // Request a write single word command
+  SEND_NOR_COMMAND (WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
+
+  // Store the word into NOR Flash;
+  MmioWrite32 (WordAddress, WriteData);
+
+  // Wait for the write to complete and then check for any errors; i.e. check the Status Register
+  do {
+    // Prepare to read the status register
+    StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
+    // The chip is busy while the WRITE bit is not asserted
+  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+  // Perform a full status check:
+  // Mask the relevant bits of Status Register.
+  // Everything should be zero, if not, we have a problem
+
+  if (StatusRegister & P30_SR_BIT_VPP) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n", WordAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_PROGRAM) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n", WordAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n", WordAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (!EFI_ERROR (Status)) {
+    // Clear the Status Register
+    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+  }
+
+  // Put device back into Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+  return Status;
+}
+
+/*
+ * Writes data to the NOR Flash using the Buffered Programming method.
+ *
+ * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
+ * Therefore this function will only handle buffers up to 32 words or 128 bytes.
+ * To deal with larger buffers, call this function again.
+ *
+ * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
+ * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
+ *
+ * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
+ * then programming time is doubled and power consumption is increased.
+ * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
+ * i.e. the last 4 bits of the target start address must be zero: 0x......00
+ */
+STATIC
+EFI_STATUS
+NorFlashWriteBuffer (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               TargetAddress,
+  IN UINTN               BufferSizeInBytes,
+  IN UINT32              *Buffer
+  )
+{
+  EFI_STATUS       Status;
+  UINTN            BufferSizeInWords;
+  UINTN            Count;
+  volatile UINT32  *Data;
+  UINTN            WaitForBuffer;
+  BOOLEAN          BufferAvailable;
+  UINT32           StatusRegister;
+
+  WaitForBuffer   = MAX_BUFFERED_PROG_ITERATIONS;
+  BufferAvailable = FALSE;
+
+  // Check that the target address does not cross a 32-word boundary.
+  if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Check there are some data to program
+  if (BufferSizeInBytes == 0) {
+    return EFI_BUFFER_TOO_SMALL;
+  }
+
+  // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
+  if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // Check that the buffer size is a multiple of 32-bit words
+  if ((BufferSizeInBytes % 4) != 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // Pre-programming conditions checked, now start the algorithm.
+
+  // Prepare the data destination address
+  Data = (UINT32 *)TargetAddress;
+
+  // Check the availability of the buffer
+  do {
+    // Issue the Buffered Program Setup command
+    SEND_NOR_COMMAND (TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
+
+    // Read back the status register bit#7 from the same address
+    if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
+      BufferAvailable = TRUE;
+    }
+
+    // Update the loop counter
+    WaitForBuffer--;
+  } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
+
+  // The buffer was not available for writing
+  if (WaitForBuffer == 0) {
+    Status = EFI_DEVICE_ERROR;
+    goto EXIT;
+  }
+
+  // From now on we work in 32-bit words
+  BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
+
+  // Write the word count, which is (buffer_size_in_words - 1),
+  // because word count 0 means one word.
+  SEND_NOR_COMMAND (TargetAddress, 0, (BufferSizeInWords - 1));
+
+  // Write the data to the NOR Flash, advancing each address by 4 bytes
+  for (Count = 0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
+    MmioWrite32 ((UINTN)Data, *Buffer);
+  }
+
+  // Issue the Buffered Program Confirm command, to start the programming operation
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
+
+  // Wait for the write to complete and then check for any errors; i.e. check the Status Register
+  do {
+    StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
+    // The chip is busy while the WRITE bit is not asserted
+  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
+
+  // Perform a full status check:
+  // Mask the relevant bits of Status Register.
+  // Everything should be zero, if not, we have a problem
+
+  Status = EFI_SUCCESS;
+
+  if (StatusRegister & P30_SR_BIT_VPP) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_PROGRAM) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n", TargetAddress));
+    Status = EFI_DEVICE_ERROR;
+  }
+
+  if (!EFI_ERROR (Status)) {
+    // Clear the Status Register
+    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
+  }
+
+EXIT:
+  // Put device back into Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+  return Status;
+}
+
+EFI_STATUS
+NorFlashWriteBlocks (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               BufferSizeInBytes,
+  IN VOID                *Buffer
+  )
+{
+  UINT32      *pWriteBuffer;
+  EFI_STATUS  Status;
+  EFI_LBA     CurrentBlock;
+  UINT32      BlockSizeInWords;
+  UINT32      NumBlocks;
+  UINT32      BlockCount;
+
+  Status = EFI_SUCCESS;
+
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (Instance->Media.ReadOnly == TRUE) {
+    return EFI_WRITE_PROTECTED;
+  }
+
+  // We must have some bytes to read
+  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
+  if (BufferSizeInBytes == 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // The size of the buffer must be a multiple of the block size
+  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
+  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // All blocks must be within the device
+  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
+
+  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+  // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
+  // to a proper data type, so use *ReadBuffer
+  pWriteBuffer = (UINT32 *)Buffer;
+
+  CurrentBlock = Lba;
+  for (BlockCount = 0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
+    DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
+
+    Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
+
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+  }
+
+  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
+  return Status;
+}
+
+/**
+  Copy Length bytes from Source to Destination, using aligned accesses only.
+  Note that this implementation uses memcpy() semantics rather then memmove()
+  semantics, i.e., SourceBuffer and DestinationBuffer should not overlap.
+
+  @param  DestinationBuffer The target of the copy request.
+  @param  SourceBuffer      The place to copy from.
+  @param  Length            The number of bytes to copy.
+
+  @return Destination
+
+**/
+STATIC
+VOID *
+AlignedCopyMem (
+  OUT     VOID        *DestinationBuffer,
+  IN      CONST VOID  *SourceBuffer,
+  IN      UINTN       Length
+  )
+{
+  UINT8         *Destination8;
+  CONST UINT8   *Source8;
+  UINT32        *Destination32;
+  CONST UINT32  *Source32;
+  UINT64        *Destination64;
+  CONST UINT64  *Source64;
+
+  if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 8) && (Length >= 8)) {
+    Destination64 = DestinationBuffer;
+    Source64      = SourceBuffer;
+    while (Length >= 8) {
+      *Destination64++ = *Source64++;
+      Length          -= 8;
+    }
+
+    Destination8 = (UINT8 *)Destination64;
+    Source8      = (CONST UINT8 *)Source64;
+  } else if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 4) && (Length >= 4)) {
+    Destination32 = DestinationBuffer;
+    Source32      = SourceBuffer;
+    while (Length >= 4) {
+      *Destination32++ = *Source32++;
+      Length          -= 4;
+    }
+
+    Destination8 = (UINT8 *)Destination32;
+    Source8      = (CONST UINT8 *)Source32;
+  } else {
+    Destination8 = DestinationBuffer;
+    Source8      = SourceBuffer;
+  }
+
+  while (Length-- != 0) {
+    *Destination8++ = *Source8++;
+  }
+
+  return DestinationBuffer;
+}
+
+EFI_STATUS
+NorFlashReadBlocks (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  )
+{
+  UINT32  NumBlocks;
+  UINTN   StartAddress;
+
+  DEBUG ((
+    DEBUG_BLKIO,
+    "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n",
+    BufferSizeInBytes,
+    Instance->Media.BlockSize,
+    Instance->Media.LastBlock,
+    Lba
+    ));
+
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Return if we have not any byte to read
+  if (BufferSizeInBytes == 0) {
+    return EFI_SUCCESS;
+  }
+
+  // The size of the buffer must be a multiple of the block size
+  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // All blocks must be within the device
+  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+    DEBUG ((DEBUG_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Get the address to start reading from
+  StartAddress = GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   Instance->Media.BlockSize
+                   );
+
+  // Put the device into Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+  // Readout the data
+  AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes);
+
+  return EFI_SUCCESS;
+}
+
+EFI_STATUS
+NorFlashRead (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               Offset,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  )
+{
+  UINTN  StartAddress;
+
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Return if we have not any byte to read
+  if (BufferSizeInBytes == 0) {
+    return EFI_SUCCESS;
+  }
+
+  if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) {
+    DEBUG ((DEBUG_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n"));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Get the address to start reading from
+  StartAddress = GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   Instance->Media.BlockSize
+                   );
+
+  // Put the device into Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+
+  // Readout the data
+  AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes);
+
+  return EFI_SUCCESS;
+}
+
+/*
+  Write a full or portion of a block. It must not span block boundaries; that is,
+  Offset + *NumBytes <= Instance->Media.BlockSize.
+*/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+  IN        NOR_FLASH_INSTANCE  *Instance,
+  IN        EFI_LBA             Lba,
+  IN        UINTN               Offset,
+  IN OUT    UINTN               *NumBytes,
+  IN        UINT8               *Buffer
+  )
+{
+  EFI_STATUS  TempStatus;
+  UINT32      Tmp;
+  UINT32      TmpBuf;
+  UINT32      WordToWrite;
+  UINT32      Mask;
+  BOOLEAN     DoErase;
+  UINTN       BytesToWrite;
+  UINTN       CurOffset;
+  UINTN       WordAddr;
+  UINTN       BlockSize;
+  UINTN       BlockAddress;
+  UINTN       PrevBlockAddress;
+
+  PrevBlockAddress = 0;
+
+  DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer));
+
+  // Detect WriteDisabled state
+  if (Instance->Media.ReadOnly == TRUE) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n"));
+    // It is in WriteDisabled state, return an error right away
+    return EFI_ACCESS_DENIED;
+  }
+
+  // Cache the block size to avoid de-referencing pointers all the time
+  BlockSize = Instance->Media.BlockSize;
+
+  // The write must not span block boundaries.
+  // We need to check each variable individually because adding two large values together overflows.
+  if ((Offset               >= BlockSize) ||
+      (*NumBytes            >  BlockSize) ||
+      ((Offset + *NumBytes) >  BlockSize))
+  {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // We must have some bytes to write
+  if (*NumBytes == 0) {
+    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // Pick 128bytes as a good start for word operations as opposed to erasing the
+  // block and writing the data regardless if an erase is really needed.
+  // It looks like most individual NV variable writes are smaller than 128bytes.
+  if (*NumBytes <= 128) {
+    // Check to see if we need to erase before programming the data into NOR.
+    // If the destination bits are only changing from 1s to 0s we can just write.
+    // After a block is erased all bits in the block is set to 1.
+    // If any byte requires us to erase we just give up and rewrite all of it.
+    DoErase      = FALSE;
+    BytesToWrite = *NumBytes;
+    CurOffset    = Offset;
+
+    while (BytesToWrite > 0) {
+      // Read full word from NOR, splice as required. A word is the smallest
+      // unit we can write.
+      TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof (Tmp), &Tmp);
+      if (EFI_ERROR (TempStatus)) {
+        return EFI_DEVICE_ERROR;
+      }
+
+      // Physical address of word in NOR to write.
+      WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS (
+                                          Instance->RegionBaseAddress,
+                                          Lba,
+                                          BlockSize
+                                          );
+      // The word of data that is to be written.
+      TmpBuf = *((UINT32 *)(Buffer + (*NumBytes - BytesToWrite)));
+
+      // First do word aligned chunks.
+      if ((CurOffset & 0x3) == 0) {
+        if (BytesToWrite >= 4) {
+          // Is the destination still in 'erased' state?
+          if (~Tmp != 0) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Write this word to NOR
+          WordToWrite   = TmpBuf;
+          CurOffset    += sizeof (TmpBuf);
+          BytesToWrite -= sizeof (TmpBuf);
+        } else {
+          // BytesToWrite < 4. Do small writes and left-overs
+          Mask = ~((~0) << (BytesToWrite * 8));
+          // Mask out the bytes we want.
+          TmpBuf &= Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
+          CurOffset   += BytesToWrite;
+          BytesToWrite = 0;
+        }
+      } else {
+        // Do multiple words, but starting unaligned.
+        if (BytesToWrite > (4 - (CurOffset & 0x3))) {
+          Mask = ((~0) << ((CurOffset & 0x3) * 8));
+          // Mask out the bytes we want.
+          TmpBuf &= Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite   = (Tmp & ~Mask) | TmpBuf;
+          BytesToWrite -= (4 - (CurOffset & 0x3));
+          CurOffset    += (4 - (CurOffset & 0x3));
+        } else {
+          // Unaligned and fits in one word.
+          Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
+          // Mask out the bytes we want.
+          TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
+          CurOffset   += BytesToWrite;
+          BytesToWrite = 0;
+        }
+      }
+
+      //
+      // Write the word to NOR.
+      //
+
+      BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize);
+      if (BlockAddress != PrevBlockAddress) {
+        TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+        if (EFI_ERROR (TempStatus)) {
+          return EFI_DEVICE_ERROR;
+        }
+
+        PrevBlockAddress = BlockAddress;
+      }
+
+      TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
+      if (EFI_ERROR (TempStatus)) {
+        return EFI_DEVICE_ERROR;
+      }
+    }
+
+    // Exit if we got here and could write all the data. Otherwise do the
+    // Erase-Write cycle.
+    if (!DoErase) {
+      return EFI_SUCCESS;
+    }
+  }
+
+  // Check we did get some memory. Buffer is BlockSize.
+  if (Instance->ShadowBuffer == NULL) {
+    DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
+    return EFI_DEVICE_ERROR;
+  }
+
+  // Read NOR Flash data into shadow buffer
+  TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
+  if (EFI_ERROR (TempStatus)) {
+    // Return one of the pre-approved error statuses
+    return EFI_DEVICE_ERROR;
+  }
+
+  // Put the data at the appropriate location inside the buffer area
+  CopyMem ((VOID *)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes);
+
+  // Write the modified buffer back to the NorFlash
+  TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
+  if (EFI_ERROR (TempStatus)) {
+    // Return one of the pre-approved error statuses
+    return EFI_DEVICE_ERROR;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+ * This function unlock and erase an entire NOR Flash block.
+ **/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       Index;
+  EFI_TPL     OriginalTPL;
+
+  NorFlashLock (&OriginalTPL);
+
+  Index = 0;
+  // The block erase might fail a first time (SW bug ?). Retry it ...
+  do {
+    // Unlock the block if we have to
+    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+
+    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+    Index++;
+  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
+
+  if (Index == NOR_FLASH_ERASE_RETRY) {
+    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index));
+  }
+
+  NorFlashUnlock (OriginalTPL);
+
+  return Status;
+}
+
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       WordAddress;
+  UINT32      WordIndex;
+  UINTN       BufferIndex;
+  UINTN       BlockAddress;
+  UINTN       BuffersInBlock;
+  UINTN       RemainingWords;
+  EFI_TPL     OriginalTPL;
+  UINTN       Cnt;
+
+  Status = EFI_SUCCESS;
+
+  // Get the physical address of the block
+  BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
+
+  // Start writing from the first address at the start of the block
+  WordAddress = BlockAddress;
+
+  NorFlashLock (&OriginalTPL);
+
+  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
+    goto EXIT;
+  }
+
+  // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
+
+  // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
+  if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
+    // First, break the entire block into buffer-sized chunks.
+    BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
+
+    // Then feed each buffer chunk to the NOR Flash
+    // If a buffer does not contain any data, don't write it.
+    for (BufferIndex = 0;
+         BufferIndex < BuffersInBlock;
+         BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
+         )
+    {
+      // Check the buffer to see if it contains any data (not set all 1s).
+      for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
+        if (~DataBuffer[Cnt] != 0 ) {
+          // Some data found, write the buffer.
+          Status = NorFlashWriteBuffer (
+                     Instance,
+                     WordAddress,
+                     P30_MAX_BUFFER_SIZE_IN_BYTES,
+                     DataBuffer
+                     );
+          if (EFI_ERROR (Status)) {
+            goto EXIT;
+          }
+
+          break;
+        }
+      }
+    }
+
+    // Finally, finish off any remaining words that are less than the maximum size of the buffer
+    RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
+
+    if (RemainingWords != 0) {
+      Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
+      if (EFI_ERROR (Status)) {
+        goto EXIT;
+      }
+    }
+  } else {
+    // For now, use the single word programming algorithm
+    // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
+    // i.e. which ends in the range 0x......01 - 0x......7F.
+    for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
+      Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+      if (EFI_ERROR (Status)) {
+        goto EXIT;
+      }
+    }
+  }
+
+EXIT:
+  NorFlashUnlock (OriginalTPL);
+
+  if (EFI_ERROR (Status)) {
+    DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
+  }
+
+  return Status;
+}
+
+EFI_STATUS
+NorFlashReset (
+  IN  NOR_FLASH_INSTANCE  *Instance
+  )
+{
+  // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
+  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
+  return EFI_SUCCESS;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119323): https://edk2.groups.io/g/devel/message/119323
Mute This Topic: https://groups.io/mt/106365458/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 09/17] Platform/ARM/NorFlashDxe: Switch from NorFlash.c to NorFlashDeviceLib
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (7 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 08/17] Platform/ARM: Add P30NorFlashDeviceLib Library Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 10/17] Platform/ARM: Add HostControllerBaseAddress variable Sahil Kaushal
                   ` (9 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

NorFlashDeviceLib can be used to provide implementations of different
NOR Flash to NorFlashDxe, i.e. NorFlashDxe links with NorFlashDeviceLib
and the platforms can specify their respective NorFlashDeviceLib
instances.

This patch adds the following major changes:

1. Adds changes in NorFlashDxe to look for NorFlashDeviceLib instead of
NorFlash.c for flash specific implementation

2. Remove NorFlash.c and NorFlash.h as they are no longer required.

3. Add changes to platform description files to provide
P30NorFlashDeviceLib as NorFlashDeviceLib

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/SgiPkg/SgiPlatform.dsc.inc                   |   1 +
 Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc                 |   1 +
 Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc              |   1 +
 Platform/ARM/JunoPkg/ArmJuno.dsc                          |   1 +
 Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc         |   1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf          |   5 +-
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf |   6 +-
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.h               | 108 ---
 Platform/ARM/Drivers/NorFlashDxe/NorFlash.c               | 956 --------------------
 Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c     |   1 -
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c            |   1 -
 Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c            |   1 -
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c   |   1 -
 13 files changed, 7 insertions(+), 1077 deletions(-)

diff --git a/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc b/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
index 1bf489ffeb39..3dcf422eab4b 100644
--- a/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
+++ b/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
@@ -34,6 +34,7 @@ [LibraryClasses.common]
   BasePathLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf
   LcdHwLib|ArmPlatformPkg/Library/HdLcd/HdLcd.inf
   LcdPlatformLib|Platform/ARM/SgiPkg/Library/HdLcdArmSgiLib/HdLcdArmSgiLib.inf
+  NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/SgiPkg/Library/NorFlashLib/NorFlashLib.inf
   HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
   ResetSystemLib|ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf
diff --git a/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc b/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
index 0dd9ebbfc16c..ab0e2a957a1b 100644
--- a/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
+++ b/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
@@ -63,6 +63,7 @@ [LibraryClasses.common.MM_STANDALONE]
   AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
   BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf
   IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
+  NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/SgiPkg/Library/NorFlashLib/StandaloneMmNorFlashLib.inf
   OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
   RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
diff --git a/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc b/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
index 9f51e05af561..70ff049d3248 100644
--- a/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
+++ b/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
@@ -93,6 +93,7 @@ [LibraryClasses.common]
   # Versatile Express Specific Libraries
   PlatformPeiLib|ArmPlatformPkg/PlatformPei/PlatformPeiLib.inf
   ArmPlatformSysConfigLib|Platform/ARM/VExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf
+  NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/VExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf
   ResetSystemLib|ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf
 
diff --git a/Platform/ARM/JunoPkg/ArmJuno.dsc b/Platform/ARM/JunoPkg/ArmJuno.dsc
index 7fe796a53433..81d2cbe4359f 100644
--- a/Platform/ARM/JunoPkg/ArmJuno.dsc
+++ b/Platform/ARM/JunoPkg/ArmJuno.dsc
@@ -40,6 +40,7 @@ [LibraryClasses.common]
   ArmPlatformLib|Platform/ARM/JunoPkg/Library/ArmJunoLib/ArmJunoLib.inf
   ArmSmcLib|ArmPkg/Library/ArmSmcLib/ArmSmcLib.inf
 
+  NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/JunoPkg/Library/NorFlashJunoLib/NorFlashJunoLib.inf
 
   CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
diff --git a/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc b/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
index 0e77b76cae69..a5805da49c92 100644
--- a/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
+++ b/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
@@ -100,6 +100,7 @@ [LibraryClasses.common.MM_STANDALONE]
 
   # STMM for Variable runtime service.
 !if $(ENABLE_UEFI_SECURE_VARIABLE) == TRUE
+  NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/VExpressPkg/Library/NorFlashArmVExpressLib/NorFlashStMmLib.inf
   VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
index 18e99bac8888..de160025b632 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
@@ -17,8 +17,6 @@ [Defines]
   ENTRY_POINT                    = NorFlashInitialise
 
 [Sources.common]
-  NorFlash.c
-  NorFlash.h
   NorFlashBlockIoDxe.c
   NorFlashDxe.c
   NorFlashCommon.h
@@ -36,6 +34,7 @@ [LibraryClasses]
   DxeServicesTableLib
   HobLib
   IoLib
+  NorFlashDeviceLib
   NorFlashPlatformLib
   UefiBootServicesTableLib
   UefiDriverEntryPoint
@@ -66,7 +65,5 @@ [Pcd.common]
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
 
-  gPlatformArmTokenSpaceGuid.PcdNorFlashCheckBlockLocked
-
 [Depex]
   gEfiCpuArchProtocolGuid
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
index 69c40ccf9c27..d9e7de07165c 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
@@ -19,8 +19,6 @@ [Defines]
   ENTRY_POINT                    = NorFlashInitialise
 
 [Sources.common]
-  NorFlash.c
-  NorFlash.h
   NorFlashFvb.c
   NorFlashCommon.h
   NorFlashStandaloneMm.c
@@ -38,6 +36,7 @@ [LibraryClasses]
   IoLib
   MemoryAllocationLib
   MmServicesTableLib
+  NorFlashDeviceLib
   NorFlashPlatformLib
   StandaloneMmDriverEntryPoint
 
@@ -60,8 +59,5 @@ [FixedPcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
 
-[FeaturePcd]
-  gPlatformArmTokenSpaceGuid.PcdNorFlashCheckBlockLocked
-
 [Depex]
   TRUE
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
deleted file mode 100644
index 6cb1f64b9875..000000000000
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/** @file  NorFlash.h
-
-  Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.<BR>
-
-  SPDX-License-Identifier: BSD-2-Clause-Patent
-
-**/
-
-#ifndef __NOR_FLASH_H__
-#define __NOR_FLASH_H__
-
-#include <Base.h>
-#include <PiDxe.h>
-
-#include <Guid/EventGroup.h>
-
-#include <Protocol/BlockIo.h>
-#include <Protocol/DiskIo.h>
-#include <Protocol/FirmwareVolumeBlock.h>
-
-#include <Library/DebugLib.h>
-#include <Library/IoLib.h>
-#include <Library/NorFlashDeviceLib.h>
-
-#define NOR_FLASH_ERASE_RETRY  10
-
-// Device access macros
-// These are necessary because we use 2 x 16bit parts to make up 32bit data
-
-#define HIGH_16_BITS  0xFFFF0000
-#define LOW_16_BITS   0x0000FFFF
-#define LOW_8_BITS    0x000000FF
-
-#define FOLD_32BIT_INTO_16BIT(value)  ( ( value >> 16 ) | ( value & LOW_16_BITS ) )
-
-#define GET_LOW_BYTE(value)   ( value & LOW_8_BITS )
-#define GET_HIGH_BYTE(value)  ( GET_LOW_BYTE( value >> 16 ) )
-
-// Each command must be sent simultaneously to both chips,
-// i.e. at the lower 16 bits AND at the higher 16 bits
-#define CREATE_NOR_ADDRESS(BaseAddr, OffsetAddr)       ((BaseAddr) + ((OffsetAddr) << 2))
-#define CREATE_DUAL_CMD(Cmd)                           ( ( Cmd << 16) | ( Cmd & LOW_16_BITS) )
-#define SEND_NOR_COMMAND(BaseAddr, Offset, Cmd)        MmioWrite32 (CREATE_NOR_ADDRESS(BaseAddr,Offset), CREATE_DUAL_CMD(Cmd))
-
-// Status Register Bits
-#define P30_SR_BIT_WRITE            (BIT7 << 16 | BIT7)
-#define P30_SR_BIT_ERASE_SUSPEND    (BIT6 << 16 | BIT6)
-#define P30_SR_BIT_ERASE            (BIT5 << 16 | BIT5)
-#define P30_SR_BIT_PROGRAM          (BIT4 << 16 | BIT4)
-#define P30_SR_BIT_VPP              (BIT3 << 16 | BIT3)
-#define P30_SR_BIT_PROGRAM_SUSPEND  (BIT2 << 16 | BIT2)
-#define P30_SR_BIT_BLOCK_LOCKED     (BIT1 << 16 | BIT1)
-#define P30_SR_BIT_BEFP             (BIT0 << 16 | BIT0)
-
-// Device Commands for Intel StrataFlash(R) Embedded Memory (P30) Family
-
-// On chip buffer size for buffered programming operations
-// There are 2 chips, each chip can buffer up to 32 (16-bit)words, and each word is 2 bytes.
-// Therefore the total size of the buffer is 2 x 32 x 2 = 128 bytes
-#define P30_MAX_BUFFER_SIZE_IN_BYTES  ((UINTN)128)
-#define P30_MAX_BUFFER_SIZE_IN_WORDS  (P30_MAX_BUFFER_SIZE_IN_BYTES/((UINTN)4))
-#define MAX_BUFFERED_PROG_ITERATIONS  10000000
-#define BOUNDARY_OF_32_WORDS          0x7F
-
-// CFI Addresses
-#define P30_CFI_ADDR_QUERY_UNIQUE_QRY  0x10
-#define P30_CFI_ADDR_VENDOR_ID         0x13
-
-// CFI Data
-#define CFI_QRY  0x00595251
-
-// READ Commands
-#define P30_CMD_READ_DEVICE_ID         0x0090
-#define P30_CMD_READ_STATUS_REGISTER   0x0070
-#define P30_CMD_CLEAR_STATUS_REGISTER  0x0050
-#define P30_CMD_READ_ARRAY             0x00FF
-#define P30_CMD_READ_CFI_QUERY         0x0098
-
-// WRITE Commands
-#define P30_CMD_WORD_PROGRAM_SETUP            0x0040
-#define P30_CMD_ALTERNATE_WORD_PROGRAM_SETUP  0x0010
-#define P30_CMD_BUFFERED_PROGRAM_SETUP        0x00E8
-#define P30_CMD_BUFFERED_PROGRAM_CONFIRM      0x00D0
-#define P30_CMD_BEFP_SETUP                    0x0080
-#define P30_CMD_BEFP_CONFIRM                  0x00D0
-
-// ERASE Commands
-#define P30_CMD_BLOCK_ERASE_SETUP    0x0020
-#define P30_CMD_BLOCK_ERASE_CONFIRM  0x00D0
-
-// SUSPEND Commands
-#define P30_CMD_PROGRAM_OR_ERASE_SUSPEND  0x00B0
-#define P30_CMD_SUSPEND_RESUME            0x00D0
-
-// BLOCK LOCKING / UNLOCKING Commands
-#define P30_CMD_LOCK_BLOCK_SETUP  0x0060
-#define P30_CMD_LOCK_BLOCK        0x0001
-#define P30_CMD_UNLOCK_BLOCK      0x00D0
-#define P30_CMD_LOCK_DOWN_BLOCK   0x002F
-
-// PROTECTION Commands
-#define P30_CMD_PROGRAM_PROTECTION_REGISTER_SETUP  0x00C0
-
-// CONFIGURATION Commands
-#define P30_CMD_READ_CONFIGURATION_REGISTER_SETUP  0x0060
-#define P30_CMD_READ_CONFIGURATION_REGISTER        0x0003
-
-#endif /* __NOR_FLASH_H__ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
deleted file mode 100644
index 254b8937e210..000000000000
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlash.c
+++ /dev/null
@@ -1,956 +0,0 @@
-/** @file  NorFlash.c
-
-  Copyright (c) 2011 - 2020, Arm Limited. All rights reserved.<BR>
-  Copyright (c) 2020, Linaro, Ltd. All rights reserved.<BR>
-
-  SPDX-License-Identifier: BSD-2-Clause-Patent
-
-**/
-
-#include <Library/BaseMemoryLib.h>
-
-#include "NorFlash.h"
-
-//
-// Global variable declarations
-//
-extern NOR_FLASH_INSTANCE  **mNorFlashInstances;
-extern UINT32              mNorFlashDeviceCount;
-
-UINT32
-NorFlashReadStatusRegister (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               SR_Address
-  )
-{
-  // Prepare to read the status register
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
-  return MmioRead32 (Instance->DeviceBaseAddress);
-}
-
-STATIC
-BOOLEAN
-NorFlashBlockIsLocked (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  UINT32  LockStatus;
-
-  // Send command for reading device id
-  SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
-
-  // Read block lock status
-  LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2));
-
-  // Decode block lock status
-  LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus);
-
-  if ((LockStatus & 0x2) != 0) {
-    DEBUG ((DEBUG_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
-  }
-
-  return ((LockStatus & 0x1) != 0);
-}
-
-STATIC
-EFI_STATUS
-NorFlashUnlockSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  UINT32  LockStatus;
-
-  // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
-  // and to protect shared data structures.
-
-  if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
-    do {
-      // Request a lock setup
-      SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
-
-      // Request an unlock
-      SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
-
-      // Send command for reading device id
-      SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
-
-      // Read block lock status
-      LockStatus = MmioRead32 (CREATE_NOR_ADDRESS (BlockAddress, 2));
-
-      // Decode block lock status
-      LockStatus = FOLD_32BIT_INTO_16BIT (LockStatus);
-    } while ((LockStatus & 0x1) == 1);
-  } else {
-    // Request a lock setup
-    SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
-
-    // Request an unlock
-    SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
-
-    // Wait until the status register gives us the all clear
-    do {
-      LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
-    } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-  }
-
-  // Put device back into Read Array mode
-  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
-
-  DEBUG ((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress));
-
-  return EFI_SUCCESS;
-}
-
-STATIC
-EFI_STATUS
-NorFlashUnlockSingleBlockIfNecessary (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  EFI_STATUS  Status;
-
-  Status = EFI_SUCCESS;
-
-  if (NorFlashBlockIsLocked (Instance, BlockAddress)) {
-    Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
-  }
-
-  return Status;
-}
-
-/**
- * The following function presumes that the block has already been unlocked.
- **/
-EFI_STATUS
-NorFlashEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  EFI_STATUS  Status;
-  UINT32      StatusRegister;
-
-  Status = EFI_SUCCESS;
-
-  // Request a block erase and then confirm it
-  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
-  SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
-
-  // Wait until the status register gives us the all clear
-  do {
-    StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
-  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
-  if (StatusRegister & P30_SR_BIT_VPP) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_ERASE) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
-    // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
-    DEBUG ((DEBUG_INFO, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
-    Status = EFI_WRITE_PROTECTED;
-  }
-
-  if (EFI_ERROR (Status)) {
-    // Clear the Status Register
-    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
-  }
-
-  // Put device back into Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
-  return Status;
-}
-
-STATIC
-EFI_STATUS
-NorFlashWriteSingleWord (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               WordAddress,
-  IN UINT32              WriteData
-  )
-{
-  EFI_STATUS  Status;
-  UINT32      StatusRegister;
-
-  Status = EFI_SUCCESS;
-
-  // Request a write single word command
-  SEND_NOR_COMMAND (WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
-
-  // Store the word into NOR Flash;
-  MmioWrite32 (WordAddress, WriteData);
-
-  // Wait for the write to complete and then check for any errors; i.e. check the Status Register
-  do {
-    // Prepare to read the status register
-    StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
-    // The chip is busy while the WRITE bit is not asserted
-  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
-  // Perform a full status check:
-  // Mask the relevant bits of Status Register.
-  // Everything should be zero, if not, we have a problem
-
-  if (StatusRegister & P30_SR_BIT_VPP) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n", WordAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_PROGRAM) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n", WordAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n", WordAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (!EFI_ERROR (Status)) {
-    // Clear the Status Register
-    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
-  }
-
-  // Put device back into Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
-  return Status;
-}
-
-/*
- * Writes data to the NOR Flash using the Buffered Programming method.
- *
- * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
- * Therefore this function will only handle buffers up to 32 words or 128 bytes.
- * To deal with larger buffers, call this function again.
- *
- * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
- * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
- *
- * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
- * then programming time is doubled and power consumption is increased.
- * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
- * i.e. the last 4 bits of the target start address must be zero: 0x......00
- */
-STATIC
-EFI_STATUS
-NorFlashWriteBuffer (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               TargetAddress,
-  IN UINTN               BufferSizeInBytes,
-  IN UINT32              *Buffer
-  )
-{
-  EFI_STATUS       Status;
-  UINTN            BufferSizeInWords;
-  UINTN            Count;
-  volatile UINT32  *Data;
-  UINTN            WaitForBuffer;
-  BOOLEAN          BufferAvailable;
-  UINT32           StatusRegister;
-
-  WaitForBuffer   = MAX_BUFFERED_PROG_ITERATIONS;
-  BufferAvailable = FALSE;
-
-  // Check that the target address does not cross a 32-word boundary.
-  if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
-    return EFI_INVALID_PARAMETER;
-  }
-
-  // Check there are some data to program
-  if (BufferSizeInBytes == 0) {
-    return EFI_BUFFER_TOO_SMALL;
-  }
-
-  // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
-  if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // Check that the buffer size is a multiple of 32-bit words
-  if ((BufferSizeInBytes % 4) != 0) {
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // Pre-programming conditions checked, now start the algorithm.
-
-  // Prepare the data destination address
-  Data = (UINT32 *)TargetAddress;
-
-  // Check the availability of the buffer
-  do {
-    // Issue the Buffered Program Setup command
-    SEND_NOR_COMMAND (TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
-
-    // Read back the status register bit#7 from the same address
-    if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
-      BufferAvailable = TRUE;
-    }
-
-    // Update the loop counter
-    WaitForBuffer--;
-  } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
-
-  // The buffer was not available for writing
-  if (WaitForBuffer == 0) {
-    Status = EFI_DEVICE_ERROR;
-    goto EXIT;
-  }
-
-  // From now on we work in 32-bit words
-  BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
-
-  // Write the word count, which is (buffer_size_in_words - 1),
-  // because word count 0 means one word.
-  SEND_NOR_COMMAND (TargetAddress, 0, (BufferSizeInWords - 1));
-
-  // Write the data to the NOR Flash, advancing each address by 4 bytes
-  for (Count = 0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
-    MmioWrite32 ((UINTN)Data, *Buffer);
-  }
-
-  // Issue the Buffered Program Confirm command, to start the programming operation
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
-
-  // Wait for the write to complete and then check for any errors; i.e. check the Status Register
-  do {
-    StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
-    // The chip is busy while the WRITE bit is not asserted
-  } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
-
-  // Perform a full status check:
-  // Mask the relevant bits of Status Register.
-  // Everything should be zero, if not, we have a problem
-
-  Status = EFI_SUCCESS;
-
-  if (StatusRegister & P30_SR_BIT_VPP) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_PROGRAM) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n", TargetAddress));
-    Status = EFI_DEVICE_ERROR;
-  }
-
-  if (!EFI_ERROR (Status)) {
-    // Clear the Status Register
-    SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
-  }
-
-EXIT:
-  // Put device back into Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
-  return Status;
-}
-
-EFI_STATUS
-NorFlashWriteBlocks (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINTN               BufferSizeInBytes,
-  IN VOID                *Buffer
-  )
-{
-  UINT32      *pWriteBuffer;
-  EFI_STATUS  Status;
-  EFI_LBA     CurrentBlock;
-  UINT32      BlockSizeInWords;
-  UINT32      NumBlocks;
-  UINT32      BlockCount;
-
-  Status = EFI_SUCCESS;
-
-  // The buffer must be valid
-  if (Buffer == NULL) {
-    return EFI_INVALID_PARAMETER;
-  }
-
-  if (Instance->Media.ReadOnly == TRUE) {
-    return EFI_WRITE_PROTECTED;
-  }
-
-  // We must have some bytes to read
-  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
-  if (BufferSizeInBytes == 0) {
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // The size of the buffer must be a multiple of the block size
-  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
-  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // All blocks must be within the device
-  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
-
-  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
-
-  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
-    return EFI_INVALID_PARAMETER;
-  }
-
-  BlockSizeInWords = Instance->Media.BlockSize / 4;
-
-  // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
-  // to a proper data type, so use *ReadBuffer
-  pWriteBuffer = (UINT32 *)Buffer;
-
-  CurrentBlock = Lba;
-  for (BlockCount = 0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
-    DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
-
-    Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
-
-    if (EFI_ERROR (Status)) {
-      break;
-    }
-  }
-
-  DEBUG ((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
-  return Status;
-}
-
-#define BOTH_ALIGNED(a, b, align)  ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0)
-
-/**
-  Copy Length bytes from Source to Destination, using aligned accesses only.
-  Note that this implementation uses memcpy() semantics rather then memmove()
-  semantics, i.e., SourceBuffer and DestinationBuffer should not overlap.
-
-  @param  DestinationBuffer The target of the copy request.
-  @param  SourceBuffer      The place to copy from.
-  @param  Length            The number of bytes to copy.
-
-  @return Destination
-
-**/
-STATIC
-VOID *
-AlignedCopyMem (
-  OUT     VOID        *DestinationBuffer,
-  IN      CONST VOID  *SourceBuffer,
-  IN      UINTN       Length
-  )
-{
-  UINT8         *Destination8;
-  CONST UINT8   *Source8;
-  UINT32        *Destination32;
-  CONST UINT32  *Source32;
-  UINT64        *Destination64;
-  CONST UINT64  *Source64;
-
-  if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 8) && (Length >= 8)) {
-    Destination64 = DestinationBuffer;
-    Source64      = SourceBuffer;
-    while (Length >= 8) {
-      *Destination64++ = *Source64++;
-      Length          -= 8;
-    }
-
-    Destination8 = (UINT8 *)Destination64;
-    Source8      = (CONST UINT8 *)Source64;
-  } else if (BOTH_ALIGNED (DestinationBuffer, SourceBuffer, 4) && (Length >= 4)) {
-    Destination32 = DestinationBuffer;
-    Source32      = SourceBuffer;
-    while (Length >= 4) {
-      *Destination32++ = *Source32++;
-      Length          -= 4;
-    }
-
-    Destination8 = (UINT8 *)Destination32;
-    Source8      = (CONST UINT8 *)Source32;
-  } else {
-    Destination8 = DestinationBuffer;
-    Source8      = SourceBuffer;
-  }
-
-  while (Length-- != 0) {
-    *Destination8++ = *Source8++;
-  }
-
-  return DestinationBuffer;
-}
-
-EFI_STATUS
-NorFlashReadBlocks (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINTN               BufferSizeInBytes,
-  OUT VOID               *Buffer
-  )
-{
-  UINT32  NumBlocks;
-  UINTN   StartAddress;
-
-  DEBUG ((
-    DEBUG_BLKIO,
-    "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n",
-    BufferSizeInBytes,
-    Instance->Media.BlockSize,
-    Instance->Media.LastBlock,
-    Lba
-    ));
-
-  // The buffer must be valid
-  if (Buffer == NULL) {
-    return EFI_INVALID_PARAMETER;
-  }
-
-  // Return if we have not any byte to read
-  if (BufferSizeInBytes == 0) {
-    return EFI_SUCCESS;
-  }
-
-  // The size of the buffer must be a multiple of the block size
-  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // All blocks must be within the device
-  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
-
-  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
-    DEBUG ((DEBUG_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
-    return EFI_INVALID_PARAMETER;
-  }
-
-  // Get the address to start reading from
-  StartAddress = GET_NOR_BLOCK_ADDRESS (
-                   Instance->RegionBaseAddress,
-                   Lba,
-                   Instance->Media.BlockSize
-                   );
-
-  // Put the device into Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
-  // Readout the data
-  AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes);
-
-  return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NorFlashRead (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINTN               Offset,
-  IN UINTN               BufferSizeInBytes,
-  OUT VOID               *Buffer
-  )
-{
-  UINTN  StartAddress;
-
-  // The buffer must be valid
-  if (Buffer == NULL) {
-    return EFI_INVALID_PARAMETER;
-  }
-
-  // Return if we have not any byte to read
-  if (BufferSizeInBytes == 0) {
-    return EFI_SUCCESS;
-  }
-
-  if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) {
-    DEBUG ((DEBUG_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n"));
-    return EFI_INVALID_PARAMETER;
-  }
-
-  // Get the address to start reading from
-  StartAddress = GET_NOR_BLOCK_ADDRESS (
-                   Instance->RegionBaseAddress,
-                   Lba,
-                   Instance->Media.BlockSize
-                   );
-
-  // Put the device into Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-
-  // Readout the data
-  AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes);
-
-  return EFI_SUCCESS;
-}
-
-/*
-  Write a full or portion of a block. It must not span block boundaries; that is,
-  Offset + *NumBytes <= Instance->Media.BlockSize.
-*/
-EFI_STATUS
-NorFlashWriteSingleBlock (
-  IN        NOR_FLASH_INSTANCE  *Instance,
-  IN        EFI_LBA             Lba,
-  IN        UINTN               Offset,
-  IN OUT    UINTN               *NumBytes,
-  IN        UINT8               *Buffer
-  )
-{
-  EFI_STATUS  TempStatus;
-  UINT32      Tmp;
-  UINT32      TmpBuf;
-  UINT32      WordToWrite;
-  UINT32      Mask;
-  BOOLEAN     DoErase;
-  UINTN       BytesToWrite;
-  UINTN       CurOffset;
-  UINTN       WordAddr;
-  UINTN       BlockSize;
-  UINTN       BlockAddress;
-  UINTN       PrevBlockAddress;
-
-  PrevBlockAddress = 0;
-
-  DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer));
-
-  // Detect WriteDisabled state
-  if (Instance->Media.ReadOnly == TRUE) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n"));
-    // It is in WriteDisabled state, return an error right away
-    return EFI_ACCESS_DENIED;
-  }
-
-  // Cache the block size to avoid de-referencing pointers all the time
-  BlockSize = Instance->Media.BlockSize;
-
-  // The write must not span block boundaries.
-  // We need to check each variable individually because adding two large values together overflows.
-  if ((Offset               >= BlockSize) ||
-      (*NumBytes            >  BlockSize) ||
-      ((Offset + *NumBytes) >  BlockSize))
-  {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize));
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // We must have some bytes to write
-  if (*NumBytes == 0) {
-    DEBUG ((DEBUG_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize));
-    return EFI_BAD_BUFFER_SIZE;
-  }
-
-  // Pick 128bytes as a good start for word operations as opposed to erasing the
-  // block and writing the data regardless if an erase is really needed.
-  // It looks like most individual NV variable writes are smaller than 128bytes.
-  if (*NumBytes <= 128) {
-    // Check to see if we need to erase before programming the data into NOR.
-    // If the destination bits are only changing from 1s to 0s we can just write.
-    // After a block is erased all bits in the block is set to 1.
-    // If any byte requires us to erase we just give up and rewrite all of it.
-    DoErase      = FALSE;
-    BytesToWrite = *NumBytes;
-    CurOffset    = Offset;
-
-    while (BytesToWrite > 0) {
-      // Read full word from NOR, splice as required. A word is the smallest
-      // unit we can write.
-      TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof (Tmp), &Tmp);
-      if (EFI_ERROR (TempStatus)) {
-        return EFI_DEVICE_ERROR;
-      }
-
-      // Physical address of word in NOR to write.
-      WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS (
-                                          Instance->RegionBaseAddress,
-                                          Lba,
-                                          BlockSize
-                                          );
-      // The word of data that is to be written.
-      TmpBuf = *((UINT32 *)(Buffer + (*NumBytes - BytesToWrite)));
-
-      // First do word aligned chunks.
-      if ((CurOffset & 0x3) == 0) {
-        if (BytesToWrite >= 4) {
-          // Is the destination still in 'erased' state?
-          if (~Tmp != 0) {
-            // Check to see if we are only changing bits to zero.
-            if ((Tmp ^ TmpBuf) & TmpBuf) {
-              DoErase = TRUE;
-              break;
-            }
-          }
-
-          // Write this word to NOR
-          WordToWrite   = TmpBuf;
-          CurOffset    += sizeof (TmpBuf);
-          BytesToWrite -= sizeof (TmpBuf);
-        } else {
-          // BytesToWrite < 4. Do small writes and left-overs
-          Mask = ~((~0) << (BytesToWrite * 8));
-          // Mask out the bytes we want.
-          TmpBuf &= Mask;
-          // Is the destination still in 'erased' state?
-          if ((Tmp & Mask) != Mask) {
-            // Check to see if we are only changing bits to zero.
-            if ((Tmp ^ TmpBuf) & TmpBuf) {
-              DoErase = TRUE;
-              break;
-            }
-          }
-
-          // Merge old and new data. Write merged word to NOR
-          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
-          CurOffset   += BytesToWrite;
-          BytesToWrite = 0;
-        }
-      } else {
-        // Do multiple words, but starting unaligned.
-        if (BytesToWrite > (4 - (CurOffset & 0x3))) {
-          Mask = ((~0) << ((CurOffset & 0x3) * 8));
-          // Mask out the bytes we want.
-          TmpBuf &= Mask;
-          // Is the destination still in 'erased' state?
-          if ((Tmp & Mask) != Mask) {
-            // Check to see if we are only changing bits to zero.
-            if ((Tmp ^ TmpBuf) & TmpBuf) {
-              DoErase = TRUE;
-              break;
-            }
-          }
-
-          // Merge old and new data. Write merged word to NOR
-          WordToWrite   = (Tmp & ~Mask) | TmpBuf;
-          BytesToWrite -= (4 - (CurOffset & 0x3));
-          CurOffset    += (4 - (CurOffset & 0x3));
-        } else {
-          // Unaligned and fits in one word.
-          Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
-          // Mask out the bytes we want.
-          TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
-          // Is the destination still in 'erased' state?
-          if ((Tmp & Mask) != Mask) {
-            // Check to see if we are only changing bits to zero.
-            if ((Tmp ^ TmpBuf) & TmpBuf) {
-              DoErase = TRUE;
-              break;
-            }
-          }
-
-          // Merge old and new data. Write merged word to NOR
-          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
-          CurOffset   += BytesToWrite;
-          BytesToWrite = 0;
-        }
-      }
-
-      //
-      // Write the word to NOR.
-      //
-
-      BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize);
-      if (BlockAddress != PrevBlockAddress) {
-        TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
-        if (EFI_ERROR (TempStatus)) {
-          return EFI_DEVICE_ERROR;
-        }
-
-        PrevBlockAddress = BlockAddress;
-      }
-
-      TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
-      if (EFI_ERROR (TempStatus)) {
-        return EFI_DEVICE_ERROR;
-      }
-    }
-
-    // Exit if we got here and could write all the data. Otherwise do the
-    // Erase-Write cycle.
-    if (!DoErase) {
-      return EFI_SUCCESS;
-    }
-  }
-
-  // Check we did get some memory. Buffer is BlockSize.
-  if (Instance->ShadowBuffer == NULL) {
-    DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
-    return EFI_DEVICE_ERROR;
-  }
-
-  // Read NOR Flash data into shadow buffer
-  TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
-  if (EFI_ERROR (TempStatus)) {
-    // Return one of the pre-approved error statuses
-    return EFI_DEVICE_ERROR;
-  }
-
-  // Put the data at the appropriate location inside the buffer area
-  CopyMem ((VOID *)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes);
-
-  // Write the modified buffer back to the NorFlash
-  TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
-  if (EFI_ERROR (TempStatus)) {
-    // Return one of the pre-approved error statuses
-    return EFI_DEVICE_ERROR;
-  }
-
-  return EFI_SUCCESS;
-}
-
-EFI_STATUS
-NorFlashReset (
-  IN  NOR_FLASH_INSTANCE  *Instance
-  )
-{
-  // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
-  SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
-  return EFI_SUCCESS;
-}
-
-/**
- * This function unlock and erase an entire NOR Flash block.
-**/
-EFI_STATUS
-NorFlashUnlockAndEraseSingleBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN UINTN               BlockAddress
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       Index;
-  EFI_TPL     OriginalTPL;
-
-  NorFlashLock (&OriginalTPL);
-
-  Index = 0;
-  // The block erase might fail a first time (SW bug ?). Retry it ...
-  do {
-    // Unlock the block if we have to
-    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
-    if (EFI_ERROR (Status)) {
-      break;
-    }
-
-    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
-    Index++;
-  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
-
-  if (Index == NOR_FLASH_ERASE_RETRY) {
-    DEBUG ((DEBUG_ERROR, "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress, Index));
-  }
-
-  NorFlashUnlock (OriginalTPL);
-
-  return Status;
-}
-
-EFI_STATUS
-NorFlashWriteFullBlock (
-  IN NOR_FLASH_INSTANCE  *Instance,
-  IN EFI_LBA             Lba,
-  IN UINT32              *DataBuffer,
-  IN UINT32              BlockSizeInWords
-  )
-{
-  EFI_STATUS  Status;
-  UINTN       WordAddress;
-  UINT32      WordIndex;
-  UINTN       BufferIndex;
-  UINTN       BlockAddress;
-  UINTN       BuffersInBlock;
-  UINTN       RemainingWords;
-  EFI_TPL     OriginalTPL;
-  UINTN       Cnt;
-
-  Status = EFI_SUCCESS;
-
-  // Get the physical address of the block
-  BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
-
-  // Start writing from the first address at the start of the block
-  WordAddress = BlockAddress;
-
-  NorFlashLock (&OriginalTPL);
-
-  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
-    goto EXIT;
-  }
-
-  // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
-
-  // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
-  if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
-    // First, break the entire block into buffer-sized chunks.
-    BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
-
-    // Then feed each buffer chunk to the NOR Flash
-    // If a buffer does not contain any data, don't write it.
-    for (BufferIndex = 0;
-         BufferIndex < BuffersInBlock;
-         BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
-         )
-    {
-      // Check the buffer to see if it contains any data (not set all 1s).
-      for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
-        if (~DataBuffer[Cnt] != 0 ) {
-          // Some data found, write the buffer.
-          Status = NorFlashWriteBuffer (
-                     Instance,
-                     WordAddress,
-                     P30_MAX_BUFFER_SIZE_IN_BYTES,
-                     DataBuffer
-                     );
-          if (EFI_ERROR (Status)) {
-            goto EXIT;
-          }
-
-          break;
-        }
-      }
-    }
-
-    // Finally, finish off any remaining words that are less than the maximum size of the buffer
-    RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
-
-    if (RemainingWords != 0) {
-      Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  } else {
-    // For now, use the single word programming algorithm
-    // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
-    // i.e. which ends in the range 0x......01 - 0x......7F.
-    for (WordIndex = 0; WordIndex < BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
-      Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
-      if (EFI_ERROR (Status)) {
-        goto EXIT;
-      }
-    }
-  }
-
-EXIT:
-  NorFlashUnlock (OriginalTPL);
-
-  if (EFI_ERROR (Status)) {
-    DEBUG ((DEBUG_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
-  }
-
-  return Status;
-}
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
index a6c73312c596..4e7e88610200 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashBlockIoDxe.c
@@ -9,7 +9,6 @@
 #include <Library/BaseMemoryLib.h>
 #include <Library/UefiBootServicesTableLib.h>
 
-#include "NorFlash.h"
 #include "NorFlashCommon.h"
 
 //
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index 4bad6e9b2a6b..1c12572ab663 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -14,7 +14,6 @@
 #include <Library/HobLib.h>
 #include <Library/DxeServicesTableLib.h>
 
-#include "NorFlash.h"
 #include "NorFlashCommon.h"
 
 STATIC EFI_EVENT  mNorFlashVirtualAddrChangeEvent;
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
index f9f2856e0c81..e48c258a3008 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashFvb.c
@@ -18,7 +18,6 @@
 #include <Guid/SystemNvDataGuid.h>
 #include <Guid/NvVarStoreFormatted.h>
 
-#include "NorFlash.h"
 #include "NorFlashCommon.h"
 
 extern UINTN  mFlashNvStorageVariableBase;
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index 5bff524e5e18..85198b98e8a8 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -11,7 +11,6 @@
 #include <Library/MemoryAllocationLib.h>
 #include <Library/MmServicesTableLib.h>
 
-#include "NorFlash.h"
 #include "NorFlashCommon.h"
 
 //
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119324): https://edk2.groups.io/g/devel/message/119324
Mute This Topic: https://groups.io/mt/106365459/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 10/17] Platform/ARM: Add HostControllerBaseAddress variable
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (8 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 09/17] Platform/ARM/NorFlashDxe: Switch from NorFlash.c to NorFlashDeviceLib Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 11/17] Platform/ARM/NorFlashDxe: Fix memory leak in NorFlashCreateInstance() Sahil Kaushal
                   ` (8 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This variable holds the QSPI controller's base address.
It is defined in ARM.dec as well with the default value of 0x0.
In case a platform is not using it, they can just ignore this
variable and the default value of 0x0 will be propogated and
the variable will not be used.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/ARM.dec                                      |  3 ++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf          |  3 ++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf |  2 ++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h         |  1 +
 Platform/ARM/Include/Library/NorFlashDeviceLib.h          | 11 ++++---
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c            | 34 +++++++++++++++++---
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c   | 12 ++++---
 7 files changed, 54 insertions(+), 12 deletions(-)

diff --git a/Platform/ARM/ARM.dec b/Platform/ARM/ARM.dec
index 86d1fcb4878e..a5e28c372903 100644
--- a/Platform/ARM/ARM.dec
+++ b/Platform/ARM/ARM.dec
@@ -26,3 +26,6 @@ [Guids]
 
 [PcdsFeatureFlag.common]
   gPlatformArmTokenSpaceGuid.PcdNorFlashCheckBlockLocked|FALSE|BOOLEAN|0x0000001
+
+[PcdsFixedAtBuild.common]
+  gPlatformArmTokenSpaceGuid.PcdNorFlashRegBaseAddress|0x0|UINT32|0x00000002
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
index de160025b632..6522968d6c5a 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
@@ -65,5 +65,8 @@ [Pcd.common]
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
 
+[FixedPcd]
+  gPlatformArmTokenSpaceGuid.PcdNorFlashRegBaseAddress
+
 [Depex]
   gEfiCpuArchProtocolGuid
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
index d9e7de07165c..eb86d423f106 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
@@ -59,5 +59,7 @@ [FixedPcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
 
+  gPlatformArmTokenSpaceGuid.PcdNorFlashRegBaseAddress
+
 [Depex]
   TRUE
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
index 7fcb949843e8..98464e4868b1 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashCommon.h
@@ -34,6 +34,7 @@
 //
 EFI_STATUS
 NorFlashCreateInstance (
+  IN UINTN                HostRegisterBase,
   IN UINTN                NorFlashDeviceBase,
   IN UINTN                NorFlashRegionBase,
   IN UINTN                NorFlashSize,
diff --git a/Platform/ARM/Include/Library/NorFlashDeviceLib.h b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
index 6833c1ddc456..348136630e78 100644
--- a/Platform/ARM/Include/Library/NorFlashDeviceLib.h
+++ b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
@@ -36,10 +36,13 @@ struct _NOR_FLASH_INSTANCE {
   UINT32                                 Signature; ///< NOR Flash instance signature.
   EFI_HANDLE                             Handle;    ///< NOR Flash instance handle.
 
-  UINTN                                  DeviceBaseAddress; ///< NOR Flash device base address.
-  UINTN                                  RegionBaseAddress; ///< NOR Flash region base address.
-  UINTN                                  Size;              ///< NOR Flash region size.
-  EFI_LBA                                StartLba;          ///< Region start LBA.
+  UINTN                                  HostControllerBaseAddress; ///< NOR Flash host controller base address.
+                                                                    ///< This field is optional if no host
+                                                                    ///< controller is present.
+  UINTN                                  DeviceBaseAddress;         ///< NOR Flash device base address.
+  UINTN                                  RegionBaseAddress;         ///< NOR Flash region base address.
+  UINTN                                  Size;                      ///< NOR Flash region size.
+  EFI_LBA                                StartLba;                  ///< Region start LBA.
 
   EFI_BLOCK_IO_PROTOCOL                  BlockIoProtocol; ///< Instance's Block IO protocol handle.
   EFI_BLOCK_IO_MEDIA                     Media;           ///< Instance's  Media information.
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index 1c12572ab663..e01b05d91978 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -1,6 +1,6 @@
 /** @file  NorFlashDxe.c
 
-  Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.<BR>
+  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
 
@@ -30,6 +30,7 @@ NOR_FLASH_INSTANCE  mNorFlashInstanceTemplate = {
   NOR_FLASH_SIGNATURE, // Signature
   NULL,                // Handle ... NEED TO BE FILLED
 
+  0, // Optional HostControllerBaseAddress  ... NEED TO BE FILLED
   0, // DeviceBaseAddress ... NEED TO BE FILLED
   0, // RegionBaseAddress ... NEED TO BE FILLED
   0, // Size ... NEED TO BE FILLED
@@ -99,6 +100,7 @@ NOR_FLASH_INSTANCE  mNorFlashInstanceTemplate = {
 
 EFI_STATUS
 NorFlashCreateInstance (
+  IN UINTN                HostControllerBase,
   IN UINTN                NorFlashDeviceBase,
   IN UINTN                NorFlashRegionBase,
   IN UINTN                NorFlashSize,
@@ -118,9 +120,10 @@ NorFlashCreateInstance (
     return EFI_OUT_OF_RESOURCES;
   }
 
-  Instance->DeviceBaseAddress = NorFlashDeviceBase;
-  Instance->RegionBaseAddress = NorFlashRegionBase;
-  Instance->Size              = NorFlashSize;
+  Instance->HostControllerBaseAddress = HostControllerBase;
+  Instance->DeviceBaseAddress         = NorFlashDeviceBase;
+  Instance->RegionBaseAddress         = NorFlashRegionBase;
+  Instance->Size                      = NorFlashSize;
 
   Instance->BlockIoProtocol.Media = &Instance->Media;
   Instance->Media.MediaId         = Index;
@@ -184,6 +187,27 @@ NorFlashInitialise (
   UINT32                 Index;
   NOR_FLASH_DESCRIPTION  *NorFlashDevices;
   BOOLEAN                ContainVariableStorage;
+  EFI_PHYSICAL_ADDRESS   HostControllerBaseAddress;
+
+  // Host controller base address region if available
+  HostControllerBaseAddress = PcdGet32 (PcdNorFlashRegBaseAddress);
+
+  if (HostControllerBaseAddress != 0) {
+    Status = gDS->AddMemorySpace (
+                    EfiGcdMemoryTypeMemoryMappedIo,
+                    HostControllerBaseAddress,
+                    SIZE_4KB,
+                    EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
+                    );
+    ASSERT_EFI_ERROR (Status);
+
+    Status = gDS->SetMemorySpaceAttributes (
+                    HostControllerBaseAddress,
+                    SIZE_4KB,
+                    EFI_MEMORY_UC | EFI_MEMORY_RUNTIME
+                    );
+    ASSERT_EFI_ERROR (Status);
+  }
 
   Status = NorFlashPlatformInitialization ();
   if (EFI_ERROR (Status)) {
@@ -215,6 +239,7 @@ NorFlashInitialise (
     }
 
     Status = NorFlashCreateInstance (
+               HostControllerBaseAddress,
                NorFlashDevices[Index].DeviceBaseAddress,
                NorFlashDevices[Index].RegionBaseAddress,
                NorFlashDevices[Index].Size,
@@ -368,6 +393,7 @@ NorFlashVirtualNotifyEvent (
   UINTN  Index;
 
   for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
+    EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->HostControllerBaseAddress);
     EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->DeviceBaseAddress);
     EfiConvertPointer (0x0, (VOID **)&mNorFlashInstances[Index]->RegionBaseAddress);
 
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index 85198b98e8a8..16fe3762e125 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -1,6 +1,6 @@
 /** @file  NorFlashStandaloneMm.c
 
-  Copyright (c) 2011 - 2021, Arm Limited. All rights reserved.<BR>
+  Copyright (c) 2011 - 2024, Arm Limited. All rights reserved.<BR>
   Copyright (c) 2020, Linaro, Ltd. All rights reserved.<BR>
 
   SPDX-License-Identifier: BSD-2-Clause-Patent
@@ -24,6 +24,7 @@ NOR_FLASH_INSTANCE  mNorFlashInstanceTemplate = {
   NOR_FLASH_SIGNATURE, // Signature
   NULL,                // Handle ... NEED TO BE FILLED
 
+  0, // Optional HostControllerBaseAddress  ... NEED TO BE FILLED
   0, // DeviceBaseAddress ... NEED TO BE FILLED
   0, // RegionBaseAddress ... NEED TO BE FILLED
   0, // Size ... NEED TO BE FILLED
@@ -93,6 +94,7 @@ NOR_FLASH_INSTANCE  mNorFlashInstanceTemplate = {
 
 EFI_STATUS
 NorFlashCreateInstance (
+  IN UINTN                HostControllerBase,
   IN UINTN                NorFlashDeviceBase,
   IN UINTN                NorFlashRegionBase,
   IN UINTN                NorFlashSize,
@@ -112,9 +114,10 @@ NorFlashCreateInstance (
     return EFI_OUT_OF_RESOURCES;
   }
 
-  Instance->DeviceBaseAddress = NorFlashDeviceBase;
-  Instance->RegionBaseAddress = NorFlashRegionBase;
-  Instance->Size              = NorFlashSize;
+  Instance->HostControllerBaseAddress = HostControllerBase;
+  Instance->DeviceBaseAddress         = NorFlashDeviceBase;
+  Instance->RegionBaseAddress         = NorFlashRegionBase;
+  Instance->Size                      = NorFlashSize;
 
   Instance->BlockIoProtocol.Media = &Instance->Media;
   Instance->Media.MediaId         = Index;
@@ -194,6 +197,7 @@ NorFlashInitialise (
     }
 
     Status = NorFlashCreateInstance (
+               PcdGet32 (PcdNorFlashRegBaseAddress),
                NorFlashDevices[Index].DeviceBaseAddress,
                NorFlashDevices[Index].RegionBaseAddress,
                NorFlashDevices[Index].Size,
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119325): https://edk2.groups.io/g/devel/message/119325
Mute This Topic: https://groups.io/mt/106365460/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 11/17] Platform/ARM/NorFlashDxe: Fix memory leak in NorFlashCreateInstance()
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (9 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 10/17] Platform/ARM: Add HostControllerBaseAddress variable Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 12/17] Platform/ARM: Add optional provision to fetch and print NOR Flash info Sahil Kaushal
                   ` (7 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch adds error_handler1 and error_handler2 labels in
NorFlashCreateInstance() function to handle the cleanup.

error_handler1: Frees just the Instance structure as the
ShadowBuffer is not allocated yet.

error_handler2: Frees both Instance and Instance->ShadowBuffer.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c          | 16 +++++++++++-----
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c | 17 ++++++++++++-----
 2 files changed, 23 insertions(+), 10 deletions(-)

diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index e01b05d91978..ebe985bdf02b 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -135,7 +135,8 @@ NorFlashCreateInstance (
 
   Instance->ShadowBuffer = AllocateRuntimePool (BlockSize);
   if (Instance->ShadowBuffer == NULL) {
-    return EFI_OUT_OF_RESOURCES;
+    Status = EFI_OUT_OF_RESOURCES;
+    goto error_handler1;
   }
 
   if (SupportFvb) {
@@ -152,8 +153,7 @@ NorFlashCreateInstance (
                     NULL
                     );
     if (EFI_ERROR (Status)) {
-      FreePool (Instance);
-      return Status;
+      goto error_handler2;
     }
   } else {
     Status = gBS->InstallMultipleProtocolInterfaces (
@@ -167,13 +167,19 @@ NorFlashCreateInstance (
                     NULL
                     );
     if (EFI_ERROR (Status)) {
-      FreePool (Instance);
-      return Status;
+      goto error_handler2;
     }
   }
 
   *NorFlashInstance = Instance;
   return Status;
+
+error_handler2:
+  FreePool (Instance->ShadowBuffer);
+
+error_handler1:
+  FreePool (Instance);
+  return Status;
 }
 
 EFI_STATUS
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index 16fe3762e125..6bfbf58f6907 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -129,7 +129,8 @@ NorFlashCreateInstance (
 
   Instance->ShadowBuffer = AllocateRuntimePool (BlockSize);
   if (Instance->ShadowBuffer == NULL) {
-    return EFI_OUT_OF_RESOURCES;
+    Status = EFI_OUT_OF_RESOURCES;
+    goto error_handler1;
   }
 
   if (SupportFvb) {
@@ -142,17 +143,23 @@ NorFlashCreateInstance (
                       &Instance->FvbProtocol
                       );
     if (EFI_ERROR (Status)) {
-      FreePool (Instance);
-      return Status;
+      goto error_handler2;
     }
   } else {
     DEBUG ((DEBUG_ERROR, "standalone MM NOR Flash driver only support FVB.\n"));
-    FreePool (Instance);
-    return EFI_UNSUPPORTED;
+    Status = EFI_UNSUPPORTED;
+    goto error_handler2;
   }
 
   *NorFlashInstance = Instance;
   return Status;
+
+error_handler2:
+  FreePool (Instance->ShadowBuffer);
+
+error_handler1:
+  FreePool (Instance);
+  return Status;
 }
 
 EFI_STATUS
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119326): https://edk2.groups.io/g/devel/message/119326
Mute This Topic: https://groups.io/mt/106365462/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 12/17] Platform/ARM: Add optional provision to fetch and print NOR Flash info
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (10 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 11/17] Platform/ARM/NorFlashDxe: Fix memory leak in NorFlashCreateInstance() Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 13/17] Silicon/ARM/NeoverseN1Soc: Enable SCP QSPI flash region Sahil Kaushal
                   ` (6 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This patch adds an optional functionality in NorFlashDxe to fetch and
print NOR Flash information from NorFlashInfoLib using its JEDEC ID.

NOR Flash libraries will implement a function "NorFlashReadID" which
will fetch and return JEDEC ID. This JEDEC ID can be then printed
along with the NOR Flash info by NorFlashInfoLib. If this functionality
is not needed then the function can just return EFI_UNSUPPORTED.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/SgiPkg/SgiPlatform.dsc.inc                          |  2 ++
 Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc                        |  2 ++
 Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc                     |  2 ++
 Platform/ARM/JunoPkg/ArmJuno.dsc                                 |  2 ++
 Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc                |  2 ++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf                 |  1 +
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf        |  1 +
 Platform/ARM/Include/Library/NorFlashDeviceLib.h                 | 17 +++++++++++++++++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c                   | 18 ++++++++++++++++++
 Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c          | 18 ++++++++++++++++++
 Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c | 18 ++++++++++++++++++
 11 files changed, 83 insertions(+)

diff --git a/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc b/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
index 3dcf422eab4b..107a5311b666 100644
--- a/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
+++ b/Platform/ARM/SgiPkg/SgiPlatform.dsc.inc
@@ -36,6 +36,8 @@ [LibraryClasses.common]
   LcdPlatformLib|Platform/ARM/SgiPkg/Library/HdLcdArmSgiLib/HdLcdArmSgiLib.inf
   NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/SgiPkg/Library/NorFlashLib/NorFlashLib.inf
+  # NOR flash identification support
+  NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
   HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf
   ResetSystemLib|ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf
   TimerLib|ArmPkg/Library/ArmArchTimerLib/ArmArchTimerLib.inf
diff --git a/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc b/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
index ab0e2a957a1b..19fd08dd7817 100644
--- a/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
+++ b/Platform/ARM/SgiPkg/SgiPlatformMm.dsc.inc
@@ -65,6 +65,8 @@ [LibraryClasses.common.MM_STANDALONE]
   IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf
   NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/SgiPkg/Library/NorFlashLib/StandaloneMmNorFlashLib.inf
+  # NOR flash identification support
+  NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
   OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf
   RngLib|MdePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
   PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf
diff --git a/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc b/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
index 70ff049d3248..f7f7b39bbf58 100644
--- a/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
+++ b/Platform/ARM/VExpressPkg/ArmVExpress.dsc.inc
@@ -95,6 +95,8 @@ [LibraryClasses.common]
   ArmPlatformSysConfigLib|Platform/ARM/VExpressPkg/Library/ArmVExpressSysConfigLib/ArmVExpressSysConfigLib.inf
   NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/VExpressPkg/Library/NorFlashArmVExpressLib/NorFlashArmVExpressLib.inf
+  # NOR flash identification support
+  NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
   ResetSystemLib|ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf
 
   # ARM PL031 RTC Driver
diff --git a/Platform/ARM/JunoPkg/ArmJuno.dsc b/Platform/ARM/JunoPkg/ArmJuno.dsc
index 81d2cbe4359f..1ca43b9e7dba 100644
--- a/Platform/ARM/JunoPkg/ArmJuno.dsc
+++ b/Platform/ARM/JunoPkg/ArmJuno.dsc
@@ -42,6 +42,8 @@ [LibraryClasses.common]
 
   NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/JunoPkg/Library/NorFlashJunoLib/NorFlashJunoLib.inf
+  # NOR flash identification support
+  NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
 
   CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf
   CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf
diff --git a/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc b/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
index a5805da49c92..a0a9d9a21a1b 100644
--- a/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
+++ b/Platform/ARM/VExpressPkg/PlatformStandaloneMm.dsc
@@ -102,6 +102,8 @@ [LibraryClasses.common.MM_STANDALONE]
 !if $(ENABLE_UEFI_SECURE_VARIABLE) == TRUE
   NorFlashDeviceLib|Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.inf
   NorFlashPlatformLib|Platform/ARM/VExpressPkg/Library/NorFlashArmVExpressLib/NorFlashStMmLib.inf
+  # NOR flash identification support
+  NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
   VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf
   VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
   AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
index 6522968d6c5a..4ab4d6a26926 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
@@ -35,6 +35,7 @@ [LibraryClasses]
   HobLib
   IoLib
   NorFlashDeviceLib
+  NorFlashInfoLib
   NorFlashPlatformLib
   UefiBootServicesTableLib
   UefiDriverEntryPoint
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
index eb86d423f106..8b583f77d927 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.inf
@@ -37,6 +37,7 @@ [LibraryClasses]
   MemoryAllocationLib
   MmServicesTableLib
   NorFlashDeviceLib
+  NorFlashInfoLib
   NorFlashPlatformLib
   StandaloneMmDriverEntryPoint
 
diff --git a/Platform/ARM/Include/Library/NorFlashDeviceLib.h b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
index 348136630e78..db5dfbf39b75 100644
--- a/Platform/ARM/Include/Library/NorFlashDeviceLib.h
+++ b/Platform/ARM/Include/Library/NorFlashDeviceLib.h
@@ -236,4 +236,21 @@ NorFlashUnlock (
   IN EFI_TPL  OriginalTPL
   );
 
+/**
+  Read JEDEC ID of NOR flash device.
+
+  @param[in]     Instance               NOR flash Instance of variable store region.
+  @param[out]    JedecId                JEDEC ID of NOR flash device.
+                                        Maximum length of JedecId can be upto 6 bytes
+  @retval        EFI_SUCCESS            The write is completed.
+  @retval        EFI_UNSUPPORTED        JEDEC ID retrieval not implemented.
+  @retval        EFI_DEVICE_ERROR       Failed to fetch JEDEC ID.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashReadId (
+  IN  NOR_FLASH_INSTANCE  *Instance,
+  OUT UINT8               *JedecId  // Maximum length of JedecId can be upto 6 bytes.
+  );
+
 #endif /* NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
index ebe985bdf02b..bfdcfcf557ed 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.c
@@ -9,6 +9,7 @@
 #include <Library/UefiLib.h>
 #include <Library/BaseMemoryLib.h>
 #include <Library/MemoryAllocationLib.h>
+#include <Library/NorFlashInfoLib.h>
 #include <Library/UefiBootServicesTableLib.h>
 #include <Library/PcdLib.h>
 #include <Library/HobLib.h>
@@ -112,6 +113,8 @@ NorFlashCreateInstance (
 {
   EFI_STATUS          Status;
   NOR_FLASH_INSTANCE  *Instance;
+  NOR_FLASH_INFO      *FlashInfo;
+  UINT8               JedecId[6];
 
   ASSERT (NorFlashInstance != NULL);
 
@@ -139,6 +142,21 @@ NorFlashCreateInstance (
     goto error_handler1;
   }
 
+  Status = NorFlashReadId (Instance, JedecId);
+  if (EFI_ERROR (Status)) {
+    if (Status != EFI_UNSUPPORTED) {
+      goto error_handler2;
+    }
+  } else {
+    Status = NorFlashGetInfo (JedecId, &FlashInfo, FALSE);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_WARN, "NorFlashCreateInstance: JedecID not supported\n"));
+    } else {
+      NorFlashPrintInfo (FlashInfo);
+      FreePool (FlashInfo);
+    }
+  }
+
   if (SupportFvb) {
     NorFlashFvbInitialize (Instance);
 
diff --git a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
index 6bfbf58f6907..828c09e5975d 100644
--- a/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
+++ b/Platform/ARM/Drivers/NorFlashDxe/NorFlashStandaloneMm.c
@@ -10,6 +10,7 @@
 #include <Library/BaseMemoryLib.h>
 #include <Library/MemoryAllocationLib.h>
 #include <Library/MmServicesTableLib.h>
+#include <Library/NorFlashInfoLib.h>
 
 #include "NorFlashCommon.h"
 
@@ -106,6 +107,8 @@ NorFlashCreateInstance (
 {
   EFI_STATUS          Status;
   NOR_FLASH_INSTANCE  *Instance;
+  NOR_FLASH_INFO      *FlashInfo;
+  UINT8               JedecId[6];
 
   ASSERT (NorFlashInstance != NULL);
 
@@ -133,6 +136,21 @@ NorFlashCreateInstance (
     goto error_handler1;
   }
 
+  Status = NorFlashReadId (Instance, JedecId);
+  if (EFI_ERROR (Status)) {
+    if (Status != EFI_UNSUPPORTED) {
+      goto error_handler2;
+    }
+  } else {
+    Status = NorFlashGetInfo (JedecId, &FlashInfo, FALSE);
+    if (EFI_ERROR (Status)) {
+      DEBUG ((DEBUG_WARN, "NorFlashCreateInstance: JedecID not supported\n"));
+    } else {
+      NorFlashPrintInfo (FlashInfo);
+      FreePool (FlashInfo);
+    }
+  }
+
   if (SupportFvb) {
     NorFlashFvbInitialize (Instance);
 
diff --git a/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c
index 5af085bdf493..da5df5b77cdb 100644
--- a/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c
+++ b/Platform/ARM/Library/P30NorFlashDeviceLib/P30NorFlashDeviceLib.c
@@ -951,3 +951,21 @@ NorFlashReset (
   SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
   return EFI_SUCCESS;
 }
+
+/**
+  Read JEDEC ID of NOR flash device.
+
+  @param[in]     Instance               NOR flash Instance of variable store region.
+  @param[out]    JedecId                JEDEC ID of NOR flash device.
+                                        Maximum length of JedecId can be upto 6 bytes.
+
+  @retval        EFI_UNSUPPORTED        JEDEC ID retrieval not implemented.
+**/
+EFI_STATUS
+NorFlashReadId (
+  IN  NOR_FLASH_INSTANCE  *Instance,
+  OUT UINT8               *JedecId
+  )
+{
+  return EFI_UNSUPPORTED;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119327): https://edk2.groups.io/g/devel/message/119327
Mute This Topic: https://groups.io/mt/106365463/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 13/17] Silicon/ARM/NeoverseN1Soc: Enable SCP QSPI flash region
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (11 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 12/17] Platform/ARM: Add optional provision to fetch and print NOR Flash info Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp Sahil Kaushal
                   ` (5 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Enable SCP QSPI flash region access by adding it in the PlatformLibMem.
This flash is shared between AP core and System Control Processor. The
lower addresses are used to store SCP and AP boot images and higher
addresses will be used for variable storage.

Signed-off-by: sahil <sahil@arm.com>
---
 Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h              | 7 +++++++
 Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c | 8 +++++++-
 2 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
index 5483e7bc5f68..2dae57a0f01a 100644
--- a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
+++ b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
@@ -4,6 +4,9 @@
 *
 * SPDX-License-Identifier: BSD-2-Clause-Patent
 *
+* Arm Neoverse N1 System Development Platform Technical Reference Manual
+* https://developer.arm.com/documentation/101489/0000/?lang=en
+*
 **/
 
 #ifndef NEOVERSEN1SOC_PLATFORM_H_
@@ -41,6 +44,10 @@
 #define NEOVERSEN1SOC_EXP_PERIPH_BASE0               0x1C000000
 #define NEOVERSEN1SOC_EXP_PERIPH_BASE0_SZ            0x1300000
 
+// SCP QSPI flash device
+#define NEOVERSEN1SOC_SCP_QSPI_AHB_BASE              0x18000000
+#define NEOVERSEN1SOC_SCP_QSPI_AHB_SZ                0x2000000
+
 /*
  * Platform information structure stored in Non-secure SRAM. Platform
  * information are passed from the trusted firmware with the below structure
diff --git a/Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c b/Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c
index 80daedb33416..282bfbc81736 100644
--- a/Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c
+++ b/Silicon/ARM/NeoverseN1Soc/Library/PlatformLib/PlatformLibMem.c
@@ -14,7 +14,7 @@
 #include <NeoverseN1Soc.h>
 
 // The total number of descriptors, including the final "end-of-table" descriptor.
-#define MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS 19
+#define MAX_VIRTUAL_MEMORY_MAP_DESCRIPTORS 20
 
 /**
   Returns the Virtual Memory Map of the platform.
@@ -203,6 +203,12 @@ ArmPlatformGetVirtualMemoryMap (
   VirtualMemoryTable[Index].Length          = NEOVERSEN1SOC_EXP_PERIPH_BASE0_SZ;
   VirtualMemoryTable[Index].Attributes      = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
 
+  // SCP QSPI flash device
+  VirtualMemoryTable[++Index].PhysicalBase  = NEOVERSEN1SOC_SCP_QSPI_AHB_BASE;
+  VirtualMemoryTable[Index].VirtualBase     = NEOVERSEN1SOC_SCP_QSPI_AHB_BASE;
+  VirtualMemoryTable[Index].Length          = NEOVERSEN1SOC_SCP_QSPI_AHB_SZ;
+  VirtualMemoryTable[Index].Attributes      = ARM_MEMORY_REGION_ATTRIBUTE_DEVICE;
+
   if (PlatInfo->MultichipMode == 1) {
     //Remote DDR (2GB)
     VirtualMemoryTable[++Index].PhysicalBase  = PcdGet64 (PcdExtMemorySpace) +
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119328): https://edk2.groups.io/g/devel/message/119328
Mute This Topic: https://groups.io/mt/106365464/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (12 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 13/17] Silicon/ARM/NeoverseN1Soc: Enable SCP QSPI flash region Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29 11:42   ` Sami Mujawar
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe Sahil Kaushal
                   ` (4 subsequent siblings)
  18 siblings, 1 reply; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Add NOR flash library, this library provides APIs for getting the list
of NOR flash devices on the platform.

This flash is shared between AP core and System Control Processor. The
lower addresses are used to store SCP and AP boot images and higher
addresses will be used for variable storage.

Signed-off-by: sahil <sahil@arm.com>
---
 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf | 35 +++++++++
 Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h             |  1 +
 Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c   | 80 ++++++++++++++++++++
 3 files changed, 116 insertions(+)

diff --git a/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
new file mode 100644
index 000000000000..a9495cf667d5
--- /dev/null
+++ b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
@@ -0,0 +1,35 @@
+## @file
+#  NOR flash lib for ARM Neoverse N1 platform.
+#
+#  Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    = 0x0001001B
+  BASE_NAME                      = NorFlashNeoverseN1SocLib
+  FILE_GUID                      = 7006fcf1-a585-4272-92e3-b286b1dff5bb
+  MODULE_TYPE                    = DXE_DRIVER
+  VERSION_STRING                 = 1.0
+  LIBRARY_CLASS                  = NorFlashPlatformLib
+
+[Sources.common]
+  NorFlashLib.c
+
+[Packages]
+  MdeModulePkg/MdeModulePkg.dec
+  MdePkg/MdePkg.dec
+  Platform/ARM/ARM.dec
+  Silicon/ARM/NeoverseN1Soc/NeoverseN1Soc.dec
+
+[LibraryClasses]
+  BaseLib
+  DebugLib
+
+[FixedPcd]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
diff --git a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
index 2dae57a0f01a..2a592e5adc2f 100644
--- a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
+++ b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
@@ -47,6 +47,7 @@
 // SCP QSPI flash device
 #define NEOVERSEN1SOC_SCP_QSPI_AHB_BASE              0x18000000
 #define NEOVERSEN1SOC_SCP_QSPI_AHB_SZ                0x2000000
+#define NEOVERSEN1SOC_FIRMWARE_IAMGES_SZ             0x800000
 
 /*
  * Platform information structure stored in Non-secure SRAM. Platform
diff --git a/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c
new file mode 100644
index 000000000000..a354ffb5ac6d
--- /dev/null
+++ b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c
@@ -0,0 +1,80 @@
+/** @file
+*  NOR flash lib for ARM Neoverse N1 platform
+*
+*  Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+*
+*  SPDX-License-Identifier: BSD-2-Clause-Patent
+*
+**/
+
+#include <Library/DebugLib.h>
+#include <Library/NorFlashPlatformLib.h>
+#include <NeoverseN1Soc.h>
+#include <PiDxe.h>
+
+#define FW_ENV_REGION_BASE  FixedPcdGet32 (PcdFlashNvStorageVariableBase)
+#define FW_ENV_REGION_SIZE  (FixedPcdGet32 (PcdFlashNvStorageVariableSize) + \
+                            FixedPcdGet32 (PcdFlashNvStorageFtwWorkingSize) + \
+                            FixedPcdGet32 (PcdFlashNvStorageFtwSpareSize))
+
+STATIC NOR_FLASH_DESCRIPTION  mNorFlashDevices[] = {
+  {
+    /// Environment variable region
+    NEOVERSEN1SOC_SCP_QSPI_AHB_BASE,                    ///< device base
+    FW_ENV_REGION_BASE,                                 ///< region base
+    FW_ENV_REGION_SIZE,                                 ///< region size
+    SIZE_4KB,                                           ///< block size
+  },
+};
+
+/**
+  Dummy implementation of NorFlashPlatformInitialization to
+  comply with NorFlashPlatformLib structure.
+
+  @retval        EFI_SUCCESS        Success.
+**/
+EFI_STATUS
+NorFlashPlatformInitialization (
+  VOID
+  )
+{
+  return EFI_SUCCESS;
+}
+
+/**
+  Get NOR flash region info
+
+  @param[out]    NorFlashDevices        NOR flash regions info.
+  @param[out]    Count                  number of flash instance.
+
+  @retval        EFI_SUCCESS            Success.
+  @retval        EFI_INVALID_PARAMETER  The parameters specified are not valid.
+  @retval        EFI_ACCESS_DENIED      Invalid variable region address.
+**/
+EFI_STATUS
+NorFlashPlatformGetDevices (
+  OUT NOR_FLASH_DESCRIPTION  **NorFlashDevices,
+  OUT UINT32                 *Count
+  )
+{
+  if ((NorFlashDevices == NULL) || (Count == NULL)) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if ((NEOVERSEN1SOC_SCP_QSPI_AHB_BASE +
+       NEOVERSEN1SOC_FIRMWARE_IAMGES_SZ) >=
+      FW_ENV_REGION_BASE)
+  {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashPlatformInitialization: Variable region overlapping with "
+      "firmware region.\n"
+      ));
+
+    return EFI_ACCESS_DENIED;
+  }
+
+  *NorFlashDevices = mNorFlashDevices;
+  *Count           = ARRAY_SIZE (mNorFlashDevices);
+  return EFI_SUCCESS;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119329): https://edk2.groups.io/g/devel/message/119329
Mute This Topic: https://groups.io/mt/106365465/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (13 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29 11:35   ` Sami Mujawar
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 16/17] Platform/ARM/N1Sdp: Persistent storage for N1Sdp Sahil Kaushal
                   ` (3 subsequent siblings)
  18 siblings, 1 reply; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

In N1Sdp platform, the SoC is connected to IOFPGA which has a
Cadence Quad SPI (QSPI) controller. This QSPI controller manages
the flash chip device via QSPI bus.

This patch adds CadenceQspiNorFlashDeviceLib which is used to
manage and access the above configuration.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf |   32 +
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h   |   46 +
 Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c   | 1034 ++++++++++++++++++++
 3 files changed, 1112 insertions(+)

diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
new file mode 100644
index 000000000000..506876b62285
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
@@ -0,0 +1,32 @@
+#/** @file
+#
+#  Component description file for CadenceQspiNorFlashDeviceLib Library
+#
+#  Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+  INF_VERSION                = 0x00010005
+  BASE_NAME                  = CadenceQspiNorFlashDeviceLib
+  FILE_GUID                  = ed172366-066b-4998-9b5e-ca7f385a170b
+  MODULE_TYPE                = DXE_RUNTIME_DRIVER
+  VERSION_STRING             = 1.0
+  LIBRARY_CLASS              = NorFlashDeviceLib
+
+[Sources.common]
+  CadenceQspiNorFlashDeviceLib.c
+  CadenceQspiNorFlashDeviceLib.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  Platform/ARM/ARM.dec
+
+[LibraryClasses]
+  BaseLib
+  BaseMemoryLib
+  DebugLib
+  IoLib
+  TimerLib
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
new file mode 100644
index 000000000000..951a93481dd1
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
@@ -0,0 +1,46 @@
+/** @file
+
+  Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+#define CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+
+#define NOR_FLASH_ERASE_RETRY  10
+
+// QSPI Controller defines
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET             0x90
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE            0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE        0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS       19
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS  16
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT         0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS     24
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE        0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_BYTE_3B       0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS     23
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS   20
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C           0x8
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS      7
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES(x)  ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS)
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES(x)  ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS)
+
+#define CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET  0xA0
+
+#define CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET  0x94
+
+#define CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS  1000u // Command Status Register read timeout
+
+#define SPINOR_SR_WIP  BIT0                               // Write in progress
+
+#define SPINOR_OP_WREN   0x06                             // Write enable
+#define SPINOR_OP_BE_4K  0x20                             // Erase 4KiB block
+#define SPINOR_OP_RDID   0x9f                             // Read JEDEC ID
+#define SPINOR_OP_RDSR   0x05                             // Read status register
+
+#define SPINOR_SR_WIP_POLL_TIMEOUT_MS  1000u              // Status Register read timeout
+
+#endif /* CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
new file mode 100644
index 000000000000..f97c8d51fd48
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
@@ -0,0 +1,1034 @@
+/** @file
+
+  Copyright (c) 2024 ARM Limited. All rights reserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/NorFlashDeviceLib.h>
+#include <Library/TimerLib.h>
+#include <Library/UefiLib.h>
+
+#include "CadenceQspiNorFlashDeviceLib.h"
+
+/**
+  Converts milliseconds into number of ticks of the performance counter.
+
+  @param[in] Milliseconds  Milliseconds to convert into ticks.
+
+  @retval Milliseconds expressed as number of ticks.
+
+**/
+STATIC
+UINT64
+MilliSecondsToTicks (
+  IN UINTN  Milliseconds
+  )
+{
+  UINT64  NanoSecondsPerTick;
+  UINT64  NanoSeconds;
+
+  NanoSecondsPerTick = GetTimeInNanoSecond (1);
+  NanoSeconds        = MultU64x32 (Milliseconds, 1000000);
+
+  return DivU64x64Remainder (NanoSeconds, NanoSecondsPerTick, NULL);
+}
+
+/**
+  Execute Flash cmd ctrl and Read Status.
+
+  @param[in]      Instance         NOR flash Instance.
+  @param[in]      Val              Value to be written to Flash cmd ctrl Register.
+
+  @retval         EFI_SUCCESS      Request is executed successfully.
+  @retval         EFI_TIMEOUT      Command execution timed out.
+
+**/
+STATIC
+EFI_STATUS
+CdnsQspiExecuteCommand (
+  IN  NOR_FLASH_INSTANCE  *Instance,
+  IN  UINT32              Val
+  )
+{
+  // Set the command
+  MmioWrite32 (
+    Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+    Val
+    );
+  // Execute the command
+  MmioWrite32 (
+    Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+    Val | CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE
+    );
+
+  CONST UINT64  TickOut =
+    GetPerformanceCounter () +
+    MilliSecondsToTicks (CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS);
+
+  // Wait until command has been executed
+  do {
+    if (GetPerformanceCounter () > TickOut) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "CdnsQspiExecuteCommand: Timeout waiting for command execution.\n"
+        ));
+      return EFI_TIMEOUT;
+    }
+  } while ((MmioRead32 (
+              Instance->HostControllerBaseAddress +
+              CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET
+              ) &
+            CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT) ==
+           CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT
+           );
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Poll Status register for NOR flash erase/write completion.
+
+  @param[in]      Instance           NOR flash Instance.
+
+  @retval         EFI_SUCCESS        Request is executed successfully.
+  @retval         EFI_TIMEOUT        Operation timed out.
+  @retval         EFI_DEVICE_ERROR   Controller operation failed.
+
+**/
+STATIC
+EFI_STATUS
+NorFlashPollStatusRegister (
+  IN NOR_FLASH_INSTANCE  *Instance
+  )
+{
+  BOOLEAN  SRegDone;
+  UINT32   val;
+
+  val = (SPINOR_OP_RDSR << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+        (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+         CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+        CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (1) |
+        (CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C <<
+         CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS);
+
+  CONST UINT64  TickOut =
+    GetPerformanceCounter () +
+    MilliSecondsToTicks (SPINOR_SR_WIP_POLL_TIMEOUT_MS);
+
+  do {
+    if (GetPerformanceCounter () > TickOut) {
+      DEBUG ((
+        DEBUG_ERROR,
+        "NorFlashPollStatusRegister: Timeout waiting for erase/write.\n"
+        ));
+      return EFI_TIMEOUT;
+    }
+
+    if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+      return EFI_DEVICE_ERROR;
+    }
+
+    SRegDone =
+      (MmioRead8 (
+         Instance->HostControllerBaseAddress +
+         CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+         )
+       & SPINOR_SR_WIP
+      ) == 0;
+  } while (!SRegDone);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Check whether NOR flash operations are Locked.
+
+  @param[in]     Instance         NOR flash Instance.
+  @param[in]     BlockAddress     BlockAddress in NOR flash device.
+
+  @retval        FALSE            If NOR flash is not locked.
+**/
+STATIC
+BOOLEAN
+NorFlashBlockIsLocked (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  return FALSE;
+}
+
+/**
+  Unlock NOR flash operations on given block.
+
+  @param[in]      Instance         NOR flash instance.
+  @param[in]      BlockAddress     BlockAddress in NOR flash device.
+
+  @retval         EFI_SUCCESS      NOR flash operations unlocked.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  return EFI_SUCCESS;
+}
+
+/**
+  Unlock NOR flash operations if it is necessary.
+
+  @param[in]      Instance         NOR flash instance.
+  @param[in]      BlockAddress     BlockAddress in NOR flash device.
+
+  @retval         EFI_SUCCESS      Request is executed successfully.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+
+  Status = EFI_SUCCESS;
+
+  if (!NorFlashBlockIsLocked (Instance, BlockAddress)) {
+    Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+  }
+
+  return Status;
+}
+
+/**
+  Enable write to NOR flash device.
+
+  @param[in]      Instance         NOR flash instance.
+
+  @retval         EFI_SUCCESS      Request is executed successfully.
+  @retval         EFI_DEVICE_ERROR The device reported an error.
+**/
+STATIC
+EFI_STATUS
+NorFlashEnableWrite (
+  IN  NOR_FLASH_INSTANCE  *Instance
+  )
+{
+  UINT32  val;
+
+  DEBUG ((DEBUG_INFO, "NorFlashEnableWrite()\n"));
+  val = (SPINOR_OP_WREN << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS);
+  if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  The following function presumes that the block has already been unlocked.
+
+  @param[in]      Instance           NOR flash instance.
+  @param[in]      BlockAddress       Block address within the variable region.
+
+  @retval       EFI_SUCCESS          Request is executed successfully.
+  @retval       EFI_DEVICE_ERROR     The device reported an error.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  UINT32  DevConfigVal;
+  UINT32  EraseOffset;
+
+  EraseOffset = 0x0;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashEraseSingleBlock(BlockAddress=0x%08x)\n",
+    BlockAddress
+    ));
+
+  if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  EraseOffset = BlockAddress - Instance->DeviceBaseAddress;
+
+  MmioWrite32 (
+    Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET,
+    EraseOffset
+    );
+
+  DevConfigVal = (SPINOR_OP_BE_4K << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+                 (CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE <<
+                  CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS) |
+                 CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES (3);
+
+  if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, DevConfigVal))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  This function unlocks and erases an entire NOR Flash block.
+
+  @param[in]     Instance       NOR flash Instance of variable store region.
+  @param[in]     BlockAddress   Block address within the variable store region.
+
+  @retval        EFI_SUCCESS          Erase and unlock successfully completed.
+  @retval        EFI_DEVICE_ERROR     The device reported an error.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               BlockAddress
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       Index;
+  EFI_TPL     OriginalTPL;
+
+  NorFlashLock (&OriginalTPL);
+
+  Index = 0;
+  do {
+    // Unlock the block if we have to
+    Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+
+    Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+
+    Index++;
+  } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status != EFI_SUCCESS));
+
+  if (Index == NOR_FLASH_ERASE_RETRY) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error "
+      "(try to erase %d times)\n",
+      BlockAddress,
+      Index
+      ));
+  }
+
+  NorFlashUnlock (OriginalTPL);
+
+  return Status;
+}
+
+/**
+  Write a single word to given location.
+
+  @param[in]    Instance          NOR flash Instance of variable store region.
+  @param[in]    WordAddress       The address in NOR flash to write given word.
+  @param[in]    WriteData         The data to write into NOR flash location.
+
+  @retval       EFI_SUCCESS       Write is complete.
+  @retval       EFI_DEVICE_ERROR  The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleWord (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN UINTN               WordAddress,
+  IN UINT32              WriteData
+  )
+{
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashWriteSingleWord(WordAddress=0x%08x, WriteData=0x%08x)\n",
+    WordAddress,
+    WriteData
+    ));
+
+  if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  MmioWrite32 (WordAddress, WriteData);
+  if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Write a full block to given location.
+
+  @param[in]    Instance           NOR flash Instance of variable store region.
+  @param[in]    Lba                The logical block address in NOR flash.
+  @param[in]    DataBuffer         The data to write into NOR flash location.
+  @param[in]    BlockSizeInWords   The number of bytes to write.
+
+  @retval       EFI_SUCCESS            Write is complete.
+  @retval       EFI_DEVICE_ERROR       The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteFullBlock (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINT32              *DataBuffer,
+  IN UINT32              BlockSizeInWords
+  )
+{
+  EFI_STATUS  Status;
+  UINTN       WordAddress;
+  UINT32      WordIndex;
+  UINTN       BlockAddress;
+  EFI_TPL     OriginalTPL;
+
+  Status = EFI_SUCCESS;
+
+  // Get the physical address of the block
+  BlockAddress = GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   BlockSizeInWords * 4
+                   );
+
+  // Start writing from the first address at the start of the block
+  WordAddress = BlockAddress;
+
+  NorFlashLock (&OriginalTPL);
+
+  Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single "
+      "block at 0x%X\n",
+      BlockAddress
+      ));
+    goto exit_handler;
+  }
+
+  for (WordIndex = 0;
+       WordIndex < BlockSizeInWords;
+       WordIndex++, DataBuffer++, WordAddress += 4)
+  {
+    Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+    if (EFI_ERROR (Status)) {
+      goto exit_handler;
+    }
+  }
+
+exit_handler:
+  NorFlashUnlock (OriginalTPL);
+
+  if (EFI_ERROR (Status)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. "
+      "Exit Status = %r.\n",
+      WordAddress,
+      Status
+      ));
+  }
+
+  return Status;
+}
+
+/**
+  Write multiple blocks.
+
+  @param[in]    Instance               NOR flash Instance of variable store region.
+  @param[in]    Lba                    The starting logical block index.
+  @param[in]    BufferSizeInBytes      The number of bytes to write.
+  @param[in]    Buffer                 The pointer to a caller-allocated buffer that
+                                       contains the source for the write.
+
+  @retval       EFI_SUCCESS            Write is complete.
+  @retval       EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval       EFI_BAD_BUFFER_SIZE    Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashWriteBlocks (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               BufferSizeInBytes,
+  IN VOID                *Buffer
+  )
+{
+  UINT32      *WriteBuffer;
+  EFI_STATUS  Status;
+  EFI_LBA     CurrentBlock;
+  UINT32      BlockSizeInWords;
+  UINT32      NumBlocks;
+  UINT32      BlockCount;
+
+  Status = EFI_SUCCESS;
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // We must have some bytes to read
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n",
+    BufferSizeInBytes
+    ));
+  if (BufferSizeInBytes == 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // The size of the buffer must be a multiple of the block size
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n",
+    Instance->Media.BlockSize
+    ));
+  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // All blocks must be within the device
+  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n",
+    NumBlocks,
+    Instance->Media.LastBlock,
+    Lba
+    ));
+
+  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"
+      ));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+  // Because the target *Buffer is a pointer to VOID, we must put
+  // all the data into a pointer to a proper data type, so use *WriteBuffer
+  WriteBuffer = (UINT32 *)Buffer;
+
+  CurrentBlock = Lba;
+  for (BlockCount = 0;
+       BlockCount < NumBlocks;
+       BlockCount++, CurrentBlock++, WriteBuffer += BlockSizeInWords)
+  {
+    DEBUG ((
+      DEBUG_INFO,
+      "NorFlashWriteBlocks: Writing block #%d\n",
+      (UINTN)CurrentBlock
+      ));
+
+    Status = NorFlashWriteFullBlock (
+               Instance,
+               CurrentBlock,
+               WriteBuffer,
+               BlockSizeInWords
+               );
+
+    if (EFI_ERROR (Status)) {
+      break;
+    }
+  }
+
+  DEBUG ((DEBUG_INFO, "NorFlashWriteBlocks: Exit Status = %r.\n", Status));
+  return Status;
+}
+
+/**
+  Read multiple blocks.
+
+  @param[in]     Instance               NOR flash Instance of variable store region.
+  @param[in]     Lba                    The starting logical block index to read from.
+  @param[in]     BufferSizeInBytes      The number of bytes to read.
+  @param[out]    Buffer                 The pointer to a caller-allocated buffer that
+                                        should be copied with read data.
+
+  @retval        EFI_SUCCESS            Read is complete.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval        EFI_BAD_BUFFER_SIZE    Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashReadBlocks (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  )
+{
+  UINT32  NumBlocks;
+  UINTN   StartAddress;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, "
+    "Lba=%ld.\n",
+    BufferSizeInBytes,
+    Instance->Media.BlockSize,
+    Instance->Media.LastBlock,
+    Lba
+    ));
+
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Return if we do not have any byte to read
+  if (BufferSizeInBytes == 0) {
+    return EFI_SUCCESS;
+  }
+
+  // The size of the buffer must be a multiple of the block size
+  if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+  if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashReadBlocks: ERROR - Read will exceed last block\n"
+      ));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Get the address to start reading from
+  StartAddress = GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   Instance->Media.BlockSize
+                   );
+
+  // Readout the data
+  CopyMem (Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Read from NOR flash.
+
+  @param[in]     Instance               NOR flash Instance of variable store region.
+  @param[in]     Lba                    The starting logical block index to read from.
+  @param[in]     Offset                 Offset into the block at which to begin reading.
+  @param[in]     BufferSizeInBytes      The number of bytes to read.
+  @param[out]    Buffer                 The pointer to a caller-allocated buffer that
+                                        should be copied with read data.
+
+  @retval        EFI_SUCCESS            Read is complete.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashRead (
+  IN NOR_FLASH_INSTANCE  *Instance,
+  IN EFI_LBA             Lba,
+  IN UINTN               Offset,
+  IN UINTN               BufferSizeInBytes,
+  OUT VOID               *Buffer
+  )
+{
+  UINTN  StartAddress;
+
+  // The buffer must be valid
+  if (Buffer == NULL) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Return if we do not have any byte to read
+  if (BufferSizeInBytes == 0) {
+    return EFI_SUCCESS;
+  }
+
+  if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) >
+      Instance->Size)
+  {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashRead: ERROR - Read will exceed device size.\n"
+      ));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  // Get the address to start reading from
+  StartAddress = GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   Instance->Media.BlockSize
+                   );
+
+  // Readout the data
+  CopyMem (Buffer, (UINTN *)(StartAddress + Offset), BufferSizeInBytes);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Write a full or portion of a block.
+
+  @param[in]       Instance               NOR flash Instance of variable store region.
+  @param[in]       Lba                    The starting logical block index to write to.
+  @param[in]       Offset                 Offset into the block at which to begin writing.
+  @param[in, out]  NumBytes               The total size of the buffer.
+  @param[in]       Buffer                 The pointer to a caller-allocated buffer that
+                                          contains the source for the write.
+
+  @retval          EFI_SUCCESS            Write is complete.
+  @retval          EFI_INVALID_PARAMETER  Invalid parameters passed.
+  @retval          EFI_BAD_BUFFER_SIZE    Buffer size not enough.
+  @retval          EFI_DEVICE_ERROR       The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+  IN        NOR_FLASH_INSTANCE  *Instance,
+  IN        EFI_LBA             Lba,
+  IN        UINTN               Offset,
+  IN OUT    UINTN               *NumBytes,
+  IN        UINT8               *Buffer
+  )
+{
+  EFI_STATUS  Status;
+  UINT32      Tmp;
+  UINT32      TmpBuf;
+  UINT32      WordToWrite;
+  UINT32      Mask;
+  BOOLEAN     DoErase;
+  UINTN       BytesToWrite;
+  UINTN       CurOffset;
+  UINTN       WordAddr;
+  UINTN       BlockSize;
+  UINTN       BlockAddress;
+  UINTN       PrevBlockAddress;
+
+  if (Buffer == NULL) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashWriteSingleBlock: ERROR - Buffer is invalid\n"
+      ));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  if (NumBytes == NULL) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashWriteSingleBlock: ERROR - NumBytes is invalid\n"
+      ));
+    return EFI_INVALID_PARAMETER;
+  }
+
+  PrevBlockAddress = 0;
+
+  DEBUG ((
+    DEBUG_INFO,
+    "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, "
+    "*NumBytes=0x%x, Buffer @ 0x%08x)\n",
+    Lba,
+    Offset,
+    *NumBytes,
+    Buffer
+    ));
+
+  // Locate the block size to avoid de-referencing pointers all the time
+  BlockSize = Instance->Media.BlockSize;
+
+  // The write must not span block boundaries.
+  // We need to check each variable individually because adding two large
+  // values together overflows.
+  if ((Offset               >= BlockSize) ||
+      (*NumBytes            >  BlockSize) ||
+      ((Offset + *NumBytes) >  BlockSize))
+  {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+      "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+      Offset,
+      *NumBytes,
+      BlockSize
+      ));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // We must have some bytes to write
+  if (*NumBytes == 0) {
+    DEBUG ((
+      DEBUG_ERROR,
+      "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+      "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+      Offset,
+      *NumBytes,
+      BlockSize
+      ));
+    return EFI_BAD_BUFFER_SIZE;
+  }
+
+  // Pick 128bytes as a good start for word operations as opposed to erasing the
+  // block and writing the data regardless if an erase is really needed.
+  // It looks like most individual NV variable writes are smaller than 128bytes.
+  if (*NumBytes <= 128) {
+    // Check to see if we need to erase before programming the data into NOR.
+    // If the destination bits are only changing from 1s to 0s we can just write.
+    // After a block is erased all bits in the block is set to 1.
+    // If any byte requires us to erase we just give up and rewrite all of it.
+    DoErase      = FALSE;
+    BytesToWrite = *NumBytes;
+    CurOffset    = Offset;
+
+    while (BytesToWrite > 0) {
+      // Read full word from NOR, splice as required. A word is the smallest
+      // unit we can write.
+      Status = NorFlashRead (
+                 Instance,
+                 Lba,
+                 CurOffset & ~(0x3),
+                 sizeof (Tmp),
+                 &Tmp
+                 );
+      if (EFI_ERROR (Status)) {
+        return EFI_DEVICE_ERROR;
+      }
+
+      // Physical address of word in NOR to write.
+      WordAddr = (CurOffset & ~(0x3)) +
+                 GET_NOR_BLOCK_ADDRESS (
+                   Instance->RegionBaseAddress,
+                   Lba,
+                   BlockSize
+                   );
+
+      // The word of data that is to be written.
+      TmpBuf = ReadUnaligned32 (
+                 (UINT32 *)(Buffer + (*NumBytes - BytesToWrite))
+                 );
+
+      // First do word aligned chunks.
+      if ((CurOffset & 0x3) == 0) {
+        if (BytesToWrite >= 4) {
+          // Is the destination still in 'erased' state?
+          if (~Tmp != 0) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Write this word to NOR
+          WordToWrite   = TmpBuf;
+          CurOffset    += sizeof (TmpBuf);
+          BytesToWrite -= sizeof (TmpBuf);
+        } else {
+          // BytesToWrite < 4. Do small writes and left-overs
+          Mask = ~((~0) << (BytesToWrite * 8));
+          // Mask out the bytes we want.
+          TmpBuf &= Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
+          CurOffset   += BytesToWrite;
+          BytesToWrite = 0;
+        }
+      } else {
+        // Do multiple words, but starting unaligned.
+        if (BytesToWrite > (4 - (CurOffset & 0x3))) {
+          Mask = ((~0) << ((CurOffset & 0x3) * 8));
+          // Mask out the bytes we want.
+          TmpBuf &= Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite   = (Tmp & ~Mask) | TmpBuf;
+          BytesToWrite -= (4 - (CurOffset & 0x3));
+          CurOffset    += (4 - (CurOffset & 0x3));
+        } else {
+          // Unaligned and fits in one word.
+          Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
+          // Mask out the bytes we want.
+          TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
+          // Is the destination still in 'erased' state?
+          if ((Tmp & Mask) != Mask) {
+            // Check to see if we are only changing bits to zero.
+            if ((Tmp ^ TmpBuf) & TmpBuf) {
+              DoErase = TRUE;
+              break;
+            }
+          }
+
+          // Merge old and new data. Write merged word to NOR
+          WordToWrite  = (Tmp & ~Mask) | TmpBuf;
+          CurOffset   += BytesToWrite;
+          BytesToWrite = 0;
+        }
+      }
+
+      BlockAddress = GET_NOR_BLOCK_ADDRESS (
+                       Instance->RegionBaseAddress,
+                       Lba,
+                       BlockSize
+                       );
+      if (BlockAddress != PrevBlockAddress) {
+        Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+        if (EFI_ERROR (Status)) {
+          return EFI_DEVICE_ERROR;
+        }
+
+        PrevBlockAddress = BlockAddress;
+      }
+
+      Status = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
+      if (EFI_ERROR (Status)) {
+        return EFI_DEVICE_ERROR;
+      }
+    }
+
+    // Exit if we got here and could write all the data. Otherwise do the
+    // Erase-Write cycle.
+    if (!DoErase) {
+      return EFI_SUCCESS;
+    }
+  }
+
+  // Check we did get some memory. Buffer is BlockSize.
+  if (Instance->ShadowBuffer == NULL) {
+    DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
+    return EFI_DEVICE_ERROR;
+  }
+
+  // Read NOR Flash data into shadow buffer
+  Status = NorFlashReadBlocks (
+             Instance,
+             Lba,
+             BlockSize,
+             Instance->ShadowBuffer
+             );
+  if (EFI_ERROR (Status)) {
+    // Return one of the pre-approved error statuses
+    return EFI_DEVICE_ERROR;
+  }
+
+  // Put the data at the appropriate location inside the buffer area
+  CopyMem (
+    (VOID *)((UINTN)Instance->ShadowBuffer + Offset),
+    Buffer,
+    *NumBytes
+    );
+
+  // Write the modified buffer back to the NorFlash
+  Status = NorFlashWriteBlocks (
+             Instance,
+             Lba,
+             BlockSize,
+             Instance->ShadowBuffer
+             );
+  if (EFI_ERROR (Status)) {
+    // Return one of the pre-approved error statuses
+    return EFI_DEVICE_ERROR;
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Read JEDEC ID of NOR flash device.
+
+  @param[in]     Instance               NOR flash Instance of variable store region.
+  @param[out]    JedecId                JEDEC ID of NOR flash device.
+                                        Maximum length of JedecId can be upto 6 bytes
+
+  @retval        EFI_SUCCESS            The write is completed.
+  @retval        EFI_DEVICE_ERROR       Failed to fetch JEDEC ID.
+  @retval        EFI_INVALID_PARAMETER  Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashReadId (
+  IN  NOR_FLASH_INSTANCE  *Instance,
+  OUT UINT8               *JedecId
+  )
+{
+  UINT32  val;
+
+  if ((Instance == NULL) || (JedecId == NULL)) {
+    return EFI_INVALID_PARAMETER;
+  }
+
+  val = (SPINOR_OP_RDID <<
+         CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+        (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+         CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+        CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (3);
+
+  if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+    return EFI_DEVICE_ERROR;
+  }
+
+  val = MmioRead32 (
+          Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+          );
+
+  // Manufacturer ID field
+  JedecId[0] = (UINT8)val;
+  // Type field
+  JedecId[1] = (UINT8)(val >> 8);
+  // Capacity field
+  JedecId[2] = (UINT8)(val >> 16);
+
+  DEBUG ((
+    DEBUG_INFO,
+    "Nor flash detected, Jedec ID, Manufacturer Id=%x Type=%x Capacity=%x \n",
+    JedecId[0],
+    JedecId[1],
+    JedecId[2]
+    ));
+
+  return EFI_SUCCESS;
+}
+
+/**
+  NOR Flash Reset
+
+  @param[in]         Instance     NOR flash instance.
+
+  @retval            EFI_SUCCESS  Return success on every call.
+**/
+EFI_STATUS
+NorFlashReset (
+  IN  NOR_FLASH_INSTANCE  *Instance
+  )
+{
+  return EFI_SUCCESS;
+}
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119330): https://edk2.groups.io/g/devel/message/119330
Mute This Topic: https://groups.io/mt/106365466/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 16/17] Platform/ARM/N1Sdp: Persistent storage for N1Sdp
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (14 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 17/17] Platform/ARM/N1Sdp: Enable FaultTolerantWrite Dxe driver " Sahil Kaushal
                   ` (2 subsequent siblings)
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

Enable persistent storage on QSPI flash device.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/N1Sdp/N1SdpPlatform.dsc | 19 ++++++++++++++-----
 Platform/ARM/N1Sdp/N1SdpPlatform.fdf |  2 ++
 2 files changed, 16 insertions(+), 5 deletions(-)

diff --git a/Platform/ARM/N1Sdp/N1SdpPlatform.dsc b/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
index 46412bff7d78..fd630fa08c35 100644
--- a/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
+++ b/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
@@ -161,11 +161,9 @@ [PcdsFixedAtBuild.common]
   # ACPI Table Version
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiExposedTableVersions|0x20
 
-  # Runtime Variable storage
-  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0
-  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvModeEnable|TRUE
-  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000
-  gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800
+  # NOR flash support
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|0x18F00000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize|0x00020000
 
 ################################################################################
 #
@@ -197,6 +195,16 @@ [Components.common]
       gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000000F
   }
 
+  # NOR flash support
+  Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf {
+    <LibraryClasses>
+      NorFlashDeviceLib|Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
+      NorFlashPlatformLib|Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
+      NorFlashInfoLib|EmbeddedPkg/Library/NorFlashInfoLib/NorFlashInfoLib.inf
+    <PcdsFixedAtBuild>
+      gPlatformArmTokenSpaceGuid.PcdNorFlashRegBaseAddress|0x1C0C0000
+  }
+
   # Architectural Protocols
   ArmPkg/Drivers/CpuDxe/CpuDxe.inf
   ArmPkg/Drivers/ArmGic/ArmGicDxe.inf
@@ -217,6 +225,7 @@ [Components.common]
   MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf {
     <LibraryClasses>
       NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf
+      NULL|EmbeddedPkg/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf
       BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
   }
 
diff --git a/Platform/ARM/N1Sdp/N1SdpPlatform.fdf b/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
index 7aae8e6a753b..07118725f168 100644
--- a/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
+++ b/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
@@ -140,6 +140,8 @@ [FV.FvMain]
   INF ArmPkg/Drivers/GenericWatchdogDxe/GenericWatchdogDxe.inf
   INF ArmPkg/Drivers/TimerDxe/TimerDxe.inf
 
+  INF Platform/ARM/Drivers/NorFlashDxe/NorFlashDxe.inf
+
   INF Platform/ARM/Drivers/BootMonFs/BootMonFs.inf
   INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf
 
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119331): https://edk2.groups.io/g/devel/message/119331
Mute This Topic: https://groups.io/mt/106365467/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* [edk2-devel] [edk2-platforms][PATCH V4 17/17] Platform/ARM/N1Sdp: Enable FaultTolerantWrite Dxe driver for N1Sdp
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (15 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 16/17] Platform/ARM/N1Sdp: Persistent storage for N1Sdp Sahil Kaushal
@ 2024-05-29  8:55 ` Sahil Kaushal
  2024-05-29 15:27 ` [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sami Mujawar
  2024-05-29 15:51 ` Sami Mujawar
  18 siblings, 0 replies; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29  8:55 UTC (permalink / raw)
  To: devel; +Cc: Ard Biesheuvel, Leif Lindholm  , Sami Mujawar, sahil  

From: sahil <sahil@arm.com>

This driver enables Fault Tolerant Write protocol, which provides
fault tolerant write capability for block devices.

Signed-off-by: sahil <sahil@arm.com>
---
 Platform/ARM/N1Sdp/N1SdpPlatform.dsc | 5 +++++
 Platform/ARM/N1Sdp/N1SdpPlatform.fdf | 1 +
 2 files changed, 6 insertions(+)

diff --git a/Platform/ARM/N1Sdp/N1SdpPlatform.dsc b/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
index fd630fa08c35..743c2e647b76 100644
--- a/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
+++ b/Platform/ARM/N1Sdp/N1SdpPlatform.dsc
@@ -162,6 +162,10 @@ [PcdsFixedAtBuild.common]
   gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiExposedTableVersions|0x20
 
   # NOR flash support
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0x18F40000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize|0x00020000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0x18F20000
+  gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize|0x00020000
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase|0x18F00000
   gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize|0x00020000
 
@@ -228,6 +232,7 @@ [Components.common]
       NULL|EmbeddedPkg/Library/NvVarStoreFormattedLib/NvVarStoreFormattedLib.inf
       BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf
   }
+  MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
 
   # ACPI Support
   MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf
diff --git a/Platform/ARM/N1Sdp/N1SdpPlatform.fdf b/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
index 07118725f168..7b7eda51c70c 100644
--- a/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
+++ b/Platform/ARM/N1Sdp/N1SdpPlatform.fdf
@@ -90,6 +90,7 @@ [FV.FvMain]
   INF MdeModulePkg/Universal/Metronome/Metronome.inf
   INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf
   INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf
+  INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf
   INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf
   INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf
   INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf
-- 
2.25.1



-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119332): https://edk2.groups.io/g/devel/message/119332
Mute This Topic: https://groups.io/mt/106365468/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe Sahil Kaushal
@ 2024-05-29 11:35   ` Sami Mujawar
  2024-05-29 11:51     ` Sahil Kaushal
  0 siblings, 1 reply; 24+ messages in thread
From: Sami Mujawar @ 2024-05-29 11:35 UTC (permalink / raw)
  To: Sahil Kaushal, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Leif Lindholm  , nd

Hi Sahil,

Please find my feedback inline marked [SAMI].

Regards,

Sami Mujawar

On 29/05/2024, 09:56, "Sahil Kaushal" <Sahil.Kaushal@arm.com <mailto:Sahil.Kaushal@arm.com>> wrote:


From: sahil <sahil@arm.com <mailto:sahil@arm.com>>


In N1Sdp platform, the SoC is connected to IOFPGA which has a
Cadence Quad SPI (QSPI) controller. This QSPI controller manages
the flash chip device via QSPI bus.


This patch adds CadenceQspiNorFlashDeviceLib which is used to
manage and access the above configuration.


Signed-off-by: sahil <sahil@arm.com <mailto:sahil@arm.com>>
---
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf | 32 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h | 46 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c | 1034 ++++++++++++++++++++
3 files changed, 1112 insertions(+)


diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
new file mode 100644
index 000000000000..506876b62285
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
@@ -0,0 +1,32 @@
+#/** @file
+#
+# Component description file for CadenceQspiNorFlashDeviceLib Library
+#
+# Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CadenceQspiNorFlashDeviceLib
+ FILE_GUID = ed172366-066b-4998-9b5e-ca7f385a170b
+ MODULE_TYPE = DXE_RUNTIME_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashDeviceLib
+
+[Sources.common]
+ CadenceQspiNorFlashDeviceLib.c
+ CadenceQspiNorFlashDeviceLib.h
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Platform/ARM/ARM.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ TimerLib
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
new file mode 100644
index 000000000000..951a93481dd1
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
@@ -0,0 +1,46 @@
+/** @file
+
+ Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+#define CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+
+#define NOR_FLASH_ERASE_RETRY 10
+
+// QSPI Controller defines
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET 0x90
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS 19
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS 16
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS 24
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_BYTE_3B 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS 23
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS 20
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C 0x8
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS 7
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS)
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS)
+
+#define CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET 0xA0
+
+#define CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET 0x94
+
+#define CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS 1000u // Command Status Register read timeout
+
+#define SPINOR_SR_WIP BIT0 // Write in progress
+
+#define SPINOR_OP_WREN 0x06 // Write enable
+#define SPINOR_OP_BE_4K 0x20 // Erase 4KiB block
+#define SPINOR_OP_RDID 0x9f // Read JEDEC ID
+#define SPINOR_OP_RDSR 0x05 // Read status register
+
+#define SPINOR_SR_WIP_POLL_TIMEOUT_MS 1000u // Status Register read timeout
+
+#endif /* CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
new file mode 100644
index 000000000000..f97c8d51fd48
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
@@ -0,0 +1,1034 @@
+/** @file
+
+ Copyright (c) 2024 ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/NorFlashDeviceLib.h>
+#include <Library/TimerLib.h>
+#include <Library/UefiLib.h>
+
+#include "CadenceQspiNorFlashDeviceLib.h"
+
+/**
+ Converts milliseconds into number of ticks of the performance counter.
+
+ @param[in] Milliseconds Milliseconds to convert into ticks.
+
+ @retval Milliseconds expressed as number of ticks.
+
+**/
+STATIC
+UINT64
+MilliSecondsToTicks (
+ IN UINTN Milliseconds
+ )
+{
+ UINT64 NanoSecondsPerTick;
+ UINT64 NanoSeconds;
+
+ NanoSecondsPerTick = GetTimeInNanoSecond (1);
+ NanoSeconds = MultU64x32 (Milliseconds, 1000000);
+
+ return DivU64x64Remainder (NanoSeconds, NanoSecondsPerTick, NULL);
+}
+
+/**
+ Execute Flash cmd ctrl and Read Status.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] Val Value to be written to Flash cmd ctrl Register.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Command execution timed out.
+
+**/
+STATIC
+EFI_STATUS
+CdnsQspiExecuteCommand (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINT32 Val
+ )
+{
+ // Set the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val
+ );
+ // Execute the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val | CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE
+ );
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS);
+
+ // Wait until command has been executed
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "CdnsQspiExecuteCommand: Timeout waiting for command execution.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+ } while ((MmioRead32 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET
+ ) &
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT) ==
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Poll Status register for NOR flash erase/write completion.
+
+ @param[in] Instance NOR flash Instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Operation timed out.
+ @retval EFI_DEVICE_ERROR Controller operation failed.
+
+**/
+STATIC
+EFI_STATUS
+NorFlashPollStatusRegister (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ BOOLEAN SRegDone;
+ UINT32 val;
+
+ val = (SPINOR_OP_RDSR << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (1) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS);
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (SPINOR_SR_WIP_POLL_TIMEOUT_MS);
+
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashPollStatusRegister: Timeout waiting for erase/write.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ SRegDone =
+ (MmioRead8 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ )
+ & SPINOR_SR_WIP
+ ) == 0;
+ } while (!SRegDone);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Check whether NOR flash operations are Locked.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval FALSE If NOR flash is not locked.
+**/
+STATIC
+BOOLEAN
+NorFlashBlockIsLocked (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return FALSE;
+}
+
+/**
+ Unlock NOR flash operations on given block.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS NOR flash operations unlocked.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Unlock NOR flash operations if it is necessary.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+
+ Status = EFI_SUCCESS;
+
+ if (!NorFlashBlockIsLocked (Instance, BlockAddress)) {
+ Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+ }
+
+ return Status;
+}
+
+/**
+ Enable write to NOR flash device.
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+STATIC
+EFI_STATUS
+NorFlashEnableWrite (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ UINT32 val;
+
+ DEBUG ((DEBUG_INFO, "NorFlashEnableWrite()\n"));
+ val = (SPINOR_OP_WREN << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS);
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The following function presumes that the block has already been unlocked.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress Block address within the variable region.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ UINT32 DevConfigVal;
+ UINT32 EraseOffset;
+
+ EraseOffset = 0x0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashEraseSingleBlock(BlockAddress=0x%08x)\n",
+ BlockAddress
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ EraseOffset = BlockAddress - Instance->DeviceBaseAddress;
+
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET,
+ EraseOffset
+ );
+
+ DevConfigVal = (SPINOR_OP_BE_4K << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, DevConfigVal))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function unlocks and erases an entire NOR Flash block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] BlockAddress Block address within the variable store region.
+
+ @retval EFI_SUCCESS Erase and unlock successfully completed.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_TPL OriginalTPL;
+
+ NorFlashLock (&OriginalTPL);
+
+ Index = 0;
+ do {
+ // Unlock the block if we have to
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Index++;
+ } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status != EFI_SUCCESS));
[SAMI] I think there is something wrong with the loop condition. 
If I am not wrong, the check (Status != EFI_SUCCESS) does not seem to have any effect as the code in the while loop will break out of there is an error.
Can you check, please?
[/SAMI]


+
+ if (Index == NOR_FLASH_ERASE_RETRY) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error "
+ "(try to erase %d times)\n",
+ BlockAddress,
+ Index
+ ));
+ }
+
+ NorFlashUnlock (OriginalTPL);
+
+ return Status;
+}
+
+/**
+ Write a single word to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] WordAddress The address in NOR flash to write given word.
+ @param[in] WriteData The data to write into NOR flash location.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleWord (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN WordAddress,
+ IN UINT32 WriteData
+ )
+{
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleWord(WordAddress=0x%08x, WriteData=0x%08x)\n",
+ WordAddress,
+ WriteData
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ MmioWrite32 (WordAddress, WriteData);
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full block to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The logical block address in NOR flash.
+ @param[in] DataBuffer The data to write into NOR flash location.
+ @param[in] BlockSizeInWords The number of bytes to write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteFullBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINT32 *DataBuffer,
+ IN UINT32 BlockSizeInWords
+ )
+{
+ EFI_STATUS Status;
+ UINTN WordAddress;
+ UINT32 WordIndex;
+ UINTN BlockAddress;
+ EFI_TPL OriginalTPL;
+
+ Status = EFI_SUCCESS;
+
+ // Get the physical address of the block
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSizeInWords * 4
+ );
+
+ // Start writing from the first address at the start of the block
+ WordAddress = BlockAddress;
+
+ NorFlashLock (&OriginalTPL);
+
+ Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single "
+ "block at 0x%X\n",
+ BlockAddress
+ ));
+ goto exit_handler;
+ }
+
+ for (WordIndex = 0;
+ WordIndex < BlockSizeInWords;
+ WordIndex++, DataBuffer++, WordAddress += 4)
+ {
+ Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+ if (EFI_ERROR (Status)) {
+ goto exit_handler;
+ }
+ }
+
+exit_handler:
+ NorFlashUnlock (OriginalTPL);
+
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. "
+ "Exit Status = %r.\n",
+ WordAddress,
+ Status
+ ));
+ }
+
+ return Status;
+}
+
+/**
+ Write multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index.
+ @param[in] BufferSizeInBytes The number of bytes to write.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashWriteBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ )
+{
+ UINT32 *WriteBuffer;
+ EFI_STATUS Status;
+ EFI_LBA CurrentBlock;
+ UINT32 BlockSizeInWords;
+ UINT32 NumBlocks;
+ UINT32 BlockCount;
+
+ Status = EFI_SUCCESS;
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // We must have some bytes to read
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n",
+ BufferSizeInBytes
+ ));
+ if (BufferSizeInBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n",
+ Instance->Media.BlockSize
+ ));
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // All blocks must be within the device
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n",
+ NumBlocks,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+ // Because the target *Buffer is a pointer to VOID, we must put
+ // all the data into a pointer to a proper data type, so use *WriteBuffer
+ WriteBuffer = (UINT32 *)Buffer;
+
+ CurrentBlock = Lba;
+ for (BlockCount = 0;
+ BlockCount < NumBlocks;
+ BlockCount++, CurrentBlock++, WriteBuffer += BlockSizeInWords)
+ {
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: Writing block #%d\n",
+ (UINTN)CurrentBlock
+ ));
+
+ Status = NorFlashWriteFullBlock (
+ Instance,
+ CurrentBlock,
+ WriteBuffer,
+ BlockSizeInWords
+ );
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+
+ DEBUG ((DEBUG_INFO, "NorFlashWriteBlocks: Exit Status = %r.\n", Status));
+ return Status;
+}
+
+/**
+ Read multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashReadBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINT32 NumBlocks;
+ UINTN StartAddress;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, "
+ "Lba=%ld.\n",
+ BufferSizeInBytes,
+ Instance->Media.BlockSize,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashReadBlocks: ERROR - Read will exceed last block\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read from NOR flash.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] Offset Offset into the block at which to begin reading.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashRead (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINTN StartAddress;
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) >
+ Instance->Size)
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashRead: ERROR - Read will exceed device size.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)(StartAddress + Offset), BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full or portion of a block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to write to.
+ @param[in] Offset Offset into the block at which to begin writing.
+ @param[in, out] NumBytes The total size of the buffer.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Buffer size not enough.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 Tmp;
+ UINT32 TmpBuf;
+ UINT32 WordToWrite;
+ UINT32 Mask;
+ BOOLEAN DoErase;
+ UINTN BytesToWrite;
+ UINTN CurOffset;
+ UINTN WordAddr;
+ UINTN BlockSize;
+ UINTN BlockAddress;
+ UINTN PrevBlockAddress;
+
+ if (Buffer == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - Buffer is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (NumBytes == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - NumBytes is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ PrevBlockAddress = 0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, "
+ "*NumBytes=0x%x, Buffer @ 0x%08x)\n",
+ Lba,
+ Offset,
+ *NumBytes,
+ Buffer
+ ));
+
+ // Locate the block size to avoid de-referencing pointers all the time
+ BlockSize = Instance->Media.BlockSize;
+
+ // The write must not span block boundaries.
+ // We need to check each variable individually because adding two large
+ // values together overflows.
+ if ((Offset >= BlockSize) ||
+ (*NumBytes > BlockSize) ||
+ ((Offset + *NumBytes) > BlockSize))
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // We must have some bytes to write
+ if (*NumBytes == 0) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Pick 128bytes as a good start for word operations as opposed to erasing the
+ // block and writing the data regardless if an erase is really needed.
+ // It looks like most individual NV variable writes are smaller than 128bytes.
+ if (*NumBytes <= 128) {
+ // Check to see if we need to erase before programming the data into NOR.
+ // If the destination bits are only changing from 1s to 0s we can just write.
+ // After a block is erased all bits in the block is set to 1.
+ // If any byte requires us to erase we just give up and rewrite all of it.
+ DoErase = FALSE;
+ BytesToWrite = *NumBytes;
+ CurOffset = Offset;
+
+ while (BytesToWrite > 0) {
+ // Read full word from NOR, splice as required. A word is the smallest
+ // unit we can write.
+ Status = NorFlashRead (
+ Instance,
+ Lba,
+ CurOffset & ~(0x3),
+ sizeof (Tmp),
+ &Tmp
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Physical address of word in NOR to write.
+ WordAddr = (CurOffset & ~(0x3)) +
+ GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+
+ // The word of data that is to be written.
+ TmpBuf = ReadUnaligned32 (
+ (UINT32 *)(Buffer + (*NumBytes - BytesToWrite))
+ );
+
+ // First do word aligned chunks.
+ if ((CurOffset & 0x3) == 0) {
+ if (BytesToWrite >= 4) {
+ // Is the destination still in 'erased' state?
+ if (~Tmp != 0) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Write this word to NOR
+ WordToWrite = TmpBuf;
+ CurOffset += sizeof (TmpBuf);
+ BytesToWrite -= sizeof (TmpBuf);
+ } else {
+ // BytesToWrite < 4. Do small writes and left-overs
+ Mask = ~((~0) << (BytesToWrite * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ } else {
+ // Do multiple words, but starting unaligned.
+ if (BytesToWrite > (4 - (CurOffset & 0x3))) {
+ Mask = ((~0) << ((CurOffset & 0x3) * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ BytesToWrite -= (4 - (CurOffset & 0x3));
+ CurOffset += (4 - (CurOffset & 0x3));
+ } else {
+ // Unaligned and fits in one word.
+ Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
+ // Mask out the bytes we want.
+ TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ }
+
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+ if (BlockAddress != PrevBlockAddress) {
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ PrevBlockAddress = BlockAddress;
+ }
+
+ Status = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+ }
+
+ // Exit if we got here and could write all the data. Otherwise do the
+ // Erase-Write cycle.
+ if (!DoErase) {
+ return EFI_SUCCESS;
+ }
+ }
+
+ // Check we did get some memory. Buffer is BlockSize.
+ if (Instance->ShadowBuffer == NULL) {
+ DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Read NOR Flash data into shadow buffer
+ Status = NorFlashReadBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Put the data at the appropriate location inside the buffer area
+ CopyMem (
+ (VOID *)((UINTN)Instance->ShadowBuffer + Offset),
+ Buffer,
+ *NumBytes
+ );
+
+ // Write the modified buffer back to the NorFlash
+ Status = NorFlashWriteBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read JEDEC ID of NOR flash device.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[out] JedecId JEDEC ID of NOR flash device.
+ Maximum length of JedecId can be upto 6 bytes
+
+ @retval EFI_SUCCESS The write is completed.
+ @retval EFI_DEVICE_ERROR Failed to fetch JEDEC ID.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashReadId (
+ IN NOR_FLASH_INSTANCE *Instance,
+ OUT UINT8 *JedecId
+ )
+{
+ UINT32 val;
+
+ if ((Instance == NULL) || (JedecId == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ val = (SPINOR_OP_RDID <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ val = MmioRead32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ );
+
+ // Manufacturer ID field
+ JedecId[0] = (UINT8)val;
+ // Type field
+ JedecId[1] = (UINT8)(val >> 8);
+ // Capacity field
+ JedecId[2] = (UINT8)(val >> 16);
+
+ DEBUG ((
+ DEBUG_INFO,
+ "Nor flash detected, Jedec ID, Manufacturer Id=%x Type=%x Capacity=%x \n",
+ JedecId[0],
+ JedecId[1],
+ JedecId[2]
+ ));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ NOR Flash Reset
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Return success on every call.
+**/
+EFI_STATUS
+NorFlashReset (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ return EFI_SUCCESS;
+}
-- 
2.25.1







-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119338): https://edk2.groups.io/g/devel/message/119338
Mute This Topic: https://groups.io/mt/106365466/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp Sahil Kaushal
@ 2024-05-29 11:42   ` Sami Mujawar
  0 siblings, 0 replies; 24+ messages in thread
From: Sami Mujawar @ 2024-05-29 11:42 UTC (permalink / raw)
  To: Sahil Kaushal, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Leif Lindholm  , nd

Hi Sahil,

There is a typo in one of the macro names, see my comment inline marked [SAMI].
I will fix that up before merging.

Other than that, this patch looks good to me.

Reviewed-by: Sami Mujawar <sami.mujawar@arm.com>

Regards,

Sami Mujawar

On 29/05/2024, 09:56, "Sahil Kaushal" <Sahil.Kaushal@arm.com <mailto:Sahil.Kaushal@arm.com>> wrote:


From: sahil <sahil@arm.com <mailto:sahil@arm.com>>


Add NOR flash library, this library provides APIs for getting the list
of NOR flash devices on the platform.


This flash is shared between AP core and System Control Processor. The
lower addresses are used to store SCP and AP boot images and higher
addresses will be used for variable storage.


Signed-off-by: sahil <sahil@arm.com <mailto:sahil@arm.com>>
---
Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf | 35 +++++++++
Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h | 1 +
Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c | 80 ++++++++++++++++++++
3 files changed, 116 insertions(+)


diff --git a/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
new file mode 100644
index 000000000000..a9495cf667d5
--- /dev/null
+++ b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.inf
@@ -0,0 +1,35 @@
+## @file
+# NOR flash lib for ARM Neoverse N1 platform.
+#
+# Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+ INF_VERSION = 0x0001001B
+ BASE_NAME = NorFlashNeoverseN1SocLib
+ FILE_GUID = 7006fcf1-a585-4272-92e3-b286b1dff5bb
+ MODULE_TYPE = DXE_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashPlatformLib
+
+[Sources.common]
+ NorFlashLib.c
+
+[Packages]
+ MdeModulePkg/MdeModulePkg.dec
+ MdePkg/MdePkg.dec
+ Platform/ARM/ARM.dec
+ Silicon/ARM/NeoverseN1Soc/NeoverseN1Soc.dec
+
+[LibraryClasses]
+ BaseLib
+ DebugLib
+
+[FixedPcd]
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareSize
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingSize
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase
+ gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableSize
diff --git a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
index 2dae57a0f01a..2a592e5adc2f 100644
--- a/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
+++ b/Silicon/ARM/NeoverseN1Soc/Include/NeoverseN1Soc.h
@@ -47,6 +47,7 @@
// SCP QSPI flash device
#define NEOVERSEN1SOC_SCP_QSPI_AHB_BASE 0x18000000
#define NEOVERSEN1SOC_SCP_QSPI_AHB_SZ 0x2000000
+#define NEOVERSEN1SOC_FIRMWARE_IAMGES_SZ 0x800000
[SAMI] I noticed there is a typo in the macro above. I will fix that locally before merging.


/*
* Platform information structure stored in Non-secure SRAM. Platform
diff --git a/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c
new file mode 100644
index 000000000000..a354ffb5ac6d
--- /dev/null
+++ b/Silicon/ARM/NeoverseN1Soc/Library/NorFlashLib/NorFlashLib.c
@@ -0,0 +1,80 @@
+/** @file
+* NOR flash lib for ARM Neoverse N1 platform
+*
+* Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+*
+* SPDX-License-Identifier: BSD-2-Clause-Patent
+*
+**/
+
+#include <Library/DebugLib.h>
+#include <Library/NorFlashPlatformLib.h>
+#include <NeoverseN1Soc.h>
+#include <PiDxe.h>
+
+#define FW_ENV_REGION_BASE FixedPcdGet32 (PcdFlashNvStorageVariableBase)
+#define FW_ENV_REGION_SIZE (FixedPcdGet32 (PcdFlashNvStorageVariableSize) + \
+ FixedPcdGet32 (PcdFlashNvStorageFtwWorkingSize) + \
+ FixedPcdGet32 (PcdFlashNvStorageFtwSpareSize))
+
+STATIC NOR_FLASH_DESCRIPTION mNorFlashDevices[] = {
+ {
+ /// Environment variable region
+ NEOVERSEN1SOC_SCP_QSPI_AHB_BASE, ///< device base
+ FW_ENV_REGION_BASE, ///< region base
+ FW_ENV_REGION_SIZE, ///< region size
+ SIZE_4KB, ///< block size
+ },
+};
+
+/**
+ Dummy implementation of NorFlashPlatformInitialization to
+ comply with NorFlashPlatformLib structure.
+
+ @retval EFI_SUCCESS Success.
+**/
+EFI_STATUS
+NorFlashPlatformInitialization (
+ VOID
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Get NOR flash region info
+
+ @param[out] NorFlashDevices NOR flash regions info.
+ @param[out] Count number of flash instance.
+
+ @retval EFI_SUCCESS Success.
+ @retval EFI_INVALID_PARAMETER The parameters specified are not valid.
+ @retval EFI_ACCESS_DENIED Invalid variable region address.
+**/
+EFI_STATUS
+NorFlashPlatformGetDevices (
+ OUT NOR_FLASH_DESCRIPTION **NorFlashDevices,
+ OUT UINT32 *Count
+ )
+{
+ if ((NorFlashDevices == NULL) || (Count == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if ((NEOVERSEN1SOC_SCP_QSPI_AHB_BASE +
+ NEOVERSEN1SOC_FIRMWARE_IAMGES_SZ) >=
+ FW_ENV_REGION_BASE)
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashPlatformInitialization: Variable region overlapping with "
+ "firmware region.\n"
+ ));
+
+ return EFI_ACCESS_DENIED;
+ }
+
+ *NorFlashDevices = mNorFlashDevices;
+ *Count = ARRAY_SIZE (mNorFlashDevices);
+ return EFI_SUCCESS;
+}
-- 
2.25.1







-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119339): https://edk2.groups.io/g/devel/message/119339
Mute This Topic: https://groups.io/mt/106365465/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



^ permalink raw reply related	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
  2024-05-29 11:35   ` Sami Mujawar
@ 2024-05-29 11:51     ` Sahil Kaushal
  2024-05-29 12:38       ` Sami Mujawar
  0 siblings, 1 reply; 24+ messages in thread
From: Sahil Kaushal @ 2024-05-29 11:51 UTC (permalink / raw)
  To: Sami Mujawar, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Leif Lindholm  , nd

[-- Attachment #1: Type: text/plain, Size: 31455 bytes --]

Hi Sami,
Thank you for reviewing the patch.
You are right. The do-while loop is redundant and hence can be removed.
Thanks,
Sahil

From: Sami Mujawar <Sami.Mujawar@arm.com>
Date: Wednesday, 29 May 2024 at 5:06 PM
To: Sahil Kaushal <Sahil.Kaushal@arm.com>, devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>, Leif Lindholm   <quic_llindhol@quicinc.com>, nd <nd@arm.com>
Subject: Re: [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
Hi Sahil,

Please find my feedback inline marked [SAMI].

Regards,

Sami Mujawar

On 29/05/2024, 09:56, "Sahil Kaushal" <Sahil.Kaushal@arm.com <mailto:Sahil.Kaushal@arm.com>> wrote:


From: sahil <sahil@arm.com <mailto:sahil@arm.com>>


In N1Sdp platform, the SoC is connected to IOFPGA which has a
Cadence Quad SPI (QSPI) controller. This QSPI controller manages
the flash chip device via QSPI bus.


This patch adds CadenceQspiNorFlashDeviceLib which is used to
manage and access the above configuration.


Signed-off-by: sahil <sahil@arm.com <mailto:sahil@arm.com>>
---
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf | 32 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h | 46 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c | 1034 ++++++++++++++++++++
3 files changed, 1112 insertions(+)


diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
new file mode 100644
index 000000000000..506876b62285
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
@@ -0,0 +1,32 @@
+#/** @file
+#
+# Component description file for CadenceQspiNorFlashDeviceLib Library
+#
+# Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CadenceQspiNorFlashDeviceLib
+ FILE_GUID = ed172366-066b-4998-9b5e-ca7f385a170b
+ MODULE_TYPE = DXE_RUNTIME_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashDeviceLib
+
+[Sources.common]
+ CadenceQspiNorFlashDeviceLib.c
+ CadenceQspiNorFlashDeviceLib.h
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Platform/ARM/ARM.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ TimerLib
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
new file mode 100644
index 000000000000..951a93481dd1
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
@@ -0,0 +1,46 @@
+/** @file
+
+ Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+#define CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+
+#define NOR_FLASH_ERASE_RETRY 10
+
+// QSPI Controller defines
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET 0x90
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS 19
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS 16
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS 24
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_BYTE_3B 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS 23
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS 20
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C 0x8
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS 7
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS)
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS)
+
+#define CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET 0xA0
+
+#define CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET 0x94
+
+#define CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS 1000u // Command Status Register read timeout
+
+#define SPINOR_SR_WIP BIT0 // Write in progress
+
+#define SPINOR_OP_WREN 0x06 // Write enable
+#define SPINOR_OP_BE_4K 0x20 // Erase 4KiB block
+#define SPINOR_OP_RDID 0x9f // Read JEDEC ID
+#define SPINOR_OP_RDSR 0x05 // Read status register
+
+#define SPINOR_SR_WIP_POLL_TIMEOUT_MS 1000u // Status Register read timeout
+
+#endif /* CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
new file mode 100644
index 000000000000..f97c8d51fd48
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
@@ -0,0 +1,1034 @@
+/** @file
+
+ Copyright (c) 2024 ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/NorFlashDeviceLib.h>
+#include <Library/TimerLib.h>
+#include <Library/UefiLib.h>
+
+#include "CadenceQspiNorFlashDeviceLib.h"
+
+/**
+ Converts milliseconds into number of ticks of the performance counter.
+
+ @param[in] Milliseconds Milliseconds to convert into ticks.
+
+ @retval Milliseconds expressed as number of ticks.
+
+**/
+STATIC
+UINT64
+MilliSecondsToTicks (
+ IN UINTN Milliseconds
+ )
+{
+ UINT64 NanoSecondsPerTick;
+ UINT64 NanoSeconds;
+
+ NanoSecondsPerTick = GetTimeInNanoSecond (1);
+ NanoSeconds = MultU64x32 (Milliseconds, 1000000);
+
+ return DivU64x64Remainder (NanoSeconds, NanoSecondsPerTick, NULL);
+}
+
+/**
+ Execute Flash cmd ctrl and Read Status.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] Val Value to be written to Flash cmd ctrl Register.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Command execution timed out.
+
+**/
+STATIC
+EFI_STATUS
+CdnsQspiExecuteCommand (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINT32 Val
+ )
+{
+ // Set the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val
+ );
+ // Execute the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val | CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE
+ );
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS);
+
+ // Wait until command has been executed
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "CdnsQspiExecuteCommand: Timeout waiting for command execution.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+ } while ((MmioRead32 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET
+ ) &
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT) ==
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Poll Status register for NOR flash erase/write completion.
+
+ @param[in] Instance NOR flash Instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Operation timed out.
+ @retval EFI_DEVICE_ERROR Controller operation failed.
+
+**/
+STATIC
+EFI_STATUS
+NorFlashPollStatusRegister (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ BOOLEAN SRegDone;
+ UINT32 val;
+
+ val = (SPINOR_OP_RDSR << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (1) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS);
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (SPINOR_SR_WIP_POLL_TIMEOUT_MS);
+
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashPollStatusRegister: Timeout waiting for erase/write.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ SRegDone =
+ (MmioRead8 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ )
+ & SPINOR_SR_WIP
+ ) == 0;
+ } while (!SRegDone);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Check whether NOR flash operations are Locked.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval FALSE If NOR flash is not locked.
+**/
+STATIC
+BOOLEAN
+NorFlashBlockIsLocked (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return FALSE;
+}
+
+/**
+ Unlock NOR flash operations on given block.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS NOR flash operations unlocked.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Unlock NOR flash operations if it is necessary.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+
+ Status = EFI_SUCCESS;
+
+ if (!NorFlashBlockIsLocked (Instance, BlockAddress)) {
+ Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+ }
+
+ return Status;
+}
+
+/**
+ Enable write to NOR flash device.
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+STATIC
+EFI_STATUS
+NorFlashEnableWrite (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ UINT32 val;
+
+ DEBUG ((DEBUG_INFO, "NorFlashEnableWrite()\n"));
+ val = (SPINOR_OP_WREN << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS);
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The following function presumes that the block has already been unlocked.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress Block address within the variable region.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ UINT32 DevConfigVal;
+ UINT32 EraseOffset;
+
+ EraseOffset = 0x0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashEraseSingleBlock(BlockAddress=0x%08x)\n",
+ BlockAddress
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ EraseOffset = BlockAddress - Instance->DeviceBaseAddress;
+
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET,
+ EraseOffset
+ );
+
+ DevConfigVal = (SPINOR_OP_BE_4K << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, DevConfigVal))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function unlocks and erases an entire NOR Flash block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] BlockAddress Block address within the variable store region.
+
+ @retval EFI_SUCCESS Erase and unlock successfully completed.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_TPL OriginalTPL;
+
+ NorFlashLock (&OriginalTPL);
+
+ Index = 0;
+ do {
+ // Unlock the block if we have to
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Index++;
+ } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status != EFI_SUCCESS));
[SAMI] I think there is something wrong with the loop condition.
If I am not wrong, the check (Status != EFI_SUCCESS) does not seem to have any effect as the code in the while loop will break out of there is an error.
Can you check, please?
[/SAMI]


+
+ if (Index == NOR_FLASH_ERASE_RETRY) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error "
+ "(try to erase %d times)\n",
+ BlockAddress,
+ Index
+ ));
+ }
+
+ NorFlashUnlock (OriginalTPL);
+
+ return Status;
+}
+
+/**
+ Write a single word to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] WordAddress The address in NOR flash to write given word.
+ @param[in] WriteData The data to write into NOR flash location.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleWord (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN WordAddress,
+ IN UINT32 WriteData
+ )
+{
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleWord(WordAddress=0x%08x, WriteData=0x%08x)\n",
+ WordAddress,
+ WriteData
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ MmioWrite32 (WordAddress, WriteData);
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full block to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The logical block address in NOR flash.
+ @param[in] DataBuffer The data to write into NOR flash location.
+ @param[in] BlockSizeInWords The number of bytes to write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteFullBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINT32 *DataBuffer,
+ IN UINT32 BlockSizeInWords
+ )
+{
+ EFI_STATUS Status;
+ UINTN WordAddress;
+ UINT32 WordIndex;
+ UINTN BlockAddress;
+ EFI_TPL OriginalTPL;
+
+ Status = EFI_SUCCESS;
+
+ // Get the physical address of the block
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSizeInWords * 4
+ );
+
+ // Start writing from the first address at the start of the block
+ WordAddress = BlockAddress;
+
+ NorFlashLock (&OriginalTPL);
+
+ Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single "
+ "block at 0x%X\n",
+ BlockAddress
+ ));
+ goto exit_handler;
+ }
+
+ for (WordIndex = 0;
+ WordIndex < BlockSizeInWords;
+ WordIndex++, DataBuffer++, WordAddress += 4)
+ {
+ Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+ if (EFI_ERROR (Status)) {
+ goto exit_handler;
+ }
+ }
+
+exit_handler:
+ NorFlashUnlock (OriginalTPL);
+
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. "
+ "Exit Status = %r.\n",
+ WordAddress,
+ Status
+ ));
+ }
+
+ return Status;
+}
+
+/**
+ Write multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index.
+ @param[in] BufferSizeInBytes The number of bytes to write.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashWriteBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ )
+{
+ UINT32 *WriteBuffer;
+ EFI_STATUS Status;
+ EFI_LBA CurrentBlock;
+ UINT32 BlockSizeInWords;
+ UINT32 NumBlocks;
+ UINT32 BlockCount;
+
+ Status = EFI_SUCCESS;
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // We must have some bytes to read
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n",
+ BufferSizeInBytes
+ ));
+ if (BufferSizeInBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n",
+ Instance->Media.BlockSize
+ ));
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // All blocks must be within the device
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n",
+ NumBlocks,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+ // Because the target *Buffer is a pointer to VOID, we must put
+ // all the data into a pointer to a proper data type, so use *WriteBuffer
+ WriteBuffer = (UINT32 *)Buffer;
+
+ CurrentBlock = Lba;
+ for (BlockCount = 0;
+ BlockCount < NumBlocks;
+ BlockCount++, CurrentBlock++, WriteBuffer += BlockSizeInWords)
+ {
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: Writing block #%d\n",
+ (UINTN)CurrentBlock
+ ));
+
+ Status = NorFlashWriteFullBlock (
+ Instance,
+ CurrentBlock,
+ WriteBuffer,
+ BlockSizeInWords
+ );
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+
+ DEBUG ((DEBUG_INFO, "NorFlashWriteBlocks: Exit Status = %r.\n", Status));
+ return Status;
+}
+
+/**
+ Read multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashReadBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINT32 NumBlocks;
+ UINTN StartAddress;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, "
+ "Lba=%ld.\n",
+ BufferSizeInBytes,
+ Instance->Media.BlockSize,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashReadBlocks: ERROR - Read will exceed last block\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read from NOR flash.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] Offset Offset into the block at which to begin reading.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashRead (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINTN StartAddress;
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) >
+ Instance->Size)
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashRead: ERROR - Read will exceed device size.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)(StartAddress + Offset), BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full or portion of a block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to write to.
+ @param[in] Offset Offset into the block at which to begin writing.
+ @param[in, out] NumBytes The total size of the buffer.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Buffer size not enough.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 Tmp;
+ UINT32 TmpBuf;
+ UINT32 WordToWrite;
+ UINT32 Mask;
+ BOOLEAN DoErase;
+ UINTN BytesToWrite;
+ UINTN CurOffset;
+ UINTN WordAddr;
+ UINTN BlockSize;
+ UINTN BlockAddress;
+ UINTN PrevBlockAddress;
+
+ if (Buffer == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - Buffer is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (NumBytes == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - NumBytes is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ PrevBlockAddress = 0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, "
+ "*NumBytes=0x%x, Buffer @ 0x%08x)\n",
+ Lba,
+ Offset,
+ *NumBytes,
+ Buffer
+ ));
+
+ // Locate the block size to avoid de-referencing pointers all the time
+ BlockSize = Instance->Media.BlockSize;
+
+ // The write must not span block boundaries.
+ // We need to check each variable individually because adding two large
+ // values together overflows.
+ if ((Offset >= BlockSize) ||
+ (*NumBytes > BlockSize) ||
+ ((Offset + *NumBytes) > BlockSize))
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // We must have some bytes to write
+ if (*NumBytes == 0) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Pick 128bytes as a good start for word operations as opposed to erasing the
+ // block and writing the data regardless if an erase is really needed.
+ // It looks like most individual NV variable writes are smaller than 128bytes.
+ if (*NumBytes <= 128) {
+ // Check to see if we need to erase before programming the data into NOR.
+ // If the destination bits are only changing from 1s to 0s we can just write.
+ // After a block is erased all bits in the block is set to 1.
+ // If any byte requires us to erase we just give up and rewrite all of it.
+ DoErase = FALSE;
+ BytesToWrite = *NumBytes;
+ CurOffset = Offset;
+
+ while (BytesToWrite > 0) {
+ // Read full word from NOR, splice as required. A word is the smallest
+ // unit we can write.
+ Status = NorFlashRead (
+ Instance,
+ Lba,
+ CurOffset & ~(0x3),
+ sizeof (Tmp),
+ &Tmp
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Physical address of word in NOR to write.
+ WordAddr = (CurOffset & ~(0x3)) +
+ GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+
+ // The word of data that is to be written.
+ TmpBuf = ReadUnaligned32 (
+ (UINT32 *)(Buffer + (*NumBytes - BytesToWrite))
+ );
+
+ // First do word aligned chunks.
+ if ((CurOffset & 0x3) == 0) {
+ if (BytesToWrite >= 4) {
+ // Is the destination still in 'erased' state?
+ if (~Tmp != 0) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Write this word to NOR
+ WordToWrite = TmpBuf;
+ CurOffset += sizeof (TmpBuf);
+ BytesToWrite -= sizeof (TmpBuf);
+ } else {
+ // BytesToWrite < 4. Do small writes and left-overs
+ Mask = ~((~0) << (BytesToWrite * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ } else {
+ // Do multiple words, but starting unaligned.
+ if (BytesToWrite > (4 - (CurOffset & 0x3))) {
+ Mask = ((~0) << ((CurOffset & 0x3) * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ BytesToWrite -= (4 - (CurOffset & 0x3));
+ CurOffset += (4 - (CurOffset & 0x3));
+ } else {
+ // Unaligned and fits in one word.
+ Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
+ // Mask out the bytes we want.
+ TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ }
+
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+ if (BlockAddress != PrevBlockAddress) {
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ PrevBlockAddress = BlockAddress;
+ }
+
+ Status = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+ }
+
+ // Exit if we got here and could write all the data. Otherwise do the
+ // Erase-Write cycle.
+ if (!DoErase) {
+ return EFI_SUCCESS;
+ }
+ }
+
+ // Check we did get some memory. Buffer is BlockSize.
+ if (Instance->ShadowBuffer == NULL) {
+ DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Read NOR Flash data into shadow buffer
+ Status = NorFlashReadBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Put the data at the appropriate location inside the buffer area
+ CopyMem (
+ (VOID *)((UINTN)Instance->ShadowBuffer + Offset),
+ Buffer,
+ *NumBytes
+ );
+
+ // Write the modified buffer back to the NorFlash
+ Status = NorFlashWriteBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read JEDEC ID of NOR flash device.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[out] JedecId JEDEC ID of NOR flash device.
+ Maximum length of JedecId can be upto 6 bytes
+
+ @retval EFI_SUCCESS The write is completed.
+ @retval EFI_DEVICE_ERROR Failed to fetch JEDEC ID.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashReadId (
+ IN NOR_FLASH_INSTANCE *Instance,
+ OUT UINT8 *JedecId
+ )
+{
+ UINT32 val;
+
+ if ((Instance == NULL) || (JedecId == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ val = (SPINOR_OP_RDID <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ val = MmioRead32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ );
+
+ // Manufacturer ID field
+ JedecId[0] = (UINT8)val;
+ // Type field
+ JedecId[1] = (UINT8)(val >> 8);
+ // Capacity field
+ JedecId[2] = (UINT8)(val >> 16);
+
+ DEBUG ((
+ DEBUG_INFO,
+ "Nor flash detected, Jedec ID, Manufacturer Id=%x Type=%x Capacity=%x \n",
+ JedecId[0],
+ JedecId[1],
+ JedecId[2]
+ ));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ NOR Flash Reset
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Return success on every call.
+**/
+EFI_STATUS
+NorFlashReset (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ return EFI_SUCCESS;
+}
--
2.25.1






-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119340): https://edk2.groups.io/g/devel/message/119340
Mute This Topic: https://groups.io/mt/106365466/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 40091 bytes --]

^ permalink raw reply related	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
  2024-05-29 11:51     ` Sahil Kaushal
@ 2024-05-29 12:38       ` Sami Mujawar
  0 siblings, 0 replies; 24+ messages in thread
From: Sami Mujawar @ 2024-05-29 12:38 UTC (permalink / raw)
  To: Sahil Kaushal, devel@edk2.groups.io
  Cc: Ard Biesheuvel, Leif Lindholm  , nd

[-- Attachment #1: Type: text/plain, Size: 32034 bytes --]

Hi Sahil,

I will drop the loop before merging the changes.
Other than that this patch looks good to me.

Reviewed-by: Sami Mujawar <sami.mujawar@arm.com>

Regards,

Sami Mujawar

From: Sahil Kaushal <Sahil.Kaushal@arm.com>
Date: Wednesday 29 May 2024 at 12:51
To: Sami Mujawar <Sami.Mujawar@arm.com>, "devel@edk2.groups.io" <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>, Leif Lindholm   <quic_llindhol@quicinc.com>, nd <nd@arm.com>
Subject: Re: [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe

Hi Sami,
Thank you for reviewing the patch.
You are right. The do-while loop is redundant and hence can be removed.
Thanks,
Sahil

From: Sami Mujawar <Sami.Mujawar@arm.com>
Date: Wednesday, 29 May 2024 at 5:06 PM
To: Sahil Kaushal <Sahil.Kaushal@arm.com>, devel@edk2.groups.io <devel@edk2.groups.io>
Cc: Ard Biesheuvel <ardb+tianocore@kernel.org>, Leif Lindholm   <quic_llindhol@quicinc.com>, nd <nd@arm.com>
Subject: Re: [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe
Hi Sahil,

Please find my feedback inline marked [SAMI].

Regards,

Sami Mujawar

On 29/05/2024, 09:56, "Sahil Kaushal" <Sahil.Kaushal@arm.com <mailto:Sahil.Kaushal@arm.com>> wrote:


From: sahil <sahil@arm.com <mailto:sahil@arm.com>>


In N1Sdp platform, the SoC is connected to IOFPGA which has a
Cadence Quad SPI (QSPI) controller. This QSPI controller manages
the flash chip device via QSPI bus.


This patch adds CadenceQspiNorFlashDeviceLib which is used to
manage and access the above configuration.


Signed-off-by: sahil <sahil@arm.com <mailto:sahil@arm.com>>
---
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf | 32 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h | 46 +
Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c | 1034 ++++++++++++++++++++
3 files changed, 1112 insertions(+)


diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
new file mode 100644
index 000000000000..506876b62285
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.inf
@@ -0,0 +1,32 @@
+#/** @file
+#
+# Component description file for CadenceQspiNorFlashDeviceLib Library
+#
+# Copyright (c) 2024, Arm Limited. All rights reserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#**/
+
+[Defines]
+ INF_VERSION = 0x00010005
+ BASE_NAME = CadenceQspiNorFlashDeviceLib
+ FILE_GUID = ed172366-066b-4998-9b5e-ca7f385a170b
+ MODULE_TYPE = DXE_RUNTIME_DRIVER
+ VERSION_STRING = 1.0
+ LIBRARY_CLASS = NorFlashDeviceLib
+
+[Sources.common]
+ CadenceQspiNorFlashDeviceLib.c
+ CadenceQspiNorFlashDeviceLib.h
+
+[Packages]
+ MdePkg/MdePkg.dec
+ Platform/ARM/ARM.dec
+
+[LibraryClasses]
+ BaseLib
+ BaseMemoryLib
+ DebugLib
+ IoLib
+ TimerLib
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
new file mode 100644
index 000000000000..951a93481dd1
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.h
@@ -0,0 +1,46 @@
+/** @file
+
+ Copyright (c) 2024, ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+#define CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_
+
+#define NOR_FLASH_ERASE_RETRY 10
+
+// QSPI Controller defines
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET 0x90
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS 19
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS 16
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS 24
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE 0x01
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_BYTE_3B 0x02
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS 23
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS 20
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C 0x8
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS 7
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_READBYTE_BIT_POS)
+#define CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES(x) ((x - 1) << CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BYTE_BIT_POS)
+
+#define CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET 0xA0
+
+#define CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET 0x94
+
+#define CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS 1000u // Command Status Register read timeout
+
+#define SPINOR_SR_WIP BIT0 // Write in progress
+
+#define SPINOR_OP_WREN 0x06 // Write enable
+#define SPINOR_OP_BE_4K 0x20 // Erase 4KiB block
+#define SPINOR_OP_RDID 0x9f // Read JEDEC ID
+#define SPINOR_OP_RDSR 0x05 // Read status register
+
+#define SPINOR_SR_WIP_POLL_TIMEOUT_MS 1000u // Status Register read timeout
+
+#endif /* CADENCE_QSPI_NOR_FLASH_DEVICE_LIB_H_ */
diff --git a/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
new file mode 100644
index 000000000000..f97c8d51fd48
--- /dev/null
+++ b/Platform/ARM/Library/CadenceQspiNorFlashDeviceLib/CadenceQspiNorFlashDeviceLib.c
@@ -0,0 +1,1034 @@
+/** @file
+
+ Copyright (c) 2024 ARM Limited. All rights reserved.<BR>
+
+ SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#include <Library/BaseMemoryLib.h>
+#include <Library/DebugLib.h>
+#include <Library/IoLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/NorFlashDeviceLib.h>
+#include <Library/TimerLib.h>
+#include <Library/UefiLib.h>
+
+#include "CadenceQspiNorFlashDeviceLib.h"
+
+/**
+ Converts milliseconds into number of ticks of the performance counter.
+
+ @param[in] Milliseconds Milliseconds to convert into ticks.
+
+ @retval Milliseconds expressed as number of ticks.
+
+**/
+STATIC
+UINT64
+MilliSecondsToTicks (
+ IN UINTN Milliseconds
+ )
+{
+ UINT64 NanoSecondsPerTick;
+ UINT64 NanoSeconds;
+
+ NanoSecondsPerTick = GetTimeInNanoSecond (1);
+ NanoSeconds = MultU64x32 (Milliseconds, 1000000);
+
+ return DivU64x64Remainder (NanoSeconds, NanoSecondsPerTick, NULL);
+}
+
+/**
+ Execute Flash cmd ctrl and Read Status.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] Val Value to be written to Flash cmd ctrl Register.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Command execution timed out.
+
+**/
+STATIC
+EFI_STATUS
+CdnsQspiExecuteCommand (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINT32 Val
+ )
+{
+ // Set the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val
+ );
+ // Execute the command
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET,
+ Val | CDNS_QSPI_FLASH_CMD_CTRL_REG_EXECUTE
+ );
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (CDNS_QSPI_FLASH_CMD_STATUS_POLL_TIMEOUT_MS);
+
+ // Wait until command has been executed
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "CdnsQspiExecuteCommand: Timeout waiting for command execution.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+ } while ((MmioRead32 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OFFSET
+ ) &
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT) ==
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_STATUS_BIT
+ );
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Poll Status register for NOR flash erase/write completion.
+
+ @param[in] Instance NOR flash Instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_TIMEOUT Operation timed out.
+ @retval EFI_DEVICE_ERROR Controller operation failed.
+
+**/
+STATIC
+EFI_STATUS
+NorFlashPollStatusRegister (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ BOOLEAN SRegDone;
+ UINT32 val;
+
+ val = (SPINOR_OP_RDSR << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (1) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_8C <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_DUMMY_BIT_POS);
+
+ CONST UINT64 TickOut =
+ GetPerformanceCounter () +
+ MilliSecondsToTicks (SPINOR_SR_WIP_POLL_TIMEOUT_MS);
+
+ do {
+ if (GetPerformanceCounter () > TickOut) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashPollStatusRegister: Timeout waiting for erase/write.\n"
+ ));
+ return EFI_TIMEOUT;
+ }
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ SRegDone =
+ (MmioRead8 (
+ Instance->HostControllerBaseAddress +
+ CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ )
+ & SPINOR_SR_WIP
+ ) == 0;
+ } while (!SRegDone);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Check whether NOR flash operations are Locked.
+
+ @param[in] Instance NOR flash Instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval FALSE If NOR flash is not locked.
+**/
+STATIC
+BOOLEAN
+NorFlashBlockIsLocked (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return FALSE;
+}
+
+/**
+ Unlock NOR flash operations on given block.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS NOR flash operations unlocked.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ return EFI_SUCCESS;
+}
+
+/**
+ Unlock NOR flash operations if it is necessary.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress BlockAddress in NOR flash device.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+**/
+EFI_STATUS
+NorFlashUnlockSingleBlockIfNecessary (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+
+ Status = EFI_SUCCESS;
+
+ if (!NorFlashBlockIsLocked (Instance, BlockAddress)) {
+ Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
+ }
+
+ return Status;
+}
+
+/**
+ Enable write to NOR flash device.
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+STATIC
+EFI_STATUS
+NorFlashEnableWrite (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ UINT32 val;
+
+ DEBUG ((DEBUG_INFO, "NorFlashEnableWrite()\n"));
+ val = (SPINOR_OP_WREN << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS);
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ The following function presumes that the block has already been unlocked.
+
+ @param[in] Instance NOR flash instance.
+ @param[in] BlockAddress Block address within the variable region.
+
+ @retval EFI_SUCCESS Request is executed successfully.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+ **/
+EFI_STATUS
+NorFlashEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ UINT32 DevConfigVal;
+ UINT32 EraseOffset;
+
+ EraseOffset = 0x0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashEraseSingleBlock(BlockAddress=0x%08x)\n",
+ BlockAddress
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ EraseOffset = BlockAddress - Instance->DeviceBaseAddress;
+
+ MmioWrite32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_ADDR_REG_OFFSET,
+ EraseOffset
+ );
+
+ DevConfigVal = (SPINOR_OP_BE_4K << CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_ADDR_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_ADDR_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, DevConfigVal))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ This function unlocks and erases an entire NOR Flash block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] BlockAddress Block address within the variable store region.
+
+ @retval EFI_SUCCESS Erase and unlock successfully completed.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashUnlockAndEraseSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN BlockAddress
+ )
+{
+ EFI_STATUS Status;
+ UINTN Index;
+ EFI_TPL OriginalTPL;
+
+ NorFlashLock (&OriginalTPL);
+
+ Index = 0;
+ do {
+ // Unlock the block if we have to
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+
+ Index++;
+ } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status != EFI_SUCCESS));
[SAMI] I think there is something wrong with the loop condition.
If I am not wrong, the check (Status != EFI_SUCCESS) does not seem to have any effect as the code in the while loop will break out of there is an error.
Can you check, please?
[/SAMI]


+
+ if (Index == NOR_FLASH_ERASE_RETRY) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error "
+ "(try to erase %d times)\n",
+ BlockAddress,
+ Index
+ ));
+ }
+
+ NorFlashUnlock (OriginalTPL);
+
+ return Status;
+}
+
+/**
+ Write a single word to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] WordAddress The address in NOR flash to write given word.
+ @param[in] WriteData The data to write into NOR flash location.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleWord (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN UINTN WordAddress,
+ IN UINT32 WriteData
+ )
+{
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleWord(WordAddress=0x%08x, WriteData=0x%08x)\n",
+ WordAddress,
+ WriteData
+ ));
+
+ if (EFI_ERROR (NorFlashEnableWrite (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ MmioWrite32 (WordAddress, WriteData);
+ if (EFI_ERROR (NorFlashPollStatusRegister (Instance))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full block to given location.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The logical block address in NOR flash.
+ @param[in] DataBuffer The data to write into NOR flash location.
+ @param[in] BlockSizeInWords The number of bytes to write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteFullBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINT32 *DataBuffer,
+ IN UINT32 BlockSizeInWords
+ )
+{
+ EFI_STATUS Status;
+ UINTN WordAddress;
+ UINT32 WordIndex;
+ UINTN BlockAddress;
+ EFI_TPL OriginalTPL;
+
+ Status = EFI_SUCCESS;
+
+ // Get the physical address of the block
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSizeInWords * 4
+ );
+
+ // Start writing from the first address at the start of the block
+ WordAddress = BlockAddress;
+
+ NorFlashLock (&OriginalTPL);
+
+ Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single "
+ "block at 0x%X\n",
+ BlockAddress
+ ));
+ goto exit_handler;
+ }
+
+ for (WordIndex = 0;
+ WordIndex < BlockSizeInWords;
+ WordIndex++, DataBuffer++, WordAddress += 4)
+ {
+ Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
+ if (EFI_ERROR (Status)) {
+ goto exit_handler;
+ }
+ }
+
+exit_handler:
+ NorFlashUnlock (OriginalTPL);
+
+ if (EFI_ERROR (Status)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. "
+ "Exit Status = %r.\n",
+ WordAddress,
+ Status
+ ));
+ }
+
+ return Status;
+}
+
+/**
+ Write multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index.
+ @param[in] BufferSizeInBytes The number of bytes to write.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashWriteBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ IN VOID *Buffer
+ )
+{
+ UINT32 *WriteBuffer;
+ EFI_STATUS Status;
+ EFI_LBA CurrentBlock;
+ UINT32 BlockSizeInWords;
+ UINT32 NumBlocks;
+ UINT32 BlockCount;
+
+ Status = EFI_SUCCESS;
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // We must have some bytes to read
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n",
+ BufferSizeInBytes
+ ));
+ if (BufferSizeInBytes == 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n",
+ Instance->Media.BlockSize
+ ));
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // All blocks must be within the device
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n",
+ NumBlocks,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ BlockSizeInWords = Instance->Media.BlockSize / 4;
+
+ // Because the target *Buffer is a pointer to VOID, we must put
+ // all the data into a pointer to a proper data type, so use *WriteBuffer
+ WriteBuffer = (UINT32 *)Buffer;
+
+ CurrentBlock = Lba;
+ for (BlockCount = 0;
+ BlockCount < NumBlocks;
+ BlockCount++, CurrentBlock++, WriteBuffer += BlockSizeInWords)
+ {
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteBlocks: Writing block #%d\n",
+ (UINTN)CurrentBlock
+ ));
+
+ Status = NorFlashWriteFullBlock (
+ Instance,
+ CurrentBlock,
+ WriteBuffer,
+ BlockSizeInWords
+ );
+
+ if (EFI_ERROR (Status)) {
+ break;
+ }
+ }
+
+ DEBUG ((DEBUG_INFO, "NorFlashWriteBlocks: Exit Status = %r.\n", Status));
+ return Status;
+}
+
+/**
+ Read multiple blocks.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Invalid buffer size passed.
+**/
+EFI_STATUS
+NorFlashReadBlocks (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINT32 NumBlocks;
+ UINTN StartAddress;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, "
+ "Lba=%ld.\n",
+ BufferSizeInBytes,
+ Instance->Media.BlockSize,
+ Instance->Media.LastBlock,
+ Lba
+ ));
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ // The size of the buffer must be a multiple of the block size
+ if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize;
+
+ if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashReadBlocks: ERROR - Read will exceed last block\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)StartAddress, BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read from NOR flash.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to read from.
+ @param[in] Offset Offset into the block at which to begin reading.
+ @param[in] BufferSizeInBytes The number of bytes to read.
+ @param[out] Buffer The pointer to a caller-allocated buffer that
+ should be copied with read data.
+
+ @retval EFI_SUCCESS Read is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashRead (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN UINTN BufferSizeInBytes,
+ OUT VOID *Buffer
+ )
+{
+ UINTN StartAddress;
+
+ // The buffer must be valid
+ if (Buffer == NULL) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Return if we do not have any byte to read
+ if (BufferSizeInBytes == 0) {
+ return EFI_SUCCESS;
+ }
+
+ if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) >
+ Instance->Size)
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashRead: ERROR - Read will exceed device size.\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ // Get the address to start reading from
+ StartAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ Instance->Media.BlockSize
+ );
+
+ // Readout the data
+ CopyMem (Buffer, (UINTN *)(StartAddress + Offset), BufferSizeInBytes);
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Write a full or portion of a block.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[in] Lba The starting logical block index to write to.
+ @param[in] Offset Offset into the block at which to begin writing.
+ @param[in, out] NumBytes The total size of the buffer.
+ @param[in] Buffer The pointer to a caller-allocated buffer that
+ contains the source for the write.
+
+ @retval EFI_SUCCESS Write is complete.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+ @retval EFI_BAD_BUFFER_SIZE Buffer size not enough.
+ @retval EFI_DEVICE_ERROR The device reported an error.
+**/
+EFI_STATUS
+NorFlashWriteSingleBlock (
+ IN NOR_FLASH_INSTANCE *Instance,
+ IN EFI_LBA Lba,
+ IN UINTN Offset,
+ IN OUT UINTN *NumBytes,
+ IN UINT8 *Buffer
+ )
+{
+ EFI_STATUS Status;
+ UINT32 Tmp;
+ UINT32 TmpBuf;
+ UINT32 WordToWrite;
+ UINT32 Mask;
+ BOOLEAN DoErase;
+ UINTN BytesToWrite;
+ UINTN CurOffset;
+ UINTN WordAddr;
+ UINTN BlockSize;
+ UINTN BlockAddress;
+ UINTN PrevBlockAddress;
+
+ if (Buffer == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - Buffer is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ if (NumBytes == NULL) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - NumBytes is invalid\n"
+ ));
+ return EFI_INVALID_PARAMETER;
+ }
+
+ PrevBlockAddress = 0;
+
+ DEBUG ((
+ DEBUG_INFO,
+ "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, "
+ "*NumBytes=0x%x, Buffer @ 0x%08x)\n",
+ Lba,
+ Offset,
+ *NumBytes,
+ Buffer
+ ));
+
+ // Locate the block size to avoid de-referencing pointers all the time
+ BlockSize = Instance->Media.BlockSize;
+
+ // The write must not span block boundaries.
+ // We need to check each variable individually because adding two large
+ // values together overflows.
+ if ((Offset >= BlockSize) ||
+ (*NumBytes > BlockSize) ||
+ ((Offset + *NumBytes) > BlockSize))
+ {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // We must have some bytes to write
+ if (*NumBytes == 0) {
+ DEBUG ((
+ DEBUG_ERROR,
+ "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: "
+ "(Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n",
+ Offset,
+ *NumBytes,
+ BlockSize
+ ));
+ return EFI_BAD_BUFFER_SIZE;
+ }
+
+ // Pick 128bytes as a good start for word operations as opposed to erasing the
+ // block and writing the data regardless if an erase is really needed.
+ // It looks like most individual NV variable writes are smaller than 128bytes.
+ if (*NumBytes <= 128) {
+ // Check to see if we need to erase before programming the data into NOR.
+ // If the destination bits are only changing from 1s to 0s we can just write.
+ // After a block is erased all bits in the block is set to 1.
+ // If any byte requires us to erase we just give up and rewrite all of it.
+ DoErase = FALSE;
+ BytesToWrite = *NumBytes;
+ CurOffset = Offset;
+
+ while (BytesToWrite > 0) {
+ // Read full word from NOR, splice as required. A word is the smallest
+ // unit we can write.
+ Status = NorFlashRead (
+ Instance,
+ Lba,
+ CurOffset & ~(0x3),
+ sizeof (Tmp),
+ &Tmp
+ );
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Physical address of word in NOR to write.
+ WordAddr = (CurOffset & ~(0x3)) +
+ GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+
+ // The word of data that is to be written.
+ TmpBuf = ReadUnaligned32 (
+ (UINT32 *)(Buffer + (*NumBytes - BytesToWrite))
+ );
+
+ // First do word aligned chunks.
+ if ((CurOffset & 0x3) == 0) {
+ if (BytesToWrite >= 4) {
+ // Is the destination still in 'erased' state?
+ if (~Tmp != 0) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Write this word to NOR
+ WordToWrite = TmpBuf;
+ CurOffset += sizeof (TmpBuf);
+ BytesToWrite -= sizeof (TmpBuf);
+ } else {
+ // BytesToWrite < 4. Do small writes and left-overs
+ Mask = ~((~0) << (BytesToWrite * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ } else {
+ // Do multiple words, but starting unaligned.
+ if (BytesToWrite > (4 - (CurOffset & 0x3))) {
+ Mask = ((~0) << ((CurOffset & 0x3) * 8));
+ // Mask out the bytes we want.
+ TmpBuf &= Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ BytesToWrite -= (4 - (CurOffset & 0x3));
+ CurOffset += (4 - (CurOffset & 0x3));
+ } else {
+ // Unaligned and fits in one word.
+ Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
+ // Mask out the bytes we want.
+ TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
+ // Is the destination still in 'erased' state?
+ if ((Tmp & Mask) != Mask) {
+ // Check to see if we are only changing bits to zero.
+ if ((Tmp ^ TmpBuf) & TmpBuf) {
+ DoErase = TRUE;
+ break;
+ }
+ }
+
+ // Merge old and new data. Write merged word to NOR
+ WordToWrite = (Tmp & ~Mask) | TmpBuf;
+ CurOffset += BytesToWrite;
+ BytesToWrite = 0;
+ }
+ }
+
+ BlockAddress = GET_NOR_BLOCK_ADDRESS (
+ Instance->RegionBaseAddress,
+ Lba,
+ BlockSize
+ );
+ if (BlockAddress != PrevBlockAddress) {
+ Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ PrevBlockAddress = BlockAddress;
+ }
+
+ Status = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
+ if (EFI_ERROR (Status)) {
+ return EFI_DEVICE_ERROR;
+ }
+ }
+
+ // Exit if we got here and could write all the data. Otherwise do the
+ // Erase-Write cycle.
+ if (!DoErase) {
+ return EFI_SUCCESS;
+ }
+ }
+
+ // Check we did get some memory. Buffer is BlockSize.
+ if (Instance->ShadowBuffer == NULL) {
+ DEBUG ((DEBUG_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Read NOR Flash data into shadow buffer
+ Status = NorFlashReadBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ // Put the data at the appropriate location inside the buffer area
+ CopyMem (
+ (VOID *)((UINTN)Instance->ShadowBuffer + Offset),
+ Buffer,
+ *NumBytes
+ );
+
+ // Write the modified buffer back to the NorFlash
+ Status = NorFlashWriteBlocks (
+ Instance,
+ Lba,
+ BlockSize,
+ Instance->ShadowBuffer
+ );
+ if (EFI_ERROR (Status)) {
+ // Return one of the pre-approved error statuses
+ return EFI_DEVICE_ERROR;
+ }
+
+ return EFI_SUCCESS;
+}
+
+/**
+ Read JEDEC ID of NOR flash device.
+
+ @param[in] Instance NOR flash Instance of variable store region.
+ @param[out] JedecId JEDEC ID of NOR flash device.
+ Maximum length of JedecId can be upto 6 bytes
+
+ @retval EFI_SUCCESS The write is completed.
+ @retval EFI_DEVICE_ERROR Failed to fetch JEDEC ID.
+ @retval EFI_INVALID_PARAMETER Invalid parameters passed.
+**/
+EFI_STATUS
+NorFlashReadId (
+ IN NOR_FLASH_INSTANCE *Instance,
+ OUT UINT8 *JedecId
+ )
+{
+ UINT32 val;
+
+ if ((Instance == NULL) || (JedecId == NULL)) {
+ return EFI_INVALID_PARAMETER;
+ }
+
+ val = (SPINOR_OP_RDID <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_OPCODE_BIT_POS) |
+ (CDNS_QSPI_FLASH_CMD_CTRL_REG_READ_ENABLE <<
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_READEN_BIT_POS) |
+ CDNS_QSPI_FLASH_CMD_CTRL_REG_NUM_DATA_BYTES (3);
+
+ if (EFI_ERROR (CdnsQspiExecuteCommand (Instance, val))) {
+ return EFI_DEVICE_ERROR;
+ }
+
+ val = MmioRead32 (
+ Instance->HostControllerBaseAddress + CDNS_QSPI_FLASH_CMD_READ_DATA_REG_OFFSET
+ );
+
+ // Manufacturer ID field
+ JedecId[0] = (UINT8)val;
+ // Type field
+ JedecId[1] = (UINT8)(val >> 8);
+ // Capacity field
+ JedecId[2] = (UINT8)(val >> 16);
+
+ DEBUG ((
+ DEBUG_INFO,
+ "Nor flash detected, Jedec ID, Manufacturer Id=%x Type=%x Capacity=%x \n",
+ JedecId[0],
+ JedecId[1],
+ JedecId[2]
+ ));
+
+ return EFI_SUCCESS;
+}
+
+/**
+ NOR Flash Reset
+
+ @param[in] Instance NOR flash instance.
+
+ @retval EFI_SUCCESS Return success on every call.
+**/
+EFI_STATUS
+NorFlashReset (
+ IN NOR_FLASH_INSTANCE *Instance
+ )
+{
+ return EFI_SUCCESS;
+}
--
2.25.1





-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119341): https://edk2.groups.io/g/devel/message/119341
Mute This Topic: https://groups.io/mt/106365466/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 42743 bytes --]

^ permalink raw reply related	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (16 preceding siblings ...)
  2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 17/17] Platform/ARM/N1Sdp: Enable FaultTolerantWrite Dxe driver " Sahil Kaushal
@ 2024-05-29 15:27 ` Sami Mujawar
  2024-05-29 15:51 ` Sami Mujawar
  18 siblings, 0 replies; 24+ messages in thread
From: Sami Mujawar @ 2024-05-29 15:27 UTC (permalink / raw)
  To: Sahil Kaushal, devel

[-- Attachment #1: Type: text/plain, Size: 605 bytes --]

Other than my comments for patch 14 and 15 (the changes for which I will fix locally before merging), this patch series looks good to me.

For this series,

Reviewed-by: Sami Mujawar <sami.mujawar@arm.com>

Regards,

Sami Mujawar


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119354): https://edk2.groups.io/g/devel/message/119354
Mute This Topic: https://groups.io/mt/106365450/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 1055 bytes --]

^ permalink raw reply	[flat|nested] 24+ messages in thread

* Re: [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library
  2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
                   ` (17 preceding siblings ...)
  2024-05-29 15:27 ` [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sami Mujawar
@ 2024-05-29 15:51 ` Sami Mujawar
  18 siblings, 0 replies; 24+ messages in thread
From: Sami Mujawar @ 2024-05-29 15:51 UTC (permalink / raw)
  To: Sahil Kaushal, devel

[-- Attachment #1: Type: text/plain, Size: 443 bytes --]

Merged as f69888ada859..35bca3ca71c0

Thanks.

Regards,

Sami Mujawar


-=-=-=-=-=-=-=-=-=-=-=-
Groups.io Links: You receive all messages sent to this group.
View/Reply Online (#119355): https://edk2.groups.io/g/devel/message/119355
Mute This Topic: https://groups.io/mt/106365450/7686176
Group Owner: devel+owner@edk2.groups.io
Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io]
-=-=-=-=-=-=-=-=-=-=-=-



[-- Attachment #2: Type: text/html, Size: 879 bytes --]

^ permalink raw reply	[flat|nested] 24+ messages in thread

end of thread, other threads:[~2024-05-29 15:51 UTC | newest]

Thread overview: 24+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2024-05-29  8:55 [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 01/17] Platform/ARM/NorFlashDxe: Move DiskIo related functions out of NorFlash.c Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 02/17] Platform/ARM/NorFlashDxe: Move NorFlashVirtualNotifyEvent Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 03/17] Platform/ARM/NorFlashDxe: Add NorFlashCommon.h header file Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 04/17] Platform/ARM/NorFlashDxe: Move flash specific functions to NorFlash.c Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 05/17] Platform/ARM/NorFlashDxe: Remove unimplemented functions from NorFlash.h Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 06/17] Platform/ARM/NorFlashDxe: Make local functions STATIC Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 07/17] Platform/ARM: Create NorFlashDeviceLib library interface for flash specific functions Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 08/17] Platform/ARM: Add P30NorFlashDeviceLib Library Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 09/17] Platform/ARM/NorFlashDxe: Switch from NorFlash.c to NorFlashDeviceLib Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 10/17] Platform/ARM: Add HostControllerBaseAddress variable Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 11/17] Platform/ARM/NorFlashDxe: Fix memory leak in NorFlashCreateInstance() Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 12/17] Platform/ARM: Add optional provision to fetch and print NOR Flash info Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 13/17] Silicon/ARM/NeoverseN1Soc: Enable SCP QSPI flash region Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 14/17] Silicon/ARM/NeoverseN1Soc: NOR flash library for N1Sdp Sahil Kaushal
2024-05-29 11:42   ` Sami Mujawar
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 15/17] Platform/ARM: Add CadenceQspiNorFlashDeviceLib for NorFlashDxe Sahil Kaushal
2024-05-29 11:35   ` Sami Mujawar
2024-05-29 11:51     ` Sahil Kaushal
2024-05-29 12:38       ` Sami Mujawar
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 16/17] Platform/ARM/N1Sdp: Persistent storage for N1Sdp Sahil Kaushal
2024-05-29  8:55 ` [edk2-devel] [edk2-platforms][PATCH V4 17/17] Platform/ARM/N1Sdp: Enable FaultTolerantWrite Dxe driver " Sahil Kaushal
2024-05-29 15:27 ` [edk2-devel] [edk2-platforms][PATCH V4 00/17] Split NorFlashDxe driver and add CadenceQspiNorFlashDeviceLib library Sami Mujawar
2024-05-29 15:51 ` Sami Mujawar

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox