1  // SPDX-License-Identifier: GPL-2.0-only
2  #include <linux/init.h>
3  
4  #include <linux/mm.h>
5  #include <linux/spinlock.h>
6  #include <linux/smp.h>
7  #include <linux/interrupt.h>
8  #include <linux/export.h>
9  #include <linux/cpu.h>
10  #include <linux/debugfs.h>
11  #include <linux/sched/smt.h>
12  #include <linux/task_work.h>
13  #include <linux/mmu_notifier.h>
14  #include <linux/mmu_context.h>
15  
16  #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/perf_event.h>
23  
24  #include "mm_internal.h"
25  
26  #ifdef CONFIG_PARAVIRT
27  # define STATIC_NOPV
28  #else
29  # define STATIC_NOPV			static
30  # define __flush_tlb_local		native_flush_tlb_local
31  # define __flush_tlb_global		native_flush_tlb_global
32  # define __flush_tlb_one_user(addr)	native_flush_tlb_one_user(addr)
33  # define __flush_tlb_multi(msk, info)	native_flush_tlb_multi(msk, info)
34  #endif
35  
36  /*
37   *	TLB flushing, formerly SMP-only
38   *		c/o Linus Torvalds.
39   *
40   *	These mean you can really definitely utterly forget about
41   *	writing to user space from interrupts. (Its not allowed anyway).
42   *
43   *	Optimizations Manfred Spraul <manfred@colorfullife.com>
44   *
45   *	More scalable flush, from Andi Kleen
46   *
47   *	Implement flush IPI by CALL_FUNCTION_VECTOR, Alex Shi
48   */
49  
50  /*
51   * Bits to mangle the TIF_SPEC_* state into the mm pointer which is
52   * stored in cpu_tlb_state.last_user_mm_spec.
53   */
54  #define LAST_USER_MM_IBPB	0x1UL
55  #define LAST_USER_MM_L1D_FLUSH	0x2UL
56  #define LAST_USER_MM_SPEC_MASK	(LAST_USER_MM_IBPB | LAST_USER_MM_L1D_FLUSH)
57  
58  /* Bits to set when tlbstate and flush is (re)initialized */
59  #define LAST_USER_MM_INIT	LAST_USER_MM_IBPB
60  
61  /*
62   * The x86 feature is called PCID (Process Context IDentifier). It is similar
63   * to what is traditionally called ASID on the RISC processors.
64   *
65   * We don't use the traditional ASID implementation, where each process/mm gets
66   * its own ASID and flush/restart when we run out of ASID space.
67   *
68   * Instead we have a small per-cpu array of ASIDs and cache the last few mm's
69   * that came by on this CPU, allowing cheaper switch_mm between processes on
70   * this CPU.
71   *
72   * We end up with different spaces for different things. To avoid confusion we
73   * use different names for each of them:
74   *
75   * ASID  - [0, TLB_NR_DYN_ASIDS-1]
76   *         the canonical identifier for an mm
77   *
78   * kPCID - [1, TLB_NR_DYN_ASIDS]
79   *         the value we write into the PCID part of CR3; corresponds to the
80   *         ASID+1, because PCID 0 is special.
81   *
82   * uPCID - [2048 + 1, 2048 + TLB_NR_DYN_ASIDS]
83   *         for KPTI each mm has two address spaces and thus needs two
84   *         PCID values, but we can still do with a single ASID denomination
85   *         for each mm. Corresponds to kPCID + 2048.
86   *
87   */
88  
89  /*
90   * When enabled, MITIGATION_PAGE_TABLE_ISOLATION consumes a single bit for
91   * user/kernel switches
92   */
93  #ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION
94  # define PTI_CONSUMED_PCID_BITS	1
95  #else
96  # define PTI_CONSUMED_PCID_BITS	0
97  #endif
98  
99  #define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS)
100  
101  /*
102   * ASIDs are zero-based: 0->MAX_AVAIL_ASID are valid.  -1 below to account
103   * for them being zero-based.  Another -1 is because PCID 0 is reserved for
104   * use by non-PCID-aware users.
105   */
106  #define MAX_ASID_AVAILABLE ((1 << CR3_AVAIL_PCID_BITS) - 2)
107  
108  /*
109   * Given @asid, compute kPCID
110   */
kern_pcid(u16 asid)111  static inline u16 kern_pcid(u16 asid)
112  {
113  	VM_WARN_ON_ONCE(asid > MAX_ASID_AVAILABLE);
114  
115  #ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION
116  	/*
117  	 * Make sure that the dynamic ASID space does not conflict with the
118  	 * bit we are using to switch between user and kernel ASIDs.
119  	 */
120  	BUILD_BUG_ON(TLB_NR_DYN_ASIDS >= (1 << X86_CR3_PTI_PCID_USER_BIT));
121  
122  	/*
123  	 * The ASID being passed in here should have respected the
124  	 * MAX_ASID_AVAILABLE and thus never have the switch bit set.
125  	 */
126  	VM_WARN_ON_ONCE(asid & (1 << X86_CR3_PTI_PCID_USER_BIT));
127  #endif
128  	/*
129  	 * The dynamically-assigned ASIDs that get passed in are small
130  	 * (<TLB_NR_DYN_ASIDS).  They never have the high switch bit set,
131  	 * so do not bother to clear it.
132  	 *
133  	 * If PCID is on, ASID-aware code paths put the ASID+1 into the
134  	 * PCID bits.  This serves two purposes.  It prevents a nasty
135  	 * situation in which PCID-unaware code saves CR3, loads some other
136  	 * value (with PCID == 0), and then restores CR3, thus corrupting
137  	 * the TLB for ASID 0 if the saved ASID was nonzero.  It also means
138  	 * that any bugs involving loading a PCID-enabled CR3 with
139  	 * CR4.PCIDE off will trigger deterministically.
140  	 */
141  	return asid + 1;
142  }
143  
144  /*
145   * Given @asid, compute uPCID
146   */
user_pcid(u16 asid)147  static inline u16 user_pcid(u16 asid)
148  {
149  	u16 ret = kern_pcid(asid);
150  #ifdef CONFIG_MITIGATION_PAGE_TABLE_ISOLATION
151  	ret |= 1 << X86_CR3_PTI_PCID_USER_BIT;
152  #endif
153  	return ret;
154  }
155  
build_cr3(pgd_t * pgd,u16 asid,unsigned long lam)156  static inline unsigned long build_cr3(pgd_t *pgd, u16 asid, unsigned long lam)
157  {
158  	unsigned long cr3 = __sme_pa(pgd) | lam;
159  
160  	if (static_cpu_has(X86_FEATURE_PCID)) {
161  		cr3 |= kern_pcid(asid);
162  	} else {
163  		VM_WARN_ON_ONCE(asid != 0);
164  	}
165  
166  	return cr3;
167  }
168  
build_cr3_noflush(pgd_t * pgd,u16 asid,unsigned long lam)169  static inline unsigned long build_cr3_noflush(pgd_t *pgd, u16 asid,
170  					      unsigned long lam)
171  {
172  	/*
173  	 * Use boot_cpu_has() instead of this_cpu_has() as this function
174  	 * might be called during early boot. This should work even after
175  	 * boot because all CPU's the have same capabilities:
176  	 */
177  	VM_WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_PCID));
178  	return build_cr3(pgd, asid, lam) | CR3_NOFLUSH;
179  }
180  
181  /*
182   * We get here when we do something requiring a TLB invalidation
183   * but could not go invalidate all of the contexts.  We do the
184   * necessary invalidation by clearing out the 'ctx_id' which
185   * forces a TLB flush when the context is loaded.
186   */
clear_asid_other(void)187  static void clear_asid_other(void)
188  {
189  	u16 asid;
190  
191  	/*
192  	 * This is only expected to be set if we have disabled
193  	 * kernel _PAGE_GLOBAL pages.
194  	 */
195  	if (!static_cpu_has(X86_FEATURE_PTI)) {
196  		WARN_ON_ONCE(1);
197  		return;
198  	}
199  
200  	for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {
201  		/* Do not need to flush the current asid */
202  		if (asid == this_cpu_read(cpu_tlbstate.loaded_mm_asid))
203  			continue;
204  		/*
205  		 * Make sure the next time we go to switch to
206  		 * this asid, we do a flush:
207  		 */
208  		this_cpu_write(cpu_tlbstate.ctxs[asid].ctx_id, 0);
209  	}
210  	this_cpu_write(cpu_tlbstate.invalidate_other, false);
211  }
212  
213  atomic64_t last_mm_ctx_id = ATOMIC64_INIT(1);
214  
215  
choose_new_asid(struct mm_struct * next,u64 next_tlb_gen,u16 * new_asid,bool * need_flush)216  static void choose_new_asid(struct mm_struct *next, u64 next_tlb_gen,
217  			    u16 *new_asid, bool *need_flush)
218  {
219  	u16 asid;
220  
221  	if (!static_cpu_has(X86_FEATURE_PCID)) {
222  		*new_asid = 0;
223  		*need_flush = true;
224  		return;
225  	}
226  
227  	if (this_cpu_read(cpu_tlbstate.invalidate_other))
228  		clear_asid_other();
229  
230  	for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {
231  		if (this_cpu_read(cpu_tlbstate.ctxs[asid].ctx_id) !=
232  		    next->context.ctx_id)
233  			continue;
234  
235  		*new_asid = asid;
236  		*need_flush = (this_cpu_read(cpu_tlbstate.ctxs[asid].tlb_gen) <
237  			       next_tlb_gen);
238  		return;
239  	}
240  
241  	/*
242  	 * We don't currently own an ASID slot on this CPU.
243  	 * Allocate a slot.
244  	 */
245  	*new_asid = this_cpu_add_return(cpu_tlbstate.next_asid, 1) - 1;
246  	if (*new_asid >= TLB_NR_DYN_ASIDS) {
247  		*new_asid = 0;
248  		this_cpu_write(cpu_tlbstate.next_asid, 1);
249  	}
250  	*need_flush = true;
251  }
252  
253  /*
254   * Given an ASID, flush the corresponding user ASID.  We can delay this
255   * until the next time we switch to it.
256   *
257   * See SWITCH_TO_USER_CR3.
258   */
invalidate_user_asid(u16 asid)259  static inline void invalidate_user_asid(u16 asid)
260  {
261  	/* There is no user ASID if address space separation is off */
262  	if (!IS_ENABLED(CONFIG_MITIGATION_PAGE_TABLE_ISOLATION))
263  		return;
264  
265  	/*
266  	 * We only have a single ASID if PCID is off and the CR3
267  	 * write will have flushed it.
268  	 */
269  	if (!cpu_feature_enabled(X86_FEATURE_PCID))
270  		return;
271  
272  	if (!static_cpu_has(X86_FEATURE_PTI))
273  		return;
274  
275  	__set_bit(kern_pcid(asid),
276  		  (unsigned long *)this_cpu_ptr(&cpu_tlbstate.user_pcid_flush_mask));
277  }
278  
load_new_mm_cr3(pgd_t * pgdir,u16 new_asid,unsigned long lam,bool need_flush)279  static void load_new_mm_cr3(pgd_t *pgdir, u16 new_asid, unsigned long lam,
280  			    bool need_flush)
281  {
282  	unsigned long new_mm_cr3;
283  
284  	if (need_flush) {
285  		invalidate_user_asid(new_asid);
286  		new_mm_cr3 = build_cr3(pgdir, new_asid, lam);
287  	} else {
288  		new_mm_cr3 = build_cr3_noflush(pgdir, new_asid, lam);
289  	}
290  
291  	/*
292  	 * Caution: many callers of this function expect
293  	 * that load_cr3() is serializing and orders TLB
294  	 * fills with respect to the mm_cpumask writes.
295  	 */
296  	write_cr3(new_mm_cr3);
297  }
298  
leave_mm(void)299  void leave_mm(void)
300  {
301  	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
302  
303  	/*
304  	 * It's plausible that we're in lazy TLB mode while our mm is init_mm.
305  	 * If so, our callers still expect us to flush the TLB, but there
306  	 * aren't any user TLB entries in init_mm to worry about.
307  	 *
308  	 * This needs to happen before any other sanity checks due to
309  	 * intel_idle's shenanigans.
310  	 */
311  	if (loaded_mm == &init_mm)
312  		return;
313  
314  	/* Warn if we're not lazy. */
315  	WARN_ON(!this_cpu_read(cpu_tlbstate_shared.is_lazy));
316  
317  	switch_mm(NULL, &init_mm, NULL);
318  }
319  EXPORT_SYMBOL_GPL(leave_mm);
320  
switch_mm(struct mm_struct * prev,struct mm_struct * next,struct task_struct * tsk)321  void switch_mm(struct mm_struct *prev, struct mm_struct *next,
322  	       struct task_struct *tsk)
323  {
324  	unsigned long flags;
325  
326  	local_irq_save(flags);
327  	switch_mm_irqs_off(NULL, next, tsk);
328  	local_irq_restore(flags);
329  }
330  
331  /*
332   * Invoked from return to user/guest by a task that opted-in to L1D
333   * flushing but ended up running on an SMT enabled core due to wrong
334   * affinity settings or CPU hotplug. This is part of the paranoid L1D flush
335   * contract which this task requested.
336   */
l1d_flush_force_sigbus(struct callback_head * ch)337  static void l1d_flush_force_sigbus(struct callback_head *ch)
338  {
339  	force_sig(SIGBUS);
340  }
341  
l1d_flush_evaluate(unsigned long prev_mm,unsigned long next_mm,struct task_struct * next)342  static void l1d_flush_evaluate(unsigned long prev_mm, unsigned long next_mm,
343  				struct task_struct *next)
344  {
345  	/* Flush L1D if the outgoing task requests it */
346  	if (prev_mm & LAST_USER_MM_L1D_FLUSH)
347  		wrmsrl(MSR_IA32_FLUSH_CMD, L1D_FLUSH);
348  
349  	/* Check whether the incoming task opted in for L1D flush */
350  	if (likely(!(next_mm & LAST_USER_MM_L1D_FLUSH)))
351  		return;
352  
353  	/*
354  	 * Validate that it is not running on an SMT sibling as this would
355  	 * make the exercise pointless because the siblings share L1D. If
356  	 * it runs on a SMT sibling, notify it with SIGBUS on return to
357  	 * user/guest
358  	 */
359  	if (this_cpu_read(cpu_info.smt_active)) {
360  		clear_ti_thread_flag(&next->thread_info, TIF_SPEC_L1D_FLUSH);
361  		next->l1d_flush_kill.func = l1d_flush_force_sigbus;
362  		task_work_add(next, &next->l1d_flush_kill, TWA_RESUME);
363  	}
364  }
365  
mm_mangle_tif_spec_bits(struct task_struct * next)366  static unsigned long mm_mangle_tif_spec_bits(struct task_struct *next)
367  {
368  	unsigned long next_tif = read_task_thread_flags(next);
369  	unsigned long spec_bits = (next_tif >> TIF_SPEC_IB) & LAST_USER_MM_SPEC_MASK;
370  
371  	/*
372  	 * Ensure that the bit shift above works as expected and the two flags
373  	 * end up in bit 0 and 1.
374  	 */
375  	BUILD_BUG_ON(TIF_SPEC_L1D_FLUSH != TIF_SPEC_IB + 1);
376  
377  	return (unsigned long)next->mm | spec_bits;
378  }
379  
cond_mitigation(struct task_struct * next)380  static void cond_mitigation(struct task_struct *next)
381  {
382  	unsigned long prev_mm, next_mm;
383  
384  	if (!next || !next->mm)
385  		return;
386  
387  	next_mm = mm_mangle_tif_spec_bits(next);
388  	prev_mm = this_cpu_read(cpu_tlbstate.last_user_mm_spec);
389  
390  	/*
391  	 * Avoid user/user BTB poisoning by flushing the branch predictor
392  	 * when switching between processes. This stops one process from
393  	 * doing Spectre-v2 attacks on another.
394  	 *
395  	 * Both, the conditional and the always IBPB mode use the mm
396  	 * pointer to avoid the IBPB when switching between tasks of the
397  	 * same process. Using the mm pointer instead of mm->context.ctx_id
398  	 * opens a hypothetical hole vs. mm_struct reuse, which is more or
399  	 * less impossible to control by an attacker. Aside of that it
400  	 * would only affect the first schedule so the theoretically
401  	 * exposed data is not really interesting.
402  	 */
403  	if (static_branch_likely(&switch_mm_cond_ibpb)) {
404  		/*
405  		 * This is a bit more complex than the always mode because
406  		 * it has to handle two cases:
407  		 *
408  		 * 1) Switch from a user space task (potential attacker)
409  		 *    which has TIF_SPEC_IB set to a user space task
410  		 *    (potential victim) which has TIF_SPEC_IB not set.
411  		 *
412  		 * 2) Switch from a user space task (potential attacker)
413  		 *    which has TIF_SPEC_IB not set to a user space task
414  		 *    (potential victim) which has TIF_SPEC_IB set.
415  		 *
416  		 * This could be done by unconditionally issuing IBPB when
417  		 * a task which has TIF_SPEC_IB set is either scheduled in
418  		 * or out. Though that results in two flushes when:
419  		 *
420  		 * - the same user space task is scheduled out and later
421  		 *   scheduled in again and only a kernel thread ran in
422  		 *   between.
423  		 *
424  		 * - a user space task belonging to the same process is
425  		 *   scheduled in after a kernel thread ran in between
426  		 *
427  		 * - a user space task belonging to the same process is
428  		 *   scheduled in immediately.
429  		 *
430  		 * Optimize this with reasonably small overhead for the
431  		 * above cases. Mangle the TIF_SPEC_IB bit into the mm
432  		 * pointer of the incoming task which is stored in
433  		 * cpu_tlbstate.last_user_mm_spec for comparison.
434  		 *
435  		 * Issue IBPB only if the mm's are different and one or
436  		 * both have the IBPB bit set.
437  		 */
438  		if (next_mm != prev_mm &&
439  		    (next_mm | prev_mm) & LAST_USER_MM_IBPB)
440  			indirect_branch_prediction_barrier();
441  	}
442  
443  	if (static_branch_unlikely(&switch_mm_always_ibpb)) {
444  		/*
445  		 * Only flush when switching to a user space task with a
446  		 * different context than the user space task which ran
447  		 * last on this CPU.
448  		 */
449  		if ((prev_mm & ~LAST_USER_MM_SPEC_MASK) !=
450  					(unsigned long)next->mm)
451  			indirect_branch_prediction_barrier();
452  	}
453  
454  	if (static_branch_unlikely(&switch_mm_cond_l1d_flush)) {
455  		/*
456  		 * Flush L1D when the outgoing task requested it and/or
457  		 * check whether the incoming task requested L1D flushing
458  		 * and ended up on an SMT sibling.
459  		 */
460  		if (unlikely((prev_mm | next_mm) & LAST_USER_MM_L1D_FLUSH))
461  			l1d_flush_evaluate(prev_mm, next_mm, next);
462  	}
463  
464  	this_cpu_write(cpu_tlbstate.last_user_mm_spec, next_mm);
465  }
466  
467  #ifdef CONFIG_PERF_EVENTS
cr4_update_pce_mm(struct mm_struct * mm)468  static inline void cr4_update_pce_mm(struct mm_struct *mm)
469  {
470  	if (static_branch_unlikely(&rdpmc_always_available_key) ||
471  	    (!static_branch_unlikely(&rdpmc_never_available_key) &&
472  	     atomic_read(&mm->context.perf_rdpmc_allowed))) {
473  		/*
474  		 * Clear the existing dirty counters to
475  		 * prevent the leak for an RDPMC task.
476  		 */
477  		perf_clear_dirty_counters();
478  		cr4_set_bits_irqsoff(X86_CR4_PCE);
479  	} else
480  		cr4_clear_bits_irqsoff(X86_CR4_PCE);
481  }
482  
cr4_update_pce(void * ignored)483  void cr4_update_pce(void *ignored)
484  {
485  	cr4_update_pce_mm(this_cpu_read(cpu_tlbstate.loaded_mm));
486  }
487  
488  #else
cr4_update_pce_mm(struct mm_struct * mm)489  static inline void cr4_update_pce_mm(struct mm_struct *mm) { }
490  #endif
491  
492  /*
493   * This optimizes when not actually switching mm's.  Some architectures use the
494   * 'unused' argument for this optimization, but x86 must use
495   * 'cpu_tlbstate.loaded_mm' instead because it does not always keep
496   * 'current->active_mm' up to date.
497   */
switch_mm_irqs_off(struct mm_struct * unused,struct mm_struct * next,struct task_struct * tsk)498  void switch_mm_irqs_off(struct mm_struct *unused, struct mm_struct *next,
499  			struct task_struct *tsk)
500  {
501  	struct mm_struct *prev = this_cpu_read(cpu_tlbstate.loaded_mm);
502  	u16 prev_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
503  	bool was_lazy = this_cpu_read(cpu_tlbstate_shared.is_lazy);
504  	unsigned cpu = smp_processor_id();
505  	unsigned long new_lam;
506  	u64 next_tlb_gen;
507  	bool need_flush;
508  	u16 new_asid;
509  
510  	/* We don't want flush_tlb_func() to run concurrently with us. */
511  	if (IS_ENABLED(CONFIG_PROVE_LOCKING))
512  		WARN_ON_ONCE(!irqs_disabled());
513  
514  	/*
515  	 * Verify that CR3 is what we think it is.  This will catch
516  	 * hypothetical buggy code that directly switches to swapper_pg_dir
517  	 * without going through leave_mm() / switch_mm_irqs_off() or that
518  	 * does something like write_cr3(read_cr3_pa()).
519  	 *
520  	 * Only do this check if CONFIG_DEBUG_VM=y because __read_cr3()
521  	 * isn't free.
522  	 */
523  #ifdef CONFIG_DEBUG_VM
524  	if (WARN_ON_ONCE(__read_cr3() != build_cr3(prev->pgd, prev_asid,
525  						   tlbstate_lam_cr3_mask()))) {
526  		/*
527  		 * If we were to BUG here, we'd be very likely to kill
528  		 * the system so hard that we don't see the call trace.
529  		 * Try to recover instead by ignoring the error and doing
530  		 * a global flush to minimize the chance of corruption.
531  		 *
532  		 * (This is far from being a fully correct recovery.
533  		 *  Architecturally, the CPU could prefetch something
534  		 *  back into an incorrect ASID slot and leave it there
535  		 *  to cause trouble down the road.  It's better than
536  		 *  nothing, though.)
537  		 */
538  		__flush_tlb_all();
539  	}
540  #endif
541  	if (was_lazy)
542  		this_cpu_write(cpu_tlbstate_shared.is_lazy, false);
543  
544  	/*
545  	 * The membarrier system call requires a full memory barrier and
546  	 * core serialization before returning to user-space, after
547  	 * storing to rq->curr, when changing mm.  This is because
548  	 * membarrier() sends IPIs to all CPUs that are in the target mm
549  	 * to make them issue memory barriers.  However, if another CPU
550  	 * switches to/from the target mm concurrently with
551  	 * membarrier(), it can cause that CPU not to receive an IPI
552  	 * when it really should issue a memory barrier.  Writing to CR3
553  	 * provides that full memory barrier and core serializing
554  	 * instruction.
555  	 */
556  	if (prev == next) {
557  		/* Not actually switching mm's */
558  		VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[prev_asid].ctx_id) !=
559  			   next->context.ctx_id);
560  
561  		/*
562  		 * If this races with another thread that enables lam, 'new_lam'
563  		 * might not match tlbstate_lam_cr3_mask().
564  		 */
565  
566  		/*
567  		 * Even in lazy TLB mode, the CPU should stay set in the
568  		 * mm_cpumask. The TLB shootdown code can figure out from
569  		 * cpu_tlbstate_shared.is_lazy whether or not to send an IPI.
570  		 */
571  		if (WARN_ON_ONCE(prev != &init_mm &&
572  				 !cpumask_test_cpu(cpu, mm_cpumask(next))))
573  			cpumask_set_cpu(cpu, mm_cpumask(next));
574  
575  		/*
576  		 * If the CPU is not in lazy TLB mode, we are just switching
577  		 * from one thread in a process to another thread in the same
578  		 * process. No TLB flush required.
579  		 */
580  		if (!was_lazy)
581  			return;
582  
583  		/*
584  		 * Read the tlb_gen to check whether a flush is needed.
585  		 * If the TLB is up to date, just use it.
586  		 * The barrier synchronizes with the tlb_gen increment in
587  		 * the TLB shootdown code.
588  		 */
589  		smp_mb();
590  		next_tlb_gen = atomic64_read(&next->context.tlb_gen);
591  		if (this_cpu_read(cpu_tlbstate.ctxs[prev_asid].tlb_gen) ==
592  				next_tlb_gen)
593  			return;
594  
595  		/*
596  		 * TLB contents went out of date while we were in lazy
597  		 * mode. Fall through to the TLB switching code below.
598  		 */
599  		new_asid = prev_asid;
600  		need_flush = true;
601  	} else {
602  		/*
603  		 * Apply process to process speculation vulnerability
604  		 * mitigations if applicable.
605  		 */
606  		cond_mitigation(tsk);
607  
608  		/*
609  		 * Stop remote flushes for the previous mm.
610  		 * Skip kernel threads; we never send init_mm TLB flushing IPIs,
611  		 * but the bitmap manipulation can cause cache line contention.
612  		 */
613  		if (prev != &init_mm) {
614  			VM_WARN_ON_ONCE(!cpumask_test_cpu(cpu,
615  						mm_cpumask(prev)));
616  			cpumask_clear_cpu(cpu, mm_cpumask(prev));
617  		}
618  
619  		/* Start receiving IPIs and then read tlb_gen (and LAM below) */
620  		if (next != &init_mm)
621  			cpumask_set_cpu(cpu, mm_cpumask(next));
622  		next_tlb_gen = atomic64_read(&next->context.tlb_gen);
623  
624  		choose_new_asid(next, next_tlb_gen, &new_asid, &need_flush);
625  
626  		/* Let nmi_uaccess_okay() know that we're changing CR3. */
627  		this_cpu_write(cpu_tlbstate.loaded_mm, LOADED_MM_SWITCHING);
628  		barrier();
629  	}
630  
631  	new_lam = mm_lam_cr3_mask(next);
632  	if (need_flush) {
633  		this_cpu_write(cpu_tlbstate.ctxs[new_asid].ctx_id, next->context.ctx_id);
634  		this_cpu_write(cpu_tlbstate.ctxs[new_asid].tlb_gen, next_tlb_gen);
635  		load_new_mm_cr3(next->pgd, new_asid, new_lam, true);
636  
637  		trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, TLB_FLUSH_ALL);
638  	} else {
639  		/* The new ASID is already up to date. */
640  		load_new_mm_cr3(next->pgd, new_asid, new_lam, false);
641  
642  		trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, 0);
643  	}
644  
645  	/* Make sure we write CR3 before loaded_mm. */
646  	barrier();
647  
648  	this_cpu_write(cpu_tlbstate.loaded_mm, next);
649  	this_cpu_write(cpu_tlbstate.loaded_mm_asid, new_asid);
650  	cpu_tlbstate_update_lam(new_lam, mm_untag_mask(next));
651  
652  	if (next != prev) {
653  		cr4_update_pce_mm(next);
654  		switch_ldt(prev, next);
655  	}
656  }
657  
658  /*
659   * Please ignore the name of this function.  It should be called
660   * switch_to_kernel_thread().
661   *
662   * enter_lazy_tlb() is a hint from the scheduler that we are entering a
663   * kernel thread or other context without an mm.  Acceptable implementations
664   * include doing nothing whatsoever, switching to init_mm, or various clever
665   * lazy tricks to try to minimize TLB flushes.
666   *
667   * The scheduler reserves the right to call enter_lazy_tlb() several times
668   * in a row.  It will notify us that we're going back to a real mm by
669   * calling switch_mm_irqs_off().
670   */
enter_lazy_tlb(struct mm_struct * mm,struct task_struct * tsk)671  void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk)
672  {
673  	if (this_cpu_read(cpu_tlbstate.loaded_mm) == &init_mm)
674  		return;
675  
676  	this_cpu_write(cpu_tlbstate_shared.is_lazy, true);
677  }
678  
679  /*
680   * Call this when reinitializing a CPU.  It fixes the following potential
681   * problems:
682   *
683   * - The ASID changed from what cpu_tlbstate thinks it is (most likely
684   *   because the CPU was taken down and came back up with CR3's PCID
685   *   bits clear.  CPU hotplug can do this.
686   *
687   * - The TLB contains junk in slots corresponding to inactive ASIDs.
688   *
689   * - The CPU went so far out to lunch that it may have missed a TLB
690   *   flush.
691   */
initialize_tlbstate_and_flush(void)692  void initialize_tlbstate_and_flush(void)
693  {
694  	int i;
695  	struct mm_struct *mm = this_cpu_read(cpu_tlbstate.loaded_mm);
696  	u64 tlb_gen = atomic64_read(&init_mm.context.tlb_gen);
697  	unsigned long lam = mm_lam_cr3_mask(mm);
698  	unsigned long cr3 = __read_cr3();
699  
700  	/* Assert that CR3 already references the right mm. */
701  	WARN_ON((cr3 & CR3_ADDR_MASK) != __pa(mm->pgd));
702  
703  	/* LAM expected to be disabled */
704  	WARN_ON(cr3 & (X86_CR3_LAM_U48 | X86_CR3_LAM_U57));
705  	WARN_ON(lam);
706  
707  	/*
708  	 * Assert that CR4.PCIDE is set if needed.  (CR4.PCIDE initialization
709  	 * doesn't work like other CR4 bits because it can only be set from
710  	 * long mode.)
711  	 */
712  	WARN_ON(boot_cpu_has(X86_FEATURE_PCID) &&
713  		!(cr4_read_shadow() & X86_CR4_PCIDE));
714  
715  	/* Disable LAM, force ASID 0 and force a TLB flush. */
716  	write_cr3(build_cr3(mm->pgd, 0, 0));
717  
718  	/* Reinitialize tlbstate. */
719  	this_cpu_write(cpu_tlbstate.last_user_mm_spec, LAST_USER_MM_INIT);
720  	this_cpu_write(cpu_tlbstate.loaded_mm_asid, 0);
721  	this_cpu_write(cpu_tlbstate.next_asid, 1);
722  	this_cpu_write(cpu_tlbstate.ctxs[0].ctx_id, mm->context.ctx_id);
723  	this_cpu_write(cpu_tlbstate.ctxs[0].tlb_gen, tlb_gen);
724  	cpu_tlbstate_update_lam(lam, mm_untag_mask(mm));
725  
726  	for (i = 1; i < TLB_NR_DYN_ASIDS; i++)
727  		this_cpu_write(cpu_tlbstate.ctxs[i].ctx_id, 0);
728  }
729  
730  /*
731   * flush_tlb_func()'s memory ordering requirement is that any
732   * TLB fills that happen after we flush the TLB are ordered after we
733   * read active_mm's tlb_gen.  We don't need any explicit barriers
734   * because all x86 flush operations are serializing and the
735   * atomic64_read operation won't be reordered by the compiler.
736   */
flush_tlb_func(void * info)737  static void flush_tlb_func(void *info)
738  {
739  	/*
740  	 * We have three different tlb_gen values in here.  They are:
741  	 *
742  	 * - mm_tlb_gen:     the latest generation.
743  	 * - local_tlb_gen:  the generation that this CPU has already caught
744  	 *                   up to.
745  	 * - f->new_tlb_gen: the generation that the requester of the flush
746  	 *                   wants us to catch up to.
747  	 */
748  	const struct flush_tlb_info *f = info;
749  	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
750  	u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
751  	u64 local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen);
752  	bool local = smp_processor_id() == f->initiating_cpu;
753  	unsigned long nr_invalidate = 0;
754  	u64 mm_tlb_gen;
755  
756  	/* This code cannot presently handle being reentered. */
757  	VM_WARN_ON(!irqs_disabled());
758  
759  	if (!local) {
760  		inc_irq_stat(irq_tlb_count);
761  		count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
762  
763  		/* Can only happen on remote CPUs */
764  		if (f->mm && f->mm != loaded_mm)
765  			return;
766  	}
767  
768  	if (unlikely(loaded_mm == &init_mm))
769  		return;
770  
771  	VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) !=
772  		   loaded_mm->context.ctx_id);
773  
774  	if (this_cpu_read(cpu_tlbstate_shared.is_lazy)) {
775  		/*
776  		 * We're in lazy mode.  We need to at least flush our
777  		 * paging-structure cache to avoid speculatively reading
778  		 * garbage into our TLB.  Since switching to init_mm is barely
779  		 * slower than a minimal flush, just switch to init_mm.
780  		 *
781  		 * This should be rare, with native_flush_tlb_multi() skipping
782  		 * IPIs to lazy TLB mode CPUs.
783  		 */
784  		switch_mm_irqs_off(NULL, &init_mm, NULL);
785  		return;
786  	}
787  
788  	if (unlikely(f->new_tlb_gen != TLB_GENERATION_INVALID &&
789  		     f->new_tlb_gen <= local_tlb_gen)) {
790  		/*
791  		 * The TLB is already up to date in respect to f->new_tlb_gen.
792  		 * While the core might be still behind mm_tlb_gen, checking
793  		 * mm_tlb_gen unnecessarily would have negative caching effects
794  		 * so avoid it.
795  		 */
796  		return;
797  	}
798  
799  	/*
800  	 * Defer mm_tlb_gen reading as long as possible to avoid cache
801  	 * contention.
802  	 */
803  	mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen);
804  
805  	if (unlikely(local_tlb_gen == mm_tlb_gen)) {
806  		/*
807  		 * There's nothing to do: we're already up to date.  This can
808  		 * happen if two concurrent flushes happen -- the first flush to
809  		 * be handled can catch us all the way up, leaving no work for
810  		 * the second flush.
811  		 */
812  		goto done;
813  	}
814  
815  	WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen);
816  	WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen);
817  
818  	/*
819  	 * If we get to this point, we know that our TLB is out of date.
820  	 * This does not strictly imply that we need to flush (it's
821  	 * possible that f->new_tlb_gen <= local_tlb_gen), but we're
822  	 * going to need to flush in the very near future, so we might
823  	 * as well get it over with.
824  	 *
825  	 * The only question is whether to do a full or partial flush.
826  	 *
827  	 * We do a partial flush if requested and two extra conditions
828  	 * are met:
829  	 *
830  	 * 1. f->new_tlb_gen == local_tlb_gen + 1.  We have an invariant that
831  	 *    we've always done all needed flushes to catch up to
832  	 *    local_tlb_gen.  If, for example, local_tlb_gen == 2 and
833  	 *    f->new_tlb_gen == 3, then we know that the flush needed to bring
834  	 *    us up to date for tlb_gen 3 is the partial flush we're
835  	 *    processing.
836  	 *
837  	 *    As an example of why this check is needed, suppose that there
838  	 *    are two concurrent flushes.  The first is a full flush that
839  	 *    changes context.tlb_gen from 1 to 2.  The second is a partial
840  	 *    flush that changes context.tlb_gen from 2 to 3.  If they get
841  	 *    processed on this CPU in reverse order, we'll see
842  	 *     local_tlb_gen == 1, mm_tlb_gen == 3, and end != TLB_FLUSH_ALL.
843  	 *    If we were to use __flush_tlb_one_user() and set local_tlb_gen to
844  	 *    3, we'd be break the invariant: we'd update local_tlb_gen above
845  	 *    1 without the full flush that's needed for tlb_gen 2.
846  	 *
847  	 * 2. f->new_tlb_gen == mm_tlb_gen.  This is purely an optimization.
848  	 *    Partial TLB flushes are not all that much cheaper than full TLB
849  	 *    flushes, so it seems unlikely that it would be a performance win
850  	 *    to do a partial flush if that won't bring our TLB fully up to
851  	 *    date.  By doing a full flush instead, we can increase
852  	 *    local_tlb_gen all the way to mm_tlb_gen and we can probably
853  	 *    avoid another flush in the very near future.
854  	 */
855  	if (f->end != TLB_FLUSH_ALL &&
856  	    f->new_tlb_gen == local_tlb_gen + 1 &&
857  	    f->new_tlb_gen == mm_tlb_gen) {
858  		/* Partial flush */
859  		unsigned long addr = f->start;
860  
861  		/* Partial flush cannot have invalid generations */
862  		VM_WARN_ON(f->new_tlb_gen == TLB_GENERATION_INVALID);
863  
864  		/* Partial flush must have valid mm */
865  		VM_WARN_ON(f->mm == NULL);
866  
867  		nr_invalidate = (f->end - f->start) >> f->stride_shift;
868  
869  		while (addr < f->end) {
870  			flush_tlb_one_user(addr);
871  			addr += 1UL << f->stride_shift;
872  		}
873  		if (local)
874  			count_vm_tlb_events(NR_TLB_LOCAL_FLUSH_ONE, nr_invalidate);
875  	} else {
876  		/* Full flush. */
877  		nr_invalidate = TLB_FLUSH_ALL;
878  
879  		flush_tlb_local();
880  		if (local)
881  			count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);
882  	}
883  
884  	/* Both paths above update our state to mm_tlb_gen. */
885  	this_cpu_write(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen, mm_tlb_gen);
886  
887  	/* Tracing is done in a unified manner to reduce the code size */
888  done:
889  	trace_tlb_flush(!local ? TLB_REMOTE_SHOOTDOWN :
890  				(f->mm == NULL) ? TLB_LOCAL_SHOOTDOWN :
891  						  TLB_LOCAL_MM_SHOOTDOWN,
892  			nr_invalidate);
893  }
894  
tlb_is_not_lazy(int cpu,void * data)895  static bool tlb_is_not_lazy(int cpu, void *data)
896  {
897  	return !per_cpu(cpu_tlbstate_shared.is_lazy, cpu);
898  }
899  
900  DEFINE_PER_CPU_SHARED_ALIGNED(struct tlb_state_shared, cpu_tlbstate_shared);
901  EXPORT_PER_CPU_SYMBOL(cpu_tlbstate_shared);
902  
native_flush_tlb_multi(const struct cpumask * cpumask,const struct flush_tlb_info * info)903  STATIC_NOPV void native_flush_tlb_multi(const struct cpumask *cpumask,
904  					 const struct flush_tlb_info *info)
905  {
906  	/*
907  	 * Do accounting and tracing. Note that there are (and have always been)
908  	 * cases in which a remote TLB flush will be traced, but eventually
909  	 * would not happen.
910  	 */
911  	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
912  	if (info->end == TLB_FLUSH_ALL)
913  		trace_tlb_flush(TLB_REMOTE_SEND_IPI, TLB_FLUSH_ALL);
914  	else
915  		trace_tlb_flush(TLB_REMOTE_SEND_IPI,
916  				(info->end - info->start) >> PAGE_SHIFT);
917  
918  	/*
919  	 * If no page tables were freed, we can skip sending IPIs to
920  	 * CPUs in lazy TLB mode. They will flush the CPU themselves
921  	 * at the next context switch.
922  	 *
923  	 * However, if page tables are getting freed, we need to send the
924  	 * IPI everywhere, to prevent CPUs in lazy TLB mode from tripping
925  	 * up on the new contents of what used to be page tables, while
926  	 * doing a speculative memory access.
927  	 */
928  	if (info->freed_tables)
929  		on_each_cpu_mask(cpumask, flush_tlb_func, (void *)info, true);
930  	else
931  		on_each_cpu_cond_mask(tlb_is_not_lazy, flush_tlb_func,
932  				(void *)info, 1, cpumask);
933  }
934  
flush_tlb_multi(const struct cpumask * cpumask,const struct flush_tlb_info * info)935  void flush_tlb_multi(const struct cpumask *cpumask,
936  		      const struct flush_tlb_info *info)
937  {
938  	__flush_tlb_multi(cpumask, info);
939  }
940  
941  /*
942   * See Documentation/arch/x86/tlb.rst for details.  We choose 33
943   * because it is large enough to cover the vast majority (at
944   * least 95%) of allocations, and is small enough that we are
945   * confident it will not cause too much overhead.  Each single
946   * flush is about 100 ns, so this caps the maximum overhead at
947   * _about_ 3,000 ns.
948   *
949   * This is in units of pages.
950   */
951  unsigned long tlb_single_page_flush_ceiling __read_mostly = 33;
952  
953  static DEFINE_PER_CPU_SHARED_ALIGNED(struct flush_tlb_info, flush_tlb_info);
954  
955  #ifdef CONFIG_DEBUG_VM
956  static DEFINE_PER_CPU(unsigned int, flush_tlb_info_idx);
957  #endif
958  
get_flush_tlb_info(struct mm_struct * mm,unsigned long start,unsigned long end,unsigned int stride_shift,bool freed_tables,u64 new_tlb_gen)959  static struct flush_tlb_info *get_flush_tlb_info(struct mm_struct *mm,
960  			unsigned long start, unsigned long end,
961  			unsigned int stride_shift, bool freed_tables,
962  			u64 new_tlb_gen)
963  {
964  	struct flush_tlb_info *info = this_cpu_ptr(&flush_tlb_info);
965  
966  #ifdef CONFIG_DEBUG_VM
967  	/*
968  	 * Ensure that the following code is non-reentrant and flush_tlb_info
969  	 * is not overwritten. This means no TLB flushing is initiated by
970  	 * interrupt handlers and machine-check exception handlers.
971  	 */
972  	BUG_ON(this_cpu_inc_return(flush_tlb_info_idx) != 1);
973  #endif
974  
975  	info->start		= start;
976  	info->end		= end;
977  	info->mm		= mm;
978  	info->stride_shift	= stride_shift;
979  	info->freed_tables	= freed_tables;
980  	info->new_tlb_gen	= new_tlb_gen;
981  	info->initiating_cpu	= smp_processor_id();
982  
983  	return info;
984  }
985  
put_flush_tlb_info(void)986  static void put_flush_tlb_info(void)
987  {
988  #ifdef CONFIG_DEBUG_VM
989  	/* Complete reentrancy prevention checks */
990  	barrier();
991  	this_cpu_dec(flush_tlb_info_idx);
992  #endif
993  }
994  
flush_tlb_mm_range(struct mm_struct * mm,unsigned long start,unsigned long end,unsigned int stride_shift,bool freed_tables)995  void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,
996  				unsigned long end, unsigned int stride_shift,
997  				bool freed_tables)
998  {
999  	struct flush_tlb_info *info;
1000  	u64 new_tlb_gen;
1001  	int cpu;
1002  
1003  	cpu = get_cpu();
1004  
1005  	/* Should we flush just the requested range? */
1006  	if ((end == TLB_FLUSH_ALL) ||
1007  	    ((end - start) >> stride_shift) > tlb_single_page_flush_ceiling) {
1008  		start = 0;
1009  		end = TLB_FLUSH_ALL;
1010  	}
1011  
1012  	/* This is also a barrier that synchronizes with switch_mm(). */
1013  	new_tlb_gen = inc_mm_tlb_gen(mm);
1014  
1015  	info = get_flush_tlb_info(mm, start, end, stride_shift, freed_tables,
1016  				  new_tlb_gen);
1017  
1018  	/*
1019  	 * flush_tlb_multi() is not optimized for the common case in which only
1020  	 * a local TLB flush is needed. Optimize this use-case by calling
1021  	 * flush_tlb_func_local() directly in this case.
1022  	 */
1023  	if (cpumask_any_but(mm_cpumask(mm), cpu) < nr_cpu_ids) {
1024  		flush_tlb_multi(mm_cpumask(mm), info);
1025  	} else if (mm == this_cpu_read(cpu_tlbstate.loaded_mm)) {
1026  		lockdep_assert_irqs_enabled();
1027  		local_irq_disable();
1028  		flush_tlb_func(info);
1029  		local_irq_enable();
1030  	}
1031  
1032  	put_flush_tlb_info();
1033  	put_cpu();
1034  	mmu_notifier_arch_invalidate_secondary_tlbs(mm, start, end);
1035  }
1036  
1037  
do_flush_tlb_all(void * info)1038  static void do_flush_tlb_all(void *info)
1039  {
1040  	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
1041  	__flush_tlb_all();
1042  }
1043  
flush_tlb_all(void)1044  void flush_tlb_all(void)
1045  {
1046  	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
1047  	on_each_cpu(do_flush_tlb_all, NULL, 1);
1048  }
1049  
do_kernel_range_flush(void * info)1050  static void do_kernel_range_flush(void *info)
1051  {
1052  	struct flush_tlb_info *f = info;
1053  	unsigned long addr;
1054  
1055  	/* flush range by one by one 'invlpg' */
1056  	for (addr = f->start; addr < f->end; addr += PAGE_SIZE)
1057  		flush_tlb_one_kernel(addr);
1058  }
1059  
flush_tlb_kernel_range(unsigned long start,unsigned long end)1060  void flush_tlb_kernel_range(unsigned long start, unsigned long end)
1061  {
1062  	/* Balance as user space task's flush, a bit conservative */
1063  	if (end == TLB_FLUSH_ALL ||
1064  	    (end - start) > tlb_single_page_flush_ceiling << PAGE_SHIFT) {
1065  		on_each_cpu(do_flush_tlb_all, NULL, 1);
1066  	} else {
1067  		struct flush_tlb_info *info;
1068  
1069  		preempt_disable();
1070  		info = get_flush_tlb_info(NULL, start, end, 0, false,
1071  					  TLB_GENERATION_INVALID);
1072  
1073  		on_each_cpu(do_kernel_range_flush, info, 1);
1074  
1075  		put_flush_tlb_info();
1076  		preempt_enable();
1077  	}
1078  }
1079  
1080  /*
1081   * This can be used from process context to figure out what the value of
1082   * CR3 is without needing to do a (slow) __read_cr3().
1083   *
1084   * It's intended to be used for code like KVM that sneakily changes CR3
1085   * and needs to restore it.  It needs to be used very carefully.
1086   */
__get_current_cr3_fast(void)1087  unsigned long __get_current_cr3_fast(void)
1088  {
1089  	unsigned long cr3 =
1090  		build_cr3(this_cpu_read(cpu_tlbstate.loaded_mm)->pgd,
1091  			  this_cpu_read(cpu_tlbstate.loaded_mm_asid),
1092  			  tlbstate_lam_cr3_mask());
1093  
1094  	/* For now, be very restrictive about when this can be called. */
1095  	VM_WARN_ON(in_nmi() || preemptible());
1096  
1097  	VM_BUG_ON(cr3 != __read_cr3());
1098  	return cr3;
1099  }
1100  EXPORT_SYMBOL_GPL(__get_current_cr3_fast);
1101  
1102  /*
1103   * Flush one page in the kernel mapping
1104   */
flush_tlb_one_kernel(unsigned long addr)1105  void flush_tlb_one_kernel(unsigned long addr)
1106  {
1107  	count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);
1108  
1109  	/*
1110  	 * If PTI is off, then __flush_tlb_one_user() is just INVLPG or its
1111  	 * paravirt equivalent.  Even with PCID, this is sufficient: we only
1112  	 * use PCID if we also use global PTEs for the kernel mapping, and
1113  	 * INVLPG flushes global translations across all address spaces.
1114  	 *
1115  	 * If PTI is on, then the kernel is mapped with non-global PTEs, and
1116  	 * __flush_tlb_one_user() will flush the given address for the current
1117  	 * kernel address space and for its usermode counterpart, but it does
1118  	 * not flush it for other address spaces.
1119  	 */
1120  	flush_tlb_one_user(addr);
1121  
1122  	if (!static_cpu_has(X86_FEATURE_PTI))
1123  		return;
1124  
1125  	/*
1126  	 * See above.  We need to propagate the flush to all other address
1127  	 * spaces.  In principle, we only need to propagate it to kernelmode
1128  	 * address spaces, but the extra bookkeeping we would need is not
1129  	 * worth it.
1130  	 */
1131  	this_cpu_write(cpu_tlbstate.invalidate_other, true);
1132  }
1133  
1134  /*
1135   * Flush one page in the user mapping
1136   */
native_flush_tlb_one_user(unsigned long addr)1137  STATIC_NOPV void native_flush_tlb_one_user(unsigned long addr)
1138  {
1139  	u32 loaded_mm_asid;
1140  	bool cpu_pcide;
1141  
1142  	/* Flush 'addr' from the kernel PCID: */
1143  	asm volatile("invlpg (%0)" ::"r" (addr) : "memory");
1144  
1145  	/* If PTI is off there is no user PCID and nothing to flush. */
1146  	if (!static_cpu_has(X86_FEATURE_PTI))
1147  		return;
1148  
1149  	loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
1150  	cpu_pcide      = this_cpu_read(cpu_tlbstate.cr4) & X86_CR4_PCIDE;
1151  
1152  	/*
1153  	 * invpcid_flush_one(pcid>0) will #GP if CR4.PCIDE==0.  Check
1154  	 * 'cpu_pcide' to ensure that *this* CPU will not trigger those
1155  	 * #GP's even if called before CR4.PCIDE has been initialized.
1156  	 */
1157  	if (boot_cpu_has(X86_FEATURE_INVPCID) && cpu_pcide)
1158  		invpcid_flush_one(user_pcid(loaded_mm_asid), addr);
1159  	else
1160  		invalidate_user_asid(loaded_mm_asid);
1161  }
1162  
flush_tlb_one_user(unsigned long addr)1163  void flush_tlb_one_user(unsigned long addr)
1164  {
1165  	__flush_tlb_one_user(addr);
1166  }
1167  
1168  /*
1169   * Flush everything
1170   */
native_flush_tlb_global(void)1171  STATIC_NOPV void native_flush_tlb_global(void)
1172  {
1173  	unsigned long flags;
1174  
1175  	if (static_cpu_has(X86_FEATURE_INVPCID)) {
1176  		/*
1177  		 * Using INVPCID is considerably faster than a pair of writes
1178  		 * to CR4 sandwiched inside an IRQ flag save/restore.
1179  		 *
1180  		 * Note, this works with CR4.PCIDE=0 or 1.
1181  		 */
1182  		invpcid_flush_all();
1183  		return;
1184  	}
1185  
1186  	/*
1187  	 * Read-modify-write to CR4 - protect it from preemption and
1188  	 * from interrupts. (Use the raw variant because this code can
1189  	 * be called from deep inside debugging code.)
1190  	 */
1191  	raw_local_irq_save(flags);
1192  
1193  	__native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4));
1194  
1195  	raw_local_irq_restore(flags);
1196  }
1197  
1198  /*
1199   * Flush the entire current user mapping
1200   */
native_flush_tlb_local(void)1201  STATIC_NOPV void native_flush_tlb_local(void)
1202  {
1203  	/*
1204  	 * Preemption or interrupts must be disabled to protect the access
1205  	 * to the per CPU variable and to prevent being preempted between
1206  	 * read_cr3() and write_cr3().
1207  	 */
1208  	WARN_ON_ONCE(preemptible());
1209  
1210  	invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid));
1211  
1212  	/* If current->mm == NULL then the read_cr3() "borrows" an mm */
1213  	native_write_cr3(__native_read_cr3());
1214  }
1215  
flush_tlb_local(void)1216  void flush_tlb_local(void)
1217  {
1218  	__flush_tlb_local();
1219  }
1220  
1221  /*
1222   * Flush everything
1223   */
__flush_tlb_all(void)1224  void __flush_tlb_all(void)
1225  {
1226  	/*
1227  	 * This is to catch users with enabled preemption and the PGE feature
1228  	 * and don't trigger the warning in __native_flush_tlb().
1229  	 */
1230  	VM_WARN_ON_ONCE(preemptible());
1231  
1232  	if (cpu_feature_enabled(X86_FEATURE_PGE)) {
1233  		__flush_tlb_global();
1234  	} else {
1235  		/*
1236  		 * !PGE -> !PCID (setup_pcid()), thus every flush is total.
1237  		 */
1238  		flush_tlb_local();
1239  	}
1240  }
1241  EXPORT_SYMBOL_GPL(__flush_tlb_all);
1242  
arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch * batch)1243  void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)
1244  {
1245  	struct flush_tlb_info *info;
1246  
1247  	int cpu = get_cpu();
1248  
1249  	info = get_flush_tlb_info(NULL, 0, TLB_FLUSH_ALL, 0, false,
1250  				  TLB_GENERATION_INVALID);
1251  	/*
1252  	 * flush_tlb_multi() is not optimized for the common case in which only
1253  	 * a local TLB flush is needed. Optimize this use-case by calling
1254  	 * flush_tlb_func_local() directly in this case.
1255  	 */
1256  	if (cpumask_any_but(&batch->cpumask, cpu) < nr_cpu_ids) {
1257  		flush_tlb_multi(&batch->cpumask, info);
1258  	} else if (cpumask_test_cpu(cpu, &batch->cpumask)) {
1259  		lockdep_assert_irqs_enabled();
1260  		local_irq_disable();
1261  		flush_tlb_func(info);
1262  		local_irq_enable();
1263  	}
1264  
1265  	cpumask_clear(&batch->cpumask);
1266  
1267  	put_flush_tlb_info();
1268  	put_cpu();
1269  }
1270  
1271  /*
1272   * Blindly accessing user memory from NMI context can be dangerous
1273   * if we're in the middle of switching the current user task or
1274   * switching the loaded mm.  It can also be dangerous if we
1275   * interrupted some kernel code that was temporarily using a
1276   * different mm.
1277   */
nmi_uaccess_okay(void)1278  bool nmi_uaccess_okay(void)
1279  {
1280  	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1281  	struct mm_struct *current_mm = current->mm;
1282  
1283  	VM_WARN_ON_ONCE(!loaded_mm);
1284  
1285  	/*
1286  	 * The condition we want to check is
1287  	 * current_mm->pgd == __va(read_cr3_pa()).  This may be slow, though,
1288  	 * if we're running in a VM with shadow paging, and nmi_uaccess_okay()
1289  	 * is supposed to be reasonably fast.
1290  	 *
1291  	 * Instead, we check the almost equivalent but somewhat conservative
1292  	 * condition below, and we rely on the fact that switch_mm_irqs_off()
1293  	 * sets loaded_mm to LOADED_MM_SWITCHING before writing to CR3.
1294  	 */
1295  	if (loaded_mm != current_mm)
1296  		return false;
1297  
1298  	VM_WARN_ON_ONCE(current_mm->pgd != __va(read_cr3_pa()));
1299  
1300  	return true;
1301  }
1302  
tlbflush_read_file(struct file * file,char __user * user_buf,size_t count,loff_t * ppos)1303  static ssize_t tlbflush_read_file(struct file *file, char __user *user_buf,
1304  			     size_t count, loff_t *ppos)
1305  {
1306  	char buf[32];
1307  	unsigned int len;
1308  
1309  	len = sprintf(buf, "%ld\n", tlb_single_page_flush_ceiling);
1310  	return simple_read_from_buffer(user_buf, count, ppos, buf, len);
1311  }
1312  
tlbflush_write_file(struct file * file,const char __user * user_buf,size_t count,loff_t * ppos)1313  static ssize_t tlbflush_write_file(struct file *file,
1314  		 const char __user *user_buf, size_t count, loff_t *ppos)
1315  {
1316  	char buf[32];
1317  	ssize_t len;
1318  	int ceiling;
1319  
1320  	len = min(count, sizeof(buf) - 1);
1321  	if (copy_from_user(buf, user_buf, len))
1322  		return -EFAULT;
1323  
1324  	buf[len] = '\0';
1325  	if (kstrtoint(buf, 0, &ceiling))
1326  		return -EINVAL;
1327  
1328  	if (ceiling < 0)
1329  		return -EINVAL;
1330  
1331  	tlb_single_page_flush_ceiling = ceiling;
1332  	return count;
1333  }
1334  
1335  static const struct file_operations fops_tlbflush = {
1336  	.read = tlbflush_read_file,
1337  	.write = tlbflush_write_file,
1338  	.llseek = default_llseek,
1339  };
1340  
create_tlb_single_page_flush_ceiling(void)1341  static int __init create_tlb_single_page_flush_ceiling(void)
1342  {
1343  	debugfs_create_file("tlb_single_page_flush_ceiling", S_IRUSR | S_IWUSR,
1344  			    arch_debugfs_dir, NULL, &fops_tlbflush);
1345  	return 0;
1346  }
1347  late_initcall(create_tlb_single_page_flush_ceiling);
1348