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 u32 image_offset __section(".data");
27 static efi_loaded_image_t *image = NULL;
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	= pci->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 static void
227 adjust_memory_range_protection(unsigned long start, 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 	if (efi_dxe_table == NULL)
236 		return;
237 
238 	rounded_start = rounddown(start, EFI_PAGE_SIZE);
239 	rounded_end = roundup(start + size, EFI_PAGE_SIZE);
240 
241 	/*
242 	 * Don't modify memory region attributes, they are
243 	 * already suitable, to lower the possibility to
244 	 * encounter firmware bugs.
245 	 */
246 
247 	for (end = start + size; start < end; start = next) {
248 
249 		status = efi_dxe_call(get_memory_space_descriptor, start, &desc);
250 
251 		if (status != EFI_SUCCESS)
252 			return;
253 
254 		next = desc.base_address + desc.length;
255 
256 		/*
257 		 * Only system memory is suitable for trampoline/kernel image placement,
258 		 * so only this type of memory needs its attributes to be modified.
259 		 */
260 
261 		if (desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory ||
262 		    (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0)
263 			continue;
264 
265 		unprotect_start = max(rounded_start, (unsigned long)desc.base_address);
266 		unprotect_size = min(rounded_end, next) - unprotect_start;
267 
268 		status = efi_dxe_call(set_memory_space_attributes,
269 				      unprotect_start, unprotect_size,
270 				      EFI_MEMORY_WB);
271 
272 		if (status != EFI_SUCCESS) {
273 			efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n",
274 				 unprotect_start,
275 				 unprotect_start + unprotect_size,
276 				 status);
277 		}
278 	}
279 }
280 
281 /*
282  * Trampoline takes 2 pages and can be loaded in first megabyte of memory
283  * with its end placed between 128k and 640k where BIOS might start.
284  * (see arch/x86/boot/compressed/pgtable_64.c)
285  *
286  * We cannot find exact trampoline placement since memory map
287  * can be modified by UEFI, and it can alter the computed address.
288  */
289 
290 #define TRAMPOLINE_PLACEMENT_BASE ((128 - 8)*1024)
291 #define TRAMPOLINE_PLACEMENT_SIZE (640*1024 - (128 - 8)*1024)
292 
293 void startup_32(struct boot_params *boot_params);
294 
295 static void
296 setup_memory_protection(unsigned long image_base, unsigned long image_size)
297 {
298 	/*
299 	 * Allow execution of possible trampoline used
300 	 * for switching between 4- and 5-level page tables
301 	 * and relocated kernel image.
302 	 */
303 
304 	adjust_memory_range_protection(TRAMPOLINE_PLACEMENT_BASE,
305 				       TRAMPOLINE_PLACEMENT_SIZE);
306 
307 #ifdef CONFIG_64BIT
308 	if (image_base != (unsigned long)startup_32)
309 		adjust_memory_range_protection(image_base, image_size);
310 #else
311 	/*
312 	 * Clear protection flags on a whole range of possible
313 	 * addresses used for KASLR. We don't need to do that
314 	 * on x86_64, since KASLR/extraction is performed after
315 	 * dedicated identity page tables are built and we only
316 	 * need to remove possible protection on relocated image
317 	 * itself disregarding further relocations.
318 	 */
319 	adjust_memory_range_protection(LOAD_PHYSICAL_ADDR,
320 				       KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR);
321 #endif
322 }
323 
324 static void setup_unaccepted_memory(void)
325 {
326 	efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID;
327 	sev_memory_acceptance_protocol_t *proto;
328 	efi_status_t status;
329 
330 	if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
331 		return;
332 
333 	/*
334 	 * Enable unaccepted memory before calling exit boot services in order
335 	 * for the UEFI to not accept all memory on EBS.
336 	 */
337 	status = efi_bs_call(locate_protocol, &mem_acceptance_proto, NULL,
338 			     (void **)&proto);
339 	if (status != EFI_SUCCESS)
340 		return;
341 
342 	status = efi_call_proto(proto, allow_unaccepted_memory);
343 	if (status != EFI_SUCCESS)
344 		efi_err("Memory acceptance protocol failed\n");
345 }
346 
347 static const efi_char16_t apple[] = L"Apple";
348 
349 static void setup_quirks(struct boot_params *boot_params,
350 			 unsigned long image_base,
351 			 unsigned long image_size)
352 {
353 	efi_char16_t *fw_vendor = (efi_char16_t *)(unsigned long)
354 		efi_table_attr(efi_system_table, fw_vendor);
355 
356 	if (!memcmp(fw_vendor, apple, sizeof(apple))) {
357 		if (IS_ENABLED(CONFIG_APPLE_PROPERTIES))
358 			retrieve_apple_device_properties(boot_params);
359 	}
360 
361 	if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES))
362 		setup_memory_protection(image_base, image_size);
363 }
364 
365 /*
366  * See if we have Universal Graphics Adapter (UGA) protocol
367  */
368 static efi_status_t
369 setup_uga(struct screen_info *si, efi_guid_t *uga_proto, unsigned long size)
370 {
371 	efi_status_t status;
372 	u32 width, height;
373 	void **uga_handle = NULL;
374 	efi_uga_draw_protocol_t *uga = NULL, *first_uga;
375 	efi_handle_t handle;
376 	int i;
377 
378 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
379 			     (void **)&uga_handle);
380 	if (status != EFI_SUCCESS)
381 		return status;
382 
383 	status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
384 			     uga_proto, NULL, &size, uga_handle);
385 	if (status != EFI_SUCCESS)
386 		goto free_handle;
387 
388 	height = 0;
389 	width = 0;
390 
391 	first_uga = NULL;
392 	for_each_efi_handle(handle, uga_handle, size, i) {
393 		efi_guid_t pciio_proto = EFI_PCI_IO_PROTOCOL_GUID;
394 		u32 w, h, depth, refresh;
395 		void *pciio;
396 
397 		status = efi_bs_call(handle_protocol, handle, uga_proto,
398 				     (void **)&uga);
399 		if (status != EFI_SUCCESS)
400 			continue;
401 
402 		pciio = NULL;
403 		efi_bs_call(handle_protocol, handle, &pciio_proto, &pciio);
404 
405 		status = efi_call_proto(uga, get_mode, &w, &h, &depth, &refresh);
406 		if (status == EFI_SUCCESS && (!first_uga || pciio)) {
407 			width = w;
408 			height = h;
409 
410 			/*
411 			 * Once we've found a UGA supporting PCIIO,
412 			 * don't bother looking any further.
413 			 */
414 			if (pciio)
415 				break;
416 
417 			first_uga = uga;
418 		}
419 	}
420 
421 	if (!width && !height)
422 		goto free_handle;
423 
424 	/* EFI framebuffer */
425 	si->orig_video_isVGA	= VIDEO_TYPE_EFI;
426 
427 	si->lfb_depth		= 32;
428 	si->lfb_width		= width;
429 	si->lfb_height		= height;
430 
431 	si->red_size		= 8;
432 	si->red_pos		= 16;
433 	si->green_size		= 8;
434 	si->green_pos		= 8;
435 	si->blue_size		= 8;
436 	si->blue_pos		= 0;
437 	si->rsvd_size		= 8;
438 	si->rsvd_pos		= 24;
439 
440 free_handle:
441 	efi_bs_call(free_pool, uga_handle);
442 
443 	return status;
444 }
445 
446 static void setup_graphics(struct boot_params *boot_params)
447 {
448 	efi_guid_t graphics_proto = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
449 	struct screen_info *si;
450 	efi_guid_t uga_proto = EFI_UGA_PROTOCOL_GUID;
451 	efi_status_t status;
452 	unsigned long size;
453 	void **gop_handle = NULL;
454 	void **uga_handle = NULL;
455 
456 	si = &boot_params->screen_info;
457 	memset(si, 0, sizeof(*si));
458 
459 	size = 0;
460 	status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
461 			     &graphics_proto, NULL, &size, gop_handle);
462 	if (status == EFI_BUFFER_TOO_SMALL)
463 		status = efi_setup_gop(si, &graphics_proto, size);
464 
465 	if (status != EFI_SUCCESS) {
466 		size = 0;
467 		status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
468 				     &uga_proto, NULL, &size, uga_handle);
469 		if (status == EFI_BUFFER_TOO_SMALL)
470 			setup_uga(si, &uga_proto, size);
471 	}
472 }
473 
474 
475 static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status)
476 {
477 	efi_bs_call(exit, handle, status, 0, NULL);
478 	for(;;)
479 		asm("hlt");
480 }
481 
482 void __noreturn efi_stub_entry(efi_handle_t handle,
483 			       efi_system_table_t *sys_table_arg,
484 			       struct boot_params *boot_params);
485 
486 /*
487  * Because the x86 boot code expects to be passed a boot_params we
488  * need to create one ourselves (usually the bootloader would create
489  * one for us).
490  */
491 efi_status_t __efiapi efi_pe_entry(efi_handle_t handle,
492 				   efi_system_table_t *sys_table_arg)
493 {
494 	struct boot_params *boot_params;
495 	struct setup_header *hdr;
496 	void *image_base;
497 	efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID;
498 	int options_size = 0;
499 	efi_status_t status;
500 	char *cmdline_ptr;
501 
502 	efi_system_table = sys_table_arg;
503 
504 	/* Check if we were booted by the EFI firmware */
505 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
506 		efi_exit(handle, EFI_INVALID_PARAMETER);
507 
508 	status = efi_bs_call(handle_protocol, handle, &proto, (void **)&image);
509 	if (status != EFI_SUCCESS) {
510 		efi_err("Failed to get handle for LOADED_IMAGE_PROTOCOL\n");
511 		efi_exit(handle, status);
512 	}
513 
514 	image_base = efi_table_attr(image, image_base);
515 	image_offset = (void *)startup_32 - image_base;
516 
517 	status = efi_allocate_pages(sizeof(struct boot_params),
518 				    (unsigned long *)&boot_params, ULONG_MAX);
519 	if (status != EFI_SUCCESS) {
520 		efi_err("Failed to allocate lowmem for boot params\n");
521 		efi_exit(handle, status);
522 	}
523 
524 	memset(boot_params, 0x0, sizeof(struct boot_params));
525 
526 	hdr = &boot_params->hdr;
527 
528 	/* Copy the setup header from the second sector to boot_params */
529 	memcpy(&hdr->jump, image_base + 512,
530 	       sizeof(struct setup_header) - offsetof(struct setup_header, jump));
531 
532 	/*
533 	 * Fill out some of the header fields ourselves because the
534 	 * EFI firmware loader doesn't load the first sector.
535 	 */
536 	hdr->root_flags	= 1;
537 	hdr->vid_mode	= 0xffff;
538 	hdr->boot_flag	= 0xAA55;
539 
540 	hdr->type_of_loader = 0x21;
541 
542 	/* Convert unicode cmdline to ascii */
543 	cmdline_ptr = efi_convert_cmdline(image, &options_size);
544 	if (!cmdline_ptr)
545 		goto fail;
546 
547 	efi_set_u64_split((unsigned long)cmdline_ptr,
548 			  &hdr->cmd_line_ptr, &boot_params->ext_cmd_line_ptr);
549 
550 	hdr->ramdisk_image = 0;
551 	hdr->ramdisk_size = 0;
552 
553 	/*
554 	 * Disregard any setup data that was provided by the bootloader:
555 	 * setup_data could be pointing anywhere, and we have no way of
556 	 * authenticating or validating the payload.
557 	 */
558 	hdr->setup_data = 0;
559 
560 	efi_stub_entry(handle, sys_table_arg, boot_params);
561 	/* not reached */
562 
563 fail:
564 	efi_free(sizeof(struct boot_params), (unsigned long)boot_params);
565 
566 	efi_exit(handle, status);
567 }
568 
569 static void add_e820ext(struct boot_params *params,
570 			struct setup_data *e820ext, u32 nr_entries)
571 {
572 	struct setup_data *data;
573 
574 	e820ext->type = SETUP_E820_EXT;
575 	e820ext->len  = nr_entries * sizeof(struct boot_e820_entry);
576 	e820ext->next = 0;
577 
578 	data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
579 
580 	while (data && data->next)
581 		data = (struct setup_data *)(unsigned long)data->next;
582 
583 	if (data)
584 		data->next = (unsigned long)e820ext;
585 	else
586 		params->hdr.setup_data = (unsigned long)e820ext;
587 }
588 
589 static efi_status_t
590 setup_e820(struct boot_params *params, struct setup_data *e820ext, u32 e820ext_size)
591 {
592 	struct boot_e820_entry *entry = params->e820_table;
593 	struct efi_info *efi = &params->efi_info;
594 	struct boot_e820_entry *prev = NULL;
595 	u32 nr_entries;
596 	u32 nr_desc;
597 	int i;
598 
599 	nr_entries = 0;
600 	nr_desc = efi->efi_memmap_size / efi->efi_memdesc_size;
601 
602 	for (i = 0; i < nr_desc; i++) {
603 		efi_memory_desc_t *d;
604 		unsigned int e820_type = 0;
605 		unsigned long m = efi->efi_memmap;
606 
607 #ifdef CONFIG_X86_64
608 		m |= (u64)efi->efi_memmap_hi << 32;
609 #endif
610 
611 		d = efi_early_memdesc_ptr(m, efi->efi_memdesc_size, i);
612 		switch (d->type) {
613 		case EFI_RESERVED_TYPE:
614 		case EFI_RUNTIME_SERVICES_CODE:
615 		case EFI_RUNTIME_SERVICES_DATA:
616 		case EFI_MEMORY_MAPPED_IO:
617 		case EFI_MEMORY_MAPPED_IO_PORT_SPACE:
618 		case EFI_PAL_CODE:
619 			e820_type = E820_TYPE_RESERVED;
620 			break;
621 
622 		case EFI_UNUSABLE_MEMORY:
623 			e820_type = E820_TYPE_UNUSABLE;
624 			break;
625 
626 		case EFI_ACPI_RECLAIM_MEMORY:
627 			e820_type = E820_TYPE_ACPI;
628 			break;
629 
630 		case EFI_LOADER_CODE:
631 		case EFI_LOADER_DATA:
632 		case EFI_BOOT_SERVICES_CODE:
633 		case EFI_BOOT_SERVICES_DATA:
634 		case EFI_CONVENTIONAL_MEMORY:
635 			if (efi_soft_reserve_enabled() &&
636 			    (d->attribute & EFI_MEMORY_SP))
637 				e820_type = E820_TYPE_SOFT_RESERVED;
638 			else
639 				e820_type = E820_TYPE_RAM;
640 			break;
641 
642 		case EFI_ACPI_MEMORY_NVS:
643 			e820_type = E820_TYPE_NVS;
644 			break;
645 
646 		case EFI_PERSISTENT_MEMORY:
647 			e820_type = E820_TYPE_PMEM;
648 			break;
649 
650 		case EFI_UNACCEPTED_MEMORY:
651 			if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY)) {
652 				efi_warn_once(
653 "The system has unaccepted memory,  but kernel does not support it\nConsider enabling CONFIG_UNACCEPTED_MEMORY\n");
654 				continue;
655 			}
656 			e820_type = E820_TYPE_RAM;
657 			process_unaccepted_memory(d->phys_addr,
658 						  d->phys_addr + PAGE_SIZE * d->num_pages);
659 			break;
660 		default:
661 			continue;
662 		}
663 
664 		/* Merge adjacent mappings */
665 		if (prev && prev->type == e820_type &&
666 		    (prev->addr + prev->size) == d->phys_addr) {
667 			prev->size += d->num_pages << 12;
668 			continue;
669 		}
670 
671 		if (nr_entries == ARRAY_SIZE(params->e820_table)) {
672 			u32 need = (nr_desc - i) * sizeof(struct e820_entry) +
673 				   sizeof(struct setup_data);
674 
675 			if (!e820ext || e820ext_size < need)
676 				return EFI_BUFFER_TOO_SMALL;
677 
678 			/* boot_params map full, switch to e820 extended */
679 			entry = (struct boot_e820_entry *)e820ext->data;
680 		}
681 
682 		entry->addr = d->phys_addr;
683 		entry->size = d->num_pages << PAGE_SHIFT;
684 		entry->type = e820_type;
685 		prev = entry++;
686 		nr_entries++;
687 	}
688 
689 	if (nr_entries > ARRAY_SIZE(params->e820_table)) {
690 		u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table);
691 
692 		add_e820ext(params, e820ext, nr_e820ext);
693 		nr_entries -= nr_e820ext;
694 	}
695 
696 	params->e820_entries = (u8)nr_entries;
697 
698 	return EFI_SUCCESS;
699 }
700 
701 static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext,
702 				  u32 *e820ext_size)
703 {
704 	efi_status_t status;
705 	unsigned long size;
706 
707 	size = sizeof(struct setup_data) +
708 		sizeof(struct e820_entry) * nr_desc;
709 
710 	if (*e820ext) {
711 		efi_bs_call(free_pool, *e820ext);
712 		*e820ext = NULL;
713 		*e820ext_size = 0;
714 	}
715 
716 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
717 			     (void **)e820ext);
718 	if (status == EFI_SUCCESS)
719 		*e820ext_size = size;
720 
721 	return status;
722 }
723 
724 static efi_status_t allocate_e820(struct boot_params *params,
725 				  struct setup_data **e820ext,
726 				  u32 *e820ext_size)
727 {
728 	struct efi_boot_memmap *map;
729 	efi_status_t status;
730 	__u32 nr_desc;
731 
732 	status = efi_get_memory_map(&map, false);
733 	if (status != EFI_SUCCESS)
734 		return status;
735 
736 	nr_desc = map->map_size / map->desc_size;
737 	if (nr_desc > ARRAY_SIZE(params->e820_table) - EFI_MMAP_NR_SLACK_SLOTS) {
738 		u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table) +
739 				 EFI_MMAP_NR_SLACK_SLOTS;
740 
741 		status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size);
742 	}
743 
744 	if (IS_ENABLED(CONFIG_UNACCEPTED_MEMORY) && status == EFI_SUCCESS)
745 		status = allocate_unaccepted_bitmap(nr_desc, map);
746 
747 	efi_bs_call(free_pool, map);
748 	return status;
749 }
750 
751 struct exit_boot_struct {
752 	struct boot_params	*boot_params;
753 	struct efi_info		*efi;
754 };
755 
756 static efi_status_t exit_boot_func(struct efi_boot_memmap *map,
757 				   void *priv)
758 {
759 	const char *signature;
760 	struct exit_boot_struct *p = priv;
761 
762 	signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE
763 				   : EFI32_LOADER_SIGNATURE;
764 	memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32));
765 
766 	efi_set_u64_split((unsigned long)efi_system_table,
767 			  &p->efi->efi_systab, &p->efi->efi_systab_hi);
768 	p->efi->efi_memdesc_size	= map->desc_size;
769 	p->efi->efi_memdesc_version	= map->desc_ver;
770 	efi_set_u64_split((unsigned long)map->map,
771 			  &p->efi->efi_memmap, &p->efi->efi_memmap_hi);
772 	p->efi->efi_memmap_size		= map->map_size;
773 
774 	return EFI_SUCCESS;
775 }
776 
777 static efi_status_t exit_boot(struct boot_params *boot_params, void *handle)
778 {
779 	struct setup_data *e820ext = NULL;
780 	__u32 e820ext_size = 0;
781 	efi_status_t status;
782 	struct exit_boot_struct priv;
783 
784 	priv.boot_params	= boot_params;
785 	priv.efi		= &boot_params->efi_info;
786 
787 	status = allocate_e820(boot_params, &e820ext, &e820ext_size);
788 	if (status != EFI_SUCCESS)
789 		return status;
790 
791 	/* Might as well exit boot services now */
792 	status = efi_exit_boot_services(handle, &priv, exit_boot_func);
793 	if (status != EFI_SUCCESS)
794 		return status;
795 
796 	/* Historic? */
797 	boot_params->alt_mem_k	= 32 * 1024;
798 
799 	status = setup_e820(boot_params, e820ext, e820ext_size);
800 	if (status != EFI_SUCCESS)
801 		return status;
802 
803 	return EFI_SUCCESS;
804 }
805 
806 /*
807  * On success, we return the address of startup_32, which has potentially been
808  * relocated by efi_relocate_kernel.
809  * On failure, we exit to the firmware via efi_exit instead of returning.
810  */
811 asmlinkage unsigned long efi_main(efi_handle_t handle,
812 				  efi_system_table_t *sys_table_arg,
813 				  struct boot_params *boot_params)
814 {
815 	unsigned long bzimage_addr = (unsigned long)startup_32;
816 	unsigned long buffer_start, buffer_end;
817 	struct setup_header *hdr = &boot_params->hdr;
818 	const struct linux_efi_initrd *initrd = NULL;
819 	efi_status_t status;
820 
821 	efi_system_table = sys_table_arg;
822 	/* Check if we were booted by the EFI firmware */
823 	if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
824 		efi_exit(handle, EFI_INVALID_PARAMETER);
825 
826 	efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID);
827 	if (efi_dxe_table &&
828 	    efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) {
829 		efi_warn("Ignoring DXE services table: invalid signature\n");
830 		efi_dxe_table = NULL;
831 	}
832 
833 	/*
834 	 * If the kernel isn't already loaded at a suitable address,
835 	 * relocate it.
836 	 *
837 	 * It must be loaded above LOAD_PHYSICAL_ADDR.
838 	 *
839 	 * The maximum address for 64-bit is 1 << 46 for 4-level paging. This
840 	 * is defined as the macro MAXMEM, but unfortunately that is not a
841 	 * compile-time constant if 5-level paging is configured, so we instead
842 	 * define our own macro for use here.
843 	 *
844 	 * For 32-bit, the maximum address is complicated to figure out, for
845 	 * now use KERNEL_IMAGE_SIZE, which will be 512MiB, the same as what
846 	 * KASLR uses.
847 	 *
848 	 * Also relocate it if image_offset is zero, i.e. the kernel wasn't
849 	 * loaded by LoadImage, but rather by a bootloader that called the
850 	 * handover entry. The reason we must always relocate in this case is
851 	 * to handle the case of systemd-boot booting a unified kernel image,
852 	 * which is a PE executable that contains the bzImage and an initrd as
853 	 * COFF sections. The initrd section is placed after the bzImage
854 	 * without ensuring that there are at least init_size bytes available
855 	 * for the bzImage, and thus the compressed kernel's startup code may
856 	 * overwrite the initrd unless it is moved out of the way.
857 	 */
858 
859 	buffer_start = ALIGN(bzimage_addr - image_offset,
860 			     hdr->kernel_alignment);
861 	buffer_end = buffer_start + hdr->init_size;
862 
863 	if ((buffer_start < LOAD_PHYSICAL_ADDR)				     ||
864 	    (IS_ENABLED(CONFIG_X86_32) && buffer_end > KERNEL_IMAGE_SIZE)    ||
865 	    (IS_ENABLED(CONFIG_X86_64) && buffer_end > MAXMEM_X86_64_4LEVEL) ||
866 	    (image_offset == 0)) {
867 		extern char _bss[];
868 
869 		status = efi_relocate_kernel(&bzimage_addr,
870 					     (unsigned long)_bss - bzimage_addr,
871 					     hdr->init_size,
872 					     hdr->pref_address,
873 					     hdr->kernel_alignment,
874 					     LOAD_PHYSICAL_ADDR);
875 		if (status != EFI_SUCCESS) {
876 			efi_err("efi_relocate_kernel() failed!\n");
877 			goto fail;
878 		}
879 		/*
880 		 * Now that we've copied the kernel elsewhere, we no longer
881 		 * have a set up block before startup_32(), so reset image_offset
882 		 * to zero in case it was set earlier.
883 		 */
884 		image_offset = 0;
885 	}
886 
887 #ifdef CONFIG_CMDLINE_BOOL
888 	status = efi_parse_options(CONFIG_CMDLINE);
889 	if (status != EFI_SUCCESS) {
890 		efi_err("Failed to parse options\n");
891 		goto fail;
892 	}
893 #endif
894 	if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) {
895 		unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr |
896 					       ((u64)boot_params->ext_cmd_line_ptr << 32));
897 		status = efi_parse_options((char *)cmdline_paddr);
898 		if (status != EFI_SUCCESS) {
899 			efi_err("Failed to parse options\n");
900 			goto fail;
901 		}
902 	}
903 
904 	/*
905 	 * At this point, an initrd may already have been loaded by the
906 	 * bootloader and passed via bootparams. We permit an initrd loaded
907 	 * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it.
908 	 *
909 	 * If the device path is not present, any command-line initrd=
910 	 * arguments will be processed only if image is not NULL, which will be
911 	 * the case only if we were loaded via the PE entry point.
912 	 */
913 	status = efi_load_initrd(image, hdr->initrd_addr_max, ULONG_MAX,
914 				 &initrd);
915 	if (status != EFI_SUCCESS)
916 		goto fail;
917 	if (initrd && initrd->size > 0) {
918 		efi_set_u64_split(initrd->base, &hdr->ramdisk_image,
919 				  &boot_params->ext_ramdisk_image);
920 		efi_set_u64_split(initrd->size, &hdr->ramdisk_size,
921 				  &boot_params->ext_ramdisk_size);
922 	}
923 
924 
925 	/*
926 	 * If the boot loader gave us a value for secure_boot then we use that,
927 	 * otherwise we ask the BIOS.
928 	 */
929 	if (boot_params->secure_boot == efi_secureboot_mode_unset)
930 		boot_params->secure_boot = efi_get_secureboot();
931 
932 	/* Ask the firmware to clear memory on unclean shutdown */
933 	efi_enable_reset_attack_mitigation();
934 
935 	efi_random_get_seed();
936 
937 	efi_retrieve_tpm2_eventlog();
938 
939 	setup_graphics(boot_params);
940 
941 	setup_efi_pci(boot_params);
942 
943 	setup_quirks(boot_params, bzimage_addr, buffer_end - buffer_start);
944 
945 	setup_unaccepted_memory();
946 
947 	status = exit_boot(boot_params, handle);
948 	if (status != EFI_SUCCESS) {
949 		efi_err("exit_boot() failed!\n");
950 		goto fail;
951 	}
952 
953 	return bzimage_addr;
954 fail:
955 	efi_err("efi_main() failed!\n");
956 
957 	efi_exit(handle, status);
958 }
959