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