Path: blob/master/arch/powerpc/mm/book3s64/hash_utils.c
26481 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/types.h>50#include <linux/uaccess.h>51#include <asm/machdep.h>52#include <asm/io.h>53#include <asm/eeh.h>54#include <asm/tlb.h>55#include <asm/cacheflush.h>56#include <asm/cputable.h>57#include <asm/sections.h>58#include <asm/spu.h>59#include <asm/udbg.h>60#include <asm/text-patching.h>61#include <asm/fadump.h>62#include <asm/firmware.h>63#include <asm/tm.h>64#include <asm/trace.h>65#include <asm/ps3.h>66#include <asm/pte-walk.h>67#include <asm/asm-prototypes.h>68#include <asm/ultravisor.h>69#include <asm/kfence.h>7071#include <mm/mmu_decl.h>7273#include "internal.h"747576#ifdef DEBUG77#define DBG(fmt...) udbg_printf(fmt)78#else79#define DBG(fmt...)80#endif8182#ifdef DEBUG_LOW83#define DBG_LOW(fmt...) udbg_printf(fmt)84#else85#define DBG_LOW(fmt...)86#endif8788#define KB (1024)89#define MB (1024*KB)90#define GB (1024L*MB)9192/*93* Note: pte --> Linux PTE94* HPTE --> PowerPC Hashed Page Table Entry95*96* Execution context:97* htab_initialize is called with the MMU off (of course), but98* the kernel has been copied down to zero so it can directly99* reference global data. At this point it is very difficult100* to print debug info.101*102*/103104static unsigned long _SDR1;105106u8 hpte_page_sizes[1 << LP_BITS];107EXPORT_SYMBOL_GPL(hpte_page_sizes);108109struct hash_pte *htab_address;110unsigned long htab_size_bytes;111unsigned long htab_hash_mask;112EXPORT_SYMBOL_GPL(htab_hash_mask);113int mmu_linear_psize = MMU_PAGE_4K;114EXPORT_SYMBOL_GPL(mmu_linear_psize);115int mmu_virtual_psize = MMU_PAGE_4K;116int mmu_vmalloc_psize = MMU_PAGE_4K;117EXPORT_SYMBOL_GPL(mmu_vmalloc_psize);118int mmu_io_psize = MMU_PAGE_4K;119int mmu_kernel_ssize = MMU_SEGSIZE_256M;120EXPORT_SYMBOL_GPL(mmu_kernel_ssize);121int mmu_highuser_ssize = MMU_SEGSIZE_256M;122u16 mmu_slb_size = 64;123EXPORT_SYMBOL_GPL(mmu_slb_size);124#ifdef CONFIG_PPC_64K_PAGES125int mmu_ci_restrictions;126#endif127struct mmu_hash_ops mmu_hash_ops __ro_after_init;128EXPORT_SYMBOL(mmu_hash_ops);129130/*131* These are definitions of page sizes arrays to be used when none132* is provided by the firmware.133*/134135/*136* Fallback (4k pages only)137*/138static struct mmu_psize_def mmu_psize_defaults[] = {139[MMU_PAGE_4K] = {140.shift = 12,141.sllp = 0,142.penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},143.avpnm = 0,144.tlbiel = 0,145},146};147148/*149* POWER4, GPUL, POWER5150*151* Support for 16Mb large pages152*/153static struct mmu_psize_def mmu_psize_defaults_gp[] = {154[MMU_PAGE_4K] = {155.shift = 12,156.sllp = 0,157.penc = {[MMU_PAGE_4K] = 0, [1 ... MMU_PAGE_COUNT - 1] = -1},158.avpnm = 0,159.tlbiel = 1,160},161[MMU_PAGE_16M] = {162.shift = 24,163.sllp = SLB_VSID_L,164.penc = {[0 ... MMU_PAGE_16M - 1] = -1, [MMU_PAGE_16M] = 0,165[MMU_PAGE_16M + 1 ... MMU_PAGE_COUNT - 1] = -1 },166.avpnm = 0x1UL,167.tlbiel = 0,168},169};170171static inline void tlbiel_hash_set_isa206(unsigned int set, unsigned int is)172{173unsigned long rb;174175rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));176177asm volatile("tlbiel %0" : : "r" (rb));178}179180/*181* tlbiel instruction for hash, set invalidation182* i.e., r=1 and is=01 or is=10 or is=11183*/184static __always_inline void tlbiel_hash_set_isa300(unsigned int set, unsigned int is,185unsigned int pid,186unsigned int ric, unsigned int prs)187{188unsigned long rb;189unsigned long rs;190unsigned int r = 0; /* hash format */191192rb = (set << PPC_BITLSHIFT(51)) | (is << PPC_BITLSHIFT(53));193rs = ((unsigned long)pid << PPC_BITLSHIFT(31));194195asm volatile(PPC_TLBIEL(%0, %1, %2, %3, %4)196: : "r"(rb), "r"(rs), "i"(ric), "i"(prs), "i"(r)197: "memory");198}199200201static void tlbiel_all_isa206(unsigned int num_sets, unsigned int is)202{203unsigned int set;204205asm volatile("ptesync": : :"memory");206207for (set = 0; set < num_sets; set++)208tlbiel_hash_set_isa206(set, is);209210ppc_after_tlbiel_barrier();211}212213static void tlbiel_all_isa300(unsigned int num_sets, unsigned int is)214{215unsigned int set;216217asm volatile("ptesync": : :"memory");218219/*220* Flush the partition table cache if this is HV mode.221*/222if (early_cpu_has_feature(CPU_FTR_HVMODE))223tlbiel_hash_set_isa300(0, is, 0, 2, 0);224225/*226* Now invalidate the process table cache. UPRT=0 HPT modes (what227* current hardware implements) do not use the process table, but228* add the flushes anyway.229*230* From ISA v3.0B p. 1078:231* The following forms are invalid.232* * PRS=1, R=0, and RIC!=2 (The only process-scoped233* HPT caching is of the Process Table.)234*/235tlbiel_hash_set_isa300(0, is, 0, 2, 1);236237/*238* Then flush the sets of the TLB proper. Hash mode uses239* partition scoped TLB translations, which may be flushed240* in !HV mode.241*/242for (set = 0; set < num_sets; set++)243tlbiel_hash_set_isa300(set, is, 0, 0, 0);244245ppc_after_tlbiel_barrier();246247asm volatile(PPC_ISA_3_0_INVALIDATE_ERAT "; isync" : : :"memory");248}249250void hash__tlbiel_all(unsigned int action)251{252unsigned int is;253254switch (action) {255case TLB_INVAL_SCOPE_GLOBAL:256is = 3;257break;258case TLB_INVAL_SCOPE_LPID:259is = 2;260break;261default:262BUG();263}264265if (early_cpu_has_feature(CPU_FTR_ARCH_300))266tlbiel_all_isa300(POWER9_TLB_SETS_HASH, is);267else if (early_cpu_has_feature(CPU_FTR_ARCH_207S))268tlbiel_all_isa206(POWER8_TLB_SETS, is);269else if (early_cpu_has_feature(CPU_FTR_ARCH_206))270tlbiel_all_isa206(POWER7_TLB_SETS, is);271else272WARN(1, "%s called on pre-POWER7 CPU\n", __func__);273}274275#if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)276static void kernel_map_linear_page(unsigned long vaddr, unsigned long idx,277u8 *slots, raw_spinlock_t *lock)278{279unsigned long hash;280unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);281unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);282unsigned long mode = htab_convert_pte_flags(pgprot_val(PAGE_KERNEL), HPTE_USE_KERNEL_KEY);283long ret;284285hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);286287/* Don't create HPTE entries for bad address */288if (!vsid)289return;290291if (slots[idx] & 0x80)292return;293294ret = hpte_insert_repeating(hash, vpn, __pa(vaddr), mode,295HPTE_V_BOLTED,296mmu_linear_psize, mmu_kernel_ssize);297298BUG_ON (ret < 0);299raw_spin_lock(lock);300BUG_ON(slots[idx] & 0x80);301slots[idx] = ret | 0x80;302raw_spin_unlock(lock);303}304305static void kernel_unmap_linear_page(unsigned long vaddr, unsigned long idx,306u8 *slots, raw_spinlock_t *lock)307{308unsigned long hash, hslot, slot;309unsigned long vsid = get_kernel_vsid(vaddr, mmu_kernel_ssize);310unsigned long vpn = hpt_vpn(vaddr, vsid, mmu_kernel_ssize);311312hash = hpt_hash(vpn, PAGE_SHIFT, mmu_kernel_ssize);313raw_spin_lock(lock);314if (!(slots[idx] & 0x80)) {315raw_spin_unlock(lock);316return;317}318hslot = slots[idx] & 0x7f;319slots[idx] = 0;320raw_spin_unlock(lock);321if (hslot & _PTEIDX_SECONDARY)322hash = ~hash;323slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;324slot += hslot & _PTEIDX_GROUP_IX;325mmu_hash_ops.hpte_invalidate(slot, vpn, mmu_linear_psize,326mmu_linear_psize,327mmu_kernel_ssize, 0);328}329#endif330331static inline bool hash_supports_debug_pagealloc(void)332{333unsigned long max_hash_count = ppc64_rma_size / 4;334unsigned long linear_map_count = memblock_end_of_DRAM() >> PAGE_SHIFT;335336if (!debug_pagealloc_enabled() || linear_map_count > max_hash_count)337return false;338return true;339}340341#ifdef CONFIG_DEBUG_PAGEALLOC342static u8 *linear_map_hash_slots;343static unsigned long linear_map_hash_count;344static DEFINE_RAW_SPINLOCK(linear_map_hash_lock);345static __init void hash_debug_pagealloc_alloc_slots(void)346{347if (!hash_supports_debug_pagealloc())348return;349350linear_map_hash_count = memblock_end_of_DRAM() >> PAGE_SHIFT;351linear_map_hash_slots = memblock_alloc_try_nid(352linear_map_hash_count, 1, MEMBLOCK_LOW_LIMIT,353ppc64_rma_size, NUMA_NO_NODE);354if (!linear_map_hash_slots)355panic("%s: Failed to allocate %lu bytes max_addr=%pa\n",356__func__, linear_map_hash_count, &ppc64_rma_size);357}358359static inline void hash_debug_pagealloc_add_slot(phys_addr_t paddr,360int slot)361{362if (!debug_pagealloc_enabled() || !linear_map_hash_count)363return;364if ((paddr >> PAGE_SHIFT) < linear_map_hash_count)365linear_map_hash_slots[paddr >> PAGE_SHIFT] = slot | 0x80;366}367368static int hash_debug_pagealloc_map_pages(struct page *page, int numpages,369int enable)370{371unsigned long flags, vaddr, lmi;372int i;373374if (!debug_pagealloc_enabled() || !linear_map_hash_count)375return 0;376377local_irq_save(flags);378for (i = 0; i < numpages; i++, page++) {379vaddr = (unsigned long)page_address(page);380lmi = __pa(vaddr) >> PAGE_SHIFT;381if (lmi >= linear_map_hash_count)382continue;383if (enable)384kernel_map_linear_page(vaddr, lmi,385linear_map_hash_slots, &linear_map_hash_lock);386else387kernel_unmap_linear_page(vaddr, lmi,388linear_map_hash_slots, &linear_map_hash_lock);389}390local_irq_restore(flags);391return 0;392}393394#else /* CONFIG_DEBUG_PAGEALLOC */395static inline void hash_debug_pagealloc_alloc_slots(void) {}396static inline void hash_debug_pagealloc_add_slot(phys_addr_t paddr, int slot) {}397static int __maybe_unused398hash_debug_pagealloc_map_pages(struct page *page, int numpages, int enable)399{400return 0;401}402#endif /* CONFIG_DEBUG_PAGEALLOC */403404#ifdef CONFIG_KFENCE405static u8 *linear_map_kf_hash_slots;406static unsigned long linear_map_kf_hash_count;407static DEFINE_RAW_SPINLOCK(linear_map_kf_hash_lock);408409static phys_addr_t kfence_pool;410411static __init void hash_kfence_alloc_pool(void)412{413if (!kfence_early_init_enabled())414goto err;415416/* allocate linear map for kfence within RMA region */417linear_map_kf_hash_count = KFENCE_POOL_SIZE >> PAGE_SHIFT;418linear_map_kf_hash_slots = memblock_alloc_try_nid(419linear_map_kf_hash_count, 1,420MEMBLOCK_LOW_LIMIT, ppc64_rma_size,421NUMA_NO_NODE);422if (!linear_map_kf_hash_slots) {423pr_err("%s: memblock for linear map (%lu) failed\n", __func__,424linear_map_kf_hash_count);425goto err;426}427428/* allocate kfence pool early */429kfence_pool = memblock_phys_alloc_range(KFENCE_POOL_SIZE, PAGE_SIZE,430MEMBLOCK_LOW_LIMIT, MEMBLOCK_ALLOC_ANYWHERE);431if (!kfence_pool) {432pr_err("%s: memblock for kfence pool (%lu) failed\n", __func__,433KFENCE_POOL_SIZE);434memblock_free(linear_map_kf_hash_slots,435linear_map_kf_hash_count);436linear_map_kf_hash_count = 0;437goto err;438}439memblock_mark_nomap(kfence_pool, KFENCE_POOL_SIZE);440441return;442err:443pr_info("Disabling kfence\n");444disable_kfence();445}446447static __init void hash_kfence_map_pool(void)448{449unsigned long kfence_pool_start, kfence_pool_end;450unsigned long prot = pgprot_val(PAGE_KERNEL);451452if (!kfence_pool)453return;454455kfence_pool_start = (unsigned long) __va(kfence_pool);456kfence_pool_end = kfence_pool_start + KFENCE_POOL_SIZE;457__kfence_pool = (char *) kfence_pool_start;458BUG_ON(htab_bolt_mapping(kfence_pool_start, kfence_pool_end,459kfence_pool, prot, mmu_linear_psize,460mmu_kernel_ssize));461memblock_clear_nomap(kfence_pool, KFENCE_POOL_SIZE);462}463464static inline void hash_kfence_add_slot(phys_addr_t paddr, int slot)465{466unsigned long vaddr = (unsigned long) __va(paddr);467unsigned long lmi = (vaddr - (unsigned long)__kfence_pool)468>> PAGE_SHIFT;469470if (!kfence_pool)471return;472BUG_ON(!is_kfence_address((void *)vaddr));473BUG_ON(lmi >= linear_map_kf_hash_count);474linear_map_kf_hash_slots[lmi] = slot | 0x80;475}476477static int hash_kfence_map_pages(struct page *page, int numpages, int enable)478{479unsigned long flags, vaddr, lmi;480int i;481482WARN_ON_ONCE(!linear_map_kf_hash_count);483local_irq_save(flags);484for (i = 0; i < numpages; i++, page++) {485vaddr = (unsigned long)page_address(page);486lmi = (vaddr - (unsigned long)__kfence_pool) >> PAGE_SHIFT;487488/* Ideally this should never happen */489if (lmi >= linear_map_kf_hash_count) {490WARN_ON_ONCE(1);491continue;492}493494if (enable)495kernel_map_linear_page(vaddr, lmi,496linear_map_kf_hash_slots,497&linear_map_kf_hash_lock);498else499kernel_unmap_linear_page(vaddr, lmi,500linear_map_kf_hash_slots,501&linear_map_kf_hash_lock);502}503local_irq_restore(flags);504return 0;505}506#else507static inline void hash_kfence_alloc_pool(void) {}508static inline void hash_kfence_map_pool(void) {}509static inline void hash_kfence_add_slot(phys_addr_t paddr, int slot) {}510static int __maybe_unused511hash_kfence_map_pages(struct page *page, int numpages, int enable)512{513return 0;514}515#endif516517#if defined(CONFIG_DEBUG_PAGEALLOC) || defined(CONFIG_KFENCE)518int hash__kernel_map_pages(struct page *page, int numpages, int enable)519{520void *vaddr = page_address(page);521522if (is_kfence_address(vaddr))523return hash_kfence_map_pages(page, numpages, enable);524else525return hash_debug_pagealloc_map_pages(page, numpages, enable);526}527528static void hash_linear_map_add_slot(phys_addr_t paddr, int slot)529{530if (is_kfence_address(__va(paddr)))531hash_kfence_add_slot(paddr, slot);532else533hash_debug_pagealloc_add_slot(paddr, slot);534}535#else536static void hash_linear_map_add_slot(phys_addr_t paddr, int slot) {}537#endif538539/*540* 'R' and 'C' update notes:541* - Under pHyp or KVM, the updatepp path will not set C, thus it *will*542* create writeable HPTEs without C set, because the hcall H_PROTECT543* that we use in that case will not update C544* - The above is however not a problem, because we also don't do that545* fancy "no flush" variant of eviction and we use H_REMOVE which will546* do the right thing and thus we don't have the race I described earlier547*548* - Under bare metal, we do have the race, so we need R and C set549* - We make sure R is always set and never lost550* - C is _PAGE_DIRTY, and *should* always be set for a writeable mapping551*/552unsigned long htab_convert_pte_flags(unsigned long pteflags, unsigned long flags)553{554unsigned long rflags = 0;555556/* _PAGE_EXEC -> NOEXEC */557if ((pteflags & _PAGE_EXEC) == 0)558rflags |= HPTE_R_N;559/*560* PPP bits:561* Linux uses slb key 0 for kernel and 1 for user.562* kernel RW areas are mapped with PPP=0b000563* User area is mapped with PPP=0b010 for read/write564* or PPP=0b011 for read-only (including writeable but clean pages).565*/566if (pteflags & _PAGE_PRIVILEGED) {567/*568* Kernel read only mapped with ppp bits 0b110569*/570if (!(pteflags & _PAGE_WRITE)) {571if (mmu_has_feature(MMU_FTR_KERNEL_RO))572rflags |= (HPTE_R_PP0 | 0x2);573else574rflags |= 0x3;575}576VM_WARN_ONCE(!(pteflags & _PAGE_RWX), "no-access mapping request");577} else {578if (pteflags & _PAGE_RWX)579rflags |= 0x2;580/*581* We should never hit this in normal fault handling because582* a permission check (check_pte_access()) will bubble this583* to higher level linux handler even for PAGE_NONE.584*/585VM_WARN_ONCE(!(pteflags & _PAGE_RWX), "no-access mapping request");586if (!((pteflags & _PAGE_WRITE) && (pteflags & _PAGE_DIRTY)))587rflags |= 0x1;588}589/*590* We can't allow hardware to update hpte bits. Hence always591* set 'R' bit and set 'C' if it is a write fault592*/593rflags |= HPTE_R_R;594595if (pteflags & _PAGE_DIRTY)596rflags |= HPTE_R_C;597/*598* Add in WIG bits599*/600601if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_TOLERANT)602rflags |= HPTE_R_I;603else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_NON_IDEMPOTENT)604rflags |= (HPTE_R_I | HPTE_R_G);605else if ((pteflags & _PAGE_CACHE_CTL) == _PAGE_SAO)606rflags |= (HPTE_R_W | HPTE_R_I | HPTE_R_M);607else608/*609* Add memory coherence if cache inhibited is not set610*/611rflags |= HPTE_R_M;612613rflags |= pte_to_hpte_pkey_bits(pteflags, flags);614return rflags;615}616617int htab_bolt_mapping(unsigned long vstart, unsigned long vend,618unsigned long pstart, unsigned long prot,619int psize, int ssize)620{621unsigned long vaddr, paddr;622unsigned int step, shift;623int ret = 0;624625shift = mmu_psize_defs[psize].shift;626step = 1 << shift;627628prot = htab_convert_pte_flags(prot, HPTE_USE_KERNEL_KEY);629630DBG("htab_bolt_mapping(%lx..%lx -> %lx (%lx,%d,%d)\n",631vstart, vend, pstart, prot, psize, ssize);632633/* Carefully map only the possible range */634vaddr = ALIGN(vstart, step);635paddr = ALIGN(pstart, step);636vend = ALIGN_DOWN(vend, step);637638for (; vaddr < vend; vaddr += step, paddr += step) {639unsigned long hash, hpteg;640unsigned long vsid = get_kernel_vsid(vaddr, ssize);641unsigned long vpn = hpt_vpn(vaddr, vsid, ssize);642unsigned long tprot = prot;643bool secondary_hash = false;644645/*646* If we hit a bad address return error.647*/648if (!vsid)649return -1;650/* Make kernel text executable */651if (overlaps_kernel_text(vaddr, vaddr + step))652tprot &= ~HPTE_R_N;653654/*655* If relocatable, check if it overlaps interrupt vectors that656* are copied down to real 0. For relocatable kernel657* (e.g. kdump case) we copy interrupt vectors down to real658* address 0. Mark that region as executable. This is659* because on p8 system with relocation on exception feature660* enabled, exceptions are raised with MMU (IR=DR=1) ON. Hence661* in order to execute the interrupt handlers in virtual662* mode the vector region need to be marked as executable.663*/664if ((PHYSICAL_START > MEMORY_START) &&665overlaps_interrupt_vector_text(vaddr, vaddr + step))666tprot &= ~HPTE_R_N;667668hash = hpt_hash(vpn, shift, ssize);669hpteg = ((hash & htab_hash_mask) * HPTES_PER_GROUP);670671BUG_ON(!mmu_hash_ops.hpte_insert);672repeat:673ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,674HPTE_V_BOLTED, psize, psize,675ssize);676if (ret == -1) {677/*678* Try to keep bolted entries in primary.679* Remove non bolted entries and try insert again680*/681ret = mmu_hash_ops.hpte_remove(hpteg);682if (ret != -1)683ret = mmu_hash_ops.hpte_insert(hpteg, vpn, paddr, tprot,684HPTE_V_BOLTED, psize, psize,685ssize);686if (ret == -1 && !secondary_hash) {687secondary_hash = true;688hpteg = ((~hash & htab_hash_mask) * HPTES_PER_GROUP);689goto repeat;690}691}692693if (ret < 0)694break;695696cond_resched();697/* add slot info in debug_pagealloc / kfence linear map */698hash_linear_map_add_slot(paddr, ret);699}700return ret < 0 ? ret : 0;701}702703int htab_remove_mapping(unsigned long vstart, unsigned long vend,704int psize, int ssize)705{706unsigned long vaddr, time_limit;707unsigned int step, shift;708int rc;709int ret = 0;710711shift = mmu_psize_defs[psize].shift;712step = 1 << shift;713714if (!mmu_hash_ops.hpte_removebolted)715return -ENODEV;716717/* Unmap the full range specificied */718vaddr = ALIGN_DOWN(vstart, step);719time_limit = jiffies + HZ;720721for (;vaddr < vend; vaddr += step) {722rc = mmu_hash_ops.hpte_removebolted(vaddr, psize, ssize);723724/*725* For large number of mappings introduce a cond_resched()726* to prevent softlockup warnings.727*/728if (time_after(jiffies, time_limit)) {729cond_resched();730time_limit = jiffies + HZ;731}732if (rc == -ENOENT) {733ret = -ENOENT;734continue;735}736if (rc < 0)737return rc;738}739740return ret;741}742743static bool disable_1tb_segments __ro_after_init;744745static int __init parse_disable_1tb_segments(char *p)746{747disable_1tb_segments = true;748return 0;749}750early_param("disable_1tb_segments", parse_disable_1tb_segments);751752bool stress_hpt_enabled __initdata;753754static int __init parse_stress_hpt(char *p)755{756stress_hpt_enabled = true;757return 0;758}759early_param("stress_hpt", parse_stress_hpt);760761__ro_after_init DEFINE_STATIC_KEY_FALSE(stress_hpt_key);762763/*764* per-CPU array allocated if we enable stress_hpt.765*/766#define STRESS_MAX_GROUPS 16767struct stress_hpt_struct {768unsigned long last_group[STRESS_MAX_GROUPS];769};770771static inline int stress_nr_groups(void)772{773/*774* LPAR H_REMOVE flushes TLB, so need some number > 1 of entries775* to allow practical forward progress. Bare metal returns 1, which776* seems to help uncover more bugs.777*/778if (firmware_has_feature(FW_FEATURE_LPAR))779return STRESS_MAX_GROUPS;780else781return 1;782}783784static struct stress_hpt_struct *stress_hpt_struct;785786static int __init htab_dt_scan_seg_sizes(unsigned long node,787const char *uname, int depth,788void *data)789{790const char *type = of_get_flat_dt_prop(node, "device_type", NULL);791const __be32 *prop;792int size = 0;793794/* We are scanning "cpu" nodes only */795if (type == NULL || strcmp(type, "cpu") != 0)796return 0;797798prop = of_get_flat_dt_prop(node, "ibm,processor-segment-sizes", &size);799if (prop == NULL)800return 0;801for (; size >= 4; size -= 4, ++prop) {802if (be32_to_cpu(prop[0]) == 40) {803DBG("1T segment support detected\n");804805if (disable_1tb_segments) {806DBG("1T segments disabled by command line\n");807break;808}809810cur_cpu_spec->mmu_features |= MMU_FTR_1T_SEGMENT;811return 1;812}813}814cur_cpu_spec->mmu_features &= ~MMU_FTR_NO_SLBIE_B;815return 0;816}817818static int __init get_idx_from_shift(unsigned int shift)819{820int idx = -1;821822switch (shift) {823case 0xc:824idx = MMU_PAGE_4K;825break;826case 0x10:827idx = MMU_PAGE_64K;828break;829case 0x14:830idx = MMU_PAGE_1M;831break;832case 0x18:833idx = MMU_PAGE_16M;834break;835case 0x22:836idx = MMU_PAGE_16G;837break;838}839return idx;840}841842static int __init htab_dt_scan_page_sizes(unsigned long node,843const char *uname, int depth,844void *data)845{846const char *type = of_get_flat_dt_prop(node, "device_type", NULL);847const __be32 *prop;848int size = 0;849850/* We are scanning "cpu" nodes only */851if (type == NULL || strcmp(type, "cpu") != 0)852return 0;853854prop = of_get_flat_dt_prop(node, "ibm,segment-page-sizes", &size);855if (!prop)856return 0;857858pr_info("Page sizes from device-tree:\n");859size /= 4;860cur_cpu_spec->mmu_features &= ~(MMU_FTR_16M_PAGE);861while(size > 0) {862unsigned int base_shift = be32_to_cpu(prop[0]);863unsigned int slbenc = be32_to_cpu(prop[1]);864unsigned int lpnum = be32_to_cpu(prop[2]);865struct mmu_psize_def *def;866int idx, base_idx;867868size -= 3; prop += 3;869base_idx = get_idx_from_shift(base_shift);870if (base_idx < 0) {871/* skip the pte encoding also */872prop += lpnum * 2; size -= lpnum * 2;873continue;874}875def = &mmu_psize_defs[base_idx];876if (base_idx == MMU_PAGE_16M)877cur_cpu_spec->mmu_features |= MMU_FTR_16M_PAGE;878879def->shift = base_shift;880if (base_shift <= 23)881def->avpnm = 0;882else883def->avpnm = (1 << (base_shift - 23)) - 1;884def->sllp = slbenc;885/*886* We don't know for sure what's up with tlbiel, so887* for now we only set it for 4K and 64K pages888*/889if (base_idx == MMU_PAGE_4K || base_idx == MMU_PAGE_64K)890def->tlbiel = 1;891else892def->tlbiel = 0;893894while (size > 0 && lpnum) {895unsigned int shift = be32_to_cpu(prop[0]);896int penc = be32_to_cpu(prop[1]);897898prop += 2; size -= 2;899lpnum--;900901idx = get_idx_from_shift(shift);902if (idx < 0)903continue;904905if (penc == -1)906pr_err("Invalid penc for base_shift=%d "907"shift=%d\n", base_shift, shift);908909def->penc[idx] = penc;910pr_info("base_shift=%d: shift=%d, sllp=0x%04lx,"911" avpnm=0x%08lx, tlbiel=%d, penc=%d\n",912base_shift, shift, def->sllp,913def->avpnm, def->tlbiel, def->penc[idx]);914}915}916917return 1;918}919920#ifdef CONFIG_HUGETLB_PAGE921/*922* Scan for 16G memory blocks that have been set aside for huge pages923* and reserve those blocks for 16G huge pages.924*/925static int __init htab_dt_scan_hugepage_blocks(unsigned long node,926const char *uname, int depth,927void *data) {928const char *type = of_get_flat_dt_prop(node, "device_type", NULL);929const __be64 *addr_prop;930const __be32 *page_count_prop;931unsigned int expected_pages;932long unsigned int phys_addr;933long unsigned int block_size;934935/* We are scanning "memory" nodes only */936if (type == NULL || strcmp(type, "memory") != 0)937return 0;938939/*940* This property is the log base 2 of the number of virtual pages that941* will represent this memory block.942*/943page_count_prop = of_get_flat_dt_prop(node, "ibm,expected#pages", NULL);944if (page_count_prop == NULL)945return 0;946expected_pages = (1 << be32_to_cpu(page_count_prop[0]));947addr_prop = of_get_flat_dt_prop(node, "reg", NULL);948if (addr_prop == NULL)949return 0;950phys_addr = be64_to_cpu(addr_prop[0]);951block_size = be64_to_cpu(addr_prop[1]);952if (block_size != (16 * GB))953return 0;954printk(KERN_INFO "Huge page(16GB) memory: "955"addr = 0x%lX size = 0x%lX pages = %d\n",956phys_addr, block_size, expected_pages);957if (phys_addr + block_size * expected_pages <= memblock_end_of_DRAM()) {958memblock_reserve(phys_addr, block_size * expected_pages);959pseries_add_gpage(phys_addr, block_size, expected_pages);960}961return 0;962}963#endif /* CONFIG_HUGETLB_PAGE */964965static void __init mmu_psize_set_default_penc(void)966{967int bpsize, apsize;968for (bpsize = 0; bpsize < MMU_PAGE_COUNT; bpsize++)969for (apsize = 0; apsize < MMU_PAGE_COUNT; apsize++)970mmu_psize_defs[bpsize].penc[apsize] = -1;971}972973#ifdef CONFIG_PPC_64K_PAGES974975static bool __init might_have_hea(void)976{977/*978* The HEA ethernet adapter requires awareness of the979* GX bus. Without that awareness we can easily assume980* we will never see an HEA ethernet device.981*/982#ifdef CONFIG_IBMEBUS983return !cpu_has_feature(CPU_FTR_ARCH_207S) &&984firmware_has_feature(FW_FEATURE_SPLPAR);985#else986return false;987#endif988}989990#endif /* #ifdef CONFIG_PPC_64K_PAGES */991992static void __init htab_scan_page_sizes(void)993{994int rc;995996/* se the invalid penc to -1 */997mmu_psize_set_default_penc();998999/* Default to 4K pages only */1000memcpy(mmu_psize_defs, mmu_psize_defaults,1001sizeof(mmu_psize_defaults));10021003/*1004* Try to find the available page sizes in the device-tree1005*/1006rc = of_scan_flat_dt(htab_dt_scan_page_sizes, NULL);1007if (rc == 0 && early_mmu_has_feature(MMU_FTR_16M_PAGE)) {1008/*1009* Nothing in the device-tree, but the CPU supports 16M pages,1010* so let's fallback on a known size list for 16M capable CPUs.1011*/1012memcpy(mmu_psize_defs, mmu_psize_defaults_gp,1013sizeof(mmu_psize_defaults_gp));1014}10151016#ifdef CONFIG_HUGETLB_PAGE1017if (!hugetlb_disabled && !early_radix_enabled() ) {1018/* Reserve 16G huge page memory sections for huge pages */1019of_scan_flat_dt(htab_dt_scan_hugepage_blocks, NULL);1020}1021#endif /* CONFIG_HUGETLB_PAGE */1022}10231024/*1025* Fill in the hpte_page_sizes[] array.1026* We go through the mmu_psize_defs[] array looking for all the1027* supported base/actual page size combinations. Each combination1028* has a unique pagesize encoding (penc) value in the low bits of1029* the LP field of the HPTE. For actual page sizes less than 1MB,1030* some of the upper LP bits are used for RPN bits, meaning that1031* we need to fill in several entries in hpte_page_sizes[].1032*1033* In diagrammatic form, with r = RPN bits and z = page size bits:1034* PTE LP actual page size1035* rrrr rrrz >=8KB1036* rrrr rrzz >=16KB1037* rrrr rzzz >=32KB1038* rrrr zzzz >=64KB1039* ...1040*1041* The zzzz bits are implementation-specific but are chosen so that1042* no encoding for a larger page size uses the same value in its1043* low-order N bits as the encoding for the 2^(12+N) byte page size1044* (if it exists).1045*/1046static void __init init_hpte_page_sizes(void)1047{1048long int ap, bp;1049long int shift, penc;10501051for (bp = 0; bp < MMU_PAGE_COUNT; ++bp) {1052if (!mmu_psize_defs[bp].shift)1053continue; /* not a supported page size */1054for (ap = bp; ap < MMU_PAGE_COUNT; ++ap) {1055penc = mmu_psize_defs[bp].penc[ap];1056if (penc == -1 || !mmu_psize_defs[ap].shift)1057continue;1058shift = mmu_psize_defs[ap].shift - LP_SHIFT;1059if (shift <= 0)1060continue; /* should never happen */1061/*1062* For page sizes less than 1MB, this loop1063* replicates the entry for all possible values1064* of the rrrr bits.1065*/1066while (penc < (1 << LP_BITS)) {1067hpte_page_sizes[penc] = (ap << 4) | bp;1068penc += 1 << shift;1069}1070}1071}1072}10731074static void __init htab_init_page_sizes(void)1075{1076bool aligned = true;1077init_hpte_page_sizes();10781079if (!hash_supports_debug_pagealloc() && !kfence_early_init_enabled()) {1080/*1081* Pick a size for the linear mapping. Currently, we only1082* support 16M, 1M and 4K which is the default1083*/1084if (IS_ENABLED(CONFIG_STRICT_KERNEL_RWX) &&1085(unsigned long)_stext % 0x1000000) {1086if (mmu_psize_defs[MMU_PAGE_16M].shift)1087pr_warn("Kernel not 16M aligned, disabling 16M linear map alignment\n");1088aligned = false;1089}10901091if (mmu_psize_defs[MMU_PAGE_16M].shift && aligned)1092mmu_linear_psize = MMU_PAGE_16M;1093else if (mmu_psize_defs[MMU_PAGE_1M].shift)1094mmu_linear_psize = MMU_PAGE_1M;1095}10961097#ifdef CONFIG_PPC_64K_PAGES1098/*1099* Pick a size for the ordinary pages. Default is 4K, we support1100* 64K for user mappings and vmalloc if supported by the processor.1101* We only use 64k for ioremap if the processor1102* (and firmware) support cache-inhibited large pages.1103* If not, we use 4k and set mmu_ci_restrictions so that1104* hash_page knows to switch processes that use cache-inhibited1105* mappings to 4k pages.1106*/1107if (mmu_psize_defs[MMU_PAGE_64K].shift) {1108mmu_virtual_psize = MMU_PAGE_64K;1109mmu_vmalloc_psize = MMU_PAGE_64K;1110if (mmu_linear_psize == MMU_PAGE_4K)1111mmu_linear_psize = MMU_PAGE_64K;1112if (mmu_has_feature(MMU_FTR_CI_LARGE_PAGE)) {1113/*1114* When running on pSeries using 64k pages for ioremap1115* would stop us accessing the HEA ethernet. So if we1116* have the chance of ever seeing one, stay at 4k.1117*/1118if (!might_have_hea())1119mmu_io_psize = MMU_PAGE_64K;1120} else1121mmu_ci_restrictions = 1;1122}1123#endif /* CONFIG_PPC_64K_PAGES */11241125#ifdef CONFIG_SPARSEMEM_VMEMMAP1126/*1127* We try to use 16M pages for vmemmap if that is supported1128* and we have at least 1G of RAM at boot1129*/1130if (mmu_psize_defs[MMU_PAGE_16M].shift &&1131memblock_phys_mem_size() >= 0x40000000)1132mmu_vmemmap_psize = MMU_PAGE_16M;1133else1134mmu_vmemmap_psize = mmu_virtual_psize;1135#endif /* CONFIG_SPARSEMEM_VMEMMAP */11361137printk(KERN_DEBUG "Page orders: linear mapping = %d, "1138"virtual = %d, io = %d"1139#ifdef CONFIG_SPARSEMEM_VMEMMAP1140", vmemmap = %d"1141#endif1142"\n",1143mmu_psize_defs[mmu_linear_psize].shift,1144mmu_psize_defs[mmu_virtual_psize].shift,1145mmu_psize_defs[mmu_io_psize].shift1146#ifdef CONFIG_SPARSEMEM_VMEMMAP1147,mmu_psize_defs[mmu_vmemmap_psize].shift1148#endif1149);1150}11511152static int __init htab_dt_scan_pftsize(unsigned long node,1153const char *uname, int depth,1154void *data)1155{1156const char *type = of_get_flat_dt_prop(node, "device_type", NULL);1157const __be32 *prop;11581159/* We are scanning "cpu" nodes only */1160if (type == NULL || strcmp(type, "cpu") != 0)1161return 0;11621163prop = of_get_flat_dt_prop(node, "ibm,pft-size", NULL);1164if (prop != NULL) {1165/* pft_size[0] is the NUMA CEC cookie */1166ppc64_pft_size = be32_to_cpu(prop[1]);1167return 1;1168}1169return 0;1170}11711172unsigned htab_shift_for_mem_size(unsigned long mem_size)1173{1174unsigned memshift = __ilog2(mem_size);1175unsigned pshift = mmu_psize_defs[mmu_virtual_psize].shift;1176unsigned pteg_shift;11771178/* round mem_size up to next power of 2 */1179if ((1UL << memshift) < mem_size)1180memshift += 1;11811182/* aim for 2 pages / pteg */1183pteg_shift = memshift - (pshift + 1);11841185/*1186* 2^11 PTEGS of 128 bytes each, ie. 2^18 bytes is the minimum htab1187* size permitted by the architecture.1188*/1189return max(pteg_shift + 7, 18U);1190}11911192static unsigned long __init htab_get_table_size(void)1193{1194/*1195* If hash size isn't already provided by the platform, we try to1196* retrieve it from the device-tree. If it's not there neither, we1197* calculate it now based on the total RAM size1198*/1199if (ppc64_pft_size == 0)1200of_scan_flat_dt(htab_dt_scan_pftsize, NULL);1201if (ppc64_pft_size)1202return 1UL << ppc64_pft_size;12031204return 1UL << htab_shift_for_mem_size(memblock_phys_mem_size());1205}12061207#ifdef CONFIG_MEMORY_HOTPLUG1208static int resize_hpt_for_hotplug(unsigned long new_mem_size)1209{1210unsigned target_hpt_shift;12111212if (!mmu_hash_ops.resize_hpt)1213return 0;12141215target_hpt_shift = htab_shift_for_mem_size(new_mem_size);12161217/*1218* To avoid lots of HPT resizes if memory size is fluctuating1219* across a boundary, we deliberately have some hysterisis1220* here: we immediately increase the HPT size if the target1221* shift exceeds the current shift, but we won't attempt to1222* reduce unless the target shift is at least 2 below the1223* current shift1224*/1225if (target_hpt_shift > ppc64_pft_size ||1226target_hpt_shift < ppc64_pft_size - 1)1227return mmu_hash_ops.resize_hpt(target_hpt_shift);12281229return 0;1230}12311232int hash__create_section_mapping(unsigned long start, unsigned long end,1233int nid, pgprot_t prot)1234{1235int rc;12361237if (end >= H_VMALLOC_START) {1238pr_warn("Outside the supported range\n");1239return -1;1240}12411242resize_hpt_for_hotplug(memblock_phys_mem_size());12431244rc = htab_bolt_mapping(start, end, __pa(start),1245pgprot_val(prot), mmu_linear_psize,1246mmu_kernel_ssize);12471248if (rc < 0) {1249int rc2 = htab_remove_mapping(start, end, mmu_linear_psize,1250mmu_kernel_ssize);1251BUG_ON(rc2 && (rc2 != -ENOENT));1252}1253return rc;1254}12551256int hash__remove_section_mapping(unsigned long start, unsigned long end)1257{1258int rc = htab_remove_mapping(start, end, mmu_linear_psize,1259mmu_kernel_ssize);12601261if (resize_hpt_for_hotplug(memblock_phys_mem_size()) == -ENOSPC)1262pr_warn("Hash collision while resizing HPT\n");12631264return rc;1265}1266#endif /* CONFIG_MEMORY_HOTPLUG */12671268static void __init hash_init_partition_table(phys_addr_t hash_table,1269unsigned long htab_size)1270{1271mmu_partition_table_init();12721273/*1274* PS field (VRMA page size) is not used for LPID 0, hence set to 0.1275* For now, UPRT is 0 and we have no segment table.1276*/1277htab_size = __ilog2(htab_size) - 18;1278mmu_partition_table_set_entry(0, hash_table | htab_size, 0, false);1279pr_info("Partition table %p\n", partition_tb);1280}12811282void hpt_clear_stress(void);1283static struct timer_list stress_hpt_timer;1284static void stress_hpt_timer_fn(struct timer_list *timer)1285{1286int next_cpu;12871288hpt_clear_stress();1289if (!firmware_has_feature(FW_FEATURE_LPAR))1290tlbiel_all();12911292next_cpu = cpumask_next(raw_smp_processor_id(), cpu_online_mask);1293if (next_cpu >= nr_cpu_ids)1294next_cpu = cpumask_first(cpu_online_mask);1295stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);1296add_timer_on(&stress_hpt_timer, next_cpu);1297}12981299static void __init htab_initialize(void)1300{1301unsigned long table;1302unsigned long pteg_count;1303unsigned long prot;1304phys_addr_t base = 0, size = 0, end;1305u64 i;13061307DBG(" -> htab_initialize()\n");13081309if (mmu_has_feature(MMU_FTR_1T_SEGMENT)) {1310mmu_kernel_ssize = MMU_SEGSIZE_1T;1311mmu_highuser_ssize = MMU_SEGSIZE_1T;1312printk(KERN_INFO "Using 1TB segments\n");1313}13141315if (stress_slb_enabled)1316static_branch_enable(&stress_slb_key);13171318if (stress_hpt_enabled) {1319unsigned long tmp;1320static_branch_enable(&stress_hpt_key);1321// Too early to use nr_cpu_ids, so use NR_CPUS1322tmp = memblock_phys_alloc_range(sizeof(struct stress_hpt_struct) * NR_CPUS,1323__alignof__(struct stress_hpt_struct),13240, MEMBLOCK_ALLOC_ANYWHERE);1325memset((void *)tmp, 0xff, sizeof(struct stress_hpt_struct) * NR_CPUS);1326stress_hpt_struct = __va(tmp);13271328timer_setup(&stress_hpt_timer, stress_hpt_timer_fn, 0);1329stress_hpt_timer.expires = jiffies + msecs_to_jiffies(10);1330add_timer(&stress_hpt_timer);1331}13321333/*1334* Calculate the required size of the htab. We want the number of1335* PTEGs to equal one half the number of real pages.1336*/1337htab_size_bytes = htab_get_table_size();1338pteg_count = htab_size_bytes >> 7;13391340htab_hash_mask = pteg_count - 1;13411342if (firmware_has_feature(FW_FEATURE_LPAR) ||1343firmware_has_feature(FW_FEATURE_PS3_LV1)) {1344/* Using a hypervisor which owns the htab */1345htab_address = NULL;1346_SDR1 = 0;1347#ifdef CONFIG_FA_DUMP1348/*1349* If firmware assisted dump is active firmware preserves1350* the contents of htab along with entire partition memory.1351* Clear the htab if firmware assisted dump is active so1352* that we dont end up using old mappings.1353*/1354if (is_fadump_active() && mmu_hash_ops.hpte_clear_all)1355mmu_hash_ops.hpte_clear_all();1356#endif1357} else {1358unsigned long limit = MEMBLOCK_ALLOC_ANYWHERE;13591360table = memblock_phys_alloc_range(htab_size_bytes,1361htab_size_bytes,13620, limit);1363if (!table)1364panic("ERROR: Failed to allocate %pa bytes below %pa\n",1365&htab_size_bytes, &limit);13661367DBG("Hash table allocated at %lx, size: %lx\n", table,1368htab_size_bytes);13691370htab_address = __va(table);13711372/* htab absolute addr + encoded htabsize */1373_SDR1 = table + __ilog2(htab_size_bytes) - 18;13741375/* Initialize the HPT with no entries */1376memset((void *)table, 0, htab_size_bytes);13771378if (!cpu_has_feature(CPU_FTR_ARCH_300))1379/* Set SDR1 */1380mtspr(SPRN_SDR1, _SDR1);1381else1382hash_init_partition_table(table, htab_size_bytes);1383}13841385prot = pgprot_val(PAGE_KERNEL);13861387hash_debug_pagealloc_alloc_slots();1388hash_kfence_alloc_pool();1389/* create bolted the linear mapping in the hash table */1390for_each_mem_range(i, &base, &end) {1391size = end - base;1392base = (unsigned long)__va(base);13931394DBG("creating mapping for region: %lx..%lx (prot: %lx)\n",1395base, size, prot);13961397if ((base + size) >= H_VMALLOC_START) {1398pr_warn("Outside the supported range\n");1399continue;1400}14011402BUG_ON(htab_bolt_mapping(base, base + size, __pa(base),1403prot, mmu_linear_psize, mmu_kernel_ssize));1404}1405hash_kfence_map_pool();1406memblock_set_current_limit(MEMBLOCK_ALLOC_ANYWHERE);14071408/*1409* If we have a memory_limit and we've allocated TCEs then we need to1410* explicitly map the TCE area at the top of RAM. We also cope with the1411* case that the TCEs start below memory_limit.1412* tce_alloc_start/end are 16MB aligned so the mapping should work1413* for either 4K or 16MB pages.1414*/1415if (tce_alloc_start) {1416tce_alloc_start = (unsigned long)__va(tce_alloc_start);1417tce_alloc_end = (unsigned long)__va(tce_alloc_end);14181419if (base + size >= tce_alloc_start)1420tce_alloc_start = base + size + 1;14211422BUG_ON(htab_bolt_mapping(tce_alloc_start, tce_alloc_end,1423__pa(tce_alloc_start), prot,1424mmu_linear_psize, mmu_kernel_ssize));1425}142614271428DBG(" <- htab_initialize()\n");1429}1430#undef KB1431#undef MB14321433void __init hash__early_init_devtree(void)1434{1435/* Initialize segment sizes */1436of_scan_flat_dt(htab_dt_scan_seg_sizes, NULL);14371438/* Initialize page sizes */1439htab_scan_page_sizes();1440}14411442static struct hash_mm_context init_hash_mm_context;1443void __init hash__early_init_mmu(void)1444{1445#ifndef CONFIG_PPC_64K_PAGES1446/*1447* We have code in __hash_page_4K() and elsewhere, which assumes it can1448* do the following:1449* new_pte |= (slot << H_PAGE_F_GIX_SHIFT) & (H_PAGE_F_SECOND | H_PAGE_F_GIX);1450*1451* Where the slot number is between 0-15, and values of 8-15 indicate1452* the secondary bucket. For that code to work H_PAGE_F_SECOND and1453* H_PAGE_F_GIX must occupy four contiguous bits in the PTE, and1454* H_PAGE_F_SECOND must be placed above H_PAGE_F_GIX. Assert that here1455* with a BUILD_BUG_ON().1456*/1457BUILD_BUG_ON(H_PAGE_F_SECOND != (1ul << (H_PAGE_F_GIX_SHIFT + 3)));1458#endif /* CONFIG_PPC_64K_PAGES */14591460htab_init_page_sizes();14611462/*1463* initialize page table size1464*/1465__pte_frag_nr = H_PTE_FRAG_NR;1466__pte_frag_size_shift = H_PTE_FRAG_SIZE_SHIFT;1467__pmd_frag_nr = H_PMD_FRAG_NR;1468__pmd_frag_size_shift = H_PMD_FRAG_SIZE_SHIFT;14691470__pte_index_size = H_PTE_INDEX_SIZE;1471__pmd_index_size = H_PMD_INDEX_SIZE;1472__pud_index_size = H_PUD_INDEX_SIZE;1473__pgd_index_size = H_PGD_INDEX_SIZE;1474__pud_cache_index = H_PUD_CACHE_INDEX;1475__pte_table_size = H_PTE_TABLE_SIZE;1476__pmd_table_size = H_PMD_TABLE_SIZE;1477__pud_table_size = H_PUD_TABLE_SIZE;1478__pgd_table_size = H_PGD_TABLE_SIZE;1479__pmd_val_bits = HASH_PMD_VAL_BITS;1480__pud_val_bits = HASH_PUD_VAL_BITS;1481__pgd_val_bits = HASH_PGD_VAL_BITS;14821483__kernel_virt_start = H_KERN_VIRT_START;1484__vmalloc_start = H_VMALLOC_START;1485__vmalloc_end = H_VMALLOC_END;1486__kernel_io_start = H_KERN_IO_START;1487__kernel_io_end = H_KERN_IO_END;1488vmemmap = (struct page *)H_VMEMMAP_START;1489ioremap_bot = IOREMAP_BASE;14901491#ifdef CONFIG_PCI1492pci_io_base = ISA_IO_BASE;1493#endif14941495/* Select appropriate backend */1496if (firmware_has_feature(FW_FEATURE_PS3_LV1))1497ps3_early_mm_init();1498else if (firmware_has_feature(FW_FEATURE_LPAR))1499hpte_init_pseries();1500else if (IS_ENABLED(CONFIG_PPC_HASH_MMU_NATIVE))1501hpte_init_native();15021503if (!mmu_hash_ops.hpte_insert)1504panic("hash__early_init_mmu: No MMU hash ops defined!\n");15051506/*1507* Initialize the MMU Hash table and create the linear mapping1508* of memory. Has to be done before SLB initialization as this is1509* currently where the page size encoding is obtained.1510*/1511htab_initialize();15121513init_mm.context.hash_context = &init_hash_mm_context;1514mm_ctx_set_slb_addr_limit(&init_mm.context, SLB_ADDR_LIMIT_DEFAULT);15151516pr_info("Initializing hash mmu with SLB\n");1517/* Initialize SLB management */1518slb_initialize();15191520if (cpu_has_feature(CPU_FTR_ARCH_206)1521&& cpu_has_feature(CPU_FTR_HVMODE))1522tlbiel_all();1523}15241525#ifdef CONFIG_SMP1526void hash__early_init_mmu_secondary(void)1527{1528/* Initialize hash table for that CPU */1529if (!firmware_has_feature(FW_FEATURE_LPAR)) {15301531if (!cpu_has_feature(CPU_FTR_ARCH_300))1532mtspr(SPRN_SDR1, _SDR1);1533else1534set_ptcr_when_no_uv(__pa(partition_tb) |1535(PATB_SIZE_SHIFT - 12));1536}1537/* Initialize SLB */1538slb_initialize();15391540if (cpu_has_feature(CPU_FTR_ARCH_206)1541&& cpu_has_feature(CPU_FTR_HVMODE))1542tlbiel_all();15431544#ifdef CONFIG_PPC_MEM_KEYS1545if (mmu_has_feature(MMU_FTR_PKEY))1546mtspr(SPRN_UAMOR, default_uamor);1547#endif1548}1549#endif /* CONFIG_SMP */15501551/*1552* Called by asm hashtable.S for doing lazy icache flush1553*/1554unsigned int hash_page_do_lazy_icache(unsigned int pp, pte_t pte, int trap)1555{1556struct folio *folio;15571558if (!pfn_valid(pte_pfn(pte)))1559return pp;15601561folio = page_folio(pte_page(pte));15621563/* page is dirty */1564if (!test_bit(PG_dcache_clean, &folio->flags) &&1565!folio_test_reserved(folio)) {1566if (trap == INTERRUPT_INST_STORAGE) {1567flush_dcache_icache_folio(folio);1568set_bit(PG_dcache_clean, &folio->flags);1569} else1570pp |= HPTE_R_N;1571}1572return pp;1573}15741575static unsigned int get_paca_psize(unsigned long addr)1576{1577unsigned char *psizes;1578unsigned long index, mask_index;15791580if (addr < SLICE_LOW_TOP) {1581psizes = get_paca()->mm_ctx_low_slices_psize;1582index = GET_LOW_SLICE_INDEX(addr);1583} else {1584psizes = get_paca()->mm_ctx_high_slices_psize;1585index = GET_HIGH_SLICE_INDEX(addr);1586}1587mask_index = index & 0x1;1588return (psizes[index >> 1] >> (mask_index * 4)) & 0xF;1589}159015911592/*1593* Demote a segment to using 4k pages.1594* For now this makes the whole process use 4k pages.1595*/1596#ifdef CONFIG_PPC_64K_PAGES1597void demote_segment_4k(struct mm_struct *mm, unsigned long addr)1598{1599if (get_slice_psize(mm, addr) == MMU_PAGE_4K)1600return;1601slice_set_range_psize(mm, addr, 1, MMU_PAGE_4K);1602#ifdef CONFIG_SPU_BASE1603spu_flush_all_slbs(mm);1604#endif1605if ((get_paca_psize(addr) != MMU_PAGE_4K) && (current->mm == mm)) {16061607copy_mm_to_paca(mm);1608slb_flush_and_restore_bolted();1609}1610}1611#endif /* CONFIG_PPC_64K_PAGES */16121613#ifdef CONFIG_PPC_SUBPAGE_PROT1614/*1615* This looks up a 2-bit protection code for a 4k subpage of a 64k page.1616* Userspace sets the subpage permissions using the subpage_prot system call.1617*1618* Result is 0: full permissions, _PAGE_RW: read-only,1619* _PAGE_RWX: no access.1620*/1621static int subpage_protection(struct mm_struct *mm, unsigned long ea)1622{1623struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context);1624u32 spp = 0;1625u32 **sbpm, *sbpp;16261627if (!spt)1628return 0;16291630if (ea >= spt->maxaddr)1631return 0;1632if (ea < 0x100000000UL) {1633/* addresses below 4GB use spt->low_prot */1634sbpm = spt->low_prot;1635} else {1636sbpm = spt->protptrs[ea >> SBP_L3_SHIFT];1637if (!sbpm)1638return 0;1639}1640sbpp = sbpm[(ea >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)];1641if (!sbpp)1642return 0;1643spp = sbpp[(ea >> PAGE_SHIFT) & (SBP_L1_COUNT - 1)];16441645/* extract 2-bit bitfield for this 4k subpage */1646spp >>= 30 - 2 * ((ea >> 12) & 0xf);16471648/*1649* 0 -> full permission1650* 1 -> Read only1651* 2 -> no access.1652* We return the flag that need to be cleared.1653*/1654spp = ((spp & 2) ? _PAGE_RWX : 0) | ((spp & 1) ? _PAGE_WRITE : 0);1655return spp;1656}16571658#else /* CONFIG_PPC_SUBPAGE_PROT */1659static inline int subpage_protection(struct mm_struct *mm, unsigned long ea)1660{1661return 0;1662}1663#endif16641665void hash_failure_debug(unsigned long ea, unsigned long access,1666unsigned long vsid, unsigned long trap,1667int ssize, int psize, int lpsize, unsigned long pte)1668{1669if (!printk_ratelimit())1670return;1671pr_info("mm: Hashing failure ! EA=0x%lx access=0x%lx current=%s\n",1672ea, access, current->comm);1673pr_info(" trap=0x%lx vsid=0x%lx ssize=%d base psize=%d psize %d pte=0x%lx\n",1674trap, vsid, ssize, psize, lpsize, pte);1675}16761677static void check_paca_psize(unsigned long ea, struct mm_struct *mm,1678int psize, bool user_region)1679{1680if (user_region) {1681if (psize != get_paca_psize(ea)) {1682copy_mm_to_paca(mm);1683slb_flush_and_restore_bolted();1684}1685} else if (get_paca()->vmalloc_sllp !=1686mmu_psize_defs[mmu_vmalloc_psize].sllp) {1687get_paca()->vmalloc_sllp =1688mmu_psize_defs[mmu_vmalloc_psize].sllp;1689slb_vmalloc_update();1690}1691}16921693/*1694* Result code is:1695* 0 - handled1696* 1 - normal page fault1697* -1 - critical hash insertion error1698* -2 - access not permitted by subpage protection mechanism1699*/1700int hash_page_mm(struct mm_struct *mm, unsigned long ea,1701unsigned long access, unsigned long trap,1702unsigned long flags)1703{1704bool is_thp;1705pgd_t *pgdir;1706unsigned long vsid;1707pte_t *ptep;1708unsigned hugeshift;1709int rc, user_region = 0;1710int psize, ssize;17111712DBG_LOW("hash_page(ea=%016lx, access=%lx, trap=%lx\n",1713ea, access, trap);1714trace_hash_fault(ea, access, trap);17151716/* Get region & vsid */1717switch (get_region_id(ea)) {1718case USER_REGION_ID:1719user_region = 1;1720if (! mm) {1721DBG_LOW(" user region with no mm !\n");1722rc = 1;1723goto bail;1724}1725psize = get_slice_psize(mm, ea);1726ssize = user_segment_size(ea);1727vsid = get_user_vsid(&mm->context, ea, ssize);1728break;1729case VMALLOC_REGION_ID:1730vsid = get_kernel_vsid(ea, mmu_kernel_ssize);1731psize = mmu_vmalloc_psize;1732ssize = mmu_kernel_ssize;1733flags |= HPTE_USE_KERNEL_KEY;1734break;17351736case IO_REGION_ID:1737vsid = get_kernel_vsid(ea, mmu_kernel_ssize);1738psize = mmu_io_psize;1739ssize = mmu_kernel_ssize;1740flags |= HPTE_USE_KERNEL_KEY;1741break;1742default:1743/*1744* Not a valid range1745* Send the problem up to do_page_fault()1746*/1747rc = 1;1748goto bail;1749}1750DBG_LOW(" mm=%p, mm->pgdir=%p, vsid=%016lx\n", mm, mm->pgd, vsid);17511752/* Bad address. */1753if (!vsid) {1754DBG_LOW("Bad address!\n");1755rc = 1;1756goto bail;1757}1758/* Get pgdir */1759pgdir = mm->pgd;1760if (pgdir == NULL) {1761rc = 1;1762goto bail;1763}17641765/* Check CPU locality */1766if (user_region && mm_is_thread_local(mm))1767flags |= HPTE_LOCAL_UPDATE;17681769#ifndef CONFIG_PPC_64K_PAGES1770/*1771* If we use 4K pages and our psize is not 4K, then we might1772* be hitting a special driver mapping, and need to align the1773* address before we fetch the PTE.1774*1775* It could also be a hugepage mapping, in which case this is1776* not necessary, but it's not harmful, either.1777*/1778if (psize != MMU_PAGE_4K)1779ea &= ~((1ul << mmu_psize_defs[psize].shift) - 1);1780#endif /* CONFIG_PPC_64K_PAGES */17811782/* Get PTE and page size from page tables */1783ptep = find_linux_pte(pgdir, ea, &is_thp, &hugeshift);1784if (ptep == NULL || !pte_present(*ptep)) {1785DBG_LOW(" no PTE !\n");1786rc = 1;1787goto bail;1788}17891790if (IS_ENABLED(CONFIG_PPC_4K_PAGES) && !radix_enabled()) {1791if (hugeshift == PMD_SHIFT && psize == MMU_PAGE_16M)1792hugeshift = mmu_psize_defs[MMU_PAGE_16M].shift;1793if (hugeshift == PUD_SHIFT && psize == MMU_PAGE_16G)1794hugeshift = mmu_psize_defs[MMU_PAGE_16G].shift;1795}17961797/*1798* Add _PAGE_PRESENT to the required access perm. If there are parallel1799* updates to the pte that can possibly clear _PAGE_PTE, catch that too.1800*1801* We can safely use the return pte address in rest of the function1802* because we do set H_PAGE_BUSY which prevents further updates to pte1803* from generic code.1804*/1805access |= _PAGE_PRESENT | _PAGE_PTE;18061807/*1808* Pre-check access permissions (will be re-checked atomically1809* in __hash_page_XX but this pre-check is a fast path1810*/1811if (!check_pte_access(access, pte_val(*ptep))) {1812DBG_LOW(" no access !\n");1813rc = 1;1814goto bail;1815}18161817if (hugeshift) {1818if (is_thp)1819rc = __hash_page_thp(ea, access, vsid, (pmd_t *)ptep,1820trap, flags, ssize, psize);1821#ifdef CONFIG_HUGETLB_PAGE1822else1823rc = __hash_page_huge(ea, access, vsid, ptep, trap,1824flags, ssize, hugeshift, psize);1825#else1826else {1827/*1828* if we have hugeshift, and is not transhuge with1829* hugetlb disabled, something is really wrong.1830*/1831rc = 1;1832WARN_ON(1);1833}1834#endif1835if (current->mm == mm)1836check_paca_psize(ea, mm, psize, user_region);18371838goto bail;1839}18401841#ifndef CONFIG_PPC_64K_PAGES1842DBG_LOW(" i-pte: %016lx\n", pte_val(*ptep));1843#else1844DBG_LOW(" i-pte: %016lx %016lx\n", pte_val(*ptep),1845pte_val(*(ptep + PTRS_PER_PTE)));1846#endif1847/* Do actual hashing */1848#ifdef CONFIG_PPC_64K_PAGES1849/* If H_PAGE_4K_PFN is set, make sure this is a 4k segment */1850if ((pte_val(*ptep) & H_PAGE_4K_PFN) && psize == MMU_PAGE_64K) {1851demote_segment_4k(mm, ea);1852psize = MMU_PAGE_4K;1853}18541855/*1856* If this PTE is non-cacheable and we have restrictions on1857* using non cacheable large pages, then we switch to 4k1858*/1859if (mmu_ci_restrictions && psize == MMU_PAGE_64K && pte_ci(*ptep)) {1860if (user_region) {1861demote_segment_4k(mm, ea);1862psize = MMU_PAGE_4K;1863} else if (ea < VMALLOC_END) {1864/*1865* some driver did a non-cacheable mapping1866* in vmalloc space, so switch vmalloc1867* to 4k pages1868*/1869printk(KERN_ALERT "Reducing vmalloc segment "1870"to 4kB pages because of "1871"non-cacheable mapping\n");1872psize = mmu_vmalloc_psize = MMU_PAGE_4K;1873#ifdef CONFIG_SPU_BASE1874spu_flush_all_slbs(mm);1875#endif1876}1877}18781879#endif /* CONFIG_PPC_64K_PAGES */18801881if (current->mm == mm)1882check_paca_psize(ea, mm, psize, user_region);18831884#ifdef CONFIG_PPC_64K_PAGES1885if (psize == MMU_PAGE_64K)1886rc = __hash_page_64K(ea, access, vsid, ptep, trap,1887flags, ssize);1888else1889#endif /* CONFIG_PPC_64K_PAGES */1890{1891int spp = subpage_protection(mm, ea);1892if (access & spp)1893rc = -2;1894else1895rc = __hash_page_4K(ea, access, vsid, ptep, trap,1896flags, ssize, spp);1897}18981899/*1900* Dump some info in case of hash insertion failure, they should1901* never happen so it is really useful to know if/when they do1902*/1903if (rc == -1)1904hash_failure_debug(ea, access, vsid, trap, ssize, psize,1905psize, pte_val(*ptep));1906#ifndef CONFIG_PPC_64K_PAGES1907DBG_LOW(" o-pte: %016lx\n", pte_val(*ptep));1908#else1909DBG_LOW(" o-pte: %016lx %016lx\n", pte_val(*ptep),1910pte_val(*(ptep + PTRS_PER_PTE)));1911#endif1912DBG_LOW(" -> rc=%d\n", rc);19131914bail:1915return rc;1916}1917EXPORT_SYMBOL_GPL(hash_page_mm);19181919int hash_page(unsigned long ea, unsigned long access, unsigned long trap,1920unsigned long dsisr)1921{1922unsigned long flags = 0;1923struct mm_struct *mm = current->mm;19241925if ((get_region_id(ea) == VMALLOC_REGION_ID) ||1926(get_region_id(ea) == IO_REGION_ID))1927mm = &init_mm;19281929if (dsisr & DSISR_NOHPTE)1930flags |= HPTE_NOHPTE_UPDATE;19311932return hash_page_mm(mm, ea, access, trap, flags);1933}1934EXPORT_SYMBOL_GPL(hash_page);19351936DEFINE_INTERRUPT_HANDLER(do_hash_fault)1937{1938unsigned long ea = regs->dar;1939unsigned long dsisr = regs->dsisr;1940unsigned long access = _PAGE_PRESENT | _PAGE_READ;1941unsigned long flags = 0;1942struct mm_struct *mm;1943unsigned int region_id;1944long err;19451946if (unlikely(dsisr & (DSISR_BAD_FAULT_64S | DSISR_KEYFAULT))) {1947hash__do_page_fault(regs);1948return;1949}19501951region_id = get_region_id(ea);1952if ((region_id == VMALLOC_REGION_ID) || (region_id == IO_REGION_ID))1953mm = &init_mm;1954else1955mm = current->mm;19561957if (dsisr & DSISR_NOHPTE)1958flags |= HPTE_NOHPTE_UPDATE;19591960if (dsisr & DSISR_ISSTORE)1961access |= _PAGE_WRITE;1962/*1963* We set _PAGE_PRIVILEGED only when1964* kernel mode access kernel space.1965*1966* _PAGE_PRIVILEGED is NOT set1967* 1) when kernel mode access user space1968* 2) user space access kernel space.1969*/1970access |= _PAGE_PRIVILEGED;1971if (user_mode(regs) || (region_id == USER_REGION_ID))1972access &= ~_PAGE_PRIVILEGED;19731974if (TRAP(regs) == INTERRUPT_INST_STORAGE)1975access |= _PAGE_EXEC;19761977err = hash_page_mm(mm, ea, access, TRAP(regs), flags);1978if (unlikely(err < 0)) {1979// failed to insert a hash PTE due to an hypervisor error1980if (user_mode(regs)) {1981if (IS_ENABLED(CONFIG_PPC_SUBPAGE_PROT) && err == -2)1982_exception(SIGSEGV, regs, SEGV_ACCERR, ea);1983else1984_exception(SIGBUS, regs, BUS_ADRERR, ea);1985} else {1986bad_page_fault(regs, SIGBUS);1987}1988err = 0;19891990} else if (err) {1991hash__do_page_fault(regs);1992}1993}19941995static bool should_hash_preload(struct mm_struct *mm, unsigned long ea)1996{1997int psize = get_slice_psize(mm, ea);19981999/* We only prefault standard pages for now */2000if (unlikely(psize != mm_ctx_user_psize(&mm->context)))2001return false;20022003/*2004* Don't prefault if subpage protection is enabled for the EA.2005*/2006if (unlikely((psize == MMU_PAGE_4K) && subpage_protection(mm, ea)))2007return false;20082009return true;2010}20112012static void hash_preload(struct mm_struct *mm, pte_t *ptep, unsigned long ea,2013bool is_exec, unsigned long trap)2014{2015unsigned long vsid;2016pgd_t *pgdir;2017int rc, ssize, update_flags = 0;2018unsigned long access = _PAGE_PRESENT | _PAGE_READ | (is_exec ? _PAGE_EXEC : 0);2019unsigned long flags;20202021BUG_ON(get_region_id(ea) != USER_REGION_ID);20222023if (!should_hash_preload(mm, ea))2024return;20252026DBG_LOW("hash_preload(mm=%p, mm->pgdir=%p, ea=%016lx, access=%lx,"2027" trap=%lx\n", mm, mm->pgd, ea, access, trap);20282029/* Get Linux PTE if available */2030pgdir = mm->pgd;2031if (pgdir == NULL)2032return;20332034/* Get VSID */2035ssize = user_segment_size(ea);2036vsid = get_user_vsid(&mm->context, ea, ssize);2037if (!vsid)2038return;20392040#ifdef CONFIG_PPC_64K_PAGES2041/* If either H_PAGE_4K_PFN or cache inhibited is set (and we are on2042* a 64K kernel), then we don't preload, hash_page() will take2043* care of it once we actually try to access the page.2044* That way we don't have to duplicate all of the logic for segment2045* page size demotion here2046* Called with PTL held, hence can be sure the value won't change in2047* between.2048*/2049if ((pte_val(*ptep) & H_PAGE_4K_PFN) || pte_ci(*ptep))2050return;2051#endif /* CONFIG_PPC_64K_PAGES */20522053/*2054* __hash_page_* must run with interrupts off, including PMI interrupts2055* off, as it sets the H_PAGE_BUSY bit.2056*2057* It's otherwise possible for perf interrupts to hit at any time and2058* may take a hash fault reading the user stack, which could take a2059* hash miss and deadlock on the same H_PAGE_BUSY bit.2060*2061* Interrupts must also be off for the duration of the2062* mm_is_thread_local test and update, to prevent preempt running the2063* mm on another CPU (XXX: this may be racy vs kthread_use_mm).2064*/2065powerpc_local_irq_pmu_save(flags);20662067/* Is that local to this CPU ? */2068if (mm_is_thread_local(mm))2069update_flags |= HPTE_LOCAL_UPDATE;20702071/* Hash it in */2072#ifdef CONFIG_PPC_64K_PAGES2073if (mm_ctx_user_psize(&mm->context) == MMU_PAGE_64K)2074rc = __hash_page_64K(ea, access, vsid, ptep, trap,2075update_flags, ssize);2076else2077#endif /* CONFIG_PPC_64K_PAGES */2078rc = __hash_page_4K(ea, access, vsid, ptep, trap, update_flags,2079ssize, subpage_protection(mm, ea));20802081/* Dump some info in case of hash insertion failure, they should2082* never happen so it is really useful to know if/when they do2083*/2084if (rc == -1)2085hash_failure_debug(ea, access, vsid, trap, ssize,2086mm_ctx_user_psize(&mm->context),2087mm_ctx_user_psize(&mm->context),2088pte_val(*ptep));20892090powerpc_local_irq_pmu_restore(flags);2091}20922093/*2094* This is called at the end of handling a user page fault, when the2095* fault has been handled by updating a PTE in the linux page tables.2096* We use it to preload an HPTE into the hash table corresponding to2097* the updated linux PTE.2098*2099* This must always be called with the pte lock held.2100*/2101void __update_mmu_cache(struct vm_area_struct *vma, unsigned long address,2102pte_t *ptep)2103{2104/*2105* We don't need to worry about _PAGE_PRESENT here because we are2106* called with either mm->page_table_lock held or ptl lock held2107*/2108unsigned long trap;2109bool is_exec;21102111/* We only want HPTEs for linux PTEs that have _PAGE_ACCESSED set */2112if (!pte_young(*ptep) || address >= TASK_SIZE)2113return;21142115/*2116* We try to figure out if we are coming from an instruction2117* access fault and pass that down to __hash_page so we avoid2118* double-faulting on execution of fresh text. We have to test2119* for regs NULL since init will get here first thing at boot.2120*2121* We also avoid filling the hash if not coming from a fault.2122*/21232124trap = current->thread.regs ? TRAP(current->thread.regs) : 0UL;2125switch (trap) {2126case 0x300:2127is_exec = false;2128break;2129case 0x400:2130is_exec = true;2131break;2132default:2133return;2134}21352136hash_preload(vma->vm_mm, ptep, address, is_exec, trap);2137}21382139#ifdef CONFIG_PPC_TRANSACTIONAL_MEM2140static inline void tm_flush_hash_page(int local)2141{2142/*2143* Transactions are not aborted by tlbiel, only tlbie. Without, syncing a2144* page back to a block device w/PIO could pick up transactional data2145* (bad!) so we force an abort here. Before the sync the page will be2146* made read-only, which will flush_hash_page. BIG ISSUE here: if the2147* kernel uses a page from userspace without unmapping it first, it may2148* see the speculated version.2149*/2150if (local && cpu_has_feature(CPU_FTR_TM) && current->thread.regs &&2151MSR_TM_ACTIVE(current->thread.regs->msr)) {2152tm_enable();2153tm_abort(TM_CAUSE_TLBI);2154}2155}2156#else2157static inline void tm_flush_hash_page(int local)2158{2159}2160#endif21612162/*2163* Return the global hash slot, corresponding to the given PTE, which contains2164* the HPTE.2165*/2166unsigned long pte_get_hash_gslot(unsigned long vpn, unsigned long shift,2167int ssize, real_pte_t rpte, unsigned int subpg_index)2168{2169unsigned long hash, gslot, hidx;21702171hash = hpt_hash(vpn, shift, ssize);2172hidx = __rpte_to_hidx(rpte, subpg_index);2173if (hidx & _PTEIDX_SECONDARY)2174hash = ~hash;2175gslot = (hash & htab_hash_mask) * HPTES_PER_GROUP;2176gslot += hidx & _PTEIDX_GROUP_IX;2177return gslot;2178}21792180void flush_hash_page(unsigned long vpn, real_pte_t pte, int psize, int ssize,2181unsigned long flags)2182{2183unsigned long index, shift, gslot;2184int local = flags & HPTE_LOCAL_UPDATE;21852186DBG_LOW("flush_hash_page(vpn=%016lx)\n", vpn);2187pte_iterate_hashed_subpages(pte, psize, vpn, index, shift) {2188gslot = pte_get_hash_gslot(vpn, shift, ssize, pte, index);2189DBG_LOW(" sub %ld: gslot=%lx\n", index, gslot);2190/*2191* We use same base page size and actual psize, because we don't2192* use these functions for hugepage2193*/2194mmu_hash_ops.hpte_invalidate(gslot, vpn, psize, psize,2195ssize, local);2196} pte_iterate_hashed_end();21972198tm_flush_hash_page(local);2199}22002201#ifdef CONFIG_TRANSPARENT_HUGEPAGE2202void flush_hash_hugepage(unsigned long vsid, unsigned long addr,2203pmd_t *pmdp, unsigned int psize, int ssize,2204unsigned long flags)2205{2206int i, max_hpte_count, valid;2207unsigned long s_addr;2208unsigned char *hpte_slot_array;2209unsigned long hidx, shift, vpn, hash, slot;2210int local = flags & HPTE_LOCAL_UPDATE;22112212s_addr = addr & HPAGE_PMD_MASK;2213hpte_slot_array = get_hpte_slot_array(pmdp);2214/*2215* IF we try to do a HUGE PTE update after a withdraw is done.2216* we will find the below NULL. This happens when we do2217* split_huge_pmd2218*/2219if (!hpte_slot_array)2220return;22212222if (mmu_hash_ops.hugepage_invalidate) {2223mmu_hash_ops.hugepage_invalidate(vsid, s_addr, hpte_slot_array,2224psize, ssize, local);2225goto tm_abort;2226}2227/*2228* No bluk hpte removal support, invalidate each entry2229*/2230shift = mmu_psize_defs[psize].shift;2231max_hpte_count = HPAGE_PMD_SIZE >> shift;2232for (i = 0; i < max_hpte_count; i++) {2233/*2234* 8 bits per each hpte entries2235* 000| [ secondary group (one bit) | hidx (3 bits) | valid bit]2236*/2237valid = hpte_valid(hpte_slot_array, i);2238if (!valid)2239continue;2240hidx = hpte_hash_index(hpte_slot_array, i);22412242/* get the vpn */2243addr = s_addr + (i * (1ul << shift));2244vpn = hpt_vpn(addr, vsid, ssize);2245hash = hpt_hash(vpn, shift, ssize);2246if (hidx & _PTEIDX_SECONDARY)2247hash = ~hash;22482249slot = (hash & htab_hash_mask) * HPTES_PER_GROUP;2250slot += hidx & _PTEIDX_GROUP_IX;2251mmu_hash_ops.hpte_invalidate(slot, vpn, psize,2252MMU_PAGE_16M, ssize, local);2253}2254tm_abort:2255tm_flush_hash_page(local);2256}2257#endif /* CONFIG_TRANSPARENT_HUGEPAGE */22582259void flush_hash_range(unsigned long number, int local)2260{2261if (mmu_hash_ops.flush_hash_range)2262mmu_hash_ops.flush_hash_range(number, local);2263else {2264int i;2265struct ppc64_tlb_batch *batch =2266this_cpu_ptr(&ppc64_tlb_batch);22672268for (i = 0; i < number; i++)2269flush_hash_page(batch->vpn[i], batch->pte[i],2270batch->psize, batch->ssize, local);2271}2272}22732274long hpte_insert_repeating(unsigned long hash, unsigned long vpn,2275unsigned long pa, unsigned long rflags,2276unsigned long vflags, int psize, int ssize)2277{2278unsigned long hpte_group;2279long slot;22802281repeat:2282hpte_group = (hash & htab_hash_mask) * HPTES_PER_GROUP;22832284/* Insert into the hash table, primary slot */2285slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags, vflags,2286psize, psize, ssize);22872288/* Primary is full, try the secondary */2289if (unlikely(slot == -1)) {2290hpte_group = (~hash & htab_hash_mask) * HPTES_PER_GROUP;2291slot = mmu_hash_ops.hpte_insert(hpte_group, vpn, pa, rflags,2292vflags | HPTE_V_SECONDARY,2293psize, psize, ssize);2294if (slot == -1) {2295if (mftb() & 0x1)2296hpte_group = (hash & htab_hash_mask) *2297HPTES_PER_GROUP;22982299mmu_hash_ops.hpte_remove(hpte_group);2300goto repeat;2301}2302}23032304return slot;2305}23062307void hpt_clear_stress(void)2308{2309int cpu = raw_smp_processor_id();2310int g;23112312for (g = 0; g < stress_nr_groups(); g++) {2313unsigned long last_group;2314last_group = stress_hpt_struct[cpu].last_group[g];23152316if (last_group != -1UL) {2317int i;2318for (i = 0; i < HPTES_PER_GROUP; i++) {2319if (mmu_hash_ops.hpte_remove(last_group) == -1)2320break;2321}2322stress_hpt_struct[cpu].last_group[g] = -1;2323}2324}2325}23262327void hpt_do_stress(unsigned long ea, unsigned long hpte_group)2328{2329unsigned long last_group;2330int cpu = raw_smp_processor_id();23312332last_group = stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1];2333if (hpte_group == last_group)2334return;23352336if (last_group != -1UL) {2337int i;2338/*2339* Concurrent CPUs might be inserting into this group, so2340* give up after a number of iterations, to prevent a live2341* lock.2342*/2343for (i = 0; i < HPTES_PER_GROUP; i++) {2344if (mmu_hash_ops.hpte_remove(last_group) == -1)2345break;2346}2347stress_hpt_struct[cpu].last_group[stress_nr_groups() - 1] = -1;2348}23492350if (ea >= PAGE_OFFSET) {2351/*2352* We would really like to prefetch to get the TLB loaded, then2353* remove the PTE before returning from fault interrupt, to2354* increase the hash fault rate.2355*2356* Unfortunately QEMU TCG does not model the TLB in a way that2357* makes this possible, and systemsim (mambo) emulator does not2358* bring in TLBs with prefetches (although loads/stores do2359* work for non-CI PTEs).2360*2361* So remember this PTE and clear it on the next hash fault.2362*/2363memmove(&stress_hpt_struct[cpu].last_group[1],2364&stress_hpt_struct[cpu].last_group[0],2365(stress_nr_groups() - 1) * sizeof(unsigned long));2366stress_hpt_struct[cpu].last_group[0] = hpte_group;2367}2368}23692370void hash__setup_initial_memory_limit(phys_addr_t first_memblock_base,2371phys_addr_t first_memblock_size)2372{2373/*2374* We don't currently support the first MEMBLOCK not mapping 02375* physical on those processors2376*/2377BUG_ON(first_memblock_base != 0);23782379/*2380* On virtualized systems the first entry is our RMA region aka VRMA,2381* non-virtualized 64-bit hash MMU systems don't have a limitation2382* on real mode access.2383*2384* For guests on platforms before POWER9, we clamp the it limit to 1G2385* to avoid some funky things such as RTAS bugs etc...2386*2387* On POWER9 we limit to 1TB in case the host erroneously told us that2388* the RMA was >1TB. Effective address bits 0:23 are treated as zero2389* (meaning the access is aliased to zero i.e. addr = addr % 1TB)2390* for virtual real mode addressing and so it doesn't make sense to2391* have an area larger than 1TB as it can't be addressed.2392*/2393if (!early_cpu_has_feature(CPU_FTR_HVMODE)) {2394ppc64_rma_size = first_memblock_size;2395if (!early_cpu_has_feature(CPU_FTR_ARCH_300))2396ppc64_rma_size = min_t(u64, ppc64_rma_size, 0x40000000);2397else2398ppc64_rma_size = min_t(u64, ppc64_rma_size,23991UL << SID_SHIFT_1T);24002401/* Finally limit subsequent allocations */2402memblock_set_current_limit(ppc64_rma_size);2403} else {2404ppc64_rma_size = ULONG_MAX;2405}2406}24072408#ifdef CONFIG_DEBUG_FS24092410static int hpt_order_get(void *data, u64 *val)2411{2412*val = ppc64_pft_size;2413return 0;2414}24152416static int hpt_order_set(void *data, u64 val)2417{2418int ret;24192420if (!mmu_hash_ops.resize_hpt)2421return -ENODEV;24222423cpus_read_lock();2424ret = mmu_hash_ops.resize_hpt(val);2425cpus_read_unlock();24262427return ret;2428}24292430DEFINE_DEBUGFS_ATTRIBUTE(fops_hpt_order, hpt_order_get, hpt_order_set, "%llu\n");24312432static int __init hash64_debugfs(void)2433{2434debugfs_create_file("hpt_order", 0600, arch_debugfs_dir, NULL,2435&fops_hpt_order);2436return 0;2437}2438machine_device_initcall(pseries, hash64_debugfs);2439#endif /* CONFIG_DEBUG_FS */24402441void __init print_system_hash_info(void)2442{2443pr_info("ppc64_pft_size = 0x%llx\n", ppc64_pft_size);24442445if (htab_hash_mask)2446pr_info("htab_hash_mask = 0x%lx\n", htab_hash_mask);2447}24482449unsigned long arch_randomize_brk(struct mm_struct *mm)2450{2451/*2452* If we are using 1TB segments and we are allowed to randomise2453* the heap, we can put it above 1TB so it is backed by a 1TB2454* segment. Otherwise the heap will be in the bottom 1TB2455* which always uses 256MB segments and this may result in a2456* performance penalty.2457*/2458if (is_32bit_task())2459return randomize_page(mm->brk, SZ_32M);2460else if (!radix_enabled() && mmu_highuser_ssize == MMU_SEGSIZE_1T)2461return randomize_page(max_t(unsigned long, mm->brk, SZ_1T), SZ_1G);2462else2463return randomize_page(mm->brk, SZ_1G);2464}246524662467