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