1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _ASM_X86_TLBFLUSH_H
3 #define _ASM_X86_TLBFLUSH_H
4 
5 #include <linux/mm.h>
6 #include <linux/sched.h>
7 
8 #include <asm/processor.h>
9 #include <asm/cpufeature.h>
10 #include <asm/special_insns.h>
11 #include <asm/smp.h>
12 #include <asm/invpcid.h>
13 #include <asm/pti.h>
14 #include <asm/processor-flags.h>
15 
16 /*
17  * The x86 feature is called PCID (Process Context IDentifier). It is similar
18  * to what is traditionally called ASID on the RISC processors.
19  *
20  * We don't use the traditional ASID implementation, where each process/mm gets
21  * its own ASID and flush/restart when we run out of ASID space.
22  *
23  * Instead we have a small per-cpu array of ASIDs and cache the last few mm's
24  * that came by on this CPU, allowing cheaper switch_mm between processes on
25  * this CPU.
26  *
27  * We end up with different spaces for different things. To avoid confusion we
28  * use different names for each of them:
29  *
30  * ASID  - [0, TLB_NR_DYN_ASIDS-1]
31  *         the canonical identifier for an mm
32  *
33  * kPCID - [1, TLB_NR_DYN_ASIDS]
34  *         the value we write into the PCID part of CR3; corresponds to the
35  *         ASID+1, because PCID 0 is special.
36  *
37  * uPCID - [2048 + 1, 2048 + TLB_NR_DYN_ASIDS]
38  *         for KPTI each mm has two address spaces and thus needs two
39  *         PCID values, but we can still do with a single ASID denomination
40  *         for each mm. Corresponds to kPCID + 2048.
41  *
42  */
43 
44 /* There are 12 bits of space for ASIDS in CR3 */
45 #define CR3_HW_ASID_BITS		12
46 
47 /*
48  * When enabled, PAGE_TABLE_ISOLATION consumes a single bit for
49  * user/kernel switches
50  */
51 #ifdef CONFIG_PAGE_TABLE_ISOLATION
52 # define PTI_CONSUMED_PCID_BITS	1
53 #else
54 # define PTI_CONSUMED_PCID_BITS	0
55 #endif
56 
57 #define CR3_AVAIL_PCID_BITS (X86_CR3_PCID_BITS - PTI_CONSUMED_PCID_BITS)
58 
59 /*
60  * ASIDs are zero-based: 0->MAX_AVAIL_ASID are valid.  -1 below to account
61  * for them being zero-based.  Another -1 is because PCID 0 is reserved for
62  * use by non-PCID-aware users.
63  */
64 #define MAX_ASID_AVAILABLE ((1 << CR3_AVAIL_PCID_BITS) - 2)
65 
66 /*
67  * 6 because 6 should be plenty and struct tlb_state will fit in two cache
68  * lines.
69  */
70 #define TLB_NR_DYN_ASIDS	6
71 
72 /*
73  * Given @asid, compute kPCID
74  */
kern_pcid(u16 asid)75 static inline u16 kern_pcid(u16 asid)
76 {
77 	VM_WARN_ON_ONCE(asid > MAX_ASID_AVAILABLE);
78 
79 #ifdef CONFIG_PAGE_TABLE_ISOLATION
80 	/*
81 	 * Make sure that the dynamic ASID space does not confict with the
82 	 * bit we are using to switch between user and kernel ASIDs.
83 	 */
84 	BUILD_BUG_ON(TLB_NR_DYN_ASIDS >= (1 << X86_CR3_PTI_PCID_USER_BIT));
85 
86 	/*
87 	 * The ASID being passed in here should have respected the
88 	 * MAX_ASID_AVAILABLE and thus never have the switch bit set.
89 	 */
90 	VM_WARN_ON_ONCE(asid & (1 << X86_CR3_PTI_PCID_USER_BIT));
91 #endif
92 	/*
93 	 * The dynamically-assigned ASIDs that get passed in are small
94 	 * (<TLB_NR_DYN_ASIDS).  They never have the high switch bit set,
95 	 * so do not bother to clear it.
96 	 *
97 	 * If PCID is on, ASID-aware code paths put the ASID+1 into the
98 	 * PCID bits.  This serves two purposes.  It prevents a nasty
99 	 * situation in which PCID-unaware code saves CR3, loads some other
100 	 * value (with PCID == 0), and then restores CR3, thus corrupting
101 	 * the TLB for ASID 0 if the saved ASID was nonzero.  It also means
102 	 * that any bugs involving loading a PCID-enabled CR3 with
103 	 * CR4.PCIDE off will trigger deterministically.
104 	 */
105 	return asid + 1;
106 }
107 
108 /*
109  * Given @asid, compute uPCID
110  */
user_pcid(u16 asid)111 static inline u16 user_pcid(u16 asid)
112 {
113 	u16 ret = kern_pcid(asid);
114 #ifdef CONFIG_PAGE_TABLE_ISOLATION
115 	ret |= 1 << X86_CR3_PTI_PCID_USER_BIT;
116 #endif
117 	return ret;
118 }
119 
120 struct pgd_t;
build_cr3(pgd_t * pgd,u16 asid)121 static inline unsigned long build_cr3(pgd_t *pgd, u16 asid)
122 {
123 	if (static_cpu_has(X86_FEATURE_PCID)) {
124 		return __sme_pa(pgd) | kern_pcid(asid);
125 	} else {
126 		VM_WARN_ON_ONCE(asid != 0);
127 		return __sme_pa(pgd);
128 	}
129 }
130 
build_cr3_noflush(pgd_t * pgd,u16 asid)131 static inline unsigned long build_cr3_noflush(pgd_t *pgd, u16 asid)
132 {
133 	VM_WARN_ON_ONCE(asid > MAX_ASID_AVAILABLE);
134 	/*
135 	 * Use boot_cpu_has() instead of this_cpu_has() as this function
136 	 * might be called during early boot. This should work even after
137 	 * boot because all CPU's the have same capabilities:
138 	 */
139 	VM_WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_PCID));
140 	return __sme_pa(pgd) | kern_pcid(asid) | CR3_NOFLUSH;
141 }
142 
143 #ifdef CONFIG_PARAVIRT
144 #include <asm/paravirt.h>
145 #else
146 #define __flush_tlb() __native_flush_tlb()
147 #define __flush_tlb_global() __native_flush_tlb_global()
148 #define __flush_tlb_one_user(addr) __native_flush_tlb_one_user(addr)
149 #endif
150 
tlb_defer_switch_to_init_mm(void)151 static inline bool tlb_defer_switch_to_init_mm(void)
152 {
153 	/*
154 	 * If we have PCID, then switching to init_mm is reasonably
155 	 * fast.  If we don't have PCID, then switching to init_mm is
156 	 * quite slow, so we try to defer it in the hopes that we can
157 	 * avoid it entirely.  The latter approach runs the risk of
158 	 * receiving otherwise unnecessary IPIs.
159 	 *
160 	 * This choice is just a heuristic.  The tlb code can handle this
161 	 * function returning true or false regardless of whether we have
162 	 * PCID.
163 	 */
164 	return !static_cpu_has(X86_FEATURE_PCID);
165 }
166 
167 struct tlb_context {
168 	u64 ctx_id;
169 	u64 tlb_gen;
170 };
171 
172 struct tlb_state {
173 	/*
174 	 * cpu_tlbstate.loaded_mm should match CR3 whenever interrupts
175 	 * are on.  This means that it may not match current->active_mm,
176 	 * which will contain the previous user mm when we're in lazy TLB
177 	 * mode even if we've already switched back to swapper_pg_dir.
178 	 *
179 	 * During switch_mm_irqs_off(), loaded_mm will be set to
180 	 * LOADED_MM_SWITCHING during the brief interrupts-off window
181 	 * when CR3 and loaded_mm would otherwise be inconsistent.  This
182 	 * is for nmi_uaccess_okay()'s benefit.
183 	 */
184 	struct mm_struct *loaded_mm;
185 
186 #define LOADED_MM_SWITCHING ((struct mm_struct *)1)
187 
188 	u16 loaded_mm_asid;
189 	u16 next_asid;
190 	/* last user mm's ctx id */
191 	u64 last_ctx_id;
192 
193 	/*
194 	 * We can be in one of several states:
195 	 *
196 	 *  - Actively using an mm.  Our CPU's bit will be set in
197 	 *    mm_cpumask(loaded_mm) and is_lazy == false;
198 	 *
199 	 *  - Not using a real mm.  loaded_mm == &init_mm.  Our CPU's bit
200 	 *    will not be set in mm_cpumask(&init_mm) and is_lazy == false.
201 	 *
202 	 *  - Lazily using a real mm.  loaded_mm != &init_mm, our bit
203 	 *    is set in mm_cpumask(loaded_mm), but is_lazy == true.
204 	 *    We're heuristically guessing that the CR3 load we
205 	 *    skipped more than makes up for the overhead added by
206 	 *    lazy mode.
207 	 */
208 	bool is_lazy;
209 
210 	/*
211 	 * If set we changed the page tables in such a way that we
212 	 * needed an invalidation of all contexts (aka. PCIDs / ASIDs).
213 	 * This tells us to go invalidate all the non-loaded ctxs[]
214 	 * on the next context switch.
215 	 *
216 	 * The current ctx was kept up-to-date as it ran and does not
217 	 * need to be invalidated.
218 	 */
219 	bool invalidate_other;
220 
221 	/*
222 	 * Mask that contains TLB_NR_DYN_ASIDS+1 bits to indicate
223 	 * the corresponding user PCID needs a flush next time we
224 	 * switch to it; see SWITCH_TO_USER_CR3.
225 	 */
226 	unsigned short user_pcid_flush_mask;
227 
228 	/*
229 	 * Access to this CR4 shadow and to H/W CR4 is protected by
230 	 * disabling interrupts when modifying either one.
231 	 */
232 	unsigned long cr4;
233 
234 	/*
235 	 * This is a list of all contexts that might exist in the TLB.
236 	 * There is one per ASID that we use, and the ASID (what the
237 	 * CPU calls PCID) is the index into ctxts.
238 	 *
239 	 * For each context, ctx_id indicates which mm the TLB's user
240 	 * entries came from.  As an invariant, the TLB will never
241 	 * contain entries that are out-of-date as when that mm reached
242 	 * the tlb_gen in the list.
243 	 *
244 	 * To be clear, this means that it's legal for the TLB code to
245 	 * flush the TLB without updating tlb_gen.  This can happen
246 	 * (for now, at least) due to paravirt remote flushes.
247 	 *
248 	 * NB: context 0 is a bit special, since it's also used by
249 	 * various bits of init code.  This is fine -- code that
250 	 * isn't aware of PCID will end up harmlessly flushing
251 	 * context 0.
252 	 */
253 	struct tlb_context ctxs[TLB_NR_DYN_ASIDS];
254 };
255 DECLARE_PER_CPU_SHARED_ALIGNED(struct tlb_state, cpu_tlbstate);
256 
257 /*
258  * Blindly accessing user memory from NMI context can be dangerous
259  * if we're in the middle of switching the current user task or
260  * switching the loaded mm.  It can also be dangerous if we
261  * interrupted some kernel code that was temporarily using a
262  * different mm.
263  */
nmi_uaccess_okay(void)264 static inline bool nmi_uaccess_okay(void)
265 {
266 	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
267 	struct mm_struct *current_mm = current->mm;
268 
269 	VM_WARN_ON_ONCE(!loaded_mm);
270 
271 	/*
272 	 * The condition we want to check is
273 	 * current_mm->pgd == __va(read_cr3_pa()).  This may be slow, though,
274 	 * if we're running in a VM with shadow paging, and nmi_uaccess_okay()
275 	 * is supposed to be reasonably fast.
276 	 *
277 	 * Instead, we check the almost equivalent but somewhat conservative
278 	 * condition below, and we rely on the fact that switch_mm_irqs_off()
279 	 * sets loaded_mm to LOADED_MM_SWITCHING before writing to CR3.
280 	 */
281 	if (loaded_mm != current_mm)
282 		return false;
283 
284 	VM_WARN_ON_ONCE(current_mm->pgd != __va(read_cr3_pa()));
285 
286 	return true;
287 }
288 
289 /* Initialize cr4 shadow for this CPU. */
cr4_init_shadow(void)290 static inline void cr4_init_shadow(void)
291 {
292 	this_cpu_write(cpu_tlbstate.cr4, __read_cr4());
293 }
294 
__cr4_set(unsigned long cr4)295 static inline void __cr4_set(unsigned long cr4)
296 {
297 	lockdep_assert_irqs_disabled();
298 	this_cpu_write(cpu_tlbstate.cr4, cr4);
299 	__write_cr4(cr4);
300 }
301 
302 /* Set in this cpu's CR4. */
cr4_set_bits(unsigned long mask)303 static inline void cr4_set_bits(unsigned long mask)
304 {
305 	unsigned long cr4, flags;
306 
307 	local_irq_save(flags);
308 	cr4 = this_cpu_read(cpu_tlbstate.cr4);
309 	if ((cr4 | mask) != cr4)
310 		__cr4_set(cr4 | mask);
311 	local_irq_restore(flags);
312 }
313 
314 /* Clear in this cpu's CR4. */
cr4_clear_bits(unsigned long mask)315 static inline void cr4_clear_bits(unsigned long mask)
316 {
317 	unsigned long cr4, flags;
318 
319 	local_irq_save(flags);
320 	cr4 = this_cpu_read(cpu_tlbstate.cr4);
321 	if ((cr4 & ~mask) != cr4)
322 		__cr4_set(cr4 & ~mask);
323 	local_irq_restore(flags);
324 }
325 
cr4_toggle_bits_irqsoff(unsigned long mask)326 static inline void cr4_toggle_bits_irqsoff(unsigned long mask)
327 {
328 	unsigned long cr4;
329 
330 	cr4 = this_cpu_read(cpu_tlbstate.cr4);
331 	__cr4_set(cr4 ^ mask);
332 }
333 
334 /* Read the CR4 shadow. */
cr4_read_shadow(void)335 static inline unsigned long cr4_read_shadow(void)
336 {
337 	return this_cpu_read(cpu_tlbstate.cr4);
338 }
339 
340 /*
341  * Mark all other ASIDs as invalid, preserves the current.
342  */
invalidate_other_asid(void)343 static inline void invalidate_other_asid(void)
344 {
345 	this_cpu_write(cpu_tlbstate.invalidate_other, true);
346 }
347 
348 /*
349  * Save some of cr4 feature set we're using (e.g.  Pentium 4MB
350  * enable and PPro Global page enable), so that any CPU's that boot
351  * up after us can get the correct flags.  This should only be used
352  * during boot on the boot cpu.
353  */
354 extern unsigned long mmu_cr4_features;
355 extern u32 *trampoline_cr4_features;
356 
cr4_set_bits_and_update_boot(unsigned long mask)357 static inline void cr4_set_bits_and_update_boot(unsigned long mask)
358 {
359 	mmu_cr4_features |= mask;
360 	if (trampoline_cr4_features)
361 		*trampoline_cr4_features = mmu_cr4_features;
362 	cr4_set_bits(mask);
363 }
364 
365 extern void initialize_tlbstate_and_flush(void);
366 
367 /*
368  * Given an ASID, flush the corresponding user ASID.  We can delay this
369  * until the next time we switch to it.
370  *
371  * See SWITCH_TO_USER_CR3.
372  */
invalidate_user_asid(u16 asid)373 static inline void invalidate_user_asid(u16 asid)
374 {
375 	/* There is no user ASID if address space separation is off */
376 	if (!IS_ENABLED(CONFIG_PAGE_TABLE_ISOLATION))
377 		return;
378 
379 	/*
380 	 * We only have a single ASID if PCID is off and the CR3
381 	 * write will have flushed it.
382 	 */
383 	if (!cpu_feature_enabled(X86_FEATURE_PCID))
384 		return;
385 
386 	if (!static_cpu_has(X86_FEATURE_PTI))
387 		return;
388 
389 	__set_bit(kern_pcid(asid),
390 		  (unsigned long *)this_cpu_ptr(&cpu_tlbstate.user_pcid_flush_mask));
391 }
392 
393 /*
394  * flush the entire current user mapping
395  */
__native_flush_tlb(void)396 static inline void __native_flush_tlb(void)
397 {
398 	/*
399 	 * Preemption or interrupts must be disabled to protect the access
400 	 * to the per CPU variable and to prevent being preempted between
401 	 * read_cr3() and write_cr3().
402 	 */
403 	WARN_ON_ONCE(preemptible());
404 
405 	invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid));
406 
407 	/* If current->mm == NULL then the read_cr3() "borrows" an mm */
408 	native_write_cr3(__native_read_cr3());
409 }
410 
411 /*
412  * flush everything
413  */
__native_flush_tlb_global(void)414 static inline void __native_flush_tlb_global(void)
415 {
416 	unsigned long cr4, flags;
417 
418 	if (static_cpu_has(X86_FEATURE_INVPCID)) {
419 		/*
420 		 * Using INVPCID is considerably faster than a pair of writes
421 		 * to CR4 sandwiched inside an IRQ flag save/restore.
422 		 *
423 		 * Note, this works with CR4.PCIDE=0 or 1.
424 		 */
425 		invpcid_flush_all();
426 		return;
427 	}
428 
429 	/*
430 	 * Read-modify-write to CR4 - protect it from preemption and
431 	 * from interrupts. (Use the raw variant because this code can
432 	 * be called from deep inside debugging code.)
433 	 */
434 	raw_local_irq_save(flags);
435 
436 	cr4 = this_cpu_read(cpu_tlbstate.cr4);
437 	/* toggle PGE */
438 	native_write_cr4(cr4 ^ X86_CR4_PGE);
439 	/* write old PGE again and flush TLBs */
440 	native_write_cr4(cr4);
441 
442 	raw_local_irq_restore(flags);
443 }
444 
445 /*
446  * flush one page in the user mapping
447  */
__native_flush_tlb_one_user(unsigned long addr)448 static inline void __native_flush_tlb_one_user(unsigned long addr)
449 {
450 	u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
451 
452 	asm volatile("invlpg (%0)" ::"r" (addr) : "memory");
453 
454 	if (!static_cpu_has(X86_FEATURE_PTI))
455 		return;
456 
457 	/*
458 	 * Some platforms #GP if we call invpcid(type=1/2) before CR4.PCIDE=1.
459 	 * Just use invalidate_user_asid() in case we are called early.
460 	 */
461 	if (!this_cpu_has(X86_FEATURE_INVPCID_SINGLE))
462 		invalidate_user_asid(loaded_mm_asid);
463 	else
464 		invpcid_flush_one(user_pcid(loaded_mm_asid), addr);
465 }
466 
467 /*
468  * flush everything
469  */
__flush_tlb_all(void)470 static inline void __flush_tlb_all(void)
471 {
472 	if (boot_cpu_has(X86_FEATURE_PGE)) {
473 		__flush_tlb_global();
474 	} else {
475 		/*
476 		 * !PGE -> !PCID (setup_pcid()), thus every flush is total.
477 		 */
478 		__flush_tlb();
479 	}
480 }
481 
482 /*
483  * flush one page in the kernel mapping
484  */
__flush_tlb_one_kernel(unsigned long addr)485 static inline void __flush_tlb_one_kernel(unsigned long addr)
486 {
487 	count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);
488 
489 	/*
490 	 * If PTI is off, then __flush_tlb_one_user() is just INVLPG or its
491 	 * paravirt equivalent.  Even with PCID, this is sufficient: we only
492 	 * use PCID if we also use global PTEs for the kernel mapping, and
493 	 * INVLPG flushes global translations across all address spaces.
494 	 *
495 	 * If PTI is on, then the kernel is mapped with non-global PTEs, and
496 	 * __flush_tlb_one_user() will flush the given address for the current
497 	 * kernel address space and for its usermode counterpart, but it does
498 	 * not flush it for other address spaces.
499 	 */
500 	__flush_tlb_one_user(addr);
501 
502 	if (!static_cpu_has(X86_FEATURE_PTI))
503 		return;
504 
505 	/*
506 	 * See above.  We need to propagate the flush to all other address
507 	 * spaces.  In principle, we only need to propagate it to kernelmode
508 	 * address spaces, but the extra bookkeeping we would need is not
509 	 * worth it.
510 	 */
511 	invalidate_other_asid();
512 }
513 
514 #define TLB_FLUSH_ALL	-1UL
515 
516 /*
517  * TLB flushing:
518  *
519  *  - flush_tlb_all() flushes all processes TLBs
520  *  - flush_tlb_mm(mm) flushes the specified mm context TLB's
521  *  - flush_tlb_page(vma, vmaddr) flushes one page
522  *  - flush_tlb_range(vma, start, end) flushes a range of pages
523  *  - flush_tlb_kernel_range(start, end) flushes a range of kernel pages
524  *  - flush_tlb_others(cpumask, info) flushes TLBs on other cpus
525  *
526  * ..but the i386 has somewhat limited tlb flushing capabilities,
527  * and page-granular flushes are available only on i486 and up.
528  */
529 struct flush_tlb_info {
530 	/*
531 	 * We support several kinds of flushes.
532 	 *
533 	 * - Fully flush a single mm.  .mm will be set, .end will be
534 	 *   TLB_FLUSH_ALL, and .new_tlb_gen will be the tlb_gen to
535 	 *   which the IPI sender is trying to catch us up.
536 	 *
537 	 * - Partially flush a single mm.  .mm will be set, .start and
538 	 *   .end will indicate the range, and .new_tlb_gen will be set
539 	 *   such that the changes between generation .new_tlb_gen-1 and
540 	 *   .new_tlb_gen are entirely contained in the indicated range.
541 	 *
542 	 * - Fully flush all mms whose tlb_gens have been updated.  .mm
543 	 *   will be NULL, .end will be TLB_FLUSH_ALL, and .new_tlb_gen
544 	 *   will be zero.
545 	 */
546 	struct mm_struct	*mm;
547 	unsigned long		start;
548 	unsigned long		end;
549 	u64			new_tlb_gen;
550 };
551 
552 #define local_flush_tlb() __flush_tlb()
553 
554 #define flush_tlb_mm(mm)	flush_tlb_mm_range(mm, 0UL, TLB_FLUSH_ALL, 0UL)
555 
556 #define flush_tlb_range(vma, start, end)	\
557 		flush_tlb_mm_range(vma->vm_mm, start, end, vma->vm_flags)
558 
559 extern void flush_tlb_all(void);
560 extern void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,
561 				unsigned long end, unsigned long vmflag);
562 extern void flush_tlb_kernel_range(unsigned long start, unsigned long end);
563 
flush_tlb_page(struct vm_area_struct * vma,unsigned long a)564 static inline void flush_tlb_page(struct vm_area_struct *vma, unsigned long a)
565 {
566 	flush_tlb_mm_range(vma->vm_mm, a, a + PAGE_SIZE, VM_NONE);
567 }
568 
569 void native_flush_tlb_others(const struct cpumask *cpumask,
570 			     const struct flush_tlb_info *info);
571 
inc_mm_tlb_gen(struct mm_struct * mm)572 static inline u64 inc_mm_tlb_gen(struct mm_struct *mm)
573 {
574 	/*
575 	 * Bump the generation count.  This also serves as a full barrier
576 	 * that synchronizes with switch_mm(): callers are required to order
577 	 * their read of mm_cpumask after their writes to the paging
578 	 * structures.
579 	 */
580 	return atomic64_inc_return(&mm->context.tlb_gen);
581 }
582 
arch_tlbbatch_add_mm(struct arch_tlbflush_unmap_batch * batch,struct mm_struct * mm)583 static inline void arch_tlbbatch_add_mm(struct arch_tlbflush_unmap_batch *batch,
584 					struct mm_struct *mm)
585 {
586 	inc_mm_tlb_gen(mm);
587 	cpumask_or(&batch->cpumask, &batch->cpumask, mm_cpumask(mm));
588 }
589 
590 extern void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch);
591 
592 #ifndef CONFIG_PARAVIRT
593 #define flush_tlb_others(mask, info)	\
594 	native_flush_tlb_others(mask, info)
595 
596 #define paravirt_tlb_remove_table(tlb, page) \
597 	tlb_remove_page(tlb, (void *)(page))
598 #endif
599 
600 #endif /* _ASM_X86_TLBFLUSH_H */
601