xref: /linux/arch/x86/mm/pat/set_memory.c (revision 568b4576b2739d8e84509e2f7bb68d12a8b0a764)
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 
723 	/*
724 	 * If the kernel text is still RWX, gently complain, this could be a
725 	 * false positive.
726 	 * Once debug_checkwx() becomes mandatory for CONFIG_STRICT_KERNEL_RWX,
727 	 * the warning can be removed completely.
728 	 */
729 	if (!kernel_set_to_readonly) {
730 		pr_warn_once("CPA detected W^X violation: %016llx -> %016llx range: 0x%016lx - 0x%016lx PFN %lx\n",
731 		  (unsigned long long)pgprot_val(old),
732 		  (unsigned long long)pgprot_val(new),
733 		  start, end, pfn);
734 		return new;
735 	}
736 
737 	WARN_ONCE(1, "CPA detected W^X violation: %016llx -> %016llx range: 0x%016lx - 0x%016lx PFN %lx\n",
738 		  (unsigned long long)pgprot_val(old),
739 		  (unsigned long long)pgprot_val(new),
740 		  start, end, pfn);
741 
742 	/*
743 	 * For now, allow all permission change attempts by returning the
744 	 * attempted permissions.  This can 'return old' to actively
745 	 * refuse the permission change at a later time.
746 	 */
747 	return new;
748 }
749 
750 /*
751  * Lookup the page table entry for a virtual address in a specific pgd.
752  * Return a pointer to the entry (or NULL if the entry does not exist),
753  * the level of the entry, and the effective NX and RW bits of all
754  * page table levels.
755  */
lookup_address_in_pgd_attr(pgd_t * pgd,unsigned long address,unsigned int * level,bool * nx,bool * rw)756 pte_t *lookup_address_in_pgd_attr(pgd_t *pgd, unsigned long address,
757 				  unsigned int *level, bool *nx, bool *rw)
758 {
759 	p4d_t *p4d;
760 	pud_t *pud;
761 	pmd_t *pmd;
762 
763 	*level = PG_LEVEL_256T;
764 	*nx = false;
765 	*rw = true;
766 
767 	if (pgd_none(*pgd))
768 		return NULL;
769 
770 	*level = PG_LEVEL_512G;
771 	*nx |= pgd_flags(*pgd) & _PAGE_NX;
772 	*rw &= !!(pgd_flags(*pgd) & _PAGE_RW);
773 
774 	p4d = p4d_offset(pgd, address);
775 	if (p4d_none(*p4d))
776 		return NULL;
777 
778 	if (p4d_leaf(*p4d) || !p4d_present(*p4d))
779 		return (pte_t *)p4d;
780 
781 	*level = PG_LEVEL_1G;
782 	*nx |= p4d_flags(*p4d) & _PAGE_NX;
783 	*rw &= !!(p4d_flags(*p4d) & _PAGE_RW);
784 
785 	pud = pud_offset(p4d, address);
786 	if (pud_none(*pud))
787 		return NULL;
788 
789 	if (pud_leaf(*pud) || !pud_present(*pud))
790 		return (pte_t *)pud;
791 
792 	*level = PG_LEVEL_2M;
793 	*nx |= pud_flags(*pud) & _PAGE_NX;
794 	*rw &= !!(pud_flags(*pud) & _PAGE_RW);
795 
796 	pmd = pmd_offset(pud, address);
797 	if (pmd_none(*pmd))
798 		return NULL;
799 
800 	if (pmd_leaf(*pmd) || !pmd_present(*pmd))
801 		return (pte_t *)pmd;
802 
803 	*level = PG_LEVEL_4K;
804 	*nx |= pmd_flags(*pmd) & _PAGE_NX;
805 	*rw &= !!(pmd_flags(*pmd) & _PAGE_RW);
806 
807 	return pte_offset_kernel(pmd, address);
808 }
809 
810 /*
811  * Lookup the page table entry for a virtual address in a specific pgd.
812  * Return a pointer to the entry and the level of the mapping.
813  */
lookup_address_in_pgd(pgd_t * pgd,unsigned long address,unsigned int * level)814 pte_t *lookup_address_in_pgd(pgd_t *pgd, unsigned long address,
815 			     unsigned int *level)
816 {
817 	bool nx, rw;
818 
819 	return lookup_address_in_pgd_attr(pgd, address, level, &nx, &rw);
820 }
821 
822 /*
823  * Lookup the page table entry for a virtual address. Return a pointer
824  * to the entry and the level of the mapping.
825  *
826  * Note: the function returns p4d, pud or pmd either when the entry is marked
827  * large or when the present bit is not set. Otherwise it returns NULL.
828  */
lookup_address(unsigned long address,unsigned int * level)829 pte_t *lookup_address(unsigned long address, unsigned int *level)
830 {
831 	return lookup_address_in_pgd(pgd_offset_k(address), address, level);
832 }
833 EXPORT_SYMBOL_GPL(lookup_address);
834 
_lookup_address_cpa(struct cpa_data * cpa,unsigned long address,unsigned int * level,bool * nx,bool * rw)835 static pte_t *_lookup_address_cpa(struct cpa_data *cpa, unsigned long address,
836 				  unsigned int *level, bool *nx, bool *rw)
837 {
838 	pgd_t *pgd;
839 
840 	if (!cpa->pgd)
841 		pgd = pgd_offset_k(address);
842 	else
843 		pgd = cpa->pgd + pgd_index(address);
844 
845 	return lookup_address_in_pgd_attr(pgd, address, level, nx, rw);
846 }
847 
848 /*
849  * Lookup the PMD entry for a virtual address. Return a pointer to the entry
850  * or NULL if not present.
851  */
lookup_pmd_address(unsigned long address)852 pmd_t *lookup_pmd_address(unsigned long address)
853 {
854 	pgd_t *pgd;
855 	p4d_t *p4d;
856 	pud_t *pud;
857 
858 	pgd = pgd_offset_k(address);
859 	if (pgd_none(*pgd))
860 		return NULL;
861 
862 	p4d = p4d_offset(pgd, address);
863 	if (p4d_none(*p4d) || p4d_leaf(*p4d) || !p4d_present(*p4d))
864 		return NULL;
865 
866 	pud = pud_offset(p4d, address);
867 	if (pud_none(*pud) || pud_leaf(*pud) || !pud_present(*pud))
868 		return NULL;
869 
870 	return pmd_offset(pud, address);
871 }
872 
873 /*
874  * This is necessary because __pa() does not work on some
875  * kinds of memory, like vmalloc() or the alloc_remap()
876  * areas on 32-bit NUMA systems.  The percpu areas can
877  * end up in this kind of memory, for instance.
878  *
879  * Note that as long as the PTEs are well-formed with correct PFNs, this
880  * works without checking the PRESENT bit in the leaf PTE.  This is unlike
881  * the similar vmalloc_to_page() and derivatives.  Callers may depend on
882  * this behavior.
883  *
884  * This could be optimized, but it is only used in paths that are not perf
885  * sensitive, and keeping it unoptimized should increase the testing coverage
886  * for the more obscure platforms.
887  */
slow_virt_to_phys(void * __virt_addr)888 phys_addr_t slow_virt_to_phys(void *__virt_addr)
889 {
890 	unsigned long virt_addr = (unsigned long)__virt_addr;
891 	phys_addr_t phys_addr;
892 	unsigned long offset;
893 	enum pg_level level;
894 	pte_t *pte;
895 
896 	pte = lookup_address(virt_addr, &level);
897 	BUG_ON(!pte);
898 
899 	/*
900 	 * pXX_pfn() returns unsigned long, which must be cast to phys_addr_t
901 	 * before being left-shifted PAGE_SHIFT bits -- this trick is to
902 	 * make 32-PAE kernel work correctly.
903 	 */
904 	switch (level) {
905 	case PG_LEVEL_1G:
906 		phys_addr = (phys_addr_t)pud_pfn(*(pud_t *)pte) << PAGE_SHIFT;
907 		offset = virt_addr & ~PUD_MASK;
908 		break;
909 	case PG_LEVEL_2M:
910 		phys_addr = (phys_addr_t)pmd_pfn(*(pmd_t *)pte) << PAGE_SHIFT;
911 		offset = virt_addr & ~PMD_MASK;
912 		break;
913 	default:
914 		phys_addr = (phys_addr_t)pte_pfn(*pte) << PAGE_SHIFT;
915 		offset = virt_addr & ~PAGE_MASK;
916 	}
917 
918 	return (phys_addr_t)(phys_addr | offset);
919 }
920 EXPORT_SYMBOL_GPL(slow_virt_to_phys);
921 
922 /*
923  * Set the new pmd in all the pgds we know about:
924  */
__set_pmd_pte(pte_t * kpte,unsigned long address,pte_t pte)925 static void __set_pmd_pte(pte_t *kpte, unsigned long address, pte_t pte)
926 {
927 	/* change init_mm */
928 	set_pte_atomic(kpte, pte);
929 
930 	if (IS_ENABLED(CONFIG_X86_32)) {
931 		struct ptdesc *ptdesc;
932 
933 		list_for_each_entry(ptdesc, &pgd_list, pt_list) {
934 			pgd_t *pgd;
935 			p4d_t *p4d;
936 			pud_t *pud;
937 			pmd_t *pmd;
938 
939 			pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(address);
940 			p4d = p4d_offset(pgd, address);
941 			pud = pud_offset(p4d, address);
942 			pmd = pmd_offset(pud, address);
943 			set_pte_atomic((pte_t *)pmd, pte);
944 		}
945 	}
946 }
947 
pgprot_clear_protnone_bits(pgprot_t prot)948 static pgprot_t pgprot_clear_protnone_bits(pgprot_t prot)
949 {
950 	/*
951 	 * _PAGE_GLOBAL means "global page" for present PTEs.
952 	 * But, it is also used to indicate _PAGE_PROTNONE
953 	 * for non-present PTEs.
954 	 *
955 	 * This ensures that a _PAGE_GLOBAL PTE going from
956 	 * present to non-present is not confused as
957 	 * _PAGE_PROTNONE.
958 	 */
959 	if (!(pgprot_val(prot) & _PAGE_PRESENT))
960 		pgprot_val(prot) &= ~_PAGE_GLOBAL;
961 
962 	return prot;
963 }
964 
__should_split_large_page(pte_t * kpte,unsigned long address,struct cpa_data * cpa)965 static int __should_split_large_page(pte_t *kpte, unsigned long address,
966 				     struct cpa_data *cpa)
967 {
968 	unsigned long numpages, pmask, psize, lpaddr, pfn, old_pfn;
969 	pgprot_t old_prot, new_prot, req_prot, chk_prot;
970 	pte_t new_pte, *tmp;
971 	enum pg_level level;
972 	bool nx, rw;
973 
974 	/*
975 	 * Check for races, another CPU might have split this page
976 	 * up already:
977 	 */
978 	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
979 	if (tmp != kpte)
980 		return 1;
981 
982 	switch (level) {
983 	case PG_LEVEL_2M:
984 		old_prot = pmd_pgprot(*(pmd_t *)kpte);
985 		old_pfn = pmd_pfn(*(pmd_t *)kpte);
986 		cpa_inc_2m_checked();
987 		break;
988 	case PG_LEVEL_1G:
989 		old_prot = pud_pgprot(*(pud_t *)kpte);
990 		old_pfn = pud_pfn(*(pud_t *)kpte);
991 		cpa_inc_1g_checked();
992 		break;
993 	default:
994 		return -EINVAL;
995 	}
996 
997 	psize = page_level_size(level);
998 	pmask = page_level_mask(level);
999 
1000 	/*
1001 	 * Calculate the number of pages, which fit into this large
1002 	 * page starting at address:
1003 	 */
1004 	lpaddr = (address + psize) & pmask;
1005 	numpages = (lpaddr - address) >> PAGE_SHIFT;
1006 	if (numpages < cpa->numpages)
1007 		cpa->numpages = numpages;
1008 
1009 	/*
1010 	 * We are safe now. Check whether the new pgprot is the same:
1011 	 * Convert protection attributes to 4k-format, as cpa->mask* are set
1012 	 * up accordingly.
1013 	 */
1014 
1015 	/* Clear PSE (aka _PAGE_PAT) and move PAT bit to correct position */
1016 	req_prot = pgprot_large_2_4k(old_prot);
1017 
1018 	pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
1019 	pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
1020 
1021 	/*
1022 	 * req_prot is in format of 4k pages. It must be converted to large
1023 	 * page format: the caching mode includes the PAT bit located at
1024 	 * different bit positions in the two formats.
1025 	 */
1026 	req_prot = pgprot_4k_2_large(req_prot);
1027 	req_prot = pgprot_clear_protnone_bits(req_prot);
1028 	if (pgprot_val(req_prot) & _PAGE_PRESENT)
1029 		pgprot_val(req_prot) |= _PAGE_PSE;
1030 
1031 	/*
1032 	 * old_pfn points to the large page base pfn. So we need to add the
1033 	 * offset of the virtual address:
1034 	 */
1035 	pfn = old_pfn + ((address & (psize - 1)) >> PAGE_SHIFT);
1036 	cpa->pfn = pfn;
1037 
1038 	/*
1039 	 * Calculate the large page base address and the number of 4K pages
1040 	 * in the large page
1041 	 */
1042 	lpaddr = address & pmask;
1043 	numpages = psize >> PAGE_SHIFT;
1044 
1045 	/*
1046 	 * Sanity check that the existing mapping is correct versus the static
1047 	 * protections. static_protections() guards against !PRESENT, so no
1048 	 * extra conditional required here.
1049 	 */
1050 	chk_prot = static_protections(old_prot, lpaddr, old_pfn, numpages,
1051 				      psize, CPA_CONFLICT);
1052 
1053 	if (WARN_ON_ONCE(pgprot_val(chk_prot) != pgprot_val(old_prot))) {
1054 		/*
1055 		 * Split the large page and tell the split code to
1056 		 * enforce static protections.
1057 		 */
1058 		cpa->force_static_prot = 1;
1059 		return 1;
1060 	}
1061 
1062 	/*
1063 	 * Optimization: If the requested pgprot is the same as the current
1064 	 * pgprot, then the large page can be preserved and no updates are
1065 	 * required independent of alignment and length of the requested
1066 	 * range. The above already established that the current pgprot is
1067 	 * correct, which in consequence makes the requested pgprot correct
1068 	 * as well if it is the same. The static protection scan below will
1069 	 * not come to a different conclusion.
1070 	 */
1071 	if (pgprot_val(req_prot) == pgprot_val(old_prot)) {
1072 		cpa_inc_lp_sameprot(level);
1073 		return 0;
1074 	}
1075 
1076 	/*
1077 	 * If the requested range does not cover the full page, split it up
1078 	 */
1079 	if (address != lpaddr || cpa->numpages != numpages)
1080 		return 1;
1081 
1082 	/*
1083 	 * Check whether the requested pgprot is conflicting with a static
1084 	 * protection requirement in the large page.
1085 	 */
1086 	new_prot = static_protections(req_prot, lpaddr, old_pfn, numpages,
1087 				      psize, CPA_DETECT);
1088 
1089 	new_prot = verify_rwx(old_prot, new_prot, lpaddr, old_pfn, numpages,
1090 			      nx, rw);
1091 
1092 	/*
1093 	 * If there is a conflict, split the large page.
1094 	 *
1095 	 * There used to be a 4k wise evaluation trying really hard to
1096 	 * preserve the large pages, but experimentation has shown, that this
1097 	 * does not help at all. There might be corner cases which would
1098 	 * preserve one large page occasionally, but it's really not worth the
1099 	 * extra code and cycles for the common case.
1100 	 */
1101 	if (pgprot_val(req_prot) != pgprot_val(new_prot))
1102 		return 1;
1103 
1104 	/* All checks passed. Update the large page mapping. */
1105 	new_pte = pfn_pte(old_pfn, new_prot);
1106 	__set_pmd_pte(kpte, address, new_pte);
1107 	cpa->flags |= CPA_FLUSHTLB;
1108 	cpa_inc_lp_preserved(level);
1109 	return 0;
1110 }
1111 
should_split_large_page(pte_t * kpte,unsigned long address,struct cpa_data * cpa)1112 static int should_split_large_page(pte_t *kpte, unsigned long address,
1113 				   struct cpa_data *cpa)
1114 {
1115 	if (cpa->force_split)
1116 		return 1;
1117 
1118 	guard(spinlock)(&pgd_lock);
1119 	return __should_split_large_page(kpte, address, cpa);
1120 }
1121 
split_set_pte(struct cpa_data * cpa,pte_t * pte,unsigned long pfn,pgprot_t ref_prot,unsigned long address,unsigned long size)1122 static void split_set_pte(struct cpa_data *cpa, pte_t *pte, unsigned long pfn,
1123 			  pgprot_t ref_prot, unsigned long address,
1124 			  unsigned long size)
1125 {
1126 	unsigned int npg = PFN_DOWN(size);
1127 	pgprot_t prot;
1128 
1129 	/*
1130 	 * If should_split_large_page() discovered an inconsistent mapping,
1131 	 * remove the invalid protection in the split mapping.
1132 	 */
1133 	if (!cpa->force_static_prot)
1134 		goto set;
1135 
1136 	/* Hand in lpsize = 0 to enforce the protection mechanism */
1137 	prot = static_protections(ref_prot, address, pfn, npg, 0, CPA_PROTECT);
1138 
1139 	if (pgprot_val(prot) == pgprot_val(ref_prot))
1140 		goto set;
1141 
1142 	/*
1143 	 * If this is splitting a PMD, fix it up. PUD splits cannot be
1144 	 * fixed trivially as that would require to rescan the newly
1145 	 * installed PMD mappings after returning from split_large_page()
1146 	 * so an eventual further split can allocate the necessary PTE
1147 	 * pages. Warn for now and revisit it in case this actually
1148 	 * happens.
1149 	 */
1150 	if (size == PAGE_SIZE)
1151 		ref_prot = prot;
1152 	else
1153 		pr_warn_once("CPA: Cannot fixup static protections for PUD split\n");
1154 set:
1155 	set_pte(pte, pfn_pte(pfn, ref_prot));
1156 }
1157 
1158 static int
__split_large_page(struct cpa_data * cpa,pte_t * kpte,unsigned long address,pte_t * pbase)1159 __split_large_page(struct cpa_data *cpa, pte_t *kpte, unsigned long address,
1160 		   pte_t *pbase)
1161 {
1162 	unsigned long lpaddr, lpinc, ref_pfn, pfn, pfninc = 1;
1163 	struct page *base = virt_to_page(pbase);
1164 	unsigned int i, level;
1165 	pgprot_t ref_prot;
1166 	bool nx, rw;
1167 	pte_t *tmp;
1168 
1169 	guard(spinlock)(&pgd_lock);
1170 	/*
1171 	 * Check for races, another CPU might have split this page
1172 	 * up for us already:
1173 	 */
1174 	tmp = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
1175 	if (tmp != kpte)
1176 		return 1;
1177 
1178 	paravirt_alloc_pte(&init_mm, page_to_pfn(base));
1179 
1180 	switch (level) {
1181 	case PG_LEVEL_2M:
1182 		ref_prot = pmd_pgprot(*(pmd_t *)kpte);
1183 		/*
1184 		 * Clear PSE (aka _PAGE_PAT) and move
1185 		 * PAT bit to correct position.
1186 		 */
1187 		ref_prot = pgprot_large_2_4k(ref_prot);
1188 		ref_pfn = pmd_pfn(*(pmd_t *)kpte);
1189 		lpaddr = address & PMD_MASK;
1190 		lpinc = PAGE_SIZE;
1191 		break;
1192 
1193 	case PG_LEVEL_1G:
1194 		ref_prot = pud_pgprot(*(pud_t *)kpte);
1195 		ref_pfn = pud_pfn(*(pud_t *)kpte);
1196 		pfninc = PMD_SIZE >> PAGE_SHIFT;
1197 		lpaddr = address & PUD_MASK;
1198 		lpinc = PMD_SIZE;
1199 		/*
1200 		 * Clear the PSE flags if the PRESENT flag is not set
1201 		 * otherwise pmd_present() will return true even on a non
1202 		 * present pmd.
1203 		 */
1204 		if (!(pgprot_val(ref_prot) & _PAGE_PRESENT))
1205 			pgprot_val(ref_prot) &= ~_PAGE_PSE;
1206 		break;
1207 
1208 	default:
1209 		return 1;
1210 	}
1211 
1212 	ref_prot = pgprot_clear_protnone_bits(ref_prot);
1213 
1214 	/*
1215 	 * Get the target pfn from the original entry:
1216 	 */
1217 	pfn = ref_pfn;
1218 	for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc, lpaddr += lpinc)
1219 		split_set_pte(cpa, pbase + i, pfn, ref_prot, lpaddr, lpinc);
1220 
1221 	if (virt_addr_valid(address)) {
1222 		unsigned long pfn = PFN_DOWN(__pa(address));
1223 
1224 		if (pfn_range_is_mapped(pfn, pfn + 1))
1225 			split_page_count(level);
1226 	}
1227 
1228 	/*
1229 	 * Install the new, split up pagetable.
1230 	 *
1231 	 * We use the standard kernel pagetable protections for the new
1232 	 * pagetable protections, the actual ptes set above control the
1233 	 * primary protection behavior:
1234 	 */
1235 	__set_pmd_pte(kpte, address, mk_pte(base, __pgprot(_KERNPG_TABLE)));
1236 
1237 	/*
1238 	 * Do a global flush tlb after splitting the large page
1239 	 * and before we do the actual change page attribute in the PTE.
1240 	 *
1241 	 * Without this, we violate the TLB application note, that says:
1242 	 * "The TLBs may contain both ordinary and large-page
1243 	 *  translations for a 4-KByte range of linear addresses. This
1244 	 *  may occur if software modifies the paging structures so that
1245 	 *  the page size used for the address range changes. If the two
1246 	 *  translations differ with respect to page frame or attributes
1247 	 *  (e.g., permissions), processor behavior is undefined and may
1248 	 *  be implementation-specific."
1249 	 *
1250 	 * We do this global tlb flush inside the cpa_lock, so that we
1251 	 * don't allow any other cpu, with stale tlb entries change the
1252 	 * page attribute in parallel, that also falls into the
1253 	 * just split large page entry.
1254 	 */
1255 	flush_tlb_all();
1256 
1257 	return 0;
1258 }
1259 
split_large_page(struct cpa_data * cpa,pte_t * kpte,unsigned long address)1260 static int split_large_page(struct cpa_data *cpa, pte_t *kpte,
1261 			    unsigned long address)
1262 {
1263 	pte_t *pte;
1264 
1265 	spin_unlock(&cpa_lock);
1266 	if (cpa->init_mm_read_locked)
1267 		mmap_read_unlock(&init_mm);
1268 	pte = pte_alloc_one_kernel(&init_mm);
1269 	if (cpa->init_mm_read_locked)
1270 		mmap_read_lock(&init_mm);
1271 	spin_lock(&cpa_lock);
1272 	if (!pte)
1273 		return -ENOMEM;
1274 
1275 	if (__split_large_page(cpa, kpte, address, pte))
1276 		pte_free_kernel(&init_mm, pte);
1277 
1278 	return 0;
1279 }
1280 
collapse_pmd_page(pmd_t * pmd,unsigned long addr,struct list_head * pgtables)1281 static int collapse_pmd_page(pmd_t *pmd, unsigned long addr,
1282 			     struct list_head *pgtables)
1283 {
1284 	pmd_t _pmd, old_pmd;
1285 	pte_t *pte, first;
1286 	unsigned long pfn;
1287 	pgprot_t pgprot;
1288 	int i = 0;
1289 
1290 	if (!cpu_feature_enabled(X86_FEATURE_PSE))
1291 		return 0;
1292 
1293 	addr &= PMD_MASK;
1294 	pte = pte_offset_kernel(pmd, addr);
1295 	first = *pte;
1296 	pfn = pte_pfn(first);
1297 
1298 	/* Make sure alignment is suitable */
1299 	if (PFN_PHYS(pfn) & ~PMD_MASK)
1300 		return 0;
1301 
1302 	/* The page is 4k intentionally */
1303 	if (pte_flags(first) & _PAGE_KERNEL_4K)
1304 		return 0;
1305 
1306 	/* Check that the rest of PTEs are compatible with the first one */
1307 	for (i = 1, pte++; i < PTRS_PER_PTE; i++, pte++) {
1308 		pte_t entry = *pte;
1309 
1310 		if (!pte_present(entry))
1311 			return 0;
1312 		if (pte_flags(entry) != pte_flags(first))
1313 			return 0;
1314 		if (pte_pfn(entry) != pte_pfn(first) + i)
1315 			return 0;
1316 	}
1317 
1318 	old_pmd = *pmd;
1319 
1320 	/* Success: set up a large page */
1321 	pgprot = pgprot_4k_2_large(pte_pgprot(first));
1322 	pgprot_val(pgprot) |= _PAGE_PSE;
1323 	_pmd = pfn_pmd(pfn, pgprot);
1324 	set_pmd(pmd, _pmd);
1325 
1326 	/* Queue the page table to be freed after TLB flush */
1327 	list_add(&page_ptdesc(pmd_page(old_pmd))->pt_list, pgtables);
1328 
1329 	if (IS_ENABLED(CONFIG_X86_32)) {
1330 		struct ptdesc *ptdesc;
1331 
1332 		/* Update all PGD tables to use the same large page */
1333 		list_for_each_entry(ptdesc, &pgd_list, pt_list) {
1334 			pgd_t *pgd = (pgd_t *)ptdesc_address(ptdesc) + pgd_index(addr);
1335 			p4d_t *p4d = p4d_offset(pgd, addr);
1336 			pud_t *pud = pud_offset(p4d, addr);
1337 			pmd_t *pmd = pmd_offset(pud, addr);
1338 			/* Something is wrong if entries doesn't match */
1339 			if (WARN_ON(pmd_val(old_pmd) != pmd_val(*pmd)))
1340 				continue;
1341 			set_pmd(pmd, _pmd);
1342 		}
1343 	}
1344 
1345 	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
1346 		collapse_page_count(PG_LEVEL_2M);
1347 
1348 	return 1;
1349 }
1350 
collapse_pud_page(pud_t * pud,unsigned long addr,struct list_head * pgtables)1351 static int collapse_pud_page(pud_t *pud, unsigned long addr,
1352 			     struct list_head *pgtables)
1353 {
1354 	unsigned long pfn;
1355 	pmd_t *pmd, first;
1356 	int i;
1357 
1358 	if (!direct_gbpages)
1359 		return 0;
1360 
1361 	addr &= PUD_MASK;
1362 	pmd = pmd_offset(pud, addr);
1363 	first = *pmd;
1364 
1365 	/*
1366 	 * To restore PUD page all PMD entries must be large and
1367 	 * have suitable alignment
1368 	 */
1369 	pfn = pmd_pfn(first);
1370 	if (!pmd_leaf(first) || (PFN_PHYS(pfn) & ~PUD_MASK))
1371 		return 0;
1372 
1373 	/*
1374 	 * To restore PUD page, all following PMDs must be compatible with the
1375 	 * first one.
1376 	 */
1377 	for (i = 1, pmd++; i < PTRS_PER_PMD; i++, pmd++) {
1378 		pmd_t entry = *pmd;
1379 
1380 		if (!pmd_present(entry) || !pmd_leaf(entry))
1381 			return 0;
1382 		if (pmd_flags(entry) != pmd_flags(first))
1383 			return 0;
1384 		if (pmd_pfn(entry) != pmd_pfn(first) + i * PTRS_PER_PTE)
1385 			return 0;
1386 	}
1387 
1388 	/* Restore PUD page and queue page table to be freed after TLB flush */
1389 	list_add(&page_ptdesc(pud_page(*pud))->pt_list, pgtables);
1390 	set_pud(pud, pfn_pud(pfn, pmd_pgprot(first)));
1391 
1392 	if (virt_addr_valid(addr) && pfn_range_is_mapped(pfn, pfn + 1))
1393 		collapse_page_count(PG_LEVEL_1G);
1394 
1395 	return 1;
1396 }
1397 
1398 /*
1399  * Collapse PMD and PUD pages in the kernel mapping around the address where
1400  * possible.
1401  *
1402  * Caller must flush TLB and free page tables queued on the list before
1403  * touching the new entries. CPU must not see TLB entries of different size
1404  * with different attributes.
1405  */
collapse_large_pages(unsigned long addr,struct list_head * pgtables)1406 static int collapse_large_pages(unsigned long addr, struct list_head *pgtables)
1407 {
1408 	int collapsed;
1409 	pgd_t *pgd;
1410 	p4d_t *p4d;
1411 	pud_t *pud;
1412 	pmd_t *pmd;
1413 
1414 	addr &= PMD_MASK;
1415 
1416 	guard(spinlock)(&pgd_lock);
1417 	pgd = pgd_offset_k(addr);
1418 	if (pgd_none(*pgd))
1419 		return 0;
1420 	p4d = p4d_offset(pgd, addr);
1421 	if (p4d_none(*p4d))
1422 		return 0;
1423 	pud = pud_offset(p4d, addr);
1424 	if (!pud_present(*pud) || pud_leaf(*pud))
1425 		return 0;
1426 	pmd = pmd_offset(pud, addr);
1427 	if (!pmd_present(*pmd) || pmd_leaf(*pmd))
1428 		return 0;
1429 
1430 	collapsed = collapse_pmd_page(pmd, addr, pgtables);
1431 	if (collapsed)
1432 		collapsed += collapse_pud_page(pud, addr, pgtables);
1433 
1434 	return collapsed;
1435 }
1436 
try_to_free_pte_page(pte_t * pte)1437 static bool try_to_free_pte_page(pte_t *pte)
1438 {
1439 	int i;
1440 
1441 	for (i = 0; i < PTRS_PER_PTE; i++)
1442 		if (!pte_none(pte[i]))
1443 			return false;
1444 
1445 	pte_free_kernel(&init_mm, pte);
1446 	return true;
1447 }
1448 
try_to_free_pmd_page(pmd_t * pmd)1449 static bool try_to_free_pmd_page(pmd_t *pmd)
1450 {
1451 	int i;
1452 
1453 	for (i = 0; i < PTRS_PER_PMD; i++)
1454 		if (!pmd_none(pmd[i]))
1455 			return false;
1456 
1457 	pmd_free(&init_mm, pmd);
1458 	return true;
1459 }
1460 
unmap_pte_range(pmd_t * pmd,unsigned long start,unsigned long end)1461 static bool unmap_pte_range(pmd_t *pmd, unsigned long start, unsigned long end)
1462 {
1463 	pte_t *pte = pte_offset_kernel(pmd, start);
1464 
1465 	while (start < end) {
1466 		set_pte(pte, __pte(0));
1467 
1468 		start += PAGE_SIZE;
1469 		pte++;
1470 	}
1471 
1472 	if (try_to_free_pte_page((pte_t *)pmd_page_vaddr(*pmd))) {
1473 		pmd_clear(pmd);
1474 		return true;
1475 	}
1476 	return false;
1477 }
1478 
__unmap_pmd_range(pud_t * pud,pmd_t * pmd,unsigned long start,unsigned long end)1479 static void __unmap_pmd_range(pud_t *pud, pmd_t *pmd,
1480 			      unsigned long start, unsigned long end)
1481 {
1482 	if (unmap_pte_range(pmd, start, end))
1483 		if (try_to_free_pmd_page(pud_pgtable(*pud)))
1484 			pud_clear(pud);
1485 }
1486 
unmap_pmd_range(pud_t * pud,unsigned long start,unsigned long end)1487 static void unmap_pmd_range(pud_t *pud, unsigned long start, unsigned long end)
1488 {
1489 	pmd_t *pmd = pmd_offset(pud, start);
1490 
1491 	/*
1492 	 * Not on a 2MB page boundary?
1493 	 */
1494 	if (start & (PMD_SIZE - 1)) {
1495 		unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
1496 		unsigned long pre_end = min_t(unsigned long, end, next_page);
1497 
1498 		__unmap_pmd_range(pud, pmd, start, pre_end);
1499 
1500 		start = pre_end;
1501 		pmd++;
1502 	}
1503 
1504 	/*
1505 	 * Try to unmap in 2M chunks.
1506 	 */
1507 	while (end - start >= PMD_SIZE) {
1508 		if (pmd_leaf(*pmd))
1509 			pmd_clear(pmd);
1510 		else
1511 			__unmap_pmd_range(pud, pmd, start, start + PMD_SIZE);
1512 
1513 		start += PMD_SIZE;
1514 		pmd++;
1515 	}
1516 
1517 	/*
1518 	 * 4K leftovers?
1519 	 */
1520 	if (start < end)
1521 		return __unmap_pmd_range(pud, pmd, start, end);
1522 
1523 	/*
1524 	 * Try again to free the PMD page if haven't succeeded above.
1525 	 */
1526 	if (!pud_none(*pud))
1527 		if (try_to_free_pmd_page(pud_pgtable(*pud)))
1528 			pud_clear(pud);
1529 }
1530 
unmap_pud_range(p4d_t * p4d,unsigned long start,unsigned long end)1531 static void unmap_pud_range(p4d_t *p4d, unsigned long start, unsigned long end)
1532 {
1533 	pud_t *pud = pud_offset(p4d, start);
1534 
1535 	/*
1536 	 * Not on a GB page boundary?
1537 	 */
1538 	if (start & (PUD_SIZE - 1)) {
1539 		unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
1540 		unsigned long pre_end	= min_t(unsigned long, end, next_page);
1541 
1542 		unmap_pmd_range(pud, start, pre_end);
1543 
1544 		start = pre_end;
1545 		pud++;
1546 	}
1547 
1548 	/*
1549 	 * Try to unmap in 1G chunks?
1550 	 */
1551 	while (end - start >= PUD_SIZE) {
1552 
1553 		if (pud_leaf(*pud))
1554 			pud_clear(pud);
1555 		else
1556 			unmap_pmd_range(pud, start, start + PUD_SIZE);
1557 
1558 		start += PUD_SIZE;
1559 		pud++;
1560 	}
1561 
1562 	/*
1563 	 * 2M leftovers?
1564 	 */
1565 	if (start < end)
1566 		unmap_pmd_range(pud, start, end);
1567 
1568 	/*
1569 	 * No need to try to free the PUD page because we'll free it in
1570 	 * populate_pgd's error path
1571 	 */
1572 }
1573 
alloc_pte_page(pmd_t * pmd)1574 static int alloc_pte_page(pmd_t *pmd)
1575 {
1576 	pte_t *pte = pte_alloc_one_kernel(&init_mm);
1577 	if (!pte)
1578 		return -1;
1579 
1580 	set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
1581 	return 0;
1582 }
1583 
alloc_pmd_page(pud_t * pud)1584 static int alloc_pmd_page(pud_t *pud)
1585 {
1586 	/*
1587 	 * Pass 0 as a placeholder for the second argument, since the
1588 	 * generic implementation of pmd_alloc_one() does not use it.
1589 	 */
1590 	pmd_t *pmd = pmd_alloc_one(&init_mm, 0);
1591 	if (!pmd)
1592 		return -1;
1593 
1594 	set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
1595 	return 0;
1596 }
1597 
populate_pte(struct cpa_data * cpa,unsigned long start,unsigned long end,unsigned num_pages,pmd_t * pmd,pgprot_t pgprot)1598 static void populate_pte(struct cpa_data *cpa,
1599 			 unsigned long start, unsigned long end,
1600 			 unsigned num_pages, pmd_t *pmd, pgprot_t pgprot)
1601 {
1602 	pte_t *pte;
1603 
1604 	pte = pte_offset_kernel(pmd, start);
1605 
1606 	pgprot = pgprot_clear_protnone_bits(pgprot);
1607 
1608 	while (num_pages-- && start < end) {
1609 		set_pte(pte, pfn_pte(cpa->pfn, pgprot));
1610 
1611 		start	 += PAGE_SIZE;
1612 		cpa->pfn++;
1613 		pte++;
1614 	}
1615 }
1616 
populate_pmd(struct cpa_data * cpa,unsigned long start,unsigned long end,unsigned num_pages,pud_t * pud,pgprot_t pgprot)1617 static long populate_pmd(struct cpa_data *cpa,
1618 			 unsigned long start, unsigned long end,
1619 			 unsigned num_pages, pud_t *pud, pgprot_t pgprot)
1620 {
1621 	long cur_pages = 0;
1622 	pmd_t *pmd;
1623 	pgprot_t pmd_pgprot;
1624 
1625 	/*
1626 	 * Not on a 2M boundary?
1627 	 */
1628 	if (start & (PMD_SIZE - 1)) {
1629 		unsigned long pre_end = start + (num_pages << PAGE_SHIFT);
1630 		unsigned long next_page = (start + PMD_SIZE) & PMD_MASK;
1631 
1632 		pre_end   = min_t(unsigned long, pre_end, next_page);
1633 		cur_pages = (pre_end - start) >> PAGE_SHIFT;
1634 		cur_pages = min_t(unsigned int, num_pages, cur_pages);
1635 
1636 		/*
1637 		 * Need a PTE page?
1638 		 */
1639 		pmd = pmd_offset(pud, start);
1640 		if (pmd_none(*pmd))
1641 			if (alloc_pte_page(pmd))
1642 				return -1;
1643 
1644 		populate_pte(cpa, start, pre_end, cur_pages, pmd, pgprot);
1645 
1646 		start = pre_end;
1647 	}
1648 
1649 	/*
1650 	 * We mapped them all?
1651 	 */
1652 	if (num_pages == cur_pages)
1653 		return cur_pages;
1654 
1655 	pmd_pgprot = pgprot_4k_2_large(pgprot);
1656 
1657 	while (end - start >= PMD_SIZE) {
1658 
1659 		/*
1660 		 * We cannot use a 1G page so allocate a PMD page if needed.
1661 		 */
1662 		if (pud_none(*pud))
1663 			if (alloc_pmd_page(pud))
1664 				return -1;
1665 
1666 		pmd = pmd_offset(pud, start);
1667 
1668 		set_pmd(pmd, pmd_mkhuge(pfn_pmd(cpa->pfn,
1669 					canon_pgprot(pmd_pgprot))));
1670 
1671 		start	  += PMD_SIZE;
1672 		cpa->pfn  += PMD_SIZE >> PAGE_SHIFT;
1673 		cur_pages += PMD_SIZE >> PAGE_SHIFT;
1674 	}
1675 
1676 	/*
1677 	 * Map trailing 4K pages.
1678 	 */
1679 	if (start < end) {
1680 		pmd = pmd_offset(pud, start);
1681 		if (pmd_none(*pmd))
1682 			if (alloc_pte_page(pmd))
1683 				return -1;
1684 
1685 		populate_pte(cpa, start, end, num_pages - cur_pages,
1686 			     pmd, pgprot);
1687 	}
1688 	return num_pages;
1689 }
1690 
populate_pud(struct cpa_data * cpa,unsigned long start,p4d_t * p4d,pgprot_t pgprot)1691 static int populate_pud(struct cpa_data *cpa, unsigned long start, p4d_t *p4d,
1692 			pgprot_t pgprot)
1693 {
1694 	pud_t *pud;
1695 	unsigned long end;
1696 	long cur_pages = 0;
1697 	pgprot_t pud_pgprot;
1698 
1699 	end = start + (cpa->numpages << PAGE_SHIFT);
1700 
1701 	/*
1702 	 * Not on a Gb page boundary? => map everything up to it with
1703 	 * smaller pages.
1704 	 */
1705 	if (start & (PUD_SIZE - 1)) {
1706 		unsigned long pre_end;
1707 		unsigned long next_page = (start + PUD_SIZE) & PUD_MASK;
1708 
1709 		pre_end   = min_t(unsigned long, end, next_page);
1710 		cur_pages = (pre_end - start) >> PAGE_SHIFT;
1711 		cur_pages = min_t(int, (int)cpa->numpages, cur_pages);
1712 
1713 		pud = pud_offset(p4d, start);
1714 
1715 		/*
1716 		 * Need a PMD page?
1717 		 */
1718 		if (pud_none(*pud))
1719 			if (alloc_pmd_page(pud))
1720 				return -1;
1721 
1722 		cur_pages = populate_pmd(cpa, start, pre_end, cur_pages,
1723 					 pud, pgprot);
1724 		if (cur_pages < 0)
1725 			return cur_pages;
1726 
1727 		start = pre_end;
1728 	}
1729 
1730 	/* We mapped them all? */
1731 	if (cpa->numpages == cur_pages)
1732 		return cur_pages;
1733 
1734 	pud = pud_offset(p4d, start);
1735 	pud_pgprot = pgprot_4k_2_large(pgprot);
1736 
1737 	/*
1738 	 * Map everything starting from the Gb boundary, possibly with 1G pages
1739 	 */
1740 	while (boot_cpu_has(X86_FEATURE_GBPAGES) && end - start >= PUD_SIZE) {
1741 		set_pud(pud, pud_mkhuge(pfn_pud(cpa->pfn,
1742 				   canon_pgprot(pud_pgprot))));
1743 
1744 		start	  += PUD_SIZE;
1745 		cpa->pfn  += PUD_SIZE >> PAGE_SHIFT;
1746 		cur_pages += PUD_SIZE >> PAGE_SHIFT;
1747 		pud++;
1748 	}
1749 
1750 	/* Map trailing leftover */
1751 	if (start < end) {
1752 		long tmp;
1753 
1754 		pud = pud_offset(p4d, start);
1755 		if (pud_none(*pud))
1756 			if (alloc_pmd_page(pud))
1757 				return -1;
1758 
1759 		tmp = populate_pmd(cpa, start, end, cpa->numpages - cur_pages,
1760 				   pud, pgprot);
1761 		if (tmp < 0)
1762 			return cur_pages;
1763 
1764 		cur_pages += tmp;
1765 	}
1766 	return cur_pages;
1767 }
1768 
1769 /*
1770  * Restrictions for kernel page table do not necessarily apply when mapping in
1771  * an alternate PGD.
1772  */
populate_pgd(struct cpa_data * cpa,unsigned long addr)1773 static int populate_pgd(struct cpa_data *cpa, unsigned long addr)
1774 {
1775 	pgprot_t pgprot = __pgprot(_KERNPG_TABLE);
1776 	pud_t *pud = NULL;	/* shut up gcc */
1777 	p4d_t *p4d;
1778 	pgd_t *pgd_entry;
1779 	long ret;
1780 
1781 	pgd_entry = cpa->pgd + pgd_index(addr);
1782 
1783 	if (pgd_none(*pgd_entry)) {
1784 		/*
1785 		 * Pass 0 as a placeholder for the second argument, since the
1786 		 * generic implementation of p4d_alloc_one() does not use it.
1787 		 */
1788 		p4d = p4d_alloc_one(&init_mm, 0);
1789 		if (!p4d)
1790 			return -1;
1791 
1792 		set_pgd(pgd_entry, __pgd(__pa(p4d) | _KERNPG_TABLE));
1793 	}
1794 
1795 	/*
1796 	 * Allocate a PUD page and hand it down for mapping.
1797 	 */
1798 	p4d = p4d_offset(pgd_entry, addr);
1799 	if (p4d_none(*p4d)) {
1800 		/*
1801 		 * Pass 0 as a placeholder for the second argument, since the
1802 		 * generic implementation of pud_alloc_one() does not use it.
1803 		 */
1804 		pud = pud_alloc_one(&init_mm, 0);
1805 		if (!pud)
1806 			return -1;
1807 
1808 		set_p4d(p4d, __p4d(__pa(pud) | _KERNPG_TABLE));
1809 	}
1810 
1811 	pgprot_val(pgprot) &= ~pgprot_val(cpa->mask_clr);
1812 	pgprot_val(pgprot) |=  pgprot_val(cpa->mask_set);
1813 
1814 	ret = populate_pud(cpa, addr, p4d, pgprot);
1815 	if (ret < 0) {
1816 		/*
1817 		 * Leave the PUD page in place in case some other CPU or thread
1818 		 * already found it, but remove any useless entries we just
1819 		 * added to it.
1820 		 */
1821 		unmap_pud_range(p4d, addr,
1822 				addr + (cpa->numpages << PAGE_SHIFT));
1823 		return ret;
1824 	}
1825 
1826 	cpa->numpages = ret;
1827 	return 0;
1828 }
1829 
__cpa_process_fault(struct cpa_data * cpa,unsigned long vaddr,int primary)1830 static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
1831 			       int primary)
1832 {
1833 	if (cpa->pgd) {
1834 		/*
1835 		 * Right now, we only execute this code path when mapping
1836 		 * the EFI virtual memory map regions, no other users
1837 		 * provide a ->pgd value. This may change in the future.
1838 		 */
1839 		return populate_pgd(cpa, vaddr);
1840 	}
1841 
1842 	/*
1843 	 * Ignore all non primary paths.
1844 	 */
1845 	if (!primary) {
1846 		cpa->numpages = 1;
1847 		return 0;
1848 	}
1849 
1850 	/*
1851 	 * Ignore the NULL PTE for kernel identity mapping, as it is expected
1852 	 * to have holes.
1853 	 * Also set numpages to '1' indicating that we processed cpa req for
1854 	 * one virtual address page and its pfn. TBD: numpages can be set based
1855 	 * on the initial value and the level returned by lookup_address().
1856 	 */
1857 	if (within(vaddr, PAGE_OFFSET,
1858 		   PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT))) {
1859 		cpa->numpages = 1;
1860 		cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
1861 		return 0;
1862 
1863 	} else if (__cpa_pfn_in_highmap(cpa->pfn)) {
1864 		/* Faults in the highmap are OK, so do not warn: */
1865 		return -EFAULT;
1866 	} else {
1867 		WARN(1, KERN_WARNING "CPA: called for zero pte. "
1868 			"vaddr = %lx cpa->vaddr = %lx\n", vaddr,
1869 			*cpa->vaddr);
1870 
1871 		return -EFAULT;
1872 	}
1873 }
1874 
__change_page_attr(struct cpa_data * cpa,int primary)1875 static int __change_page_attr(struct cpa_data *cpa, int primary)
1876 {
1877 	unsigned long address;
1878 	int do_split, err;
1879 	unsigned int level;
1880 	pte_t *kpte, old_pte;
1881 	bool nx, rw;
1882 
1883 	address = __cpa_addr(cpa, cpa->curpage);
1884 repeat:
1885 	kpte = _lookup_address_cpa(cpa, address, &level, &nx, &rw);
1886 	if (!kpte)
1887 		return __cpa_process_fault(cpa, address, primary);
1888 
1889 	old_pte = *kpte;
1890 	if (pte_none(old_pte))
1891 		return __cpa_process_fault(cpa, address, primary);
1892 
1893 	if (level == PG_LEVEL_4K) {
1894 		pte_t new_pte;
1895 		pgprot_t old_prot = pte_pgprot(old_pte);
1896 		pgprot_t new_prot = pte_pgprot(old_pte);
1897 		unsigned long pfn = pte_pfn(old_pte);
1898 
1899 		pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
1900 		pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
1901 
1902 		cpa_inc_4k_install();
1903 		/* Hand in lpsize = 0 to enforce the protection mechanism */
1904 		new_prot = static_protections(new_prot, address, pfn, 1, 0,
1905 					      CPA_PROTECT);
1906 
1907 		new_prot = verify_rwx(old_prot, new_prot, address, pfn, 1,
1908 				      nx, rw);
1909 
1910 		new_prot = pgprot_clear_protnone_bits(new_prot);
1911 
1912 		/*
1913 		 * We need to keep the pfn from the existing PTE,
1914 		 * after all we're only going to change its attributes
1915 		 * not the memory it points to
1916 		 */
1917 		new_pte = pfn_pte(pfn, new_prot);
1918 		cpa->pfn = pfn;
1919 		/*
1920 		 * Do we really change anything ?
1921 		 */
1922 		if (pte_val(old_pte) != pte_val(new_pte)) {
1923 			set_pte_atomic(kpte, new_pte);
1924 			cpa->flags |= CPA_FLUSHTLB;
1925 		}
1926 		cpa->numpages = 1;
1927 		return 0;
1928 	}
1929 
1930 	/*
1931 	 * Check, whether we can keep the large page intact
1932 	 * and just change the pte:
1933 	 */
1934 	do_split = should_split_large_page(kpte, address, cpa);
1935 	/*
1936 	 * When the range fits into the existing large page,
1937 	 * return. cp->numpages and cpa->tlbflush have been updated in
1938 	 * try_large_page:
1939 	 */
1940 	if (do_split <= 0)
1941 		return do_split;
1942 
1943 	/*
1944 	 * We have to split the large page:
1945 	 */
1946 	err = split_large_page(cpa, kpte, address);
1947 	if (!err)
1948 		goto repeat;
1949 
1950 	return err;
1951 }
1952 
1953 static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary);
1954 
1955 /*
1956  * Check the directmap and "high kernel map" 'aliases'.
1957  */
cpa_process_alias(struct cpa_data * cpa)1958 static int cpa_process_alias(struct cpa_data *cpa)
1959 {
1960 	struct cpa_data alias_cpa;
1961 	unsigned long laddr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
1962 	unsigned long vaddr;
1963 	int ret;
1964 
1965 	if (!pfn_range_is_mapped(cpa->pfn, cpa->pfn + 1))
1966 		return 0;
1967 
1968 	/*
1969 	 * No need to redo, when the primary call touched the direct
1970 	 * mapping already:
1971 	 */
1972 	vaddr = __cpa_addr(cpa, cpa->curpage);
1973 	if (!(within(vaddr, PAGE_OFFSET,
1974 		    PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))) {
1975 
1976 		alias_cpa = *cpa;
1977 		alias_cpa.vaddr = &laddr;
1978 		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
1979 		alias_cpa.curpage = 0;
1980 
1981 		/* Directmap always has NX set, do not modify. */
1982 		if (__supported_pte_mask & _PAGE_NX) {
1983 			alias_cpa.mask_clr.pgprot &= ~_PAGE_NX;
1984 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
1985 		}
1986 
1987 		cpa->force_flush_all = 1;
1988 
1989 		ret = __change_page_attr_set_clr(&alias_cpa, 0);
1990 		if (ret)
1991 			return ret;
1992 	}
1993 
1994 #ifdef CONFIG_X86_64
1995 	/*
1996 	 * If the primary call didn't touch the high mapping already
1997 	 * and the physical address is inside the kernel map, we need
1998 	 * to touch the high mapped kernel as well:
1999 	 */
2000 	if (!within(vaddr, (unsigned long)_text, _brk_end) &&
2001 	    __cpa_pfn_in_highmap(cpa->pfn)) {
2002 		unsigned long temp_cpa_vaddr = (cpa->pfn << PAGE_SHIFT) +
2003 					       __START_KERNEL_map - phys_base;
2004 		alias_cpa = *cpa;
2005 		alias_cpa.vaddr = &temp_cpa_vaddr;
2006 		alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
2007 		alias_cpa.curpage = 0;
2008 
2009 		/*
2010 		 * [_text, _brk_end) also covers data, do not modify NX except
2011 		 * in cases where the highmap is the primary target.
2012 		 */
2013 		if (__supported_pte_mask & _PAGE_NX) {
2014 			alias_cpa.mask_clr.pgprot &= ~_PAGE_NX;
2015 			alias_cpa.mask_set.pgprot &= ~_PAGE_NX;
2016 		}
2017 
2018 		cpa->force_flush_all = 1;
2019 		/*
2020 		 * The high mapping range is imprecise, so ignore the
2021 		 * return value.
2022 		 */
2023 		__change_page_attr_set_clr(&alias_cpa, 0);
2024 	}
2025 #endif
2026 
2027 	return 0;
2028 }
2029 
__change_page_attr_set_clr(struct cpa_data * cpa,int primary)2030 static int __change_page_attr_set_clr(struct cpa_data *cpa, int primary)
2031 {
2032 	unsigned long numpages = cpa->numpages;
2033 	unsigned long rempages = numpages;
2034 	bool lock = true;
2035 	int ret = 0;
2036 
2037 	/*
2038 	 * No changes, easy!
2039 	 */
2040 	if (!(pgprot_val(cpa->mask_set) | pgprot_val(cpa->mask_clr)) &&
2041 	    !cpa->force_split)
2042 		return ret;
2043 
2044 	/*
2045 	 * DEBUG_PAGEALLOC is special; it is called from any context the
2046 	 * page-allocator is, which violates the normal cpa_lock locking
2047 	 * rules.
2048 	 *
2049 	 * However, since it is part of the page-allocator, things are still
2050 	 * properly serialized by the page-allocator locking and the fact that
2051 	 * when a page is owned by the page-allocator, it isn't owned by
2052 	 * anybody else. That is, you *SHOULD NOT* be calling cpa() on memory
2053 	 * that isn't allocated.
2054 	 *
2055 	 * Additionally, DEBUG_PAGEALLOC ensures (per probe_page_size_mask())
2056 	 * that the kernel mapping is 4k pages, therefore there are no large
2057 	 * pages to split/collapse.
2058 	 *
2059 	 * Furthermore, the page-allocator strictly manages pages that
2060 	 * *exist*, avoiding pgd_lock.
2061 	 *
2062 	 * Therefore, it is safe to not take cpa_lock.
2063 	 */
2064 	if (debug_pagealloc_enabled() && (cpa->flags & CPA_DEBUG_PAGEALLOC))
2065 		lock = false;
2066 
2067 	while (rempages) {
2068 		/*
2069 		 * Store the remaining nr of pages for the large page
2070 		 * preservation check.
2071 		 */
2072 		cpa->numpages = rempages;
2073 		/* for array changes, we can't use large page */
2074 		if (cpa->flags & (CPA_ARRAY | CPA_PAGES_ARRAY))
2075 			cpa->numpages = 1;
2076 
2077 		if (lock) {
2078 			guard(spinlock)(&cpa_lock);
2079 			ret = __change_page_attr(cpa, primary);
2080 		} else {
2081 			ret = __change_page_attr(cpa, primary);
2082 		}
2083 		if (ret)
2084 			goto out;
2085 
2086 		if (primary && !(cpa->flags & CPA_NO_CHECK_ALIAS)) {
2087 			ret = cpa_process_alias(cpa);
2088 			if (ret)
2089 				goto out;
2090 		}
2091 
2092 		/*
2093 		 * Adjust the number of pages with the result of the
2094 		 * CPA operation. Either a large page has been
2095 		 * preserved or a single page update happened.
2096 		 */
2097 		BUG_ON(cpa->numpages > rempages || !cpa->numpages);
2098 		rempages -= cpa->numpages;
2099 		cpa->curpage += cpa->numpages;
2100 	}
2101 
2102 out:
2103 	/* Restore the original numpages */
2104 	cpa->numpages = numpages;
2105 	return ret;
2106 }
2107 
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)2108 static int change_page_attr_set_clr(unsigned long *addr, int numpages,
2109 				    pgprot_t mask_set, pgprot_t mask_clr,
2110 				    int force_split, int in_flag,
2111 				    struct page **pages)
2112 {
2113 	struct cpa_data cpa;
2114 	int ret, cache;
2115 
2116 	memset(&cpa, 0, sizeof(cpa));
2117 
2118 	/*
2119 	 * Check, if we are requested to set a not supported
2120 	 * feature.  Clearing non-supported features is OK.
2121 	 */
2122 	mask_set = canon_pgprot(mask_set);
2123 
2124 	if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) && !force_split)
2125 		return 0;
2126 
2127 	/* Ensure we are PAGE_SIZE aligned */
2128 	if (in_flag & CPA_ARRAY) {
2129 		int i;
2130 		for (i = 0; i < numpages; i++) {
2131 			if (addr[i] & ~PAGE_MASK) {
2132 				addr[i] &= PAGE_MASK;
2133 				WARN_ON_ONCE(1);
2134 			}
2135 		}
2136 	} else if (!(in_flag & CPA_PAGES_ARRAY)) {
2137 		/*
2138 		 * in_flag of CPA_PAGES_ARRAY implies it is aligned.
2139 		 * No need to check in that case
2140 		 */
2141 		if (*addr & ~PAGE_MASK) {
2142 			*addr &= PAGE_MASK;
2143 			/*
2144 			 * People should not be passing in unaligned addresses:
2145 			 */
2146 			WARN_ON_ONCE(1);
2147 		}
2148 	}
2149 
2150 	/* Must avoid aliasing mappings in the highmem code */
2151 	kmap_flush_unused();
2152 
2153 	vm_unmap_aliases();
2154 
2155 	cpa.vaddr = addr;
2156 	cpa.pages = pages;
2157 	cpa.numpages = numpages;
2158 	cpa.mask_set = mask_set;
2159 	cpa.mask_clr = mask_clr;
2160 	cpa.flags = in_flag;
2161 	cpa.curpage = 0;
2162 	cpa.force_split = force_split;
2163 
2164 	/* Avoid race with concurrent CPA collapse. */
2165 	cpa.init_mm_read_locked = true;
2166 	scoped_guard(mmap_read_lock, &init_mm)
2167 		ret = __change_page_attr_set_clr(&cpa, 1);
2168 	cpa.init_mm_read_locked = false;
2169 
2170 	/*
2171 	 * Check whether we really changed something:
2172 	 */
2173 	if (!(cpa.flags & CPA_FLUSHTLB))
2174 		goto out;
2175 
2176 	/*
2177 	 * No need to flush, when we did not set any of the caching
2178 	 * attributes:
2179 	 */
2180 	cache = !!pgprot2cachemode(mask_set);
2181 
2182 	/*
2183 	 * On error; flush everything to be sure.
2184 	 */
2185 	if (ret) {
2186 		cpa_flush_all(cache);
2187 		goto out;
2188 	}
2189 
2190 	cpa_flush(&cpa, cache);
2191 out:
2192 	return ret;
2193 }
2194 
change_page_attr_set(unsigned long * addr,int numpages,pgprot_t mask,int array)2195 static inline int change_page_attr_set(unsigned long *addr, int numpages,
2196 				       pgprot_t mask, int array)
2197 {
2198 	return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
2199 		(array ? CPA_ARRAY : 0), NULL);
2200 }
2201 
change_page_attr_clear(unsigned long * addr,int numpages,pgprot_t mask,int array)2202 static inline int change_page_attr_clear(unsigned long *addr, int numpages,
2203 					 pgprot_t mask, int array)
2204 {
2205 	return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
2206 		(array ? CPA_ARRAY : 0), NULL);
2207 }
2208 
cpa_set_pages_array(struct page ** pages,int numpages,pgprot_t mask)2209 static inline int cpa_set_pages_array(struct page **pages, int numpages,
2210 				       pgprot_t mask)
2211 {
2212 	return change_page_attr_set_clr(NULL, numpages, mask, __pgprot(0), 0,
2213 		CPA_PAGES_ARRAY, pages);
2214 }
2215 
cpa_clear_pages_array(struct page ** pages,int numpages,pgprot_t mask)2216 static inline int cpa_clear_pages_array(struct page **pages, int numpages,
2217 					 pgprot_t mask)
2218 {
2219 	return change_page_attr_set_clr(NULL, numpages, __pgprot(0), mask, 0,
2220 		CPA_PAGES_ARRAY, pages);
2221 }
2222 
_set_memory_uc(unsigned long addr,int numpages)2223 int _set_memory_uc(unsigned long addr, int numpages)
2224 {
2225 	/*
2226 	 * for now UC MINUS. see comments in ioremap()
2227 	 * If you really need strong UC use ioremap_uc(), but note
2228 	 * that you cannot override IO areas with set_memory_*() as
2229 	 * these helpers cannot work with IO memory.
2230 	 */
2231 	return change_page_attr_set(&addr, numpages,
2232 				    cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
2233 				    0);
2234 }
2235 
set_memory_uc(unsigned long addr,int numpages)2236 int set_memory_uc(unsigned long addr, int numpages)
2237 {
2238 	int ret;
2239 
2240 	/*
2241 	 * for now UC MINUS. see comments in ioremap()
2242 	 */
2243 	ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
2244 			      _PAGE_CACHE_MODE_UC_MINUS, NULL);
2245 	if (ret)
2246 		goto out_err;
2247 
2248 	ret = _set_memory_uc(addr, numpages);
2249 	if (ret)
2250 		goto out_free;
2251 
2252 	return 0;
2253 
2254 out_free:
2255 	memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2256 out_err:
2257 	return ret;
2258 }
2259 EXPORT_SYMBOL(set_memory_uc);
2260 
_set_memory_wc(unsigned long addr,int numpages)2261 int _set_memory_wc(unsigned long addr, int numpages)
2262 {
2263 	int ret;
2264 
2265 	ret = change_page_attr_set(&addr, numpages,
2266 				   cachemode2pgprot(_PAGE_CACHE_MODE_UC_MINUS),
2267 				   0);
2268 	if (!ret) {
2269 		ret = change_page_attr_set_clr(&addr, numpages,
2270 					       cachemode2pgprot(_PAGE_CACHE_MODE_WC),
2271 					       __pgprot(_PAGE_CACHE_MASK),
2272 					       0, 0, NULL);
2273 	}
2274 	return ret;
2275 }
2276 
set_memory_wc(unsigned long addr,int numpages)2277 int set_memory_wc(unsigned long addr, int numpages)
2278 {
2279 	int ret;
2280 
2281 	ret = memtype_reserve(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
2282 		_PAGE_CACHE_MODE_WC, NULL);
2283 	if (ret)
2284 		return ret;
2285 
2286 	ret = _set_memory_wc(addr, numpages);
2287 	if (ret)
2288 		memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2289 
2290 	return ret;
2291 }
2292 EXPORT_SYMBOL(set_memory_wc);
2293 
_set_memory_wt(unsigned long addr,int numpages)2294 int _set_memory_wt(unsigned long addr, int numpages)
2295 {
2296 	return change_page_attr_set(&addr, numpages,
2297 				    cachemode2pgprot(_PAGE_CACHE_MODE_WT), 0);
2298 }
2299 
_set_memory_wb(unsigned long addr,int numpages)2300 int _set_memory_wb(unsigned long addr, int numpages)
2301 {
2302 	/* WB cache mode is hard wired to all cache attribute bits being 0 */
2303 	return change_page_attr_clear(&addr, numpages,
2304 				      __pgprot(_PAGE_CACHE_MASK), 0);
2305 }
2306 
set_memory_wb(unsigned long addr,int numpages)2307 int set_memory_wb(unsigned long addr, int numpages)
2308 {
2309 	int ret;
2310 
2311 	ret = _set_memory_wb(addr, numpages);
2312 	if (ret)
2313 		return ret;
2314 
2315 	memtype_free(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
2316 	return 0;
2317 }
2318 EXPORT_SYMBOL(set_memory_wb);
2319 
2320 /* Prevent speculative access to a page by marking it not-present */
2321 #ifdef CONFIG_X86_64
set_mce_nospec(unsigned long pfn)2322 int set_mce_nospec(unsigned long pfn)
2323 {
2324 	unsigned long decoy_addr;
2325 	int rc;
2326 
2327 	/* SGX pages are not in the 1:1 map */
2328 	if (arch_is_platform_page(pfn << PAGE_SHIFT))
2329 		return 0;
2330 	/*
2331 	 * We would like to just call:
2332 	 *      set_memory_XX((unsigned long)pfn_to_kaddr(pfn), 1);
2333 	 * but doing that would radically increase the odds of a
2334 	 * speculative access to the poison page because we'd have
2335 	 * the virtual address of the kernel 1:1 mapping sitting
2336 	 * around in registers.
2337 	 * Instead we get tricky.  We create a non-canonical address
2338 	 * that looks just like the one we want, but has bit 63 flipped.
2339 	 * This relies on set_memory_XX() properly sanitizing any __pa()
2340 	 * results with __PHYSICAL_MASK or PTE_PFN_MASK.
2341 	 */
2342 	decoy_addr = (pfn << PAGE_SHIFT) + (PAGE_OFFSET ^ BIT(63));
2343 
2344 	rc = set_memory_np(decoy_addr, 1);
2345 	if (rc)
2346 		pr_warn("Could not invalidate pfn=0x%lx from 1:1 map\n", pfn);
2347 	return rc;
2348 }
2349 EXPORT_SYMBOL_GPL(set_mce_nospec);
2350 
2351 /* Restore full speculative operation to the pfn. */
clear_mce_nospec(unsigned long pfn)2352 int clear_mce_nospec(unsigned long pfn)
2353 {
2354 	unsigned long addr = (unsigned long) pfn_to_kaddr(pfn);
2355 
2356 	return set_memory_p(addr, 1);
2357 }
2358 EXPORT_SYMBOL_GPL(clear_mce_nospec);
2359 #endif /* CONFIG_X86_64 */
2360 
set_memory_x(unsigned long addr,int numpages)2361 int set_memory_x(unsigned long addr, int numpages)
2362 {
2363 	if (!(__supported_pte_mask & _PAGE_NX))
2364 		return 0;
2365 
2366 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_NX), 0);
2367 }
2368 
set_memory_nx(unsigned long addr,int numpages)2369 int set_memory_nx(unsigned long addr, int numpages)
2370 {
2371 	if (!(__supported_pte_mask & _PAGE_NX))
2372 		return 0;
2373 
2374 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_NX), 0);
2375 }
2376 
set_memory_ro(unsigned long addr,int numpages)2377 int set_memory_ro(unsigned long addr, int numpages)
2378 {
2379 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW | _PAGE_DIRTY), 0);
2380 }
2381 
set_memory_rox(unsigned long addr,int numpages)2382 int set_memory_rox(unsigned long addr, int numpages)
2383 {
2384 	pgprot_t clr = __pgprot(_PAGE_RW | _PAGE_DIRTY);
2385 
2386 	if (__supported_pte_mask & _PAGE_NX)
2387 		clr.pgprot |= _PAGE_NX;
2388 
2389 	return change_page_attr_set_clr(&addr, numpages, __pgprot(0), clr, 0,
2390 					CPA_COLLAPSE, NULL);
2391 }
2392 
set_memory_rw(unsigned long addr,int numpages)2393 int set_memory_rw(unsigned long addr, int numpages)
2394 {
2395 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_RW), 0);
2396 }
2397 
set_memory_np(unsigned long addr,int numpages)2398 int set_memory_np(unsigned long addr, int numpages)
2399 {
2400 	return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
2401 }
2402 
set_memory_np_noalias(unsigned long addr,int numpages)2403 int set_memory_np_noalias(unsigned long addr, int numpages)
2404 {
2405 	return change_page_attr_set_clr(&addr, numpages, __pgprot(0),
2406 					__pgprot(_PAGE_PRESENT), 0,
2407 					CPA_NO_CHECK_ALIAS, NULL);
2408 }
2409 
set_memory_p(unsigned long addr,int numpages)2410 int set_memory_p(unsigned long addr, int numpages)
2411 {
2412 	return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
2413 }
2414 
set_memory_4k(unsigned long addr,int numpages)2415 int set_memory_4k(unsigned long addr, int numpages)
2416 {
2417 	return change_page_attr_set_clr(&addr, numpages,
2418 					__pgprot(_PAGE_KERNEL_4K),
2419 					__pgprot(0), 1, 0, NULL);
2420 }
2421 
set_memory_nonglobal(unsigned long addr,int numpages)2422 int set_memory_nonglobal(unsigned long addr, int numpages)
2423 {
2424 	return change_page_attr_clear(&addr, numpages,
2425 				      __pgprot(_PAGE_GLOBAL), 0);
2426 }
2427 
set_memory_global(unsigned long addr,int numpages)2428 int set_memory_global(unsigned long addr, int numpages)
2429 {
2430 	return change_page_attr_set(&addr, numpages,
2431 				    __pgprot(_PAGE_GLOBAL), 0);
2432 }
2433 
2434 /*
2435  * __set_memory_enc_pgtable() is used for the hypervisors that get
2436  * informed about "encryption" status via page tables.
2437  */
__set_memory_enc_pgtable(unsigned long addr,int numpages,bool enc)2438 static int __set_memory_enc_pgtable(unsigned long addr, int numpages, bool enc)
2439 {
2440 	pgprot_t empty = __pgprot(0);
2441 	struct cpa_data cpa;
2442 	int ret;
2443 
2444 	/* Should not be working on unaligned addresses */
2445 	if (WARN_ONCE(addr & ~PAGE_MASK, "misaligned address: %#lx\n", addr))
2446 		addr &= PAGE_MASK;
2447 
2448 	memset(&cpa, 0, sizeof(cpa));
2449 	cpa.vaddr = &addr;
2450 	cpa.numpages = numpages;
2451 	cpa.mask_set = enc ? pgprot_encrypted(empty) : pgprot_decrypted(empty);
2452 	cpa.mask_clr = enc ? pgprot_decrypted(empty) : pgprot_encrypted(empty);
2453 	cpa.pgd = init_mm.pgd;
2454 
2455 	/* Must avoid aliasing mappings in the highmem code */
2456 	kmap_flush_unused();
2457 	vm_unmap_aliases();
2458 
2459 	/* Flush the caches as needed before changing the encryption attribute. */
2460 	if (x86_platform.guest.enc_tlb_flush_required(enc))
2461 		cpa_flush(&cpa, x86_platform.guest.enc_cache_flush_required());
2462 
2463 	/* Notify hypervisor that we are about to set/clr encryption attribute. */
2464 	ret = x86_platform.guest.enc_status_change_prepare(addr, numpages, enc);
2465 	if (ret)
2466 		goto vmm_fail;
2467 
2468 	ret = __change_page_attr_set_clr(&cpa, 1);
2469 
2470 	/*
2471 	 * After changing the encryption attribute, we need to flush TLBs again
2472 	 * in case any speculative TLB caching occurred (but no need to flush
2473 	 * caches again).  We could just use cpa_flush_all(), but in case TLB
2474 	 * flushing gets optimized in the cpa_flush() path use the same logic
2475 	 * as above.
2476 	 */
2477 	cpa_flush(&cpa, 0);
2478 
2479 	if (ret)
2480 		return ret;
2481 
2482 	/* Notify hypervisor that we have successfully set/clr encryption attribute. */
2483 	ret = x86_platform.guest.enc_status_change_finish(addr, numpages, enc);
2484 	if (ret)
2485 		goto vmm_fail;
2486 
2487 	return 0;
2488 
2489 vmm_fail:
2490 	WARN_ONCE(1, "CPA VMM failure to convert memory (addr=%p, numpages=%d) to %s: %d\n",
2491 		  (void *)addr, numpages, enc ? "private" : "shared", ret);
2492 
2493 	return ret;
2494 }
2495 
2496 /*
2497  * The lock serializes conversions between private and shared memory.
2498  *
2499  * It is taken for read on conversion. A write lock guarantees that no
2500  * concurrent conversions are in progress.
2501  */
2502 static DECLARE_RWSEM(mem_enc_lock);
2503 
2504 /*
2505  * Stop new private<->shared conversions.
2506  *
2507  * Taking the exclusive mem_enc_lock waits for in-flight conversions to complete.
2508  * The lock is not released to prevent new conversions from being started.
2509  */
set_memory_enc_stop_conversion(void)2510 bool set_memory_enc_stop_conversion(void)
2511 {
2512 	/*
2513 	 * In a crash scenario, sleep is not allowed. Try to take the lock.
2514 	 * Failure indicates that there is a race with the conversion.
2515 	 */
2516 	if (oops_in_progress)
2517 		return down_write_trylock(&mem_enc_lock);
2518 
2519 	down_write(&mem_enc_lock);
2520 
2521 	return true;
2522 }
2523 
__set_memory_enc_dec(unsigned long addr,int numpages,bool enc)2524 static int __set_memory_enc_dec(unsigned long addr, int numpages, bool enc)
2525 {
2526 	int ret = 0;
2527 
2528 	if (cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
2529 		if (!down_read_trylock(&mem_enc_lock))
2530 			return -EBUSY;
2531 
2532 		ret = __set_memory_enc_pgtable(addr, numpages, enc);
2533 
2534 		up_read(&mem_enc_lock);
2535 	}
2536 
2537 	return ret;
2538 }
2539 
set_memory_encrypted(unsigned long addr,int numpages)2540 int set_memory_encrypted(unsigned long addr, int numpages)
2541 {
2542 	return __set_memory_enc_dec(addr, numpages, true);
2543 }
2544 EXPORT_SYMBOL_GPL(set_memory_encrypted);
2545 
set_memory_decrypted(unsigned long addr,int numpages)2546 int set_memory_decrypted(unsigned long addr, int numpages)
2547 {
2548 	return __set_memory_enc_dec(addr, numpages, false);
2549 }
2550 EXPORT_SYMBOL_GPL(set_memory_decrypted);
2551 
set_pages_uc(struct page * page,int numpages)2552 int set_pages_uc(struct page *page, int numpages)
2553 {
2554 	unsigned long addr = (unsigned long)page_address(page);
2555 
2556 	return set_memory_uc(addr, numpages);
2557 }
2558 EXPORT_SYMBOL(set_pages_uc);
2559 
_set_pages_array(struct page ** pages,int numpages,enum page_cache_mode new_type)2560 static int _set_pages_array(struct page **pages, int numpages,
2561 		enum page_cache_mode new_type)
2562 {
2563 	unsigned long start;
2564 	unsigned long end;
2565 	enum page_cache_mode set_type;
2566 	int i;
2567 	int free_idx;
2568 	int ret;
2569 
2570 	for (i = 0; i < numpages; i++) {
2571 		if (PageHighMem(pages[i]))
2572 			continue;
2573 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2574 		end = start + PAGE_SIZE;
2575 		if (memtype_reserve(start, end, new_type, NULL))
2576 			goto err_out;
2577 	}
2578 
2579 	/* If WC, set to UC- first and then WC */
2580 	set_type = (new_type == _PAGE_CACHE_MODE_WC) ?
2581 				_PAGE_CACHE_MODE_UC_MINUS : new_type;
2582 
2583 	ret = cpa_set_pages_array(pages, numpages,
2584 				  cachemode2pgprot(set_type));
2585 	if (!ret && new_type == _PAGE_CACHE_MODE_WC)
2586 		ret = change_page_attr_set_clr(NULL, numpages,
2587 					       cachemode2pgprot(
2588 						_PAGE_CACHE_MODE_WC),
2589 					       __pgprot(_PAGE_CACHE_MASK),
2590 					       0, CPA_PAGES_ARRAY, pages);
2591 	if (ret)
2592 		goto err_out;
2593 	return 0; /* Success */
2594 err_out:
2595 	free_idx = i;
2596 	for (i = 0; i < free_idx; i++) {
2597 		if (PageHighMem(pages[i]))
2598 			continue;
2599 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2600 		end = start + PAGE_SIZE;
2601 		memtype_free(start, end);
2602 	}
2603 	return -EINVAL;
2604 }
2605 
set_pages_array_uc(struct page ** pages,int numpages)2606 int set_pages_array_uc(struct page **pages, int numpages)
2607 {
2608 	return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_UC_MINUS);
2609 }
2610 EXPORT_SYMBOL(set_pages_array_uc);
2611 
set_pages_array_wc(struct page ** pages,int numpages)2612 int set_pages_array_wc(struct page **pages, int numpages)
2613 {
2614 	return _set_pages_array(pages, numpages, _PAGE_CACHE_MODE_WC);
2615 }
2616 EXPORT_SYMBOL(set_pages_array_wc);
2617 
set_pages_wb(struct page * page,int numpages)2618 int set_pages_wb(struct page *page, int numpages)
2619 {
2620 	unsigned long addr = (unsigned long)page_address(page);
2621 
2622 	return set_memory_wb(addr, numpages);
2623 }
2624 EXPORT_SYMBOL(set_pages_wb);
2625 
set_pages_array_wb(struct page ** pages,int numpages)2626 int set_pages_array_wb(struct page **pages, int numpages)
2627 {
2628 	int retval;
2629 	unsigned long start;
2630 	unsigned long end;
2631 	int i;
2632 
2633 	/* WB cache mode is hard wired to all cache attribute bits being 0 */
2634 	retval = cpa_clear_pages_array(pages, numpages,
2635 			__pgprot(_PAGE_CACHE_MASK));
2636 	if (retval)
2637 		return retval;
2638 
2639 	for (i = 0; i < numpages; i++) {
2640 		if (PageHighMem(pages[i]))
2641 			continue;
2642 		start = page_to_pfn(pages[i]) << PAGE_SHIFT;
2643 		end = start + PAGE_SIZE;
2644 		memtype_free(start, end);
2645 	}
2646 
2647 	return 0;
2648 }
2649 EXPORT_SYMBOL(set_pages_array_wb);
2650 
set_pages_ro(struct page * page,int numpages)2651 int set_pages_ro(struct page *page, int numpages)
2652 {
2653 	unsigned long addr = (unsigned long)page_address(page);
2654 
2655 	return set_memory_ro(addr, numpages);
2656 }
2657 
set_pages_rw(struct page * page,int numpages)2658 int set_pages_rw(struct page *page, int numpages)
2659 {
2660 	unsigned long addr = (unsigned long)page_address(page);
2661 
2662 	return set_memory_rw(addr, numpages);
2663 }
2664 
__set_pages_p(struct page * page,int numpages,unsigned int cpa_flags)2665 static int __set_pages_p(struct page *page, int numpages, unsigned int cpa_flags)
2666 {
2667 	unsigned long tempaddr = (unsigned long) page_address(page);
2668 	struct cpa_data cpa = { .vaddr = &tempaddr,
2669 				.pgd = NULL,
2670 				.numpages = numpages,
2671 				.mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
2672 				.mask_clr = __pgprot(0),
2673 				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
2674 
2675 	/*
2676 	 * No alias checking needed for setting present flag. otherwise,
2677 	 * we may need to break large pages for 64-bit kernel text
2678 	 * mappings (this adds to complexity if we want to do this from
2679 	 * atomic context especially). Let's keep it simple!
2680 	 */
2681 	return __change_page_attr_set_clr(&cpa, 1);
2682 }
2683 
__set_pages_np(struct page * page,int numpages,unsigned int cpa_flags)2684 static int __set_pages_np(struct page *page, int numpages, unsigned int cpa_flags)
2685 {
2686 	unsigned long tempaddr = (unsigned long) page_address(page);
2687 	struct cpa_data cpa = { .vaddr = &tempaddr,
2688 				.pgd = NULL,
2689 				.numpages = numpages,
2690 				.mask_set = __pgprot(0),
2691 				.mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
2692 				.flags = CPA_NO_CHECK_ALIAS | cpa_flags };
2693 
2694 	/*
2695 	 * No alias checking needed for setting not present flag. otherwise,
2696 	 * we may need to break large pages for 64-bit kernel text
2697 	 * mappings (this adds to complexity if we want to do this from
2698 	 * atomic context especially). Let's keep it simple!
2699 	 */
2700 	return __change_page_attr_set_clr(&cpa, 1);
2701 }
2702 
set_direct_map_invalid_noflush(struct page * page)2703 int set_direct_map_invalid_noflush(struct page *page)
2704 {
2705 	return __set_pages_np(page, 1, 0);
2706 }
2707 
set_direct_map_default_noflush(struct page * page)2708 int set_direct_map_default_noflush(struct page *page)
2709 {
2710 	return __set_pages_p(page, 1, 0);
2711 }
2712 
set_direct_map_valid_noflush(struct page * page,unsigned nr,bool valid)2713 int set_direct_map_valid_noflush(struct page *page, unsigned nr, bool valid)
2714 {
2715 	if (valid)
2716 		return __set_pages_p(page, nr, 0);
2717 
2718 	return __set_pages_np(page, nr, 0);
2719 }
2720 
2721 #ifdef CONFIG_DEBUG_PAGEALLOC
__kernel_map_pages(struct page * page,int numpages,int enable)2722 void __kernel_map_pages(struct page *page, int numpages, int enable)
2723 {
2724 	if (PageHighMem(page))
2725 		return;
2726 	if (!enable) {
2727 		debug_check_no_locks_freed(page_address(page),
2728 					   numpages * PAGE_SIZE);
2729 	}
2730 
2731 	/*
2732 	 * The return value is ignored as the calls cannot fail.
2733 	 * Large pages for identity mappings are not used at boot time
2734 	 * and hence no memory allocations during large page split.
2735 	 */
2736 	if (enable)
2737 		__set_pages_p(page, numpages, CPA_DEBUG_PAGEALLOC);
2738 	else
2739 		__set_pages_np(page, numpages, CPA_DEBUG_PAGEALLOC);
2740 
2741 	/*
2742 	 * We should perform an IPI and flush all tlbs, but that can
2743 	 * deadlock, settle for a local flush.
2744 	 *
2745 	 * Not doing a global TLB flush means that remote CPUs will retain
2746 	 * stale TLB entries. In case of P->NP (on free) this means the remote
2747 	 * CPUs will not take the faults, making the debug scheme less
2748 	 * reliable. On the NP->P (on alloc) this means the remote CPUs can
2749 	 * take a spurious fault. However spurious_kernel_fault() will observe
2750 	 * *_present() and fix it up.
2751 	 *
2752 	 * Preemption needs to be disabled around __flush_tlb_all() due to CR3
2753 	 * reload in __native_flush_tlb().
2754 	 */
2755 	preempt_disable();
2756 	__flush_tlb_all();
2757 	preempt_enable();
2758 
2759 	arch_flush_lazy_mmu_mode();
2760 }
2761 #endif /* CONFIG_DEBUG_PAGEALLOC */
2762 
kernel_page_present(struct page * page)2763 bool kernel_page_present(struct page *page)
2764 {
2765 	unsigned int level;
2766 	pte_t *pte;
2767 
2768 	if (PageHighMem(page))
2769 		return false;
2770 
2771 	pte = lookup_address((unsigned long)page_address(page), &level);
2772 	return (pte_val(*pte) & _PAGE_PRESENT);
2773 }
2774 
kernel_map_pages_in_pgd(pgd_t * pgd,u64 pfn,unsigned long address,unsigned numpages,unsigned long page_flags)2775 int __init kernel_map_pages_in_pgd(pgd_t *pgd, u64 pfn, unsigned long address,
2776 				   unsigned numpages, unsigned long page_flags)
2777 {
2778 	int retval = -EINVAL;
2779 
2780 	struct cpa_data cpa = {
2781 		.vaddr = &address,
2782 		.pfn = pfn,
2783 		.pgd = pgd,
2784 		.numpages = numpages,
2785 		.mask_set = __pgprot(0),
2786 		.mask_clr = __pgprot(~page_flags & (_PAGE_NX|_PAGE_RW|_PAGE_DIRTY)),
2787 		.flags = CPA_NO_CHECK_ALIAS,
2788 	};
2789 
2790 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
2791 
2792 	if (!(__supported_pte_mask & _PAGE_NX))
2793 		goto out;
2794 
2795 	if (!(page_flags & _PAGE_ENC))
2796 		cpa.mask_clr = pgprot_encrypted(cpa.mask_clr);
2797 
2798 	cpa.mask_set = __pgprot(_PAGE_PRESENT | page_flags);
2799 
2800 	retval = __change_page_attr_set_clr(&cpa, 1);
2801 	__flush_tlb_all();
2802 
2803 out:
2804 	return retval;
2805 }
2806 
2807 /*
2808  * __flush_tlb_all() flushes mappings only on current CPU and hence this
2809  * function shouldn't be used in an SMP environment. Presently, it's used only
2810  * during boot (way before smp_init()) by EFI subsystem and hence is ok.
2811  */
kernel_unmap_pages_in_pgd(pgd_t * pgd,unsigned long address,unsigned long numpages)2812 int __init kernel_unmap_pages_in_pgd(pgd_t *pgd, unsigned long address,
2813 				     unsigned long numpages)
2814 {
2815 	int retval;
2816 
2817 	/*
2818 	 * The typical sequence for unmapping is to find a pte through
2819 	 * lookup_address_in_pgd() (ideally, it should never return NULL because
2820 	 * the address is already mapped) and change its protections. As pfn is
2821 	 * the *target* of a mapping, it's not useful while unmapping.
2822 	 */
2823 	struct cpa_data cpa = {
2824 		.vaddr		= &address,
2825 		.pfn		= 0,
2826 		.pgd		= pgd,
2827 		.numpages	= numpages,
2828 		.mask_set	= __pgprot(0),
2829 		.mask_clr	= __pgprot(_PAGE_PRESENT | _PAGE_RW | _PAGE_DIRTY),
2830 		.flags		= CPA_NO_CHECK_ALIAS,
2831 	};
2832 
2833 	WARN_ONCE(num_online_cpus() > 1, "Don't call after initializing SMP");
2834 
2835 	retval = __change_page_attr_set_clr(&cpa, 1);
2836 	__flush_tlb_all();
2837 
2838 	return retval;
2839 }
2840 
2841 /*
2842  * The testcases use internal knowledge of the implementation that shouldn't
2843  * be exposed to the rest of the kernel. Include these directly here.
2844  */
2845 #ifdef CONFIG_CPA_DEBUG
2846 #include "cpa-test.c"
2847 #endif
2848