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