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 <stdarg.h>
11 
12 #include <linux/efi.h>
13 #include <linux/kernel.h>
14 #include <linux/printk.h> /* For CONSOLE_LOGLEVEL_* */
15 #include <asm/efi.h>
16 
17 #include "efistub.h"
18 
19 bool efi_nochunk;
20 bool efi_nokaslr;
21 bool efi_noinitrd;
22 int efi_loglevel = CONSOLE_LOGLEVEL_DEFAULT;
23 bool efi_novamap;
24 
25 static bool efi_nosoftreserve;
26 static bool efi_disable_pci_dma = IS_ENABLED(CONFIG_EFI_DISABLE_PCI_DMA);
27 
28 bool __pure __efi_soft_reserve_enabled(void)
29 {
30 	return !efi_nosoftreserve;
31 }
32 
33 void efi_char16_puts(efi_char16_t *str)
34 {
35 	efi_call_proto(efi_table_attr(efi_system_table, con_out),
36 		       output_string, str);
37 }
38 
39 void efi_puts(const char *str)
40 {
41 	efi_char16_t buf[128];
42 	size_t pos = 0, lim = ARRAY_SIZE(buf);
43 
44 	while (*str) {
45 		if (*str == '\n')
46 			buf[pos++] = L'\r';
47 		/* Cast to unsigned char to avoid sign-extension */
48 		buf[pos++] = (unsigned char)(*str++);
49 		if (*str == '\0' || pos >= lim - 2) {
50 			buf[pos] = L'\0';
51 			efi_char16_puts(buf);
52 			pos = 0;
53 		}
54 	}
55 }
56 
57 int efi_printk(const char *fmt, ...)
58 {
59 	char printf_buf[256];
60 	va_list args;
61 	int printed;
62 	int loglevel = printk_get_level(fmt);
63 
64 	switch (loglevel) {
65 	case '0' ... '9':
66 		loglevel -= '0';
67 		break;
68 	default:
69 		/*
70 		 * Use loglevel -1 for cases where we just want to print to
71 		 * the screen.
72 		 */
73 		loglevel = -1;
74 		break;
75 	}
76 
77 	if (loglevel >= efi_loglevel)
78 		return 0;
79 
80 	if (loglevel >= 0)
81 		efi_puts("EFI stub: ");
82 
83 	fmt = printk_skip_level(fmt);
84 
85 	va_start(args, fmt);
86 	printed = vsnprintf(printf_buf, sizeof(printf_buf), fmt, args);
87 	va_end(args);
88 
89 	efi_puts(printf_buf);
90 	if (printed >= sizeof(printf_buf)) {
91 		efi_puts("[Message truncated]\n");
92 		return -1;
93 	}
94 
95 	return printed;
96 }
97 
98 /*
99  * Parse the ASCII string 'cmdline' for EFI options, denoted by the efi=
100  * option, e.g. efi=nochunk.
101  *
102  * It should be noted that efi= is parsed in two very different
103  * environments, first in the early boot environment of the EFI boot
104  * stub, and subsequently during the kernel boot.
105  */
106 efi_status_t efi_parse_options(char const *cmdline)
107 {
108 	size_t len = strlen(cmdline) + 1;
109 	efi_status_t status;
110 	char *str, *buf;
111 
112 	status = efi_bs_call(allocate_pool, EFI_LOADER_DATA, len, (void **)&buf);
113 	if (status != EFI_SUCCESS)
114 		return status;
115 
116 	str = skip_spaces(memcpy(buf, cmdline, len));
117 
118 	while (*str) {
119 		char *param, *val;
120 
121 		str = next_arg(str, &param, &val);
122 
123 		if (!strcmp(param, "nokaslr")) {
124 			efi_nokaslr = true;
125 		} else if (!strcmp(param, "quiet")) {
126 			efi_loglevel = CONSOLE_LOGLEVEL_QUIET;
127 		} else if (!strcmp(param, "noinitrd")) {
128 			efi_noinitrd = true;
129 		} else if (!strcmp(param, "efi") && val) {
130 			efi_nochunk = parse_option_str(val, "nochunk");
131 			efi_novamap = parse_option_str(val, "novamap");
132 
133 			efi_nosoftreserve = IS_ENABLED(CONFIG_EFI_SOFT_RESERVE) &&
134 					    parse_option_str(val, "nosoftreserve");
135 
136 			if (parse_option_str(val, "disable_early_pci_dma"))
137 				efi_disable_pci_dma = true;
138 			if (parse_option_str(val, "no_disable_early_pci_dma"))
139 				efi_disable_pci_dma = false;
140 			if (parse_option_str(val, "debug"))
141 				efi_loglevel = CONSOLE_LOGLEVEL_DEBUG;
142 		} else if (!strcmp(param, "video") &&
143 			   val && strstarts(val, "efifb:")) {
144 			efi_parse_option_graphics(val + strlen("efifb:"));
145 		}
146 	}
147 	efi_bs_call(free_pool, buf);
148 	return EFI_SUCCESS;
149 }
150 
151 /*
152  * Get the number of UTF-8 bytes corresponding to an UTF-16 character.
153  * This overestimates for surrogates, but that is okay.
154  */
155 static int efi_utf8_bytes(u16 c)
156 {
157 	return 1 + (c >= 0x80) + (c >= 0x800);
158 }
159 
160 /*
161  * Convert an UTF-16 string, not necessarily null terminated, to UTF-8.
162  */
163 static u8 *efi_utf16_to_utf8(u8 *dst, const u16 *src, int n)
164 {
165 	unsigned int c;
166 
167 	while (n--) {
168 		c = *src++;
169 		if (n && c >= 0xd800 && c <= 0xdbff &&
170 		    *src >= 0xdc00 && *src <= 0xdfff) {
171 			c = 0x10000 + ((c & 0x3ff) << 10) + (*src & 0x3ff);
172 			src++;
173 			n--;
174 		}
175 		if (c >= 0xd800 && c <= 0xdfff)
176 			c = 0xfffd; /* Unmatched surrogate */
177 		if (c < 0x80) {
178 			*dst++ = c;
179 			continue;
180 		}
181 		if (c < 0x800) {
182 			*dst++ = 0xc0 + (c >> 6);
183 			goto t1;
184 		}
185 		if (c < 0x10000) {
186 			*dst++ = 0xe0 + (c >> 12);
187 			goto t2;
188 		}
189 		*dst++ = 0xf0 + (c >> 18);
190 		*dst++ = 0x80 + ((c >> 12) & 0x3f);
191 	t2:
192 		*dst++ = 0x80 + ((c >> 6) & 0x3f);
193 	t1:
194 		*dst++ = 0x80 + (c & 0x3f);
195 	}
196 
197 	return dst;
198 }
199 
200 /*
201  * Convert the unicode UEFI command line to ASCII to pass to kernel.
202  * Size of memory allocated return in *cmd_line_len.
203  * Returns NULL on error.
204  */
205 char *efi_convert_cmdline(efi_loaded_image_t *image,
206 			  int *cmd_line_len, unsigned long max_addr)
207 {
208 	const u16 *s2;
209 	u8 *s1 = NULL;
210 	unsigned long cmdline_addr = 0;
211 	int load_options_chars = efi_table_attr(image, load_options_size) / 2;
212 	const u16 *options = efi_table_attr(image, load_options);
213 	int options_bytes = 0;  /* UTF-8 bytes */
214 	int options_chars = 0;  /* UTF-16 chars */
215 	efi_status_t status;
216 	u16 zero = 0;
217 
218 	if (options) {
219 		s2 = options;
220 		while (*s2 && *s2 != '\n'
221 		       && options_chars < load_options_chars) {
222 			options_bytes += efi_utf8_bytes(*s2++);
223 			options_chars++;
224 		}
225 	}
226 
227 	if (!options_chars) {
228 		/* No command line options, so return empty string*/
229 		options = &zero;
230 	}
231 
232 	options_bytes++;	/* NUL termination */
233 
234 	status = efi_allocate_pages(options_bytes, &cmdline_addr, max_addr);
235 	if (status != EFI_SUCCESS)
236 		return NULL;
237 
238 	s1 = (u8 *)cmdline_addr;
239 	s2 = (const u16 *)options;
240 
241 	s1 = efi_utf16_to_utf8(s1, s2, options_chars);
242 	*s1 = '\0';
243 
244 	*cmd_line_len = options_bytes;
245 	return (char *)cmdline_addr;
246 }
247 
248 /*
249  * Handle calling ExitBootServices according to the requirements set out by the
250  * spec.  Obtains the current memory map, and returns that info after calling
251  * ExitBootServices.  The client must specify a function to perform any
252  * processing of the memory map data prior to ExitBootServices.  A client
253  * specific structure may be passed to the function via priv.  The client
254  * function may be called multiple times.
255  */
256 efi_status_t efi_exit_boot_services(void *handle,
257 				    struct efi_boot_memmap *map,
258 				    void *priv,
259 				    efi_exit_boot_map_processing priv_func)
260 {
261 	efi_status_t status;
262 
263 	status = efi_get_memory_map(map);
264 
265 	if (status != EFI_SUCCESS)
266 		goto fail;
267 
268 	status = priv_func(map, priv);
269 	if (status != EFI_SUCCESS)
270 		goto free_map;
271 
272 	if (efi_disable_pci_dma)
273 		efi_pci_disable_bridge_busmaster();
274 
275 	status = efi_bs_call(exit_boot_services, handle, *map->key_ptr);
276 
277 	if (status == EFI_INVALID_PARAMETER) {
278 		/*
279 		 * The memory map changed between efi_get_memory_map() and
280 		 * exit_boot_services().  Per the UEFI Spec v2.6, Section 6.4:
281 		 * EFI_BOOT_SERVICES.ExitBootServices we need to get the
282 		 * updated map, and try again.  The spec implies one retry
283 		 * should be sufficent, which is confirmed against the EDK2
284 		 * implementation.  Per the spec, we can only invoke
285 		 * get_memory_map() and exit_boot_services() - we cannot alloc
286 		 * so efi_get_memory_map() cannot be used, and we must reuse
287 		 * the buffer.  For all practical purposes, the headroom in the
288 		 * buffer should account for any changes in the map so the call
289 		 * to get_memory_map() is expected to succeed here.
290 		 */
291 		*map->map_size = *map->buff_size;
292 		status = efi_bs_call(get_memory_map,
293 				     map->map_size,
294 				     *map->map,
295 				     map->key_ptr,
296 				     map->desc_size,
297 				     map->desc_ver);
298 
299 		/* exit_boot_services() was called, thus cannot free */
300 		if (status != EFI_SUCCESS)
301 			goto fail;
302 
303 		status = priv_func(map, priv);
304 		/* exit_boot_services() was called, thus cannot free */
305 		if (status != EFI_SUCCESS)
306 			goto fail;
307 
308 		status = efi_bs_call(exit_boot_services, handle, *map->key_ptr);
309 	}
310 
311 	/* exit_boot_services() was called, thus cannot free */
312 	if (status != EFI_SUCCESS)
313 		goto fail;
314 
315 	return EFI_SUCCESS;
316 
317 free_map:
318 	efi_bs_call(free_pool, *map->map);
319 fail:
320 	return status;
321 }
322 
323 void *get_efi_config_table(efi_guid_t guid)
324 {
325 	unsigned long tables = efi_table_attr(efi_system_table, tables);
326 	int nr_tables = efi_table_attr(efi_system_table, nr_tables);
327 	int i;
328 
329 	for (i = 0; i < nr_tables; i++) {
330 		efi_config_table_t *t = (void *)tables;
331 
332 		if (efi_guidcmp(t->guid, guid) == 0)
333 			return efi_table_attr(t, table);
334 
335 		tables += efi_is_native() ? sizeof(efi_config_table_t)
336 					  : sizeof(efi_config_table_32_t);
337 	}
338 	return NULL;
339 }
340 
341 /*
342  * The LINUX_EFI_INITRD_MEDIA_GUID vendor media device path below provides a way
343  * for the firmware or bootloader to expose the initrd data directly to the stub
344  * via the trivial LoadFile2 protocol, which is defined in the UEFI spec, and is
345  * very easy to implement. It is a simple Linux initrd specific conduit between
346  * kernel and firmware, allowing us to put the EFI stub (being part of the
347  * kernel) in charge of where and when to load the initrd, while leaving it up
348  * to the firmware to decide whether it needs to expose its filesystem hierarchy
349  * via EFI protocols.
350  */
351 static const struct {
352 	struct efi_vendor_dev_path	vendor;
353 	struct efi_generic_dev_path	end;
354 } __packed initrd_dev_path = {
355 	{
356 		{
357 			EFI_DEV_MEDIA,
358 			EFI_DEV_MEDIA_VENDOR,
359 			sizeof(struct efi_vendor_dev_path),
360 		},
361 		LINUX_EFI_INITRD_MEDIA_GUID
362 	}, {
363 		EFI_DEV_END_PATH,
364 		EFI_DEV_END_ENTIRE,
365 		sizeof(struct efi_generic_dev_path)
366 	}
367 };
368 
369 /**
370  * efi_load_initrd_dev_path - load the initrd from the Linux initrd device path
371  * @load_addr:	pointer to store the address where the initrd was loaded
372  * @load_size:	pointer to store the size of the loaded initrd
373  * @max:	upper limit for the initrd memory allocation
374  * @return:	%EFI_SUCCESS if the initrd was loaded successfully, in which
375  *		case @load_addr and @load_size are assigned accordingly
376  *		%EFI_NOT_FOUND if no LoadFile2 protocol exists on the initrd
377  *		device path
378  *		%EFI_INVALID_PARAMETER if load_addr == NULL or load_size == NULL
379  *		%EFI_OUT_OF_RESOURCES if memory allocation failed
380  *		%EFI_LOAD_ERROR in all other cases
381  */
382 static
383 efi_status_t efi_load_initrd_dev_path(unsigned long *load_addr,
384 				      unsigned long *load_size,
385 				      unsigned long max)
386 {
387 	efi_guid_t lf2_proto_guid = EFI_LOAD_FILE2_PROTOCOL_GUID;
388 	efi_device_path_protocol_t *dp;
389 	efi_load_file2_protocol_t *lf2;
390 	unsigned long initrd_addr;
391 	unsigned long initrd_size;
392 	efi_handle_t handle;
393 	efi_status_t status;
394 
395 	dp = (efi_device_path_protocol_t *)&initrd_dev_path;
396 	status = efi_bs_call(locate_device_path, &lf2_proto_guid, &dp, &handle);
397 	if (status != EFI_SUCCESS)
398 		return status;
399 
400 	status = efi_bs_call(handle_protocol, handle, &lf2_proto_guid,
401 			     (void **)&lf2);
402 	if (status != EFI_SUCCESS)
403 		return status;
404 
405 	status = efi_call_proto(lf2, load_file, dp, false, &initrd_size, NULL);
406 	if (status != EFI_BUFFER_TOO_SMALL)
407 		return EFI_LOAD_ERROR;
408 
409 	status = efi_allocate_pages(initrd_size, &initrd_addr, max);
410 	if (status != EFI_SUCCESS)
411 		return status;
412 
413 	status = efi_call_proto(lf2, load_file, dp, false, &initrd_size,
414 				(void *)initrd_addr);
415 	if (status != EFI_SUCCESS) {
416 		efi_free(initrd_size, initrd_addr);
417 		return EFI_LOAD_ERROR;
418 	}
419 
420 	*load_addr = initrd_addr;
421 	*load_size = initrd_size;
422 	return EFI_SUCCESS;
423 }
424 
425 static
426 efi_status_t efi_load_initrd_cmdline(efi_loaded_image_t *image,
427 				     unsigned long *load_addr,
428 				     unsigned long *load_size,
429 				     unsigned long soft_limit,
430 				     unsigned long hard_limit)
431 {
432 	if (!IS_ENABLED(CONFIG_EFI_GENERIC_STUB_INITRD_CMDLINE_LOADER) ||
433 	    (IS_ENABLED(CONFIG_X86) && (!efi_is_native() || image == NULL))) {
434 		*load_addr = *load_size = 0;
435 		return EFI_SUCCESS;
436 	}
437 
438 	return handle_cmdline_files(image, L"initrd=", sizeof(L"initrd=") - 2,
439 				    soft_limit, hard_limit,
440 				    load_addr, load_size);
441 }
442 
443 efi_status_t efi_load_initrd(efi_loaded_image_t *image,
444 			     unsigned long *load_addr,
445 			     unsigned long *load_size,
446 			     unsigned long soft_limit,
447 			     unsigned long hard_limit)
448 {
449 	efi_status_t status;
450 
451 	if (!load_addr || !load_size)
452 		return EFI_INVALID_PARAMETER;
453 
454 	status = efi_load_initrd_dev_path(load_addr, load_size, hard_limit);
455 	if (status == EFI_SUCCESS) {
456 		efi_info("Loaded initrd from LINUX_EFI_INITRD_MEDIA_GUID device path\n");
457 	} else if (status == EFI_NOT_FOUND) {
458 		status = efi_load_initrd_cmdline(image, load_addr, load_size,
459 						 soft_limit, hard_limit);
460 		if (status == EFI_SUCCESS && *load_size > 0)
461 			efi_info("Loaded initrd from command line option\n");
462 	}
463 
464 	return status;
465 }
466