05f9aef6818a14f02c87b7a4e4cf6a0d5d455b71
[pandora-kernel.git] / arch / x86 / mm / pat.c
1 /*
2  * Handle caching attributes in page tables (PAT)
3  *
4  * Authors: Venkatesh Pallipadi <venkatesh.pallipadi@intel.com>
5  *          Suresh B Siddha <suresh.b.siddha@intel.com>
6  *
7  * Loosely based on earlier PAT patchset from Eric Biederman and Andi Kleen.
8  */
9
10 #include <linux/seq_file.h>
11 #include <linux/bootmem.h>
12 #include <linux/debugfs.h>
13 #include <linux/kernel.h>
14 #include <linux/gfp.h>
15 #include <linux/mm.h>
16 #include <linux/fs.h>
17
18 #include <asm/cacheflush.h>
19 #include <asm/processor.h>
20 #include <asm/tlbflush.h>
21 #include <asm/pgtable.h>
22 #include <asm/fcntl.h>
23 #include <asm/e820.h>
24 #include <asm/mtrr.h>
25 #include <asm/page.h>
26 #include <asm/msr.h>
27 #include <asm/pat.h>
28 #include <asm/io.h>
29
30 #ifdef CONFIG_X86_PAT
31 int __read_mostly pat_enabled = 1;
32
33 void __cpuinit pat_disable(const char *reason)
34 {
35         pat_enabled = 0;
36         printk(KERN_INFO "%s\n", reason);
37 }
38
39 static int __init nopat(char *str)
40 {
41         pat_disable("PAT support disabled.");
42         return 0;
43 }
44 early_param("nopat", nopat);
45 #else
46 static inline void pat_disable(const char *reason)
47 {
48         (void)reason;
49 }
50 #endif
51
52
53 static int debug_enable;
54
55 static int __init pat_debug_setup(char *str)
56 {
57         debug_enable = 1;
58         return 0;
59 }
60 __setup("debugpat", pat_debug_setup);
61
62 #define dprintk(fmt, arg...) \
63         do { if (debug_enable) printk(KERN_INFO fmt, ##arg); } while (0)
64
65
66 static u64 __read_mostly boot_pat_state;
67
68 enum {
69         PAT_UC = 0,             /* uncached */
70         PAT_WC = 1,             /* Write combining */
71         PAT_WT = 4,             /* Write Through */
72         PAT_WP = 5,             /* Write Protected */
73         PAT_WB = 6,             /* Write Back (default) */
74         PAT_UC_MINUS = 7,       /* UC, but can be overriden by MTRR */
75 };
76
77 #define PAT(x, y)       ((u64)PAT_ ## y << ((x)*8))
78
79 void pat_init(void)
80 {
81         u64 pat;
82
83         if (!pat_enabled)
84                 return;
85
86         if (!cpu_has_pat) {
87                 if (!boot_pat_state) {
88                         pat_disable("PAT not supported by CPU.");
89                         return;
90                 } else {
91                         /*
92                          * If this happens we are on a secondary CPU, but
93                          * switched to PAT on the boot CPU. We have no way to
94                          * undo PAT.
95                          */
96                         printk(KERN_ERR "PAT enabled, "
97                                "but not supported by secondary CPU\n");
98                         BUG();
99                 }
100         }
101
102         /* Set PWT to Write-Combining. All other bits stay the same */
103         /*
104          * PTE encoding used in Linux:
105          *      PAT
106          *      |PCD
107          *      ||PWT
108          *      |||
109          *      000 WB          _PAGE_CACHE_WB
110          *      001 WC          _PAGE_CACHE_WC
111          *      010 UC-         _PAGE_CACHE_UC_MINUS
112          *      011 UC          _PAGE_CACHE_UC
113          * PAT bit unused
114          */
115         pat = PAT(0, WB) | PAT(1, WC) | PAT(2, UC_MINUS) | PAT(3, UC) |
116               PAT(4, WB) | PAT(5, WC) | PAT(6, UC_MINUS) | PAT(7, UC);
117
118         /* Boot CPU check */
119         if (!boot_pat_state)
120                 rdmsrl(MSR_IA32_CR_PAT, boot_pat_state);
121
122         wrmsrl(MSR_IA32_CR_PAT, pat);
123         printk(KERN_INFO "x86 PAT enabled: cpu %d, old 0x%Lx, new 0x%Lx\n",
124                smp_processor_id(), boot_pat_state, pat);
125 }
126
127 #undef PAT
128
129 static char *cattr_name(unsigned long flags)
130 {
131         switch (flags & _PAGE_CACHE_MASK) {
132         case _PAGE_CACHE_UC:            return "uncached";
133         case _PAGE_CACHE_UC_MINUS:      return "uncached-minus";
134         case _PAGE_CACHE_WB:            return "write-back";
135         case _PAGE_CACHE_WC:            return "write-combining";
136         default:                        return "broken";
137         }
138 }
139
140 /*
141  * The global memtype list keeps track of memory type for specific
142  * physical memory areas. Conflicting memory types in different
143  * mappings can cause CPU cache corruption. To avoid this we keep track.
144  *
145  * The list is sorted based on starting address and can contain multiple
146  * entries for each address (this allows reference counting for overlapping
147  * areas). All the aliases have the same cache attributes of course.
148  * Zero attributes are represented as holes.
149  *
150  * Currently the data structure is a list because the number of mappings
151  * are expected to be relatively small. If this should be a problem
152  * it could be changed to a rbtree or similar.
153  *
154  * memtype_lock protects the whole list.
155  */
156
157 struct memtype {
158         u64                     start;
159         u64                     end;
160         unsigned long           type;
161         struct list_head        nd;
162 };
163
164 static LIST_HEAD(memtype_list);
165 static DEFINE_SPINLOCK(memtype_lock);   /* protects memtype list */
166
167 /*
168  * Does intersection of PAT memory type and MTRR memory type and returns
169  * the resulting memory type as PAT understands it.
170  * (Type in pat and mtrr will not have same value)
171  * The intersection is based on "Effective Memory Type" tables in IA-32
172  * SDM vol 3a
173  */
174 static unsigned long pat_x_mtrr_type(u64 start, u64 end, unsigned long req_type)
175 {
176         /*
177          * Look for MTRR hint to get the effective type in case where PAT
178          * request is for WB.
179          */
180         if (req_type == _PAGE_CACHE_WB) {
181                 u8 mtrr_type;
182
183                 mtrr_type = mtrr_type_lookup(start, end);
184                 if (mtrr_type == MTRR_TYPE_UNCACHABLE)
185                         return _PAGE_CACHE_UC;
186                 if (mtrr_type == MTRR_TYPE_WRCOMB)
187                         return _PAGE_CACHE_WC;
188         }
189
190         return req_type;
191 }
192
193 static int
194 chk_conflict(struct memtype *new, struct memtype *entry, unsigned long *type)
195 {
196         if (new->type != entry->type) {
197                 if (type) {
198                         new->type = entry->type;
199                         *type = entry->type;
200                 } else
201                         goto conflict;
202         }
203
204          /* check overlaps with more than one entry in the list */
205         list_for_each_entry_continue(entry, &memtype_list, nd) {
206                 if (new->end <= entry->start)
207                         break;
208                 else if (new->type != entry->type)
209                         goto conflict;
210         }
211         return 0;
212
213  conflict:
214         printk(KERN_INFO "%s:%d conflicting memory types "
215                "%Lx-%Lx %s<->%s\n", current->comm, current->pid, new->start,
216                new->end, cattr_name(new->type), cattr_name(entry->type));
217         return -EBUSY;
218 }
219
220 static struct memtype *cached_entry;
221 static u64 cached_start;
222
223 static int pat_pagerange_is_ram(unsigned long start, unsigned long end)
224 {
225         int ram_page = 0, not_rampage = 0;
226         unsigned long page_nr;
227
228         for (page_nr = (start >> PAGE_SHIFT); page_nr < (end >> PAGE_SHIFT);
229              ++page_nr) {
230                 /*
231                  * For legacy reasons, physical address range in the legacy ISA
232                  * region is tracked as non-RAM. This will allow users of
233                  * /dev/mem to map portions of legacy ISA region, even when
234                  * some of those portions are listed(or not even listed) with
235                  * different e820 types(RAM/reserved/..)
236                  */
237                 if (page_nr >= (ISA_END_ADDRESS >> PAGE_SHIFT) &&
238                     page_is_ram(page_nr))
239                         ram_page = 1;
240                 else
241                         not_rampage = 1;
242
243                 if (ram_page == not_rampage)
244                         return -1;
245         }
246
247         return ram_page;
248 }
249
250 /*
251  * For RAM pages, mark the pages as non WB memory type using
252  * PageNonWB (PG_arch_1). We allow only one set_memory_uc() or
253  * set_memory_wc() on a RAM page at a time before marking it as WB again.
254  * This is ok, because only one driver will be owning the page and
255  * doing set_memory_*() calls.
256  *
257  * For now, we use PageNonWB to track that the RAM page is being mapped
258  * as non WB. In future, we will have to use one more flag
259  * (or some other mechanism in page_struct) to distinguish between
260  * UC and WC mapping.
261  */
262 static int reserve_ram_pages_type(u64 start, u64 end, unsigned long req_type,
263                                   unsigned long *new_type)
264 {
265         struct page *page;
266         u64 pfn, end_pfn;
267
268         for (pfn = (start >> PAGE_SHIFT); pfn < (end >> PAGE_SHIFT); ++pfn) {
269                 page = pfn_to_page(pfn);
270                 if (page_mapped(page) || PageNonWB(page))
271                         goto out;
272
273                 SetPageNonWB(page);
274         }
275         return 0;
276
277 out:
278         end_pfn = pfn;
279         for (pfn = (start >> PAGE_SHIFT); pfn < end_pfn; ++pfn) {
280                 page = pfn_to_page(pfn);
281                 ClearPageNonWB(page);
282         }
283
284         return -EINVAL;
285 }
286
287 static int free_ram_pages_type(u64 start, u64 end)
288 {
289         struct page *page;
290         u64 pfn, end_pfn;
291
292         for (pfn = (start >> PAGE_SHIFT); pfn < (end >> PAGE_SHIFT); ++pfn) {
293                 page = pfn_to_page(pfn);
294                 if (page_mapped(page) || !PageNonWB(page))
295                         goto out;
296
297                 ClearPageNonWB(page);
298         }
299         return 0;
300
301 out:
302         end_pfn = pfn;
303         for (pfn = (start >> PAGE_SHIFT); pfn < end_pfn; ++pfn) {
304                 page = pfn_to_page(pfn);
305                 SetPageNonWB(page);
306         }
307         return -EINVAL;
308 }
309
310 /*
311  * req_type typically has one of the:
312  * - _PAGE_CACHE_WB
313  * - _PAGE_CACHE_WC
314  * - _PAGE_CACHE_UC_MINUS
315  * - _PAGE_CACHE_UC
316  *
317  * req_type will have a special case value '-1', when requester want to inherit
318  * the memory type from mtrr (if WB), existing PAT, defaulting to UC_MINUS.
319  *
320  * If new_type is NULL, function will return an error if it cannot reserve the
321  * region with req_type. If new_type is non-NULL, function will return
322  * available type in new_type in case of no error. In case of any error
323  * it will return a negative return value.
324  */
325 int reserve_memtype(u64 start, u64 end, unsigned long req_type,
326                     unsigned long *new_type)
327 {
328         struct memtype *new, *entry;
329         unsigned long actual_type;
330         struct list_head *where;
331         int is_range_ram;
332         int err = 0;
333
334         BUG_ON(start >= end); /* end is exclusive */
335
336         if (!pat_enabled) {
337                 /* This is identical to page table setting without PAT */
338                 if (new_type) {
339                         if (req_type == -1)
340                                 *new_type = _PAGE_CACHE_WB;
341                         else
342                                 *new_type = req_type & _PAGE_CACHE_MASK;
343                 }
344                 return 0;
345         }
346
347         /* Low ISA region is always mapped WB in page table. No need to track */
348         if (is_ISA_range(start, end - 1)) {
349                 if (new_type)
350                         *new_type = _PAGE_CACHE_WB;
351                 return 0;
352         }
353
354         if (req_type == -1) {
355                 /*
356                  * Call mtrr_lookup to get the type hint. This is an
357                  * optimization for /dev/mem mmap'ers into WB memory (BIOS
358                  * tools and ACPI tools). Use WB request for WB memory and use
359                  * UC_MINUS otherwise.
360                  */
361                 u8 mtrr_type = mtrr_type_lookup(start, end);
362
363                 if (mtrr_type == MTRR_TYPE_WRBACK)
364                         actual_type = _PAGE_CACHE_WB;
365                 else
366                         actual_type = _PAGE_CACHE_UC_MINUS;
367         } else {
368                 actual_type = pat_x_mtrr_type(start, end,
369                                               req_type & _PAGE_CACHE_MASK);
370         }
371
372         if (new_type)
373                 *new_type = actual_type;
374
375         is_range_ram = pat_pagerange_is_ram(start, end);
376         if (is_range_ram == 1)
377                 return reserve_ram_pages_type(start, end, req_type,
378                                               new_type);
379         else if (is_range_ram < 0)
380                 return -EINVAL;
381
382         new  = kmalloc(sizeof(struct memtype), GFP_KERNEL);
383         if (!new)
384                 return -ENOMEM;
385
386         new->start      = start;
387         new->end        = end;
388         new->type       = actual_type;
389
390         spin_lock(&memtype_lock);
391
392         if (cached_entry && start >= cached_start)
393                 entry = cached_entry;
394         else
395                 entry = list_entry(&memtype_list, struct memtype, nd);
396
397         /* Search for existing mapping that overlaps the current range */
398         where = NULL;
399         list_for_each_entry_continue(entry, &memtype_list, nd) {
400                 if (end <= entry->start) {
401                         where = entry->nd.prev;
402                         cached_entry = list_entry(where, struct memtype, nd);
403                         break;
404                 } else if (start <= entry->start) { /* end > entry->start */
405                         err = chk_conflict(new, entry, new_type);
406                         if (!err) {
407                                 dprintk("Overlap at 0x%Lx-0x%Lx\n",
408                                         entry->start, entry->end);
409                                 where = entry->nd.prev;
410                                 cached_entry = list_entry(where,
411                                                         struct memtype, nd);
412                         }
413                         break;
414                 } else if (start < entry->end) { /* start > entry->start */
415                         err = chk_conflict(new, entry, new_type);
416                         if (!err) {
417                                 dprintk("Overlap at 0x%Lx-0x%Lx\n",
418                                         entry->start, entry->end);
419                                 cached_entry = list_entry(entry->nd.prev,
420                                                         struct memtype, nd);
421
422                                 /*
423                                  * Move to right position in the linked
424                                  * list to add this new entry
425                                  */
426                                 list_for_each_entry_continue(entry,
427                                                         &memtype_list, nd) {
428                                         if (start <= entry->start) {
429                                                 where = entry->nd.prev;
430                                                 break;
431                                         }
432                                 }
433                         }
434                         break;
435                 }
436         }
437
438         if (err) {
439                 printk(KERN_INFO "reserve_memtype failed 0x%Lx-0x%Lx, "
440                        "track %s, req %s\n",
441                        start, end, cattr_name(new->type), cattr_name(req_type));
442                 kfree(new);
443                 spin_unlock(&memtype_lock);
444
445                 return err;
446         }
447
448         cached_start = start;
449
450         if (where)
451                 list_add(&new->nd, where);
452         else
453                 list_add_tail(&new->nd, &memtype_list);
454
455         spin_unlock(&memtype_lock);
456
457         dprintk("reserve_memtype added 0x%Lx-0x%Lx, track %s, req %s, ret %s\n",
458                 start, end, cattr_name(new->type), cattr_name(req_type),
459                 new_type ? cattr_name(*new_type) : "-");
460
461         return err;
462 }
463
464 int free_memtype(u64 start, u64 end)
465 {
466         struct memtype *entry;
467         int err = -EINVAL;
468         int is_range_ram;
469
470         if (!pat_enabled)
471                 return 0;
472
473         /* Low ISA region is always mapped WB. No need to track */
474         if (is_ISA_range(start, end - 1))
475                 return 0;
476
477         is_range_ram = pat_pagerange_is_ram(start, end);
478         if (is_range_ram == 1)
479                 return free_ram_pages_type(start, end);
480         else if (is_range_ram < 0)
481                 return -EINVAL;
482
483         spin_lock(&memtype_lock);
484         list_for_each_entry(entry, &memtype_list, nd) {
485                 if (entry->start == start && entry->end == end) {
486                         if (cached_entry == entry || cached_start == start)
487                                 cached_entry = NULL;
488
489                         list_del(&entry->nd);
490                         kfree(entry);
491                         err = 0;
492                         break;
493                 }
494         }
495         spin_unlock(&memtype_lock);
496
497         if (err) {
498                 printk(KERN_INFO "%s:%d freeing invalid memtype %Lx-%Lx\n",
499                         current->comm, current->pid, start, end);
500         }
501
502         dprintk("free_memtype request 0x%Lx-0x%Lx\n", start, end);
503
504         return err;
505 }
506
507
508 pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
509                                 unsigned long size, pgprot_t vma_prot)
510 {
511         return vma_prot;
512 }
513
514 #ifdef CONFIG_STRICT_DEVMEM
515 /* This check is done in drivers/char/mem.c in case of STRICT_DEVMEM*/
516 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
517 {
518         return 1;
519 }
520 #else
521 /* This check is needed to avoid cache aliasing when PAT is enabled */
522 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
523 {
524         u64 from = ((u64)pfn) << PAGE_SHIFT;
525         u64 to = from + size;
526         u64 cursor = from;
527
528         if (!pat_enabled)
529                 return 1;
530
531         while (cursor < to) {
532                 if (!devmem_is_allowed(pfn)) {
533                         printk(KERN_INFO
534                 "Program %s tried to access /dev/mem between %Lx->%Lx.\n",
535                                 current->comm, from, to);
536                         return 0;
537                 }
538                 cursor += PAGE_SIZE;
539                 pfn++;
540         }
541         return 1;
542 }
543 #endif /* CONFIG_STRICT_DEVMEM */
544
545 int phys_mem_access_prot_allowed(struct file *file, unsigned long pfn,
546                                 unsigned long size, pgprot_t *vma_prot)
547 {
548         u64 offset = ((u64) pfn) << PAGE_SHIFT;
549         unsigned long flags = -1;
550         int retval;
551
552         if (!range_is_allowed(pfn, size))
553                 return 0;
554
555         if (file->f_flags & O_SYNC) {
556                 flags = _PAGE_CACHE_UC_MINUS;
557         }
558
559 #ifdef CONFIG_X86_32
560         /*
561          * On the PPro and successors, the MTRRs are used to set
562          * memory types for physical addresses outside main memory,
563          * so blindly setting UC or PWT on those pages is wrong.
564          * For Pentiums and earlier, the surround logic should disable
565          * caching for the high addresses through the KEN pin, but
566          * we maintain the tradition of paranoia in this code.
567          */
568         if (!pat_enabled &&
569             !(boot_cpu_has(X86_FEATURE_MTRR) ||
570               boot_cpu_has(X86_FEATURE_K6_MTRR) ||
571               boot_cpu_has(X86_FEATURE_CYRIX_ARR) ||
572               boot_cpu_has(X86_FEATURE_CENTAUR_MCR)) &&
573             (pfn << PAGE_SHIFT) >= __pa(high_memory)) {
574                 flags = _PAGE_CACHE_UC;
575         }
576 #endif
577
578         /*
579          * With O_SYNC, we can only take UC_MINUS mapping. Fail if we cannot.
580          *
581          * Without O_SYNC, we want to get
582          * - WB for WB-able memory and no other conflicting mappings
583          * - UC_MINUS for non-WB-able memory with no other conflicting mappings
584          * - Inherit from confliting mappings otherwise
585          */
586         if (flags != -1) {
587                 retval = reserve_memtype(offset, offset + size, flags, NULL);
588         } else {
589                 retval = reserve_memtype(offset, offset + size, -1, &flags);
590         }
591
592         if (retval < 0)
593                 return 0;
594
595         if (((pfn < max_low_pfn_mapped) ||
596              (pfn >= (1UL<<(32 - PAGE_SHIFT)) && pfn < max_pfn_mapped)) &&
597             ioremap_change_attr((unsigned long)__va(offset), size, flags) < 0) {
598                 free_memtype(offset, offset + size);
599                 printk(KERN_INFO
600                 "%s:%d /dev/mem ioremap_change_attr failed %s for %Lx-%Lx\n",
601                         current->comm, current->pid,
602                         cattr_name(flags),
603                         offset, (unsigned long long)(offset + size));
604                 return 0;
605         }
606
607         *vma_prot = __pgprot((pgprot_val(*vma_prot) & ~_PAGE_CACHE_MASK) |
608                              flags);
609         return 1;
610 }
611
612 void map_devmem(unsigned long pfn, unsigned long size, pgprot_t vma_prot)
613 {
614         unsigned long want_flags = (pgprot_val(vma_prot) & _PAGE_CACHE_MASK);
615         u64 addr = (u64)pfn << PAGE_SHIFT;
616         unsigned long flags;
617
618         reserve_memtype(addr, addr + size, want_flags, &flags);
619         if (flags != want_flags) {
620                 printk(KERN_INFO
621                 "%s:%d /dev/mem expected mapping type %s for %Lx-%Lx, got %s\n",
622                         current->comm, current->pid,
623                         cattr_name(want_flags),
624                         addr, (unsigned long long)(addr + size),
625                         cattr_name(flags));
626         }
627 }
628
629 void unmap_devmem(unsigned long pfn, unsigned long size, pgprot_t vma_prot)
630 {
631         u64 addr = (u64)pfn << PAGE_SHIFT;
632
633         free_memtype(addr, addr + size);
634 }
635
636 /*
637  * Internal interface to reserve a range of physical memory with prot.
638  * Reserved non RAM regions only and after successful reserve_memtype,
639  * this func also keeps identity mapping (if any) in sync with this new prot.
640  */
641 static int reserve_pfn_range(u64 paddr, unsigned long size, pgprot_t *vma_prot,
642                                 int strict_prot)
643 {
644         int is_ram = 0;
645         int id_sz, ret;
646         unsigned long flags;
647         unsigned long want_flags = (pgprot_val(*vma_prot) & _PAGE_CACHE_MASK);
648
649         is_ram = pat_pagerange_is_ram(paddr, paddr + size);
650
651         /*
652          * reserve_pfn_range() doesn't support RAM pages.
653          */
654         if (is_ram != 0)
655                 return -EINVAL;
656
657         ret = reserve_memtype(paddr, paddr + size, want_flags, &flags);
658         if (ret)
659                 return ret;
660
661         if (flags != want_flags) {
662                 if (strict_prot || !is_new_memtype_allowed(want_flags, flags)) {
663                         free_memtype(paddr, paddr + size);
664                         printk(KERN_ERR "%s:%d map pfn expected mapping type %s"
665                                 " for %Lx-%Lx, got %s\n",
666                                 current->comm, current->pid,
667                                 cattr_name(want_flags),
668                                 (unsigned long long)paddr,
669                                 (unsigned long long)(paddr + size),
670                                 cattr_name(flags));
671                         return -EINVAL;
672                 }
673                 /*
674                  * We allow returning different type than the one requested in
675                  * non strict case.
676                  */
677                 *vma_prot = __pgprot((pgprot_val(*vma_prot) &
678                                       (~_PAGE_CACHE_MASK)) |
679                                      flags);
680         }
681
682         /* Need to keep identity mapping in sync */
683         if (paddr >= __pa(high_memory))
684                 return 0;
685
686         id_sz = (__pa(high_memory) < paddr + size) ?
687                                 __pa(high_memory) - paddr :
688                                 size;
689
690         if (ioremap_change_attr((unsigned long)__va(paddr), id_sz, flags) < 0) {
691                 free_memtype(paddr, paddr + size);
692                 printk(KERN_ERR
693                         "%s:%d reserve_pfn_range ioremap_change_attr failed %s "
694                         "for %Lx-%Lx\n",
695                         current->comm, current->pid,
696                         cattr_name(flags),
697                         (unsigned long long)paddr,
698                         (unsigned long long)(paddr + size));
699                 return -EINVAL;
700         }
701         return 0;
702 }
703
704 /*
705  * Internal interface to free a range of physical memory.
706  * Frees non RAM regions only.
707  */
708 static void free_pfn_range(u64 paddr, unsigned long size)
709 {
710         int is_ram;
711
712         is_ram = pat_pagerange_is_ram(paddr, paddr + size);
713         if (is_ram == 0)
714                 free_memtype(paddr, paddr + size);
715 }
716
717 /*
718  * track_pfn_vma_copy is called when vma that is covering the pfnmap gets
719  * copied through copy_page_range().
720  *
721  * If the vma has a linear pfn mapping for the entire range, we get the prot
722  * from pte and reserve the entire vma range with single reserve_pfn_range call.
723  * Otherwise, we reserve the entire vma range, my ging through the PTEs page
724  * by page to get physical address and protection.
725  */
726 int track_pfn_vma_copy(struct vm_area_struct *vma)
727 {
728         int retval = 0;
729         unsigned long i, j;
730         resource_size_t paddr;
731         unsigned long prot;
732         unsigned long vma_start = vma->vm_start;
733         unsigned long vma_end = vma->vm_end;
734         unsigned long vma_size = vma_end - vma_start;
735         pgprot_t pgprot;
736
737         if (!pat_enabled)
738                 return 0;
739
740         if (is_linear_pfn_mapping(vma)) {
741                 /*
742                  * reserve the whole chunk covered by vma. We need the
743                  * starting address and protection from pte.
744                  */
745                 if (follow_phys(vma, vma_start, 0, &prot, &paddr)) {
746                         WARN_ON_ONCE(1);
747                         return -EINVAL;
748                 }
749                 pgprot = __pgprot(prot);
750                 return reserve_pfn_range(paddr, vma_size, &pgprot, 1);
751         }
752
753         /* reserve entire vma page by page, using pfn and prot from pte */
754         for (i = 0; i < vma_size; i += PAGE_SIZE) {
755                 if (follow_phys(vma, vma_start + i, 0, &prot, &paddr))
756                         continue;
757
758                 pgprot = __pgprot(prot);
759                 retval = reserve_pfn_range(paddr, PAGE_SIZE, &pgprot, 1);
760                 if (retval)
761                         goto cleanup_ret;
762         }
763         return 0;
764
765 cleanup_ret:
766         /* Reserve error: Cleanup partial reservation and return error */
767         for (j = 0; j < i; j += PAGE_SIZE) {
768                 if (follow_phys(vma, vma_start + j, 0, &prot, &paddr))
769                         continue;
770
771                 free_pfn_range(paddr, PAGE_SIZE);
772         }
773
774         return retval;
775 }
776
777 /*
778  * track_pfn_vma_new is called when a _new_ pfn mapping is being established
779  * for physical range indicated by pfn and size.
780  *
781  * prot is passed in as a parameter for the new mapping. If the vma has a
782  * linear pfn mapping for the entire range reserve the entire vma range with
783  * single reserve_pfn_range call.
784  * Otherwise, we look t the pfn and size and reserve only the specified range
785  * page by page.
786  *
787  * Note that this function can be called with caller trying to map only a
788  * subrange/page inside the vma.
789  */
790 int track_pfn_vma_new(struct vm_area_struct *vma, pgprot_t *prot,
791                         unsigned long pfn, unsigned long size)
792 {
793         int retval = 0;
794         unsigned long i, j;
795         resource_size_t base_paddr;
796         resource_size_t paddr;
797         unsigned long vma_start = vma->vm_start;
798         unsigned long vma_end = vma->vm_end;
799         unsigned long vma_size = vma_end - vma_start;
800
801         if (!pat_enabled)
802                 return 0;
803
804         if (is_linear_pfn_mapping(vma)) {
805                 /* reserve the whole chunk starting from vm_pgoff */
806                 paddr = (resource_size_t)vma->vm_pgoff << PAGE_SHIFT;
807                 return reserve_pfn_range(paddr, vma_size, prot, 0);
808         }
809
810         /* reserve page by page using pfn and size */
811         base_paddr = (resource_size_t)pfn << PAGE_SHIFT;
812         for (i = 0; i < size; i += PAGE_SIZE) {
813                 paddr = base_paddr + i;
814                 retval = reserve_pfn_range(paddr, PAGE_SIZE, prot, 0);
815                 if (retval)
816                         goto cleanup_ret;
817         }
818         return 0;
819
820 cleanup_ret:
821         /* Reserve error: Cleanup partial reservation and return error */
822         for (j = 0; j < i; j += PAGE_SIZE) {
823                 paddr = base_paddr + j;
824                 free_pfn_range(paddr, PAGE_SIZE);
825         }
826
827         return retval;
828 }
829
830 /*
831  * untrack_pfn_vma is called while unmapping a pfnmap for a region.
832  * untrack can be called for a specific region indicated by pfn and size or
833  * can be for the entire vma (in which case size can be zero).
834  */
835 void untrack_pfn_vma(struct vm_area_struct *vma, unsigned long pfn,
836                         unsigned long size)
837 {
838         unsigned long i;
839         resource_size_t paddr;
840         unsigned long prot;
841         unsigned long vma_start = vma->vm_start;
842         unsigned long vma_end = vma->vm_end;
843         unsigned long vma_size = vma_end - vma_start;
844
845         if (!pat_enabled)
846                 return;
847
848         if (is_linear_pfn_mapping(vma)) {
849                 /* free the whole chunk starting from vm_pgoff */
850                 paddr = (resource_size_t)vma->vm_pgoff << PAGE_SHIFT;
851                 free_pfn_range(paddr, vma_size);
852                 return;
853         }
854
855         if (size != 0 && size != vma_size) {
856                 /* free page by page, using pfn and size */
857                 paddr = (resource_size_t)pfn << PAGE_SHIFT;
858                 for (i = 0; i < size; i += PAGE_SIZE) {
859                         paddr = paddr + i;
860                         free_pfn_range(paddr, PAGE_SIZE);
861                 }
862         } else {
863                 /* free entire vma, page by page, using the pfn from pte */
864                 for (i = 0; i < vma_size; i += PAGE_SIZE) {
865                         if (follow_phys(vma, vma_start + i, 0, &prot, &paddr))
866                                 continue;
867
868                         free_pfn_range(paddr, PAGE_SIZE);
869                 }
870         }
871 }
872
873 pgprot_t pgprot_writecombine(pgprot_t prot)
874 {
875         if (pat_enabled)
876                 return __pgprot(pgprot_val(prot) | _PAGE_CACHE_WC);
877         else
878                 return pgprot_noncached(prot);
879 }
880
881 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_X86_PAT)
882
883 /* get Nth element of the linked list */
884 static struct memtype *memtype_get_idx(loff_t pos)
885 {
886         struct memtype *list_node, *print_entry;
887         int i = 1;
888
889         print_entry  = kmalloc(sizeof(struct memtype), GFP_KERNEL);
890         if (!print_entry)
891                 return NULL;
892
893         spin_lock(&memtype_lock);
894         list_for_each_entry(list_node, &memtype_list, nd) {
895                 if (pos == i) {
896                         *print_entry = *list_node;
897                         spin_unlock(&memtype_lock);
898                         return print_entry;
899                 }
900                 ++i;
901         }
902         spin_unlock(&memtype_lock);
903         kfree(print_entry);
904
905         return NULL;
906 }
907
908 static void *memtype_seq_start(struct seq_file *seq, loff_t *pos)
909 {
910         if (*pos == 0) {
911                 ++*pos;
912                 seq_printf(seq, "PAT memtype list:\n");
913         }
914
915         return memtype_get_idx(*pos);
916 }
917
918 static void *memtype_seq_next(struct seq_file *seq, void *v, loff_t *pos)
919 {
920         ++*pos;
921         return memtype_get_idx(*pos);
922 }
923
924 static void memtype_seq_stop(struct seq_file *seq, void *v)
925 {
926 }
927
928 static int memtype_seq_show(struct seq_file *seq, void *v)
929 {
930         struct memtype *print_entry = (struct memtype *)v;
931
932         seq_printf(seq, "%s @ 0x%Lx-0x%Lx\n", cattr_name(print_entry->type),
933                         print_entry->start, print_entry->end);
934         kfree(print_entry);
935
936         return 0;
937 }
938
939 static struct seq_operations memtype_seq_ops = {
940         .start = memtype_seq_start,
941         .next  = memtype_seq_next,
942         .stop  = memtype_seq_stop,
943         .show  = memtype_seq_show,
944 };
945
946 static int memtype_seq_open(struct inode *inode, struct file *file)
947 {
948         return seq_open(file, &memtype_seq_ops);
949 }
950
951 static const struct file_operations memtype_fops = {
952         .open    = memtype_seq_open,
953         .read    = seq_read,
954         .llseek  = seq_lseek,
955         .release = seq_release,
956 };
957
958 static int __init pat_memtype_list_init(void)
959 {
960         debugfs_create_file("pat_memtype_list", S_IRUSR, arch_debugfs_dir,
961                                 NULL, &memtype_fops);
962         return 0;
963 }
964
965 late_initcall(pat_memtype_list_init);
966
967 #endif /* CONFIG_DEBUG_FS && CONFIG_X86_PAT */