Merge remote-tracking branch 'origin/x86/boot' into x86/mm2
[firefly-linux-kernel-4.4.55.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/module.h>
8 #include <linux/sched.h>
9 #include <linux/mm.h>
10 #include <linux/interrupt.h>
11 #include <linux/seq_file.h>
12 #include <linux/debugfs.h>
13 #include <linux/pfn.h>
14 #include <linux/percpu.h>
15 #include <linux/gfp.h>
16 #include <linux/pci.h>
17
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         pgprot_t        mask_set;
34         pgprot_t        mask_clr;
35         int             numpages;
36         int             flags;
37         unsigned long   pfn;
38         unsigned        force_split : 1;
39         int             curpage;
40         struct page     **pages;
41 };
42
43 /*
44  * Serialize cpa() (for !DEBUG_PAGEALLOC which uses large identity mappings)
45  * using cpa_lock. So that we don't allow any other cpu, with stale large tlb
46  * entries change the page attribute in parallel to some other cpu
47  * splitting a large page entry along with changing the attribute.
48  */
49 static DEFINE_SPINLOCK(cpa_lock);
50
51 #define CPA_FLUSHTLB 1
52 #define CPA_ARRAY 2
53 #define CPA_PAGES_ARRAY 4
54
55 #ifdef CONFIG_PROC_FS
56 static unsigned long direct_pages_count[PG_LEVEL_NUM];
57
58 void update_page_count(int level, unsigned long pages)
59 {
60         /* Protect against CPA */
61         spin_lock(&pgd_lock);
62         direct_pages_count[level] += pages;
63         spin_unlock(&pgd_lock);
64 }
65
66 static void split_page_count(int level)
67 {
68         direct_pages_count[level]--;
69         direct_pages_count[level - 1] += PTRS_PER_PTE;
70 }
71
72 void arch_report_meminfo(struct seq_file *m)
73 {
74         seq_printf(m, "DirectMap4k:    %8lu kB\n",
75                         direct_pages_count[PG_LEVEL_4K] << 2);
76 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
77         seq_printf(m, "DirectMap2M:    %8lu kB\n",
78                         direct_pages_count[PG_LEVEL_2M] << 11);
79 #else
80         seq_printf(m, "DirectMap4M:    %8lu kB\n",
81                         direct_pages_count[PG_LEVEL_2M] << 12);
82 #endif
83 #ifdef CONFIG_X86_64
84         if (direct_gbpages)
85                 seq_printf(m, "DirectMap1G:    %8lu kB\n",
86                         direct_pages_count[PG_LEVEL_1G] << 20);
87 #endif
88 }
89 #else
90 static inline void split_page_count(int level) { }
91 #endif
92
93 #ifdef CONFIG_X86_64
94
95 static inline unsigned long highmap_start_pfn(void)
96 {
97         return __pa(_text) >> PAGE_SHIFT;
98 }
99
100 static inline unsigned long highmap_end_pfn(void)
101 {
102         return __pa(roundup(_brk_end, PMD_SIZE)) >> PAGE_SHIFT;
103 }
104
105 #endif
106
107 #ifdef CONFIG_DEBUG_PAGEALLOC
108 # define debug_pagealloc 1
109 #else
110 # define debug_pagealloc 0
111 #endif
112
113 static inline int
114 within(unsigned long addr, unsigned long start, unsigned long end)
115 {
116         return addr >= start && addr < end;
117 }
118
119 /*
120  * Flushing functions
121  */
122
123 /**
124  * clflush_cache_range - flush a cache range with clflush
125  * @vaddr:      virtual start address
126  * @size:       number of bytes to flush
127  *
128  * clflush is an unordered instruction which needs fencing with mfence
129  * to avoid ordering issues.
130  */
131 void clflush_cache_range(void *vaddr, unsigned int size)
132 {
133         void *vend = vaddr + size - 1;
134
135         mb();
136
137         for (; vaddr < vend; vaddr += boot_cpu_data.x86_clflush_size)
138                 clflush(vaddr);
139         /*
140          * Flush any possible final partial cacheline:
141          */
142         clflush(vend);
143
144         mb();
145 }
146 EXPORT_SYMBOL_GPL(clflush_cache_range);
147
148 static void __cpa_flush_all(void *arg)
149 {
150         unsigned long cache = (unsigned long)arg;
151
152         /*
153          * Flush all to work around Errata in early athlons regarding
154          * large page flushing.
155          */
156         __flush_tlb_all();
157
158         if (cache && boot_cpu_data.x86 >= 4)
159                 wbinvd();
160 }
161
162 static void cpa_flush_all(unsigned long cache)
163 {
164         BUG_ON(irqs_disabled());
165
166         on_each_cpu(__cpa_flush_all, (void *) cache, 1);
167 }
168
169 static void __cpa_flush_range(void *arg)
170 {
171         /*
172          * We could optimize that further and do individual per page
173          * tlb invalidates for a low number of pages. Caveat: we must
174          * flush the high aliases on 64bit as well.
175          */
176         __flush_tlb_all();
177 }
178
179 static void cpa_flush_range(unsigned long start, int numpages, int cache)
180 {
181         unsigned int i, level;
182         unsigned long addr;
183
184         BUG_ON(irqs_disabled());
185         WARN_ON(PAGE_ALIGN(start) != start);
186
187         on_each_cpu(__cpa_flush_range, NULL, 1);
188
189         if (!cache)
190                 return;
191
192         /*
193          * We only need to flush on one CPU,
194          * clflush is a MESI-coherent instruction that
195          * will cause all other CPUs to flush the same
196          * cachelines:
197          */
198         for (i = 0, addr = start; i < numpages; i++, addr += PAGE_SIZE) {
199                 pte_t *pte = lookup_address(addr, &level);
200
201                 /*
202                  * Only flush present addresses:
203                  */
204                 if (pte && (pte_val(*pte) & _PAGE_PRESENT))
205                         clflush_cache_range((void *) addr, PAGE_SIZE);
206         }
207 }
208
209 static void cpa_flush_array(unsigned long *start, int numpages, int cache,
210                             int in_flags, struct page **pages)
211 {
212         unsigned int i, level;
213         unsigned long do_wbinvd = cache && numpages >= 1024; /* 4M threshold */
214
215         BUG_ON(irqs_disabled());
216
217         on_each_cpu(__cpa_flush_all, (void *) do_wbinvd, 1);
218
219         if (!cache || do_wbinvd)
220                 return;
221
222         /*
223          * We only need to flush on one CPU,
224          * clflush is a MESI-coherent instruction that
225          * will cause all other CPUs to flush the same
226          * cachelines:
227          */
228         for (i = 0; i < numpages; i++) {
229                 unsigned long addr;
230                 pte_t *pte;
231
232                 if (in_flags & CPA_PAGES_ARRAY)
233                         addr = (unsigned long)page_address(pages[i]);
234                 else
235                         addr = start[i];
236
237                 pte = lookup_address(addr, &level);
238
239                 /*
240                  * Only flush present addresses:
241                  */
242                 if (pte && (pte_val(*pte) & _PAGE_PRESENT))
243                         clflush_cache_range((void *)addr, PAGE_SIZE);
244         }
245 }
246
247 /*
248  * Certain areas of memory on x86 require very specific protection flags,
249  * for example the BIOS area or kernel text. Callers don't always get this
250  * right (again, ioremap() on BIOS memory is not uncommon) so this function
251  * checks and fixes these known static required protection bits.
252  */
253 static inline pgprot_t static_protections(pgprot_t prot, unsigned long address,
254                                    unsigned long pfn)
255 {
256         pgprot_t forbidden = __pgprot(0);
257
258         /*
259          * The BIOS area between 640k and 1Mb needs to be executable for
260          * PCI BIOS based config access (CONFIG_PCI_GOBIOS) support.
261          */
262 #ifdef CONFIG_PCI_BIOS
263         if (pcibios_enabled && within(pfn, BIOS_BEGIN >> PAGE_SHIFT, BIOS_END >> PAGE_SHIFT))
264                 pgprot_val(forbidden) |= _PAGE_NX;
265 #endif
266
267         /*
268          * The kernel text needs to be executable for obvious reasons
269          * Does not cover __inittext since that is gone later on. On
270          * 64bit we do not enforce !NX on the low mapping
271          */
272         if (within(address, (unsigned long)_text, (unsigned long)_etext))
273                 pgprot_val(forbidden) |= _PAGE_NX;
274
275         /*
276          * The .rodata section needs to be read-only. Using the pfn
277          * catches all aliases.
278          */
279         if (within(pfn, __pa((unsigned long)__start_rodata) >> PAGE_SHIFT,
280                    __pa((unsigned long)__end_rodata) >> PAGE_SHIFT))
281                 pgprot_val(forbidden) |= _PAGE_RW;
282
283 #if defined(CONFIG_X86_64) && defined(CONFIG_DEBUG_RODATA)
284         /*
285          * Once the kernel maps the text as RO (kernel_set_to_readonly is set),
286          * kernel text mappings for the large page aligned text, rodata sections
287          * will be always read-only. For the kernel identity mappings covering
288          * the holes caused by this alignment can be anything that user asks.
289          *
290          * This will preserve the large page mappings for kernel text/data
291          * at no extra cost.
292          */
293         if (kernel_set_to_readonly &&
294             within(address, (unsigned long)_text,
295                    (unsigned long)__end_rodata_hpage_align)) {
296                 unsigned int level;
297
298                 /*
299                  * Don't enforce the !RW mapping for the kernel text mapping,
300                  * if the current mapping is already using small page mapping.
301                  * No need to work hard to preserve large page mappings in this
302                  * case.
303                  *
304                  * This also fixes the Linux Xen paravirt guest boot failure
305                  * (because of unexpected read-only mappings for kernel identity
306                  * mappings). In this paravirt guest case, the kernel text
307                  * mapping and the kernel identity mapping share the same
308                  * page-table pages. Thus we can't really use different
309                  * protections for the kernel text and identity mappings. Also,
310                  * these shared mappings are made of small page mappings.
311                  * Thus this don't enforce !RW mapping for small page kernel
312                  * text mapping logic will help Linux Xen parvirt guest boot
313                  * as well.
314                  */
315                 if (lookup_address(address, &level) && (level != PG_LEVEL_4K))
316                         pgprot_val(forbidden) |= _PAGE_RW;
317         }
318 #endif
319
320         prot = __pgprot(pgprot_val(prot) & ~pgprot_val(forbidden));
321
322         return prot;
323 }
324
325 /*
326  * Lookup the page table entry for a virtual address. Return a pointer
327  * to the entry and the level of the mapping.
328  *
329  * Note: We return pud and pmd either when the entry is marked large
330  * or when the present bit is not set. Otherwise we would return a
331  * pointer to a nonexisting mapping.
332  */
333 pte_t *lookup_address(unsigned long address, unsigned int *level)
334 {
335         pgd_t *pgd = pgd_offset_k(address);
336         pud_t *pud;
337         pmd_t *pmd;
338
339         *level = PG_LEVEL_NONE;
340
341         if (pgd_none(*pgd))
342                 return NULL;
343
344         pud = pud_offset(pgd, address);
345         if (pud_none(*pud))
346                 return NULL;
347
348         *level = PG_LEVEL_1G;
349         if (pud_large(*pud) || !pud_present(*pud))
350                 return (pte_t *)pud;
351
352         pmd = pmd_offset(pud, address);
353         if (pmd_none(*pmd))
354                 return NULL;
355
356         *level = PG_LEVEL_2M;
357         if (pmd_large(*pmd) || !pmd_present(*pmd))
358                 return (pte_t *)pmd;
359
360         *level = PG_LEVEL_4K;
361
362         return pte_offset_kernel(pmd, address);
363 }
364 EXPORT_SYMBOL_GPL(lookup_address);
365
366 /*
367  * Set the new pmd in all the pgds we know about:
368  */
369 static void __set_pmd_pte(pte_t *kpte, unsigned long address, pte_t pte)
370 {
371         /* change init_mm */
372         set_pte_atomic(kpte, pte);
373 #ifdef CONFIG_X86_32
374         if (!SHARED_KERNEL_PMD) {
375                 struct page *page;
376
377                 list_for_each_entry(page, &pgd_list, lru) {
378                         pgd_t *pgd;
379                         pud_t *pud;
380                         pmd_t *pmd;
381
382                         pgd = (pgd_t *)page_address(page) + pgd_index(address);
383                         pud = pud_offset(pgd, address);
384                         pmd = pmd_offset(pud, address);
385                         set_pte_atomic((pte_t *)pmd, pte);
386                 }
387         }
388 #endif
389 }
390
391 static int
392 try_preserve_large_page(pte_t *kpte, unsigned long address,
393                         struct cpa_data *cpa)
394 {
395         unsigned long nextpage_addr, numpages, pmask, psize, addr, pfn;
396         pte_t new_pte, old_pte, *tmp;
397         pgprot_t old_prot, new_prot, req_prot;
398         int i, do_split = 1;
399         unsigned int level;
400
401         if (cpa->force_split)
402                 return 1;
403
404         spin_lock(&pgd_lock);
405         /*
406          * Check for races, another CPU might have split this page
407          * up already:
408          */
409         tmp = lookup_address(address, &level);
410         if (tmp != kpte)
411                 goto out_unlock;
412
413         switch (level) {
414         case PG_LEVEL_2M:
415                 psize = PMD_PAGE_SIZE;
416                 pmask = PMD_PAGE_MASK;
417                 break;
418 #ifdef CONFIG_X86_64
419         case PG_LEVEL_1G:
420                 psize = PUD_PAGE_SIZE;
421                 pmask = PUD_PAGE_MASK;
422                 break;
423 #endif
424         default:
425                 do_split = -EINVAL;
426                 goto out_unlock;
427         }
428
429         /*
430          * Calculate the number of pages, which fit into this large
431          * page starting at address:
432          */
433         nextpage_addr = (address + psize) & pmask;
434         numpages = (nextpage_addr - address) >> PAGE_SHIFT;
435         if (numpages < cpa->numpages)
436                 cpa->numpages = numpages;
437
438         /*
439          * We are safe now. Check whether the new pgprot is the same:
440          */
441         old_pte = *kpte;
442         old_prot = new_prot = req_prot = pte_pgprot(old_pte);
443
444         pgprot_val(req_prot) &= ~pgprot_val(cpa->mask_clr);
445         pgprot_val(req_prot) |= pgprot_val(cpa->mask_set);
446
447         /*
448          * old_pte points to the large page base address. So we need
449          * to add the offset of the virtual address:
450          */
451         pfn = pte_pfn(old_pte) + ((address & (psize - 1)) >> PAGE_SHIFT);
452         cpa->pfn = pfn;
453
454         new_prot = static_protections(req_prot, address, pfn);
455
456         /*
457          * We need to check the full range, whether
458          * static_protection() requires a different pgprot for one of
459          * the pages in the range we try to preserve:
460          */
461         addr = address & pmask;
462         pfn = pte_pfn(old_pte);
463         for (i = 0; i < (psize >> PAGE_SHIFT); i++, addr += PAGE_SIZE, pfn++) {
464                 pgprot_t chk_prot = static_protections(req_prot, addr, pfn);
465
466                 if (pgprot_val(chk_prot) != pgprot_val(new_prot))
467                         goto out_unlock;
468         }
469
470         /*
471          * If there are no changes, return. maxpages has been updated
472          * above:
473          */
474         if (pgprot_val(new_prot) == pgprot_val(old_prot)) {
475                 do_split = 0;
476                 goto out_unlock;
477         }
478
479         /*
480          * We need to change the attributes. Check, whether we can
481          * change the large page in one go. We request a split, when
482          * the address is not aligned and the number of pages is
483          * smaller than the number of pages in the large page. Note
484          * that we limited the number of possible pages already to
485          * the number of pages in the large page.
486          */
487         if (address == (address & pmask) && cpa->numpages == (psize >> PAGE_SHIFT)) {
488                 /*
489                  * The address is aligned and the number of pages
490                  * covers the full page.
491                  */
492                 new_pte = pfn_pte(pte_pfn(old_pte), canon_pgprot(new_prot));
493                 __set_pmd_pte(kpte, address, new_pte);
494                 cpa->flags |= CPA_FLUSHTLB;
495                 do_split = 0;
496         }
497
498 out_unlock:
499         spin_unlock(&pgd_lock);
500
501         return do_split;
502 }
503
504 static int split_large_page(pte_t *kpte, unsigned long address)
505 {
506         unsigned long pfn, pfninc = 1;
507         unsigned int i, level;
508         pte_t *pbase, *tmp;
509         pgprot_t ref_prot;
510         struct page *base;
511
512         if (!debug_pagealloc)
513                 spin_unlock(&cpa_lock);
514         base = alloc_pages(GFP_KERNEL | __GFP_NOTRACK, 0);
515         if (!debug_pagealloc)
516                 spin_lock(&cpa_lock);
517         if (!base)
518                 return -ENOMEM;
519
520         spin_lock(&pgd_lock);
521         /*
522          * Check for races, another CPU might have split this page
523          * up for us already:
524          */
525         tmp = lookup_address(address, &level);
526         if (tmp != kpte)
527                 goto out_unlock;
528
529         pbase = (pte_t *)page_address(base);
530         paravirt_alloc_pte(&init_mm, page_to_pfn(base));
531         ref_prot = pte_pgprot(pte_clrhuge(*kpte));
532         /*
533          * If we ever want to utilize the PAT bit, we need to
534          * update this function to make sure it's converted from
535          * bit 12 to bit 7 when we cross from the 2MB level to
536          * the 4K level:
537          */
538         WARN_ON_ONCE(pgprot_val(ref_prot) & _PAGE_PAT_LARGE);
539
540 #ifdef CONFIG_X86_64
541         if (level == PG_LEVEL_1G) {
542                 pfninc = PMD_PAGE_SIZE >> PAGE_SHIFT;
543                 pgprot_val(ref_prot) |= _PAGE_PSE;
544         }
545 #endif
546
547         /*
548          * Get the target pfn from the original entry:
549          */
550         pfn = pte_pfn(*kpte);
551         for (i = 0; i < PTRS_PER_PTE; i++, pfn += pfninc)
552                 set_pte(&pbase[i], pfn_pte(pfn, ref_prot));
553
554         if (pfn_range_is_mapped(PFN_DOWN(__pa(address)),
555                                 PFN_DOWN(__pa(address)) + 1))
556                 split_page_count(level);
557
558         /*
559          * Install the new, split up pagetable.
560          *
561          * We use the standard kernel pagetable protections for the new
562          * pagetable protections, the actual ptes set above control the
563          * primary protection behavior:
564          */
565         __set_pmd_pte(kpte, address, mk_pte(base, __pgprot(_KERNPG_TABLE)));
566
567         /*
568          * Intel Atom errata AAH41 workaround.
569          *
570          * The real fix should be in hw or in a microcode update, but
571          * we also probabilistically try to reduce the window of having
572          * a large TLB mixed with 4K TLBs while instruction fetches are
573          * going on.
574          */
575         __flush_tlb_all();
576
577         base = NULL;
578
579 out_unlock:
580         /*
581          * If we dropped out via the lookup_address check under
582          * pgd_lock then stick the page back into the pool:
583          */
584         if (base)
585                 __free_page(base);
586         spin_unlock(&pgd_lock);
587
588         return 0;
589 }
590
591 static int __cpa_process_fault(struct cpa_data *cpa, unsigned long vaddr,
592                                int primary)
593 {
594         /*
595          * Ignore all non primary paths.
596          */
597         if (!primary)
598                 return 0;
599
600         /*
601          * Ignore the NULL PTE for kernel identity mapping, as it is expected
602          * to have holes.
603          * Also set numpages to '1' indicating that we processed cpa req for
604          * one virtual address page and its pfn. TBD: numpages can be set based
605          * on the initial value and the level returned by lookup_address().
606          */
607         if (within(vaddr, PAGE_OFFSET,
608                    PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT))) {
609                 cpa->numpages = 1;
610                 cpa->pfn = __pa(vaddr) >> PAGE_SHIFT;
611                 return 0;
612         } else {
613                 WARN(1, KERN_WARNING "CPA: called for zero pte. "
614                         "vaddr = %lx cpa->vaddr = %lx\n", vaddr,
615                         *cpa->vaddr);
616
617                 return -EFAULT;
618         }
619 }
620
621 static int __change_page_attr(struct cpa_data *cpa, int primary)
622 {
623         unsigned long address;
624         int do_split, err;
625         unsigned int level;
626         pte_t *kpte, old_pte;
627
628         if (cpa->flags & CPA_PAGES_ARRAY) {
629                 struct page *page = cpa->pages[cpa->curpage];
630                 if (unlikely(PageHighMem(page)))
631                         return 0;
632                 address = (unsigned long)page_address(page);
633         } else if (cpa->flags & CPA_ARRAY)
634                 address = cpa->vaddr[cpa->curpage];
635         else
636                 address = *cpa->vaddr;
637 repeat:
638         kpte = lookup_address(address, &level);
639         if (!kpte)
640                 return __cpa_process_fault(cpa, address, primary);
641
642         old_pte = *kpte;
643         if (!pte_val(old_pte))
644                 return __cpa_process_fault(cpa, address, primary);
645
646         if (level == PG_LEVEL_4K) {
647                 pte_t new_pte;
648                 pgprot_t new_prot = pte_pgprot(old_pte);
649                 unsigned long pfn = pte_pfn(old_pte);
650
651                 pgprot_val(new_prot) &= ~pgprot_val(cpa->mask_clr);
652                 pgprot_val(new_prot) |= pgprot_val(cpa->mask_set);
653
654                 new_prot = static_protections(new_prot, address, pfn);
655
656                 /*
657                  * We need to keep the pfn from the existing PTE,
658                  * after all we're only going to change it's attributes
659                  * not the memory it points to
660                  */
661                 new_pte = pfn_pte(pfn, canon_pgprot(new_prot));
662                 cpa->pfn = pfn;
663                 /*
664                  * Do we really change anything ?
665                  */
666                 if (pte_val(old_pte) != pte_val(new_pte)) {
667                         set_pte_atomic(kpte, new_pte);
668                         cpa->flags |= CPA_FLUSHTLB;
669                 }
670                 cpa->numpages = 1;
671                 return 0;
672         }
673
674         /*
675          * Check, whether we can keep the large page intact
676          * and just change the pte:
677          */
678         do_split = try_preserve_large_page(kpte, address, cpa);
679         /*
680          * When the range fits into the existing large page,
681          * return. cp->numpages and cpa->tlbflush have been updated in
682          * try_large_page:
683          */
684         if (do_split <= 0)
685                 return do_split;
686
687         /*
688          * We have to split the large page:
689          */
690         err = split_large_page(kpte, address);
691         if (!err) {
692                 /*
693                  * Do a global flush tlb after splitting the large page
694                  * and before we do the actual change page attribute in the PTE.
695                  *
696                  * With out this, we violate the TLB application note, that says
697                  * "The TLBs may contain both ordinary and large-page
698                  *  translations for a 4-KByte range of linear addresses. This
699                  *  may occur if software modifies the paging structures so that
700                  *  the page size used for the address range changes. If the two
701                  *  translations differ with respect to page frame or attributes
702                  *  (e.g., permissions), processor behavior is undefined and may
703                  *  be implementation-specific."
704                  *
705                  * We do this global tlb flush inside the cpa_lock, so that we
706                  * don't allow any other cpu, with stale tlb entries change the
707                  * page attribute in parallel, that also falls into the
708                  * just split large page entry.
709                  */
710                 flush_tlb_all();
711                 goto repeat;
712         }
713
714         return err;
715 }
716
717 static int __change_page_attr_set_clr(struct cpa_data *cpa, int checkalias);
718
719 static int cpa_process_alias(struct cpa_data *cpa)
720 {
721         struct cpa_data alias_cpa;
722         unsigned long laddr = (unsigned long)__va(cpa->pfn << PAGE_SHIFT);
723         unsigned long vaddr;
724         int ret;
725
726         if (!pfn_range_is_mapped(cpa->pfn, cpa->pfn + 1))
727                 return 0;
728
729         /*
730          * No need to redo, when the primary call touched the direct
731          * mapping already:
732          */
733         if (cpa->flags & CPA_PAGES_ARRAY) {
734                 struct page *page = cpa->pages[cpa->curpage];
735                 if (unlikely(PageHighMem(page)))
736                         return 0;
737                 vaddr = (unsigned long)page_address(page);
738         } else if (cpa->flags & CPA_ARRAY)
739                 vaddr = cpa->vaddr[cpa->curpage];
740         else
741                 vaddr = *cpa->vaddr;
742
743         if (!(within(vaddr, PAGE_OFFSET,
744                     PAGE_OFFSET + (max_pfn_mapped << PAGE_SHIFT)))) {
745
746                 alias_cpa = *cpa;
747                 alias_cpa.vaddr = &laddr;
748                 alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
749
750                 ret = __change_page_attr_set_clr(&alias_cpa, 0);
751                 if (ret)
752                         return ret;
753         }
754
755 #ifdef CONFIG_X86_64
756         /*
757          * If the primary call didn't touch the high mapping already
758          * and the physical address is inside the kernel map, we need
759          * to touch the high mapped kernel as well:
760          */
761         if (!within(vaddr, (unsigned long)_text, _brk_end) &&
762             within(cpa->pfn, highmap_start_pfn(), highmap_end_pfn())) {
763                 unsigned long temp_cpa_vaddr = (cpa->pfn << PAGE_SHIFT) +
764                                                __START_KERNEL_map - phys_base;
765                 alias_cpa = *cpa;
766                 alias_cpa.vaddr = &temp_cpa_vaddr;
767                 alias_cpa.flags &= ~(CPA_PAGES_ARRAY | CPA_ARRAY);
768
769                 /*
770                  * The high mapping range is imprecise, so ignore the
771                  * return value.
772                  */
773                 __change_page_attr_set_clr(&alias_cpa, 0);
774         }
775 #endif
776
777         return 0;
778 }
779
780 static int __change_page_attr_set_clr(struct cpa_data *cpa, int checkalias)
781 {
782         int ret, numpages = cpa->numpages;
783
784         while (numpages) {
785                 /*
786                  * Store the remaining nr of pages for the large page
787                  * preservation check.
788                  */
789                 cpa->numpages = numpages;
790                 /* for array changes, we can't use large page */
791                 if (cpa->flags & (CPA_ARRAY | CPA_PAGES_ARRAY))
792                         cpa->numpages = 1;
793
794                 if (!debug_pagealloc)
795                         spin_lock(&cpa_lock);
796                 ret = __change_page_attr(cpa, checkalias);
797                 if (!debug_pagealloc)
798                         spin_unlock(&cpa_lock);
799                 if (ret)
800                         return ret;
801
802                 if (checkalias) {
803                         ret = cpa_process_alias(cpa);
804                         if (ret)
805                                 return ret;
806                 }
807
808                 /*
809                  * Adjust the number of pages with the result of the
810                  * CPA operation. Either a large page has been
811                  * preserved or a single page update happened.
812                  */
813                 BUG_ON(cpa->numpages > numpages);
814                 numpages -= cpa->numpages;
815                 if (cpa->flags & (CPA_PAGES_ARRAY | CPA_ARRAY))
816                         cpa->curpage++;
817                 else
818                         *cpa->vaddr += cpa->numpages * PAGE_SIZE;
819
820         }
821         return 0;
822 }
823
824 static inline int cache_attr(pgprot_t attr)
825 {
826         return pgprot_val(attr) &
827                 (_PAGE_PAT | _PAGE_PAT_LARGE | _PAGE_PWT | _PAGE_PCD);
828 }
829
830 static int change_page_attr_set_clr(unsigned long *addr, int numpages,
831                                     pgprot_t mask_set, pgprot_t mask_clr,
832                                     int force_split, int in_flag,
833                                     struct page **pages)
834 {
835         struct cpa_data cpa;
836         int ret, cache, checkalias;
837         unsigned long baddr = 0;
838
839         /*
840          * Check, if we are requested to change a not supported
841          * feature:
842          */
843         mask_set = canon_pgprot(mask_set);
844         mask_clr = canon_pgprot(mask_clr);
845         if (!pgprot_val(mask_set) && !pgprot_val(mask_clr) && !force_split)
846                 return 0;
847
848         /* Ensure we are PAGE_SIZE aligned */
849         if (in_flag & CPA_ARRAY) {
850                 int i;
851                 for (i = 0; i < numpages; i++) {
852                         if (addr[i] & ~PAGE_MASK) {
853                                 addr[i] &= PAGE_MASK;
854                                 WARN_ON_ONCE(1);
855                         }
856                 }
857         } else if (!(in_flag & CPA_PAGES_ARRAY)) {
858                 /*
859                  * in_flag of CPA_PAGES_ARRAY implies it is aligned.
860                  * No need to cehck in that case
861                  */
862                 if (*addr & ~PAGE_MASK) {
863                         *addr &= PAGE_MASK;
864                         /*
865                          * People should not be passing in unaligned addresses:
866                          */
867                         WARN_ON_ONCE(1);
868                 }
869                 /*
870                  * Save address for cache flush. *addr is modified in the call
871                  * to __change_page_attr_set_clr() below.
872                  */
873                 baddr = *addr;
874         }
875
876         /* Must avoid aliasing mappings in the highmem code */
877         kmap_flush_unused();
878
879         vm_unmap_aliases();
880
881         cpa.vaddr = addr;
882         cpa.pages = pages;
883         cpa.numpages = numpages;
884         cpa.mask_set = mask_set;
885         cpa.mask_clr = mask_clr;
886         cpa.flags = 0;
887         cpa.curpage = 0;
888         cpa.force_split = force_split;
889
890         if (in_flag & (CPA_ARRAY | CPA_PAGES_ARRAY))
891                 cpa.flags |= in_flag;
892
893         /* No alias checking for _NX bit modifications */
894         checkalias = (pgprot_val(mask_set) | pgprot_val(mask_clr)) != _PAGE_NX;
895
896         ret = __change_page_attr_set_clr(&cpa, checkalias);
897
898         /*
899          * Check whether we really changed something:
900          */
901         if (!(cpa.flags & CPA_FLUSHTLB))
902                 goto out;
903
904         /*
905          * No need to flush, when we did not set any of the caching
906          * attributes:
907          */
908         cache = cache_attr(mask_set);
909
910         /*
911          * On success we use clflush, when the CPU supports it to
912          * avoid the wbindv. If the CPU does not support it and in the
913          * error case we fall back to cpa_flush_all (which uses
914          * wbindv):
915          */
916         if (!ret && cpu_has_clflush) {
917                 if (cpa.flags & (CPA_PAGES_ARRAY | CPA_ARRAY)) {
918                         cpa_flush_array(addr, numpages, cache,
919                                         cpa.flags, pages);
920                 } else
921                         cpa_flush_range(baddr, numpages, cache);
922         } else
923                 cpa_flush_all(cache);
924
925 out:
926         return ret;
927 }
928
929 static inline int change_page_attr_set(unsigned long *addr, int numpages,
930                                        pgprot_t mask, int array)
931 {
932         return change_page_attr_set_clr(addr, numpages, mask, __pgprot(0), 0,
933                 (array ? CPA_ARRAY : 0), NULL);
934 }
935
936 static inline int change_page_attr_clear(unsigned long *addr, int numpages,
937                                          pgprot_t mask, int array)
938 {
939         return change_page_attr_set_clr(addr, numpages, __pgprot(0), mask, 0,
940                 (array ? CPA_ARRAY : 0), NULL);
941 }
942
943 static inline int cpa_set_pages_array(struct page **pages, int numpages,
944                                        pgprot_t mask)
945 {
946         return change_page_attr_set_clr(NULL, numpages, mask, __pgprot(0), 0,
947                 CPA_PAGES_ARRAY, pages);
948 }
949
950 static inline int cpa_clear_pages_array(struct page **pages, int numpages,
951                                          pgprot_t mask)
952 {
953         return change_page_attr_set_clr(NULL, numpages, __pgprot(0), mask, 0,
954                 CPA_PAGES_ARRAY, pages);
955 }
956
957 int _set_memory_uc(unsigned long addr, int numpages)
958 {
959         /*
960          * for now UC MINUS. see comments in ioremap_nocache()
961          */
962         return change_page_attr_set(&addr, numpages,
963                                     __pgprot(_PAGE_CACHE_UC_MINUS), 0);
964 }
965
966 int set_memory_uc(unsigned long addr, int numpages)
967 {
968         int ret;
969
970         /*
971          * for now UC MINUS. see comments in ioremap_nocache()
972          */
973         ret = reserve_memtype(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
974                             _PAGE_CACHE_UC_MINUS, NULL);
975         if (ret)
976                 goto out_err;
977
978         ret = _set_memory_uc(addr, numpages);
979         if (ret)
980                 goto out_free;
981
982         return 0;
983
984 out_free:
985         free_memtype(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
986 out_err:
987         return ret;
988 }
989 EXPORT_SYMBOL(set_memory_uc);
990
991 static int _set_memory_array(unsigned long *addr, int addrinarray,
992                 unsigned long new_type)
993 {
994         int i, j;
995         int ret;
996
997         /*
998          * for now UC MINUS. see comments in ioremap_nocache()
999          */
1000         for (i = 0; i < addrinarray; i++) {
1001                 ret = reserve_memtype(__pa(addr[i]), __pa(addr[i]) + PAGE_SIZE,
1002                                         new_type, NULL);
1003                 if (ret)
1004                         goto out_free;
1005         }
1006
1007         ret = change_page_attr_set(addr, addrinarray,
1008                                     __pgprot(_PAGE_CACHE_UC_MINUS), 1);
1009
1010         if (!ret && new_type == _PAGE_CACHE_WC)
1011                 ret = change_page_attr_set_clr(addr, addrinarray,
1012                                                __pgprot(_PAGE_CACHE_WC),
1013                                                __pgprot(_PAGE_CACHE_MASK),
1014                                                0, CPA_ARRAY, NULL);
1015         if (ret)
1016                 goto out_free;
1017
1018         return 0;
1019
1020 out_free:
1021         for (j = 0; j < i; j++)
1022                 free_memtype(__pa(addr[j]), __pa(addr[j]) + PAGE_SIZE);
1023
1024         return ret;
1025 }
1026
1027 int set_memory_array_uc(unsigned long *addr, int addrinarray)
1028 {
1029         return _set_memory_array(addr, addrinarray, _PAGE_CACHE_UC_MINUS);
1030 }
1031 EXPORT_SYMBOL(set_memory_array_uc);
1032
1033 int set_memory_array_wc(unsigned long *addr, int addrinarray)
1034 {
1035         return _set_memory_array(addr, addrinarray, _PAGE_CACHE_WC);
1036 }
1037 EXPORT_SYMBOL(set_memory_array_wc);
1038
1039 int _set_memory_wc(unsigned long addr, int numpages)
1040 {
1041         int ret;
1042         unsigned long addr_copy = addr;
1043
1044         ret = change_page_attr_set(&addr, numpages,
1045                                     __pgprot(_PAGE_CACHE_UC_MINUS), 0);
1046         if (!ret) {
1047                 ret = change_page_attr_set_clr(&addr_copy, numpages,
1048                                                __pgprot(_PAGE_CACHE_WC),
1049                                                __pgprot(_PAGE_CACHE_MASK),
1050                                                0, 0, NULL);
1051         }
1052         return ret;
1053 }
1054
1055 int set_memory_wc(unsigned long addr, int numpages)
1056 {
1057         int ret;
1058
1059         if (!pat_enabled)
1060                 return set_memory_uc(addr, numpages);
1061
1062         ret = reserve_memtype(__pa(addr), __pa(addr) + numpages * PAGE_SIZE,
1063                 _PAGE_CACHE_WC, NULL);
1064         if (ret)
1065                 goto out_err;
1066
1067         ret = _set_memory_wc(addr, numpages);
1068         if (ret)
1069                 goto out_free;
1070
1071         return 0;
1072
1073 out_free:
1074         free_memtype(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
1075 out_err:
1076         return ret;
1077 }
1078 EXPORT_SYMBOL(set_memory_wc);
1079
1080 int _set_memory_wb(unsigned long addr, int numpages)
1081 {
1082         return change_page_attr_clear(&addr, numpages,
1083                                       __pgprot(_PAGE_CACHE_MASK), 0);
1084 }
1085
1086 int set_memory_wb(unsigned long addr, int numpages)
1087 {
1088         int ret;
1089
1090         ret = _set_memory_wb(addr, numpages);
1091         if (ret)
1092                 return ret;
1093
1094         free_memtype(__pa(addr), __pa(addr) + numpages * PAGE_SIZE);
1095         return 0;
1096 }
1097 EXPORT_SYMBOL(set_memory_wb);
1098
1099 int set_memory_array_wb(unsigned long *addr, int addrinarray)
1100 {
1101         int i;
1102         int ret;
1103
1104         ret = change_page_attr_clear(addr, addrinarray,
1105                                       __pgprot(_PAGE_CACHE_MASK), 1);
1106         if (ret)
1107                 return ret;
1108
1109         for (i = 0; i < addrinarray; i++)
1110                 free_memtype(__pa(addr[i]), __pa(addr[i]) + PAGE_SIZE);
1111
1112         return 0;
1113 }
1114 EXPORT_SYMBOL(set_memory_array_wb);
1115
1116 int set_memory_x(unsigned long addr, int numpages)
1117 {
1118         if (!(__supported_pte_mask & _PAGE_NX))
1119                 return 0;
1120
1121         return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_NX), 0);
1122 }
1123 EXPORT_SYMBOL(set_memory_x);
1124
1125 int set_memory_nx(unsigned long addr, int numpages)
1126 {
1127         if (!(__supported_pte_mask & _PAGE_NX))
1128                 return 0;
1129
1130         return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_NX), 0);
1131 }
1132 EXPORT_SYMBOL(set_memory_nx);
1133
1134 int set_memory_ro(unsigned long addr, int numpages)
1135 {
1136         return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_RW), 0);
1137 }
1138 EXPORT_SYMBOL_GPL(set_memory_ro);
1139
1140 int set_memory_rw(unsigned long addr, int numpages)
1141 {
1142         return change_page_attr_set(&addr, numpages, __pgprot(_PAGE_RW), 0);
1143 }
1144 EXPORT_SYMBOL_GPL(set_memory_rw);
1145
1146 int set_memory_np(unsigned long addr, int numpages)
1147 {
1148         return change_page_attr_clear(&addr, numpages, __pgprot(_PAGE_PRESENT), 0);
1149 }
1150
1151 int set_memory_4k(unsigned long addr, int numpages)
1152 {
1153         return change_page_attr_set_clr(&addr, numpages, __pgprot(0),
1154                                         __pgprot(0), 1, 0, NULL);
1155 }
1156
1157 int set_pages_uc(struct page *page, int numpages)
1158 {
1159         unsigned long addr = (unsigned long)page_address(page);
1160
1161         return set_memory_uc(addr, numpages);
1162 }
1163 EXPORT_SYMBOL(set_pages_uc);
1164
1165 static int _set_pages_array(struct page **pages, int addrinarray,
1166                 unsigned long new_type)
1167 {
1168         unsigned long start;
1169         unsigned long end;
1170         int i;
1171         int free_idx;
1172         int ret;
1173
1174         for (i = 0; i < addrinarray; i++) {
1175                 if (PageHighMem(pages[i]))
1176                         continue;
1177                 start = page_to_pfn(pages[i]) << PAGE_SHIFT;
1178                 end = start + PAGE_SIZE;
1179                 if (reserve_memtype(start, end, new_type, NULL))
1180                         goto err_out;
1181         }
1182
1183         ret = cpa_set_pages_array(pages, addrinarray,
1184                         __pgprot(_PAGE_CACHE_UC_MINUS));
1185         if (!ret && new_type == _PAGE_CACHE_WC)
1186                 ret = change_page_attr_set_clr(NULL, addrinarray,
1187                                                __pgprot(_PAGE_CACHE_WC),
1188                                                __pgprot(_PAGE_CACHE_MASK),
1189                                                0, CPA_PAGES_ARRAY, pages);
1190         if (ret)
1191                 goto err_out;
1192         return 0; /* Success */
1193 err_out:
1194         free_idx = i;
1195         for (i = 0; i < free_idx; i++) {
1196                 if (PageHighMem(pages[i]))
1197                         continue;
1198                 start = page_to_pfn(pages[i]) << PAGE_SHIFT;
1199                 end = start + PAGE_SIZE;
1200                 free_memtype(start, end);
1201         }
1202         return -EINVAL;
1203 }
1204
1205 int set_pages_array_uc(struct page **pages, int addrinarray)
1206 {
1207         return _set_pages_array(pages, addrinarray, _PAGE_CACHE_UC_MINUS);
1208 }
1209 EXPORT_SYMBOL(set_pages_array_uc);
1210
1211 int set_pages_array_wc(struct page **pages, int addrinarray)
1212 {
1213         return _set_pages_array(pages, addrinarray, _PAGE_CACHE_WC);
1214 }
1215 EXPORT_SYMBOL(set_pages_array_wc);
1216
1217 int set_pages_wb(struct page *page, int numpages)
1218 {
1219         unsigned long addr = (unsigned long)page_address(page);
1220
1221         return set_memory_wb(addr, numpages);
1222 }
1223 EXPORT_SYMBOL(set_pages_wb);
1224
1225 int set_pages_array_wb(struct page **pages, int addrinarray)
1226 {
1227         int retval;
1228         unsigned long start;
1229         unsigned long end;
1230         int i;
1231
1232         retval = cpa_clear_pages_array(pages, addrinarray,
1233                         __pgprot(_PAGE_CACHE_MASK));
1234         if (retval)
1235                 return retval;
1236
1237         for (i = 0; i < addrinarray; i++) {
1238                 if (PageHighMem(pages[i]))
1239                         continue;
1240                 start = page_to_pfn(pages[i]) << PAGE_SHIFT;
1241                 end = start + PAGE_SIZE;
1242                 free_memtype(start, end);
1243         }
1244
1245         return 0;
1246 }
1247 EXPORT_SYMBOL(set_pages_array_wb);
1248
1249 int set_pages_x(struct page *page, int numpages)
1250 {
1251         unsigned long addr = (unsigned long)page_address(page);
1252
1253         return set_memory_x(addr, numpages);
1254 }
1255 EXPORT_SYMBOL(set_pages_x);
1256
1257 int set_pages_nx(struct page *page, int numpages)
1258 {
1259         unsigned long addr = (unsigned long)page_address(page);
1260
1261         return set_memory_nx(addr, numpages);
1262 }
1263 EXPORT_SYMBOL(set_pages_nx);
1264
1265 int set_pages_ro(struct page *page, int numpages)
1266 {
1267         unsigned long addr = (unsigned long)page_address(page);
1268
1269         return set_memory_ro(addr, numpages);
1270 }
1271
1272 int set_pages_rw(struct page *page, int numpages)
1273 {
1274         unsigned long addr = (unsigned long)page_address(page);
1275
1276         return set_memory_rw(addr, numpages);
1277 }
1278
1279 #ifdef CONFIG_DEBUG_PAGEALLOC
1280
1281 static int __set_pages_p(struct page *page, int numpages)
1282 {
1283         unsigned long tempaddr = (unsigned long) page_address(page);
1284         struct cpa_data cpa = { .vaddr = &tempaddr,
1285                                 .numpages = numpages,
1286                                 .mask_set = __pgprot(_PAGE_PRESENT | _PAGE_RW),
1287                                 .mask_clr = __pgprot(0),
1288                                 .flags = 0};
1289
1290         /*
1291          * No alias checking needed for setting present flag. otherwise,
1292          * we may need to break large pages for 64-bit kernel text
1293          * mappings (this adds to complexity if we want to do this from
1294          * atomic context especially). Let's keep it simple!
1295          */
1296         return __change_page_attr_set_clr(&cpa, 0);
1297 }
1298
1299 static int __set_pages_np(struct page *page, int numpages)
1300 {
1301         unsigned long tempaddr = (unsigned long) page_address(page);
1302         struct cpa_data cpa = { .vaddr = &tempaddr,
1303                                 .numpages = numpages,
1304                                 .mask_set = __pgprot(0),
1305                                 .mask_clr = __pgprot(_PAGE_PRESENT | _PAGE_RW),
1306                                 .flags = 0};
1307
1308         /*
1309          * No alias checking needed for setting not present flag. otherwise,
1310          * we may need to break large pages for 64-bit kernel text
1311          * mappings (this adds to complexity if we want to do this from
1312          * atomic context especially). Let's keep it simple!
1313          */
1314         return __change_page_attr_set_clr(&cpa, 0);
1315 }
1316
1317 void kernel_map_pages(struct page *page, int numpages, int enable)
1318 {
1319         if (PageHighMem(page))
1320                 return;
1321         if (!enable) {
1322                 debug_check_no_locks_freed(page_address(page),
1323                                            numpages * PAGE_SIZE);
1324         }
1325
1326         /*
1327          * The return value is ignored as the calls cannot fail.
1328          * Large pages for identity mappings are not used at boot time
1329          * and hence no memory allocations during large page split.
1330          */
1331         if (enable)
1332                 __set_pages_p(page, numpages);
1333         else
1334                 __set_pages_np(page, numpages);
1335
1336         /*
1337          * We should perform an IPI and flush all tlbs,
1338          * but that can deadlock->flush only current cpu:
1339          */
1340         __flush_tlb_all();
1341 }
1342
1343 #ifdef CONFIG_HIBERNATION
1344
1345 bool kernel_page_present(struct page *page)
1346 {
1347         unsigned int level;
1348         pte_t *pte;
1349
1350         if (PageHighMem(page))
1351                 return false;
1352
1353         pte = lookup_address((unsigned long)page_address(page), &level);
1354         return (pte_val(*pte) & _PAGE_PRESENT);
1355 }
1356
1357 #endif /* CONFIG_HIBERNATION */
1358
1359 #endif /* CONFIG_DEBUG_PAGEALLOC */
1360
1361 /*
1362  * The testcases use internal knowledge of the implementation that shouldn't
1363  * be exposed to the rest of the kernel. Include these directly here.
1364  */
1365 #ifdef CONFIG_CPA_DEBUG
1366 #include "pageattr-test.c"
1367 #endif