xref: /linux/arch/x86/platform/efi/efi.c (revision cc919b0db7d322c65067801869bc6354669726dc)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Common EFI (Extensible Firmware Interface) support functions
4  * Based on Extensible Firmware Interface Specification version 1.0
5  *
6  * Copyright (C) 1999 VA Linux Systems
7  * Copyright (C) 1999 Walt Drummond <drummond@valinux.com>
8  * Copyright (C) 1999-2002 Hewlett-Packard Co.
9  *	David Mosberger-Tang <davidm@hpl.hp.com>
10  *	Stephane Eranian <eranian@hpl.hp.com>
11  * Copyright (C) 2005-2008 Intel Co.
12  *	Fenghua Yu <fenghua.yu@intel.com>
13  *	Bibo Mao <bibo.mao@intel.com>
14  *	Chandramouli Narayanan <mouli@linux.intel.com>
15  *	Huang Ying <ying.huang@intel.com>
16  * Copyright (C) 2013 SuSE Labs
17  *	Borislav Petkov <bp@suse.de> - runtime services VA mapping
18  *
19  * Copied from efi_32.c to eliminate the duplicated code between EFI
20  * 32/64 support code. --ying 2007-10-26
21  *
22  * All EFI Runtime Services are not implemented yet as EFI only
23  * supports physical mode addressing on SoftSDV. This is to be fixed
24  * in a future version.  --drummond 1999-07-20
25  *
26  * Implemented EFI runtime services and virtual mode calls.  --davidm
27  *
28  * Goutham Rao: <goutham.rao@intel.com>
29  *	Skip non-WB memory and ignore empty memory ranges.
30  */
31 
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 
34 #include <linux/kernel.h>
35 #include <linux/init.h>
36 #include <linux/efi.h>
37 #include <linux/efi-bgrt.h>
38 #include <linux/export.h>
39 #include <linux/memblock.h>
40 #include <linux/slab.h>
41 #include <linux/spinlock.h>
42 #include <linux/uaccess.h>
43 #include <linux/time.h>
44 #include <linux/io.h>
45 #include <linux/reboot.h>
46 #include <linux/bcd.h>
47 
48 #include <asm/setup.h>
49 #include <asm/efi.h>
50 #include <asm/e820/api.h>
51 #include <asm/time.h>
52 #include <asm/tlbflush.h>
53 #include <asm/x86_init.h>
54 #include <asm/uv/uv.h>
55 
56 static unsigned long efi_systab_phys __initdata;
57 static unsigned long efi_runtime, efi_nr_tables;
58 
59 unsigned long efi_fw_vendor, efi_config_table;
60 
61 static const efi_config_table_type_t arch_tables[] __initconst = {
62 #ifdef CONFIG_X86_UV
63 	{UV_SYSTEM_TABLE_GUID,		&uv_systab_phys,	"UVsystab"	},
64 #endif
65 	{},
66 };
67 
68 static const unsigned long * const efi_tables[] = {
69 	&efi.acpi,
70 	&efi.acpi20,
71 	&efi.smbios,
72 	&efi.smbios3,
73 #ifdef CONFIG_X86_UV
74 	&uv_systab_phys,
75 #endif
76 	&efi_fw_vendor,
77 	&efi_runtime,
78 	&efi_config_table,
79 	&efi.esrt,
80 	&efi_mem_attr_table,
81 #ifdef CONFIG_EFI_RCI2_TABLE
82 	&rci2_table_phys,
83 #endif
84 	&efi.tpm_log,
85 	&efi.tpm_final_log,
86 	&efi_rng_seed,
87 #ifdef CONFIG_LOAD_UEFI_KEYS
88 	&efi.mokvar_table,
89 #endif
90 #ifdef CONFIG_EFI_COCO_SECRET
91 	&efi.coco_secret,
92 #endif
93 #ifdef CONFIG_UNACCEPTED_MEMORY
94 	&efi.unaccepted,
95 #endif
96 };
97 
98 u64 efi_setup;		/* efi setup_data physical address */
99 
100 static int add_efi_memmap __initdata;
101 static int __init setup_add_efi_memmap(char *arg)
102 {
103 	add_efi_memmap = 1;
104 	return 0;
105 }
106 early_param("add_efi_memmap", setup_add_efi_memmap);
107 
108 /*
109  * Tell the kernel about the EFI memory map.  This might include
110  * more than the max 128 entries that can fit in the passed in e820
111  * legacy (zeropage) memory map, but the kernel's e820 table can hold
112  * E820_MAX_ENTRIES.
113  */
114 
115 static void __init do_add_efi_memmap(void)
116 {
117 	efi_memory_desc_t *md;
118 
119 	if (!efi_enabled(EFI_MEMMAP))
120 		return;
121 
122 	for_each_efi_memory_desc(md) {
123 		unsigned long long start = md->phys_addr;
124 		unsigned long long size = md->num_pages << EFI_PAGE_SHIFT;
125 		int e820_type;
126 
127 		switch (md->type) {
128 		case EFI_LOADER_CODE:
129 		case EFI_LOADER_DATA:
130 		case EFI_BOOT_SERVICES_CODE:
131 		case EFI_BOOT_SERVICES_DATA:
132 		case EFI_CONVENTIONAL_MEMORY:
133 			if (efi_soft_reserve_enabled()
134 			    && (md->attribute & EFI_MEMORY_SP))
135 				e820_type = E820_TYPE_SOFT_RESERVED;
136 			else if (md->attribute & EFI_MEMORY_WB)
137 				e820_type = E820_TYPE_RAM;
138 			else
139 				e820_type = E820_TYPE_RESERVED;
140 			break;
141 		case EFI_ACPI_RECLAIM_MEMORY:
142 			e820_type = E820_TYPE_ACPI;
143 			break;
144 		case EFI_ACPI_MEMORY_NVS:
145 			e820_type = E820_TYPE_NVS;
146 			break;
147 		case EFI_UNUSABLE_MEMORY:
148 			e820_type = E820_TYPE_UNUSABLE;
149 			break;
150 		case EFI_PERSISTENT_MEMORY:
151 			e820_type = E820_TYPE_PMEM;
152 			break;
153 		default:
154 			/*
155 			 * EFI_RESERVED_TYPE EFI_RUNTIME_SERVICES_CODE
156 			 * EFI_RUNTIME_SERVICES_DATA EFI_MEMORY_MAPPED_IO
157 			 * EFI_MEMORY_MAPPED_IO_PORT_SPACE EFI_PAL_CODE
158 			 */
159 			e820_type = E820_TYPE_RESERVED;
160 			break;
161 		}
162 
163 		e820__range_add(start, size, e820_type);
164 	}
165 	e820__update_table(e820_table);
166 }
167 
168 /*
169  * Given add_efi_memmap defaults to 0 and there is no alternative
170  * e820 mechanism for soft-reserved memory, import the full EFI memory
171  * map if soft reservations are present and enabled. Otherwise, the
172  * mechanism to disable the kernel's consideration of EFI_MEMORY_SP is
173  * the efi=nosoftreserve option.
174  */
175 static bool do_efi_soft_reserve(void)
176 {
177 	efi_memory_desc_t *md;
178 
179 	if (!efi_enabled(EFI_MEMMAP))
180 		return false;
181 
182 	if (!efi_soft_reserve_enabled())
183 		return false;
184 
185 	for_each_efi_memory_desc(md)
186 		if (md->type == EFI_CONVENTIONAL_MEMORY &&
187 		    (md->attribute & EFI_MEMORY_SP))
188 			return true;
189 	return false;
190 }
191 
192 int __init efi_memblock_x86_reserve_range(void)
193 {
194 	struct efi_info *e = &boot_params.efi_info;
195 	struct efi_memory_map_data data;
196 	phys_addr_t pmap;
197 	int rv;
198 
199 	if (efi_enabled(EFI_PARAVIRT))
200 		return 0;
201 
202 	/* Can't handle firmware tables above 4GB on i386 */
203 	if (IS_ENABLED(CONFIG_X86_32) && e->efi_memmap_hi > 0) {
204 		pr_err("Memory map is above 4GB, disabling EFI.\n");
205 		return -EINVAL;
206 	}
207 	pmap = (phys_addr_t)(e->efi_memmap | ((u64)e->efi_memmap_hi << 32));
208 
209 	data.phys_map		= pmap;
210 	data.size 		= e->efi_memmap_size;
211 	data.desc_size		= e->efi_memdesc_size;
212 	data.desc_version	= e->efi_memdesc_version;
213 
214 	if (!efi_enabled(EFI_PARAVIRT)) {
215 		rv = efi_memmap_init_early(&data);
216 		if (rv)
217 			return rv;
218 	}
219 
220 	if (add_efi_memmap || do_efi_soft_reserve())
221 		do_add_efi_memmap();
222 
223 	WARN(efi.memmap.desc_version != 1,
224 	     "Unexpected EFI_MEMORY_DESCRIPTOR version %ld",
225 	     efi.memmap.desc_version);
226 
227 	memblock_reserve(pmap, efi.memmap.nr_map * efi.memmap.desc_size);
228 	set_bit(EFI_PRESERVE_BS_REGIONS, &efi.flags);
229 
230 	return 0;
231 }
232 
233 #define OVERFLOW_ADDR_SHIFT	(64 - EFI_PAGE_SHIFT)
234 #define OVERFLOW_ADDR_MASK	(U64_MAX << OVERFLOW_ADDR_SHIFT)
235 #define U64_HIGH_BIT		(~(U64_MAX >> 1))
236 
237 static bool __init efi_memmap_entry_valid(const efi_memory_desc_t *md, int i)
238 {
239 	u64 end = (md->num_pages << EFI_PAGE_SHIFT) + md->phys_addr - 1;
240 	u64 end_hi = 0;
241 	char buf[64];
242 
243 	if (md->num_pages == 0) {
244 		end = 0;
245 	} else if (md->num_pages > EFI_PAGES_MAX ||
246 		   EFI_PAGES_MAX - md->num_pages <
247 		   (md->phys_addr >> EFI_PAGE_SHIFT)) {
248 		end_hi = (md->num_pages & OVERFLOW_ADDR_MASK)
249 			>> OVERFLOW_ADDR_SHIFT;
250 
251 		if ((md->phys_addr & U64_HIGH_BIT) && !(end & U64_HIGH_BIT))
252 			end_hi += 1;
253 	} else {
254 		return true;
255 	}
256 
257 	pr_warn_once(FW_BUG "Invalid EFI memory map entries:\n");
258 
259 	if (end_hi) {
260 		pr_warn("mem%02u: %s range=[0x%016llx-0x%llx%016llx] (invalid)\n",
261 			i, efi_md_typeattr_format(buf, sizeof(buf), md),
262 			md->phys_addr, end_hi, end);
263 	} else {
264 		pr_warn("mem%02u: %s range=[0x%016llx-0x%016llx] (invalid)\n",
265 			i, efi_md_typeattr_format(buf, sizeof(buf), md),
266 			md->phys_addr, end);
267 	}
268 	return false;
269 }
270 
271 static void __init efi_clean_memmap(void)
272 {
273 	efi_memory_desc_t *out = efi.memmap.map;
274 	const efi_memory_desc_t *in = out;
275 	const efi_memory_desc_t *end = efi.memmap.map_end;
276 	int i, n_removal;
277 
278 	for (i = n_removal = 0; in < end; i++) {
279 		if (efi_memmap_entry_valid(in, i)) {
280 			if (out != in)
281 				memcpy(out, in, efi.memmap.desc_size);
282 			out = (void *)out + efi.memmap.desc_size;
283 		} else {
284 			n_removal++;
285 		}
286 		in = (void *)in + efi.memmap.desc_size;
287 	}
288 
289 	if (n_removal > 0) {
290 		struct efi_memory_map_data data = {
291 			.phys_map	= efi.memmap.phys_map,
292 			.desc_version	= efi.memmap.desc_version,
293 			.desc_size	= efi.memmap.desc_size,
294 			.size		= efi.memmap.desc_size * (efi.memmap.nr_map - n_removal),
295 			.flags		= 0,
296 		};
297 
298 		pr_warn("Removing %d invalid memory map entries.\n", n_removal);
299 		efi_memmap_install(&data);
300 	}
301 }
302 
303 /*
304  * Firmware can use EfiMemoryMappedIO to request that MMIO regions be
305  * mapped by the OS so they can be accessed by EFI runtime services, but
306  * should have no other significance to the OS (UEFI r2.10, sec 7.2).
307  * However, most bootloaders and EFI stubs convert EfiMemoryMappedIO
308  * regions to E820_TYPE_RESERVED entries, which prevent Linux from
309  * allocating space from them (see remove_e820_regions()).
310  *
311  * Some platforms use EfiMemoryMappedIO entries for PCI MMCONFIG space and
312  * PCI host bridge windows, which means Linux can't allocate BAR space for
313  * hot-added devices.
314  *
315  * Remove large EfiMemoryMappedIO regions from the E820 map to avoid this
316  * problem.
317  *
318  * Retain small EfiMemoryMappedIO regions because on some platforms, these
319  * describe non-window space that's included in host bridge _CRS.  If we
320  * assign that space to PCI devices, they don't work.
321  */
322 static void __init efi_remove_e820_mmio(void)
323 {
324 	efi_memory_desc_t *md;
325 	u64 size, start, end;
326 	int i = 0;
327 
328 	for_each_efi_memory_desc(md) {
329 		if (md->type == EFI_MEMORY_MAPPED_IO) {
330 			size = md->num_pages << EFI_PAGE_SHIFT;
331 			start = md->phys_addr;
332 			end = start + size - 1;
333 			if (size >= 256*1024) {
334 				pr_info("Remove mem%02u: MMIO range=[0x%08llx-0x%08llx] (%lluMB) from e820 map\n",
335 					i, start, end, size >> 20);
336 				e820__range_remove(start, size, E820_TYPE_RESERVED);
337 			} else {
338 				pr_info("Not removing mem%02u: MMIO range=[0x%08llx-0x%08llx] (%lluKB) from e820 map\n",
339 					i, start, end, size >> 10);
340 			}
341 		}
342 		i++;
343 	}
344 }
345 
346 void __init efi_print_memmap(void)
347 {
348 	efi_memory_desc_t *md;
349 	int i = 0;
350 
351 	for_each_efi_memory_desc(md) {
352 		char buf[64];
353 
354 		pr_info("mem%02u: %s range=[0x%016llx-0x%016llx] (%lluMB)\n",
355 			i++, efi_md_typeattr_format(buf, sizeof(buf), md),
356 			md->phys_addr,
357 			md->phys_addr + (md->num_pages << EFI_PAGE_SHIFT) - 1,
358 			(md->num_pages >> (20 - EFI_PAGE_SHIFT)));
359 	}
360 }
361 
362 static int __init efi_systab_init(unsigned long phys)
363 {
364 	int size = efi_enabled(EFI_64BIT) ? sizeof(efi_system_table_64_t)
365 					  : sizeof(efi_system_table_32_t);
366 	const efi_table_hdr_t *hdr;
367 	bool over4g = false;
368 	void *p;
369 	int ret;
370 
371 	hdr = p = early_memremap_ro(phys, size);
372 	if (p == NULL) {
373 		pr_err("Couldn't map the system table!\n");
374 		return -ENOMEM;
375 	}
376 
377 	ret = efi_systab_check_header(hdr);
378 	if (ret) {
379 		early_memunmap(p, size);
380 		return ret;
381 	}
382 
383 	if (efi_enabled(EFI_64BIT)) {
384 		const efi_system_table_64_t *systab64 = p;
385 
386 		efi_runtime	= systab64->runtime;
387 		over4g		= systab64->runtime > U32_MAX;
388 
389 		if (efi_setup) {
390 			struct efi_setup_data *data;
391 
392 			data = early_memremap_ro(efi_setup, sizeof(*data));
393 			if (!data) {
394 				early_memunmap(p, size);
395 				return -ENOMEM;
396 			}
397 
398 			efi_fw_vendor		= (unsigned long)data->fw_vendor;
399 			efi_config_table	= (unsigned long)data->tables;
400 
401 			over4g |= data->fw_vendor	> U32_MAX ||
402 				  data->tables		> U32_MAX;
403 
404 			early_memunmap(data, sizeof(*data));
405 		} else {
406 			efi_fw_vendor		= systab64->fw_vendor;
407 			efi_config_table	= systab64->tables;
408 
409 			over4g |= systab64->fw_vendor	> U32_MAX ||
410 				  systab64->tables	> U32_MAX;
411 		}
412 		efi_nr_tables = systab64->nr_tables;
413 	} else {
414 		const efi_system_table_32_t *systab32 = p;
415 
416 		efi_fw_vendor		= systab32->fw_vendor;
417 		efi_runtime		= systab32->runtime;
418 		efi_config_table	= systab32->tables;
419 		efi_nr_tables		= systab32->nr_tables;
420 	}
421 
422 	efi.runtime_version = hdr->revision;
423 
424 	efi_systab_report_header(hdr, efi_fw_vendor);
425 	early_memunmap(p, size);
426 
427 	if (IS_ENABLED(CONFIG_X86_32) && over4g) {
428 		pr_err("EFI data located above 4GB, disabling EFI.\n");
429 		return -EINVAL;
430 	}
431 
432 	return 0;
433 }
434 
435 /*
436  * kexec passes the firmware's config table array on to the next kernel as-is,
437  * but some of the tables it describes must be disregarded when booting via
438  * kexec, which is indicated by the presence of a SETUP_EFI setup_data entry:
439  *
440  * - The INITRD table is installed by the EFI stub to describe the initrd that
441  *   it loaded. Both the table and the initrd are allocated from EFI loader
442  *   data, which is released to the page allocator once the kernel is up and
443  *   running, and so the table is stale by the time kexec boots the next kernel.
444  *
445  * - The TPM event log table is installed by the EFI stub too. It is allocated
446  *   from EFI loader data rather than ACPI reclaim memory, as the latter would
447  *   create an E820 entry that may move around between boots, which breaks
448  *   resume from hibernation. It is reserved by the kernel, but the E820 map
449  *   that kexec passes on describes it as ordinary RAM, and so it may get
450  *   clobbered before the next kernel gets around to reserving it.
451  *
452  * - The Memory Attributes table may reside in EFI boot services data, which is
453  *   released to the page allocator as well. Even if it is still intact, the
454  *   sanity check in efi_memattr_init() may fail spuriously, given that only
455  *   the runtime regions of the EFI memory map are passed on via kexec. Applying
456  *   the permissions it describes is not critical, so just ignore it.
457  */
458 bool __init x86_efi_config_table_is_usable(const efi_guid_t *guid,
459 					   unsigned long table)
460 {
461 	if (!efi_setup)
462 		return true;
463 
464 	return efi_guidcmp(*guid, LINUX_EFI_INITRD_MEDIA_GUID) &&
465 	       efi_guidcmp(*guid, LINUX_EFI_TPM_EVENT_LOG_GUID) &&
466 	       efi_guidcmp(*guid, EFI_MEMORY_ATTRIBUTES_TABLE_GUID);
467 }
468 
469 static int __init efi_config_init(const efi_config_table_type_t *arch_tables)
470 {
471 	void *config_tables;
472 	int sz, ret;
473 
474 	if (efi_nr_tables == 0)
475 		return 0;
476 
477 	if (efi_enabled(EFI_64BIT))
478 		sz = sizeof(efi_config_table_64_t);
479 	else
480 		sz = sizeof(efi_config_table_32_t);
481 
482 	/*
483 	 * Let's see what config tables the firmware passed to us.
484 	 */
485 	config_tables = early_memremap(efi_config_table, efi_nr_tables * sz);
486 	if (config_tables == NULL) {
487 		pr_err("Could not map Configuration table!\n");
488 		return -ENOMEM;
489 	}
490 
491 	ret = efi_config_parse_tables(config_tables, efi_nr_tables,
492 				      arch_tables);
493 
494 	early_memunmap(config_tables, efi_nr_tables * sz);
495 	return ret;
496 }
497 
498 void __init efi_init(void)
499 {
500 	if (IS_ENABLED(CONFIG_X86_32) &&
501 	    (boot_params.efi_info.efi_systab_hi ||
502 	     boot_params.efi_info.efi_memmap_hi)) {
503 		pr_info("Table located above 4GB, disabling EFI.\n");
504 		return;
505 	}
506 
507 	efi_systab_phys = boot_params.efi_info.efi_systab |
508 			  ((__u64)boot_params.efi_info.efi_systab_hi << 32);
509 
510 	if (efi_systab_init(efi_systab_phys))
511 		return;
512 
513 	if (efi_reuse_config(efi_config_table, efi_nr_tables))
514 		return;
515 
516 	if (efi_config_init(arch_tables))
517 		return;
518 
519 	/*
520 	 * Note: We currently don't support runtime services on an EFI
521 	 * that doesn't match the kernel 32/64-bit mode.
522 	 */
523 
524 	if (!efi_runtime_supported())
525 		pr_err("No EFI runtime due to 32/64-bit mismatch with kernel\n");
526 
527 	if (!efi_runtime_supported() || efi_runtime_disabled()) {
528 		efi_memmap_unmap();
529 		return;
530 	}
531 
532 	set_bit(EFI_RUNTIME_SERVICES, &efi.flags);
533 	efi_clean_memmap();
534 
535 	efi_remove_e820_mmio();
536 
537 	if (efi_enabled(EFI_DBG))
538 		efi_print_memmap();
539 }
540 
541 /* Merge contiguous regions of the same type and attribute */
542 static void __init efi_merge_regions(void)
543 {
544 	efi_memory_desc_t *md, *prev_md = NULL;
545 
546 	for_each_efi_memory_desc(md) {
547 		u64 prev_size;
548 
549 		if (!prev_md) {
550 			prev_md = md;
551 			continue;
552 		}
553 
554 		if (prev_md->type != md->type ||
555 		    prev_md->attribute != md->attribute) {
556 			prev_md = md;
557 			continue;
558 		}
559 
560 		prev_size = prev_md->num_pages << EFI_PAGE_SHIFT;
561 
562 		if (md->phys_addr == (prev_md->phys_addr + prev_size)) {
563 			prev_md->num_pages += md->num_pages;
564 			md->type = EFI_RESERVED_TYPE;
565 			md->attribute = 0;
566 			continue;
567 		}
568 		prev_md = md;
569 	}
570 }
571 
572 static void *realloc_pages(void *old_memmap, int old_shift)
573 {
574 	void *ret;
575 
576 	ret = (void *)__get_free_pages(GFP_KERNEL, old_shift + 1);
577 	if (!ret)
578 		goto out;
579 
580 	/*
581 	 * A first-time allocation doesn't have anything to copy.
582 	 */
583 	if (!old_memmap)
584 		return ret;
585 
586 	memcpy(ret, old_memmap, PAGE_SIZE << old_shift);
587 
588 out:
589 	free_pages((unsigned long)old_memmap, old_shift);
590 	return ret;
591 }
592 
593 /*
594  * Iterate the EFI memory map in reverse order because the regions
595  * will be mapped top-down. The end result is the same as if we had
596  * mapped things forward, but doesn't require us to change the
597  * existing implementation of efi_map_region().
598  */
599 static inline void *efi_map_next_entry_reverse(void *entry)
600 {
601 	/* Initial call */
602 	if (!entry)
603 		return efi.memmap.map_end - efi.memmap.desc_size;
604 
605 	entry -= efi.memmap.desc_size;
606 	if (entry < efi.memmap.map)
607 		return NULL;
608 
609 	return entry;
610 }
611 
612 /*
613  * efi_map_next_entry - Return the next EFI memory map descriptor
614  * @entry: Previous EFI memory map descriptor
615  *
616  * This is a helper function to iterate over the EFI memory map, which
617  * we do in different orders depending on the current configuration.
618  *
619  * To begin traversing the memory map @entry must be %NULL.
620  *
621  * Returns %NULL when we reach the end of the memory map.
622  */
623 static void *efi_map_next_entry(void *entry)
624 {
625 	if (efi_enabled(EFI_64BIT)) {
626 		/*
627 		 * Starting in UEFI v2.5 the EFI_PROPERTIES_TABLE
628 		 * config table feature requires us to map all entries
629 		 * in the same order as they appear in the EFI memory
630 		 * map. That is to say, entry N must have a lower
631 		 * virtual address than entry N+1. This is because the
632 		 * firmware toolchain leaves relative references in
633 		 * the code/data sections, which are split and become
634 		 * separate EFI memory regions. Mapping things
635 		 * out-of-order leads to the firmware accessing
636 		 * unmapped addresses.
637 		 *
638 		 * Since we need to map things this way whether or not
639 		 * the kernel actually makes use of
640 		 * EFI_PROPERTIES_TABLE, let's just switch to this
641 		 * scheme by default for 64-bit.
642 		 */
643 		return efi_map_next_entry_reverse(entry);
644 	}
645 
646 	/* Initial call */
647 	if (!entry)
648 		return efi.memmap.map;
649 
650 	entry += efi.memmap.desc_size;
651 	if (entry >= efi.memmap.map_end)
652 		return NULL;
653 
654 	return entry;
655 }
656 
657 static bool should_map_region(efi_memory_desc_t *md)
658 {
659 	/*
660 	 * Runtime regions always require runtime mappings (obviously).
661 	 */
662 	if (md->attribute & EFI_MEMORY_RUNTIME)
663 		return true;
664 
665 	/*
666 	 * 32-bit EFI doesn't suffer from the bug that requires us to
667 	 * reserve boot services regions, and mixed mode support
668 	 * doesn't exist for 32-bit kernels.
669 	 */
670 	if (IS_ENABLED(CONFIG_X86_32))
671 		return false;
672 
673 	/*
674 	 * EFI specific purpose memory may be reserved by default
675 	 * depending on kernel config and boot options.
676 	 */
677 	if (md->type == EFI_CONVENTIONAL_MEMORY &&
678 	    efi_soft_reserve_enabled() &&
679 	    (md->attribute & EFI_MEMORY_SP))
680 		return false;
681 
682 	/*
683 	 * Map all of RAM so that we can access arguments in the 1:1
684 	 * mapping when making EFI runtime calls.
685 	 */
686 	if (efi_is_mixed()) {
687 		if (md->type == EFI_CONVENTIONAL_MEMORY ||
688 		    md->type == EFI_LOADER_DATA ||
689 		    md->type == EFI_LOADER_CODE)
690 			return true;
691 	}
692 
693 	/*
694 	 * Map boot services regions as a workaround for buggy
695 	 * firmware that accesses them even when they shouldn't.
696 	 *
697 	 * See efi_{reserve,free}_boot_services().
698 	 */
699 	if (md->type == EFI_BOOT_SERVICES_CODE ||
700 	    md->type == EFI_BOOT_SERVICES_DATA)
701 		return true;
702 
703 	return false;
704 }
705 
706 /*
707  * Map the efi memory ranges of the runtime services and update new_mmap with
708  * virtual addresses.
709  */
710 static void * __init efi_map_regions(int *count, int *pg_shift)
711 {
712 	void *p, *new_memmap = NULL;
713 	unsigned long left = 0;
714 	unsigned long desc_size;
715 	efi_memory_desc_t *md;
716 
717 	desc_size = efi.memmap.desc_size;
718 
719 	p = NULL;
720 	while ((p = efi_map_next_entry(p))) {
721 		md = p;
722 
723 		if (!should_map_region(md))
724 			continue;
725 
726 		efi_map_region(md);
727 
728 		if (left < desc_size) {
729 			new_memmap = realloc_pages(new_memmap, *pg_shift);
730 			if (!new_memmap)
731 				return NULL;
732 
733 			left += PAGE_SIZE << *pg_shift;
734 			(*pg_shift)++;
735 		}
736 
737 		memcpy(new_memmap + (*count * desc_size), md, desc_size);
738 
739 		left -= desc_size;
740 		(*count)++;
741 	}
742 
743 	return new_memmap;
744 }
745 
746 static void __init kexec_enter_virtual_mode(void)
747 {
748 #ifdef CONFIG_KEXEC_CORE
749 	efi_memory_desc_t *md;
750 	unsigned int num_pages;
751 
752 	/*
753 	 * We don't do virtual mode, since we don't do runtime services, on
754 	 * non-native EFI.
755 	 */
756 	if (efi_is_mixed()) {
757 		efi_memmap_unmap();
758 		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
759 		return;
760 	}
761 
762 	if (efi_alloc_page_tables()) {
763 		pr_err("Failed to allocate EFI page tables\n");
764 		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
765 		return;
766 	}
767 
768 	/*
769 	* Map efi regions which were passed via setup_data. The virt_addr is a
770 	* fixed addr which was used in first kernel of a kexec boot.
771 	*/
772 	for_each_efi_memory_desc(md)
773 		efi_map_region_fixed(md); /* FIXME: add error handling */
774 
775 	/*
776 	 * Unregister the early EFI memmap from efi_init() and install
777 	 * the new EFI memory map.
778 	 */
779 	efi_memmap_unmap();
780 
781 	if (efi_memmap_init_late(efi.memmap.phys_map,
782 				 efi.memmap.desc_size * efi.memmap.nr_map)) {
783 		pr_err("Failed to remap late EFI memory map\n");
784 		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
785 		return;
786 	}
787 
788 	num_pages = ALIGN(efi.memmap.nr_map * efi.memmap.desc_size, PAGE_SIZE);
789 	num_pages >>= PAGE_SHIFT;
790 
791 	if (efi_setup_page_tables(efi.memmap.phys_map, num_pages)) {
792 		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
793 		return;
794 	}
795 
796 	efi_sync_low_kernel_mappings();
797 	efi_native_runtime_setup();
798 	efi_runtime_update_mappings();
799 #endif
800 }
801 
802 /*
803  * This function will switch the EFI runtime services to virtual mode.
804  * Essentially, we look through the EFI memmap and map every region that
805  * has the runtime attribute bit set in its memory descriptor into the
806  * efi_pgd page table.
807  *
808  * The new method does a pagetable switch in a preemption-safe manner
809  * so that we're in a different address space when calling a runtime
810  * function. For function arguments passing we do copy the PUDs of the
811  * kernel page table into efi_pgd prior to each call.
812  *
813  * Specially for kexec boot, efi runtime maps in previous kernel should
814  * be passed in via setup_data. In that case runtime ranges will be mapped
815  * to the same virtual addresses as the first kernel, see
816  * kexec_enter_virtual_mode().
817  */
818 static void __init __efi_enter_virtual_mode(void)
819 {
820 	int count = 0, pg_shift = 0;
821 	void *new_memmap = NULL;
822 	efi_status_t status;
823 	unsigned long pa;
824 
825 	if (efi_alloc_page_tables()) {
826 		pr_err("Failed to allocate EFI page tables\n");
827 		goto err;
828 	}
829 
830 	efi_merge_regions();
831 	new_memmap = efi_map_regions(&count, &pg_shift);
832 	if (!new_memmap) {
833 		pr_err("Error reallocating memory, EFI runtime non-functional!\n");
834 		goto err;
835 	}
836 
837 	pa = __pa(new_memmap);
838 
839 	/*
840 	 * Unregister the early EFI memmap from efi_init() and install
841 	 * the new EFI memory map that we are about to pass to the
842 	 * firmware via SetVirtualAddressMap().
843 	 */
844 	efi_memmap_unmap();
845 
846 	if (efi_memmap_init_late(pa, efi.memmap.desc_size * count)) {
847 		pr_err("Failed to remap late EFI memory map\n");
848 		goto err;
849 	}
850 
851 	if (efi_enabled(EFI_DBG)) {
852 		pr_info("EFI runtime memory map:\n");
853 		efi_print_memmap();
854 	}
855 
856 	if (efi_setup_page_tables(pa, 1 << pg_shift))
857 		goto err;
858 
859 	efi_sync_low_kernel_mappings();
860 
861 	status = efi_set_virtual_address_map(efi.memmap.desc_size * count,
862 					     efi.memmap.desc_size,
863 					     efi.memmap.desc_version,
864 					     (efi_memory_desc_t *)pa,
865 					     efi_systab_phys);
866 	if (status != EFI_SUCCESS) {
867 		pr_err("Unable to switch EFI into virtual mode (status=%lx)!\n",
868 		       status);
869 		goto err;
870 	}
871 
872 	efi_check_for_embedded_firmwares();
873 	efi_unmap_boot_services();
874 
875 	if (!efi_is_mixed())
876 		efi_native_runtime_setup();
877 	else
878 		efi_thunk_runtime_setup();
879 
880 	/*
881 	 * Apply more restrictive page table mapping attributes now that
882 	 * SVAM() has been called and the firmware has performed all
883 	 * necessary relocation fixups for the new virtual addresses.
884 	 */
885 	efi_runtime_update_mappings();
886 
887 	/* clean DUMMY object */
888 	efi_delete_dummy_variable();
889 	return;
890 
891 err:
892 	clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
893 }
894 
895 void __init efi_enter_virtual_mode(void)
896 {
897 	if (efi_enabled(EFI_PARAVIRT))
898 		return;
899 
900 	efi.runtime = (efi_runtime_services_t *)efi_runtime;
901 
902 	if (efi_setup)
903 		kexec_enter_virtual_mode();
904 	else
905 		__efi_enter_virtual_mode();
906 
907 	efi_dump_pagetable();
908 }
909 
910 bool efi_is_table_address(unsigned long phys_addr)
911 {
912 	unsigned int i;
913 
914 	if (phys_addr == EFI_INVALID_TABLE_ADDR)
915 		return false;
916 
917 	for (i = 0; i < ARRAY_SIZE(efi_tables); i++)
918 		if (*(efi_tables[i]) == phys_addr)
919 			return true;
920 
921 	return false;
922 }
923 
924 #define EFI_FIELD(var) efi_ ## var
925 
926 #define EFI_ATTR_SHOW(name) \
927 static ssize_t name##_show(struct kobject *kobj, \
928 			   const struct kobj_attribute *attr, char *buf) \
929 { \
930 	return sysfs_emit(buf, "0x%lx\n", EFI_FIELD(name)); \
931 }
932 
933 EFI_ATTR_SHOW(fw_vendor);
934 EFI_ATTR_SHOW(runtime);
935 EFI_ATTR_SHOW(config_table);
936 
937 const struct kobj_attribute efi_attr_fw_vendor = __KOBJ_ATTR_RO(fw_vendor);
938 const struct kobj_attribute efi_attr_runtime = __KOBJ_ATTR_RO(runtime);
939 const struct kobj_attribute efi_attr_config_table = __KOBJ_ATTR_RO(config_table);
940 
941 umode_t efi_attr_is_visible(struct kobject *kobj, const struct attribute *attr,
942 			    int n)
943 {
944 	if (attr == &efi_attr_fw_vendor.attr) {
945 		if (efi_enabled(EFI_PARAVIRT) ||
946 				efi_fw_vendor == EFI_INVALID_TABLE_ADDR)
947 			return 0;
948 	} else if (attr == &efi_attr_runtime.attr) {
949 		if (efi_runtime == EFI_INVALID_TABLE_ADDR)
950 			return 0;
951 	} else if (attr == &efi_attr_config_table.attr) {
952 		if (efi_config_table == EFI_INVALID_TABLE_ADDR)
953 			return 0;
954 	}
955 	return attr->mode;
956 }
957 
958 enum efi_secureboot_mode __x86_efi_boot_mode(void)
959 {
960 	return boot_params.secure_boot;
961 }
962