]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - stand/efi/loader/main.c
MFV r331400: 8484 Implement aggregate sum and use for arc counters
[FreeBSD/FreeBSD.git] / stand / efi / loader / main.c
1 /*-
2  * Copyright (c) 2008-2010 Rui Paulo
3  * Copyright (c) 2006 Marcel Moolenaar
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
31 #include <sys/disk.h>
32 #include <sys/param.h>
33 #include <sys/reboot.h>
34 #include <sys/boot.h>
35 #include <stdint.h>
36 #include <stand.h>
37 #include <string.h>
38 #include <setjmp.h>
39 #include <disk.h>
40
41 #include <efi.h>
42 #include <efilib.h>
43
44 #include <uuid.h>
45
46 #include <bootstrap.h>
47 #include <smbios.h>
48
49 #ifdef EFI_ZFS_BOOT
50 #include <libzfs.h>
51
52 #include "efizfs.h"
53 #endif
54
55 #include "loader_efi.h"
56
57 extern char bootprog_info[];
58
59 struct arch_switch archsw;      /* MI/MD interface boundary */
60
61 EFI_GUID acpi = ACPI_TABLE_GUID;
62 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
63 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
64 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
65 EFI_GUID mps = MPS_TABLE_GUID;
66 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
67 EFI_GUID smbios = SMBIOS_TABLE_GUID;
68 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
69 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
70 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
71 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
72 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
73 EFI_GUID esrt = ESRT_TABLE_GUID;
74 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
75 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
76 EFI_GUID fdtdtb = FDT_TABLE_GUID;
77 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
78
79 static EFI_LOADED_IMAGE *img;
80
81 #ifdef  EFI_ZFS_BOOT
82 bool
83 efi_zfs_is_preferred(EFI_HANDLE *h)
84 {
85         return (h == img->DeviceHandle);
86 }
87 #endif
88
89 static int
90 has_keyboard(void)
91 {
92         EFI_STATUS status;
93         EFI_DEVICE_PATH *path;
94         EFI_HANDLE *hin, *hin_end, *walker;
95         UINTN sz;
96         int retval = 0;
97
98         /*
99          * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
100          * do the typical dance to get the right sized buffer.
101          */
102         sz = 0;
103         hin = NULL;
104         status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
105         if (status == EFI_BUFFER_TOO_SMALL) {
106                 hin = (EFI_HANDLE *)malloc(sz);
107                 status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
108                     hin);
109                 if (EFI_ERROR(status))
110                         free(hin);
111         }
112         if (EFI_ERROR(status))
113                 return retval;
114
115         /*
116          * Look at each of the handles. If it supports the device path protocol,
117          * use it to get the device path for this handle. Then see if that
118          * device path matches either the USB device path for keyboards or the
119          * legacy device path for keyboards.
120          */
121         hin_end = &hin[sz / sizeof(*hin)];
122         for (walker = hin; walker < hin_end; walker++) {
123                 status = BS->HandleProtocol(*walker, &devid, (VOID **)&path);
124                 if (EFI_ERROR(status))
125                         continue;
126
127                 while (!IsDevicePathEnd(path)) {
128                         /*
129                          * Check for the ACPI keyboard node. All PNP3xx nodes
130                          * are keyboards of different flavors. Note: It is
131                          * unclear of there's always a keyboard node when
132                          * there's a keyboard controller, or if there's only one
133                          * when a keyboard is detected at boot.
134                          */
135                         if (DevicePathType(path) == ACPI_DEVICE_PATH &&
136                             (DevicePathSubType(path) == ACPI_DP ||
137                                 DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
138                                 ACPI_HID_DEVICE_PATH  *acpi;
139
140                                 acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
141                                 if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
142                                     (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
143                                         retval = 1;
144                                         goto out;
145                                 }
146                         /*
147                          * Check for USB keyboard node, if present. Unlike a
148                          * PS/2 keyboard, these definitely only appear when
149                          * connected to the system.
150                          */
151                         } else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
152                             DevicePathSubType(path) == MSG_USB_CLASS_DP) {
153                                 USB_CLASS_DEVICE_PATH *usb;
154
155                                 usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
156                                 if (usb->DeviceClass == 3 && /* HID */
157                                     usb->DeviceSubClass == 1 && /* Boot devices */
158                                     usb->DeviceProtocol == 1) { /* Boot keyboards */
159                                         retval = 1;
160                                         goto out;
161                                 }
162                         }
163                         path = NextDevicePathNode(path);
164                 }
165         }
166 out:
167         free(hin);
168         return retval;
169 }
170
171 static void
172 set_devdesc_currdev(struct devsw *dev, int unit)
173 {
174         struct devdesc currdev;
175         char *devname;
176
177         currdev.d_dev = dev;
178         currdev.d_unit = unit;
179         devname = efi_fmtdev(&currdev);
180
181         env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev,
182             env_nounset);
183         env_setenv("loaddev", EV_VOLATILE, devname, env_noset, env_nounset);
184 }
185
186 static int
187 find_currdev(EFI_LOADED_IMAGE *img)
188 {
189         pdinfo_list_t *pdi_list;
190         pdinfo_t *dp, *pp;
191         EFI_DEVICE_PATH *devpath, *copy;
192         EFI_HANDLE h;
193         char *devname;
194         struct devsw *dev;
195         int unit;
196         uint64_t extra;
197
198 #ifdef EFI_ZFS_BOOT
199         /* Did efi_zfs_probe() detect the boot pool? */
200         if (pool_guid != 0) {
201                 struct zfs_devdesc currdev;
202
203                 currdev.dd.d_dev = &zfs_dev;
204                 currdev.dd.d_unit = 0;
205                 currdev.pool_guid = pool_guid;
206                 currdev.root_guid = 0;
207                 devname = efi_fmtdev(&currdev);
208
209                 env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev,
210                     env_nounset);
211                 env_setenv("loaddev", EV_VOLATILE, devname, env_noset,
212                     env_nounset);
213                 init_zfs_bootenv(devname);
214                 return (0);
215         }
216 #endif /* EFI_ZFS_BOOT */
217
218         /* We have device lists for hd, cd, fd, walk them all. */
219         pdi_list = efiblk_get_pdinfo_list(&efipart_hddev);
220         STAILQ_FOREACH(dp, pdi_list, pd_link) {
221                 struct disk_devdesc currdev;
222
223                 currdev.dd.d_dev = &efipart_hddev;
224                 currdev.dd.d_unit = dp->pd_unit;
225                 currdev.d_slice = -1;
226                 currdev.d_partition = -1;
227
228                 if (dp->pd_handle == img->DeviceHandle) {
229                         devname = efi_fmtdev(&currdev);
230
231                         env_setenv("currdev", EV_VOLATILE, devname,
232                             efi_setcurrdev, env_nounset);
233                         env_setenv("loaddev", EV_VOLATILE, devname,
234                             env_noset, env_nounset);
235                         return (0);
236                 }
237                 /* Assuming GPT partitioning. */
238                 STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
239                         if (pp->pd_handle == img->DeviceHandle) {
240                                 currdev.d_slice = pp->pd_unit;
241                                 currdev.d_partition = 255;
242                                 devname = efi_fmtdev(&currdev);
243
244                                 env_setenv("currdev", EV_VOLATILE, devname,
245                                     efi_setcurrdev, env_nounset);
246                                 env_setenv("loaddev", EV_VOLATILE, devname,
247                                     env_noset, env_nounset);
248                                 return (0);
249                         }
250                 }
251         }
252
253         pdi_list = efiblk_get_pdinfo_list(&efipart_cddev);
254         STAILQ_FOREACH(dp, pdi_list, pd_link) {
255                 if (dp->pd_handle == img->DeviceHandle ||
256                     dp->pd_alias == img->DeviceHandle) {
257                         set_devdesc_currdev(&efipart_cddev, dp->pd_unit);
258                         return (0);
259                 }
260         }
261
262         pdi_list = efiblk_get_pdinfo_list(&efipart_fddev);
263         STAILQ_FOREACH(dp, pdi_list, pd_link) {
264                 if (dp->pd_handle == img->DeviceHandle) {
265                         set_devdesc_currdev(&efipart_fddev, dp->pd_unit);
266                         return (0);
267                 }
268         }
269
270         /*
271          * Try the device handle from our loaded image first.  If that
272          * fails, use the device path from the loaded image and see if
273          * any of the nodes in that path match one of the enumerated
274          * handles.
275          */
276         if (efi_handle_lookup(img->DeviceHandle, &dev, &unit, &extra) == 0) {
277                 set_devdesc_currdev(dev, unit);
278                 return (0);
279         }
280
281         copy = NULL;
282         devpath = efi_lookup_image_devpath(IH);
283         while (devpath != NULL) {
284                 h = efi_devpath_handle(devpath);
285                 if (h == NULL)
286                         break;
287
288                 free(copy);
289                 copy = NULL;
290
291                 if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
292                         set_devdesc_currdev(dev, unit);
293                         return (0);
294                 }
295
296                 devpath = efi_lookup_devpath(h);
297                 if (devpath != NULL) {
298                         copy = efi_devpath_trim(devpath);
299                         devpath = copy;
300                 }
301         }
302         free(copy);
303
304         return (ENOENT);
305 }
306
307 EFI_STATUS
308 main(int argc, CHAR16 *argv[])
309 {
310         char var[128];
311         EFI_GUID *guid;
312         int i, j, vargood, howto;
313         UINTN k;
314         int has_kbd;
315         CHAR16 *text;
316         UINT16 boot_current;
317         size_t sz;
318         UINT16 boot_order[100];
319         EFI_DEVICE_PATH *imgpath;
320         EFI_STATUS status;
321 #if !defined(__arm__)
322         char buf[40];
323 #endif
324
325         archsw.arch_autoload = efi_autoload;
326         archsw.arch_getdev = efi_getdev;
327         archsw.arch_copyin = efi_copyin;
328         archsw.arch_copyout = efi_copyout;
329         archsw.arch_readin = efi_readin;
330 #ifdef EFI_ZFS_BOOT
331         /* Note this needs to be set before ZFS init. */
332         archsw.arch_zfs_probe = efi_zfs_probe;
333 #endif
334
335         /* Get our loaded image protocol interface structure. */
336         BS->HandleProtocol(IH, &imgid, (VOID**)&img);
337
338         /* Init the time source */
339         efi_time_init();
340
341         has_kbd = has_keyboard();
342
343         /*
344          * XXX Chicken-and-egg problem; we want to have console output
345          * early, but some console attributes may depend on reading from
346          * eg. the boot device, which we can't do yet.  We can use
347          * printf() etc. once this is done.
348          */
349         cons_probe();
350
351         /*
352          * Initialise the block cache. Set the upper limit.
353          */
354         bcache_init(32768, 512);
355
356         /*
357          * Parse the args to set the console settings, etc
358          * boot1.efi passes these in, if it can read /boot.config or /boot/config
359          * or iPXE may be setup to pass these in.
360          *
361          * Loop through the args, and for each one that contains an '=' that is
362          * not the first character, add it to the environment.  This allows
363          * loader and kernel env vars to be passed on the command line.  Convert
364          * args from UCS-2 to ASCII (16 to 8 bit) as they are copied.
365          */
366         howto = 0;
367         for (i = 1; i < argc; i++) {
368                 if (argv[i][0] == '-') {
369                         for (j = 1; argv[i][j] != 0; j++) {
370                                 int ch;
371
372                                 ch = argv[i][j];
373                                 switch (ch) {
374                                 case 'a':
375                                         howto |= RB_ASKNAME;
376                                         break;
377                                 case 'd':
378                                         howto |= RB_KDB;
379                                         break;
380                                 case 'D':
381                                         howto |= RB_MULTIPLE;
382                                         break;
383                                 case 'h':
384                                         howto |= RB_SERIAL;
385                                         break;
386                                 case 'm':
387                                         howto |= RB_MUTE;
388                                         break;
389                                 case 'p':
390                                         howto |= RB_PAUSE;
391                                         break;
392                                 case 'P':
393                                         if (!has_kbd)
394                                                 howto |= RB_SERIAL | RB_MULTIPLE;
395                                         break;
396                                 case 'r':
397                                         howto |= RB_DFLTROOT;
398                                         break;
399                                 case 's':
400                                         howto |= RB_SINGLE;
401                                         break;
402                                 case 'S':
403                                         if (argv[i][j + 1] == 0) {
404                                                 if (i + 1 == argc) {
405                                                         setenv("comconsole_speed", "115200", 1);
406                                                 } else {
407                                                         cpy16to8(&argv[i + 1][0], var,
408                                                             sizeof(var));
409                                                         setenv("comconsole_speed", var, 1);
410                                                 }
411                                                 i++;
412                                                 break;
413                                         } else {
414                                                 cpy16to8(&argv[i][j + 1], var,
415                                                     sizeof(var));
416                                                 setenv("comconsole_speed", var, 1);
417                                                 break;
418                                         }
419                                 case 'v':
420                                         howto |= RB_VERBOSE;
421                                         break;
422                                 }
423                         }
424                 } else {
425                         vargood = 0;
426                         for (j = 0; argv[i][j] != 0; j++) {
427                                 if (j == sizeof(var)) {
428                                         vargood = 0;
429                                         break;
430                                 }
431                                 if (j > 0 && argv[i][j] == '=')
432                                         vargood = 1;
433                                 var[j] = (char)argv[i][j];
434                         }
435                         if (vargood) {
436                                 var[j] = 0;
437                                 putenv(var);
438                         }
439                 }
440         }
441         for (i = 0; howto_names[i].ev != NULL; i++)
442                 if (howto & howto_names[i].mask)
443                         setenv(howto_names[i].ev, "YES", 1);
444         if (howto & RB_MULTIPLE) {
445                 if (howto & RB_SERIAL)
446                         setenv("console", "comconsole efi" , 1);
447                 else
448                         setenv("console", "efi comconsole" , 1);
449         } else if (howto & RB_SERIAL) {
450                 setenv("console", "comconsole" , 1);
451         }
452
453         if (efi_copy_init()) {
454                 printf("failed to allocate staging area\n");
455                 return (EFI_BUFFER_TOO_SMALL);
456         }
457
458         /*
459          * Scan the BLOCK IO MEDIA handles then
460          * march through the device switch probing for things.
461          */
462         if ((i = efipart_inithandles()) == 0) {
463                 for (i = 0; devsw[i] != NULL; i++)
464                         if (devsw[i]->dv_init != NULL)
465                                 (devsw[i]->dv_init)();
466         } else
467                 printf("efipart_inithandles failed %d, expect failures", i);
468
469         printf("Command line arguments:");
470         for (i = 0; i < argc; i++)
471                 printf(" %S", argv[i]);
472         printf("\n");
473
474         printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
475         printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
476             ST->Hdr.Revision & 0xffff);
477         printf("EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
478             ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
479
480         printf("\n%s", bootprog_info);
481
482         text = efi_devpath_name(img->FilePath);
483         if (text != NULL) {
484                 printf("   Load Path: %S\n", text);
485                 efi_setenv_freebsd_wcs("LoaderPath", text);
486                 efi_free_devpath_name(text);
487         }
488
489         status = BS->HandleProtocol(img->DeviceHandle, &devid, (void **)&imgpath);
490         if (status == EFI_SUCCESS) {
491                 text = efi_devpath_name(imgpath);
492                 if (text != NULL) {
493                         printf("   Load Device: %S\n", text);
494                         efi_setenv_freebsd_wcs("LoaderDev", text);
495                         efi_free_devpath_name(text);
496                 }
497         }
498
499         boot_current = 0;
500         sz = sizeof(boot_current);
501         efi_global_getenv("BootCurrent", &boot_current, &sz);
502         printf("   BootCurrent: %04x\n", boot_current);
503
504         sz = sizeof(boot_order);
505         efi_global_getenv("BootOrder", &boot_order, &sz);
506         printf("   BootOrder:");
507         for (i = 0; i < sz / sizeof(boot_order[0]); i++)
508                 printf(" %04x%s", boot_order[i],
509                     boot_order[i] == boot_current ? "[*]" : "");
510         printf("\n");
511
512         /*
513          * Disable the watchdog timer. By default the boot manager sets
514          * the timer to 5 minutes before invoking a boot option. If we
515          * want to return to the boot manager, we have to disable the
516          * watchdog timer and since we're an interactive program, we don't
517          * want to wait until the user types "quit". The timer may have
518          * fired by then. We don't care if this fails. It does not prevent
519          * normal functioning in any way...
520          */
521         BS->SetWatchdogTimer(0, 0, 0, NULL);
522
523         if (find_currdev(img) != 0)
524                 return (EFI_NOT_FOUND);
525
526         efi_init_environment();
527         setenv("LINES", "24", 1);       /* optional */
528
529         for (k = 0; k < ST->NumberOfTableEntries; k++) {
530                 guid = &ST->ConfigurationTable[k].VendorGuid;
531 #if !defined(__arm__)
532                 if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
533                         snprintf(buf, sizeof(buf), "%p",
534                             ST->ConfigurationTable[k].VendorTable);
535                         setenv("hint.smbios.0.mem", buf, 1);
536                         smbios_detect(ST->ConfigurationTable[k].VendorTable);
537                         break;
538                 }
539 #endif
540         }
541
542         interact();                     /* doesn't return */
543
544         return (EFI_SUCCESS);           /* keep compiler happy */
545 }
546
547 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
548
549 static int
550 command_reboot(int argc, char *argv[])
551 {
552         int i;
553
554         for (i = 0; devsw[i] != NULL; ++i)
555                 if (devsw[i]->dv_cleanup != NULL)
556                         (devsw[i]->dv_cleanup)();
557
558         RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
559
560         /* NOTREACHED */
561         return (CMD_ERROR);
562 }
563
564 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
565
566 static int
567 command_quit(int argc, char *argv[])
568 {
569         exit(0);
570         return (CMD_OK);
571 }
572
573 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
574
575 static int
576 command_memmap(int argc, char *argv[])
577 {
578         UINTN sz;
579         EFI_MEMORY_DESCRIPTOR *map, *p;
580         UINTN key, dsz;
581         UINT32 dver;
582         EFI_STATUS status;
583         int i, ndesc;
584         char line[80];
585         static char *types[] = {
586             "Reserved",
587             "LoaderCode",
588             "LoaderData",
589             "BootServicesCode",
590             "BootServicesData",
591             "RuntimeServicesCode",
592             "RuntimeServicesData",
593             "ConventionalMemory",
594             "UnusableMemory",
595             "ACPIReclaimMemory",
596             "ACPIMemoryNVS",
597             "MemoryMappedIO",
598             "MemoryMappedIOPortSpace",
599             "PalCode"
600         };
601
602         sz = 0;
603         status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
604         if (status != EFI_BUFFER_TOO_SMALL) {
605                 printf("Can't determine memory map size\n");
606                 return (CMD_ERROR);
607         }
608         map = malloc(sz);
609         status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
610         if (EFI_ERROR(status)) {
611                 printf("Can't read memory map\n");
612                 return (CMD_ERROR);
613         }
614
615         ndesc = sz / dsz;
616         snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
617             "Type", "Physical", "Virtual", "#Pages", "Attr");
618         pager_open();
619         if (pager_output(line)) {
620                 pager_close();
621                 return (CMD_OK);
622         }
623
624         for (i = 0, p = map; i < ndesc;
625              i++, p = NextMemoryDescriptor(p, dsz)) {
626                 printf("%23s %012jx %012jx %08jx ", types[p->Type],
627                     (uintmax_t)p->PhysicalStart, (uintmax_t)p->VirtualStart,
628                     (uintmax_t)p->NumberOfPages);
629                 if (p->Attribute & EFI_MEMORY_UC)
630                         printf("UC ");
631                 if (p->Attribute & EFI_MEMORY_WC)
632                         printf("WC ");
633                 if (p->Attribute & EFI_MEMORY_WT)
634                         printf("WT ");
635                 if (p->Attribute & EFI_MEMORY_WB)
636                         printf("WB ");
637                 if (p->Attribute & EFI_MEMORY_UCE)
638                         printf("UCE ");
639                 if (p->Attribute & EFI_MEMORY_WP)
640                         printf("WP ");
641                 if (p->Attribute & EFI_MEMORY_RP)
642                         printf("RP ");
643                 if (p->Attribute & EFI_MEMORY_XP)
644                         printf("XP ");
645                 if (pager_output("\n"))
646                         break;
647         }
648
649         pager_close();
650         return (CMD_OK);
651 }
652
653 COMMAND_SET(configuration, "configuration", "print configuration tables",
654     command_configuration);
655
656 static const char *
657 guid_to_string(EFI_GUID *guid)
658 {
659         static char buf[40];
660
661         sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
662             guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
663             guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
664             guid->Data4[5], guid->Data4[6], guid->Data4[7]);
665         return (buf);
666 }
667
668 static int
669 command_configuration(int argc, char *argv[])
670 {
671         char line[80];
672         UINTN i;
673
674         snprintf(line, sizeof(line), "NumberOfTableEntries=%lu\n",
675                 (unsigned long)ST->NumberOfTableEntries);
676         pager_open();
677         if (pager_output(line)) {
678                 pager_close();
679                 return (CMD_OK);
680         }
681
682         for (i = 0; i < ST->NumberOfTableEntries; i++) {
683                 EFI_GUID *guid;
684
685                 printf("  ");
686                 guid = &ST->ConfigurationTable[i].VendorGuid;
687                 if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
688                         printf("MPS Table");
689                 else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
690                         printf("ACPI Table");
691                 else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
692                         printf("ACPI 2.0 Table");
693                 else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
694                         printf("SMBIOS Table %p",
695                             ST->ConfigurationTable[i].VendorTable);
696                 else if (!memcmp(guid, &smbios3, sizeof(EFI_GUID)))
697                         printf("SMBIOS3 Table");
698                 else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
699                         printf("DXE Table");
700                 else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
701                         printf("HOB List Table");
702                 else if (!memcmp(guid, &lzmadecomp, sizeof(EFI_GUID)))
703                         printf("LZMA Compression");
704                 else if (!memcmp(guid, &mpcore, sizeof(EFI_GUID)))
705                         printf("ARM MpCore Information Table");
706                 else if (!memcmp(guid, &esrt, sizeof(EFI_GUID)))
707                         printf("ESRT Table");
708                 else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
709                         printf("Memory Type Information Table");
710                 else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
711                         printf("Debug Image Info Table");
712                 else if (!memcmp(guid, &fdtdtb, sizeof(EFI_GUID)))
713                         printf("FDT Table");
714                 else
715                         printf("Unknown Table (%s)", guid_to_string(guid));
716                 snprintf(line, sizeof(line), " at %p\n",
717                     ST->ConfigurationTable[i].VendorTable);
718                 if (pager_output(line))
719                         break;
720         }
721
722         pager_close();
723         return (CMD_OK);
724 }
725
726
727 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
728
729 static int
730 command_mode(int argc, char *argv[])
731 {
732         UINTN cols, rows;
733         unsigned int mode;
734         int i;
735         char *cp;
736         char rowenv[8];
737         EFI_STATUS status;
738         SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
739         extern void HO(void);
740
741         conout = ST->ConOut;
742
743         if (argc > 1) {
744                 mode = strtol(argv[1], &cp, 0);
745                 if (cp[0] != '\0') {
746                         printf("Invalid mode\n");
747                         return (CMD_ERROR);
748                 }
749                 status = conout->QueryMode(conout, mode, &cols, &rows);
750                 if (EFI_ERROR(status)) {
751                         printf("invalid mode %d\n", mode);
752                         return (CMD_ERROR);
753                 }
754                 status = conout->SetMode(conout, mode);
755                 if (EFI_ERROR(status)) {
756                         printf("couldn't set mode %d\n", mode);
757                         return (CMD_ERROR);
758                 }
759                 sprintf(rowenv, "%u", (unsigned)rows);
760                 setenv("LINES", rowenv, 1);
761                 HO();           /* set cursor */
762                 return (CMD_OK);
763         }
764
765         printf("Current mode: %d\n", conout->Mode->Mode);
766         for (i = 0; i <= conout->Mode->MaxMode; i++) {
767                 status = conout->QueryMode(conout, i, &cols, &rows);
768                 if (EFI_ERROR(status))
769                         continue;
770                 printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
771                     (unsigned)rows);
772         }
773
774         if (i != 0)
775                 printf("Select a mode with the command \"mode <number>\"\n");
776
777         return (CMD_OK);
778 }
779
780 #ifdef LOADER_FDT_SUPPORT
781 extern int command_fdt_internal(int argc, char *argv[]);
782
783 /*
784  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
785  * and declaring it as extern is in contradiction with COMMAND_SET() macro
786  * (which uses static pointer), we're defining wrapper function, which
787  * calls the proper fdt handling routine.
788  */
789 static int
790 command_fdt(int argc, char *argv[])
791 {
792
793         return (command_fdt_internal(argc, argv));
794 }
795
796 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
797 #endif
798
799 /*
800  * Chain load another efi loader.
801  */
802 static int
803 command_chain(int argc, char *argv[])
804 {
805         EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
806         EFI_HANDLE loaderhandle;
807         EFI_LOADED_IMAGE *loaded_image;
808         EFI_STATUS status;
809         struct stat st;
810         struct devdesc *dev;
811         char *name, *path;
812         void *buf;
813         int fd;
814
815         if (argc < 2) {
816                 command_errmsg = "wrong number of arguments";
817                 return (CMD_ERROR);
818         }
819
820         name = argv[1];
821
822         if ((fd = open(name, O_RDONLY)) < 0) {
823                 command_errmsg = "no such file";
824                 return (CMD_ERROR);
825         }
826
827         if (fstat(fd, &st) < -1) {
828                 command_errmsg = "stat failed";
829                 close(fd);
830                 return (CMD_ERROR);
831         }
832
833         status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
834         if (status != EFI_SUCCESS) {
835                 command_errmsg = "failed to allocate buffer";
836                 close(fd);
837                 return (CMD_ERROR);
838         }
839         if (read(fd, buf, st.st_size) != st.st_size) {
840                 command_errmsg = "error while reading the file";
841                 (void)BS->FreePool(buf);
842                 close(fd);
843                 return (CMD_ERROR);
844         }
845         close(fd);
846         status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
847         (void)BS->FreePool(buf);
848         if (status != EFI_SUCCESS) {
849                 command_errmsg = "LoadImage failed";
850                 return (CMD_ERROR);
851         }
852         status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
853             (void **)&loaded_image);
854
855         if (argc > 2) {
856                 int i, len = 0;
857                 CHAR16 *argp;
858
859                 for (i = 2; i < argc; i++)
860                         len += strlen(argv[i]) + 1;
861
862                 len *= sizeof (*argp);
863                 loaded_image->LoadOptions = argp = malloc (len);
864                 loaded_image->LoadOptionsSize = len;
865                 for (i = 2; i < argc; i++) {
866                         char *ptr = argv[i];
867                         while (*ptr)
868                                 *(argp++) = *(ptr++);
869                         *(argp++) = ' ';
870                 }
871                 *(--argv) = 0;
872         }
873
874         if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
875 #ifdef EFI_ZFS_BOOT
876                 struct zfs_devdesc *z_dev;
877 #endif
878                 struct disk_devdesc *d_dev;
879                 pdinfo_t *hd, *pd;
880
881                 switch (dev->d_dev->dv_type) {
882 #ifdef EFI_ZFS_BOOT
883                 case DEVT_ZFS:
884                         z_dev = (struct zfs_devdesc *)dev;
885                         loaded_image->DeviceHandle =
886                             efizfs_get_handle_by_guid(z_dev->pool_guid);
887                         break;
888 #endif
889                 case DEVT_NET:
890                         loaded_image->DeviceHandle =
891                             efi_find_handle(dev->d_dev, dev->d_unit);
892                         break;
893                 default:
894                         hd = efiblk_get_pdinfo(dev);
895                         if (STAILQ_EMPTY(&hd->pd_part)) {
896                                 loaded_image->DeviceHandle = hd->pd_handle;
897                                 break;
898                         }
899                         d_dev = (struct disk_devdesc *)dev;
900                         STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
901                                 /*
902                                  * d_partition should be 255
903                                  */
904                                 if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
905                                         loaded_image->DeviceHandle =
906                                             pd->pd_handle;
907                                         break;
908                                 }
909                         }
910                         break;
911                 }
912         }
913
914         dev_cleanup();
915         status = BS->StartImage(loaderhandle, NULL, NULL);
916         if (status != EFI_SUCCESS) {
917                 command_errmsg = "StartImage failed";
918                 free(loaded_image->LoadOptions);
919                 loaded_image->LoadOptions = NULL;
920                 status = BS->UnloadImage(loaded_image);
921                 return (CMD_ERROR);
922         }
923
924         return (CMD_ERROR);     /* not reached */
925 }
926
927 COMMAND_SET(chain, "chain", "chain load file", command_chain);