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