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