]> Git Repo - linux.git/blob - arch/x86/mm/pat/memtype.c
Linux 6.14-rc3
[linux.git] / arch / x86 / mm / pat / memtype.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Page Attribute Table (PAT) support: handle memory caching attributes in page tables.
4  *
5  * Authors: Venkatesh Pallipadi <[email protected]>
6  *          Suresh B Siddha <[email protected]>
7  *
8  * Loosely based on earlier PAT patchset from Eric Biederman and Andi Kleen.
9  *
10  * Basic principles:
11  *
12  * PAT is a CPU feature supported by all modern x86 CPUs, to allow the firmware and
13  * the kernel to set one of a handful of 'caching type' attributes for physical
14  * memory ranges: uncached, write-combining, write-through, write-protected,
15  * and the most commonly used and default attribute: write-back caching.
16  *
17  * PAT support supersedes and augments MTRR support in a compatible fashion: MTRR is
18  * a hardware interface to enumerate a limited number of physical memory ranges
19  * and set their caching attributes explicitly, programmed into the CPU via MSRs.
20  * Even modern CPUs have MTRRs enabled - but these are typically not touched
21  * by the kernel or by user-space (such as the X server), we rely on PAT for any
22  * additional cache attribute logic.
23  *
24  * PAT doesn't work via explicit memory ranges, but uses page table entries to add
25  * cache attribute information to the mapped memory range: there's 3 bits used,
26  * (_PAGE_PWT, _PAGE_PCD, _PAGE_PAT), with the 8 possible values mapped by the
27  * CPU to actual cache attributes via an MSR loaded into the CPU (MSR_IA32_CR_PAT).
28  *
29  * ( There's a metric ton of finer details, such as compatibility with CPU quirks
30  *   that only support 4 types of PAT entries, and interaction with MTRRs, see
31  *   below for details. )
32  */
33
34 #include <linux/seq_file.h>
35 #include <linux/memblock.h>
36 #include <linux/debugfs.h>
37 #include <linux/ioport.h>
38 #include <linux/kernel.h>
39 #include <linux/pfn_t.h>
40 #include <linux/slab.h>
41 #include <linux/mm.h>
42 #include <linux/highmem.h>
43 #include <linux/fs.h>
44 #include <linux/rbtree.h>
45
46 #include <asm/cacheflush.h>
47 #include <asm/cacheinfo.h>
48 #include <asm/processor.h>
49 #include <asm/tlbflush.h>
50 #include <asm/x86_init.h>
51 #include <asm/fcntl.h>
52 #include <asm/e820/api.h>
53 #include <asm/mtrr.h>
54 #include <asm/page.h>
55 #include <asm/msr.h>
56 #include <asm/memtype.h>
57 #include <asm/io.h>
58
59 #include "memtype.h"
60 #include "../mm_internal.h"
61
62 #undef pr_fmt
63 #define pr_fmt(fmt) "" fmt
64
65 static bool __read_mostly pat_disabled = !IS_ENABLED(CONFIG_X86_PAT);
66 static u64 __ro_after_init pat_msr_val;
67
68 /*
69  * PAT support is enabled by default, but can be disabled for
70  * various user-requested or hardware-forced reasons:
71  */
72 static void __init pat_disable(const char *msg_reason)
73 {
74         if (pat_disabled)
75                 return;
76
77         pat_disabled = true;
78         pr_info("x86/PAT: %s\n", msg_reason);
79
80         memory_caching_control &= ~CACHE_PAT;
81 }
82
83 static int __init nopat(char *str)
84 {
85         pat_disable("PAT support disabled via boot option.");
86         return 0;
87 }
88 early_param("nopat", nopat);
89
90 bool pat_enabled(void)
91 {
92         return !pat_disabled;
93 }
94 EXPORT_SYMBOL_GPL(pat_enabled);
95
96 int pat_debug_enable;
97
98 static int __init pat_debug_setup(char *str)
99 {
100         pat_debug_enable = 1;
101         return 1;
102 }
103 __setup("debugpat", pat_debug_setup);
104
105 #ifdef CONFIG_X86_PAT
106 /*
107  * X86 PAT uses page flags arch_1 and arch_2 together to keep track of
108  * memory type of pages that have backing page struct.
109  *
110  * X86 PAT supports 4 different memory types:
111  *  - _PAGE_CACHE_MODE_WB
112  *  - _PAGE_CACHE_MODE_WC
113  *  - _PAGE_CACHE_MODE_UC_MINUS
114  *  - _PAGE_CACHE_MODE_WT
115  *
116  * _PAGE_CACHE_MODE_WB is the default type.
117  */
118
119 #define _PGMT_WB                0
120 #define _PGMT_WC                (1UL << PG_arch_1)
121 #define _PGMT_UC_MINUS          (1UL << PG_arch_2)
122 #define _PGMT_WT                (1UL << PG_arch_2 | 1UL << PG_arch_1)
123 #define _PGMT_MASK              (1UL << PG_arch_2 | 1UL << PG_arch_1)
124 #define _PGMT_CLEAR_MASK        (~_PGMT_MASK)
125
126 static inline enum page_cache_mode get_page_memtype(struct page *pg)
127 {
128         unsigned long pg_flags = pg->flags & _PGMT_MASK;
129
130         if (pg_flags == _PGMT_WB)
131                 return _PAGE_CACHE_MODE_WB;
132         else if (pg_flags == _PGMT_WC)
133                 return _PAGE_CACHE_MODE_WC;
134         else if (pg_flags == _PGMT_UC_MINUS)
135                 return _PAGE_CACHE_MODE_UC_MINUS;
136         else
137                 return _PAGE_CACHE_MODE_WT;
138 }
139
140 static inline void set_page_memtype(struct page *pg,
141                                     enum page_cache_mode memtype)
142 {
143         unsigned long memtype_flags;
144         unsigned long old_flags;
145         unsigned long new_flags;
146
147         switch (memtype) {
148         case _PAGE_CACHE_MODE_WC:
149                 memtype_flags = _PGMT_WC;
150                 break;
151         case _PAGE_CACHE_MODE_UC_MINUS:
152                 memtype_flags = _PGMT_UC_MINUS;
153                 break;
154         case _PAGE_CACHE_MODE_WT:
155                 memtype_flags = _PGMT_WT;
156                 break;
157         case _PAGE_CACHE_MODE_WB:
158         default:
159                 memtype_flags = _PGMT_WB;
160                 break;
161         }
162
163         old_flags = READ_ONCE(pg->flags);
164         do {
165                 new_flags = (old_flags & _PGMT_CLEAR_MASK) | memtype_flags;
166         } while (!try_cmpxchg(&pg->flags, &old_flags, new_flags));
167 }
168 #else
169 static inline enum page_cache_mode get_page_memtype(struct page *pg)
170 {
171         return -1;
172 }
173 static inline void set_page_memtype(struct page *pg,
174                                     enum page_cache_mode memtype)
175 {
176 }
177 #endif
178
179 #define CM(c) (_PAGE_CACHE_MODE_ ## c)
180
181 static enum page_cache_mode __init pat_get_cache_mode(unsigned int pat_val,
182                                                       char *msg)
183 {
184         enum page_cache_mode cache;
185         char *cache_mode;
186
187         switch (pat_val) {
188         case X86_MEMTYPE_UC:       cache = CM(UC);       cache_mode = "UC  "; break;
189         case X86_MEMTYPE_WC:       cache = CM(WC);       cache_mode = "WC  "; break;
190         case X86_MEMTYPE_WT:       cache = CM(WT);       cache_mode = "WT  "; break;
191         case X86_MEMTYPE_WP:       cache = CM(WP);       cache_mode = "WP  "; break;
192         case X86_MEMTYPE_WB:       cache = CM(WB);       cache_mode = "WB  "; break;
193         case X86_MEMTYPE_UC_MINUS: cache = CM(UC_MINUS); cache_mode = "UC- "; break;
194         default:                   cache = CM(WB);       cache_mode = "WB  "; break;
195         }
196
197         memcpy(msg, cache_mode, 4);
198
199         return cache;
200 }
201
202 #undef CM
203
204 /*
205  * Update the cache mode to pgprot translation tables according to PAT
206  * configuration.
207  * Using lower indices is preferred, so we start with highest index.
208  */
209 static void __init init_cache_modes(u64 pat)
210 {
211         enum page_cache_mode cache;
212         char pat_msg[33];
213         int i;
214
215         pat_msg[32] = 0;
216         for (i = 7; i >= 0; i--) {
217                 cache = pat_get_cache_mode((pat >> (i * 8)) & 7,
218                                            pat_msg + 4 * i);
219                 update_cache_mode_entry(i, cache);
220         }
221         pr_info("x86/PAT: Configuration [0-7]: %s\n", pat_msg);
222 }
223
224 void pat_cpu_init(void)
225 {
226         if (!boot_cpu_has(X86_FEATURE_PAT)) {
227                 /*
228                  * If this happens we are on a secondary CPU, but switched to
229                  * PAT on the boot CPU. We have no way to undo PAT.
230                  */
231                 panic("x86/PAT: PAT enabled, but not supported by secondary CPU\n");
232         }
233
234         wrmsrl(MSR_IA32_CR_PAT, pat_msr_val);
235
236         __flush_tlb_all();
237 }
238
239 /**
240  * pat_bp_init - Initialize the PAT MSR value and PAT table
241  *
242  * This function initializes PAT MSR value and PAT table with an OS-defined
243  * value to enable additional cache attributes, WC, WT and WP.
244  *
245  * This function prepares the calls of pat_cpu_init() via cache_cpu_init()
246  * on all CPUs.
247  */
248 void __init pat_bp_init(void)
249 {
250         struct cpuinfo_x86 *c = &boot_cpu_data;
251
252         if (!IS_ENABLED(CONFIG_X86_PAT))
253                 pr_info_once("x86/PAT: PAT support disabled because CONFIG_X86_PAT is disabled in the kernel.\n");
254
255         if (!cpu_feature_enabled(X86_FEATURE_PAT))
256                 pat_disable("PAT not supported by the CPU.");
257         else
258                 rdmsrl(MSR_IA32_CR_PAT, pat_msr_val);
259
260         if (!pat_msr_val) {
261                 pat_disable("PAT support disabled by the firmware.");
262
263                 /*
264                  * No PAT. Emulate the PAT table that corresponds to the two
265                  * cache bits, PWT (Write Through) and PCD (Cache Disable).
266                  * This setup is also the same as the BIOS default setup.
267                  *
268                  * PTE encoding:
269                  *
270                  *       PCD
271                  *       |PWT  PAT
272                  *       ||    slot
273                  *       00    0    WB : _PAGE_CACHE_MODE_WB
274                  *       01    1    WT : _PAGE_CACHE_MODE_WT
275                  *       10    2    UC-: _PAGE_CACHE_MODE_UC_MINUS
276                  *       11    3    UC : _PAGE_CACHE_MODE_UC
277                  *
278                  * NOTE: When WC or WP is used, it is redirected to UC- per
279                  * the default setup in __cachemode2pte_tbl[].
280                  */
281                 pat_msr_val = PAT_VALUE(WB, WT, UC_MINUS, UC, WB, WT, UC_MINUS, UC);
282         }
283
284         /*
285          * Xen PV doesn't allow to set PAT MSR, but all cache modes are
286          * supported.
287          */
288         if (pat_disabled || cpu_feature_enabled(X86_FEATURE_XENPV)) {
289                 init_cache_modes(pat_msr_val);
290                 return;
291         }
292
293         if ((c->x86_vendor == X86_VENDOR_INTEL) &&
294             (((c->x86 == 0x6) && (c->x86_model <= 0xd)) ||
295              ((c->x86 == 0xf) && (c->x86_model <= 0x6)))) {
296                 /*
297                  * PAT support with the lower four entries. Intel Pentium 2,
298                  * 3, M, and 4 are affected by PAT errata, which makes the
299                  * upper four entries unusable. To be on the safe side, we don't
300                  * use those.
301                  *
302                  *  PTE encoding:
303                  *      PAT
304                  *      |PCD
305                  *      ||PWT  PAT
306                  *      |||    slot
307                  *      000    0    WB : _PAGE_CACHE_MODE_WB
308                  *      001    1    WC : _PAGE_CACHE_MODE_WC
309                  *      010    2    UC-: _PAGE_CACHE_MODE_UC_MINUS
310                  *      011    3    UC : _PAGE_CACHE_MODE_UC
311                  * PAT bit unused
312                  *
313                  * NOTE: When WT or WP is used, it is redirected to UC- per
314                  * the default setup in __cachemode2pte_tbl[].
315                  */
316                 pat_msr_val = PAT_VALUE(WB, WC, UC_MINUS, UC, WB, WC, UC_MINUS, UC);
317         } else {
318                 /*
319                  * Full PAT support.  We put WT in slot 7 to improve
320                  * robustness in the presence of errata that might cause
321                  * the high PAT bit to be ignored.  This way, a buggy slot 7
322                  * access will hit slot 3, and slot 3 is UC, so at worst
323                  * we lose performance without causing a correctness issue.
324                  * Pentium 4 erratum N46 is an example for such an erratum,
325                  * although we try not to use PAT at all on affected CPUs.
326                  *
327                  *  PTE encoding:
328                  *      PAT
329                  *      |PCD
330                  *      ||PWT  PAT
331                  *      |||    slot
332                  *      000    0    WB : _PAGE_CACHE_MODE_WB
333                  *      001    1    WC : _PAGE_CACHE_MODE_WC
334                  *      010    2    UC-: _PAGE_CACHE_MODE_UC_MINUS
335                  *      011    3    UC : _PAGE_CACHE_MODE_UC
336                  *      100    4    WB : Reserved
337                  *      101    5    WP : _PAGE_CACHE_MODE_WP
338                  *      110    6    UC-: Reserved
339                  *      111    7    WT : _PAGE_CACHE_MODE_WT
340                  *
341                  * The reserved slots are unused, but mapped to their
342                  * corresponding types in the presence of PAT errata.
343                  */
344                 pat_msr_val = PAT_VALUE(WB, WC, UC_MINUS, UC, WB, WP, UC_MINUS, WT);
345         }
346
347         memory_caching_control |= CACHE_PAT;
348
349         init_cache_modes(pat_msr_val);
350 }
351
352 static DEFINE_SPINLOCK(memtype_lock);   /* protects memtype accesses */
353
354 /*
355  * Does intersection of PAT memory type and MTRR memory type and returns
356  * the resulting memory type as PAT understands it.
357  * (Type in pat and mtrr will not have same value)
358  * The intersection is based on "Effective Memory Type" tables in IA-32
359  * SDM vol 3a
360  */
361 static unsigned long pat_x_mtrr_type(u64 start, u64 end,
362                                      enum page_cache_mode req_type)
363 {
364         /*
365          * Look for MTRR hint to get the effective type in case where PAT
366          * request is for WB.
367          */
368         if (req_type == _PAGE_CACHE_MODE_WB) {
369                 u8 mtrr_type, uniform;
370
371                 mtrr_type = mtrr_type_lookup(start, end, &uniform);
372                 if (mtrr_type != MTRR_TYPE_WRBACK)
373                         return _PAGE_CACHE_MODE_UC_MINUS;
374
375                 return _PAGE_CACHE_MODE_WB;
376         }
377
378         return req_type;
379 }
380
381 struct pagerange_state {
382         unsigned long           cur_pfn;
383         int                     ram;
384         int                     not_ram;
385 };
386
387 static int
388 pagerange_is_ram_callback(unsigned long initial_pfn, unsigned long total_nr_pages, void *arg)
389 {
390         struct pagerange_state *state = arg;
391
392         state->not_ram  |= initial_pfn > state->cur_pfn;
393         state->ram      |= total_nr_pages > 0;
394         state->cur_pfn   = initial_pfn + total_nr_pages;
395
396         return state->ram && state->not_ram;
397 }
398
399 static int pat_pagerange_is_ram(resource_size_t start, resource_size_t end)
400 {
401         int ret = 0;
402         unsigned long start_pfn = start >> PAGE_SHIFT;
403         unsigned long end_pfn = (end + PAGE_SIZE - 1) >> PAGE_SHIFT;
404         struct pagerange_state state = {start_pfn, 0, 0};
405
406         /*
407          * For legacy reasons, physical address range in the legacy ISA
408          * region is tracked as non-RAM. This will allow users of
409          * /dev/mem to map portions of legacy ISA region, even when
410          * some of those portions are listed(or not even listed) with
411          * different e820 types(RAM/reserved/..)
412          */
413         if (start_pfn < ISA_END_ADDRESS >> PAGE_SHIFT)
414                 start_pfn = ISA_END_ADDRESS >> PAGE_SHIFT;
415
416         if (start_pfn < end_pfn) {
417                 ret = walk_system_ram_range(start_pfn, end_pfn - start_pfn,
418                                 &state, pagerange_is_ram_callback);
419         }
420
421         return (ret > 0) ? -1 : (state.ram ? 1 : 0);
422 }
423
424 /*
425  * For RAM pages, we use page flags to mark the pages with appropriate type.
426  * The page flags are limited to four types, WB (default), WC, WT and UC-.
427  * WP request fails with -EINVAL, and UC gets redirected to UC-.  Setting
428  * a new memory type is only allowed for a page mapped with the default WB
429  * type.
430  *
431  * Here we do two passes:
432  * - Find the memtype of all the pages in the range, look for any conflicts.
433  * - In case of no conflicts, set the new memtype for pages in the range.
434  */
435 static int reserve_ram_pages_type(u64 start, u64 end,
436                                   enum page_cache_mode req_type,
437                                   enum page_cache_mode *new_type)
438 {
439         struct page *page;
440         u64 pfn;
441
442         if (req_type == _PAGE_CACHE_MODE_WP) {
443                 if (new_type)
444                         *new_type = _PAGE_CACHE_MODE_UC_MINUS;
445                 return -EINVAL;
446         }
447
448         if (req_type == _PAGE_CACHE_MODE_UC) {
449                 /* We do not support strong UC */
450                 WARN_ON_ONCE(1);
451                 req_type = _PAGE_CACHE_MODE_UC_MINUS;
452         }
453
454         for (pfn = (start >> PAGE_SHIFT); pfn < (end >> PAGE_SHIFT); ++pfn) {
455                 enum page_cache_mode type;
456
457                 page = pfn_to_page(pfn);
458                 type = get_page_memtype(page);
459                 if (type != _PAGE_CACHE_MODE_WB) {
460                         pr_info("x86/PAT: reserve_ram_pages_type failed [mem %#010Lx-%#010Lx], track 0x%x, req 0x%x\n",
461                                 start, end - 1, type, req_type);
462                         if (new_type)
463                                 *new_type = type;
464
465                         return -EBUSY;
466                 }
467         }
468
469         if (new_type)
470                 *new_type = req_type;
471
472         for (pfn = (start >> PAGE_SHIFT); pfn < (end >> PAGE_SHIFT); ++pfn) {
473                 page = pfn_to_page(pfn);
474                 set_page_memtype(page, req_type);
475         }
476         return 0;
477 }
478
479 static int free_ram_pages_type(u64 start, u64 end)
480 {
481         struct page *page;
482         u64 pfn;
483
484         for (pfn = (start >> PAGE_SHIFT); pfn < (end >> PAGE_SHIFT); ++pfn) {
485                 page = pfn_to_page(pfn);
486                 set_page_memtype(page, _PAGE_CACHE_MODE_WB);
487         }
488         return 0;
489 }
490
491 static u64 sanitize_phys(u64 address)
492 {
493         /*
494          * When changing the memtype for pages containing poison allow
495          * for a "decoy" virtual address (bit 63 clear) passed to
496          * set_memory_X(). __pa() on a "decoy" address results in a
497          * physical address with bit 63 set.
498          *
499          * Decoy addresses are not present for 32-bit builds, see
500          * set_mce_nospec().
501          */
502         if (IS_ENABLED(CONFIG_X86_64))
503                 return address & __PHYSICAL_MASK;
504         return address;
505 }
506
507 /*
508  * req_type typically has one of the:
509  * - _PAGE_CACHE_MODE_WB
510  * - _PAGE_CACHE_MODE_WC
511  * - _PAGE_CACHE_MODE_UC_MINUS
512  * - _PAGE_CACHE_MODE_UC
513  * - _PAGE_CACHE_MODE_WT
514  *
515  * If new_type is NULL, function will return an error if it cannot reserve the
516  * region with req_type. If new_type is non-NULL, function will return
517  * available type in new_type in case of no error. In case of any error
518  * it will return a negative return value.
519  */
520 int memtype_reserve(u64 start, u64 end, enum page_cache_mode req_type,
521                     enum page_cache_mode *new_type)
522 {
523         struct memtype *entry_new;
524         enum page_cache_mode actual_type;
525         int is_range_ram;
526         int err = 0;
527
528         start = sanitize_phys(start);
529
530         /*
531          * The end address passed into this function is exclusive, but
532          * sanitize_phys() expects an inclusive address.
533          */
534         end = sanitize_phys(end - 1) + 1;
535         if (start >= end) {
536                 WARN(1, "%s failed: [mem %#010Lx-%#010Lx], req %s\n", __func__,
537                                 start, end - 1, cattr_name(req_type));
538                 return -EINVAL;
539         }
540
541         if (!pat_enabled()) {
542                 /* This is identical to page table setting without PAT */
543                 if (new_type)
544                         *new_type = req_type;
545                 return 0;
546         }
547
548         /* Low ISA region is always mapped WB in page table. No need to track */
549         if (x86_platform.is_untracked_pat_range(start, end)) {
550                 if (new_type)
551                         *new_type = _PAGE_CACHE_MODE_WB;
552                 return 0;
553         }
554
555         /*
556          * Call mtrr_lookup to get the type hint. This is an
557          * optimization for /dev/mem mmap'ers into WB memory (BIOS
558          * tools and ACPI tools). Use WB request for WB memory and use
559          * UC_MINUS otherwise.
560          */
561         actual_type = pat_x_mtrr_type(start, end, req_type);
562
563         if (new_type)
564                 *new_type = actual_type;
565
566         is_range_ram = pat_pagerange_is_ram(start, end);
567         if (is_range_ram == 1) {
568
569                 err = reserve_ram_pages_type(start, end, req_type, new_type);
570
571                 return err;
572         } else if (is_range_ram < 0) {
573                 return -EINVAL;
574         }
575
576         entry_new = kzalloc(sizeof(struct memtype), GFP_KERNEL);
577         if (!entry_new)
578                 return -ENOMEM;
579
580         entry_new->start = start;
581         entry_new->end   = end;
582         entry_new->type  = actual_type;
583
584         spin_lock(&memtype_lock);
585
586         err = memtype_check_insert(entry_new, new_type);
587         if (err) {
588                 pr_info("x86/PAT: memtype_reserve failed [mem %#010Lx-%#010Lx], track %s, req %s\n",
589                         start, end - 1,
590                         cattr_name(entry_new->type), cattr_name(req_type));
591                 kfree(entry_new);
592                 spin_unlock(&memtype_lock);
593
594                 return err;
595         }
596
597         spin_unlock(&memtype_lock);
598
599         dprintk("memtype_reserve added [mem %#010Lx-%#010Lx], track %s, req %s, ret %s\n",
600                 start, end - 1, cattr_name(entry_new->type), cattr_name(req_type),
601                 new_type ? cattr_name(*new_type) : "-");
602
603         return err;
604 }
605
606 int memtype_free(u64 start, u64 end)
607 {
608         int is_range_ram;
609         struct memtype *entry_old;
610
611         if (!pat_enabled())
612                 return 0;
613
614         start = sanitize_phys(start);
615         end = sanitize_phys(end);
616
617         /* Low ISA region is always mapped WB. No need to track */
618         if (x86_platform.is_untracked_pat_range(start, end))
619                 return 0;
620
621         is_range_ram = pat_pagerange_is_ram(start, end);
622         if (is_range_ram == 1)
623                 return free_ram_pages_type(start, end);
624         if (is_range_ram < 0)
625                 return -EINVAL;
626
627         spin_lock(&memtype_lock);
628         entry_old = memtype_erase(start, end);
629         spin_unlock(&memtype_lock);
630
631         if (IS_ERR(entry_old)) {
632                 pr_info("x86/PAT: %s:%d freeing invalid memtype [mem %#010Lx-%#010Lx]\n",
633                         current->comm, current->pid, start, end - 1);
634                 return -EINVAL;
635         }
636
637         kfree(entry_old);
638
639         dprintk("memtype_free request [mem %#010Lx-%#010Lx]\n", start, end - 1);
640
641         return 0;
642 }
643
644
645 /**
646  * lookup_memtype - Looks up the memory type for a physical address
647  * @paddr: physical address of which memory type needs to be looked up
648  *
649  * Only to be called when PAT is enabled
650  *
651  * Returns _PAGE_CACHE_MODE_WB, _PAGE_CACHE_MODE_WC, _PAGE_CACHE_MODE_UC_MINUS
652  * or _PAGE_CACHE_MODE_WT.
653  */
654 static enum page_cache_mode lookup_memtype(u64 paddr)
655 {
656         enum page_cache_mode rettype = _PAGE_CACHE_MODE_WB;
657         struct memtype *entry;
658
659         if (x86_platform.is_untracked_pat_range(paddr, paddr + PAGE_SIZE))
660                 return rettype;
661
662         if (pat_pagerange_is_ram(paddr, paddr + PAGE_SIZE)) {
663                 struct page *page;
664
665                 page = pfn_to_page(paddr >> PAGE_SHIFT);
666                 return get_page_memtype(page);
667         }
668
669         spin_lock(&memtype_lock);
670
671         entry = memtype_lookup(paddr);
672         if (entry != NULL)
673                 rettype = entry->type;
674         else
675                 rettype = _PAGE_CACHE_MODE_UC_MINUS;
676
677         spin_unlock(&memtype_lock);
678
679         return rettype;
680 }
681
682 /**
683  * pat_pfn_immune_to_uc_mtrr - Check whether the PAT memory type
684  * of @pfn cannot be overridden by UC MTRR memory type.
685  *
686  * Only to be called when PAT is enabled.
687  *
688  * Returns true, if the PAT memory type of @pfn is UC, UC-, or WC.
689  * Returns false in other cases.
690  */
691 bool pat_pfn_immune_to_uc_mtrr(unsigned long pfn)
692 {
693         enum page_cache_mode cm = lookup_memtype(PFN_PHYS(pfn));
694
695         return cm == _PAGE_CACHE_MODE_UC ||
696                cm == _PAGE_CACHE_MODE_UC_MINUS ||
697                cm == _PAGE_CACHE_MODE_WC;
698 }
699 EXPORT_SYMBOL_GPL(pat_pfn_immune_to_uc_mtrr);
700
701 /**
702  * memtype_reserve_io - Request a memory type mapping for a region of memory
703  * @start: start (physical address) of the region
704  * @end: end (physical address) of the region
705  * @type: A pointer to memtype, with requested type. On success, requested
706  * or any other compatible type that was available for the region is returned
707  *
708  * On success, returns 0
709  * On failure, returns non-zero
710  */
711 int memtype_reserve_io(resource_size_t start, resource_size_t end,
712                         enum page_cache_mode *type)
713 {
714         resource_size_t size = end - start;
715         enum page_cache_mode req_type = *type;
716         enum page_cache_mode new_type;
717         int ret;
718
719         WARN_ON_ONCE(iomem_map_sanity_check(start, size));
720
721         ret = memtype_reserve(start, end, req_type, &new_type);
722         if (ret)
723                 goto out_err;
724
725         if (!is_new_memtype_allowed(start, size, req_type, new_type))
726                 goto out_free;
727
728         if (memtype_kernel_map_sync(start, size, new_type) < 0)
729                 goto out_free;
730
731         *type = new_type;
732         return 0;
733
734 out_free:
735         memtype_free(start, end);
736         ret = -EBUSY;
737 out_err:
738         return ret;
739 }
740
741 /**
742  * memtype_free_io - Release a memory type mapping for a region of memory
743  * @start: start (physical address) of the region
744  * @end: end (physical address) of the region
745  */
746 void memtype_free_io(resource_size_t start, resource_size_t end)
747 {
748         memtype_free(start, end);
749 }
750
751 #ifdef CONFIG_X86_PAT
752 int arch_io_reserve_memtype_wc(resource_size_t start, resource_size_t size)
753 {
754         enum page_cache_mode type = _PAGE_CACHE_MODE_WC;
755
756         return memtype_reserve_io(start, start + size, &type);
757 }
758 EXPORT_SYMBOL(arch_io_reserve_memtype_wc);
759
760 void arch_io_free_memtype_wc(resource_size_t start, resource_size_t size)
761 {
762         memtype_free_io(start, start + size);
763 }
764 EXPORT_SYMBOL(arch_io_free_memtype_wc);
765 #endif
766
767 pgprot_t phys_mem_access_prot(struct file *file, unsigned long pfn,
768                                 unsigned long size, pgprot_t vma_prot)
769 {
770         if (!phys_mem_access_encrypted(pfn << PAGE_SHIFT, size))
771                 vma_prot = pgprot_decrypted(vma_prot);
772
773         return vma_prot;
774 }
775
776 #ifdef CONFIG_STRICT_DEVMEM
777 /* This check is done in drivers/char/mem.c in case of STRICT_DEVMEM */
778 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
779 {
780         return 1;
781 }
782 #else
783 /* This check is needed to avoid cache aliasing when PAT is enabled */
784 static inline int range_is_allowed(unsigned long pfn, unsigned long size)
785 {
786         u64 from = ((u64)pfn) << PAGE_SHIFT;
787         u64 to = from + size;
788         u64 cursor = from;
789
790         if (!pat_enabled())
791                 return 1;
792
793         while (cursor < to) {
794                 if (!devmem_is_allowed(pfn))
795                         return 0;
796                 cursor += PAGE_SIZE;
797                 pfn++;
798         }
799         return 1;
800 }
801 #endif /* CONFIG_STRICT_DEVMEM */
802
803 int phys_mem_access_prot_allowed(struct file *file, unsigned long pfn,
804                                 unsigned long size, pgprot_t *vma_prot)
805 {
806         enum page_cache_mode pcm = _PAGE_CACHE_MODE_WB;
807
808         if (!range_is_allowed(pfn, size))
809                 return 0;
810
811         if (file->f_flags & O_DSYNC)
812                 pcm = _PAGE_CACHE_MODE_UC_MINUS;
813
814         *vma_prot = __pgprot((pgprot_val(*vma_prot) & ~_PAGE_CACHE_MASK) |
815                              cachemode2protval(pcm));
816         return 1;
817 }
818
819 /*
820  * Change the memory type for the physical address range in kernel identity
821  * mapping space if that range is a part of identity map.
822  */
823 int memtype_kernel_map_sync(u64 base, unsigned long size,
824                             enum page_cache_mode pcm)
825 {
826         unsigned long id_sz;
827
828         if (base > __pa(high_memory-1))
829                 return 0;
830
831         /*
832          * Some areas in the middle of the kernel identity range
833          * are not mapped, for example the PCI space.
834          */
835         if (!page_is_ram(base >> PAGE_SHIFT))
836                 return 0;
837
838         id_sz = (__pa(high_memory-1) <= base + size) ?
839                                 __pa(high_memory) - base : size;
840
841         if (ioremap_change_attr((unsigned long)__va(base), id_sz, pcm) < 0) {
842                 pr_info("x86/PAT: %s:%d ioremap_change_attr failed %s for [mem %#010Lx-%#010Lx]\n",
843                         current->comm, current->pid,
844                         cattr_name(pcm),
845                         base, (unsigned long long)(base + size-1));
846                 return -EINVAL;
847         }
848         return 0;
849 }
850
851 /*
852  * Internal interface to reserve a range of physical memory with prot.
853  * Reserved non RAM regions only and after successful memtype_reserve,
854  * this func also keeps identity mapping (if any) in sync with this new prot.
855  */
856 static int reserve_pfn_range(u64 paddr, unsigned long size, pgprot_t *vma_prot,
857                                 int strict_prot)
858 {
859         int is_ram = 0;
860         int ret;
861         enum page_cache_mode want_pcm = pgprot2cachemode(*vma_prot);
862         enum page_cache_mode pcm = want_pcm;
863
864         is_ram = pat_pagerange_is_ram(paddr, paddr + size);
865
866         /*
867          * reserve_pfn_range() for RAM pages. We do not refcount to keep
868          * track of number of mappings of RAM pages. We can assert that
869          * the type requested matches the type of first page in the range.
870          */
871         if (is_ram) {
872                 if (!pat_enabled())
873                         return 0;
874
875                 pcm = lookup_memtype(paddr);
876                 if (want_pcm != pcm) {
877                         pr_warn("x86/PAT: %s:%d map pfn RAM range req %s for [mem %#010Lx-%#010Lx], got %s\n",
878                                 current->comm, current->pid,
879                                 cattr_name(want_pcm),
880                                 (unsigned long long)paddr,
881                                 (unsigned long long)(paddr + size - 1),
882                                 cattr_name(pcm));
883                         *vma_prot = __pgprot((pgprot_val(*vma_prot) &
884                                              (~_PAGE_CACHE_MASK)) |
885                                              cachemode2protval(pcm));
886                 }
887                 return 0;
888         }
889
890         ret = memtype_reserve(paddr, paddr + size, want_pcm, &pcm);
891         if (ret)
892                 return ret;
893
894         if (pcm != want_pcm) {
895                 if (strict_prot ||
896                     !is_new_memtype_allowed(paddr, size, want_pcm, pcm)) {
897                         memtype_free(paddr, paddr + size);
898                         pr_err("x86/PAT: %s:%d map pfn expected mapping type %s for [mem %#010Lx-%#010Lx], got %s\n",
899                                current->comm, current->pid,
900                                cattr_name(want_pcm),
901                                (unsigned long long)paddr,
902                                (unsigned long long)(paddr + size - 1),
903                                cattr_name(pcm));
904                         return -EINVAL;
905                 }
906                 /*
907                  * We allow returning different type than the one requested in
908                  * non strict case.
909                  */
910                 *vma_prot = __pgprot((pgprot_val(*vma_prot) &
911                                       (~_PAGE_CACHE_MASK)) |
912                                      cachemode2protval(pcm));
913         }
914
915         if (memtype_kernel_map_sync(paddr, size, pcm) < 0) {
916                 memtype_free(paddr, paddr + size);
917                 return -EINVAL;
918         }
919         return 0;
920 }
921
922 /*
923  * Internal interface to free a range of physical memory.
924  * Frees non RAM regions only.
925  */
926 static void free_pfn_range(u64 paddr, unsigned long size)
927 {
928         int is_ram;
929
930         is_ram = pat_pagerange_is_ram(paddr, paddr + size);
931         if (is_ram == 0)
932                 memtype_free(paddr, paddr + size);
933 }
934
935 static int follow_phys(struct vm_area_struct *vma, unsigned long *prot,
936                 resource_size_t *phys)
937 {
938         struct follow_pfnmap_args args = { .vma = vma, .address = vma->vm_start };
939
940         if (follow_pfnmap_start(&args))
941                 return -EINVAL;
942
943         /* Never return PFNs of anon folios in COW mappings. */
944         if (!args.special) {
945                 follow_pfnmap_end(&args);
946                 return -EINVAL;
947         }
948
949         *prot = pgprot_val(args.pgprot);
950         *phys = (resource_size_t)args.pfn << PAGE_SHIFT;
951         follow_pfnmap_end(&args);
952         return 0;
953 }
954
955 static int get_pat_info(struct vm_area_struct *vma, resource_size_t *paddr,
956                 pgprot_t *pgprot)
957 {
958         unsigned long prot;
959
960         VM_WARN_ON_ONCE(!(vma->vm_flags & VM_PAT));
961
962         /*
963          * We need the starting PFN and cachemode used for track_pfn_remap()
964          * that covered the whole VMA. For most mappings, we can obtain that
965          * information from the page tables. For COW mappings, we might now
966          * suddenly have anon folios mapped and follow_phys() will fail.
967          *
968          * Fallback to using vma->vm_pgoff, see remap_pfn_range_notrack(), to
969          * detect the PFN. If we need the cachemode as well, we're out of luck
970          * for now and have to fail fork().
971          */
972         if (!follow_phys(vma, &prot, paddr)) {
973                 if (pgprot)
974                         *pgprot = __pgprot(prot);
975                 return 0;
976         }
977         if (is_cow_mapping(vma->vm_flags)) {
978                 if (pgprot)
979                         return -EINVAL;
980                 *paddr = (resource_size_t)vma->vm_pgoff << PAGE_SHIFT;
981                 return 0;
982         }
983         WARN_ON_ONCE(1);
984         return -EINVAL;
985 }
986
987 /*
988  * track_pfn_copy is called when vma that is covering the pfnmap gets
989  * copied through copy_page_range().
990  *
991  * If the vma has a linear pfn mapping for the entire range, we get the prot
992  * from pte and reserve the entire vma range with single reserve_pfn_range call.
993  */
994 int track_pfn_copy(struct vm_area_struct *vma)
995 {
996         resource_size_t paddr;
997         unsigned long vma_size = vma->vm_end - vma->vm_start;
998         pgprot_t pgprot;
999
1000         if (vma->vm_flags & VM_PAT) {
1001                 if (get_pat_info(vma, &paddr, &pgprot))
1002                         return -EINVAL;
1003                 /* reserve the whole chunk covered by vma. */
1004                 return reserve_pfn_range(paddr, vma_size, &pgprot, 1);
1005         }
1006
1007         return 0;
1008 }
1009
1010 /*
1011  * prot is passed in as a parameter for the new mapping. If the vma has
1012  * a linear pfn mapping for the entire range, or no vma is provided,
1013  * reserve the entire pfn + size range with single reserve_pfn_range
1014  * call.
1015  */
1016 int track_pfn_remap(struct vm_area_struct *vma, pgprot_t *prot,
1017                     unsigned long pfn, unsigned long addr, unsigned long size)
1018 {
1019         resource_size_t paddr = (resource_size_t)pfn << PAGE_SHIFT;
1020         enum page_cache_mode pcm;
1021
1022         /* reserve the whole chunk starting from paddr */
1023         if (!vma || (addr == vma->vm_start
1024                                 && size == (vma->vm_end - vma->vm_start))) {
1025                 int ret;
1026
1027                 ret = reserve_pfn_range(paddr, size, prot, 0);
1028                 if (ret == 0 && vma)
1029                         vm_flags_set(vma, VM_PAT);
1030                 return ret;
1031         }
1032
1033         if (!pat_enabled())
1034                 return 0;
1035
1036         /*
1037          * For anything smaller than the vma size we set prot based on the
1038          * lookup.
1039          */
1040         pcm = lookup_memtype(paddr);
1041
1042         /* Check memtype for the remaining pages */
1043         while (size > PAGE_SIZE) {
1044                 size -= PAGE_SIZE;
1045                 paddr += PAGE_SIZE;
1046                 if (pcm != lookup_memtype(paddr))
1047                         return -EINVAL;
1048         }
1049
1050         *prot = __pgprot((pgprot_val(*prot) & (~_PAGE_CACHE_MASK)) |
1051                          cachemode2protval(pcm));
1052
1053         return 0;
1054 }
1055
1056 void track_pfn_insert(struct vm_area_struct *vma, pgprot_t *prot, pfn_t pfn)
1057 {
1058         enum page_cache_mode pcm;
1059
1060         if (!pat_enabled())
1061                 return;
1062
1063         /* Set prot based on lookup */
1064         pcm = lookup_memtype(pfn_t_to_phys(pfn));
1065         *prot = __pgprot((pgprot_val(*prot) & (~_PAGE_CACHE_MASK)) |
1066                          cachemode2protval(pcm));
1067 }
1068
1069 /*
1070  * untrack_pfn is called while unmapping a pfnmap for a region.
1071  * untrack can be called for a specific region indicated by pfn and size or
1072  * can be for the entire vma (in which case pfn, size are zero).
1073  */
1074 void untrack_pfn(struct vm_area_struct *vma, unsigned long pfn,
1075                  unsigned long size, bool mm_wr_locked)
1076 {
1077         resource_size_t paddr;
1078
1079         if (vma && !(vma->vm_flags & VM_PAT))
1080                 return;
1081
1082         /* free the chunk starting from pfn or the whole chunk */
1083         paddr = (resource_size_t)pfn << PAGE_SHIFT;
1084         if (!paddr && !size) {
1085                 if (get_pat_info(vma, &paddr, NULL))
1086                         return;
1087                 size = vma->vm_end - vma->vm_start;
1088         }
1089         free_pfn_range(paddr, size);
1090         if (vma) {
1091                 if (mm_wr_locked)
1092                         vm_flags_clear(vma, VM_PAT);
1093                 else
1094                         __vm_flags_mod(vma, 0, VM_PAT);
1095         }
1096 }
1097
1098 /*
1099  * untrack_pfn_clear is called if the following situation fits:
1100  *
1101  * 1) while mremapping a pfnmap for a new region,  with the old vma after
1102  * its pfnmap page table has been removed.  The new vma has a new pfnmap
1103  * to the same pfn & cache type with VM_PAT set.
1104  * 2) while duplicating vm area, the new vma fails to copy the pgtable from
1105  * old vma.
1106  */
1107 void untrack_pfn_clear(struct vm_area_struct *vma)
1108 {
1109         vm_flags_clear(vma, VM_PAT);
1110 }
1111
1112 pgprot_t pgprot_writecombine(pgprot_t prot)
1113 {
1114         return __pgprot(pgprot_val(prot) |
1115                                 cachemode2protval(_PAGE_CACHE_MODE_WC));
1116 }
1117 EXPORT_SYMBOL_GPL(pgprot_writecombine);
1118
1119 pgprot_t pgprot_writethrough(pgprot_t prot)
1120 {
1121         return __pgprot(pgprot_val(prot) |
1122                                 cachemode2protval(_PAGE_CACHE_MODE_WT));
1123 }
1124 EXPORT_SYMBOL_GPL(pgprot_writethrough);
1125
1126 #if defined(CONFIG_DEBUG_FS) && defined(CONFIG_X86_PAT)
1127
1128 /*
1129  * We are allocating a temporary printout-entry to be passed
1130  * between seq_start()/next() and seq_show():
1131  */
1132 static struct memtype *memtype_get_idx(loff_t pos)
1133 {
1134         struct memtype *entry_print;
1135         int ret;
1136
1137         entry_print  = kzalloc(sizeof(struct memtype), GFP_KERNEL);
1138         if (!entry_print)
1139                 return NULL;
1140
1141         spin_lock(&memtype_lock);
1142         ret = memtype_copy_nth_element(entry_print, pos);
1143         spin_unlock(&memtype_lock);
1144
1145         /* Free it on error: */
1146         if (ret) {
1147                 kfree(entry_print);
1148                 return NULL;
1149         }
1150
1151         return entry_print;
1152 }
1153
1154 static void *memtype_seq_start(struct seq_file *seq, loff_t *pos)
1155 {
1156         if (*pos == 0) {
1157                 ++*pos;
1158                 seq_puts(seq, "PAT memtype list:\n");
1159         }
1160
1161         return memtype_get_idx(*pos);
1162 }
1163
1164 static void *memtype_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1165 {
1166         kfree(v);
1167         ++*pos;
1168         return memtype_get_idx(*pos);
1169 }
1170
1171 static void memtype_seq_stop(struct seq_file *seq, void *v)
1172 {
1173         kfree(v);
1174 }
1175
1176 static int memtype_seq_show(struct seq_file *seq, void *v)
1177 {
1178         struct memtype *entry_print = (struct memtype *)v;
1179
1180         seq_printf(seq, "PAT: [mem 0x%016Lx-0x%016Lx] %s\n",
1181                         entry_print->start,
1182                         entry_print->end,
1183                         cattr_name(entry_print->type));
1184
1185         return 0;
1186 }
1187
1188 static const struct seq_operations memtype_seq_ops = {
1189         .start = memtype_seq_start,
1190         .next  = memtype_seq_next,
1191         .stop  = memtype_seq_stop,
1192         .show  = memtype_seq_show,
1193 };
1194
1195 static int memtype_seq_open(struct inode *inode, struct file *file)
1196 {
1197         return seq_open(file, &memtype_seq_ops);
1198 }
1199
1200 static const struct file_operations memtype_fops = {
1201         .open    = memtype_seq_open,
1202         .read    = seq_read,
1203         .llseek  = seq_lseek,
1204         .release = seq_release,
1205 };
1206
1207 static int __init pat_memtype_list_init(void)
1208 {
1209         if (pat_enabled()) {
1210                 debugfs_create_file("pat_memtype_list", S_IRUSR,
1211                                     arch_debugfs_dir, NULL, &memtype_fops);
1212         }
1213         return 0;
1214 }
1215 late_initcall(pat_memtype_list_init);
1216
1217 #endif /* CONFIG_DEBUG_FS && CONFIG_X86_PAT */
This page took 0.102052 seconds and 4 git commands to generate.