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