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/RSB poisoning by flushing them when switching
671 * between processes. This stops one process from doing Spectre-v2
672 * 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 * Indicate that CR3 is about to change. nmi_uaccess_okay()
903 * and others are sensitive to the window where mm_cpumask(),
904 * CR3 and cpu_tlbstate.loaded_mm are not all in sync.
905 */
906 this_cpu_write(cpu_tlbstate.loaded_mm, LOADED_MM_SWITCHING);
907 barrier();
908
909 /*
910 * Leave this CPU in prev's mm_cpumask. Atomic writes to
911 * mm_cpumask can be expensive under contention. The CPU
912 * will be removed lazily at TLB flush time.
913 */
914 VM_WARN_ON_ONCE(prev != &init_mm && !cpumask_test_cpu(cpu,
915 mm_cpumask(prev)));
916
917 /* Start receiving IPIs and then read tlb_gen (and LAM below) */
918 if (next != &init_mm && !cpumask_test_cpu(cpu, mm_cpumask(next)))
919 cpumask_set_cpu(cpu, mm_cpumask(next));
920 next_tlb_gen = atomic64_read(&next->context.tlb_gen);
921
922 choose_new_asid(next, next_tlb_gen, &new_asid, &need_flush);
923 }
924
925 reload_tlb:
926 new_lam = mm_lam_cr3_mask(next);
927 if (need_flush) {
928 VM_WARN_ON_ONCE(is_global_asid(new_asid));
929 this_cpu_write(cpu_tlbstate.ctxs[new_asid].ctx_id, next->context.ctx_id);
930 this_cpu_write(cpu_tlbstate.ctxs[new_asid].tlb_gen, next_tlb_gen);
931 load_new_mm_cr3(next->pgd, new_asid, new_lam, true);
932
933 trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, TLB_FLUSH_ALL);
934 } else {
935 /* The new ASID is already up to date. */
936 load_new_mm_cr3(next->pgd, new_asid, new_lam, false);
937
938 trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, 0);
939 }
940
941 /* Make sure we write CR3 before loaded_mm. */
942 barrier();
943
944 this_cpu_write(cpu_tlbstate.loaded_mm, next);
945 this_cpu_write(cpu_tlbstate.loaded_mm_asid, new_asid);
946 cpu_tlbstate_update_lam(new_lam, mm_untag_mask(next));
947
948 if (next != prev) {
949 cr4_update_pce_mm(next);
950 switch_ldt(prev, next);
951 }
952 }
953
954 /*
955 * Please ignore the name of this function. It should be called
956 * switch_to_kernel_thread().
957 *
958 * enter_lazy_tlb() is a hint from the scheduler that we are entering a
959 * kernel thread or other context without an mm. Acceptable implementations
960 * include doing nothing whatsoever, switching to init_mm, or various clever
961 * lazy tricks to try to minimize TLB flushes.
962 *
963 * The scheduler reserves the right to call enter_lazy_tlb() several times
964 * in a row. It will notify us that we're going back to a real mm by
965 * calling switch_mm_irqs_off().
966 */
enter_lazy_tlb(struct mm_struct * mm,struct task_struct * tsk)967 void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk)
968 {
969 if (this_cpu_read(cpu_tlbstate.loaded_mm) == &init_mm)
970 return;
971
972 this_cpu_write(cpu_tlbstate_shared.is_lazy, true);
973 }
974
975 /*
976 * Call this when reinitializing a CPU. It fixes the following potential
977 * problems:
978 *
979 * - The ASID changed from what cpu_tlbstate thinks it is (most likely
980 * because the CPU was taken down and came back up with CR3's PCID
981 * bits clear. CPU hotplug can do this.
982 *
983 * - The TLB contains junk in slots corresponding to inactive ASIDs.
984 *
985 * - The CPU went so far out to lunch that it may have missed a TLB
986 * flush.
987 */
initialize_tlbstate_and_flush(void)988 void initialize_tlbstate_and_flush(void)
989 {
990 int i;
991 struct mm_struct *mm = this_cpu_read(cpu_tlbstate.loaded_mm);
992 u64 tlb_gen = atomic64_read(&init_mm.context.tlb_gen);
993 unsigned long lam = mm_lam_cr3_mask(mm);
994 unsigned long cr3 = __read_cr3();
995
996 /* Assert that CR3 already references the right mm. */
997 WARN_ON((cr3 & CR3_ADDR_MASK) != __pa(mm->pgd));
998
999 /* LAM expected to be disabled */
1000 WARN_ON(cr3 & (X86_CR3_LAM_U48 | X86_CR3_LAM_U57));
1001 WARN_ON(lam);
1002
1003 /*
1004 * Assert that CR4.PCIDE is set if needed. (CR4.PCIDE initialization
1005 * doesn't work like other CR4 bits because it can only be set from
1006 * long mode.)
1007 */
1008 WARN_ON(boot_cpu_has(X86_FEATURE_PCID) &&
1009 !(cr4_read_shadow() & X86_CR4_PCIDE));
1010
1011 /* Disable LAM, force ASID 0 and force a TLB flush. */
1012 write_cr3(build_cr3(mm->pgd, 0, 0));
1013
1014 /* Reinitialize tlbstate. */
1015 this_cpu_write(cpu_tlbstate.last_user_mm_spec, LAST_USER_MM_INIT);
1016 this_cpu_write(cpu_tlbstate.loaded_mm_asid, 0);
1017 this_cpu_write(cpu_tlbstate.next_asid, 1);
1018 this_cpu_write(cpu_tlbstate.ctxs[0].ctx_id, mm->context.ctx_id);
1019 this_cpu_write(cpu_tlbstate.ctxs[0].tlb_gen, tlb_gen);
1020 cpu_tlbstate_update_lam(lam, mm_untag_mask(mm));
1021
1022 for (i = 1; i < TLB_NR_DYN_ASIDS; i++)
1023 this_cpu_write(cpu_tlbstate.ctxs[i].ctx_id, 0);
1024 }
1025
1026 /*
1027 * flush_tlb_func()'s memory ordering requirement is that any
1028 * TLB fills that happen after we flush the TLB are ordered after we
1029 * read active_mm's tlb_gen. We don't need any explicit barriers
1030 * because all x86 flush operations are serializing and the
1031 * atomic64_read operation won't be reordered by the compiler.
1032 */
flush_tlb_func(void * info)1033 static void flush_tlb_func(void *info)
1034 {
1035 /*
1036 * We have three different tlb_gen values in here. They are:
1037 *
1038 * - mm_tlb_gen: the latest generation.
1039 * - local_tlb_gen: the generation that this CPU has already caught
1040 * up to.
1041 * - f->new_tlb_gen: the generation that the requester of the flush
1042 * wants us to catch up to.
1043 */
1044 const struct flush_tlb_info *f = info;
1045 struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1046 u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
1047 u64 local_tlb_gen;
1048 bool local = smp_processor_id() == f->initiating_cpu;
1049 unsigned long nr_invalidate = 0;
1050 u64 mm_tlb_gen;
1051
1052 /* This code cannot presently handle being reentered. */
1053 VM_WARN_ON(!irqs_disabled());
1054
1055 if (!local) {
1056 inc_irq_stat(irq_tlb_count);
1057 count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
1058 }
1059
1060 /* The CPU was left in the mm_cpumask of the target mm. Clear it. */
1061 if (f->mm && f->mm != loaded_mm) {
1062 cpumask_clear_cpu(raw_smp_processor_id(), mm_cpumask(f->mm));
1063 trace_tlb_flush(TLB_REMOTE_WRONG_CPU, 0);
1064 return;
1065 }
1066
1067 if (unlikely(loaded_mm == &init_mm))
1068 return;
1069
1070 /* Reload the ASID if transitioning into or out of a global ASID */
1071 if (mm_needs_global_asid(loaded_mm, loaded_mm_asid)) {
1072 switch_mm_irqs_off(NULL, loaded_mm, NULL);
1073 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
1074 }
1075
1076 /* Broadcast ASIDs are always kept up to date with INVLPGB. */
1077 if (is_global_asid(loaded_mm_asid))
1078 return;
1079
1080 VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) !=
1081 loaded_mm->context.ctx_id);
1082
1083 if (this_cpu_read(cpu_tlbstate_shared.is_lazy)) {
1084 /*
1085 * We're in lazy mode. We need to at least flush our
1086 * paging-structure cache to avoid speculatively reading
1087 * garbage into our TLB. Since switching to init_mm is barely
1088 * slower than a minimal flush, just switch to init_mm.
1089 *
1090 * This should be rare, with native_flush_tlb_multi() skipping
1091 * IPIs to lazy TLB mode CPUs.
1092 */
1093 switch_mm_irqs_off(NULL, &init_mm, NULL);
1094 return;
1095 }
1096
1097 local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen);
1098
1099 if (unlikely(f->new_tlb_gen != TLB_GENERATION_INVALID &&
1100 f->new_tlb_gen <= local_tlb_gen)) {
1101 /*
1102 * The TLB is already up to date in respect to f->new_tlb_gen.
1103 * While the core might be still behind mm_tlb_gen, checking
1104 * mm_tlb_gen unnecessarily would have negative caching effects
1105 * so avoid it.
1106 */
1107 return;
1108 }
1109
1110 /*
1111 * Defer mm_tlb_gen reading as long as possible to avoid cache
1112 * contention.
1113 */
1114 mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen);
1115
1116 if (unlikely(local_tlb_gen == mm_tlb_gen)) {
1117 /*
1118 * There's nothing to do: we're already up to date. This can
1119 * happen if two concurrent flushes happen -- the first flush to
1120 * be handled can catch us all the way up, leaving no work for
1121 * the second flush.
1122 */
1123 goto done;
1124 }
1125
1126 WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen);
1127 WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen);
1128
1129 /*
1130 * If we get to this point, we know that our TLB is out of date.
1131 * This does not strictly imply that we need to flush (it's
1132 * possible that f->new_tlb_gen <= local_tlb_gen), but we're
1133 * going to need to flush in the very near future, so we might
1134 * as well get it over with.
1135 *
1136 * The only question is whether to do a full or partial flush.
1137 *
1138 * We do a partial flush if requested and two extra conditions
1139 * are met:
1140 *
1141 * 1. f->new_tlb_gen == local_tlb_gen + 1. We have an invariant that
1142 * we've always done all needed flushes to catch up to
1143 * local_tlb_gen. If, for example, local_tlb_gen == 2 and
1144 * f->new_tlb_gen == 3, then we know that the flush needed to bring
1145 * us up to date for tlb_gen 3 is the partial flush we're
1146 * processing.
1147 *
1148 * As an example of why this check is needed, suppose that there
1149 * are two concurrent flushes. The first is a full flush that
1150 * changes context.tlb_gen from 1 to 2. The second is a partial
1151 * flush that changes context.tlb_gen from 2 to 3. If they get
1152 * processed on this CPU in reverse order, we'll see
1153 * local_tlb_gen == 1, mm_tlb_gen == 3, and end != TLB_FLUSH_ALL.
1154 * If we were to use __flush_tlb_one_user() and set local_tlb_gen to
1155 * 3, we'd be break the invariant: we'd update local_tlb_gen above
1156 * 1 without the full flush that's needed for tlb_gen 2.
1157 *
1158 * 2. f->new_tlb_gen == mm_tlb_gen. This is purely an optimization.
1159 * Partial TLB flushes are not all that much cheaper than full TLB
1160 * flushes, so it seems unlikely that it would be a performance win
1161 * to do a partial flush if that won't bring our TLB fully up to
1162 * date. By doing a full flush instead, we can increase
1163 * local_tlb_gen all the way to mm_tlb_gen and we can probably
1164 * avoid another flush in the very near future.
1165 */
1166 if (f->end != TLB_FLUSH_ALL &&
1167 f->new_tlb_gen == local_tlb_gen + 1 &&
1168 f->new_tlb_gen == mm_tlb_gen) {
1169 /* Partial flush */
1170 unsigned long addr = f->start;
1171
1172 /* Partial flush cannot have invalid generations */
1173 VM_WARN_ON(f->new_tlb_gen == TLB_GENERATION_INVALID);
1174
1175 /* Partial flush must have valid mm */
1176 VM_WARN_ON(f->mm == NULL);
1177
1178 nr_invalidate = (f->end - f->start) >> f->stride_shift;
1179
1180 while (addr < f->end) {
1181 flush_tlb_one_user(addr);
1182 addr += 1UL << f->stride_shift;
1183 }
1184 if (local)
1185 count_vm_tlb_events(NR_TLB_LOCAL_FLUSH_ONE, nr_invalidate);
1186 } else {
1187 /* Full flush. */
1188 nr_invalidate = TLB_FLUSH_ALL;
1189
1190 flush_tlb_local();
1191 if (local)
1192 count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);
1193 }
1194
1195 /* Both paths above update our state to mm_tlb_gen. */
1196 this_cpu_write(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen, mm_tlb_gen);
1197
1198 /* Tracing is done in a unified manner to reduce the code size */
1199 done:
1200 trace_tlb_flush(!local ? TLB_REMOTE_SHOOTDOWN :
1201 (f->mm == NULL) ? TLB_LOCAL_SHOOTDOWN :
1202 TLB_LOCAL_MM_SHOOTDOWN,
1203 nr_invalidate);
1204 }
1205
should_flush_tlb(int cpu,void * data)1206 static bool should_flush_tlb(int cpu, void *data)
1207 {
1208 struct mm_struct *loaded_mm = per_cpu(cpu_tlbstate.loaded_mm, cpu);
1209 struct flush_tlb_info *info = data;
1210
1211 /*
1212 * Order the 'loaded_mm' and 'is_lazy' against their
1213 * write ordering in switch_mm_irqs_off(). Ensure
1214 * 'is_lazy' is at least as new as 'loaded_mm'.
1215 */
1216 smp_rmb();
1217
1218 /* Lazy TLB will get flushed at the next context switch. */
1219 if (per_cpu(cpu_tlbstate_shared.is_lazy, cpu))
1220 return false;
1221
1222 /* No mm means kernel memory flush. */
1223 if (!info->mm)
1224 return true;
1225
1226 /*
1227 * While switching, the remote CPU could have state from
1228 * either the prev or next mm. Assume the worst and flush.
1229 */
1230 if (loaded_mm == LOADED_MM_SWITCHING)
1231 return true;
1232
1233 /* The target mm is loaded, and the CPU is not lazy. */
1234 if (loaded_mm == info->mm)
1235 return true;
1236
1237 /* In cpumask, but not the loaded mm? Periodically remove by flushing. */
1238 if (info->trim_cpumask)
1239 return true;
1240
1241 return false;
1242 }
1243
should_trim_cpumask(struct mm_struct * mm)1244 static bool should_trim_cpumask(struct mm_struct *mm)
1245 {
1246 if (time_after(jiffies, READ_ONCE(mm->context.next_trim_cpumask))) {
1247 WRITE_ONCE(mm->context.next_trim_cpumask, jiffies + HZ);
1248 return true;
1249 }
1250 return false;
1251 }
1252
1253 DEFINE_PER_CPU_SHARED_ALIGNED(struct tlb_state_shared, cpu_tlbstate_shared);
1254 EXPORT_PER_CPU_SYMBOL(cpu_tlbstate_shared);
1255
native_flush_tlb_multi(const struct cpumask * cpumask,const struct flush_tlb_info * info)1256 STATIC_NOPV void native_flush_tlb_multi(const struct cpumask *cpumask,
1257 const struct flush_tlb_info *info)
1258 {
1259 /*
1260 * Do accounting and tracing. Note that there are (and have always been)
1261 * cases in which a remote TLB flush will be traced, but eventually
1262 * would not happen.
1263 */
1264 count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
1265 if (info->end == TLB_FLUSH_ALL)
1266 trace_tlb_flush(TLB_REMOTE_SEND_IPI, TLB_FLUSH_ALL);
1267 else
1268 trace_tlb_flush(TLB_REMOTE_SEND_IPI,
1269 (info->end - info->start) >> PAGE_SHIFT);
1270
1271 /*
1272 * If no page tables were freed, we can skip sending IPIs to
1273 * CPUs in lazy TLB mode. They will flush the CPU themselves
1274 * at the next context switch.
1275 *
1276 * However, if page tables are getting freed, we need to send the
1277 * IPI everywhere, to prevent CPUs in lazy TLB mode from tripping
1278 * up on the new contents of what used to be page tables, while
1279 * doing a speculative memory access.
1280 */
1281 if (info->freed_tables || mm_in_asid_transition(info->mm))
1282 on_each_cpu_mask(cpumask, flush_tlb_func, (void *)info, true);
1283 else
1284 on_each_cpu_cond_mask(should_flush_tlb, flush_tlb_func,
1285 (void *)info, 1, cpumask);
1286 }
1287
flush_tlb_multi(const struct cpumask * cpumask,const struct flush_tlb_info * info)1288 void flush_tlb_multi(const struct cpumask *cpumask,
1289 const struct flush_tlb_info *info)
1290 {
1291 __flush_tlb_multi(cpumask, info);
1292 }
1293
1294 /*
1295 * See Documentation/arch/x86/tlb.rst for details. We choose 33
1296 * because it is large enough to cover the vast majority (at
1297 * least 95%) of allocations, and is small enough that we are
1298 * confident it will not cause too much overhead. Each single
1299 * flush is about 100 ns, so this caps the maximum overhead at
1300 * _about_ 3,000 ns.
1301 *
1302 * This is in units of pages.
1303 */
1304 unsigned long tlb_single_page_flush_ceiling __read_mostly = 33;
1305
1306 static DEFINE_PER_CPU_SHARED_ALIGNED(struct flush_tlb_info, flush_tlb_info);
1307
1308 #ifdef CONFIG_DEBUG_VM
1309 static DEFINE_PER_CPU(unsigned int, flush_tlb_info_idx);
1310 #endif
1311
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)1312 static struct flush_tlb_info *get_flush_tlb_info(struct mm_struct *mm,
1313 unsigned long start, unsigned long end,
1314 unsigned int stride_shift, bool freed_tables,
1315 u64 new_tlb_gen)
1316 {
1317 struct flush_tlb_info *info = this_cpu_ptr(&flush_tlb_info);
1318
1319 #ifdef CONFIG_DEBUG_VM
1320 /*
1321 * Ensure that the following code is non-reentrant and flush_tlb_info
1322 * is not overwritten. This means no TLB flushing is initiated by
1323 * interrupt handlers and machine-check exception handlers.
1324 */
1325 BUG_ON(this_cpu_inc_return(flush_tlb_info_idx) != 1);
1326 #endif
1327
1328 /*
1329 * If the number of flushes is so large that a full flush
1330 * would be faster, do a full flush.
1331 */
1332 if ((end - start) >> stride_shift > tlb_single_page_flush_ceiling) {
1333 start = 0;
1334 end = TLB_FLUSH_ALL;
1335 }
1336
1337 info->start = start;
1338 info->end = end;
1339 info->mm = mm;
1340 info->stride_shift = stride_shift;
1341 info->freed_tables = freed_tables;
1342 info->new_tlb_gen = new_tlb_gen;
1343 info->initiating_cpu = smp_processor_id();
1344 info->trim_cpumask = 0;
1345
1346 return info;
1347 }
1348
put_flush_tlb_info(void)1349 static void put_flush_tlb_info(void)
1350 {
1351 #ifdef CONFIG_DEBUG_VM
1352 /* Complete reentrancy prevention checks */
1353 barrier();
1354 this_cpu_dec(flush_tlb_info_idx);
1355 #endif
1356 }
1357
flush_tlb_mm_range(struct mm_struct * mm,unsigned long start,unsigned long end,unsigned int stride_shift,bool freed_tables)1358 void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,
1359 unsigned long end, unsigned int stride_shift,
1360 bool freed_tables)
1361 {
1362 struct flush_tlb_info *info;
1363 int cpu = get_cpu();
1364 u64 new_tlb_gen;
1365
1366 /* This is also a barrier that synchronizes with switch_mm(). */
1367 new_tlb_gen = inc_mm_tlb_gen(mm);
1368
1369 info = get_flush_tlb_info(mm, start, end, stride_shift, freed_tables,
1370 new_tlb_gen);
1371
1372 /*
1373 * flush_tlb_multi() is not optimized for the common case in which only
1374 * a local TLB flush is needed. Optimize this use-case by calling
1375 * flush_tlb_func_local() directly in this case.
1376 */
1377 if (mm_global_asid(mm)) {
1378 broadcast_tlb_flush(info);
1379 } else if (cpumask_any_but(mm_cpumask(mm), cpu) < nr_cpu_ids) {
1380 info->trim_cpumask = should_trim_cpumask(mm);
1381 flush_tlb_multi(mm_cpumask(mm), info);
1382 consider_global_asid(mm);
1383 } else if (mm == this_cpu_read(cpu_tlbstate.loaded_mm)) {
1384 lockdep_assert_irqs_enabled();
1385 local_irq_disable();
1386 flush_tlb_func(info);
1387 local_irq_enable();
1388 }
1389
1390 put_flush_tlb_info();
1391 put_cpu();
1392 mmu_notifier_arch_invalidate_secondary_tlbs(mm, start, end);
1393 }
1394
do_flush_tlb_all(void * info)1395 static void do_flush_tlb_all(void *info)
1396 {
1397 count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
1398 __flush_tlb_all();
1399 }
1400
flush_tlb_all(void)1401 void flush_tlb_all(void)
1402 {
1403 count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
1404
1405 /* First try (faster) hardware-assisted TLB invalidation. */
1406 if (cpu_feature_enabled(X86_FEATURE_INVLPGB))
1407 invlpgb_flush_all();
1408 else
1409 /* Fall back to the IPI-based invalidation. */
1410 on_each_cpu(do_flush_tlb_all, NULL, 1);
1411 }
1412
1413 /* Flush an arbitrarily large range of memory with INVLPGB. */
invlpgb_kernel_range_flush(struct flush_tlb_info * info)1414 static void invlpgb_kernel_range_flush(struct flush_tlb_info *info)
1415 {
1416 unsigned long addr, nr;
1417
1418 for (addr = info->start; addr < info->end; addr += nr << PAGE_SHIFT) {
1419 nr = (info->end - addr) >> PAGE_SHIFT;
1420
1421 /*
1422 * INVLPGB has a limit on the size of ranges it can
1423 * flush. Break up large flushes.
1424 */
1425 nr = clamp_val(nr, 1, invlpgb_count_max);
1426
1427 invlpgb_flush_addr_nosync(addr, nr);
1428 }
1429 __tlbsync();
1430 }
1431
do_kernel_range_flush(void * info)1432 static void do_kernel_range_flush(void *info)
1433 {
1434 struct flush_tlb_info *f = info;
1435 unsigned long addr;
1436
1437 /* flush range by one by one 'invlpg' */
1438 for (addr = f->start; addr < f->end; addr += PAGE_SIZE)
1439 flush_tlb_one_kernel(addr);
1440 }
1441
kernel_tlb_flush_all(struct flush_tlb_info * info)1442 static void kernel_tlb_flush_all(struct flush_tlb_info *info)
1443 {
1444 if (cpu_feature_enabled(X86_FEATURE_INVLPGB))
1445 invlpgb_flush_all();
1446 else
1447 on_each_cpu(do_flush_tlb_all, NULL, 1);
1448 }
1449
kernel_tlb_flush_range(struct flush_tlb_info * info)1450 static void kernel_tlb_flush_range(struct flush_tlb_info *info)
1451 {
1452 if (cpu_feature_enabled(X86_FEATURE_INVLPGB))
1453 invlpgb_kernel_range_flush(info);
1454 else
1455 on_each_cpu(do_kernel_range_flush, info, 1);
1456 }
1457
flush_tlb_kernel_range(unsigned long start,unsigned long end)1458 void flush_tlb_kernel_range(unsigned long start, unsigned long end)
1459 {
1460 struct flush_tlb_info *info;
1461
1462 guard(preempt)();
1463
1464 info = get_flush_tlb_info(NULL, start, end, PAGE_SHIFT, false,
1465 TLB_GENERATION_INVALID);
1466
1467 if (info->end == TLB_FLUSH_ALL)
1468 kernel_tlb_flush_all(info);
1469 else
1470 kernel_tlb_flush_range(info);
1471
1472 put_flush_tlb_info();
1473 }
1474
1475 /*
1476 * This can be used from process context to figure out what the value of
1477 * CR3 is without needing to do a (slow) __read_cr3().
1478 *
1479 * It's intended to be used for code like KVM that sneakily changes CR3
1480 * and needs to restore it. It needs to be used very carefully.
1481 */
__get_current_cr3_fast(void)1482 unsigned long __get_current_cr3_fast(void)
1483 {
1484 unsigned long cr3 =
1485 build_cr3(this_cpu_read(cpu_tlbstate.loaded_mm)->pgd,
1486 this_cpu_read(cpu_tlbstate.loaded_mm_asid),
1487 tlbstate_lam_cr3_mask());
1488
1489 /* For now, be very restrictive about when this can be called. */
1490 VM_WARN_ON(in_nmi() || preemptible());
1491
1492 VM_BUG_ON(cr3 != __read_cr3());
1493 return cr3;
1494 }
1495 EXPORT_SYMBOL_GPL(__get_current_cr3_fast);
1496
1497 /*
1498 * Flush one page in the kernel mapping
1499 */
flush_tlb_one_kernel(unsigned long addr)1500 void flush_tlb_one_kernel(unsigned long addr)
1501 {
1502 count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ONE);
1503
1504 /*
1505 * If PTI is off, then __flush_tlb_one_user() is just INVLPG or its
1506 * paravirt equivalent. Even with PCID, this is sufficient: we only
1507 * use PCID if we also use global PTEs for the kernel mapping, and
1508 * INVLPG flushes global translations across all address spaces.
1509 *
1510 * If PTI is on, then the kernel is mapped with non-global PTEs, and
1511 * __flush_tlb_one_user() will flush the given address for the current
1512 * kernel address space and for its usermode counterpart, but it does
1513 * not flush it for other address spaces.
1514 */
1515 flush_tlb_one_user(addr);
1516
1517 if (!static_cpu_has(X86_FEATURE_PTI))
1518 return;
1519
1520 /*
1521 * See above. We need to propagate the flush to all other address
1522 * spaces. In principle, we only need to propagate it to kernelmode
1523 * address spaces, but the extra bookkeeping we would need is not
1524 * worth it.
1525 */
1526 this_cpu_write(cpu_tlbstate.invalidate_other, true);
1527 }
1528
1529 /*
1530 * Flush one page in the user mapping
1531 */
native_flush_tlb_one_user(unsigned long addr)1532 STATIC_NOPV void native_flush_tlb_one_user(unsigned long addr)
1533 {
1534 u32 loaded_mm_asid;
1535 bool cpu_pcide;
1536
1537 /* Flush 'addr' from the kernel PCID: */
1538 invlpg(addr);
1539
1540 /* If PTI is off there is no user PCID and nothing to flush. */
1541 if (!static_cpu_has(X86_FEATURE_PTI))
1542 return;
1543
1544 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
1545 cpu_pcide = this_cpu_read(cpu_tlbstate.cr4) & X86_CR4_PCIDE;
1546
1547 /*
1548 * invpcid_flush_one(pcid>0) will #GP if CR4.PCIDE==0. Check
1549 * 'cpu_pcide' to ensure that *this* CPU will not trigger those
1550 * #GP's even if called before CR4.PCIDE has been initialized.
1551 */
1552 if (boot_cpu_has(X86_FEATURE_INVPCID) && cpu_pcide)
1553 invpcid_flush_one(user_pcid(loaded_mm_asid), addr);
1554 else
1555 invalidate_user_asid(loaded_mm_asid);
1556 }
1557
flush_tlb_one_user(unsigned long addr)1558 void flush_tlb_one_user(unsigned long addr)
1559 {
1560 __flush_tlb_one_user(addr);
1561 }
1562
1563 /*
1564 * Flush everything
1565 */
native_flush_tlb_global(void)1566 STATIC_NOPV void native_flush_tlb_global(void)
1567 {
1568 unsigned long flags;
1569
1570 if (static_cpu_has(X86_FEATURE_INVPCID)) {
1571 /*
1572 * Using INVPCID is considerably faster than a pair of writes
1573 * to CR4 sandwiched inside an IRQ flag save/restore.
1574 *
1575 * Note, this works with CR4.PCIDE=0 or 1.
1576 */
1577 invpcid_flush_all();
1578 return;
1579 }
1580
1581 /*
1582 * Read-modify-write to CR4 - protect it from preemption and
1583 * from interrupts. (Use the raw variant because this code can
1584 * be called from deep inside debugging code.)
1585 */
1586 raw_local_irq_save(flags);
1587
1588 __native_tlb_flush_global(this_cpu_read(cpu_tlbstate.cr4));
1589
1590 raw_local_irq_restore(flags);
1591 }
1592
1593 /*
1594 * Flush the entire current user mapping
1595 */
native_flush_tlb_local(void)1596 STATIC_NOPV void native_flush_tlb_local(void)
1597 {
1598 /*
1599 * Preemption or interrupts must be disabled to protect the access
1600 * to the per CPU variable and to prevent being preempted between
1601 * read_cr3() and write_cr3().
1602 */
1603 WARN_ON_ONCE(preemptible());
1604
1605 invalidate_user_asid(this_cpu_read(cpu_tlbstate.loaded_mm_asid));
1606
1607 /* If current->mm == NULL then the read_cr3() "borrows" an mm */
1608 native_write_cr3(__native_read_cr3());
1609 }
1610
flush_tlb_local(void)1611 void flush_tlb_local(void)
1612 {
1613 __flush_tlb_local();
1614 }
1615
1616 /*
1617 * Flush everything
1618 */
__flush_tlb_all(void)1619 void __flush_tlb_all(void)
1620 {
1621 /*
1622 * This is to catch users with enabled preemption and the PGE feature
1623 * and don't trigger the warning in __native_flush_tlb().
1624 */
1625 VM_WARN_ON_ONCE(preemptible());
1626
1627 if (cpu_feature_enabled(X86_FEATURE_PGE)) {
1628 __flush_tlb_global();
1629 } else {
1630 /*
1631 * !PGE -> !PCID (setup_pcid()), thus every flush is total.
1632 */
1633 flush_tlb_local();
1634 }
1635 }
1636 EXPORT_SYMBOL_GPL(__flush_tlb_all);
1637
arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch * batch)1638 void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)
1639 {
1640 struct flush_tlb_info *info;
1641
1642 int cpu = get_cpu();
1643
1644 info = get_flush_tlb_info(NULL, 0, TLB_FLUSH_ALL, 0, false,
1645 TLB_GENERATION_INVALID);
1646 /*
1647 * flush_tlb_multi() is not optimized for the common case in which only
1648 * a local TLB flush is needed. Optimize this use-case by calling
1649 * flush_tlb_func_local() directly in this case.
1650 */
1651 if (cpu_feature_enabled(X86_FEATURE_INVLPGB) && batch->unmapped_pages) {
1652 invlpgb_flush_all_nonglobals();
1653 batch->unmapped_pages = false;
1654 } else if (cpumask_any_but(&batch->cpumask, cpu) < nr_cpu_ids) {
1655 flush_tlb_multi(&batch->cpumask, info);
1656 } else if (cpumask_test_cpu(cpu, &batch->cpumask)) {
1657 lockdep_assert_irqs_enabled();
1658 local_irq_disable();
1659 flush_tlb_func(info);
1660 local_irq_enable();
1661 }
1662
1663 cpumask_clear(&batch->cpumask);
1664
1665 put_flush_tlb_info();
1666 put_cpu();
1667 }
1668
1669 /*
1670 * Blindly accessing user memory from NMI context can be dangerous
1671 * if we're in the middle of switching the current user task or
1672 * switching the loaded mm. It can also be dangerous if we
1673 * interrupted some kernel code that was temporarily using a
1674 * different mm.
1675 */
nmi_uaccess_okay(void)1676 bool nmi_uaccess_okay(void)
1677 {
1678 struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
1679 struct mm_struct *current_mm = current->mm;
1680
1681 VM_WARN_ON_ONCE(!loaded_mm);
1682
1683 /*
1684 * The condition we want to check is
1685 * current_mm->pgd == __va(read_cr3_pa()). This may be slow, though,
1686 * if we're running in a VM with shadow paging, and nmi_uaccess_okay()
1687 * is supposed to be reasonably fast.
1688 *
1689 * Instead, we check the almost equivalent but somewhat conservative
1690 * condition below, and we rely on the fact that switch_mm_irqs_off()
1691 * sets loaded_mm to LOADED_MM_SWITCHING before writing to CR3.
1692 */
1693 if (loaded_mm != current_mm)
1694 return false;
1695
1696 VM_WARN_ON_ONCE(__pa(current_mm->pgd) != read_cr3_pa());
1697
1698 return true;
1699 }
1700
tlbflush_read_file(struct file * file,char __user * user_buf,size_t count,loff_t * ppos)1701 static ssize_t tlbflush_read_file(struct file *file, char __user *user_buf,
1702 size_t count, loff_t *ppos)
1703 {
1704 char buf[32];
1705 unsigned int len;
1706
1707 len = sprintf(buf, "%ld\n", tlb_single_page_flush_ceiling);
1708 return simple_read_from_buffer(user_buf, count, ppos, buf, len);
1709 }
1710
tlbflush_write_file(struct file * file,const char __user * user_buf,size_t count,loff_t * ppos)1711 static ssize_t tlbflush_write_file(struct file *file,
1712 const char __user *user_buf, size_t count, loff_t *ppos)
1713 {
1714 char buf[32];
1715 ssize_t len;
1716 int ceiling;
1717
1718 len = min(count, sizeof(buf) - 1);
1719 if (copy_from_user(buf, user_buf, len))
1720 return -EFAULT;
1721
1722 buf[len] = '\0';
1723 if (kstrtoint(buf, 0, &ceiling))
1724 return -EINVAL;
1725
1726 if (ceiling < 0)
1727 return -EINVAL;
1728
1729 tlb_single_page_flush_ceiling = ceiling;
1730 return count;
1731 }
1732
1733 static const struct file_operations fops_tlbflush = {
1734 .read = tlbflush_read_file,
1735 .write = tlbflush_write_file,
1736 .llseek = default_llseek,
1737 };
1738
create_tlb_single_page_flush_ceiling(void)1739 static int __init create_tlb_single_page_flush_ceiling(void)
1740 {
1741 debugfs_create_file("tlb_single_page_flush_ceiling", S_IRUSR | S_IWUSR,
1742 arch_debugfs_dir, NULL, &fops_tlbflush);
1743 return 0;
1744 }
1745 late_initcall(create_tlb_single_page_flush_ceiling);
1746