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