// 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>1415#include <asm/tlbflush.h>16#include <asm/mmu_context.h>17#include <asm/nospec-branch.h>18#include <asm/cache.h>19#include <asm/cacheflush.h>20#include <asm/apic.h>21#include <asm/msr.h>22#include <asm/perf_event.h>23#include <asm/tlb.h>2425#include "mm_internal.h"2627#ifdef CONFIG_PARAVIRT28# define STATIC_NOPV29#else30# define STATIC_NOPV static31# define __flush_tlb_local native_flush_tlb_local32# define __flush_tlb_global native_flush_tlb_global33# define __flush_tlb_one_user(addr) native_flush_tlb_one_user(addr)34# define __flush_tlb_multi(msk, info) native_flush_tlb_multi(msk, info)35#endif3637/*38* TLB flushing, formerly SMP-only39* c/o Linus Torvalds.40*41* These mean you can really definitely utterly forget about42* writing to user space from interrupts. (Its not allowed anyway).43*44* Optimizations Manfred Spraul <[email protected]>45*46* More scalable flush, from Andi Kleen47*48* Implement flush IPI by CALL_FUNCTION_VECTOR, Alex Shi49*/5051/*52* Bits to mangle the TIF_SPEC_* state into the mm pointer which is53* stored in cpu_tlb_state.last_user_mm_spec.54*/55#define LAST_USER_MM_IBPB 0x1UL56#define LAST_USER_MM_L1D_FLUSH 0x2UL57#define LAST_USER_MM_SPEC_MASK (LAST_USER_MM_IBPB | LAST_USER_MM_L1D_FLUSH)5859/* Bits to set when tlbstate and flush is (re)initialized */60#define LAST_USER_MM_INIT LAST_USER_MM_IBPB6162/*63* The x86 feature is called PCID (Process Context IDentifier). It is similar64* to what is traditionally called ASID on the RISC processors.65*66* We don't use the traditional ASID implementation, where each process/mm gets67* its own ASID and flush/restart when we run out of ASID space.68*69* Instead we have a small per-cpu array of ASIDs and cache the last few mm's70* that came by on this CPU, allowing cheaper switch_mm between processes on71* this CPU.72*73* We end up with different spaces for different things. To avoid confusion we74* use different names for each of them:75*76* ASID - [0, TLB_NR_DYN_ASIDS-1]77* the canonical identifier for an mm, dynamically allocated on each CPU78* [TLB_NR_DYN_ASIDS, MAX_ASID_AVAILABLE-1]79* the canonical, global identifier for an mm, identical across all CPUs80*81* kPCID - [1, MAX_ASID_AVAILABLE]82* the value we write into the PCID part of CR3; corresponds to the83* ASID+1, because PCID 0 is special.84*85* uPCID - [2048 + 1, 2048 + MAX_ASID_AVAILABLE]86* for KPTI each mm has two address spaces and thus needs two87* PCID values, but we can still do with a single ASID denomination88* for each mm. Corresponds to kPCID + 2048.89*90*/9192/*93* When enabled, MITIGATION_PAGE_TABLE_ISOLATION consumes a single bit for94* user/kernel switches95*/96#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION97# define PTI_CONSUMED_PCID_BITS 198#else99# define PTI_CONSUMED_PCID_BITS 0100#endif101102#define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS)103104/*105* ASIDs are zero-based: 0->MAX_AVAIL_ASID are valid. -1 below to account106* for them being zero-based. Another -1 is because PCID 0 is reserved for107* use by non-PCID-aware users.108*/109#define MAX_ASID_AVAILABLE ((1 << CR3_AVAIL_PCID_BITS) - 2)110111/*112* Given @asid, compute kPCID113*/114static inline u16 kern_pcid(u16 asid)115{116VM_WARN_ON_ONCE(asid > MAX_ASID_AVAILABLE);117118#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION119/*120* Make sure that the dynamic ASID space does not conflict with the121* bit we are using to switch between user and kernel ASIDs.122*/123BUILD_BUG_ON(TLB_NR_DYN_ASIDS >= (1 << X86_CR3_PTI_PCID_USER_BIT));124125/*126* The ASID being passed in here should have respected the127* MAX_ASID_AVAILABLE and thus never have the switch bit set.128*/129VM_WARN_ON_ONCE(asid & (1 << X86_CR3_PTI_PCID_USER_BIT));130#endif131/*132* The dynamically-assigned ASIDs that get passed in are small133* (<TLB_NR_DYN_ASIDS). They never have the high switch bit set,134* so do not bother to clear it.135*136* If PCID is on, ASID-aware code paths put the ASID+1 into the137* PCID bits. This serves two purposes. It prevents a nasty138* situation in which PCID-unaware code saves CR3, loads some other139* value (with PCID == 0), and then restores CR3, thus corrupting140* the TLB for ASID 0 if the saved ASID was nonzero. It also means141* that any bugs involving loading a PCID-enabled CR3 with142* CR4.PCIDE off will trigger deterministically.143*/144return asid + 1;145}146147/*148* Given @asid, compute uPCID149*/150static inline u16 user_pcid(u16 asid)151{152u16 ret = kern_pcid(asid);153#ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION154ret |= 1 << X86_CR3_PTI_PCID_USER_BIT;155#endif156return ret;157}158159static inline unsigned long build_cr3(pgd_t *pgd, u16 asid, unsigned long lam)160{161unsigned long cr3 = __sme_pa(pgd) | lam;162163if (static_cpu_has(X86_FEATURE_PCID)) {164cr3 |= kern_pcid(asid);165} else {166VM_WARN_ON_ONCE(asid != 0);167}168169return cr3;170}171172static inline unsigned long build_cr3_noflush(pgd_t *pgd, u16 asid,173unsigned long lam)174{175/*176* Use boot_cpu_has() instead of this_cpu_has() as this function177* might be called during early boot. This should work even after178* boot because all CPU's the have same capabilities:179*/180VM_WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_PCID));181return build_cr3(pgd, asid, lam) | CR3_NOFLUSH;182}183184/*185* We get here when we do something requiring a TLB invalidation186* but could not go invalidate all of the contexts. We do the187* necessary invalidation by clearing out the 'ctx_id' which188* forces a TLB flush when the context is loaded.189*/190static void clear_asid_other(void)191{192u16 asid;193194/*195* This is only expected to be set if we have disabled196* kernel _PAGE_GLOBAL pages.197*/198if (!static_cpu_has(X86_FEATURE_PTI)) {199WARN_ON_ONCE(1);200return;201}202203for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {204/* Do not need to flush the current asid */205if (asid == this_cpu_read(cpu_tlbstate.loaded_mm_asid))206continue;207/*208* Make sure the next time we go to switch to209* this asid, we do a flush:210*/211this_cpu_write(cpu_tlbstate.ctxs[asid].ctx_id, 0);212}213this_cpu_write(cpu_tlbstate.invalidate_other, false);214}215216atomic64_t last_mm_ctx_id = ATOMIC64_INIT(1);217218struct new_asid {219unsigned int asid : 16;220unsigned int need_flush : 1;221};222223static struct new_asid choose_new_asid(struct mm_struct *next, u64 next_tlb_gen)224{225struct new_asid ns;226u16 asid;227228if (!static_cpu_has(X86_FEATURE_PCID)) {229ns.asid = 0;230ns.need_flush = 1;231return ns;232}233234/*235* TLB consistency for global ASIDs is maintained with hardware assisted236* remote TLB flushing. Global ASIDs are always up to date.237*/238if (cpu_feature_enabled(X86_FEATURE_INVLPGB)) {239u16 global_asid = mm_global_asid(next);240241if (global_asid) {242ns.asid = global_asid;243ns.need_flush = 0;244return ns;245}246}247248if (this_cpu_read(cpu_tlbstate.invalidate_other))249clear_asid_other();250251for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {252if (this_cpu_read(cpu_tlbstate.ctxs[asid].ctx_id) !=253next->context.ctx_id)254continue;255256ns.asid = asid;257ns.need_flush = (this_cpu_read(cpu_tlbstate.ctxs[asid].tlb_gen) < next_tlb_gen);258return ns;259}260261/*262* We don't currently own an ASID slot on this CPU.263* Allocate a slot.264*/265ns.asid = this_cpu_add_return(cpu_tlbstate.next_asid, 1) - 1;266if (ns.asid >= TLB_NR_DYN_ASIDS) {267ns.asid = 0;268this_cpu_write(cpu_tlbstate.next_asid, 1);269}270ns.need_flush = true;271272return ns;273}274275/*276* Global ASIDs are allocated for multi-threaded processes that are277* active on multiple CPUs simultaneously, giving each of those278* processes the same PCID on every CPU, for use with hardware-assisted279* TLB shootdown on remote CPUs, like AMD INVLPGB or Intel RAR.280*281* These global ASIDs are held for the lifetime of the process.282*/283static DEFINE_RAW_SPINLOCK(global_asid_lock);284static u16 last_global_asid = MAX_ASID_AVAILABLE;285static DECLARE_BITMAP(global_asid_used, MAX_ASID_AVAILABLE);286static DECLARE_BITMAP(global_asid_freed, MAX_ASID_AVAILABLE);287static int global_asid_available = MAX_ASID_AVAILABLE - TLB_NR_DYN_ASIDS - 1;288289/*290* When the search for a free ASID in the global ASID space reaches291* MAX_ASID_AVAILABLE, a global TLB flush guarantees that previously292* freed global ASIDs are safe to re-use.293*294* This way the global flush only needs to happen at ASID rollover295* time, and not at ASID allocation time.296*/297static void reset_global_asid_space(void)298{299lockdep_assert_held(&global_asid_lock);300301invlpgb_flush_all_nonglobals();302303/*304* The TLB flush above makes it safe to re-use the previously305* freed global ASIDs.306*/307bitmap_andnot(global_asid_used, global_asid_used,308global_asid_freed, MAX_ASID_AVAILABLE);309bitmap_clear(global_asid_freed, 0, MAX_ASID_AVAILABLE);310311/* Restart the search from the start of global ASID space. */312last_global_asid = TLB_NR_DYN_ASIDS;313}314315static u16 allocate_global_asid(void)316{317u16 asid;318319lockdep_assert_held(&global_asid_lock);320321/* The previous allocation hit the edge of available address space */322if (last_global_asid >= MAX_ASID_AVAILABLE - 1)323reset_global_asid_space();324325asid = find_next_zero_bit(global_asid_used, MAX_ASID_AVAILABLE, last_global_asid);326327if (asid >= MAX_ASID_AVAILABLE && !global_asid_available) {328/* This should never happen. */329VM_WARN_ONCE(1, "Unable to allocate global ASID despite %d available\n",330global_asid_available);331return 0;332}333334/* Claim this global ASID. */335__set_bit(asid, global_asid_used);336last_global_asid = asid;337global_asid_available--;338return asid;339}340341/*342* Check whether a process is currently active on more than @threshold CPUs.343* This is a cheap estimation on whether or not it may make sense to assign344* a global ASID to this process, and use broadcast TLB invalidation.345*/346static bool mm_active_cpus_exceeds(struct mm_struct *mm, int threshold)347{348int count = 0;349int cpu;350351/* This quick check should eliminate most single threaded programs. */352if (cpumask_weight(mm_cpumask(mm)) <= threshold)353return false;354355/* Slower check to make sure. */356for_each_cpu(cpu, mm_cpumask(mm)) {357/* Skip the CPUs that aren't really running this process. */358if (per_cpu(cpu_tlbstate.loaded_mm, cpu) != mm)359continue;360361if (per_cpu(cpu_tlbstate_shared.is_lazy, cpu))362continue;363364if (++count > threshold)365return true;366}367return false;368}369370/*371* Assign a global ASID to the current process, protecting against372* races between multiple threads in the process.373*/374static void use_global_asid(struct mm_struct *mm)375{376u16 asid;377378guard(raw_spinlock_irqsave)(&global_asid_lock);379380/* This process is already using broadcast TLB invalidation. */381if (mm_global_asid(mm))382return;383384/*385* The last global ASID was consumed while waiting for the lock.386*387* If this fires, a more aggressive ASID reuse scheme might be388* needed.389*/390if (!global_asid_available) {391VM_WARN_ONCE(1, "Ran out of global ASIDs\n");392return;393}394395asid = allocate_global_asid();396if (!asid)397return;398399mm_assign_global_asid(mm, asid);400}401402void mm_free_global_asid(struct mm_struct *mm)403{404if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))405return;406407if (!mm_global_asid(mm))408return;409410guard(raw_spinlock_irqsave)(&global_asid_lock);411412/* The global ASID can be re-used only after flush at wrap-around. */413#ifdef CONFIG_BROADCAST_TLB_FLUSH414__set_bit(mm->context.global_asid, global_asid_freed);415416mm->context.global_asid = 0;417global_asid_available++;418#endif419}420421/*422* Is the mm transitioning from a CPU-local ASID to a global ASID?423*/424static bool mm_needs_global_asid(struct mm_struct *mm, u16 asid)425{426u16 global_asid = mm_global_asid(mm);427428if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))429return false;430431/* Process is transitioning to a global ASID */432if (global_asid && asid != global_asid)433return true;434435return false;436}437438/*439* x86 has 4k ASIDs (2k when compiled with KPTI), but the largest x86440* systems have over 8k CPUs. Because of this potential ASID shortage,441* global ASIDs are handed out to processes that have frequent TLB442* flushes and are active on 4 or more CPUs simultaneously.443*/444static void consider_global_asid(struct mm_struct *mm)445{446if (!cpu_feature_enabled(X86_FEATURE_INVLPGB))447return;448449/* Check every once in a while. */450if ((current->pid & 0x1f) != (jiffies & 0x1f))451return;452453/*454* Assign a global ASID if the process is active on455* 4 or more CPUs simultaneously.456*/457if (mm_active_cpus_exceeds(mm, 3))458use_global_asid(mm);459}460461static void finish_asid_transition(struct flush_tlb_info *info)462{463struct mm_struct *mm = info->mm;464int bc_asid = mm_global_asid(mm);465int cpu;466467if (!mm_in_asid_transition(mm))468return;469470for_each_cpu(cpu, mm_cpumask(mm)) {471/*472* The remote CPU is context switching. Wait for that to473* finish, to catch the unlikely case of it switching to474* the target mm with an out of date ASID.475*/476while (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm, cpu)) == LOADED_MM_SWITCHING)477cpu_relax();478479if (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm, cpu)) != mm)480continue;481482/*483* If at least one CPU is not using the global ASID yet,484* send a TLB flush IPI. The IPI should cause stragglers485* to transition soon.486*487* This can race with the CPU switching to another task;488* that results in a (harmless) extra IPI.489*/490if (READ_ONCE(per_cpu(cpu_tlbstate.loaded_mm_asid, cpu)) != bc_asid) {491flush_tlb_multi(mm_cpumask(info->mm), info);492return;493}494}495496/* All the CPUs running this process are using the global ASID. */497mm_clear_asid_transition(mm);498}499500static void broadcast_tlb_flush(struct flush_tlb_info *info)501{502bool pmd = info->stride_shift == PMD_SHIFT;503unsigned long asid = mm_global_asid(info->mm);504unsigned long addr = info->start;505506/*507* TLB flushes with INVLPGB are kicked off asynchronously.508* The inc_mm_tlb_gen() guarantees page table updates are done509* before these TLB flushes happen.510*/511if (info->end == TLB_FLUSH_ALL) {512invlpgb_flush_single_pcid_nosync(kern_pcid(asid));513/* Do any CPUs supporting INVLPGB need PTI? */514if (cpu_feature_enabled(X86_FEATURE_PTI))515invlpgb_flush_single_pcid_nosync(user_pcid(asid));516} else do {517unsigned long nr = 1;518519if (info->stride_shift <= PMD_SHIFT) {520nr = (info->end - addr) >> info->stride_shift;521nr = clamp_val(nr, 1, invlpgb_count_max);522}523524invlpgb_flush_user_nr_nosync(kern_pcid(asid), addr, nr, pmd);525if (cpu_feature_enabled(X86_FEATURE_PTI))526invlpgb_flush_user_nr_nosync(user_pcid(asid), addr, nr, pmd);527528addr += nr << info->stride_shift;529} while (addr < info->end);530531finish_asid_transition(info);532533/* Wait for the INVLPGBs kicked off above to finish. */534__tlbsync();535}536537/*538* Given an ASID, flush the corresponding user ASID. We can delay this539* until the next time we switch to it.540*541* See SWITCH_TO_USER_CR3.542*/543static inline void invalidate_user_asid(u16 asid)544{545/* There is no user ASID if address space separation is off */546if (!IS_ENABLED(CONFIG_MITIGATION_PAGE_TABLE_ISOLATION))547return;548549/*550* We only have a single ASID if PCID is off and the CR3551* write will have flushed it.552*/553if (!cpu_feature_enabled(X86_FEATURE_PCID))554return;555556if (!static_cpu_has(X86_FEATURE_PTI))557return;558559__set_bit(kern_pcid(asid),560(unsigned long *)this_cpu_ptr(&cpu_tlbstate.user_pcid_flush_mask));561}562563static void load_new_mm_cr3(pgd_t *pgdir, u16 new_asid, unsigned long lam,564bool need_flush)565{566unsigned long new_mm_cr3;567568if (need_flush) {569invalidate_user_asid(new_asid);570new_mm_cr3 = build_cr3(pgdir, new_asid, lam);571} else {572new_mm_cr3 = build_cr3_noflush(pgdir, new_asid, lam);573}574575/*576* Caution: many callers of this function expect577* that load_cr3() is serializing and orders TLB578* fills with respect to the mm_cpumask writes.579*/580write_cr3(new_mm_cr3);581}582583void leave_mm(void)584{585struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);586587/*588* It's plausible that we're in lazy TLB mode while our mm is init_mm.589* If so, our callers still expect us to flush the TLB, but there590* aren't any user TLB entries in init_mm to worry about.591*592* This needs to happen before any other sanity checks due to593* intel_idle's shenanigans.594*/595if (loaded_mm == &init_mm)596return;597598/* Warn if we're not lazy. */599WARN_ON(!this_cpu_read(cpu_tlbstate_shared.is_lazy));600601switch_mm(NULL, &init_mm, NULL);602}603EXPORT_SYMBOL_GPL(leave_mm);604605void switch_mm(struct mm_struct *prev, struct mm_struct *next,606struct task_struct *tsk)607{608unsigned long flags;609610local_irq_save(flags);611switch_mm_irqs_off(NULL, next, tsk);612local_irq_restore(flags);613}614615/*616* Invoked from return to user/guest by a task that opted-in to L1D617* flushing but ended up running on an SMT enabled core due to wrong618* affinity settings or CPU hotplug. This is part of the paranoid L1D flush619* contract which this task requested.620*/621static void l1d_flush_force_sigbus(struct callback_head *ch)622{623force_sig(SIGBUS);624}625626static void l1d_flush_evaluate(unsigned long prev_mm, unsigned long next_mm,627struct task_struct *next)628{629/* Flush L1D if the outgoing task requests it */630if (prev_mm & LAST_USER_MM_L1D_FLUSH)631wrmsrq(MSR_IA32_FLUSH_CMD, L1D_FLUSH);632633/* Check whether the incoming task opted in for L1D flush */634if (likely(!(next_mm & LAST_USER_MM_L1D_FLUSH)))635return;636637/*638* Validate that it is not running on an SMT sibling as this would639* make the exercise pointless because the siblings share L1D. If640* it runs on a SMT sibling, notify it with SIGBUS on return to641* user/guest642*/643if (this_cpu_read(cpu_info.smt_active)) {644clear_ti_thread_flag(&next->thread_info, TIF_SPEC_L1D_FLUSH);645next->l1d_flush_kill.func = l1d_flush_force_sigbus;646task_work_add(next, &next->l1d_flush_kill, TWA_RESUME);647}648}649650static unsigned long mm_mangle_tif_spec_bits(struct task_struct *next)651{652unsigned long next_tif = read_task_thread_flags(next);653unsigned long spec_bits = (next_tif >> TIF_SPEC_IB) & LAST_USER_MM_SPEC_MASK;654655/*656* Ensure that the bit shift above works as expected and the two flags657* end up in bit 0 and 1.658*/659BUILD_BUG_ON(TIF_SPEC_L1D_FLUSH != TIF_SPEC_IB + 1);660661return (unsigned long)next->mm | spec_bits;662}663664static void cond_mitigation(struct task_struct *next)665{666unsigned long prev_mm, next_mm;667668if (!next || !next->mm)669return;670671next_mm = mm_mangle_tif_spec_bits(next);672prev_mm = this_cpu_read(cpu_tlbstate.last_user_mm_spec);673674/*675* Avoid user->user BTB/RSB poisoning by flushing them when switching676* between processes. This stops one process from doing Spectre-v2677* attacks on another.678*679* Both, the conditional and the always IBPB mode use the mm680* pointer to avoid the IBPB when switching between tasks of the681* same process. Using the mm pointer instead of mm->context.ctx_id682* opens a hypothetical hole vs. mm_struct reuse, which is more or683* less impossible to control by an attacker. Aside of that it684* would only affect the first schedule so the theoretically685* exposed data is not really interesting.686*/687if (static_branch_likely(&switch_mm_cond_ibpb)) {688/*689* This is a bit more complex than the always mode because690* it has to handle two cases:691*692* 1) Switch from a user space task (potential attacker)693* which has TIF_SPEC_IB set to a user space task694* (potential victim) which has TIF_SPEC_IB not set.695*696* 2) Switch from a user space task (potential attacker)697* which has TIF_SPEC_IB not set to a user space task698* (potential victim) which has TIF_SPEC_IB set.699*700* This could be done by unconditionally issuing IBPB when701* a task which has TIF_SPEC_IB set is either scheduled in702* or out. Though that results in two flushes when:703*704* - the same user space task is scheduled out and later705* scheduled in again and only a kernel thread ran in706* between.707*708* - a user space task belonging to the same process is709* scheduled in after a kernel thread ran in between710*711* - a user space task belonging to the same process is712* scheduled in immediately.713*714* Optimize this with reasonably small overhead for the715* above cases. Mangle the TIF_SPEC_IB bit into the mm716* pointer of the incoming task which is stored in717* cpu_tlbstate.last_user_mm_spec for comparison.718*719* Issue IBPB only if the mm's are different and one or720* both have the IBPB bit set.721*/722if (next_mm != prev_mm &&723(next_mm | prev_mm) & LAST_USER_MM_IBPB)724indirect_branch_prediction_barrier();725}726727if (static_branch_unlikely(&switch_mm_always_ibpb)) {728/*729* Only flush when switching to a user space task with a730* different context than the user space task which ran731* last on this CPU.732*/733if ((prev_mm & ~LAST_USER_MM_SPEC_MASK) != (unsigned long)next->mm)734indirect_branch_prediction_barrier();735}736737if (static_branch_unlikely(&switch_mm_cond_l1d_flush)) {738/*739* Flush L1D when the outgoing task requested it and/or740* check whether the incoming task requested L1D flushing741* and ended up on an SMT sibling.742*/743if (unlikely((prev_mm | next_mm) & LAST_USER_MM_L1D_FLUSH))744l1d_flush_evaluate(prev_mm, next_mm, next);745}746747this_cpu_write(cpu_tlbstate.last_user_mm_spec, next_mm);748}749750#ifdef CONFIG_PERF_EVENTS751static inline void cr4_update_pce_mm(struct mm_struct *mm)752{753if (static_branch_unlikely(&rdpmc_always_available_key) ||754(!static_branch_unlikely(&rdpmc_never_available_key) &&755atomic_read(&mm->context.perf_rdpmc_allowed))) {756/*757* Clear the existing dirty counters to758* prevent the leak for an RDPMC task.759*/760perf_clear_dirty_counters();761cr4_set_bits_irqsoff(X86_CR4_PCE);762} else763cr4_clear_bits_irqsoff(X86_CR4_PCE);764}765766void cr4_update_pce(void *ignored)767{768cr4_update_pce_mm(this_cpu_read(cpu_tlbstate.loaded_mm));769}770771#else772static inline void cr4_update_pce_mm(struct mm_struct *mm) { }773#endif774775/*776* This optimizes when not actually switching mm's. Some architectures use the777* 'unused' argument for this optimization, but x86 must use778* 'cpu_tlbstate.loaded_mm' instead because it does not always keep779* 'current->active_mm' up to date.780*/781void switch_mm_irqs_off(struct mm_struct *unused, struct mm_struct *next,782struct task_struct *tsk)783{784struct mm_struct *prev = this_cpu_read(cpu_tlbstate.loaded_mm);785u16 prev_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);786bool was_lazy = this_cpu_read(cpu_tlbstate_shared.is_lazy);787unsigned cpu = smp_processor_id();788unsigned long new_lam;789struct new_asid ns;790u64 next_tlb_gen;791792793/* We don't want flush_tlb_func() to run concurrently with us. */794if (IS_ENABLED(CONFIG_PROVE_LOCKING))795WARN_ON_ONCE(!irqs_disabled());796797/*798* Verify that CR3 is what we think it is. This will catch799* hypothetical buggy code that directly switches to swapper_pg_dir800* without going through leave_mm() / switch_mm_irqs_off() or that801* does something like write_cr3(read_cr3_pa()).802*803* Only do this check if CONFIG_DEBUG_VM=y because __read_cr3()804* isn't free.805*/806#ifdef CONFIG_DEBUG_VM807if (WARN_ON_ONCE(__read_cr3() != build_cr3(prev->pgd, prev_asid,808tlbstate_lam_cr3_mask()))) {809/*810* If we were to BUG here, we'd be very likely to kill811* the system so hard that we don't see the call trace.812* Try to recover instead by ignoring the error and doing813* a global flush to minimize the chance of corruption.814*815* (This is far from being a fully correct recovery.816* Architecturally, the CPU could prefetch something817* back into an incorrect ASID slot and leave it there818* to cause trouble down the road. It's better than819* nothing, though.)820*/821__flush_tlb_all();822}823#endif824if (was_lazy)825this_cpu_write(cpu_tlbstate_shared.is_lazy, false);826827/*828* The membarrier system call requires a full memory barrier and829* core serialization before returning to user-space, after830* storing to rq->curr, when changing mm. This is because831* membarrier() sends IPIs to all CPUs that are in the target mm832* to make them issue memory barriers. However, if another CPU833* switches to/from the target mm concurrently with834* membarrier(), it can cause that CPU not to receive an IPI835* when it really should issue a memory barrier. Writing to CR3836* provides that full memory barrier and core serializing837* instruction.838*/839if (prev == next) {840/* Not actually switching mm's */841VM_WARN_ON(is_dyn_asid(prev_asid) &&842this_cpu_read(cpu_tlbstate.ctxs[prev_asid].ctx_id) !=843next->context.ctx_id);844845/*846* If this races with another thread that enables lam, 'new_lam'847* might not match tlbstate_lam_cr3_mask().848*/849850/*851* Even in lazy TLB mode, the CPU should stay set in the852* mm_cpumask. The TLB shootdown code can figure out from853* cpu_tlbstate_shared.is_lazy whether or not to send an IPI.854*/855if (IS_ENABLED(CONFIG_DEBUG_VM) &&856WARN_ON_ONCE(prev != &init_mm && !is_notrack_mm(prev) &&857!cpumask_test_cpu(cpu, mm_cpumask(next))))858cpumask_set_cpu(cpu, mm_cpumask(next));859860/* Check if the current mm is transitioning to a global ASID */861if (mm_needs_global_asid(next, prev_asid)) {862next_tlb_gen = atomic64_read(&next->context.tlb_gen);863ns = choose_new_asid(next, next_tlb_gen);864goto reload_tlb;865}866867/*868* Broadcast TLB invalidation keeps this ASID up to date869* all the time.870*/871if (is_global_asid(prev_asid))872return;873874/*875* If the CPU is not in lazy TLB mode, we are just switching876* from one thread in a process to another thread in the same877* process. No TLB flush required.878*/879if (!was_lazy)880return;881882/*883* Read the tlb_gen to check whether a flush is needed.884* If the TLB is up to date, just use it.885* The barrier synchronizes with the tlb_gen increment in886* the TLB shootdown code.887*/888smp_mb();889next_tlb_gen = atomic64_read(&next->context.tlb_gen);890if (this_cpu_read(cpu_tlbstate.ctxs[prev_asid].tlb_gen) ==891next_tlb_gen)892return;893894/*895* TLB contents went out of date while we were in lazy896* mode. Fall through to the TLB switching code below.897*/898ns.asid = prev_asid;899ns.need_flush = true;900} else {901/*902* Apply process to process speculation vulnerability903* mitigations if applicable.904*/905cond_mitigation(tsk);906907/*908* Indicate that CR3 is about to change. nmi_uaccess_okay()909* and others are sensitive to the window where mm_cpumask(),910* CR3 and cpu_tlbstate.loaded_mm are not all in sync.911*/912this_cpu_write(cpu_tlbstate.loaded_mm, LOADED_MM_SWITCHING);913barrier();914915/* Start receiving IPIs and then read tlb_gen (and LAM below) */916if (next != &init_mm && !cpumask_test_cpu(cpu, mm_cpumask(next)))917cpumask_set_cpu(cpu, mm_cpumask(next));918next_tlb_gen = atomic64_read(&next->context.tlb_gen);919920ns = choose_new_asid(next, next_tlb_gen);921}922923reload_tlb:924new_lam = mm_lam_cr3_mask(next);925if (ns.need_flush) {926VM_WARN_ON_ONCE(is_global_asid(ns.asid));927this_cpu_write(cpu_tlbstate.ctxs[ns.asid].ctx_id, next->context.ctx_id);928this_cpu_write(cpu_tlbstate.ctxs[ns.asid].tlb_gen, next_tlb_gen);929load_new_mm_cr3(next->pgd, ns.asid, new_lam, true);930931trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, TLB_FLUSH_ALL);932} else {933/* The new ASID is already up to date. */934load_new_mm_cr3(next->pgd, ns.asid, new_lam, false);935936trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, 0);937}938939/* Make sure we write CR3 before loaded_mm. */940barrier();941942this_cpu_write(cpu_tlbstate.loaded_mm, next);943this_cpu_write(cpu_tlbstate.loaded_mm_asid, ns.asid);944cpu_tlbstate_update_lam(new_lam, mm_untag_mask(next));945946if (next != prev) {947cr4_update_pce_mm(next);948switch_ldt(prev, next);949}950}951952/*953* Please ignore the name of this function. It should be called954* switch_to_kernel_thread().955*956* enter_lazy_tlb() is a hint from the scheduler that we are entering a957* kernel thread or other context without an mm. Acceptable implementations958* include doing nothing whatsoever, switching to init_mm, or various clever959* lazy tricks to try to minimize TLB flushes.960*961* The scheduler reserves the right to call enter_lazy_tlb() several times962* in a row. It will notify us that we're going back to a real mm by963* calling switch_mm_irqs_off().964*/965void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk)966{967if (this_cpu_read(cpu_tlbstate.loaded_mm) == &init_mm)968return;969970this_cpu_write(cpu_tlbstate_shared.is_lazy, true);971}972973/*974* Using a temporary mm allows to set temporary mappings that are not accessible975* by other CPUs. Such mappings are needed to perform sensitive memory writes976* that override the kernel memory protections (e.g., W^X), without exposing the977* temporary page-table mappings that are required for these write operations to978* other CPUs. Using a temporary mm also allows to avoid TLB shootdowns when the979* mapping is torn down. Temporary mms can also be used for EFI runtime service980* calls or similar functionality.981*982* It is illegal to schedule while using a temporary mm -- the context switch983* code is unaware of the temporary mm and does not know how to context switch.984* Use a real (non-temporary) mm in a kernel thread if you need to sleep.985*986* Note: For sensitive memory writes, the temporary mm needs to be used987* exclusively by a single core, and IRQs should be disabled while the988* temporary mm is loaded, thereby preventing interrupt handler bugs from989* overriding the kernel memory protection.990*/991struct mm_struct *use_temporary_mm(struct mm_struct *temp_mm)992{993struct mm_struct *prev_mm;994995lockdep_assert_preemption_disabled();996guard(irqsave)();997998/*999* Make sure not to be in TLB lazy mode, as otherwise we'll end up1000* with a stale address space WITHOUT being in lazy mode after1001* restoring the previous mm.1002*/1003if (this_cpu_read(cpu_tlbstate_shared.is_lazy))1004leave_mm();10051006prev_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1007switch_mm_irqs_off(NULL, temp_mm, current);10081009/*1010* If breakpoints are enabled, disable them while the temporary mm is1011* used. Userspace might set up watchpoints on addresses that are used1012* in the temporary mm, which would lead to wrong signals being sent or1013* crashes.1014*1015* Note that breakpoints are not disabled selectively, which also causes1016* kernel breakpoints (e.g., perf's) to be disabled. This might be1017* undesirable, but still seems reasonable as the code that runs in the1018* temporary mm should be short.1019*/1020if (hw_breakpoint_active())1021hw_breakpoint_disable();10221023return prev_mm;1024}10251026void unuse_temporary_mm(struct mm_struct *prev_mm)1027{1028lockdep_assert_preemption_disabled();1029guard(irqsave)();10301031/* Clear the cpumask, to indicate no TLB flushing is needed anywhere */1032cpumask_clear_cpu(smp_processor_id(), mm_cpumask(this_cpu_read(cpu_tlbstate.loaded_mm)));10331034switch_mm_irqs_off(NULL, prev_mm, current);10351036/*1037* Restore the breakpoints if they were disabled before the temporary mm1038* was loaded.1039*/1040if (hw_breakpoint_active())1041hw_breakpoint_restore();1042}10431044/*1045* Call this when reinitializing a CPU. It fixes the following potential1046* problems:1047*1048* - The ASID changed from what cpu_tlbstate thinks it is (most likely1049* because the CPU was taken down and came back up with CR3's PCID1050* bits clear. CPU hotplug can do this.1051*1052* - The TLB contains junk in slots corresponding to inactive ASIDs.1053*1054* - The CPU went so far out to lunch that it may have missed a TLB1055* flush.1056*/1057void initialize_tlbstate_and_flush(void)1058{1059int i;1060struct mm_struct *mm = this_cpu_read(cpu_tlbstate.loaded_mm);1061u64 tlb_gen = atomic64_read(&init_mm.context.tlb_gen);1062unsigned long lam = mm_lam_cr3_mask(mm);1063unsigned long cr3 = __read_cr3();10641065/* Assert that CR3 already references the right mm. */1066WARN_ON((cr3 & CR3_ADDR_MASK) != __pa(mm->pgd));10671068/* LAM expected to be disabled */1069WARN_ON(cr3 & (X86_CR3_LAM_U48 | X86_CR3_LAM_U57));1070WARN_ON(lam);10711072/*1073* Assert that CR4.PCIDE is set if needed. (CR4.PCIDE initialization1074* doesn't work like other CR4 bits because it can only be set from1075* long mode.)1076*/1077WARN_ON(boot_cpu_has(X86_FEATURE_PCID) &&1078!(cr4_read_shadow() & X86_CR4_PCIDE));10791080/* Disable LAM, force ASID 0 and force a TLB flush. */1081write_cr3(build_cr3(mm->pgd, 0, 0));10821083/* Reinitialize tlbstate. */1084this_cpu_write(cpu_tlbstate.last_user_mm_spec, LAST_USER_MM_INIT);1085this_cpu_write(cpu_tlbstate.loaded_mm_asid, 0);1086this_cpu_write(cpu_tlbstate.next_asid, 1);1087this_cpu_write(cpu_tlbstate.ctxs[0].ctx_id, mm->context.ctx_id);1088this_cpu_write(cpu_tlbstate.ctxs[0].tlb_gen, tlb_gen);1089cpu_tlbstate_update_lam(lam, mm_untag_mask(mm));10901091for (i = 1; i < TLB_NR_DYN_ASIDS; i++)1092this_cpu_write(cpu_tlbstate.ctxs[i].ctx_id, 0);1093}10941095/*1096* flush_tlb_func()'s memory ordering requirement is that any1097* TLB fills that happen after we flush the TLB are ordered after we1098* read active_mm's tlb_gen. We don't need any explicit barriers1099* because all x86 flush operations are serializing and the1100* atomic64_read operation won't be reordered by the compiler.1101*/1102static void flush_tlb_func(void *info)1103{1104/*1105* We have three different tlb_gen values in here. They are:1106*1107* - mm_tlb_gen: the latest generation.1108* - local_tlb_gen: the generation that this CPU has already caught1109* up to.1110* - f->new_tlb_gen: the generation that the requester of the flush1111* wants us to catch up to.1112*/1113const struct flush_tlb_info *f = info;1114struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1115u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1116u64 local_tlb_gen;1117bool local = smp_processor_id() == f->initiating_cpu;1118unsigned long nr_invalidate = 0;1119u64 mm_tlb_gen;11201121/* This code cannot presently handle being reentered. */1122VM_WARN_ON(!irqs_disabled());11231124if (!local) {1125inc_irq_stat(irq_tlb_count);1126count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);1127}11281129/* The CPU was left in the mm_cpumask of the target mm. Clear it. */1130if (f->mm && f->mm != loaded_mm) {1131cpumask_clear_cpu(raw_smp_processor_id(), mm_cpumask(f->mm));1132trace_tlb_flush(TLB_REMOTE_WRONG_CPU, 0);1133return;1134}11351136if (unlikely(loaded_mm == &init_mm))1137return;11381139/* Reload the ASID if transitioning into or out of a global ASID */1140if (mm_needs_global_asid(loaded_mm, loaded_mm_asid)) {1141switch_mm_irqs_off(NULL, loaded_mm, NULL);1142loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1143}11441145/* Broadcast ASIDs are always kept up to date with INVLPGB. */1146if (is_global_asid(loaded_mm_asid))1147return;11481149VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) !=1150loaded_mm->context.ctx_id);11511152if (this_cpu_read(cpu_tlbstate_shared.is_lazy)) {1153/*1154* We're in lazy mode. We need to at least flush our1155* paging-structure cache to avoid speculatively reading1156* garbage into our TLB. Since switching to init_mm is barely1157* slower than a minimal flush, just switch to init_mm.1158*1159* This should be rare, with native_flush_tlb_multi() skipping1160* IPIs to lazy TLB mode CPUs.1161*/1162switch_mm_irqs_off(NULL, &init_mm, NULL);1163return;1164}11651166local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen);11671168if (unlikely(f->new_tlb_gen != TLB_GENERATION_INVALID &&1169f->new_tlb_gen <= local_tlb_gen)) {1170/*1171* The TLB is already up to date in respect to f->new_tlb_gen.1172* While the core might be still behind mm_tlb_gen, checking1173* mm_tlb_gen unnecessarily would have negative caching effects1174* so avoid it.1175*/1176return;1177}11781179/*1180* Defer mm_tlb_gen reading as long as possible to avoid cache1181* contention.1182*/1183mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen);11841185if (unlikely(local_tlb_gen == mm_tlb_gen)) {1186/*1187* There's nothing to do: we're already up to date. This can1188* happen if two concurrent flushes happen -- the first flush to1189* be handled can catch us all the way up, leaving no work for1190* the second flush.1191*/1192goto done;1193}11941195WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen);1196WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen);11971198/*1199* If we get to this point, we know that our TLB is out of date.1200* This does not strictly imply that we need to flush (it's1201* possible that f->new_tlb_gen <= local_tlb_gen), but we're1202* going to need to flush in the very near future, so we might1203* as well get it over with.1204*1205* The only question is whether to do a full or partial flush.1206*1207* We do a partial flush if requested and two extra conditions1208* are met:1209*1210* 1. f->new_tlb_gen == local_tlb_gen + 1. We have an invariant that1211* we've always done all needed flushes to catch up to1212* local_tlb_gen. If, for example, local_tlb_gen == 2 and1213* f->new_tlb_gen == 3, then we know that the flush needed to bring1214* us up to date for tlb_gen 3 is the partial flush we're1215* processing.1216*1217* As an example of why this check is needed, suppose that there1218* are two concurrent flushes. The first is a full flush that1219* changes context.tlb_gen from 1 to 2. The second is a partial1220* flush that changes context.tlb_gen from 2 to 3. If they get1221* processed on this CPU in reverse order, we'll see1222* local_tlb_gen == 1, mm_tlb_gen == 3, and end != TLB_FLUSH_ALL.1223* If we were to use __flush_tlb_one_user() and set local_tlb_gen to1224* 3, we'd be break the invariant: we'd update local_tlb_gen above1225* 1 without the full flush that's needed for tlb_gen 2.1226*1227* 2. f->new_tlb_gen == mm_tlb_gen. This is purely an optimization.1228* Partial TLB flushes are not all that much cheaper than full TLB1229* flushes, so it seems unlikely that it would be a performance win1230* to do a partial flush if that won't bring our TLB fully up to1231* date. By doing a full flush instead, we can increase1232* local_tlb_gen all the way to mm_tlb_gen and we can probably1233* avoid another flush in the very near future.1234*/1235if (f->end != TLB_FLUSH_ALL &&1236f->new_tlb_gen == local_tlb_gen + 1 &&1237f->new_tlb_gen == mm_tlb_gen) {1238/* Partial flush */1239unsigned long addr = f->start;12401241/* Partial flush cannot have invalid generations */1242VM_WARN_ON(f->new_tlb_gen == TLB_GENERATION_INVALID);12431244/* Partial flush must have valid mm */1245VM_WARN_ON(f->mm == NULL);12461247nr_invalidate = (f->end - f->start) >> f->stride_shift;12481249while (addr < f->end) {1250flush_tlb_one_user(addr);1251addr += 1UL << f->stride_shift;1252}1253if (local)1254count_vm_tlb_events(NR_TLB_LOCAL_FLUSH_ONE, nr_invalidate);1255} else {1256/* Full flush. */1257nr_invalidate = TLB_FLUSH_ALL;12581259flush_tlb_local();1260if (local)1261count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);1262}12631264/* Both paths above update our state to mm_tlb_gen. */1265this_cpu_write(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen, mm_tlb_gen);12661267/* Tracing is done in a unified manner to reduce the code size */1268done:1269trace_tlb_flush(!local ? TLB_REMOTE_SHOOTDOWN :1270(f->mm == NULL) ? TLB_LOCAL_SHOOTDOWN :1271TLB_LOCAL_MM_SHOOTDOWN,1272nr_invalidate);1273}12741275static bool should_flush_tlb(int cpu, void *data)1276{1277struct mm_struct *loaded_mm = per_cpu(cpu_tlbstate.loaded_mm, cpu);1278struct flush_tlb_info *info = data;12791280/*1281* Order the 'loaded_mm' and 'is_lazy' against their1282* write ordering in switch_mm_irqs_off(). Ensure1283* 'is_lazy' is at least as new as 'loaded_mm'.1284*/1285smp_rmb();12861287/* Lazy TLB will get flushed at the next context switch. */1288if (per_cpu(cpu_tlbstate_shared.is_lazy, cpu))1289return false;12901291/* No mm means kernel memory flush. */1292if (!info->mm)1293return true;12941295/*1296* While switching, the remote CPU could have state from1297* either the prev or next mm. Assume the worst and flush.1298*/1299if (loaded_mm == LOADED_MM_SWITCHING)1300return true;13011302/* The target mm is loaded, and the CPU is not lazy. */1303if (loaded_mm == info->mm)1304return true;13051306/* In cpumask, but not the loaded mm? Periodically remove by flushing. */1307if (info->trim_cpumask)1308return true;13091310return false;1311}13121313static bool should_trim_cpumask(struct mm_struct *mm)1314{1315if (time_after(jiffies, READ_ONCE(mm->context.next_trim_cpumask))) {1316WRITE_ONCE(mm->context.next_trim_cpumask, jiffies + HZ);1317return true;1318}1319return false;1320}13211322DEFINE_PER_CPU_SHARED_ALIGNED(struct tlb_state_shared, cpu_tlbstate_shared);1323EXPORT_PER_CPU_SYMBOL(cpu_tlbstate_shared);13241325STATIC_NOPV void native_flush_tlb_multi(const struct cpumask *cpumask,1326const struct flush_tlb_info *info)1327{1328/*1329* Do accounting and tracing. Note that there are (and have always been)1330* cases in which a remote TLB flush will be traced, but eventually1331* would not happen.1332*/1333count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);1334if (info->end == TLB_FLUSH_ALL)1335trace_tlb_flush(TLB_REMOTE_SEND_IPI, TLB_FLUSH_ALL);1336else1337trace_tlb_flush(TLB_REMOTE_SEND_IPI,1338(info->end - info->start) >> PAGE_SHIFT);13391340/*1341* If no page tables were freed, we can skip sending IPIs to1342* CPUs in lazy TLB mode. They will flush the CPU themselves1343* at the next context switch.1344*1345* However, if page tables are getting freed, we need to send the1346* IPI everywhere, to prevent CPUs in lazy TLB mode from tripping1347* up on the new contents of what used to be page tables, while1348* doing a speculative memory access.1349*/1350if (info->freed_tables || mm_in_asid_transition(info->mm))1351on_each_cpu_mask(cpumask, flush_tlb_func, (void *)info, true);1352else1353on_each_cpu_cond_mask(should_flush_tlb, flush_tlb_func,1354(void *)info, 1, cpumask);1355}13561357void flush_tlb_multi(const struct cpumask *cpumask,1358const struct flush_tlb_info *info)1359{1360__flush_tlb_multi(cpumask, info);1361}13621363/*1364* See Documentation/arch/x86/tlb.rst for details. We choose 331365* because it is large enough to cover the vast majority (at1366* least 95%) of allocations, and is small enough that we are1367* confident it will not cause too much overhead. Each single1368* flush is about 100 ns, so this caps the maximum overhead at1369* _about_ 3,000 ns.1370*1371* This is in units of pages.1372*/1373unsigned long tlb_single_page_flush_ceiling __read_mostly = 33;13741375static DEFINE_PER_CPU_SHARED_ALIGNED(struct flush_tlb_info, flush_tlb_info);13761377#ifdef CONFIG_DEBUG_VM1378static DEFINE_PER_CPU(unsigned int, flush_tlb_info_idx);1379#endif13801381static struct flush_tlb_info *get_flush_tlb_info(struct mm_struct *mm,1382unsigned long start, unsigned long end,1383unsigned int stride_shift, bool freed_tables,1384u64 new_tlb_gen)1385{1386struct flush_tlb_info *info = this_cpu_ptr(&flush_tlb_info);13871388#ifdef CONFIG_DEBUG_VM1389/*1390* Ensure that the following code is non-reentrant and flush_tlb_info1391* is not overwritten. This means no TLB flushing is initiated by1392* interrupt handlers and machine-check exception handlers.1393*/1394BUG_ON(this_cpu_inc_return(flush_tlb_info_idx) != 1);1395#endif13961397/*1398* If the number of flushes is so large that a full flush1399* would be faster, do a full flush.1400*/1401if ((end - start) >> stride_shift > tlb_single_page_flush_ceiling) {1402start = 0;1403end = TLB_FLUSH_ALL;1404}14051406info->start = start;1407info->end = end;1408info->mm = mm;1409info->stride_shift = stride_shift;1410info->freed_tables = freed_tables;1411info->new_tlb_gen = new_tlb_gen;1412info->initiating_cpu = smp_processor_id();1413info->trim_cpumask = 0;14141415return info;1416}14171418static void put_flush_tlb_info(void)1419{1420#ifdef CONFIG_DEBUG_VM1421/* Complete reentrancy prevention checks */1422barrier();1423this_cpu_dec(flush_tlb_info_idx);1424#endif1425}14261427void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,1428unsigned long end, unsigned int stride_shift,1429bool freed_tables)1430{1431struct flush_tlb_info *info;1432int cpu = get_cpu();1433u64 new_tlb_gen;14341435/* This is also a barrier that synchronizes with switch_mm(). */1436new_tlb_gen = inc_mm_tlb_gen(mm);14371438info = get_flush_tlb_info(mm, start, end, stride_shift, freed_tables,1439new_tlb_gen);14401441/*1442* flush_tlb_multi() is not optimized for the common case in which only1443* a local TLB flush is needed. Optimize this use-case by calling1444* flush_tlb_func_local() directly in this case.1445*/1446if (mm_global_asid(mm)) {1447broadcast_tlb_flush(info);1448} else if (cpumask_any_but(mm_cpumask(mm), cpu) < nr_cpu_ids) {1449info->trim_cpumask = should_trim_cpumask(mm);1450flush_tlb_multi(mm_cpumask(mm), info);1451consider_global_asid(mm);1452} else if (mm == this_cpu_read(cpu_tlbstate.loaded_mm)) {1453lockdep_assert_irqs_enabled();1454local_irq_disable();1455flush_tlb_func(info);1456local_irq_enable();1457}14581459put_flush_tlb_info();1460put_cpu();1461mmu_notifier_arch_invalidate_secondary_tlbs(mm, start, end);1462}14631464static void do_flush_tlb_all(void *info)1465{1466count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);1467__flush_tlb_all();1468}14691470void flush_tlb_all(void)1471{1472count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);14731474/* First try (faster) hardware-assisted TLB invalidation. */1475if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1476invlpgb_flush_all();1477else1478/* Fall back to the IPI-based invalidation. */1479on_each_cpu(do_flush_tlb_all, NULL, 1);1480}14811482/* Flush an arbitrarily large range of memory with INVLPGB. */1483static void invlpgb_kernel_range_flush(struct flush_tlb_info *info)1484{1485unsigned long addr, nr;14861487for (addr = info->start; addr < info->end; addr += nr << PAGE_SHIFT) {1488nr = (info->end - addr) >> PAGE_SHIFT;14891490/*1491* INVLPGB has a limit on the size of ranges it can1492* flush. Break up large flushes.1493*/1494nr = clamp_val(nr, 1, invlpgb_count_max);14951496invlpgb_flush_addr_nosync(addr, nr);1497}1498__tlbsync();1499}15001501static void do_kernel_range_flush(void *info)1502{1503struct flush_tlb_info *f = info;1504unsigned long addr;15051506/* flush range by one by one 'invlpg' */1507for (addr = f->start; addr < f->end; addr += PAGE_SIZE)1508flush_tlb_one_kernel(addr);1509}15101511static void kernel_tlb_flush_all(struct flush_tlb_info *info)1512{1513if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1514invlpgb_flush_all();1515else1516on_each_cpu(do_flush_tlb_all, NULL, 1);1517}15181519static void kernel_tlb_flush_range(struct flush_tlb_info *info)1520{1521if (cpu_feature_enabled(X86_FEATURE_INVLPGB))1522invlpgb_kernel_range_flush(info);1523else1524on_each_cpu(do_kernel_range_flush, info, 1);1525}15261527void flush_tlb_kernel_range(unsigned long start, unsigned long end)1528{1529struct flush_tlb_info *info;15301531guard(preempt)();15321533info = get_flush_tlb_info(NULL, start, end, PAGE_SHIFT, false,1534TLB_GENERATION_INVALID);15351536if (info->end == TLB_FLUSH_ALL)1537kernel_tlb_flush_all(info);1538else1539kernel_tlb_flush_range(info);15401541put_flush_tlb_info();1542}15431544/*1545* This can be used from process context to figure out what the value of1546* CR3 is without needing to do a (slow) __read_cr3().1547*1548* It's intended to be used for code like KVM that sneakily changes CR31549* and needs to restore it. It needs to be used very carefully.1550*/1551unsigned long __get_current_cr3_fast(void)1552{1553unsigned long cr3 =1554build_cr3(this_cpu_read(cpu_tlbstate.loaded_mm)->pgd,1555this_cpu_read(cpu_tlbstate.loaded_mm_asid),1556tlbstate_lam_cr3_mask());15571558/* For now, be very restrictive about when this can be called. */1559VM_WARN_ON(in_nmi() || preemptible());15601561VM_BUG_ON(cr3 != __read_cr3());1562return cr3;1563}1564EXPORT_SYMBOL_GPL(__get_current_cr3_fast);15651566/*1567* Flush one page in the kernel mapping1568*/1569void flush_tlb_one_kernel(unsigned long addr)1570{1571count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);15721573/*1574* If PTI is off, then __flush_tlb_one_user() is just INVLPG or its1575* paravirt equivalent. Even with PCID, this is sufficient: we only1576* use PCID if we also use global PTEs for the kernel mapping, and1577* INVLPG flushes global translations across all address spaces.1578*1579* If PTI is on, then the kernel is mapped with non-global PTEs, and1580* __flush_tlb_one_user() will flush the given address for the current1581* kernel address space and for its usermode counterpart, but it does1582* not flush it for other address spaces.1583*/1584flush_tlb_one_user(addr);15851586if (!static_cpu_has(X86_FEATURE_PTI))1587return;15881589/*1590* See above. We need to propagate the flush to all other address1591* spaces. In principle, we only need to propagate it to kernelmode1592* address spaces, but the extra bookkeeping we would need is not1593* worth it.1594*/1595this_cpu_write(cpu_tlbstate.invalidate_other, true);1596}15971598/*1599* Flush one page in the user mapping1600*/1601STATIC_NOPV void native_flush_tlb_one_user(unsigned long addr)1602{1603u32 loaded_mm_asid;1604bool cpu_pcide;16051606/* Flush 'addr' from the kernel PCID: */1607invlpg(addr);16081609/* If PTI is off there is no user PCID and nothing to flush. */1610if (!static_cpu_has(X86_FEATURE_PTI))1611return;16121613loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);1614cpu_pcide = this_cpu_read(cpu_tlbstate.cr4) & X86_CR4_PCIDE;16151616/*1617* invpcid_flush_one(pcid>0) will #GP if CR4.PCIDE==0. Check1618* 'cpu_pcide' to ensure that *this* CPU will not trigger those1619* #GP's even if called before CR4.PCIDE has been initialized.1620*/1621if (boot_cpu_has(X86_FEATURE_INVPCID) && cpu_pcide)1622invpcid_flush_one(user_pcid(loaded_mm_asid), addr);1623else1624invalidate_user_asid(loaded_mm_asid);1625}16261627void flush_tlb_one_user(unsigned long addr)1628{1629__flush_tlb_one_user(addr);1630}16311632/*1633* Flush everything1634*/1635STATIC_NOPV void native_flush_tlb_global(void)1636{1637unsigned long flags;16381639if (static_cpu_has(X86_FEATURE_INVPCID)) {1640/*1641* Using INVPCID is considerably faster than a pair of writes1642* to CR4 sandwiched inside an IRQ flag save/restore.1643*1644* Note, this works with CR4.PCIDE=0 or 1.1645*/1646invpcid_flush_all();1647return;1648}16491650/*1651* Read-modify-write to CR4 - protect it from preemption and1652* from interrupts. (Use the raw variant because this code can1653* be called from deep inside debugging code.)1654*/1655raw_local_irq_save(flags);16561657__native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4));16581659raw_local_irq_restore(flags);1660}16611662/*1663* Flush the entire current user mapping1664*/1665STATIC_NOPV void native_flush_tlb_local(void)1666{1667/*1668* Preemption or interrupts must be disabled to protect the access1669* to the per CPU variable and to prevent being preempted between1670* read_cr3() and write_cr3().1671*/1672WARN_ON_ONCE(preemptible());16731674invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid));16751676/* If current->mm == NULL then the read_cr3() "borrows" an mm */1677native_write_cr3(__native_read_cr3());1678}16791680void flush_tlb_local(void)1681{1682__flush_tlb_local();1683}16841685/*1686* Flush everything1687*/1688void __flush_tlb_all(void)1689{1690/*1691* This is to catch users with enabled preemption and the PGE feature1692* and don't trigger the warning in __native_flush_tlb().1693*/1694VM_WARN_ON_ONCE(preemptible());16951696if (cpu_feature_enabled(X86_FEATURE_PGE)) {1697__flush_tlb_global();1698} else {1699/*1700* !PGE -> !PCID (setup_pcid()), thus every flush is total.1701*/1702flush_tlb_local();1703}1704}1705EXPORT_SYMBOL_GPL(__flush_tlb_all);17061707void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)1708{1709struct flush_tlb_info *info;17101711int cpu = get_cpu();17121713info = get_flush_tlb_info(NULL, 0, TLB_FLUSH_ALL, 0, false,1714TLB_GENERATION_INVALID);1715/*1716* flush_tlb_multi() is not optimized for the common case in which only1717* a local TLB flush is needed. Optimize this use-case by calling1718* flush_tlb_func_local() directly in this case.1719*/1720if (cpu_feature_enabled(X86_FEATURE_INVLPGB) && batch->unmapped_pages) {1721invlpgb_flush_all_nonglobals();1722batch->unmapped_pages = false;1723} else if (cpumask_any_but(&batch->cpumask, cpu) < nr_cpu_ids) {1724flush_tlb_multi(&batch->cpumask, info);1725} else if (cpumask_test_cpu(cpu, &batch->cpumask)) {1726lockdep_assert_irqs_enabled();1727local_irq_disable();1728flush_tlb_func(info);1729local_irq_enable();1730}17311732cpumask_clear(&batch->cpumask);17331734put_flush_tlb_info();1735put_cpu();1736}17371738/*1739* Blindly accessing user memory from NMI context can be dangerous1740* if we're in the middle of switching the current user task or1741* switching the loaded mm. It can also be dangerous if we1742* interrupted some kernel code that was temporarily using a1743* different mm.1744*/1745bool nmi_uaccess_okay(void)1746{1747struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);1748struct mm_struct *current_mm = current->mm;17491750VM_WARN_ON_ONCE(!loaded_mm);17511752/*1753* The condition we want to check is1754* current_mm->pgd == __va(read_cr3_pa()). This may be slow, though,1755* if we're running in a VM with shadow paging, and nmi_uaccess_okay()1756* is supposed to be reasonably fast.1757*1758* Instead, we check the almost equivalent but somewhat conservative1759* condition below, and we rely on the fact that switch_mm_irqs_off()1760* sets loaded_mm to LOADED_MM_SWITCHING before writing to CR3.1761*/1762if (loaded_mm != current_mm)1763return false;17641765VM_WARN_ON_ONCE(__pa(current_mm->pgd) != read_cr3_pa());17661767return true;1768}17691770static ssize_t tlbflush_read_file(struct file *file, char __user *user_buf,1771size_t count, loff_t *ppos)1772{1773char buf[32];1774unsigned int len;17751776len = sprintf(buf, "%ld\n", tlb_single_page_flush_ceiling);1777return simple_read_from_buffer(user_buf, count, ppos, buf, len);1778}17791780static ssize_t tlbflush_write_file(struct file *file,1781const char __user *user_buf, size_t count, loff_t *ppos)1782{1783char buf[32];1784ssize_t len;1785int ceiling;17861787len = min(count, sizeof(buf) - 1);1788if (copy_from_user(buf, user_buf, len))1789return -EFAULT;17901791buf[len] = '\0';1792if (kstrtoint(buf, 0, &ceiling))1793return -EINVAL;17941795if (ceiling < 0)1796return -EINVAL;17971798tlb_single_page_flush_ceiling = ceiling;1799return count;1800}18011802static const struct file_operations fops_tlbflush = {1803.read = tlbflush_read_file,1804.write = tlbflush_write_file,1805.llseek = default_llseek,1806};18071808static int __init create_tlb_single_page_flush_ceiling(void)1809{1810debugfs_create_file("tlb_single_page_flush_ceiling", S_IRUSR | S_IWUSR,1811arch_debugfs_dir, NULL, &fops_tlbflush);1812return 0;1813}1814late_initcall(create_tlb_single_page_flush_ceiling);181518161817