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