1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This code is used on x86_64 to create page table identity mappings on
4  * demand by building up a new set of page tables (or appending to the
5  * existing ones), and then switching over to them when ready.
6  *
7  * Copyright (C) 2015-2016  Yinghai Lu
8  * Copyright (C)      2016  Kees Cook
9  */
10 
11 /*
12  * Since we're dealing with identity mappings, physical and virtual
13  * addresses are the same, so override these defines which are ultimately
14  * used by the headers in misc.h.
15  */
16 #define __pa(x)  ((unsigned long)(x))
17 #define __va(x)  ((void *)((unsigned long)(x)))
18 
19 /* No PAGE_TABLE_ISOLATION support needed either: */
20 #undef CONFIG_PAGE_TABLE_ISOLATION
21 
22 #include "error.h"
23 #include "misc.h"
24 
25 /* These actually do the work of building the kernel identity maps. */
26 #include <linux/pgtable.h>
27 #include <asm/cmpxchg.h>
28 #include <asm/trap_pf.h>
29 #include <asm/trapnr.h>
30 #include <asm/init.h>
31 /* Use the static base for this part of the boot process */
32 #undef __PAGE_OFFSET
33 #define __PAGE_OFFSET __PAGE_OFFSET_BASE
34 #include "../../mm/ident_map.c"
35 
36 #ifdef CONFIG_X86_5LEVEL
37 unsigned int __pgtable_l5_enabled;
38 unsigned int pgdir_shift = 39;
39 unsigned int ptrs_per_p4d = 1;
40 #endif
41 
42 /* Used by PAGE_KERN* macros: */
43 pteval_t __default_kernel_pte_mask __read_mostly = ~0;
44 
45 /* Used to track our page table allocation area. */
46 struct alloc_pgt_data {
47 	unsigned char *pgt_buf;
48 	unsigned long pgt_buf_size;
49 	unsigned long pgt_buf_offset;
50 };
51 
52 /*
53  * Allocates space for a page table entry, using struct alloc_pgt_data
54  * above. Besides the local callers, this is used as the allocation
55  * callback in mapping_info below.
56  */
57 static void *alloc_pgt_page(void *context)
58 {
59 	struct alloc_pgt_data *pages = (struct alloc_pgt_data *)context;
60 	unsigned char *entry;
61 
62 	/* Validate there is space available for a new page. */
63 	if (pages->pgt_buf_offset >= pages->pgt_buf_size) {
64 		debug_putstr("out of pgt_buf in " __FILE__ "!?\n");
65 		debug_putaddr(pages->pgt_buf_offset);
66 		debug_putaddr(pages->pgt_buf_size);
67 		return NULL;
68 	}
69 
70 	entry = pages->pgt_buf + pages->pgt_buf_offset;
71 	pages->pgt_buf_offset += PAGE_SIZE;
72 
73 	return entry;
74 }
75 
76 /* Used to track our allocated page tables. */
77 static struct alloc_pgt_data pgt_data;
78 
79 /* The top level page table entry pointer. */
80 static unsigned long top_level_pgt;
81 
82 phys_addr_t physical_mask = (1ULL << __PHYSICAL_MASK_SHIFT) - 1;
83 
84 /*
85  * Mapping information structure passed to kernel_ident_mapping_init().
86  * Due to relocation, pointers must be assigned at run time not build time.
87  */
88 static struct x86_mapping_info mapping_info;
89 
90 /*
91  * Adds the specified range to the identity mappings.
92  */
93 static void add_identity_map(unsigned long start, unsigned long end)
94 {
95 	int ret;
96 
97 	/* Align boundary to 2M. */
98 	start = round_down(start, PMD_SIZE);
99 	end = round_up(end, PMD_SIZE);
100 	if (start >= end)
101 		return;
102 
103 	/* Build the mapping. */
104 	ret = kernel_ident_mapping_init(&mapping_info, (pgd_t *)top_level_pgt, start, end);
105 	if (ret)
106 		error("Error: kernel_ident_mapping_init() failed\n");
107 }
108 
109 /* Locates and clears a region for a new top level page table. */
110 void initialize_identity_maps(void)
111 {
112 	/* Exclude the encryption mask from __PHYSICAL_MASK */
113 	physical_mask &= ~sme_me_mask;
114 
115 	/* Init mapping_info with run-time function/buffer pointers. */
116 	mapping_info.alloc_pgt_page = alloc_pgt_page;
117 	mapping_info.context = &pgt_data;
118 	mapping_info.page_flag = __PAGE_KERNEL_LARGE_EXEC | sme_me_mask;
119 	mapping_info.kernpg_flag = _KERNPG_TABLE;
120 
121 	/*
122 	 * It should be impossible for this not to already be true,
123 	 * but since calling this a second time would rewind the other
124 	 * counters, let's just make sure this is reset too.
125 	 */
126 	pgt_data.pgt_buf_offset = 0;
127 
128 	/*
129 	 * If we came here via startup_32(), cr3 will be _pgtable already
130 	 * and we must append to the existing area instead of entirely
131 	 * overwriting it.
132 	 *
133 	 * With 5-level paging, we use '_pgtable' to allocate the p4d page table,
134 	 * the top-level page table is allocated separately.
135 	 *
136 	 * p4d_offset(top_level_pgt, 0) would cover both the 4- and 5-level
137 	 * cases. On 4-level paging it's equal to 'top_level_pgt'.
138 	 */
139 	top_level_pgt = read_cr3_pa();
140 	if (p4d_offset((pgd_t *)top_level_pgt, 0) == (p4d_t *)_pgtable) {
141 		pgt_data.pgt_buf = _pgtable + BOOT_INIT_PGT_SIZE;
142 		pgt_data.pgt_buf_size = BOOT_PGT_SIZE - BOOT_INIT_PGT_SIZE;
143 		memset(pgt_data.pgt_buf, 0, pgt_data.pgt_buf_size);
144 	} else {
145 		pgt_data.pgt_buf = _pgtable;
146 		pgt_data.pgt_buf_size = BOOT_PGT_SIZE;
147 		memset(pgt_data.pgt_buf, 0, pgt_data.pgt_buf_size);
148 		top_level_pgt = (unsigned long)alloc_pgt_page(&pgt_data);
149 	}
150 
151 	/*
152 	 * New page-table is set up - map the kernel image and load it
153 	 * into cr3.
154 	 */
155 	add_identity_map((unsigned long)_head, (unsigned long)_end);
156 	write_cr3(top_level_pgt);
157 }
158 
159 /*
160  * This switches the page tables to the new level4 that has been built
161  * via calls to add_identity_map() above. If booted via startup_32(),
162  * this is effectively a no-op.
163  */
164 void finalize_identity_maps(void)
165 {
166 	write_cr3(top_level_pgt);
167 }
168 
169 static pte_t *split_large_pmd(struct x86_mapping_info *info,
170 			      pmd_t *pmdp, unsigned long __address)
171 {
172 	unsigned long page_flags;
173 	unsigned long address;
174 	pte_t *pte;
175 	pmd_t pmd;
176 	int i;
177 
178 	pte = (pte_t *)info->alloc_pgt_page(info->context);
179 	if (!pte)
180 		return NULL;
181 
182 	address     = __address & PMD_MASK;
183 	/* No large page - clear PSE flag */
184 	page_flags  = info->page_flag & ~_PAGE_PSE;
185 
186 	/* Populate the PTEs */
187 	for (i = 0; i < PTRS_PER_PMD; i++) {
188 		set_pte(&pte[i], __pte(address | page_flags));
189 		address += PAGE_SIZE;
190 	}
191 
192 	/*
193 	 * Ideally we need to clear the large PMD first and do a TLB
194 	 * flush before we write the new PMD. But the 2M range of the
195 	 * PMD might contain the code we execute and/or the stack
196 	 * we are on, so we can't do that. But that should be safe here
197 	 * because we are going from large to small mappings and we are
198 	 * also the only user of the page-table, so there is no chance
199 	 * of a TLB multihit.
200 	 */
201 	pmd = __pmd((unsigned long)pte | info->kernpg_flag);
202 	set_pmd(pmdp, pmd);
203 	/* Flush TLB to establish the new PMD */
204 	write_cr3(top_level_pgt);
205 
206 	return pte + pte_index(__address);
207 }
208 
209 static void clflush_page(unsigned long address)
210 {
211 	unsigned int flush_size;
212 	char *cl, *start, *end;
213 
214 	/*
215 	 * Hardcode cl-size to 64 - CPUID can't be used here because that might
216 	 * cause another #VC exception and the GHCB is not ready to use yet.
217 	 */
218 	flush_size = 64;
219 	start      = (char *)(address & PAGE_MASK);
220 	end        = start + PAGE_SIZE;
221 
222 	/*
223 	 * First make sure there are no pending writes on the cache-lines to
224 	 * flush.
225 	 */
226 	asm volatile("mfence" : : : "memory");
227 
228 	for (cl = start; cl != end; cl += flush_size)
229 		clflush(cl);
230 }
231 
232 static int set_clr_page_flags(struct x86_mapping_info *info,
233 			      unsigned long address,
234 			      pteval_t set, pteval_t clr)
235 {
236 	pgd_t *pgdp = (pgd_t *)top_level_pgt;
237 	p4d_t *p4dp;
238 	pud_t *pudp;
239 	pmd_t *pmdp;
240 	pte_t *ptep, pte;
241 
242 	/*
243 	 * First make sure there is a PMD mapping for 'address'.
244 	 * It should already exist, but keep things generic.
245 	 *
246 	 * To map the page just read from it and fault it in if there is no
247 	 * mapping yet. add_identity_map() can't be called here because that
248 	 * would unconditionally map the address on PMD level, destroying any
249 	 * PTE-level mappings that might already exist. Use assembly here so
250 	 * the access won't be optimized away.
251 	 */
252 	asm volatile("mov %[address], %%r9"
253 		     :: [address] "g" (*(unsigned long *)address)
254 		     : "r9", "memory");
255 
256 	/*
257 	 * The page is mapped at least with PMD size - so skip checks and walk
258 	 * directly to the PMD.
259 	 */
260 	p4dp = p4d_offset(pgdp, address);
261 	pudp = pud_offset(p4dp, address);
262 	pmdp = pmd_offset(pudp, address);
263 
264 	if (pmd_large(*pmdp))
265 		ptep = split_large_pmd(info, pmdp, address);
266 	else
267 		ptep = pte_offset_kernel(pmdp, address);
268 
269 	if (!ptep)
270 		return -ENOMEM;
271 
272 	/*
273 	 * Changing encryption attributes of a page requires to flush it from
274 	 * the caches.
275 	 */
276 	if ((set | clr) & _PAGE_ENC)
277 		clflush_page(address);
278 
279 	/* Update PTE */
280 	pte = *ptep;
281 	pte = pte_set_flags(pte, set);
282 	pte = pte_clear_flags(pte, clr);
283 	set_pte(ptep, pte);
284 
285 	/* Flush TLB after changing encryption attribute */
286 	write_cr3(top_level_pgt);
287 
288 	return 0;
289 }
290 
291 int set_page_decrypted(unsigned long address)
292 {
293 	return set_clr_page_flags(&mapping_info, address, 0, _PAGE_ENC);
294 }
295 
296 int set_page_encrypted(unsigned long address)
297 {
298 	return set_clr_page_flags(&mapping_info, address, _PAGE_ENC, 0);
299 }
300 
301 int set_page_non_present(unsigned long address)
302 {
303 	return set_clr_page_flags(&mapping_info, address, 0, _PAGE_PRESENT);
304 }
305 
306 static void do_pf_error(const char *msg, unsigned long error_code,
307 			unsigned long address, unsigned long ip)
308 {
309 	error_putstr(msg);
310 
311 	error_putstr("\nError Code: ");
312 	error_puthex(error_code);
313 	error_putstr("\nCR2: 0x");
314 	error_puthex(address);
315 	error_putstr("\nRIP relative to _head: 0x");
316 	error_puthex(ip - (unsigned long)_head);
317 	error_putstr("\n");
318 
319 	error("Stopping.\n");
320 }
321 
322 void do_boot_page_fault(struct pt_regs *regs, unsigned long error_code)
323 {
324 	unsigned long address = native_read_cr2();
325 	unsigned long end;
326 	bool ghcb_fault;
327 
328 	ghcb_fault = sev_es_check_ghcb_fault(address);
329 
330 	address   &= PMD_MASK;
331 	end        = address + PMD_SIZE;
332 
333 	/*
334 	 * Check for unexpected error codes. Unexpected are:
335 	 *	- Faults on present pages
336 	 *	- User faults
337 	 *	- Reserved bits set
338 	 */
339 	if (error_code & (X86_PF_PROT | X86_PF_USER | X86_PF_RSVD))
340 		do_pf_error("Unexpected page-fault:", error_code, address, regs->ip);
341 	else if (ghcb_fault)
342 		do_pf_error("Page-fault on GHCB page:", error_code, address, regs->ip);
343 
344 	/*
345 	 * Error code is sane - now identity map the 2M region around
346 	 * the faulting address.
347 	 */
348 	add_identity_map(address, end);
349 }
350