OSDN Git Service

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