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 	int has_system_memory = 0;
224 
225 	if (efi_dxe_table == NULL)
226 		return;
227 
228 	rounded_start = rounddown(start, EFI_PAGE_SIZE);
229 	rounded_end = roundup(start + size, EFI_PAGE_SIZE);
230 
231 	/*
232 	 * Don't modify memory region attributes, they are
233 	 * already suitable, to lower the possibility to
234 	 * encounter firmware bugs.
235 	 */
236 
237 	for (end = start + size; start < end; start = next) {
238 
239 		status = efi_dxe_call(get_memory_space_descriptor, start, &desc);
240 
241 		if (status != EFI_SUCCESS)
242 			return;
243 
244 		next = desc.base_address + desc.length;
245 
246 		/*
247 		 * Only system memory is suitable for trampoline/kernel image placement,
248 		 * so only this type of memory needs its attributes to be modified.
249 		 */
250 
251 		if (desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory ||
252 		    (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0)
253 			continue;
254 
255 		unprotect_start = max(rounded_start, (unsigned long)desc.base_address);
256 		unprotect_size = min(rounded_end, next) - unprotect_start;
257 
258 		status = efi_dxe_call(set_memory_space_attributes,
259 				      unprotect_start, unprotect_size,
260 				      EFI_MEMORY_WB);
261 
262 		if (status != EFI_SUCCESS) {
263 			efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n",
264 				 unprotect_start,
265 				 unprotect_start + unprotect_size,
266 				 status);
267 		}
268 	}
269 }
270 
271 /*
272  * Trampoline takes 2 pages and can be loaded in first megabyte of memory
273  * with its end placed between 128k and 640k where BIOS might start.
274  * (see arch/x86/boot/compressed/pgtable_64.c)
275  *
276  * We cannot find exact trampoline placement since memory map
277  * can be modified by UEFI, and it can alter the computed address.
278  */
279 
280 #define TRAMPOLINE_PLACEMENT_BASE ((128 - 8)*1024)
281 #define TRAMPOLINE_PLACEMENT_SIZE (640*1024 - (128 - 8)*1024)
282 
283 void startup_32(struct boot_params *boot_params);
284 
285 static void
286 setup_memory_protection(unsigned long image_base, unsigned long image_size)
287 {
288 	/*
289 	 * Allow execution of possible trampoline used
290 	 * for switching between 4- and 5-level page tables
291 	 * and relocated kernel image.
292 	 */
293 
294 	adjust_memory_range_protection(TRAMPOLINE_PLACEMENT_BASE,
295 				       TRAMPOLINE_PLACEMENT_SIZE);
296 
297 #ifdef CONFIG_64BIT
298 	if (image_base != (unsigned long)startup_32)
299 		adjust_memory_range_protection(image_base, image_size);
300 #else
301 	/*
302 	 * Clear protection flags on a whole range of possible
303 	 * addresses used for KASLR. We don't need to do that
304 	 * on x86_64, since KASLR/extraction is performed after
305 	 * dedicated identity page tables are built and we only
306 	 * need to remove possible protection on relocated image
307 	 * itself disregarding further relocations.
308 	 */
309 	adjust_memory_range_protection(LOAD_PHYSICAL_ADDR,
310 				       KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR);
311 #endif
312 }
313 
314 static const efi_char16_t apple[] = L"Apple";
315 
316 static void setup_quirks(struct boot_params *boot_params,
317 			 unsigned long image_base,
318 			 unsigned long image_size)
319 {
320 	efi_char16_t *fw_vendor = (efi_char16_t *)(unsigned long)
321 		efi_table_attr(efi_system_table, fw_vendor);
322 
323 	if (!memcmp(fw_vendor, apple, sizeof(apple))) {
324 		if (IS_ENABLED(CONFIG_APPLE_PROPERTIES))
325 			retrieve_apple_device_properties(boot_params);
326 	}
327 
328 	if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES))
329 		setup_memory_protection(image_base, image_size);
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 	image_offset = (void *)startup_32 - image_base;
483 
484 	status = efi_allocate_pages(sizeof(struct boot_params),
485 				    (unsigned long *)&boot_params, ULONG_MAX);
486 	if (status != EFI_SUCCESS) {
487 		efi_err("Failed to allocate lowmem for boot params\n");
488 		efi_exit(handle, status);
489 	}
490 
491 	memset(boot_params, 0x0, sizeof(struct boot_params));
492 
493 	hdr = &boot_params->hdr;
494 
495 	/* Copy the setup header from the second sector to boot_params */
496 	memcpy(&hdr->jump, image_base + 512,
497 	       sizeof(struct setup_header) - offsetof(struct setup_header, jump));
498 
499 	/*
500 	 * Fill out some of the header fields ourselves because the
501 	 * EFI firmware loader doesn't load the first sector.
502 	 */
503 	hdr->root_flags	= 1;
504 	hdr->vid_mode	= 0xffff;
505 	hdr->boot_flag	= 0xAA55;
506 
507 	hdr->type_of_loader = 0x21;
508 
509 	/* Convert unicode cmdline to ascii */
510 	cmdline_ptr = efi_convert_cmdline(image, &options_size);
511 	if (!cmdline_ptr)
512 		goto fail;
513 
514 	efi_set_u64_split((unsigned long)cmdline_ptr,
515 			  &hdr->cmd_line_ptr, &boot_params->ext_cmd_line_ptr);
516 
517 	hdr->ramdisk_image = 0;
518 	hdr->ramdisk_size = 0;
519 
520 	efi_stub_entry(handle, sys_table_arg, boot_params);
521 	/* not reached */
522 
523 fail:
524 	efi_free(sizeof(struct boot_params), (unsigned long)boot_params);
525 
526 	efi_exit(handle, status);
527 }
528 
529 static void add_e820ext(struct boot_params *params,
530 			struct setup_data *e820ext, u32 nr_entries)
531 {
532 	struct setup_data *data;
533 
534 	e820ext->type = SETUP_E820_EXT;
535 	e820ext->len  = nr_entries * sizeof(struct boot_e820_entry);
536 	e820ext->next = 0;
537 
538 	data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
539 
540 	while (data && data->next)
541 		data = (struct setup_data *)(unsigned long)data->next;
542 
543 	if (data)
544 		data->next = (unsigned long)e820ext;
545 	else
546 		params->hdr.setup_data = (unsigned long)e820ext;
547 }
548 
549 static efi_status_t
550 setup_e820(struct boot_params *params, struct setup_data *e820ext, u32 e820ext_size)
551 {
552 	struct boot_e820_entry *entry = params->e820_table;
553 	struct efi_info *efi = &params->efi_info;
554 	struct boot_e820_entry *prev = NULL;
555 	u32 nr_entries;
556 	u32 nr_desc;
557 	int i;
558 
559 	nr_entries = 0;
560 	nr_desc = efi->efi_memmap_size / efi->efi_memdesc_size;
561 
562 	for (i = 0; i < nr_desc; i++) {
563 		efi_memory_desc_t *d;
564 		unsigned int e820_type = 0;
565 		unsigned long m = efi->efi_memmap;
566 
567 #ifdef CONFIG_X86_64
568 		m |= (u64)efi->efi_memmap_hi << 32;
569 #endif
570 
571 		d = efi_early_memdesc_ptr(m, efi->efi_memdesc_size, i);
572 		switch (d->type) {
573 		case EFI_RESERVED_TYPE:
574 		case EFI_RUNTIME_SERVICES_CODE:
575 		case EFI_RUNTIME_SERVICES_DATA:
576 		case EFI_MEMORY_MAPPED_IO:
577 		case EFI_MEMORY_MAPPED_IO_PORT_SPACE:
578 		case EFI_PAL_CODE:
579 			e820_type = E820_TYPE_RESERVED;
580 			break;
581 
582 		case EFI_UNUSABLE_MEMORY:
583 			e820_type = E820_TYPE_UNUSABLE;
584 			break;
585 
586 		case EFI_ACPI_RECLAIM_MEMORY:
587 			e820_type = E820_TYPE_ACPI;
588 			break;
589 
590 		case EFI_LOADER_CODE:
591 		case EFI_LOADER_DATA:
592 		case EFI_BOOT_SERVICES_CODE:
593 		case EFI_BOOT_SERVICES_DATA:
594 		case EFI_CONVENTIONAL_MEMORY:
595 			if (efi_soft_reserve_enabled() &&
596 			    (d->attribute & EFI_MEMORY_SP))
597 				e820_type = E820_TYPE_SOFT_RESERVED;
598 			else
599 				e820_type = E820_TYPE_RAM;
600 			break;
601 
602 		case EFI_ACPI_MEMORY_NVS:
603 			e820_type = E820_TYPE_NVS;
604 			break;
605 
606 		case EFI_PERSISTENT_MEMORY:
607 			e820_type = E820_TYPE_PMEM;
608 			break;
609 
610 		default:
611 			continue;
612 		}
613 
614 		/* Merge adjacent mappings */
615 		if (prev && prev->type == e820_type &&
616 		    (prev->addr + prev->size) == d->phys_addr) {
617 			prev->size += d->num_pages << 12;
618 			continue;
619 		}
620 
621 		if (nr_entries == ARRAY_SIZE(params->e820_table)) {
622 			u32 need = (nr_desc - i) * sizeof(struct e820_entry) +
623 				   sizeof(struct setup_data);
624 
625 			if (!e820ext || e820ext_size < need)
626 				return EFI_BUFFER_TOO_SMALL;
627 
628 			/* boot_params map full, switch to e820 extended */
629 			entry = (struct boot_e820_entry *)e820ext->data;
630 		}
631 
632 		entry->addr = d->phys_addr;
633 		entry->size = d->num_pages << PAGE_SHIFT;
634 		entry->type = e820_type;
635 		prev = entry++;
636 		nr_entries++;
637 	}
638 
639 	if (nr_entries > ARRAY_SIZE(params->e820_table)) {
640 		u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table);
641 
642 		add_e820ext(params, e820ext, nr_e820ext);
643 		nr_entries -= nr_e820ext;
644 	}
645 
646 	params->e820_entries = (u8)nr_entries;
647 
648 	return EFI_SUCCESS;
649 }
650 
651 static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext,
652 				  u32 *e820ext_size)
653 {
654 	efi_status_t status;
655 	unsigned long size;
656 
657 	size = sizeof(struct setup_data) +
658 		sizeof(struct e820_entry) * nr_desc;
659 
660 	if (*e820ext) {
661 		efi_bs_call(free_pool, *e820ext);
662 		*e820ext = NULL;
663 		*e820ext_size = 0;
664 	}
665 
666 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
667 			     (void **)e820ext);
668 	if (status == EFI_SUCCESS)
669 		*e820ext_size = size;
670 
671 	return status;
672 }
673 
674 static efi_status_t allocate_e820(struct boot_params *params,
675 				  struct setup_data **e820ext,
676 				  u32 *e820ext_size)
677 {
678 	unsigned long map_size, desc_size, map_key;
679 	efi_status_t status;
680 	__u32 nr_desc, desc_version;
681 
682 	/* Only need the size of the mem map and size of each mem descriptor */
683 	map_size = 0;
684 	status = efi_bs_call(get_memory_map, &map_size, NULL, &map_key,
685 			     &desc_size, &desc_version);
686 	if (status != EFI_BUFFER_TOO_SMALL)
687 		return (status != EFI_SUCCESS) ? status : EFI_UNSUPPORTED;
688 
689 	nr_desc = map_size / desc_size + EFI_MMAP_NR_SLACK_SLOTS;
690 
691 	if (nr_desc > ARRAY_SIZE(params->e820_table)) {
692 		u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table);
693 
694 		status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size);
695 		if (status != EFI_SUCCESS)
696 			return status;
697 	}
698 
699 	return EFI_SUCCESS;
700 }
701 
702 struct exit_boot_struct {
703 	struct boot_params	*boot_params;
704 	struct efi_info		*efi;
705 };
706 
707 static efi_status_t exit_boot_func(struct efi_boot_memmap *map,
708 				   void *priv)
709 {
710 	const char *signature;
711 	struct exit_boot_struct *p = priv;
712 
713 	signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE
714 				   : EFI32_LOADER_SIGNATURE;
715 	memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32));
716 
717 	efi_set_u64_split((unsigned long)efi_system_table,
718 			  &p->efi->efi_systab, &p->efi->efi_systab_hi);
719 	p->efi->efi_memdesc_size	= *map->desc_size;
720 	p->efi->efi_memdesc_version	= *map->desc_ver;
721 	efi_set_u64_split((unsigned long)*map->map,
722 			  &p->efi->efi_memmap, &p->efi->efi_memmap_hi);
723 	p->efi->efi_memmap_size		= *map->map_size;
724 
725 	return EFI_SUCCESS;
726 }
727 
728 static efi_status_t exit_boot(struct boot_params *boot_params, void *handle)
729 {
730 	unsigned long map_sz, key, desc_size, buff_size;
731 	efi_memory_desc_t *mem_map;
732 	struct setup_data *e820ext = NULL;
733 	__u32 e820ext_size = 0;
734 	efi_status_t status;
735 	__u32 desc_version;
736 	struct efi_boot_memmap map;
737 	struct exit_boot_struct priv;
738 
739 	map.map			= &mem_map;
740 	map.map_size		= &map_sz;
741 	map.desc_size		= &desc_size;
742 	map.desc_ver		= &desc_version;
743 	map.key_ptr		= &key;
744 	map.buff_size		= &buff_size;
745 	priv.boot_params	= boot_params;
746 	priv.efi		= &boot_params->efi_info;
747 
748 	status = allocate_e820(boot_params, &e820ext, &e820ext_size);
749 	if (status != EFI_SUCCESS)
750 		return status;
751 
752 	/* Might as well exit boot services now */
753 	status = efi_exit_boot_services(handle, &map, &priv, exit_boot_func);
754 	if (status != EFI_SUCCESS)
755 		return status;
756 
757 	/* Historic? */
758 	boot_params->alt_mem_k	= 32 * 1024;
759 
760 	status = setup_e820(boot_params, e820ext, e820ext_size);
761 	if (status != EFI_SUCCESS)
762 		return status;
763 
764 	return EFI_SUCCESS;
765 }
766 
767 /*
768  * On success, we return the address of startup_32, which has potentially been
769  * relocated by efi_relocate_kernel.
770  * On failure, we exit to the firmware via efi_exit instead of returning.
771  */
772 unsigned long efi_main(efi_handle_t handle,
773 			     efi_system_table_t *sys_table_arg,
774 			     struct boot_params *boot_params)
775 {
776 	unsigned long bzimage_addr = (unsigned long)startup_32;
777 	unsigned long buffer_start, buffer_end;
778 	struct setup_header *hdr = &boot_params->hdr;
779 	unsigned long addr, size;
780 	efi_status_t status;
781 
782 	efi_system_table = sys_table_arg;
783 	/* Check if we were booted by the EFI firmware */
784 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
785 		efi_exit(handle, EFI_INVALID_PARAMETER);
786 
787 	efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID);
788 	if (efi_dxe_table &&
789 	    efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) {
790 		efi_warn("Ignoring DXE services table: invalid signature\n");
791 		efi_dxe_table = NULL;
792 	}
793 
794 	/*
795 	 * If the kernel isn't already loaded at a suitable address,
796 	 * relocate it.
797 	 *
798 	 * It must be loaded above LOAD_PHYSICAL_ADDR.
799 	 *
800 	 * The maximum address for 64-bit is 1 << 46 for 4-level paging. This
801 	 * is defined as the macro MAXMEM, but unfortunately that is not a
802 	 * compile-time constant if 5-level paging is configured, so we instead
803 	 * define our own macro for use here.
804 	 *
805 	 * For 32-bit, the maximum address is complicated to figure out, for
806 	 * now use KERNEL_IMAGE_SIZE, which will be 512MiB, the same as what
807 	 * KASLR uses.
808 	 *
809 	 * Also relocate it if image_offset is zero, i.e. the kernel wasn't
810 	 * loaded by LoadImage, but rather by a bootloader that called the
811 	 * handover entry. The reason we must always relocate in this case is
812 	 * to handle the case of systemd-boot booting a unified kernel image,
813 	 * which is a PE executable that contains the bzImage and an initrd as
814 	 * COFF sections. The initrd section is placed after the bzImage
815 	 * without ensuring that there are at least init_size bytes available
816 	 * for the bzImage, and thus the compressed kernel's startup code may
817 	 * overwrite the initrd unless it is moved out of the way.
818 	 */
819 
820 	buffer_start = ALIGN(bzimage_addr - image_offset,
821 			     hdr->kernel_alignment);
822 	buffer_end = buffer_start + hdr->init_size;
823 
824 	if ((buffer_start < LOAD_PHYSICAL_ADDR)				     ||
825 	    (IS_ENABLED(CONFIG_X86_32) && buffer_end > KERNEL_IMAGE_SIZE)    ||
826 	    (IS_ENABLED(CONFIG_X86_64) && buffer_end > MAXMEM_X86_64_4LEVEL) ||
827 	    (image_offset == 0)) {
828 		extern char _bss[];
829 
830 		status = efi_relocate_kernel(&bzimage_addr,
831 					     (unsigned long)_bss - bzimage_addr,
832 					     hdr->init_size,
833 					     hdr->pref_address,
834 					     hdr->kernel_alignment,
835 					     LOAD_PHYSICAL_ADDR);
836 		if (status != EFI_SUCCESS) {
837 			efi_err("efi_relocate_kernel() failed!\n");
838 			goto fail;
839 		}
840 		/*
841 		 * Now that we've copied the kernel elsewhere, we no longer
842 		 * have a set up block before startup_32(), so reset image_offset
843 		 * to zero in case it was set earlier.
844 		 */
845 		image_offset = 0;
846 	}
847 
848 #ifdef CONFIG_CMDLINE_BOOL
849 	status = efi_parse_options(CONFIG_CMDLINE);
850 	if (status != EFI_SUCCESS) {
851 		efi_err("Failed to parse options\n");
852 		goto fail;
853 	}
854 #endif
855 	if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) {
856 		unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr |
857 					       ((u64)boot_params->ext_cmd_line_ptr << 32));
858 		status = efi_parse_options((char *)cmdline_paddr);
859 		if (status != EFI_SUCCESS) {
860 			efi_err("Failed to parse options\n");
861 			goto fail;
862 		}
863 	}
864 
865 	/*
866 	 * At this point, an initrd may already have been loaded by the
867 	 * bootloader and passed via bootparams. We permit an initrd loaded
868 	 * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it.
869 	 *
870 	 * If the device path is not present, any command-line initrd=
871 	 * arguments will be processed only if image is not NULL, which will be
872 	 * the case only if we were loaded via the PE entry point.
873 	 */
874 	status = efi_load_initrd(image, &addr, &size, hdr->initrd_addr_max,
875 				 ULONG_MAX);
876 	if (status != EFI_SUCCESS)
877 		goto fail;
878 	if (size > 0) {
879 		efi_set_u64_split(addr, &hdr->ramdisk_image,
880 				  &boot_params->ext_ramdisk_image);
881 		efi_set_u64_split(size, &hdr->ramdisk_size,
882 				  &boot_params->ext_ramdisk_size);
883 	}
884 
885 	/*
886 	 * If the boot loader gave us a value for secure_boot then we use that,
887 	 * otherwise we ask the BIOS.
888 	 */
889 	if (boot_params->secure_boot == efi_secureboot_mode_unset)
890 		boot_params->secure_boot = efi_get_secureboot();
891 
892 	/* Ask the firmware to clear memory on unclean shutdown */
893 	efi_enable_reset_attack_mitigation();
894 
895 	efi_random_get_seed();
896 
897 	efi_retrieve_tpm2_eventlog();
898 
899 	setup_graphics(boot_params);
900 
901 	setup_efi_pci(boot_params);
902 
903 	setup_quirks(boot_params, bzimage_addr, buffer_end - buffer_start);
904 
905 	status = exit_boot(boot_params, handle);
906 	if (status != EFI_SUCCESS) {
907 		efi_err("exit_boot() failed!\n");
908 		goto fail;
909 	}
910 
911 	return bzimage_addr;
912 fail:
913 	efi_err("efi_main() failed!\n");
914 
915 	efi_exit(handle, status);
916 }
917