efi_loader: fix 'efidebug boot dump'
[oweals/u-boot.git] / cmd / efidebug.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  UEFI Shell-like command
4  *
5  *  Copyright (c) 2018 AKASHI Takahiro, Linaro Limited
6  */
7
8 #include <charset.h>
9 #include <common.h>
10 #include <command.h>
11 #include <efi_loader.h>
12 #include <exports.h>
13 #include <hexdump.h>
14 #include <malloc.h>
15 #include <mapmem.h>
16 #include <search.h>
17 #include <linux/ctype.h>
18
19 #define BS systab.boottime
20 #define RT systab.runtime
21
22 /**
23  * efi_get_device_handle_info() - get information of UEFI device
24  *
25  * @handle:             Handle of UEFI device
26  * @dev_path_text:      Pointer to text of device path
27  * Return:              0 on success, -1 on failure
28  *
29  * Currently return a formatted text of device path.
30  */
31 static int efi_get_device_handle_info(efi_handle_t handle, u16 **dev_path_text)
32 {
33         struct efi_device_path *dp;
34         efi_status_t ret;
35
36         ret = EFI_CALL(BS->open_protocol(handle, &efi_guid_device_path,
37                                          (void **)&dp, NULL /* FIXME */, NULL,
38                                          EFI_OPEN_PROTOCOL_GET_PROTOCOL));
39         if (ret == EFI_SUCCESS) {
40                 *dev_path_text = efi_dp_str(dp);
41                 return 0;
42         } else {
43                 return -1;
44         }
45 }
46
47 #define EFI_HANDLE_WIDTH ((int)sizeof(efi_handle_t) * 2)
48
49 static const char spc[] = "                ";
50 static const char sep[] = "================";
51
52 /**
53  * do_efi_show_devices() - show UEFI devices
54  *
55  * @cmdtp:      Command table
56  * @flag:       Command flag
57  * @argc:       Number of arguments
58  * @argv:       Argument array
59  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
60  *
61  * Implement efidebug "devices" sub-command.
62  * Show all UEFI devices and their information.
63  */
64 static int do_efi_show_devices(cmd_tbl_t *cmdtp, int flag,
65                                int argc, char * const argv[])
66 {
67         efi_handle_t *handles;
68         efi_uintn_t num, i;
69         u16 *dev_path_text;
70         efi_status_t ret;
71
72         ret = EFI_CALL(BS->locate_handle_buffer(ALL_HANDLES, NULL, NULL,
73                                                 &num, &handles));
74         if (ret != EFI_SUCCESS)
75                 return CMD_RET_FAILURE;
76
77         if (!num)
78                 return CMD_RET_SUCCESS;
79
80         printf("Device%.*s Device Path\n", EFI_HANDLE_WIDTH - 6, spc);
81         printf("%.*s ====================\n", EFI_HANDLE_WIDTH, sep);
82         for (i = 0; i < num; i++) {
83                 if (!efi_get_device_handle_info(handles[i], &dev_path_text)) {
84                         printf("%p %ls\n", handles[i], dev_path_text);
85                         efi_free_pool(dev_path_text);
86                 }
87         }
88
89         EFI_CALL(BS->free_pool(handles));
90
91         return CMD_RET_SUCCESS;
92 }
93
94 /**
95  * efi_get_driver_handle_info() - get information of UEFI driver
96  *
97  * @handle:             Handle of UEFI device
98  * @driver_name:        Driver name
99  * @image_path:         Pointer to text of device path
100  * Return:              0 on success, -1 on failure
101  *
102  * Currently return no useful information as all UEFI drivers are
103  * built-in..
104  */
105 static int efi_get_driver_handle_info(efi_handle_t handle, u16 **driver_name,
106                                       u16 **image_path)
107 {
108         struct efi_handler *handler;
109         struct efi_loaded_image *image;
110         efi_status_t ret;
111
112         /*
113          * driver name
114          * TODO: support EFI_COMPONENT_NAME2_PROTOCOL
115          */
116         *driver_name = NULL;
117
118         /* image name */
119         ret = efi_search_protocol(handle, &efi_guid_loaded_image, &handler);
120         if (ret != EFI_SUCCESS) {
121                 *image_path = NULL;
122                 return 0;
123         }
124
125         image = handler->protocol_interface;
126         *image_path = efi_dp_str(image->file_path);
127
128         return 0;
129 }
130
131 /**
132  * do_efi_show_drivers() - show UEFI drivers
133  *
134  * @cmdtp:      Command table
135  * @flag:       Command flag
136  * @argc:       Number of arguments
137  * @argv:       Argument array
138  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
139  *
140  * Implement efidebug "drivers" sub-command.
141  * Show all UEFI drivers and their information.
142  */
143 static int do_efi_show_drivers(cmd_tbl_t *cmdtp, int flag,
144                                int argc, char * const argv[])
145 {
146         efi_handle_t *handles;
147         efi_uintn_t num, i;
148         u16 *driver_name, *image_path_text;
149         efi_status_t ret;
150
151         ret = EFI_CALL(BS->locate_handle_buffer(
152                                 BY_PROTOCOL, &efi_guid_driver_binding_protocol,
153                                 NULL, &num, &handles));
154         if (ret != EFI_SUCCESS)
155                 return CMD_RET_FAILURE;
156
157         if (!num)
158                 return CMD_RET_SUCCESS;
159
160         printf("Driver%.*s Name                 Image Path\n",
161                EFI_HANDLE_WIDTH - 6, spc);
162         printf("%.*s ==================== ====================\n",
163                EFI_HANDLE_WIDTH, sep);
164         for (i = 0; i < num; i++) {
165                 if (!efi_get_driver_handle_info(handles[i], &driver_name,
166                                                 &image_path_text)) {
167                         if (image_path_text)
168                                 printf("%p %-20ls %ls\n", handles[i],
169                                        driver_name, image_path_text);
170                         else
171                                 printf("%p %-20ls <built-in>\n",
172                                        handles[i], driver_name);
173                         EFI_CALL(BS->free_pool(driver_name));
174                         EFI_CALL(BS->free_pool(image_path_text));
175                 }
176         }
177
178         EFI_CALL(BS->free_pool(handles));
179
180         return CMD_RET_SUCCESS;
181 }
182
183 static const struct {
184         const char *text;
185         const efi_guid_t guid;
186 } guid_list[] = {
187         {
188                 "Device Path",
189                 EFI_DEVICE_PATH_PROTOCOL_GUID,
190         },
191         {
192                 "Device Path To Text",
193                 EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID,
194         },
195         {
196                 "Device Path Utilities",
197                 EFI_DEVICE_PATH_UTILITIES_PROTOCOL_GUID,
198         },
199         {
200                 "Unicode Collation 2",
201                 EFI_UNICODE_COLLATION_PROTOCOL2_GUID,
202         },
203         {
204                 "Driver Binding",
205                 EFI_DRIVER_BINDING_PROTOCOL_GUID,
206         },
207         {
208                 "Simple Text Input",
209                 EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID,
210         },
211         {
212                 "Simple Text Input Ex",
213                 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID,
214         },
215         {
216                 "Simple Text Output",
217                 EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID,
218         },
219         {
220                 "Block IO",
221                 EFI_BLOCK_IO_PROTOCOL_GUID,
222         },
223         {
224                 "Simple File System",
225                 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID,
226         },
227         {
228                 "Loaded Image",
229                 EFI_LOADED_IMAGE_PROTOCOL_GUID,
230         },
231         {
232                 "Graphics Output",
233                 EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID,
234         },
235         {
236                 "HII String",
237                 EFI_HII_STRING_PROTOCOL_GUID,
238         },
239         {
240                 "HII Database",
241                 EFI_HII_DATABASE_PROTOCOL_GUID,
242         },
243         {
244                 "HII Config Routing",
245                 EFI_HII_CONFIG_ROUTING_PROTOCOL_GUID,
246         },
247         {
248                 "Load File2",
249                 EFI_LOAD_FILE2_PROTOCOL_GUID,
250         },
251         {
252                 "Simple Network",
253                 EFI_SIMPLE_NETWORK_PROTOCOL_GUID,
254         },
255         {
256                 "PXE Base Code",
257                 EFI_PXE_BASE_CODE_PROTOCOL_GUID,
258         },
259         /* Configuration table GUIDs */
260         {
261                 "ACPI table",
262                 EFI_ACPI_TABLE_GUID,
263         },
264         {
265                 "device tree",
266                 EFI_FDT_GUID,
267         },
268         {
269                 "SMBIOS table",
270                 SMBIOS_TABLE_GUID,
271         },
272         {
273                 "Runtime properties",
274                 EFI_RT_PROPERTIES_TABLE_GUID,
275         },
276 };
277
278 /**
279  * get_guid_text - get string of GUID
280  *
281  * Return description of GUID.
282  *
283  * @guid:       GUID
284  * Return:      description of GUID or NULL
285  */
286 static const char *get_guid_text(const void *guid)
287 {
288         int i;
289
290         for (i = 0; i < ARRAY_SIZE(guid_list); i++) {
291                 /*
292                  * As guidcmp uses memcmp() we can safely accept unaligned
293                  * GUIDs.
294                  */
295                 if (!guidcmp(&guid_list[i].guid, guid))
296                         return guid_list[i].text;
297         }
298
299         return NULL;
300 }
301
302 /**
303  * do_efi_show_handles() - show UEFI handles
304  *
305  * @cmdtp:      Command table
306  * @flag:       Command flag
307  * @argc:       Number of arguments
308  * @argv:       Argument array
309  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
310  *
311  * Implement efidebug "dh" sub-command.
312  * Show all UEFI handles and their information, currently all protocols
313  * added to handle.
314  */
315 static int do_efi_show_handles(cmd_tbl_t *cmdtp, int flag,
316                                int argc, char * const argv[])
317 {
318         efi_handle_t *handles;
319         efi_guid_t **guid;
320         efi_uintn_t num, count, i, j;
321         const char *guid_text;
322         efi_status_t ret;
323
324         ret = EFI_CALL(BS->locate_handle_buffer(ALL_HANDLES, NULL, NULL,
325                                                 &num, &handles));
326         if (ret != EFI_SUCCESS)
327                 return CMD_RET_FAILURE;
328
329         if (!num)
330                 return CMD_RET_SUCCESS;
331
332         printf("Handle%.*s Protocols\n", EFI_HANDLE_WIDTH - 6, spc);
333         printf("%.*s ====================\n", EFI_HANDLE_WIDTH, sep);
334         for (i = 0; i < num; i++) {
335                 printf("%p", handles[i]);
336                 ret = EFI_CALL(BS->protocols_per_handle(handles[i], &guid,
337                                                         &count));
338                 if (ret || !count) {
339                         putc('\n');
340                         continue;
341                 }
342
343                 for (j = 0; j < count; j++) {
344                         if (j)
345                                 printf(", ");
346                         else
347                                 putc(' ');
348
349                         guid_text = get_guid_text(guid[j]);
350                         if (guid_text)
351                                 puts(guid_text);
352                         else
353                                 printf("%pUl", guid[j]);
354                 }
355                 putc('\n');
356         }
357
358         EFI_CALL(BS->free_pool(handles));
359
360         return CMD_RET_SUCCESS;
361 }
362
363 /**
364  * do_efi_show_images() - show UEFI images
365  *
366  * @cmdtp:      Command table
367  * @flag:       Command flag
368  * @argc:       Number of arguments
369  * @argv:       Argument array
370  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
371  *
372  * Implement efidebug "images" sub-command.
373  * Show all UEFI loaded images and their information.
374  */
375 static int do_efi_show_images(cmd_tbl_t *cmdtp, int flag,
376                               int argc, char * const argv[])
377 {
378         efi_print_image_infos(NULL);
379
380         return CMD_RET_SUCCESS;
381 }
382
383 static const char * const efi_mem_type_string[] = {
384         [EFI_RESERVED_MEMORY_TYPE] = "RESERVED",
385         [EFI_LOADER_CODE] = "LOADER CODE",
386         [EFI_LOADER_DATA] = "LOADER DATA",
387         [EFI_BOOT_SERVICES_CODE] = "BOOT CODE",
388         [EFI_BOOT_SERVICES_DATA] = "BOOT DATA",
389         [EFI_RUNTIME_SERVICES_CODE] = "RUNTIME CODE",
390         [EFI_RUNTIME_SERVICES_DATA] = "RUNTIME DATA",
391         [EFI_CONVENTIONAL_MEMORY] = "CONVENTIONAL",
392         [EFI_UNUSABLE_MEMORY] = "UNUSABLE MEM",
393         [EFI_ACPI_RECLAIM_MEMORY] = "ACPI RECLAIM MEM",
394         [EFI_ACPI_MEMORY_NVS] = "ACPI NVS",
395         [EFI_MMAP_IO] = "IO",
396         [EFI_MMAP_IO_PORT] = "IO PORT",
397         [EFI_PAL_CODE] = "PAL",
398 };
399
400 static const struct efi_mem_attrs {
401         const u64 bit;
402         const char *text;
403 } efi_mem_attrs[] = {
404         {EFI_MEMORY_UC, "UC"},
405         {EFI_MEMORY_UC, "UC"},
406         {EFI_MEMORY_WC, "WC"},
407         {EFI_MEMORY_WT, "WT"},
408         {EFI_MEMORY_WB, "WB"},
409         {EFI_MEMORY_UCE, "UCE"},
410         {EFI_MEMORY_WP, "WP"},
411         {EFI_MEMORY_RP, "RP"},
412         {EFI_MEMORY_XP, "WP"},
413         {EFI_MEMORY_NV, "NV"},
414         {EFI_MEMORY_MORE_RELIABLE, "REL"},
415         {EFI_MEMORY_RO, "RO"},
416         {EFI_MEMORY_RUNTIME, "RT"},
417 };
418
419 /**
420  * print_memory_attributes() - print memory map attributes
421  *
422  * @attributes: Attribute value
423  *
424  * Print memory map attributes
425  */
426 static void print_memory_attributes(u64 attributes)
427 {
428         int sep, i;
429
430         for (sep = 0, i = 0; i < ARRAY_SIZE(efi_mem_attrs); i++)
431                 if (attributes & efi_mem_attrs[i].bit) {
432                         if (sep) {
433                                 putc('|');
434                         } else {
435                                 putc(' ');
436                                 sep = 1;
437                         }
438                         puts(efi_mem_attrs[i].text);
439                 }
440 }
441
442 #define EFI_PHYS_ADDR_WIDTH (int)(sizeof(efi_physical_addr_t) * 2)
443
444 /**
445  * do_efi_show_memmap() - show UEFI memory map
446  *
447  * @cmdtp:      Command table
448  * @flag:       Command flag
449  * @argc:       Number of arguments
450  * @argv:       Argument array
451  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
452  *
453  * Implement efidebug "memmap" sub-command.
454  * Show UEFI memory map.
455  */
456 static int do_efi_show_memmap(cmd_tbl_t *cmdtp, int flag,
457                               int argc, char * const argv[])
458 {
459         struct efi_mem_desc *memmap = NULL, *map;
460         efi_uintn_t map_size = 0;
461         const char *type;
462         int i;
463         efi_status_t ret;
464
465         ret = EFI_CALL(BS->get_memory_map(&map_size, memmap, NULL, NULL, NULL));
466         if (ret == EFI_BUFFER_TOO_SMALL) {
467                 map_size += sizeof(struct efi_mem_desc); /* for my own */
468                 ret = EFI_CALL(BS->allocate_pool(EFI_LOADER_DATA,
469                                                  map_size, (void *)&memmap));
470                 if (ret != EFI_SUCCESS)
471                         return CMD_RET_FAILURE;
472                 ret = EFI_CALL(BS->get_memory_map(&map_size, memmap,
473                                                   NULL, NULL, NULL));
474         }
475         if (ret != EFI_SUCCESS) {
476                 EFI_CALL(BS->free_pool(memmap));
477                 return CMD_RET_FAILURE;
478         }
479
480         printf("Type             Start%.*s End%.*s Attributes\n",
481                EFI_PHYS_ADDR_WIDTH - 5, spc, EFI_PHYS_ADDR_WIDTH - 3, spc);
482         printf("================ %.*s %.*s ==========\n",
483                EFI_PHYS_ADDR_WIDTH, sep, EFI_PHYS_ADDR_WIDTH, sep);
484         for (i = 0, map = memmap; i < map_size / sizeof(*map); map++, i++) {
485                 if (map->type < EFI_MAX_MEMORY_TYPE)
486                         type = efi_mem_type_string[map->type];
487                 else
488                         type = "(unknown)";
489
490                 printf("%-16s %.*llx-%.*llx", type,
491                        EFI_PHYS_ADDR_WIDTH,
492                        (u64)map_to_sysmem((void *)(uintptr_t)
493                                           map->physical_start),
494                        EFI_PHYS_ADDR_WIDTH,
495                        (u64)map_to_sysmem((void *)(uintptr_t)
496                                           (map->physical_start +
497                                            map->num_pages * EFI_PAGE_SIZE)));
498
499                 print_memory_attributes(map->attribute);
500                 putc('\n');
501         }
502
503         EFI_CALL(BS->free_pool(memmap));
504
505         return CMD_RET_SUCCESS;
506 }
507
508 /**
509  * do_efi_show_tables() - show UEFI configuration tables
510  *
511  * @cmdtp:      Command table
512  * @flag:       Command flag
513  * @argc:       Number of arguments
514  * @argv:       Argument array
515  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
516  *
517  * Implement efidebug "tables" sub-command.
518  * Show UEFI configuration tables.
519  */
520 static int do_efi_show_tables(cmd_tbl_t *cmdtp, int flag,
521                               int argc, char * const argv[])
522 {
523         efi_uintn_t i;
524         const char *guid_str;
525
526         for (i = 0; i < systab.nr_tables; ++i) {
527                 guid_str = get_guid_text(&systab.tables[i].guid);
528                 if (!guid_str)
529                         guid_str = "";
530                 printf("%pUl %s\n", &systab.tables[i].guid, guid_str);
531         }
532
533         return CMD_RET_SUCCESS;
534 }
535
536 /**
537  * do_efi_boot_add() - set UEFI load option
538  *
539  * @cmdtp:      Command table
540  * @flag:       Command flag
541  * @argc:       Number of arguments
542  * @argv:       Argument array
543  * Return:      CMD_RET_SUCCESS on success,
544  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
545  *
546  * Implement efidebug "boot add" sub-command. Create or change UEFI load option.
547  *
548  *     efidebug boot add <id> <label> <interface> <devnum>[:<part>] <file> <options>
549  */
550 static int do_efi_boot_add(cmd_tbl_t *cmdtp, int flag,
551                            int argc, char * const argv[])
552 {
553         int id;
554         char *endp;
555         char var_name[9];
556         u16 var_name16[9], *p;
557         efi_guid_t guid;
558         size_t label_len, label_len16;
559         u16 *label;
560         struct efi_device_path *device_path = NULL, *file_path = NULL;
561         struct efi_load_option lo;
562         void *data = NULL;
563         efi_uintn_t size;
564         efi_status_t ret;
565         int r = CMD_RET_SUCCESS;
566
567         if (argc < 6 || argc > 7)
568                 return CMD_RET_USAGE;
569
570         id = (int)simple_strtoul(argv[1], &endp, 16);
571         if (*endp != '\0' || id > 0xffff)
572                 return CMD_RET_USAGE;
573
574         sprintf(var_name, "Boot%04X", id);
575         p = var_name16;
576         utf8_utf16_strncpy(&p, var_name, 9);
577
578         guid = efi_global_variable_guid;
579
580         /* attributes */
581         lo.attributes = LOAD_OPTION_ACTIVE; /* always ACTIVE */
582
583         /* label */
584         label_len = strlen(argv[2]);
585         label_len16 = utf8_utf16_strnlen(argv[2], label_len);
586         label = malloc((label_len16 + 1) * sizeof(u16));
587         if (!label)
588                 return CMD_RET_FAILURE;
589         lo.label = label; /* label will be changed below */
590         utf8_utf16_strncpy(&label, argv[2], label_len);
591
592         /* file path */
593         ret = efi_dp_from_name(argv[3], argv[4], argv[5], &device_path,
594                                &file_path);
595         if (ret != EFI_SUCCESS) {
596                 printf("Cannot create device path for \"%s %s\"\n",
597                        argv[3], argv[4]);
598                 r = CMD_RET_FAILURE;
599                 goto out;
600         }
601         lo.file_path = file_path;
602         lo.file_path_length = efi_dp_size(file_path)
603                                 + sizeof(struct efi_device_path); /* for END */
604
605         /* optional data */
606         if (argc < 6)
607                 lo.optional_data = NULL;
608         else
609                 lo.optional_data = (const u8 *)argv[6];
610
611         size = efi_serialize_load_option(&lo, (u8 **)&data);
612         if (!size) {
613                 r = CMD_RET_FAILURE;
614                 goto out;
615         }
616
617         ret = EFI_CALL(RT->set_variable(var_name16, &guid,
618                                         EFI_VARIABLE_NON_VOLATILE |
619                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
620                                         EFI_VARIABLE_RUNTIME_ACCESS,
621                                         size, data));
622         if (ret != EFI_SUCCESS) {
623                 printf("Cannot set %ls\n", var_name16);
624                 r = CMD_RET_FAILURE;
625         }
626 out:
627         free(data);
628         efi_free_pool(device_path);
629         efi_free_pool(file_path);
630         free(lo.label);
631
632         return r;
633 }
634
635 /**
636  * do_efi_boot_rm() - delete UEFI load options
637  *
638  * @cmdtp:      Command table
639  * @flag:       Command flag
640  * @argc:       Number of arguments
641  * @argv:       Argument array
642  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
643  *
644  * Implement efidebug "boot rm" sub-command.
645  * Delete UEFI load options.
646  *
647  *     efidebug boot rm <id> ...
648  */
649 static int do_efi_boot_rm(cmd_tbl_t *cmdtp, int flag,
650                           int argc, char * const argv[])
651 {
652         efi_guid_t guid;
653         int id, i;
654         char *endp;
655         char var_name[9];
656         u16 var_name16[9], *p;
657         efi_status_t ret;
658
659         if (argc == 1)
660                 return CMD_RET_USAGE;
661
662         guid = efi_global_variable_guid;
663         for (i = 1; i < argc; i++, argv++) {
664                 id = (int)simple_strtoul(argv[1], &endp, 16);
665                 if (*endp != '\0' || id > 0xffff)
666                         return CMD_RET_FAILURE;
667
668                 sprintf(var_name, "Boot%04X", id);
669                 p = var_name16;
670                 utf8_utf16_strncpy(&p, var_name, 9);
671
672                 ret = EFI_CALL(RT->set_variable(var_name16, &guid, 0, 0, NULL));
673                 if (ret) {
674                         printf("Cannot remove %ls\n", var_name16);
675                         return CMD_RET_FAILURE;
676                 }
677         }
678
679         return CMD_RET_SUCCESS;
680 }
681
682 /**
683  * show_efi_boot_opt_data() - dump UEFI load option
684  *
685  * @varname16:  variable name
686  * @data:       value of UEFI load option variable
687  * @size:       size of the boot option
688  *
689  * Decode the value of UEFI load option variable and print information.
690  */
691 static void show_efi_boot_opt_data(u16 *varname16, void *data, size_t size)
692 {
693         struct efi_load_option lo;
694         char *label, *p;
695         size_t label_len16, label_len;
696         u16 *dp_str;
697
698         efi_deserialize_load_option(&lo, data);
699
700         label_len16 = u16_strlen(lo.label);
701         label_len = utf16_utf8_strnlen(lo.label, label_len16);
702         label = malloc(label_len + 1);
703         if (!label)
704                 return;
705         p = label;
706         utf16_utf8_strncpy(&p, lo.label, label_len16);
707
708         printf("%ls:\nattributes: %c%c%c (0x%08x)\n",
709                varname16,
710                /* ACTIVE */
711                lo.attributes & LOAD_OPTION_ACTIVE ? 'A' : '-',
712                /* FORCE RECONNECT */
713                lo.attributes & LOAD_OPTION_FORCE_RECONNECT ? 'R' : '-',
714                /* HIDDEN */
715                lo.attributes & LOAD_OPTION_HIDDEN ? 'H' : '-',
716                lo.attributes);
717         printf("  label: %s\n", label);
718
719         dp_str = efi_dp_str(lo.file_path);
720         printf("  file_path: %ls\n", dp_str);
721         efi_free_pool(dp_str);
722
723         printf("  data:\n");
724         print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
725                        lo.optional_data, size + (u8 *)data -
726                        (u8 *)lo.optional_data, true);
727         free(label);
728 }
729
730 /**
731  * show_efi_boot_opt() - dump UEFI load option
732  *
733  * @varname16:  variable name
734  *
735  * Dump information defined by UEFI load option.
736  */
737 static void show_efi_boot_opt(u16 *varname16)
738 {
739         void *data;
740         efi_uintn_t size;
741         efi_status_t ret;
742
743         size = 0;
744         ret = EFI_CALL(efi_get_variable(varname16, &efi_global_variable_guid,
745                                         NULL, &size, NULL));
746         if (ret == EFI_BUFFER_TOO_SMALL) {
747                 data = malloc(size);
748                 if (!data) {
749                         printf("ERROR: Out of memory\n");
750                         return;
751                 }
752                 ret = EFI_CALL(efi_get_variable(varname16,
753                                                 &efi_global_variable_guid,
754                                                 NULL, &size, data));
755                 if (ret == EFI_SUCCESS)
756                         show_efi_boot_opt_data(varname16, data, size);
757                 free(data);
758         }
759 }
760
761 static int u16_tohex(u16 c)
762 {
763         if (c >= '0' && c <= '9')
764                 return c - '0';
765         if (c >= 'A' && c <= 'F')
766                 return c - 'A' + 10;
767
768         /* not hexadecimal */
769         return -1;
770 }
771
772 /**
773  * show_efi_boot_dump() - dump all UEFI load options
774  *
775  * @cmdtp:      Command table
776  * @flag:       Command flag
777  * @argc:       Number of arguments
778  * @argv:       Argument array
779  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
780  *
781  * Implement efidebug "boot dump" sub-command.
782  * Dump information of all UEFI load options defined.
783  *
784  *     efidebug boot dump
785  */
786 static int do_efi_boot_dump(cmd_tbl_t *cmdtp, int flag,
787                             int argc, char * const argv[])
788 {
789         u16 *var_name16, *p;
790         efi_uintn_t buf_size, size;
791         efi_guid_t guid;
792         int id, i, digit;
793         efi_status_t ret;
794
795         if (argc > 1)
796                 return CMD_RET_USAGE;
797
798         buf_size = 128;
799         var_name16 = malloc(buf_size);
800         if (!var_name16)
801                 return CMD_RET_FAILURE;
802
803         var_name16[0] = 0;
804         for (;;) {
805                 size = buf_size;
806                 ret = EFI_CALL(efi_get_next_variable_name(&size, var_name16,
807                                                           &guid));
808                 if (ret == EFI_NOT_FOUND)
809                         break;
810                 if (ret == EFI_BUFFER_TOO_SMALL) {
811                         buf_size = size;
812                         p = realloc(var_name16, buf_size);
813                         if (!p) {
814                                 free(var_name16);
815                                 return CMD_RET_FAILURE;
816                         }
817                         var_name16 = p;
818                         ret = EFI_CALL(efi_get_next_variable_name(&size,
819                                                                   var_name16,
820                                                                   &guid));
821                 }
822                 if (ret != EFI_SUCCESS) {
823                         free(var_name16);
824                         return CMD_RET_FAILURE;
825                 }
826
827                 if (memcmp(var_name16, L"Boot", 8))
828                         continue;
829
830                 for (id = 0, i = 0; i < 4; i++) {
831                         digit = u16_tohex(var_name16[4 + i]);
832                         if (digit < 0)
833                                 break;
834                         id = (id << 4) + digit;
835                 }
836                 if (i == 4 && !var_name16[8])
837                         show_efi_boot_opt(var_name16);
838         }
839
840         free(var_name16);
841
842         return CMD_RET_SUCCESS;
843 }
844
845 /**
846  * show_efi_boot_order() - show order of UEFI load options
847  *
848  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
849  *
850  * Show order of UEFI load options defined by BootOrder variable.
851  */
852 static int show_efi_boot_order(void)
853 {
854         efi_guid_t guid;
855         u16 *bootorder = NULL;
856         efi_uintn_t size;
857         int num, i;
858         char var_name[9];
859         u16 var_name16[9], *p16;
860         void *data;
861         struct efi_load_option lo;
862         char *label, *p;
863         size_t label_len16, label_len;
864         efi_status_t ret;
865
866         guid = efi_global_variable_guid;
867         size = 0;
868         ret = EFI_CALL(RT->get_variable(L"BootOrder", &guid, NULL, &size,
869                                         NULL));
870         if (ret == EFI_BUFFER_TOO_SMALL) {
871                 bootorder = malloc(size);
872                 ret = EFI_CALL(RT->get_variable(L"BootOrder", &guid, NULL,
873                                                 &size, bootorder));
874         }
875         if (ret == EFI_NOT_FOUND) {
876                 printf("BootOrder not defined\n");
877                 ret = CMD_RET_SUCCESS;
878                 goto out;
879         } else if (ret != EFI_SUCCESS) {
880                 ret = CMD_RET_FAILURE;
881                 goto out;
882         }
883
884         num = size / sizeof(u16);
885         for (i = 0; i < num; i++) {
886                 sprintf(var_name, "Boot%04X", bootorder[i]);
887                 p16 = var_name16;
888                 utf8_utf16_strncpy(&p16, var_name, 9);
889
890                 size = 0;
891                 ret = EFI_CALL(RT->get_variable(var_name16, &guid, NULL, &size,
892                                                 NULL));
893                 if (ret != EFI_BUFFER_TOO_SMALL) {
894                         printf("%2d: Boot%04X: (not defined)\n",
895                                i + 1, bootorder[i]);
896                         continue;
897                 }
898
899                 data = malloc(size);
900                 if (!data) {
901                         ret = CMD_RET_FAILURE;
902                         goto out;
903                 }
904                 ret = EFI_CALL(RT->get_variable(var_name16, &guid, NULL, &size,
905                                                 data));
906                 if (ret != EFI_SUCCESS) {
907                         free(data);
908                         ret = CMD_RET_FAILURE;
909                         goto out;
910                 }
911
912                 efi_deserialize_load_option(&lo, data);
913
914                 label_len16 = u16_strlen(lo.label);
915                 label_len = utf16_utf8_strnlen(lo.label, label_len16);
916                 label = malloc(label_len + 1);
917                 if (!label) {
918                         free(data);
919                         ret = CMD_RET_FAILURE;
920                         goto out;
921                 }
922                 p = label;
923                 utf16_utf8_strncpy(&p, lo.label, label_len16);
924                 printf("%2d: Boot%04X: %s\n", i + 1, bootorder[i], label);
925                 free(label);
926
927                 free(data);
928         }
929 out:
930         free(bootorder);
931
932         return ret;
933 }
934
935 /**
936  * do_efi_boot_next() - manage UEFI BootNext variable
937  *
938  * @cmdtp:      Command table
939  * @flag:       Command flag
940  * @argc:       Number of arguments
941  * @argv:       Argument array
942  * Return:      CMD_RET_SUCCESS on success,
943  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
944  *
945  * Implement efidebug "boot next" sub-command.
946  * Set BootNext variable.
947  *
948  *     efidebug boot next <id>
949  */
950 static int do_efi_boot_next(cmd_tbl_t *cmdtp, int flag,
951                             int argc, char * const argv[])
952 {
953         u16 bootnext;
954         efi_uintn_t size;
955         char *endp;
956         efi_guid_t guid;
957         efi_status_t ret;
958         int r = CMD_RET_SUCCESS;
959
960         if (argc != 2)
961                 return CMD_RET_USAGE;
962
963         bootnext = (u16)simple_strtoul(argv[1], &endp, 16);
964         if (*endp != '\0' || bootnext > 0xffff) {
965                 printf("invalid value: %s\n", argv[1]);
966                 r = CMD_RET_FAILURE;
967                 goto out;
968         }
969
970         guid = efi_global_variable_guid;
971         size = sizeof(u16);
972         ret = EFI_CALL(RT->set_variable(L"BootNext", &guid,
973                                         EFI_VARIABLE_NON_VOLATILE |
974                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
975                                         EFI_VARIABLE_RUNTIME_ACCESS,
976                                         size, &bootnext));
977         if (ret != EFI_SUCCESS) {
978                 printf("Cannot set BootNext\n");
979                 r = CMD_RET_FAILURE;
980         }
981 out:
982         return r;
983 }
984
985 /**
986  * do_efi_boot_order() - manage UEFI BootOrder variable
987  *
988  * @cmdtp:      Command table
989  * @flag:       Command flag
990  * @argc:       Number of arguments
991  * @argv:       Argument array
992  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
993  *
994  * Implement efidebug "boot order" sub-command.
995  * Show order of UEFI load options, or change it in BootOrder variable.
996  *
997  *     efidebug boot order [<id> ...]
998  */
999 static int do_efi_boot_order(cmd_tbl_t *cmdtp, int flag,
1000                              int argc, char * const argv[])
1001 {
1002         u16 *bootorder = NULL;
1003         efi_uintn_t size;
1004         int id, i;
1005         char *endp;
1006         efi_guid_t guid;
1007         efi_status_t ret;
1008         int r = CMD_RET_SUCCESS;
1009
1010         if (argc == 1)
1011                 return show_efi_boot_order();
1012
1013         argc--;
1014         argv++;
1015
1016         size = argc * sizeof(u16);
1017         bootorder = malloc(size);
1018         if (!bootorder)
1019                 return CMD_RET_FAILURE;
1020
1021         for (i = 0; i < argc; i++) {
1022                 id = (int)simple_strtoul(argv[i], &endp, 16);
1023                 if (*endp != '\0' || id > 0xffff) {
1024                         printf("invalid value: %s\n", argv[i]);
1025                         r = CMD_RET_FAILURE;
1026                         goto out;
1027                 }
1028
1029                 bootorder[i] = (u16)id;
1030         }
1031
1032         guid = efi_global_variable_guid;
1033         ret = EFI_CALL(RT->set_variable(L"BootOrder", &guid,
1034                                         EFI_VARIABLE_NON_VOLATILE |
1035                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
1036                                         EFI_VARIABLE_RUNTIME_ACCESS,
1037                                         size, bootorder));
1038         if (ret != EFI_SUCCESS) {
1039                 printf("Cannot set BootOrder\n");
1040                 r = CMD_RET_FAILURE;
1041         }
1042 out:
1043         free(bootorder);
1044
1045         return r;
1046 }
1047
1048 static cmd_tbl_t cmd_efidebug_boot_sub[] = {
1049         U_BOOT_CMD_MKENT(add, CONFIG_SYS_MAXARGS, 1, do_efi_boot_add, "", ""),
1050         U_BOOT_CMD_MKENT(rm, CONFIG_SYS_MAXARGS, 1, do_efi_boot_rm, "", ""),
1051         U_BOOT_CMD_MKENT(dump, CONFIG_SYS_MAXARGS, 1, do_efi_boot_dump, "", ""),
1052         U_BOOT_CMD_MKENT(next, CONFIG_SYS_MAXARGS, 1, do_efi_boot_next, "", ""),
1053         U_BOOT_CMD_MKENT(order, CONFIG_SYS_MAXARGS, 1, do_efi_boot_order,
1054                          "", ""),
1055 };
1056
1057 /**
1058  * do_efi_boot_opt() - manage UEFI load options
1059  *
1060  * @cmdtp:      Command table
1061  * @flag:       Command flag
1062  * @argc:       Number of arguments
1063  * @argv:       Argument array
1064  * Return:      CMD_RET_SUCCESS on success,
1065  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1066  *
1067  * Implement efidebug "boot" sub-command.
1068  */
1069 static int do_efi_boot_opt(cmd_tbl_t *cmdtp, int flag,
1070                            int argc, char * const argv[])
1071 {
1072         cmd_tbl_t *cp;
1073
1074         if (argc < 2)
1075                 return CMD_RET_USAGE;
1076
1077         argc--; argv++;
1078
1079         cp = find_cmd_tbl(argv[0], cmd_efidebug_boot_sub,
1080                           ARRAY_SIZE(cmd_efidebug_boot_sub));
1081         if (!cp)
1082                 return CMD_RET_USAGE;
1083
1084         return cp->cmd(cmdtp, flag, argc, argv);
1085 }
1086
1087 /**
1088  * do_efi_test_bootmgr() - run simple bootmgr for test
1089  *
1090  * @cmdtp:      Command table
1091  * @flag:       Command flag
1092  * @argc:       Number of arguments
1093  * @argv:       Argument array
1094  * Return:      CMD_RET_SUCCESS on success,
1095  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1096  *
1097  * Implement efidebug "test bootmgr" sub-command.
1098  * Run simple bootmgr for test.
1099  *
1100  *     efidebug test bootmgr
1101  */
1102 static int do_efi_test_bootmgr(cmd_tbl_t *cmdtp, int flag,
1103                                int argc, char * const argv[])
1104 {
1105         efi_handle_t image;
1106         efi_uintn_t exit_data_size = 0;
1107         u16 *exit_data = NULL;
1108         efi_status_t ret;
1109
1110         ret = efi_bootmgr_load(&image);
1111         printf("efi_bootmgr_load() returned: %ld\n", ret & ~EFI_ERROR_MASK);
1112
1113         /* We call efi_start_image() even if error for test purpose. */
1114         ret = EFI_CALL(efi_start_image(image, &exit_data_size, &exit_data));
1115         printf("efi_start_image() returned: %ld\n", ret & ~EFI_ERROR_MASK);
1116         if (ret && exit_data)
1117                 efi_free_pool(exit_data);
1118
1119         efi_restore_gd();
1120
1121         return CMD_RET_SUCCESS;
1122 }
1123
1124 static cmd_tbl_t cmd_efidebug_test_sub[] = {
1125         U_BOOT_CMD_MKENT(bootmgr, CONFIG_SYS_MAXARGS, 1, do_efi_test_bootmgr,
1126                          "", ""),
1127 };
1128
1129 /**
1130  * do_efi_test() - manage UEFI load options
1131  *
1132  * @cmdtp:      Command table
1133  * @flag:       Command flag
1134  * @argc:       Number of arguments
1135  * @argv:       Argument array
1136  * Return:      CMD_RET_SUCCESS on success,
1137  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1138  *
1139  * Implement efidebug "test" sub-command.
1140  */
1141 static int do_efi_test(cmd_tbl_t *cmdtp, int flag,
1142                        int argc, char * const argv[])
1143 {
1144         cmd_tbl_t *cp;
1145
1146         if (argc < 2)
1147                 return CMD_RET_USAGE;
1148
1149         argc--; argv++;
1150
1151         cp = find_cmd_tbl(argv[0], cmd_efidebug_test_sub,
1152                           ARRAY_SIZE(cmd_efidebug_test_sub));
1153         if (!cp)
1154                 return CMD_RET_USAGE;
1155
1156         return cp->cmd(cmdtp, flag, argc, argv);
1157 }
1158
1159 static cmd_tbl_t cmd_efidebug_sub[] = {
1160         U_BOOT_CMD_MKENT(boot, CONFIG_SYS_MAXARGS, 1, do_efi_boot_opt, "", ""),
1161         U_BOOT_CMD_MKENT(devices, CONFIG_SYS_MAXARGS, 1, do_efi_show_devices,
1162                          "", ""),
1163         U_BOOT_CMD_MKENT(drivers, CONFIG_SYS_MAXARGS, 1, do_efi_show_drivers,
1164                          "", ""),
1165         U_BOOT_CMD_MKENT(dh, CONFIG_SYS_MAXARGS, 1, do_efi_show_handles,
1166                          "", ""),
1167         U_BOOT_CMD_MKENT(images, CONFIG_SYS_MAXARGS, 1, do_efi_show_images,
1168                          "", ""),
1169         U_BOOT_CMD_MKENT(memmap, CONFIG_SYS_MAXARGS, 1, do_efi_show_memmap,
1170                          "", ""),
1171         U_BOOT_CMD_MKENT(tables, CONFIG_SYS_MAXARGS, 1, do_efi_show_tables,
1172                          "", ""),
1173         U_BOOT_CMD_MKENT(test, CONFIG_SYS_MAXARGS, 1, do_efi_test,
1174                          "", ""),
1175 };
1176
1177 /**
1178  * do_efidebug() - display and configure UEFI environment
1179  *
1180  * @cmdtp:      Command table
1181  * @flag:       Command flag
1182  * @argc:       Number of arguments
1183  * @argv:       Argument array
1184  * Return:      CMD_RET_SUCCESS on success,
1185  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1186  *
1187  * Implement efidebug command which allows us to display and
1188  * configure UEFI environment.
1189  */
1190 static int do_efidebug(cmd_tbl_t *cmdtp, int flag,
1191                        int argc, char * const argv[])
1192 {
1193         cmd_tbl_t *cp;
1194         efi_status_t r;
1195
1196         if (argc < 2)
1197                 return CMD_RET_USAGE;
1198
1199         argc--; argv++;
1200
1201         /* Initialize UEFI drivers */
1202         r = efi_init_obj_list();
1203         if (r != EFI_SUCCESS) {
1204                 printf("Error: Cannot initialize UEFI sub-system, r = %lu\n",
1205                        r & ~EFI_ERROR_MASK);
1206                 return CMD_RET_FAILURE;
1207         }
1208
1209         cp = find_cmd_tbl(argv[0], cmd_efidebug_sub,
1210                           ARRAY_SIZE(cmd_efidebug_sub));
1211         if (!cp)
1212                 return CMD_RET_USAGE;
1213
1214         return cp->cmd(cmdtp, flag, argc, argv);
1215 }
1216
1217 #ifdef CONFIG_SYS_LONGHELP
1218 static char efidebug_help_text[] =
1219         "  - UEFI Shell-like interface to configure UEFI environment\n"
1220         "\n"
1221         "efidebug boot add <bootid> <label> <interface> <devnum>[:<part>] <file path> [<load options>]\n"
1222         "  - set UEFI BootXXXX variable\n"
1223         "    <load options> will be passed to UEFI application\n"
1224         "efidebug boot rm <bootid#1> [<bootid#2> [<bootid#3> [...]]]\n"
1225         "  - delete UEFI BootXXXX variables\n"
1226         "efidebug boot dump\n"
1227         "  - dump all UEFI BootXXXX variables\n"
1228         "efidebug boot next <bootid>\n"
1229         "  - set UEFI BootNext variable\n"
1230         "efidebug boot order [<bootid#1> [<bootid#2> [<bootid#3> [...]]]]\n"
1231         "  - set/show UEFI boot order\n"
1232         "\n"
1233         "efidebug devices\n"
1234         "  - show UEFI devices\n"
1235         "efidebug drivers\n"
1236         "  - show UEFI drivers\n"
1237         "efidebug dh\n"
1238         "  - show UEFI handles\n"
1239         "efidebug images\n"
1240         "  - show loaded images\n"
1241         "efidebug memmap\n"
1242         "  - show UEFI memory map\n"
1243         "efidebug tables\n"
1244         "  - show UEFI configuration tables\n"
1245         "efidebug test bootmgr\n"
1246         "  - run simple bootmgr for test\n";
1247 #endif
1248
1249 U_BOOT_CMD(
1250         efidebug, 10, 0, do_efidebug,
1251         "Configure UEFI environment",
1252         efidebug_help_text
1253 );