tlb.c 41 KB

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