From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from mail02.groups.io (mail02.groups.io [66.175.222.108]) by spool.mail.gandi.net (Postfix) with ESMTPS id 86F0F740053 for ; Mon, 20 Nov 2023 09:55:43 +0000 (UTC) DKIM-Signature: a=rsa-sha256; bh=8PfLtSXttRuMN7kfHiHbMJN852bAUdAcYg9eX+ndZ6c=; c=relaxed/simple; d=groups.io; h=Message-ID:Date:MIME-Version:User-Agent:Subject:From:To:Cc:Reply-To:References:In-Reply-To:Precedence:List-Subscribe:List-Help:Sender:List-Id:Mailing-List:Delivered-To:List-Unsubscribe-Post:List-Unsubscribe:Content-Type; s=20140610; t=1700474142; v=1; b=LVMLioH0NZxbh15ko4V7BVj8qstulYZ72eFXQ+nQ+PQ1zfWpAQeMvsvHTmnhnPmP19CbTyeo sTd4WXx7B1U3GyfmnnWRaSmCL+vTC+Wrip0NtoxmU629xpW01RgbupP6xXABQVuBIJeYAhmKs0h YP4jRecCEYL+8Prqj7csscjc= X-Received: by 127.0.0.2 with SMTP id yaHKYY7687511xyV774M2hPy; Mon, 20 Nov 2023 01:55:42 -0800 X-Received: from mail.loongson.cn (mail.loongson.cn [114.242.206.163]) by mx.groups.io with SMTP id smtpd.web11.47086.1700474135581155049 for ; Mon, 20 Nov 2023 01:55:39 -0800 X-Received: from loongson.cn (unknown [10.40.24.149]) by gateway (Coremail) with SMTP id _____8DxRvERLVtlry47AA--.51481S3; Mon, 20 Nov 2023 17:55:29 +0800 (CST) X-Received: from [10.40.24.149] (unknown [10.40.24.149]) by localhost.localdomain (Coremail) with SMTP id AQAAf8DxiuQOLVtlxGxHAA--.27168S3; Mon, 20 Nov 2023 17:55:26 +0800 (CST) Message-ID: <2850cbb7-ab9a-4192-ac83-15e0d1193425@loongson.cn> Date: Mon, 20 Nov 2023 17:55:26 +0800 MIME-Version: 1.0 User-Agent: Mozilla Thunderbird Subject: Re: [edk2-devel] [PATCH v3 14/39] UefiCpuPkg: Add LoongArch64CpuMmuLib to UefiCpuPkg From: "Chao Li" To: devel@edk2.groups.io Cc: Eric Dong , Ray Ni , Rahul Kumar , Gerd Hoffmann , Baoqi Zhang , Dongyan Qian , Xianglai Li , Bibo Mao Reply-To: devel@edk2.groups.io,lichao@loongson.cn References: <20231117095742.3605778-1-lichao@loongs> <179860C0A131BC70.3002@groups.io> In-Reply-To: <179860C0A131BC70.3002@groups.io> X-CM-TRANSID: AQAAf8DxiuQOLVtlxGxHAA--.27168S3 X-CM-SenderInfo: xolfxt3r6o00pqjv00gofq/1tbiAQABCGVawioDZgAGs8 X-Coremail-Antispam: 1Uk129KBj9fXoWDtr4kAF1rCF43ZFWfKr13KFX_yoWfAr43Wo WY9F4rCw4UJw1fAr48C3s7Way7JFsY9rZ3Xr40va1jgan0vrs0kFW7ta15C34fA34j9F1D Gr97X3yvyFWfXr1rl-sFpf9Il3svdjkaLaAFLSUrUUUUjb8apTn2vfkv8UJUUUU8wcxFpf 9Il3svdxBIdaVrnUUv73VFW2AGmfu7bjvjm3AaLaJ3UjIYCTnIWjp_UUU5E7kC6x804xWl 14x267AKxVWUJVW8JwAFc2x0x2IEx4CE42xK8VAvwI8IcIk0rVWrJVCq3wAFIxvE14AKwV WUGVWUXwA2ocxC64kIII0Yj41l84x0c7CEw4AK67xGY2AK021l84ACjcxK6xIIjxv20xvE 14v26r1I6r4UM28EF7xvwVC0I7IYx2IY6xkF7I0E14v26r1j6r4UM28EF7xvwVC2z280aV AFwI0_Gr1j6F4UJwA2z4x0Y4vEx4A2jsIEc7CjxVAFwI0_Cr1j6rxdM2AIxVAIcxkEcVAq 07x20xvEncxIr21l57IF6xkI12xvs2x26I8E6xACxx1lYx0E2Ix0cI8IcVAFwI0_JrI_Jr ylYx0Ex4A2jsIE14v26r4j6F4UMcvjeVCFs4IE7xkEbVWUJVW8JwACjcxG0xvEwIxGrwCj r7xvwVCIw2I0I7xG6c02F41l42xK82IYc2Ij64vIr41l4I8I3I0E4IkC6x0Yz7v_Jr0_Gr 1lx2IqxVAqx4xG67AKxVWUGVWUWwC20s026x8GjcxK67AKxVWUGVWUWwC2zVAF1VAY17CE 14v26r1q6r43MIIYrxkI7VAKI48JMIIF0xvE2Ix0cI8IcVAFwI0_Jr0_JF4lIxAIcVC0I7 IYx2IY6xkF7I0E14v26r1j6r4UMIIF0xvE42xK8VAvwI8IcIk0rVWUJVWUCwCI42IY6I8E 87Iv67AKxVW8JVWxJwCI42IY6I8E87Iv6xkF7I0E14v26r4j6r4UJbIYCTnIWIevJa73Uj IFyTuYvjxUzdgAUUUUU Precedence: Bulk List-Subscribe: List-Help: Sender: devel@edk2.groups.io List-Id: Mailing-List: list devel@edk2.groups.io; contact devel+owner@edk2.groups.io List-Unsubscribe-Post: List-Unsubscribe=One-Click List-Unsubscribe: X-Gm-Message-State: WxHolGpFWSH8COAWILZQHSZSx7686176AA= Content-Type: multipart/alternative; boundary="------------RDvPmkobGmCJvBi0hVDVbomp" X-GND-Status: LEGIT Authentication-Results: spool.mail.gandi.net; dkim=pass header.d=groups.io header.s=20140610 header.b=LVMLioH0; dmarc=none; spf=pass (spool.mail.gandi.net: domain of bounce@groups.io designates 66.175.222.108 as permitted sender) smtp.mailfrom=bounce@groups.io --------------RDvPmkobGmCJvBi0hVDVbomp Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: quoted-printable This patch includes two folder, both named LoongArch64CpuMmuLib. This=20 was a mistak when creating the patch, I will fix it in the V4. Thanks, Chao On 2023/11/17 18:00, Chao Li wrote: > Add a new library LoongArch64CpuMmuLib. It provides two-stage MMU library > instances, PEI and DXE. > > BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=3D4584 > > Cc: Eric Dong > Cc: Ray Ni > Cc: Rahul Kumar > Cc: Gerd Hoffmann > Signed-off-by: Chao Li > Co-authored-by: Baoqi Zhang > Co-authored-by: Dongyan Qian > Co-authored-by: Xianglai Li > Co-authored-by: Bibo Mao > --- > .../LoongArch64CpuMmuLib/CommonMmuLib.c | 965 ++++++++++++++++++ > .../LoongArch64CpuMmuLib/CommonMmuLib.h | 43 + > .../LoongArch64CpuMmuLib/DxeCpuMmuLib.inf | 37 + > .../LoongArch64CpuMmuLib/DxeCpuMmuLib.uni | 14 + > .../LoongArch64CpuMmuLib/CommonMmuLib.c | 964 +++++++++++++++++ > .../LoongArch64CpuMmuLib/CommonMmuLib.h | 43 + > .../LoongArch64CpuMmuLib/DxeCpuMmuLib.inf | 37 + > .../LoongArch64CpuMmuLib/DxeCpuMmuLib.uni | 14 + > .../LoongArch64CpuMmuLib/Page.h | 279 +++++ > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.c | 165 +++ > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.inf | 44 + > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.uni | 14 + > .../LoongArch64CpuMmuLib/Tlb.h | 48 + > .../LoongArch64CpuMmuLib/TlbOperation.S | 44 + > .../Library/LoongArch64CpuMmuLib/Page.h | 279 +++++ > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.c | 165 +++ > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.inf | 44 + > .../LoongArch64CpuMmuLib/PeiCpuMmuLib.uni | 14 + > UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h | 48 + > .../LoongArch64CpuMmuLib/TlbOperation.S | 44 + > UefiCpuPkg/UefiCpuPkg.dsc | 2 + > 21 files changed, 3307 insertions(+) > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib= .c > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib= .h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib= .inf > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib= .uni > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/CommonMmuLib.c > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/CommonMmuLib.h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/DxeCpuMmuLib.inf > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/DxeCpuMmuLib.uni > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/Page.h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/PeiCpuMmuLib.c > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/PeiCpuMmuLib.inf > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/PeiCpuMmuLib.uni > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/Tlb.h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64C= puMmuLib/TlbOperation.S > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib= .c > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib= .inf > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib= .uni > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h > create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation= .S > > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c b/Uef= iCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c > new file mode 100644 > index 0000000000..bd5c7e55b6 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c > @@ -0,0 +1,965 @@ > +/** @file > + > + CPU Memory Map Unit Handler Library common functions. > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Pgd or Pgd or PGD - Page Global Directory > + - Pud or Pud or PUD - Page Upper Directory > + - Pmd or Pmd or PMD - Page Middle Directory > + - Pte or pte or PTE - Page Table Entry > + - Val or VAL or val - Value > + - Dir - Directory > +**/ > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include "Tlb.h" > +#include "Page.h" > + > +BOOLEAN mMmuInited =3D FALSE; > +#define SWAP_PAGE_DIR CsrRead(LOONGARCH_CSR_PGDL) > + > +/** > + Check to see if mmu successfully initializes. > + > + @param VOID. > + > + @retval TRUE Initialization has been completed. > + FALSE Initialization did not complete. > +**/ > +BOOLEAN > +MmuIsInit ( > + VOID > + ) > +{ > + if (mMmuInited || (SWAP_PAGE_DIR !=3D 0)) { > + return TRUE; > + } > + > + return FALSE; > +} > + > +/** > + Iterates through the page directory to initialize it. > + > + @param Dst A pointer to the directory of the page to initialize. > + @param Num The number of page directories to initialize. > + @param Src A pointer to the data used to initialize the page directo= ry. > + > + @return VOID. > +**/ > +VOID > +PageDirInit ( > + IN VOID *Dst, > + IN UINTN Num, > + IN VOID *Src > + ) > +{ > + UINTN *Ptr; > + UINTN *End; > + UINTN Entry; > + > + Entry =3D (UINTN)Src; > + Ptr =3D (UINTN *)Dst; > + End =3D Ptr + Num; > + > + for ( ; Ptr < End; Ptr++) { > + *Ptr =3D Entry; > + } > + > + return; > +} > + > +/** > + Gets the virtual address corresponding to the page global directory ta= ble entry. > + > + @param Address the virtual address for the table entry. > + > + @retval PGD A pointer to get the table item. > +**/ > +PGD * > +PgdOffset ( > + IN UINTN Address > + ) > +{ > + return (PGD *)(SWAP_PAGE_DIR) + PGD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page upper directory tab= le entry. > + > + @param Pgd A pointer to a page global directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PUD A pointer to get the table item. > +**/ > +PUD * > +PudOffset ( > + IN PGD *Pgd, > + IN UINTN Address > + ) > +{ > + UINTN PgdVal; > + > + PgdVal =3D (UINTN)PGD_VAL (*Pgd); > + > + return (PUD *)PgdVal + PUD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page middle directory ta= ble entry. > + > + @param Pud A pointer to a page upper directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PMD A pointer to get the table item. > +**/ > +PMD * > +PmdOffset ( > + IN PUD *Pud, > + IN UINTN Address > + ) > +{ > + UINTN PudVal; > + > + PudVal =3D PUD_VAL (*Pud); > + > + return (PMD *)PudVal + PMD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page table entry. > + > + @param Pmd A pointer to a page middle directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PTE A pointer to get the table item. > +**/ > +PTE * > +PteOffset ( > + IN PMD *Pmd, > + IN UINTN Address > + ) > +{ > + UINTN PmdVal; > + > + PmdVal =3D (UINTN)PMD_VAL (*Pmd); > + > + return (PTE *)PmdVal + PTE_INDEX (Address); > +} > + > +/** > + Sets the value of the page table entry. > + > + @param Pte A pointer to a page table entry. > + @param PteVal The value of the page table entry to set. > + > +**/ > +VOID > +SetPte ( > + IN PTE *Pte, > + IN PTE PteVal > + ) > +{ > + *Pte =3D PteVal; > +} > + > +/** > + Sets the value of the page global directory. > + > + @param Pgd A pointer to a page global directory. > + @param Pud The value of the page global directory to set. > + > +**/ > +VOID > +SetPgd ( > + IN PGD *Pgd, > + IN PUD *Pud > + ) > +{ > + *Pgd =3D (PGD) { > + ((UINTN)Pud) > + }; > +} > + > +/** > + Sets the value of the page upper directory. > + > + @param Pud A pointer to a page upper directory. > + @param Pmd The value of the page upper directory to set. > + > +**/ > +VOID > +SetPud ( > + IN PUD *Pud, > + IN PMD *Pmd > + ) > +{ > + *Pud =3D (PUD) { > + ((UINTN)Pmd) > + }; > +} > + > +/** > + Sets the value of the page middle directory. > + > + @param Pmd A pointer to a page middle directory. > + @param Pte The value of the page middle directory to set. > + > +**/ > +VOID > +SetPmd ( > + IN PMD *Pmd, > + IN PTE *Pte > + ) > +{ > + *Pmd =3D (PMD) { > + ((UINTN)Pte) > + }; > +} > + > +/** > + Free up memory space occupied by page tables. > + > + @param Pte A pointer to the page table. > + > +**/ > +VOID > +PteFree ( > + IN PTE *Pte > + ) > +{ > + FreePages ((VOID *)Pte, 1); > +} > + > +/** > + Free up memory space occupied by page middle directory. > + > + @param Pmd A pointer to the page middle directory. > + > +**/ > +VOID > +PmdFree ( > + IN PMD *Pmd > + ) > +{ > + FreePages ((VOID *)Pmd, 1); > +} > + > +/** > + Free up memory space occupied by page upper directory. > + > + @param Pud A pointer to the page upper directory. > + > +**/ > +VOID > +PudFree ( > + IN PUD *Pud > + ) > +{ > + FreePages ((VOID *)Pud, 1); > +} > + > +/** > + Requests the memory space required for the page upper directory, > + initializes it, and places it in the specified page global directory > + > + @param Pgd A pointer to the page global directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PudAlloc ( > + IN PGD *Pgd > + ) > +{ > + PUD *Pud; > + > + Pud =3D (PUD *)AllocatePages (1); > + if (Pud =3D=3D NULL) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + PageDirInit ((VOID *)Pud, ENTRYS_PER_PUD, (VOID *)INVALID_PAGE); > + > + SetPgd (Pgd, Pud); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page middle directory, > + initializes it, and places it in the specified page upper directory > + > + @param Pud A pointer to the page upper directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PmdAlloc ( > + IN PUD *Pud > + ) > +{ > + PMD *Pmd; > + > + Pmd =3D (PMD *)AllocatePages (1); > + if (!Pmd) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + PageDirInit ((VOID *)Pmd, ENTRYS_PER_PMD, (VOID *)INVALID_PAGE); > + > + SetPud (Pud, Pmd); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page table, > + initializes it, and places it in the specified page middle directory > + > + @param Pmd A pointer to the page middle directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PteAlloc ( > + IN PMD *Pmd > + ) > +{ > + PTE *Pte; > + > + Pte =3D (PTE *)AllocatePages (1); > + if (!Pte) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + Pte =3D ZeroMem (Pte, EFI_PAGE_SIZE); > + > + SetPmd (Pmd, Pte); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page upper directory, > + initializes it, and places it in the specified page global directory, > + and get the page upper directory entry corresponding to the virtual ad= dress. > + > + @param Pgd A pointer to the page global directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page upper directory entry. Return N= ULL, if > + allocate the memory buffer is fail. > +**/ > +PUD * > +PudAllocGet ( > + IN PGD *Pgd, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PGD_IS_EMPTY (*Pgd)) { > + Status =3D PudAlloc (Pgd); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PudOffset (Pgd, Address); > +} > + > +/** > + Requests the memory space required for the page middle directory, > + initializes it, and places it in the specified page upper directory, > + and get the page middle directory entry corresponding to the virtual a= ddress. > + > + @param Pud A pointer to the page upper directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page middle directory entry. Return = NULL, if > + allocate the memory buffer is fail. > +**/ > +PMD * > +PmdAllocGet ( > + IN PUD *Pud, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PUD_IS_EMPTY (*Pud)) { > + Status =3D PmdAlloc (Pud); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PmdOffset (Pud, Address); > +} > + > +/** > + Requests the memory space required for the page table, > + initializes it, and places it in the specified page middle directory, > + and get the page table entry corresponding to the virtual address. > + > + @param Pmd A pointer to the page upper directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page table entry. Return NULL, if al= locate > + the memory buffer is fail. > +**/ > +PTE * > +PteAllocGet ( > + IN PMD *Pmd, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PMD_IS_EMPTY (*Pmd)) { > + Status =3D PteAlloc (Pmd); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PteOffset (Pmd, Address); > +} > + > +/** > + Gets the physical address of the page table entry corresponding to the= specified virtual address. > + > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page table entry. > + @retval NULL > +**/ > +PTE * > +GetPteAddress ( > + IN UINTN Address > + ) > +{ > + PGD *Pgd; > + PUD *Pud; > + PMD *Pmd; > + > + Pgd =3D PgdOffset (Address); > + > + if (PGD_IS_EMPTY (*Pgd)) { > + return NULL; > + } > + > + Pud =3D PudOffset (Pgd, Address); > + > + if (PUD_IS_EMPTY (*Pud)) { > + return NULL; > + } > + > + Pmd =3D PmdOffset (Pud, Address); > + if (PMD_IS_EMPTY (*Pmd)) { > + return NULL; > + } > + > + if (IS_HUGE_PAGE (Pmd->PmdVal)) { > + return ((PTE *)Pmd); > + } > + > + return PteOffset (Pmd, Address); > +} > + > +/** > + Gets the Attributes of Huge Page. > + > + @param Pmd A pointer to the page middle directory. > + > + @retval Value of Attributes. > +**/ > +UINTN > +GetHugePageAttributes ( > + IN PMD *Pmd > + ) > +{ > + UINTN Attributes; > + UINTN GlobalFlag; > + UINTN HugeVal; > + > + HugeVal =3D PMD_VAL (*Pmd); > + Attributes =3D HugeVal & (~HUGEP_PAGE_MASK); > + GlobalFlag =3D ((Attributes & (1 << PAGE_HGLOBAL_SHIFT)) >> PAGE_HGLO= BAL_SHIFT) << PAGE_GLOBAL_SHIFT; > + Attributes &=3D ~(1 << PAGE_HGLOBAL_SHIFT); > + Attributes |=3D GlobalFlag; > + return Attributes; > +} > + > +/** > + Establishes a page table entry based on the specified memory region. > + > + @param Pmd A pointer to the page middle directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page table entry was created successfull= y. > + @retval EFI_OUT_OF_RESOURCES Page table entry establishment faile= d due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPteRange ( > + IN PMD *Pmd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PTE *Pte; > + PTE PteVal; > + BOOLEAN UpDate; > + > + Pte =3D PteAllocGet (Pmd, Address); > + if (!Pte) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + DEBUG (( > + DEBUG_INFO, > + "%a %d Address %p End %p Attributes %llx\n", > + __func__, > + __LINE__, > + Address, > + End, > + Attributes > + )); > + > + do { > + UpDate =3D FALSE; > + PteVal =3D MAKE_PTE (Address, Attributes); > + > + if ((!PTE_IS_EMPTY (*Pte)) && > + (PTE_VAL (*Pte) !=3D PTE_VAL (PteVal))) > + { > + UpDate =3D TRUE; > + } > + > + SetPte (Pte, PteVal); > + if (UpDate) { > + InvalidTlb (Address); > + } > + } while (Pte++, Address +=3D EFI_PAGE_SIZE, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Convert Huge Page to Page. > + > + @param Pmd A pointer to the page middle directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page table entry was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table entry establishment failed d= ue to resource exhaustion. > +**/ > +EFI_STATUS > +ConvertHugePageToPage ( > + IN PMD *Pmd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + UINTN OldAttributes; > + UINTN HugePageEnd; > + UINTN HugePageStart; > + EFI_STATUS Status; > + > + Status =3D EFI_SUCCESS; > + > + if ((PMD_IS_EMPTY (*Pmd)) || > + (!IS_HUGE_PAGE (Pmd->PmdVal))) > + { > + Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes); > + } else { > + OldAttributes =3D GetHugePageAttributes (Pmd); > + if (Attributes =3D=3D OldAttributes) { > + return Status; > + } > + > + SetPmd (Pmd, (PTE *)(INVALID_PAGE)); > + HugePageStart =3D Address & PMD_MASK; > + HugePageEnd =3D HugePageStart + HUGE_PAGE_SIZE; > + ASSERT (HugePageEnd >=3D End); > + > + if (Address > HugePageStart) { > + Status |=3D MemoryMapPteRange (Pmd, HugePageStart, Address, OldAtt= ributes); > + } > + > + Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes); > + > + if (End < HugePageEnd) { > + Status |=3D MemoryMapPteRange (Pmd, End, HugePageEnd, OldAttribute= s); > + } > + } > + > + return Status; > +} > + > +/** > + Establishes a page middle directory based on the specified memory regi= on. > + > + @param Pud A pointer to the page upper directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page middle directory was created succes= sfully. > + @retval EFI_OUT_OF_RESOURCES Page middle directory establishment = failed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPmdRange ( > + IN PUD *Pud, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PMD *Pmd; > + UINTN Next; > + PTE PteVal; > + BOOLEAN UpDate; > + > + Pmd =3D PmdAllocGet (Pud, Address); > + if (!Pmd) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + do { > + Next =3D PMD_ADDRESS_END (Address, End); > + if (((Address & (~PMD_MASK)) =3D=3D 0) && > + ((Next & (~PMD_MASK)) =3D=3D 0) && > + (PMD_IS_EMPTY (*Pmd) || IS_HUGE_PAGE (Pmd->PmdVal))) > + { > + UpDate =3D FALSE; > + PteVal =3D MAKE_HUGE_PTE (Address, Attributes); > + > + if ((!PMD_IS_EMPTY (*Pmd)) && > + (PMD_VAL (*Pmd) !=3D PTE_VAL (PteVal))) > + { > + UpDate =3D TRUE; > + } > + > + SetPmd (Pmd, (PTE *)PteVal.PteVal); > + if (UpDate) { > + InvalidTlb (Address); > + } > + } else { > + ConvertHugePageToPage (Pmd, Address, Next, Attributes); > + } > + } while (Pmd++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Establishes a page upper directory based on the specified memory regio= n. > + > + @param Pgd A pointer to the page global directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page upper directory was created success= fully. > + @retval EFI_OUT_OF_RESOURCES Page upper directory establishment f= ailed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPudRange ( > + IN PGD *Pgd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PUD *Pud; > + UINTN Next; > + > + Pud =3D PudAllocGet (Pgd, Address); > + if (!Pud) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + do { > + Next =3D PUD_ADDRESS_END (Address, End); > + if (EFI_ERROR (MemoryMapPmdRange (Pud, Address, Next, Attributes))) = { > + return EFI_OUT_OF_RESOURCES; > + } > + } while (Pud++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Establishes a page global directory based on the specified memory regi= on. > + > + @param Start The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page global directory was created succes= sfully. > + @retval EFI_OUT_OF_RESOURCES Page global directory establishment = failed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPageRange ( > + IN UINTN Start, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PGD *Pgd; > + UINTN Next; > + UINTN Address; > + EFI_STATUS Err; > + > + Address =3D Start; > + > + /* Get PGD(PTE PMD PUD PGD) in PageTables */ > + Pgd =3D PgdOffset (Address); > + do { > + Next =3D PGD_ADDRESS_END (Address, End); > + /* Get Next Align Page to Map */ > + Err =3D MemoryMapPudRange (Pgd, Address, Next, Attributes); > + if (Err) { > + return Err; > + } > + } while (Pgd++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Page tables are established from memory-mapped tables. > + > + @param MemoryRegion A pointer to a memory-mapped table entry. > + > + @retval EFI_SUCCESS The page table was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table establishment failed due= to resource exhaustion. > +**/ > +EFI_STATUS > +FillTranslationTable ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryRegion > + ) > +{ > + return MemoryMapPageRange ( > + MemoryRegion->VirtualBase, > + (MemoryRegion->Length + MemoryRegion->VirtualBase), > + MemoryRegion->Attributes > + ); > +} > + > +/** > + Convert EFI Attributes to Loongarch Attributes. > + > + @param[in] EfiAttributes Efi Attributes. > + > + @retval Corresponding architecture attributes. > +**/ > +UINTN > +EfiAttributeConverse ( > + IN UINTN EfiAttributes > + ) > +{ > + UINTN LoongArchAttributes; > + > + LoongArchAttributes =3D PAGE_VALID | PAGE_DIRTY | PLV_KERNEL | PAGE_GL= OBAL; > + > + switch (EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) { > + case EFI_MEMORY_UC: > + LoongArchAttributes |=3D CACHE_SUC; > + break; > + case EFI_MEMORY_WC: > + case EFI_MEMORY_WT: > + case EFI_MEMORY_WB: > + LoongArchAttributes |=3D CACHE_CC; > + break; > + default: > + LoongArchAttributes |=3D CACHE_CC; > + break; > + } > + > + // Write protection attributes > + if (((EfiAttributes & EFI_MEMORY_RO) !=3D 0) || > + ((EfiAttributes & EFI_MEMORY_WP) !=3D 0)) > + { > + LoongArchAttributes &=3D ~PAGE_DIRTY; > + } > + > + if ((EfiAttributes & EFI_MEMORY_RP) !=3D 0) { > + LoongArchAttributes |=3D PAGE_NO_READ; > + } > + > + // eXecute protection attribute > + if ((EfiAttributes & EFI_MEMORY_XP) !=3D 0) { > + LoongArchAttributes |=3D PAGE_NO_EXEC; > + } > + > + return LoongArchAttributes; > +} > + > +/** > + Finds the length and memory properties of the memory region correspond= ing to the specified base address. > + > + @param[in] BaseAddress To find the base address of the memory regi= on. > + @param[in] EndAddress To find the end address of the memory regio= n. > + @param[out] RegionLength The length of the memory region found. > + @param[out] RegionAttributes Properties of the memory region found= . > + > + @retval EFI_SUCCESS The corresponding memory area was successfully= found > + EFI_NOT_FOUND No memory area found > +**/ > +EFI_STATUS > +GetMemoryRegionAttribute ( > + IN UINTN BaseAddress, > + IN UINTN EndAddress, > + OUT UINTN *RegionLength, > + OUT UINTN *RegionAttributes > + ) > +{ > + PTE *Pte; > + UINTN Attributes; > + UINTN AttributesTmp; > + UINTN MaxAddress; > + > + if (!MmuIsInit ()) { > + return EFI_UNSUPPORTED; > + } > + > + MaxAddress =3D LShiftU64 (1ULL, MAX_VA_BITS) - 1; > + Pte =3D GetPteAddress (BaseAddress); > + > + if (Pte =3D=3D NULL) { > + return EFI_NOT_FOUND; > + } > + > + Attributes =3D GET_PAGE_ATTRIBUTES (*Pte); > + if (IS_HUGE_PAGE (Pte->PteVal)) { > + *RegionAttributes =3D Attributes & (~(PAGE_HUGE)); > + *RegionLength +=3D HUGE_PAGE_SIZE; > + } else { > + *RegionLength +=3D EFI_PAGE_SIZE; > + *RegionAttributes =3D Attributes; > + } > + > + while (BaseAddress <=3D MaxAddress) { > + Pte =3D GetPteAddress (BaseAddress); > + if (Pte =3D=3D NULL) { > + return EFI_SUCCESS; > + } > + > + AttributesTmp =3D GET_PAGE_ATTRIBUTES (*Pte); > + if (IS_HUGE_PAGE (Pte->PteVal)) { > + if (AttributesTmp =3D=3D Attributes) { > + *RegionLength +=3D HUGE_PAGE_SIZE; > + } > + > + BaseAddress +=3D HUGE_PAGE_SIZE; > + } else { > + if (AttributesTmp =3D=3D Attributes) { > + *RegionLength +=3D EFI_PAGE_SIZE; > + } > + > + BaseAddress +=3D EFI_PAGE_SIZE; > + } > + > + if (BaseAddress > EndAddress) { > + break; > + } > + } > + > + return EFI_SUCCESS; > +} > + > +/** > + Sets the Attributes of the specified memory region > + > + @param[in] BaseAddress The base address of the memory region to se= t the Attributes. > + @param[in] Length The length of the memory region to set the = Attributes. > + @param[in] Attributes The Attributes to be set. > + @param[in] AttributeMask Mask of memory attributes to take into acco= unt. > + > + @retval EFI_SUCCESS The Attributes was set successfully > +**/ > +EFI_STATUS > +SetMemoryRegionAttributes ( > + IN EFI_PHYSICAL_ADDRESS BaseAddress, > + IN UINTN Length, > + IN UINTN Attributes, > + IN UINT64 AttributeMask > + ) > +{ > + if (!MmuIsInit ()) { > + return EFI_UNSUPPORTED; > + } > + > + Attributes =3D EfiAttributeConverse (Attributes); > + MemoryMapPageRange (BaseAddress, BaseAddress + Length, Attributes); > + > + return EFI_SUCCESS; > +} > + > +/** > + Sets the non-executable Attributes for the specified memory region > + > + @param[in] BaseAddress The base address of the memory region to set = the Attributes. > + @param[in] Length The length of the memory region to set the At= tributes. > + > + @retval EFI_SUCCESS The Attributes was set successfully > +**/ > +EFI_STATUS > +SetMemoryRegionNoExec ( > + IN EFI_PHYSICAL_ADDRESS BaseAddress, > + IN UINTN Length > + ) > +{ > + if (MmuIsInit ()) { > + Length =3D EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (Length)); > + SetMemoryRegionAttributes (BaseAddress, Length, EFI_MEMORY_XP, 0x0); > + } > + > + return EFI_SUCCESS; > +} > + > +/** > + Check to see if mmu successfully initializes and saves the result. > + > + @param[in] ImageHandle The firmware allocated handle for the EFI ima= ge. > + @param[in] SystemTable A pointer to the EFI System Table. > + > + @retval RETURN_SUCCESS Initialization succeeded. > +**/ > +RETURN_STATUS > +EFIAPI > +MmuInitialize ( > + IN EFI_HANDLE ImageHandle, > + IN EFI_SYSTEM_TABLE *SystemTable > + ) > +{ > + if (SWAP_PAGE_DIR !=3D 0) { > + mMmuInited =3D TRUE; > + } > + > + return RETURN_SUCCESS; > +} > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h b/Uef= iCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h > new file mode 100644 > index 0000000000..aa96f5143c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h > @@ -0,0 +1,43 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Dir - Directory > +**/ > + > +#ifndef MMU_LIB_CORE_H_ > +#define MMU_LIB_CORE_H_ > + > +/** > + Iterates through the page directory to initialize it. > + > + @param Dst A pointer to the directory of the page to initialize. > + @param Num The number of page directories to initialize. > + @param Src A pointer to the data used to initialize the page directo= ry. > + > + @retval VOID. > +**/ > +VOID > +PageDirInit ( > + IN VOID *dest, > + IN UINTN Count, > + IN VOID *src > + ); > + > +/** > + Page tables are established from memory-mapped tables. > + > + @param MemoryRegion A pointer to a memory-mapped table entry. > + > + @retval EFI_SUCCESS The page table was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table establishment failed due= to resource exhaustion. > +**/ > +EFI_STATUS > +FillTranslationTable ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryRegion > + ); > + > +#endif // MMU_LIB_CORE_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf b/U= efiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf > new file mode 100644 > index 0000000000..d153354dd2 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf > @@ -0,0 +1,37 @@ > +## @file > +# CPU Memory Map Unit DXE phase driver. > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All right= s reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +## > + > +[Defines] > + INF_VERSION =3D 0x00010005 > + BASE_NAME =3D DxeCpuMmuLib > + MODULE_UNI_FILE =3D DxeCpuMmuLib.uni > + FILE_GUID =3D DA8F0232-FB14-42F0-922C-63104D2C70B= E > + MODULE_TYPE =3D DXE_DRIVER > + VERSION_STRING =3D 1.0 > + LIBRARY_CLASS =3D CpuMmuLib | DXE_DRIVER > + CONSTRUCTOR =3D MmuInitialize > + > +# > +# VALID_ARCHITECTURES =3D LOONGARCH64 > +# > + > +[Sources] > + TlbOperation.S | GCC > + CommonMmuLib.c > + Tlb.h > + Page.h > + > +[Packages] > + MdePkg/MdePkg.dec > + UefiCpuPkg/UefiCpuPkg.dec > + > +[LibraryClasses] > + MemoryAllocationLib > + PcdLib > + DebugLib > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni b/U= efiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni > new file mode 100644 > index 0000000000..2e841d714c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni > @@ -0,0 +1,14 @@ > +// /** @file > +// CPU Memory Manager Unit library instance for DXE modules. > +// > +// CPU Memory Manager Unit library instance for DXE modules. > +// > +// Copyright (c) 2023, Loongson Technology Corporation Limited. All righ= ts reserved.
> +// > +// SPDX-License-Identifier: BSD-2-Clause-Patent > +// > +// **/ > + > +#string STR_MODULE_ABSTRACT #language en-US "CPU Memory Mana= ger Unit library instance for DXE modules." > + > +#string STR_MODULE_DESCRIPTION #language en-US "CPU Memory Mana= ger Unit library instance for DXE modules." > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /CommonMmuLib.c b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu= Lib/CommonMmuLib.c > new file mode 100644 > index 0000000000..f5e632a237 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Common= MmuLib.c > @@ -0,0 +1,964 @@ > +/** @file > + > + CPU Memory Map Unit Handler Library common functions. > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Pgd or Pgd or PGD - Page Global Directory > + - Pud or Pud or PUD - Page Upper Directory > + - Pmd or Pmd or PMD - Page Middle Directory > + - Pte or pte or PTE - Page Table Entry > + - Val or VAL or val - Value > + - Dir - Directory > +**/ > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include "Tlb.h" > +#include "Page.h" > + > +BOOLEAN mMmuInited =3D FALSE; > +#define SWAP_PAGE_DIR CsrRead(LOONGARCH_CSR_PGDL) > + > +/** > + Check to see if mmu successfully initializes. > + > + @param VOID. > + > + @retval TRUE Initialization has been completed. > + FALSE Initialization did not complete. > +**/ > +BOOLEAN > +MmuIsInit ( > + VOID > + ) > +{ > + if (mMmuInited || (SWAP_PAGE_DIR !=3D 0)) { > + return TRUE; > + } > + > + return FALSE; > +} > + > +/** > + Iterates through the page directory to initialize it. > + > + @param Dst A pointer to the directory of the page to initialize. > + @param Num The number of page directories to initialize. > + @param Src A pointer to the data used to initialize the page directo= ry. > + > + @return VOID. > +**/ > +VOID > +PageDirInit ( > + IN VOID *Dst, > + IN UINTN Num, > + IN VOID *Src > + ) > +{ > + UINTN *Ptr; > + UINTN *End; > + UINTN Entry; > + > + Entry =3D (UINTN)Src; > + Ptr =3D (UINTN *)Dst; > + End =3D Ptr + Num; > + > + for ( ; Ptr < End; Ptr++) { > + *Ptr =3D Entry; > + } > + > + return; > +} > + > +/** > + Gets the virtual address corresponding to the page global directory ta= ble entry. > + > + @param Address the virtual address for the table entry. > + > + @retval PGD A pointer to get the table item. > +**/ > +PGD * > +PgdOffset ( > + IN UINTN Address > + ) > +{ > + return (PGD *)(SWAP_PAGE_DIR) + PGD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page upper directory tab= le entry. > + > + @param Pgd A pointer to a page global directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PUD A pointer to get the table item. > +**/ > +PUD * > +PudOffset ( > + IN PGD *Pgd, > + IN UINTN Address > + ) > +{ > + UINTN PgdVal; > + > + PgdVal =3D (UINTN)PGD_VAL (*Pgd); > + > + return (PUD *)PgdVal + PUD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page middle directory ta= ble entry. > + > + @param Pud A pointer to a page upper directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PMD A pointer to get the table item. > +**/ > +PMD * > +PmdOffset ( > + IN PUD *Pud, > + IN UINTN Address > + ) > +{ > + UINTN PudVal; > + > + PudVal =3D PUD_VAL (*Pud); > + > + return (PMD *)PudVal + PMD_INDEX (Address); > +} > + > +/** > + Gets the virtual address corresponding to the page table entry. > + > + @param Pmd A pointer to a page middle directory table entry. > + @param Address the virtual address for the table entry. > + > + @retval PTE A pointer to get the table item. > +**/ > +PTE * > +PteOffset ( > + IN PMD *Pmd, > + IN UINTN Address > + ) > +{ > + UINTN PmdVal; > + > + PmdVal =3D (UINTN)PMD_VAL (*Pmd); > + > + return (PTE *)PmdVal + PTE_INDEX (Address); > +} > + > +/** > + Sets the value of the page table entry. > + > + @param Pte A pointer to a page table entry. > + @param PteVal The value of the page table entry to set. > + > +**/ > +VOID > +SetPte ( > + IN PTE *Pte, > + IN PTE PteVal > + ) > +{ > + *Pte =3D PteVal; > +} > + > +/** > + Sets the value of the page global directory. > + > + @param Pgd A pointer to a page global directory. > + @param Pud The value of the page global directory to set. > + > +**/ > +VOID > +SetPgd ( > + IN PGD *Pgd, > + IN PUD *Pud > + ) > +{ > + *Pgd =3D (PGD) { > + ((UINTN)Pud) > + }; > +} > + > +/** > + Sets the value of the page upper directory. > + > + @param Pud A pointer to a page upper directory. > + @param Pmd The value of the page upper directory to set. > + > +**/ > +VOID > +SetPud ( > + IN PUD *Pud, > + IN PMD *Pmd > + ) > +{ > + *Pud =3D (PUD) { > + ((UINTN)Pmd) > + }; > +} > + > +/** > + Sets the value of the page middle directory. > + > + @param Pmd A pointer to a page middle directory. > + @param Pte The value of the page middle directory to set. > + > +**/ > +VOID > +SetPmd ( > + IN PMD *Pmd, > + IN PTE *Pte > + ) > +{ > + *Pmd =3D (PMD) { > + ((UINTN)Pte) > + }; > +} > + > +/** > + Free up memory space occupied by page tables. > + > + @param Pte A pointer to the page table. > + > +**/ > +VOID > +PteFree ( > + IN PTE *Pte > + ) > +{ > + FreePages ((VOID *)Pte, 1); > +} > + > +/** > + Free up memory space occupied by page middle directory. > + > + @param Pmd A pointer to the page middle directory. > + > +**/ > +VOID > +PmdFree ( > + IN PMD *Pmd > + ) > +{ > + FreePages ((VOID *)Pmd, 1); > +} > + > +/** > + Free up memory space occupied by page upper directory. > + > + @param Pud A pointer to the page upper directory. > + > +**/ > +VOID > +PudFree ( > + IN PUD *Pud > + ) > +{ > + FreePages ((VOID *)Pud, 1); > +} > + > +/** > + Requests the memory space required for the page upper directory, > + initializes it, and places it in the specified page global directory > + > + @param Pgd A pointer to the page global directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PudAlloc ( > + IN PGD *Pgd > + ) > +{ > + PUD *Pud; > + > + Pud =3D (PUD *)AllocatePages (1); > + if (Pud =3D=3D NULL) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + PageDirInit ((VOID *)Pud, ENTRYS_PER_PUD, (VOID *)INVALID_PAGE); > + > + SetPgd (Pgd, Pud); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page middle directory, > + initializes it, and places it in the specified page upper directory > + > + @param Pud A pointer to the page upper directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PmdAlloc ( > + IN PUD *Pud > + ) > +{ > + PMD *Pmd; > + > + Pmd =3D (PMD *)AllocatePages (1); > + if (!Pmd) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + PageDirInit ((VOID *)Pmd, ENTRYS_PER_PMD, (VOID *)INVALID_PAGE); > + > + SetPud (Pud, Pmd); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page table, > + initializes it, and places it in the specified page middle directory > + > + @param Pmd A pointer to the page middle directory. > + > + @retval EFI_SUCCESS Memory request successful. > + @retval EFI_OUT_OF_RESOURCES Resource exhaustion cannot be requested= to memory. > +**/ > +EFI_STATUS > +PteAlloc ( > + IN PMD *Pmd > + ) > +{ > + PTE *Pte; > + > + Pte =3D (PTE *)AllocatePages (1); > + if (!Pte) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + Pte =3D ZeroMem (Pte, EFI_PAGE_SIZE); > + > + SetPmd (Pmd, Pte); > + > + return EFI_SUCCESS; > +} > + > +/** > + Requests the memory space required for the page upper directory, > + initializes it, and places it in the specified page global directory, > + and get the page upper directory entry corresponding to the virtual ad= dress. > + > + @param Pgd A pointer to the page global directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page upper directory entry. Return N= ULL, if > + allocate the memory buffer is fail. > +**/ > +PUD * > +PudAllocGet ( > + IN PGD *Pgd, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PGD_IS_EMPTY (*Pgd)) { > + Status =3D PudAlloc (Pgd); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PudOffset (Pgd, Address); > +} > + > +/** > + Requests the memory space required for the page middle directory, > + initializes it, and places it in the specified page upper directory, > + and get the page middle directory entry corresponding to the virtual a= ddress. > + > + @param Pud A pointer to the page upper directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page middle directory entry. Return = NULL, if > + allocate the memory buffer is fail. > +**/ > +PMD * > +PmdAllocGet ( > + IN PUD *Pud, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PUD_IS_EMPTY (*Pud)) { > + Status =3D PmdAlloc (Pud); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PmdOffset (Pud, Address); > +} > + > +/** > + Requests the memory space required for the page table, > + initializes it, and places it in the specified page middle directory, > + and get the page table entry corresponding to the virtual address. > + > + @param Pmd A pointer to the page upper directory. > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page table entry. Return NULL, if al= locate > + the memory buffer is fail. > +**/ > +PTE * > +PteAllocGet ( > + IN PMD *Pmd, > + IN UINTN Address > + ) > +{ > + EFI_STATUS Status; > + > + if (PMD_IS_EMPTY (*Pmd)) { > + Status =3D PteAlloc (Pmd); > + ASSERT_EFI_ERROR (Status); > + if (EFI_ERROR (Status)) { > + return NULL; > + } > + } > + > + return PteOffset (Pmd, Address); > +} > + > +/** > + Gets the physical address of the page table entry corresponding to the= specified virtual address. > + > + @param Address The corresponding virtual address of the page table e= ntry. > + > + @retval A pointer to the page table entry. > + @retval NULL > +**/ > +PTE * > +GetPteAddress ( > + IN UINTN Address > + ) > +{ > + PGD *Pgd; > + PUD *Pud; > + PMD *Pmd; > + > + Pgd =3D PgdOffset (Address); > + > + if (PGD_IS_EMPTY (*Pgd)) { > + return NULL; > + } > + > + Pud =3D PudOffset (Pgd, Address); > + > + if (PUD_IS_EMPTY (*Pud)) { > + return NULL; > + } > + > + Pmd =3D PmdOffset (Pud, Address); > + if (PMD_IS_EMPTY (*Pmd)) { > + return NULL; > + } > + > + if (IS_HUGE_PAGE (Pmd->PmdVal)) { > + return ((PTE *)Pmd); > + } > + > + return PteOffset (Pmd, Address); > +} > + > +/** > + Gets the Attributes of Huge Page. > + > + @param Pmd A pointer to the page middle directory. > + > + @retval Value of Attributes. > +**/ > +UINTN > +GetHugePageAttributes ( > + IN PMD *Pmd > + ) > +{ > + UINTN Attributes; > + UINTN GlobalFlag; > + UINTN HugeVal; > + > + HugeVal =3D PMD_VAL (*Pmd); > + Attributes =3D HugeVal & (~HUGEP_PAGE_MASK); > + GlobalFlag =3D ((Attributes & (1 << PAGE_HGLOBAL_SHIFT)) >> PAGE_HGLO= BAL_SHIFT) << PAGE_GLOBAL_SHIFT; > + Attributes &=3D ~(1 << PAGE_HGLOBAL_SHIFT); > + Attributes |=3D GlobalFlag; > + return Attributes; > +} > + > +/** > + Establishes a page table entry based on the specified memory region. > + > + @param Pmd A pointer to the page middle directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page table entry was created successfull= y. > + @retval EFI_OUT_OF_RESOURCES Page table entry establishment faile= d due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPteRange ( > + IN PMD *Pmd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PTE *Pte; > + PTE PteVal; > + BOOLEAN UpDate; > + > + Pte =3D PteAllocGet (Pmd, Address); > + if (!Pte) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + DEBUG (( > + DEBUG_INFO, > + "%a %d Address %p End %p Attributes %llx\n", > + __func__, > + __LINE__, > + Address, > + End, > + Attributes > + )); > + > + do { > + UpDate =3D FALSE; > + PteVal =3D MAKE_PTE (Address, Attributes); > + > + if ((!PTE_IS_EMPTY (*Pte)) && > + (PTE_VAL (*Pte) !=3D PTE_VAL (PteVal))) > + { > + UpDate =3D TRUE; > + } > + > + SetPte (Pte, PteVal); > + if (UpDate) { > + InvalidTlb (Address); > + } > + } while (Pte++, Address +=3D EFI_PAGE_SIZE, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Convert Huge Page to Page. > + > + @param Pmd A pointer to the page middle directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page table entry was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table entry establishment failed d= ue to resource exhaustion. > +**/ > +EFI_STATUS > +ConvertHugePageToPage ( > + IN PMD *Pmd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + UINTN OldAttributes; > + UINTN HugePageEnd; > + UINTN HugePageStart; > + EFI_STATUS Status; > + > + Status =3D EFI_SUCCESS; > + > + if ((PMD_IS_EMPTY (*Pmd)) || > + (!IS_HUGE_PAGE (Pmd->PmdVal))) > + { > + Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes); > + } else { > + OldAttributes =3D GetHugePageAttributes (Pmd); > + if (Attributes =3D=3D OldAttributes) { > + return Status; > + } > + > + SetPmd (Pmd, (PTE *)(INVALID_PAGE)); > + HugePageStart =3D Address & PMD_MASK; > + HugePageEnd =3D HugePageStart + HUGE_PAGE_SIZE; > + ASSERT (HugePageEnd >=3D End); > + > + if (Address > HugePageStart) { > + Status |=3D MemoryMapPteRange (Pmd, HugePageStart, Address, OldAtt= ributes); > + } > + > + Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes); > + > + if (End < HugePageEnd) { > + Status |=3D MemoryMapPteRange (Pmd, End, HugePageEnd, OldAttribute= s); > + } > + } > + > + return Status; > +} > + > +/** > + Establishes a page middle directory based on the specified memory regi= on. > + > + @param Pud A pointer to the page upper directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page middle directory was created succes= sfully. > + @retval EFI_OUT_OF_RESOURCES Page middle directory establishment = failed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPmdRange ( > + IN PUD *Pud, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PMD *Pmd; > + UINTN Next; > + PTE PteVal; > + BOOLEAN UpDate; > + > + Pmd =3D PmdAllocGet (Pud, Address); > + if (!Pmd) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + do { > + Next =3D PMD_ADDRESS_END (Address, End); > + if (((Address & (~PMD_MASK)) =3D=3D 0) && > + ((Next & (~PMD_MASK)) =3D=3D 0) && > + (PMD_IS_EMPTY (*Pmd) || IS_HUGE_PAGE (Pmd->PmdVal))) > + { > + UpDate =3D FALSE; > + PteVal =3D MAKE_HUGE_PTE (Address, Attributes); > + > + if ((!PMD_IS_EMPTY (*Pmd)) && > + (PMD_VAL (*Pmd) !=3D PTE_VAL (PteVal))) > + { > + UpDate =3D TRUE; > + } > + > + SetPmd (Pmd, (PTE *)PteVal.PteVal); > + if (UpDate) { > + InvalidTlb (Address); > + } > + } else { > + ConvertHugePageToPage (Pmd, Address, Next, Attributes); > + } > + } while (Pmd++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Establishes a page upper directory based on the specified memory regio= n. > + > + @param Pgd A pointer to the page global directory. > + @param Address The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page upper directory was created success= fully. > + @retval EFI_OUT_OF_RESOURCES Page upper directory establishment f= ailed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPudRange ( > + IN PGD *Pgd, > + IN UINTN Address, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PUD *Pud; > + UINTN Next; > + > + Pud =3D PudAllocGet (Pgd, Address); > + if (!Pud) { > + return EFI_OUT_OF_RESOURCES; > + } > + > + do { > + Next =3D PUD_ADDRESS_END (Address, End); > + if (EFI_ERROR (MemoryMapPmdRange (Pud, Address, Next, Attributes))) = { > + return EFI_OUT_OF_RESOURCES; > + } > + } while (Pud++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Establishes a page global directory based on the specified memory regi= on. > + > + @param Start The memory space start address. > + @param End The end address of the memory space. > + @param Attributes Memory space Attributes. > + > + @retval EFI_SUCCESS The page global directory was created succes= sfully. > + @retval EFI_OUT_OF_RESOURCES Page global directory establishment = failed due to resource exhaustion. > +**/ > +EFI_STATUS > +MemoryMapPageRange ( > + IN UINTN Start, > + IN UINTN End, > + IN UINTN Attributes > + ) > +{ > + PGD *Pgd; > + UINTN Next; > + UINTN Address; > + EFI_STATUS Err; > + > + Address =3D Start; > + > + /* Get PGD(PTE PMD PUD PGD) in PageTables */ > + Pgd =3D PgdOffset (Address); > + do { > + Next =3D PGD_ADDRESS_END (Address, End); > + /* Get Next Align Page to Map */ > + Err =3D MemoryMapPudRange (Pgd, Address, Next, Attributes); > + if (Err) { > + return Err; > + } > + } while (Pgd++, Address =3D Next, Address !=3D End); > + > + return EFI_SUCCESS; > +} > + > +/** > + Page tables are established from memory-mapped tables. > + > + @param MemoryRegion A pointer to a memory-mapped table entry. > + > + @retval EFI_SUCCESS The page table was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table establishment failed due= to resource exhaustion. > +**/ > +EFI_STATUS > +FillTranslationTable ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryRegion > + ) > +{ > + return MemoryMapPageRange ( > + MemoryRegion->VirtualBase, > + (MemoryRegion->Length + MemoryRegion->VirtualBase), > + MemoryRegion->Attributes > + ); > +} > + > +/** > + Convert EFI Attributes to Loongarch Attributes. > + > + @param[in] EfiAttributes Efi Attributes. > + > + @retval Corresponding architecture attributes. > +**/ > +UINTN > +EfiAttributeConverse ( > + IN UINTN EfiAttributes > + ) > +{ > + UINTN LoongArchAttributes; > + > + LoongArchAttributes =3D PAGE_VALID | PAGE_DIRTY | PLV_KERNEL | PAGE_GL= OBAL; > + > + switch (EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) { > + case EFI_MEMORY_UC: > + LoongArchAttributes |=3D CACHE_SUC; > + break; > + case EFI_MEMORY_WC: > + case EFI_MEMORY_WT: > + case EFI_MEMORY_WB: > + LoongArchAttributes |=3D CACHE_CC; > + break; > + default: > + LoongArchAttributes |=3D CACHE_CC; > + break; > + } > + > + // Write protection attributes > + if (((EfiAttributes & EFI_MEMORY_RO) !=3D 0) || > + ((EfiAttributes & EFI_MEMORY_WP) !=3D 0)) > + { > + LoongArchAttributes &=3D ~PAGE_DIRTY; > + } > + > + if ((EfiAttributes & EFI_MEMORY_RP) !=3D 0) { > + LoongArchAttributes |=3D PAGE_NO_READ; > + } > + > + // eXecute protection attribute > + if ((EfiAttributes & EFI_MEMORY_XP) !=3D 0) { > + LoongArchAttributes |=3D PAGE_NO_EXEC; > + } > + > + return LoongArchAttributes; > +} > + > +/** > + Finds the length and memory properties of the memory region correspond= ing to the specified base address. > + > + @param[in] BaseAddress To find the base address of the memory regi= on. > + @param[in] EndAddress To find the end address of the memory regio= n. > + @param[out] RegionLength The length of the memory region found. > + @param[out] RegionAttributes Properties of the memory region found= . > + > + @retval EFI_SUCCESS The corresponding memory area was successfully= found > + EFI_NOT_FOUND No memory area found > +**/ > +EFI_STATUS > +GetMemoryRegionAttribute ( > + IN UINTN BaseAddress, > + IN UINTN EndAddress, > + OUT UINTN *RegionLength, > + OUT UINTN *RegionAttributes > + ) > +{ > + PTE *Pte; > + UINTN Attributes; > + UINTN AttributesTmp; > + UINTN MaxAddress; > + > + if (!MmuIsInit ()) { > + return EFI_UNSUPPORTED; > + } > + > + MaxAddress =3D LShiftU64 (1ULL, MAX_VA_BITS) - 1; > + Pte =3D GetPteAddress (BaseAddress); > + > + if (Pte =3D=3D NULL) { > + return EFI_NOT_FOUND; > + } > + > + Attributes =3D GET_PAGE_ATTRIBUTES (*Pte); > + if (IS_HUGE_PAGE (Pte->PteVal)) { > + *RegionAttributes =3D Attributes & (~(PAGE_HUGE)); > + *RegionLength +=3D HUGE_PAGE_SIZE; > + } else { > + *RegionLength +=3D EFI_PAGE_SIZE; > + *RegionAttributes =3D Attributes; > + } > + > + while (BaseAddress <=3D MaxAddress) { > + Pte =3D GetPteAddress (BaseAddress); > + if (Pte =3D=3D NULL) { > + return EFI_SUCCESS; > + } > + > + AttributesTmp =3D GET_PAGE_ATTRIBUTES (*Pte); > + if (IS_HUGE_PAGE (Pte->PteVal)) { > + if (AttributesTmp =3D=3D Attributes) { > + *RegionLength +=3D HUGE_PAGE_SIZE; > + } > + > + BaseAddress +=3D HUGE_PAGE_SIZE; > + } else { > + if (AttributesTmp =3D=3D Attributes) { > + *RegionLength +=3D EFI_PAGE_SIZE; > + } > + > + BaseAddress +=3D EFI_PAGE_SIZE; > + } > + > + if (BaseAddress > EndAddress) { > + break; > + } > + } > + > + return EFI_SUCCESS; > +} > + > +/** > + Sets the Attributes of the specified memory region > + > + @param[in] BaseAddress The base address of the memory region to set = the Attributes. > + @param[in] Length The length of the memory region to set the At= tributes. > + @param[in] Attributes The Attributes to be set. > + > + @retval EFI_SUCCESS The Attributes was set successfully > +**/ > +EFI_STATUS > +SetMemoryRegionAttributes ( > + IN EFI_PHYSICAL_ADDRESS BaseAddress, > + IN UINTN Length, > + IN UINTN Attributes, > + IN UINT64 AttributeMask > + ) > +{ > + if (!MmuIsInit ()) { > + return EFI_UNSUPPORTED; > + } > + > + Attributes =3D EfiAttributeConverse (Attributes); > + MemoryMapPageRange (BaseAddress, BaseAddress + Length, Attributes); > + > + return EFI_SUCCESS; > +} > + > +/** > + Sets the non-executable Attributes for the specified memory region > + > + @param[in] BaseAddress The base address of the memory region to set = the Attributes. > + @param[in] Length The length of the memory region to set the At= tributes. > + > + @retval EFI_SUCCESS The Attributes was set successfully > +**/ > +EFI_STATUS > +SetMemoryRegionNoExec ( > + IN EFI_PHYSICAL_ADDRESS BaseAddress, > + IN UINTN Length > + ) > +{ > + if (MmuIsInit ()) { > + Length =3D EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (Length)); > + SetMemoryRegionAttributes (BaseAddress, Length, EFI_MEMORY_XP, 0x0); > + } > + > + return EFI_SUCCESS; > +} > + > +/** > + Check to see if mmu successfully initializes and saves the result. > + > + @param[in] ImageHandle The firmware allocated handle for the EFI ima= ge. > + @param[in] SystemTable A pointer to the EFI System Table. > + > + @retval RETURN_SUCCESS Initialization succeeded. > +**/ > +RETURN_STATUS > +EFIAPI > +MmuInitialize ( > + IN EFI_HANDLE ImageHandle, > + IN EFI_SYSTEM_TABLE *SystemTable > + ) > +{ > + if (SWAP_PAGE_DIR !=3D 0) { > + mMmuInited =3D TRUE; > + } > + > + return RETURN_SUCCESS; > +} > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /CommonMmuLib.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu= Lib/CommonMmuLib.h > new file mode 100644 > index 0000000000..aa96f5143c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Common= MmuLib.h > @@ -0,0 +1,43 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Dir - Directory > +**/ > + > +#ifndef MMU_LIB_CORE_H_ > +#define MMU_LIB_CORE_H_ > + > +/** > + Iterates through the page directory to initialize it. > + > + @param Dst A pointer to the directory of the page to initialize. > + @param Num The number of page directories to initialize. > + @param Src A pointer to the data used to initialize the page directo= ry. > + > + @retval VOID. > +**/ > +VOID > +PageDirInit ( > + IN VOID *dest, > + IN UINTN Count, > + IN VOID *src > + ); > + > +/** > + Page tables are established from memory-mapped tables. > + > + @param MemoryRegion A pointer to a memory-mapped table entry. > + > + @retval EFI_SUCCESS The page table was created successfully. > + @retval EFI_OUT_OF_RESOURCES Page table establishment failed due= to resource exhaustion. > +**/ > +EFI_STATUS > +FillTranslationTable ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryRegion > + ); > + > +#endif // MMU_LIB_CORE_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /DxeCpuMmuLib.inf b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM= muLib/DxeCpuMmuLib.inf > new file mode 100644 > index 0000000000..d153354dd2 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/DxeCpu= MmuLib.inf > @@ -0,0 +1,37 @@ > +## @file > +# CPU Memory Map Unit DXE phase driver. > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All right= s reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +## > + > +[Defines] > + INF_VERSION =3D 0x00010005 > + BASE_NAME =3D DxeCpuMmuLib > + MODULE_UNI_FILE =3D DxeCpuMmuLib.uni > + FILE_GUID =3D DA8F0232-FB14-42F0-922C-63104D2C70B= E > + MODULE_TYPE =3D DXE_DRIVER > + VERSION_STRING =3D 1.0 > + LIBRARY_CLASS =3D CpuMmuLib | DXE_DRIVER > + CONSTRUCTOR =3D MmuInitialize > + > +# > +# VALID_ARCHITECTURES =3D LOONGARCH64 > +# > + > +[Sources] > + TlbOperation.S | GCC > + CommonMmuLib.c > + Tlb.h > + Page.h > + > +[Packages] > + MdePkg/MdePkg.dec > + UefiCpuPkg/UefiCpuPkg.dec > + > +[LibraryClasses] > + MemoryAllocationLib > + PcdLib > + DebugLib > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /DxeCpuMmuLib.uni b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM= muLib/DxeCpuMmuLib.uni > new file mode 100644 > index 0000000000..2e841d714c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/DxeCpu= MmuLib.uni > @@ -0,0 +1,14 @@ > +// /** @file > +// CPU Memory Manager Unit library instance for DXE modules. > +// > +// CPU Memory Manager Unit library instance for DXE modules. > +// > +// Copyright (c) 2023, Loongson Technology Corporation Limited. All righ= ts reserved.
> +// > +// SPDX-License-Identifier: BSD-2-Clause-Patent > +// > +// **/ > + > +#string STR_MODULE_ABSTRACT #language en-US "CPU Memory Mana= ger Unit library instance for DXE modules." > + > +#string STR_MODULE_DESCRIPTION #language en-US "CPU Memory Mana= ger Unit library instance for DXE modules." > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /Page.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Page= .h > new file mode 100644 > index 0000000000..ad8f751ad7 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Page.h > @@ -0,0 +1,279 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Pgd or Pgd or PGD - Page Global Directory > + - Pud or Pud or PUD - Page Upper Directory > + - Pmd or Pmd or PMD - Page Middle Directory > + - Pte or pte or PTE - Page Table Entry > + - Val or VAL or val - Value > + - Dir - Directory > +**/ > + > +#ifndef PAGE_H_ > +#define PAGE_H_ > + > +#include > + > +#define MAX_VA_BITS 47 > +#define PGD_WIDE (8) > +#define PUD_WIDE (9) > +#define PMD_WIDE (9) > +#define PTE_WIDE (9) > + > +#define ENTRYS_PER_PGD (1 << PGD_WIDE) > +#define ENTRYS_PER_PUD (1 << PUD_WIDE) > +#define ENTRYS_PER_PMD (1 << PMD_WIDE) > +#define ENTRYS_PER_PTE (1 << PTE_WIDE) > + > +#define PGD_SHIFT (PUD_SHIFT + PUD_WIDE) > +#define PUD_SHIFT (PMD_SHIFT + PMD_WIDE) > +#define PMD_SHIFT (EFI_PAGE_SHIFT + PTE_WIDE) > +#define PTE_SHIFT (EFI_PAGE_SHIFT) > + > +#define PGD_SIZE (1UL << PGD_SHIFT) > +#define PUD_SIZE (1UL << PUD_SHIFT) > +#define PMD_SIZE (1UL << PMD_SHIFT) > + > +#define PGD_MASK (~(PGD_SIZE-1)) > +#define PUD_MASK (~(PUD_SIZE-1)) > +#define PMD_MASK (~(PMD_SIZE-1)) > +#define PAGE_MASK (~(EFI_PAGE_SIZE - 1)) > +#define PFN_MASK (~(((UINTN)(1) << (EFI_PAGE_SHIFT)) - 1) & \ > + (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)) > + > +#define HUGEP_PAGE_MASK (~(((UINTN)(1) << (PMD_SHIFT)) - 1) & \ > + (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)) > + > +#define INVALID_PAGE 0 > + > +typedef struct { > + UINTN PgdVal; > +} PGD; > +typedef struct { > + UINTN PudVal; > +} PUD; > +typedef struct { > + UINTN PmdVal; > +} PMD; > +typedef struct { > + UINTN PteVal; > +} PTE; > + > +/** > + Gets the value of the page global directory table entry. > + > + @param x Page global directory struct variables. > + > + @retval the value of the page global directory table entry. > + **/ > +#define PGD_VAL(x) ((x).PgdVal) > + > +/** > + Gets the value of the page upper directory table entry. > + > + @param x Page upper directory struct variables. > + > + @retval the value of the page upper directory table entry. > + **/ > +#define PUD_VAL(x) ((x).PudVal) > + > +/** > + Gets the value of the page middle directory table entry. > + > + @param x Page middle directory struct variables. > + > + @retval the value of the page middle directory table entry. > + **/ > +#define PMD_VAL(x) ((x).PmdVal) > + > +/** > + Gets the value of the page table entry. > + > + @param x Page table entry struct variables. > + > + @retval the value of the page table entry. > + **/ > +#define PTE_VAL(x) ((x).PteVal) > + > +#define PGD_TABLE_SIZE (ENTRYS_PER_PGD * sizeof(PGD)) > +#define PUD_TABLE_SIZE (ENTRYS_PER_PUD * sizeof(PUD)) > +#define PMD_TABLE_SIZE (ENTRYS_PER_PMD * sizeof(PMD)) > +#define PTE_TABLE_SIZE (ENTRYS_PER_PTE * sizeof(PTE)) > + > +/** > + Gets the physical address of the record in the page table entry. > + > + @param x Page table entry struct variables. > + > + @retval the value of the physical address. > + **/ > +#define GET_PAGE_ATTRIBUTES(x) (UINTN) {(PTE_VAL(x) & ~PFN_MASK)} > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the global page directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PGD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PGD_SIZE) & PGD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the page upper directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PUD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PUD_SIZE) & PUD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the page middle directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PMD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PMD_SIZE) & PMD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge global directory table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page global directory table entry. > + **/ > +#define PGD_INDEX(Address) (((Address) >> PGD_SHIFT) & (ENTRYS_PER_PGD-= 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge upper directory table entry. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the index of the page upper directory table entry. > + **/ > +#define PUD_INDEX(Address) (((Address) >> PUD_SHIFT) & (ENTRYS_PER_PUD = - 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge middle directory table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page middle directory table entry. > + **/ > +#define PMD_INDEX(Address) (((Address) >> PMD_SHIFT) & (ENTRYS_PER_PMD = - 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page table entry. > + **/ > +#define PTE_INDEX(Address) (((Address) >> EFI_PAGE_SHIFT) & (ENTRYS_PER= _PTE - 1)) > + > +/** > + Calculates the value of the page table entry based on the specified vi= rtual address and properties. > + > + @param Address Specifies the virtual address. > + @param Attributes Specifies the Attributes. > + > + @retval the value of the page table entry. > + **/ > +#define MAKE_PTE(Address, Attributes) (PTE){((((Address) >> EFI_PAGE_SH= IFT) << 12) | (Attributes))} > + > +/** > + Get Global bit from Attributes > + > + @param Attributes Specifies the Attributes. > + * */ > +#define GET_GLOBALBIT(Attributes) ((Attributes & PAGE_GLOBAL) >> PAGE_G= LOBAL_SHIFT) > + > +/** > + Calculates the value of the Huge page table entry based on the specifi= ed virtual address and properties. > + > + @param Address Specifies the virtual address. > + @param Attributes Specifies the Attributes. > + > + @retval the value of the HUGE page table entry. > + **/ > +#define MAKE_HUGE_PTE(Address, Attributes) (PTE){(((((Address) >> PMD_S= HIFT) << PMD_SHIFT) | \ > + ((Attributes) | (GET_GLOBAL= BIT(Attributes) << PAGE_HGLOBAL_SHIFT) | \ > + PAGE_HUGE)))} > + > +/** > + Check whether the large page table entry is. > + > + @param Val The value of the page table entry. > + > + @retval 1 Is huge page table entry. > + @retval 0 Isn't huge page table entry. > +**/ > +#define IS_HUGE_PAGE(Val) ((((Val) & PAGE_HUGE) =3D=3D PAGE_HUGE) && \ > + (((Val) & PAGE_HGLOBAL) =3D=3D PAGE_HGLOBAL)= ) > + > +#define HUGE_PAGE_SIZE (PMD_SIZE) > + > +/** > + Check that the global page directory table entry is empty. > + > + @param pgd the global page directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PGD_IS_EMPTY(Val) (PGD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page upper directory table entry is empty. > + > + @param pud Page upper directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PUD_IS_EMPTY(Val) (PUD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page middle directory table entry is empty. > + > + @param pmd Page middle directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PMD_IS_EMPTY(Val) (PMD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page the page table entry is empty. > + > + @param pte Page table entry struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PTE_IS_EMPTY(Val) (!(PTE_VAL(Val) & (~PAGE_VALID))) > +#endif // PAGE_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /PeiCpuMmuLib.c b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu= Lib/PeiCpuMmuLib.c > new file mode 100644 > index 0000000000..42a424b84d > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpu= MmuLib.c > @@ -0,0 +1,165 @@ > +/** @file > + CPU Memory Map Unit PEI phase driver. > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Tlb - Translation Lookaside Buffer > +**/ > + > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include > + > +#include "Page.h" > +#include "Tlb.h" > +#include "CommonMmuLib.h" > + > +/** > + Create a page table and initialize the memory management unit(MMU). > + > + @param[in] MemoryTable A pointer to a memory ragion table. > + @param[out] TranslationTableBase A pointer to a translation table ba= se address. > + @param[out] TranslationTableSize A pointer to a translation table ba= se size. > + > + @retval EFI_SUCCESS Configure MMU successfully. > + EFI_INVALID_PARAMETER MemoryTable is NULL. > + EFI_UNSUPPORTED Out of memory space or size not al= igned. > +**/ > +EFI_STATUS > +EFIAPI > +ConfigureMemoryManagementUint ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryTable, > + OUT VOID **TranslationTableBase OPTIONAL, > + OUT UINTN *TranslationTableSize OPTIONAL > + ) > +{ > + PGD *SwapperPageDir; > + UINTN PgdShift; > + UINTN PgdWide; > + UINTN PudShift; > + UINTN PudWide; > + UINTN PmdShift; > + UINTN PmdWide; > + UINTN PteShift; > + UINTN PteWide; > + UINTN Length; > + UINTN TlbReEntry; > + UINTN TlbReEntryOffset; > + RETURN_STATUS Status; > + > + SwapperPageDir =3D NULL; > + PgdShift =3D PGD_SHIFT; > + PgdWide =3D PGD_WIDE; > + PudShift =3D PUD_SHIFT; > + PudWide =3D PUD_WIDE; > + PmdShift =3D PMD_SHIFT; > + PmdWide =3D PMD_WIDE; > + PteShift =3D PTE_SHIFT; > + PteWide =3D PTE_WIDE; > + > + if (MemoryTable =3D=3D NULL) { > + ASSERT (MemoryTable !=3D NULL); > + return EFI_INVALID_PARAMETER; > + } > + > + SwapperPageDir =3D AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE)); > + ZeroMem (SwapperPageDir, PGD_TABLE_SIZE); > + > + if (SwapperPageDir =3D=3D NULL) { > + goto FreeTranslationTable; > + } > + > + CsrWrite (LOONGARCH_CSR_PGDL, (UINTN)SwapperPageDir); > + > + while (MemoryTable->Length !=3D 0) { > + DEBUG (( > + DEBUG_INFO, > + "%a %d VirtualBase %p VirtualEnd %p Attributes %p .\n", > + __func__, > + __LINE__, > + MemoryTable->VirtualBase, > + (MemoryTable->Length + MemoryTable->VirtualBase), > + MemoryTable->Attributes > + )); > + > + Status =3D FillTranslationTable (MemoryTable); > + if (EFI_ERROR (Status)) { > + goto FreeTranslationTable; > + } > + > + MemoryTable++; > + } > + > + // > + // TLB Re-entry address at the end of exception vector, a vector is up= to 512 bytes, > + // so the starting address is: total exception vector size + total int= errupt vector size + base. > + // The total size of TLB handler and exception vector size and interru= pt vector size should not > + // be lager than 64KB. > + // > + Length =3D (UINTN)HandleTlbRefillEnd - (UINTN)HandleTlbRefil= lStart; > + TlbReEntryOffset =3D (MAX_LOONGARCH_EXCEPTION + MAX_LOONGARCH_INTERRUP= T) * 512; > + TlbReEntry =3D PcdGet64 (PcdCpuExceptionVectorBaseAddress) + Tlb= ReEntryOffset; > + if ((TlbReEntryOffset + Length) > SIZE_64KB) { > + goto FreeTranslationTable; > + } > + > + // > + // Make sure TLB refill exception base address alignment is greater th= an or equal to 4KB and valid > + // > + if (TlbReEntry & (SIZE_4KB - 1)) { > + goto FreeTranslationTable; > + } > + > + CopyMem ((VOID *)TlbReEntry, HandleTlbRefillStart, Length); > + InvalidateInstructionCacheRange ((VOID *)(UINTN)HandleTlbRefillStart, = Length); > + > + DEBUG (( > + DEBUG_INFO, > + "%a %d PteShift %d PteWide %d PmdShift %d PmdWide %d PudShift %d Pu= dWide %d PgdShift %d PgdWide %d.\n", > + __func__, > + __LINE__, > + PteShift, > + PteWide, > + PmdShift, > + PmdWide, > + PudShift, > + PudWide, > + PgdShift, > + PgdWide > + )); > + > + // > + // Set the address of TLB refill exception handler > + // > + SetTlbRebaseAddress ((UINTN)TlbReEntry); > + > + // > + // Set page size > + // > + CsrXChg (LOONGARCH_CSR_TLBIDX, (DEFAULT_PAGE_SIZE << CSR_TLBIDX_SIZE),= CSR_TLBIDX_SIZE_MASK); > + CsrWrite (LOONGARCH_CSR_STLBPGSIZE, DEFAULT_PAGE_SIZE); > + CsrXChg (LOONGARCH_CSR_TLBREHI, (DEFAULT_PAGE_SIZE << CSR_TLBREHI_PS_S= HIFT), CSR_TLBREHI_PS); > + > + CsrWrite (LOONGARCH_CSR_PWCTL0, (PteShift | PteWide << 5 | PmdShift <<= 10 | PmdWide << 15 | PudShift << 20 | PudWide << 25)); > + CsrWrite (LOONGARCH_CSR_PWCTL1, (PgdShift | PgdWide << 6)); > + > + DEBUG ((DEBUG_INFO, "%a %d Enable Mmu Start PageBassAddress %p.\n", __= func__, __LINE__, SwapperPageDir)); > + > + return EFI_SUCCESS; > + > +FreeTranslationTable: > + if (SwapperPageDir !=3D NULL) { > + FreePages (SwapperPageDir, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE)); > + } > + > + return EFI_UNSUPPORTED; > +} > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /PeiCpuMmuLib.inf b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM= muLib/PeiCpuMmuLib.inf > new file mode 100644 > index 0000000000..e746c3b1a7 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpu= MmuLib.inf > @@ -0,0 +1,44 @@ > +## @file > +# CPU Memory Map Unit PEI phase driver. > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All right= s reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +## > + > +[Defines] > + INF_VERSION =3D 0x00010005 > + BASE_NAME =3D PeiCpuMmuLib > + MODULE_UNI_FILE =3D PeiCpuMmuLib.uni > + FILE_GUID =3D F67EB983-AC2A-7550-AB69-3BC51A1C895= B > + MODULE_TYPE =3D PEIM > + VERSION_STRING =3D 1.0 > + LIBRARY_CLASS =3D CpuMmuLib | SEC PEIM > + > +# > +# VALID_ARCHITECTURES =3D LOONGARCH64 > +# > + > +[Sources] > + TlbOperation.S | GCC > + PeiCpuMmuLib.c > + CommonMmuLib.c > + CommonMmuLib.h > + Tlb.h > + Page.h > + > +[Packages] > + MdePkg/MdePkg.dec > + MdeModulePkg/MdeModulePkg.dec > + UefiCpuPkg/UefiCpuPkg.dec > + > +[PCD] > + gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask > + gUefiCpuPkgTokenSpaceGuid.PcdCpuExceptionVectorBaseAddress > + > +[LibraryClasses] > + MemoryAllocationLib > + CacheMaintenanceLib > + PcdLib > + DebugLib > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /PeiCpuMmuLib.uni b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM= muLib/PeiCpuMmuLib.uni > new file mode 100644 > index 0000000000..331500543c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpu= MmuLib.uni > @@ -0,0 +1,14 @@ > +// /** @file > +// CPU Memory Manager Unit library instance for PEI modules. > +// > +// CPU Memory Manager Unit library instance for PEI modules. > +// > +// Copyright (c) 2023, Loongson Technology Corporation Limited. All righ= ts reserved.
> +// > +// SPDX-License-Identifier: BSD-2-Clause-Patent > +// > +// **/ > + > +#string STR_MODULE_ABSTRACT #language en-US "CPU Memory Mana= ger Unit library instance for PEI modules." > + > +#string STR_MODULE_DESCRIPTION #language en-US "CPU Memory Mana= ger Unit library instance for PEI modules." > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /Tlb.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Tlb.h > new file mode 100644 > index 0000000000..5d3f80fe34 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Tlb.h > @@ -0,0 +1,48 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > +**/ > + > +#ifndef TLB_H_ > +#define TLB_H_ > + > +/** > + Invalid corresponding TLB entries are based on the address given > + > + @param Address The address corresponding to the invalid page table ent= ry > + > + @retval none > +**/ > +VOID > +InvalidTlb ( > + UINTN Address > + ); > + > +/** > + TLB refill handler start. > + > + @param none > + > + @retval none > +**/ > +VOID > +HandleTlbRefillStart ( > + VOID > + ); > + > +/** > + TLB refill handler end. > + > + @param none > + > + @retval none > +**/ > +VOID > +HandleTlbRefillEnd ( > + VOID > + ); > + > +#endif // TLB_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib= /TlbOperation.S b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu= Lib/TlbOperation.S > new file mode 100644 > index 0000000000..e446f0839c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/TlbOpe= ration.S > @@ -0,0 +1,44 @@ > +#-----------------------------------------------------------------------= ------- > +# > +# TLB operation functions > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +#-----------------------------------------------------------------------= ------ > + > +#include > + > +ASM_GLOBAL ASM_PFX(HandleTlbRefillStart) > +ASM_GLOBAL ASM_PFX(HandleTlbRefillEnd) > +ASM_GLOBAL ASM_PFX(InvalidTlb) > + > +# > +# Refill the page table. > +# @param VOID > +# @retval VOID > +# > +ASM_PFX(HandleTlbRefillStart): > + csrwr $t0, LOONGARCH_CSR_TLBRSAVE > + csrrd $t0, LOONGARCH_CSR_PGD > + lddir $t0, $t0, 3 #Put pud BaseAddress into T0 > + lddir $t0, $t0, 2 #Put pmd BaseAddress into T0 > + lddir $t0, $t0, 1 #Put pte BaseAddress into T0 > + ldpte $t0, 0 > + ldpte $t0, 1 > + tlbfill // refill hi,lo0,lo1 > + csrrd $t0, LOONGARCH_CSR_TLBRSAVE > + ertn > +ASM_PFX(HandleTlbRefillEnd): > + > +# > +# Invalid corresponding TLB entries are based on the address given > +# @param a0 The address corresponding to the invalid page table entry > +# @retval none > +# > +ASM_PFX(InvalidTlb): > + invtlb INVTLB_ADDR_GTRUE_OR_ASID, $zero, $a0 > + jirl $zero, $ra, 0 > + > + .end > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h b/UefiCpuPkg/= Library/LoongArch64CpuMmuLib/Page.h > new file mode 100644 > index 0000000000..ad8f751ad7 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h > @@ -0,0 +1,279 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Pgd or Pgd or PGD - Page Global Directory > + - Pud or Pud or PUD - Page Upper Directory > + - Pmd or Pmd or PMD - Page Middle Directory > + - Pte or pte or PTE - Page Table Entry > + - Val or VAL or val - Value > + - Dir - Directory > +**/ > + > +#ifndef PAGE_H_ > +#define PAGE_H_ > + > +#include > + > +#define MAX_VA_BITS 47 > +#define PGD_WIDE (8) > +#define PUD_WIDE (9) > +#define PMD_WIDE (9) > +#define PTE_WIDE (9) > + > +#define ENTRYS_PER_PGD (1 << PGD_WIDE) > +#define ENTRYS_PER_PUD (1 << PUD_WIDE) > +#define ENTRYS_PER_PMD (1 << PMD_WIDE) > +#define ENTRYS_PER_PTE (1 << PTE_WIDE) > + > +#define PGD_SHIFT (PUD_SHIFT + PUD_WIDE) > +#define PUD_SHIFT (PMD_SHIFT + PMD_WIDE) > +#define PMD_SHIFT (EFI_PAGE_SHIFT + PTE_WIDE) > +#define PTE_SHIFT (EFI_PAGE_SHIFT) > + > +#define PGD_SIZE (1UL << PGD_SHIFT) > +#define PUD_SIZE (1UL << PUD_SHIFT) > +#define PMD_SIZE (1UL << PMD_SHIFT) > + > +#define PGD_MASK (~(PGD_SIZE-1)) > +#define PUD_MASK (~(PUD_SIZE-1)) > +#define PMD_MASK (~(PMD_SIZE-1)) > +#define PAGE_MASK (~(EFI_PAGE_SIZE - 1)) > +#define PFN_MASK (~(((UINTN)(1) << (EFI_PAGE_SHIFT)) - 1) & \ > + (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)) > + > +#define HUGEP_PAGE_MASK (~(((UINTN)(1) << (PMD_SHIFT)) - 1) & \ > + (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)) > + > +#define INVALID_PAGE 0 > + > +typedef struct { > + UINTN PgdVal; > +} PGD; > +typedef struct { > + UINTN PudVal; > +} PUD; > +typedef struct { > + UINTN PmdVal; > +} PMD; > +typedef struct { > + UINTN PteVal; > +} PTE; > + > +/** > + Gets the value of the page global directory table entry. > + > + @param x Page global directory struct variables. > + > + @retval the value of the page global directory table entry. > + **/ > +#define PGD_VAL(x) ((x).PgdVal) > + > +/** > + Gets the value of the page upper directory table entry. > + > + @param x Page upper directory struct variables. > + > + @retval the value of the page upper directory table entry. > + **/ > +#define PUD_VAL(x) ((x).PudVal) > + > +/** > + Gets the value of the page middle directory table entry. > + > + @param x Page middle directory struct variables. > + > + @retval the value of the page middle directory table entry. > + **/ > +#define PMD_VAL(x) ((x).PmdVal) > + > +/** > + Gets the value of the page table entry. > + > + @param x Page table entry struct variables. > + > + @retval the value of the page table entry. > + **/ > +#define PTE_VAL(x) ((x).PteVal) > + > +#define PGD_TABLE_SIZE (ENTRYS_PER_PGD * sizeof(PGD)) > +#define PUD_TABLE_SIZE (ENTRYS_PER_PUD * sizeof(PUD)) > +#define PMD_TABLE_SIZE (ENTRYS_PER_PMD * sizeof(PMD)) > +#define PTE_TABLE_SIZE (ENTRYS_PER_PTE * sizeof(PTE)) > + > +/** > + Gets the physical address of the record in the page table entry. > + > + @param x Page table entry struct variables. > + > + @retval the value of the physical address. > + **/ > +#define GET_PAGE_ATTRIBUTES(x) (UINTN) {(PTE_VAL(x) & ~PFN_MASK)} > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the global page directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PGD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PGD_SIZE) & PGD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the page upper directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PUD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PUD_SIZE) & PUD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Gets the virtual address of the next block of the specified virtual ad= dress > + that is aligned with the size of the page middle directory mapping. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the specified virtual address of the next block. > + **/ > +#define PMD_ADDRESS_END(Address, End) \ > +({ \ > + UINTN Boundary =3D ((Address) + PMD_SIZE) & PMD_MASK; \ > + (Boundary - 1 < (End) - 1)? Boundary: (End); \ > +}) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge global directory table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page global directory table entry. > + **/ > +#define PGD_INDEX(Address) (((Address) >> PGD_SHIFT) & (ENTRYS_PER_PGD-= 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge upper directory table entry. > + > + @param Address Specifies the virtual address. > + @param End The end address of the memory region. > + > + @retval the index of the page upper directory table entry. > + **/ > +#define PUD_INDEX(Address) (((Address) >> PUD_SHIFT) & (ENTRYS_PER_PUD = - 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge middle directory table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page middle directory table entry. > + **/ > +#define PMD_INDEX(Address) (((Address) >> PMD_SHIFT) & (ENTRYS_PER_PMD = - 1)) > + > +/** > + Get Specifies the virtual address corresponding to the index of the pa= ge table entry. > + > + @param Address Specifies the virtual address. > + > + @retval the index of the page table entry. > + **/ > +#define PTE_INDEX(Address) (((Address) >> EFI_PAGE_SHIFT) & (ENTRYS_PER= _PTE - 1)) > + > +/** > + Calculates the value of the page table entry based on the specified vi= rtual address and properties. > + > + @param Address Specifies the virtual address. > + @param Attributes Specifies the Attributes. > + > + @retval the value of the page table entry. > + **/ > +#define MAKE_PTE(Address, Attributes) (PTE){((((Address) >> EFI_PAGE_SH= IFT) << 12) | (Attributes))} > + > +/** > + Get Global bit from Attributes > + > + @param Attributes Specifies the Attributes. > + * */ > +#define GET_GLOBALBIT(Attributes) ((Attributes & PAGE_GLOBAL) >> PAGE_G= LOBAL_SHIFT) > + > +/** > + Calculates the value of the Huge page table entry based on the specifi= ed virtual address and properties. > + > + @param Address Specifies the virtual address. > + @param Attributes Specifies the Attributes. > + > + @retval the value of the HUGE page table entry. > + **/ > +#define MAKE_HUGE_PTE(Address, Attributes) (PTE){(((((Address) >> PMD_S= HIFT) << PMD_SHIFT) | \ > + ((Attributes) | (GET_GLOBAL= BIT(Attributes) << PAGE_HGLOBAL_SHIFT) | \ > + PAGE_HUGE)))} > + > +/** > + Check whether the large page table entry is. > + > + @param Val The value of the page table entry. > + > + @retval 1 Is huge page table entry. > + @retval 0 Isn't huge page table entry. > +**/ > +#define IS_HUGE_PAGE(Val) ((((Val) & PAGE_HUGE) =3D=3D PAGE_HUGE) && \ > + (((Val) & PAGE_HGLOBAL) =3D=3D PAGE_HGLOBAL)= ) > + > +#define HUGE_PAGE_SIZE (PMD_SIZE) > + > +/** > + Check that the global page directory table entry is empty. > + > + @param pgd the global page directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PGD_IS_EMPTY(Val) (PGD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page upper directory table entry is empty. > + > + @param pud Page upper directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PUD_IS_EMPTY(Val) (PUD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page middle directory table entry is empty. > + > + @param pmd Page middle directory struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PMD_IS_EMPTY(Val) (PMD_VAL(Val) =3D=3D INVALID_PAGE) > + > +/** > + Check that the page the page table entry is empty. > + > + @param pte Page table entry struct variables. > + > + @retval 1 The page table is invalid. > + @retval 0 The page table is valid. > +**/ > +#define PTE_IS_EMPTY(Val) (!(PTE_VAL(Val) & (~PAGE_VALID))) > +#endif // PAGE_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c b/Uef= iCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c > new file mode 100644 > index 0000000000..42a424b84d > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c > @@ -0,0 +1,165 @@ > +/** @file > + CPU Memory Map Unit PEI phase driver. > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > + @par Glossary: > + - Tlb - Translation Lookaside Buffer > +**/ > + > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include > +#include > + > +#include "Page.h" > +#include "Tlb.h" > +#include "CommonMmuLib.h" > + > +/** > + Create a page table and initialize the memory management unit(MMU). > + > + @param[in] MemoryTable A pointer to a memory ragion table. > + @param[out] TranslationTableBase A pointer to a translation table ba= se address. > + @param[out] TranslationTableSize A pointer to a translation table ba= se size. > + > + @retval EFI_SUCCESS Configure MMU successfully. > + EFI_INVALID_PARAMETER MemoryTable is NULL. > + EFI_UNSUPPORTED Out of memory space or size not al= igned. > +**/ > +EFI_STATUS > +EFIAPI > +ConfigureMemoryManagementUint ( > + IN MEMORY_REGION_DESCRIPTOR *MemoryTable, > + OUT VOID **TranslationTableBase OPTIONAL, > + OUT UINTN *TranslationTableSize OPTIONAL > + ) > +{ > + PGD *SwapperPageDir; > + UINTN PgdShift; > + UINTN PgdWide; > + UINTN PudShift; > + UINTN PudWide; > + UINTN PmdShift; > + UINTN PmdWide; > + UINTN PteShift; > + UINTN PteWide; > + UINTN Length; > + UINTN TlbReEntry; > + UINTN TlbReEntryOffset; > + RETURN_STATUS Status; > + > + SwapperPageDir =3D NULL; > + PgdShift =3D PGD_SHIFT; > + PgdWide =3D PGD_WIDE; > + PudShift =3D PUD_SHIFT; > + PudWide =3D PUD_WIDE; > + PmdShift =3D PMD_SHIFT; > + PmdWide =3D PMD_WIDE; > + PteShift =3D PTE_SHIFT; > + PteWide =3D PTE_WIDE; > + > + if (MemoryTable =3D=3D NULL) { > + ASSERT (MemoryTable !=3D NULL); > + return EFI_INVALID_PARAMETER; > + } > + > + SwapperPageDir =3D AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE)); > + ZeroMem (SwapperPageDir, PGD_TABLE_SIZE); > + > + if (SwapperPageDir =3D=3D NULL) { > + goto FreeTranslationTable; > + } > + > + CsrWrite (LOONGARCH_CSR_PGDL, (UINTN)SwapperPageDir); > + > + while (MemoryTable->Length !=3D 0) { > + DEBUG (( > + DEBUG_INFO, > + "%a %d VirtualBase %p VirtualEnd %p Attributes %p .\n", > + __func__, > + __LINE__, > + MemoryTable->VirtualBase, > + (MemoryTable->Length + MemoryTable->VirtualBase), > + MemoryTable->Attributes > + )); > + > + Status =3D FillTranslationTable (MemoryTable); > + if (EFI_ERROR (Status)) { > + goto FreeTranslationTable; > + } > + > + MemoryTable++; > + } > + > + // > + // TLB Re-entry address at the end of exception vector, a vector is up= to 512 bytes, > + // so the starting address is: total exception vector size + total int= errupt vector size + base. > + // The total size of TLB handler and exception vector size and interru= pt vector size should not > + // be lager than 64KB. > + // > + Length =3D (UINTN)HandleTlbRefillEnd - (UINTN)HandleTlbRefil= lStart; > + TlbReEntryOffset =3D (MAX_LOONGARCH_EXCEPTION + MAX_LOONGARCH_INTERRUP= T) * 512; > + TlbReEntry =3D PcdGet64 (PcdCpuExceptionVectorBaseAddress) + Tlb= ReEntryOffset; > + if ((TlbReEntryOffset + Length) > SIZE_64KB) { > + goto FreeTranslationTable; > + } > + > + // > + // Make sure TLB refill exception base address alignment is greater th= an or equal to 4KB and valid > + // > + if (TlbReEntry & (SIZE_4KB - 1)) { > + goto FreeTranslationTable; > + } > + > + CopyMem ((VOID *)TlbReEntry, HandleTlbRefillStart, Length); > + InvalidateInstructionCacheRange ((VOID *)(UINTN)HandleTlbRefillStart, = Length); > + > + DEBUG (( > + DEBUG_INFO, > + "%a %d PteShift %d PteWide %d PmdShift %d PmdWide %d PudShift %d Pu= dWide %d PgdShift %d PgdWide %d.\n", > + __func__, > + __LINE__, > + PteShift, > + PteWide, > + PmdShift, > + PmdWide, > + PudShift, > + PudWide, > + PgdShift, > + PgdWide > + )); > + > + // > + // Set the address of TLB refill exception handler > + // > + SetTlbRebaseAddress ((UINTN)TlbReEntry); > + > + // > + // Set page size > + // > + CsrXChg (LOONGARCH_CSR_TLBIDX, (DEFAULT_PAGE_SIZE << CSR_TLBIDX_SIZE),= CSR_TLBIDX_SIZE_MASK); > + CsrWrite (LOONGARCH_CSR_STLBPGSIZE, DEFAULT_PAGE_SIZE); > + CsrXChg (LOONGARCH_CSR_TLBREHI, (DEFAULT_PAGE_SIZE << CSR_TLBREHI_PS_S= HIFT), CSR_TLBREHI_PS); > + > + CsrWrite (LOONGARCH_CSR_PWCTL0, (PteShift | PteWide << 5 | PmdShift <<= 10 | PmdWide << 15 | PudShift << 20 | PudWide << 25)); > + CsrWrite (LOONGARCH_CSR_PWCTL1, (PgdShift | PgdWide << 6)); > + > + DEBUG ((DEBUG_INFO, "%a %d Enable Mmu Start PageBassAddress %p.\n", __= func__, __LINE__, SwapperPageDir)); > + > + return EFI_SUCCESS; > + > +FreeTranslationTable: > + if (SwapperPageDir !=3D NULL) { > + FreePages (SwapperPageDir, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE)); > + } > + > + return EFI_UNSUPPORTED; > +} > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf b/U= efiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf > new file mode 100644 > index 0000000000..e746c3b1a7 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf > @@ -0,0 +1,44 @@ > +## @file > +# CPU Memory Map Unit PEI phase driver. > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All right= s reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +## > + > +[Defines] > + INF_VERSION =3D 0x00010005 > + BASE_NAME =3D PeiCpuMmuLib > + MODULE_UNI_FILE =3D PeiCpuMmuLib.uni > + FILE_GUID =3D F67EB983-AC2A-7550-AB69-3BC51A1C895= B > + MODULE_TYPE =3D PEIM > + VERSION_STRING =3D 1.0 > + LIBRARY_CLASS =3D CpuMmuLib | SEC PEIM > + > +# > +# VALID_ARCHITECTURES =3D LOONGARCH64 > +# > + > +[Sources] > + TlbOperation.S | GCC > + PeiCpuMmuLib.c > + CommonMmuLib.c > + CommonMmuLib.h > + Tlb.h > + Page.h > + > +[Packages] > + MdePkg/MdePkg.dec > + MdeModulePkg/MdeModulePkg.dec > + UefiCpuPkg/UefiCpuPkg.dec > + > +[PCD] > + gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask > + gUefiCpuPkgTokenSpaceGuid.PcdCpuExceptionVectorBaseAddress > + > +[LibraryClasses] > + MemoryAllocationLib > + CacheMaintenanceLib > + PcdLib > + DebugLib > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni b/U= efiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni > new file mode 100644 > index 0000000000..331500543c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni > @@ -0,0 +1,14 @@ > +// /** @file > +// CPU Memory Manager Unit library instance for PEI modules. > +// > +// CPU Memory Manager Unit library instance for PEI modules. > +// > +// Copyright (c) 2023, Loongson Technology Corporation Limited. All righ= ts reserved.
> +// > +// SPDX-License-Identifier: BSD-2-Clause-Patent > +// > +// **/ > + > +#string STR_MODULE_ABSTRACT #language en-US "CPU Memory Mana= ger Unit library instance for PEI modules." > + > +#string STR_MODULE_DESCRIPTION #language en-US "CPU Memory Mana= ger Unit library instance for PEI modules." > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h b/UefiCpuPkg/L= ibrary/LoongArch64CpuMmuLib/Tlb.h > new file mode 100644 > index 0000000000..5d3f80fe34 > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h > @@ -0,0 +1,48 @@ > +/** @file > + > + Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> + > + SPDX-License-Identifier: BSD-2-Clause-Patent > + > +**/ > + > +#ifndef TLB_H_ > +#define TLB_H_ > + > +/** > + Invalid corresponding TLB entries are based on the address given > + > + @param Address The address corresponding to the invalid page table ent= ry > + > + @retval none > +**/ > +VOID > +InvalidTlb ( > + UINTN Address > + ); > + > +/** > + TLB refill handler start. > + > + @param none > + > + @retval none > +**/ > +VOID > +HandleTlbRefillStart ( > + VOID > + ); > + > +/** > + TLB refill handler end. > + > + @param none > + > + @retval none > +**/ > +VOID > +HandleTlbRefillEnd ( > + VOID > + ); > + > +#endif // TLB_H_ > diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S b/Uef= iCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S > new file mode 100644 > index 0000000000..e446f0839c > --- /dev/null > +++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S > @@ -0,0 +1,44 @@ > +#-----------------------------------------------------------------------= ------- > +# > +# TLB operation functions > +# > +# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights= reserved.
> +# > +# SPDX-License-Identifier: BSD-2-Clause-Patent > +# > +#-----------------------------------------------------------------------= ------ > + > +#include > + > +ASM_GLOBAL ASM_PFX(HandleTlbRefillStart) > +ASM_GLOBAL ASM_PFX(HandleTlbRefillEnd) > +ASM_GLOBAL ASM_PFX(InvalidTlb) > + > +# > +# Refill the page table. > +# @param VOID > +# @retval VOID > +# > +ASM_PFX(HandleTlbRefillStart): > + csrwr $t0, LOONGARCH_CSR_TLBRSAVE > + csrrd $t0, LOONGARCH_CSR_PGD > + lddir $t0, $t0, 3 #Put pud BaseAddress into T0 > + lddir $t0, $t0, 2 #Put pmd BaseAddress into T0 > + lddir $t0, $t0, 1 #Put pte BaseAddress into T0 > + ldpte $t0, 0 > + ldpte $t0, 1 > + tlbfill // refill hi,lo0,lo1 > + csrrd $t0, LOONGARCH_CSR_TLBRSAVE > + ertn > +ASM_PFX(HandleTlbRefillEnd): > + > +# > +# Invalid corresponding TLB entries are based on the address given > +# @param a0 The address corresponding to the invalid page table entry > +# @retval none > +# > +ASM_PFX(InvalidTlb): > + invtlb INVTLB_ADDR_GTRUE_OR_ASID, $zero, $a0 > + jirl $zero, $ra, 0 > + > + .end > diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc > index 872f20fc36..709992d327 100644 > --- a/UefiCpuPkg/UefiCpuPkg.dsc > +++ b/UefiCpuPkg/UefiCpuPkg.dsc > @@ -209,6 +209,8 @@ > UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimer= Lib.inf > UefiCpuPkg/Library/LoongArch64CpuExceptionHandlerLib/SecPeiCpuExcepti= onHandlerLib.inf > UefiCpuPkg/Library/LoongArch64CpuExceptionHandlerLib/DxeCpuExceptionH= andlerLib.inf > + UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf > + UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf > =20 > [BuildOptions] > *_*_*_CC_FLAGS =3D -D DISABLE_NEW_DEPRECATED_INTERFACES -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- Groups.io Links: You receive all messages sent to this group. View/Reply Online (#111465): https://edk2.groups.io/g/devel/message/111465 Mute This Topic: https://groups.io/mt/102644769/7686176 Group Owner: devel+owner@edk2.groups.io Unsubscribe: https://edk2.groups.io/g/devel/unsub [rebecca@openfw.io] -=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D-=3D- --------------RDvPmkobGmCJvBi0hVDVbomp Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable

This patch includes two folder, both named LoongArch64CpuMmuLib. This was a mistak when creating the patch, I will fix it in the V4.


=
Thanks,
Chao
On 2023/11/17 18:00, Chao Li wrote:
Add a new library LoongArch64C=
puMmuLib. It provides two-stage MMU library
instances, PEI and DXE.

BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=
=3D4584

Cc: Eric Dong <eric.dong@intel.com>
Cc: Ray Ni <ray.ni@intel.com>
Cc: Rahul Kumar <rahul1.kumar@intel.com>
Cc: Gerd Hoffmann <kraxel@redhat.com>
Signed-off-by: Chao Li <lichao@loongson.cn>
Co-authored-by: Baoqi Zhang <zhangbaoqi@loongson.cn>
Co-authored-by: Dongyan Qian <qiandongyan@loongson.cn>
Co-authored-by: Xianglai Li <lixianglai@loongson.cn>
Co-authored-by: Bibo Mao <maobibo@loongson.cn>
---
 .../LoongArch64CpuMmuLib/CommonMmuLib.c       | 965 ++++++++++++++++++
 .../LoongArch64CpuMmuLib/CommonMmuLib.h       |  43 +
 .../LoongArch64CpuMmuLib/DxeCpuMmuLib.inf     |  37 +
 .../LoongArch64CpuMmuLib/DxeCpuMmuLib.uni     |  14 +
 .../LoongArch64CpuMmuLib/CommonMmuLib.c       | 964 +++++++++++++++++
 .../LoongArch64CpuMmuLib/CommonMmuLib.h       |  43 +
 .../LoongArch64CpuMmuLib/DxeCpuMmuLib.inf     |  37 +
 .../LoongArch64CpuMmuLib/DxeCpuMmuLib.uni     |  14 +
 .../LoongArch64CpuMmuLib/Page.h               | 279 +++++
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.c       | 165 +++
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.inf     |  44 +
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.uni     |  14 +
 .../LoongArch64CpuMmuLib/Tlb.h                |  48 +
 .../LoongArch64CpuMmuLib/TlbOperation.S       |  44 +
 .../Library/LoongArch64CpuMmuLib/Page.h       | 279 +++++
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.c       | 165 +++
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.inf     |  44 +
 .../LoongArch64CpuMmuLib/PeiCpuMmuLib.uni     |  14 +
 UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h |  48 +
 .../LoongArch64CpuMmuLib/TlbOperation.S       |  44 +
 UefiCpuPkg/UefiCpuPkg.dsc                     |   2 +
 21 files changed, 3307 insertions(+)
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.in=
f
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.un=
i
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/CommonMmuLib.c
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/CommonMmuLib.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/DxeCpuMmuLib.inf
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/DxeCpuMmuLib.uni
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/Page.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/PeiCpuMmuLib.c
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/PeiCpuMmuLib.inf
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/PeiCpuMmuLib.uni
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/Tlb.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuM=
muLib/TlbOperation.S
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.in=
f
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.un=
i
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h
 create mode 100644 UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S

diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c b/UefiC=
puPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c
new file mode 100644
index 0000000000..bd5c7e55b6
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.c
@@ -0,0 +1,965 @@
+/** @file
+
+  CPU Memory Map Unit Handler Library common functions.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Pgd or Pgd or PGD    - Page Global Directory
+    - Pud or Pud or PUD    - Page Upper Directory
+    - Pmd or Pmd or PMD    - Page Middle Directory
+    - Pte or pte or PTE    - Page Table Entry
+    - Val or VAL or val    - Value
+    - Dir    - Directory
+**/
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Register/LoongArch64/Csr.h>
+#include "Tlb.h"
+#include "Page.h"
+
+BOOLEAN  mMmuInited =3D FALSE;
+#define  SWAP_PAGE_DIR  CsrRead(LOONGARCH_CSR_PGDL)
+
+/**
+  Check to see if mmu successfully initializes.
+
+  @param  VOID.
+
+  @retval  TRUE  Initialization has been completed.
+           FALSE Initialization did not complete.
+**/
+BOOLEAN
+MmuIsInit (
+  VOID
+  )
+{
+  if (mMmuInited || (SWAP_PAGE_DIR !=3D 0)) {
+    return TRUE;
+  }
+
+  return FALSE;
+}
+
+/**
+  Iterates through the page directory to initialize it.
+
+  @param  Dst  A pointer to the directory of the page to initialize.
+  @param  Num  The number of page directories to initialize.
+  @param  Src  A pointer to the data used to initialize the page directory=
.
+
+  @return VOID.
+**/
+VOID
+PageDirInit (
+  IN VOID   *Dst,
+  IN UINTN  Num,
+  IN VOID   *Src
+  )
+{
+  UINTN  *Ptr;
+  UINTN  *End;
+  UINTN  Entry;
+
+  Entry =3D (UINTN)Src;
+  Ptr   =3D (UINTN *)Dst;
+  End   =3D Ptr + Num;
+
+  for ( ; Ptr < End; Ptr++) {
+    *Ptr =3D Entry;
+  }
+
+  return;
+}
+
+/**
+  Gets the virtual address corresponding to the page global directory tabl=
e entry.
+
+  @param  Address  the virtual address for the table entry.
+
+  @retval PGD A pointer to get the table item.
+**/
+PGD *
+PgdOffset (
+  IN UINTN  Address
+  )
+{
+  return (PGD *)(SWAP_PAGE_DIR) + PGD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page upper directory table=
 entry.
+
+  @param  Pgd  A pointer to a page global directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PUD A pointer to get the table item.
+**/
+PUD *
+PudOffset (
+  IN PGD    *Pgd,
+  IN UINTN  Address
+  )
+{
+  UINTN  PgdVal;
+
+  PgdVal =3D (UINTN)PGD_VAL (*Pgd);
+
+  return (PUD *)PgdVal + PUD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page middle directory tabl=
e entry.
+
+  @param  Pud  A pointer to a page upper directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PMD A pointer to get the table item.
+**/
+PMD *
+PmdOffset (
+  IN PUD    *Pud,
+  IN UINTN  Address
+  )
+{
+  UINTN  PudVal;
+
+  PudVal =3D PUD_VAL (*Pud);
+
+  return (PMD *)PudVal + PMD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page table entry.
+
+  @param  Pmd  A pointer to a page middle directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PTE A pointer to get the table item.
+**/
+PTE *
+PteOffset (
+  IN PMD    *Pmd,
+  IN UINTN  Address
+  )
+{
+  UINTN  PmdVal;
+
+  PmdVal =3D (UINTN)PMD_VAL (*Pmd);
+
+  return (PTE *)PmdVal + PTE_INDEX (Address);
+}
+
+/**
+  Sets the value of the page table entry.
+
+  @param  Pte  A pointer to a page table entry.
+  @param  PteVal  The value of the page table entry to set.
+
+**/
+VOID
+SetPte (
+  IN PTE  *Pte,
+  IN PTE  PteVal
+  )
+{
+  *Pte =3D PteVal;
+}
+
+/**
+  Sets the value of the page global directory.
+
+  @param  Pgd  A pointer to a page global directory.
+  @param  Pud  The value of the page global directory to set.
+
+**/
+VOID
+SetPgd (
+  IN PGD  *Pgd,
+  IN PUD  *Pud
+  )
+{
+  *Pgd =3D (PGD) {
+    ((UINTN)Pud)
+  };
+}
+
+/**
+  Sets the value of the page upper directory.
+
+  @param  Pud  A pointer to a page upper directory.
+  @param  Pmd  The value of the page upper directory to set.
+
+**/
+VOID
+SetPud (
+  IN PUD  *Pud,
+  IN PMD  *Pmd
+  )
+{
+  *Pud =3D (PUD) {
+    ((UINTN)Pmd)
+  };
+}
+
+/**
+  Sets the value of the page middle directory.
+
+  @param  Pmd  A pointer to a page middle directory.
+  @param  Pte  The value of the page middle directory to set.
+
+**/
+VOID
+SetPmd (
+  IN PMD  *Pmd,
+  IN PTE  *Pte
+  )
+{
+  *Pmd =3D (PMD) {
+    ((UINTN)Pte)
+  };
+}
+
+/**
+  Free up memory space occupied by page tables.
+
+  @param  Pte  A pointer to the page table.
+
+**/
+VOID
+PteFree (
+  IN PTE  *Pte
+  )
+{
+  FreePages ((VOID *)Pte, 1);
+}
+
+/**
+  Free up memory space occupied by page middle directory.
+
+  @param  Pmd  A pointer to the page middle directory.
+
+**/
+VOID
+PmdFree (
+  IN PMD  *Pmd
+  )
+{
+  FreePages ((VOID *)Pmd, 1);
+}
+
+/**
+  Free up memory space occupied by page upper directory.
+
+  @param  Pud  A pointer to the page upper directory.
+
+**/
+VOID
+PudFree (
+  IN PUD  *Pud
+  )
+{
+  FreePages ((VOID *)Pud, 1);
+}
+
+/**
+  Requests the memory space required for the page upper directory,
+  initializes it, and places it in the specified page global directory
+
+  @param  Pgd  A pointer to the page global directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PudAlloc (
+  IN PGD  *Pgd
+  )
+{
+  PUD  *Pud;
+
+  Pud =3D (PUD *)AllocatePages (1);
+  if (Pud =3D=3D NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  PageDirInit ((VOID *)Pud, ENTRYS_PER_PUD, (VOID *)INVALID_PAGE);
+
+  SetPgd (Pgd, Pud);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page middle directory,
+  initializes it, and places it in the specified page upper directory
+
+  @param  Pud  A pointer to the page upper directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PmdAlloc (
+  IN PUD  *Pud
+  )
+{
+  PMD  *Pmd;
+
+  Pmd =3D (PMD *)AllocatePages (1);
+  if (!Pmd) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  PageDirInit ((VOID *)Pmd, ENTRYS_PER_PMD, (VOID *)INVALID_PAGE);
+
+  SetPud (Pud, Pmd);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page table,
+  initializes it, and places it in the specified page middle directory
+
+  @param  Pmd  A pointer to the page middle directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PteAlloc (
+  IN PMD  *Pmd
+  )
+{
+  PTE  *Pte;
+
+  Pte =3D (PTE *)AllocatePages (1);
+  if (!Pte) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  Pte =3D ZeroMem (Pte, EFI_PAGE_SIZE);
+
+  SetPmd (Pmd, Pte);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page upper directory,
+  initializes it, and places it in the specified page global directory,
+  and get the page upper directory entry corresponding to the virtual addr=
ess.
+
+  @param  Pgd      A pointer to the page global directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page upper directory entry. Return NUL=
L, if
+                   allocate the memory buffer is fail.
+**/
+PUD *
+PudAllocGet (
+  IN PGD    *Pgd,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PGD_IS_EMPTY (*Pgd)) {
+    Status =3D PudAlloc (Pgd);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PudOffset (Pgd, Address);
+}
+
+/**
+  Requests the memory space required for the page middle directory,
+  initializes it, and places it in the specified page upper directory,
+  and get the page middle directory entry corresponding to the virtual add=
ress.
+
+  @param  Pud      A pointer to the page upper directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page middle directory entry. Return NU=
LL, if
+                   allocate the memory buffer is fail.
+**/
+PMD *
+PmdAllocGet (
+  IN PUD    *Pud,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PUD_IS_EMPTY (*Pud)) {
+    Status =3D PmdAlloc (Pud);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PmdOffset (Pud, Address);
+}
+
+/**
+  Requests the memory space required for the page table,
+  initializes it, and places it in the specified page middle directory,
+  and get the page table entry corresponding to the virtual address.
+
+  @param  Pmd      A pointer to the page upper directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page table entry. Return NULL, if allo=
cate
+                   the memory buffer is fail.
+**/
+PTE *
+PteAllocGet (
+  IN PMD    *Pmd,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PMD_IS_EMPTY (*Pmd)) {
+    Status =3D PteAlloc (Pmd);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PteOffset (Pmd, Address);
+}
+
+/**
+  Gets the physical address of the page table entry corresponding to the s=
pecified virtual address.
+
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval  A pointer to the page table entry.
+  @retval  NULL
+**/
+PTE *
+GetPteAddress (
+  IN UINTN  Address
+  )
+{
+  PGD  *Pgd;
+  PUD  *Pud;
+  PMD  *Pmd;
+
+  Pgd =3D PgdOffset (Address);
+
+  if (PGD_IS_EMPTY (*Pgd)) {
+    return NULL;
+  }
+
+  Pud =3D PudOffset (Pgd, Address);
+
+  if (PUD_IS_EMPTY (*Pud)) {
+    return NULL;
+  }
+
+  Pmd =3D PmdOffset (Pud, Address);
+  if (PMD_IS_EMPTY (*Pmd)) {
+    return NULL;
+  }
+
+  if (IS_HUGE_PAGE (Pmd->PmdVal)) {
+    return ((PTE *)Pmd);
+  }
+
+  return PteOffset (Pmd, Address);
+}
+
+/**
+  Gets the Attributes of Huge Page.
+
+  @param  Pmd  A pointer to the page middle directory.
+
+  @retval     Value of Attributes.
+**/
+UINTN
+GetHugePageAttributes (
+  IN  PMD  *Pmd
+  )
+{
+  UINTN  Attributes;
+  UINTN  GlobalFlag;
+  UINTN  HugeVal;
+
+  HugeVal     =3D PMD_VAL (*Pmd);
+  Attributes  =3D HugeVal & (~HUGEP_PAGE_MASK);
+  GlobalFlag  =3D ((Attributes & (1 << PAGE_HGLOBAL_SHIFT)) >=
> PAGE_HGLOBAL_SHIFT) << PAGE_GLOBAL_SHIFT;
+  Attributes &=3D ~(1 << PAGE_HGLOBAL_SHIFT);
+  Attributes |=3D GlobalFlag;
+  return Attributes;
+}
+
+/**
+  Establishes a page table entry based on the specified memory region.
+
+  @param  Pmd  A pointer to the page middle directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page table entry was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table entry establishment failed =
due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPteRange (
+  IN PMD    *Pmd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PTE      *Pte;
+  PTE      PteVal;
+  BOOLEAN  UpDate;
+
+  Pte =3D PteAllocGet (Pmd, Address);
+  if (!Pte) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  DEBUG ((
+    DEBUG_INFO,
+    "%a %d Address %p End %p  Attributes %llx\n",
+    __func__,
+    __LINE__,
+    Address,
+    End,
+    Attributes
+    ));
+
+  do {
+    UpDate =3D FALSE;
+    PteVal =3D MAKE_PTE (Address, Attributes);
+
+    if ((!PTE_IS_EMPTY (*Pte)) &&
+        (PTE_VAL (*Pte) !=3D PTE_VAL (PteVal)))
+    {
+      UpDate =3D TRUE;
+    }
+
+    SetPte (Pte, PteVal);
+    if (UpDate) {
+      InvalidTlb (Address);
+    }
+  } while (Pte++, Address +=3D EFI_PAGE_SIZE, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Convert Huge Page to Page.
+
+  @param  Pmd  A pointer to the page middle directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval  EFI_SUCCESS   The page table entry was created successfully.
+  @retval  EFI_OUT_OF_RESOURCES  Page table entry establishment failed due=
 to resource exhaustion.
+**/
+EFI_STATUS
+ConvertHugePageToPage (
+  IN  PMD   *Pmd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  UINTN       OldAttributes;
+  UINTN       HugePageEnd;
+  UINTN       HugePageStart;
+  EFI_STATUS  Status;
+
+  Status =3D EFI_SUCCESS;
+
+  if ((PMD_IS_EMPTY (*Pmd)) ||
+      (!IS_HUGE_PAGE (Pmd->PmdVal)))
+  {
+    Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes);
+  } else {
+    OldAttributes =3D GetHugePageAttributes (Pmd);
+    if (Attributes =3D=3D OldAttributes) {
+      return Status;
+    }
+
+    SetPmd (Pmd, (PTE *)(INVALID_PAGE));
+    HugePageStart =3D Address & PMD_MASK;
+    HugePageEnd   =3D HugePageStart + HUGE_PAGE_SIZE;
+    ASSERT (HugePageEnd >=3D End);
+
+    if (Address > HugePageStart) {
+      Status |=3D MemoryMapPteRange (Pmd, HugePageStart, Address, OldAttri=
butes);
+    }
+
+    Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes);
+
+    if (End < HugePageEnd) {
+      Status |=3D MemoryMapPteRange (Pmd, End, HugePageEnd, OldAttributes)=
;
+    }
+  }
+
+  return Status;
+}
+
+/**
+  Establishes a page middle directory based on the specified memory region=
.
+
+  @param  Pud  A pointer to the page upper directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page middle directory was created successf=
ully.
+  @retval     EFI_OUT_OF_RESOURCES  Page middle directory establishment fa=
iled due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPmdRange (
+  IN PUD    *Pud,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PMD      *Pmd;
+  UINTN    Next;
+  PTE      PteVal;
+  BOOLEAN  UpDate;
+
+  Pmd =3D PmdAllocGet (Pud, Address);
+  if (!Pmd) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  do {
+    Next =3D PMD_ADDRESS_END (Address, End);
+    if (((Address & (~PMD_MASK)) =3D=3D 0) &&
+        ((Next &  (~PMD_MASK)) =3D=3D 0) &&
+        (PMD_IS_EMPTY (*Pmd) || IS_HUGE_PAGE (Pmd->PmdVal)))
+    {
+      UpDate =3D FALSE;
+      PteVal =3D MAKE_HUGE_PTE (Address, Attributes);
+
+      if ((!PMD_IS_EMPTY (*Pmd)) &&
+          (PMD_VAL (*Pmd) !=3D PTE_VAL (PteVal)))
+      {
+        UpDate =3D TRUE;
+      }
+
+      SetPmd (Pmd, (PTE *)PteVal.PteVal);
+      if (UpDate) {
+        InvalidTlb (Address);
+      }
+    } else {
+      ConvertHugePageToPage (Pmd, Address, Next, Attributes);
+    }
+  } while (Pmd++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Establishes a page upper directory based on the specified memory region.
+
+  @param  Pgd  A pointer to the page global directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page upper directory was created successfu=
lly.
+  @retval     EFI_OUT_OF_RESOURCES  Page upper directory establishment fai=
led due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPudRange (
+  IN PGD    *Pgd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PUD    *Pud;
+  UINTN  Next;
+
+  Pud =3D PudAllocGet (Pgd, Address);
+  if (!Pud) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  do {
+    Next =3D PUD_ADDRESS_END (Address, End);
+    if (EFI_ERROR (MemoryMapPmdRange (Pud, Address, Next, Attributes))) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+  } while (Pud++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Establishes a page global directory based on the specified memory region=
.
+
+  @param  Start  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page global directory was created successf=
ully.
+  @retval     EFI_OUT_OF_RESOURCES  Page global directory establishment fa=
iled due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPageRange (
+  IN UINTN  Start,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PGD         *Pgd;
+  UINTN       Next;
+  UINTN       Address;
+  EFI_STATUS  Err;
+
+  Address =3D Start;
+
+  /* Get PGD(PTE PMD PUD PGD) in PageTables */
+  Pgd =3D PgdOffset (Address);
+  do {
+    Next =3D PGD_ADDRESS_END (Address, End);
+    /* Get Next Align Page to Map */
+    Err =3D MemoryMapPudRange (Pgd, Address, Next, Attributes);
+    if (Err) {
+      return Err;
+    }
+  } while (Pgd++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Page tables are established from memory-mapped tables.
+
+  @param  MemoryRegion   A pointer to a memory-mapped table entry.
+
+  @retval     EFI_SUCCESS   The page table was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table  establishment failed due t=
o resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryRegion
+  )
+{
+  return MemoryMapPageRange (
+           MemoryRegion->VirtualBase,
+           (MemoryRegion->Length + MemoryRegion->VirtualBase),
+           MemoryRegion->Attributes
+           );
+}
+
+/**
+  Convert EFI Attributes to Loongarch Attributes.
+
+  @param[in]  EfiAttributes     Efi Attributes.
+
+  @retval  Corresponding architecture attributes.
+**/
+UINTN
+EfiAttributeConverse (
+  IN UINTN  EfiAttributes
+  )
+{
+  UINTN  LoongArchAttributes;
+
+  LoongArchAttributes =3D PAGE_VALID | PAGE_DIRTY | PLV_KERNEL | PAGE_GLOB=
AL;
+
+  switch (EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) {
+    case EFI_MEMORY_UC:
+      LoongArchAttributes |=3D CACHE_SUC;
+      break;
+    case EFI_MEMORY_WC:
+    case EFI_MEMORY_WT:
+    case EFI_MEMORY_WB:
+      LoongArchAttributes |=3D CACHE_CC;
+      break;
+    default:
+      LoongArchAttributes |=3D CACHE_CC;
+      break;
+  }
+
+  // Write protection attributes
+  if (((EfiAttributes & EFI_MEMORY_RO) !=3D 0) ||
+      ((EfiAttributes & EFI_MEMORY_WP) !=3D 0))
+  {
+    LoongArchAttributes &=3D ~PAGE_DIRTY;
+  }
+
+  if ((EfiAttributes & EFI_MEMORY_RP) !=3D 0) {
+    LoongArchAttributes |=3D PAGE_NO_READ;
+  }
+
+  // eXecute protection attribute
+  if ((EfiAttributes & EFI_MEMORY_XP) !=3D 0) {
+    LoongArchAttributes |=3D PAGE_NO_EXEC;
+  }
+
+  return LoongArchAttributes;
+}
+
+/**
+  Finds the length and memory properties of the memory region correspondin=
g to the specified base address.
+
+  @param[in]  BaseAddress    To find the base address of the memory region=
.
+  @param[in]  EndAddress     To find the end address of the memory region.
+  @param[out]  RegionLength    The length of the memory region found.
+  @param[out]  RegionAttributes    Properties of the memory region found.
+
+  @retval  EFI_SUCCESS    The corresponding memory area was successfully f=
ound
+           EFI_NOT_FOUND    No memory area found
+**/
+EFI_STATUS
+GetMemoryRegionAttribute (
+  IN     UINTN  BaseAddress,
+  IN     UINTN  EndAddress,
+  OUT    UINTN  *RegionLength,
+  OUT    UINTN  *RegionAttributes
+  )
+{
+  PTE    *Pte;
+  UINTN  Attributes;
+  UINTN  AttributesTmp;
+  UINTN  MaxAddress;
+
+  if (!MmuIsInit ()) {
+    return EFI_UNSUPPORTED;
+  }
+
+  MaxAddress =3D LShiftU64 (1ULL, MAX_VA_BITS) - 1;
+  Pte        =3D GetPteAddress (BaseAddress);
+
+  if (Pte =3D=3D NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  Attributes =3D GET_PAGE_ATTRIBUTES (*Pte);
+  if (IS_HUGE_PAGE (Pte->PteVal)) {
+    *RegionAttributes =3D Attributes & (~(PAGE_HUGE));
+    *RegionLength    +=3D HUGE_PAGE_SIZE;
+  } else {
+    *RegionLength    +=3D EFI_PAGE_SIZE;
+    *RegionAttributes =3D Attributes;
+  }
+
+  while (BaseAddress <=3D MaxAddress) {
+    Pte =3D GetPteAddress (BaseAddress);
+    if (Pte =3D=3D NULL) {
+      return EFI_SUCCESS;
+    }
+
+    AttributesTmp =3D GET_PAGE_ATTRIBUTES (*Pte);
+    if (IS_HUGE_PAGE (Pte->PteVal)) {
+      if (AttributesTmp =3D=3D Attributes) {
+        *RegionLength +=3D HUGE_PAGE_SIZE;
+      }
+
+      BaseAddress +=3D HUGE_PAGE_SIZE;
+    } else {
+      if (AttributesTmp =3D=3D Attributes) {
+        *RegionLength +=3D EFI_PAGE_SIZE;
+      }
+
+      BaseAddress +=3D EFI_PAGE_SIZE;
+    }
+
+    if (BaseAddress > EndAddress) {
+      break;
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the Attributes  of the specified memory region
+
+  @param[in]  BaseAddress    The base address of the memory region to set =
the Attributes.
+  @param[in]  Length         The length of the memory region to set the At=
tributes.
+  @param[in]  Attributes     The Attributes to be set.
+  @param[in]  AttributeMask  Mask of memory attributes to take into accoun=
t.
+
+  @retval  EFI_SUCCESS    The Attributes was set successfully
+**/
+EFI_STATUS
+SetMemoryRegionAttributes (
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN UINTN                 Length,
+  IN UINTN                 Attributes,
+  IN UINT64                AttributeMask
+  )
+{
+  if (!MmuIsInit ()) {
+    return EFI_UNSUPPORTED;
+  }
+
+  Attributes =3D EfiAttributeConverse (Attributes);
+  MemoryMapPageRange (BaseAddress, BaseAddress + Length, Attributes);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the non-executable Attributes for the specified memory region
+
+  @param[in]  BaseAddress  The base address of the memory region to set th=
e Attributes.
+  @param[in]  Length       The length of the memory region to set the Attr=
ibutes.
+
+  @retval  EFI_SUCCESS    The Attributes was set successfully
+**/
+EFI_STATUS
+SetMemoryRegionNoExec (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINTN                 Length
+  )
+{
+  if (MmuIsInit ()) {
+    Length =3D EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (Length));
+    SetMemoryRegionAttributes (BaseAddress, Length, EFI_MEMORY_XP, 0x0);
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Check to see if mmu successfully initializes and saves the result.
+
+  @param[in]  ImageHandle  The firmware allocated handle for the EFI image=
.
+  @param[in]  SystemTable  A pointer to the EFI System Table.
+
+  @retval  RETURN_SUCCESS    Initialization succeeded.
+**/
+RETURN_STATUS
+EFIAPI
+MmuInitialize (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  if (SWAP_PAGE_DIR !=3D 0) {
+    mMmuInited =3D TRUE;
+  }
+
+  return RETURN_SUCCESS;
+}
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h b/UefiC=
puPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h
new file mode 100644
index 0000000000..aa96f5143c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/CommonMmuLib.h
@@ -0,0 +1,43 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Dir    - Directory
+**/
+
+#ifndef  MMU_LIB_CORE_H_
+#define  MMU_LIB_CORE_H_
+
+/**
+  Iterates through the page directory to initialize it.
+
+  @param  Dst  A pointer to the directory of the page to initialize.
+  @param  Num  The number of page directories to initialize.
+  @param  Src  A pointer to the data used to initialize the page directory=
.
+
+  @retval VOID.
+**/
+VOID
+PageDirInit (
+  IN VOID   *dest,
+  IN UINTN  Count,
+  IN VOID   *src
+  );
+
+/**
+  Page tables are established from memory-mapped tables.
+
+  @param  MemoryRegion   A pointer to a memory-mapped table entry.
+
+  @retval     EFI_SUCCESS   The page table was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table  establishment failed due t=
o resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryRegion
+  );
+
+#endif // MMU_LIB_CORE_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf b/Uef=
iCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf
new file mode 100644
index 0000000000..d153354dd2
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf
@@ -0,0 +1,37 @@
+## @file
+#  CPU Memory Map Unit DXE phase driver.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights =
reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    =3D 0x00010005
+  BASE_NAME                      =3D DxeCpuMmuLib
+  MODULE_UNI_FILE                =3D DxeCpuMmuLib.uni
+  FILE_GUID                      =3D DA8F0232-FB14-42F0-922C-63104D2C70BE
+  MODULE_TYPE                    =3D DXE_DRIVER
+  VERSION_STRING                 =3D 1.0
+  LIBRARY_CLASS                  =3D CpuMmuLib | DXE_DRIVER
+  CONSTRUCTOR                    =3D MmuInitialize
+
+#
+#  VALID_ARCHITECTURES           =3D LOONGARCH64
+#
+
+[Sources]
+  TlbOperation.S   | GCC
+  CommonMmuLib.c
+  Tlb.h
+  Page.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  MemoryAllocationLib
+  PcdLib
+  DebugLib
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni b/Uef=
iCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni
new file mode 100644
index 0000000000..2e841d714c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.uni
@@ -0,0 +1,14 @@
+// /** @file
+// CPU Memory Manager Unit library instance for DXE modules.
+//
+// CPU Memory Manager Unit library instance for DXE modules.
+//
+// Copyright (c) 2023, Loongson Technology Corporation Limited. All rights=
 reserved.<BR>
+//
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+//
+// **/
+
+#string STR_MODULE_ABSTRACT             #language en-US "CPU Memory Manage=
r Unit library instance for DXE modules."
+
+#string STR_MODULE_DESCRIPTION          #language en-US "CPU Memory Manage=
r Unit library instance for DXE modules."
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/C=
ommonMmuLib.c b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLi=
b/CommonMmuLib.c
new file mode 100644
index 0000000000..f5e632a237
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/CommonMm=
uLib.c
@@ -0,0 +1,964 @@
+/** @file
+
+  CPU Memory Map Unit Handler Library common functions.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Pgd or Pgd or PGD    - Page Global Directory
+    - Pud or Pud or PUD    - Page Upper Directory
+    - Pmd or Pmd or PMD    - Page Middle Directory
+    - Pte or pte or PTE    - Page Table Entry
+    - Val or VAL or val    - Value
+    - Dir    - Directory
+**/
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Register/LoongArch64/Csr.h>
+#include "Tlb.h"
+#include "Page.h"
+
+BOOLEAN  mMmuInited =3D FALSE;
+#define  SWAP_PAGE_DIR  CsrRead(LOONGARCH_CSR_PGDL)
+
+/**
+  Check to see if mmu successfully initializes.
+
+  @param  VOID.
+
+  @retval  TRUE  Initialization has been completed.
+           FALSE Initialization did not complete.
+**/
+BOOLEAN
+MmuIsInit (
+  VOID
+  )
+{
+  if (mMmuInited || (SWAP_PAGE_DIR !=3D 0)) {
+    return TRUE;
+  }
+
+  return FALSE;
+}
+
+/**
+  Iterates through the page directory to initialize it.
+
+  @param  Dst  A pointer to the directory of the page to initialize.
+  @param  Num  The number of page directories to initialize.
+  @param  Src  A pointer to the data used to initialize the page directory=
.
+
+  @return VOID.
+**/
+VOID
+PageDirInit (
+  IN VOID   *Dst,
+  IN UINTN  Num,
+  IN VOID   *Src
+  )
+{
+  UINTN  *Ptr;
+  UINTN  *End;
+  UINTN  Entry;
+
+  Entry =3D (UINTN)Src;
+  Ptr   =3D (UINTN *)Dst;
+  End   =3D Ptr + Num;
+
+  for ( ; Ptr < End; Ptr++) {
+    *Ptr =3D Entry;
+  }
+
+  return;
+}
+
+/**
+  Gets the virtual address corresponding to the page global directory tabl=
e entry.
+
+  @param  Address  the virtual address for the table entry.
+
+  @retval PGD A pointer to get the table item.
+**/
+PGD *
+PgdOffset (
+  IN UINTN  Address
+  )
+{
+  return (PGD *)(SWAP_PAGE_DIR) + PGD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page upper directory table=
 entry.
+
+  @param  Pgd  A pointer to a page global directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PUD A pointer to get the table item.
+**/
+PUD *
+PudOffset (
+  IN PGD    *Pgd,
+  IN UINTN  Address
+  )
+{
+  UINTN  PgdVal;
+
+  PgdVal =3D (UINTN)PGD_VAL (*Pgd);
+
+  return (PUD *)PgdVal + PUD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page middle directory tabl=
e entry.
+
+  @param  Pud  A pointer to a page upper directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PMD A pointer to get the table item.
+**/
+PMD *
+PmdOffset (
+  IN PUD    *Pud,
+  IN UINTN  Address
+  )
+{
+  UINTN  PudVal;
+
+  PudVal =3D PUD_VAL (*Pud);
+
+  return (PMD *)PudVal + PMD_INDEX (Address);
+}
+
+/**
+  Gets the virtual address corresponding to the page table entry.
+
+  @param  Pmd  A pointer to a page middle directory table entry.
+  @param  Address  the virtual address for the table entry.
+
+  @retval PTE A pointer to get the table item.
+**/
+PTE *
+PteOffset (
+  IN PMD    *Pmd,
+  IN UINTN  Address
+  )
+{
+  UINTN  PmdVal;
+
+  PmdVal =3D (UINTN)PMD_VAL (*Pmd);
+
+  return (PTE *)PmdVal + PTE_INDEX (Address);
+}
+
+/**
+  Sets the value of the page table entry.
+
+  @param  Pte  A pointer to a page table entry.
+  @param  PteVal  The value of the page table entry to set.
+
+**/
+VOID
+SetPte (
+  IN PTE  *Pte,
+  IN PTE  PteVal
+  )
+{
+  *Pte =3D PteVal;
+}
+
+/**
+  Sets the value of the page global directory.
+
+  @param  Pgd  A pointer to a page global directory.
+  @param  Pud  The value of the page global directory to set.
+
+**/
+VOID
+SetPgd (
+  IN PGD  *Pgd,
+  IN PUD  *Pud
+  )
+{
+  *Pgd =3D (PGD) {
+    ((UINTN)Pud)
+  };
+}
+
+/**
+  Sets the value of the page upper directory.
+
+  @param  Pud  A pointer to a page upper directory.
+  @param  Pmd  The value of the page upper directory to set.
+
+**/
+VOID
+SetPud (
+  IN PUD  *Pud,
+  IN PMD  *Pmd
+  )
+{
+  *Pud =3D (PUD) {
+    ((UINTN)Pmd)
+  };
+}
+
+/**
+  Sets the value of the page middle directory.
+
+  @param  Pmd  A pointer to a page middle directory.
+  @param  Pte  The value of the page middle directory to set.
+
+**/
+VOID
+SetPmd (
+  IN PMD  *Pmd,
+  IN PTE  *Pte
+  )
+{
+  *Pmd =3D (PMD) {
+    ((UINTN)Pte)
+  };
+}
+
+/**
+  Free up memory space occupied by page tables.
+
+  @param  Pte  A pointer to the page table.
+
+**/
+VOID
+PteFree (
+  IN PTE  *Pte
+  )
+{
+  FreePages ((VOID *)Pte, 1);
+}
+
+/**
+  Free up memory space occupied by page middle directory.
+
+  @param  Pmd  A pointer to the page middle directory.
+
+**/
+VOID
+PmdFree (
+  IN PMD  *Pmd
+  )
+{
+  FreePages ((VOID *)Pmd, 1);
+}
+
+/**
+  Free up memory space occupied by page upper directory.
+
+  @param  Pud  A pointer to the page upper directory.
+
+**/
+VOID
+PudFree (
+  IN PUD  *Pud
+  )
+{
+  FreePages ((VOID *)Pud, 1);
+}
+
+/**
+  Requests the memory space required for the page upper directory,
+  initializes it, and places it in the specified page global directory
+
+  @param  Pgd  A pointer to the page global directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PudAlloc (
+  IN PGD  *Pgd
+  )
+{
+  PUD  *Pud;
+
+  Pud =3D (PUD *)AllocatePages (1);
+  if (Pud =3D=3D NULL) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  PageDirInit ((VOID *)Pud, ENTRYS_PER_PUD, (VOID *)INVALID_PAGE);
+
+  SetPgd (Pgd, Pud);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page middle directory,
+  initializes it, and places it in the specified page upper directory
+
+  @param  Pud  A pointer to the page upper directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PmdAlloc (
+  IN PUD  *Pud
+  )
+{
+  PMD  *Pmd;
+
+  Pmd =3D (PMD *)AllocatePages (1);
+  if (!Pmd) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  PageDirInit ((VOID *)Pmd, ENTRYS_PER_PMD, (VOID *)INVALID_PAGE);
+
+  SetPud (Pud, Pmd);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page table,
+  initializes it, and places it in the specified page middle directory
+
+  @param  Pmd  A pointer to the page middle directory.
+
+  @retval  EFI_SUCCESS  Memory request successful.
+  @retval  EFI_OUT_OF_RESOURCES  Resource exhaustion cannot be requested t=
o memory.
+**/
+EFI_STATUS
+PteAlloc (
+  IN PMD  *Pmd
+  )
+{
+  PTE  *Pte;
+
+  Pte =3D (PTE *)AllocatePages (1);
+  if (!Pte) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  Pte =3D ZeroMem (Pte, EFI_PAGE_SIZE);
+
+  SetPmd (Pmd, Pte);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Requests the memory space required for the page upper directory,
+  initializes it, and places it in the specified page global directory,
+  and get the page upper directory entry corresponding to the virtual addr=
ess.
+
+  @param  Pgd      A pointer to the page global directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page upper directory entry. Return NUL=
L, if
+                   allocate the memory buffer is fail.
+**/
+PUD *
+PudAllocGet (
+  IN PGD    *Pgd,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PGD_IS_EMPTY (*Pgd)) {
+    Status =3D PudAlloc (Pgd);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PudOffset (Pgd, Address);
+}
+
+/**
+  Requests the memory space required for the page middle directory,
+  initializes it, and places it in the specified page upper directory,
+  and get the page middle directory entry corresponding to the virtual add=
ress.
+
+  @param  Pud      A pointer to the page upper directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page middle directory entry. Return NU=
LL, if
+                   allocate the memory buffer is fail.
+**/
+PMD *
+PmdAllocGet (
+  IN PUD    *Pud,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PUD_IS_EMPTY (*Pud)) {
+    Status =3D PmdAlloc (Pud);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PmdOffset (Pud, Address);
+}
+
+/**
+  Requests the memory space required for the page table,
+  initializes it, and places it in the specified page middle directory,
+  and get the page table entry corresponding to the virtual address.
+
+  @param  Pmd      A pointer to the page upper directory.
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval          A pointer to the page table entry. Return NULL, if allo=
cate
+                   the memory buffer is fail.
+**/
+PTE *
+PteAllocGet (
+  IN PMD    *Pmd,
+  IN UINTN  Address
+  )
+{
+  EFI_STATUS  Status;
+
+  if (PMD_IS_EMPTY (*Pmd)) {
+    Status =3D PteAlloc (Pmd);
+    ASSERT_EFI_ERROR (Status);
+    if (EFI_ERROR (Status)) {
+      return NULL;
+    }
+  }
+
+  return PteOffset (Pmd, Address);
+}
+
+/**
+  Gets the physical address of the page table entry corresponding to the s=
pecified virtual address.
+
+  @param  Address  The corresponding virtual address of the page table ent=
ry.
+
+  @retval  A pointer to the page table entry.
+  @retval  NULL
+**/
+PTE *
+GetPteAddress (
+  IN UINTN  Address
+  )
+{
+  PGD  *Pgd;
+  PUD  *Pud;
+  PMD  *Pmd;
+
+  Pgd =3D PgdOffset (Address);
+
+  if (PGD_IS_EMPTY (*Pgd)) {
+    return NULL;
+  }
+
+  Pud =3D PudOffset (Pgd, Address);
+
+  if (PUD_IS_EMPTY (*Pud)) {
+    return NULL;
+  }
+
+  Pmd =3D PmdOffset (Pud, Address);
+  if (PMD_IS_EMPTY (*Pmd)) {
+    return NULL;
+  }
+
+  if (IS_HUGE_PAGE (Pmd->PmdVal)) {
+    return ((PTE *)Pmd);
+  }
+
+  return PteOffset (Pmd, Address);
+}
+
+/**
+  Gets the Attributes of Huge Page.
+
+  @param  Pmd  A pointer to the page middle directory.
+
+  @retval     Value of Attributes.
+**/
+UINTN
+GetHugePageAttributes (
+  IN  PMD  *Pmd
+  )
+{
+  UINTN  Attributes;
+  UINTN  GlobalFlag;
+  UINTN  HugeVal;
+
+  HugeVal     =3D PMD_VAL (*Pmd);
+  Attributes  =3D HugeVal & (~HUGEP_PAGE_MASK);
+  GlobalFlag  =3D ((Attributes & (1 << PAGE_HGLOBAL_SHIFT)) >=
> PAGE_HGLOBAL_SHIFT) << PAGE_GLOBAL_SHIFT;
+  Attributes &=3D ~(1 << PAGE_HGLOBAL_SHIFT);
+  Attributes |=3D GlobalFlag;
+  return Attributes;
+}
+
+/**
+  Establishes a page table entry based on the specified memory region.
+
+  @param  Pmd  A pointer to the page middle directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page table entry was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table entry establishment failed =
due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPteRange (
+  IN PMD    *Pmd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PTE      *Pte;
+  PTE      PteVal;
+  BOOLEAN  UpDate;
+
+  Pte =3D PteAllocGet (Pmd, Address);
+  if (!Pte) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  DEBUG ((
+    DEBUG_INFO,
+    "%a %d Address %p End %p  Attributes %llx\n",
+    __func__,
+    __LINE__,
+    Address,
+    End,
+    Attributes
+    ));
+
+  do {
+    UpDate =3D FALSE;
+    PteVal =3D MAKE_PTE (Address, Attributes);
+
+    if ((!PTE_IS_EMPTY (*Pte)) &&
+        (PTE_VAL (*Pte) !=3D PTE_VAL (PteVal)))
+    {
+      UpDate =3D TRUE;
+    }
+
+    SetPte (Pte, PteVal);
+    if (UpDate) {
+      InvalidTlb (Address);
+    }
+  } while (Pte++, Address +=3D EFI_PAGE_SIZE, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Convert Huge Page to Page.
+
+  @param  Pmd  A pointer to the page middle directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval  EFI_SUCCESS   The page table entry was created successfully.
+  @retval  EFI_OUT_OF_RESOURCES  Page table entry establishment failed due=
 to resource exhaustion.
+**/
+EFI_STATUS
+ConvertHugePageToPage (
+  IN  PMD   *Pmd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  UINTN       OldAttributes;
+  UINTN       HugePageEnd;
+  UINTN       HugePageStart;
+  EFI_STATUS  Status;
+
+  Status =3D EFI_SUCCESS;
+
+  if ((PMD_IS_EMPTY (*Pmd)) ||
+      (!IS_HUGE_PAGE (Pmd->PmdVal)))
+  {
+    Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes);
+  } else {
+    OldAttributes =3D GetHugePageAttributes (Pmd);
+    if (Attributes =3D=3D OldAttributes) {
+      return Status;
+    }
+
+    SetPmd (Pmd, (PTE *)(INVALID_PAGE));
+    HugePageStart =3D Address & PMD_MASK;
+    HugePageEnd   =3D HugePageStart + HUGE_PAGE_SIZE;
+    ASSERT (HugePageEnd >=3D End);
+
+    if (Address > HugePageStart) {
+      Status |=3D MemoryMapPteRange (Pmd, HugePageStart, Address, OldAttri=
butes);
+    }
+
+    Status |=3D MemoryMapPteRange (Pmd, Address, End, Attributes);
+
+    if (End < HugePageEnd) {
+      Status |=3D MemoryMapPteRange (Pmd, End, HugePageEnd, OldAttributes)=
;
+    }
+  }
+
+  return Status;
+}
+
+/**
+  Establishes a page middle directory based on the specified memory region=
.
+
+  @param  Pud  A pointer to the page upper directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page middle directory was created successf=
ully.
+  @retval     EFI_OUT_OF_RESOURCES  Page middle directory establishment fa=
iled due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPmdRange (
+  IN PUD    *Pud,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PMD      *Pmd;
+  UINTN    Next;
+  PTE      PteVal;
+  BOOLEAN  UpDate;
+
+  Pmd =3D PmdAllocGet (Pud, Address);
+  if (!Pmd) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  do {
+    Next =3D PMD_ADDRESS_END (Address, End);
+    if (((Address & (~PMD_MASK)) =3D=3D 0) &&
+        ((Next &  (~PMD_MASK)) =3D=3D 0) &&
+        (PMD_IS_EMPTY (*Pmd) || IS_HUGE_PAGE (Pmd->PmdVal)))
+    {
+      UpDate =3D FALSE;
+      PteVal =3D MAKE_HUGE_PTE (Address, Attributes);
+
+      if ((!PMD_IS_EMPTY (*Pmd)) &&
+          (PMD_VAL (*Pmd) !=3D PTE_VAL (PteVal)))
+      {
+        UpDate =3D TRUE;
+      }
+
+      SetPmd (Pmd, (PTE *)PteVal.PteVal);
+      if (UpDate) {
+        InvalidTlb (Address);
+      }
+    } else {
+      ConvertHugePageToPage (Pmd, Address, Next, Attributes);
+    }
+  } while (Pmd++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Establishes a page upper directory based on the specified memory region.
+
+  @param  Pgd  A pointer to the page global directory.
+  @param  Address  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page upper directory was created successfu=
lly.
+  @retval     EFI_OUT_OF_RESOURCES  Page upper directory establishment fai=
led due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPudRange (
+  IN PGD    *Pgd,
+  IN UINTN  Address,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PUD    *Pud;
+  UINTN  Next;
+
+  Pud =3D PudAllocGet (Pgd, Address);
+  if (!Pud) {
+    return EFI_OUT_OF_RESOURCES;
+  }
+
+  do {
+    Next =3D PUD_ADDRESS_END (Address, End);
+    if (EFI_ERROR (MemoryMapPmdRange (Pud, Address, Next, Attributes))) {
+      return EFI_OUT_OF_RESOURCES;
+    }
+  } while (Pud++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Establishes a page global directory based on the specified memory region=
.
+
+  @param  Start  The memory space start address.
+  @param  End  The end address of the memory space.
+  @param  Attributes  Memory space Attributes.
+
+  @retval     EFI_SUCCESS   The page global directory was created successf=
ully.
+  @retval     EFI_OUT_OF_RESOURCES  Page global directory establishment fa=
iled due to resource exhaustion.
+**/
+EFI_STATUS
+MemoryMapPageRange (
+  IN UINTN  Start,
+  IN UINTN  End,
+  IN UINTN  Attributes
+  )
+{
+  PGD         *Pgd;
+  UINTN       Next;
+  UINTN       Address;
+  EFI_STATUS  Err;
+
+  Address =3D Start;
+
+  /* Get PGD(PTE PMD PUD PGD) in PageTables */
+  Pgd =3D PgdOffset (Address);
+  do {
+    Next =3D PGD_ADDRESS_END (Address, End);
+    /* Get Next Align Page to Map */
+    Err =3D MemoryMapPudRange (Pgd, Address, Next, Attributes);
+    if (Err) {
+      return Err;
+    }
+  } while (Pgd++, Address =3D Next, Address !=3D End);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Page tables are established from memory-mapped tables.
+
+  @param  MemoryRegion   A pointer to a memory-mapped table entry.
+
+  @retval     EFI_SUCCESS   The page table was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table  establishment failed due t=
o resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryRegion
+  )
+{
+  return MemoryMapPageRange (
+           MemoryRegion->VirtualBase,
+           (MemoryRegion->Length + MemoryRegion->VirtualBase),
+           MemoryRegion->Attributes
+           );
+}
+
+/**
+  Convert EFI Attributes to Loongarch Attributes.
+
+  @param[in]  EfiAttributes     Efi Attributes.
+
+  @retval  Corresponding architecture attributes.
+**/
+UINTN
+EfiAttributeConverse (
+  IN UINTN  EfiAttributes
+  )
+{
+  UINTN  LoongArchAttributes;
+
+  LoongArchAttributes =3D PAGE_VALID | PAGE_DIRTY | PLV_KERNEL | PAGE_GLOB=
AL;
+
+  switch (EfiAttributes & EFI_MEMORY_CACHETYPE_MASK) {
+    case EFI_MEMORY_UC:
+      LoongArchAttributes |=3D CACHE_SUC;
+      break;
+    case EFI_MEMORY_WC:
+    case EFI_MEMORY_WT:
+    case EFI_MEMORY_WB:
+      LoongArchAttributes |=3D CACHE_CC;
+      break;
+    default:
+      LoongArchAttributes |=3D CACHE_CC;
+      break;
+  }
+
+  // Write protection attributes
+  if (((EfiAttributes & EFI_MEMORY_RO) !=3D 0) ||
+      ((EfiAttributes & EFI_MEMORY_WP) !=3D 0))
+  {
+    LoongArchAttributes &=3D ~PAGE_DIRTY;
+  }
+
+  if ((EfiAttributes & EFI_MEMORY_RP) !=3D 0) {
+    LoongArchAttributes |=3D PAGE_NO_READ;
+  }
+
+  // eXecute protection attribute
+  if ((EfiAttributes & EFI_MEMORY_XP) !=3D 0) {
+    LoongArchAttributes |=3D PAGE_NO_EXEC;
+  }
+
+  return LoongArchAttributes;
+}
+
+/**
+  Finds the length and memory properties of the memory region correspondin=
g to the specified base address.
+
+  @param[in]  BaseAddress    To find the base address of the memory region=
.
+  @param[in]  EndAddress     To find the end address of the memory region.
+  @param[out]  RegionLength    The length of the memory region found.
+  @param[out]  RegionAttributes    Properties of the memory region found.
+
+  @retval  EFI_SUCCESS    The corresponding memory area was successfully f=
ound
+           EFI_NOT_FOUND    No memory area found
+**/
+EFI_STATUS
+GetMemoryRegionAttribute (
+  IN     UINTN  BaseAddress,
+  IN     UINTN  EndAddress,
+  OUT    UINTN  *RegionLength,
+  OUT    UINTN  *RegionAttributes
+  )
+{
+  PTE    *Pte;
+  UINTN  Attributes;
+  UINTN  AttributesTmp;
+  UINTN  MaxAddress;
+
+  if (!MmuIsInit ()) {
+    return EFI_UNSUPPORTED;
+  }
+
+  MaxAddress =3D LShiftU64 (1ULL, MAX_VA_BITS) - 1;
+  Pte        =3D GetPteAddress (BaseAddress);
+
+  if (Pte =3D=3D NULL) {
+    return EFI_NOT_FOUND;
+  }
+
+  Attributes =3D GET_PAGE_ATTRIBUTES (*Pte);
+  if (IS_HUGE_PAGE (Pte->PteVal)) {
+    *RegionAttributes =3D Attributes & (~(PAGE_HUGE));
+    *RegionLength    +=3D HUGE_PAGE_SIZE;
+  } else {
+    *RegionLength    +=3D EFI_PAGE_SIZE;
+    *RegionAttributes =3D Attributes;
+  }
+
+  while (BaseAddress <=3D MaxAddress) {
+    Pte =3D GetPteAddress (BaseAddress);
+    if (Pte =3D=3D NULL) {
+      return EFI_SUCCESS;
+    }
+
+    AttributesTmp =3D GET_PAGE_ATTRIBUTES (*Pte);
+    if (IS_HUGE_PAGE (Pte->PteVal)) {
+      if (AttributesTmp =3D=3D Attributes) {
+        *RegionLength +=3D HUGE_PAGE_SIZE;
+      }
+
+      BaseAddress +=3D HUGE_PAGE_SIZE;
+    } else {
+      if (AttributesTmp =3D=3D Attributes) {
+        *RegionLength +=3D EFI_PAGE_SIZE;
+      }
+
+      BaseAddress +=3D EFI_PAGE_SIZE;
+    }
+
+    if (BaseAddress > EndAddress) {
+      break;
+    }
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the Attributes  of the specified memory region
+
+  @param[in]  BaseAddress  The base address of the memory region to set th=
e Attributes.
+  @param[in]  Length       The length of the memory region to set the Attr=
ibutes.
+  @param[in]  Attributes   The Attributes to be set.
+
+  @retval  EFI_SUCCESS    The Attributes was set successfully
+**/
+EFI_STATUS
+SetMemoryRegionAttributes (
+  IN EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN UINTN                 Length,
+  IN UINTN                 Attributes,
+  IN UINT64                AttributeMask
+  )
+{
+  if (!MmuIsInit ()) {
+    return EFI_UNSUPPORTED;
+  }
+
+  Attributes =3D EfiAttributeConverse (Attributes);
+  MemoryMapPageRange (BaseAddress, BaseAddress + Length, Attributes);
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Sets the non-executable Attributes for the specified memory region
+
+  @param[in]  BaseAddress  The base address of the memory region to set th=
e Attributes.
+  @param[in]  Length       The length of the memory region to set the Attr=
ibutes.
+
+  @retval  EFI_SUCCESS    The Attributes was set successfully
+**/
+EFI_STATUS
+SetMemoryRegionNoExec (
+  IN  EFI_PHYSICAL_ADDRESS  BaseAddress,
+  IN  UINTN                 Length
+  )
+{
+  if (MmuIsInit ()) {
+    Length =3D EFI_PAGES_TO_SIZE (EFI_SIZE_TO_PAGES (Length));
+    SetMemoryRegionAttributes (BaseAddress, Length, EFI_MEMORY_XP, 0x0);
+  }
+
+  return EFI_SUCCESS;
+}
+
+/**
+  Check to see if mmu successfully initializes and saves the result.
+
+  @param[in]  ImageHandle  The firmware allocated handle for the EFI image=
.
+  @param[in]  SystemTable  A pointer to the EFI System Table.
+
+  @retval  RETURN_SUCCESS    Initialization succeeded.
+**/
+RETURN_STATUS
+EFIAPI
+MmuInitialize (
+  IN EFI_HANDLE        ImageHandle,
+  IN EFI_SYSTEM_TABLE  *SystemTable
+  )
+{
+  if (SWAP_PAGE_DIR !=3D 0) {
+    mMmuInited =3D TRUE;
+  }
+
+  return RETURN_SUCCESS;
+}
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/C=
ommonMmuLib.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLi=
b/CommonMmuLib.h
new file mode 100644
index 0000000000..aa96f5143c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/CommonMm=
uLib.h
@@ -0,0 +1,43 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Dir    - Directory
+**/
+
+#ifndef  MMU_LIB_CORE_H_
+#define  MMU_LIB_CORE_H_
+
+/**
+  Iterates through the page directory to initialize it.
+
+  @param  Dst  A pointer to the directory of the page to initialize.
+  @param  Num  The number of page directories to initialize.
+  @param  Src  A pointer to the data used to initialize the page directory=
.
+
+  @retval VOID.
+**/
+VOID
+PageDirInit (
+  IN VOID   *dest,
+  IN UINTN  Count,
+  IN VOID   *src
+  );
+
+/**
+  Page tables are established from memory-mapped tables.
+
+  @param  MemoryRegion   A pointer to a memory-mapped table entry.
+
+  @retval     EFI_SUCCESS   The page table was created successfully.
+  @retval     EFI_OUT_OF_RESOURCES  Page table  establishment failed due t=
o resource exhaustion.
+**/
+EFI_STATUS
+FillTranslationTable (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryRegion
+  );
+
+#endif // MMU_LIB_CORE_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/D=
xeCpuMmuLib.inf b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu=
Lib/DxeCpuMmuLib.inf
new file mode 100644
index 0000000000..d153354dd2
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/DxeCpuMm=
uLib.inf
@@ -0,0 +1,37 @@
+## @file
+#  CPU Memory Map Unit DXE phase driver.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights =
reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    =3D 0x00010005
+  BASE_NAME                      =3D DxeCpuMmuLib
+  MODULE_UNI_FILE                =3D DxeCpuMmuLib.uni
+  FILE_GUID                      =3D DA8F0232-FB14-42F0-922C-63104D2C70BE
+  MODULE_TYPE                    =3D DXE_DRIVER
+  VERSION_STRING                 =3D 1.0
+  LIBRARY_CLASS                  =3D CpuMmuLib | DXE_DRIVER
+  CONSTRUCTOR                    =3D MmuInitialize
+
+#
+#  VALID_ARCHITECTURES           =3D LOONGARCH64
+#
+
+[Sources]
+  TlbOperation.S   | GCC
+  CommonMmuLib.c
+  Tlb.h
+  Page.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[LibraryClasses]
+  MemoryAllocationLib
+  PcdLib
+  DebugLib
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/D=
xeCpuMmuLib.uni b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu=
Lib/DxeCpuMmuLib.uni
new file mode 100644
index 0000000000..2e841d714c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/DxeCpuMm=
uLib.uni
@@ -0,0 +1,14 @@
+// /** @file
+// CPU Memory Manager Unit library instance for DXE modules.
+//
+// CPU Memory Manager Unit library instance for DXE modules.
+//
+// Copyright (c) 2023, Loongson Technology Corporation Limited. All rights=
 reserved.<BR>
+//
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+//
+// **/
+
+#string STR_MODULE_ABSTRACT             #language en-US "CPU Memory Manage=
r Unit library instance for DXE modules."
+
+#string STR_MODULE_DESCRIPTION          #language en-US "CPU Memory Manage=
r Unit library instance for DXE modules."
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/P=
age.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Page.h
new file mode 100644
index 0000000000..ad8f751ad7
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Page.h
@@ -0,0 +1,279 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Pgd or Pgd or PGD    - Page Global Directory
+    - Pud or Pud or PUD    - Page Upper Directory
+    - Pmd or Pmd or PMD    - Page Middle Directory
+    - Pte or pte or PTE    - Page Table Entry
+    - Val or VAL or val    - Value
+    - Dir    - Directory
+**/
+
+#ifndef PAGE_H_
+#define PAGE_H_
+
+#include <Library/CpuMmuLib.h>
+
+#define MAX_VA_BITS  47
+#define PGD_WIDE     (8)
+#define PUD_WIDE     (9)
+#define PMD_WIDE     (9)
+#define PTE_WIDE     (9)
+
+#define ENTRYS_PER_PGD  (1 << PGD_WIDE)
+#define ENTRYS_PER_PUD  (1 << PUD_WIDE)
+#define ENTRYS_PER_PMD  (1 << PMD_WIDE)
+#define ENTRYS_PER_PTE  (1 << PTE_WIDE)
+
+#define PGD_SHIFT  (PUD_SHIFT + PUD_WIDE)
+#define PUD_SHIFT  (PMD_SHIFT + PMD_WIDE)
+#define PMD_SHIFT  (EFI_PAGE_SHIFT + PTE_WIDE)
+#define PTE_SHIFT  (EFI_PAGE_SHIFT)
+
+#define PGD_SIZE  (1UL << PGD_SHIFT)
+#define PUD_SIZE  (1UL << PUD_SHIFT)
+#define PMD_SIZE  (1UL << PMD_SHIFT)
+
+#define PGD_MASK   (~(PGD_SIZE-1))
+#define PUD_MASK   (~(PUD_SIZE-1))
+#define PMD_MASK   (~(PMD_SIZE-1))
+#define PAGE_MASK  (~(EFI_PAGE_SIZE - 1))
+#define PFN_MASK   (~(((UINTN)(1) << (EFI_PAGE_SHIFT)) - 1) & \
+                   (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1))
+
+#define HUGEP_PAGE_MASK  (~(((UINTN)(1) << (PMD_SHIFT)) - 1) & \
+                          (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)=
)
+
+#define INVALID_PAGE  0
+
+typedef struct {
+  UINTN    PgdVal;
+} PGD;
+typedef struct {
+  UINTN    PudVal;
+} PUD;
+typedef struct {
+  UINTN    PmdVal;
+} PMD;
+typedef struct {
+  UINTN    PteVal;
+} PTE;
+
+/**
+  Gets the value of the page global directory table entry.
+
+  @param  x    Page global directory struct variables.
+
+  @retval   the value of the page global directory table entry.
+ **/
+#define PGD_VAL(x)  ((x).PgdVal)
+
+/**
+  Gets the value of the page upper directory table entry.
+
+  @param  x    Page upper directory struct variables.
+
+  @retval  the value of the page upper directory table entry.
+ **/
+#define PUD_VAL(x)  ((x).PudVal)
+
+/**
+  Gets the value of the page middle directory table entry.
+
+  @param  x    Page middle directory struct variables.
+
+  @retval  the value of the page middle directory table entry.
+ **/
+#define PMD_VAL(x)  ((x).PmdVal)
+
+/**
+  Gets the value of the page table entry.
+
+  @param  x    Page table entry struct variables.
+
+  @retval  the value of the page table entry.
+ **/
+#define PTE_VAL(x)  ((x).PteVal)
+
+#define PGD_TABLE_SIZE  (ENTRYS_PER_PGD * sizeof(PGD))
+#define PUD_TABLE_SIZE  (ENTRYS_PER_PUD * sizeof(PUD))
+#define PMD_TABLE_SIZE  (ENTRYS_PER_PMD * sizeof(PMD))
+#define PTE_TABLE_SIZE  (ENTRYS_PER_PTE * sizeof(PTE))
+
+/**
+  Gets the physical address of the record in the page table entry.
+
+  @param  x    Page table entry struct variables.
+
+  @retval  the value of the physical address.
+ **/
+#define GET_PAGE_ATTRIBUTES(x)  (UINTN) {(PTE_VAL(x) & ~PFN_MASK)}
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the global page directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PGD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PGD_SIZE) & PGD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the page upper directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PUD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PUD_SIZE) & PUD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the page middle directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PMD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PMD_SIZE) & PMD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 global directory table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page global directory table entry.
+ **/
+#define PGD_INDEX(Address)  (((Address) >> PGD_SHIFT) & (ENTRYS_=
PER_PGD-1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 upper directory table entry.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the index of the page upper directory table entry.
+ **/
+#define PUD_INDEX(Address)  (((Address) >> PUD_SHIFT) & (ENTRYS_=
PER_PUD - 1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 middle directory table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page middle directory table entry.
+ **/
+#define PMD_INDEX(Address)  (((Address) >> PMD_SHIFT) & (ENTRYS_=
PER_PMD - 1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page table entry.
+ **/
+#define PTE_INDEX(Address)  (((Address) >> EFI_PAGE_SHIFT) & (EN=
TRYS_PER_PTE - 1))
+
+/**
+  Calculates the value of the page table entry based on the specified virt=
ual address and properties.
+
+  @param  Address  Specifies the virtual address.
+  @param  Attributes  Specifies the Attributes.
+
+  @retval    the value of the page table entry.
+ **/
+#define MAKE_PTE(Address, Attributes)  (PTE){((((Address) >> EFI_PAG=
E_SHIFT) << 12) | (Attributes))}
+
+/**
+  Get Global bit from Attributes
+
+  @param  Attributes  Specifies the Attributes.
+ * */
+#define GET_GLOBALBIT(Attributes)  ((Attributes & PAGE_GLOBAL) >>=
; PAGE_GLOBAL_SHIFT)
+
+/**
+  Calculates the value of the Huge page table entry based on the specified=
 virtual address and properties.
+
+  @param  Address  Specifies the virtual address.
+  @param  Attributes  Specifies the Attributes.
+
+  @retval    the value of the HUGE page table entry.
+ **/
+#define MAKE_HUGE_PTE(Address, Attributes)  (PTE){(((((Address) >> P=
MD_SHIFT) << PMD_SHIFT) | \
+                                             ((Attributes) | (GET_GLOBALBI=
T(Attributes) << PAGE_HGLOBAL_SHIFT) | \
+                                             PAGE_HUGE)))}
+
+/**
+  Check whether the large page table entry is.
+
+  @param  Val The value of the page table entry.
+
+  @retval    1   Is huge page table entry.
+  @retval    0   Isn't huge page table entry.
+**/
+#define IS_HUGE_PAGE(Val)  ((((Val) & PAGE_HUGE) =3D=3D PAGE_HUGE) &am=
p;& \
+                            (((Val) & PAGE_HGLOBAL) =3D=3D PAGE_HGLOBA=
L))
+
+#define HUGE_PAGE_SIZE  (PMD_SIZE)
+
+/**
+  Check that the global page directory table entry is empty.
+
+  @param  pgd   the global page directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PGD_IS_EMPTY(Val)  (PGD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page upper directory table entry is empty.
+
+  @param  pud   Page upper directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PUD_IS_EMPTY(Val)  (PUD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page middle directory table entry is empty.
+
+  @param  pmd   Page middle directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PMD_IS_EMPTY(Val)  (PMD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page the page table entry is empty.
+
+  @param  pte   Page table entry struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PTE_IS_EMPTY(Val)  (!(PTE_VAL(Val) & (~PAGE_VALID)))
+#endif // PAGE_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/P=
eiCpuMmuLib.c b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLi=
b/PeiCpuMmuLib.c
new file mode 100644
index 0000000000..42a424b84d
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpuMm=
uLib.c
@@ -0,0 +1,165 @@
+/** @file
+  CPU Memory Map Unit PEI phase driver.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Tlb      - Translation Lookaside Buffer
+**/
+
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Library/CacheMaintenanceLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Register/LoongArch64/Csr.h>
+
+#include "Page.h"
+#include "Tlb.h"
+#include "CommonMmuLib.h"
+
+/**
+  Create a page table and initialize the memory management unit(MMU).
+
+  @param[in]   MemoryTable           A pointer to a memory ragion table.
+  @param[out]  TranslationTableBase  A pointer to a translation table base=
 address.
+  @param[out]  TranslationTableSize  A pointer to a translation table base=
 size.
+
+  @retval  EFI_SUCCESS                Configure MMU successfully.
+           EFI_INVALID_PARAMETER      MemoryTable is NULL.
+           EFI_UNSUPPORTED            Out of memory space or size not alig=
ned.
+**/
+EFI_STATUS
+EFIAPI
+ConfigureMemoryManagementUint (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryTable,
+  OUT VOID                      **TranslationTableBase OPTIONAL,
+  OUT UINTN                     *TranslationTableSize  OPTIONAL
+  )
+{
+  PGD            *SwapperPageDir;
+  UINTN          PgdShift;
+  UINTN          PgdWide;
+  UINTN          PudShift;
+  UINTN          PudWide;
+  UINTN          PmdShift;
+  UINTN          PmdWide;
+  UINTN          PteShift;
+  UINTN          PteWide;
+  UINTN          Length;
+  UINTN          TlbReEntry;
+  UINTN          TlbReEntryOffset;
+  RETURN_STATUS  Status;
+
+  SwapperPageDir =3D NULL;
+  PgdShift       =3D PGD_SHIFT;
+  PgdWide        =3D PGD_WIDE;
+  PudShift       =3D PUD_SHIFT;
+  PudWide        =3D PUD_WIDE;
+  PmdShift       =3D PMD_SHIFT;
+  PmdWide        =3D PMD_WIDE;
+  PteShift       =3D PTE_SHIFT;
+  PteWide        =3D PTE_WIDE;
+
+  if (MemoryTable =3D=3D NULL) {
+    ASSERT (MemoryTable !=3D NULL);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  SwapperPageDir =3D AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+  ZeroMem (SwapperPageDir, PGD_TABLE_SIZE);
+
+  if (SwapperPageDir =3D=3D NULL) {
+    goto FreeTranslationTable;
+  }
+
+  CsrWrite (LOONGARCH_CSR_PGDL, (UINTN)SwapperPageDir);
+
+  while (MemoryTable->Length !=3D 0) {
+    DEBUG ((
+      DEBUG_INFO,
+      "%a %d VirtualBase %p VirtualEnd %p Attributes %p .\n",
+      __func__,
+      __LINE__,
+      MemoryTable->VirtualBase,
+      (MemoryTable->Length + MemoryTable->VirtualBase),
+      MemoryTable->Attributes
+      ));
+
+    Status =3D FillTranslationTable (MemoryTable);
+    if (EFI_ERROR (Status)) {
+      goto FreeTranslationTable;
+    }
+
+    MemoryTable++;
+  }
+
+  //
+  // TLB Re-entry address at the end of exception vector, a vector is up t=
o 512 bytes,
+  // so the starting address is: total exception vector size + total inter=
rupt vector size + base.
+  // The total size of TLB handler and exception vector size and interrupt=
 vector size should not
+  // be lager than 64KB.
+  //
+  Length           =3D (UINTN)HandleTlbRefillEnd - (UINTN)HandleTlbRefillS=
tart;
+  TlbReEntryOffset =3D (MAX_LOONGARCH_EXCEPTION + MAX_LOONGARCH_INTERRUPT)=
 * 512;
+  TlbReEntry       =3D PcdGet64 (PcdCpuExceptionVectorBaseAddress) + TlbRe=
EntryOffset;
+  if ((TlbReEntryOffset + Length) > SIZE_64KB) {
+    goto FreeTranslationTable;
+  }
+
+  //
+  // Make sure TLB refill exception base address alignment is greater than=
 or equal to 4KB and valid
+  //
+  if (TlbReEntry & (SIZE_4KB - 1)) {
+    goto FreeTranslationTable;
+  }
+
+  CopyMem ((VOID *)TlbReEntry, HandleTlbRefillStart, Length);
+  InvalidateInstructionCacheRange ((VOID *)(UINTN)HandleTlbRefillStart, Le=
ngth);
+
+  DEBUG ((
+    DEBUG_INFO,
+    "%a  %d PteShift %d PteWide %d PmdShift %d PmdWide %d PudShift %d PudW=
ide %d PgdShift %d PgdWide %d.\n",
+    __func__,
+    __LINE__,
+    PteShift,
+    PteWide,
+    PmdShift,
+    PmdWide,
+    PudShift,
+    PudWide,
+    PgdShift,
+    PgdWide
+    ));
+
+  //
+  // Set the address of TLB refill exception handler
+  //
+  SetTlbRebaseAddress ((UINTN)TlbReEntry);
+
+  //
+  // Set page size
+  //
+  CsrXChg (LOONGARCH_CSR_TLBIDX, (DEFAULT_PAGE_SIZE << CSR_TLBIDX_SI=
ZE), CSR_TLBIDX_SIZE_MASK);
+  CsrWrite (LOONGARCH_CSR_STLBPGSIZE, DEFAULT_PAGE_SIZE);
+  CsrXChg (LOONGARCH_CSR_TLBREHI, (DEFAULT_PAGE_SIZE << CSR_TLBREHI_=
PS_SHIFT), CSR_TLBREHI_PS);
+
+  CsrWrite (LOONGARCH_CSR_PWCTL0, (PteShift | PteWide << 5 | PmdShif=
t << 10 | PmdWide << 15 | PudShift << 20 | PudWide <&l=
t; 25));
+  CsrWrite (LOONGARCH_CSR_PWCTL1, (PgdShift | PgdWide << 6));
+
+  DEBUG ((DEBUG_INFO, "%a %d Enable Mmu Start PageBassAddress %p.\n", __fu=
nc__, __LINE__, SwapperPageDir));
+
+  return EFI_SUCCESS;
+
+FreeTranslationTable:
+  if (SwapperPageDir !=3D NULL) {
+    FreePages (SwapperPageDir, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+  }
+
+  return EFI_UNSUPPORTED;
+}
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/P=
eiCpuMmuLib.inf b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu=
Lib/PeiCpuMmuLib.inf
new file mode 100644
index 0000000000..e746c3b1a7
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpuMm=
uLib.inf
@@ -0,0 +1,44 @@
+## @file
+#  CPU Memory Map Unit PEI phase driver.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights =
reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    =3D 0x00010005
+  BASE_NAME                      =3D PeiCpuMmuLib
+  MODULE_UNI_FILE                =3D PeiCpuMmuLib.uni
+  FILE_GUID                      =3D F67EB983-AC2A-7550-AB69-3BC51A1C895B
+  MODULE_TYPE                    =3D PEIM
+  VERSION_STRING                 =3D 1.0
+  LIBRARY_CLASS                  =3D CpuMmuLib | SEC PEIM
+
+#
+#  VALID_ARCHITECTURES           =3D LOONGARCH64
+#
+
+[Sources]
+  TlbOperation.S   | GCC
+  PeiCpuMmuLib.c
+  CommonMmuLib.c
+  CommonMmuLib.h
+  Tlb.h
+  Page.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[PCD]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuExceptionVectorBaseAddress
+
+[LibraryClasses]
+  MemoryAllocationLib
+  CacheMaintenanceLib
+  PcdLib
+  DebugLib
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/P=
eiCpuMmuLib.uni b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmu=
Lib/PeiCpuMmuLib.uni
new file mode 100644
index 0000000000..331500543c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/PeiCpuMm=
uLib.uni
@@ -0,0 +1,14 @@
+// /** @file
+// CPU Memory Manager Unit library instance for PEI modules.
+//
+// CPU Memory Manager Unit library instance for PEI modules.
+//
+// Copyright (c) 2023, Loongson Technology Corporation Limited. All rights=
 reserved.<BR>
+//
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+//
+// **/
+
+#string STR_MODULE_ABSTRACT             #language en-US "CPU Memory Manage=
r Unit library instance for PEI modules."
+
+#string STR_MODULE_DESCRIPTION          #language en-US "CPU Memory Manage=
r Unit library instance for PEI modules."
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/T=
lb.h b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Tlb.h
new file mode 100644
index 0000000000..5d3f80fe34
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/Tlb.h
@@ -0,0 +1,48 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TLB_H_
+#define TLB_H_
+
+/**
+  Invalid corresponding TLB entries are based on the address given
+
+  @param Address The address corresponding to the invalid page table entry
+
+  @retval  none
+**/
+VOID
+InvalidTlb (
+  UINTN  Address
+  );
+
+/**
+  TLB refill handler start.
+
+  @param  none
+
+  @retval none
+**/
+VOID
+HandleTlbRefillStart (
+  VOID
+  );
+
+/**
+  TLB refill handler end.
+
+  @param  none
+
+  @retval none
+**/
+VOID
+HandleTlbRefillEnd (
+  VOID
+  );
+
+#endif // TLB_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/T=
lbOperation.S b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLi=
b/TlbOperation.S
new file mode 100644
index 0000000000..e446f0839c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/LoongArch64CpuMmuLib/TlbOpera=
tion.S
@@ -0,0 +1,44 @@
+#-------------------------------------------------------------------------=
-----
+#
+# TLB operation functions
+#
+# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#-------------------------------------------------------------------------=
----
+
+#include <Register/LoongArch64/Csr.h>
+
+ASM_GLOBAL ASM_PFX(HandleTlbRefillStart)
+ASM_GLOBAL ASM_PFX(HandleTlbRefillEnd)
+ASM_GLOBAL ASM_PFX(InvalidTlb)
+
+#
+#  Refill the page table.
+#  @param  VOID
+#  @retval  VOID
+#
+ASM_PFX(HandleTlbRefillStart):
+  csrwr   $t0, LOONGARCH_CSR_TLBRSAVE
+  csrrd   $t0, LOONGARCH_CSR_PGD
+  lddir   $t0, $t0, 3   #Put pud BaseAddress into T0
+  lddir   $t0, $t0, 2   #Put pmd BaseAddress into T0
+  lddir   $t0, $t0, 1   #Put pte BaseAddress into T0
+  ldpte   $t0, 0
+  ldpte   $t0, 1
+  tlbfill   // refill hi,lo0,lo1
+  csrrd   $t0, LOONGARCH_CSR_TLBRSAVE
+  ertn
+ASM_PFX(HandleTlbRefillEnd):
+
+#
+# Invalid corresponding TLB entries are based on the address given
+# @param a0 The address corresponding to the invalid page table entry
+# @retval  none
+#
+ASM_PFX(InvalidTlb):
+    invtlb  INVTLB_ADDR_GTRUE_OR_ASID, $zero, $a0
+    jirl    $zero, $ra, 0
+
+    .end
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h b/UefiCpuPkg/Li=
brary/LoongArch64CpuMmuLib/Page.h
new file mode 100644
index 0000000000..ad8f751ad7
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Page.h
@@ -0,0 +1,279 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Pgd or Pgd or PGD    - Page Global Directory
+    - Pud or Pud or PUD    - Page Upper Directory
+    - Pmd or Pmd or PMD    - Page Middle Directory
+    - Pte or pte or PTE    - Page Table Entry
+    - Val or VAL or val    - Value
+    - Dir    - Directory
+**/
+
+#ifndef PAGE_H_
+#define PAGE_H_
+
+#include <Library/CpuMmuLib.h>
+
+#define MAX_VA_BITS  47
+#define PGD_WIDE     (8)
+#define PUD_WIDE     (9)
+#define PMD_WIDE     (9)
+#define PTE_WIDE     (9)
+
+#define ENTRYS_PER_PGD  (1 << PGD_WIDE)
+#define ENTRYS_PER_PUD  (1 << PUD_WIDE)
+#define ENTRYS_PER_PMD  (1 << PMD_WIDE)
+#define ENTRYS_PER_PTE  (1 << PTE_WIDE)
+
+#define PGD_SHIFT  (PUD_SHIFT + PUD_WIDE)
+#define PUD_SHIFT  (PMD_SHIFT + PMD_WIDE)
+#define PMD_SHIFT  (EFI_PAGE_SHIFT + PTE_WIDE)
+#define PTE_SHIFT  (EFI_PAGE_SHIFT)
+
+#define PGD_SIZE  (1UL << PGD_SHIFT)
+#define PUD_SIZE  (1UL << PUD_SHIFT)
+#define PMD_SIZE  (1UL << PMD_SHIFT)
+
+#define PGD_MASK   (~(PGD_SIZE-1))
+#define PUD_MASK   (~(PUD_SIZE-1))
+#define PMD_MASK   (~(PMD_SIZE-1))
+#define PAGE_MASK  (~(EFI_PAGE_SIZE - 1))
+#define PFN_MASK   (~(((UINTN)(1) << (EFI_PAGE_SHIFT)) - 1) & \
+                   (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1))
+
+#define HUGEP_PAGE_MASK  (~(((UINTN)(1) << (PMD_SHIFT)) - 1) & \
+                          (((UINTN)(1) << (PAGE_PFN_END_SHIFT)) - 1)=
)
+
+#define INVALID_PAGE  0
+
+typedef struct {
+  UINTN    PgdVal;
+} PGD;
+typedef struct {
+  UINTN    PudVal;
+} PUD;
+typedef struct {
+  UINTN    PmdVal;
+} PMD;
+typedef struct {
+  UINTN    PteVal;
+} PTE;
+
+/**
+  Gets the value of the page global directory table entry.
+
+  @param  x    Page global directory struct variables.
+
+  @retval   the value of the page global directory table entry.
+ **/
+#define PGD_VAL(x)  ((x).PgdVal)
+
+/**
+  Gets the value of the page upper directory table entry.
+
+  @param  x    Page upper directory struct variables.
+
+  @retval  the value of the page upper directory table entry.
+ **/
+#define PUD_VAL(x)  ((x).PudVal)
+
+/**
+  Gets the value of the page middle directory table entry.
+
+  @param  x    Page middle directory struct variables.
+
+  @retval  the value of the page middle directory table entry.
+ **/
+#define PMD_VAL(x)  ((x).PmdVal)
+
+/**
+  Gets the value of the page table entry.
+
+  @param  x    Page table entry struct variables.
+
+  @retval  the value of the page table entry.
+ **/
+#define PTE_VAL(x)  ((x).PteVal)
+
+#define PGD_TABLE_SIZE  (ENTRYS_PER_PGD * sizeof(PGD))
+#define PUD_TABLE_SIZE  (ENTRYS_PER_PUD * sizeof(PUD))
+#define PMD_TABLE_SIZE  (ENTRYS_PER_PMD * sizeof(PMD))
+#define PTE_TABLE_SIZE  (ENTRYS_PER_PTE * sizeof(PTE))
+
+/**
+  Gets the physical address of the record in the page table entry.
+
+  @param  x    Page table entry struct variables.
+
+  @retval  the value of the physical address.
+ **/
+#define GET_PAGE_ATTRIBUTES(x)  (UINTN) {(PTE_VAL(x) & ~PFN_MASK)}
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the global page directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PGD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PGD_SIZE) & PGD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the page upper directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PUD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PUD_SIZE) & PUD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Gets the virtual address of the next block of the specified virtual addr=
ess
+  that is aligned with the size of the page middle directory mapping.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the specified virtual address  of the next block.
+ **/
+#define PMD_ADDRESS_END(Address, End)                  \
+({                                                     \
+  UINTN Boundary =3D ((Address) + PMD_SIZE) & PMD_MASK;  \
+  (Boundary - 1 < (End) - 1)? Boundary: (End);         \
+})
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 global directory table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page global directory table entry.
+ **/
+#define PGD_INDEX(Address)  (((Address) >> PGD_SHIFT) & (ENTRYS_=
PER_PGD-1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 upper directory table entry.
+
+  @param  Address  Specifies the virtual address.
+  @param  End    The end address of the memory region.
+
+  @retval   the index of the page upper directory table entry.
+ **/
+#define PUD_INDEX(Address)  (((Address) >> PUD_SHIFT) & (ENTRYS_=
PER_PUD - 1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 middle directory table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page middle directory table entry.
+ **/
+#define PMD_INDEX(Address)  (((Address) >> PMD_SHIFT) & (ENTRYS_=
PER_PMD - 1))
+
+/**
+  Get Specifies the virtual address corresponding to the index of the page=
 table entry.
+
+  @param  Address  Specifies the virtual address.
+
+  @retval   the index of the page table entry.
+ **/
+#define PTE_INDEX(Address)  (((Address) >> EFI_PAGE_SHIFT) & (EN=
TRYS_PER_PTE - 1))
+
+/**
+  Calculates the value of the page table entry based on the specified virt=
ual address and properties.
+
+  @param  Address  Specifies the virtual address.
+  @param  Attributes  Specifies the Attributes.
+
+  @retval    the value of the page table entry.
+ **/
+#define MAKE_PTE(Address, Attributes)  (PTE){((((Address) >> EFI_PAG=
E_SHIFT) << 12) | (Attributes))}
+
+/**
+  Get Global bit from Attributes
+
+  @param  Attributes  Specifies the Attributes.
+ * */
+#define GET_GLOBALBIT(Attributes)  ((Attributes & PAGE_GLOBAL) >>=
; PAGE_GLOBAL_SHIFT)
+
+/**
+  Calculates the value of the Huge page table entry based on the specified=
 virtual address and properties.
+
+  @param  Address  Specifies the virtual address.
+  @param  Attributes  Specifies the Attributes.
+
+  @retval    the value of the HUGE page table entry.
+ **/
+#define MAKE_HUGE_PTE(Address, Attributes)  (PTE){(((((Address) >> P=
MD_SHIFT) << PMD_SHIFT) | \
+                                             ((Attributes) | (GET_GLOBALBI=
T(Attributes) << PAGE_HGLOBAL_SHIFT) | \
+                                             PAGE_HUGE)))}
+
+/**
+  Check whether the large page table entry is.
+
+  @param  Val The value of the page table entry.
+
+  @retval    1   Is huge page table entry.
+  @retval    0   Isn't huge page table entry.
+**/
+#define IS_HUGE_PAGE(Val)  ((((Val) & PAGE_HUGE) =3D=3D PAGE_HUGE) &am=
p;& \
+                            (((Val) & PAGE_HGLOBAL) =3D=3D PAGE_HGLOBA=
L))
+
+#define HUGE_PAGE_SIZE  (PMD_SIZE)
+
+/**
+  Check that the global page directory table entry is empty.
+
+  @param  pgd   the global page directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PGD_IS_EMPTY(Val)  (PGD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page upper directory table entry is empty.
+
+  @param  pud   Page upper directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PUD_IS_EMPTY(Val)  (PUD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page middle directory table entry is empty.
+
+  @param  pmd   Page middle directory struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PMD_IS_EMPTY(Val)  (PMD_VAL(Val) =3D=3D INVALID_PAGE)
+
+/**
+  Check that the page the page table entry is empty.
+
+  @param  pte   Page table entry struct variables.
+
+  @retval    1   The page table is invalid.
+  @retval    0   The page table is valid.
+**/
+#define PTE_IS_EMPTY(Val)  (!(PTE_VAL(Val) & (~PAGE_VALID)))
+#endif // PAGE_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c b/UefiC=
puPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c
new file mode 100644
index 0000000000..42a424b84d
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.c
@@ -0,0 +1,165 @@
+/** @file
+  CPU Memory Map Unit PEI phase driver.
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+  @par Glossary:
+    - Tlb      - Translation Lookaside Buffer
+**/
+
+#include <Uefi.h>
+#include <Library/BaseMemoryLib.h>
+#include <Library/MemoryAllocationLib.h>
+#include <Library/BaseLib.h>
+#include <Library/DebugLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Library/CacheMaintenanceLib.h>
+#include <Library/CpuMmuLib.h>
+#include <Register/LoongArch64/Csr.h>
+
+#include "Page.h"
+#include "Tlb.h"
+#include "CommonMmuLib.h"
+
+/**
+  Create a page table and initialize the memory management unit(MMU).
+
+  @param[in]   MemoryTable           A pointer to a memory ragion table.
+  @param[out]  TranslationTableBase  A pointer to a translation table base=
 address.
+  @param[out]  TranslationTableSize  A pointer to a translation table base=
 size.
+
+  @retval  EFI_SUCCESS                Configure MMU successfully.
+           EFI_INVALID_PARAMETER      MemoryTable is NULL.
+           EFI_UNSUPPORTED            Out of memory space or size not alig=
ned.
+**/
+EFI_STATUS
+EFIAPI
+ConfigureMemoryManagementUint (
+  IN  MEMORY_REGION_DESCRIPTOR  *MemoryTable,
+  OUT VOID                      **TranslationTableBase OPTIONAL,
+  OUT UINTN                     *TranslationTableSize  OPTIONAL
+  )
+{
+  PGD            *SwapperPageDir;
+  UINTN          PgdShift;
+  UINTN          PgdWide;
+  UINTN          PudShift;
+  UINTN          PudWide;
+  UINTN          PmdShift;
+  UINTN          PmdWide;
+  UINTN          PteShift;
+  UINTN          PteWide;
+  UINTN          Length;
+  UINTN          TlbReEntry;
+  UINTN          TlbReEntryOffset;
+  RETURN_STATUS  Status;
+
+  SwapperPageDir =3D NULL;
+  PgdShift       =3D PGD_SHIFT;
+  PgdWide        =3D PGD_WIDE;
+  PudShift       =3D PUD_SHIFT;
+  PudWide        =3D PUD_WIDE;
+  PmdShift       =3D PMD_SHIFT;
+  PmdWide        =3D PMD_WIDE;
+  PteShift       =3D PTE_SHIFT;
+  PteWide        =3D PTE_WIDE;
+
+  if (MemoryTable =3D=3D NULL) {
+    ASSERT (MemoryTable !=3D NULL);
+    return EFI_INVALID_PARAMETER;
+  }
+
+  SwapperPageDir =3D AllocatePages (EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+  ZeroMem (SwapperPageDir, PGD_TABLE_SIZE);
+
+  if (SwapperPageDir =3D=3D NULL) {
+    goto FreeTranslationTable;
+  }
+
+  CsrWrite (LOONGARCH_CSR_PGDL, (UINTN)SwapperPageDir);
+
+  while (MemoryTable->Length !=3D 0) {
+    DEBUG ((
+      DEBUG_INFO,
+      "%a %d VirtualBase %p VirtualEnd %p Attributes %p .\n",
+      __func__,
+      __LINE__,
+      MemoryTable->VirtualBase,
+      (MemoryTable->Length + MemoryTable->VirtualBase),
+      MemoryTable->Attributes
+      ));
+
+    Status =3D FillTranslationTable (MemoryTable);
+    if (EFI_ERROR (Status)) {
+      goto FreeTranslationTable;
+    }
+
+    MemoryTable++;
+  }
+
+  //
+  // TLB Re-entry address at the end of exception vector, a vector is up t=
o 512 bytes,
+  // so the starting address is: total exception vector size + total inter=
rupt vector size + base.
+  // The total size of TLB handler and exception vector size and interrupt=
 vector size should not
+  // be lager than 64KB.
+  //
+  Length           =3D (UINTN)HandleTlbRefillEnd - (UINTN)HandleTlbRefillS=
tart;
+  TlbReEntryOffset =3D (MAX_LOONGARCH_EXCEPTION + MAX_LOONGARCH_INTERRUPT)=
 * 512;
+  TlbReEntry       =3D PcdGet64 (PcdCpuExceptionVectorBaseAddress) + TlbRe=
EntryOffset;
+  if ((TlbReEntryOffset + Length) > SIZE_64KB) {
+    goto FreeTranslationTable;
+  }
+
+  //
+  // Make sure TLB refill exception base address alignment is greater than=
 or equal to 4KB and valid
+  //
+  if (TlbReEntry & (SIZE_4KB - 1)) {
+    goto FreeTranslationTable;
+  }
+
+  CopyMem ((VOID *)TlbReEntry, HandleTlbRefillStart, Length);
+  InvalidateInstructionCacheRange ((VOID *)(UINTN)HandleTlbRefillStart, Le=
ngth);
+
+  DEBUG ((
+    DEBUG_INFO,
+    "%a  %d PteShift %d PteWide %d PmdShift %d PmdWide %d PudShift %d PudW=
ide %d PgdShift %d PgdWide %d.\n",
+    __func__,
+    __LINE__,
+    PteShift,
+    PteWide,
+    PmdShift,
+    PmdWide,
+    PudShift,
+    PudWide,
+    PgdShift,
+    PgdWide
+    ));
+
+  //
+  // Set the address of TLB refill exception handler
+  //
+  SetTlbRebaseAddress ((UINTN)TlbReEntry);
+
+  //
+  // Set page size
+  //
+  CsrXChg (LOONGARCH_CSR_TLBIDX, (DEFAULT_PAGE_SIZE << CSR_TLBIDX_SI=
ZE), CSR_TLBIDX_SIZE_MASK);
+  CsrWrite (LOONGARCH_CSR_STLBPGSIZE, DEFAULT_PAGE_SIZE);
+  CsrXChg (LOONGARCH_CSR_TLBREHI, (DEFAULT_PAGE_SIZE << CSR_TLBREHI_=
PS_SHIFT), CSR_TLBREHI_PS);
+
+  CsrWrite (LOONGARCH_CSR_PWCTL0, (PteShift | PteWide << 5 | PmdShif=
t << 10 | PmdWide << 15 | PudShift << 20 | PudWide <&l=
t; 25));
+  CsrWrite (LOONGARCH_CSR_PWCTL1, (PgdShift | PgdWide << 6));
+
+  DEBUG ((DEBUG_INFO, "%a %d Enable Mmu Start PageBassAddress %p.\n", __fu=
nc__, __LINE__, SwapperPageDir));
+
+  return EFI_SUCCESS;
+
+FreeTranslationTable:
+  if (SwapperPageDir !=3D NULL) {
+    FreePages (SwapperPageDir, EFI_SIZE_TO_PAGES (PGD_TABLE_SIZE));
+  }
+
+  return EFI_UNSUPPORTED;
+}
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf b/Uef=
iCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf
new file mode 100644
index 0000000000..e746c3b1a7
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf
@@ -0,0 +1,44 @@
+## @file
+#  CPU Memory Map Unit PEI phase driver.
+#
+#  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights =
reserved.<BR>
+#
+#  SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+##
+
+[Defines]
+  INF_VERSION                    =3D 0x00010005
+  BASE_NAME                      =3D PeiCpuMmuLib
+  MODULE_UNI_FILE                =3D PeiCpuMmuLib.uni
+  FILE_GUID                      =3D F67EB983-AC2A-7550-AB69-3BC51A1C895B
+  MODULE_TYPE                    =3D PEIM
+  VERSION_STRING                 =3D 1.0
+  LIBRARY_CLASS                  =3D CpuMmuLib | SEC PEIM
+
+#
+#  VALID_ARCHITECTURES           =3D LOONGARCH64
+#
+
+[Sources]
+  TlbOperation.S   | GCC
+  PeiCpuMmuLib.c
+  CommonMmuLib.c
+  CommonMmuLib.h
+  Tlb.h
+  Page.h
+
+[Packages]
+  MdePkg/MdePkg.dec
+  MdeModulePkg/MdeModulePkg.dec
+  UefiCpuPkg/UefiCpuPkg.dec
+
+[PCD]
+  gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask
+  gUefiCpuPkgTokenSpaceGuid.PcdCpuExceptionVectorBaseAddress
+
+[LibraryClasses]
+  MemoryAllocationLib
+  CacheMaintenanceLib
+  PcdLib
+  DebugLib
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni b/Uef=
iCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni
new file mode 100644
index 0000000000..331500543c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.uni
@@ -0,0 +1,14 @@
+// /** @file
+// CPU Memory Manager Unit library instance for PEI modules.
+//
+// CPU Memory Manager Unit library instance for PEI modules.
+//
+// Copyright (c) 2023, Loongson Technology Corporation Limited. All rights=
 reserved.<BR>
+//
+// SPDX-License-Identifier: BSD-2-Clause-Patent
+//
+// **/
+
+#string STR_MODULE_ABSTRACT             #language en-US "CPU Memory Manage=
r Unit library instance for PEI modules."
+
+#string STR_MODULE_DESCRIPTION          #language en-US "CPU Memory Manage=
r Unit library instance for PEI modules."
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h b/UefiCpuPkg/Lib=
rary/LoongArch64CpuMmuLib/Tlb.h
new file mode 100644
index 0000000000..5d3f80fe34
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/Tlb.h
@@ -0,0 +1,48 @@
+/** @file
+
+  Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+
+  SPDX-License-Identifier: BSD-2-Clause-Patent
+
+**/
+
+#ifndef TLB_H_
+#define TLB_H_
+
+/**
+  Invalid corresponding TLB entries are based on the address given
+
+  @param Address The address corresponding to the invalid page table entry
+
+  @retval  none
+**/
+VOID
+InvalidTlb (
+  UINTN  Address
+  );
+
+/**
+  TLB refill handler start.
+
+  @param  none
+
+  @retval none
+**/
+VOID
+HandleTlbRefillStart (
+  VOID
+  );
+
+/**
+  TLB refill handler end.
+
+  @param  none
+
+  @retval none
+**/
+VOID
+HandleTlbRefillEnd (
+  VOID
+  );
+
+#endif // TLB_H_
diff --git a/UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S b/UefiC=
puPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S
new file mode 100644
index 0000000000..e446f0839c
--- /dev/null
+++ b/UefiCpuPkg/Library/LoongArch64CpuMmuLib/TlbOperation.S
@@ -0,0 +1,44 @@
+#-------------------------------------------------------------------------=
-----
+#
+# TLB operation functions
+#
+# Copyright (c) 2023 Loongson Technology Corporation Limited. All rights r=
eserved.<BR>
+#
+# SPDX-License-Identifier: BSD-2-Clause-Patent
+#
+#-------------------------------------------------------------------------=
----
+
+#include <Register/LoongArch64/Csr.h>
+
+ASM_GLOBAL ASM_PFX(HandleTlbRefillStart)
+ASM_GLOBAL ASM_PFX(HandleTlbRefillEnd)
+ASM_GLOBAL ASM_PFX(InvalidTlb)
+
+#
+#  Refill the page table.
+#  @param  VOID
+#  @retval  VOID
+#
+ASM_PFX(HandleTlbRefillStart):
+  csrwr   $t0, LOONGARCH_CSR_TLBRSAVE
+  csrrd   $t0, LOONGARCH_CSR_PGD
+  lddir   $t0, $t0, 3   #Put pud BaseAddress into T0
+  lddir   $t0, $t0, 2   #Put pmd BaseAddress into T0
+  lddir   $t0, $t0, 1   #Put pte BaseAddress into T0
+  ldpte   $t0, 0
+  ldpte   $t0, 1
+  tlbfill   // refill hi,lo0,lo1
+  csrrd   $t0, LOONGARCH_CSR_TLBRSAVE
+  ertn
+ASM_PFX(HandleTlbRefillEnd):
+
+#
+# Invalid corresponding TLB entries are based on the address given
+# @param a0 The address corresponding to the invalid page table entry
+# @retval  none
+#
+ASM_PFX(InvalidTlb):
+    invtlb  INVTLB_ADDR_GTRUE_OR_ASID, $zero, $a0
+    jirl    $zero, $ra, 0
+
+    .end
diff --git a/UefiCpuPkg/UefiCpuPkg.dsc b/UefiCpuPkg/UefiCpuPkg.dsc
index 872f20fc36..709992d327 100644
--- a/UefiCpuPkg/UefiCpuPkg.dsc
+++ b/UefiCpuPkg/UefiCpuPkg.dsc
@@ -209,6 +209,8 @@
   UefiCpuPkg/Library/BaseLoongArch64CpuTimerLib/BaseLoongArch64CpuTimerLib=
.inf
   UefiCpuPkg/Library/LoongArch64CpuExceptionHandlerLib/SecPeiCpuExceptionH=
andlerLib.inf
   UefiCpuPkg/Library/LoongArch64CpuExceptionHandlerLib/DxeCpuExceptionHand=
lerLib.inf
+  UefiCpuPkg/Library/LoongArch64CpuMmuLib/PeiCpuMmuLib.inf
+  UefiCpuPkg/Library/LoongArch64CpuMmuLib/DxeCpuMmuLib.inf
=20
 [BuildOptions]
   *_*_*_CC_FLAGS =3D -D DISABLE_NEW_DEPRECATED_INTERFACES
_._,_._,_

Groups.io Links:

=20 You receive all messages sent to this group. =20 =20

View/Reply Online (#111465) | =20 | Mute= This Topic | New Topic
Your Subscriptio= n | Contact Group Owner | Unsubscribe [rebecca@openfw.io]

_._,_._,_
--------------RDvPmkobGmCJvBi0hVDVbomp--