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