tlb.c 38 KB

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