xref: /linux/drivers/firmware/efi/libstub/x86-stub.c (revision 40082fb4015712084df977bb8e7f0aa681a56a1a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /* -----------------------------------------------------------------------
4  *
5  *   Copyright 2011 Intel Corporation; author Matt Fleming
6  *
7  * ----------------------------------------------------------------------- */
8 
9 #include <linux/efi.h>
10 #include <linux/pci.h>
11 #include <linux/stddef.h>
12 
13 #include <asm/cpuid/api.h>
14 #include <asm/efi.h>
15 #include <asm/e820/types.h>
16 #include <asm/setup.h>
17 #include <asm/desc.h>
18 #include <asm/boot.h>
19 #include <asm/kaslr.h>
20 #include <asm/sev.h>
21 #include <asm/shared/tdx.h>
22 
23 #include "efistub.h"
24 #include "x86-stub.h"
25 
26 extern char _bss[], _ebss[];
27 
28 const efi_system_table_t *efi_system_table;
29 const efi_dxe_services_table_t *efi_dxe_table;
30 static efi_loaded_image_t *image = NULL;
31 static efi_memory_attribute_protocol_t *memattr;
32 
33 typedef union sev_memory_acceptance_protocol sev_memory_acceptance_protocol_t;
34 union sev_memory_acceptance_protocol {
35 	struct {
36 		efi_status_t (__efiapi * allow_unaccepted_memory)(
37 			sev_memory_acceptance_protocol_t *);
38 	};
39 	struct {
40 		u32 allow_unaccepted_memory;
41 	} mixed_mode;
42 };
43 
44 static efi_status_t
preserve_pci_rom_image(efi_pci_io_protocol_t * pci,struct pci_setup_rom ** __rom)45 preserve_pci_rom_image(efi_pci_io_protocol_t *pci, struct pci_setup_rom **__rom)
46 {
47 	struct pci_setup_rom *rom __free(efi_pool) = NULL;
48 	efi_status_t status;
49 	unsigned long size;
50 	uint64_t romsize;
51 	void *romimage;
52 
53 	/*
54 	 * Some firmware images contain EFI function pointers at the place where
55 	 * the romimage and romsize fields are supposed to be. Typically the EFI
56 	 * code is mapped at high addresses, translating to an unrealistically
57 	 * large romsize. The UEFI spec limits the size of option ROMs to 16
58 	 * MiB so we reject any ROMs over 16 MiB in size to catch this.
59 	 */
60 	romimage = efi_table_attr(pci, romimage);
61 	romsize = efi_table_attr(pci, romsize);
62 	if (!romimage || !romsize || romsize > SZ_16M)
63 		return EFI_INVALID_PARAMETER;
64 
65 	size = romsize + sizeof(*rom);
66 
67 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
68 			     (void **)&rom);
69 	if (status != EFI_SUCCESS) {
70 		efi_err("Failed to allocate memory for 'rom'\n");
71 		return status;
72 	}
73 
74 	memset(rom, 0, sizeof(*rom));
75 
76 	rom->data.type	= SETUP_PCI;
77 	rom->data.len	= size - sizeof(struct setup_data);
78 	rom->data.next	= 0;
79 	rom->pcilen	= romsize;
80 
81 	status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16,
82 				PCI_VENDOR_ID, 1, &rom->vendor);
83 
84 	if (status != EFI_SUCCESS) {
85 		efi_err("Failed to read rom->vendor\n");
86 		return status;
87 	}
88 
89 	status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16,
90 				PCI_DEVICE_ID, 1, &rom->devid);
91 
92 	if (status != EFI_SUCCESS) {
93 		efi_err("Failed to read rom->devid\n");
94 		return status;
95 	}
96 
97 	status = efi_call_proto(pci, get_location, &rom->segment, &rom->bus,
98 				&rom->device, &rom->function);
99 
100 	if (status != EFI_SUCCESS)
101 		return status;
102 
103 	memcpy(rom->romdata, romimage, romsize);
104 	*__rom = no_free_ptr(rom);
105 	return EFI_SUCCESS;
106 }
107 
108 /*
109  * There's no way to return an informative status from this function,
110  * because any analysis (and printing of error messages) needs to be
111  * done directly at the EFI function call-site.
112  *
113  * For example, EFI_INVALID_PARAMETER could indicate a bug or maybe we
114  * just didn't find any PCI devices, but there's no way to tell outside
115  * the context of the call.
116  */
setup_efi_pci(struct boot_params * params)117 static void setup_efi_pci(struct boot_params *params)
118 {
119 	efi_status_t status;
120 	efi_handle_t *pci_handle __free(efi_pool) = NULL;
121 	efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID;
122 	struct setup_data *data;
123 	unsigned long num;
124 	efi_handle_t h;
125 
126 	status = efi_bs_call(locate_handle_buffer, EFI_LOCATE_BY_PROTOCOL,
127 			     &pci_proto, NULL, &num, &pci_handle);
128 	if (status != EFI_SUCCESS)
129 		return;
130 
131 	data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
132 
133 	while (data && data->next)
134 		data = (struct setup_data *)(unsigned long)data->next;
135 
136 	for_each_efi_handle(h, pci_handle, num) {
137 		efi_pci_io_protocol_t *pci = NULL;
138 		struct pci_setup_rom *rom;
139 
140 		status = efi_bs_call(handle_protocol, h, &pci_proto,
141 				     (void **)&pci);
142 		if (status != EFI_SUCCESS || !pci)
143 			continue;
144 
145 		status = preserve_pci_rom_image(pci, &rom);
146 		if (status != EFI_SUCCESS)
147 			continue;
148 
149 		if (data)
150 			data->next = (unsigned long)rom;
151 		else
152 			params->hdr.setup_data = (unsigned long)rom;
153 
154 		data = (struct setup_data *)rom;
155 	}
156 }
157 
retrieve_apple_device_properties(struct boot_params * boot_params)158 static void retrieve_apple_device_properties(struct boot_params *boot_params)
159 {
160 	efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID;
161 	struct setup_data *data, *new;
162 	efi_status_t status;
163 	u32 size = 0;
164 	apple_properties_protocol_t *p;
165 
166 	status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&p);
167 	if (status != EFI_SUCCESS)
168 		return;
169 
170 	if (efi_table_attr(p, version) != 0x10000) {
171 		efi_err("Unsupported properties proto version\n");
172 		return;
173 	}
174 
175 	efi_call_proto(p, get_all, NULL, &size);
176 	if (!size)
177 		return;
178 
179 	do {
180 		status = efi_bs_call(allocate_pool, EFI_LOADER_DATA,
181 				     size + sizeof(struct setup_data),
182 				     (void **)&new);
183 		if (status != EFI_SUCCESS) {
184 			efi_err("Failed to allocate memory for 'properties'\n");
185 			return;
186 		}
187 
188 		status = efi_call_proto(p, get_all, new->data, &size);
189 
190 		if (status == EFI_BUFFER_TOO_SMALL)
191 			efi_bs_call(free_pool, new);
192 	} while (status == EFI_BUFFER_TOO_SMALL);
193 
194 	new->type = SETUP_APPLE_PROPERTIES;
195 	new->len  = size;
196 	new->next = 0;
197 
198 	data = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
199 	if (!data) {
200 		boot_params->hdr.setup_data = (unsigned long)new;
201 	} else {
202 		while (data->next)
203 			data = (struct setup_data *)(unsigned long)data->next;
204 		data->next = (unsigned long)new;
205 	}
206 }
207 
208 struct smbios_entry_point {
209 	u8	anchor[4];
210 	u8	ep_checksum;
211 	u8	ep_length;
212 	u8	major_version;
213 	u8	minor_version;
214 	u16	max_size_entry;
215 	u8	ep_rev;
216 	u8	reserved[5];
217 
218 	struct __packed {
219 		u8	anchor[5];
220 		u8	checksum;
221 		u16	st_length;
222 		u32	st_address;
223 		u16	number_of_entries;
224 		u8	bcd_rev;
225 	} intm;
226 };
227 
verify_ep_checksum(const void * ptr,int length)228 static bool verify_ep_checksum(const void *ptr, int length)
229 {
230 	u8 sum = 0;
231 
232 	for (int i = 0; i < length; i++)
233 		sum += ((u8 *)ptr)[i];
234 
235 	return sum == 0;
236 }
237 
verify_ep_integrity(const struct smbios_entry_point * ep)238 static bool verify_ep_integrity(const struct smbios_entry_point *ep)
239 {
240 	if (memcmp(ep->anchor, "_SM_", sizeof(ep->anchor)) != 0)
241 		return false;
242 
243 	if (memcmp(ep->intm.anchor, "_DMI_", sizeof(ep->intm.anchor)) != 0)
244 		return false;
245 
246 	if (!verify_ep_checksum(ep, ep->ep_length) ||
247 	    !verify_ep_checksum(&ep->intm, sizeof(ep->intm)))
248 		return false;
249 
250 	return true;
251 }
252 
search_record(void * table,u32 length,u8 type)253 static const struct efi_smbios_record *search_record(void *table, u32 length,
254 						     u8 type)
255 {
256 	const u8 *p, *end;
257 
258 	p = (u8 *)table;
259 	end = p + length;
260 
261 	while (p + sizeof(struct efi_smbios_record) < end) {
262 		const struct efi_smbios_record *hdr =
263 			(struct efi_smbios_record *)p;
264 		const u8 *next;
265 
266 		if (hdr->type == type)
267 			return hdr;
268 
269 		/* Type 127 = End-of-Table */
270 		if (hdr->type == 0x7F)
271 			return NULL;
272 
273 		/* Jumping to the unformed section */
274 		next = p + hdr->length;
275 
276 		/* Unformed section ends with 0000h */
277 		while ((next[0] != 0 || next[1] != 0) && next + 1 < end)
278 			next++;
279 
280 		next += 2;
281 		p = next;
282 	}
283 
284 	return NULL;
285 }
286 
get_table_record(u8 type)287 static const struct efi_smbios_record *get_table_record(u8 type)
288 {
289 	const struct smbios_entry_point *ep;
290 
291 	/*
292 	 * Locate the legacy 32-bit SMBIOS entrypoint in memory, and parse it
293 	 * directly. Needed by some Macs that do not implement the EFI protocol.
294 	 */
295 	ep = get_efi_config_table(SMBIOS_TABLE_GUID);
296 	if (!ep)
297 		return NULL;
298 
299 	if (!verify_ep_integrity(ep))
300 		return NULL;
301 
302 	return search_record((void *)(unsigned long)ep->intm.st_address,
303 			     ep->intm.st_length, type);
304 }
305 
apple_match_product_name(void)306 static bool apple_match_product_name(void)
307 {
308 	static const char type1_product_matches[][15] = {
309 		"MacBookPro11,3",
310 		"MacBookPro11,5",
311 		"MacBookPro13,3",
312 		"MacBookPro14,3",
313 		"MacBookPro15,1",
314 		"MacBookPro15,3",
315 		"MacBookPro16,1",
316 		"MacBookPro16,4",
317 	};
318 	const struct efi_smbios_type1_record *record;
319 	const u8 *product;
320 
321 	record = (struct efi_smbios_type1_record *)
322 			(efi_get_smbios_record(1) ?: get_table_record(1));
323 	if (!record)
324 		return false;
325 
326 	product = efi_get_smbios_string(record, product_name);
327 	if (!product)
328 		return false;
329 
330 	for (int i = 0; i < ARRAY_SIZE(type1_product_matches); i++) {
331 		if (!strcmp(product, type1_product_matches[i]))
332 			return true;
333 	}
334 
335 	return false;
336 }
337 
apple_set_os(void)338 static void apple_set_os(void)
339 {
340 	struct {
341 		unsigned long version;
342 		efi_status_t (__efiapi *set_os_version)(const char *);
343 		efi_status_t (__efiapi *set_os_vendor)(const char *);
344 	} *set_os;
345 	efi_status_t status;
346 
347 	if (!efi_is_64bit() || !apple_match_product_name())
348 		return;
349 
350 	status = efi_bs_call(locate_protocol, &APPLE_SET_OS_PROTOCOL_GUID, NULL,
351 			     (void **)&set_os);
352 	if (status != EFI_SUCCESS)
353 		return;
354 
355 	if (set_os->version >= 2) {
356 		status = set_os->set_os_vendor("Apple Inc.");
357 		if (status != EFI_SUCCESS)
358 			efi_err("Failed to set OS vendor via apple_set_os\n");
359 	}
360 
361 	if (set_os->version > 0) {
362 		/* The version being set doesn't seem to matter */
363 		status = set_os->set_os_version("Mac OS X 10.9");
364 		if (status != EFI_SUCCESS)
365 			efi_err("Failed to set OS version via apple_set_os\n");
366 	}
367 }
368 
efi_adjust_memory_range_protection(unsigned long start,unsigned long size)369 efi_status_t efi_adjust_memory_range_protection(unsigned long start,
370 						unsigned long size)
371 {
372 	efi_status_t status;
373 	efi_gcd_memory_space_desc_t desc;
374 	unsigned long end, next;
375 	unsigned long rounded_start, rounded_end;
376 	unsigned long unprotect_start, unprotect_size;
377 
378 	rounded_start = rounddown(start, EFI_PAGE_SIZE);
379 	rounded_end = roundup(start + size, EFI_PAGE_SIZE);
380 
381 	if (memattr != NULL) {
382 		status = efi_call_proto(memattr, set_memory_attributes,
383 					rounded_start,
384 					rounded_end - rounded_start,
385 					EFI_MEMORY_RO);
386 		if (status != EFI_SUCCESS) {
387 			efi_warn("Failed to set EFI_MEMORY_RO attribute\n");
388 			return status;
389 		}
390 
391 		status = efi_call_proto(memattr, clear_memory_attributes,
392 					rounded_start,
393 					rounded_end - rounded_start,
394 					EFI_MEMORY_XP);
395 		if (status != EFI_SUCCESS)
396 			efi_warn("Failed to clear EFI_MEMORY_XP attribute\n");
397 		return status;
398 	}
399 
400 	if (efi_dxe_table == NULL)
401 		return EFI_SUCCESS;
402 
403 	/*
404 	 * Don't modify memory region attributes, if they are
405 	 * already suitable, to lower the possibility to
406 	 * encounter firmware bugs.
407 	 */
408 
409 	for (end = start + size; start < end; start = next) {
410 
411 		status = efi_dxe_call(get_memory_space_descriptor, start, &desc);
412 
413 		if (status != EFI_SUCCESS)
414 			break;
415 
416 		next = desc.base_address + desc.length;
417 
418 		/*
419 		 * Only system memory and more reliable memory are suitable for
420 		 * trampoline/kernel image placement. So only those memory types
421 		 * may need to have attributes modified.
422 		 */
423 
424 		if ((desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory &&
425 		     desc.gcd_memory_type != EfiGcdMemoryTypeMoreReliable) ||
426 		    (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0)
427 			continue;
428 
429 		unprotect_start = max(rounded_start, (unsigned long)desc.base_address);
430 		unprotect_size = min(rounded_end, next) - unprotect_start;
431 
432 		status = efi_dxe_call(set_memory_space_attributes,
433 				      unprotect_start, unprotect_size,
434 				      EFI_MEMORY_WB);
435 
436 		if (status != EFI_SUCCESS) {
437 			efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n",
438 				 unprotect_start,
439 				 unprotect_start + unprotect_size,
440 				 status);
441 			break;
442 		}
443 	}
444 	return EFI_SUCCESS;
445 }
446 
setup_unaccepted_memory(void)447 static void setup_unaccepted_memory(void)
448 {
449 	efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID;
450 	sev_memory_acceptance_protocol_t *proto;
451 	efi_status_t status;
452 
453 	if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
454 		return;
455 
456 	/*
457 	 * Enable unaccepted memory before calling exit boot services in order
458 	 * for the UEFI to not accept all memory on EBS.
459 	 */
460 	status = efi_bs_call(locate_protocol, &mem_acceptance_proto, NULL,
461 			     (void **)&proto);
462 	if (status != EFI_SUCCESS)
463 		return;
464 
465 	status = efi_call_proto(proto, allow_unaccepted_memory);
466 	if (status != EFI_SUCCESS)
467 		efi_err("Memory acceptance protocol failed\n");
468 }
469 
efistub_fw_vendor(void)470 static efi_char16_t *efistub_fw_vendor(void)
471 {
472 	unsigned long vendor = efi_table_attr(efi_system_table, fw_vendor);
473 
474 	return (efi_char16_t *)vendor;
475 }
476 
477 static const efi_char16_t apple[] = L"Apple";
478 
setup_quirks(struct boot_params * boot_params)479 static void setup_quirks(struct boot_params *boot_params)
480 {
481 	if (!memcmp(efistub_fw_vendor(), apple, sizeof(apple))) {
482 		if (IS_ENABLED(CONFIG_APPLE_PROPERTIES))
483 			retrieve_apple_device_properties(boot_params);
484 
485 		apple_set_os();
486 	}
487 }
488 
setup_graphics(struct boot_params * boot_params)489 static void setup_graphics(struct boot_params *boot_params)
490 {
491 	struct screen_info *si = memset(&boot_params->screen_info, 0, sizeof(*si));
492 	struct edid_info *edid = memset(&boot_params->edid_info, 0, sizeof(*edid));
493 
494 	efi_setup_graphics(si, edid);
495 }
496 
efi_exit(efi_handle_t handle,efi_status_t status)497 static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status)
498 {
499 	efi_bs_call(exit, handle, status, 0, NULL);
500 	for(;;)
501 		asm("hlt");
502 }
503 
504 /*
505  * Because the x86 boot code expects to be passed a boot_params we
506  * need to create one ourselves (usually the bootloader would create
507  * one for us).
508  */
efi_allocate_bootparams(efi_handle_t handle,struct boot_params ** bp)509 static efi_status_t efi_allocate_bootparams(efi_handle_t handle,
510 					    struct boot_params **bp)
511 {
512 	efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID;
513 	struct boot_params *boot_params;
514 	struct setup_header *hdr;
515 	efi_status_t status;
516 	unsigned long alloc;
517 	char *cmdline_ptr;
518 
519 	status = efi_bs_call(handle_protocol, handle, &proto, (void **)&image);
520 	if (status != EFI_SUCCESS) {
521 		efi_err("Failed to get handle for LOADED_IMAGE_PROTOCOL\n");
522 		return status;
523 	}
524 
525 	status = efi_allocate_pages(PARAM_SIZE, &alloc, ULONG_MAX);
526 	if (status != EFI_SUCCESS)
527 		return status;
528 
529 	boot_params = memset((void *)alloc, 0x0, PARAM_SIZE);
530 	hdr	    = &boot_params->hdr;
531 
532 	/* Assign the setup_header fields that the kernel actually cares about */
533 	hdr->root_flags	= 1;
534 	hdr->vid_mode	= 0xffff;
535 
536 	hdr->type_of_loader = 0x21;
537 	hdr->initrd_addr_max = INT_MAX;
538 
539 	/* Convert unicode cmdline to ascii */
540 	cmdline_ptr = efi_convert_cmdline(image);
541 	if (!cmdline_ptr) {
542 		efi_free(PARAM_SIZE, alloc);
543 		return EFI_OUT_OF_RESOURCES;
544 	}
545 
546 	efi_set_u64_split((unsigned long)cmdline_ptr, &hdr->cmd_line_ptr,
547 			  &boot_params->ext_cmd_line_ptr);
548 
549 	*bp = boot_params;
550 	return EFI_SUCCESS;
551 }
552 
add_e820ext(struct boot_params * params,struct setup_data * e820ext,u32 nr_entries)553 static void add_e820ext(struct boot_params *params,
554 			struct setup_data *e820ext, u32 nr_entries)
555 {
556 	struct setup_data *data;
557 
558 	e820ext->type = SETUP_E820_EXT;
559 	e820ext->len  = nr_entries * sizeof(struct boot_e820_entry);
560 	e820ext->next = 0;
561 
562 	data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
563 
564 	while (data && data->next)
565 		data = (struct setup_data *)(unsigned long)data->next;
566 
567 	if (data)
568 		data->next = (unsigned long)e820ext;
569 	else
570 		params->hdr.setup_data = (unsigned long)e820ext;
571 }
572 
573 static efi_status_t
setup_e820(struct boot_params * params,struct setup_data * e820ext,u32 e820ext_size)574 setup_e820(struct boot_params *params, struct setup_data *e820ext, u32 e820ext_size)
575 {
576 	struct boot_e820_entry *entry = params->e820_table;
577 	struct efi_info *efi = &params->efi_info;
578 	struct boot_e820_entry *prev = NULL;
579 	u32 nr_entries;
580 	u32 nr_desc;
581 	int i;
582 
583 	nr_entries = 0;
584 	nr_desc = efi->efi_memmap_size / efi->efi_memdesc_size;
585 
586 	for (i = 0; i < nr_desc; i++) {
587 		efi_memory_desc_t *d;
588 		unsigned int e820_type = 0;
589 		unsigned long m = efi->efi_memmap;
590 
591 #ifdef CONFIG_X86_64
592 		m |= (u64)efi->efi_memmap_hi << 32;
593 #endif
594 
595 		d = efi_memdesc_ptr(m, efi->efi_memdesc_size, i);
596 		switch (d->type) {
597 		case EFI_RESERVED_TYPE:
598 		case EFI_RUNTIME_SERVICES_CODE:
599 		case EFI_RUNTIME_SERVICES_DATA:
600 		case EFI_MEMORY_MAPPED_IO:
601 		case EFI_MEMORY_MAPPED_IO_PORT_SPACE:
602 		case EFI_PAL_CODE:
603 			e820_type = E820_TYPE_RESERVED;
604 			break;
605 
606 		case EFI_UNUSABLE_MEMORY:
607 			e820_type = E820_TYPE_UNUSABLE;
608 			break;
609 
610 		case EFI_ACPI_RECLAIM_MEMORY:
611 			e820_type = E820_TYPE_ACPI;
612 			break;
613 
614 		case EFI_LOADER_CODE:
615 		case EFI_LOADER_DATA:
616 		case EFI_BOOT_SERVICES_CODE:
617 		case EFI_BOOT_SERVICES_DATA:
618 		case EFI_CONVENTIONAL_MEMORY:
619 			if (efi_soft_reserve_enabled() &&
620 			    (d->attribute & EFI_MEMORY_SP))
621 				e820_type = E820_TYPE_SOFT_RESERVED;
622 			else
623 				e820_type = E820_TYPE_RAM;
624 			break;
625 
626 		case EFI_ACPI_MEMORY_NVS:
627 			e820_type = E820_TYPE_NVS;
628 			break;
629 
630 		case EFI_PERSISTENT_MEMORY:
631 			e820_type = E820_TYPE_PMEM;
632 			break;
633 
634 		case EFI_UNACCEPTED_MEMORY:
635 			if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
636 				continue;
637 			e820_type = E820_TYPE_RAM;
638 			process_unaccepted_memory(d->phys_addr,
639 						  d->phys_addr + PAGE_SIZE * d->num_pages);
640 			break;
641 		default:
642 			continue;
643 		}
644 
645 		/* Merge adjacent mappings */
646 		if (prev && prev->type == e820_type &&
647 		    (prev->addr + prev->size) == d->phys_addr) {
648 			prev->size += d->num_pages << 12;
649 			continue;
650 		}
651 
652 		if (nr_entries == ARRAY_SIZE(params->e820_table)) {
653 			u32 need = (nr_desc - i) * sizeof(struct e820_entry) +
654 				   sizeof(struct setup_data);
655 
656 			if (!e820ext || e820ext_size < need)
657 				return EFI_BUFFER_TOO_SMALL;
658 
659 			/* boot_params map full, switch to e820 extended */
660 			entry = (struct boot_e820_entry *)e820ext->data;
661 		}
662 
663 		entry->addr = d->phys_addr;
664 		entry->size = d->num_pages << PAGE_SHIFT;
665 		entry->type = e820_type;
666 		prev = entry++;
667 		nr_entries++;
668 	}
669 
670 	if (nr_entries > ARRAY_SIZE(params->e820_table)) {
671 		u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table);
672 
673 		add_e820ext(params, e820ext, nr_e820ext);
674 		nr_entries -= nr_e820ext;
675 	}
676 
677 	params->e820_entries = (u8)nr_entries;
678 
679 	return EFI_SUCCESS;
680 }
681 
alloc_e820ext(u32 nr_desc,struct setup_data ** e820ext,u32 * e820ext_size)682 static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext,
683 				  u32 *e820ext_size)
684 {
685 	efi_status_t status;
686 	unsigned long size;
687 
688 	size = sizeof(struct setup_data) +
689 		sizeof(struct e820_entry) * nr_desc;
690 
691 	if (*e820ext) {
692 		efi_bs_call(free_pool, *e820ext);
693 		*e820ext = NULL;
694 		*e820ext_size = 0;
695 	}
696 
697 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
698 			     (void **)e820ext);
699 	if (status == EFI_SUCCESS)
700 		*e820ext_size = size;
701 
702 	return status;
703 }
704 
allocate_e820(struct boot_params * params,struct setup_data ** e820ext,u32 * e820ext_size)705 static efi_status_t allocate_e820(struct boot_params *params,
706 				  struct setup_data **e820ext,
707 				  u32 *e820ext_size)
708 {
709 	struct efi_boot_memmap *map __free(efi_pool) = NULL;
710 	efi_status_t status;
711 	__u32 nr_desc;
712 
713 	status = efi_get_memory_map(&map, false);
714 	if (status != EFI_SUCCESS)
715 		return status;
716 
717 	nr_desc = map->map_size / map->desc_size;
718 	if (nr_desc > ARRAY_SIZE(params->e820_table) - EFI_MMAP_NR_SLACK_SLOTS) {
719 		u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table) +
720 				 EFI_MMAP_NR_SLACK_SLOTS;
721 
722 		status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size);
723 		if (status != EFI_SUCCESS)
724 			return status;
725 	}
726 
727 	if (IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
728 		return allocate_unaccepted_bitmap(nr_desc, map);
729 
730 	return EFI_SUCCESS;
731 }
732 
733 struct exit_boot_struct {
734 	struct boot_params	*boot_params;
735 	struct efi_info		*efi;
736 };
737 
exit_boot_func(struct efi_boot_memmap * map,void * priv)738 static efi_status_t exit_boot_func(struct efi_boot_memmap *map,
739 				   void *priv)
740 {
741 	const char *signature;
742 	struct exit_boot_struct *p = priv;
743 
744 	signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE
745 				   : EFI32_LOADER_SIGNATURE;
746 	memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32));
747 
748 	efi_set_u64_split((unsigned long)efi_system_table,
749 			  &p->efi->efi_systab, &p->efi->efi_systab_hi);
750 	p->efi->efi_memdesc_size	= map->desc_size;
751 	p->efi->efi_memdesc_version	= map->desc_ver;
752 	efi_set_u64_split((unsigned long)map->map,
753 			  &p->efi->efi_memmap, &p->efi->efi_memmap_hi);
754 	p->efi->efi_memmap_size		= map->map_size;
755 
756 	return EFI_SUCCESS;
757 }
758 
exit_boot(struct boot_params * boot_params,void * handle)759 static efi_status_t exit_boot(struct boot_params *boot_params, void *handle)
760 {
761 	struct setup_data *e820ext = NULL;
762 	__u32 e820ext_size = 0;
763 	efi_status_t status;
764 	struct exit_boot_struct priv;
765 
766 	priv.boot_params	= boot_params;
767 	priv.efi		= &boot_params->efi_info;
768 
769 	status = allocate_e820(boot_params, &e820ext, &e820ext_size);
770 	if (status != EFI_SUCCESS)
771 		return status;
772 
773 	/* Might as well exit boot services now */
774 	status = efi_exit_boot_services(handle, &priv, exit_boot_func);
775 	if (status != EFI_SUCCESS)
776 		return status;
777 
778 	/* Historic? */
779 	boot_params->alt_mem_k	= 32 * 1024;
780 
781 	status = setup_e820(boot_params, e820ext, e820ext_size);
782 	if (status != EFI_SUCCESS)
783 		return status;
784 
785 	return EFI_SUCCESS;
786 }
787 
have_unsupported_snp_features(void)788 static bool have_unsupported_snp_features(void)
789 {
790 	u64 unsupported;
791 
792 	unsupported = snp_get_unsupported_features(sev_get_status());
793 	if (unsupported) {
794 		efi_err("Unsupported SEV-SNP features detected: 0x%llx\n",
795 			unsupported);
796 		return true;
797 	}
798 	return false;
799 }
800 
efi_get_seed(void * seed,int size)801 static void efi_get_seed(void *seed, int size)
802 {
803 	efi_get_random_bytes(size, seed);
804 
805 	/*
806 	 * This only updates seed[0] when running on 32-bit, but in that case,
807 	 * seed[1] is not used anyway, as there is no virtual KASLR on 32-bit.
808 	 */
809 	*(unsigned long *)seed ^= kaslr_get_random_long("EFI");
810 }
811 
error(char * str)812 static void error(char *str)
813 {
814 	efi_warn("Decompression failed: %s\n", str);
815 }
816 
817 static const char *cmdline_memmap_override;
818 
parse_options(const char * cmdline)819 static efi_status_t parse_options(const char *cmdline)
820 {
821 	static const char opts[][14] = {
822 		"mem=", "memmap=", "hugepages="
823 	};
824 
825 	for (int i = 0; i < ARRAY_SIZE(opts); i++) {
826 		const char *p = strstr(cmdline, opts[i]);
827 
828 		if (p == cmdline || (p > cmdline && isspace(p[-1]))) {
829 			cmdline_memmap_override = opts[i];
830 			break;
831 		}
832 	}
833 
834 	return efi_parse_options(cmdline);
835 }
836 
efi_decompress_kernel(unsigned long * kernel_entry,struct boot_params * boot_params)837 static efi_status_t efi_decompress_kernel(unsigned long *kernel_entry,
838 					  struct boot_params *boot_params)
839 {
840 	unsigned long virt_addr = LOAD_PHYSICAL_ADDR;
841 	unsigned long addr, alloc_size, entry;
842 	efi_status_t status;
843 	u32 seed[2] = {};
844 
845 	boot_params_ptr	= boot_params;
846 
847 	/* determine the required size of the allocation */
848 	alloc_size = ALIGN(max_t(unsigned long, output_len, kernel_total_size),
849 			   MIN_KERNEL_ALIGN);
850 
851 	if (IS_ENABLED(CONFIG_RANDOMIZE_BASE) && !efi_nokaslr) {
852 		u64 range = KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR - kernel_total_size;
853 		static const efi_char16_t ami[] = L"American Megatrends";
854 
855 		efi_get_seed(seed, sizeof(seed));
856 
857 		virt_addr += (range * seed[1]) >> 32;
858 		virt_addr &= ~(CONFIG_PHYSICAL_ALIGN - 1);
859 
860 		/*
861 		 * Older Dell systems with AMI UEFI firmware v2.0 may hang
862 		 * while decompressing the kernel if physical address
863 		 * randomization is enabled.
864 		 *
865 		 * https://bugzilla.kernel.org/show_bug.cgi?id=218173
866 		 */
867 		if (efi_system_table->hdr.revision <= EFI_2_00_SYSTEM_TABLE_REVISION &&
868 		    !memcmp(efistub_fw_vendor(), ami, sizeof(ami))) {
869 			efi_debug("AMI firmware v2.0 or older detected - disabling physical KASLR\n");
870 			seed[0] = 0;
871 		} else if (cmdline_memmap_override) {
872 			efi_info("%s detected on the kernel command line - disabling physical KASLR\n",
873 				 cmdline_memmap_override);
874 			seed[0] = 0;
875 		}
876 
877 		boot_params->hdr.loadflags |= KASLR_FLAG;
878 	}
879 
880 	status = efi_random_alloc(alloc_size, CONFIG_PHYSICAL_ALIGN, &addr,
881 				  seed[0], EFI_LOADER_CODE,
882 				  LOAD_PHYSICAL_ADDR,
883 				  EFI_X86_KERNEL_ALLOC_LIMIT);
884 	if (status != EFI_SUCCESS)
885 		return status;
886 
887 	entry = decompress_kernel((void *)addr, virt_addr, error);
888 	if (entry == ULONG_MAX) {
889 		efi_free(alloc_size, addr);
890 		return EFI_LOAD_ERROR;
891 	}
892 
893 	*kernel_entry = addr + entry;
894 
895 	return efi_adjust_memory_range_protection(addr, kernel_text_size) ?:
896 	       efi_adjust_memory_range_protection(addr + kernel_inittext_offset,
897 						  kernel_inittext_size);
898 }
899 
enter_kernel(unsigned long kernel_addr,struct boot_params * boot_params)900 static void __noreturn enter_kernel(unsigned long kernel_addr,
901 				    struct boot_params *boot_params)
902 {
903 	/* enter decompressed kernel with boot_params pointer in RSI/ESI */
904 	asm("jmp *%0"::"r"(kernel_addr), "S"(boot_params));
905 
906 	unreachable();
907 }
908 
909 /*
910  * On success, this routine will jump to the relocated image directly and never
911  * return.  On failure, it will exit to the firmware via efi_exit() instead of
912  * returning.
913  */
efi_stub_entry(efi_handle_t handle,efi_system_table_t * sys_table_arg,struct boot_params * boot_params)914 void __noreturn efi_stub_entry(efi_handle_t handle,
915 			       efi_system_table_t *sys_table_arg,
916 			       struct boot_params *boot_params)
917 
918 {
919 	efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID;
920 	const struct linux_efi_initrd *initrd = NULL;
921 	unsigned long kernel_entry;
922 	struct setup_header *hdr;
923 	efi_status_t status;
924 
925 	efi_system_table = sys_table_arg;
926 	/* Check if we were booted by the EFI firmware */
927 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
928 		efi_exit(handle, EFI_INVALID_PARAMETER);
929 
930 	if (!IS_ENABLED(CONFIG_EFI_HANDOVER_PROTOCOL) || !boot_params) {
931 		status = efi_allocate_bootparams(handle, &boot_params);
932 		if (status != EFI_SUCCESS)
933 			efi_exit(handle, status);
934 	}
935 
936 	hdr = &boot_params->hdr;
937 
938 	if (have_unsupported_snp_features())
939 		efi_exit(handle, EFI_UNSUPPORTED);
940 
941 	if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES)) {
942 		efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID);
943 		if (efi_dxe_table &&
944 		    efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) {
945 			efi_warn("Ignoring DXE services table: invalid signature\n");
946 			efi_dxe_table = NULL;
947 		}
948 	}
949 
950 	/* grab the memory attributes protocol if it exists */
951 	efi_bs_call(locate_protocol, &guid, NULL, (void **)&memattr);
952 
953 	status = efi_setup_5level_paging();
954 	if (status != EFI_SUCCESS) {
955 		efi_err("efi_setup_5level_paging() failed!\n");
956 		goto fail;
957 	}
958 
959 #ifdef CONFIG_CMDLINE_BOOL
960 	status = parse_options(CONFIG_CMDLINE);
961 	if (status != EFI_SUCCESS) {
962 		efi_err("Failed to parse options\n");
963 		goto fail;
964 	}
965 #endif
966 	if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) {
967 		unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr |
968 					       ((u64)boot_params->ext_cmd_line_ptr << 32));
969 		status = parse_options((char *)cmdline_paddr);
970 		if (status != EFI_SUCCESS) {
971 			efi_err("Failed to parse options\n");
972 			goto fail;
973 		}
974 	}
975 
976 	if (efi_mem_encrypt > 0)
977 		hdr->xloadflags |= XLF_MEM_ENCRYPTION;
978 
979 	status = efi_decompress_kernel(&kernel_entry, boot_params);
980 	if (status != EFI_SUCCESS) {
981 		efi_err("Failed to decompress kernel\n");
982 		goto fail;
983 	}
984 
985 	/*
986 	 * At this point, an initrd may already have been loaded by the
987 	 * bootloader and passed via bootparams. We permit an initrd loaded
988 	 * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it.
989 	 *
990 	 * If the device path is not present, any command-line initrd=
991 	 * arguments will be processed only if image is not NULL, which will be
992 	 * the case only if we were loaded via the PE entry point.
993 	 */
994 	status = efi_load_initrd(image, hdr->initrd_addr_max, ULONG_MAX,
995 				 &initrd);
996 	if (status != EFI_SUCCESS)
997 		goto fail;
998 	if (initrd && initrd->size > 0) {
999 		efi_set_u64_split(initrd->base, &hdr->ramdisk_image,
1000 				  &boot_params->ext_ramdisk_image);
1001 		efi_set_u64_split(initrd->size, &hdr->ramdisk_size,
1002 				  &boot_params->ext_ramdisk_size);
1003 	}
1004 
1005 
1006 	/*
1007 	 * If the boot loader gave us a value for secure_boot then we use that,
1008 	 * otherwise we ask the BIOS.
1009 	 */
1010 	if (boot_params->secure_boot == efi_secureboot_mode_unset)
1011 		boot_params->secure_boot = efi_get_secureboot();
1012 
1013 	/* Ask the firmware to clear memory on unclean shutdown */
1014 	efi_enable_reset_attack_mitigation();
1015 
1016 	efi_random_get_seed();
1017 
1018 	efi_retrieve_eventlog();
1019 
1020 	setup_graphics(boot_params);
1021 
1022 	setup_efi_pci(boot_params);
1023 
1024 	setup_quirks(boot_params);
1025 
1026 	setup_unaccepted_memory();
1027 
1028 	status = exit_boot(boot_params, handle);
1029 	if (status != EFI_SUCCESS) {
1030 		efi_err("exit_boot() failed!\n");
1031 		goto fail;
1032 	}
1033 
1034 	/*
1035 	 * Call the SEV init code while still running with the firmware's
1036 	 * GDT/IDT, so #VC exceptions will be handled by EFI.
1037 	 */
1038 	sev_enable(boot_params);
1039 
1040 	efi_5level_switch();
1041 
1042 	enter_kernel(kernel_entry, boot_params);
1043 fail:
1044 	efi_err("efi_stub_entry() failed!\n");
1045 
1046 	efi_exit(handle, status);
1047 }
1048 
efi_pe_entry(efi_handle_t handle,efi_system_table_t * sys_table_arg)1049 efi_status_t __efiapi efi_pe_entry(efi_handle_t handle,
1050 				   efi_system_table_t *sys_table_arg)
1051 {
1052 	efi_stub_entry(handle, sys_table_arg, NULL);
1053 }
1054 
1055 #ifdef CONFIG_EFI_HANDOVER_PROTOCOL
efi_handover_entry(efi_handle_t handle,efi_system_table_t * sys_table_arg,struct boot_params * boot_params)1056 void efi_handover_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
1057 			struct boot_params *boot_params)
1058 {
1059 	memset(_bss, 0, _ebss - _bss);
1060 	efi_stub_entry(handle, sys_table_arg, boot_params);
1061 }
1062 
1063 #ifndef CONFIG_EFI_MIXED
1064 extern __alias(efi_handover_entry)
1065 void efi32_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
1066 		      struct boot_params *boot_params);
1067 
1068 extern __alias(efi_handover_entry)
1069 void efi64_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
1070 		      struct boot_params *boot_params);
1071 #endif
1072 #endif
1073 
1074 #ifdef CONFIG_UNACCEPTED_MEMORY
1075 /*
1076  * process_unaccepted_memory() is called after ExitBootServices(), and so these
1077  * memory acceptance routines cannot rely on EFI protocols for detecting the
1078  * presence of TDX or SEV-SNP, or emit any kind of output if any error
1079  * conditions are detected.
1080  */
early_is_tdx_guest(void)1081 static bool early_is_tdx_guest(void)
1082 {
1083 	static bool once;
1084 	static bool is_tdx;
1085 
1086 	if (!IS_ENABLED(CONFIG_INTEL_TDX_GUEST))
1087 		return false;
1088 
1089 	if (!once) {
1090 		u32 eax = TDX_CPUID_LEAF_ID, sig[3] = {};
1091 
1092 		native_cpuid(&eax, &sig[0], &sig[2], &sig[1]);
1093 		is_tdx = !memcmp(TDX_IDENT, sig, sizeof(sig));
1094 		once = true;
1095 	}
1096 
1097 	return is_tdx;
1098 }
1099 
arch_accept_memory(phys_addr_t start,phys_addr_t end)1100 void arch_accept_memory(phys_addr_t start, phys_addr_t end)
1101 {
1102 	if (early_is_tdx_guest()) {
1103 		if (!tdx_accept_memory(start, end))
1104 			tdx_panic("Failed to accept memory");
1105 	} else if (early_is_sevsnp_guest()) {
1106 		snp_accept_memory(start, end);
1107 	}
1108 }
1109 #endif
1110