xref: /linux/drivers/firmware/efi/libstub/efi-stub-helper.c (revision 95e6d3ba0571330df866911da9dedd83e05417ca)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Helper functions used by the EFI stub on multiple
4  * architectures. This should be #included by the EFI stub
5  * implementation files.
6  *
7  * Copyright 2011 Intel Corporation; author Matt Fleming
8  */
9 
10 #include <linux/stdarg.h>
11 
12 #include <linux/efi.h>
13 #include <linux/kernel.h>
14 #include <linux/overflow.h>
15 #include <asm/efi.h>
16 #include <asm/setup.h>
17 
18 #include "efistub.h"
19 
20 bool efi_nochunk;
21 bool efi_nokaslr = !IS_ENABLED(CONFIG_RANDOMIZE_BASE);
22 bool efi_novamap;
23 
24 static bool efi_noinitrd;
25 static bool efi_nosoftreserve;
26 static bool efi_disable_pci_dma = IS_ENABLED(CONFIG_EFI_DISABLE_PCI_DMA);
27 
28 int efi_mem_encrypt;
29 
__efi_soft_reserve_enabled(void)30 bool __pure __efi_soft_reserve_enabled(void)
31 {
32 	return !efi_nosoftreserve;
33 }
34 
35 /**
36  * efi_parse_options() - Parse EFI command line options
37  * @cmdline:	kernel command line
38  *
39  * Parse the ASCII string @cmdline for EFI options, denoted by the efi=
40  * option, e.g. efi=nochunk.
41  *
42  * It should be noted that efi= is parsed in two very different
43  * environments, first in the early boot environment of the EFI boot
44  * stub, and subsequently during the kernel boot.
45  *
46  * Return:	status code
47  */
efi_parse_options(char const * cmdline)48 efi_status_t efi_parse_options(char const *cmdline)
49 {
50 	char *buf __free(efi_pool) = NULL;
51 	efi_status_t status;
52 	size_t len;
53 	char *str;
54 
55 	if (!cmdline)
56 		return EFI_SUCCESS;
57 
58 	len = strnlen(cmdline, COMMAND_LINE_SIZE - 1) + 1;
59 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, len, (void **)&buf);
60 	if (status != EFI_SUCCESS)
61 		return status;
62 
63 	memcpy(buf, cmdline, len - 1);
64 	buf[len - 1] = '\0';
65 	str = skip_spaces(buf);
66 
67 	while (*str) {
68 		char *param, *val;
69 
70 		str = next_arg(str, &param, &val);
71 		if (!val && !strcmp(param, "--"))
72 			break;
73 
74 		if (!strcmp(param, "nokaslr")) {
75 			efi_nokaslr = true;
76 		} else if (!strcmp(param, "quiet")) {
77 			efi_loglevel = CONSOLE_LOGLEVEL_QUIET;
78 		} else if (!strcmp(param, "noinitrd")) {
79 			efi_noinitrd = true;
80 		} else if (IS_ENABLED(CONFIG_X86_64) && !strcmp(param, "no5lvl")) {
81 			efi_no5lvl = true;
82 		} else if (IS_ENABLED(CONFIG_LOONGARCH) &&
83 			   IS_ENABLED(CONFIG_HIBERNATION) &&
84 			   !strcmp(param, "resume") && val) {
85 			efi_nokaslr = true; /* LoongArch can't KASLR for hibernation */
86 		} else if (IS_ENABLED(CONFIG_ARCH_HAS_MEM_ENCRYPT) &&
87 			   !strcmp(param, "mem_encrypt") && val) {
88 			if (parse_option_str(val, "on"))
89 				efi_mem_encrypt = 1;
90 			else if (parse_option_str(val, "off"))
91 				efi_mem_encrypt = -1;
92 		} else if (!strcmp(param, "efi") && val) {
93 			efi_nochunk = parse_option_str(val, "nochunk");
94 			efi_novamap |= parse_option_str(val, "novamap");
95 
96 			efi_nosoftreserve = IS_ENABLED(CONFIG_EFI_SOFT_RESERVE) &&
97 					    parse_option_str(val, "nosoftreserve");
98 
99 			if (parse_option_str(val, "disable_early_pci_dma"))
100 				efi_disable_pci_dma = true;
101 			if (parse_option_str(val, "no_disable_early_pci_dma"))
102 				efi_disable_pci_dma = false;
103 			if (parse_option_str(val, "debug"))
104 				efi_loglevel = CONSOLE_LOGLEVEL_DEBUG;
105 		} else if (!strcmp(param, "video") &&
106 			   val && strstarts(val, "efifb:")) {
107 			efi_parse_option_graphics(val + strlen("efifb:"));
108 		}
109 	}
110 	return EFI_SUCCESS;
111 }
112 
113 /*
114  * The EFI_LOAD_OPTION descriptor has the following layout:
115  *	u32 Attributes;
116  *	u16 FilePathListLength;
117  *	u16 Description[];
118  *	efi_device_path_protocol_t FilePathList[];
119  *	u8 OptionalData[];
120  *
121  * This function validates and unpacks the variable-size data fields.
122  */
123 static
efi_load_option_unpack(efi_load_option_unpacked_t * dest,const efi_load_option_t * src,size_t size)124 bool efi_load_option_unpack(efi_load_option_unpacked_t *dest,
125 			    const efi_load_option_t *src, size_t size)
126 {
127 	const void *pos;
128 	u16 c;
129 	efi_device_path_protocol_t header;
130 	const efi_char16_t *description;
131 	const efi_device_path_protocol_t *file_path_list;
132 
133 	if (size < offsetof(efi_load_option_t, variable_data))
134 		return false;
135 	pos = src->variable_data;
136 	size -= offsetof(efi_load_option_t, variable_data);
137 
138 	if ((src->attributes & ~EFI_LOAD_OPTION_MASK) != 0)
139 		return false;
140 
141 	/* Scan description. */
142 	description = pos;
143 	do {
144 		if (size < sizeof(c))
145 			return false;
146 		c = *(const u16 *)pos;
147 		pos += sizeof(c);
148 		size -= sizeof(c);
149 	} while (c != L'\0');
150 
151 	/* Scan file_path_list. */
152 	file_path_list = pos;
153 	do {
154 		if (size < sizeof(header))
155 			return false;
156 		header = *(const efi_device_path_protocol_t *)pos;
157 		if (header.length < sizeof(header))
158 			return false;
159 		if (size < header.length)
160 			return false;
161 		pos += header.length;
162 		size -= header.length;
163 	} while ((header.type != EFI_DEV_END_PATH && header.type != EFI_DEV_END_PATH2) ||
164 		 (header.sub_type != EFI_DEV_END_ENTIRE));
165 	if (pos != (const void *)file_path_list + src->file_path_list_length)
166 		return false;
167 
168 	dest->attributes = src->attributes;
169 	dest->file_path_list_length = src->file_path_list_length;
170 	dest->description = description;
171 	dest->file_path_list = file_path_list;
172 	dest->optional_data_size = size;
173 	dest->optional_data = size ? pos : NULL;
174 
175 	return true;
176 }
177 
178 /*
179  * At least some versions of Dell firmware pass the entire contents of the
180  * Boot#### variable, i.e. the EFI_LOAD_OPTION descriptor, rather than just the
181  * OptionalData field.
182  *
183  * Detect this case and extract OptionalData.
184  */
efi_apply_loadoptions_quirk(const void ** load_options,u32 * load_options_size)185 void efi_apply_loadoptions_quirk(const void **load_options, u32 *load_options_size)
186 {
187 	const efi_load_option_t *load_option = *load_options;
188 	efi_load_option_unpacked_t load_option_unpacked;
189 
190 	if (!IS_ENABLED(CONFIG_X86))
191 		return;
192 	if (!load_option)
193 		return;
194 	if (*load_options_size < sizeof(*load_option))
195 		return;
196 	if ((load_option->attributes & ~EFI_LOAD_OPTION_BOOT_MASK) != 0)
197 		return;
198 
199 	if (!efi_load_option_unpack(&load_option_unpacked, load_option, *load_options_size))
200 		return;
201 
202 	efi_warn_once(FW_BUG "LoadOptions is an EFI_LOAD_OPTION descriptor\n");
203 	efi_warn_once(FW_BUG "Using OptionalData as a workaround\n");
204 
205 	*load_options = load_option_unpacked.optional_data;
206 	*load_options_size = load_option_unpacked.optional_data_size;
207 }
208 
209 enum efistub_event_type {
210 	EFISTUB_EVT_INITRD,
211 	EFISTUB_EVT_LOAD_OPTIONS,
212 	EFISTUB_EVT_COUNT,
213 };
214 
215 #define STR_WITH_SIZE(s)	sizeof(s), s
216 
217 static const struct {
218 	u32		pcr_index;
219 	u32		event_id;
220 	u32		event_data_len;
221 	u8		event_data[52];
222 } events[] = {
223 	[EFISTUB_EVT_INITRD] = {
224 		9,
225 		INITRD_EVENT_TAG_ID,
226 		STR_WITH_SIZE("Linux initrd")
227 	},
228 	[EFISTUB_EVT_LOAD_OPTIONS] = {
229 		9,
230 		LOAD_OPTIONS_EVENT_TAG_ID,
231 		STR_WITH_SIZE("LOADED_IMAGE::LoadOptions")
232 	},
233 };
234 
235 static_assert(sizeof(efi_tcg2_event_t) == sizeof(efi_cc_event_t));
236 
237 union efistub_event {
238 	efi_tcg2_event_t	tcg2_data;
239 	efi_cc_event_t		cc_data;
240 };
241 
242 struct efistub_measured_event {
243 	union efistub_event	event_data;
244 	TCG_PCClientTaggedEvent tagged_event __packed;
245 };
246 
efi_measure_tagged_event(unsigned long load_addr,unsigned long load_size,enum efistub_event_type event)247 static efi_status_t efi_measure_tagged_event(unsigned long load_addr,
248 					     unsigned long load_size,
249 					     enum efistub_event_type event)
250 {
251 	union {
252 		efi_status_t
253 		(__efiapi *hash_log_extend_event)(void *, u64, efi_physical_addr_t,
254 						  u64, const union efistub_event *);
255 		struct { u32 hash_log_extend_event; } mixed_mode;
256 	} method;
257 	struct efistub_measured_event *evt __free(efi_pool) = NULL;
258 	int size = struct_size(evt, tagged_event.tagged_event_data,
259 			       events[event].event_data_len);
260 	efi_guid_t tcg2_guid = EFI_TCG2_PROTOCOL_GUID;
261 	efi_tcg2_protocol_t *tcg2 = NULL;
262 	union efistub_event ev;
263 	efi_status_t status;
264 	void *protocol;
265 
266 	efi_bs_call(locate_protocol, &tcg2_guid, NULL, (void **)&tcg2);
267 	if (tcg2) {
268 		ev.tcg2_data = (struct efi_tcg2_event){
269 			.event_size			= size,
270 			.event_header.header_size	= sizeof(ev.tcg2_data.event_header),
271 			.event_header.header_version	= EFI_TCG2_EVENT_HEADER_VERSION,
272 			.event_header.pcr_index		= events[event].pcr_index,
273 			.event_header.event_type	= EV_EVENT_TAG,
274 		};
275 		protocol = tcg2;
276 		method.hash_log_extend_event =
277 			(void *)efi_table_attr(tcg2, hash_log_extend_event);
278 	} else {
279 		efi_guid_t cc_guid = EFI_CC_MEASUREMENT_PROTOCOL_GUID;
280 		efi_cc_protocol_t *cc = NULL;
281 
282 		efi_bs_call(locate_protocol, &cc_guid, NULL, (void **)&cc);
283 		if (!cc)
284 			return EFI_UNSUPPORTED;
285 
286 		ev.cc_data = (struct efi_cc_event){
287 			.event_size			= size,
288 			.event_header.header_size	= sizeof(ev.cc_data.event_header),
289 			.event_header.header_version	= EFI_CC_EVENT_HEADER_VERSION,
290 			.event_header.event_type	= EV_EVENT_TAG,
291 		};
292 
293 		status = efi_call_proto(cc, map_pcr_to_mr_index,
294 					events[event].pcr_index,
295 					&ev.cc_data.event_header.mr_index);
296 		if (status != EFI_SUCCESS)
297 			goto fail;
298 
299 		protocol = cc;
300 		method.hash_log_extend_event =
301 			(void *)efi_table_attr(cc, hash_log_extend_event);
302 	}
303 
304 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, size, (void **)&evt);
305 	if (status != EFI_SUCCESS)
306 		goto fail;
307 
308 	*evt = (struct efistub_measured_event) {
309 		.event_data			     = ev,
310 		.tagged_event.tagged_event_id	     = events[event].event_id,
311 		.tagged_event.tagged_event_data_size = events[event].event_data_len,
312 	};
313 
314 	memcpy(evt->tagged_event.tagged_event_data, events[event].event_data,
315 	       events[event].event_data_len);
316 
317 	status = efi_fn_call(&method, hash_log_extend_event, protocol, 0,
318 			     load_addr, load_size, &evt->event_data);
319 
320 	if (status == EFI_SUCCESS)
321 		return EFI_SUCCESS;
322 
323 fail:
324 	efi_warn("Failed to measure data for event %d: 0x%lx\n", event, status);
325 	return status;
326 }
327 
328 /*
329  * Convert the unicode UEFI command line to ASCII to pass to kernel.
330  * Size of memory allocated return in *cmd_line_len.
331  * Returns NULL on error.
332  */
efi_convert_cmdline(efi_loaded_image_t * image)333 char *efi_convert_cmdline(efi_loaded_image_t *image)
334 {
335 	const efi_char16_t *options = efi_table_attr(image, load_options);
336 	u32 options_size = efi_table_attr(image, load_options_size);
337 	int options_bytes = 0, safe_options_bytes = 0;  /* UTF-8 bytes */
338 	unsigned long cmdline_addr = 0;
339 	const efi_char16_t *s2;
340 	bool in_quote = false;
341 	efi_status_t status;
342 	u32 options_chars;
343 
344 	if (options_size > 0)
345 		efi_measure_tagged_event((unsigned long)options, options_size,
346 					 EFISTUB_EVT_LOAD_OPTIONS);
347 
348 	efi_apply_loadoptions_quirk((const void **)&options, &options_size);
349 	options_chars = options_size / sizeof(efi_char16_t);
350 
351 	if (options) {
352 		s2 = options;
353 		while (options_bytes < COMMAND_LINE_SIZE && options_chars--) {
354 			efi_char16_t c = *s2++;
355 
356 			if (c < 0x80) {
357 				if (c == L'\0' || c == L'\n')
358 					break;
359 				if (c == L'"')
360 					in_quote = !in_quote;
361 				else if (!in_quote && isspace((char)c))
362 					safe_options_bytes = options_bytes;
363 
364 				options_bytes++;
365 				continue;
366 			}
367 
368 			/*
369 			 * Get the number of UTF-8 bytes corresponding to a
370 			 * UTF-16 character.
371 			 * The first part handles everything in the BMP.
372 			 */
373 			options_bytes += 2 + (c >= 0x800);
374 			/*
375 			 * Add one more byte for valid surrogate pairs. Invalid
376 			 * surrogates will be replaced with 0xfffd and take up
377 			 * only 3 bytes.
378 			 */
379 			if ((c & 0xfc00) == 0xd800) {
380 				/*
381 				 * If the very last word is a high surrogate,
382 				 * we must ignore it since we can't access the
383 				 * low surrogate.
384 				 */
385 				if (!options_chars) {
386 					options_bytes -= 3;
387 				} else if ((*s2 & 0xfc00) == 0xdc00) {
388 					options_bytes++;
389 					options_chars--;
390 					s2++;
391 				}
392 			}
393 		}
394 		if (options_bytes >= COMMAND_LINE_SIZE) {
395 			options_bytes = safe_options_bytes;
396 			efi_err("Command line is too long: truncated to %d bytes\n",
397 				options_bytes);
398 		}
399 	}
400 
401 	options_bytes++;	/* NUL termination */
402 
403 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, options_bytes,
404 			     (void **)&cmdline_addr);
405 	if (status != EFI_SUCCESS)
406 		return NULL;
407 
408 	snprintf((char *)cmdline_addr, options_bytes, "%.*ls",
409 		 options_bytes - 1, options);
410 
411 	return (char *)cmdline_addr;
412 }
413 
414 /**
415  * efi_exit_boot_services() - Exit boot services
416  * @handle:	handle of the exiting image
417  * @priv:	argument to be passed to @priv_func
418  * @priv_func:	function to process the memory map before exiting boot services
419  *
420  * Handle calling ExitBootServices according to the requirements set out by the
421  * spec.  Obtains the current memory map, and returns that info after calling
422  * ExitBootServices.  The client must specify a function to perform any
423  * processing of the memory map data prior to ExitBootServices.  A client
424  * specific structure may be passed to the function via priv.  The client
425  * function may be called multiple times.
426  *
427  * Return:	status code
428  */
efi_exit_boot_services(void * handle,void * priv,efi_exit_boot_map_processing priv_func)429 efi_status_t efi_exit_boot_services(void *handle, void *priv,
430 				    efi_exit_boot_map_processing priv_func)
431 {
432 	struct efi_boot_memmap *map;
433 	efi_status_t status;
434 
435 	if (efi_disable_pci_dma)
436 		efi_pci_disable_bridge_busmaster();
437 
438 	status = efi_get_memory_map(&map, true);
439 	if (status != EFI_SUCCESS)
440 		return status;
441 
442 	status = priv_func(map, priv);
443 	if (status != EFI_SUCCESS) {
444 		efi_bs_call(free_pool, map);
445 		return status;
446 	}
447 
448 	status = efi_bs_call(exit_boot_services, handle, map->map_key);
449 
450 	if (status == EFI_INVALID_PARAMETER) {
451 		/*
452 		 * The memory map changed between efi_get_memory_map() and
453 		 * exit_boot_services().  Per the UEFI Spec v2.6, Section 6.4:
454 		 * EFI_BOOT_SERVICES.ExitBootServices we need to get the
455 		 * updated map, and try again.  The spec implies one retry
456 		 * should be sufficent, which is confirmed against the EDK2
457 		 * implementation.  Per the spec, we can only invoke
458 		 * get_memory_map() and exit_boot_services() - we cannot alloc
459 		 * so efi_get_memory_map() cannot be used, and we must reuse
460 		 * the buffer.  For all practical purposes, the headroom in the
461 		 * buffer should account for any changes in the map so the call
462 		 * to get_memory_map() is expected to succeed here.
463 		 */
464 		map->map_size = map->buff_size;
465 		status = efi_bs_call(get_memory_map,
466 				     &map->map_size,
467 				     &map->map,
468 				     &map->map_key,
469 				     &map->desc_size,
470 				     &map->desc_ver);
471 
472 		/* exit_boot_services() was called, thus cannot free */
473 		if (status != EFI_SUCCESS)
474 			return status;
475 
476 		status = priv_func(map, priv);
477 		/* exit_boot_services() was called, thus cannot free */
478 		if (status != EFI_SUCCESS)
479 			return status;
480 
481 		status = efi_bs_call(exit_boot_services, handle, map->map_key);
482 	}
483 
484 	return status;
485 }
486 
487 /**
488  * get_efi_config_table() - retrieve UEFI configuration table
489  * @guid:	GUID of the configuration table to be retrieved
490  * Return:	pointer to the configuration table or NULL
491  */
get_efi_config_table(efi_guid_t guid)492 void *get_efi_config_table(efi_guid_t guid)
493 {
494 	unsigned long tables = efi_table_attr(efi_system_table, tables);
495 	int nr_tables = efi_table_attr(efi_system_table, nr_tables);
496 	int i;
497 
498 	for (i = 0; i < nr_tables; i++) {
499 		efi_config_table_t *t = (void *)tables;
500 
501 		if (efi_guidcmp(t->guid, guid) == 0)
502 			return efi_table_attr(t, table);
503 
504 		tables += efi_is_native() ? sizeof(efi_config_table_t)
505 					  : sizeof(efi_config_table_32_t);
506 	}
507 	return NULL;
508 }
509 
510 /*
511  * The LINUX_EFI_INITRD_MEDIA_GUID vendor media device path below provides a way
512  * for the firmware or bootloader to expose the initrd data directly to the stub
513  * via the trivial LoadFile2 protocol, which is defined in the UEFI spec, and is
514  * very easy to implement. It is a simple Linux initrd specific conduit between
515  * kernel and firmware, allowing us to put the EFI stub (being part of the
516  * kernel) in charge of where and when to load the initrd, while leaving it up
517  * to the firmware to decide whether it needs to expose its filesystem hierarchy
518  * via EFI protocols.
519  */
520 static const struct {
521 	struct efi_vendor_dev_path	vendor;
522 	struct efi_generic_dev_path	end;
523 } __packed initrd_dev_path = {
524 	{
525 		{
526 			EFI_DEV_MEDIA,
527 			EFI_DEV_MEDIA_VENDOR,
528 			sizeof(struct efi_vendor_dev_path),
529 		},
530 		LINUX_EFI_INITRD_MEDIA_GUID
531 	}, {
532 		EFI_DEV_END_PATH,
533 		EFI_DEV_END_ENTIRE,
534 		sizeof(struct efi_generic_dev_path)
535 	}
536 };
537 
538 /**
539  * efi_load_initrd_dev_path() - load the initrd from the Linux initrd device path
540  * @initrd:	pointer of struct to store the address where the initrd was loaded
541  *		and the size of the loaded initrd
542  * @max:	upper limit for the initrd memory allocation
543  *
544  * Return:
545  * * %EFI_SUCCESS if the initrd was loaded successfully, in which
546  *   case @load_addr and @load_size are assigned accordingly
547  * * %EFI_NOT_FOUND if no LoadFile2 protocol exists on the initrd device path
548  * * %EFI_OUT_OF_RESOURCES if memory allocation failed
549  * * %EFI_LOAD_ERROR in all other cases
550  */
551 static
efi_load_initrd_dev_path(struct linux_efi_initrd * initrd,unsigned long max)552 efi_status_t efi_load_initrd_dev_path(struct linux_efi_initrd *initrd,
553 				      unsigned long max)
554 {
555 	efi_guid_t lf2_proto_guid = EFI_LOAD_FILE2_PROTOCOL_GUID;
556 	efi_device_path_protocol_t *dp;
557 	efi_load_file2_protocol_t *lf2;
558 	efi_handle_t handle;
559 	efi_status_t status;
560 
561 	dp = (efi_device_path_protocol_t *)&initrd_dev_path;
562 	status = efi_bs_call(locate_device_path, &lf2_proto_guid, &dp, &handle);
563 	if (status != EFI_SUCCESS)
564 		return status;
565 
566 	status = efi_bs_call(handle_protocol, handle, &lf2_proto_guid,
567 			     (void **)&lf2);
568 	if (status != EFI_SUCCESS)
569 		return status;
570 
571 	initrd->size = 0;
572 	status = efi_call_proto(lf2, load_file, dp, false, &initrd->size, NULL);
573 	if (status != EFI_BUFFER_TOO_SMALL)
574 		return EFI_LOAD_ERROR;
575 
576 	status = efi_allocate_pages(initrd->size, &initrd->base, max);
577 	if (status != EFI_SUCCESS)
578 		return status;
579 
580 	status = efi_call_proto(lf2, load_file, dp, false, &initrd->size,
581 				(void *)initrd->base);
582 	if (status != EFI_SUCCESS) {
583 		efi_free(initrd->size, initrd->base);
584 		return EFI_LOAD_ERROR;
585 	}
586 	return EFI_SUCCESS;
587 }
588 
589 static
efi_load_initrd_cmdline(efi_loaded_image_t * image,struct linux_efi_initrd * initrd,unsigned long soft_limit,unsigned long hard_limit)590 efi_status_t efi_load_initrd_cmdline(efi_loaded_image_t *image,
591 				     struct linux_efi_initrd *initrd,
592 				     unsigned long soft_limit,
593 				     unsigned long hard_limit)
594 {
595 	if (image == NULL)
596 		return EFI_UNSUPPORTED;
597 
598 	return handle_cmdline_files(image, L"initrd=", sizeof(L"initrd=") - 2,
599 				    soft_limit, hard_limit,
600 				    &initrd->base, &initrd->size);
601 }
602 
603 /**
604  * efi_load_initrd() - Load initial RAM disk
605  * @image:	EFI loaded image protocol
606  * @soft_limit:	preferred address for loading the initrd
607  * @hard_limit:	upper limit address for loading the initrd
608  * @out:	pointer to store the address of the initrd table
609  *
610  * Return:	status code
611  */
efi_load_initrd(efi_loaded_image_t * image,unsigned long soft_limit,unsigned long hard_limit,const struct linux_efi_initrd ** out)612 efi_status_t efi_load_initrd(efi_loaded_image_t *image,
613 			     unsigned long soft_limit,
614 			     unsigned long hard_limit,
615 			     const struct linux_efi_initrd **out)
616 {
617 	efi_guid_t tbl_guid = LINUX_EFI_INITRD_MEDIA_GUID;
618 	efi_status_t status = EFI_SUCCESS;
619 	struct linux_efi_initrd initrd, *tbl;
620 
621 	if (!IS_ENABLED(CONFIG_BLK_DEV_INITRD) || efi_noinitrd)
622 		return EFI_SUCCESS;
623 
624 	status = efi_load_initrd_dev_path(&initrd, hard_limit);
625 	if (status == EFI_SUCCESS) {
626 		efi_info("Loaded initrd from LINUX_EFI_INITRD_MEDIA_GUID device path\n");
627 	} else if (status == EFI_NOT_FOUND) {
628 		status = efi_load_initrd_cmdline(image, &initrd, soft_limit,
629 						 hard_limit);
630 		/* command line loader disabled or no initrd= passed? */
631 		if (status == EFI_UNSUPPORTED || status == EFI_NOT_READY)
632 			return EFI_SUCCESS;
633 		if (status == EFI_SUCCESS)
634 			efi_info("Loaded initrd from command line option\n");
635 	}
636 	if (status != EFI_SUCCESS)
637 		goto failed;
638 
639 	if (initrd.size > 0 &&
640 	    efi_measure_tagged_event(initrd.base, initrd.size,
641 				     EFISTUB_EVT_INITRD) == EFI_SUCCESS)
642 		efi_info("Measured initrd data into PCR 9\n");
643 
644 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, sizeof(initrd),
645 			     (void **)&tbl);
646 	if (status != EFI_SUCCESS)
647 		goto free_initrd;
648 
649 	*tbl = initrd;
650 	status = efi_bs_call(install_configuration_table, &tbl_guid, tbl);
651 	if (status != EFI_SUCCESS)
652 		goto free_tbl;
653 
654 	if (out)
655 		*out = tbl;
656 	return EFI_SUCCESS;
657 
658 free_tbl:
659 	efi_bs_call(free_pool, tbl);
660 free_initrd:
661 	efi_free(initrd.size, initrd.base);
662 failed:
663 	efi_err("Failed to load initrd: 0x%lx\n", status);
664 	return status;
665 }
666 
667 /**
668  * efi_wait_for_key() - Wait for key stroke
669  * @usec:	number of microseconds to wait for key stroke
670  * @key:	key entered
671  *
672  * Wait for up to @usec microseconds for a key stroke.
673  *
674  * Return:	status code, EFI_SUCCESS if key received
675  */
efi_wait_for_key(unsigned long usec,efi_input_key_t * key)676 efi_status_t efi_wait_for_key(unsigned long usec, efi_input_key_t *key)
677 {
678 	efi_event_t events[2], timer;
679 	unsigned long index;
680 	efi_simple_text_input_protocol_t *con_in;
681 	efi_status_t status;
682 
683 	con_in = efi_table_attr(efi_system_table, con_in);
684 	if (!con_in)
685 		return EFI_UNSUPPORTED;
686 	efi_set_event_at(events, 0, efi_table_attr(con_in, wait_for_key));
687 
688 	status = efi_bs_call(create_event, EFI_EVT_TIMER, 0, NULL, NULL, &timer);
689 	if (status != EFI_SUCCESS)
690 		return status;
691 
692 	status = efi_bs_call(set_timer, timer, EfiTimerRelative,
693 			     EFI_100NSEC_PER_USEC * usec);
694 	if (status != EFI_SUCCESS)
695 		return status;
696 	efi_set_event_at(events, 1, timer);
697 
698 	status = efi_bs_call(wait_for_event, 2, events, &index);
699 	if (status == EFI_SUCCESS) {
700 		if (index == 0)
701 			status = efi_call_proto(con_in, read_keystroke, key);
702 		else
703 			status = EFI_TIMEOUT;
704 	}
705 
706 	efi_bs_call(close_event, timer);
707 
708 	return status;
709 }
710 
711 /**
712  * efi_remap_image - Remap a loaded image with the appropriate permissions
713  *                   for code and data
714  *
715  * @image_base:	the base of the image in memory
716  * @alloc_size:	the size of the area in memory occupied by the image
717  * @code_size:	the size of the leading part of the image containing code
718  * 		and read-only data
719  *
720  * efi_remap_image() uses the EFI memory attribute protocol to remap the code
721  * region of the loaded image read-only/executable, and the remainder
722  * read-write/non-executable. The code region is assumed to start at the base
723  * of the image, and will therefore cover the PE/COFF header as well.
724  */
efi_remap_image(unsigned long image_base,unsigned alloc_size,unsigned long code_size)725 void efi_remap_image(unsigned long image_base, unsigned alloc_size,
726 		     unsigned long code_size)
727 {
728 	efi_guid_t guid = EFI_MEMORY_ATTRIBUTE_PROTOCOL_GUID;
729 	efi_memory_attribute_protocol_t *memattr;
730 	efi_status_t status;
731 	u64 attr;
732 
733 	/*
734 	 * If the firmware implements the EFI_MEMORY_ATTRIBUTE_PROTOCOL, let's
735 	 * invoke it to remap the text/rodata region of the decompressed image
736 	 * as read-only and the data/bss region as non-executable.
737 	 */
738 	status = efi_bs_call(locate_protocol, &guid, NULL, (void **)&memattr);
739 	if (status != EFI_SUCCESS)
740 		return;
741 
742 	// Get the current attributes for the entire region
743 	status = memattr->get_memory_attributes(memattr, image_base,
744 						alloc_size, &attr);
745 	if (status != EFI_SUCCESS) {
746 		efi_warn("Failed to retrieve memory attributes for image region: 0x%lx\n",
747 			 status);
748 		return;
749 	}
750 
751 	// Mark the code region as read-only
752 	status = memattr->set_memory_attributes(memattr, image_base, code_size,
753 						EFI_MEMORY_RO);
754 	if (status != EFI_SUCCESS) {
755 		efi_warn("Failed to remap code region read-only\n");
756 		return;
757 	}
758 
759 	// If the entire region was already mapped as non-exec, clear the
760 	// attribute from the code region. Otherwise, set it on the data
761 	// region.
762 	if (attr & EFI_MEMORY_XP) {
763 		status = memattr->clear_memory_attributes(memattr, image_base,
764 							  code_size,
765 							  EFI_MEMORY_XP);
766 		if (status != EFI_SUCCESS)
767 			efi_warn("Failed to remap code region executable\n");
768 	} else {
769 		status = memattr->set_memory_attributes(memattr,
770 							image_base + code_size,
771 							alloc_size - code_size,
772 							EFI_MEMORY_XP);
773 		if (status != EFI_SUCCESS)
774 			efi_warn("Failed to remap data region non-executable\n");
775 	}
776 }
777