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/efi.h>
11 #include <asm/efi.h>
12 
13 #include "efistub.h"
14 
15 /*
16  * Some firmware implementations have problems reading files in one go.
17  * A read chunk size of 1MB seems to work for most platforms.
18  *
19  * Unfortunately, reading files in chunks triggers *other* bugs on some
20  * platforms, so we provide a way to disable this workaround, which can
21  * be done by passing "efi=nochunk" on the EFI boot stub command line.
22  *
23  * If you experience issues with initrd images being corrupt it's worth
24  * trying efi=nochunk, but chunking is enabled by default because there
25  * are far more machines that require the workaround than those that
26  * break with it enabled.
27  */
28 #define EFI_READ_CHUNK_SIZE	(1024 * 1024)
29 
30 static unsigned long __chunk_size = EFI_READ_CHUNK_SIZE;
31 
32 static int __section(.data) __nokaslr;
33 static int __section(.data) __quiet;
34 static int __section(.data) __novamap;
35 static bool __section(.data) efi_nosoftreserve;
36 
37 int __pure nokaslr(void)
38 {
39 	return __nokaslr;
40 }
41 int __pure is_quiet(void)
42 {
43 	return __quiet;
44 }
45 int __pure novamap(void)
46 {
47 	return __novamap;
48 }
49 bool __pure __efi_soft_reserve_enabled(void)
50 {
51 	return !efi_nosoftreserve;
52 }
53 
54 #define EFI_MMAP_NR_SLACK_SLOTS	8
55 
56 struct file_info {
57 	efi_file_handle_t *handle;
58 	u64 size;
59 };
60 
61 void efi_printk(efi_system_table_t *sys_table_arg, char *str)
62 {
63 	char *s8;
64 
65 	for (s8 = str; *s8; s8++) {
66 		efi_char16_t ch[2] = { 0 };
67 
68 		ch[0] = *s8;
69 		if (*s8 == '\n') {
70 			efi_char16_t nl[2] = { '\r', 0 };
71 			efi_char16_printk(sys_table_arg, nl);
72 		}
73 
74 		efi_char16_printk(sys_table_arg, ch);
75 	}
76 }
77 
78 static inline bool mmap_has_headroom(unsigned long buff_size,
79 				     unsigned long map_size,
80 				     unsigned long desc_size)
81 {
82 	unsigned long slack = buff_size - map_size;
83 
84 	return slack / desc_size >= EFI_MMAP_NR_SLACK_SLOTS;
85 }
86 
87 efi_status_t efi_get_memory_map(efi_system_table_t *sys_table_arg,
88 				struct efi_boot_memmap *map)
89 {
90 	efi_memory_desc_t *m = NULL;
91 	efi_status_t status;
92 	unsigned long key;
93 	u32 desc_version;
94 
95 	*map->desc_size =	sizeof(*m);
96 	*map->map_size =	*map->desc_size * 32;
97 	*map->buff_size =	*map->map_size;
98 again:
99 	status = efi_call_early(allocate_pool, EFI_LOADER_DATA,
100 				*map->map_size, (void **)&m);
101 	if (status != EFI_SUCCESS)
102 		goto fail;
103 
104 	*map->desc_size = 0;
105 	key = 0;
106 	status = efi_call_early(get_memory_map, map->map_size, m,
107 				&key, map->desc_size, &desc_version);
108 	if (status == EFI_BUFFER_TOO_SMALL ||
109 	    !mmap_has_headroom(*map->buff_size, *map->map_size,
110 			       *map->desc_size)) {
111 		efi_call_early(free_pool, m);
112 		/*
113 		 * Make sure there is some entries of headroom so that the
114 		 * buffer can be reused for a new map after allocations are
115 		 * no longer permitted.  Its unlikely that the map will grow to
116 		 * exceed this headroom once we are ready to trigger
117 		 * ExitBootServices()
118 		 */
119 		*map->map_size += *map->desc_size * EFI_MMAP_NR_SLACK_SLOTS;
120 		*map->buff_size = *map->map_size;
121 		goto again;
122 	}
123 
124 	if (status != EFI_SUCCESS)
125 		efi_call_early(free_pool, m);
126 
127 	if (map->key_ptr && status == EFI_SUCCESS)
128 		*map->key_ptr = key;
129 	if (map->desc_ver && status == EFI_SUCCESS)
130 		*map->desc_ver = desc_version;
131 
132 fail:
133 	*map->map = m;
134 	return status;
135 }
136 
137 
138 unsigned long get_dram_base(efi_system_table_t *sys_table_arg)
139 {
140 	efi_status_t status;
141 	unsigned long map_size, buff_size;
142 	unsigned long membase  = EFI_ERROR;
143 	struct efi_memory_map map;
144 	efi_memory_desc_t *md;
145 	struct efi_boot_memmap boot_map;
146 
147 	boot_map.map =		(efi_memory_desc_t **)&map.map;
148 	boot_map.map_size =	&map_size;
149 	boot_map.desc_size =	&map.desc_size;
150 	boot_map.desc_ver =	NULL;
151 	boot_map.key_ptr =	NULL;
152 	boot_map.buff_size =	&buff_size;
153 
154 	status = efi_get_memory_map(sys_table_arg, &boot_map);
155 	if (status != EFI_SUCCESS)
156 		return membase;
157 
158 	map.map_end = map.map + map_size;
159 
160 	for_each_efi_memory_desc_in_map(&map, md) {
161 		if (md->attribute & EFI_MEMORY_WB) {
162 			if (membase > md->phys_addr)
163 				membase = md->phys_addr;
164 		}
165 	}
166 
167 	efi_call_early(free_pool, map.map);
168 
169 	return membase;
170 }
171 
172 /*
173  * Allocate at the highest possible address that is not above 'max'.
174  */
175 efi_status_t efi_high_alloc(efi_system_table_t *sys_table_arg,
176 			    unsigned long size, unsigned long align,
177 			    unsigned long *addr, unsigned long max)
178 {
179 	unsigned long map_size, desc_size, buff_size;
180 	efi_memory_desc_t *map;
181 	efi_status_t status;
182 	unsigned long nr_pages;
183 	u64 max_addr = 0;
184 	int i;
185 	struct efi_boot_memmap boot_map;
186 
187 	boot_map.map =		&map;
188 	boot_map.map_size =	&map_size;
189 	boot_map.desc_size =	&desc_size;
190 	boot_map.desc_ver =	NULL;
191 	boot_map.key_ptr =	NULL;
192 	boot_map.buff_size =	&buff_size;
193 
194 	status = efi_get_memory_map(sys_table_arg, &boot_map);
195 	if (status != EFI_SUCCESS)
196 		goto fail;
197 
198 	/*
199 	 * Enforce minimum alignment that EFI or Linux requires when
200 	 * requesting a specific address.  We are doing page-based (or
201 	 * larger) allocations, and both the address and size must meet
202 	 * alignment constraints.
203 	 */
204 	if (align < EFI_ALLOC_ALIGN)
205 		align = EFI_ALLOC_ALIGN;
206 
207 	size = round_up(size, EFI_ALLOC_ALIGN);
208 	nr_pages = size / EFI_PAGE_SIZE;
209 again:
210 	for (i = 0; i < map_size / desc_size; i++) {
211 		efi_memory_desc_t *desc;
212 		unsigned long m = (unsigned long)map;
213 		u64 start, end;
214 
215 		desc = efi_early_memdesc_ptr(m, desc_size, i);
216 		if (desc->type != EFI_CONVENTIONAL_MEMORY)
217 			continue;
218 
219 		if (efi_soft_reserve_enabled() &&
220 		    (desc->attribute & EFI_MEMORY_SP))
221 			continue;
222 
223 		if (desc->num_pages < nr_pages)
224 			continue;
225 
226 		start = desc->phys_addr;
227 		end = start + desc->num_pages * EFI_PAGE_SIZE;
228 
229 		if (end > max)
230 			end = max;
231 
232 		if ((start + size) > end)
233 			continue;
234 
235 		if (round_down(end - size, align) < start)
236 			continue;
237 
238 		start = round_down(end - size, align);
239 
240 		/*
241 		 * Don't allocate at 0x0. It will confuse code that
242 		 * checks pointers against NULL.
243 		 */
244 		if (start == 0x0)
245 			continue;
246 
247 		if (start > max_addr)
248 			max_addr = start;
249 	}
250 
251 	if (!max_addr)
252 		status = EFI_NOT_FOUND;
253 	else {
254 		status = efi_call_early(allocate_pages,
255 					EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA,
256 					nr_pages, &max_addr);
257 		if (status != EFI_SUCCESS) {
258 			max = max_addr;
259 			max_addr = 0;
260 			goto again;
261 		}
262 
263 		*addr = max_addr;
264 	}
265 
266 	efi_call_early(free_pool, map);
267 fail:
268 	return status;
269 }
270 
271 /*
272  * Allocate at the lowest possible address that is not below 'min'.
273  */
274 efi_status_t efi_low_alloc_above(efi_system_table_t *sys_table_arg,
275 				 unsigned long size, unsigned long align,
276 				 unsigned long *addr, unsigned long min)
277 {
278 	unsigned long map_size, desc_size, buff_size;
279 	efi_memory_desc_t *map;
280 	efi_status_t status;
281 	unsigned long nr_pages;
282 	int i;
283 	struct efi_boot_memmap boot_map;
284 
285 	boot_map.map =		&map;
286 	boot_map.map_size =	&map_size;
287 	boot_map.desc_size =	&desc_size;
288 	boot_map.desc_ver =	NULL;
289 	boot_map.key_ptr =	NULL;
290 	boot_map.buff_size =	&buff_size;
291 
292 	status = efi_get_memory_map(sys_table_arg, &boot_map);
293 	if (status != EFI_SUCCESS)
294 		goto fail;
295 
296 	/*
297 	 * Enforce minimum alignment that EFI or Linux requires when
298 	 * requesting a specific address.  We are doing page-based (or
299 	 * larger) allocations, and both the address and size must meet
300 	 * alignment constraints.
301 	 */
302 	if (align < EFI_ALLOC_ALIGN)
303 		align = EFI_ALLOC_ALIGN;
304 
305 	size = round_up(size, EFI_ALLOC_ALIGN);
306 	nr_pages = size / EFI_PAGE_SIZE;
307 	for (i = 0; i < map_size / desc_size; i++) {
308 		efi_memory_desc_t *desc;
309 		unsigned long m = (unsigned long)map;
310 		u64 start, end;
311 
312 		desc = efi_early_memdesc_ptr(m, desc_size, i);
313 
314 		if (desc->type != EFI_CONVENTIONAL_MEMORY)
315 			continue;
316 
317 		if (efi_soft_reserve_enabled() &&
318 		    (desc->attribute & EFI_MEMORY_SP))
319 			continue;
320 
321 		if (desc->num_pages < nr_pages)
322 			continue;
323 
324 		start = desc->phys_addr;
325 		end = start + desc->num_pages * EFI_PAGE_SIZE;
326 
327 		if (start < min)
328 			start = min;
329 
330 		start = round_up(start, align);
331 		if ((start + size) > end)
332 			continue;
333 
334 		status = efi_call_early(allocate_pages,
335 					EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA,
336 					nr_pages, &start);
337 		if (status == EFI_SUCCESS) {
338 			*addr = start;
339 			break;
340 		}
341 	}
342 
343 	if (i == map_size / desc_size)
344 		status = EFI_NOT_FOUND;
345 
346 	efi_call_early(free_pool, map);
347 fail:
348 	return status;
349 }
350 
351 void efi_free(efi_system_table_t *sys_table_arg, unsigned long size,
352 	      unsigned long addr)
353 {
354 	unsigned long nr_pages;
355 
356 	if (!size)
357 		return;
358 
359 	nr_pages = round_up(size, EFI_ALLOC_ALIGN) / EFI_PAGE_SIZE;
360 	efi_call_early(free_pages, addr, nr_pages);
361 }
362 
363 static efi_status_t efi_file_size(efi_system_table_t *sys_table_arg, void *__fh,
364 				  efi_char16_t *filename_16, void **handle,
365 				  u64 *file_sz)
366 {
367 	efi_file_handle_t *h, *fh = __fh;
368 	efi_file_info_t *info;
369 	efi_status_t status;
370 	efi_guid_t info_guid = EFI_FILE_INFO_ID;
371 	unsigned long info_sz;
372 
373 	status = efi_call_proto(efi_file_handle, open, fh, &h, filename_16,
374 				EFI_FILE_MODE_READ, (u64)0);
375 	if (status != EFI_SUCCESS) {
376 		efi_printk(sys_table_arg, "Failed to open file: ");
377 		efi_char16_printk(sys_table_arg, filename_16);
378 		efi_printk(sys_table_arg, "\n");
379 		return status;
380 	}
381 
382 	*handle = h;
383 
384 	info_sz = 0;
385 	status = efi_call_proto(efi_file_handle, get_info, h, &info_guid,
386 				&info_sz, NULL);
387 	if (status != EFI_BUFFER_TOO_SMALL) {
388 		efi_printk(sys_table_arg, "Failed to get file info size\n");
389 		return status;
390 	}
391 
392 grow:
393 	status = efi_call_early(allocate_pool, EFI_LOADER_DATA,
394 				info_sz, (void **)&info);
395 	if (status != EFI_SUCCESS) {
396 		efi_printk(sys_table_arg, "Failed to alloc mem for file info\n");
397 		return status;
398 	}
399 
400 	status = efi_call_proto(efi_file_handle, get_info, h, &info_guid,
401 				&info_sz, info);
402 	if (status == EFI_BUFFER_TOO_SMALL) {
403 		efi_call_early(free_pool, info);
404 		goto grow;
405 	}
406 
407 	*file_sz = info->file_size;
408 	efi_call_early(free_pool, info);
409 
410 	if (status != EFI_SUCCESS)
411 		efi_printk(sys_table_arg, "Failed to get initrd info\n");
412 
413 	return status;
414 }
415 
416 static efi_status_t efi_file_read(void *handle, unsigned long *size, void *addr)
417 {
418 	return efi_call_proto(efi_file_handle, read, handle, size, addr);
419 }
420 
421 static efi_status_t efi_file_close(void *handle)
422 {
423 	return efi_call_proto(efi_file_handle, close, handle);
424 }
425 
426 static efi_status_t efi_open_volume(efi_system_table_t *sys_table_arg,
427 				    efi_loaded_image_t *image,
428 				    efi_file_handle_t **__fh)
429 {
430 	efi_file_io_interface_t *io;
431 	efi_file_handle_t *fh;
432 	efi_guid_t fs_proto = EFI_FILE_SYSTEM_GUID;
433 	efi_status_t status;
434 	void *handle = (void *)(unsigned long)efi_table_attr(efi_loaded_image,
435 							     device_handle,
436 							     image);
437 
438 	status = efi_call_early(handle_protocol, handle,
439 				&fs_proto, (void **)&io);
440 	if (status != EFI_SUCCESS) {
441 		efi_printk(sys_table_arg, "Failed to handle fs_proto\n");
442 		return status;
443 	}
444 
445 	status = efi_call_proto(efi_file_io_interface, open_volume, io, &fh);
446 	if (status != EFI_SUCCESS)
447 		efi_printk(sys_table_arg, "Failed to open volume\n");
448 	else
449 		*__fh = fh;
450 
451 	return status;
452 }
453 
454 /*
455  * Parse the ASCII string 'cmdline' for EFI options, denoted by the efi=
456  * option, e.g. efi=nochunk.
457  *
458  * It should be noted that efi= is parsed in two very different
459  * environments, first in the early boot environment of the EFI boot
460  * stub, and subsequently during the kernel boot.
461  */
462 efi_status_t efi_parse_options(char const *cmdline)
463 {
464 	char *str;
465 
466 	str = strstr(cmdline, "nokaslr");
467 	if (str == cmdline || (str && str > cmdline && *(str - 1) == ' '))
468 		__nokaslr = 1;
469 
470 	str = strstr(cmdline, "quiet");
471 	if (str == cmdline || (str && str > cmdline && *(str - 1) == ' '))
472 		__quiet = 1;
473 
474 	/*
475 	 * If no EFI parameters were specified on the cmdline we've got
476 	 * nothing to do.
477 	 */
478 	str = strstr(cmdline, "efi=");
479 	if (!str)
480 		return EFI_SUCCESS;
481 
482 	/* Skip ahead to first argument */
483 	str += strlen("efi=");
484 
485 	/*
486 	 * Remember, because efi= is also used by the kernel we need to
487 	 * skip over arguments we don't understand.
488 	 */
489 	while (*str && *str != ' ') {
490 		if (!strncmp(str, "nochunk", 7)) {
491 			str += strlen("nochunk");
492 			__chunk_size = -1UL;
493 		}
494 
495 		if (!strncmp(str, "novamap", 7)) {
496 			str += strlen("novamap");
497 			__novamap = 1;
498 		}
499 
500 		if (IS_ENABLED(CONFIG_EFI_SOFT_RESERVE) &&
501 		    !strncmp(str, "nosoftreserve", 7)) {
502 			str += strlen("nosoftreserve");
503 			efi_nosoftreserve = 1;
504 		}
505 
506 		/* Group words together, delimited by "," */
507 		while (*str && *str != ' ' && *str != ',')
508 			str++;
509 
510 		if (*str == ',')
511 			str++;
512 	}
513 
514 	return EFI_SUCCESS;
515 }
516 
517 /*
518  * Check the cmdline for a LILO-style file= arguments.
519  *
520  * We only support loading a file from the same filesystem as
521  * the kernel image.
522  */
523 efi_status_t handle_cmdline_files(efi_system_table_t *sys_table_arg,
524 				  efi_loaded_image_t *image,
525 				  char *cmd_line, char *option_string,
526 				  unsigned long max_addr,
527 				  unsigned long *load_addr,
528 				  unsigned long *load_size)
529 {
530 	struct file_info *files;
531 	unsigned long file_addr;
532 	u64 file_size_total;
533 	efi_file_handle_t *fh = NULL;
534 	efi_status_t status;
535 	int nr_files;
536 	char *str;
537 	int i, j, k;
538 
539 	file_addr = 0;
540 	file_size_total = 0;
541 
542 	str = cmd_line;
543 
544 	j = 0;			/* See close_handles */
545 
546 	if (!load_addr || !load_size)
547 		return EFI_INVALID_PARAMETER;
548 
549 	*load_addr = 0;
550 	*load_size = 0;
551 
552 	if (!str || !*str)
553 		return EFI_SUCCESS;
554 
555 	for (nr_files = 0; *str; nr_files++) {
556 		str = strstr(str, option_string);
557 		if (!str)
558 			break;
559 
560 		str += strlen(option_string);
561 
562 		/* Skip any leading slashes */
563 		while (*str == '/' || *str == '\\')
564 			str++;
565 
566 		while (*str && *str != ' ' && *str != '\n')
567 			str++;
568 	}
569 
570 	if (!nr_files)
571 		return EFI_SUCCESS;
572 
573 	status = efi_call_early(allocate_pool, EFI_LOADER_DATA,
574 				nr_files * sizeof(*files), (void **)&files);
575 	if (status != EFI_SUCCESS) {
576 		pr_efi_err(sys_table_arg, "Failed to alloc mem for file handle list\n");
577 		goto fail;
578 	}
579 
580 	str = cmd_line;
581 	for (i = 0; i < nr_files; i++) {
582 		struct file_info *file;
583 		efi_char16_t filename_16[256];
584 		efi_char16_t *p;
585 
586 		str = strstr(str, option_string);
587 		if (!str)
588 			break;
589 
590 		str += strlen(option_string);
591 
592 		file = &files[i];
593 		p = filename_16;
594 
595 		/* Skip any leading slashes */
596 		while (*str == '/' || *str == '\\')
597 			str++;
598 
599 		while (*str && *str != ' ' && *str != '\n') {
600 			if ((u8 *)p >= (u8 *)filename_16 + sizeof(filename_16))
601 				break;
602 
603 			if (*str == '/') {
604 				*p++ = '\\';
605 				str++;
606 			} else {
607 				*p++ = *str++;
608 			}
609 		}
610 
611 		*p = '\0';
612 
613 		/* Only open the volume once. */
614 		if (!i) {
615 			status = efi_open_volume(sys_table_arg, image, &fh);
616 			if (status != EFI_SUCCESS)
617 				goto free_files;
618 		}
619 
620 		status = efi_file_size(sys_table_arg, fh, filename_16,
621 				       (void **)&file->handle, &file->size);
622 		if (status != EFI_SUCCESS)
623 			goto close_handles;
624 
625 		file_size_total += file->size;
626 	}
627 
628 	if (file_size_total) {
629 		unsigned long addr;
630 
631 		/*
632 		 * Multiple files need to be at consecutive addresses in memory,
633 		 * so allocate enough memory for all the files.  This is used
634 		 * for loading multiple files.
635 		 */
636 		status = efi_high_alloc(sys_table_arg, file_size_total, 0x1000,
637 				    &file_addr, max_addr);
638 		if (status != EFI_SUCCESS) {
639 			pr_efi_err(sys_table_arg, "Failed to alloc highmem for files\n");
640 			goto close_handles;
641 		}
642 
643 		/* We've run out of free low memory. */
644 		if (file_addr > max_addr) {
645 			pr_efi_err(sys_table_arg, "We've run out of free low memory\n");
646 			status = EFI_INVALID_PARAMETER;
647 			goto free_file_total;
648 		}
649 
650 		addr = file_addr;
651 		for (j = 0; j < nr_files; j++) {
652 			unsigned long size;
653 
654 			size = files[j].size;
655 			while (size) {
656 				unsigned long chunksize;
657 
658 				if (IS_ENABLED(CONFIG_X86) && size > __chunk_size)
659 					chunksize = __chunk_size;
660 				else
661 					chunksize = size;
662 
663 				status = efi_file_read(files[j].handle,
664 						       &chunksize,
665 						       (void *)addr);
666 				if (status != EFI_SUCCESS) {
667 					pr_efi_err(sys_table_arg, "Failed to read file\n");
668 					goto free_file_total;
669 				}
670 				addr += chunksize;
671 				size -= chunksize;
672 			}
673 
674 			efi_file_close(files[j].handle);
675 		}
676 
677 	}
678 
679 	efi_call_early(free_pool, files);
680 
681 	*load_addr = file_addr;
682 	*load_size = file_size_total;
683 
684 	return status;
685 
686 free_file_total:
687 	efi_free(sys_table_arg, file_size_total, file_addr);
688 
689 close_handles:
690 	for (k = j; k < i; k++)
691 		efi_file_close(files[k].handle);
692 free_files:
693 	efi_call_early(free_pool, files);
694 fail:
695 	*load_addr = 0;
696 	*load_size = 0;
697 
698 	return status;
699 }
700 /*
701  * Relocate a kernel image, either compressed or uncompressed.
702  * In the ARM64 case, all kernel images are currently
703  * uncompressed, and as such when we relocate it we need to
704  * allocate additional space for the BSS segment. Any low
705  * memory that this function should avoid needs to be
706  * unavailable in the EFI memory map, as if the preferred
707  * address is not available the lowest available address will
708  * be used.
709  */
710 efi_status_t efi_relocate_kernel(efi_system_table_t *sys_table_arg,
711 				 unsigned long *image_addr,
712 				 unsigned long image_size,
713 				 unsigned long alloc_size,
714 				 unsigned long preferred_addr,
715 				 unsigned long alignment,
716 				 unsigned long min_addr)
717 {
718 	unsigned long cur_image_addr;
719 	unsigned long new_addr = 0;
720 	efi_status_t status;
721 	unsigned long nr_pages;
722 	efi_physical_addr_t efi_addr = preferred_addr;
723 
724 	if (!image_addr || !image_size || !alloc_size)
725 		return EFI_INVALID_PARAMETER;
726 	if (alloc_size < image_size)
727 		return EFI_INVALID_PARAMETER;
728 
729 	cur_image_addr = *image_addr;
730 
731 	/*
732 	 * The EFI firmware loader could have placed the kernel image
733 	 * anywhere in memory, but the kernel has restrictions on the
734 	 * max physical address it can run at.  Some architectures
735 	 * also have a prefered address, so first try to relocate
736 	 * to the preferred address.  If that fails, allocate as low
737 	 * as possible while respecting the required alignment.
738 	 */
739 	nr_pages = round_up(alloc_size, EFI_ALLOC_ALIGN) / EFI_PAGE_SIZE;
740 	status = efi_call_early(allocate_pages,
741 				EFI_ALLOCATE_ADDRESS, EFI_LOADER_DATA,
742 				nr_pages, &efi_addr);
743 	new_addr = efi_addr;
744 	/*
745 	 * If preferred address allocation failed allocate as low as
746 	 * possible.
747 	 */
748 	if (status != EFI_SUCCESS) {
749 		status = efi_low_alloc_above(sys_table_arg, alloc_size,
750 					     alignment, &new_addr, min_addr);
751 	}
752 	if (status != EFI_SUCCESS) {
753 		pr_efi_err(sys_table_arg, "Failed to allocate usable memory for kernel.\n");
754 		return status;
755 	}
756 
757 	/*
758 	 * We know source/dest won't overlap since both memory ranges
759 	 * have been allocated by UEFI, so we can safely use memcpy.
760 	 */
761 	memcpy((void *)new_addr, (void *)cur_image_addr, image_size);
762 
763 	/* Return the new address of the relocated image. */
764 	*image_addr = new_addr;
765 
766 	return status;
767 }
768 
769 /*
770  * Get the number of UTF-8 bytes corresponding to an UTF-16 character.
771  * This overestimates for surrogates, but that is okay.
772  */
773 static int efi_utf8_bytes(u16 c)
774 {
775 	return 1 + (c >= 0x80) + (c >= 0x800);
776 }
777 
778 /*
779  * Convert an UTF-16 string, not necessarily null terminated, to UTF-8.
780  */
781 static u8 *efi_utf16_to_utf8(u8 *dst, const u16 *src, int n)
782 {
783 	unsigned int c;
784 
785 	while (n--) {
786 		c = *src++;
787 		if (n && c >= 0xd800 && c <= 0xdbff &&
788 		    *src >= 0xdc00 && *src <= 0xdfff) {
789 			c = 0x10000 + ((c & 0x3ff) << 10) + (*src & 0x3ff);
790 			src++;
791 			n--;
792 		}
793 		if (c >= 0xd800 && c <= 0xdfff)
794 			c = 0xfffd; /* Unmatched surrogate */
795 		if (c < 0x80) {
796 			*dst++ = c;
797 			continue;
798 		}
799 		if (c < 0x800) {
800 			*dst++ = 0xc0 + (c >> 6);
801 			goto t1;
802 		}
803 		if (c < 0x10000) {
804 			*dst++ = 0xe0 + (c >> 12);
805 			goto t2;
806 		}
807 		*dst++ = 0xf0 + (c >> 18);
808 		*dst++ = 0x80 + ((c >> 12) & 0x3f);
809 	t2:
810 		*dst++ = 0x80 + ((c >> 6) & 0x3f);
811 	t1:
812 		*dst++ = 0x80 + (c & 0x3f);
813 	}
814 
815 	return dst;
816 }
817 
818 #ifndef MAX_CMDLINE_ADDRESS
819 #define MAX_CMDLINE_ADDRESS	ULONG_MAX
820 #endif
821 
822 /*
823  * Convert the unicode UEFI command line to ASCII to pass to kernel.
824  * Size of memory allocated return in *cmd_line_len.
825  * Returns NULL on error.
826  */
827 char *efi_convert_cmdline(efi_system_table_t *sys_table_arg,
828 			  efi_loaded_image_t *image,
829 			  int *cmd_line_len)
830 {
831 	const u16 *s2;
832 	u8 *s1 = NULL;
833 	unsigned long cmdline_addr = 0;
834 	int load_options_chars = image->load_options_size / 2; /* UTF-16 */
835 	const u16 *options = image->load_options;
836 	int options_bytes = 0;  /* UTF-8 bytes */
837 	int options_chars = 0;  /* UTF-16 chars */
838 	efi_status_t status;
839 	u16 zero = 0;
840 
841 	if (options) {
842 		s2 = options;
843 		while (*s2 && *s2 != '\n'
844 		       && options_chars < load_options_chars) {
845 			options_bytes += efi_utf8_bytes(*s2++);
846 			options_chars++;
847 		}
848 	}
849 
850 	if (!options_chars) {
851 		/* No command line options, so return empty string*/
852 		options = &zero;
853 	}
854 
855 	options_bytes++;	/* NUL termination */
856 
857 	status = efi_high_alloc(sys_table_arg, options_bytes, 0,
858 				&cmdline_addr, MAX_CMDLINE_ADDRESS);
859 	if (status != EFI_SUCCESS)
860 		return NULL;
861 
862 	s1 = (u8 *)cmdline_addr;
863 	s2 = (const u16 *)options;
864 
865 	s1 = efi_utf16_to_utf8(s1, s2, options_chars);
866 	*s1 = '\0';
867 
868 	*cmd_line_len = options_bytes;
869 	return (char *)cmdline_addr;
870 }
871 
872 /*
873  * Handle calling ExitBootServices according to the requirements set out by the
874  * spec.  Obtains the current memory map, and returns that info after calling
875  * ExitBootServices.  The client must specify a function to perform any
876  * processing of the memory map data prior to ExitBootServices.  A client
877  * specific structure may be passed to the function via priv.  The client
878  * function may be called multiple times.
879  */
880 efi_status_t efi_exit_boot_services(efi_system_table_t *sys_table_arg,
881 				    void *handle,
882 				    struct efi_boot_memmap *map,
883 				    void *priv,
884 				    efi_exit_boot_map_processing priv_func)
885 {
886 	efi_status_t status;
887 
888 	status = efi_get_memory_map(sys_table_arg, map);
889 
890 	if (status != EFI_SUCCESS)
891 		goto fail;
892 
893 	status = priv_func(sys_table_arg, map, priv);
894 	if (status != EFI_SUCCESS)
895 		goto free_map;
896 
897 	status = efi_call_early(exit_boot_services, handle, *map->key_ptr);
898 
899 	if (status == EFI_INVALID_PARAMETER) {
900 		/*
901 		 * The memory map changed between efi_get_memory_map() and
902 		 * exit_boot_services().  Per the UEFI Spec v2.6, Section 6.4:
903 		 * EFI_BOOT_SERVICES.ExitBootServices we need to get the
904 		 * updated map, and try again.  The spec implies one retry
905 		 * should be sufficent, which is confirmed against the EDK2
906 		 * implementation.  Per the spec, we can only invoke
907 		 * get_memory_map() and exit_boot_services() - we cannot alloc
908 		 * so efi_get_memory_map() cannot be used, and we must reuse
909 		 * the buffer.  For all practical purposes, the headroom in the
910 		 * buffer should account for any changes in the map so the call
911 		 * to get_memory_map() is expected to succeed here.
912 		 */
913 		*map->map_size = *map->buff_size;
914 		status = efi_call_early(get_memory_map,
915 					map->map_size,
916 					*map->map,
917 					map->key_ptr,
918 					map->desc_size,
919 					map->desc_ver);
920 
921 		/* exit_boot_services() was called, thus cannot free */
922 		if (status != EFI_SUCCESS)
923 			goto fail;
924 
925 		status = priv_func(sys_table_arg, map, priv);
926 		/* exit_boot_services() was called, thus cannot free */
927 		if (status != EFI_SUCCESS)
928 			goto fail;
929 
930 		status = efi_call_early(exit_boot_services, handle, *map->key_ptr);
931 	}
932 
933 	/* exit_boot_services() was called, thus cannot free */
934 	if (status != EFI_SUCCESS)
935 		goto fail;
936 
937 	return EFI_SUCCESS;
938 
939 free_map:
940 	efi_call_early(free_pool, *map->map);
941 fail:
942 	return status;
943 }
944 
945 #define GET_EFI_CONFIG_TABLE(bits)					\
946 static void *get_efi_config_table##bits(efi_system_table_t *_sys_table,	\
947 					efi_guid_t guid)		\
948 {									\
949 	efi_system_table_##bits##_t *sys_table;				\
950 	efi_config_table_##bits##_t *tables;				\
951 	int i;								\
952 									\
953 	sys_table = (typeof(sys_table))_sys_table;			\
954 	tables = (typeof(tables))(unsigned long)sys_table->tables;	\
955 									\
956 	for (i = 0; i < sys_table->nr_tables; i++) {			\
957 		if (efi_guidcmp(tables[i].guid, guid) != 0)		\
958 			continue;					\
959 									\
960 		return (void *)(unsigned long)tables[i].table;		\
961 	}								\
962 									\
963 	return NULL;							\
964 }
965 GET_EFI_CONFIG_TABLE(32)
966 GET_EFI_CONFIG_TABLE(64)
967 
968 void *get_efi_config_table(efi_system_table_t *sys_table, efi_guid_t guid)
969 {
970 	if (efi_is_64bit())
971 		return get_efi_config_table64(sys_table, guid);
972 	else
973 		return get_efi_config_table32(sys_table, guid);
974 }
975