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 
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
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
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
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 
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 
152 static int init_transition_pgtable(struct kimage *image, pgd_t *pgd)
153 {
154 	pgprot_t prot = PAGE_KERNEL_EXEC_NOENC;
155 	unsigned long vaddr, paddr;
156 	int result = -ENOMEM;
157 	p4d_t *p4d;
158 	pud_t *pud;
159 	pmd_t *pmd;
160 	pte_t *pte;
161 
162 	vaddr = (unsigned long)relocate_kernel;
163 	paddr = __pa(page_address(image->control_code_page)+PAGE_SIZE);
164 	pgd += pgd_index(vaddr);
165 	if (!pgd_present(*pgd)) {
166 		p4d = (p4d_t *)get_zeroed_page(GFP_KERNEL);
167 		if (!p4d)
168 			goto err;
169 		image->arch.p4d = p4d;
170 		set_pgd(pgd, __pgd(__pa(p4d) | _KERNPG_TABLE));
171 	}
172 	p4d = p4d_offset(pgd, vaddr);
173 	if (!p4d_present(*p4d)) {
174 		pud = (pud_t *)get_zeroed_page(GFP_KERNEL);
175 		if (!pud)
176 			goto err;
177 		image->arch.pud = pud;
178 		set_p4d(p4d, __p4d(__pa(pud) | _KERNPG_TABLE));
179 	}
180 	pud = pud_offset(p4d, vaddr);
181 	if (!pud_present(*pud)) {
182 		pmd = (pmd_t *)get_zeroed_page(GFP_KERNEL);
183 		if (!pmd)
184 			goto err;
185 		image->arch.pmd = pmd;
186 		set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE));
187 	}
188 	pmd = pmd_offset(pud, vaddr);
189 	if (!pmd_present(*pmd)) {
190 		pte = (pte_t *)get_zeroed_page(GFP_KERNEL);
191 		if (!pte)
192 			goto err;
193 		image->arch.pte = pte;
194 		set_pmd(pmd, __pmd(__pa(pte) | _KERNPG_TABLE));
195 	}
196 	pte = pte_offset_kernel(pmd, vaddr);
197 
198 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT))
199 		prot = PAGE_KERNEL_EXEC;
200 
201 	set_pte(pte, pfn_pte(paddr >> PAGE_SHIFT, prot));
202 	return 0;
203 err:
204 	return result;
205 }
206 
207 static void *alloc_pgt_page(void *data)
208 {
209 	struct kimage *image = (struct kimage *)data;
210 	struct page *page;
211 	void *p = NULL;
212 
213 	page = kimage_alloc_control_pages(image, 0);
214 	if (page) {
215 		p = page_address(page);
216 		clear_page(p);
217 	}
218 
219 	return p;
220 }
221 
222 static int init_pgtable(struct kimage *image, unsigned long start_pgtable)
223 {
224 	struct x86_mapping_info info = {
225 		.alloc_pgt_page	= alloc_pgt_page,
226 		.context	= image,
227 		.page_flag	= __PAGE_KERNEL_LARGE_EXEC,
228 		.kernpg_flag	= _KERNPG_TABLE_NOENC,
229 	};
230 	unsigned long mstart, mend;
231 	pgd_t *level4p;
232 	int result;
233 	int i;
234 
235 	level4p = (pgd_t *)__va(start_pgtable);
236 	clear_page(level4p);
237 
238 	if (cc_platform_has(CC_ATTR_GUEST_MEM_ENCRYPT)) {
239 		info.page_flag   |= _PAGE_ENC;
240 		info.kernpg_flag |= _PAGE_ENC;
241 	}
242 
243 	if (direct_gbpages)
244 		info.direct_gbpages = true;
245 
246 	for (i = 0; i < nr_pfn_mapped; i++) {
247 		mstart = pfn_mapped[i].start << PAGE_SHIFT;
248 		mend   = pfn_mapped[i].end << PAGE_SHIFT;
249 
250 		result = kernel_ident_mapping_init(&info,
251 						 level4p, mstart, mend);
252 		if (result)
253 			return result;
254 	}
255 
256 	/*
257 	 * segments's mem ranges could be outside 0 ~ max_pfn,
258 	 * for example when jump back to original kernel from kexeced kernel.
259 	 * or first kernel is booted with user mem map, and second kernel
260 	 * could be loaded out of that range.
261 	 */
262 	for (i = 0; i < image->nr_segments; i++) {
263 		mstart = image->segment[i].mem;
264 		mend   = mstart + image->segment[i].memsz;
265 
266 		result = kernel_ident_mapping_init(&info,
267 						 level4p, mstart, mend);
268 
269 		if (result)
270 			return result;
271 	}
272 
273 	/*
274 	 * Prepare EFI systab and ACPI tables for kexec kernel since they are
275 	 * not covered by pfn_mapped.
276 	 */
277 	result = map_efi_systab(&info, level4p);
278 	if (result)
279 		return result;
280 
281 	result = map_acpi_tables(&info, level4p);
282 	if (result)
283 		return result;
284 
285 	return init_transition_pgtable(image, level4p);
286 }
287 
288 static void load_segments(void)
289 {
290 	__asm__ __volatile__ (
291 		"\tmovl %0,%%ds\n"
292 		"\tmovl %0,%%es\n"
293 		"\tmovl %0,%%ss\n"
294 		"\tmovl %0,%%fs\n"
295 		"\tmovl %0,%%gs\n"
296 		: : "a" (__KERNEL_DS) : "memory"
297 		);
298 }
299 
300 int machine_kexec_prepare(struct kimage *image)
301 {
302 	unsigned long start_pgtable;
303 	int result;
304 
305 	/* Calculate the offsets */
306 	start_pgtable = page_to_pfn(image->control_code_page) << PAGE_SHIFT;
307 
308 	/* Setup the identity mapped 64bit page table */
309 	result = init_pgtable(image, start_pgtable);
310 	if (result)
311 		return result;
312 
313 	return 0;
314 }
315 
316 void machine_kexec_cleanup(struct kimage *image)
317 {
318 	free_transition_pgtable(image);
319 }
320 
321 /*
322  * Do not allocate memory (or fail in any way) in machine_kexec().
323  * We are past the point of no return, committed to rebooting now.
324  */
325 void machine_kexec(struct kimage *image)
326 {
327 	unsigned long page_list[PAGES_NR];
328 	unsigned int host_mem_enc_active;
329 	int save_ftrace_enabled;
330 	void *control_page;
331 
332 	/*
333 	 * This must be done before load_segments() since if call depth tracking
334 	 * is used then GS must be valid to make any function calls.
335 	 */
336 	host_mem_enc_active = cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT);
337 
338 #ifdef CONFIG_KEXEC_JUMP
339 	if (image->preserve_context)
340 		save_processor_state();
341 #endif
342 
343 	save_ftrace_enabled = __ftrace_enabled_save();
344 
345 	/* Interrupts aren't acceptable while we reboot */
346 	local_irq_disable();
347 	hw_breakpoint_disable();
348 	cet_disable();
349 
350 	if (image->preserve_context) {
351 #ifdef CONFIG_X86_IO_APIC
352 		/*
353 		 * We need to put APICs in legacy mode so that we can
354 		 * get timer interrupts in second kernel. kexec/kdump
355 		 * paths already have calls to restore_boot_irq_mode()
356 		 * in one form or other. kexec jump path also need one.
357 		 */
358 		clear_IO_APIC();
359 		restore_boot_irq_mode();
360 #endif
361 	}
362 
363 	control_page = page_address(image->control_code_page) + PAGE_SIZE;
364 	__memcpy(control_page, relocate_kernel, KEXEC_CONTROL_CODE_MAX_SIZE);
365 
366 	page_list[PA_CONTROL_PAGE] = virt_to_phys(control_page);
367 	page_list[VA_CONTROL_PAGE] = (unsigned long)control_page;
368 	page_list[PA_TABLE_PAGE] =
369 	  (unsigned long)__pa(page_address(image->control_code_page));
370 
371 	if (image->type == KEXEC_TYPE_DEFAULT)
372 		page_list[PA_SWAP_PAGE] = (page_to_pfn(image->swap_page)
373 						<< PAGE_SHIFT);
374 
375 	/*
376 	 * The segment registers are funny things, they have both a
377 	 * visible and an invisible part.  Whenever the visible part is
378 	 * set to a specific selector, the invisible part is loaded
379 	 * with from a table in memory.  At no other time is the
380 	 * descriptor table in memory accessed.
381 	 *
382 	 * I take advantage of this here by force loading the
383 	 * segments, before I zap the gdt with an invalid value.
384 	 */
385 	load_segments();
386 	/*
387 	 * The gdt & idt are now invalid.
388 	 * If you want to load them you must set up your own idt & gdt.
389 	 */
390 	native_idt_invalidate();
391 	native_gdt_invalidate();
392 
393 	/* now call it */
394 	image->start = relocate_kernel((unsigned long)image->head,
395 				       (unsigned long)page_list,
396 				       image->start,
397 				       image->preserve_context,
398 				       host_mem_enc_active);
399 
400 #ifdef CONFIG_KEXEC_JUMP
401 	if (image->preserve_context)
402 		restore_processor_state();
403 #endif
404 
405 	__ftrace_enabled_restore(save_ftrace_enabled);
406 }
407 
408 /* arch-dependent functionality related to kexec file-based syscall */
409 
410 #ifdef CONFIG_KEXEC_FILE
411 /*
412  * Apply purgatory relocations.
413  *
414  * @pi:		Purgatory to be relocated.
415  * @section:	Section relocations applying to.
416  * @relsec:	Section containing RELAs.
417  * @symtabsec:	Corresponding symtab.
418  *
419  * TODO: Some of the code belongs to generic code. Move that in kexec.c.
420  */
421 int arch_kexec_apply_relocations_add(struct purgatory_info *pi,
422 				     Elf_Shdr *section, const Elf_Shdr *relsec,
423 				     const Elf_Shdr *symtabsec)
424 {
425 	unsigned int i;
426 	Elf64_Rela *rel;
427 	Elf64_Sym *sym;
428 	void *location;
429 	unsigned long address, sec_base, value;
430 	const char *strtab, *name, *shstrtab;
431 	const Elf_Shdr *sechdrs;
432 
433 	/* String & section header string table */
434 	sechdrs = (void *)pi->ehdr + pi->ehdr->e_shoff;
435 	strtab = (char *)pi->ehdr + sechdrs[symtabsec->sh_link].sh_offset;
436 	shstrtab = (char *)pi->ehdr + sechdrs[pi->ehdr->e_shstrndx].sh_offset;
437 
438 	rel = (void *)pi->ehdr + relsec->sh_offset;
439 
440 	pr_debug("Applying relocate section %s to %u\n",
441 		 shstrtab + relsec->sh_name, relsec->sh_info);
442 
443 	for (i = 0; i < relsec->sh_size / sizeof(*rel); i++) {
444 
445 		/*
446 		 * rel[i].r_offset contains byte offset from beginning
447 		 * of section to the storage unit affected.
448 		 *
449 		 * This is location to update. This is temporary buffer
450 		 * where section is currently loaded. This will finally be
451 		 * loaded to a different address later, pointed to by
452 		 * ->sh_addr. kexec takes care of moving it
453 		 *  (kexec_load_segment()).
454 		 */
455 		location = pi->purgatory_buf;
456 		location += section->sh_offset;
457 		location += rel[i].r_offset;
458 
459 		/* Final address of the location */
460 		address = section->sh_addr + rel[i].r_offset;
461 
462 		/*
463 		 * rel[i].r_info contains information about symbol table index
464 		 * w.r.t which relocation must be made and type of relocation
465 		 * to apply. ELF64_R_SYM() and ELF64_R_TYPE() macros get
466 		 * these respectively.
467 		 */
468 		sym = (void *)pi->ehdr + symtabsec->sh_offset;
469 		sym += ELF64_R_SYM(rel[i].r_info);
470 
471 		if (sym->st_name)
472 			name = strtab + sym->st_name;
473 		else
474 			name = shstrtab + sechdrs[sym->st_shndx].sh_name;
475 
476 		pr_debug("Symbol: %s info: %02x shndx: %02x value=%llx size: %llx\n",
477 			 name, sym->st_info, sym->st_shndx, sym->st_value,
478 			 sym->st_size);
479 
480 		if (sym->st_shndx == SHN_UNDEF) {
481 			pr_err("Undefined symbol: %s\n", name);
482 			return -ENOEXEC;
483 		}
484 
485 		if (sym->st_shndx == SHN_COMMON) {
486 			pr_err("symbol '%s' in common section\n", name);
487 			return -ENOEXEC;
488 		}
489 
490 		if (sym->st_shndx == SHN_ABS)
491 			sec_base = 0;
492 		else if (sym->st_shndx >= pi->ehdr->e_shnum) {
493 			pr_err("Invalid section %d for symbol %s\n",
494 			       sym->st_shndx, name);
495 			return -ENOEXEC;
496 		} else
497 			sec_base = pi->sechdrs[sym->st_shndx].sh_addr;
498 
499 		value = sym->st_value;
500 		value += sec_base;
501 		value += rel[i].r_addend;
502 
503 		switch (ELF64_R_TYPE(rel[i].r_info)) {
504 		case R_X86_64_NONE:
505 			break;
506 		case R_X86_64_64:
507 			*(u64 *)location = value;
508 			break;
509 		case R_X86_64_32:
510 			*(u32 *)location = value;
511 			if (value != *(u32 *)location)
512 				goto overflow;
513 			break;
514 		case R_X86_64_32S:
515 			*(s32 *)location = value;
516 			if ((s64)value != *(s32 *)location)
517 				goto overflow;
518 			break;
519 		case R_X86_64_PC32:
520 		case R_X86_64_PLT32:
521 			value -= (u64)address;
522 			*(u32 *)location = value;
523 			break;
524 		default:
525 			pr_err("Unknown rela relocation: %llu\n",
526 			       ELF64_R_TYPE(rel[i].r_info));
527 			return -ENOEXEC;
528 		}
529 	}
530 	return 0;
531 
532 overflow:
533 	pr_err("Overflow in relocation type %d value 0x%lx\n",
534 	       (int)ELF64_R_TYPE(rel[i].r_info), value);
535 	return -ENOEXEC;
536 }
537 
538 int arch_kimage_file_post_load_cleanup(struct kimage *image)
539 {
540 	vfree(image->elf_headers);
541 	image->elf_headers = NULL;
542 	image->elf_headers_sz = 0;
543 
544 	return kexec_image_post_load_cleanup_default(image);
545 }
546 #endif /* CONFIG_KEXEC_FILE */
547 
548 static int
549 kexec_mark_range(unsigned long start, unsigned long end, bool protect)
550 {
551 	struct page *page;
552 	unsigned int nr_pages;
553 
554 	/*
555 	 * For physical range: [start, end]. We must skip the unassigned
556 	 * crashk resource with zero-valued "end" member.
557 	 */
558 	if (!end || start > end)
559 		return 0;
560 
561 	page = pfn_to_page(start >> PAGE_SHIFT);
562 	nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
563 	if (protect)
564 		return set_pages_ro(page, nr_pages);
565 	else
566 		return set_pages_rw(page, nr_pages);
567 }
568 
569 static void kexec_mark_crashkres(bool protect)
570 {
571 	unsigned long control;
572 
573 	kexec_mark_range(crashk_low_res.start, crashk_low_res.end, protect);
574 
575 	/* Don't touch the control code page used in crash_kexec().*/
576 	control = PFN_PHYS(page_to_pfn(kexec_crash_image->control_code_page));
577 	/* Control code page is located in the 2nd page. */
578 	kexec_mark_range(crashk_res.start, control + PAGE_SIZE - 1, protect);
579 	control += KEXEC_CONTROL_PAGE_SIZE;
580 	kexec_mark_range(control, crashk_res.end, protect);
581 }
582 
583 void arch_kexec_protect_crashkres(void)
584 {
585 	kexec_mark_crashkres(true);
586 }
587 
588 void arch_kexec_unprotect_crashkres(void)
589 {
590 	kexec_mark_crashkres(false);
591 }
592 
593 /*
594  * During a traditional boot under SME, SME will encrypt the kernel,
595  * so the SME kexec kernel also needs to be un-encrypted in order to
596  * replicate a normal SME boot.
597  *
598  * During a traditional boot under SEV, the kernel has already been
599  * loaded encrypted, so the SEV kexec kernel needs to be encrypted in
600  * order to replicate a normal SEV boot.
601  */
602 int arch_kexec_post_alloc_pages(void *vaddr, unsigned int pages, gfp_t gfp)
603 {
604 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
605 		return 0;
606 
607 	/*
608 	 * If host memory encryption is active we need to be sure that kexec
609 	 * pages are not encrypted because when we boot to the new kernel the
610 	 * pages won't be accessed encrypted (initially).
611 	 */
612 	return set_memory_decrypted((unsigned long)vaddr, pages);
613 }
614 
615 void arch_kexec_pre_free_pages(void *vaddr, unsigned int pages)
616 {
617 	if (!cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT))
618 		return;
619 
620 	/*
621 	 * If host memory encryption is active we need to reset the pages back
622 	 * to being an encrypted mapping before freeing them.
623 	 */
624 	set_memory_encrypted((unsigned long)vaddr, pages);
625 }
626