xref: /linux/arch/x86/mm/pat/set_memory.c (revision 704340f1cd0dcef829eb62f5b48ae95a2ce17bdf)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2002 Andi Kleen, SuSE Labs.
4  * Thanks to Ben LaHaise for precious feedback.
5  */
6 #include <linux/highmem.h>
7 #include <linux/memblock.h>
8 #include <linux/sched.h>
9 #include <linux/mm.h>
10 #include <linux/interrupt.h>
11 #include <linux/seq_file.h>
12 #include <linux/proc_fs.h>
13 #include <linux/debugfs.h>
14 #include <linux/pfn.h>
15 #include <linux/percpu.h>
16 #include <linux/gfp.h>
17 #include <linux/pci.h>
18 #include <linux/vmalloc.h>
19 #include <linux/libnvdimm.h>
20 #include <linux/vmstat.h>
21 #include <linux/kernel.h>
22 #include <linux/cc_platform.h>
23 #include <linux/set_memory.h>
24 #include <linux/memregion.h>
25 #include <linux/cleanup.h>
26 
27 #include <asm/e820/api.h>
28 #include <asm/processor.h>
29 #include <asm/tlbflush.h>
30 #include <asm/sections.h>
31 #include <asm/setup.h>
32 #include <linux/uaccess.h>
33 #include <asm/pgalloc.h>
34 #include <asm/proto.h>
35 #include <asm/memtype.h>
36 
37 #include "../mm_internal.h"
38 
39 /*
40  * The current flushing context - we pass it instead of 5 arguments:
41  */
42 struct cpa_data {
43 	unsigned long	*vaddr;
44 	pgd_t		*pgd;
45 	pgprot_t	mask_set;
46 	pgprot_t	mask_clr;
47 	unsigned long	numpages;
48 	unsigned long	curpage;
49 	unsigned long	pfn;
50 	unsigned int	flags;
51 	unsigned int	force_split		: 1,
52 			force_static_prot	: 1,
53 			force_flush_all		: 1,
54 			init_mm_read_locked	: 1;
55 	struct page	**pages;
56 };
57 
58 enum cpa_warn {
59 	CPA_CONFLICT,
60 	CPA_PROTECT,
61 	CPA_DETECT,
62 };
63 
64 static const int cpa_warn_level = CPA_PROTECT;
65 
66 /*
67  * Serialize cpa() using cpa_lock so that we don't allow any other cpu, with
68  * stale large tlb entries, to change the page attribute in parallel to some
69  * other cpu splitting a large page entry along with changing the attribute.
70  */
71 static DEFINE_SPINLOCK(cpa_lock);
72 
73 #define CPA_FLUSHTLB		0x01
74 #define CPA_ARRAY		0x02
75 #define CPA_PAGES_ARRAY		0x04
76 #define CPA_NO_CHECK_ALIAS	0x08 /* Do not search for aliases */
77 #define CPA_COLLAPSE		0x10 /* try to collapse large pages */
78 #define CPA_DEBUG_PAGEALLOC	0x20
79 
cachemode2pgprot(enum page_cache_mode pcm)80 static inline pgprot_t cachemode2pgprot(enum page_cache_mode pcm)
81 {
82 	return __pgprot(cachemode2protval(pcm));
83 }
84 
85 #ifdef CONFIG_PROC_FS
86 static unsigned long direct_pages_count[PG_LEVEL_NUM];
87 
update_page_count(int level,unsigned long pages)88 void update_page_count(int level, unsigned long pages)
89 {
90 	/* Protect against CPA */
91 	guard(spinlock)(&pgd_lock);
92 	direct_pages_count[level] += pages;
93 }
94 
split_page_count(int level)95 static void split_page_count(int level)
96 {
97 	if (direct_pages_count[level] == 0)
98 		return;
99 
100 	direct_pages_count[level]--;
101 	if (system_state == SYSTEM_RUNNING) {
102 		if (level == PG_LEVEL_2M)
103 			count_vm_event(DIRECT_MAP_LEVEL2_SPLIT);
104 		else if (level == PG_LEVEL_1G)
105 			count_vm_event(DIRECT_MAP_LEVEL3_SPLIT);
106 	}
107 	direct_pages_count[level - 1] += PTRS_PER_PTE;
108 }
109 
collapse_page_count(int level)110 static void collapse_page_count(int level)
111 {
112 	direct_pages_count[level]++;
113 	if (system_state == SYSTEM_RUNNING) {
114 		if (level == PG_LEVEL_2M)
115 			count_vm_event(DIRECT_MAP_LEVEL2_COLLAPSE);
116 		else if (level == PG_LEVEL_1G)
117 			count_vm_event(DIRECT_MAP_LEVEL3_COLLAPSE);
118 	}
119 	direct_pages_count[level - 1] -= PTRS_PER_PTE;
120 }
121 
arch_report_meminfo(struct seq_file * m)122 void arch_report_meminfo(struct seq_file *m)
123 {
124 	seq_printf(m, "DirectMap4k:    %8lu kB\n",
125 			direct_pages_count[PG_LEVEL_4K] << 2);
126 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
127 	seq_printf(m, "DirectMap2M:    %8lu kB\n",
128 			direct_pages_count[PG_LEVEL_2M] << 11);
129 #else
130 	seq_printf(m, "DirectMap4M:    %8lu kB\n",
131 			direct_pages_count[PG_LEVEL_2M] << 12);
132 #endif
133 	if (direct_gbpages)
134 		seq_printf(m, "DirectMap1G:    %8lu kB\n",
135 			direct_pages_count[PG_LEVEL_1G] << 20);
136 }
137 #else
split_page_count(int level)138 static inline void split_page_count(int level) { }
collapse_page_count(int level)139 static inline void collapse_page_count(int level) { }
140 #endif
141 
142 #ifdef CONFIG_X86_CPA_STATISTICS
143 
144 static unsigned long cpa_1g_checked;
145 static unsigned long cpa_1g_sameprot;
146 static unsigned long cpa_1g_preserved;
147 static unsigned long cpa_2m_checked;
148 static unsigned long cpa_2m_sameprot;
149 static unsigned long cpa_2m_preserved;
150 static unsigned long cpa_4k_install;
151 
cpa_inc_1g_checked(void)152 static inline void cpa_inc_1g_checked(void)
153 {
154 	cpa_1g_checked++;
155 }
156 
cpa_inc_2m_checked(void)157 static inline void cpa_inc_2m_checked(void)
158 {
159 	cpa_2m_checked++;
160 }
161 
cpa_inc_4k_install(void)162 static inline void cpa_inc_4k_install(void)
163 {
164 	data_race(cpa_4k_install++);
165 }
166 
cpa_inc_lp_sameprot(int level)167 static inline void cpa_inc_lp_sameprot(int level)
168 {
169 	if (level == PG_LEVEL_1G)
170 		cpa_1g_sameprot++;
171 	else
172 		cpa_2m_sameprot++;
173 }
174 
cpa_inc_lp_preserved(int level)175 static inline void cpa_inc_lp_preserved(int level)
176 {
177 	if (level == PG_LEVEL_1G)
178 		cpa_1g_preserved++;
179 	else
180 		cpa_2m_preserved++;
181 }
182 
cpastats_show(struct seq_file * m,void * p)183 static int cpastats_show(struct seq_file *m, void *p)
184 {
185 	seq_printf(m, "1G pages checked:     %16lu\n", cpa_1g_checked);
186 	seq_printf(m, "1G pages sameprot:    %16lu\n", cpa_1g_sameprot);
187 	seq_printf(m, "1G pages preserved:   %16lu\n", cpa_1g_preserved);
188 	seq_printf(m, "2M pages checked:     %16lu\n", cpa_2m_checked);
189 	seq_printf(m, "2M pages sameprot:    %16lu\n", cpa_2m_sameprot);
190 	seq_printf(m, "2M pages preserved:   %16lu\n", cpa_2m_preserved);
191 	seq_printf(m, "4K pages set-checked: %16lu\n", cpa_4k_install);
192 	return 0;
193 }
194 
cpastats_open(struct inode * inode,struct file * file)195 static int cpastats_open(struct inode *inode, struct file *file)
196 {
197 	return single_open(file, cpastats_show, NULL);
198 }
199 
200 static const struct file_operations cpastats_fops = {
201 	.open		= cpastats_open,
202 	.read		= seq_read,
203 	.llseek		= seq_lseek,
204 	.release	= single_release,
205 };
206 
cpa_stats_init(void)207 static int __init cpa_stats_init(void)
208 {
209 	debugfs_create_file("cpa_stats", S_IRUSR, arch_debugfs_dir, NULL,
210 			    &cpastats_fops);
211 	return 0;
212 }
213 late_initcall(cpa_stats_init);
214 #else
cpa_inc_1g_checked(void)215 static inline void cpa_inc_1g_checked(void) { }
cpa_inc_2m_checked(void)216 static inline void cpa_inc_2m_checked(void) { }
cpa_inc_4k_install(void)217 static inline void cpa_inc_4k_install(void) { }
cpa_inc_lp_sameprot(int level)218 static inline void cpa_inc_lp_sameprot(int level) { }
cpa_inc_lp_preserved(int level)219 static inline void cpa_inc_lp_preserved(int level) { }
220 #endif
221 
222 
223 static inline int
within(unsigned long addr,unsigned long start,unsigned long end)224 within(unsigned long addr, unsigned long start, unsigned long end)
225 {
226 	return addr >= start && addr < end;
227 }
228 
229 #ifdef CONFIG_X86_64
230 
231 static inline int
within_inclusive(unsigned long addr,unsigned long start,unsigned long end)232 within_inclusive(unsigned long addr, unsigned long start, unsigned long end)
233 {
234 	return addr >= start && addr <= end;
235 }
236 
237 /*
238  * The kernel image is mapped into two places in the virtual address space
239  * (addresses without KASLR, of course):
240  *
241  * 1. The kernel direct map (0xffff880000000000)
242  * 2. The "high kernel map" (0xffffffff81000000)
243  *
244  * We actually execute out of #2. If we get the address of a kernel symbol, it
245  * points to #2, but almost all physical-to-virtual translations point to #1.
246  *
247  * This is so that we can have both a directmap of all physical memory *and*
248  * take full advantage of the limited (s32) immediate addressing range (2G)
249  * of x86_64.
250  *
251  * See Documentation/arch/x86/x86_64/mm.rst for more detail.
252  */
253 
highmap_start_pfn(void)254 static inline unsigned long highmap_start_pfn(void)
255 {
256 	return __pa_symbol(_text) >> PAGE_SHIFT;
257 }
258 
highmap_end_pfn(void)259 static inline unsigned long highmap_end_pfn(void)
260 {
261 	/* Do not reference physical address outside the kernel. */
262 	return __pa_symbol(roundup(_brk_end, PMD_SIZE) - 1) >> PAGE_SHIFT;
263 }
264 
__cpa_pfn_in_highmap(unsigned long pfn)265 static bool __cpa_pfn_in_highmap(unsigned long pfn)
266 {
267 	/*
268 	 * Kernel text has an alias mapping at a high address, known
269 	 * here as "highmap".
270 	 */
271 	return within_inclusive(pfn, highmap_start_pfn(), highmap_end_pfn());
272 }
273 
274 #else
275 
__cpa_pfn_in_highmap(unsigned long pfn)276 static bool __cpa_pfn_in_highmap(unsigned long pfn)
277 {
278 	/* There is no highmap on 32-bit */
279 	return false;
280 }
281 
282 #endif
283 
284 /*
285  * See set_mce_nospec().
286  *
287  * Machine check recovery code needs to change cache mode of poisoned pages to
288  * UC to avoid speculative access logging another error. But passing the
289  * address of the 1:1 mapping to set_memory_uc() is a fine way to encourage a
290  * speculative access. So we cheat and flip the top bit of the address. This
291  * works fine for the code that updates the page tables. But at the end of the
292  * process we need to flush the TLB and cache and the non-canonical address
293  * causes a #GP fault when used by the INVLPG and CLFLUSH instructions.
294  *
295  * But in the common case we already have a canonical address. This code
296  * will fix the top bit if needed and is a no-op otherwise.
297  */
fix_addr(unsigned long addr)298 static inline unsigned long fix_addr(unsigned long addr)
299 {
300 #ifdef CONFIG_X86_64
301 	return (long)(addr << 1) >> 1;
302 #else
303 	return addr;
304 #endif
305 }
306 
__cpa_addr(struct cpa_data * cpa,unsigned long idx)307 static unsigned long __cpa_addr(struct cpa_data *cpa, unsigned long idx)
308 {
309 	if (cpa->flags & CPA_PAGES_ARRAY) {
310 		struct page *page = cpa->pages[idx];
311 
312 		if (unlikely(PageHighMem(page)))
313 			return 0;
314 
315 		return (unsigned long)page_address(page);
316 	}
317 
318 	if (cpa->flags & CPA_ARRAY)
319 		return cpa->vaddr[idx];
320 
321 	return *cpa->vaddr + idx * PAGE_SIZE;
322 }
323 
324 /*
325  * Flushing functions
326  */
327 
clflush_cache_range_opt(void * vaddr,unsigned int size)328 static void clflush_cache_range_opt(void *vaddr, unsigned int size)
329 {
330 	const unsigned long clflush_size = boot_cpu_data.x86_clflush_size;
331 	void *p = (void *)((unsigned long)vaddr & ~(clflush_size - 1));
332 	void *vend = vaddr + size;
333 
334 	if (p >= vend)
335 		return;
336 
337 	for (; p < vend; p += clflush_size)
338 		clflushopt(p);
339 }
340 
341 /**
342  * clflush_cache_range - flush a cache range with clflush
343  * @vaddr:	virtual start address
344  * @size:	number of bytes to flush
345  *
346  * CLFLUSHOPT is an unordered instruction which needs fencing with MFENCE or
347  * SFENCE to avoid ordering issues.
348  */
clflush_cache_range(void * vaddr,unsigned int size)349 void clflush_cache_range(void *vaddr, unsigned int size)
350 {
351 	mb();
352 	clflush_cache_range_opt(vaddr, size);
353 	mb();
354 }
355 EXPORT_SYMBOL_GPL(clflush_cache_range);
356 
357 #ifdef CONFIG_ARCH_HAS_PMEM_API
arch_invalidate_pmem(void * addr,size_t size)358 void arch_invalidate_pmem(void *addr, size_t size)
359 {
360 	clflush_cache_range(addr, size);
361 }
362 EXPORT_SYMBOL_GPL(arch_invalidate_pmem);
363 #endif
364 
365 #ifdef CONFIG_ARCH_HAS_CPU_CACHE_INVALIDATE_MEMREGION
cpu_cache_has_invalidate_memregion(void)366 bool cpu_cache_has_invalidate_memregion(void)
367 {
368 	return !cpu_feature_enabled(X86_FEATURE_HYPERVISOR);
369 }
370 EXPORT_SYMBOL_NS_GPL(cpu_cache_has_invalidate_memregion, "DEVMEM");
371 
cpu_cache_invalidate_memregion(phys_addr_t start,size_t len)372 int cpu_cache_invalidate_memregion(phys_addr_t start, size_t len)
373 {
374 	if (WARN_ON_ONCE(!cpu_cache_has_invalidate_memregion()))
375 		return -ENXIO;
376 	wbinvd_on_all_cpus();
377 	return 0;
378 }
379 EXPORT_SYMBOL_NS_GPL(cpu_cache_invalidate_memregion, "DEVMEM");
380 #endif
381 
__cpa_flush_all(void * arg)382 static void __cpa_flush_all(void *arg)
383 {
384 	unsigned long cache = (unsigned long)arg;
385 
386 	/*
387 	 * Flush all to work around Errata in early athlons regarding
388 	 * large page flushing.
389 	 */
390 	__flush_tlb_all();
391 
392 	if (cache && boot_cpu_data.x86 >= 4)
393 		wbinvd();
394 }
395 
cpa_flush_all(unsigned long cache)396 static void cpa_flush_all(unsigned long cache)
397 {
398 	BUG_ON(irqs_disabled() && !early_boot_irqs_disabled);
399 
400 	on_each_cpu(__cpa_flush_all, (void *) cache, 1);
401 }
402 
__cpa_flush_tlb(void * data)403 static void __cpa_flush_tlb(void *data)
404 {
405 	struct cpa_data *cpa = data;
406 	unsigned int i;
407 
408 	for (i = 0; i < cpa->numpages; i++)
409 		flush_tlb_one_kernel(fix_addr(__cpa_addr(cpa, i)));
410 }
411 
412 static int collapse_large_pages(unsigned long addr, struct list_head *pgtables);
413 
__cpa_collapse_large_pages(struct cpa_data * cpa)414 static void __cpa_collapse_large_pages(struct cpa_data *cpa)
415 {
416 	unsigned long start, addr, end;
417 	struct ptdesc *ptdesc, *tmp;
418 	LIST_HEAD(pgtables);
419 	int collapsed = 0;
420 	int i;
421 
422 	guard(spinlock)(&cpa_lock);
423 
424 	if (cpa->flags & (CPA_PAGES_ARRAY | CPA_ARRAY)) {
425 		for (i = 0; i < cpa->numpages; i++)
426 			collapsed += collapse_large_pages(__cpa_addr(cpa, i),
427 							  &pgtables);
428 	} else {
429 		addr = __cpa_addr(cpa, 0);
430 		start = addr & PMD_MASK;
431 		end = addr + PAGE_SIZE * cpa->numpages;
432 
433 		for (addr = start; within(addr, start, end); addr += PMD_SIZE)
434 			collapsed += collapse_large_pages(addr, &pgtables);
435 	}
436 
437 	if (!collapsed)
438 		return;
439 
440 	flush_tlb_all();
441 
442 	list_for_each_entry_safe(ptdesc, tmp, &pgtables, pt_list) {
443 		list_del(&ptdesc->pt_list);
444 		/*
445 		 * Only early alloc'd direct map should not be flagged PG_table
446 		 * here and those shouldn't be collapsed. However be abundantly
447 		 * cautious and handle the !PG_table case too.
448 		 */
449 		if (PageTable((ptdesc_page(ptdesc))))
450 			pagetable_dtor_free(ptdesc);
451 		else
452 			pagetable_free(ptdesc);
453 	}
454 }
455 
cpa_collapse_large_pages(struct cpa_data * cpa)456 static void cpa_collapse_large_pages(struct cpa_data *cpa)
457 {
458 	/*
459 	 * Take the mmap write lock on init_mm to:
460 	 * - Avoid a use-after-free if raced by ptdump (which takes its own
461 	 *   write lock on init_mm).
462 	 * - Serialise concurrent CPA walkers.
463 	 */
464 	scoped_guard(mmap_write_lock, &init_mm)
465 		__cpa_collapse_large_pages(cpa);
466 }
467 
cpa_flush(struct cpa_data * cpa,int cache)468 static void cpa_flush(struct cpa_data *cpa, int cache)
469 {
470 	unsigned int i;
471 
472 	BUG_ON(irqs_disabled() && !early_boot_irqs_disabled);
473 
474 	if (cache && !cpu_feature_enabled(X86_FEATURE_CLFLUSH)) {
475 		cpa_flush_all(cache);
476 		goto collapse_large_pages;
477 	}
478 
479 	if (cpa->force_flush_all || cpa->numpages > tlb_single_page_flush_ceiling)
480 		flush_tlb_all();
481 	else
482 		on_each_cpu(__cpa_flush_tlb, cpa, 1);
483 
484 	if (!cache)
485 		goto collapse_large_pages;
486 
487 	mb();
488 	for (i = 0; i < cpa->numpages; i++) {
489 		unsigned long addr = __cpa_addr(cpa, i);
490 		unsigned int level;
491 
492 		pte_t *pte = lookup_address(addr, &level);
493 
494 		/*
495 		 * Only flush present addresses:
496 		 */
497 		if (pte && (pte_val(*pte) & _PAGE_PRESENT))
498 			clflush_cache_range_opt((void *)fix_addr(addr), PAGE_SIZE);
499 	}
500 	mb();
501 
502 collapse_large_pages:
503 	if (cpa->flags & CPA_COLLAPSE)
504 		cpa_collapse_large_pages(cpa);
505 }
506 
overlaps(unsigned long r1_start,unsigned long r1_end,unsigned long r2_start,unsigned long r2_end)507 static bool overlaps(unsigned long r1_start, unsigned long r1_end,
508 		     unsigned long r2_start, unsigned long r2_end)
509 {
510 	return (r1_start <= r2_end && r1_end >= r2_start) ||
511 		(r2_start <= r1_end && r2_end >= r1_start);
512 }
513 
514 #ifdef CONFIG_PCI_BIOS
515 /*
516  * The BIOS area between 640k and 1Mb needs to be executable for PCI BIOS
517  * based config access (CONFIG_PCI_GOBIOS) support.
518  */
519 #define BIOS_PFN	PFN_DOWN(BIOS_BEGIN)
520 #define BIOS_PFN_END	PFN_DOWN(BIOS_END - 1)
521 
protect_pci_bios(unsigned long spfn,unsigned long epfn)522 static pgprotval_t protect_pci_bios(unsigned long spfn, unsigned long epfn)
523 {
524 	if (pcibios_enabled && overlaps(spfn, epfn, BIOS_PFN, BIOS_PFN_END))
525 		return _PAGE_NX;
526 	return 0;
527 }
528 #else
protect_pci_bios(unsigned long spfn,unsigned long epfn)529 static pgprotval_t protect_pci_bios(unsigned long spfn, unsigned long epfn)
530 {
531 	return 0;
532 }
533 #endif
534 
535 /*
536  * The .rodata section needs to be read-only. Using the pfn catches all
537  * aliases.  This also includes __ro_after_init, so do not enforce until
538  * kernel_set_to_readonly is true.
539  */
protect_rodata(unsigned long spfn,unsigned long epfn)540 static pgprotval_t protect_rodata(unsigned long spfn, unsigned long epfn)
541 {
542 	unsigned long epfn_ro, spfn_ro = PFN_DOWN(__pa_symbol(__start_rodata));
543 
544 	/*
545 	 * Note: __end_rodata is at page aligned and not inclusive, so
546 	 * subtract 1 to get the last enforced PFN in the rodata area.
547 	 */
548 	epfn_ro = PFN_DOWN(__pa_symbol(__end_rodata)) - 1;
549 
550 	if (kernel_set_to_readonly && overlaps(spfn, epfn, spfn_ro, epfn_ro))
551 		return _PAGE_RW;
552 	return 0;
553 }
554 
555 /*
556  * Protect kernel text against becoming non executable by forbidding
557  * _PAGE_NX.  This protects only the high kernel mapping (_text -> _etext)
558  * out of which the kernel actually executes.  Do not protect the low
559  * mapping.
560  *
561  * This does not cover __inittext since that is gone after boot.
562  */
protect_kernel_text(unsigned long start,unsigned long end)563 static pgprotval_t protect_kernel_text(unsigned long start, unsigned long end)
564 {
565 	unsigned long t_end = (unsigned long)_etext - 1;
566 	unsigned long t_start = (unsigned long)_text;
567 
568 	if (overlaps(start, end, t_start, t_end))
569 		return _PAGE_NX;
570 	return 0;
571 }
572 
573 #if defined(CONFIG_X86_64)
574 /*
575  * Once the kernel maps the text as RO (kernel_set_to_readonly is set),
576  * kernel text mappings for the large page aligned text, rodata sections
577  * will be always read-only. For the kernel identity mappings covering the
578  * holes caused by this alignment can be anything that user asks.
579  *
580  * This will preserve the large page mappings for kernel text/data at no
581  * extra cost.
582  */
protect_kernel_text_ro(unsigned long start,unsigned long end)583 static pgprotval_t protect_kernel_text_ro(unsigned long start,
584 					  unsigned long end)
585 {
586 	unsigned long t_end = (unsigned long)__end_rodata_hpage_align - 1;
587 	unsigned long t_start = (unsigned long)_text;
588 	unsigned int level;
589 
590 	if (!kernel_set_to_readonly || !overlaps(start, end, t_start, t_end))
591 		return 0;
592 	/*
593 	 * Don't enforce the !RW mapping for the kernel text mapping, if
594 	 * the current mapping is already using small page mapping.  No
595 	 * need to work hard to preserve large page mappings in this case.
596 	 *
597 	 * This also fixes the Linux Xen paravirt guest boot failure caused
598 	 * by unexpected read-only mappings for kernel identity
599 	 * mappings. In this paravirt guest case, the kernel text mapping
600 	 * and the kernel identity mapping share the same page-table pages,
601 	 * so the protections for kernel text and identity mappings have to
602 	 * be the same.
603 	 */
604 	if (lookup_address(start, &level) && (level != PG_LEVEL_4K))
605 		return _PAGE_RW;
606 	return 0;
607 }
608 #else
protect_kernel_text_ro(unsigned long start,unsigned long end)609 static pgprotval_t protect_kernel_text_ro(unsigned long start,
610 					  unsigned long end)
611 {
612 	return 0;
613 }
614 #endif
615 
conflicts(pgprot_t prot,pgprotval_t val)616 static inline bool conflicts(pgprot_t prot, pgprotval_t val)
617 {
618 	return (pgprot_val(prot) & ~val) != pgprot_val(prot);
619 }
620 
check_conflict(int warnlvl,pgprot_t prot,pgprotval_t val,unsigned long start,unsigned long end,unsigned long pfn,const char * txt)621 static inline void check_conflict(int warnlvl, pgprot_t prot, pgprotval_t val,
622 				  unsigned long start, unsigned long end,
623 				  unsigned long pfn, const char *txt)
624 {
625 	static const char *lvltxt[] = {
626 		[CPA_CONFLICT]	= "conflict",
627 		[CPA_PROTECT]	= "protect",
628 		[CPA_DETECT]	= "detect",
629 	};
630 
631 	if (warnlvl > cpa_warn_level || !conflicts(prot, val))
632 		return;
633 
634 	pr_warn("CPA %8s %10s: 0x%016lx - 0x%016lx PFN %lx req %016llx prevent %016llx\n",
635 		lvltxt[warnlvl], txt, start, end, pfn, (unsigned long long)pgprot_val(prot),
636 		(unsigned long long)val);
637 }
638 
639 /*
640  * Certain areas of memory on x86 require very specific protection flags,
641  * for example the BIOS area or kernel text. Callers don't always get this
642  * right (again, ioremap() on BIOS memory is not uncommon) so this function
643  * checks and fixes these known static required protection bits.
644  */
static_protections(pgprot_t prot,unsigned long start,unsigned long pfn,unsigned long npg,unsigned long lpsize,int warnlvl)645 static inline pgprot_t static_protections(pgprot_t prot, unsigned long start,
646 					  unsigned long pfn, unsigned long npg,
647 					  unsigned long lpsize, int warnlvl)
648 {
649 	pgprotval_t forbidden, res;
650 	unsigned long end;
651 
652 	/*
653 	 * There is no point in checking RW/NX conflicts when the requested
654 	 * mapping is setting the page !PRESENT.
655 	 */
656 	if (!(pgprot_val(prot) & _PAGE_PRESENT))
657 		return prot;
658 
659 	/* Operate on the virtual address */
660 	end = start + npg * PAGE_SIZE - 1;
661 
662 	res = protect_kernel_text(start, end);
663 	check_conflict(warnlvl, prot, res, start, end, pfn, "Text NX");
664 	forbidden = res;
665 
666 	/*
667 	 * Special case to preserve a large page. If the change spawns the
668 	 * full large page mapping then there is no point to split it
669 	 * up. Happens with ftrace and is going to be removed once ftrace
670 	 * switched to text_poke().
671 	 */
672 	if (lpsize != (npg * PAGE_SIZE) || (start & (lpsize - 1))) {
673 		res = protect_kernel_text_ro(start, end);
674 		check_conflict(warnlvl, prot, res, start, end, pfn, "Text RO");
675 		forbidden |= res;
676 	}
677 
678 	/* Check the PFN directly */
679 	res = protect_pci_bios(pfn, pfn + npg - 1);
680 	check_conflict(warnlvl, prot, res, start, end, pfn, "PCIBIOS NX");
681 	forbidden |= res;
682 
683 	res = protect_rodata(pfn, pfn + npg - 1);
684 	check_conflict(warnlvl, prot, res, start, end, pfn, "Rodata RO");
685 	forbidden |= res;
686 
687 	return __pgprot(pgprot_val(prot) & ~forbidden);
688 }
689 
690 /*
691  * Validate strict W^X semantics.
692  */
verify_rwx(pgprot_t old,pgprot_t new,unsigned long start,unsigned long pfn,unsigned long npg,bool nx,bool rw)693 static inline pgprot_t verify_rwx(pgprot_t old, pgprot_t new, unsigned long start,
694 				  unsigned long pfn, unsigned long npg,
695 				  bool nx, bool rw)
696 {
697 	unsigned long end;
698 
699 	/*
700 	 * 32-bit has some unfixable W+X issues, like EFI code
701 	 * and writeable data being in the same page.  Disable
702 	 * detection and enforcement there.
703 	 */
704 	if (IS_ENABLED(CONFIG_X86_32))
705 		return new;
706 
707 	/* Only verify when NX is supported: */
708 	if (!(__supported_pte_mask & _PAGE_NX))
709 		return new;
710 
711 	if (!((pgprot_val(old) ^ pgprot_val(new)) & (_PAGE_RW | _PAGE_NX)))
712 		return new;
713 
714 	if ((pgprot_val(new) & (_PAGE_RW | _PAGE_NX)) != _PAGE_RW)
715 		return new;
716 
717 	/* Non-leaf translation entries can disable writing or execution. */
718 	if (!rw || nx)
719 		return new;
720 
721 	end = start + npg * PAGE_SIZE - 1;
722 	WARN_ONCE(1, "CPA detected W^X violation: %016llx -> %016llx range: 0x%016lx - 0x%016lx PFN %lx\n",
723 		  (unsigned long long)pgprot_val(old),
724 		  (unsigned long long)pgprot_val(new),
725 		  start, end, pfn);
726 
727 	/*
728 	 * For now, allow all permission change attempts by returning the
729 	 * attempted permissions.  This can 'return old' to actively
730 	 * refuse the permission change at a later time.
731 	 */
732 	return new;
733 }
734 
735 /*
736  * Lookup the page table entry for a virtual address in a specific pgd.
737  * Return a pointer to the entry (or NULL if the entry does not exist),
738  * the level of the entry, and the effective NX and RW bits of all
739  * page table levels.
740  */
lookup_address_in_pgd_attr(pgd_t * pgd,unsigned long address,unsigned int * level,bool * nx,bool * rw)741 pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address,
742 				  unsigned int *level, bool *nx, bool *rw)
743 {
744 	p4d_t *p4d;
745 	pud_t *pud;
746 	pmd_t *pmd;
747 
748 	*level = PG_LEVEL_256T;
749 	*nx = false;
750 	*rw = true;
751 
752 	if (pgd_none(*pgd))
753 		return NULL;
754 
755 	*level = PG_LEVEL_512G;
756 	*nx |= pgd_flags(*pgd) & _PAGE_NX;
757 	*rw &= pgd_flags(*pgd) & _PAGE_RW;
758 
759 	p4d = p4d_offset(pgd, address);
760 	if (p4d_none(*p4d))
761 		return NULL;
762 
763 	if (p4d_leaf(*p4d) || !p4d_present(*p4d))
764 		return (pte_t *)p4d;
765 
766 	*level = PG_LEVEL_1G;
767 	*nx |= p4d_flags(*p4d) & _PAGE_NX;
768 	*rw &= p4d_flags(*p4d) & _PAGE_RW;
769 
770 	pud = pud_offset(p4d, address);
771 	if (pud_none(*pud))
772 		return NULL;
773 
774 	if (pud_leaf(*pud) || !pud_present(*pud))
775 		return (pte_t *)pud;
776 
777 	*level = PG_LEVEL_2M;
778 	*nx |= pud_flags(*pud) & _PAGE_NX;
779 	*rw &= pud_flags(*pud) & _PAGE_RW;
780 
781 	pmd = pmd_offset(pud, address);
782 	if (pmd_none(*pmd))
783 		return NULL;
784 
785 	if (pmd_leaf(*pmd) || !pmd_present(*pmd))
786 		return (pte_t *)pmd;
787 
788 	*level = PG_LEVEL_4K;
789 	*nx |= pmd_flags(*pmd) & _PAGE_NX;
790 	*rw &= pmd_flags(*pmd) & _PAGE_RW;
791 
792 	return pte_offset_kernel(pmd, address);
793 }
794 
795 /*
796  * Lookup the page table entry for a virtual address in a specific pgd.
797  * Return a pointer to the entry and the level of the mapping.
798  */
lookup_address_in_pgd(pgd_t * pgd,unsigned long address,unsigned int * level)799 pte_t *lookup_address_in_pgd(pgd_t *pgd, unsigned long address,
800 			     unsigned int *level)
801 {
802 	bool nx, rw;
803 
804 	return lookup_address_in_pgd_attr(pgd, address, level, &nx, &rw);
805 }
806 
807 /*
808  * Lookup the page table entry for a virtual address. Return a pointer
809  * to the entry and the level of the mapping.
810  *
811  * Note: the function returns p4d, pud or pmd either when the entry is marked
812  * large or when the present bit is not set. Otherwise it returns NULL.
813  */
lookup_address(unsigned long address,unsigned int * level)814 pte_t *lookup_address(unsigned long address, unsigned int *level)
815 {
816 	return lookup_address_in_pgd(pgd_offset_k(address), address, level);
817 }
818 EXPORT_SYMBOL_GPL(lookup_address);
819 
_lookup_address_cpa(struct cpa_data * cpa,unsigned long address,unsigned int * level,bool * nx,bool * rw)820 static pte_t *_lookup_address_cpa(struct cpa_data *cpa, unsigned long address,
821 				  unsigned int *level, bool *nx, bool *rw)
822 {
823 	pgd_t *pgd;
824 
825 	if (!cpa->pgd)
826 		pgd = pgd_offset_k(address);
827 	else
828 		pgd = cpa->pgd + pgd_index(address);
829 
830 	return lookup_address_in_pgd_attr(pgd, address, level, nx, rw);
831 }
832 
833 /*
834  * Lookup the PMD entry for a virtual address. Return a pointer to the entry
835  * or NULL if not present.
836  */
lookup_pmd_address(unsigned long address)837 pmd_t *lookup_pmd_address(unsigned long address)
838 {
839 	pgd_t *pgd;
840 	p4d_t *p4d;
841 	pud_t *pud;
842 
843 	pgd = pgd_offset_k(address);
844 	if (pgd_none(*pgd))
845 		return NULL;
846 
847 	p4d = p4d_offset(pgd, address);
848 	if (p4d_none(*p4d) || p4d_leaf(*p4d) || !p4d_present(*p4d))
849 		return NULL;
850 
851 	pud = pud_offset(p4d, address);
852 	if (pud_none(*pud) || pud_leaf(*pud) || !pud_present(*pud))
853 		return NULL;
854 
855 	return pmd_offset(pud, address);
856 }
857 
858 /*
859  * This is necessary because __pa() does not work on some
860  * kinds of memory, like vmalloc() or the alloc_remap()
861  * areas on 32-bit NUMA systems.  The percpu areas can
862  * end up in this kind of memory, for instance.
863  *
864  * Note that as long as the PTEs are well-formed with correct PFNs, this
865  * works without checking the PRESENT bit in the leaf PTE.  This is unlike
866  * the similar vmalloc_to_page() and derivatives.  Callers may depend on
867  * this behavior.
868  *
869  * This could be optimized, but it is only used in paths that are not perf
870  * sensitive, and keeping it unoptimized should increase the testing coverage
871  * for the more obscure platforms.
872  */
slow_virt_to_phys(void * __virt_addr)873 phys_addr_t slow_virt_to_phys(void *__virt_addr)
874 {
875 	unsigned long virt_addr = (unsigned long)__virt_addr;
876 	phys_addr_t phys_addr;
877 	unsigned long offset;
878 	enum pg_level level;
879 	pte_t *pte;
880 
881 	pte = lookup_address(virt_addr, &level);
882 	BUG_ON(!pte);
883 
884 	/*
885 	 * pXX_pfn() returns unsigned long, which must be cast to phys_addr_t
886 	 * before being left-shifted PAGE_SHIFT bits -- this trick is to
887 	 * make 32-PAE kernel work correctly.
888 	 */
889 	switch (level) {
890 	case PG_LEVEL_1G:
891 		phys_addr = (phys_addr_t)pud_pfn(*(pud_t *)pte) << PAGE_SHIFT;
892 		offset = virt_addr & ~PUD_MASK;
893 		break;
894 	case PG_LEVEL_2M:
895 		phys_addr = (phys_addr_t)pmd_pfn(*(pmd_t *)pte) << PAGE_SHIFT;
896 		offset = virt_addr & ~PMD_MASK;
897 		break;
898 	default:
899 		phys_addr = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
900 		offset = virt_addr & ~PAGE_MASK;
901 	}
902 
903 	return (phys_addr_t)(phys_addr | offset);
904 }
905 EXPORT_SYMBOL_GPL(slow_virt_to_phys);
906 
907 /*
908  * Set the new pmd in all the pgds we know about:
909  */
__set_pmd_pte(pte_t * kpte,unsigned long address,pte_t pte)910 static void __set_pmd_pte(pte_t *kpte, unsigned long address, pte_t pte)
911 {
912 	/* change init_mm */
913 	set_pte_atomic(kpte, pte);
914 
915 	if (IS_ENABLED(CONFIG_X86_32)) {
916 		struct ptdesc *ptdesc;
917 
918 		list_for_each_entry(ptdesc, &pgd_list, pt_list) {
919 			pgd_t *pgd;
920 			p4d_t *p4d;
921 			pud_t *pud;
922 			pmd_t *pmd;
923 
924 			pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(address);
925 			p4d = p4d_offset(pgd, address);
926 			pud = pud_offset(p4d, address);
927 			pmd = pmd_offset(pud, address);
928 			set_pte_atomic((pte_t *)pmd, pte);
929 		}
930 	}
931 }
932 
pgprot_clear_protnone_bits(pgprot_t prot)933 static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
934 {
935 	/*
936 	 * _PAGE_GLOBAL means "global page" for present PTEs.
937 	 * But, it is also used to indicate _PAGE_PROTNONE
938 	 * for non-present PTEs.
939 	 *
940 	 * This ensures that a _PAGE_GLOBAL PTE going from
941 	 * present to non-present is not confused as
942 	 * _PAGE_PROTNONE.
943 	 */
944 	if (!(pgprot_val(prot) & _PAGE_PRESENT))
945 		pgprot_val(prot) &= ~_PAGE_GLOBAL;
946 
947 	return prot;
948 }
949 
__should_split_large_page(pte_t * kpte,unsigned long address,struct cpa_data * cpa)950 static int __should_split_large_page(pte_t *kpte, unsigned long address,
951 				     struct cpa_data *cpa)
952 {
953 	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
954 	pgprot_t old_prot, new_prot, req_prot, chk_prot;
955 	pte_t new_pte, *tmp;
956 	enum pg_level level;
957 	bool nx, rw;
958 
959 	/*
960 	 * Check for races, another CPU might have split this page
961 	 * up already:
962 	 */
963 	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
964 	if (tmp != kpte)
965 		return 1;
966 
967 	switch (level) {
968 	case PG_LEVEL_2M:
969 		old_prot = pmd_pgprot(*(pmd_t *)kpte);
970 		old_pfn = pmd_pfn(*(pmd_t *)kpte);
971 		cpa_inc_2m_checked();
972 		break;
973 	case PG_LEVEL_1G:
974 		old_prot = pud_pgprot(*(pud_t *)kpte);
975 		old_pfn = pud_pfn(*(pud_t *)kpte);
976 		cpa_inc_1g_checked();
977 		break;
978 	default:
979 		return -EINVAL;
980 	}
981 
982 	psize = page_level_size(level);
983 	pmask = page_level_mask(level);
984 
985 	/*
986 	 * Calculate the number of pages, which fit into this large
987 	 * page starting at address:
988 	 */
989 	lpaddr = (address + psize) & pmask;
990 	numpages = (lpaddr - address) >> PAGE_SHIFT;
991 	if (numpages < cpa->numpages)
992 		cpa->numpages = numpages;
993 
994 	/*
995 	 * We are safe now. Check whether the new pgprot is the same:
996 	 * Convert protection attributes to 4k-format, as cpa->mask* are set
997 	 * up accordingly.
998 	 */
999 
1000 	/* Clear PSE (aka _PAGE_PAT) and move PAT bit to correct position */
1001 	req_prot = pgprot_large_2_4k(old_prot);
1002 
1003 	pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
1004 	pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
1005 
1006 	/*
1007 	 * req_prot is in format of 4k pages. It must be converted to large
1008 	 * page format: the caching mode includes the PAT bit located at
1009 	 * different bit positions in the two formats.
1010 	 */
1011 	req_prot = pgprot_4k_2_large(req_prot);
1012 	req_prot = pgprot_clear_protnone_bits(req_prot);
1013 	if (pgprot_val(req_prot) & _PAGE_PRESENT)
1014 		pgprot_val(req_prot) |= _PAGE_PSE;
1015 
1016 	/*
1017 	 * old_pfn points to the large page base pfn. So we need to add the
1018 	 * offset of the virtual address:
1019 	 */
1020 	pfn = old_pfn + ((address & (psize - 1)) >> PAGE_SHIFT);
1021 	cpa->pfn = pfn;
1022 
1023 	/*
1024 	 * Calculate the large page base address and the number of 4K pages
1025 	 * in the large page
1026 	 */
1027 	lpaddr = address & pmask;
1028 	numpages = psize >> PAGE_SHIFT;
1029 
1030 	/*
1031 	 * Sanity check that the existing mapping is correct versus the static
1032 	 * protections. static_protections() guards against !PRESENT, so no
1033 	 * extra conditional required here.
1034 	 */
1035 	chk_prot = static_protections(old_prot, lpaddr, old_pfn, numpages,
1036 				      psize, CPA_CONFLICT);
1037 
1038 	if (WARN_ON_ONCE(pgprot_val(chk_prot) != pgprot_val(old_prot))) {
1039 		/*
1040 		 * Split the large page and tell the split code to
1041 		 * enforce static protections.
1042 		 */
1043 		cpa->force_static_prot = 1;
1044 		return 1;
1045 	}
1046 
1047 	/*
1048 	 * Optimization: If the requested pgprot is the same as the current
1049 	 * pgprot, then the large page can be preserved and no updates are
1050 	 * required independent of alignment and length of the requested
1051 	 * range. The above already established that the current pgprot is
1052 	 * correct, which in consequence makes the requested pgprot correct
1053 	 * as well if it is the same. The static protection scan below will
1054 	 * not come to a different conclusion.
1055 	 */
1056 	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
1057 		cpa_inc_lp_sameprot(level);
1058 		return 0;
1059 	}
1060 
1061 	/*
1062 	 * If the requested range does not cover the full page, split it up
1063 	 */
1064 	if (address != lpaddr || cpa->numpages != numpages)
1065 		return 1;
1066 
1067 	/*
1068 	 * Check whether the requested pgprot is conflicting with a static
1069 	 * protection requirement in the large page.
1070 	 */
1071 	new_prot = static_protections(req_prot, lpaddr, old_pfn, numpages,
1072 				      psize, CPA_DETECT);
1073 
1074 	new_prot = verify_rwx(old_prot, new_prot, lpaddr, old_pfn, numpages,
1075 			      nx, rw);
1076 
1077 	/*
1078 	 * If there is a conflict, split the large page.
1079 	 *
1080 	 * There used to be a 4k wise evaluation trying really hard to
1081 	 * preserve the large pages, but experimentation has shown, that this
1082 	 * does not help at all. There might be corner cases which would
1083 	 * preserve one large page occasionally, but it's really not worth the
1084 	 * extra code and cycles for the common case.
1085 	 */
1086 	if (pgprot_val(req_prot) != pgprot_val(new_prot))
1087 		return 1;
1088 
1089 	/* All checks passed. Update the large page mapping. */
1090 	new_pte = pfn_pte(old_pfn, new_prot);
1091 	__set_pmd_pte(kpte, address, new_pte);
1092 	cpa->flags |= CPA_FLUSHTLB;
1093 	cpa_inc_lp_preserved(level);
1094 	return 0;
1095 }
1096 
should_split_large_page(pte_t * kpte,unsigned long address,struct cpa_data * cpa)1097 static int should_split_large_page(pte_t *kpte, unsigned long address,
1098 				   struct cpa_data *cpa)
1099 {
1100 	if (cpa->force_split)
1101 		return 1;
1102 
1103 	guard(spinlock)(&pgd_lock);
1104 	return __should_split_large_page(kpte, address, cpa);
1105 }
1106 
split_set_pte(struct cpa_data * cpa,pte_t * pte,unsigned long pfn,pgprot_t ref_prot,unsigned long address,unsigned long size)1107 static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
1108 			  pgprot_t ref_prot, unsigned long address,
1109 			  unsigned long size)
1110 {
1111 	unsigned int npg = PFN_DOWN(size);
1112 	pgprot_t prot;
1113 
1114 	/*
1115 	 * If should_split_large_page() discovered an inconsistent mapping,
1116 	 * remove the invalid protection in the split mapping.
1117 	 */
1118 	if (!cpa->force_static_prot)
1119 		goto set;
1120 
1121 	/* Hand in lpsize = 0 to enforce the protection mechanism */
1122 	prot = static_protections(ref_prot, address, pfn, npg, 0, CPA_PROTECT);
1123 
1124 	if (pgprot_val(prot) == pgprot_val(ref_prot))
1125 		goto set;
1126 
1127 	/*
1128 	 * If this is splitting a PMD, fix it up. PUD splits cannot be
1129 	 * fixed trivially as that would require to rescan the newly
1130 	 * installed PMD mappings after returning from split_large_page()
1131 	 * so an eventual further split can allocate the necessary PTE
1132 	 * pages. Warn for now and revisit it in case this actually
1133 	 * happens.
1134 	 */
1135 	if (size == PAGE_SIZE)
1136 		ref_prot = prot;
1137 	else
1138 		pr_warn_once("CPA: Cannot fixup static protections for PUD split\n");
1139 set:
1140 	set_pte(pte, pfn_pte(pfn, ref_prot));
1141 }
1142 
1143 static int
__split_large_page(struct cpa_data * cpa,pte_t * kpte,unsigned long address,pte_t * pbase)1144 __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
1145 		   pte_t *pbase)
1146 {
1147 	unsigned long lpaddr, lpinc, ref_pfn, pfn, pfninc = 1;
1148 	struct page *base = virt_to_page(pbase);
1149 	unsigned int i, level;
1150 	pgprot_t ref_prot;
1151 	bool nx, rw;
1152 	pte_t *tmp;
1153 
1154 	guard(spinlock)(&pgd_lock);
1155 	/*
1156 	 * Check for races, another CPU might have split this page
1157 	 * up for us already:
1158 	 */
1159 	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
1160 	if (tmp != kpte)
1161 		return 1;
1162 
1163 	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
1164 
1165 	switch (level) {
1166 	case PG_LEVEL_2M:
1167 		ref_prot = pmd_pgprot(*(pmd_t *)kpte);
1168 		/*
1169 		 * Clear PSE (aka _PAGE_PAT) and move
1170 		 * PAT bit to correct position.
1171 		 */
1172 		ref_prot = pgprot_large_2_4k(ref_prot);
1173 		ref_pfn = pmd_pfn(*(pmd_t *)kpte);
1174 		lpaddr = address & PMD_MASK;
1175 		lpinc = PAGE_SIZE;
1176 		break;
1177 
1178 	case PG_LEVEL_1G:
1179 		ref_prot = pud_pgprot(*(pud_t *)kpte);
1180 		ref_pfn = pud_pfn(*(pud_t *)kpte);
1181 		pfninc = PMD_SIZE >> PAGE_SHIFT;
1182 		lpaddr = address & PUD_MASK;
1183 		lpinc = PMD_SIZE;
1184 		/*
1185 		 * Clear the PSE flags if the PRESENT flag is not set
1186 		 * otherwise pmd_present() will return true even on a non
1187 		 * present pmd.
1188 		 */
1189 		if (!(pgprot_val(ref_prot) & _PAGE_PRESENT))
1190 			pgprot_val(ref_prot) &= ~_PAGE_PSE;
1191 		break;
1192 
1193 	default:
1194 		return 1;
1195 	}
1196 
1197 	ref_prot = pgprot_clear_protnone_bits(ref_prot);
1198 
1199 	/*
1200 	 * Get the target pfn from the original entry:
1201 	 */
1202 	pfn = ref_pfn;
1203 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc, lpaddr += lpinc)
1204 		split_set_pte(cpa, pbase + i, pfn, ref_prot, lpaddr, lpinc);
1205 
1206 	if (virt_addr_valid(address)) {
1207 		unsigned long pfn = PFN_DOWN(__pa(address));
1208 
1209 		if (pfn_range_is_mapped(pfn, pfn + 1))
1210 			split_page_count(level);
1211 	}
1212 
1213 	/*
1214 	 * Install the new, split up pagetable.
1215 	 *
1216 	 * We use the standard kernel pagetable protections for the new
1217 	 * pagetable protections, the actual ptes set above control the
1218 	 * primary protection behavior:
1219 	 */
1220 	__set_pmd_pte(kpte, address, mk_pte(base, __pgprot(_KERNPG_TABLE)));
1221 
1222 	/*
1223 	 * Do a global flush tlb after splitting the large page
1224 	 * and before we do the actual change page attribute in the PTE.
1225 	 *
1226 	 * Without this, we violate the TLB application note, that says:
1227 	 * "The TLBs may contain both ordinary and large-page
1228 	 *  translations for a 4-KByte range of linear addresses. This
1229 	 *  may occur if software modifies the paging structures so that
1230 	 *  the page size used for the address range changes. If the two
1231 	 *  translations differ with respect to page frame or attributes
1232 	 *  (e.g., permissions), processor behavior is undefined and may
1233 	 *  be implementation-specific."
1234 	 *
1235 	 * We do this global tlb flush inside the cpa_lock, so that we
1236 	 * don't allow any other cpu, with stale tlb entries change the
1237 	 * page attribute in parallel, that also falls into the
1238 	 * just split large page entry.
1239 	 */
1240 	flush_tlb_all();
1241 
1242 	return 0;
1243 }
1244 
split_large_page(struct cpa_data * cpa,pte_t * kpte,unsigned long address)1245 static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
1246 			    unsigned long address)
1247 {
1248 	pte_t *pte;
1249 
1250 	spin_unlock(&cpa_lock);
1251 	if (cpa->init_mm_read_locked)
1252 		mmap_read_unlock(&init_mm);
1253 	pte = pte_alloc_one_kernel(&init_mm);
1254 	if (cpa->init_mm_read_locked)
1255 		mmap_read_lock(&init_mm);
1256 	spin_lock(&cpa_lock);
1257 	if (!pte)
1258 		return -ENOMEM;
1259 
1260 	if (__split_large_page(cpa, kpte, address, pte))
1261 		pte_free_kernel(&init_mm, pte);
1262 
1263 	return 0;
1264 }
1265 
collapse_pmd_page(pmd_t * pmd,unsigned long addr,struct list_head * pgtables)1266 static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
1267 			     struct list_head *pgtables)
1268 {
1269 	pmd_t _pmd, old_pmd;
1270 	pte_t *pte, first;
1271 	unsigned long pfn;
1272 	pgprot_t pgprot;
1273 	int i = 0;
1274 
1275 	if (!cpu_feature_enabled(X86_FEATURE_PSE))
1276 		return 0;
1277 
1278 	addr &= PMD_MASK;
1279 	pte = pte_offset_kernel(pmd, addr);
1280 	first = *pte;
1281 	pfn = pte_pfn(first);
1282 
1283 	/* Make sure alignment is suitable */
1284 	if (PFN_PHYS(pfn) & ~PMD_MASK)
1285 		return 0;
1286 
1287 	/* The page is 4k intentionally */
1288 	if (pte_flags(first) & _PAGE_KERNEL_4K)
1289 		return 0;
1290 
1291 	/* Check that the rest of PTEs are compatible with the first one */
1292 	for (i = 1, pte++; i < PTRS_PER_PTE; i++, pte++) {
1293 		pte_t entry = *pte;
1294 
1295 		if (!pte_present(entry))
1296 			return 0;
1297 		if (pte_flags(entry) != pte_flags(first))
1298 			return 0;
1299 		if (pte_pfn(entry) != pte_pfn(first) + i)
1300 			return 0;
1301 	}
1302 
1303 	old_pmd = *pmd;
1304 
1305 	/* Success: set up a large page */
1306 	pgprot = pgprot_4k_2_large(pte_pgprot(first));
1307 	pgprot_val(pgprot) |= _PAGE_PSE;
1308 	_pmd = pfn_pmd(pfn, pgprot);
1309 	set_pmd(pmd, _pmd);
1310 
1311 	/* Queue the page table to be freed after TLB flush */
1312 	list_add(&page_ptdesc(pmd_page(old_pmd))->pt_list, pgtables);
1313 
1314 	if (IS_ENABLED(CONFIG_X86_32)) {
1315 		struct ptdesc *ptdesc;
1316 
1317 		/* Update all PGD tables to use the same large page */
1318 		list_for_each_entry(ptdesc, &pgd_list, pt_list) {
1319 			pgd_t *pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(addr);
1320 			p4d_t *p4d = p4d_offset(pgd, addr);
1321 			pud_t *pud = pud_offset(p4d, addr);
1322 			pmd_t *pmd = pmd_offset(pud, addr);
1323 			/* Something is wrong if entries doesn't match */
1324 			if (WARN_ON(pmd_val(old_pmd) != pmd_val(*pmd)))
1325 				continue;
1326 			set_pmd(pmd, _pmd);
1327 		}
1328 	}
1329 
1330 	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
1331 		collapse_page_count(PG_LEVEL_2M);
1332 
1333 	return 1;
1334 }
1335 
collapse_pud_page(pud_t * pud,unsigned long addr,struct list_head * pgtables)1336 static int collapse_pud_page(pud_t *pud, unsigned long addr,
1337 			     struct list_head *pgtables)
1338 {
1339 	unsigned long pfn;
1340 	pmd_t *pmd, first;
1341 	int i;
1342 
1343 	if (!direct_gbpages)
1344 		return 0;
1345 
1346 	addr &= PUD_MASK;
1347 	pmd = pmd_offset(pud, addr);
1348 	first = *pmd;
1349 
1350 	/*
1351 	 * To restore PUD page all PMD entries must be large and
1352 	 * have suitable alignment
1353 	 */
1354 	pfn = pmd_pfn(first);
1355 	if (!pmd_leaf(first) || (PFN_PHYS(pfn) & ~PUD_MASK))
1356 		return 0;
1357 
1358 	/*
1359 	 * To restore PUD page, all following PMDs must be compatible with the
1360 	 * first one.
1361 	 */
1362 	for (i = 1, pmd++; i < PTRS_PER_PMD; i++, pmd++) {
1363 		pmd_t entry = *pmd;
1364 
1365 		if (!pmd_present(entry) || !pmd_leaf(entry))
1366 			return 0;
1367 		if (pmd_flags(entry) != pmd_flags(first))
1368 			return 0;
1369 		if (pmd_pfn(entry) != pmd_pfn(first) + i * PTRS_PER_PTE)
1370 			return 0;
1371 	}
1372 
1373 	/* Restore PUD page and queue page table to be freed after TLB flush */
1374 	list_add(&page_ptdesc(pud_page(*pud))->pt_list, pgtables);
1375 	set_pud(pud, pfn_pud(pfn, pmd_pgprot(first)));
1376 
1377 	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
1378 		collapse_page_count(PG_LEVEL_1G);
1379 
1380 	return 1;
1381 }
1382 
1383 /*
1384  * Collapse PMD and PUD pages in the kernel mapping around the address where
1385  * possible.
1386  *
1387  * Caller must flush TLB and free page tables queued on the list before
1388  * touching the new entries. CPU must not see TLB entries of different size
1389  * with different attributes.
1390  */
collapse_large_pages(unsigned long addr,struct list_head * pgtables)1391 static int collapse_large_pages(unsigned long addr, struct list_head *pgtables)
1392 {
1393 	int collapsed;
1394 	pgd_t *pgd;
1395 	p4d_t *p4d;
1396 	pud_t *pud;
1397 	pmd_t *pmd;
1398 
1399 	addr &= PMD_MASK;
1400 
1401 	guard(spinlock)(&pgd_lock);
1402 	pgd = pgd_offset_k(addr);
1403 	if (pgd_none(*pgd))
1404 		return 0;
1405 	p4d = p4d_offset(pgd, addr);
1406 	if (p4d_none(*p4d))
1407 		return 0;
1408 	pud = pud_offset(p4d, addr);
1409 	if (!pud_present(*pud) || pud_leaf(*pud))
1410 		return 0;
1411 	pmd = pmd_offset(pud, addr);
1412 	if (!pmd_present(*pmd) || pmd_leaf(*pmd))
1413 		return 0;
1414 
1415 	collapsed = collapse_pmd_page(pmd, addr, pgtables);
1416 	if (collapsed)
1417 		collapsed += collapse_pud_page(pud, addr, pgtables);
1418 
1419 	return collapsed;
1420 }
1421 
try_to_free_pte_page(pte_t * pte)1422 static bool try_to_free_pte_page(pte_t *pte)
1423 {
1424 	int i;
1425 
1426 	for (i = 0; i < PTRS_PER_PTE; i++)
1427 		if (!pte_none(pte[i]))
1428 			return false;
1429 
1430 	pte_free_kernel(&init_mm, pte);
1431 	return true;
1432 }
1433 
try_to_free_pmd_page(pmd_t * pmd)1434 static bool try_to_free_pmd_page(pmd_t *pmd)
1435 {
1436 	int i;
1437 
1438 	for (i = 0; i < PTRS_PER_PMD; i++)
1439 		if (!pmd_none(pmd[i]))
1440 			return false;
1441 
1442 	pmd_free(&init_mm, pmd);
1443 	return true;
1444 }
1445 
unmap_pte_range(pmd_t * pmd,unsigned long start,unsigned long end)1446 static bool unmap_pte_range(pmd_t *pmd, unsigned long start, unsigned long end)
1447 {
1448 	pte_t *pte = pte_offset_kernel(pmd, start);
1449 
1450 	while (start < end) {
1451 		set_pte(pte, __pte(0));
1452 
1453 		start += PAGE_SIZE;
1454 		pte++;
1455 	}
1456 
1457 	if (try_to_free_pte_page((pte_t *)pmd_page_vaddr(*pmd))) {
1458 		pmd_clear(pmd);
1459 		return true;
1460 	}
1461 	return false;
1462 }
1463 
__unmap_pmd_range(pud_t * pud,pmd_t * pmd,unsigned long start,unsigned long end)1464 static void __unmap_pmd_range(pud_t *pud, pmd_t *pmd,
1465 			      unsigned long start, unsigned long end)
1466 {
1467 	if (unmap_pte_range(pmd, start, end))
1468 		if (try_to_free_pmd_page(pud_pgtable(*pud)))
1469 			pud_clear(pud);
1470 }
1471 
unmap_pmd_range(pud_t * pud,unsigned long start,unsigned long end)1472 static void unmap_pmd_range(pud_t *pud, unsigned long start, unsigned long end)
1473 {
1474 	pmd_t *pmd = pmd_offset(pud, start);
1475 
1476 	/*
1477 	 * Not on a 2MB page boundary?
1478 	 */
1479 	if (start & (PMD_SIZE - 1)) {
1480 		unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
1481 		unsigned long pre_end = min_t(unsigned long, end, next_page);
1482 
1483 		__unmap_pmd_range(pud, pmd, start, pre_end);
1484 
1485 		start = pre_end;
1486 		pmd++;
1487 	}
1488 
1489 	/*
1490 	 * Try to unmap in 2M chunks.
1491 	 */
1492 	while (end - start >= PMD_SIZE) {
1493 		if (pmd_leaf(*pmd))
1494 			pmd_clear(pmd);
1495 		else
1496 			__unmap_pmd_range(pud, pmd, start, start + PMD_SIZE);
1497 
1498 		start += PMD_SIZE;
1499 		pmd++;
1500 	}
1501 
1502 	/*
1503 	 * 4K leftovers?
1504 	 */
1505 	if (start < end)
1506 		return __unmap_pmd_range(pud, pmd, start, end);
1507 
1508 	/*
1509 	 * Try again to free the PMD page if haven't succeeded above.
1510 	 */
1511 	if (!pud_none(*pud))
1512 		if (try_to_free_pmd_page(pud_pgtable(*pud)))
1513 			pud_clear(pud);
1514 }
1515 
unmap_pud_range(p4d_t * p4d,unsigned long start,unsigned long end)1516 static void unmap_pud_range(p4d_t *p4d, unsigned long start, unsigned long end)
1517 {
1518 	pud_t *pud = pud_offset(p4d, start);
1519 
1520 	/*
1521 	 * Not on a GB page boundary?
1522 	 */
1523 	if (start & (PUD_SIZE - 1)) {
1524 		unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
1525 		unsigned long pre_end	= min_t(unsigned long, end, next_page);
1526 
1527 		unmap_pmd_range(pud, start, pre_end);
1528 
1529 		start = pre_end;
1530 		pud++;
1531 	}
1532 
1533 	/*
1534 	 * Try to unmap in 1G chunks?
1535 	 */
1536 	while (end - start >= PUD_SIZE) {
1537 
1538 		if (pud_leaf(*pud))
1539 			pud_clear(pud);
1540 		else
1541 			unmap_pmd_range(pud, start, start + PUD_SIZE);
1542 
1543 		start += PUD_SIZE;
1544 		pud++;
1545 	}
1546 
1547 	/*
1548 	 * 2M leftovers?
1549 	 */
1550 	if (start < end)
1551 		unmap_pmd_range(pud, start, end);
1552 
1553 	/*
1554 	 * No need to try to free the PUD page because we'll free it in
1555 	 * populate_pgd's error path
1556 	 */
1557 }
1558 
alloc_pte_page(pmd_t * pmd)1559 static int alloc_pte_page(pmd_t *pmd)
1560 {
1561 	pte_t *pte = pte_alloc_one_kernel(&init_mm);
1562 	if (!pte)
1563 		return -1;
1564 
1565 	set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
1566 	return 0;
1567 }
1568 
alloc_pmd_page(pud_t * pud)1569 static int alloc_pmd_page(pud_t *pud)
1570 {
1571 	/*
1572 	 * Pass 0 as a placeholder for the second argument, since the
1573 	 * generic implementation of pmd_alloc_one() does not use it.
1574 	 */
1575 	pmd_t *pmd = pmd_alloc_one(&init_mm, 0);
1576 	if (!pmd)
1577 		return -1;
1578 
1579 	set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
1580 	return 0;
1581 }
1582 
populate_pte(struct cpa_data * cpa,unsigned long start,unsigned long end,unsigned num_pages,pmd_t * pmd,pgprot_t pgprot)1583 static void populate_pte(struct cpa_data *cpa,
1584 			 unsigned long start, unsigned long end,
1585 			 unsigned num_pages, pmd_t *pmd, pgprot_t pgprot)
1586 {
1587 	pte_t *pte;
1588 
1589 	pte = pte_offset_kernel(pmd, start);
1590 
1591 	pgprot = pgprot_clear_protnone_bits(pgprot);
1592 
1593 	while (num_pages-- && start < end) {
1594 		set_pte(pte, pfn_pte(cpa->pfn, pgprot));
1595 
1596 		start	 += PAGE_SIZE;
1597 		cpa->pfn++;
1598 		pte++;
1599 	}
1600 }
1601 
populate_pmd(struct cpa_data * cpa,unsigned long start,unsigned long end,unsigned num_pages,pud_t * pud,pgprot_t pgprot)1602 static long populate_pmd(struct cpa_data *cpa,
1603 			 unsigned long start, unsigned long end,
1604 			 unsigned num_pages, pud_t *pud, pgprot_t pgprot)
1605 {
1606 	long cur_pages = 0;
1607 	pmd_t *pmd;
1608 	pgprot_t pmd_pgprot;
1609 
1610 	/*
1611 	 * Not on a 2M boundary?
1612 	 */
1613 	if (start & (PMD_SIZE - 1)) {
1614 		unsigned long pre_end = start + (num_pages << PAGE_SHIFT);
1615 		unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
1616 
1617 		pre_end   = min_t(unsigned long, pre_end, next_page);
1618 		cur_pages = (pre_end - start) >> PAGE_SHIFT;
1619 		cur_pages = min_t(unsigned int, num_pages, cur_pages);
1620 
1621 		/*
1622 		 * Need a PTE page?
1623 		 */
1624 		pmd = pmd_offset(pud, start);
1625 		if (pmd_none(*pmd))
1626 			if (alloc_pte_page(pmd))
1627 				return -1;
1628 
1629 		populate_pte(cpa, start, pre_end, cur_pages, pmd, pgprot);
1630 
1631 		start = pre_end;
1632 	}
1633 
1634 	/*
1635 	 * We mapped them all?
1636 	 */
1637 	if (num_pages == cur_pages)
1638 		return cur_pages;
1639 
1640 	pmd_pgprot = pgprot_4k_2_large(pgprot);
1641 
1642 	while (end - start >= PMD_SIZE) {
1643 
1644 		/*
1645 		 * We cannot use a 1G page so allocate a PMD page if needed.
1646 		 */
1647 		if (pud_none(*pud))
1648 			if (alloc_pmd_page(pud))
1649 				return -1;
1650 
1651 		pmd = pmd_offset(pud, start);
1652 
1653 		set_pmd(pmd, pmd_mkhuge(pfn_pmd(cpa->pfn,
1654 					canon_pgprot(pmd_pgprot))));
1655 
1656 		start	  += PMD_SIZE;
1657 		cpa->pfn  += PMD_SIZE >> PAGE_SHIFT;
1658 		cur_pages += PMD_SIZE >> PAGE_SHIFT;
1659 	}
1660 
1661 	/*
1662 	 * Map trailing 4K pages.
1663 	 */
1664 	if (start < end) {
1665 		pmd = pmd_offset(pud, start);
1666 		if (pmd_none(*pmd))
1667 			if (alloc_pte_page(pmd))
1668 				return -1;
1669 
1670 		populate_pte(cpa, start, end, num_pages - cur_pages,
1671 			     pmd, pgprot);
1672 	}
1673 	return num_pages;
1674 }
1675 
populate_pud(struct cpa_data * cpa,unsigned long start,p4d_t * p4d,pgprot_t pgprot)1676 static int populate_pud(struct cpa_data *cpa, unsigned long start, p4d_t *p4d,
1677 			pgprot_t pgprot)
1678 {
1679 	pud_t *pud;
1680 	unsigned long end;
1681 	long cur_pages = 0;
1682 	pgprot_t pud_pgprot;
1683 
1684 	end = start + (cpa->numpages << PAGE_SHIFT);
1685 
1686 	/*
1687 	 * Not on a Gb page boundary? => map everything up to it with
1688 	 * smaller pages.
1689 	 */
1690 	if (start & (PUD_SIZE - 1)) {
1691 		unsigned long pre_end;
1692 		unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
1693 
1694 		pre_end   = min_t(unsigned long, end, next_page);
1695 		cur_pages = (pre_end - start) >> PAGE_SHIFT;
1696 		cur_pages = min_t(int, (int)cpa->numpages, cur_pages);
1697 
1698 		pud = pud_offset(p4d, start);
1699 
1700 		/*
1701 		 * Need a PMD page?
1702 		 */
1703 		if (pud_none(*pud))
1704 			if (alloc_pmd_page(pud))
1705 				return -1;
1706 
1707 		cur_pages = populate_pmd(cpa, start, pre_end, cur_pages,
1708 					 pud, pgprot);
1709 		if (cur_pages < 0)
1710 			return cur_pages;
1711 
1712 		start = pre_end;
1713 	}
1714 
1715 	/* We mapped them all? */
1716 	if (cpa->numpages == cur_pages)
1717 		return cur_pages;
1718 
1719 	pud = pud_offset(p4d, start);
1720 	pud_pgprot = pgprot_4k_2_large(pgprot);
1721 
1722 	/*
1723 	 * Map everything starting from the Gb boundary, possibly with 1G pages
1724 	 */
1725 	while (boot_cpu_has(X86_FEATURE_GBPAGES) && end - start >= PUD_SIZE) {
1726 		set_pud(pud, pud_mkhuge(pfn_pud(cpa->pfn,
1727 				   canon_pgprot(pud_pgprot))));
1728 
1729 		start	  += PUD_SIZE;
1730 		cpa->pfn  += PUD_SIZE >> PAGE_SHIFT;
1731 		cur_pages += PUD_SIZE >> PAGE_SHIFT;
1732 		pud++;
1733 	}
1734 
1735 	/* Map trailing leftover */
1736 	if (start < end) {
1737 		long tmp;
1738 
1739 		pud = pud_offset(p4d, start);
1740 		if (pud_none(*pud))
1741 			if (alloc_pmd_page(pud))
1742 				return -1;
1743 
1744 		tmp = populate_pmd(cpa, start, end, cpa->numpages - cur_pages,
1745 				   pud, pgprot);
1746 		if (tmp < 0)
1747 			return cur_pages;
1748 
1749 		cur_pages += tmp;
1750 	}
1751 	return cur_pages;
1752 }
1753 
1754 /*
1755  * Restrictions for kernel page table do not necessarily apply when mapping in
1756  * an alternate PGD.
1757  */
populate_pgd(struct cpa_data * cpa,unsigned long addr)1758 static int populate_pgd(struct cpa_data *cpa, unsigned long addr)
1759 {
1760 	pgprot_t pgprot = __pgprot(_KERNPG_TABLE);
1761 	pud_t *pud = NULL;	/* shut up gcc */
1762 	p4d_t *p4d;
1763 	pgd_t *pgd_entry;
1764 	long ret;
1765 
1766 	pgd_entry = cpa->pgd + pgd_index(addr);
1767 
1768 	if (pgd_none(*pgd_entry)) {
1769 		/*
1770 		 * Pass 0 as a placeholder for the second argument, since the
1771 		 * generic implementation of p4d_alloc_one() does not use it.
1772 		 */
1773 		p4d = p4d_alloc_one(&init_mm, 0);
1774 		if (!p4d)
1775 			return -1;
1776 
1777 		set_pgd(pgd_entry, __pgd(__pa(p4d) | _KERNPG_TABLE));
1778 	}
1779 
1780 	/*
1781 	 * Allocate a PUD page and hand it down for mapping.
1782 	 */
1783 	p4d = p4d_offset(pgd_entry, addr);
1784 	if (p4d_none(*p4d)) {
1785 		/*
1786 		 * Pass 0 as a placeholder for the second argument, since the
1787 		 * generic implementation of pud_alloc_one() does not use it.
1788 		 */
1789 		pud = pud_alloc_one(&init_mm, 0);
1790 		if (!pud)
1791 			return -1;
1792 
1793 		set_p4d(p4d, __p4d(__pa(pud) | _KERNPG_TABLE));
1794 	}
1795 
1796 	pgprot_val(pgprot) &= ~pgprot_val(cpa->mask_clr);
1797 	pgprot_val(pgprot) |=  pgprot_val(cpa->mask_set);
1798 
1799 	ret = populate_pud(cpa, addr, p4d, pgprot);
1800 	if (ret < 0) {
1801 		/*
1802 		 * Leave the PUD page in place in case some other CPU or thread
1803 		 * already found it, but remove any useless entries we just
1804 		 * added to it.
1805 		 */
1806 		unmap_pud_range(p4d, addr,
1807 				addr + (cpa->numpages << PAGE_SHIFT));
1808 		return ret;
1809 	}
1810 
1811 	cpa->numpages = ret;
1812 	return 0;
1813 }
1814 
__cpa_process_fault(struct cpa_data * cpa,unsigned long vaddr,int primary)1815 static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
1816 			       int primary)
1817 {
1818 	if (cpa->pgd) {
1819 		/*
1820 		 * Right now, we only execute this code path when mapping
1821 		 * the EFI virtual memory map regions, no other users
1822 		 * provide a ->pgd value. This may change in the future.
1823 		 */
1824 		return populate_pgd(cpa, vaddr);
1825 	}
1826 
1827 	/*
1828 	 * Ignore all non primary paths.
1829 	 */
1830 	if (!primary) {
1831 		cpa->numpages = 1;
1832 		return 0;
1833 	}
1834 
1835 	/*
1836 	 * Ignore the NULL PTE for kernel identity mapping, as it is expected
1837 	 * to have holes.
1838 	 * Also set numpages to '1' indicating that we processed cpa req for
1839 	 * one virtual address page and its pfn. TBD: numpages can be set based
1840 	 * on the initial value and the level returned by lookup_address().
1841 	 */
1842 	if (within(vaddr, PAGE_OFFSET,
1843 		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT))) {
1844 		cpa->numpages = 1;
1845 		cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
1846 		return 0;
1847 
1848 	} else if (__cpa_pfn_in_highmap(cpa->pfn)) {
1849 		/* Faults in the highmap are OK, so do not warn: */
1850 		return -EFAULT;
1851 	} else {
1852 		WARN(1, KERN_WARNING "CPA: called for zero pte. "
1853 			"vaddr = %lx cpa->vaddr = %lx\n", vaddr,
1854 			*cpa->vaddr);
1855 
1856 		return -EFAULT;
1857 	}
1858 }
1859 
__change_page_attr(struct cpa_data * cpa,int primary)1860 static int __change_page_attr(struct cpa_data *cpa, int primary)
1861 {
1862 	unsigned long address;
1863 	int do_split, err;
1864 	unsigned int level;
1865 	pte_t *kpte, old_pte;
1866 	bool nx, rw;
1867 
1868 	address = __cpa_addr(cpa, cpa->curpage);
1869 repeat:
1870 	kpte = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
1871 	if (!kpte)
1872 		return __cpa_process_fault(cpa, address, primary);
1873 
1874 	old_pte = *kpte;
1875 	if (pte_none(old_pte))
1876 		return __cpa_process_fault(cpa, address, primary);
1877 
1878 	if (level == PG_LEVEL_4K) {
1879 		pte_t new_pte;
1880 		pgprot_t old_prot = pte_pgprot(old_pte);
1881 		pgprot_t new_prot = pte_pgprot(old_pte);
1882 		unsigned long pfn = pte_pfn(old_pte);
1883 
1884 		pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
1885 		pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
1886 
1887 		cpa_inc_4k_install();
1888 		/* Hand in lpsize = 0 to enforce the protection mechanism */
1889 		new_prot = static_protections(new_prot, address, pfn, 1, 0,
1890 					      CPA_PROTECT);
1891 
1892 		new_prot = verify_rwx(old_prot, new_prot, address, pfn, 1,
1893 				      nx, rw);
1894 
1895 		new_prot = pgprot_clear_protnone_bits(new_prot);
1896 
1897 		/*
1898 		 * We need to keep the pfn from the existing PTE,
1899 		 * after all we're only going to change its attributes
1900 		 * not the memory it points to
1901 		 */
1902 		new_pte = pfn_pte(pfn, new_prot);
1903 		cpa->pfn = pfn;
1904 		/*
1905 		 * Do we really change anything ?
1906 		 */
1907 		if (pte_val(old_pte) != pte_val(new_pte)) {
1908 			set_pte_atomic(kpte, new_pte);
1909 			cpa->flags |= CPA_FLUSHTLB;
1910 		}
1911 		cpa->numpages = 1;
1912 		return 0;
1913 	}
1914 
1915 	/*
1916 	 * Check, whether we can keep the large page intact
1917 	 * and just change the pte:
1918 	 */
1919 	do_split = should_split_large_page(kpte, address, cpa);
1920 	/*
1921 	 * When the range fits into the existing large page,
1922 	 * return. cp->numpages and cpa->tlbflush have been updated in
1923 	 * try_large_page:
1924 	 */
1925 	if (do_split <= 0)
1926 		return do_split;
1927 
1928 	/*
1929 	 * We have to split the large page:
1930 	 */
1931 	err = split_large_page(cpa, kpte, address);
1932 	if (!err)
1933 		goto repeat;
1934 
1935 	return err;
1936 }
1937 
1938 static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary);
1939 
1940 /*
1941  * Check the directmap and "high kernel map" 'aliases'.
1942  */
cpa_process_alias(struct cpa_data * cpa)1943 static int cpa_process_alias(struct cpa_data *cpa)
1944 {
1945 	struct cpa_data alias_cpa;
1946 	unsigned long laddr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
1947 	unsigned long vaddr;
1948 	int ret;
1949 
1950 	if (!pfn_range_is_mapped(cpa->pfn, cpa->pfn + 1))
1951 		return 0;
1952 
1953 	/*
1954 	 * No need to redo, when the primary call touched the direct
1955 	 * mapping already:
1956 	 */
1957 	vaddr = __cpa_addr(cpa, cpa->curpage);
1958 	if (!(within(vaddr, PAGE_OFFSET,
1959 		    PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))) {
1960 
1961 		alias_cpa = *cpa;
1962 		alias_cpa.vaddr = &laddr;
1963 		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
1964 		alias_cpa.curpage = 0;
1965 
1966 		/* Directmap always has NX set, do not modify. */
1967 		if (__supported_pte_mask & _PAGE_NX) {
1968 			alias_cpa.mask_clr.pgprot &= ~_PAGE_NX;
1969 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
1970 		}
1971 
1972 		cpa->force_flush_all = 1;
1973 
1974 		ret = __change_page_attr_set_clr(&alias_cpa, 0);
1975 		if (ret)
1976 			return ret;
1977 	}
1978 
1979 #ifdef CONFIG_X86_64
1980 	/*
1981 	 * If the primary call didn't touch the high mapping already
1982 	 * and the physical address is inside the kernel map, we need
1983 	 * to touch the high mapped kernel as well:
1984 	 */
1985 	if (!within(vaddr, (unsigned long)_text, _brk_end) &&
1986 	    __cpa_pfn_in_highmap(cpa->pfn)) {
1987 		unsigned long temp_cpa_vaddr = (cpa->pfn << PAGE_SHIFT) +
1988 					       __START_KERNEL_map - phys_base;
1989 		alias_cpa = *cpa;
1990 		alias_cpa.vaddr = &temp_cpa_vaddr;
1991 		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
1992 		alias_cpa.curpage = 0;
1993 
1994 		/*
1995 		 * [_text, _brk_end) also covers data, do not modify NX except
1996 		 * in cases where the highmap is the primary target.
1997 		 */
1998 		if (__supported_pte_mask & _PAGE_NX) {
1999 			alias_cpa.mask_clr.pgprot &= ~_PAGE_NX;
2000 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
2001 		}
2002 
2003 		cpa->force_flush_all = 1;
2004 		/*
2005 		 * The high mapping range is imprecise, so ignore the
2006 		 * return value.
2007 		 */
2008 		__change_page_attr_set_clr(&alias_cpa, 0);
2009 	}
2010 #endif
2011 
2012 	return 0;
2013 }
2014 
__change_page_attr_set_clr(struct cpa_data * cpa,int primary)2015 static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
2016 {
2017 	unsigned long numpages = cpa->numpages;
2018 	unsigned long rempages = numpages;
2019 	bool lock = true;
2020 	int ret = 0;
2021 
2022 	/*
2023 	 * No changes, easy!
2024 	 */
2025 	if (!(pgprot_val(cpa->mask_set) | pgprot_val(cpa->mask_clr)) &&
2026 	    !cpa->force_split)
2027 		return ret;
2028 
2029 	/*
2030 	 * DEBUG_PAGEALLOC is special; it is called from any context the
2031 	 * page-allocator is, which violates the normal cpa_lock locking
2032 	 * rules.
2033 	 *
2034 	 * However, since it is part of the page-allocator, things are still
2035 	 * properly serialized by the page-allocator locking and the fact that
2036 	 * when a page is owned by the page-allocator, it isn't owned by
2037 	 * anybody else. That is, you *SHOULD NOT* be calling cpa() on memory
2038 	 * that isn't allocated.
2039 	 *
2040 	 * Additionally, DEBUG_PAGEALLOC ensures (per probe_page_size_mask())
2041 	 * that the kernel mapping is 4k pages, therefore there are no large
2042 	 * pages to split/collapse.
2043 	 *
2044 	 * Furthermore, the page-allocator strictly manages pages that
2045 	 * *exist*, avoiding pgd_lock.
2046 	 *
2047 	 * Therefore, it is safe to not take cpa_lock.
2048 	 */
2049 	if (debug_pagealloc_enabled() && (cpa->flags & CPA_DEBUG_PAGEALLOC))
2050 		lock = false;
2051 
2052 	while (rempages) {
2053 		/*
2054 		 * Store the remaining nr of pages for the large page
2055 		 * preservation check.
2056 		 */
2057 		cpa->numpages = rempages;
2058 		/* for array changes, we can't use large page */
2059 		if (cpa->flags & (CPA_ARRAY | CPA_PAGES_ARRAY))
2060 			cpa->numpages = 1;
2061 
2062 		if (lock) {
2063 			guard(spinlock)(&cpa_lock);
2064 			ret = __change_page_attr(cpa, primary);
2065 		} else {
2066 			ret = __change_page_attr(cpa, primary);
2067 		}
2068 		if (ret)
2069 			goto out;
2070 
2071 		if (primary && !(cpa->flags & CPA_NO_CHECK_ALIAS)) {
2072 			ret = cpa_process_alias(cpa);
2073 			if (ret)
2074 				goto out;
2075 		}
2076 
2077 		/*
2078 		 * Adjust the number of pages with the result of the
2079 		 * CPA operation. Either a large page has been
2080 		 * preserved or a single page update happened.
2081 		 */
2082 		BUG_ON(cpa->numpages > rempages || !cpa->numpages);
2083 		rempages -= cpa->numpages;
2084 		cpa->curpage += cpa->numpages;
2085 	}
2086 
2087 out:
2088 	/* Restore the original numpages */
2089 	cpa->numpages = numpages;
2090 	return ret;
2091 }
2092 
change_page_attr_set_clr(unsigned long * addr,int numpages,pgprot_t mask_set,pgprot_t mask_clr,int force_split,int in_flag,struct page ** pages)2093 static int change_page_attr_set_clr(unsigned long *addr, int numpages,
2094 				    pgprot_t mask_set, pgprot_t mask_clr,
2095 				    int force_split, int in_flag,
2096 				    struct page **pages)
2097 {
2098 	struct cpa_data cpa;
2099 	int ret, cache;
2100 
2101 	memset(&cpa, 0, sizeof(cpa));
2102 
2103 	/*
2104 	 * Check, if we are requested to set a not supported
2105 	 * feature.  Clearing non-supported features is OK.
2106 	 */
2107 	mask_set = canon_pgprot(mask_set);
2108 
2109 	if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) && !force_split)
2110 		return 0;
2111 
2112 	/* Ensure we are PAGE_SIZE aligned */
2113 	if (in_flag & CPA_ARRAY) {
2114 		int i;
2115 		for (i = 0; i < numpages; i++) {
2116 			if (addr[i] & ~PAGE_MASK) {
2117 				addr[i] &= PAGE_MASK;
2118 				WARN_ON_ONCE(1);
2119 			}
2120 		}
2121 	} else if (!(in_flag & CPA_PAGES_ARRAY)) {
2122 		/*
2123 		 * in_flag of CPA_PAGES_ARRAY implies it is aligned.
2124 		 * No need to check in that case
2125 		 */
2126 		if (*addr & ~PAGE_MASK) {
2127 			*addr &= PAGE_MASK;
2128 			/*
2129 			 * People should not be passing in unaligned addresses:
2130 			 */
2131 			WARN_ON_ONCE(1);
2132 		}
2133 	}
2134 
2135 	/* Must avoid aliasing mappings in the highmem code */
2136 	kmap_flush_unused();
2137 
2138 	vm_unmap_aliases();
2139 
2140 	cpa.vaddr = addr;
2141 	cpa.pages = pages;
2142 	cpa.numpages = numpages;
2143 	cpa.mask_set = mask_set;
2144 	cpa.mask_clr = mask_clr;
2145 	cpa.flags = in_flag;
2146 	cpa.curpage = 0;
2147 	cpa.force_split = force_split;
2148 
2149 	/* Avoid race with concurrent CPA collapse. */
2150 	cpa.init_mm_read_locked = true;
2151 	scoped_guard(mmap_read_lock, &init_mm)
2152 		ret = __change_page_attr_set_clr(&cpa, 1);
2153 	cpa.init_mm_read_locked = false;
2154 
2155 	/*
2156 	 * Check whether we really changed something:
2157 	 */
2158 	if (!(cpa.flags & CPA_FLUSHTLB))
2159 		goto out;
2160 
2161 	/*
2162 	 * No need to flush, when we did not set any of the caching
2163 	 * attributes:
2164 	 */
2165 	cache = !!pgprot2cachemode(mask_set);
2166 
2167 	/*
2168 	 * On error; flush everything to be sure.
2169 	 */
2170 	if (ret) {
2171 		cpa_flush_all(cache);
2172 		goto out;
2173 	}
2174 
2175 	cpa_flush(&cpa, cache);
2176 out:
2177 	return ret;
2178 }
2179 
change_page_attr_set(unsigned long * addr,int numpages,pgprot_t mask,int array)2180 static inline int change_page_attr_set(unsigned long *addr, int numpages,
2181 				       pgprot_t mask, int array)
2182 {
2183 	return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
2184 		(array ? CPA_ARRAY : 0), NULL);
2185 }
2186 
change_page_attr_clear(unsigned long * addr,int numpages,pgprot_t mask,int array)2187 static inline int change_page_attr_clear(unsigned long *addr, int numpages,
2188 					 pgprot_t mask, int array)
2189 {
2190 	return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
2191 		(array ? CPA_ARRAY : 0), NULL);
2192 }
2193 
cpa_set_pages_array(struct page ** pages,int numpages,pgprot_t mask)2194 static inline int cpa_set_pages_array(struct page **pages, int numpages,
2195 				       pgprot_t mask)
2196 {
2197 	return change_page_attr_set_clr(NULL, numpages, mask, __pgprot(0), 0,
2198 		CPA_PAGES_ARRAY, pages);
2199 }
2200 
cpa_clear_pages_array(struct page ** pages,int numpages,pgprot_t mask)2201 static inline int cpa_clear_pages_array(struct page **pages, int numpages,
2202 					 pgprot_t mask)
2203 {
2204 	return change_page_attr_set_clr(NULL, numpages, __pgprot(0), mask, 0,
2205 		CPA_PAGES_ARRAY, pages);
2206 }
2207 
_set_memory_uc(unsigned long addr,int numpages)2208 int _set_memory_uc(unsigned long addr, int numpages)
2209 {
2210 	/*
2211 	 * for now UC MINUS. see comments in ioremap()
2212 	 * If you really need strong UC use ioremap_uc(), but note
2213 	 * that you cannot override IO areas with set_memory_*() as
2214 	 * these helpers cannot work with IO memory.
2215 	 */
2216 	return change_page_attr_set(&addr, numpages,
2217 				    cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
2218 				    0);
2219 }
2220 
set_memory_uc(unsigned long addr,int numpages)2221 int set_memory_uc(unsigned long addr, int numpages)
2222 {
2223 	int ret;
2224 
2225 	/*
2226 	 * for now UC MINUS. see comments in ioremap()
2227 	 */
2228 	ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
2229 			      _PAGE_CACHE_MODE_UC_MINUS, NULL);
2230 	if (ret)
2231 		goto out_err;
2232 
2233 	ret = _set_memory_uc(addr, numpages);
2234 	if (ret)
2235 		goto out_free;
2236 
2237 	return 0;
2238 
2239 out_free:
2240 	memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2241 out_err:
2242 	return ret;
2243 }
2244 EXPORT_SYMBOL(set_memory_uc);
2245 
_set_memory_wc(unsigned long addr,int numpages)2246 int _set_memory_wc(unsigned long addr, int numpages)
2247 {
2248 	int ret;
2249 
2250 	ret = change_page_attr_set(&addr, numpages,
2251 				   cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
2252 				   0);
2253 	if (!ret) {
2254 		ret = change_page_attr_set_clr(&addr, numpages,
2255 					       cachemode2pgprot(_PAGE_CACHE_MODE_WC),
2256 					       __pgprot(_PAGE_CACHE_MASK),
2257 					       0, 0, NULL);
2258 	}
2259 	return ret;
2260 }
2261 
set_memory_wc(unsigned long addr,int numpages)2262 int set_memory_wc(unsigned long addr, int numpages)
2263 {
2264 	int ret;
2265 
2266 	ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
2267 		_PAGE_CACHE_MODE_WC, NULL);
2268 	if (ret)
2269 		return ret;
2270 
2271 	ret = _set_memory_wc(addr, numpages);
2272 	if (ret)
2273 		memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2274 
2275 	return ret;
2276 }
2277 EXPORT_SYMBOL(set_memory_wc);
2278 
_set_memory_wt(unsigned long addr,int numpages)2279 int _set_memory_wt(unsigned long addr, int numpages)
2280 {
2281 	return change_page_attr_set(&addr, numpages,
2282 				    cachemode2pgprot(_PAGE_CACHE_MODE_WT), 0);
2283 }
2284 
_set_memory_wb(unsigned long addr,int numpages)2285 int _set_memory_wb(unsigned long addr, int numpages)
2286 {
2287 	/* WB cache mode is hard wired to all cache attribute bits being 0 */
2288 	return change_page_attr_clear(&addr, numpages,
2289 				      __pgprot(_PAGE_CACHE_MASK), 0);
2290 }
2291 
set_memory_wb(unsigned long addr,int numpages)2292 int set_memory_wb(unsigned long addr, int numpages)
2293 {
2294 	int ret;
2295 
2296 	ret = _set_memory_wb(addr, numpages);
2297 	if (ret)
2298 		return ret;
2299 
2300 	memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2301 	return 0;
2302 }
2303 EXPORT_SYMBOL(set_memory_wb);
2304 
2305 /* Prevent speculative access to a page by marking it not-present */
2306 #ifdef CONFIG_X86_64
set_mce_nospec(unsigned long pfn)2307 int set_mce_nospec(unsigned long pfn)
2308 {
2309 	unsigned long decoy_addr;
2310 	int rc;
2311 
2312 	/* SGX pages are not in the 1:1 map */
2313 	if (arch_is_platform_page(pfn << PAGE_SHIFT))
2314 		return 0;
2315 	/*
2316 	 * We would like to just call:
2317 	 *      set_memory_XX((unsigned long)pfn_to_kaddr(pfn), 1);
2318 	 * but doing that would radically increase the odds of a
2319 	 * speculative access to the poison page because we'd have
2320 	 * the virtual address of the kernel 1:1 mapping sitting
2321 	 * around in registers.
2322 	 * Instead we get tricky.  We create a non-canonical address
2323 	 * that looks just like the one we want, but has bit 63 flipped.
2324 	 * This relies on set_memory_XX() properly sanitizing any __pa()
2325 	 * results with __PHYSICAL_MASK or PTE_PFN_MASK.
2326 	 */
2327 	decoy_addr = (pfn << PAGE_SHIFT) + (PAGE_OFFSET ^ BIT(63));
2328 
2329 	rc = set_memory_np(decoy_addr, 1);
2330 	if (rc)
2331 		pr_warn("Could not invalidate pfn=0x%lx from 1:1 map\n", pfn);
2332 	return rc;
2333 }
2334 EXPORT_SYMBOL_GPL(set_mce_nospec);
2335 
2336 /* Restore full speculative operation to the pfn. */
clear_mce_nospec(unsigned long pfn)2337 int clear_mce_nospec(unsigned long pfn)
2338 {
2339 	unsigned long addr = (unsigned long) pfn_to_kaddr(pfn);
2340 
2341 	return set_memory_p(addr, 1);
2342 }
2343 EXPORT_SYMBOL_GPL(clear_mce_nospec);
2344 #endif /* CONFIG_X86_64 */
2345 
set_memory_x(unsigned long addr,int numpages)2346 int set_memory_x(unsigned long addr, int numpages)
2347 {
2348 	if (!(__supported_pte_mask & _PAGE_NX))
2349 		return 0;
2350 
2351 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_NX), 0);
2352 }
2353 
set_memory_nx(unsigned long addr,int numpages)2354 int set_memory_nx(unsigned long addr, int numpages)
2355 {
2356 	if (!(__supported_pte_mask & _PAGE_NX))
2357 		return 0;
2358 
2359 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_NX), 0);
2360 }
2361 
set_memory_ro(unsigned long addr,int numpages)2362 int set_memory_ro(unsigned long addr, int numpages)
2363 {
2364 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW | _PAGE_DIRTY), 0);
2365 }
2366 
set_memory_rox(unsigned long addr,int numpages)2367 int set_memory_rox(unsigned long addr, int numpages)
2368 {
2369 	pgprot_t clr = __pgprot(_PAGE_RW | _PAGE_DIRTY);
2370 
2371 	if (__supported_pte_mask & _PAGE_NX)
2372 		clr.pgprot |= _PAGE_NX;
2373 
2374 	return change_page_attr_set_clr(&addr, numpages, __pgprot(0), clr, 0,
2375 					CPA_COLLAPSE, NULL);
2376 }
2377 
set_memory_rw(unsigned long addr,int numpages)2378 int set_memory_rw(unsigned long addr, int numpages)
2379 {
2380 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_RW), 0);
2381 }
2382 
set_memory_np(unsigned long addr,int numpages)2383 int set_memory_np(unsigned long addr, int numpages)
2384 {
2385 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
2386 }
2387 
set_memory_np_noalias(unsigned long addr,int numpages)2388 int set_memory_np_noalias(unsigned long addr, int numpages)
2389 {
2390 	return change_page_attr_set_clr(&addr, numpages, __pgprot(0),
2391 					__pgprot(_PAGE_PRESENT), 0,
2392 					CPA_NO_CHECK_ALIAS, NULL);
2393 }
2394 
set_memory_p(unsigned long addr,int numpages)2395 int set_memory_p(unsigned long addr, int numpages)
2396 {
2397 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
2398 }
2399 
set_memory_4k(unsigned long addr,int numpages)2400 int set_memory_4k(unsigned long addr, int numpages)
2401 {
2402 	return change_page_attr_set_clr(&addr, numpages,
2403 					__pgprot(_PAGE_KERNEL_4K),
2404 					__pgprot(0), 1, 0, NULL);
2405 }
2406 
set_memory_nonglobal(unsigned long addr,int numpages)2407 int set_memory_nonglobal(unsigned long addr, int numpages)
2408 {
2409 	return change_page_attr_clear(&addr, numpages,
2410 				      __pgprot(_PAGE_GLOBAL), 0);
2411 }
2412 
set_memory_global(unsigned long addr,int numpages)2413 int set_memory_global(unsigned long addr, int numpages)
2414 {
2415 	return change_page_attr_set(&addr, numpages,
2416 				    __pgprot(_PAGE_GLOBAL), 0);
2417 }
2418 
2419 /*
2420  * __set_memory_enc_pgtable() is used for the hypervisors that get
2421  * informed about "encryption" status via page tables.
2422  */
__set_memory_enc_pgtable(unsigned long addr,int numpages,bool enc)2423 static int __set_memory_enc_pgtable(unsigned long addr, int numpages, bool enc)
2424 {
2425 	pgprot_t empty = __pgprot(0);
2426 	struct cpa_data cpa;
2427 	int ret;
2428 
2429 	/* Should not be working on unaligned addresses */
2430 	if (WARN_ONCE(addr & ~PAGE_MASK, "misaligned address: %#lx\n", addr))
2431 		addr &= PAGE_MASK;
2432 
2433 	memset(&cpa, 0, sizeof(cpa));
2434 	cpa.vaddr = &addr;
2435 	cpa.numpages = numpages;
2436 	cpa.mask_set = enc ? pgprot_encrypted(empty) : pgprot_decrypted(empty);
2437 	cpa.mask_clr = enc ? pgprot_decrypted(empty) : pgprot_encrypted(empty);
2438 	cpa.pgd = init_mm.pgd;
2439 
2440 	/* Must avoid aliasing mappings in the highmem code */
2441 	kmap_flush_unused();
2442 	vm_unmap_aliases();
2443 
2444 	/* Flush the caches as needed before changing the encryption attribute. */
2445 	if (x86_platform.guest.enc_tlb_flush_required(enc))
2446 		cpa_flush(&cpa, x86_platform.guest.enc_cache_flush_required());
2447 
2448 	/* Notify hypervisor that we are about to set/clr encryption attribute. */
2449 	ret = x86_platform.guest.enc_status_change_prepare(addr, numpages, enc);
2450 	if (ret)
2451 		goto vmm_fail;
2452 
2453 	ret = __change_page_attr_set_clr(&cpa, 1);
2454 
2455 	/*
2456 	 * After changing the encryption attribute, we need to flush TLBs again
2457 	 * in case any speculative TLB caching occurred (but no need to flush
2458 	 * caches again).  We could just use cpa_flush_all(), but in case TLB
2459 	 * flushing gets optimized in the cpa_flush() path use the same logic
2460 	 * as above.
2461 	 */
2462 	cpa_flush(&cpa, 0);
2463 
2464 	if (ret)
2465 		return ret;
2466 
2467 	/* Notify hypervisor that we have successfully set/clr encryption attribute. */
2468 	ret = x86_platform.guest.enc_status_change_finish(addr, numpages, enc);
2469 	if (ret)
2470 		goto vmm_fail;
2471 
2472 	return 0;
2473 
2474 vmm_fail:
2475 	WARN_ONCE(1, "CPA VMM failure to convert memory (addr=%p, numpages=%d) to %s: %d\n",
2476 		  (void *)addr, numpages, enc ? "private" : "shared", ret);
2477 
2478 	return ret;
2479 }
2480 
2481 /*
2482  * The lock serializes conversions between private and shared memory.
2483  *
2484  * It is taken for read on conversion. A write lock guarantees that no
2485  * concurrent conversions are in progress.
2486  */
2487 static DECLARE_RWSEM(mem_enc_lock);
2488 
2489 /*
2490  * Stop new private<->shared conversions.
2491  *
2492  * Taking the exclusive mem_enc_lock waits for in-flight conversions to complete.
2493  * The lock is not released to prevent new conversions from being started.
2494  */
set_memory_enc_stop_conversion(void)2495 bool set_memory_enc_stop_conversion(void)
2496 {
2497 	/*
2498 	 * In a crash scenario, sleep is not allowed. Try to take the lock.
2499 	 * Failure indicates that there is a race with the conversion.
2500 	 */
2501 	if (oops_in_progress)
2502 		return down_write_trylock(&mem_enc_lock);
2503 
2504 	down_write(&mem_enc_lock);
2505 
2506 	return true;
2507 }
2508 
__set_memory_enc_dec(unsigned long addr,int numpages,bool enc)2509 static int __set_memory_enc_dec(unsigned long addr, int numpages, bool enc)
2510 {
2511 	int ret = 0;
2512 
2513 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
2514 		if (!down_read_trylock(&mem_enc_lock))
2515 			return -EBUSY;
2516 
2517 		ret = __set_memory_enc_pgtable(addr, numpages, enc);
2518 
2519 		up_read(&mem_enc_lock);
2520 	}
2521 
2522 	return ret;
2523 }
2524 
set_memory_encrypted(unsigned long addr,int numpages)2525 int set_memory_encrypted(unsigned long addr, int numpages)
2526 {
2527 	return __set_memory_enc_dec(addr, numpages, true);
2528 }
2529 EXPORT_SYMBOL_GPL(set_memory_encrypted);
2530 
set_memory_decrypted(unsigned long addr,int numpages)2531 int set_memory_decrypted(unsigned long addr, int numpages)
2532 {
2533 	return __set_memory_enc_dec(addr, numpages, false);
2534 }
2535 EXPORT_SYMBOL_GPL(set_memory_decrypted);
2536 
set_pages_uc(struct page * page,int numpages)2537 int set_pages_uc(struct page *page, int numpages)
2538 {
2539 	unsigned long addr = (unsigned long)page_address(page);
2540 
2541 	return set_memory_uc(addr, numpages);
2542 }
2543 EXPORT_SYMBOL(set_pages_uc);
2544 
_set_pages_array(struct page ** pages,int numpages,enum page_cache_mode new_type)2545 static int _set_pages_array(struct page **pages, int numpages,
2546 		enum page_cache_mode new_type)
2547 {
2548 	unsigned long start;
2549 	unsigned long end;
2550 	enum page_cache_mode set_type;
2551 	int i;
2552 	int free_idx;
2553 	int ret;
2554 
2555 	for (i = 0; i < numpages; i++) {
2556 		if (PageHighMem(pages[i]))
2557 			continue;
2558 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2559 		end = start + PAGE_SIZE;
2560 		if (memtype_reserve(start, end, new_type, NULL))
2561 			goto err_out;
2562 	}
2563 
2564 	/* If WC, set to UC- first and then WC */
2565 	set_type = (new_type == _PAGE_CACHE_MODE_WC) ?
2566 				_PAGE_CACHE_MODE_UC_MINUS : new_type;
2567 
2568 	ret = cpa_set_pages_array(pages, numpages,
2569 				  cachemode2pgprot(set_type));
2570 	if (!ret && new_type == _PAGE_CACHE_MODE_WC)
2571 		ret = change_page_attr_set_clr(NULL, numpages,
2572 					       cachemode2pgprot(
2573 						_PAGE_CACHE_MODE_WC),
2574 					       __pgprot(_PAGE_CACHE_MASK),
2575 					       0, CPA_PAGES_ARRAY, pages);
2576 	if (ret)
2577 		goto err_out;
2578 	return 0; /* Success */
2579 err_out:
2580 	free_idx = i;
2581 	for (i = 0; i < free_idx; i++) {
2582 		if (PageHighMem(pages[i]))
2583 			continue;
2584 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2585 		end = start + PAGE_SIZE;
2586 		memtype_free(start, end);
2587 	}
2588 	return -EINVAL;
2589 }
2590 
set_pages_array_uc(struct page ** pages,int numpages)2591 int set_pages_array_uc(struct page **pages, int numpages)
2592 {
2593 	return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_UC_MINUS);
2594 }
2595 EXPORT_SYMBOL(set_pages_array_uc);
2596 
set_pages_array_wc(struct page ** pages,int numpages)2597 int set_pages_array_wc(struct page **pages, int numpages)
2598 {
2599 	return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_WC);
2600 }
2601 EXPORT_SYMBOL(set_pages_array_wc);
2602 
set_pages_wb(struct page * page,int numpages)2603 int set_pages_wb(struct page *page, int numpages)
2604 {
2605 	unsigned long addr = (unsigned long)page_address(page);
2606 
2607 	return set_memory_wb(addr, numpages);
2608 }
2609 EXPORT_SYMBOL(set_pages_wb);
2610 
set_pages_array_wb(struct page ** pages,int numpages)2611 int set_pages_array_wb(struct page **pages, int numpages)
2612 {
2613 	int retval;
2614 	unsigned long start;
2615 	unsigned long end;
2616 	int i;
2617 
2618 	/* WB cache mode is hard wired to all cache attribute bits being 0 */
2619 	retval = cpa_clear_pages_array(pages, numpages,
2620 			__pgprot(_PAGE_CACHE_MASK));
2621 	if (retval)
2622 		return retval;
2623 
2624 	for (i = 0; i < numpages; i++) {
2625 		if (PageHighMem(pages[i]))
2626 			continue;
2627 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2628 		end = start + PAGE_SIZE;
2629 		memtype_free(start, end);
2630 	}
2631 
2632 	return 0;
2633 }
2634 EXPORT_SYMBOL(set_pages_array_wb);
2635 
set_pages_ro(struct page * page,int numpages)2636 int set_pages_ro(struct page *page, int numpages)
2637 {
2638 	unsigned long addr = (unsigned long)page_address(page);
2639 
2640 	return set_memory_ro(addr, numpages);
2641 }
2642 
set_pages_rw(struct page * page,int numpages)2643 int set_pages_rw(struct page *page, int numpages)
2644 {
2645 	unsigned long addr = (unsigned long)page_address(page);
2646 
2647 	return set_memory_rw(addr, numpages);
2648 }
2649 
__set_pages_p(struct page * page,int numpages,unsigned int cpa_flags)2650 static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags)
2651 {
2652 	unsigned long tempaddr = (unsigned long) page_address(page);
2653 	struct cpa_data cpa = { .vaddr = &tempaddr,
2654 				.pgd = NULL,
2655 				.numpages = numpages,
2656 				.mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
2657 				.mask_clr = __pgprot(0),
2658 				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
2659 
2660 	/*
2661 	 * No alias checking needed for setting present flag. otherwise,
2662 	 * we may need to break large pages for 64-bit kernel text
2663 	 * mappings (this adds to complexity if we want to do this from
2664 	 * atomic context especially). Let's keep it simple!
2665 	 */
2666 	return __change_page_attr_set_clr(&cpa, 1);
2667 }
2668 
__set_pages_np(struct page * page,int numpages,unsigned int cpa_flags)2669 static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flags)
2670 {
2671 	unsigned long tempaddr = (unsigned long) page_address(page);
2672 	struct cpa_data cpa = { .vaddr = &tempaddr,
2673 				.pgd = NULL,
2674 				.numpages = numpages,
2675 				.mask_set = __pgprot(0),
2676 				.mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
2677 				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
2678 
2679 	/*
2680 	 * No alias checking needed for setting not present flag. otherwise,
2681 	 * we may need to break large pages for 64-bit kernel text
2682 	 * mappings (this adds to complexity if we want to do this from
2683 	 * atomic context especially). Let's keep it simple!
2684 	 */
2685 	return __change_page_attr_set_clr(&cpa, 1);
2686 }
2687 
set_direct_map_invalid_noflush(struct page * page)2688 int set_direct_map_invalid_noflush(struct page *page)
2689 {
2690 	return __set_pages_np(page, 1, 0);
2691 }
2692 
set_direct_map_default_noflush(struct page * page)2693 int set_direct_map_default_noflush(struct page *page)
2694 {
2695 	return __set_pages_p(page, 1, 0);
2696 }
2697 
set_direct_map_valid_noflush(struct page * page,unsigned nr,bool valid)2698 int set_direct_map_valid_noflush(struct page *page, unsigned nr, bool valid)
2699 {
2700 	if (valid)
2701 		return __set_pages_p(page, nr, 0);
2702 
2703 	return __set_pages_np(page, nr, 0);
2704 }
2705 
2706 #ifdef CONFIG_DEBUG_PAGEALLOC
__kernel_map_pages(struct page * page,int numpages,int enable)2707 void __kernel_map_pages(struct page *page, int numpages, int enable)
2708 {
2709 	if (PageHighMem(page))
2710 		return;
2711 	if (!enable) {
2712 		debug_check_no_locks_freed(page_address(page),
2713 					   numpages * PAGE_SIZE);
2714 	}
2715 
2716 	/*
2717 	 * The return value is ignored as the calls cannot fail.
2718 	 * Large pages for identity mappings are not used at boot time
2719 	 * and hence no memory allocations during large page split.
2720 	 */
2721 	if (enable)
2722 		__set_pages_p(page, numpages, CPA_DEBUG_PAGEALLOC);
2723 	else
2724 		__set_pages_np(page, numpages, CPA_DEBUG_PAGEALLOC);
2725 
2726 	/*
2727 	 * We should perform an IPI and flush all tlbs, but that can
2728 	 * deadlock, settle for a local flush.
2729 	 *
2730 	 * Not doing a global TLB flush means that remote CPUs will retain
2731 	 * stale TLB entries. In case of P->NP (on free) this means the remote
2732 	 * CPUs will not take the faults, making the debug scheme less
2733 	 * reliable. On the NP->P (on alloc) this means the remote CPUs can
2734 	 * take a spurious fault. However spurious_kernel_fault() will observe
2735 	 * *_present() and fix it up.
2736 	 *
2737 	 * Preemption needs to be disabled around __flush_tlb_all() due to CR3
2738 	 * reload in __native_flush_tlb().
2739 	 */
2740 	preempt_disable();
2741 	__flush_tlb_all();
2742 	preempt_enable();
2743 
2744 	arch_flush_lazy_mmu_mode();
2745 }
2746 #endif /* CONFIG_DEBUG_PAGEALLOC */
2747 
kernel_page_present(struct page * page)2748 bool kernel_page_present(struct page *page)
2749 {
2750 	unsigned int level;
2751 	pte_t *pte;
2752 
2753 	if (PageHighMem(page))
2754 		return false;
2755 
2756 	pte = lookup_address((unsigned long)page_address(page), &level);
2757 	return (pte_val(*pte) & _PAGE_PRESENT);
2758 }
2759 
kernel_map_pages_in_pgd(pgd_t * pgd,u64 pfn,unsigned long address,unsigned numpages,unsigned long page_flags)2760 int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
2761 				   unsigned numpages, unsigned long page_flags)
2762 {
2763 	int retval = -EINVAL;
2764 
2765 	struct cpa_data cpa = {
2766 		.vaddr = &address,
2767 		.pfn = pfn,
2768 		.pgd = pgd,
2769 		.numpages = numpages,
2770 		.mask_set = __pgprot(0),
2771 		.mask_clr = __pgprot(~page_flags & (_PAGE_NX|_PAGE_RW|_PAGE_DIRTY)),
2772 		.flags = CPA_NO_CHECK_ALIAS,
2773 	};
2774 
2775 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
2776 
2777 	if (!(__supported_pte_mask & _PAGE_NX))
2778 		goto out;
2779 
2780 	if (!(page_flags & _PAGE_ENC))
2781 		cpa.mask_clr = pgprot_encrypted(cpa.mask_clr);
2782 
2783 	cpa.mask_set = __pgprot(_PAGE_PRESENT | page_flags);
2784 
2785 	retval = __change_page_attr_set_clr(&cpa, 1);
2786 	__flush_tlb_all();
2787 
2788 out:
2789 	return retval;
2790 }
2791 
2792 /*
2793  * __flush_tlb_all() flushes mappings only on current CPU and hence this
2794  * function shouldn't be used in an SMP environment. Presently, it's used only
2795  * during boot (way before smp_init()) by EFI subsystem and hence is ok.
2796  */
kernel_unmap_pages_in_pgd(pgd_t * pgd,unsigned long address,unsigned long numpages)2797 int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
2798 				     unsigned long numpages)
2799 {
2800 	int retval;
2801 
2802 	/*
2803 	 * The typical sequence for unmapping is to find a pte through
2804 	 * lookup_address_in_pgd() (ideally, it should never return NULL because
2805 	 * the address is already mapped) and change its protections. As pfn is
2806 	 * the *target* of a mapping, it's not useful while unmapping.
2807 	 */
2808 	struct cpa_data cpa = {
2809 		.vaddr		= &address,
2810 		.pfn		= 0,
2811 		.pgd		= pgd,
2812 		.numpages	= numpages,
2813 		.mask_set	= __pgprot(0),
2814 		.mask_clr	= __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
2815 		.flags		= CPA_NO_CHECK_ALIAS,
2816 	};
2817 
2818 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
2819 
2820 	retval = __change_page_attr_set_clr(&cpa, 1);
2821 	__flush_tlb_all();
2822 
2823 	return retval;
2824 }
2825 
2826 /*
2827  * The testcases use internal knowledge of the implementation that shouldn't
2828  * be exposed to the rest of the kernel. Include these directly here.
2829  */
2830 #ifdef CONFIG_CPA_DEBUG
2831 #include "cpa-test.c"
2832 #endif
2833