1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * PowerPC64 port by Mike Corrigan and Dave Engebretsen
4 * {mikejc|engebret}@us.ibm.com
6 * Copyright (c) 2000 Mike Corrigan <mikejc@us.ibm.com>
8 * SMP scalability work:
9 * Copyright (C) 2001 Anton Blanchard <anton@au.ibm.com>, IBM
14 * PowerPC Hashed Page Table functions
20 #define pr_fmt(fmt) "hash-mmu: " fmt
21 #include <linux/spinlock.h>
22 #include <linux/errno.h>
23 #include <linux/sched/mm.h>
24 #include <linux/proc_fs.h>
25 #include <linux/stat.h>
26 #include <linux/sysctl.h>
27 #include <linux/export.h>
28 #include <linux/ctype.h>
29 #include <linux/cache.h>
30 #include <linux/init.h>
31 #include <linux/signal.h>
32 #include <linux/memblock.h>
33 #include <linux/context_tracking.h>
34 #include <linux/libfdt.h>
35 #include <linux/pkeys.h>
36 #include <linux/hugetlb.h>
37 #include <linux/cpu.h>
38 #include <linux/pgtable.h>
39 #include <linux/debugfs.h>
40 #include <linux/random.h>
41 #include <linux/elf-randomize.h>
42 #include <linux/of_fdt.h>
44 #include <asm/interrupt.h>
45 #include <asm/processor.h>
47 #include <asm/mmu_context.h>
49 #include <asm/types.h>
50 #include <linux/uaccess.h>
51 #include <asm/machdep.h>
55 #include <asm/cacheflush.h>
56 #include <asm/cputable.h>
57 #include <asm/sections.h>
58 #include <asm/copro.h>
60 #include <asm/code-patching.h>
61 #include <asm/fadump.h>
62 #include <asm/firmware.h>
64 #include <asm/trace.h>
66 #include <asm/pte-walk.h>
67 #include <asm/asm-prototypes.h>
68 #include <asm/ultravisor.h>
70 #include <mm/mmu_decl.h>
76 #define DBG(fmt...) udbg_printf(fmt)
82 #define DBG_LOW(fmt...) udbg_printf(fmt)
84 #define DBG_LOW(fmt...)
92 * Note: pte --> Linux PTE
93 * HPTE --> PowerPC Hashed Page Table Entry
96 * htab_initialize is called with the MMU off (of course), but
97 * the kernel has been copied down to zero so it can directly
98 * reference global data. At this point it is very difficult
99 * to print debug info.
103 static unsigned long _SDR1;
105 u8 hpte_page_sizes[1 << LP_BITS];
106 EXPORT_SYMBOL_GPL(hpte_page_sizes);
108 struct hash_pte *htab_address;
109 unsigned long htab_size_bytes;
110 unsigned long htab_hash_mask;
111 EXPORT_SYMBOL_GPL(htab_hash_mask);
112 int mmu_linear_psize = MMU_PAGE_4K;
113 EXPORT_SYMBOL_GPL(mmu_linear_psize);
114 int mmu_virtual_psize = MMU_PAGE_4K;
115 int mmu_vmalloc_psize = MMU_PAGE_4K;
116 EXPORT_SYMBOL_GPL(mmu_vmalloc_psize);
117 int mmu_io_psize = MMU_PAGE_4K;
118 int mmu_kernel_ssize = MMU_SEGSIZE_256M;
119 EXPORT_SYMBOL_GPL(mmu_kernel_ssize);
120 int mmu_highuser_ssize = MMU_SEGSIZE_256M;
121 u16 mmu_slb_size = 64;
122 EXPORT_SYMBOL_GPL(mmu_slb_size);
123 #ifdef CONFIG_PPC_64K_PAGES
124 int mmu_ci_restrictions;
126 static u8 *linear_map_hash_slots;
127 static unsigned long linear_map_hash_count;
128 struct mmu_hash_ops mmu_hash_ops;
129 EXPORT_SYMBOL(mmu_hash_ops);
132 * These are definitions of page sizes arrays to be used when none
133 * is provided by the firmware.
137 * Fallback (4k pages only)
139 static struct mmu_psize_def mmu_psize_defaults[] = {
143 .penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},
150 * POWER4, GPUL, POWER5
152 * Support for 16Mb large pages
154 static struct mmu_psize_def mmu_psize_defaults_gp[] = {
158 .penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},
165 .penc = {[0 ... MMU_PAGE_16M - 1] = -1, [MMU_PAGE_16M] = 0,
166 [MMU_PAGE_16M + 1 ... MMU_PAGE_COUNT - 1] = -1 },
172 static inline void tlbiel_hash_set_isa206(unsigned int set, unsigned int is)
176 rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));
178 asm volatile("tlbiel %0" : : "r" (rb));
182 * tlbiel instruction for hash, set invalidation
183 * i.e., r=1 and is=01 or is=10 or is=11
185 static __always_inline void tlbiel_hash_set_isa300(unsigned int set, unsigned int is,
187 unsigned int ric, unsigned int prs)
191 unsigned int r = 0; /* hash format */
193 rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));
194 rs = ((unsigned long)pid << PPC_BITLSHIFT(31));
196 asm volatile(PPC_TLBIEL(%0, %1, %2, %3, %4)
197 : : "r"(rb), "r"(rs), "i"(ric), "i"(prs), "i"(r)
202 static void tlbiel_all_isa206(unsigned int num_sets, unsigned int is)
206 asm volatile("ptesync": : :"memory");
208 for (set = 0; set < num_sets; set++)
209 tlbiel_hash_set_isa206(set, is);
211 ppc_after_tlbiel_barrier();
214 static void tlbiel_all_isa300(unsigned int num_sets, unsigned int is)
218 asm volatile("ptesync": : :"memory");
221 * Flush the partition table cache if this is HV mode.
223 if (early_cpu_has_feature(CPU_FTR_HVMODE))
224 tlbiel_hash_set_isa300(0, is, 0, 2, 0);
227 * Now invalidate the process table cache. UPRT=0 HPT modes (what
228 * current hardware implements) do not use the process table, but
229 * add the flushes anyway.
231 * From ISA v3.0B p. 1078:
232 * The following forms are invalid.
233 * * PRS=1, R=0, and RIC!=2 (The only process-scoped
234 * HPT caching is of the Process Table.)
236 tlbiel_hash_set_isa300(0, is, 0, 2, 1);
239 * Then flush the sets of the TLB proper. Hash mode uses
240 * partition scoped TLB translations, which may be flushed
243 for (set = 0; set < num_sets; set++)
244 tlbiel_hash_set_isa300(set, is, 0, 0, 0);
246 ppc_after_tlbiel_barrier();
248 asm volatile(PPC_ISA_3_0_INVALIDATE_ERAT "; isync" : : :"memory");
251 void hash__tlbiel_all(unsigned int action)
256 case TLB_INVAL_SCOPE_GLOBAL:
259 case TLB_INVAL_SCOPE_LPID:
266 if (early_cpu_has_feature(CPU_FTR_ARCH_300))
267 tlbiel_all_isa300(POWER9_TLB_SETS_HASH, is);
268 else if (early_cpu_has_feature(CPU_FTR_ARCH_207S))
269 tlbiel_all_isa206(POWER8_TLB_SETS, is);
270 else if (early_cpu_has_feature(CPU_FTR_ARCH_206))
271 tlbiel_all_isa206(POWER7_TLB_SETS, is);
273 WARN(1, "%s called on pre-POWER7 CPU\n", __func__);
277 * 'R' and 'C' update notes:
278 * - Under pHyp or KVM, the updatepp path will not set C, thus it *will*
279 * create writeable HPTEs without C set, because the hcall H_PROTECT
280 * that we use in that case will not update C
281 * - The above is however not a problem, because we also don't do that
282 * fancy "no flush" variant of eviction and we use H_REMOVE which will
283 * do the right thing and thus we don't have the race I described earlier
285 * - Under bare metal, we do have the race, so we need R and C set
286 * - We make sure R is always set and never lost
287 * - C is _PAGE_DIRTY, and *should* always be set for a writeable mapping
289 unsigned long htab_convert_pte_flags(unsigned long pteflags, unsigned long flags)
291 unsigned long rflags = 0;
293 /* _PAGE_EXEC -> NOEXEC */
294 if ((pteflags & _PAGE_EXEC) == 0)
298 * Linux uses slb key 0 for kernel and 1 for user.
299 * kernel RW areas are mapped with PPP=0b000
300 * User area is mapped with PPP=0b010 for read/write
301 * or PPP=0b011 for read-only (including writeable but clean pages).
303 if (pteflags & _PAGE_PRIVILEGED) {
305 * Kernel read only mapped with ppp bits 0b110
307 if (!(pteflags & _PAGE_WRITE)) {
308 if (mmu_has_feature(MMU_FTR_KERNEL_RO))
309 rflags |= (HPTE_R_PP0 | 0x2);
314 if (pteflags & _PAGE_RWX)
316 if (!((pteflags & _PAGE_WRITE) && (pteflags & _PAGE_DIRTY)))
320 * We can't allow hardware to update hpte bits. Hence always
321 * set 'R' bit and set 'C' if it is a write fault
325 if (pteflags & _PAGE_DIRTY)
331 if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_TOLERANT)
333 else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_NON_IDEMPOTENT)
334 rflags |= (HPTE_R_I | HPTE_R_G);
335 else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_SAO)
336 rflags |= (HPTE_R_W | HPTE_R_I | HPTE_R_M);
339 * Add memory coherence if cache inhibited is not set
343 rflags |= pte_to_hpte_pkey_bits(pteflags, flags);
347 int htab_bolt_mapping(unsigned long vstart, unsigned long vend,
348 unsigned long pstart, unsigned long prot,
349 int psize, int ssize)
351 unsigned long vaddr, paddr;
352 unsigned int step, shift;
355 shift = mmu_psize_defs[psize].shift;
358 prot = htab_convert_pte_flags(prot, HPTE_USE_KERNEL_KEY);
360 DBG("htab_bolt_mapping(%lx..%lx -> %lx (%lx,%d,%d)\n",
361 vstart, vend, pstart, prot, psize, ssize);
363 /* Carefully map only the possible range */
364 vaddr = ALIGN(vstart, step);
365 paddr = ALIGN(pstart, step);
366 vend = ALIGN_DOWN(vend, step);
368 for (; vaddr < vend; vaddr += step, paddr += step) {
369 unsigned long hash, hpteg;
370 unsigned long vsid = get_kernel_vsid(vaddr, ssize);
371 unsigned long vpn = hpt_vpn(vaddr, vsid, ssize);
372 unsigned long tprot = prot;
373 bool secondary_hash = false;
376 * If we hit a bad address return error.
380 /* Make kernel text executable */
381 if (overlaps_kernel_text(vaddr, vaddr + step))
385 * If relocatable, check if it overlaps interrupt vectors that
386 * are copied down to real 0. For relocatable kernel
387 * (e.g. kdump case) we copy interrupt vectors down to real
388 * address 0. Mark that region as executable. This is
389 * because on p8 system with relocation on exception feature
390 * enabled, exceptions are raised with MMU (IR=DR=1) ON. Hence
391 * in order to execute the interrupt handlers in virtual
392 * mode the vector region need to be marked as executable.
394 if ((PHYSICAL_START > MEMORY_START) &&
395 overlaps_interrupt_vector_text(vaddr, vaddr + step))
398 hash = hpt_hash(vpn, shift, ssize);
399 hpteg = ((hash & htab_hash_mask) * HPTES_PER_GROUP);
401 BUG_ON(!mmu_hash_ops.hpte_insert);
403 ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,
404 HPTE_V_BOLTED, psize, psize,
408 * Try to keep bolted entries in primary.
409 * Remove non bolted entries and try insert again
411 ret = mmu_hash_ops.hpte_remove(hpteg);
413 ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,
414 HPTE_V_BOLTED, psize, psize,
416 if (ret == -1 && !secondary_hash) {
417 secondary_hash = true;
418 hpteg = ((~hash & htab_hash_mask) * HPTES_PER_GROUP);
427 if (debug_pagealloc_enabled_or_kfence() &&
428 (paddr >> PAGE_SHIFT) < linear_map_hash_count)
429 linear_map_hash_slots[paddr >> PAGE_SHIFT] = ret | 0x80;
431 return ret < 0 ? ret : 0;
434 int htab_remove_mapping(unsigned long vstart, unsigned long vend,
435 int psize, int ssize)
437 unsigned long vaddr, time_limit;
438 unsigned int step, shift;
442 shift = mmu_psize_defs[psize].shift;
445 if (!mmu_hash_ops.hpte_removebolted)
448 /* Unmap the full range specificied */
449 vaddr = ALIGN_DOWN(vstart, step);
450 time_limit = jiffies + HZ;
452 for (;vaddr < vend; vaddr += step) {
453 rc = mmu_hash_ops.hpte_removebolted(vaddr, psize, ssize);
456 * For large number of mappings introduce a cond_resched()
457 * to prevent softlockup warnings.
459 if (time_after(jiffies, time_limit)) {
461 time_limit = jiffies + HZ;
474 static bool disable_1tb_segments __ro_after_init;
476 static int __init parse_disable_1tb_segments(char *p)
478 disable_1tb_segments = true;
481 early_param("disable_1tb_segments", parse_disable_1tb_segments);
483 bool stress_hpt_enabled __initdata;
485 static int __init parse_stress_hpt(char *p)
487 stress_hpt_enabled = true;
490 early_param("stress_hpt", parse_stress_hpt);
492 __ro_after_init DEFINE_STATIC_KEY_FALSE(stress_hpt_key);
495 * per-CPU array allocated if we enable stress_hpt.
497 #define STRESS_MAX_GROUPS 16
498 struct stress_hpt_struct {
499 unsigned long last_group[STRESS_MAX_GROUPS];
502 static inline int stress_nr_groups(void)
505 * LPAR H_REMOVE flushes TLB, so need some number > 1 of entries
506 * to allow practical forward progress. Bare metal returns 1, which
507 * seems to help uncover more bugs.
509 if (firmware_has_feature(FW_FEATURE_LPAR))
510 return STRESS_MAX_GROUPS;
515 static struct stress_hpt_struct *stress_hpt_struct;
517 static int __init htab_dt_scan_seg_sizes(unsigned long node,
518 const char *uname, int depth,
521 const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
525 /* We are scanning "cpu" nodes only */
526 if (type == NULL || strcmp(type, "cpu") != 0)
529 prop = of_get_flat_dt_prop(node, "ibm,processor-segment-sizes", &size);
532 for (; size >= 4; size -= 4, ++prop) {
533 if (be32_to_cpu(prop[0]) == 40) {
534 DBG("1T segment support detected\n");
536 if (disable_1tb_segments) {
537 DBG("1T segments disabled by command line\n");
541 cur_cpu_spec->mmu_features |= MMU_FTR_1T_SEGMENT;
545 cur_cpu_spec->mmu_features &= ~MMU_FTR_NO_SLBIE_B;
549 static int __init get_idx_from_shift(unsigned int shift)
573 static int __init htab_dt_scan_page_sizes(unsigned long node,
574 const char *uname, int depth,
577 const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
581 /* We are scanning "cpu" nodes only */
582 if (type == NULL || strcmp(type, "cpu") != 0)
585 prop = of_get_flat_dt_prop(node, "ibm,segment-page-sizes", &size);
589 pr_info("Page sizes from device-tree:\n");
591 cur_cpu_spec->mmu_features &= ~(MMU_FTR_16M_PAGE);
593 unsigned int base_shift = be32_to_cpu(prop[0]);
594 unsigned int slbenc = be32_to_cpu(prop[1]);
595 unsigned int lpnum = be32_to_cpu(prop[2]);
596 struct mmu_psize_def *def;
599 size -= 3; prop += 3;
600 base_idx = get_idx_from_shift(base_shift);
602 /* skip the pte encoding also */
603 prop += lpnum * 2; size -= lpnum * 2;
606 def = &mmu_psize_defs[base_idx];
607 if (base_idx == MMU_PAGE_16M)
608 cur_cpu_spec->mmu_features |= MMU_FTR_16M_PAGE;
610 def->shift = base_shift;
611 if (base_shift <= 23)
614 def->avpnm = (1 << (base_shift - 23)) - 1;
617 * We don't know for sure what's up with tlbiel, so
618 * for now we only set it for 4K and 64K pages
620 if (base_idx == MMU_PAGE_4K || base_idx == MMU_PAGE_64K)
625 while (size > 0 && lpnum) {
626 unsigned int shift = be32_to_cpu(prop[0]);
627 int penc = be32_to_cpu(prop[1]);
629 prop += 2; size -= 2;
632 idx = get_idx_from_shift(shift);
637 pr_err("Invalid penc for base_shift=%d "
638 "shift=%d\n", base_shift, shift);
640 def->penc[idx] = penc;
641 pr_info("base_shift=%d: shift=%d, sllp=0x%04lx,"
642 " avpnm=0x%08lx, tlbiel=%d, penc=%d\n",
643 base_shift, shift, def->sllp,
644 def->avpnm, def->tlbiel, def->penc[idx]);
651 #ifdef CONFIG_HUGETLB_PAGE
653 * Scan for 16G memory blocks that have been set aside for huge pages
654 * and reserve those blocks for 16G huge pages.
656 static int __init htab_dt_scan_hugepage_blocks(unsigned long node,
657 const char *uname, int depth,
659 const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
660 const __be64 *addr_prop;
661 const __be32 *page_count_prop;
662 unsigned int expected_pages;
663 long unsigned int phys_addr;
664 long unsigned int block_size;
666 /* We are scanning "memory" nodes only */
667 if (type == NULL || strcmp(type, "memory") != 0)
671 * This property is the log base 2 of the number of virtual pages that
672 * will represent this memory block.
674 page_count_prop = of_get_flat_dt_prop(node, "ibm,expected#pages", NULL);
675 if (page_count_prop == NULL)
677 expected_pages = (1 << be32_to_cpu(page_count_prop[0]));
678 addr_prop = of_get_flat_dt_prop(node, "reg", NULL);
679 if (addr_prop == NULL)
681 phys_addr = be64_to_cpu(addr_prop[0]);
682 block_size = be64_to_cpu(addr_prop[1]);
683 if (block_size != (16 * GB))
685 printk(KERN_INFO "Huge page(16GB) memory: "
686 "addr = 0x%lX size = 0x%lX pages = %d\n",
687 phys_addr, block_size, expected_pages);
688 if (phys_addr + block_size * expected_pages <= memblock_end_of_DRAM()) {
689 memblock_reserve(phys_addr, block_size * expected_pages);
690 pseries_add_gpage(phys_addr, block_size, expected_pages);
694 #endif /* CONFIG_HUGETLB_PAGE */
696 static void __init mmu_psize_set_default_penc(void)
699 for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)
700 for (apsize = 0; apsize < MMU_PAGE_COUNT; apsize++)
701 mmu_psize_defs[bpsize].penc[apsize] = -1;
704 #ifdef CONFIG_PPC_64K_PAGES
706 static bool __init might_have_hea(void)
709 * The HEA ethernet adapter requires awareness of the
710 * GX bus. Without that awareness we can easily assume
711 * we will never see an HEA ethernet device.
713 #ifdef CONFIG_IBMEBUS
714 return !cpu_has_feature(CPU_FTR_ARCH_207S) &&
715 firmware_has_feature(FW_FEATURE_SPLPAR);
721 #endif /* #ifdef CONFIG_PPC_64K_PAGES */
723 static void __init htab_scan_page_sizes(void)
727 /* se the invalid penc to -1 */
728 mmu_psize_set_default_penc();
730 /* Default to 4K pages only */
731 memcpy(mmu_psize_defs, mmu_psize_defaults,
732 sizeof(mmu_psize_defaults));
735 * Try to find the available page sizes in the device-tree
737 rc = of_scan_flat_dt(htab_dt_scan_page_sizes, NULL);
738 if (rc == 0 && early_mmu_has_feature(MMU_FTR_16M_PAGE)) {
740 * Nothing in the device-tree, but the CPU supports 16M pages,
741 * so let's fallback on a known size list for 16M capable CPUs.
743 memcpy(mmu_psize_defs, mmu_psize_defaults_gp,
744 sizeof(mmu_psize_defaults_gp));
747 #ifdef CONFIG_HUGETLB_PAGE
748 if (!hugetlb_disabled && !early_radix_enabled() ) {
749 /* Reserve 16G huge page memory sections for huge pages */
750 of_scan_flat_dt(htab_dt_scan_hugepage_blocks, NULL);
752 #endif /* CONFIG_HUGETLB_PAGE */
756 * Fill in the hpte_page_sizes[] array.
757 * We go through the mmu_psize_defs[] array looking for all the
758 * supported base/actual page size combinations. Each combination
759 * has a unique pagesize encoding (penc) value in the low bits of
760 * the LP field of the HPTE. For actual page sizes less than 1MB,
761 * some of the upper LP bits are used for RPN bits, meaning that
762 * we need to fill in several entries in hpte_page_sizes[].
764 * In diagrammatic form, with r = RPN bits and z = page size bits:
765 * PTE LP actual page size
772 * The zzzz bits are implementation-specific but are chosen so that
773 * no encoding for a larger page size uses the same value in its
774 * low-order N bits as the encoding for the 2^(12+N) byte page size
777 static void __init init_hpte_page_sizes(void)
780 long int shift, penc;
782 for (bp = 0; bp < MMU_PAGE_COUNT; ++bp) {
783 if (!mmu_psize_defs[bp].shift)
784 continue; /* not a supported page size */
785 for (ap = bp; ap < MMU_PAGE_COUNT; ++ap) {
786 penc = mmu_psize_defs[bp].penc[ap];
787 if (penc == -1 || !mmu_psize_defs[ap].shift)
789 shift = mmu_psize_defs[ap].shift - LP_SHIFT;
791 continue; /* should never happen */
793 * For page sizes less than 1MB, this loop
794 * replicates the entry for all possible values
797 while (penc < (1 << LP_BITS)) {
798 hpte_page_sizes[penc] = (ap << 4) | bp;
805 static void __init htab_init_page_sizes(void)
808 init_hpte_page_sizes();
810 if (!debug_pagealloc_enabled_or_kfence()) {
812 * Pick a size for the linear mapping. Currently, we only
813 * support 16M, 1M and 4K which is the default
815 if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) &&
816 (unsigned long)_stext % 0x1000000) {
817 if (mmu_psize_defs[MMU_PAGE_16M].shift)
818 pr_warn("Kernel not 16M aligned, disabling 16M linear map alignment\n");
822 if (mmu_psize_defs[MMU_PAGE_16M].shift && aligned)
823 mmu_linear_psize = MMU_PAGE_16M;
824 else if (mmu_psize_defs[MMU_PAGE_1M].shift)
825 mmu_linear_psize = MMU_PAGE_1M;
828 #ifdef CONFIG_PPC_64K_PAGES
830 * Pick a size for the ordinary pages. Default is 4K, we support
831 * 64K for user mappings and vmalloc if supported by the processor.
832 * We only use 64k for ioremap if the processor
833 * (and firmware) support cache-inhibited large pages.
834 * If not, we use 4k and set mmu_ci_restrictions so that
835 * hash_page knows to switch processes that use cache-inhibited
836 * mappings to 4k pages.
838 if (mmu_psize_defs[MMU_PAGE_64K].shift) {
839 mmu_virtual_psize = MMU_PAGE_64K;
840 mmu_vmalloc_psize = MMU_PAGE_64K;
841 if (mmu_linear_psize == MMU_PAGE_4K)
842 mmu_linear_psize = MMU_PAGE_64K;
843 if (mmu_has_feature(MMU_FTR_CI_LARGE_PAGE)) {
845 * When running on pSeries using 64k pages for ioremap
846 * would stop us accessing the HEA ethernet. So if we
847 * have the chance of ever seeing one, stay at 4k.
849 if (!might_have_hea())
850 mmu_io_psize = MMU_PAGE_64K;
852 mmu_ci_restrictions = 1;
854 #endif /* CONFIG_PPC_64K_PAGES */
856 #ifdef CONFIG_SPARSEMEM_VMEMMAP
858 * We try to use 16M pages for vmemmap if that is supported
859 * and we have at least 1G of RAM at boot
861 if (mmu_psize_defs[MMU_PAGE_16M].shift &&
862 memblock_phys_mem_size() >= 0x40000000)
863 mmu_vmemmap_psize = MMU_PAGE_16M;
865 mmu_vmemmap_psize = mmu_virtual_psize;
866 #endif /* CONFIG_SPARSEMEM_VMEMMAP */
868 printk(KERN_DEBUG "Page orders: linear mapping = %d, "
869 "virtual = %d, io = %d"
870 #ifdef CONFIG_SPARSEMEM_VMEMMAP
874 mmu_psize_defs[mmu_linear_psize].shift,
875 mmu_psize_defs[mmu_virtual_psize].shift,
876 mmu_psize_defs[mmu_io_psize].shift
877 #ifdef CONFIG_SPARSEMEM_VMEMMAP
878 ,mmu_psize_defs[mmu_vmemmap_psize].shift
883 static int __init htab_dt_scan_pftsize(unsigned long node,
884 const char *uname, int depth,
887 const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
890 /* We are scanning "cpu" nodes only */
891 if (type == NULL || strcmp(type, "cpu") != 0)
894 prop = of_get_flat_dt_prop(node, "ibm,pft-size", NULL);
896 /* pft_size[0] is the NUMA CEC cookie */
897 ppc64_pft_size = be32_to_cpu(prop[1]);
903 unsigned htab_shift_for_mem_size(unsigned long mem_size)
905 unsigned memshift = __ilog2(mem_size);
906 unsigned pshift = mmu_psize_defs[mmu_virtual_psize].shift;
909 /* round mem_size up to next power of 2 */
910 if ((1UL << memshift) < mem_size)
913 /* aim for 2 pages / pteg */
914 pteg_shift = memshift - (pshift + 1);
917 * 2^11 PTEGS of 128 bytes each, ie. 2^18 bytes is the minimum htab
918 * size permitted by the architecture.
920 return max(pteg_shift + 7, 18U);
923 static unsigned long __init htab_get_table_size(void)
926 * If hash size isn't already provided by the platform, we try to
927 * retrieve it from the device-tree. If it's not there neither, we
928 * calculate it now based on the total RAM size
930 if (ppc64_pft_size == 0)
931 of_scan_flat_dt(htab_dt_scan_pftsize, NULL);
933 return 1UL << ppc64_pft_size;
935 return 1UL << htab_shift_for_mem_size(memblock_phys_mem_size());
938 #ifdef CONFIG_MEMORY_HOTPLUG
939 static int resize_hpt_for_hotplug(unsigned long new_mem_size)
941 unsigned target_hpt_shift;
943 if (!mmu_hash_ops.resize_hpt)
946 target_hpt_shift = htab_shift_for_mem_size(new_mem_size);
949 * To avoid lots of HPT resizes if memory size is fluctuating
950 * across a boundary, we deliberately have some hysterisis
951 * here: we immediately increase the HPT size if the target
952 * shift exceeds the current shift, but we won't attempt to
953 * reduce unless the target shift is at least 2 below the
956 if (target_hpt_shift > ppc64_pft_size ||
957 target_hpt_shift < ppc64_pft_size - 1)
958 return mmu_hash_ops.resize_hpt(target_hpt_shift);
963 int hash__create_section_mapping(unsigned long start, unsigned long end,
964 int nid, pgprot_t prot)
968 if (end >= H_VMALLOC_START) {
969 pr_warn("Outside the supported range\n");
973 resize_hpt_for_hotplug(memblock_phys_mem_size());
975 rc = htab_bolt_mapping(start, end, __pa(start),
976 pgprot_val(prot), mmu_linear_psize,
980 int rc2 = htab_remove_mapping(start, end, mmu_linear_psize,
982 BUG_ON(rc2 && (rc2 != -ENOENT));
987 int hash__remove_section_mapping(unsigned long start, unsigned long end)
989 int rc = htab_remove_mapping(start, end, mmu_linear_psize,
992 if (resize_hpt_for_hotplug(memblock_phys_mem_size()) == -ENOSPC)
993 pr_warn("Hash collision while resizing HPT\n");
997 #endif /* CONFIG_MEMORY_HOTPLUG */
999 static void __init hash_init_partition_table(phys_addr_t hash_table,
1000 unsigned long htab_size)
1002 mmu_partition_table_init();
1005 * PS field (VRMA page size) is not used for LPID 0, hence set to 0.
1006 * For now, UPRT is 0 and we have no segment table.
1008 htab_size = __ilog2(htab_size) - 18;
1009 mmu_partition_table_set_entry(0, hash_table | htab_size, 0, false);
1010 pr_info("Partition table %p\n", partition_tb);
1013 void hpt_clear_stress(void);
1014 static struct timer_list stress_hpt_timer;
1015 static void stress_hpt_timer_fn(struct timer_list *timer)
1020 if (!firmware_has_feature(FW_FEATURE_LPAR))
1023 next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);
1024 if (next_cpu >= nr_cpu_ids)
1025 next_cpu = cpumask_first(cpu_online_mask);
1026 stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);
1027 add_timer_on(&stress_hpt_timer, next_cpu);
1030 static void __init htab_initialize(void)
1032 unsigned long table;
1033 unsigned long pteg_count;
1035 phys_addr_t base = 0, size = 0, end;
1038 DBG(" -> htab_initialize()\n");
1040 if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) {
1041 mmu_kernel_ssize = MMU_SEGSIZE_1T;
1042 mmu_highuser_ssize = MMU_SEGSIZE_1T;
1043 printk(KERN_INFO "Using 1TB segments\n");
1046 if (stress_slb_enabled)
1047 static_branch_enable(&stress_slb_key);
1049 if (stress_hpt_enabled) {
1051 static_branch_enable(&stress_hpt_key);
1052 // Too early to use nr_cpu_ids, so use NR_CPUS
1053 tmp = memblock_phys_alloc_range(sizeof(struct stress_hpt_struct) * NR_CPUS,
1054 __alignof__(struct stress_hpt_struct),
1055 0, MEMBLOCK_ALLOC_ANYWHERE);
1056 memset((void *)tmp, 0xff, sizeof(struct stress_hpt_struct) * NR_CPUS);
1057 stress_hpt_struct = __va(tmp);
1059 timer_setup(&stress_hpt_timer, stress_hpt_timer_fn, 0);
1060 stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);
1061 add_timer(&stress_hpt_timer);
1065 * Calculate the required size of the htab. We want the number of
1066 * PTEGs to equal one half the number of real pages.
1068 htab_size_bytes = htab_get_table_size();
1069 pteg_count = htab_size_bytes >> 7;
1071 htab_hash_mask = pteg_count - 1;
1073 if (firmware_has_feature(FW_FEATURE_LPAR) ||
1074 firmware_has_feature(FW_FEATURE_PS3_LV1)) {
1075 /* Using a hypervisor which owns the htab */
1076 htab_address = NULL;
1078 #ifdef CONFIG_FA_DUMP
1080 * If firmware assisted dump is active firmware preserves
1081 * the contents of htab along with entire partition memory.
1082 * Clear the htab if firmware assisted dump is active so
1083 * that we dont end up using old mappings.
1085 if (is_fadump_active() && mmu_hash_ops.hpte_clear_all)
1086 mmu_hash_ops.hpte_clear_all();
1089 unsigned long limit = MEMBLOCK_ALLOC_ANYWHERE;
1091 #ifdef CONFIG_PPC_CELL
1093 * Cell may require the hash table down low when using the
1094 * Axon IOMMU in order to fit the dynamic region over it, see
1095 * comments in cell/iommu.c
1097 if (fdt_subnode_offset(initial_boot_params, 0, "axon") > 0) {
1099 pr_info("Hash table forced below 2G for Axon IOMMU\n");
1101 #endif /* CONFIG_PPC_CELL */
1103 table = memblock_phys_alloc_range(htab_size_bytes,
1107 panic("ERROR: Failed to allocate %pa bytes below %pa\n",
1108 &htab_size_bytes, &limit);
1110 DBG("Hash table allocated at %lx, size: %lx\n", table,
1113 htab_address = __va(table);
1115 /* htab absolute addr + encoded htabsize */
1116 _SDR1 = table + __ilog2(htab_size_bytes) - 18;
1118 /* Initialize the HPT with no entries */
1119 memset((void *)table, 0, htab_size_bytes);
1121 if (!cpu_has_feature(CPU_FTR_ARCH_300))
1123 mtspr(SPRN_SDR1, _SDR1);
1125 hash_init_partition_table(table, htab_size_bytes);
1128 prot = pgprot_val(PAGE_KERNEL);
1130 if (debug_pagealloc_enabled_or_kfence()) {
1131 linear_map_hash_count = memblock_end_of_DRAM() >> PAGE_SHIFT;
1132 linear_map_hash_slots = memblock_alloc_try_nid(
1133 linear_map_hash_count, 1, MEMBLOCK_LOW_LIMIT,
1134 ppc64_rma_size, NUMA_NO_NODE);
1135 if (!linear_map_hash_slots)
1136 panic("%s: Failed to allocate %lu bytes max_addr=%pa\n",
1137 __func__, linear_map_hash_count, &ppc64_rma_size);
1140 /* create bolted the linear mapping in the hash table */
1141 for_each_mem_range(i, &base, &end) {
1143 base = (unsigned long)__va(base);
1145 DBG("creating mapping for region: %lx..%lx (prot: %lx)\n",
1148 if ((base + size) >= H_VMALLOC_START) {
1149 pr_warn("Outside the supported range\n");
1153 BUG_ON(htab_bolt_mapping(base, base + size, __pa(base),
1154 prot, mmu_linear_psize, mmu_kernel_ssize));
1156 memblock_set_current_limit(MEMBLOCK_ALLOC_ANYWHERE);
1159 * If we have a memory_limit and we've allocated TCEs then we need to
1160 * explicitly map the TCE area at the top of RAM. We also cope with the
1161 * case that the TCEs start below memory_limit.
1162 * tce_alloc_start/end are 16MB aligned so the mapping should work
1163 * for either 4K or 16MB pages.
1165 if (tce_alloc_start) {
1166 tce_alloc_start = (unsigned long)__va(tce_alloc_start);
1167 tce_alloc_end = (unsigned long)__va(tce_alloc_end);
1169 if (base + size >= tce_alloc_start)
1170 tce_alloc_start = base + size + 1;
1172 BUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,
1173 __pa(tce_alloc_start), prot,
1174 mmu_linear_psize, mmu_kernel_ssize));
1178 DBG(" <- htab_initialize()\n");
1183 void __init hash__early_init_devtree(void)
1185 /* Initialize segment sizes */
1186 of_scan_flat_dt(htab_dt_scan_seg_sizes, NULL);
1188 /* Initialize page sizes */
1189 htab_scan_page_sizes();
1192 static struct hash_mm_context init_hash_mm_context;
1193 void __init hash__early_init_mmu(void)
1195 #ifndef CONFIG_PPC_64K_PAGES
1197 * We have code in __hash_page_4K() and elsewhere, which assumes it can
1199 * new_pte |= (slot << H_PAGE_F_GIX_SHIFT) & (H_PAGE_F_SECOND | H_PAGE_F_GIX);
1201 * Where the slot number is between 0-15, and values of 8-15 indicate
1202 * the secondary bucket. For that code to work H_PAGE_F_SECOND and
1203 * H_PAGE_F_GIX must occupy four contiguous bits in the PTE, and
1204 * H_PAGE_F_SECOND must be placed above H_PAGE_F_GIX. Assert that here
1205 * with a BUILD_BUG_ON().
1207 BUILD_BUG_ON(H_PAGE_F_SECOND != (1ul << (H_PAGE_F_GIX_SHIFT + 3)));
1208 #endif /* CONFIG_PPC_64K_PAGES */
1210 htab_init_page_sizes();
1213 * initialize page table size
1215 __pte_frag_nr = H_PTE_FRAG_NR;
1216 __pte_frag_size_shift = H_PTE_FRAG_SIZE_SHIFT;
1217 __pmd_frag_nr = H_PMD_FRAG_NR;
1218 __pmd_frag_size_shift = H_PMD_FRAG_SIZE_SHIFT;
1220 __pte_index_size = H_PTE_INDEX_SIZE;
1221 __pmd_index_size = H_PMD_INDEX_SIZE;
1222 __pud_index_size = H_PUD_INDEX_SIZE;
1223 __pgd_index_size = H_PGD_INDEX_SIZE;
1224 __pud_cache_index = H_PUD_CACHE_INDEX;
1225 __pte_table_size = H_PTE_TABLE_SIZE;
1226 __pmd_table_size = H_PMD_TABLE_SIZE;
1227 __pud_table_size = H_PUD_TABLE_SIZE;
1228 __pgd_table_size = H_PGD_TABLE_SIZE;
1230 * 4k use hugepd format, so for hash set then to
1233 __pmd_val_bits = HASH_PMD_VAL_BITS;
1234 __pud_val_bits = HASH_PUD_VAL_BITS;
1235 __pgd_val_bits = HASH_PGD_VAL_BITS;
1237 __kernel_virt_start = H_KERN_VIRT_START;
1238 __vmalloc_start = H_VMALLOC_START;
1239 __vmalloc_end = H_VMALLOC_END;
1240 __kernel_io_start = H_KERN_IO_START;
1241 __kernel_io_end = H_KERN_IO_END;
1242 vmemmap = (struct page *)H_VMEMMAP_START;
1243 ioremap_bot = IOREMAP_BASE;
1246 pci_io_base = ISA_IO_BASE;
1249 /* Select appropriate backend */
1250 if (firmware_has_feature(FW_FEATURE_PS3_LV1))
1251 ps3_early_mm_init();
1252 else if (firmware_has_feature(FW_FEATURE_LPAR))
1253 hpte_init_pseries();
1254 else if (IS_ENABLED(CONFIG_PPC_HASH_MMU_NATIVE))
1257 if (!mmu_hash_ops.hpte_insert)
1258 panic("hash__early_init_mmu: No MMU hash ops defined!\n");
1261 * Initialize the MMU Hash table and create the linear mapping
1262 * of memory. Has to be done before SLB initialization as this is
1263 * currently where the page size encoding is obtained.
1267 init_mm.context.hash_context = &init_hash_mm_context;
1268 mm_ctx_set_slb_addr_limit(&init_mm.context, SLB_ADDR_LIMIT_DEFAULT);
1270 pr_info("Initializing hash mmu with SLB\n");
1271 /* Initialize SLB management */
1274 if (cpu_has_feature(CPU_FTR_ARCH_206)
1275 && cpu_has_feature(CPU_FTR_HVMODE))
1280 void hash__early_init_mmu_secondary(void)
1282 /* Initialize hash table for that CPU */
1283 if (!firmware_has_feature(FW_FEATURE_LPAR)) {
1285 if (!cpu_has_feature(CPU_FTR_ARCH_300))
1286 mtspr(SPRN_SDR1, _SDR1);
1288 set_ptcr_when_no_uv(__pa(partition_tb) |
1289 (PATB_SIZE_SHIFT - 12));
1291 /* Initialize SLB */
1294 if (cpu_has_feature(CPU_FTR_ARCH_206)
1295 && cpu_has_feature(CPU_FTR_HVMODE))
1298 #ifdef CONFIG_PPC_MEM_KEYS
1299 if (mmu_has_feature(MMU_FTR_PKEY))
1300 mtspr(SPRN_UAMOR, default_uamor);
1303 #endif /* CONFIG_SMP */
1306 * Called by asm hashtable.S for doing lazy icache flush
1308 unsigned int hash_page_do_lazy_icache(unsigned int pp, pte_t pte, int trap)
1310 struct folio *folio;
1312 if (!pfn_valid(pte_pfn(pte)))
1315 folio = page_folio(pte_page(pte));
1318 if (!test_bit(PG_dcache_clean, &folio->flags) &&
1319 !folio_test_reserved(folio)) {
1320 if (trap == INTERRUPT_INST_STORAGE) {
1321 flush_dcache_icache_folio(folio);
1322 set_bit(PG_dcache_clean, &folio->flags);
1329 static unsigned int get_paca_psize(unsigned long addr)
1331 unsigned char *psizes;
1332 unsigned long index, mask_index;
1334 if (addr < SLICE_LOW_TOP) {
1335 psizes = get_paca()->mm_ctx_low_slices_psize;
1336 index = GET_LOW_SLICE_INDEX(addr);
1338 psizes = get_paca()->mm_ctx_high_slices_psize;
1339 index = GET_HIGH_SLICE_INDEX(addr);
1341 mask_index = index & 0x1;
1342 return (psizes[index >> 1] >> (mask_index * 4)) & 0xF;
1347 * Demote a segment to using 4k pages.
1348 * For now this makes the whole process use 4k pages.
1350 #ifdef CONFIG_PPC_64K_PAGES
1351 void demote_segment_4k(struct mm_struct *mm, unsigned long addr)
1353 if (get_slice_psize(mm, addr) == MMU_PAGE_4K)
1355 slice_set_range_psize(mm, addr, 1, MMU_PAGE_4K);
1356 copro_flush_all_slbs(mm);
1357 if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {
1359 copy_mm_to_paca(mm);
1360 slb_flush_and_restore_bolted();
1363 #endif /* CONFIG_PPC_64K_PAGES */
1365 #ifdef CONFIG_PPC_SUBPAGE_PROT
1367 * This looks up a 2-bit protection code for a 4k subpage of a 64k page.
1368 * Userspace sets the subpage permissions using the subpage_prot system call.
1370 * Result is 0: full permissions, _PAGE_RW: read-only,
1371 * _PAGE_RWX: no access.
1373 static int subpage_protection(struct mm_struct *mm, unsigned long ea)
1375 struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context);
1382 if (ea >= spt->maxaddr)
1384 if (ea < 0x100000000UL) {
1385 /* addresses below 4GB use spt->low_prot */
1386 sbpm = spt->low_prot;
1388 sbpm = spt->protptrs[ea >> SBP_L3_SHIFT];
1392 sbpp = sbpm[(ea >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)];
1395 spp = sbpp[(ea >> PAGE_SHIFT) & (SBP_L1_COUNT - 1)];
1397 /* extract 2-bit bitfield for this 4k subpage */
1398 spp >>= 30 - 2 * ((ea >> 12) & 0xf);
1401 * 0 -> full permission
1404 * We return the flag that need to be cleared.
1406 spp = ((spp & 2) ? _PAGE_RWX : 0) | ((spp & 1) ? _PAGE_WRITE : 0);
1410 #else /* CONFIG_PPC_SUBPAGE_PROT */
1411 static inline int subpage_protection(struct mm_struct *mm, unsigned long ea)
1417 void hash_failure_debug(unsigned long ea, unsigned long access,
1418 unsigned long vsid, unsigned long trap,
1419 int ssize, int psize, int lpsize, unsigned long pte)
1421 if (!printk_ratelimit())
1423 pr_info("mm: Hashing failure ! EA=0x%lx access=0x%lx current=%s\n",
1424 ea, access, current->comm);
1425 pr_info(" trap=0x%lx vsid=0x%lx ssize=%d base psize=%d psize %d pte=0x%lx\n",
1426 trap, vsid, ssize, psize, lpsize, pte);
1429 static void check_paca_psize(unsigned long ea, struct mm_struct *mm,
1430 int psize, bool user_region)
1433 if (psize != get_paca_psize(ea)) {
1434 copy_mm_to_paca(mm);
1435 slb_flush_and_restore_bolted();
1437 } else if (get_paca()->vmalloc_sllp !=
1438 mmu_psize_defs[mmu_vmalloc_psize].sllp) {
1439 get_paca()->vmalloc_sllp =
1440 mmu_psize_defs[mmu_vmalloc_psize].sllp;
1441 slb_vmalloc_update();
1448 * 1 - normal page fault
1449 * -1 - critical hash insertion error
1450 * -2 - access not permitted by subpage protection mechanism
1452 int hash_page_mm(struct mm_struct *mm, unsigned long ea,
1453 unsigned long access, unsigned long trap,
1454 unsigned long flags)
1461 int rc, user_region = 0;
1464 DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n",
1466 trace_hash_fault(ea, access, trap);
1468 /* Get region & vsid */
1469 switch (get_region_id(ea)) {
1470 case USER_REGION_ID:
1473 DBG_LOW(" user region with no mm !\n");
1477 psize = get_slice_psize(mm, ea);
1478 ssize = user_segment_size(ea);
1479 vsid = get_user_vsid(&mm->context, ea, ssize);
1481 case VMALLOC_REGION_ID:
1482 vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1483 psize = mmu_vmalloc_psize;
1484 ssize = mmu_kernel_ssize;
1485 flags |= HPTE_USE_KERNEL_KEY;
1489 vsid = get_kernel_vsid(ea, mmu_kernel_ssize);
1490 psize = mmu_io_psize;
1491 ssize = mmu_kernel_ssize;
1492 flags |= HPTE_USE_KERNEL_KEY;
1497 * Send the problem up to do_page_fault()
1502 DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid);
1506 DBG_LOW("Bad address!\n");
1512 if (pgdir == NULL) {
1517 /* Check CPU locality */
1518 if (user_region && mm_is_thread_local(mm))
1519 flags |= HPTE_LOCAL_UPDATE;
1521 #ifndef CONFIG_PPC_64K_PAGES
1523 * If we use 4K pages and our psize is not 4K, then we might
1524 * be hitting a special driver mapping, and need to align the
1525 * address before we fetch the PTE.
1527 * It could also be a hugepage mapping, in which case this is
1528 * not necessary, but it's not harmful, either.
1530 if (psize != MMU_PAGE_4K)
1531 ea &= ~((1ul << mmu_psize_defs[psize].shift) - 1);
1532 #endif /* CONFIG_PPC_64K_PAGES */
1534 /* Get PTE and page size from page tables */
1535 ptep = find_linux_pte(pgdir, ea, &is_thp, &hugeshift);
1536 if (ptep == NULL || !pte_present(*ptep)) {
1537 DBG_LOW(" no PTE !\n");
1543 * Add _PAGE_PRESENT to the required access perm. If there are parallel
1544 * updates to the pte that can possibly clear _PAGE_PTE, catch that too.
1546 * We can safely use the return pte address in rest of the function
1547 * because we do set H_PAGE_BUSY which prevents further updates to pte
1548 * from generic code.
1550 access |= _PAGE_PRESENT | _PAGE_PTE;
1553 * Pre-check access permissions (will be re-checked atomically
1554 * in __hash_page_XX but this pre-check is a fast path
1556 if (!check_pte_access(access, pte_val(*ptep))) {
1557 DBG_LOW(" no access !\n");
1564 rc = __hash_page_thp(ea, access, vsid, (pmd_t *)ptep,
1565 trap, flags, ssize, psize);
1566 #ifdef CONFIG_HUGETLB_PAGE
1568 rc = __hash_page_huge(ea, access, vsid, ptep, trap,
1569 flags, ssize, hugeshift, psize);
1573 * if we have hugeshift, and is not transhuge with
1574 * hugetlb disabled, something is really wrong.
1580 if (current->mm == mm)
1581 check_paca_psize(ea, mm, psize, user_region);
1586 #ifndef CONFIG_PPC_64K_PAGES
1587 DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep));
1589 DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep),
1590 pte_val(*(ptep + PTRS_PER_PTE)));
1592 /* Do actual hashing */
1593 #ifdef CONFIG_PPC_64K_PAGES
1594 /* If H_PAGE_4K_PFN is set, make sure this is a 4k segment */
1595 if ((pte_val(*ptep) & H_PAGE_4K_PFN) && psize == MMU_PAGE_64K) {
1596 demote_segment_4k(mm, ea);
1597 psize = MMU_PAGE_4K;
1601 * If this PTE is non-cacheable and we have restrictions on
1602 * using non cacheable large pages, then we switch to 4k
1604 if (mmu_ci_restrictions && psize == MMU_PAGE_64K && pte_ci(*ptep)) {
1606 demote_segment_4k(mm, ea);
1607 psize = MMU_PAGE_4K;
1608 } else if (ea < VMALLOC_END) {
1610 * some driver did a non-cacheable mapping
1611 * in vmalloc space, so switch vmalloc
1614 printk(KERN_ALERT "Reducing vmalloc segment "
1615 "to 4kB pages because of "
1616 "non-cacheable mapping\n");
1617 psize = mmu_vmalloc_psize = MMU_PAGE_4K;
1618 copro_flush_all_slbs(mm);
1622 #endif /* CONFIG_PPC_64K_PAGES */
1624 if (current->mm == mm)
1625 check_paca_psize(ea, mm, psize, user_region);
1627 #ifdef CONFIG_PPC_64K_PAGES
1628 if (psize == MMU_PAGE_64K)
1629 rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1632 #endif /* CONFIG_PPC_64K_PAGES */
1634 int spp = subpage_protection(mm, ea);
1638 rc = __hash_page_4K(ea, access, vsid, ptep, trap,
1643 * Dump some info in case of hash insertion failure, they should
1644 * never happen so it is really useful to know if/when they do
1647 hash_failure_debug(ea, access, vsid, trap, ssize, psize,
1648 psize, pte_val(*ptep));
1649 #ifndef CONFIG_PPC_64K_PAGES
1650 DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep));
1652 DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep),
1653 pte_val(*(ptep + PTRS_PER_PTE)));
1655 DBG_LOW(" -> rc=%d\n", rc);
1660 EXPORT_SYMBOL_GPL(hash_page_mm);
1662 int hash_page(unsigned long ea, unsigned long access, unsigned long trap,
1663 unsigned long dsisr)
1665 unsigned long flags = 0;
1666 struct mm_struct *mm = current->mm;
1668 if ((get_region_id(ea) == VMALLOC_REGION_ID) ||
1669 (get_region_id(ea) == IO_REGION_ID))
1672 if (dsisr & DSISR_NOHPTE)
1673 flags |= HPTE_NOHPTE_UPDATE;
1675 return hash_page_mm(mm, ea, access, trap, flags);
1677 EXPORT_SYMBOL_GPL(hash_page);
1679 DEFINE_INTERRUPT_HANDLER(do_hash_fault)
1681 unsigned long ea = regs->dar;
1682 unsigned long dsisr = regs->dsisr;
1683 unsigned long access = _PAGE_PRESENT | _PAGE_READ;
1684 unsigned long flags = 0;
1685 struct mm_struct *mm;
1686 unsigned int region_id;
1689 if (unlikely(dsisr & (DSISR_BAD_FAULT_64S | DSISR_KEYFAULT))) {
1690 hash__do_page_fault(regs);
1694 region_id = get_region_id(ea);
1695 if ((region_id == VMALLOC_REGION_ID) || (region_id == IO_REGION_ID))
1700 if (dsisr & DSISR_NOHPTE)
1701 flags |= HPTE_NOHPTE_UPDATE;
1703 if (dsisr & DSISR_ISSTORE)
1704 access |= _PAGE_WRITE;
1706 * We set _PAGE_PRIVILEGED only when
1707 * kernel mode access kernel space.
1709 * _PAGE_PRIVILEGED is NOT set
1710 * 1) when kernel mode access user space
1711 * 2) user space access kernel space.
1713 access |= _PAGE_PRIVILEGED;
1714 if (user_mode(regs) || (region_id == USER_REGION_ID))
1715 access &= ~_PAGE_PRIVILEGED;
1717 if (TRAP(regs) == INTERRUPT_INST_STORAGE)
1718 access |= _PAGE_EXEC;
1720 err = hash_page_mm(mm, ea, access, TRAP(regs), flags);
1721 if (unlikely(err < 0)) {
1722 // failed to insert a hash PTE due to an hypervisor error
1723 if (user_mode(regs)) {
1724 if (IS_ENABLED(CONFIG_PPC_SUBPAGE_PROT) && err == -2)
1725 _exception(SIGSEGV, regs, SEGV_ACCERR, ea);
1727 _exception(SIGBUS, regs, BUS_ADRERR, ea);
1729 bad_page_fault(regs, SIGBUS);
1734 hash__do_page_fault(regs);
1738 static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)
1740 int psize = get_slice_psize(mm, ea);
1742 /* We only prefault standard pages for now */
1743 if (unlikely(psize != mm_ctx_user_psize(&mm->context)))
1747 * Don't prefault if subpage protection is enabled for the EA.
1749 if (unlikely((psize == MMU_PAGE_4K) && subpage_protection(mm, ea)))
1755 static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,
1756 bool is_exec, unsigned long trap)
1760 int rc, ssize, update_flags = 0;
1761 unsigned long access = _PAGE_PRESENT | _PAGE_READ | (is_exec ? _PAGE_EXEC : 0);
1762 unsigned long flags;
1764 BUG_ON(get_region_id(ea) != USER_REGION_ID);
1766 if (!should_hash_preload(mm, ea))
1769 DBG_LOW("hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,"
1770 " trap=%lx\n", mm, mm->pgd, ea, access, trap);
1772 /* Get Linux PTE if available */
1778 ssize = user_segment_size(ea);
1779 vsid = get_user_vsid(&mm->context, ea, ssize);
1783 #ifdef CONFIG_PPC_64K_PAGES
1784 /* If either H_PAGE_4K_PFN or cache inhibited is set (and we are on
1785 * a 64K kernel), then we don't preload, hash_page() will take
1786 * care of it once we actually try to access the page.
1787 * That way we don't have to duplicate all of the logic for segment
1788 * page size demotion here
1789 * Called with PTL held, hence can be sure the value won't change in
1792 if ((pte_val(*ptep) & H_PAGE_4K_PFN) || pte_ci(*ptep))
1794 #endif /* CONFIG_PPC_64K_PAGES */
1797 * __hash_page_* must run with interrupts off, including PMI interrupts
1798 * off, as it sets the H_PAGE_BUSY bit.
1800 * It's otherwise possible for perf interrupts to hit at any time and
1801 * may take a hash fault reading the user stack, which could take a
1802 * hash miss and deadlock on the same H_PAGE_BUSY bit.
1804 * Interrupts must also be off for the duration of the
1805 * mm_is_thread_local test and update, to prevent preempt running the
1806 * mm on another CPU (XXX: this may be racy vs kthread_use_mm).
1808 powerpc_local_irq_pmu_save(flags);
1810 /* Is that local to this CPU ? */
1811 if (mm_is_thread_local(mm))
1812 update_flags |= HPTE_LOCAL_UPDATE;
1815 #ifdef CONFIG_PPC_64K_PAGES
1816 if (mm_ctx_user_psize(&mm->context) == MMU_PAGE_64K)
1817 rc = __hash_page_64K(ea, access, vsid, ptep, trap,
1818 update_flags, ssize);
1820 #endif /* CONFIG_PPC_64K_PAGES */
1821 rc = __hash_page_4K(ea, access, vsid, ptep, trap, update_flags,
1822 ssize, subpage_protection(mm, ea));
1824 /* Dump some info in case of hash insertion failure, they should
1825 * never happen so it is really useful to know if/when they do
1828 hash_failure_debug(ea, access, vsid, trap, ssize,
1829 mm_ctx_user_psize(&mm->context),
1830 mm_ctx_user_psize(&mm->context),
1833 powerpc_local_irq_pmu_restore(flags);
1837 * This is called at the end of handling a user page fault, when the
1838 * fault has been handled by updating a PTE in the linux page tables.
1839 * We use it to preload an HPTE into the hash table corresponding to
1840 * the updated linux PTE.
1842 * This must always be called with the pte lock held.
1844 void __update_mmu_cache(struct vm_area_struct *vma, unsigned long address,
1848 * We don't need to worry about _PAGE_PRESENT here because we are
1849 * called with either mm->page_table_lock held or ptl lock held
1854 /* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */
1855 if (!pte_young(*ptep) || address >= TASK_SIZE)
1859 * We try to figure out if we are coming from an instruction
1860 * access fault and pass that down to __hash_page so we avoid
1861 * double-faulting on execution of fresh text. We have to test
1862 * for regs NULL since init will get here first thing at boot.
1864 * We also avoid filling the hash if not coming from a fault.
1867 trap = current->thread.regs ? TRAP(current->thread.regs) : 0UL;
1879 hash_preload(vma->vm_mm, ptep, address, is_exec, trap);
1882 #ifdef CONFIG_PPC_TRANSACTIONAL_MEM
1883 static inline void tm_flush_hash_page(int local)
1886 * Transactions are not aborted by tlbiel, only tlbie. Without, syncing a
1887 * page back to a block device w/PIO could pick up transactional data
1888 * (bad!) so we force an abort here. Before the sync the page will be
1889 * made read-only, which will flush_hash_page. BIG ISSUE here: if the
1890 * kernel uses a page from userspace without unmapping it first, it may
1891 * see the speculated version.
1893 if (local && cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&
1894 MSR_TM_ACTIVE(current->thread.regs->msr)) {
1896 tm_abort(TM_CAUSE_TLBI);
1900 static inline void tm_flush_hash_page(int local)
1906 * Return the global hash slot, corresponding to the given PTE, which contains
1909 unsigned long pte_get_hash_gslot(unsigned long vpn, unsigned long shift,
1910 int ssize, real_pte_t rpte, unsigned int subpg_index)
1912 unsigned long hash, gslot, hidx;
1914 hash = hpt_hash(vpn, shift, ssize);
1915 hidx = __rpte_to_hidx(rpte, subpg_index);
1916 if (hidx & _PTEIDX_SECONDARY)
1918 gslot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1919 gslot += hidx & _PTEIDX_GROUP_IX;
1923 void flush_hash_page(unsigned long vpn, real_pte_t pte, int psize, int ssize,
1924 unsigned long flags)
1926 unsigned long index, shift, gslot;
1927 int local = flags & HPTE_LOCAL_UPDATE;
1929 DBG_LOW("flush_hash_page(vpn=%016lx)\n", vpn);
1930 pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {
1931 gslot = pte_get_hash_gslot(vpn, shift, ssize, pte, index);
1932 DBG_LOW(" sub %ld: gslot=%lx\n", index, gslot);
1934 * We use same base page size and actual psize, because we don't
1935 * use these functions for hugepage
1937 mmu_hash_ops.hpte_invalidate(gslot, vpn, psize, psize,
1939 } pte_iterate_hashed_end();
1941 tm_flush_hash_page(local);
1944 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1945 void flush_hash_hugepage(unsigned long vsid, unsigned long addr,
1946 pmd_t *pmdp, unsigned int psize, int ssize,
1947 unsigned long flags)
1949 int i, max_hpte_count, valid;
1950 unsigned long s_addr;
1951 unsigned char *hpte_slot_array;
1952 unsigned long hidx, shift, vpn, hash, slot;
1953 int local = flags & HPTE_LOCAL_UPDATE;
1955 s_addr = addr & HPAGE_PMD_MASK;
1956 hpte_slot_array = get_hpte_slot_array(pmdp);
1958 * IF we try to do a HUGE PTE update after a withdraw is done.
1959 * we will find the below NULL. This happens when we do
1962 if (!hpte_slot_array)
1965 if (mmu_hash_ops.hugepage_invalidate) {
1966 mmu_hash_ops.hugepage_invalidate(vsid, s_addr, hpte_slot_array,
1967 psize, ssize, local);
1971 * No bluk hpte removal support, invalidate each entry
1973 shift = mmu_psize_defs[psize].shift;
1974 max_hpte_count = HPAGE_PMD_SIZE >> shift;
1975 for (i = 0; i < max_hpte_count; i++) {
1977 * 8 bits per each hpte entries
1978 * 000| [ secondary group (one bit) | hidx (3 bits) | valid bit]
1980 valid = hpte_valid(hpte_slot_array, i);
1983 hidx = hpte_hash_index(hpte_slot_array, i);
1986 addr = s_addr + (i * (1ul << shift));
1987 vpn = hpt_vpn(addr, vsid, ssize);
1988 hash = hpt_hash(vpn, shift, ssize);
1989 if (hidx & _PTEIDX_SECONDARY)
1992 slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
1993 slot += hidx & _PTEIDX_GROUP_IX;
1994 mmu_hash_ops.hpte_invalidate(slot, vpn, psize,
1995 MMU_PAGE_16M, ssize, local);
1998 tm_flush_hash_page(local);
2000 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2002 void flush_hash_range(unsigned long number, int local)
2004 if (mmu_hash_ops.flush_hash_range)
2005 mmu_hash_ops.flush_hash_range(number, local);
2008 struct ppc64_tlb_batch *batch =
2009 this_cpu_ptr(&ppc64_tlb_batch);
2011 for (i = 0; i < number; i++)
2012 flush_hash_page(batch->vpn[i], batch->pte[i],
2013 batch->psize, batch->ssize, local);
2017 long hpte_insert_repeating(unsigned long hash, unsigned long vpn,
2018 unsigned long pa, unsigned long rflags,
2019 unsigned long vflags, int psize, int ssize)
2021 unsigned long hpte_group;
2025 hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;
2027 /* Insert into the hash table, primary slot */
2028 slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags, vflags,
2029 psize, psize, ssize);
2031 /* Primary is full, try the secondary */
2032 if (unlikely(slot == -1)) {
2033 hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;
2034 slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags,
2035 vflags | HPTE_V_SECONDARY,
2036 psize, psize, ssize);
2039 hpte_group = (hash & htab_hash_mask) *
2042 mmu_hash_ops.hpte_remove(hpte_group);
2050 void hpt_clear_stress(void)
2052 int cpu = raw_smp_processor_id();
2055 for (g = 0; g < stress_nr_groups(); g++) {
2056 unsigned long last_group;
2057 last_group = stress_hpt_struct[cpu].last_group[g];
2059 if (last_group != -1UL) {
2061 for (i = 0; i < HPTES_PER_GROUP; i++) {
2062 if (mmu_hash_ops.hpte_remove(last_group) == -1)
2065 stress_hpt_struct[cpu].last_group[g] = -1;
2070 void hpt_do_stress(unsigned long ea, unsigned long hpte_group)
2072 unsigned long last_group;
2073 int cpu = raw_smp_processor_id();
2075 last_group = stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1];
2076 if (hpte_group == last_group)
2079 if (last_group != -1UL) {
2082 * Concurrent CPUs might be inserting into this group, so
2083 * give up after a number of iterations, to prevent a live
2086 for (i = 0; i < HPTES_PER_GROUP; i++) {
2087 if (mmu_hash_ops.hpte_remove(last_group) == -1)
2090 stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1] = -1;
2093 if (ea >= PAGE_OFFSET) {
2095 * We would really like to prefetch to get the TLB loaded, then
2096 * remove the PTE before returning from fault interrupt, to
2097 * increase the hash fault rate.
2099 * Unfortunately QEMU TCG does not model the TLB in a way that
2100 * makes this possible, and systemsim (mambo) emulator does not
2101 * bring in TLBs with prefetches (although loads/stores do
2102 * work for non-CI PTEs).
2104 * So remember this PTE and clear it on the next hash fault.
2106 memmove(&stress_hpt_struct[cpu].last_group[1],
2107 &stress_hpt_struct[cpu].last_group[0],
2108 (stress_nr_groups() - 1) * sizeof(unsigned long));
2109 stress_hpt_struct[cpu].last_group[0] = hpte_group;
2113 #if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)
2114 static DEFINE_RAW_SPINLOCK(linear_map_hash_lock);
2116 static void kernel_map_linear_page(unsigned long vaddr, unsigned long lmi)
2119 unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
2120 unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
2121 unsigned long mode = htab_convert_pte_flags(pgprot_val(PAGE_KERNEL), HPTE_USE_KERNEL_KEY);
2124 hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
2126 /* Don't create HPTE entries for bad address */
2130 if (linear_map_hash_slots[lmi] & 0x80)
2133 ret = hpte_insert_repeating(hash, vpn, __pa(vaddr), mode,
2135 mmu_linear_psize, mmu_kernel_ssize);
2138 raw_spin_lock(&linear_map_hash_lock);
2139 BUG_ON(linear_map_hash_slots[lmi] & 0x80);
2140 linear_map_hash_slots[lmi] = ret | 0x80;
2141 raw_spin_unlock(&linear_map_hash_lock);
2144 static void kernel_unmap_linear_page(unsigned long vaddr, unsigned long lmi)
2146 unsigned long hash, hidx, slot;
2147 unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);
2148 unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);
2150 hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);
2151 raw_spin_lock(&linear_map_hash_lock);
2152 if (!(linear_map_hash_slots[lmi] & 0x80)) {
2153 raw_spin_unlock(&linear_map_hash_lock);
2156 hidx = linear_map_hash_slots[lmi] & 0x7f;
2157 linear_map_hash_slots[lmi] = 0;
2158 raw_spin_unlock(&linear_map_hash_lock);
2159 if (hidx & _PTEIDX_SECONDARY)
2161 slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;
2162 slot += hidx & _PTEIDX_GROUP_IX;
2163 mmu_hash_ops.hpte_invalidate(slot, vpn, mmu_linear_psize,
2165 mmu_kernel_ssize, 0);
2168 void hash__kernel_map_pages(struct page *page, int numpages, int enable)
2170 unsigned long flags, vaddr, lmi;
2173 local_irq_save(flags);
2174 for (i = 0; i < numpages; i++, page++) {
2175 vaddr = (unsigned long)page_address(page);
2176 lmi = __pa(vaddr) >> PAGE_SHIFT;
2177 if (lmi >= linear_map_hash_count)
2180 kernel_map_linear_page(vaddr, lmi);
2182 kernel_unmap_linear_page(vaddr, lmi);
2184 local_irq_restore(flags);
2186 #endif /* CONFIG_DEBUG_PAGEALLOC || CONFIG_KFENCE */
2188 void hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,
2189 phys_addr_t first_memblock_size)
2192 * We don't currently support the first MEMBLOCK not mapping 0
2193 * physical on those processors
2195 BUG_ON(first_memblock_base != 0);
2198 * On virtualized systems the first entry is our RMA region aka VRMA,
2199 * non-virtualized 64-bit hash MMU systems don't have a limitation
2200 * on real mode access.
2202 * For guests on platforms before POWER9, we clamp the it limit to 1G
2203 * to avoid some funky things such as RTAS bugs etc...
2205 * On POWER9 we limit to 1TB in case the host erroneously told us that
2206 * the RMA was >1TB. Effective address bits 0:23 are treated as zero
2207 * (meaning the access is aliased to zero i.e. addr = addr % 1TB)
2208 * for virtual real mode addressing and so it doesn't make sense to
2209 * have an area larger than 1TB as it can't be addressed.
2211 if (!early_cpu_has_feature(CPU_FTR_HVMODE)) {
2212 ppc64_rma_size = first_memblock_size;
2213 if (!early_cpu_has_feature(CPU_FTR_ARCH_300))
2214 ppc64_rma_size = min_t(u64, ppc64_rma_size, 0x40000000);
2216 ppc64_rma_size = min_t(u64, ppc64_rma_size,
2217 1UL << SID_SHIFT_1T);
2219 /* Finally limit subsequent allocations */
2220 memblock_set_current_limit(ppc64_rma_size);
2222 ppc64_rma_size = ULONG_MAX;
2226 #ifdef CONFIG_DEBUG_FS
2228 static int hpt_order_get(void *data, u64 *val)
2230 *val = ppc64_pft_size;
2234 static int hpt_order_set(void *data, u64 val)
2238 if (!mmu_hash_ops.resize_hpt)
2242 ret = mmu_hash_ops.resize_hpt(val);
2248 DEFINE_DEBUGFS_ATTRIBUTE(fops_hpt_order, hpt_order_get, hpt_order_set, "%llu\n");
2250 static int __init hash64_debugfs(void)
2252 debugfs_create_file("hpt_order", 0600, arch_debugfs_dir, NULL,
2256 machine_device_initcall(pseries, hash64_debugfs);
2257 #endif /* CONFIG_DEBUG_FS */
2259 void __init print_system_hash_info(void)
2261 pr_info("ppc64_pft_size = 0x%llx\n", ppc64_pft_size);
2264 pr_info("htab_hash_mask = 0x%lx\n", htab_hash_mask);
2267 unsigned long arch_randomize_brk(struct mm_struct *mm)
2270 * If we are using 1TB segments and we are allowed to randomise
2271 * the heap, we can put it above 1TB so it is backed by a 1TB
2272 * segment. Otherwise the heap will be in the bottom 1TB
2273 * which always uses 256MB segments and this may result in a
2274 * performance penalty.
2276 if (is_32bit_task())
2277 return randomize_page(mm->brk, SZ_32M);
2278 else if (!radix_enabled() && mmu_highuser_ssize == MMU_SEGSIZE_1T)
2279 return randomize_page(max_t(unsigned long, mm->brk, SZ_1T), SZ_1G);
2281 return randomize_page(mm->brk, SZ_1G);