Path: blob/master/arch/powerpc/mm/book3s64/hash_utils.c
52695 views
// SPDX-License-Identifier: GPL-2.0-or-later1/*2* PowerPC64 port by Mike Corrigan and Dave Engebretsen3* {mikejc|engebret}@us.ibm.com4*5* Copyright (c) 2000 Mike Corrigan <[email protected]>6*7* SMP scalability work:8* Copyright (C) 2001 Anton Blanchard <[email protected]>, IBM9*10* Module name: htab.c11*12* Description:13* PowerPC Hashed Page Table functions14*/1516#undef DEBUG17#undef DEBUG_LOW1819#define pr_fmt(fmt) "hash-mmu: " fmt20#include <linux/spinlock.h>21#include <linux/errno.h>22#include <linux/sched/mm.h>23#include <linux/proc_fs.h>24#include <linux/stat.h>25#include <linux/sysctl.h>26#include <linux/export.h>27#include <linux/ctype.h>28#include <linux/cache.h>29#include <linux/init.h>30#include <linux/signal.h>31#include <linux/memblock.h>32#include <linux/context_tracking.h>33#include <linux/libfdt.h>34#include <linux/pkeys.h>35#include <linux/hugetlb.h>36#include <linux/cpu.h>37#include <linux/pgtable.h>38#include <linux/debugfs.h>39#include <linux/random.h>40#include <linux/elf-randomize.h>41#include <linux/of_fdt.h>42#include <linux/kfence.h>4344#include <asm/interrupt.h>45#include <asm/processor.h>46#include <asm/mmu.h>47#include <asm/mmu_context.h>48#include <asm/page.h>49#include <asm/pgalloc.h>50#include <asm/types.h>51#include <linux/uaccess.h>52#include <asm/machdep.h>53#include <asm/io.h>54#include <asm/eeh.h>55#include <asm/tlb.h>56#include <asm/cacheflush.h>57#include <asm/cputable.h>58#include <asm/sections.h>59#include <asm/spu.h>60#include <asm/udbg.h>61#include <asm/text-patching.h>62#include <asm/fadump.h>63#include <asm/firmware.h>64#include <asm/tm.h>65#include <asm/trace.h>66#include <asm/ps3.h>67#include <asm/pte-walk.h>68#include <asm/asm-prototypes.h>69#include <asm/ultravisor.h>70#include <asm/kfence.h>7172#include <mm/mmu_decl.h>7374#include "internal.h"757677#ifdef DEBUG78#define DBG(fmt...) udbg_printf(fmt)79#else80#define DBG(fmt...)81#endif8283#ifdef DEBUG_LOW84#define DBG_LOW(fmt...) udbg_printf(fmt)85#else86#define DBG_LOW(fmt...)87#endif8889#define KB (1024)90#define MB (1024*KB)91#define GB (1024L*MB)9293/*94* Note: pte --> Linux PTE95* HPTE --> PowerPC Hashed Page Table Entry96*97* Execution context:98* htab_initialize is called with the MMU off (of course), but99* the kernel has been copied down to zero so it can directly100* reference global data. At this point it is very difficult101* to print debug info.102*103*/104105static unsigned long _SDR1;106107u8 hpte_page_sizes[1 << LP_BITS];108EXPORT_SYMBOL_GPL(hpte_page_sizes);109110struct hash_pte *htab_address;111unsigned long htab_size_bytes;112unsigned long htab_hash_mask;113EXPORT_SYMBOL_GPL(htab_hash_mask);114int mmu_linear_psize = MMU_PAGE_4K;115EXPORT_SYMBOL_GPL(mmu_linear_psize);116int mmu_virtual_psize = MMU_PAGE_4K;117int mmu_vmalloc_psize = MMU_PAGE_4K;118EXPORT_SYMBOL_GPL(mmu_vmalloc_psize);119int mmu_io_psize = MMU_PAGE_4K;120int mmu_kernel_ssize = MMU_SEGSIZE_256M;121EXPORT_SYMBOL_GPL(mmu_kernel_ssize);122int mmu_highuser_ssize = MMU_SEGSIZE_256M;123u16 mmu_slb_size = 64;124EXPORT_SYMBOL_GPL(mmu_slb_size);125#ifdef CONFIG_PPC_64K_PAGES126int mmu_ci_restrictions;127#endif128struct mmu_hash_ops mmu_hash_ops __ro_after_init;129EXPORT_SYMBOL(mmu_hash_ops);130131/*132* These are definitions of page sizes arrays to be used when none133* is provided by the firmware.134*/135136/*137* Fallback (4k pages only)138*/139static struct mmu_psize_def mmu_psize_defaults[] = {140[MMU_PAGE_4K] = {141.shift = 12,142.sllp = 0,143.penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},144.avpnm = 0,145.tlbiel = 0,146},147};148149/*150* POWER4, GPUL, POWER5151*152* Support for 16Mb large pages153*/154static struct mmu_psize_def mmu_psize_defaults_gp[] = {155[MMU_PAGE_4K] = {156.shift = 12,157.sllp = 0,158.penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},159.avpnm = 0,160.tlbiel = 1,161},162[MMU_PAGE_16M] = {163.shift = 24,164.sllp = SLB_VSID_L,165.penc = {[0 ... MMU_PAGE_16M - 1] = -1, [MMU_PAGE_16M] = 0,166[MMU_PAGE_16M + 1 ... MMU_PAGE_COUNT - 1] = -1 },167.avpnm = 0x1UL,168.tlbiel = 0,169},170};171172static inline void tlbiel_hash_set_isa206(unsigned int set, unsigned int is)173{174unsigned long rb;175176rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));177178asm volatile("tlbiel %0" : : "r" (rb));179}180181/*182* tlbiel instruction for hash, set invalidation183* i.e., r=1 and is=01 or is=10 or is=11184*/185static __always_inline void tlbiel_hash_set_isa300(unsigned int set, unsigned int is,186unsigned int pid,187unsigned int ric, unsigned int prs)188{189unsigned long rb;190unsigned long rs;191unsigned int r = 0; /* hash format */192193rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));194rs = ((unsigned long)pid << PPC_BITLSHIFT(31));195196asm volatile(PPC_TLBIEL(%0, %1, %2, %3, %4)197: : "r"(rb), "r"(rs), "i"(ric), "i"(prs), "i"(r)198: "memory");199}200201202static void tlbiel_all_isa206(unsigned int num_sets, unsigned int is)203{204unsigned int set;205206asm volatile("ptesync": : :"memory");207208for (set = 0; set < num_sets; set++)209tlbiel_hash_set_isa206(set, is);210211ppc_after_tlbiel_barrier();212}213214static void tlbiel_all_isa300(unsigned int num_sets, unsigned int is)215{216unsigned int set;217218asm volatile("ptesync": : :"memory");219220/*221* Flush the partition table cache if this is HV mode.222*/223if (early_cpu_has_feature(CPU_FTR_HVMODE))224tlbiel_hash_set_isa300(0, is, 0, 2, 0);225226/*227* Now invalidate the process table cache. UPRT=0 HPT modes (what228* current hardware implements) do not use the process table, but229* add the flushes anyway.230*231* From ISA v3.0B p. 1078:232* The following forms are invalid.233* * PRS=1, R=0, and RIC!=2 (The only process-scoped234* HPT caching is of the Process Table.)235*/236tlbiel_hash_set_isa300(0, is, 0, 2, 1);237238/*239* Then flush the sets of the TLB proper. Hash mode uses240* partition scoped TLB translations, which may be flushed241* in !HV mode.242*/243for (set = 0; set < num_sets; set++)244tlbiel_hash_set_isa300(set, is, 0, 0, 0);245246ppc_after_tlbiel_barrier();247248asm volatile(PPC_ISA_3_0_INVALIDATE_ERAT "; isync" : : :"memory");249}250251void hash__tlbiel_all(unsigned int action)252{253unsigned int is;254255switch (action) {256case TLB_INVAL_SCOPE_GLOBAL:257is = 3;258break;259case TLB_INVAL_SCOPE_LPID:260is = 2;261break;262default:263BUG();264}265266if (early_cpu_has_feature(CPU_FTR_ARCH_300))267tlbiel_all_isa300(POWER9_TLB_SETS_HASH, is);268else if (early_cpu_has_feature(CPU_FTR_ARCH_207S))269tlbiel_all_isa206(POWER8_TLB_SETS, is);270else if (early_cpu_has_feature(CPU_FTR_ARCH_206))271tlbiel_all_isa206(POWER7_TLB_SETS, is);272else273WARN(1, "%s called on pre-POWER7 CPU\n", __func__);274}275276#if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)277static void kernel_map_linear_page(unsigned long vaddr, unsigned long idx,278u8 *slots, raw_spinlock_t *lock)279{280unsigned long hash;281unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);282unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);283unsigned long mode = htab_convert_pte_flags(pgprot_val(PAGE_KERNEL), HPTE_USE_KERNEL_KEY);284long ret;285286hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);287288/* Don't create HPTE entries for bad address */289if (!vsid)290return;291292if (slots[idx] & 0x80)293return;294295ret = hpte_insert_repeating(hash, vpn, __pa(vaddr), mode,296HPTE_V_BOLTED,297mmu_linear_psize, mmu_kernel_ssize);298299BUG_ON (ret < 0);300raw_spin_lock(lock);301BUG_ON(slots[idx] & 0x80);302slots[idx] = ret | 0x80;303raw_spin_unlock(lock);304}305306static void kernel_unmap_linear_page(unsigned long vaddr, unsigned long idx,307u8 *slots, raw_spinlock_t *lock)308{309unsigned long hash, hslot, slot;310unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);311unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);312313hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);314raw_spin_lock(lock);315if (!(slots[idx] & 0x80)) {316raw_spin_unlock(lock);317return;318}319hslot = slots[idx] & 0x7f;320slots[idx] = 0;321raw_spin_unlock(lock);322if (hslot & _PTEIDX_SECONDARY)323hash = ~hash;324slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;325slot += hslot & _PTEIDX_GROUP_IX;326mmu_hash_ops.hpte_invalidate(slot, vpn, mmu_linear_psize,327mmu_linear_psize,328mmu_kernel_ssize, 0);329}330#endif331332static inline bool hash_supports_debug_pagealloc(void)333{334unsigned long max_hash_count = ppc64_rma_size / 4;335unsigned long linear_map_count = memblock_end_of_DRAM() >> PAGE_SHIFT;336337if (!debug_pagealloc_enabled() || linear_map_count > max_hash_count)338return false;339return true;340}341342#ifdef CONFIG_DEBUG_PAGEALLOC343static u8 *linear_map_hash_slots;344static unsigned long linear_map_hash_count;345static DEFINE_RAW_SPINLOCK(linear_map_hash_lock);346static __init void hash_debug_pagealloc_alloc_slots(void)347{348if (!hash_supports_debug_pagealloc())349return;350351linear_map_hash_count = memblock_end_of_DRAM() >> PAGE_SHIFT;352linear_map_hash_slots = memblock_alloc_try_nid(353linear_map_hash_count, 1, MEMBLOCK_LOW_LIMIT,354ppc64_rma_size, NUMA_NO_NODE);355if (!linear_map_hash_slots)356panic("%s: Failed to allocate %lu bytes max_addr=%pa\n",357__func__, linear_map_hash_count, &ppc64_rma_size);358}359360static inline void hash_debug_pagealloc_add_slot(phys_addr_t paddr,361int slot)362{363if (!debug_pagealloc_enabled() || !linear_map_hash_count)364return;365if ((paddr >> PAGE_SHIFT) < linear_map_hash_count)366linear_map_hash_slots[paddr >> PAGE_SHIFT] = slot | 0x80;367}368369static int hash_debug_pagealloc_map_pages(struct page *page, int numpages,370int enable)371{372unsigned long flags, vaddr, lmi;373int i;374375if (!debug_pagealloc_enabled() || !linear_map_hash_count)376return 0;377378local_irq_save(flags);379for (i = 0; i < numpages; i++, page++) {380vaddr = (unsigned long)page_address(page);381lmi = __pa(vaddr) >> PAGE_SHIFT;382if (lmi >= linear_map_hash_count)383continue;384if (enable)385kernel_map_linear_page(vaddr, lmi,386linear_map_hash_slots, &linear_map_hash_lock);387else388kernel_unmap_linear_page(vaddr, lmi,389linear_map_hash_slots, &linear_map_hash_lock);390}391local_irq_restore(flags);392return 0;393}394395#else /* CONFIG_DEBUG_PAGEALLOC */396static inline void hash_debug_pagealloc_alloc_slots(void) {}397static inline void hash_debug_pagealloc_add_slot(phys_addr_t paddr, int slot) {}398static int __maybe_unused399hash_debug_pagealloc_map_pages(struct page *page, int numpages, int enable)400{401return 0;402}403#endif /* CONFIG_DEBUG_PAGEALLOC */404405#ifdef CONFIG_KFENCE406static u8 *linear_map_kf_hash_slots;407static unsigned long linear_map_kf_hash_count;408static DEFINE_RAW_SPINLOCK(linear_map_kf_hash_lock);409410static phys_addr_t kfence_pool;411412static __init void hash_kfence_alloc_pool(void)413{414if (!kfence_early_init_enabled())415goto err;416417/* allocate linear map for kfence within RMA region */418linear_map_kf_hash_count = KFENCE_POOL_SIZE >> PAGE_SHIFT;419linear_map_kf_hash_slots = memblock_alloc_try_nid(420linear_map_kf_hash_count, 1,421MEMBLOCK_LOW_LIMIT, ppc64_rma_size,422NUMA_NO_NODE);423if (!linear_map_kf_hash_slots) {424pr_err("%s: memblock for linear map (%lu) failed\n", __func__,425linear_map_kf_hash_count);426goto err;427}428429/* allocate kfence pool early */430kfence_pool = memblock_phys_alloc_range(KFENCE_POOL_SIZE, PAGE_SIZE,431MEMBLOCK_LOW_LIMIT, MEMBLOCK_ALLOC_ANYWHERE);432if (!kfence_pool) {433pr_err("%s: memblock for kfence pool (%lu) failed\n", __func__,434KFENCE_POOL_SIZE);435memblock_free(linear_map_kf_hash_slots,436linear_map_kf_hash_count);437linear_map_kf_hash_count = 0;438goto err;439}440memblock_mark_nomap(kfence_pool, KFENCE_POOL_SIZE);441442return;443err:444pr_info("Disabling kfence\n");445disable_kfence();446}447448static __init void hash_kfence_map_pool(void)449{450unsigned long kfence_pool_start, kfence_pool_end;451unsigned long prot = pgprot_val(PAGE_KERNEL);452unsigned int pshift = mmu_psize_defs[mmu_linear_psize].shift;453454if (!kfence_pool)455return;456457kfence_pool_start = (unsigned long) __va(kfence_pool);458kfence_pool_end = kfence_pool_start + KFENCE_POOL_SIZE;459__kfence_pool = (char *) kfence_pool_start;460BUG_ON(htab_bolt_mapping(kfence_pool_start, kfence_pool_end,461kfence_pool, prot, mmu_linear_psize,462mmu_kernel_ssize));463update_page_count(mmu_linear_psize, KFENCE_POOL_SIZE >> pshift);464memblock_clear_nomap(kfence_pool, KFENCE_POOL_SIZE);465}466467static inline void hash_kfence_add_slot(phys_addr_t paddr, int slot)468{469unsigned long vaddr = (unsigned long) __va(paddr);470unsigned long lmi = (vaddr - (unsigned long)__kfence_pool)471>> PAGE_SHIFT;472473if (!kfence_pool)474return;475BUG_ON(!is_kfence_address((void *)vaddr));476BUG_ON(lmi >= linear_map_kf_hash_count);477linear_map_kf_hash_slots[lmi] = slot | 0x80;478}479480static int hash_kfence_map_pages(struct page *page, int numpages, int enable)481{482unsigned long flags, vaddr, lmi;483int i;484485WARN_ON_ONCE(!linear_map_kf_hash_count);486local_irq_save(flags);487for (i = 0; i < numpages; i++, page++) {488vaddr = (unsigned long)page_address(page);489lmi = (vaddr - (unsigned long)__kfence_pool) >> PAGE_SHIFT;490491/* Ideally this should never happen */492if (lmi >= linear_map_kf_hash_count) {493WARN_ON_ONCE(1);494continue;495}496497if (enable)498kernel_map_linear_page(vaddr, lmi,499linear_map_kf_hash_slots,500&linear_map_kf_hash_lock);501else502kernel_unmap_linear_page(vaddr, lmi,503linear_map_kf_hash_slots,504&linear_map_kf_hash_lock);505}506local_irq_restore(flags);507return 0;508}509#else510static inline void hash_kfence_alloc_pool(void) {}511static inline void hash_kfence_map_pool(void) {}512static inline void hash_kfence_add_slot(phys_addr_t paddr, int slot) {}513static int __maybe_unused514hash_kfence_map_pages(struct page *page, int numpages, int enable)515{516return 0;517}518#endif519520#if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)521int hash__kernel_map_pages(struct page *page, int numpages, int enable)522{523void *vaddr = page_address(page);524525if (is_kfence_address(vaddr))526return hash_kfence_map_pages(page, numpages, enable);527else528return hash_debug_pagealloc_map_pages(page, numpages, enable);529}530531static void hash_linear_map_add_slot(phys_addr_t paddr, int slot)532{533if (is_kfence_address(__va(paddr)))534hash_kfence_add_slot(paddr, slot);535else536hash_debug_pagealloc_add_slot(paddr, slot);537}538#else539static void hash_linear_map_add_slot(phys_addr_t paddr, int slot) {}540#endif541542/*543* 'R' and 'C' update notes:544* - Under pHyp or KVM, the updatepp path will not set C, thus it *will*545* create writeable HPTEs without C set, because the hcall H_PROTECT546* that we use in that case will not update C547* - The above is however not a problem, because we also don't do that548* fancy "no flush" variant of eviction and we use H_REMOVE which will549* do the right thing and thus we don't have the race I described earlier550*551* - Under bare metal, we do have the race, so we need R and C set552* - We make sure R is always set and never lost553* - C is _PAGE_DIRTY, and *should* always be set for a writeable mapping554*/555unsigned long htab_convert_pte_flags(unsigned long pteflags, unsigned long flags)556{557unsigned long rflags = 0;558559/* _PAGE_EXEC -> NOEXEC */560if ((pteflags & _PAGE_EXEC) == 0)561rflags |= HPTE_R_N;562/*563* PPP bits:564* Linux uses slb key 0 for kernel and 1 for user.565* kernel RW areas are mapped with PPP=0b000566* User area is mapped with PPP=0b010 for read/write567* or PPP=0b011 for read-only (including writeable but clean pages).568*/569if (pteflags & _PAGE_PRIVILEGED) {570/*571* Kernel read only mapped with ppp bits 0b110572*/573if (!(pteflags & _PAGE_WRITE)) {574if (mmu_has_feature(MMU_FTR_KERNEL_RO))575rflags |= (HPTE_R_PP0 | 0x2);576else577rflags |= 0x3;578}579VM_WARN_ONCE(!(pteflags & _PAGE_RWX), "no-access mapping request");580} else {581if (pteflags & _PAGE_RWX)582rflags |= 0x2;583/*584* We should never hit this in normal fault handling because585* a permission check (check_pte_access()) will bubble this586* to higher level linux handler even for PAGE_NONE.587*/588VM_WARN_ONCE(!(pteflags & _PAGE_RWX), "no-access mapping request");589if (!((pteflags & _PAGE_WRITE) && (pteflags & _PAGE_DIRTY)))590rflags |= 0x1;591}592/*593* We can't allow hardware to update hpte bits. Hence always594* set 'R' bit and set 'C' if it is a write fault595*/596rflags |= HPTE_R_R;597598if (pteflags & _PAGE_DIRTY)599rflags |= HPTE_R_C;600/*601* Add in WIG bits602*/603604if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_TOLERANT)605rflags |= HPTE_R_I;606else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_NON_IDEMPOTENT)607rflags |= (HPTE_R_I | HPTE_R_G);608else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_SAO)609rflags |= (HPTE_R_W | HPTE_R_I | HPTE_R_M);610else611/*612* Add memory coherence if cache inhibited is not set613*/614rflags |= HPTE_R_M;615616rflags |= pte_to_hpte_pkey_bits(pteflags, flags);617return rflags;618}619620int htab_bolt_mapping(unsigned long vstart, unsigned long vend,621unsigned long pstart, unsigned long prot,622int psize, int ssize)623{624unsigned long vaddr, paddr;625unsigned int step, shift;626int ret = 0;627628shift = mmu_psize_defs[psize].shift;629step = 1 << shift;630631prot = htab_convert_pte_flags(prot, HPTE_USE_KERNEL_KEY);632633DBG("htab_bolt_mapping(%lx..%lx -> %lx (%lx,%d,%d)\n",634vstart, vend, pstart, prot, psize, ssize);635636/* Carefully map only the possible range */637vaddr = ALIGN(vstart, step);638paddr = ALIGN(pstart, step);639vend = ALIGN_DOWN(vend, step);640641for (; vaddr < vend; vaddr += step, paddr += step) {642unsigned long hash, hpteg;643unsigned long vsid = get_kernel_vsid(vaddr, ssize);644unsigned long vpn = hpt_vpn(vaddr, vsid, ssize);645unsigned long tprot = prot;646bool secondary_hash = false;647648/*649* If we hit a bad address return error.650*/651if (!vsid)652return -1;653/* Make kernel text executable */654if (overlaps_kernel_text(vaddr, vaddr + step))655tprot &= ~HPTE_R_N;656657/*658* If relocatable, check if it overlaps interrupt vectors that659* are copied down to real 0. For relocatable kernel660* (e.g. kdump case) we copy interrupt vectors down to real661* address 0. Mark that region as executable. This is662* because on p8 system with relocation on exception feature663* enabled, exceptions are raised with MMU (IR=DR=1) ON. Hence664* in order to execute the interrupt handlers in virtual665* mode the vector region need to be marked as executable.666*/667if ((PHYSICAL_START > MEMORY_START) &&668overlaps_interrupt_vector_text(vaddr, vaddr + step))669tprot &= ~HPTE_R_N;670671hash = hpt_hash(vpn, shift, ssize);672hpteg = ((hash & htab_hash_mask) * HPTES_PER_GROUP);673674BUG_ON(!mmu_hash_ops.hpte_insert);675repeat:676ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,677HPTE_V_BOLTED, psize, psize,678ssize);679if (ret == -1) {680/*681* Try to keep bolted entries in primary.682* Remove non bolted entries and try insert again683*/684ret = mmu_hash_ops.hpte_remove(hpteg);685if (ret != -1)686ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,687HPTE_V_BOLTED, psize, psize,688ssize);689if (ret == -1 && !secondary_hash) {690secondary_hash = true;691hpteg = ((~hash & htab_hash_mask) * HPTES_PER_GROUP);692goto repeat;693}694}695696if (ret < 0)697break;698699cond_resched();700/* add slot info in debug_pagealloc / kfence linear map */701hash_linear_map_add_slot(paddr, ret);702}703return ret < 0 ? ret : 0;704}705706int htab_remove_mapping(unsigned long vstart, unsigned long vend,707int psize, int ssize)708{709unsigned long vaddr, time_limit;710unsigned int step, shift;711int rc;712int ret = 0;713714shift = mmu_psize_defs[psize].shift;715step = 1 << shift;716717if (!mmu_hash_ops.hpte_removebolted)718return -ENODEV;719720/* Unmap the full range specificied */721vaddr = ALIGN_DOWN(vstart, step);722time_limit = jiffies + HZ;723724for (;vaddr < vend; vaddr += step) {725rc = mmu_hash_ops.hpte_removebolted(vaddr, psize, ssize);726727/*728* For large number of mappings introduce a cond_resched()729* to prevent softlockup warnings.730*/731if (time_after(jiffies, time_limit)) {732cond_resched();733time_limit = jiffies + HZ;734}735if (rc == -ENOENT) {736ret = -ENOENT;737continue;738}739if (rc < 0)740return rc;741}742743return ret;744}745746static bool disable_1tb_segments __ro_after_init;747748static int __init parse_disable_1tb_segments(char *p)749{750disable_1tb_segments = true;751return 0;752}753early_param("disable_1tb_segments", parse_disable_1tb_segments);754755bool stress_hpt_enabled __initdata;756757static int __init parse_stress_hpt(char *p)758{759stress_hpt_enabled = true;760return 0;761}762early_param("stress_hpt", parse_stress_hpt);763764__ro_after_init DEFINE_STATIC_KEY_FALSE(stress_hpt_key);765766/*767* per-CPU array allocated if we enable stress_hpt.768*/769#define STRESS_MAX_GROUPS 16770struct stress_hpt_struct {771unsigned long last_group[STRESS_MAX_GROUPS];772};773774static inline int stress_nr_groups(void)775{776/*777* LPAR H_REMOVE flushes TLB, so need some number > 1 of entries778* to allow practical forward progress. Bare metal returns 1, which779* seems to help uncover more bugs.780*/781if (firmware_has_feature(FW_FEATURE_LPAR))782return STRESS_MAX_GROUPS;783else784return 1;785}786787static struct stress_hpt_struct *stress_hpt_struct;788789static int __init htab_dt_scan_seg_sizes(unsigned long node,790const char *uname, int depth,791void *data)792{793const char *type = of_get_flat_dt_prop(node, "device_type", NULL);794const __be32 *prop;795int size = 0;796797/* We are scanning "cpu" nodes only */798if (type == NULL || strcmp(type, "cpu") != 0)799return 0;800801prop = of_get_flat_dt_prop(node, "ibm,processor-segment-sizes", &size);802if (prop == NULL)803return 0;804for (; size >= 4; size -= 4, ++prop) {805if (be32_to_cpu(prop[0]) == 40) {806DBG("1T segment support detected\n");807808if (disable_1tb_segments) {809DBG("1T segments disabled by command line\n");810break;811}812813cur_cpu_spec->mmu_features |= MMU_FTR_1T_SEGMENT;814return 1;815}816}817cur_cpu_spec->mmu_features &= ~MMU_FTR_NO_SLBIE_B;818return 0;819}820821static int __init get_idx_from_shift(unsigned int shift)822{823int idx = -1;824825switch (shift) {826case 0xc:827idx = MMU_PAGE_4K;828break;829case 0x10:830idx = MMU_PAGE_64K;831break;832case 0x14:833idx = MMU_PAGE_1M;834break;835case 0x18:836idx = MMU_PAGE_16M;837break;838case 0x22:839idx = MMU_PAGE_16G;840break;841}842return idx;843}844845static int __init htab_dt_scan_page_sizes(unsigned long node,846const char *uname, int depth,847void *data)848{849const char *type = of_get_flat_dt_prop(node, "device_type", NULL);850const __be32 *prop;851int size = 0;852853/* We are scanning "cpu" nodes only */854if (type == NULL || strcmp(type, "cpu") != 0)855return 0;856857prop = of_get_flat_dt_prop(node, "ibm,segment-page-sizes", &size);858if (!prop)859return 0;860861pr_info("Page sizes from device-tree:\n");862size /= 4;863cur_cpu_spec->mmu_features &= ~(MMU_FTR_16M_PAGE);864while(size > 0) {865unsigned int base_shift = be32_to_cpu(prop[0]);866unsigned int slbenc = be32_to_cpu(prop[1]);867unsigned int lpnum = be32_to_cpu(prop[2]);868struct mmu_psize_def *def;869int idx, base_idx;870871size -= 3; prop += 3;872base_idx = get_idx_from_shift(base_shift);873if (base_idx < 0) {874/* skip the pte encoding also */875prop += lpnum * 2; size -= lpnum * 2;876continue;877}878def = &mmu_psize_defs[base_idx];879if (base_idx == MMU_PAGE_16M)880cur_cpu_spec->mmu_features |= MMU_FTR_16M_PAGE;881882def->shift = base_shift;883if (base_shift <= 23)884def->avpnm = 0;885else886def->avpnm = (1 << (base_shift - 23)) - 1;887def->sllp = slbenc;888/*889* We don't know for sure what's up with tlbiel, so890* for now we only set it for 4K and 64K pages891*/892if (base_idx == MMU_PAGE_4K || base_idx == MMU_PAGE_64K)893def->tlbiel = 1;894else895def->tlbiel = 0;896897while (size > 0 && lpnum) {898unsigned int shift = be32_to_cpu(prop[0]);899int penc = be32_to_cpu(prop[1]);900901prop += 2; size -= 2;902lpnum--;903904idx = get_idx_from_shift(shift);905if (idx < 0)906continue;907908if (penc == -1)909pr_err("Invalid penc for base_shift=%d "910"shift=%d\n", base_shift, shift);911912def->penc[idx] = penc;913pr_info("base_shift=%d: shift=%d, sllp=0x%04lx,"914" avpnm=0x%08lx, tlbiel=%d, penc=%d\n",915base_shift, shift, def->sllp,916def->avpnm, def->tlbiel, def->penc[idx]);917}918}919920return 1;921}922923#ifdef CONFIG_HUGETLB_PAGE924/*925* Scan for 16G memory blocks that have been set aside for huge pages926* and reserve those blocks for 16G huge pages.927*/928static int __init htab_dt_scan_hugepage_blocks(unsigned long node,929const char *uname, int depth,930void *data) {931const char *type = of_get_flat_dt_prop(node, "device_type", NULL);932const __be64 *addr_prop;933const __be32 *page_count_prop;934unsigned int expected_pages;935long unsigned int phys_addr;936long unsigned int block_size;937938/* We are scanning "memory" nodes only */939if (type == NULL || strcmp(type, "memory") != 0)940return 0;941942/*943* This property is the log base 2 of the number of virtual pages that944* will represent this memory block.945*/946page_count_prop = of_get_flat_dt_prop(node, "ibm,expected#pages", NULL);947if (page_count_prop == NULL)948return 0;949expected_pages = (1 << be32_to_cpu(page_count_prop[0]));950addr_prop = of_get_flat_dt_prop(node, "reg", NULL);951if (addr_prop == NULL)952return 0;953phys_addr = be64_to_cpu(addr_prop[0]);954block_size = be64_to_cpu(addr_prop[1]);955if (block_size != (16 * GB))956return 0;957pr_info("Huge page(16GB) memory: "958"addr = 0x%lX size = 0x%lX pages = %d\n",959phys_addr, block_size, expected_pages);960if (phys_addr + block_size * expected_pages <= memblock_end_of_DRAM()) {961memblock_reserve(phys_addr, block_size * expected_pages);962pseries_add_gpage(phys_addr, block_size, expected_pages);963}964return 0;965}966#endif /* CONFIG_HUGETLB_PAGE */967968static void __init mmu_psize_set_default_penc(void)969{970int bpsize, apsize;971for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)972for (apsize = 0; apsize < MMU_PAGE_COUNT; apsize++)973mmu_psize_defs[bpsize].penc[apsize] = -1;974}975976#ifdef CONFIG_PPC_64K_PAGES977978static bool __init might_have_hea(void)979{980/*981* The HEA ethernet adapter requires awareness of the982* GX bus. Without that awareness we can easily assume983* we will never see an HEA ethernet device.984*/985#ifdef CONFIG_IBMEBUS986return !cpu_has_feature(CPU_FTR_ARCH_207S) &&987firmware_has_feature(FW_FEATURE_SPLPAR);988#else989return false;990#endif991}992993#endif /* #ifdef CONFIG_PPC_64K_PAGES */994995static void __init htab_scan_page_sizes(void)996{997int rc;998999/* se the invalid penc to -1 */1000mmu_psize_set_default_penc();10011002/* Default to 4K pages only */1003memcpy(mmu_psize_defs, mmu_psize_defaults,1004sizeof(mmu_psize_defaults));10051006/*1007* Try to find the available page sizes in the device-tree1008*/1009rc = of_scan_flat_dt(htab_dt_scan_page_sizes, NULL);1010if (rc == 0 && early_mmu_has_feature(MMU_FTR_16M_PAGE)) {1011/*1012* Nothing in the device-tree, but the CPU supports 16M pages,1013* so let's fallback on a known size list for 16M capable CPUs.1014*/1015memcpy(mmu_psize_defs, mmu_psize_defaults_gp,1016sizeof(mmu_psize_defaults_gp));1017}10181019#ifdef CONFIG_HUGETLB_PAGE1020if (!hugetlb_disabled && !early_radix_enabled() ) {1021/* Reserve 16G huge page memory sections for huge pages */1022of_scan_flat_dt(htab_dt_scan_hugepage_blocks, NULL);1023}1024#endif /* CONFIG_HUGETLB_PAGE */1025}10261027/*1028* Fill in the hpte_page_sizes[] array.1029* We go through the mmu_psize_defs[] array looking for all the1030* supported base/actual page size combinations. Each combination1031* has a unique pagesize encoding (penc) value in the low bits of1032* the LP field of the HPTE. For actual page sizes less than 1MB,1033* some of the upper LP bits are used for RPN bits, meaning that1034* we need to fill in several entries in hpte_page_sizes[].1035*1036* In diagrammatic form, with r = RPN bits and z = page size bits:1037* PTE LP actual page size1038* rrrr rrrz >=8KB1039* rrrr rrzz >=16KB1040* rrrr rzzz >=32KB1041* rrrr zzzz >=64KB1042* ...1043*1044* The zzzz bits are implementation-specific but are chosen so that1045* no encoding for a larger page size uses the same value in its1046* low-order N bits as the encoding for the 2^(12+N) byte page size1047* (if it exists).1048*/1049static void __init init_hpte_page_sizes(void)1050{1051long int ap, bp;1052long int shift, penc;10531054for (bp = 0; bp < MMU_PAGE_COUNT; ++bp) {1055if (!mmu_psize_defs[bp].shift)1056continue; /* not a supported page size */1057for (ap = bp; ap < MMU_PAGE_COUNT; ++ap) {1058penc = mmu_psize_defs[bp].penc[ap];1059if (penc == -1 || !mmu_psize_defs[ap].shift)1060continue;1061shift = mmu_psize_defs[ap].shift - LP_SHIFT;1062if (shift <= 0)1063continue; /* should never happen */1064/*1065* For page sizes less than 1MB, this loop1066* replicates the entry for all possible values1067* of the rrrr bits.1068*/1069while (penc < (1 << LP_BITS)) {1070hpte_page_sizes[penc] = (ap << 4) | bp;1071penc += 1 << shift;1072}1073}1074}1075}10761077static void __init htab_init_page_sizes(void)1078{1079bool aligned = true;1080init_hpte_page_sizes();10811082if (!hash_supports_debug_pagealloc() && !kfence_early_init_enabled()) {1083/*1084* Pick a size for the linear mapping. Currently, we only1085* support 16M, 1M and 4K which is the default1086*/1087if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) &&1088(unsigned long)_stext % 0x1000000) {1089if (mmu_psize_defs[MMU_PAGE_16M].shift)1090pr_warn("Kernel not 16M aligned, disabling 16M linear map alignment\n");1091aligned = false;1092}10931094if (mmu_psize_defs[MMU_PAGE_16M].shift && aligned)1095mmu_linear_psize = MMU_PAGE_16M;1096else if (mmu_psize_defs[MMU_PAGE_1M].shift)1097mmu_linear_psize = MMU_PAGE_1M;1098}10991100#ifdef CONFIG_PPC_64K_PAGES1101/*1102* Pick a size for the ordinary pages. Default is 4K, we support1103* 64K for user mappings and vmalloc if supported by the processor.1104* We only use 64k for ioremap if the processor1105* (and firmware) support cache-inhibited large pages.1106* If not, we use 4k and set mmu_ci_restrictions so that1107* hash_page knows to switch processes that use cache-inhibited1108* mappings to 4k pages.1109*/1110if (mmu_psize_defs[MMU_PAGE_64K].shift) {1111mmu_virtual_psize = MMU_PAGE_64K;1112mmu_vmalloc_psize = MMU_PAGE_64K;1113if (mmu_linear_psize == MMU_PAGE_4K)1114mmu_linear_psize = MMU_PAGE_64K;1115if (mmu_has_feature(MMU_FTR_CI_LARGE_PAGE)) {1116/*1117* When running on pSeries using 64k pages for ioremap1118* would stop us accessing the HEA ethernet. So if we1119* have the chance of ever seeing one, stay at 4k.1120*/1121if (!might_have_hea())1122mmu_io_psize = MMU_PAGE_64K;1123} else1124mmu_ci_restrictions = 1;1125}1126#endif /* CONFIG_PPC_64K_PAGES */11271128#ifdef CONFIG_SPARSEMEM_VMEMMAP1129/*1130* We try to use 16M pages for vmemmap if that is supported1131* and we have at least 1G of RAM at boot1132*/1133if (mmu_psize_defs[MMU_PAGE_16M].shift &&1134memblock_phys_mem_size() >= 0x40000000)1135mmu_vmemmap_psize = MMU_PAGE_16M;1136else1137mmu_vmemmap_psize = mmu_virtual_psize;1138#endif /* CONFIG_SPARSEMEM_VMEMMAP */11391140pr_info("Page orders: linear mapping = %d, "1141"virtual = %d, io = %d"1142#ifdef CONFIG_SPARSEMEM_VMEMMAP1143", vmemmap = %d"1144#endif1145"\n",1146mmu_psize_defs[mmu_linear_psize].shift,1147mmu_psize_defs[mmu_virtual_psize].shift,1148mmu_psize_defs[mmu_io_psize].shift1149#ifdef CONFIG_SPARSEMEM_VMEMMAP1150,mmu_psize_defs[mmu_vmemmap_psize].shift1151#endif1152);1153}11541155static int __init htab_dt_scan_pftsize(unsigned long node,1156const char *uname, int depth,1157void *data)1158{1159const char *type = of_get_flat_dt_prop(node, "device_type", NULL);1160const __be32 *prop;11611162/* We are scanning "cpu" nodes only */1163if (type == NULL || strcmp(type, "cpu") != 0)1164return 0;11651166prop = of_get_flat_dt_prop(node, "ibm,pft-size", NULL);1167if (prop != NULL) {1168/* pft_size[0] is the NUMA CEC cookie */1169ppc64_pft_size = be32_to_cpu(prop[1]);1170return 1;1171}1172return 0;1173}11741175unsigned htab_shift_for_mem_size(unsigned long mem_size)1176{1177unsigned memshift = __ilog2(mem_size);1178unsigned pshift = mmu_psize_defs[mmu_virtual_psize].shift;1179unsigned pteg_shift;11801181/* round mem_size up to next power of 2 */1182if ((1UL << memshift) < mem_size)1183memshift += 1;11841185/* aim for 2 pages / pteg */1186pteg_shift = memshift - (pshift + 1);11871188/*1189* 2^11 PTEGS of 128 bytes each, ie. 2^18 bytes is the minimum htab1190* size permitted by the architecture.1191*/1192return max(pteg_shift + 7, 18U);1193}11941195static unsigned long __init htab_get_table_size(void)1196{1197/*1198* If hash size isn't already provided by the platform, we try to1199* retrieve it from the device-tree. If it's not there neither, we1200* calculate it now based on the total RAM size1201*/1202if (ppc64_pft_size == 0)1203of_scan_flat_dt(htab_dt_scan_pftsize, NULL);1204if (ppc64_pft_size)1205return 1UL << ppc64_pft_size;12061207return 1UL << htab_shift_for_mem_size(memblock_phys_mem_size());1208}12091210#ifdef CONFIG_MEMORY_HOTPLUG1211static int resize_hpt_for_hotplug(unsigned long new_mem_size)1212{1213unsigned target_hpt_shift;12141215if (!mmu_hash_ops.resize_hpt)1216return 0;12171218target_hpt_shift = htab_shift_for_mem_size(new_mem_size);12191220/*1221* To avoid lots of HPT resizes if memory size is fluctuating1222* across a boundary, we deliberately have some hysterisis1223* here: we immediately increase the HPT size if the target1224* shift exceeds the current shift, but we won't attempt to1225* reduce unless the target shift is at least 2 below the1226* current shift1227*/1228if (target_hpt_shift > ppc64_pft_size ||1229target_hpt_shift < ppc64_pft_size - 1)1230return mmu_hash_ops.resize_hpt(target_hpt_shift);12311232return 0;1233}12341235int hash__create_section_mapping(unsigned long start, unsigned long end,1236int nid, pgprot_t prot)1237{1238int rc;1239unsigned int pshift = mmu_psize_defs[mmu_linear_psize].shift;12401241if (end >= H_VMALLOC_START) {1242pr_warn("Outside the supported range\n");1243return -1;1244}12451246resize_hpt_for_hotplug(memblock_phys_mem_size());12471248rc = htab_bolt_mapping(start, end, __pa(start),1249pgprot_val(prot), mmu_linear_psize,1250mmu_kernel_ssize);12511252if (rc < 0) {1253int rc2 = htab_remove_mapping(start, end, mmu_linear_psize,1254mmu_kernel_ssize);1255BUG_ON(rc2 && (rc2 != -ENOENT));1256}1257update_page_count(mmu_linear_psize, (end - start) >> pshift);1258return rc;1259}12601261int hash__remove_section_mapping(unsigned long start, unsigned long end)1262{1263unsigned int pshift = mmu_psize_defs[mmu_linear_psize].shift;12641265int rc = htab_remove_mapping(start, end, mmu_linear_psize,1266mmu_kernel_ssize);12671268if (resize_hpt_for_hotplug(memblock_phys_mem_size()) == -ENOSPC)1269pr_warn("Hash collision while resizing HPT\n");12701271if (!rc)1272update_page_count(mmu_linear_psize, -((end - start) >> pshift));1273return rc;1274}1275#endif /* CONFIG_MEMORY_HOTPLUG */12761277static void __init hash_init_partition_table(phys_addr_t hash_table,1278unsigned long htab_size)1279{1280mmu_partition_table_init();12811282/*1283* PS field (VRMA page size) is not used for LPID 0, hence set to 0.1284* For now, UPRT is 0 and we have no segment table.1285*/1286htab_size = __ilog2(htab_size) - 18;1287mmu_partition_table_set_entry(0, hash_table | htab_size, 0, false);1288pr_info("Partition table %p\n", partition_tb);1289}12901291void hpt_clear_stress(void);1292static struct timer_list stress_hpt_timer;1293static void stress_hpt_timer_fn(struct timer_list *timer)1294{1295int next_cpu;12961297hpt_clear_stress();1298if (!firmware_has_feature(FW_FEATURE_LPAR))1299tlbiel_all();13001301next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);1302if (next_cpu >= nr_cpu_ids)1303next_cpu = cpumask_first(cpu_online_mask);1304stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);1305add_timer_on(&stress_hpt_timer, next_cpu);1306}13071308static void __init htab_initialize(void)1309{1310unsigned long table;1311unsigned long pteg_count;1312unsigned long prot;1313phys_addr_t base = 0, size = 0, end, limit = MEMBLOCK_ALLOC_ANYWHERE;1314u64 i;1315unsigned int pshift = mmu_psize_defs[mmu_linear_psize].shift;13161317DBG(" -> htab_initialize()\n");13181319if (firmware_has_feature(FW_FEATURE_LPAR))1320limit = ppc64_rma_size;13211322if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) {1323mmu_kernel_ssize = MMU_SEGSIZE_1T;1324mmu_highuser_ssize = MMU_SEGSIZE_1T;1325pr_info("Using 1TB segments\n");1326}13271328if (stress_slb_enabled)1329static_branch_enable(&stress_slb_key);13301331if (no_slb_preload)1332static_branch_enable(&no_slb_preload_key);13331334if (stress_hpt_enabled) {1335unsigned long tmp;1336static_branch_enable(&stress_hpt_key);1337// Too early to use nr_cpu_ids, so use NR_CPUS1338tmp = memblock_phys_alloc_range(sizeof(struct stress_hpt_struct) * NR_CPUS,1339__alignof__(struct stress_hpt_struct),1340MEMBLOCK_LOW_LIMIT, limit);1341memset((void *)tmp, 0xff, sizeof(struct stress_hpt_struct) * NR_CPUS);1342stress_hpt_struct = __va(tmp);13431344timer_setup(&stress_hpt_timer, stress_hpt_timer_fn, 0);1345stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);1346add_timer(&stress_hpt_timer);1347}13481349/*1350* Calculate the required size of the htab. We want the number of1351* PTEGs to equal one half the number of real pages.1352*/1353htab_size_bytes = htab_get_table_size();1354pteg_count = htab_size_bytes >> 7;13551356htab_hash_mask = pteg_count - 1;13571358if (firmware_has_feature(FW_FEATURE_LPAR) ||1359firmware_has_feature(FW_FEATURE_PS3_LV1)) {1360/* Using a hypervisor which owns the htab */1361htab_address = NULL;1362_SDR1 = 0;1363#ifdef CONFIG_FA_DUMP1364/*1365* If firmware assisted dump is active firmware preserves1366* the contents of htab along with entire partition memory.1367* Clear the htab if firmware assisted dump is active so1368* that we dont end up using old mappings.1369*/1370if (is_fadump_active() && mmu_hash_ops.hpte_clear_all)1371mmu_hash_ops.hpte_clear_all();1372#endif1373} else {13741375table = memblock_phys_alloc_range(htab_size_bytes,1376htab_size_bytes,1377MEMBLOCK_LOW_LIMIT, limit);1378if (!table)1379panic("ERROR: Failed to allocate %pa bytes below %pa\n",1380&htab_size_bytes, &limit);13811382DBG("Hash table allocated at %lx, size: %lx\n", table,1383htab_size_bytes);13841385htab_address = __va(table);13861387/* htab absolute addr + encoded htabsize */1388_SDR1 = table + __ilog2(htab_size_bytes) - 18;13891390/* Initialize the HPT with no entries */1391memset((void *)table, 0, htab_size_bytes);13921393if (!cpu_has_feature(CPU_FTR_ARCH_300))1394/* Set SDR1 */1395mtspr(SPRN_SDR1, _SDR1);1396else1397hash_init_partition_table(table, htab_size_bytes);1398}13991400prot = pgprot_val(PAGE_KERNEL);14011402hash_debug_pagealloc_alloc_slots();1403hash_kfence_alloc_pool();1404/* create bolted the linear mapping in the hash table */1405for_each_mem_range(i, &base, &end) {1406size = end - base;1407base = (unsigned long)__va(base);14081409pr_debug("creating mapping for region: 0x%pa..0x%pa (prot: %lx)\n",1410&base, &size, prot);14111412if ((base + size) >= H_VMALLOC_START) {1413pr_warn("Outside the supported range\n");1414continue;1415}14161417BUG_ON(htab_bolt_mapping(base, base + size, __pa(base),1418prot, mmu_linear_psize, mmu_kernel_ssize));14191420update_page_count(mmu_linear_psize, size >> pshift);1421}1422hash_kfence_map_pool();1423memblock_set_current_limit(MEMBLOCK_ALLOC_ANYWHERE);14241425/*1426* If we have a memory_limit and we've allocated TCEs then we need to1427* explicitly map the TCE area at the top of RAM. We also cope with the1428* case that the TCEs start below memory_limit.1429* tce_alloc_start/end are 16MB aligned so the mapping should work1430* for either 4K or 16MB pages.1431*/1432if (tce_alloc_start) {1433tce_alloc_start = (unsigned long)__va(tce_alloc_start);1434tce_alloc_end = (unsigned long)__va(tce_alloc_end);14351436if (base + size >= tce_alloc_start)1437tce_alloc_start = base + size + 1;14381439BUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,1440__pa(tce_alloc_start), prot,1441mmu_linear_psize, mmu_kernel_ssize));1442update_page_count(mmu_linear_psize,1443(tce_alloc_end - tce_alloc_start) >> pshift);1444}144514461447DBG(" <- htab_initialize()\n");1448}1449#undef KB1450#undef MB14511452void __init hash__early_init_devtree(void)1453{1454/* Initialize segment sizes */1455of_scan_flat_dt(htab_dt_scan_seg_sizes, NULL);14561457/* Initialize page sizes */1458htab_scan_page_sizes();1459}14601461static struct hash_mm_context init_hash_mm_context;1462void __init hash__early_init_mmu(void)1463{1464#ifndef CONFIG_PPC_64K_PAGES1465/*1466* We have code in __hash_page_4K() and elsewhere, which assumes it can1467* do the following:1468* new_pte |= (slot << H_PAGE_F_GIX_SHIFT) & (H_PAGE_F_SECOND | H_PAGE_F_GIX);1469*1470* Where the slot number is between 0-15, and values of 8-15 indicate1471* the secondary bucket. For that code to work H_PAGE_F_SECOND and1472* H_PAGE_F_GIX must occupy four contiguous bits in the PTE, and1473* H_PAGE_F_SECOND must be placed above H_PAGE_F_GIX. Assert that here1474* with a BUILD_BUG_ON().1475*/1476BUILD_BUG_ON(H_PAGE_F_SECOND != (1ul << (H_PAGE_F_GIX_SHIFT + 3)));1477#endif /* CONFIG_PPC_64K_PAGES */14781479htab_init_page_sizes();14801481/*1482* initialize page table size1483*/1484__pte_frag_nr = H_PTE_FRAG_NR;1485__pte_frag_size_shift = H_PTE_FRAG_SIZE_SHIFT;1486__pmd_frag_nr = H_PMD_FRAG_NR;1487__pmd_frag_size_shift = H_PMD_FRAG_SIZE_SHIFT;14881489__pte_index_size = H_PTE_INDEX_SIZE;1490__pmd_index_size = H_PMD_INDEX_SIZE;1491__pud_index_size = H_PUD_INDEX_SIZE;1492__pgd_index_size = H_PGD_INDEX_SIZE;1493__pud_cache_index = H_PUD_CACHE_INDEX;1494__pte_table_size = H_PTE_TABLE_SIZE;1495__pmd_table_size = H_PMD_TABLE_SIZE;1496__pud_table_size = H_PUD_TABLE_SIZE;1497__pgd_table_size = H_PGD_TABLE_SIZE;1498__pmd_val_bits = HASH_PMD_VAL_BITS;1499__pud_val_bits = HASH_PUD_VAL_BITS;1500__pgd_val_bits = HASH_PGD_VAL_BITS;15011502__kernel_virt_start = H_KERN_VIRT_START;1503__vmalloc_start = H_VMALLOC_START;1504__vmalloc_end = H_VMALLOC_END;1505__kernel_io_start = H_KERN_IO_START;1506__kernel_io_end = H_KERN_IO_END;1507vmemmap = (struct page *)H_VMEMMAP_START;1508ioremap_bot = IOREMAP_BASE;15091510#ifdef CONFIG_PCI1511pci_io_base = ISA_IO_BASE;1512#endif15131514/* Select appropriate backend */1515if (firmware_has_feature(FW_FEATURE_PS3_LV1))1516ps3_early_mm_init();1517else if (firmware_has_feature(FW_FEATURE_LPAR))1518hpte_init_pseries();1519else if (IS_ENABLED(CONFIG_PPC_HASH_MMU_NATIVE))1520hpte_init_native();15211522if (!mmu_hash_ops.hpte_insert)1523panic("hash__early_init_mmu: No MMU hash ops defined!\n");15241525/*1526* Initialize the MMU Hash table and create the linear mapping1527* of memory. Has to be done before SLB initialization as this is1528* currently where the page size encoding is obtained.1529*/1530htab_initialize();15311532init_mm.context.hash_context = &init_hash_mm_context;1533mm_ctx_set_slb_addr_limit(&init_mm.context, SLB_ADDR_LIMIT_DEFAULT);15341535pr_info("Initializing hash mmu with SLB\n");1536/* Initialize SLB management */1537slb_initialize();15381539if (cpu_has_feature(CPU_FTR_ARCH_206)1540&& cpu_has_feature(CPU_FTR_HVMODE))1541tlbiel_all();1542}15431544#ifdef CONFIG_SMP1545void hash__early_init_mmu_secondary(void)1546{1547/* Initialize hash table for that CPU */1548if (!firmware_has_feature(FW_FEATURE_LPAR)) {15491550if (!cpu_has_feature(CPU_FTR_ARCH_300))1551mtspr(SPRN_SDR1, _SDR1);1552else1553set_ptcr_when_no_uv(__pa(partition_tb) |1554(PATB_SIZE_SHIFT - 12));1555}1556/* Initialize SLB */1557slb_initialize();15581559if (cpu_has_feature(CPU_FTR_ARCH_206)1560&& cpu_has_feature(CPU_FTR_HVMODE))1561tlbiel_all();15621563#ifdef CONFIG_PPC_MEM_KEYS1564if (mmu_has_feature(MMU_FTR_PKEY))1565mtspr(SPRN_UAMOR, default_uamor);1566#endif1567}1568#endif /* CONFIG_SMP */15691570/*1571* Called by asm hashtable.S for doing lazy icache flush1572*/1573unsigned int hash_page_do_lazy_icache(unsigned int pp, pte_t pte, int trap)1574{1575struct folio *folio;15761577if (!pfn_valid(pte_pfn(pte)))1578return pp;15791580folio = page_folio(pte_page(pte));15811582/* page is dirty */1583if (!test_bit(PG_dcache_clean, &folio->flags.f) &&1584!folio_test_reserved(folio)) {1585if (trap == INTERRUPT_INST_STORAGE) {1586flush_dcache_icache_folio(folio);1587set_bit(PG_dcache_clean, &folio->flags.f);1588} else1589pp |= HPTE_R_N;1590}1591return pp;1592}15931594static unsigned int get_paca_psize(unsigned long addr)1595{1596unsigned char *psizes;1597unsigned long index, mask_index;15981599if (addr < SLICE_LOW_TOP) {1600psizes = get_paca()->mm_ctx_low_slices_psize;1601index = GET_LOW_SLICE_INDEX(addr);1602} else {1603psizes = get_paca()->mm_ctx_high_slices_psize;1604index = GET_HIGH_SLICE_INDEX(addr);1605}1606mask_index = index & 0x1;1607return (psizes[index >> 1] >> (mask_index * 4)) & 0xF;1608}160916101611/*1612* Demote a segment to using 4k pages.1613* For now this makes the whole process use 4k pages.1614*/1615#ifdef CONFIG_PPC_64K_PAGES1616void demote_segment_4k(struct mm_struct *mm, unsigned long addr)1617{1618if (get_slice_psize(mm, addr) == MMU_PAGE_4K)1619return;1620slice_set_range_psize(mm, addr, 1, MMU_PAGE_4K);1621#ifdef CONFIG_SPU_BASE1622spu_flush_all_slbs(mm);1623#endif1624if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {16251626copy_mm_to_paca(mm);1627slb_flush_and_restore_bolted();1628}1629}1630#endif /* CONFIG_PPC_64K_PAGES */16311632#ifdef CONFIG_PPC_SUBPAGE_PROT1633/*1634* This looks up a 2-bit protection code for a 4k subpage of a 64k page.1635* Userspace sets the subpage permissions using the subpage_prot system call.1636*1637* Result is 0: full permissions, _PAGE_RW: read-only,1638* _PAGE_RWX: no access.1639*/1640static int subpage_protection(struct mm_struct *mm, unsigned long ea)1641{1642struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context);1643u32 spp = 0;1644u32 **sbpm, *sbpp;16451646if (!spt)1647return 0;16481649if (ea >= spt->maxaddr)1650return 0;1651if (ea < 0x100000000UL) {1652/* addresses below 4GB use spt->low_prot */1653sbpm = spt->low_prot;1654} else {1655sbpm = spt->protptrs[ea >> SBP_L3_SHIFT];1656if (!sbpm)1657return 0;1658}1659sbpp = sbpm[(ea >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)];1660if (!sbpp)1661return 0;1662spp = sbpp[(ea >> PAGE_SHIFT) & (SBP_L1_COUNT - 1)];16631664/* extract 2-bit bitfield for this 4k subpage */1665spp >>= 30 - 2 * ((ea >> 12) & 0xf);16661667/*1668* 0 -> full permission1669* 1 -> Read only1670* 2 -> no access.1671* We return the flag that need to be cleared.1672*/1673spp = ((spp & 2) ? _PAGE_RWX : 0) | ((spp & 1) ? _PAGE_WRITE : 0);1674return spp;1675}16761677#else /* CONFIG_PPC_SUBPAGE_PROT */1678static inline int subpage_protection(struct mm_struct *mm, unsigned long ea)1679{1680return 0;1681}1682#endif16831684void hash_failure_debug(unsigned long ea, unsigned long access,1685unsigned long vsid, unsigned long trap,1686int ssize, int psize, int lpsize, unsigned long pte)1687{1688if (!printk_ratelimit())1689return;1690pr_info("mm: Hashing failure ! EA=0x%lx access=0x%lx current=%s\n",1691ea, access, current->comm);1692pr_info(" trap=0x%lx vsid=0x%lx ssize=%d base psize=%d psize %d pte=0x%lx\n",1693trap, vsid, ssize, psize, lpsize, pte);1694}16951696static void check_paca_psize(unsigned long ea, struct mm_struct *mm,1697int psize, bool user_region)1698{1699if (user_region) {1700if (psize != get_paca_psize(ea)) {1701copy_mm_to_paca(mm);1702slb_flush_and_restore_bolted();1703}1704} else if (get_paca()->vmalloc_sllp !=1705mmu_psize_defs[mmu_vmalloc_psize].sllp) {1706get_paca()->vmalloc_sllp =1707mmu_psize_defs[mmu_vmalloc_psize].sllp;1708slb_vmalloc_update();1709}1710}17111712/*1713* Result code is:1714* 0 - handled1715* 1 - normal page fault1716* -1 - critical hash insertion error1717* -2 - access not permitted by subpage protection mechanism1718*/1719int hash_page_mm(struct mm_struct *mm, unsigned long ea,1720unsigned long access, unsigned long trap,1721unsigned long flags)1722{1723bool is_thp;1724pgd_t *pgdir;1725unsigned long vsid;1726pte_t *ptep;1727unsigned hugeshift;1728int rc, user_region = 0;1729int psize, ssize;17301731DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n",1732ea, access, trap);1733trace_hash_fault(ea, access, trap);17341735/* Get region & vsid */1736switch (get_region_id(ea)) {1737case USER_REGION_ID:1738user_region = 1;1739if (! mm) {1740DBG_LOW(" user region with no mm !\n");1741rc = 1;1742goto bail;1743}1744psize = get_slice_psize(mm, ea);1745ssize = user_segment_size(ea);1746vsid = get_user_vsid(&mm->context, ea, ssize);1747break;1748case VMALLOC_REGION_ID:1749vsid = get_kernel_vsid(ea, mmu_kernel_ssize);1750psize = mmu_vmalloc_psize;1751ssize = mmu_kernel_ssize;1752flags |= HPTE_USE_KERNEL_KEY;1753break;17541755case IO_REGION_ID:1756vsid = get_kernel_vsid(ea, mmu_kernel_ssize);1757psize = mmu_io_psize;1758ssize = mmu_kernel_ssize;1759flags |= HPTE_USE_KERNEL_KEY;1760break;1761default:1762/*1763* Not a valid range1764* Send the problem up to do_page_fault()1765*/1766rc = 1;1767goto bail;1768}1769DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid);17701771/* Bad address. */1772if (!vsid) {1773DBG_LOW("Bad address!\n");1774rc = 1;1775goto bail;1776}1777/* Get pgdir */1778pgdir = mm->pgd;1779if (pgdir == NULL) {1780rc = 1;1781goto bail;1782}17831784/* Check CPU locality */1785if (user_region && mm_is_thread_local(mm))1786flags |= HPTE_LOCAL_UPDATE;17871788#ifndef CONFIG_PPC_64K_PAGES1789/*1790* If we use 4K pages and our psize is not 4K, then we might1791* be hitting a special driver mapping, and need to align the1792* address before we fetch the PTE.1793*1794* It could also be a hugepage mapping, in which case this is1795* not necessary, but it's not harmful, either.1796*/1797if (psize != MMU_PAGE_4K)1798ea &= ~((1ul << mmu_psize_defs[psize].shift) - 1);1799#endif /* CONFIG_PPC_64K_PAGES */18001801/* Get PTE and page size from page tables */1802ptep = find_linux_pte(pgdir, ea, &is_thp, &hugeshift);1803if (ptep == NULL || !pte_present(*ptep)) {1804DBG_LOW(" no PTE !\n");1805rc = 1;1806goto bail;1807}18081809if (IS_ENABLED(CONFIG_PPC_4K_PAGES) && !radix_enabled()) {1810if (hugeshift == PMD_SHIFT && psize == MMU_PAGE_16M)1811hugeshift = mmu_psize_defs[MMU_PAGE_16M].shift;1812if (hugeshift == PUD_SHIFT && psize == MMU_PAGE_16G)1813hugeshift = mmu_psize_defs[MMU_PAGE_16G].shift;1814}18151816/*1817* Add _PAGE_PRESENT to the required access perm. If there are parallel1818* updates to the pte that can possibly clear _PAGE_PTE, catch that too.1819*1820* We can safely use the return pte address in rest of the function1821* because we do set H_PAGE_BUSY which prevents further updates to pte1822* from generic code.1823*/1824access |= _PAGE_PRESENT | _PAGE_PTE;18251826/*1827* Pre-check access permissions (will be re-checked atomically1828* in __hash_page_XX but this pre-check is a fast path1829*/1830if (!check_pte_access(access, pte_val(*ptep))) {1831DBG_LOW(" no access !\n");1832rc = 1;1833goto bail;1834}18351836if (hugeshift) {1837if (is_thp)1838rc = __hash_page_thp(ea, access, vsid, (pmd_t *)ptep,1839trap, flags, ssize, psize);1840#ifdef CONFIG_HUGETLB_PAGE1841else1842rc = __hash_page_huge(ea, access, vsid, ptep, trap,1843flags, ssize, hugeshift, psize);1844#else1845else {1846/*1847* if we have hugeshift, and is not transhuge with1848* hugetlb disabled, something is really wrong.1849*/1850rc = 1;1851WARN_ON(1);1852}1853#endif1854if (current->mm == mm)1855check_paca_psize(ea, mm, psize, user_region);18561857goto bail;1858}18591860#ifndef CONFIG_PPC_64K_PAGES1861DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep));1862#else1863DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep),1864pte_val(*(ptep + PTRS_PER_PTE)));1865#endif1866/* Do actual hashing */1867#ifdef CONFIG_PPC_64K_PAGES1868/* If H_PAGE_4K_PFN is set, make sure this is a 4k segment */1869if ((pte_val(*ptep) & H_PAGE_4K_PFN) && psize == MMU_PAGE_64K) {1870demote_segment_4k(mm, ea);1871psize = MMU_PAGE_4K;1872}18731874/*1875* If this PTE is non-cacheable and we have restrictions on1876* using non cacheable large pages, then we switch to 4k1877*/1878if (mmu_ci_restrictions && psize == MMU_PAGE_64K && pte_ci(*ptep)) {1879if (user_region) {1880demote_segment_4k(mm, ea);1881psize = MMU_PAGE_4K;1882} else if (ea < VMALLOC_END) {1883/*1884* some driver did a non-cacheable mapping1885* in vmalloc space, so switch vmalloc1886* to 4k pages1887*/1888pr_alert("Reducing vmalloc segment "1889"to 4kB pages because of "1890"non-cacheable mapping\n");1891psize = mmu_vmalloc_psize = MMU_PAGE_4K;1892#ifdef CONFIG_SPU_BASE1893spu_flush_all_slbs(mm);1894#endif1895}1896}18971898#endif /* CONFIG_PPC_64K_PAGES */18991900if (current->mm == mm)1901check_paca_psize(ea, mm, psize, user_region);19021903#ifdef CONFIG_PPC_64K_PAGES1904if (psize == MMU_PAGE_64K)1905rc = __hash_page_64K(ea, access, vsid, ptep, trap,1906flags, ssize);1907else1908#endif /* CONFIG_PPC_64K_PAGES */1909{1910int spp = subpage_protection(mm, ea);1911if (access & spp)1912rc = -2;1913else1914rc = __hash_page_4K(ea, access, vsid, ptep, trap,1915flags, ssize, spp);1916}19171918/*1919* Dump some info in case of hash insertion failure, they should1920* never happen so it is really useful to know if/when they do1921*/1922if (rc == -1)1923hash_failure_debug(ea, access, vsid, trap, ssize, psize,1924psize, pte_val(*ptep));1925#ifndef CONFIG_PPC_64K_PAGES1926DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep));1927#else1928DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep),1929pte_val(*(ptep + PTRS_PER_PTE)));1930#endif1931DBG_LOW(" -> rc=%d\n", rc);19321933bail:1934return rc;1935}1936EXPORT_SYMBOL_GPL(hash_page_mm);19371938int hash_page(unsigned long ea, unsigned long access, unsigned long trap,1939unsigned long dsisr)1940{1941unsigned long flags = 0;1942struct mm_struct *mm = current->mm;19431944if ((get_region_id(ea) == VMALLOC_REGION_ID) ||1945(get_region_id(ea) == IO_REGION_ID))1946mm = &init_mm;19471948if (dsisr & DSISR_NOHPTE)1949flags |= HPTE_NOHPTE_UPDATE;19501951return hash_page_mm(mm, ea, access, trap, flags);1952}1953EXPORT_SYMBOL_GPL(hash_page);19541955DEFINE_INTERRUPT_HANDLER(do_hash_fault)1956{1957unsigned long ea = regs->dar;1958unsigned long dsisr = regs->dsisr;1959unsigned long access = _PAGE_PRESENT | _PAGE_READ;1960unsigned long flags = 0;1961struct mm_struct *mm;1962unsigned int region_id;1963long err;19641965if (unlikely(dsisr & (DSISR_BAD_FAULT_64S | DSISR_KEYFAULT))) {1966hash__do_page_fault(regs);1967return;1968}19691970region_id = get_region_id(ea);1971if ((region_id == VMALLOC_REGION_ID) || (region_id == IO_REGION_ID))1972mm = &init_mm;1973else1974mm = current->mm;19751976if (dsisr & DSISR_NOHPTE)1977flags |= HPTE_NOHPTE_UPDATE;19781979if (dsisr & DSISR_ISSTORE)1980access |= _PAGE_WRITE;1981/*1982* We set _PAGE_PRIVILEGED only when1983* kernel mode access kernel space.1984*1985* _PAGE_PRIVILEGED is NOT set1986* 1) when kernel mode access user space1987* 2) user space access kernel space.1988*/1989access |= _PAGE_PRIVILEGED;1990if (user_mode(regs) || (region_id == USER_REGION_ID))1991access &= ~_PAGE_PRIVILEGED;19921993if (TRAP(regs) == INTERRUPT_INST_STORAGE)1994access |= _PAGE_EXEC;19951996err = hash_page_mm(mm, ea, access, TRAP(regs), flags);1997if (unlikely(err < 0)) {1998// failed to insert a hash PTE due to an hypervisor error1999if (user_mode(regs)) {2000if (IS_ENABLED(CONFIG_PPC_SUBPAGE_PROT) && err == -2)2001_exception(SIGSEGV, regs, SEGV_ACCERR, ea);2002else2003_exception(SIGBUS, regs, BUS_ADRERR, ea);2004} else {2005bad_page_fault(regs, SIGBUS);2006}2007err = 0;20082009} else if (err) {2010hash__do_page_fault(regs);2011}2012}20132014static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)2015{2016int psize = get_slice_psize(mm, ea);20172018/* We only prefault standard pages for now */2019if (unlikely(psize != mm_ctx_user_psize(&mm->context)))2020return false;20212022/*2023* Don't prefault if subpage protection is enabled for the EA.2024*/2025if (unlikely((psize == MMU_PAGE_4K) && subpage_protection(mm, ea)))2026return false;20272028return true;2029}20302031static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,2032bool is_exec, unsigned long trap)2033{2034unsigned long vsid;2035pgd_t *pgdir;2036int rc, ssize, update_flags = 0;2037unsigned long access = _PAGE_PRESENT | _PAGE_READ | (is_exec ? _PAGE_EXEC : 0);2038unsigned long flags;20392040BUG_ON(get_region_id(ea) != USER_REGION_ID);20412042if (!should_hash_preload(mm, ea))2043return;20442045DBG_LOW("hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,"2046" trap=%lx\n", mm, mm->pgd, ea, access, trap);20472048/* Get Linux PTE if available */2049pgdir = mm->pgd;2050if (pgdir == NULL)2051return;20522053/* Get VSID */2054ssize = user_segment_size(ea);2055vsid = get_user_vsid(&mm->context, ea, ssize);2056if (!vsid)2057return;20582059#ifdef CONFIG_PPC_64K_PAGES2060/* If either H_PAGE_4K_PFN or cache inhibited is set (and we are on2061* a 64K kernel), then we don't preload, hash_page() will take2062* care of it once we actually try to access the page.2063* That way we don't have to duplicate all of the logic for segment2064* page size demotion here2065* Called with PTL held, hence can be sure the value won't change in2066* between.2067*/2068if ((pte_val(*ptep) & H_PAGE_4K_PFN) || pte_ci(*ptep))2069return;2070#endif /* CONFIG_PPC_64K_PAGES */20712072/*2073* __hash_page_* must run with interrupts off, including PMI interrupts2074* off, as it sets the H_PAGE_BUSY bit.2075*2076* It's otherwise possible for perf interrupts to hit at any time and2077* may take a hash fault reading the user stack, which could take a2078* hash miss and deadlock on the same H_PAGE_BUSY bit.2079*2080* Interrupts must also be off for the duration of the2081* mm_is_thread_local test and update, to prevent preempt running the2082* mm on another CPU (XXX: this may be racy vs kthread_use_mm).2083*/2084powerpc_local_irq_pmu_save(flags);20852086/* Is that local to this CPU ? */2087if (mm_is_thread_local(mm))2088update_flags |= HPTE_LOCAL_UPDATE;20892090/* Hash it in */2091#ifdef CONFIG_PPC_64K_PAGES2092if (mm_ctx_user_psize(&mm->context) == MMU_PAGE_64K)2093rc = __hash_page_64K(ea, access, vsid, ptep, trap,2094update_flags, ssize);2095else2096#endif /* CONFIG_PPC_64K_PAGES */2097rc = __hash_page_4K(ea, access, vsid, ptep, trap, update_flags,2098ssize, subpage_protection(mm, ea));20992100/* Dump some info in case of hash insertion failure, they should2101* never happen so it is really useful to know if/when they do2102*/2103if (rc == -1)2104hash_failure_debug(ea, access, vsid, trap, ssize,2105mm_ctx_user_psize(&mm->context),2106mm_ctx_user_psize(&mm->context),2107pte_val(*ptep));21082109powerpc_local_irq_pmu_restore(flags);2110}21112112/*2113* This is called at the end of handling a user page fault, when the2114* fault has been handled by updating a PTE in the linux page tables.2115* We use it to preload an HPTE into the hash table corresponding to2116* the updated linux PTE.2117*2118* This must always be called with the pte lock held.2119*/2120void __update_mmu_cache(struct vm_area_struct *vma, unsigned long address,2121pte_t *ptep)2122{2123/*2124* We don't need to worry about _PAGE_PRESENT here because we are2125* called with either mm->page_table_lock held or ptl lock held2126*/2127unsigned long trap;2128bool is_exec;21292130/* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */2131if (!pte_young(*ptep) || address >= TASK_SIZE)2132return;21332134/*2135* We try to figure out if we are coming from an instruction2136* access fault and pass that down to __hash_page so we avoid2137* double-faulting on execution of fresh text. We have to test2138* for regs NULL since init will get here first thing at boot.2139*2140* We also avoid filling the hash if not coming from a fault.2141*/21422143trap = current->thread.regs ? TRAP(current->thread.regs) : 0UL;2144switch (trap) {2145case 0x300:2146is_exec = false;2147break;2148case 0x400:2149is_exec = true;2150break;2151default:2152return;2153}21542155hash_preload(vma->vm_mm, ptep, address, is_exec, trap);2156}21572158#ifdef CONFIG_PPC_TRANSACTIONAL_MEM2159static inline void tm_flush_hash_page(int local)2160{2161/*2162* Transactions are not aborted by tlbiel, only tlbie. Without, syncing a2163* page back to a block device w/PIO could pick up transactional data2164* (bad!) so we force an abort here. Before the sync the page will be2165* made read-only, which will flush_hash_page. BIG ISSUE here: if the2166* kernel uses a page from userspace without unmapping it first, it may2167* see the speculated version.2168*/2169if (local && cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&2170MSR_TM_ACTIVE(current->thread.regs->msr)) {2171tm_enable();2172tm_abort(TM_CAUSE_TLBI);2173}2174}2175#else2176static inline void tm_flush_hash_page(int local)2177{2178}2179#endif21802181/*2182* Return the global hash slot, corresponding to the given PTE, which contains2183* the HPTE.2184*/2185unsigned long pte_get_hash_gslot(unsigned long vpn, unsigned long shift,2186int ssize, real_pte_t rpte, unsigned int subpg_index)2187{2188unsigned long hash, gslot, hidx;21892190hash = hpt_hash(vpn, shift, ssize);2191hidx = __rpte_to_hidx(rpte, subpg_index);2192if (hidx & _PTEIDX_SECONDARY)2193hash = ~hash;2194gslot = (hash & htab_hash_mask) * HPTES_PER_GROUP;2195gslot += hidx & _PTEIDX_GROUP_IX;2196return gslot;2197}21982199void flush_hash_page(unsigned long vpn, real_pte_t pte, int psize, int ssize,2200unsigned long flags)2201{2202unsigned long index, shift, gslot;2203int local = flags & HPTE_LOCAL_UPDATE;22042205DBG_LOW("flush_hash_page(vpn=%016lx)\n", vpn);2206pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {2207gslot = pte_get_hash_gslot(vpn, shift, ssize, pte, index);2208DBG_LOW(" sub %ld: gslot=%lx\n", index, gslot);2209/*2210* We use same base page size and actual psize, because we don't2211* use these functions for hugepage2212*/2213mmu_hash_ops.hpte_invalidate(gslot, vpn, psize, psize,2214ssize, local);2215} pte_iterate_hashed_end();22162217tm_flush_hash_page(local);2218}22192220#ifdef CONFIG_TRANSPARENT_HUGEPAGE2221void flush_hash_hugepage(unsigned long vsid, unsigned long addr,2222pmd_t *pmdp, unsigned int psize, int ssize,2223unsigned long flags)2224{2225int i, max_hpte_count, valid;2226unsigned long s_addr;2227unsigned char *hpte_slot_array;2228unsigned long hidx, shift, vpn, hash, slot;2229int local = flags & HPTE_LOCAL_UPDATE;22302231s_addr = addr & HPAGE_PMD_MASK;2232hpte_slot_array = get_hpte_slot_array(pmdp);2233/*2234* IF we try to do a HUGE PTE update after a withdraw is done.2235* we will find the below NULL. This happens when we do2236* split_huge_pmd2237*/2238if (!hpte_slot_array)2239return;22402241if (mmu_hash_ops.hugepage_invalidate) {2242mmu_hash_ops.hugepage_invalidate(vsid, s_addr, hpte_slot_array,2243psize, ssize, local);2244goto tm_abort;2245}2246/*2247* No bluk hpte removal support, invalidate each entry2248*/2249shift = mmu_psize_defs[psize].shift;2250max_hpte_count = HPAGE_PMD_SIZE >> shift;2251for (i = 0; i < max_hpte_count; i++) {2252/*2253* 8 bits per each hpte entries2254* 000| [ secondary group (one bit) | hidx (3 bits) | valid bit]2255*/2256valid = hpte_valid(hpte_slot_array, i);2257if (!valid)2258continue;2259hidx = hpte_hash_index(hpte_slot_array, i);22602261/* get the vpn */2262addr = s_addr + (i * (1ul << shift));2263vpn = hpt_vpn(addr, vsid, ssize);2264hash = hpt_hash(vpn, shift, ssize);2265if (hidx & _PTEIDX_SECONDARY)2266hash = ~hash;22672268slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;2269slot += hidx & _PTEIDX_GROUP_IX;2270mmu_hash_ops.hpte_invalidate(slot, vpn, psize,2271MMU_PAGE_16M, ssize, local);2272}2273tm_abort:2274tm_flush_hash_page(local);2275}2276#endif /* CONFIG_TRANSPARENT_HUGEPAGE */22772278void flush_hash_range(unsigned long number, int local)2279{2280if (mmu_hash_ops.flush_hash_range)2281mmu_hash_ops.flush_hash_range(number, local);2282else {2283int i;2284struct ppc64_tlb_batch *batch =2285this_cpu_ptr(&ppc64_tlb_batch);22862287for (i = 0; i < number; i++)2288flush_hash_page(batch->vpn[i], batch->pte[i],2289batch->psize, batch->ssize, local);2290}2291}22922293long hpte_insert_repeating(unsigned long hash, unsigned long vpn,2294unsigned long pa, unsigned long rflags,2295unsigned long vflags, int psize, int ssize)2296{2297unsigned long hpte_group;2298long slot;22992300repeat:2301hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;23022303/* Insert into the hash table, primary slot */2304slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags, vflags,2305psize, psize, ssize);23062307/* Primary is full, try the secondary */2308if (unlikely(slot == -1)) {2309hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;2310slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags,2311vflags | HPTE_V_SECONDARY,2312psize, psize, ssize);2313if (slot == -1) {2314if (mftb() & 0x1)2315hpte_group = (hash & htab_hash_mask) *2316HPTES_PER_GROUP;23172318mmu_hash_ops.hpte_remove(hpte_group);2319goto repeat;2320}2321}23222323return slot;2324}23252326void hpt_clear_stress(void)2327{2328int cpu = raw_smp_processor_id();2329int g;23302331for (g = 0; g < stress_nr_groups(); g++) {2332unsigned long last_group;2333last_group = stress_hpt_struct[cpu].last_group[g];23342335if (last_group != -1UL) {2336int i;2337for (i = 0; i < HPTES_PER_GROUP; i++) {2338if (mmu_hash_ops.hpte_remove(last_group) == -1)2339break;2340}2341stress_hpt_struct[cpu].last_group[g] = -1;2342}2343}2344}23452346void hpt_do_stress(unsigned long ea, unsigned long hpte_group)2347{2348unsigned long last_group;2349int cpu = raw_smp_processor_id();23502351last_group = stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1];2352if (hpte_group == last_group)2353return;23542355if (last_group != -1UL) {2356int i;2357/*2358* Concurrent CPUs might be inserting into this group, so2359* give up after a number of iterations, to prevent a live2360* lock.2361*/2362for (i = 0; i < HPTES_PER_GROUP; i++) {2363if (mmu_hash_ops.hpte_remove(last_group) == -1)2364break;2365}2366stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1] = -1;2367}23682369if (ea >= PAGE_OFFSET) {2370/*2371* We would really like to prefetch to get the TLB loaded, then2372* remove the PTE before returning from fault interrupt, to2373* increase the hash fault rate.2374*2375* Unfortunately QEMU TCG does not model the TLB in a way that2376* makes this possible, and systemsim (mambo) emulator does not2377* bring in TLBs with prefetches (although loads/stores do2378* work for non-CI PTEs).2379*2380* So remember this PTE and clear it on the next hash fault.2381*/2382memmove(&stress_hpt_struct[cpu].last_group[1],2383&stress_hpt_struct[cpu].last_group[0],2384(stress_nr_groups() - 1) * sizeof(unsigned long));2385stress_hpt_struct[cpu].last_group[0] = hpte_group;2386}2387}23882389void hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,2390phys_addr_t first_memblock_size)2391{2392/*2393* We don't currently support the first MEMBLOCK not mapping 02394* physical on those processors2395*/2396BUG_ON(first_memblock_base != 0);23972398/*2399* On virtualized systems the first entry is our RMA region aka VRMA,2400* non-virtualized 64-bit hash MMU systems don't have a limitation2401* on real mode access.2402*2403* For guests on platforms before POWER9, we clamp the it limit to 1G2404* to avoid some funky things such as RTAS bugs etc...2405*2406* On POWER9 we limit to 1TB in case the host erroneously told us that2407* the RMA was >1TB. Effective address bits 0:23 are treated as zero2408* (meaning the access is aliased to zero i.e. addr = addr % 1TB)2409* for virtual real mode addressing and so it doesn't make sense to2410* have an area larger than 1TB as it can't be addressed.2411*/2412if (!early_cpu_has_feature(CPU_FTR_HVMODE)) {2413ppc64_rma_size = first_memblock_size;2414if (!early_cpu_has_feature(CPU_FTR_ARCH_300))2415ppc64_rma_size = min_t(u64, ppc64_rma_size, 0x40000000);2416else2417ppc64_rma_size = min_t(u64, ppc64_rma_size,24181UL << SID_SHIFT_1T);24192420/* Finally limit subsequent allocations */2421memblock_set_current_limit(ppc64_rma_size);2422} else {2423ppc64_rma_size = ULONG_MAX;2424}2425}24262427#ifdef CONFIG_DEBUG_FS24282429static int hpt_order_get(void *data, u64 *val)2430{2431*val = ppc64_pft_size;2432return 0;2433}24342435static int hpt_order_set(void *data, u64 val)2436{2437int ret;24382439if (!mmu_hash_ops.resize_hpt)2440return -ENODEV;24412442cpus_read_lock();2443ret = mmu_hash_ops.resize_hpt(val);2444cpus_read_unlock();24452446return ret;2447}24482449DEFINE_DEBUGFS_ATTRIBUTE(fops_hpt_order, hpt_order_get, hpt_order_set, "%llu\n");24502451static int __init hash64_debugfs(void)2452{2453if (radix_enabled())2454return 0;2455debugfs_create_file("hpt_order", 0600, arch_debugfs_dir, NULL,2456&fops_hpt_order);2457return 0;2458}2459machine_device_initcall(pseries, hash64_debugfs);2460#endif /* CONFIG_DEBUG_FS */24612462void __init print_system_hash_info(void)2463{2464pr_info("ppc64_pft_size = 0x%llx\n", ppc64_pft_size);24652466if (htab_hash_mask)2467pr_info("htab_hash_mask = 0x%lx\n", htab_hash_mask);2468}24692470unsigned long arch_randomize_brk(struct mm_struct *mm)2471{2472/*2473* If we are using 1TB segments and we are allowed to randomise2474* the heap, we can put it above 1TB so it is backed by a 1TB2475* segment. Otherwise the heap will be in the bottom 1TB2476* which always uses 256MB segments and this may result in a2477* performance penalty.2478*/2479if (is_32bit_task())2480return randomize_page(mm->brk, SZ_32M);2481else if (!radix_enabled() && mmu_highuser_ssize == MMU_SEGSIZE_1T)2482return randomize_page(max_t(unsigned long, mm->brk, SZ_1T), SZ_1G);2483else2484return randomize_page(mm->brk, SZ_1G);2485}248624872488