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