// SPDX-License-Identifier: GPL-2.0-only1#include <linux/init.h>23#include <linux/mm.h>4#include <linux/spinlock.h>5#include <linux/smp.h>6#include <linux/interrupt.h>7#include <linux/export.h>8#include <linux/cpu.h>9#include <linux/debugfs.h>10#include <linux/sched/smt.h>11#include <linux/task_work.h>12#include <linux/mmu_notifier.h>13#include <linux/mmu_context.h>14#include <linux/kvm_types.h>1516#include <asm/tlbflush.h>17#include <asm/mmu_context.h>18#include <asm/nospec-branch.h>19#include <asm/cache.h>20#include <asm/cacheflush.h>21#include <asm/apic.h>22#include <asm/msr.h>23#include <asm/perf_event.h>24#include <asm/tlb.h>2526#include "mm_internal.h"2728#ifdef CONFIG_PARAVIRT29# define STATIC_NOPV30#else31# define STATIC_NOPV static32# define __flush_tlb_local native_flush_tlb_local33# define __flush_tlb_global native_flush_tlb_global34# define __flush_tlb_one_user(addr) native_flush_tlb_one_user(addr)35# define __flush_tlb_multi(msk, info) native_flush_tlb_multi(msk, info)36#endif3738/*39* TLB flushing, formerly SMP-only40* c/o Linus Torvalds.41*42* These mean you can really definitely utterly forget about43* writing to user space from interrupts. (Its not allowed anyway).44*45* Optimizations Manfred Spraul <[email protected]>46*47* More scalable flush, from Andi Kleen48*49* Implement flush IPI by CALL_FUNCTION_VECTOR, Alex Shi50*/5152/*53* Bits to mangle the TIF_SPEC_* state into the mm pointer which is54* stored in cpu_tlb_state.last_user_mm_spec.55*/56#define LAST_USER_MM_IBPB 0x1UL57#define LAST_USER_MM_L1D_FLUSH 0x2UL58#define LAST_USER_MM_SPEC_MASK (LAST_USER_MM_IBPB | LAST_USER_MM_L1D_FLUSH)5960/* Bits to set when tlbstate and flush is (re)initialized */61#define LAST_USER_MM_INIT LAST_USER_MM_IBPB6263/*64* The x86 feature is called PCID (Process Context IDentifier). It is similar65* to what is traditionally called ASID on the RISC processors.66*67* We don't use the traditional ASID implementation, where each process/mm gets68* its own ASID and flush/restart when we run out of ASID space.69*70* Instead we have a small per-cpu array of ASIDs and cache the last few mm's71* that came by on this CPU, allowing cheaper switch_mm between processes on72* this CPU.73*74* We end up with different spaces for different things. To avoid confusion we75* use different names for each of them:76*77* ASID - [0, TLB_NR_DYN_ASIDS-1]78* the canonical identifier for an mm, dynamically allocated on each CPU79* [TLB_NR_DYN_ASIDS, MAX_ASID_AVAILABLE-1]80* the canonical, global identifier for an mm, identical across all CPUs81*82* kPCID - [1, MAX_ASID_AVAILABLE]83* the value we write into the PCID part of CR3; corresponds to the84* ASID+1, because PCID 0 is special.85*86* uPCID - [2048 + 1, 2048 + MAX_ASID_AVAILABLE]87* for KPTI each mm has two address spaces and thus needs two88* PCID values, but we can still do with a single ASID denomination89* for each mm. Corresponds to kPCID + 2048.90*91*/9293/*94* When enabled, MITIGATION_PAGE_TABLE_ISOLATION consumes a single bit for95* user/kernel switches96*/97#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION98# define PTI_CONSUMED_PCID_BITS 199#else100# define PTI_CONSUMED_PCID_BITS 0101#endif102103#define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS)104105/*106* ASIDs are zero-based: 0->MAX_AVAIL_ASID are valid. -1 below to account107* for them being zero-based. Another -1 is because PCID 0 is reserved for108* use by non-PCID-aware users.109*/110#define MAX_ASID_AVAILABLE ((1 << CR3_AVAIL_PCID_BITS) - 2)111112/*113* Given @asid, compute kPCID114*/115static inline u16 kern_pcid(u16 asid)116{117VM_WARN_ON_ONCE(asid > MAX_ASID_AVAILABLE);118119#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION120/*121* Make sure that the dynamic ASID space does not conflict with the122* bit we are using to switch between user and kernel ASIDs.123*/124BUILD_BUG_ON(TLB_NR_DYN_ASIDS >= (1 << X86_CR3_PTI_PCID_USER_BIT));125126/*127* The ASID being passed in here should have respected the128* MAX_ASID_AVAILABLE and thus never have the switch bit set.129*/130VM_WARN_ON_ONCE(asid & (1 << X86_CR3_PTI_PCID_USER_BIT));131#endif132/*133* The dynamically-assigned ASIDs that get passed in are small134* (<TLB_NR_DYN_ASIDS). They never have the high switch bit set,135* so do not bother to clear it.136*137* If PCID is on, ASID-aware code paths put the ASID+1 into the138* PCID bits. This serves two purposes. It prevents a nasty139* situation in which PCID-unaware code saves CR3, loads some other140* value (with PCID == 0), and then restores CR3, thus corrupting141* the TLB for ASID 0 if the saved ASID was nonzero. It also means142* that any bugs involving loading a PCID-enabled CR3 with143* CR4.PCIDE off will trigger deterministically.144*/145return asid + 1;146}147148/*149* Given @asid, compute uPCID150*/151static inline u16 user_pcid(u16 asid)152{153u16 ret = kern_pcid(asid);154#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION155ret |= 1 << X86_CR3_PTI_PCID_USER_BIT;156#endif157return ret;158}159160static inline unsigned long build_cr3(pgd_t *pgd, u16 asid, unsigned long lam)161{162unsigned long cr3 = __sme_pa(pgd) | lam;163164if (static_cpu_has(X86_FEATURE_PCID)) {165cr3 |= kern_pcid(asid);166} else {167VM_WARN_ON_ONCE(asid != 0);168}169170return cr3;171}172173static inline unsigned long build_cr3_noflush(pgd_t *pgd, u16 asid,174unsigned long lam)175{176/*177* Use boot_cpu_has() instead of this_cpu_has() as this function178* might be called during early boot. This should work even after179* boot because all CPU's the have same capabilities:180*/181VM_WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_PCID));182return build_cr3(pgd, asid, lam) | CR3_NOFLUSH;183}184185/*186* We get here when we do something requiring a TLB invalidation187* but could not go invalidate all of the contexts. We do the188* necessary invalidation by clearing out the 'ctx_id' which189* forces a TLB flush when the context is loaded.190*/191static void clear_asid_other(void)192{193u16 asid;194195/*196* This is only expected to be set if we have disabled197* kernel _PAGE_GLOBAL pages.198*/199if (!static_cpu_has(X86_FEATURE_PTI)) {200WARN_ON_ONCE(1);201return;202}203204for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {205/* Do not need to flush the current asid */206if (asid == this_cpu_read(cpu_tlbstate.loaded_mm_asid))207continue;208/*209* Make sure the next time we go to switch to210* this asid, we do a flush:211*/212this_cpu_write(cpu_tlbstate.ctxs[asid].ctx_id, 0);213}214this_cpu_write(cpu_tlbstate.invalidate_other, false);215}216217atomic64_t last_mm_ctx_id = ATOMIC64_INIT(1);218219struct new_asid {220unsigned int asid : 16;221unsigned int need_flush : 1;222};223224static struct new_asid choose_new_asid(struct mm_struct *next, u64 next_tlb_gen)225{226struct new_asid ns;227u16 asid;228229if (!static_cpu_has(X86_FEATURE_PCID)) {230ns.asid = 0;231ns.need_flush = 1;232return ns;233}234235/*236* TLB consistency for global ASIDs is maintained with hardware assisted237* remote TLB flushing. Global ASIDs are always up to date.238*/239if (cpu_feature_enabled(X86_FEATURE_INVLPGB)) {240u16 global_asid = mm_global_asid(next);241242if (global_asid) {243ns.asid = global_asid;244ns.need_flush = 0;245return ns;246}247}248249if (this_cpu_read(cpu_tlbstate.invalidate_other))250clear_asid_other();251252for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {253if (this_cpu_read(cpu_tlbstate.ctxs[asid].ctx_id) !=254next->context.ctx_id)255continue;256257ns.asid = asid;258ns.need_flush = (this_cpu_read(cpu_tlbstate.ctxs[asid].tlb_gen) < next_tlb_gen);259return ns;260}261262/*263* We don't currently own an ASID slot on this CPU.264* Allocate a slot.265*/266ns.asid = this_cpu_add_return(cpu_tlbstate.next_asid, 1) - 1;267if (ns.asid >= TLB_NR_DYN_ASIDS) {268ns.asid = 0;269this_cpu_write(cpu_tlbstate.next_asid, 1);270}271ns.need_flush = true;272273return ns;274}275276/*277* Global ASIDs are allocated for multi-threaded processes that are278* active on multiple CPUs simultaneously, giving each of those279* processes the same PCID on every CPU, for use with hardware-assisted280* TLB shootdown on remote CPUs, like AMD INVLPGB or Intel RAR.281*282* These global ASIDs are held for the lifetime of the process.283*/284static DEFINE_RAW_SPINLOCK(global_asid_lock);285static u16 last_global_asid = MAX_ASID_AVAILABLE;286static DECLARE_BITMAP(global_asid_used, MAX_ASID_AVAILABLE);287static DECLARE_BITMAP(global_asid_freed, MAX_ASID_AVAILABLE);288static int global_asid_available = MAX_ASID_AVAILABLE - TLB_NR_DYN_ASIDS - 1;289290/*291* When the search for a free ASID in the global ASID space reaches292* MAX_ASID_AVAILABLE, a global TLB flush guarantees that previously293* freed global ASIDs are safe to re-use.294*295* This way the global flush only needs to happen at ASID rollover296* time, and not at ASID allocation time.297*/298static void reset_global_asid_space(void)299{300lockdep_assert_held(&global_asid_lock);301302invlpgb_flush_all_nonglobals();303304/*305* The TLB flush above makes it safe to re-use the previously306* freed global ASIDs.307*/308bitmap_andnot(global_asid_used, global_asid_used,309global_asid_freed, MAX_ASID_AVAILABLE);310bitmap_clear(global_asid_freed, 0, MAX_ASID_AVAILABLE);311312/* Restart the search from the start of global ASID space. */313last_global_asid = TLB_NR_DYN_ASIDS;314}315316static u16 allocate_global_asid(void)317{318u16 asid;319320lockdep_assert_held(&global_asid_lock);321322/* The previous allocation hit the edge of available address space */323if (last_global_asid >= MAX_ASID_AVAILABLE - 1)324reset_global_asid_space();325326asid = find_next_zero_bit(global_asid_used, MAX_ASID_AVAILABLE, last_global_asid);327328if (asid >= MAX_ASID_AVAILABLE && !global_asid_available) {329/* This should never happen. */330VM_WARN_ONCE(1, "Unable to allocate global ASID despite %d available\n",331global_asid_available);332return 0;333}334335/* Claim this global ASID. */336__set_bit(asid, global_asid_used);337last_global_asid = asid;338global_asid_available--;339return asid;340}341342/*343* Check whether a process is currently active on more than @threshold CPUs.344* This is a cheap estimation on whether or not it may make sense to assign345* a global ASID to this process, and use broadcast TLB invalidation.346*/347static bool mm_active_cpus_exceeds(struct mm_struct *mm, int threshold)348{349int count = 0;350int cpu;351352/* This quick check should eliminate most single threaded programs. */353if (cpumask_weight(mm_cpumask(mm)) <= threshold)354return false;355356/* Slower check to make sure. */357for_each_cpu(cpu, mm_cpumask(mm)) {358/* Skip the CPUs that aren't really running this process. */359if (per_cpu(cpu_tlbstate.loaded_mm, cpu) != mm)360continue;361362if (per_cpu(cpu_tlbstate_shared.is_lazy, cpu))363continue;364365if (++count > threshold)366return true;367}368return false;369}370371/*372* Assign a global ASID to the current process, protecting against373* races between multiple threads in the process.374*/375static void use_global_asid(struct mm_struct *mm)376{377u16 asid;378379guard(raw_spinlock_irqsave)(&global_asid_lock);380381/* This process is already using broadcast TLB invalidation. */382if (mm_global_asid(mm))383return;384385/*386* The last global ASID was consumed while waiting for the lock.387*388* If this fires, a more aggressive ASID reuse scheme might be389* needed.390*/391if (!global_asid_available) {392VM_WARN_ONCE(1, "Ran out of global ASIDs\n");393return;394}395396asid = allocate_global_asid();397if (!asid)398return;399400mm_assign_global_asid(mm, asid);401}402403#ifdef CONFIG_BROADCAST_TLB_FLUSH404void mm_free_global_asid(struct mm_struct *mm)405{406if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))407return;408409if (!mm_global_asid(mm))410return;411412guard(raw_spinlock_irqsave)(&global_asid_lock);413414/* The global ASID can be re-used only after flush at wrap-around. */415__set_bit(mm->context.global_asid, global_asid_freed);416417mm->context.global_asid = 0;418global_asid_available++;419}420#endif421422/*423* Is the mm transitioning from a CPU-local ASID to a global ASID?424*/425static bool mm_needs_global_asid(struct mm_struct *mm, u16 asid)426{427u16 global_asid = mm_global_asid(mm);428429if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))430return false;431432/* Process is transitioning to a global ASID */433if (global_asid && asid != global_asid)434return true;435436return false;437}438439/*440* x86 has 4k ASIDs (2k when compiled with KPTI), but the largest x86441* systems have over 8k CPUs. Because of this potential ASID shortage,442* global ASIDs are handed out to processes that have frequent TLB443* flushes and are active on 4 or more CPUs simultaneously.444*/445static void consider_global_asid(struct mm_struct *mm)446{447if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))448return;449450/* Check every once in a while. */451if ((current->pid & 0x1f) != (jiffies & 0x1f))452return;453454/*455* Assign a global ASID if the process is active on456* 4 or more CPUs simultaneously.457*/458if (mm_active_cpus_exceeds(mm, 3))459use_global_asid(mm);460}461462static void finish_asid_transition(struct flush_tlb_info *info)463{464struct mm_struct *mm = info->mm;465int bc_asid = mm_global_asid(mm);466int cpu;467468if (!mm_in_asid_transition(mm))469return;470471for_each_cpu(cpu, mm_cpumask(mm)) {472/*473* The remote CPU is context switching. Wait for that to474* finish, to catch the unlikely case of it switching to475* the target mm with an out of date ASID.476*/477while (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm, cpu)) == LOADED_MM_SWITCHING)478cpu_relax();479480if (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm, cpu)) != mm)481continue;482483/*484* If at least one CPU is not using the global ASID yet,485* send a TLB flush IPI. The IPI should cause stragglers486* to transition soon.487*488* This can race with the CPU switching to another task;489* that results in a (harmless) extra IPI.490*/491if (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm_asid, cpu)) != bc_asid) {492flush_tlb_multi(mm_cpumask(info->mm), info);493return;494}495}496497/* All the CPUs running this process are using the global ASID. */498mm_clear_asid_transition(mm);499}500501static void broadcast_tlb_flush(struct flush_tlb_info *info)502{503bool pmd = info->stride_shift == PMD_SHIFT;504unsigned long asid = mm_global_asid(info->mm);505unsigned long addr = info->start;506507/*508* TLB flushes with INVLPGB are kicked off asynchronously.509* The inc_mm_tlb_gen() guarantees page table updates are done510* before these TLB flushes happen.511*/512if (info->end == TLB_FLUSH_ALL) {513invlpgb_flush_single_pcid_nosync(kern_pcid(asid));514/* Do any CPUs supporting INVLPGB need PTI? */515if (cpu_feature_enabled(X86_FEATURE_PTI))516invlpgb_flush_single_pcid_nosync(user_pcid(asid));517} else do {518unsigned long nr = 1;519520if (info->stride_shift <= PMD_SHIFT) {521nr = (info->end - addr) >> info->stride_shift;522nr = clamp_val(nr, 1, invlpgb_count_max);523}524525invlpgb_flush_user_nr_nosync(kern_pcid(asid), addr, nr, pmd);526if (cpu_feature_enabled(X86_FEATURE_PTI))527invlpgb_flush_user_nr_nosync(user_pcid(asid), addr, nr, pmd);528529addr += nr << info->stride_shift;530} while (addr < info->end);531532finish_asid_transition(info);533534/* Wait for the INVLPGBs kicked off above to finish. */535__tlbsync();536}537538/*539* Given an ASID, flush the corresponding user ASID. We can delay this540* until the next time we switch to it.541*542* See SWITCH_TO_USER_CR3.543*/544static inline void invalidate_user_asid(u16 asid)545{546/* There is no user ASID if address space separation is off */547if (!IS_ENABLED(CONFIG_MITIGATION_PAGE_TABLE_ISOLATION))548return;549550/*551* We only have a single ASID if PCID is off and the CR3552* write will have flushed it.553*/554if (!cpu_feature_enabled(X86_FEATURE_PCID))555return;556557if (!static_cpu_has(X86_FEATURE_PTI))558return;559560__set_bit(kern_pcid(asid),561(unsigned long *)this_cpu_ptr(&cpu_tlbstate.user_pcid_flush_mask));562}563564static void load_new_mm_cr3(pgd_t *pgdir, u16 new_asid, unsigned long lam,565bool need_flush)566{567unsigned long new_mm_cr3;568569if (need_flush) {570invalidate_user_asid(new_asid);571new_mm_cr3 = build_cr3(pgdir, new_asid, lam);572} else {573new_mm_cr3 = build_cr3_noflush(pgdir, new_asid, lam);574}575576/*577* Caution: many callers of this function expect578* that load_cr3() is serializing and orders TLB579* fills with respect to the mm_cpumask writes.580*/581write_cr3(new_mm_cr3);582}583584void leave_mm(void)585{586struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);587588/*589* It's plausible that we're in lazy TLB mode while our mm is init_mm.590* If so, our callers still expect us to flush the TLB, but there591* aren't any user TLB entries in init_mm to worry about.592*593* This needs to happen before any other sanity checks due to594* intel_idle's shenanigans.595*/596if (loaded_mm == &init_mm)597return;598599/* Warn if we're not lazy. */600WARN_ON(!this_cpu_read(cpu_tlbstate_shared.is_lazy));601602switch_mm(NULL, &init_mm, NULL);603}604EXPORT_SYMBOL_GPL(leave_mm);605606void switch_mm(struct mm_struct *prev, struct mm_struct *next,607struct task_struct *tsk)608{609unsigned long flags;610611local_irq_save(flags);612switch_mm_irqs_off(NULL, next, tsk);613local_irq_restore(flags);614}615616/*617* Invoked from return to user/guest by a task that opted-in to L1D618* flushing but ended up running on an SMT enabled core due to wrong619* affinity settings or CPU hotplug. This is part of the paranoid L1D flush620* contract which this task requested.621*/622static void l1d_flush_force_sigbus(struct callback_head *ch)623{624force_sig(SIGBUS);625}626627static void l1d_flush_evaluate(unsigned long prev_mm, unsigned long next_mm,628struct task_struct *next)629{630/* Flush L1D if the outgoing task requests it */631if (prev_mm & LAST_USER_MM_L1D_FLUSH)632wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);633634/* Check whether the incoming task opted in for L1D flush */635if (likely(!(next_mm & LAST_USER_MM_L1D_FLUSH)))636return;637638/*639* Validate that it is not running on an SMT sibling as this would640* make the exercise pointless because the siblings share L1D. If641* it runs on a SMT sibling, notify it with SIGBUS on return to642* user/guest643*/644if (this_cpu_read(cpu_info.smt_active)) {645clear_ti_thread_flag(&next->thread_info, TIF_SPEC_L1D_FLUSH);646next->l1d_flush_kill.func = l1d_flush_force_sigbus;647task_work_add(next, &next->l1d_flush_kill, TWA_RESUME);648}649}650651static unsigned long mm_mangle_tif_spec_bits(struct task_struct *next)652{653unsigned long next_tif = read_task_thread_flags(next);654unsigned long spec_bits = (next_tif >> TIF_SPEC_IB) & LAST_USER_MM_SPEC_MASK;655656/*657* Ensure that the bit shift above works as expected and the two flags658* end up in bit 0 and 1.659*/660BUILD_BUG_ON(TIF_SPEC_L1D_FLUSH != TIF_SPEC_IB + 1);661662return (unsigned long)next->mm | spec_bits;663}664665static void cond_mitigation(struct task_struct *next)666{667unsigned long prev_mm, next_mm;668669if (!next || !next->mm)670return;671672next_mm = mm_mangle_tif_spec_bits(next);673prev_mm = this_cpu_read(cpu_tlbstate.last_user_mm_spec);674675/*676* Avoid user->user BTB/RSB poisoning by flushing them when switching677* between processes. This stops one process from doing Spectre-v2678* attacks on another.679*680* Both, the conditional and the always IBPB mode use the mm681* pointer to avoid the IBPB when switching between tasks of the682* same process. Using the mm pointer instead of mm->context.ctx_id683* opens a hypothetical hole vs. mm_struct reuse, which is more or684* less impossible to control by an attacker. Aside of that it685* would only affect the first schedule so the theoretically686* exposed data is not really interesting.687*/688if (static_branch_likely(&switch_mm_cond_ibpb)) {689/*690* This is a bit more complex than the always mode because691* it has to handle two cases:692*693* 1) Switch from a user space task (potential attacker)694* which has TIF_SPEC_IB set to a user space task695* (potential victim) which has TIF_SPEC_IB not set.696*697* 2) Switch from a user space task (potential attacker)698* which has TIF_SPEC_IB not set to a user space task699* (potential victim) which has TIF_SPEC_IB set.700*701* This could be done by unconditionally issuing IBPB when702* a task which has TIF_SPEC_IB set is either scheduled in703* or out. Though that results in two flushes when:704*705* - the same user space task is scheduled out and later706* scheduled in again and only a kernel thread ran in707* between.708*709* - a user space task belonging to the same process is710* scheduled in after a kernel thread ran in between711*712* - a user space task belonging to the same process is713* scheduled in immediately.714*715* Optimize this with reasonably small overhead for the716* above cases. Mangle the TIF_SPEC_IB bit into the mm717* pointer of the incoming task which is stored in718* cpu_tlbstate.last_user_mm_spec for comparison.719*720* Issue IBPB only if the mm's are different and one or721* both have the IBPB bit set.722*/723if (next_mm != prev_mm &&724(next_mm | prev_mm) & LAST_USER_MM_IBPB)725indirect_branch_prediction_barrier();726}727728if (static_branch_unlikely(&switch_mm_always_ibpb)) {729/*730* Only flush when switching to a user space task with a731* different context than the user space task which ran732* last on this CPU.733*/734if ((prev_mm & ~LAST_USER_MM_SPEC_MASK) != (unsigned long)next->mm)735indirect_branch_prediction_barrier();736}737738if (static_branch_unlikely(&switch_mm_cond_l1d_flush)) {739/*740* Flush L1D when the outgoing task requested it and/or741* check whether the incoming task requested L1D flushing742* and ended up on an SMT sibling.743*/744if (unlikely((prev_mm | next_mm) & LAST_USER_MM_L1D_FLUSH))745l1d_flush_evaluate(prev_mm, next_mm, next);746}747748this_cpu_write(cpu_tlbstate.last_user_mm_spec, next_mm);749}750751#ifdef CONFIG_PERF_EVENTS752static inline void cr4_update_pce_mm(struct mm_struct *mm)753{754if (static_branch_unlikely(&rdpmc_always_available_key) ||755(!static_branch_unlikely(&rdpmc_never_available_key) &&756atomic_read(&mm->context.perf_rdpmc_allowed))) {757/*758* Clear the existing dirty counters to759* prevent the leak for an RDPMC task.760*/761perf_clear_dirty_counters();762cr4_set_bits_irqsoff(X86_CR4_PCE);763} else764cr4_clear_bits_irqsoff(X86_CR4_PCE);765}766767void cr4_update_pce(void *ignored)768{769cr4_update_pce_mm(this_cpu_read(cpu_tlbstate.loaded_mm));770}771772#else773static inline void cr4_update_pce_mm(struct mm_struct *mm) { }774#endif775776/*777* This optimizes when not actually switching mm's. Some architectures use the778* 'unused' argument for this optimization, but x86 must use779* 'cpu_tlbstate.loaded_mm' instead because it does not always keep780* 'current->active_mm' up to date.781*/782void switch_mm_irqs_off(struct mm_struct *unused, struct mm_struct *next,783struct task_struct *tsk)784{785struct mm_struct *prev = this_cpu_read(cpu_tlbstate.loaded_mm);786u16 prev_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);787bool was_lazy = this_cpu_read(cpu_tlbstate_shared.is_lazy);788unsigned cpu = smp_processor_id();789unsigned long new_lam;790struct new_asid ns;791u64 next_tlb_gen;792793794/* We don't want flush_tlb_func() to run concurrently with us. */795if (IS_ENABLED(CONFIG_PROVE_LOCKING))796WARN_ON_ONCE(!irqs_disabled());797798/*799* Verify that CR3 is what we think it is. This will catch800* hypothetical buggy code that directly switches to swapper_pg_dir801* without going through leave_mm() / switch_mm_irqs_off() or that802* does something like write_cr3(read_cr3_pa()).803*804* Only do this check if CONFIG_DEBUG_VM=y because __read_cr3()805* isn't free.806*/807#ifdef CONFIG_DEBUG_VM808if (WARN_ON_ONCE(__read_cr3() != build_cr3(prev->pgd, prev_asid,809tlbstate_lam_cr3_mask()))) {810/*811* If we were to BUG here, we'd be very likely to kill812* the system so hard that we don't see the call trace.813* Try to recover instead by ignoring the error and doing814* a global flush to minimize the chance of corruption.815*816* (This is far from being a fully correct recovery.817* Architecturally, the CPU could prefetch something818* back into an incorrect ASID slot and leave it there819* to cause trouble down the road. It's better than820* nothing, though.)821*/822__flush_tlb_all();823}824#endif825if (was_lazy)826this_cpu_write(cpu_tlbstate_shared.is_lazy, false);827828/*829* The membarrier system call requires a full memory barrier and830* core serialization before returning to user-space, after831* storing to rq->curr, when changing mm. This is because832* membarrier() sends IPIs to all CPUs that are in the target mm833* to make them issue memory barriers. However, if another CPU834* switches to/from the target mm concurrently with835* membarrier(), it can cause that CPU not to receive an IPI836* when it really should issue a memory barrier. Writing to CR3837* provides that full memory barrier and core serializing838* instruction.839*/840if (prev == next) {841/* Not actually switching mm's */842VM_WARN_ON(is_dyn_asid(prev_asid) &&843this_cpu_read(cpu_tlbstate.ctxs[prev_asid].ctx_id) !=844next->context.ctx_id);845846/*847* If this races with another thread that enables lam, 'new_lam'848* might not match tlbstate_lam_cr3_mask().849*/850851/*852* Even in lazy TLB mode, the CPU should stay set in the853* mm_cpumask. The TLB shootdown code can figure out from854* cpu_tlbstate_shared.is_lazy whether or not to send an IPI.855*/856if (IS_ENABLED(CONFIG_DEBUG_VM) &&857WARN_ON_ONCE(prev != &init_mm && !is_notrack_mm(prev) &&858!cpumask_test_cpu(cpu, mm_cpumask(next))))859cpumask_set_cpu(cpu, mm_cpumask(next));860861/* Check if the current mm is transitioning to a global ASID */862if (mm_needs_global_asid(next, prev_asid)) {863next_tlb_gen = atomic64_read(&next->context.tlb_gen);864ns = choose_new_asid(next, next_tlb_gen);865goto reload_tlb;866}867868/*869* Broadcast TLB invalidation keeps this ASID up to date870* all the time.871*/872if (is_global_asid(prev_asid))873return;874875/*876* If the CPU is not in lazy TLB mode, we are just switching877* from one thread in a process to another thread in the same878* process. No TLB flush required.879*/880if (!was_lazy)881return;882883/*884* Read the tlb_gen to check whether a flush is needed.885* If the TLB is up to date, just use it.886* The barrier synchronizes with the tlb_gen increment in887* the TLB shootdown code.888*/889smp_mb();890next_tlb_gen = atomic64_read(&next->context.tlb_gen);891if (this_cpu_read(cpu_tlbstate.ctxs[prev_asid].tlb_gen) ==892next_tlb_gen)893return;894895/*896* TLB contents went out of date while we were in lazy897* mode. Fall through to the TLB switching code below.898*/899ns.asid = prev_asid;900ns.need_flush = true;901} else {902/*903* Apply process to process speculation vulnerability904* mitigations if applicable.905*/906cond_mitigation(tsk);907908/*909* Indicate that CR3 is about to change. nmi_uaccess_okay()910* and others are sensitive to the window where mm_cpumask(),911* CR3 and cpu_tlbstate.loaded_mm are not all in sync.912*/913this_cpu_write(cpu_tlbstate.loaded_mm, LOADED_MM_SWITCHING);914915/*916* Make sure this CPU is set in mm_cpumask() such that we'll917* receive invalidation IPIs.918*919* Rely on the smp_mb() implied by cpumask_set_cpu()'s atomic920* operation, or explicitly provide one. Such that:921*922* switch_mm_irqs_off() flush_tlb_mm_range()923* smp_store_release(loaded_mm, SWITCHING); atomic64_inc_return(tlb_gen)924* smp_mb(); // here // smp_mb() implied925* atomic64_read(tlb_gen); this_cpu_read(loaded_mm);926*927* we properly order against flush_tlb_mm_range(), where the928* loaded_mm load can happen in mative_flush_tlb_multi() ->929* should_flush_tlb().930*931* This way switch_mm() must see the new tlb_gen or932* flush_tlb_mm_range() must see the new loaded_mm, or both.933*/934if (next != &init_mm && !cpumask_test_cpu(cpu, mm_cpumask(next)))935cpumask_set_cpu(cpu, mm_cpumask(next));936else937smp_mb();938939next_tlb_gen = atomic64_read(&next->context.tlb_gen);940941ns = choose_new_asid(next, next_tlb_gen);942}943944reload_tlb:945new_lam = mm_lam_cr3_mask(next);946if (ns.need_flush) {947VM_WARN_ON_ONCE(is_global_asid(ns.asid));948this_cpu_write(cpu_tlbstate.ctxs[ns.asid].ctx_id, next->context.ctx_id);949this_cpu_write(cpu_tlbstate.ctxs[ns.asid].tlb_gen, next_tlb_gen);950load_new_mm_cr3(next->pgd, ns.asid, new_lam, true);951952trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, TLB_FLUSH_ALL);953} else {954/* The new ASID is already up to date. */955load_new_mm_cr3(next->pgd, ns.asid, new_lam, false);956957trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, 0);958}959960/* Make sure we write CR3 before loaded_mm. */961barrier();962963this_cpu_write(cpu_tlbstate.loaded_mm, next);964this_cpu_write(cpu_tlbstate.loaded_mm_asid, ns.asid);965cpu_tlbstate_update_lam(new_lam, mm_untag_mask(next));966967if (next != prev) {968cr4_update_pce_mm(next);969switch_ldt(prev, next);970}971}972973/*974* Please ignore the name of this function. It should be called975* switch_to_kernel_thread().976*977* enter_lazy_tlb() is a hint from the scheduler that we are entering a978* kernel thread or other context without an mm. Acceptable implementations979* include doing nothing whatsoever, switching to init_mm, or various clever980* lazy tricks to try to minimize TLB flushes.981*982* The scheduler reserves the right to call enter_lazy_tlb() several times983* in a row. It will notify us that we're going back to a real mm by984* calling switch_mm_irqs_off().985*/986void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk)987{988if (this_cpu_read(cpu_tlbstate.loaded_mm) == &init_mm)989return;990991this_cpu_write(cpu_tlbstate_shared.is_lazy, true);992}993994/*995* Using a temporary mm allows to set temporary mappings that are not accessible996* by other CPUs. Such mappings are needed to perform sensitive memory writes997* that override the kernel memory protections (e.g., W^X), without exposing the998* temporary page-table mappings that are required for these write operations to999* other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the1000* mapping is torn down. Temporary mms can also be used for EFI runtime service1001* calls or similar functionality.1002*1003* It is illegal to schedule while using a temporary mm -- the context switch1004* code is unaware of the temporary mm and does not know how to context switch.1005* Use a real (non-temporary) mm in a kernel thread if you need to sleep.1006*1007* Note: For sensitive memory writes, the temporary mm needs to be used1008* exclusively by a single core, and IRQs should be disabled while the1009* temporary mm is loaded, thereby preventing interrupt handler bugs from1010* overriding the kernel memory protection.1011*/1012struct mm_struct *use_temporary_mm(struct mm_struct *temp_mm)1013{1014struct mm_struct *prev_mm;10151016lockdep_assert_preemption_disabled();1017guard(irqsave)();10181019/*1020* Make sure not to be in TLB lazy mode, as otherwise we'll end up1021* with a stale address space WITHOUT being in lazy mode after1022* restoring the previous mm.1023*/1024if (this_cpu_read(cpu_tlbstate_shared.is_lazy))1025leave_mm();10261027prev_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1028switch_mm_irqs_off(NULL, temp_mm, current);10291030/*1031* If breakpoints are enabled, disable them while the temporary mm is1032* used. Userspace might set up watchpoints on addresses that are used1033* in the temporary mm, which would lead to wrong signals being sent or1034* crashes.1035*1036* Note that breakpoints are not disabled selectively, which also causes1037* kernel breakpoints (e.g., perf's) to be disabled. This might be1038* undesirable, but still seems reasonable as the code that runs in the1039* temporary mm should be short.1040*/1041if (hw_breakpoint_active())1042hw_breakpoint_disable();10431044return prev_mm;1045}10461047void unuse_temporary_mm(struct mm_struct *prev_mm)1048{1049lockdep_assert_preemption_disabled();1050guard(irqsave)();10511052/* Clear the cpumask, to indicate no TLB flushing is needed anywhere */1053cpumask_clear_cpu(smp_processor_id(), mm_cpumask(this_cpu_read(cpu_tlbstate.loaded_mm)));10541055switch_mm_irqs_off(NULL, prev_mm, current);10561057/*1058* Restore the breakpoints if they were disabled before the temporary mm1059* was loaded.1060*/1061if (hw_breakpoint_active())1062hw_breakpoint_restore();1063}10641065/*1066* Call this when reinitializing a CPU. It fixes the following potential1067* problems:1068*1069* - The ASID changed from what cpu_tlbstate thinks it is (most likely1070* because the CPU was taken down and came back up with CR3's PCID1071* bits clear. CPU hotplug can do this.1072*1073* - The TLB contains junk in slots corresponding to inactive ASIDs.1074*1075* - The CPU went so far out to lunch that it may have missed a TLB1076* flush.1077*/1078void initialize_tlbstate_and_flush(void)1079{1080int i;1081struct mm_struct *mm = this_cpu_read(cpu_tlbstate.loaded_mm);1082u64 tlb_gen = atomic64_read(&init_mm.context.tlb_gen);1083unsigned long lam = mm_lam_cr3_mask(mm);1084unsigned long cr3 = __read_cr3();10851086/* Assert that CR3 already references the right mm. */1087WARN_ON((cr3 & CR3_ADDR_MASK) != __pa(mm->pgd));10881089/* LAM expected to be disabled */1090WARN_ON(cr3 & (X86_CR3_LAM_U48 | X86_CR3_LAM_U57));1091WARN_ON(lam);10921093/*1094* Assert that CR4.PCIDE is set if needed. (CR4.PCIDE initialization1095* doesn't work like other CR4 bits because it can only be set from1096* long mode.)1097*/1098WARN_ON(boot_cpu_has(X86_FEATURE_PCID) &&1099!(cr4_read_shadow() & X86_CR4_PCIDE));11001101/* Disable LAM, force ASID 0 and force a TLB flush. */1102write_cr3(build_cr3(mm->pgd, 0, 0));11031104/* Reinitialize tlbstate. */1105this_cpu_write(cpu_tlbstate.last_user_mm_spec, LAST_USER_MM_INIT);1106this_cpu_write(cpu_tlbstate.loaded_mm_asid, 0);1107this_cpu_write(cpu_tlbstate.next_asid, 1);1108this_cpu_write(cpu_tlbstate.ctxs[0].ctx_id, mm->context.ctx_id);1109this_cpu_write(cpu_tlbstate.ctxs[0].tlb_gen, tlb_gen);1110cpu_tlbstate_update_lam(lam, mm_untag_mask(mm));11111112for (i = 1; i < TLB_NR_DYN_ASIDS; i++)1113this_cpu_write(cpu_tlbstate.ctxs[i].ctx_id, 0);1114}11151116/*1117* flush_tlb_func()'s memory ordering requirement is that any1118* TLB fills that happen after we flush the TLB are ordered after we1119* read active_mm's tlb_gen. We don't need any explicit barriers1120* because all x86 flush operations are serializing and the1121* atomic64_read operation won't be reordered by the compiler.1122*/1123static void flush_tlb_func(void *info)1124{1125/*1126* We have three different tlb_gen values in here. They are:1127*1128* - mm_tlb_gen: the latest generation.1129* - local_tlb_gen: the generation that this CPU has already caught1130* up to.1131* - f->new_tlb_gen: the generation that the requester of the flush1132* wants us to catch up to.1133*/1134const struct flush_tlb_info *f = info;1135struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1136u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1137u64 local_tlb_gen;1138bool local = smp_processor_id() == f->initiating_cpu;1139unsigned long nr_invalidate = 0;1140u64 mm_tlb_gen;11411142/* This code cannot presently handle being reentered. */1143VM_WARN_ON(!irqs_disabled());11441145if (!local) {1146inc_irq_stat(irq_tlb_count);1147count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);1148}11491150/* The CPU was left in the mm_cpumask of the target mm. Clear it. */1151if (f->mm && f->mm != loaded_mm) {1152cpumask_clear_cpu(raw_smp_processor_id(), mm_cpumask(f->mm));1153trace_tlb_flush(TLB_REMOTE_WRONG_CPU, 0);1154return;1155}11561157if (unlikely(loaded_mm == &init_mm))1158return;11591160/* Reload the ASID if transitioning into or out of a global ASID */1161if (mm_needs_global_asid(loaded_mm, loaded_mm_asid)) {1162switch_mm_irqs_off(NULL, loaded_mm, NULL);1163loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1164}11651166/* Broadcast ASIDs are always kept up to date with INVLPGB. */1167if (is_global_asid(loaded_mm_asid))1168return;11691170VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) !=1171loaded_mm->context.ctx_id);11721173if (this_cpu_read(cpu_tlbstate_shared.is_lazy)) {1174/*1175* We're in lazy mode. We need to at least flush our1176* paging-structure cache to avoid speculatively reading1177* garbage into our TLB. Since switching to init_mm is barely1178* slower than a minimal flush, just switch to init_mm.1179*1180* This should be rare, with native_flush_tlb_multi() skipping1181* IPIs to lazy TLB mode CPUs.1182*/1183switch_mm_irqs_off(NULL, &init_mm, NULL);1184return;1185}11861187local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen);11881189if (unlikely(f->new_tlb_gen != TLB_GENERATION_INVALID &&1190f->new_tlb_gen <= local_tlb_gen)) {1191/*1192* The TLB is already up to date in respect to f->new_tlb_gen.1193* While the core might be still behind mm_tlb_gen, checking1194* mm_tlb_gen unnecessarily would have negative caching effects1195* so avoid it.1196*/1197return;1198}11991200/*1201* Defer mm_tlb_gen reading as long as possible to avoid cache1202* contention.1203*/1204mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen);12051206if (unlikely(local_tlb_gen == mm_tlb_gen)) {1207/*1208* There's nothing to do: we're already up to date. This can1209* happen if two concurrent flushes happen -- the first flush to1210* be handled can catch us all the way up, leaving no work for1211* the second flush.1212*/1213goto done;1214}12151216WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen);1217WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen);12181219/*1220* If we get to this point, we know that our TLB is out of date.1221* This does not strictly imply that we need to flush (it's1222* possible that f->new_tlb_gen <= local_tlb_gen), but we're1223* going to need to flush in the very near future, so we might1224* as well get it over with.1225*1226* The only question is whether to do a full or partial flush.1227*1228* We do a partial flush if requested and two extra conditions1229* are met:1230*1231* 1. f->new_tlb_gen == local_tlb_gen + 1. We have an invariant that1232* we've always done all needed flushes to catch up to1233* local_tlb_gen. If, for example, local_tlb_gen == 2 and1234* f->new_tlb_gen == 3, then we know that the flush needed to bring1235* us up to date for tlb_gen 3 is the partial flush we're1236* processing.1237*1238* As an example of why this check is needed, suppose that there1239* are two concurrent flushes. The first is a full flush that1240* changes context.tlb_gen from 1 to 2. The second is a partial1241* flush that changes context.tlb_gen from 2 to 3. If they get1242* processed on this CPU in reverse order, we'll see1243* local_tlb_gen == 1, mm_tlb_gen == 3, and end != TLB_FLUSH_ALL.1244* If we were to use __flush_tlb_one_user() and set local_tlb_gen to1245* 3, we'd be break the invariant: we'd update local_tlb_gen above1246* 1 without the full flush that's needed for tlb_gen 2.1247*1248* 2. f->new_tlb_gen == mm_tlb_gen. This is purely an optimization.1249* Partial TLB flushes are not all that much cheaper than full TLB1250* flushes, so it seems unlikely that it would be a performance win1251* to do a partial flush if that won't bring our TLB fully up to1252* date. By doing a full flush instead, we can increase1253* local_tlb_gen all the way to mm_tlb_gen and we can probably1254* avoid another flush in the very near future.1255*/1256if (f->end != TLB_FLUSH_ALL &&1257f->new_tlb_gen == local_tlb_gen + 1 &&1258f->new_tlb_gen == mm_tlb_gen) {1259/* Partial flush */1260unsigned long addr = f->start;12611262/* Partial flush cannot have invalid generations */1263VM_WARN_ON(f->new_tlb_gen == TLB_GENERATION_INVALID);12641265/* Partial flush must have valid mm */1266VM_WARN_ON(f->mm == NULL);12671268nr_invalidate = (f->end - f->start) >> f->stride_shift;12691270while (addr < f->end) {1271flush_tlb_one_user(addr);1272addr += 1UL << f->stride_shift;1273}1274if (local)1275count_vm_tlb_events(NR_TLB_LOCAL_FLUSH_ONE, nr_invalidate);1276} else {1277/* Full flush. */1278nr_invalidate = TLB_FLUSH_ALL;12791280flush_tlb_local();1281if (local)1282count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);1283}12841285/* Both paths above update our state to mm_tlb_gen. */1286this_cpu_write(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen, mm_tlb_gen);12871288/* Tracing is done in a unified manner to reduce the code size */1289done:1290trace_tlb_flush(!local ? TLB_REMOTE_SHOOTDOWN :1291(f->mm == NULL) ? TLB_LOCAL_SHOOTDOWN :1292TLB_LOCAL_MM_SHOOTDOWN,1293nr_invalidate);1294}12951296static bool should_flush_tlb(int cpu, void *data)1297{1298struct mm_struct *loaded_mm = per_cpu(cpu_tlbstate.loaded_mm, cpu);1299struct flush_tlb_info *info = data;13001301/*1302* Order the 'loaded_mm' and 'is_lazy' against their1303* write ordering in switch_mm_irqs_off(). Ensure1304* 'is_lazy' is at least as new as 'loaded_mm'.1305*/1306smp_rmb();13071308/* Lazy TLB will get flushed at the next context switch. */1309if (per_cpu(cpu_tlbstate_shared.is_lazy, cpu))1310return false;13111312/* No mm means kernel memory flush. */1313if (!info->mm)1314return true;13151316/*1317* While switching, the remote CPU could have state from1318* either the prev or next mm. Assume the worst and flush.1319*/1320if (loaded_mm == LOADED_MM_SWITCHING)1321return true;13221323/* The target mm is loaded, and the CPU is not lazy. */1324if (loaded_mm == info->mm)1325return true;13261327/* In cpumask, but not the loaded mm? Periodically remove by flushing. */1328if (info->trim_cpumask)1329return true;13301331return false;1332}13331334static bool should_trim_cpumask(struct mm_struct *mm)1335{1336if (time_after(jiffies, READ_ONCE(mm->context.next_trim_cpumask))) {1337WRITE_ONCE(mm->context.next_trim_cpumask, jiffies + HZ);1338return true;1339}1340return false;1341}13421343DEFINE_PER_CPU_SHARED_ALIGNED(struct tlb_state_shared, cpu_tlbstate_shared);1344EXPORT_PER_CPU_SYMBOL(cpu_tlbstate_shared);13451346STATIC_NOPV void native_flush_tlb_multi(const struct cpumask *cpumask,1347const struct flush_tlb_info *info)1348{1349/*1350* Do accounting and tracing. Note that there are (and have always been)1351* cases in which a remote TLB flush will be traced, but eventually1352* would not happen.1353*/1354count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);1355if (info->end == TLB_FLUSH_ALL)1356trace_tlb_flush(TLB_REMOTE_SEND_IPI, TLB_FLUSH_ALL);1357else1358trace_tlb_flush(TLB_REMOTE_SEND_IPI,1359(info->end - info->start) >> PAGE_SHIFT);13601361/*1362* If no page tables were freed, we can skip sending IPIs to1363* CPUs in lazy TLB mode. They will flush the CPU themselves1364* at the next context switch.1365*1366* However, if page tables are getting freed, we need to send the1367* IPI everywhere, to prevent CPUs in lazy TLB mode from tripping1368* up on the new contents of what used to be page tables, while1369* doing a speculative memory access.1370*/1371if (info->freed_tables || mm_in_asid_transition(info->mm))1372on_each_cpu_mask(cpumask, flush_tlb_func, (void *)info, true);1373else1374on_each_cpu_cond_mask(should_flush_tlb, flush_tlb_func,1375(void *)info, 1, cpumask);1376}13771378void flush_tlb_multi(const struct cpumask *cpumask,1379const struct flush_tlb_info *info)1380{1381__flush_tlb_multi(cpumask, info);1382}13831384/*1385* See Documentation/arch/x86/tlb.rst for details. We choose 331386* because it is large enough to cover the vast majority (at1387* least 95%) of allocations, and is small enough that we are1388* confident it will not cause too much overhead. Each single1389* flush is about 100 ns, so this caps the maximum overhead at1390* _about_ 3,000 ns.1391*1392* This is in units of pages.1393*/1394unsigned long tlb_single_page_flush_ceiling __read_mostly = 33;13951396static DEFINE_PER_CPU_SHARED_ALIGNED(struct flush_tlb_info, flush_tlb_info);13971398#ifdef CONFIG_DEBUG_VM1399static DEFINE_PER_CPU(unsigned int, flush_tlb_info_idx);1400#endif14011402static struct flush_tlb_info *get_flush_tlb_info(struct mm_struct *mm,1403unsigned long start, unsigned long end,1404unsigned int stride_shift, bool freed_tables,1405u64 new_tlb_gen)1406{1407struct flush_tlb_info *info = this_cpu_ptr(&flush_tlb_info);14081409#ifdef CONFIG_DEBUG_VM1410/*1411* Ensure that the following code is non-reentrant and flush_tlb_info1412* is not overwritten. This means no TLB flushing is initiated by1413* interrupt handlers and machine-check exception handlers.1414*/1415BUG_ON(this_cpu_inc_return(flush_tlb_info_idx) != 1);1416#endif14171418/*1419* If the number of flushes is so large that a full flush1420* would be faster, do a full flush.1421*/1422if ((end - start) >> stride_shift > tlb_single_page_flush_ceiling) {1423start = 0;1424end = TLB_FLUSH_ALL;1425}14261427info->start = start;1428info->end = end;1429info->mm = mm;1430info->stride_shift = stride_shift;1431info->freed_tables = freed_tables;1432info->new_tlb_gen = new_tlb_gen;1433info->initiating_cpu = smp_processor_id();1434info->trim_cpumask = 0;14351436return info;1437}14381439static void put_flush_tlb_info(void)1440{1441#ifdef CONFIG_DEBUG_VM1442/* Complete reentrancy prevention checks */1443barrier();1444this_cpu_dec(flush_tlb_info_idx);1445#endif1446}14471448void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,1449unsigned long end, unsigned int stride_shift,1450bool freed_tables)1451{1452struct flush_tlb_info *info;1453int cpu = get_cpu();1454u64 new_tlb_gen;14551456/* This is also a barrier that synchronizes with switch_mm(). */1457new_tlb_gen = inc_mm_tlb_gen(mm);14581459info = get_flush_tlb_info(mm, start, end, stride_shift, freed_tables,1460new_tlb_gen);14611462/*1463* flush_tlb_multi() is not optimized for the common case in which only1464* a local TLB flush is needed. Optimize this use-case by calling1465* flush_tlb_func_local() directly in this case.1466*/1467if (mm_global_asid(mm)) {1468broadcast_tlb_flush(info);1469} else if (cpumask_any_but(mm_cpumask(mm), cpu) < nr_cpu_ids) {1470info->trim_cpumask = should_trim_cpumask(mm);1471flush_tlb_multi(mm_cpumask(mm), info);1472consider_global_asid(mm);1473} else if (mm == this_cpu_read(cpu_tlbstate.loaded_mm)) {1474lockdep_assert_irqs_enabled();1475local_irq_disable();1476flush_tlb_func(info);1477local_irq_enable();1478}14791480put_flush_tlb_info();1481put_cpu();1482mmu_notifier_arch_invalidate_secondary_tlbs(mm, start, end);1483}14841485static void do_flush_tlb_all(void *info)1486{1487count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);1488__flush_tlb_all();1489}14901491void flush_tlb_all(void)1492{1493count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);14941495/* First try (faster) hardware-assisted TLB invalidation. */1496if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1497invlpgb_flush_all();1498else1499/* Fall back to the IPI-based invalidation. */1500on_each_cpu(do_flush_tlb_all, NULL, 1);1501}15021503/* Flush an arbitrarily large range of memory with INVLPGB. */1504static void invlpgb_kernel_range_flush(struct flush_tlb_info *info)1505{1506unsigned long addr, nr;15071508for (addr = info->start; addr < info->end; addr += nr << PAGE_SHIFT) {1509nr = (info->end - addr) >> PAGE_SHIFT;15101511/*1512* INVLPGB has a limit on the size of ranges it can1513* flush. Break up large flushes.1514*/1515nr = clamp_val(nr, 1, invlpgb_count_max);15161517invlpgb_flush_addr_nosync(addr, nr);1518}1519__tlbsync();1520}15211522static void do_kernel_range_flush(void *info)1523{1524struct flush_tlb_info *f = info;1525unsigned long addr;15261527/* flush range by one by one 'invlpg' */1528for (addr = f->start; addr < f->end; addr += PAGE_SIZE)1529flush_tlb_one_kernel(addr);1530}15311532static void kernel_tlb_flush_all(struct flush_tlb_info *info)1533{1534if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1535invlpgb_flush_all();1536else1537on_each_cpu(do_flush_tlb_all, NULL, 1);1538}15391540static void kernel_tlb_flush_range(struct flush_tlb_info *info)1541{1542if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1543invlpgb_kernel_range_flush(info);1544else1545on_each_cpu(do_kernel_range_flush, info, 1);1546}15471548void flush_tlb_kernel_range(unsigned long start, unsigned long end)1549{1550struct flush_tlb_info *info;15511552guard(preempt)();15531554info = get_flush_tlb_info(NULL, start, end, PAGE_SHIFT, false,1555TLB_GENERATION_INVALID);15561557if (info->end == TLB_FLUSH_ALL)1558kernel_tlb_flush_all(info);1559else1560kernel_tlb_flush_range(info);15611562put_flush_tlb_info();1563}15641565/*1566* This can be used from process context to figure out what the value of1567* CR3 is without needing to do a (slow) __read_cr3().1568*1569* It's intended to be used for code like KVM that sneakily changes CR31570* and needs to restore it. It needs to be used very carefully.1571*/1572unsigned long __get_current_cr3_fast(void)1573{1574unsigned long cr3 =1575build_cr3(this_cpu_read(cpu_tlbstate.loaded_mm)->pgd,1576this_cpu_read(cpu_tlbstate.loaded_mm_asid),1577tlbstate_lam_cr3_mask());15781579/* For now, be very restrictive about when this can be called. */1580VM_WARN_ON(in_nmi() || preemptible());15811582VM_BUG_ON(cr3 != __read_cr3());1583return cr3;1584}1585EXPORT_SYMBOL_FOR_KVM(__get_current_cr3_fast);15861587/*1588* Flush one page in the kernel mapping1589*/1590void flush_tlb_one_kernel(unsigned long addr)1591{1592count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);15931594/*1595* If PTI is off, then __flush_tlb_one_user() is just INVLPG or its1596* paravirt equivalent. Even with PCID, this is sufficient: we only1597* use PCID if we also use global PTEs for the kernel mapping, and1598* INVLPG flushes global translations across all address spaces.1599*1600* If PTI is on, then the kernel is mapped with non-global PTEs, and1601* __flush_tlb_one_user() will flush the given address for the current1602* kernel address space and for its usermode counterpart, but it does1603* not flush it for other address spaces.1604*/1605flush_tlb_one_user(addr);16061607if (!static_cpu_has(X86_FEATURE_PTI))1608return;16091610/*1611* See above. We need to propagate the flush to all other address1612* spaces. In principle, we only need to propagate it to kernelmode1613* address spaces, but the extra bookkeeping we would need is not1614* worth it.1615*/1616this_cpu_write(cpu_tlbstate.invalidate_other, true);1617}16181619/*1620* Flush one page in the user mapping1621*/1622STATIC_NOPV void native_flush_tlb_one_user(unsigned long addr)1623{1624u32 loaded_mm_asid;1625bool cpu_pcide;16261627/* Flush 'addr' from the kernel PCID: */1628invlpg(addr);16291630/* If PTI is off there is no user PCID and nothing to flush. */1631if (!static_cpu_has(X86_FEATURE_PTI))1632return;16331634loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1635cpu_pcide = this_cpu_read(cpu_tlbstate.cr4) & X86_CR4_PCIDE;16361637/*1638* invpcid_flush_one(pcid>0) will #GP if CR4.PCIDE==0. Check1639* 'cpu_pcide' to ensure that *this* CPU will not trigger those1640* #GP's even if called before CR4.PCIDE has been initialized.1641*/1642if (boot_cpu_has(X86_FEATURE_INVPCID) && cpu_pcide)1643invpcid_flush_one(user_pcid(loaded_mm_asid), addr);1644else1645invalidate_user_asid(loaded_mm_asid);1646}16471648void flush_tlb_one_user(unsigned long addr)1649{1650__flush_tlb_one_user(addr);1651}16521653/*1654* Flush everything1655*/1656STATIC_NOPV void native_flush_tlb_global(void)1657{1658unsigned long flags;16591660if (static_cpu_has(X86_FEATURE_INVPCID)) {1661/*1662* Using INVPCID is considerably faster than a pair of writes1663* to CR4 sandwiched inside an IRQ flag save/restore.1664*1665* Note, this works with CR4.PCIDE=0 or 1.1666*/1667invpcid_flush_all();1668return;1669}16701671/*1672* Read-modify-write to CR4 - protect it from preemption and1673* from interrupts. (Use the raw variant because this code can1674* be called from deep inside debugging code.)1675*/1676raw_local_irq_save(flags);16771678__native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4));16791680raw_local_irq_restore(flags);1681}16821683/*1684* Flush the entire current user mapping1685*/1686STATIC_NOPV void native_flush_tlb_local(void)1687{1688/*1689* Preemption or interrupts must be disabled to protect the access1690* to the per CPU variable and to prevent being preempted between1691* read_cr3() and write_cr3().1692*/1693WARN_ON_ONCE(preemptible());16941695invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid));16961697/* If current->mm == NULL then the read_cr3() "borrows" an mm */1698native_write_cr3(__native_read_cr3());1699}17001701void flush_tlb_local(void)1702{1703__flush_tlb_local();1704}17051706/*1707* Flush everything1708*/1709void __flush_tlb_all(void)1710{1711/*1712* This is to catch users with enabled preemption and the PGE feature1713* and don't trigger the warning in __native_flush_tlb().1714*/1715VM_WARN_ON_ONCE(preemptible());17161717if (cpu_feature_enabled(X86_FEATURE_PGE)) {1718__flush_tlb_global();1719} else {1720/*1721* !PGE -> !PCID (setup_pcid()), thus every flush is total.1722*/1723flush_tlb_local();1724}1725}1726EXPORT_SYMBOL_FOR_KVM(__flush_tlb_all);17271728void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)1729{1730struct flush_tlb_info *info;17311732int cpu = get_cpu();17331734info = get_flush_tlb_info(NULL, 0, TLB_FLUSH_ALL, 0, false,1735TLB_GENERATION_INVALID);1736/*1737* flush_tlb_multi() is not optimized for the common case in which only1738* a local TLB flush is needed. Optimize this use-case by calling1739* flush_tlb_func_local() directly in this case.1740*/1741if (cpu_feature_enabled(X86_FEATURE_INVLPGB) && batch->unmapped_pages) {1742invlpgb_flush_all_nonglobals();1743batch->unmapped_pages = false;1744} else if (cpumask_any_but(&batch->cpumask, cpu) < nr_cpu_ids) {1745flush_tlb_multi(&batch->cpumask, info);1746} else if (cpumask_test_cpu(cpu, &batch->cpumask)) {1747lockdep_assert_irqs_enabled();1748local_irq_disable();1749flush_tlb_func(info);1750local_irq_enable();1751}17521753cpumask_clear(&batch->cpumask);17541755put_flush_tlb_info();1756put_cpu();1757}17581759/*1760* Blindly accessing user memory from NMI context can be dangerous1761* if we're in the middle of switching the current user task or1762* switching the loaded mm. It can also be dangerous if we1763* interrupted some kernel code that was temporarily using a1764* different mm.1765*/1766bool nmi_uaccess_okay(void)1767{1768struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1769struct mm_struct *current_mm = current->mm;17701771VM_WARN_ON_ONCE(!loaded_mm);17721773/*1774* The condition we want to check is1775* current_mm->pgd == __va(read_cr3_pa()). This may be slow, though,1776* if we're running in a VM with shadow paging, and nmi_uaccess_okay()1777* is supposed to be reasonably fast.1778*1779* Instead, we check the almost equivalent but somewhat conservative1780* condition below, and we rely on the fact that switch_mm_irqs_off()1781* sets loaded_mm to LOADED_MM_SWITCHING before writing to CR3.1782*/1783if (loaded_mm != current_mm)1784return false;17851786VM_WARN_ON_ONCE(__pa(current_mm->pgd) != read_cr3_pa());17871788return true;1789}17901791static ssize_t tlbflush_read_file(struct file *file, char __user *user_buf,1792size_t count, loff_t *ppos)1793{1794char buf[32];1795unsigned int len;17961797len = sprintf(buf, "%ld\n", tlb_single_page_flush_ceiling);1798return simple_read_from_buffer(user_buf, count, ppos, buf, len);1799}18001801static ssize_t tlbflush_write_file(struct file *file,1802const char __user *user_buf, size_t count, loff_t *ppos)1803{1804char buf[32];1805ssize_t len;1806int ceiling;18071808len = min(count, sizeof(buf) - 1);1809if (copy_from_user(buf, user_buf, len))1810return -EFAULT;18111812buf[len] = '\0';1813if (kstrtoint(buf, 0, &ceiling))1814return -EINVAL;18151816if (ceiling < 0)1817return -EINVAL;18181819tlb_single_page_flush_ceiling = ceiling;1820return count;1821}18221823static const struct file_operations fops_tlbflush = {1824.read = tlbflush_read_file,1825.write = tlbflush_write_file,1826.llseek = default_llseek,1827};18281829static int __init create_tlb_single_page_flush_ceiling(void)1830{1831debugfs_create_file("tlb_single_page_flush_ceiling", S_IRUSR | S_IWUSR,1832arch_debugfs_dir, NULL, &fops_tlbflush);1833return 0;1834}1835late_initcall(create_tlb_single_page_flush_ceiling);183618371838