[edk2] [PATCH v2 4/4] UefiCpuPkg/CpuDxe: Enable protection for newly added page table

Jian J Wang posted 4 patches 7 years ago
There is a newer version of this series
[edk2] [PATCH v2 4/4] UefiCpuPkg/CpuDxe: Enable protection for newly added page table
Posted by Jian J Wang 7 years ago
> v2:
>    Use the page table pool to allocate new page tables and save code
>    to enable protection for them separately.

One of the functionalities of CpuDxe is to update memory paging attributes.
If page table protection is applied, it must be disabled temporarily before
any attributes update and enabled again afterwards.

Another job in this patch is to re-use the page table pool reserved in DxeIpl,
if there're still free pages in it. Otherwise, the driver will reserve another
block of memory (specified by PcdPageTablePoolUnitSize and
PcdPageTablePoolAlignment) as new page table pool. The protection will be only
applied to the whole pool instead of individual table pages. Same as DxeIpl,
this helps to reduce potential "split" operation and recursive calling of
SetMemorySpaceAttributes().

Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Eric Dong <eric.dong@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Cc: Ruiyu Ni <ruiyu.ni@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Jian J Wang <jian.j.wang@intel.com>
---
 UefiCpuPkg/CpuDxe/CpuDxe.c       |  17 +-
 UefiCpuPkg/CpuDxe/CpuDxe.h       |   2 +
 UefiCpuPkg/CpuDxe/CpuDxe.inf     |   3 +
 UefiCpuPkg/CpuDxe/CpuPageTable.c | 329 ++++++++++++++++++++++++++++++++++++++-
 UefiCpuPkg/CpuDxe/CpuPageTable.h |  22 +++
 5 files changed, 364 insertions(+), 9 deletions(-)

diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.c b/UefiCpuPkg/CpuDxe/CpuDxe.c
index 8ddebabd02..6ae2dcd1c7 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.c
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.c
@@ -25,6 +25,7 @@
 BOOLEAN                   InterruptState = FALSE;
 EFI_HANDLE                mCpuHandle = NULL;
 BOOLEAN                   mIsFlushingGCD;
+BOOLEAN                   mIsAllocatingPageTable = FALSE;
 UINT64                    mValidMtrrAddressMask;
 UINT64                    mValidMtrrBitsMask;
 UINT64                    mTimerPeriod = 0;
@@ -407,6 +408,20 @@ CpuSetMemoryAttributes (
     return EFI_SUCCESS;
   }
 
+  //
+  // During memory attributes updating, new pages may be allocated to setup
+  // smaller granularity of page table. Page allocation action might then cause
+  // another calling of CpuSetMemoryAttributes() recursively, due to memory
+  // protection policy configured (such as PcdDxeNxMemoryProtectionPolicy).
+  // Since this driver will always protect memory used as page table by itself,
+  // there's no need to apply protection policy requested from memory service.
+  // So it's safe to just return EFI_SUCCESS if this time of calling is caused
+  // by page table memory allocation.
+  //
+  if (mIsAllocatingPageTable) {
+    DEBUG((DEBUG_VERBOSE, "  Allocating page table memory\n"));
+    return EFI_SUCCESS;
+  }
 
   CacheAttributes = Attributes & CACHE_ATTRIBUTE_MASK;
   MemoryAttributes = Attributes & MEMORY_ATTRIBUTE_MASK;
@@ -487,7 +502,7 @@ CpuSetMemoryAttributes (
   //
   // Set memory attribute by page table
   //
-  return AssignMemoryPageAttributes (NULL, BaseAddress, Length, MemoryAttributes, AllocatePages);
+  return AssignMemoryPageAttributes (NULL, BaseAddress, Length, MemoryAttributes, NULL);
 }
 
 /**
diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.h b/UefiCpuPkg/CpuDxe/CpuDxe.h
index 9c0d22359d..540f5f2dbf 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.h
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.h
@@ -273,5 +273,7 @@ RefreshGcdMemoryAttributesFromPaging (
   VOID
   );
 
+extern BOOLEAN mIsAllocatingPageTable;
+
 #endif
 
diff --git a/UefiCpuPkg/CpuDxe/CpuDxe.inf b/UefiCpuPkg/CpuDxe/CpuDxe.inf
index 3e8d196739..0a45285427 100644
--- a/UefiCpuPkg/CpuDxe/CpuDxe.inf
+++ b/UefiCpuPkg/CpuDxe/CpuDxe.inf
@@ -74,6 +74,7 @@
 [Guids]
   gIdleLoopEventGuid                            ## CONSUMES           ## Event
   gEfiVectorHandoffTableGuid                    ## SOMETIMES_CONSUMES ## SystemTable
+  gPageTablePoolGuid                            ## CONSUMES
 
 [Ppis]
   gEfiSecPlatformInformation2PpiGuid            ## UNDEFINED # HOB
@@ -81,6 +82,8 @@
 
 [Pcd]
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolUnitSize               ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolAlignment              ## CONSUMES
 
 [Depex]
   TRUE
diff --git a/UefiCpuPkg/CpuDxe/CpuPageTable.c b/UefiCpuPkg/CpuDxe/CpuPageTable.c
index 9658ed74c5..03b54a2111 100644
--- a/UefiCpuPkg/CpuDxe/CpuPageTable.c
+++ b/UefiCpuPkg/CpuDxe/CpuPageTable.c
@@ -62,6 +62,9 @@
 #define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull
 #define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull
 
+#define PAGE_TABLE_POOL_ALIGN_MASK   \
+    (~(EFI_PHYSICAL_ADDRESS)(FixedPcdGet32 (PcdPageTablePoolAlignment) - 1))
+
 typedef enum {
   PageNone,
   Page4K,
@@ -87,6 +90,8 @@ PAGE_ATTRIBUTE_TABLE mPageAttributeTable[] = {
   {Page1G,  SIZE_1GB, PAGING_1G_ADDRESS_MASK_64},
 };
 
+PAGE_TABLE_POOL_HEADER   *mPageTablePool = NULL;
+
 /**
   Enable write protection function for AP.
 
@@ -172,10 +177,6 @@ GetCurrentPagingContext (
   }
   if ((AsmReadCr0 () & BIT31) != 0) {
     PagingContext->ContextData.X64.PageTableBase = (AsmReadCr3 () & PAGING_4K_ADDRESS_MASK_64);
-    if ((AsmReadCr0 () & BIT16) == 0) {
-      AsmWriteCr0 (AsmReadCr0 () | BIT16);
-      SyncMemoryPageAttributesAp (SyncCpuEnableWriteProtection);
-    }
   } else {
     PagingContext->ContextData.X64.PageTableBase = 0;
   }
@@ -561,6 +562,59 @@ SplitPage (
   }
 }
 
+/**
+ Check the WP status in CR0 register. This bit is used to lock or unlock write
+ access to pages marked as read-only.
+
+  @retval TRUE    Write protection is enabled.
+  @retval FALSE   Write protection is disabled.
+**/
+BOOLEAN
+IsReadOnlyPageWriteProtected (
+  VOID
+  )
+{
+  return ((AsmReadCr0 () & BIT16) != 0);
+}
+
+/**
+  Disable write protection function for AP.
+
+  @param[in,out] Buffer  The pointer to private data buffer.
+**/
+VOID
+EFIAPI
+SyncCpuDisableWriteProtection (
+  IN OUT VOID *Buffer
+  )
+{
+  AsmWriteCr0 (AsmReadCr0() & ~BIT16);
+}
+
+/**
+ Disable Write Protect on pages marked as read-only.
+**/
+VOID
+DisableReadOnlyPageWriteProtect (
+  VOID
+  )
+{
+  AsmWriteCr0 (AsmReadCr0() & ~BIT16);
+  SyncMemoryPageAttributesAp (SyncCpuDisableWriteProtection);
+}
+
+/**
+ Enable Write Protect on pages marked as read-only.
+**/
+VOID
+EnableReadOnlyPageWriteProtect (
+  VOID
+  )
+{
+  AsmWriteCr0 (AsmReadCr0() | BIT16);
+  SyncMemoryPageAttributesAp (SyncCpuEnableWriteProtection);
+}
+
 /**
   This function modifies the page attributes for the memory region specified by BaseAddress and
   Length from their current attributes to the attributes specified by Attributes.
@@ -609,6 +663,7 @@ ConvertMemoryPageAttributes (
   PAGE_ATTRIBUTE                    SplitAttribute;
   RETURN_STATUS                     Status;
   BOOLEAN                           IsEntryModified;
+  BOOLEAN                           IsWpEnabled;
 
   if ((BaseAddress & (SIZE_4KB - 1)) != 0) {
     DEBUG ((DEBUG_ERROR, "BaseAddress(0x%lx) is not aligned!\n", BaseAddress));
@@ -665,14 +720,27 @@ ConvertMemoryPageAttributes (
   if (IsModified != NULL) {
     *IsModified = FALSE;
   }
+  if (AllocatePagesFunc == NULL) {
+    AllocatePagesFunc = AllocatePageTableMemory;
+  }
+
+  //
+  // Make sure that the page table is changeable.
+  //
+  IsWpEnabled = IsReadOnlyPageWriteProtected ();
+  if (IsWpEnabled) {
+    DisableReadOnlyPageWriteProtect ();
+  }
 
   //
   // Below logic is to check 2M/4K page to make sure we donot waist memory.
   //
+  Status = EFI_SUCCESS;
   while (Length != 0) {
     PageEntry = GetPageTableEntry (&CurrentPagingContext, BaseAddress, &PageAttribute);
     if (PageEntry == NULL) {
-      return RETURN_UNSUPPORTED;
+      Status = RETURN_UNSUPPORTED;
+      goto Done;
     }
     PageEntryLength = PageAttributeToLength (PageAttribute);
     SplitAttribute = NeedSplitPage (BaseAddress, Length, PageEntry, PageAttribute);
@@ -690,11 +758,13 @@ ConvertMemoryPageAttributes (
       Length -= PageEntryLength;
     } else {
       if (AllocatePagesFunc == NULL) {
-        return RETURN_UNSUPPORTED;
+        Status = RETURN_UNSUPPORTED;
+        goto Done;
       }
       Status = SplitPage (PageEntry, PageAttribute, SplitAttribute, AllocatePagesFunc);
       if (RETURN_ERROR (Status)) {
-        return RETURN_UNSUPPORTED;
+        Status = RETURN_UNSUPPORTED;
+        goto Done;
       }
       if (IsSplitted != NULL) {
         *IsSplitted = TRUE;
@@ -709,7 +779,14 @@ ConvertMemoryPageAttributes (
     }
   }
 
-  return RETURN_SUCCESS;
+Done:
+  //
+  // Restore page table write protection, if any.
+  //
+  if (IsWpEnabled) {
+    EnableReadOnlyPageWriteProtect ();
+  }
+  return Status;
 }
 
 /**
@@ -922,6 +999,230 @@ RefreshGcdMemoryAttributesFromPaging (
   FreePool (MemorySpaceMap);
 }
 
+/**
+  Try to find the page table pool reserved before.
+
+  Since the page table pool is always allocated at the boundary specified by
+  PcdPageTablePoolAlignment, we can definitely find the header address of pool
+  containing the page table given by CR3, by just checking the aligned address
+  lower than value of it.
+
+  @param[in] PagingContext  The paging context.
+
+  @retval Address of page table pool reserved before.
+  @retval NULL    The page table pool was not found.
+**/
+PAGE_TABLE_POOL_HEADER *
+FindPageTablePool (
+  IN  PAGE_TABLE_LIB_PAGING_CONTEXT   *PagingContext
+  )
+{
+  PAGE_TABLE_POOL_HEADER    *Pool;
+  VOID                      *BaseAddress;
+  UINTN                     Index;
+
+  BaseAddress = (VOID *)(UINTN)PagingContext->ContextData.X64.PageTableBase;
+  for (Index = 0; Index < EFI_PAGE_SIZE / sizeof (UINT64); ++Index) {
+    //
+    // Because the pool header occupies one page, let's always check the address
+    // one page before.
+    //
+    Pool = (VOID *)(UINTN)(((UINTN)BaseAddress - EFI_PAGE_SIZE) &
+                           PAGE_TABLE_POOL_ALIGN_MASK);
+
+    //
+    // Check the signature.
+    //
+    if (!CompareMem (&Pool->Signature, &gPageTablePoolGuid, sizeof (EFI_GUID))) {
+      return Pool;
+    }
+
+    //
+    // Check the address at previous alginment boundary.
+    //
+    BaseAddress = Pool;
+  }
+
+  return NULL;
+}
+
+/**
+  Initialize a buffer pool for page table use only.
+
+  To reduce the potential split operation on page table, the pages reserved for
+  page table should be allocated in the times of 512 (= SIZE_2MB) and at the
+  boundary of SIZE_2MB. So the page pool is always initialized with number of
+  pages greater than or equal to the given PoolPages.
+
+  Once the pages in the pool are used up, this method should be called again to
+  reserve at least another 512 pages. Usually this won't happen often in
+  practice.
+
+  But for the first time calling of this method, it will search page table pool
+  reserved before (DxeIpl) and try to re-use it if there're still free pages
+  in it.
+
+  @param[in] PagingContext  The paging context.
+  @param[in] PoolPages      The least page number of the pool to be created.
+
+  @retval TRUE    The pool is initialized successfully.
+  @retval FALSE   The memory is out of resource.
+**/
+BOOLEAN
+InitializePageTablePool (
+  IN  PAGE_TABLE_LIB_PAGING_CONTEXT   *PagingContext,
+  IN  UINTN                           PoolPages
+  )
+{
+  VOID                      *Buffer;
+  BOOLEAN                   IsModified;
+  PAGE_TABLE_POOL_HEADER    *HeadPool;
+  PAGE_TABLE_POOL_HEADER    *Pool;
+  UINTN                     PoolUnitPages;
+
+  //
+  // There must be page table pool already reserved in IPL or PEI. Let's reuse
+  // them if there're still pages available.
+  //
+  if (mPageTablePool == NULL) {
+    HeadPool = FindPageTablePool (PagingContext);
+
+    if (HeadPool != NULL) {
+      Pool = HeadPool;
+      do {
+        ASSERT (
+          !CompareMem (&Pool->Signature, &gPageTablePoolGuid, sizeof (EFI_GUID))
+          );
+
+        if (mPageTablePool == NULL ||
+            mPageTablePool->FreePages < Pool->FreePages) {
+          mPageTablePool = Pool;
+        }
+
+        Pool = (VOID *)(UINTN)Pool->NextPool;
+      } while (Pool != HeadPool);
+
+      //
+      // Enough pages available?
+      //
+      if (PoolPages <= mPageTablePool->FreePages) {
+        return TRUE;
+      }
+    }
+  }
+
+  //
+  // Reserve at least PcdPageTablePoolUnitSize.
+  //
+  PoolUnitPages = EFI_SIZE_TO_PAGES (PcdGet32 (PcdPageTablePoolUnitSize));
+  if (PoolPages <= PoolUnitPages) {
+    PoolPages = PoolUnitPages;
+  } else {
+    PoolPages = (PoolPages + PoolUnitPages) % PoolUnitPages;
+  }
+
+  //
+  // Set guard flag to avoid recursive calling of SetMemoryAttributes.
+  // Protection will be applied in this methond instead before return.
+  //
+  mIsAllocatingPageTable = TRUE;
+  Buffer = AllocateAlignedPages (
+             PoolPages,
+             FixedPcdGet32 (PcdPageTablePoolAlignment)
+             );
+  mIsAllocatingPageTable = FALSE;
+
+  if (Buffer == NULL) {
+    DEBUG ((DEBUG_ERROR, "ERROR: Out of pages aligned at 0x%x\n",
+            FixedPcdGet32 (PcdPageTablePoolAlignment)));
+    return FALSE;
+  }
+
+  if (mPageTablePool == NULL) {
+    mPageTablePool = Buffer;
+    mPageTablePool->NextPool = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer;
+  }
+
+  //
+  // Link all pools into a list.
+  //
+  ((PAGE_TABLE_POOL_HEADER *)Buffer)->NextPool = mPageTablePool->NextPool;
+  mPageTablePool->NextPool = (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer;
+
+  //
+  // Reserve one page for pool header.
+  //
+  mPageTablePool = Buffer;
+  CopyMem (&mPageTablePool->Signature, &gPageTablePoolGuid, sizeof (EFI_GUID));
+  mPageTablePool->FreePages  = PoolPages - 1;
+  mPageTablePool->Offset = EFI_PAGES_TO_SIZE (1);
+
+  //
+  // Mark the whole pool pages as read-only.
+  //
+  ConvertMemoryPageAttributes (
+    NULL,
+    (PHYSICAL_ADDRESS)(UINTN)Buffer,
+    EFI_PAGES_TO_SIZE (PoolPages),
+    EFI_MEMORY_RO,
+    PageActionSet,
+    AllocatePageTableMemory,
+    NULL,
+    &IsModified
+    );
+  ASSERT (IsModified == TRUE);
+
+  return TRUE;
+}
+
+/**
+  This API provides a way to allocate memory for page table.
+
+  This API can be called more than once to allocate memory for page tables.
+
+  Allocates the number of 4KB pages and returns a pointer to the allocated
+  buffer. The buffer returned is aligned on a 4KB boundary.
+
+  If Pages is 0, then NULL is returned.
+  If there is not enough memory remaining to satisfy the request, then NULL is
+  returned.
+
+  @param  Pages                 The number of 4 KB pages to allocate.
+
+  @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocatePageTableMemory (
+  IN UINTN           Pages
+  )
+{
+  PAGE_TABLE_LIB_PAGING_CONTEXT   PagingContext;
+  VOID                            *Buffer;
+
+  if (Pages == 0) {
+    return NULL;
+  }
+
+  //
+  // Renew the pool if necessary.
+  //
+  if (Pages > mPageTablePool->FreePages) {
+    GetCurrentPagingContext (&PagingContext);
+    if (!InitializePageTablePool (&PagingContext, Pages)) {
+      return NULL;
+    }
+  }
+
+  Buffer = (UINT8 *)mPageTablePool + mPageTablePool->Offset;
+
+  mPageTablePool->Offset     += EFI_PAGES_TO_SIZE (Pages);
+  mPageTablePool->FreePages  -= Pages;
+
+  return Buffer;
+}
+
 /**
   Initialize the Page Table lib.
 **/
@@ -933,6 +1234,18 @@ InitializePageTableLib (
   PAGE_TABLE_LIB_PAGING_CONTEXT     CurrentPagingContext;
 
   GetCurrentPagingContext (&CurrentPagingContext);
+
+  //
+  // Reserve memory of page tables for future uses, if paging is enabled.
+  //
+  if (CurrentPagingContext.ContextData.X64.PageTableBase != 0 &&
+      (CurrentPagingContext.ContextData.Ia32.Attributes &
+       PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE) != 0) {
+    DisableReadOnlyPageWriteProtect();
+    InitializePageTablePool (&CurrentPagingContext, 0);
+    EnableReadOnlyPageWriteProtect ();
+  }
+
   DEBUG ((DEBUG_INFO, "CurrentPagingContext:\n", CurrentPagingContext.MachineType));
   DEBUG ((DEBUG_INFO, "  MachineType   - 0x%x\n", CurrentPagingContext.MachineType));
   DEBUG ((DEBUG_INFO, "  PageTableBase - 0x%x\n", CurrentPagingContext.ContextData.X64.PageTableBase));
diff --git a/UefiCpuPkg/CpuDxe/CpuPageTable.h b/UefiCpuPkg/CpuDxe/CpuPageTable.h
index eaff595b4c..0faa11830d 100644
--- a/UefiCpuPkg/CpuDxe/CpuPageTable.h
+++ b/UefiCpuPkg/CpuDxe/CpuPageTable.h
@@ -16,6 +16,7 @@
 #define _PAGE_TABLE_LIB_H_
 
 #include <IndustryStandard/PeImage.h>
+#include <Guid/PageTablePool.h>
 
 #define PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PSE              BIT0
 #define PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE              BIT1
@@ -110,4 +111,25 @@ InitializePageTableLib (
   VOID
   );
 
+/**
+  This API provides a way to allocate memory for page table.
+
+  This API can be called more once to allocate memory for page tables.
+
+  Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the
+  allocated buffer.  The buffer returned is aligned on a 4KB boundary.  If Pages is 0, then NULL
+  is returned.  If there is not enough memory remaining to satisfy the request, then NULL is
+  returned.
+
+  @param  Pages                 The number of 4 KB pages to allocate.
+
+  @return A pointer to the allocated buffer or NULL if allocation fails.
+
+**/
+VOID *
+EFIAPI
+AllocatePageTableMemory (
+  IN UINTN           Pages
+  );
+
 #endif
-- 
2.14.1.windows.1

_______________________________________________
edk2-devel mailing list
edk2-devel@lists.01.org
https://lists.01.org/mailman/listinfo/edk2-devel