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