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