]> git.proxmox.com Git - mirror_edk2.git/blobdiff - MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWrite.c
MdeModulePkg: Refine type cast for pointer subtraction
[mirror_edk2.git] / MdeModulePkg / Universal / FaultTolerantWriteDxe / FaultTolerantWrite.c
index 53352881c4233aab40eb2397e6dac70aa176ef74..49e747b9016bd41fe2894d875ca4edc98d0cf6ea 100644 (file)
@@ -1,47 +1,10 @@
 /** @file\r
 \r
-  This is a simple fault tolerant write driver.\r
+  These are the common Fault Tolerant Write (FTW) functions that are shared \r
+  by DXE FTW driver and SMM FTW driver.\r
 \r
-  This boot service protocol only provides fault tolerant write capability for \r
-  block devices.  The protocol has internal non-volatile intermediate storage \r
-  of the data and private information. It should be able to recover \r
-  automatically from a critical fault, such as power failure. \r
-\r
-  The implementation uses an FTW (Fault Tolerant Write) Work Space. \r
-  This work space is a memory copy of the work space on the Working Block,\r
-  the size of the work space is the FTW_WORK_SPACE_SIZE bytes.\r
-  \r
-  The work space stores each write record as EFI_FTW_RECORD structure.\r
-  The spare block stores the write buffer before write to the target block.\r
-  \r
-  The write record has three states to specify the different phase of write operation.\r
-  1) WRITE_ALLOCATED is that the record is allocated in write space.\r
-     The information of write operation is stored in write record structure.\r
-  2) SPARE_COMPLETED is that the data from write buffer is writed into the spare block as the backup.\r
-  3) WRITE_COMPLETED is that the data is copied from the spare block to the target block.\r
-\r
-  This driver operates the data as the whole size of spare block.\r
-  It first read the SpareAreaLength data from the target block into the spare memory buffer.\r
-  Then copy the write buffer data into the spare memory buffer.\r
-  Then write the spare memory buffer into the spare block.\r
-  Final copy the data from the spare block to the target block.\r
-\r
-  To make this drive work well, the following conditions must be satisfied:\r
-  1. The write NumBytes data must be fit within Spare area. \r
-     Offset + NumBytes <= SpareAreaLength\r
-  2. The whole flash range has the same block size.\r
-  3. Working block is an area which contains working space in its last block and has the same size as spare block.\r
-  4. Working Block area must be in the single one Firmware Volume Block range which FVB protocol is produced on.  \r
-  5. Spare area must be in the single one Firmware Volume Block range which FVB protocol is produced on.\r
-  6. Any write data area (SpareAreaLength Area) which the data will be written into must be \r
-     in the single one Firmware Volume Block range which FVB protocol is produced on.\r
-  7. If write data area (such as Variable range) is enlarged, the spare area range must be enlarged.\r
-     The spare area must be enough large to store the write data before write them into the target range.\r
-  If one of them is not satisfied, FtwWrite may fail.\r
-  Usually, Spare area only takes one block. That's SpareAreaLength = BlockSize, NumberOfSpareBlock = 1.\r
-\r
-Copyright (c) 2006 - 2009, Intel Corporation                                                         \r
-All rights reserved. This program and the accompanying materials                          \r
+Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>\r
+This program and the accompanying materials                          \r
 are licensed and made available under the terms and conditions of the BSD License         \r
 which accompanies this distribution.  The full text of the license may be found at        \r
 http://opensource.org/licenses/bsd-license.php                                            \r
@@ -53,7 +16,6 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 \r
 #include "FaultTolerantWrite.h"\r
 \r
-\r
 //\r
 // Fault Tolerant Write Protocol API\r
 //\r
@@ -119,7 +81,6 @@ FtwAllocate (
   )\r
 {\r
   EFI_STATUS                      Status;\r
-  UINTN                           Length;\r
   UINTN                           Offset;\r
   EFI_FTW_DEVICE                  *FtwDevice;\r
   EFI_FAULT_TOLERANT_WRITE_HEADER *FtwHeader;\r
@@ -133,7 +94,7 @@ FtwAllocate (
   //\r
   // Check if there is enough space for the coming allocation\r
   //\r
-  if (WRITE_TOTAL_SIZE (NumberOfWrites, PrivateDataSize) > FtwDevice->FtwWorkSpaceHeader->WriteQueueSize) {\r
+  if (FTW_WRITE_TOTAL_SIZE (NumberOfWrites, PrivateDataSize) > FtwDevice->FtwWorkSpaceHeader->WriteQueueSize) {\r
     DEBUG ((EFI_D_ERROR, "Ftw: Allocate() request exceed Workspace, Caller: %g\n", CallerId));\r
     return EFI_BUFFER_TOO_SMALL;\r
   }\r
@@ -153,7 +114,7 @@ FtwAllocate (
   // If workspace is not enough, then reclaim workspace\r
   //\r
   Offset = (UINT8 *) FtwHeader - (UINT8 *) FtwDevice->FtwWorkSpace;\r
-  if (Offset + WRITE_TOTAL_SIZE (NumberOfWrites, PrivateDataSize) > FtwDevice->FtwWorkSpaceSize) {\r
+  if (Offset + FTW_WRITE_TOTAL_SIZE (NumberOfWrites, PrivateDataSize) > FtwDevice->FtwWorkSpaceSize) {\r
     Status = FtwReclaimWorkSpace (FtwDevice, TRUE);\r
     if (EFI_ERROR (Status)) {\r
       return EFI_ABORTED;\r
@@ -172,14 +133,14 @@ FtwAllocate (
   FtwHeader->PrivateDataSize  = PrivateDataSize;\r
   FtwHeader->HeaderAllocated  = FTW_VALID_STATE;\r
 \r
-  Length                      = sizeof (EFI_FAULT_TOLERANT_WRITE_HEADER);\r
-  Status = FtwDevice->FtwFvBlock->Write (\r
-                                    FtwDevice->FtwFvBlock,\r
-                                    FtwDevice->FtwWorkSpaceLba,\r
-                                    FtwDevice->FtwWorkSpaceBase + Offset,\r
-                                    &Length,\r
-                                    (UINT8 *) FtwHeader\r
-                                    );\r
+  Status = WriteWorkSpaceData (\r
+             FtwDevice->FtwFvBlock,\r
+             FtwDevice->WorkBlockSize,\r
+             FtwDevice->FtwWorkSpaceLba,\r
+             FtwDevice->FtwWorkSpaceBase + Offset,\r
+             sizeof (EFI_FAULT_TOLERANT_WRITE_HEADER),\r
+             (UINT8 *) FtwHeader\r
+             );\r
   if (EFI_ERROR (Status)) {\r
     return EFI_ABORTED;\r
   }\r
@@ -188,6 +149,7 @@ FtwAllocate (
   //\r
   Status = FtwUpdateFvState (\r
             FtwDevice->FtwFvBlock,\r
+            FtwDevice->WorkBlockSize,\r
             FtwDevice->FtwWorkSpaceLba,\r
             FtwDevice->FtwWorkSpaceBase + Offset,\r
             WRITES_ALLOCATED\r
@@ -197,7 +159,7 @@ FtwAllocate (
   }\r
 \r
   DEBUG (\r
-    (EFI_D_ERROR,\r
+    (EFI_D_INFO,\r
     "Ftw: Allocate() success, Caller:%g, # %d\n",\r
     CallerId,\r
     NumberOfWrites)\r
@@ -208,13 +170,14 @@ FtwAllocate (
 \r
 \r
 /**\r
-  Write a record with fault tolerant mannaer.\r
+  Write a record with fault tolerant manner.\r
   Since the content has already backuped in spare block, the write is\r
   guaranteed to be completed with fault tolerant manner.\r
 \r
   @param This            The pointer to this protocol instance. \r
   @param Fvb             The FVB protocol that provides services for\r
                          reading, writing, and erasing the target block.\r
+  @param BlockSize       The size of the block.\r
 \r
   @retval  EFI_SUCCESS          The function completed successfully\r
   @retval  EFI_ABORTED          The function could not complete successfully\r
@@ -223,7 +186,8 @@ FtwAllocate (
 EFI_STATUS\r
 FtwWriteRecord (\r
   IN EFI_FAULT_TOLERANT_WRITE_PROTOCOL     *This,\r
-  IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *Fvb\r
+  IN EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL    *Fvb,\r
+  IN UINTN                                 BlockSize\r
   )\r
 {\r
   EFI_STATUS                      Status;\r
@@ -231,12 +195,13 @@ FtwWriteRecord (
   EFI_FAULT_TOLERANT_WRITE_HEADER *Header;\r
   EFI_FAULT_TOLERANT_WRITE_RECORD *Record;\r
   UINTN                           Offset;\r
+  UINTN                           NumberOfWriteBlocks;\r
 \r
   FtwDevice = FTW_CONTEXT_FROM_THIS (This);\r
 \r
   //\r
   // Spare Complete but Destination not complete,\r
-  // Recover the targt block with the spare block.\r
+  // Recover the target block with the spare block.\r
   //\r
   Header  = FtwDevice->FtwLastWriteHeader;\r
   Record  = FtwDevice->FtwLastWriteRecord;\r
@@ -253,8 +218,9 @@ FtwWriteRecord (
     Offset = (UINT8 *) Record - FtwDevice->FtwWorkSpace;\r
     Status = FtwUpdateFvState (\r
               FtwDevice->FtwBackupFvb,\r
-              FtwDevice->FtwWorkSpaceLba,\r
-              FtwDevice->FtwWorkSpaceBase + Offset,\r
+              FtwDevice->SpareBlockSize,\r
+              FtwDevice->FtwSpareLba + FtwDevice->FtwWorkSpaceLbaInSpare,\r
+              FtwDevice->FtwWorkSpaceBaseInSpare + Offset,\r
               SPARE_COMPLETED\r
               );\r
     if (EFI_ERROR (Status)) {\r
@@ -262,7 +228,7 @@ FtwWriteRecord (
     }\r
 \r
     Status = FlushSpareBlockToWorkingBlock (FtwDevice);\r
-  } else if (IsBootBlock (FtwDevice, Fvb, Record->Lba)) {\r
+  } else if (IsBootBlock (FtwDevice, Fvb)) {\r
     //\r
     // Update boot block\r
     //\r
@@ -271,7 +237,8 @@ FtwWriteRecord (
     //\r
     // Update blocks other than working block or boot block\r
     //\r
-    Status = FlushSpareBlockToTargetBlock (FtwDevice, Fvb, Record->Lba);\r
+    NumberOfWriteBlocks = FTW_BLOCKS ((UINTN) (Record->Offset + Record->Length), BlockSize);\r
+    Status = FlushSpareBlockToTargetBlock (FtwDevice, Fvb, Record->Lba, BlockSize, NumberOfWriteBlocks);\r
   }\r
 \r
   if (EFI_ERROR (Status)) {\r
@@ -283,6 +250,7 @@ FtwWriteRecord (
   Offset = (UINT8 *) Record - FtwDevice->FtwWorkSpace;\r
   Status = FtwUpdateFvState (\r
             FtwDevice->FtwFvBlock,\r
+            FtwDevice->WorkBlockSize,\r
             FtwDevice->FtwWorkSpaceLba,\r
             FtwDevice->FtwWorkSpaceBase + Offset,\r
             DEST_COMPLETED\r
@@ -301,6 +269,7 @@ FtwWriteRecord (
     Offset = (UINT8 *) Header - FtwDevice->FtwWorkSpace;\r
     Status = FtwUpdateFvState (\r
               FtwDevice->FtwFvBlock,\r
+              FtwDevice->WorkBlockSize,\r
               FtwDevice->FtwWorkSpaceLba,\r
               FtwDevice->FtwWorkSpaceBase + Offset,\r
               WRITES_COMPLETED\r
@@ -365,6 +334,10 @@ FtwWrite (
   UINTN                               Index;\r
   UINT8                               *Ptr;\r
   EFI_PHYSICAL_ADDRESS                FvbPhysicalAddress;\r
+  UINTN                               BlockSize;\r
+  UINTN                               NumberOfBlocks;\r
+  UINTN                               NumberOfWriteBlocks;\r
+  UINTN                               WriteLength;\r
 \r
   FtwDevice = FTW_CONTEXT_FROM_THIS (This);\r
 \r
@@ -400,7 +373,7 @@ FtwWrite (
   //\r
   // If Record is out of the range of Header, return access denied.\r
   //\r
-  if (((UINTN)((UINT8 *) Record - (UINT8 *) Header)) > WRITE_TOTAL_SIZE (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {\r
+  if (((UINTN) Record - (UINTN) Header) > FTW_WRITE_TOTAL_SIZE (Header->NumberOfWrites - 1, Header->PrivateDataSize)) {\r
     return EFI_ACCESS_DENIED;\r
   }\r
 \r
@@ -418,12 +391,7 @@ FtwWrite (
   if ((Record->SpareComplete == FTW_VALID_STATE) && (Record->DestinationComplete != FTW_VALID_STATE)) {\r
     return EFI_NOT_READY;\r
   }\r
-  //\r
-  // Check if the input data can fit within the target block\r
-  //\r
-  if ((Offset + Length) > FtwDevice->SpareAreaLength) {\r
-    return EFI_BAD_BUFFER_SIZE;\r
-  }\r
+\r
   //\r
   // Get the FVB protocol by handle\r
   //\r
@@ -434,15 +402,39 @@ FtwWrite (
 \r
   Status = Fvb->GetPhysicalAddress (Fvb, &FvbPhysicalAddress);\r
   if (EFI_ERROR (Status)) {\r
-    DEBUG ((EFI_D_ERROR, "FtwLite: Get FVB physical address - %r\n", Status));\r
+    DEBUG ((EFI_D_ERROR, "Ftw: Write(), Get FVB physical address - %r\n", Status));\r
     return EFI_ABORTED;\r
   }\r
 \r
+  //\r
+  // Now, one FVB has one type of BlockSize.\r
+  //\r
+  Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);\r
+  if (EFI_ERROR (Status)) {\r
+    DEBUG ((EFI_D_ERROR, "Ftw: Write(), Get block size - %r\n", Status));\r
+    return EFI_ABORTED;\r
+  }\r
+\r
+  NumberOfWriteBlocks = FTW_BLOCKS (Offset + Length, BlockSize);\r
+  DEBUG ((EFI_D_INFO, "Ftw: Write(), BlockSize - 0x%x, NumberOfWriteBlock - 0x%x\n", BlockSize, NumberOfWriteBlocks));\r
+  WriteLength = NumberOfWriteBlocks * BlockSize;\r
+\r
+  //\r
+  // Check if the input data can fit within the spare block.\r
+  //\r
+  if (WriteLength > FtwDevice->SpareAreaLength) {\r
+    return EFI_BAD_BUFFER_SIZE;\r
+  }\r
+\r
   //\r
   // Set BootBlockUpdate FLAG if it's updating boot block.\r
   //\r
-  if (IsBootBlock (FtwDevice, Fvb, Lba)) {\r
+  if (IsBootBlock (FtwDevice, Fvb)) {\r
     Record->BootBlockUpdate = FTW_VALID_STATE;\r
+    //\r
+    // Boot Block and Spare Block should have same block size and block numbers.\r
+    //\r
+    ASSERT ((BlockSize == FtwDevice->SpareBlockSize) && (NumberOfWriteBlocks == FtwDevice->NumberOfSpareBlock));\r
   }\r
   //\r
   // Write the record to the work space.\r
@@ -450,21 +442,22 @@ FtwWrite (
   Record->Lba     = Lba;\r
   Record->Offset  = Offset;\r
   Record->Length  = Length;\r
-  Record->FvBaseAddress = FvbPhysicalAddress;\r
+  Record->RelativeOffset = (INT64) (FvbPhysicalAddress + (UINTN) Lba * BlockSize) - (INT64) FtwDevice->SpareAreaAddress;\r
   if (PrivateData != NULL) {\r
-    CopyMem ((Record + 1), PrivateData, Header->PrivateDataSize);\r
+    CopyMem ((Record + 1), PrivateData, (UINTN) Header->PrivateDataSize);\r
   }\r
 \r
   MyOffset  = (UINT8 *) Record - FtwDevice->FtwWorkSpace;\r
-  MyLength  = RECORD_SIZE (Header->PrivateDataSize);\r
-\r
-  Status = FtwDevice->FtwFvBlock->Write (\r
-                                    FtwDevice->FtwFvBlock,\r
-                                    FtwDevice->FtwWorkSpaceLba,\r
-                                    FtwDevice->FtwWorkSpaceBase + MyOffset,\r
-                                    &MyLength,\r
-                                    (UINT8 *) Record\r
-                                    );\r
+  MyLength  = FTW_RECORD_SIZE (Header->PrivateDataSize);\r
+\r
+  Status = WriteWorkSpaceData (\r
+             FtwDevice->FtwFvBlock,\r
+             FtwDevice->WorkBlockSize,\r
+             FtwDevice->FtwWorkSpaceLba,\r
+             FtwDevice->FtwWorkSpaceBase + MyOffset,\r
+             MyLength,\r
+             (UINT8 *) Record\r
+             );\r
   if (EFI_ERROR (Status)) {\r
     return EFI_ABORTED;\r
   }\r
@@ -474,7 +467,7 @@ FtwWrite (
   //\r
   // Allocate a memory buffer\r
   //\r
-  MyBufferSize  = FtwDevice->SpareAreaLength;\r
+  MyBufferSize  = WriteLength;\r
   MyBuffer      = AllocatePool (MyBufferSize);\r
   if (MyBuffer == NULL) {\r
     return EFI_OUT_OF_RESOURCES;\r
@@ -483,8 +476,8 @@ FtwWrite (
   // Read all original data from target block to memory buffer\r
   //\r
   Ptr = MyBuffer;\r
-  for (Index = 0; Index < FtwDevice->NumberOfSpareBlock; Index += 1) {\r
-    MyLength  = FtwDevice->BlockSize;\r
+  for (Index = 0; Index < NumberOfWriteBlocks; Index += 1) {\r
+    MyLength  = BlockSize;\r
     Status    = Fvb->Read (Fvb, Lba + Index, 0, &MyLength, Ptr);\r
     if (EFI_ERROR (Status)) {\r
       FreePool (MyBuffer);\r
@@ -512,7 +505,7 @@ FtwWrite (
 \r
   Ptr = SpareBuffer;\r
   for (Index = 0; Index < FtwDevice->NumberOfSpareBlock; Index += 1) {\r
-    MyLength = FtwDevice->BlockSize;\r
+    MyLength = FtwDevice->SpareBlockSize;\r
     Status = FtwDevice->FtwBackupFvb->Read (\r
                                         FtwDevice->FtwBackupFvb,\r
                                         FtwDevice->FtwSpareLba + Index,\r
@@ -530,11 +523,21 @@ FtwWrite (
   }\r
   //\r
   // Write the memory buffer to spare block\r
+  // Do not assume Spare Block and Target Block have same block size\r
   //\r
   Status  = FtwEraseSpareBlock (FtwDevice);\r
+  if (EFI_ERROR (Status)) {\r
+    FreePool (MyBuffer);\r
+    FreePool (SpareBuffer);\r
+    return EFI_ABORTED;\r
+  }\r
   Ptr     = MyBuffer;\r
-  for (Index = 0; Index < FtwDevice->NumberOfSpareBlock; Index += 1) {\r
-    MyLength = FtwDevice->BlockSize;\r
+  for (Index = 0; MyBufferSize > 0; Index += 1) {\r
+    if (MyBufferSize > FtwDevice->SpareBlockSize) {\r
+      MyLength = FtwDevice->SpareBlockSize;\r
+    } else {\r
+      MyLength = MyBufferSize;\r
+    }\r
     Status = FtwDevice->FtwBackupFvb->Write (\r
                                         FtwDevice->FtwBackupFvb,\r
                                         FtwDevice->FtwSpareLba + Index,\r
@@ -549,6 +552,7 @@ FtwWrite (
     }\r
 \r
     Ptr += MyLength;\r
+    MyBufferSize -= MyLength;\r
   }\r
   //\r
   // Free MyBuffer\r
@@ -561,6 +565,7 @@ FtwWrite (
   MyOffset = (UINT8 *) Record - FtwDevice->FtwWorkSpace;\r
   Status = FtwUpdateFvState (\r
             FtwDevice->FtwFvBlock,\r
+            FtwDevice->WorkBlockSize,\r
             FtwDevice->FtwWorkSpaceLba,\r
             FtwDevice->FtwWorkSpaceBase + MyOffset,\r
             SPARE_COMPLETED\r
@@ -576,7 +581,7 @@ FtwWrite (
   //  Since the content has already backuped in spare block, the write is\r
   //  guaranteed to be completed with fault tolerant manner.\r
   //\r
-  Status = FtwWriteRecord (This, Fvb);\r
+  Status = FtwWriteRecord (This, Fvb, BlockSize);\r
   if (EFI_ERROR (Status)) {\r
     FreePool (SpareBuffer);\r
     return EFI_ABORTED;\r
@@ -585,9 +590,13 @@ FtwWrite (
   // Restore spare backup buffer into spare block , if no failure happened during FtwWrite.\r
   //\r
   Status  = FtwEraseSpareBlock (FtwDevice);\r
+  if (EFI_ERROR (Status)) {\r
+    FreePool (SpareBuffer);\r
+    return EFI_ABORTED;\r
+  }\r
   Ptr     = SpareBuffer;\r
   for (Index = 0; Index < FtwDevice->NumberOfSpareBlock; Index += 1) {\r
-    MyLength = FtwDevice->BlockSize;\r
+    MyLength = FtwDevice->SpareBlockSize;\r
     Status = FtwDevice->FtwBackupFvb->Write (\r
                                         FtwDevice->FtwBackupFvb,\r
                                         FtwDevice->FtwSpareLba + Index,\r
@@ -608,7 +617,7 @@ FtwWrite (
   FreePool (SpareBuffer);\r
 \r
   DEBUG (\r
-    (EFI_D_ERROR,\r
+    (EFI_D_INFO,\r
     "Ftw: Write() success, (Lba:Offset)=(%lx:0x%x), Length: 0x%x\n",\r
     Lba,\r
     Offset,\r
@@ -644,6 +653,8 @@ FtwRestart (
   EFI_FAULT_TOLERANT_WRITE_HEADER     *Header;\r
   EFI_FAULT_TOLERANT_WRITE_RECORD     *Record;\r
   EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *Fvb;\r
+  UINTN                               BlockSize;\r
+  UINTN                               NumberOfBlocks;\r
 \r
   FtwDevice = FTW_CONTEXT_FROM_THIS (This);\r
 \r
@@ -664,6 +675,15 @@ FtwRestart (
     return EFI_NOT_FOUND;\r
   }\r
 \r
+  //\r
+  // Now, one FVB has one type of BlockSize\r
+  //\r
+  Status = Fvb->GetBlockSize (Fvb, 0, &BlockSize, &NumberOfBlocks);\r
+  if (EFI_ERROR (Status)) {\r
+    DEBUG ((EFI_D_ERROR, "Ftw: Restart(), Get block size - %r\n", Status));\r
+    return EFI_ABORTED;\r
+  }\r
+\r
   //\r
   // Check the COMPLETE flag of last write header\r
   //\r
@@ -686,7 +706,7 @@ FtwRestart (
   //  Since the content has already backuped in spare block, the write is\r
   //  guaranteed to be completed with fault tolerant manner.\r
   //\r
-  Status = FtwWriteRecord (This, Fvb);\r
+  Status = FtwWriteRecord (This, Fvb, BlockSize);\r
   if (EFI_ERROR (Status)) {\r
     return EFI_ABORTED;\r
   }\r
@@ -695,9 +715,12 @@ FtwRestart (
   // Erase Spare block\r
   // This is restart, no need to keep spareblock content.\r
   //\r
-  FtwEraseSpareBlock (FtwDevice);\r
+  Status = FtwEraseSpareBlock (FtwDevice);\r
+  if (EFI_ERROR (Status)) {\r
+    return EFI_ABORTED;\r
+  }\r
 \r
-  DEBUG ((EFI_D_ERROR, "Ftw: Restart() success \n"));\r
+  DEBUG ((EFI_D_INFO, "%a(): success\n", __FUNCTION__));\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -728,6 +751,10 @@ FtwAbort (
     return EFI_ABORTED;\r
   }\r
 \r
+  if (FtwDevice->FtwLastWriteHeader->HeaderAllocated != FTW_VALID_STATE) {\r
+    return EFI_NOT_FOUND;\r
+  }\r
+\r
   if (FtwDevice->FtwLastWriteHeader->Complete == FTW_VALID_STATE) {\r
     return EFI_NOT_FOUND;\r
   }\r
@@ -737,6 +764,7 @@ FtwAbort (
   Offset = (UINT8 *) FtwDevice->FtwLastWriteHeader - FtwDevice->FtwWorkSpace;\r
   Status = FtwUpdateFvState (\r
             FtwDevice->FtwFvBlock,\r
+            FtwDevice->WorkBlockSize,\r
             FtwDevice->FtwWorkSpaceLba,\r
             FtwDevice->FtwWorkSpaceBase + Offset,\r
             WRITES_COMPLETED\r
@@ -747,7 +775,7 @@ FtwAbort (
 \r
   FtwDevice->FtwLastWriteHeader->Complete = FTW_VALID_STATE;\r
 \r
-  DEBUG ((EFI_D_ERROR, "Ftw: Abort() success \n"));\r
+  DEBUG ((EFI_D_INFO, "%a(): success\n", __FUNCTION__));\r
   return EFI_SUCCESS;\r
 }\r
 \r
@@ -836,6 +864,7 @@ FtwGetLastWrite (
       *Complete = TRUE;\r
       return EFI_NOT_FOUND;\r
     }\r
+    ASSERT (Record != NULL);\r
   }\r
 \r
   //\r
@@ -843,389 +872,22 @@ FtwGetLastWrite (
   //\r
   CopyMem (CallerId, &Header->CallerId, sizeof (EFI_GUID));\r
   *Lba      = Record->Lba;\r
-  *Offset   = Record->Offset;\r
-  *Length   = Record->Length;\r
+  *Offset   = (UINTN) Record->Offset;\r
+  *Length   = (UINTN) Record->Length;\r
   *Complete = (BOOLEAN) (Record->DestinationComplete == FTW_VALID_STATE);\r
 \r
   if (*PrivateDataSize < Header->PrivateDataSize) {\r
-    *PrivateDataSize  = Header->PrivateDataSize;\r
+    *PrivateDataSize  = (UINTN) Header->PrivateDataSize;\r
     PrivateData       = NULL;\r
     Status            = EFI_BUFFER_TOO_SMALL;\r
   } else {\r
-    *PrivateDataSize = Header->PrivateDataSize;\r
+    *PrivateDataSize = (UINTN) Header->PrivateDataSize;\r
     CopyMem (PrivateData, Record + 1, *PrivateDataSize);\r
     Status = EFI_SUCCESS;\r
   }\r
 \r
-  DEBUG ((EFI_D_ERROR, "Ftw: GetLasetWrite() success\n"));\r
+  DEBUG ((EFI_D_INFO, "%a(): success\n", __FUNCTION__));\r
 \r
   return Status;\r
 }\r
 \r
-/**\r
-  This function is the entry point of the Fault Tolerant Write driver.\r
-\r
-  @param ImageHandle     A handle for the image that is initializing this driver\r
-  @param SystemTable     A pointer to the EFI system table\r
-\r
-  @return EFI_SUCCESS           FTW has finished the initialization\r
-  @retval EFI_NOT_FOUND         Locate FVB protocol error\r
-  @retval EFI_OUT_OF_RESOURCES  Allocate memory error\r
-  @retval EFI_VOLUME_CORRUPTED  Firmware volume is error\r
-  @retval EFI_ABORTED           FTW initialization error\r
-\r
-**/\r
-EFI_STATUS\r
-EFIAPI\r
-InitializeFaultTolerantWrite (\r
-  IN EFI_HANDLE         ImageHandle,\r
-  IN EFI_SYSTEM_TABLE   *SystemTable\r
-  )\r
-{\r
-  EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL  *Fvb;\r
-  UINTN                               Index;\r
-  EFI_HANDLE                          *HandleBuffer;\r
-  UINTN                               HandleCount;\r
-  EFI_FIRMWARE_VOLUME_HEADER          *FwVolHeader;\r
-  EFI_PHYSICAL_ADDRESS                BaseAddress;\r
-  EFI_FTW_DEVICE                      *FtwDevice;\r
-  EFI_FAULT_TOLERANT_WRITE_HEADER     *FtwHeader;\r
-  UINTN                               Length;\r
-  EFI_STATUS                          Status;\r
-  UINTN                               Offset;\r
-  EFI_FV_BLOCK_MAP_ENTRY              *FvbMapEntry;\r
-  UINT32                              LbaIndex;\r
-  EFI_HANDLE                          FvbHandle;\r
-\r
-  //\r
-  // Allocate Private data of this driver,\r
-  // INCLUDING THE FtwWorkSpace[FTW_WORK_SPACE_SIZE].\r
-  //\r
-  FvbHandle = NULL;\r
-  FtwDevice = NULL;\r
-  FtwDevice = AllocatePool (sizeof (EFI_FTW_DEVICE) + PcdGet32 (PcdFlashNvStorageFtwWorkingSize));\r
-  if (FtwDevice == NULL) {\r
-    return EFI_OUT_OF_RESOURCES;\r
-  }\r
-\r
-  ZeroMem (FtwDevice, sizeof (EFI_FTW_DEVICE));\r
-  FtwDevice->Signature = FTW_DEVICE_SIGNATURE;\r
-\r
-  //\r
-  // Initialize other parameters, and set WorkSpace as FTW_ERASED_BYTE.\r
-  //\r
-\r
-  FtwDevice->WorkSpaceAddress = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageFtwWorkingBase);\r
-  FtwDevice->WorkSpaceLength  = (UINTN) PcdGet32 (PcdFlashNvStorageFtwWorkingSize);\r
-\r
-  FtwDevice->SpareAreaAddress = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageFtwSpareBase);\r
-  FtwDevice->SpareAreaLength  = (UINTN) PcdGet32 (PcdFlashNvStorageFtwSpareSize);\r
-\r
-  if ((FtwDevice->WorkSpaceLength == 0) || (FtwDevice->SpareAreaLength == 0)) {\r
-    DEBUG ((EFI_D_ERROR, "Ftw: Workspace or Spare block does not exist!\n"));\r
-    FreePool (FtwDevice);\r
-    return EFI_OUT_OF_RESOURCES;\r
-  }\r
-  //\r
-  // Locate FVB protocol by handle\r
-  //\r
-  Status = gBS->LocateHandleBuffer (\r
-                  ByProtocol,\r
-                  &gEfiFirmwareVolumeBlockProtocolGuid,\r
-                  NULL,\r
-                  &HandleCount,\r
-                  &HandleBuffer\r
-                  );\r
-  if (EFI_ERROR (Status)) {\r
-    FreePool (FtwDevice);\r
-    return EFI_NOT_FOUND;\r
-  }\r
-\r
-  if (HandleCount <= 0) {\r
-    FreePool (FtwDevice);\r
-    return EFI_NOT_FOUND;\r
-  }\r
-\r
-  Fvb                         = NULL;\r
-  FtwDevice->FtwFvBlock       = NULL;\r
-  FtwDevice->FtwBackupFvb     = NULL;\r
-  FtwDevice->FtwWorkSpaceLba  = (EFI_LBA) (-1);\r
-  FtwDevice->FtwSpareLba      = (EFI_LBA) (-1);\r
-  for (Index = 0; Index < HandleCount; Index += 1) {\r
-    Status = gBS->HandleProtocol (\r
-                    HandleBuffer[Index],\r
-                    &gEfiFirmwareVolumeBlockProtocolGuid,\r
-                    (VOID **) &Fvb\r
-                    );\r
-    if (EFI_ERROR (Status)) {\r
-      FreePool (FtwDevice);\r
-      return Status;\r
-    }\r
-\r
-    Status = Fvb->GetPhysicalAddress (Fvb, &BaseAddress);\r
-    if (EFI_ERROR (Status)) {\r
-      continue;\r
-    }\r
-\r
-    FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) ((UINTN) BaseAddress);\r
-\r
-    if ((FtwDevice->WorkSpaceAddress >= BaseAddress) &&\r
-        ((FtwDevice->WorkSpaceAddress + FtwDevice->WorkSpaceLength) <= (BaseAddress + FwVolHeader->FvLength))\r
-        ) {\r
-      FtwDevice->FtwFvBlock = Fvb;\r
-      //\r
-      // To get the LBA of work space\r
-      //\r
-      if ((FwVolHeader->FvLength) > (FwVolHeader->HeaderLength)) {\r
-        //\r
-        // Now, one FV has one type of BlockLength\r
-        //\r
-        FvbMapEntry = &FwVolHeader->BlockMap[0];\r
-        for (LbaIndex = 1; LbaIndex <= FvbMapEntry->NumBlocks; LbaIndex += 1) {\r
-            if ((FtwDevice->WorkSpaceAddress >= (BaseAddress + FvbMapEntry->Length * (LbaIndex - 1)))\r
-              && (FtwDevice->WorkSpaceAddress < (BaseAddress + FvbMapEntry->Length * LbaIndex))) {\r
-            FtwDevice->FtwWorkSpaceLba = LbaIndex - 1;\r
-            //\r
-            // Get the Work space size and Base(Offset)\r
-            //\r
-            FtwDevice->FtwWorkSpaceSize = FtwDevice->WorkSpaceLength;\r
-            FtwDevice->FtwWorkSpaceBase = (UINTN) (FtwDevice->WorkSpaceAddress - (BaseAddress + FvbMapEntry->Length * (LbaIndex - 1)));\r
-            break;\r
-          }\r
-        }\r
-      }\r
-    }\r
-\r
-    if ((FtwDevice->SpareAreaAddress >= BaseAddress) &&\r
-        ((FtwDevice->SpareAreaAddress + FtwDevice->SpareAreaLength) <= (BaseAddress + FwVolHeader->FvLength))\r
-        ) {\r
-      FtwDevice->FtwBackupFvb = Fvb;\r
-      //\r
-      // To get the LBA of spare\r
-      //\r
-      if ((FwVolHeader->FvLength) > (FwVolHeader->HeaderLength)) {\r
-        //\r
-        // Now, one FV has one type of BlockLength\r
-        //\r
-        FvbMapEntry = &FwVolHeader->BlockMap[0];\r
-        for (LbaIndex = 1; LbaIndex <= FvbMapEntry->NumBlocks; LbaIndex += 1) {\r
-            if ((FtwDevice->SpareAreaAddress >= (BaseAddress + FvbMapEntry->Length * (LbaIndex - 1)))\r
-              && (FtwDevice->SpareAreaAddress < (BaseAddress + FvbMapEntry->Length * LbaIndex))) {\r
-            //\r
-            // Get the NumberOfSpareBlock and BlockSize\r
-            //\r
-            FtwDevice->FtwSpareLba        = LbaIndex - 1;\r
-            FtwDevice->BlockSize          = FvbMapEntry->Length;\r
-            FtwDevice->NumberOfSpareBlock = FtwDevice->SpareAreaLength / FtwDevice->BlockSize;\r
-            //\r
-            // Check the range of spare area to make sure that it's in FV range\r
-            //\r
-            if ((FtwDevice->FtwSpareLba + FtwDevice->NumberOfSpareBlock) > FvbMapEntry->NumBlocks) {\r
-              DEBUG ((EFI_D_ERROR, "Ftw: Spare area is out of FV range\n"));\r
-              FreePool (FtwDevice);\r
-              return EFI_ABORTED;\r
-            }\r
-            break;\r
-          }\r
-        }\r
-      }\r
-    }\r
-  }\r
-\r
-  //\r
-  // Calculate the start LBA of working block. Working block is an area which\r
-  // contains working space in its last block and has the same size as spare\r
-  // block, unless there are not enough blocks before the block that contains\r
-  // working space.\r
-  //\r
-  FtwDevice->FtwWorkBlockLba = FtwDevice->FtwWorkSpaceLba - FtwDevice->NumberOfSpareBlock + 1;\r
-  if ((INT64) (FtwDevice->FtwWorkBlockLba) < 0) {\r
-    DEBUG ((EFI_D_ERROR, "Ftw: The spare block range is too large than the working block range!\n"));\r
-    FreePool (FtwDevice);\r
-    return EFI_ABORTED;\r
-  }\r
-\r
-  if ((FtwDevice->FtwFvBlock == NULL) ||\r
-      (FtwDevice->FtwBackupFvb == NULL) ||\r
-      (FtwDevice->FtwWorkSpaceLba == (EFI_LBA) (-1)) ||\r
-      (FtwDevice->FtwSpareLba == (EFI_LBA) (-1))\r
-      ) {\r
-    DEBUG ((EFI_D_ERROR, "Ftw: Working or spare FVB not ready\n"));\r
-    FreePool (FtwDevice);\r
-    return EFI_ABORTED;\r
-  }\r
-  //\r
-  // Initialize other parameters, and set WorkSpace as FTW_ERASED_BYTE.\r
-  //\r
-  FtwDevice->FtwWorkSpace = (UINT8 *) (FtwDevice + 1);\r
-  FtwDevice->FtwWorkSpaceHeader = (EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER *) FtwDevice->FtwWorkSpace;\r
-\r
-  FtwDevice->FtwLastWriteHeader = NULL;\r
-  FtwDevice->FtwLastWriteRecord = NULL;\r
-\r
-  //\r
-  // Refresh the working space data from working block\r
-  //\r
-  Status = WorkSpaceRefresh (FtwDevice);\r
-  if (EFI_ERROR (Status)) {\r
-    goto Recovery;\r
-  }\r
-  //\r
-  // If the working block workspace is not valid, try the spare block\r
-  //\r
-  if (!IsValidWorkSpace (FtwDevice->FtwWorkSpaceHeader)) {\r
-    //\r
-    // Read from spare block\r
-    //\r
-    Length = FtwDevice->FtwWorkSpaceSize;\r
-    Status = FtwDevice->FtwBackupFvb->Read (\r
-                                        FtwDevice->FtwBackupFvb,\r
-                                        FtwDevice->FtwSpareLba,\r
-                                        FtwDevice->FtwWorkSpaceBase,\r
-                                        &Length,\r
-                                        FtwDevice->FtwWorkSpace\r
-                                        );\r
-    if (EFI_ERROR (Status)) {\r
-      goto Recovery;\r
-    }\r
-    //\r
-    // If spare block is valid, then replace working block content.\r
-    //\r
-    if (IsValidWorkSpace (FtwDevice->FtwWorkSpaceHeader)) {\r
-      Status = FlushSpareBlockToWorkingBlock (FtwDevice);\r
-      DEBUG ((EFI_D_ERROR, "Ftw: Restart working block update in Init() - %r\n", Status));\r
-      FtwAbort (&FtwDevice->FtwInstance);\r
-      //\r
-      // Refresh work space.\r
-      //\r
-      Status = WorkSpaceRefresh (FtwDevice);\r
-      if (EFI_ERROR (Status)) {\r
-        goto Recovery;\r
-      }\r
-    } else {\r
-      DEBUG ((EFI_D_ERROR, "Ftw: Both are invalid, init workspace\n"));\r
-      //\r
-      // If both are invalid, then initialize work space.\r
-      //\r
-      SetMem (\r
-        FtwDevice->FtwWorkSpace,\r
-        FtwDevice->FtwWorkSpaceSize,\r
-        FTW_ERASED_BYTE\r
-        );\r
-      InitWorkSpaceHeader (FtwDevice->FtwWorkSpaceHeader);\r
-      //\r
-      // Initialize the work space\r
-      //\r
-      Status = FtwReclaimWorkSpace (FtwDevice, FALSE);\r
-      if (EFI_ERROR (Status)) {\r
-        goto Recovery;\r
-      }\r
-    }\r
-  }\r
-\r
-  //\r
-  // If the FtwDevice->FtwLastWriteRecord is 1st record of write header &&\r
-  // (! SpareComplete)  THEN  call Abort().\r
-  //\r
-  if ((FtwDevice->FtwLastWriteHeader->HeaderAllocated == FTW_VALID_STATE) &&\r
-      (FtwDevice->FtwLastWriteRecord->SpareComplete != FTW_VALID_STATE) &&\r
-      IsFirstRecordOfWrites (FtwDevice->FtwLastWriteHeader, FtwDevice->FtwLastWriteRecord)\r
-        ) {\r
-    DEBUG ((EFI_D_ERROR, "Ftw: Init.. find first record not SpareCompleted, abort()\n"));\r
-    FtwAbort (&FtwDevice->FtwInstance);\r
-  }\r
-  //\r
-  // If Header is incompleted and the last record has completed, then\r
-  // call Abort() to set the Header->Complete FLAG.\r
-  //\r
-  if ((FtwDevice->FtwLastWriteHeader->Complete != FTW_VALID_STATE) &&\r
-      (FtwDevice->FtwLastWriteRecord->DestinationComplete == FTW_VALID_STATE) &&\r
-      IsLastRecordOfWrites (FtwDevice->FtwLastWriteHeader, FtwDevice->FtwLastWriteRecord)\r
-        ) {\r
-    DEBUG ((EFI_D_ERROR, "Ftw: Init.. find last record completed but header not, abort()\n"));\r
-    FtwAbort (&FtwDevice->FtwInstance);\r
-  }\r
-  //\r
-  // To check the workspace buffer following last Write header/records is EMPTY or not.\r
-  // If it's not EMPTY, FTW also need to call reclaim().\r
-  //\r
-  FtwHeader = FtwDevice->FtwLastWriteHeader;\r
-  Offset    = (UINT8 *) FtwHeader - FtwDevice->FtwWorkSpace;\r
-  if (FtwDevice->FtwWorkSpace[Offset] != FTW_ERASED_BYTE) {\r
-    Offset += WRITE_TOTAL_SIZE (FtwHeader->NumberOfWrites, FtwHeader->PrivateDataSize);\r
-  }\r
-\r
-  if (!IsErasedFlashBuffer (\r
-        FtwDevice->FtwWorkSpace + Offset,\r
-        FtwDevice->FtwWorkSpaceSize - Offset\r
-        )) {\r
-    Status = FtwReclaimWorkSpace (FtwDevice, TRUE);\r
-    if (EFI_ERROR (Status)) {\r
-      goto Recovery;\r
-    }\r
-  }\r
-  //\r
-  // Restart if it's boot block\r
-  //\r
-  if ((FtwDevice->FtwLastWriteHeader->Complete != FTW_VALID_STATE) &&\r
-      (FtwDevice->FtwLastWriteRecord->SpareComplete == FTW_VALID_STATE)\r
-      ) {\r
-    if (FtwDevice->FtwLastWriteRecord->BootBlockUpdate == FTW_VALID_STATE) {\r
-      Status = FlushSpareBlockToBootBlock (FtwDevice);\r
-      DEBUG ((EFI_D_ERROR, "Ftw: Restart boot block update - %r\n", Status));\r
-      if (EFI_ERROR (Status)) {\r
-        goto Recovery;\r
-      }\r
-  \r
-      FtwAbort (&FtwDevice->FtwInstance);\r
-    } else {\r
-      //\r
-      // if (SpareCompleted) THEN  Restart to fault tolerant write.\r
-      //\r
-      FvbHandle = GetFvbByAddress (FtwDevice->FtwLastWriteRecord->FvBaseAddress, &Fvb);\r
-      if (FvbHandle != NULL) {\r
-        Status = FtwRestart (&FtwDevice->FtwInstance, FvbHandle);\r
-        DEBUG ((EFI_D_ERROR, "FtwLite: Restart last write - %r\n", Status));\r
-        if (EFI_ERROR (Status)) {\r
-          goto Recovery;\r
-        }\r
-      }\r
-      FtwAbort (&FtwDevice->FtwInstance);\r
-    }\r
-  }\r
-\r
-  //\r
-  // Hook the protocol API\r
-  //\r
-  FtwDevice->FtwInstance.GetMaxBlockSize  = FtwGetMaxBlockSize;\r
-  FtwDevice->FtwInstance.Allocate         = FtwAllocate;\r
-  FtwDevice->FtwInstance.Write            = FtwWrite;\r
-  FtwDevice->FtwInstance.Restart          = FtwRestart;\r
-  FtwDevice->FtwInstance.Abort            = FtwAbort;\r
-  FtwDevice->FtwInstance.GetLastWrite     = FtwGetLastWrite;\r
-\r
-  //\r
-  // Install protocol interface\r
-  //\r
-  Status = gBS->InstallProtocolInterface (\r
-                  &FtwDevice->Handle,\r
-                  &gEfiFaultTolerantWriteProtocolGuid,\r
-                  EFI_NATIVE_INTERFACE,\r
-                  &FtwDevice->FtwInstance\r
-                  );\r
-  if (EFI_ERROR (Status)) {\r
-    goto Recovery;\r
-  }\r
-\r
-  return EFI_SUCCESS;\r
-\r
-Recovery:\r
-\r
-  if (FtwDevice != NULL) {\r
-    FreePool (FtwDevice);\r
-  }\r
-\r
-  DEBUG ((EFI_D_ERROR, "Ftw: Severe Error occurs, need to recovery\n"));\r
-\r
-  return EFI_VOLUME_CORRUPTED;\r
-}\r