From nobody Tue Dec 24 17:18:33 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1512376564635416.62396312751014; Mon, 4 Dec 2017 00:36:04 -0800 (PST) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id CAA48220EE08B; Mon, 4 Dec 2017 00:31:33 -0800 (PST) Received: from mga09.intel.com (mga09.intel.com [134.134.136.24]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 60CE1220EE07C for ; Mon, 4 Dec 2017 00:31:32 -0800 (PST) Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by orsmga102.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 04 Dec 2017 00:36:01 -0800 Received: from jwang36-mobl2.ccr.corp.intel.com ([10.239.192.42]) by fmsmga001.fm.intel.com with ESMTP; 04 Dec 2017 00:36:00 -0800 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.24; helo=mga09.intel.com; envelope-from=jian.j.wang@intel.com; receiver=edk2-devel@lists.01.org X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.45,358,1508828400"; d="scan'208";a="10201539" From: Jian J Wang To: edk2-devel@lists.01.org Date: Mon, 4 Dec 2017 16:35:53 +0800 Message-Id: <20171204083556.19416-2-jian.j.wang@intel.com> X-Mailer: git-send-email 2.14.1.windows.1 In-Reply-To: <20171204083556.19416-1-jian.j.wang@intel.com> References: <20171204083556.19416-1-jian.j.wang@intel.com> Subject: [edk2] [PATCH v2 1/4] MdeModulePkg/MdeModulePkg.dec: Add new PCDs and Guid X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Ruiyu Ni , Jiewen Yao , Eric Dong , Star Zeng MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" > v2: > newly added PcdPageTablePoolUnitSize is used to specify the smallest size of memory pool reserved for page table. PcdPageTablePoolAlignment is used to specify the alignment of the memory po= ol reserved for page table. gPageTablePoolGuid is used to identify the memory pool used for page table. These definitions are used to simplify the page table creation and protecti= on. They are also used to make sure that DxeIpl and CpuDxe driver are using the same way to allocate page table memory. Cc: Jiewen Yao Cc: Star Zeng Cc: Eric Dong Cc: Ruiyu Ni Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang --- MdeModulePkg/MdeModulePkg.dec | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 856d67aceb..075d51f807 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -392,6 +392,9 @@ ## Include/Guid/PlatformHasAcpi.h gEdkiiPlatformHasAcpiGuid =3D { 0xf0966b41, 0xc23f, 0x41b9, { 0x96, 0x04= , 0x0f, 0xf7, 0xe1, 0x11, 0x96, 0x5a } } =20 + ## Include/Guid/PageTablePool.h + gPageTablePoolGuid =3D { 0x18347A49, 0xF48B, 0x4012, {0x67, 0x1D, 0x70, = 0x23, 0x76, 0x5C, 0x92, 0xAD} } + [Ppis] ## Include/Ppi/AtaController.h gPeiAtaControllerPpiGuid =3D { 0xa45e60d1, 0xc719, 0x44aa, { 0xb0,= 0x7a, 0xaa, 0x77, 0x7f, 0x85, 0x90, 0x6d }} @@ -949,6 +952,31 @@ # @Prompt The Heap Guard feature mask gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask|0x0|UINT8|0x3000= 1054 =20 + ## Specifiy the size in byte of memory unit allocated for page table. + # + # This PCD is used for reserving certain amount of pages for page table + # initialization. If pages reserved at last time are used up, another a= mount + # of memory specified by this PCD will be allocated again, until all pa= ge + # tables are initialized. + # + # It's designed to reduce the recursive "split" action from larger + # granularity to smaller one, and simplify the page table protection. I= ts + # value must be the same as one of page sizes supported by the processo= r and + # should be larger than the size of one page table. + # + # @Prompt Size of memory unit allocated for page table. + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolUnitSize|0x200000|UINT32|= 0x30001060 + + ## Specifiy the alignment of page table pool. + # + # This PCD is used for reserving page table pool at desired alignment b= oundary. + # It's designed to reduce the recursive "split" action from larger gran= ularity + # to smaller one, and simplify the page table protection. Its value sho= uld + # not be less than PcdPageTablePoolUnitSize for IA32 processor. + # + # @Prompt Alignment of page pool memory unit. + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolAlignment|0x200000|UINT32= |0x30001061 + [PcdsFixedAtBuild, PcdsPatchableInModule] ## Dynamic type PCD can be registered callback function for Pcd setting = action. # PcdMaxPeiPcdCallBackNumberPerPcdEntry indicates the maximum number of= callback function --=20 2.14.1.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Tue Dec 24 17:18:33 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 151237656743762.54621162333524; Mon, 4 Dec 2017 00:36:07 -0800 (PST) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 1041A220EE090; Mon, 4 Dec 2017 00:31:35 -0800 (PST) Received: from mga09.intel.com (mga09.intel.com [134.134.136.24]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 92322220EE08A for ; Mon, 4 Dec 2017 00:31:33 -0800 (PST) Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by orsmga102.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 04 Dec 2017 00:36:03 -0800 Received: from jwang36-mobl2.ccr.corp.intel.com ([10.239.192.42]) by fmsmga001.fm.intel.com with ESMTP; 04 Dec 2017 00:36:02 -0800 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.24; helo=mga09.intel.com; envelope-from=jian.j.wang@intel.com; receiver=edk2-devel@lists.01.org X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.45,358,1508828400"; d="scan'208";a="10201629" From: Jian J Wang To: edk2-devel@lists.01.org Date: Mon, 4 Dec 2017 16:35:54 +0800 Message-Id: <20171204083556.19416-3-jian.j.wang@intel.com> X-Mailer: git-send-email 2.14.1.windows.1 In-Reply-To: <20171204083556.19416-1-jian.j.wang@intel.com> References: <20171204083556.19416-1-jian.j.wang@intel.com> Subject: [edk2] [PATCH v2 2/4] MdeModulePkg/PageTablePool.h: Page table pool GUID definition file X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Ruiyu Ni , Jiewen Yao , Eric Dong , Star Zeng MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" > v2: > newly added This file is added to definition of gPageTablePoolGuid. In addition, following structure type is defined to describe the page table pool information which can be used by different drivers to allocate memory for new page tables. It's supposed to be at the start address of each separated pool. The NextPool field is used to link all the pools together which helps to track and manage all the page tables easily. typedef struct { EFI_GUID Signature; EFI_PHYSICAL_ADDRESS NextPool; UINT64 Offset; UINT64 FreePages; } PAGE_TABLE_POOL_HEADER; Cc: Jiewen Yao Cc: Star Zeng Cc: Eric Dong Cc: Ruiyu Ni Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang --- MdeModulePkg/Include/Guid/PageTablePool.h | 53 +++++++++++++++++++++++++++= ++++ 1 file changed, 53 insertions(+) create mode 100644 MdeModulePkg/Include/Guid/PageTablePool.h diff --git a/MdeModulePkg/Include/Guid/PageTablePool.h b/MdeModulePkg/Inclu= de/Guid/PageTablePool.h new file mode 100644 index 0000000000..103739a9db --- /dev/null +++ b/MdeModulePkg/Include/Guid/PageTablePool.h @@ -0,0 +1,53 @@ +/** @file + GUID used to identify the memory pool used for page table. + +Copyright (c) 2017, Intel Corporation. All rights reserved.
+(C) Copyright 2016 Hewlett Packard Enterprise Development LP
+This program and the accompanying materials are licensed and made availabl= e under +the terms and conditions of the BSD License that accompanies this distribu= tion. +The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php. + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLI= ED. + +**/ + +#ifndef __PAGE_TABLE_POOL_H__ +#define __PAGE_TABLE_POOL_H__ + +/// +/// GUID value used to identify page table pool. +/// +/// [18347A49-F48B-4012-671D-7023765C92AD] +/// +#define PAGE_TABLE_POOL_GUID \ + { \ + 0x18347A49, 0xF48B, 0x4012, {0x67, 0x1D, 0x70, 0x23, 0x76, 0x5C, 0x92,= 0xAD} \ + } + +/// +/// A structure at the header of first page in each page table pool. +/// +typedef struct { + /// + /// Signature used to identify the memory pool used for page table. + /// + EFI_GUID Signature; + /// + /// The address pointing to the header of next page table pool. + /// + EFI_PHYSICAL_ADDRESS NextPool; + /// + /// The offset (in bytes) of free pages in current pool. + /// + UINT64 Offset; + /// + /// The number of free pages. + /// + UINT64 FreePages; +} PAGE_TABLE_POOL_HEADER; + +extern EFI_GUID gPageTablePoolGuid; + +#endif //__PAGE_TABLE_POOL_H__ --=20 2.14.1.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Tue Dec 24 17:18:33 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1512376570027550.8432407248963; Mon, 4 Dec 2017 00:36:10 -0800 (PST) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 477A8220EE094; Mon, 4 Dec 2017 00:31:36 -0800 (PST) Received: from mga09.intel.com (mga09.intel.com [134.134.136.24]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id E4CFC220EE08E for ; Mon, 4 Dec 2017 00:31:34 -0800 (PST) Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by orsmga102.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 04 Dec 2017 00:36:04 -0800 Received: from jwang36-mobl2.ccr.corp.intel.com ([10.239.192.42]) by fmsmga001.fm.intel.com with ESMTP; 04 Dec 2017 00:36:03 -0800 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.24; helo=mga09.intel.com; envelope-from=jian.j.wang@intel.com; receiver=edk2-devel@lists.01.org X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.45,358,1508828400"; d="scan'208";a="10201729" From: Jian J Wang To: edk2-devel@lists.01.org Date: Mon, 4 Dec 2017 16:35:55 +0800 Message-Id: <20171204083556.19416-4-jian.j.wang@intel.com> X-Mailer: git-send-email 2.14.1.windows.1 In-Reply-To: <20171204083556.19416-1-jian.j.wang@intel.com> References: <20171204083556.19416-1-jian.j.wang@intel.com> Subject: [edk2] [PATCH v2 3/4] MdeModulePkg/DxeIpl: Mark page table as read-only X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Ruiyu Ni , Jiewen Yao , Eric Dong , Star Zeng MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" > v2: > Introduce page table pool to ease the page table memory allocation and > protection, which replaces the direct calling of AllocatePages(). This patch will set the memory pages used for page table as read-only memory after the paging is setup. CR0.WP must set to let it take into effect. A simple page table memory management mechanism, page table pool concept, is introduced to simplify the page table memory allocation and protection. It will also help to reduce the potential recursive "split" action during updating memory paging attributes. The basic idea is to allocate a bunch of continuous pages of memory in advance as one or more page table pools, and all future page tables consumption will happen in those pool instead of system memory. If the page pool is reserved at the boundary of 2MB page and with same size of 2MB page, there's no page granularity "split" operation will be needed, because the memory of new page tables (if needed) will be usually in the same page as target page table you're working on. And since we have centralized page tables (a few 2MB pages), it's easier to protect them by changing their attributes to be read-only once and for all. There's no need to apply the protection for new page tables any more as long as the pool has free pages available. Once current page table pool has been used up, one can allocate another 2MB memory pool and just set this new 2MB memory block to be read-only instead = of setting the new page tables one page by one page. Two new PCDs PcdPageTablePoolUnitSize and PcdPageTablePoolAlignment are used to specify the size and alignment for page table pool. For IA32 processor 0x200000 (2MB) is the only choice for both of them to meet the requirement = of page table pool. Cc: Jiewen Yao Cc: Star Zeng Cc: Eric Dong Cc: Ruiyu Ni Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang --- MdeModulePkg/Core/DxeIplPeim/DxeIpl.h | 34 +++ MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf | 3 + MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c | 8 +- MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c | 315 +++++++++++++++++++= +++- MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h | 15 ++ 5 files changed, 371 insertions(+), 4 deletions(-) diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h b/MdeModulePkg/Core/DxeI= plPeim/DxeIpl.h index f3aabdb7e0..9dc80b1508 100644 --- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h +++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.h @@ -265,4 +265,38 @@ IsNullDetectionEnabled ( VOID ); =20 +/** + Prevent the memory pages used for page table from been overwritten. + + @param[in] PageTableBase Base address of page table (CR3). + +**/ +VOID +EnablePageTableProtection ( + IN UINTN PageTableBase, + IN BOOLEAN Level4Paging + ); + +/** + 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 NUL= L 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 * +AllocatePageTableMemory ( + IN UINTN Pages + ); + #endif diff --git a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf b/MdeModulePkg/Core/Dx= eIplPeim/DxeIpl.inf index a1b8748432..e9ab74a800 100644 --- a/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf +++ b/MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf @@ -102,6 +102,7 @@ ## SOMETIMES_CONSUMES ## Variable:L"MemoryTypeInformation" ## SOMETIMES_PRODUCES ## HOB gEfiMemoryTypeInformationGuid + gPageTablePoolGuid ## CONSUMES =20 [FeaturePcd.IA32] gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode ## CONSUMES @@ -117,6 +118,8 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask ##= CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask ##= CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask ##= CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolUnitSize ##= CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolAlignment ##= CONSUMES =20 [Pcd.IA32,Pcd.X64,Pcd.ARM,Pcd.AARCH64] gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack ## SOMETIM= ES_CONSUMES diff --git a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c b/MdeModulePkg= /Core/DxeIplPeim/Ia32/DxeLoadFunc.c index 5649265367..13fff28e93 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c @@ -99,7 +99,7 @@ Create4GPageTablesIa32Pae ( NumberOfPdpEntriesNeeded =3D (UINT32) LShiftU64 (1, (PhysicalAddressBits= - 30)); =20 TotalPagesNum =3D NumberOfPdpEntriesNeeded + 1; - PageAddress =3D (UINTN) AllocatePages (TotalPagesNum); + PageAddress =3D (UINTN) AllocatePageTableMemory (TotalPagesNum); ASSERT (PageAddress !=3D 0); =20 PageMap =3D (VOID *) PageAddress; @@ -149,6 +149,12 @@ Create4GPageTablesIa32Pae ( ); } =20 + // + // Protect the page table by marking the memory used for page table to be + // read-only. + // + EnablePageTableProtection ((UINTN)PageMap, FALSE); + return (UINTN) PageMap; } =20 diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c b/MdeModulePk= g/Core/DxeIplPeim/X64/VirtualMemory.c index 29b6205e88..e22a105eb3 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c +++ b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c @@ -31,6 +31,14 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHE= R EXPRESS OR IMPLIED. #include "DxeIpl.h" #include "VirtualMemory.h" =20 +#define PAGE_TABLE_POOL_ALIGN_MASK \ + (~(EFI_PHYSICAL_ADDRESS)(FixedPcdGet32 (PcdPageTablePoolAlignment) - 1= )) + +// +// Global variable to keep track current available memory used as page tab= le. +// +PAGE_TABLE_POOL_HEADER *mPageTablePool =3D NULL; + /** Clear legacy memory located at the first 4K-page, if available. =20 @@ -117,6 +125,127 @@ EnableExecuteDisableBit ( AsmWriteMsr64 (0xC0000080, MsrRegisters); } =20 +/** + Initialize a buffer pool for page table use only. + + To reduce the potential split operation on page table, the pages reserve= d for + page table should be allocated in the times of 512 (=3D 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 aga= in to + reserve at least another 512 pages. But usually this won't happen in pra= ctice. + + @param 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 UINTN PoolPages + ) +{ + VOID *Buffer; + UINTN PoolUnitPages; + + // + // Make sure that page table pool is effective and efficient. + // + ASSERT (PcdGet32 (PcdPageTablePoolUnitSize) > EFI_PAGE_SIZE); + ASSERT (PcdGet32 (PcdPageTablePoolAlignment) =3D=3D PcdGet32 (PcdPageTab= lePoolUnitSize)); + + // + // Always reserve at least PcdPageTablePoolUnitSize. + // + PoolUnitPages =3D EFI_SIZE_TO_PAGES (PcdGet32 (PcdPageTablePoolUnitSize)= ); + if (PoolPages <=3D PoolUnitPages) { + PoolPages =3D PoolUnitPages; + } else { + PoolPages =3D ((PoolPages + PoolUnitPages) % PoolUnitPages) * PoolUnit= Pages; + } + + Buffer =3D AllocateAlignedPages ( + PoolPages, + FixedPcdGet32 (PcdPageTablePoolAlignment) + ); + if (Buffer =3D=3D NULL) { + DEBUG ((DEBUG_ERROR, "ERROR: Out of pages aligned at 0x%x\n", + FixedPcdGet32 (PcdPageTablePoolAlignment))); + return FALSE; + } + + DEBUG ((DEBUG_INFO, "Allocated %d pages at %x!\r\n", PoolPages, Buffer)); + if (mPageTablePool =3D=3D NULL) { + mPageTablePool =3D Buffer; + mPageTablePool->NextPool =3D (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; + } + + // + // Link all pools into a list. + // + ((PAGE_TABLE_POOL_HEADER *)Buffer)->NextPool =3D mPageTablePool->NextPoo= l; + mPageTablePool->NextPool =3D (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; + + // + // Reserve one page for pool header. + // + mPageTablePool =3D Buffer; + CopyMem (&mPageTablePool->Signature, &gPageTablePoolGuid, sizeof (EFI_GU= ID)); + mPageTablePool->FreePages =3D PoolPages - 1; + mPageTablePool->Offset =3D EFI_PAGES_TO_SIZE (1); + + 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 NUL= L 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 * +AllocatePageTableMemory ( + IN UINTN Pages + ) +{ + VOID *Buffer; + + if (Pages =3D=3D 0) { + return NULL; + } + + // + // Renew the pool if necessary. + // + if (mPageTablePool =3D=3D NULL || + Pages > mPageTablePool->FreePages) { + if (!InitializePageTablePool (Pages)) { + return NULL; + } + } + + Buffer =3D (UINT8 *)mPageTablePool + mPageTablePool->Offset; + + mPageTablePool->Offset +=3D EFI_PAGES_TO_SIZE (Pages); + mPageTablePool->FreePages -=3D Pages; + + DEBUG ((DEBUG_INFO, "Allocate total %d pages for page table!\r\n", RShif= tU64 (mPageTablePool->Offset, 12))); + + return Buffer; +} + /** Split 2M page to 4K. =20 @@ -144,7 +273,7 @@ Split2MPageTo4K ( // AddressEncMask =3D PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGI= NG_1G_ADDRESS_MASK_64; =20 - PageTableEntry =3D AllocatePages (1); + PageTableEntry =3D AllocatePageTableMemory (1); ASSERT (PageTableEntry !=3D NULL); =20 // @@ -204,7 +333,7 @@ Split1GPageTo2M ( // AddressEncMask =3D PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & PAGI= NG_1G_ADDRESS_MASK_64; =20 - PageDirectoryEntry =3D AllocatePages (1); + PageDirectoryEntry =3D AllocatePageTableMemory (1); ASSERT (PageDirectoryEntry !=3D NULL); =20 // @@ -234,6 +363,180 @@ Split1GPageTo2M ( } } =20 +/** + Set one page of page table pool memory to be read-only. + + @param[in] PageTableBase Base address of page table (CR3). + @param[in] Address Start address of a page to be set as read-on= ly. + @param[in] Level4Paging Level 4 paging flag. + +**/ +VOID +SetPageTablePoolReadOnly ( + IN UINTN PageTableBase, + IN EFI_PHYSICAL_ADDRESS Address, + IN BOOLEAN Level4Paging + ) +{ + UINTN Index; + UINTN EntryIndex; + UINT64 AddressEncMask; + EFI_PHYSICAL_ADDRESS PhysicalAddress; + UINT64 *PageTable; + UINT64 *NewPageTable; + UINT64 PageAttr; + UINT64 LevelSize[5]; + UINT64 LevelMask[5]; + UINTN LevelShift[5]; + UINTN Level; + UINT64 PoolUnitSize; + + ASSERT (PageTableBase !=3D 0); + + // + // Since the page table is always from page table pool, which is always + // located at the boundary of PcdPageTablePoolAlignment, we just need to + // set the whole pool unit to be read-only. + // + Address =3D Address & PAGE_TABLE_POOL_ALIGN_MASK; + + LevelShift[1] =3D PAGING_L1_ADDRESS_SHIFT; + LevelShift[2] =3D PAGING_L2_ADDRESS_SHIFT; + LevelShift[3] =3D PAGING_L3_ADDRESS_SHIFT; + LevelShift[4] =3D PAGING_L4_ADDRESS_SHIFT; + + LevelMask[1] =3D PAGING_4K_ADDRESS_MASK_64; + LevelMask[2] =3D PAGING_2M_ADDRESS_MASK_64; + LevelMask[3] =3D PAGING_1G_ADDRESS_MASK_64; + LevelMask[4] =3D PAGING_1G_ADDRESS_MASK_64; + + LevelSize[1] =3D SIZE_4KB; + LevelSize[2] =3D SIZE_2MB; + LevelSize[3] =3D SIZE_1GB; + LevelSize[4] =3D SIZE_512GB; + + AddressEncMask =3D PcdGet64 (PcdPteMemoryEncryptionAddressOrMask) & + PAGING_1G_ADDRESS_MASK_64; + PageTable =3D (UINT64 *)(UINTN)PageTableBase; + PoolUnitSize =3D PcdGet32 (PcdPageTablePoolUnitSize); + for (Level =3D (Level4Paging) ? 4 : 3; Level > 0; --Level) { + Index =3D ((UINTN)RShiftU64 (Address, LevelShift[Level])); + Index &=3D PAGING_PAE_INDEX_MASK; + + PageAttr =3D PageTable[Index]; + if ((PageAttr & IA32_PG_PS) =3D=3D 0) { + // + // Go to next level of table. + // + PageTable =3D (UINT64 *)(UINTN)(PageAttr & ~AddressEncMask & + PAGING_4K_ADDRESS_MASK_64); + continue; + } + + // + // Clear R/W bit if current page granularity is not bigger than pool u= nit + // size. + // + if (PoolUnitSize >=3D LevelSize[Level]) { + if ((PageAttr & IA32_PG_RW) !=3D 0) { + while (PoolUnitSize > 0) { + // + // PcdPageTablePoolUnitSize and PcdPageTablePoolAlignment must b= e set + // with values within one page (2MB by default). Then we don't n= eed + // to update attributes for pages crossing page directory . ASSE= RT + // below is for that purpose. + // + ASSERT (Index < EFI_PAGE_SIZE/sizeof (UINT64)); + + PageTable[Index] &=3D ~(UINT64)IA32_PG_RW; + PoolUnitSize -=3D LevelSize[Level]; + ++Index; + } + } + break; + } + + // + // The smaller granularity of page must be needed. + // + NewPageTable =3D AllocatePageTableMemory (1); + ASSERT (NewPageTable !=3D NULL); + + PhysicalAddress =3D PageAttr & LevelMask[Level]; + for (EntryIndex =3D 0; + EntryIndex < EFI_PAGE_SIZE/sizeof (UINT64); + ++EntryIndex) { + NewPageTable[EntryIndex] =3D PhysicalAddress | AddressEncMask | + IA32_PG_P | IA32_PG_RW; + if (Level > 1) { + NewPageTable[EntryIndex] |=3D IA32_PG_PS; + } + PhysicalAddress +=3D LevelSize[Level]; + } + + PageTable[Index] =3D (UINT64)(UINTN)NewPageTable | AddressEncMask | + IA32_PG_P | IA32_PG_RW; + PageTable =3D NewPageTable; + } +} + +/** + Prevent the memory pages used for page table from been overwritten. + + @param[in] PageTableBase Base address of page table (CR3). + +**/ +VOID +EnablePageTableProtection ( + IN UINTN PageTableBase, + IN BOOLEAN Level4Paging + ) +{ + PAGE_TABLE_POOL_HEADER *HeadPool; + PAGE_TABLE_POOL_HEADER *Pool; + UINT64 PoolSize; + EFI_PHYSICAL_ADDRESS Address; + + if (mPageTablePool =3D=3D NULL) { + return; + } + + // + // Disable write protection, because we need to mark page table to be wr= ite + // protected. + // + AsmWriteCr0 (AsmReadCr0() & ~CR0_WP); + + // + // SetPageTablePoolReadOnly might update mPageTablePool. It's safer to + // remember original one in advance. + // + HeadPool =3D mPageTablePool; + Pool =3D HeadPool; + do { + Address =3D (EFI_PHYSICAL_ADDRESS)(UINTN)Pool; + PoolSize =3D Pool->Offset + EFI_PAGES_TO_SIZE ((UINTN)Pool->FreePages); + + // + // The size of one pool must be multiple of PcdPageTablePoolUnitSize, = which + // is one of page size of the processor (2MB by default). Let's apply = the + // protection to them one by one. + // + while (PoolSize > 0) { + SetPageTablePoolReadOnly(PageTableBase, Address, Level4Paging); + Address +=3D PcdGet32 (PcdPageTablePoolUnitSize); + PoolSize -=3D PcdGet32 (PcdPageTablePoolUnitSize); + } + + Pool =3D (PAGE_TABLE_POOL_HEADER *)(UINTN)Pool->NextPool; + } while (Pool !=3D HeadPool); + + // + // Enable write protection, after page table updated. + // + AsmWriteCr0 (AsmReadCr0() | CR0_WP); +} + /** Allocates and fills in the Page Directory and Page Table Entries to establish a 1:1 Virtual to Physical mapping. @@ -329,7 +632,7 @@ CreateIdentityMappingPageTables ( } else { TotalPagesNum =3D NumberOfPml4EntriesNeeded + 1; } - BigPageAddress =3D (UINTN) AllocatePages (TotalPagesNum); + BigPageAddress =3D (UINTN) AllocatePageTableMemory (TotalPagesNum); ASSERT (BigPageAddress !=3D 0); =20 // @@ -430,6 +733,12 @@ CreateIdentityMappingPageTables ( ); } =20 + // + // Protect the page table by marking the memory used for page table to be + // read-only. + // + EnablePageTableProtection ((UINTN)PageMap, TRUE); + if (PcdGetBool (PcdSetNxForStack)) { EnableExecuteDisableBit (); } diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h b/MdeModulePk= g/Core/DxeIplPeim/X64/VirtualMemory.h index 7c9bb49e3e..73ec074c5d 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h +++ b/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.h @@ -22,6 +22,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER= EXPRESS OR IMPLIED. #ifndef _VIRTUAL_MEMORY_H_ #define _VIRTUAL_MEMORY_H_ =20 +#include =20 #define SYS_CODE64_SEL 0x38 =20 @@ -148,11 +149,25 @@ typedef union { =20 #pragma pack() =20 +#define CR0_WP BIT16 + #define IA32_PG_P BIT0 #define IA32_PG_RW BIT1 +#define IA32_PG_PS BIT7 + +#define PAGING_PAE_INDEX_MASK 0x1FF =20 +#define PAGING_4K_ADDRESS_MASK_64 0x000FFFFFFFFFF000ull +#define PAGING_2M_ADDRESS_MASK_64 0x000FFFFFFFE00000ull #define PAGING_1G_ADDRESS_MASK_64 0x000FFFFFC0000000ull =20 +#define PAGING_L1_ADDRESS_SHIFT 12 +#define PAGING_L2_ADDRESS_SHIFT 21 +#define PAGING_L3_ADDRESS_SHIFT 30 +#define PAGING_L4_ADDRESS_SHIFT 39 + +#define PAGING_PML4E_NUMBER 4 + /** Enable Execute Disable Bit. =20 --=20 2.14.1.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel From nobody Tue Dec 24 17:18:33 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; spf=none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) smtp.mailfrom=edk2-devel-bounces@lists.01.org Return-Path: Received: from ml01.01.org (ml01.01.org [198.145.21.10]) by mx.zohomail.com with SMTPS id 1512376572580467.7520397628467; Mon, 4 Dec 2017 00:36:12 -0800 (PST) Received: from [127.0.0.1] (localhost [IPv6:::1]) by ml01.01.org (Postfix) with ESMTP id 854E3220EE096; Mon, 4 Dec 2017 00:31:36 -0800 (PST) Received: from mga09.intel.com (mga09.intel.com [134.134.136.24]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ml01.01.org (Postfix) with ESMTPS id 1D401220EE092 for ; Mon, 4 Dec 2017 00:31:36 -0800 (PST) Received: from fmsmga001.fm.intel.com ([10.253.24.23]) by orsmga102.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384; 04 Dec 2017 00:36:05 -0800 Received: from jwang36-mobl2.ccr.corp.intel.com ([10.239.192.42]) by fmsmga001.fm.intel.com with ESMTP; 04 Dec 2017 00:36:04 -0800 X-Original-To: edk2-devel@lists.01.org Received-SPF: none (zoho.com: 198.145.21.10 is neither permitted nor denied by domain of lists.01.org) client-ip=198.145.21.10; envelope-from=edk2-devel-bounces@lists.01.org; helo=ml01.01.org; Received-SPF: Pass (sender SPF authorized) identity=mailfrom; client-ip=134.134.136.24; helo=mga09.intel.com; envelope-from=jian.j.wang@intel.com; receiver=edk2-devel@lists.01.org X-ExtLoop1: 1 X-IronPort-AV: E=Sophos;i="5.45,358,1508828400"; d="scan'208";a="10201770" From: Jian J Wang To: edk2-devel@lists.01.org Date: Mon, 4 Dec 2017 16:35:56 +0800 Message-Id: <20171204083556.19416-5-jian.j.wang@intel.com> X-Mailer: git-send-email 2.14.1.windows.1 In-Reply-To: <20171204083556.19416-1-jian.j.wang@intel.com> References: <20171204083556.19416-1-jian.j.wang@intel.com> Subject: [edk2] [PATCH v2 4/4] UefiCpuPkg/CpuDxe: Enable protection for newly added page table X-BeenThere: edk2-devel@lists.01.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: EDK II Development List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Ruiyu Ni , Laszlo Ersek , Jiewen Yao , Eric Dong MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Errors-To: edk2-devel-bounces@lists.01.org Sender: "edk2-devel" X-ZohoMail: RSF_4 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" > 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 DxeI= pl, if there're still free pages in it. Otherwise, the driver will reserve anot= her block of memory (specified by PcdPageTablePoolUnitSize and PcdPageTablePoolAlignment) as new page table pool. The protection will be o= nly 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 Cc: Eric Dong Cc: Laszlo Ersek Cc: Ruiyu Ni Contributed-under: TianoCore Contribution Agreement 1.1 Signed-off-by: Jian J Wang --- 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 =3D FALSE; EFI_HANDLE mCpuHandle =3D NULL; BOOLEAN mIsFlushingGCD; +BOOLEAN mIsAllocatingPageTable =3D FALSE; UINT64 mValidMtrrAddressMask; UINT64 mValidMtrrBitsMask; UINT64 mTimerPeriod =3D 0; @@ -407,6 +408,20 @@ CpuSetMemoryAttributes ( return EFI_SUCCESS; } =20 + // + // 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 it= self, + // there's no need to apply protection policy requested from memory serv= ice. + // So it's safe to just return EFI_SUCCESS if this time of calling is ca= used + // by page table memory allocation. + // + if (mIsAllocatingPageTable) { + DEBUG((DEBUG_VERBOSE, " Allocating page table memory\n")); + return EFI_SUCCESS; + } =20 CacheAttributes =3D Attributes & CACHE_ATTRIBUTE_MASK; MemoryAttributes =3D Attributes & MEMORY_ATTRIBUTE_MASK; @@ -487,7 +502,7 @@ CpuSetMemoryAttributes ( // // Set memory attribute by page table // - return AssignMemoryPageAttributes (NULL, BaseAddress, Length, MemoryAttr= ibutes, AllocatePages); + return AssignMemoryPageAttributes (NULL, BaseAddress, Length, MemoryAttr= ibutes, NULL); } =20 /** 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 ); =20 +extern BOOLEAN mIsAllocatingPageTable; + #endif =20 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 ## E= vent gEfiVectorHandoffTableGuid ## SOMETIMES_CONSUMES ## S= ystemTable + gPageTablePoolGuid ## CONSUMES =20 [Ppis] gEfiSecPlatformInformation2PpiGuid ## UNDEFINED # HOB @@ -81,6 +82,8 @@ =20 [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask ##= CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolUnitSize ##= CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdPageTablePoolAlignment ##= CONSUMES =20 [Depex] TRUE diff --git a/UefiCpuPkg/CpuDxe/CpuPageTable.c b/UefiCpuPkg/CpuDxe/CpuPageTa= ble.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 =20 +#define PAGE_TABLE_POOL_ALIGN_MASK \ + (~(EFI_PHYSICAL_ADDRESS)(FixedPcdGet32 (PcdPageTablePoolAlignment) - 1= )) + typedef enum { PageNone, Page4K, @@ -87,6 +90,8 @@ PAGE_ATTRIBUTE_TABLE mPageAttributeTable[] =3D { {Page1G, SIZE_1GB, PAGING_1G_ADDRESS_MASK_64}, }; =20 +PAGE_TABLE_POOL_HEADER *mPageTablePool =3D NULL; + /** Enable write protection function for AP. =20 @@ -172,10 +177,6 @@ GetCurrentPagingContext ( } if ((AsmReadCr0 () & BIT31) !=3D 0) { PagingContext->ContextData.X64.PageTableBase =3D (AsmReadCr3 () & PAGI= NG_4K_ADDRESS_MASK_64); - if ((AsmReadCr0 () & BIT16) =3D=3D 0) { - AsmWriteCr0 (AsmReadCr0 () | BIT16); - SyncMemoryPageAttributesAp (SyncCpuEnableWriteProtection); - } } else { PagingContext->ContextData.X64.PageTableBase =3D 0; } @@ -561,6 +562,59 @@ SplitPage ( } } =20 +/** + Check the WP status in CR0 register. This bit is used to lock or unlock w= rite + 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) !=3D 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 specifi= ed by BaseAddress and Length from their current attributes to the attributes specified by Attr= ibutes. @@ -609,6 +663,7 @@ ConvertMemoryPageAttributes ( PAGE_ATTRIBUTE SplitAttribute; RETURN_STATUS Status; BOOLEAN IsEntryModified; + BOOLEAN IsWpEnabled; =20 if ((BaseAddress & (SIZE_4KB - 1)) !=3D 0) { DEBUG ((DEBUG_ERROR, "BaseAddress(0x%lx) is not aligned!\n", BaseAddre= ss)); @@ -665,14 +720,27 @@ ConvertMemoryPageAttributes ( if (IsModified !=3D NULL) { *IsModified =3D FALSE; } + if (AllocatePagesFunc =3D=3D NULL) { + AllocatePagesFunc =3D AllocatePageTableMemory; + } + + // + // Make sure that the page table is changeable. + // + IsWpEnabled =3D IsReadOnlyPageWriteProtected (); + if (IsWpEnabled) { + DisableReadOnlyPageWriteProtect (); + } =20 // // Below logic is to check 2M/4K page to make sure we donot waist memory. // + Status =3D EFI_SUCCESS; while (Length !=3D 0) { PageEntry =3D GetPageTableEntry (&CurrentPagingContext, BaseAddress, &= PageAttribute); if (PageEntry =3D=3D NULL) { - return RETURN_UNSUPPORTED; + Status =3D RETURN_UNSUPPORTED; + goto Done; } PageEntryLength =3D PageAttributeToLength (PageAttribute); SplitAttribute =3D NeedSplitPage (BaseAddress, Length, PageEntry, Page= Attribute); @@ -690,11 +758,13 @@ ConvertMemoryPageAttributes ( Length -=3D PageEntryLength; } else { if (AllocatePagesFunc =3D=3D NULL) { - return RETURN_UNSUPPORTED; + Status =3D RETURN_UNSUPPORTED; + goto Done; } Status =3D SplitPage (PageEntry, PageAttribute, SplitAttribute, Allo= catePagesFunc); if (RETURN_ERROR (Status)) { - return RETURN_UNSUPPORTED; + Status =3D RETURN_UNSUPPORTED; + goto Done; } if (IsSplitted !=3D NULL) { *IsSplitted =3D TRUE; @@ -709,7 +779,14 @@ ConvertMemoryPageAttributes ( } } =20 - return RETURN_SUCCESS; +Done: + // + // Restore page table write protection, if any. + // + if (IsWpEnabled) { + EnableReadOnlyPageWriteProtect (); + } + return Status; } =20 /** @@ -922,6 +999,230 @@ RefreshGcdMemoryAttributesFromPaging ( FreePool (MemorySpaceMap); } =20 +/** + 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 add= ress + 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 =3D (VOID *)(UINTN)PagingContext->ContextData.X64.PageTableB= ase; + for (Index =3D 0; Index < EFI_PAGE_SIZE / sizeof (UINT64); ++Index) { + // + // Because the pool header occupies one page, let's always check the a= ddress + // one page before. + // + Pool =3D (VOID *)(UINTN)(((UINTN)BaseAddress - EFI_PAGE_SIZE) & + PAGE_TABLE_POOL_ALIGN_MASK); + + // + // Check the signature. + // + if (!CompareMem (&Pool->Signature, &gPageTablePoolGuid, sizeof (EFI_GU= ID))) { + return Pool; + } + + // + // Check the address at previous alginment boundary. + // + BaseAddress =3D Pool; + } + + return NULL; +} + +/** + Initialize a buffer pool for page table use only. + + To reduce the potential split operation on page table, the pages reserve= d for + page table should be allocated in the times of 512 (=3D 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 aga= in 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 pag= es + in it. + + @param[in] PagingContext The paging context. + @param[in] PoolPages The least page number of the pool to be create= d. + + @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 r= euse + // them if there're still pages available. + // + if (mPageTablePool =3D=3D NULL) { + HeadPool =3D FindPageTablePool (PagingContext); + + if (HeadPool !=3D NULL) { + Pool =3D HeadPool; + do { + ASSERT ( + !CompareMem (&Pool->Signature, &gPageTablePoolGuid, sizeof (EFI_= GUID)) + ); + + if (mPageTablePool =3D=3D NULL || + mPageTablePool->FreePages < Pool->FreePages) { + mPageTablePool =3D Pool; + } + + Pool =3D (VOID *)(UINTN)Pool->NextPool; + } while (Pool !=3D HeadPool); + + // + // Enough pages available? + // + if (PoolPages <=3D mPageTablePool->FreePages) { + return TRUE; + } + } + } + + // + // Reserve at least PcdPageTablePoolUnitSize. + // + PoolUnitPages =3D EFI_SIZE_TO_PAGES (PcdGet32 (PcdPageTablePoolUnitSize)= ); + if (PoolPages <=3D PoolUnitPages) { + PoolPages =3D PoolUnitPages; + } else { + PoolPages =3D (PoolPages + PoolUnitPages) % PoolUnitPages; + } + + // + // Set guard flag to avoid recursive calling of SetMemoryAttributes. + // Protection will be applied in this methond instead before return. + // + mIsAllocatingPageTable =3D TRUE; + Buffer =3D AllocateAlignedPages ( + PoolPages, + FixedPcdGet32 (PcdPageTablePoolAlignment) + ); + mIsAllocatingPageTable =3D FALSE; + + if (Buffer =3D=3D NULL) { + DEBUG ((DEBUG_ERROR, "ERROR: Out of pages aligned at 0x%x\n", + FixedPcdGet32 (PcdPageTablePoolAlignment))); + return FALSE; + } + + if (mPageTablePool =3D=3D NULL) { + mPageTablePool =3D Buffer; + mPageTablePool->NextPool =3D (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; + } + + // + // Link all pools into a list. + // + ((PAGE_TABLE_POOL_HEADER *)Buffer)->NextPool =3D mPageTablePool->NextPoo= l; + mPageTablePool->NextPool =3D (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer; + + // + // Reserve one page for pool header. + // + mPageTablePool =3D Buffer; + CopyMem (&mPageTablePool->Signature, &gPageTablePoolGuid, sizeof (EFI_GU= ID)); + mPageTablePool->FreePages =3D PoolPages - 1; + mPageTablePool->Offset =3D 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 =3D=3D 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 NUL= L 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 =3D=3D 0) { + return NULL; + } + + // + // Renew the pool if necessary. + // + if (Pages > mPageTablePool->FreePages) { + GetCurrentPagingContext (&PagingContext); + if (!InitializePageTablePool (&PagingContext, Pages)) { + return NULL; + } + } + + Buffer =3D (UINT8 *)mPageTablePool + mPageTablePool->Offset; + + mPageTablePool->Offset +=3D EFI_PAGES_TO_SIZE (Pages); + mPageTablePool->FreePages -=3D Pages; + + return Buffer; +} + /** Initialize the Page Table lib. **/ @@ -933,6 +1234,18 @@ InitializePageTableLib ( PAGE_TABLE_LIB_PAGING_CONTEXT CurrentPagingContext; =20 GetCurrentPagingContext (&CurrentPagingContext); + + // + // Reserve memory of page tables for future uses, if paging is enabled. + // + if (CurrentPagingContext.ContextData.X64.PageTableBase !=3D 0 && + (CurrentPagingContext.ContextData.Ia32.Attributes & + PAGE_TABLE_LIB_PAGING_CONTEXT_IA32_X64_ATTRIBUTES_PAE) !=3D 0) { + DisableReadOnlyPageWriteProtect(); + InitializePageTablePool (&CurrentPagingContext, 0); + EnableReadOnlyPageWriteProtect (); + } + DEBUG ((DEBUG_INFO, "CurrentPagingContext:\n", CurrentPagingContext.Mach= ineType)); DEBUG ((DEBUG_INFO, " MachineType - 0x%x\n", CurrentPagingContext.Mac= hineType)); DEBUG ((DEBUG_INFO, " PageTableBase - 0x%x\n", CurrentPagingContext.Con= textData.X64.PageTableBase)); diff --git a/UefiCpuPkg/CpuDxe/CpuPageTable.h b/UefiCpuPkg/CpuDxe/CpuPageTa= ble.h index eaff595b4c..0faa11830d 100644 --- a/UefiCpuPkg/CpuDxe/CpuPageTable.h +++ b/UefiCpuPkg/CpuDxe/CpuPageTable.h @@ -16,6 +16,7 @@ #define _PAGE_TABLE_LIB_H_ =20 #include +#include =20 #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 ); =20 +/** + 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 ret= urns 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 req= uest, 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 --=20 2.14.1.windows.1 _______________________________________________ edk2-devel mailing list edk2-devel@lists.01.org https://lists.01.org/mailman/listinfo/edk2-devel