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