Merge tag 'block-6.9-20240315' of git://git.kernel.dk/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 const efi_system_table_t *efi_system_table;
25 const efi_dxe_services_table_t *efi_dxe_table;
26 static efi_loaded_image_t *image = NULL;
27 static efi_memory_attribute_protocol_t *memattr;
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     = 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 efi_status_t efi_adjust_memory_range_protection(unsigned long start,
227                                                 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         rounded_start = rounddown(start, EFI_PAGE_SIZE);
236         rounded_end = roundup(start + size, EFI_PAGE_SIZE);
237
238         if (memattr != NULL) {
239                 status = efi_call_proto(memattr, set_memory_attributes,
240                                         rounded_start,
241                                         rounded_end - rounded_start,
242                                         EFI_MEMORY_RO);
243                 if (status != EFI_SUCCESS) {
244                         efi_warn("Failed to set EFI_MEMORY_RO attribute\n");
245                         return status;
246                 }
247
248                 status = efi_call_proto(memattr, clear_memory_attributes,
249                                         rounded_start,
250                                         rounded_end - rounded_start,
251                                         EFI_MEMORY_XP);
252                 if (status != EFI_SUCCESS)
253                         efi_warn("Failed to clear EFI_MEMORY_XP attribute\n");
254                 return status;
255         }
256
257         if (efi_dxe_table == NULL)
258                 return EFI_SUCCESS;
259
260         /*
261          * Don't modify memory region attributes, they are
262          * already suitable, to lower the possibility to
263          * encounter firmware bugs.
264          */
265
266         for (end = start + size; start < end; start = next) {
267
268                 status = efi_dxe_call(get_memory_space_descriptor, start, &desc);
269
270                 if (status != EFI_SUCCESS)
271                         break;
272
273                 next = desc.base_address + desc.length;
274
275                 /*
276                  * Only system memory is suitable for trampoline/kernel image placement,
277                  * so only this type of memory needs its attributes to be modified.
278                  */
279
280                 if (desc.gcd_memory_type != EfiGcdMemoryTypeSystemMemory ||
281                     (desc.attributes & (EFI_MEMORY_RO | EFI_MEMORY_XP)) == 0)
282                         continue;
283
284                 unprotect_start = max(rounded_start, (unsigned long)desc.base_address);
285                 unprotect_size = min(rounded_end, next) - unprotect_start;
286
287                 status = efi_dxe_call(set_memory_space_attributes,
288                                       unprotect_start, unprotect_size,
289                                       EFI_MEMORY_WB);
290
291                 if (status != EFI_SUCCESS) {
292                         efi_warn("Unable to unprotect memory range [%08lx,%08lx]: %lx\n",
293                                  unprotect_start,
294                                  unprotect_start + unprotect_size,
295                                  status);
296                         break;
297                 }
298         }
299         return EFI_SUCCESS;
300 }
301
302 static void setup_unaccepted_memory(void)
303 {
304         efi_guid_t mem_acceptance_proto = OVMF_SEV_MEMORY_ACCEPTANCE_PROTOCOL_GUID;
305         sev_memory_acceptance_protocol_t *proto;
306         efi_status_t status;
307
308         if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
309                 return;
310
311         /*
312          * Enable unaccepted memory before calling exit boot services in order
313          * for the UEFI to not accept all memory on EBS.
314          */
315         status = efi_bs_call(locate_protocol, &mem_acceptance_proto, NULL,
316                              (void **)&proto);
317         if (status != EFI_SUCCESS)
318                 return;
319
320         status = efi_call_proto(proto, allow_unaccepted_memory);
321         if (status != EFI_SUCCESS)
322                 efi_err("Memory acceptance protocol failed\n");
323 }
324
325 static efi_char16_t *efistub_fw_vendor(void)
326 {
327         unsigned long vendor = efi_table_attr(efi_system_table, fw_vendor);
328
329         return (efi_char16_t *)vendor;
330 }
331
332 static const efi_char16_t apple[] = L"Apple";
333
334 static void setup_quirks(struct boot_params *boot_params)
335 {
336         if (IS_ENABLED(CONFIG_APPLE_PROPERTIES) &&
337             !memcmp(efistub_fw_vendor(), apple, sizeof(apple)))
338                 retrieve_apple_device_properties(boot_params);
339 }
340
341 /*
342  * See if we have Universal Graphics Adapter (UGA) protocol
343  */
344 static efi_status_t
345 setup_uga(struct screen_info *si, efi_guid_t *uga_proto, unsigned long size)
346 {
347         efi_status_t status;
348         u32 width, height;
349         void **uga_handle = NULL;
350         efi_uga_draw_protocol_t *uga = NULL, *first_uga;
351         efi_handle_t handle;
352         int i;
353
354         status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
355                              (void **)&uga_handle);
356         if (status != EFI_SUCCESS)
357                 return status;
358
359         status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
360                              uga_proto, NULL, &size, uga_handle);
361         if (status != EFI_SUCCESS)
362                 goto free_handle;
363
364         height = 0;
365         width = 0;
366
367         first_uga = NULL;
368         for_each_efi_handle(handle, uga_handle, size, i) {
369                 efi_guid_t pciio_proto = EFI_PCI_IO_PROTOCOL_GUID;
370                 u32 w, h, depth, refresh;
371                 void *pciio;
372
373                 status = efi_bs_call(handle_protocol, handle, uga_proto,
374                                      (void **)&uga);
375                 if (status != EFI_SUCCESS)
376                         continue;
377
378                 pciio = NULL;
379                 efi_bs_call(handle_protocol, handle, &pciio_proto, &pciio);
380
381                 status = efi_call_proto(uga, get_mode, &w, &h, &depth, &refresh);
382                 if (status == EFI_SUCCESS && (!first_uga || pciio)) {
383                         width = w;
384                         height = h;
385
386                         /*
387                          * Once we've found a UGA supporting PCIIO,
388                          * don't bother looking any further.
389                          */
390                         if (pciio)
391                                 break;
392
393                         first_uga = uga;
394                 }
395         }
396
397         if (!width && !height)
398                 goto free_handle;
399
400         /* EFI framebuffer */
401         si->orig_video_isVGA    = VIDEO_TYPE_EFI;
402
403         si->lfb_depth           = 32;
404         si->lfb_width           = width;
405         si->lfb_height          = height;
406
407         si->red_size            = 8;
408         si->red_pos             = 16;
409         si->green_size          = 8;
410         si->green_pos           = 8;
411         si->blue_size           = 8;
412         si->blue_pos            = 0;
413         si->rsvd_size           = 8;
414         si->rsvd_pos            = 24;
415
416 free_handle:
417         efi_bs_call(free_pool, uga_handle);
418
419         return status;
420 }
421
422 static void setup_graphics(struct boot_params *boot_params)
423 {
424         efi_guid_t graphics_proto = EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
425         struct screen_info *si;
426         efi_guid_t uga_proto = EFI_UGA_PROTOCOL_GUID;
427         efi_status_t status;
428         unsigned long size;
429         void **gop_handle = NULL;
430         void **uga_handle = NULL;
431
432         si = &boot_params->screen_info;
433         memset(si, 0, sizeof(*si));
434
435         size = 0;
436         status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
437                              &graphics_proto, NULL, &size, gop_handle);
438         if (status == EFI_BUFFER_TOO_SMALL)
439                 status = efi_setup_gop(si, &graphics_proto, size);
440
441         if (status != EFI_SUCCESS) {
442                 size = 0;
443                 status = efi_bs_call(locate_handle, EFI_LOCATE_BY_PROTOCOL,
444                                      &uga_proto, NULL, &size, uga_handle);
445                 if (status == EFI_BUFFER_TOO_SMALL)
446                         setup_uga(si, &uga_proto, size);
447         }
448 }
449
450
451 static void __noreturn efi_exit(efi_handle_t handle, efi_status_t status)
452 {
453         efi_bs_call(exit, handle, status, 0, NULL);
454         for(;;)
455                 asm("hlt");
456 }
457
458 void __noreturn efi_stub_entry(efi_handle_t handle,
459                                efi_system_table_t *sys_table_arg,
460                                struct boot_params *boot_params);
461
462 /*
463  * Because the x86 boot code expects to be passed a boot_params we
464  * need to create one ourselves (usually the bootloader would create
465  * one for us).
466  */
467 efi_status_t __efiapi efi_pe_entry(efi_handle_t handle,
468                                    efi_system_table_t *sys_table_arg)
469 {
470         static struct boot_params boot_params __page_aligned_bss;
471         struct setup_header *hdr = &boot_params.hdr;
472         efi_guid_t proto = LOADED_IMAGE_PROTOCOL_GUID;
473         int options_size = 0;
474         efi_status_t status;
475         char *cmdline_ptr;
476
477         efi_system_table = sys_table_arg;
478
479         /* Check if we were booted by the EFI firmware */
480         if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
481                 efi_exit(handle, EFI_INVALID_PARAMETER);
482
483         status = efi_bs_call(handle_protocol, handle, &proto, (void **)&image);
484         if (status != EFI_SUCCESS) {
485                 efi_err("Failed to get handle for LOADED_IMAGE_PROTOCOL\n");
486                 efi_exit(handle, status);
487         }
488
489         /* Assign the setup_header fields that the kernel actually cares about */
490         hdr->root_flags = 1;
491         hdr->vid_mode   = 0xffff;
492
493         hdr->type_of_loader = 0x21;
494
495         /* Convert unicode cmdline to ascii */
496         cmdline_ptr = efi_convert_cmdline(image, &options_size);
497         if (!cmdline_ptr)
498                 goto fail;
499
500         efi_set_u64_split((unsigned long)cmdline_ptr, &hdr->cmd_line_ptr,
501                           &boot_params.ext_cmd_line_ptr);
502
503         efi_stub_entry(handle, sys_table_arg, &boot_params);
504         /* not reached */
505
506 fail:
507         efi_exit(handle, status);
508 }
509
510 static void add_e820ext(struct boot_params *params,
511                         struct setup_data *e820ext, u32 nr_entries)
512 {
513         struct setup_data *data;
514
515         e820ext->type = SETUP_E820_EXT;
516         e820ext->len  = nr_entries * sizeof(struct boot_e820_entry);
517         e820ext->next = 0;
518
519         data = (struct setup_data *)(unsigned long)params->hdr.setup_data;
520
521         while (data && data->next)
522                 data = (struct setup_data *)(unsigned long)data->next;
523
524         if (data)
525                 data->next = (unsigned long)e820ext;
526         else
527                 params->hdr.setup_data = (unsigned long)e820ext;
528 }
529
530 static efi_status_t
531 setup_e820(struct boot_params *params, struct setup_data *e820ext, u32 e820ext_size)
532 {
533         struct boot_e820_entry *entry = params->e820_table;
534         struct efi_info *efi = &params->efi_info;
535         struct boot_e820_entry *prev = NULL;
536         u32 nr_entries;
537         u32 nr_desc;
538         int i;
539
540         nr_entries = 0;
541         nr_desc = efi->efi_memmap_size / efi->efi_memdesc_size;
542
543         for (i = 0; i < nr_desc; i++) {
544                 efi_memory_desc_t *d;
545                 unsigned int e820_type = 0;
546                 unsigned long m = efi->efi_memmap;
547
548 #ifdef CONFIG_X86_64
549                 m |= (u64)efi->efi_memmap_hi << 32;
550 #endif
551
552                 d = efi_early_memdesc_ptr(m, efi->efi_memdesc_size, i);
553                 switch (d->type) {
554                 case EFI_RESERVED_TYPE:
555                 case EFI_RUNTIME_SERVICES_CODE:
556                 case EFI_RUNTIME_SERVICES_DATA:
557                 case EFI_MEMORY_MAPPED_IO:
558                 case EFI_MEMORY_MAPPED_IO_PORT_SPACE:
559                 case EFI_PAL_CODE:
560                         e820_type = E820_TYPE_RESERVED;
561                         break;
562
563                 case EFI_UNUSABLE_MEMORY:
564                         e820_type = E820_TYPE_UNUSABLE;
565                         break;
566
567                 case EFI_ACPI_RECLAIM_MEMORY:
568                         e820_type = E820_TYPE_ACPI;
569                         break;
570
571                 case EFI_LOADER_CODE:
572                 case EFI_LOADER_DATA:
573                 case EFI_BOOT_SERVICES_CODE:
574                 case EFI_BOOT_SERVICES_DATA:
575                 case EFI_CONVENTIONAL_MEMORY:
576                         if (efi_soft_reserve_enabled() &&
577                             (d->attribute & EFI_MEMORY_SP))
578                                 e820_type = E820_TYPE_SOFT_RESERVED;
579                         else
580                                 e820_type = E820_TYPE_RAM;
581                         break;
582
583                 case EFI_ACPI_MEMORY_NVS:
584                         e820_type = E820_TYPE_NVS;
585                         break;
586
587                 case EFI_PERSISTENT_MEMORY:
588                         e820_type = E820_TYPE_PMEM;
589                         break;
590
591                 case EFI_UNACCEPTED_MEMORY:
592                         if (!IS_ENABLED(CONFIG_UNACCEPTED_MEMORY))
593                                 continue;
594                         e820_type = E820_TYPE_RAM;
595                         process_unaccepted_memory(d->phys_addr,
596                                                   d->phys_addr + PAGE_SIZE * d->num_pages);
597                         break;
598                 default:
599                         continue;
600                 }
601
602                 /* Merge adjacent mappings */
603                 if (prev && prev->type == e820_type &&
604                     (prev->addr + prev->size) == d->phys_addr) {
605                         prev->size += d->num_pages << 12;
606                         continue;
607                 }
608
609                 if (nr_entries == ARRAY_SIZE(params->e820_table)) {
610                         u32 need = (nr_desc - i) * sizeof(struct e820_entry) +
611                                    sizeof(struct setup_data);
612
613                         if (!e820ext || e820ext_size < need)
614                                 return EFI_BUFFER_TOO_SMALL;
615
616                         /* boot_params map full, switch to e820 extended */
617                         entry = (struct boot_e820_entry *)e820ext->data;
618                 }
619
620                 entry->addr = d->phys_addr;
621                 entry->size = d->num_pages << PAGE_SHIFT;
622                 entry->type = e820_type;
623                 prev = entry++;
624                 nr_entries++;
625         }
626
627         if (nr_entries > ARRAY_SIZE(params->e820_table)) {
628                 u32 nr_e820ext = nr_entries - ARRAY_SIZE(params->e820_table);
629
630                 add_e820ext(params, e820ext, nr_e820ext);
631                 nr_entries -= nr_e820ext;
632         }
633
634         params->e820_entries = (u8)nr_entries;
635
636         return EFI_SUCCESS;
637 }
638
639 static efi_status_t alloc_e820ext(u32 nr_desc, struct setup_data **e820ext,
640                                   u32 *e820ext_size)
641 {
642         efi_status_t status;
643         unsigned long size;
644
645         size = sizeof(struct setup_data) +
646                 sizeof(struct e820_entry) * nr_desc;
647
648         if (*e820ext) {
649                 efi_bs_call(free_pool, *e820ext);
650                 *e820ext = NULL;
651                 *e820ext_size = 0;
652         }
653
654         status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size,
655                              (void **)e820ext);
656         if (status == EFI_SUCCESS)
657                 *e820ext_size = size;
658
659         return status;
660 }
661
662 static efi_status_t allocate_e820(struct boot_params *params,
663                                   struct setup_data **e820ext,
664                                   u32 *e820ext_size)
665 {
666         struct efi_boot_memmap *map;
667         efi_status_t status;
668         __u32 nr_desc;
669
670         status = efi_get_memory_map(&map, false);
671         if (status != EFI_SUCCESS)
672                 return status;
673
674         nr_desc = map->map_size / map->desc_size;
675         if (nr_desc > ARRAY_SIZE(params->e820_table) - EFI_MMAP_NR_SLACK_SLOTS) {
676                 u32 nr_e820ext = nr_desc - ARRAY_SIZE(params->e820_table) +
677                                  EFI_MMAP_NR_SLACK_SLOTS;
678
679                 status = alloc_e820ext(nr_e820ext, e820ext, e820ext_size);
680         }
681
682         if (IS_ENABLED(CONFIG_UNACCEPTED_MEMORY) && status == EFI_SUCCESS)
683                 status = allocate_unaccepted_bitmap(nr_desc, map);
684
685         efi_bs_call(free_pool, map);
686         return status;
687 }
688
689 struct exit_boot_struct {
690         struct boot_params      *boot_params;
691         struct efi_info         *efi;
692 };
693
694 static efi_status_t exit_boot_func(struct efi_boot_memmap *map,
695                                    void *priv)
696 {
697         const char *signature;
698         struct exit_boot_struct *p = priv;
699
700         signature = efi_is_64bit() ? EFI64_LOADER_SIGNATURE
701                                    : EFI32_LOADER_SIGNATURE;
702         memcpy(&p->efi->efi_loader_signature, signature, sizeof(__u32));
703
704         efi_set_u64_split((unsigned long)efi_system_table,
705                           &p->efi->efi_systab, &p->efi->efi_systab_hi);
706         p->efi->efi_memdesc_size        = map->desc_size;
707         p->efi->efi_memdesc_version     = map->desc_ver;
708         efi_set_u64_split((unsigned long)map->map,
709                           &p->efi->efi_memmap, &p->efi->efi_memmap_hi);
710         p->efi->efi_memmap_size         = map->map_size;
711
712         return EFI_SUCCESS;
713 }
714
715 static efi_status_t exit_boot(struct boot_params *boot_params, void *handle)
716 {
717         struct setup_data *e820ext = NULL;
718         __u32 e820ext_size = 0;
719         efi_status_t status;
720         struct exit_boot_struct priv;
721
722         priv.boot_params        = boot_params;
723         priv.efi                = &boot_params->efi_info;
724
725         status = allocate_e820(boot_params, &e820ext, &e820ext_size);
726         if (status != EFI_SUCCESS)
727                 return status;
728
729         /* Might as well exit boot services now */
730         status = efi_exit_boot_services(handle, &priv, exit_boot_func);
731         if (status != EFI_SUCCESS)
732                 return status;
733
734         /* Historic? */
735         boot_params->alt_mem_k  = 32 * 1024;
736
737         status = setup_e820(boot_params, e820ext, e820ext_size);
738         if (status != EFI_SUCCESS)
739                 return status;
740
741         return EFI_SUCCESS;
742 }
743
744 static bool have_unsupported_snp_features(void)
745 {
746         u64 unsupported;
747
748         unsupported = snp_get_unsupported_features(sev_get_status());
749         if (unsupported) {
750                 efi_err("Unsupported SEV-SNP features detected: 0x%llx\n",
751                         unsupported);
752                 return true;
753         }
754         return false;
755 }
756
757 static void efi_get_seed(void *seed, int size)
758 {
759         efi_get_random_bytes(size, seed);
760
761         /*
762          * This only updates seed[0] when running on 32-bit, but in that case,
763          * seed[1] is not used anyway, as there is no virtual KASLR on 32-bit.
764          */
765         *(unsigned long *)seed ^= kaslr_get_random_long("EFI");
766 }
767
768 static void error(char *str)
769 {
770         efi_warn("Decompression failed: %s\n", str);
771 }
772
773 static efi_status_t efi_decompress_kernel(unsigned long *kernel_entry)
774 {
775         unsigned long virt_addr = LOAD_PHYSICAL_ADDR;
776         unsigned long addr, alloc_size, entry;
777         efi_status_t status;
778         u32 seed[2] = {};
779
780         /* determine the required size of the allocation */
781         alloc_size = ALIGN(max_t(unsigned long, output_len, kernel_total_size),
782                            MIN_KERNEL_ALIGN);
783
784         if (IS_ENABLED(CONFIG_RANDOMIZE_BASE) && !efi_nokaslr) {
785                 u64 range = KERNEL_IMAGE_SIZE - LOAD_PHYSICAL_ADDR - kernel_total_size;
786                 static const efi_char16_t ami[] = L"American Megatrends";
787
788                 efi_get_seed(seed, sizeof(seed));
789
790                 virt_addr += (range * seed[1]) >> 32;
791                 virt_addr &= ~(CONFIG_PHYSICAL_ALIGN - 1);
792
793                 /*
794                  * Older Dell systems with AMI UEFI firmware v2.0 may hang
795                  * while decompressing the kernel if physical address
796                  * randomization is enabled.
797                  *
798                  * https://bugzilla.kernel.org/show_bug.cgi?id=218173
799                  */
800                 if (efi_system_table->hdr.revision <= EFI_2_00_SYSTEM_TABLE_REVISION &&
801                     !memcmp(efistub_fw_vendor(), ami, sizeof(ami))) {
802                         efi_debug("AMI firmware v2.0 or older detected - disabling physical KASLR\n");
803                         seed[0] = 0;
804                 }
805
806                 boot_params_ptr->hdr.loadflags |= KASLR_FLAG;
807         }
808
809         status = efi_random_alloc(alloc_size, CONFIG_PHYSICAL_ALIGN, &addr,
810                                   seed[0], EFI_LOADER_CODE,
811                                   LOAD_PHYSICAL_ADDR,
812                                   EFI_X86_KERNEL_ALLOC_LIMIT);
813         if (status != EFI_SUCCESS)
814                 return status;
815
816         entry = decompress_kernel((void *)addr, virt_addr, error);
817         if (entry == ULONG_MAX) {
818                 efi_free(alloc_size, addr);
819                 return EFI_LOAD_ERROR;
820         }
821
822         *kernel_entry = addr + entry;
823
824         return efi_adjust_memory_range_protection(addr, kernel_text_size);
825 }
826
827 static void __noreturn enter_kernel(unsigned long kernel_addr,
828                                     struct boot_params *boot_params)
829 {
830         /* enter decompressed kernel with boot_params pointer in RSI/ESI */
831         asm("jmp *%0"::"r"(kernel_addr), "S"(boot_params));
832
833         unreachable();
834 }
835
836 /*
837  * On success, this routine will jump to the relocated image directly and never
838  * return.  On failure, it will exit to the firmware via efi_exit() instead of
839  * returning.
840  */
841 void __noreturn efi_stub_entry(efi_handle_t handle,
842                                efi_system_table_t *sys_table_arg,
843                                struct boot_params *boot_params)
844 {
845         efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID;
846         struct setup_header *hdr = &boot_params->hdr;
847         const struct linux_efi_initrd *initrd = NULL;
848         unsigned long kernel_entry;
849         efi_status_t status;
850
851         boot_params_ptr = boot_params;
852
853         efi_system_table = sys_table_arg;
854         /* Check if we were booted by the EFI firmware */
855         if (efi_system_table->hdr.signature != EFI_SYSTEM_TABLE_SIGNATURE)
856                 efi_exit(handle, EFI_INVALID_PARAMETER);
857
858         if (have_unsupported_snp_features())
859                 efi_exit(handle, EFI_UNSUPPORTED);
860
861         if (IS_ENABLED(CONFIG_EFI_DXE_MEM_ATTRIBUTES)) {
862                 efi_dxe_table = get_efi_config_table(EFI_DXE_SERVICES_TABLE_GUID);
863                 if (efi_dxe_table &&
864                     efi_dxe_table->hdr.signature != EFI_DXE_SERVICES_TABLE_SIGNATURE) {
865                         efi_warn("Ignoring DXE services table: invalid signature\n");
866                         efi_dxe_table = NULL;
867                 }
868         }
869
870         /* grab the memory attributes protocol if it exists */
871         efi_bs_call(locate_protocol, &guid, NULL, (void **)&memattr);
872
873         status = efi_setup_5level_paging();
874         if (status != EFI_SUCCESS) {
875                 efi_err("efi_setup_5level_paging() failed!\n");
876                 goto fail;
877         }
878
879 #ifdef CONFIG_CMDLINE_BOOL
880         status = efi_parse_options(CONFIG_CMDLINE);
881         if (status != EFI_SUCCESS) {
882                 efi_err("Failed to parse options\n");
883                 goto fail;
884         }
885 #endif
886         if (!IS_ENABLED(CONFIG_CMDLINE_OVERRIDE)) {
887                 unsigned long cmdline_paddr = ((u64)hdr->cmd_line_ptr |
888                                                ((u64)boot_params->ext_cmd_line_ptr << 32));
889                 status = efi_parse_options((char *)cmdline_paddr);
890                 if (status != EFI_SUCCESS) {
891                         efi_err("Failed to parse options\n");
892                         goto fail;
893                 }
894         }
895
896         if (efi_mem_encrypt > 0)
897                 hdr->xloadflags |= XLF_MEM_ENCRYPTION;
898
899         status = efi_decompress_kernel(&kernel_entry);
900         if (status != EFI_SUCCESS) {
901                 efi_err("Failed to decompress kernel\n");
902                 goto fail;
903         }
904
905         /*
906          * At this point, an initrd may already have been loaded by the
907          * bootloader and passed via bootparams. We permit an initrd loaded
908          * from the LINUX_EFI_INITRD_MEDIA_GUID device path to supersede it.
909          *
910          * If the device path is not present, any command-line initrd=
911          * arguments will be processed only if image is not NULL, which will be
912          * the case only if we were loaded via the PE entry point.
913          */
914         status = efi_load_initrd(image, hdr->initrd_addr_max, ULONG_MAX,
915                                  &initrd);
916         if (status != EFI_SUCCESS)
917                 goto fail;
918         if (initrd && initrd->size > 0) {
919                 efi_set_u64_split(initrd->base, &hdr->ramdisk_image,
920                                   &boot_params->ext_ramdisk_image);
921                 efi_set_u64_split(initrd->size, &hdr->ramdisk_size,
922                                   &boot_params->ext_ramdisk_size);
923         }
924
925
926         /*
927          * If the boot loader gave us a value for secure_boot then we use that,
928          * otherwise we ask the BIOS.
929          */
930         if (boot_params->secure_boot == efi_secureboot_mode_unset)
931                 boot_params->secure_boot = efi_get_secureboot();
932
933         /* Ask the firmware to clear memory on unclean shutdown */
934         efi_enable_reset_attack_mitigation();
935
936         efi_random_get_seed();
937
938         efi_retrieve_eventlog();
939
940         setup_graphics(boot_params);
941
942         setup_efi_pci(boot_params);
943
944         setup_quirks(boot_params);
945
946         setup_unaccepted_memory();
947
948         status = exit_boot(boot_params, handle);
949         if (status != EFI_SUCCESS) {
950                 efi_err("exit_boot() failed!\n");
951                 goto fail;
952         }
953
954         /*
955          * Call the SEV init code while still running with the firmware's
956          * GDT/IDT, so #VC exceptions will be handled by EFI.
957          */
958         sev_enable(boot_params);
959
960         efi_5level_switch();
961
962         enter_kernel(kernel_entry, boot_params);
963 fail:
964         efi_err("efi_stub_entry() failed!\n");
965
966         efi_exit(handle, status);
967 }
968
969 #ifdef CONFIG_EFI_HANDOVER_PROTOCOL
970 void efi_handover_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
971                         struct boot_params *boot_params)
972 {
973         extern char _bss[], _ebss[];
974
975         memset(_bss, 0, _ebss - _bss);
976         efi_stub_entry(handle, sys_table_arg, boot_params);
977 }
978
979 #ifndef CONFIG_EFI_MIXED
980 extern __alias(efi_handover_entry)
981 void efi32_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
982                       struct boot_params *boot_params);
983
984 extern __alias(efi_handover_entry)
985 void efi64_stub_entry(efi_handle_t handle, efi_system_table_t *sys_table_arg,
986                       struct boot_params *boot_params);
987 #endif
988 #endif