ba00d0205447735b6ffd9d48ed065fc78727ee1e
[sfrench/cifs-2.6.git] / arch / arm64 / mm / mmu.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Based on arch/arm/mm/mmu.c
4  *
5  * Copyright (C) 1995-2005 Russell King
6  * Copyright (C) 2012 ARM Ltd.
7  */
8
9 #include <linux/cache.h>
10 #include <linux/export.h>
11 #include <linux/kernel.h>
12 #include <linux/errno.h>
13 #include <linux/init.h>
14 #include <linux/ioport.h>
15 #include <linux/kexec.h>
16 #include <linux/libfdt.h>
17 #include <linux/mman.h>
18 #include <linux/nodemask.h>
19 #include <linux/memblock.h>
20 #include <linux/memremap.h>
21 #include <linux/memory.h>
22 #include <linux/fs.h>
23 #include <linux/io.h>
24 #include <linux/mm.h>
25 #include <linux/vmalloc.h>
26 #include <linux/set_memory.h>
27 #include <linux/kfence.h>
28
29 #include <asm/barrier.h>
30 #include <asm/cputype.h>
31 #include <asm/fixmap.h>
32 #include <asm/kasan.h>
33 #include <asm/kernel-pgtable.h>
34 #include <asm/sections.h>
35 #include <asm/setup.h>
36 #include <linux/sizes.h>
37 #include <asm/tlb.h>
38 #include <asm/mmu_context.h>
39 #include <asm/ptdump.h>
40 #include <asm/tlbflush.h>
41 #include <asm/pgalloc.h>
42 #include <asm/kfence.h>
43
44 #define NO_BLOCK_MAPPINGS       BIT(0)
45 #define NO_CONT_MAPPINGS        BIT(1)
46 #define NO_EXEC_MAPPINGS        BIT(2)  /* assumes FEAT_HPDS is not used */
47
48 u64 kimage_voffset __ro_after_init;
49 EXPORT_SYMBOL(kimage_voffset);
50
51 u32 __boot_cpu_mode[] = { BOOT_CPU_MODE_EL2, BOOT_CPU_MODE_EL1 };
52
53 static bool rodata_is_rw __ro_after_init = true;
54
55 /*
56  * The booting CPU updates the failed status @__early_cpu_boot_status,
57  * with MMU turned off.
58  */
59 long __section(".mmuoff.data.write") __early_cpu_boot_status;
60
61 /*
62  * Empty_zero_page is a special page that is used for zero-initialized data
63  * and COW.
64  */
65 unsigned long empty_zero_page[PAGE_SIZE / sizeof(unsigned long)] __page_aligned_bss;
66 EXPORT_SYMBOL(empty_zero_page);
67
68 static DEFINE_SPINLOCK(swapper_pgdir_lock);
69 static DEFINE_MUTEX(fixmap_lock);
70
71 void noinstr set_swapper_pgd(pgd_t *pgdp, pgd_t pgd)
72 {
73         pgd_t *fixmap_pgdp;
74
75         /*
76          * Don't bother with the fixmap if swapper_pg_dir is still mapped
77          * writable in the kernel mapping.
78          */
79         if (rodata_is_rw) {
80                 WRITE_ONCE(*pgdp, pgd);
81                 dsb(ishst);
82                 isb();
83                 return;
84         }
85
86         spin_lock(&swapper_pgdir_lock);
87         fixmap_pgdp = pgd_set_fixmap(__pa_symbol(pgdp));
88         WRITE_ONCE(*fixmap_pgdp, pgd);
89         /*
90          * We need dsb(ishst) here to ensure the page-table-walker sees
91          * our new entry before set_p?d() returns. The fixmap's
92          * flush_tlb_kernel_range() via clear_fixmap() does this for us.
93          */
94         pgd_clear_fixmap();
95         spin_unlock(&swapper_pgdir_lock);
96 }
97
98 pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
99                               unsigned long size, pgprot_t vma_prot)
100 {
101         if (!pfn_is_map_memory(pfn))
102                 return pgprot_noncached(vma_prot);
103         else if (file->f_flags & O_SYNC)
104                 return pgprot_writecombine(vma_prot);
105         return vma_prot;
106 }
107 EXPORT_SYMBOL(phys_mem_access_prot);
108
109 static phys_addr_t __init early_pgtable_alloc(int shift)
110 {
111         phys_addr_t phys;
112         void *ptr;
113
114         phys = memblock_phys_alloc_range(PAGE_SIZE, PAGE_SIZE, 0,
115                                          MEMBLOCK_ALLOC_NOLEAKTRACE);
116         if (!phys)
117                 panic("Failed to allocate page table page\n");
118
119         /*
120          * The FIX_{PGD,PUD,PMD} slots may be in active use, but the FIX_PTE
121          * slot will be free, so we can (ab)use the FIX_PTE slot to initialise
122          * any level of table.
123          */
124         ptr = pte_set_fixmap(phys);
125
126         memset(ptr, 0, PAGE_SIZE);
127
128         /*
129          * Implicit barriers also ensure the zeroed page is visible to the page
130          * table walker
131          */
132         pte_clear_fixmap();
133
134         return phys;
135 }
136
137 bool pgattr_change_is_safe(u64 old, u64 new)
138 {
139         /*
140          * The following mapping attributes may be updated in live
141          * kernel mappings without the need for break-before-make.
142          */
143         pteval_t mask = PTE_PXN | PTE_RDONLY | PTE_WRITE | PTE_NG;
144
145         /* creating or taking down mappings is always safe */
146         if (!pte_valid(__pte(old)) || !pte_valid(__pte(new)))
147                 return true;
148
149         /* A live entry's pfn should not change */
150         if (pte_pfn(__pte(old)) != pte_pfn(__pte(new)))
151                 return false;
152
153         /* live contiguous mappings may not be manipulated at all */
154         if ((old | new) & PTE_CONT)
155                 return false;
156
157         /* Transitioning from Non-Global to Global is unsafe */
158         if (old & ~new & PTE_NG)
159                 return false;
160
161         /*
162          * Changing the memory type between Normal and Normal-Tagged is safe
163          * since Tagged is considered a permission attribute from the
164          * mismatched attribute aliases perspective.
165          */
166         if (((old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
167              (old & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)) &&
168             ((new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL) ||
169              (new & PTE_ATTRINDX_MASK) == PTE_ATTRINDX(MT_NORMAL_TAGGED)))
170                 mask |= PTE_ATTRINDX_MASK;
171
172         return ((old ^ new) & ~mask) == 0;
173 }
174
175 static void init_pte(pmd_t *pmdp, unsigned long addr, unsigned long end,
176                      phys_addr_t phys, pgprot_t prot)
177 {
178         pte_t *ptep;
179
180         ptep = pte_set_fixmap_offset(pmdp, addr);
181         do {
182                 pte_t old_pte = READ_ONCE(*ptep);
183
184                 set_pte(ptep, pfn_pte(__phys_to_pfn(phys), prot));
185
186                 /*
187                  * After the PTE entry has been populated once, we
188                  * only allow updates to the permission attributes.
189                  */
190                 BUG_ON(!pgattr_change_is_safe(pte_val(old_pte),
191                                               READ_ONCE(pte_val(*ptep))));
192
193                 phys += PAGE_SIZE;
194         } while (ptep++, addr += PAGE_SIZE, addr != end);
195
196         pte_clear_fixmap();
197 }
198
199 static void alloc_init_cont_pte(pmd_t *pmdp, unsigned long addr,
200                                 unsigned long end, phys_addr_t phys,
201                                 pgprot_t prot,
202                                 phys_addr_t (*pgtable_alloc)(int),
203                                 int flags)
204 {
205         unsigned long next;
206         pmd_t pmd = READ_ONCE(*pmdp);
207
208         BUG_ON(pmd_sect(pmd));
209         if (pmd_none(pmd)) {
210                 pmdval_t pmdval = PMD_TYPE_TABLE | PMD_TABLE_UXN;
211                 phys_addr_t pte_phys;
212
213                 if (flags & NO_EXEC_MAPPINGS)
214                         pmdval |= PMD_TABLE_PXN;
215                 BUG_ON(!pgtable_alloc);
216                 pte_phys = pgtable_alloc(PAGE_SHIFT);
217                 __pmd_populate(pmdp, pte_phys, pmdval);
218                 pmd = READ_ONCE(*pmdp);
219         }
220         BUG_ON(pmd_bad(pmd));
221
222         do {
223                 pgprot_t __prot = prot;
224
225                 next = pte_cont_addr_end(addr, end);
226
227                 /* use a contiguous mapping if the range is suitably aligned */
228                 if ((((addr | next | phys) & ~CONT_PTE_MASK) == 0) &&
229                     (flags & NO_CONT_MAPPINGS) == 0)
230                         __prot = __pgprot(pgprot_val(prot) | PTE_CONT);
231
232                 init_pte(pmdp, addr, next, phys, __prot);
233
234                 phys += next - addr;
235         } while (addr = next, addr != end);
236 }
237
238 static void init_pmd(pud_t *pudp, unsigned long addr, unsigned long end,
239                      phys_addr_t phys, pgprot_t prot,
240                      phys_addr_t (*pgtable_alloc)(int), int flags)
241 {
242         unsigned long next;
243         pmd_t *pmdp;
244
245         pmdp = pmd_set_fixmap_offset(pudp, addr);
246         do {
247                 pmd_t old_pmd = READ_ONCE(*pmdp);
248
249                 next = pmd_addr_end(addr, end);
250
251                 /* try section mapping first */
252                 if (((addr | next | phys) & ~PMD_MASK) == 0 &&
253                     (flags & NO_BLOCK_MAPPINGS) == 0) {
254                         pmd_set_huge(pmdp, phys, prot);
255
256                         /*
257                          * After the PMD entry has been populated once, we
258                          * only allow updates to the permission attributes.
259                          */
260                         BUG_ON(!pgattr_change_is_safe(pmd_val(old_pmd),
261                                                       READ_ONCE(pmd_val(*pmdp))));
262                 } else {
263                         alloc_init_cont_pte(pmdp, addr, next, phys, prot,
264                                             pgtable_alloc, flags);
265
266                         BUG_ON(pmd_val(old_pmd) != 0 &&
267                                pmd_val(old_pmd) != READ_ONCE(pmd_val(*pmdp)));
268                 }
269                 phys += next - addr;
270         } while (pmdp++, addr = next, addr != end);
271
272         pmd_clear_fixmap();
273 }
274
275 static void alloc_init_cont_pmd(pud_t *pudp, unsigned long addr,
276                                 unsigned long end, phys_addr_t phys,
277                                 pgprot_t prot,
278                                 phys_addr_t (*pgtable_alloc)(int), int flags)
279 {
280         unsigned long next;
281         pud_t pud = READ_ONCE(*pudp);
282
283         /*
284          * Check for initial section mappings in the pgd/pud.
285          */
286         BUG_ON(pud_sect(pud));
287         if (pud_none(pud)) {
288                 pudval_t pudval = PUD_TYPE_TABLE | PUD_TABLE_UXN;
289                 phys_addr_t pmd_phys;
290
291                 if (flags & NO_EXEC_MAPPINGS)
292                         pudval |= PUD_TABLE_PXN;
293                 BUG_ON(!pgtable_alloc);
294                 pmd_phys = pgtable_alloc(PMD_SHIFT);
295                 __pud_populate(pudp, pmd_phys, pudval);
296                 pud = READ_ONCE(*pudp);
297         }
298         BUG_ON(pud_bad(pud));
299
300         do {
301                 pgprot_t __prot = prot;
302
303                 next = pmd_cont_addr_end(addr, end);
304
305                 /* use a contiguous mapping if the range is suitably aligned */
306                 if ((((addr | next | phys) & ~CONT_PMD_MASK) == 0) &&
307                     (flags & NO_CONT_MAPPINGS) == 0)
308                         __prot = __pgprot(pgprot_val(prot) | PTE_CONT);
309
310                 init_pmd(pudp, addr, next, phys, __prot, pgtable_alloc, flags);
311
312                 phys += next - addr;
313         } while (addr = next, addr != end);
314 }
315
316 static void alloc_init_pud(pgd_t *pgdp, unsigned long addr, unsigned long end,
317                            phys_addr_t phys, pgprot_t prot,
318                            phys_addr_t (*pgtable_alloc)(int),
319                            int flags)
320 {
321         unsigned long next;
322         pud_t *pudp;
323         p4d_t *p4dp = p4d_offset(pgdp, addr);
324         p4d_t p4d = READ_ONCE(*p4dp);
325
326         if (p4d_none(p4d)) {
327                 p4dval_t p4dval = P4D_TYPE_TABLE | P4D_TABLE_UXN;
328                 phys_addr_t pud_phys;
329
330                 if (flags & NO_EXEC_MAPPINGS)
331                         p4dval |= P4D_TABLE_PXN;
332                 BUG_ON(!pgtable_alloc);
333                 pud_phys = pgtable_alloc(PUD_SHIFT);
334                 __p4d_populate(p4dp, pud_phys, p4dval);
335                 p4d = READ_ONCE(*p4dp);
336         }
337         BUG_ON(p4d_bad(p4d));
338
339         pudp = pud_set_fixmap_offset(p4dp, addr);
340         do {
341                 pud_t old_pud = READ_ONCE(*pudp);
342
343                 next = pud_addr_end(addr, end);
344
345                 /*
346                  * For 4K granule only, attempt to put down a 1GB block
347                  */
348                 if (pud_sect_supported() &&
349                    ((addr | next | phys) & ~PUD_MASK) == 0 &&
350                     (flags & NO_BLOCK_MAPPINGS) == 0) {
351                         pud_set_huge(pudp, phys, prot);
352
353                         /*
354                          * After the PUD entry has been populated once, we
355                          * only allow updates to the permission attributes.
356                          */
357                         BUG_ON(!pgattr_change_is_safe(pud_val(old_pud),
358                                                       READ_ONCE(pud_val(*pudp))));
359                 } else {
360                         alloc_init_cont_pmd(pudp, addr, next, phys, prot,
361                                             pgtable_alloc, flags);
362
363                         BUG_ON(pud_val(old_pud) != 0 &&
364                                pud_val(old_pud) != READ_ONCE(pud_val(*pudp)));
365                 }
366                 phys += next - addr;
367         } while (pudp++, addr = next, addr != end);
368
369         pud_clear_fixmap();
370 }
371
372 static void __create_pgd_mapping_locked(pgd_t *pgdir, phys_addr_t phys,
373                                         unsigned long virt, phys_addr_t size,
374                                         pgprot_t prot,
375                                         phys_addr_t (*pgtable_alloc)(int),
376                                         int flags)
377 {
378         unsigned long addr, end, next;
379         pgd_t *pgdp = pgd_offset_pgd(pgdir, virt);
380
381         /*
382          * If the virtual and physical address don't have the same offset
383          * within a page, we cannot map the region as the caller expects.
384          */
385         if (WARN_ON((phys ^ virt) & ~PAGE_MASK))
386                 return;
387
388         phys &= PAGE_MASK;
389         addr = virt & PAGE_MASK;
390         end = PAGE_ALIGN(virt + size);
391
392         do {
393                 next = pgd_addr_end(addr, end);
394                 alloc_init_pud(pgdp, addr, next, phys, prot, pgtable_alloc,
395                                flags);
396                 phys += next - addr;
397         } while (pgdp++, addr = next, addr != end);
398 }
399
400 static void __create_pgd_mapping(pgd_t *pgdir, phys_addr_t phys,
401                                  unsigned long virt, phys_addr_t size,
402                                  pgprot_t prot,
403                                  phys_addr_t (*pgtable_alloc)(int),
404                                  int flags)
405 {
406         mutex_lock(&fixmap_lock);
407         __create_pgd_mapping_locked(pgdir, phys, virt, size, prot,
408                                     pgtable_alloc, flags);
409         mutex_unlock(&fixmap_lock);
410 }
411
412 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
413 extern __alias(__create_pgd_mapping_locked)
414 void create_kpti_ng_temp_pgd(pgd_t *pgdir, phys_addr_t phys, unsigned long virt,
415                              phys_addr_t size, pgprot_t prot,
416                              phys_addr_t (*pgtable_alloc)(int), int flags);
417 #endif
418
419 static phys_addr_t __pgd_pgtable_alloc(int shift)
420 {
421         void *ptr = (void *)__get_free_page(GFP_PGTABLE_KERNEL);
422         BUG_ON(!ptr);
423
424         /* Ensure the zeroed page is visible to the page table walker */
425         dsb(ishst);
426         return __pa(ptr);
427 }
428
429 static phys_addr_t pgd_pgtable_alloc(int shift)
430 {
431         phys_addr_t pa = __pgd_pgtable_alloc(shift);
432         struct ptdesc *ptdesc = page_ptdesc(phys_to_page(pa));
433
434         /*
435          * Call proper page table ctor in case later we need to
436          * call core mm functions like apply_to_page_range() on
437          * this pre-allocated page table.
438          *
439          * We don't select ARCH_ENABLE_SPLIT_PMD_PTLOCK if pmd is
440          * folded, and if so pagetable_pte_ctor() becomes nop.
441          */
442         if (shift == PAGE_SHIFT)
443                 BUG_ON(!pagetable_pte_ctor(ptdesc));
444         else if (shift == PMD_SHIFT)
445                 BUG_ON(!pagetable_pmd_ctor(ptdesc));
446
447         return pa;
448 }
449
450 /*
451  * This function can only be used to modify existing table entries,
452  * without allocating new levels of table. Note that this permits the
453  * creation of new section or page entries.
454  */
455 void __init create_mapping_noalloc(phys_addr_t phys, unsigned long virt,
456                                    phys_addr_t size, pgprot_t prot)
457 {
458         if (virt < PAGE_OFFSET) {
459                 pr_warn("BUG: not creating mapping for %pa at 0x%016lx - outside kernel range\n",
460                         &phys, virt);
461                 return;
462         }
463         __create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
464                              NO_CONT_MAPPINGS);
465 }
466
467 void __init create_pgd_mapping(struct mm_struct *mm, phys_addr_t phys,
468                                unsigned long virt, phys_addr_t size,
469                                pgprot_t prot, bool page_mappings_only)
470 {
471         int flags = 0;
472
473         BUG_ON(mm == &init_mm);
474
475         if (page_mappings_only)
476                 flags = NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
477
478         __create_pgd_mapping(mm->pgd, phys, virt, size, prot,
479                              pgd_pgtable_alloc, flags);
480 }
481
482 static void update_mapping_prot(phys_addr_t phys, unsigned long virt,
483                                 phys_addr_t size, pgprot_t prot)
484 {
485         if (virt < PAGE_OFFSET) {
486                 pr_warn("BUG: not updating mapping for %pa at 0x%016lx - outside kernel range\n",
487                         &phys, virt);
488                 return;
489         }
490
491         __create_pgd_mapping(init_mm.pgd, phys, virt, size, prot, NULL,
492                              NO_CONT_MAPPINGS);
493
494         /* flush the TLBs after updating live kernel mappings */
495         flush_tlb_kernel_range(virt, virt + size);
496 }
497
498 static void __init __map_memblock(pgd_t *pgdp, phys_addr_t start,
499                                   phys_addr_t end, pgprot_t prot, int flags)
500 {
501         __create_pgd_mapping(pgdp, start, __phys_to_virt(start), end - start,
502                              prot, early_pgtable_alloc, flags);
503 }
504
505 void __init mark_linear_text_alias_ro(void)
506 {
507         /*
508          * Remove the write permissions from the linear alias of .text/.rodata
509          */
510         update_mapping_prot(__pa_symbol(_stext), (unsigned long)lm_alias(_stext),
511                             (unsigned long)__init_begin - (unsigned long)_stext,
512                             PAGE_KERNEL_RO);
513 }
514
515 #ifdef CONFIG_KFENCE
516
517 bool __ro_after_init kfence_early_init = !!CONFIG_KFENCE_SAMPLE_INTERVAL;
518
519 /* early_param() will be parsed before map_mem() below. */
520 static int __init parse_kfence_early_init(char *arg)
521 {
522         int val;
523
524         if (get_option(&arg, &val))
525                 kfence_early_init = !!val;
526         return 0;
527 }
528 early_param("kfence.sample_interval", parse_kfence_early_init);
529
530 static phys_addr_t __init arm64_kfence_alloc_pool(void)
531 {
532         phys_addr_t kfence_pool;
533
534         if (!kfence_early_init)
535                 return 0;
536
537         kfence_pool = memblock_phys_alloc(KFENCE_POOL_SIZE, PAGE_SIZE);
538         if (!kfence_pool) {
539                 pr_err("failed to allocate kfence pool\n");
540                 kfence_early_init = false;
541                 return 0;
542         }
543
544         /* Temporarily mark as NOMAP. */
545         memblock_mark_nomap(kfence_pool, KFENCE_POOL_SIZE);
546
547         return kfence_pool;
548 }
549
550 static void __init arm64_kfence_map_pool(phys_addr_t kfence_pool, pgd_t *pgdp)
551 {
552         if (!kfence_pool)
553                 return;
554
555         /* KFENCE pool needs page-level mapping. */
556         __map_memblock(pgdp, kfence_pool, kfence_pool + KFENCE_POOL_SIZE,
557                         pgprot_tagged(PAGE_KERNEL),
558                         NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS);
559         memblock_clear_nomap(kfence_pool, KFENCE_POOL_SIZE);
560         __kfence_pool = phys_to_virt(kfence_pool);
561 }
562 #else /* CONFIG_KFENCE */
563
564 static inline phys_addr_t arm64_kfence_alloc_pool(void) { return 0; }
565 static inline void arm64_kfence_map_pool(phys_addr_t kfence_pool, pgd_t *pgdp) { }
566
567 #endif /* CONFIG_KFENCE */
568
569 static void __init map_mem(pgd_t *pgdp)
570 {
571         static const u64 direct_map_end = _PAGE_END(VA_BITS_MIN);
572         phys_addr_t kernel_start = __pa_symbol(_stext);
573         phys_addr_t kernel_end = __pa_symbol(__init_begin);
574         phys_addr_t start, end;
575         phys_addr_t early_kfence_pool;
576         int flags = NO_EXEC_MAPPINGS;
577         u64 i;
578
579         /*
580          * Setting hierarchical PXNTable attributes on table entries covering
581          * the linear region is only possible if it is guaranteed that no table
582          * entries at any level are being shared between the linear region and
583          * the vmalloc region. Check whether this is true for the PGD level, in
584          * which case it is guaranteed to be true for all other levels as well.
585          */
586         BUILD_BUG_ON(pgd_index(direct_map_end - 1) == pgd_index(direct_map_end));
587
588         early_kfence_pool = arm64_kfence_alloc_pool();
589
590         if (can_set_direct_map())
591                 flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
592
593         /*
594          * Take care not to create a writable alias for the
595          * read-only text and rodata sections of the kernel image.
596          * So temporarily mark them as NOMAP to skip mappings in
597          * the following for-loop
598          */
599         memblock_mark_nomap(kernel_start, kernel_end - kernel_start);
600
601         /* map all the memory banks */
602         for_each_mem_range(i, &start, &end) {
603                 if (start >= end)
604                         break;
605                 /*
606                  * The linear map must allow allocation tags reading/writing
607                  * if MTE is present. Otherwise, it has the same attributes as
608                  * PAGE_KERNEL.
609                  */
610                 __map_memblock(pgdp, start, end, pgprot_tagged(PAGE_KERNEL),
611                                flags);
612         }
613
614         /*
615          * Map the linear alias of the [_stext, __init_begin) interval
616          * as non-executable now, and remove the write permission in
617          * mark_linear_text_alias_ro() below (which will be called after
618          * alternative patching has completed). This makes the contents
619          * of the region accessible to subsystems such as hibernate,
620          * but protects it from inadvertent modification or execution.
621          * Note that contiguous mappings cannot be remapped in this way,
622          * so we should avoid them here.
623          */
624         __map_memblock(pgdp, kernel_start, kernel_end,
625                        PAGE_KERNEL, NO_CONT_MAPPINGS);
626         memblock_clear_nomap(kernel_start, kernel_end - kernel_start);
627         arm64_kfence_map_pool(early_kfence_pool, pgdp);
628 }
629
630 void mark_rodata_ro(void)
631 {
632         unsigned long section_size;
633
634         /*
635          * mark .rodata as read only. Use __init_begin rather than __end_rodata
636          * to cover NOTES and EXCEPTION_TABLE.
637          */
638         section_size = (unsigned long)__init_begin - (unsigned long)__start_rodata;
639         WRITE_ONCE(rodata_is_rw, false);
640         update_mapping_prot(__pa_symbol(__start_rodata), (unsigned long)__start_rodata,
641                             section_size, PAGE_KERNEL_RO);
642
643         debug_checkwx();
644 }
645
646 static void __init declare_vma(struct vm_struct *vma,
647                                void *va_start, void *va_end,
648                                unsigned long vm_flags)
649 {
650         phys_addr_t pa_start = __pa_symbol(va_start);
651         unsigned long size = va_end - va_start;
652
653         BUG_ON(!PAGE_ALIGNED(pa_start));
654         BUG_ON(!PAGE_ALIGNED(size));
655
656         if (!(vm_flags & VM_NO_GUARD))
657                 size += PAGE_SIZE;
658
659         vma->addr       = va_start;
660         vma->phys_addr  = pa_start;
661         vma->size       = size;
662         vma->flags      = VM_MAP | vm_flags;
663         vma->caller     = __builtin_return_address(0);
664
665         vm_area_add_early(vma);
666 }
667
668 #ifdef CONFIG_UNMAP_KERNEL_AT_EL0
669 static pgprot_t kernel_exec_prot(void)
670 {
671         return rodata_enabled ? PAGE_KERNEL_ROX : PAGE_KERNEL_EXEC;
672 }
673
674 static int __init map_entry_trampoline(void)
675 {
676         int i;
677
678         if (!arm64_kernel_unmapped_at_el0())
679                 return 0;
680
681         pgprot_t prot = kernel_exec_prot();
682         phys_addr_t pa_start = __pa_symbol(__entry_tramp_text_start);
683
684         /* The trampoline is always mapped and can therefore be global */
685         pgprot_val(prot) &= ~PTE_NG;
686
687         /* Map only the text into the trampoline page table */
688         memset(tramp_pg_dir, 0, PGD_SIZE);
689         __create_pgd_mapping(tramp_pg_dir, pa_start, TRAMP_VALIAS,
690                              entry_tramp_text_size(), prot,
691                              __pgd_pgtable_alloc, NO_BLOCK_MAPPINGS);
692
693         /* Map both the text and data into the kernel page table */
694         for (i = 0; i < DIV_ROUND_UP(entry_tramp_text_size(), PAGE_SIZE); i++)
695                 __set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
696                              pa_start + i * PAGE_SIZE, prot);
697
698         if (IS_ENABLED(CONFIG_RELOCATABLE))
699                 __set_fixmap(FIX_ENTRY_TRAMP_TEXT1 - i,
700                              pa_start + i * PAGE_SIZE, PAGE_KERNEL_RO);
701
702         return 0;
703 }
704 core_initcall(map_entry_trampoline);
705 #endif
706
707 /*
708  * Declare the VMA areas for the kernel
709  */
710 static void __init declare_kernel_vmas(void)
711 {
712         static struct vm_struct vmlinux_seg[KERNEL_SEGMENT_COUNT];
713
714         declare_vma(&vmlinux_seg[0], _stext, _etext, VM_NO_GUARD);
715         declare_vma(&vmlinux_seg[1], __start_rodata, __inittext_begin, VM_NO_GUARD);
716         declare_vma(&vmlinux_seg[2], __inittext_begin, __inittext_end, VM_NO_GUARD);
717         declare_vma(&vmlinux_seg[3], __initdata_begin, __initdata_end, VM_NO_GUARD);
718         declare_vma(&vmlinux_seg[4], _data, _end, 0);
719 }
720
721 void __pi_map_range(u64 *pgd, u64 start, u64 end, u64 pa, pgprot_t prot,
722                     int level, pte_t *tbl, bool may_use_cont, u64 va_offset);
723
724 static u8 idmap_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init,
725           kpti_ptes[IDMAP_LEVELS - 1][PAGE_SIZE] __aligned(PAGE_SIZE) __ro_after_init;
726
727 static void __init create_idmap(void)
728 {
729         u64 start = __pa_symbol(__idmap_text_start);
730         u64 end   = __pa_symbol(__idmap_text_end);
731         u64 ptep  = __pa_symbol(idmap_ptes);
732
733         __pi_map_range(&ptep, start, end, start, PAGE_KERNEL_ROX,
734                        IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
735                        __phys_to_virt(ptep) - ptep);
736
737         if (IS_ENABLED(CONFIG_UNMAP_KERNEL_AT_EL0)) {
738                 extern u32 __idmap_kpti_flag;
739                 u64 pa = __pa_symbol(&__idmap_kpti_flag);
740
741                 /*
742                  * The KPTI G-to-nG conversion code needs a read-write mapping
743                  * of its synchronization flag in the ID map.
744                  */
745                 ptep = __pa_symbol(kpti_ptes);
746                 __pi_map_range(&ptep, pa, pa + sizeof(u32), pa, PAGE_KERNEL,
747                                IDMAP_ROOT_LEVEL, (pte_t *)idmap_pg_dir, false,
748                                __phys_to_virt(ptep) - ptep);
749         }
750 }
751
752 void __init paging_init(void)
753 {
754         map_mem(swapper_pg_dir);
755
756         memblock_allow_resize();
757
758         create_idmap();
759         declare_kernel_vmas();
760 }
761
762 #ifdef CONFIG_MEMORY_HOTPLUG
763 static void free_hotplug_page_range(struct page *page, size_t size,
764                                     struct vmem_altmap *altmap)
765 {
766         if (altmap) {
767                 vmem_altmap_free(altmap, size >> PAGE_SHIFT);
768         } else {
769                 WARN_ON(PageReserved(page));
770                 free_pages((unsigned long)page_address(page), get_order(size));
771         }
772 }
773
774 static void free_hotplug_pgtable_page(struct page *page)
775 {
776         free_hotplug_page_range(page, PAGE_SIZE, NULL);
777 }
778
779 static bool pgtable_range_aligned(unsigned long start, unsigned long end,
780                                   unsigned long floor, unsigned long ceiling,
781                                   unsigned long mask)
782 {
783         start &= mask;
784         if (start < floor)
785                 return false;
786
787         if (ceiling) {
788                 ceiling &= mask;
789                 if (!ceiling)
790                         return false;
791         }
792
793         if (end - 1 > ceiling - 1)
794                 return false;
795         return true;
796 }
797
798 static void unmap_hotplug_pte_range(pmd_t *pmdp, unsigned long addr,
799                                     unsigned long end, bool free_mapped,
800                                     struct vmem_altmap *altmap)
801 {
802         pte_t *ptep, pte;
803
804         do {
805                 ptep = pte_offset_kernel(pmdp, addr);
806                 pte = READ_ONCE(*ptep);
807                 if (pte_none(pte))
808                         continue;
809
810                 WARN_ON(!pte_present(pte));
811                 pte_clear(&init_mm, addr, ptep);
812                 flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
813                 if (free_mapped)
814                         free_hotplug_page_range(pte_page(pte),
815                                                 PAGE_SIZE, altmap);
816         } while (addr += PAGE_SIZE, addr < end);
817 }
818
819 static void unmap_hotplug_pmd_range(pud_t *pudp, unsigned long addr,
820                                     unsigned long end, bool free_mapped,
821                                     struct vmem_altmap *altmap)
822 {
823         unsigned long next;
824         pmd_t *pmdp, pmd;
825
826         do {
827                 next = pmd_addr_end(addr, end);
828                 pmdp = pmd_offset(pudp, addr);
829                 pmd = READ_ONCE(*pmdp);
830                 if (pmd_none(pmd))
831                         continue;
832
833                 WARN_ON(!pmd_present(pmd));
834                 if (pmd_sect(pmd)) {
835                         pmd_clear(pmdp);
836
837                         /*
838                          * One TLBI should be sufficient here as the PMD_SIZE
839                          * range is mapped with a single block entry.
840                          */
841                         flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
842                         if (free_mapped)
843                                 free_hotplug_page_range(pmd_page(pmd),
844                                                         PMD_SIZE, altmap);
845                         continue;
846                 }
847                 WARN_ON(!pmd_table(pmd));
848                 unmap_hotplug_pte_range(pmdp, addr, next, free_mapped, altmap);
849         } while (addr = next, addr < end);
850 }
851
852 static void unmap_hotplug_pud_range(p4d_t *p4dp, unsigned long addr,
853                                     unsigned long end, bool free_mapped,
854                                     struct vmem_altmap *altmap)
855 {
856         unsigned long next;
857         pud_t *pudp, pud;
858
859         do {
860                 next = pud_addr_end(addr, end);
861                 pudp = pud_offset(p4dp, addr);
862                 pud = READ_ONCE(*pudp);
863                 if (pud_none(pud))
864                         continue;
865
866                 WARN_ON(!pud_present(pud));
867                 if (pud_sect(pud)) {
868                         pud_clear(pudp);
869
870                         /*
871                          * One TLBI should be sufficient here as the PUD_SIZE
872                          * range is mapped with a single block entry.
873                          */
874                         flush_tlb_kernel_range(addr, addr + PAGE_SIZE);
875                         if (free_mapped)
876                                 free_hotplug_page_range(pud_page(pud),
877                                                         PUD_SIZE, altmap);
878                         continue;
879                 }
880                 WARN_ON(!pud_table(pud));
881                 unmap_hotplug_pmd_range(pudp, addr, next, free_mapped, altmap);
882         } while (addr = next, addr < end);
883 }
884
885 static void unmap_hotplug_p4d_range(pgd_t *pgdp, unsigned long addr,
886                                     unsigned long end, bool free_mapped,
887                                     struct vmem_altmap *altmap)
888 {
889         unsigned long next;
890         p4d_t *p4dp, p4d;
891
892         do {
893                 next = p4d_addr_end(addr, end);
894                 p4dp = p4d_offset(pgdp, addr);
895                 p4d = READ_ONCE(*p4dp);
896                 if (p4d_none(p4d))
897                         continue;
898
899                 WARN_ON(!p4d_present(p4d));
900                 unmap_hotplug_pud_range(p4dp, addr, next, free_mapped, altmap);
901         } while (addr = next, addr < end);
902 }
903
904 static void unmap_hotplug_range(unsigned long addr, unsigned long end,
905                                 bool free_mapped, struct vmem_altmap *altmap)
906 {
907         unsigned long next;
908         pgd_t *pgdp, pgd;
909
910         /*
911          * altmap can only be used as vmemmap mapping backing memory.
912          * In case the backing memory itself is not being freed, then
913          * altmap is irrelevant. Warn about this inconsistency when
914          * encountered.
915          */
916         WARN_ON(!free_mapped && altmap);
917
918         do {
919                 next = pgd_addr_end(addr, end);
920                 pgdp = pgd_offset_k(addr);
921                 pgd = READ_ONCE(*pgdp);
922                 if (pgd_none(pgd))
923                         continue;
924
925                 WARN_ON(!pgd_present(pgd));
926                 unmap_hotplug_p4d_range(pgdp, addr, next, free_mapped, altmap);
927         } while (addr = next, addr < end);
928 }
929
930 static void free_empty_pte_table(pmd_t *pmdp, unsigned long addr,
931                                  unsigned long end, unsigned long floor,
932                                  unsigned long ceiling)
933 {
934         pte_t *ptep, pte;
935         unsigned long i, start = addr;
936
937         do {
938                 ptep = pte_offset_kernel(pmdp, addr);
939                 pte = READ_ONCE(*ptep);
940
941                 /*
942                  * This is just a sanity check here which verifies that
943                  * pte clearing has been done by earlier unmap loops.
944                  */
945                 WARN_ON(!pte_none(pte));
946         } while (addr += PAGE_SIZE, addr < end);
947
948         if (!pgtable_range_aligned(start, end, floor, ceiling, PMD_MASK))
949                 return;
950
951         /*
952          * Check whether we can free the pte page if the rest of the
953          * entries are empty. Overlap with other regions have been
954          * handled by the floor/ceiling check.
955          */
956         ptep = pte_offset_kernel(pmdp, 0UL);
957         for (i = 0; i < PTRS_PER_PTE; i++) {
958                 if (!pte_none(READ_ONCE(ptep[i])))
959                         return;
960         }
961
962         pmd_clear(pmdp);
963         __flush_tlb_kernel_pgtable(start);
964         free_hotplug_pgtable_page(virt_to_page(ptep));
965 }
966
967 static void free_empty_pmd_table(pud_t *pudp, unsigned long addr,
968                                  unsigned long end, unsigned long floor,
969                                  unsigned long ceiling)
970 {
971         pmd_t *pmdp, pmd;
972         unsigned long i, next, start = addr;
973
974         do {
975                 next = pmd_addr_end(addr, end);
976                 pmdp = pmd_offset(pudp, addr);
977                 pmd = READ_ONCE(*pmdp);
978                 if (pmd_none(pmd))
979                         continue;
980
981                 WARN_ON(!pmd_present(pmd) || !pmd_table(pmd) || pmd_sect(pmd));
982                 free_empty_pte_table(pmdp, addr, next, floor, ceiling);
983         } while (addr = next, addr < end);
984
985         if (CONFIG_PGTABLE_LEVELS <= 2)
986                 return;
987
988         if (!pgtable_range_aligned(start, end, floor, ceiling, PUD_MASK))
989                 return;
990
991         /*
992          * Check whether we can free the pmd page if the rest of the
993          * entries are empty. Overlap with other regions have been
994          * handled by the floor/ceiling check.
995          */
996         pmdp = pmd_offset(pudp, 0UL);
997         for (i = 0; i < PTRS_PER_PMD; i++) {
998                 if (!pmd_none(READ_ONCE(pmdp[i])))
999                         return;
1000         }
1001
1002         pud_clear(pudp);
1003         __flush_tlb_kernel_pgtable(start);
1004         free_hotplug_pgtable_page(virt_to_page(pmdp));
1005 }
1006
1007 static void free_empty_pud_table(p4d_t *p4dp, unsigned long addr,
1008                                  unsigned long end, unsigned long floor,
1009                                  unsigned long ceiling)
1010 {
1011         pud_t *pudp, pud;
1012         unsigned long i, next, start = addr;
1013
1014         do {
1015                 next = pud_addr_end(addr, end);
1016                 pudp = pud_offset(p4dp, addr);
1017                 pud = READ_ONCE(*pudp);
1018                 if (pud_none(pud))
1019                         continue;
1020
1021                 WARN_ON(!pud_present(pud) || !pud_table(pud) || pud_sect(pud));
1022                 free_empty_pmd_table(pudp, addr, next, floor, ceiling);
1023         } while (addr = next, addr < end);
1024
1025         if (CONFIG_PGTABLE_LEVELS <= 3)
1026                 return;
1027
1028         if (!pgtable_range_aligned(start, end, floor, ceiling, PGDIR_MASK))
1029                 return;
1030
1031         /*
1032          * Check whether we can free the pud page if the rest of the
1033          * entries are empty. Overlap with other regions have been
1034          * handled by the floor/ceiling check.
1035          */
1036         pudp = pud_offset(p4dp, 0UL);
1037         for (i = 0; i < PTRS_PER_PUD; i++) {
1038                 if (!pud_none(READ_ONCE(pudp[i])))
1039                         return;
1040         }
1041
1042         p4d_clear(p4dp);
1043         __flush_tlb_kernel_pgtable(start);
1044         free_hotplug_pgtable_page(virt_to_page(pudp));
1045 }
1046
1047 static void free_empty_p4d_table(pgd_t *pgdp, unsigned long addr,
1048                                  unsigned long end, unsigned long floor,
1049                                  unsigned long ceiling)
1050 {
1051         unsigned long next;
1052         p4d_t *p4dp, p4d;
1053
1054         do {
1055                 next = p4d_addr_end(addr, end);
1056                 p4dp = p4d_offset(pgdp, addr);
1057                 p4d = READ_ONCE(*p4dp);
1058                 if (p4d_none(p4d))
1059                         continue;
1060
1061                 WARN_ON(!p4d_present(p4d));
1062                 free_empty_pud_table(p4dp, addr, next, floor, ceiling);
1063         } while (addr = next, addr < end);
1064 }
1065
1066 static void free_empty_tables(unsigned long addr, unsigned long end,
1067                               unsigned long floor, unsigned long ceiling)
1068 {
1069         unsigned long next;
1070         pgd_t *pgdp, pgd;
1071
1072         do {
1073                 next = pgd_addr_end(addr, end);
1074                 pgdp = pgd_offset_k(addr);
1075                 pgd = READ_ONCE(*pgdp);
1076                 if (pgd_none(pgd))
1077                         continue;
1078
1079                 WARN_ON(!pgd_present(pgd));
1080                 free_empty_p4d_table(pgdp, addr, next, floor, ceiling);
1081         } while (addr = next, addr < end);
1082 }
1083 #endif
1084
1085 void __meminit vmemmap_set_pmd(pmd_t *pmdp, void *p, int node,
1086                                unsigned long addr, unsigned long next)
1087 {
1088         pmd_set_huge(pmdp, __pa(p), __pgprot(PROT_SECT_NORMAL));
1089 }
1090
1091 int __meminit vmemmap_check_pmd(pmd_t *pmdp, int node,
1092                                 unsigned long addr, unsigned long next)
1093 {
1094         vmemmap_verify((pte_t *)pmdp, node, addr, next);
1095         return 1;
1096 }
1097
1098 int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node,
1099                 struct vmem_altmap *altmap)
1100 {
1101         WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1102
1103         if (!IS_ENABLED(CONFIG_ARM64_4K_PAGES))
1104                 return vmemmap_populate_basepages(start, end, node, altmap);
1105         else
1106                 return vmemmap_populate_hugepages(start, end, node, altmap);
1107 }
1108
1109 #ifdef CONFIG_MEMORY_HOTPLUG
1110 void vmemmap_free(unsigned long start, unsigned long end,
1111                 struct vmem_altmap *altmap)
1112 {
1113         WARN_ON((start < VMEMMAP_START) || (end > VMEMMAP_END));
1114
1115         unmap_hotplug_range(start, end, true, altmap);
1116         free_empty_tables(start, end, VMEMMAP_START, VMEMMAP_END);
1117 }
1118 #endif /* CONFIG_MEMORY_HOTPLUG */
1119
1120 int pud_set_huge(pud_t *pudp, phys_addr_t phys, pgprot_t prot)
1121 {
1122         pud_t new_pud = pfn_pud(__phys_to_pfn(phys), mk_pud_sect_prot(prot));
1123
1124         /* Only allow permission changes for now */
1125         if (!pgattr_change_is_safe(READ_ONCE(pud_val(*pudp)),
1126                                    pud_val(new_pud)))
1127                 return 0;
1128
1129         VM_BUG_ON(phys & ~PUD_MASK);
1130         set_pud(pudp, new_pud);
1131         return 1;
1132 }
1133
1134 int pmd_set_huge(pmd_t *pmdp, phys_addr_t phys, pgprot_t prot)
1135 {
1136         pmd_t new_pmd = pfn_pmd(__phys_to_pfn(phys), mk_pmd_sect_prot(prot));
1137
1138         /* Only allow permission changes for now */
1139         if (!pgattr_change_is_safe(READ_ONCE(pmd_val(*pmdp)),
1140                                    pmd_val(new_pmd)))
1141                 return 0;
1142
1143         VM_BUG_ON(phys & ~PMD_MASK);
1144         set_pmd(pmdp, new_pmd);
1145         return 1;
1146 }
1147
1148 int pud_clear_huge(pud_t *pudp)
1149 {
1150         if (!pud_sect(READ_ONCE(*pudp)))
1151                 return 0;
1152         pud_clear(pudp);
1153         return 1;
1154 }
1155
1156 int pmd_clear_huge(pmd_t *pmdp)
1157 {
1158         if (!pmd_sect(READ_ONCE(*pmdp)))
1159                 return 0;
1160         pmd_clear(pmdp);
1161         return 1;
1162 }
1163
1164 int pmd_free_pte_page(pmd_t *pmdp, unsigned long addr)
1165 {
1166         pte_t *table;
1167         pmd_t pmd;
1168
1169         pmd = READ_ONCE(*pmdp);
1170
1171         if (!pmd_table(pmd)) {
1172                 VM_WARN_ON(1);
1173                 return 1;
1174         }
1175
1176         table = pte_offset_kernel(pmdp, addr);
1177         pmd_clear(pmdp);
1178         __flush_tlb_kernel_pgtable(addr);
1179         pte_free_kernel(NULL, table);
1180         return 1;
1181 }
1182
1183 int pud_free_pmd_page(pud_t *pudp, unsigned long addr)
1184 {
1185         pmd_t *table;
1186         pmd_t *pmdp;
1187         pud_t pud;
1188         unsigned long next, end;
1189
1190         pud = READ_ONCE(*pudp);
1191
1192         if (!pud_table(pud)) {
1193                 VM_WARN_ON(1);
1194                 return 1;
1195         }
1196
1197         table = pmd_offset(pudp, addr);
1198         pmdp = table;
1199         next = addr;
1200         end = addr + PUD_SIZE;
1201         do {
1202                 pmd_free_pte_page(pmdp, next);
1203         } while (pmdp++, next += PMD_SIZE, next != end);
1204
1205         pud_clear(pudp);
1206         __flush_tlb_kernel_pgtable(addr);
1207         pmd_free(NULL, table);
1208         return 1;
1209 }
1210
1211 #ifdef CONFIG_MEMORY_HOTPLUG
1212 static void __remove_pgd_mapping(pgd_t *pgdir, unsigned long start, u64 size)
1213 {
1214         unsigned long end = start + size;
1215
1216         WARN_ON(pgdir != init_mm.pgd);
1217         WARN_ON((start < PAGE_OFFSET) || (end > PAGE_END));
1218
1219         unmap_hotplug_range(start, end, false, NULL);
1220         free_empty_tables(start, end, PAGE_OFFSET, PAGE_END);
1221 }
1222
1223 struct range arch_get_mappable_range(void)
1224 {
1225         struct range mhp_range;
1226         u64 start_linear_pa = __pa(_PAGE_OFFSET(vabits_actual));
1227         u64 end_linear_pa = __pa(PAGE_END - 1);
1228
1229         if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) {
1230                 /*
1231                  * Check for a wrap, it is possible because of randomized linear
1232                  * mapping the start physical address is actually bigger than
1233                  * the end physical address. In this case set start to zero
1234                  * because [0, end_linear_pa] range must still be able to cover
1235                  * all addressable physical addresses.
1236                  */
1237                 if (start_linear_pa > end_linear_pa)
1238                         start_linear_pa = 0;
1239         }
1240
1241         WARN_ON(start_linear_pa > end_linear_pa);
1242
1243         /*
1244          * Linear mapping region is the range [PAGE_OFFSET..(PAGE_END - 1)]
1245          * accommodating both its ends but excluding PAGE_END. Max physical
1246          * range which can be mapped inside this linear mapping range, must
1247          * also be derived from its end points.
1248          */
1249         mhp_range.start = start_linear_pa;
1250         mhp_range.end =  end_linear_pa;
1251
1252         return mhp_range;
1253 }
1254
1255 int arch_add_memory(int nid, u64 start, u64 size,
1256                     struct mhp_params *params)
1257 {
1258         int ret, flags = NO_EXEC_MAPPINGS;
1259
1260         VM_BUG_ON(!mhp_range_allowed(start, size, true));
1261
1262         if (can_set_direct_map())
1263                 flags |= NO_BLOCK_MAPPINGS | NO_CONT_MAPPINGS;
1264
1265         __create_pgd_mapping(swapper_pg_dir, start, __phys_to_virt(start),
1266                              size, params->pgprot, __pgd_pgtable_alloc,
1267                              flags);
1268
1269         memblock_clear_nomap(start, size);
1270
1271         ret = __add_pages(nid, start >> PAGE_SHIFT, size >> PAGE_SHIFT,
1272                            params);
1273         if (ret)
1274                 __remove_pgd_mapping(swapper_pg_dir,
1275                                      __phys_to_virt(start), size);
1276         else {
1277                 max_pfn = PFN_UP(start + size);
1278                 max_low_pfn = max_pfn;
1279         }
1280
1281         return ret;
1282 }
1283
1284 void arch_remove_memory(u64 start, u64 size, struct vmem_altmap *altmap)
1285 {
1286         unsigned long start_pfn = start >> PAGE_SHIFT;
1287         unsigned long nr_pages = size >> PAGE_SHIFT;
1288
1289         __remove_pages(start_pfn, nr_pages, altmap);
1290         __remove_pgd_mapping(swapper_pg_dir, __phys_to_virt(start), size);
1291 }
1292
1293 /*
1294  * This memory hotplug notifier helps prevent boot memory from being
1295  * inadvertently removed as it blocks pfn range offlining process in
1296  * __offline_pages(). Hence this prevents both offlining as well as
1297  * removal process for boot memory which is initially always online.
1298  * In future if and when boot memory could be removed, this notifier
1299  * should be dropped and free_hotplug_page_range() should handle any
1300  * reserved pages allocated during boot.
1301  */
1302 static int prevent_bootmem_remove_notifier(struct notifier_block *nb,
1303                                            unsigned long action, void *data)
1304 {
1305         struct mem_section *ms;
1306         struct memory_notify *arg = data;
1307         unsigned long end_pfn = arg->start_pfn + arg->nr_pages;
1308         unsigned long pfn = arg->start_pfn;
1309
1310         if ((action != MEM_GOING_OFFLINE) && (action != MEM_OFFLINE))
1311                 return NOTIFY_OK;
1312
1313         for (; pfn < end_pfn; pfn += PAGES_PER_SECTION) {
1314                 unsigned long start = PFN_PHYS(pfn);
1315                 unsigned long end = start + (1UL << PA_SECTION_SHIFT);
1316
1317                 ms = __pfn_to_section(pfn);
1318                 if (!early_section(ms))
1319                         continue;
1320
1321                 if (action == MEM_GOING_OFFLINE) {
1322                         /*
1323                          * Boot memory removal is not supported. Prevent
1324                          * it via blocking any attempted offline request
1325                          * for the boot memory and just report it.
1326                          */
1327                         pr_warn("Boot memory [%lx %lx] offlining attempted\n", start, end);
1328                         return NOTIFY_BAD;
1329                 } else if (action == MEM_OFFLINE) {
1330                         /*
1331                          * This should have never happened. Boot memory
1332                          * offlining should have been prevented by this
1333                          * very notifier. Probably some memory removal
1334                          * procedure might have changed which would then
1335                          * require further debug.
1336                          */
1337                         pr_err("Boot memory [%lx %lx] offlined\n", start, end);
1338
1339                         /*
1340                          * Core memory hotplug does not process a return
1341                          * code from the notifier for MEM_OFFLINE events.
1342                          * The error condition has been reported. Return
1343                          * from here as if ignored.
1344                          */
1345                         return NOTIFY_DONE;
1346                 }
1347         }
1348         return NOTIFY_OK;
1349 }
1350
1351 static struct notifier_block prevent_bootmem_remove_nb = {
1352         .notifier_call = prevent_bootmem_remove_notifier,
1353 };
1354
1355 /*
1356  * This ensures that boot memory sections on the platform are online
1357  * from early boot. Memory sections could not be prevented from being
1358  * offlined, unless for some reason they are not online to begin with.
1359  * This helps validate the basic assumption on which the above memory
1360  * event notifier works to prevent boot memory section offlining and
1361  * its possible removal.
1362  */
1363 static void validate_bootmem_online(void)
1364 {
1365         phys_addr_t start, end, addr;
1366         struct mem_section *ms;
1367         u64 i;
1368
1369         /*
1370          * Scanning across all memblock might be expensive
1371          * on some big memory systems. Hence enable this
1372          * validation only with DEBUG_VM.
1373          */
1374         if (!IS_ENABLED(CONFIG_DEBUG_VM))
1375                 return;
1376
1377         for_each_mem_range(i, &start, &end) {
1378                 for (addr = start; addr < end; addr += (1UL << PA_SECTION_SHIFT)) {
1379                         ms = __pfn_to_section(PHYS_PFN(addr));
1380
1381                         /*
1382                          * All memory ranges in the system at this point
1383                          * should have been marked as early sections.
1384                          */
1385                         WARN_ON(!early_section(ms));
1386
1387                         /*
1388                          * Memory notifier mechanism here to prevent boot
1389                          * memory offlining depends on the fact that each
1390                          * early section memory on the system is initially
1391                          * online. Otherwise a given memory section which
1392                          * is already offline will be overlooked and can
1393                          * be removed completely. Call out such sections.
1394                          */
1395                         if (!online_section(ms))
1396                                 pr_err("Boot memory [%llx %llx] is offline, can be removed\n",
1397                                         addr, addr + (1UL << PA_SECTION_SHIFT));
1398                 }
1399         }
1400 }
1401
1402 static int __init prevent_bootmem_remove_init(void)
1403 {
1404         int ret = 0;
1405
1406         if (!IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
1407                 return ret;
1408
1409         validate_bootmem_online();
1410         ret = register_memory_notifier(&prevent_bootmem_remove_nb);
1411         if (ret)
1412                 pr_err("%s: Notifier registration failed %d\n", __func__, ret);
1413
1414         return ret;
1415 }
1416 early_initcall(prevent_bootmem_remove_init);
1417 #endif
1418
1419 pte_t ptep_modify_prot_start(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep)
1420 {
1421         if (alternative_has_cap_unlikely(ARM64_WORKAROUND_2645198)) {
1422                 /*
1423                  * Break-before-make (BBM) is required for all user space mappings
1424                  * when the permission changes from executable to non-executable
1425                  * in cases where cpu is affected with errata #2645198.
1426                  */
1427                 if (pte_user_exec(READ_ONCE(*ptep)))
1428                         return ptep_clear_flush(vma, addr, ptep);
1429         }
1430         return ptep_get_and_clear(vma->vm_mm, addr, ptep);
1431 }
1432
1433 void ptep_modify_prot_commit(struct vm_area_struct *vma, unsigned long addr, pte_t *ptep,
1434                              pte_t old_pte, pte_t pte)
1435 {
1436         set_pte_at(vma->vm_mm, addr, ptep, pte);
1437 }
1438
1439 /*
1440  * Atomically replaces the active TTBR1_EL1 PGD with a new VA-compatible PGD,
1441  * avoiding the possibility of conflicting TLB entries being allocated.
1442  */
1443 void __cpu_replace_ttbr1(pgd_t *pgdp, bool cnp)
1444 {
1445         typedef void (ttbr_replace_func)(phys_addr_t);
1446         extern ttbr_replace_func idmap_cpu_replace_ttbr1;
1447         ttbr_replace_func *replace_phys;
1448         unsigned long daif;
1449
1450         /* phys_to_ttbr() zeros lower 2 bits of ttbr with 52-bit PA */
1451         phys_addr_t ttbr1 = phys_to_ttbr(virt_to_phys(pgdp));
1452
1453         if (cnp)
1454                 ttbr1 |= TTBR_CNP_BIT;
1455
1456         replace_phys = (void *)__pa_symbol(idmap_cpu_replace_ttbr1);
1457
1458         cpu_install_idmap();
1459
1460         /*
1461          * We really don't want to take *any* exceptions while TTBR1 is
1462          * in the process of being replaced so mask everything.
1463          */
1464         daif = local_daif_save();
1465         replace_phys(ttbr1);
1466         local_daif_restore(daif);
1467
1468         cpu_uninstall_idmap();
1469 }