xref: /openbmc/linux/arch/x86/kernel/machine_kexec_64.c (revision 360823a09426347ea8f232b0b0b5156d0aed0302)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * handle transition of Linux booting another kernel
4  * Copyright (C) 2002-2005 Eric Biederman  <ebiederm@xmission.com>
5  */
6 
7 #define pr_fmt(fmt)	"kexec: " fmt
8 
9 #include <linux/mm.h>
10 #include <linux/kexec.h>
11 #include <linux/string.h>
12 #include <linux/gfp.h>
13 #include <linux/reboot.h>
14 #include <linux/numa.h>
15 #include <linux/ftrace.h>
16 #include <linux/io.h>
17 #include <linux/suspend.h>
18 #include <linux/vmalloc.h>
19 #include <linux/efi.h>
20 #include <linux/cc_platform.h>
21 
22 #include <asm/init.h>
23 #include <asm/tlbflush.h>
24 #include <asm/mmu_context.h>
25 #include <asm/io_apic.h>
26 #include <asm/debugreg.h>
27 #include <asm/kexec-bzimage64.h>
28 #include <asm/setup.h>
29 #include <asm/set_memory.h>
30 #include <asm/cpu.h>
31 #include <asm/efi.h>
32 
33 #ifdef CONFIG_ACPI
34 /*
35  * Used while adding mapping for ACPI tables.
36  * Can be reused when other iomem regions need be mapped
37  */
38 struct init_pgtable_data {
39 	struct x86_mapping_info *info;
40 	pgd_t *level4p;
41 };
42 
mem_region_callback(struct resource * res,void * arg)43 static int mem_region_callback(struct resource *res, void *arg)
44 {
45 	struct init_pgtable_data *data = arg;
46 	unsigned long mstart, mend;
47 
48 	mstart = res->start;
49 	mend = mstart + resource_size(res) - 1;
50 
51 	return kernel_ident_mapping_init(data->info, data->level4p, mstart, mend);
52 }
53 
54 static int
map_acpi_tables(struct x86_mapping_info * info,pgd_t * level4p)55 map_acpi_tables(struct x86_mapping_info *info, pgd_t *level4p)
56 {
57 	struct init_pgtable_data data;
58 	unsigned long flags;
59 	int ret;
60 
61 	data.info = info;
62 	data.level4p = level4p;
63 	flags = IORESOURCE_MEM | IORESOURCE_BUSY;
64 
65 	ret = walk_iomem_res_desc(IORES_DESC_ACPI_TABLES, flags, 0, -1,
66 				  &data, mem_region_callback);
67 	if (ret && ret != -EINVAL)
68 		return ret;
69 
70 	/* ACPI tables could be located in ACPI Non-volatile Storage region */
71 	ret = walk_iomem_res_desc(IORES_DESC_ACPI_NV_STORAGE, flags, 0, -1,
72 				  &data, mem_region_callback);
73 	if (ret && ret != -EINVAL)
74 		return ret;
75 
76 	return 0;
77 }
78 #else
map_acpi_tables(struct x86_mapping_info * info,pgd_t * level4p)79 static int map_acpi_tables(struct x86_mapping_info *info, pgd_t *level4p) { return 0; }
80 #endif
81 
82 #ifdef CONFIG_KEXEC_FILE
83 const struct kexec_file_ops * const kexec_file_loaders[] = {
84 		&kexec_bzImage64_ops,
85 		NULL
86 };
87 #endif
88 
89 static int
map_efi_systab(struct x86_mapping_info * info,pgd_t * level4p)90 map_efi_systab(struct x86_mapping_info *info, pgd_t *level4p)
91 {
92 #ifdef CONFIG_EFI
93 	unsigned long mstart, mend;
94 	void *kaddr;
95 	int ret;
96 
97 	if (!efi_enabled(EFI_BOOT))
98 		return 0;
99 
100 	mstart = (boot_params.efi_info.efi_systab |
101 			((u64)boot_params.efi_info.efi_systab_hi<<32));
102 
103 	if (efi_enabled(EFI_64BIT))
104 		mend = mstart + sizeof(efi_system_table_64_t);
105 	else
106 		mend = mstart + sizeof(efi_system_table_32_t);
107 
108 	if (!mstart)
109 		return 0;
110 
111 	ret = kernel_ident_mapping_init(info, level4p, mstart, mend);
112 	if (ret)
113 		return ret;
114 
115 	kaddr = memremap(mstart, mend - mstart, MEMREMAP_WB);
116 	if (!kaddr) {
117 		pr_err("Could not map UEFI system table\n");
118 		return -ENOMEM;
119 	}
120 
121 	mstart = efi_config_table;
122 
123 	if (efi_enabled(EFI_64BIT)) {
124 		efi_system_table_64_t *stbl = (efi_system_table_64_t *)kaddr;
125 
126 		mend = mstart + sizeof(efi_config_table_64_t) * stbl->nr_tables;
127 	} else {
128 		efi_system_table_32_t *stbl = (efi_system_table_32_t *)kaddr;
129 
130 		mend = mstart + sizeof(efi_config_table_32_t) * stbl->nr_tables;
131 	}
132 
133 	memunmap(kaddr);
134 
135 	return kernel_ident_mapping_init(info, level4p, mstart, mend);
136 #endif
137 	return 0;
138 }
139 
free_transition_pgtable(struct kimage * image)140 static void free_transition_pgtable(struct kimage *image)
141 {
142 	free_page((unsigned long)image->arch.p4d);
143 	image->arch.p4d = NULL;
144 	free_page((unsigned long)image->arch.pud);
145 	image->arch.pud = NULL;
146 	free_page((unsigned long)image->arch.pmd);
147 	image->arch.pmd = NULL;
148 	free_page((unsigned long)image->arch.pte);
149 	image->arch.pte = NULL;
150 }
151 
init_transition_pgtable(struct kimage * image,pgd_t * pgd,unsigned long control_page)152 static int init_transition_pgtable(struct kimage *image, pgd_t *pgd,
153 				   unsigned long control_page)
154 {
155 	pgprot_t prot = PAGE_KERNEL_EXEC_NOENC;
156 	unsigned long vaddr, paddr;
157 	int result = -ENOMEM;
158 	p4d_t *p4d;
159 	pud_t *pud;
160 	pmd_t *pmd;
161 	pte_t *pte;
162 
163 	vaddr = (unsigned long)relocate_kernel;
164 	paddr = control_page;
165 	pgd += pgd_index(vaddr);
166 	if (!pgd_present(*pgd)) {
167 		p4d = (p4d_t *)get_zeroed_page(GFP_KERNEL);
168 		if (!p4d)
169 			goto err;
170 		image->arch.p4d = p4d;
171 		set_pgd(pgd, __pgd(__pa(p4d) | _KERNPG_TABLE));
172 	}
173 	p4d = p4d_offset(pgd, vaddr);
174 	if (!p4d_present(*p4d)) {
175 		pud = (pud_t *)get_zeroed_page(GFP_KERNEL);
176 		if (!pud)
177 			goto err;
178 		image->arch.pud = pud;
179 		set_p4d(p4d, __p4d(__pa(pud) | _KERNPG_TABLE));
180 	}
181 	pud = pud_offset(p4d, vaddr);
182 	if (!pud_present(*pud)) {
183 		pmd = (pmd_t *)get_zeroed_page(GFP_KERNEL);
184 		if (!pmd)
185 			goto err;
186 		image->arch.pmd = pmd;
187 		set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
188 	}
189 	pmd = pmd_offset(pud, vaddr);
190 	if (!pmd_present(*pmd)) {
191 		pte = (pte_t *)get_zeroed_page(GFP_KERNEL);
192 		if (!pte)
193 			goto err;
194 		image->arch.pte = pte;
195 		set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
196 	}
197 	pte = pte_offset_kernel(pmd, vaddr);
198 
199 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
200 		prot = PAGE_KERNEL_EXEC;
201 
202 	set_pte(pte, pfn_pte(paddr >> PAGE_SHIFT, prot));
203 	return 0;
204 err:
205 	return result;
206 }
207 
alloc_pgt_page(void * data)208 static void *alloc_pgt_page(void *data)
209 {
210 	struct kimage *image = (struct kimage *)data;
211 	struct page *page;
212 	void *p = NULL;
213 
214 	page = kimage_alloc_control_pages(image, 0);
215 	if (page) {
216 		p = page_address(page);
217 		clear_page(p);
218 	}
219 
220 	return p;
221 }
222 
init_pgtable(struct kimage * image,unsigned long control_page)223 static int init_pgtable(struct kimage *image, unsigned long control_page)
224 {
225 	struct x86_mapping_info info = {
226 		.alloc_pgt_page	= alloc_pgt_page,
227 		.context	= image,
228 		.page_flag	= __PAGE_KERNEL_LARGE_EXEC,
229 		.kernpg_flag	= _KERNPG_TABLE_NOENC,
230 	};
231 	unsigned long mstart, mend;
232 	int result;
233 	int i;
234 
235 	image->arch.pgd = alloc_pgt_page(image);
236 	if (!image->arch.pgd)
237 		return -ENOMEM;
238 
239 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
240 		info.page_flag   |= _PAGE_ENC;
241 		info.kernpg_flag |= _PAGE_ENC;
242 	}
243 
244 	if (direct_gbpages)
245 		info.direct_gbpages = true;
246 
247 	for (i = 0; i < nr_pfn_mapped; i++) {
248 		mstart = pfn_mapped[i].start << PAGE_SHIFT;
249 		mend   = pfn_mapped[i].end << PAGE_SHIFT;
250 
251 		result = kernel_ident_mapping_init(&info, image->arch.pgd,
252 						   mstart, mend);
253 		if (result)
254 			return result;
255 	}
256 
257 	/*
258 	 * segments's mem ranges could be outside 0 ~ max_pfn,
259 	 * for example when jump back to original kernel from kexeced kernel.
260 	 * or first kernel is booted with user mem map, and second kernel
261 	 * could be loaded out of that range.
262 	 */
263 	for (i = 0; i < image->nr_segments; i++) {
264 		mstart = image->segment[i].mem;
265 		mend   = mstart + image->segment[i].memsz;
266 
267 		result = kernel_ident_mapping_init(&info, image->arch.pgd,
268 						   mstart, mend);
269 
270 		if (result)
271 			return result;
272 	}
273 
274 	/*
275 	 * Prepare EFI systab and ACPI tables for kexec kernel since they are
276 	 * not covered by pfn_mapped.
277 	 */
278 	result = map_efi_systab(&info, image->arch.pgd);
279 	if (result)
280 		return result;
281 
282 	result = map_acpi_tables(&info, image->arch.pgd);
283 	if (result)
284 		return result;
285 
286 	/*
287 	 * This must be last because the intermediate page table pages it
288 	 * allocates will not be control pages and may overlap the image.
289 	 */
290 	return init_transition_pgtable(image, image->arch.pgd, control_page);
291 }
292 
load_segments(void)293 static void load_segments(void)
294 {
295 	__asm__ __volatile__ (
296 		"\tmovl %0,%%ds\n"
297 		"\tmovl %0,%%es\n"
298 		"\tmovl %0,%%ss\n"
299 		"\tmovl %0,%%fs\n"
300 		"\tmovl %0,%%gs\n"
301 		: : "a" (__KERNEL_DS) : "memory"
302 		);
303 }
304 
machine_kexec_prepare(struct kimage * image)305 int machine_kexec_prepare(struct kimage *image)
306 {
307 	unsigned long control_page;
308 	int result;
309 
310 	/* Calculate the offsets */
311 	control_page = page_to_pfn(image->control_code_page) << PAGE_SHIFT;
312 
313 	/* Setup the identity mapped 64bit page table */
314 	result = init_pgtable(image, control_page);
315 	if (result)
316 		return result;
317 
318 	return 0;
319 }
320 
machine_kexec_cleanup(struct kimage * image)321 void machine_kexec_cleanup(struct kimage *image)
322 {
323 	free_transition_pgtable(image);
324 }
325 
326 /*
327  * Do not allocate memory (or fail in any way) in machine_kexec().
328  * We are past the point of no return, committed to rebooting now.
329  */
machine_kexec(struct kimage * image)330 void machine_kexec(struct kimage *image)
331 {
332 	unsigned long page_list[PAGES_NR];
333 	unsigned int host_mem_enc_active;
334 	int save_ftrace_enabled;
335 	void *control_page;
336 
337 	/*
338 	 * This must be done before load_segments() since if call depth tracking
339 	 * is used then GS must be valid to make any function calls.
340 	 */
341 	host_mem_enc_active = cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT);
342 
343 #ifdef CONFIG_KEXEC_JUMP
344 	if (image->preserve_context)
345 		save_processor_state();
346 #endif
347 
348 	save_ftrace_enabled = __ftrace_enabled_save();
349 
350 	/* Interrupts aren't acceptable while we reboot */
351 	local_irq_disable();
352 	hw_breakpoint_disable();
353 	cet_disable();
354 
355 	if (image->preserve_context) {
356 #ifdef CONFIG_X86_IO_APIC
357 		/*
358 		 * We need to put APICs in legacy mode so that we can
359 		 * get timer interrupts in second kernel. kexec/kdump
360 		 * paths already have calls to restore_boot_irq_mode()
361 		 * in one form or other. kexec jump path also need one.
362 		 */
363 		clear_IO_APIC();
364 		restore_boot_irq_mode();
365 #endif
366 	}
367 
368 	control_page = page_address(image->control_code_page);
369 	__memcpy(control_page, relocate_kernel, KEXEC_CONTROL_CODE_MAX_SIZE);
370 
371 	page_list[PA_CONTROL_PAGE] = virt_to_phys(control_page);
372 	page_list[VA_CONTROL_PAGE] = (unsigned long)control_page;
373 	page_list[PA_TABLE_PAGE] = (unsigned long)__pa(image->arch.pgd);
374 
375 	if (image->type == KEXEC_TYPE_DEFAULT)
376 		page_list[PA_SWAP_PAGE] = (page_to_pfn(image->swap_page)
377 						<< PAGE_SHIFT);
378 
379 	/*
380 	 * The segment registers are funny things, they have both a
381 	 * visible and an invisible part.  Whenever the visible part is
382 	 * set to a specific selector, the invisible part is loaded
383 	 * with from a table in memory.  At no other time is the
384 	 * descriptor table in memory accessed.
385 	 *
386 	 * I take advantage of this here by force loading the
387 	 * segments, before I zap the gdt with an invalid value.
388 	 */
389 	load_segments();
390 	/*
391 	 * The gdt & idt are now invalid.
392 	 * If you want to load them you must set up your own idt & gdt.
393 	 */
394 	native_idt_invalidate();
395 	native_gdt_invalidate();
396 
397 	/* now call it */
398 	image->start = relocate_kernel((unsigned long)image->head,
399 				       (unsigned long)page_list,
400 				       image->start,
401 				       image->preserve_context,
402 				       host_mem_enc_active);
403 
404 #ifdef CONFIG_KEXEC_JUMP
405 	if (image->preserve_context)
406 		restore_processor_state();
407 #endif
408 
409 	__ftrace_enabled_restore(save_ftrace_enabled);
410 }
411 
412 /* arch-dependent functionality related to kexec file-based syscall */
413 
414 #ifdef CONFIG_KEXEC_FILE
415 /*
416  * Apply purgatory relocations.
417  *
418  * @pi:		Purgatory to be relocated.
419  * @section:	Section relocations applying to.
420  * @relsec:	Section containing RELAs.
421  * @symtabsec:	Corresponding symtab.
422  *
423  * TODO: Some of the code belongs to generic code. Move that in kexec.c.
424  */
arch_kexec_apply_relocations_add(struct purgatory_info * pi,Elf_Shdr * section,const Elf_Shdr * relsec,const Elf_Shdr * symtabsec)425 int arch_kexec_apply_relocations_add(struct purgatory_info *pi,
426 				     Elf_Shdr *section, const Elf_Shdr *relsec,
427 				     const Elf_Shdr *symtabsec)
428 {
429 	unsigned int i;
430 	Elf64_Rela *rel;
431 	Elf64_Sym *sym;
432 	void *location;
433 	unsigned long address, sec_base, value;
434 	const char *strtab, *name, *shstrtab;
435 	const Elf_Shdr *sechdrs;
436 
437 	/* String & section header string table */
438 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
439 	strtab = (char *)pi->ehdr + sechdrs[symtabsec->sh_link].sh_offset;
440 	shstrtab = (char *)pi->ehdr + sechdrs[pi->ehdr->e_shstrndx].sh_offset;
441 
442 	rel = (void *)pi->ehdr + relsec->sh_offset;
443 
444 	pr_debug("Applying relocate section %s to %u\n",
445 		 shstrtab + relsec->sh_name, relsec->sh_info);
446 
447 	for (i = 0; i < relsec->sh_size / sizeof(*rel); i++) {
448 
449 		/*
450 		 * rel[i].r_offset contains byte offset from beginning
451 		 * of section to the storage unit affected.
452 		 *
453 		 * This is location to update. This is temporary buffer
454 		 * where section is currently loaded. This will finally be
455 		 * loaded to a different address later, pointed to by
456 		 * ->sh_addr. kexec takes care of moving it
457 		 *  (kexec_load_segment()).
458 		 */
459 		location = pi->purgatory_buf;
460 		location += section->sh_offset;
461 		location += rel[i].r_offset;
462 
463 		/* Final address of the location */
464 		address = section->sh_addr + rel[i].r_offset;
465 
466 		/*
467 		 * rel[i].r_info contains information about symbol table index
468 		 * w.r.t which relocation must be made and type of relocation
469 		 * to apply. ELF64_R_SYM() and ELF64_R_TYPE() macros get
470 		 * these respectively.
471 		 */
472 		sym = (void *)pi->ehdr + symtabsec->sh_offset;
473 		sym += ELF64_R_SYM(rel[i].r_info);
474 
475 		if (sym->st_name)
476 			name = strtab + sym->st_name;
477 		else
478 			name = shstrtab + sechdrs[sym->st_shndx].sh_name;
479 
480 		pr_debug("Symbol: %s info: %02x shndx: %02x value=%llx size: %llx\n",
481 			 name, sym->st_info, sym->st_shndx, sym->st_value,
482 			 sym->st_size);
483 
484 		if (sym->st_shndx == SHN_UNDEF) {
485 			pr_err("Undefined symbol: %s\n", name);
486 			return -ENOEXEC;
487 		}
488 
489 		if (sym->st_shndx == SHN_COMMON) {
490 			pr_err("symbol '%s' in common section\n", name);
491 			return -ENOEXEC;
492 		}
493 
494 		if (sym->st_shndx == SHN_ABS)
495 			sec_base = 0;
496 		else if (sym->st_shndx >= pi->ehdr->e_shnum) {
497 			pr_err("Invalid section %d for symbol %s\n",
498 			       sym->st_shndx, name);
499 			return -ENOEXEC;
500 		} else
501 			sec_base = pi->sechdrs[sym->st_shndx].sh_addr;
502 
503 		value = sym->st_value;
504 		value += sec_base;
505 		value += rel[i].r_addend;
506 
507 		switch (ELF64_R_TYPE(rel[i].r_info)) {
508 		case R_X86_64_NONE:
509 			break;
510 		case R_X86_64_64:
511 			*(u64 *)location = value;
512 			break;
513 		case R_X86_64_32:
514 			*(u32 *)location = value;
515 			if (value != *(u32 *)location)
516 				goto overflow;
517 			break;
518 		case R_X86_64_32S:
519 			*(s32 *)location = value;
520 			if ((s64)value != *(s32 *)location)
521 				goto overflow;
522 			break;
523 		case R_X86_64_PC32:
524 		case R_X86_64_PLT32:
525 			value -= (u64)address;
526 			*(u32 *)location = value;
527 			break;
528 		default:
529 			pr_err("Unknown rela relocation: %llu\n",
530 			       ELF64_R_TYPE(rel[i].r_info));
531 			return -ENOEXEC;
532 		}
533 	}
534 	return 0;
535 
536 overflow:
537 	pr_err("Overflow in relocation type %d value 0x%lx\n",
538 	       (int)ELF64_R_TYPE(rel[i].r_info), value);
539 	return -ENOEXEC;
540 }
541 
arch_kimage_file_post_load_cleanup(struct kimage * image)542 int arch_kimage_file_post_load_cleanup(struct kimage *image)
543 {
544 	vfree(image->elf_headers);
545 	image->elf_headers = NULL;
546 	image->elf_headers_sz = 0;
547 
548 	return kexec_image_post_load_cleanup_default(image);
549 }
550 #endif /* CONFIG_KEXEC_FILE */
551 
552 static int
kexec_mark_range(unsigned long start,unsigned long end,bool protect)553 kexec_mark_range(unsigned long start, unsigned long end, bool protect)
554 {
555 	struct page *page;
556 	unsigned int nr_pages;
557 
558 	/*
559 	 * For physical range: [start, end]. We must skip the unassigned
560 	 * crashk resource with zero-valued "end" member.
561 	 */
562 	if (!end || start > end)
563 		return 0;
564 
565 	page = pfn_to_page(start >> PAGE_SHIFT);
566 	nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
567 	if (protect)
568 		return set_pages_ro(page, nr_pages);
569 	else
570 		return set_pages_rw(page, nr_pages);
571 }
572 
kexec_mark_crashkres(bool protect)573 static void kexec_mark_crashkres(bool protect)
574 {
575 	unsigned long control;
576 
577 	kexec_mark_range(crashk_low_res.start, crashk_low_res.end, protect);
578 
579 	/* Don't touch the control code page used in crash_kexec().*/
580 	control = PFN_PHYS(page_to_pfn(kexec_crash_image->control_code_page));
581 	kexec_mark_range(crashk_res.start, control - 1, protect);
582 	control += KEXEC_CONTROL_PAGE_SIZE;
583 	kexec_mark_range(control, crashk_res.end, protect);
584 }
585 
arch_kexec_protect_crashkres(void)586 void arch_kexec_protect_crashkres(void)
587 {
588 	kexec_mark_crashkres(true);
589 }
590 
arch_kexec_unprotect_crashkres(void)591 void arch_kexec_unprotect_crashkres(void)
592 {
593 	kexec_mark_crashkres(false);
594 }
595 
596 /*
597  * During a traditional boot under SME, SME will encrypt the kernel,
598  * so the SME kexec kernel also needs to be un-encrypted in order to
599  * replicate a normal SME boot.
600  *
601  * During a traditional boot under SEV, the kernel has already been
602  * loaded encrypted, so the SEV kexec kernel needs to be encrypted in
603  * order to replicate a normal SEV boot.
604  */
arch_kexec_post_alloc_pages(void * vaddr,unsigned int pages,gfp_t gfp)605 int arch_kexec_post_alloc_pages(void *vaddr, unsigned int pages, gfp_t gfp)
606 {
607 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
608 		return 0;
609 
610 	/*
611 	 * If host memory encryption is active we need to be sure that kexec
612 	 * pages are not encrypted because when we boot to the new kernel the
613 	 * pages won't be accessed encrypted (initially).
614 	 */
615 	return set_memory_decrypted((unsigned long)vaddr, pages);
616 }
617 
arch_kexec_pre_free_pages(void * vaddr,unsigned int pages)618 void arch_kexec_pre_free_pages(void *vaddr, unsigned int pages)
619 {
620 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
621 		return;
622 
623 	/*
624 	 * If host memory encryption is active we need to reset the pages back
625 	 * to being an encrypted mapping before freeing them.
626 	 */
627 	set_memory_encrypted((unsigned long)vaddr, pages);
628 }
629