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