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