cmd: efi: ESRT table debug print
[platform/kernel/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_dt_fixup.h>
12 #include <efi_load_initrd.h>
13 #include <efi_loader.h>
14 #include <efi_rng.h>
15 #include <exports.h>
16 #include <hexdump.h>
17 #include <log.h>
18 #include <malloc.h>
19 #include <mapmem.h>
20 #include <part.h>
21 #include <search.h>
22 #include <linux/ctype.h>
23 #include <linux/err.h>
24
25 #define BS systab.boottime
26 #define RT systab.runtime
27
28 #ifdef CONFIG_EFI_HAVE_CAPSULE_SUPPORT
29 /**
30  * do_efi_capsule_update() - process a capsule update
31  *
32  * @cmdtp:      Command table
33  * @flag:       Command flag
34  * @argc:       Number of arguments
35  * @argv:       Argument array
36  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
37  *
38  * Implement efidebug "capsule update" sub-command.
39  * process a capsule update.
40  *
41  *     efidebug capsule update [-v] <capsule address>
42  */
43 static int do_efi_capsule_update(struct cmd_tbl *cmdtp, int flag,
44                                  int argc, char * const argv[])
45 {
46         struct efi_capsule_header *capsule;
47         int verbose = 0;
48         char *endp;
49         efi_status_t ret;
50
51         if (argc != 2 && argc != 3)
52                 return CMD_RET_USAGE;
53
54         if (argc == 3) {
55                 if (strcmp(argv[1], "-v"))
56                         return CMD_RET_USAGE;
57
58                 verbose = 1;
59                 argc--;
60                 argv++;
61         }
62
63         capsule = (typeof(capsule))simple_strtoul(argv[1], &endp, 16);
64         if (endp == argv[1]) {
65                 printf("Invalid address: %s", argv[1]);
66                 return CMD_RET_FAILURE;
67         }
68
69         if (verbose) {
70                 printf("Capsule guid: %pUl\n", &capsule->capsule_guid);
71                 printf("Capsule flags: 0x%x\n", capsule->flags);
72                 printf("Capsule header size: 0x%x\n", capsule->header_size);
73                 printf("Capsule image size: 0x%x\n",
74                        capsule->capsule_image_size);
75         }
76
77         ret = EFI_CALL(RT->update_capsule(&capsule, 1, 0));
78         if (ret) {
79                 printf("Cannot handle a capsule at %p", capsule);
80                 return CMD_RET_FAILURE;
81         }
82
83         return CMD_RET_SUCCESS;
84 }
85
86 static int do_efi_capsule_on_disk_update(struct cmd_tbl *cmdtp, int flag,
87                                          int argc, char * const argv[])
88 {
89         efi_status_t ret;
90
91         ret = efi_launch_capsules();
92
93         return ret == EFI_SUCCESS ? CMD_RET_SUCCESS : CMD_RET_FAILURE;
94 }
95
96 /**
97  * do_efi_capsule_show() - show capsule information
98  *
99  * @cmdtp:      Command table
100  * @flag:       Command flag
101  * @argc:       Number of arguments
102  * @argv:       Argument array
103  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
104  *
105  * Implement efidebug "capsule show" sub-command.
106  * show capsule information.
107  *
108  *     efidebug capsule show <capsule address>
109  */
110 static int do_efi_capsule_show(struct cmd_tbl *cmdtp, int flag,
111                                int argc, char * const argv[])
112 {
113         struct efi_capsule_header *capsule;
114         char *endp;
115
116         if (argc != 2)
117                 return CMD_RET_USAGE;
118
119         capsule = (typeof(capsule))simple_strtoul(argv[1], &endp, 16);
120         if (endp == argv[1]) {
121                 printf("Invalid address: %s", argv[1]);
122                 return CMD_RET_FAILURE;
123         }
124
125         printf("Capsule guid: %pUl\n", &capsule->capsule_guid);
126         printf("Capsule flags: 0x%x\n", capsule->flags);
127         printf("Capsule header size: 0x%x\n", capsule->header_size);
128         printf("Capsule image size: 0x%x\n",
129                capsule->capsule_image_size);
130
131         return CMD_RET_SUCCESS;
132 }
133
134 #ifdef CONFIG_EFI_ESRT
135
136 #define EFI_ESRT_FW_TYPE_NUM 4
137 char *efi_fw_type_str[EFI_ESRT_FW_TYPE_NUM] = {"unknown", "system FW", "device FW",
138          "UEFI driver"};
139
140 #define EFI_ESRT_UPDATE_STATUS_NUM 9
141 char *efi_update_status_str[EFI_ESRT_UPDATE_STATUS_NUM] = {"success", "unsuccessful",
142         "insufficient resources", "incorrect version", "invalid format",
143         "auth error", "power event (AC)", "power event (batt)",
144         "unsatisfied dependencies"};
145
146 #define EFI_FW_TYPE_STR_GET(idx) (\
147 EFI_ESRT_FW_TYPE_NUM > (idx) ? efi_fw_type_str[(idx)] : "error"\
148 )
149
150 #define EFI_FW_STATUS_STR_GET(idx) (\
151 EFI_ESRT_UPDATE_STATUS_NUM  > (idx) ? efi_update_status_str[(idx)] : "error"\
152 )
153
154 /**
155  * do_efi_capsule_esrt() - manage UEFI capsules
156  *
157  * @cmdtp:      Command table
158  * @flag:       Command flag
159  * @argc:       Number of arguments
160  * @argv:       Argument array
161  * Return:      CMD_RET_SUCCESS on success,
162  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
163  *
164  * Implement efidebug "capsule esrt" sub-command.
165  * The prints the current ESRT table.
166  *
167  *     efidebug capsule esrt
168  */
169 static int do_efi_capsule_esrt(struct cmd_tbl *cmdtp, int flag,
170                                int argc, char * const argv[])
171 {
172         struct efi_system_resource_table *esrt = NULL;
173
174         if (argc != 1)
175                 return CMD_RET_USAGE;
176
177         for (int idx = 0; idx < systab.nr_tables; idx++)
178                 if (!guidcmp(&efi_esrt_guid, &systab.tables[idx].guid))
179                         esrt = (struct efi_system_resource_table *)systab.tables[idx].table;
180
181         if (!esrt) {
182                 log_info("ESRT: table not present\n");
183                 return CMD_RET_SUCCESS;
184         }
185
186         printf("========================================\n");
187         printf("ESRT: fw_resource_count=%d\n", esrt->fw_resource_count);
188         printf("ESRT: fw_resource_count_max=%d\n", esrt->fw_resource_count_max);
189         printf("ESRT: fw_resource_version=%lld\n", esrt->fw_resource_version);
190
191         for (int idx = 0; idx < esrt->fw_resource_count; idx++) {
192                 printf("[entry %d]==============================\n", idx);
193                 printf("ESRT: fw_class=%pUL\n", &esrt->entries[idx].fw_class);
194                 printf("ESRT: fw_type=%s\n", EFI_FW_TYPE_STR_GET(esrt->entries[idx].fw_type));
195                 printf("ESRT: fw_version=%d\n", esrt->entries[idx].fw_version);
196                 printf("ESRT: lowest_supported_fw_version=%d\n",
197                        esrt->entries[idx].lowest_supported_fw_version);
198                 printf("ESRT: capsule_flags=%d\n",
199                        esrt->entries[idx].capsule_flags);
200                 printf("ESRT: last_attempt_version=%d\n",
201                        esrt->entries[idx].last_attempt_version);
202                 printf("ESRT: last_attempt_status=%s\n",
203                        EFI_FW_STATUS_STR_GET(esrt->entries[idx].last_attempt_status));
204         }
205         printf("========================================\n");
206
207         return CMD_RET_SUCCESS;
208 }
209 #endif /*  CONFIG_EFI_ESRT */
210 /**
211  * do_efi_capsule_res() - show a capsule update result
212  *
213  * @cmdtp:      Command table
214  * @flag:       Command flag
215  * @argc:       Number of arguments
216  * @argv:       Argument array
217  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
218  *
219  * Implement efidebug "capsule result" sub-command.
220  * show a capsule update result.
221  * If result number is not specified, CapsuleLast will be shown.
222  *
223  *     efidebug capsule result [<capsule result number>]
224  */
225 static int do_efi_capsule_res(struct cmd_tbl *cmdtp, int flag,
226                               int argc, char * const argv[])
227 {
228         int capsule_id;
229         char *endp;
230         char var_name[12];
231         u16 var_name16[12], *p;
232         efi_guid_t guid;
233         struct efi_capsule_result_variable_header *result = NULL;
234         efi_uintn_t size;
235         efi_status_t ret;
236
237         if (argc != 1 && argc != 2)
238                 return CMD_RET_USAGE;
239
240         guid = efi_guid_capsule_report;
241         if (argc == 1) {
242                 size = sizeof(var_name16);
243                 ret = EFI_CALL(RT->get_variable(L"CapsuleLast", &guid, NULL,
244                                                 &size, var_name16));
245                 if (ret != EFI_SUCCESS) {
246                         if (ret == EFI_NOT_FOUND)
247                                 printf("CapsuleLast doesn't exist\n");
248                         else
249                                 printf("Failed to get CapsuleLast\n");
250
251                         return CMD_RET_FAILURE;
252                 }
253                 printf("CapsuleLast is %ls\n", var_name16);
254         } else {
255                 argc--;
256                 argv++;
257
258                 capsule_id = simple_strtoul(argv[0], &endp, 16);
259                 if (capsule_id < 0 || capsule_id > 0xffff)
260                         return CMD_RET_USAGE;
261
262                 sprintf(var_name, "Capsule%04X", capsule_id);
263                 p = var_name16;
264                 utf8_utf16_strncpy(&p, var_name, 9);
265         }
266
267         size = 0;
268         ret = EFI_CALL(RT->get_variable(var_name16, &guid, NULL, &size, NULL));
269         if (ret == EFI_BUFFER_TOO_SMALL) {
270                 result = malloc(size);
271                 if (!result)
272                         return CMD_RET_FAILURE;
273                 ret = EFI_CALL(RT->get_variable(var_name16, &guid, NULL, &size,
274                                                 result));
275         }
276         if (ret != EFI_SUCCESS) {
277                 free(result);
278                 printf("Failed to get %ls\n", var_name16);
279
280                 return CMD_RET_FAILURE;
281         }
282
283         printf("Result total size: 0x%x\n", result->variable_total_size);
284         printf("Capsule guid: %pUl\n", &result->capsule_guid);
285         printf("Time processed: %04d-%02d-%02d %02d:%02d:%02d\n",
286                result->capsule_processed.year, result->capsule_processed.month,
287                result->capsule_processed.day, result->capsule_processed.hour,
288                result->capsule_processed.minute,
289                result->capsule_processed.second);
290         printf("Capsule status: 0x%lx\n", result->capsule_status);
291
292         free(result);
293
294         return CMD_RET_SUCCESS;
295 }
296
297 static struct cmd_tbl cmd_efidebug_capsule_sub[] = {
298         U_BOOT_CMD_MKENT(update, CONFIG_SYS_MAXARGS, 1, do_efi_capsule_update,
299                          "", ""),
300         U_BOOT_CMD_MKENT(show, CONFIG_SYS_MAXARGS, 1, do_efi_capsule_show,
301                          "", ""),
302 #ifdef CONFIG_EFI_ESRT
303         U_BOOT_CMD_MKENT(esrt, CONFIG_SYS_MAXARGS, 1, do_efi_capsule_esrt,
304                          "", ""),
305 #endif
306         U_BOOT_CMD_MKENT(disk-update, 0, 0, do_efi_capsule_on_disk_update,
307                          "", ""),
308         U_BOOT_CMD_MKENT(result, CONFIG_SYS_MAXARGS, 1, do_efi_capsule_res,
309                          "", ""),
310 };
311
312 /**
313  * do_efi_capsule() - manage UEFI capsules
314  *
315  * @cmdtp:      Command table
316  * @flag:       Command flag
317  * @argc:       Number of arguments
318  * @argv:       Argument array
319  * Return:      CMD_RET_SUCCESS on success,
320  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
321  *
322  * Implement efidebug "capsule" sub-command.
323  */
324 static int do_efi_capsule(struct cmd_tbl *cmdtp, int flag,
325                           int argc, char * const argv[])
326 {
327         struct cmd_tbl *cp;
328
329         if (argc < 2)
330                 return CMD_RET_USAGE;
331
332         argc--; argv++;
333
334         cp = find_cmd_tbl(argv[0], cmd_efidebug_capsule_sub,
335                           ARRAY_SIZE(cmd_efidebug_capsule_sub));
336         if (!cp)
337                 return CMD_RET_USAGE;
338
339         return cp->cmd(cmdtp, flag, argc, argv);
340 }
341 #endif /* CONFIG_EFI_HAVE_CAPSULE_SUPPORT */
342
343 /**
344  * efi_get_device_handle_info() - get information of UEFI device
345  *
346  * @handle:             Handle of UEFI device
347  * @dev_path_text:      Pointer to text of device path
348  * Return:              0 on success, -1 on failure
349  *
350  * Currently return a formatted text of device path.
351  */
352 static int efi_get_device_handle_info(efi_handle_t handle, u16 **dev_path_text)
353 {
354         struct efi_device_path *dp;
355         efi_status_t ret;
356
357         ret = EFI_CALL(BS->open_protocol(handle, &efi_guid_device_path,
358                                          (void **)&dp, NULL /* FIXME */, NULL,
359                                          EFI_OPEN_PROTOCOL_GET_PROTOCOL));
360         if (ret == EFI_SUCCESS) {
361                 *dev_path_text = efi_dp_str(dp);
362                 return 0;
363         } else {
364                 return -1;
365         }
366 }
367
368 #define EFI_HANDLE_WIDTH ((int)sizeof(efi_handle_t) * 2)
369
370 static const char spc[] = "                ";
371 static const char sep[] = "================";
372
373 /**
374  * do_efi_show_devices() - show UEFI devices
375  *
376  * @cmdtp:      Command table
377  * @flag:       Command flag
378  * @argc:       Number of arguments
379  * @argv:       Argument array
380  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
381  *
382  * Implement efidebug "devices" sub-command.
383  * Show all UEFI devices and their information.
384  */
385 static int do_efi_show_devices(struct cmd_tbl *cmdtp, int flag,
386                                int argc, char *const argv[])
387 {
388         efi_handle_t *handles;
389         efi_uintn_t num, i;
390         u16 *dev_path_text;
391         efi_status_t ret;
392
393         ret = EFI_CALL(efi_locate_handle_buffer(ALL_HANDLES, NULL, NULL,
394                                                 &num, &handles));
395         if (ret != EFI_SUCCESS)
396                 return CMD_RET_FAILURE;
397
398         if (!num)
399                 return CMD_RET_SUCCESS;
400
401         printf("Device%.*s Device Path\n", EFI_HANDLE_WIDTH - 6, spc);
402         printf("%.*s ====================\n", EFI_HANDLE_WIDTH, sep);
403         for (i = 0; i < num; i++) {
404                 if (!efi_get_device_handle_info(handles[i], &dev_path_text)) {
405                         printf("%p %ls\n", handles[i], dev_path_text);
406                         efi_free_pool(dev_path_text);
407                 }
408         }
409
410         efi_free_pool(handles);
411
412         return CMD_RET_SUCCESS;
413 }
414
415 /**
416  * efi_get_driver_handle_info() - get information of UEFI driver
417  *
418  * @handle:             Handle of UEFI device
419  * @driver_name:        Driver name
420  * @image_path:         Pointer to text of device path
421  * Return:              0 on success, -1 on failure
422  *
423  * Currently return no useful information as all UEFI drivers are
424  * built-in..
425  */
426 static int efi_get_driver_handle_info(efi_handle_t handle, u16 **driver_name,
427                                       u16 **image_path)
428 {
429         struct efi_handler *handler;
430         struct efi_loaded_image *image;
431         efi_status_t ret;
432
433         /*
434          * driver name
435          * TODO: support EFI_COMPONENT_NAME2_PROTOCOL
436          */
437         *driver_name = NULL;
438
439         /* image name */
440         ret = efi_search_protocol(handle, &efi_guid_loaded_image, &handler);
441         if (ret != EFI_SUCCESS) {
442                 *image_path = NULL;
443                 return 0;
444         }
445
446         image = handler->protocol_interface;
447         *image_path = efi_dp_str(image->file_path);
448
449         return 0;
450 }
451
452 /**
453  * do_efi_show_drivers() - show UEFI drivers
454  *
455  * @cmdtp:      Command table
456  * @flag:       Command flag
457  * @argc:       Number of arguments
458  * @argv:       Argument array
459  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
460  *
461  * Implement efidebug "drivers" sub-command.
462  * Show all UEFI drivers and their information.
463  */
464 static int do_efi_show_drivers(struct cmd_tbl *cmdtp, int flag,
465                                int argc, char *const argv[])
466 {
467         efi_handle_t *handles;
468         efi_uintn_t num, i;
469         u16 *driver_name, *image_path_text;
470         efi_status_t ret;
471
472         ret = EFI_CALL(efi_locate_handle_buffer(
473                                 BY_PROTOCOL, &efi_guid_driver_binding_protocol,
474                                 NULL, &num, &handles));
475         if (ret != EFI_SUCCESS)
476                 return CMD_RET_FAILURE;
477
478         if (!num)
479                 return CMD_RET_SUCCESS;
480
481         printf("Driver%.*s Name                 Image Path\n",
482                EFI_HANDLE_WIDTH - 6, spc);
483         printf("%.*s ==================== ====================\n",
484                EFI_HANDLE_WIDTH, sep);
485         for (i = 0; i < num; i++) {
486                 if (!efi_get_driver_handle_info(handles[i], &driver_name,
487                                                 &image_path_text)) {
488                         if (image_path_text)
489                                 printf("%p %-20ls %ls\n", handles[i],
490                                        driver_name, image_path_text);
491                         else
492                                 printf("%p %-20ls <built-in>\n",
493                                        handles[i], driver_name);
494                         efi_free_pool(driver_name);
495                         efi_free_pool(image_path_text);
496                 }
497         }
498
499         efi_free_pool(handles);
500
501         return CMD_RET_SUCCESS;
502 }
503
504 static const struct {
505         const char *text;
506         const efi_guid_t guid;
507 } guid_list[] = {
508         {
509                 "Device Path",
510                 EFI_DEVICE_PATH_PROTOCOL_GUID,
511         },
512         {
513                 "Device Path To Text",
514                 EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID,
515         },
516         {
517                 "Device Path Utilities",
518                 EFI_DEVICE_PATH_UTILITIES_PROTOCOL_GUID,
519         },
520         {
521                 "Unicode Collation 2",
522                 EFI_UNICODE_COLLATION_PROTOCOL2_GUID,
523         },
524         {
525                 "Driver Binding",
526                 EFI_DRIVER_BINDING_PROTOCOL_GUID,
527         },
528         {
529                 "Simple Text Input",
530                 EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID,
531         },
532         {
533                 "Simple Text Input Ex",
534                 EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID,
535         },
536         {
537                 "Simple Text Output",
538                 EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL_GUID,
539         },
540         {
541                 "Block IO",
542                 EFI_BLOCK_IO_PROTOCOL_GUID,
543         },
544         {
545                 "Simple File System",
546                 EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID,
547         },
548         {
549                 "Loaded Image",
550                 EFI_LOADED_IMAGE_PROTOCOL_GUID,
551         },
552         {
553                 "Graphics Output",
554                 EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID,
555         },
556         {
557                 "HII String",
558                 EFI_HII_STRING_PROTOCOL_GUID,
559         },
560         {
561                 "HII Database",
562                 EFI_HII_DATABASE_PROTOCOL_GUID,
563         },
564         {
565                 "HII Config Routing",
566                 EFI_HII_CONFIG_ROUTING_PROTOCOL_GUID,
567         },
568         {
569                 "Load File2",
570                 EFI_LOAD_FILE2_PROTOCOL_GUID,
571         },
572         {
573                 "Random Number Generator",
574                 EFI_RNG_PROTOCOL_GUID,
575         },
576         {
577                 "Simple Network",
578                 EFI_SIMPLE_NETWORK_PROTOCOL_GUID,
579         },
580         {
581                 "PXE Base Code",
582                 EFI_PXE_BASE_CODE_PROTOCOL_GUID,
583         },
584         {
585                 "Device-Tree Fixup",
586                 EFI_DT_FIXUP_PROTOCOL_GUID,
587         },
588         {
589                 "System Partition",
590                 PARTITION_SYSTEM_GUID
591         },
592         {
593                 "Firmware Management",
594                 EFI_FIRMWARE_MANAGEMENT_PROTOCOL_GUID
595         },
596         /* Configuration table GUIDs */
597         {
598                 "ACPI table",
599                 EFI_ACPI_TABLE_GUID,
600         },
601         {
602                 "EFI System Resource Table",
603                 EFI_SYSTEM_RESOURCE_TABLE_GUID,
604         },
605         {
606                 "device tree",
607                 EFI_FDT_GUID,
608         },
609         {
610                 "SMBIOS table",
611                 SMBIOS_TABLE_GUID,
612         },
613         {
614                 "Runtime properties",
615                 EFI_RT_PROPERTIES_TABLE_GUID,
616         },
617         {
618                 "TCG2 Final Events Table",
619                 EFI_TCG2_FINAL_EVENTS_TABLE_GUID,
620         },
621 };
622
623 /**
624  * get_guid_text - get string of GUID
625  *
626  * Return description of GUID.
627  *
628  * @guid:       GUID
629  * Return:      description of GUID or NULL
630  */
631 static const char *get_guid_text(const void *guid)
632 {
633         int i;
634
635         for (i = 0; i < ARRAY_SIZE(guid_list); i++) {
636                 /*
637                  * As guidcmp uses memcmp() we can safely accept unaligned
638                  * GUIDs.
639                  */
640                 if (!guidcmp(&guid_list[i].guid, guid))
641                         return guid_list[i].text;
642         }
643
644         return NULL;
645 }
646
647 /**
648  * do_efi_show_handles() - show UEFI handles
649  *
650  * @cmdtp:      Command table
651  * @flag:       Command flag
652  * @argc:       Number of arguments
653  * @argv:       Argument array
654  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
655  *
656  * Implement efidebug "dh" sub-command.
657  * Show all UEFI handles and their information, currently all protocols
658  * added to handle.
659  */
660 static int do_efi_show_handles(struct cmd_tbl *cmdtp, int flag,
661                                int argc, char *const argv[])
662 {
663         efi_handle_t *handles;
664         efi_guid_t **guid;
665         efi_uintn_t num, count, i, j;
666         const char *guid_text;
667         efi_status_t ret;
668
669         ret = EFI_CALL(efi_locate_handle_buffer(ALL_HANDLES, NULL, NULL,
670                                                 &num, &handles));
671         if (ret != EFI_SUCCESS)
672                 return CMD_RET_FAILURE;
673
674         if (!num)
675                 return CMD_RET_SUCCESS;
676
677         printf("Handle%.*s Protocols\n", EFI_HANDLE_WIDTH - 6, spc);
678         printf("%.*s ====================\n", EFI_HANDLE_WIDTH, sep);
679         for (i = 0; i < num; i++) {
680                 printf("%p", handles[i]);
681                 ret = EFI_CALL(BS->protocols_per_handle(handles[i], &guid,
682                                                         &count));
683                 if (ret || !count) {
684                         putc('\n');
685                         continue;
686                 }
687
688                 for (j = 0; j < count; j++) {
689                         if (j)
690                                 printf(", ");
691                         else
692                                 putc(' ');
693
694                         guid_text = get_guid_text(guid[j]);
695                         if (guid_text)
696                                 puts(guid_text);
697                         else
698                                 printf("%pUl", guid[j]);
699                 }
700                 putc('\n');
701         }
702
703         efi_free_pool(handles);
704
705         return CMD_RET_SUCCESS;
706 }
707
708 /**
709  * do_efi_show_images() - show UEFI images
710  *
711  * @cmdtp:      Command table
712  * @flag:       Command flag
713  * @argc:       Number of arguments
714  * @argv:       Argument array
715  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
716  *
717  * Implement efidebug "images" sub-command.
718  * Show all UEFI loaded images and their information.
719  */
720 static int do_efi_show_images(struct cmd_tbl *cmdtp, int flag,
721                               int argc, char *const argv[])
722 {
723         efi_print_image_infos(NULL);
724
725         return CMD_RET_SUCCESS;
726 }
727
728 static const char * const efi_mem_type_string[] = {
729         [EFI_RESERVED_MEMORY_TYPE] = "RESERVED",
730         [EFI_LOADER_CODE] = "LOADER CODE",
731         [EFI_LOADER_DATA] = "LOADER DATA",
732         [EFI_BOOT_SERVICES_CODE] = "BOOT CODE",
733         [EFI_BOOT_SERVICES_DATA] = "BOOT DATA",
734         [EFI_RUNTIME_SERVICES_CODE] = "RUNTIME CODE",
735         [EFI_RUNTIME_SERVICES_DATA] = "RUNTIME DATA",
736         [EFI_CONVENTIONAL_MEMORY] = "CONVENTIONAL",
737         [EFI_UNUSABLE_MEMORY] = "UNUSABLE MEM",
738         [EFI_ACPI_RECLAIM_MEMORY] = "ACPI RECLAIM MEM",
739         [EFI_ACPI_MEMORY_NVS] = "ACPI NVS",
740         [EFI_MMAP_IO] = "IO",
741         [EFI_MMAP_IO_PORT] = "IO PORT",
742         [EFI_PAL_CODE] = "PAL",
743         [EFI_PERSISTENT_MEMORY_TYPE] = "PERSISTENT",
744 };
745
746 static const struct efi_mem_attrs {
747         const u64 bit;
748         const char *text;
749 } efi_mem_attrs[] = {
750         {EFI_MEMORY_UC, "UC"},
751         {EFI_MEMORY_UC, "UC"},
752         {EFI_MEMORY_WC, "WC"},
753         {EFI_MEMORY_WT, "WT"},
754         {EFI_MEMORY_WB, "WB"},
755         {EFI_MEMORY_UCE, "UCE"},
756         {EFI_MEMORY_WP, "WP"},
757         {EFI_MEMORY_RP, "RP"},
758         {EFI_MEMORY_XP, "WP"},
759         {EFI_MEMORY_NV, "NV"},
760         {EFI_MEMORY_MORE_RELIABLE, "REL"},
761         {EFI_MEMORY_RO, "RO"},
762         {EFI_MEMORY_SP, "SP"},
763         {EFI_MEMORY_RUNTIME, "RT"},
764 };
765
766 /**
767  * print_memory_attributes() - print memory map attributes
768  *
769  * @attributes: Attribute value
770  *
771  * Print memory map attributes
772  */
773 static void print_memory_attributes(u64 attributes)
774 {
775         int sep, i;
776
777         for (sep = 0, i = 0; i < ARRAY_SIZE(efi_mem_attrs); i++)
778                 if (attributes & efi_mem_attrs[i].bit) {
779                         if (sep) {
780                                 putc('|');
781                         } else {
782                                 putc(' ');
783                                 sep = 1;
784                         }
785                         puts(efi_mem_attrs[i].text);
786                 }
787 }
788
789 #define EFI_PHYS_ADDR_WIDTH (int)(sizeof(efi_physical_addr_t) * 2)
790
791 /**
792  * do_efi_show_memmap() - show UEFI memory map
793  *
794  * @cmdtp:      Command table
795  * @flag:       Command flag
796  * @argc:       Number of arguments
797  * @argv:       Argument array
798  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
799  *
800  * Implement efidebug "memmap" sub-command.
801  * Show UEFI memory map.
802  */
803 static int do_efi_show_memmap(struct cmd_tbl *cmdtp, int flag,
804                               int argc, char *const argv[])
805 {
806         struct efi_mem_desc *memmap = NULL, *map;
807         efi_uintn_t map_size = 0;
808         const char *type;
809         int i;
810         efi_status_t ret;
811
812         ret = efi_get_memory_map(&map_size, memmap, NULL, NULL, NULL);
813         if (ret == EFI_BUFFER_TOO_SMALL) {
814                 map_size += sizeof(struct efi_mem_desc); /* for my own */
815                 ret = efi_allocate_pool(EFI_LOADER_DATA, map_size,
816                                         (void *)&memmap);
817                 if (ret != EFI_SUCCESS)
818                         return CMD_RET_FAILURE;
819                 ret = efi_get_memory_map(&map_size, memmap, NULL, NULL, NULL);
820         }
821         if (ret != EFI_SUCCESS) {
822                 efi_free_pool(memmap);
823                 return CMD_RET_FAILURE;
824         }
825
826         printf("Type             Start%.*s End%.*s Attributes\n",
827                EFI_PHYS_ADDR_WIDTH - 5, spc, EFI_PHYS_ADDR_WIDTH - 3, spc);
828         printf("================ %.*s %.*s ==========\n",
829                EFI_PHYS_ADDR_WIDTH, sep, EFI_PHYS_ADDR_WIDTH, sep);
830         /*
831          * Coverity check: dereferencing null pointer "map."
832          * This is a false positive as memmap will always be
833          * populated by allocate_pool() above.
834          */
835         for (i = 0, map = memmap; i < map_size / sizeof(*map); map++, i++) {
836                 if (map->type < ARRAY_SIZE(efi_mem_type_string))
837                         type = efi_mem_type_string[map->type];
838                 else
839                         type = "(unknown)";
840
841                 printf("%-16s %.*llx-%.*llx", type,
842                        EFI_PHYS_ADDR_WIDTH,
843                        (u64)map_to_sysmem((void *)(uintptr_t)
844                                           map->physical_start),
845                        EFI_PHYS_ADDR_WIDTH,
846                        (u64)map_to_sysmem((void *)(uintptr_t)
847                                           (map->physical_start +
848                                            map->num_pages * EFI_PAGE_SIZE)));
849
850                 print_memory_attributes(map->attribute);
851                 putc('\n');
852         }
853
854         efi_free_pool(memmap);
855
856         return CMD_RET_SUCCESS;
857 }
858
859 /**
860  * do_efi_show_tables() - show UEFI configuration tables
861  *
862  * @cmdtp:      Command table
863  * @flag:       Command flag
864  * @argc:       Number of arguments
865  * @argv:       Argument array
866  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
867  *
868  * Implement efidebug "tables" sub-command.
869  * Show UEFI configuration tables.
870  */
871 static int do_efi_show_tables(struct cmd_tbl *cmdtp, int flag,
872                               int argc, char *const argv[])
873 {
874         efi_uintn_t i;
875         const char *guid_str;
876
877         for (i = 0; i < systab.nr_tables; ++i) {
878                 guid_str = get_guid_text(&systab.tables[i].guid);
879                 if (!guid_str)
880                         guid_str = "";
881                 printf("%pUl %s\n", &systab.tables[i].guid, guid_str);
882         }
883
884         return CMD_RET_SUCCESS;
885 }
886
887 /**
888  * create_initrd_dp() - Create a special device for our Boot### option
889  *
890  * @dev:        Device
891  * @part:       Disk partition
892  * @file:       Filename
893  * Return:      Pointer to the device path or ERR_PTR
894  *
895  */
896 static
897 struct efi_device_path *create_initrd_dp(const char *dev, const char *part,
898                                          const char *file)
899
900 {
901         struct efi_device_path *tmp_dp = NULL, *tmp_fp = NULL;
902         struct efi_device_path *initrd_dp = NULL;
903         efi_status_t ret;
904         const struct efi_initrd_dp id_dp = {
905                 .vendor = {
906                         {
907                         DEVICE_PATH_TYPE_MEDIA_DEVICE,
908                         DEVICE_PATH_SUB_TYPE_VENDOR_PATH,
909                         sizeof(id_dp.vendor),
910                         },
911                         EFI_INITRD_MEDIA_GUID,
912                 },
913                 .end = {
914                         DEVICE_PATH_TYPE_END,
915                         DEVICE_PATH_SUB_TYPE_END,
916                         sizeof(id_dp.end),
917                 }
918         };
919
920         ret = efi_dp_from_name(dev, part, file, &tmp_dp, &tmp_fp);
921         if (ret != EFI_SUCCESS) {
922                 printf("Cannot create device path for \"%s %s\"\n", part, file);
923                 goto out;
924         }
925
926         initrd_dp = efi_dp_append((const struct efi_device_path *)&id_dp,
927                                   tmp_fp);
928
929 out:
930         efi_free_pool(tmp_dp);
931         efi_free_pool(tmp_fp);
932         return initrd_dp;
933 }
934
935 /**
936  * do_efi_boot_add() - set UEFI load option
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 add" sub-command. Create or change UEFI load option.
946  *
947  * efidebug boot add -b <id> <label> <interface> <devnum>[:<part>] <file>
948  *                   -i <file> <interface2> <devnum2>[:<part>] <initrd>
949  *                   -s '<options>'
950  */
951 static int do_efi_boot_add(struct cmd_tbl *cmdtp, int flag,
952                            int argc, char *const argv[])
953 {
954         int id;
955         char *endp;
956         char var_name[9];
957         u16 var_name16[9], *p;
958         efi_guid_t guid;
959         size_t label_len, label_len16;
960         u16 *label;
961         struct efi_device_path *device_path = NULL, *file_path = NULL;
962         struct efi_device_path *final_fp = NULL;
963         struct efi_device_path *initrd_dp = NULL;
964         struct efi_load_option lo;
965         void *data = NULL;
966         efi_uintn_t size;
967         efi_uintn_t fp_size = 0;
968         efi_status_t ret;
969         int r = CMD_RET_SUCCESS;
970
971         guid = efi_global_variable_guid;
972
973         /* attributes */
974         lo.attributes = LOAD_OPTION_ACTIVE; /* always ACTIVE */
975         lo.optional_data = NULL;
976         lo.label = NULL;
977
978         argc--;
979         argv++; /* 'add' */
980         for (; argc > 0; argc--, argv++) {
981                 if (!strcmp(argv[0], "-b")) {
982                         if (argc <  5 || lo.label) {
983                                 r = CMD_RET_USAGE;
984                                 goto out;
985                         }
986                         id = (int)simple_strtoul(argv[1], &endp, 16);
987                         if (*endp != '\0' || id > 0xffff)
988                                 return CMD_RET_USAGE;
989
990                         sprintf(var_name, "Boot%04X", id);
991                         p = var_name16;
992                         utf8_utf16_strncpy(&p, var_name, 9);
993
994                         /* label */
995                         label_len = strlen(argv[2]);
996                         label_len16 = utf8_utf16_strnlen(argv[2], label_len);
997                         label = malloc((label_len16 + 1) * sizeof(u16));
998                         if (!label)
999                                 return CMD_RET_FAILURE;
1000                         lo.label = label; /* label will be changed below */
1001                         utf8_utf16_strncpy(&label, argv[2], label_len);
1002
1003                         /* file path */
1004                         ret = efi_dp_from_name(argv[3], argv[4], argv[5],
1005                                                &device_path, &file_path);
1006                         if (ret != EFI_SUCCESS) {
1007                                 printf("Cannot create device path for \"%s %s\"\n",
1008                                        argv[3], argv[4]);
1009                                 r = CMD_RET_FAILURE;
1010                                 goto out;
1011                         }
1012                         fp_size += efi_dp_size(file_path) +
1013                                 sizeof(struct efi_device_path);
1014                         argc -= 5;
1015                         argv += 5;
1016                 } else if (!strcmp(argv[0], "-i")) {
1017                         if (argc < 3 || initrd_dp) {
1018                                 r = CMD_RET_USAGE;
1019                                 goto out;
1020                         }
1021
1022                         initrd_dp = create_initrd_dp(argv[1], argv[2], argv[3]);
1023                         if (!initrd_dp) {
1024                                 printf("Cannot add an initrd\n");
1025                                 r = CMD_RET_FAILURE;
1026                                 goto out;
1027                         }
1028                         argc -= 3;
1029                         argv += 3;
1030                         fp_size += efi_dp_size(initrd_dp) +
1031                                 sizeof(struct efi_device_path);
1032                 } else if (!strcmp(argv[0], "-s")) {
1033                         if (argc < 1 || lo.optional_data) {
1034                                 r = CMD_RET_USAGE;
1035                                 goto out;
1036                         }
1037                         lo.optional_data = (const u8 *)argv[1];
1038                         argc -= 1;
1039                         argv += 1;
1040                 } else {
1041                         r = CMD_RET_USAGE;
1042                         goto out;
1043                 }
1044         }
1045
1046         if (!file_path) {
1047                 printf("Missing binary\n");
1048                 r = CMD_RET_USAGE;
1049                 goto out;
1050         }
1051
1052         final_fp = efi_dp_concat(file_path, initrd_dp);
1053         if (!final_fp) {
1054                 printf("Cannot create final device path\n");
1055                 r = CMD_RET_FAILURE;
1056                 goto out;
1057         }
1058
1059         lo.file_path = final_fp;
1060         lo.file_path_length = fp_size;
1061
1062         size = efi_serialize_load_option(&lo, (u8 **)&data);
1063         if (!size) {
1064                 r = CMD_RET_FAILURE;
1065                 goto out;
1066         }
1067
1068         ret = EFI_CALL(efi_set_variable(var_name16, &guid,
1069                                         EFI_VARIABLE_NON_VOLATILE |
1070                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
1071                                         EFI_VARIABLE_RUNTIME_ACCESS,
1072                                         size, data));
1073         if (ret != EFI_SUCCESS) {
1074                 printf("Cannot set %ls\n", var_name16);
1075                 r = CMD_RET_FAILURE;
1076         }
1077
1078 out:
1079         free(data);
1080         efi_free_pool(final_fp);
1081         efi_free_pool(initrd_dp);
1082         efi_free_pool(device_path);
1083         efi_free_pool(file_path);
1084         free(lo.label);
1085
1086         return r;
1087 }
1088
1089 /**
1090  * do_efi_boot_rm() - delete UEFI load options
1091  *
1092  * @cmdtp:      Command table
1093  * @flag:       Command flag
1094  * @argc:       Number of arguments
1095  * @argv:       Argument array
1096  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
1097  *
1098  * Implement efidebug "boot rm" sub-command.
1099  * Delete UEFI load options.
1100  *
1101  *     efidebug boot rm <id> ...
1102  */
1103 static int do_efi_boot_rm(struct cmd_tbl *cmdtp, int flag,
1104                           int argc, char *const argv[])
1105 {
1106         efi_guid_t guid;
1107         int id, i;
1108         char *endp;
1109         char var_name[9];
1110         u16 var_name16[9], *p;
1111         efi_status_t ret;
1112
1113         if (argc == 1)
1114                 return CMD_RET_USAGE;
1115
1116         guid = efi_global_variable_guid;
1117         for (i = 1; i < argc; i++, argv++) {
1118                 id = (int)simple_strtoul(argv[1], &endp, 16);
1119                 if (*endp != '\0' || id > 0xffff)
1120                         return CMD_RET_FAILURE;
1121
1122                 sprintf(var_name, "Boot%04X", id);
1123                 p = var_name16;
1124                 utf8_utf16_strncpy(&p, var_name, 9);
1125
1126                 ret = EFI_CALL(efi_set_variable(var_name16, &guid, 0, 0, NULL));
1127                 if (ret) {
1128                         printf("Cannot remove %ls\n", var_name16);
1129                         return CMD_RET_FAILURE;
1130                 }
1131         }
1132
1133         return CMD_RET_SUCCESS;
1134 }
1135
1136 /**
1137  * show_efi_boot_opt_data() - dump UEFI load option
1138  *
1139  * @varname16:  variable name
1140  * @data:       value of UEFI load option variable
1141  * @size:       size of the boot option
1142  *
1143  * Decode the value of UEFI load option variable and print information.
1144  */
1145 static void show_efi_boot_opt_data(u16 *varname16, void *data, size_t *size)
1146 {
1147         struct efi_device_path *initrd_path = NULL;
1148         struct efi_load_option lo;
1149         char *label, *p;
1150         size_t label_len16, label_len;
1151         u16 *dp_str;
1152         efi_status_t ret;
1153         efi_uintn_t initrd_dp_size;
1154         const efi_guid_t lf2_initrd_guid = EFI_INITRD_MEDIA_GUID;
1155
1156         ret = efi_deserialize_load_option(&lo, data, size);
1157         if (ret != EFI_SUCCESS) {
1158                 printf("%ls: invalid load option\n", varname16);
1159                 return;
1160         }
1161
1162         label_len16 = u16_strlen(lo.label);
1163         label_len = utf16_utf8_strnlen(lo.label, label_len16);
1164         label = malloc(label_len + 1);
1165         if (!label)
1166                 return;
1167         p = label;
1168         utf16_utf8_strncpy(&p, lo.label, label_len16);
1169
1170         printf("%ls:\nattributes: %c%c%c (0x%08x)\n",
1171                varname16,
1172                /* ACTIVE */
1173                lo.attributes & LOAD_OPTION_ACTIVE ? 'A' : '-',
1174                /* FORCE RECONNECT */
1175                lo.attributes & LOAD_OPTION_FORCE_RECONNECT ? 'R' : '-',
1176                /* HIDDEN */
1177                lo.attributes & LOAD_OPTION_HIDDEN ? 'H' : '-',
1178                lo.attributes);
1179         printf("  label: %s\n", label);
1180
1181         dp_str = efi_dp_str(lo.file_path);
1182         printf("  file_path: %ls\n", dp_str);
1183         efi_free_pool(dp_str);
1184
1185         initrd_path = efi_dp_from_lo(&lo, &initrd_dp_size, lf2_initrd_guid);
1186         if (initrd_path) {
1187                 dp_str = efi_dp_str(initrd_path);
1188                 printf("  initrd_path: %ls\n", dp_str);
1189                 efi_free_pool(dp_str);
1190                 efi_free_pool(initrd_path);
1191         }
1192
1193         printf("  data:\n");
1194         print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
1195                        lo.optional_data, *size, true);
1196         free(label);
1197 }
1198
1199 /**
1200  * show_efi_boot_opt() - dump UEFI load option
1201  *
1202  * @varname16:  variable name
1203  *
1204  * Dump information defined by UEFI load option.
1205  */
1206 static void show_efi_boot_opt(u16 *varname16)
1207 {
1208         void *data;
1209         efi_uintn_t size;
1210         efi_status_t ret;
1211
1212         size = 0;
1213         ret = EFI_CALL(efi_get_variable(varname16, &efi_global_variable_guid,
1214                                         NULL, &size, NULL));
1215         if (ret == EFI_BUFFER_TOO_SMALL) {
1216                 data = malloc(size);
1217                 if (!data) {
1218                         printf("ERROR: Out of memory\n");
1219                         return;
1220                 }
1221                 ret = EFI_CALL(efi_get_variable(varname16,
1222                                                 &efi_global_variable_guid,
1223                                                 NULL, &size, data));
1224                 if (ret == EFI_SUCCESS)
1225                         show_efi_boot_opt_data(varname16, data, &size);
1226                 free(data);
1227         }
1228 }
1229
1230 static int u16_tohex(u16 c)
1231 {
1232         if (c >= '0' && c <= '9')
1233                 return c - '0';
1234         if (c >= 'A' && c <= 'F')
1235                 return c - 'A' + 10;
1236
1237         /* not hexadecimal */
1238         return -1;
1239 }
1240
1241 /**
1242  * show_efi_boot_dump() - dump all UEFI load options
1243  *
1244  * @cmdtp:      Command table
1245  * @flag:       Command flag
1246  * @argc:       Number of arguments
1247  * @argv:       Argument array
1248  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
1249  *
1250  * Implement efidebug "boot dump" sub-command.
1251  * Dump information of all UEFI load options defined.
1252  *
1253  *     efidebug boot dump
1254  */
1255 static int do_efi_boot_dump(struct cmd_tbl *cmdtp, int flag,
1256                             int argc, char *const argv[])
1257 {
1258         u16 *var_name16, *p;
1259         efi_uintn_t buf_size, size;
1260         efi_guid_t guid;
1261         int id, i, digit;
1262         efi_status_t ret;
1263
1264         if (argc > 1)
1265                 return CMD_RET_USAGE;
1266
1267         buf_size = 128;
1268         var_name16 = malloc(buf_size);
1269         if (!var_name16)
1270                 return CMD_RET_FAILURE;
1271
1272         var_name16[0] = 0;
1273         for (;;) {
1274                 size = buf_size;
1275                 ret = EFI_CALL(efi_get_next_variable_name(&size, var_name16,
1276                                                           &guid));
1277                 if (ret == EFI_NOT_FOUND)
1278                         break;
1279                 if (ret == EFI_BUFFER_TOO_SMALL) {
1280                         buf_size = size;
1281                         p = realloc(var_name16, buf_size);
1282                         if (!p) {
1283                                 free(var_name16);
1284                                 return CMD_RET_FAILURE;
1285                         }
1286                         var_name16 = p;
1287                         ret = EFI_CALL(efi_get_next_variable_name(&size,
1288                                                                   var_name16,
1289                                                                   &guid));
1290                 }
1291                 if (ret != EFI_SUCCESS) {
1292                         free(var_name16);
1293                         return CMD_RET_FAILURE;
1294                 }
1295
1296                 if (memcmp(var_name16, L"Boot", 8))
1297                         continue;
1298
1299                 for (id = 0, i = 0; i < 4; i++) {
1300                         digit = u16_tohex(var_name16[4 + i]);
1301                         if (digit < 0)
1302                                 break;
1303                         id = (id << 4) + digit;
1304                 }
1305                 if (i == 4 && !var_name16[8])
1306                         show_efi_boot_opt(var_name16);
1307         }
1308
1309         free(var_name16);
1310
1311         return CMD_RET_SUCCESS;
1312 }
1313
1314 /**
1315  * show_efi_boot_order() - show order of UEFI load options
1316  *
1317  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
1318  *
1319  * Show order of UEFI load options defined by BootOrder variable.
1320  */
1321 static int show_efi_boot_order(void)
1322 {
1323         u16 *bootorder;
1324         efi_uintn_t size;
1325         int num, i;
1326         char var_name[9];
1327         u16 var_name16[9], *p16;
1328         void *data;
1329         struct efi_load_option lo;
1330         char *label, *p;
1331         size_t label_len16, label_len;
1332         efi_status_t ret;
1333
1334         size = 0;
1335         ret = EFI_CALL(efi_get_variable(L"BootOrder", &efi_global_variable_guid,
1336                                         NULL, &size, NULL));
1337         if (ret != EFI_BUFFER_TOO_SMALL) {
1338                 if (ret == EFI_NOT_FOUND) {
1339                         printf("BootOrder not defined\n");
1340                         return CMD_RET_SUCCESS;
1341                 } else {
1342                         return CMD_RET_FAILURE;
1343                 }
1344         }
1345         bootorder = malloc(size);
1346         if (!bootorder) {
1347                 printf("ERROR: Out of memory\n");
1348                 return CMD_RET_FAILURE;
1349         }
1350         ret = EFI_CALL(efi_get_variable(L"BootOrder", &efi_global_variable_guid,
1351                                         NULL, &size, bootorder));
1352         if (ret != EFI_SUCCESS) {
1353                 ret = CMD_RET_FAILURE;
1354                 goto out;
1355         }
1356
1357         num = size / sizeof(u16);
1358         for (i = 0; i < num; i++) {
1359                 sprintf(var_name, "Boot%04X", bootorder[i]);
1360                 p16 = var_name16;
1361                 utf8_utf16_strncpy(&p16, var_name, 9);
1362
1363                 size = 0;
1364                 ret = EFI_CALL(efi_get_variable(var_name16,
1365                                                 &efi_global_variable_guid, NULL,
1366                                                 &size, NULL));
1367                 if (ret != EFI_BUFFER_TOO_SMALL) {
1368                         printf("%2d: %s: (not defined)\n", i + 1, var_name);
1369                         continue;
1370                 }
1371
1372                 data = malloc(size);
1373                 if (!data) {
1374                         ret = CMD_RET_FAILURE;
1375                         goto out;
1376                 }
1377                 ret = EFI_CALL(efi_get_variable(var_name16,
1378                                                 &efi_global_variable_guid, NULL,
1379                                                 &size, data));
1380                 if (ret != EFI_SUCCESS) {
1381                         free(data);
1382                         ret = CMD_RET_FAILURE;
1383                         goto out;
1384                 }
1385
1386                 ret = efi_deserialize_load_option(&lo, data, &size);
1387                 if (ret != EFI_SUCCESS) {
1388                         printf("%ls: invalid load option\n", var_name16);
1389                         ret = CMD_RET_FAILURE;
1390                         goto out;
1391                 }
1392
1393                 label_len16 = u16_strlen(lo.label);
1394                 label_len = utf16_utf8_strnlen(lo.label, label_len16);
1395                 label = malloc(label_len + 1);
1396                 if (!label) {
1397                         free(data);
1398                         ret = CMD_RET_FAILURE;
1399                         goto out;
1400                 }
1401                 p = label;
1402                 utf16_utf8_strncpy(&p, lo.label, label_len16);
1403                 printf("%2d: %s: %s\n", i + 1, var_name, label);
1404                 free(label);
1405
1406                 free(data);
1407         }
1408 out:
1409         free(bootorder);
1410
1411         return ret;
1412 }
1413
1414 /**
1415  * do_efi_boot_next() - manage UEFI BootNext variable
1416  *
1417  * @cmdtp:      Command table
1418  * @flag:       Command flag
1419  * @argc:       Number of arguments
1420  * @argv:       Argument array
1421  * Return:      CMD_RET_SUCCESS on success,
1422  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1423  *
1424  * Implement efidebug "boot next" sub-command.
1425  * Set BootNext variable.
1426  *
1427  *     efidebug boot next <id>
1428  */
1429 static int do_efi_boot_next(struct cmd_tbl *cmdtp, int flag,
1430                             int argc, char *const argv[])
1431 {
1432         u16 bootnext;
1433         efi_uintn_t size;
1434         char *endp;
1435         efi_guid_t guid;
1436         efi_status_t ret;
1437         int r = CMD_RET_SUCCESS;
1438
1439         if (argc != 2)
1440                 return CMD_RET_USAGE;
1441
1442         bootnext = (u16)simple_strtoul(argv[1], &endp, 16);
1443         if (*endp) {
1444                 printf("invalid value: %s\n", argv[1]);
1445                 r = CMD_RET_FAILURE;
1446                 goto out;
1447         }
1448
1449         guid = efi_global_variable_guid;
1450         size = sizeof(u16);
1451         ret = EFI_CALL(efi_set_variable(L"BootNext", &guid,
1452                                         EFI_VARIABLE_NON_VOLATILE |
1453                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
1454                                         EFI_VARIABLE_RUNTIME_ACCESS,
1455                                         size, &bootnext));
1456         if (ret != EFI_SUCCESS) {
1457                 printf("Cannot set BootNext\n");
1458                 r = CMD_RET_FAILURE;
1459         }
1460 out:
1461         return r;
1462 }
1463
1464 /**
1465  * do_efi_boot_order() - manage UEFI BootOrder variable
1466  *
1467  * @cmdtp:      Command table
1468  * @flag:       Command flag
1469  * @argc:       Number of arguments
1470  * @argv:       Argument array
1471  * Return:      CMD_RET_SUCCESS on success, CMD_RET_RET_FAILURE on failure
1472  *
1473  * Implement efidebug "boot order" sub-command.
1474  * Show order of UEFI load options, or change it in BootOrder variable.
1475  *
1476  *     efidebug boot order [<id> ...]
1477  */
1478 static int do_efi_boot_order(struct cmd_tbl *cmdtp, int flag,
1479                              int argc, char *const argv[])
1480 {
1481         u16 *bootorder = NULL;
1482         efi_uintn_t size;
1483         int id, i;
1484         char *endp;
1485         efi_guid_t guid;
1486         efi_status_t ret;
1487         int r = CMD_RET_SUCCESS;
1488
1489         if (argc == 1)
1490                 return show_efi_boot_order();
1491
1492         argc--;
1493         argv++;
1494
1495         size = argc * sizeof(u16);
1496         bootorder = malloc(size);
1497         if (!bootorder)
1498                 return CMD_RET_FAILURE;
1499
1500         for (i = 0; i < argc; i++) {
1501                 id = (int)simple_strtoul(argv[i], &endp, 16);
1502                 if (*endp != '\0' || id > 0xffff) {
1503                         printf("invalid value: %s\n", argv[i]);
1504                         r = CMD_RET_FAILURE;
1505                         goto out;
1506                 }
1507
1508                 bootorder[i] = (u16)id;
1509         }
1510
1511         guid = efi_global_variable_guid;
1512         ret = EFI_CALL(efi_set_variable(L"BootOrder", &guid,
1513                                         EFI_VARIABLE_NON_VOLATILE |
1514                                         EFI_VARIABLE_BOOTSERVICE_ACCESS |
1515                                         EFI_VARIABLE_RUNTIME_ACCESS,
1516                                         size, bootorder));
1517         if (ret != EFI_SUCCESS) {
1518                 printf("Cannot set BootOrder\n");
1519                 r = CMD_RET_FAILURE;
1520         }
1521 out:
1522         free(bootorder);
1523
1524         return r;
1525 }
1526
1527 static struct cmd_tbl cmd_efidebug_boot_sub[] = {
1528         U_BOOT_CMD_MKENT(add, CONFIG_SYS_MAXARGS, 1, do_efi_boot_add, "", ""),
1529         U_BOOT_CMD_MKENT(rm, CONFIG_SYS_MAXARGS, 1, do_efi_boot_rm, "", ""),
1530         U_BOOT_CMD_MKENT(dump, CONFIG_SYS_MAXARGS, 1, do_efi_boot_dump, "", ""),
1531         U_BOOT_CMD_MKENT(next, CONFIG_SYS_MAXARGS, 1, do_efi_boot_next, "", ""),
1532         U_BOOT_CMD_MKENT(order, CONFIG_SYS_MAXARGS, 1, do_efi_boot_order,
1533                          "", ""),
1534 };
1535
1536 /**
1537  * do_efi_boot_opt() - manage UEFI load options
1538  *
1539  * @cmdtp:      Command table
1540  * @flag:       Command flag
1541  * @argc:       Number of arguments
1542  * @argv:       Argument array
1543  * Return:      CMD_RET_SUCCESS on success,
1544  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1545  *
1546  * Implement efidebug "boot" sub-command.
1547  */
1548 static int do_efi_boot_opt(struct cmd_tbl *cmdtp, int flag,
1549                            int argc, char *const argv[])
1550 {
1551         struct cmd_tbl *cp;
1552
1553         if (argc < 2)
1554                 return CMD_RET_USAGE;
1555
1556         argc--; argv++;
1557
1558         cp = find_cmd_tbl(argv[0], cmd_efidebug_boot_sub,
1559                           ARRAY_SIZE(cmd_efidebug_boot_sub));
1560         if (!cp)
1561                 return CMD_RET_USAGE;
1562
1563         return cp->cmd(cmdtp, flag, argc, argv);
1564 }
1565
1566 /**
1567  * do_efi_test_bootmgr() - run simple bootmgr for test
1568  *
1569  * @cmdtp:      Command table
1570  * @flag:       Command flag
1571  * @argc:       Number of arguments
1572  * @argv:       Argument array
1573  * Return:      CMD_RET_SUCCESS on success,
1574  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1575  *
1576  * Implement efidebug "test bootmgr" sub-command.
1577  * Run simple bootmgr for test.
1578  *
1579  *     efidebug test bootmgr
1580  */
1581 static __maybe_unused int do_efi_test_bootmgr(struct cmd_tbl *cmdtp, int flag,
1582                                               int argc, char * const argv[])
1583 {
1584         efi_handle_t image;
1585         efi_uintn_t exit_data_size = 0;
1586         u16 *exit_data = NULL;
1587         efi_status_t ret;
1588         void *load_options = NULL;
1589
1590         ret = efi_bootmgr_load(&image, &load_options);
1591         printf("efi_bootmgr_load() returned: %ld\n", ret & ~EFI_ERROR_MASK);
1592
1593         /* We call efi_start_image() even if error for test purpose. */
1594         ret = EFI_CALL(efi_start_image(image, &exit_data_size, &exit_data));
1595         printf("efi_start_image() returned: %ld\n", ret & ~EFI_ERROR_MASK);
1596         if (ret && exit_data)
1597                 efi_free_pool(exit_data);
1598
1599         efi_restore_gd();
1600
1601         free(load_options);
1602         return CMD_RET_SUCCESS;
1603 }
1604
1605 static struct cmd_tbl cmd_efidebug_test_sub[] = {
1606 #ifdef CONFIG_CMD_BOOTEFI_BOOTMGR
1607         U_BOOT_CMD_MKENT(bootmgr, CONFIG_SYS_MAXARGS, 1, do_efi_test_bootmgr,
1608                          "", ""),
1609 #endif
1610 };
1611
1612 /**
1613  * do_efi_test() - manage UEFI load options
1614  *
1615  * @cmdtp:      Command table
1616  * @flag:       Command flag
1617  * @argc:       Number of arguments
1618  * @argv:       Argument array
1619  * Return:      CMD_RET_SUCCESS on success,
1620  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1621  *
1622  * Implement efidebug "test" sub-command.
1623  */
1624 static int do_efi_test(struct cmd_tbl *cmdtp, int flag,
1625                        int argc, char * const argv[])
1626 {
1627         struct cmd_tbl *cp;
1628
1629         if (argc < 2)
1630                 return CMD_RET_USAGE;
1631
1632         argc--; argv++;
1633
1634         cp = find_cmd_tbl(argv[0], cmd_efidebug_test_sub,
1635                           ARRAY_SIZE(cmd_efidebug_test_sub));
1636         if (!cp)
1637                 return CMD_RET_USAGE;
1638
1639         return cp->cmd(cmdtp, flag, argc, argv);
1640 }
1641
1642 /**
1643  * do_efi_query_info() - QueryVariableInfo EFI service
1644  *
1645  * @cmdtp:      Command table
1646  * @flag:       Command flag
1647  * @argc:       Number of arguments
1648  * @argv:       Argument array
1649  * Return:      CMD_RET_SUCCESS on success,
1650  *              CMD_RET_USAGE or CMD_RET_FAILURE on failure
1651  *
1652  * Implement efidebug "test" sub-command.
1653  */
1654
1655 static int do_efi_query_info(struct cmd_tbl *cmdtp, int flag,
1656                              int argc, char * const argv[])
1657 {
1658         efi_status_t ret;
1659         u32 attr = 0;
1660         u64 max_variable_storage_size;
1661         u64 remain_variable_storage_size;
1662         u64 max_variable_size;
1663         int i;
1664
1665         for (i = 1; i < argc; i++) {
1666                 if (!strcmp(argv[i], "-bs"))
1667                         attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS;
1668                 else if (!strcmp(argv[i], "-rt"))
1669                         attr |= EFI_VARIABLE_RUNTIME_ACCESS;
1670                 else if (!strcmp(argv[i], "-nv"))
1671                         attr |= EFI_VARIABLE_NON_VOLATILE;
1672                 else if (!strcmp(argv[i], "-at"))
1673                         attr |=
1674                                 EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
1675         }
1676
1677         ret = EFI_CALL(efi_query_variable_info(attr,
1678                                                &max_variable_storage_size,
1679                                                &remain_variable_storage_size,
1680                                                &max_variable_size));
1681         if (ret != EFI_SUCCESS) {
1682                 printf("Error: Cannot query UEFI variables, r = %lu\n",
1683                        ret & ~EFI_ERROR_MASK);
1684                 return CMD_RET_FAILURE;
1685         }
1686
1687         printf("Max storage size %llu\n", max_variable_storage_size);
1688         printf("Remaining storage size %llu\n", remain_variable_storage_size);
1689         printf("Max variable size %llu\n", max_variable_size);
1690
1691         return CMD_RET_SUCCESS;
1692 }
1693
1694 static struct cmd_tbl cmd_efidebug_sub[] = {
1695         U_BOOT_CMD_MKENT(boot, CONFIG_SYS_MAXARGS, 1, do_efi_boot_opt, "", ""),
1696 #ifdef CONFIG_EFI_HAVE_CAPSULE_SUPPORT
1697         U_BOOT_CMD_MKENT(capsule, CONFIG_SYS_MAXARGS, 1, do_efi_capsule,
1698                          "", ""),
1699 #endif
1700         U_BOOT_CMD_MKENT(devices, CONFIG_SYS_MAXARGS, 1, do_efi_show_devices,
1701                          "", ""),
1702         U_BOOT_CMD_MKENT(drivers, CONFIG_SYS_MAXARGS, 1, do_efi_show_drivers,
1703                          "", ""),
1704         U_BOOT_CMD_MKENT(dh, CONFIG_SYS_MAXARGS, 1, do_efi_show_handles,
1705                          "", ""),
1706         U_BOOT_CMD_MKENT(images, CONFIG_SYS_MAXARGS, 1, do_efi_show_images,
1707                          "", ""),
1708         U_BOOT_CMD_MKENT(memmap, CONFIG_SYS_MAXARGS, 1, do_efi_show_memmap,
1709                          "", ""),
1710         U_BOOT_CMD_MKENT(tables, CONFIG_SYS_MAXARGS, 1, do_efi_show_tables,
1711                          "", ""),
1712         U_BOOT_CMD_MKENT(test, CONFIG_SYS_MAXARGS, 1, do_efi_test,
1713                          "", ""),
1714         U_BOOT_CMD_MKENT(query, CONFIG_SYS_MAXARGS, 1, do_efi_query_info,
1715                          "", ""),
1716 };
1717
1718 /**
1719  * do_efidebug() - display and configure UEFI environment
1720  *
1721  * @cmdtp:      Command table
1722  * @flag:       Command flag
1723  * @argc:       Number of arguments
1724  * @argv:       Argument array
1725  * Return:      CMD_RET_SUCCESS on success,
1726  *              CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
1727  *
1728  * Implement efidebug command which allows us to display and
1729  * configure UEFI environment.
1730  */
1731 static int do_efidebug(struct cmd_tbl *cmdtp, int flag,
1732                        int argc, char *const argv[])
1733 {
1734         struct cmd_tbl *cp;
1735         efi_status_t r;
1736
1737         if (argc < 2)
1738                 return CMD_RET_USAGE;
1739
1740         argc--; argv++;
1741
1742         /* Initialize UEFI drivers */
1743         r = efi_init_obj_list();
1744         if (r != EFI_SUCCESS) {
1745                 printf("Error: Cannot initialize UEFI sub-system, r = %lu\n",
1746                        r & ~EFI_ERROR_MASK);
1747                 return CMD_RET_FAILURE;
1748         }
1749
1750         cp = find_cmd_tbl(argv[0], cmd_efidebug_sub,
1751                           ARRAY_SIZE(cmd_efidebug_sub));
1752         if (!cp)
1753                 return CMD_RET_USAGE;
1754
1755         return cp->cmd(cmdtp, flag, argc, argv);
1756 }
1757
1758 #ifdef CONFIG_SYS_LONGHELP
1759 static char efidebug_help_text[] =
1760         "  - UEFI Shell-like interface to configure UEFI environment\n"
1761         "\n"
1762         "efidebug boot add "
1763         "-b <bootid> <label> <interface> <devnum>[:<part>] <file path> "
1764         "-i <interface> <devnum>[:<part>] <initrd file path> "
1765         "-s '<optional data>'\n"
1766         "  - set UEFI BootXXXX variable\n"
1767         "    <load options> will be passed to UEFI application\n"
1768         "efidebug boot rm <bootid#1> [<bootid#2> [<bootid#3> [...]]]\n"
1769         "  - delete UEFI BootXXXX variables\n"
1770         "efidebug boot dump\n"
1771         "  - dump all UEFI BootXXXX variables\n"
1772         "efidebug boot next <bootid>\n"
1773         "  - set UEFI BootNext variable\n"
1774         "efidebug boot order [<bootid#1> [<bootid#2> [<bootid#3> [...]]]]\n"
1775         "  - set/show UEFI boot order\n"
1776         "\n"
1777 #ifdef CONFIG_EFI_HAVE_CAPSULE_SUPPORT
1778         "efidebug capsule update [-v] <capsule address>\n"
1779         "  - process a capsule\n"
1780         "efidebug capsule disk-update\n"
1781         "  - update a capsule from disk\n"
1782         "efidebug capsule show <capsule address>\n"
1783         "  - show capsule information\n"
1784         "efidebug capsule result [<capsule result var>]\n"
1785         "  - show a capsule update result\n"
1786 #ifdef CONFIG_EFI_ESRT
1787         "efidebug capsule esrt\n"
1788         "  - print the ESRT\n"
1789 #endif
1790         "\n"
1791 #endif
1792         "efidebug devices\n"
1793         "  - show UEFI devices\n"
1794         "efidebug drivers\n"
1795         "  - show UEFI drivers\n"
1796         "efidebug dh\n"
1797         "  - show UEFI handles\n"
1798         "efidebug images\n"
1799         "  - show loaded images\n"
1800         "efidebug memmap\n"
1801         "  - show UEFI memory map\n"
1802         "efidebug tables\n"
1803         "  - show UEFI configuration tables\n"
1804 #ifdef CONFIG_CMD_BOOTEFI_BOOTMGR
1805         "efidebug test bootmgr\n"
1806         "  - run simple bootmgr for test\n"
1807 #endif
1808         "efidebug query [-nv][-bs][-rt][-at]\n"
1809         "  - show size of UEFI variables store\n";
1810 #endif
1811
1812 U_BOOT_CMD(
1813         efidebug, CONFIG_SYS_MAXARGS, 0, do_efidebug,
1814         "Configure UEFI environment",
1815         efidebug_help_text
1816 );