xref: /linux/arch/x86/mm/tlb.c (revision 26b433d0da062d6e19d75350c0171d3cf8ff560d)
1 #include <linux/init.h>
2 
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 
10 #include <asm/tlbflush.h>
11 #include <asm/mmu_context.h>
12 #include <asm/cache.h>
13 #include <asm/apic.h>
14 #include <asm/uv/uv.h>
15 #include <linux/debugfs.h>
16 
17 /*
18  *	TLB flushing, formerly SMP-only
19  *		c/o Linus Torvalds.
20  *
21  *	These mean you can really definitely utterly forget about
22  *	writing to user space from interrupts. (Its not allowed anyway).
23  *
24  *	Optimizations Manfred Spraul <manfred@colorfullife.com>
25  *
26  *	More scalable flush, from Andi Kleen
27  *
28  *	Implement flush IPI by CALL_FUNCTION_VECTOR, Alex Shi
29  */
30 
31 atomic64_t last_mm_ctx_id = ATOMIC64_INIT(1);
32 
33 static void choose_new_asid(struct mm_struct *next, u64 next_tlb_gen,
34 			    u16 *new_asid, bool *need_flush)
35 {
36 	u16 asid;
37 
38 	if (!static_cpu_has(X86_FEATURE_PCID)) {
39 		*new_asid = 0;
40 		*need_flush = true;
41 		return;
42 	}
43 
44 	for (asid = 0; asid < TLB_NR_DYN_ASIDS; asid++) {
45 		if (this_cpu_read(cpu_tlbstate.ctxs[asid].ctx_id) !=
46 		    next->context.ctx_id)
47 			continue;
48 
49 		*new_asid = asid;
50 		*need_flush = (this_cpu_read(cpu_tlbstate.ctxs[asid].tlb_gen) <
51 			       next_tlb_gen);
52 		return;
53 	}
54 
55 	/*
56 	 * We don't currently own an ASID slot on this CPU.
57 	 * Allocate a slot.
58 	 */
59 	*new_asid = this_cpu_add_return(cpu_tlbstate.next_asid, 1) - 1;
60 	if (*new_asid >= TLB_NR_DYN_ASIDS) {
61 		*new_asid = 0;
62 		this_cpu_write(cpu_tlbstate.next_asid, 1);
63 	}
64 	*need_flush = true;
65 }
66 
67 void leave_mm(int cpu)
68 {
69 	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
70 
71 	/*
72 	 * It's plausible that we're in lazy TLB mode while our mm is init_mm.
73 	 * If so, our callers still expect us to flush the TLB, but there
74 	 * aren't any user TLB entries in init_mm to worry about.
75 	 *
76 	 * This needs to happen before any other sanity checks due to
77 	 * intel_idle's shenanigans.
78 	 */
79 	if (loaded_mm == &init_mm)
80 		return;
81 
82 	/* Warn if we're not lazy. */
83 	WARN_ON(cpumask_test_cpu(smp_processor_id(), mm_cpumask(loaded_mm)));
84 
85 	switch_mm(NULL, &init_mm, NULL);
86 }
87 
88 void switch_mm(struct mm_struct *prev, struct mm_struct *next,
89 	       struct task_struct *tsk)
90 {
91 	unsigned long flags;
92 
93 	local_irq_save(flags);
94 	switch_mm_irqs_off(prev, next, tsk);
95 	local_irq_restore(flags);
96 }
97 
98 void switch_mm_irqs_off(struct mm_struct *prev, struct mm_struct *next,
99 			struct task_struct *tsk)
100 {
101 	struct mm_struct *real_prev = this_cpu_read(cpu_tlbstate.loaded_mm);
102 	u16 prev_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
103 	unsigned cpu = smp_processor_id();
104 	u64 next_tlb_gen;
105 
106 	/*
107 	 * NB: The scheduler will call us with prev == next when switching
108 	 * from lazy TLB mode to normal mode if active_mm isn't changing.
109 	 * When this happens, we don't assume that CR3 (and hence
110 	 * cpu_tlbstate.loaded_mm) matches next.
111 	 *
112 	 * NB: leave_mm() calls us with prev == NULL and tsk == NULL.
113 	 */
114 
115 	/* We don't want flush_tlb_func_* to run concurrently with us. */
116 	if (IS_ENABLED(CONFIG_PROVE_LOCKING))
117 		WARN_ON_ONCE(!irqs_disabled());
118 
119 	/*
120 	 * Verify that CR3 is what we think it is.  This will catch
121 	 * hypothetical buggy code that directly switches to swapper_pg_dir
122 	 * without going through leave_mm() / switch_mm_irqs_off() or that
123 	 * does something like write_cr3(read_cr3_pa()).
124 	 */
125 	VM_BUG_ON(__read_cr3() != (__sme_pa(real_prev->pgd) | prev_asid));
126 
127 	if (real_prev == next) {
128 		VM_BUG_ON(this_cpu_read(cpu_tlbstate.ctxs[prev_asid].ctx_id) !=
129 			  next->context.ctx_id);
130 
131 		if (cpumask_test_cpu(cpu, mm_cpumask(next))) {
132 			/*
133 			 * There's nothing to do: we weren't lazy, and we
134 			 * aren't changing our mm.  We don't need to flush
135 			 * anything, nor do we need to update CR3, CR4, or
136 			 * LDTR.
137 			 */
138 			return;
139 		}
140 
141 		/* Resume remote flushes and then read tlb_gen. */
142 		cpumask_set_cpu(cpu, mm_cpumask(next));
143 		next_tlb_gen = atomic64_read(&next->context.tlb_gen);
144 
145 		if (this_cpu_read(cpu_tlbstate.ctxs[prev_asid].tlb_gen) <
146 		    next_tlb_gen) {
147 			/*
148 			 * Ideally, we'd have a flush_tlb() variant that
149 			 * takes the known CR3 value as input.  This would
150 			 * be faster on Xen PV and on hypothetical CPUs
151 			 * on which INVPCID is fast.
152 			 */
153 			this_cpu_write(cpu_tlbstate.ctxs[prev_asid].tlb_gen,
154 				       next_tlb_gen);
155 			write_cr3(__sme_pa(next->pgd) | prev_asid);
156 			trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH,
157 					TLB_FLUSH_ALL);
158 		}
159 
160 		/*
161 		 * We just exited lazy mode, which means that CR4 and/or LDTR
162 		 * may be stale.  (Changes to the required CR4 and LDTR states
163 		 * are not reflected in tlb_gen.)
164 		 */
165 	} else {
166 		u16 new_asid;
167 		bool need_flush;
168 
169 		if (IS_ENABLED(CONFIG_VMAP_STACK)) {
170 			/*
171 			 * If our current stack is in vmalloc space and isn't
172 			 * mapped in the new pgd, we'll double-fault.  Forcibly
173 			 * map it.
174 			 */
175 			unsigned int index = pgd_index(current_stack_pointer());
176 			pgd_t *pgd = next->pgd + index;
177 
178 			if (unlikely(pgd_none(*pgd)))
179 				set_pgd(pgd, init_mm.pgd[index]);
180 		}
181 
182 		/* Stop remote flushes for the previous mm */
183 		if (cpumask_test_cpu(cpu, mm_cpumask(real_prev)))
184 			cpumask_clear_cpu(cpu, mm_cpumask(real_prev));
185 
186 		VM_WARN_ON_ONCE(cpumask_test_cpu(cpu, mm_cpumask(next)));
187 
188 		/*
189 		 * Start remote flushes and then read tlb_gen.
190 		 */
191 		cpumask_set_cpu(cpu, mm_cpumask(next));
192 		next_tlb_gen = atomic64_read(&next->context.tlb_gen);
193 
194 		choose_new_asid(next, next_tlb_gen, &new_asid, &need_flush);
195 
196 		if (need_flush) {
197 			this_cpu_write(cpu_tlbstate.ctxs[new_asid].ctx_id, next->context.ctx_id);
198 			this_cpu_write(cpu_tlbstate.ctxs[new_asid].tlb_gen, next_tlb_gen);
199 			write_cr3(__sme_pa(next->pgd) | new_asid);
200 			trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH,
201 					TLB_FLUSH_ALL);
202 		} else {
203 			/* The new ASID is already up to date. */
204 			write_cr3(__sme_pa(next->pgd) | new_asid | CR3_NOFLUSH);
205 			trace_tlb_flush(TLB_FLUSH_ON_TASK_SWITCH, 0);
206 		}
207 
208 		this_cpu_write(cpu_tlbstate.loaded_mm, next);
209 		this_cpu_write(cpu_tlbstate.loaded_mm_asid, new_asid);
210 	}
211 
212 	load_mm_cr4(next);
213 	switch_ldt(real_prev, next);
214 }
215 
216 /*
217  * flush_tlb_func_common()'s memory ordering requirement is that any
218  * TLB fills that happen after we flush the TLB are ordered after we
219  * read active_mm's tlb_gen.  We don't need any explicit barriers
220  * because all x86 flush operations are serializing and the
221  * atomic64_read operation won't be reordered by the compiler.
222  */
223 static void flush_tlb_func_common(const struct flush_tlb_info *f,
224 				  bool local, enum tlb_flush_reason reason)
225 {
226 	/*
227 	 * We have three different tlb_gen values in here.  They are:
228 	 *
229 	 * - mm_tlb_gen:     the latest generation.
230 	 * - local_tlb_gen:  the generation that this CPU has already caught
231 	 *                   up to.
232 	 * - f->new_tlb_gen: the generation that the requester of the flush
233 	 *                   wants us to catch up to.
234 	 */
235 	struct mm_struct *loaded_mm = this_cpu_read(cpu_tlbstate.loaded_mm);
236 	u32 loaded_mm_asid = this_cpu_read(cpu_tlbstate.loaded_mm_asid);
237 	u64 mm_tlb_gen = atomic64_read(&loaded_mm->context.tlb_gen);
238 	u64 local_tlb_gen = this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen);
239 
240 	/* This code cannot presently handle being reentered. */
241 	VM_WARN_ON(!irqs_disabled());
242 
243 	VM_WARN_ON(this_cpu_read(cpu_tlbstate.ctxs[loaded_mm_asid].ctx_id) !=
244 		   loaded_mm->context.ctx_id);
245 
246 	if (!cpumask_test_cpu(smp_processor_id(), mm_cpumask(loaded_mm))) {
247 		/*
248 		 * We're in lazy mode -- don't flush.  We can get here on
249 		 * remote flushes due to races and on local flushes if a
250 		 * kernel thread coincidentally flushes the mm it's lazily
251 		 * still using.
252 		 */
253 		return;
254 	}
255 
256 	if (unlikely(local_tlb_gen == mm_tlb_gen)) {
257 		/*
258 		 * There's nothing to do: we're already up to date.  This can
259 		 * happen if two concurrent flushes happen -- the first flush to
260 		 * be handled can catch us all the way up, leaving no work for
261 		 * the second flush.
262 		 */
263 		trace_tlb_flush(reason, 0);
264 		return;
265 	}
266 
267 	WARN_ON_ONCE(local_tlb_gen > mm_tlb_gen);
268 	WARN_ON_ONCE(f->new_tlb_gen > mm_tlb_gen);
269 
270 	/*
271 	 * If we get to this point, we know that our TLB is out of date.
272 	 * This does not strictly imply that we need to flush (it's
273 	 * possible that f->new_tlb_gen <= local_tlb_gen), but we're
274 	 * going to need to flush in the very near future, so we might
275 	 * as well get it over with.
276 	 *
277 	 * The only question is whether to do a full or partial flush.
278 	 *
279 	 * We do a partial flush if requested and two extra conditions
280 	 * are met:
281 	 *
282 	 * 1. f->new_tlb_gen == local_tlb_gen + 1.  We have an invariant that
283 	 *    we've always done all needed flushes to catch up to
284 	 *    local_tlb_gen.  If, for example, local_tlb_gen == 2 and
285 	 *    f->new_tlb_gen == 3, then we know that the flush needed to bring
286 	 *    us up to date for tlb_gen 3 is the partial flush we're
287 	 *    processing.
288 	 *
289 	 *    As an example of why this check is needed, suppose that there
290 	 *    are two concurrent flushes.  The first is a full flush that
291 	 *    changes context.tlb_gen from 1 to 2.  The second is a partial
292 	 *    flush that changes context.tlb_gen from 2 to 3.  If they get
293 	 *    processed on this CPU in reverse order, we'll see
294 	 *     local_tlb_gen == 1, mm_tlb_gen == 3, and end != TLB_FLUSH_ALL.
295 	 *    If we were to use __flush_tlb_single() and set local_tlb_gen to
296 	 *    3, we'd be break the invariant: we'd update local_tlb_gen above
297 	 *    1 without the full flush that's needed for tlb_gen 2.
298 	 *
299 	 * 2. f->new_tlb_gen == mm_tlb_gen.  This is purely an optimiation.
300 	 *    Partial TLB flushes are not all that much cheaper than full TLB
301 	 *    flushes, so it seems unlikely that it would be a performance win
302 	 *    to do a partial flush if that won't bring our TLB fully up to
303 	 *    date.  By doing a full flush instead, we can increase
304 	 *    local_tlb_gen all the way to mm_tlb_gen and we can probably
305 	 *    avoid another flush in the very near future.
306 	 */
307 	if (f->end != TLB_FLUSH_ALL &&
308 	    f->new_tlb_gen == local_tlb_gen + 1 &&
309 	    f->new_tlb_gen == mm_tlb_gen) {
310 		/* Partial flush */
311 		unsigned long addr;
312 		unsigned long nr_pages = (f->end - f->start) >> PAGE_SHIFT;
313 
314 		addr = f->start;
315 		while (addr < f->end) {
316 			__flush_tlb_single(addr);
317 			addr += PAGE_SIZE;
318 		}
319 		if (local)
320 			count_vm_tlb_events(NR_TLB_LOCAL_FLUSH_ONE, nr_pages);
321 		trace_tlb_flush(reason, nr_pages);
322 	} else {
323 		/* Full flush. */
324 		local_flush_tlb();
325 		if (local)
326 			count_vm_tlb_event(NR_TLB_LOCAL_FLUSH_ALL);
327 		trace_tlb_flush(reason, TLB_FLUSH_ALL);
328 	}
329 
330 	/* Both paths above update our state to mm_tlb_gen. */
331 	this_cpu_write(cpu_tlbstate.ctxs[loaded_mm_asid].tlb_gen, mm_tlb_gen);
332 }
333 
334 static void flush_tlb_func_local(void *info, enum tlb_flush_reason reason)
335 {
336 	const struct flush_tlb_info *f = info;
337 
338 	flush_tlb_func_common(f, true, reason);
339 }
340 
341 static void flush_tlb_func_remote(void *info)
342 {
343 	const struct flush_tlb_info *f = info;
344 
345 	inc_irq_stat(irq_tlb_count);
346 
347 	if (f->mm && f->mm != this_cpu_read(cpu_tlbstate.loaded_mm))
348 		return;
349 
350 	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
351 	flush_tlb_func_common(f, false, TLB_REMOTE_SHOOTDOWN);
352 }
353 
354 void native_flush_tlb_others(const struct cpumask *cpumask,
355 			     const struct flush_tlb_info *info)
356 {
357 	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
358 	if (info->end == TLB_FLUSH_ALL)
359 		trace_tlb_flush(TLB_REMOTE_SEND_IPI, TLB_FLUSH_ALL);
360 	else
361 		trace_tlb_flush(TLB_REMOTE_SEND_IPI,
362 				(info->end - info->start) >> PAGE_SHIFT);
363 
364 	if (is_uv_system()) {
365 		/*
366 		 * This whole special case is confused.  UV has a "Broadcast
367 		 * Assist Unit", which seems to be a fancy way to send IPIs.
368 		 * Back when x86 used an explicit TLB flush IPI, UV was
369 		 * optimized to use its own mechanism.  These days, x86 uses
370 		 * smp_call_function_many(), but UV still uses a manual IPI,
371 		 * and that IPI's action is out of date -- it does a manual
372 		 * flush instead of calling flush_tlb_func_remote().  This
373 		 * means that the percpu tlb_gen variables won't be updated
374 		 * and we'll do pointless flushes on future context switches.
375 		 *
376 		 * Rather than hooking native_flush_tlb_others() here, I think
377 		 * that UV should be updated so that smp_call_function_many(),
378 		 * etc, are optimal on UV.
379 		 */
380 		unsigned int cpu;
381 
382 		cpu = smp_processor_id();
383 		cpumask = uv_flush_tlb_others(cpumask, info);
384 		if (cpumask)
385 			smp_call_function_many(cpumask, flush_tlb_func_remote,
386 					       (void *)info, 1);
387 		return;
388 	}
389 	smp_call_function_many(cpumask, flush_tlb_func_remote,
390 			       (void *)info, 1);
391 }
392 
393 /*
394  * See Documentation/x86/tlb.txt for details.  We choose 33
395  * because it is large enough to cover the vast majority (at
396  * least 95%) of allocations, and is small enough that we are
397  * confident it will not cause too much overhead.  Each single
398  * flush is about 100 ns, so this caps the maximum overhead at
399  * _about_ 3,000 ns.
400  *
401  * This is in units of pages.
402  */
403 static unsigned long tlb_single_page_flush_ceiling __read_mostly = 33;
404 
405 void flush_tlb_mm_range(struct mm_struct *mm, unsigned long start,
406 				unsigned long end, unsigned long vmflag)
407 {
408 	int cpu;
409 
410 	struct flush_tlb_info info = {
411 		.mm = mm,
412 	};
413 
414 	cpu = get_cpu();
415 
416 	/* This is also a barrier that synchronizes with switch_mm(). */
417 	info.new_tlb_gen = inc_mm_tlb_gen(mm);
418 
419 	/* Should we flush just the requested range? */
420 	if ((end != TLB_FLUSH_ALL) &&
421 	    !(vmflag & VM_HUGETLB) &&
422 	    ((end - start) >> PAGE_SHIFT) <= tlb_single_page_flush_ceiling) {
423 		info.start = start;
424 		info.end = end;
425 	} else {
426 		info.start = 0UL;
427 		info.end = TLB_FLUSH_ALL;
428 	}
429 
430 	if (mm == this_cpu_read(cpu_tlbstate.loaded_mm)) {
431 		VM_WARN_ON(irqs_disabled());
432 		local_irq_disable();
433 		flush_tlb_func_local(&info, TLB_LOCAL_MM_SHOOTDOWN);
434 		local_irq_enable();
435 	}
436 
437 	if (cpumask_any_but(mm_cpumask(mm), cpu) < nr_cpu_ids)
438 		flush_tlb_others(mm_cpumask(mm), &info);
439 
440 	put_cpu();
441 }
442 
443 
444 static void do_flush_tlb_all(void *info)
445 {
446 	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH_RECEIVED);
447 	__flush_tlb_all();
448 }
449 
450 void flush_tlb_all(void)
451 {
452 	count_vm_tlb_event(NR_TLB_REMOTE_FLUSH);
453 	on_each_cpu(do_flush_tlb_all, NULL, 1);
454 }
455 
456 static void do_kernel_range_flush(void *info)
457 {
458 	struct flush_tlb_info *f = info;
459 	unsigned long addr;
460 
461 	/* flush range by one by one 'invlpg' */
462 	for (addr = f->start; addr < f->end; addr += PAGE_SIZE)
463 		__flush_tlb_single(addr);
464 }
465 
466 void flush_tlb_kernel_range(unsigned long start, unsigned long end)
467 {
468 
469 	/* Balance as user space task's flush, a bit conservative */
470 	if (end == TLB_FLUSH_ALL ||
471 	    (end - start) > tlb_single_page_flush_ceiling << PAGE_SHIFT) {
472 		on_each_cpu(do_flush_tlb_all, NULL, 1);
473 	} else {
474 		struct flush_tlb_info info;
475 		info.start = start;
476 		info.end = end;
477 		on_each_cpu(do_kernel_range_flush, &info, 1);
478 	}
479 }
480 
481 void arch_tlbbatch_flush(struct arch_tlbflush_unmap_batch *batch)
482 {
483 	struct flush_tlb_info info = {
484 		.mm = NULL,
485 		.start = 0UL,
486 		.end = TLB_FLUSH_ALL,
487 	};
488 
489 	int cpu = get_cpu();
490 
491 	if (cpumask_test_cpu(cpu, &batch->cpumask)) {
492 		VM_WARN_ON(irqs_disabled());
493 		local_irq_disable();
494 		flush_tlb_func_local(&info, TLB_LOCAL_SHOOTDOWN);
495 		local_irq_enable();
496 	}
497 
498 	if (cpumask_any_but(&batch->cpumask, cpu) < nr_cpu_ids)
499 		flush_tlb_others(&batch->cpumask, &info);
500 
501 	cpumask_clear(&batch->cpumask);
502 
503 	put_cpu();
504 }
505 
506 static ssize_t tlbflush_read_file(struct file *file, char __user *user_buf,
507 			     size_t count, loff_t *ppos)
508 {
509 	char buf[32];
510 	unsigned int len;
511 
512 	len = sprintf(buf, "%ld\n", tlb_single_page_flush_ceiling);
513 	return simple_read_from_buffer(user_buf, count, ppos, buf, len);
514 }
515 
516 static ssize_t tlbflush_write_file(struct file *file,
517 		 const char __user *user_buf, size_t count, loff_t *ppos)
518 {
519 	char buf[32];
520 	ssize_t len;
521 	int ceiling;
522 
523 	len = min(count, sizeof(buf) - 1);
524 	if (copy_from_user(buf, user_buf, len))
525 		return -EFAULT;
526 
527 	buf[len] = '\0';
528 	if (kstrtoint(buf, 0, &ceiling))
529 		return -EINVAL;
530 
531 	if (ceiling < 0)
532 		return -EINVAL;
533 
534 	tlb_single_page_flush_ceiling = ceiling;
535 	return count;
536 }
537 
538 static const struct file_operations fops_tlbflush = {
539 	.read = tlbflush_read_file,
540 	.write = tlbflush_write_file,
541 	.llseek = default_llseek,
542 };
543 
544 static int __init create_tlb_single_page_flush_ceiling(void)
545 {
546 	debugfs_create_file("tlb_single_page_flush_ceiling", S_IRUSR | S_IWUSR,
547 			    arch_debugfs_dir, NULL, &fops_tlbflush);
548 	return 0;
549 }
550 late_initcall(create_tlb_single_page_flush_ceiling);
551