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