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