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