efi.c 26.3 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * efi.c - EFI subsystem
 *
 * Copyright (C) 2001,2003,2004 Dell <Matt_Domsch@dell.com>
 * Copyright (C) 2004 Intel Corporation <matthew.e.tolentino@intel.com>
 * Copyright (C) 2013 Tom Gundersen <teg@jklm.no>
 *
 * This code registers /sys/firmware/efi{,/efivars} when EFI is supported,
 * allowing the efivarfs to be mounted or the efivars module to be loaded.
 * The existance of /sys/firmware/efi may also be used by userspace to
 * determine that the system supports EFI.
 */

15 16
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

17 18 19 20 21
#include <linux/kobject.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/efi.h>
22 23
#include <linux/of.h>
#include <linux/of_fdt.h>
24
#include <linux/io.h>
25
#include <linux/kexec.h>
L
Lee, Chun-Yi 已提交
26
#include <linux/platform_device.h>
27 28
#include <linux/random.h>
#include <linux/reboot.h>
29 30 31
#include <linux/slab.h>
#include <linux/acpi.h>
#include <linux/ucs2_string.h>
32
#include <linux/memblock.h>
33
#include <linux/security.h>
34

35
#include <asm/early_ioremap.h>
36

37
struct efi __read_mostly efi = {
38 39 40 41 42
	.acpi			= EFI_INVALID_TABLE_ADDR,
	.acpi20			= EFI_INVALID_TABLE_ADDR,
	.smbios			= EFI_INVALID_TABLE_ADDR,
	.smbios3		= EFI_INVALID_TABLE_ADDR,
	.esrt			= EFI_INVALID_TABLE_ADDR,
43
	.tpm_log		= EFI_INVALID_TABLE_ADDR,
44
	.tpm_final_log		= EFI_INVALID_TABLE_ADDR,
45 46
};
EXPORT_SYMBOL(efi);
47

48
static unsigned long __ro_after_init rng_seed = EFI_INVALID_TABLE_ADDR;
49
static unsigned long __initdata mem_reserve = EFI_INVALID_TABLE_ADDR;
50

51 52 53 54 55 56 57
struct mm_struct efi_mm = {
	.mm_rb			= RB_ROOT,
	.mm_users		= ATOMIC_INIT(2),
	.mm_count		= ATOMIC_INIT(1),
	.mmap_sem		= __RWSEM_INITIALIZER(efi_mm.mmap_sem),
	.page_table_lock	= __SPIN_LOCK_UNLOCKED(efi_mm.page_table_lock),
	.mmlist			= LIST_HEAD_INIT(efi_mm.mmlist),
58
	.cpu_bitmap		= { [BITS_TO_LONGS(NR_CPUS)] = 0},
59 60
};

61 62
struct workqueue_struct *efi_rts_wq;

63 64 65 66 67 68 69 70 71 72 73 74 75
static bool disable_runtime;
static int __init setup_noefi(char *arg)
{
	disable_runtime = true;
	return 0;
}
early_param("noefi", setup_noefi);

bool efi_runtime_disabled(void)
{
	return disable_runtime;
}

76 77 78 79 80
bool __pure __efi_soft_reserve_enabled(void)
{
	return !efi_enabled(EFI_MEM_NO_SOFT_RESERVE);
}

D
Dave Young 已提交
81 82
static int __init parse_efi_cmdline(char *str)
{
83 84 85 86 87
	if (!str) {
		pr_warn("need at least one option\n");
		return -EINVAL;
	}

88 89 90
	if (parse_option_str(str, "debug"))
		set_bit(EFI_DBG, &efi.flags);

D
Dave Young 已提交
91 92 93
	if (parse_option_str(str, "noruntime"))
		disable_runtime = true;

94 95
	if (parse_option_str(str, "nosoftreserve"))
		set_bit(EFI_MEM_NO_SOFT_RESERVE, &efi.flags);
D
Dave Young 已提交
96 97 98 99 100

	return 0;
}
early_param("efi", parse_efi_cmdline);

P
Peter Jones 已提交
101
struct kobject *efi_kobj;
102 103 104 105

/*
 * Let's not leave out systab information that snuck into
 * the efivars driver
106 107
 * Note, do not add more fields in systab sysfs file as it breaks sysfs
 * one value per file rule!
108 109 110 111 112 113 114 115 116 117 118 119 120
 */
static ssize_t systab_show(struct kobject *kobj,
			   struct kobj_attribute *attr, char *buf)
{
	char *str = buf;

	if (!kobj || !buf)
		return -EINVAL;

	if (efi.acpi20 != EFI_INVALID_TABLE_ADDR)
		str += sprintf(str, "ACPI20=0x%lx\n", efi.acpi20);
	if (efi.acpi != EFI_INVALID_TABLE_ADDR)
		str += sprintf(str, "ACPI=0x%lx\n", efi.acpi);
121 122 123 124 125
	/*
	 * If both SMBIOS and SMBIOS3 entry points are implemented, the
	 * SMBIOS3 entry point shall be preferred, so we list it first to
	 * let applications stop parsing after the first match.
	 */
126 127
	if (efi.smbios3 != EFI_INVALID_TABLE_ADDR)
		str += sprintf(str, "SMBIOS3=0x%lx\n", efi.smbios3);
128 129
	if (efi.smbios != EFI_INVALID_TABLE_ADDR)
		str += sprintf(str, "SMBIOS=0x%lx\n", efi.smbios);
130

131
	if (IS_ENABLED(CONFIG_IA64) || IS_ENABLED(CONFIG_X86)) {
132 133 134 135 136
		extern char *efi_systab_show_arch(char *str);

		str = efi_systab_show_arch(str);
	}

137 138 139
	return str - buf;
}

140
static struct kobj_attribute efi_attr_systab = __ATTR_RO_MODE(systab, 0400);
141

142 143 144 145 146 147
static ssize_t fw_platform_size_show(struct kobject *kobj,
				     struct kobj_attribute *attr, char *buf)
{
	return sprintf(buf, "%d\n", efi_enabled(EFI_64BIT) ? 64 : 32);
}

148 149 150
extern __weak struct kobj_attribute efi_attr_fw_vendor;
extern __weak struct kobj_attribute efi_attr_runtime;
extern __weak struct kobj_attribute efi_attr_config_table;
151 152
static struct kobj_attribute efi_attr_fw_platform_size =
	__ATTR_RO(fw_platform_size);
153

154 155
static struct attribute *efi_subsys_attrs[] = {
	&efi_attr_systab.attr,
156
	&efi_attr_fw_platform_size.attr,
157 158 159 160
	&efi_attr_fw_vendor.attr,
	&efi_attr_runtime.attr,
	&efi_attr_config_table.attr,
	NULL,
161 162
};

163 164
umode_t __weak efi_attr_is_visible(struct kobject *kobj, struct attribute *attr,
				   int n)
165
{
D
Daniel Kiper 已提交
166
	return attr->mode;
167 168
}

169
static const struct attribute_group efi_subsys_attr_group = {
170
	.attrs = efi_subsys_attrs,
171
	.is_visible = efi_attr_is_visible,
172 173 174 175 176 177 178 179 180
};

static struct efivars generic_efivars;
static struct efivar_operations generic_ops;

static int generic_ops_register(void)
{
	generic_ops.get_variable = efi.get_variable;
	generic_ops.set_variable = efi.set_variable;
181
	generic_ops.set_variable_nonblocking = efi.set_variable_nonblocking;
182
	generic_ops.get_next_variable = efi.get_next_variable;
183
	generic_ops.query_variable_store = efi_query_variable_store;
184 185 186 187 188 189 190 191 192

	return efivars_register(&generic_efivars, &generic_ops, efi_kobj);
}

static void generic_ops_unregister(void)
{
	efivars_unregister(&generic_efivars);
}

193 194 195 196 197
#if IS_ENABLED(CONFIG_ACPI)
#define EFIVAR_SSDT_NAME_MAX	16
static char efivar_ssdt[EFIVAR_SSDT_NAME_MAX] __initdata;
static int __init efivar_ssdt_setup(char *str)
{
198 199 200 201 202
	int ret = security_locked_down(LOCKDOWN_ACPI_TABLES);

	if (ret)
		return ret;

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
	if (strlen(str) < sizeof(efivar_ssdt))
		memcpy(efivar_ssdt, str, strlen(str));
	else
		pr_warn("efivar_ssdt: name too long: %s\n", str);
	return 0;
}
__setup("efivar_ssdt=", efivar_ssdt_setup);

static __init int efivar_ssdt_iter(efi_char16_t *name, efi_guid_t vendor,
				   unsigned long name_size, void *data)
{
	struct efivar_entry *entry;
	struct list_head *list = data;
	char utf8_name[EFIVAR_SSDT_NAME_MAX];
	int limit = min_t(unsigned long, EFIVAR_SSDT_NAME_MAX, name_size);

	ucs2_as_utf8(utf8_name, name, limit - 1);
	if (strncmp(utf8_name, efivar_ssdt, limit) != 0)
		return 0;

	entry = kmalloc(sizeof(*entry), GFP_KERNEL);
	if (!entry)
		return 0;

	memcpy(entry->var.VariableName, name, name_size);
	memcpy(&entry->var.VendorGuid, &vendor, sizeof(efi_guid_t));

	efivar_entry_add(entry, list);

	return 0;
}

static __init int efivar_ssdt_load(void)
{
	LIST_HEAD(entries);
	struct efivar_entry *entry, *aux;
	unsigned long size;
	void *data;
	int ret;

243 244 245
	if (!efivar_ssdt[0])
		return 0;

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
	ret = efivar_init(efivar_ssdt_iter, &entries, true, &entries);

	list_for_each_entry_safe(entry, aux, &entries, list) {
		pr_info("loading SSDT from variable %s-%pUl\n", efivar_ssdt,
			&entry->var.VendorGuid);

		list_del(&entry->list);

		ret = efivar_entry_size(entry, &size);
		if (ret) {
			pr_err("failed to get var size\n");
			goto free_entry;
		}

		data = kmalloc(size, GFP_KERNEL);
261 262
		if (!data) {
			ret = -ENOMEM;
263
			goto free_entry;
264
		}
265 266 267 268 269 270 271

		ret = efivar_entry_get(entry, NULL, &size, data);
		if (ret) {
			pr_err("failed to get var data\n");
			goto free_data;
		}

272
		ret = acpi_load_table(data, NULL);
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
		if (ret) {
			pr_err("failed to load table: %d\n", ret);
			goto free_data;
		}

		goto free_entry;

free_data:
		kfree(data);

free_entry:
		kfree(entry);
	}

	return ret;
}
#else
static inline int efivar_ssdt_load(void) { return 0; }
#endif

293 294 295 296 297 298 299 300 301 302 303 304
/*
 * We register the efi subsystem with the firmware subsystem and the
 * efivars subsystem with the efi subsystem, if the system was booted with
 * EFI.
 */
static int __init efisubsys_init(void)
{
	int error;

	if (!efi_enabled(EFI_BOOT))
		return 0;

305 306 307 308 309 310 311 312 313 314 315 316
	/*
	 * Since we process only one efi_runtime_service() at a time, an
	 * ordered workqueue (which creates only one execution context)
	 * should suffice all our needs.
	 */
	efi_rts_wq = alloc_ordered_workqueue("efi_rts_wq", 0);
	if (!efi_rts_wq) {
		pr_err("Creating efi_rts_wq failed, EFI runtime services disabled.\n");
		clear_bit(EFI_RUNTIME_SERVICES, &efi.flags);
		return 0;
	}

317 318 319 320 321 322 323 324 325 326 327
	/* We register the efi directory at /sys/firmware/efi */
	efi_kobj = kobject_create_and_add("efi", firmware_kobj);
	if (!efi_kobj) {
		pr_err("efi: Firmware registration failed.\n");
		return -ENOMEM;
	}

	error = generic_ops_register();
	if (error)
		goto err_put;

328 329 330
	if (efi_enabled(EFI_RUNTIME_SERVICES))
		efivar_ssdt_load();

331 332 333 334 335 336 337
	error = sysfs_create_group(efi_kobj, &efi_subsys_attr_group);
	if (error) {
		pr_err("efi: Sysfs attribute export failed with error %d.\n",
		       error);
		goto err_unregister;
	}

338 339 340 341
	error = efi_runtime_map_init(efi_kobj);
	if (error)
		goto err_remove_group;

342
	/* and the standard mountpoint for efivarfs */
343 344
	error = sysfs_create_mount_point(efi_kobj, "efivars");
	if (error) {
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
		pr_err("efivars: Subsystem registration failed.\n");
		goto err_remove_group;
	}

	return 0;

err_remove_group:
	sysfs_remove_group(efi_kobj, &efi_subsys_attr_group);
err_unregister:
	generic_ops_unregister();
err_put:
	kobject_put(efi_kobj);
	return error;
}

subsys_initcall(efisubsys_init);
361

P
Peter Jones 已提交
362 363
/*
 * Find the efi memory descriptor for a given physical address.  Given a
364
 * physical address, determine if it exists within an EFI Memory Map entry,
P
Peter Jones 已提交
365 366 367
 * and if so, populate the supplied memory descriptor with the appropriate
 * data.
 */
368
int efi_mem_desc_lookup(u64 phys_addr, efi_memory_desc_t *out_md)
P
Peter Jones 已提交
369
{
370
	efi_memory_desc_t *md;
P
Peter Jones 已提交
371 372 373 374 375 376 377 378 379 380 381

	if (!efi_enabled(EFI_MEMMAP)) {
		pr_err_once("EFI_MEMMAP is not enabled.\n");
		return -EINVAL;
	}

	if (!out_md) {
		pr_err_once("out_md is null.\n");
		return -EINVAL;
        }

382
	for_each_efi_memory_desc(md) {
P
Peter Jones 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
		u64 size;
		u64 end;

		size = md->num_pages << EFI_PAGE_SHIFT;
		end = md->phys_addr + size;
		if (phys_addr >= md->phys_addr && phys_addr < end) {
			memcpy(out_md, md, sizeof(*out_md));
			return 0;
		}
	}
	return -ENOENT;
}

/*
 * Calculate the highest address of an efi memory descriptor.
 */
u64 __init efi_mem_desc_end(efi_memory_desc_t *md)
{
	u64 size = md->num_pages << EFI_PAGE_SHIFT;
	u64 end = md->phys_addr + size;
	return end;
}
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
void __init __weak efi_arch_mem_reserve(phys_addr_t addr, u64 size) {}

/**
 * efi_mem_reserve - Reserve an EFI memory region
 * @addr: Physical address to reserve
 * @size: Size of reservation
 *
 * Mark a region as reserved from general kernel allocation and
 * prevent it being released by efi_free_boot_services().
 *
 * This function should be called drivers once they've parsed EFI
 * configuration tables to figure out where their data lives, e.g.
 * efi_esrt_init().
 */
void __init efi_mem_reserve(phys_addr_t addr, u64 size)
{
	if (!memblock_is_region_reserved(addr, size))
		memblock_reserve(addr, size);

	/*
	 * Some architectures (x86) reserve all boot services ranges
	 * until efi_free_boot_services() because of buggy firmware
	 * implementations. This means the above memblock_reserve() is
	 * superfluous on x86 and instead what it needs to do is
	 * ensure the @start, @size is not freed.
	 */
	efi_arch_mem_reserve(addr, size);
}

435
static const efi_config_table_type_t common_tables[] __initconst = {
436 437 438
	{ACPI_20_TABLE_GUID, "ACPI 2.0", &efi.acpi20},
	{ACPI_TABLE_GUID, "ACPI", &efi.acpi},
	{SMBIOS_TABLE_GUID, "SMBIOS", &efi.smbios},
439
	{SMBIOS3_TABLE_GUID, "SMBIOS 3.0", &efi.smbios3},
P
Peter Jones 已提交
440
	{EFI_SYSTEM_RESOURCE_TABLE_GUID, "ESRT", &efi.esrt},
441
	{EFI_MEMORY_ATTRIBUTES_TABLE_GUID, "MEMATTR", &efi_mem_attr_table},
442
	{LINUX_EFI_RANDOM_SEED_TABLE_GUID, "RNG", &rng_seed},
443
	{LINUX_EFI_TPM_EVENT_LOG_GUID, "TPMEventLog", &efi.tpm_log},
444
	{LINUX_EFI_TPM_FINAL_LOG_GUID, "TPMFinalLog", &efi.tpm_final_log},
445
	{LINUX_EFI_MEMRESERVE_TABLE_GUID, "MEMRESERVE", &mem_reserve},
446 447 448
#ifdef CONFIG_EFI_RCI2_TABLE
	{DELLEMC_EFI_RCI2_TABLE_GUID, NULL, &rci2_table_phys},
#endif
449
	{NULL_GUID, NULL, NULL},
450 451
};

452
static __init int match_config_table(const efi_guid_t *guid,
453
				     unsigned long table,
454
				     const efi_config_table_type_t *table_types)
455 456 457 458 459 460 461
{
	int i;

	if (table_types) {
		for (i = 0; efi_guidcmp(table_types[i].guid, NULL_GUID); i++) {
			if (!efi_guidcmp(*guid, table_types[i].guid)) {
				*(table_types[i].ptr) = table;
462 463 464
				if (table_types[i].name)
					pr_cont(" %s=0x%lx ",
						table_types[i].name, table);
465 466 467 468 469 470 471 472
				return 1;
			}
		}
	}

	return 0;
}

473 474 475
int __init efi_config_parse_tables(const efi_config_table_t *config_tables,
				   int count,
				   const efi_config_table_type_t *arch_tables)
476
{
477 478 479 480
	const efi_config_table_64_t *tbl64 = (void *)config_tables;
	const efi_config_table_32_t *tbl32 = (void *)config_tables;
	const efi_guid_t *guid;
	unsigned long table;
481
	int i;
482 483

	pr_info("");
484
	for (i = 0; i < count; i++) {
485 486 487 488 489 490 491 492 493
		if (!IS_ENABLED(CONFIG_X86)) {
			guid = &config_tables[i].guid;
			table = (unsigned long)config_tables[i].table;
		} else if (efi_enabled(EFI_64BIT)) {
			guid = &tbl64[i].guid;
			table = tbl64[i].table;

			if (IS_ENABLED(CONFIG_X86_32) &&
			    tbl64[i].table > U32_MAX) {
494 495 496 497 498
				pr_cont("\n");
				pr_err("Table located above 4GB, disabling EFI.\n");
				return -EINVAL;
			}
		} else {
499 500
			guid = &tbl32[i].guid;
			table = tbl32[i].table;
501 502
		}

503 504
		if (!match_config_table(guid, table, common_tables))
			match_config_table(guid, table, arch_tables);
505 506
	}
	pr_cont("\n");
507
	set_bit(EFI_CONFIG_TABLES, &efi.flags);
508

509
	if (rng_seed != EFI_INVALID_TABLE_ADDR) {
510 511 512
		struct linux_efi_random_seed *seed;
		u32 size = 0;

513
		seed = early_memremap(rng_seed, sizeof(*seed));
514 515 516 517 518 519 520
		if (seed != NULL) {
			size = seed->size;
			early_memunmap(seed, sizeof(*seed));
		} else {
			pr_err("Could not map UEFI random seed!\n");
		}
		if (size > 0) {
521
			seed = early_memremap(rng_seed, sizeof(*seed) + size);
522
			if (seed != NULL) {
523
				pr_notice("seeding entropy pool\n");
524
				add_bootloader_randomness(seed->bits, seed->size);
525 526 527 528 529 530 531
				early_memunmap(seed, sizeof(*seed) + size);
			} else {
				pr_err("Could not map UEFI random seed!\n");
			}
		}
	}

532 533
	if (efi_enabled(EFI_MEMMAP))
		efi_memattr_init();
534

535 536
	efi_tpm_eventlog_init();

537 538
	if (mem_reserve != EFI_INVALID_TABLE_ADDR) {
		unsigned long prsv = mem_reserve;
539 540 541

		while (prsv) {
			struct linux_efi_memreserve *rsv;
542 543 544 545 546 547 548 549 550 551 552
			u8 *p;
			int i;

			/*
			 * Just map a full page: that is what we will get
			 * anyway, and it permits us to map the entire entry
			 * before knowing its size.
			 */
			p = early_memremap(ALIGN_DOWN(prsv, PAGE_SIZE),
					   PAGE_SIZE);
			if (p == NULL) {
553 554 555 556
				pr_err("Could not map UEFI memreserve entry!\n");
				return -ENOMEM;
			}

557 558 559 560 561 562 563 564 565
			rsv = (void *)(p + prsv % PAGE_SIZE);

			/* reserve the entry itself */
			memblock_reserve(prsv, EFI_MEMRESERVE_SIZE(rsv->size));

			for (i = 0; i < atomic_read(&rsv->count); i++) {
				memblock_reserve(rsv->entry[i].base,
						 rsv->entry[i].size);
			}
566 567

			prsv = rsv->next;
568
			early_memunmap(p, PAGE_SIZE);
569 570 571
		}
	}

572 573
	return 0;
}
574

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
int __init efi_systab_check_header(const efi_table_hdr_t *systab_hdr,
				   int min_major_version)
{
	if (systab_hdr->signature != EFI_SYSTEM_TABLE_SIGNATURE) {
		pr_err("System table signature incorrect!\n");
		return -EINVAL;
	}

	if ((systab_hdr->revision >> 16) < min_major_version)
		pr_err("Warning: System table version %d.%02d, expected %d.00 or greater!\n",
		       systab_hdr->revision >> 16,
		       systab_hdr->revision & 0xffff,
		       min_major_version);

	return 0;
}

#ifndef CONFIG_IA64
static const efi_char16_t *__init map_fw_vendor(unsigned long fw_vendor,
						size_t size)
{
	const efi_char16_t *ret;

	ret = early_memremap_ro(fw_vendor, size);
	if (!ret)
		pr_err("Could not map the firmware vendor!\n");
	return ret;
}

static void __init unmap_fw_vendor(const void *fw_vendor, size_t size)
{
	early_memunmap((void *)fw_vendor, size);
}
#else
#define map_fw_vendor(p, s)	__va(p)
#define unmap_fw_vendor(v, s)
#endif

void __init efi_systab_report_header(const efi_table_hdr_t *systab_hdr,
				     unsigned long fw_vendor)
{
	char vendor[100] = "unknown";
	const efi_char16_t *c16;
	size_t i;

	c16 = map_fw_vendor(fw_vendor, sizeof(vendor) * sizeof(efi_char16_t));
	if (c16) {
		for (i = 0; i < sizeof(vendor) - 1 && c16[i]; ++i)
			vendor[i] = c16[i];
		vendor[i] = '\0';

		unmap_fw_vendor(c16, sizeof(vendor) * sizeof(efi_char16_t));
	}

	pr_info("EFI v%u.%.02u by %s\n",
		systab_hdr->revision >> 16,
		systab_hdr->revision & 0xffff,
		vendor);
}

L
Lee, Chun-Yi 已提交
635 636 637 638 639 640 641 642 643
#ifdef CONFIG_EFI_VARS_MODULE
static int __init efi_load_efivars(void)
{
	struct platform_device *pdev;

	if (!efi_enabled(EFI_RUNTIME_SERVICES))
		return 0;

	pdev = platform_device_register_simple("efivars", 0, NULL, 0);
V
Vasyl Gomonovych 已提交
644
	return PTR_ERR_OR_ZERO(pdev);
L
Lee, Chun-Yi 已提交
645 646 647 648
}
device_initcall(efi_load_efivars);
#endif

649 650 651 652 653 654 655
#ifdef CONFIG_EFI_PARAMS_FROM_FDT

#define UEFI_PARAM(name, prop, field)			   \
	{						   \
		{ name },				   \
		{ prop },				   \
		offsetof(struct efi_fdt_params, field),    \
656
		sizeof_field(struct efi_fdt_params, field) \
657 658
	}

659
struct params {
660 661 662 663
	const char name[32];
	const char propname[32];
	int offset;
	int size;
664 665 666
};

static __initdata struct params fdt_params[] = {
667 668 669 670 671 672 673
	UEFI_PARAM("System Table", "linux,uefi-system-table", system_table),
	UEFI_PARAM("MemMap Address", "linux,uefi-mmap-start", mmap),
	UEFI_PARAM("MemMap Size", "linux,uefi-mmap-size", mmap_size),
	UEFI_PARAM("MemMap Desc. Size", "linux,uefi-mmap-desc-size", desc_size),
	UEFI_PARAM("MemMap Desc. Version", "linux,uefi-mmap-desc-ver", desc_ver)
};

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
static __initdata struct params xen_fdt_params[] = {
	UEFI_PARAM("System Table", "xen,uefi-system-table", system_table),
	UEFI_PARAM("MemMap Address", "xen,uefi-mmap-start", mmap),
	UEFI_PARAM("MemMap Size", "xen,uefi-mmap-size", mmap_size),
	UEFI_PARAM("MemMap Desc. Size", "xen,uefi-mmap-desc-size", desc_size),
	UEFI_PARAM("MemMap Desc. Version", "xen,uefi-mmap-desc-ver", desc_ver)
};

#define EFI_FDT_PARAMS_SIZE	ARRAY_SIZE(fdt_params)

static __initdata struct {
	const char *uname;
	const char *subnode;
	struct params *params;
} dt_params[] = {
	{ "hypervisor", "uefi", xen_fdt_params },
	{ "chosen", NULL, fdt_params },
};

693
struct param_info {
694
	int found;
695
	void *params;
696
	const char *missing;
697 698
};

699 700 701
static int __init __find_uefi_params(unsigned long node,
				     struct param_info *info,
				     struct params *params)
702
{
703 704
	const void *prop;
	void *dest;
705
	u64 val;
706
	int i, len;
707

708 709 710 711
	for (i = 0; i < EFI_FDT_PARAMS_SIZE; i++) {
		prop = of_get_flat_dt_prop(node, params[i].propname, &len);
		if (!prop) {
			info->missing = params[i].name;
712
			return 0;
713 714 715
		}

		dest = info->params + params[i].offset;
716
		info->found++;
717 718 719

		val = of_read_number(prop, len / sizeof(u32));

720
		if (params[i].size == sizeof(u32))
721 722 723 724
			*(u32 *)dest = val;
		else
			*(u64 *)dest = val;

725
		if (efi_enabled(EFI_DBG))
726 727
			pr_info("  %s: 0x%0*llx\n", params[i].name,
				params[i].size * 2, val);
728
	}
729

730 731 732
	return 1;
}

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
static int __init fdt_find_uefi_params(unsigned long node, const char *uname,
				       int depth, void *data)
{
	struct param_info *info = data;
	int i;

	for (i = 0; i < ARRAY_SIZE(dt_params); i++) {
		const char *subnode = dt_params[i].subnode;

		if (depth != 1 || strcmp(uname, dt_params[i].uname) != 0) {
			info->missing = dt_params[i].params[0].name;
			continue;
		}

		if (subnode) {
748 749 750
			int err = of_get_flat_dt_subnode_by_name(node, subnode);

			if (err < 0)
751
				return 0;
752 753

			node = err;
754 755 756 757 758 759 760 761
		}

		return __find_uefi_params(node, info, dt_params[i].params);
	}

	return 0;
}

762
int __init efi_get_fdt_params(struct efi_fdt_params *params)
763 764
{
	struct param_info info;
765 766 767
	int ret;

	pr_info("Getting EFI parameters from FDT:\n");
768

769
	info.found = 0;
770 771
	info.params = params;

772 773 774 775 776
	ret = of_scan_flat_dt(fdt_find_uefi_params, &info);
	if (!info.found)
		pr_info("UEFI not found.\n");
	else if (!ret)
		pr_err("Can't find '%s' in device tree!\n",
777
		       info.missing);
778 779

	return ret;
780 781
}
#endif /* CONFIG_EFI_PARAMS_FROM_FDT */
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796

static __initdata char memory_type_name[][20] = {
	"Reserved",
	"Loader Code",
	"Loader Data",
	"Boot Code",
	"Boot Data",
	"Runtime Code",
	"Runtime Data",
	"Conventional Memory",
	"Unusable Memory",
	"ACPI Reclaim Memory",
	"ACPI Memory NVS",
	"Memory Mapped I/O",
	"MMIO Port Space",
797 798
	"PAL Code",
	"Persistent Memory",
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
};

char * __init efi_md_typeattr_format(char *buf, size_t size,
				     const efi_memory_desc_t *md)
{
	char *pos;
	int type_len;
	u64 attr;

	pos = buf;
	if (md->type >= ARRAY_SIZE(memory_type_name))
		type_len = snprintf(pos, size, "[type=%u", md->type);
	else
		type_len = snprintf(pos, size, "[%-*s",
				    (int)(sizeof(memory_type_name[0]) - 1),
				    memory_type_name[md->type]);
	if (type_len >= size)
		return buf;

	pos += type_len;
	size -= type_len;

	attr = md->attribute;
	if (attr & ~(EFI_MEMORY_UC | EFI_MEMORY_WC | EFI_MEMORY_WT |
823 824
		     EFI_MEMORY_WB | EFI_MEMORY_UCE | EFI_MEMORY_RO |
		     EFI_MEMORY_WP | EFI_MEMORY_RP | EFI_MEMORY_XP |
D
Dan Williams 已提交
825
		     EFI_MEMORY_NV | EFI_MEMORY_SP |
826
		     EFI_MEMORY_RUNTIME | EFI_MEMORY_MORE_RELIABLE))
827 828 829
		snprintf(pos, size, "|attr=0x%016llx]",
			 (unsigned long long)attr);
	else
R
Robert Elliott 已提交
830
		snprintf(pos, size,
D
Dan Williams 已提交
831
			 "|%3s|%2s|%2s|%2s|%2s|%2s|%2s|%2s|%3s|%2s|%2s|%2s|%2s]",
832
			 attr & EFI_MEMORY_RUNTIME ? "RUN" : "",
833
			 attr & EFI_MEMORY_MORE_RELIABLE ? "MR" : "",
D
Dan Williams 已提交
834
			 attr & EFI_MEMORY_SP      ? "SP"  : "",
R
Robert Elliott 已提交
835
			 attr & EFI_MEMORY_NV      ? "NV"  : "",
836 837 838
			 attr & EFI_MEMORY_XP      ? "XP"  : "",
			 attr & EFI_MEMORY_RP      ? "RP"  : "",
			 attr & EFI_MEMORY_WP      ? "WP"  : "",
839
			 attr & EFI_MEMORY_RO      ? "RO"  : "",
840 841 842 843 844 845 846
			 attr & EFI_MEMORY_UCE     ? "UCE" : "",
			 attr & EFI_MEMORY_WB      ? "WB"  : "",
			 attr & EFI_MEMORY_WT      ? "WT"  : "",
			 attr & EFI_MEMORY_WC      ? "WC"  : "",
			 attr & EFI_MEMORY_UC      ? "UC"  : "");
	return buf;
}
847

848 849 850 851 852
/*
 * IA64 has a funky EFI memory map that doesn't work the same way as
 * other architectures.
 */
#ifndef CONFIG_IA64
853 854 855 856 857 858 859 860
/*
 * efi_mem_attributes - lookup memmap attributes for physical address
 * @phys_addr: the physical address to lookup
 *
 * Search in the EFI memory map for the region covering
 * @phys_addr. Returns the EFI memory attributes if the region
 * was found in the memory map, 0 otherwise.
 */
861
u64 efi_mem_attributes(unsigned long phys_addr)
862 863 864 865 866 867
{
	efi_memory_desc_t *md;

	if (!efi_enabled(EFI_MEMMAP))
		return 0;

868
	for_each_efi_memory_desc(md) {
869 870 871 872 873 874 875
		if ((md->phys_addr <= phys_addr) &&
		    (phys_addr < (md->phys_addr +
		    (md->num_pages << EFI_PAGE_SHIFT))))
			return md->attribute;
	}
	return 0;
}
876

877 878 879 880 881 882
/*
 * efi_mem_type - lookup memmap type for physical address
 * @phys_addr: the physical address to lookup
 *
 * Search in the EFI memory map for the region covering @phys_addr.
 * Returns the EFI memory type if the region was found in the memory
883
 * map, -EINVAL otherwise.
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
 */
int efi_mem_type(unsigned long phys_addr)
{
	const efi_memory_desc_t *md;

	if (!efi_enabled(EFI_MEMMAP))
		return -ENOTSUPP;

	for_each_efi_memory_desc(md) {
		if ((md->phys_addr <= phys_addr) &&
		    (phys_addr < (md->phys_addr +
				  (md->num_pages << EFI_PAGE_SHIFT))))
			return md->type;
	}
	return -EINVAL;
}
#endif

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
int efi_status_to_err(efi_status_t status)
{
	int err;

	switch (status) {
	case EFI_SUCCESS:
		err = 0;
		break;
	case EFI_INVALID_PARAMETER:
		err = -EINVAL;
		break;
	case EFI_OUT_OF_RESOURCES:
		err = -ENOSPC;
		break;
	case EFI_DEVICE_ERROR:
		err = -EIO;
		break;
	case EFI_WRITE_PROTECTED:
		err = -EROFS;
		break;
	case EFI_SECURITY_VIOLATION:
		err = -EACCES;
		break;
	case EFI_NOT_FOUND:
		err = -ENOENT;
		break;
928 929 930
	case EFI_ABORTED:
		err = -EINTR;
		break;
931 932 933 934 935
	default:
		err = -EINVAL;
	}

	return err;
936 937
}

938
static DEFINE_SPINLOCK(efi_mem_reserve_persistent_lock);
939
static struct linux_efi_memreserve *efi_memreserve_root __ro_after_init;
940

941 942
static int __init efi_memreserve_map_root(void)
{
943
	if (mem_reserve == EFI_INVALID_TABLE_ADDR)
944 945
		return -ENODEV;

946
	efi_memreserve_root = memremap(mem_reserve,
947 948 949 950 951 952 953
				       sizeof(*efi_memreserve_root),
				       MEMREMAP_WB);
	if (WARN_ON_ONCE(!efi_memreserve_root))
		return -ENOMEM;
	return 0;
}

954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
static int efi_mem_reserve_iomem(phys_addr_t addr, u64 size)
{
	struct resource *res, *parent;

	res = kzalloc(sizeof(struct resource), GFP_ATOMIC);
	if (!res)
		return -ENOMEM;

	res->name	= "reserved";
	res->flags	= IORESOURCE_MEM;
	res->start	= addr;
	res->end	= addr + size - 1;

	/* we expect a conflict with a 'System RAM' region */
	parent = request_resource_conflict(&iomem_resource, res);
	return parent ? request_resource(parent, res) : 0;
}

972
int __ref efi_mem_reserve_persistent(phys_addr_t addr, u64 size)
973
{
974
	struct linux_efi_memreserve *rsv;
975 976
	unsigned long prsv;
	int rc, index;
977

978
	if (efi_memreserve_root == (void *)ULONG_MAX)
979 980
		return -ENODEV;

981 982 983 984 985 986
	if (!efi_memreserve_root) {
		rc = efi_memreserve_map_root();
		if (rc)
			return rc;
	}

987 988
	/* first try to find a slot in an existing linked list entry */
	for (prsv = efi_memreserve_root->next; prsv; prsv = rsv->next) {
989
		rsv = memremap(prsv, sizeof(*rsv), MEMREMAP_WB);
990 991 992 993 994
		index = atomic_fetch_add_unless(&rsv->count, 1, rsv->size);
		if (index < rsv->size) {
			rsv->entry[index].base = addr;
			rsv->entry[index].size = size;

995
			memunmap(rsv);
996
			return efi_mem_reserve_iomem(addr, size);
997
		}
998
		memunmap(rsv);
999 1000 1001 1002
	}

	/* no slot found - allocate a new linked list entry */
	rsv = (struct linux_efi_memreserve *)__get_free_page(GFP_ATOMIC);
1003 1004 1005
	if (!rsv)
		return -ENOMEM;

1006 1007 1008 1009 1010 1011
	rc = efi_mem_reserve_iomem(__pa(rsv), SZ_4K);
	if (rc) {
		free_page((unsigned long)rsv);
		return rc;
	}

1012 1013 1014 1015 1016 1017 1018
	/*
	 * The memremap() call above assumes that a linux_efi_memreserve entry
	 * never crosses a page boundary, so let's ensure that this remains true
	 * even when kexec'ing a 4k pages kernel from a >4k pages kernel, by
	 * using SZ_4K explicitly in the size calculation below.
	 */
	rsv->size = EFI_MEMRESERVE_COUNT(SZ_4K);
1019 1020 1021
	atomic_set(&rsv->count, 1);
	rsv->entry[0].base = addr;
	rsv->entry[0].size = size;
1022 1023

	spin_lock(&efi_mem_reserve_persistent_lock);
1024 1025
	rsv->next = efi_memreserve_root->next;
	efi_memreserve_root->next = __pa(rsv);
1026 1027
	spin_unlock(&efi_mem_reserve_persistent_lock);

1028
	return efi_mem_reserve_iomem(addr, size);
1029
}
1030

1031 1032
static int __init efi_memreserve_root_init(void)
{
1033 1034 1035 1036
	if (efi_memreserve_root)
		return 0;
	if (efi_memreserve_map_root())
		efi_memreserve_root = (void *)ULONG_MAX;
1037 1038
	return 0;
}
1039
early_initcall(efi_memreserve_root_init);
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
#ifdef CONFIG_KEXEC
static int update_efi_random_seed(struct notifier_block *nb,
				  unsigned long code, void *unused)
{
	struct linux_efi_random_seed *seed;
	u32 size = 0;

	if (!kexec_in_progress)
		return NOTIFY_DONE;

1051
	seed = memremap(rng_seed, sizeof(*seed), MEMREMAP_WB);
1052
	if (seed != NULL) {
1053
		size = min(seed->size, EFI_RANDOM_SEED_SIZE);
1054 1055 1056 1057 1058
		memunmap(seed);
	} else {
		pr_err("Could not map UEFI random seed!\n");
	}
	if (size > 0) {
1059
		seed = memremap(rng_seed, sizeof(*seed) + size, MEMREMAP_WB);
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
		if (seed != NULL) {
			seed->size = size;
			get_random_bytes(seed->bits, seed->size);
			memunmap(seed);
		} else {
			pr_err("Could not map UEFI random seed!\n");
		}
	}
	return NOTIFY_DONE;
}

static struct notifier_block efi_random_seed_nb = {
	.notifier_call = update_efi_random_seed,
};

1075
static int __init register_update_efi_random_seed(void)
1076
{
1077
	if (rng_seed == EFI_INVALID_TABLE_ADDR)
1078 1079 1080 1081 1082
		return 0;
	return register_reboot_notifier(&efi_random_seed_nb);
}
late_initcall(register_update_efi_random_seed);
#endif