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