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 
19 #include "efistub.h"
20 
21 /* Maximum physical address for 64-bit kernel with 4-level paging */
22 #define MAXMEM_X86_64_4LEVEL (1ull << 46)
23 
24 const efi_system_table_t *efi_system_table;
25 const efi_dxe_services_table_t *efi_dxe_table;
26 extern u32 image_offset;
27 static efi_loaded_image_t *image = NULL;
28 
29 static efi_status_t
30 preserve_pci_rom_image(efi_pci_io_protocol_t *pci, struct pci_setup_rom **__rom)
31 {
32 	struct pci_setup_rom *rom = NULL;
33 	efi_status_t status;
34 	unsigned long size;
35 	uint64_t romsize;
36 	void *romimage;
37 
38 	/*
39 	 * Some firmware images contain EFI function pointers at the place where
40 	 * the romimage and romsize fields are supposed to be. Typically the EFI
41 	 * code is mapped at high addresses, translating to an unrealistically
42 	 * large romsize. The UEFI spec limits the size of option ROMs to 16
43 	 * MiB so we reject any ROMs over 16 MiB in size to catch this.
44 	 */
45 	romimage = efi_table_attr(pci, romimage);
46 	romsize = efi_table_attr(pci, romsize);
47 	if (!romimage || !romsize || romsize > SZ_16M)
48 		return EFI_INVALID_PARAMETER;
49 
50 	size = romsize + sizeof(*rom);
51 
52 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
53 			     (void **)&rom);
54 	if (status != EFI_SUCCESS) {
55 		efi_err("Failed to allocate memory for 'rom'\n");
56 		return status;
57 	}
58 
59 	memset(rom, 0, sizeof(*rom));
60 
61 	rom->data.type	= SETUP_PCI;
62 	rom->data.len	= size - sizeof(struct setup_data);
63 	rom->data.next	= 0;
64 	rom->pcilen	= pci->romsize;
65 	*__rom = rom;
66 
67 	status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16,
68 				PCI_VENDOR_ID, 1, &rom->vendor);
69 
70 	if (status != EFI_SUCCESS) {
71 		efi_err("Failed to read rom->vendor\n");
72 		goto free_struct;
73 	}
74 
75 	status = efi_call_proto(pci, pci.read, EfiPciIoWidthUint16,
76 				PCI_DEVICE_ID, 1, &rom->devid);
77 
78 	if (status != EFI_SUCCESS) {
79 		efi_err("Failed to read rom->devid\n");
80 		goto free_struct;
81 	}
82 
83 	status = efi_call_proto(pci, get_location, &rom->segment, &rom->bus,
84 				&rom->device, &rom->function);
85 
86 	if (status != EFI_SUCCESS)
87 		goto free_struct;
88 
89 	memcpy(rom->romdata, romimage, romsize);
90 	return status;
91 
92 free_struct:
93 	efi_bs_call(free_pool, rom);
94 	return status;
95 }
96 
97 /*
98  * There's no way to return an informative status from this function,
99  * because any analysis (and printing of error messages) needs to be
100  * done directly at the EFI function call-site.
101  *
102  * For example, EFI_INVALID_PARAMETER could indicate a bug or maybe we
103  * just didn't find any PCI devices, but there's no way to tell outside
104  * the context of the call.
105  */
106 static void setup_efi_pci(struct boot_params *params)
107 {
108 	efi_status_t status;
109 	void **pci_handle = NULL;
110 	efi_guid_t pci_proto = EFI_PCI_IO_PROTOCOL_GUID;
111 	unsigned long size = 0;
112 	struct setup_data *data;
113 	efi_handle_t h;
114 	int i;
115 
116 	status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
117 			     &pci_proto, NULL, &size, pci_handle);
118 
119 	if (status == EFI_BUFFER_TOO_SMALL) {
120 		status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
121 				     (void **)&pci_handle);
122 
123 		if (status != EFI_SUCCESS) {
124 			efi_err("Failed to allocate memory for 'pci_handle'\n");
125 			return;
126 		}
127 
128 		status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
129 				     &pci_proto, NULL, &size, pci_handle);
130 	}
131 
132 	if (status != EFI_SUCCESS)
133 		goto free_handle;
134 
135 	data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
136 
137 	while (data && data->next)
138 		data = (struct setup_data *)(unsigned long)data->next;
139 
140 	for_each_efi_handle(h, pci_handle, size, i) {
141 		efi_pci_io_protocol_t *pci = NULL;
142 		struct pci_setup_rom *rom;
143 
144 		status = efi_bs_call(handle_protocol, h, &pci_proto,
145 				     (void **)&pci);
146 		if (status != EFI_SUCCESS || !pci)
147 			continue;
148 
149 		status = preserve_pci_rom_image(pci, &rom);
150 		if (status != EFI_SUCCESS)
151 			continue;
152 
153 		if (data)
154 			data->next = (unsigned long)rom;
155 		else
156 			params->hdr.setup_data = (unsigned long)rom;
157 
158 		data = (struct setup_data *)rom;
159 	}
160 
161 free_handle:
162 	efi_bs_call(free_pool, pci_handle);
163 }
164 
165 static void retrieve_apple_device_properties(struct boot_params *boot_params)
166 {
167 	efi_guid_t guid = APPLE_PROPERTIES_PROTOCOL_GUID;
168 	struct setup_data *data, *new;
169 	efi_status_t status;
170 	u32 size = 0;
171 	apple_properties_protocol_t *p;
172 
173 	status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&p);
174 	if (status != EFI_SUCCESS)
175 		return;
176 
177 	if (efi_table_attr(p, version) != 0x10000) {
178 		efi_err("Unsupported properties proto version\n");
179 		return;
180 	}
181 
182 	efi_call_proto(p, get_all, NULL, &size);
183 	if (!size)
184 		return;
185 
186 	do {
187 		status = efi_bs_call(allocate_pool, EFI_LOADER_DATA,
188 				     size + sizeof(struct setup_data),
189 				     (void **)&new);
190 		if (status != EFI_SUCCESS) {
191 			efi_err("Failed to allocate memory for 'properties'\n");
192 			return;
193 		}
194 
195 		status = efi_call_proto(p, get_all, new->data, &size);
196 
197 		if (status == EFI_BUFFER_TOO_SMALL)
198 			efi_bs_call(free_pool, new);
199 	} while (status == EFI_BUFFER_TOO_SMALL);
200 
201 	new->type = SETUP_APPLE_PROPERTIES;
202 	new->len  = size;
203 	new->next = 0;
204 
205 	data = (struct setup_data *)(unsigned long)boot_params->hdr.setup_data;
206 	if (!data) {
207 		boot_params->hdr.setup_data = (unsigned long)new;
208 	} else {
209 		while (data->next)
210 			data = (struct setup_data *)(unsigned long)data->next;
211 		data->next = (unsigned long)new;
212 	}
213 }
214 
215 static void
216 adjust_memory_range_protection(unsigned long start, unsigned long size)
217 {
218 	efi_status_t status;
219 	efi_gcd_memory_space_desc_t desc;
220 	unsigned long end, next;
221 	unsigned long rounded_start, rounded_end;
222 	unsigned long unprotect_start, unprotect_size;
223 
224 	if (efi_dxe_table == NULL)
225 		return;
226 
227 	rounded_start = rounddown(start, EFI_PAGE_SIZE);
228 	rounded_end = roundup(start + size, EFI_PAGE_SIZE);
229 
230 	/*
231 	 * Don't modify memory region attributes, they are
232 	 * already suitable, to lower the possibility to
233 	 * encounter firmware bugs.
234 	 */
235 
236 	for (end = start + size; start < end; start = next) {
237 
238 		status = efi_dxe_call(get_memory_space_descriptor, start, &desc);
239 
240 		if (status != EFI_SUCCESS)
241 			return;
242 
243 		next = desc.base_address + desc.length;
244 
245 		/*
246 		 * Only system memory is suitable for trampoline/kernel image placement,
247 		 * so only this type of memory needs its attributes to be modified.
248 		 */
249 
250 		if (desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory ||
251 		    (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0)
252 			continue;
253 
254 		unprotect_start = max(rounded_start, (unsigned long)desc.base_address);
255 		unprotect_size = min(rounded_end, next) - unprotect_start;
256 
257 		status = efi_dxe_call(set_memory_space_attributes,
258 				      unprotect_start, unprotect_size,
259 				      EFI_MEMORY_WB);
260 
261 		if (status != EFI_SUCCESS) {
262 			efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n",
263 				 unprotect_start,
264 				 unprotect_start + unprotect_size,
265 				 status);
266 		}
267 	}
268 }
269 
270 /*
271  * Trampoline takes 2 pages and can be loaded in first megabyte of memory
272  * with its end placed between 128k and 640k where BIOS might start.
273  * (see arch/x86/boot/compressed/pgtable_64.c)
274  *
275  * We cannot find exact trampoline placement since memory map
276  * can be modified by UEFI, and it can alter the computed address.
277  */
278 
279 #define TRAMPOLINE_PLACEMENT_BASE ((128 - 8)*1024)
280 #define TRAMPOLINE_PLACEMENT_SIZE (640*1024 - (128 - 8)*1024)
281 
282 void startup_32(struct boot_params *boot_params);
283 
284 static void
285 setup_memory_protection(unsigned long image_base, unsigned long image_size)
286 {
287 	/*
288 	 * Allow execution of possible trampoline used
289 	 * for switching between 4- and 5-level page tables
290 	 * and relocated kernel image.
291 	 */
292 
293 	adjust_memory_range_protection(TRAMPOLINE_PLACEMENT_BASE,
294 				       TRAMPOLINE_PLACEMENT_SIZE);
295 
296 #ifdef CONFIG_64BIT
297 	if (image_base != (unsigned long)startup_32)
298 		adjust_memory_range_protection(image_base, image_size);
299 #else
300 	/*
301 	 * Clear protection flags on a whole range of possible
302 	 * addresses used for KASLR. We don't need to do that
303 	 * on x86_64, since KASLR/extraction is performed after
304 	 * dedicated identity page tables are built and we only
305 	 * need to remove possible protection on relocated image
306 	 * itself disregarding further relocations.
307 	 */
308 	adjust_memory_range_protection(LOAD_PHYSICAL_ADDR,
309 				       KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR);
310 #endif
311 }
312 
313 static const efi_char16_t apple[] = L"Apple";
314 
315 static void setup_quirks(struct boot_params *boot_params,
316 			 unsigned long image_base,
317 			 unsigned long image_size)
318 {
319 	efi_char16_t *fw_vendor = (efi_char16_t *)(unsigned long)
320 		efi_table_attr(efi_system_table, fw_vendor);
321 
322 	if (!memcmp(fw_vendor, apple, sizeof(apple))) {
323 		if (IS_ENABLED(CONFIG_APPLE_PROPERTIES))
324 			retrieve_apple_device_properties(boot_params);
325 	}
326 
327 	if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES))
328 		setup_memory_protection(image_base, image_size);
329 }
330 
331 /*
332  * See if we have Universal Graphics Adapter (UGA) protocol
333  */
334 static efi_status_t
335 setup_uga(struct screen_info *si, efi_guid_t *uga_proto, unsigned long size)
336 {
337 	efi_status_t status;
338 	u32 width, height;
339 	void **uga_handle = NULL;
340 	efi_uga_draw_protocol_t *uga = NULL, *first_uga;
341 	efi_handle_t handle;
342 	int i;
343 
344 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
345 			     (void **)&uga_handle);
346 	if (status != EFI_SUCCESS)
347 		return status;
348 
349 	status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
350 			     uga_proto, NULL, &size, uga_handle);
351 	if (status != EFI_SUCCESS)
352 		goto free_handle;
353 
354 	height = 0;
355 	width = 0;
356 
357 	first_uga = NULL;
358 	for_each_efi_handle(handle, uga_handle, size, i) {
359 		efi_guid_t pciio_proto = EFI_PCI_IO_PROTOCOL_GUID;
360 		u32 w, h, depth, refresh;
361 		void *pciio;
362 
363 		status = efi_bs_call(handle_protocol, handle, uga_proto,
364 				     (void **)&uga);
365 		if (status != EFI_SUCCESS)
366 			continue;
367 
368 		pciio = NULL;
369 		efi_bs_call(handle_protocol, handle, &pciio_proto, &pciio);
370 
371 		status = efi_call_proto(uga, get_mode, &w, &h, &depth, &refresh);
372 		if (status == EFI_SUCCESS && (!first_uga || pciio)) {
373 			width = w;
374 			height = h;
375 
376 			/*
377 			 * Once we've found a UGA supporting PCIIO,
378 			 * don't bother looking any further.
379 			 */
380 			if (pciio)
381 				break;
382 
383 			first_uga = uga;
384 		}
385 	}
386 
387 	if (!width && !height)
388 		goto free_handle;
389 
390 	/* EFI framebuffer */
391 	si->orig_video_isVGA	= VIDEO_TYPE_EFI;
392 
393 	si->lfb_depth		= 32;
394 	si->lfb_width		= width;
395 	si->lfb_height		= height;
396 
397 	si->red_size		= 8;
398 	si->red_pos		= 16;
399 	si->green_size		= 8;
400 	si->green_pos		= 8;
401 	si->blue_size		= 8;
402 	si->blue_pos		= 0;
403 	si->rsvd_size		= 8;
404 	si->rsvd_pos		= 24;
405 
406 free_handle:
407 	efi_bs_call(free_pool, uga_handle);
408 
409 	return status;
410 }
411 
412 static void setup_graphics(struct boot_params *boot_params)
413 {
414 	efi_guid_t graphics_proto = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
415 	struct screen_info *si;
416 	efi_guid_t uga_proto = EFI_UGA_PROTOCOL_GUID;
417 	efi_status_t status;
418 	unsigned long size;
419 	void **gop_handle = NULL;
420 	void **uga_handle = NULL;
421 
422 	si = &boot_params->screen_info;
423 	memset(si, 0, sizeof(*si));
424 
425 	size = 0;
426 	status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
427 			     &graphics_proto, NULL, &size, gop_handle);
428 	if (status == EFI_BUFFER_TOO_SMALL)
429 		status = efi_setup_gop(si, &graphics_proto, size);
430 
431 	if (status != EFI_SUCCESS) {
432 		size = 0;
433 		status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
434 				     &uga_proto, NULL, &size, uga_handle);
435 		if (status == EFI_BUFFER_TOO_SMALL)
436 			setup_uga(si, &uga_proto, size);
437 	}
438 }
439 
440 
441 static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status)
442 {
443 	efi_bs_call(exit, handle, status, 0, NULL);
444 	for(;;)
445 		asm("hlt");
446 }
447 
448 void __noreturn efi_stub_entry(efi_handle_t handle,
449 			       efi_system_table_t *sys_table_arg,
450 			       struct boot_params *boot_params);
451 
452 /*
453  * Because the x86 boot code expects to be passed a boot_params we
454  * need to create one ourselves (usually the bootloader would create
455  * one for us).
456  */
457 efi_status_t __efiapi efi_pe_entry(efi_handle_t handle,
458 				   efi_system_table_t *sys_table_arg)
459 {
460 	struct boot_params *boot_params;
461 	struct setup_header *hdr;
462 	void *image_base;
463 	efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID;
464 	int options_size = 0;
465 	efi_status_t status;
466 	char *cmdline_ptr;
467 
468 	efi_system_table = sys_table_arg;
469 
470 	/* Check if we were booted by the EFI firmware */
471 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
472 		efi_exit(handle, EFI_INVALID_PARAMETER);
473 
474 	status = efi_bs_call(handle_protocol, handle, &proto, (void **)&image);
475 	if (status != EFI_SUCCESS) {
476 		efi_err("Failed to get handle for LOADED_IMAGE_PROTOCOL\n");
477 		efi_exit(handle, status);
478 	}
479 
480 	image_base = efi_table_attr(image, image_base);
481 	image_offset = (void *)startup_32 - 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 		default:
617 			continue;
618 		}
619 
620 		/* Merge adjacent mappings */
621 		if (prev && prev->type == e820_type &&
622 		    (prev->addr + prev->size) == d->phys_addr) {
623 			prev->size += d->num_pages << 12;
624 			continue;
625 		}
626 
627 		if (nr_entries == ARRAY_SIZE(params->e820_table)) {
628 			u32 need = (nr_desc - i) * sizeof(struct e820_entry) +
629 				   sizeof(struct setup_data);
630 
631 			if (!e820ext || e820ext_size < need)
632 				return EFI_BUFFER_TOO_SMALL;
633 
634 			/* boot_params map full, switch to e820 extended */
635 			entry = (struct boot_e820_entry *)e820ext->data;
636 		}
637 
638 		entry->addr = d->phys_addr;
639 		entry->size = d->num_pages << PAGE_SHIFT;
640 		entry->type = e820_type;
641 		prev = entry++;
642 		nr_entries++;
643 	}
644 
645 	if (nr_entries > ARRAY_SIZE(params->e820_table)) {
646 		u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table);
647 
648 		add_e820ext(params, e820ext, nr_e820ext);
649 		nr_entries -= nr_e820ext;
650 	}
651 
652 	params->e820_entries = (u8)nr_entries;
653 
654 	return EFI_SUCCESS;
655 }
656 
657 static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext,
658 				  u32 *e820ext_size)
659 {
660 	efi_status_t status;
661 	unsigned long size;
662 
663 	size = sizeof(struct setup_data) +
664 		sizeof(struct e820_entry) * nr_desc;
665 
666 	if (*e820ext) {
667 		efi_bs_call(free_pool, *e820ext);
668 		*e820ext = NULL;
669 		*e820ext_size = 0;
670 	}
671 
672 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
673 			     (void **)e820ext);
674 	if (status == EFI_SUCCESS)
675 		*e820ext_size = size;
676 
677 	return status;
678 }
679 
680 static efi_status_t allocate_e820(struct boot_params *params,
681 				  struct setup_data **e820ext,
682 				  u32 *e820ext_size)
683 {
684 	unsigned long map_size, desc_size, map_key;
685 	efi_status_t status;
686 	__u32 nr_desc, desc_version;
687 
688 	/* Only need the size of the mem map and size of each mem descriptor */
689 	map_size = 0;
690 	status = efi_bs_call(get_memory_map, &map_size, NULL, &map_key,
691 			     &desc_size, &desc_version);
692 	if (status != EFI_BUFFER_TOO_SMALL)
693 		return (status != EFI_SUCCESS) ? status : EFI_UNSUPPORTED;
694 
695 	nr_desc = map_size / desc_size + EFI_MMAP_NR_SLACK_SLOTS;
696 
697 	if (nr_desc > ARRAY_SIZE(params->e820_table)) {
698 		u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table);
699 
700 		status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size);
701 		if (status != EFI_SUCCESS)
702 			return status;
703 	}
704 
705 	return EFI_SUCCESS;
706 }
707 
708 struct exit_boot_struct {
709 	struct boot_params	*boot_params;
710 	struct efi_info		*efi;
711 };
712 
713 static efi_status_t exit_boot_func(struct efi_boot_memmap *map,
714 				   void *priv)
715 {
716 	const char *signature;
717 	struct exit_boot_struct *p = priv;
718 
719 	signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE
720 				   : EFI32_LOADER_SIGNATURE;
721 	memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32));
722 
723 	efi_set_u64_split((unsigned long)efi_system_table,
724 			  &p->efi->efi_systab, &p->efi->efi_systab_hi);
725 	p->efi->efi_memdesc_size	= map->desc_size;
726 	p->efi->efi_memdesc_version	= map->desc_ver;
727 	efi_set_u64_split((unsigned long)map->map,
728 			  &p->efi->efi_memmap, &p->efi->efi_memmap_hi);
729 	p->efi->efi_memmap_size		= map->map_size;
730 
731 	return EFI_SUCCESS;
732 }
733 
734 static efi_status_t exit_boot(struct boot_params *boot_params, void *handle)
735 {
736 	struct setup_data *e820ext = NULL;
737 	__u32 e820ext_size = 0;
738 	efi_status_t status;
739 	struct exit_boot_struct priv;
740 
741 	priv.boot_params	= boot_params;
742 	priv.efi		= &boot_params->efi_info;
743 
744 	status = allocate_e820(boot_params, &e820ext, &e820ext_size);
745 	if (status != EFI_SUCCESS)
746 		return status;
747 
748 	/* Might as well exit boot services now */
749 	status = efi_exit_boot_services(handle, &priv, exit_boot_func);
750 	if (status != EFI_SUCCESS)
751 		return status;
752 
753 	/* Historic? */
754 	boot_params->alt_mem_k	= 32 * 1024;
755 
756 	status = setup_e820(boot_params, e820ext, e820ext_size);
757 	if (status != EFI_SUCCESS)
758 		return status;
759 
760 	return EFI_SUCCESS;
761 }
762 
763 /*
764  * On success, we return the address of startup_32, which has potentially been
765  * relocated by efi_relocate_kernel.
766  * On failure, we exit to the firmware via efi_exit instead of returning.
767  */
768 asmlinkage unsigned long efi_main(efi_handle_t handle,
769 				  efi_system_table_t *sys_table_arg,
770 				  struct boot_params *boot_params)
771 {
772 	unsigned long bzimage_addr = (unsigned long)startup_32;
773 	unsigned long buffer_start, buffer_end;
774 	struct setup_header *hdr = &boot_params->hdr;
775 	const struct linux_efi_initrd *initrd = NULL;
776 	efi_status_t status;
777 
778 	efi_system_table = sys_table_arg;
779 	/* Check if we were booted by the EFI firmware */
780 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
781 		efi_exit(handle, EFI_INVALID_PARAMETER);
782 
783 	efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID);
784 	if (efi_dxe_table &&
785 	    efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) {
786 		efi_warn("Ignoring DXE services table: invalid signature\n");
787 		efi_dxe_table = NULL;
788 	}
789 
790 	/*
791 	 * If the kernel isn't already loaded at a suitable address,
792 	 * relocate it.
793 	 *
794 	 * It must be loaded above LOAD_PHYSICAL_ADDR.
795 	 *
796 	 * The maximum address for 64-bit is 1 << 46 for 4-level paging. This
797 	 * is defined as the macro MAXMEM, but unfortunately that is not a
798 	 * compile-time constant if 5-level paging is configured, so we instead
799 	 * define our own macro for use here.
800 	 *
801 	 * For 32-bit, the maximum address is complicated to figure out, for
802 	 * now use KERNEL_IMAGE_SIZE, which will be 512MiB, the same as what
803 	 * KASLR uses.
804 	 *
805 	 * Also relocate it if image_offset is zero, i.e. the kernel wasn't
806 	 * loaded by LoadImage, but rather by a bootloader that called the
807 	 * handover entry. The reason we must always relocate in this case is
808 	 * to handle the case of systemd-boot booting a unified kernel image,
809 	 * which is a PE executable that contains the bzImage and an initrd as
810 	 * COFF sections. The initrd section is placed after the bzImage
811 	 * without ensuring that there are at least init_size bytes available
812 	 * for the bzImage, and thus the compressed kernel's startup code may
813 	 * overwrite the initrd unless it is moved out of the way.
814 	 */
815 
816 	buffer_start = ALIGN(bzimage_addr - image_offset,
817 			     hdr->kernel_alignment);
818 	buffer_end = buffer_start + hdr->init_size;
819 
820 	if ((buffer_start < LOAD_PHYSICAL_ADDR)				     ||
821 	    (IS_ENABLED(CONFIG_X86_32) && buffer_end > KERNEL_IMAGE_SIZE)    ||
822 	    (IS_ENABLED(CONFIG_X86_64) && buffer_end > MAXMEM_X86_64_4LEVEL) ||
823 	    (image_offset == 0)) {
824 		extern char _bss[];
825 
826 		status = efi_relocate_kernel(&bzimage_addr,
827 					     (unsigned long)_bss - bzimage_addr,
828 					     hdr->init_size,
829 					     hdr->pref_address,
830 					     hdr->kernel_alignment,
831 					     LOAD_PHYSICAL_ADDR);
832 		if (status != EFI_SUCCESS) {
833 			efi_err("efi_relocate_kernel() failed!\n");
834 			goto fail;
835 		}
836 		/*
837 		 * Now that we've copied the kernel elsewhere, we no longer
838 		 * have a set up block before startup_32(), so reset image_offset
839 		 * to zero in case it was set earlier.
840 		 */
841 		image_offset = 0;
842 	}
843 
844 #ifdef CONFIG_CMDLINE_BOOL
845 	status = efi_parse_options(CONFIG_CMDLINE);
846 	if (status != EFI_SUCCESS) {
847 		efi_err("Failed to parse options\n");
848 		goto fail;
849 	}
850 #endif
851 	if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) {
852 		unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr |
853 					       ((u64)boot_params->ext_cmd_line_ptr << 32));
854 		status = efi_parse_options((char *)cmdline_paddr);
855 		if (status != EFI_SUCCESS) {
856 			efi_err("Failed to parse options\n");
857 			goto fail;
858 		}
859 	}
860 
861 	/*
862 	 * At this point, an initrd may already have been loaded by the
863 	 * bootloader and passed via bootparams. We permit an initrd loaded
864 	 * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it.
865 	 *
866 	 * If the device path is not present, any command-line initrd=
867 	 * arguments will be processed only if image is not NULL, which will be
868 	 * the case only if we were loaded via the PE entry point.
869 	 */
870 	status = efi_load_initrd(image, hdr->initrd_addr_max, ULONG_MAX,
871 				 &initrd);
872 	if (status != EFI_SUCCESS)
873 		goto fail;
874 	if (initrd && initrd->size > 0) {
875 		efi_set_u64_split(initrd->base, &hdr->ramdisk_image,
876 				  &boot_params->ext_ramdisk_image);
877 		efi_set_u64_split(initrd->size, &hdr->ramdisk_size,
878 				  &boot_params->ext_ramdisk_size);
879 	}
880 
881 
882 	/*
883 	 * If the boot loader gave us a value for secure_boot then we use that,
884 	 * otherwise we ask the BIOS.
885 	 */
886 	if (boot_params->secure_boot == efi_secureboot_mode_unset)
887 		boot_params->secure_boot = efi_get_secureboot();
888 
889 	/* Ask the firmware to clear memory on unclean shutdown */
890 	efi_enable_reset_attack_mitigation();
891 
892 	efi_random_get_seed();
893 
894 	efi_retrieve_tpm2_eventlog();
895 
896 	setup_graphics(boot_params);
897 
898 	setup_efi_pci(boot_params);
899 
900 	setup_quirks(boot_params, bzimage_addr, buffer_end - buffer_start);
901 
902 	status = exit_boot(boot_params, handle);
903 	if (status != EFI_SUCCESS) {
904 		efi_err("exit_boot() failed!\n");
905 		goto fail;
906 	}
907 
908 	return bzimage_addr;
909 fail:
910 	efi_err("efi_main() failed!\n");
911 
912 	efi_exit(handle, status);
913 }
914