Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Based on arch/arm/mm/mmu.c
0004  *
0005  * Copyright (C) 1995-2005 Russell King
0006  * Copyright (C) 2012 ARM Ltd.
0007  */
0008 
0009 #include <linux/cache.h>
0010 #include <linux/export.h>
0011 #include <linux/kernel.h>
0012 #include <linux/errno.h>
0013 #include <linux/init.h>
0014 #include <linux/ioport.h>
0015 #include <linux/kexec.h>
0016 #include <linux/libfdt.h>
0017 #include <linux/mman.h>
0018 #include <linux/nodemask.h>
0019 #include <linux/memblock.h>
0020 #include <linux/memremap.h>
0021 #include <linux/memory.h>
0022 #include <linux/fs.h>
0023 #include <linux/io.h>
0024 #include <linux/mm.h>
0025 #include <linux/vmalloc.h>
0026 #include <linux/set_memory.h>
0027 
0028 #include <asm/barrier.h>
0029 #include <asm/cputype.h>
0030 #include <asm/fixmap.h>
0031 #include <asm/kasan.h>
0032 #include <asm/kernel-pgtable.h>
0033 #include <asm/sections.h>
0034 #include <asm/setup.h>
0035 #include <linux/sizes.h>
0036 #include <asm/tlb.h>
0037 #include <asm/mmu_context.h>
0038 #include <asm/ptdump.h>
0039 #include <asm/tlbflush.h>
0040 #include <asm/pgalloc.h>
0041 
0042 #define NO_BLOCK_MAPPINGS   BIT(0)
0043 #define NO_CONT_MAPPINGS    BIT(1)
0044 #define NO_EXEC_MAPPINGS    BIT(2)  /* assumes FEAT_HPDS is not used */
0045 
0046 int idmap_t0sz __ro_after_init;
0047 
0048 #if VA_BITS > 48
0049 u64 vabits_actual __ro_after_init = VA_BITS_MIN;
0050 EXPORT_SYMBOL(vabits_actual);
0051 #endif
0052 
0053 u64 kimage_vaddr __ro_after_init = (u64)&_text;
0054 EXPORT_SYMBOL(kimage_vaddr);
0055 
0056 u64 kimage_voffset __ro_after_init;
0057 EXPORT_SYMBOL(kimage_voffset);
0058 
0059 u32 __boot_cpu_mode[] = { BOOT_CPU_MODE_EL2, BOOT_CPU_MODE_EL1 };
0060 
0061 /*
0062  * The booting CPU updates the failed status @__early_cpu_boot_status,
0063  * with MMU turned off.
0064  */
0065 long __section(".mmuoff.data.write") __early_cpu_boot_status;
0066 
0067 /*
0068  * Empty_zero_page is a special page that is used for zero-initialized data
0069  * and COW.
0070  */
0071 unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)] __page_aligned_bss;
0072 EXPORT_SYMBOL(empty_zero_page);
0073 
0074 static pte_t bm_pte[PTRS_PER_PTE] __page_aligned_bss;
0075 static pmd_t bm_pmd[PTRS_PER_PMD] __page_aligned_bss __maybe_unused;
0076 static pud_t bm_pud[PTRS_PER_PUD] __page_aligned_bss __maybe_unused;
0077 
0078 static DEFINE_SPINLOCK(swapper_pgdir_lock);
0079 static DEFINE_MUTEX(fixmap_lock);
0080 
0081 void set_swapper_pgd(pgd_t *pgdp, pgd_t pgd)
0082 {
0083     pgd_t *fixmap_pgdp;
0084 
0085     spin_lock(&swapper_pgdir_lock);
0086     fixmap_pgdp = pgd_set_fixmap(__pa_symbol(pgdp));
0087     WRITE_ONCE(*fixmap_pgdp, pgd);
0088     /*
0089      * We need dsb(ishst) here to ensure the page-table-walker sees
0090      * our new entry before set_p?d() returns. The fixmap's
0091      * flush_tlb_kernel_range() via clear_fixmap() does this for us.
0092      */
0093     pgd_clear_fixmap();
0094     spin_unlock(&swapper_pgdir_lock);
0095 }
0096 
0097 pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
0098                   unsigned long size, pgprot_t vma_prot)
0099 {
0100     if (!pfn_is_map_memory(pfn))
0101         return pgprot_noncached(vma_prot);
0102     else if (file->f_flags & O_SYNC)
0103         return pgprot_writecombine(vma_prot);
0104     return vma_prot;
0105 }
0106 EXPORT_SYMBOL(phys_mem_access_prot);
0107 
0108 static phys_addr_t __init early_pgtable_alloc(int shift)
0109 {
0110     phys_addr_t phys;
0111     void *ptr;
0112 
0113     phys = memblock_phys_alloc_range(PAGE_SIZE, PAGE_SIZE, 0,
0114                      MEMBLOCK_ALLOC_NOLEAKTRACE);
0115     if (!phys)
0116         panic("Failed to allocate page table page\n");
0117 
0118     /*
0119      * The FIX_{PGD,PUD,PMD} slots may be in active use, but the FIX_PTE
0120      * slot will be free, so we can (ab)use the FIX_PTE slot to initialise
0121      * any level of table.
0122      */
0123     ptr = pte_set_fixmap(phys);
0124 
0125     memset(ptr, 0, PAGE_SIZE);
0126 
0127     /*
0128      * Implicit barriers also ensure the zeroed page is visible to the page
0129      * table walker
0130      */
0131     pte_clear_fixmap();
0132 
0133     return phys;
0134 }
0135 
0136 static bool pgattr_change_is_safe(u64 old, u64 new)
0137 {
0138     /*
0139      * The following mapping attributes may be updated in live
0140      * kernel mappings without the need for break-before-make.
0141      */
0142     pteval_t mask = PTE_PXN | PTE_RDONLY | PTE_WRITE | PTE_NG;
0143 
0144     /* creating or taking down mappings is always safe */
0145     if (old == 0 || new == 0)
0146         return true;
0147 
0148     /* live contiguous mappings may not be manipulated at all */
0149     if ((old | new) & PTE_CONT)
0150         return false;
0151 
0152     /* Transitioning from Non-Global to Global is unsafe */
0153     if (old & ~new & PTE_NG)
0154         return false;
0155 
0156     /*
0157      * Changing the memory type between Normal and Normal-Tagged is safe
0158      * since Tagged is considered a permission attribute from the
0159      * mismatched attribute aliases perspective.
0160      */
0161     if (((old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
0162          (old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)) &&
0163         ((new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
0164          (new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)))
0165         mask |= PTE_ATTRINDX_MASK;
0166 
0167     return ((old ^ new) & ~mask) == 0;
0168 }
0169 
0170 static void init_pte(pmd_t *pmdp, unsigned long addr, unsigned long end,
0171              phys_addr_t phys, pgprot_t prot)
0172 {
0173     pte_t *ptep;
0174 
0175     ptep = pte_set_fixmap_offset(pmdp, addr);
0176     do {
0177         pte_t old_pte = READ_ONCE(*ptep);
0178 
0179         set_pte(ptep, pfn_pte(__phys_to_pfn(phys), prot));
0180 
0181         /*
0182          * After the PTE entry has been populated once, we
0183          * only allow updates to the permission attributes.
0184          */
0185         BUG_ON(!pgattr_change_is_safe(pte_val(old_pte),
0186                           READ_ONCE(pte_val(*ptep))));
0187 
0188         phys += PAGE_SIZE;
0189     } while (ptep++, addr += PAGE_SIZE, addr != end);
0190 
0191     pte_clear_fixmap();
0192 }
0193 
0194 static void alloc_init_cont_pte(pmd_t *pmdp, unsigned long addr,
0195                 unsigned long end, phys_addr_t phys,
0196                 pgprot_t prot,
0197                 phys_addr_t (*pgtable_alloc)(int),
0198                 int flags)
0199 {
0200     unsigned long next;
0201     pmd_t pmd = READ_ONCE(*pmdp);
0202 
0203     BUG_ON(pmd_sect(pmd));
0204     if (pmd_none(pmd)) {
0205         pmdval_t pmdval = PMD_TYPE_TABLE | PMD_TABLE_UXN;
0206         phys_addr_t pte_phys;
0207 
0208         if (flags & NO_EXEC_MAPPINGS)
0209             pmdval |= PMD_TABLE_PXN;
0210         BUG_ON(!pgtable_alloc);
0211         pte_phys = pgtable_alloc(PAGE_SHIFT);
0212         __pmd_populate(pmdp, pte_phys, pmdval);
0213         pmd = READ_ONCE(*pmdp);
0214     }
0215     BUG_ON(pmd_bad(pmd));
0216 
0217     do {
0218         pgprot_t __prot = prot;
0219 
0220         next = pte_cont_addr_end(addr, end);
0221 
0222         /* use a contiguous mapping if the range is suitably aligned */
0223         if ((((addr | next | phys) & ~CONT_PTE_MASK) == 0) &&
0224             (flags & NO_CONT_MAPPINGS) == 0)
0225             __prot = __pgprot(pgprot_val(prot) | PTE_CONT);
0226 
0227         init_pte(pmdp, addr, next, phys, __prot);
0228 
0229         phys += next - addr;
0230     } while (addr = next, addr != end);
0231 }
0232 
0233 static void init_pmd(pud_t *pudp, unsigned long addr, unsigned long end,
0234              phys_addr_t phys, pgprot_t prot,
0235              phys_addr_t (*pgtable_alloc)(int), int flags)
0236 {
0237     unsigned long next;
0238     pmd_t *pmdp;
0239 
0240     pmdp = pmd_set_fixmap_offset(pudp, addr);
0241     do {
0242         pmd_t old_pmd = READ_ONCE(*pmdp);
0243 
0244         next = pmd_addr_end(addr, end);
0245 
0246         /* try section mapping first */
0247         if (((addr | next | phys) & ~PMD_MASK) == 0 &&
0248             (flags & NO_BLOCK_MAPPINGS) == 0) {
0249             pmd_set_huge(pmdp, phys, prot);
0250 
0251             /*
0252              * After the PMD entry has been populated once, we
0253              * only allow updates to the permission attributes.
0254              */
0255             BUG_ON(!pgattr_change_is_safe(pmd_val(old_pmd),
0256                               READ_ONCE(pmd_val(*pmdp))));
0257         } else {
0258             alloc_init_cont_pte(pmdp, addr, next, phys, prot,
0259                         pgtable_alloc, flags);
0260 
0261             BUG_ON(pmd_val(old_pmd) != 0 &&
0262                    pmd_val(old_pmd) != READ_ONCE(pmd_val(*pmdp)));
0263         }
0264         phys += next - addr;
0265     } while (pmdp++, addr = next, addr != end);
0266 
0267     pmd_clear_fixmap();
0268 }
0269 
0270 static void alloc_init_cont_pmd(pud_t *pudp, unsigned long addr,
0271                 unsigned long end, phys_addr_t phys,
0272                 pgprot_t prot,
0273                 phys_addr_t (*pgtable_alloc)(int), int flags)
0274 {
0275     unsigned long next;
0276     pud_t pud = READ_ONCE(*pudp);
0277 
0278     /*
0279      * Check for initial section mappings in the pgd/pud.
0280      */
0281     BUG_ON(pud_sect(pud));
0282     if (pud_none(pud)) {
0283         pudval_t pudval = PUD_TYPE_TABLE | PUD_TABLE_UXN;
0284         phys_addr_t pmd_phys;
0285 
0286         if (flags & NO_EXEC_MAPPINGS)
0287             pudval |= PUD_TABLE_PXN;
0288         BUG_ON(!pgtable_alloc);
0289         pmd_phys = pgtable_alloc(PMD_SHIFT);
0290         __pud_populate(pudp, pmd_phys, pudval);
0291         pud = READ_ONCE(*pudp);
0292     }
0293     BUG_ON(pud_bad(pud));
0294 
0295     do {
0296         pgprot_t __prot = prot;
0297 
0298         next = pmd_cont_addr_end(addr, end);
0299 
0300         /* use a contiguous mapping if the range is suitably aligned */
0301         if ((((addr | next | phys) & ~CONT_PMD_MASK) == 0) &&
0302             (flags & NO_CONT_MAPPINGS) == 0)
0303             __prot = __pgprot(pgprot_val(prot) | PTE_CONT);
0304 
0305         init_pmd(pudp, addr, next, phys, __prot, pgtable_alloc, flags);
0306 
0307         phys += next - addr;
0308     } while (addr = next, addr != end);
0309 }
0310 
0311 static void alloc_init_pud(pgd_t *pgdp, unsigned long addr, unsigned long end,
0312                phys_addr_t phys, pgprot_t prot,
0313                phys_addr_t (*pgtable_alloc)(int),
0314                int flags)
0315 {
0316     unsigned long next;
0317     pud_t *pudp;
0318     p4d_t *p4dp = p4d_offset(pgdp, addr);
0319     p4d_t p4d = READ_ONCE(*p4dp);
0320 
0321     if (p4d_none(p4d)) {
0322         p4dval_t p4dval = P4D_TYPE_TABLE | P4D_TABLE_UXN;
0323         phys_addr_t pud_phys;
0324 
0325         if (flags & NO_EXEC_MAPPINGS)
0326             p4dval |= P4D_TABLE_PXN;
0327         BUG_ON(!pgtable_alloc);
0328         pud_phys = pgtable_alloc(PUD_SHIFT);
0329         __p4d_populate(p4dp, pud_phys, p4dval);
0330         p4d = READ_ONCE(*p4dp);
0331     }
0332     BUG_ON(p4d_bad(p4d));
0333 
0334     pudp = pud_set_fixmap_offset(p4dp, addr);
0335     do {
0336         pud_t old_pud = READ_ONCE(*pudp);
0337 
0338         next = pud_addr_end(addr, end);
0339 
0340         /*
0341          * For 4K granule only, attempt to put down a 1GB block
0342          */
0343         if (pud_sect_supported() &&
0344            ((addr | next | phys) & ~PUD_MASK) == 0 &&
0345             (flags & NO_BLOCK_MAPPINGS) == 0) {
0346             pud_set_huge(pudp, phys, prot);
0347 
0348             /*
0349              * After the PUD entry has been populated once, we
0350              * only allow updates to the permission attributes.
0351              */
0352             BUG_ON(!pgattr_change_is_safe(pud_val(old_pud),
0353                               READ_ONCE(pud_val(*pudp))));
0354         } else {
0355             alloc_init_cont_pmd(pudp, addr, next, phys, prot,
0356                         pgtable_alloc, flags);
0357 
0358             BUG_ON(pud_val(old_pud) != 0 &&
0359                    pud_val(old_pud) != READ_ONCE(pud_val(*pudp)));
0360         }
0361         phys += next - addr;
0362     } while (pudp++, addr = next, addr != end);
0363 
0364     pud_clear_fixmap();
0365 }
0366 
0367 static void __create_pgd_mapping_locked(pgd_t *pgdir, phys_addr_t phys,
0368                     unsigned long virt, phys_addr_t size,
0369                     pgprot_t prot,
0370                     phys_addr_t (*pgtable_alloc)(int),
0371                     int flags)
0372 {
0373     unsigned long addr, end, next;
0374     pgd_t *pgdp = pgd_offset_pgd(pgdir, virt);
0375 
0376     /*
0377      * If the virtual and physical address don't have the same offset
0378      * within a page, we cannot map the region as the caller expects.
0379      */
0380     if (WARN_ON((phys ^ virt) & ~PAGE_MASK))
0381         return;
0382 
0383     phys &= PAGE_MASK;
0384     addr = virt & PAGE_MASK;
0385     end = PAGE_ALIGN(virt + size);
0386 
0387     do {
0388         next = pgd_addr_end(addr, end);
0389         alloc_init_pud(pgdp, addr, next, phys, prot, pgtable_alloc,
0390                    flags);
0391         phys += next - addr;
0392     } while (pgdp++, addr = next, addr != end);
0393 }
0394 
0395 static void __create_pgd_mapping(pgd_t *pgdir, phys_addr_t phys,
0396                  unsigned long virt, phys_addr_t size,
0397                  pgprot_t prot,
0398                  phys_addr_t (*pgtable_alloc)(int),
0399                  int flags)
0400 {
0401     mutex_lock(&fixmap_lock);
0402     __create_pgd_mapping_locked(pgdir, phys, virt, size, prot,
0403                     pgtable_alloc, flags);
0404     mutex_unlock(&fixmap_lock);
0405 }
0406 
0407 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
0408 extern __alias(__create_pgd_mapping_locked)
0409 void create_kpti_ng_temp_pgd(pgd_t *pgdir, phys_addr_t phys, unsigned long virt,
0410                  phys_addr_t size, pgprot_t prot,
0411                  phys_addr_t (*pgtable_alloc)(int), int flags);
0412 #endif
0413 
0414 static phys_addr_t __pgd_pgtable_alloc(int shift)
0415 {
0416     void *ptr = (void *)__get_free_page(GFP_PGTABLE_KERNEL);
0417     BUG_ON(!ptr);
0418 
0419     /* Ensure the zeroed page is visible to the page table walker */
0420     dsb(ishst);
0421     return __pa(ptr);
0422 }
0423 
0424 static phys_addr_t pgd_pgtable_alloc(int shift)
0425 {
0426     phys_addr_t pa = __pgd_pgtable_alloc(shift);
0427 
0428     /*
0429      * Call proper page table ctor in case later we need to
0430      * call core mm functions like apply_to_page_range() on
0431      * this pre-allocated page table.
0432      *
0433      * We don't select ARCH_ENABLE_SPLIT_PMD_PTLOCK if pmd is
0434      * folded, and if so pgtable_pmd_page_ctor() becomes nop.
0435      */
0436     if (shift == PAGE_SHIFT)
0437         BUG_ON(!pgtable_pte_page_ctor(phys_to_page(pa)));
0438     else if (shift == PMD_SHIFT)
0439         BUG_ON(!pgtable_pmd_page_ctor(phys_to_page(pa)));
0440 
0441     return pa;
0442 }
0443 
0444 /*
0445  * This function can only be used to modify existing table entries,
0446  * without allocating new levels of table. Note that this permits the
0447  * creation of new section or page entries.
0448  */
0449 static void __init create_mapping_noalloc(phys_addr_t phys, unsigned long virt,
0450                   phys_addr_t size, pgprot_t prot)
0451 {
0452     if ((virt >= PAGE_END) && (virt < VMALLOC_START)) {
0453         pr_warn("BUG: not creating mapping for %pa at 0x%016lx - outside kernel range\n",
0454             &phys, virt);
0455         return;
0456     }
0457     __create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
0458                  NO_CONT_MAPPINGS);
0459 }
0460 
0461 void __init create_pgd_mapping(struct mm_struct *mm, phys_addr_t phys,
0462                    unsigned long virt, phys_addr_t size,
0463                    pgprot_t prot, bool page_mappings_only)
0464 {
0465     int flags = 0;
0466 
0467     BUG_ON(mm == &init_mm);
0468 
0469     if (page_mappings_only)
0470         flags = NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
0471 
0472     __create_pgd_mapping(mm->pgd, phys, virt, size, prot,
0473                  pgd_pgtable_alloc, flags);
0474 }
0475 
0476 static void update_mapping_prot(phys_addr_t phys, unsigned long virt,
0477                 phys_addr_t size, pgprot_t prot)
0478 {
0479     if ((virt >= PAGE_END) && (virt < VMALLOC_START)) {
0480         pr_warn("BUG: not updating mapping for %pa at 0x%016lx - outside kernel range\n",
0481             &phys, virt);
0482         return;
0483     }
0484 
0485     __create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
0486                  NO_CONT_MAPPINGS);
0487 
0488     /* flush the TLBs after updating live kernel mappings */
0489     flush_tlb_kernel_range(virt, virt + size);
0490 }
0491 
0492 static void __init __map_memblock(pgd_t *pgdp, phys_addr_t start,
0493                   phys_addr_t end, pgprot_t prot, int flags)
0494 {
0495     __create_pgd_mapping(pgdp, start, __phys_to_virt(start), end - start,
0496                  prot, early_pgtable_alloc, flags);
0497 }
0498 
0499 void __init mark_linear_text_alias_ro(void)
0500 {
0501     /*
0502      * Remove the write permissions from the linear alias of .text/.rodata
0503      */
0504     update_mapping_prot(__pa_symbol(_stext), (unsigned long)lm_alias(_stext),
0505                 (unsigned long)__init_begin - (unsigned long)_stext,
0506                 PAGE_KERNEL_RO);
0507 }
0508 
0509 static bool crash_mem_map __initdata;
0510 
0511 static int __init enable_crash_mem_map(char *arg)
0512 {
0513     /*
0514      * Proper parameter parsing is done by reserve_crashkernel(). We only
0515      * need to know if the linear map has to avoid block mappings so that
0516      * the crashkernel reservations can be unmapped later.
0517      */
0518     crash_mem_map = true;
0519 
0520     return 0;
0521 }
0522 early_param("crashkernel", enable_crash_mem_map);
0523 
0524 static void __init map_mem(pgd_t *pgdp)
0525 {
0526     static const u64 direct_map_end = _PAGE_END(VA_BITS_MIN);
0527     phys_addr_t kernel_start = __pa_symbol(_stext);
0528     phys_addr_t kernel_end = __pa_symbol(__init_begin);
0529     phys_addr_t start, end;
0530     int flags = NO_EXEC_MAPPINGS;
0531     u64 i;
0532 
0533     /*
0534      * Setting hierarchical PXNTable attributes on table entries covering
0535      * the linear region is only possible if it is guaranteed that no table
0536      * entries at any level are being shared between the linear region and
0537      * the vmalloc region. Check whether this is true for the PGD level, in
0538      * which case it is guaranteed to be true for all other levels as well.
0539      */
0540     BUILD_BUG_ON(pgd_index(direct_map_end - 1) == pgd_index(direct_map_end));
0541 
0542     if (can_set_direct_map() || IS_ENABLED(CONFIG_KFENCE))
0543         flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
0544 
0545     /*
0546      * Take care not to create a writable alias for the
0547      * read-only text and rodata sections of the kernel image.
0548      * So temporarily mark them as NOMAP to skip mappings in
0549      * the following for-loop
0550      */
0551     memblock_mark_nomap(kernel_start, kernel_end - kernel_start);
0552 
0553 #ifdef CONFIG_KEXEC_CORE
0554     if (crash_mem_map) {
0555         if (defer_reserve_crashkernel())
0556             flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
0557         else if (crashk_res.end)
0558             memblock_mark_nomap(crashk_res.start,
0559                 resource_size(&crashk_res));
0560     }
0561 #endif
0562 
0563     /* map all the memory banks */
0564     for_each_mem_range(i, &start, &end) {
0565         if (start >= end)
0566             break;
0567         /*
0568          * The linear map must allow allocation tags reading/writing
0569          * if MTE is present. Otherwise, it has the same attributes as
0570          * PAGE_KERNEL.
0571          */
0572         __map_memblock(pgdp, start, end, pgprot_tagged(PAGE_KERNEL),
0573                    flags);
0574     }
0575 
0576     /*
0577      * Map the linear alias of the [_stext, __init_begin) interval
0578      * as non-executable now, and remove the write permission in
0579      * mark_linear_text_alias_ro() below (which will be called after
0580      * alternative patching has completed). This makes the contents
0581      * of the region accessible to subsystems such as hibernate,
0582      * but protects it from inadvertent modification or execution.
0583      * Note that contiguous mappings cannot be remapped in this way,
0584      * so we should avoid them here.
0585      */
0586     __map_memblock(pgdp, kernel_start, kernel_end,
0587                PAGE_KERNEL, NO_CONT_MAPPINGS);
0588     memblock_clear_nomap(kernel_start, kernel_end - kernel_start);
0589 
0590     /*
0591      * Use page-level mappings here so that we can shrink the region
0592      * in page granularity and put back unused memory to buddy system
0593      * through /sys/kernel/kexec_crash_size interface.
0594      */
0595 #ifdef CONFIG_KEXEC_CORE
0596     if (crash_mem_map && !defer_reserve_crashkernel()) {
0597         if (crashk_res.end) {
0598             __map_memblock(pgdp, crashk_res.start,
0599                        crashk_res.end + 1,
0600                        PAGE_KERNEL,
0601                        NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS);
0602             memblock_clear_nomap(crashk_res.start,
0603                          resource_size(&crashk_res));
0604         }
0605     }
0606 #endif
0607 }
0608 
0609 void mark_rodata_ro(void)
0610 {
0611     unsigned long section_size;
0612 
0613     /*
0614      * mark .rodata as read only. Use __init_begin rather than __end_rodata
0615      * to cover NOTES and EXCEPTION_TABLE.
0616      */
0617     section_size = (unsigned long)__init_begin - (unsigned long)__start_rodata;
0618     update_mapping_prot(__pa_symbol(__start_rodata), (unsigned long)__start_rodata,
0619                 section_size, PAGE_KERNEL_RO);
0620 
0621     debug_checkwx();
0622 }
0623 
0624 static void __init map_kernel_segment(pgd_t *pgdp, void *va_start, void *va_end,
0625                       pgprot_t prot, struct vm_struct *vma,
0626                       int flags, unsigned long vm_flags)
0627 {
0628     phys_addr_t pa_start = __pa_symbol(va_start);
0629     unsigned long size = va_end - va_start;
0630 
0631     BUG_ON(!PAGE_ALIGNED(pa_start));
0632     BUG_ON(!PAGE_ALIGNED(size));
0633 
0634     __create_pgd_mapping(pgdp, pa_start, (unsigned long)va_start, size, prot,
0635                  early_pgtable_alloc, flags);
0636 
0637     if (!(vm_flags & VM_NO_GUARD))
0638         size += PAGE_SIZE;
0639 
0640     vma->addr   = va_start;
0641     vma->phys_addr  = pa_start;
0642     vma->size   = size;
0643     vma->flags  = VM_MAP | vm_flags;
0644     vma->caller = __builtin_return_address(0);
0645 
0646     vm_area_add_early(vma);
0647 }
0648 
0649 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
0650 static int __init map_entry_trampoline(void)
0651 {
0652     int i;
0653 
0654     pgprot_t prot = rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
0655     phys_addr_t pa_start = __pa_symbol(__entry_tramp_text_start);
0656 
0657     /* The trampoline is always mapped and can therefore be global */
0658     pgprot_val(prot) &= ~PTE_NG;
0659 
0660     /* Map only the text into the trampoline page table */
0661     memset(tramp_pg_dir, 0, PGD_SIZE);
0662     __create_pgd_mapping(tramp_pg_dir, pa_start, TRAMP_VALIAS,
0663                  entry_tramp_text_size(), prot,
0664                  __pgd_pgtable_alloc, NO_BLOCK_MAPPINGS);
0665 
0666     /* Map both the text and data into the kernel page table */
0667     for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++)
0668         __set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
0669                  pa_start + i * PAGE_SIZE, prot);
0670 
0671     if (IS_ENABLED(CONFIG_RELOCATABLE))
0672         __set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
0673                  pa_start + i * PAGE_SIZE, PAGE_KERNEL_RO);
0674 
0675     return 0;
0676 }
0677 core_initcall(map_entry_trampoline);
0678 #endif
0679 
0680 /*
0681  * Open coded check for BTI, only for use to determine configuration
0682  * for early mappings for before the cpufeature code has run.
0683  */
0684 static bool arm64_early_this_cpu_has_bti(void)
0685 {
0686     u64 pfr1;
0687 
0688     if (!IS_ENABLED(CONFIG_ARM64_BTI_KERNEL))
0689         return false;
0690 
0691     pfr1 = __read_sysreg_by_encoding(SYS_ID_AA64PFR1_EL1);
0692     return cpuid_feature_extract_unsigned_field(pfr1,
0693                             ID_AA64PFR1_BT_SHIFT);
0694 }
0695 
0696 /*
0697  * Create fine-grained mappings for the kernel.
0698  */
0699 static void __init map_kernel(pgd_t *pgdp)
0700 {
0701     static struct vm_struct vmlinux_text, vmlinux_rodata, vmlinux_inittext,
0702                 vmlinux_initdata, vmlinux_data;
0703 
0704     /*
0705      * External debuggers may need to write directly to the text
0706      * mapping to install SW breakpoints. Allow this (only) when
0707      * explicitly requested with rodata=off.
0708      */
0709     pgprot_t text_prot = rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
0710 
0711     /*
0712      * If we have a CPU that supports BTI and a kernel built for
0713      * BTI then mark the kernel executable text as guarded pages
0714      * now so we don't have to rewrite the page tables later.
0715      */
0716     if (arm64_early_this_cpu_has_bti())
0717         text_prot = __pgprot_modify(text_prot, PTE_GP, PTE_GP);
0718 
0719     /*
0720      * Only rodata will be remapped with different permissions later on,
0721      * all other segments are allowed to use contiguous mappings.
0722      */
0723     map_kernel_segment(pgdp, _stext, _etext, text_prot, &vmlinux_text, 0,
0724                VM_NO_GUARD);
0725     map_kernel_segment(pgdp, __start_rodata, __inittext_begin, PAGE_KERNEL,
0726                &vmlinux_rodata, NO_CONT_MAPPINGS, VM_NO_GUARD);
0727     map_kernel_segment(pgdp, __inittext_begin, __inittext_end, text_prot,
0728                &vmlinux_inittext, 0, VM_NO_GUARD);
0729     map_kernel_segment(pgdp, __initdata_begin, __initdata_end, PAGE_KERNEL,
0730                &vmlinux_initdata, 0, VM_NO_GUARD);
0731     map_kernel_segment(pgdp, _data, _end, PAGE_KERNEL, &vmlinux_data, 0, 0);
0732 
0733     if (!READ_ONCE(pgd_val(*pgd_offset_pgd(pgdp, FIXADDR_START)))) {
0734         /*
0735          * The fixmap falls in a separate pgd to the kernel, and doesn't
0736          * live in the carveout for the swapper_pg_dir. We can simply
0737          * re-use the existing dir for the fixmap.
0738          */
0739         set_pgd(pgd_offset_pgd(pgdp, FIXADDR_START),
0740             READ_ONCE(*pgd_offset_k(FIXADDR_START)));
0741     } else if (CONFIG_PGTABLE_LEVELS > 3) {
0742         pgd_t *bm_pgdp;
0743         p4d_t *bm_p4dp;
0744         pud_t *bm_pudp;
0745         /*
0746          * The fixmap shares its top level pgd entry with the kernel
0747          * mapping. This can really only occur when we are running
0748          * with 16k/4 levels, so we can simply reuse the pud level
0749          * entry instead.
0750          */
0751         BUG_ON(!IS_ENABLED(CONFIG_ARM64_16K_PAGES));
0752         bm_pgdp = pgd_offset_pgd(pgdp, FIXADDR_START);
0753         bm_p4dp = p4d_offset(bm_pgdp, FIXADDR_START);
0754         bm_pudp = pud_set_fixmap_offset(bm_p4dp, FIXADDR_START);
0755         pud_populate(&init_mm, bm_pudp, lm_alias(bm_pmd));
0756         pud_clear_fixmap();
0757     } else {
0758         BUG();
0759     }
0760 
0761     kasan_copy_shadow(pgdp);
0762 }
0763 
0764 static void __init create_idmap(void)
0765 {
0766     u64 start = __pa_symbol(__idmap_text_start);
0767     u64 size = __pa_symbol(__idmap_text_end) - start;
0768     pgd_t *pgd = idmap_pg_dir;
0769     u64 pgd_phys;
0770 
0771     /* check if we need an additional level of translation */
0772     if (VA_BITS < 48 && idmap_t0sz < (64 - VA_BITS_MIN)) {
0773         pgd_phys = early_pgtable_alloc(PAGE_SHIFT);
0774         set_pgd(&idmap_pg_dir[start >> VA_BITS],
0775             __pgd(pgd_phys | P4D_TYPE_TABLE));
0776         pgd = __va(pgd_phys);
0777     }
0778     __create_pgd_mapping(pgd, start, start, size, PAGE_KERNEL_ROX,
0779                  early_pgtable_alloc, 0);
0780 
0781     if (IS_ENABLED(CONFIG_UNMAP_KERNEL_AT_EL0)) {
0782         extern u32 __idmap_kpti_flag;
0783         u64 pa = __pa_symbol(&__idmap_kpti_flag);
0784 
0785         /*
0786          * The KPTI G-to-nG conversion code needs a read-write mapping
0787          * of its synchronization flag in the ID map.
0788          */
0789         __create_pgd_mapping(pgd, pa, pa, sizeof(u32), PAGE_KERNEL,
0790                      early_pgtable_alloc, 0);
0791     }
0792 }
0793 
0794 void __init paging_init(void)
0795 {
0796     pgd_t *pgdp = pgd_set_fixmap(__pa_symbol(swapper_pg_dir));
0797     extern pgd_t init_idmap_pg_dir[];
0798 
0799     idmap_t0sz = 63UL - __fls(__pa_symbol(_end) | GENMASK(VA_BITS_MIN - 1, 0));
0800 
0801     map_kernel(pgdp);
0802     map_mem(pgdp);
0803 
0804     pgd_clear_fixmap();
0805 
0806     cpu_replace_ttbr1(lm_alias(swapper_pg_dir), init_idmap_pg_dir);
0807     init_mm.pgd = swapper_pg_dir;
0808 
0809     memblock_phys_free(__pa_symbol(init_pg_dir),
0810                __pa_symbol(init_pg_end) - __pa_symbol(init_pg_dir));
0811 
0812     memblock_allow_resize();
0813 
0814     create_idmap();
0815 }
0816 
0817 /*
0818  * Check whether a kernel address is valid (derived from arch/x86/).
0819  */
0820 int kern_addr_valid(unsigned long addr)
0821 {
0822     pgd_t *pgdp;
0823     p4d_t *p4dp;
0824     pud_t *pudp, pud;
0825     pmd_t *pmdp, pmd;
0826     pte_t *ptep, pte;
0827 
0828     addr = arch_kasan_reset_tag(addr);
0829     if ((((long)addr) >> VA_BITS) != -1UL)
0830         return 0;
0831 
0832     pgdp = pgd_offset_k(addr);
0833     if (pgd_none(READ_ONCE(*pgdp)))
0834         return 0;
0835 
0836     p4dp = p4d_offset(pgdp, addr);
0837     if (p4d_none(READ_ONCE(*p4dp)))
0838         return 0;
0839 
0840     pudp = pud_offset(p4dp, addr);
0841     pud = READ_ONCE(*pudp);
0842     if (pud_none(pud))
0843         return 0;
0844 
0845     if (pud_sect(pud))
0846         return pfn_valid(pud_pfn(pud));
0847 
0848     pmdp = pmd_offset(pudp, addr);
0849     pmd = READ_ONCE(*pmdp);
0850     if (pmd_none(pmd))
0851         return 0;
0852 
0853     if (pmd_sect(pmd))
0854         return pfn_valid(pmd_pfn(pmd));
0855 
0856     ptep = pte_offset_kernel(pmdp, addr);
0857     pte = READ_ONCE(*ptep);
0858     if (pte_none(pte))
0859         return 0;
0860 
0861     return pfn_valid(pte_pfn(pte));
0862 }
0863 
0864 #ifdef CONFIG_MEMORY_HOTPLUG
0865 static void free_hotplug_page_range(struct page *page, size_t size,
0866                     struct vmem_altmap *altmap)
0867 {
0868     if (altmap) {
0869         vmem_altmap_free(altmap, size >> PAGE_SHIFT);
0870     } else {
0871         WARN_ON(PageReserved(page));
0872         free_pages((unsigned long)page_address(page), get_order(size));
0873     }
0874 }
0875 
0876 static void free_hotplug_pgtable_page(struct page *page)
0877 {
0878     free_hotplug_page_range(page, PAGE_SIZE, NULL);
0879 }
0880 
0881 static bool pgtable_range_aligned(unsigned long start, unsigned long end,
0882                   unsigned long floor, unsigned long ceiling,
0883                   unsigned long mask)
0884 {
0885     start &= mask;
0886     if (start < floor)
0887         return false;
0888 
0889     if (ceiling) {
0890         ceiling &= mask;
0891         if (!ceiling)
0892             return false;
0893     }
0894 
0895     if (end - 1 > ceiling - 1)
0896         return false;
0897     return true;
0898 }
0899 
0900 static void unmap_hotplug_pte_range(pmd_t *pmdp, unsigned long addr,
0901                     unsigned long end, bool free_mapped,
0902                     struct vmem_altmap *altmap)
0903 {
0904     pte_t *ptep, pte;
0905 
0906     do {
0907         ptep = pte_offset_kernel(pmdp, addr);
0908         pte = READ_ONCE(*ptep);
0909         if (pte_none(pte))
0910             continue;
0911 
0912         WARN_ON(!pte_present(pte));
0913         pte_clear(&init_mm, addr, ptep);
0914         flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
0915         if (free_mapped)
0916             free_hotplug_page_range(pte_page(pte),
0917                         PAGE_SIZE, altmap);
0918     } while (addr += PAGE_SIZE, addr < end);
0919 }
0920 
0921 static void unmap_hotplug_pmd_range(pud_t *pudp, unsigned long addr,
0922                     unsigned long end, bool free_mapped,
0923                     struct vmem_altmap *altmap)
0924 {
0925     unsigned long next;
0926     pmd_t *pmdp, pmd;
0927 
0928     do {
0929         next = pmd_addr_end(addr, end);
0930         pmdp = pmd_offset(pudp, addr);
0931         pmd = READ_ONCE(*pmdp);
0932         if (pmd_none(pmd))
0933             continue;
0934 
0935         WARN_ON(!pmd_present(pmd));
0936         if (pmd_sect(pmd)) {
0937             pmd_clear(pmdp);
0938 
0939             /*
0940              * One TLBI should be sufficient here as the PMD_SIZE
0941              * range is mapped with a single block entry.
0942              */
0943             flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
0944             if (free_mapped)
0945                 free_hotplug_page_range(pmd_page(pmd),
0946                             PMD_SIZE, altmap);
0947             continue;
0948         }
0949         WARN_ON(!pmd_table(pmd));
0950         unmap_hotplug_pte_range(pmdp, addr, next, free_mapped, altmap);
0951     } while (addr = next, addr < end);
0952 }
0953 
0954 static void unmap_hotplug_pud_range(p4d_t *p4dp, unsigned long addr,
0955                     unsigned long end, bool free_mapped,
0956                     struct vmem_altmap *altmap)
0957 {
0958     unsigned long next;
0959     pud_t *pudp, pud;
0960 
0961     do {
0962         next = pud_addr_end(addr, end);
0963         pudp = pud_offset(p4dp, addr);
0964         pud = READ_ONCE(*pudp);
0965         if (pud_none(pud))
0966             continue;
0967 
0968         WARN_ON(!pud_present(pud));
0969         if (pud_sect(pud)) {
0970             pud_clear(pudp);
0971 
0972             /*
0973              * One TLBI should be sufficient here as the PUD_SIZE
0974              * range is mapped with a single block entry.
0975              */
0976             flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
0977             if (free_mapped)
0978                 free_hotplug_page_range(pud_page(pud),
0979                             PUD_SIZE, altmap);
0980             continue;
0981         }
0982         WARN_ON(!pud_table(pud));
0983         unmap_hotplug_pmd_range(pudp, addr, next, free_mapped, altmap);
0984     } while (addr = next, addr < end);
0985 }
0986 
0987 static void unmap_hotplug_p4d_range(pgd_t *pgdp, unsigned long addr,
0988                     unsigned long end, bool free_mapped,
0989                     struct vmem_altmap *altmap)
0990 {
0991     unsigned long next;
0992     p4d_t *p4dp, p4d;
0993 
0994     do {
0995         next = p4d_addr_end(addr, end);
0996         p4dp = p4d_offset(pgdp, addr);
0997         p4d = READ_ONCE(*p4dp);
0998         if (p4d_none(p4d))
0999             continue;
1000 
1001         WARN_ON(!p4d_present(p4d));
1002         unmap_hotplug_pud_range(p4dp, addr, next, free_mapped, altmap);
1003     } while (addr = next, addr < end);
1004 }
1005 
1006 static void unmap_hotplug_range(unsigned long addr, unsigned long end,
1007                 bool free_mapped, struct vmem_altmap *altmap)
1008 {
1009     unsigned long next;
1010     pgd_t *pgdp, pgd;
1011 
1012     /*
1013      * altmap can only be used as vmemmap mapping backing memory.
1014      * In case the backing memory itself is not being freed, then
1015      * altmap is irrelevant. Warn about this inconsistency when
1016      * encountered.
1017      */
1018     WARN_ON(!free_mapped && altmap);
1019 
1020     do {
1021         next = pgd_addr_end(addr, end);
1022         pgdp = pgd_offset_k(addr);
1023         pgd = READ_ONCE(*pgdp);
1024         if (pgd_none(pgd))
1025             continue;
1026 
1027         WARN_ON(!pgd_present(pgd));
1028         unmap_hotplug_p4d_range(pgdp, addr, next, free_mapped, altmap);
1029     } while (addr = next, addr < end);
1030 }
1031 
1032 static void free_empty_pte_table(pmd_t *pmdp, unsigned long addr,
1033                  unsigned long end, unsigned long floor,
1034                  unsigned long ceiling)
1035 {
1036     pte_t *ptep, pte;
1037     unsigned long i, start = addr;
1038 
1039     do {
1040         ptep = pte_offset_kernel(pmdp, addr);
1041         pte = READ_ONCE(*ptep);
1042 
1043         /*
1044          * This is just a sanity check here which verifies that
1045          * pte clearing has been done by earlier unmap loops.
1046          */
1047         WARN_ON(!pte_none(pte));
1048     } while (addr += PAGE_SIZE, addr < end);
1049 
1050     if (!pgtable_range_aligned(start, end, floor, ceiling, PMD_MASK))
1051         return;
1052 
1053     /*
1054      * Check whether we can free the pte page if the rest of the
1055      * entries are empty. Overlap with other regions have been
1056      * handled by the floor/ceiling check.
1057      */
1058     ptep = pte_offset_kernel(pmdp, 0UL);
1059     for (i = 0; i < PTRS_PER_PTE; i++) {
1060         if (!pte_none(READ_ONCE(ptep[i])))
1061             return;
1062     }
1063 
1064     pmd_clear(pmdp);
1065     __flush_tlb_kernel_pgtable(start);
1066     free_hotplug_pgtable_page(virt_to_page(ptep));
1067 }
1068 
1069 static void free_empty_pmd_table(pud_t *pudp, unsigned long addr,
1070                  unsigned long end, unsigned long floor,
1071                  unsigned long ceiling)
1072 {
1073     pmd_t *pmdp, pmd;
1074     unsigned long i, next, start = addr;
1075 
1076     do {
1077         next = pmd_addr_end(addr, end);
1078         pmdp = pmd_offset(pudp, addr);
1079         pmd = READ_ONCE(*pmdp);
1080         if (pmd_none(pmd))
1081             continue;
1082 
1083         WARN_ON(!pmd_present(pmd) || !pmd_table(pmd) || pmd_sect(pmd));
1084         free_empty_pte_table(pmdp, addr, next, floor, ceiling);
1085     } while (addr = next, addr < end);
1086 
1087     if (CONFIG_PGTABLE_LEVELS <= 2)
1088         return;
1089 
1090     if (!pgtable_range_aligned(start, end, floor, ceiling, PUD_MASK))
1091         return;
1092 
1093     /*
1094      * Check whether we can free the pmd page if the rest of the
1095      * entries are empty. Overlap with other regions have been
1096      * handled by the floor/ceiling check.
1097      */
1098     pmdp = pmd_offset(pudp, 0UL);
1099     for (i = 0; i < PTRS_PER_PMD; i++) {
1100         if (!pmd_none(READ_ONCE(pmdp[i])))
1101             return;
1102     }
1103 
1104     pud_clear(pudp);
1105     __flush_tlb_kernel_pgtable(start);
1106     free_hotplug_pgtable_page(virt_to_page(pmdp));
1107 }
1108 
1109 static void free_empty_pud_table(p4d_t *p4dp, unsigned long addr,
1110                  unsigned long end, unsigned long floor,
1111                  unsigned long ceiling)
1112 {
1113     pud_t *pudp, pud;
1114     unsigned long i, next, start = addr;
1115 
1116     do {
1117         next = pud_addr_end(addr, end);
1118         pudp = pud_offset(p4dp, addr);
1119         pud = READ_ONCE(*pudp);
1120         if (pud_none(pud))
1121             continue;
1122 
1123         WARN_ON(!pud_present(pud) || !pud_table(pud) || pud_sect(pud));
1124         free_empty_pmd_table(pudp, addr, next, floor, ceiling);
1125     } while (addr = next, addr < end);
1126 
1127     if (CONFIG_PGTABLE_LEVELS <= 3)
1128         return;
1129 
1130     if (!pgtable_range_aligned(start, end, floor, ceiling, PGDIR_MASK))
1131         return;
1132 
1133     /*
1134      * Check whether we can free the pud page if the rest of the
1135      * entries are empty. Overlap with other regions have been
1136      * handled by the floor/ceiling check.
1137      */
1138     pudp = pud_offset(p4dp, 0UL);
1139     for (i = 0; i < PTRS_PER_PUD; i++) {
1140         if (!pud_none(READ_ONCE(pudp[i])))
1141             return;
1142     }
1143 
1144     p4d_clear(p4dp);
1145     __flush_tlb_kernel_pgtable(start);
1146     free_hotplug_pgtable_page(virt_to_page(pudp));
1147 }
1148 
1149 static void free_empty_p4d_table(pgd_t *pgdp, unsigned long addr,
1150                  unsigned long end, unsigned long floor,
1151                  unsigned long ceiling)
1152 {
1153     unsigned long next;
1154     p4d_t *p4dp, p4d;
1155 
1156     do {
1157         next = p4d_addr_end(addr, end);
1158         p4dp = p4d_offset(pgdp, addr);
1159         p4d = READ_ONCE(*p4dp);
1160         if (p4d_none(p4d))
1161             continue;
1162 
1163         WARN_ON(!p4d_present(p4d));
1164         free_empty_pud_table(p4dp, addr, next, floor, ceiling);
1165     } while (addr = next, addr < end);
1166 }
1167 
1168 static void free_empty_tables(unsigned long addr, unsigned long end,
1169                   unsigned long floor, unsigned long ceiling)
1170 {
1171     unsigned long next;
1172     pgd_t *pgdp, pgd;
1173 
1174     do {
1175         next = pgd_addr_end(addr, end);
1176         pgdp = pgd_offset_k(addr);
1177         pgd = READ_ONCE(*pgdp);
1178         if (pgd_none(pgd))
1179             continue;
1180 
1181         WARN_ON(!pgd_present(pgd));
1182         free_empty_p4d_table(pgdp, addr, next, floor, ceiling);
1183     } while (addr = next, addr < end);
1184 }
1185 #endif
1186 
1187 #if !ARM64_KERNEL_USES_PMD_MAPS
1188 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1189         struct vmem_altmap *altmap)
1190 {
1191     WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1192     return vmemmap_populate_basepages(start, end, node, altmap);
1193 }
1194 #else   /* !ARM64_KERNEL_USES_PMD_MAPS */
1195 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1196         struct vmem_altmap *altmap)
1197 {
1198     unsigned long addr = start;
1199     unsigned long next;
1200     pgd_t *pgdp;
1201     p4d_t *p4dp;
1202     pud_t *pudp;
1203     pmd_t *pmdp;
1204 
1205     WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1206     do {
1207         next = pmd_addr_end(addr, end);
1208 
1209         pgdp = vmemmap_pgd_populate(addr, node);
1210         if (!pgdp)
1211             return -ENOMEM;
1212 
1213         p4dp = vmemmap_p4d_populate(pgdp, addr, node);
1214         if (!p4dp)
1215             return -ENOMEM;
1216 
1217         pudp = vmemmap_pud_populate(p4dp, addr, node);
1218         if (!pudp)
1219             return -ENOMEM;
1220 
1221         pmdp = pmd_offset(pudp, addr);
1222         if (pmd_none(READ_ONCE(*pmdp))) {
1223             void *p = NULL;
1224 
1225             p = vmemmap_alloc_block_buf(PMD_SIZE, node, altmap);
1226             if (!p) {
1227                 if (vmemmap_populate_basepages(addr, next, node, altmap))
1228                     return -ENOMEM;
1229                 continue;
1230             }
1231 
1232             pmd_set_huge(pmdp, __pa(p), __pgprot(PROT_SECT_NORMAL));
1233         } else
1234             vmemmap_verify((pte_t *)pmdp, node, addr, next);
1235     } while (addr = next, addr != end);
1236 
1237     return 0;
1238 }
1239 #endif  /* !ARM64_KERNEL_USES_PMD_MAPS */
1240 
1241 #ifdef CONFIG_MEMORY_HOTPLUG
1242 void vmemmap_free(unsigned long start, unsigned long end,
1243         struct vmem_altmap *altmap)
1244 {
1245     WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1246 
1247     unmap_hotplug_range(start, end, true, altmap);
1248     free_empty_tables(start, end, VMEMMAP_START, VMEMMAP_END);
1249 }
1250 #endif /* CONFIG_MEMORY_HOTPLUG */
1251 
1252 static inline pud_t *fixmap_pud(unsigned long addr)
1253 {
1254     pgd_t *pgdp = pgd_offset_k(addr);
1255     p4d_t *p4dp = p4d_offset(pgdp, addr);
1256     p4d_t p4d = READ_ONCE(*p4dp);
1257 
1258     BUG_ON(p4d_none(p4d) || p4d_bad(p4d));
1259 
1260     return pud_offset_kimg(p4dp, addr);
1261 }
1262 
1263 static inline pmd_t *fixmap_pmd(unsigned long addr)
1264 {
1265     pud_t *pudp = fixmap_pud(addr);
1266     pud_t pud = READ_ONCE(*pudp);
1267 
1268     BUG_ON(pud_none(pud) || pud_bad(pud));
1269 
1270     return pmd_offset_kimg(pudp, addr);
1271 }
1272 
1273 static inline pte_t *fixmap_pte(unsigned long addr)
1274 {
1275     return &bm_pte[pte_index(addr)];
1276 }
1277 
1278 /*
1279  * The p*d_populate functions call virt_to_phys implicitly so they can't be used
1280  * directly on kernel symbols (bm_p*d). This function is called too early to use
1281  * lm_alias so __p*d_populate functions must be used to populate with the
1282  * physical address from __pa_symbol.
1283  */
1284 void __init early_fixmap_init(void)
1285 {
1286     pgd_t *pgdp;
1287     p4d_t *p4dp, p4d;
1288     pud_t *pudp;
1289     pmd_t *pmdp;
1290     unsigned long addr = FIXADDR_START;
1291 
1292     pgdp = pgd_offset_k(addr);
1293     p4dp = p4d_offset(pgdp, addr);
1294     p4d = READ_ONCE(*p4dp);
1295     if (CONFIG_PGTABLE_LEVELS > 3 &&
1296         !(p4d_none(p4d) || p4d_page_paddr(p4d) == __pa_symbol(bm_pud))) {
1297         /*
1298          * We only end up here if the kernel mapping and the fixmap
1299          * share the top level pgd entry, which should only happen on
1300          * 16k/4 levels configurations.
1301          */
1302         BUG_ON(!IS_ENABLED(CONFIG_ARM64_16K_PAGES));
1303         pudp = pud_offset_kimg(p4dp, addr);
1304     } else {
1305         if (p4d_none(p4d))
1306             __p4d_populate(p4dp, __pa_symbol(bm_pud), P4D_TYPE_TABLE);
1307         pudp = fixmap_pud(addr);
1308     }
1309     if (pud_none(READ_ONCE(*pudp)))
1310         __pud_populate(pudp, __pa_symbol(bm_pmd), PUD_TYPE_TABLE);
1311     pmdp = fixmap_pmd(addr);
1312     __pmd_populate(pmdp, __pa_symbol(bm_pte), PMD_TYPE_TABLE);
1313 
1314     /*
1315      * The boot-ioremap range spans multiple pmds, for which
1316      * we are not prepared:
1317      */
1318     BUILD_BUG_ON((__fix_to_virt(FIX_BTMAP_BEGIN) >> PMD_SHIFT)
1319              != (__fix_to_virt(FIX_BTMAP_END) >> PMD_SHIFT));
1320 
1321     if ((pmdp != fixmap_pmd(fix_to_virt(FIX_BTMAP_BEGIN)))
1322          || pmdp != fixmap_pmd(fix_to_virt(FIX_BTMAP_END))) {
1323         WARN_ON(1);
1324         pr_warn("pmdp %p != %p, %p\n",
1325             pmdp, fixmap_pmd(fix_to_virt(FIX_BTMAP_BEGIN)),
1326             fixmap_pmd(fix_to_virt(FIX_BTMAP_END)));
1327         pr_warn("fix_to_virt(FIX_BTMAP_BEGIN): %08lx\n",
1328             fix_to_virt(FIX_BTMAP_BEGIN));
1329         pr_warn("fix_to_virt(FIX_BTMAP_END):   %08lx\n",
1330             fix_to_virt(FIX_BTMAP_END));
1331 
1332         pr_warn("FIX_BTMAP_END:       %d\n", FIX_BTMAP_END);
1333         pr_warn("FIX_BTMAP_BEGIN:     %d\n", FIX_BTMAP_BEGIN);
1334     }
1335 }
1336 
1337 /*
1338  * Unusually, this is also called in IRQ context (ghes_iounmap_irq) so if we
1339  * ever need to use IPIs for TLB broadcasting, then we're in trouble here.
1340  */
1341 void __set_fixmap(enum fixed_addresses idx,
1342                    phys_addr_t phys, pgprot_t flags)
1343 {
1344     unsigned long addr = __fix_to_virt(idx);
1345     pte_t *ptep;
1346 
1347     BUG_ON(idx <= FIX_HOLE || idx >= __end_of_fixed_addresses);
1348 
1349     ptep = fixmap_pte(addr);
1350 
1351     if (pgprot_val(flags)) {
1352         set_pte(ptep, pfn_pte(phys >> PAGE_SHIFT, flags));
1353     } else {
1354         pte_clear(&init_mm, addr, ptep);
1355         flush_tlb_kernel_range(addr, addr+PAGE_SIZE);
1356     }
1357 }
1358 
1359 void *__init fixmap_remap_fdt(phys_addr_t dt_phys, int *size, pgprot_t prot)
1360 {
1361     const u64 dt_virt_base = __fix_to_virt(FIX_FDT);
1362     int offset;
1363     void *dt_virt;
1364 
1365     /*
1366      * Check whether the physical FDT address is set and meets the minimum
1367      * alignment requirement. Since we are relying on MIN_FDT_ALIGN to be
1368      * at least 8 bytes so that we can always access the magic and size
1369      * fields of the FDT header after mapping the first chunk, double check
1370      * here if that is indeed the case.
1371      */
1372     BUILD_BUG_ON(MIN_FDT_ALIGN < 8);
1373     if (!dt_phys || dt_phys % MIN_FDT_ALIGN)
1374         return NULL;
1375 
1376     /*
1377      * Make sure that the FDT region can be mapped without the need to
1378      * allocate additional translation table pages, so that it is safe
1379      * to call create_mapping_noalloc() this early.
1380      *
1381      * On 64k pages, the FDT will be mapped using PTEs, so we need to
1382      * be in the same PMD as the rest of the fixmap.
1383      * On 4k pages, we'll use section mappings for the FDT so we only
1384      * have to be in the same PUD.
1385      */
1386     BUILD_BUG_ON(dt_virt_base % SZ_2M);
1387 
1388     BUILD_BUG_ON(__fix_to_virt(FIX_FDT_END) >> SWAPPER_TABLE_SHIFT !=
1389              __fix_to_virt(FIX_BTMAP_BEGIN) >> SWAPPER_TABLE_SHIFT);
1390 
1391     offset = dt_phys % SWAPPER_BLOCK_SIZE;
1392     dt_virt = (void *)dt_virt_base + offset;
1393 
1394     /* map the first chunk so we can read the size from the header */
1395     create_mapping_noalloc(round_down(dt_phys, SWAPPER_BLOCK_SIZE),
1396             dt_virt_base, SWAPPER_BLOCK_SIZE, prot);
1397 
1398     if (fdt_magic(dt_virt) != FDT_MAGIC)
1399         return NULL;
1400 
1401     *size = fdt_totalsize(dt_virt);
1402     if (*size > MAX_FDT_SIZE)
1403         return NULL;
1404 
1405     if (offset + *size > SWAPPER_BLOCK_SIZE)
1406         create_mapping_noalloc(round_down(dt_phys, SWAPPER_BLOCK_SIZE), dt_virt_base,
1407                    round_up(offset + *size, SWAPPER_BLOCK_SIZE), prot);
1408 
1409     return dt_virt;
1410 }
1411 
1412 int pud_set_huge(pud_t *pudp, phys_addr_t phys, pgprot_t prot)
1413 {
1414     pud_t new_pud = pfn_pud(__phys_to_pfn(phys), mk_pud_sect_prot(prot));
1415 
1416     /* Only allow permission changes for now */
1417     if (!pgattr_change_is_safe(READ_ONCE(pud_val(*pudp)),
1418                    pud_val(new_pud)))
1419         return 0;
1420 
1421     VM_BUG_ON(phys & ~PUD_MASK);
1422     set_pud(pudp, new_pud);
1423     return 1;
1424 }
1425 
1426 int pmd_set_huge(pmd_t *pmdp, phys_addr_t phys, pgprot_t prot)
1427 {
1428     pmd_t new_pmd = pfn_pmd(__phys_to_pfn(phys), mk_pmd_sect_prot(prot));
1429 
1430     /* Only allow permission changes for now */
1431     if (!pgattr_change_is_safe(READ_ONCE(pmd_val(*pmdp)),
1432                    pmd_val(new_pmd)))
1433         return 0;
1434 
1435     VM_BUG_ON(phys & ~PMD_MASK);
1436     set_pmd(pmdp, new_pmd);
1437     return 1;
1438 }
1439 
1440 int pud_clear_huge(pud_t *pudp)
1441 {
1442     if (!pud_sect(READ_ONCE(*pudp)))
1443         return 0;
1444     pud_clear(pudp);
1445     return 1;
1446 }
1447 
1448 int pmd_clear_huge(pmd_t *pmdp)
1449 {
1450     if (!pmd_sect(READ_ONCE(*pmdp)))
1451         return 0;
1452     pmd_clear(pmdp);
1453     return 1;
1454 }
1455 
1456 int pmd_free_pte_page(pmd_t *pmdp, unsigned long addr)
1457 {
1458     pte_t *table;
1459     pmd_t pmd;
1460 
1461     pmd = READ_ONCE(*pmdp);
1462 
1463     if (!pmd_table(pmd)) {
1464         VM_WARN_ON(1);
1465         return 1;
1466     }
1467 
1468     table = pte_offset_kernel(pmdp, addr);
1469     pmd_clear(pmdp);
1470     __flush_tlb_kernel_pgtable(addr);
1471     pte_free_kernel(NULL, table);
1472     return 1;
1473 }
1474 
1475 int pud_free_pmd_page(pud_t *pudp, unsigned long addr)
1476 {
1477     pmd_t *table;
1478     pmd_t *pmdp;
1479     pud_t pud;
1480     unsigned long next, end;
1481 
1482     pud = READ_ONCE(*pudp);
1483 
1484     if (!pud_table(pud)) {
1485         VM_WARN_ON(1);
1486         return 1;
1487     }
1488 
1489     table = pmd_offset(pudp, addr);
1490     pmdp = table;
1491     next = addr;
1492     end = addr + PUD_SIZE;
1493     do {
1494         pmd_free_pte_page(pmdp, next);
1495     } while (pmdp++, next += PMD_SIZE, next != end);
1496 
1497     pud_clear(pudp);
1498     __flush_tlb_kernel_pgtable(addr);
1499     pmd_free(NULL, table);
1500     return 1;
1501 }
1502 
1503 #ifdef CONFIG_MEMORY_HOTPLUG
1504 static void __remove_pgd_mapping(pgd_t *pgdir, unsigned long start, u64 size)
1505 {
1506     unsigned long end = start + size;
1507 
1508     WARN_ON(pgdir != init_mm.pgd);
1509     WARN_ON((start < PAGE_OFFSET) || (end > PAGE_END));
1510 
1511     unmap_hotplug_range(start, end, false, NULL);
1512     free_empty_tables(start, end, PAGE_OFFSET, PAGE_END);
1513 }
1514 
1515 struct range arch_get_mappable_range(void)
1516 {
1517     struct range mhp_range;
1518     u64 start_linear_pa = __pa(_PAGE_OFFSET(vabits_actual));
1519     u64 end_linear_pa = __pa(PAGE_END - 1);
1520 
1521     if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
1522         /*
1523          * Check for a wrap, it is possible because of randomized linear
1524          * mapping the start physical address is actually bigger than
1525          * the end physical address. In this case set start to zero
1526          * because [0, end_linear_pa] range must still be able to cover
1527          * all addressable physical addresses.
1528          */
1529         if (start_linear_pa > end_linear_pa)
1530             start_linear_pa = 0;
1531     }
1532 
1533     WARN_ON(start_linear_pa > end_linear_pa);
1534 
1535     /*
1536      * Linear mapping region is the range [PAGE_OFFSET..(PAGE_END - 1)]
1537      * accommodating both its ends but excluding PAGE_END. Max physical
1538      * range which can be mapped inside this linear mapping range, must
1539      * also be derived from its end points.
1540      */
1541     mhp_range.start = start_linear_pa;
1542     mhp_range.end =  end_linear_pa;
1543 
1544     return mhp_range;
1545 }
1546 
1547 int arch_add_memory(int nid, u64 start, u64 size,
1548             struct mhp_params *params)
1549 {
1550     int ret, flags = NO_EXEC_MAPPINGS;
1551 
1552     VM_BUG_ON(!mhp_range_allowed(start, size, true));
1553 
1554     /*
1555      * KFENCE requires linear map to be mapped at page granularity, so that
1556      * it is possible to protect/unprotect single pages in the KFENCE pool.
1557      */
1558     if (can_set_direct_map() || IS_ENABLED(CONFIG_KFENCE))
1559         flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
1560 
1561     __create_pgd_mapping(swapper_pg_dir, start, __phys_to_virt(start),
1562                  size, params->pgprot, __pgd_pgtable_alloc,
1563                  flags);
1564 
1565     memblock_clear_nomap(start, size);
1566 
1567     ret = __add_pages(nid, start >> PAGE_SHIFT, size >> PAGE_SHIFT,
1568                params);
1569     if (ret)
1570         __remove_pgd_mapping(swapper_pg_dir,
1571                      __phys_to_virt(start), size);
1572     else {
1573         max_pfn = PFN_UP(start + size);
1574         max_low_pfn = max_pfn;
1575     }
1576 
1577     return ret;
1578 }
1579 
1580 void arch_remove_memory(u64 start, u64 size, struct vmem_altmap *altmap)
1581 {
1582     unsigned long start_pfn = start >> PAGE_SHIFT;
1583     unsigned long nr_pages = size >> PAGE_SHIFT;
1584 
1585     __remove_pages(start_pfn, nr_pages, altmap);
1586     __remove_pgd_mapping(swapper_pg_dir, __phys_to_virt(start), size);
1587 }
1588 
1589 /*
1590  * This memory hotplug notifier helps prevent boot memory from being
1591  * inadvertently removed as it blocks pfn range offlining process in
1592  * __offline_pages(). Hence this prevents both offlining as well as
1593  * removal process for boot memory which is initially always online.
1594  * In future if and when boot memory could be removed, this notifier
1595  * should be dropped and free_hotplug_page_range() should handle any
1596  * reserved pages allocated during boot.
1597  */
1598 static int prevent_bootmem_remove_notifier(struct notifier_block *nb,
1599                        unsigned long action, void *data)
1600 {
1601     struct mem_section *ms;
1602     struct memory_notify *arg = data;
1603     unsigned long end_pfn = arg->start_pfn + arg->nr_pages;
1604     unsigned long pfn = arg->start_pfn;
1605 
1606     if ((action != MEM_GOING_OFFLINE) && (action != MEM_OFFLINE))
1607         return NOTIFY_OK;
1608 
1609     for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1610         unsigned long start = PFN_PHYS(pfn);
1611         unsigned long end = start + (1UL << PA_SECTION_SHIFT);
1612 
1613         ms = __pfn_to_section(pfn);
1614         if (!early_section(ms))
1615             continue;
1616 
1617         if (action == MEM_GOING_OFFLINE) {
1618             /*
1619              * Boot memory removal is not supported. Prevent
1620              * it via blocking any attempted offline request
1621              * for the boot memory and just report it.
1622              */
1623             pr_warn("Boot memory [%lx %lx] offlining attempted\n", start, end);
1624             return NOTIFY_BAD;
1625         } else if (action == MEM_OFFLINE) {
1626             /*
1627              * This should have never happened. Boot memory
1628              * offlining should have been prevented by this
1629              * very notifier. Probably some memory removal
1630              * procedure might have changed which would then
1631              * require further debug.
1632              */
1633             pr_err("Boot memory [%lx %lx] offlined\n", start, end);
1634 
1635             /*
1636              * Core memory hotplug does not process a return
1637              * code from the notifier for MEM_OFFLINE events.
1638              * The error condition has been reported. Return
1639              * from here as if ignored.
1640              */
1641             return NOTIFY_DONE;
1642         }
1643     }
1644     return NOTIFY_OK;
1645 }
1646 
1647 static struct notifier_block prevent_bootmem_remove_nb = {
1648     .notifier_call = prevent_bootmem_remove_notifier,
1649 };
1650 
1651 /*
1652  * This ensures that boot memory sections on the platform are online
1653  * from early boot. Memory sections could not be prevented from being
1654  * offlined, unless for some reason they are not online to begin with.
1655  * This helps validate the basic assumption on which the above memory
1656  * event notifier works to prevent boot memory section offlining and
1657  * its possible removal.
1658  */
1659 static void validate_bootmem_online(void)
1660 {
1661     phys_addr_t start, end, addr;
1662     struct mem_section *ms;
1663     u64 i;
1664 
1665     /*
1666      * Scanning across all memblock might be expensive
1667      * on some big memory systems. Hence enable this
1668      * validation only with DEBUG_VM.
1669      */
1670     if (!IS_ENABLED(CONFIG_DEBUG_VM))
1671         return;
1672 
1673     for_each_mem_range(i, &start, &end) {
1674         for (addr = start; addr < end; addr += (1UL << PA_SECTION_SHIFT)) {
1675             ms = __pfn_to_section(PHYS_PFN(addr));
1676 
1677             /*
1678              * All memory ranges in the system at this point
1679              * should have been marked as early sections.
1680              */
1681             WARN_ON(!early_section(ms));
1682 
1683             /*
1684              * Memory notifier mechanism here to prevent boot
1685              * memory offlining depends on the fact that each
1686              * early section memory on the system is initially
1687              * online. Otherwise a given memory section which
1688              * is already offline will be overlooked and can
1689              * be removed completely. Call out such sections.
1690              */
1691             if (!online_section(ms))
1692                 pr_err("Boot memory [%llx %llx] is offline, can be removed\n",
1693                     addr, addr + (1UL << PA_SECTION_SHIFT));
1694         }
1695     }
1696 }
1697 
1698 static int __init prevent_bootmem_remove_init(void)
1699 {
1700     int ret = 0;
1701 
1702     if (!IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
1703         return ret;
1704 
1705     validate_bootmem_online();
1706     ret = register_memory_notifier(&prevent_bootmem_remove_nb);
1707     if (ret)
1708         pr_err("%s: Notifier registration failed %d\n", __func__, ret);
1709 
1710     return ret;
1711 }
1712 early_initcall(prevent_bootmem_remove_init);
1713 #endif