x86/mm/pti: Add Warning when booting on a PCID capable CPU
[linux-2.6-microblaze.git] / arch / x86 / mm / pti.c
1 /*
2  * Copyright(c) 2017 Intel Corporation. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of version 2 of the GNU General Public License as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * This code is based in part on work published here:
14  *
15  *      https://github.com/IAIK/KAISER
16  *
17  * The original work was written by and and signed off by for the Linux
18  * kernel by:
19  *
20  *   Signed-off-by: Richard Fellner <richard.fellner@student.tugraz.at>
21  *   Signed-off-by: Moritz Lipp <moritz.lipp@iaik.tugraz.at>
22  *   Signed-off-by: Daniel Gruss <daniel.gruss@iaik.tugraz.at>
23  *   Signed-off-by: Michael Schwarz <michael.schwarz@iaik.tugraz.at>
24  *
25  * Major changes to the original code by: Dave Hansen <dave.hansen@intel.com>
26  * Mostly rewritten by Thomas Gleixner <tglx@linutronix.de> and
27  *                     Andy Lutomirsky <luto@amacapital.net>
28  */
29 #include <linux/kernel.h>
30 #include <linux/errno.h>
31 #include <linux/string.h>
32 #include <linux/types.h>
33 #include <linux/bug.h>
34 #include <linux/init.h>
35 #include <linux/spinlock.h>
36 #include <linux/mm.h>
37 #include <linux/uaccess.h>
38
39 #include <asm/cpufeature.h>
40 #include <asm/hypervisor.h>
41 #include <asm/vsyscall.h>
42 #include <asm/cmdline.h>
43 #include <asm/pti.h>
44 #include <asm/pgtable.h>
45 #include <asm/pgalloc.h>
46 #include <asm/tlbflush.h>
47 #include <asm/desc.h>
48
49 #undef pr_fmt
50 #define pr_fmt(fmt)     "Kernel/User page tables isolation: " fmt
51
52 /* Backporting helper */
53 #ifndef __GFP_NOTRACK
54 #define __GFP_NOTRACK   0
55 #endif
56
57 static void __init pti_print_if_insecure(const char *reason)
58 {
59         if (boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
60                 pr_info("%s\n", reason);
61 }
62
63 static void __init pti_print_if_secure(const char *reason)
64 {
65         if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
66                 pr_info("%s\n", reason);
67 }
68
69 enum pti_mode {
70         PTI_AUTO = 0,
71         PTI_FORCE_OFF,
72         PTI_FORCE_ON
73 } pti_mode;
74
75 void __init pti_check_boottime_disable(void)
76 {
77         char arg[5];
78         int ret;
79
80         /* Assume mode is auto unless overridden. */
81         pti_mode = PTI_AUTO;
82
83         if (hypervisor_is_type(X86_HYPER_XEN_PV)) {
84                 pti_mode = PTI_FORCE_OFF;
85                 pti_print_if_insecure("disabled on XEN PV.");
86                 return;
87         }
88
89         ret = cmdline_find_option(boot_command_line, "pti", arg, sizeof(arg));
90         if (ret > 0)  {
91                 if (ret == 3 && !strncmp(arg, "off", 3)) {
92                         pti_mode = PTI_FORCE_OFF;
93                         pti_print_if_insecure("disabled on command line.");
94                         return;
95                 }
96                 if (ret == 2 && !strncmp(arg, "on", 2)) {
97                         pti_mode = PTI_FORCE_ON;
98                         pti_print_if_secure("force enabled on command line.");
99                         goto enable;
100                 }
101                 if (ret == 4 && !strncmp(arg, "auto", 4)) {
102                         pti_mode = PTI_AUTO;
103                         goto autosel;
104                 }
105         }
106
107         if (cmdline_find_option_bool(boot_command_line, "nopti")) {
108                 pti_mode = PTI_FORCE_OFF;
109                 pti_print_if_insecure("disabled on command line.");
110                 return;
111         }
112
113 autosel:
114         if (!boot_cpu_has_bug(X86_BUG_CPU_MELTDOWN))
115                 return;
116 enable:
117         setup_force_cpu_cap(X86_FEATURE_PTI);
118 }
119
120 pgd_t __pti_set_user_pgtbl(pgd_t *pgdp, pgd_t pgd)
121 {
122         /*
123          * Changes to the high (kernel) portion of the kernelmode page
124          * tables are not automatically propagated to the usermode tables.
125          *
126          * Users should keep in mind that, unlike the kernelmode tables,
127          * there is no vmalloc_fault equivalent for the usermode tables.
128          * Top-level entries added to init_mm's usermode pgd after boot
129          * will not be automatically propagated to other mms.
130          */
131         if (!pgdp_maps_userspace(pgdp))
132                 return pgd;
133
134         /*
135          * The user page tables get the full PGD, accessible from
136          * userspace:
137          */
138         kernel_to_user_pgdp(pgdp)->pgd = pgd.pgd;
139
140         /*
141          * If this is normal user memory, make it NX in the kernel
142          * pagetables so that, if we somehow screw up and return to
143          * usermode with the kernel CR3 loaded, we'll get a page fault
144          * instead of allowing user code to execute with the wrong CR3.
145          *
146          * As exceptions, we don't set NX if:
147          *  - _PAGE_USER is not set.  This could be an executable
148          *     EFI runtime mapping or something similar, and the kernel
149          *     may execute from it
150          *  - we don't have NX support
151          *  - we're clearing the PGD (i.e. the new pgd is not present).
152          */
153         if ((pgd.pgd & (_PAGE_USER|_PAGE_PRESENT)) == (_PAGE_USER|_PAGE_PRESENT) &&
154             (__supported_pte_mask & _PAGE_NX))
155                 pgd.pgd |= _PAGE_NX;
156
157         /* return the copy of the PGD we want the kernel to use: */
158         return pgd;
159 }
160
161 /*
162  * Walk the user copy of the page tables (optionally) trying to allocate
163  * page table pages on the way down.
164  *
165  * Returns a pointer to a P4D on success, or NULL on failure.
166  */
167 static p4d_t *pti_user_pagetable_walk_p4d(unsigned long address)
168 {
169         pgd_t *pgd = kernel_to_user_pgdp(pgd_offset_k(address));
170         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
171
172         if (address < PAGE_OFFSET) {
173                 WARN_ONCE(1, "attempt to walk user address\n");
174                 return NULL;
175         }
176
177         if (pgd_none(*pgd)) {
178                 unsigned long new_p4d_page = __get_free_page(gfp);
179                 if (!new_p4d_page)
180                         return NULL;
181
182                 set_pgd(pgd, __pgd(_KERNPG_TABLE | __pa(new_p4d_page)));
183         }
184         BUILD_BUG_ON(pgd_large(*pgd) != 0);
185
186         return p4d_offset(pgd, address);
187 }
188
189 /*
190  * Walk the user copy of the page tables (optionally) trying to allocate
191  * page table pages on the way down.
192  *
193  * Returns a pointer to a PMD on success, or NULL on failure.
194  */
195 static pmd_t *pti_user_pagetable_walk_pmd(unsigned long address)
196 {
197         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
198         p4d_t *p4d = pti_user_pagetable_walk_p4d(address);
199         pud_t *pud;
200
201         BUILD_BUG_ON(p4d_large(*p4d) != 0);
202         if (p4d_none(*p4d)) {
203                 unsigned long new_pud_page = __get_free_page(gfp);
204                 if (!new_pud_page)
205                         return NULL;
206
207                 set_p4d(p4d, __p4d(_KERNPG_TABLE | __pa(new_pud_page)));
208         }
209
210         pud = pud_offset(p4d, address);
211         /* The user page tables do not use large mappings: */
212         if (pud_large(*pud)) {
213                 WARN_ON(1);
214                 return NULL;
215         }
216         if (pud_none(*pud)) {
217                 unsigned long new_pmd_page = __get_free_page(gfp);
218                 if (!new_pmd_page)
219                         return NULL;
220
221                 set_pud(pud, __pud(_KERNPG_TABLE | __pa(new_pmd_page)));
222         }
223
224         return pmd_offset(pud, address);
225 }
226
227 #ifdef CONFIG_X86_VSYSCALL_EMULATION
228 /*
229  * Walk the shadow copy of the page tables (optionally) trying to allocate
230  * page table pages on the way down.  Does not support large pages.
231  *
232  * Note: this is only used when mapping *new* kernel data into the
233  * user/shadow page tables.  It is never used for userspace data.
234  *
235  * Returns a pointer to a PTE on success, or NULL on failure.
236  */
237 static __init pte_t *pti_user_pagetable_walk_pte(unsigned long address)
238 {
239         gfp_t gfp = (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO);
240         pmd_t *pmd = pti_user_pagetable_walk_pmd(address);
241         pte_t *pte;
242
243         /* We can't do anything sensible if we hit a large mapping. */
244         if (pmd_large(*pmd)) {
245                 WARN_ON(1);
246                 return NULL;
247         }
248
249         if (pmd_none(*pmd)) {
250                 unsigned long new_pte_page = __get_free_page(gfp);
251                 if (!new_pte_page)
252                         return NULL;
253
254                 set_pmd(pmd, __pmd(_KERNPG_TABLE | __pa(new_pte_page)));
255         }
256
257         pte = pte_offset_kernel(pmd, address);
258         if (pte_flags(*pte) & _PAGE_USER) {
259                 WARN_ONCE(1, "attempt to walk to user pte\n");
260                 return NULL;
261         }
262         return pte;
263 }
264
265 static void __init pti_setup_vsyscall(void)
266 {
267         pte_t *pte, *target_pte;
268         unsigned int level;
269
270         pte = lookup_address(VSYSCALL_ADDR, &level);
271         if (!pte || WARN_ON(level != PG_LEVEL_4K) || pte_none(*pte))
272                 return;
273
274         target_pte = pti_user_pagetable_walk_pte(VSYSCALL_ADDR);
275         if (WARN_ON(!target_pte))
276                 return;
277
278         *target_pte = *pte;
279         set_vsyscall_pgtable_user_bits(kernel_to_user_pgdp(swapper_pg_dir));
280 }
281 #else
282 static void __init pti_setup_vsyscall(void) { }
283 #endif
284
285 static void
286 pti_clone_pmds(unsigned long start, unsigned long end, pmdval_t clear)
287 {
288         unsigned long addr;
289
290         /*
291          * Clone the populated PMDs which cover start to end. These PMD areas
292          * can have holes.
293          */
294         for (addr = start; addr < end; addr += PMD_SIZE) {
295                 pmd_t *pmd, *target_pmd;
296                 pgd_t *pgd;
297                 p4d_t *p4d;
298                 pud_t *pud;
299
300                 /* Overflow check */
301                 if (addr < start)
302                         break;
303
304                 pgd = pgd_offset_k(addr);
305                 if (WARN_ON(pgd_none(*pgd)))
306                         return;
307                 p4d = p4d_offset(pgd, addr);
308                 if (WARN_ON(p4d_none(*p4d)))
309                         return;
310                 pud = pud_offset(p4d, addr);
311                 if (pud_none(*pud))
312                         continue;
313                 pmd = pmd_offset(pud, addr);
314                 if (pmd_none(*pmd))
315                         continue;
316
317                 target_pmd = pti_user_pagetable_walk_pmd(addr);
318                 if (WARN_ON(!target_pmd))
319                         return;
320
321                 /*
322                  * Only clone present PMDs.  This ensures only setting
323                  * _PAGE_GLOBAL on present PMDs.  This should only be
324                  * called on well-known addresses anyway, so a non-
325                  * present PMD would be a surprise.
326                  */
327                 if (WARN_ON(!(pmd_flags(*pmd) & _PAGE_PRESENT)))
328                         return;
329
330                 /*
331                  * Setting 'target_pmd' below creates a mapping in both
332                  * the user and kernel page tables.  It is effectively
333                  * global, so set it as global in both copies.  Note:
334                  * the X86_FEATURE_PGE check is not _required_ because
335                  * the CPU ignores _PAGE_GLOBAL when PGE is not
336                  * supported.  The check keeps consistentency with
337                  * code that only set this bit when supported.
338                  */
339                 if (boot_cpu_has(X86_FEATURE_PGE))
340                         *pmd = pmd_set_flags(*pmd, _PAGE_GLOBAL);
341
342                 /*
343                  * Copy the PMD.  That is, the kernelmode and usermode
344                  * tables will share the last-level page tables of this
345                  * address range
346                  */
347                 *target_pmd = pmd_clear_flags(*pmd, clear);
348         }
349 }
350
351 #ifdef CONFIG_X86_64
352 /*
353  * Clone a single p4d (i.e. a top-level entry on 4-level systems and a
354  * next-level entry on 5-level systems.
355  */
356 static void __init pti_clone_p4d(unsigned long addr)
357 {
358         p4d_t *kernel_p4d, *user_p4d;
359         pgd_t *kernel_pgd;
360
361         user_p4d = pti_user_pagetable_walk_p4d(addr);
362         kernel_pgd = pgd_offset_k(addr);
363         kernel_p4d = p4d_offset(kernel_pgd, addr);
364         *user_p4d = *kernel_p4d;
365 }
366
367 /*
368  * Clone the CPU_ENTRY_AREA into the user space visible page table.
369  */
370 static void __init pti_clone_user_shared(void)
371 {
372         pti_clone_p4d(CPU_ENTRY_AREA_BASE);
373 }
374
375 #else /* CONFIG_X86_64 */
376
377 /*
378  * On 32 bit PAE systems with 1GB of Kernel address space there is only
379  * one pgd/p4d for the whole kernel. Cloning that would map the whole
380  * address space into the user page-tables, making PTI useless. So clone
381  * the page-table on the PMD level to prevent that.
382  */
383 static void __init pti_clone_user_shared(void)
384 {
385         unsigned long start, end;
386
387         start = CPU_ENTRY_AREA_BASE;
388         end   = start + (PAGE_SIZE * CPU_ENTRY_AREA_PAGES);
389
390         pti_clone_pmds(start, end, 0);
391 }
392 #endif /* CONFIG_X86_64 */
393
394 /*
395  * Clone the ESPFIX P4D into the user space visible page table
396  */
397 static void __init pti_setup_espfix64(void)
398 {
399 #ifdef CONFIG_X86_ESPFIX64
400         pti_clone_p4d(ESPFIX_BASE_ADDR);
401 #endif
402 }
403
404 /*
405  * Clone the populated PMDs of the entry and irqentry text and force it RO.
406  */
407 static void pti_clone_entry_text(void)
408 {
409         pti_clone_pmds((unsigned long) __entry_text_start,
410                         (unsigned long) __irqentry_text_end,
411                        _PAGE_RW);
412 }
413
414 /*
415  * Global pages and PCIDs are both ways to make kernel TLB entries
416  * live longer, reduce TLB misses and improve kernel performance.
417  * But, leaving all kernel text Global makes it potentially accessible
418  * to Meltdown-style attacks which make it trivial to find gadgets or
419  * defeat KASLR.
420  *
421  * Only use global pages when it is really worth it.
422  */
423 static inline bool pti_kernel_image_global_ok(void)
424 {
425         /*
426          * Systems with PCIDs get litlle benefit from global
427          * kernel text and are not worth the downsides.
428          */
429         if (cpu_feature_enabled(X86_FEATURE_PCID))
430                 return false;
431
432         /*
433          * Only do global kernel image for pti=auto.  Do the most
434          * secure thing (not global) if pti=on specified.
435          */
436         if (pti_mode != PTI_AUTO)
437                 return false;
438
439         /*
440          * K8 may not tolerate the cleared _PAGE_RW on the userspace
441          * global kernel image pages.  Do the safe thing (disable
442          * global kernel image).  This is unlikely to ever be
443          * noticed because PTI is disabled by default on AMD CPUs.
444          */
445         if (boot_cpu_has(X86_FEATURE_K8))
446                 return false;
447
448         /*
449          * RANDSTRUCT derives its hardening benefits from the
450          * attacker's lack of knowledge about the layout of kernel
451          * data structures.  Keep the kernel image non-global in
452          * cases where RANDSTRUCT is in use to help keep the layout a
453          * secret.
454          */
455         if (IS_ENABLED(CONFIG_GCC_PLUGIN_RANDSTRUCT))
456                 return false;
457
458         return true;
459 }
460
461 /*
462  * For some configurations, map all of kernel text into the user page
463  * tables.  This reduces TLB misses, especially on non-PCID systems.
464  */
465 static void pti_clone_kernel_text(void)
466 {
467         /*
468          * rodata is part of the kernel image and is normally
469          * readable on the filesystem or on the web.  But, do not
470          * clone the areas past rodata, they might contain secrets.
471          */
472         unsigned long start = PFN_ALIGN(_text);
473         unsigned long end = (unsigned long)__end_rodata_aligned;
474
475         if (!pti_kernel_image_global_ok())
476                 return;
477
478         pr_debug("mapping partial kernel image into user address space\n");
479
480         /*
481          * Note that this will undo _some_ of the work that
482          * pti_set_kernel_image_nonglobal() did to clear the
483          * global bit.
484          */
485         pti_clone_pmds(start, end, 0);
486 }
487
488 /*
489  * This is the only user for it and it is not arch-generic like
490  * the other set_memory.h functions.  Just extern it.
491  */
492 extern int set_memory_nonglobal(unsigned long addr, int numpages);
493 static void pti_set_kernel_image_nonglobal(void)
494 {
495         /*
496          * The identity map is created with PMDs, regardless of the
497          * actual length of the kernel.  We need to clear
498          * _PAGE_GLOBAL up to a PMD boundary, not just to the end
499          * of the image.
500          */
501         unsigned long start = PFN_ALIGN(_text);
502         unsigned long end = ALIGN((unsigned long)_end, PMD_PAGE_SIZE);
503
504         if (pti_kernel_image_global_ok())
505                 return;
506
507         set_memory_nonglobal(start, (end - start) >> PAGE_SHIFT);
508 }
509
510 /*
511  * Initialize kernel page table isolation
512  */
513 void __init pti_init(void)
514 {
515         if (!static_cpu_has(X86_FEATURE_PTI))
516                 return;
517
518         pr_info("enabled\n");
519
520 #ifdef CONFIG_X86_32
521         /*
522          * We check for X86_FEATURE_PCID here. But the init-code will
523          * clear the feature flag on 32 bit because the feature is not
524          * supported on 32 bit anyway. To print the warning we need to
525          * check with cpuid directly again.
526          */
527         if (cpuid_ecx(0x1) && BIT(17)) {
528                 /* Use printk to work around pr_fmt() */
529                 printk(KERN_WARNING "\n");
530                 printk(KERN_WARNING "************************************************************\n");
531                 printk(KERN_WARNING "** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!  **\n");
532                 printk(KERN_WARNING "**                                                        **\n");
533                 printk(KERN_WARNING "** You are using 32-bit PTI on a 64-bit PCID-capable CPU. **\n");
534                 printk(KERN_WARNING "** Your performance will increase dramatically if you     **\n");
535                 printk(KERN_WARNING "** switch to a 64-bit kernel!                             **\n");
536                 printk(KERN_WARNING "**                                                        **\n");
537                 printk(KERN_WARNING "** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!  **\n");
538                 printk(KERN_WARNING "************************************************************\n");
539         }
540 #endif
541
542         pti_clone_user_shared();
543
544         /* Undo all global bits from the init pagetables in head_64.S: */
545         pti_set_kernel_image_nonglobal();
546         /* Replace some of the global bits just for shared entry text: */
547         pti_clone_entry_text();
548         pti_setup_espfix64();
549         pti_setup_vsyscall();
550 }
551
552 /*
553  * Finalize the kernel mappings in the userspace page-table. Some of the
554  * mappings for the kernel image might have changed since pti_init()
555  * cloned them. This is because parts of the kernel image have been
556  * mapped RO and/or NX.  These changes need to be cloned again to the
557  * userspace page-table.
558  */
559 void pti_finalize(void)
560 {
561         /*
562          * We need to clone everything (again) that maps parts of the
563          * kernel image.
564          */
565         pti_clone_entry_text();
566         pti_clone_kernel_text();
567 }