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