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